hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
05935593d048f7d0754c602fb109377f105918ef
| 15,014
|
cpp
|
C++
|
Tempest/2d/font.cpp
|
enotio/Tempest
|
1a7105cfca3669d54c696ad8188f04f25159c0a0
|
[
"MIT"
] | 5
|
2017-05-31T21:25:57.000Z
|
2020-01-14T14:11:41.000Z
|
Tempest/2d/font.cpp
|
enotio/Tempest
|
1a7105cfca3669d54c696ad8188f04f25159c0a0
|
[
"MIT"
] | 2
|
2017-11-13T14:32:21.000Z
|
2018-10-03T17:07:36.000Z
|
Tempest/2d/font.cpp
|
enotio/Tempest
|
1a7105cfca3669d54c696ad8188f04f25159c0a0
|
[
"MIT"
] | 2
|
2018-01-31T14:06:58.000Z
|
2018-10-02T11:46:34.000Z
|
#include "font.h"
#include <Tempest/Pixmap>
#include <Tempest/File>
#include <ft2build.h>
#include FT_FREETYPE_H
#include <freetype/freetype.h>
#include <algorithm>
struct Tempest::FontElement::FreeTypeLib{
FreeTypeLib(){
FT_Init_FreeType( &library );
Tempest::FontElement::fnames.reserve(16);
}
~FreeTypeLib(){
std::map<Tempest::FontElement::Key, Tempest::FontElement::Leters*>::iterator
b, e;
b = letterBox.begin();
e = letterBox.end();
for( ; b!=e; ++b )
delete b->second;
FT_Done_FreeType( library );
}
std::map<Key, Leters*> letterBox;
FT_Library library;
static unsigned long ft_stream_io( FT_Stream stream,
unsigned long offset,
unsigned char* buffer,
unsigned long count ) {
if( !count && offset > stream->size )
return 1;
MemReader* file;
file = ( (MemReader*)stream->descriptor.pointer );
return file->peek(offset, (char*)buffer, count );
}
static void ft_stream_close( FT_Stream /*stream*/ ) {
return;
}
void mkStream( FT_StreamRec& stream, MemReader& file ){
stream.descriptor.pointer = &file;
stream.read = ft_stream_io;
stream.close = ft_stream_close;
stream.size = -1;
}
FT_Error New_Face( FT_Library library,
FT_StreamRec& stream,
FT_Long face_index,
FT_Face *aface ) {
FT_Open_Args args;
args.pathname = 0;
args.flags = FT_OPEN_STREAM;
args.stream = &stream;
return FT_Open_Face( library, &args, face_index, aface );
}
};
std::vector< std::u16string > Tempest::FontElement::fnames;
std::vector< std::unique_ptr<char[]> > Tempest::FontElement::fdata;
Tempest::FontElement::FreeTypeLib& Tempest::FontElement::ft(){
static FreeTypeLib lib;
return lib;
}
size_t Tempest::FontElement::findFontName(const std::string &n) {
std::u16string str;
str.assign(std::begin(n),std::end(n));
for( size_t i=0; i<fnames.size(); ++i )
if( fnames[i]==str )
return i;
fnames.push_back(std::move(str));
fdata.resize(fnames.size());
return fnames.size()-1;
}
size_t Tempest::FontElement::findFontName(const std::u16string &n) {
for( size_t i=0; i<fnames.size(); ++i )
if( fnames[i]==n )
return i;
fnames.push_back(n);
fdata.resize(fnames.size());
return fnames.size()-1;
}
Tempest::FontElement::FontElement( const std::string &name,
int sz) {
init(name, sz);
}
Tempest::FontElement::FontElement(const std::u16string &name, int sz) {
init(name, sz);
}
Tempest::FontElement::FontElement(Tempest::MemReader &buffer, int sz) {
MemFont* fnt = new MemFont();
fnt->data = new char[buffer.size()];
buffer.readData(fnt->data,buffer.size());
memData = std::shared_ptr<MemFont>(fnt);
lt = &fnt->leters;
key.size = sz;
}
Tempest::FontElement::~FontElement() {
}
Tempest::FontElement::FontElement() {
#ifdef __ANDROID__
init("/system/fonts/DroidSans", 16);
#else
init("./data/arial", 16);
#endif
}
template<class Str>
void Tempest::FontElement::init(const Str &name, int sz ) {
key.name = findFontName(name);
key.size = sz;
lt = ft().letterBox[key];
if( !lt ){
lt = new Leters();
ft().letterBox[key] = lt;
}
}
const Tempest::FontElement::Letter&
Tempest::FontElement::fetchLeter( char16_t ch,
Tempest::SpritesHolder & res ) const {
Leters & leters = *lt;
if( Letter *l = leters.find(ch) ){
if(l->surf.w()==l->size.w && l->surf.h()==l->size.h)
return *l;
}
FT_Face face = nullptr;
FT_Vector pen = {0,0};
FT_Error err = 0;
char* data = nullptr;
if(memData){
data = memData->data;
} else
if(fdata[key.name]!=nullptr){
data = fdata[key.name].get();
} else {
RFile file(fnames[key.name].c_str());
size_t sz = file.size();
data = new char[sz];
fdata[key.name].reset(data);
if(file.readData(data,sz)!=sz)
fdata[key.name].reset();
}
Tempest::MemReader reader(data,-1);
FT_StreamRec stream;
ft().mkStream(stream,reader);
err = ft().New_Face( ft().library, stream, 0, &face );
if( err )
return nullLeter(ch);
err = FT_Set_Pixel_Sizes( face, key.size, key.size );
if( err )
return nullLeter(ch);
FT_Set_Transform( face, 0, &pen );
Letter letter;
if( FT_Load_Char( face, ch, FT_LOAD_RENDER ) ){
Letter &ref = leters[ch];
ref = letter;
return ref;
}
FT_GlyphSlot slot = face->glyph;
FT_Bitmap& bmap = slot->bitmap;
letter.dpos = Tempest::Point( slot->bitmap_left,
key.size - slot->bitmap_top );
if( bmap.width!=0 && bmap.rows!=0 ){
Tempest::Pixmap pixmap( bmap.width, bmap.rows, true );
for( int r=0; r<pixmap.height(); ++r )
for( int i=0; i<pixmap.width(); ++i ) {
uint8_t lum = bmap.buffer[r * bmap.width + i];
Tempest::Pixmap::Pixel p = {255, 255, 255, lum};
pixmap.set( i,r, p );
}
//pixmap.save("./l.png");
letter.surf = res.load( pixmap );
}
letter.size = Tempest::Size( bmap.width, bmap.rows );
letter.advance = Tempest::Point( slot->advance.x >> 6,
slot->advance.y >> 6 );
FT_Done_Face( face );
Letter &ref = leters[ch];
ref = letter;
return ref;
}
Tempest::FontElement::LetterGeometry Tempest::FontElement::letterGeometry( char16_t ch ) const {
Leters & letters = *lt;
if( Letter *l = letters.find(ch) ){
LetterGeometry r;
r.advance = l->advance;
r.dpos = l->dpos;
r.size = l->size;
return r;
}
FT_Face face;
FT_Vector pen = {0,0};
FT_Error err = 0;
if(fdata[key.name]==nullptr){
RFile file(fnames[key.name].c_str());
size_t sz = file.size();
char * ch = new char[sz];
fdata[key.name].reset(ch);
if(file.readData(ch,sz)!=sz)
fdata[key.name].reset();
}
Tempest::MemReader reader(fdata[key.name].get(),size_t(-1));
FT_StreamRec stream;
ft().mkStream(stream, reader);
err = ft().New_Face( ft().library, stream, 0, &face );
if( err )
return LetterGeometry();
err = FT_Set_Pixel_Sizes( face, key.size, key.size );
if( err ){
return LetterGeometry();
}
FT_Set_Transform( face, 0, &pen );
LetterGeometry letter;
if( FT_Load_Char( face, ch, FT_LOAD_RENDER ) ){
return letter;
}
FT_GlyphSlot slot = face->glyph;
FT_Bitmap& bmap = slot->bitmap;
letter.dpos = Tempest::Point( slot->bitmap_left,
key.size - slot->bitmap_top );
letter.size = Tempest::Size( bmap.width, bmap.rows );
letter.advance = Tempest::Point( slot->advance.x >> 6,
slot->advance.y >> 6 );
FT_Done_Face( face );
Letter &ref = letters[ch];
ref.size =letter.size;
ref.dpos =letter.dpos;
ref.advance=letter.advance;
return letter;
}
const Tempest::FontElement::Letter &
Tempest::FontElement::nullLeter(char16_t ch) const {
Leters & leters = *lt;
Letter letter;
Letter &ref = leters[ch];
ref = letter;
//ref.surf.data.tex = 0;
return ref;
}
void Tempest::FontElement::fetch(const std::u16string &str,
Tempest::SpritesHolder &sp) const {
fetch(str.c_str(),sp);
}
void Tempest::FontElement::fetch(const std::string &str,
Tempest::SpritesHolder &sp) const {
fetch(str.c_str(),sp);
}
void Tempest::FontElement::fetch(const char16_t* str,
Tempest::SpritesHolder & sp ) const {
if(!str)
return;
for( size_t i=0; str[i]; ++i )
fetchLeter( str[i], sp );
}
void Tempest::FontElement::fetch(const char *str,
Tempest::SpritesHolder & sp ) const {
if(!str)
return;
for( size_t i=0; str[i]; ++i )
fetchLeter( str[i], sp );
}
Tempest::Size Tempest::FontElement::textSize(const std::u16string &str ) const {
return textSize( str.c_str(), str.c_str()+str.size() );
}
Tempest::Size Tempest::FontElement::textSize(const std::string &str ) const {
return textSize( str.c_str(), str.c_str()+str.size() );
}
Tempest::Size Tempest::FontElement::textSize(const char16_t *str) const {
const char16_t *e = str;
while(*e) ++e;
return textSize(str, e);
}
Tempest::Size Tempest::FontElement::textSize(const char *str) const {
const char *e = str;
while(*e) ++e;
return textSize(str, e);
}
Tempest::Size Tempest::FontElement::textSize(const char16_t *b, const char16_t *e) const {
int tx = 0, ty = 0, lx=0, ly=0, tw = 0, th = 0;
if(b!=e){
const LetterGeometry& l = letterGeometry( *b );
lx = l.dpos.x;
ly = l.dpos.y;
}
for( const char16_t* i=b; i<e; ++i ){
const LetterGeometry& l = letterGeometry( *i );
lx = std::min( tx+l.dpos.x, lx);
ly = std::min( ty+l.dpos.y, ly);
tw = std::max( tx+l.dpos.x+l.size.w, tw );
th = std::max( ty+l.dpos.y+l.size.h, th );
tx+= l.advance.x;
ty+= l.advance.y;
}
return Tempest::Size(tw-lx,th-ly);
}
Tempest::Size Tempest::FontElement::textSize(const char *b, const char *e) const {
int tx = 0, ty = 0, lx = 0, ly = 0, tw = 0, th = 0;
if(b!=e){
const LetterGeometry& l = letterGeometry( *b );
lx = l.dpos.x;
ly = l.dpos.y;
}
for( const char* i=b; i<e; ++i ){
const LetterGeometry& l = letterGeometry( *i );
lx = std::min( tx+l.dpos.x, lx);
ly = std::min( ty+l.dpos.y, ly);
tw = std::max( tx+l.dpos.x+l.size.w, tw );
th = std::max( ty+l.dpos.y+l.size.h, th );
tx+= l.advance.x;
ty+= l.advance.y;
}
return Tempest::Size(tw-lx,th-ly);
}
const Tempest::FontElement::Letter&
Tempest::FontElement::letter( char16_t ch,
Tempest::SpritesHolder & sp ) const {
const Tempest::FontElement::Letter& tmp = fetchLeter(ch,sp);
return tmp;
}
void Tempest::FontElement::update() {
lt = ft().letterBox[key];
if( !lt ){
lt = new Leters();
ft().letterBox[key] = lt;
}
}
Tempest::FontElement::LMap::LMap():let(0), e(0){
std::fill( n, n+256, (LMap*)0 );
}
Tempest::FontElement::LMap::~LMap() {
delete[] e;
delete[] let;
for( int i=0; i<256; ++i )
delete n[i];
}
Tempest::FontElement::Letter *Tempest::FontElement::LMap::find(char16_t c) const {
unsigned char cp[sizeof(c)];
for( size_t i=0; i<sizeof(char16_t); ++i){
cp[i] = c%256;
c/=256;
}
const LMap *l = this;
for( size_t i=sizeof(char16_t)-1; i>0; --i ){
unsigned char cx = cp[i];
if( l->n[cx]==0 )
return 0;
l = l->n[cx];
}
if( l->let==0 ){
l->let = new Letter[256];
l->e = new bool[256];
std::fill( l->e, l->e+256, false );
}
if( l->e[cp[0]] )
return l->let+cp[0];
return 0;
}
Tempest::FontElement::Letter &Tempest::FontElement::LMap::operator [](char16_t c) {
unsigned char cp[sizeof(c)];
for( size_t i=0; i<sizeof(char16_t); ++i){
cp[i] = c%256;
c/=256;
}
const LMap *l = this;
for( size_t i=sizeof(char16_t)-1; i>0; --i ){
unsigned char cx = cp[i];
if( l->n[cx]==0 ){
l->n[cx] = new LMap();
}
l = l->n[cx];
}
if( l->let==0 ){
l->let = new Letter[256];
l->e = new bool[256];
std::fill( l->e, l->e+256, false );
}
l->e[cp[0]] = 1;
return *(l->let+cp[0]);
}
bool Tempest::FontElement::Key::operator < (const Tempest::FontElement::Key &other) const {
if( size < other.size )
return 1;
if( size > other.size )
return 0;
/*
if( bold < other.bold )
return 1;
if( bold > other.bold )
return 0;
if( italic < other.italic )
return 1;
if( italic > other.italic )
return 0;
*/
return name < other.name;
}
Tempest::Font::Font(){
}
Tempest::Font::Font(const std::string &name, int sz) {
ttf[0][0] = FontElement(name + ".ttf", sz);
ttf[0][1] = FontElement(name + "i.ttf", sz);
ttf[1][0] = FontElement(name + "b.ttf", sz);
ttf[1][1] = FontElement(name + "bi.ttf", sz);
}
Tempest::Font::Font(const std::u16string &name, int sz) {
std::u16string n0 = name;
n0.append(".ttf",".ttf"+4);
ttf[0][0] = FontElement(n0, sz);
n0 = name;
n0.append("i.ttf","i.ttf"+5);
ttf[0][1] = FontElement(n0, sz);
n0 = name;
n0.append("b.ttf","b.ttf"+5);
ttf[1][0] = FontElement(n0, sz);
n0 = name;
n0.append("i.ttf","i.ttf"+5);
ttf[1][1] = FontElement(n0, sz);
}
Tempest::Font::Font( const Tempest::FontElement &n,
const Tempest::FontElement &b,
const Tempest::FontElement &i,
const Tempest::FontElement &bi ) {
ttf[0][0] = n;
ttf[0][1] = i;
ttf[1][0] = b;
ttf[1][1] = bi;
}
void Tempest::Font::fetch( const std::u16string &str,
Tempest::SpritesHolder &sp ) const {
ttf[bold][italic].fetch(str, sp);
}
void Tempest::Font::fetch( const std::string &str,
Tempest::SpritesHolder &sp ) const {
ttf[bold][italic].fetch(str, sp);
}
void Tempest::Font::fetch(const char16_t *str, Tempest::SpritesHolder &sp) const {
ttf[bold][italic].fetch(str, sp);
}
void Tempest::Font::fetch(const char *str, Tempest::SpritesHolder &sp) const {
ttf[bold][italic].fetch(str, sp);
}
const Tempest::Font::Letter &Tempest::Font::letter( char16_t ch,
Tempest::SpritesHolder &sp) const {
return ttf[bold][italic].letter(ch, sp);
}
Tempest::Font::LetterGeometry Tempest::Font::letterGeometry(char16_t ch) const {
return ttf[bold][italic].letterGeometry(ch);
}
Tempest::Size Tempest::Font::textSize(const std::u16string &s) const {
return ttf[bold][italic].textSize(s);
}
Tempest::Size Tempest::Font::textSize(const std::string &s) const {
return ttf[bold][italic].textSize(s);
}
Tempest::Size Tempest::Font::textSize(const char16_t *b, const char16_t *e) const {
return ttf[bold][italic].textSize(b,e);
}
Tempest::Size Tempest::Font::textSize(const char *b, const char *e) const {
return ttf[bold][italic].textSize(b,e);
}
Tempest::Size Tempest::Font::textSize(const char16_t *s) const {
return ttf[bold][italic].textSize(s);
}
Tempest::Size Tempest::Font::textSize(const char *s) const {
return ttf[bold][italic].textSize(s);
}
int Tempest::Font::size() const {
return ttf[bold][italic].key.size;
}
void Tempest::Font::setBold(bool b) {
bold = b? 1:0;
}
bool Tempest::Font::isBold() const {
return bold>0;
}
void Tempest::Font::setItalic(bool i) {
italic = i ? 1:0;
}
bool Tempest::Font::isItalic() const {
return italic>0;
}
void Tempest::Font::setSize(int s) {
for( int i=0; i<2; ++i )
for( int r=0; r<2; ++r ){
ttf[i][r].key.size = s;
ttf[i][r].update();
}
}
Tempest::FontElement::MemFont::~MemFont() {
delete[] data;
}
| 24.53268
| 96
| 0.58239
|
enotio
|
0594a0d72dd7da10f22b66dd865ca59dfa41f56d
| 734
|
hpp
|
C++
|
SDK/ARKSurvivalEvolved_DinoSpawnEntries_Ocean_parameters.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 10
|
2020-02-17T19:08:46.000Z
|
2021-07-31T11:07:19.000Z
|
SDK/ARKSurvivalEvolved_DinoSpawnEntries_Ocean_parameters.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 9
|
2020-02-17T18:15:41.000Z
|
2021-06-06T19:17:34.000Z
|
SDK/ARKSurvivalEvolved_DinoSpawnEntries_Ocean_parameters.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 3
|
2020-07-22T17:42:07.000Z
|
2021-06-19T17:16:13.000Z
|
#pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_DinoSpawnEntries_Ocean_classes.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function DinoSpawnEntries_Ocean.DinoSpawnEntries_Ocean_C.ExecuteUbergraph_DinoSpawnEntries_Ocean
struct UDinoSpawnEntries_Ocean_C_ExecuteUbergraph_DinoSpawnEntries_Ocean_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 26.214286
| 152
| 0.543597
|
2bite
|
05970ed668b4dc46c03af935b9eedfcb4a9d178d
| 7,799
|
hpp
|
C++
|
include/usb_asio/usb_device.hpp
|
MiSo1289/usb-asio
|
cd6aac7b9bfad1c617aa0e6d1eefeea8b00cfcdf
|
[
"MIT"
] | 47
|
2020-08-24T17:53:04.000Z
|
2022-03-11T16:03:22.000Z
|
include/usb_asio/usb_device.hpp
|
MiSo1289/usb-asio
|
cd6aac7b9bfad1c617aa0e6d1eefeea8b00cfcdf
|
[
"MIT"
] | null | null | null |
include/usb_asio/usb_device.hpp
|
MiSo1289/usb-asio
|
cd6aac7b9bfad1c617aa0e6d1eefeea8b00cfcdf
|
[
"MIT"
] | null | null | null |
#pragma once
#include <concepts>
#include <compare>
#include <cstdint>
#include <span>
#include <libusb.h>
#include "usb_asio/asio.hpp"
#include "usb_asio/error.hpp"
#include "usb_asio/libusb_ptr.hpp"
#include "usb_asio/usb_device_info.hpp"
#include "usb_asio/usb_service.hpp"
namespace usb_asio
{
template <typename Executor = asio::any_io_executor>
class basic_usb_device
{
public:
using handle_type = ::libusb_device_handle*;
using unique_handle_type = libusb_ptr<::libusb_device_handle, &::libusb_close>;
using executor_type = Executor;
using service_type = usb_service;
explicit basic_usb_device(executor_type const& executor)
: executor_{executor}
, service_{&asio::use_service<service_type>(asio::query(executor, asio::execution::context))}
{
}
template <std::derived_from<asio::execution_context> ExecutionContext>
explicit basic_usb_device(ExecutionContext& context)
: basic_usb_device{context.get_executor()}
{
}
basic_usb_device(executor_type const& executor, usb_device_info const& info)
: basic_usb_device{executor}
{
open(info);
}
template <std::derived_from<asio::execution_context> ExecutionContext>
basic_usb_device(ExecutionContext& context, usb_device_info const& info)
: basic_usb_device{context.get_executor(), info}
{
}
template <std::convertible_to<executor_type> OtherExecutor>
basic_usb_device(basic_usb_device<OtherExecutor>&& other) noexcept
: handle_{std::exchange(other.handle_, nullptr)}
, executor_{other.executor_}
, service_{other.service_}
{
}
void open(usb_device_info const& info) noexcept
{
try_with_ec([&](auto& ec) {
open(info, ec);
});
}
void open(usb_device_info const& info, error_code& ec)
{
close();
auto handle = handle_type{};
libusb_try(ec, &::libusb_open, info.handle(), &handle);
if (ec) { return; }
handle_ = unique_handle_type{handle};
service_->notify_dev_opened();
}
void close() noexcept
{
if (is_open())
{
service_->notify_dev_closed();
handle_.reset();
}
}
void set_configuration(std::uint8_t const configuration)
{
try_with_ec([&](auto& ec) {
set_configuration(configuration, ec);
});
}
void set_configuration(
std::uint8_t const configuration,
error_code& ec) noexcept
{
libusb_try(ec, &::libusb_set_configuration, handle(), configuration);
}
template <typename CompletionToken = asio::default_completion_token_t<executor_type>>
auto async_set_configuration(
std::uint8_t const configuration,
CompletionToken&& token = {})
{
return async_try_blocking_with_ec(
executor_,
service_->blocking_op_executor(),
std::forward<CompletionToken>(token),
[configuration, handle = handle()](auto& ec) {
libusb_try(ec, &::libusb_set_configuration, handle, configuration);
});
}
void clear_halt(std::uint8_t const endpoint)
{
try_with_ec([&](auto& ec) {
clear_halt(endpoint, ec);
});
}
void clear_halt(
std::uint8_t const endpoint,
error_code& ec) noexcept
{
libusb_try(ec, &::libusb_clear_halt, handle(), endpoint);
}
template <typename CompletionToken = asio::default_completion_token_t<executor_type>>
auto async_clear_halt(
std::uint8_t const endpoint,
CompletionToken&& token = {})
{
return async_try_blocking_with_ec(
executor_,
service_->blocking_op_executor(),
std::forward<CompletionToken>(token),
[endpoint, handle = handle()](auto& ec) {
libusb_try(ec, &::libusb_clear_halt, handle, endpoint);
});
}
void reset_device()
{
try_with_ec([&](auto& ec) {
reset_device(ec);
});
}
void reset_device(error_code& ec) noexcept
{
libusb_try(ec, &::libusb_reset_device, handle());
}
template <typename CompletionToken = asio::default_completion_token_t<executor_type>>
auto async_reset_device(CompletionToken&& token = {})
{
return async_try_blocking_with_ec(
executor_,
service_->blocking_op_executor(),
std::forward<CompletionToken>(token),
[handle = handle()](auto& ec) {
libusb_try(ec, &::libusb_reset_device, handle);
});
}
void alloc_streams(
std::uint32_t const num_streams,
std::span<std::uint8_t const> const endpoints)
{
try_with_ec([&](auto& ec) {
alloc_streams(num_streams, endpoints, ec);
});
}
void alloc_streams(
std::uint32_t const num_streams,
std::span<std::uint8_t const> const endpoints,
error_code& ec) noexcept
{
libusb_try(
&::libusb_alloc_streams,
handle(),
num_streams,
const_cast<unsigned char*>(
reinterpret_cast<unsigned char const*>(endpoints.data())),
static_cast<int>(endpoints.size()));
}
void free_streams(
std::span<std::uint8_t const> const endpoints)
{
try_with_ec([&](auto& ec) {
free_streams(endpoints, ec);
});
}
void free_streams(
std::span<std::uint8_t const> const endpoints,
error_code& ec) noexcept
{
libusb_try(
&::libusb_free_streams,
handle(),
const_cast<unsigned char*>(
reinterpret_cast<unsigned char const*>(endpoints.data())),
static_cast<int>(endpoints.size()));
}
[[nodiscard]] auto handle() const noexcept -> handle_type
{
return handle_.get();
}
[[nodiscard]] auto get_executor() const noexcept -> executor_type
{
return executor_;
}
[[nodiscard]] auto is_open() const noexcept -> bool
{
return handle_ == nullptr;
}
template <std::convertible_to<executor_type> OtherExecutor>
auto operator=(basic_usb_device<OtherExecutor>&& other) noexcept -> basic_usb_device&
{
handle_ = std::exchange(other.handle_, nullptr);
executor_ = other.executor_;
service_ = other.service_;
return *this;
}
[[nodiscard]] explicit operator bool() const noexcept
{
return is_open();
}
[[nodiscard]] friend auto operator<=>(
basic_usb_device const& lhs,
basic_usb_device const& rhs) noexcept
-> std::strong_ordering
{
return lhs.handle() <=> rhs.handle();
}
private:
unique_handle_type handle_;
executor_type executor_;
service_type* service_;
};
using usb_device = basic_usb_device<>;
} // namespace usb_asio
| 30.584314
| 103
| 0.548788
|
MiSo1289
|
05971dcc65a0a9e093db223379ade73c5c53932c
| 6,903
|
cpp
|
C++
|
aegisub/src/timeedit_ctrl.cpp
|
rcombs/Aegisub
|
58f35cd31c7f0f5728e0a28e6a7a9fd6fce70c50
|
[
"ISC"
] | 1
|
2018-02-12T02:44:57.000Z
|
2018-02-12T02:44:57.000Z
|
aegisub/src/timeedit_ctrl.cpp
|
rcombs/Aegisub
|
58f35cd31c7f0f5728e0a28e6a7a9fd6fce70c50
|
[
"ISC"
] | null | null | null |
aegisub/src/timeedit_ctrl.cpp
|
rcombs/Aegisub
|
58f35cd31c7f0f5728e0a28e6a7a9fd6fce70c50
|
[
"ISC"
] | 2
|
2018-02-12T03:46:24.000Z
|
2018-02-12T14:36:07.000Z
|
// Copyright (c) 2005, Rodrigo Braz Monteiro
// 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 Aegisub Group 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.
//
// Aegisub Project http://www.aegisub.org/
/// @file timeedit_ctrl.cpp
/// @brief Edit-control for editing SSA-format timestamps
/// @ingroup custom_control
///
#include "config.h"
#include "timeedit_ctrl.h"
#include <functional>
#include "ass_time.h"
#include "compat.h"
#include "include/aegisub/context.h"
#include "options.h"
#include "utils.h"
#include "video_context.h"
#include <wx/clipbrd.h>
#include <wx/dataobj.h>
#include <wx/menu.h>
#include <wx/valtext.h>
#define TimeEditWindowStyle
enum {
Time_Edit_Copy = 1320,
Time_Edit_Paste
};
TimeEdit::TimeEdit(wxWindow* parent, wxWindowID id, agi::Context *c, const std::string& value, const wxSize& size, bool asEnd)
: wxTextCtrl(parent, id, to_wx(value), wxDefaultPosition, size, wxTE_CENTRE | wxTE_PROCESS_ENTER)
, c(c)
, isEnd(asEnd)
, insert(!OPT_GET("Subtitle/Time Edit/Insert Mode")->GetBool())
, insert_opt(OPT_SUB("Subtitle/Time Edit/Insert Mode", &TimeEdit::OnInsertChanged, this))
{
// Set validator
wxTextValidator val(wxFILTER_INCLUDE_CHAR_LIST);
wxString includes[] = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ".", ":", ","};
val.SetIncludes(wxArrayString(countof(includes), includes));
SetValidator(val);
// Other stuff
if (value.empty()) SetValue(to_wx(time.GetAssFormated()));
Bind(wxEVT_MENU, std::bind(&TimeEdit::CopyTime, this), Time_Edit_Copy);
Bind(wxEVT_MENU, std::bind(&TimeEdit::PasteTime, this), Time_Edit_Paste);
Bind(wxEVT_TEXT, &TimeEdit::OnModified, this);
Bind(wxEVT_CONTEXT_MENU, &TimeEdit::OnContextMenu, this);
Bind(wxEVT_CHAR_HOOK, &TimeEdit::OnKeyDown, this);
Bind(wxEVT_CHAR, &TimeEdit::OnChar, this);
Bind(wxEVT_KILL_FOCUS, &TimeEdit::OnFocusLost, this);
}
void TimeEdit::SetTime(AssTime new_time) {
if (time != new_time) {
time = new_time;
UpdateText();
}
}
int TimeEdit::GetFrame() const {
return c->videoController->FrameAtTime(time, isEnd ? agi::vfr::END : agi::vfr::START);
}
void TimeEdit::SetFrame(int fn) {
SetTime(c->videoController->TimeAtFrame(fn, isEnd ? agi::vfr::END : agi::vfr::START));
}
void TimeEdit::SetByFrame(bool enableByFrame) {
if (enableByFrame == byFrame) return;
byFrame = enableByFrame && c->videoController->TimecodesLoaded();
UpdateText();
}
void TimeEdit::OnModified(wxCommandEvent &event) {
event.Skip();
if (byFrame) {
long temp = 0;
GetValue().ToLong(&temp);
time = c->videoController->TimeAtFrame(temp, isEnd ? agi::vfr::END : agi::vfr::START);
}
else if (insert)
time = from_wx(GetValue());
}
void TimeEdit::UpdateText() {
if (byFrame)
ChangeValue(std::to_wstring(c->videoController->FrameAtTime(time, isEnd ? agi::vfr::END : agi::vfr::START)));
else
ChangeValue(to_wx(time.GetAssFormated()));
}
void TimeEdit::OnKeyDown(wxKeyEvent &event) {
int kc = event.GetKeyCode();
// Needs to be done here to trump user-defined hotkeys
int key = event.GetUnicodeKey();
if (event.CmdDown()) {
if (key == 'C' || key == 'X')
CopyTime();
else if (key == 'V')
PasteTime();
else
event.Skip();
return;
}
// Shift-Insert would paste the stuff anyway
// but no one updates the private "time" variable.
if (event.ShiftDown() && kc == WXK_INSERT) {
PasteTime();
return;
}
if (byFrame || insert) {
event.Skip();
return;
}
// Overwrite mode stuff
// On OS X backspace is reported as delete
#ifdef __APPLE__
if (kc == WXK_DELETE)
kc = WXK_BACK;
#endif
// Back just moves cursor back one without deleting
if (kc == WXK_BACK) {
long start = GetInsertionPoint();
if (start > 0)
SetInsertionPoint(start - 1);
}
// Delete just does nothing
else if (kc != WXK_DELETE)
event.Skip();
}
void TimeEdit::OnChar(wxKeyEvent &event) {
event.Skip();
if (byFrame || insert) return;
int key = event.GetUnicodeKey();
if ((key < '0' || key > '9') && key != ';' && key != '.' && key != ',') return;
event.Skip(false);
long start = GetInsertionPoint();
std::string text = from_wx(GetValue());
// Cursor is at the end so do nothing
if (start >= (long)text.size()) return;
// If the cursor is at punctuation, move it forward to the next digit
if (text[start] == ':' || text[start] == '.' || text[start] == ',')
++start;
// : and . hop over punctuation but never insert anything
if (key == ':' || key == ';' || key == '.' || key == ',') {
SetInsertionPoint(start);
return;
}
// Overwrite the digit
text[start] = (char)key;
time = text;
SetValue(to_wx(time.GetAssFormated()));
SetInsertionPoint(start + 1);
}
void TimeEdit::OnInsertChanged(agi::OptionValue const& opt) {
insert = !opt.GetBool();
}
void TimeEdit::OnContextMenu(wxContextMenuEvent &evt) {
if (byFrame || insert) {
evt.Skip();
return;
}
wxMenu menu;
menu.Append(Time_Edit_Copy, _("&Copy"));
menu.Append(Time_Edit_Paste, _("&Paste"));
PopupMenu(&menu);
}
void TimeEdit::OnFocusLost(wxFocusEvent &evt) {
if (insert || byFrame)
UpdateText();
evt.Skip();
}
void TimeEdit::CopyTime() {
SetClipboard(from_wx(GetValue()));
}
void TimeEdit::PasteTime() {
if (byFrame) {
Paste();
return;
}
std::string text(GetClipboard());
if (text.empty()) return;
AssTime tempTime(text);
if (tempTime.GetAssFormated() == text) {
SetTime(tempTime);
SetSelection(0, GetValue().size());
wxCommandEvent evt(wxEVT_TEXT, GetId());
evt.SetEventObject(this);
HandleWindowEvent(evt);
}
}
| 28.060976
| 126
| 0.694626
|
rcombs
|
0597a663407b40a70366c93612eb6b1d47c6743e
| 3,210
|
cpp
|
C++
|
src/UnitTest/Core/MemoryManager.cpp
|
fangchuan/Open3D
|
61f991ba5d9fe3ee1e4e195a607bf48f4695d821
|
[
"MIT"
] | null | null | null |
src/UnitTest/Core/MemoryManager.cpp
|
fangchuan/Open3D
|
61f991ba5d9fe3ee1e4e195a607bf48f4695d821
|
[
"MIT"
] | null | null | null |
src/UnitTest/Core/MemoryManager.cpp
|
fangchuan/Open3D
|
61f991ba5d9fe3ee1e4e195a607bf48f4695d821
|
[
"MIT"
] | null | null | null |
// ----------------------------------------------------------------------------
// - Open3D: www.open3d.org -
// ----------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2018 www.open3d.org
//
// 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 "Open3D/Core/MemoryManager.h"
#include "Open3D/Core/Blob.h"
#include "Open3D/Core/Device.h"
#include "Core/CoreTest.h"
#include "UnitTest/UnitTest.h"
#include <vector>
namespace open3d {
namespace unit_test {
class MemoryManagerPermuteDevices : public PermuteDevices {};
INSTANTIATE_TEST_SUITE_P(MemoryManager,
MemoryManagerPermuteDevices,
testing::ValuesIn(PermuteDevices::TestCases()));
class MemoryManagerPermuteDevicePairs : public PermuteDevicePairs {};
INSTANTIATE_TEST_SUITE_P(
MemoryManager,
MemoryManagerPermuteDevicePairs,
testing::ValuesIn(MemoryManagerPermuteDevicePairs::TestCases()));
TEST_P(MemoryManagerPermuteDevices, MallocFree) {
Device device = GetParam();
void* ptr = MemoryManager::Malloc(10, device);
MemoryManager::Free(ptr, device);
}
TEST_P(MemoryManagerPermuteDevicePairs, Memcpy) {
Device dst_device;
Device src_device;
std::tie(dst_device, src_device) = GetParam();
char dst_vals[6] = "xxxxx";
char src_vals[6] = "hello";
size_t num_bytes = strlen(src_vals) + 1;
void* dst_ptr = MemoryManager::Malloc(num_bytes, dst_device);
void* src_ptr = MemoryManager::Malloc(num_bytes, src_device);
MemoryManager::MemcpyFromHost(src_ptr, src_device, (void*)src_vals,
num_bytes);
MemoryManager::Memcpy(dst_ptr, dst_device, src_ptr, src_device, num_bytes);
MemoryManager::MemcpyToHost((void*)dst_vals, dst_ptr, dst_device,
num_bytes);
ASSERT_STREQ(dst_vals, src_vals);
MemoryManager::Free(dst_ptr, dst_device);
MemoryManager::Free(src_ptr, src_device);
}
} // namespace unit_test
} // namespace open3d
| 39.146341
| 80
| 0.655763
|
fangchuan
|
0598ded5dbcc7673af8d0b34d123a50536350218
| 1,681
|
cpp
|
C++
|
Tools/NounShipPort/Port.cpp
|
SnipeDragon/darkspace
|
b6a1fa0a29d3559b158156e7b96935bd0a832ee3
|
[
"MIT"
] | 1
|
2016-05-22T21:28:29.000Z
|
2016-05-22T21:28:29.000Z
|
Tools/NounShipPort/Port.cpp
|
SnipeDragon/darkspace
|
b6a1fa0a29d3559b158156e7b96935bd0a832ee3
|
[
"MIT"
] | null | null | null |
Tools/NounShipPort/Port.cpp
|
SnipeDragon/darkspace
|
b6a1fa0a29d3559b158156e7b96935bd0a832ee3
|
[
"MIT"
] | null | null | null |
/*
Port.cpp
(c)1998 Palestar, Richard Lyle
*/
#define NOUNSHIPPORT_DLL
#include "stdafx.h"
#include "Port.h"
#include "DarkSpace/NounShip.h"
#include "DarkSpace/GameContext.h"
#include "Tools/ShipContextPort/Port.h"
#include "Tools/ScenePort/ChildFrame.h"
#include "Tools/ResourcerDoc/Port.h"
//----------------------------------------------------------------------------
IMPLEMENT_FACTORY( NounShipPort, NounBodyPort );
REGISTER_FACTORY_KEY( NounShipPort, 4040224354651462474 );
BEGIN_PROPERTY_LIST( NounShipPort, NounBodyPort )
END_PROPERTY_LIST();
NounShipPort::NounShipPort() : NounBodyPort()
{
m_Class = m_Type = CLASS_KEY( NounShip );
}
//----------------------------------------------------------------------------
const int VERSION_080701 = 80701;
bool NounShipPort::read( const InStream &input )
{
if (! NounBodyPort::read( input ) )
{
int version;
input >> version;
switch( version )
{
case VERSION_080701:
break;
}
return false;
}
return true;
}
//-------------------------------------------------------------------------------
void NounShipPort::dependencies( DependentArray & dep )
{
NounBodyPort::dependencies( dep );
}
CFrameWnd * NounShipPort::createView()
{
return( NounBodyPort::createView() );
}
BaseNode * NounShipPort::createNode()
{
return NounBodyPort::createNode();
}
void NounShipPort::initializeNode( BaseNode * pNode )
{
NounBodyPort::initializeNode( pNode );
NounShip * pShip = WidgetCast<NounShip>( pNode );
if ( pShip != NULL )
{
// make the ship visible in resourcer..
pShip->setSyncronized( true );
}
}
//-------------------------------------------------------------------------------
// EOF
| 19.776471
| 81
| 0.580012
|
SnipeDragon
|
059c22af97e6bb4f86b0a1797c0ed377e1c1176e
| 5,689
|
cpp
|
C++
|
src/Microsoft.DotNet.Wpf/src/System.Printing/CPP/src/InteropInfoLevelProfile.cpp
|
txlos/wpf
|
4004b4e8c8d5c0d5e9de0f1be1fd929c3dee6fa1
|
[
"MIT"
] | 5,937
|
2018-12-04T16:32:50.000Z
|
2022-03-31T09:48:37.000Z
|
src/Microsoft.DotNet.Wpf/src/System.Printing/CPP/src/InteropInfoLevelProfile.cpp
|
txlos/wpf
|
4004b4e8c8d5c0d5e9de0f1be1fd929c3dee6fa1
|
[
"MIT"
] | 4,151
|
2018-12-04T16:38:19.000Z
|
2022-03-31T18:41:14.000Z
|
src/Microsoft.DotNet.Wpf/src/System.Printing/CPP/src/InteropInfoLevelProfile.cpp
|
txlos/wpf
|
4004b4e8c8d5c0d5e9de0f1be1fd929c3dee6fa1
|
[
"MIT"
] | 1,084
|
2018-12-04T16:24:21.000Z
|
2022-03-30T13:52:03.000Z
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
/*++
Abstract:
InfoLevelThunk - Abstract base class for the object that it's being created
for each level that is being thunked to unmanaged code.
--*/
#include "win32inc.hpp"
#ifndef __INTEROPNAMESPACEUSAGE_HPP__
#include <InteropNamespaceUsage.hpp>
#endif
#ifndef __PRINTSYSTEMINTEROPINC_HPP__
#include <PrintSystemInteropInc.hpp>
#endif
#ifndef __INTERNALPRINTSYSTEMEXCEPTION_HPP__
#include <InternalPrintSystemException.hpp>
#endif
using namespace System::Printing;
using namespace System::Printing::IndexedProperties;
using namespace MS::Internal::PrintWin32Thunk;
using namespace MS::Internal::PrintWin32Thunk::AttributeNameToInfoLevelMapping;
/*++
Routine Name:
InfoLevelThunk
Routine Description:
Constructor
Arguments:
None.
Return Value:
N\A
--*/
InfoLevelThunk::
InfoLevelThunk(
void
) : levelMask(InfoLevelMask::NoLevel),
printInfoData(nullptr)
{
}
/*++
Routine Name:
InfoLevelThunk
Routine Description:
Constructor
Arguments:
infoLevel - Win32 level
infoLevelMask - mnask associated with the level
Return Value:
N\A
--*/
InfoLevelThunk::
InfoLevelThunk(
UInt32 infoLevel,
InfoLevelMask infoLevelMask
) : level(infoLevel),
levelMask(infoLevelMask),
printInfoData(nullptr)
{
}
/*++
Routine Name:
InternalDispose
Routine Description:
Internal Dispose method.
Arguments:
disposing - true if called on destructor
Return Value:
N\A
--*/
void
InfoLevelThunk::
Release(
)
{
if(!isDisposed)
{
if (printInfoData)
{
printInfoData->Release();
}
isDisposed = true;
}
}
/*++
Routine Name:
get_Level
Routine Description:
property
Arguments:
N\A
Return Value:
returns the level member
--*/
UInt32
InfoLevelThunk::Level::
get(
)
{
return level;
}
/*++
Routine Name:
get_Succeeded
Routine Description:
property
Arguments:
N\A
Return Value:
true if the thunking operation succeeded.
--*/
bool
InfoLevelThunk::Succeeded::
get(
void
)
{
return succeeded;
}
/*++
Routine Name:
set_Succeeded
Routine Description:
property
Arguments:
N\A
Return Value:
true if the thunking operation succeeded.
--*/
void
InfoLevelThunk::Succeeded::
set(
bool thunkingSucceeded
)
{
succeeded = thunkingSucceeded;
}
/*++
Routine Name:
get_PrintInfoData
Routine Description:
property
Arguments:
N\A
Return Value:
returns the printInfoData member that wraps the unmanaged data.
--*/
IPrinterInfo^
InfoLevelThunk::PrintInfoData::
get(
)
{
return printInfoData;
}
/*++
Routine Name:
set_PrintInfoData
Routine Description:
property
Arguments:
pInfo - this is the object that wraps the unmanaged data.
The type of the unmanaged data must be the same as
of level member inside this object.
Return Value:
N/A
--*/
void
InfoLevelThunk::PrintInfoData::
set(
IPrinterInfo^ printerInfo
)
{
printInfoData = printerInfo;
}
/*++
Routine Name:
get_LevelMask
Routine Description:
property
Arguments:
N\A
Return Value:
returns the levelMask member
--*/
InfoLevelMask
InfoLevelThunk::LevelMask::
get(
void
)
{
return levelMask;
}
/*++
Routine Name:
GetValueFromInfoData
Routine Description:
Extracts the value of a given attribute out of the unmanaged buffer.
The unmanaged buffer is assumed to contain only one structure. This applies for
Get operations.
Arguments:
name - name of the attribute.
Return Value:
Managed copy of the unmanaged data exposed as an object.
--*/
Object^
InfoLevelThunk::
GetValueFromInfoData(
String^ name
)
{
Object^ value = nullptr;
if (PrintInfoData->Count == 1)
{
value = PrintInfoData->GetValueFromName(name, 0);
}
return value;
}
/*++
Routine Name:
GetValueFromInfoData
Routine Description:
Extracts the value of a given attribute out of the unmanaged buffer.
The unmanaged buffer is assumed to contain more than one structure.
This applies for Enum operations.
Arguments:
name - name of the attribute.
index - index of the structure inside the unmanaged buffer
Return Value:
Managed copy of the unmanaged data exposed as an object.
--*/
Object^
InfoLevelThunk::
GetValueFromInfoData(
String^ valueName,
UInt32 index
)
{
Object^ value = nullptr;
if (PrintInfoData->Count)
{
value = PrintInfoData->GetValueFromName(valueName, index);
}
return value;
}
/*++
Routine Name:
SetValueFromAttributeValue
Routine Description:
Sets the value of a given attribute inside the unmanaged buffer.
The unmanaged buffer is assumed to contain one structure.
This applies for Set operations.
Arguments:
name - name of the attribute.
value - managed value to be set in the unmanaged buffer.
Return Value:
true if succeeded.
--*/
bool
InfoLevelThunk::
SetValueFromAttributeValue(
String^ valueName,
Object^ value
)
{
bool returnValue = false;
returnValue = PrintInfoData->SetValueFromName(valueName, value);
return returnValue;
}
| 14.081683
| 84
| 0.65987
|
txlos
|
059ce283b8c93cad84111c7b32408394d3b01e32
| 23,713
|
cpp
|
C++
|
compiler-rt/lib/memprof/memprof_allocator.cpp
|
ajaykumarkannan/llvm
|
d31b42c27e72d305f158289d34e55a190e00942e
|
[
"Apache-2.0"
] | 1
|
2021-12-10T01:17:03.000Z
|
2021-12-10T01:17:03.000Z
|
compiler-rt/lib/memprof/memprof_allocator.cpp
|
1samhicks/llvm-project
|
c3017819cb7fe22dcfabf90ecb34130fb6bed314
|
[
"Apache-2.0"
] | 1
|
2021-02-11T23:06:57.000Z
|
2021-02-11T23:06:57.000Z
|
compiler-rt/lib/memprof/memprof_allocator.cpp
|
1samhicks/llvm-project
|
c3017819cb7fe22dcfabf90ecb34130fb6bed314
|
[
"Apache-2.0"
] | 1
|
2021-02-11T15:05:32.000Z
|
2021-02-11T15:05:32.000Z
|
//===-- memprof_allocator.cpp --------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file is a part of MemProfiler, a memory profiler.
//
// Implementation of MemProf's memory allocator, which uses the allocator
// from sanitizer_common.
//
//===----------------------------------------------------------------------===//
#include "memprof_allocator.h"
#include "memprof_mapping.h"
#include "memprof_meminfoblock.h"
#include "memprof_mibmap.h"
#include "memprof_rawprofile.h"
#include "memprof_stack.h"
#include "memprof_thread.h"
#include "sanitizer_common/sanitizer_allocator_checks.h"
#include "sanitizer_common/sanitizer_allocator_interface.h"
#include "sanitizer_common/sanitizer_allocator_report.h"
#include "sanitizer_common/sanitizer_errno.h"
#include "sanitizer_common/sanitizer_file.h"
#include "sanitizer_common/sanitizer_flags.h"
#include "sanitizer_common/sanitizer_internal_defs.h"
#include "sanitizer_common/sanitizer_list.h"
#include "sanitizer_common/sanitizer_procmaps.h"
#include "sanitizer_common/sanitizer_stackdepot.h"
#include "sanitizer_common/sanitizer_vector.h"
#include <sched.h>
#include <time.h>
namespace __memprof {
static int GetCpuId(void) {
// _memprof_preinit is called via the preinit_array, which subsequently calls
// malloc. Since this is before _dl_init calls VDSO_SETUP, sched_getcpu
// will seg fault as the address of __vdso_getcpu will be null.
if (!memprof_init_done)
return -1;
return sched_getcpu();
}
// Compute the timestamp in ms.
static int GetTimestamp(void) {
// timespec_get will segfault if called from dl_init
if (!memprof_timestamp_inited) {
// By returning 0, this will be effectively treated as being
// timestamped at memprof init time (when memprof_init_timestamp_s
// is initialized).
return 0;
}
timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
return (ts.tv_sec - memprof_init_timestamp_s) * 1000 + ts.tv_nsec / 1000000;
}
static MemprofAllocator &get_allocator();
// The memory chunk allocated from the underlying allocator looks like this:
// H H U U U U U U
// H -- ChunkHeader (32 bytes)
// U -- user memory.
// If there is left padding before the ChunkHeader (due to use of memalign),
// we store a magic value in the first uptr word of the memory block and
// store the address of ChunkHeader in the next uptr.
// M B L L L L L L L L L H H U U U U U U
// | ^
// ---------------------|
// M -- magic value kAllocBegMagic
// B -- address of ChunkHeader pointing to the first 'H'
constexpr uptr kMaxAllowedMallocBits = 40;
// Should be no more than 32-bytes
struct ChunkHeader {
// 1-st 4 bytes.
u32 alloc_context_id;
// 2-nd 4 bytes
u32 cpu_id;
// 3-rd 4 bytes
u32 timestamp_ms;
// 4-th 4 bytes
// Note only 1 bit is needed for this flag if we need space in the future for
// more fields.
u32 from_memalign;
// 5-th and 6-th 4 bytes
// The max size of an allocation is 2^40 (kMaxAllowedMallocSize), so this
// could be shrunk to kMaxAllowedMallocBits if we need space in the future for
// more fields.
atomic_uint64_t user_requested_size;
// 23 bits available
// 7-th and 8-th 4 bytes
u64 data_type_id; // TODO: hash of type name
};
static const uptr kChunkHeaderSize = sizeof(ChunkHeader);
COMPILER_CHECK(kChunkHeaderSize == 32);
struct MemprofChunk : ChunkHeader {
uptr Beg() { return reinterpret_cast<uptr>(this) + kChunkHeaderSize; }
uptr UsedSize() {
return atomic_load(&user_requested_size, memory_order_relaxed);
}
void *AllocBeg() {
if (from_memalign)
return get_allocator().GetBlockBegin(reinterpret_cast<void *>(this));
return reinterpret_cast<void *>(this);
}
};
class LargeChunkHeader {
static constexpr uptr kAllocBegMagic =
FIRST_32_SECOND_64(0xCC6E96B9, 0xCC6E96B9CC6E96B9ULL);
atomic_uintptr_t magic;
MemprofChunk *chunk_header;
public:
MemprofChunk *Get() const {
return atomic_load(&magic, memory_order_acquire) == kAllocBegMagic
? chunk_header
: nullptr;
}
void Set(MemprofChunk *p) {
if (p) {
chunk_header = p;
atomic_store(&magic, kAllocBegMagic, memory_order_release);
return;
}
uptr old = kAllocBegMagic;
if (!atomic_compare_exchange_strong(&magic, &old, 0,
memory_order_release)) {
CHECK_EQ(old, kAllocBegMagic);
}
}
};
void FlushUnneededMemProfShadowMemory(uptr p, uptr size) {
// Since memprof's mapping is compacting, the shadow chunk may be
// not page-aligned, so we only flush the page-aligned portion.
ReleaseMemoryPagesToOS(MemToShadow(p), MemToShadow(p + size));
}
void MemprofMapUnmapCallback::OnMap(uptr p, uptr size) const {
// Statistics.
MemprofStats &thread_stats = GetCurrentThreadStats();
thread_stats.mmaps++;
thread_stats.mmaped += size;
}
void MemprofMapUnmapCallback::OnUnmap(uptr p, uptr size) const {
// We are about to unmap a chunk of user memory.
// Mark the corresponding shadow memory as not needed.
FlushUnneededMemProfShadowMemory(p, size);
// Statistics.
MemprofStats &thread_stats = GetCurrentThreadStats();
thread_stats.munmaps++;
thread_stats.munmaped += size;
}
AllocatorCache *GetAllocatorCache(MemprofThreadLocalMallocStorage *ms) {
CHECK(ms);
return &ms->allocator_cache;
}
// Accumulates the access count from the shadow for the given pointer and size.
u64 GetShadowCount(uptr p, u32 size) {
u64 *shadow = (u64 *)MEM_TO_SHADOW(p);
u64 *shadow_end = (u64 *)MEM_TO_SHADOW(p + size);
u64 count = 0;
for (; shadow <= shadow_end; shadow++)
count += *shadow;
return count;
}
// Clears the shadow counters (when memory is allocated).
void ClearShadow(uptr addr, uptr size) {
CHECK(AddrIsAlignedByGranularity(addr));
CHECK(AddrIsInMem(addr));
CHECK(AddrIsAlignedByGranularity(addr + size));
CHECK(AddrIsInMem(addr + size - SHADOW_GRANULARITY));
CHECK(REAL(memset));
uptr shadow_beg = MEM_TO_SHADOW(addr);
uptr shadow_end = MEM_TO_SHADOW(addr + size - SHADOW_GRANULARITY) + 1;
if (shadow_end - shadow_beg < common_flags()->clear_shadow_mmap_threshold) {
REAL(memset)((void *)shadow_beg, 0, shadow_end - shadow_beg);
} else {
uptr page_size = GetPageSizeCached();
uptr page_beg = RoundUpTo(shadow_beg, page_size);
uptr page_end = RoundDownTo(shadow_end, page_size);
if (page_beg >= page_end) {
REAL(memset)((void *)shadow_beg, 0, shadow_end - shadow_beg);
} else {
if (page_beg != shadow_beg) {
REAL(memset)((void *)shadow_beg, 0, page_beg - shadow_beg);
}
if (page_end != shadow_end) {
REAL(memset)((void *)page_end, 0, shadow_end - page_end);
}
ReserveShadowMemoryRange(page_beg, page_end - 1, nullptr);
}
}
}
struct Allocator {
static const uptr kMaxAllowedMallocSize = 1ULL << kMaxAllowedMallocBits;
MemprofAllocator allocator;
StaticSpinMutex fallback_mutex;
AllocatorCache fallback_allocator_cache;
uptr max_user_defined_malloc_size;
atomic_uint8_t rss_limit_exceeded;
// Holds the mapping of stack ids to MemInfoBlocks.
MIBMapTy MIBMap;
atomic_uint8_t destructing;
atomic_uint8_t constructed;
bool print_text;
// ------------------- Initialization ------------------------
explicit Allocator(LinkerInitialized) : print_text(flags()->print_text) {
atomic_store_relaxed(&destructing, 0);
atomic_store_relaxed(&constructed, 1);
}
~Allocator() {
atomic_store_relaxed(&destructing, 1);
FinishAndWrite();
}
static void PrintCallback(const uptr Key, LockedMemInfoBlock *const &Value,
void *Arg) {
SpinMutexLock(&Value->mutex);
Value->mib.Print(Key, bool(Arg));
}
void FinishAndWrite() {
if (print_text && common_flags()->print_module_map)
DumpProcessMap();
allocator.ForceLock();
InsertLiveBlocks();
if (print_text) {
if (!flags()->print_terse)
Printf("Recorded MIBs (incl. live on exit):\n");
MIBMap.ForEach(PrintCallback,
reinterpret_cast<void *>(flags()->print_terse));
StackDepotPrintAll();
} else {
// Serialize the contents to a raw profile. Format documented in
// memprof_rawprofile.h.
char *Buffer = nullptr;
MemoryMappingLayout Layout(/*cache_enabled=*/true);
u64 BytesSerialized = SerializeToRawProfile(MIBMap, Layout, Buffer);
CHECK(Buffer && BytesSerialized && "could not serialize to buffer");
report_file.Write(Buffer, BytesSerialized);
}
allocator.ForceUnlock();
}
// Inserts any blocks which have been allocated but not yet deallocated.
void InsertLiveBlocks() {
allocator.ForEachChunk(
[](uptr chunk, void *alloc) {
u64 user_requested_size;
Allocator *A = (Allocator *)alloc;
MemprofChunk *m =
A->GetMemprofChunk((void *)chunk, user_requested_size);
if (!m)
return;
uptr user_beg = ((uptr)m) + kChunkHeaderSize;
u64 c = GetShadowCount(user_beg, user_requested_size);
long curtime = GetTimestamp();
MemInfoBlock newMIB(user_requested_size, c, m->timestamp_ms, curtime,
m->cpu_id, GetCpuId());
InsertOrMerge(m->alloc_context_id, newMIB, A->MIBMap);
},
this);
}
void InitLinkerInitialized() {
SetAllocatorMayReturnNull(common_flags()->allocator_may_return_null);
allocator.InitLinkerInitialized(
common_flags()->allocator_release_to_os_interval_ms);
max_user_defined_malloc_size = common_flags()->max_allocation_size_mb
? common_flags()->max_allocation_size_mb
<< 20
: kMaxAllowedMallocSize;
}
bool RssLimitExceeded() {
return atomic_load(&rss_limit_exceeded, memory_order_relaxed);
}
void SetRssLimitExceeded(bool limit_exceeded) {
atomic_store(&rss_limit_exceeded, limit_exceeded, memory_order_relaxed);
}
// -------------------- Allocation/Deallocation routines ---------------
void *Allocate(uptr size, uptr alignment, BufferedStackTrace *stack,
AllocType alloc_type) {
if (UNLIKELY(!memprof_inited))
MemprofInitFromRtl();
if (RssLimitExceeded()) {
if (AllocatorMayReturnNull())
return nullptr;
ReportRssLimitExceeded(stack);
}
CHECK(stack);
const uptr min_alignment = MEMPROF_ALIGNMENT;
if (alignment < min_alignment)
alignment = min_alignment;
if (size == 0) {
// We'd be happy to avoid allocating memory for zero-size requests, but
// some programs/tests depend on this behavior and assume that malloc
// would not return NULL even for zero-size allocations. Moreover, it
// looks like operator new should never return NULL, and results of
// consecutive "new" calls must be different even if the allocated size
// is zero.
size = 1;
}
CHECK(IsPowerOfTwo(alignment));
uptr rounded_size = RoundUpTo(size, alignment);
uptr needed_size = rounded_size + kChunkHeaderSize;
if (alignment > min_alignment)
needed_size += alignment;
CHECK(IsAligned(needed_size, min_alignment));
if (size > kMaxAllowedMallocSize || needed_size > kMaxAllowedMallocSize ||
size > max_user_defined_malloc_size) {
if (AllocatorMayReturnNull()) {
Report("WARNING: MemProfiler failed to allocate 0x%zx bytes\n", size);
return nullptr;
}
uptr malloc_limit =
Min(kMaxAllowedMallocSize, max_user_defined_malloc_size);
ReportAllocationSizeTooBig(size, malloc_limit, stack);
}
MemprofThread *t = GetCurrentThread();
void *allocated;
if (t) {
AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
allocated = allocator.Allocate(cache, needed_size, 8);
} else {
SpinMutexLock l(&fallback_mutex);
AllocatorCache *cache = &fallback_allocator_cache;
allocated = allocator.Allocate(cache, needed_size, 8);
}
if (UNLIKELY(!allocated)) {
SetAllocatorOutOfMemory();
if (AllocatorMayReturnNull())
return nullptr;
ReportOutOfMemory(size, stack);
}
uptr alloc_beg = reinterpret_cast<uptr>(allocated);
uptr alloc_end = alloc_beg + needed_size;
uptr beg_plus_header = alloc_beg + kChunkHeaderSize;
uptr user_beg = beg_plus_header;
if (!IsAligned(user_beg, alignment))
user_beg = RoundUpTo(user_beg, alignment);
uptr user_end = user_beg + size;
CHECK_LE(user_end, alloc_end);
uptr chunk_beg = user_beg - kChunkHeaderSize;
MemprofChunk *m = reinterpret_cast<MemprofChunk *>(chunk_beg);
m->from_memalign = alloc_beg != chunk_beg;
CHECK(size);
m->cpu_id = GetCpuId();
m->timestamp_ms = GetTimestamp();
m->alloc_context_id = StackDepotPut(*stack);
uptr size_rounded_down_to_granularity =
RoundDownTo(size, SHADOW_GRANULARITY);
if (size_rounded_down_to_granularity)
ClearShadow(user_beg, size_rounded_down_to_granularity);
MemprofStats &thread_stats = GetCurrentThreadStats();
thread_stats.mallocs++;
thread_stats.malloced += size;
thread_stats.malloced_overhead += needed_size - size;
if (needed_size > SizeClassMap::kMaxSize)
thread_stats.malloc_large++;
else
thread_stats.malloced_by_size[SizeClassMap::ClassID(needed_size)]++;
void *res = reinterpret_cast<void *>(user_beg);
atomic_store(&m->user_requested_size, size, memory_order_release);
if (alloc_beg != chunk_beg) {
CHECK_LE(alloc_beg + sizeof(LargeChunkHeader), chunk_beg);
reinterpret_cast<LargeChunkHeader *>(alloc_beg)->Set(m);
}
MEMPROF_MALLOC_HOOK(res, size);
return res;
}
void Deallocate(void *ptr, uptr delete_size, uptr delete_alignment,
BufferedStackTrace *stack, AllocType alloc_type) {
uptr p = reinterpret_cast<uptr>(ptr);
if (p == 0)
return;
MEMPROF_FREE_HOOK(ptr);
uptr chunk_beg = p - kChunkHeaderSize;
MemprofChunk *m = reinterpret_cast<MemprofChunk *>(chunk_beg);
u64 user_requested_size =
atomic_exchange(&m->user_requested_size, 0, memory_order_acquire);
if (memprof_inited && memprof_init_done &&
atomic_load_relaxed(&constructed) &&
!atomic_load_relaxed(&destructing)) {
u64 c = GetShadowCount(p, user_requested_size);
long curtime = GetTimestamp();
MemInfoBlock newMIB(user_requested_size, c, m->timestamp_ms, curtime,
m->cpu_id, GetCpuId());
InsertOrMerge(m->alloc_context_id, newMIB, MIBMap);
}
MemprofStats &thread_stats = GetCurrentThreadStats();
thread_stats.frees++;
thread_stats.freed += user_requested_size;
void *alloc_beg = m->AllocBeg();
if (alloc_beg != m) {
// Clear the magic value, as allocator internals may overwrite the
// contents of deallocated chunk, confusing GetMemprofChunk lookup.
reinterpret_cast<LargeChunkHeader *>(alloc_beg)->Set(nullptr);
}
MemprofThread *t = GetCurrentThread();
if (t) {
AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
allocator.Deallocate(cache, alloc_beg);
} else {
SpinMutexLock l(&fallback_mutex);
AllocatorCache *cache = &fallback_allocator_cache;
allocator.Deallocate(cache, alloc_beg);
}
}
void *Reallocate(void *old_ptr, uptr new_size, BufferedStackTrace *stack) {
CHECK(old_ptr && new_size);
uptr p = reinterpret_cast<uptr>(old_ptr);
uptr chunk_beg = p - kChunkHeaderSize;
MemprofChunk *m = reinterpret_cast<MemprofChunk *>(chunk_beg);
MemprofStats &thread_stats = GetCurrentThreadStats();
thread_stats.reallocs++;
thread_stats.realloced += new_size;
void *new_ptr = Allocate(new_size, 8, stack, FROM_MALLOC);
if (new_ptr) {
CHECK_NE(REAL(memcpy), nullptr);
uptr memcpy_size = Min(new_size, m->UsedSize());
REAL(memcpy)(new_ptr, old_ptr, memcpy_size);
Deallocate(old_ptr, 0, 0, stack, FROM_MALLOC);
}
return new_ptr;
}
void *Calloc(uptr nmemb, uptr size, BufferedStackTrace *stack) {
if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) {
if (AllocatorMayReturnNull())
return nullptr;
ReportCallocOverflow(nmemb, size, stack);
}
void *ptr = Allocate(nmemb * size, 8, stack, FROM_MALLOC);
// If the memory comes from the secondary allocator no need to clear it
// as it comes directly from mmap.
if (ptr && allocator.FromPrimary(ptr))
REAL(memset)(ptr, 0, nmemb * size);
return ptr;
}
void CommitBack(MemprofThreadLocalMallocStorage *ms,
BufferedStackTrace *stack) {
AllocatorCache *ac = GetAllocatorCache(ms);
allocator.SwallowCache(ac);
}
// -------------------------- Chunk lookup ----------------------
// Assumes alloc_beg == allocator.GetBlockBegin(alloc_beg).
MemprofChunk *GetMemprofChunk(void *alloc_beg, u64 &user_requested_size) {
if (!alloc_beg)
return nullptr;
MemprofChunk *p = reinterpret_cast<LargeChunkHeader *>(alloc_beg)->Get();
if (!p) {
if (!allocator.FromPrimary(alloc_beg))
return nullptr;
p = reinterpret_cast<MemprofChunk *>(alloc_beg);
}
// The size is reset to 0 on deallocation (and a min of 1 on
// allocation).
user_requested_size =
atomic_load(&p->user_requested_size, memory_order_acquire);
if (user_requested_size)
return p;
return nullptr;
}
MemprofChunk *GetMemprofChunkByAddr(uptr p, u64 &user_requested_size) {
void *alloc_beg = allocator.GetBlockBegin(reinterpret_cast<void *>(p));
return GetMemprofChunk(alloc_beg, user_requested_size);
}
uptr AllocationSize(uptr p) {
u64 user_requested_size;
MemprofChunk *m = GetMemprofChunkByAddr(p, user_requested_size);
if (!m)
return 0;
if (m->Beg() != p)
return 0;
return user_requested_size;
}
void Purge(BufferedStackTrace *stack) { allocator.ForceReleaseToOS(); }
void PrintStats() { allocator.PrintStats(); }
void ForceLock() NO_THREAD_SAFETY_ANALYSIS {
allocator.ForceLock();
fallback_mutex.Lock();
}
void ForceUnlock() NO_THREAD_SAFETY_ANALYSIS {
fallback_mutex.Unlock();
allocator.ForceUnlock();
}
};
static Allocator instance(LINKER_INITIALIZED);
static MemprofAllocator &get_allocator() { return instance.allocator; }
void InitializeAllocator() { instance.InitLinkerInitialized(); }
void MemprofThreadLocalMallocStorage::CommitBack() {
GET_STACK_TRACE_MALLOC;
instance.CommitBack(this, &stack);
}
void PrintInternalAllocatorStats() { instance.PrintStats(); }
void memprof_free(void *ptr, BufferedStackTrace *stack, AllocType alloc_type) {
instance.Deallocate(ptr, 0, 0, stack, alloc_type);
}
void memprof_delete(void *ptr, uptr size, uptr alignment,
BufferedStackTrace *stack, AllocType alloc_type) {
instance.Deallocate(ptr, size, alignment, stack, alloc_type);
}
void *memprof_malloc(uptr size, BufferedStackTrace *stack) {
return SetErrnoOnNull(instance.Allocate(size, 8, stack, FROM_MALLOC));
}
void *memprof_calloc(uptr nmemb, uptr size, BufferedStackTrace *stack) {
return SetErrnoOnNull(instance.Calloc(nmemb, size, stack));
}
void *memprof_reallocarray(void *p, uptr nmemb, uptr size,
BufferedStackTrace *stack) {
if (UNLIKELY(CheckForCallocOverflow(size, nmemb))) {
errno = errno_ENOMEM;
if (AllocatorMayReturnNull())
return nullptr;
ReportReallocArrayOverflow(nmemb, size, stack);
}
return memprof_realloc(p, nmemb * size, stack);
}
void *memprof_realloc(void *p, uptr size, BufferedStackTrace *stack) {
if (!p)
return SetErrnoOnNull(instance.Allocate(size, 8, stack, FROM_MALLOC));
if (size == 0) {
if (flags()->allocator_frees_and_returns_null_on_realloc_zero) {
instance.Deallocate(p, 0, 0, stack, FROM_MALLOC);
return nullptr;
}
// Allocate a size of 1 if we shouldn't free() on Realloc to 0
size = 1;
}
return SetErrnoOnNull(instance.Reallocate(p, size, stack));
}
void *memprof_valloc(uptr size, BufferedStackTrace *stack) {
return SetErrnoOnNull(
instance.Allocate(size, GetPageSizeCached(), stack, FROM_MALLOC));
}
void *memprof_pvalloc(uptr size, BufferedStackTrace *stack) {
uptr PageSize = GetPageSizeCached();
if (UNLIKELY(CheckForPvallocOverflow(size, PageSize))) {
errno = errno_ENOMEM;
if (AllocatorMayReturnNull())
return nullptr;
ReportPvallocOverflow(size, stack);
}
// pvalloc(0) should allocate one page.
size = size ? RoundUpTo(size, PageSize) : PageSize;
return SetErrnoOnNull(instance.Allocate(size, PageSize, stack, FROM_MALLOC));
}
void *memprof_memalign(uptr alignment, uptr size, BufferedStackTrace *stack,
AllocType alloc_type) {
if (UNLIKELY(!IsPowerOfTwo(alignment))) {
errno = errno_EINVAL;
if (AllocatorMayReturnNull())
return nullptr;
ReportInvalidAllocationAlignment(alignment, stack);
}
return SetErrnoOnNull(instance.Allocate(size, alignment, stack, alloc_type));
}
void *memprof_aligned_alloc(uptr alignment, uptr size,
BufferedStackTrace *stack) {
if (UNLIKELY(!CheckAlignedAllocAlignmentAndSize(alignment, size))) {
errno = errno_EINVAL;
if (AllocatorMayReturnNull())
return nullptr;
ReportInvalidAlignedAllocAlignment(size, alignment, stack);
}
return SetErrnoOnNull(instance.Allocate(size, alignment, stack, FROM_MALLOC));
}
int memprof_posix_memalign(void **memptr, uptr alignment, uptr size,
BufferedStackTrace *stack) {
if (UNLIKELY(!CheckPosixMemalignAlignment(alignment))) {
if (AllocatorMayReturnNull())
return errno_EINVAL;
ReportInvalidPosixMemalignAlignment(alignment, stack);
}
void *ptr = instance.Allocate(size, alignment, stack, FROM_MALLOC);
if (UNLIKELY(!ptr))
// OOM error is already taken care of by Allocate.
return errno_ENOMEM;
CHECK(IsAligned((uptr)ptr, alignment));
*memptr = ptr;
return 0;
}
uptr memprof_malloc_usable_size(const void *ptr, uptr pc, uptr bp) {
if (!ptr)
return 0;
uptr usable_size = instance.AllocationSize(reinterpret_cast<uptr>(ptr));
return usable_size;
}
void MemprofSoftRssLimitExceededCallback(bool limit_exceeded) {
instance.SetRssLimitExceeded(limit_exceeded);
}
} // namespace __memprof
// ---------------------- Interface ---------------- {{{1
using namespace __memprof;
#if !SANITIZER_SUPPORTS_WEAK_HOOKS
// Provide default (no-op) implementation of malloc hooks.
SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_malloc_hook, void *ptr,
uptr size) {
(void)ptr;
(void)size;
}
SANITIZER_INTERFACE_WEAK_DEF(void, __sanitizer_free_hook, void *ptr) {
(void)ptr;
}
#endif
uptr __sanitizer_get_estimated_allocated_size(uptr size) { return size; }
int __sanitizer_get_ownership(const void *p) {
return memprof_malloc_usable_size(p, 0, 0) != 0;
}
uptr __sanitizer_get_allocated_size(const void *p) {
return memprof_malloc_usable_size(p, 0, 0);
}
int __memprof_profile_dump() {
instance.FinishAndWrite();
// In the future we may want to return non-zero if there are any errors
// detected during the dumping process.
return 0;
}
| 33.731152
| 80
| 0.684983
|
ajaykumarkannan
|
05a1fcc957de1a7b4b5bbdd0d19a2f92991e296b
| 15,134
|
hpp
|
C++
|
http.hpp
|
kissbeni/tinyhttp
|
2e7dddbbb4ac0824ec457eadfcf00106fce5154c
|
[
"Apache-2.0"
] | 2
|
2021-11-27T18:35:20.000Z
|
2022-03-23T08:11:57.000Z
|
http.hpp
|
kissbeni/tinyhttp
|
2e7dddbbb4ac0824ec457eadfcf00106fce5154c
|
[
"Apache-2.0"
] | null | null | null |
http.hpp
|
kissbeni/tinyhttp
|
2e7dddbbb4ac0824ec457eadfcf00106fce5154c
|
[
"Apache-2.0"
] | null | null | null |
#ifndef HTTP_SERVER_H
#define HTTP_SERVER_H
// json support (Currently uses MiniJson)
#define TINYHTTP_JSON
// websocket support
#define TINYHTTP_WS
// template integration
#define TINYHTTP_TEMPLATES
#ifndef MAX_HTTP_HEADERS
# define MAX_HTTP_HEADERS 30
#endif
#ifndef MAX_HTTP_CONTENT_SIZE
# define MAX_HTTP_CONTENT_SIZE (50*1024) // 50kiB
#endif
#ifndef MAX_ALLOWED_WS_FRAME_LENGTH
# define MAX_ALLOWED_WS_FRAME_LENGTH (50*1024) // 50kiB
#endif
#ifndef WS_FRAGMENT_THRESHOLD
# define WS_FRAGMENT_THRESHOLD (2*1024) // 2kiB
#endif
#include <cstdint>
#include <string>
#include <memory>
#include <stdexcept>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <thread>
#include <regex>
#include <map>
#include <iostream>
#include <fstream>
#ifdef TINYHTTP_JSON
# include <json.h>
#endif
#ifdef TINYHTTP_TEMPLATES
# include <HTMLTemplate.h>
#endif
enum class HttpRequestMethod { GET,POST,PUT,DELETE,OPTIONS,UNKNOWN };
#ifdef TINYHTTP_WS
enum {
WSOPC_CONTINUATION = 0x0,
WSOPC_TEXT = 0x1,
WSOPC_BINARY = 0x2,
WSOPC_NONCTRL_RES0 = 0x3,
WSOPC_NONCTRL_RES1 = 0x4,
WSOPC_NONCTRL_RES2 = 0x5,
WSOPC_NONCTRL_RES3 = 0x6,
WSOPC_NONCTRL_RES4 = 0x7,
WSOPC_DISCONNECT = 0x8,
WSOPC_PING = 0x9,
WSOPC_PONG = 0xA,
WSOPC_CTRL_RES0 = 0xB,
WSOPC_CTRL_RES1 = 0xC,
WSOPC_CTRL_RES2 = 0xD,
WSOPC_CTRL_RES3 = 0xE,
WSOPC_CTRL_RES4 = 0xF,
};
#endif
struct IClientStream {
virtual ~IClientStream() = default;
virtual bool isOpen() noexcept = 0;
virtual void send(const void* what, size_t size) = 0;
virtual size_t receive(void* target, size_t max) = 0;
virtual std::string receiveLine(bool asciiOnly = true, size_t max = -1) = 0;
virtual void close() = 0;
// wrapper for send for any object having a data() -> uint8_t* and a size() -> integer function
template<
typename T,
typename Chk1 = typename std::enable_if<std::is_same<decltype(T().data()), uint8_t*>::value>::type,
typename Chk2 = typename std::enable_if<std::is_integral<decltype(T().size())>::value>::type
>
void send(const T& data) { send(data.data(), data.size()); }
bool mErrorFlag = false;
};
class TCPClientStream : public IClientStream {
short mSocket;
public:
~TCPClientStream() { close(); }
TCPClientStream(short socket) : mSocket{socket} {}
TCPClientStream(const TCPClientStream&) = delete;
TCPClientStream(TCPClientStream&& other) : mSocket{other.mSocket} { other.mSocket = -1; }
static TCPClientStream acceptFrom(short listener);
bool isOpen() noexcept override { return mSocket >= 0 && !mErrorFlag; }
void send(const void* what, size_t size) override;
size_t receive(void* target, size_t max) override;
std::string receiveLine(bool asciiOnly = true, size_t max = -1) override;
void close() override;
};
struct StdinClientStream : IClientStream {
bool isOpen() noexcept override { return true; };
void send(const void* what, size_t size) override {
fwrite(what, 1, size, stdout);
fflush(stdout);
}
size_t receive(void* target, size_t max) override {
return fread(target, 1, max, stdin);
}
std::string receiveLine(bool asciiOnly = true, size_t max = -1) override {
std::string res;
std::getline(std::cin, res);
if (res.length() > 0 && res[res.length()-1] == '\r')
res = res.substr(0, res.length() - 1);
return res;
}
void close() override {}
};
struct MessageBuilder : public std::vector<uint8_t> {
template<typename T>
void write(T s) {
write(&s, sizeof(T));
}
void write(const std::string& s) {
write(s.data(), s.size());
}
void write(const char* s) {
write(s, strlen(s));
}
void writeCRLF() { write("\r\n", 2); }
void write(const void* data, const size_t len) {
size_t ogsize = size();
resize(ogsize + len);
memcpy(this->data() + ogsize, data, len);
}
};
class HttpMessageCommon {
protected:
std::map<std::string, std::string> mHeaders;
std::string mContent;
public:
std::string& operator[](std::string i) {
std::transform(i.begin(), i.end(), i.begin(), [](unsigned char c){ return std::tolower(c); });
auto f = mHeaders.find(i);
if (f == mHeaders.end()) {
if (mHeaders.size() >= MAX_HTTP_HEADERS)
throw std::runtime_error("too many HTTP headers");
mHeaders.insert(std::pair<std::string,std::string>(i, ""));
}
return mHeaders.find(i)->second;
}
std::string operator[](std::string i) const {
std::transform(i.begin(), i.end(), i.begin(), [](unsigned char c){ return std::tolower(c); });
auto f = mHeaders.find(i);
if (f == mHeaders.end())
return "";
return mHeaders.find(i)->second;
}
void setContent(std::string content) {
mContent = std::move(content);
(*this)["Content-Length"] = std::to_string(mContent.size());
}
const auto& content() const noexcept { return mContent; }
};
class HttpRequest : public HttpMessageCommon {
HttpRequestMethod mMethod = HttpRequestMethod::UNKNOWN;
std::string path, query;
#ifdef TINYHTTP_JSON
miniJson::Json mContentJson;
#endif
public:
bool parse(std::shared_ptr<IClientStream> stream);
const HttpRequestMethod& getMethod() const noexcept { return mMethod; }
const std::string& getPath() const noexcept { return path; }
const std::string& getQuery() const noexcept { return query; }
#ifdef TINYHTTP_JSON
const miniJson::Json& json() const noexcept { return mContentJson; }
#endif
};
struct ICanRequestProtocolHandover {
virtual ~ICanRequestProtocolHandover() = default;
virtual void acceptHandover(short& serverSock, IClientStream& client, std::unique_ptr<HttpRequest> srcRequest) = 0;
};
#ifdef TINYHTTP_WS
struct WebsockClientHandler {
virtual void onConnect() {}
virtual void onDisconnect() {}
virtual void onTextMessage(const std::string& message) {}
virtual void onBinaryMessage(const std::vector<uint8_t>& data) {}
void sendRaw(uint8_t opcode, const void* data, size_t length, bool mask = false);
void sendDisconnect();
void sendText(const std::string& str);
void sendBinary(const void* data, size_t length);
template<size_t N>
void sendBinary(const uint8_t data[N]) {
sendBinary(data, N);
}
// wrapper for send for any object having a data() -> uint8_t* and a size() -> integer function
template<
typename T,
typename Chk1 = typename std::enable_if<std::is_same<decltype(T().data()), uint8_t*>::value>::type,
typename Chk2 = typename std::enable_if<std::is_integral<decltype(T().size())>::value>::type
>
void sendBinary(const T& data) { sendBinary(data.data(), data.size()); }
#ifdef TINYHTTP_JSON
void sendJson(const miniJson::Json& json) {
sendText(json.serialize());
}
#endif
void attachTcpStream(IClientStream* s) { mClient = s; }
void attachRequest(std::unique_ptr<HttpRequest> req) { mRequest.swap(req); }
protected:
IClientStream* mClient;
std::unique_ptr<HttpRequest> mRequest;
};
#endif
class HttpResponse : public HttpMessageCommon {
unsigned mStatusCode = 400;
ICanRequestProtocolHandover* mHandover = nullptr;
public:
HttpResponse(const unsigned statusCode) : mStatusCode{statusCode} {
(*this)["Server"] = "tinyHTTP_1.1";
if (statusCode >= 200)
(*this)["Content-Length"] = "0";
}
HttpResponse(const unsigned statusCode, std::string contentType, std::string content)
: HttpResponse{statusCode} {
(*this)["Content-Type"] = contentType;
setContent(content);
}
void requestProtocolHandover(ICanRequestProtocolHandover* newOwner) {
mHandover = newOwner;
}
bool acceptProtocolHandover(ICanRequestProtocolHandover** outTarget) {
if (outTarget && mHandover)
{
*outTarget = mHandover;
return true;
}
return false;
}
#ifdef TINYHTTP_JSON
HttpResponse(const unsigned statusCode, const miniJson::Json& json)
: HttpResponse{statusCode, "application/json", json.serialize()} {}
#endif
#ifdef TINYHTTP_TEMPLATES
HttpResponse(const unsigned statusCode, HTMLTemplate&& _template)
: HttpResponse{statusCode, "text/html", _template.render()} {}
#endif
MessageBuilder buildMessage() {
MessageBuilder b;
b.write("HTTP/1.1 " + std::to_string(mStatusCode));
b.writeCRLF();
for (auto& h : mHeaders)
if (!h.second.empty())
b.write(h.first + ": " + h.second + "\r\n");
b.writeCRLF();
b.write(mContent);
return b;
}
};
struct HandlerBuilder {
virtual ~HandlerBuilder() = default;
virtual std::unique_ptr<HttpResponse> process(const HttpRequest& req) {
return nullptr;
}
};
class WebsockHandlerBuilder : public HandlerBuilder, public ICanRequestProtocolHandover {
struct Factory {
virtual ~Factory() = default;
virtual WebsockClientHandler* makeInstance() = 0;
};
template<typename T>
struct FactoryT : Factory {
virtual WebsockClientHandler* makeInstance() {
return new T();
}
};
std::unique_ptr<Factory> mFactory;
public:
WebsockHandlerBuilder()
: mFactory{new FactoryT<WebsockClientHandler>} {}
template<typename T>
void handleWith() {
mFactory = std::unique_ptr<Factory>(new FactoryT<T>);
}
virtual std::unique_ptr<HttpResponse> process(const HttpRequest& req) override;
void acceptHandover(short& serverSock, IClientStream& client, std::unique_ptr<HttpRequest> srcRequest) override;
};
class HttpHandlerBuilder : public HandlerBuilder {
typedef std::function<HttpResponse(const HttpRequest&)> HandlerFunc;
std::map<HttpRequestMethod, HandlerFunc> mHandlers;
static bool isSafeFilename(const std::string& name, bool allowSlash);
static std::string getMimeType(std::string name);
public:
HttpHandlerBuilder* posted(HandlerFunc h) {
mHandlers.insert(std::pair<HttpRequestMethod, HandlerFunc>(HttpRequestMethod::POST, std::move(h)));
return this;
}
HttpHandlerBuilder* requested(HandlerFunc h) {
mHandlers.insert(std::pair<HttpRequestMethod, HandlerFunc>(HttpRequestMethod::GET, std::move(h)));
return this;
}
HttpHandlerBuilder* serveFile(std::string name) {
return requested([name](const HttpRequest&) {
std::ifstream t(name);
if (t.is_open())
return HttpResponse{200, getMimeType(name), std::string((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>())};
else {
std::cerr << "Could not locate file: " << name << std::endl;
return HttpResponse{404, "text/plain", "The requested file is missing from the server"};
}
});
}
HttpHandlerBuilder* serveFromFolder(std::string dir) {
return requested([dir](const HttpRequest&q) {
std::string fname = q.getPath();
fname = fname.substr(fname.rfind('/')+1);
if (isSafeFilename(fname, false)) {
fname = dir + "/" + fname;
std::ifstream t(fname);
if (t.is_open())
return HttpResponse{200, getMimeType(fname), std::string((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>())};
else
std::cerr << "Could not locate file: " << fname << std::endl;
}
return HttpResponse{404, "text/plain", "The requested file is missing from the server"};
});
}
template<typename T>
HttpHandlerBuilder* posted(T x) { return posted(HandlerFunc(x)); }
template<typename T>
HttpHandlerBuilder* requested(T x) { return requested(HandlerFunc(x)); }
std::unique_ptr<HttpResponse> process(const HttpRequest& req) override {
auto h = mHandlers.find(req.getMethod());
if (h == mHandlers.end())
return std::make_unique<HttpResponse>(405, "text/plain", "405 method not allowed");
else
return std::make_unique<HttpResponse>(h->second(req));
}
};
class HttpServer {
std::vector<std::pair<std::string, std::shared_ptr<HandlerBuilder>>> mHandlers;
std::vector<std::pair<std::regex, std::shared_ptr<HandlerBuilder>>> mReHandlers;
MessageBuilder mDefault404Message, mDefault400Message;
short mSocket = -1;
std::shared_ptr<HttpResponse> processRequest(std::string key, const HttpRequest& req) {
try {
for (auto& x : mHandlers)
if (x.first == key) {
auto res = x.second->process(req);
if (res) return res;
}
for (auto x : mReHandlers)
if (std::regex_match(key, x.first)) {
auto res = x.second->process(req);
if (res) return res;
}
} catch (std::exception& e) {
std::cerr << "Exception while handling request (" << key << "): " << e.what() << std::endl;
return std::make_shared<HttpResponse>(500, "text/plain", "500 exception while processing");
}
return nullptr;
}
public:
HttpServer();
std::shared_ptr<WebsockHandlerBuilder> websocket(std::string path) {
auto h = std::make_shared<WebsockHandlerBuilder>();
mHandlers.insert(mHandlers.begin(), std::pair<std::string, std::shared_ptr<WebsockHandlerBuilder>>(path, h));
return h;
}
std::shared_ptr<HttpHandlerBuilder> when(std::string path) {
auto h = std::make_shared<HttpHandlerBuilder>();
mHandlers.push_back(std::pair<std::string, std::shared_ptr<HttpHandlerBuilder>>(path, h));
return h;
}
std::shared_ptr<HttpHandlerBuilder> whenMatching(std::string path) {
auto h = std::make_shared<HttpHandlerBuilder>();
mReHandlers.push_back(std::pair<std::regex, std::shared_ptr<HttpHandlerBuilder>>(std::regex(path), h));
return h;
}
void startListening(uint16_t port);
void shutdown();
};
#endif
| 31.861053
| 153
| 0.606647
|
kissbeni
|
05a2505a2f5188765ad529de3ee1af874a409105
| 30,222
|
cpp
|
C++
|
tests/PhiCore/unittests/src/type_traits/is_arithmetic.test.cpp
|
AMS21/Phi
|
d62d7235dc5307dd18607ade0f95432ae3a73dfd
|
[
"MIT"
] | 3
|
2020-12-21T13:47:35.000Z
|
2022-03-16T23:53:21.000Z
|
tests/PhiCore/unittests/src/type_traits/is_arithmetic.test.cpp
|
AMS21/Phi
|
d62d7235dc5307dd18607ade0f95432ae3a73dfd
|
[
"MIT"
] | 53
|
2020-08-07T07:46:57.000Z
|
2022-02-12T11:07:08.000Z
|
tests/PhiCore/unittests/src/type_traits/is_arithmetic.test.cpp
|
AMS21/Phi
|
d62d7235dc5307dd18607ade0f95432ae3a73dfd
|
[
"MIT"
] | 1
|
2020-08-19T15:50:02.000Z
|
2020-08-19T15:50:02.000Z
|
#include <phi/test/test_macros.hpp>
#include "test_types.hpp"
#include <phi/compiler_support/char8_t.hpp>
#include <phi/core/boolean.hpp>
#include <phi/core/floating_point.hpp>
#include <phi/core/integer.hpp>
#include <phi/core/nullptr_t.hpp>
#include <phi/core/scope_ptr.hpp>
#include <phi/type_traits/is_arithmetic.hpp>
#include <type_traits>
#include <vector>
template <typename T>
void test_is_arithmetic_impl()
{
STATIC_REQUIRE(phi::is_arithmetic<T>::value);
STATIC_REQUIRE_FALSE(phi::is_not_arithmetic<T>::value);
#if PHI_HAS_FEATURE_VARIABLE_TEMPLATE()
STATIC_REQUIRE(phi::is_arithmetic_v<T>);
STATIC_REQUIRE_FALSE(phi::is_not_arithmetic_v<T>);
#endif
}
template <typename T>
void test_is_arithmetic()
{
test_is_arithmetic_impl<T>();
test_is_arithmetic_impl<const T>();
test_is_arithmetic_impl<volatile T>();
test_is_arithmetic_impl<const volatile T>();
}
template <typename T>
void test_is_not_arithmetic_impl()
{
STATIC_REQUIRE_FALSE(phi::is_arithmetic<T>::value);
STATIC_REQUIRE(phi::is_not_arithmetic<T>::value);
#if PHI_HAS_FEATURE_VARIABLE_TEMPLATE()
STATIC_REQUIRE_FALSE(phi::is_arithmetic_v<T>);
STATIC_REQUIRE(phi::is_not_arithmetic_v<T>);
#endif
}
template <typename T>
void test_is_not_arithmetic()
{
test_is_not_arithmetic_impl<T>();
test_is_not_arithmetic_impl<const T>();
test_is_not_arithmetic_impl<volatile T>();
test_is_not_arithmetic_impl<const volatile T>();
}
TEST_CASE("is_arithmetic")
{
test_is_not_arithmetic<void>();
test_is_not_arithmetic<phi::nullptr_t>();
test_is_arithmetic<bool>();
test_is_arithmetic<char>();
test_is_arithmetic<signed char>();
test_is_arithmetic<unsigned char>();
test_is_arithmetic<short>();
test_is_arithmetic<unsigned short>();
test_is_arithmetic<int>();
test_is_arithmetic<unsigned int>();
test_is_arithmetic<long>();
test_is_arithmetic<unsigned long>();
test_is_arithmetic<long long>();
test_is_arithmetic<unsigned long long>();
test_is_arithmetic<float>();
test_is_arithmetic<double>();
test_is_arithmetic<long double>();
test_is_arithmetic<char8_t>();
test_is_arithmetic<char16_t>();
test_is_arithmetic<char32_t>();
test_is_arithmetic<wchar_t>();
test_is_arithmetic<phi::boolean>();
test_is_arithmetic<phi::integer<signed char>>();
test_is_arithmetic<phi::integer<unsigned char>>();
test_is_arithmetic<phi::integer<short>>();
test_is_arithmetic<phi::integer<unsigned short>>();
test_is_arithmetic<phi::integer<int>>();
test_is_arithmetic<phi::integer<unsigned int>>();
test_is_arithmetic<phi::integer<long>>();
test_is_arithmetic<phi::integer<unsigned long>>();
test_is_arithmetic<phi::integer<long long>>();
test_is_arithmetic<phi::integer<unsigned long long>>();
test_is_arithmetic<phi::floating_point<float>>();
test_is_arithmetic<phi::floating_point<double>>();
test_is_arithmetic<phi::floating_point<long double>>();
test_is_not_arithmetic<std::vector<int>>();
test_is_not_arithmetic<phi::scope_ptr<int>>();
test_is_not_arithmetic<int&>();
test_is_not_arithmetic<const int&>();
test_is_not_arithmetic<volatile int&>();
test_is_not_arithmetic<const volatile int&>();
test_is_not_arithmetic<int&&>();
test_is_not_arithmetic<const int&&>();
test_is_not_arithmetic<volatile int&&>();
test_is_not_arithmetic<const volatile int&&>();
test_is_not_arithmetic<int*>();
test_is_not_arithmetic<const int*>();
test_is_not_arithmetic<volatile int*>();
test_is_not_arithmetic<const volatile int*>();
test_is_not_arithmetic<int**>();
test_is_not_arithmetic<const int**>();
test_is_not_arithmetic<volatile int**>();
test_is_not_arithmetic<const volatile int**>();
test_is_not_arithmetic<int*&>();
test_is_not_arithmetic<const int*&>();
test_is_not_arithmetic<volatile int*&>();
test_is_not_arithmetic<const volatile int*&>();
test_is_not_arithmetic<int*&&>();
test_is_not_arithmetic<const int*&&>();
test_is_not_arithmetic<volatile int*&&>();
test_is_not_arithmetic<const volatile int*&&>();
test_is_not_arithmetic<void*>();
test_is_not_arithmetic<char[3]>();
test_is_not_arithmetic<char[]>();
test_is_not_arithmetic<char[3]>();
test_is_not_arithmetic<char[]>();
test_is_not_arithmetic<char* [3]>();
test_is_not_arithmetic<char*[]>();
test_is_not_arithmetic<int(*)[3]>();
test_is_not_arithmetic<int(*)[]>();
test_is_not_arithmetic<int(&)[3]>();
test_is_not_arithmetic<int(&)[]>();
test_is_not_arithmetic<int(&&)[3]>();
test_is_not_arithmetic<int(&&)[]>();
test_is_not_arithmetic<char[3][2]>();
test_is_not_arithmetic<char[][2]>();
test_is_not_arithmetic<char* [3][2]>();
test_is_not_arithmetic<char*[][2]>();
test_is_not_arithmetic<int(*)[3][2]>();
test_is_not_arithmetic<int(*)[][2]>();
test_is_not_arithmetic<int(&)[3][2]>();
test_is_not_arithmetic<int(&)[][2]>();
test_is_not_arithmetic<int(&&)[3][2]>();
test_is_not_arithmetic<int(&&)[][2]>();
test_is_not_arithmetic<Class>();
test_is_not_arithmetic<Class[]>();
test_is_not_arithmetic<Class[2]>();
test_is_not_arithmetic<Template<void>>();
test_is_not_arithmetic<Template<int>>();
test_is_not_arithmetic<Template<Class>>();
test_is_not_arithmetic<Template<incomplete_type>>();
test_is_not_arithmetic<VariadicTemplate<>>();
test_is_not_arithmetic<VariadicTemplate<void>>();
test_is_not_arithmetic<VariadicTemplate<int>>();
test_is_not_arithmetic<VariadicTemplate<Class>>();
test_is_not_arithmetic<VariadicTemplate<incomplete_type>>();
test_is_not_arithmetic<VariadicTemplate<int, void, Class, volatile char[]>>();
test_is_not_arithmetic<PublicDerviedFromTemplate<Base>>();
test_is_not_arithmetic<PublicDerviedFromTemplate<Derived>>();
test_is_not_arithmetic<PublicDerviedFromTemplate<Class>>();
test_is_not_arithmetic<PrivateDerviedFromTemplate<Base>>();
test_is_not_arithmetic<PrivateDerviedFromTemplate<Derived>>();
test_is_not_arithmetic<PrivateDerviedFromTemplate<Class>>();
test_is_not_arithmetic<ProtectedDerviedFromTemplate<Base>>();
test_is_not_arithmetic<ProtectedDerviedFromTemplate<Derived>>();
test_is_not_arithmetic<ProtectedDerviedFromTemplate<Class>>();
test_is_not_arithmetic<Union>();
test_is_not_arithmetic<NonEmptyUnion>();
test_is_not_arithmetic<Empty>();
test_is_not_arithmetic<NotEmpty>();
test_is_not_arithmetic<bit_zero>();
test_is_not_arithmetic<bit_one>();
test_is_not_arithmetic<Base>();
test_is_not_arithmetic<Derived>();
test_is_not_arithmetic<Abstract>();
test_is_not_arithmetic<PublicAbstract>();
test_is_not_arithmetic<PrivateAbstract>();
test_is_not_arithmetic<ProtectedAbstract>();
test_is_not_arithmetic<AbstractTemplate<int>>();
test_is_not_arithmetic<AbstractTemplate<double>>();
test_is_not_arithmetic<AbstractTemplate<Class>>();
test_is_not_arithmetic<AbstractTemplate<incomplete_type>>();
test_is_not_arithmetic<Final>();
test_is_not_arithmetic<PublicDestructor>();
test_is_not_arithmetic<ProtectedDestructor>();
test_is_not_arithmetic<PrivateDestructor>();
test_is_not_arithmetic<VirtualPublicDestructor>();
test_is_not_arithmetic<VirtualProtectedDestructor>();
test_is_not_arithmetic<VirtualPrivateDestructor>();
test_is_not_arithmetic<PurePublicDestructor>();
test_is_not_arithmetic<PureProtectedDestructor>();
test_is_not_arithmetic<PurePrivateDestructor>();
test_is_not_arithmetic<DeletedPublicDestructor>();
test_is_not_arithmetic<DeletedProtectedDestructor>();
test_is_not_arithmetic<DeletedPrivateDestructor>();
test_is_not_arithmetic<DeletedVirtualPublicDestructor>();
test_is_not_arithmetic<DeletedVirtualProtectedDestructor>();
test_is_not_arithmetic<DeletedVirtualPrivateDestructor>();
test_is_not_arithmetic<Enum>();
test_is_not_arithmetic<EnumSigned>();
test_is_not_arithmetic<EnumUnsigned>();
test_is_not_arithmetic<EnumClass>();
test_is_not_arithmetic<EnumStruct>();
test_is_not_arithmetic<Function>();
test_is_not_arithmetic<FunctionPtr>();
test_is_not_arithmetic<MemberObjectPtr>();
test_is_not_arithmetic<MemberFunctionPtr>();
test_is_not_arithmetic<incomplete_type>();
test_is_not_arithmetic<IncompleteTemplate<void>>();
test_is_not_arithmetic<IncompleteTemplate<int>>();
test_is_not_arithmetic<IncompleteTemplate<Class>>();
test_is_not_arithmetic<IncompleteTemplate<incomplete_type>>();
test_is_not_arithmetic<IncompleteVariadicTemplate<>>();
test_is_not_arithmetic<IncompleteVariadicTemplate<void>>();
test_is_not_arithmetic<IncompleteVariadicTemplate<int>>();
test_is_not_arithmetic<IncompleteVariadicTemplate<Class>>();
test_is_not_arithmetic<IncompleteVariadicTemplate<incomplete_type>>();
test_is_not_arithmetic<IncompleteVariadicTemplate<int, void, Class, volatile char[]>>();
test_is_not_arithmetic<int Class::*>();
test_is_not_arithmetic<float Class::*>();
test_is_not_arithmetic<void * Class::*>();
test_is_not_arithmetic<int * Class::*>();
test_is_not_arithmetic<int Class::*&>();
test_is_not_arithmetic<float Class::*&>();
test_is_not_arithmetic<void * Class::*&>();
test_is_not_arithmetic<int * Class::*&>();
test_is_not_arithmetic<int Class::*&&>();
test_is_not_arithmetic<float Class::*&&>();
test_is_not_arithmetic<void * Class::*&&>();
test_is_not_arithmetic<int * Class::*&&>();
test_is_not_arithmetic<int Class::*const>();
test_is_not_arithmetic<float Class::*const>();
test_is_not_arithmetic<void * Class::*const>();
test_is_not_arithmetic<int Class::*const&>();
test_is_not_arithmetic<float Class::*const&>();
test_is_not_arithmetic<void * Class::*const&>();
test_is_not_arithmetic<int Class::*const&&>();
test_is_not_arithmetic<float Class::*const&&>();
test_is_not_arithmetic<void * Class::*const&&>();
test_is_not_arithmetic<int Class::*volatile>();
test_is_not_arithmetic<float Class::*volatile>();
test_is_not_arithmetic<void * Class::*volatile>();
test_is_not_arithmetic<int Class::*volatile&>();
test_is_not_arithmetic<float Class::*volatile&>();
test_is_not_arithmetic<void * Class::*volatile&>();
test_is_not_arithmetic<int Class::*volatile&&>();
test_is_not_arithmetic<float Class::*volatile&&>();
test_is_not_arithmetic<void * Class::*volatile&&>();
test_is_not_arithmetic<int Class::*const volatile>();
test_is_not_arithmetic<float Class::*const volatile>();
test_is_not_arithmetic<void * Class::*const volatile>();
test_is_not_arithmetic<int Class::*const volatile&>();
test_is_not_arithmetic<float Class::*const volatile&>();
test_is_not_arithmetic<void * Class::*const volatile&>();
test_is_not_arithmetic<int Class::*const volatile&&>();
test_is_not_arithmetic<float Class::*const volatile&&>();
test_is_not_arithmetic<void * Class::*const volatile&&>();
test_is_not_arithmetic<NonCopyable>();
test_is_not_arithmetic<NonMoveable>();
test_is_not_arithmetic<NonConstructible>();
test_is_not_arithmetic<Tracked>();
test_is_not_arithmetic<TrapConstructible>();
test_is_not_arithmetic<TrapImplicitConversion>();
test_is_not_arithmetic<TrapComma>();
test_is_not_arithmetic<TrapCall>();
test_is_not_arithmetic<TrapSelfAssign>();
test_is_not_arithmetic<TrapDeref>();
test_is_not_arithmetic<TrapArraySubscript>();
test_is_not_arithmetic<void()>();
test_is_not_arithmetic<void()&>();
test_is_not_arithmetic<void() &&>();
test_is_not_arithmetic<void() const>();
test_is_not_arithmetic<void() const&>();
test_is_not_arithmetic<void() const&&>();
test_is_not_arithmetic<void() volatile>();
test_is_not_arithmetic<void() volatile&>();
test_is_not_arithmetic<void() volatile&&>();
test_is_not_arithmetic<void() const volatile>();
test_is_not_arithmetic<void() const volatile&>();
test_is_not_arithmetic<void() const volatile&&>();
test_is_not_arithmetic<void() noexcept>();
test_is_not_arithmetic<void()& noexcept>();
test_is_not_arithmetic<void()&& noexcept>();
test_is_not_arithmetic<void() const noexcept>();
test_is_not_arithmetic<void() const& noexcept>();
test_is_not_arithmetic<void() const&& noexcept>();
test_is_not_arithmetic<void() volatile noexcept>();
test_is_not_arithmetic<void() volatile& noexcept>();
test_is_not_arithmetic<void() volatile&& noexcept>();
test_is_not_arithmetic<void() const volatile noexcept>();
test_is_not_arithmetic<void() const volatile& noexcept>();
test_is_not_arithmetic<void() const volatile&& noexcept>();
test_is_not_arithmetic<void(int)>();
test_is_not_arithmetic<void(int)&>();
test_is_not_arithmetic<void(int) &&>();
test_is_not_arithmetic<void(int) const>();
test_is_not_arithmetic<void(int) const&>();
test_is_not_arithmetic<void(int) const&&>();
test_is_not_arithmetic<void(int) volatile>();
test_is_not_arithmetic<void(int) volatile&>();
test_is_not_arithmetic<void(int) volatile&&>();
test_is_not_arithmetic<void(int) const volatile>();
test_is_not_arithmetic<void(int) const volatile&>();
test_is_not_arithmetic<void(int) const volatile&&>();
test_is_not_arithmetic<void(int) noexcept>();
test_is_not_arithmetic<void(int)& noexcept>();
test_is_not_arithmetic<void(int)&& noexcept>();
test_is_not_arithmetic<void(int) const noexcept>();
test_is_not_arithmetic<void(int) const& noexcept>();
test_is_not_arithmetic<void(int) const&& noexcept>();
test_is_not_arithmetic<void(int) volatile noexcept>();
test_is_not_arithmetic<void(int) volatile& noexcept>();
test_is_not_arithmetic<void(int) volatile&& noexcept>();
test_is_not_arithmetic<void(int) const volatile noexcept>();
test_is_not_arithmetic<void(int) const volatile& noexcept>();
test_is_not_arithmetic<void(int) const volatile&& noexcept>();
test_is_not_arithmetic<void(...)>();
test_is_not_arithmetic<void(...)&>();
test_is_not_arithmetic<void(...) &&>();
test_is_not_arithmetic<void(...) const>();
test_is_not_arithmetic<void(...) const&>();
test_is_not_arithmetic<void(...) const&&>();
test_is_not_arithmetic<void(...) volatile>();
test_is_not_arithmetic<void(...) volatile&>();
test_is_not_arithmetic<void(...) volatile&&>();
test_is_not_arithmetic<void(...) const volatile>();
test_is_not_arithmetic<void(...) const volatile&>();
test_is_not_arithmetic<void(...) const volatile&&>();
test_is_not_arithmetic<void(...) noexcept>();
test_is_not_arithmetic<void(...)& noexcept>();
test_is_not_arithmetic<void(...)&& noexcept>();
test_is_not_arithmetic<void(...) const noexcept>();
test_is_not_arithmetic<void(...) const& noexcept>();
test_is_not_arithmetic<void(...) const&& noexcept>();
test_is_not_arithmetic<void(...) volatile noexcept>();
test_is_not_arithmetic<void(...) volatile& noexcept>();
test_is_not_arithmetic<void(...) volatile&& noexcept>();
test_is_not_arithmetic<void(...) const volatile noexcept>();
test_is_not_arithmetic<void(...) const volatile& noexcept>();
test_is_not_arithmetic<void(...) const volatile&& noexcept>();
test_is_not_arithmetic<void(int, ...)>();
test_is_not_arithmetic<void(int, ...)&>();
test_is_not_arithmetic<void(int, ...) &&>();
test_is_not_arithmetic<void(int, ...) const>();
test_is_not_arithmetic<void(int, ...) const&>();
test_is_not_arithmetic<void(int, ...) const&&>();
test_is_not_arithmetic<void(int, ...) volatile>();
test_is_not_arithmetic<void(int, ...) volatile&>();
test_is_not_arithmetic<void(int, ...) volatile&&>();
test_is_not_arithmetic<void(int, ...) const volatile>();
test_is_not_arithmetic<void(int, ...) const volatile&>();
test_is_not_arithmetic<void(int, ...) const volatile&&>();
test_is_not_arithmetic<void(int, ...) noexcept>();
test_is_not_arithmetic<void(int, ...)& noexcept>();
test_is_not_arithmetic<void(int, ...)&& noexcept>();
test_is_not_arithmetic<void(int, ...) const noexcept>();
test_is_not_arithmetic<void(int, ...) const& noexcept>();
test_is_not_arithmetic<void(int, ...) const&& noexcept>();
test_is_not_arithmetic<void(int, ...) volatile noexcept>();
test_is_not_arithmetic<void(int, ...) volatile& noexcept>();
test_is_not_arithmetic<void(int, ...) volatile&& noexcept>();
test_is_not_arithmetic<void(int, ...) const volatile noexcept>();
test_is_not_arithmetic<void(int, ...) const volatile& noexcept>();
test_is_not_arithmetic<void(int, ...) const volatile&& noexcept>();
test_is_not_arithmetic<int()>();
test_is_not_arithmetic<int()&>();
test_is_not_arithmetic<int() &&>();
test_is_not_arithmetic<int() const>();
test_is_not_arithmetic<int() const&>();
test_is_not_arithmetic<int() const&&>();
test_is_not_arithmetic<int() volatile>();
test_is_not_arithmetic<int() volatile&>();
test_is_not_arithmetic<int() volatile&&>();
test_is_not_arithmetic<int() const volatile>();
test_is_not_arithmetic<int() const volatile&>();
test_is_not_arithmetic<int() const volatile&&>();
test_is_not_arithmetic<int() noexcept>();
test_is_not_arithmetic<int()& noexcept>();
test_is_not_arithmetic<int()&& noexcept>();
test_is_not_arithmetic<int() const noexcept>();
test_is_not_arithmetic<int() const& noexcept>();
test_is_not_arithmetic<int() const&& noexcept>();
test_is_not_arithmetic<int() volatile noexcept>();
test_is_not_arithmetic<int() volatile& noexcept>();
test_is_not_arithmetic<int() volatile&& noexcept>();
test_is_not_arithmetic<int() const volatile noexcept>();
test_is_not_arithmetic<int() const volatile& noexcept>();
test_is_not_arithmetic<int() const volatile&& noexcept>();
test_is_not_arithmetic<int(int)>();
test_is_not_arithmetic<int(int)&>();
test_is_not_arithmetic<int(int) &&>();
test_is_not_arithmetic<int(int) const>();
test_is_not_arithmetic<int(int) const&>();
test_is_not_arithmetic<int(int) const&&>();
test_is_not_arithmetic<int(int) volatile>();
test_is_not_arithmetic<int(int) volatile&>();
test_is_not_arithmetic<int(int) volatile&&>();
test_is_not_arithmetic<int(int) const volatile>();
test_is_not_arithmetic<int(int) const volatile&>();
test_is_not_arithmetic<int(int) const volatile&&>();
test_is_not_arithmetic<int(int) noexcept>();
test_is_not_arithmetic<int(int)& noexcept>();
test_is_not_arithmetic<int(int)&& noexcept>();
test_is_not_arithmetic<int(int) const noexcept>();
test_is_not_arithmetic<int(int) const& noexcept>();
test_is_not_arithmetic<int(int) const&& noexcept>();
test_is_not_arithmetic<int(int) volatile noexcept>();
test_is_not_arithmetic<int(int) volatile& noexcept>();
test_is_not_arithmetic<int(int) volatile&& noexcept>();
test_is_not_arithmetic<int(int) const volatile noexcept>();
test_is_not_arithmetic<int(int) const volatile& noexcept>();
test_is_not_arithmetic<int(int) const volatile&& noexcept>();
test_is_not_arithmetic<int(...)>();
test_is_not_arithmetic<int(...)&>();
test_is_not_arithmetic<int(...) &&>();
test_is_not_arithmetic<int(...) const>();
test_is_not_arithmetic<int(...) const&>();
test_is_not_arithmetic<int(...) const&&>();
test_is_not_arithmetic<int(...) volatile>();
test_is_not_arithmetic<int(...) volatile&>();
test_is_not_arithmetic<int(...) volatile&&>();
test_is_not_arithmetic<int(...) const volatile>();
test_is_not_arithmetic<int(...) const volatile&>();
test_is_not_arithmetic<int(...) const volatile&&>();
test_is_not_arithmetic<int(...) noexcept>();
test_is_not_arithmetic<int(...)& noexcept>();
test_is_not_arithmetic<int(...)&& noexcept>();
test_is_not_arithmetic<int(...) const noexcept>();
test_is_not_arithmetic<int(...) const& noexcept>();
test_is_not_arithmetic<int(...) const&& noexcept>();
test_is_not_arithmetic<int(...) volatile noexcept>();
test_is_not_arithmetic<int(...) volatile& noexcept>();
test_is_not_arithmetic<int(...) volatile&& noexcept>();
test_is_not_arithmetic<int(...) const volatile noexcept>();
test_is_not_arithmetic<int(...) const volatile& noexcept>();
test_is_not_arithmetic<int(...) const volatile&& noexcept>();
test_is_not_arithmetic<int(int, ...)>();
test_is_not_arithmetic<int(int, ...)&>();
test_is_not_arithmetic<int(int, ...) &&>();
test_is_not_arithmetic<int(int, ...) const>();
test_is_not_arithmetic<int(int, ...) const&>();
test_is_not_arithmetic<int(int, ...) const&&>();
test_is_not_arithmetic<int(int, ...) volatile>();
test_is_not_arithmetic<int(int, ...) volatile&>();
test_is_not_arithmetic<int(int, ...) volatile&&>();
test_is_not_arithmetic<int(int, ...) const volatile>();
test_is_not_arithmetic<int(int, ...) const volatile&>();
test_is_not_arithmetic<int(int, ...) const volatile&&>();
test_is_not_arithmetic<int(int, ...) noexcept>();
test_is_not_arithmetic<int(int, ...)& noexcept>();
test_is_not_arithmetic<int(int, ...)&& noexcept>();
test_is_not_arithmetic<int(int, ...) const noexcept>();
test_is_not_arithmetic<int(int, ...) const& noexcept>();
test_is_not_arithmetic<int(int, ...) const&& noexcept>();
test_is_not_arithmetic<int(int, ...) volatile noexcept>();
test_is_not_arithmetic<int(int, ...) volatile& noexcept>();
test_is_not_arithmetic<int(int, ...) volatile&& noexcept>();
test_is_not_arithmetic<int(int, ...) const volatile noexcept>();
test_is_not_arithmetic<int(int, ...) const volatile& noexcept>();
test_is_not_arithmetic<int(int, ...) const volatile&& noexcept>();
test_is_not_arithmetic<void (*)()>();
test_is_not_arithmetic<void (*)() noexcept>();
test_is_not_arithmetic<void (*)(int)>();
test_is_not_arithmetic<void (*)(int) noexcept>();
test_is_not_arithmetic<void (*)(...)>();
test_is_not_arithmetic<void (*)(...) noexcept>();
test_is_not_arithmetic<void (*)(int, ...)>();
test_is_not_arithmetic<void (*)(int, ...) noexcept>();
test_is_not_arithmetic<int (*)()>();
test_is_not_arithmetic<int (*)() noexcept>();
test_is_not_arithmetic<int (*)(int)>();
test_is_not_arithmetic<int (*)(int) noexcept>();
test_is_not_arithmetic<int (*)(...)>();
test_is_not_arithmetic<int (*)(...) noexcept>();
test_is_not_arithmetic<int (*)(int, ...)>();
test_is_not_arithmetic<int (*)(int, ...) noexcept>();
test_is_not_arithmetic<void (&)()>();
test_is_not_arithmetic<void (&)() noexcept>();
test_is_not_arithmetic<void (&)(int)>();
test_is_not_arithmetic<void (&)(int) noexcept>();
test_is_not_arithmetic<void (&)(...)>();
test_is_not_arithmetic<void (&)(...) noexcept>();
test_is_not_arithmetic<void (&)(int, ...)>();
test_is_not_arithmetic<void (&)(int, ...) noexcept>();
test_is_not_arithmetic<int (&)()>();
test_is_not_arithmetic<int (&)() noexcept>();
test_is_not_arithmetic<int (&)(int)>();
test_is_not_arithmetic<int (&)(int) noexcept>();
test_is_not_arithmetic<int (&)(...)>();
test_is_not_arithmetic<int (&)(...) noexcept>();
test_is_not_arithmetic<int (&)(int, ...)>();
test_is_not_arithmetic<int (&)(int, ...) noexcept>();
test_is_not_arithmetic<void(&&)()>();
test_is_not_arithmetic<void(&&)() noexcept>();
test_is_not_arithmetic<void(&&)(int)>();
test_is_not_arithmetic<void(&&)(int) noexcept>();
test_is_not_arithmetic<void(&&)(...)>();
test_is_not_arithmetic<void(&&)(...) noexcept>();
test_is_not_arithmetic<void(&&)(int, ...)>();
test_is_not_arithmetic<void(&&)(int, ...) noexcept>();
test_is_not_arithmetic<int(&&)()>();
test_is_not_arithmetic<int(&&)() noexcept>();
test_is_not_arithmetic<int(&&)(int)>();
test_is_not_arithmetic<int(&&)(int) noexcept>();
test_is_not_arithmetic<int(&&)(...)>();
test_is_not_arithmetic<int(&&)(...) noexcept>();
test_is_not_arithmetic<int(&&)(int, ...)>();
test_is_not_arithmetic<int(&&)(int, ...) noexcept>();
test_is_not_arithmetic<void (Class::*)()>();
test_is_not_arithmetic<void (Class::*)()&>();
test_is_not_arithmetic<void (Class::*)() &&>();
test_is_not_arithmetic<void (Class::*)() const>();
test_is_not_arithmetic<void (Class::*)() const&>();
test_is_not_arithmetic<void (Class::*)() const&&>();
test_is_not_arithmetic<void (Class::*)() noexcept>();
test_is_not_arithmetic<void (Class::*)()& noexcept>();
test_is_not_arithmetic<void (Class::*)()&& noexcept>();
test_is_not_arithmetic<void (Class::*)() const noexcept>();
test_is_not_arithmetic<void (Class::*)() const& noexcept>();
test_is_not_arithmetic<void (Class::*)() const&& noexcept>();
test_is_not_arithmetic<void (Class::*)(int)>();
test_is_not_arithmetic<void (Class::*)(int)&>();
test_is_not_arithmetic<void (Class::*)(int) &&>();
test_is_not_arithmetic<void (Class::*)(int) const>();
test_is_not_arithmetic<void (Class::*)(int) const&>();
test_is_not_arithmetic<void (Class::*)(int) const&&>();
test_is_not_arithmetic<void (Class::*)(int) noexcept>();
test_is_not_arithmetic<void (Class::*)(int)& noexcept>();
test_is_not_arithmetic<void (Class::*)(int)&& noexcept>();
test_is_not_arithmetic<void (Class::*)(int) const noexcept>();
test_is_not_arithmetic<void (Class::*)(int) const& noexcept>();
test_is_not_arithmetic<void (Class::*)(int) const&& noexcept>();
test_is_not_arithmetic<void (Class::*)(...)>();
test_is_not_arithmetic<void (Class::*)(...)&>();
test_is_not_arithmetic<void (Class::*)(...) &&>();
test_is_not_arithmetic<void (Class::*)(...) const>();
test_is_not_arithmetic<void (Class::*)(...) const&>();
test_is_not_arithmetic<void (Class::*)(...) const&&>();
test_is_not_arithmetic<void (Class::*)(...) noexcept>();
test_is_not_arithmetic<void (Class::*)(...)& noexcept>();
test_is_not_arithmetic<void (Class::*)(...)&& noexcept>();
test_is_not_arithmetic<void (Class::*)(...) const noexcept>();
test_is_not_arithmetic<void (Class::*)(...) const& noexcept>();
test_is_not_arithmetic<void (Class::*)(...) const&& noexcept>();
test_is_not_arithmetic<void (Class::*)(int, ...)>();
test_is_not_arithmetic<void (Class::*)(int, ...)&>();
test_is_not_arithmetic<void (Class::*)(int, ...) &&>();
test_is_not_arithmetic<void (Class::*)(int, ...) const>();
test_is_not_arithmetic<void (Class::*)(int, ...) const&>();
test_is_not_arithmetic<void (Class::*)(int, ...) const&&>();
test_is_not_arithmetic<void (Class::*)(int, ...) noexcept>();
test_is_not_arithmetic<void (Class::*)(int, ...)& noexcept>();
test_is_not_arithmetic<void (Class::*)(int, ...)&& noexcept>();
test_is_not_arithmetic<void (Class::*)(int, ...) const noexcept>();
test_is_not_arithmetic<void (Class::*)(int, ...) const& noexcept>();
test_is_not_arithmetic<void (Class::*)(int, ...) const&& noexcept>();
test_is_not_arithmetic<int (Class::*)()>();
test_is_not_arithmetic<int (Class::*)()&>();
test_is_not_arithmetic<int (Class::*)() &&>();
test_is_not_arithmetic<int (Class::*)() const>();
test_is_not_arithmetic<int (Class::*)() const&>();
test_is_not_arithmetic<int (Class::*)() const&&>();
test_is_not_arithmetic<int (Class::*)() noexcept>();
test_is_not_arithmetic<int (Class::*)()& noexcept>();
test_is_not_arithmetic<int (Class::*)()&& noexcept>();
test_is_not_arithmetic<int (Class::*)() const noexcept>();
test_is_not_arithmetic<int (Class::*)() const& noexcept>();
test_is_not_arithmetic<int (Class::*)() const&& noexcept>();
test_is_not_arithmetic<int (Class::*)(int)>();
test_is_not_arithmetic<int (Class::*)(int)&>();
test_is_not_arithmetic<int (Class::*)(int) &&>();
test_is_not_arithmetic<int (Class::*)(int) const>();
test_is_not_arithmetic<int (Class::*)(int) const&>();
test_is_not_arithmetic<int (Class::*)(int) const&&>();
test_is_not_arithmetic<int (Class::*)(int) noexcept>();
test_is_not_arithmetic<int (Class::*)(int)& noexcept>();
test_is_not_arithmetic<int (Class::*)(int)&& noexcept>();
test_is_not_arithmetic<int (Class::*)(int) const noexcept>();
test_is_not_arithmetic<int (Class::*)(int) const& noexcept>();
test_is_not_arithmetic<int (Class::*)(int) const&& noexcept>();
test_is_not_arithmetic<int (Class::*)(...)>();
test_is_not_arithmetic<int (Class::*)(...)&>();
test_is_not_arithmetic<int (Class::*)(...) &&>();
test_is_not_arithmetic<int (Class::*)(...) const>();
test_is_not_arithmetic<int (Class::*)(...) const&>();
test_is_not_arithmetic<int (Class::*)(...) const&&>();
test_is_not_arithmetic<int (Class::*)(...) noexcept>();
test_is_not_arithmetic<int (Class::*)(...)& noexcept>();
test_is_not_arithmetic<int (Class::*)(...)&& noexcept>();
test_is_not_arithmetic<int (Class::*)(...) const noexcept>();
test_is_not_arithmetic<int (Class::*)(...) const& noexcept>();
test_is_not_arithmetic<int (Class::*)(...) const&& noexcept>();
test_is_not_arithmetic<int (Class::*)(int, ...)>();
test_is_not_arithmetic<int (Class::*)(int, ...)&>();
test_is_not_arithmetic<int (Class::*)(int, ...) &&>();
test_is_not_arithmetic<int (Class::*)(int, ...) const>();
test_is_not_arithmetic<int (Class::*)(int, ...) const&>();
test_is_not_arithmetic<int (Class::*)(int, ...) const&&>();
test_is_not_arithmetic<int (Class::*)(int, ...) noexcept>();
test_is_not_arithmetic<int (Class::*)(int, ...)& noexcept>();
test_is_not_arithmetic<int (Class::*)(int, ...)&& noexcept>();
test_is_not_arithmetic<int (Class::*)(int, ...) const noexcept>();
test_is_not_arithmetic<int (Class::*)(int, ...) const& noexcept>();
test_is_not_arithmetic<int (Class::*)(int, ...) const&& noexcept>();
}
| 46.783282
| 92
| 0.694097
|
AMS21
|
05a3bd736ec53c47ded063d6e84f7be75056e38e
| 2,755
|
cpp
|
C++
|
platform-windows/source/Bitmap.cpp
|
mtezych/cpp
|
05c1b85eb89117a9b406f3f32470367937331614
|
[
"BSD-3-Clause"
] | null | null | null |
platform-windows/source/Bitmap.cpp
|
mtezych/cpp
|
05c1b85eb89117a9b406f3f32470367937331614
|
[
"BSD-3-Clause"
] | null | null | null |
platform-windows/source/Bitmap.cpp
|
mtezych/cpp
|
05c1b85eb89117a9b406f3f32470367937331614
|
[
"BSD-3-Clause"
] | 2
|
2019-12-21T00:31:17.000Z
|
2021-07-14T23:16:23.000Z
|
#include <windows/Bitmap.h>
#include <cassert>
#include <cstring>
namespace windows
{
namespace
{
template <typename ObjectHandleType>
struct ObjectInfo;
template <>
struct ObjectInfo<HBITMAP > { using type = BITMAP; };
template <>
struct ObjectInfo<HPALETTE> { using type = WORD; };
template <>
struct ObjectInfo<HBRUSH > { using type = LOGBRUSH; };
template <>
struct ObjectInfo<HFONT > { using type = LOGFONT; };
template <typename ObjectHandleType>
using ObjectInfoType = typename ObjectInfo<ObjectHandleType>::type;
template <typename ObjectHandleType>
auto GetObjectInfo (ObjectHandleType objectHandle)
{
auto objectInfo = ObjectInfoType<ObjectHandleType> { };
const auto result = GetObject
(
objectHandle, sizeof(objectInfo), &objectInfo
);
assert(result > 0);
return objectInfo;
}
}
Bitmap::Bitmap (const util::uvec2& size)
:
bitmapHandle { nullptr },
deviceContextHandle { nullptr }
{
deviceContextHandle = CreateCompatibleDC(nullptr);
assert(deviceContextHandle != nullptr);
const auto bitmapInfo = BITMAPINFO
{
BITMAPINFOHEADER
{
sizeof(BITMAPINFOHEADER), // size
+static_cast<LONG>(size.width), // width
-static_cast<LONG>(size.height), // height
1, // planes
32, // bit count
BI_RGB, // compression
}
};
void* bitValues = nullptr;
bitmapHandle = CreateDIBSection
(
deviceContextHandle,
&bitmapInfo,
DIB_RGB_COLORS,
&bitValues, // pointer to bitmap's storage
nullptr, 0 // allocate memory for the DIB
);
assert((bitmapHandle != nullptr) && (bitValues != nullptr));
const auto pixelSize = bitmapInfo.bmiHeader.biBitCount / CHAR_BIT;
std::memset(bitValues, 0xAA, size.width * size.height * pixelSize);
}
Bitmap::~Bitmap ()
{
auto result = DeleteObject(bitmapHandle);
assert(result != 0);
result = DeleteDC(deviceContextHandle);
assert(result != 0);
}
Bitmap::Bitmap (Bitmap&& bitmap)
:
bitmapHandle { bitmap.bitmapHandle },
deviceContextHandle { bitmap.deviceContextHandle }
{
bitmap.bitmapHandle = nullptr;
bitmap.deviceContextHandle = nullptr;
}
Bitmap& Bitmap::operator = (Bitmap&& bitmap)
{
bitmapHandle = bitmap.bitmapHandle;
deviceContextHandle = bitmap.deviceContextHandle;
bitmap.bitmapHandle = nullptr;
bitmap.deviceContextHandle = nullptr;
return *this;
}
util::uvec2 Bitmap::Size () const
{
const auto bitmapInfo = BITMAP { GetObjectInfo(bitmapHandle) };
return util::uvec2
{
static_cast<unsigned int>(bitmapInfo.bmWidth),
static_cast<unsigned int>(bitmapInfo.bmHeight),
};
}
}
| 23.347458
| 69
| 0.661706
|
mtezych
|
05a5f467fe10e76c637a76d16b1c30130e64f884
| 4,990
|
cpp
|
C++
|
code/fiber/Manager.cpp
|
MarqusJonsson/NomadTasks
|
91fd52432c96ed3945761ceef45eb0a6e2f0ddac
|
[
"MIT"
] | 5
|
2020-06-22T06:32:59.000Z
|
2022-01-22T00:35:02.000Z
|
code/fiber/Manager.cpp
|
MarqusJonsson/NomadTasks
|
91fd52432c96ed3945761ceef45eb0a6e2f0ddac
|
[
"MIT"
] | null | null | null |
code/fiber/Manager.cpp
|
MarqusJonsson/NomadTasks
|
91fd52432c96ed3945761ceef45eb0a6e2f0ddac
|
[
"MIT"
] | 3
|
2020-01-26T17:25:59.000Z
|
2020-05-13T15:12:38.000Z
|
/*
* All or portions of this file Copyright (c) NOMAD Group<nomad-group.net> or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include <fiber/Manager.h>
#include <fiber/Thread.h>
#include <fiber/Fiber.h>
#include <thread>
nmd::fiber::Manager::Manager(const ManagerOptions& options) :
_numThreads(options.NumThreads + 1 /* IO */),
_hasThreadAffinity(options.ThreadAffinity),
_autoSpawnThreads(options.AutoSpawnThreads),
_numFibers(options.NumFibers),
_highPriorityQueue(options.HighPriorityQueueSize),
_normalPriorityQueue(options.NormalPriorityQueueSize),
_lowPriorityQueue(options.LowPriorityQueueSize),
_ioQueue(options.IOQueueSize),
_shutdownAfterMain(options.ShutdownAfterMainCallback)
{}
nmd::fiber::Manager::~Manager()
{
delete[] _threads;
delete[] _fibers;
delete[] _idleFibers;
}
nmd::fiber::Thread *nmd::fiber::Manager::GetThread(uint8_t idx)
{
assert(idx < _numThreads);
return &_threads[idx];
}
bool nmd::fiber::Manager::SpawnThread(uint8_t idx)
{
return GetThread(idx)->Spawn(ThreadCallback_Worker, this);
}
bool nmd::fiber::Manager::SetupThread(uint8_t idx)
{
auto thread = GetThread(idx);
if (thread->HasSpawned()) {
return false;
}
auto tls = GetCurrentTLS();
if (tls) {
return false;
}
thread->FromCurrentThread();
tls = GetCurrentTLS();
assert(tls->_threadIndex == idx);
tls->_threadFiber.FromCurrentThread();
tls->_currentFiberIndex = FindFreeFiber();
return true;
}
nmd::fiber::Manager::ReturnCode nmd::fiber::Manager::Run(Main_t main)
{
if (_threads || _fibers) {
return ReturnCode::AlreadyInitialized;
}
_threads = new Thread[_numThreads];
// Current (Main) Thread
auto mainThread = &_threads[0];
mainThread->FromCurrentThread();
TLS *mainThreadTLS = mainThread->GetTLS();
mainThreadTLS->_threadFiber.FromCurrentThread();
if (main) {
if (_hasThreadAffinity) {
mainThread->SetAffinity(1);
}
}
// Create Fibers
// This has to be done after Thread is converted to Fiber!
if (_numFibers == 0) {
return ReturnCode::InvalidNumFibers;
}
_fibers = new Fiber[_numFibers];
_idleFibers = new std::atomic_bool[_numFibers];
for (uint16_t i = 0; i < _numFibers; i++) {
_fibers[i].SetCallback(FiberCallback_Worker);
_idleFibers[i].store(true, std::memory_order_relaxed);
}
// Thread Affinity
if (_hasThreadAffinity && (_numThreads == 0 || _numThreads > std::thread::hardware_concurrency() + 1)) {
return ReturnCode::ErrorThreadAffinity;
}
// Spawn Threads
for (uint8_t i = 0; i < _numThreads; i++) {
auto itTls = _threads[i].GetTLS();
itTls->_threadIndex = i;
if (i > 0) // 0 is Main Thread
{
if (i == (_numThreads - 1)) {
// IO Thread
itTls->_isIO = true;
} else {
itTls->_hasAffinity = _hasThreadAffinity;
}
if (_autoSpawnThreads && !SpawnThread(i)) {
return ReturnCode::OSError;
}
}
}
mainThreadTLS->_currentFiberIndex = FindFreeFiber();
// Main
_mainCallback = main;
if (_mainCallback == nullptr && _shutdownAfterMain) {
return ReturnCode::NullCallback;
}
// Setup main Fiber
const auto mainFiber = &_fibers[mainThreadTLS->_currentFiberIndex];
mainFiber->SetCallback(FiberCallback_Main);
if (_mainCallback) {
mainThreadTLS->_threadFiber.SwitchTo(mainFiber, this);
}
if (_mainCallback) {
// Wait for all Threads to shut down
for (uint8_t i = 1; i < _numThreads; i++) {
_threads[i].Join();
}
}
return ReturnCode::Succes;
}
void nmd::fiber::Manager::Shutdown(bool blocking)
{
_shuttingDown.store(true, std::memory_order_release);
if (blocking)
{
for (uint8_t i = 1; i < _numThreads; i++) {
_threads[i].Join();
}
}
}
uint16_t nmd::fiber::Manager::FindFreeFiber()
{
while (true)
{
for (uint16_t i = 0; i < _numFibers; i++)
{
if (!_idleFibers[i].load(std::memory_order_relaxed)
|| !_idleFibers[i].load(std::memory_order_acquire)) {
continue;
}
bool expected = true;
if (std::atomic_compare_exchange_weak_explicit(&_idleFibers[i], &expected, false, std::memory_order_release, std::memory_order_relaxed)) {
return i;
}
}
// TODO: Add Debug Counter and error message
}
}
void nmd::fiber::Manager::CleanupPreviousFiber(TLS* tls)
{
if (tls == nullptr) {
tls = GetCurrentTLS();
}
switch (tls->_previousFiberDestination)
{
case FiberDestination::None:
return;
case FiberDestination::Pool:
_idleFibers[tls->_previousFiberIndex].store(true, std::memory_order_release);
break;
case FiberDestination::Waiting:
tls->_previousFiberStored->store(true, std::memory_order_relaxed);
break;
default:
break;
}
tls->Cleanup();
}
| 23.42723
| 141
| 0.707214
|
MarqusJonsson
|
05a79b51fe5cffeda2814cf180805a6308ee6c2f
| 2,141
|
cpp
|
C++
|
main4-4.cpp
|
if025-pm-unpsjb/tp5-2019-emanuelbalcazar
|
e5201ce62a06a4177340799c78cfeb81923d1fa9
|
[
"MIT"
] | 1
|
2019-11-12T21:20:23.000Z
|
2019-11-12T21:20:23.000Z
|
main4-4.cpp
|
if025-pm-unpsjb/tp5-2019-emanuelbalcazar
|
e5201ce62a06a4177340799c78cfeb81923d1fa9
|
[
"MIT"
] | null | null | null |
main4-4.cpp
|
if025-pm-unpsjb/tp5-2019-emanuelbalcazar
|
e5201ce62a06a4177340799c78cfeb81923d1fa9
|
[
"MIT"
] | null | null | null |
#include "mbed.h" // Librería mbed
#include "FreeRTOS.h" // Definiciones principales de FreeRTOS
#include "task.h" // Funciones para el control de las tareas
Serial pc(USBTX, USBRX); // tx, rx
DigitalOut led1(LED1);
// SYSTEM 0, 1 o 2
const int SYSTEM = 0;
void thread1(void*);
struct Task {
char name[10];
int priority;
int c;
int t;
int d;
};
Task setr1[3] = { { "t1", 1, 2, 4, 4 }, { "t2", 2, 1, 5, 5 },
{ "t3", 3, 1, 6, 6 } };
Task setr2[3] = { { 1, 3, 5, 5 }, { 2, 1, 7, 7 }, { 3, 2, 10, 10 } };
Task setr3[4] = { { 1, 2, 5, 5 }, { 2, 1, 6, 6 }, { 3, 2, 10, 10 }, { 4, 1, 15,
15 } };
Task *all[] = { setr1, setr2, setr3 };
Task* get_system(int number) {
Task *setr;
setr = all[number];
return setr;
}
// TODO arreglar algun dia
int get_length(int number) {
if (number == 0) {
return 3;
} else if (number == 1) {
return 3;
} else if (number == 2) {
return 4;
}
return 0;
}
int main() {
// Initializes the trace recorder, but does not start the tracing.
vTraceEnable( TRC_INIT);
Task *setr = get_system(SYSTEM);
int length = get_length(SYSTEM);
for (int i = 0; i < length; i++) {
Task *task = &(setr[i]);
xTaskCreate(thread1, task->name, 256, (void*) task,
configMAX_PRIORITIES - task->priority,
NULL);
}
vTraceEnable( TRC_START);
pc.printf("Iniciando planificador...\n\r");
vTaskStartScheduler();
for (;;)
;
}
void wait_without_block(TickType_t ticks) {
TickType_t currentTick = xTaskGetTickCount();
while (xTaskGetTickCount() - currentTick < ticks) {
}
return;
}
void thread1(void *params) {
// get current task
Task *task = (Task*) params;
TickType_t startTime = 0;
TickType_t endTime = 0;
const TickType_t xFrequency = task->t * 1000;
int instance = 0;
startTime = xTaskGetTickCount();
// para el instante critico.
if (instance == 0) {
startTime = 0;
}
while (1) {
led1 = !led1;
wait_without_block(task->c * 1000);
endTime = xTaskGetTickCount();
pc.printf("Tarea [%s] - inicio: %d - fin: %d - instancia: %d\n\r",
task->name, startTime, endTime, instance);
instance++;
vTaskDelayUntil(&startTime, xFrequency);
}
}
| 18.946903
| 79
| 0.610929
|
if025-pm-unpsjb
|
05aa007478d246c30fe28407256cc60dc922165c
| 707
|
inl
|
C++
|
performance-tests/Synch-Benchmarks/Base_Test/Baseline_Test.inl
|
BeiJiaan/ace
|
2845970c894bb350d12d6a32e867d7ddf2487f25
|
[
"DOC"
] | 16
|
2015-05-11T04:33:44.000Z
|
2022-02-15T04:28:39.000Z
|
performance-tests/Synch-Benchmarks/Base_Test/Baseline_Test.inl
|
BeiJiaan/ace
|
2845970c894bb350d12d6a32e867d7ddf2487f25
|
[
"DOC"
] | null | null | null |
performance-tests/Synch-Benchmarks/Base_Test/Baseline_Test.inl
|
BeiJiaan/ace
|
2845970c894bb350d12d6a32e867d7ddf2487f25
|
[
"DOC"
] | 7
|
2015-01-08T16:11:34.000Z
|
2021-07-04T16:04:40.000Z
|
// $Id$
ACE_INLINE size_t
Baseline_Test_Base::iteration (void)
{
return this->iteration_;
}
ACE_INLINE int
Baseline_Test_Base::yield_method (void)
{
return this->yield_method_;
}
ACE_INLINE int
Baseline_Test_Options::test_try_lock (void)
{
return this->test_try_lock_;
}
ACE_INLINE size_t
Baseline_Test_Options::current_iteration (void)
{
return this->current_iteration_;
}
ACE_INLINE void
Baseline_Test_Options::start_inc_timer (void)
{
this->timer.start_incr ();
}
ACE_INLINE void
Baseline_Test_Options::stop_inc_timer (void)
{
this->timer.stop_incr ();
}
ACE_INLINE int
Baseline_Test_Options::inc_loop_counter (void)
{
return (++this->current_iteration_ < this->total_iteration_);
}
| 16.068182
| 63
| 0.772277
|
BeiJiaan
|
05ae1572c7945c27845058a91ddf0021294b064d
| 357
|
cpp
|
C++
|
Setul_D.5/P6.cpp
|
rlodina99/Learn_cpp
|
0c5bd9e6c52ca21e2eb95eb91597272ddc842c08
|
[
"MIT"
] | null | null | null |
Setul_D.5/P6.cpp
|
rlodina99/Learn_cpp
|
0c5bd9e6c52ca21e2eb95eb91597272ddc842c08
|
[
"MIT"
] | null | null | null |
Setul_D.5/P6.cpp
|
rlodina99/Learn_cpp
|
0c5bd9e6c52ca21e2eb95eb91597272ddc842c08
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <fstream>
using namespace std;
int main(){
ifstream f("P6.in");
int n,p,x,scif=0;
f >> n;
f >> p;
int arr[n];
for (int i=0; i<n; i++){
f >> arr[i];
}
for (int i=0; i<n; i++){
x=arr[i];
while(x!=0){
scif+=x%10;
x=x/10;
}
if(scif%p==0)
cout << arr[i] << ' ';
scif=0;
}
return 0;
}
| 11.516129
| 28
| 0.464986
|
rlodina99
|
05af093645111de3fc5f0533d5de887324095f85
| 8,912
|
cpp
|
C++
|
calc_v3/calccore.cpp
|
fa993/calc_v3
|
d01d010764e7f49a60a0b2d222612cc25d7bf7a1
|
[
"MIT"
] | null | null | null |
calc_v3/calccore.cpp
|
fa993/calc_v3
|
d01d010764e7f49a60a0b2d222612cc25d7bf7a1
|
[
"MIT"
] | null | null | null |
calc_v3/calccore.cpp
|
fa993/calc_v3
|
d01d010764e7f49a60a0b2d222612cc25d7bf7a1
|
[
"MIT"
] | null | null | null |
#ifndef CALCCORE_FA993
#define CALCCORE_FA993
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <sstream>
#include "calcentity.cpp"
class CalcFunctionData;
class CalcPrimaryFunctionData;
class CalcText : public CalcData {
protected:
std::string value;
public:
CalcText(std::string &name) {
this->value = name;
}
std::string& get_value() {
return this->value;
}
void to_string(std::ostringstream &buffer) {
buffer << value;
}
CalcData* clone() {
return new CalcText(this->value);
}
CalcNodeType get_node_type() {
return TEXT;
}
};
enum CalcSymbolType {
PLUS,
MINUS,
ASTERISK,
SLASH,
MODULUS,
CARET,
PARENTHESISOPEN,
PARENTHESISCLOSE,
COMMA,
EQUALS
};
class CalcSymbol: public CalcData
{
std::string name;
CalcSymbolType type;
public:
CalcSymbol(std::string name, CalcSymbolType symType) {
this->name = name;
this->type = symType;
}
void to_string(std::ostringstream &buffer) {
buffer << name;
}
std::string& get_name() {
return this->name;
}
CalcSymbolType get_type() {
return this->type;
}
CalcData* clone() {
//no clone support for this
return this;
}
CalcNodeType get_node_type() {
return SYMBOL;
}
bool operator == (const CalcSymbol &c2) {
return this->type == c2.type;
}
bool operator == (const CalcSymbolType &c2) {
return this->type == c2;
}
};
char from_symbol(CalcSymbolType type)
{
switch (type)
{
case PLUS:
return '+';
case MINUS:
return '-';
case ASTERISK:
return '*';
case SLASH:
return '/';
case MODULUS:
return '%';
case CARET:
return '^';
case PARENTHESISOPEN:
return '(';
case PARENTHESISCLOSE:
return ')';
case COMMA:
return ',';
case EQUALS:
return '=';
default:
throw "Unrecognized symbol";
}
}
CalcSymbol* PLUS_SYMBOL = new CalcSymbol(std::string("plus"), PLUS);
CalcSymbol* MINUS_SYMBOL = new CalcSymbol(std::string("minus"), MINUS);
CalcSymbol* ASTERISK_SYMBOL = new CalcSymbol(std::string("asterisk"), ASTERISK);
CalcSymbol* SLASH_SYMBOL = new CalcSymbol(std::string("slash"), SLASH);
CalcSymbol* MODULUS_SYMBOL = new CalcSymbol(std::string("modulus"), MODULUS);
CalcSymbol* CARET_SYMBOL = new CalcSymbol(std::string("caret"), CARET);
CalcSymbol* PARENTHESISOPEN_SYMBOL = new CalcSymbol(std::string("parenthesis open"), PARENTHESISOPEN);
CalcSymbol* PARENTHESISCLOSE_SYMBOL = new CalcSymbol(std::string("parenthesis close"), PARENTHESISCLOSE);
CalcSymbol* COMMA_SYMBOL = new CalcSymbol(std::string("comma"), COMMA);
CalcSymbol* EQUALS_SYMBOL = new CalcSymbol(std::string("equals"), EQUALS);
class CalcSecondaryFunctionData;
class CalcNode
{
CalcNode *prev = nullptr;
CalcNode *next = nullptr;
CalcData *data;
bool parsed = false;
public:
CalcNode()
{
}
CalcNode(CalcSymbol* symType)
{
data = symType;
}
CalcNode(CalcValue* numData)
{
data = numData;
}
CalcNode(std::string &text)
{
data = new CalcText(text);
}
CalcNode(CalcSecondaryFunctionData *dat);
CalcNode(CalcPrimaryFunctionData *dat);
CalcNode *clone()
{
CalcNode *cl = new CalcNode();
cl->parsed = this->parsed;
cl->data = this->data->clone();
return cl;
}
void to_string(std::ostringstream &buffer)
{
CalcNode *cn = this;
cn->get_data()->to_string(buffer);
}
void to_debug_string(std::ostringstream &buffer) {
CalcNode *cn = this;
this->to_string(buffer);
if(cn->next != nullptr){
buffer << "---";
cn->next->to_debug_string(buffer);
}
}
void push_node(CalcNode *nextNode)
{
this->next = nextNode;
nextNode->prev = this;
}
bool is_symbol(CalcSymbol *symType)
{
return this->get_type() == SYMBOL && static_cast<CalcSymbol *>(this->data)->get_type() == symType->get_type();
}
CalcNodeType get_type() {
return this->data->get_node_type();
}
CalcData *get_data()
{
return this->data;
}
void set_data(CalcData *newData)
{
this->data = newData;
}
void set_data(CalcSymbol* newData)
{
this->data = newData;
}
CalcNode *get_next()
{
if (this->parsed)
{
throw "Node has been Disconnected";
}
return this->next;
}
void set_next(CalcNode *newNext)
{
if (this->parsed)
{
throw "Node has been Disconnected";
}
this->next = newNext;
}
CalcNode *get_prev()
{
if (this->parsed)
{
throw "Node has been Disconnected";
}
return this->prev;
}
void set_prev(CalcNode *newPrev)
{
if (this->parsed)
{
throw "Node has been Disconnected";
}
this->prev = newPrev;
}
void disconnect()
{
this->parsed = true;
this->prev = nullptr;
this->next = nullptr;
}
~CalcNode()
{
}
};
class CalcFunctionData : public CalcData {
public:
virtual CalcData* get_arg(size_t index) = 0;
virtual void set_arg(size_t index, CalcData* newArg) = 0;
virtual size_t get_arg_size() = 0;
virtual CalcFunctionData* clone_self() = 0;
CalcData* clone() final {
CalcFunctionData* self = clone_self();
for(int i = 0; i < this->get_arg_size(); i++) {
if(this->get_arg(i) != nullptr) {
self->set_arg(i, this->get_arg(i)->clone());
} else {
self->set_arg(i, nullptr);
}
}
return self;
}
};
class CalcPrimaryFunctionData : public CalcFunctionData
{
protected:
bool wrapWithBrackets = false;
public:
CalcPrimaryFunctionData() {
this->wrapWithBrackets = false;
}
CalcNodeType get_node_type() {
return PRIMARY_FUNCTION;
}
virtual bool is_inverse(const std::string &name)
{
return false;
}
virtual CalcData *evaluate() = 0;
virtual void push_arg(CalcData* arg) = 0;
virtual ~CalcPrimaryFunctionData() {
}
void set_wrap_brackets(bool wrap) {
this->wrapWithBrackets = wrap;
}
bool get_wrap_brackets() {
return this->wrapWithBrackets;
}
};
class CalcSecondaryFunctionData : public CalcFunctionData
{
std::string name;
std::vector<CalcData *> args;
bool wrapWithBrackets = false;
public:
CalcSecondaryFunctionData(std::string &name)
{
this->name = name;
this->wrapWithBrackets = false;
}
CalcNodeType get_node_type() {
return SECONDARY_FUNCTION;
}
void push_arg(CalcData *nd)
{
this->args.push_back(nd);
}
std::vector<CalcData *> &get_args()
{
return this->args;
}
void set_args(std::vector<CalcData*>& args){
this->args = args;
}
size_t get_arg_size() {
return this->args.size();
}
void set_arg(size_t index, CalcData* newArg) {
this->args[index] = newArg;
}
CalcData* get_arg(size_t index) {
return this->args[index];
}
std::string& get_name() {
return this->name;
}
void set_wrap_brackets(bool wrap) {
this->wrapWithBrackets = wrap;
}
bool get_wrap_brackets() {
return this->wrapWithBrackets;
}
CalcFunctionData *clone_self()
{
throw "Unsupported as of now";
}
void to_string(std::ostringstream &buffer)
{
buffer << this->get_name();
buffer << '(';
bool first = true;
for (std::vector<CalcData *>::iterator it1 = args.begin(); it1 != args.end(); it1++)
{
if (!first)
{
buffer << ", ";
}
else
{
first = false;
}
CalcData *cn = *it1;
cn->to_string(buffer);
}
buffer << ") ";
}
~CalcSecondaryFunctionData()
{
for (std::vector<CalcData *>::iterator it = args.begin(); it != args.end(); ++it)
{
delete *it;
}
std::vector<CalcData *>().swap(args);
}
};
CalcNode::CalcNode(CalcSecondaryFunctionData *dat)
{
data = dat;
parsed = false;
}
CalcNode::CalcNode(CalcPrimaryFunctionData *dat)
{
data = dat;
parsed = true;
}
#endif
| 19.804444
| 118
| 0.554758
|
fa993
|
05b1a9d3fd5a2f4fc22db2e5fe22f780c1bc7b30
| 24,064
|
cpp
|
C++
|
src/mumble/OverlayEditorScene.cpp
|
JoelTroch/mumble
|
cdaff31b00a713b2a259d9c6a4c81bf7496a592e
|
[
"BSD-3-Clause"
] | 1
|
2015-02-27T15:40:11.000Z
|
2015-02-27T15:40:11.000Z
|
src/mumble/OverlayEditorScene.cpp
|
JoelTroch/mumble
|
cdaff31b00a713b2a259d9c6a4c81bf7496a592e
|
[
"BSD-3-Clause"
] | null | null | null |
src/mumble/OverlayEditorScene.cpp
|
JoelTroch/mumble
|
cdaff31b00a713b2a259d9c6a4c81bf7496a592e
|
[
"BSD-3-Clause"
] | null | null | null |
/* Copyright (C) 2005-2011, Thorvald Natvig <thorvald@natvig.com>
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 Mumble Developers 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 FOUNDATION 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 "mumble_pch.hpp"
#include "OverlayEditorScene.h"
#include "OverlayClient.h"
#include "OverlayUser.h"
#include "OverlayText.h"
#include "User.h"
#include "Channel.h"
#include "Global.h"
#include "Message.h"
#include "Database.h"
#include "NetworkConfig.h"
#include "ServerHandler.h"
#include "MainWindow.h"
#include "GlobalShortcut.h"
OverlayEditorScene::OverlayEditorScene(const OverlaySettings &srcos, QObject *p) : QGraphicsScene(p), os(srcos) {
tsColor = Settings::Talking;
uiZoom = 2;
if (g.ocIntercept)
uiSize = g.ocIntercept->uiHeight;
else
uiSize = 1080.f;
qgiGroup = new OverlayGroup();
qgiGroup->setAcceptHoverEvents(true);
qgiGroup->setPos(0.0f, 0.0f);
addItem(qgiGroup);
qgpiMuted = new QGraphicsPixmapItem(qgiGroup);
qgpiMuted->hide();
qgpiAvatar = new QGraphicsPixmapItem(qgiGroup);
qgpiAvatar->hide();
qgpiName = new QGraphicsPixmapItem(qgiGroup);
qgpiName->hide();
qgpiChannel = new QGraphicsPixmapItem(qgiGroup);
qgpiChannel->hide();
qgpiBox = new QGraphicsPathItem(qgiGroup);
qgpiBox->hide();
qgpiSelected = NULL;
qgriSelected = new QGraphicsRectItem;
qgriSelected->hide();
qgriSelected->setFlag(QGraphicsItem::ItemIgnoresParentOpacity, true);
qgriSelected->setOpacity(1.0f);
qgriSelected->setBrush(Qt::NoBrush);
qgriSelected->setPen(QPen(Qt::black, 4.0f));
qgriSelected->setZValue(5.0f);
addItem(qgriSelected);
qgpiChannel->setZValue(2.0f);
qgpiName->setZValue(1.0f);
qgpiMuted->setZValue(3.0f);
qgpiBox->setZValue(-1.0f);
resync();
}
#define SCALESIZE(var) iroundf(uiSize * uiZoom * os.qrf##var .width() + 0.5f), iroundf(uiSize * uiZoom * os.qrf##var .height() + 0.5f)
void OverlayEditorScene::updateMuted() {
QImageReader qir(QLatin1String("skin:muted_self.svg"));
QSize sz = qir.size();
sz.scale(SCALESIZE(MutedDeafened), Qt::KeepAspectRatio);
qir.setScaledSize(sz);
qgpiMuted->setPixmap(QPixmap::fromImage(qir.read()));
moveMuted();
}
void OverlayEditorScene::moveMuted() {
qgpiMuted->setVisible(os.bMutedDeafened);
qgpiMuted->setPos(OverlayUser::alignedPosition(OverlayUser::scaledRect(os.qrfMutedDeafened, uiSize * uiZoom), qgpiMuted->boundingRect(), os.qaMutedDeafened));
qgpiMuted->setOpacity(os.fMutedDeafened);
}
void OverlayEditorScene::updateUserName() {
QString qsName;
switch (tsColor) {
case Settings::Passive:
qsName = Overlay::tr("Silent");
break;
case Settings::Talking:
qsName = Overlay::tr("Talking");
break;
case Settings::Whispering:
qsName = Overlay::tr("Whisper");
break;
case Settings::Shouting:
qsName = Overlay::tr("Shout");
break;
}
const QPixmap &pm = OverlayTextLine(qsName, os.qfUserName).createPixmap(SCALESIZE(UserName), os.qcUserName[tsColor]);
qgpiName->setPixmap(pm);
moveUserName();
}
void OverlayEditorScene::moveUserName() {
qgpiName->setVisible(os.bUserName);
qgpiName->setPos(OverlayUser::alignedPosition(OverlayUser::scaledRect(os.qrfUserName, uiSize * uiZoom), qgpiName->boundingRect(), os.qaUserName));
qgpiName->setOpacity(os.fUserName);
}
void OverlayEditorScene::updateChannel() {
const QPixmap &pm = OverlayTextLine(Overlay::tr("Channel"), os.qfChannel).createPixmap(SCALESIZE(Channel), os.qcChannel);
qgpiChannel->setPixmap(pm);
moveChannel();
}
void OverlayEditorScene::moveChannel() {
qgpiChannel->setVisible(os.bChannel);
qgpiChannel->setPos(OverlayUser::alignedPosition(OverlayUser::scaledRect(os.qrfChannel, uiSize * uiZoom), qgpiChannel->boundingRect(), os.qaChannel));
qgpiChannel->setOpacity(os.fChannel);
}
void OverlayEditorScene::updateAvatar() {
QImage img;
QImageReader qir(QLatin1String("skin:default_avatar.svg"));
QSize sz = qir.size();
sz.scale(SCALESIZE(Avatar), Qt::KeepAspectRatio);
qir.setScaledSize(sz);
img = qir.read();
qgpiAvatar->setPixmap(QPixmap::fromImage(img));
moveAvatar();
}
void OverlayEditorScene::moveAvatar() {
qgpiAvatar->setVisible(os.bAvatar);
qgpiAvatar->setPos(OverlayUser::alignedPosition(OverlayUser::scaledRect(os.qrfAvatar, uiSize * uiZoom), qgpiAvatar->boundingRect(), os.qaAvatar));
qgpiAvatar->setOpacity(os.fAvatar);
}
void OverlayEditorScene::moveBox() {
QRectF childrenBounds = os.qrfAvatar | os.qrfChannel | os.qrfMutedDeafened | os.qrfUserName;
bool haspen = (os.qcBoxPen != os.qcBoxFill) && (! qFuzzyCompare(os.qcBoxPen.alphaF(), static_cast<qreal>(0.0f)));
qreal pw = haspen ? qMax<qreal>(1.0f, os.fBoxPenWidth * uiSize * uiZoom) : 0.0f;
qreal pad = os.fBoxPad * uiSize * uiZoom;
QPainterPath pp;
pp.addRoundedRect(childrenBounds.x() * uiSize * uiZoom + -pw / 2.0f - pad, childrenBounds.y() * uiSize * uiZoom + -pw / 2.0f - pad, childrenBounds.width() * uiSize * uiZoom + pw + 2.0f * pad, childrenBounds.height() * uiSize * uiZoom + pw + 2.0f * pad, 2.0f * pw, 2.0f * pw);
qgpiBox->setPath(pp);
qgpiBox->setPos(0.0f, 0.0f);
qgpiBox->setPen(haspen ? QPen(os.qcBoxPen, pw) : Qt::NoPen);
qgpiBox->setBrush(qFuzzyCompare(os.qcBoxFill.alphaF(), static_cast<qreal>(0.0f)) ? Qt::NoBrush : os.qcBoxFill);
qgpiBox->setOpacity(1.0f);
qgpiBox->setVisible(os.bBox);
}
void OverlayEditorScene::updateSelected() {
if (qgpiSelected == qgpiAvatar)
updateAvatar();
else if (qgpiSelected == qgpiName)
updateUserName();
else if (qgpiSelected == qgpiMuted)
updateMuted();
}
void OverlayEditorScene::resync() {
QRadialGradient gradient(0, 0, 10 * uiZoom);
gradient.setSpread(QGradient::ReflectSpread);
gradient.setColorAt(0.0f, QColor(255, 255, 255, 64));
gradient.setColorAt(0.2f, QColor(0, 0, 0, 64));
gradient.setColorAt(0.4f, QColor(255, 128, 0, 64));
gradient.setColorAt(0.6f, QColor(0, 0, 0, 64));
gradient.setColorAt(0.8f, QColor(0, 128, 255, 64));
gradient.setColorAt(1.0f, QColor(0, 0, 0, 64));
setBackgroundBrush(gradient);
updateMuted();
updateUserName();
updateChannel();
updateAvatar();
moveMuted();
moveUserName();
moveChannel();
moveAvatar();
moveBox();
qgiGroup->setOpacity(os.fUser[tsColor]);
qgpiSelected = NULL;
qgriSelected->setVisible(false);
}
void OverlayEditorScene::drawBackground(QPainter *p, const QRectF &rect) {
p->setBrushOrigin(0, 0);
p->fillRect(rect, backgroundBrush());
QRectF upscaled = OverlayUser::scaledRect(rect, 128.f / static_cast<float>(uiSize * uiZoom));
{
int min = iroundf(upscaled.left());
int max = iroundf(ceil(upscaled.right()));
for (int i=min;i<=max;++i) {
qreal v = (i / 128) * static_cast<qreal>(uiSize * uiZoom);
if (i != 0)
p->setPen(QPen(QColor(128, 128, 128, 255), 0.0f));
else
p->setPen(QPen(QColor(0, 0, 0, 255), 2.0f));
p->drawLine(QPointF(v, rect.top()), QPointF(v, rect.bottom()));
}
}
{
int min = iroundf(upscaled.top());
int max = iroundf(ceil(upscaled.bottom()));
for (int i=min;i<=max;++i) {
qreal v = (i / 128) * static_cast<qreal>(uiSize * uiZoom);
if (i != 0)
p->setPen(QPen(QColor(128, 128, 128, 255), 0.0f));
else
p->setPen(QPen(QColor(0, 0, 0, 255), 2.0f));
p->drawLine(QPointF(rect.left(), v), QPointF(rect.right(), v));
}
}
}
QGraphicsPixmapItem *OverlayEditorScene::childAt(const QPointF &pos) {
QGraphicsItem *item = NULL;
if (qgriSelected->isVisible()) {
if (qgriSelected->rect().contains(pos)) {
return qgpiSelected;
}
}
foreach(QGraphicsItem *qgi, items(Qt::AscendingOrder)) {
if (!qgi->isVisible() || ! qgraphicsitem_cast<QGraphicsPixmapItem *>(qgi))
continue;
QPointF qp = pos - qgi->pos();
if (qgi->contains(qp)) {
item = qgi;
}
}
return static_cast<QGraphicsPixmapItem *>(item);
}
QRectF OverlayEditorScene::selectedRect() const {
const QRectF *qrf = NULL;
if (qgpiSelected == qgpiMuted)
qrf = & os.qrfMutedDeafened;
else if (qgpiSelected == qgpiAvatar)
qrf = & os.qrfAvatar;
else if (qgpiSelected == qgpiChannel)
qrf = & os.qrfChannel;
else if (qgpiSelected == qgpiName)
qrf = & os.qrfUserName;
if (! qrf)
return QRectF();
return OverlayUser::scaledRect(*qrf, uiSize * uiZoom).toAlignedRect();
}
void OverlayEditorScene::mousePressEvent(QGraphicsSceneMouseEvent *e) {
QGraphicsScene::mousePressEvent(e);
if (e->isAccepted())
return;
if (e->button() == Qt::LeftButton) {
e->accept();
if (wfsHover == Qt::NoSection) {
qgpiSelected = childAt(e->scenePos());
if (qgpiSelected) {
qgriSelected->setRect(selectedRect());
qgriSelected->show();
} else {
qgriSelected->hide();
}
}
updateCursorShape(e->scenePos());
}
}
void OverlayEditorScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *e) {
QGraphicsScene::mouseReleaseEvent(e);
if (e->isAccepted())
return;
if (e->button() == Qt::LeftButton) {
e->accept();
QRectF rect = qgriSelected->rect();
if (! qgpiSelected || (rect == selectedRect())) {
return;
}
QRectF scaled(rect.x() / (uiSize * uiZoom), rect.y() / (uiSize * uiZoom), rect.width() / (uiSize * uiZoom), rect.height() / (uiSize * uiZoom));
if (qgpiSelected == qgpiMuted) {
os.qrfMutedDeafened = scaled;
updateMuted();
} else if (qgpiSelected == qgpiAvatar) {
os.qrfAvatar = scaled;
updateAvatar();
} else if (qgpiSelected == qgpiChannel) {
os.qrfChannel = scaled;
updateChannel();
} else if (qgpiSelected == qgpiName) {
os.qrfUserName = scaled;
updateUserName();
}
moveBox();
}
}
void OverlayEditorScene::mouseMoveEvent(QGraphicsSceneMouseEvent *e) {
QGraphicsScene::mouseMoveEvent(e);
if (e->isAccepted())
return;
if (qgpiSelected && (e->buttons() & Qt::LeftButton)) {
e->accept();
if (wfsHover == Qt::NoSection)
return;
QPointF delta = e->scenePos() - e->buttonDownScenePos(Qt::LeftButton);
bool square = e->modifiers() & Qt::ShiftModifier;
QRectF orig = selectedRect();
switch (wfsHover) {
case Qt::TitleBarArea:
orig.translate(delta);
break;
case Qt::TopSection:
orig.setTop(orig.top() + delta.y());
if (orig.height() < 8.0f)
orig.setTop(orig.bottom() - 8.0f);
if (square)
orig.setRight(orig.left() + orig.height());
break;
case Qt::BottomSection:
orig.setBottom(orig.bottom() + delta.y());
if (orig.height() < 8.0f)
orig.setBottom(orig.top() + 8.0f);
if (square)
orig.setRight(orig.left() + orig.height());
break;
case Qt::LeftSection:
orig.setLeft(orig.left() + delta.x());
if (orig.width() < 8.0f)
orig.setLeft(orig.right() - 8.0f);
if (square)
orig.setBottom(orig.top() + orig.width());
break;
case Qt::RightSection:
orig.setRight(orig.right() + delta.x());
if (orig.width() < 8.0f)
orig.setRight(orig.left() + 8.0f);
if (square)
orig.setBottom(orig.top() + orig.width());
break;
case Qt::TopLeftSection:
orig.setTopLeft(orig.topLeft() + delta);
if (orig.height() < 8.0f)
orig.setTop(orig.bottom() - 8.0f);
if (orig.width() < 8.0f)
orig.setLeft(orig.right() - 8.0f);
if (square) {
qreal size = qMin(orig.width(), orig.height());
QPointF sz(-size, -size);
orig.setTopLeft(orig.bottomRight() + sz);
}
break;
case Qt::TopRightSection:
orig.setTopRight(orig.topRight() + delta);
if (orig.height() < 8.0f)
orig.setTop(orig.bottom() - 8.0f);
if (orig.width() < 8.0f)
orig.setRight(orig.left() + 8.0f);
if (square) {
qreal size = qMin(orig.width(), orig.height());
QPointF sz(size, -size);
orig.setTopRight(orig.bottomLeft() + sz);
}
break;
case Qt::BottomLeftSection:
orig.setBottomLeft(orig.bottomLeft() + delta);
if (orig.height() < 8.0f)
orig.setBottom(orig.top() + 8.0f);
if (orig.width() < 8.0f)
orig.setLeft(orig.right() - 8.0f);
if (square) {
qreal size = qMin(orig.width(), orig.height());
QPointF sz(-size, size);
orig.setBottomLeft(orig.topRight() + sz);
}
break;
case Qt::BottomRightSection:
orig.setBottomRight(orig.bottomRight() + delta);
if (orig.height() < 8.0f)
orig.setBottom(orig.top() + 8.0f);
if (orig.width() < 8.0f)
orig.setRight(orig.left() + 8.0f);
if (square) {
qreal size = qMin(orig.width(), orig.height());
QPointF sz(size, size);
orig.setBottomRight(orig.topLeft() + sz);
}
break;
case Qt::NoSection:
// Handled above, but this makes the compiler happy.
return;
}
qgriSelected->setRect(orig);
} else {
updateCursorShape(e->scenePos());
}
}
void OverlayEditorScene::updateCursorShape(const QPointF &point) {
Qt::CursorShape cs;
if (qgriSelected->isVisible()) {
wfsHover = rectSection(qgriSelected->rect(), point);
} else {
wfsHover = Qt::NoSection;
}
switch (wfsHover) {
case Qt::TopLeftSection:
case Qt::BottomRightSection:
cs = Qt::SizeFDiagCursor;
break;
case Qt::TopRightSection:
case Qt::BottomLeftSection:
cs = Qt::SizeBDiagCursor;
break;
case Qt::TopSection:
case Qt::BottomSection:
cs = Qt::SizeVerCursor;
break;
case Qt::LeftSection:
case Qt::RightSection:
cs = Qt::SizeHorCursor;
break;
case Qt::TitleBarArea:
cs = Qt::OpenHandCursor;
break;
default:
cs = Qt::ArrowCursor;
break;
}
foreach(QGraphicsView *v, views()) {
if (v->viewport()->cursor().shape() != cs) {
v->viewport()->setCursor(cs);
// But an embedded, injected GraphicsView doesn't propagage mouse cursors...
QWidget *p = v->parentWidget();
if (p) {
QGraphicsProxyWidget *qgpw = p->graphicsProxyWidget();
if (qgpw) {
qgpw->setCursor(cs);
if (g.ocIntercept)
g.ocIntercept->updateMouse();
}
}
}
}
}
void OverlayEditorScene::contextMenuEvent(QGraphicsSceneContextMenuEvent *e) {
QGraphicsScene::contextMenuEvent(e);
if (e->isAccepted())
return;
if (! e->widget())
return;
QGraphicsPixmapItem *item = childAt(e->scenePos());
QMenu qm(e->widget());
QMenu *qmLayout = qm.addMenu(tr("Layout preset"));
QAction *qaLayoutLargeAvatar = qmLayout->addAction(tr("Large square avatar"));
QAction *qaLayoutText = qmLayout->addAction(tr("Avatar and Name"));
QMenu *qmTrans = qm.addMenu(tr("User Opacity"));
QActionGroup *qagUser = new QActionGroup(&qm);
QAction *userOpacity[8];
for (int i=0;i<8;++i) {
qreal o = (i + 1) / 8.0;
userOpacity[i] = new QAction(tr("%1%").arg(o * 100.0f, 0, 'f', 1), qagUser);
userOpacity[i]->setCheckable(true);
userOpacity[i]->setData(o);
if (qFuzzyCompare(qgiGroup->opacity(), o))
userOpacity[i]->setChecked(true);
qmTrans->addAction(userOpacity[i]);
}
QAction *color = NULL;
QAction *fontAction = NULL;
QAction *objectOpacity[8];
for (int i=0;i<8;++i)
objectOpacity[i] = NULL;
QAction *boxpen[4] = { NULL, NULL, NULL, NULL};
QAction *boxpad[4] = { NULL, NULL, NULL, NULL};
QAction *boxpencolor = NULL;
QAction *boxfillcolor = NULL;
QAction *align[6];
for (int i=0;i<6;++i)
align[i] = NULL;
if (item) {
qm.addSeparator();
QMenu *qmObjTrans = qm.addMenu(tr("Object Opacity"));
QActionGroup *qagObject = new QActionGroup(&qm);
for (int i=0;i<8;++i) {
qreal o = i + 1 / 8.0;
objectOpacity[i] = new QAction(tr("%1%").arg(o * 100.0f, 0, 'f', 1), qagObject);
objectOpacity[i]->setCheckable(true);
objectOpacity[i]->setData(o);
if (qFuzzyCompare(item->opacity(), o))
objectOpacity[i]->setChecked(true);
qmObjTrans->addAction(objectOpacity[i]);
}
QMenu *qmObjAlign = qm.addMenu(tr("Alignment"));
Qt::Alignment a;
if (item == qgpiAvatar)
a = os.qaAvatar;
else if (item == qgpiChannel)
a = os.qaChannel;
else if (item == qgpiMuted)
a = os.qaMutedDeafened;
else
a = os.qaUserName;
align[0] = qmObjAlign->addAction(tr("Left"));
align[0]->setCheckable(true);
align[0]->setData(Qt::AlignLeft);
if (a & Qt::AlignLeft)
align[0]->setChecked(true);
align[1] = qmObjAlign->addAction(tr("Center"));
align[1]->setCheckable(true);
align[1]->setData(Qt::AlignHCenter);
if (a & Qt::AlignHCenter)
align[1]->setChecked(true);
align[2] = qmObjAlign->addAction(tr("Right"));
align[2]->setCheckable(true);
align[2]->setData(Qt::AlignRight);
if (a & Qt::AlignRight)
align[2]->setChecked(true);
qmObjAlign->addSeparator();
align[3] = qmObjAlign->addAction(tr("Top"));
align[3]->setCheckable(true);
align[3]->setData(Qt::AlignTop);
if (a & Qt::AlignTop)
align[3]->setChecked(true);
align[4] = qmObjAlign->addAction(tr("Center"));
align[4]->setCheckable(true);
align[4]->setData(Qt::AlignVCenter);
if (a & Qt::AlignVCenter)
align[4]->setChecked(true);
align[5] = qmObjAlign->addAction(tr("Bottom"));
align[5]->setCheckable(true);
align[5]->setData(Qt::AlignBottom);
if (a & Qt::AlignBottom)
align[5]->setChecked(true);
if ((item != qgpiAvatar) && (item != qgpiMuted)) {
color = qm.addAction(tr("Color..."));
fontAction = qm.addAction(tr("Font..."));
}
}
if (qgpiBox->isVisible()) {
qm.addSeparator();
QMenu *qmBox = qm.addMenu(tr("Bounding box"));
QMenu *qmPen = qmBox->addMenu(tr("Pen width"));
QMenu *qmPad = qmBox->addMenu(tr("Padding"));
boxpencolor = qmBox->addAction(tr("Pen color"));
boxfillcolor = qmBox->addAction(tr("Fill color"));
QActionGroup *qagPen = new QActionGroup(qmPen);
QActionGroup *qagPad = new QActionGroup(qmPad);
for (int i=0;i<4;++i) {
qreal v = (i) ? powf(2.0f, static_cast<float>(-10 + i)) : 0.0f;
boxpen[i] = new QAction(QString::number(i), qagPen);
boxpen[i]->setData(v);
boxpen[i]->setCheckable(true);
if (qFuzzyCompare(os.fBoxPenWidth, v))
boxpen[i]->setChecked(true);
qmPen->addAction(boxpen[i]);
boxpad[i] = new QAction(QString::number(i), qagPad);
boxpad[i]->setData(v);
boxpad[i]->setCheckable(true);
if (qFuzzyCompare(os.fBoxPad, v))
boxpad[i]->setChecked(true);
qmPad->addAction(boxpad[i]);
}
}
QAction *act = qm.exec(e->screenPos());
if (! act)
return;
for (int i=0;i<8;++i) {
if (userOpacity[i] == act) {
float o = static_cast<float>(act->data().toReal());
os.fUser[tsColor] = o;
qgiGroup->setOpacity(o);
}
}
for (int i=0;i<8;++i) {
if (objectOpacity[i] == act) {
qreal o = act->data().toReal();
if (item == qgpiMuted)
os.fMutedDeafened = o;
else if (item == qgpiAvatar)
os.fAvatar = o;
else if (item == qgpiChannel)
os.fChannel = o;
else if (item == qgpiName)
os.fUserName = o;
item->setOpacity(o);
}
}
for (int i=0;i<4;++i) {
if (boxpen[i] == act) {
os.fBoxPenWidth = act->data().toReal();
moveBox();
} else if (boxpad[i] == act) {
os.fBoxPad = act->data().toReal();
moveBox();
}
}
for (int i=0;i<6;++i) {
if (align[i] == act) {
Qt::Alignment *aptr;
if (item == qgpiAvatar)
aptr = & os.qaAvatar;
else if (item == qgpiChannel)
aptr = & os.qaChannel;
else if (item == qgpiMuted)
aptr = & os.qaMutedDeafened;
else
aptr = & os.qaUserName;
Qt::Alignment a = static_cast<Qt::Alignment>(act->data().toInt());
if (a & Qt::AlignHorizontal_Mask) {
*aptr = (*aptr & ~Qt::AlignHorizontal_Mask) | a;
} else {
*aptr = (*aptr & ~Qt::AlignVertical_Mask) | a;
}
updateSelected();
}
}
if (act == boxpencolor) {
QColor qc = QColorDialog::getColor(os.qcBoxPen, e->widget(), tr("Pick pen color"), QColorDialog::DontUseNativeDialog | QColorDialog::ShowAlphaChannel);
if (! qc.isValid())
return;
os.qcBoxPen = qc;
moveBox();
} else if (act == boxfillcolor) {
QColor qc = QColorDialog::getColor(os.qcBoxFill, e->widget(), tr("Pick fill color"), QColorDialog::DontUseNativeDialog | QColorDialog::ShowAlphaChannel);
if (! qc.isValid())
return;
os.qcBoxFill = qc;
moveBox();
} else if (act == color) {
QColor *col = NULL;
if (item == qgpiChannel)
col = & os.qcChannel;
else if (item == qgpiName)
col = & os.qcUserName[tsColor];
if (! col)
return;
QColor qc = QColorDialog::getColor(*col, e->widget(), tr("Pick color"), QColorDialog::DontUseNativeDialog);
if (! qc.isValid())
return;
qc.setAlpha(255);
if (qc == *col)
return;
*col = qc;
updateSelected();
} else if (act == fontAction) {
QFont *fontptr = (item == qgpiChannel) ? &os.qfChannel : &os.qfUserName;
qgpiSelected = NULL;
qgriSelected->hide();
// QFontDialog doesn't really like graphics view. At all.
QFontDialog qfd;
qfd.setOptions(QFontDialog::DontUseNativeDialog);
qfd.setCurrentFont(*fontptr);
qfd.setWindowTitle(tr("Pick font"));
int ret;
if (g.ocIntercept) {
QGraphicsProxyWidget *qgpw = new QGraphicsProxyWidget(NULL, Qt::Window);
qgpw->setWidget(&qfd);
addItem(qgpw);
qgpw->setZValue(3.0f);
qgpw->setPanelModality(QGraphicsItem::PanelModal);
qgpw->setPos(- qgpw->boundingRect().width() / 2.0f, - qgpw->boundingRect().height() / 2.0f);
qgpw->show();
ret = qfd.exec();
qgpw->hide();
qgpw->setWidget(NULL);
delete qgpw;
} else {
Qt::WindowFlags wf = g.mw->windowFlags();
if (wf.testFlag(Qt::WindowStaysOnTopHint))
qfd.setWindowFlags(qfd.windowFlags() | Qt::WindowStaysOnTopHint);
ret = qfd.exec();
}
if (! ret)
return;
*fontptr = qfd.selectedFont();
resync();
} else if (act == qaLayoutLargeAvatar) {
os.setPreset(OverlaySettings::LargeSquareAvatar);
resync();
} else if (act == qaLayoutText) {
os.setPreset(OverlaySettings::AvatarAndName);
resync();
}
}
static qreal distancePointLine(const QPointF &a, const QPointF &b, const QPointF &p) {
qreal xda = a.x() - p.x();
qreal xdb = p.x() - b.x();
qreal xd = 0;
if (xda > 0)
xd = xda;
if (xdb > 0)
xd = qMax(xd, xdb);
qreal yda = a.y() - p.y();
qreal ydb = p.y() - b.y();
qreal yd = 0;
if (yda > 0)
yd = yda;
if (ydb > 0)
yd = qMax(yd, ydb);
return qMax(xd, yd);
}
Qt::WindowFrameSection OverlayEditorScene::rectSection(const QRectF &qrf, const QPointF &qp, qreal dist) {
qreal left, right, top, bottom;
top = distancePointLine(qrf.topLeft(), qrf.topRight(), qp);
bottom = distancePointLine(qrf.bottomLeft(), qrf.bottomRight(), qp);
left = distancePointLine(qrf.topLeft(), qrf.bottomLeft(), qp);
right = distancePointLine(qrf.topRight(), qrf.bottomRight(), qp);
if ((top < dist) && (top < bottom)) {
if ((left < dist) && (left < right))
return Qt::TopLeftSection;
else if (right < dist)
return Qt::TopRightSection;
return Qt::TopSection;
} else if (bottom < dist) {
if ((left < dist) && (left < right))
return Qt::BottomLeftSection;
else if (right < dist)
return Qt::BottomRightSection;
return Qt::BottomSection;
} else if (left < dist) {
return Qt::LeftSection;
} else if (right < dist) {
return Qt::RightSection;
}
if (qrf.contains(qp))
return Qt::TitleBarArea;
return Qt::NoSection;
}
| 27.564719
| 276
| 0.664977
|
JoelTroch
|
05b4cfdde4aa27055466888a7420912deb00023a
| 460
|
cpp
|
C++
|
AOJ/ITP1/07B_How_many_ways.cpp
|
tyokinuhata/procon
|
d0a8439f961c7b28b74201c65cc3c603011a94dc
|
[
"MIT"
] | 1
|
2019-04-18T02:25:05.000Z
|
2019-04-18T02:25:05.000Z
|
AOJ/ITP1/07B_How_many_ways.cpp
|
tyokinuhata/procon
|
d0a8439f961c7b28b74201c65cc3c603011a94dc
|
[
"MIT"
] | 1
|
2018-06-27T08:00:07.000Z
|
2018-06-27T08:00:07.000Z
|
AOJ/ITP1/07B_How_many_ways.cpp
|
tyokinuhata/procon
|
d0a8439f961c7b28b74201c65cc3c603011a94dc
|
[
"MIT"
] | null | null | null |
#include <iostream>
using namespace std;
int main () {
int n, x;
while (true) {
cin >> n >> x;
if (n == 0 && x == 0) break;
int cnt = 0;
for (int i = 1; i <= n - 2; i++) {
for (int j = i + 1; j <= n - 1; j++) {
for (int k = j + 1; k <= n; k++) {
if (i + j + k == x) cnt++;
}
}
}
cout << cnt << endl;
cnt = 0;
}
}
| 20
| 50
| 0.297826
|
tyokinuhata
|
05c8b3124e4298abcd65c09fd63d3274b1863c06
| 3,588
|
hpp
|
C++
|
pyjac/kernel_utils/c/memcpy_2d.hpp
|
stgeke/pyJac-v2
|
c2716a05df432efd8e5f6cc5cc3d46b72c24c019
|
[
"MIT"
] | 9
|
2018-10-08T07:49:20.000Z
|
2021-06-26T15:28:30.000Z
|
pyjac/kernel_utils/c/memcpy_2d.hpp
|
stgeke/pyJac-v2
|
c2716a05df432efd8e5f6cc5cc3d46b72c24c019
|
[
"MIT"
] | 13
|
2018-09-01T14:17:51.000Z
|
2021-07-30T16:19:33.000Z
|
pyjac/kernel_utils/c/memcpy_2d.hpp
|
arghdos/spyJac
|
bdd6940c27681e3b19ee41efb31abd20a89d1be8
|
[
"MIT"
] | 7
|
2018-09-08T11:57:34.000Z
|
2022-02-14T13:57:20.000Z
|
/**
* memcpy_2d.h
*
* \author Nick Curtis
* \date 2017
*
* Simple 2D memcopy function to enable strided copy of state vectors
* for cases where the maximum allowable number of initial conditions is
* _less_ than the total number of conditions to be tested
*
*/
#ifndef MEMCPY2D_H
#define MEMCPY2D_H
#include <stdlib.h>
#include <string.h>
/**
* \brief A convienience method to copy memory between host pointers of different pitches, widths and heights.
*
* \param[out] dst The destination array
* \param[in] pitch_dst The width (in number of elements) of the destination array.
This corresponds to the padded number of IVPs to be solved.
* \param[in] src The source pointer
* \param[in] pitch_src The width (in number of elements) of the source array.
This corresponds to the (non-padded) number of IVPs read by read_initial_conditions
* \param[in] offset The offset within the source array (IVP index) to copy from.
This is useful in the case (for large models) where the solver and state vector memory will not fit in device memory
and the integration must be split into multiple kernel calls.
* \param[in] width The size (in bytes) of memory to copy for each entry in the state vector
* \param[in] height The number of entries in the state vector
*/
static inline void memcpy2D_in(double* dst, const int pitch_dst, double const * src, const int pitch_src,
const int offset, const size_t width, const int height) {
for (int i = 0; i < height; ++i)
{
memcpy(dst, &src[offset], width);
dst += pitch_dst;
src += pitch_src;
}
}
/**
* \brief A convienience method to copy memory between host pointers of different pitches, widths and heights.
*
* \param[out] dst The destination array
* \param[in] pitch_dst The width (in number of elements) of the source array.
This corresponds to the (non-padded) number of IVPs read by read_initial_conditions
* \param[in] src The source pointer
* \param[in] pitch_src The width (in number of elements) of the destination array.
This corresponds to the padded number of IVPs to be solved.
* \param[in] offset The offset within the destination array (IVP index) to copy to.
This is useful in the case (for large models) where the solver and state vector memory will not fit in device memory
and the integration must be split into multiple kernel calls.
* \param[in] width The size (in bytes) of memory to copy for each entry in the state vector
* \param[in] height The number of entries in the state vector
*/
static inline void memcpy2D_out(double* dst, const int pitch_dst, double const * src, const int pitch_src,
const int offset, const size_t width, const int height) {
for (int i = 0; i < height; ++i)
{
memcpy(&dst[offset], src, width);
dst += pitch_dst;
src += pitch_src;
}
}
#endif
| 50.535211
| 160
| 0.571906
|
stgeke
|
05c8f7f43074ff0999305b2df26ba879fe288db2
| 6,759
|
cpp
|
C++
|
TOMB5/game/willwisp.cpp
|
walkawayy/TOMB5
|
cc33d5147ed21c8db123a72f4acdc9241e3ed73c
|
[
"MIT"
] | null | null | null |
TOMB5/game/willwisp.cpp
|
walkawayy/TOMB5
|
cc33d5147ed21c8db123a72f4acdc9241e3ed73c
|
[
"MIT"
] | null | null | null |
TOMB5/game/willwisp.cpp
|
walkawayy/TOMB5
|
cc33d5147ed21c8db123a72f4acdc9241e3ed73c
|
[
"MIT"
] | null | null | null |
#include "../tomb5/pch.h"
#include "willwisp.h"
#include "box.h"
#include "objects.h"
#include "../specific/3dmath.h"
#include "sound.h"
#include "effect2.h"
#include "control.h"
#include "sphere.h"
#include "tomb4fx.h"
#include "lot.h"
#include "items.h"
#include "../specific/function_stubs.h"
#include "effects.h"
static BITE_INFO mazemonster_hitright = {0, 0, 0, 22};
static BITE_INFO mazemonster_hitleft = {0, 0, 0, 16};
void InitialiseWillOWisp(short item_number)
{
ITEM_INFO* item;
item = &items[item_number];
InitialiseCreature(item_number);
item->anim_number = objects[WILLOWISP].anim_index;
item->frame_number = anims[item->anim_number].frame_base;
item->goal_anim_state = 1;
item->current_anim_state = 1;
}
void WillOWispControl(short item_number)
{
ITEM_INFO* item;
CREATURE_INFO* willowisp;
FLOOR_INFO* floor;
PHD_VECTOR pos;
AI_INFO info, lara_info;
long lara_dx, lara_dz, height, ceiling;
short angle, tilt, room_number, lightlevel, x;
//short torso_y, torso_x, head;
if (CreatureActive(item_number))
{
tilt = 0;
item = &items[item_number];
willowisp = (CREATURE_INFO*) item->data;
item->ai_bits = 0x10;
if (willowisp->reached_goal)
{
item->item_flags[3]++;
willowisp->reached_goal = 0;
willowisp->enemy = NULL;
}
if (item->ai_bits)
GetAITarget(willowisp);
else if (willowisp->hurt_by_lara)
willowisp->enemy = lara_item;
CreatureAIInfo(item, &info);
if (willowisp->enemy == lara_item)
lara_info.distance = info.distance;
else
{
lara_dx = lara_item->pos.x_pos - item->pos.x_pos;
lara_dz = lara_item->pos.z_pos - item->pos.z_pos;
phd_atan(lara_dz, lara_dx);
lara_info.distance = SQUARE(lara_dx) + SQUARE(lara_dz);
}
GetCreatureMood(item, &info, 1);
CreatureMood(item, &info, 1);
angle = CreatureTurn(item, willowisp->maximum_turn);
willowisp->maximum_turn = 1274;
if (lara_info.distance <= 1863225 && ABS((int) (item->pos.y_pos - lara_item->pos.y_pos <= 1024)) && !willowisp->reached_goal)
item->goal_anim_state = 2;
else
item->goal_anim_state = 1;
if (item->current_anim_state == 1)
willowisp->reached_goal = 0;
SoundEffect(239, &item->pos, 0);
lightlevel = (GetRandomControl() & 0x1F) - (item->item_flags[0] >> 2) + 48;
for (int i = 0; i < 3; i++)
{
pos.x = 0;
pos.y = 0;
pos.z = 200;
GetJointAbsPosition(item, &pos, i + 1);
TriggerLightningGlow(pos.x, pos.y, pos.z, RGBA(48, 48, 64, lightlevel));
}
TriggerDynamic(item->pos.x_pos, item->pos.y_pos, item->pos.z_pos, 15, lightlevel + 12, lightlevel + 12, lightlevel + 16);
room_number = item->room_number;
floor = GetFloor(item->pos.x_pos, item->pos.y_pos, item->pos.z_pos, &room_number);
height = GetHeight(floor, item->pos.x_pos, item->pos.y_pos, item->pos.z_pos);
ceiling = GetCeiling(floor, item->pos.x_pos, item->pos.y_pos, item->pos.z_pos);
if (item->pos.y_pos > height - 512)
item->pos.y_pos = height - 512;
else if (item->pos.y_pos < ceiling + 768)
item->pos.y_pos = ceiling + 768;
CreatureAnimation(item_number, angle, tilt);
if (willowisp->enemy == lara_item)
{
x = item->item_flags[0];
item->item_flags[0]++;
if (x > 191)
{
item->hit_points = -16384;
DisableBaddieAI(item_number);
KillItem(item_number);
}
}
}
}
void InitialiseMazeMonster(short item_number)
{
ITEM_INFO* item;
item = &items[item_number];
InitialiseCreature(item_number);
item->anim_number = objects[MAZE_MONSTER].anim_index;
item->frame_number = anims[item->anim_number].frame_base;
item->goal_anim_state = 1;
item->current_anim_state = 1;
}
void MazeMonsterControl(short item_number)
{
ITEM_INFO* item;
CREATURE_INFO* monster;
AI_INFO info;
long distance, dx, dz;
short angle, anim, frame;
if (CreatureActive(item_number))
{
item = &items[item_number];
monster = (CREATURE_INFO*) item->data;
angle = 0;
anim = objects[MAZE_MONSTER].anim_index;
if (item->hit_points <= 0)
{
item->hit_points = 0;
if (item->current_anim_state != 7)
{
item->anim_number = anim + 10;
item->frame_number = anims[item->anim_number].frame_base;
item->current_anim_state = 7;
}
}
else
{
if (item->ai_bits)
GetAITarget(monster);
else if (monster->hurt_by_lara)
monster->enemy = lara_item;
CreatureAIInfo(item, &info);
if (monster->enemy == lara_item)
distance = info.distance;
else
{
dx = lara_item->pos.x_pos - item->pos.x_pos;
dz = lara_item->pos.z_pos - item->pos.z_pos;
phd_atan(dz, dx);
distance = SQUARE(dx) + SQUARE(dz);
}
GetCreatureMood(item, &info, 1);
CreatureMood(item, &info, 1);
angle = CreatureTurn(item, monster->maximum_turn);
monster->maximum_turn = 1274;
switch (item->current_anim_state)
{
case 1:
monster->flags = 0;
if (monster->mood != ATTACK_MOOD)
item->goal_anim_state = 1;
else if (distance > 1048576)
item->goal_anim_state = GetRandomControl() & 1 ? 2 : 3;
else
item->goal_anim_state = GetRandomControl() & 1 ? 4 : 6;
break;
case 2:
case 3:
if (distance < 1048576 || monster->mood != ATTACK_MOOD)
item->goal_anim_state = 1;
SoundEffect(SFX_IMP_BARREL_ROLL, &item->pos, SFX_DEFAULT);
break;
case 4:
case 6:
monster->maximum_turn = 0;
if (ABS(info.angle) < 364)
item->pos.y_rot += info.angle;
else if (info.angle < 0)
item->pos.y_rot -= 364;
else
item->pos.y_rot += 364;
if (!monster->flags)
{
frame = anims[item->anim_number].frame_base;
if (item->touch_bits & 0x3C000 &&
(item->anim_number == anim + 8 && item->frame_number > frame + 19 && item->frame_number < frame + 25 ||
item->anim_number == anim + 2 && item->frame_number > frame + 6 && item->frame_number < frame + 16))
{
CreatureEffectT(item, &mazemonster_hitleft, 20, item->pos.y_rot, DoBloodSplat);
lara_item->hit_points -= 150;
lara_item->hit_status = 1;
monster->flags |= 1;
}
else if (item->touch_bits & 0xF00000 &&
(item->anim_number == anim + 8 && item->frame_number > frame + 13 && item->frame_number < frame + 20 ||
item->anim_number == anim + 2 && item->frame_number > frame + 33 && item->frame_number < frame + 43))
{
CreatureEffectT(item, &mazemonster_hitright, 20, item->pos.y_rot, DoBloodSplat);
lara_item->hit_points -= 150;
lara_item->hit_status = 1;
monster->flags |= 2;
}
}
break;
}
}
CreatureAnimation(item_number, angle, 0);
}
}
void inject_wisp(bool replace)
{
INJECT(0x0048E500, InitialiseWillOWisp, replace);
INJECT(0x0048E580, WillOWispControl, replace);
INJECT(0x0048E8E0, InitialiseMazeMonster, replace);
INJECT(0x0048E960, MazeMonsterControl, replace);
}
| 25.896552
| 127
| 0.660749
|
walkawayy
|
05cc2d169818d66a47bf2133326c658b2e317820
| 12,446
|
cpp
|
C++
|
tests/hdf5.cpp
|
embarktrucks/armadillo-code
|
edfce747962f8ad508db660caa3892ed1a4069f8
|
[
"Apache-2.0"
] | 11
|
2017-08-31T16:38:39.000Z
|
2022-03-26T03:45:12.000Z
|
tests/hdf5.cpp
|
embarktrucks/armadillo-code
|
edfce747962f8ad508db660caa3892ed1a4069f8
|
[
"Apache-2.0"
] | 1
|
2017-03-14T02:27:16.000Z
|
2017-03-14T02:27:16.000Z
|
tests/hdf5.cpp
|
embarktrucks/armadillo-code
|
edfce747962f8ad508db660caa3892ed1a4069f8
|
[
"Apache-2.0"
] | 4
|
2017-08-08T18:18:06.000Z
|
2020-10-02T02:03:06.000Z
|
// Copyright 2011-2017 Ryan Curtin (http://www.ratml.org/)
// Copyright 2017 National ICT Australia (NICTA)
//
// 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 <armadillo>
#include "catch.hpp"
using namespace arma;
#if defined(ARMA_USE_HDF5)
TEST_CASE("hdf5_u8_test")
{
arma::Mat<u8> a;
a.randu(20, 20);
// Save first.
a.save("file.h5", hdf5_binary);
// Load as different matrix.
arma::Mat<u8> b;
b.load("file.h5", hdf5_binary);
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == b[i] );
}
// Now autoload.
arma::Mat<u8> c;
c.load("file.h5");
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == c[i] );
}
remove("file.h5");
}
TEST_CASE("hdf5_u16_test")
{
arma::Mat<u16> a;
a.randu(20, 20);
// Save first.
a.save("file.h5", hdf5_binary);
// Load as different matrix.
arma::Mat<u16> b;
b.load("file.h5", hdf5_binary);
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == b[i] );
}
// Now autoload.
arma::Mat<u16> c;
c.load("file.h5");
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == c[i] );
}
remove("file.h5");
}
TEST_CASE("hdf5_u32_test")
{
arma::Mat<u32> a;
a.randu(20, 20);
// Save first.
a.save("file.h5", hdf5_binary);
// Load as different matrix.
arma::Mat<u32> b;
b.load("file.h5", hdf5_binary);
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == b[i] );
}
// Now autoload.
arma::Mat<u32> c;
c.load("file.h5");
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == c[i] );
}
remove("file.h5");
}
#ifdef ARMA_USE_U64S64
TEST_CASE("hdf5_u64_test")
{
arma::Mat<u64> a;
a.randu(20, 20);
// Save first.
a.save("file.h5", hdf5_binary);
// Load as different matrix.
arma::Mat<u64> b;
b.load("file.h5", hdf5_binary);
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == b[i] );
}
// Now autoload.
arma::Mat<u64> c;
c.load("file.h5");
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == c[i] );
}
remove("file.h5");
}
#endif
TEST_CASE("hdf5_s8_test")
{
arma::Mat<s8> a;
a.randu(20, 20);
// Save first.
a.save("file.h5", hdf5_binary);
// Load as different matrix.
arma::Mat<s8> b;
b.load("file.h5", hdf5_binary);
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == b[i] );
}
// Now autoload.
arma::Mat<s8> c;
c.load("file.h5");
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == c[i] );
}
remove("file.h5");
}
TEST_CASE("hdf5_s16_test")
{
arma::Mat<s16> a;
a.randu(20, 20);
// Save first.
a.save("file.h5", hdf5_binary);
// Load as different matrix.
arma::Mat<s16> b;
b.load("file.h5", hdf5_binary);
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == b[i] );
}
// Now autoload.
arma::Mat<s16> c;
c.load("file.h5");
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == c[i] );
}
remove("file.h5");
}
TEST_CASE("hdf5_s32_test")
{
arma::Mat<s32> a;
a.randu(20, 20);
// Save first.
a.save("file.h5", hdf5_binary);
// Load as different matrix.
arma::Mat<s32> b;
b.load("file.h5", hdf5_binary);
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == b[i] );
}
// Now autoload.
arma::Mat<s32> c;
c.load("file.h5");
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == c[i] );
}
remove("file.h5");
}
#ifdef ARMA_USE_U64S64
TEST_CASE("hdf5_s64_test")
{
arma::Mat<s64> a;
a.randu(20, 20);
// Save first.
a.save("file.h5", hdf5_binary);
// Load as different matrix.
arma::Mat<s64> b;
b.load("file.h5", hdf5_binary);
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == b[i] );
}
// Now autoload.
arma::Mat<s64> c;
c.load("file.h5");
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == c[i] );
}
remove("file.h5");
}
#endif
TEST_CASE("hdf5_char_test")
{
arma::Mat<char> a;
a.randu(20, 20);
// Save first.
a.save("file.h5", hdf5_binary);
// Load as different matrix.
arma::Mat<char> b;
b.load("file.h5", hdf5_binary);
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == b[i] );
}
// Now autoload.
arma::Mat<char> c;
c.load("file.h5");
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == c[i] );
}
remove("file.h5");
}
TEST_CASE("hdf5_int_test")
{
arma::Mat<signed int> a;
a.randu(20, 20);
// Save first.
a.save("file.h5", hdf5_binary);
// Load as different matrix.
arma::Mat<signed int> b;
b.load("file.h5", hdf5_binary);
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == b[i] );
}
// Now autoload.
arma::Mat<signed int> c;
c.load("file.h5");
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == c[i] );
}
remove("file.h5");
}
TEST_CASE("hdf5_uint_test")
{
arma::Mat<unsigned int> a;
a.randu(20, 20);
// Save first.
a.save("file.h5", hdf5_binary);
// Load as different matrix.
arma::Mat<unsigned int> b;
b.load("file.h5", hdf5_binary);
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == b[i] );
}
// Now autoload.
arma::Mat<unsigned int> c;
c.load("file.h5");
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == c[i] );
}
remove("file.h5");
}
TEST_CASE("hdf5_short_test")
{
arma::Mat<signed short> a;
a.randu(20, 20);
// Save first.
a.save("file.h5", hdf5_binary);
// Load as different matrix.
arma::Mat<signed short> b;
b.load("file.h5", hdf5_binary);
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == b[i] );
}
// Now autoload.
arma::Mat<signed short> c;
c.load("file.h5");
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == c[i] );
}
remove("file.h5");
}
TEST_CASE("hdf5_ushort_test")
{
arma::Mat<unsigned short> a;
a.randu(20, 20);
// Save first.
a.save("file.h5", hdf5_binary);
// Load as different matrix.
arma::Mat<unsigned short> b;
b.load("file.h5", hdf5_binary);
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == b[i] );
}
// Now autoload.
arma::Mat<unsigned short> c;
c.load("file.h5");
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == c[i] );
}
remove("file.h5");
}
TEST_CASE("hdf5_long_test")
{
arma::Mat<signed long> a;
a.randu(20, 20);
// Save first.
a.save("file.h5", hdf5_binary);
// Load as different matrix.
arma::Mat<signed long> b;
b.load("file.h5", hdf5_binary);
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == b[i] );
}
// Now autoload.
arma::Mat<signed long> c;
c.load("file.h5");
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == c[i] );
}
remove("file.h5");
}
TEST_CASE("hdf5_ulong_test")
{
arma::Mat<unsigned long> a;
a.randu(20, 20);
// Save first.
a.save("file.h5", hdf5_binary);
// Load as different matrix.
arma::Mat<unsigned long> b;
b.load("file.h5", hdf5_binary);
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == b[i] );
}
// Now autoload.
arma::Mat<unsigned long> c;
c.load("file.h5");
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == c[i] );
}
remove("file.h5");
}
#ifdef ARMA_USE_U64S64
TEST_CASE("hdf5_llong_test")
{
arma::Mat<signed long long> a;
a.randu(20, 20);
// Save first.
a.save("file.h5", hdf5_binary);
// Load as different matrix.
arma::Mat<signed long long> b;
b.load("file.h5", hdf5_binary);
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == b[i] );
}
// Now autoload.
arma::Mat<signed long long> c;
c.load("file.h5");
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == c[i] );
}
remove("file.h5");
}
TEST_CASE("hdf5_ullong_test")
{
arma::Mat<unsigned long long> a;
a.randu(20, 20);
// Save first.
a.save("file.h5", hdf5_binary);
// Load as different matrix.
arma::Mat<unsigned long long> b;
b.load("file.h5", hdf5_binary);
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == b[i] );
}
// Now autoload.
arma::Mat<unsigned long long> c;
c.load("file.h5");
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == c[i] );
}
remove("file.h5");
}
#endif
TEST_CASE("hdf5_float_test")
{
arma::Mat<float> a;
a.randu(20, 20);
// Save first.
a.save("file.h5", hdf5_binary);
// Load as different matrix.
arma::Mat<float> b;
b.load("file.h5", hdf5_binary);
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == b[i] );
}
// Now autoload.
arma::Mat<float> c;
c.load("file.h5");
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == c[i] );
}
remove("file.h5");
}
TEST_CASE("hdf5_double_test")
{
arma::Mat<double> a;
a.randu(20, 20);
// Save first.
a.save("file.h5", hdf5_binary);
// Load as different matrix.
arma::Mat<double> b;
b.load("file.h5", hdf5_binary);
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == b[i] );
}
// Now autoload.
arma::Mat<double> c;
c.load("file.h5");
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == c[i] );
}
remove("file.h5");
}
TEST_CASE("hdf5_complex_float_test")
{
arma::Mat<std::complex<float> > a;
a.randu(20, 20);
// Save first.
a.save("file.h5", hdf5_binary);
// Load as different matrix.
arma::Mat<std::complex<float> > b;
b.load("file.h5", hdf5_binary);
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == b[i] );
}
// Now autoload.
arma::Mat<std::complex<float> > c;
c.load("file.h5");
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == c[i] );
}
remove("file.h5");
}
TEST_CASE("hdf5_complex_double_test")
{
arma::Mat<std::complex<double> > a;
a.randu(20, 20);
// Save first.
a.save("file.h5", hdf5_binary);
// Load as different matrix.
arma::Mat<std::complex<double> > b;
b.load("file.h5", hdf5_binary);
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
REQUIRE( a[i] == b[i] );
// Now autoload.
arma::Mat<std::complex<double> > c;
c.load("file.h5");
// Check that they are the same.
for (uword i = 0; i < a.n_elem; ++i)
{
REQUIRE( a[i] == c[i] );
}
remove("file.h5");
}
#endif
| 17.286111
| 75
| 0.550217
|
embarktrucks
|
fe4aee51d806f723938b7ef0050e414eda3a9eb9
| 59
|
cpp
|
C++
|
test_package/test_package.cpp
|
Hopobcn/conan-cutlass
|
d6ba4c31562b56c1de3ce0df25daaad3755365ee
|
[
"MIT"
] | null | null | null |
test_package/test_package.cpp
|
Hopobcn/conan-cutlass
|
d6ba4c31562b56c1de3ce0df25daaad3755365ee
|
[
"MIT"
] | null | null | null |
test_package/test_package.cpp
|
Hopobcn/conan-cutlass
|
d6ba4c31562b56c1de3ce0df25daaad3755365ee
|
[
"MIT"
] | null | null | null |
#include <cutlass/cutlass.h>
int main()
{
return 0;
}
| 8.428571
| 28
| 0.610169
|
Hopobcn
|
fe4f16a266134c04e8466236a801e3afc70c0a13
| 1,063
|
cpp
|
C++
|
stack/test/tests/coh/testCohRequestMsg.cpp
|
shrewdlin/BPE
|
cf29647479b1b8ed53afadaf70557387f4c07e16
|
[
"BSD-3-Clause"
] | 1
|
2016-07-12T06:00:37.000Z
|
2016-07-12T06:00:37.000Z
|
stack/test/tests/coh/testCohRequestMsg.cpp
|
shrewdlin/BPE
|
cf29647479b1b8ed53afadaf70557387f4c07e16
|
[
"BSD-3-Clause"
] | null | null | null |
stack/test/tests/coh/testCohRequestMsg.cpp
|
shrewdlin/BPE
|
cf29647479b1b8ed53afadaf70557387f4c07e16
|
[
"BSD-3-Clause"
] | 2
|
2016-09-06T07:59:09.000Z
|
2020-12-12T03:25:24.000Z
|
#include <boost/test/unit_test.hpp>
#include "CohRequestMsg.h"
using namespace sdo::coh;
BOOST_AUTO_TEST_SUITE(test_cohrequestmsg)
BOOST_AUTO_TEST_CASE(test_parser)
{
CCohRequestMsg msg;
msg.SetUrl("http://192.168.0.3/SetLog");
BOOST_CHECK_EQUAL(msg.GetIp(),"192.168.0.3");
BOOST_CHECK_EQUAL(msg.GetPort(),(unsigned int)80);
msg.SetUrl("http://192.168.0.3:8090/SetLog");
BOOST_CHECK_EQUAL(msg.GetPort(),(unsigned int)8090);
msg.SetAttribute("test1", "value1");
msg.SetAttribute("test2", 20);
msg.SetAttribute("test3","aa");
msg.SetAttribute("test3","bb");
msg.Decode(msg.Encode());
BOOST_CHECK_EQUAL(msg.GetCommand(),"SetLog");
BOOST_CHECK_EQUAL(msg.GetAttribute("test1"),"value1");
BOOST_CHECK_EQUAL(msg.GetAttribute("test2"),"20");
vector<string> vecCoh=msg.GetAttributes("test3");
vector<string>::iterator itr=vecCoh.begin();
string strV1=*itr++;
string strV2=*itr++;
BOOST_CHECK_EQUAL(strV1,string("aa"));
BOOST_CHECK(strV2=="bb");
}
BOOST_AUTO_TEST_SUITE_END()
| 27.973684
| 58
| 0.687676
|
shrewdlin
|
fe528f57febbc3ce32384ecc4b1929d8a0918c44
| 1,801
|
cc
|
C++
|
src/developer/forensics/feedback_data/device_id_provider.cc
|
JokeZhang/fuchsia
|
d6e9dea8dca7a1c8fa89d03e131367e284b30d23
|
[
"BSD-3-Clause"
] | 1
|
2021-09-09T12:25:41.000Z
|
2021-09-09T12:25:41.000Z
|
src/developer/forensics/feedback_data/device_id_provider.cc
|
JokeZhang/fuchsia
|
d6e9dea8dca7a1c8fa89d03e131367e284b30d23
|
[
"BSD-3-Clause"
] | null | null | null |
src/developer/forensics/feedback_data/device_id_provider.cc
|
JokeZhang/fuchsia
|
d6e9dea8dca7a1c8fa89d03e131367e284b30d23
|
[
"BSD-3-Clause"
] | null | null | null |
// Copyright 2020 The Fuchsia 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/developer/forensics/feedback_data/device_id_provider.h"
#include <lib/syslog/cpp/macros.h>
#include <optional>
#include "src/developer/forensics/utils/errors.h"
#include "src/lib/files/directory.h"
#include "src/lib/files/file.h"
#include "src/lib/fxl/strings/string_printf.h"
#include "src/lib/uuid/uuid.h"
namespace forensics {
namespace feedback_data {
namespace {
// Reads a device id from the file at |path|. If the device id doesn't exist or is invalid, return
// a nullopt.
std::optional<std::string> ReadDeviceId(const std::string& path) {
std::string id;
if (!files::ReadFileToString(path, &id)) {
return std::nullopt;
}
return id;
}
// Creates a new device id and stores it at |path|.
//
// The id is a 128-bit (pseudo) random UUID in the form of version 4 as described in RFC 4122,
// section 4.4.
std::string InitializeDeviceId(const std::string& path) {
if (const auto read_id = ReadDeviceId(path);
read_id.has_value() && uuid::IsValid(read_id.value())) {
return read_id.value();
}
std::string new_id = uuid::Generate();
if (!files::WriteFile(path, new_id.c_str(), new_id.size())) {
FX_LOGS(ERROR) << fxl::StringPrintf("Cannot write device id '%s' to '%s'", new_id.c_str(),
path.c_str());
}
FX_LOGS(INFO) << "Created new feedback device id";
return new_id;
}
} // namespace
DeviceIdProvider::DeviceIdProvider(const std::string& path)
: device_id_(InitializeDeviceId(path)) {}
void DeviceIdProvider::GetId(GetIdCallback callback) { callback(device_id_); }
} // namespace feedback_data
} // namespace forensics
| 29.52459
| 98
| 0.694059
|
JokeZhang
|
fe52fa6dbf4f8ec46a71486c99dce01779201b66
| 711
|
cpp
|
C++
|
Projects/CoX/Clients/Client_I0/patch_all_the_things.cpp
|
HeraldOfOmega/Segs
|
0de876d7c28481dc2eab743781e86141be0fc8ba
|
[
"BSD-3-Clause"
] | 1
|
2019-02-19T02:52:29.000Z
|
2019-02-19T02:52:29.000Z
|
Projects/CoX/Clients/Client_I0/patch_all_the_things.cpp
|
HeraldOfOmega/Segs
|
0de876d7c28481dc2eab743781e86141be0fc8ba
|
[
"BSD-3-Clause"
] | null | null | null |
Projects/CoX/Clients/Client_I0/patch_all_the_things.cpp
|
HeraldOfOmega/Segs
|
0de876d7c28481dc2eab743781e86141be0fc8ba
|
[
"BSD-3-Clause"
] | 1
|
2021-04-13T16:04:08.000Z
|
2021-04-13T16:04:08.000Z
|
#include "patch_all_the_things.h"
#include "entity/entityDebug.h"
#include "renderer/RendererUtils.h"
#include "renderer/RenderTricks.h"
#include "renderer/RenderBonedModel.h"
#include "renderer/RenderModel.h"
#include "renderer/RendererState.h"
#include "renderer/RenderShadow.h"
#include "renderer/RenderSprites.h"
#include "renderer/RenderTree.h"
#include "renderer/Texture.h"
#include "graphics/gfx.h"
void patch_all_the_things()
{
patch_gfx();
patch_render_utils();
patch_rendertricks();
patch_render_state();
patch_textures();
patch_render_model();
patch_render_node();
patch_shadow_renderer();
patch_rendertree();
patch_ent_debug();
patch_rendersprites();
}
| 24.517241
| 38
| 0.745429
|
HeraldOfOmega
|
fe52fb262931d41160ccf7ea7f4ed2e908574e26
| 11,997
|
hpp
|
C++
|
include/cynodelic/tesela/rgba_types.hpp
|
cynodelic/tesela
|
3b86a7b9501c7136d5168c7e314740fa7f72f7a7
|
[
"BSL-1.0"
] | null | null | null |
include/cynodelic/tesela/rgba_types.hpp
|
cynodelic/tesela
|
3b86a7b9501c7136d5168c7e314740fa7f72f7a7
|
[
"BSL-1.0"
] | null | null | null |
include/cynodelic/tesela/rgba_types.hpp
|
cynodelic/tesela
|
3b86a7b9501c7136d5168c7e314740fa7f72f7a7
|
[
"BSL-1.0"
] | null | null | null |
// Copyright (c) 2019 Álvaro Ceballos
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt
/**
* @file rgba_types.hpp
*
* @brief Defines RGBA pixel types.
*/
#ifndef CYNODELIC_TESELA_RGBA_TYPES_HPP
#define CYNODELIC_TESELA_RGBA_TYPES_HPP
#include <istream>
#include <ostream>
#include <sstream>
#include <cstdlib>
#include <cstddef>
#include <cstdint>
#include <utility>
#include <cynodelic/tesela/config.hpp>
#include <cynodelic/tesela/detail/utils.hpp>
#include <cynodelic/tesela/color_space.hpp>
#include <cynodelic/tesela/tdouble.hpp>
namespace cynodelic { namespace tesela {
/**
* @ingroup pixeltypes
* @brief RGBA pixel type
*
* An RGBA pixel type, with values between 0 and 255.
*/
struct rgba_t
{
/// @brief Reference to itself
using type = rgba_t;
/// @brief Type used for each component
using component_type = std::uint8_t;
/// @brief The corresponding color space
static constexpr color_space pixel_color_space = color_space::rgba;
/// @brief Red
component_type red;
/// @brief Green
component_type green;
/// @brief Blue
component_type blue;
/// @brief Alpha
component_type alpha;
/**
* @brief Default constructor
*
* Initializes with default RGBA values (0,0,0,0).
*/
constexpr rgba_t() :
red(0x00), green(0x00), blue(0x00), alpha(0x00)
{}
/**
* @brief Initialize with brightness
*
* Initializes with a brightness value @c y (y,y,y,255).
*
* @param y Brightness.
*/
constexpr rgba_t(const component_type& y) :
red(y), green(y), blue(y), alpha(0xff)
{}
/**
* @brief Initialize with brightness and alpha
*
* Initializes with brightness and alpha values (y,y,y,a).
*
* @param y Brightness.
* @param a Alpha.
*/
constexpr rgba_t(const component_type& y,const component_type& a) :
red(y), green(y), blue(y), alpha(a)
{}
/**
* @brief RGB initializer
*
* Initializes with values for red, green and blue channels (r,g,b,255).
*
* @param r Red.
* @param g Green.
* @param b Blue.
*/
constexpr rgba_t(const component_type& r,const component_type& g,const component_type& b) :
red(r), green(g), blue(b), alpha(0xff)
{}
/**
* @brief RGBA initializer
*
* Initializes with values for red, green, blue and alpha channels (r,g,b,a).
*
* @param r Red.
* @param g Green.
* @param b Blue.
* @param a Alpha.
*/
constexpr rgba_t(const component_type& r,const component_type& g,const component_type& b,const component_type& a) :
red(r), green(g), blue(b), alpha(a)
{}
/**
* @brief Copy assignment operator
*
* Replaces the contents of a @ref rgba_t with those of `other`.
*/
rgba_t& operator=(const rgba_t& other)
{
red = other.red;
green = other.green;
blue = other.blue;
alpha = other.alpha;
return *this;
}
/**
* @brief Sets red value
*
* Sets a value for the red component.
*
* @param new_r The new value.
*/
rgba_t& set_red(const component_type& new_r)
{
red = new_r;
return *this;
}
/**
* @brief Sets green value
*
* Sets a value for the green component.
*
* @param new_g The new value.
*/
rgba_t& set_green(const component_type& new_g)
{
green = new_g;
return *this;
}
/**
* @brief Sets blue value
*
* Sets a value for the blue component.
*
* @param new_b The new value.
*/
rgba_t& set_blue(const component_type& new_b)
{
blue = new_b;
return *this;
}
/**
* @brief Sets alpha value
*
* Sets a value for the alpha component.
*
* @param new_a The new value.
*/
rgba_t& set_alpha(const component_type& new_a)
{
alpha = new_a;
return *this;
}
/**
* @brief Equality operator
*
* Checks if two @ref rgba_t s are equal.
*/
constexpr friend bool operator==(const rgba_t& lhs,const rgba_t& rhs)
{
return (lhs.red == rhs.red) && (lhs.green == rhs.green) && (lhs.blue == rhs.blue) && (lhs.alpha == rhs.alpha);
}
/**
* @brief Inequality operator
*
* Checks if two @ref rgba_t s are not equal.
*/
constexpr friend bool operator!=(const rgba_t& lhs,const rgba_t& rhs)
{
return !(lhs == rhs);
}
/**
* @brief Swaps the contents
*
* Swaps (exchanges) the contents with those of `other`.
*/
void swap(rgba_t& other)
{
std::swap(red,other.red);
std::swap(green,other.green);
std::swap(blue,other.blue);
std::swap(alpha,other.alpha);
}
/**
* @brief Output stream operator
*
* Writes to an output stream.
*/
template <typename CharT,typename Traits>
friend std::basic_ostream<CharT,Traits>& operator<<(std::basic_ostream<CharT,Traits>& os,const rgba_t& out)
{
std::basic_ostringstream<CharT,Traits> ss;
ss.flags(os.flags());
ss.imbue(os.getloc());
ss.precision(os.precision());
ss << static_cast<unsigned>(out.red) << ' '
<< static_cast<unsigned>(out.green) << ' '
<< static_cast<unsigned>(out.blue) << ' '
<< static_cast<unsigned>(out.alpha);
return os << ss.str();
}
/**
* @brief Input stream operator
*
* Reads from an input stream.
*/
template <typename CharT,typename Traits>
friend std::basic_istream<CharT,Traits>& operator>>(std::basic_istream<CharT,Traits>& is,rgba_t& in)
{
unsigned aux_r, aux_g, aux_b, aux_a;
is >> aux_r >> std::ws
>> aux_g >> std::ws
>> aux_b >> std::ws
>> aux_a >> std::ws;
in = rgba_t(
static_cast<std::uint8_t>(aux_r),
static_cast<std::uint8_t>(aux_g),
static_cast<std::uint8_t>(aux_b),
static_cast<std::uint8_t>(aux_a)
);
return is;
}
};
constexpr color_space rgba_t::pixel_color_space;
/**
* @ingroup pixeltypes
* @brief Normalized RGBA pixel type
*
* An RGBA pixel type, with values between 0.0 and 1.0.
*/
struct nrgba_t
{
/// @brief Reference to itself
using type = nrgba_t;
/// @brief Type used for each component
using component_type = tdouble;
/// @brief The underlying type of the component type
using component_base_type = typename component_type::value_type;
/// @brief The corresponding color space
static constexpr color_space pixel_color_space = color_space::rgba;
/// @brief Red
component_type red;
/// @brief Green
component_type green;
/// @brief Blue
component_type blue;
/// @brief Alpha
component_type alpha;
/**
* @brief Default constructor
*
* Initializes with default RGBA values (0,0,0,0).
*/
constexpr nrgba_t() :
red(0.0), green(0.0), blue(0.0), alpha(0.0)
{}
/**
* @brief Initialize with brightness
*
* Initializes with a brightness value @c y (y,y,y,1.0).
*
* @param y Brightness.
*/
constexpr nrgba_t(const component_type& y) :
red(y), green(y), blue(y), alpha(1.0)
{}
/**
* @brief Initialize with brightness and alpha
*
* Initializes with brightness and alpha values (y,y,y,a).
*
* @param y Brightness.
* @param a Alpha.
*/
constexpr nrgba_t(const component_type& y,const component_type& a) :
red(y), green(y), blue(y), alpha(a)
{}
/**
* @brief RGB initializer
*
* Initializes with values for red, green and blue channels (r,g,b,255).
*
* @param r Red.
* @param g Green.
* @param b Blue.
*/
constexpr nrgba_t(const component_type& r,const component_type& g,const component_type& b) :
red(r), green(g), blue(b), alpha(1.0)
{}
/**
* @brief RGBA initializer
*
* Initializes with values for red, green, blue and alpha channels (r,g,b,a).
*
* @param r Red.
* @param g Green.
* @param b Blue.
* @param a Alpha.
*/
constexpr nrgba_t(const component_type& r,const component_type& g,const component_type& b,const component_type& a) :
red(r), green(g), blue(b), alpha(a)
{}
/**
* @brief Initialize with brightness
*
* Initializes with a brightness value @c y (y,y,y,1.0).
*
* @param y Brightness.
*/
constexpr nrgba_t(const component_base_type& y) :
red(y), green(y), blue(y), alpha(1.0)
{}
/**
* @brief Initialize with brightness and alpha
*
* Initializes with brightness and alpha values (y,y,y,a).
*
* @param y Brightness.
* @param a Alpha.
*/
constexpr nrgba_t(const component_base_type& y,const component_base_type& a) :
red(y), green(y), blue(y), alpha(a)
{}
/**
* @brief RGB initializer
*
* Initializes with values for red, green and blue channels (r,g,b,255).
*
* @param r Red.
* @param g Green.
* @param b Blue.
*/
constexpr nrgba_t(const component_base_type& r,const component_base_type& g,const component_base_type& b) :
red(r), green(g), blue(b), alpha(1.0)
{}
/**
* @brief RGBA initializer
*
* Initializes with values for red, green, blue and alpha channels (r,g,b,a).
*
* @param r Red.
* @param g Green.
* @param b Blue.
* @param a Alpha.
*/
constexpr nrgba_t(const component_base_type& r,const component_base_type& g,const component_base_type& b,const component_base_type& a) :
red(r), green(g), blue(b), alpha(a)
{}
/**
* @brief Copy constructor
*
* Initializes an @ref nrgba_t with the contents of `other`.
*/
constexpr nrgba_t(const nrgba_t& other) :
red(other.red),
green(other.green),
blue(other.blue),
alpha(other.alpha)
{}
/**
* @brief Copy assignment operator
*
* Replaces the contents of a @ref nrgba_t with those of `other`.
*/
nrgba_t& operator=(const nrgba_t& other)
{
red = other.red;
green = other.green;
blue = other.blue;
alpha = other.alpha;
return *this;
}
/**
* @brief Sets red value
*
* Sets a value for the red component.
*
* @param new_r The new value.
*/
nrgba_t& set_red(const component_type& new_r)
{
red = new_r;
return *this;
}
/**
* @brief Sets green value
*
* Sets a value for the green component.
*
* @param new_g The new value.
*/
nrgba_t& set_green(const component_type& new_g)
{
green = new_g;
return *this;
}
/**
* @brief Sets blue value
*
* Sets a value for the blue component.
*
* @param new_b The new value.
*/
nrgba_t& set_blue(const component_type& new_b)
{
blue = new_b;
return *this;
}
/**
* @brief Sets alpha value
*
* Sets a value for the alpha component.
*
* @param new_a The new value.
*/
nrgba_t& set_alpha(const component_type& new_a)
{
alpha = new_a;
return *this;
}
/**
* @brief Equality operator
*
* Checks if two @ref nrgba_t s are equal.
*/
constexpr friend bool operator==(const nrgba_t& lhs,const nrgba_t& rhs)
{
return (lhs.red == rhs.red) && (lhs.green == rhs.green) && (lhs.blue == rhs.blue) && (lhs.alpha == rhs.alpha);
}
/**
* @brief Inquality operator
*
* Checks if two @ref nrgba_t s are not equal.
*/
constexpr friend bool operator!=(const nrgba_t& lhs,const nrgba_t& rhs)
{
return !(lhs == rhs);
}
/**
* @brief Swaps the contents
*
* Swaps (exchanges) the contents with those of `other`.
*/
void swap(nrgba_t& other)
{
std::swap(red,other.red);
std::swap(green,other.green);
std::swap(blue,other.blue);
std::swap(alpha,other.alpha);
}
/**
* @brief Output stream operator
*
* Writes to an output stream.
*/
template <typename CharT,typename Traits>
friend std::basic_ostream<CharT,Traits>& operator<<(std::basic_ostream<CharT,Traits>& os,const nrgba_t& out)
{
std::basic_ostringstream<CharT,Traits> ss;
ss.flags(os.flags());
ss.imbue(os.getloc());
ss.precision(os.precision());
ss << out.red << ' ' << out.green << ' ' << out.blue << ' ' << out.alpha;
return os << ss.str();
}
/**
* @brief Input stream operator
*
* Reads from an input stream.
*/
template <typename CharT,typename Traits>
friend std::basic_istream<CharT,Traits>& operator>>(std::basic_istream<CharT,Traits>& is,nrgba_t& in)
{
is >> in.red >> std::ws
>> in.green >> std::ws
>> in.blue >> std::ws
>> in.alpha >> std::ws;
return is;
}
};
constexpr color_space nrgba_t::pixel_color_space;
}} // end of "cynodelic::tesela" namespace
#endif // CYNODELIC_TESELA_RGBA_TYPES_HPP
| 19.928571
| 137
| 0.643828
|
cynodelic
|
fe555779d3aa725ab958ee9fe9568f41f4d2935c
| 7,141
|
cpp
|
C++
|
Zone/libs/cocos2dx/extensions/CCBReader/CCParticleSystemQuadLoader.cpp
|
sdost/Zone
|
747e5998b23ba58b1389880640e16a699a115c9e
|
[
"Apache-2.0"
] | 6
|
2015-01-10T03:42:34.000Z
|
2016-03-24T05:17:02.000Z
|
Zone/libs/cocos2dx/extensions/CCBReader/CCParticleSystemQuadLoader.cpp
|
sdost/Zone
|
747e5998b23ba58b1389880640e16a699a115c9e
|
[
"Apache-2.0"
] | 1
|
2015-11-11T08:38:11.000Z
|
2015-11-11T08:38:11.000Z
|
Zone/libs/cocos2dx/extensions/CCBReader/CCParticleSystemQuadLoader.cpp
|
sdost/Zone
|
747e5998b23ba58b1389880640e16a699a115c9e
|
[
"Apache-2.0"
] | 4
|
2015-03-24T02:19:57.000Z
|
2020-09-19T06:16:51.000Z
|
#include "CCParticleSystemQuadLoader.h"
USING_NS_CC;
USING_NS_CC_EXT;
#define PROPERTY_EMITERMODE "emitterMode"
#define PROPERTY_POSVAR "posVar"
#define PROPERTY_EMISSIONRATE "emissionRate"
#define PROPERTY_DURATION "duration"
#define PROPERTY_TOTALPARTICLES "totalParticles"
#define PROPERTY_LIFE "life"
#define PROPERTY_STARTSIZE "startSize"
#define PROPERTY_ENDSIZE "endSize"
#define PROPERTY_STARTSPIN "startSpin"
#define PROPERTY_ENDSPIN "endSpin"
#define PROPERTY_ANGLE "angle"
#define PROPERTY_STARTCOLOR "startColor"
#define PROPERTY_ENDCOLOR "endColor"
#define PROPERTY_BLENDFUNC "blendFunc"
#define PROPERTY_GRAVITY "gravity"
#define PROPERTY_SPEED "speed"
#define PROPERTY_TANGENTIALACCEL "tangentialAccel"
#define PROPERTY_RADIALACCEL "radialAccel"
#define PROPERTY_TEXTURE "texture"
#define PROPERTY_STARTRADIUS "startRadius"
#define PROPERTY_ENDRADIUS "endRadius"
#define PROPERTY_ROTATEPERSECOND "rotatePerSecond"
void CCParticleSystemQuadLoader::onHandlePropTypeIntegerLabeled(CCNode * pNode, CCNode * pParent, CCString * pPropertyName, int pIntegerLabeled, CCBReader * pCCBReader) {
if(pPropertyName->compare(PROPERTY_EMITERMODE) == 0) {
((CCParticleSystemQuad *)pNode)->setEmitterMode(pIntegerLabeled);
} else {
CCNodeLoader::onHandlePropTypeIntegerLabeled(pNode, pParent, pPropertyName, pIntegerLabeled, pCCBReader);
}
}
void CCParticleSystemQuadLoader::onHandlePropTypePoint(CCNode * pNode, CCNode * pParent, CCString * pPropertyName, CCPoint pPoint, CCBReader * pCCBReader) {
if(pPropertyName->compare(PROPERTY_POSVAR) == 0) {
((CCParticleSystemQuad *)pNode)->setPosVar(pPoint);
} else if(pPropertyName->compare(PROPERTY_GRAVITY) == 0) {
((CCParticleSystemQuad *)pNode)->setGravity(pPoint);
} else {
CCNodeLoader::onHandlePropTypePoint(pNode, pParent, pPropertyName, pPoint, pCCBReader);
}
}
void CCParticleSystemQuadLoader::onHandlePropTypeFloat(CCNode * pNode, CCNode * pParent, CCString * pPropertyName, float pFloat, CCBReader * pCCBReader) {
if(pPropertyName->compare(PROPERTY_EMISSIONRATE) == 0) {
((CCParticleSystemQuad *)pNode)->setEmissionRate(pFloat);
} else if(pPropertyName->compare(PROPERTY_DURATION) == 0) {
((CCParticleSystemQuad *)pNode)->setDuration(pFloat);
} else {
CCNodeLoader::onHandlePropTypeFloat(pNode, pParent, pPropertyName, pFloat, pCCBReader);
}
}
void CCParticleSystemQuadLoader::onHandlePropTypeInteger(CCNode * pNode, CCNode * pParent, CCString * pPropertyName, int pInteger, CCBReader * pCCBReader) {
if(pPropertyName->compare(PROPERTY_TOTALPARTICLES) == 0) {
((CCParticleSystemQuad *)pNode)->setTotalParticles(pInteger);
} else {
CCNodeLoader::onHandlePropTypeInteger(pNode, pParent, pPropertyName, pInteger, pCCBReader);
}
}
void CCParticleSystemQuadLoader::onHandlePropTypeFloatVar(CCNode * pNode, CCNode * pParent, CCString * pPropertyName, float * pFloatVar, CCBReader * pCCBReader) {
if(pPropertyName->compare(PROPERTY_LIFE) == 0) {
((CCParticleSystemQuad *)pNode)->setLife(pFloatVar[0]);
((CCParticleSystemQuad *)pNode)->setLifeVar(pFloatVar[1]);
} else if(pPropertyName->compare(PROPERTY_STARTSIZE) == 0) {
((CCParticleSystemQuad *)pNode)->setStartSize(pFloatVar[0]);
((CCParticleSystemQuad *)pNode)->setStartSizeVar(pFloatVar[1]);
} else if(pPropertyName->compare(PROPERTY_ENDSIZE) == 0) {
((CCParticleSystemQuad *)pNode)->setEndSize(pFloatVar[0]);
((CCParticleSystemQuad *)pNode)->setEndSizeVar(pFloatVar[1]);
} else if(pPropertyName->compare(PROPERTY_STARTSPIN) == 0) {
((CCParticleSystemQuad *)pNode)->setStartSpin(pFloatVar[0]);
((CCParticleSystemQuad *)pNode)->setStartSpinVar(pFloatVar[1]);
} else if(pPropertyName->compare(PROPERTY_ENDSPIN) == 0) {
((CCParticleSystemQuad *)pNode)->setEndSpin(pFloatVar[0]);
((CCParticleSystemQuad *)pNode)->setEndSpinVar(pFloatVar[1]);
} else if(pPropertyName->compare(PROPERTY_ANGLE) == 0) {
((CCParticleSystemQuad *)pNode)->setAngle(pFloatVar[0]);
((CCParticleSystemQuad *)pNode)->setAngleVar(pFloatVar[1]);
} else if(pPropertyName->compare(PROPERTY_SPEED) == 0) {
((CCParticleSystemQuad *)pNode)->setSpeed(pFloatVar[0]);
((CCParticleSystemQuad *)pNode)->setSpeedVar(pFloatVar[1]);
} else if(pPropertyName->compare(PROPERTY_TANGENTIALACCEL) == 0) {
((CCParticleSystemQuad *)pNode)->setTangentialAccel(pFloatVar[0]);
((CCParticleSystemQuad *)pNode)->setTangentialAccelVar(pFloatVar[1]);
} else if(pPropertyName->compare(PROPERTY_RADIALACCEL) == 0) {
((CCParticleSystemQuad *)pNode)->setRadialAccel(pFloatVar[0]);
((CCParticleSystemQuad *)pNode)->setRadialAccelVar(pFloatVar[1]);
} else if(pPropertyName->compare(PROPERTY_STARTRADIUS) == 0) {
((CCParticleSystemQuad *)pNode)->setStartRadius(pFloatVar[0]);
((CCParticleSystemQuad *)pNode)->setStartRadiusVar(pFloatVar[1]);
} else if(pPropertyName->compare(PROPERTY_ENDRADIUS) == 0) {
((CCParticleSystemQuad *)pNode)->setEndRadius(pFloatVar[0]);
((CCParticleSystemQuad *)pNode)->setEndRadiusVar(pFloatVar[1]);
} else if(pPropertyName->compare(PROPERTY_ROTATEPERSECOND) == 0) {
((CCParticleSystemQuad *)pNode)->setRotatePerSecond(pFloatVar[0]);
((CCParticleSystemQuad *)pNode)->setRotatePerSecondVar(pFloatVar[1]);
} else {
CCNodeLoader::onHandlePropTypeFloatVar(pNode, pParent, pPropertyName, pFloatVar, pCCBReader);
}
}
void CCParticleSystemQuadLoader::onHandlePropTypeColor4FVar(CCNode * pNode, CCNode * pParent, CCString * pPropertyName, ccColor4F * pCCColor4FVar, CCBReader * pCCBReader) {
if(pPropertyName->compare(PROPERTY_STARTCOLOR) == 0) {
((CCParticleSystemQuad *)pNode)->setStartColor(pCCColor4FVar[0]);
((CCParticleSystemQuad *)pNode)->setStartColorVar(pCCColor4FVar[1]);
} else if(pPropertyName->compare(PROPERTY_ENDCOLOR) == 0) {
((CCParticleSystemQuad *)pNode)->setEndColor(pCCColor4FVar[0]);
((CCParticleSystemQuad *)pNode)->setEndColorVar(pCCColor4FVar[1]);
} else {
CCNodeLoader::onHandlePropTypeColor4FVar(pNode, pParent, pPropertyName, pCCColor4FVar, pCCBReader);
}
}
void CCParticleSystemQuadLoader::onHandlePropTypeBlendFunc(CCNode * pNode, CCNode * pParent, CCString * pPropertyName, ccBlendFunc pCCBlendFunc, CCBReader * pCCBReader) {
if(pPropertyName->compare(PROPERTY_BLENDFUNC) == 0) {
((CCParticleSystemQuad *)pNode)->setBlendFunc(pCCBlendFunc);
} else {
CCNodeLoader::onHandlePropTypeBlendFunc(pNode, pParent, pPropertyName, pCCBlendFunc, pCCBReader);
}
}
void CCParticleSystemQuadLoader::onHandlePropTypeTexture(CCNode * pNode, CCNode * pParent, CCString * pPropertyName, CCTexture2D * pCCTexture2D, CCBReader * pCCBReader) {
if(pPropertyName->compare(PROPERTY_TEXTURE) == 0) {
((CCParticleSystemQuad *)pNode)->setTexture(pCCTexture2D);
} else {
CCNodeLoader::onHandlePropTypeTexture(pNode, pParent, pPropertyName, pCCTexture2D, pCCBReader);
}
}
| 53.691729
| 172
| 0.734911
|
sdost
|
fe5718e950c709fdfa16355378ea5d09bb3ab65d
| 1,078
|
cpp
|
C++
|
Implement strStr().cpp
|
Xe0n0/LeetCode
|
a7a383d88d222edaadd52b317e848f06632a569a
|
[
"MIT"
] | 1
|
2017-08-22T00:43:27.000Z
|
2017-08-22T00:43:27.000Z
|
Implement strStr().cpp
|
Xe0n0/LeetCode
|
a7a383d88d222edaadd52b317e848f06632a569a
|
[
"MIT"
] | null | null | null |
Implement strStr().cpp
|
Xe0n0/LeetCode
|
a7a383d88d222edaadd52b317e848f06632a569a
|
[
"MIT"
] | null | null | null |
//1. what should be return if needle is NULL
//2. some condition prevent go inside loop may have satifiable pattern
class Solution {
public:
char *strStr(char *haystack, char *needle) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
char *r = NULL;
if (haystack == NULL || needle == NULL) return r;
char *c_start = haystack;
if (*haystack == '\0' and *needle == '\0') return haystack;
while (*c_start != '\0') {
bool found = true;
char *c = c_start;
char *p = needle;
while (*c != '\0' and *p != '\0') {
if (*c++ != *p++) {
found = false;
break;
}
}
if (found && *c == '\0' && *p != '\0') break;
if (found) {
r = c_start;
break;
}
c_start++;
}
return r;
}
};
| 26.95
| 70
| 0.38961
|
Xe0n0
|
fe5cc0521a12dc45abbbf0a3bb4e06cc2f2c3034
| 32,287
|
hpp
|
C++
|
SamSrc/sam/SubgraphQueryResult.hpp
|
elgood/SAM
|
5943d637270581e4fe307bc68fbeb5a8e4eccc2c
|
[
"MIT"
] | 6
|
2019-08-16T07:13:17.000Z
|
2021-06-08T21:15:52.000Z
|
SamSrc/sam/SubgraphQueryResult.hpp
|
elgood/SAM
|
5943d637270581e4fe307bc68fbeb5a8e4eccc2c
|
[
"MIT"
] | 1
|
2020-05-30T20:35:18.000Z
|
2020-05-30T20:35:18.000Z
|
SamSrc/sam/SubgraphQueryResult.hpp
|
elgood/SAM
|
5943d637270581e4fe307bc68fbeb5a8e4eccc2c
|
[
"MIT"
] | 3
|
2020-02-17T18:38:14.000Z
|
2021-03-28T02:47:57.000Z
|
#ifndef SAM_SUBGRAPH_QUERY_RESULT_HPP
#define SAM_SUBGRAPH_QUERY_RESULT_HPP
#include <sam/SubgraphQuery.hpp>
#include <sam/Null.hpp>
#include <sam/EdgeRequest.hpp>
#include <sam/Util.hpp>
#include <sam/VertexConstraintChecker.hpp>
#include <set>
namespace sam {
class SubgraphQueryResultException : public std::runtime_error {
public:
SubgraphQueryResultException(char const * message) :
std::runtime_error(message) { }
SubgraphQueryResultException(std::string message) :
std::runtime_error(message) { }
};
/**
* This contains the data that satisfies a SubgraphQuery. The overall
* process is to create the SubgraphQueryResult with a constant reference
* to the SubgraphQuery, and add edges iteratively until it the entire
* SubgraphQuery is satisfied.
*
* The SubgraphQueryResult class does not store time. A determination is
* made that an intermediate result cannot be fulfilled by calling the
* isExpired function. Management of deleting expired partial results
* resides outside this class.
*
* The source and target fields need to be of the same type.
*/
template <typename EdgeType, size_t source, size_t target,
size_t time, size_t duration>
class SubgraphQueryResult
{
public:
typedef typename EdgeType::LocalTupleType TupleType;
typedef typename std::tuple_element<source, TupleType>::type SourceType;
typedef typename std::tuple_element<target, TupleType>::type TargetType;
typedef SourceType NodeType;
typedef SubgraphQueryResult<EdgeType, source, target, time, duration>
SubgraphQueryResultType;
typedef SubgraphQuery<TupleType, source, target, time, duration>
SubgraphQueryType;
typedef EdgeDescription<TupleType, time, duration> EdgeDescriptionType;
typedef EdgeRequest<TupleType, source, target> EdgeRequestType;
private:
/// The SubgraphQuery that this is a result for.
std::shared_ptr<const SubgraphQueryType> subgraphQuery;
/// A mapping from the variable name to the bound value.
std::map<std::string, NodeType> var2BoundValue;
/// A vector of edges that satisfied the edge descriptions.
std::vector<EdgeType> resultEdges;
/// Index to current edge we are trying to satisfy.
size_t currentEdge = 0;
/// How many edges are in the query
size_t numEdges = 0;
/// The time this query result expires (usually time in seconds since
/// epoch).
double expireTime = 0;
/// The time that the query started (either starttime or endtime of
/// first edge)
double startTime = 0;
/// Seen edges. It is possible for the same edge to be presented to the
/// same partial result. For example, two edge requests can be produced
/// return the same edge to this node. When we try to map against the
/// query result, the same edge will fulfill the same criteria twice.
/// We want to prevent that. We create a string from time,source,target,
/// and then store them in this set so that we only see it once.
std::set<std::string> seenEdges;
public:
/**
* Default constructor.
*/
SubgraphQueryResult();
/**
* The constructor assumes that the check on the first edge description
* has been satisfied.
*
* \param query The SubgraphQuery we are trying to satisfy.
* \param id The id of the edge being added.
* \param firstEdge The first edge that satisfies the first edge description.
*/
SubgraphQueryResult(std::shared_ptr<const SubgraphQueryType> query,
EdgeType firstEdge);
/**
* Tries to add the edge to the subgraph query result. If successful
* returns true along with the new query result. This result remains
* unchanged. Returns false if adding doesn't work.
* \return Returns a pair where the first value is true if the netflow was
* added. False otherwise. If it was added, the second value is the
* new result with the added edge.
*/
std::pair<bool, SubgraphQueryResult<EdgeType, source,
target, time, duration>>
addEdge(EdgeType const& edge);
/**
* Tries to add the edge to the subgraph query result. This is a public
* method to make it easy to test, but it should actually be a private
* method. It shouldn't be used outside of this class. It is only
* used by the constructor to create the first edge in the result.
* For existing results, when we add an edge, we want to keep the
* existing result for other matches and also create a new result.
* That is the purpose of the other addEdge method.
*
* \return Returns true if the netflow was added. False otherwise.
*/
bool
addEdgeInPlace(EdgeType const& edge);
/**
* Convenience method that returns true if the source variable has been bound
* to an actual value. The source variable is the source of the edge
* we are currently trying to match.
*/
bool boundSource() const {return !sam::isNull(getCurrentSource()); }
/**
* Convenience method that returns true if the target variable has been bound
* to an actual value. The target variable is the target of the edge
* we are currently trying to match.
*/
bool boundTarget() const {return !sam::isNull(getCurrentTarget()); }
/**
* Returns true if the query has expired (meaning it can't be fulfilled
* because the time constraint of the entire query has been violated).
* This class is not responsible for storing the current time, thus
* it is provided as a parameter to the function.
*/
bool isExpired(double currentTime) const {
if (currentTime > expireTime) return true;
return false;
}
/**
* Returns the expire time of the query, which is the start time
* of the last edge.
*/
double getExpireTime() const;
/**
* Returns the variable binding for the source of the current edge or
* a null value using nullValue<NodeType>() if there is no variable
* binding for the source.
*/
NodeType getCurrentSource() const;
/**
* Returns the variable binding for the target of the current edge or
* a null value using nullValue<NodeType>() if there is no variable
* binding for the target.
*/
NodeType getCurrentTarget() const;
double getCurrentStartTimeFirst() const;
double getCurrentStartTimeSecond() const;
double getCurrentEndTimeFirst() const;
double getCurrentEndTimeSecond() const;
/**
* We need to hash based on source if that is defined, target, if that
* is defined, or both if both are defined. This function looks at the
* current edge (unprocessed) and computes the hash based on what is defined.
* Also, it adds an edgeRequest to the list parameter, edgeRequests, if
* the edge we are looking for will be found on another node.
* \param sourceHash The source hash function.
* \param targetHash The target hash function (usually the same as the souce
* hash function).
* \param edgeRequests A reference to a list of edge requests. If the next
* edge to be satisfied will be found on another node,
* then an edge request is added to the list.
* \param nodeId The id of the node running this code. Used to determine
* if the next edge will be sent to this node by the
* partitioner (in ZeroMQPushPull).
* \param numNodes The number of nodes in the cluster. Used to determin
* if the next edge will be sent to this node by the
* partitioner (in ZeroMQPushPull).
*/
template <typename SourceHF, typename TargetHF>
size_t hash(SourceHF const& sourceHash,
TargetHF const& targetHash,
std::list<EdgeRequestType> & edgeRequests,
size_t nodeId,
size_t numNodes)
const;
/**
* Returns true if the query has been satisfied.
*/
bool complete() const {
DEBUG_PRINT("SubgraphQueryResult::complete() %s\n", toString().c_str());
return currentEdge == numEdges;
}
/**
* Returns a string representation of the query result
*/
std::string toString() const {
if (resultEdges.size() != currentEdge) {
std::string message = "resultEdges.size() was not equal to currentEdge " +
boost::lexical_cast<std::string>(resultEdges.size()) + " != " +
boost::lexical_cast<std::string>(currentEdge);
throw SubgraphQueryResultException(message);
}
std::string rString = "Result Edges: ";
size_t i = 0;
for(EdgeType const& edge : resultEdges) {
TupleType t = edge.tuple;
rString = rString + " ResultTuple " +
"Id " + boost::lexical_cast<std::string>(edge.id) +
" Time " + boost::lexical_cast<std::string>(std::get<time>(t)) +
" Duration " + boost::lexical_cast<std::string>(std::get<duration>(t)) +
" Source " + boost::lexical_cast<std::string>(std::get<source>(t)) +
" Target " + boost::lexical_cast<std::string>(std::get<target>(t));
//rString = rString + "ResultTuple " + sam::toString(t) + " ";
}
rString += " startTime" + boost::lexical_cast<std::string>(startTime);
rString += " var2BoundValue ";
for(auto key : var2BoundValue) {
rString += key.first + "->" + key.second + " ";
}
rString += " currentEdge: " + boost::lexical_cast<std::string>(currentEdge);
rString += " numEdges: " + boost::lexical_cast<std::string>(numEdges);
return rString;
}
/**
* Returns true if none of the result edges have the given sam id.
*/
bool noSamId(size_t samId)
{
size_t i = 0;
for (EdgeType const& edge : resultEdges) {
if (edge.id == samId) {
return false;
}
}
return true;
}
/**
* An instance of a SubgraphQueryResult is considered null if there is
* no associated subgraphQuery.
*/
bool isNull() const
{
return subgraphQuery.get() == nullptr;
}
EdgeType getResultTuple(size_t i) const {
return resultEdges[i];
}
private:
void addTimeInfoFromCurrent(EdgeRequestType & edgeRequest,
double previousStartTime) const;
double getPreviousStartTime() const;
};
// Constructor
template <typename EdgeType, size_t source, size_t target,
size_t time, size_t duration>
SubgraphQueryResult<EdgeType, source, target, time, duration>::
SubgraphQueryResult(std::shared_ptr<const SubgraphQueryType> query,
EdgeType firstEdge) :
subgraphQuery(query)
{
DEBUG_PRINT("SubgraphQueryResult::SubgraphQueryResult(query, firstedge) "
"Creating subgraphquery result, first edge: %s\n",
firstEdge.toString().c_str());
//TODO: Maybe remove this to improve performance
if (!query->isFinalized()) {
throw SubgraphQueryResultException("Subgraph query passed to "
"SubgraphQueryResult is not finalized.");
}
numEdges = subgraphQuery->size();
// If the query has start time defined relative to the start of the edge,
// we set start time to be the start of the first edge. Otherwise,
// we set the start time of the query to be the end time of the first edge.
if (subgraphQuery->zeroTimeRelativeToStart()) {
startTime = std::get<time>(firstEdge.tuple);
} else {
startTime = std::get<time>(firstEdge.tuple) +
std::get<duration>(firstEdge.tuple);
}
expireTime = startTime + query->getMaxTimeExtent();
if (!addEdgeInPlace(firstEdge)) {
throw SubgraphQueryResultException("SubgraphQueryResult::"
"SubgraphQueryResult(query, firstEdge) Tried to add edge in "
"constructor and it failed.");
}
}
template <typename EdgeType, size_t source, size_t target,
size_t time, size_t duration>
SubgraphQueryResult<EdgeType, source, target, time, duration>::
SubgraphQueryResult()
{
subgraphQuery = nullptr;
}
template <typename EdgeType, size_t source, size_t target,
size_t time, size_t duration>
void
SubgraphQueryResult<EdgeType, source, target, time, duration>::
addTimeInfoFromCurrent(EdgeRequestType & edgeRequest,
double previousStartTime) const
{
EdgeDescriptionType desc = subgraphQuery->getEdgeDescription(currentEdge);
if (previousStartTime > desc.startTimeRange.first + startTime) {
edgeRequest.setStartTimeFirst(previousStartTime);
} else {
edgeRequest.setStartTimeFirst(desc.startTimeRange.first + startTime);
}
edgeRequest.setStartTimeSecond(desc.startTimeRange.second + startTime);
edgeRequest.setEndTimeFirst(desc.endTimeRange.first + startTime);
edgeRequest.setEndTimeSecond(desc.endTimeRange.second + startTime);
}
template <typename EdgeType, size_t source, size_t target,
size_t time, size_t duration>
double
SubgraphQueryResult<EdgeType, source, target, time, duration>::
getPreviousStartTime() const
{
if (resultEdges.size() > 0) {
return std::get<time>(resultEdges.at(resultEdges.size() - 1).tuple);
}
return std::numeric_limits<double>::lowest();
}
template <typename EdgeType, size_t source, size_t target,
size_t time, size_t duration>
template <typename SourceHF, typename TargetHF>
size_t
SubgraphQueryResult<EdgeType, source, target, time, duration>::
hash(SourceHF const& sourceHash,
TargetHF const& targetHash,
std::list<EdgeRequestType> & edgeRequests,
size_t nodeId,
size_t numNodes)
const
{
// Get the source that we are looking for. If the source is unbound,
// then the null value is returned. Otherwise the source is bound to
// a value, and the next tuple must have that value for the source.
NodeType src = getCurrentSource();
// Get the target that we are looking for. If the target is unbound,
// then the null value is returned. Otherwise the target is bound to
// a valud, and the next tuple must have that value for the target.
NodeType trg = getCurrentTarget();
double previousTime = getPreviousStartTime();
EdgeDescriptionType desc = subgraphQuery->getEdgeDescription(currentEdge);
DEBUG_PRINT("SubgraphQueryResult::hash currentEdge %lu start time range "
"%f %f stop time range %f %f\n",
currentEdge, desc.startTimeRange.first, desc.startTimeRange.second,
desc.endTimeRange.first, desc.endTimeRange.second);
DEBUG_PRINT("SubgraphQueryResult::hash src %s trg %s\n", src.c_str(), trg.c_str());
// Case when the source is unbound but the target is bound to a value.
if (sam::isNull(src) && !sam::isNull(trg)) {
DEBUG_PRINT("SubgraphQueryResult::hash: source is unbound, target is bound to"
" %s\n", trg.c_str());
// If the target hashes to a different node, we need to make an edge
// request to that node.
if (targetHash(trg) % numNodes != nodeId) {
EdgeRequestType edgeRequest;
edgeRequest.setTarget(trg);
addTimeInfoFromCurrent(edgeRequest, previousTime);
edgeRequest.setReturn(nodeId);
// Add the edge request to the list of new edge requests.
edgeRequests.push_back(edgeRequest);
}
// Returns a hash of the target so that it can be placed in the correct
// bin in the SubgraphQueryResultMap.
return targetHash(trg);
} else
// Case when the target is unbound but the source is bound to a value.
if (!sam::isNull(src) && sam::isNull(trg)) {
#ifdef DEBUG
printf("SubgraphQueryResult::hash: target is unbound, source is bound to"
" %s\n", src.c_str());
#endif
// If the source hashes to a different node, we need to make an edge
// request to that node.
#ifdef DEBUG
printf("SubgraphQueryResult::hash: sourceHash %llu %llu "
" numNodes %lu nodeId %lu\n", sourceHash(src), sourceHash(src) % numNodes,
numNodes, nodeId);
#endif
if (sourceHash(src) % numNodes != nodeId) {
EdgeRequestType edgeRequest;
edgeRequest.setSource(src);
addTimeInfoFromCurrent(edgeRequest, previousTime);
edgeRequest.setReturn(nodeId);
// Add the edge request to the list of new edge requests.
edgeRequests.push_back(edgeRequest);
}
// Returns a hash of the source so that it can be placed in the correct
// bin in the SubgraphQueryResultMap.
return sourceHash(src);
} else
// Case when the target and source are both bound to a value.
if (!sam::isNull(src) && !sam::isNull(trg)) {
// Need to make edge requests if both the source or target
// map to a different node. If either one maps to this node,
// then we will get the edge.
if (sourceHash(src) % numNodes != nodeId &&
targetHash(trg) % numNodes != nodeId)
{
// It doesn't matter which node we send the edge request to
EdgeRequestType edgeRequest;
edgeRequest.setSource(src);
edgeRequest.setTarget(trg);
addTimeInfoFromCurrent(edgeRequest, previousTime);
edgeRequest.setReturn(nodeId);
edgeRequests.push_back(edgeRequest);
}
// Returns a hash of the source combined with the hash of the target
// so that it can be placed in the correct
// bin in the SubgraphQueryResultMap.
return sourceHash(src) * targetHash(trg);
} else {
std::string message = "SubgraphQueryResult::hash When trying "
"to calculate the hash, both source and target are unbound. ";
try {
message += "Current edge: " +
boost::lexical_cast<std::string>(currentEdge);
} catch (std::exception e) {
std::string message = "Trouble with lexical cast: " +
std::string(e.what());
throw SubgraphQueryResultException(message);
}
try {
message += " Num edges: " + boost::lexical_cast<std::string>(numEdges);
message += " QueryResult as is " + toString();
} catch (std::exception e) {
std::string message = "Trouble with lexical cast: " +
std::string(e.what());
throw SubgraphQueryResultException(message);
}
auto description = subgraphQuery->getEdgeDescription(
currentEdge);
message += " Current EdgeDescription: " + description.toString();
throw SubgraphQueryResultException(message);
}
}
template <typename EdgeType, size_t source, size_t target,
size_t time, size_t duration>
double
SubgraphQueryResult<EdgeType, source, target, time, duration>::
getExpireTime() const
{
return expireTime;
}
template <typename EdgeType, size_t source, size_t target,
size_t time, size_t duration>
bool
SubgraphQueryResult<EdgeType, source, target, time, duration>::
addEdgeInPlace(EdgeType const& edge)
{
if (resultEdges.size() != currentEdge) {
std::string message = "addEdgeInPlace resultEdges.size() was not equal"
" to currentEdge " +
boost::lexical_cast<std::string>(resultEdges.size()) + " != " +
boost::lexical_cast<std::string>(currentEdge);
throw SubgraphQueryResultException(message);
}
if (currentEdge >= numEdges) {
std::string message = "SubgraphQueryResult::addEdge Tried to add an edge "
"but the query has already been satisfied, i.e. currentEdge(" +
boost::lexical_cast<std::string>(currentEdge) +
") >= numEdges (" + boost::lexical_cast<std::string>(numEdges) + ")";
throw SubgraphQueryResultException(message);
}
// We need to check if it fulfills the constraints of the edge description
// and also it fits the existing variable bindings.
if (!subgraphQuery->satisfiesConstraints(currentEdge, edge.tuple, startTime))
{
return false;
}
EdgeDescriptionType const& edgeDescription =
subgraphQuery->getEdgeDescription(currentEdge);
std::string src = edgeDescription.getSource();
std::string trg = edgeDescription.getTarget();
// Case when the source has been bound but the target has not
if (var2BoundValue.count(src) > 0 &&
var2BoundValue.count(trg) == 0)
{
NodeType edgeSource = std::get<source>(edge.tuple);
if (edgeSource == var2BoundValue[src]) {
NodeType edgeTarget = std::get<target>(edge.tuple);
var2BoundValue[trg] = edgeTarget;
} else {
return false;
}
} else if (var2BoundValue.count(src) == 0 &&
var2BoundValue.count(trg) > 0) {
NodeType edgeTarget = std::get<target>(edge.tuple);
if (edgeTarget == var2BoundValue[trg]) {
NodeType edgeSource = std::get<source>(edge.tuple);
var2BoundValue[src] = edgeSource;
} else {
return false;
}
} else if (var2BoundValue.count(src) == 0 &&
var2BoundValue.count(trg) == 0)
{
DEBUG_PRINT("Setting %s->%s and %s->%s\n", src.c_str(),
std::get<source>(edge.tuple).c_str(), trg.c_str(),
std::get<target>(edge.tuple).c_str());
var2BoundValue[src] = std::get<source>(edge.tuple);
var2BoundValue[trg] = std::get<target>(edge.tuple);
} else {
NodeType edgeTarget = std::get<target>(edge.tuple);
NodeType edgeSource = std::get<target>(edge.tuple);
if (edgeTarget != var2BoundValue[trg] ||
edgeSource != var2BoundValue[src])
{
return false;
}
}
resultEdges.push_back(edge);
currentEdge++;
DEBUG_PRINT_SIMPLE("Add edge in place returning true\n");
std::string edgeKey =
boost::lexical_cast<std::string>(std::get<source>(edge.tuple)) +
boost::lexical_cast<std::string>(std::get<target>(edge.tuple)) +
boost::lexical_cast<std::string>(std::get<time>(edge.tuple)) +
boost::lexical_cast<std::string>(std::get<duration>(edge.tuple));
seenEdges.insert(edgeKey);
return true;
}
template <typename EdgeType, size_t source, size_t target,
size_t time, size_t duration>
std::pair<bool, SubgraphQueryResult<EdgeType, source, target, time, duration>>
SubgraphQueryResult<EdgeType, source, target, time, duration>::
addEdge(EdgeType const& edge)
{
// Create a string from the source, target, time, and duration. Check to see
// if that is in seenEdges. If not, add it and continue processing. If
// so, do not continue processing. This prevents duplicate subgraphs to
// be created.
std::string edgeKey =
boost::lexical_cast<std::string>(std::get<source>(edge.tuple)) +
boost::lexical_cast<std::string>(std::get<target>(edge.tuple)) +
boost::lexical_cast<std::string>(std::get<time>(edge.tuple)) +
boost::lexical_cast<std::string>(std::get<duration>(edge.tuple));
if (seenEdges.count(edgeKey) < 1) {
seenEdges.insert(edgeKey);
DEBUG_PRINT("SubgraphQueryResult::addEdge trying to add edge %s to result"
" %s\n", sam::toString(edge.tuple).c_str(), toString().c_str());
if (currentEdge >= numEdges) {
std::string message = "SubgraphQueryResult::addEdge Tried to add an edge "
"but the query has already been satisfied, i.e. currentEdge(" +
boost::lexical_cast<std::string>(currentEdge) +
") >= numEdges (" + boost::lexical_cast<std::string>(numEdges) + ")";
throw SubgraphQueryResultException(message);
}
// We need to check if it fulfills the constraints of the edge description
// and also it fits the existing variable bindings.
if (currentEdge >= 1) {
double previousTime = std::get<time>(resultEdges[currentEdge - 1].tuple);
double currentTime = std::get<time>(edge.tuple);
if (currentTime <= previousTime) {
return std::pair<bool, SubgraphQueryResultType>(false,
SubgraphQueryResultType());
}
}
// Checking against edge description constraints
//EdgeDescriptionType const& edgeDescription =
// subgraphQuery->getEdgeDescription(currentEdge);
if (!subgraphQuery->satisfiesConstraints(currentEdge, edge.tuple,
startTime))
{
DEBUG_PRINT("SubgraphQueryResult::addEdge this tuple %s did not satisfy"
" this edge constraings\n", sam::toString(edge.tuple).c_str());
return std::pair<bool, SubgraphQueryResultType>(false,
SubgraphQueryResultType());
}
/*if (!edgeDescription.satisfiesEdgeConstraints(
currentEdge, this->startTime)) {
DEBUG_PRINT("SubgraphQueryResult::addEdge this tuple %s did not satisfy"
" this edgeDescription %s\n", sam::toString(edge).c_str(),
edgeDescription.toString().c_str());
return std::pair<bool, SubgraphQueryResultType>(false,
SubgraphQueryResultType());
}
if (!subgraphQuery->satisfiesVertexConstraints(currentEdge, edge))
{
return std::pair<bool, SubgraphQueryResultType>(false,
SubgraphQueryResultType());
}*/
/*std::string src = edgeDescription.getSource();
std::string trg = edgeDescription.getTarget();
VertexConstraintChecker<SubgraphQueryType> check(*featureMap,
*subgraphQuery);
if (!check(src, edgeSource)) {
return std::pair<bool, SubgraphQueryResultType>(false,
SubgraphQueryResultType());
}
if (!check(trg, edgeTarget)) {
return std::pair<bool, SubgraphQueryResultType>(false,
SubgraphQueryResultType());
}*/
SubgraphQueryResultType newResult(*this);
EdgeDescriptionType const& edgeDescription =
subgraphQuery->getEdgeDescription(currentEdge);
std::string src = edgeDescription.getSource();
std::string trg = edgeDescription.getTarget();
NodeType edgeSource = std::get<source>(edge.tuple);
NodeType edgeTarget = std::get<target>(edge.tuple);
// Case when the source has been bound but the target has not
if (var2BoundValue.count(src) > 0 &&
var2BoundValue.count(trg) == 0)
{
if (edgeSource == var2BoundValue.at(src)) {
NodeType edgeTarget = std::get<target>(edge.tuple);
newResult.var2BoundValue[trg] = edgeTarget;
} else {
DEBUG_PRINT("SubgraphQueryResult::addEdge: edgeSource %s "
" did not match var2BoundValue.at(src) %s for tuple %s\n",
edgeSource.c_str(), var2BoundValue.at(src).c_str(),
sam::toString(edge.tuple).c_str());
return std::pair<bool, SubgraphQueryResultType>(false,
SubgraphQueryResultType());
}
} else if (var2BoundValue.count(src) == 0 &&
var2BoundValue.count(trg) > 0)
{
if (edgeTarget == var2BoundValue.at(trg)) {
NodeType edgeSource = std::get<source>(edge.tuple);
newResult.var2BoundValue[src] = edgeSource;
} else {
DEBUG_PRINT("SubgraphQueryResult::addEdge: edgeTarget %s "
" did not match var2BoundValue.at(trg) %s for tuple %s\n",
edgeTarget.c_str(), var2BoundValue.at(trg).c_str(),
sam::toString(edge.tuple).c_str());
return std::pair<bool, SubgraphQueryResultType>(false,
SubgraphQueryResultType());
}
} else if (var2BoundValue.count(src) == 0 &&
var2BoundValue.count(trg) == 0)
{
newResult.var2BoundValue[src] = edgeSource;
newResult.var2BoundValue[trg] = edgeTarget;
} else {
if (edgeTarget != var2BoundValue.at(trg) ||
edgeSource != var2BoundValue.at(src))
{
DEBUG_PRINT("SubgraphQueryResult::addEdge: edgeTarget %s "
" did not match var2BoundValue.at(trg) %s or edgeSource %s "
" dis not match var2BoundValue.at(src) %s for tuple %s\n",
edgeTarget.c_str(), var2BoundValue.at(trg).c_str(),
edgeSource.c_str(), var2BoundValue.at(src).c_str(),
sam::toString(edge.tuple).c_str());
return std::pair<bool, SubgraphQueryResultType>(false,
SubgraphQueryResultType());
}
}
newResult.resultEdges.push_back(edge);
newResult.currentEdge++;
DEBUG_PRINT("SubgraphQueryResult::addEdge: Added edge %s, update query:"
" %s\n", sam::toString(edge.tuple).c_str(), newResult.toString().c_str());
return std::pair<bool, SubgraphQueryResultType>(true, newResult);
} else {
DEBUG_PRINT("SubgraphQueryResult::addEdge: Did not add edge %s to query %s"
" because the edge had already been seen before.\n",
sam::toString(edge.tuple).c_str(), toString().c_str());
return std::pair<bool, SubgraphQueryResultType>(false,
SubgraphQueryResultType());
}
}
template <typename EdgeType, size_t source, size_t target,
size_t time, size_t duration>
typename SubgraphQueryResult<EdgeType, source,
target, time, duration>::NodeType
SubgraphQueryResult<EdgeType, source, target,
time, duration>::
getCurrentSource() const
{
if (currentEdge >= numEdges) {
std::string message = "SubgraphQueryResult::getCurrentSource "
"Tried to access an edge that is past the index of numEdges: "
"currentEdge " + boost::lexical_cast<std::string>(currentEdge) +
" numEdges " + boost::lexical_cast<std::string>(numEdges);
throw SubgraphQueryResultException(message);
}
std::string sourceVar = subgraphQuery->getEdgeDescription(
currentEdge).getSource();
if (var2BoundValue.count(sourceVar) > 0) {
return var2BoundValue.at(sourceVar);
} else {
return nullValue<NodeType>();
}
}
template <typename EdgeType, size_t source, size_t target,
size_t time, size_t duration>
typename SubgraphQueryResult<EdgeType, source, target,
time, duration>::NodeType
SubgraphQueryResult<EdgeType, source, target,
time, duration>::
getCurrentTarget() const
{
if (currentEdge >= numEdges) {
std::string message = "SubgraphQueryResult::getCurrentTarget Tried to"
" access an edge that is past the index of numEdges";
throw SubgraphQueryResultException(message);
}
std::string targetVar = subgraphQuery->getEdgeDescription(
currentEdge).getTarget();
if (var2BoundValue.count(targetVar) > 0) {
return var2BoundValue.at(targetVar);
} else {
return nullValue<NodeType>();
}
}
template <typename EdgeType, size_t source, size_t target,
size_t time, size_t duration>
double
SubgraphQueryResult<EdgeType, source, target,
time, duration>::
getCurrentStartTimeFirst() const
{
if (currentEdge >= numEdges) {
std::string message = "SubgraphQueryResult::getCurrentStartTimeFirst "
"Tried to access an edge that is past the index of numEdges: "
"currentEdge " + boost::lexical_cast<std::string>(currentEdge) +
" numEdges " + boost::lexical_cast<std::string>(numEdges);
throw SubgraphQueryResultException(message);
}
return startTime +
subgraphQuery->getEdgeDescription(currentEdge).startTimeRange.first;
}
template <typename EdgeType, size_t source, size_t target,
size_t time, size_t duration>
double
SubgraphQueryResult<EdgeType, source, target,
time, duration>::
getCurrentStartTimeSecond() const
{
if (currentEdge >= numEdges) {
std::string message = "SubgraphQueryResult::getCurrentStartTimeSecond "
"Tried to access an edge that is past the index of numEdges";
throw SubgraphQueryResultException(message);
}
return startTime +
subgraphQuery->getEdgeDescription(currentEdge).startTimeRange.second;
}
template <typename EdgeType, size_t source, size_t target,
size_t time, size_t duration>
double
SubgraphQueryResult<EdgeType, source, target,
time, duration>::
getCurrentEndTimeFirst() const
{
if (currentEdge >= numEdges) {
std::string message = "SubgraphQueryResult::getCurrentEndTimeFirst "
"Tried to access an edge that is past the index of numEdges";
throw SubgraphQueryResultException(message);
}
return startTime +
subgraphQuery->getEdgeDescription(currentEdge).endTimeRange.first;
}
template <typename EdgeType, size_t source, size_t target,
size_t time, size_t duration>
double
SubgraphQueryResult<EdgeType, source, target,
time, duration>::
getCurrentEndTimeSecond() const
{
if (currentEdge >= numEdges) {
std::string message = "SubgraphQueryResult::getCurrentEndTimeSecond "
"Tried to access an edge that is past the index of numEdges";
throw SubgraphQueryResultException(message);
}
return startTime +
subgraphQuery->getEdgeDescription(currentEdge).endTimeRange.second;
}
}
#endif
| 35.7949
| 85
| 0.67442
|
elgood
|
fe6340a8ff0b093b349b3245307e3a0e27ab7f00
| 48,602
|
cpp
|
C++
|
openfpga/src/fabric/build_memory_modules.cpp
|
LNIS-Projects/POSH
|
9a3c82039d40c3878549775264b0d769237a65d0
|
[
"MIT"
] | 148
|
2018-08-12T11:25:50.000Z
|
2020-11-30T16:08:54.000Z
|
openfpga/src/fabric/build_memory_modules.cpp
|
VHDL-Digital-Systems/OpenFPGA
|
9d00308166b8800d245b265d7378b0593761a61f
|
[
"MIT"
] | 52
|
2019-01-18T18:54:36.000Z
|
2020-12-01T18:41:36.000Z
|
openfpga/src/fabric/build_memory_modules.cpp
|
VHDL-Digital-Systems/OpenFPGA
|
9d00308166b8800d245b265d7378b0593761a61f
|
[
"MIT"
] | 26
|
2018-06-28T18:12:18.000Z
|
2020-11-24T03:11:46.000Z
|
/*********************************************************************
* This file includes functions to generate Verilog submodules for
* the memories that are affiliated to multiplexers and other programmable
* circuit models, such as IOPADs, LUTs, etc.
********************************************************************/
#include <ctime>
#include <string>
#include <algorithm>
/* Headers from vtrutil library */
#include "vtr_log.h"
#include "vtr_time.h"
#include "vtr_assert.h"
#include "mux_graph.h"
#include "module_manager.h"
#include "circuit_library_utils.h"
#include "decoder_library_utils.h"
#include "module_manager_utils.h"
#include "mux_utils.h"
#include "openfpga_reserved_words.h"
#include "openfpga_naming.h"
#include "build_decoder_modules.h"
#include "build_memory_modules.h"
/* begin namespace openfpga */
namespace openfpga {
/*********************************************************************
* Add module nets to connect an input port of a memory module to
* an input port of its child module
* Restriction: this function is really designed for memory modules
* 1. It assumes that input port name of child module is the same as memory module
* 2. It assumes exact pin-to-pin mapping:
* j-th pin of input port of the i-th child module is wired to the j + i*W -th
* pin of input port of the memory module, where W is the size of port
********************************************************************/
static
void add_module_input_nets_to_mem_modules(ModuleManager& module_manager,
const ModuleId& mem_module,
const ModulePortId& module_port,
const CircuitLibrary& circuit_lib,
const CircuitPortId& circuit_port,
const ModuleId& child_module,
const size_t& child_index,
const size_t& child_instance) {
/* Wire inputs of parent module to inputs of child modules */
ModulePortId src_port_id = module_port;
ModulePortId sink_port_id = module_manager.find_module_port(child_module, circuit_lib.port_prefix(circuit_port));
/* Source pin is shifted by the number of memories */
size_t src_pin_id = module_manager.module_port(mem_module, src_port_id).pins()[child_index];
ModuleNetId net = module_manager.module_instance_port_net(mem_module,
mem_module, 0,
src_port_id, src_pin_id);
if (ModuleNetId::INVALID() == net) {
net = module_manager.create_module_net(mem_module);
module_manager.add_module_net_source(mem_module, net, mem_module, 0, src_port_id, src_pin_id);
}
for (size_t pin_id = 0; pin_id < module_manager.module_port(child_module, sink_port_id).pins().size(); ++pin_id) {
/* Sink node of the input net is the input of sram module */
size_t sink_pin_id = module_manager.module_port(child_module, sink_port_id).pins()[pin_id];
module_manager.add_module_net_sink(mem_module, net, child_module, child_instance, sink_port_id, sink_pin_id);
}
}
/*********************************************************************
* Add module nets to connect an output port of a configuration-chain
* memory module to an output port of its child module
* Restriction: this function is really designed for memory modules
* 1. It assumes that output port name of child module is the same as memory module
* 2. It assumes exact pin-to-pin mapping:
* j-th pin of output port of the i-th child module is wired to the j + i*W -th
* pin of output port of the memory module, where W is the size of port
* 3. It assumes fixed port name for output ports
********************************************************************/
std::vector<ModuleNetId> add_module_output_nets_to_chain_mem_modules(ModuleManager& module_manager,
const ModuleId& mem_module,
const std::string& mem_module_output_name,
const CircuitLibrary& circuit_lib,
const CircuitPortId& circuit_port,
const ModuleId& child_module,
const size_t& child_index,
const size_t& child_instance) {
std::vector<ModuleNetId> module_nets;
/* Wire inputs of parent module to inputs of child modules */
ModulePortId src_port_id = module_manager.find_module_port(child_module, circuit_lib.port_prefix(circuit_port));
ModulePortId sink_port_id = module_manager.find_module_port(mem_module, mem_module_output_name);
for (size_t pin_id = 0; pin_id < module_manager.module_port(child_module, src_port_id).pins().size(); ++pin_id) {
ModuleNetId net = module_manager.create_module_net(mem_module);
/* Source pin is shifted by the number of memories */
size_t src_pin_id = module_manager.module_port(child_module, src_port_id).pins()[pin_id];
/* Source node of the input net is the input of memory module */
module_manager.add_module_net_source(mem_module, net, child_module, child_instance, src_port_id, src_pin_id);
/* Sink node of the input net is the input of sram module */
size_t sink_pin_id = child_index * circuit_lib.port_size(circuit_port) + module_manager.module_port(mem_module, sink_port_id).pins()[pin_id];
module_manager.add_module_net_sink(mem_module, net, mem_module, 0, sink_port_id, sink_pin_id);
/* Cache the nets */
module_nets.push_back(net);
}
return module_nets;
}
/*********************************************************************
* Add module nets to connect an output port of a memory module to
* an output port of its child module
* Restriction: this function is really designed for memory modules
* 1. It assumes that output port name of child module is the same as memory module
* 2. It assumes exact pin-to-pin mapping:
* j-th pin of output port of the i-th child module is wired to the j + i*W -th
* pin of output port of the memory module, where W is the size of port
********************************************************************/
static
void add_module_output_nets_to_mem_modules(ModuleManager& module_manager,
const ModuleId& mem_module,
const CircuitLibrary& circuit_lib,
const std::vector<CircuitPortId>& sram_output_ports,
const ModuleId& child_module,
const size_t& child_index,
const size_t& child_instance) {
for (size_t iport = 0; iport < sram_output_ports.size(); ++iport) {
std::string port_name;
if (0 == iport) {
port_name = generate_configurable_memory_data_out_name();
} else {
VTR_ASSERT( 1 == iport);
port_name = generate_configurable_memory_inverted_data_out_name();
}
add_module_output_nets_to_chain_mem_modules(module_manager, mem_module,
port_name, circuit_lib, sram_output_ports[iport],
child_module, child_index, child_instance);
}
}
/********************************************************************
* Connect all the memory modules under the parent module in a chain
*
* +--------+ +--------+ +--------+
* ccff_head --->| Memory |--->| Memory |--->... --->| Memory |----> ccff_tail
* | Module | | Module | | Module |
* | [0] | | [1] | | [N-1] |
* +--------+ +--------+ +--------+
* For the 1st memory module:
* net source is the configuration chain head of the primitive module
* net sink is the configuration chain head of the next memory module
*
* For the rest of memory modules:
* net source is the configuration chain tail of the previous memory module
* net sink is the configuration chain head of the next memory module
*
* Note that:
* This function is designed for memory modules ONLY!
* Do not use it to replace the
* add_module_nets_cmos_memory_chain_config_bus() !!!
*********************************************************************/
static
void add_module_nets_to_cmos_memory_config_chain_module(ModuleManager& module_manager,
const ModuleId& parent_module,
const CircuitLibrary& circuit_lib,
const CircuitPortId& model_input_port,
const CircuitPortId& model_output_port) {
for (size_t mem_index = 0; mem_index < module_manager.configurable_children(parent_module).size(); ++mem_index) {
ModuleId net_src_module_id;
size_t net_src_instance_id;
ModulePortId net_src_port_id;
ModuleId net_sink_module_id;
size_t net_sink_instance_id;
ModulePortId net_sink_port_id;
if (0 == mem_index) {
/* Find the port name of configuration chain head */
std::string src_port_name = generate_configuration_chain_head_name();
net_src_module_id = parent_module;
net_src_instance_id = 0;
net_src_port_id = module_manager.find_module_port(net_src_module_id, src_port_name);
/* Find the port name of next memory module */
std::string sink_port_name = circuit_lib.port_prefix(model_input_port);
net_sink_module_id = module_manager.configurable_children(parent_module)[mem_index];
net_sink_instance_id = module_manager.configurable_child_instances(parent_module)[mem_index];
net_sink_port_id = module_manager.find_module_port(net_sink_module_id, sink_port_name);
} else {
/* Find the port name of previous memory module */
std::string src_port_name = circuit_lib.port_prefix(model_output_port);
net_src_module_id = module_manager.configurable_children(parent_module)[mem_index - 1];
net_src_instance_id = module_manager.configurable_child_instances(parent_module)[mem_index - 1];
net_src_port_id = module_manager.find_module_port(net_src_module_id, src_port_name);
/* Find the port name of next memory module */
std::string sink_port_name = circuit_lib.port_prefix(model_input_port);
net_sink_module_id = module_manager.configurable_children(parent_module)[mem_index];
net_sink_instance_id = module_manager.configurable_child_instances(parent_module)[mem_index];
net_sink_port_id = module_manager.find_module_port(net_sink_module_id, sink_port_name);
}
/* Get the pin id for source port */
BasicPort net_src_port = module_manager.module_port(net_src_module_id, net_src_port_id);
/* Get the pin id for sink port */
BasicPort net_sink_port = module_manager.module_port(net_sink_module_id, net_sink_port_id);
/* Port sizes of source and sink should match */
VTR_ASSERT(net_src_port.get_width() == net_sink_port.get_width());
/* Create a net for each pin */
for (size_t pin_id = 0; pin_id < net_src_port.pins().size(); ++pin_id) {
/* Create a net and add source and sink to it */
ModuleNetId net = create_module_source_pin_net(module_manager, parent_module, net_src_module_id, net_src_instance_id, net_src_port_id, net_src_port.pins()[pin_id]);
/* Add net sink */
module_manager.add_module_net_sink(parent_module, net, net_sink_module_id, net_sink_instance_id, net_sink_port_id, net_sink_port.pins()[pin_id]);
}
}
/* For the last memory module:
* net source is the configuration chain tail of the previous memory module
* net sink is the configuration chain tail of the primitive module
*/
/* Find the port name of previous memory module */
std::string src_port_name = circuit_lib.port_prefix(model_output_port);
ModuleId net_src_module_id = module_manager.configurable_children(parent_module).back();
size_t net_src_instance_id = module_manager.configurable_child_instances(parent_module).back();
ModulePortId net_src_port_id = module_manager.find_module_port(net_src_module_id, src_port_name);
/* Find the port name of next memory module */
std::string sink_port_name = generate_configuration_chain_tail_name();
ModuleId net_sink_module_id = parent_module;
size_t net_sink_instance_id = 0;
ModulePortId net_sink_port_id = module_manager.find_module_port(net_sink_module_id, sink_port_name);
/* Get the pin id for source port */
BasicPort net_src_port = module_manager.module_port(net_src_module_id, net_src_port_id);
/* Get the pin id for sink port */
BasicPort net_sink_port = module_manager.module_port(net_sink_module_id, net_sink_port_id);
/* Port sizes of source and sink should match */
VTR_ASSERT(net_src_port.get_width() == net_sink_port.get_width());
/* Create a net for each pin */
for (size_t pin_id = 0; pin_id < net_src_port.pins().size(); ++pin_id) {
/* Create a net and add source and sink to it */
ModuleNetId net = create_module_source_pin_net(module_manager, parent_module, net_src_module_id, net_src_instance_id, net_src_port_id, net_src_port.pins()[pin_id]);
/* Add net sink */
module_manager.add_module_net_sink(parent_module, net, net_sink_module_id, net_sink_instance_id, net_sink_port_id, net_sink_port.pins()[pin_id]);
}
}
/********************************************************************
* Connect the scan input of all the memory modules
* under the parent module in a chain
*
* +--------+ +--------+ +--------+
* ccff_head --->| Memory |--->| Memory |--->... --->| Memory |
* | Module | | Module | | Module |
* | [0] | | [1] | | [N-1] |
* +--------+ +--------+ +--------+
* For the 1st memory module:
* net source is the configuration chain head of the primitive module
* net sink is the scan input of the next memory module
*
* For the rest of memory modules:
* net source is the configuration chain tail of the previous memory module
* net sink is the scan input of the next memory module
*
* Note that:
* This function is designed for memory modules ONLY!
* Do not use it to replace the
* add_module_nets_cmos_memory_chain_config_bus() !!!
*********************************************************************/
static
void add_module_nets_to_cmos_memory_scan_chain_module(ModuleManager& module_manager,
const ModuleId& parent_module,
const CircuitLibrary& circuit_lib,
const CircuitPortId& model_input_port,
const CircuitPortId& model_output_port) {
for (size_t mem_index = 0; mem_index < module_manager.configurable_children(parent_module).size(); ++mem_index) {
ModuleId net_src_module_id;
size_t net_src_instance_id;
ModulePortId net_src_port_id;
ModuleId net_sink_module_id;
size_t net_sink_instance_id;
ModulePortId net_sink_port_id;
if (0 == mem_index) {
/* Find the port name of configuration chain head */
std::string src_port_name = generate_configuration_chain_head_name();
net_src_module_id = parent_module;
net_src_instance_id = 0;
net_src_port_id = module_manager.find_module_port(net_src_module_id, src_port_name);
/* Find the port name of next memory module */
std::string sink_port_name = circuit_lib.port_prefix(model_input_port);
net_sink_module_id = module_manager.configurable_children(parent_module)[mem_index];
net_sink_instance_id = module_manager.configurable_child_instances(parent_module)[mem_index];
net_sink_port_id = module_manager.find_module_port(net_sink_module_id, sink_port_name);
} else {
/* Find the port name of previous memory module */
std::string src_port_name = circuit_lib.port_prefix(model_output_port);
net_src_module_id = module_manager.configurable_children(parent_module)[mem_index - 1];
net_src_instance_id = module_manager.configurable_child_instances(parent_module)[mem_index - 1];
net_src_port_id = module_manager.find_module_port(net_src_module_id, src_port_name);
/* Find the port name of next memory module */
std::string sink_port_name = circuit_lib.port_prefix(model_input_port);
net_sink_module_id = module_manager.configurable_children(parent_module)[mem_index];
net_sink_instance_id = module_manager.configurable_child_instances(parent_module)[mem_index];
net_sink_port_id = module_manager.find_module_port(net_sink_module_id, sink_port_name);
}
/* Get the pin id for source port */
BasicPort net_src_port = module_manager.module_port(net_src_module_id, net_src_port_id);
/* Get the pin id for sink port */
BasicPort net_sink_port = module_manager.module_port(net_sink_module_id, net_sink_port_id);
/* Port sizes of source and sink should match */
VTR_ASSERT(net_src_port.get_width() == net_sink_port.get_width());
/* Create a net for each pin */
for (size_t pin_id = 0; pin_id < net_src_port.pins().size(); ++pin_id) {
/* Create a net and add source and sink to it */
ModuleNetId net = create_module_source_pin_net(module_manager, parent_module, net_src_module_id, net_src_instance_id, net_src_port_id, net_src_port.pins()[pin_id]);
/* Add net sink */
module_manager.add_module_net_sink(parent_module, net, net_sink_module_id, net_sink_instance_id, net_sink_port_id, net_sink_port.pins()[pin_id]);
}
}
}
/*********************************************************************
* Flatten memory organization
*
* Bit lines(BL/BLB) Word lines (WL/WLB)
* | |
* v v
* +------------------------------------+
* | Memory Module Configuration port |
* +------------------------------------+
* | | |
* v v v
* +-------+ +-------+ +-------+
* | SRAM | | SRAM | ... | SRAM |
* | [0] | | [1] | | [N-1] |
* +-------+ +-------+ +-------+
* | | ... |
* v v v
* +------------------------------------+
* | Multiplexer Configuration port |
*
********************************************************************/
static
void build_memory_flatten_module(ModuleManager& module_manager,
const CircuitLibrary& circuit_lib,
const std::string& module_name,
const CircuitModelId& sram_model,
const size_t& num_mems) {
/* Get the global ports required by the SRAM */
std::vector<enum e_circuit_model_port_type> global_port_types;
global_port_types.push_back(CIRCUIT_MODEL_PORT_CLOCK);
global_port_types.push_back(CIRCUIT_MODEL_PORT_INPUT);
std::vector<CircuitPortId> sram_global_ports = circuit_lib.model_global_ports_by_type(sram_model, global_port_types, true, false);
/* Get the BL/WL ports from the SRAM */
std::vector<CircuitPortId> sram_bl_ports = circuit_lib.model_ports_by_type(sram_model, CIRCUIT_MODEL_PORT_BL, true);
std::vector<CircuitPortId> sram_wl_ports = circuit_lib.model_ports_by_type(sram_model, CIRCUIT_MODEL_PORT_WL, true);
/* Optional: Get the WLR ports from the SRAM */
std::vector<CircuitPortId> sram_wlr_ports = circuit_lib.model_ports_by_type(sram_model, CIRCUIT_MODEL_PORT_WLR, true);
/* Get the output ports from the SRAM */
std::vector<CircuitPortId> sram_output_ports = circuit_lib.model_ports_by_type(sram_model, CIRCUIT_MODEL_PORT_OUTPUT, true);
/* Ensure that we have only 1 BL, 1 WL and 2 output ports, as well as an optional WLR*/
VTR_ASSERT(1 == sram_bl_ports.size());
VTR_ASSERT(1 == sram_wl_ports.size());
VTR_ASSERT(2 > sram_wlr_ports.size());
VTR_ASSERT(2 == sram_output_ports.size());
/* Create a module and add to the module manager */
ModuleId mem_module = module_manager.add_module(module_name);
VTR_ASSERT(true == module_manager.valid_module_id(mem_module));
/* Label module usage */
module_manager.set_module_usage(mem_module, ModuleManager::MODULE_CONFIG);
/* Add module ports */
/* Input: BL port */
BasicPort bl_port(std::string(MEMORY_BL_PORT_NAME), num_mems);
ModulePortId mem_bl_port = module_manager.add_port(mem_module, bl_port, ModuleManager::MODULE_INPUT_PORT);
BasicPort wl_port(std::string(MEMORY_WL_PORT_NAME), num_mems);
ModulePortId mem_wl_port = module_manager.add_port(mem_module, wl_port, ModuleManager::MODULE_INPUT_PORT);
BasicPort wlr_port(std::string(MEMORY_WLR_PORT_NAME), num_mems);
ModulePortId mem_wlr_port = ModulePortId::INVALID();
if (!sram_wlr_ports.empty()) {
mem_wlr_port = module_manager.add_port(mem_module, wlr_port, ModuleManager::MODULE_INPUT_PORT);
}
/* Add each output port: port width should match the number of memories */
for (size_t iport = 0; iport < sram_output_ports.size(); ++iport) {
std::string port_name;
if (0 == iport) {
port_name = generate_configurable_memory_data_out_name();
} else {
VTR_ASSERT( 1 == iport);
port_name = generate_configurable_memory_inverted_data_out_name();
}
BasicPort output_port(port_name, num_mems);
module_manager.add_port(mem_module, output_port, ModuleManager::MODULE_OUTPUT_PORT);
}
/* Find the sram module in the module manager */
ModuleId sram_mem_module = module_manager.find_module(circuit_lib.model_name(sram_model));
/* Instanciate each submodule */
for (size_t i = 0; i < num_mems; ++i) {
size_t sram_mem_instance = module_manager.num_instance(mem_module, sram_mem_module);
module_manager.add_child_module(mem_module, sram_mem_module);
module_manager.add_configurable_child(mem_module, sram_mem_module, sram_mem_instance);
/* Build module nets */
/* Wire inputs of parent module to inputs of child modules */
for (const CircuitPortId& port : sram_bl_ports) {
add_module_input_nets_to_mem_modules(module_manager, mem_module, mem_bl_port, circuit_lib, port, sram_mem_module, i, sram_mem_instance);
}
for (const CircuitPortId& port : sram_wl_ports) {
add_module_input_nets_to_mem_modules(module_manager, mem_module, mem_wl_port, circuit_lib, port, sram_mem_module, i, sram_mem_instance);
}
for (const CircuitPortId& port : sram_wlr_ports) {
add_module_input_nets_to_mem_modules(module_manager, mem_module, mem_wlr_port, circuit_lib, port, sram_mem_module, i, sram_mem_instance);
}
/* Wire outputs of child module to outputs of parent module */
add_module_output_nets_to_mem_modules(module_manager, mem_module, circuit_lib, sram_output_ports, sram_mem_module, i, sram_mem_instance);
}
/* Add global ports to the pb_module:
* This is a much easier job after adding sub modules (instances),
* we just need to find all the global ports from the child modules and build a list of it
*/
add_module_global_ports_from_child_modules(module_manager, mem_module);
}
/*********************************************************************
* Scan-chain organization
*
* +-------+ +-------+ +-------+
* scan-chain--->| CCFF |--->| CCFF |--->... --->| CCFF |---->scan-chain
* input&clock | [0] | | [1] | | [N-1] | output
* +-------+ +-------+ +-------+
* | | ... | config-memory output
* v v v
* +-----------------------------------------+
* | Multiplexer Configuration port |
*
********************************************************************/
static
void build_memory_chain_module(ModuleManager& module_manager,
const CircuitLibrary& circuit_lib,
const std::string& module_name,
const CircuitModelId& sram_model,
const size_t& num_mems) {
/* Get the input ports from the SRAM */
std::vector<CircuitPortId> sram_input_ports = circuit_lib.model_ports_by_type(sram_model, CIRCUIT_MODEL_PORT_INPUT, true);
/* Should have only 1 or 2 input port */
VTR_ASSERT( (1 == sram_input_ports.size())
|| (2 == sram_input_ports.size()) );
/* Get the output ports from the SRAM */
std::vector<CircuitPortId> sram_output_ports = circuit_lib.model_ports_by_type(sram_model, CIRCUIT_MODEL_PORT_OUTPUT, true);
/* Should have only 1 or 2 or 3 output port */
VTR_ASSERT( (1 == sram_output_ports.size())
|| (2 == sram_output_ports.size())
|| (3 == sram_output_ports.size()) );
/* Create a module and add to the module manager */
ModuleId mem_module = module_manager.add_module(module_name);
VTR_ASSERT(true == module_manager.valid_module_id(mem_module));
/* Label module usage */
module_manager.set_module_usage(mem_module, ModuleManager::MODULE_CONFIG);
/* Add an input port, which is the head of configuration chain in the module */
/* TODO: restriction!!!
* consider only the first input of the CCFF model as the D port,
* which will be connected to the head of the chain
*/
BasicPort chain_head_port(generate_configuration_chain_head_name(),
circuit_lib.port_size(sram_input_ports[0]));
module_manager.add_port(mem_module, chain_head_port, ModuleManager::MODULE_INPUT_PORT);
/* Add an output port, which is the tail of configuration chain in the module */
/* TODO: restriction!!!
* consider only the first output of the CCFF model as the Q port,
* which will be connected to the tail of the chain
*/
BasicPort chain_tail_port(generate_configuration_chain_tail_name(),
circuit_lib.port_size(sram_output_ports[0]));
module_manager.add_port(mem_module, chain_tail_port, ModuleManager::MODULE_OUTPUT_PORT);
/* There could be 3 conditions w.r.t. the number of output ports:
* - Only one output port is defined. In this case, the 1st port is the Q
* In such case, only Q will be considered as data output ports
* - Two output port is defined. In this case, the 1st port is the Q while the 2nd port is the QN
* In such case, both Q and QN will be considered as data output ports
* - Three output port is defined.
* In this case:
* - the 1st port is the Q (the chain output)
* - the 2nd port is the QN (the inverted data output)
* - the 3nd port is the configure-enabled Q
* In such case, configure-enabled Q and QN will be considered as data output ports
*/
size_t num_data_output_ports = sram_output_ports.size();
if (3 == sram_output_ports.size()) {
num_data_output_ports = 2;
}
for (size_t iport = 0; iport < num_data_output_ports; ++iport) {
std::string port_name;
if (0 == iport) {
port_name = generate_configurable_memory_data_out_name();
} else if (1 == iport) {
port_name = generate_configurable_memory_inverted_data_out_name();
}
BasicPort output_port(port_name, num_mems);
module_manager.add_port(mem_module, output_port, ModuleManager::MODULE_OUTPUT_PORT);
}
/* Find the sram module in the module manager */
ModuleId sram_mem_module = module_manager.find_module(circuit_lib.model_name(sram_model));
/* Instanciate each submodule */
for (size_t i = 0; i < num_mems; ++i) {
size_t sram_mem_instance = module_manager.num_instance(mem_module, sram_mem_module);
module_manager.add_child_module(mem_module, sram_mem_module);
module_manager.add_configurable_child(mem_module, sram_mem_module, sram_mem_instance);
/* Build module nets to wire outputs of sram modules to outputs of memory module */
for (size_t iport = 0; iport < num_data_output_ports; ++iport) {
std::string port_name;
if (0 == iport) {
port_name = generate_configurable_memory_data_out_name();
} else {
VTR_ASSERT( 1 == iport);
port_name = generate_configurable_memory_inverted_data_out_name();
}
/* Find the proper data output port
* The exception is when there are 3 output ports defined
* The 3rd port is the regular data output port to be used
*/
CircuitPortId data_output_port_to_connect = sram_output_ports[iport];
if ((3 == sram_output_ports.size()) && (0 == iport)) {
data_output_port_to_connect = sram_output_ports.back();
}
std::vector<ModuleNetId> output_nets = add_module_output_nets_to_chain_mem_modules(module_manager, mem_module,
port_name, circuit_lib, data_output_port_to_connect,
sram_mem_module, i, sram_mem_instance);
}
}
/* Build module nets to wire the configuration chain */
add_module_nets_to_cmos_memory_config_chain_module(module_manager, mem_module,
circuit_lib, sram_input_ports[0], sram_output_ports[0]);
/* If there is a second input defined,
* add nets to short wire the 2nd inputs to the first inputs
*/
if (2 == sram_input_ports.size()) {
add_module_nets_to_cmos_memory_scan_chain_module(module_manager, mem_module,
circuit_lib, sram_input_ports[1], sram_output_ports[0]);
}
/* Add global ports to the pb_module:
* This is a much easier job after adding sub modules (instances),
* we just need to find all the global ports from the child modules and build a list of it
*/
add_module_global_ports_from_child_modules(module_manager, mem_module);
}
/*********************************************************************
* Frame-based Memory organization
*
* EN Address Data
* | | |
* v v v
* +------------------------------------+
* | Address Decoder |
* +------------------------------------+
* | | |
* v v v
* +-------+ +-------+ +-------+
* | SRAM | | SRAM | ... | SRAM |
* | [0] | | [1] | | [N-1] |
* +-------+ +-------+ +-------+
* | | ... |
* v v v
* +------------------------------------+
* | Multiplexer Configuration port |
*
********************************************************************/
static
void build_frame_memory_module(ModuleManager& module_manager,
DecoderLibrary& frame_decoder_lib,
const CircuitLibrary& circuit_lib,
const std::string& module_name,
const CircuitModelId& sram_model,
const size_t& num_mems) {
/* Get the global ports required by the SRAM */
std::vector<enum e_circuit_model_port_type> global_port_types;
global_port_types.push_back(CIRCUIT_MODEL_PORT_CLOCK);
global_port_types.push_back(CIRCUIT_MODEL_PORT_INPUT);
std::vector<CircuitPortId> sram_global_ports = circuit_lib.model_global_ports_by_type(sram_model, global_port_types, true, false);
/* Get the input ports from the SRAM */
std::vector<CircuitPortId> sram_input_ports = circuit_lib.model_ports_by_type(sram_model, CIRCUIT_MODEL_PORT_INPUT, true);
/* A SRAM cell with BL/WL should not have any input */
VTR_ASSERT( 0 == sram_input_ports.size() );
/* Get the output ports from the SRAM */
std::vector<CircuitPortId> sram_output_ports = circuit_lib.model_ports_by_type(sram_model, CIRCUIT_MODEL_PORT_OUTPUT, true);
/* Get the BL/WL ports from the SRAM
* Here, we consider that the WL port will be EN signal of a SRAM
* and the BL port will be the data_in signal of a SRAM
*/
std::vector<CircuitPortId> sram_bl_ports = circuit_lib.model_ports_by_type(sram_model, CIRCUIT_MODEL_PORT_BL, true);
std::vector<CircuitPortId> sram_blb_ports = circuit_lib.model_ports_by_type(sram_model, CIRCUIT_MODEL_PORT_BLB, true);
std::vector<CircuitPortId> sram_wl_ports = circuit_lib.model_ports_by_type(sram_model, CIRCUIT_MODEL_PORT_WL, true);
std::vector<CircuitPortId> sram_wlb_ports = circuit_lib.model_ports_by_type(sram_model, CIRCUIT_MODEL_PORT_WLB, true);
/* We do NOT expect any BLB port here!!!
* TODO: to suppor this, we need an inverter circuit model to be specified by users !!!
*/
VTR_ASSERT(1 == sram_bl_ports.size());
VTR_ASSERT(1 == circuit_lib.port_size(sram_bl_ports[0]));
VTR_ASSERT(1 == sram_wl_ports.size());
VTR_ASSERT(1 == circuit_lib.port_size(sram_wl_ports[0]));
VTR_ASSERT(0 == sram_blb_ports.size());
/* Create a module and add to the module manager */
ModuleId mem_module = module_manager.add_module(module_name);
VTR_ASSERT(true == module_manager.valid_module_id(mem_module));
/* Label module usage */
module_manager.set_module_usage(mem_module, ModuleManager::MODULE_CONFIG);
/* Find the specification of the decoder:
* Size of address port and data input
*/
size_t addr_size = find_mux_local_decoder_addr_size(num_mems);
/* Data input should match the WL (data_in) of a SRAM */
size_t data_size = num_mems * circuit_lib.port_size(sram_bl_ports[0]);
bool use_data_inv = (0 < sram_blb_ports.size());
/* Search the decoder library
* If we find one, we use the module.
* Otherwise, we create one and add it to the decoder library
*/
DecoderId decoder_id = frame_decoder_lib.find_decoder(addr_size, data_size, true, false, use_data_inv, false);
if (DecoderId::INVALID() == decoder_id) {
decoder_id = frame_decoder_lib.add_decoder(addr_size, data_size, true, false, use_data_inv, false);
}
VTR_ASSERT(DecoderId::INVALID() != decoder_id);
/* Create a module if not existed yet */
std::string decoder_module_name = generate_memory_decoder_subckt_name(addr_size, data_size);
ModuleId decoder_module = module_manager.find_module(decoder_module_name);
if (ModuleId::INVALID() == decoder_module) {
decoder_module = build_frame_memory_decoder_module(module_manager,
frame_decoder_lib,
decoder_id);
}
VTR_ASSERT(ModuleId::INVALID() != decoder_module);
/* Add module ports */
/* Input: Enable port */
BasicPort en_port(std::string(DECODER_ENABLE_PORT_NAME), 1);
ModulePortId mem_en_port = module_manager.add_port(mem_module, en_port, ModuleManager::MODULE_INPUT_PORT);
/* Input: Address port */
BasicPort addr_port(std::string(DECODER_ADDRESS_PORT_NAME), addr_size);
ModulePortId mem_addr_port = module_manager.add_port(mem_module, addr_port, ModuleManager::MODULE_INPUT_PORT);
/* Input: Data port */
BasicPort data_port(std::string(DECODER_DATA_IN_PORT_NAME), 1);
ModulePortId mem_data_port = module_manager.add_port(mem_module, data_port, ModuleManager::MODULE_INPUT_PORT);
/* Should have only 1 or 2 output port */
VTR_ASSERT( (1 == sram_output_ports.size()) || ( 2 == sram_output_ports.size()) );
/* Add each output port: port width should match the number of memories */
for (size_t iport = 0; iport < sram_output_ports.size(); ++iport) {
std::string port_name;
if (0 == iport) {
port_name = generate_configurable_memory_data_out_name();
} else {
VTR_ASSERT( 1 == iport);
port_name = generate_configurable_memory_inverted_data_out_name();
}
BasicPort output_port(port_name, num_mems);
module_manager.add_port(mem_module, output_port, ModuleManager::MODULE_OUTPUT_PORT);
}
/* Instanciate the decoder module here */
VTR_ASSERT(0 == module_manager.num_instance(mem_module, decoder_module));
module_manager.add_child_module(mem_module, decoder_module);
/* Find the sram module in the module manager */
ModuleId sram_mem_module = module_manager.find_module(circuit_lib.model_name(sram_model));
/* Build module nets */
/* Wire enable port to decoder enable port */
ModulePortId decoder_en_port = module_manager.find_module_port(decoder_module, std::string(DECODER_ENABLE_PORT_NAME));
add_module_bus_nets(module_manager, mem_module,
mem_module, 0, mem_en_port,
decoder_module, 0, decoder_en_port);
/* Wire address port to decoder address port */
ModulePortId decoder_addr_port = module_manager.find_module_port(decoder_module, std::string(DECODER_ADDRESS_PORT_NAME));
add_module_bus_nets(module_manager, mem_module,
mem_module, 0, mem_addr_port,
decoder_module, 0, decoder_addr_port);
/* Instanciate each submodule */
for (size_t i = 0; i < num_mems; ++i) {
/* Memory seed module instanciation */
size_t sram_instance = module_manager.num_instance(mem_module, sram_mem_module);
module_manager.add_child_module(mem_module, sram_mem_module);
module_manager.add_configurable_child(mem_module, sram_mem_module, sram_instance);
/* Wire data_in port to SRAM BL port */
ModulePortId sram_bl_port = module_manager.find_module_port(sram_mem_module, circuit_lib.port_prefix(sram_bl_ports[0]));
add_module_bus_nets(module_manager, mem_module,
mem_module, 0, mem_data_port,
sram_mem_module, sram_instance, sram_bl_port);
/* Wire decoder data_out port to sram WL ports */
ModulePortId sram_wl_port = module_manager.find_module_port(sram_mem_module, circuit_lib.port_prefix(sram_wl_ports[0]));
ModulePortId decoder_data_port = module_manager.find_module_port(decoder_module, std::string(DECODER_DATA_OUT_PORT_NAME));
ModuleNetId wl_net = module_manager.create_module_net(mem_module);
/* Source node of the input net is the input of memory module */
module_manager.add_module_net_source(mem_module, wl_net, decoder_module, 0, decoder_data_port, sram_instance);
module_manager.add_module_net_sink(mem_module, wl_net, sram_mem_module, sram_instance, sram_wl_port, 0);
/* Optional: Wire decoder data_out inverted port to sram WLB ports */
if (true == use_data_inv) {
ModulePortId sram_wlb_port = module_manager.find_module_port(sram_mem_module, circuit_lib.port_lib_name(sram_wlb_ports[0]));
ModulePortId decoder_data_inv_port = module_manager.find_module_port(decoder_module, std::string(DECODER_DATA_OUT_INV_PORT_NAME));
ModuleNetId wlb_net = module_manager.create_module_net(mem_module);
/* Source node of the input net is the input of memory module */
module_manager.add_module_net_source(mem_module, wlb_net, decoder_module, 0, decoder_data_inv_port, sram_instance);
module_manager.add_module_net_sink(mem_module, wlb_net, sram_mem_module, sram_instance, sram_wlb_port, 0);
}
/* Wire inputs of parent module to outputs of child modules */
for (size_t iport = 0; iport < sram_output_ports.size(); ++iport) {
std::string port_name;
if (0 == iport) {
port_name = generate_configurable_memory_data_out_name();
} else {
VTR_ASSERT( 1 == iport);
port_name = generate_configurable_memory_inverted_data_out_name();
}
add_module_output_nets_to_chain_mem_modules(module_manager, mem_module,
port_name, circuit_lib, sram_output_ports[iport],
sram_mem_module, i, sram_instance);
}
}
/* Add global ports to the pb_module:
* This is a much easier job after adding sub modules (instances),
* we just need to find all the global ports from the child modules and build a list of it
*/
add_module_global_ports_from_child_modules(module_manager, mem_module);
/* Add the decoder as the last configurable children */
module_manager.add_configurable_child(mem_module, decoder_module, 0);
}
/*********************************************************************
* Generate Verilog modules for the memories that are used
* by a circuit model
* The organization of memory circuit will depend on the style of
* configuration protocols
* Currently, we support
* 1. Flat SRAM organization
* 2. Configuration chain
* 3. Memory bank (memory decoders)
********************************************************************/
static
void build_memory_module(ModuleManager& module_manager,
DecoderLibrary& arch_decoder_lib,
const CircuitLibrary& circuit_lib,
const e_config_protocol_type& sram_orgz_type,
const std::string& module_name,
const CircuitModelId& sram_model,
const size_t& num_mems) {
switch (sram_orgz_type) {
case CONFIG_MEM_STANDALONE:
case CONFIG_MEM_QL_MEMORY_BANK:
case CONFIG_MEM_MEMORY_BANK:
build_memory_flatten_module(module_manager, circuit_lib,
module_name, sram_model, num_mems);
break;
case CONFIG_MEM_SCAN_CHAIN:
build_memory_chain_module(module_manager, circuit_lib,
module_name, sram_model, num_mems);
break;
case CONFIG_MEM_FRAME_BASED:
build_frame_memory_module(module_manager, arch_decoder_lib, circuit_lib,
module_name, sram_model, num_mems);
break;
default:
VTR_LOGF_ERROR(__FILE__, __LINE__,
"Invalid configurable memory organization!\n");
exit(1);
}
}
/*********************************************************************
* Generate Verilog modules for the memories that are used
* by multiplexers
*
* +----------------+
* mem_in --->| Memory Module |---> mem_out
* +----------------+
* | | ... | |
* v v v v SRAM ports of multiplexer
* +---------------------+
* in--->| Multiplexer Module |---> out
* +---------------------+
********************************************************************/
static
void build_mux_memory_module(ModuleManager& module_manager,
DecoderLibrary& arch_decoder_lib,
const CircuitLibrary& circuit_lib,
const e_config_protocol_type& sram_orgz_type,
const CircuitModelId& mux_model,
const MuxGraph& mux_graph) {
/* Find the actual number of configuration bits, based on the mux graph
* Due to the use of local decoders inside mux, this may be
*/
size_t num_config_bits = find_mux_num_config_bits(circuit_lib, mux_model, mux_graph, sram_orgz_type);
/* Multiplexers built with different technology is in different organization */
switch (circuit_lib.design_tech_type(mux_model)) {
case CIRCUIT_MODEL_DESIGN_CMOS: {
/* Generate module name */
std::string module_name = generate_mux_subckt_name(circuit_lib, mux_model,
find_mux_num_datapath_inputs(circuit_lib, mux_model, mux_graph.num_inputs()),
std::string(MEMORY_MODULE_POSTFIX));
/* Get the sram ports from the mux */
std::vector<CircuitModelId> sram_models = find_circuit_sram_models(circuit_lib, mux_model);
VTR_ASSERT( 1 == sram_models.size() );
build_memory_module(module_manager, arch_decoder_lib,
circuit_lib, sram_orgz_type, module_name, sram_models[0], num_config_bits);
break;
}
case CIRCUIT_MODEL_DESIGN_RRAM:
/* We do not need a memory submodule for RRAM MUX,
* RRAM are embedded in the datapath
* TODO: generate local encoders for RRAM-based multiplexers here!!!
*/
break;
default:
VTR_LOGF_ERROR(__FILE__, __LINE__,
"Invalid design technology of multiplexer '%s'\n",
circuit_lib.model_name(mux_model).c_str());
exit(1);
}
}
/*********************************************************************
* Build modules for
* the memories that are affiliated to multiplexers and other programmable
* circuit models, such as IOPADs, LUTs, etc.
*
* We keep the memory modules separated from the multiplexers and other
* programmable circuit models, for the sake of supporting
* various configuration schemes.
* By following such organiztion, the Verilog modules of the circuit models
* implements the functionality (circuit logic) only, while the memory Verilog
* modules implements the memory circuits as well as configuration protocols.
* For example, the local decoders of multiplexers are implemented in the
* memory modules.
* Take another example, the memory circuit can implement the scan-chain or
* memory-bank organization for the memories.
********************************************************************/
void build_memory_modules(ModuleManager& module_manager,
DecoderLibrary& arch_decoder_lib,
const MuxLibrary& mux_lib,
const CircuitLibrary& circuit_lib,
const e_config_protocol_type& sram_orgz_type) {
vtr::ScopedStartFinishTimer timer("Build memory modules");
/* Create the memory circuits for the multiplexer */
for (auto mux : mux_lib.muxes()) {
const MuxGraph& mux_graph = mux_lib.mux_graph(mux);
CircuitModelId mux_model = mux_lib.mux_circuit_model(mux);
/* Bypass the non-MUX circuit models (i.e., LUTs).
* They should be handled in a different way
* Memory circuits of LUT includes both regular and mode-select ports
*/
if (CIRCUIT_MODEL_MUX != circuit_lib.model_type(mux_model)) {
continue;
}
/* Create a Verilog module for the memories used by the multiplexer */
build_mux_memory_module(module_manager, arch_decoder_lib,
circuit_lib, sram_orgz_type, mux_model, mux_graph);
}
/* Create the memory circuits for non-MUX circuit models.
* In this case, the memory modules are designed to interface
* the mode-select ports
*/
for (const auto& model : circuit_lib.models()) {
/* Bypass MUXes, they have already been considered */
if (CIRCUIT_MODEL_MUX == circuit_lib.model_type(model)) {
continue;
}
/* Bypass those modules without any SRAM ports */
std::vector<CircuitPortId> sram_ports = circuit_lib.model_ports_by_type(model, CIRCUIT_MODEL_PORT_SRAM, true);
if (0 == sram_ports.size()) {
continue;
}
/* Find the name of memory module */
/* Get the total number of SRAMs */
size_t num_mems = 0;
for (const auto& port : sram_ports) {
num_mems += circuit_lib.port_size(port);
}
/* Get the circuit model for the memory circuit used by the multiplexer */
std::vector<CircuitModelId> sram_models = find_circuit_sram_models(circuit_lib, model);
/* Should have only 1 SRAM model */
VTR_ASSERT( 1 == sram_models.size() );
/* Create the module name for the memory block */
std::string module_name = generate_memory_module_name(circuit_lib, model, sram_models[0], std::string(MEMORY_MODULE_POSTFIX));
/* Create a Verilog module for the memories used by the circuit model */
build_memory_module(module_manager, arch_decoder_lib,
circuit_lib, sram_orgz_type, module_name, sram_models[0], num_mems);
}
}
} /* end namespace openfpga */
| 51.213909
| 170
| 0.638451
|
LNIS-Projects
|
fe6507d57a1b28cddc2b3fedea4b54aea30bb8ef
| 1,931
|
cpp
|
C++
|
Graph/kruskal.cpp
|
kasettakorn/algorithms
|
877c0be14b1816efe02bad8f1556c2af378ab2d1
|
[
"MIT"
] | null | null | null |
Graph/kruskal.cpp
|
kasettakorn/algorithms
|
877c0be14b1816efe02bad8f1556c2af378ab2d1
|
[
"MIT"
] | null | null | null |
Graph/kruskal.cpp
|
kasettakorn/algorithms
|
877c0be14b1816efe02bad8f1556c2af378ab2d1
|
[
"MIT"
] | null | null | null |
// Online C++ compiler to run C++ program online
#include <iostream>
#include <algorithm>
#define MAXV 500
typedef struct
{
int edges[MAXV][MAXV];
int degrees[MAXV];
bool visited[MAXV];
int nedges, nvertices;
} Graph;
typedef struct
{
int start;
int finish;
int distance;
} Vertex;
using namespace std;
bool comparator(Vertex v1, Vertex v2) {
return v1.distance < v2.distance;
}
bool isCycle(Graph *g, int start, int finish) {
for(int i=0; i<g->nvertices; i++) {
}
}
void kruskal(Graph *g) {
Vertex v[g->nedges];
int count = 0;
for(int i=0; i<g->nvertices; i++) {
for(int j=0; j<g->nvertices; j++) {
if(g->edges[i][j] > 0) {
v[count].start = i;
v[count].finish = j;
v[count].distance = g->edges[i][j];
g->edges[j][i] = -1;
count++;
}
}
}
sort(v, v+count, comparator);
cout << endl;
int visited[g->nvertices];
for(int i=0; i<count; i++) {
if(!isCycle(g, v[i].start, v[i].finish)) {
g->edges[v[i].start][v[i].finish] = v[i].distance;
g->edges[v[i].finish][v[i].start] = v[i].distance;
}
}
for(int i=0; i<g->nvertices; i++) {
for(int j=0; j<g->nvertices; j++) {
if(g->edges[i][j] > 0) {
cout << i << "-" << j << " = " << g->edges[i][j] << endl;
g->edges[j][i] = 0;
}
}
}
}
int main() {
// Write C++ code here
Graph g;
cin >> g.nvertices >> g.nedges;
for (int i = 0; i < g.nedges; i++)
{
int start, finish, distance;
cin >> start >> finish >> distance;
g.edges[start][finish] = distance;
g.edges[finish][start] = distance;
}
kruskal(&g);
return 0;
}
// 8 9
// 0 1
// 1 2
// 1 6
// 2 6
// 4 2
// 5 1
// 5 3
// 6 7
// 7 5
| 21.943182
| 73
| 0.469705
|
kasettakorn
|
fe68a253f284820b8a0c1100b0657db7080b1891
| 3,800
|
cpp
|
C++
|
src/xserver_emscripten.cpp
|
QuantStack/xeus
|
40bc5a0865d1076a5d17e16ba43e1362bd9bbd8c
|
[
"BSD-3-Clause"
] | 559
|
2016-12-07T11:37:24.000Z
|
2019-12-23T12:20:38.000Z
|
src/xserver_emscripten.cpp
|
QuantStack/xeus
|
40bc5a0865d1076a5d17e16ba43e1362bd9bbd8c
|
[
"BSD-3-Clause"
] | 90
|
2016-12-07T12:06:33.000Z
|
2019-12-19T17:42:17.000Z
|
src/xserver_emscripten.cpp
|
QuantStack/xeus
|
40bc5a0865d1076a5d17e16ba43e1362bd9bbd8c
|
[
"BSD-3-Clause"
] | 52
|
2016-12-08T21:20:11.000Z
|
2019-12-10T09:14:48.000Z
|
#include "xeus/xeus.hpp"
#include "xeus/xserver.hpp"
#include "xeus/xmessage.hpp"
#include "xeus/xkernel_configuration.hpp"
#include "xeus/xserver_emscripten.hpp"
#include "xeus/xembind.hpp"
#include <iostream>
#include <emscripten.h>
namespace nl = nlohmann;
namespace ems = emscripten;
namespace xeus
{
EM_JS(ems::EM_VAL, get_stdin, (), {
return Asyncify.handleAsync(() => {
return globalThis.get_stdin().then(msg => {
return Emval.toHandle(msg);
});
});
});
EM_JS(void, post_kernel_message, (const char* channel, ems::EM_VAL message_handle), {
var message = Emval.toValue(message_handle);
message.channel = UTF8ToString(channel);
if (typeof self !== 'undefined') {
self.postMessage(message);
}
});
xtrivial_emscripten_messenger::xtrivial_emscripten_messenger(xserver_emscripten* server)
: p_server(server)
{
}
xtrivial_emscripten_messenger::~xtrivial_emscripten_messenger()
{
}
nl::json xtrivial_emscripten_messenger::send_to_shell_impl(const nl::json& message)
{
return p_server->notify_internal_listener(message);
}
xserver_emscripten::xserver_emscripten(const xconfiguration& /*config*/)
: p_messenger(new xtrivial_emscripten_messenger(this))
{
}
xserver_emscripten::~xserver_emscripten()
{
}
void xserver_emscripten::js_notify_listener(ems::val js_message)
{
const std::string channel = js_message["channel"].as<std::string>();
auto message = xmessage_from_js_message(js_message);
if(channel == "shell")
{
this->notify_shell_listener(std::move(message));
}
else if(channel == "control")
{
this->notify_control_listener(std::move(message));
}
else if(channel == "stdin")
{
this->notify_stdin_listener(std::move(message));
}
else
{
throw std::runtime_error("unknown channel");
}
}
xcontrol_messenger& xserver_emscripten::get_control_messenger_impl()
{
return *p_messenger;
}
void xserver_emscripten::send_shell_impl(xmessage message)
{
post_kernel_message("shell", js_message_from_xmessage(message, true).as_handle());
}
void xserver_emscripten::send_control_impl(xmessage message)
{
post_kernel_message("control", js_message_from_xmessage(message, true).as_handle());
}
void xserver_emscripten::send_stdin_impl(xmessage message)
{
post_kernel_message("stdin", js_message_from_xmessage(message, true).as_handle());
// Block until a response to the input request is received.
ems::val js_message = ems::val::take_ownership(get_stdin());
try
{
auto reply = xmessage_from_js_message(js_message);
xserver::notify_stdin_listener(std::move(reply));
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
}
void xserver_emscripten::publish_impl(xpub_message message, channel)
{
post_kernel_message("iopub", js_message_from_xmessage(message, true).as_handle());
}
void xserver_emscripten::start_impl(xpub_message /*message*/)
{
}
void xserver_emscripten::abort_queue_impl(const listener& /*l*/, long /*polling_interval*/)
{
}
void xserver_emscripten::stop_impl()
{
}
void xserver_emscripten::update_config_impl(xconfiguration& /*config*/) const
{
}
std::unique_ptr<xserver> make_xserver_emscripten(xcontext& /*context*/, const xconfiguration& config, nl::json::error_handler_t /*eh*/)
{
return std::make_unique<xserver_emscripten>(config);
}
}
| 27.941176
| 139
| 0.643421
|
QuantStack
|
fe6a7a5513d95d947a47347a67fcd0264deb5d9a
| 2,508
|
cpp
|
C++
|
branch/old_angsys/angsys_beta3/source/angsys/angsys.shared/source/async/thread_manager.cpp
|
ChuyX3/angsys
|
89b2eaee866bcfd11e66efda49b38acc7468c780
|
[
"Apache-2.0"
] | null | null | null |
branch/old_angsys/angsys_beta3/source/angsys/angsys.shared/source/async/thread_manager.cpp
|
ChuyX3/angsys
|
89b2eaee866bcfd11e66efda49b38acc7468c780
|
[
"Apache-2.0"
] | null | null | null |
branch/old_angsys/angsys_beta3/source/angsys/angsys.shared/source/async/thread_manager.cpp
|
ChuyX3/angsys
|
89b2eaee866bcfd11e66efda49b38acc7468c780
|
[
"Apache-2.0"
] | null | null | null |
#include "pch.h"
#include <ang/core/async.h>
#include "thread_manager.h"
//#if defined _DEBUG || defined _DEVELOPPER
//#define new new(__FILE__, __LINE__)
//#define new_args(...) new(__VAR_ARGS__, __FILE__, __LINE__)
//#else
//#define new_args(...) new(__VAR_ARGS__)
//#endif // MEMORY_
using namespace ang;
using namespace ang::core;
using namespace ang::core::async;
//////////////////////////////////////////////////////////////////////
thread_manager::thread_manager()
: _thread_map()
, _main_cond()
, _main_mutex()
, _main_thread(null)
{
_main_thread = attach_this_thread(new worker_thread(), true);
_attached_threads += _main_thread;
//_main_thread->AddRef();
_thread_map.insert(worker_thread::this_thread_id(), _main_thread);
}
thread_manager::~thread_manager()
{
_main_mutex.lock();
_thread_map.clear();
_main_thread = null;
_attached_threads.reset();
_main_mutex.unlock();
}
worker_thread_t thread_manager::attach_this_thread(worker_thread_t thread, bool isMain)
{
if (thread.is_empty()) thread = new worker_thread();
thread->m_is_main_thread = isMain;
thread->attach();
return thread;
}
dword thread_manager::this_thread_id()
{
#if defined ANDROID_PLATFORM || defined LINUX_PLATFORM
return (dword)pthread_self();
#elif defined WINDOWS_PLATFORM
return GetCurrentThreadId();
#endif
}
worker_thread_t thread_manager::main_thread()const
{
return _main_thread;
}
worker_thread_t thread_manager::this_thread()const
{
worker_thread_t thread = null;
_main_mutex.lock();
if (!_thread_map.find(this_thread_id(), &thread))
{
thread = const_cast<thread_manager*>(this)->attach_this_thread(null, false);
const_cast<thread_manager*>(this)->_thread_map.insert(this_thread_id(), thread);
const_cast<thread_manager*>(this)->_attached_threads += thread;
}
else {
thread->add_ref();
}
_main_mutex.unlock();
return thread;
}
worker_thread* thread_manager::regist_thread(worker_thread* thread)
{
worker_thread* result = null;
_main_mutex.lock();
if (_thread_map.insert(thread->thread_id(), thread))
result = thread;
_main_mutex.unlock();
return result;
}
worker_thread* thread_manager::unregist_thread(worker_thread* thread)
{
worker_thread* result = null;
_main_mutex.lock();
if (!_thread_map.remove(thread->this_thread_id(), &result))
result = null;
_main_mutex.unlock();
return result;
}
/////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////
/////////////
| 24.115385
| 87
| 0.680223
|
ChuyX3
|
fe6f3cf671a7217f45b6ad4d7a39d8b00534b66a
| 3,413
|
cpp
|
C++
|
module/buffer/src/buffer/AtomicContainerDataFaster.cpp
|
Khoronus/StoreData
|
067c64cc0e240412fab99759fab5b88083d0dbe0
|
[
"MIT"
] | null | null | null |
module/buffer/src/buffer/AtomicContainerDataFaster.cpp
|
Khoronus/StoreData
|
067c64cc0e240412fab99759fab5b88083d0dbe0
|
[
"MIT"
] | null | null | null |
module/buffer/src/buffer/AtomicContainerDataFaster.cpp
|
Khoronus/StoreData
|
067c64cc0e240412fab99759fab5b88083d0dbe0
|
[
"MIT"
] | null | null | null |
/* @file AtomicContainerDataFaster.cpp
* @brief Main file with the example for the hog descriptor and visualization.
*
* @section LICENSE
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR/AUTHORS 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 Alessandro Moro <alessandromoro.italy@gmail.com>
* @bug No known bugs.
* @version 0.1.0.0
*
*/
#include "buffer/inc/buffer/AtomicContainerDataFaster.hpp"
namespace storedata
{
//-----------------------------------------------------------------------------
AtomicContainerDataFaster::AtomicContainerDataFaster() {
data_ = nullptr;
}
//-----------------------------------------------------------------------------
void AtomicContainerDataFaster::set_unique_msg(const std::string &unique_msg) {
unique_msg_ = unique_msg;
}
//-----------------------------------------------------------------------------
void AtomicContainerDataFaster::copyFrom(const void* src,
size_t src_size_bytes) {
if (data_) dispose();
size_bytes_ = src_size_bytes;
data_ = malloc(size_bytes_);
std::memcpy(data_, src, size_bytes_);
safe_dispose_ = true;
}
//-----------------------------------------------------------------------------
void AtomicContainerDataFaster::copyFrom(AtomicContainerDataFaster &obj) {
if (data_) dispose();
size_bytes_ = obj.size_bytes();
data_ = malloc(size_bytes_);
memcpy(data_, obj.data(), obj.size_bytes());
safe_dispose_ = true;
}
//-----------------------------------------------------------------------------
void AtomicContainerDataFaster::assignFrom(void* src, size_t src_size_bytes) {
if (data_) dispose();
size_bytes_ = src_size_bytes;
data_ = src;
safe_dispose_ = false;
}
//-----------------------------------------------------------------------------
void AtomicContainerDataFaster::assignFrom(AtomicContainerDataFaster &obj) {
if (data_) dispose();
size_bytes_ = obj.size_bytes();
data_ = obj.data();
safe_dispose_ = false;
}
//-----------------------------------------------------------------------------
void AtomicContainerDataFaster::dispose() {
if (safe_dispose_ && data_) { free(data_); data_ = nullptr; }
}
//-----------------------------------------------------------------------------
std::string AtomicContainerDataFaster::unique_msg() {
return unique_msg_;
}
//-----------------------------------------------------------------------------
void* AtomicContainerDataFaster::data() {
return data_;
}
//-----------------------------------------------------------------------------
size_t AtomicContainerDataFaster::size_bytes() {
return size_bytes_;
}
//-----------------------------------------------------------------------------
bool AtomicContainerDataFaster::safe_dispose() {
return safe_dispose_;
}
} // namespace storedata
| 38.348315
| 79
| 0.564899
|
Khoronus
|
fe7339f73246d5876d68a29349339fb579c7406b
| 18,279
|
cpp
|
C++
|
startalk_ui/EmotionTabDialog.cpp
|
xuepingiw/open_source_startalk
|
44d962b04039f5660ec47a10313876a0754d3e72
|
[
"MIT"
] | 34
|
2019-03-18T08:09:24.000Z
|
2022-03-15T02:03:25.000Z
|
startalk_ui/EmotionTabDialog.cpp
|
venliong/open_source_startalk
|
51fda091a932a8adea626c312692836555753a9a
|
[
"MIT"
] | 5
|
2019-05-29T09:32:05.000Z
|
2019-08-29T03:01:33.000Z
|
startalk_ui/EmotionTabDialog.cpp
|
venliong/open_source_startalk
|
51fda091a932a8adea626c312692836555753a9a
|
[
"MIT"
] | 32
|
2019-03-15T09:43:22.000Z
|
2021-08-10T08:26:02.000Z
|
#include "EmotionTabDialog.h"
#include <QApplication>
#include <QDesktopWidget>
#include <QStackedLayout>
#include "LanguageHelper.h"
#include "QFileDialog"
#include "Session.h"
#include "Account.h"
#include "AccountData.h"
#include "EmotionListData.h"
#include "ConfigureHelper.h"
#include "EmotionManager.h"
#include "Player.h"
#include "diywidgit/customviews/qframelayout.h"
#include "../3rd/quazip/JlCompress.h"
#include "UIFrame.h"
#include "NotifyCenterController.h"
#include "emotionmanagerdialog.h"
#include "SettingData.h"
const static char* user_data = "user_data";
const static int btnwidth = 40;
EmotionTabDialog::EmotionTabDialog(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
using namespace Qt;
auto remove = WindowTitleHint;
auto add = FramelessWindowHint | WindowMinMaxButtonsHint | Popup;
setAttribute(Qt::WA_TranslucentBackground, true);
//setAutoFillBackground(true);
overrideWindowFlags( (Qt::WindowFlags)((windowFlags() & ~remove) | add));
//setBackgroundRole();
//让移动的宽度,每次移动一个按钮的宽度
QScrollBar* bar = ui.scrollArea->horizontalScrollBar();
bar->setSingleStep(btnwidth + 1);
InitMenu();
InitEmotion();
connect(ui.setting, &QPushButton::clicked, this, &EmotionTabDialog::OnSettingBtnClicked);
connect(ui.leftpage,&QPushButton::clicked,[this](bool bcheck){
QScrollBar* bar = ui.scrollArea->horizontalScrollBar();
// bar->setValue(qMax(0,bar->value()-bar->pageStep()));
bar->setValue(bar->value()-btnwidth);
int val = bar->value();
ui.leftpage->setEnabled(bar->value()>0);
ui.rightpage->setEnabled(bar->value()<bar->maximum());
});
connect(ui.rightpage,&QPushButton::clicked,[this](bool bcheck){
QScrollBar* bar = ui.scrollArea->horizontalScrollBar();
// bar->setValue(qMin(bar->maximum(),bar->value()+bar->pageStep()));
bar->setValue(bar->value()+btnwidth);
int val = bar->value();
ui.leftpage->setEnabled(bar->value()>0);
ui.rightpage->setEnabled(bar->value()<bar->maximum());
});
connect(ui.scrollArea->horizontalScrollBar(),&QAbstractSlider::rangeChanged,[this](int min, int max){
ui.leftpage->setVisible(true);
ui.rightpage->setVisible(true);
QScrollBar* bar = ui.scrollArea->horizontalScrollBar();
ui.leftpage->setEnabled(bar->value()>0);
ui.rightpage->setEnabled(bar->value()<bar->maximum());
});
// ui.lastpage->setVisible(false);
// ui.nextpage->setVisible(false);
ui.leftpage->setArrowType(Qt::LeftArrow);
ui.rightpage->setArrowType(Qt::RightArrow);
// ui.setting ->setVisible(false);
QFrameLayout* layout = new QFrameLayout(ui.contentpanel);
layout->appendWidget(ui.stackedWidget,ALINE_FILL);
layout->appendWidget(ui.emotListPanel,ALINE_FILL);
ui.contentpanel->setLayout(layout);
//layout->setCurrentWidget(ui.stackedWidget);
ui.emotListPanel->setVisible(false);
ui.emotList->setAutoExclusive(true);
connect(ui.emotList,&QPushButton::clicked,this,&EmotionTabDialog::onCheckEmotionBtnClicked);
connect(Biz::Session::getEmoticonManager(),&Biz::EmotionManager::sgReloadEmojiconPackage,this,&EmotionTabDialog::onReloadEmojiconPackage);
connect(Biz::Session::getEmoticonManager(),&Biz::EmotionManager::sgUploadEmotionResult,[this](bool result){
MainApp::UIFrame::getNotifyCenterController ()->popupNotice (result?QStringLiteral("收藏图片成功"):QStringLiteral("收藏图片失败"));
if (result)
{
Biz::Session::getEmoticonManager()->sgSaveEmotionSuccess();
}
});
connect(Biz::Session::getEmoticonManager(), &Biz::EmotionManager::sgDeleteCustomerEmotion, this, &EmotionTabDialog::onDeleteCustormerEmotion);
connect(Biz::Session::getEmoticonManager(), &Biz::EmotionManager::sgDownloadFinishEmotionPackage, this, &EmotionTabDialog::OnDownloadFinishEmotionPackage);
}
EmotionTabDialog::~EmotionTabDialog()
{
}
void EmotionTabDialog::init()
{
}
void EmotionTabDialog::autoshow()
{
QPoint pos = QCursor::pos();
int heightscreen=QApplication::desktop()->screenGeometry().bottom();
int h = 210;
int width = this->geometry().width();
int height = this->geometry().height();
//让图像框显示在工具条的上面
if ( ((pos.x() - width/2) >0) && ((pos.y() -height - 20) > 0) )
{
this->move(pos.x() - width/2, pos.y() - height - 20);
}
else
{
this->move(pos);
}
bool hasChecked = false;
for (int i=0;i<ui.btngroup_layout->count();i++)
{
QPushButton* pbtn =dynamic_cast<QPushButton*>(ui.btngroup_layout->itemAt(i)->widget());
if (pbtn!=NULL)
{
hasChecked |= pbtn->isChecked();
}
}
if (!hasChecked && ui.btngroup_layout->count() > 1 )
{
QPushButton* pbtn =dynamic_cast<QPushButton*>(ui.btngroup_layout->itemAt(1)->widget());
if (NULL!=pbtn)
{
pbtn->click();
}
}
show();
activateWindow();
}
void EmotionTabDialog::InitEmotion()
{
// 获取所有的表情包id
QStringList list = Biz::Session::getEmoticonManager()->getEmoticonIds();
if (list.contains("qunar_camel"))
{
addOneEmotionPackage("qunar_camel");
list.removeOne("qunar_camel");
}
for (QString pid:list)
{
addOneEmotionPackage(pid);
}
}
void EmotionTabDialog::addOneEmotionPackage(const QString& pkgid)
{
//判断一下
if (parseToolBarContianBtn(pkgid))
{
return;
}
QPushButton* pbtn = new QPushButton(ui.btngroup);
pbtn->setAutoExclusive(true);
pbtn->setProperty(user_data,pkgid);
pbtn->setFlat(true);
pbtn->setCheckable(true);
pbtn->setFixedSize(btnwidth,30);
do
{
QSharedPointer<Biz::EmoticonPackage> spPackage = Biz::Session::getEmoticonManager()->getEmotionPackageInfo(pkgid);
if (!spPackage.isNull())
{
if (spPackage->strPackageId == Biz::EmotionManager::sCustomPackageName)
{
QPixmap couver(":Images/custom_emoj_btn.png");
couver.setDevicePixelRatio(1.0);
pbtn->setIcon(couver);
pbtn->setIconSize(QSize(24,24));
break;
}
QSharedPointer<Biz::EmotionItem> spItem = spPackage->packageCoverImg;
if (spItem.isNull() && spPackage->emotionList.size()>0)
{
spItem = spPackage->emotionList.at(0);
}
if (!spItem.isNull())
{
QPixmap couver(spItem->strPath);
if (!couver.isNull())
{
couver.setDevicePixelRatio(1.0);
pbtn->setIcon(couver);
pbtn->setIconSize(QSize(24,24));
break;
}
else
{
pbtn->setText(spPackage->strPackageDesc);
break;
}
}
}
pbtn->setText(pkgid);
} while (false);
ui.btngroup_layout->addWidget(pbtn);
connect(pbtn,&QPushButton::clicked,this,&EmotionTabDialog::onTabBtnClicked);
int fixwidth = (ui.btngroup_layout->count()-1)*(btnwidth+ui.btngroup_layout->spacing()) + 70+ui.btngroup_layout->spacing();
ui.btngroup->setFixedWidth(fixwidth);
}
void EmotionTabDialog::onTabBtnClicked( bool b )
{
QPushButton* btn = dynamic_cast<QPushButton*>(sender());
// 表情切换
QString pkgid = btn->property(user_data).toString();
if (pkgid.isEmpty())
{
return;
}
if (!mapEmoticonDialogs.contains(pkgid))
{
EmotionDialog* pDialog = new EmotionDialog(this);
pDialog->setitemInLine(7);
pDialog->setitemSize(61);
pDialog->setitempadding(5);
pDialog->initEmoticonPkgIcons(pkgid);
mapEmoticonDialogs.insert(pkgid,pDialog);
ui.stackedWidget->addWidget(pDialog);
connect(pDialog,&EmotionDialog::sgSelectItem,this,&EmotionTabDialog::onEmoticonSelected);
}
ui.stackedWidget->setCurrentWidget(mapEmoticonDialogs.value(pkgid));
ui.emotListPanel->setVisible(false);
}
void EmotionTabDialog::OnSettingMenu()
{
settingMenu->exec(QCursor::pos());
}
void EmotionTabDialog::onImportEmotion()
{
//
// QString strDir = QFileDialog::getExistingDirectory(this, "Open Directory", "", QFileDialog::ShowDirsOnly|QFileDialog::DontResolveSymlinks);
// if (!strDir.isEmpty())
// {
// int npos = strDir.lastIndexOf("/");
// QString FileName = strDir.mid(npos+1);
// //onCreateOnePBInPanl(FileName.replace("Emoticon", ""), strDir + QString("/%1.xml").arg(FileName));
// Biz::EmotionListData* gld = Biz::Session::currentAccount().getEmotionsData();
// Biz::EmotionSetting *setting = gld->getEmotionSetting();
//
// setting->TitleName(FileName.replace("Emoticon", ""));
// setting->EmotionPath(strDir + QString("/%1.xml").arg(FileName));
//
//
// //写数据到Emotion.dat文件中
// Biz::Session::currentAccount().saveEmotionListData();
// }
}
void EmotionTabDialog::onExportEmotion()
{
}
void EmotionTabDialog::onCustomEmotion()
{
}
void EmotionTabDialog::InitMenu()
{
settingMenu = new QMenu(ui.setting);
QAction* action = NULL;
action = new QAction(T_("Emotion_ImportMenu"),ui.setting);
connect(action,&QAction::triggered,this,&EmotionTabDialog::onImportEmotion);
settingMenu->addAction(action);
action = NULL;
action = new QAction(T_("Emotion_ExportMenu"), ui.setting);
connect(action, &QAction::triggered,this,&EmotionTabDialog::onExportEmotion);
settingMenu->addAction(action);
settingMenu->addSeparator();
action = NULL;
action = new QAction(T_("Emotion_CustomMenu"), ui.setting);
connect(action, &QAction::triggered,this,&EmotionTabDialog::onCustomEmotion);
settingMenu->addAction(action);
}
QStringList EmotionTabDialog::getAllPackageIds()
{
QStringList strList;
strList = Biz::Session::getEmoticonManager()->getEmoticonIds();
return strList;
}
void EmotionTabDialog::onEmoticonSelected(const QString& pkgid,const QString& shortcut)
{
QSharedPointer<Biz::EmoticonPackage> spPackage = Biz::Session::getEmoticonManager()->getEmotionPackageInfo(pkgid);
if (!spPackage.isNull())
{
if (spPackage->bMiniData)
{
QSharedPointer<Biz::EmotionItem> spItem = spPackage->emotionMap.value(shortcut);
if (!spItem.isNull())
{
if (!spItem->strUrl.isEmpty())
emit sgSendUrlImage(mconversionId,pkgid,shortcut);
else
emit sgSendImage(mconversionId,spItem->strPath);
}
}
else
{
emit sgSelectItem(mconversionId,pkgid,shortcut);
}
}
this->hide();
}
void EmotionTabDialog::onCheckEmotionBtnClicked(bool bcheck)
{
ui.emotListPanel->setVisible(ui.emotList->isChecked());
disconnect(Biz::Session::getEmoticonManager(),&Biz::EmotionManager::sgEmotionInfoListRecvied,this,&EmotionTabDialog::onEmotionInfoListRecvied);
connect(Biz::Session::getEmoticonManager(),&Biz::EmotionManager::sgEmotionInfoListRecvied,this,&EmotionTabDialog::onEmotionInfoListRecvied);
Biz::Session::getEmoticonManager()->getEmotionsPackages();
}
void EmotionTabDialog::onEmotionInfoListRecvied(const QList<QSharedPointer<Biz::EmoticonPackageInfo>>& list)
{
QVBoxLayout* hl = (QVBoxLayout*)ui.emotcionShop->layout();
QLayoutItem *child;
while ((child = hl->takeAt(0)) != 0) {
QWidget* pWidget = child->widget();
if (NULL!=pWidget)
{
pWidget->setParent(NULL);
delete pWidget;
}
delete child;
}
QStringList localPkgid = Biz::Session::getEmoticonManager()->getEmoticonIds();
//看有多少被删除的
Biz::AllUserSettingData *pSetting = Biz::Session::getSettingConfig();
QString strdelete = pSetting->DeleteEmotionList();
QStringList strdeletelist;
if (!strdelete.isEmpty())
{
strdeletelist = strdelete.split(",");
}
for (QSharedPointer<Biz::EmoticonPackageInfo> item:list)
{
if (item->id().isEmpty())
{
continue;
}
EmoticonDownloadInfoWidget* widget = new EmoticonDownloadInfoWidget(ui.emotcionShop);
hl->addWidget(widget);
widget->name->setText(item->name());
widget->desc->setText(item->desc());
widget->spEpinfo = item;
widget->pTabDialog = this;
if (localPkgid.contains(item->id()))
{
if (strdeletelist.contains(item->id()))
{
widget->download->setText(QStringLiteral("下载"));
widget->download->setEnabled(true);
}
else
{
widget->download->setText(QStringLiteral("已下载"));
widget->download->setEnabled(false);
}
}
}
}
void EmotionTabDialog::onReloadEmojiconPackage(const QString& pkgid)
{
if (mapEmoticonDialogs.contains(pkgid))
{
EmotionDialog* pDialog = mapEmoticonDialogs.value(pkgid);
pDialog->initEmoticonPkgIcons(pkgid);
}
}
void EmotionTabDialog::OnSettingBtnClicked()
{
EmotionManagerDialog *pEmotionManagerdlg = EmotionManagerDialog::getInstance();
if(pEmotionManagerdlg)
{
if(!pEmotionManagerdlg->isVisible())
{
pEmotionManagerdlg->onShowEmotionManagerDialog();
}
else
{
pEmotionManagerdlg->hide();
}
this->close();
}
}
void EmotionTabDialog::onDeleteCustormerEmotion( const QString&pkgid )
{
if ( pkgid == Biz::EmotionManager::sCustomPackageName )//删除自定义中的表情
{
if ( mapEmoticonDialogs.contains(pkgid))
{
EmotionDialog* pDialog = mapEmoticonDialogs.value(pkgid);
pDialog->initEmoticonPkgIcons(pkgid);
}
}
else //删除管理的表情
{
//先删掉toolbar上的btn
QPushButton*pbtn = getEmotionButtonById(pkgid);
if (pbtn)
{
ui.btngroup_layout->removeWidget(pbtn);
}
int fixwidth = (ui.btngroup_layout->count()-1)*(btnwidth+ui.btngroup_layout->spacing()) + 70+ui.btngroup_layout->spacing();
ui.btngroup->setFixedWidth(fixwidth);
//然后删掉页面中的Dialog
EmotionDialog* pDialog = mapEmoticonDialogs.value(pkgid);
if (pDialog)
{
mapEmoticonDialogs.remove(pkgid);
ui.stackedWidget->removeWidget(pDialog);
}
//下载页面中的下载按钮,“已下载”变成“下载”
//emit Biz::Session::getEmoticonManager()->sgDeleteEmotionPackage(pkgid);
QStringList localPkgid = Biz::Session::getEmoticonManager()->getEmoticonIds();
QVBoxLayout* hl = (QVBoxLayout*)ui.emotcionShop->layout();
QLayoutItem *child;
while ((child = hl->takeAt(0)) != 0) {
EmoticonDownloadInfoWidget* pWidget = (EmoticonDownloadInfoWidget*)child->widget();
if (NULL!=pWidget)
{
if (pkgid == pWidget->spEpinfo->id())
{
pWidget->download->setText(QStringLiteral("下载"));
pWidget->download->setEnabled(true);
break;
}
}
}
}
}
void EmotionTabDialog::OnDownloadFinishEmotionPackage( const QString&pkgid )
{
addOneEmotionPackage(pkgid);
}
bool EmotionTabDialog::parseToolBarContianBtn( const QString&id )
{
QStringList ids;
bool bResult = false;
for (int i=0;i<ui.btngroup_layout->count();i++)
{
QPushButton* pbtn =dynamic_cast<QPushButton*>(ui.btngroup_layout->itemAt(i)->widget());
if (pbtn!=NULL)
{
ids.push_back(pbtn->property(user_data).toString());
}
}
if (ids.contains(id))
{
bResult = true;
}
return bResult;
}
QPushButton* EmotionTabDialog::getEmotionButtonById( const QString&id )
{
QStringList ids;
bool bResult = false;
QPushButton *retBtn = NULL;
for (int i=0;i<ui.btngroup_layout->count();i++)
{
QPushButton* pbtn =dynamic_cast<QPushButton*>(ui.btngroup_layout->itemAt(i)->widget());
if (pbtn!=NULL)
{
QString btnId = pbtn->property(user_data).toString();
if (id == btnId)
{
retBtn = pbtn;
break;
}
}
}
return retBtn;
}
EmoticonDownloadInfoWidget::EmoticonDownloadInfoWidget(QWidget* parent) :QWidget(parent),pTabDialog(NULL)
{
// 横向布局 头像+文字区+按钮
horizontalLayout_5 = new QHBoxLayout(this);
horizontalLayout_5->setContentsMargins(10, 0, 10, 0);
// 右侧头像
label = new QLabel(this);
label->setMinimumSize(QSize(32, 32));
label->setMaximumSize(QSize(32, 32));
label->setStyleSheet(QLatin1String("image:url(:/Images/toolbar_emoticon_hover.png);\n"
"border:2px solid #666666;\n"
"border-radius: 4px;"));
horizontalLayout_5->addWidget(label);
widget_5 = new QWidget(this);
verticalLayout_3 = new QVBoxLayout(widget_5);
verticalLayout_3->setSpacing(0);
verticalLayout_3->setContentsMargins(0, 0, 0, 0);
widget_6 = new QWidget(widget_5);
widget_6->setObjectName(QStringLiteral("widget_6"));
verticalLayout_4 = new QVBoxLayout(widget_6);
verticalLayout_4->setSpacing(0);
verticalLayout_4->setContentsMargins(0, 0, 0, 0);
name = new QLabel(widget_6);
name->setObjectName(QStringLiteral("name"));
verticalLayout_4->addWidget(name);
verticalLayout_3->addWidget(widget_6);
widget_8 = new QWidget(widget_5);
verticalLayout_5 = new QVBoxLayout(widget_8);
verticalLayout_5->setSpacing(0);
verticalLayout_5->setObjectName(QStringLiteral("verticalLayout_5"));
verticalLayout_5->setContentsMargins(0, 0, 0, 0);
desc = new QLabel(widget_8);
desc->setObjectName(QStringLiteral("desc"));
verticalLayout_5->addWidget(desc);
verticalLayout_3->addWidget(widget_8);
horizontalLayout_5->addWidget(widget_5);
download = new QPushButton(this);
download->setText(QStringLiteral("下载"));
download->setMinimumSize(QSize(70, 30));
download->setMaximumSize(QSize(70, 30));
horizontalLayout_5->addWidget(download);
connect(download,&QPushButton::clicked,[this](bool b){
if (!spEpinfo.isNull())
{
Biz::Session::getEmoticonManager()->downloadEmotionsPackage(spEpinfo);
}
});
connect(Biz::Session::getEmoticonManager(),&Biz::EmotionManager::sgUpdateDescription,this,&EmoticonDownloadInfoWidget::onUpdateDescription);
connect(Biz::Session::getEmoticonManager(),&Biz::EmotionManager::sgDownloadPackageResult,this,&EmoticonDownloadInfoWidget::onDownloadPackageResult);
connect(Biz::Session::getEmoticonManager(),&Biz::EmotionManager::sgDeleteEmotionPackage, this, &EmoticonDownloadInfoWidget::onDeleteEmotionPackage);
}
void EmoticonDownloadInfoWidget::onUpdateDescription(const QString& pkgid, const QString& descinfo)
{
if (pkgid != spEpinfo->id())
{
return;
}
this->desc->setText(descinfo);
}
void EmoticonDownloadInfoWidget::onDownloadPackageResult(const QString& pkgid,bool bResult)
{
if (spEpinfo->id()!=pkgid)
{
return;
}
if (bResult)
{
this->download->setText(QStringLiteral("已下载"));
this->download->setEnabled(false);
this->desc->setText(spEpinfo->desc());
if (NULL!=pTabDialog)
{
pTabDialog->addOneEmotionPackage(pkgid);
}
}
else
{
this->desc->setText(QStringLiteral("下载失败"));
}
}
void EmoticonDownloadInfoWidget::onDeleteEmotionPackage( const QString& pkgid )
{
if (pkgid.isEmpty() || spEpinfo->id()!=pkgid )
{
return;
}
this->download->setText(QStringLiteral("下载"));
this->download->setEnabled(true);
}
EmoticonDownloadInfoWidget::~EmoticonDownloadInfoWidget()
{
}
| 27.120178
| 157
| 0.698835
|
xuepingiw
|
fe76dbde2028b20a1cadf9392ce3e6ff2019f314
| 581
|
hh
|
C++
|
textQuery/v3/TextQuery.hh
|
snow-tyan/learn-cpp
|
ecab0fae7999005ed7fdb60ff4954b4014b2c2e6
|
[
"MulanPSL-1.0"
] | null | null | null |
textQuery/v3/TextQuery.hh
|
snow-tyan/learn-cpp
|
ecab0fae7999005ed7fdb60ff4954b4014b2c2e6
|
[
"MulanPSL-1.0"
] | null | null | null |
textQuery/v3/TextQuery.hh
|
snow-tyan/learn-cpp
|
ecab0fae7999005ed7fdb60ff4954b4014b2c2e6
|
[
"MulanPSL-1.0"
] | null | null | null |
#pragma once
#include "QueryResult.hh"
#include <iostream>
#include <memory>
#include <vector>
#include <string>
#include <map>
#include <set>
#include <fstream>
using namespace std;
class QueryResult;
class TextQuery
{
public:
TextQuery(ifstream &);
QueryResult query(const string &) const;
void checkFile() const
{
for (const string &line : *_file)
cout << line << endl;
}
private:
static string cleanup_str(const string&); // 忽略标点大小写
private:
shared_ptr<vector<string>> _file;
map<string, shared_ptr<set<int>>> _map;
};
| 17.088235
| 56
| 0.660929
|
snow-tyan
|
fe77abf80934b8d011df4da358b72ddbb9ed1d4e
| 131
|
hxx
|
C++
|
src/Providers/UNIXProviders/ServiceStatistics/UNIX_ServiceStatistics_DARWIN.hxx
|
brunolauze/openpegasus-providers-old
|
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
|
[
"MIT"
] | 1
|
2020-10-12T09:00:09.000Z
|
2020-10-12T09:00:09.000Z
|
src/Providers/UNIXProviders/ServiceStatistics/UNIX_ServiceStatistics_DARWIN.hxx
|
brunolauze/openpegasus-providers-old
|
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
|
[
"MIT"
] | null | null | null |
src/Providers/UNIXProviders/ServiceStatistics/UNIX_ServiceStatistics_DARWIN.hxx
|
brunolauze/openpegasus-providers-old
|
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
|
[
"MIT"
] | null | null | null |
#ifdef PEGASUS_OS_DARWIN
#ifndef __UNIX_SERVICESTATISTICS_PRIVATE_H
#define __UNIX_SERVICESTATISTICS_PRIVATE_H
#endif
#endif
| 10.916667
| 42
| 0.854962
|
brunolauze
|
fe7e5823e4f366d4ea2a1ca4d128e0cee37b4e5a
| 11,555
|
cpp
|
C++
|
common/src/ninjamclient.cpp
|
ventosus/abNinjam
|
fc50af9e2603c2184f24f3a3483203d69d4b2c2a
|
[
"MIT"
] | 14
|
2020-05-13T21:14:22.000Z
|
2021-04-05T12:28:00.000Z
|
common/src/ninjamclient.cpp
|
ventosus/abNinjam
|
fc50af9e2603c2184f24f3a3483203d69d4b2c2a
|
[
"MIT"
] | 12
|
2020-05-13T22:56:29.000Z
|
2021-07-08T13:17:32.000Z
|
common/src/ninjamclient.cpp
|
ventosus/abNinjam
|
fc50af9e2603c2184f24f3a3483203d69d4b2c2a
|
[
"MIT"
] | 4
|
2020-05-15T11:03:42.000Z
|
2020-11-24T18:06:29.000Z
|
#include "../include/ninjamclient.h"
#include "../include/fileutil.h"
#include "../include/licensedialog.h"
#include "../include/stringutil.h"
#include <sstream>
using namespace AbNinjam::Common;
using namespace std;
static int agree = 1;
static bool autoAgree = false;
static int bpm = 110;
int licensecallback(void *userData, const char *licensetext) {
L_(ltrace) << "Entering licensecallback";
if (autoAgree) {
return true;
}
LicenseDialog *licenseDialog = new LicenseDialog();
agree = licenseDialog->showDialog(licensetext);
if (agree == 0) {
return true;
}
return false;
}
void chatmsg_cb(void *userData, NJClient *inst, const char **parms,
int nparms) {
L_(ltrace) << "Entering chatmsg_cb";
if (parms[2] && !strcmp(parms[2], "No BPM/BPI permission")) {
L_(ldebug) << parms[2];
string message = "!vote bpm ";
message.append(to_string(bpm));
inst->ChatMessage_Send("MSG", message.c_str());
}
}
NinjamClient::NinjamClient() {
L_(ltrace) << "[NinjamClient] Entering NinjamClient::NinjamClient";
njClient->config_savelocalaudio = 1;
njClient->LicenseAgreementCallback = licensecallback;
njClient->ChatMessage_Callback = chatmsg_cb;
njClient->SetLocalChannelInfo(0, "channel0", true, 0, false, 0, true, true);
njClient->SetLocalChannelMonitoring(0, false, 0.0f, false, 0.0f, false, false,
false, false);
connectionThread = nullptr;
stopConnectionThread = true;
}
NinjamClient::~NinjamClient() {
L_(ltrace) << "[NinjamClient] Entering NinjamClient::~NinjamClient";
disconnect();
}
void keepConnectionThread(NinjamClient *ninjamClient) {
L_(ltrace) << "Entering keepConnectionThread";
// TODO: use scoped_lock for all environments when becomes available
#ifdef unix
scoped_lock<mutex> lock(ninjamClient->gsMtx());
#elif defined(_WIN32)
lock_guard<mutex> lock(ninjamClient->gsMtx());
#endif
ninjamClient->gsStopConnectionThread() = false;
NJClient *g_client = ninjamClient->gsNjClient();
bool connected = false;
while (g_client->GetStatus() >= 0 &&
ninjamClient->gsStopConnectionThread() == false) {
if (g_client->Run()) {
// Sleep to prevent 100% CPU usage
#ifdef unix
struct timespec ts = {0, 1000 * 1000};
nanosleep(&ts, nullptr);
#elif defined(_WIN32)
HANDLE hTimer = NULL;
LARGE_INTEGER liDueTime;
liDueTime.QuadPart = -10000LL;
// Create an unnamed waitable timer.
hTimer = CreateWaitableTimer(NULL, TRUE, NULL);
if (NULL == hTimer) {
L_(ltrace) << "CreateWaitableTimer failed";
} else {
// Set a timer to wait for 1 ms.
if (!SetWaitableTimer(hTimer, &liDueTime, 0, NULL, NULL, 0)) {
L_(ltrace) << "SetWaitableTimer failed";
} else {
if (WaitForSingleObject(hTimer, INFINITE) != WAIT_OBJECT_0) {
L_(ltrace) << "WaitForSingleObject failed";
} else {
L_(ltrace) << "Timer was signaled.";
}
}
}
#endif
if (g_client->GetStatus() == 0) {
if (!connected) {
L_(ldebug) << "status: " << g_client->GetStatus();
L_(ldebug) << "bpi: " << g_client->GetBPI();
L_(ldebug) << "bpm: " << g_client->GetActualBPM();
L_(ldebug) << "is audio running: " << g_client->IsAudioRunning();
L_(ldebug) << "user: " << g_client->GetUser();
L_(ldebug) << "hostname: " << g_client->GetHostName();
L_(ldebug) << "num users: " << g_client->GetNumUsers() << endl;
}
connected = true;
}
}
}
}
NinjamClientStatus
NinjamClient::connect(ConnectionProperties *connectionProperties) {
L_(ltrace) << "[NinjamClient] Entering NinjamClient::connect";
path propertiesPath = getHomePath();
ostringstream oss;
oss << "abNinjam" << separator() << "connection.properties";
propertiesPath /= oss.str();
if (exists(propertiesPath)) {
L_(ldebug) << "Configuration file provided: " << propertiesPath;
connectionProperties->readFromFile(propertiesPath);
} else {
L_(ldebug) << "[NinjamClient] Configuration file not provided.";
}
if (isEmpty(connectionProperties->gsHost())) {
return serverNotProvided;
}
if (isEmpty(connectionProperties->gsUsername())) {
connectionProperties->gsUsername() = strdup("anonymous");
}
agree = 1;
autoAgree = connectionProperties->gsAutoLicenseAgree();
autoRemoteVolume = connectionProperties->gsAutoRemoteVolume();
L_(ltrace) << "[NinjamClient] Status: " << njClient->GetStatus();
L_(ltrace) << "[NinjamClient] IsAudioRunning: " << njClient->IsAudioRunning();
// TODO: check if "if" condition is needed here
if (njClient->GetStatus() != 0 && njClient->IsAudioRunning() != 1) {
njClient->Connect(connectionProperties->gsHost(),
connectionProperties->gsUsername(),
connectionProperties->gsPassword());
}
while (njClient->GetStatus() >= 0) {
if (njClient->Run()) {
if (njClient->GetStatus() == 0) {
L_(ldebug) << "Connected";
connected = true;
break;
}
}
}
if (connected) {
connectionThread = new thread(keepConnectionThread, this);
if (connectionThread) {
connectionThread->detach();
}
return ok;
}
if (agree == 256) {
L_(lwarning) << "[NinjamClient] License not accepted. Not Connected.";
return licenseNotAccepted;
}
L_(lerror) << "[NinjamClient] Connection error";
return connectionError;
}
void NinjamClient::disconnect() {
L_(ltrace) << "[NinjamClient] Entering NinjamClient::disconnect";
stopConnectionThread = true;
if (connectionThread) {
if (connectionThread->joinable()) {
connectionThread->join();
} else {
// L_(ltrace) << "delete";
// delete connectionThread;
}
}
if (connected && njClient) {
njClient->Disconnect();
}
connected = false;
}
void NinjamClient::audiostreamOnSamples(float **inbuf, int innch,
float **outbuf, int outnch, int len,
int srate) {
// L_(ltrace) << "[NinjamClient] Entering NinjamClient::audiostreamOnSamples";
if (!connected) {
// clear all output buffers
clearBuffers(outbuf, outnch, len);
}
if (connected) {
njClient->AudioProc(inbuf, innch, outbuf, outnch, len, srate);
}
}
void NinjamClient::audiostreamForSync(float **inbuf, int innch, float **outbuf,
int outnch, int len, int srate) {
L_(ltrace) << "[NinjamClient] Entering NinjamClient::audiostreamForSync";
clearBuffers(outbuf, outnch, len);
if (connected) {
clearBuffers(inbuf, innch, len);
njClient->AudioProc(inbuf, innch, outbuf, outnch, len, srate);
clearBuffers(outbuf, outnch, len);
clearBuffers(inbuf, innch, len);
}
}
void NinjamClient::clearBuffers(float **buf, int nch, int len) {
// L_(ltrace) << "[NinjamClient] Entering NinjamClient::clearBuffers";
int x;
for (x = 0; x < nch; x++)
memset(buf[x], 0, sizeof(float) * static_cast<unsigned long>(len));
return;
}
void NinjamClient::adjustVolume() {
L_(ltrace) << "[NinjamClient] Entering NinjamClient::adjustVolume";
if (autoRemoteVolume) {
int totalRemoteChannels = 0;
float adjustedVolume = 1.f;
int mostUserChannels = 0;
int numUsers = njClient->GetNumUsers();
L_(ldebug) << "[NinjamClient] numUsers: " << numUsers;
if (numUsers < ADJUST_VOLUME) {
for (int useridx = 0; useridx < numUsers; useridx++) {
for (int channelidx = 0; channelidx < MAX_USER_CHANNELS; channelidx++) {
if (njClient->EnumUserChannels(useridx, channelidx) > -1) {
totalRemoteChannels++;
if (channelidx > mostUserChannels) {
mostUserChannels = channelidx;
}
} else {
break;
}
}
}
L_(ldebug) << "[PlugProcessor] totalRemoteChannels: "
<< totalRemoteChannels;
if (totalRemoteChannels > 0) {
adjustedVolume = adjustedVolume / totalRemoteChannels;
L_(ldebug) << "[PlugProcessor] adjustedVolume: " << adjustedVolume;
for (int useridx = 0; useridx < numUsers; useridx++) {
for (int channelidx = 0; channelidx <= mostUserChannels;
channelidx++) {
setUserChannelVolume(useridx, channelidx, adjustedVolume);
}
L_(ltrace) << "[PlugProcessor] Channels volume updated for useridx: "
<< useridx;
}
}
}
}
}
std::vector<AbNinjam::Common::RemoteUser> NinjamClient::getRemoteUsers() {
L_(ltrace) << "[NinjamClient] Entering NinjamClient::getRemoteUsers";
std::vector<RemoteUser> users;
int numUsers = njClient->GetNumUsers();
L_(ltrace) << "[NinjamClient] numUsers: " << numUsers;
for (int useridx = 0; useridx < numUsers; useridx++) {
RemoteUser *user = new RemoteUser();
user->id = useridx;
user->name = njClient->GetUserState(useridx);
L_(ltrace) << "[NinjamClient] user->id: " << user->id;
L_(ltrace) << "[NinjamClient] user->name: " << user->name;
for (int channelidx = 0; channelidx < MAX_USER_CHANNELS; channelidx++) {
float vol;
char *result =
njClient->GetUserChannelState(useridx, channelidx, nullptr, &vol);
if (result != 0) {
RemoteChannel *channel = new RemoteChannel();
channel->id = channelidx;
channel->volume = vol;
channel->name = result;
user->channels.push_back(*channel);
L_(ltrace) << "[NinjamClient] channel->id: " << channel->id;
L_(ltrace) << "[NinjamClient] channel->volume: " << channel->volume;
L_(ltrace) << "[NinjamClient] channel->name: " << channel->name;
} else {
L_(ltrace) << "[NinjamClient] No channel with id " << channelidx
<< " found for user " << user->name;
}
}
users.push_back(*user);
}
return users;
}
void NinjamClient::setBpm(int tempo) {
L_(ltrace) << "[NinjamClient] Entering NinjamClient::setBpm";
bpm = tempo;
string message = "bpm ";
message.append(to_string(tempo));
njClient->ChatMessage_Send("ADMIN", message.c_str());
}
void NinjamClient::setUserChannelVolume(int userId, int channelId,
float volume) {
L_(ltrace) << "[NinjamClient] Entering NinjamClient::setUserChannelVolume";
L_(ltrace) << "[NinjamClient] userId: " << userId;
L_(ltrace) << "[NinjamClient] channelId: " << channelId;
L_(ltrace) << "[NinjamClient] volume: " << volume;
if (njClient) {
njClient->SetUserChannelState(userId, channelId, false, false, true, volume,
false, 0.f, false, false, false, false);
}
}
void NinjamClient::setLocalChannelVolume(int channelId, float volume) {
L_(ltrace) << "[NinjamClient] Entering NinjamClient::setLocalChannelVolume";
L_(ltrace) << "[NinjamClient] channelId: " << channelId;
L_(ltrace) << "[NinjamClient] volume: " << volume;
if (njClient) {
if (volume > 1 || volume < 0) {
L_(lwarning) << "[NinjamClient] monitor volume is out of range";
} else {
njClient->SetLocalChannelMonitoring(channelId, true, volume, false, 0.0f,
false, false, false, false);
}
}
}
void NinjamClient::sendChatMessage(std::string message) {
L_(ltrace) << "[NinjamClient] Entering NinjamClient::sendChatMessage";
if (njClient) {
njClient->ChatMessage_Send("MSG", message.c_str());
}
}
| 34.287834
| 80
| 0.624924
|
ventosus
|
fe81b4c0d1eb50764ee4c99d35cc48075f3dfde1
| 22,320
|
cpp
|
C++
|
DatabaseUpgrade.cpp
|
addam/SkauTan
|
a46b60e91741da343a50a63948d3a19d961550d0
|
[
"Unlicense"
] | null | null | null |
DatabaseUpgrade.cpp
|
addam/SkauTan
|
a46b60e91741da343a50a63948d3a19d961550d0
|
[
"Unlicense"
] | null | null | null |
DatabaseUpgrade.cpp
|
addam/SkauTan
|
a46b60e91741da343a50a63948d3a19d961550d0
|
[
"Unlicense"
] | null | null | null |
#include "DatabaseUpgrade.h"
#include <vector>
#include <QSqlError>
#include <QSqlRecord>
#include <QDebug>
#include "Database.h"
class VersionScript
{
public:
VersionScript(std::vector<std::string> && a_Commands):
m_Commands(std::move(a_Commands))
{}
std::vector<std::string> m_Commands;
/** Applies this upgrade script to the specified DB, and updates its version to a_Version. */
void apply(QSqlDatabase & a_DB, size_t a_Version) const
{
qDebug() << "Executing DB upgrade script to version " << a_Version;
// Temporarily disable FKs:
{
auto query = a_DB.exec("pragma foreign_keys = off");
if (query.lastError().type() != QSqlError::NoError)
{
qWarning() << "SQL query failed: " << query.lastError();
throw DatabaseUpgrade::SqlError(query.lastError(), query.lastQuery().toStdString());
}
}
// Begin transaction:
{
auto query = a_DB.exec("begin");
if (query.lastError().type() != QSqlError::NoError)
{
qWarning() << "SQL query failed: " << query.lastError();
throw DatabaseUpgrade::SqlError(query.lastError(), query.lastQuery().toStdString());
}
}
// Execute the individual commands:
for (const auto & cmd: m_Commands)
{
auto query = a_DB.exec(QString::fromStdString(cmd));
if (query.lastError().type() != QSqlError::NoError)
{
qWarning() << "SQL upgrade command failed: " << query.lastError();
qDebug() << " ^-- command: " << cmd.c_str();
throw DatabaseUpgrade::SqlError(query.lastError(), cmd);
}
}
// Set the new version:
{
auto query = a_DB.exec(QString("UPDATE Version SET Version = %1").arg(a_Version));
if (query.lastError().type() != QSqlError::NoError)
{
qWarning() << "SQL transaction commit failed: " << query.lastError();
throw DatabaseUpgrade::SqlError(query.lastError(), query.lastQuery().toStdString());
}
}
// Check the FK constraints:
{
auto query = a_DB.exec("pragma check_foreign_keys");
if (query.lastError().type() != QSqlError::NoError)
{
qWarning() << "SQL transaction commit failed: " << query.lastError();
throw DatabaseUpgrade::SqlError(query.lastError(), query.lastQuery().toStdString());
}
}
// Commit the transaction:
{
auto query = a_DB.exec("commit");
if (query.lastError().type() != QSqlError::NoError)
{
qWarning() << "SQL transaction commit failed: " << query.lastError();
throw DatabaseUpgrade::SqlError(query.lastError(), query.lastQuery().toStdString());
}
}
// Re-enable FKs:
{
auto query = a_DB.exec("pragma foreign_keys = on");
if (query.lastError().type() != QSqlError::NoError)
{
qWarning() << "SQL query failed: " << query.lastError();
throw DatabaseUpgrade::SqlError(query.lastError(), query.lastQuery().toStdString());
}
}
}
};
static const std::vector<VersionScript> g_VersionScripts =
{
// Version 0 (no versioning info / empty DB) to version 1:
VersionScript({
"CREATE TABLE IF NOT EXISTS SongHashes ("
"FileName TEXT,"
"FileSize NUMBER,"
"Hash BLOB"
")",
"CREATE TABLE IF NOT EXISTS SongMetadata ("
"Hash BLOB PRIMARY KEY,"
"Length NUMERIC,"
"ManualAuthor TEXT,"
"ManualTitle TEXT,"
"ManualGenre TEXT,"
"ManualMeasuresPerMinute NUMERIC,"
"FileNameAuthor TEXT,"
"FileNameTitle TEXT,"
"FileNameGenre TEXT,"
"FileNameMeasuresPerMinute NUMERIC,"
"ID3Author TEXT,"
"ID3Title TEXT,"
"ID3Genre TEXT,"
"ID3MeasuresPerMinute NUMERIC,"
"LastPlayed DATETIME,"
"Rating NUMERIC,"
"LastMetadataUpdated DATETIME"
")",
"CREATE TABLE IF NOT EXISTS PlaybackHistory ("
"SongHash BLOB,"
"Timestamp DATETIME"
")",
"CREATE TABLE IF NOT EXISTS Templates ("
"RowID INTEGER PRIMARY KEY,"
"DisplayName TEXT,"
"Notes TEXT,"
"BgColor TEXT" // "#rrggbb"
")",
"CREATE TABLE IF NOT EXISTS TemplateItems ("
"RowID INTEGER PRIMARY KEY,"
"TemplateID INTEGER,"
"IndexInParent INTEGER," // The index of the Item within its Template
"DisplayName TEXT,"
"Notes TEXT,"
"IsFavorite INTEGER,"
"BgColor TEXT" // "#rrggbb"
")",
"CREATE TABLE IF NOT EXISTS TemplateFilters ("
"RowID INTEGER PRIMARY KEY,"
"ItemID INTEGER," // RowID of the TemplateItem that owns this filter
"TemplateID INTEGER," // RowID of the Template that owns this filter's item
"ParentID INTEGER," // RowID of this filter's parent, or -1 if root
"Kind INTEGER," // Numeric representation of the Template::Filter::Kind enum
"SongProperty INTEGER," // Numeric representation of the Template::Filter::SongProperty enum
"Comparison INTEGER," // Numeric representation of the Template::Filter::Comparison enum
"Value TEXT" // The value against which to compare
")",
"CREATE TABLE IF NOT EXISTS Version ("
"Version INTEGER"
")",
"INSERT INTO Version (Version) VALUES (1)",
}), // Version 0 to Version 1
// Version 1 to Version 2:
// Reorganize the data so that file-related data is with the filename, and song-related data is with the hash (#94)
VersionScript({
"CREATE TABLE SongFiles ("
"FileName TEXT PRIMARY KEY,"
"FileSize NUMERIC,"
"Hash BLOB,"
"ManualAuthor TEXT,"
"ManualTitle TEXT,"
"ManualGenre TEXT,"
"ManualMeasuresPerMinute NUMERIC,"
"FileNameAuthor TEXT,"
"FileNameTitle TEXT,"
"FileNameGenre TEXT,"
"FileNameMeasuresPerMinute NUMERIC,"
"ID3Author TEXT,"
"ID3Title TEXT,"
"ID3Genre TEXT,"
"ID3MeasuresPerMinute NUMERIC,"
"LastTagRescanned DATETIME DEFAULT NULL,"
"NumTagRescanAttempts NUMERIC DEFAULT 0"
")",
"INSERT INTO SongFiles ("
"FileName, FileSize, Hash,"
"ManualAuthor, ManualTitle, ManualGenre, ManualMeasuresPerMinute,"
"FileNameAuthor, FileNameTitle, FileNameGenre, FileNameMeasuresPerMinute,"
"ID3Author, ID3Title, ID3Genre, ID3MeasuresPerMinute"
") SELECT "
"SongHashes.FileName AS FileName,"
"SongHashes.FileSize AS FileSize,"
"SongHashes.Hash AS Hash,"
"SongMetadata.ManualAuthor AS ManualAuthor,"
"SongMetadata.ManualTitle AS ManualTitle,"
"SongMetadata.ManualGenre AS ManualGenre,"
"SongMetadata.ManualMeasuresPerMinute AS ManualMeasuresPerMinute,"
"SongMetadata.FileNameAuthor AS FileNameAuthor,"
"SongMetadata.FileNameTitle AS FileNameTitle,"
"SongMetadata.FileNameGenre AS FileNameGenre,"
"SongMetadata.FileNameMeasuresPerMinute AS FileNameMeasuresPerMinute,"
"SongMetadata.ID3Author AS ID3Author,"
"SongMetadata.ID3Title AS ID3Title,"
"SongMetadata.ID3Genre AS ID3Genre,"
"SongMetadata.ID3MeasuresPerMinute AS ID3MeasuresPerMinute "
"FROM SongHashes LEFT JOIN SongMetadata ON SongHashes.Hash == SongMetadata.Hash",
"CREATE TABLE SongSharedData ("
"Hash BLOB PRIMARY KEY,"
"Length NUMERIC,"
"LastPlayed DATETIME,"
"Rating NUMERIC"
")",
"INSERT INTO SongSharedData("
"Hash,"
"Length,"
"LastPlayed,"
"Rating"
") SELECT "
"Hash,"
"Length,"
"LastPlayed,"
"Rating "
"FROM SongMetadata",
"DROP TABLE SongMetadata",
"DROP TABLE SongHashes",
}), // Version 1 to Version 2
// Version 2 to Version 3:
// Add a last-modified field for each manual song prop:
VersionScript({
"ALTER TABLE SongFiles ADD COLUMN ManualAuthorLM DATETIME",
"ALTER TABLE SongFiles ADD COLUMN ManualTitleLM DATETIME",
"ALTER TABLE SongFiles ADD COLUMN ManualGenreLM DATETIME",
"ALTER TABLE SongFiles ADD COLUMN ManualMeasuresPerMinuteLM DATETIME",
}), // Version 2 to Version 3
// Version 3 to Version 4:
// Split rating into categories:
VersionScript({
"ALTER TABLE SongSharedData RENAME TO SongSharedData_Old",
"CREATE TABLE SongSharedData ("
"Hash BLOB PRIMARY KEY,"
"Length NUMERIC,"
"LastPlayed DATETIME,"
"LocalRating NUMERIC,"
"LocalRatingLM DATETIME,"
"RatingRhythmClarity NUMERIC,"
"RatingRhythmClarityLM DATETIME,"
"RatingGenreTypicality NUMERIC,"
"RatingGenreTypicalityLM DATETIME,"
"RatingPopularity NUMERIC,"
"RatingPopularityLM DATETIME"
")",
"INSERT INTO SongSharedData("
"Hash, Length, LastPlayed,"
"LocalRating, LocalRatingLM,"
"RatingRhythmClarity, RatingRhythmClarityLM,"
"RatingGenreTypicality, RatingGenreTypicalityLM,"
"RatingPopularity, RatingPopularityLM"
") SELECT "
"Hash, Length, LastPlayed,"
"Rating, NULL,"
"Rating, NULL,"
"Rating, NULL,"
"Rating, NULL"
" FROM SongSharedData_Old",
"DROP TABLE SongSharedData_Old",
}), // Version 3 to Version 4
// Version 5 to Version 5:
// Add song skip-start to shared data (#69):
VersionScript({
"ALTER TABLE SongSharedData ADD COLUMN SkipStart NUMERIC",
"ALTER TABLE SongSharedData ADD COLUMN SkipStartLM DATETIME",
}), // Version 4 to Version 5
// Version 5 to Version 6:
// Add Notes to SongFiles (#137):
VersionScript({
"ALTER TABLE SongFiles ADD COLUMN Notes TEXT",
"ALTER TABLE SongFiles ADD COLUMN NotesLM DATETIME",
}), // Version 5 to Version 6
// Version 6 to Version 7:
// Add LimitDuration to template filters:
VersionScript({
"ALTER TABLE TemplateItems ADD COLUMN DurationLimit NUMERIC",
}),
// Version 7 to Version 8:
// Split TagManual into separate tables:
VersionScript({
"CREATE TEMPORARY VIEW ManualAuthor ("
"Hash,"
"Author,"
"LastMod"
") AS SELECT "
"Hash,"
"ManualAuthor,"
"max(ManualAuthorLM) "
"FROM SongFiles "
"WHERE ManualAuthor IS NOT NULL "
"GROUP BY Hash",
"CREATE TEMPORARY VIEW ManualTitle ("
"Hash,"
"Title,"
"LastMod"
") AS SELECT "
"Hash,"
"ManualTitle,"
"max(ManualTitleLM) "
"FROM SongFiles "
"WHERE ManualTitle IS NOT NULL "
"GROUP BY Hash",
"CREATE TEMPORARY VIEW ManualGenre ("
"Hash,"
"Genre,"
"LastMod"
") AS SELECT "
"Hash,"
"ManualGenre,"
"max(ManualGenreLM) "
"FROM SongFiles "
"WHERE ManualGenre IS NOT NULL "
"GROUP BY Hash",
"CREATE TEMPORARY VIEW ManualMeasuresPerMinute ("
"Hash,"
"MeasuresPerMinute,"
"LastMod"
") AS SELECT "
"Hash,"
"ManualMeasuresPerMinute,"
"max(ManualMeasuresPerMinuteLM) "
"FROM SongFiles "
"WHERE ManualMeasuresPerMinute IS NOT NULL "
"GROUP BY Hash",
"ALTER TABLE SongSharedData RENAME TO SongSharedData_Old",
"CREATE TABLE SongSharedData ("
"Hash BLOB PRIMARY KEY,"
"Length NUMERIC,"
"LastPlayed DATETIME,"
"LocalRating NUMERIC,"
"LocalRatingLM DATETIME,"
"RatingRhythmClarity NUMERIC,"
"RatingRhythmClarityLM DATETIME,"
"RatingGenreTypicality NUMERIC,"
"RatingGenreTypicalityLM DATETIME,"
"RatingPopularity NUMERIC,"
"RatingPopularityLM DATETIME,"
"ManualAuthor TEXT,"
"ManualAuthorLM DATETIME,"
"ManualTitle TEXT,"
"ManualTitleLM DATETIME,"
"ManualGenre TEXT,"
"ManualGenreLM DATETIME,"
"ManualMeasuresPerMinute TEXT,"
"ManualMeasuresPerMinuteLM DATETIME,"
"SkipStart NUMERIC,"
"SkipStartLM DATETIME"
")",
"INSERT INTO SongSharedData("
"Hash, Length, LastPlayed,"
"LocalRating, LocalRatingLM,"
"RatingRhythmClarity, RatingRhythmClarityLM,"
"RatingGenreTypicality, RatingGenreTypicalityLM,"
"RatingPopularity, RatingPopularityLM,"
"ManualAuthor, ManualAuthorLM,"
"ManualTitle, ManualTitleLM,"
"ManualGenre, ManualGenreLM,"
"ManualMeasuresPerMinute, ManualMeasuresPerMinuteLM,"
"SkipStart, SkipStartLM"
") SELECT "
"SongSharedData_Old.Hash, SongSharedData_Old.Length, SongSharedData_Old.LastPlayed,"
"SongSharedData_Old.LocalRating, SongSharedData_Old.LocalRatingLM,"
"SongSharedData_Old.RatingRhythmClarity, SongSharedData_Old.RatingRhythmClarityLM,"
"SongSharedData_Old.RatingGenreTypicality, SongSharedData_Old.RatingGenreTypicalityLM,"
"SongSharedData_Old.RatingPopularity, SongSharedData_Old.RatingPopularityLM,"
"ManualAuthor.Author, ManualAuthor.LastMod,"
"ManualTitle.Title, ManualTitle.LastMod,"
"ManualGenre.Genre, ManualGenre.LastMod,"
"ManualMeasuresPerMinute.MeasuresPerMinute, ManualMeasuresPerMinute.LastMod,"
"SongSharedData_Old.SkipStart, SongSharedData_Old.SkipStartLM "
"FROM SongSharedData_Old "
"LEFT JOIN ManualAuthor ON ManualAuthor.Hash = SongSharedData_Old.Hash "
"LEFT JOIN ManualTitle ON ManualTitle.Hash = SongSharedData_Old.Hash "
"LEFT JOIN ManualGenre ON ManualGenre.Hash = SongSharedData_Old.Hash "
"LEFT JOIN ManualMeasuresPerMinute ON ManualMeasuresPerMinute.Hash = SongSharedData_Old.Hash",
"DROP TABLE SongSharedData_Old",
"DROP VIEW ManualAuthor",
"DROP VIEW ManualTitle",
"DROP VIEW ManualGenre",
"DROP VIEW ManualMeasuresPerMinute",
"ALTER TABLE SongFiles RENAME TO SongFiles_Old",
"CREATE TABLE SongFiles ("
"FileName TEXT PRIMARY KEY,"
"FileSize NUMERIC,"
"Hash BLOB,"
"FileNameAuthor TEXT,"
"FileNameTitle TEXT,"
"FileNameGenre TEXT,"
"FileNameMeasuresPerMinute NUMERIC,"
"ID3Author TEXT,"
"ID3Title TEXT,"
"ID3Genre TEXT,"
"ID3MeasuresPerMinute NUMERIC,"
"LastTagRescanned DATETIME DEFAULT NULL,"
"NumTagRescanAttempts NUMERIC DEFAULT 0,"
"Notes TEXT,"
"NotesLM DATETIME"
")",
"INSERT INTO SongFiles("
"FileName,"
"FileSize,"
"Hash,"
"FileNameAuthor,"
"FileNameTitle,"
"FileNameGenre,"
"FileNameMeasuresPerMinute,"
"ID3Author,"
"ID3Title,"
"ID3Genre,"
"ID3MeasuresPerMinute,"
"LastTagRescanned,"
"NumTagRescanAttempts,"
"Notes,"
"NotesLM"
") SELECT "
"FileName,"
"FileSize,"
"Hash,"
"FileNameAuthor,"
"FileNameTitle,"
"FileNameGenre,"
"FileNameMeasuresPerMinute,"
"ID3Author,"
"ID3Title,"
"ID3Genre,"
"ID3MeasuresPerMinute,"
"LastTagRescanned,"
"NumTagRescanAttempts,"
"Notes,"
"NotesLM "
"FROM SongFiles_Old",
"DROP TABLE SongFiles_Old",
}), // Version 7 to Version 8
// Version 8 to Version 9:
// Move the Notes from SongFiles to SongSharedData:
VersionScript({
"CREATE TEMPORARY VIEW SongNotes ("
"Hash,"
"Notes,"
"LastMod"
") AS SELECT "
"Hash,"
"Notes,"
"max(NotesLM)"
"FROM SongFiles WHERE Notes IS NOT NULL "
"GROUP BY Hash",
"ALTER TABLE SongSharedData RENAME TO SongSharedData_Old",
"CREATE TABLE SongSharedData ("
"Hash BLOB PRIMARY KEY,"
"Length NUMERIC,"
"LastPlayed DATETIME,"
"LocalRating NUMERIC,"
"LocalRatingLM DATETIME,"
"RatingRhythmClarity NUMERIC,"
"RatingRhythmClarityLM DATETIME,"
"RatingGenreTypicality NUMERIC,"
"RatingGenreTypicalityLM DATETIME,"
"RatingPopularity NUMERIC,"
"RatingPopularityLM DATETIME,"
"ManualAuthor TEXT,"
"ManualAuthorLM DATETIME,"
"ManualTitle TEXT,"
"ManualTitleLM DATETIME,"
"ManualGenre TEXT,"
"ManualGenreLM DATETIME,"
"ManualMeasuresPerMinute TEXT,"
"ManualMeasuresPerMinuteLM DATETIME,"
"SkipStart NUMERIC,"
"SkipStartLM DATETIME,"
"Notes TEXT,"
"NotesLM DATETIME"
")",
"INSERT INTO SongSharedData("
"Hash, Length, LastPlayed,"
"LocalRating, LocalRatingLM,"
"RatingRhythmClarity, RatingRhythmClarityLM,"
"RatingGenreTypicality, RatingGenreTypicalityLM,"
"RatingPopularity, RatingPopularityLM,"
"ManualAuthor, ManualAuthorLM,"
"ManualTitle, ManualTitleLM,"
"ManualGenre, ManualGenreLM,"
"ManualMeasuresPerMinute, ManualMeasuresPerMinuteLM,"
"SkipStart, SkipStartLM,"
"Notes, NotesLM"
") SELECT "
"SongSharedData_Old.Hash, SongSharedData_Old.Length, SongSharedData_Old.LastPlayed,"
"SongSharedData_Old.LocalRating, SongSharedData_Old.LocalRatingLM,"
"SongSharedData_Old.RatingRhythmClarity, SongSharedData_Old.RatingRhythmClarityLM,"
"SongSharedData_Old.RatingGenreTypicality, SongSharedData_Old.RatingGenreTypicalityLM,"
"SongSharedData_Old.RatingPopularity, SongSharedData_Old.RatingPopularityLM,"
"SongSharedData_Old.ManualAuthor, SongSharedData_Old.ManualAuthorLM,"
"SongSharedData_Old.ManualTitle, SongSharedData_Old.ManualTitleLM,"
"SongSharedData_Old.ManualGenre, SongSharedData_Old.ManualGenreLM,"
"SongSharedData_Old.ManualMeasuresPerMinute, SongSharedData_Old.ManualMeasuresPerMinuteLM,"
"SongSharedData_Old.SkipStart, SongSharedData_Old.SkipStartLM, "
"SongNotes.Notes, SongNotes.LastMod "
"FROM SongSharedData_Old "
"LEFT JOIN SongNotes ON SongNotes.Hash = SongSharedData_Old.Hash",
"DROP TABLE SongSharedData_Old",
"DROP VIEW SongNotes",
"ALTER TABLE SongFiles RENAME TO SongFiles_Old",
"CREATE TABLE SongFiles ("
"FileName TEXT PRIMARY KEY,"
"FileSize NUMERIC,"
"Hash BLOB,"
"FileNameAuthor TEXT,"
"FileNameTitle TEXT,"
"FileNameGenre TEXT,"
"FileNameMeasuresPerMinute NUMERIC,"
"ID3Author TEXT,"
"ID3Title TEXT,"
"ID3Genre TEXT,"
"ID3MeasuresPerMinute NUMERIC,"
"LastTagRescanned DATETIME DEFAULT NULL,"
"NumTagRescanAttempts NUMERIC DEFAULT 0"
")",
"INSERT INTO SongFiles("
"FileName,"
"FileSize,"
"Hash,"
"FileNameAuthor,"
"FileNameTitle,"
"FileNameGenre,"
"FileNameMeasuresPerMinute,"
"ID3Author,"
"ID3Title,"
"ID3Genre,"
"ID3MeasuresPerMinute,"
"LastTagRescanned,"
"NumTagRescanAttempts"
") SELECT "
"FileName,"
"FileSize,"
"Hash,"
"FileNameAuthor,"
"FileNameTitle,"
"FileNameGenre,"
"FileNameMeasuresPerMinute,"
"ID3Author,"
"ID3Title,"
"ID3Genre,"
"ID3MeasuresPerMinute,"
"LastTagRescanned,"
"NumTagRescanAttempts "
"FROM SongFiles_Old",
"DROP TABLE SongFiles_Old",
}), // Version 8 to Version 9
// Version 9 to Version 10:
// New files are put into a queue until their hash is calculated, only then added to SongFiles (#25)
// Drop Song FileSize (it's useless and not updated on file change)
VersionScript({
"CREATE TABLE NewFiles ("
"FileName TEXT PRIMARY KEY"
")",
"INSERT INTO NewFiles (FileName) "
"SELECT FileName FROM SongFiles WHERE Hash IS NULL",
"DELETE FROM SongFiles WHERE Hash IS NULL",
"ALTER TABLE SongFiles RENAME TO SongFiles_Old",
"CREATE TABLE SongFiles ("
"FileName TEXT PRIMARY KEY,"
"Hash BLOB NOT NULL REFERENCES SongSharedData(Hash),"
"FileNameAuthor TEXT,"
"FileNameTitle TEXT,"
"FileNameGenre TEXT,"
"FileNameMeasuresPerMinute NUMERIC,"
"ID3Author TEXT,"
"ID3Title TEXT,"
"ID3Genre TEXT,"
"ID3MeasuresPerMinute NUMERIC,"
"LastTagRescanned DATETIME DEFAULT NULL,"
"NumTagRescanAttempts NUMERIC DEFAULT 0"
")",
"INSERT INTO SongFiles("
"FileName,"
"Hash,"
"FileNameAuthor,"
"FileNameTitle,"
"FileNameGenre,"
"FileNameMeasuresPerMinute,"
"ID3Author,"
"ID3Title,"
"ID3Genre,"
"ID3MeasuresPerMinute,"
"LastTagRescanned,"
"NumTagRescanAttempts"
") SELECT "
"FileName,"
"Hash,"
"FileNameAuthor,"
"FileNameTitle,"
"FileNameGenre,"
"FileNameMeasuresPerMinute,"
"ID3Author,"
"ID3Title,"
"ID3Genre,"
"ID3MeasuresPerMinute,"
"LastTagRescanned,"
"NumTagRescanAttempts "
"FROM SongFiles_Old",
"DROP TABLE SongFiles_Old",
}), // Version 9 to Version 10
// Version 10 to Version 11
// Add a log of removed and deleted songs
VersionScript({
"CREATE TABLE RemovedSongs ("
"FileName TEXT,"
"Hash BLOB REFERENCES SongSharedData(Hash),"
"DateRemoved DATETIME,"
"WasFileDeleted INTEGER,"
"NumDuplicates INTEGER"
")",
}),
};
////////////////////////////////////////////////////////////////////////////////
// DatabaseUpgrade:
DatabaseUpgrade::DatabaseUpgrade(Database & a_DB):
m_DB(a_DB.database())
{
}
void DatabaseUpgrade::upgrade(Database & a_DB)
{
DatabaseUpgrade upg(a_DB);
return upg.execute();
}
void DatabaseUpgrade::execute()
{
auto version = getVersion();
qDebug() << "DB is at version " << version;
bool hasUpgraded = false;
for (auto i = version; i < g_VersionScripts.size(); ++i)
{
qWarning() << "Upgrading DB to version" << i + 1;
g_VersionScripts[i].apply(m_DB, i + 1);
hasUpgraded = true;
}
// After upgrading, vacuum the leftover space:
if (hasUpgraded)
{
auto query = m_DB.exec("VACUUM");
if (query.lastError().type() != QSqlError::NoError)
{
throw SqlError(query.lastError(), "VACUUM");
}
}
}
size_t DatabaseUpgrade::getVersion()
{
auto query = m_DB.exec("SELECT MAX(Version) AS Version FROM Version");
if (!query.first())
{
return 0;
}
return query.record().value("Version").toULongLong();
}
////////////////////////////////////////////////////////////////////////////////
// DatabaseUpgrade::SqlError:
DatabaseUpgrade::SqlError::SqlError(const QSqlError & a_SqlError, const std::string & a_SqlCommand):
Super((std::string("DatabaseUpgrade::SqlError: ") + a_SqlError.text().toStdString()).c_str()),
m_Error(a_SqlError),
m_Command(a_SqlCommand)
{
}
| 29.21466
| 116
| 0.640636
|
addam
|
fe86780268c1ff4b208053446b7199550f6d58b3
| 953
|
cpp
|
C++
|
Projects/Kalinka5_Factorial2.cpp
|
Nakama3942/SimpleProjects
|
2d927fde6b3fd4a597a3035c25a0534873aa1f47
|
[
"WTFPL"
] | 1
|
2020-11-08T22:03:56.000Z
|
2020-11-08T22:03:56.000Z
|
Projects/Kalinka5_Factorial2.cpp
|
Nakama3942/SimpleProjects
|
2d927fde6b3fd4a597a3035c25a0534873aa1f47
|
[
"WTFPL"
] | null | null | null |
Projects/Kalinka5_Factorial2.cpp
|
Nakama3942/SimpleProjects
|
2d927fde6b3fd4a597a3035c25a0534873aa1f47
|
[
"WTFPL"
] | null | null | null |
//*Пользовател вводит натуральное число n и действительное x, а программа просчитывает сумму по формуле x + x^2/2! + .. + x^n/n!
#include <iostream>
#include <math.h>
using namespace std;
int factorial(int n)
{
if (n == 1)
return 1;
else
return n * factorial(n - 1);
}
double form(int n, int x)
{
double S = x, an = x;
for (n; n != 1; n--)
{
S = S + an;
double xn = pow(x, n);
int n1 = n - 1;
int fact_n1 = factorial(n1);
int fact_n = factorial(n);
double x_n1 = pow(x, n1);
double b = (xn * fact_n1) / (fact_n * x_n1);
an = an * b;
}
S = S + an + x;
return S;
}
double poll()
{
double n, x;
cout << "N = ";
cin >> n;
cout << "X = ";
cin >> x;
cout << "\n";
return form(n, x);
}
int main()
{
double S = poll();
cout << "S = " << S << ".\n";
return 0;
}
| 20.276596
| 129
| 0.451207
|
Nakama3942
|
fe878002ee03f2a738d4991d2bd0fba3d0dcc2c5
| 1,244
|
cpp
|
C++
|
src/vhdlConvertor/archParser.cpp
|
lionheart117/hdlConvertor
|
935941471fbb592942776d2c46af2be0b14b9b06
|
[
"MIT"
] | 1
|
2021-08-02T02:23:39.000Z
|
2021-08-02T02:23:39.000Z
|
src/vhdlConvertor/archParser.cpp
|
dalance/hdlConvertor
|
34efb6ce0e38b7fa73251c179a8e34cabe1c7772
|
[
"MIT"
] | null | null | null |
src/vhdlConvertor/archParser.cpp
|
dalance/hdlConvertor
|
34efb6ce0e38b7fa73251c179a8e34cabe1c7772
|
[
"MIT"
] | null | null | null |
#include <hdlConvertor/vhdlConvertor/archParser.h>
#include <hdlConvertor/vhdlConvertor/blockDeclarationParser.h>
#include <hdlConvertor/vhdlConvertor/referenceParser.h>
#include <hdlConvertor/vhdlConvertor/statementParser.h>
#include <hdlConvertor/createObject.h>
namespace hdlConvertor {
namespace vhdl {
using vhdlParser = vhdl_antlr::vhdlParser;
using namespace hdlConvertor::hdlAst;
std::unique_ptr<HdlModuleDef> VhdlArchParser::visitArchitecture_body(
vhdlParser::Architecture_bodyContext *ctx) {
auto a = create_object<HdlModuleDef>(ctx);
// architecture_body:
// ARCHITECTURE identifier OF name IS
// ( block_declarative_item )*
// BEGIN
// ( concurrent_statement )*
// END ( ARCHITECTURE )? ( identifier )? SEMI
// ;
a->name = ctx->identifier(0)->getText();
a->module_name = VhdlReferenceParser::visitName(ctx->name());
if (!hierarchyOnly) {
for (auto bi : ctx->block_declarative_item()) {
VhdlBlockDeclarationParser bp(commentParser, hierarchyOnly);
bp.visitBlock_declarative_item(bi, a->objs);
}
}
VhdlStatementParser sp(commentParser, hierarchyOnly);
for (auto s : ctx->concurrent_statement()) {
sp.visitConcurrent_statement(s, a->objs);
}
return a;
}
}
}
| 28.272727
| 69
| 0.732315
|
lionheart117
|
fe8981cb2ff13d6a8e72ac7b3b6185dbb03d248e
| 755
|
hpp
|
C++
|
src/dispatcher.hpp
|
jlangvand/jucipp
|
0a3102f13e62d78a329d488fb1eb8812181e448e
|
[
"MIT"
] | null | null | null |
src/dispatcher.hpp
|
jlangvand/jucipp
|
0a3102f13e62d78a329d488fb1eb8812181e448e
|
[
"MIT"
] | null | null | null |
src/dispatcher.hpp
|
jlangvand/jucipp
|
0a3102f13e62d78a329d488fb1eb8812181e448e
|
[
"MIT"
] | null | null | null |
#pragma once
#include "mutex.hpp"
#include <functional>
#include <gtkmm.h>
#include <list>
class Dispatcher {
private:
Mutex functions_mutex;
std::list<std::function<void()>> functions GUARDED_BY(functions_mutex);
Glib::Dispatcher dispatcher;
sigc::connection connection;
void connect();
public:
/// Must be called from main GUI thread
Dispatcher();
~Dispatcher();
/// Queue function to main GUI thread.
/// Can be called from any thread.
template <typename T>
void post(T &&function) {
LockGuard lock(functions_mutex);
functions.emplace_back(std::forward<T>(function));
dispatcher();
}
/// Must be called from main GUI thread
void disconnect();
/// Must be called from main GUI thread
void reset();
};
| 20.972222
| 73
| 0.692715
|
jlangvand
|
fe8c0c80e9a34226c3dc53614fe2db92c7b2dda5
| 26,192
|
hpp
|
C++
|
shared/utils/il2cpp-functions.hpp
|
Metalit/beatsaber-hook
|
d9eed309cee7c3aca3da6c983f8787d2395c1713
|
[
"MIT"
] | null | null | null |
shared/utils/il2cpp-functions.hpp
|
Metalit/beatsaber-hook
|
d9eed309cee7c3aca3da6c983f8787d2395c1713
|
[
"MIT"
] | null | null | null |
shared/utils/il2cpp-functions.hpp
|
Metalit/beatsaber-hook
|
d9eed309cee7c3aca3da6c983f8787d2395c1713
|
[
"MIT"
] | null | null | null |
#ifndef IL2CPP_FUNCTIONS_H
#define IL2CPP_FUNCTIONS_H
#pragma pack(push)
#include <cstddef>
#include <stdio.h>
#include <stdlib.h>
#include "logging.hpp"
#include "utils.h"
#if !defined(UNITY_2019) && __has_include("il2cpp-runtime-stats.h")
#define UNITY_2019
#endif
#if defined(__GLIBCXX__) || defined(__GLIBCPP__)
// We are currently compiling with GNU GCC libstdc++, so we are already using its STL implementation
typedef std::string gnu_string;
#else
#ifndef UNITY_2019
struct _Rep {
size_t _M_length;
size_t _M_capacity;
int _M_refcount;
};
struct gnu_string {
const char* _M_p;
// TODO: why are these needed to prevent a crash on _Type_GetName_ call? They don't contain string data!
const char padding[9];
const char* _M_data() const {
return _M_p;
}
const _Rep* _M_rep() const {
return &((reinterpret_cast<const _Rep *>(_M_data()))[-1]);
}
const char* c_str() const {
return _M_p;
}
int length() const {
return _M_rep()->_M_length;
}
};
#endif // UNITY_2019
#endif
struct Il2CppAssembly;
struct Il2CppObject;
struct Il2CppClass;
struct Il2CppImage;
struct Il2CppArray;
struct Il2CppType;
struct MethodInfo;
struct FieldInfo;
struct PropertyInfo;
struct EventInfo;
struct Il2CppDomain;
struct Il2CppReflectionType;
struct Il2CppException;
struct Il2CppProfiler;
struct Il2CppThread;
struct Il2CppReflectionMethod;
struct Il2CppManagedMemorySnapshot;
struct Il2CppStackFrameInfo;
struct Il2CppCustomAttrInfo;
struct Il2CppGenericClass;
struct Il2CppDefaults;
struct Il2CppTypeDefinition;
struct Il2CppGenericParameter;
struct Il2CppGenericContainer;
#include "il2cpp-api-types.h"
#include "il2cpp-metadata.h"
#include "il2cpp-class-internals.h"
#include "utils.h"
typedef std::vector<const Il2CppAssembly*> AssemblyVector;
#ifndef IL2CPP_FUNC_VISIBILITY
#define IL2CPP_FUNC_VISIBILITY private
#endif
#define API_FUNC(rt, name, ...) \
IL2CPP_FUNC_VISIBILITY: \
static rt (*il2cpp_##name)__VA_ARGS__; \
public: \
template<class... TArgs> \
static rt name(TArgs&&... args) { \
if (!il2cpp_##name) { \
SAFE_ABORT(); \
} \
if constexpr (std::is_same_v<rt, void>) { \
il2cpp_##name(args...); \
} else { \
return il2cpp_##name(args...); \
} \
}
#define API_FUNC_VISIBLE(rt, name, ...) \
public: \
static rt (*il2cpp_##name)__VA_ARGS__; \
template<class... TArgs> \
static rt name(TArgs&&... args) { \
if (!il2cpp_##name) { \
SAFE_ABORT(); \
} \
if constexpr (std::is_same_v<rt, void>) { \
il2cpp_##name(args...); \
} else { \
return il2cpp_##name(args...); \
} \
}
// A class which contains all available il2cpp functions
// Created by zoller27osu
class il2cpp_functions {
public:
// These methods autogenerated by Sc2ad:
#ifdef UNITY_2019
API_FUNC(int, init, (const char* domain_name));
API_FUNC(int, init_utf16, (const Il2CppChar * domain_name));
#else
API_FUNC(void, init, (const char* domain_name));
API_FUNC(void, init_utf16, (const Il2CppChar * domain_name));
#endif
API_FUNC(void, shutdown, ());
API_FUNC(void, set_config_dir, (const char *config_path));
API_FUNC(void, set_data_dir, (const char *data_path));
API_FUNC(void, set_temp_dir, (const char *temp_path));
API_FUNC(void, set_commandline_arguments, (int argc, const char* const argv[], const char* basedir));
API_FUNC(void, set_commandline_arguments_utf16, (int argc, const Il2CppChar * const argv[], const char* basedir));
API_FUNC(void, set_config_utf16, (const Il2CppChar * executablePath));
API_FUNC(void, set_config, (const char* executablePath));
API_FUNC(void, set_memory_callbacks, (Il2CppMemoryCallbacks * callbacks));
API_FUNC(const Il2CppImage*, get_corlib, ());
API_FUNC(void, add_internal_call, (const char* name, Il2CppMethodPointer method));
API_FUNC(Il2CppMethodPointer, resolve_icall, (const char* name));
API_FUNC(void*, alloc, (size_t size));
API_FUNC(void, free, (void* ptr));
API_FUNC(Il2CppClass*, array_class_get, (Il2CppClass * element_class, uint32_t rank));
API_FUNC(uint32_t, array_length, (Il2CppArray * array));
API_FUNC(uint32_t, array_get_byte_length, (Il2CppArray * array));
API_FUNC(Il2CppArray*, array_new, (Il2CppClass * elementTypeInfo, il2cpp_array_size_t length));
API_FUNC(Il2CppArray*, array_new_specific, (Il2CppClass * arrayTypeInfo, il2cpp_array_size_t length));
API_FUNC(Il2CppArray*, array_new_full, (Il2CppClass * array_class, il2cpp_array_size_t * lengths, il2cpp_array_size_t * lower_bounds));
API_FUNC(Il2CppClass*, bounded_array_class_get, (Il2CppClass * element_class, uint32_t rank, bool bounded));
API_FUNC(int, array_element_size, (const Il2CppClass * array_class));
API_FUNC(const Il2CppImage*, assembly_get_image, (const Il2CppAssembly * assembly));
#ifdef UNITY_2019
API_FUNC(void, class_for_each, (void(*klassReportFunc)(Il2CppClass* klass, void* userData), void* userData));
#endif
API_FUNC(const Il2CppType*, class_enum_basetype, (Il2CppClass * klass));
API_FUNC(bool, class_is_generic, (const Il2CppClass * klass));
API_FUNC(bool, class_is_inflated, (const Il2CppClass * klass));
API_FUNC(bool, class_is_assignable_from, (Il2CppClass * klass, Il2CppClass * oklass));
API_FUNC(bool, class_is_subclass_of, (Il2CppClass * klass, Il2CppClass * klassc, bool check_interfaces));
API_FUNC(bool, class_has_parent, (Il2CppClass * klass, Il2CppClass * klassc));
API_FUNC(Il2CppClass*, class_from_il2cpp_type, (const Il2CppType * type));
API_FUNC(Il2CppClass*, class_from_name, (const Il2CppImage * image, const char* namespaze, const char *name));
API_FUNC(Il2CppClass*, class_from_system_type, (Il2CppReflectionType * type));
API_FUNC(Il2CppClass*, class_get_element_class, (Il2CppClass * klass));
API_FUNC(const EventInfo*, class_get_events, (Il2CppClass * klass, void* *iter));
API_FUNC(FieldInfo*, class_get_fields, (Il2CppClass * klass, void* *iter));
API_FUNC(Il2CppClass*, class_get_nested_types, (Il2CppClass * klass, void* *iter));
API_FUNC(Il2CppClass*, class_get_interfaces, (Il2CppClass * klass, void* *iter));
API_FUNC(const PropertyInfo*, class_get_properties, (Il2CppClass * klass, void* *iter));
API_FUNC(const PropertyInfo*, class_get_property_from_name, (Il2CppClass * klass, const char *name));
API_FUNC(FieldInfo*, class_get_field_from_name, (Il2CppClass * klass, const char *name));
API_FUNC(const MethodInfo*, class_get_methods, (Il2CppClass * klass, void* *iter));
API_FUNC(const MethodInfo*, class_get_method_from_name, (const Il2CppClass * klass, const char* name, int argsCount));
API_FUNC(const char*, class_get_name, (const Il2CppClass * klass));
#ifdef UNITY_2019
API_FUNC(void, type_get_name_chunked, (const Il2CppType * type, void(*chunkReportFunc)(void* data, void* userData), void* userData));
#endif
API_FUNC(const char*, class_get_namespace, (const Il2CppClass * klass));
API_FUNC(Il2CppClass*, class_get_parent, (Il2CppClass * klass));
API_FUNC(Il2CppClass*, class_get_declaring_type, (const Il2CppClass * klass));
API_FUNC(int32_t, class_instance_size, (Il2CppClass * klass));
API_FUNC(size_t, class_num_fields, (const Il2CppClass * enumKlass));
API_FUNC(bool, class_is_valuetype, (const Il2CppClass * klass));
API_FUNC(int32_t, class_value_size, (Il2CppClass * klass, uint32_t * align));
API_FUNC(bool, class_is_blittable, (const Il2CppClass * klass));
API_FUNC(int, class_get_flags, (const Il2CppClass * klass));
API_FUNC(bool, class_is_abstract, (const Il2CppClass * klass));
API_FUNC(bool, class_is_interface, (const Il2CppClass * klass));
API_FUNC(int, class_array_element_size, (const Il2CppClass * klass));
API_FUNC(Il2CppClass*, class_from_type, (const Il2CppType * type));
API_FUNC(const Il2CppType*, class_get_type, (Il2CppClass * klass));
API_FUNC(uint32_t, class_get_type_token, (Il2CppClass * klass));
API_FUNC(bool, class_has_attribute, (Il2CppClass * klass, Il2CppClass * attr_class));
API_FUNC(bool, class_has_references, (Il2CppClass * klass));
API_FUNC(bool, class_is_enum, (const Il2CppClass * klass));
API_FUNC(const Il2CppImage*, class_get_image, (Il2CppClass * klass));
API_FUNC(const char*, class_get_assemblyname, (const Il2CppClass * klass));
API_FUNC(int, class_get_rank, (const Il2CppClass * klass));
#ifdef UNITY_2019
API_FUNC(uint32_t, class_get_data_size, (const Il2CppClass * klass));
API_FUNC(void*, class_get_static_field_data, (const Il2CppClass * klass));
#endif
API_FUNC(size_t, class_get_bitmap_size, (const Il2CppClass * klass));
API_FUNC(void, class_get_bitmap, (Il2CppClass * klass, size_t * bitmap));
API_FUNC(bool, stats_dump_to_file, (const char *path));
API_FUNC(uint64_t, stats_get_value, (Il2CppStat stat));
API_FUNC(Il2CppDomain*, domain_get, ());
API_FUNC(const Il2CppAssembly*, domain_assembly_open, (Il2CppDomain * domain, const char* name));
API_FUNC(const Il2CppAssembly**, domain_get_assemblies, (const Il2CppDomain * domain, size_t * size));
#ifdef UNITY_2019
API_FUNC(void, raise_exception, (Il2CppException*));
#endif
API_FUNC(Il2CppException*, exception_from_name_msg, (const Il2CppImage * image, const char *name_space, const char *name, const char *msg));
API_FUNC(Il2CppException*, get_exception_argument_null, (const char *arg));
API_FUNC(void, format_exception, (const Il2CppException * ex, char* message, int message_size));
API_FUNC(void, format_stack_trace, (const Il2CppException * ex, char* output, int output_size));
API_FUNC(void, unhandled_exception, (Il2CppException*));
API_FUNC(int, field_get_flags, (FieldInfo * field));
API_FUNC(const char*, field_get_name, (FieldInfo * field));
API_FUNC(Il2CppClass*, field_get_parent, (FieldInfo * field));
API_FUNC(size_t, field_get_offset, (FieldInfo * field));
API_FUNC(const Il2CppType*, field_get_type, (FieldInfo * field));
API_FUNC(void, field_get_value, (Il2CppObject * obj, FieldInfo * field, void *value));
API_FUNC(Il2CppObject*, field_get_value_object, (FieldInfo * field, Il2CppObject * obj));
API_FUNC(bool, field_has_attribute, (FieldInfo * field, Il2CppClass * attr_class));
API_FUNC(void, field_set_value, (Il2CppObject * obj, FieldInfo * field, void *value));
API_FUNC(void, field_static_get_value, (FieldInfo * field, void *value));
API_FUNC(void, field_static_set_value, (FieldInfo * field, void *value));
API_FUNC(void, field_set_value_object, (Il2CppObject * instance, FieldInfo * field, Il2CppObject * value));
#ifdef UNITY_2019
API_FUNC(bool, field_is_literal, (FieldInfo * field));
#endif
API_FUNC(void, gc_collect, (int maxGenerations));
API_FUNC(int32_t, gc_collect_a_little, ());
API_FUNC(void, gc_disable, ());
API_FUNC(void, gc_enable, ());
API_FUNC(bool, gc_is_disabled, ());
#ifdef UNITY_2019
API_FUNC(int64_t, gc_get_max_time_slice_ns, ());
API_FUNC(void, gc_set_max_time_slice_ns, (int64_t maxTimeSlice));
API_FUNC(bool, gc_is_incremental, ());
#endif
API_FUNC(int64_t, gc_get_used_size, ());
API_FUNC(int64_t, gc_get_heap_size, ());
API_FUNC(void, gc_wbarrier_set_field, (Il2CppObject * obj, void **targetAddress, void *object));
#ifdef UNITY_2019
API_FUNC(bool, gc_has_strict_wbarriers, ());
API_FUNC(void, gc_set_external_allocation_tracker, (void(*func)(void*, size_t, int)));
API_FUNC(void, gc_set_external_wbarrier_tracker, (void(*func)(void**)));
API_FUNC(void, gc_foreach_heap, (void(*func)(void* data, void* userData), void* userData));
API_FUNC(void, stop_gc_world, ());
API_FUNC(void, start_gc_world, ());
#endif
API_FUNC(uint32_t, gchandle_new, (Il2CppObject * obj, bool pinned));
API_FUNC(uint32_t, gchandle_new_weakref, (Il2CppObject * obj, bool track_resurrection));
API_FUNC(Il2CppObject*, gchandle_get_target, (uint32_t gchandle));
API_FUNC(void, gchandle_free, (uint32_t gchandle));
#ifdef UNITY_2019
API_FUNC(void, gchandle_foreach_get_target, (void(*func)(void* data, void* userData), void* userData));
API_FUNC(uint32_t, object_header_size, ());
API_FUNC(uint32_t, array_object_header_size, ());
API_FUNC(uint32_t, offset_of_array_length_in_array_object_header, ());
API_FUNC(uint32_t, offset_of_array_bounds_in_array_object_header, ());
API_FUNC(uint32_t, allocation_granularity, ());
#endif
API_FUNC(void*, unity_liveness_calculation_begin, (Il2CppClass * filter, int max_object_count, il2cpp_register_object_callback callback, void* userdata, il2cpp_WorldChangedCallback onWorldStarted, il2cpp_WorldChangedCallback onWorldStopped));
API_FUNC(void, unity_liveness_calculation_end, (void* state));
API_FUNC(void, unity_liveness_calculation_from_root, (Il2CppObject * root, void* state));
API_FUNC(void, unity_liveness_calculation_from_statics, (void* state));
API_FUNC(const Il2CppType*, method_get_return_type, (const MethodInfo * method));
API_FUNC(Il2CppClass*, method_get_declaring_type, (const MethodInfo * method));
API_FUNC(const char*, method_get_name, (const MethodInfo * method));
API_FUNC(const MethodInfo*, method_get_from_reflection, (const Il2CppReflectionMethod * method));
API_FUNC(Il2CppReflectionMethod*, method_get_object, (const MethodInfo * method, Il2CppClass * refclass));
API_FUNC(bool, method_is_generic, (const MethodInfo * method));
API_FUNC(bool, method_is_inflated, (const MethodInfo * method));
API_FUNC(bool, method_is_instance, (const MethodInfo * method));
API_FUNC(uint32_t, method_get_param_count, (const MethodInfo * method));
API_FUNC(const Il2CppType*, method_get_param, (const MethodInfo * method, uint32_t index));
API_FUNC(Il2CppClass*, method_get_class, (const MethodInfo * method));
API_FUNC(bool, method_has_attribute, (const MethodInfo * method, Il2CppClass * attr_class));
API_FUNC(uint32_t, method_get_flags, (const MethodInfo * method, uint32_t * iflags));
API_FUNC(uint32_t, method_get_token, (const MethodInfo * method));
API_FUNC(const char*, method_get_param_name, (const MethodInfo * method, uint32_t index));
// ONLY IF THE PROFILER EXISTS FOR UNITY_2019
API_FUNC(void, profiler_install, (Il2CppProfiler * prof, Il2CppProfileFunc shutdown_callback));
API_FUNC(void, profiler_set_events, (Il2CppProfileFlags events));
API_FUNC(void, profiler_install_enter_leave, (Il2CppProfileMethodFunc enter, Il2CppProfileMethodFunc fleave));
API_FUNC(void, profiler_install_allocation, (Il2CppProfileAllocFunc callback));
API_FUNC(void, profiler_install_gc, (Il2CppProfileGCFunc callback, Il2CppProfileGCResizeFunc heap_resize_callback));
API_FUNC(void, profiler_install_fileio, (Il2CppProfileFileIOFunc callback));
API_FUNC(void, profiler_install_thread, (Il2CppProfileThreadFunc start, Il2CppProfileThreadFunc end));
API_FUNC(uint32_t, property_get_flags, (const PropertyInfo * prop));
API_FUNC(const MethodInfo*, property_get_get_method, (const PropertyInfo * prop));
API_FUNC(const MethodInfo*, property_get_set_method, (const PropertyInfo * prop));
API_FUNC(const char*, property_get_name, (const PropertyInfo * prop));
API_FUNC(Il2CppClass*, property_get_parent, (const PropertyInfo * prop));
API_FUNC(Il2CppClass*, object_get_class, (Il2CppObject * obj));
API_FUNC(uint32_t, object_get_size, (Il2CppObject * obj));
API_FUNC(const MethodInfo*, object_get_virtual_method, (Il2CppObject * obj, const MethodInfo * method));
API_FUNC(Il2CppObject*, object_new, (const Il2CppClass * klass));
// Always returns (void*, (obj + 1)
API_FUNC(void*, object_unbox, (Il2CppObject * obj));
// If klass is not a ValueType, returns (Il2CppObject*, (*data), else boxes
API_FUNC(Il2CppObject*, value_box, (Il2CppClass * klass, void* data));
API_FUNC(void, monitor_enter, (Il2CppObject * obj));
API_FUNC(bool, monitor_try_enter, (Il2CppObject * obj, uint32_t timeout));
API_FUNC(void, monitor_exit, (Il2CppObject * obj));
API_FUNC(void, monitor_pulse, (Il2CppObject * obj));
API_FUNC(void, monitor_pulse_all, (Il2CppObject * obj));
API_FUNC(void, monitor_wait, (Il2CppObject * obj));
API_FUNC(bool, monitor_try_wait, (Il2CppObject * obj, uint32_t timeout));
API_FUNC(Il2CppObject*, runtime_invoke, (const MethodInfo * method, void *obj, void **params, Il2CppException **exc));
API_FUNC(Il2CppObject*, runtime_invoke_convert_args, (const MethodInfo * method, void *obj, Il2CppObject **params, int paramCount, Il2CppException **exc));
API_FUNC(void, runtime_class_init, (Il2CppClass * klass));
API_FUNC(void, runtime_object_init, (Il2CppObject * obj));
API_FUNC(void, runtime_object_init_exception, (Il2CppObject * obj, Il2CppException** exc));
API_FUNC(void, runtime_unhandled_exception_policy_set, (Il2CppRuntimeUnhandledExceptionPolicy value));
API_FUNC(int32_t, string_length, (Il2CppString * str));
API_FUNC(Il2CppChar*, string_chars, (Il2CppString * str));
API_FUNC(Il2CppString*, string_new, (const char* str));
API_FUNC(Il2CppString*, string_new_len, (const char* str, uint32_t length));
API_FUNC(Il2CppString*, string_new_utf16, (const Il2CppChar * text, int32_t len));
API_FUNC(Il2CppString*, string_new_wrapper, (const char* str));
API_FUNC(Il2CppString*, string_intern, (Il2CppString * str));
API_FUNC(Il2CppString*, string_is_interned, (Il2CppString * str));
API_FUNC(Il2CppThread*, thread_current, ());
API_FUNC(Il2CppThread*, thread_attach, (Il2CppDomain * domain));
API_FUNC(void, thread_detach, (Il2CppThread * thread));
API_FUNC(Il2CppThread**, thread_get_all_attached_threads, (size_t * size));
API_FUNC(bool, is_vm_thread, (Il2CppThread * thread));
API_FUNC(void, current_thread_walk_frame_stack, (Il2CppFrameWalkFunc func, void* user_data));
API_FUNC(void, thread_walk_frame_stack, (Il2CppThread * thread, Il2CppFrameWalkFunc func, void* user_data));
API_FUNC(bool, current_thread_get_top_frame, (Il2CppStackFrameInfo * frame));
API_FUNC(bool, thread_get_top_frame, (Il2CppThread * thread, Il2CppStackFrameInfo * frame));
API_FUNC(bool, current_thread_get_frame_at, (int32_t offset, Il2CppStackFrameInfo * frame));
API_FUNC(bool, thread_get_frame_at, (Il2CppThread * thread, int32_t offset, Il2CppStackFrameInfo * frame));
API_FUNC(int32_t, current_thread_get_stack_depth, ());
API_FUNC(int32_t, thread_get_stack_depth, (Il2CppThread * thread));
#ifdef UNITY_2019
API_FUNC(void, override_stack_backtrace, (Il2CppBacktraceFunc stackBacktraceFunc));
#endif
API_FUNC(Il2CppObject*, type_get_object, (const Il2CppType * type));
API_FUNC(int, type_get_type, (const Il2CppType * type));
API_FUNC(Il2CppClass*, type_get_class_or_element_class, (const Il2CppType * type));
API_FUNC(char*, type_get_name, (const Il2CppType * type));
API_FUNC(bool, type_is_byref, (const Il2CppType * type));
API_FUNC(uint32_t, type_get_attrs, (const Il2CppType * type));
API_FUNC(bool, type_equals, (const Il2CppType * type, const Il2CppType * otherType));
API_FUNC(char*, type_get_assembly_qualified_name, (const Il2CppType * type));
#ifdef UNITY_2019
API_FUNC(bool, type_is_static, (const Il2CppType * type));
API_FUNC(bool, type_is_pointer_type, (const Il2CppType * type));
#endif
API_FUNC(const Il2CppAssembly*, image_get_assembly, (const Il2CppImage * image));
API_FUNC(const char*, image_get_name, (const Il2CppImage * image));
API_FUNC(const char*, image_get_filename, (const Il2CppImage * image));
API_FUNC(const MethodInfo*, image_get_entry_point, (const Il2CppImage * image));
API_FUNC(size_t, image_get_class_count, (const Il2CppImage * image));
API_FUNC(const Il2CppClass*, image_get_class, (const Il2CppImage * image, size_t index));
API_FUNC(Il2CppManagedMemorySnapshot*, capture_memory_snapshot, ());
API_FUNC(void, free_captured_memory_snapshot, (Il2CppManagedMemorySnapshot * snapshot));
API_FUNC(void, set_find_plugin_callback, (Il2CppSetFindPlugInCallback method));
API_FUNC(void, register_log_callback, (Il2CppLogCallback method));
API_FUNC(void, debugger_set_agent_options, (const char* options));
API_FUNC(bool, is_debugger_attached, ());
#ifdef UNITY_2019
API_FUNC(void, register_debugger_agent_transport, (Il2CppDebuggerTransport * debuggerTransport));
API_FUNC(bool, debug_get_method_info, (const MethodInfo*, Il2CppMethodDebugInfo * methodDebugInfo));
#endif
API_FUNC(void, unity_install_unitytls_interface, (const void* unitytlsInterfaceStruct));
API_FUNC(Il2CppCustomAttrInfo*, custom_attrs_from_class, (Il2CppClass * klass));
API_FUNC(Il2CppCustomAttrInfo*, custom_attrs_from_method, (const MethodInfo * method));
API_FUNC(Il2CppObject*, custom_attrs_get_attr, (Il2CppCustomAttrInfo * ainfo, Il2CppClass * attr_klass));
API_FUNC(bool, custom_attrs_has_attr, (Il2CppCustomAttrInfo * ainfo, Il2CppClass * attr_klass));
API_FUNC(Il2CppArray*, custom_attrs_construct, (Il2CppCustomAttrInfo * cinfo));
API_FUNC(void, custom_attrs_free, (Il2CppCustomAttrInfo * ainfo));
#ifdef UNITY_2019
API_FUNC(void, class_set_userdata, (Il2CppClass * klass, void* userdata));
API_FUNC(int, class_get_userdata_offset, ());
#endif
// MANUALLY DEFINED CONST DEFINITIONS
API_FUNC(const Il2CppType*, class_get_type_const, (const Il2CppClass * klass));
API_FUNC(const char*, class_get_name_const, (const Il2CppClass * klass));
// SELECT NON-API LIBIL2CPP FUNCTIONS:
API_FUNC_VISIBLE(bool, Class_Init, (Il2CppClass* klass));
API_FUNC_VISIBLE(Il2CppClass*, MetadataCache_GetTypeInfoFromTypeDefinitionIndex, (TypeDefinitionIndex index));
API_FUNC_VISIBLE(Il2CppClass*, MetadataCache_GetTypeInfoFromTypeIndex, (TypeIndex index));
#ifdef UNITY_2019
API_FUNC_VISIBLE(std::string, _Type_GetName_, (const Il2CppType *type, Il2CppTypeNameFormat format));
#else
API_FUNC_VISIBLE(gnu_string, _Type_GetName_, (const Il2CppType *type, Il2CppTypeNameFormat format));
#endif
API_FUNC_VISIBLE(void, GC_free, (void* addr));
API_FUNC_VISIBLE(void, GarbageCollector_SetWriteBarrier, (void** ptr));
API_FUNC_VISIBLE(void*, GarbageCollector_AllocateFixed, (size_t sz, void* descr));
API_FUNC_VISIBLE(Il2CppClass*, Class_FromIl2CppType, (Il2CppType* typ));
API_FUNC_VISIBLE(Il2CppClass*, Class_GetPtrClass, (Il2CppClass* elementClass));
API_FUNC_VISIBLE(Il2CppClass*, GenericClass_GetClass, (Il2CppGenericClass* gclass));
API_FUNC_VISIBLE(AssemblyVector*, Assembly_GetAllAssemblies, ());
private:
static bool find_GC_free(const uint32_t* Runtime_Shutdown);
static bool find_GC_SetWriteBarrier(const uint32_t* set_wbarrier_field);
static bool trace_GC_AllocFixed(const uint32_t* DomainGetCurrent);
static bool find_GC_AllocFixed(const uint32_t* DomainGetCurrent);
static const Il2CppMetadataRegistration** s_Il2CppMetadataRegistrationPtr;
static const void** s_GlobalMetadataPtr;
static const Il2CppGlobalMetadataHeader** s_GlobalMetadataHeaderPtr;
public:
static bool hasGCFuncs;
// You must il2cpp_functions::free the char* when you are done with it
static char* Type_GetName(const Il2CppType *type, Il2CppTypeNameFormat format);
static std::remove_pointer_t<decltype(s_GlobalMetadataPtr)> s_GlobalMetadata;
static std::remove_pointer_t<decltype(s_GlobalMetadataHeaderPtr)> s_GlobalMetadataHeader;
static std::remove_pointer_t<decltype(s_Il2CppMetadataRegistrationPtr)> s_Il2CppMetadataRegistration;
static const Il2CppDefaults* defaults;
// must be done on-demand because the pointers aren't necessarily correct at the time of il2cpp_functions::Init
static void CheckS_GlobalMetadata() {
if (!s_GlobalMetadataHeader) {
static auto& logger = getFuncLogger();
s_GlobalMetadata = *CRASH_UNLESS(il2cpp_functions::s_GlobalMetadataPtr);
s_GlobalMetadataHeader = *CRASH_UNLESS(il2cpp_functions::s_GlobalMetadataHeaderPtr);
s_Il2CppMetadataRegistration = *CRASH_UNLESS(il2cpp_functions::s_Il2CppMetadataRegistrationPtr);
logger.debug("sanity: %X (should be 0xFAB11BAF)", s_GlobalMetadataHeader->sanity);
logger.debug("version: %i", s_GlobalMetadataHeader->version);
CRASH_UNLESS((uint32_t)s_GlobalMetadataHeader->sanity == 0xFAB11BAF);
logger.debug("typeDefinitionsOffset: %i", s_GlobalMetadataHeader->typeDefinitionsOffset);
logger.debug("exportedTypeDefinitionsOffset: %i", s_GlobalMetadataHeader->exportedTypeDefinitionsOffset);
logger.debug("nestedTypesOffset: %i", s_GlobalMetadataHeader->nestedTypesOffset);
// TODO: use il2cpp_functions::defaults to define the il2cpp_defaults variable mentioned in il2cpp-class-internals.h
}
}
// COPIES OF FREQUENTLY INLINED NON-API LIBIL2CPP FUNCTIONS:
static const char* MetadataCache_GetStringFromIndex(StringIndex index);
static const Il2CppTypeDefinition* MetadataCache_GetTypeDefinitionFromIndex(TypeDefinitionIndex index);
static TypeDefinitionIndex MetadataCache_GetExportedTypeFromIndex(TypeDefinitionIndex index);
static const Il2CppGenericContainer* MetadataCache_GetGenericContainerFromIndex(GenericContainerIndex index);
static const Il2CppGenericParameter* MetadataCache_GetGenericParameterFromIndex(GenericParameterIndex index);
static Il2CppClass* MetadataCache_GetNestedTypeFromIndex(NestedTypeIndex index);
static TypeDefinitionIndex MetadataCache_GetIndexForTypeDefinition(const Il2CppClass* typeDefinition);
// Whether all of the il2cpp functions have been initialized or not
static bool initialized;
// Initializes all of the IL2CPP functions via dlopen and dlsym for use.
static void Init();
static LoggerContextObject& getFuncLogger();
};
#undef API_FUNC
#pragma pack(pop)
#endif /* IL2CPP_FUNCTIONS_H */
| 55.491525
| 246
| 0.748511
|
Metalit
|
fe8e1d7761a863d7868d2afa0acf21e713da7564
| 8,543
|
hpp
|
C++
|
include/lbann/utils/cudnn.hpp
|
andy-yoo/lbann-andy
|
237c45c392e7a5548796ac29537ab0a374e7e825
|
[
"Apache-2.0"
] | null | null | null |
include/lbann/utils/cudnn.hpp
|
andy-yoo/lbann-andy
|
237c45c392e7a5548796ac29537ab0a374e7e825
|
[
"Apache-2.0"
] | null | null | null |
include/lbann/utils/cudnn.hpp
|
andy-yoo/lbann-andy
|
237c45c392e7a5548796ac29537ab0a374e7e825
|
[
"Apache-2.0"
] | null | null | null |
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2014-2016, Lawrence Livermore National Security, LLC.
// Produced at the Lawrence Livermore National Laboratory.
// Written by the LBANN Research Team (B. Van Essen, et al.) listed in
// the CONTRIBUTORS file. <lbann-dev@llnl.gov>
//
// LLNL-CODE-697807.
// All rights reserved.
//
// This file is part of LBANN: Livermore Big Artificial Neural Network
// Toolkit. For details, see http://software.llnl.gov/LBANN or
// https://github.com/LLNL/LBANN.
//
// Licensed under the Apache License, Version 2.0 (the "Licensee"); 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 LBANN_UTILS_CUDNN_HPP
#define LBANN_UTILS_CUDNN_HPP
#include "lbann/base.hpp"
#include "lbann/utils/cuda.hpp"
#include "lbann/utils/exception.hpp"
#include "lbann/layers/layer.hpp"
#include <vector>
#ifdef LBANN_HAS_CUDNN
#include <cudnn.h>
// Error utility macros
#define CHECK_CUDNN_NODEBUG(cudnn_call) \
do { \
const cudnnStatus_t status_CHECK_CUDNN = (cudnn_call); \
if (status_CHECK_CUDNN != CUDNN_STATUS_SUCCESS) { \
cudaDeviceReset(); \
LBANN_ERROR(std::string("cuDNN error (") \
+ cudnnGetErrorString(status_CHECK_CUDNN) \
+ std::string(")")); \
} \
} while (0)
#define CHECK_CUDNN_DEBUG(cudnn_call) \
do { \
LBANN_CUDA_CHECK_LAST_ERROR(true); \
CHECK_CUDNN_NODEBUG(cudnn_call); \
} while (0)
#ifdef LBANN_DEBUG
#define CHECK_CUDNN(cudnn_call) CHECK_CUDNN_DEBUG(cudnn_call)
#else
#define CHECK_CUDNN(cudnn_call) CHECK_CUDNN_NODEBUG(cudnn_call)
#endif // #ifdef LBANN_DEBUG
#define CHECK_CUDNN_DTOR(cudnn_call) \
try { \
CHECK_CUDNN(cudnn_call); \
} \
catch (std::exception const& e) { \
std::cerr << "Caught exception:\n\n what(): " \
<< e.what() << "\n\nCalling std::terminate() now." \
<< std::endl; \
std::terminate(); \
} \
catch (...) { \
std::cerr << "Caught something that isn't an std::exception.\n\n" \
<< "Calling std::terminate() now." << std::endl; \
std::terminate(); \
}
namespace lbann {
// Forward declaration
class Layer;
namespace cudnn {
////////////////////////////////////////////////////////////
// Global cuDNN objects
////////////////////////////////////////////////////////////
/** Initialize global cuDNN objects. */
void initialize();
/** Destroy global cuDNN objects. */
void destroy();
/** Get cuDNN handle.
* This resets the active CUDA device and stream to the Hydrogen
* defaults. The cuDNN handle is initialized if needed.
*/
cudnnHandle_t& get_handle();
////////////////////////////////////////////////////////////
// Helper functions for cuDNN types
////////////////////////////////////////////////////////////
/** Get cuDNN data type associated with DataType. */
cudnnDataType_t get_data_type();
/** Set cuDNN tensor descriptor.
* desc is created if necessary.
*/
void set_tensor_desc(cudnnTensorDescriptor_t& desc,
std::vector<int> dims,
std::vector<int> strides = {});
/** Copy cuDNN tensor descriptor.
* dst is created or destroyed if needed.
*/
void copy_tensor_desc(const cudnnTensorDescriptor_t& src,
cudnnTensorDescriptor_t& dst);
/** Copy cuDNN activation descriptor.
* dst is created or destroyed if needed.
*/
void copy_activation_desc(const cudnnActivationDescriptor_t& src,
cudnnActivationDescriptor_t& dst);
////////////////////////////////////////////////////////////
// cuDNN tensor managers
////////////////////////////////////////////////////////////
/** Manager for a layer's cuDNN tensor descriptors. */
class layer_tensor_manager {
public:
layer_tensor_manager(const Layer* l = nullptr);
layer_tensor_manager(const layer_tensor_manager& other);
layer_tensor_manager& operator=(const layer_tensor_manager& other);
virtual ~layer_tensor_manager();
/** Get the layer being managed. */
const Layer* get_layer() const { return m_layer; }
/** Set the layer being managed. */
void set_layer(const Layer* l);
/** Get cuDNN tensor descriptor for layer input. */
virtual cudnnTensorDescriptor_t& get_prev_activations(int parent_index = 0) = 0;
/** Get cuDNN tensor descriptor for layer output. */
virtual cudnnTensorDescriptor_t& get_activations(int child_index = 0) = 0;
/** Get cuDNN tensor descriptor for gradient w.r.t. layer output. */
virtual cudnnTensorDescriptor_t& get_prev_error_signals(int child_index = 0) = 0;
/** Get cuDNN tensor descriptor for gradient w.r.t. layer input. */
virtual cudnnTensorDescriptor_t& get_error_signals(int parent_index = 0) = 0;
protected:
/** Set number of tensor descriptors corresponding to layer inputs. */
void set_num_parents(int num_parents);
/** Set number of tensor descriptors corresponding to layer outputs. */
void set_num_children(int num_children);
/** Layer being managed. */
const Layer* m_layer;
/** cuDNN tensor descriptors for layer inputs. */
std::vector<cudnnTensorDescriptor_t> m_prev_activations;
/** cuDNN tensor descriptors for layer outputs. */
std::vector<cudnnTensorDescriptor_t> m_activations;
/** cuDNN tensor descriptors for gradients w.r.t. layer outputs. */
std::vector<cudnnTensorDescriptor_t> m_prev_error_signals;
/** cuDNN tensor descriptors for gradients w.r.t. layer inputs. */
std::vector<cudnnTensorDescriptor_t> m_error_signals;
};
/** Manager for a data-parallel layer's cuDNN tensor descriptors. */
class data_parallel_layer_tensor_manager : public layer_tensor_manager {
public:
data_parallel_layer_tensor_manager(const Layer* l = nullptr);
data_parallel_layer_tensor_manager(
const data_parallel_layer_tensor_manager& other) = default;
data_parallel_layer_tensor_manager&
operator=(const data_parallel_layer_tensor_manager& other) = default;
~data_parallel_layer_tensor_manager() = default;
cudnnTensorDescriptor_t& get_prev_activations(int parent_index = 0) override;
cudnnTensorDescriptor_t& get_activations(int child_index = 0) override;
cudnnTensorDescriptor_t& get_prev_error_signals(int child_index = 0) override;
cudnnTensorDescriptor_t& get_error_signals(int parent_index = 0) override;
};
/** Manager for an entry-wise layer's cuDNN tensor descriptors. */
class entrywise_layer_tensor_manager : public layer_tensor_manager {
public:
entrywise_layer_tensor_manager(const Layer* l = nullptr);
entrywise_layer_tensor_manager(
const entrywise_layer_tensor_manager& other) = default;
entrywise_layer_tensor_manager&
operator=(const entrywise_layer_tensor_manager& other) = default;
~entrywise_layer_tensor_manager() = default;
cudnnTensorDescriptor_t& get_prev_activations(int parent_index = 0) override;
cudnnTensorDescriptor_t& get_activations(int child_index = 0) override;
cudnnTensorDescriptor_t& get_prev_error_signals(int child_index = 0) override;
cudnnTensorDescriptor_t& get_error_signals(int parent_index = 0) override;
};
} // namespace cudnn
} // namespace lbann
#endif // LBANN_HAS_CUDNN
#endif // LBANN_UTILS_CUDNN_HPP
| 41.270531
| 83
| 0.610675
|
andy-yoo
|
fe8e341043d412fbf85d071ec983141d6afb4d5f
| 2,938
|
cc
|
C++
|
cyber/scheduler/scheduler_policy_test.cc
|
ghdawn/apollo
|
002eba4a1635d6af7f1ebd2118464bca6f86b106
|
[
"Apache-2.0"
] | null | null | null |
cyber/scheduler/scheduler_policy_test.cc
|
ghdawn/apollo
|
002eba4a1635d6af7f1ebd2118464bca6f86b106
|
[
"Apache-2.0"
] | null | null | null |
cyber/scheduler/scheduler_policy_test.cc
|
ghdawn/apollo
|
002eba4a1635d6af7f1ebd2118464bca6f86b106
|
[
"Apache-2.0"
] | null | null | null |
/******************************************************************************
* Copyright 2018 The Apollo Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
#include <gtest/gtest.h>
#include "cyber/base/for_each.h"
#include "cyber/common/global_data.h"
#include "cyber/cyber.h"
#include "cyber/scheduler/policy/choreography_context.h"
#include "cyber/scheduler/policy/classic_context.h"
#include "cyber/scheduler/policy/scheduler_choreography.h"
#include "cyber/scheduler/policy/scheduler_classic.h"
#include "cyber/scheduler/processor.h"
#include "cyber/scheduler/scheduler_factory.h"
#include "cyber/task/task.h"
namespace apollo {
namespace cyber {
namespace scheduler {
void func() {}
TEST(SchedulerPolicyTest, choreo) {
auto processor = std::make_shared<Processor>();
auto ctx = std::make_shared<ChoreographyContext>();
processor->BindContext(ctx);
std::shared_ptr<CRoutine> cr = std::make_shared<CRoutine>(func);
auto task_id = GlobalData::RegisterTaskName("choreo");
cr->set_id(task_id);
EXPECT_TRUE(static_cast<ChoreographyContext*>(ctx.get())->Enqueue(cr));
ctx->Shutdown();
}
TEST(SchedulerPolicyTest, classic) {
auto processor = std::make_shared<Processor>();
auto ctx = std::make_shared<ClassicContext>();
processor->BindContext(ctx);
std::vector<std::future<void>> res;
// test single routine
auto future = Async([]() {
FOR_EACH(i, 0, 20) { cyber::SleepFor(std::chrono::milliseconds(i)); }
AINFO << "Finish task: single";
});
future.get();
// test multiple routine
FOR_EACH(i, 0, 20) {
res.emplace_back(Async([i]() {
FOR_EACH(time, 0, 30) { cyber::SleepFor(std::chrono::milliseconds(i)); }
}));
AINFO << "Finish task: " << i;
};
for (auto& future : res) {
future.wait_for(std::chrono::milliseconds(1000));
}
res.clear();
ctx->Shutdown();
}
TEST(SchedulerPolicyTest, sched_classic) {
auto sched = dynamic_cast<SchedulerClassic*>(scheduler::Instance());
std::shared_ptr<CRoutine> cr = std::make_shared<CRoutine>(func);
auto task_id = GlobalData::RegisterTaskName("ABC");
cr->set_id(task_id);
EXPECT_TRUE(sched->DispatchTask(cr));
// dispatch the same task
EXPECT_FALSE(sched->DispatchTask(cr));
EXPECT_TRUE(sched->RemoveTask("ABC"));
}
} // namespace scheduler
} // namespace cyber
} // namespace apollo
| 32.644444
| 79
| 0.67631
|
ghdawn
|
fe9210adf4e62aec6f352ae853e618bf0948d838
| 3,224
|
hpp
|
C++
|
INCLUDE/Vcl/qclipbrd.hpp
|
earthsiege2/borland-cpp-ide
|
09bcecc811841444338e81b9c9930c0e686f9530
|
[
"Unlicense",
"FSFAP",
"Apache-1.1"
] | 1
|
2022-01-13T01:03:55.000Z
|
2022-01-13T01:03:55.000Z
|
INCLUDE/Vcl/qclipbrd.hpp
|
earthsiege2/borland-cpp-ide
|
09bcecc811841444338e81b9c9930c0e686f9530
|
[
"Unlicense",
"FSFAP",
"Apache-1.1"
] | null | null | null |
INCLUDE/Vcl/qclipbrd.hpp
|
earthsiege2/borland-cpp-ide
|
09bcecc811841444338e81b9c9930c0e686f9530
|
[
"Unlicense",
"FSFAP",
"Apache-1.1"
] | null | null | null |
// Borland C++ Builder
// Copyright (c) 1995, 2002 by Borland Software Corporation
// All rights reserved
// (DO NOT EDIT: machine generated header) 'QClipbrd.pas' rev: 6.00
#ifndef QClipbrdHPP
#define QClipbrdHPP
#pragma delphiheader begin
#pragma option push -w-
#pragma option push -Vx
#include <QGraphics.hpp> // Pascal unit
#include <QConsts.hpp> // Pascal unit
#include <QTypes.hpp> // Pascal unit
#include <Qt.hpp> // Pascal unit
#include <Classes.hpp> // Pascal unit
#include <SysUtils.hpp> // Pascal unit
#include <SysInit.hpp> // Pascal unit
#include <System.hpp> // Pascal unit
//-- user supplied -----------------------------------------------------------
namespace Qclipbrd
{
//-- type declarations -------------------------------------------------------
class DELPHICLASS TClipboard;
class PASCALIMPLEMENTATION TClipboard : public Classes::TPersistent
{
typedef Classes::TPersistent inherited;
private:
AnsiString FCachedProvidesFormat;
WideString FCachedText;
Qt::QClipboardH* FHandle;
Qt::QClipboard_hookH* FHook;
bool FCachedProvidesResponse;
bool FCachedTextValid;
void __fastcall ClearCache(void);
void __cdecl ClipboardChangedNotification(void);
void __fastcall AssignGraphic(Qgraphics::TGraphic* Source);
void __fastcall AssignPicture(Qgraphics::TPicture* Source);
void __fastcall AssignMimeSource(Qtypes::TMimeSource* Source);
void __fastcall AssignToBitmap(Qgraphics::TBitmap* Dest);
void __fastcall AssignToPicture(Qgraphics::TPicture* Dest);
WideString __fastcall GetAsText();
void __fastcall SetAsText(const WideString Value);
Qt::QClipboardH* __fastcall GetHandle(void);
protected:
virtual void __fastcall AssignTo(Classes::TPersistent* Dest);
public:
__fastcall virtual ~TClipboard(void);
bool __fastcall AddFormat(const AnsiString Format, Classes::TStream* Stream);
virtual void __fastcall Assign(Classes::TPersistent* Source);
void __fastcall Clear(void);
Classes::TComponent* __fastcall GetComponent(Classes::TComponent* Owner, Classes::TComponent* Parent);
bool __fastcall GetFormat(const AnsiString Format, Classes::TStream* Stream);
void __fastcall SetFormat(const AnsiString Format, Classes::TStream* Stream);
bool __fastcall Provides(const AnsiString Format);
int __fastcall RegisterClipboardFormat(const AnsiString Format);
void __fastcall SetComponent(Classes::TComponent* Component);
void __fastcall SupportedFormats(Classes::TStrings* List);
__property WideString AsText = {read=GetAsText, write=SetAsText};
__property Qt::QClipboardH* Handle = {read=GetHandle};
public:
#pragma option push -w-inl
/* TObject.Create */ inline __fastcall TClipboard(void) : Classes::TPersistent() { }
#pragma option pop
};
//-- var, const, procedure ---------------------------------------------------
extern PACKAGE TClipboard* __fastcall Clipboard(void);
extern PACKAGE TClipboard* __fastcall SetClipboard(TClipboard* NewClipboard);
} /* namespace Qclipbrd */
using namespace Qclipbrd;
#pragma option pop // -w-
#pragma option pop // -Vx
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // QClipbrd
| 37.057471
| 104
| 0.701303
|
earthsiege2
|
fe92ffca13c5d8825ec617b976adfe37f72c82f3
| 15,997
|
hxx
|
C++
|
src/dcc/Loco.hxx
|
TrainzLuvr/openmrn
|
b3bb9d4995e49aa39856740d292d38cf4a99845b
|
[
"BSD-2-Clause"
] | null | null | null |
src/dcc/Loco.hxx
|
TrainzLuvr/openmrn
|
b3bb9d4995e49aa39856740d292d38cf4a99845b
|
[
"BSD-2-Clause"
] | null | null | null |
src/dcc/Loco.hxx
|
TrainzLuvr/openmrn
|
b3bb9d4995e49aa39856740d292d38cf4a99845b
|
[
"BSD-2-Clause"
] | null | null | null |
/** \copyright
* Copyright (c) 2014, Balazs Racz
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* \file Loco.hxx
*
* Defines a simple DCC locomotive.
*
* @author Balazs Racz
* @date 10 May 2014
*/
#ifndef _DCC_LOCO_HXX_
#define _DCC_LOCO_HXX_
#include "dcc/Packet.hxx"
#include "dcc/PacketSource.hxx"
#include "dcc/UpdateLoop.hxx"
#include "dcc/Defs.hxx"
#include "utils/logging.h"
namespace dcc
{
/// Describes what sort of packet the dcc:PacketSource (usually a single train)
/// should generate. This is used for two purposes:
///
/// - When a user action results in a high priority band packet to be enerated,
/// we can enqueue a message containing this code to the refreshloop
/// object. Then when the refresh loop gets to the given packet, the train
/// will be called with the appropriate code to generate the desired packet
/// from its internal state (the freshest version of that).
///
/// - When a train is on the background refresh loop, it can keep an internal
/// variable describing what packet to generate next as a refresh packet.
enum DccTrainUpdateCode
{
REFRESH = 0,
SPEED = 1,
FUNCTION0 = 2,
FUNCTION5 = 3,
FUNCTION9 = 4,
FUNCTION13 = 5,
FUNCTION21 = 6,
MM_F1 = 2,
MM_F2,
MM_F3,
MM_F4,
MIN_REFRESH = SPEED,
/** @TODO(balazs.racz) choose adaptive max-refresh based on how many
* functions are actually in use for the loco. */
MAX_REFRESH = FUNCTION9,
MM_MAX_REFRESH = 7,
ESTOP = 16,
};
/// AbstractTrain is a templated class for train implementations in a command
/// station. It gives implementations for most functions that the OpenLCB
/// command station neeeds, while using a compact structure for representing
/// the state the command station needs to know about the train itself.
///
/// The only shared assumption about the train is that it has to participate in
/// the standard command station packet loop. The exact protocol, number of
/// speed steps, number of functions etc. are all defined by the template
/// argument. The goal is to minimize the number of bytes needed to store
/// information about one train in the RAM so that command stations with
/// limited memory can still serve a large number of trains in their update
/// loop.
///
/// Example implementations of the template payload are @ref Dcc28Payload, @ref
/// Dcc128Payload, @ref MMOldPayload, @ref MMNewPayload.
template <class P> class AbstractTrain : public PacketSource
{
public:
AbstractTrain()
{
}
/// Sets the train speed (asking for a high-priority outgoing update packet
/// to be generated). @param speed is the desired speed that came from the
/// throttle.
void set_speed(SpeedType speed) OVERRIDE
{
float16_t new_speed = speed.get_wire();
if (p.lastSetSpeed_ == new_speed)
{
LOG(VERBOSE, "not updating speed: old speed %04x, new speed %04x",
p.lastSetSpeed_, new_speed);
return;
}
p.lastSetSpeed_ = new_speed;
if (speed.direction() != p.direction_)
{
p.directionChanged_ = 1;
p.direction_ = speed.direction();
}
float f_speed = speed.mph();
if (f_speed > 0)
{
f_speed *= ((p.get_speed_steps() * 1.0) / 126);
unsigned sp = f_speed;
sp++; // makes sure it is at least speed step 1.
if (sp > p.get_speed_steps())
sp = p.get_speed_steps();
LOG(VERBOSE, "set speed to step %u", sp);
p.speed_ = sp;
}
else
{
p.speed_ = 0;
}
packet_processor_notify_update(this, SPEED);
}
/// @return the last set speed.
SpeedType get_speed() OVERRIDE
{
SpeedType v;
v.set_wire(p.lastSetSpeed_);
return v;
}
/// @return the commanded speed (which as of now is interpreted as the last
/// set speed).
SpeedType get_commanded_speed() OVERRIDE
{
return get_speed();
}
/// Sets the train to ESTOP state, generating an emergency stop packet.
void set_emergencystop() OVERRIDE
{
p.speed_ = 0;
SpeedType dir0;
dir0.set_direction(p.direction_);
p.lastSetSpeed_ = dir0.get_wire();
p.directionChanged_ = 1;
packet_processor_notify_update(this, ESTOP);
}
/// Sets a function to a given value. @param address is the function number
/// (0..28), @param value is 0 for funciton OFF, 1 for function ON.
void set_fn(uint32_t address, uint16_t value) OVERRIDE
{
if (address > p.get_max_fn())
{
// Ignore.
return;
}
unsigned bit = 1 << address;
if (value)
{
p.fn_ |= bit;
}
else
{
p.fn_ &= ~bit;
}
packet_processor_notify_update(this, p.get_fn_update_code(address));
}
/// @return the last set value of a given function, or 0 if the function is
/// not known. @param address is the function address.
uint16_t get_fn(uint32_t address) OVERRIDE
{
if (address > p.get_max_fn())
{
// Unknown.
return 0;
}
return (p.fn_ & (1 << address)) ? 1 : 0;
}
/// @return the legacy address of this loco.
uint32_t legacy_address() OVERRIDE
{
return p.address_;
}
/// @return the legacy address type.
TrainAddressType legacy_address_type() OVERRIDE
{
return p.get_address_type();
}
protected:
/// Payload -- actual data we know about the train.
P p;
};
/// Structure defining the volatile state for a 28-speed-step DCC locomotive.
struct Dcc28Payload
{
Dcc28Payload()
{
memset(this, 0, sizeof(*this));
}
/// Track address. largest address allowed is 10239.
unsigned address_ : 14;
/// 1 if this is a short address train.
unsigned isShortAddress_ : 1;
/// 0: forward, 1: reverse
unsigned direction_ : 1;
/// fp16 value of the last set speed.
unsigned lastSetSpeed_ : 16;
/// functions f0-f28.
unsigned fn_ : 29;
/// Which refresh packet should go out next.
unsigned nextRefresh_ : 3;
/// Speed step we last set.
unsigned speed_ : 5;
/// Whether the direction change packet still needs to go out.
unsigned directionChanged_ : 1;
/** @return the number of speed steps (in float). */
static unsigned get_speed_steps()
{
return 28;
}
/** @returns the largest function number that is still valid. */
static unsigned get_max_fn()
{
return 28;
}
/** @return the update code to send ot the packet handler for a given
* function value change. @param address is the function number(0..28). */
static unsigned get_fn_update_code(unsigned address);
/** Adds the speed payload to a DCC packet. @param p is the packet to add
* the speed payload to. */
void add_dcc_speed_to_packet(dcc::Packet *p)
{
p->add_dcc_speed28(!direction_, speed_);
}
/** Adds the speed payload to a DCC packet with value == EMERGENCY_STOP
* @param p is the packet to add the speed payload to. */
void add_dcc_estop_to_packet(dcc::Packet *p)
{
p->add_dcc_speed28(!direction_, Packet::EMERGENCY_STOP);
}
/// @return what type of address this train has.
TrainAddressType get_address_type()
{
return isShortAddress_ ? TrainAddressType::DCC_SHORT_ADDRESS : TrainAddressType::DCC_LONG_ADDRESS;
}
};
/// TrainImpl class for a DCC locomotive.
template <class Payload> class DccTrain : public AbstractTrain<Payload>
{
public:
/// Constructor. @param a is the address.
DccTrain(DccShortAddress a)
{
this->p.isShortAddress_ = 1;
this->p.address_ = a.value;
packet_processor_add_refresh_source(this);
}
/// Constructor. @param a is the address.
DccTrain(DccLongAddress a)
{
this->p.isShortAddress_ = 0;
this->p.address_ = a.value;
packet_processor_add_refresh_source(this);
}
~DccTrain();
/// Generates next outgoing packet. @param code is the packet code (as
/// requested by the previous cycle or the on-update notification). @param
/// packet needs to be filled in for the output.
void get_next_packet(unsigned code, Packet *packet) OVERRIDE;
};
/// TrainImpl class for a 28-speed-step DCC locomotive.
typedef DccTrain<Dcc28Payload> Dcc28Train;
/// Structure defining the volatile state for a 128-speed-step DCC locomotive.
struct Dcc128Payload
{
Dcc128Payload()
{
memset(this, 0, sizeof(*this));
}
/// Track address. largest address allowed is 10239.
unsigned address_ : 14;
/// 1 if this is a short address train.
unsigned isShortAddress_ : 1;
/// 0: forward, 1: reverse
unsigned direction_ : 1;
/// fp16 value of the last set speed.
unsigned lastSetSpeed_ : 16;
/// functions f0-f28.
unsigned fn_ : 29;
/// Which refresh packet should go out next.
unsigned nextRefresh_ : 3;
/// Speed step we last set.
unsigned speed_ : 7;
/// Whether the direction change packet still needs to go out.
unsigned directionChanged_ : 1;
/** @return the number of speed steps (the largest valid speed step). */
static unsigned get_speed_steps()
{
return 126;
}
/** @return the largest function number that is still valid. */
static unsigned get_max_fn()
{
return 28;
}
/** @return the update code to send ot the packet handler for a given
* function value change. */
static unsigned get_fn_update_code(unsigned address)
{
return Dcc28Payload::get_fn_update_code(address);
}
/** Adds the speed payload to a DCC packet. @param p is the packet to add
* the speed payload to. */
void add_dcc_speed_to_packet(dcc::Packet *p)
{
p->add_dcc_speed128(!direction_, speed_);
}
/** Adds the speed payload to a DCC packet with value == EMERGENCY_STOP
* @param p is the packet to add the speed payload to. */
void add_dcc_estop_to_packet(dcc::Packet *p)
{
p->add_dcc_speed128(!direction_, Packet::EMERGENCY_STOP);
}
/// @return what type of address this train has.
TrainAddressType get_address_type()
{
return isShortAddress_ ? TrainAddressType::DCC_SHORT_ADDRESS : TrainAddressType::DCC_LONG_ADDRESS;
}
};
/// TrainImpl class for a 128-speed-step DCC locomotive.
typedef DccTrain<Dcc128Payload> Dcc128Train;
/// Structure defining the volatile state for a Marklin-Motorola v1 protocol
/// locomotive (with 14 speed steps, one function and relative direction only).
struct MMOldPayload
{
MMOldPayload()
{
memset(this, 0, sizeof(*this));
}
/// largest address allowed is 80, but we keep a few more bits around to
/// allow for an extension to arbitrary MM address packets.
unsigned address_ : 8;
/// fp16 value of the last set speed.
unsigned lastSetSpeed_ : 16;
/// function f0.
unsigned fn_ : 1;
/// 0: forward, 1: reverse
unsigned direction_ : 1;
/// Whether the direction change packet still needs to go out.
unsigned directionChanged_ : 1;
/// Speed step we last set.
unsigned speed_ : 4;
/** @return the number of speed steps (in float). */
unsigned get_speed_steps()
{
return 14;
}
/** @return the largest function number that is still valid. */
unsigned get_max_fn()
{
return 0;
}
/** @return the update code to send to the packet handler for a given
* function value change. @param address is ignored */
unsigned get_fn_update_code(unsigned address)
{
return SPEED;
}
/// @return what type of address this train has.
static TrainAddressType get_address_type()
{
return TrainAddressType::MM;
}
};
/// TrainImpl structure for Marklin-Motorola v1 protocol locomotives.
class MMOldTrain : public AbstractTrain<MMOldPayload>
{
public:
/// Constructor. @param a is the MM address.
MMOldTrain(MMAddress a);
~MMOldTrain();
/// Generates next outgoing packet. @param code is the packet code (as
/// requested by the previous cycle or the on-update notification). @param
/// packet needs to be filled in for the output.
void get_next_packet(unsigned code, Packet *packet) OVERRIDE;
};
/// Structure defining the volatile state for a Marklin-Motorola v2 protocol
/// locomotive (with 28 speed steps, five functions and absolute direction).
struct MMNewPayload
{
MMNewPayload()
{
memset(this, 0, sizeof(*this));
}
/// largest address allowed is 80, but we keep a few more bits around to
/// allow for an extension to arbitrary MM address packets.
unsigned address_ : 8;
/// fp16 value of the last set speed.
unsigned lastSetSpeed_ : 16;
/// function f0-f4.
unsigned fn_ : 5;
/// 0: forward, 1: reverse
unsigned direction_ : 1;
/// Whether the direction change packet still needs to go out.
unsigned directionChanged_ : 1;
/// reserved
unsigned resvd1_ : 1;
/// Speed step we last set.
unsigned speed_ : 4;
/// internal refresh cycle state machine
unsigned nextRefresh_ : 3;
/** @return the number of speed steps (in float). */
unsigned get_speed_steps()
{
return 14;
}
/** @return the largest function number that is still valid. */
unsigned get_max_fn()
{
return 4;
}
/** @return the update code to send to the packet handler for a given
* function value change. @param address is the function number (0..4) */
unsigned get_fn_update_code(unsigned address)
{
if (1 <= address && address <= 4)
{
return MM_F1 + address - 1;
}
else
{
return SPEED;
}
}
/// @return what type of address this train has.
static TrainAddressType get_address_type()
{
return TrainAddressType::MM;
}
};
/// TrainImpl structure for Marklin-Motorola v2 protocol locomotives.
class MMNewTrain : public AbstractTrain<MMNewPayload>
{
public:
/// Constructor. @param a is the MM address.
MMNewTrain(MMAddress a);
~MMNewTrain();
/// Generates next outgoing packet. @param code is the packet code (as
/// requested by the previous cycle or the on-update notification). @param
/// packet needs to be filled in for the output.
void get_next_packet(unsigned code, Packet *packet) OVERRIDE;
};
} // namespace dcc
#endif // _DCC_LOCO_HXX_
| 31.740079
| 106
| 0.653185
|
TrainzLuvr
|
fe96f577c4a8cc52efd1178c2edb70564ea6d497
| 6,969
|
cpp
|
C++
|
Graphics/ParticleEmitter.cpp
|
craigjlovell/aieBootstrap-master
|
2b0b850ed4be9103b15e38631fee496c93e1f5a5
|
[
"MIT"
] | null | null | null |
Graphics/ParticleEmitter.cpp
|
craigjlovell/aieBootstrap-master
|
2b0b850ed4be9103b15e38631fee496c93e1f5a5
|
[
"MIT"
] | null | null | null |
Graphics/ParticleEmitter.cpp
|
craigjlovell/aieBootstrap-master
|
2b0b850ed4be9103b15e38631fee496c93e1f5a5
|
[
"MIT"
] | null | null | null |
#include "ParticleEmitter.h"
#include <glm/ext.hpp>
#include <gl_core_4_4.h>
ParticleEmitter::ParticleEmitter() : m_particles(nullptr), m_firstDead(0), m_maxParticles(0), m_position(0,0,0), m_vao(0), m_vbo(0), m_ibo(0), m_vertexData(nullptr)
{
}
ParticleEmitter::~ParticleEmitter()
{
delete[] m_particles;
delete[] m_vertexData;
glDeleteVertexArrays(1, &m_vao);
glDeleteBuffers(1, &m_vbo);
glDeleteBuffers(1, &m_ibo);
}
void ParticleEmitter::Initialise(unsigned int a_maxParticles, unsigned int a_emitRate, float a_lifetimeMin, float a_lifetimeMax, float a_velocityMin, float a_velocityMax, float a_startSize, float a_endSize, const glm::vec4& a_startColor, const glm::vec4& a_endColor)
{
// First we want to set up the emitters
m_emitTimer = 0;
m_emitRate = 1.f / a_emitRate;
// Then store all the arguments as our variables
m_startColor = a_startColor;
m_endColor = a_endColor;
m_startSize = a_startSize;
m_endSize = a_endSize;
m_velocityMin = a_velocityMin;
m_velocityMax = a_velocityMax;
m_lifespanMin = a_lifetimeMin;
m_lifespanMax = a_lifetimeMax;
m_maxParticles = a_maxParticles;
// Next create the array of particles
m_particles = new Particle[m_maxParticles];
m_firstDead = 0;
// Next we need to create an array of vertices for the particles
// There needs to be four (4) verticies per poarticle to make a quad
// This data will be generated as we update the emitter
m_vertexData = new ParticleVertex[m_maxParticles * 4];
unsigned int* indexData = new unsigned int[m_maxParticles * 6];
for (unsigned int i = 0; i < m_maxParticles; i++)
{
indexData[i * 6 + 0] = i * 4 + 0;
indexData[i * 6 + 1] = i * 4 + 1;
indexData[i * 6 + 2] = i * 4 + 2;
indexData[i * 6 + 3] = i * 4 + 0;
indexData[i * 6 + 4] = i * 4 + 2;
indexData[i * 6 + 5] = i * 4 + 3;
}
// Finally, create the openGL buffers
glGenVertexArrays(1, &m_vao);
glBindVertexArray(m_vao);
glGenBuffers(1, &m_vbo);
glGenBuffers(1, &m_ibo);
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
glBufferData(GL_ARRAY_BUFFER, m_maxParticles * 4 * sizeof(ParticleVertex), m_vertexData, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, m_maxParticles * 6 * sizeof(unsigned int), indexData, GL_STATIC_DRAW);
glEnableVertexAttribArray(0); // This os the position
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, sizeof(ParticleVertex), 0);
glEnableVertexAttribArray(1); // This is the color of the particle
glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, sizeof(ParticleVertex), ((char*)0) + 16);
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
delete[] indexData;
}
void ParticleEmitter::Emit()
{
// Check to see if there is an avaible particle for the system to emit
if (m_firstDead >= m_maxParticles)
return;
// Otherwise, return the first dead particle
Particle& particle = m_particles[m_firstDead++];
// Reset the position of the returned particle
particle.position = m_position;
// Reset the lifespan of the returned particle we will be randomizing this by default
particle.lifetime = 0;
particle.lifespan = (rand() / (float)RAND_MAX) * (m_lifespanMax - m_lifespanMin) + m_lifespanMin;
// Reset the starting color of the particle
particle.color = m_startColor;
// Reset the starting scale of the particle
particle.size = m_startSize;
// Reset the starting velocity of the particle. this will be randomised on each axis and the force provided.
float velocity = (rand() / (float)RAND_MAX) * (m_velocityMax - m_velocityMin) + m_velocityMin;
particle.velocity.x = (rand() / (float)RAND_MAX) * 2 - 1;
particle.velocity.y = (rand() / (float)RAND_MAX) * 2 - 1;
particle.velocity.z = (rand() / (float)RAND_MAX) * 2 - 1;
particle.velocity = glm::normalize(particle.velocity) * velocity;
}
void ParticleEmitter::Update(float a_deltaTime, const glm::mat4& a_cameraTransform)
{
// This will move and update all the alive particles
// Then remove the dying particles
// It will then emit the particles based on thge emitters provided rate.
// Finally we will update the vertex array and construct the billboarding
m_emitTimer += a_deltaTime;
// Spawn particles
while (m_emitTimer > m_emitRate)
{
Emit();
m_emitTimer -= m_emitRate;
}
unsigned int quad = 0;
// Now we need to update all of the particles to make sure they work as billboards quads
for (unsigned int i = 0; i < m_firstDead; i++)
{
Particle* particle = &m_particles[i];
particle->lifetime += a_deltaTime;
if (particle->lifetime >= particle->lifespan)
{ // If true, replace the last alive particle with this one
*particle = m_particles[m_firstDead - 1];
m_firstDead--;
}
else
{
// While false, allow the particle to change.
// First we move the particle
particle->position += particle->velocity * a_deltaTime;
// Next scale the particle
particle->size = glm::mix(m_startSize, m_endSize, particle->lifetime / particle->lifespan);
// Then we can color the particle
particle->color = glm::mix(m_startColor, m_endColor, particle->lifetime / particle->lifespan);
// Finally we will set up our quad using the correct psoition, color and scale
float halfSize = particle->size * 0.5f;
m_vertexData[quad * 4 + 0].position = glm::vec4( halfSize, halfSize, 0, 1);
m_vertexData[quad * 4 + 0].color = particle->color;
m_vertexData[quad * 4 + 1].position = glm::vec4(-halfSize, halfSize, 0, 1);
m_vertexData[quad * 4 + 1].color = particle->color;
m_vertexData[quad * 4 + 2].position = glm::vec4(-halfSize, -halfSize, 0, 1);
m_vertexData[quad * 4 + 2].color = particle->color;
m_vertexData[quad * 4 + 3].position = glm::vec4( halfSize, -halfSize, 0, 1);
m_vertexData[quad * 4 + 3].color = particle->color;
// Set up our billboard's transform
glm::vec3 zAxis = glm::normalize(glm::vec3(a_cameraTransform[3]) - particle->position);
glm::vec3 xAxis = glm::cross(glm::vec3(a_cameraTransform[1]), zAxis);
glm::vec3 yAxis = glm::cross(zAxis, xAxis);
glm::mat4 billboard(glm::vec4(xAxis, 0), glm::vec4(yAxis, 0),
glm::vec4(zAxis, 0), glm::vec4(0, 0, 0, 1));
m_vertexData[quad * 4 + 0].position = billboard *
m_vertexData[quad * 4].position + glm::vec4(particle->position, 0);
m_vertexData[quad * 4 + 1].position = billboard *
m_vertexData[quad * 4 + 1].position + glm::vec4(particle->position, 0);
m_vertexData[quad * 4 + 2].position = billboard *
m_vertexData[quad * 4 + 2].position + glm::vec4(particle->position, 0);
m_vertexData[quad * 4 + 3].position = billboard *
m_vertexData[quad * 4 + 3].position + glm::vec4(particle->position, 0);
++quad;
}
}
}
void ParticleEmitter::Draw()
{
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
glBufferSubData(GL_ARRAY_BUFFER, 0, m_firstDead * 4 * sizeof(ParticleVertex), m_vertexData);
glBindVertexArray(m_vao);
glDrawElements(GL_TRIANGLES, m_firstDead * 6, GL_UNSIGNED_INT, 0);
}
| 33.666667
| 266
| 0.710719
|
craigjlovell
|
fe9ace811ea5bdcbd7e065c7ef9e5804b48710f8
| 656
|
cpp
|
C++
|
N0440-K-th-Smallest-in-Lexicographical-Order/solution1.cpp
|
loyio/leetcode
|
366393c29a434a621592ef6674a45795a3086184
|
[
"CC0-1.0"
] | null | null | null |
N0440-K-th-Smallest-in-Lexicographical-Order/solution1.cpp
|
loyio/leetcode
|
366393c29a434a621592ef6674a45795a3086184
|
[
"CC0-1.0"
] | null | null | null |
N0440-K-th-Smallest-in-Lexicographical-Order/solution1.cpp
|
loyio/leetcode
|
366393c29a434a621592ef6674a45795a3086184
|
[
"CC0-1.0"
] | 2
|
2022-01-25T05:31:31.000Z
|
2022-02-26T07:22:23.000Z
|
class Solution {
public:
int findKthNumber(int n, int k) {
int curr = 1;
k--;
while(k > 0){
int steps = getStep(curr, n);
if(steps <= k){
k -= steps;
curr++;
}else{
curr = curr*10;
k--;
}
}
return curr;
}
int getStep(int curr, long n){
int steps = 0;
long first = curr;
long last = curr;
while(first <= n){
steps += min(last, n) - first + 1;
first = first*10;
last = last*10+9;
}
return steps;
}
};
| 21.16129
| 46
| 0.368902
|
loyio
|
fea15aabecf641d5e10a0afbff8f635f076e6992
| 10,158
|
hpp
|
C++
|
Tensile/Source/client/include/ResultReporter.hpp
|
micmelesse/Tensile
|
62fb9a16909ddef08010915cfefe4c0341f48daa
|
[
"MIT"
] | null | null | null |
Tensile/Source/client/include/ResultReporter.hpp
|
micmelesse/Tensile
|
62fb9a16909ddef08010915cfefe4c0341f48daa
|
[
"MIT"
] | null | null | null |
Tensile/Source/client/include/ResultReporter.hpp
|
micmelesse/Tensile
|
62fb9a16909ddef08010915cfefe4c0341f48daa
|
[
"MIT"
] | null | null | null |
/*******************************************************************************
*
* MIT License
*
* Copyright (c) 2019 Advanced Micro Devices, Inc.
*
* 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.
*
*******************************************************************************/
#pragma once
#include "RunListener.hpp"
#include <cstddef>
#include <string>
namespace Tensile
{
namespace Client
{
enum class LogLevel
{
Error = 0,
Terse,
Verbose,
Debug,
Count
};
std::string ToString(LogLevel level);
std::ostream & operator<<(std::ostream & stream, LogLevel level);
std::istream & operator>>(std::istream & stream, LogLevel & level);
namespace ResultKey
{
const std::string BenchmarkRunNumber = "run";
// Problem definition
const std::string ProblemIndex = "problem-index";
const std::string ProblemCount = "problem-count";
const std::string ProblemProgress = "problem-progress";
const std::string OperationIdentifier = "operation";
const std::string ASizes = "a-sizes";
const std::string BSizes = "b-sizes";
const std::string CSizes = "c-sizes";
const std::string DSizes = "d-sizes";
const std::string AStrides = "a-strides";
const std::string BStrides = "b-strides";
const std::string CStrides = "c-strides";
const std::string DStrides = "d-strides";
const std::string LDA = "lda";
const std::string LDB = "ldb";
const std::string LDC = "ldc";
const std::string LDD = "ldd";
const std::string TotalFlops = "total-flops";
const std::string ProblemSizes = "problem-sizes";
// Solution information
const std::string SolutionName = "solution";
const std::string SolutionIndex = "solution-index";
const std::string SolutionProgress = "solution-progress";
// Performance-related
const std::string Validation = "validation";
const std::string TimeUS = "time-us";
const std::string SpeedGFlops = "gflops";
const std::string EnqueueTime = "enqueue-time";
// Performance estimation and granularity
const std::string Tile0Granularity = "tile0-gran";
const std::string Tile1Granularity = "tile1-gran";
const std::string CuGranularity = "cu-gran";
const std::string WaveGranularity = "wave-gran";
const std::string TotalGranularity = "total-gran";
const std::string TilesPerCu = "tiles-per-cu";
const std::string MemReadBytes = "mem-read-bytes";
const std::string MemWriteBytes = "mem-write-bytes";
const std::string MemGlobalReads = "mem-global-reads";
const std::string MemGlobalWrites = "mem-global-writes";
const std::string L2ReadHits = "perf-l2-read-hits";
const std::string L2WriteHits = "perf-l2-write-hits";
const std::string L2ReadBwMul = "perf-l2-read-bw-mul";
const std::string L2BandwidthMBps = "perf-l2-bandwidth-mbps";
const std::string Empty = "empty";
const std::string Efficiency = "efficiency";
const std::string NumCus = "num-cus";
const std::string PeakGFlops = "peak-gflops";
// Hardware monitoring
const std::string TempEdge = "temp-edge";
const std::string ClockRateSys = "clock-sys"; // GPU clock in Mhz
const std::string ClockRateSOC = "clock-soc"; // Soc clock in Mhz
const std::string ClockRateMem = "clock-mem"; // Mem clock in Mhz
const std::string DeviceIndex = "device-idx";
const std::string FanSpeedRPMs = "fan-rpm";
const std::string HardwareSampleCount = "hardware-samples";
};
class ResultReporter: public RunListener
{
public:
/**
* Reports the value for a key, related to the current state of the run.
*/
void report(std::string const& key, std::string const& value)
{
reportValue_string(key, value);
}
void report(std::string const& key, uint64_t value)
{
reportValue_uint(key, value);
}
void report(std::string const& key, int value)
{
reportValue_int(key, value);
}
void report(std::string const& key, int64_t value)
{
reportValue_int(key, value);
}
void report(std::string const& key, double value)
{
reportValue_double(key, value);
}
void report(std::string const& key, std::vector<size_t> const& value)
{
reportValue_sizes(key, value);
}
virtual void reportValue_string(std::string const& key, std::string const& value) = 0;
virtual void reportValue_uint( std::string const& key, uint64_t value) = 0;
virtual void reportValue_int( std::string const& key, int64_t value) = 0;
virtual void reportValue_double(std::string const& key, double value) = 0;
virtual void reportValue_sizes(std::string const& key, std::vector<size_t> const& value) = 0;
virtual bool logAtLevel(LogLevel level) { return false; };
/**
* Records an informative message. This may or may not actually get printed anywhere depending on settings.
*/
template <typename T>
void log(LogLevel level, T const& object)
{
if(logAtLevel(level))
{
std::ostringstream msg;
msg << object;
logMessage(level, msg.str());
}
}
virtual void logMessage(LogLevel level, std::string const& message) {}
virtual void logTensor(LogLevel level, std::string const& name, void const* data, TensorDescriptor const& tensor, void const* ptrVal) {}
/// RunListener interface functions
virtual void setReporter(std::shared_ptr<ResultReporter> reporter) override {}
virtual bool needMoreBenchmarkRuns() const override { return false; }
virtual void preBenchmarkRun() override {}
virtual void postBenchmarkRun() override {}
virtual void preProblem(ContractionProblem const& problem) override {}
virtual void postProblem() override {}
virtual void preSolution(ContractionSolution const& solution) override {}
virtual void postSolution() override {}
virtual bool needMoreRunsInSolution() const override { return false; }
virtual size_t numWarmupRuns() override { return 0; }
virtual void setNumWarmupRuns(size_t count) override {}
virtual void preWarmup() override {}
virtual void postWarmup() override {}
virtual void validateWarmups(std::shared_ptr<ContractionInputs> inputs,
TimingEvents const& startEvents,
TimingEvents const& stopEvents) override {}
virtual size_t numSyncs() override { return 0; }
virtual void setNumSyncs(size_t count) override {}
virtual void preSyncs() override {}
virtual void postSyncs() override {}
virtual size_t numEnqueuesPerSync() override { return 0; }
virtual void setNumEnqueuesPerSync(size_t count) override {}
virtual void preEnqueues() override {}
virtual void postEnqueues(TimingEvents const& startEvents,
TimingEvents const& stopEvents) override {}
virtual void validateEnqueues(std::shared_ptr<ContractionInputs> inputs,
TimingEvents const& startEvents,
TimingEvents const& stopEvents) override {}
// finalizeReport() deliberately left out of here to force it to be implemented in subclasses.
virtual int error() const override
{
return 0;
}
};
}
}
| 43.784483
| 148
| 0.546171
|
micmelesse
|
fea5787d36aa11d39cfbd670ba034d1cdc00f4f8
| 14,447
|
cc
|
C++
|
vbd/vbd.cc
|
akihito-takeuchi/cpp-variable-binding
|
9664d1245984faf4e40090eab99304ad2d817072
|
[
"MIT"
] | null | null | null |
vbd/vbd.cc
|
akihito-takeuchi/cpp-variable-binding
|
9664d1245984faf4e40090eab99304ad2d817072
|
[
"MIT"
] | null | null | null |
vbd/vbd.cc
|
akihito-takeuchi/cpp-variable-binding
|
9664d1245984faf4e40090eab99304ad2d817072
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2019 Akihito Takeuchi
// Distributed under the MIT License : http://opensource.org/licenses/MIT
#include "vbd/vbd.h"
#include "vbd/vbd_impl.h"
#include "vbd/graphstyle.h"
#include <iostream>
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/join.hpp>
namespace vbd {
namespace {
const std::string kGraphNameKey = "graph_name";
const std::string kGraphSectionName = "graph";
const std::string kNodeSectionName = "node";
const std::string kEdgeSectionName = "edge";
void WriteGraphVizHeader(const std::string& graph_name,
std::ostream& os,
const std::shared_ptr<GraphStyle>& style) {
auto values = style->GetStyle();
os << "digraph " << graph_name << " {\n";
for (auto& sec_name : {kGraphSectionName,
kNodeSectionName,
kEdgeSectionName}) {
std::vector<std::string> style_lines;
for (auto& item : values) {
if (!boost::algorithm::starts_with(item.first, sec_name + "."))
continue;
style_lines.push_back(
(boost::format("%1% = \"%2%\"")
% item.first.substr(sec_name.size() + 1) % item.second).str());
}
if (style_lines.empty())
continue;
os << " " << sec_name << " [\n";
os << " " << boost::algorithm::join(style_lines, ",\n ");
os << "\n ];\n";
}
}
void WriteGraphVizFooter(std::ostream& os) {
os << "}\n";
}
std::string GetVarName(
VariableBase* v, std::unordered_map<VariableBase*, std::string>& name_map) {
std::string var_name;
do {
auto itr = name_map.find(v);
if (itr != name_map.end()) {
var_name = itr->second;
break;
}
std::string name_base = v->Name();
if (name_base.empty())
name_base = "Var";
var_name = name_base;
size_t name_idx = 0;
std::unordered_set<std::string> used_names;
for (auto& pair : name_map)
used_names.insert(pair.second);
while (used_names.find(var_name) != used_names.cend())
var_name = name_base + "_" + boost::lexical_cast<std::string>(name_idx ++);
} while (false);
name_map[v] = var_name;
return var_name;
}
} // namespace
class FunctionNode {
public:
FunctionNode() = default;
FunctionNode(const VoidFuncType& func,
VariableBase* listener,
const std::vector<VariableBase*>& broadcasters)
: func_(func), listener_variable_(listener),
broadcaster_variables_(broadcasters) {}
VariableBase* Listener() const { return listener_variable_; }
const std::vector<VariableBase*>& Broadcasters() const {
return broadcaster_variables_;
}
void Apply() {
func_();
}
private:
VoidFuncType func_;
VariableBase* listener_variable_ = nullptr;
std::vector<VariableBase*> broadcaster_variables_;
friend class VbdEngine;
};
struct PropergateTreeNode {
PropergateTreeNode() = default;
PropergateTreeNode(FunctionNode* f) : func(f) {}
FunctionNode* func = nullptr;
std::vector<PropergateTreeNode> next_nodes;
};
class VbdEngine {
public:
VbdEngine(const VbdEngine&) = delete;
VbdEngine& operator=(const VbdEngine&) = delete;
static VbdEngine& Instance();
void InitVariable(const std::shared_ptr<VariableBase>& v);
void UpdateAccess(VariableBase* v) const;
bool HasPath(const VariableBase* listener,
const VariableBase* broadcaster) const;
void UpdateGroupID(VariableBase* listener,
VariableBase* broadcaster);
void StartTransaction();
bool TryStartTransaction();
void EndTransaction();
void RegisterAssignOperation(VariableBase* variable,
const VoidFuncType& func);
void UnregisterAssignOperation(VariableBase* variable);
void Exec();
bool Executing() { return executing_; }
void CreateGraphViz(const std::string& graph_name,
std::ostream& os,
const std::shared_ptr<GraphStyle>& style);
private:
VbdEngine();
void UpdateAccess_(VariableBase* v,
std::forward_list<VariableBase*>& visited) const;
bool HasPath_(std::unordered_set<const VariableBase*> listeners,
const VariableBase* broadcaster) const;
void Assign_();
void BuildPropergationFlow_(PropergateTreeNode& tree);
void TraceTree_(PropergateTreeNode& tree,
std::unordered_set<FunctionNode*>& visited);
void Propergate_(PropergateTreeNode& tree);
void ProcessPropergateNode_(PropergateTreeNode& tree);
void Rollback_();
static void Init();
static std::once_flag init_flag_;
static std::unique_ptr<VbdEngine> instance_;
std::unordered_set<std::shared_ptr<VariableBase>> variables_;
std::unordered_map<unsigned int,
std::unordered_set<VariableBase*>> variables_by_group_;
std::vector<std::pair<VariableBase*, VoidFuncType>> assign_info_list_;
std::unordered_map<VariableBase*, boost::any> initial_values_;
unsigned int group_id_next_ = 0;
bool in_transaction_ = false;
bool executing_ = false;
};
VbdEngine::VbdEngine() = default;
std::once_flag VbdEngine::init_flag_;
std::unique_ptr<VbdEngine> VbdEngine::instance_ = nullptr;
VbdEngine& VbdEngine::Instance() {
std::call_once(init_flag_, Init);
return *instance_;
}
void VbdEngine::Init() {
instance_ = std::unique_ptr<VbdEngine>(new VbdEngine);
}
void VbdEngine::InitVariable(const std::shared_ptr<VariableBase>& v) {
v->group_id_ = group_id_next_ ++;
variables_by_group_[v->group_id_].emplace(v.get());
variables_.emplace(v);
}
void VbdEngine::StartTransaction() {
if (in_transaction_)
throw Exception(
"VbdEngine::StartTransaction : "
"Transaction has already been started.");
if (!assign_info_list_.empty())
throw Exception(
"VbdEngine::StartTransaction : "
"A transaction has already been constructed and wait execution");
in_transaction_ = true;
}
bool VbdEngine::TryStartTransaction() {
if (in_transaction_)
return false;
StartTransaction();
return true;
}
void VbdEngine::EndTransaction() {
if (!in_transaction_)
throw Exception(
"VbdEngine::EndTransaction : Transaction has not been started.");
in_transaction_ = false;
}
void VbdEngine::RegisterAssignOperation(VariableBase* variable,
const VoidFuncType& func) {
UnregisterAssignOperation(variable);
assign_info_list_.emplace_back(variable, func);
}
void VbdEngine::UnregisterAssignOperation(VariableBase* variable) {
assign_info_list_.erase(
std::remove_if(assign_info_list_.begin(), assign_info_list_.end(),
[&variable](auto p) { return p.first == variable; }),
assign_info_list_.end());
}
void VbdEngine::Exec() {
executing_ = true;
PropergateTreeNode start_node;
BuildPropergationFlow_(start_node);
try {
Propergate_(start_node);
initial_values_.clear();
executing_ = false;
} catch (const Exception& e) {
Rollback_();
assign_info_list_.clear();
initial_values_.clear();
executing_ = false;
throw;
}
}
void VbdEngine::Assign_() {
for (auto& info : assign_info_list_) {
auto v = info.first;
if (initial_values_.find(v) == initial_values_.end())
initial_values_[v] = v->value_;
info.second();
info.first->ExecCallback();
}
assign_info_list_.clear();
}
void VbdEngine::BuildPropergationFlow_(PropergateTreeNode& tree) {
for (auto& info : assign_info_list_) {
for (auto next_func : info.first->to_listener_funcs_) {
auto next_func_ptr = next_func.get();
std::unordered_set<FunctionNode*> visited{next_func_ptr};
tree.next_nodes.emplace_back(next_func_ptr);
TraceTree_(tree.next_nodes.back(), visited);
}
}
}
void VbdEngine::TraceTree_(PropergateTreeNode& tree,
std::unordered_set<FunctionNode*>& visited) {
for (auto next_func : tree.func->listener_variable_->to_listener_funcs_) {
auto next_func_ptr = next_func.get();
if (visited.find(next_func_ptr) == visited.end()) {
visited.insert(next_func_ptr);
tree.next_nodes.emplace_back(next_func_ptr);
TraceTree_(tree.next_nodes.back(), visited);
}
}
}
void VbdEngine::ProcessPropergateNode_(PropergateTreeNode& node) {
node.func->Apply();
Assign_();
for (auto& next_node : node.next_nodes)
ProcessPropergateNode_(next_node);
}
void VbdEngine::Propergate_(PropergateTreeNode& tree) {
Assign_();
for (auto& node : tree.next_nodes)
ProcessPropergateNode_(node);
Assign_();
}
void VbdEngine::Rollback_() {
for (auto v : initial_values_)
v.first->value_ = v.second;
}
void VbdEngine::UpdateAccess(VariableBase* v) const {
std::forward_list<VariableBase*> chain{v};
UpdateAccess_(v, chain);
}
void VbdEngine::UpdateAccess_(
VariableBase* v, std::forward_list<VariableBase*>& chain) const {
if (v->to_broadcaster_funcs_.size() == 0) {
// v is not a listener
v->access_ = Access::kWritable;
return;
}
for (auto& broadcaster_func : v->to_broadcaster_funcs_) {
for (auto& broadcaster : broadcaster_func->Broadcasters()) {
// If subtree is already initialized, there should be no cyclic reference
if (broadcaster->access_ != Access::kNotInitialized) {
v->access_ = Access::kReadOnly;
continue;
}
auto itr = std::find(chain.begin(), chain.end(), broadcaster);
// If broadcaster is already in chain, it has cyclic reference
if (itr != chain.end()) {
itr ++;
std::for_each(chain.begin(), itr,
[](auto& v) { v->access_ = Access::kWritable; });
continue;
}
chain.push_front(broadcaster);
UpdateAccess_(broadcaster, chain);
chain.pop_front();
}
}
}
bool VbdEngine::HasPath(const VariableBase* listener,
const VariableBase* broadcaster) const {
return HasPath_({listener}, broadcaster);
}
bool VbdEngine::HasPath_(
std::unordered_set<const VariableBase*> listeners,
const VariableBase* broadcaster) const {
if (listeners.empty())
return false;
if (listeners.find(broadcaster) != listeners.end())
return true;
std::unordered_set<const VariableBase*> next_listeners;
for (auto& listener : listeners)
for (auto& broadcaster_func : listener->to_broadcaster_funcs_)
next_listeners.insert(broadcaster_func->Broadcasters().begin(),
broadcaster_func->Broadcasters().end());
return HasPath_(next_listeners, broadcaster);
}
void VbdEngine::UpdateGroupID(VariableBase* listener,
VariableBase* broadcaster) {
std::vector<unsigned int> group_ids_to_reset;
group_ids_to_reset.emplace_back(listener->group_id_);
if (listener->group_id_ != broadcaster->group_id_) {
group_ids_to_reset.emplace_back(broadcaster->group_id_);
listener->group_id_ = broadcaster->group_id_;
variables_by_group_[listener->group_id_].erase(listener);
variables_by_group_[broadcaster->group_id_].emplace(listener);
}
for (auto group_id : group_ids_to_reset)
for (auto v : variables_by_group_[group_id])
v->access_ = Access::kNotInitialized;
}
void VbdEngine::CreateGraphViz(const std::string& graph_name,
std::ostream& os,
const std::shared_ptr<GraphStyle>& style) {
WriteGraphVizHeader(graph_name, os, style);
std::unordered_map<VariableBase*, std::string> name_map;
std::vector<std::string> edges;
os << " // nodes\n";
for (auto& node : variables_) {
auto name_from = GetVarName(node.get(), name_map);
os << " " << name_from << ";\n";
for (auto& listener_func : node->to_listener_funcs_) {
auto name_to = GetVarName(listener_func->listener_variable_, name_map);
edges.push_back(name_from + " -> " + name_to);
}
}
os << " // edges\n";
for (auto& edge : edges)
os << " " << edge << ";\n";
WriteGraphVizFooter(os);
}
VariableBase::VariableBase()
: access_(Access::kNotInitialized) {
}
VariableBase::VariableBase(const std::string& name)
: name_(name), access_(Access::kNotInitialized) {
}
VariableBase::~VariableBase() = default;
bool VariableBase::IsReadonly() const {
if (access_ == Access::kNotInitialized) {
VbdEngine::Instance().UpdateAccess(
const_cast<VariableBase*>(this));
}
return access_ != Access::kWritable;
}
void VariableBase::RegisterAssignOperation(VariableBase* variable,
const VoidFuncType& func) {
auto& engine = VbdEngine::Instance();
if (engine.Executing()) {
engine.RegisterAssignOperation(variable, func);
return;
}
auto new_transaction = engine.TryStartTransaction();
engine.RegisterAssignOperation(variable, func);
if (new_transaction) {
engine.EndTransaction();
engine.Exec();
}
}
void VariableBase::UnregisterAssignOperation(VariableBase* variable) {
auto& engine = VbdEngine::Instance();
engine.UnregisterAssignOperation(variable);
}
void VariableBase::UpdateGroupID(VariableBase* listener,
VariableBase* broadcaster) {
VbdEngine::Instance().UpdateGroupID(listener, broadcaster);
}
bool VariableBase::HasPath(const VariableBase* listener,
const VariableBase* broadcaster) const {
return VbdEngine::Instance().HasPath(listener, broadcaster);
}
FunctionPtr VariableBase::CreateFunctionNode(
const VoidFuncType& func,
VariableBase* listener,
const std::vector<VariableBase*>&& broadcaster) {
return std::make_shared<FunctionNode>(func, listener, broadcaster);
}
void InitVariable(const std::shared_ptr<VariableBase>& v) {
VbdEngine::Instance().InitVariable(v);
}
void CreateGraphViz(const std::string& graph_name,
std::ostream& os,
std::shared_ptr<GraphStyle> style) {
if (!style)
style = std::make_shared<GraphStyle>();
VbdEngine::Instance().CreateGraphViz(graph_name, os, style);
}
void Transaction(const TransactionFuncType& func) {
ConstructTransaction(func);
ExecTransaction();
}
void ConstructTransaction(const TransactionFuncType& func) {
auto& engine = VbdEngine::Instance();
engine.StartTransaction();
func();
engine.EndTransaction();
}
void ExecTransaction() {
VbdEngine::Instance().Exec();
}
} // namespace vbd
| 31.135776
| 81
| 0.67232
|
akihito-takeuchi
|
fea847180db4236e8668e6eb2ada7c4f2fbe1cce
| 7,833
|
cxx
|
C++
|
Qt/Widgets/pqDoubleLineEdit.cxx
|
hkroeger/caetool-paraview
|
716d3174523674134a93bfe3a3d335c1ed87d7f1
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
Qt/Widgets/pqDoubleLineEdit.cxx
|
hkroeger/caetool-paraview
|
716d3174523674134a93bfe3a3d335c1ed87d7f1
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
Qt/Widgets/pqDoubleLineEdit.cxx
|
hkroeger/caetool-paraview
|
716d3174523674134a93bfe3a3d335c1ed87d7f1
|
[
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null |
/*=========================================================================
Program: ParaView
Module: pqDoubleLineEdit.cxx
Copyright (c) 2005-2018 Sandia Corporation, Kitware Inc.
All rights reserved.
ParaView is a free software; you can redistribute it and/or modify it
under the terms of the ParaView license version 1.2.
See License_v1.2.txt for the full ParaView license.
A copy of this license can be obtained by contacting
Kitware Inc.
28 Corporate Drive
Clifton Park, NY 12065
USA
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 AUTHORS 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 "pqDoubleLineEdit.h"
// Qt Includes.
#include <QDoubleValidator>
#include <QFocusEvent>
#include <QPointer>
#include <QTextStream>
namespace
{
//-----------------------------------------------------------------------------
QTextStream::RealNumberNotation toTextStreamNotation(pqDoubleLineEdit::RealNumberNotation notation)
{
if (notation == pqDoubleLineEdit::FixedNotation)
{
return QTextStream::FixedNotation;
}
else if (notation == pqDoubleLineEdit::ScientificNotation)
{
return QTextStream::ScientificNotation;
}
else
{
return QTextStream::SmartNotation;
}
}
//-----------------------------------------------------------------------------
using InstanceTrackerType = QList<QPointer<pqDoubleLineEdit> >;
static InstanceTrackerType* InstanceTracker = nullptr;
}
int pqDoubleLineEdit::GlobalPrecision = 6;
pqDoubleLineEdit::RealNumberNotation pqDoubleLineEdit::GlobalNotation =
pqDoubleLineEdit::MixedNotation;
//-----------------------------------------------------------------------------
void pqDoubleLineEdit::setGlobalPrecisionAndNotation(int precision, RealNumberNotation notation)
{
bool modified = false;
if (precision != pqDoubleLineEdit::GlobalPrecision)
{
pqDoubleLineEdit::GlobalPrecision = precision;
modified = true;
}
if (pqDoubleLineEdit::GlobalNotation != notation)
{
pqDoubleLineEdit::GlobalNotation = notation;
modified = true;
}
if (modified && InstanceTracker != nullptr)
{
for (const auto& instance : *InstanceTracker)
{
if (instance && instance->useGlobalPrecisionAndNotation())
{
instance->updateLimitedPrecisionText();
}
}
}
}
//-----------------------------------------------------------------------------
pqDoubleLineEdit::RealNumberNotation pqDoubleLineEdit::globalNotation()
{
return pqDoubleLineEdit::GlobalNotation;
}
//-----------------------------------------------------------------------------
int pqDoubleLineEdit::globalPrecision()
{
return pqDoubleLineEdit::GlobalPrecision;
}
//-----------------------------------------------------------------------------
pqDoubleLineEdit::pqDoubleLineEdit(QWidget* _parent)
: Superclass(_parent)
, Precision(2)
, UseGlobalPrecisionAndNotation(true)
{
this->setValidator(new QDoubleValidator(this));
this->setNotation(pqDoubleLineEdit::FixedNotation);
if (InstanceTracker == nullptr)
{
InstanceTracker = new InstanceTrackerType();
}
InstanceTracker->push_back(this);
}
//-----------------------------------------------------------------------------
pqDoubleLineEdit::~pqDoubleLineEdit()
{
if (InstanceTracker)
{
InstanceTracker->removeAll(this);
if (InstanceTracker->size() == 0)
{
delete InstanceTracker;
InstanceTracker = nullptr;
}
}
}
//-----------------------------------------------------------------------------
QString pqDoubleLineEdit::fullPrecisionText() const
{
return this->FullPrecisionText;
}
//-----------------------------------------------------------------------------
void pqDoubleLineEdit::setFullPrecisionText(const QString& _text)
{
if (this->FullPrecisionText == _text)
{
return;
}
this->FullPrecisionText = _text;
this->updateLimitedPrecisionText();
emit fullPrecisionTextChanged(this->FullPrecisionText);
}
//-----------------------------------------------------------------------------
pqDoubleLineEdit::RealNumberNotation pqDoubleLineEdit::notation() const
{
return this->Notation;
}
//-----------------------------------------------------------------------------
void pqDoubleLineEdit::setNotation(pqDoubleLineEdit::RealNumberNotation _notation)
{
if (this->Notation == _notation)
{
return;
}
this->Notation = _notation;
this->updateLimitedPrecisionText();
}
//-----------------------------------------------------------------------------
int pqDoubleLineEdit::precision() const
{
return this->Precision;
}
//-----------------------------------------------------------------------------
void pqDoubleLineEdit::setPrecision(int _precision)
{
if (this->Precision == _precision)
{
return;
}
this->Precision = _precision;
this->updateLimitedPrecisionText();
}
//-----------------------------------------------------------------------------
void pqDoubleLineEdit::focusInEvent(QFocusEvent* event)
{
if (event->gotFocus())
{
this->onEditingStarted();
}
return this->Superclass::focusInEvent(event);
}
//-----------------------------------------------------------------------------
void pqDoubleLineEdit::updateLimitedPrecisionText()
{
const auto real_precision =
this->UseGlobalPrecisionAndNotation ? pqDoubleLineEdit::GlobalPrecision : this->Precision;
const auto real_notation =
this->UseGlobalPrecisionAndNotation ? pqDoubleLineEdit::GlobalNotation : this->Notation;
QString limited;
QTextStream converter(&limited);
converter.setRealNumberNotation(toTextStreamNotation(real_notation));
converter.setRealNumberPrecision(real_precision);
converter << this->FullPrecisionText.toDouble();
this->setText(limited);
}
//-----------------------------------------------------------------------------
void pqDoubleLineEdit::onEditingStarted()
{
this->setText(this->FullPrecisionText);
connect(this, SIGNAL(editingFinished()), this, SLOT(onEditingFinished()));
}
//-----------------------------------------------------------------------------
void pqDoubleLineEdit::onEditingFinished()
{
disconnect(this, SIGNAL(editingFinished()), this, SLOT(onEditingFinished()));
QString previousFullPrecisionText = this->FullPrecisionText;
this->setFullPrecisionText(this->text());
this->updateLimitedPrecisionText();
this->clearFocus();
if (previousFullPrecisionText != this->FullPrecisionText)
{
emit fullPrecisionTextChangedAndEditingFinished();
}
}
//-----------------------------------------------------------------------------
void pqDoubleLineEdit::triggerFullPrecisionTextChangedAndEditingFinished()
{
emit fullPrecisionTextChangedAndEditingFinished();
}
//-----------------------------------------------------------------------------
bool pqDoubleLineEdit::useGlobalPrecisionAndNotation() const
{
return this->UseGlobalPrecisionAndNotation;
}
//-----------------------------------------------------------------------------
void pqDoubleLineEdit::setUseGlobalPrecisionAndNotation(bool value)
{
this->UseGlobalPrecisionAndNotation = value;
this->updateLimitedPrecisionText();
}
| 30.838583
| 99
| 0.58994
|
hkroeger
|
feaf9b4f8a7902a8d1ed0745a72ea920a5f56eaa
| 2,731
|
cpp
|
C++
|
Plugins/MadaraLibrary/Source/ThirdParty/madara/expression/CompositeAndNode.cpp
|
jredmondson/GamsPlugins
|
d133f86c263997a55f11b3b3d3344faeee60d726
|
[
"BSD-2-Clause"
] | 3
|
2020-03-25T01:59:20.000Z
|
2020-06-02T17:58:05.000Z
|
Plugins/MadaraLibrary/Source/ThirdParty/madara/expression/CompositeAndNode.cpp
|
jredmondson/GamsPlugins
|
d133f86c263997a55f11b3b3d3344faeee60d726
|
[
"BSD-2-Clause"
] | null | null | null |
Plugins/MadaraLibrary/Source/ThirdParty/madara/expression/CompositeAndNode.cpp
|
jredmondson/GamsPlugins
|
d133f86c263997a55f11b3b3d3344faeee60d726
|
[
"BSD-2-Clause"
] | 1
|
2020-11-05T23:04:05.000Z
|
2020-11-05T23:04:05.000Z
|
/* -*- C++ -*- */
#ifndef COMPOSITE_AND_NODE_CPP
#define COMPOSITE_AND_NODE_CPP
#ifndef _MADARA_NO_KARL_
#include <iostream>
#include "madara/expression/ComponentNode.h"
#include "madara/expression/Visitor.h"
#include "madara/expression/CompositeAndNode.h"
#include "madara/expression/LeafNode.h"
// Ctor
madara::expression::CompositeAndNode::CompositeAndNode(
logger::Logger& logger, const ComponentNodes& nodes)
: madara::expression::CompositeTernaryNode(logger, nodes)
{
}
madara::knowledge::KnowledgeRecord madara::expression::CompositeAndNode::item(
void) const
{
return knowledge::KnowledgeRecord("&&");
}
/// Prune the tree of unnecessary nodes.
/// Returns evaluation of the node and sets can_change appropriately.
/// if this node can be changed, that means it shouldn't be pruned.
madara::knowledge::KnowledgeRecord madara::expression::CompositeAndNode::prune(
bool& can_change)
{
madara::knowledge::KnowledgeRecord return_value;
int j = 0;
for (ComponentNodes::iterator i = nodes_.begin(); i != nodes_.end(); ++i, ++j)
{
bool value_changes = false;
madara::knowledge::KnowledgeRecord value;
value = (*i)->prune(value_changes);
if (!value_changes && dynamic_cast<LeafNode*>(*i) == 0)
{
delete *i;
*i = new LeafNode(*this->logger_, value);
}
if (j == 0)
return_value = value;
else
return_value = knowledge::KnowledgeRecord(value && return_value);
can_change = can_change || value_changes;
}
if (nodes_.size() < 2)
{
madara_logger_ptr_log(logger_, logger::LOG_ERROR,
"CompositeAndNode: "
"KARL COMPILE ERROR (&&): "
"And should have a left and right-hand side argument.\n");
throw exceptions::KarlException(
"CompositeAndNode: "
"KARL COMPILE ERROR (&&): "
"And should have a left and right-hand side argument.\n");
}
return return_value;
}
/// Evaluates the node and its children. This does not prune any of
/// the expression tree, and is much faster than the prune function
madara::knowledge::KnowledgeRecord
madara::expression::CompositeAndNode::evaluate(
const madara::knowledge::KnowledgeUpdateSettings& settings)
{
int j = 0;
for (ComponentNodes::iterator i = nodes_.begin(); i != nodes_.end(); ++i, ++j)
{
// if we have a zero eval, return 0 immediately
if ((*i)->evaluate(settings).is_false())
return madara::knowledge::KnowledgeRecord(0);
}
// if everything was true, return true
return madara::knowledge::KnowledgeRecord(1);
}
// accept a visitor
void madara::expression::CompositeAndNode::accept(Visitor& visitor) const
{
visitor.visit(*this);
}
#endif // _MADARA_NO_KARL_
#endif /* COMPOSITE_AND_NODE_CPP */
| 27.31
| 80
| 0.692054
|
jredmondson
|
feb06acef31e784da976ebc368b7b575ad5873c7
| 6,222
|
cpp
|
C++
|
src/thirdparty/qtpropertybrowser/qtpropertybrowser-2.5_1-opensource/examples/object_controller/main.cpp
|
kulibali/neurolab
|
c522358a22fb384dbea6fee87b49d8572f8db844
|
[
"BSD-3-Clause"
] | 1
|
2021-10-09T16:12:07.000Z
|
2021-10-09T16:12:07.000Z
|
src/thirdparty/qtpropertybrowser/qtpropertybrowser-2.5_1-opensource/examples/object_controller/main.cpp
|
kulibali/neurolab
|
c522358a22fb384dbea6fee87b49d8572f8db844
|
[
"BSD-3-Clause"
] | null | null | null |
src/thirdparty/qtpropertybrowser/qtpropertybrowser-2.5_1-opensource/examples/object_controller/main.cpp
|
kulibali/neurolab
|
c522358a22fb384dbea6fee87b49d8572f8db844
|
[
"BSD-3-Clause"
] | null | null | null |
/****************************************************************************
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of a Qt Solutions component.
**
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Solutions Commercial License Agreement provided
** with the Software or, alternatively, in accordance with the terms
** contained in a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.1, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** Please note Third Party Software included with Qt Solutions may impose
** additional restrictions and it is the user's responsibility to ensure
** that they have met the licensing requirements of the GPL, LGPL, or Qt
** Solutions Commercial license and the relevant license of the Third
** Party Software they are using.
**
** If you are unsure which license is appropriate for your use, please
** contact Nokia at qt-info@nokia.com.
**
****************************************************************************/
#include <QtGui/QApplication>
#include <QtGui/QSpinBox>
#include <QtGui/QDialogButtonBox>
#include <QtGui/QLineEdit>
#include <QtGui/QDialog>
#include <QtGui/QComboBox>
#include <QtGui/QToolButton>
#include <QtGui/QPushButton>
#include <QtGui/QBoxLayout>
#include <QtGui/QTreeWidget>
#include <QtGui/QAction>
#include <QtGui/QDesktopWidget>
#include <QtGui/QTextDocument>
#include <QtGui/QCalendarWidget>
#include <QtCore/QTimeLine>
#include "objectcontroller.h"
class MyController : public QDialog
{
Q_OBJECT
public:
MyController(QWidget *parent = 0);
~MyController();
private slots:
void createAndControl();
private:
QComboBox *theClassCombo;
ObjectController *theController;
QStringList theClassNames;
QObject *theControlledObject;
};
MyController::MyController(QWidget *parent)
: QDialog(parent), theControlledObject(0)
{
theClassCombo = new QComboBox(this);
QToolButton *button = new QToolButton(this);
theController = new ObjectController(this);
QDialogButtonBox *buttonBox = new QDialogButtonBox(this);
connect(button, SIGNAL(clicked()), this, SLOT(createAndControl()));
connect(buttonBox, SIGNAL(rejected()), this, SLOT(reject()));
button->setText(tr("Create And Control"));
buttonBox->setStandardButtons(QDialogButtonBox::Close);
QVBoxLayout *layout = new QVBoxLayout(this);
QHBoxLayout *internalLayout = new QHBoxLayout();
internalLayout->addWidget(theClassCombo);
internalLayout->addWidget(button);
layout->addLayout(internalLayout);
layout->addWidget(theController);
layout->addWidget(buttonBox);
theClassNames.append(QLatin1String("QWidget"));
theClassNames.append(QLatin1String("QPushButton"));
theClassNames.append(QLatin1String("QDialogButtonBox"));
theClassNames.append(QLatin1String("QTreeWidget"));
theClassNames.append(QLatin1String("QCalendarWidget"));
theClassNames.append(QLatin1String("QAction"));
theClassNames.append(QLatin1String("QTimeLine"));
theClassNames.append(QLatin1String("QTextDocument"));
theClassCombo->addItems(theClassNames);
}
MyController::~MyController()
{
if (theControlledObject)
delete theControlledObject;
}
void MyController::createAndControl()
{
QObject *newObject = 0;
QString className = theClassNames.at(theClassCombo->currentIndex());
if (className == QLatin1String("QWidget"))
newObject = new QWidget();
else if (className == QLatin1String("QPushButton"))
newObject = new QPushButton();
else if (className == QLatin1String("QDialogButtonBox"))
newObject = new QDialogButtonBox();
else if (className == QLatin1String("QTreeWidget"))
newObject = new QTreeWidget();
else if (className == QLatin1String("QCalendarWidget"))
newObject = new QCalendarWidget();
else if (className == QLatin1String("QAction"))
newObject = new QAction(0);
else if (className == QLatin1String("QTimeLine"))
newObject = new QTimeLine();
else if (className == QLatin1String("QTextDocument"))
newObject = new QTextDocument();
if (!newObject)
return;
QWidget *newWidget = qobject_cast<QWidget *>(newObject);
if (newWidget) {
QRect r = newWidget->geometry();
r.setSize(newWidget->sizeHint());
r.setWidth(qMax(r.width(), 150));
r.setHeight(qMax(r.height(), 50));
r.moveCenter(QApplication::desktop()->geometry().center());
newWidget->setGeometry(r);
newWidget->setWindowTitle(tr("Controlled Object: %1").arg(className));
newWidget->show();
}
if (theControlledObject)
delete theControlledObject;
theControlledObject = newObject;
theController->setObject(theControlledObject);
}
int main(int argc, char **argv)
{
QApplication app(argc, argv);
MyController *controller = new MyController();
controller->show();
int ret = app.exec();
return ret;
}
#include "main.moc"
| 35.554286
| 78
| 0.704275
|
kulibali
|
feb6c072ed5af3d2ebfbd8ea77d955e4dce3d5e9
| 3,874
|
cc
|
C++
|
modules/pacing/paced_sender_unittest.cc
|
tstan123/webrtc-client-native
|
ef66da2abd2db839c9e57958ea090538ab339808
|
[
"BSD-3-Clause"
] | 128
|
2019-10-07T14:03:15.000Z
|
2022-02-25T10:25:57.000Z
|
modules/pacing/paced_sender_unittest.cc
|
tstan123/webrtc-client-native
|
ef66da2abd2db839c9e57958ea090538ab339808
|
[
"BSD-3-Clause"
] | 51
|
2019-10-19T04:58:30.000Z
|
2022-01-03T07:16:46.000Z
|
modules/pacing/paced_sender_unittest.cc
|
tstan123/webrtc-client-native
|
ef66da2abd2db839c9e57958ea090538ab339808
|
[
"BSD-3-Clause"
] | 90
|
2019-10-16T06:13:14.000Z
|
2022-03-02T10:29:19.000Z
|
/*
* Copyright (c) 2012 The WebRTC 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 in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "modules/pacing/paced_sender.h"
#include <list>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include "modules/pacing/packet_router.h"
#include "modules/utility/include/mock/mock_process_thread.h"
#include "system_wrappers/include/clock.h"
#include "system_wrappers/include/field_trial.h"
#include "test/field_trial.h"
#include "test/gmock.h"
#include "test/gtest.h"
using ::testing::_;
using ::testing::Return;
using ::testing::SaveArg;
namespace {
constexpr uint32_t kAudioSsrc = 12345;
constexpr uint32_t kVideoSsrc = 234565;
constexpr uint32_t kVideoRtxSsrc = 34567;
constexpr uint32_t kFlexFecSsrc = 45678;
constexpr size_t kDefaultPacketSize = 234;
} // namespace
namespace webrtc {
namespace test {
// Mock callback implementing the raw api.
class MockCallback : public PacketRouter {
public:
MOCK_METHOD2(SendPacket,
void(std::unique_ptr<RtpPacketToSend> packet,
const PacedPacketInfo& cluster_info));
MOCK_METHOD1(
GeneratePadding,
std::vector<std::unique_ptr<RtpPacketToSend>>(size_t target_size_bytes));
};
std::unique_ptr<RtpPacketToSend> BuildRtpPacket(RtpPacketToSend::Type type) {
auto packet = std::make_unique<RtpPacketToSend>(nullptr);
packet->set_packet_type(type);
switch (type) {
case RtpPacketToSend::Type::kAudio:
packet->SetSsrc(kAudioSsrc);
break;
case RtpPacketToSend::Type::kVideo:
packet->SetSsrc(kVideoSsrc);
break;
case RtpPacketToSend::Type::kRetransmission:
case RtpPacketToSend::Type::kPadding:
packet->SetSsrc(kVideoRtxSsrc);
break;
case RtpPacketToSend::Type::kForwardErrorCorrection:
packet->SetSsrc(kFlexFecSsrc);
break;
}
packet->SetPayloadSize(kDefaultPacketSize);
return packet;
}
TEST(PacedSenderTest, PacesPackets) {
SimulatedClock clock(0);
MockCallback callback;
MockProcessThread process_thread;
Module* paced_module = nullptr;
EXPECT_CALL(process_thread, RegisterModule(_, _))
.WillOnce(SaveArg<0>(&paced_module));
PacedSender pacer(&clock, &callback, nullptr, nullptr, &process_thread);
EXPECT_CALL(process_thread, DeRegisterModule(paced_module)).Times(1);
// Insert a number of packets, covering one second.
static constexpr size_t kPacketsToSend = 42;
pacer.SetPacingRates(DataRate::bps(kDefaultPacketSize * 8 * kPacketsToSend),
DataRate::Zero());
std::vector<std::unique_ptr<RtpPacketToSend>> packets;
for (size_t i = 0; i < kPacketsToSend; ++i) {
packets.emplace_back(BuildRtpPacket(RtpPacketToSend::Type::kVideo));
}
pacer.EnqueuePackets(std::move(packets));
// Expect all of them to be sent.
size_t packets_sent = 0;
clock.AdvanceTimeMilliseconds(paced_module->TimeUntilNextProcess());
EXPECT_CALL(callback, SendPacket)
.WillRepeatedly(
[&](std::unique_ptr<RtpPacketToSend> packet,
const PacedPacketInfo& cluster_info) { ++packets_sent; });
const Timestamp start_time = clock.CurrentTime();
while (packets_sent < kPacketsToSend) {
clock.AdvanceTimeMilliseconds(paced_module->TimeUntilNextProcess());
paced_module->Process();
}
// Packets should be sent over a period of close to 1s. Expect a little lower
// than this since initial probing is a bit quicker.
TimeDelta duration = clock.CurrentTime() - start_time;
EXPECT_GT(duration, TimeDelta::ms(900));
}
} // namespace test
} // namespace webrtc
| 32.283333
| 79
| 0.728704
|
tstan123
|
feb9c3d70cea77934f163a13008042476d41e0d0
| 431
|
cpp
|
C++
|
areas/MarjanQML/main.cpp
|
misoboute/playground
|
9732bf50ddec7fd2112d60b372c4489f9d1b1763
|
[
"MIT"
] | null | null | null |
areas/MarjanQML/main.cpp
|
misoboute/playground
|
9732bf50ddec7fd2112d60b372c4489f9d1b1763
|
[
"MIT"
] | 1
|
2019-12-01T11:03:21.000Z
|
2020-07-27T12:21:28.000Z
|
areas/MarjanQML/main.cpp
|
misoboute/playground
|
9732bf50ddec7fd2112d60b372c4489f9d1b1763
|
[
"MIT"
] | 2
|
2019-07-26T10:01:25.000Z
|
2019-12-01T10:55:26.000Z
|
#include <iostream>
#include <QApplication>
#include <QQmlApplicationEngine>
int main(int argc, char** argv)
{
// try
// {
QApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
// }
// catch(const std::exception& e)
// {
// std::cout << "What the hell: " << e.what() << std::endl;
// }
}
| 21.55
| 67
| 0.559165
|
misoboute
|
febaa98e494ff30b63d5ed1fc27864108e2bc989
| 8,503
|
cpp
|
C++
|
disc-fe/src/Panzer_Workset_Utilities.cpp
|
hillyuan/Panzer
|
13ece3ea4c145c4d7b6339e3ad6332a501932ea8
|
[
"BSD-3-Clause"
] | 1
|
2022-03-22T03:49:50.000Z
|
2022-03-22T03:49:50.000Z
|
disc-fe/src/Panzer_Workset_Utilities.cpp
|
hillyuan/Panzer
|
13ece3ea4c145c4d7b6339e3ad6332a501932ea8
|
[
"BSD-3-Clause"
] | null | null | null |
disc-fe/src/Panzer_Workset_Utilities.cpp
|
hillyuan/Panzer
|
13ece3ea4c145c4d7b6339e3ad6332a501932ea8
|
[
"BSD-3-Clause"
] | null | null | null |
// @HEADER
// ***********************************************************************
//
// Panzer: A partial differential equation assembly
// engine for strongly coupled complex multiphysics systems
// Copyright (2011) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// 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 Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// Questions? Contact Roger P. Pawlowski (rppawlo@sandia.gov) and
// Eric C. Cyr (eccyr@sandia.gov)
// ***********************************************************************
// @HEADER
#ifndef PANZER_WORKSET_UTILITIES_HPP
#define PANZER_WORKSET_UTILITIES_HPP
#include "Panzer_Traits.hpp"
#include "Panzer_Workset.hpp"
#include "Teuchos_Assert.hpp"
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>
namespace panzer {
std::vector<std::string>::size_type
getPureBasisIndex(std::string basis_name, const panzer::Workset& workset, WorksetDetailsAccessor& wda)
{
std::vector<std::string>::iterator basis = wda(workset).basis_names->begin();
std::vector<std::string>::const_iterator last = wda(workset).basis_names->end();
while (basis != last) {
std::vector<std::string>::size_type index = std::distance(wda(workset).basis_names->begin(), basis);
if (wda(workset).bases[index]->basis_layout->getBasis()->name() == basis_name)
break;
++basis;
}
TEUCHOS_TEST_FOR_EXCEPTION(basis == wda(workset).basis_names->end(),
std::logic_error,
"Could not find the basis named \""
<< basis_name << "\" in the workset!");
return std::distance(wda(workset).basis_names->begin(), basis);
}
std::vector<std::string>::size_type
getBasisIndex(std::string basis_name, const panzer::Workset& workset, WorksetDetailsAccessor& wda)
{
std::vector<std::string>::iterator basis;
basis = std::find(wda(workset).basis_names->begin(),
wda(workset).basis_names->end(),
basis_name);
TEUCHOS_TEST_FOR_EXCEPTION(basis == wda(workset).basis_names->end(),
std::logic_error,
"Could not find the basis named \""
<< basis_name << "\" in the workset!");
return std::distance(wda(workset).basis_names->begin(), basis);
}
std::vector<int>::size_type
getIntegrationRuleIndex(int ir_degree, const panzer::Workset& workset, WorksetDetailsAccessor& wda)
{
std::vector<int>::iterator ir;
ir = std::find(wda(workset).ir_degrees->begin(),
wda(workset).ir_degrees->end(),
ir_degree);
TEUCHOS_TEST_FOR_EXCEPTION(ir == wda(workset).ir_degrees->end(),
std::logic_error,
"Could not find the integration rule degree \""
<< ir_degree << "\" in the workset!");
return std::distance(wda(workset).ir_degrees->begin(), ir);
}
void printWorkset(std::ostream& os, const panzer::Workset & workset, WorksetDetailsAccessor& wda)
{
os << "WORKSET"
<< " block_id = \"" << wda(workset).block_id << "\""
<< " num_cells = \"" << workset.num_cells << "\"\n";
os << " cell_local_ids = [ ";
for(index_t i=0;i<workset.num_cells;i++)
os << wda(workset).cell_local_ids[i] << " ";
os << "]\n";
os << " ir_degrees = [ ";
for(std::size_t i=0;i<wda(workset).ir_degrees->size();i++)
os << (*wda(workset).ir_degrees)[i] << " ";
os << "]\n";
os << " basis_names = [ ";
for(std::size_t i=0;i<wda(workset).basis_names->size();i++)
os << (*wda(workset).basis_names)[i] << " ";
os << "]\n";
/*
os << " int rule = "; wda(workset).int_rules[0]->int_rule->print(os); os << "\n";
os << " basis = "; wda(workset).bases[0]->panzer_basis->print(os); os << "\n";
for(index_t i=0;i<workset.num_cells;i++) {
os << " cell " << i << " vertices =\n";
for(int j=0;j<wda(workset).cell_vertex_coordinates.extent(1);j++) {
os << " ";
for(int k=0;k<wda(workset).cell_vertex_coordinates.extent(2);k++)
os << wda(workset).cell_vertex_coordinates(i,j,k) << " ";
os << "\n";
}
}
os << " integration rule points =\n";
for(int j=0;j<wda(workset).int_rules[0]->cub_points.extent(0);j++) {
os << " ";
for(int k=0;k<wda(workset).int_rules[0]->cub_points.extent(1);k++)
os << wda(workset).int_rules[0]->cub_points(j,k) << " ";
os << "\n";
}
os << " integration weights = [ ";
for(int j=0;j<wda(workset).int_rules[0]->cub_weights.extent(0);j++) {
os << wda(workset).int_rules[0]->cub_weights(j) << " ";
}
os << "]\n";
os << " jac = [ ";
for(int i=0;i<wda(workset).int_rules[0]->jac.size();i++) {
os << wda(workset).int_rules[0]->jac[i] << " ";
}
os << "]\n";
os << " jac_inv = [ ";
for(int i=0;i<wda(workset).int_rules[0]->jac_inv.size();i++) {
os << wda(workset).int_rules[0]->jac_inv[i] << " ";
}
os << "]\n";
os << " jac_det = [ ";
for(int i=0;i<wda(workset).int_rules[0]->jac_det.size();i++) {
os << wda(workset).int_rules[0]->jac_det[i] << " ";
}
os << "]\n";
os << " node_coordinates = [ ";
for(int i=0;i<wda(workset).int_rules[0]->node_coordinates.size();i++) {
os << wda(workset).int_rules[0]->node_coordinates[i] << " ";
}
os << "]\n";
os << " weighted_basis = [ ";
for(int i=0;i<wda(workset).bases[0]->weighted_basis.size();i++)
os << wda(workset).bases[0]->weighted_basis[i] << " ";
os << "]\n";
os << " weighted_grad_basis = [ ";
for(int i=0;i<wda(workset).bases[0]->weighted_grad_basis.size();i++)
os << wda(workset).bases[0]->weighted_grad_basis[i] << " ";
os << "]\n";
os << " basis = [ ";
for(int i=0;i<wda(workset).bases[0]->basis.size();i++)
os << wda(workset).bases[0]->basis[i] << " ";
os << "]\n";
os << " grad_basis = [ ";
for(int i=0;i<wda(workset).bases[0]->grad_basis.size();i++)
os << wda(workset).bases[0]->grad_basis[i] << " ";
os << "]\n";
*/
}
std::vector<std::string>::size_type
getPureBasisIndex(std::string basis_name, const panzer::Workset& workset) {
WorksetDetailsAccessor wda;
return getPureBasisIndex(basis_name, workset, wda);
}
std::vector<std::string>::size_type
getBasisIndex(std::string basis_name, const panzer::Workset& workset) {
WorksetDetailsAccessor wda;
return getBasisIndex(basis_name, workset, wda);
}
std::vector<int>::size_type
getIntegrationRuleIndex(int ir_degree, const panzer::Workset& workset) {
WorksetDetailsAccessor wda;
return getIntegrationRuleIndex(ir_degree, workset, wda);
}
void printWorkset(std::ostream& os, const panzer::Workset & workset) {
WorksetDetailsAccessor wda;
printWorkset(os, workset, wda);
}
}
#endif
| 37.791111
| 106
| 0.605551
|
hillyuan
|
febdf4064217a57acc335f150e4fe6d60fc26ee8
| 957
|
hpp
|
C++
|
include/flatboobs/types.hpp
|
akhilman/flatboobs
|
1bf116d7dbd1bc51b3c98c1c5f968ed6daa62231
|
[
"MIT"
] | null | null | null |
include/flatboobs/types.hpp
|
akhilman/flatboobs
|
1bf116d7dbd1bc51b3c98c1c5f968ed6daa62231
|
[
"MIT"
] | 1
|
2019-04-14T17:47:11.000Z
|
2019-04-17T16:42:41.000Z
|
include/flatboobs/types.hpp
|
akhilman/flatboobs
|
1bf116d7dbd1bc51b3c98c1c5f968ed6daa62231
|
[
"MIT"
] | null | null | null |
#ifndef FLATBOOBS_TYPES_HPP_
#define FLATBOOBS_TYPES_HPP_
#include <flatbuffers/flatbuffers.h>
#include <map>
#include <type_traits>
namespace flatboobs {
using content_id_t = size_t;
using offset_map_t = std::map<flatboobs::content_id_t, flatbuffers::uoffset_t>;
struct BaseStruct {};
struct BaseTable {};
struct BaseVector {};
template <typename T> struct is_struct {
static constexpr bool value = std::is_base_of_v<BaseStruct, T>;
};
template <typename T> inline constexpr bool is_struct_v = is_struct<T>::value;
template <typename T> struct is_table {
static constexpr bool value = std::is_base_of_v<BaseTable, T>;
};
template <typename T> inline constexpr bool is_table_v = is_table<T>::value;
template <typename T> struct is_vector {
static constexpr bool value = std::is_base_of_v<BaseVector, T>;
};
template <typename T> inline constexpr bool is_vector_v = is_vector<T>::value;
} // namespace flatboobs
#endif // FLATBOOBS_TYPES_HPP_
| 27.342857
| 79
| 0.765935
|
akhilman
|
febe01c76be441f4c8d5a789a8a4d0a655af8cca
| 19,531
|
hpp
|
C++
|
include/memory/hadesmem/pelib/pe_file.hpp
|
phlip9/hadesmem
|
59e13a92c05918b8c842141fd5cac1ed390cd79e
|
[
"MIT"
] | 19
|
2017-10-19T23:13:11.000Z
|
2022-03-29T11:37:26.000Z
|
include/memory/hadesmem/pelib/pe_file.hpp
|
namreeb/hadesmem
|
f0a1f0f2c7a00e0c5f085162a09e2a6cb6bb1684
|
[
"MIT"
] | null | null | null |
include/memory/hadesmem/pelib/pe_file.hpp
|
namreeb/hadesmem
|
f0a1f0f2c7a00e0c5f085162a09e2a6cb6bb1684
|
[
"MIT"
] | 10
|
2018-04-04T07:55:16.000Z
|
2021-11-23T20:22:43.000Z
|
// Copyright (C) 2010-2015 Joshua Boyce
// See the file COPYING for copying permission.
#pragma once
#include <cstddef>
#include <cstdint>
#include <iosfwd>
#include <memory>
#include <ostream>
#include <utility>
#include <windows.h>
#include <winnt.h>
#include <hadesmem/config.hpp>
#include <hadesmem/detail/assert.hpp>
#include <hadesmem/detail/region_alloc_size.hpp>
#include <hadesmem/error.hpp>
#include <hadesmem/module.hpp>
#include <hadesmem/process.hpp>
#include <hadesmem/region.hpp>
#include <hadesmem/region_list.hpp>
#include <hadesmem/read.hpp>
// TODO: Add proper regression tests for PeLib. This will require running
// against a known sample set with reference data to compare to.
// TODO: Add better checking to all types that we're not reading outside the
// file/buffer. We usually check the RVA/VA, but we don't always validate the
// size. Also need to check for overflow etc. when using size.
// TODO: Add option to manually map data files, so we can apply fixups etc which
// in turn means we can basically just treat it as an Image in memory. It also
// means we can handle weird loader differences with different mapping flags for
// XP vs 7 vs 8 etc.
// TODO: Investigate what the point of IMAGE_DIRECTORY_ENTRY_IAT is. Used by
// virtsectblXP.exe. Does it actually have to be the IAT (i.e. FirstThunk)? I'm
// pretty sure it's different in some cases... Add warning in Dump for this and
// run a full scan.
// TODO: Decouple PeLib from Process so we can operate directly on
// files/memory/etc. Need some sort of abstraction to replace Process (and the
// accompanying calls to Read/Write/etc.). Dependency on hadesmem APIs in
// general should be removed, as ideally we could make the PeFile code
// OS-independent as all we're doing is parsing files.
// TODO: Move to an attribute based system for warning on malformed or
// suspicious files. Also important for testing, so we can ensure certain
// branches are hit.
// TODO: Return correctly typed pointers from GetBase, GetStart, etc. (Adjust
// ostream overloads to cast to void*).
// TODO: Add noexcept to all functions which are now using cached data and can
// no longer throw.
// TODO: Helper functions such as FindExport, FindImport, HasDataDir,
// GetArchitecture, IsDotNet, GetPDB, etc.
// TODO: Move to 'pelib' namespace.
// TODO: Rewrite PeLib to allow writes from scratch (building new PE file
// sections, data, etc. or even an entire mew PE file). This includes full
// support for writing back to existing PE files also, including automatically
// performing adjustments where required to fit in new data or remove
// unnecessary space.
// TODO: Support more of the PE file format. (Overlay data. Resource directory.
// Exception directory. Relocation directory. Security directory. Debug
// directory. Load config directory. Delay import directory. Bound import
// directory. IAT(as opposed to Import) directory. CLR runtime directory
// support. DOS stub. Rich header. Checksum. etc.)
// TODO: Reduce dependencies various components have on each other (e.g.
// ImportDir depends on TlsDir for detecting AOI trick, BoundImportDir depends
// on ImportDir to ensure that we have imports before accessing bound imports,
// etc.).
// TODO: We should be far more defensive than we are currently being. Validate
// things such as whether offsets are within the file, within the expected data
// dir, higher than an expected address (e.g. NameOffset for bound imports),
// etc.
// TODO: Where possible, document the SHA1 of example files which prompted the
// addition of corner cases, and add them to online repository.
// TODO: Proper overflow checking everywhere.
// TODO: In some cases we're doing checks in list types, in others we're doing
// it in the underlying type. Make this more consistent. Also think about how
// this interacts with the proposed move to an attribute based system.
// TODO: Write and use synthetic files similar to Corkami as part of unit tests.
// One sample per trick/feature/etc.
// TODO: Stop hard-swallowing warnings/errors in PeLib types, they should be
// exposed to the tools (e.g. so Dump can warn). This should probably be fixed
// with the aformentioned attributes suggestion.
namespace hadesmem
{
// TODO: Investigate if there is a better way to implement PeLib rather than
// branching on PeFileType everywhere.
enum class PeFileType
{
kImage,
kData
};
class PeFile
{
public:
explicit PeFile(Process const& process,
void* address,
PeFileType type,
DWORD size)
: process_{&process},
base_{static_cast<std::uint8_t*>(address)},
type_{type},
size_{size}
{
HADESMEM_DETAIL_ASSERT(base_ != 0);
if (type == PeFileType::kData && !size)
{
HADESMEM_DETAIL_THROW_EXCEPTION(Error{}
<< ErrorString{"Invalid file size."});
}
if (type == PeFileType::kImage && !size)
{
try
{
Module const module{process, reinterpret_cast<HMODULE>(address)};
size_ = module.GetSize();
}
catch (...)
{
auto const module_region_size =
detail::GetModuleRegionSize(*process_, base_);
HADESMEM_DETAIL_ASSERT(module_region_size <
(std::numeric_limits<DWORD>::max)());
size_ = static_cast<DWORD>(module_region_size);
}
}
// Not erroring out anywhere here in order to retain back-compat.
// TODO: Do this properly as part of the rewrite.
try
{
if (size_ > sizeof(IMAGE_DOS_HEADER))
{
auto const nt_hdrs_ofs =
Read<IMAGE_DOS_HEADER>(process, address).e_lfanew;
if (size_ >= nt_hdrs_ofs + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER))
{
auto const nt_hdrs = Read<IMAGE_NT_HEADERS>(
process, static_cast<std::uint8_t*>(address) + nt_hdrs_ofs);
if (nt_hdrs.Signature == IMAGE_NT_SIGNATURE &&
nt_hdrs.FileHeader.Machine == IMAGE_FILE_MACHINE_AMD64)
{
is_64_ = true;
}
}
}
}
catch (...)
{
}
}
explicit PeFile(Process const&& process,
void* address,
PeFileType type,
DWORD size) = delete;
PVOID GetBase() const noexcept
{
return base_;
}
PeFileType GetType() const noexcept
{
return type_;
}
DWORD GetSize() const noexcept
{
return size_;
}
bool Is64() const noexcept
{
return is_64_;
}
private:
Process const* process_;
PBYTE base_;
PeFileType type_;
DWORD size_;
bool is_64_{false};
};
inline bool operator==(PeFile const& lhs, PeFile const& rhs) noexcept
{
return lhs.GetBase() == rhs.GetBase();
}
inline bool operator!=(PeFile const& lhs, PeFile const& rhs) noexcept
{
return !(lhs == rhs);
}
inline bool operator<(PeFile const& lhs, PeFile const& rhs) noexcept
{
return lhs.GetBase() < rhs.GetBase();
}
inline bool operator<=(PeFile const& lhs, PeFile const& rhs) noexcept
{
return lhs.GetBase() <= rhs.GetBase();
}
inline bool operator>(PeFile const& lhs, PeFile const& rhs) noexcept
{
return lhs.GetBase() > rhs.GetBase();
}
inline bool operator>=(PeFile const& lhs, PeFile const& rhs) noexcept
{
return lhs.GetBase() >= rhs.GetBase();
}
inline std::ostream& operator<<(std::ostream& lhs, PeFile const& rhs)
{
std::locale const old = lhs.imbue(std::locale::classic());
lhs << static_cast<void*>(rhs.GetBase());
lhs.imbue(old);
return lhs;
}
inline std::wostream& operator<<(std::wostream& lhs, PeFile const& rhs)
{
std::locale const old = lhs.imbue(std::locale::classic());
lhs << static_cast<void*>(rhs.GetBase());
lhs.imbue(old);
return lhs;
}
// TODO: Add sample files for all the corner cases we're handling, and ensure it
// is correct, so we can add regression tests.
// TODO: Find a better name for this functions? It's slightly confusing...
// TODO: Measure code coverage of this and other critical functions when writing
// tests to ensure full coverage. Then add attributes and regression tests.
// TODO: Consider if there is a better way to handle virtual VAs other than an
// out param. Attributes?
inline PVOID RvaToVa(Process const& process,
PeFile const& pe_file,
DWORD rva,
bool* virtual_va = nullptr)
{
if (virtual_va)
{
*virtual_va = false;
}
PeFileType const type = pe_file.GetType();
PBYTE base = static_cast<PBYTE>(pe_file.GetBase());
if (type == PeFileType::kData)
{
if (!rva)
{
return nullptr;
}
IMAGE_DOS_HEADER dos_header = Read<IMAGE_DOS_HEADER>(process, base);
if (dos_header.e_magic != IMAGE_DOS_SIGNATURE)
{
HADESMEM_DETAIL_THROW_EXCEPTION(Error{}
<< ErrorString{"Invalid DOS header."});
}
BYTE* ptr_nt_headers = base + dos_header.e_lfanew;
if (Read<DWORD>(process, ptr_nt_headers) != IMAGE_NT_SIGNATURE)
{
HADESMEM_DETAIL_THROW_EXCEPTION(Error{}
<< ErrorString{"Invalid NT headers."});
}
auto const file_header =
Read<IMAGE_FILE_HEADER>(process, ptr_nt_headers + sizeof(DWORD));
auto const optional_header_32 =
pe_file.Is64()
? IMAGE_OPTIONAL_HEADER32{}
: Read<IMAGE_OPTIONAL_HEADER32>(process,
ptr_nt_headers + sizeof(DWORD) +
sizeof(IMAGE_FILE_HEADER));
auto const optional_header_64 =
pe_file.Is64()
? Read<IMAGE_OPTIONAL_HEADER64>(
process, ptr_nt_headers + sizeof(DWORD) + sizeof(IMAGE_FILE_HEADER))
: IMAGE_OPTIONAL_HEADER64{};
DWORD const size_of_headers = pe_file.Is64()
? optional_header_64.SizeOfHeaders
: optional_header_32.SizeOfHeaders;
DWORD const file_alignment = pe_file.Is64()
? optional_header_64.FileAlignment
: optional_header_32.FileAlignment;
DWORD const size_of_image = pe_file.Is64() ? optional_header_64.SizeOfImage
: optional_header_32.SizeOfImage;
// A PE file can legally have zero sections, in which case the entire file
// is executable as though it were a single section whose size is equal to
// the SizeOfHeaders value rounded up to the nearest page.
// TODO: Confirm that the comment on rounding is correct, then implement it.
WORD num_sections = file_header.NumberOfSections;
if (!num_sections)
{
// In cases where the PE file has no sections it can apparently also have
// all sorts of messed up RVAs for data dirs etc... Make sure that none of
// them lie outside the file, because otherwise simply returning a direct
// offset from the base wouldn't work anyway...
if (rva > pe_file.GetSize())
{
return nullptr;
}
else
{
return base + rva;
}
}
// SizeOfHeaders can be arbitrarily large, including the size of the entire.
// RVAs inside the headers are treated as an offset from zero, rather than
// finding the 'true' location in a section.
if (rva < size_of_headers)
{
// TODO: This probably needs some extra checks as some cases are probably
// invalid, but I don't know what the checks should be. Need to
// investigate to see what is allowed and what is not.
if (rva > pe_file.GetSize() || rva > size_of_image)
{
return nullptr;
}
else
{
return base + rva;
}
}
if (rva > size_of_image)
{
return nullptr;
}
auto ptr_section_header = reinterpret_cast<PIMAGE_SECTION_HEADER>(
ptr_nt_headers + offsetof(IMAGE_NT_HEADERS, OptionalHeader) +
file_header.SizeOfOptionalHeader);
void const* const file_end =
static_cast<std::uint8_t*>(pe_file.GetBase()) + pe_file.GetSize();
// Virtual section table.
if (ptr_section_header >= file_end)
{
if (rva > pe_file.GetSize())
{
return nullptr;
}
else
{
return base + rva;
}
}
bool in_header = true;
for (WORD i = 0; i < num_sections; ++i)
{
// For a virtual section header, simply return nullptr. (Similar to above,
// except this time only the Nth entry onwards is virtual, rather than all
// the headers.)
if (ptr_section_header + 1 > file_end)
{
return nullptr;
}
auto const section_header =
Read<IMAGE_SECTION_HEADER>(process, ptr_section_header);
DWORD const virtual_beg = section_header.VirtualAddress;
DWORD const virtual_size = section_header.Misc.VirtualSize;
DWORD const raw_size = section_header.SizeOfRawData;
// If VirtualSize is zero then SizeOfRawData is used.
DWORD const virtual_end =
virtual_beg + (virtual_size ? virtual_size : raw_size);
if (virtual_beg <= rva && rva < virtual_end)
{
rva -= virtual_beg;
// If the RVA is outside the raw data (which would put it in the
// zero-fill of the virtual data) just return nullptr because it's
// invalid. Technically files like this will work when loaded by the
// PE loader due to the sections being mapped differention in memory
// to on disk, but if you want to inspect the file in that manner you
// should just use LoadLibrary with the appropriate flags for your
// scenario and then use PeFileType::kImage.
if (rva > raw_size)
{
// It's useful to be able to detect this case as a user for things
// like exports, where typically a failure to resolve an RVA would be
// an error/suspicious, but not in the case of a data export where it
// is normal for the RVA to be in the zero fill of a data segment.
// TODO: Find other places in this function where we need to set this
// flag.
// TODO: Also check section characteristics?
if (rva < virtual_size && virtual_va)
{
*virtual_va = true;
}
return nullptr;
}
// If PointerToRawData is less than 0x200 it is rounded
// down to 0.
if (section_header.PointerToRawData >= 0x200)
{
// TODO: Check whether we actually need/want to force alignment here.
rva += section_header.PointerToRawData & ~(file_alignment - 1);
}
// If the RVA now lies outside the actual file just return nullptr
// because it's invalid.
if (rva >= pe_file.GetSize())
{
return nullptr;
}
return base + rva;
}
// This should be the 'normal' case. However sometimes the RVA is at a
// lower address than any of the sections, so we want to detect this so we
// can just treat the RVA as an offset from the module base (similar to
// when the image is loaded).
if (virtual_beg <= rva)
{
in_header = false;
}
++ptr_section_header;
}
// Doing the same thing as in the SizeOfHeaders check above because we're
// not sure of better criteria to base it off. Perhaps it's correct now?
if (in_header && rva < pe_file.GetSize())
{
// Only applies in low alignment, otherwise it's invalid?
if (file_alignment < 200)
{
return base + rva;
}
// Also only applies if the RVA is smaller than file alignment?
else if (rva < file_alignment)
{
return base + rva;
}
else
{
return nullptr;
}
}
// Sample: nullSOH-XP (Corkami PE Corpus)
if (rva < size_of_image && rva < pe_file.GetSize())
{
return base + rva;
}
return nullptr;
}
else if (type == PeFileType::kImage)
{
return rva ? (base + rva) : nullptr;
}
else
{
HADESMEM_DETAIL_THROW_EXCEPTION(Error{}
<< ErrorString{"Unhandled file type."});
}
}
// TODO: 'Harden' this function against malicious/malformed PE files like is
// done for RvaToVa.
inline DWORD FileOffsetToRva(Process const& process,
PeFile const& pe_file,
DWORD file_offset)
{
PeFileType const type = pe_file.GetType();
PBYTE base = static_cast<PBYTE>(pe_file.GetBase());
if (type == PeFileType::kData)
{
IMAGE_DOS_HEADER dos_header = Read<IMAGE_DOS_HEADER>(process, base);
if (dos_header.e_magic != IMAGE_DOS_SIGNATURE)
{
HADESMEM_DETAIL_THROW_EXCEPTION(Error{}
<< ErrorString{"Invalid DOS header."});
}
BYTE* ptr_nt_headers = base + dos_header.e_lfanew;
if (Read<DWORD>(process, ptr_nt_headers) != IMAGE_NT_SIGNATURE)
{
HADESMEM_DETAIL_THROW_EXCEPTION(Error{}
<< ErrorString{"Invalid NT headers."});
}
auto const file_header =
Read<IMAGE_FILE_HEADER>(process, ptr_nt_headers + sizeof(DWORD));
auto ptr_section_header = reinterpret_cast<PIMAGE_SECTION_HEADER>(
ptr_nt_headers + offsetof(IMAGE_NT_HEADERS, OptionalHeader) +
file_header.SizeOfOptionalHeader);
WORD num_sections = file_header.NumberOfSections;
for (WORD i = 0; i < num_sections; ++i)
{
auto const section_header =
Read<IMAGE_SECTION_HEADER>(process, ptr_section_header);
DWORD const raw_beg = section_header.PointerToRawData;
DWORD const raw_size = section_header.SizeOfRawData;
DWORD const raw_end = raw_beg + raw_size;
if (raw_beg <= file_offset && file_offset < raw_end)
{
file_offset -= raw_beg;
file_offset += section_header.VirtualAddress;
return file_offset;
}
++ptr_section_header;
}
return 0;
}
else if (type == PeFileType::kImage)
{
return file_offset;
}
else
{
HADESMEM_DETAIL_THROW_EXCEPTION(Error{}
<< ErrorString{"Unhandled file type."});
}
}
namespace detail
{
// TODO: Handle virtual termination.
// TODO: Warn in tools when EOF/Virtual/etc. termination is detected.
// TODO: Move this somewhere more appropriate.
template <typename CharT>
std::basic_string<CharT> CheckedReadString(Process const& process,
PeFile const& pe_file,
void* address)
{
if (pe_file.GetType() == PeFileType::kImage)
{
// TODO: Extra bounds checking to ensure we don't read outside the image in
// the case that we're reading a string at the end of the file which is not
// null terminated, and we're on a region boundary.
return ReadString<CharT>(process, address);
}
else if (pe_file.GetType() == PeFileType::kData)
{
void* const file_end =
static_cast<std::uint8_t*>(pe_file.GetBase()) + pe_file.GetSize();
if (address >= file_end)
{
HADESMEM_DETAIL_THROW_EXCEPTION(Error{} << ErrorString{"Invalid VA."});
}
// Handle EOF termination.
// Sample: maxsecXP.exe (Corkami PE Corpus)
return ReadStringBounded<CharT>(process, address, file_end);
}
else
{
HADESMEM_DETAIL_ASSERT(false);
HADESMEM_DETAIL_THROW_EXCEPTION(Error{}
<< ErrorString{"Unknown PE file type."});
}
}
}
}
| 32.660535
| 80
| 0.644002
|
phlip9
|
febed95a96c85ab196036847ce07a8466f010626
| 2,521
|
hpp
|
C++
|
gamelib/gamelib_physics_component.hpp
|
scifi6546/game
|
27d79976ba879263147cbf36e520c72c80f0461d
|
[
"MIT"
] | null | null | null |
gamelib/gamelib_physics_component.hpp
|
scifi6546/game
|
27d79976ba879263147cbf36e520c72c80f0461d
|
[
"MIT"
] | null | null | null |
gamelib/gamelib_physics_component.hpp
|
scifi6546/game
|
27d79976ba879263147cbf36e520c72c80f0461d
|
[
"MIT"
] | null | null | null |
#ifndef GAMELIB_PHYSICS_COMPONENT_HPP
#define GAMELIB_PHYSICS_COMPONENT_HPP
#include <gamelib_actor.hpp>
#include <gamelib_world.hpp>
namespace GameLib {
class PhysicsComponent {
public:
virtual ~PhysicsComponent() {}
// handles needed initialization before play begins
virtual void beginPlay(Actor& actor) {}
// handles update of actor in the physics engine before update
virtual void preupdate(Actor& actor) {}
// handles update of actor after physics engine
virtual void postupdate(Actor& actor) {}
// handles updates of position, velocity, and acceleration
virtual void update(Actor& actor, World& world) {}
// handles collisions between world and actor
virtual bool collideWorld(Actor& actor, World& world) { return false; }
// handles collision between movable actors
virtual bool collideDynamic(Actor& a, Actor& b) { return false; }
// handles collision between movable actor and static actor
virtual bool collideStatic(Actor& a, Actor& b) { return false; }
// handles collision between movable actor and trigger
virtual bool collideTrigger(Actor& a, Actor& b) { return false; }
};
class SimplePhysicsComponent : public PhysicsComponent {
public:
virtual ~SimplePhysicsComponent() {}
void beginPlay(Actor& actor) override;
void postupdate(Actor& a) override;
void preupdate(Actor& a) override;
void update(Actor& a, World& w) override;
bool collideWorld(Actor& a, World& w) override;
bool collideDynamic(Actor& a, Actor& b) override;
bool collideStatic(Actor& a, Actor& b) override;
bool collideTrigger(Actor& a, Actor& b) override;
};
class TraceCurtisDynamicActorComponent : public PhysicsComponent {
public:
~TraceCurtisDynamicActorComponent(){};
bool collideDynamic(Actor& a, Actor& b) override;
void update(Actor& a, World& w) override;
};
class DainNickJosephWorldPhysicsComponent : public PhysicsComponent {
public:
~DainNickJosephWorldPhysicsComponent(){};
bool collideWorld(Actor& actor, World& world) override;
void update(Actor& a, World& w) override;
};
class TailonsDynamicPhysicsComponent : public PhysicsComponent {
public:
~TailonsDynamicPhysicsComponent(){};
bool collideDynamic(Actor& a, Actor& b) override;
void update(Actor& a, World& w) override;
};
class TailonsStaticPhysicsComponent : public PhysicsComponent {
public:
~TailonsStaticPhysicsComponent(){};
bool collideStatic(Actor& a, Actor& b) override;
void update(Actor& a, World& w) override;
};
} // namespace GameLib
#endif
| 31.123457
| 73
| 0.746926
|
scifi6546
|
febffc789b4d3409c18920173f117cb8985bfbb2
| 2,621
|
cpp
|
C++
|
BFS/Food Cubes/FoodCubes.cpp
|
Sean16SYSU/Algorithms4N
|
24f06c29d476c4bd9c90bcc89dac90ba3a448c27
|
[
"MIT"
] | 2
|
2019-09-30T01:26:41.000Z
|
2019-10-02T01:36:34.000Z
|
BFS/Food Cubes/FoodCubes.cpp
|
Sean16SYSU/Algorithms4N
|
24f06c29d476c4bd9c90bcc89dac90ba3a448c27
|
[
"MIT"
] | null | null | null |
BFS/Food Cubes/FoodCubes.cpp
|
Sean16SYSU/Algorithms4N
|
24f06c29d476c4bd9c90bcc89dac90ba3a448c27
|
[
"MIT"
] | 3
|
2020-05-18T15:09:01.000Z
|
2020-12-21T10:14:51.000Z
|
#include <iostream>
using namespace std;
#include <queue>
#include <cstring>
#include <algorithm>
#define INF 1 << 30
#define MINF 1 << 31
bool map[103][103][103]; // true 表示是障碍,否则就不是障碍
bool visited[103][103][103]; // true表示访问过
int ans;
struct Node
{
int x, y, z;
Node(int a = 0, int b = 0, int c = 0) : x(a), y(b), z(c){};
};
int op[][6] = {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}};
int main()
{
int t, time, x, y, z, a, b, c, maxx, minx, maxy, miny, maxz, minz;
bool wrong;
cin >> t;
while (t--)
{
cin >> time;
memset(map, false, sizeof(map));
memset(visited, false, sizeof(visited));
ans = 0;
maxx = maxy = maxz = MINF;
minx = miny = minz = INF;
while (time--)
{
cin >> x >> y >> z;
map[x][y][z] = true; //设置障碍
maxx = max(x, maxx);
maxy = max(y, maxy);
maxz = max(z, maxz);
minx = min(x, minx);
miny = min(y, miny);
minz = min(z, minz);
}
for (x = minx; x <= maxx; ++x)
for (y = miny; y <= maxy; ++y)
for (z = minz; z <= maxz; ++z)
{
if (!map[x][y][z] && !visited[x][y][z])
{
queue<Node> q;
q.push(Node(x, y, z));
wrong = false;
visited[x][y][z] = true;
while (!q.empty())
{
Node now = q.front();
q.pop();
for (int i = 0; i < 6; ++i)
{
a = now.x + op[i][0];
b = now.y + op[i][1];
c = now.z + op[i][2];
if (a < minx || b < miny || c < minz || a > maxx || b > maxy || c > maxz)
{
wrong = true;
}
else if (!map[a][b][c] && !visited[a][b][c])
{
q.push(Node(a, b, c));
visited[a][b][c] = true;
}
}
}
if (!wrong)
{
ans++;
}
}
}
cout << ans << endl;
}
}
| 33.177215
| 105
| 0.295307
|
Sean16SYSU
|
fec139e8d540cf55b7f1fe580b500512300380b4
| 937
|
hpp
|
C++
|
gearoenix/render/pipeline/gx-rnd-pip-unlit-resource-set.hpp
|
Hossein-Noroozpour/gearoenix
|
c8fa8b8946c03c013dad568d6d7a97d81097c051
|
[
"BSD-Source-Code"
] | 35
|
2018-01-07T02:34:38.000Z
|
2022-02-09T05:19:03.000Z
|
gearoenix/render/pipeline/gx-rnd-pip-unlit-resource-set.hpp
|
Hossein-Noroozpour/gearoenix
|
c8fa8b8946c03c013dad568d6d7a97d81097c051
|
[
"BSD-Source-Code"
] | 111
|
2017-09-20T09:12:36.000Z
|
2020-12-27T12:52:03.000Z
|
gearoenix/render/pipeline/gx-rnd-pip-unlit-resource-set.hpp
|
Hossein-Noroozpour/gearoenix
|
c8fa8b8946c03c013dad568d6d7a97d81097c051
|
[
"BSD-Source-Code"
] | 5
|
2020-02-11T11:17:37.000Z
|
2021-01-08T17:55:43.000Z
|
#ifndef GEAROENIX_RENDER_PIPELINE_UNLIT_RESOURCE_SET_HPP
#define GEAROENIX_RENDER_PIPELINE_UNLIT_RESOURCE_SET_HPP
#include "../../core/gx-cr-build-configuration.hpp"
#include "gx-rnd-pip-resource-set.hpp"
namespace gearoenix::render::pipeline {
class Unlit;
class UnlitResourceSet : public ResourceSet {
protected:
/// It is not owner of any of these pointers
const buffer::Uniform* material_uniform_buffer = nullptr;
const buffer::Uniform* node_uniform_buffer = nullptr;
const mesh::Mesh* msh = nullptr;
const texture::Texture2D* color = nullptr;
explicit UnlitResourceSet(std::shared_ptr<Unlit const> pip) noexcept;
public:
~UnlitResourceSet() noexcept override;
void set_material(const material::Material* m) noexcept;
void set_mesh(const mesh::Mesh* m) noexcept;
void set_node_uniform_buffer(buffer::Uniform* node_uniform_buffer) noexcept;
void clean() noexcept override;
};
}
#endif
| 32.310345
| 80
| 0.763074
|
Hossein-Noroozpour
|
fec1658be242f868f880112605401c48d25d15c9
| 3,506
|
hh
|
C++
|
inc/stb_model.hh
|
stbd/stoolbox
|
4535e1df2795cb0157420e7d4b1a01f3bda441da
|
[
"MIT"
] | null | null | null |
inc/stb_model.hh
|
stbd/stoolbox
|
4535e1df2795cb0157420e7d4b1a01f3bda441da
|
[
"MIT"
] | null | null | null |
inc/stb_model.hh
|
stbd/stoolbox
|
4535e1df2795cb0157420e7d4b1a01f3bda441da
|
[
"MIT"
] | null | null | null |
#ifndef STB_GL_MODEL_HH_
#define STB_GL_MODEL_HH_
#include "stb_types.hh"
#include <string>
#include <vector>
#include <boost/ref.hpp>
#include <memory>
#include <cstdio>
namespace stb
{
class ModelData
{
public:
enum AttributeDataMode { TRIANGLE, TRIANGE_STRIP };
enum AttributeBufferDataType { FLOAT, UINT32 };
typedef std::vector<size_t> ValuesPerAttributeContainer;
struct AttributeData
{
AttributeData(const char * attrBufferData,
const size_t attrBufferDataSize,
const ValuesPerAttributeContainer & valuesPerAttr,
const size_t sizeOfAttrElement,
const AttributeBufferDataType attrDataType)
: m_attributeData(attrBufferData, attrBufferDataSize),
m_valuesPerAttribute(valuesPerAttr),
m_sizeOfAttributeElement(sizeOfAttrElement),
m_dataType(attrDataType)
{}
std::string m_attributeData;
ValuesPerAttributeContainer m_valuesPerAttribute;
size_t m_sizeOfAttributeElement;
AttributeBufferDataType m_dataType;
};
typedef std::shared_ptr<const AttributeData> AttributeElement;
typedef std::vector<AttributeElement> AttributeElementContainer;
ModelData(AttributeElementContainer attrDataBuffers,
const char * indicesBuffer,
const size_t indicesBufferSize,
const size_t indiceElementSize,
const AttributeDataMode modeOfAttrData
);
ModelData(const ModelData & other);
ModelData();
size_t numberOfAttrBuffers() const { return m_attrDataBuffers.size(); }
const char * attrBuffer(const size_t attributeBufferIndex) const;
size_t attrBufferSize(const size_t attributeBufferIndex) const;
size_t attrBufferSizeOfElement(const size_t attributeBufferIndex) const;
size_t numberOfAttrInBuffer(const size_t attributeBufferIndex) const;
AttributeBufferDataType attrBufferDataType(const size_t attributeBufferIndex) const;
size_t valuesPerAttribute(const size_t attributeBufferIndex, const size_t attrIndex) const;
size_t numberOfAttributes() const { return m_numberAttributes; }
size_t pointerToDataInBuffer(const size_t attributeBufferIndex, const size_t attrIndex) const;
size_t indicesDataSize(void) const { return m_indicesBuffer.size(); }
const char * indicesData(void) const { return m_indicesBuffer.c_str(); }
size_t sizeOfIndiceElement(void) const { return m_indiceElementSize; }
AttributeDataMode attributeDataMode(void) const { return m_modeOfAttributeData; }
bool valid() const {
return (m_numberAttributes != 0)
&& (m_indiceElementSize != 0)
;
}
private:
AttributeElementContainer m_attrDataBuffers;
U32 m_numberAttributes;
const std::string m_indicesBuffer;
const size_t m_indiceElementSize;
const AttributeDataMode m_modeOfAttributeData;
// Prevent heap allocation
void * operator new (size_t);
void * operator new[](size_t);
void operator delete (void *);
void operator delete[](void*);
void operator = (const ModelData & /*other*/) {}
};
ModelData readModel(const char * buffer, const size_t size);
void dumpModel(const stb::ModelData & model, FILE * stream);
}
#endif
| 36.14433
| 102
| 0.676554
|
stbd
|
feca807a84de2b3f2c4b0b24dc78ac07da04dbf5
| 314
|
cpp
|
C++
|
LilEngie/Core/src/Entity/Components/PointLight.cpp
|
Nordaj/LilEngie
|
453cee13c45ae33abe2665e1446fc90e67b1117a
|
[
"MIT"
] | null | null | null |
LilEngie/Core/src/Entity/Components/PointLight.cpp
|
Nordaj/LilEngie
|
453cee13c45ae33abe2665e1446fc90e67b1117a
|
[
"MIT"
] | null | null | null |
LilEngie/Core/src/Entity/Components/PointLight.cpp
|
Nordaj/LilEngie
|
453cee13c45ae33abe2665e1446fc90e67b1117a
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <glm/glm.hpp>
#include <Entity/GameObject.h>
#include <Entity/Component.h>
#include <Graphics/LightHandler.h>
#include "PointLight.h"
PointLight::PointLight(GameObject *obj)
:Component(obj)
{ }
void PointLight::Start()
{
//Add to lightmanager
LightHandler::AddPointLight(this);
}
| 18.470588
| 39
| 0.745223
|
Nordaj
|
fecb6b1dfa14901f5f477bc3772ba064d5782ebc
| 322
|
cpp
|
C++
|
Source/Sample/Sample2/TransformObject.cpp
|
MasyoLab/Directx9-Framework
|
b7525865744b64a7c10078656cfb086a1276c819
|
[
"MIT"
] | null | null | null |
Source/Sample/Sample2/TransformObject.cpp
|
MasyoLab/Directx9-Framework
|
b7525865744b64a7c10078656cfb086a1276c819
|
[
"MIT"
] | null | null | null |
Source/Sample/Sample2/TransformObject.cpp
|
MasyoLab/Directx9-Framework
|
b7525865744b64a7c10078656cfb086a1276c819
|
[
"MIT"
] | null | null | null |
#include "TransformObject.h"
TransformObject::TransformObject()
{
SetComponentName("TransformObject");
}
TransformObject::~TransformObject()
{
}
void TransformObject::Update()
{
}
void TransformObject::UpdateMatrix()
{
CreateWorldMatrix();
}
void TransformObject::GUISystem()
{
GUIGameObject();
GUITransform();
}
| 12.384615
| 37
| 0.745342
|
MasyoLab
|
feceb1ac6da166ac7be7ce6a2a87e8ab7722e9b2
| 5,149
|
cpp
|
C++
|
Planning/waypoint_generator/src/ROI_publisher.cpp
|
acr-iitkgp/swarm_search
|
3857edde0238c2f5d83a33c8969e6e3e3b9a3dcf
|
[
"MIT"
] | 6
|
2020-01-07T15:45:14.000Z
|
2021-06-19T12:14:20.000Z
|
Planning/waypoint_generator/src/ROI_publisher.cpp
|
manthan99/swarm_search
|
3857edde0238c2f5d83a33c8969e6e3e3b9a3dcf
|
[
"MIT"
] | null | null | null |
Planning/waypoint_generator/src/ROI_publisher.cpp
|
manthan99/swarm_search
|
3857edde0238c2f5d83a33c8969e6e3e3b9a3dcf
|
[
"MIT"
] | 3
|
2020-04-21T06:29:26.000Z
|
2020-11-23T05:39:41.000Z
|
#include <cmath>
#include "ros/ros.h"
#include <math.h>
#include "geodetic_conv.hpp"
#include "sensor_msgs/NavSatFix.h"
#include "geometry_msgs/Point.h"
#include <geometry_msgs/Twist.h>
#include "waypoint_generator/point_list.h"
#include "geometry_msgs/PoseStamped.h"
#include <std_msgs/Float64.h>
// #define M_PI 3.14159
using namespace std;
using namespace ros;
// nav_msgs::Path path;
bool waypoint_reached = true;
double height = 0;
double FOV = 2*M_PI/3; // define in radians
double resolution_y = 1280; // image cols
double resolution_x = 720; // image rows
bool GPS_received, heading_received, height_received, frameToGPS;
geometry_msgs::PoseStamped current_pos;
std::map < pair<double, double>, vector<pair<double, double> > > ROI_list;
// GPS coordinate received
double lat, lon, alt;
void globalCallback(const sensor_msgs::NavSatFix::ConstPtr& msg)
{
// if(!GPS_received)
lat=msg->latitude;
lon=msg->longitude;
alt=msg->altitude;
// cout<<"GPS received: "<<lat<<" "<<lon<<" "<<alt<<endl;
}
// heading angle received
double heading_angle = 0.0;
void orientCallback(const std_msgs::Float64::ConstPtr& msg)
{
heading_angle = msg->data * M_PI/180.0;
// cout<<"Heading received: "<<heading_angle<<endl;
}
// height callback
void localposcallback(const geometry_msgs::PoseStamped::ConstPtr& position)
{
current_pos = *position;
height = current_pos.pose.position.z;
// cout<<"Height received: "<<height<<endl;
}
// input is list of frame points
// converting that to distance in m
// finding cosine in direction of N and E
// using N and E to find
waypoint_generator::point_list frame_points_gps;
void framePointCallback(const waypoint_generator::point_list::ConstPtr& frame_points)
{
geodetic_converter::GeodeticConverter conv;
conv.initialiseReference(lat,lon,alt);
// cout<<"length_per_pixel: "<<length_per_pixel<<endl;
double alpha = 0;
double lat_temp, lon_temp, alt_temp;
double distance_N, distance_E, distance;
double length_per_pixel = 2*height*tan(FOV/2)/resolution_y;
geometry_msgs::Point temp_point;
for (int i=0; i<frame_points->points.size(); i++)
{
distance = length_per_pixel*sqrt(pow(frame_points->points[i].x-resolution_x/2, 2)+(frame_points->points[i].y-resolution_y/2, 2));
// cout<<"distance: "<<distance<<endl;
if((frame_points->points[i].x-resolution_x/2)!= 0)
alpha = atan((frame_points->points[i].y-resolution_y/2)/(frame_points->points[i].x-resolution_x/2));
else if((frame_points->points[i].y-resolution_y/2)>0)
alpha = M_PI/2;
else if((frame_points->points[i].y-resolution_y/2)<0 )
alpha = -M_PI/2;
else alpha = 0;
// cout<<"α: "<<alpha<<endl;
if (frame_points->points[i].x-resolution_x/2 < 0)
distance *= (-1);
distance_E = distance*sin(M_PI-alpha+heading_angle);
distance_N = distance*cos(M_PI-alpha+heading_angle);
// cout<<distance_N<<" "<<distance_E<<endl;
conv.enu2Geodetic(distance_E, distance_N, 0, &lat_temp, &lon_temp, &alt_temp);
temp_point.x = lat_temp;
temp_point.y = lon_temp;
// cout << std::fixed << std::setprecision(8)<< "Lat: "<<lat_temp<<" Lon: "<<lon_temp<<endl;
frame_points_gps.points.push_back(temp_point);
}
double scale = 0.00001;
for (int i=0; i<frame_points_gps.points.size(); i++)
{
double lat = frame_points_gps.points[i].x;
double lon = frame_points_gps.points[i].y;
double lat_scaled = (int)(lat/scale) * scale;
double lon_scaled = (int)(lon/scale) * scale;
ROI_list[{lat_scaled, lon_scaled}].push_back({lat, lon});
}
}
ros::Publisher waypoint_pub;
void statusCallback(const geometry_msgs::Twist::ConstPtr& data)
{
if (data->linear.y == 1)
{
waypoint_generator::point_list final_target_points_gps;
for (auto i=ROI_list.begin(); i!=ROI_list.end(); i++)
{
geometry_msgs::Point temp;
double lat_final=0, lon_final=0;
for (int j=0; j<i->second.size(); j++)
{
lat_final += i->second[j].first;
lon_final += i->second[j].second;
}
lat_final /= i->second.size();
lon_final /= i->second.size();
temp.y = lon_final;
temp.x = lat_final;
final_target_points_gps.points.push_back(temp);
// cout<<"Final points: "<< std::fixed << std::setprecision(8)<<temp.x<<" "<<temp.y<<endl;
}
waypoint_pub.publish(final_target_points_gps);
}
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "ROI_publisher");
ros::NodeHandle n;
ros::Subscriber frame_point_sub = n.subscribe("/drone1/some_topic", 1000, framePointCallback);
ros::Subscriber gps_sub = n.subscribe("/drone1/mavros/global_position/global", 10, globalCallback);
ros::Subscriber current_position = n.subscribe("/drone1/mavros/local_position/pose",10, localposcallback);
ros::Subscriber heading_sub = n.subscribe("/drone1/mavros/global_position/compass_hdg", 1000, orientCallback);
ros::Subscriber status_sub = n.subscribe("/drone1/flags", 1000, statusCallback);
waypoint_pub = n.advertise<waypoint_generator::point_list>("/drone1/ROI_flow", 1000);
ros::Rate loop_rate(20);
while( ros::ok )
{
ros::spinOnce();
loop_rate.sleep();
}
return 0;
}
// input: M_PIxel_points, drone_gps, theta, height, image_resolution(x,y)
| 31.206061
| 131
| 0.707322
|
acr-iitkgp
|
fecf8281fde3a86854821e28b53de5f20bea0084
| 60,415
|
cxx
|
C++
|
PWGCF/EBYE/NetLambda/AliAnalysisTaskNetLambdaIdent.cxx
|
vfilova/AliPhysics
|
2ec91e234e5601e855daf3e58ef90a1eaae2f413
|
[
"BSD-3-Clause"
] | 1
|
2021-06-11T20:36:16.000Z
|
2021-06-11T20:36:16.000Z
|
PWGCF/EBYE/NetLambda/AliAnalysisTaskNetLambdaIdent.cxx
|
vfilova/AliPhysics
|
2ec91e234e5601e855daf3e58ef90a1eaae2f413
|
[
"BSD-3-Clause"
] | 1
|
2017-03-14T15:11:43.000Z
|
2017-03-14T15:53:09.000Z
|
PWGCF/EBYE/NetLambda/AliAnalysisTaskNetLambdaIdent.cxx
|
vfilova/AliPhysics
|
2ec91e234e5601e855daf3e58ef90a1eaae2f413
|
[
"BSD-3-Clause"
] | null | null | null |
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
// Analysis task for net-lambda fluctuations analysis
// Author: Alice Ohlson (alice.ohlson@cern.ch)
// aliroot
#include "AliAnalysisManager.h"
#include "AliInputEventHandler.h"
#include "AliESDEvent.h"
#include "AliAODEvent.h"
#include "AliMCEvent.h"
#include "AliAODTrack.h"
#include "AliESDtrack.h"
#include "AliExternalTrackParam.h"
#include "AliAnalysisFilter.h"
#include "AliVMultiplicity.h"
#include "AliAnalysisUtils.h"
#include "AliAODMCParticle.h"
#include "AliStack.h"
#include "AliPIDResponse.h"
#include "AliMCEventHandler.h"
#include "AliV0vertexer.h"
#include "AliESDv0Cuts.h"
#include "AliMultSelection.h"
#include "AliEventPoolManager.h"
// root
#include "TMath.h"
#include "TFile.h"
#include "TList.h"
#include "TChain.h"
#include "TTree.h"
#include "TH1.h"
#include "TH2.h"
#include "TH3.h"
#include "TH3F.h"
//#include "AliNetLambdaHelper.h"
#include "AliAnalysisTaskNetLambdaIdent.h"
ClassImp(AliAnalysisTaskNetLambdaIdent)
//-----------------------------------------------------------------------------
AliAnalysisTaskNetLambdaIdent::AliAnalysisTaskNetLambdaIdent(const char* name) :
AliAnalysisTaskSE(name),
fESD(0x0),
fAOD(0x0),
stack(0x0),
fPIDResponse(0x0),
fEventCuts(0),
fListOfHistos(0x0),
fTree(0x0),
hEventStatistics(0x0),
fPoolMgr(0x0),
hGenPt(0x0),
hGenPhi(0x0),
hGenEta(0x0),
hTrackPt(0x0),
hTrackPhi(0x0),
hTrackEta(0x0),
hNTracksEsd(0x0),
hNSigmaProton(0x0),
hArmPod(0x0),
hVxVy(0x0),
hLambdaPtGen(0x0),
hAntiLambdaPtGen(0x0),
hLambdaPtReco(0x0),
hAntiLambdaPtReco(0x0),
hInvMassLambda(0x0),
hInvMassAntiLambda(0x0),
hInvMassLambdaOnTheFly(0x0),
hInvMassAntiLambdaOnTheFly(0x0),
hInvMassLambdaReco(0x0),
hInvMassAntiLambdaReco(0x0),
hInvMassLambdaSecFromMaterial(0x0),
hInvMassAntiLambdaSecFromMaterial(0x0),
hInvMassLambdaSecFromWeakDecay(0x0),
hInvMassAntiLambdaSecFromWeakDecay(0x0),
hInvMassLike(0x0),
hInvMassLambdaK0S(0x0),
hInvMassAntiLambdaK0S(0x0),
hInvMassLambdaConversions(0x0),
hInvMassAntiLambdaConversions(0x0),
//hInvMassPtPidLambda(0x0),
//hInvMassPtPidAntiLambda(0x0),
hXiPlus(0x0),
hXiMinus(0x0),
hXiZero(0x0),
hXiZeroAnti(0x0),
hInvMassLambdaMPidPt(0x0),
hInvMassAntiLambdaMPidPt(0x0),
hPtResLambda(0x0),
hPtResAntiLambda(0x0),
hPtResLambdaPrim(0x0),
hPtResAntiLambdaPrim(0x0),
centcut(80.),
ptminlambda(0.5),
etacutlambda(0.8),
ncrossedrowscut(70),
crossedrowsclustercut(0.8),
fCentV0M(-1),
fCentCL1(-1),
fMultV0M(-1),
fNtracksTPCout(-1),
fVtxZ(-20),
fRunNumber(-1),
fAcceptV0(0x0),
//fAcceptV0test(0x0),
fGenLambda(0x0),
fGenCascade(0x0),
fMixV0(0x0),
fIsMC(kFALSE),
fIsAOD(kTRUE),
fEvSel(AliVEvent::kINT7),
fLambdaTree(kTRUE),
fEventMixingTree(kFALSE),
fRevertex(kFALSE),
nmaxmixtracks(1000),
nmaxmixevents(5),
pidVals(0x0),
fChi2max(33.), //max chi2
fDmin(0.1),//0.05; //min imp parameter for the 1st daughter
fDCAmax(1.),//1.5; //max DCA between the daughter tracks
fCPAmin(0.998),//0.9; //min cosine of V0's pointing angle
fRmin(0.9), //min radius of the fiducial volume
fRmax(100)//200.; //max radius of the fiducial volume
{
Info("AliAnalysisTaskNetLambdaIdent","Calling Constructor");
//fEventCuts.fUseVariablesCorrelationCuts = true;
//fEventCuts.fUseStrongVarCorrelationCut = true;
DefineInput(0,TChain::Class());
DefineOutput(1,TList::Class());
DefineOutput(2,TTree::Class());
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void AliAnalysisTaskNetLambdaIdent::UserCreateOutputObjects(){
fListOfHistos = new TList();
fListOfHistos->SetOwner();
hEventStatistics = new TH1I("hEventStatistics","",20,0,20);
//hEventStatistics->SetBit(TH1::kCanRebin);
fListOfHistos->Add(hEventStatistics);
Int_t ncentbinspool = 10;
//Double_t centbinspool[11] = {0,100,200,400,600,1000,2000,3000,4000,5000,100000};
Double_t centbinspool[11] = {0,5,10,20,30,40,50,60,70,80,90};
//Int_t nzvtxbinspool = 2;
//Double_t zvtxbinspool[3] = {-10,0,10};
Int_t nzvtxbinspool = 20;
Double_t zvtxbinspool[21] = {-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10};
//Int_t nzvtxbinspool = 100;
//Double_t zvtxbinspool[101];
//for(Int_t i = 0; i < 100; i++) zvtxbinspool[i] = -10.+0.2*i;
//zvtxbinspool[100] = 10.;
fPoolMgr = new AliEventPoolManager(nmaxmixevents,nmaxmixtracks, ncentbinspool, centbinspool, nzvtxbinspool, zvtxbinspool);
fPoolMgr->SetTargetValues(nmaxmixtracks, 0.1, 2);
// single-track QA plots
hTrackPt = new TH1F("hTrackPt","track p_{T};p_{T} (GeV/c);",100,0,10);
fListOfHistos->Add(hTrackPt);
hTrackPhi = new TH1F("hTrackPhi","track #varphi;#varphi;",100,0,2*TMath::Pi());
fListOfHistos->Add(hTrackPhi);
hTrackEta = new TH1F("hTrackEta","track #eta;#eta;",100,-0.8,0.8);
fListOfHistos->Add(hTrackEta);
hGenPt = new TH1F("hGenPt","generated p_{T};p_{T} (GeV/c);",100,0,10);
fListOfHistos->Add(hGenPt);
hGenPhi = new TH1F("hGenPhi","generated #varphi;#varphi;",100,0,2*TMath::Pi());
fListOfHistos->Add(hGenPhi);
hGenEta = new TH1F("hGenEta","generated #eta;#eta;",100,-0.8,0.8);
fListOfHistos->Add(hGenEta);
hNTracksEsd = new TH1F("hNTracksEsd","number of tracks for event mixing",300,0,9000);
fListOfHistos->Add(hNTracksEsd);
hVxVy = new TH2F("hVxVy","vx vs vy;v_{x};v_{y}",50,0.073,0.083,50,0.331,0.341);
fListOfHistos->Add(hVxVy);
// PID QA
hNSigmaProton = new TH2F("hNSigmaProton","n#sigma for protons;p_{T};n#sigma",100,-10,10,100,-10,10);
fListOfHistos->Add(hNSigmaProton);
hArmPod = new TH2F("hArmPod","Armenteros-Podolanski plot;#alpha;p_{T}",100,-1,1,100,0,0.25);
fListOfHistos->Add(hArmPod);
// lambda reco plots
hLambdaPtGen = new TH1F("hLambdaPtGen","generated #Lambda p_{T}",100,0,10);
fListOfHistos->Add(hLambdaPtGen);
hAntiLambdaPtGen = new TH1F("hAntiLambdaPtGen","generated #bar{#Lambda} p_{T}",100,0,10);
fListOfHistos->Add(hAntiLambdaPtGen);
hLambdaPtReco = new TH1F("hLambdaPtReco","reconstructed #Lambda p_{T}",100,0,10);
fListOfHistos->Add(hLambdaPtReco);
hAntiLambdaPtReco = new TH1F("hAntiLambdaPtReco","reconstructed #bar{#Lambda} p_{T}",100,0,10);
fListOfHistos->Add(hAntiLambdaPtReco);
hInvMassLambda = new TH2F("hInvMassLambda","#Lambda invariant mass",100,1.05,1.25,100,0,10);
fListOfHistos->Add(hInvMassLambda);
hInvMassAntiLambda = new TH2F("hInvMassAntiLambda","#bar{#Lambda} invariant mass",100,1.05,1.25,100,0,10);
fListOfHistos->Add(hInvMassAntiLambda);
hInvMassLambdaOnTheFly = new TH2F("hInvMassLambdaOnTheFly","#Lambda invariant mass -- on-the-fly V0 finder",100,1.05,1.25,100,0,10);
fListOfHistos->Add(hInvMassLambdaOnTheFly);
hInvMassAntiLambdaOnTheFly = new TH2F("hInvMassAntiLambdaOnTheFly","#bar{#Lambda} invariant mass -- on-the-fly V0 finder",100,1.05,1.25,100,0,10);
fListOfHistos->Add(hInvMassAntiLambdaOnTheFly);
hInvMassLambdaReco = new TH2F("hInvMassLambdaReco","#Lambda invariant mass",100,1.05,1.25,100,0,10);
fListOfHistos->Add(hInvMassLambdaReco);
hInvMassAntiLambdaReco = new TH2F("hInvMassAntiLambdaReco","#bar{#Lambda} invariant mass",100,1.05,1.25,100,0,10);
fListOfHistos->Add(hInvMassAntiLambdaReco);
hInvMassLambdaSecFromMaterial = new TH2F("hInvMassLambdaSecFromMaterial","#Lambda from material",100,1.05,1.25,100,0,10);
fListOfHistos->Add(hInvMassLambdaSecFromMaterial);
hInvMassAntiLambdaSecFromMaterial = new TH2F("hInvMassAntiLambdaSecFromMaterial","#bar{#Lambda} from material",100,1.05,1.25,100,0,10);
fListOfHistos->Add(hInvMassAntiLambdaSecFromMaterial);
hInvMassLambdaSecFromWeakDecay = new TH2F("hInvMassLambdaSecFromWeakDecay","#Lambda from weak decays",100,1.05,1.25,100,0,10);
fListOfHistos->Add(hInvMassLambdaSecFromWeakDecay);
hInvMassAntiLambdaSecFromWeakDecay = new TH2F("hInvMassAntiLambdaSecFromWeakDecay","#bar{#Lambda} from weak decays",100,1.05,1.25,100,0,10);
fListOfHistos->Add(hInvMassAntiLambdaSecFromWeakDecay);
hInvMassLambdaK0S = new TH2F("hInvMassLambdaK0S","#Lambda vs K0S invariant mass",100,1.08,1.18,100,0.45,0.55);
fListOfHistos->Add(hInvMassLambdaK0S);
hInvMassAntiLambdaK0S = new TH2F("hInvMassAntiLambdaK0S","#bar{#Lambda} vs K0S invariant mass",100,1.08,1.18,100,0.45,0.55);
fListOfHistos->Add(hInvMassAntiLambdaK0S);
hInvMassLambdaConversions = new TH2F("hInvMassLambdaConversions","#Lambda vs e+e- invariant mass",100,1.08,1.18,100,0.,0.6);
fListOfHistos->Add(hInvMassLambdaConversions);
hInvMassAntiLambdaConversions = new TH2F("hInvMassAntiLambdaConversions","#bar{#Lambda} vs e+e- invariant mass",100,1.08,1.18,100,0.,0.6);
fListOfHistos->Add(hInvMassAntiLambdaConversions);
hInvMassLike = new TH2F("hInvMassLike","like-sign pair invariant mass",100,1.05,1.25,100,0,10);
fListOfHistos->Add(hInvMassLike);
//hInvMassPtPidLambda = new TH3F("hInvMassPtPidLambda","inv mass of lambda candidates",100,1.08,1.15,17,0.6,4,14,-0.5,13.5);
//fListOfHistos->Add(hInvMassPtPidLambda);
//hInvMassPtPidAntiLambda = new TH3F("hInvMassPtPidAntiLambda","inv mass of anti-lambda candidates",100,1.08,1.15,17,0.6,4,14,-0.5,13.5);
//fListOfHistos->Add(hInvMassPtPidAntiLambda);
hXiPlus = new TH3F("hXiPlus","Xi+ vs pt, eta, centrality",100,0,20,20,-1,1,80,0,80);
fListOfHistos->Add(hXiPlus);
hXiMinus = new TH3F("hXiMinus","Xi- vs pt, eta, centrality",100,0,20,20,-1,1,80,0,80);
fListOfHistos->Add(hXiMinus);
hXiZero = new TH3F("hXiZero","Xi0 vs pt, eta, centrality",100,0,20,20,-1,1,80,0,80);
fListOfHistos->Add(hXiZero);
hXiZeroAnti = new TH3F("hXiZeroAnti","anti-Xi0 vs pt, eta, centrality",100,0,20,20,-1,1,80,0,80);
fListOfHistos->Add(hXiZeroAnti);
hInvMassLambdaMPidPt = new TH3F("hInvMassLambdaMPidPt","#Lambda inv mass vs mother pid",100,1.08,1.15,26,0.5,26.5,45,0.5,5);
fListOfHistos->Add(hInvMassLambdaMPidPt);
hInvMassAntiLambdaMPidPt = new TH3F("hInvMassAntiLambdaMPidPt","#bar{#Lambda} inv mass vs mother pid",100,1.08,1.15,26,0.5,26.5,45,0.5,5);
fListOfHistos->Add(hInvMassAntiLambdaMPidPt);
pidVals = new Int_t[24];
Int_t pidValsTemp[24] = { 22, 11, -11, 13, -13, -211, 211, 111, -111, -321, 321, 311, -311, 310, 130, 2212, -2212, 3122, -3122, 3312, -3312, 3322, -3322, 113};
TString pidLabels[24] = {"gamma","e-","e+","mu-","mu+","pi-","pi+","pi0","anti pi0","K-", "K+","K0","anti K0","K0S","K0L","p", "anti p","lambda","anti lambda","Xi-","Xi+", "Xi0","anti Xi0","rho0"};
for(Int_t p = 0; p < 24; p++)
{
pidVals[p] = pidValsTemp[p];
hInvMassLambdaMPidPt->GetYaxis()->SetBinLabel(p+1,pidLabels[p]);
hInvMassAntiLambdaMPidPt->GetYaxis()->SetBinLabel(p+1,pidLabels[p]);
}
hInvMassLambdaMPidPt->GetYaxis()->SetBinLabel(25,"mismatch Xi-");
hInvMassAntiLambdaMPidPt->GetYaxis()->SetBinLabel(25,"mismatch Xi-");
hInvMassLambdaMPidPt->GetYaxis()->SetBinLabel(26,"mismatch Xi+");
hInvMassAntiLambdaMPidPt->GetYaxis()->SetBinLabel(26,"mismatch Xi+");
hPtResLambda = new TH2F("hPtResLambda","#Lambda pt resolution;gen p_{T};reco p_{T}",100,0,10,100,0,10);
fListOfHistos->Add(hPtResLambda);
hPtResAntiLambda = new TH2F("hPtResAntiLambda","#bar{#Lambda} pt resolution;gen p_{T};reco p_{T}",100,0,10,100,0,10);
fListOfHistos->Add(hPtResAntiLambda);
hPtResLambdaPrim = new TH2F("hPtResLambdaPrim","primary #Lambda pt resolution;gen p_{T};reco p_{T}",100,0,10,100,0,10);
fListOfHistos->Add(hPtResLambdaPrim);
hPtResAntiLambdaPrim = new TH2F("hPtResAntiLambdaPrim","primary #bar{#Lambda} pt resolution;gen p_{T};reco p_{T}",100,0,10,100,0,10);
fListOfHistos->Add(hPtResAntiLambdaPrim);
fEventCuts.AddQAplotsToList(fListOfHistos,true);
if(fLambdaTree)
{
fAcceptV0 = new TClonesArray("AliLightV0",1000);
//fAcceptV0test = new TClonesArray("AliLightV0",1000);
if(fIsMC)
{
fGenLambda = new TClonesArray("AliLightGenV0",1000);
fGenCascade = new TClonesArray("AliLightGenV0",1000);
}
if(fEventMixingTree)
{
fMixV0 = new TClonesArray("AliLightV0",1000);
}
}
// create file-resident tree
TDirectory *owd = gDirectory;
OpenFile(2);
fTree = new TTree("events","events");
owd->cd();
fTree->Branch("fCentV0M",&fCentV0M);
fTree->Branch("fCentCL1",&fCentCL1);
fTree->Branch("fMultV0M",&fMultV0M);
fTree->Branch("fNtracksTPCout",&fNtracksTPCout);
fTree->Branch("fVtxZ",&fVtxZ);
fTree->Branch("fRunNumber",&fRunNumber);
if(fLambdaTree)
{
fTree->Branch("fAcceptV0",&fAcceptV0);
if(fIsMC)
{
fTree->Branch("fGenLambda",&fGenLambda);
fTree->Branch("fGenCascade",&fGenCascade);
}
if(fEventMixingTree)
{
fTree->Branch("fMixV0",&fMixV0);
}
}
//fUtils = new AliAnalysisUtils();
//fUtils->SetMinPlpContribSPD(3);
//fUtils->SetMinPlpContribMV(3);
PostData(1,fListOfHistos);
PostData(2,fTree);
}
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
void AliAnalysisTaskNetLambdaIdent::UserExec(Option_t *){
hEventStatistics->Fill("before cuts",1);
if (!fInputEvent) return;
hEventStatistics->Fill("after event check",1);
if(fIsAOD) // aod
{
fAOD = dynamic_cast<AliAODEvent*>(fInputEvent);
if (!fAOD) return;
hEventStatistics->Fill("after aod check",1);
}
else // esd
{
fESD = dynamic_cast<AliESDEvent*>(InputEvent());
if (!fESD) return;
hEventStatistics->Fill("after esd check",1);
}
fPIDResponse = fInputHandler->GetPIDResponse();
if(!fPIDResponse) return;
hEventStatistics->Fill("after pid check",1);
stack = 0x0;
if(fIsMC)
{
if(!fIsAOD) // esd
{
AliMCEventHandler *mcH = dynamic_cast<AliMCEventHandler*>((AliAnalysisManager::GetAnalysisManager())->GetMCtruthEventHandler());
if(!mcH) return;
hEventStatistics->Fill("found MC handler",1);
fMCEvent=mcH->MCEvent();
//fMCEvent = dynamic_cast<AliMCEvent*>(MCEvent());
}
if(!fMCEvent) return;
hEventStatistics->Fill("found fMCEvent",1);
if(!fIsAOD) //esd
{
stack = fMCEvent->Stack();
if(!stack) return;
hEventStatistics->Fill("found MC stack",1);
}
}
AliMultSelection *MultSelection = (AliMultSelection*) fInputEvent->FindListObject("MultSelection");
if(!MultSelection) return;
hEventStatistics->Fill("found MultSelection object",1);
if(!(fInputHandler->IsEventSelected() & fEvSel)) return;
hEventStatistics->Fill("physics selection",1);
Double_t fVtx[3];
/*if(fIsAOD) // aod
{
AliAODVertex *aodVertex = (AliAODVertex*)fInputEvent->GetPrimaryVertex();
if (!aodVertex) return;
fVtx[0] = aodVertex->GetX();
fVtx[1] = aodVertex->GetY();
fVtx[2] = aodVertex->GetZ();
}
else // esd
{
AliESDVertex *esdVertex = (AliESDVertex*)fInputEvent->GetPrimaryVertex();
if (!esdVertex) return;
fVtx[0] = esdVertex->GetX();
fVtx[1] = esdVertex->GetY();
fVtx[2] = esdVertex->GetZ();
}*/
AliVVertex *vvertex = (AliVVertex*)fInputEvent->GetPrimaryVertex();
if (!vvertex) return;
fVtx[0] = vvertex->GetX();
fVtx[1] = vvertex->GetY();
fVtx[2] = vvertex->GetZ();
hEventStatistics->Fill("found primary vertex",1);
if(fVtx[2] < -10. || fVtx[2] > 10.) return;
hEventStatistics->Fill("vz cut",1);
fVtxZ = fVtx[2];
hVxVy->Fill(fVtx[0],fVtx[1]);
fCentCL1 = MultSelection->GetMultiplicityPercentile("CL1");
fCentV0M = MultSelection->GetMultiplicityPercentile("V0M");
fMultV0M = MultSelection->GetEstimator("V0M")->GetValue();
if(fCentV0M > centcut && fCentCL1 > centcut) return;
hEventStatistics->Fill("centrality selection",1);
/*Printf("require track vertex = %i",fEventCuts.fRequireTrackVertex);
Printf("min z-vertex = %lf",fEventCuts.fMinVtz);
Printf("max z-vertex = %lf",fEventCuts.fMaxVtz);
Printf("spd to track vertex = %lf",fEventCuts.fMaxDeltaSpdTrackAbsolute);
Printf("resolution spd vertex = %lf",fEventCuts.fMaxResolutionSPDvertex);
Printf("trigger mask = %lf",fEventCuts.fTriggerMask);
Printf("reject incomplete daq = %i",fEventCuts.fRejectDAQincomplete);
Printf("min spd pileup contribs = %lf",fEventCuts.fSPDpileupMinContributors);
Printf("spd pileup min z distance = %lf",fEventCuts.fSPDpileupMinZdist);
Printf("spd pileup nsigma z distance = %lf",fEventCuts.fSPDpileupNsigmaZdist);
Printf("spd pileup nsigma diam xy = %lf",fEventCuts.fSPDpileupNsigmaDiamXY);
Printf("spd pileup nsigma diam z = %lf",fEventCuts.fSPDpileupNsigmaDiamZ);
Printf("tracklet background cut = %i",fEventCuts.fTrackletBGcut);*/
if (!fEventCuts.AcceptEvent(fInputEvent)) return;
hEventStatistics->Fill("AliEventCuts",1);
TObjArray* mixtracks = 0x0, *mixprotons = 0x0;
if(fEventMixingTree || fRevertex)
{
mixtracks = new TObjArray();
mixtracks->SetOwner(kTRUE);
}
Double_t b = fInputEvent->GetMagneticField();
// loop over reconstructed tracks
Int_t nTracks = 0;
if(fIsAOD) nTracks = fAOD->GetNumberOfTracks(); // aod
else nTracks = fESD->GetNumberOfTracks(); // esd
fNtracksTPCout = 0;
Int_t nTracksEsd = 0;
for(Int_t iTrack = 0; iTrack < nTracks; iTrack++)
{
Float_t pt = -999, eta = -999, phi = -999;
if(fIsAOD) // aod
{
AliAODTrack* track = (AliAODTrack*)fAOD->GetTrack(iTrack);
if(!track) continue;
if(track->Pt() > 0.15 && (track->GetStatus() & AliESDtrack::kTPCout) && track->GetID() > 0) fNtracksTPCout += 1.;
if(!TrackCutsForTreeAOD(track)) continue;
if(TMath::Abs(track->Eta()) > 0.8) continue;
if(!(track->TestFilterBit(96))) continue; //filter bits 5+6
pt = track->Pt();
eta = track->Eta();
phi = track->Phi();
}
else //esd
{
AliESDtrack* track = (AliESDtrack*)fESD->GetTrack(iTrack);
if(!track) continue;
if(track->Pt() > 0.15 && (track->GetStatus() & AliESDtrack::kTPCout)) fNtracksTPCout += 1.;
if(!TrackCutsForTreeESD(track)) continue;
pt = track->Pt();
eta = track->Eta();
phi = track->Phi();
if((track->GetStatus()&AliESDtrack::kTPCrefit) != 0)
{
nTracksEsd++;
if(fEventMixingTree || fRevertex)
{
Double_t dn = TMath::Abs(track->GetD(fVtx[0],fVtx[1],b));
if(dn > fDmin && dn < fRmax)
{
AliLightV0track* lighttrack = new AliLightV0track(*track,fPIDResponse->NumberOfSigmasTPC(track, AliPID::kProton),fVtx);
lighttrack->SetMcLabel(TMath::Abs(track->GetLabel()));
mixtracks->Add(lighttrack);
}
}
}
}
hTrackPt->Fill(pt);
hTrackPhi->Fill(phi);
hTrackEta->Fill(eta);
} // end loop over reconstructed tracks
hNTracksEsd->Fill(nTracksEsd);
fRunNumber = fInputEvent->GetRunNumber();
Int_t nGen = 0;
if(fIsMC)
{
if(fLambdaTree)
{
fGenLambda->Clear();
fGenCascade->Clear();
}
// loop over generated particles to find lambdas
if(fIsAOD) nGen = fMCEvent->GetNumberOfTracks(); // aod
else nGen = stack->GetNtrack(); // esd
for(Int_t iGen = 0; iGen < nGen; iGen++)
{
Int_t pid = -999, abspid = -999, nd = -999, fd = -999, ld = -999;
Float_t pt = -999, phi = -999, eta = -999, abseta = -999;
if(fIsAOD) // aod
{
AliAODMCParticle* mctrack = (AliAODMCParticle*)fMCEvent->GetTrack(iGen);
if(!mctrack) continue;
if(!(mctrack->IsPhysicalPrimary())) continue;
pid = mctrack->PdgCode();
pt = mctrack->Pt();
eta = mctrack->Eta();
phi = mctrack->Phi();
nd = mctrack->GetNDaughters();
fd = mctrack->GetFirstDaughter();
ld = mctrack->GetLastDaughter();
}
else // esd
{
TParticle* mctrack = stack->Particle(iGen);
if(!mctrack) continue;
if(!(stack->IsPhysicalPrimary(iGen))) continue;
pid = mctrack->GetPdgCode();
pt = mctrack->Pt();
eta = mctrack->Eta();
phi = mctrack->Phi();
nd = mctrack->GetNDaughters();
fd = mctrack->GetFirstDaughter();
ld = mctrack->GetLastDaughter();
}
abspid = TMath::Abs(pid);
abseta = TMath::Abs(eta);
// basic QA of pi/K/p
if(abseta < 0.8 && (abspid == 211 || abspid == 321 || abspid == 2212))
{
hGenPt->Fill(pt);
hGenPhi->Fill(phi);
hGenEta->Fill(eta);
}
if(abseta > etacutlambda) continue;
// cascades for feeddown correction
AliLightGenV0* tempGenCascade = 0x0;
if(pid == -3312) // xi+
{
hXiPlus->Fill(pt,eta,fCentV0M);
if(fLambdaTree) tempGenCascade = new((*fGenCascade)[fGenCascade->GetEntriesFast()]) AliLightGenV0(pt,eta,1);
}
else if(pid == 3312) // xi-
{
hXiMinus->Fill(pt,eta,fCentV0M);
if(fLambdaTree) tempGenCascade = new((*fGenCascade)[fGenCascade->GetEntriesFast()]) AliLightGenV0(pt,eta,-1);
}
else if(pid == 3322) // xi0
{
hXiZero->Fill(pt,eta,fCentV0M);
if(fLambdaTree) tempGenCascade = new((*fGenCascade)[fGenCascade->GetEntriesFast()]) AliLightGenV0(pt,eta,-2);
}
else if(pid == -3322) // anti-xi0
{
hXiZeroAnti->Fill(pt,eta,fCentV0M);
if(fLambdaTree) tempGenCascade = new((*fGenCascade)[fGenCascade->GetEntriesFast()]) AliLightGenV0(pt,eta,2);
}
//if(abspid != 3122) continue;
// generated (anti-)lambda pt spectra
AliLightGenV0* tempGenLambda = 0x0;
if(pid == 3122)
{
hLambdaPtGen->Fill(pt);
if(pt >= ptminlambda)
{
if(fLambdaTree) tempGenLambda = new((*fGenLambda)[fGenLambda->GetEntriesFast()]) AliLightGenV0(pt,eta,1);
}
}
else if(pid == -3122)
{
hAntiLambdaPtGen->Fill(pt);
if(pt >= ptminlambda)
{
if(fLambdaTree) tempGenLambda = new((*fGenLambda)[fGenLambda->GetEntriesFast()]) AliLightGenV0(pt,eta,-1);
}
}
if(tempGenLambda)
{
tempGenLambda->SetPosDaughter(-999,-999);
tempGenLambda->SetNegDaughter(-999,-999);
}
else if(tempGenCascade)
{
tempGenCascade->SetPosDaughter(-999,-999);
tempGenCascade->SetNegDaughter(-999,-999);
}
else
{
continue;
}
// remove weird (1-prong, 3-prong) decays
if(nd != 2) continue;
Int_t pdg1 = -999, pdg2 = -999;
Float_t pt1 = -999, phi1 = -999, eta1 = -999;
Float_t pt2 = -999, phi2 = -999, eta2 = -999;
if(fIsAOD) // aod
{
AliAODMCParticle *daughtertrack1 = (AliAODMCParticle*)fMCEvent->GetTrack(fd);
if(!daughtertrack1) continue;
AliAODMCParticle *daughtertrack2 = (AliAODMCParticle*)fMCEvent->GetTrack(ld);
if(!daughtertrack2) continue;
pdg1 = daughtertrack1->GetPdgCode();
pdg2 = daughtertrack2->GetPdgCode();
pt1 = daughtertrack1->Pt();
eta1 = daughtertrack1->Eta();
phi1 = daughtertrack1->Phi();
pt2 = daughtertrack2->Pt();
eta2 = daughtertrack2->Eta();
phi2 = daughtertrack2->Phi();
}
else // esd
{
TParticle *daughtertrack1 = (TParticle*)stack->Particle(fd);
if(!daughtertrack1) continue;
TParticle *daughtertrack2 = (TParticle*)stack->Particle(ld);
if(!daughtertrack2) continue;
pdg1 = daughtertrack1->GetPdgCode();
pdg2 = daughtertrack2->GetPdgCode();
pt1 = daughtertrack1->Pt();
eta1 = daughtertrack1->Eta();
phi1 = daughtertrack1->Phi();
pt2 = daughtertrack2->Pt();
eta2 = daughtertrack2->Eta();
phi2 = daughtertrack2->Phi();
}
if(tempGenLambda)
{
if(pid == 3122 && pdg1 == 2212 && pdg2 == -211) // daughter 1 is proton, daughter 2 is pi-, mother is lambda
{
tempGenLambda->SetPosDaughter(pt1,eta1);
tempGenLambda->SetNegDaughter(pt2,eta2);
}
else if(pid == -3122 && pdg1 == -2212 && pdg2 == 211) // daughter 1 is antiproton, daughter 2 is pi+, mother is anti-lambda
{
tempGenLambda->SetNegDaughter(pt1,eta1);
tempGenLambda->SetPosDaughter(pt2,eta2);
}
else if(pid == 3122 && pdg1 == -211 && pdg2 == 2212) // daughter 1 is pi-, daughter 2 is proton, mother is lambda
{
tempGenLambda->SetNegDaughter(pt1,eta1);
tempGenLambda->SetPosDaughter(pt2,eta2);
}
else if(pid == -3122 && pdg1 == 211 && pdg2 == -2212) // daughter 1 is pi+, daughter 2 is antiproton, mother is anti-lambda
{
tempGenLambda->SetPosDaughter(pt1,eta1);
tempGenLambda->SetNegDaughter(pt2,eta2);
}
}
if(tempGenCascade)
{
if(TMath::Abs(pdg1) == 3122 && (TMath::Abs(pdg2) == 211 || TMath::Abs(pdg2) == 111)) // daughter 1 is lambda, daughter 2 is pion
{
tempGenCascade->SetPosDaughter(pt1,eta1);
tempGenCascade->SetNegDaughter(pt2,eta2);
}
else if(TMath::Abs(pdg2) == 3122 && (TMath::Abs(pdg1) == 211 || TMath::Abs(pdg1) == 111)) // daughter 1 is pion, daughter 2 is lambda
{
tempGenCascade->SetPosDaughter(pt2,eta2);
tempGenCascade->SetNegDaughter(pt1,eta1);
}
}
} // end loop over generated particles
}
/*AliESDv0Cuts* v0cuts = new AliESDv0Cuts();
v0cuts->SetMinDcaPosToVertex(0.05);
v0cuts->SetMinDcaNegToVertex(0.05);
v0cuts->SetMaxChi2(33.);
v0cuts->SetMaxDcaV0Daughters(1.5);
v0cuts->SetMinRadius(0.2);
v0cuts->SetMaxRadius(200.);
v0cuts->SetMinCosinePointingAngle(0.99);
v0cuts->SetMaxDcaV0ToVertex(5*7.89);
Int_t nV0 = v0cuts->CountAcceptedV0s(fESD);
TObjArray* v0array = v0cuts->GetAcceptedV0s(fESD);*/
if(fLambdaTree) {fAcceptV0->Clear();/* fAcceptV0test->Clear();*/}
Int_t nV0 = 0;
//TObjArray *v0array = 0x0;
if(fIsAOD) nV0 = fAOD->GetNumberOfV0s(); // aod
else if(!fRevertex) nV0 = fESD->GetNumberOfV0s(); // esd
else
{
Tracks2V0vertices(fAcceptV0,mixtracks,mixtracks,kFALSE,vvertex,b);
}
AliESDv0 *esdv0 = 0x0;
AliESDtrack *esdTrackPos = 0x0;
AliESDtrack *esdTrackNeg = 0x0;
AliAODv0 *aodv0 = 0x0;
AliAODTrack *aodTrackPos = 0x0;
AliAODTrack *aodTrackNeg = 0x0;
//Printf("same event");
for(Int_t iV0 = 0; iV0 < nV0; iV0++)
{
esdv0 = 0x0;
esdTrackPos = 0x0;
esdTrackNeg = 0x0;
aodv0 = 0x0;
aodTrackPos = 0x0;
aodTrackNeg = 0x0;
Double_t secvtx[3];
Float_t invMassLambda = -999, invMassAntiLambda = -999, invMassK0S = -999, invMassEplusEminus = -999;
Float_t alpha = -999, ptarm = -999;
Float_t pt = -999, phi = -999, eta = -999, pmom = -999;
Float_t ppt = -999, pphi = -999, peta = -999, pnsigmapr = -999;
Float_t npt = -999, nphi = -999, neta = -999, nnsigmapr = -999;
Float_t /*dcaV0ToVertex = -999,*/ dcaPosToVertex = -999, dcaNegToVertex = -999, dcaDaughters = -999, cosPointingAngle = -999;
if(fIsAOD) // aod
{
aodv0 = fAOD->GetV0(iV0);
if(!aodv0) continue;
AliAODVertex* v0vtx = (AliAODVertex*)aodv0->GetSecondaryVtx();
if(!v0vtx) continue;
if(aodv0->GetOnFlyStatus() == kTRUE)
{
hInvMassLambdaOnTheFly->Fill(aodv0->MassLambda(),aodv0->Pt());
hInvMassAntiLambdaOnTheFly->Fill(aodv0->MassAntiLambda(),aodv0->Pt());
continue;
}
v0vtx->GetPosition(secvtx);
aodTrackPos = (AliAODTrack*)v0vtx->GetDaughter(0);
if(!aodTrackPos) continue;
if(!TrackCutsForTreeAOD(aodTrackPos)) continue;
aodTrackNeg = (AliAODTrack*)v0vtx->GetDaughter(1);
if(!aodTrackNeg) continue;
if(!TrackCutsForTreeAOD(aodTrackNeg)) continue;
if(!V0CutsForTreeAOD(aodv0,fVtx)) continue;
invMassLambda = aodv0->MassLambda();
invMassAntiLambda = aodv0->MassAntiLambda();
invMassK0S = aodv0->MassK0Short();
invMassEplusEminus = aodv0->InvMass2Prongs(0,1,11,11);
alpha = aodv0->AlphaV0();
ptarm = aodv0->PtArmV0();
dcaPosToVertex = aodv0->DcaPosToPrimVertex();
dcaNegToVertex = aodv0->DcaNegToPrimVertex();
if(aodTrackPos->Charge() == aodTrackNeg->Charge()) // "like-sign V0s"
{
hInvMassLike->Fill(invMassLambda,aodv0->Pt());
continue;
}
if(aodTrackPos->Charge() < 0 && aodTrackNeg->Charge() > 0) // fix wrongly assigned charges
{
AliAODTrack* swaptrack = aodTrackPos;
aodTrackPos = aodTrackNeg;
aodTrackNeg = swaptrack;
invMassLambda = aodv0->MassAntiLambda();
invMassAntiLambda = aodv0->MassLambda();
ptarm = aodv0->QtProng(1);
alpha = -1.*alpha;
dcaPosToVertex = aodv0->DcaNegToPrimVertex();
dcaNegToVertex = aodv0->DcaPosToPrimVertex();
}
pt = aodv0->Pt();
pmom = aodv0->P();
eta = aodv0->Eta();
phi = aodv0->Phi();
ppt = aodTrackPos->Pt();
peta = aodTrackPos->Eta();
pphi = aodTrackPos->Phi();
npt = aodTrackNeg->Pt();
neta = aodTrackNeg->Eta();
nphi = aodTrackNeg->Phi();
pnsigmapr = fPIDResponse->NumberOfSigmasTPC(aodTrackPos, AliPID::kProton);
nnsigmapr = fPIDResponse->NumberOfSigmasTPC(aodTrackNeg, AliPID::kProton);
//dcaV0ToVertex = aodv0->DcaV0ToPrimVertex();
cosPointingAngle = aodv0->CosPointingAngle(fVtx);
dcaDaughters = aodv0->DcaV0Daughters();
}
else // esd
{
esdv0 = fESD->GetV0(iV0);
//esdv0 = (AliESDv0*)v0array->At(iV0);
if(!esdv0) continue;
if(esdv0->GetOnFlyStatus() == kTRUE)
{
hInvMassLambdaOnTheFly->Fill(esdv0->GetEffMass(4,2),esdv0->Pt());
hInvMassAntiLambdaOnTheFly->Fill(esdv0->GetEffMass(2,4),esdv0->Pt());
continue;
}
esdv0->GetXYZ(secvtx[0], secvtx[1], secvtx[2]);
esdTrackPos = (AliESDtrack*)fESD->GetTrack(TMath::Abs(esdv0->GetPindex()));
if(!esdTrackPos) continue;
if(!TrackCutsForTreeESD(esdTrackPos)) continue;
esdTrackNeg = (AliESDtrack*)fESD->GetTrack(TMath::Abs(esdv0->GetNindex()));
if(!esdTrackNeg) continue;
if(!TrackCutsForTreeESD(esdTrackNeg)) continue;
if(!V0CutsForTreeESD(esdv0,fVtx,esdTrackPos,esdTrackNeg,b)) continue;
invMassLambda = esdv0->GetEffMass(4,2);
invMassAntiLambda = esdv0->GetEffMass(2,4);
invMassK0S = esdv0->GetEffMass(2,2);
invMassEplusEminus = esdv0->GetEffMass(0,0);
alpha = esdv0->AlphaV0();
ptarm = esdv0->PtArmV0();
if(esdTrackPos->Charge() == esdTrackNeg->Charge()) // "like-sign V0s"
{
hInvMassLike->Fill(invMassLambda,esdv0->Pt());
continue;
}
if(esdTrackPos->Charge() < 0 && esdTrackNeg->Charge() > 0) // fix wrongly assigned charges
{
AliESDtrack* swaptrack = esdTrackPos;
esdTrackPos = esdTrackNeg;
esdTrackNeg = swaptrack;
invMassLambda = esdv0->GetEffMass(2,4);
invMassAntiLambda = esdv0->GetEffMass(4,2);
Double_t tot = esdv0->Px()*esdv0->Px()+esdv0->Py()*esdv0->Py()+esdv0->Pz()*esdv0->Pz();
Double_t ss = esdv0->Px()*esdTrackNeg->Px()+esdv0->Py()*esdTrackNeg->Py()+esdv0->Pz()*esdTrackNeg->Pz();
Double_t per = esdTrackNeg->Px()*esdTrackNeg->Px()+esdTrackNeg->Py()*esdTrackNeg->Py()+esdTrackNeg->Pz()*esdTrackNeg->Pz();
if(tot > 0.) per -= ss*ss/tot;
if(per < 0.) per = 0;
//TVector3 momNeg(esdTrackNeg->Px(),esdTrackNeg->Py(),esdTrackNeg->Pz());
//TVector3 momTot(esdv0->Px(),esdv0->Py(),esdv0->Pz());
//ptarm = momNeg.Perp(momTot);
ptarm = TMath::Sqrt(per);
//Printf("%.3lf %.3lf",ptarm,momNeg.Perp(momTot));
alpha = -1.*alpha;
}
pt = esdv0->Pt();
pmom = esdv0->P();
eta = esdv0->Eta();
phi = esdv0->Phi();
ppt = esdTrackPos->Pt();
peta = esdTrackPos->Eta();
pphi = esdTrackPos->Phi();
npt = esdTrackNeg->Pt();
neta = esdTrackNeg->Eta();
nphi = esdTrackNeg->Phi();
pnsigmapr = fPIDResponse->NumberOfSigmasTPC(esdTrackPos, AliPID::kProton);
nnsigmapr = fPIDResponse->NumberOfSigmasTPC(esdTrackNeg, AliPID::kProton);
//dcaV0ToVertex = esdv0->GetD(fVtx[0],fVtx[1],fVtx[2]);
Float_t d1, d2;
esdTrackPos->GetImpactParameters(d1,d2);
dcaPosToVertex = TMath::Sqrt(d1*d1+d2*d2);
esdTrackNeg->GetImpactParameters(d1,d2);
dcaNegToVertex = TMath::Sqrt(d1*d1+d2*d2);
cosPointingAngle = esdv0->GetV0CosineOfPointingAngle();
dcaDaughters = esdv0->GetDcaV0Daughters();
}
if(TMath::Abs(eta) > etacutlambda) continue;
hInvMassLambda->Fill(invMassLambda,pt);
hInvMassAntiLambda->Fill(invMassAntiLambda,pt);
hInvMassLambdaK0S->Fill(invMassLambda,invMassK0S);
hInvMassAntiLambdaK0S->Fill(invMassAntiLambda,invMassK0S);
hInvMassLambdaConversions->Fill(invMassLambda,invMassEplusEminus);
hInvMassAntiLambdaConversions->Fill(invMassAntiLambda,invMassEplusEminus);
hNSigmaProton->Fill(ppt,pnsigmapr);
hNSigmaProton->Fill(-1.*npt,nnsigmapr);
Float_t v0Radius = TMath::Sqrt(secvtx[0]*secvtx[0]+secvtx[1]*secvtx[1]);
Float_t v0DecayLength = TMath::Sqrt(TMath::Power(secvtx[0] - fVtx[0],2) +
TMath::Power(secvtx[1] - fVtx[1],2) +
TMath::Power(secvtx[2] - fVtx[2],2 ));
hArmPod->Fill(alpha,ptarm);
AliLightV0* tempLightV0L = 0x0, *tempLightV0AL = 0x0;
if(fLambdaTree)
{
// make tree
if(invMassLambda < 1.16 && TMath::Abs(pnsigmapr) < 5.) // lambda candidate
{
tempLightV0L = new((*fAcceptV0)[fAcceptV0->GetEntriesFast()]) AliLightV0(pt,eta);
tempLightV0L->SetInvMass(invMassLambda);
tempLightV0L->SetInvMassK0S(invMassK0S);
tempLightV0L->SetInvMassGamma(invMassEplusEminus);
tempLightV0L->SetCosPointingAngle(cosPointingAngle);
tempLightV0L->SetDecayR(v0Radius);
tempLightV0L->SetProperLifetime(pmom > 0. ? invMassLambda*v0DecayLength/pmom : 0.);
//tempLightV0L->SetDCAV0(dcaV0ToVertex);
tempLightV0L->SetDCADaughters(dcaDaughters);
tempLightV0L->SetArmPodVars(ptarm,alpha);
tempLightV0L->SetMcStatus(0);
tempLightV0L->SetPosDaughter(ppt,peta,pnsigmapr, dcaPosToVertex);
tempLightV0L->SetNegDaughter(npt,neta,nnsigmapr, dcaNegToVertex);
//Printf("pt = %.3lf eta = %.3lf minv = %.3lf cosPA = %.3lf decayR = %.3lf propLife = %.3lf DCAdaughters = %.3lf posPt = %.3lf posDCA = %.3lf posNSigma = %.3lf posD = %.3lf negPt = %.3lf negDCA = %.3lf negNSigma = %.3lf negD = %.3lf",pt,eta,invMassLambda,cosPointingAngle,v0Radius,invMassLambda*v0DecayLength/pmom,dcaDaughters,ppt,dcaPosToVertex,pnsigmapr,esdTrackPos->GetD(fVtx[0],fVtx[1],b),npt,dcaNegToVertex,nnsigmapr,esdTrackNeg->GetD(fVtx[0],fVtx[1],b));
//Printf("A id1 = %i id2 = %i pt = %.3lf eta = %.3lf minv = %.3lf cosPA = %.3lf decayR = %.3lf propLife = %.3lf DCAdaughters = %.3lf",esdv0->GetPindex(),esdv0->GetNindex(),pt,eta,invMassLambda,cosPointingAngle,v0Radius,invMassLambda*v0DecayLength/pmom,dcaDaughters);
//Printf(" posPt = %.3lf posDCA = %.3lf posNSigma = %.3lf posD = %.3lf negPt = %.3lf negDCA = %.3lf negNSigma = %.3lf negD = %.3lf",ppt,dcaPosToVertex,pnsigmapr,esdTrackPos->GetD(fVtx[0],fVtx[1],b),npt,dcaNegToVertex,nnsigmapr,esdTrackNeg->GetD(fVtx[0],fVtx[1],b));
}
if(invMassAntiLambda < 1.16 && TMath::Abs(nnsigmapr) < 5.) // anti-lambda candidate
{
tempLightV0AL = new((*fAcceptV0)[fAcceptV0->GetEntriesFast()]) AliLightV0(pt,eta);
tempLightV0AL->SetInvMass(-1.*invMassAntiLambda);
tempLightV0AL->SetInvMassK0S(invMassK0S);
tempLightV0AL->SetInvMassGamma(invMassEplusEminus);
tempLightV0AL->SetCosPointingAngle(cosPointingAngle);
tempLightV0AL->SetDecayR(v0Radius);
tempLightV0AL->SetProperLifetime(pmom > 0. ? invMassAntiLambda*v0DecayLength/pmom : 0.);
//tempLightV0AL->SetDCAV0(dcaV0ToVertex);
tempLightV0AL->SetDCADaughters(dcaDaughters);
tempLightV0AL->SetArmPodVars(ptarm,alpha);
tempLightV0AL->SetMcStatus(0);
tempLightV0AL->SetPosDaughter(ppt,peta,pnsigmapr, dcaPosToVertex);
tempLightV0AL->SetNegDaughter(npt,neta,nnsigmapr, dcaNegToVertex);
//Printf("pt = %.3lf eta = %.3lf minv = %.3lf cosPA = %.3lf decayR = %.3lf propLife = %.3lf DCAdaughters = %.3lf posPt = %.3lf posDCA = %.3lf posNSigma = %.3lf posD = %.3lf negPt = %.3lf negDCA = %.3lf negNSigma = %.3lf negD = %.3lf",pt,eta,invMassAntiLambda,cosPointingAngle,v0Radius,invMassAntiLambda*v0DecayLength/pmom,dcaDaughters,ppt,dcaPosToVertex,pnsigmapr,esdTrackPos->GetD(fVtx[0],fVtx[1],b),npt,dcaNegToVertex,nnsigmapr,esdTrackNeg->GetD(fVtx[0],fVtx[1],b));
//Printf("A id1 = %i id2 = %i pt = %.3lf eta = %.3lf minv = %.3lf cosPA = %.3lf decayR = %.3lf propLife = %.3lf DCAdaughters = %.3lf",esdv0->GetPindex(),esdv0->GetNindex(),pt,eta,invMassAntiLambda,cosPointingAngle,v0Radius,invMassAntiLambda*v0DecayLength/pmom,dcaDaughters);
//Printf(" posPt = %.3lf posDCA = %.3lf posNSigma = %.3lf posD = %.3lf negPt = %.3lf negDCA = %.3lf negNSigma = %.3lf negD = %.3lf",ppt,dcaPosToVertex,pnsigmapr,esdTrackPos->GetD(fVtx[0],fVtx[1],b),npt,dcaNegToVertex,nnsigmapr,esdTrackNeg->GetD(fVtx[0],fVtx[1],b));
}
}
//Armenteros-Podolanski plot
//calculate variables manually
/*Float_t pLplus = trackPos->Px()*v0cand->Px()+trackPos->Py()*v0cand->Py()+trackPos->Pz()*v0cand->Pz();
Float_t pLminus = trackNeg->Px()*v0cand->Px()+trackNeg->Py()*v0cand->Py()+trackNeg->Pz()*v0cand->Pz();
Float_t pLpL = v0cand->Px()*v0cand->Px()+v0cand->Py()*v0cand->Py()+v0cand->Pz()*v0cand->Pz();
pLpL = sqrt(pLpL);
pLplus /= pLpL;
pLminus /= pLpL;
Float_t alphatest = (pLplus-pLminus)/(pLplus+pLminus);
Float_t qttest = (trackNeg->Py()*v0cand->Pz()-trackNeg->Pz()*v0cand->Py())*(trackNeg->Py()*v0cand->Pz()-trackNeg->Pz()*v0cand->Py())+(trackNeg->Pz()*v0cand->Px()-trackNeg->Px()*v0cand->Pz())*(trackNeg->Pz()*v0cand->Px()-trackNeg->Px()*v0cand->Pz())+(trackNeg->Px()*v0cand->Py()-trackNeg->Py()*v0cand->Px())*(trackNeg->Px()*v0cand->Py()-trackNeg->Py()*v0cand->Px());
qttest = sqrt(qttest);
qttest /= pLpL;
Printf("%.3lf %.3lf %.3lf %.3lf",alpha,alphatest,ptarm,qttest);*/
//hArmPod->Fill(alpha,ptarm);
// check if V0 corresponds to a real generated lambda
if(fIsMC)
{
if(fIsAOD) IsGenLambda(TMath::Abs(aodTrackPos->GetLabel()), TMath::Abs(aodTrackNeg->GetLabel()), tempLightV0L, tempLightV0AL,pt,invMassLambda,invMassAntiLambda);
else IsGenLambda(TMath::Abs(esdTrackPos->GetLabel()), TMath::Abs(esdTrackNeg->GetLabel()), tempLightV0L, tempLightV0AL,pt,invMassLambda,invMassAntiLambda);
}
}
//Printf("mixed event");
// event mixing
if(fLambdaTree && fEventMixingTree)
{
fMixV0->Clear();
AliEventPool* pool = fPoolMgr->GetEventPool(fCentV0M,fVtxZ);
if(pool)
{
if (pool->IsReady())
{
//Printf("found pool for cent %lf vz %lf with %i entries",fCentV0M,fVtxZ,pool->GetCurrentNEvents());
for (Int_t jMix=0; jMix<TMath::Min(nmaxmixevents,pool->GetCurrentNEvents()); jMix++)
{
Tracks2V0vertices(fMixV0,mixtracks,pool->GetEvent(jMix),kTRUE,vvertex,b);
}
}
//pool->UpdatePool(mixprotons);
pool->UpdatePool(mixtracks);
}
//Tracks2V0vertices(mixtracks,mixtracks,vvertex,b);
//mixtracks->Clear();
//Printf("%i %i",fAcceptV0->GetEntriesFast(),fMixV0->GetEntriesFast()/2);
}
//if(fAcceptV0test->GetEntriesFast() != fAcceptV0->GetEntriesFast())
//{
//Printf("Warning!!! number of V0s don't match!!!");
//Printf("nV0s = %i calc = %i",fAcceptV0->GetEntriesFast(),fAcceptV0test->GetEntriesFast());
//}
fTree->Fill();
hEventStatistics->Fill("after event loop",1);
PostData(1,fListOfHistos);
PostData(2,fTree);
}
// copied from AliRoot/STEER/ESD/AliV0vertexer.cxx and modified
void AliAnalysisTaskNetLambdaIdent::Tracks2V0vertices(TClonesArray* fv0s, TObjArray* ev1, TObjArray* ev2, Bool_t mixing, AliVVertex *vtxT3D, Double_t b)
{
//--------------------------------------------------------------------
//This function reconstructs V0 vertices
//--------------------------------------------------------------------
//const AliESDVertex *vtxT3D=event->GetPrimaryVertex();
Double_t primVtx[3] = {vtxT3D->GetX(),vtxT3D->GetY(),vtxT3D->GetZ()};
Double_t covMat[6];
vtxT3D->GetCovarianceMatrix(covMat);
AliExternalTrackParam *temptrk1 = 0x0, *temptrk2 = 0x0;
for(Int_t i = 0; i < ev1->GetEntries(); i++)
{
temptrk1 = (AliExternalTrackParam*)((AliLightV0track*)ev1->At(i))->GetExtParam();
//Double_t dn = TMath::Abs(temptrk1->GetD(primVtx[0],primVtx[1],b));
//if (dn<fDmin) continue;
//if (dn>fRmax) continue;
for(Int_t k = (mixing ? 0 : i); k < ev2->GetEntries(); k++)
{
temptrk2 = (AliExternalTrackParam*)((AliLightV0track*)ev2->At(k))->GetExtParam();
if(temptrk1->GetSign() == temptrk2->GetSign()) continue;
if(TMath::Abs(((AliLightV0track*)ev1->At(i))->GetProtonPID()) > 5. && TMath::Abs(((AliLightV0track*)ev2->At(k))->GetProtonPID()) > 5.) continue;
AliExternalTrackParam *ntrk = 0x0, *ptrk = 0x0;
Float_t pnsigmapr = -999, nnsigmapr = -999;
Int_t pmclabel = -999, nmclabel = -999;
if(temptrk1->GetSign() > 0 && temptrk2->GetSign() < 0)
{
ntrk = new AliExternalTrackParam(*temptrk2);
nnsigmapr = ((AliLightV0track*)ev2->At(k))->GetProtonPID();
if(fIsMC) nmclabel = ((AliLightV0track*)ev2->At(k))->GetMcLabel();
Double_t diffVtx[3];
((AliLightV0track*)ev2->At(k))->GetPrimaryVertex(diffVtx[0],diffVtx[1],diffVtx[2]);
//Printf("zvtx1 = %.3lf, zvtx2 = %.3lf old z1 = %.3lf, old z2 = %.3lf",primVtx[2],diffVtx[2],temptrk1->GetZ(),temptrk2->GetZ());
//diffVtx[0] = primVtx[0]-diffVtx[0];
//diffVtx[1] = primVtx[1]-diffVtx[1];
//diffVtx[2] = primVtx[2]-diffVtx[2];
diffVtx[0] -= primVtx[0];
diffVtx[1] -= primVtx[1];
diffVtx[2] -= primVtx[2];
//Printf("old D = %.3lf",ntrk->GetD(primVtx[0],primVtx[1],b));
if(mixing) ntrk->Translate(diffVtx,covMat);
//Printf("new D = %.3lf",ntrk->GetD(primVtx[0],primVtx[1],b));
//Double_t dp = TMath::Abs(ntrk->GetD(primVtx[0],primVtx[1],b));
//if (dp<fDmin) {delete ntrk; continue;}
//if (dp>fRmax) {delete ntrk; continue;}
ptrk = new AliExternalTrackParam(*temptrk1);
pnsigmapr = ((AliLightV0track*)ev1->At(i))->GetProtonPID();
if(fIsMC) pmclabel = ((AliLightV0track*)ev1->At(i))->GetMcLabel();
//Printf("new z1 = %.3lf, old z2 = %.3lf",ptrk->GetZ(),ntrk->GetZ());
}
else if(temptrk1->GetSign() < 0 && temptrk2->GetSign() > 0)
{
ptrk = new AliExternalTrackParam(*temptrk2);
pnsigmapr = ((AliLightV0track*)ev2->At(k))->GetProtonPID();
if(fIsMC) pmclabel = ((AliLightV0track*)ev2->At(k))->GetMcLabel();
Double_t diffVtx[3];
((AliLightV0track*)ev2->At(k))->GetPrimaryVertex(diffVtx[0],diffVtx[1],diffVtx[2]);
//Printf("zvtx1 = %.3lf, zvtx2 = %.3lf old z1 = %.3lf, old z2 = %.3lf",primVtx[2],diffVtx[2],temptrk1->GetZ(),temptrk2->GetZ());
//diffVtx[0] = primVtx[0]-diffVtx[0];
//diffVtx[1] = primVtx[1]-diffVtx[1];
//diffVtx[2] = primVtx[2]-diffVtx[2];
diffVtx[0] -= primVtx[0];
diffVtx[1] -= primVtx[1];
diffVtx[2] -= primVtx[2];
//Printf("old D = %.3lf",ptrk->GetD(primVtx[0],primVtx[1],b));
if(mixing) ptrk->Translate(diffVtx,covMat);
//Printf("new D = %.3lf",ptrk->GetD(primVtx[0],primVtx[1],b));
//Double_t dp = TMath::Abs(ptrk->GetD(primVtx[0],primVtx[1],b));
//if (dp<fDmin) {delete ptrk; continue;}
//if (dp>fRmax) {delete ptrk; continue;}
ntrk = new AliExternalTrackParam(*temptrk1);
nnsigmapr = ((AliLightV0track*)ev1->At(i))->GetProtonPID();
if(fIsMC) nmclabel = ((AliLightV0track*)ev1->At(i))->GetMcLabel();
//Printf("new z1 = %.3lf, old z2 = %.3lf",ntrk->GetZ(),ptrk->GetZ());
}
else continue;
Double_t xn, xp;
Double_t dca = ntrk->GetDCA(ptrk,b,xn,xp);
if (dca > fDCAmax) {delete ntrk; delete ptrk; continue;}
if ((xn+xp) > 2*fRmax) {delete ntrk; delete ptrk; continue;}
if ((xn+xp) < 2*fRmin) {delete ntrk; delete ptrk; continue;}
ntrk->PropagateTo(xn,b); // check this
ptrk->PropagateTo(xp,b);
AliESDv0 vertex(*ntrk,i,*ptrk,k);
if (vertex.GetChi2V0() > fChi2max) continue;
Double_t x = vertex.Xv(), y=vertex.Yv(), z=vertex.Zv();
Double_t r2 = x*x + y*y;
if (r2 < fRmin*fRmin) {delete ntrk; delete ptrk; continue;}
if (r2 > fRmax*fRmax) {delete ntrk; delete ptrk; continue;}
Double_t v0DecayLength = TMath::Sqrt(TMath::Power(x - primVtx[0],2) +
TMath::Power(y - primVtx[1],2) +
TMath::Power(z - primVtx[2],2 ));
Float_t cpa = vertex.GetV0CosineOfPointingAngle(primVtx[0],primVtx[1],primVtx[2]);
const Double_t pThr=1.5;
Double_t pv0 = vertex.P();
if (!fRevertex && pv0<pThr)
{
//Below the threshold "pThr", try a momentum dependent cos(PA) cut
const Double_t bend=0.03; // approximate Xi bending angle
const Double_t qt=0.211; // max Lambda pT in Omega decay
const Double_t cpaThr=TMath::Cos(TMath::ATan(qt/pThr) + bend);
Double_t
cpaCut=(fCPAmin/cpaThr)*TMath::Cos(TMath::ATan(qt/pv0) + bend);
if (cpa < cpaCut) {delete ntrk; delete ptrk; continue;}
}
else
{
if (cpa < fCPAmin) {delete ntrk; delete ptrk; continue;}
}
vertex.SetV0CosineOfPointingAngle(cpa);
vertex.SetDcaV0Daughters(dca);
if(!V0CutsForTreeESD(&vertex,primVtx,ptrk,ntrk,b)) {delete ntrk; delete ptrk; continue;}
Float_t nd[2] = {0,0};
Float_t pd[2] = {0,0};
ntrk->GetDZ(primVtx[0],primVtx[1],primVtx[2],b,nd);
ptrk->GetDZ(primVtx[0],primVtx[1],primVtx[2],b,pd);
Double_t alpha = vertex.AlphaV0();
Double_t ptarm = vertex.PtArmV0();
AliLightV0 *tempLightV0L = 0x0;
AliLightV0 *tempLightV0AL = 0x0;
if(vertex.GetEffMass(4,2) < 1.16 && TMath::Abs(pnsigmapr) < 5.) // mixed lambda candidate
{
tempLightV0L = new((*fv0s)[fv0s->GetEntriesFast()]) AliLightV0(vertex.Pt(),vertex.Eta());
tempLightV0L->SetInvMass(vertex.GetEffMass(4,2));
tempLightV0L->SetInvMassK0S(vertex.GetEffMass(2,2));
tempLightV0L->SetInvMassGamma(vertex.GetEffMass(0,0));
tempLightV0L->SetCosPointingAngle(cpa);
tempLightV0L->SetDecayR(TMath::Sqrt(r2));
tempLightV0L->SetProperLifetime(vertex.P() > 0. ? vertex.GetEffMass(4,2)*v0DecayLength/vertex.P() : 0.);
tempLightV0L->SetDCADaughters(dca);
tempLightV0L->SetArmPodVars(ptarm,alpha);
tempLightV0L->SetMcStatus(0);
tempLightV0L->SetPosDaughter(ptrk->Pt(),ptrk->Eta(),pnsigmapr,TMath::Sqrt(pd[0]*pd[0]+pd[1]*pd[1]));
tempLightV0L->SetNegDaughter(ntrk->Pt(),ntrk->Eta(),nnsigmapr,TMath::Sqrt(nd[0]*nd[0]+nd[1]*nd[1]));
//Printf("B id1 = %i id2 = %i pt = %.3lf eta = %.3lf minv = %.3lf cosPA = %.3lf decayR = %.3lf propLife = %.3lf DCAdaughters = %.3lf",((AliLightV0track*)ev1->At(i))->GetMcLabel(),((AliLightV0track*)ev2->At(k))->GetMcLabel(),vertex.Pt(),vertex.Eta(),vertex.GetEffMass(4,2),cpa,TMath::Sqrt(r2),vertex.GetEffMass(4,2)*v0DecayLength/vertex.P(),dca);
//Printf(" posPt = %.3lf posDCA = %.3lf posNSigma = %.3lf posD = %.3lf negPt = %.3lf negDCA = %.3lf negNSigma = %.3lf negD = %.3lf",ptrk->Pt(),TMath::Sqrt(pd[0]*pd[0]+pd[1]*pd[1]),pnsigmapr,ptrk->GetD(primVtx[0],primVtx[1],b),ntrk->Pt(),TMath::Sqrt(nd[0]*nd[0]+nd[1]*nd[1]),nnsigmapr,ntrk->GetD(primVtx[0],primVtx[1],b));
}
if(vertex.GetEffMass(2,4) < 1.16 && TMath::Abs(nnsigmapr) < 5.) // mixed anti-lambda candidate
{
tempLightV0AL = new((*fv0s)[fv0s->GetEntriesFast()]) AliLightV0(vertex.Pt(),vertex.Eta());
tempLightV0AL->SetInvMass(-1.*vertex.GetEffMass(2,4));
tempLightV0AL->SetInvMassK0S(vertex.GetEffMass(2,2));
tempLightV0AL->SetInvMassGamma(vertex.GetEffMass(0,0));
tempLightV0AL->SetCosPointingAngle(cpa);
tempLightV0AL->SetDecayR(TMath::Sqrt(r2));
tempLightV0AL->SetProperLifetime(vertex.P() > 0. ? vertex.GetEffMass(2,4)*v0DecayLength/vertex.P() : 0.);
tempLightV0AL->SetDCADaughters(dca);
tempLightV0AL->SetArmPodVars(ptarm,alpha);
tempLightV0AL->SetMcStatus(0);
tempLightV0AL->SetPosDaughter(ptrk->Pt(),ptrk->Eta(),pnsigmapr,TMath::Sqrt(pd[0]*pd[0]+pd[1]*pd[1]));
tempLightV0AL->SetNegDaughter(ntrk->Pt(),ntrk->Eta(),nnsigmapr,TMath::Sqrt(nd[0]*nd[0]+nd[1]*nd[1]));
//Printf("B id1 = %i id2 = %i pt = %.3lf eta = %.3lf minv = %.3lf cosPA = %.3lf decayR = %.3lf propLife = %.3lf DCAdaughters = %.3lf",((AliLightV0track*)ev1->At(i))->GetMcLabel(),((AliLightV0track*)ev2->At(k))->GetMcLabel(),vertex.Pt(),vertex.Eta(),vertex.GetEffMass(2,4),cpa,TMath::Sqrt(r2),vertex.GetEffMass(2,4)*v0DecayLength/vertex.P(),dca);
//Printf(" posPt = %.3lf posDCA = %.3lf posNSigma = %.3lf posD = %.3lf negPt = %.3lf negDCA = %.3lf negNSigma = %.3lf negD = %.3lf",ptrk->Pt(),TMath::Sqrt(pd[0]*pd[0]+pd[1]*pd[1]),pnsigmapr,ptrk->GetD(primVtx[0],primVtx[1],b),ntrk->Pt(),TMath::Sqrt(nd[0]*nd[0]+nd[1]*nd[1]),nnsigmapr,ntrk->GetD(primVtx[0],primVtx[1],b));
}
if(!mixing && fIsMC && (tempLightV0L || tempLightV0AL)) IsGenLambda(pmclabel, nmclabel, tempLightV0L, tempLightV0AL,vertex.Pt(),vertex.GetEffMass(4,2),vertex.GetEffMass(2,4));
}
}
return;
}
Bool_t AliAnalysisTaskNetLambdaIdent::TrackCutsForTreeAOD(AliAODTrack* trk)
{
if(TMath::Abs(trk->Eta()) > 1.) return kFALSE;
if(trk->Pt() < 0.15) return kFALSE;
if(trk->GetTPCNCrossedRows() < ncrossedrowscut) return kFALSE;
if(trk->GetTPCNclsF() <= 0) return kFALSE;
if(trk->GetTPCNCrossedRows()/Float_t(trk->GetTPCNclsF()) < crossedrowsclustercut) return kFALSE;
return kTRUE;
}
Bool_t AliAnalysisTaskNetLambdaIdent::TrackCutsForTreeESD(AliESDtrack* trk)
{
if(TMath::Abs(trk->Eta()) > 1.) return kFALSE;
if(trk->Pt() < 0.15) return kFALSE;
if(trk->GetTPCCrossedRows() < ncrossedrowscut) return kFALSE;
if(trk->GetTPCNclsF() <= 0) return kFALSE;
if(trk->GetTPCCrossedRows()/Float_t(trk->GetTPCNclsF()) < crossedrowsclustercut) return kFALSE;
return kTRUE;
}
Bool_t AliAnalysisTaskNetLambdaIdent::V0CutsForTreeAOD(AliAODv0* v0, Double_t* vt)
{
if(v0->Pt() < ptminlambda) return kFALSE;
if(TMath::Abs(v0->Eta()) > etacutlambda) return kFALSE;
if(v0->CosPointingAngle(vt) < fCPAmin) return kFALSE;
if(v0->DcaV0Daughters() > fDCAmax) return kFALSE; // these are default cuts from AODs
if(v0->DcaPosToPrimVertex() < fDmin) return kFALSE;
if(v0->DcaNegToPrimVertex() < fDmin) return kFALSE;
Double_t sv[3];
v0->GetSecondaryVtx()->GetPosition(sv);
Float_t v0Radius2 = sv[0]*sv[0]+sv[1]*sv[1];
if(v0Radius2 < fRmin*fRmin) return kFALSE;
if(v0Radius2 > fRmax*fRmax) return kFALSE;
return kTRUE;
}
Bool_t AliAnalysisTaskNetLambdaIdent::V0CutsForTreeESD(AliESDv0* v0, Double_t* vt, AliExternalTrackParam* ptrk, AliExternalTrackParam* ntrk, Double_t b)
{
if(v0->Pt() < ptminlambda) return kFALSE;
if(TMath::Abs(v0->Eta()) > etacutlambda) return kFALSE;
if(v0->GetV0CosineOfPointingAngle() < fCPAmin) return kFALSE;
if(v0->GetDcaV0Daughters() > fDCAmax) return kFALSE; // these are default cuts from AODs
Float_t nd[2] = {0,0};
Float_t pd[2] = {0,0};
ntrk->GetDZ(vt[0],vt[1],vt[2],b,nd);
ptrk->GetDZ(vt[0],vt[1],vt[2],b,pd);
if(pd[0]*pd[0]+pd[1]*pd[1] < fDmin*fDmin) return kFALSE;
if(nd[0]*nd[0]+nd[1]*nd[1] < fDmin*fDmin) return kFALSE;
Double_t sv[3] = {0,0,0};
v0->GetXYZ(sv[0], sv[1], sv[2]);
Float_t v0Radius2 = sv[0]*sv[0]+sv[1]*sv[1];
if(v0Radius2 < fRmin*fRmin) return kFALSE;
if(v0Radius2 > fRmax*fRmax) return kFALSE;
return kTRUE;
}
void AliAnalysisTaskNetLambdaIdent::IsGenLambda(Int_t poslabel, Int_t neglabel, AliLightV0* tempLightV0L, AliLightV0* tempLightV0AL, Float_t pt, Float_t invMassLambda, Float_t invMassAntiLambda)
{
Int_t mpid = -999, pid1 = -999, pid2 = -999;
Float_t mpt = -999, meta = -999;
Bool_t isPrim = kFALSE, isSecFromMaterial = kFALSE, isSecFromWeakDecay = kFALSE;
Float_t cascpt = -999, casceta = -999;
Int_t nGen = 0;
if(fIsAOD) // aod
{
nGen = fMCEvent->GetNumberOfTracks();
if(poslabel >= nGen || neglabel >= nGen) return;
AliAODMCParticle *aodGenTrackPos = (AliAODMCParticle*)fMCEvent->GetTrack(poslabel);
if(!aodGenTrackPos) return;
AliAODMCParticle *aodGenTrackNeg = (AliAODMCParticle*)fMCEvent->GetTrack(neglabel);
if(!aodGenTrackNeg) return;
Int_t m1 = aodGenTrackPos->GetMother();
if(m1 < 0) return;
Int_t m2 = aodGenTrackNeg->GetMother();
if(m2 < 0) return;
if(m1 != m2) return;
pid1 = aodGenTrackPos->GetPdgCode();
pid2 = aodGenTrackNeg->GetPdgCode();
AliVParticle *aodTestMother = fMCEvent->GetTrack(m1);
if(!aodTestMother) return;
mpid = aodTestMother->PdgCode();
mpt = aodTestMother->Pt();
meta = aodTestMother->Eta();
isSecFromMaterial = aodTestMother->IsSecondaryFromMaterial();
isSecFromWeakDecay = aodTestMother->IsSecondaryFromWeakDecay();
isPrim = aodTestMother->IsPhysicalPrimary();
if(mpid == 3122 || mpid == -3122)
{
if(isSecFromWeakDecay)
{
Int_t gm = aodTestMother->GetMother();
if(gm >= 0)
{
AliVParticle *aodGrandmother = fMCEvent->GetTrack(gm);
if(aodGrandmother)
{
if(aodGrandmother->IsPhysicalPrimary())
{
Int_t gmpid = aodGrandmother->PdgCode();
if(gmpid == 3322 || gmpid == -3322) // xi0
{
cascpt = -1.*aodGrandmother->Pt();
casceta = aodGrandmother->Eta();
}
if(gmpid == 3312 || gmpid == -3312) // xi+, xi-
{
cascpt = aodGrandmother->Pt();
casceta = aodGrandmother->Eta();
}
}
}
}
}
}
}
else // esd
{
nGen = stack->GetNtrack();
if(poslabel >= nGen || neglabel >= nGen) return;
TParticle *esdGenTrackPos = (TParticle*)stack->Particle(poslabel);
if(!esdGenTrackPos) return;
TParticle *esdGenTrackNeg = (TParticle*)stack->Particle(neglabel);
if(!esdGenTrackNeg) return;
Int_t m1 = esdGenTrackPos->GetMother(0);
if(m1 < 0) return;
Int_t m2 = esdGenTrackNeg->GetMother(0);
if(m2 < 0) return;
Int_t gm1 = stack->Particle(m1)->GetMother(0);
Int_t gm2 = stack->Particle(m2)->GetMother(0);
if(gm1 == m2 && gm1 >= 0)
{
TParticle *esdMother1 = stack->Particle(m1);
TParticle *esdMother2 = stack->Particle(m2);
TParticle *esdGrandmother1 = stack->Particle(gm1);
if(esdMother1)
if(esdMother2)
if(esdGrandmother1)
{
//Printf("%i-->%i-->%i, %i-->%i",esdGrandmother1->GetPdgCode(),esdMother1->GetPdgCode(),esdGenTrackPos->GetPdgCode(),esdMother2->GetPdgCode(),esdGenTrackNeg->GetPdgCode());
if(esdGrandmother1->GetPdgCode() == 3312)
{
hInvMassLambdaMPidPt->Fill(invMassLambda,25,pt);
hInvMassAntiLambdaMPidPt->Fill(invMassAntiLambda,25,pt);
}
else if(esdGrandmother1->GetPdgCode() == -3312)
{
hInvMassLambdaMPidPt->Fill(invMassLambda,26,pt);
hInvMassAntiLambdaMPidPt->Fill(invMassAntiLambda,26,pt);
}
}
}
if(gm2 == m1 && gm2 >= 0)
{
TParticle *esdMother1 = stack->Particle(m1);
TParticle *esdMother2 = stack->Particle(m2);
TParticle *esdGrandmother2 = stack->Particle(gm2);
if(esdMother1)
if(esdMother2)
if(esdGrandmother2)
{
//Printf("%i-->%i-->%i, %i-->%i",esdGrandmother2->GetPdgCode(),esdMother2->GetPdgCode(),esdGenTrackNeg->GetPdgCode(),esdMother1->GetPdgCode(),esdGenTrackPos->GetPdgCode());
if(esdGrandmother2->GetPdgCode() == 3312)
{
hInvMassLambdaMPidPt->Fill(invMassLambda,25,pt);
hInvMassAntiLambdaMPidPt->Fill(invMassAntiLambda,25,pt);
}
else if(esdGrandmother2->GetPdgCode() == -3312)
{
hInvMassLambdaMPidPt->Fill(invMassLambda,26,pt);
hInvMassAntiLambdaMPidPt->Fill(invMassAntiLambda,26,pt);
}
}
}
if(m1 != m2) return;
pid1 = esdGenTrackPos->GetPdgCode();
pid2 = esdGenTrackNeg->GetPdgCode();
TParticle *esdTestMother = stack->Particle(m1);
if(!esdTestMother) return;
mpid = esdTestMother->GetPdgCode();
mpt = esdTestMother->Pt();
meta = esdTestMother->Eta();
isSecFromMaterial = stack->IsSecondaryFromMaterial(m1);
isSecFromWeakDecay = stack->IsSecondaryFromWeakDecay(m1);
isPrim = stack->IsPhysicalPrimary(m1);
if(mpid == 3122 || mpid == -3122)
{
if(isSecFromWeakDecay)
{
Int_t gm1 = esdTestMother->GetMother(0);
if(gm1 >= 0)
{
TParticle *esdGrandmother = stack->Particle(gm1);
if(esdGrandmother)
{
if(stack->IsPhysicalPrimary(gm1))
{
Int_t gmpid = esdGrandmother->GetPdgCode();
if(gmpid == 3322 || gmpid == -3322) // xi0
{
cascpt = -1.*esdGrandmother->Pt();
casceta = esdGrandmother->Eta();
}
if(gmpid == 3312 || gmpid == -3312) // xi+, xi-
{
cascpt = esdGrandmother->Pt();
casceta = esdGrandmother->Eta();
}
}
}
}
}
}
}
Int_t mpidind = 0;
for(Int_t p = 0; p < 24; p++)
{
if(mpid == pidVals[p]){mpidind = p+1; break;}
}
if(mpidind == 0) Printf("unknown mother = %i",mpid);
hInvMassLambdaMPidPt->Fill(invMassLambda,mpidind,pt);
hInvMassAntiLambdaMPidPt->Fill(invMassAntiLambda,mpidind,pt);
//if(mpid == 310) Printf("daughter pid = %i %i, invMassL = %.3lf, invMassAL = %.3lf, invmassG = %.3lf, decay radius = %.3lf",pid1,pid2,invMassLambda,invMassAntiLambda,invMassEplusEminus,v0Radius);
if(TMath::Abs(mpid) != 3122) return;
Int_t mcstatus = 1;
if(TMath::Abs(meta) > etacutlambda) mcstatus += 10; //mcstatus > 10 means it falls outside acceptance
if(isSecFromMaterial)
{
mcstatus += 1; // mcstatus = 3 means secondary from material
if(mpid == 3122)
hInvMassLambdaSecFromMaterial->Fill(invMassLambda,pt);
if(mpid == -3122)
hInvMassAntiLambdaSecFromMaterial->Fill(invMassAntiLambda,pt);
}
if(isSecFromWeakDecay)
{
mcstatus += 2; // mcstatus = 4 means secondary from weak decay
if(mpid == 3122)
{
hInvMassLambdaSecFromWeakDecay->Fill(invMassLambda,pt);
if(tempLightV0L) tempLightV0L->SetCascadePtEta(cascpt,casceta);
}
if(mpid == -3122)
{
hInvMassAntiLambdaSecFromWeakDecay->Fill(invMassAntiLambda,pt);
if(tempLightV0AL) tempLightV0AL->SetCascadePtEta(cascpt,casceta);
}
}
//if(!(stack->IsPhysicalPrimary(m1))) return;
if(!isPrim) mcstatus += 1; // mcstatus = 2 means secondary
if(tempLightV0L) tempLightV0L->SetGenPtEta(mpt,meta);
if(tempLightV0AL) tempLightV0AL->SetGenPtEta(mpt,meta);
if(mpid == 3122)
{
if(tempLightV0L) tempLightV0L->SetMcStatus(mcstatus);
hPtResLambda->Fill(mpt,pt);
if(isPrim) hPtResLambdaPrim->Fill(mpt,pt);
if(TMath::Abs(meta) <= etacutlambda)
{
hLambdaPtReco->Fill(mpt);
hInvMassLambdaReco->Fill(invMassLambda,pt);
}
}
else if(mpid == -3122)
{
if(tempLightV0AL) tempLightV0AL->SetMcStatus(-1*mcstatus); // mcstatus < 0 means antilambda
hPtResAntiLambda->Fill(mpt,pt);
if(isPrim) hPtResAntiLambdaPrim->Fill(mpt,pt);
if(TMath::Abs(meta) <= etacutlambda)
{
hAntiLambdaPtReco->Fill(mpt);
hInvMassAntiLambdaReco->Fill(invMassAntiLambda,pt);
}
}
}
| 39.720579
| 503
| 0.645634
|
vfilova
|
fed36904f2fc71038820c11a975dd5e84661f9b9
| 10,657
|
hpp
|
C++
|
include/ouchilib/crypto/algorithm/aes.hpp
|
ouchiminh/ouchilib
|
de1bab0aa75c9e567ce06d76c95bc330dffbf52e
|
[
"MIT"
] | 1
|
2019-06-11T05:22:54.000Z
|
2019-06-11T05:22:54.000Z
|
include/ouchilib/crypto/algorithm/aes.hpp
|
ouchiminh/ouchilib
|
de1bab0aa75c9e567ce06d76c95bc330dffbf52e
|
[
"MIT"
] | 1
|
2019-10-30T14:33:37.000Z
|
2019-10-31T15:01:09.000Z
|
include/ouchilib/crypto/algorithm/aes.hpp
|
ouchiminh/ouchilib
|
de1bab0aa75c9e567ce06d76c95bc330dffbf52e
|
[
"MIT"
] | null | null | null |
#pragma once
#include <cstdlib>
#include <cstdint>
#include <cstring>
#include <utility>
#include "ouchilib/utl/step.hpp"
#include "../common.hpp"
namespace ouchi::crypto {
inline constexpr std::uint32_t rotword(std::uint32_t in) {
return rotl(in, 8);
}
static_assert(rotword(0x00112233) == 0x11223300);
inline std::uint32_t mul(std::uint32_t dt, std::uint32_t n)
{
std::uint32_t x = 0;
for (auto i = 8u; i>0; i >>= 1) {
x <<= 1;
if (x & 0x100)
x = (x ^ 0x1b) & 0xff;
if ((n & i))
x ^= dt;
}
return(x);
}
inline std::uint32_t dataget(void * data, std::uint32_t n) {
return (reinterpret_cast<std::uint8_t*>(data)[n]);
}
template<size_t KeyLength> // size in byte : 16,24,32
struct aes {
static_assert(KeyLength == 16 || KeyLength == 24 || KeyLength == 32);
static constexpr size_t nb = 4;
static constexpr size_t nr = KeyLength / 4 + 6;
static constexpr size_t block_size = 4 * nb;
using block_t = memory_view<block_size>;
using key_t = memory_entity<KeyLength>;
using key_view = memory_view<KeyLength>;
static constexpr std::uint8_t sbox[256] = {
0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
0xb7,0xfd,0x93,0x26,0x36,0x3f,0xf7,0xcc,0x34,0xa5,0xe5,0xf1,0x71,0xd8,0x31,0x15,
0x04,0xc7,0x23,0xc3,0x18,0x96,0x05,0x9a,0x07,0x12,0x80,0xe2,0xeb,0x27,0xb2,0x75,
0x09,0x83,0x2c,0x1a,0x1b,0x6e,0x5a,0xa0,0x52,0x3b,0xd6,0xb3,0x29,0xe3,0x2f,0x84,
0x53,0xd1,0x00,0xed,0x20,0xfc,0xb1,0x5b,0x6a,0xcb,0xbe,0x39,0x4a,0x4c,0x58,0xcf,
0xd0,0xef,0xaa,0xfb,0x43,0x4d,0x33,0x85,0x45,0xf9,0x02,0x7f,0x50,0x3c,0x9f,0xa8,
0x51,0xa3,0x40,0x8f,0x92,0x9d,0x38,0xf5,0xbc,0xb6,0xda,0x21,0x10,0xff,0xf3,0xd2,
0xcd,0x0c,0x13,0xec,0x5f,0x97,0x44,0x17,0xc4,0xa7,0x7e,0x3d,0x64,0x5d,0x19,0x73,
0x60,0x81,0x4f,0xdc,0x22,0x2a,0x90,0x88,0x46,0xee,0xb8,0x14,0xde,0x5e,0x0b,0xdb,
0xe0,0x32,0x3a,0x0a,0x49,0x06,0x24,0x5c,0xc2,0xd3,0xac,0x62,0x91,0x95,0xe4,0x79,
0xe7,0xc8,0x37,0x6d,0x8d,0xd5,0x4e,0xa9,0x6c,0x56,0xf4,0xea,0x65,0x7a,0xae,0x08,
0xba,0x78,0x25,0x2e,0x1c,0xa6,0xb4,0xc6,0xe8,0xdd,0x74,0x1f,0x4b,0xbd,0x8b,0x8a,
0x70,0x3e,0xb5,0x66,0x48,0x03,0xf6,0x0e,0x61,0x35,0x57,0xb9,0x86,0xc1,0x1d,0x9e,
0xe1,0xf8,0x98,0x11,0x69,0xd9,0x8e,0x94,0x9b,0x1e,0x87,0xe9,0xce,0x55,0x28,0xdf,
0x8c,0xa1,0x89,0x0d,0xbf,0xe6,0x42,0x68,0x41,0x99,0x2d,0x0f,0xb0,0x54,0xbb,0x16
};
static constexpr std::uint8_t inv_sbox[256] = {
0x52,0x09,0x6a,0xd5,0x30,0x36,0xa5,0x38,0xbf,0x40,0xa3,0x9e,0x81,0xf3,0xd7,0xfb,
0x7c,0xe3,0x39,0x82,0x9b,0x2f,0xff,0x87,0x34,0x8e,0x43,0x44,0xc4,0xde,0xe9,0xcb,
0x54,0x7b,0x94,0x32,0xa6,0xc2,0x23,0x3d,0xee,0x4c,0x95,0x0b,0x42,0xfa,0xc3,0x4e,
0x08,0x2e,0xa1,0x66,0x28,0xd9,0x24,0xb2,0x76,0x5b,0xa2,0x49,0x6d,0x8b,0xd1,0x25,
0x72,0xf8,0xf6,0x64,0x86,0x68,0x98,0x16,0xd4,0xa4,0x5c,0xcc,0x5d,0x65,0xb6,0x92,
0x6c,0x70,0x48,0x50,0xfd,0xed,0xb9,0xda,0x5e,0x15,0x46,0x57,0xa7,0x8d,0x9d,0x84,
0x90,0xd8,0xab,0x00,0x8c,0xbc,0xd3,0x0a,0xf7,0xe4,0x58,0x05,0xb8,0xb3,0x45,0x06,
0xd0,0x2c,0x1e,0x8f,0xca,0x3f,0x0f,0x02,0xc1,0xaf,0xbd,0x03,0x01,0x13,0x8a,0x6b,
0x3a,0x91,0x11,0x41,0x4f,0x67,0xdc,0xea,0x97,0xf2,0xcf,0xce,0xf0,0xb4,0xe6,0x73,
0x96,0xac,0x74,0x22,0xe7,0xad,0x35,0x85,0xe2,0xf9,0x37,0xe8,0x1c,0x75,0xdf,0x6e,
0x47,0xf1,0x1a,0x71,0x1d,0x29,0xc5,0x89,0x6f,0xb7,0x62,0x0e,0xaa,0x18,0xbe,0x1b,
0xfc,0x56,0x3e,0x4b,0xc6,0xd2,0x79,0x20,0x9a,0xdb,0xc0,0xfe,0x78,0xcd,0x5a,0xf4,
0x1f,0xdd,0xa8,0x33,0x88,0x07,0xc7,0x31,0xb1,0x12,0x10,0x59,0x27,0x80,0xec,0x5f,
0x60,0x51,0x7f,0xa9,0x19,0xb5,0x4a,0x0d,0x2d,0xe5,0x7a,0x9f,0x93,0xc9,0x9c,0xef,
0xa0,0xe0,0x3b,0x4d,0xae,0x2a,0xf5,0xb0,0xc8,0xeb,0xbb,0x3c,0x83,0x53,0x99,0x61,
0x17,0x2b,0x04,0x7e,0xba,0x77,0xd6,0x26,0xe1,0x69,0x14,0x63,0x55,0x21,0x0c,0x7d
};
aes(key_view key) {
set_key(key);
}
aes() = default;
~aes()
{
secure_memset(key_.data, 0);
secure_memset(w_, 0);
}
void set_key(key_view key) noexcept
{
std::memcpy(key_.data, key.data, KeyLength);
expand_key();
}
void encrypt(block_t src, void* dest) const noexcept
{
std::memmove(dest, src.data, block_size);
add_roundkey(dest, 0);
for (auto i = 1u; i < nr; ++i) {
sub_bytes(dest);
shift_rows(dest);
mix_columns(dest);
add_roundkey(dest, i);
}
sub_bytes(dest);
shift_rows(dest);
add_roundkey(dest, nr);
}
void decrypt(block_t src, void* dest) const noexcept
{
std::memmove(dest, src.data, block_size);
add_roundkey(dest, (unsigned)nr);
unsigned i;
for (i = nr - 1; i > 0; i--) {
inv_shift_rows(dest);
inv_sub_bytes(dest);
add_roundkey(dest, (int)i);
inv_mix_columns(dest);
}
inv_shift_rows(dest);
inv_sub_bytes(dest);
add_roundkey(dest, 0);
}
static std::uint32_t subword(std::uint32_t in) noexcept
{
uint32_t inw = in;
unsigned char* cin = (unsigned char*)&inw;
cin[0] = sbox[cin[0]];
cin[1] = sbox[cin[1]];
cin[2] = sbox[cin[2]];
cin[3] = sbox[cin[3]];
return (inw);
}
static constexpr std::uint8_t subchar(std::uint8_t in) noexcept
{
return sbox[in];
}
private:
void expand_key() noexcept
{
constexpr std::uint32_t Rcon[10] = {
0x0100'0000,0x0200'0000,0x0400'0000,0x0800'0000,0x100'00000,
0x2000'0000,0x4000'0000,0x8000'0000,0x1b00'0000,0x3600'0000 };
constexpr auto nk = KeyLength / 4;
size_t i;
for (i = 0u; i < nk; ++i) {
w_[i] = detail::pack<std::uint32_t>(key_.data + i * 4);
}
for (i = nk; i<nb*(nr + 1); ++i) {
std::uint32_t temp = w_[i - 1];
if ((i % nk) == 0)
temp = subword(rotword(temp)) ^ Rcon[i / nk - 1];
else if (nk > 6 && (i % nk) == 4)
temp = subword(temp);
w_[i] = w_[i - nk] ^ temp;
}
}
void add_roundkey(void* data, unsigned round) const noexcept
{
auto ptr = reinterpret_cast<std::uint8_t*>(data);
for (auto i : ouchi::step(4)) {
detail::unpack(detail::pack<std::uint32_t>(ptr + i * 4) ^ w_[i + round * 4],
ptr + i * 4);
}
}
static void sub_bytes(void* data) noexcept
{
unsigned char* cb = static_cast<std::uint8_t*>(data);
for (auto i : ouchi ::step(16)) {
cb[i] = sbox[cb[i]];
}
}
static void inv_sub_bytes(void* data) noexcept
{
unsigned char* cb = static_cast<std::uint8_t*>(data);
for (auto i : ouchi ::step(16)) {
cb[i] = inv_sbox[cb[i]];
}
}
static void shift_rows(void* data) noexcept
{
auto ptr{ static_cast<uint8_t*>(data) };
memory_entity<block_size> cw(data);
for (int i = 0; i<nb; i += 4) {
int i4 = i * 4;
for (int j = 1; j<4; j++) {
cw.data[i4 + j + 0 * 4] = ptr[i4 + j + ((j + 0) & 3) * 4];
cw.data[i4 + j + 1 * 4] = ptr[i4 + j + ((j + 1) & 3) * 4];
cw.data[i4 + j + 2 * 4] = ptr[i4 + j + ((j + 2) & 3) * 4];
cw.data[i4 + j + 3 * 4] = ptr[i4 + j + ((j + 3) & 3) * 4];
}
}
std::memcpy(data, cw.data, block_size);
}
static void inv_shift_rows(void* data) noexcept
{
auto ptr{ static_cast<uint8_t*>(data) };
memory_entity<block_size> cw(data);
for (int i = 0; i<nb; i += 4) {
int i4 = i * 4;
for (int j = 1; j<4; j++) {
cw.data[i4 + j + ((j + 0) & 3) * 4] = ptr[i4 + j + 0 * 4];
cw.data[i4 + j + ((j + 1) & 3) * 4] = ptr[i4 + j + 1 * 4];
cw.data[i4 + j + ((j + 2) & 3) * 4] = ptr[i4 + j + 2 * 4];
cw.data[i4 + j + ((j + 3) & 3) * 4] = ptr[i4 + j + 3 * 4];
}
}
std::memcpy(data, cw.data, block_size);
}
static void mix_columns(void* data) noexcept
{
std::uint32_t i4, x;
auto adata = static_cast<std::uint8_t*>(data);
for (auto i : ouchi::step((std::uint32_t)nb)) {
i4 = i * 4;
x = mul(dataget(adata, i4 + 0), 2) ^
mul(dataget(adata, i4 + 1), 3) ^
mul(dataget(adata, i4 + 2), 1) ^
mul(dataget(adata, i4 + 3), 1);
x |= (mul(dataget(adata, i4 + 1), 2) ^
mul(dataget(adata, i4 + 2), 3) ^
mul(dataget(adata, i4 + 3), 1) ^
mul(dataget(adata, i4 + 0), 1)) << 8;
x |= (mul(dataget(adata, i4 + 2), 2) ^
mul(dataget(adata, i4 + 3), 3) ^
mul(dataget(adata, i4 + 0), 1) ^
mul(dataget(adata, i4 + 1), 1)) << 16;
x |= (mul(dataget(adata, i4 + 3), 2) ^
mul(dataget(adata, i4 + 0), 3) ^
mul(dataget(adata, i4 + 1), 1) ^
mul(dataget(adata, i4 + 2), 1)) << 24;
std::memcpy(adata + i * 4, &x, sizeof(x));
}
}
static void inv_mix_columns(void* data) noexcept
{
std::uint32_t i4, x;
auto adata = static_cast<std::uint8_t*>(data);
for (auto i : ouchi::step((std::uint32_t)nb)) {
i4 = i * 4;
x = mul(dataget(adata, i4 + 0), 14) ^
mul(dataget(adata, i4 + 1), 11) ^
mul(dataget(adata, i4 + 2), 13) ^
mul(dataget(adata, i4 + 3), 9);
x |= (mul(dataget(adata, i4 + 1), 14) ^
mul(dataget(adata, i4 + 2), 11) ^
mul(dataget(adata, i4 + 3), 13) ^
mul(dataget(adata, i4 + 0), 9)) << 8;
x |= (mul(dataget(adata, i4 + 2), 14) ^
mul(dataget(adata, i4 + 3), 11) ^
mul(dataget(adata, i4 + 0), 13) ^
mul(dataget(adata, i4 + 1), 9)) << 16;
x |= (mul(dataget(adata, i4 + 3), 14) ^
mul(dataget(adata, i4 + 0), 11) ^
mul(dataget(adata, i4 + 1), 13) ^
mul(dataget(adata, i4 + 2), 9)) << 24;
std::memcpy(adata + i * 4, &x, sizeof(x));
}
}
key_t key_;
std::uint32_t w_[nb * (nr + 1)]; // expanded key
};
using aes128 = aes<16>;
using aes192 = aes<24>;
using aes256 = aes<32>;
}
| 38.472924
| 88
| 0.546683
|
ouchiminh
|
fedbac19f574b275988c8a19b137fe48ae95b4c0
| 6,301
|
cpp
|
C++
|
tests/report/enc/datetime.cpp
|
jbdelcuv/openenclave
|
c2e9cfabd788597f283c8dd39edda5837b1b1339
|
[
"MIT"
] | 617
|
2019-06-19T22:08:04.000Z
|
2022-03-25T09:21:03.000Z
|
tests/report/enc/datetime.cpp
|
jbdelcuv/openenclave
|
c2e9cfabd788597f283c8dd39edda5837b1b1339
|
[
"MIT"
] | 2,545
|
2019-06-18T21:46:10.000Z
|
2022-03-31T23:26:51.000Z
|
tests/report/enc/datetime.cpp
|
jbdelcuv/openenclave
|
c2e9cfabd788597f283c8dd39edda5837b1b1339
|
[
"MIT"
] | 292
|
2019-07-02T15:40:35.000Z
|
2022-03-27T13:27:10.000Z
|
// Copyright (c) Open Enclave SDK contributors.
// Licensed under the MIT License.
#include <openenclave/enclave.h>
#include <openenclave/internal/datetime.h>
#include <openenclave/internal/tests.h>
#include <stdio.h>
#include <string.h>
#include "../../../common/sgx/quote.h"
#include "tests_t.h"
void TestPositive(const oe_datetime_t& date_time, const char* expected)
{
char utc_string[21];
size_t length = sizeof(utc_string);
OE_TEST(oe_datetime_to_string(&date_time, utc_string, &length) == OE_OK);
OE_TEST(strcmp(utc_string, expected) == 0);
oe_datetime_t date_time_round_trip = {0};
OE_TEST(
oe_datetime_from_string(utc_string, length, &date_time_round_trip) ==
OE_OK);
OE_TEST(memcmp(&date_time, &date_time_round_trip, sizeof(date_time)) == 0);
}
void TestNegative(oe_datetime_t date_time, oe_result_t result)
{
char utc_string[21];
size_t length = sizeof(utc_string);
OE_TEST(oe_datetime_to_string(&date_time, utc_string, &length) == result);
}
void test_iso8601_time()
{
// Single digit fields
TestPositive(oe_datetime_t{2018, 8, 8, 0, 0, 0}, "2018-08-08T00:00:00Z");
// Double digit day
TestPositive(oe_datetime_t{2018, 8, 18, 0, 0, 0}, "2018-08-18T00:00:00Z");
// And double digit month
TestPositive(oe_datetime_t{2018, 12, 18, 0, 0, 0}, "2018-12-18T00:00:00Z");
// Single digit hours
TestPositive(oe_datetime_t{2018, 12, 18, 1, 0, 0}, "2018-12-18T01:00:00Z");
// And single digit minutes
TestPositive(oe_datetime_t{2018, 12, 18, 1, 1, 0}, "2018-12-18T01:01:00Z");
// And single digit seconds
TestPositive(oe_datetime_t{2018, 12, 18, 1, 1, 1}, "2018-12-18T01:01:01Z");
// Double digit seconds
TestPositive(oe_datetime_t{2018, 12, 18, 1, 1, 11}, "2018-12-18T01:01:11Z");
// And double digit minutes
TestPositive(
oe_datetime_t{2018, 12, 18, 1, 13, 11}, "2018-12-18T01:13:11Z");
// And double digit hours
TestPositive(
oe_datetime_t{2018, 12, 18, 21, 13, 11}, "2018-12-18T21:13:11Z");
// Max valid days for all months except February.
TestPositive(oe_datetime_t{2018, 1, 31, 0, 0, 0}, "2018-01-31T00:00:00Z");
TestPositive(oe_datetime_t{2018, 3, 31, 0, 0, 0}, "2018-03-31T00:00:00Z");
TestPositive(oe_datetime_t{2018, 4, 30, 0, 0, 0}, "2018-04-30T00:00:00Z");
TestPositive(oe_datetime_t{2018, 5, 31, 0, 0, 0}, "2018-05-31T00:00:00Z");
TestPositive(oe_datetime_t{2018, 6, 30, 0, 0, 0}, "2018-06-30T00:00:00Z");
TestPositive(oe_datetime_t{2018, 7, 31, 0, 0, 0}, "2018-07-31T00:00:00Z");
TestPositive(oe_datetime_t{2018, 8, 31, 0, 0, 0}, "2018-08-31T00:00:00Z");
TestPositive(oe_datetime_t{2018, 9, 30, 0, 0, 0}, "2018-09-30T00:00:00Z");
TestPositive(oe_datetime_t{2018, 10, 31, 0, 0, 0}, "2018-10-31T00:00:00Z");
TestPositive(oe_datetime_t{2018, 11, 30, 0, 0, 0}, "2018-11-30T00:00:00Z");
TestPositive(oe_datetime_t{2018, 12, 31, 0, 0, 0}, "2018-12-31T00:00:00Z");
// February. Non leap year.
TestPositive(oe_datetime_t{2018, 2, 28, 0, 0, 0}, "2018-02-28T00:00:00Z");
TestNegative(oe_datetime_t{2018, 2, 29, 0, 0, 0}, OE_INVALID_UTC_DATE_TIME);
// February. Leap year.
TestPositive(oe_datetime_t{2004, 2, 29, 0, 0, 0}, "2004-02-29T00:00:00Z");
// Divisible by 4 and 100 is not a leap year.
TestPositive(oe_datetime_t{2100, 2, 28, 0, 0, 0}, "2100-02-28T00:00:00Z");
TestNegative(oe_datetime_t{2100, 2, 29, 0, 0, 0}, OE_INVALID_UTC_DATE_TIME);
// Unless divisible by 400.
TestPositive(oe_datetime_t{2000, 2, 29, 0, 0, 0}, "2000-02-29T00:00:00Z");
// hours, minutes and seconds are zero based.
// Maximum possible value of hours, minutes and seconds.
TestPositive(
oe_datetime_t{2000, 2, 29, 23, 59, 59}, "2000-02-29T23:59:59Z");
oe_host_printf("TestIso8601Time passed\n");
}
void test_iso8601_time_negative()
{
// Year before unix epoch 1970.
TestNegative(oe_datetime_t{1969, 8, 8, 0, 0, 0}, OE_INVALID_UTC_DATE_TIME);
// Zero and 13 months
TestNegative(oe_datetime_t{2018, 0, 8, 0, 0, 0}, OE_INVALID_UTC_DATE_TIME);
TestNegative(oe_datetime_t{2018, 13, 8, 0, 0, 0}, OE_INVALID_UTC_DATE_TIME);
// Invalid hour, minutes, seconds.
TestNegative(oe_datetime_t{2018, 8, 8, 24, 0, 0}, OE_INVALID_UTC_DATE_TIME);
TestNegative(oe_datetime_t{2018, 8, 8, 0, 60, 0}, OE_INVALID_UTC_DATE_TIME);
TestNegative(oe_datetime_t{2018, 8, 8, 0, 0, 60}, OE_INVALID_UTC_DATE_TIME);
// Invalid days for all months except February.
TestNegative(oe_datetime_t{2018, 1, 32, 0, 0, 0}, OE_INVALID_UTC_DATE_TIME);
TestNegative(oe_datetime_t{2018, 3, 32, 0, 0, 0}, OE_INVALID_UTC_DATE_TIME);
TestNegative(oe_datetime_t{2018, 4, 31, 0, 0, 0}, OE_INVALID_UTC_DATE_TIME);
TestNegative(oe_datetime_t{2018, 5, 32, 0, 0, 0}, OE_INVALID_UTC_DATE_TIME);
TestNegative(oe_datetime_t{2018, 6, 31, 0, 0, 0}, OE_INVALID_UTC_DATE_TIME);
TestNegative(oe_datetime_t{2018, 7, 32, 0, 0, 0}, OE_INVALID_UTC_DATE_TIME);
TestNegative(oe_datetime_t{2018, 8, 32, 0, 0, 0}, OE_INVALID_UTC_DATE_TIME);
TestNegative(oe_datetime_t{2018, 9, 31, 0, 0, 0}, OE_INVALID_UTC_DATE_TIME);
TestNegative(
oe_datetime_t{2018, 10, 32, 0, 0, 0}, OE_INVALID_UTC_DATE_TIME);
TestNegative(
oe_datetime_t{2018, 11, 31, 0, 0, 0}, OE_INVALID_UTC_DATE_TIME);
TestNegative(
oe_datetime_t{2018, 12, 32, 0, 0, 0}, OE_INVALID_UTC_DATE_TIME);
// Normally Feb has max 28 days.
TestNegative(oe_datetime_t{2018, 2, 29, 0, 0, 0}, OE_INVALID_UTC_DATE_TIME);
// Zero day test.
TestNegative(oe_datetime_t{2018, 2, 0, 0, 0, 0}, OE_INVALID_UTC_DATE_TIME);
// A year divisible by 4 and 100 is not a leap year.
TestNegative(oe_datetime_t{2100, 2, 29, 0, 0, 0}, OE_INVALID_UTC_DATE_TIME);
// Unless divisible by 400
TestNegative(oe_datetime_t{2000, 2, 30, 0, 0, 0}, OE_INVALID_UTC_DATE_TIME);
// Invalid hours, minutes, seconds.
TestNegative(
oe_datetime_t{2000, 2, 29, 24, 0, 0}, OE_INVALID_UTC_DATE_TIME);
TestNegative(
oe_datetime_t{2000, 2, 29, 0, 60, 0}, OE_INVALID_UTC_DATE_TIME);
TestNegative(
oe_datetime_t{2000, 2, 29, 0, 0, 60}, OE_INVALID_UTC_DATE_TIME);
oe_host_printf("TestIso8601TimeNegative passed\n");
}
| 41.728477
| 80
| 0.679416
|
jbdelcuv
|
fedd42565c43c97d8076d5105b8d6f5d96c178a4
| 9,288
|
cpp
|
C++
|
lib/Modules.in.cpp
|
bastille-attic/SoapySDR
|
7976f888ea03d128bfc0c2ebe49ce8316ce9e2ea
|
[
"BSL-1.0"
] | 1
|
2021-03-04T07:02:11.000Z
|
2021-03-04T07:02:11.000Z
|
lib/Modules.in.cpp
|
bastille-attic/SoapySDR
|
7976f888ea03d128bfc0c2ebe49ce8316ce9e2ea
|
[
"BSL-1.0"
] | null | null | null |
lib/Modules.in.cpp
|
bastille-attic/SoapySDR
|
7976f888ea03d128bfc0c2ebe49ce8316ce9e2ea
|
[
"BSL-1.0"
] | null | null | null |
// Copyright (c) 2014-2016 Josh Blum
// SPDX-License-Identifier: BSL-1.0
#include <SoapySDR/Modules.hpp>
#include <SoapySDR/Logger.hpp>
#include <SoapySDR/Version.hpp>
#include <vector>
#include <string>
#include <cstdlib> //getenv
#include <sstream>
#include <map>
#ifdef _MSC_VER
#include <windows.h>
#else
#include <dlfcn.h>
#include <glob.h>
#endif
/***********************************************************************
* root installation path
**********************************************************************/
std::string getEnvImpl(const char *name)
{
#ifdef _MSC_VER
const DWORD len = GetEnvironmentVariableA(name, 0, 0);
if (len == 0) return "";
char* buffer = new char[len];
GetEnvironmentVariableA(name, buffer, len);
std::string result(buffer);
delete [] buffer;
return result;
#else
const char *result = getenv(name);
if (result != NULL) return result;
#endif
return "";
}
std::string SoapySDR::getRootPath(void)
{
const std::string rootPathEnv = getEnvImpl("@SOAPY_SDR_ROOT_ENV@");
if (not rootPathEnv.empty()) return rootPathEnv;
// Get the path to the current dynamic linked library.
// The path to this library can be used to determine
// the installation root without prior knowledge.
#ifdef _MSC_VER
char path[MAX_PATH];
HMODULE hm = NULL;
if (GetModuleHandleExA(
GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS |
GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
(LPCSTR) &SoapySDR::getRootPath, &hm))
{
const DWORD size = GetModuleFileNameA(hm, path, sizeof(path));
if (size != 0)
{
const std::string libPath(path, size);
const size_t slash0Pos = libPath.find_last_of("/\\");
const size_t slash1Pos = libPath.substr(0, slash0Pos).find_last_of("/\\");
if (slash0Pos != std::string::npos and slash1Pos != std::string::npos)
return libPath.substr(0, slash1Pos);
}
}
#endif
return "@SOAPY_SDR_ROOT@";
}
/***********************************************************************
* list modules API call
**********************************************************************/
static std::vector<std::string> searchModulePath(const std::string &path)
{
const std::string pattern = path + "*.*";
std::vector<std::string> modulePaths;
#ifdef _MSC_VER
//http://stackoverflow.com/questions/612097/how-can-i-get-a-list-of-files-in-a-directory-using-c-or-c
WIN32_FIND_DATA fd;
HANDLE hFind = ::FindFirstFile(pattern.c_str(), &fd);
if(hFind != INVALID_HANDLE_VALUE)
{
do
{
// read all (real) files in current folder
// , delete '!' read other 2 default folder . and ..
if(! (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) )
{
modulePaths.push_back(path + fd.cFileName);
}
}while(::FindNextFile(hFind, &fd));
::FindClose(hFind);
}
#else
glob_t globResults;
const int ret = glob(pattern.c_str(), 0/*no flags*/, NULL, &globResults);
if (ret == 0) for (size_t i = 0; i < globResults.gl_pathc; i++)
{
modulePaths.push_back(globResults.gl_pathv[i]);
}
else if (ret == GLOB_NOMATCH) {/* acceptable error condition, do not print error */}
else SoapySDR::logf(SOAPY_SDR_ERROR, "SoapySDR::listModules(%s) glob(%s) error %d", path.c_str(), pattern.c_str(), ret);
globfree(&globResults);
#endif
return modulePaths;
}
std::vector<std::string> SoapySDR::listSearchPaths(void)
{
//the default search path
std::vector<std::string> searchPaths;
searchPaths.push_back(SoapySDR::getRootPath() + "/lib@LIB_SUFFIX@/SoapySDR/modules" + SoapySDR::getABIVersion());
//support /usr/local module installs when the install prefix is /usr
if (SoapySDR::getRootPath() == "/usr")
{
searchPaths.push_back("/usr/local/lib@LIB_SUFFIX@/SoapySDR/modules" + SoapySDR::getABIVersion());
//when using a multi-arch directory, support single-arch path as well
static const std::string libsuffix("@LIB_SUFFIX@");
if (not libsuffix.empty() and libsuffix.at(0) == '/')
searchPaths.push_back("/usr/local/lib/SoapySDR/modules" + SoapySDR::getABIVersion());
}
//separator for search paths
#ifdef _MSC_VER
static const char sep = ';';
#else
static const char sep = ':';
#endif
//check the environment's search path
std::stringstream pluginPaths(getEnvImpl("SOAPY_SDR_PLUGIN_PATH"));
std::string pluginPath;
while (std::getline(pluginPaths, pluginPath, sep))
{
if (pluginPath.empty()) continue;
searchPaths.push_back(pluginPath);
}
return searchPaths;
}
std::vector<std::string> SoapySDR::listModules(void)
{
//traverse the search paths
std::vector<std::string> modules;
for (const auto &searchPath : SoapySDR::listSearchPaths())
{
const std::vector<std::string> subModules = SoapySDR::listModules(searchPath);
modules.insert(modules.end(), subModules.begin(), subModules.end());
}
return modules;
}
std::vector<std::string> SoapySDR::listModules(const std::string &path)
{
return searchModulePath(path + "/"); //requires trailing slash
}
/***********************************************************************
* load module API call
**********************************************************************/
std::map<std::string, void *> &getModuleHandles(void)
{
static std::map<std::string, void *> handles;
return handles;
}
//! share the module path during loadModule
std::string &getModuleLoading(void)
{
static std::string moduleLoading;
return moduleLoading;
}
//! share registration errors during loadModule
std::map<std::string, SoapySDR::Kwargs> &getLoaderResults(void)
{
static std::map<std::string, SoapySDR::Kwargs> results;
return results;
}
#ifdef _MSC_VER
static std::string GetLastErrorMessage(void)
{
LPVOID lpMsgBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
std::string msg((char *)lpMsgBuf);
LocalFree(lpMsgBuf);
return msg;
}
#endif
std::string SoapySDR::loadModule(const std::string &path)
{
//check if already loaded
if (getModuleHandles().count(path) != 0) return path + " already loaded";
//stash the path for registry access
getModuleLoading().assign(path);
//load the module
#ifdef _MSC_VER
//SetThreadErrorMode() - disable error pop-ups when DLLs are not found
DWORD oldMode;
SetThreadErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX, &oldMode);
HMODULE handle = LoadLibrary(path.c_str());
SetThreadErrorMode(oldMode, nullptr);
getModuleLoading().clear();
if (handle == NULL) return "LoadLibrary() failed: " + GetLastErrorMessage();
#else
void *handle = dlopen(path.c_str(), RTLD_LAZY);
getModuleLoading().clear();
if (handle == NULL) return "dlopen() failed: " + std::string(dlerror());
#endif
//stash the handle
getModuleHandles()[path] = handle;
return "";
}
SoapySDR::Kwargs SoapySDR::getLoaderResult(const std::string &path)
{
if (getLoaderResults().count(path) == 0) return SoapySDR::Kwargs();
return getLoaderResults()[path];
}
std::string SoapySDR::unloadModule(const std::string &path)
{
//check if already loaded
if (getModuleHandles().count(path) == 0) return path + " never loaded";
//stash the path for registry access
getModuleLoading().assign(path);
//unload the module
void *handle = getModuleHandles()[path];
#ifdef _MSC_VER
BOOL success = FreeLibrary((HMODULE)handle);
getModuleLoading().clear();
if (not success) return "FreeLibrary() failed: " + GetLastErrorMessage();
#else
int status = dlclose(handle);
getModuleLoading().clear();
if (status != 0) return "dlclose() failed: " + std::string(dlerror());
#endif
//clear the handle
getLoaderResults().erase(path);
getModuleHandles().erase(path);
return "";
}
/***********************************************************************
* load modules API call
**********************************************************************/
void lateLoadNullDevice(void);
void SoapySDR::loadModules(void)
{
static bool loaded = false;
if (loaded) return;
loaded = true;
lateLoadNullDevice();
const auto paths = listModules();
for (size_t i = 0; i < paths.size(); i++)
{
if (getModuleHandles().count(paths[i]) != 0) continue; //was manually loaded
const std::string errorMsg = loadModule(paths[i]);
if (not errorMsg.empty()) SoapySDR::logf(SOAPY_SDR_ERROR, "SoapySDR::loadModule(%s)\n %s", paths[i].c_str(), errorMsg.c_str());
for (const auto &it : SoapySDR::getLoaderResult(paths[i]))
{
if (it.second.empty()) continue;
SoapySDR::logf(SOAPY_SDR_ERROR, "SoapySDR::loadModule(%s)\n %s", paths[i].c_str(), it.second.c_str());
}
}
}
| 30.754967
| 136
| 0.612618
|
bastille-attic
|
fee0330c29683881624ff108e2fe55816e4ae2fc
| 1,256
|
cpp
|
C++
|
socket/src/socket_error.cpp
|
Clonkk/ezHttpServer
|
41299d480d8ef19c264d41fb0731f93edff2f6ea
|
[
"MIT"
] | 1
|
2018-01-20T08:40:10.000Z
|
2018-01-20T08:40:10.000Z
|
socket/src/socket_error.cpp
|
Clonkk/cpp11HttpServer
|
41299d480d8ef19c264d41fb0731f93edff2f6ea
|
[
"MIT"
] | null | null | null |
socket/src/socket_error.cpp
|
Clonkk/cpp11HttpServer
|
41299d480d8ef19c264d41fb0731f93edff2f6ea
|
[
"MIT"
] | null | null | null |
/*
* Copyright (C) 2017-2018 Régis Caillaud
*
* This source code is provided 'as-is', without any express or implied
* warranty. In no event will the author be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this source code must not be misrepresented; you must not
* claim that you wrote the original source code. If you use this source code
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original source code.
*
* 3. This notice may not be removed or altered from any source distribution.
*
*/
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <cstring>
#include <errno.h>
#include "socket_error.hpp"
socket_error::socket_error(const char* msg) :
std::exception()
{
snprintf(error_msg, 180, "%s : %s", msg, strerror(errno));
}
socket_error::~socket_error() {}
| 36.941176
| 79
| 0.710191
|
Clonkk
|
fee14cc9a8df9ac6ed581fc097296b6c758e6551
| 15,162
|
cpp
|
C++
|
hardware/src/display_monitor_andr.cpp
|
vinders/pandora_toolbox
|
f32e301ebaa2b281a1ffc3d6d0c556091420520a
|
[
"MIT"
] | 2
|
2020-11-19T03:23:35.000Z
|
2021-02-25T03:34:40.000Z
|
hardware/src/display_monitor_andr.cpp
|
vinders/pandora_toolbox
|
f32e301ebaa2b281a1ffc3d6d0c556091420520a
|
[
"MIT"
] | null | null | null |
hardware/src/display_monitor_andr.cpp
|
vinders/pandora_toolbox
|
f32e301ebaa2b281a1ffc3d6d0c556091420520a
|
[
"MIT"
] | null | null | null |
/*******************************************************************************
MIT License
Copyright (c) 2021 Romain Vinders
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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO 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.
--------------------------------------------------------------------------------
Description : Display monitor - Android implementation
*******************************************************************************/
#if !defined(_WINDOWS) && defined(__ANDROID__)
# include <cstdint>
# include <string>
# include <stdexcept>
# include <vector>
# include <system/api/android_app.h>
# include "hardware/_private/_libraries_andr.h"
# include "hardware/display_monitor.h"
using namespace pandora::hardware;
using pandora::system::AndroidApp;
// -- monitor attributes - id/area/description/primary -- ----------------------
namespace attributes {
// read primary screen area + density (screen position/size + work area + DPI/scale)
static inline void _readScreenAreaDensity(AndroidJavaSession& jenv, AndroidBindings& bindings,
jobject& activity, jobject& windowManager, jobject& display,
DisplayMonitor::Attributes& outAttr, DisplayMonitor::Density& outDensity) {
// WindowMetrics (API level >= 30)
if (bindings._windowMetrics.isAvailable) {
bindings.readDisplayDensity_wm(jenv, activity, display, outDensity);
bindings.readDisplayWorkArea_wm(jenv, windowManager, outAttr.workArea);
}
// DisplayMetrics (API level < 30)
else {
bindings.readDisplayDensity_dm(jenv, display, outDensity);
bindings.readDisplayWorkArea_dm(jenv, display, outAttr.workArea);
}
// work area: pixels to points
outAttr.workArea.x = static_cast<int32_t>( ((double)outAttr.workArea.x / outDensity.scale) + 0.500001);
outAttr.workArea.y = static_cast<int32_t>( ((double)outAttr.workArea.y / outDensity.scale) + 0.500001);
outAttr.workArea.width = static_cast<int32_t>( ((double)outAttr.workArea.width / outDensity.scale) + 0.500001);
outAttr.workArea.height = static_cast<int32_t>( ((double)outAttr.workArea.height / outDensity.scale) + 0.500001);
// screen area (points)
outAttr.screenArea.x = 0;
outAttr.screenArea.y = 0;
if (bindings._config.screenWidthDpValue > 0 && bindings._config.screenHeightDpValue > 0) {
outAttr.screenArea.width = bindings._config.screenWidthDpValue;
outAttr.screenArea.height = bindings._config.screenHeightDpValue;
}
else {
outAttr.screenArea.width = outAttr.workArea.width + outAttr.workArea.x;
outAttr.screenArea.height = outAttr.workArea.height + outAttr.workArea.y;
}
}
// read attributes and display modes of primary monitor
static DisplayMonitor::Handle readPrimary(AndroidJavaSession& jenv, DisplayMonitor::Attributes& outAttr,
DisplayMonitor::Density& outDensity) {
AndroidBindings& bindings = AndroidBindings::globalInstance();
bindings.bindDisplayClasses(jenv);
jobject activity = AndroidApp::instance().state().activity->clazz;
jobject windowManager = jenv.env().CallObjectMethod(activity, bindings._activity.getWindowManager); // windowManager = app.getWindowManager()
_P_THROW_ON_ACCESS_FAILURE(jenv, "window manager", windowManager);
jobject display = (bindings._windowMetrics.isAvailable)
? jenv.env().CallObjectMethod(activity, bindings._activity.getDisplay) // API level >= 30
: jenv.env().CallObjectMethod(windowManager, bindings._windowManager.getDefaultDisplay); // API level < 30
_P_THROW_ON_ACCESS_FAILURE(jenv, "display", display);
// read ID + primary
int displayId = jenv.env().CallIntMethod(display, bindings._display.getDisplayId); // displayId = display.getDisplayId()
_P_THROW_ON_FIELD_ACCESS_FAILURE(jenv, "display.getDisplayId");
if (displayId <= DEFAULT_DISPLAY) {
displayId = DEFAULT_DISPLAY; // 0
outAttr.id = "0";
outAttr.isPrimary = true;
}
else {
outAttr.id = std::to_string(displayId);
outAttr.isPrimary = false;
}
// read screen area + work area + density/DPI
::attributes::_readScreenAreaDensity(jenv, bindings, activity, windowManager, display, outAttr, outDensity);
// read description
jstring displayName = static_cast<jstring>(jenv.env().CallObjectMethod(display, bindings._display.getName)); // displayName = display.getName()
if (jenv.env().ExceptionCheck() || !AndroidBindings::jstringToString(jenv, displayName, outAttr.description)) {
jenv.env().ExceptionClear();
outAttr.description = std::string("Screen ") + outAttr.id;
}
return (DisplayMonitor::Handle)AndroidBindings::displayIdToHandle(displayId);
}
}
// -- contructors/list -- ------------------------------------------------------
DisplayMonitor::DisplayMonitor() {
AndroidJavaSession env;
this->_handle = attributes::readPrimary(env, this->_attributes, this->_density);
}
DisplayMonitor::DisplayMonitor(DisplayMonitor::Handle monitorHandle, bool usePrimaryAsDefault) {
AndroidJavaSession env;
this->_handle = attributes::readPrimary(env, this->_attributes, this->_density);
if (!usePrimaryAsDefault && this->_handle != monitorHandle)
throw std::invalid_argument("DisplayMonitor: monitor handle is invalid or can't be used.");
}
DisplayMonitor::DisplayMonitor(const DisplayMonitor::DeviceId& id, bool usePrimaryAsDefault) {
AndroidJavaSession env;
this->_handle = attributes::readPrimary(env, this->_attributes, this->_density);
if (!usePrimaryAsDefault && this->_attributes.id != id)
throw std::invalid_argument("DisplayMonitor: monitor ID was not found on system.");
}
DisplayMonitor::DisplayMonitor(bool usePrimaryAsDefault, uint32_t index) {
if (!usePrimaryAsDefault && index != 0) // currently only default screen supported (if available)
throw std::invalid_argument("DisplayMonitor: monitor index was not found on system.");
AndroidJavaSession env;
this->_handle = attributes::readPrimary(env, this->_attributes, this->_density);
}
std::vector<DisplayMonitor> DisplayMonitor::listAvailableMonitors() {
std::vector<DisplayMonitor> monitors;
try {
monitors.emplace_back(); // currently only default screen supported (if available)
}
catch (const std::bad_alloc&) { throw; }
catch (...) {} // ignore if display not available
return monitors;
}
// -- accessors -- -------------------------------------------------------------
DisplayMonitor::String DisplayMonitor::adapterName() const {
return ""; // not supported
}
// -- display modes -- ---------------------------------------------------------
DisplayMode DisplayMonitor::getDisplayMode() const noexcept {
DisplayMode mode;
try {
AndroidJavaSession jenv;
AndroidBindings& bindings = AndroidBindings::globalInstance(); // already bound in DisplayMonitor constructor
jobject activity = AndroidApp::instance().state().activity->clazz;
if (bindings._windowMetrics.isAvailable) { // API level >= 30
jobject display = jenv.env().CallObjectMethod(activity, bindings._activity.getDisplay); // display = activity.getDisplay()
_P_THROW_ON_ACCESS_FAILURE(jenv, "display", display);
bindings.readCurrentDisplayMode(jenv, display, mode);
}
else { // API level < 30
jobject windowManager = jenv.env().CallObjectMethod(activity, bindings._activity.getWindowManager); // windowManager = app.getWindowManager()
_P_THROW_ON_ACCESS_FAILURE(jenv, "window manager", windowManager);
jobject display = jenv.env().CallObjectMethod(windowManager, bindings._windowManager.getDefaultDisplay); // display = windowManager.getDefaultDisplay()
_P_THROW_ON_ACCESS_FAILURE(jenv, "display", display);
bindings.readCurrentDisplayMode(jenv, display, mode);
}
}
catch (...) { // on error, fill default mode
mode.width = this->_attributes.screenArea.width * this->_density.scale;
mode.height = this->_attributes.screenArea.height * this->_density.scale;
mode.bitDepth = 32;
mode.refreshRate = undefinedRefreshRate();
}
return mode;
}
bool DisplayMonitor::setDisplayMode(const DisplayMode& mode) {
try {
AndroidJavaSession jenv;
AndroidBindings& bindings = AndroidBindings::globalInstance(); // already bound in DisplayMonitor constructor
jobject activity = AndroidApp::instance().state().activity->clazz;
if (bindings._windowMetrics.isAvailable) { // API level >= 30
jobject display = jenv.env().CallObjectMethod(activity, bindings._activity.getDisplay); // display = activity.getDisplay()
_P_THROW_ON_ACCESS_FAILURE(jenv, "display", display);
bindings.setDisplayMode(jenv, activity, display, mode, this->_density);
}
else { // API level < 30
jobject windowManager = jenv.env().CallObjectMethod(activity, bindings._activity.getWindowManager); // windowManager = app.getWindowManager()
_P_THROW_ON_ACCESS_FAILURE(jenv, "window manager", windowManager);
jobject display = jenv.env().CallObjectMethod(windowManager, bindings._windowManager.getDefaultDisplay); // display = windowManager.getDefaultDisplay()
_P_THROW_ON_ACCESS_FAILURE(jenv, "display", display);
bindings.setDisplayMode(jenv, activity, display, mode, this->_density);
}
return true;
}
catch (...) { return false; }
}
bool DisplayMonitor::setDefaultDisplayMode() {
try {
AndroidJavaSession jenv;
AndroidBindings& bindings = AndroidBindings::globalInstance(); // already bound in DisplayMonitor constructor
jobject activity = AndroidApp::instance().state().activity->clazz;
if (bindings._windowMetrics.isAvailable) { // API level >= 30
jobject display = jenv.env().CallObjectMethod(activity, bindings._activity.getDisplay); // display = activity.getDisplay()
_P_THROW_ON_ACCESS_FAILURE(jenv, "display", display);
bindings.restoreDisplayMode(jenv, activity, display, this->_density);
}
else { // API level < 30
jobject windowManager = jenv.env().CallObjectMethod(activity, bindings._activity.getWindowManager); // windowManager = app.getWindowManager()
_P_THROW_ON_ACCESS_FAILURE(jenv, "window manager", windowManager);
jobject display = jenv.env().CallObjectMethod(windowManager, bindings._windowManager.getDefaultDisplay); // display = windowManager.getDefaultDisplay()
_P_THROW_ON_ACCESS_FAILURE(jenv, "display", display);
bindings.restoreDisplayMode(jenv, activity, display, this->_density);
}
return true;
}
catch (...) { return false; }
}
std::vector<DisplayMode> DisplayMonitor::listAvailableDisplayModes() const {
std::vector<DisplayMode> modes;
try {
AndroidJavaSession jenv;
AndroidBindings& bindings = AndroidBindings::globalInstance(); // already bound in DisplayMonitor constructor
jobject activity = AndroidApp::instance().state().activity->clazz;
if (bindings._windowMetrics.isAvailable) { // API level >= 30
jobject display = jenv.env().CallObjectMethod(activity, bindings._activity.getDisplay); // display = activity.getDisplay()
_P_THROW_ON_ACCESS_FAILURE(jenv, "display", display);
bindings.readDisplayModes(jenv, display, modes);
}
else { // API level < 30
jobject windowManager = jenv.env().CallObjectMethod(activity, bindings._activity.getWindowManager); // windowManager = app.getWindowManager()
_P_THROW_ON_ACCESS_FAILURE(jenv, "window manager", windowManager);
jobject display = jenv.env().CallObjectMethod(windowManager, bindings._windowManager.getDefaultDisplay); // display = windowManager.getDefaultDisplay()
_P_THROW_ON_ACCESS_FAILURE(jenv, "display", display);
bindings.readDisplayModes(jenv, display, modes);
}
}
catch (...) { // on error, fill default mode
modes.clear();
modes.emplace_back(getDisplayMode());
}
return modes;
}
// -- DPI awareness -- ---------------------------------------------------------
bool DisplayMonitor::setDpiAwareness(bool isEnabled) noexcept {
return isEnabled; // always enabled
}
void DisplayMonitor::getMonitorDpi(uint32_t& outDpiX, uint32_t& outDpiY, DisplayMonitor::WindowHandle) const noexcept {
outDpiX = this->_density.dpiX;
outDpiY = this->_density.dpiY;
}
void DisplayMonitor::getMonitorScaling(float& outScaleX, float& outScaleY, DisplayMonitor::WindowHandle) const noexcept {
outScaleX = outScaleY = this->_density.scale;
}
// -- metrics -- ---------------------------------------------------------------
DisplayArea DisplayMonitor::convertClientAreaToWindowArea(const DisplayArea& clientArea, DisplayMonitor::WindowHandle,
bool, uint32_t, uint32_t) const noexcept {
try {
DisplayArea windowArea;
AndroidJavaSession jenv;
AndroidBindings& bindings = AndroidBindings::globalInstance(); // already bound in DisplayMonitor constructor
jobject activity = AndroidApp::instance().state().activity->clazz;
jobject windowManager = jenv.env().CallObjectMethod(activity, bindings._activity.getWindowManager); // windowManager = app.getWindowManager()
_P_THROW_ON_ACCESS_FAILURE(jenv, "window manager", windowManager);
// WindowMetrics (API level >= 30)
if (bindings._windowMetrics.isAvailable) {
bindings.readWindowArea_wm(jenv, windowManager, windowArea);
}
// DisplayMetrics (API level < 30)
else {
jobject display = jenv.env().CallObjectMethod(windowManager, bindings._windowManager.getDefaultDisplay); // display = windowManager.getDefaultDisplay()
_P_THROW_ON_ACCESS_FAILURE(jenv, "display", display);
bindings.readWindowArea_dm(jenv, display, windowArea);
}
return windowArea;
}
catch (...) { return clientArea; }
}
#endif
| 49.875
| 159
| 0.675636
|
vinders
|
fef21fde4e50939f14c95851d34669baa6c9e07b
| 5,282
|
hxx
|
C++
|
include/opengm/functions/modelviewfunction.hxx
|
burcin/opengm
|
a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41
|
[
"MIT"
] | 318
|
2015-01-07T15:22:02.000Z
|
2022-01-22T10:10:29.000Z
|
include/opengm/functions/modelviewfunction.hxx
|
burcin/opengm
|
a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41
|
[
"MIT"
] | 89
|
2015-03-24T14:33:01.000Z
|
2020-07-10T13:59:13.000Z
|
include/opengm/functions/modelviewfunction.hxx
|
burcin/opengm
|
a1b21eecb93c6c5a7b11ab312d26b1c98c55ff41
|
[
"MIT"
] | 119
|
2015-01-13T08:35:03.000Z
|
2022-03-01T01:49:08.000Z
|
#pragma once
#ifndef OPENGM_MODELVIEWFUNCTION_HXX
#define OPENGM_MODELVIEWFUNCTION_HXX
#include "opengm/functions/function_properties_base.hxx"
namespace opengm {
/// Function that refers to a factor of another GraphicalModel
///
/// \tparam GM type of the graphical model which we want to view
/// \tparam MARRAY type of the array that holds the offset
///
/// \ingroup functions
template<class GM, class MARRAY>
class ModelViewFunction
: public FunctionBase<ModelViewFunction<GM,MARRAY>,
typename GM::ValueType,
typename GM::IndexType,
typename GM::LabelType>
{
public:
typedef GM GraphicalModelType;
typedef MARRAY OffsetType;
typedef typename GM::ValueType ValueType;
typedef typename GM::ValueType value_type;
typedef typename GM::IndexType IndexType;
typedef typename GM::LabelType LabelType;
ModelViewFunction(const GraphicalModelType& gm, const IndexType factorIndex, const ValueType scale, OffsetType const* offset);
ModelViewFunction(const GraphicalModelType& gm, const IndexType factorIndex, const ValueType scale);
ModelViewFunction(OffsetType const* offset);
template<class Iterator> ValueType operator()(Iterator begin) const;
size_t size() const;
LabelType shape(const size_t i) const;
size_t dimension() const;
private:
/// ViewType
enum ViewType {
/// only view
VIEW,
/// view with a offset
VIEWOFFSET,
/// only offset
OFFSET
};
GraphicalModelType const* gm_;
IndexType factorIndex_;
ValueType scale_;
OffsetType const* offset_;
ViewType viewType_;
};
/// constructor
/// \param gm graphical model we want to view
/// \param factorIndex index of the factor of gm we want to view
/// \param scale scaling factor of the view function
/// \param offset pointer to the offset marray
template<class GM, class MARRAY>
inline ModelViewFunction<GM, MARRAY>::ModelViewFunction
(
const GM& gm ,
const typename ModelViewFunction<GM, MARRAY>::IndexType factorIndex,
const typename ModelViewFunction<GM, MARRAY>::ValueType scale,
MARRAY const* offset
)
: gm_(&gm),
factorIndex_(factorIndex),
scale_(scale),
offset_(offset),
viewType_(VIEWOFFSET)
{
//viewType_ = VIEWOFFSET;
OPENGM_ASSERT((*offset_).size() == gm_->operator[](factorIndex_).size());
OPENGM_ASSERT((*offset_).dimension() == gm_->operator[](factorIndex_).numberOfVariables());
for(size_t i=0; i<(*offset_).dimension();++i)
OPENGM_ASSERT((*offset_).shape(i) == gm_->operator[](factorIndex_).numberOfLabels(i));
}
/// Constructor
/// \param gm graphical model we want to view
/// \param factorIndex index of the factor of gm we want to view
/// \param scale scaling factor of the view function
template<class GM, class MARRAY>
inline ModelViewFunction<GM, MARRAY>::ModelViewFunction
(
const GM& gm,
const typename ModelViewFunction<GM, MARRAY>::IndexType factorIndex,
const ValueType scale
)
: gm_(&gm),
factorIndex_(factorIndex),
scale_(scale),
viewType_(VIEW)
{
}
/// Constructor
/// \param offset pointer to the offset marray
template<class GM, class MARRAY>
inline ModelViewFunction<GM, MARRAY>::ModelViewFunction
(
MARRAY const* offset
)
: gm_(NULL),
factorIndex_(0),
scale_(0),
offset_(offset),
viewType_(OFFSET)
{
}
template<class GM, class MARRAY>
template<class Iterator>
inline typename opengm::ModelViewFunction<GM, MARRAY>::ValueType
ModelViewFunction<GM, MARRAY>::operator()
(
Iterator begin
) const
{
switch(viewType_) {
case VIEWOFFSET:
return scale_*gm_->operator[](factorIndex_)(begin) + (*offset_)(begin);
case VIEW:
return scale_*gm_->operator[](factorIndex_)(begin);
case OFFSET:
return (*offset_)(begin);
default:
break;
}
return 0;
}
template<class GM, class MARRAY>
inline typename ModelViewFunction<GM, MARRAY>::LabelType
ModelViewFunction<GM, MARRAY>::shape(const size_t i) const
{
switch(viewType_) {
case VIEWOFFSET:
OPENGM_ASSERT(gm_->operator[](factorIndex_).shape(i)==(*offset_).shape(i));
return (*offset_).shape(i);
case VIEW:
return gm_->operator[](factorIndex_).shape(i);
case OFFSET:
return (*offset_).shape(i);
//default:
}
// To avoid compiler error "warning : control reached end
return 0;
}
template<class GM, class MARRAY>
inline size_t ModelViewFunction<GM, MARRAY>::size() const
{
switch(viewType_) {
case VIEWOFFSET:
return (*offset_).size();
case VIEW:
return gm_->operator[](factorIndex_).size();
case OFFSET:
return (*offset_).size();
//default:
}
return 0;
}
template<class GM, class MARRAY>
inline size_t ModelViewFunction<GM, MARRAY>::dimension() const
{
switch(viewType_) {
case VIEWOFFSET:
OPENGM_ASSERT(gm_->operator[](factorIndex_).numberOfVariables()==(*offset_).dimension());
return (*offset_).dimension();
case VIEW:
return gm_->operator[](factorIndex_).numberOfVariables();
case OFFSET:
return (*offset_).dimension();
default:
;
}
// To avoid compiler error "warning : control reached end
return 0;
}
} // namespace opengm
#endif // #ifndef OPENGM_MODELVIEWFUNCTION_HXX
| 27.65445
| 129
| 0.695191
|
burcin
|
fef22804ea27051568f02524adb66cd9abef0aa8
| 1,772
|
cpp
|
C++
|
src/keyboard.cpp
|
EduardoPagotto/Esp32DisplayKeyboard
|
492b10e5e974050778f3cd47c57d72a32f0c09ca
|
[
"MIT"
] | null | null | null |
src/keyboard.cpp
|
EduardoPagotto/Esp32DisplayKeyboard
|
492b10e5e974050778f3cd47c57d72a32f0c09ca
|
[
"MIT"
] | null | null | null |
src/keyboard.cpp
|
EduardoPagotto/Esp32DisplayKeyboard
|
492b10e5e974050778f3cd47c57d72a32f0c09ca
|
[
"MIT"
] | null | null | null |
#include "../include/keyboard.hpp"
#include "Arduino.h"
#define LINHAS 4
#define COLUNAS 4
const int linhas[] = {16, 17, 13, 19};
const int colunas[] = {21, 22, 12, 25};
const char hexaKey[LINHAS][COLUNAS] = {{'1', '2', '3', 'A'}, // Linha 0
{'4', '5', '6', 'B'}, // Linha 1
{'7', '8', '9', 'C'}, // Linha 2
{'*', '0', '#', 'D'}}; // Linha 3
KeyBoardMatrix::KeyBoardMatrix() {
int pin;
for (uint8_t l = 0; l < LINHAS; l++) {
pin = linhas[l];
pinMode(pin, OUTPUT);
digitalWrite(pin, HIGH);
}
for (uint8_t c = 0; c < COLUNAS; c++) {
pin = colunas[c];
pinMode(pin, INPUT_PULLUP);
}
this->coluna = 0;
this->linha = 0;
this->last = false;
}
KeyBoardMatrix::~KeyBoardMatrix() {}
bool KeyBoardMatrix::__getKey() {
uint8_t debuncingTime;
for (uint8_t l = 0; l < LINHAS; l++) {
digitalWrite(linhas[l], LOW);
for (uint8_t c = 0; c < COLUNAS; c++) {
debuncingTime = 0;
while ((digitalRead(colunas[c]) == 0) && (debuncingTime < 10)) {
debuncingTime++;
vTaskDelay(pdMS_TO_TICKS(10));
}
if (debuncingTime == 10) {
this->linha = l;
this->coluna = c;
digitalWrite(linhas[l], HIGH);
return true;
}
}
digitalWrite(linhas[l], HIGH);
}
return false;
}
char* KeyBoardMatrix::getKey() {
if (this->__getKey() == true) {
if (last == true)
return NULL;
last = true;
return (char*)&hexaKey[linha][coluna];
}
last = false;
return NULL;
}
| 24.957746
| 76
| 0.461061
|
EduardoPagotto
|
fef2345454027bc0c790750ef89900d764782667
| 2,793
|
hpp
|
C++
|
stacks/layer/data/Outputs.hpp
|
akatray/stacks
|
2922b6556983894c550f7b650bcabdbfaf45e9d9
|
[
"Unlicense"
] | 1
|
2019-08-27T22:16:40.000Z
|
2019-08-27T22:16:40.000Z
|
stacks/layer/data/Outputs.hpp
|
akatray/stacks
|
2922b6556983894c550f7b650bcabdbfaf45e9d9
|
[
"Unlicense"
] | null | null | null |
stacks/layer/data/Outputs.hpp
|
akatray/stacks
|
2922b6556983894c550f7b650bcabdbfaf45e9d9
|
[
"Unlicense"
] | null | null | null |
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Pragma.
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
#pragma once
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Neural Networks Experiment.
// ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
namespace sx
{
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Expand namespaces.
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
using namespace fx;
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Output buffers.
// --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Default.
template<class T, uMAX SZ_OUT, uMAX SZ_GRAD, FnTrans FN_TRANS>
struct LDOutputs
{
alignas(ALIGNMENT) T OutTrans[SZ_OUT];
alignas(ALIGNMENT) T Gradient[SZ_GRAD];
LDOutputs ( void ) : OutTrans{}, Gradient{} {}
};
// Specialization for relu.
template<class T, uMAX SZ_OUT, uMAX SZ_GRAD>
struct LDOutputs<T, SZ_OUT, SZ_GRAD, FnTrans::RELU>
{
alignas(ALIGNMENT) T OutTrans[SZ_OUT];
alignas(ALIGNMENT) T OutRaw[SZ_OUT];
alignas(ALIGNMENT) T Gradient[SZ_GRAD];
LDOutputs ( void ) : OutTrans{}, OutRaw{}, Gradient{} {}
};
// Specialization for prelu.
template<class T, uMAX SZ_OUT, uMAX SZ_GRAD>
struct LDOutputs<T, SZ_OUT, SZ_GRAD, FnTrans::PRELU>
{
alignas(ALIGNMENT) T OutTrans[SZ_OUT];
alignas(ALIGNMENT) T OutRaw[SZ_OUT];
alignas(ALIGNMENT) T Gradient[SZ_GRAD];
LDOutputs ( void ) : OutTrans{}, OutRaw{}, Gradient{} {}
};
// Specialization for elu.
template<class T, uMAX SZ_OUT, uMAX SZ_GRAD>
struct LDOutputs<T, SZ_OUT, SZ_GRAD, FnTrans::ELU>
{
alignas(ALIGNMENT) T OutTrans[SZ_OUT];
alignas(ALIGNMENT) T OutRaw[SZ_OUT];
alignas(ALIGNMENT) T Gradient[SZ_GRAD];
LDOutputs ( void ) : OutTrans{}, OutRaw{}, Gradient{} {}
};
}
| 41.686567
| 183
| 0.332617
|
akatray
|
fef2972a16a97c7c0f003dbb1c0c21b4e0e8dcac
| 17,123
|
cpp
|
C++
|
src/graysvr/ntservice.cpp
|
shiryux/UOLatam-0.57a
|
892aefd42cbcf4c1ca9b4f89b196cea0757a93f1
|
[
"Apache-2.0"
] | null | null | null |
src/graysvr/ntservice.cpp
|
shiryux/UOLatam-0.57a
|
892aefd42cbcf4c1ca9b4f89b196cea0757a93f1
|
[
"Apache-2.0"
] | null | null | null |
src/graysvr/ntservice.cpp
|
shiryux/UOLatam-0.57a
|
892aefd42cbcf4c1ca9b4f89b196cea0757a93f1
|
[
"Apache-2.0"
] | null | null | null |
// Stuff for making this application run as an NT service
#ifdef _WIN32
#include "graysvr.h"
#include "../common/grayver.h"
#include "ntservice.h"
#include <direct.h>
CNTService g_Service;
CNTService::CNTService()
{
m_hStatusHandle = NULL;
m_fIsNTService = false;
}
// Try to create the registry key containing the working directory for the application
static void ExtractPath(LPTSTR szPath)
{
TCHAR *pszPath = strrchr(szPath, '\\');
if ( pszPath )
*pszPath = 0;
}
static LPTSTR GetLastErrorText(LPTSTR lpszBuf, DWORD dwSize)
{
// Check CGrayError.
// PURPOSE: copies error message text to a string
//
// PARAMETERS:
// lpszBuf - destination buffer
// dwSize - size of buffer
//
// RETURN VALUE:
// destination buffer
int nChars = CGrayError::GetSystemErrorMessage( GetLastError(), lpszBuf, dwSize );
sprintf( lpszBuf+nChars, " (0x%lx)", GetLastError());
return lpszBuf;
}
/////////////////////////////////////////////////////////////////////////////////////
// PURPOSE: Allows any thread to log a message to the NT Event Log
void CNTService::ReportEvent( WORD wType, DWORD dwEventID, LPCTSTR lpszMsg, LPCTSTR lpszArgs )
{
UNREFERENCED_PARAMETER(dwEventID);
g_Log.Event(LOGM_INIT|(( wType == EVENTLOG_INFORMATION_TYPE ) ? LOGL_EVENT : LOGL_ERROR), "%s %s\n", lpszMsg, lpszArgs);
}
// RETURN: false = exit app.
bool CNTService::OnTick()
{
if (( !m_fIsNTService ) || ( m_sStatus.dwCurrentState != SERVICE_STOP_PENDING ) )
return true;
// Let the SCM know we aren't ignoring it
SetServiceStatus(SERVICE_STOP_PENDING, NO_ERROR, 1000);
g_Serv.SetExitFlag(4);
return false;
}
// PURPOSE: Sets the current status of the service and reports it to the Service Control Manager
BOOL CNTService::SetServiceStatus( DWORD dwCurrentState, DWORD dwWin32ExitCode, DWORD dwWaitHint )
{
if ( dwCurrentState == SERVICE_START_PENDING )
m_sStatus.dwControlsAccepted = 0;
else
m_sStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP;
m_sStatus.dwCurrentState = dwCurrentState;
m_sStatus.dwWin32ExitCode = dwWin32ExitCode;
m_sStatus.dwWaitHint = dwWaitHint;
static DWORD dwCheckPoint = 1;
if (( dwCurrentState == SERVICE_RUNNING) || (dwCurrentState == SERVICE_STOPPED))
m_sStatus.dwCheckPoint = 0;
else
m_sStatus.dwCheckPoint = dwCheckPoint++;
// Report the status of the service to the Service Control Manager
BOOL fResult = ::SetServiceStatus(m_hStatusHandle, &m_sStatus);
if ( !fResult && m_fIsNTService )
{
// if fResult is not 0, then an error occurred. Throw this in the event log.
char szErr[256];
ReportEvent(EVENTLOG_ERROR_TYPE, 0, "SetServiceStatus", GetLastErrorText(szErr, sizeof(szErr)));
}
return fResult;
}
// PURPOSE: This function is called by the SCM whenever ControlService() is called on this service. The
// SCM does not start the service through this function.
void WINAPI CNTService::service_ctrl(DWORD dwCtrlCode) // static
{
if ( dwCtrlCode == SERVICE_CONTROL_STOP )
g_Service.ServiceStop();
g_Service.SetServiceStatus(g_Service.m_sStatus.dwCurrentState, NO_ERROR, 0);
}
// PURPOSE: is called by the SCM, and takes care of some initialization and calls ServiceStart().
void WINAPI CNTService::service_main(DWORD dwArgc, LPTSTR *lpszArgv) // static
{
g_Service.ServiceStartMain(dwArgc, lpszArgv);
}
// PURPOSE: starts the service. (synchronous)
void CNTService::ServiceStartMain(DWORD dwArgc, LPTSTR *lpszArgv)
{
TCHAR *pszMsg = Str_GetTemp();
sprintf(pszMsg, SPHERE_TITLE " V" SPHERE_VERSION " - %s", g_Serv.GetName());
m_hStatusHandle = RegisterServiceCtrlHandler(pszMsg, service_ctrl);
if ( !m_hStatusHandle ) // Not much we can do about this.
{
g_Log.Event(LOGL_FATAL|LOGM_INIT, "RegisterServiceCtrlHandler failed\n");
return;
}
// SERVICE_STATUS members that don't change
m_sStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
m_sStatus.dwServiceSpecificExitCode = 0;
// report the status to the service control manager.
if ( SetServiceStatus(SERVICE_START_PENDING, NO_ERROR, 3000) )
ServiceStart( dwArgc, lpszArgv);
SetServiceStatus(SERVICE_STOPPED, NO_ERROR, 0);
}
// PURPOSE: starts the service. (synchronous)
int CNTService::ServiceStart(DWORD dwArgc, LPTSTR *lpszArgv)
{
ReportEvent(EVENTLOG_INFORMATION_TYPE, 0, "Service start pending.");
// Service initialization report status to the service control manager.
int rc = -1;
if ( !SetServiceStatus(SERVICE_START_PENDING, NO_ERROR, 3000) )
return rc;
// Create the event object. The control handler function signals this event when it receives a "stop" control code
m_hServerStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if ( !m_hServerStopEvent )
return rc;
if ( !SetServiceStatus(SERVICE_START_PENDING, NO_ERROR, 3000) )
{
bailout1:
CloseHandle(m_hServerStopEvent);
return rc;
}
// Create the event object used in overlapped i/o
HANDLE hEvents[2] = {NULL, NULL};
hEvents[0] = m_hServerStopEvent;
hEvents[1] = CreateEvent(NULL, TRUE, FALSE, NULL);
if ( !hEvents[1] )
goto bailout1;
if ( !SetServiceStatus(SERVICE_START_PENDING, NO_ERROR, 3000) )
{
bailout2:
CloseHandle(hEvents[1]);
goto bailout1;
}
// Create a security descriptor that allows anyone to write to the pipe
PSECURITY_DESCRIPTOR pSD = (PSECURITY_DESCRIPTOR) malloc(SECURITY_DESCRIPTOR_MIN_LENGTH);
if ( !pSD )
goto bailout2;
if ( !InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION) )
{
bailout3:
free(pSD);
goto bailout2;
}
// Add a NULL descriptor ACL to the security descriptor
if ( !SetSecurityDescriptorDacl(pSD, TRUE, NULL, FALSE) )
goto bailout3;
SECURITY_ATTRIBUTES sa;
sa.nLength = sizeof(sa);
sa.lpSecurityDescriptor = pSD;
sa.bInheritHandle = TRUE;
if ( !SetServiceStatus(SERVICE_START_PENDING, NO_ERROR, 3000) )
goto bailout3;
// Set the name of the named pipe this application uses. We create a named pipe to ensure that
// only one instance of this application runs on the machine at a time. If there is an instance
// running, it will own this pipe, and any further attempts to create the same named pipe will fail.
char lpszPipeName[80];
sprintf(lpszPipeName, "\\\\.\\pipe\\" SPHERE_FILE "svr\\%s", g_Serv.GetName());
char szErr[256];
// Open the named pipe
HANDLE hPipe = CreateNamedPipe(lpszPipeName,
FILE_FLAG_OVERLAPPED|PIPE_ACCESS_DUPLEX,
PIPE_TYPE_MESSAGE|PIPE_READMODE_MESSAGE|PIPE_WAIT,
1, 0, 0, 1000, &sa);
if ( hPipe == INVALID_HANDLE_VALUE )
{
ReportEvent(EVENTLOG_ERROR_TYPE, 0, "Can't create named pipe. Check multi-instance?", GetLastErrorText(szErr, sizeof(szErr)));
goto bailout3;
}
if ( SetServiceStatus(SERVICE_RUNNING, NO_ERROR, 0) )
{
rc = Sphere_MainEntryPoint(dwArgc, lpszArgv);
if ( !rc )
ReportEvent(EVENTLOG_INFORMATION_TYPE, 0, "service stopped", GetLastErrorText(szErr, sizeof(szErr)));
else
{
char szMessage[80];
sprintf(szMessage, "%d.", rc);
ReportEvent(EVENTLOG_ERROR_TYPE, 0, "service stopped abnormally", szMessage);
}
}
else
ReportEvent(EVENTLOG_ERROR_TYPE, 0, "ServiceStart failed.");
CloseHandle(hPipe);
goto bailout3;
}
// PURPOSE: reports that the service is attempting to stop
void CNTService::ServiceStop()
{
ReportEvent(EVENTLOG_INFORMATION_TYPE, 0, "Attempting to stop service");
m_sStatus.dwCurrentState = SERVICE_STOP_PENDING;
SetServiceStatus(m_sStatus.dwCurrentState, NO_ERROR, 3000);
if (m_hServerStopEvent)
SetEvent(m_hServerStopEvent);
}
// PURPOSE: Installs the service on the local machine
void CNTService::CmdInstallService()
{
char szPath[_MAX_PATH * 2];
char szErr[256];
ReportEvent(EVENTLOG_INFORMATION_TYPE, 0, "Installing Service.");
// Try to determine the name and path of this application.
if ( !GetModuleFileName(NULL, szPath, sizeof(szPath)) )
{
ReportEvent(EVENTLOG_ERROR_TYPE, 0, "Install GetModuleFileName", GetLastErrorText(szErr, sizeof(szErr)));
return;
}
// Try to open the Service Control Manager
SC_HANDLE schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if ( !schSCManager )
{
ReportEvent(EVENTLOG_ERROR_TYPE, 0, "Install OpenSCManager", GetLastErrorText(szErr, sizeof(szErr)));
return;
}
// Try to create the service
char szInternalName[MAX_PATH];
sprintf(szInternalName, SPHERE_TITLE " - %s", g_Serv.GetName());
SC_HANDLE schService = CreateService(
schSCManager, // handle of the Service Control Manager
szInternalName, // Internal name of the service (used when controlling the service using "net start" or "netsvc")
szInternalName, // Display name of the service (displayed in the Control Panel | Services page)
SERVICE_ALL_ACCESS,
SERVICE_WIN32_OWN_PROCESS,
SERVICE_AUTO_START, // Start automatically when the OS starts
SERVICE_ERROR_NORMAL,
szPath, // Path and filename of this executable
NULL, NULL, NULL, NULL, NULL
);
if ( !schService )
{
ReportEvent(EVENTLOG_ERROR_TYPE, 0, "Install CreateService", GetLastErrorText(szErr, sizeof(szErr)));
bailout1:
CloseServiceHandle(schSCManager);
return;
}
// Configure service - Service description
char szDescription[MAX_PATH];
sprintf(szDescription, "SphereServer Service for %s", g_Serv.GetName());
SERVICE_DESCRIPTION sdDescription;
sdDescription.lpDescription = szDescription;
if ( !ChangeServiceConfig2(schService, SERVICE_CONFIG_DESCRIPTION, &sdDescription) )
{
// not critical, so no need to abort the service creation
ReportEvent(EVENTLOG_WARNING_TYPE, 0, "Install SetDescription", GetLastErrorText(szErr, sizeof(szErr)));
}
// Configure service - Restart options
SC_ACTION scAction[3];
scAction[0].Type = SC_ACTION_RESTART; // restart process on failure
scAction[0].Delay = 10000; // wait 10 seconds before restarting
scAction[1].Type = SC_ACTION_RESTART;
scAction[1].Delay = 10000;
scAction[2].Type = SC_ACTION_RESTART; // wait 2 minutes before restarting the third time
scAction[2].Delay = 120000;
SERVICE_FAILURE_ACTIONS sfaFailure;
sfaFailure.dwResetPeriod = (1 * 60 * 60); // reset failure count after an hour passes with no fails
sfaFailure.lpRebootMsg = NULL; // no reboot message
sfaFailure.lpCommand = NULL; // no command executed
sfaFailure.cActions = COUNTOF(scAction); // number of actions
sfaFailure.lpsaActions = scAction; //
if ( !ChangeServiceConfig2(schService, SERVICE_CONFIG_FAILURE_ACTIONS, &sfaFailure) )
{
// not critical, so no need to abort the service creation
ReportEvent(EVENTLOG_WARNING_TYPE, 0, "Install SetAutoRestart", GetLastErrorText(szErr, sizeof(szErr)));
}
HKEY hKey;
char szKey[MAX_PATH];
// Register the application for event logging
DWORD dwData;
// Try to create the registry key containing information about this application
strcpy(szKey, "System\\CurrentControlSet\\Services\\EventLog\\Application\\" SPHERE_FILE "svr");
if (RegCreateKey(HKEY_LOCAL_MACHINE, szKey, &hKey))
ReportEvent(EVENTLOG_ERROR_TYPE, 0, "Install RegCreateKey", GetLastErrorText(szErr, sizeof(szErr)));
else
{
// Try to create the registry key containing the name of the EventMessageFile
// Replace the name of the exe with the name of the dll in the szPath variable
if (RegSetValueEx(hKey, "EventMessageFile", 0, REG_EXPAND_SZ, (LPBYTE) szPath, strlen(szPath) + 1))
ReportEvent(EVENTLOG_ERROR_TYPE, 0, "Install RegSetValueEx", GetLastErrorText(szErr, sizeof(szErr)));
else
{
// Try to create the registry key containing the types of errors this application will generate
dwData = EVENTLOG_ERROR_TYPE|EVENTLOG_INFORMATION_TYPE|EVENTLOG_WARNING_TYPE;
if ( RegSetValueEx(hKey, "TypesSupported", 0, REG_DWORD, (LPBYTE) &dwData, sizeof(DWORD)) )
ReportEvent(EVENTLOG_ERROR_TYPE, 0, "Install RegSetValueEx", GetLastErrorText(szErr, sizeof(szErr)));
}
RegCloseKey(hKey);
}
// Set the working path for the application
sprintf(szKey, "System\\CurrentControlSet\\Services\\" SPHERE_TITLE " - %s\\Parameters", g_Serv.GetName());
if ( RegCreateKey(HKEY_LOCAL_MACHINE, szKey, &hKey) )
{
ReportEvent(EVENTLOG_ERROR_TYPE, 0, "Install RegCreateKey", GetLastErrorText(szErr, sizeof(szErr)));
bailout2:
CloseServiceHandle(schService);
goto bailout1;
}
ExtractPath(szPath);
if ( RegSetValueEx(hKey, "WorkingPath", 0, REG_SZ, (const unsigned char *) &szPath[0], strlen(szPath)) )
ReportEvent(EVENTLOG_ERROR_TYPE, 0, "Install RegSetValueEx", GetLastErrorText(szErr, sizeof(szErr)));
ReportEvent(EVENTLOG_INFORMATION_TYPE, 0, "Install OK", g_Serv.GetName());
goto bailout2;
}
// PURPOSE: Stops and removes the service
void CNTService::CmdRemoveService()
{
char szErr[256];
ReportEvent(EVENTLOG_INFORMATION_TYPE, 0, "Removing Service.");
SC_HANDLE schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if ( !schSCManager )
{
ReportEvent(EVENTLOG_ERROR_TYPE, 0, "Remove OpenSCManager failed", GetLastErrorText(szErr, sizeof(szErr)));
return;
}
// Try to obtain the handle of this service
char szInternalName[MAX_PATH];
sprintf(szInternalName, SPHERE_TITLE " - %s", g_Serv.GetName());
SC_HANDLE schService = OpenService(schSCManager, szInternalName, SERVICE_ALL_ACCESS);
if ( !schService )
{
ReportEvent(EVENTLOG_ERROR_TYPE, 0, "Remove OpenService failed", GetLastErrorText(szErr, sizeof(szErr)));
CloseServiceHandle(schSCManager);
return;
}
// Check to see if the service is started, if so try to stop it.
if ( ControlService(schService, SERVICE_CONTROL_STOP, &m_sStatus) )
{
ReportEvent(EVENTLOG_INFORMATION_TYPE, 0, "Stopping");
Sleep(1000);
while ( QueryServiceStatus(schService, &m_sStatus) ) // wait the service to stop
{
if ( m_sStatus.dwCurrentState == SERVICE_STOP_PENDING )
Sleep(1000);
else
break;
}
if (m_sStatus.dwCurrentState == SERVICE_STOPPED)
ReportEvent(EVENTLOG_INFORMATION_TYPE, 0, "Stopped");
else
ReportEvent(EVENTLOG_ERROR_TYPE, 0, "Failed to Stop");
}
// Remove the service
if ( DeleteService(schService) )
ReportEvent(EVENTLOG_INFORMATION_TYPE, 0, "Removed OK");
else
ReportEvent(EVENTLOG_ERROR_TYPE, 0, "Remove Fail", GetLastErrorText(szErr, sizeof(szErr)));
CloseServiceHandle(schService);
CloseServiceHandle(schSCManager);
}
void CNTService::CmdMainStart()
{
m_fIsNTService = true;
char szTmp[256];
sprintf(szTmp, SPHERE_TITLE " - %s", g_Serv.GetName());
SERVICE_TABLE_ENTRY dispatchTable[] =
{
{ szTmp, (LPSERVICE_MAIN_FUNCTION)service_main },
{ NULL, NULL },
};
if ( !StartServiceCtrlDispatcher(dispatchTable) )
ReportEvent(EVENTLOG_ERROR_TYPE, 0, "StartServiceCtrlDispatcher", GetLastErrorText(szTmp, sizeof(szTmp)));
}
/////////////////////////////////////////////////////////////////////////////////////
//
// FUNCTION: main()
//
/////////////////////////////////////////////////////////////////////////////////////
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
TCHAR *argv[32];
argv[0] = NULL;
int argc = Str_ParseCmds(lpCmdLine, &argv[1], COUNTOF(argv)-1, " \t") + 1;
if ( GRAY_GetOSInfo()->dwPlatformId != VER_PLATFORM_WIN32_NT )
{
// We are running Win9x - So we are not an NT service.
do_not_nt_service:
NTWindow_Init(hInstance, lpCmdLine, nCmdShow);
int iRet = Sphere_MainEntryPoint(argc, argv);
NTWindow_Exit();
TerminateProcess(GetCurrentProcess(), iRet);
return iRet;
}
// We need to find out what the server name is....look it up in the .ini file
if ( !g_Cfg.LoadIni(true) )
{
// Try to determine the name and path of this application.
char szPath[_MAX_PATH];
GetModuleFileName(NULL, szPath, sizeof(szPath));
if ( !szPath[0] )
return -2;
ExtractPath(szPath);
g_Cfg.LoadIni(false);
}
if ( !g_Cfg.m_fUseNTService ) // since there is no way to detect how did we start, use config for that
goto do_not_nt_service;
g_Service.SetServiceStatus(SERVICE_START_PENDING, NO_ERROR, 5000);
// process the command line arguments...
if (( argc > 1 ) && _IS_SWITCH(*argv[1]) )
{
if ( argv[1][1] == 'k' ) // service control
{
if ( argc < 3 )
{
printf("Use \"-k command\" with operation to proceed (install/remove)\n");
}
else if ( !strcmp(argv[2], "install") )
{
g_Service.CmdInstallService();
}
else if ( !strcmp(argv[2], "remove") )
{
g_Service.CmdRemoveService();
}
return 0;
}
}
// If the argument does not match any of the above parameters, the Service Control Manager (SCM) may
// be attempting to start the service, so we must call StartServiceCtrlDispatcher.
g_Service.ReportEvent(EVENTLOG_INFORMATION_TYPE, 0, "Starting Service.");
g_Service.CmdMainStart();
g_Service.SetServiceStatus(SERVICE_STOPPED, NO_ERROR, 0);
return -1;
}
#endif
| 33.248544
| 129
| 0.708346
|
shiryux
|
fef2e40bd84ca91dd09ff9464209a409eb81e5c1
| 533
|
cpp
|
C++
|
Tests/Source/StackTests.cpp
|
stefanfrings/LuaBridge
|
36c0c62815f9f6bf43c81a3977502cd3996302a0
|
[
"X11",
"MIT"
] | 1,171
|
2015-01-03T06:19:58.000Z
|
2022-03-31T10:37:08.000Z
|
Tests/Source/StackTests.cpp
|
nikita-yfh/LuaBridge
|
6c1d0a1126487f993e5f93141c0954ff6600fdfe
|
[
"X11",
"MIT"
] | 164
|
2015-01-20T11:58:39.000Z
|
2022-03-29T20:36:12.000Z
|
Tests/Source/StackTests.cpp
|
nikita-yfh/LuaBridge
|
6c1d0a1126487f993e5f93141c0954ff6600fdfe
|
[
"X11",
"MIT"
] | 324
|
2015-01-02T11:03:48.000Z
|
2022-03-15T08:00:35.000Z
|
// https://github.com/vinniefalco/LuaBridge
// Copyright 2020, Dmitry Tarakanov
// SPDX-License-Identifier: MIT
#include "TestBase.h"
struct StackTests : TestBase
{
};
TEST_F(StackTests, IntegralTypes)
{
luabridge::push(L, true);
ASSERT_TRUE(luabridge::isInstance<bool>(L, -1));
ASSERT_FALSE(luabridge::isInstance<int>(L, -1));
luabridge::push(L, 5);
ASSERT_TRUE(luabridge::isInstance<int>(L, -1));
ASSERT_FALSE(luabridge::isInstance<bool>(L, -1));
ASSERT_TRUE(luabridge::isInstance<bool>(L, -2));
}
| 23.173913
| 53
| 0.690432
|
stefanfrings
|
fef32977f29d3c5c2d16bfc95596e18ccd7dc9cb
| 9,783
|
cpp
|
C++
|
tests/service_test.cpp
|
angelcaban/cpp_rest_servlets
|
8debf35c67ce9cd96dfc9ca3c4ea06b77abcaea9
|
[
"MIT"
] | null | null | null |
tests/service_test.cpp
|
angelcaban/cpp_rest_servlets
|
8debf35c67ce9cd96dfc9ca3c4ea06b77abcaea9
|
[
"MIT"
] | null | null | null |
tests/service_test.cpp
|
angelcaban/cpp_rest_servlets
|
8debf35c67ce9cd96dfc9ca3c4ea06b77abcaea9
|
[
"MIT"
] | null | null | null |
/*
* Copyright 2018 Angel Caban
*
* 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 <exception>
#include <functional>
#include <map>
#include <memory>
#include <utility>
#include <cpprest/containerstream.h>
#include <cpprest/http_msg.h>
#include <cpprest/http_client.h>
#include <rest_service.hpp>
#include <servlet_controller.hpp>
#include <gtest/gtest.h>
using namespace std;
using namespace web;
using namespace web::http;
using namespace cfx;
using restful_servlets::ServletController;
using restful_servlets::ServletCache;
using restful_servlets::AbstractServlet;
using ::testing::EmptyTestEventListener;
using ::testing::InitGoogleTest;
using ::testing::Test;
using ::testing::TestEventListeners;
using ::testing::TestInfo;
using ::testing::TestPartResult;
using ::testing::UnitTest;
namespace {
constexpr char endpoint[] = "http://localhost:33434";
class ServiceFixture : public Test {
public:
ServletController controller;
ServiceFixture() = default;
~ServiceFixture() override {
ServletCache::getInstance().clearAll();
}
};
class RootServlet : public AbstractServlet {
public:
constexpr static char BODY_STR[]{
"<html><body><h1>It Works!</h1></body></html>"};
RootServlet() : AbstractServlet() {}
explicit RootServlet(const char* path) : AbstractServlet{path} {}
explicit RootServlet(std::string&& path) : AbstractServlet{move(path)} {}
~RootServlet() override = default;
bool handle(http_request req) override {
utf8string body{BODY_STR};
req.reply(status_codes::OK, std::move(body),
"text/html; charset=utf-8");
return true;
}
};
class RootChildServlet : public AbstractServlet {
public:
constexpr static char BODY_STR[]{
"{ \"child_of_root\" : true }"};
RootChildServlet() : AbstractServlet() {}
explicit RootChildServlet(const char* path) : AbstractServlet{path} {}
explicit RootChildServlet(std::string&& path) : AbstractServlet{move(path)} {}
~RootChildServlet() override = default;
bool handle(http_request req) override {
utf8string body{BODY_STR};
req.reply(status_codes::OK, std::move(body),
"text/html; charset=utf-8");
return true;
}
};
class HelloWorldServlet : public AbstractServlet {
public:
constexpr static char BODY_STR[]{
"<html><body><strong>hello world</strong></body></html>"};
HelloWorldServlet() : AbstractServlet() {}
explicit HelloWorldServlet(const char* path) : AbstractServlet{path} {}
explicit HelloWorldServlet(std::string&& path) : AbstractServlet{move(path)} {}
~HelloWorldServlet() override = default;
bool handle(http_request req) override {
utf8string body{BODY_STR};
req.reply(status_codes::OK, std::move(body),
"text/html; charset=utf-8");
return true;
}
};
TEST_F(ServiceFixture, DefaultCtor) {
EXPECT_EQ(0u, ServletCache::getInstance().typesSize());
EXPECT_EQ(0u, ServletCache::getInstance().cacheSize());
}
TEST_F(ServiceFixture, registerOneServlet) {
controller.registerServlet<HelloWorldServlet>("/hello/world");
EXPECT_EQ(1u, ServletCache::getInstance().typesSize());
EXPECT_EQ(1u, ServletCache::getInstance().cacheSize());
}
TEST_F(ServiceFixture, registerTwoServlets) {
controller.registerServlet<HelloWorldServlet>("/hello-world");
controller.registerServlet<RootServlet>("/");
EXPECT_EQ(2u, ServletCache::getInstance().typesSize());
EXPECT_EQ(2u, ServletCache::getInstance().cacheSize());
}
TEST_F(ServiceFixture, createServlets) {
using web::http::client::http_client;
using web::http::method;
using web::http::methods;
controller.registerServlet<HelloWorldServlet>("/hello-world");
controller.registerServlet<RootServlet>("/");
controller.setEndpoint("http://localhost:33434");
controller.accept().wait();
http_client client{{"http://localhost:33434"}};
{
auto task1 = client.request(methods::GET, "/");
auto result1 = task1.wait();
ASSERT_EQ(pplx::completed, result1);
auto response = task1.get();
auto task2 = response.extract_string();
auto result2 = task2.wait();
ASSERT_EQ(pplx::completed, result2);
ASSERT_EQ(RootServlet::BODY_STR, task2.get());
}
{
auto task1 = client.request(methods::GET, "/hello-world");
auto result1 = task1.wait();
ASSERT_EQ(pplx::completed, result1);
auto response = task1.get();
auto task2 = response.extract_string();
auto result2 = task2.wait();
ASSERT_EQ(pplx::completed, result2);
ASSERT_EQ(HelloWorldServlet::BODY_STR, task2.get());
}
controller.shutdown().wait();
}
TEST_F(ServiceFixture, callBadUrl) {
using web::http::client::http_client;
using web::http::method;
using web::http::methods;
controller.registerServlet<HelloWorldServlet>("/hello-world");
controller.setEndpoint(endpoint);
controller.accept().wait();
http_client client{{endpoint}};
auto task1 = client.request(methods::GET, "/bad-url/");
auto result1 = task1.wait();
ASSERT_EQ(pplx::completed, result1);
auto response = task1.get();
auto task2 = response.extract_string();
auto result2 = task2.wait();
ASSERT_EQ(pplx::completed, result2);
ASSERT_EQ("", task2.get());
ASSERT_EQ(404, response.status_code());
controller.shutdown().wait();
}
TEST_F(ServiceFixture, createChildServlet) {
using web::http::client::http_client;
using web::http::method;
using web::http::methods;
string helloPath{"/hello"};
string worldPath{"/world"};
controller.registerServlet<RootServlet>(move(string{"/hello"}));
controller.registerServlet<RootChildServlet>(move(worldPath),
helloPath);
controller.setEndpoint(endpoint);
controller.accept().wait();
http_client client{{endpoint}};
auto task1 = client.request(methods::POST, "/hello");
auto result1 = task1.wait();
EXPECT_EQ(2u, ServletCache::getInstance().typesSize());
EXPECT_EQ(2u, ServletCache::getInstance().cacheSize());
EXPECT_EQ(1u, ServletCache::getInstance().at("/hello")->childrenCount());
ASSERT_EQ(pplx::completed, result1);
auto task2 = client.request(methods::POST, "/hello/world");
auto result2 = task2.wait();
ASSERT_EQ(pplx::completed, result2);
auto response = task2.get();
auto task3 = response.extract_string();
auto result3 = task3.wait();
ASSERT_EQ(pplx::completed, result3);
ASSERT_EQ(RootChildServlet::BODY_STR, task3.get());
controller.shutdown().wait();
}
TEST_F(ServiceFixture, createPythonServlet) {
using web::http::client::http_client;
using web::http::method;
using web::http::methods;
string rootPath{"/"};
string configPath{"../tests/python_servlet/hello_world.json"};
controller.registerJsonServlet(std::move(rootPath),
std::move(configPath));
EXPECT_EQ(1u, ServletCache::getInstance().typesSize());
EXPECT_EQ(1u, ServletCache::getInstance().cacheSize());
controller.setEndpoint(endpoint);
controller.accept().wait();
http_client client{{endpoint}};
auto task1 = client.request(methods::POST, "/");
auto result1 = task1.wait();
ASSERT_EQ(pplx::completed, result1);
auto response = task1.get();
EXPECT_EQ(http::status_codes::OK, response.status_code());
auto task2 = response.extract_string();
auto result2 = task2.wait();
ASSERT_EQ(pplx::completed, result2);
ASSERT_EQ("HELLO FROM PYTHON", task2.get());
controller.shutdown().wait();
}
TEST_F(ServiceFixture, createPythonServletUnauthorized) {
using web::http::client::http_client;
using web::http::method;
using web::http::methods;
string rootPath{"/login"};
string configPath{"../tests/python_servlet/no_access.json"};
controller.registerJsonServlet(std::move(rootPath),
std::move(configPath));
EXPECT_EQ(1u, ServletCache::getInstance().typesSize());
EXPECT_EQ(1u, ServletCache::getInstance().cacheSize());
controller.setEndpoint(endpoint);
controller.accept().wait();
http_client client{{endpoint}};
auto task1 = client.request(methods::POST, "/login");
auto result1 = task1.wait();
ASSERT_EQ(pplx::completed, result1);
auto response = task1.get();
EXPECT_EQ(http::status_codes::Unauthorized, response.status_code());
auto task2 = response.extract_string();
auto result2 = task2.wait();
ASSERT_EQ(pplx::completed, result2);
ASSERT_EQ("ACCESS DENIED", task2.get());
controller.shutdown().wait();
}
} // namespace
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 31.156051
| 88
| 0.69263
|
angelcaban
|
fef46847de52199d4d5232b62c53b9f42c8bca4a
| 5,387
|
cpp
|
C++
|
3rd/snap7-1.4.2/src/sys/snap_threads.cpp
|
xeniumlee/edge.skynet
|
011b227e67663f298d6dd02b82eb41d30c6924f1
|
[
"MIT"
] | 133
|
2015-02-19T04:49:23.000Z
|
2022-02-23T22:15:53.000Z
|
3rd/snap7-1.4.2/src/sys/snap_threads.cpp
|
xeniumlee/edge.skynet
|
011b227e67663f298d6dd02b82eb41d30c6924f1
|
[
"MIT"
] | 76
|
2015-02-21T09:41:56.000Z
|
2022-03-03T11:59:15.000Z
|
3rd/snap7-1.4.2/src/sys/snap_threads.cpp
|
xeniumlee/edge.skynet
|
011b227e67663f298d6dd02b82eb41d30c6924f1
|
[
"MIT"
] | 51
|
2015-03-02T21:48:09.000Z
|
2022-03-17T12:10:36.000Z
|
/*=============================================================================|
| PROJECT SNAP7 1.3.0 |
|==============================================================================|
| Copyright (C) 2013, 2015 Davide Nardella |
| All rights reserved. |
|==============================================================================|
| SNAP7 is free software: you can redistribute it and/or modify |
| it under the terms of the Lesser GNU General Public License as published by |
| the Free Software Foundation, either version 3 of the License, or |
| (at your option) any later version. |
| |
| It means that you can distribute your commercial software linked with |
| SNAP7 without the requirement to distribute the source code of your |
| application and without the requirement that your application be itself |
| distributed under LGPL. |
| |
| SNAP7 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 |
| Lesser GNU General Public License for more details. |
| |
| You should have received a copy of the GNU General Public License and a |
| copy of Lesser GNU General Public License along with Snap7. |
| If not, see http://www.gnu.org/licenses/ |
|=============================================================================*/
#include "snap_threads.h"
//---------------------------------------------------------------------------
#ifdef OS_WINDOWS
DWORD WINAPI ThreadProc(LPVOID param)
#else
void* ThreadProc(void* param)
#endif
{
PSnapThread Thread;
// Unix but not Solaris
#if (defined(POSIX) || defined(OS_OSX)) && (!defined(OS_SOLARIS_NATIVE_THREADS))
int last_type, last_state;
pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &last_type);
pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, &last_state);
#endif
Thread = PSnapThread(param);
if (!Thread->Terminated)
try
{
Thread->Execute();
} catch (...)
{
};
Thread->Closed = true;
if (Thread->FreeOnTerminate)
{
delete Thread;
};
#ifdef OS_WINDOWS
ExitThread(0);
#endif
#if defined(POSIX) && (!defined(OS_SOLARIS_NATIVE_THREADS))
pthread_exit((void*)0);
#endif
#if defined(OS_OSX)
pthread_exit((void*)0);
#endif
#ifdef OS_SOLARIS_NATIVE_THREADS
thr_exit((void*)0);
#endif
return 0; // never reach, only to avoid compiler warning
}
//---------------------------------------------------------------------------
TSnapThread::TSnapThread()
{
Started = false;
Closed=false;
Terminated = false;
FreeOnTerminate = false;
}
//---------------------------------------------------------------------------
TSnapThread::~TSnapThread()
{
if (Started && !Closed)
{
Terminate();
Join();
};
#ifdef OS_WINDOWS
if (Started)
CloseHandle(th);
#endif
}
//---------------------------------------------------------------------------
void TSnapThread::ThreadCreate()
{
#ifdef OS_WINDOWS
th = CreateThread(0, 0, ThreadProc, this, 0, 0);
#endif
#if defined(POSIX) && (!defined(OS_SOLARIS_NATIVE_THREADS))
pthread_attr_t a;
pthread_attr_init(&a);
pthread_attr_setdetachstate(&a, PTHREAD_CREATE_DETACHED);
pthread_create(&th, &a, &ThreadProc, this);
#endif
#if defined(OS_OSX)
pthread_create(&th, 0, &ThreadProc, this);
#endif
#ifdef OS_SOLARIS_NATIVE_THREADS
thr_create(0, // default stack base
0, // default stack size
&ThreadProc, // Thread routine
this, // argument
0,
&th);
#endif
}
//---------------------------------------------------------------------------
void TSnapThread::Start()
{
if (!Started)
{
ThreadCreate();
Started = true;
}
}
//---------------------------------------------------------------------------
void TSnapThread::Terminate()
{
Terminated = true;
}
//---------------------------------------------------------------------------
void TSnapThread::Kill()
{
if (Started && !Closed)
{
ThreadKill();
Closed = true;
}
}
//---------------------------------------------------------------------------
void TSnapThread::Join()
{
if (Started && !Closed)
{
ThreadJoin();
Closed = true;
}
}
//---------------------------------------------------------------------------
longword TSnapThread::WaitFor(uint64_t Timeout)
{
if (Started)
{
if (!Closed)
return ThreadWait(Timeout);
else
return WAIT_OBJECT_0;
}
else
return WAIT_OBJECT_0;
}
//---------------------------------------------------------------------------
| 33.04908
| 80
| 0.437906
|
xeniumlee
|
67940aaa92211fc635e986b50812605503c0f757
| 2,062
|
hpp
|
C++
|
libraries/kid/include/bts/kid/name_record.hpp
|
denkhaus/bitsharesx
|
60b3653881e02873ff6802ea0c5e3c531da773c0
|
[
"Unlicense"
] | 1
|
2018-01-25T19:18:09.000Z
|
2018-01-25T19:18:09.000Z
|
libraries/kid/include/bts/kid/name_record.hpp
|
denkhaus/bitsharesx
|
60b3653881e02873ff6802ea0c5e3c531da773c0
|
[
"Unlicense"
] | null | null | null |
libraries/kid/include/bts/kid/name_record.hpp
|
denkhaus/bitsharesx
|
60b3653881e02873ff6802ea0c5e3c531da773c0
|
[
"Unlicense"
] | null | null | null |
#include <fc/crypto/elliptic.hpp>
#include <fc/time.hpp>
#include <fc/reflect/reflect.hpp>
namespace bts { namespace kid
{
struct name_record
{
name_record():nonce(0){}
fc::sha256 digest()const;
fc::sha256 digest512()const;
uint64_t difficulty()const;
std::string name;
fc::ecc::public_key master_key;
fc::ecc::public_key active_key;
fc::sha256 prev_block_id;
fc::time_point_sec last_update;
fc::time_point_sec first_update;
uint32_t nonce; // used to rate limit
};
struct signed_name_record : public name_record
{
fc::sha256 id()const;
fc::ecc::public_key get_signee()const;
void sign( const fc::ecc::private_key& master_key );
fc::ecc::compact_signature master_signature;
};
struct block
{
block():number(0),difficulty(1000){}
fc::sha256 digest()const;
uint32_t number;
fc::time_point_sec timestamp;
uint64_t difficulty;
std::vector<signed_name_record> records;
};
struct signed_block : public block
{
fc::sha256 id()const;
void sign( const fc::ecc::private_key& trustee_priv_key );
void verify( const fc::ecc::public_key& trustee_pub_key );
fc::ecc::compact_signature trustee_signature;
};
struct stored_key
{
fc::ecc::public_key get_signee()const;
std::vector<char> encrypted_key;
fc::ecc::compact_signature signature;
};
} } // namespace bts::kid
FC_REFLECT( bts::kid::name_record, (name)(master_key)(active_key)(prev_block_id)(last_update)(first_update)(nonce) )
FC_REFLECT_DERIVED( bts::kid::signed_name_record, (bts::kid::name_record), (master_signature) )
FC_REFLECT( bts::kid::block, (number)(timestamp)(difficulty)(records) )
FC_REFLECT_DERIVED( bts::kid::signed_block, (bts::kid::block), (trustee_signature) )
FC_REFLECT( bts::kid::stored_key, (encrypted_key)(signature) )
| 31.723077
| 116
| 0.625606
|
denkhaus
|
67981bdb8f675c75abc54b9f0046564817586c4f
| 14,279
|
cpp
|
C++
|
src/package.cpp
|
akivajp/lev
|
945aa438ce4718f60cde35556c55655515cb423b
|
[
"MIT"
] | null | null | null |
src/package.cpp
|
akivajp/lev
|
945aa438ce4718f60cde35556c55655515cb423b
|
[
"MIT"
] | null | null | null |
src/package.cpp
|
akivajp/lev
|
945aa438ce4718f60cde35556c55655515cb423b
|
[
"MIT"
] | null | null | null |
/////////////////////////////////////////////////////////////////////////////
// Name: src/package.cpp
// Purpose: source for package management
// Author: Akiva Miura <akiva.miura@gmail.com>
// Modified by:
// Created: 09/01/2011
// Copyright: (C) 2010-2012 Akiva Miura
// Licence: MIT License
/////////////////////////////////////////////////////////////////////////////
// pre-compiled header
#include "prec.h"
// declarations
#include "lev/package.hpp"
// dependencies
#include "lev/archive.hpp"
#include "lev/debug.hpp"
#include "lev/entry.hpp"
#include "lev/fs.hpp"
#include "lev/util.hpp"
#include "lev/system.hpp"
// libraries
#include <luabind/raw_policy.hpp>
#include <luabind/luabind.hpp>
int luaopen_lev_package(lua_State *L)
{
using namespace lev;
using namespace luabind;
open(L);
globals(L)["require"]("table");
module(L, "lev")
[
namespace_("package")
[
def("add_font", &package::add_font, raw(_1)),
def("add_font_dir", &package::add_font_dir, raw(_1)),
def("add_path", &package::add_path, raw(_1)),
def("find_font", &package::find_font, raw(_1)),
def("find_font", &package::find_font0, raw(_1)),
def("get_font_dirs", &package::get_font_dirs, raw(_1)),
def("get_font_list", &package::get_font_list, raw(_1)),
def("resolve", &package::resolve, raw(_1))
]
];
object lev = globals(L)["lev"];
object package = lev["package"];
register_to(package, "add_search", &package::add_search_l);
register_to(package, "clear_search", &package::clear_search_l);
register_to(package, "dofile", &package::dofile_l);
register_to(package, "require", &package::require_l);
lev["dofile"] = package["dofile"];
lev["require"] = package["require"];
globals(L)["package"]["loaded"]["lev.package"] = package;
return 0;
}
namespace lev
{
static int traceback (lua_State *L) {
if (!lua_isstring(L, 1)) /* 'message' not a string? */
return 1; /* keep it intact */
lua_getfield(L, LUA_GLOBALSINDEX, "debug");
if (!lua_istable(L, -1)) {
lua_pop(L, 1);
return 1;
}
lua_getfield(L, -1, "traceback");
if (!lua_isfunction(L, -1)) {
lua_pop(L, 2);
return 1;
}
lua_pushvalue(L, 1); /* pass error message */
lua_pushinteger(L, 2); /* skip this function and traceback */
lua_call(L, 2, 1); /* call debug.traceback */
return 1;
}
static int dobuffer(lua_State *L, const std::string &name, const std::string &data)
{
lua_pushcfunction(L, traceback);
int trace_pos = lua_gettop(L);
int result = luaL_loadbuffer(L, data.c_str(), data.length(), name.c_str())
|| lua_pcall(L, 0, LUA_MULTRET, trace_pos);
lua_remove(L, trace_pos);
return result;
}
static bool purge_path(std::string &path)
{
long double_slash = path.find("//", 1);
while (double_slash != std::string::npos)
{
path.replace(double_slash, 2, "/");
double_slash = path.find("//", 1);
}
return true;
}
bool package::add_font(lua_State *L, const std::string &filename)
{
luabind::open(L);
luabind::globals(L)["require"]("lev.package");
luabind::object t = luabind::globals(L)["lev"]["package"]["get_font_list"]();
luabind::globals(L)["table"]["insert"](t, 1, filename);
return true;
}
bool package::add_font_dir(lua_State *L, const std::string &dir)
{
luabind::open(L);
luabind::globals(L)["require"]("lev.package");
luabind::object t = luabind::globals(L)["lev"]["package"]["get_font_dirs"]();
luabind::globals(L)["table"]["insert"](t, 1, dir);
}
bool package::add_path(lua_State *L, const std::string &path)
{
using namespace luabind;
open(L);
globals(L)["require"]("lev.package");
if (! globals(L)["lev"]["package"]["path_list"])
{
globals(L)["lev"]["package"]["path_list"] = newtable(L);
}
globals(L)["table"]["insert"](globals(L)["lev"]["package"]["path_list"], 1, path);
return true;
}
bool package::add_search(lua_State *L, const std::string &search)
{
using namespace luabind;
open(L);
globals(L)["require"]("table");
module(L, "lev")
[
namespace_("package")
];
if (! globals(L)["lev"]["package"]["search_list"])
{
globals(L)["lev"]["package"]["search_list"] = newtable(L);
}
globals(L)["table"]["insert"](globals(L)["lev"]["package"]["search_list"], 1, search);
return true;
}
int package::add_search_l(lua_State *L)
{
using namespace luabind;
const char *search = NULL;
object t = util::get_merged(L, 1, -1);
if (t["search_path"]) { search = object_cast<const char *>(t["search_path"]); }
else if (t["search"]) { search = object_cast<const char *>(t["search"]); }
else if (t["path"]) { search = object_cast<const char *>(t["path"]); }
else if (t["lua.string1"]) { search = object_cast<const char *>(t["lua.string1"]); }
if (search == NULL) { luaL_error(L, "path (string) is not given"); }
lua_pushboolean(L, package::add_search(L, search));
return 1;
}
int package::clear_search_l(lua_State *L)
{
using namespace luabind;
module(L, "lev") [ namespace_("package") ];
globals(L)["lev"]["package"]["search_path"] = luabind::nil;
lua_pushboolean(L, true);
return 1;
}
bool package::dofile(lua_State *L, const std::string &filename)
{
using namespace luabind;
file::ptr f = package::resolve(L, filename);
if (f)
{
std::string data;
if (! f->read_all(data))
{
return false;
}
if (dobuffer(L, filename.c_str(), data) != 0)
{
lev::debug_print(lua_tostring(L, -1));
return false;
}
return true;
}
lev::debug_print("cannnot open " + filename + ": No such file or directory");
return true;
}
int package::dofile_l(lua_State *L)
{
using namespace luabind;
int last_top = lua_gettop(L);
luaL_checkstring(L, 1);
std::string filename = object_cast<const char *>(object(from_stack(L, 1)));
object path_list = package::get_path_list(L);
file::ptr f = package::resolve(L, filename);
if (f)
{
std::string data;
if (! f->read_all(data)) { return 0; }
if (dobuffer(L, filename.c_str(), data) != 0)
{
lev::debug_print(lua_tostring(L, -1));
return 0;
}
return lua_gettop(L) - last_top;
}
luaL_error(L, ("cannnot open " + filename + ": No such file or directory").c_str());
return 0;
}
boost::shared_ptr<font> package::find_font(lua_State *L, const std::string &filename)
{
using namespace luabind;
boost::shared_ptr<font> f;
try {
globals(L)["require"]("lev.font");
object dirs = package::get_font_dirs(L);
for (iterator i(dirs), end; i != end; i++)
{
std::string path = object_cast<const char *>(*i);
if (fs::is_file(path + "/" + filename))
{
f = font::load(path + "/" + filename);
if (f) { break; }
}
}
}
catch (...) {
f.reset();
lev::debug_print(lua_tostring(L, -1));
lev::debug_print("error on font finding");
}
return f;
}
boost::shared_ptr<font> package::find_font0(lua_State *L)
{
using namespace luabind;
boost::shared_ptr<font> f;
try {
globals(L)["require"]("lev.font");
object fonts = package::get_font_list(L);
for (iterator i(fonts), end; i != end; i++)
{
std::string filename = object_cast<const char *>(*i);
f = package::find_font(L, filename);
if (f) { break; }
}
}
catch (...) {
f.reset();
lev::debug_print(lua_tostring(L, -1));
lev::debug_print("error on font finding\n");
}
return f;
}
luabind::object package::get_font_dirs(lua_State *L)
{
using namespace luabind;
open(L);
module(L, "lev")
[
namespace_("package")
];
if (! globals(L)["lev"]["package"]["font_dirs"])
{
object t = newtable(L);
globals(L)["lev"]["package"]["font_dirs"] = t;
globals(L)["table"]["insert"](t, "./");
globals(L)["table"]["insert"](t, "./fonts");
globals(L)["table"]["insert"](t, "/usr/share/fonts/corefonts");
globals(L)["table"]["insert"](t, "C:/system/fonts");
return t;
}
return globals(L)["lev"]["package"]["font_dirs"];
}
luabind::object package::get_font_list(lua_State *L)
{
using namespace luabind;
open(L);
globals(L)["require"]("lev.package");
if (! globals(L)["lev"]["package"]["font_list"])
{
object t = newtable(L);
globals(L)["lev"]["package"]["font_list"] = t;
globals(L)["table"]["insert"](t, "default.ttf");
globals(L)["table"]["insert"](t, "arial.ttf");
}
return globals(L)["lev"]["package"]["font_list"];
}
luabind::object package::get_path_list(lua_State *L)
{
using namespace luabind;
open(L);
module(L, "lev")
[
namespace_("package")
];
if (! globals(L)["lev"]["package"]["path_list"])
{
object path_list = newtable(L);
path_list[1] = "./";
globals(L)["lev"]["package"]["path_list"] = path_list;
}
return globals(L)["lev"]["package"]["path_list"];
}
luabind::object package::get_search_list(lua_State *L)
{
using namespace luabind;
open(L);
module(L, "lev")
[
namespace_("package")
];
if (! globals(L)["lev"]["package"]["search_list"])
{
object search_list = newtable(L);
search_list[1] = "";
globals(L)["lev"]["package"]["search_list"] = search_list;
}
return globals(L)["lev"]["package"]["search_list"];
}
int package::require_l(lua_State *L)
{
using namespace luabind;
luaL_checkstring(L, 1);
std::string module = object_cast<const char *>(object(from_stack(L, 1)));
if (globals(L)["package"]["loaded"][module])
{
object t = globals(L)["package"]["loaded"][module];
t.push(L);
return 1;
}
file::ptr f = package::resolve(L, module);
if (! f) { f = package::resolve(L, module + ".lua"); }
if (f)
{
std::string data;
if (! f->read_all(data)) { return 0; }
if (dobuffer(L, module.c_str(), data.c_str()))
{
lev::debug_print(lua_tostring(L, -1));
lua_pushnil(L);
return 1;
}
if (! globals(L)["package"]["loaded"][module])
{
globals(L)["package"]["loaded"][module] = true;
}
globals(L)["package"]["loaded"][module].push(L);
return 1;
}
try {
object result = globals(L)["require"](module);
result.push(L);
return 1;
}
catch (...) {
luaL_error(L, ("module '" + module + "' not found").c_str());
return 0;
}
}
// filepath::ptr package::resolve(lua_State *L, const std::string &file)
file::ptr package::resolve(lua_State *L, const std::string &file)
{
using namespace luabind;
try {
object path_list = package::get_path_list(L);
object search_list = package::get_search_list(L);
for (iterator p(path_list), end; p != end; p++)
{
std::string path = object_cast<const char *>(*p);
for (iterator s(search_list); s != end; s++)
{
std::string search = object_cast<const char *>(*s);
std::string real_path = path + "/" + search + "/" + file;
purge_path(real_path);
if (fs::is_file(real_path))
{
return file::open(real_path, "rb");
// return filepath::create(real_path);
}
}
if (lev::archive::is_archive(path))
{
for (iterator s(search_list); s != end; s++)
{
std::string entry = object_cast<const char *>(*s);
if (entry.empty()) { entry = file; }
else { entry = entry + "/" + file; }
if (archive::entry_exists_direct(path, entry))
{
std::string sys_name = ".";
if (system::get()) { sys_name = system::get()->get_name(); }
std::string ext = fs::to_extension(file);
// filepath::ptr fpath(filepath::create_temp(sys_name + "/", ext));
// if (! fpath) { return fpath; }
// lev::archive::extract_direct_to(path, entry, fpath->get_string());
// return fpath;
return archive::extract_direct(path, entry, NULL);
}
}
std::string arc_name = fs::to_stem(path);
for (iterator s(search_list); s != end; s++)
{
std::string entry = object_cast<const char *>(*s);
if (entry.empty()) { entry = arc_name + "/" + file; }
else { entry = arc_name + "/" + entry + "/" + file; }
if (archive::entry_exists_direct(path, entry))
{
std::string sys_name = ".";
if (system::get()) { sys_name = system::get()->get_name(); }
std::string ext = fs::to_extension(file);
// filepath::ptr fpath(filepath::create_temp(sys_name + "/", ext));
// if (! fpath) { return fpath; }
// lev::archive::extract_direct_to(path, entry, fpath->get_string());
// return fpath;
return archive::extract_direct(path, entry, NULL);
}
}
}
}
}
catch (...) {
lev::debug_print("error on file path resolving");
}
return file::ptr();
}
bool package::set_default_font_dirs(lua_State *L)
{
using namespace luabind;
open(L);
globals(L)["require"]("table");
module(L, "lev")
[
namespace_("package")
];
try {
object list = newtable(L);
globals(L)["lev"]["package"]["font_dirs"] = list;
#if (defined(_WIN32))
globals(L)["table"]["insert"](list, 1, "C:/Windows/Fonts");
#elif (defined(__linux))
globals(L)["table"]["insert"](list, 1, "/usr/share/fonts/");
#else
#endif // _WIN32
globals(L)["table"]["insert"](list, 1, "./");
globals(L)["table"]["insert"](list, 1, "./font");
globals(L)["table"]["insert"](list, 1, "./fonts");
return true;
}
catch (...) {
return false;
}
}
}
| 28.275248
| 90
| 0.555011
|
akivajp
|
679d36cd794c628dc3f91a0716de1834fafb66e1
| 3,494
|
cpp
|
C++
|
src/ThirdParty/jvarTest.cpp
|
beached/JsonBenchmark
|
87d4862f872cb05d58ccbfb4df008e0c4ca72818
|
[
"MIT"
] | 7
|
2020-07-22T10:45:44.000Z
|
2021-09-30T10:09:54.000Z
|
src/ThirdParty/jvarTest.cpp
|
beached/JsonBenchmark
|
87d4862f872cb05d58ccbfb4df008e0c4ca72818
|
[
"MIT"
] | 6
|
2020-07-25T08:58:25.000Z
|
2020-07-30T10:12:20.000Z
|
src/ThirdParty/jvarTest.cpp
|
beached/JsonBenchmark
|
87d4862f872cb05d58ccbfb4df008e0c4ca72818
|
[
"MIT"
] | 1
|
2021-05-29T21:15:01.000Z
|
2021-05-29T21:15:01.000Z
|
#include "test.h"
#include "jvar/include/jvar.h"
#include "jvar/include/util.h"
#include "jvar/include/var.h"
#include "jvar/include/str.h"
#include "jvar/include/json.h"
#include "jvar/include/arr.h"
#include <memory>
using namespace jvar;
static void GenStat(Stat& stat, Variant* v)
{
switch (v->type())
{
case Variant::V_ARRAY:
{
for (Iter<Variant> i; v->forEach(i); )
{
GenStat(stat, &i);
}
stat.arrayCount++;
stat.elementCount += v->length();
}
break;
case Variant::V_OBJECT:
for (Iter<Variant> i; v->forEach(i); )
{
GenStat(stat, &i);
stat.stringLength += strlen(i.key());
}
stat.objectCount++;
stat.memberCount += v->length();
stat.stringCount += v->length();
break;
case Variant::V_STRING:
stat.stringCount++;
stat.stringLength += v->s().length();
break;
case Variant::V_INT:
case Variant::V_DOUBLE:
stat.numberCount++;
break;
case Variant::V_BOOL:
if (v->toBool())
{
stat.trueCount++;
}
else
{
stat.falseCount++;
}
break;
case Variant::V_NULL:
case Variant::V_EMPTY:
stat.nullCount++;
break;
default:
break;
}
}
class JvarParseResult : public ParseResultBase
{
public:
Variant mVar;
};
class JvarStringResult : public StringResultBase
{
public:
virtual const char* c_str() const
{
return mStr.c_str();
}
std::string mStr;
};
class JvarTest : public TestBase {
public:
virtual const char* GetName() const { return "jvar"; }
virtual const char* Type() const { return "C++";}
virtual const char* GetFilename() const { return __FILE__; }
virtual ParseResultBase* Parse(const char* json, size_t /*length*/) const
{
JvarParseResult* p = new JvarParseResult;
if (!p->mVar.parseJson(json))
{
delete p;
p = NULL;;
}
return p;
}
virtual StringResultBase* Stringify(const ParseResultBase* parseResult) const
{
const JvarParseResult* p = (const JvarParseResult*)parseResult;
JvarStringResult* sr = new JvarStringResult;
sr->mStr = p->mVar.toString();
return sr;
}
virtual bool Statistics(const ParseResultBase* parseResult, Stat* stat) const
{
const JvarParseResult* p = (const JvarParseResult*)parseResult;
memset(stat, 0, sizeof(Stat));
GenStat(*stat, (Variant*)&p->mVar);
return true;
}
virtual bool ParseDouble(const char* json, double* d) const
{
Variant v;
if (v.parseJson(json) &&
v.isArray() &&
v.length() == 1)
{
if (v[0].type() == Variant::V_DOUBLE || v[0].type() == Variant::V_INT)
{
*d = v[0].toDouble();
return true;
}
}
return false;
}
virtual bool ParseString(const char* json, std::string& s) const
{
Variant v;
if (v.parseJson(json) &&
v.isArray() &&
v.length() == 1 &&
v[0].type() == Variant::V_STRING)
{
s = v[0].toString();
return true;
}
else
{
return false;
}
}
};
REGISTER_TEST(JvarTest);
| 22.113924
| 82
| 0.524041
|
beached
|
67a12d236833f9b07ce8184646f77b7be4976ea5
| 1,016
|
hpp
|
C++
|
include/game/skirmish/coordinates.hpp
|
namelessvoid/qrwar
|
bbc4036cd3bab6b0edcaccbc95286379ef51f12b
|
[
"MIT"
] | 3
|
2015-03-28T02:51:58.000Z
|
2018-11-08T16:49:53.000Z
|
include/game/skirmish/coordinates.hpp
|
namelessvoid/qrwar
|
bbc4036cd3bab6b0edcaccbc95286379ef51f12b
|
[
"MIT"
] | 39
|
2015-05-18T08:29:16.000Z
|
2020-07-18T21:17:44.000Z
|
include/game/skirmish/coordinates.hpp
|
namelessvoid/qrwar
|
bbc4036cd3bab6b0edcaccbc95286379ef51f12b
|
[
"MIT"
] | null | null | null |
#ifndef QRW_COORDINATES_HPP
#define QRW_COORDINATES_HPP
#include "core/sid.hpp"
#include "meta/reflectable.hpp"
namespace qrw
{
class Coordinates : public Reflectable
{
public:
friend class CoordinateMetaClass;
static SID typeName;
const SID& getTypeName() const override { return typeName; }
Coordinates();
Coordinates(int x, int y);
Coordinates(const Coordinates& rhs)
{
_x = rhs._x;
_y = rhs._y;
}
Coordinates& operator=(const Coordinates& rhs)
{
_x = rhs._x;
_y = rhs._y;
return *this;
}
int getX() const;
int getY() const;
bool operator==(const Coordinates& rhs) const;
bool operator!=(const Coordinates& rhs) const;
bool operator<(const Coordinates& rhs) const;
bool operator>(const Coordinates& rhs) const;
Coordinates operator+(const Coordinates& rhs) const;
Coordinates operator-(const Coordinates& rhs) const;
unsigned int distanceTo(const Coordinates& b) const;
private:
int _x;
int _y;
};
}
#endif
| 18.472727
| 63
| 0.680118
|
namelessvoid
|
67a38dd233ddc1d2209bb6b47a22be249c5e3398
| 3,612
|
hpp
|
C++
|
include/extractor/internal_extractor_edge.hpp
|
neilbu/osrm-backend
|
2a8e1f77459fef33ca34c9fe01ec62e88e255452
|
[
"BSD-2-Clause"
] | null | null | null |
include/extractor/internal_extractor_edge.hpp
|
neilbu/osrm-backend
|
2a8e1f77459fef33ca34c9fe01ec62e88e255452
|
[
"BSD-2-Clause"
] | null | null | null |
include/extractor/internal_extractor_edge.hpp
|
neilbu/osrm-backend
|
2a8e1f77459fef33ca34c9fe01ec62e88e255452
|
[
"BSD-2-Clause"
] | 1
|
2021-11-24T14:24:44.000Z
|
2021-11-24T14:24:44.000Z
|
#ifndef INTERNAL_EXTRACTOR_EDGE_HPP
#define INTERNAL_EXTRACTOR_EDGE_HPP
#include "extractor/guidance/road_classification.hpp"
#include "extractor/guidance/turn_lane_types.hpp"
#include "extractor/node_based_edge.hpp"
#include "extractor/travel_mode.hpp"
#include "osrm/coordinate.hpp"
#include "util/typedefs.hpp"
#include <boost/assert.hpp>
#include <mapbox/variant.hpp>
#include <utility>
namespace osrm
{
namespace extractor
{
namespace detail
{
// Use a single float to pack two positive values:
// * by_edge: + sign, value >= 0, value used as the edge weight
// * by_meter: - sign, value > 0, value used as a denominator in distance / value
struct ByEdgeOrByMeterValue
{
struct ValueByEdge
{
} static const by_edge;
struct ValueByMeter
{
} static const by_meter;
ByEdgeOrByMeterValue() : value(0.f) {}
ByEdgeOrByMeterValue(ValueByEdge, double input)
{
BOOST_ASSERT(input >= 0.f);
value = static_cast<value_type>(input);
}
ByEdgeOrByMeterValue(ValueByMeter, double input)
{
BOOST_ASSERT(input > 0.f);
value = -static_cast<value_type>(input);
}
double operator()(double distance) { return value >= 0 ? value : -distance / value; }
private:
using value_type = float;
value_type value;
};
}
struct InternalExtractorEdge
{
using WeightData = detail::ByEdgeOrByMeterValue;
using DurationData = detail::ByEdgeOrByMeterValue;
explicit InternalExtractorEdge() : weight_data(), duration_data() {}
explicit InternalExtractorEdge(OSMNodeID source,
OSMNodeID target,
WeightData weight_data,
DurationData duration_data,
util::Coordinate source_coordinate)
: result(source, target, 0, 0, {}, -1, {}), weight_data(std::move(weight_data)),
duration_data(std::move(duration_data)), source_coordinate(std::move(source_coordinate))
{
}
explicit InternalExtractorEdge(NodeBasedEdgeWithOSM edge,
WeightData weight_data,
DurationData duration_data,
util::Coordinate source_coordinate)
: result(std::move(edge)), weight_data(weight_data), duration_data(duration_data),
source_coordinate(source_coordinate)
{
}
// data that will be written to disk
NodeBasedEdgeWithOSM result;
// intermediate edge weight
WeightData weight_data;
// intermediate edge duration
DurationData duration_data;
// coordinate of the source node
util::Coordinate source_coordinate;
// necessary static util functions for stxxl's sorting
static InternalExtractorEdge min_osm_value()
{
return InternalExtractorEdge(
MIN_OSM_NODEID, MIN_OSM_NODEID, WeightData(), DurationData(), util::Coordinate());
}
static InternalExtractorEdge max_osm_value()
{
return InternalExtractorEdge(
MAX_OSM_NODEID, MAX_OSM_NODEID, WeightData(), DurationData(), util::Coordinate());
}
static InternalExtractorEdge min_internal_value()
{
auto v = min_osm_value();
v.result.source = 0;
v.result.target = 0;
return v;
}
static InternalExtractorEdge max_internal_value()
{
auto v = max_osm_value();
v.result.source = std::numeric_limits<NodeID>::max();
v.result.target = std::numeric_limits<NodeID>::max();
return v;
}
};
}
}
#endif // INTERNAL_EXTRACTOR_EDGE_HPP
| 29.606557
| 98
| 0.650886
|
neilbu
|
67a4625ed3e410aad9ed727da698dc60d6772ff9
| 2,821
|
hpp
|
C++
|
Nacro/SDK/FN_AthenaLeaderboardTabButton_parameters.hpp
|
Milxnor/Nacro
|
eebabf662bbce6d5af41820ea0342d3567a0aecc
|
[
"BSD-2-Clause"
] | 11
|
2021-08-08T23:25:10.000Z
|
2022-02-19T23:07:22.000Z
|
Nacro/SDK/FN_AthenaLeaderboardTabButton_parameters.hpp
|
Milxnor/Nacro
|
eebabf662bbce6d5af41820ea0342d3567a0aecc
|
[
"BSD-2-Clause"
] | 1
|
2021-08-11T18:40:26.000Z
|
2021-08-11T18:40:26.000Z
|
Nacro/SDK/FN_AthenaLeaderboardTabButton_parameters.hpp
|
Milxnor/Nacro
|
eebabf662bbce6d5af41820ea0342d3567a0aecc
|
[
"BSD-2-Clause"
] | 8
|
2021-08-09T13:51:54.000Z
|
2022-01-26T20:33:37.000Z
|
#pragma once
// Fortnite (1.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function AthenaLeaderboardTabButton.AthenaLeaderboardTabButton_C.ShowText
struct UAthenaLeaderboardTabButton_C_ShowText_Params
{
};
// Function AthenaLeaderboardTabButton.AthenaLeaderboardTabButton_C.Set Icon
struct UAthenaLeaderboardTabButton_C_Set_Icon_Params
{
struct FSlateBrush IconBrush; // (Parm)
};
// Function AthenaLeaderboardTabButton.AthenaLeaderboardTabButton_C.Set Text
struct UAthenaLeaderboardTabButton_C_Set_Text_Params
{
struct FText ButtonText; // (Parm)
};
// Function AthenaLeaderboardTabButton.AthenaLeaderboardTabButton_C.PreConstruct
struct UAthenaLeaderboardTabButton_C_PreConstruct_Params
{
bool* IsDesignTime; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function AthenaLeaderboardTabButton.AthenaLeaderboardTabButton_C.OnCurrentTextStyleChanged
struct UAthenaLeaderboardTabButton_C_OnCurrentTextStyleChanged_Params
{
};
// Function AthenaLeaderboardTabButton.AthenaLeaderboardTabButton_C.SetTabLabelInfo
struct UAthenaLeaderboardTabButton_C_SetTabLabelInfo_Params
{
struct FFortTabButtonLabelInfo TabLabelInfo; // (ConstParm, Parm, OutParm, ReferenceParm)
};
// Function AthenaLeaderboardTabButton.AthenaLeaderboardTabButton_C.OnSelected
struct UAthenaLeaderboardTabButton_C_OnSelected_Params
{
};
// Function AthenaLeaderboardTabButton.AthenaLeaderboardTabButton_C.OnDeselected
struct UAthenaLeaderboardTabButton_C_OnDeselected_Params
{
};
// Function AthenaLeaderboardTabButton.AthenaLeaderboardTabButton_C.Construct
struct UAthenaLeaderboardTabButton_C_Construct_Params
{
};
// Function AthenaLeaderboardTabButton.AthenaLeaderboardTabButton_C.OnHovered
struct UAthenaLeaderboardTabButton_C_OnHovered_Params
{
};
// Function AthenaLeaderboardTabButton.AthenaLeaderboardTabButton_C.OnUnhovered
struct UAthenaLeaderboardTabButton_C_OnUnhovered_Params
{
};
// Function AthenaLeaderboardTabButton.AthenaLeaderboardTabButton_C.ExecuteUbergraph_AthenaLeaderboardTabButton
struct UAthenaLeaderboardTabButton_C_ExecuteUbergraph_AthenaLeaderboardTabButton_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 32.425287
| 154
| 0.689826
|
Milxnor
|
67a46dca2533e0f32b5eb37c87a52aa4de4b6429
| 2,666
|
cpp
|
C++
|
include/base/util/unicode.cpp
|
HaiyongLi/LuaDebugCode
|
8a12e5b21ab5fb74b7b5cd1b50393191df1382ca
|
[
"MIT"
] | 2
|
2019-09-29T07:06:32.000Z
|
2021-09-10T09:46:19.000Z
|
include/base/util/unicode.cpp
|
HaiyongLi/LuaDebugCode
|
8a12e5b21ab5fb74b7b5cd1b50393191df1382ca
|
[
"MIT"
] | null | null | null |
include/base/util/unicode.cpp
|
HaiyongLi/LuaDebugCode
|
8a12e5b21ab5fb74b7b5cd1b50393191df1382ca
|
[
"MIT"
] | null | null | null |
#include <base/util/unicode.h>
#include <rapidjson/encodings.h>
#include <vector>
#if defined(_WIN32)
#include <Windows.h>
#endif
namespace base
{
template <class T>
struct input_stream
{
typedef T Ch;
input_stream(const T* t) : t_(t) { }
T Take() { return *t_++; }
const T* t_;
};
template <class T>
struct output_stream
{
typedef typename T::value_type Ch;
output_stream(T* t) : t_(t) { }
void Put(Ch c) { t_->push_back(c); }
T* t_;
};
std::wstring u2w(const char* str)
{
std::wstring wstr;
output_stream<std::wstring> ostream(&wstr);
for (input_stream<char> p(str);;)
{
unsigned codepoint = 0;
bool suc = rapidjson::UTF8<>::Decode(p, &codepoint);
if (suc && codepoint == 0)
break;
rapidjson::UTF16<>::Encode(ostream, suc ? codepoint : (unsigned int)L'?');
}
return wstr;
}
std::wstring u2w(const strview& str)
{
return u2w(str.data());
}
std::string w2u(const wchar_t* wstr)
{
std::string str;
output_stream<std::string> ostream(&str);
for (input_stream<wchar_t> p(wstr);;)
{
unsigned codepoint = 0;
bool suc = rapidjson::UTF16<>::Decode(p, &codepoint);
if (suc && codepoint == 0)
break;
rapidjson::UTF8<>::Encode(ostream, suc ? codepoint : (unsigned int)'?');
}
return str;
}
std::string w2u(const wstrview& wstr)
{
return w2u(wstr.data());
}
#if defined(_WIN32)
std::wstring a2w(const strview& str)
{
if (str.empty())
{
return L"";
}
int wlen = ::MultiByteToWideChar(CP_ACP, 0, str.data(), static_cast<int>(str.size()), NULL, 0);
if (wlen <= 0)
{
return L"";
}
std::vector<wchar_t> result(wlen);
::MultiByteToWideChar(CP_ACP, 0, str.data(), static_cast<int>(str.size()), result.data(), wlen);
return std::wstring(result.data(), result.size());
}
std::string w2a(const wstrview& wstr)
{
if (wstr.empty())
{
return "";
}
int len = ::WideCharToMultiByte(CP_ACP, 0, wstr.data(), static_cast<int>(wstr.size()), NULL, 0, 0, 0);
if (len <= 0)
{
return "";
}
std::vector<char> result(len);
::WideCharToMultiByte(CP_ACP, 0, wstr.data(), static_cast<int>(wstr.size()), result.data(), len, 0, 0);
return std::string(result.data(), result.size());
}
std::string a2u(const strview& str)
{
return w2u(a2w(str));
}
std::string u2a(const strview& str)
{
return w2a(u2w(str));
}
#else
std::wstring a2w(const strview& str)
{
return u2w(str);
}
std::string w2a(const wstrview& wstr)
{
return w2u(wstr);
}
std::string a2u(const strview& str)
{
return std::string(str.data(), str.size());
}
std::string u2a(const strview& str)
{
return std::string(str.data(), str.size());
}
#endif
}
| 20.045113
| 105
| 0.624156
|
HaiyongLi
|
67a5372338837a665cfff0b62a048da7542226e8
| 1,602
|
cpp
|
C++
|
base/Windows/singx86/bytev.cpp
|
sphinxlogic/Singularity-RDK-2.0
|
2968c3b920a5383f7360e3e489aa772f964a7c42
|
[
"MIT"
] | null | null | null |
base/Windows/singx86/bytev.cpp
|
sphinxlogic/Singularity-RDK-2.0
|
2968c3b920a5383f7360e3e489aa772f964a7c42
|
[
"MIT"
] | null | null | null |
base/Windows/singx86/bytev.cpp
|
sphinxlogic/Singularity-RDK-2.0
|
2968c3b920a5383f7360e3e489aa772f964a7c42
|
[
"MIT"
] | null | null | null |
// ----------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ----------------------------------------------------------------------------
#include "singx86.h"
struct ByteVector {
ULONG64 ulDataOffset;
ULONG64 ulDataLength;
};
EXT_DECL(bytev) // Defines: PDEBUG_CLIENT Client, PCSTR args
{
EXT_ENTER(); // Defines: HRESULT status = S_OK;
if (!isalpha(args[0])) {
ExtOut("Usage:\n !bytev <var>\n");
goto Exit;
}
ULONG64 indirect = 0;
EXT_CHECK(g_ExtSymbols->GetOffsetByName(args, &indirect));
ULONG64 offset = 0;
EXT_CHECK(TraceReadPointer(1, indirect, &offset));
// Add type check here.
ULONG typeId;
ULONG64 module;
EXT_CHECK(g_ExtSymbols->GetSymbolTypeId(args, &typeId, &module));
CHAR szTypeName[255];
const SIZE_T cbTypeName = sizeof(szTypeName) / sizeof(szTypeName[0]);
EXT_CHECK(g_ExtSymbols->GetTypeName(module, typeId,
szTypeName, cbTypeName, NULL));
const CHAR szExpected[] = "unsigned char**";
const SIZE_T cbExpected = sizeof(szExpected) / sizeof(szExpected[0]);
if (strncmp(szTypeName, szExpected, cbExpected)) {
ExtOut("%s is not a byte vector.\n", args);
goto Exit;
}
struct ByteVector bv;
EXT_CHECK(TraceReadPointer(2, offset, (PULONG64)&bv));
ExtOut("Byte vector %s : address 0x%p length 0x%p\n",
args, bv.ulDataOffset, bv.ulDataLength);
EXT_LEAVE();
}
| 30.807692
| 80
| 0.553683
|
sphinxlogic
|
67a659291e8357acd1a0abe142e9b5af8c78988d
| 7,833
|
cpp
|
C++
|
02-Opengl-window/main.cpp
|
NeroGames/Learn-SFML
|
44e4e17b9af0eacf776f0d8bdbea869433224cff
|
[
"MIT"
] | null | null | null |
02-Opengl-window/main.cpp
|
NeroGames/Learn-SFML
|
44e4e17b9af0eacf776f0d8bdbea869433224cff
|
[
"MIT"
] | null | null | null |
02-Opengl-window/main.cpp
|
NeroGames/Learn-SFML
|
44e4e17b9af0eacf776f0d8bdbea869433224cff
|
[
"MIT"
] | null | null | null |
////////////////////////////////////////////////////////////
// Nero Game Engine - SFML Tutorials
// Copyright (c) 2021 Sanou A. K. Landry
////////////////////////////////////////////////////////////
///////////////////////////HEADERS//////////////////////////
//Glew
#include <GL/glew.h>
//SFML
#include <SFML/Window.hpp>
#include <SFML/OpenGL.hpp>
//CPP
#include <iostream>
////////////////////////////////////////////////////////////
// Forward Declaration : Utility functions
struct TriangleState{unsigned int VBO, VAO, EBO;};
sf::Vector2f pixelToNDC(const sf::Vector2f& vertex, sf::Vector2u resolution);
int createShaderProgram();
void createTriangle(TriangleState& triangle, sf::Vector2u resolution, const sf::Vector2f& vertex1, const sf::Vector2f& vertex2, const sf::Vector2f& vertex3);
void drawTriangle(TriangleState& triangle, int shaderProgram);
void destroyTriangle(TriangleState& triangle);
////////////////////////////////////////////////////////////
int main()
{
//Create OpenGL Window
//window parameters (OpenGL 3.3)
sf::Vector2u window_resolution(1080, 720);
std::string window_title = "OpenGL Window";
sf::ContextSettings contextSettings;
contextSettings.depthBits = 24;
contextSettings.stencilBits = 8;
contextSettings.antialiasingLevel = 4;
contextSettings.majorVersion = 3;
contextSettings.minorVersion = 3;
//create the window
sf::Window openGLWindow(sf::VideoMode(window_resolution.x, window_resolution.y), window_title, sf::Style::Default, contextSettings);
//setup the window
openGLWindow.setVerticalSyncEnabled(true);
openGLWindow.setActive(true);
//Initialize GLEW (OpenGL Extension Wrangler Library) and check if OpenGL is available
bool openGlAvailable = true;
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK)
{
openGlAvailable = false;
}
//If OpenGL is not available let's stop everything and exit the program.
if(!openGlAvailable) return 0;
//Initialize your game here, let's create a simple triangle
//create shader program
int shaderProgram = createShaderProgram();
//build a triangle
TriangleState triangle; //a structure to hold the OpenGL state of the triangle
createTriangle(triangle, window_resolution, sf::Vector2f(540.f, 100.f), sf::Vector2f(340.f, 360.f), sf::Vector2f(740.f, 360.f));
//Game loop
bool gameRunning = true;
while(gameRunning)
{
// handle events
sf::Event event;
while(openGLWindow.pollEvent(event))
{
if(event.type == sf::Event::Closed)
{
// end the program
gameRunning = false;
}
else if (event.type == sf::Event::Resized)
{
// adjust the viewport when the window is resized
glViewport(0, 0, event.size.width, event.size.height);
}
}
//update your game here
//we have noting to update, so it's empty
// clear the buffers
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
drawTriangle(triangle, shaderProgram);
// end the current frame (internally swaps the front and back buffers)
openGLWindow.display();
}
//Destroy triangle state
destroyTriangle(triangle);
//Destroy shader Program
glDeleteProgram(shaderProgram);
return 0;
}
int createShaderProgram()
{
const char *vertexShaderSource = "#version 330 core\n"
"layout (location = 0) in vec3 aPos;\n"
"void main()\n"
"{\n"
" gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n"
"}\0";
const char *fragmentShaderSource = "#version 330 core\n"
"out vec4 FragColor;\n"
"void main()\n"
"{\n"
" FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n"
"}\n\0";
// load resources, initialize the OpenGL states, ...
// build and compile our shader program
// ------------------------------------
// vertex shader
int vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
// check for shader compile errors
int success;
char infoLog[512];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
}
// fragment shader
int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
// check for shader compile errors
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if (!success)
{
glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
}
// link shaders
int shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
// check for linking errors
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if (!success) {
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
}
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
return shaderProgram;
}
sf::Vector2f pixelToNDC(const sf::Vector2f& vertex, sf::Vector2u resolution)
{
return sf::Vector2f(-1.f + vertex.x/resolution.x * 2.f,
1.f - vertex.y/resolution.y * 2.f);
}
void createTriangle(TriangleState& triangle, sf::Vector2u resolution, const sf::Vector2f& vertex1, const sf::Vector2f& vertex2, const sf::Vector2f& vertex3)
{
// set up vertex data (and buffer(s)) and configure vertex attributes
// ------------------------------------------------------------------
float vertices[] =
{
pixelToNDC(vertex1, resolution).x, pixelToNDC(vertex1, resolution).y, 0.0f, // left
pixelToNDC(vertex2, resolution).x, pixelToNDC(vertex2, resolution).y, 0.0f, // right
pixelToNDC(vertex3, resolution).x, pixelToNDC(vertex3, resolution).y, 0.0f // top
};
glGenVertexArrays(1, &triangle.VAO);
glGenBuffers(1, &triangle.VBO);
// bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
glBindVertexArray(triangle.VAO);
glBindBuffer(GL_ARRAY_BUFFER, triangle.VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// note that this is allowed, the call to glVertexAttribPointer registered VBO as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind
glBindBuffer(GL_ARRAY_BUFFER, 0);
// You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other
// VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary.
glBindVertexArray(0);
}
void drawTriangle(TriangleState& triangle, int shaderProgram)
{
glUseProgram(shaderProgram);
glBindVertexArray(triangle.VAO);
glDrawArrays(GL_TRIANGLES, 0, 3);
}
void destroyTriangle(TriangleState& triangle)
{
glDeleteVertexArrays(1, &triangle.VAO);
glDeleteBuffers(1, &triangle.VBO);
glDeleteBuffers(1, &triangle.EBO);
}
| 37.123223
| 170
| 0.634623
|
NeroGames
|
67a6ab2b2600f763670c66c975a683fe59560e97
| 5,213
|
cpp
|
C++
|
Source/Services/Presence/presence_title_record.cpp
|
yklys/Xbox-Live-API
|
e409400ec38c0c131b16e09281cdc83199d1c90f
|
[
"MIT"
] | 1
|
2019-04-19T01:37:34.000Z
|
2019-04-19T01:37:34.000Z
|
Source/Services/Presence/presence_title_record.cpp
|
DalavanCloud/xbox-live-api
|
2166ffcb4a1ca1f5d89a43dce9ab4c5ff9b797b7
|
[
"MIT"
] | null | null | null |
Source/Services/Presence/presence_title_record.cpp
|
DalavanCloud/xbox-live-api
|
2166ffcb4a1ca1f5d89a43dce9ab4c5ff9b797b7
|
[
"MIT"
] | null | null | null |
// Copyright (c) Microsoft Corporation
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include "pch.h"
#include "xsapi/presence.h"
#include "presence_internal.h"
NAMESPACE_MICROSOFT_XBOX_SERVICES_PRESENCE_CPP_BEGIN
presence_title_record::presence_title_record(
_In_ std::shared_ptr<presence_title_record_internal> internalObj
) :
m_internalObj(std::move(internalObj))
{
}
DEFINE_GET_UINT32(presence_title_record, title_id);
DEFINE_GET_STRING(presence_title_record, title_name);
DEFINE_GET_OBJECT_REF(presence_title_record, utility::datetime, last_modified_date);
DEFINE_GET_BOOL(presence_title_record, is_title_active);
DEFINE_GET_STRING(presence_title_record, presence);
DEFINE_GET_ENUM_TYPE(presence_title_record, presence_title_view_state, presence_title_view);
presence_broadcast_record
presence_title_record::broadcast_record() const
{
return presence_broadcast_record(m_internalObj->broadcast_record());
}
bool
presence_title_record::operator!=(
_In_ const presence_title_record& rhs
) const
{
return *m_internalObj != *rhs.m_internalObj;
}
presence_title_record_internal::presence_title_record_internal() :
m_titleViewState(presence_title_view_state::unknown),
m_titleId(0),
m_isTitleActive(false)
{
}
presence_title_record_internal::presence_title_record_internal(
_In_ uint32_t titleId,
_In_ title_presence_state titlePresenceState
) :
m_titleId(titleId),
m_titleViewState(presence_title_view_state::unknown)
{
m_isTitleActive = (titlePresenceState == title_presence_state::started);
}
uint32_t
presence_title_record_internal::title_id() const
{
return m_titleId;
}
const xsapi_internal_string&
presence_title_record_internal::title_name() const
{
return m_titleName;
}
const utility::datetime&
presence_title_record_internal::last_modified_date() const
{
return m_lastModifiedDate;
}
bool
presence_title_record_internal::is_title_active() const
{
return m_isTitleActive;
}
const xsapi_internal_string&
presence_title_record_internal::presence() const
{
return m_presence;
}
presence_title_view_state
presence_title_record_internal::presence_title_view() const
{
return m_titleViewState;
}
const std::shared_ptr<presence_broadcast_record_internal>
presence_title_record_internal::broadcast_record() const
{
return m_broadcastRecord;
}
bool
presence_title_record_internal::operator!=(
_In_ const presence_title_record_internal& rhs
) const
{
return (
m_broadcastRecord != rhs.m_broadcastRecord ||
m_isTitleActive != rhs.m_isTitleActive ||
m_lastModifiedDate != rhs.m_lastModifiedDate ||
m_presence != rhs.m_presence ||
m_titleId != rhs.m_titleId ||
m_titleName != rhs.m_titleName ||
m_titleViewState != rhs.m_titleViewState
);
}
xbox_live_result<std::shared_ptr<presence_title_record_internal>>
presence_title_record_internal::deserialize(
_In_ const web::json::value& json
)
{
auto returnObject = xsapi_allocate_shared<presence_title_record_internal>();
if (json.is_null()) return xbox_live_result<std::shared_ptr<presence_title_record_internal>>(returnObject);
std::error_code errc = xbox_live_error_code::no_error;
auto activityJson = utils::extract_json_field(json, "activity", errc, false);
returnObject->m_titleId = utils::internal_string_to_uint32(utils::extract_json_string(json, "id", errc));
returnObject->m_titleName = utils::extract_json_string(json, "name", errc);
returnObject->m_lastModifiedDate = utils::extract_json_time(json, "lastModified", errc);
xsapi_internal_string state = utils::extract_json_string(json, "state", errc);
returnObject->m_isTitleActive = (!state.empty() && utils::str_icmp(state, "active") == 0);
returnObject->m_presence = utils::extract_json_string(activityJson, "richPresence", errc);
returnObject->m_titleViewState = convert_string_to_presence_title_view_state(
utils::extract_json_string(json, "placement", errc)
);
auto broadcastRecord = presence_broadcast_record_internal::deserialize(
utils::extract_json_field(activityJson, "broadcast", errc, false)
);
if (broadcastRecord.err())
{
errc = broadcastRecord.err();
}
returnObject->m_broadcastRecord = broadcastRecord.payload();
return xbox_live_result<std::shared_ptr<presence_title_record_internal>>(returnObject, errc);
}
presence_title_view_state
presence_title_record_internal::convert_string_to_presence_title_view_state(
_In_ const xsapi_internal_string &value
)
{
if (utils::str_icmp(value, "full") == 0)
{
return presence_title_view_state::full_screen;
}
else if (utils::str_icmp(value, "fill") == 0)
{
return presence_title_view_state::filled;
}
else if (utils::str_icmp(value, "snapped") == 0)
{
return presence_title_view_state::snapped;
}
else if (utils::str_icmp(value, "background") == 0)
{
return presence_title_view_state::background;
}
return presence_title_view_state::unknown;
}
NAMESPACE_MICROSOFT_XBOX_SERVICES_PRESENCE_CPP_END
| 29.619318
| 111
| 0.761366
|
yklys
|
67aaf36ac088bd70e014232334638ae0fb58ca7a
| 3,340
|
cpp
|
C++
|
irohad/pending_txs_storage/impl/pending_txs_storage_impl.cpp
|
IvanTyulyandin/iroha
|
442a08325c7b808236569600653370e28ec5eff6
|
[
"Apache-2.0"
] | 24
|
2016-09-26T17:11:46.000Z
|
2020-03-03T13:42:58.000Z
|
irohad/pending_txs_storage/impl/pending_txs_storage_impl.cpp
|
ecsantana76/iroha
|
9cc430bb2c8eb885393e2a636fa92d1e605443ae
|
[
"Apache-2.0"
] | 11
|
2016-10-13T10:09:55.000Z
|
2019-06-13T08:49:11.000Z
|
irohad/pending_txs_storage/impl/pending_txs_storage_impl.cpp
|
ecsantana76/iroha
|
9cc430bb2c8eb885393e2a636fa92d1e605443ae
|
[
"Apache-2.0"
] | 4
|
2016-09-27T13:18:28.000Z
|
2019-08-05T20:47:15.000Z
|
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include "pending_txs_storage/impl/pending_txs_storage_impl.hpp"
#include "interfaces/transaction.hpp"
#include "multi_sig_transactions/state/mst_state.hpp"
namespace iroha {
PendingTransactionStorageImpl::PendingTransactionStorageImpl(
StateObservable updated_batches,
BatchObservable prepared_batch,
BatchObservable expired_batch) {
updated_batches_subscription_ =
updated_batches.subscribe([this](const SharedState &batches) {
this->updatedBatchesHandler(batches);
});
prepared_batch_subscription_ =
prepared_batch.subscribe([this](const SharedBatch &preparedBatch) {
this->removeBatch(preparedBatch);
});
expired_batch_subscription_ =
expired_batch.subscribe([this](const SharedBatch &expiredBatch) {
this->removeBatch(expiredBatch);
});
}
PendingTransactionStorageImpl::~PendingTransactionStorageImpl() {
updated_batches_subscription_.unsubscribe();
prepared_batch_subscription_.unsubscribe();
expired_batch_subscription_.unsubscribe();
}
PendingTransactionStorageImpl::SharedTxsCollectionType
PendingTransactionStorageImpl::getPendingTransactions(
const AccountIdType &account_id) const {
std::shared_lock<std::shared_timed_mutex> lock(mutex_);
auto creator_it = storage_.index.find(account_id);
if (storage_.index.end() != creator_it) {
auto &batch_hashes = creator_it->second;
SharedTxsCollectionType result;
auto &batches = storage_.batches;
for (const auto &batch_hash : batch_hashes) {
auto batch_it = batches.find(batch_hash);
if (batches.end() != batch_it) {
auto &txs = batch_it->second->transactions();
result.insert(result.end(), txs.begin(), txs.end());
}
}
return result;
}
return {};
}
std::set<PendingTransactionStorageImpl::AccountIdType>
PendingTransactionStorageImpl::batchCreators(const TransactionBatch &batch) {
std::set<AccountIdType> creators;
for (const auto &transaction : batch.transactions()) {
creators.insert(transaction->creatorAccountId());
}
return creators;
}
void PendingTransactionStorageImpl::updatedBatchesHandler(
const SharedState &updated_batches) {
std::unique_lock<std::shared_timed_mutex> lock(mutex_);
updated_batches->iterateBatches([this](const auto &batch) {
auto hash = batch->reducedHash();
auto it = storage_.batches.find(hash);
if (storage_.batches.end() == it) {
for (const auto &creator : batchCreators(*batch)) {
storage_.index[creator].insert(hash);
}
}
storage_.batches[hash] = batch;
});
}
void PendingTransactionStorageImpl::removeBatch(const SharedBatch &batch) {
auto creators = batchCreators(*batch);
auto hash = batch->reducedHash();
std::unique_lock<std::shared_timed_mutex> lock(mutex_);
storage_.batches.erase(hash);
for (const auto &creator : creators) {
auto &index = storage_.index;
auto index_it = index.find(creator);
if (index.end() != index_it) {
auto &creator_set = index_it->second;
creator_set.erase(hash);
}
}
}
} // namespace iroha
| 34.081633
| 79
| 0.690419
|
IvanTyulyandin
|
67ab0d1481045c36caa100f8e18e569e1a252ad4
| 37,047
|
cpp
|
C++
|
dali/treeview/inspectctrl.cpp
|
emuharemagic/HPCC-Platform
|
bbd5423b25f6ba2d675521c8917f9ecfa97dace5
|
[
"Apache-2.0"
] | 1
|
2020-08-01T19:54:56.000Z
|
2020-08-01T19:54:56.000Z
|
dali/treeview/inspectctrl.cpp
|
emuharemagic/HPCC-Platform
|
bbd5423b25f6ba2d675521c8917f9ecfa97dace5
|
[
"Apache-2.0"
] | null | null | null |
dali/treeview/inspectctrl.cpp
|
emuharemagic/HPCC-Platform
|
bbd5423b25f6ba2d675521c8917f9ecfa97dace5
|
[
"Apache-2.0"
] | null | null | null |
/*##############################################################################
HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems.
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 "stdafx.h"
#include "inspectctrl.hpp"
#include "resource.h"
#include "newvaluedlg.h"
#include "jthread.hpp"
#define MAX_PROPERTY_VALUE_SIZE 256
#define TREE_TOOLTIP_ID 100
#define IDC_EIP_CTRL 1099
enum TreeList_t { TLT_property, TLT_attribute, TLT_root };
const char binaryValue[] = "[BINARY]";
const UINT MSG_COLUMN_SIZED = 7000;
const UINT MSG_EIP_RESIZE = 7001;
bool ShowAttrsOnProps = true;
bool ShowQualifiedNames = false;
IConnection * connection = NULL; // the current connection
const COLORREF color_highlight = GetSysColor(COLOR_HIGHLIGHT);
const COLORREF color_window = GetSysColor(COLOR_WINDOW);
const COLORREF color_windowtext = GetSysColor(COLOR_WINDOWTEXT);
const COLORREF color_inactiveborder = GetSysColor(COLOR_INACTIVEBORDER);
const COLORREF color_highlighttext = GetSysColor(COLOR_HIGHLIGHTTEXT);
const COLORREF color_eip_back = RGB(210, 210, 240);
#define STRCAT(dest, destSz, src) {size32_t l = strlen(src); if(destSz > l) { strcat(dest, src); destSz -= l; } }
enum CTState { CTS_None, CTS_Visible = 0x01, CTS_Expanded = 0x02 };
class CTreeListItem
{
private:
TreeList_t type;
char * name;
IPropertyTree * pTree;
byte state;
public:
CTreeListItem(LPCSTR _name, IPropertyTree * _pTree, TreeList_t _type)
{
state = CTS_None;
type = _type;
pTree =_pTree;
name = type == TLT_attribute ? strdup(_name) : NULL;
}
~CTreeListItem() { if(name) free(name); }
inline int getDisplayName(IPropertyTree * parent, char * buffer, size32_t buffsz) const
{
*buffer = 0;
size32_t insz = buffsz;
switch(type)
{
case TLT_root:
case TLT_property:
STRCAT(buffer, buffsz, " ");
STRCAT(buffer, buffsz, getName(parent));
if(ShowAttrsOnProps)
{
bool first = true;
IAttributeIterator * attrIterator = pTree->getAttributes();
attrIterator->first();
while(attrIterator->isValid())
{
STRCAT(buffer, buffsz, " ");
if(first)
{
STRCAT(buffer, buffsz, "<");
first = false;
}
STRCAT(buffer, buffsz, attrIterator->queryName() + 1);
STRCAT(buffer, buffsz, "=");
STRCAT(buffer, buffsz, attrIterator->queryValue());
attrIterator->next();
}
attrIterator->Release();
if(!first) STRCAT(buffer, buffsz, ">");
}
break;
case TLT_attribute:
STRCAT(buffer, buffsz, "= ");
STRCAT(buffer, buffsz, getName(NULL));
break;
}
return insz - buffsz;
}
bool setValue(LPCSTR newValue) // returns true if value actually updated
{
ASSERT(!isBinary());
ASSERT(connection != NULL);
if(connection->lockWrite())
{
pTree->setProp(name, newValue);
connection->unlockWrite();
return true;
}
return false;
}
inline bool isBinary() const { return pTree->isBinary(name); }
inline bool isExpanded() const { return 0 != (state & CTS_Expanded); }
inline bool isVisible() const { return 0 != (state & CTS_Visible); }
inline void setExpanded() { state += CTS_Expanded; }
inline void setVisible() { state += CTS_Visible; }
inline IPropertyTree *queryPropertyTree() const { return pTree; }
inline LPCSTR getName(IPropertyTree * parent, bool forceQualified = false) const
{
if(type != TLT_attribute && parent && (ShowQualifiedNames || forceQualified))
{
static StringBuffer buf;
buf.clear().append(type == TLT_attribute ? name + 1 : pTree->queryName());
buf.append("[");
buf.append(parent->queryChildIndex(pTree) + 1);
buf.append("]");
return buf.toCharArray();
}
return type == TLT_attribute ? name + 1 : pTree->queryName();
}
inline LPCSTR getValue() const
{
static StringBuffer buf;
if(isBinary())
buf.clear().append(binaryValue);
else
pTree->getProp(name, buf.clear());
return buf.toCharArray();
}
inline TreeList_t getType() const { return type; }
};
CTreeListItem * createTreeListProperty(LPCSTR PropName, IPropertyTree & pTree)
{
return new CTreeListItem(PropName, &pTree, TLT_property);
}
CTreeListItem * createTreeListAttribute(LPCSTR AttrName, IPropertyTree & pTree)
{
return new CTreeListItem(AttrName, &pTree, TLT_attribute);
}
CTreeListItem * createTreeListRoot(LPCSTR RootName, IPropertyTree & pTree)
{
return new CTreeListItem(RootName, &pTree, TLT_root);
}
class CFinderThread : public Thread
{
private:
CInspectorTreeCtrl & tree;
LPSTR findWhat;
BOOL matchCase;
BOOL wholeWord;
Semaphore hold;
bool terminate;
HTREEITEM matchedItem;
bool matches(CTreeListItem * tli)
{
LPCSTR name = tli->getName(NULL), value = tli->getValue();
if(matchCase)
{
if(strstr(name, findWhat)) return true;
if(value && !tli->isBinary() && strstr(value, findWhat)) return true;
}
else
{
static CString what, nbuf;
what = findWhat;
nbuf = name;
what.MakeUpper();
nbuf.MakeUpper();
if(strstr(nbuf, what)) return true;
if(value && !tli->isBinary())
{
static CString vbuf;
vbuf= value;
vbuf.MakeUpper();
if(strstr(vbuf, what)) return true;
}
}
return false;
}
public:
CFinderThread(CInspectorTreeCtrl &_tree, LPCSTR _findWhat, BOOL _matchCase, BOOL _wholeWord) : tree(_tree)
{
findWhat = strdup(_findWhat);
matchCase = _matchCase;
wholeWord = _wholeWord;
terminate = false;
matchedItem = 0;
}
~CFinderThread()
{
free(findWhat);
}
void process(HTREEITEM in)
{
if(!terminate)
{
CTreeListItem * tli = tree.GetTreeListItem(in);
if(tli->getType() == TLT_property && !tli->isExpanded()) tree.AddLevel(*tli->queryPropertyTree(), in);
if(matches(tli))
{
tree.EnsureVisible(in);
tree.SelectItem(in);
hold.wait();
if(terminate) return;
}
HTREEITEM i = tree.GetChildItem(in);
while(i)
{
process(i);
if(terminate) break;
i = tree.GetNextItem(i, TVGN_NEXT);
}
}
}
void kill() // called on message thread
{
terminate = true;
hold.signal();
}
void next()
{
hold.signal();
}
virtual int run()
{
process(tree.GetRootItem());
if(!terminate) MessageBox(NULL, "Search finished, no more matches", "Search Complete", MB_OK | MB_ICONHAND);
return 0;
}
};
inline void getTypeText(TreeList_t type, CString & dest, bool forToolTip)
{
switch(type)
{
case TLT_property: dest = "Property"; break;
case TLT_attribute: dest = "Attribute"; break;
case TLT_root: dest = "Root"; break;
}
if(forToolTip) dest += ": ";
}
// ----- Inspector tree control --------------------------------------------------
BEGIN_MESSAGE_MAP(CInspectorTreeCtrl, CTreeCtrl)
//{{AFX_MSG_MAP(CInspectorTreeCtrl)
ON_WM_PAINT()
ON_WM_SIZE()
ON_WM_CREATE()
ON_WM_LBUTTONDOWN()
ON_WM_LBUTTONDBLCLK()
ON_WM_KEYDOWN()
ON_WM_DESTROY()
ON_WM_LBUTTONUP()
ON_WM_RBUTTONDOWN()
ON_WM_RBUTTONUP()
ON_WM_CLOSE()
ON_WM_VSCROLL()
ON_WM_MOUSEWHEEL()
ON_WM_CTLCOLOR()
ON_NOTIFY_REFLECT(TVN_ITEMEXPANDED, OnItemExpanded)
ON_NOTIFY_REFLECT(TVN_GETDISPINFO, OnGetDispInfo)
ON_COMMAND(IDMP_SETASROOT, OnSetAsRoot)
ON_COMMAND(IDMP_ADDATTRIBUTE, OnAddAttribute)
ON_COMMAND(IDMP_ADDPROPERTY, OnAddProperty)
ON_COMMAND(IDMP_DELETE, OnDelete)
ON_WM_HSCROLL()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
CInspectorTreeCtrl::CInspectorTreeCtrl()
{
linePen.CreatePen(PS_SOLID, 0, color_inactiveborder);
whitespaceHighlightBrush_Focused.CreateSolidBrush(color_highlight);
whitespaceHighlightBrush_Unfocused.CreateSolidBrush(color_inactiveborder);
EIPBrush.CreateSolidBrush(color_eip_back);
popupMenus.LoadMenu(IDR_POPUPMENUS);
EIPActive = false;
connection = NULL;
finder = NULL;
}
CInspectorTreeCtrl::~CInspectorTreeCtrl()
{
if(finder) delete finder;
}
void CInspectorTreeCtrl::killDataItems(HTREEITEM in)
{
if(in)
{
HTREEITEM i = GetChildItem(in);
while(i)
{
killDataItems(i);
i = GetNextItem(i, TVGN_NEXT);
}
CTreeListItem * tli = GetTreeListItem(in);
SetItemData(in, 0);
delete tli;
}
}
LRESULT CInspectorTreeCtrl::WindowProc(UINT Msg, WPARAM wParam, LPARAM lParam)
{
switch(Msg)
{
case MSG_EIP_RESIZE:
HTREEITEM hitItem = GetSelectedItem();
CRect rect;
GetItemRect(hitItem, &rect, FALSE);
rect.left = getColumnWidth(0);
rect.right = rect.left + getColumnWidth(1);
if(rect.Width() > 0)
editCtrl.Resize(rect);
else
DeactivateEIP();
return 0;
}
return CTreeCtrl::WindowProc(Msg, wParam, lParam);
}
void CInspectorTreeCtrl::DeleteCurrentItem(bool confirm)
{
HTREEITEM hItem = GetSelectedItem();
if (hItem)
{
if(connection->lockWrite())
{
IPropertyTree * pTree = NULL;
CString name;
CTreeListItem * tli = GetTreeListItem(hItem);
if(tli->getType() == TLT_property)
{
if (!confirm || MessageBox("Delete property, are you sure?", "Delete Confirmation", MB_ICONQUESTION | MB_YESNO) == IDYES)
{
CTreeListItem * parentTli = GetTreeListItem(GetParentItem(hItem));
pTree = parentTli->queryPropertyTree();
name = tli->getName(pTree, true);
}
}
else
{
if (!confirm || MessageBox("Delete attribute, are you sure?", "Delete Confirmation", MB_ICONQUESTION | MB_YESNO) == IDYES)
{
pTree = tli->queryPropertyTree();
name = "@";
name += tli->getName(NULL);
}
}
if(pTree)
{
if(pTree->removeProp(name))
{
killDataItems(hItem);
DeleteItem(hItem);
}
else
{
MessageBox("Failed to remove property or attribute, removeProp()\nfailed", "Failed to Remove", MB_OK | MB_ICONEXCLAMATION);
}
}
connection->unlockWrite();
}
else
MessageBox("Unable to lock connection for write", "Cannot Obtain Lock", MB_OK);
}
}
BOOL CInspectorTreeCtrl::DeleteAllItems()
{
DeactivateEIP();
killDataItems(GetRootItem());
CTreeCtrl::DeleteAllItems();
return TRUE;
}
CTreeListItem * CInspectorTreeCtrl::GetTreeListItem(HTREEITEM in)
{
return in ? reinterpret_cast <CTreeListItem *> (GetItemData(in)) : NULL;
}
void CInspectorTreeCtrl::xpath(HTREEITEM item, CString & dest)
{
HTREEITEM parent = GetParentItem(item);
if(parent) xpath(parent, dest); // recursion
CTreeListItem * i = GetTreeListItem(item);
if(i->getType() != TLT_root)
{
if(parent && GetTreeListItem(parent)->getType() != TLT_root) dest += "/";
IPropertyTree * ppTree = GetTreeListItem(parent)->queryPropertyTree();
if(i->getType() == TLT_attribute) dest += "@";
dest += i->getName(ppTree, true);
}
}
DWORD CInspectorTreeCtrl::getFullXPath(HTREEITEM item, CString & dest)
{
xpath(item, dest);
return dest.GetLength();
}
BOOL CInspectorTreeCtrl::DestroyWindow()
{
DeactivateEIP();
DeleteAllItems();
return CWnd::DestroyWindow();
}
bool CInspectorTreeCtrl::VScrollVisible()
{
int sMin, sMax; // crafty eh?
GetScrollRange(SB_VERT, &sMin, &sMax);
return sMax != 0;
}
int CInspectorTreeCtrl::getColumnWidth(int idx)
{
int r = (reinterpret_cast <CPropertyInspector *> (GetParent()))->getColumnWidth(idx);
if(idx == 1 && VScrollVisible()) r -= GetSystemMetrics(SM_CXVSCROLL);
return r > 0 ? r : 0;
}
void CInspectorTreeCtrl::setColumnWidth(int idx, int wid)
{
(reinterpret_cast <CPropertyInspector *> (GetParent()))->setColumnWidth(idx, wid);
}
#define DRAWLINE(x1, y1, x2, y2) dc.MoveTo(x1, y1); dc.LineTo(x2, y2)
void CInspectorTreeCtrl::drawValues(CPaintDC & dc)
{
CRect rect;
GetWindowRect(rect);
dc.SetViewportOrg(0, 0);
dc.SelectObject(linePen);
dc.SetBkMode(TRANSPARENT);
dc.SelectObject(GetFont());
dc.SetTextColor(color_windowtext);
DRAWLINE(0, 0, rect.right, 0);
int cWid0 = getColumnWidth(0);
int cWid1 = getColumnWidth(1);
int height = 0;
HTREEITEM hItemFocus = GetSelectedItem();
HTREEITEM hItem = GetFirstVisibleItem();
while(hItem && height < rect.Height())
{
CRect iRect;
GetItemRect(hItem, &iRect, FALSE);
DRAWLINE(0, iRect.bottom, rect.right, iRect.bottom);
height += iRect.Height();
CTreeListItem * itemData = GetTreeListItem(hItem);
if(itemData)
{
iRect.left = cWid0 + 6;
iRect.right = cWid0 + cWid1;
if(hItem == hItemFocus)
{
CRect whitespaceRect;
GetItemRect(hItem, &whitespaceRect, TRUE);
if(whitespaceRect.right < cWid0)
{
whitespaceRect.left = whitespaceRect.right;
whitespaceRect.right = cWid0;
CWnd * focusWnd = GetFocus();
if(focusWnd && (focusWnd->m_hWnd == m_hWnd)) // I have focus
dc.FillRect(whitespaceRect, &whitespaceHighlightBrush_Focused);
else
dc.FillRect(whitespaceRect, &whitespaceHighlightBrush_Unfocused);
}
CString xpath;
getTypeText(itemData->getType(), xpath, true);
if(getFullXPath(hItem, xpath))
{
CRect itemRect, r;
GetItemRect(hItem, &itemRect, FALSE);
r.UnionRect(&itemRect, &whitespaceRect);
tooltipCtrl->DelTool(this, TREE_TOOLTIP_ID);
tooltipCtrl->AddTool(this, xpath, r, TREE_TOOLTIP_ID);
}
}
dc.DrawText(itemData->getValue(), &iRect, DT_SINGLELINE | DT_LEFT);
}
hItem = GetNextVisibleItem(hItem);
}
DRAWLINE(cWid0, 0, cWid0, height);
}
void CInspectorTreeCtrl::OnSize(UINT type, int cx, int cy)
{
CWnd::OnSize(type, cx, cy);
if(EIPActive) PostMessage(MSG_EIP_RESIZE);
}
void CInspectorTreeCtrl::OnPaint()
{
CPaintDC dc(this);
CPropertyInspector * parent = static_cast <CPropertyInspector *> (GetParent());
CRect rcClip;
dc.GetClipBox( &rcClip );
rcClip.right = getColumnWidth(0);
CRgn rgn;
rgn.CreateRectRgnIndirect( &rcClip );
dc.SelectClipRgn(&rgn);
CWnd::DefWindowProc(WM_PAINT, reinterpret_cast <WPARAM> (dc.m_hDC), 0); // let CTreeCtrl paint as normal
rgn.DeleteObject();
rcClip.right += parent->getColumnWidth(1);
rgn.CreateRectRgnIndirect( &rcClip );
dc.SelectClipRgn(&rgn);
drawValues(dc);
rgn.DeleteObject();
}
int CInspectorTreeCtrl::OnCreate(LPCREATESTRUCT createStruct)
{
if(CTreeCtrl::OnCreate(createStruct) == -1) return -1;
tooltipCtrl = GetToolTips();
ASSERT(tooltipCtrl != NULL);
if(!editCtrl.Create(WS_CHILD | WS_BORDER | ES_AUTOHSCROLL, CRect(0, 0, 0, 0), this, IDC_EIP_CTRL)) return -1;
return 0;
}
HTREEITEM CInspectorTreeCtrl::selectFromPoint(CPoint & point)
{
HTREEITEM hitItem = HitTest(point);
if(hitItem && hitItem != GetSelectedItem()) SelectItem(hitItem);
return hitItem;
}
void CInspectorTreeCtrl::OnLButtonDown(UINT flags, CPoint point)
{
DeactivateEIP();
HTREEITEM hitItem = HitTest(point);
if(hitItem && hitItem != GetSelectedItem()) selectFromPoint(point);
CTreeCtrl::OnLButtonDown(flags, point);
}
void CInspectorTreeCtrl::DeactivateEIP(BOOL save)
{
if(editCtrl.Deactivate(save)) Invalidate();
}
void CInspectorTreeCtrl::ActivateEIP(HTREEITEM i, CRect & rect)
{
ASSERT(connection != NULL);
DeactivateEIP();
EIPActive = editCtrl.Activate(GetTreeListItem(i), rect);
}
void CInspectorTreeCtrl::OnLButtonUp(UINT flags, CPoint point)
{
DeactivateEIP();
HTREEITEM hitItem = HitTest(point);
if(hitItem && hitItem == GetSelectedItem())
{
CRect rect;
GetItemRect(hitItem, &rect, FALSE);
rect.left = getColumnWidth(0);
rect.right = rect.left + getColumnWidth(1);
if(rect.PtInRect(point)) ActivateEIP(hitItem, rect);
}
CTreeCtrl::OnLButtonUp(flags, point);
}
void CInspectorTreeCtrl::OnRButtonDown(UINT flags, CPoint point)
{
/* NULL */
}
void CInspectorTreeCtrl::OnRButtonUp(UINT flags, CPoint point)
{
HTREEITEM sel = selectFromPoint(point);
if(sel)
{
ClientToScreen(&point);
CMenu * sm = popupMenus.GetSubMenu(0);
switch(GetTreeListItem(sel)->getType())
{
case TLT_root:
sm->EnableMenuItem(IDMP_ADDPROPERTY, MF_ENABLED);
sm->EnableMenuItem(IDMP_ADDATTRIBUTE, MF_ENABLED);
sm->EnableMenuItem(IDMP_DELETE, MF_GRAYED);
sm->EnableMenuItem(IDMP_SETASROOT, MF_GRAYED);
break;
case TLT_property:
sm->EnableMenuItem(IDMP_ADDPROPERTY, MF_ENABLED);
sm->EnableMenuItem(IDMP_ADDATTRIBUTE, MF_ENABLED);
sm->EnableMenuItem(IDMP_DELETE, MF_ENABLED);
sm->EnableMenuItem(IDMP_SETASROOT, MF_ENABLED);
break;
case TLT_attribute:
sm->EnableMenuItem(IDMP_ADDPROPERTY, MF_GRAYED);
sm->EnableMenuItem(IDMP_ADDATTRIBUTE, MF_GRAYED);
sm->EnableMenuItem(IDMP_DELETE, MF_ENABLED);
sm->EnableMenuItem(IDMP_SETASROOT, MF_GRAYED);
break;
default:
ASSERT(FALSE);
}
sm->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y, this);
}
}
void CInspectorTreeCtrl::OnLButtonDblClk(UINT flags, CPoint point)
{
CTreeCtrl::OnLButtonDblClk(flags, point);
}
void CInspectorTreeCtrl::OnKeyDown(UINT chr, UINT repCnt, UINT flags)
{
CTreeCtrl::OnKeyDown(chr, repCnt, flags);
}
void CInspectorTreeCtrl::OnDestroy()
{
DeactivateEIP(FALSE);
DeleteAllItems();
CTreeCtrl::OnDestroy();
}
void CInspectorTreeCtrl::OnClose()
{
DeactivateEIP();
CTreeCtrl::OnClose();
}
void CInspectorTreeCtrl::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
DeactivateEIP();
CTreeCtrl::OnVScroll(nSBCode, nPos, pScrollBar);
}
BOOL CInspectorTreeCtrl::OnMouseWheel(UINT nFlags, short zDelta, CPoint pt)
{
DeactivateEIP();
return CTreeCtrl::OnMouseWheel(nFlags, zDelta, pt);
}
void CInspectorTreeCtrl::OnGetDispInfo(NMHDR* pNMHDR, LRESULT* pResult)
{
TV_DISPINFO * pTVDispInfo = reinterpret_cast <TV_DISPINFO *> (pNMHDR);
CTreeListItem * tli = reinterpret_cast <CTreeListItem *> (pTVDispInfo->item.lParam);
if(tli)
{
static char nameBuffer[256];
IPropertyTree * ppTree = tli->getType() == TLT_root ? NULL : GetTreeListItem(GetParentItem(pTVDispInfo->item.hItem))->queryPropertyTree();
int origlen = tli->getDisplayName(ppTree, nameBuffer , sizeof(nameBuffer));
HTREEITEM parent = NULL;
CDC * dc = GetDC();
dc->SetViewportOrg(0, 0);
dc->SelectObject(GetFont());
int fit;
CSize sz;
CRect rect;
if(GetItemRect(pTVDispInfo->item.hItem, &rect, TRUE))
{
rect.right = getColumnWidth(0);
GetTextExtentExPoint(dc->m_hDC, nameBuffer, origlen, rect.Width() - 2, &fit, NULL, &sz);
if(fit < origlen)
{
if(fit > 3)
{
strcpy(&nameBuffer[fit - 3], "...");
pTVDispInfo->item.pszText = nameBuffer;
}
else
{
pTVDispInfo->item.pszText = NULL;
}
}
else
{
pTVDispInfo->item.pszText = nameBuffer;
}
}
else
{
pTVDispInfo->item.pszText = NULL;
}
ReleaseDC(dc);
}
*pResult = 0;
}
HBRUSH CInspectorTreeCtrl::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CTreeCtrl::OnCtlColor(pDC, pWnd, nCtlColor);
if(pWnd->GetDlgCtrlID() == IDC_EIP_CTRL)
{
if(nCtlColor == CTLCOLOR_EDIT || nCtlColor == CTLCOLOR_MSGBOX)
{
pDC->SetBkColor(color_eip_back);
return EIPBrush;
}
}
return hbr;
}
void CInspectorTreeCtrl::NewTree(LPCSTR rootxpath)
{
ASSERT(connection != NULL);
DeleteAllItems();
IPropertyTree & pTree = *connection->queryRoot(rootxpath);
if(connection->getType() != CT_none)
{
TV_INSERTSTRUCT is;
is.hInsertAfter = TVI_LAST;
is.item.mask = TVIF_TEXT | TVIF_PARAM;
is.item.pszText = LPSTR_TEXTCALLBACK;
is.hParent = TVI_ROOT;
is.item.lParam = reinterpret_cast <DWORD> (createTreeListRoot(pTree.queryName(), pTree));
HTREEITEM r = InsertItem(&is);
AddLevel(pTree, r);
Expand(r, TVE_EXPAND);
}
}
void CInspectorTreeCtrl::dynExpand(HTREEITEM in)
{
CTreeListItem *parent = GetTreeListItem(in);
assertex(parent);
IPropertyTree &pTree = *parent->queryPropertyTree();
if (!parent->isExpanded())
{
HTREEITEM i = GetChildItem(in);
while(i)
{
DeleteItem(i);
i = GetNextItem(i, TVGN_NEXT);
}
CString txt;
TV_INSERTSTRUCT is;
is.hInsertAfter = TVI_LAST;
is.item.mask = TVIF_TEXT | TVIF_PARAM;
is.item.pszText = LPSTR_TEXTCALLBACK;
Owned<IAttributeIterator> attrIterator = pTree.getAttributes();
ForEach(*attrIterator)
{
is.hParent = in;
is.item.lParam = reinterpret_cast <DWORD> (createTreeListAttribute(attrIterator->queryName(), pTree));
HTREEITEM r = InsertItem(&is);
ASSERT(r != NULL);
}
Owned<IPropertyTreeIterator> iterator = pTree.getElements("*", iptiter_sort);
ForEach(*iterator)
{
IPropertyTree & thisTree = iterator->query();
is.hParent = in;
is.item.lParam = reinterpret_cast <DWORD> (createTreeListProperty(thisTree.queryName(), thisTree));
HTREEITEM thisTreeItem = InsertItem(&is);
ASSERT(thisTreeItem != NULL);
}
parent->setExpanded();
}
HTREEITEM i = GetChildItem(in);
while(i)
{
CTreeListItem * ctli = GetTreeListItem(i);
if(ctli->getType() == TLT_property) AddLevel(*ctli->queryPropertyTree(), i);
i = GetNextItem(i, TVGN_NEXT);
}
}
void CInspectorTreeCtrl::OnItemExpanded(NMHDR* pNMHDR, LRESULT* pResult)
{
NM_TREEVIEW * pNMTreeView = reinterpret_cast <NM_TREEVIEW*> (pNMHDR);
dynExpand(pNMTreeView->itemNew.hItem);
*pResult = 0;
}
void CInspectorTreeCtrl::AddLevel(IPropertyTree & pTree, HTREEITEM hParent)
{
CTreeListItem * itm = GetTreeListItem(hParent);
if(!itm->isVisible())
{
CString txt;
TV_INSERTSTRUCT is;
is.hInsertAfter = TVI_LAST;
is.item.mask = TVIF_TEXT | TVIF_PARAM;
is.item.pszText = LPSTR_TEXTCALLBACK;
// place holder for children
if (pTree.hasChildren())
{
is.hParent = hParent;
is.item.lParam = reinterpret_cast <DWORD> (createTreeListAttribute("@[loading...]", pTree));
HTREEITEM thisTreeItem = InsertItem(&is);
ASSERT(thisTreeItem != NULL);
}
itm->setVisible();
}
}
void CInspectorTreeCtrl::BeginFind()
{
}
void CInspectorTreeCtrl::EndFind()
{
if(finder)
{
finder->kill();
finder->join();
delete finder;
finder = NULL;
}
}
void CInspectorTreeCtrl::NextFind(LPCSTR txt, BOOL matchCase, BOOL wholeWord)
{
if(!finder)
{
finder = new CFinderThread(*this, txt, matchCase, wholeWord);
finder->start();
}
else
{
finder->next();
}
}
void CInspectorTreeCtrl::OnSetAsRoot()
{
HTREEITEM hItem = GetSelectedItem();
if(hItem)
{
CString xp;
xpath(hItem, xp);
NewTree(xp);
}
}
bool CInspectorTreeCtrl::GetNewItem(NewValue_t nvt, CString & name, CString & value, HTREEITEM & hParent)
{
hParent = GetSelectedItem();
if(hParent)
{
Invalidate();
CNewValueDlg nvDlg(nvt, name, value, this);
if(nvDlg.DoModal() == IDOK)
{
name = nvDlg.GetName();
value = nvDlg.GetValue();
return true;
}
}
return false;
}
void CInspectorTreeCtrl::OnAddAttribute()
{
CString name, value;
HTREEITEM hParent;
while(GetNewItem(NVT_attribute, name, value, hParent))
{
if(connection->lockWrite())
{
CString attrName;
if(name[0] != '@')
{
attrName = "@";
attrName += name;
}
else
attrName = name;
IPropertyTree * pTree = GetTreeListItem(hParent)->queryPropertyTree();
pTree->addProp(attrName, value);
TV_INSERTSTRUCT is;
is.hInsertAfter = TVI_LAST;
is.item.mask = TVIF_TEXT | TVIF_PARAM;
is.item.pszText = LPSTR_TEXTCALLBACK;
is.hParent = hParent;
is.item.lParam = reinterpret_cast <DWORD> (createTreeListAttribute(attrName, *pTree));
InsertItem(&is);
connection->unlockWrite();
Expand(hParent, TVE_EXPAND);
break;
}
}
}
void CInspectorTreeCtrl::OnAddProperty()
{
HTREEITEM hParent;
CString name, value;
while(GetNewItem(NVT_property, name, value, hParent))
{
if(connection->lockWrite())
{
IPropertyTree * t = createPTree();
t->setProp(NULL, value);
t = GetTreeListItem(hParent)->queryPropertyTree()->addPropTree(name, t);
TV_INSERTSTRUCT is;
is.hInsertAfter = TVI_LAST;
is.item.mask = TVIF_TEXT | TVIF_PARAM;
is.item.pszText = LPSTR_TEXTCALLBACK;
is.hParent = hParent;
is.item.lParam = reinterpret_cast <DWORD> (createTreeListProperty(t->queryName(), * t));
InsertItem(&is);
connection->unlockWrite();
Expand(hParent, TVE_EXPAND);
break;
}
else
MessageBox("Unable to lock connection for write", "Cannot Obtain Lock", MB_OK);
}
}
void CInspectorTreeCtrl::OnDelete()
{
DeleteCurrentItem();
}
void CInspectorTreeCtrl::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
/* NULL */
}
// ----- Inspector frame window --------------------------------------------------
BEGIN_MESSAGE_MAP(CPropertyInspector, CWnd)
ON_WM_SIZE()
END_MESSAGE_MAP()
CPropertyInspector::~CPropertyInspector()
{
connection = NULL;
}
LONG FAR PASCAL CPropertyInspector::wndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
return ::DefWindowProc(hWnd, msg, wParam, lParam);
}
LRESULT CPropertyInspector::WindowProc(UINT Msg, WPARAM wParam, LPARAM lParam)
{
switch(Msg)
{
case MSG_COLUMN_SIZED:
CRect rect;
GetWindowRect(&rect);
setColumnWidth(1, rect.Width() - getColumnWidth(0) - 2);
inspectorCtrl.Invalidate();
if(inspectorCtrl.EIPActive) inspectorCtrl.PostMessage(MSG_EIP_RESIZE);
return 0;
}
return CWnd::WindowProc(Msg, wParam, lParam);
}
void CPropertyInspector::registerClass()
{
WNDCLASS wc;
memset(&wc, 0, sizeof(wc));
wc.style = CS_DBLCLKS | CS_VREDRAW | CS_HREDRAW | CS_GLOBALCLASS;
wc.lpfnWndProc = (WNDPROC)wndProc;
wc.hInstance = AfxGetInstanceHandle();
wc.hCursor = 0;
wc.lpszClassName = "PROPERTY_INSPECTOR_CTRL";
wc.hbrBackground = (HBRUSH) GetStockObject(LTGRAY_BRUSH);
if (!::RegisterClass(&wc)) ASSERT(FALSE);
}
BOOL CPropertyInspector::SubclassDlgItem(UINT id, CWnd * parent)
{
return CWnd::SubclassDlgItem(id, parent) ? initialize() : FALSE;
}
CWnd * CPropertyInspector::SetFocus()
{
return inspectorCtrl.SetFocus();
}
int CPropertyInspector::initialize()
{
CRect rect;
GetWindowRect(rect);
if(!staticCtrl.Create(NULL, WS_CHILD | WS_VISIBLE | SS_SUNKEN, CRect(0, 0 ,0 ,0), this)) return FALSE;
staticCtrl.SetWindowPos(&wndBottom, 0, 0, rect.Width(), rect.Height(), SWP_SHOWWINDOW);
if(!headerCtrl.Create(WS_CHILD | WS_VISIBLE | HDS_HORZ, CRect(0, 0, 0, 0), this, IDC_TREE_LIST_HEADER)) return FALSE;
CSize textSize;
headerCtrl.SetFont(GetParent()->GetFont());
CDC * dc = headerCtrl.GetDC();
textSize = dc->GetTextExtent("A");
headerCtrl.ReleaseDC(dc);
headerCtrl.SetWindowPos(NULL, 1, 1, rect.Width() - 2, textSize.cy + 4, SWP_SHOWWINDOW | SWP_NOZORDER);
HD_ITEM hdItem;
hdItem.mask = HDI_FORMAT | HDI_TEXT | HDI_WIDTH;
hdItem.fmt = HDF_LEFT | HDF_STRING;
hdItem.pszText = "Value";
hdItem.cchTextMax = 5;
hdItem.cxy = 140;
headerCtrl.InsertItem(0, &hdItem);
hdItem.pszText = "Property";
hdItem.cchTextMax = 8;
hdItem.cxy = rect.Width() - hdItem.cxy;
headerCtrl.InsertItem(0, &hdItem);
if(!inspectorCtrl.Create(WS_CHILD | WS_VISIBLE | TVS_SHOWSELALWAYS | TVS_HASLINES |TVS_LINESATROOT | TVS_HASBUTTONS |TVS_DISABLEDRAGDROP, CRect(0, 0, 0, 0), this, IDC_TREE_LIST_CTRL)) return FALSE;
inspectorCtrl.SetWindowPos(NULL, 1, textSize.cy + 5, rect.Width(), rect.Height() - (textSize.cy + 6), SWP_SHOWWINDOW | SWP_NOZORDER);
PostMessage(MSG_COLUMN_SIZED);
return TRUE;
}
BOOL CPropertyInspector::OnNotify(WPARAM wParam, LPARAM lParam, LRESULT * result)
{
LPNMHEADER hdn = reinterpret_cast <LPNMHEADER> (lParam);
if(wParam == IDC_TREE_LIST_HEADER)
{
if(hdn->hdr.code == HDN_ENDTRACK) PostMessage(MSG_COLUMN_SIZED);
}
return CWnd::OnNotify(wParam, lParam, result);
}
void CPropertyInspector::OnSize(UINT type, int cx, int cy)
{
CWnd::OnSize(type, cx, cy);
staticCtrl.MoveWindow(0, 0, cx, cy);
CRect headerRect;
headerCtrl.GetWindowRect(&headerRect);
headerCtrl.MoveWindow(1, 1, cx - 2, headerRect.Height());
inspectorCtrl.MoveWindow(1, headerRect.Height() + 1, cx - 2, cy - headerRect.Height() - 2);
setColumnWidth(1, cx - getColumnWidth(0) - 2);
}
void CPropertyInspector::NewTree(IConnection * conn)
{
connection = conn;
if(connection) inspectorCtrl.NewTree();
}
void CPropertyInspector::KillTree()
{
connection = NULL;
inspectorCtrl.DeleteAllItems();
}
UINT CPropertyInspector::GetCount()
{
return inspectorCtrl.GetCount();
}
void CPropertyInspector::NextFind(LPCSTR txt, BOOL MatchCase, BOOL MatchWholeWord)
{
inspectorCtrl.NextFind(txt, MatchCase, MatchWholeWord);
}
void CPropertyInspector::BeginFind()
{
inspectorCtrl.BeginFind();
}
void CPropertyInspector::EndFind()
{
inspectorCtrl.EndFind();
}
int CPropertyInspector::getColumnWidth(int idx)
{
if(idx < 2)
{
static HD_ITEM hdItem;
hdItem.mask = HDI_WIDTH;
if(headerCtrl.GetItem(idx, &hdItem)) return hdItem.cxy;
}
return 0;
}
void CPropertyInspector::setColumnWidth(int idx, int wid)
{
if(idx < 2)
{
static HD_ITEM hdItem;
hdItem.mask = HDI_WIDTH;
hdItem.cxy = wid;
headerCtrl.SetItem(idx, &hdItem);
}
}
void CPropertyInspector::showAttribs(bool show)
{
if(ShowAttrsOnProps != show)
{
ShowAttrsOnProps = show;
inspectorCtrl.Invalidate();
}
}
void CPropertyInspector::showQualified(bool show)
{
if(ShowQualifiedNames != show)
{
ShowQualifiedNames = show;
inspectorCtrl.Invalidate();
}
}
/////////////////////////////////////////////////////////////////////////////
// CEditEIP
CEditEIP::CEditEIP()
{
tli = NULL;
}
CEditEIP::~CEditEIP()
{
}
BEGIN_MESSAGE_MAP(CEditEIP, CEdit)
//{{AFX_MSG_MAP(CEditEIP)
ON_WM_CREATE()
ON_WM_KEYUP()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CEditEIP message handlers
int CEditEIP::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if(CEdit::OnCreate(lpCreateStruct) == -1) return -1;
parent = static_cast <CInspectorTreeCtrl *> (GetParent());
ASSERT(parent != NULL);
SetFont(parent->GetFont());
return 0;
}
BOOL CEditEIP::Activate(CTreeListItem * i, CRect & rect)
{
ASSERT(i != NULL);
if(!i->isBinary())
{
tli = i;
Resize(rect);
SetFocusText(tli->getValue());
GetWindowText(ValuePreserve);
return TRUE;
}
return FALSE;
}
BOOL CEditEIP::Deactivate(BOOL save)
{
BOOL r = FALSE;
if(IsActive())
{
ASSERT(!tli->isBinary());
ShowWindow(FALSE);
CString ecTxt;
GetWindowText(ecTxt);
if(connection && save && GetModify())
{
if((!tli->getValue() || strcmp(tli->getValue(), ecTxt) != 0))
{
if(tli->setValue(ecTxt))
{
GetParent()->Invalidate();
r = TRUE;
}
else
{
::MessageBox(NULL, "Unable to gain exclusive lock for write", "Unable to lock", MB_OK);
}
}
}
tli = NULL;
}
return r;
}
BOOL CEditEIP::IsActive()
{
return tli == NULL ? FALSE : TRUE;
}
void CEditEIP::OnKeyUp(UINT nChar, UINT nRepCnt, UINT nFlags)
{
switch(nChar)
{
case 0x09: // tab key
case 0x0d: // enter key - accept value
Deactivate();
break;
case 0x1b: // esc key - get value when editing began
SetFocusText(ValuePreserve);
break;
default:
CEdit::OnKeyUp(nChar, nRepCnt, nFlags);
break;
}
}
void CEditEIP::SetFocusText(LPCSTR text)
{
SetWindowText(text);
SetModify(FALSE);
SetFocus();
SetSel(0, -1); // NB select all
}
BOOL CEditEIP::Resize(CRect & rect)
{
return IsActive() ? SetWindowPos(&wndTop, rect.left, rect.top, rect.Width(), rect.Height(), SWP_SHOWWINDOW) : FALSE;
}
| 26.98252
| 201
| 0.5828
|
emuharemagic
|
67ae6d5c8d54ad99fb27f838fe49b44f04b64a30
| 1,021
|
cpp
|
C++
|
competitive_programming/programming_contests/uri/flavious_josephus_legend.cpp
|
LeandroTk/Algorithms
|
569ed68eba3eeff902f8078992099c28ce4d7cd6
|
[
"MIT"
] | 205
|
2018-12-01T17:49:49.000Z
|
2021-12-22T07:02:27.000Z
|
competitive_programming/programming_contests/uri/flavious_josephus_legend.cpp
|
LeandroTk/Algorithms
|
569ed68eba3eeff902f8078992099c28ce4d7cd6
|
[
"MIT"
] | 2
|
2020-01-01T16:34:29.000Z
|
2020-04-26T19:11:13.000Z
|
competitive_programming/programming_contests/uri/flavious_josephus_legend.cpp
|
LeandroTk/Algorithms
|
569ed68eba3eeff902f8078992099c28ce4d7cd6
|
[
"MIT"
] | 50
|
2018-11-28T20:51:36.000Z
|
2021-11-29T04:08:25.000Z
|
// https://www.urionlinejudge.com.br/judge/en/problems/view/1030
#include <iostream>
#include <vector>
using namespace std;
int verify_last_value(vector<int> &v) {
int counter = 0;
for (int i = 0; i < v.size(); i++) if (v[i] == 1) counter++;
return counter;
}
int can_be_counted(vector<int> &v, int index, int n) {
while (v[index] == 0) {
if (index == n - 1) index = 0;
else index++;
cout << index << " ";
}
cout << endl;
return index;
}
int get_last_value_index(vector<int> &v) {
for (int i = 0; i < v.size(); i++) if (v[i] == 1) return i;
}
int main() {
int nc, n, k, c = 1;
cin >> nc;
while (nc--) {
cin >> n >> k;
vector<int> v;
int i = 0, counter = 1;
for (int i = 0; i < n; i++) v.push_back(1);
while (verify_last_value(v)) {
i = can_be_counted(v, i, n);
if (counter == k) {
v[i] = 0;
counter = 0;
} else {
counter++;
}
i++;
if (i == n - 1) i = 0;
}
cout << "Case " << c << ": " << get_last_value_index(v) << endl;
c++;
}
return 0;
}
| 16.737705
| 66
| 0.528893
|
LeandroTk
|
67b1fa9045b34e365f41b2000ee814a92e030616
| 4,051
|
cc
|
C++
|
cc/data-fix.cc
|
acorg/acmacs-whocc
|
af508bd4651ffb565cd4cf771200540918b1b2bd
|
[
"MIT"
] | null | null | null |
cc/data-fix.cc
|
acorg/acmacs-whocc
|
af508bd4651ffb565cd4cf771200540918b1b2bd
|
[
"MIT"
] | null | null | null |
cc/data-fix.cc
|
acorg/acmacs-whocc
|
af508bd4651ffb565cd4cf771200540918b1b2bd
|
[
"MIT"
] | null | null | null |
#include "acmacs-whocc/log.hh"
#include "acmacs-whocc/data-fix.hh"
#include "acmacs-whocc/sheet-extractor.hh"
// ----------------------------------------------------------------------
#pragma GCC diagnostic push
#ifdef __clang__
#pragma GCC diagnostic ignored "-Wglobal-constructors"
#pragma GCC diagnostic ignored "-Wexit-time-destructors"
#endif
static std::unique_ptr<acmacs::data_fix::v1::Set> sSet;
#pragma GCC diagnostic pop
const acmacs::data_fix::v1::Set& acmacs::data_fix::v1::Set::get()
{
if (!sSet)
sSet.reset(new Set{}); // throw std::runtime_error { "acmacs::data_fix::v1::Set accessed via get() before creating" };
return *sSet;
} // acmacs::data_fix::v1::Set::get
// ----------------------------------------------------------------------
acmacs::data_fix::v1::Set& acmacs::data_fix::v1::Set::update()
{
if (!sSet)
sSet.reset(new Set{});
return *sSet;
} // acmacs::data_fix::v1::Set::update
// ----------------------------------------------------------------------
void acmacs::data_fix::v1::Set::fix(acmacs::sheet::antigen_fields_t& antigen, size_t antigen_no)
{
using namespace std::string_view_literals;
auto& data = get().data_;
for (const auto& en : data) {
const auto orig = antigen.name;
if (const auto res = en->antigen_name(antigen.name); res) {
AD_INFO("AG {:4d} name \"{}\" <-- \"{}\"", antigen_no, antigen.name, orig);
break;
}
}
for (const auto& en : data) {
const auto orig_name = antigen.name;
const auto orig_passage = antigen.passage;
if (const auto res = en->antigen_passage(antigen.passage, antigen.name); res) {
AD_INFO("AG {:4d} passage \"{}\" <-- \"{}\" name \"{}\" <-- \"{}\"", antigen_no, antigen.passage, orig_passage, antigen.name, orig_name);
break;
}
}
for (const auto& en : data) {
const auto orig_date = antigen.date;
if (const auto res = en->date(antigen.date); res) {
AD_INFO("AG {:4d} date \"{}\" <-- \"{}\"", antigen_no, antigen.date, orig_date);
break;
}
}
} // acmacs::data_fix::v1::Set::fix
// ----------------------------------------------------------------------
void acmacs::data_fix::v1::Set::fix(acmacs::sheet::serum_fields_t& serum, size_t serum_no)
{
auto& data = get().data_;
// AD_DEBUG("fix serum.name \"{}\"", serum.name);
for (const auto& en : data) {
const auto orig = serum.name;
if (const auto res = en->serum_name(serum.name); res) {
AD_INFO("SR {:4d} name \"{}\" <-- \"{}\"", serum_no, serum.name, orig);
break;
}
}
for (const auto& en : data) {
const auto orig_name = serum.name;
const auto orig_passage = serum.passage;
if (const auto res = en->serum_passage(serum.passage, serum.name); res) {
AD_INFO("SR {:4d} passage \"{}\" <-- \"{}\" name \"{}\" <-- \"{}\"", serum_no, serum.passage, orig_passage, serum.name, orig_name);
break;
}
}
for (const auto& en : data) {
const auto orig_serum_id = serum.serum_id;
if (const auto res = en->serum_id(serum.serum_id); res) {
AD_INFO("SR {:4d} serum_id \"{}\" <-- \"{}\"", serum_no, serum.serum_id, orig_serum_id);
break;
}
}
} // acmacs::data_fix::v1::Set::fix
// ----------------------------------------------------------------------
void acmacs::data_fix::v1::Set::fix_titer(std::string& titer, size_t antigen_no, size_t serum_no)
{
for (const auto& en : get().data_) {
const auto orig = titer;
if (const auto res = en->titer(titer); res) {
AD_INFO("AG {:4d} SR {:4d} titer \"{}\" <-- \"{}\" ", antigen_no, serum_no, titer, orig);
break;
}
}
} // acmacs::data_fix::v1::Set::fix_titer
// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
| 33.204918
| 151
| 0.5137
|
acorg
|
67b2cd9991983d069d1c807324e99bd52a36d771
| 1,308
|
cpp
|
C++
|
Demo Code/operator_overload_example/animal_class_example/animal.cpp
|
pranavas11/CS162-Introduction-to-CS-II
|
c17c5c1f844de1be4a49646201d77717394dfdbc
|
[
"MIT"
] | null | null | null |
Demo Code/operator_overload_example/animal_class_example/animal.cpp
|
pranavas11/CS162-Introduction-to-CS-II
|
c17c5c1f844de1be4a49646201d77717394dfdbc
|
[
"MIT"
] | null | null | null |
Demo Code/operator_overload_example/animal_class_example/animal.cpp
|
pranavas11/CS162-Introduction-to-CS-II
|
c17c5c1f844de1be4a49646201d77717394dfdbc
|
[
"MIT"
] | null | null | null |
/*
Animal Class
*/
#include <iostream>
#include "animal.h"
Animal::Animal(string name) {
cout << "Alternate animal constructor called" << endl;
this->name = name;
this->age = 0;
}
Animal::Animal(string name, int age) {
cout << "Alternate 2 animal constructor called" << endl;
this->name = name;
this->age = age;
}
Animal::Animal() {
cout << "Default animal constructor called" << endl;
this->name = "Specimen Unknown";
this->age = 0;
}
// overload the pre-increment operator
Animal& Animal::operator++() {
++age;
return *this;
}
// overload the post-increment operator
// notice the dummy variable that is provided to distinguish
// this from the pre-increment operator
Animal Animal::operator++(int) {
Animal old(*this); //copy constructor
++(*this);
return old;
}
string Animal::get_name() const {
return name;
}
int Animal::get_age() const{
return age;
}
// overload the stream operator
ostream& operator<<(ostream& out, const Animal& a) {
out << "Name: " << a.get_name() << ", Age: " << a.get_age();
return out;
}
bool operator<(const Animal& a1, const Animal& a2){
return (a1.get_age() < a2.get_age());
}
bool operator>(const Animal& a1, const Animal& a2){
return (a1.get_age() > a2.get_age());
}
bool operator<(const Animal& a, int age){
return (a.get_age() < age);
}
| 20.123077
| 61
| 0.663609
|
pranavas11
|
67b33b7d0cedbadbea6d581bdc6c589827a328e5
| 4,795
|
cpp
|
C++
|
Coin3D/src/engines/SoFieldConverter.cpp
|
pniaz20/inventor-utils
|
2306b758b15bd1a0df3fb9bd250215b7bb7fac3f
|
[
"MIT"
] | null | null | null |
Coin3D/src/engines/SoFieldConverter.cpp
|
pniaz20/inventor-utils
|
2306b758b15bd1a0df3fb9bd250215b7bb7fac3f
|
[
"MIT"
] | null | null | null |
Coin3D/src/engines/SoFieldConverter.cpp
|
pniaz20/inventor-utils
|
2306b758b15bd1a0df3fb9bd250215b7bb7fac3f
|
[
"MIT"
] | null | null | null |
/**************************************************************************\
* Copyright (c) Kongsberg Oil & Gas Technologies AS
* 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 copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\**************************************************************************/
/*!
\class SoFieldConverter SoFieldConverter.h Inventor/engines/SoFieldConverter.h
\brief The SoFieldConverter class is the abstract base class for field converters.
\ingroup engines
When fields of different types are attempted connected, the Coin
library tries to find a field converter class which can be inserted
between them, acting as a filter converting values from the master
field to values matching the type of the slave field.
If a value type conversion is possible (like between an SoSFFloat
field and an SoSFInt32 field, for instance, where we could do a
simple typecast for converting the value of one to the other), an
SoFieldConverter derived object is inserted.
This class is the abstract base superclass which all such field
converters needs to inherit.
Coin comes with one built-in field converter class which takes care
of all possible field-to-field conversions we know about. This means
applications programmers should seldom need to care about this
class, it will probably only be useful if you expand the Coin
library with your own field type classes. (Doing so is considered
advanced use of the library.)
\sa SoDB::addConverter()
*/
#include <Inventor/engines/SoFieldConverter.h>
#include <cassert>
#include <Inventor/fields/SoField.h>
#include <Inventor/engines/SoOutputData.h>
#include <Inventor/lists/SoTypeList.h>
#include <Inventor/lists/SoEngineOutputList.h>
#if COIN_DEBUG
#include <Inventor/errors/SoDebugError.h>
#endif // COIN_DEBUG
#include "engines/SoConvertAll.h"
#include "engines/SoSubEngineP.h"
#include "coindefs.h" // COIN_OBSOLETED
/*!
\fn SoField * SoFieldConverter::getInput(SoType type)
Returns input field for the converter engine. Must be overridden in
non-abstract converter engine classes.
*/
/*!
\fn SoEngineOutput * SoFieldConverter::getOutput(SoType type)
Returns output for the converter engine. Must be overridden in
non-abstract converter engine classes.
*/
SO_ENGINE_ABSTRACT_SOURCE(SoFieldConverter);
/*!
Default constructor.
*/
SoFieldConverter::SoFieldConverter(void)
{
#if COIN_DEBUG && 0 // debug
SoDebugError::postInfo("SoFieldConverter::SoFieldConverter", "%p", this);
#endif // debug
}
/*!
Default destructor.
*/
SoFieldConverter::~SoFieldConverter()
{
}
// doc in super
void
SoFieldConverter::initClass(void)
{
SO_ENGINE_INTERNAL_INIT_ABSTRACT_CLASS(SoFieldConverter);
SoFieldConverter::initClasses();
}
void
SoFieldConverter::initClasses(void)
{
SoConvertAll::initClass();
}
/*!
This method is obsoleted in Coin. It should probably have been
private in OIV.
*/
SoField *
SoFieldConverter::getConnectedInput(void)
{
COIN_OBSOLETED();
return NULL;
}
/*!
Returns fields which are connected as slaves of the engine output.
*/
int
SoFieldConverter::getForwardConnections(SoFieldList & l) const
{
SoEngineOutputList outputlist;
int n = 0;
(void) this->getOutputs(outputlist);
for (int i = 0; i < outputlist.getLength(); i++) {
n += outputlist[i]->getForwardConnections(l);
}
return n;
}
| 31.546053
| 84
| 0.739937
|
pniaz20
|
67b5987fe0766aef30608a214937b28d98fcd281
| 2,705
|
hpp
|
C++
|
hpx/components/security/secret_key.hpp
|
kempj/hpx
|
ffdbfed5dfa029a0f2e97e7367cb66d12103df67
|
[
"BSL-1.0"
] | null | null | null |
hpx/components/security/secret_key.hpp
|
kempj/hpx
|
ffdbfed5dfa029a0f2e97e7367cb66d12103df67
|
[
"BSL-1.0"
] | null | null | null |
hpx/components/security/secret_key.hpp
|
kempj/hpx
|
ffdbfed5dfa029a0f2e97e7367cb66d12103df67
|
[
"BSL-1.0"
] | null | null | null |
// Copyright (c) 2013 Jeroen Habraken
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef HPX_COMPONENTS_SECURITY_SERVER_SECRET_KEY_HPP
#define HPX_COMPONENTS_SECURITY_SERVER_SECRET_KEY_HPP
#include <hpx/hpx_fwd.hpp>
#include <hpx/exception.hpp>
#include <boost/array.hpp>
#include <boost/io/ios_state.hpp>
#include <sodium.h>
#include "public_key.hpp"
#include "signed_type.hpp"
namespace hpx { namespace components { namespace security
{
#if defined(_MSC_VER)
# pragma pack(push, 1)
#endif
class secret_key
{
public:
secret_key(public_key & public_key)
{
crypto_sign_keypair(public_key.bytes_.c_array(), bytes_.c_array());
}
template <typename T>
signed_type<T> sign(T const & type, error_code& ec = throws) const
{
signed_type<T> signed_type;
unsigned long long signed_type_length;
if (crypto_sign(
signed_type.begin(),
&signed_type_length,
type.begin(),
type.size(),
bytes_.data()) != 0)
{
HPX_THROWS_IF(
ec
, hpx::security_error
, "secret_key::sign"
, "Failed to sign type"
)
return signed_type;
}
if (type.size() + crypto_sign_BYTES != signed_type_length)
{
HPX_THROWS_IF(
ec
, hpx::security_error
, "secret_key::sign"
, "Signature of incorrect length"
)
return signed_type;
}
if (&ec != &throws)
ec = make_success_code();
return signed_type;
}
friend std::ostream & operator<<(std::ostream & os,
secret_key const & secret_key)
{
boost::io::ios_flags_saver ifs(os);
os << "<secret_key \"";
for (std::size_t i = 0; i < crypto_sign_SECRETKEYBYTES; ++i)
{
os << std::hex
<< std::nouppercase
<< std::setfill('0')
<< std::setw(2)
<< static_cast<unsigned int>(secret_key.bytes_[i]);
}
return os << "\">";
}
private:
boost::array<
unsigned char, crypto_sign_SECRETKEYBYTES
> bytes_;
};
#if defined(_MSC_VER)
# pragma pack(pop)
#endif
}}}
#endif
| 26.009615
| 80
| 0.50647
|
kempj
|
67b7d681391af04e35a2ba15ab61233c0099630a
| 1,639
|
cpp
|
C++
|
rEFIt_UEFI/Platform/Volumes.cpp
|
crazyinsanejames/CloverBootloader
|
799880e95aaa2783f27373e91837fc105352e82f
|
[
"BSD-2-Clause"
] | 3,861
|
2019-09-04T10:10:11.000Z
|
2022-03-31T15:46:28.000Z
|
rEFIt_UEFI/Platform/Volumes.cpp
|
crazyinsanejames/CloverBootloader
|
799880e95aaa2783f27373e91837fc105352e82f
|
[
"BSD-2-Clause"
] | 461
|
2019-09-24T10:26:56.000Z
|
2022-03-26T13:22:32.000Z
|
rEFIt_UEFI/Platform/Volumes.cpp
|
crazyinsanejames/CloverBootloader
|
799880e95aaa2783f27373e91837fc105352e82f
|
[
"BSD-2-Clause"
] | 654
|
2019-09-05T11:42:37.000Z
|
2022-03-30T02:42:32.000Z
|
/*
* Volumes.cpp
*
* Created on: Feb 4, 2021
* Author: jief
*/
#include "Volumes.h"
REFIT_VOLUME *SelfVolume = NULL;
VolumesArrayClass Volumes;
//REFIT_VOLUME* VolumesArrayClass::getApfsPartitionWithUUID(const XString8& ApfsContainerUUID, const XString8& APFSTargetUUID)
//{
//}
REFIT_VOLUME* VolumesArrayClass::getVolumeWithApfsContainerUUIDAndFileSystemUUID(const XString8& ApfsContainerUUID, const XString8& ApfsFileSystemUUID)
{
for (size_t VolumeIndex = 0; VolumeIndex < Volumes.size(); VolumeIndex++) {
REFIT_VOLUME* Volume = &Volumes[VolumeIndex];
//DBG("idx=%zu name %ls uuid=%s \n", VolumeIndex2, Volume2->VolName.wc_str(), Volume2->ApfsFileSystemUUID.c_str());
if ( Volume->ApfsContainerUUID == ApfsContainerUUID ) {
if ( Volume->ApfsFileSystemUUID == ApfsFileSystemUUID ) {
return Volume;
}
}
}
return NULL;
}
REFIT_VOLUME* VolumesArrayClass::getVolumeWithApfsContainerUUIDAndRole(const XString8& ApfsContainerUUID, APPLE_APFS_VOLUME_ROLE roleMask)
{
REFIT_VOLUME* targetVolume = NULL;
for (size_t VolumeIndex = 0; VolumeIndex < Volumes.size(); VolumeIndex++) {
REFIT_VOLUME* Volume = &Volumes[VolumeIndex];
//DBG("idx=%zu name %ls uuid=%s \n", VolumeIndex2, Volume2->VolName.wc_str(), Volume2->ApfsFileSystemUUID.c_str());
if ( Volume->ApfsContainerUUID == ApfsContainerUUID ) {
if ( (Volume->ApfsRole & roleMask) != 0 ) {
if ( !targetVolume ) {
targetVolume = Volume;
}else{
// More than one partition with this role in container.
return NULL;
}
}
}
}
return targetVolume;
}
| 30.924528
| 151
| 0.688835
|
crazyinsanejames
|
67b998033dbe8e18c4c306516116d855126ee195
| 33,655
|
cxx
|
C++
|
MUON/MUONrec/AliMUONClusterFinderPeakCOG.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 52
|
2016-12-11T13:04:01.000Z
|
2022-03-11T11:49:35.000Z
|
MUON/MUONrec/AliMUONClusterFinderPeakCOG.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 1,388
|
2016-11-01T10:27:36.000Z
|
2022-03-30T15:26:09.000Z
|
MUON/MUONrec/AliMUONClusterFinderPeakCOG.cxx
|
AllaMaevskaya/AliRoot
|
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
|
[
"BSD-3-Clause"
] | 275
|
2016-06-21T20:24:05.000Z
|
2022-03-31T13:06:19.000Z
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
//-----------------------------------------------------------------------------
/// \class AliMUONClusterFinderPeakCOG
///
/// Clusterizer class based on simple peak finder
///
/// Pre-clustering is handled by AliMUONPreClusterFinder
/// From a precluster a pixel array is built, and its local maxima are used
/// to get pads and compute pad center of gravity.
///
/// \author Laurent Aphecetche (for the "new" C++ structure) and
/// Alexander Zinchenko, JINR Dubna, for the hardcore of it ;-)
//-----------------------------------------------------------------------------
#include "AliMUONClusterFinderPeakCOG.h"
#include "AliMUONCluster.h"
#include "AliMUONPad.h"
#include "AliMpPad.h"
#include "AliMpVSegmentation.h"
#include "AliMpEncodePair.h"
#include "AliLog.h"
#include "AliRunLoader.h"
//#include "AliCodeTimer.h"
#include <Riostream.h>
#include <TH2.h>
//#include <TCanvas.h>
#include <TMath.h>
using std::endl;
using std::cout;
/// \cond CLASSIMP
ClassImp(AliMUONClusterFinderPeakCOG)
/// \endcond
const Double_t AliMUONClusterFinderPeakCOG::fgkZeroSuppression = 6; // average zero suppression value
//const Double_t AliMUONClusterFinderMLEM::fgkDistancePrecision = 1e-6; // (cm) used to check overlaps and so on
const Double_t AliMUONClusterFinderPeakCOG::fgkDistancePrecision = 1e-3; // (cm) used to check overlaps and so on
const TVector2 AliMUONClusterFinderPeakCOG::fgkIncreaseSize(-AliMUONClusterFinderPeakCOG::fgkDistancePrecision,-AliMUONClusterFinderPeakCOG::fgkDistancePrecision);
const TVector2 AliMUONClusterFinderPeakCOG::fgkDecreaseSize(AliMUONClusterFinderPeakCOG::fgkDistancePrecision,AliMUONClusterFinderPeakCOG::fgkDistancePrecision);
// Status flags for pads
const Int_t AliMUONClusterFinderPeakCOG::fgkZero = 0x0; ///< pad "basic" state
const Int_t AliMUONClusterFinderPeakCOG::fgkMustKeep = 0x1; ///< do not kill (for pixels)
const Int_t AliMUONClusterFinderPeakCOG::fgkUseForFit = 0x10; ///< should be used for fit
const Int_t AliMUONClusterFinderPeakCOG::fgkOver = 0x100; ///< processing is over
const Int_t AliMUONClusterFinderPeakCOG::fgkModified = 0x1000; ///< modified pad charge
const Int_t AliMUONClusterFinderPeakCOG::fgkCoupled = 0x10000; ///< coupled pad
//_____________________________________________________________________________
AliMUONClusterFinderPeakCOG::AliMUONClusterFinderPeakCOG(Bool_t plot, AliMUONVClusterFinder* clusterFinder)
: AliMUONVClusterFinder(),
fPreClusterFinder(clusterFinder),
fPreCluster(0x0),
fClusterList(),
fEventNumber(0),
fDetElemId(-1),
fClusterNumber(0),
fHistAnode(0x0),
fPixArray(new TObjArray(20)),
fDebug(0),
fPlot(plot),
fNClusters(0),
fNAddVirtualPads(0)
{
/// Constructor
fkSegmentation[1] = fkSegmentation[0] = 0x0;
if (fPlot) fDebug = 1;
}
//_____________________________________________________________________________
AliMUONClusterFinderPeakCOG::~AliMUONClusterFinderPeakCOG()
{
/// Destructor
delete fPixArray; fPixArray = 0;
delete fPreClusterFinder;
AliInfo(Form("Total clusters %d AddVirtualPad needed %d",
fNClusters,fNAddVirtualPads));
}
//_____________________________________________________________________________
Bool_t
AliMUONClusterFinderPeakCOG::Prepare(Int_t detElemId, TObjArray* pads[2],
const AliMpArea& area,
const AliMpVSegmentation* seg[2])
{
/// Prepare for clustering
// AliCodeTimerAuto("",0)
for ( Int_t i = 0; i < 2; ++i )
{
fkSegmentation[i] = seg[i];
}
// Find out the DetElemId
fDetElemId = detElemId;
// find out current event number, and reset the cluster number
AliRunLoader *runLoader = AliRunLoader::Instance();
fEventNumber = runLoader ? runLoader->GetEventNumber() : 0;
fClusterNumber = -1;
fClusterList.Delete();
AliDebug(3,Form("EVT %d DE %d",fEventNumber,fDetElemId));
if ( fPreClusterFinder->NeedSegmentation() )
{
return fPreClusterFinder->Prepare(detElemId,pads,area,seg);
}
else
{
return fPreClusterFinder->Prepare(detElemId,pads,area);
}
}
//_____________________________________________________________________________
AliMUONCluster*
AliMUONClusterFinderPeakCOG::NextCluster()
{
/// Return next cluster
// AliCodeTimerAuto("",0)
// if the list of clusters is not void, pick one from there
TObject* o = fClusterList.At(++fClusterNumber);
if ( o != 0x0 ) return static_cast<AliMUONCluster*>(o);
//FIXME : at this point, must check whether we've used all the digits
//from precluster : if not, let the preclustering know about those unused
//digits, so it can reuse them
// if the cluster list is exhausted, we need to go to the next
// pre-cluster and treat it
fClusterList.Delete(); // reset the list of clusters for this pre-cluster
fClusterNumber = -1;
fPreCluster = fPreClusterFinder->NextCluster();
if (!fPreCluster)
{
// we are done
return 0x0;
}
WorkOnPreCluster();
// WorkOnPreCluster may have used only part of the pads, so we check that
// now, and let the unused pads be reused by the preclustering...
Int_t mult = fPreCluster->Multiplicity();
for ( Int_t i = 0; i < mult; ++i )
{
AliMUONPad* pad = fPreCluster->Pad(i);
if ( !pad->IsUsed() )
{
fPreClusterFinder->UsePad(*pad);
}
}
return NextCluster();
}
//_____________________________________________________________________________
Bool_t
AliMUONClusterFinderPeakCOG::WorkOnPreCluster()
{
/// Starting from a precluster, builds a pixel array, and then
/// extract clusters from this array
// AliCodeTimerAuto("",0)
if (fDebug) {
cout << " *** Event # " << fEventNumber
<< " det. elem.: " << fDetElemId << endl;
for (Int_t j = 0; j < fPreCluster->Multiplicity(); ++j) {
AliMUONPad* pad = fPreCluster->Pad(j);
printf(" bbb %3d %1d %8.4f %8.4f %8.4f %8.4f %6.1f %3d %3d %2d %1d %1d \n",
j, pad->Cathode(), pad->Coord(0), pad->Coord(1), pad->DX()*2, pad->DY()*2,
pad->Charge(), pad->Ix(), pad->Iy(), pad->Status(), pad->IsReal(), pad->IsSaturated());
}
}
AliMUONCluster* cluster = CheckPrecluster(*fPreCluster);
if (!cluster) return kFALSE;
BuildPixArray(*cluster);
if ( fPixArray->GetLast() < 0 )
{
AliDebug(1,"No pixel for the above cluster");
delete cluster;
return kFALSE;
}
Int_t nMax = 1, localMax[100], maxPos[100] = {0};
Double_t maxVal[100];
nMax = FindLocalMaxima(fPixArray, localMax, maxVal); // find local maxima
if (nMax > 1) TMath::Sort(nMax, maxVal, maxPos, kTRUE); // in descending order
for (Int_t i = 0; i < nMax; ++i)
{
FindCluster(*cluster,localMax, maxPos[i]);
}
delete cluster;
if (fPlot == 0) {
delete fHistAnode;
fHistAnode = 0x0;
}
return kTRUE;
}
//_____________________________________________________________________________
Bool_t
AliMUONClusterFinderPeakCOG::Overlap(const AliMUONPad& pad, const AliMUONPad& pixel)
{
/// Check if the pad and the pixel overlaps
// make a fake pad from the pixel
AliMUONPad tmp(pad.DetElemId(),pad.Cathode(),pad.Ix(),pad.Iy(),
pixel.Coord(0),pixel.Coord(1),
pixel.Size(0),pixel.Size(1),0);
return AliMUONPad::AreOverlapping(pad,tmp,fgkDecreaseSize);
}
//_____________________________________________________________________________
AliMUONCluster*
AliMUONClusterFinderPeakCOG::CheckPrecluster(const AliMUONCluster& origCluster)
{
/// Check precluster in order to attempt to simplify it (mostly for
/// two-cathode preclusters)
// AliCodeTimerAuto("",0)
// Disregard small clusters (leftovers from splitting or noise)
if ((origCluster.Multiplicity()==1 || origCluster.Multiplicity()==2) &&
origCluster.Charge(0)+origCluster.Charge(1) < 1.525) // JC: adc -> fc
{
return 0x0;
}
AliMUONCluster* cluster = new AliMUONCluster(origCluster);
AliDebug(2,"Start of CheckPreCluster=");
//StdoutToAliDebug(2,cluster->Print("full"));
AliMUONCluster* rv(0x0);
if (cluster->Multiplicity(0) && cluster->Multiplicity(1))
{
rv = CheckPreclusterTwoCathodes(cluster);
}
else
{
rv = cluster;
}
return rv;
}
//_____________________________________________________________________________
AliMUONCluster*
AliMUONClusterFinderPeakCOG::CheckPreclusterTwoCathodes(AliMUONCluster* cluster)
{
/// Check two-cathode cluster
Int_t npad = cluster->Multiplicity();
Int_t* flags = new Int_t[npad];
for (Int_t j = 0; j < npad; ++j) flags[j] = 0;
// Check pad overlaps
for ( Int_t i = 0; i < npad; ++i)
{
AliMUONPad* padi = cluster->Pad(i);
if ( padi->Cathode() != 0 ) continue;
for (Int_t j = i+1; j < npad; ++j)
{
AliMUONPad* padj = cluster->Pad(j);
if ( padj->Cathode() != 1 ) continue;
if ( !AliMUONPad::AreOverlapping(*padi,*padj,fgkDecreaseSize) ) continue;
flags[i] = flags[j] = 1; // mark overlapped pads
}
}
// Check if all pads overlap
Int_t nFlags=0;
for (Int_t i = 0; i < npad; ++i)
{
if (!flags[i]) ++nFlags;
}
if (nFlags > 0)
{
// not all pads overlap.
if (fDebug) cout << " nFlags: " << nFlags << endl;
TObjArray toBeRemoved;
for (Int_t i = 0; i < npad; ++i)
{
AliMUONPad* pad = cluster->Pad(i);
if (flags[i]) continue;
Int_t cath = pad->Cathode();
Int_t cath1 = TMath::Even(cath);
// Check for edge effect (missing pads on the _other_ cathode)
AliMpPad mpPad
= fkSegmentation[cath1]->PadByPosition(pad->Position().X(),pad->Position().Y(),kFALSE);
if (!mpPad.IsValid()) continue;
//if (nFlags == 1 && pad->Charge() < fgkZeroSuppression * 3) continue;
if (nFlags == 1 && pad->Charge() < 3.05) continue; // JC: adc -> fc
AliDebug(2,Form("Releasing the following pad : de,cath,ix,iy %d,%d,%d,%d charge %e",
fDetElemId,pad->Cathode(),pad->Ix(),pad->Iy(),pad->Charge()));
toBeRemoved.AddLast(pad);
fPreCluster->Pad(i)->Release();
}
Int_t nRemove = toBeRemoved.GetEntriesFast();
for ( Int_t i = 0; i < nRemove; ++i )
{
cluster->RemovePad(static_cast<AliMUONPad*>(toBeRemoved.UncheckedAt(i)));
}
}
// Check correlations of cathode charges
if ( !cluster->IsSaturated() && cluster->ChargeAsymmetry() > 1 )
{
// big difference
Int_t cathode = cluster->MaxRawChargeCathode();
Int_t imin(-1);
Int_t imax(-1);
Double_t cmax(0);
Double_t cmin(1E9);
// get min and max pad charges on the cathode opposite to the
// max pad (given by MaxRawChargeCathode())
//
Int_t mult = cluster->Multiplicity();
for ( Int_t i = 0; i < mult; ++i )
{
AliMUONPad* pad = cluster->Pad(i);
if ( pad->Cathode() != cathode || !pad->IsReal() )
{
// only consider pads in the opposite cathode, and
// only consider real pads (i.e. exclude the virtual ones)
continue;
}
if ( pad->Charge() < cmin )
{
cmin = pad->Charge();
imin = i;
if (imax < 0) {
imax = imin;
cmax = cmin;
}
}
else if ( pad->Charge() > cmax )
{
cmax = pad->Charge();
imax = i;
}
}
AliDebug(2,Form("Pad imin,imax %d,%d cmin,cmax %e,%e",
imin,imax,cmin,cmax));
//
// arrange pads according to their distance to the max, normalized
// to the pad size
Double_t* dist = new Double_t[mult];
Double_t dxMin(1E9);
Double_t dyMin(1E9);
Double_t dmin(0);
AliMUONPad* padmax = cluster->Pad(imax);
for ( Int_t i = 0; i < mult; ++i )
{
dist[i] = 0.0;
if ( i == imax) continue;
AliMUONPad* pad = cluster->Pad(i);
if ( pad->Cathode() != cathode || !pad->IsReal() ) continue;
Double_t dx = (pad->X()-padmax->X())/padmax->DX()/2.0;
Double_t dy = (pad->Y()-padmax->Y())/padmax->DY()/2.0;
dist[i] = TMath::Sqrt(dx*dx+dy*dy);
if ( i == imin )
{
dmin = dist[i] + 1E-3; // distance to the pad with minimum charge
dxMin = dx;
dyMin = dy;
}
}
TMath::Sort(mult,dist,flags,kFALSE); // in ascending order
Double_t xmax(-1), distPrev(999);
TObjArray toBeRemoved;
for ( Int_t i = 0; i < mult; ++i )
{
Int_t indx = flags[i];
AliMUONPad* pad = cluster->Pad(indx);
if ( pad->Cathode() != cathode || !pad->IsReal() ) continue;
if ( dist[indx] > dmin )
{
// farther than the minimum pad
Double_t dx = (pad->X()-padmax->X())/padmax->DX()/2.0;
Double_t dy = (pad->Y()-padmax->Y())/padmax->DY()/2.0;
dx *= dxMin;
dy *= dyMin;
if (dx >= 0 && dy >= 0) continue;
if (TMath::Abs(dx) > TMath::Abs(dy) && dx >= 0) continue;
if (TMath::Abs(dy) > TMath::Abs(dx) && dy >= 0) continue;
}
if (dist[indx] > distPrev + 1) break; // overstepping empty pads
if ( pad->Charge() <= cmax || TMath::Abs(dist[indx]-xmax) < 1E-3 )
{
// release pad
if (TMath::Abs(dist[indx]-xmax) < 1.e-3)
{
cmax = TMath::Max(pad->Charge(),cmax);
}
else
{
cmax = pad->Charge();
}
xmax = dist[indx];
distPrev = dist[indx];
AliDebug(2,Form("Releasing the following pad : de,cath,ix,iy %d,%d,%d,%d charge %e",
fDetElemId,pad->Cathode(),pad->Ix(),pad->Iy(),
pad->Charge()));
toBeRemoved.AddLast(pad);
fPreCluster->Pad(indx)->Release();
}
}
Int_t nRemove = toBeRemoved.GetEntriesFast();
for ( Int_t i = 0; i < nRemove; ++i )
{
cluster->RemovePad(static_cast<AliMUONPad*>(toBeRemoved.UncheckedAt(i)));
}
delete[] dist;
} // if ( !cluster->IsSaturated() &&
delete[] flags;
AliDebug(2,"End of CheckPreClusterTwoCathodes=");
//StdoutToAliDebug(2,cluster->Print("full"));
return cluster;
}
//_____________________________________________________________________________
void
AliMUONClusterFinderPeakCOG::CheckOverlaps()
{
/// For debug only : check if some pixels overlap...
Int_t nPix = fPixArray->GetLast()+1;
Int_t dummy(0);
for ( Int_t i = 0; i < nPix; ++i )
{
AliMUONPad* pixelI = Pixel(i);
AliMUONPad pi(dummy,dummy,dummy,dummy,
pixelI->Coord(0),pixelI->Coord(1),
pixelI->Size(0),pixelI->Size(1),0.0);
for ( Int_t j = i+1; j < nPix; ++j )
{
AliMUONPad* pixelJ = Pixel(j);
AliMUONPad pj(dummy,dummy,dummy,dummy,
pixelJ->Coord(0),pixelJ->Coord(1),
pixelJ->Size(0),pixelJ->Size(1),0.0);
AliMpArea area;
if ( AliMUONPad::AreOverlapping(pi,pj,fgkDecreaseSize,area) )
{
AliInfo(Form("The following 2 pixels (%d and %d) overlap !",i,j));
/*
StdoutToAliInfo(pixelI->Print();
cout << " Surface = " << pixelI->Size(0)*pixelI->Size(1)*4 << endl;
pixelJ->Print();
cout << " Surface = " << pixelJ->Size(0)*pixelJ->Size(1)*4 << endl;
cout << " Area surface = " << area.Dimensions().X()*area.Dimensions().Y()*4 << endl;
cout << "-------" << endl;
);
*/
}
}
}
}
//_____________________________________________________________________________
void AliMUONClusterFinderPeakCOG::BuildPixArray(AliMUONCluster& cluster)
{
/// Build pixel array
Int_t npad = cluster.Multiplicity();
if (npad<=0)
{
AliWarning("Got no pad at all ?!");
}
fPixArray->Delete();
BuildPixArrayOneCathode(cluster);
// StdoutToAliDebug(2,cout << "End of BuildPixelArray:" << endl;
// fPixArray->Print(););
//CheckOverlaps();//FIXME : this is for debug only. Remove it.
}
//_____________________________________________________________________________
void AliMUONClusterFinderPeakCOG::BuildPixArrayOneCathode(AliMUONCluster& cluster)
{
/// Build the pixel array
// AliDebug(2,Form("cluster.Multiplicity=%d",cluster.Multiplicity()));
TVector2 dim = cluster.MinPadDimensions (-1, kFALSE);
Double_t width[2] = {dim.X(), dim.Y()}, xy0[2] = { 0.0, 0.0 };
Int_t found[2] = {0}, mult = cluster.Multiplicity();
for ( Int_t i = 0; i < mult; ++i) {
AliMUONPad* pad = cluster.Pad(i);
for (Int_t j = 0; j < 2; ++j) {
if (found[j] == 0 && TMath::Abs(pad->Size(j)-width[j]) < fgkDistancePrecision) {
xy0[j] = pad->Coord(j);
found[j] = 1;
}
}
if (found[0] && found[1]) break;
}
Double_t min[2], max[2];
Int_t cath0 = 0, cath1 = 1;
if (cluster.Multiplicity(0) == 0) cath0 = 1;
else if (cluster.Multiplicity(1) == 0) cath1 = 0;
Double_t leftDownX, leftDownY;
cluster.Area(cath0).LeftDownCorner(leftDownX, leftDownY);
Double_t rightUpX, rightUpY;
cluster.Area(cath0).RightUpCorner(rightUpX, rightUpY);
min[0] = leftDownX;
min[1] = leftDownY;
max[0] = rightUpX;
max[1] = rightUpY;
if (cath1 != cath0) {
cluster.Area(cath1).LeftDownCorner(leftDownX, leftDownY);
cluster.Area(cath1).RightUpCorner(rightUpX, rightUpY);
min[0] = TMath::Max (min[0], leftDownX);
min[1] = TMath::Max (min[1], leftDownY);
max[0] = TMath::Min (max[0], rightUpX);
max[1] = TMath::Min (max[1], rightUpY);
}
// Adjust limits
//width[0] /= 2; width[1] /= 2; // just for check
Int_t nbins[2];
for (Int_t i = 0; i < 2; ++i) {
Double_t dist = (min[i] - xy0[i]) / width[i] / 2;
if (TMath::Abs(dist) < 1.e-6) dist = -1.e-6;
min[i] = xy0[i] + (TMath::Nint(dist-TMath::Sign(1.e-6,dist))
+ TMath::Sign(0.5,dist)) * width[i] * 2;
nbins[i] = TMath::Nint ((max[i] - min[i]) / width[i] / 2);
if (nbins[i] == 0) ++nbins[i];
max[i] = min[i] + nbins[i] * width[i] * 2;
//cout << dist << " " << min[i] << " " << max[i] << " " << nbins[i] << endl;
}
// Book histogram
TH2D *hist1 = new TH2D ("Grid", "", nbins[0], min[0], max[0], nbins[1], min[1], max[1]);
TH2D *hist2 = new TH2D ("Entries", "", nbins[0], min[0], max[0], nbins[1], min[1], max[1]);
TAxis *xaxis = hist1->GetXaxis();
TAxis *yaxis = hist1->GetYaxis();
// Fill histogram
for ( Int_t i = 0; i < mult; ++i) {
AliMUONPad* pad = cluster.Pad(i);
Int_t ix0 = xaxis->FindBin(pad->X());
Int_t iy0 = yaxis->FindBin(pad->Y());
PadOverHist(0, ix0, iy0, pad, hist1, hist2);
}
// Store pixels
for (Int_t i = 1; i <= nbins[0]; ++i) {
Double_t x = xaxis->GetBinCenter(i);
for (Int_t j = 1; j <= nbins[1]; ++j) {
if (hist2->GetBinContent(hist2->GetBin(i,j)) < 0.01525) continue; // JC: adc -> fc
if (cath0 != cath1) {
// Two-sided cluster
Double_t cont = hist2->GetBinContent(hist2->GetBin(i,j));
if (cont < 999.) continue;
if (cont-Int_t(cont/1000.)*1000. < 0.07625) continue; // JC: adc -> fc
}
//if (hist2->GetBinContent(hist2->GetBin(i,j)) < 1.1 && cluster.Multiplicity(0) &&
// cluster.Multiplicity(1)) continue;
Double_t y = yaxis->GetBinCenter(j);
Double_t charge = hist1->GetBinContent(hist1->GetBin(i,j));
AliMUONPad* pixPtr = new AliMUONPad(x, y, width[0], width[1], charge);
fPixArray->Add(pixPtr);
}
}
/*
if (fPixArray->GetEntriesFast() == 1) {
// Split pixel into 2
AliMUONPad* pixPtr = static_cast<AliMUONPad*> (fPixArray->UncheckedAt(0));
pixPtr->SetSize(0,width[0]/2.);
pixPtr->Shift(0,-width[0]/4.);
pixPtr = new AliMUONPad(pixPtr->X()+width[0], pixPtr->Y(), width[0]/2., width[1], pixPtr->Charge());
fPixArray->Add(pixPtr);
}
*/
//fPixArray->Print();
delete hist1;
delete hist2;
}
//_____________________________________________________________________________
void AliMUONClusterFinderPeakCOG::PadOverHist(Int_t idir, Int_t ix0, Int_t iy0, AliMUONPad *pad,
TH2D *hist1, TH2D *hist2)
{
/// "Span" pad over histogram in the direction idir
TAxis *axis = idir == 0 ? hist1->GetXaxis() : hist1->GetYaxis();
Int_t nbins = axis->GetNbins(), cath = pad->Cathode();
Double_t bin = axis->GetBinWidth(1), amask = TMath::Power(1000.,cath*1.);
Int_t nbinPad = (Int_t)(pad->Size(idir)/bin*2+fgkDistancePrecision) + 1; // number of bins covered by pad
for (Int_t i = 0; i < nbinPad; ++i) {
Int_t ixy = idir == 0 ? ix0 + i : iy0 + i;
if (ixy > nbins) break;
Double_t lowEdge = axis->GetBinLowEdge(ixy);
if (lowEdge + fgkDistancePrecision > pad->Coord(idir) + pad->Size(idir)) break;
if (idir == 0) PadOverHist(1, ixy, iy0, pad, hist1, hist2); // span in the other direction
else {
// Fill histogram
Double_t cont = pad->Charge();
if (hist2->GetBinContent(hist2->GetBin(ix0, ixy)) > 0.01525) // JC: adc -> fc
cont = TMath::Min (hist1->GetBinContent(hist1->GetBin(ix0, ixy)), cont)
+ TMath::Min (TMath::Max(hist1->GetBinContent(hist1->GetBin(ix0, ixy)),cont)*0.1, 1.525); // JC: adc -> fc
hist1->SetBinContent(hist1->GetBin(ix0, ixy), cont);
hist2->SetBinContent(hist2->GetBin(ix0, ixy), hist2->GetBinContent(hist2->GetBin(ix0, ixy))+amask);
}
}
for (Int_t i = -1; i > -nbinPad; --i) {
Int_t ixy = idir == 0 ? ix0 + i : iy0 + i;
if (ixy < 1) break;
Double_t upEdge = axis->GetBinUpEdge(ixy);
if (upEdge - fgkDistancePrecision < pad->Coord(idir) - pad->Size(idir)) break;
if (idir == 0) PadOverHist(1, ixy, iy0, pad, hist1, hist2); // span in the other direction
else {
// Fill histogram
Double_t cont = pad->Charge();
if (hist2->GetBinContent(hist2->GetBin(ix0, ixy)) > 0.01525) // JC: adc -> fc
cont = TMath::Min (hist1->GetBinContent(hist1->GetBin(ix0, ixy)), cont)
+ TMath::Min (TMath::Max(hist1->GetBinContent(hist1->GetBin(ix0, ixy)),cont)*0.1,1.525); // JC: adc -> fc
hist1->SetBinContent(hist1->GetBin(ix0, ixy), cont);
hist2->SetBinContent( hist2->GetBin(ix0, ixy), hist2->GetBinContent(hist2->GetBin(ix0, ixy))+amask);
}
}
}
//_____________________________________________________________________________
Int_t AliMUONClusterFinderPeakCOG::FindLocalMaxima(TObjArray *pixArray, Int_t *localMax, Double_t *maxVal)
{
/// Find local maxima in pixel space
AliDebug(1,Form("nPix=%d",pixArray->GetLast()+1));
//TH2D *hist = NULL;
//delete ((TH2D*) gROOT->FindObject("anode"));
//if (pixArray == fPixArray) hist = (TH2D*) gROOT->FindObject("anode");
//else { hist = (TH2D*) gROOT->FindObject("anode1"); cout << hist << endl; }
//if (hist) hist->Delete();
delete fHistAnode;
Double_t xylim[4] = {999, 999, 999, 999};
Int_t nPix = pixArray->GetEntriesFast();
if ( nPix <= 0 ) return 0;
AliMUONPad *pixPtr = 0;
for (Int_t ipix = 0; ipix < nPix; ++ipix) {
pixPtr = (AliMUONPad*) pixArray->UncheckedAt(ipix);
for (Int_t i = 0; i < 4; ++i)
xylim[i] = TMath::Min (xylim[i], (i%2 ? -1 : 1)*pixPtr->Coord(i/2));
}
for (Int_t i = 0; i < 4; ++i) xylim[i] -= pixPtr->Size(i/2);
Int_t nx = TMath::Nint ((-xylim[1]-xylim[0])/pixPtr->Size(0)/2);
Int_t ny = TMath::Nint ((-xylim[3]-xylim[2])/pixPtr->Size(1)/2);
if (pixArray == fPixArray) fHistAnode = new TH2D("anode","anode",nx,xylim[0],-xylim[1],ny,xylim[2],-xylim[3]);
else fHistAnode = new TH2D("anode1","anode1",nx,xylim[0],-xylim[1],ny,xylim[2],-xylim[3]);
for (Int_t ipix = 0; ipix < nPix; ++ipix) {
pixPtr = (AliMUONPad*) pixArray->UncheckedAt(ipix);
fHistAnode->Fill(pixPtr->Coord(0), pixPtr->Coord(1), pixPtr->Charge());
}
// if (fDraw && pixArray == fPixArray) fDraw->DrawHist("c2", hist);
Int_t nMax = 0, indx, nxy = ny * nx;
Int_t *isLocalMax = new Int_t[nxy];
for (Int_t i = 0; i < nxy; ++i) isLocalMax[i] = 0;
for (Int_t i = 1; i <= ny; ++i) {
indx = (i-1) * nx;
for (Int_t j = 1; j <= nx; ++j) {
if (fHistAnode->GetBinContent(fHistAnode->GetBin(j,i)) < 0.07625) continue; // JC: adc -> fc
//if (isLocalMax[indx+j-1] < 0) continue;
if (isLocalMax[indx+j-1] != 0) continue;
FlagLocalMax(fHistAnode, i, j, isLocalMax);
}
}
for (Int_t i = 1; i <= ny; ++i) {
indx = (i-1) * nx;
for (Int_t j = 1; j <= nx; ++j) {
if (isLocalMax[indx+j-1] > 0) {
localMax[nMax] = indx + j - 1;
maxVal[nMax++] = fHistAnode->GetBinContent(fHistAnode->GetBin(j,i));
if (nMax > 99) break;
}
}
if (nMax > 99) {
AliError(" Too many local maxima !!!");
break;
}
}
if (fDebug) cout << " Local max: " << nMax << endl;
delete [] isLocalMax;
return nMax;
}
//_____________________________________________________________________________
void AliMUONClusterFinderPeakCOG::FlagLocalMax(TH2D *hist, Int_t i, Int_t j, Int_t *isLocalMax)
{
/// Flag pixels (whether or not local maxima)
Int_t nx = hist->GetNbinsX();
Int_t ny = hist->GetNbinsY();
Int_t cont = TMath::Nint (hist->GetBinContent(hist->GetBin(j,i)));
Int_t cont1 = 0, indx = (i-1)*nx+j-1, indx1 = 0, indx2 = 0;
Int_t ie = i + 2, je = j + 2;
for (Int_t i1 = i-1; i1 < ie; ++i1) {
if (i1 < 1 || i1 > ny) continue;
indx1 = (i1 - 1) * nx;
for (Int_t j1 = j-1; j1 < je; ++j1) {
if (j1 < 1 || j1 > nx) continue;
if (i == i1 && j == j1) continue;
indx2 = indx1 + j1 - 1;
cont1 = TMath::Nint (hist->GetBinContent(hist->GetBin(j1,i1)));
if (cont < cont1) { isLocalMax[indx] = -1; return; }
else if (cont > cont1) isLocalMax[indx2] = -1;
else { // the same charge
isLocalMax[indx] = 1;
if (isLocalMax[indx2] == 0) {
FlagLocalMax(hist, i1, j1, isLocalMax);
if (isLocalMax[indx2] < 0) { isLocalMax[indx] = -1; return; }
else isLocalMax[indx2] = -1;
}
}
}
}
isLocalMax[indx] = 1; // local maximum
}
//_____________________________________________________________________________
void AliMUONClusterFinderPeakCOG::FindCluster(AliMUONCluster& cluster,
const Int_t *localMax, Int_t iMax)
{
/// Find pixel cluster around local maximum \a iMax and pick up pads
/// overlapping with it
//TH2D *hist = (TH2D*) gROOT->FindObject("anode");
/* Just for check
TCanvas* c = new TCanvas("Anode","Anode",800,600);
c->cd();
hist->Draw("lego1Fb"); // debug
c->Update();
Int_t tmp;
cin >> tmp;
*/
Int_t nx = fHistAnode->GetNbinsX();
//Int_t ny = hist->GetNbinsY();
Int_t ic = localMax[iMax] / nx + 1;
Int_t jc = localMax[iMax] % nx + 1;
// Get min pad dimensions for the precluster
Int_t nSides = 2;
if (cluster.Multiplicity(0) == 0 || cluster.Multiplicity(1) == 0) nSides = 1;
TVector2 dim0 = cluster.MinPadDimensions(0, -1, kFALSE);
TVector2 dim1 = cluster.MinPadDimensions(1, -1, kFALSE);
//Double_t width[2][2] = {{dim0.X(), dim0.Y()},{dim1.X(),dim1.Y()}};
Int_t nonb[2] = {1, 0}; // coordinate index vs cathode
if (nSides == 1 || dim0.X() < dim1.X() - fgkDistancePrecision) {
nonb[0] = 0;
nonb[1] = 1;
}
// Drop all pixels from the array - pick up only the ones from the cluster
//fPixArray->Delete();
Double_t wx = fHistAnode->GetXaxis()->GetBinWidth(1)/2;
Double_t wy = fHistAnode->GetYaxis()->GetBinWidth(1)/2;
Double_t yc = fHistAnode->GetYaxis()->GetBinCenter(ic);
Double_t xc = fHistAnode->GetXaxis()->GetBinCenter(jc);
Double_t cont = fHistAnode->GetBinContent(fHistAnode->GetBin(jc,ic));
AliMUONPad pixel(xc, yc, wx, wy, cont);
if (fDebug) pixel.Print("full");
Int_t npad = cluster.Multiplicity();
// Pick up pads which overlap with the maximum pixel and find pads with the max signal
Double_t qMax[2] = {0};
AliMUONPad *matrix[2][3] = {{0x0,0x0,0x0},{0x0,0x0,0x0}};
for (Int_t j = 0; j < npad; ++j)
{
AliMUONPad* pad = cluster.Pad(j);
if ( Overlap(*pad,pixel) )
{
if (fDebug) { cout << j << " "; pad->Print("full"); }
if (pad->Charge() > qMax[pad->Cathode()]) {
qMax[pad->Cathode()] = pad->Charge();
matrix[pad->Cathode()][1] = pad;
if (nSides == 1) matrix[!pad->Cathode()][1] = pad;
}
}
}
//if (nSides == 2 && (matrix[0][1] == 0x0 || matrix[1][1] == 0x0)) return; // ???
// Find neighbours of maxima to have 3 pads per direction (if possible)
for (Int_t j = 0; j < npad; ++j)
{
AliMUONPad* pad = cluster.Pad(j);
Int_t cath = pad->Cathode();
if (pad == matrix[cath][1]) continue;
Int_t nLoops = 3 - nSides;
for (Int_t k = 0; k < nLoops; ++k) {
Int_t cath1 = cath;
if (k) cath1 = !cath;
// Check the coordinate corresponding to the cathode (bending or non-bending case)
Double_t dist = pad->Coord(nonb[cath1]) - matrix[cath][1]->Coord(nonb[cath1]);
Double_t dir = TMath::Sign (1., dist);
dist = TMath::Abs(dist) - pad->Size(nonb[cath1]) - matrix[cath][1]->Size(nonb[cath1]);
if (TMath::Abs(dist) < fgkDistancePrecision) {
// Check the other coordinate
dist = pad->Coord(!nonb[cath1]) - matrix[cath1][1]->Coord(!nonb[cath1]);
if (TMath::Abs(dist) >
TMath::Max(pad->Size(!nonb[cath1]), matrix[cath1][1]->Size(!nonb[cath1])) - fgkDistancePrecision) break;
Int_t idir = TMath::Nint (dir);
if (matrix[cath1][1+idir] == 0x0) matrix[cath1][1+idir] = pad;
else if (pad->Charge() > matrix[cath1][1+idir]->Charge()) matrix[cath1][1+idir] = pad; // diff. segmentation
//cout << pad->Coord(nonb[cath1]) << " " << pad->Coord(!nonb[cath1]) << " " << pad->Size(nonb[cath1]) << " " << pad->Size(!nonb[cath1]) << " " << pad->Charge() << endl ;
break;
}
}
}
Double_t coord[2] = {0.}, qAver = 0.;
for (Int_t i = 0; i < 2; ++i) {
Double_t q = 0.;
Double_t coordQ = 0.;
Int_t cath = matrix[i][1]->Cathode();
if (i && nSides == 1) cath = !cath;
for (Int_t j = 0; j < 3; ++j) {
if (matrix[i][j] == 0x0) continue;
Double_t dq = matrix[i][j]->Charge();
q += dq;
coordQ += dq * matrix[i][j]->Coord(nonb[cath]);
//coordQ += (matrix[i][j]->Charge() * matrix[i][j]->Coord(nonb[cath]));
}
coord[cath] = coordQ / q;
qAver = TMath::Max (qAver, q);
}
//qAver = TMath::Sqrt(qAver);
if ( qAver >= 2.135 ) // JC: adc -> fc
{
AliMUONCluster* cluster1 = new AliMUONCluster(cluster);
cluster1->SetCharge(qAver,qAver);
if (nonb[0] == 1)
cluster1->SetPosition(TVector2(coord[1],coord[0]),TVector2(0.,0.));
else
cluster1->SetPosition(TVector2(coord[0],coord[1]),TVector2(0.,0.));
cluster1->SetChi2(0.);
// FIXME: we miss some information in this cluster, as compared to
// the original AddRawCluster code.
AliDebug(2,Form("Adding RawCluster detElemId %4d mult %2d charge %5d (xl,yl)=(%9.6g,%9.6g)",
fDetElemId,cluster1->Multiplicity(),(Int_t)cluster1->Charge(),
cluster1->Position().X(),cluster1->Position().Y()));
fClusterList.Add(cluster1);
}
}
//_____________________________________________________________________________
AliMUONClusterFinderPeakCOG&
AliMUONClusterFinderPeakCOG::operator=(const AliMUONClusterFinderPeakCOG& rhs)
{
/// Protected assignement operator
if (this == &rhs) return *this;
AliFatal("Not implemented.");
return *this;
}
//_____________________________________________________________________________
void AliMUONClusterFinderPeakCOG::PadsInXandY(AliMUONCluster& cluster,
Int_t &nInX, Int_t &nInY) const
{
/// Find number of pads in X and Y-directions (excluding virtual ones and
/// overflows)
//Int_t statusToTest = 1;
Int_t statusToTest = fgkUseForFit;
//if ( nInX < 0 ) statusToTest = 0;
if ( nInX < 0 ) statusToTest = fgkZero;
Bool_t mustMatch(kTRUE);
Long_t cn = cluster.NofPads(statusToTest,mustMatch);
nInX = AliMp::PairFirst(cn);
nInY = AliMp::PairSecond(cn);
}
//_____________________________________________________________________________
void AliMUONClusterFinderPeakCOG::RemovePixel(Int_t i)
{
/// Remove pixel at index i
AliMUONPad* pixPtr = Pixel(i);
fPixArray->RemoveAt(i);
delete pixPtr;
}
//_____________________________________________________________________________
AliMUONPad*
AliMUONClusterFinderPeakCOG::Pixel(Int_t i) const
{
/// Returns pixel at index i
return static_cast<AliMUONPad*>(fPixArray->UncheckedAt(i));
}
//_____________________________________________________________________________
void
AliMUONClusterFinderPeakCOG::Print(Option_t* what) const
{
/// printout
TString swhat(what);
swhat.ToLower();
if ( swhat.Contains("precluster") )
{
if ( fPreCluster) fPreCluster->Print();
}
}
| 34.063765
| 170
| 0.6145
|
AllaMaevskaya
|
67be918e5dd99e296c760a0ab545617700aded39
| 5,229
|
cpp
|
C++
|
CSIS 112 - Advanced Programming/Lab 6/Splice_Arrays/Splice_Arrays/main.cpp
|
setdebarr/university-assignments
|
64bfc720a9ade16a5ba056f200b09c6db216f338
|
[
"Unlicense"
] | null | null | null |
CSIS 112 - Advanced Programming/Lab 6/Splice_Arrays/Splice_Arrays/main.cpp
|
setdebarr/university-assignments
|
64bfc720a9ade16a5ba056f200b09c6db216f338
|
[
"Unlicense"
] | null | null | null |
CSIS 112 - Advanced Programming/Lab 6/Splice_Arrays/Splice_Arrays/main.cpp
|
setdebarr/university-assignments
|
64bfc720a9ade16a5ba056f200b09c6db216f338
|
[
"Unlicense"
] | null | null | null |
//main.cpp -- splices two integer arrays together, and then copys the elements of both arrays into a new array
//CSIS 112-<Section Number>
//<Sources if necessary>
//Include statements
#include <iostream>
#include <string>
//Global declarations: Constants and type definitions only -- NO variables
//Function prototypes
int *splice(int[], int, int[], int, int);
void getPosInt(int&);
void fillArrayWithRandInt(int[], int, bool = true);
void displayArray(int[], int);
int main() {
//In cout statement below substitute your name and lab number
std::cout << "Sean DeBarr -- Lab 6" << std::endl << std::endl;
//Variable declarations
int array1Len; // store user defined lenght for array1
int array2Len; // store user defined lenght for array2
int splicePosition; // store user defined splice position
//Program logic
// get size of integer arrays from user
std::cout << "Please enter size of first array: ";
getPosInt(array1Len);
std::cout << "Please enter size of second array: ";
getPosInt(array2Len);
// declare the two arrays on heap with user defined size
int *array1{new int[array1Len]};
int *array2{new int[array2Len]};
// ask user for position to splice array1
std::cout << "How many elements from Array 1 would you like to splice before Array 2: ";
getPosInt(splicePosition);
// initialize random number generator with seed 100
srand(100);
// fill array1 with random numbers between positive 1-100
fillArrayWithRandInt(array1, array1Len);
// fill array2 with random numbers between negative 1-100
// went with negative numbers to distinguish between the two arrays
fillArrayWithRandInt(array2, array2Len, false);
// displays the contents of array1
std::cout << std::endl << std::endl;
std::cout << "Array 1:";
displayArray(array1, array1Len);
// displays the contents of array2
std::cout << std::endl << std::endl;
std::cout << "Array 2:";
displayArray(array2, array2Len);
// splice the arrays together
int *splicedArray = splice(array1, array1Len, array2, array2Len, splicePosition);
// display the contents of final spliced array
std::cout << std::endl << std::endl;
std::cout << "Spliced Array:";
displayArray(splicedArray, array1Len + array2Len);
// clean up the heap
delete[] array1;
delete[] array2;
delete[] splicedArray;
//Closing program statements
std::cout << std::endl << std::endl;
system("pause");
return 0;
}
//Function definitions
// splices an array inbetween another at specified position
int *splice(int array1[], int array1Len, int array2[], int array2Len, int splicePosition) {
int *combinedArray{new int[array1Len + array2Len]}; // create new array big enough to hold all elements from both input arrays
int array1Position{0}; // keeps track of current position in first array
int arrayPosition{0}; // keeps track of current position in combinedArray
// adds each element of first array into combinedArray up to splice position
for(size_t i = 0; i < splicePosition; ++i) {
combinedArray[i] = array1[i];
array1Position += 1;
}
// sets current combinedArray positon to last postion in array1
arrayPosition = array1Position;
// adds the entire array2 to combinedArray
for(size_t i = 0; i < array2Len; ++i) {
combinedArray[arrayPosition] = array2[i];
arrayPosition += 1;
}
// adds the remaining elements of array1 to combinedArray
for(size_t i = array1Position; i < array1Len; ++i) {
combinedArray[arrayPosition] = array1[i];
arrayPosition += 1;
}
// returns the spliced array
return combinedArray;
}
// gets positive integer from user
void getPosInt(int &value) {
const std::string ALLOWED_CHARACTERS = "0123456789"; // character array of allowed user input
std::string temp; // local string variable to temporarily store user input
bool valid = false; // check for if user entered vaild input
getline(std::cin, temp); // gets input from user
// checks if the user entered allowed characters
while(!valid) {
if((temp.find_first_not_of(ALLOWED_CHARACTERS) != std::string::npos) | temp == "0") {
std::cout << "You must enter an integer, and that integer must be positive and not 0. Please try again. " << std::endl;
std::cout << ">> ";
getline(std::cin, temp);
}
else {
// trys to convert to integer, if the integer is too big stoi throws std::out_of_range exception
try {
value = std::stoi(temp);
valid = true;
}
catch(const std::out_of_range&) {
std::cout << "That integer was too big. Please try again." << std::endl;
std::cout << ">> ";
getline(std::cin, temp);
}
}
}
}
// fill array with random numbers between positive or negative 1-100
void fillArrayWithRandInt(int array[], int arrayLen, bool postitive) {
if(postitive) {
for(size_t i = 0; i < arrayLen; ++i) {
array[i] = (1 + rand() % 100);
}
}
else {
for(size_t i = 0; i < arrayLen; ++i) {
array[i] = -(1 + rand() % 100);
}
}
}
// displays the contents of array
void displayArray(int array[], int arrayLen) {
for(size_t i = 0; i < arrayLen; ++i) {
// this makes sure only 10 elements are displayed per row
if((i % 10) == 0) {
std::cout << std::endl << array[i] << " ";
}
else {
std::cout << array[i] << " ";
}
}
}
| 30.401163
| 127
| 0.688277
|
setdebarr
|
67bfe582d3bb4f9a633dbb13fab2d1ca1e45e1a9
| 436
|
cpp
|
C++
|
LAB6/LAB6/Dacia.cpp
|
florinERotaru/oop-et-al
|
750af01be09967e4112e7c783439fe2bdc0a11ce
|
[
"MIT"
] | null | null | null |
LAB6/LAB6/Dacia.cpp
|
florinERotaru/oop-et-al
|
750af01be09967e4112e7c783439fe2bdc0a11ce
|
[
"MIT"
] | null | null | null |
LAB6/LAB6/Dacia.cpp
|
florinERotaru/oop-et-al
|
750af01be09967e4112e7c783439fe2bdc0a11ce
|
[
"MIT"
] | null | null | null |
#define _CRT_SECURE_NO_WARNINGS
#include "Dacia.h"
#include <cstring>
int Dacia::avgSpeed(int weather) {
switch (weather) {
case 0: // rain
return 60;
case 1: // sunny
return 80;
case 2: // snow
return 43;
}
}
Dacia::Dacia() {
strcpy(name, "Dacia");
fuelCap = 45;
fuelCons = 8;
}
int Dacia::getFuelCons() {
return fuelCons;
}
int Dacia::getFuelCap() {
return fuelCap;
}
| 17.44
| 36
| 0.582569
|
florinERotaru
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.