blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0cb3f6839a8731b0f86303e5908d4d9fb0d7bb26
|
866355b14c8c63d00a56692253af3a33d7bae4d9
|
/Carbanak/Carbanak - part 1/botep/core/source/string.cpp
|
5dafbf80065e68afc9c18f18b330070fda8b490c
|
[] |
no_license
|
mstfknn/malware-sample-library
|
058ed65225602bcea8c90ca5597b6bd5cef8772a
|
521be5ba79c9410f4130cff37d932f0c8277f4b3
|
refs/heads/master
| 2022-05-22T05:24:29.651015
| 2022-04-28T08:58:16
| 2022-04-28T08:58:16
| 154,541,310
| 516
| 160
| null | 2021-02-12T20:39:17
| 2018-10-24T17:28:52
|
C++
|
WINDOWS-1251
|
C++
| false
| false
| 15,448
|
cpp
|
string.cpp
|
#include "core\winapi.h"
#include "core\string.h"
#include "core\memory.h"
#include "core\misc.h"
#include "core\debug.h"
#include <shlwapi.h>
namespace Str
{
bool Init()
{
return true;
}
void Release()
{
}
int Len( const char* s )
{
if( s == 0 ) return 0;
int res = 0;
while( *s++ ) res++;
return res;
}
char* Copy( char* dst, const char* src, int len )
{
if( dst )
{
if( len < 0 ) len = Len(src);
Mem::Copy( dst, src, len );
dst[len] = 0;
}
return dst;
}
char* Copy( char* dst, int sz_dst, const char* src, int len )
{
if( len < 0 ) len = Str::Len(src);
if( len >= sz_dst ) len = sz_dst - 1;
return Copy( dst, src, len );
}
char* Duplication( const char* s, int len )
{
if( s )
{
if( len < 0 ) len = Len(s);
char* ret = (char*)Mem::Alloc( len + 1 );
if( ret )
return Copy( ret, s, len );
}
return 0;
}
char* Alloc( int len )
{
if( len < 0 ) return 0;
char* s = (char*)Mem::Alloc(len + 1);
s[0] = 0;
return s;
}
char* Join( const char* s, ... )
{
int len[16];
const char* str[16];
int count = 0;
int lenRes = 0;
if( s )
{
//считаем конечную длину строки
len[0] = Len(s); str[0] = s;
lenRes += len[0];
count++;
va_list va;
va_start( va, s );
while( count < 16 )
{
const char* sn = va_arg( va, const char* );
if( !sn ) break;
len[count] = Len(sn);
str[count] = sn;
lenRes += len[count];
count++;
}
va_end(va);
}
//создаем новую строку
if( lenRes == 0 ) return 0;
char* res = (char*)Mem::Alloc( lenRes + 1 );
char* p = res;
for( int i = 0; i < count; i++ )
{
Mem::Copy( p, str[i], len[i] );
p += len[i];
}
res[lenRes] = 0;
return res;
}
int FormatVA( char* buf, const char* format, va_list va )
{
return API(USER32, wvsprintfA)( buf, format, va );
}
char* Format( int maxSize, const char* format, ... )
{
char* res = (char*)Mem::Alloc(maxSize);
if( res )
{
va_list va;
va_start( va, format );
FormatVA( res, format, va );
}
return res;
}
int Format( char* buf, const char* format, ... )
{
va_list va;
va_start( va, format );
return FormatVA( buf, format, va );
}
uint Hash( const char* s, int c_s )
{
if( c_s < 0 ) c_s = Len(s);
return CalcHash( (byte*)s, c_s );
}
char* Upper( char* s )
{
char* p = s;
while( *p )
{
*p = Upper(*p);
p++;
}
return s;
}
char Upper( char c )
{
if( c >= 'a' && c <= 'z' )
return c - 'a' + 'A';
else
if( (byte)c >= byte('а') && (byte)c <= byte('я') ) //русские буквы в кодировке 1251
return (byte)c - byte('а') + byte('А');
return c;
}
char* Lower( char* s )
{
char* p = s;
while( *p )
{
*p = Lower(*p);
p++;
}
return s;
}
char Lower( char c )
{
if( c >= 'A' && c <= 'Z' )
return c - 'A' + 'a';
else
if( (byte)c >= byte('А') && (byte)c <= byte('Я') ) //русские буквы в кодировке 1251
return (byte)c - byte('А') + byte('а');
return c;
}
int Cmp( const char* s1, const char* s2, int max )
{
if( s1 )
if( s2 )
{
int n = 0; //количество пройденых символов
for(;;)
{
if( n >= max ) return 0;
if( *s1 )
if( *s2 )
{
if( *s1 > *s2 )
return 1;
else if( *s1 < *s2 )
return -1;
}
else
return 1;
else
if( *s2 )
return -1;
else
return 0;
s1++; s2++; n++;
}
}
else
return 1;
else
if( s2 )
return -1;
else
return 0;
}
int IndexOf( const char* s, const char* sub, int c_s, int c_sub )
{
if( c_s < 0 ) c_s = Len(s);
if( c_sub < 0 ) c_sub = Len(sub);
return Mem::IndexOf( s, c_s, sub, c_sub );
}
int IndexOf( const char* s, char c )
{
if( s )
{
const char* p = s;
while( *p )
{
if( *p == c )
return p - s;
p++;
}
}
return -1;
}
int ReplaceChars( char* s, const char* olds, const char* news )
{
int ret = 0;
char* from = s;
char* to = s;
int c_news = 0;
if( news ) c_news = Len(news);
while( *from )
{
int i = IndexOf( olds, *from );
if( i >= 0 )
{
if( i < c_news )
*to++ = news[i];
else
if( c_news > 0 )
*to++ = news[c_news - 1];
}
else
*to++ = *from;
from++;
}
*to = 0;
return to - s;
}
int ToInt( const char* s, bool hex )
{
if( s == 0 ) return 0;
char hex0x[16];
const char* ptr = s;
int flag = STIF_DEFAULT;
if( hex )
{
//функция StrToIntEx требует, чтобы в начале было 0x
flag = STIF_SUPPORT_HEX;
if( s[0] != '0' || s[1] != 'x' || s[1] != 'X' )
{
hex0x[0] = '0';
hex0x[1] = 'x';
while( *s == ' ' ) s++; //игнорируем пробелы
int len = Len(s);
if( len > sizeof(hex0x) - 3 ) len = sizeof(hex0x) - 3;
Copy( hex0x + 2, s, len );
ptr = hex0x;
}
}
int ret;
if( API(SHLWAPI, StrToIntExA)( ptr, flag, &ret ) )
{
return ret;
}
return 0;
}
char DecToHex( int v )
{
if( v >= 0 && v <= 9 )
return '0' + v;
else
return 'A' + (v - 10);
}
//непосредственный перевод числа в текст
static int ToStringBegin( uint v, char* buf, int radix )
{
int i = 0;
do
{
int digit = v % radix;
if( radix == 16 )
buf[i] = DecToHex(digit);
else
buf[i] = digit + '0';
i++;
v = v / radix;
} while( v );
return i;
}
//переворачивает результат работы ToStringBegin
static void ToStringEnd( const char* buf, char* s, int len )
{
while( --len >= 0 )
*s++ = buf[len];
*s = 0;
}
int ToString( int v, char* s, int radix )
{
bool neg = false;
if( v < 0 && radix == 10 )
{
neg = true;
v = -v;
}
char buf[16];
int len = ToStringBegin( v, buf, radix );
int j = 0;
if( neg ) s[j++] = '-';
ToStringEnd( buf, s + j, len );
return len + j;
}
int ToString( uint v, char* s, int radix )
{
char buf[16];
int len = ToStringBegin( v, buf, radix );
ToStringEnd( buf, s, len );
return len;
}
int LTrim( char* s, char c )
{
if( s == 0 ) return 0;
int i = 0;
while( s[i] == c ) i++;
int ret = i;
if( i > 0 )
{
int j = 0;
while( s[i] ) s[j++] = s[i++];
s[j] = 0;
}
return ret;
}
int RTrim( char* s, int c, int c_s )
{
if( s == 0 ) return 0;
if( c_s < 0 ) c_s = Str::Len(s);
int i = c_s - 1;
while( i >= 0 )
{
if( s[i] != c ) break;
i--;
}
s[i + 1] = 0;
return c_s - i - 1;
}
int Trim( char* s, int c, int c_s )
{
int ret = LTrim( s, c );
if( c_s >= 0 ) c_s -= ret;
ret += RTrim( s, c, c_s );
return ret;
}
int ToWideChar( const char* src, int c_src, wchar_t* to, int size )
{
return API(KERNEL32, MultiByteToWideChar)( CP_ACP, 0, src, c_src, to, size );
}
wchar_t* ToWideChar( const char* src, int c_src )
{
if( c_src < 0 ) c_src = Str::Len(src);
wchar_t* ret = WStr::Alloc(c_src);
ToWideChar( src, c_src + 1, ret, c_src + 1 );
return ret;
}
int Ignore( const char* s, int p, char c )
{
if( s == 0 || p < 0 ) return -1;
while( s[p] == c ) p++;
return p;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
namespace WStr
{
int Len( const wchar_t* s )
{
if( s == 0 ) return 0;
int res = 0;
while( *s++ ) res++;
return res;
}
int ToWin1251( const wchar_t* src, int c_src, char* to, int size )
{
int len = API(KERNEL32, WideCharToMultiByte)( 1251, 0, src, c_src, to, size, 0, 0);
return len;
}
//выделяет память для строки указанной длины
wchar_t* Alloc( int len )
{
if( len < 0 ) return 0;
wchar_t* s = (wchar_t*)Mem::Alloc( sizeof(wchar_t) * (len + 1) );
s[0] = 0;
return s;
}
int IndexOf( const wchar_t* s, wchar_t c )
{
wchar_t* p = Chr( s, c );
if( p )
return s - p;
return -1;
}
wchar_t* Chr( const wchar_t* s, wchar_t c )
{
if( s )
{
while( *s )
{
if( *s == c )
return (wchar_t*)s;
s++;
}
}
return 0;
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
StringBuilder::StringBuilder( int _size, const char* s, int len_s )
{
ptr = Str::Alloc(_size);
size = _size;
alloc = true;
len = 0;
Cat( s, len_s );
}
StringBuilder::StringBuilder( char* _ptr, int _size, const char* s, int len_s )
{
size = _size;
alloc = false;
if( _ptr )
{
if( size < 0 ) size = 0;
ptr = _ptr;
ptr[0] = 0;
len = 0;
Cat( s, len_s );
}
else
{
ptr = (char*)s;
if( len_s < 0 ) len_s = Str::Len(s);
len = len_s;
if( size < 0 ) size = len + 1;
}
}
StringBuilder::StringBuilder( Mem::Data& data, int start, int _len )
{
if( data.Ptr() == 0 )
{
ptr = 0;
len = 0;
size = 0;
}
else
{
alloc = false;
if( start < 0 )
start = 0;
else
if( start > data.Len() )
start = data.Len();
if( _len < 0 || _len + start > data.Len() ) _len = data.Len() - start;
ptr = (char*)data.Ptr() + start;
len = _len;
//в конце блока data могут быть нули, поэтому корректируем длину строки
while( len > 0 && ptr[len - 1] == 0 ) len--;
ptr[len] = 0;
size = data.Size() - start;
}
}
StringBuilder::~StringBuilder()
{
if( alloc )
Str::Free(ptr);
}
bool StringBuilder::Grow( int addSize )
{
if( len + addSize >= size - 1 )
{
if( alloc )
{
int addSize2 = size / 2;
if( addSize2 > addSize ) addSize = addSize2;
int newSize = size + addSize;
char* newPtr = (char*)Mem::Realloc( ptr, newSize );
if( newPtr ) //если память перевыделилась
{
ptr = newPtr;
size = newSize;
return true;
}
}
else
return false;
}
return true;
}
StringBuilder& StringBuilder::Cat( const char* s, int len_s )
{
if( s )
{
if( len_s < 0 ) len_s = Str::Len(s);
if( !Grow(len_s) )
len_s = size - len - 1;
Str::Copy( ptr + len, s, len_s );
len += len_s;
}
return *this;
}
StringBuilder& StringBuilder::Cat( char c )
{
Grow(1);
if( len < size - 1 )
{
ptr[len] = c;
len++;
ptr[len] = 0;
}
return *this;
}
StringBuilder& StringBuilder::Cat( int v, int radix )
{
char buf[16];
int len = Str::ToString( v, buf, radix );
return Cat( buf, len );
}
StringBuilder& StringBuilder::Cat( uint v, int radix )
{
char buf[16];
int len = Str::ToString( v, buf, radix );
return Cat( buf, len );
}
StringBuilder& StringBuilder::Copy( const char* s, int len_s )
{
len = 0;
return Cat( s, len_s );
}
int StringBuilder::UpdateLen()
{
len = Str::Len(ptr);
return len;
}
int StringBuilder::SetLen( int newLen )
{
int oldLen = len;
if( newLen < size && newLen >= 0 ) //если новая меньше выделенной памяти
{
ptr[newLen] = 0;
len = newLen;
}
return oldLen;
}
int StringBuilder::IndexOf( int start, const char* sub, int c_sub ) const
{
if( start < 0 ) start = 0;
int res = Str::IndexOf( ptr + start, sub, len - start, c_sub );
if( res >= 0 )
return start + res;
return -1;
}
int StringBuilder::IndexOf( int start, char c ) const
{
if( start < 0 ) start = 0;
if( start >= len ) return -1;
int res = Str::IndexOf( ptr + start, c );
if( res >= 0 )
return start + res;
return -1;
}
StringBuilder& StringBuilder::Substring( int index, int _len )
{
if( index >= 0 )
{
if( index < len )
{
if( _len > len - index ) _len = len - index;
Str::Copy( ptr, ptr + index, _len );
len = _len;
}
else
{
*ptr = 0;
len = 0;
}
}
return *this;
}
StringBuilder& StringBuilder::Substring( StringBuilder& s, int index, int _len ) const
{
if( index >= 0 )
{
if( index < len )
{
if( _len > len - index ) _len = len - index;
s.Copy( ptr + index, _len );
}
else
s.SetEmpty();
}
return s;
}
StringBuilder& StringBuilder::Insert( int index, const char* s, int c_s )
{
if( index >= 0 && index <= len )
{
if( c_s < 0 ) c_s = Str::Len(s);
Grow(c_s);
int newLen = len + c_s;
int moved = len - index;
if( newLen > size - 1 )
{
moved -= newLen - (size - 1);
if( moved < 0 )
c_s = size - 1 - index;
newLen = size - 1;
}
if( c_s > 0 )
{
int end = newLen - 1;
while( moved > 0 )
{
ptr[end] = ptr[end - c_s];
moved--; end--;
}
Mem::Copy( ptr + index, s, c_s );
ptr[newLen] = 0;
len = newLen;
}
}
return *this;
}
StringBuilder& StringBuilder::Insert( int index, char c )
{
char buf[2];
buf[0] = c;
buf[1] = 0;
return Insert( index, buf, 1 );
}
StringBuilder& StringBuilder::Replace( int index, int sz, const char* s, int c_s )
{
if( index >= 0 && index <= len && sz >= 0 )
{
if( index + sz > len ) sz = len - index;
if( c_s < 0 ) c_s = Str::Len(s);
int newLen = len - sz + c_s;
int moved = len - (index + sz);
if( sz > c_s ) //убираем больше чем вставляем
{
Mem::Copy( ptr + index + c_s, ptr + index + sz, moved );
}
else //убираем меньше чем вставляем
{
Grow( c_s - sz );
if( newLen > size - 1 )
{
moved -= newLen - (size - 1);
if( moved < 0 )
c_s = size - 1 - index;
newLen = size - 1;
}
if( c_s > 0 )
{
int end = newLen - 1;
char* src = &ptr[end - (c_s - sz)];
char* dst = &ptr[end];
while( moved > 0 )
{
*dst-- = *src--;
moved--;
}
}
}
Mem::Copy( ptr + index, s, c_s );
ptr[newLen] = 0;
len = newLen;
}
return *this;
}
StringBuilder& StringBuilder::Replace( int start, int n, const char* oldStr, const char* newStr, int c_oldStr, int c_newStr )
{
int p = start;
if( c_oldStr < 0 ) c_oldStr = Str::Len(oldStr);
if( c_newStr < 0 ) c_newStr = Str::Len(newStr);
while( n-- )
{
int p2 = IndexOf( p, oldStr, c_oldStr );
if( p2 >= 0 )
{
Replace( p2, c_oldStr, newStr, c_newStr );
p = p2 + c_newStr;
}
else
break;
}
return *this;
}
int StringBuilder::ReplaceChar( char oldc, char newc )
{
char buf1[2]; buf1[0] = oldc; buf1[1] = 0;
char buf2[2]; buf2[0] = newc; buf2[1] = 0;
return ReplaceChars( buf1, buf2 );
}
StringArray StringBuilder::Split( char c ) const
{
char buf[2];
buf[0] = c;
buf[1] = 0;
return Split( buf, 1 );
}
StringArray StringBuilder::Split( const char* s, int c_s ) const
{
StringArray ret;
if( s )
{
if( c_s < 0 ) c_s = Str::Len(s);
int p = 0;
StringBuilder tmp;
for(;;)
{
int pp = Str::IndexOf( ptr + p, s, len - p, c_s );
if( pp < 0 )
pp = len;
else
pp += p;
tmp.Copy( ptr + p, pp - p );
ret.Add(tmp);
if( pp >= len ) break;
p = pp + c_s;
}
}
return ret;
}
int StringBuilder::ToInt( int start, bool hex )
{
if( start >= 0 && start < len )
return Str::ToInt( ptr + start, hex );
else
return 0;
}
StringBuilder& StringBuilder::FillEndStr()
{
if( size >= 3 )
{
ptr[0] = '\r';
ptr[1] = '\n';
ptr[2] = 0;
len = 2;
}
else
len = 0;
return *this;
}
StringBuilder& StringBuilder::Set( char c, int count )
{
if( count >= 0 )
{
if( count > size - 1 )
{
if( !Grow( count - size + 1 ) )
count = size - 1;
}
Mem::Set( ptr, c, count );
ptr[count] = 0;
len = count;
}
return *this;
}
StringBuilder& StringBuilder::Right( int count )
{
if( count < len && count >= 0 )
return Substring( len - count );
return *this;
}
StringBuilder& StringBuilder::ToWin1251( const wchar_t* from, int c_from )
{
int needed = WStr::ToWin1251( from, c_from, 0, 0 );
if( needed > 0 )
{
if( c_from > 0 ) needed++; //если c_from = -1, то в needed учтен завершающий нуль
if( needed > size )
{
if( !Grow(needed - size ) )
c_from = size - 1;
}
needed = WStr::ToWin1251( from, c_from, ptr, size );
if( c_from < 0 ) needed--;
}
SetLen(needed);
return *this;
}
|
59e70d610b01337ff45efd606e121b5f93987548
|
cdbcb7f24acd616a1ed0222855d54e6625c94776
|
/Breakout/Gameplay.cpp
|
a409d893ff7ce257d0be4ee0d7d161162638fa83
|
[] |
no_license
|
kraiper/Breakout
|
fce2b1863ce23dbb61b5a871967a72de596ac8f8
|
d7c9794f1e04b9d9acd35fa767d822ba46b2b720
|
refs/heads/master
| 2020-05-18T16:47:37.386399
| 2013-10-22T13:13:41
| 2013-10-22T13:13:41
| 12,587,146
| 0
| 1
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 10,215
|
cpp
|
Gameplay.cpp
|
#include "Gameplay.h"
#ifdef _WIN32
#include "GraphicsDX11.h"
#else
#include "GraphicsOGL4.h"
#include <iostream>
#endif
namespace Logic
{
Gameplay::Gameplay(Inputhandler *&_handler, SoundSystem *soundSys)
{
fps = 0;
mapLoading = new Map();
//tolka Map och skBAJSAPA object enligt den
objectCore = new ObjectCore();
play = ballPadCollided = false;
soundSystem = soundSys;
eventSystem = new EventSystem(0,5); // testvärde
srand (time(NULL));
#ifdef _WIN32
GraphicsDX11::getInstance()->setObjectCore(objectCore);
#else
GraphicsOGL4::getInstance()->setObjectCore(objectCore);
#endif
//objectCore->mapType = objectCore->MapType::eWater;
objectCore->ball->setModelID(0);
camera = new Camera();
camera->setPosition(Logic::fitToScreen(Vec3(0,360,0), Vec3(660,360,0), Vec3(0,0,0), Vec3(660,0,0)));
//camera->setPosition(Logic::fitToScreen(Vec3(0,200,0), Vec3(200,200,0), Vec3(0,0,0), Vec3(200,0,0)));
Logic::calculateCameraBorders(camera->getPosition(), -camera->getPosition().z, (float)(4.f / 3));
std::vector<KeyBind> keys;
keys.push_back(KeyBind(KC_UP, &objectCore->pad->rotateLeft));
keys.push_back(KeyBind(KC_DOWN, &objectCore->pad->rotateRight));
keys.push_back(KeyBind(KC_LEFT, &objectCore->pad->moveLeft));
keys.push_back(KeyBind(KC_RIGHT, &objectCore->pad->moveRight));
keys.push_back(KeyBind(KC_SPACE, &objectCore->pad->ejectBall));
_handler->setPad(objectCore->pad, keys);
//inputHandler = handler;
//inputHandler->setCamera(camera, keys);
objectCore->uiBillboards.push_back(BBUI());
objectCore->uiBillboards.at(objectCore->uiBillboards.size() - 1).pos = Vec2(-200,0);
objectCore->uiBillboards.at(objectCore->uiBillboards.size() - 1).rotation = 0;
objectCore->uiBillboards.at(objectCore->uiBillboards.size() - 1).size = Vec2(400,768);
objectCore->uiBillboards.at(objectCore->uiBillboards.size() - 1).texIndex = 0;
objectCore->uiBillboards.at(objectCore->uiBillboards.size() - 1).tintAlpha = Vec4(0,0,0,1);
objectCore->testFont->loadFontSettings("Fonts/blackwhite.txt");
std::vector<BBFont> test = std::vector<BBFont>();
objectCore->testFont->setImageIndex(7);
objectCore->testText->setFont(objectCore->testFont);
objectCore->testText->setTextData(0, 10);
currentMapIndex = 0;
mapLoading->loadMap(currentMapIndex, &objectCore->bricks, objectCore->ball, objectCore->pad,&objectCore->mapType);
if(objectCore->mapType == objectCore->MapType::eWater)
objectCore->water = new Water(objectCore->pad->getPosition().y);
#ifndef _WIN32
GraphicsOGL4::getInstance()->initVertexBuffer();
#endif
}
void Gameplay::update(double _dt)
{
fps = (int)(1.0 / _dt + 0.5);
//update label
std::ostringstream buffFps;
buffFps << fps;
std::string fpsText = "FPS: "+buffFps.str();
objectCore->testText->setText( fpsText.c_str() );
objectCore->testText->updateTextData();
objectCore->pad->update(_dt);
if(play)
{
objectCore->ball->update(_dt);
if(!ballPadCollided)
ballPadCollided = Logic::ballCollision(objectCore->ball, objectCore->pad, objectCore->pad->getRotation().z);
else
ballPadCollided = false;
}
if(objectCore->ball->getPosition().y < 0)
{
play = false;
objectCore->pad->setReleaseBall(false);
}
if(!play)
{
if(objectCore->pad->getReleaseBall())
{
Vec3 dir = objectCore->pad->getDirection();
objectCore->ball->setDirection(dir.x, dir.y, NULL);
play = true;
objectCore->pad->setReleaseBall(false);
}
objectCore->ball->setPosition(objectCore->pad->getBallPos());
objectCore->ball->updateWorld();
}
#ifdef _WIN32
if(GetAsyncKeyState(VK_NUMPAD0) != 0)
{
nextMap();
}
#endif
if(objectCore->bricks.size() == 0)
{
nextMap();
}
if(objectCore->mapType == objectCore->MapType::eWater)
{
objectCore->water->update(_dt);
Vec3 oldPos = camera->getPosition();
Vec3 oldLookat = camera->getLookAt();
// should be the pad that follows water level and then camera follows pad?
camera->setPosition(Vec3(oldPos.x, objectCore->water->getWaterLevel(),oldPos.z));
camera->setLookAt(Vec3(oldLookat.x,objectCore->water->getWaterLevel(),oldLookat.z));
Logic::calculateCameraBorders(camera->getPosition(), -camera->getPosition().z, (float)(4.f / 3));
oldPos = objectCore->pad->getPosition();
objectCore->pad->setPosition(Vec3(oldPos.x,objectCore->water->getWaterLevel(),oldPos.z));
}
camera->update();
// check collision between a ball and the bricks, will return the id of any brick the ball has
// collided with, if no collision then -1 is returned
int collidingObject = Logic::Check2DCollissions(objectCore->ball, objectCore->bricks);
if(collidingObject != -1)
{
Brick *tempBrick = dynamic_cast<Brick *>(objectCore->bricks.at(collidingObject));
tempBrick->damage();
if(tempBrick->isDestroyed() == true)
{
SAFE_DELETE(objectCore->bricks.at(collidingObject));
objectCore->bricks.erase(objectCore->bricks.begin() + collidingObject, objectCore->bricks.begin() + collidingObject + 1);
std::cout << "Collided with a brick yo! Only " << objectCore->bricks.size() << " left!!!!" << std::endl;
}
else
std::cout << "Collided with a brick yo! But it is still alive!" << std::endl;
}
//Effects
//if(play)
int temptest = eventSystem->Update(_dt);
if (temptest != 0)//Start av effekter
{
#pragma region effects
temptest = 0; //TEST
std::cout << "effect started: ";
if (temptest == 1) //Zapper
{
//starta förvanande effekt
effectTypeActive = 1;
effectTimer = 1;
effectOriginal = objectCore->pad->getPosition();
std::cout << "Zapper" << std::endl;
}
else if (temptest == 2) //Wind
{
objectCore->ball->startWind();
soundSystem->Play(12, 0.5);
std::cout << "Wind" << std::endl;
}
else if (temptest == 4) //Fireballs
{
effectTypeActive = 4;
effectTimer = 3;
effectSpawnTimer = 0;
Vec3 tempVec3;
tempVec3 = Vec3(rand()% 50, 200, 0);
effectFireballs.push_back(tempVec3);
soundSystem->Play(13, 3);
std::cout << "Fireballs" << std::endl;
}
else if (temptest == 5)//Earthquake
{
objectCore->pad->startSlow();
effectTypeActive = 5;
effectOriginal = camera->getPosition();
effectTimer = 3.5;
effectDirection = Vec3((rand()%100)-50, (rand()%100)-50, (rand()%100)-50);
soundSystem->Play(18, 1);
std::cout << "Earthquake" << std::endl;
}
else if (temptest == 7)//Speed
{
objectCore->pad->startSpeed();
soundSystem->Play(16);
std::cout << "Speed" << std::endl;
}
else if (temptest == 8)//Slow
{
objectCore->pad->startSlow();
soundSystem->Play(17);
std::cout << "Slow" << std::endl;
}
else if (temptest == 15)//Stun
{
objectCore->pad->startStun();
soundSystem->Play(6);
std::cout << "Stun" << std::endl;
}
#pragma endregion
}
if(effectTypeActive != 0)//Uppdatering av aktiv effekt
{
#pragma region activeEffects
if (effectTypeActive == 1)//Zapper
{
effectTimer -= _dt;
if (effectTimer < 0)
{
soundSystem->Play(6);
effectTimer = 0;
effectTypeActive = 0;
effectOriginal -= objectCore->pad->getPosition();
std::cout << effectOriginal.length();
if(effectOriginal.length() < 20)
{
objectCore->pad->startStun();
std::cout << "Zapper hit" << std::endl;
}
else
std::cout << "Zapper miss" << std::endl;
}
}
else if (effectTypeActive == 4)//Fireballs
{
if (effectTimer > 0)
{
effectTimer -= _dt;
effectSpawnTimer += _dt;
Vec3 tempVec3;
if (rand() % 300 - effectSpawnTimer * 10 <= 1 && effectFireballs.size() <= 5)
{
tempVec3 = Vec3(rand()% 200, 200, 0);
effectFireballs.push_back(tempVec3);
effectSpawnTimer = 0;
}
}
for(unsigned int i = 0; i < effectFireballs.size(); i++)
effectFireballs[i].y += -_dt * 60;
//objectCore->pad->setPosition(effectFireballs[0]);//TEST
if (effectFireballs[0].y < 45)
{
effectOriginal = effectFireballs[0] - objectCore->pad->getPosition();
effectFireballs.erase(effectFireballs.begin());
if (effectOriginal.length() < 20)
{
objectCore->pad->startStun();
std::cout << "Fireball hit" << std::endl;
}
else
std::cout << "Fireball miss" << std::endl;
}
if (effectFireballs.size() == 0)
effectTypeActive = 0;
}
else if (effectTypeActive == 5)//Earthquake
{
effectTimer -= _dt;
Vec3 tempVec;
tempVec = camera->getPosition();
if (effectTimer < 1)
{
tempVec = Vec3(tempVec.x * (1 -_dt*10) + _dt*10 * effectOriginal.x,
tempVec.y * (1 -_dt*10) + _dt*10 * effectOriginal.y,
tempVec.z * (1 -_dt*10) + _dt*10 * effectOriginal.z);
camera->setPosition(tempVec);
}
else
{
if (rand()%100 <= 20)
effectDirection = Vec3((rand()%120)-60, (rand()%120)-60, (rand()%120)-60);
tempVec = Vec3(tempVec.x + _dt * effectDirection.x,
tempVec.y + _dt * effectDirection.y,
tempVec.z + _dt * effectDirection.z);
camera->setPosition(tempVec);
}
if (effectTimer < 0)
{
effectTimer = 0;
effectTypeActive = 0;
camera->setPosition(effectOriginal);
}
}
#pragma endregion
}
/*static float diff = 0.0f;
diff += 0.5f * _dt;
objectCore->pad->setPosition(Logic::from2DToCylinder(objectCore->pad->getPosition(), 105, diff, Vec3(105,0,0)));*/
}
void Gameplay::nextMap()
{
int noMaps = Resources::LoadHandler::getInstance()->getMapSize();
currentMapIndex++;
if(currentMapIndex >= noMaps)
currentMapIndex = 0;
std::cout << "switched to map with index: " << currentMapIndex << std::endl;
mapLoading->loadMap(currentMapIndex, &objectCore->bricks,NULL,objectCore->pad,&objectCore->mapType);
if(objectCore->mapType == objectCore->MapType::eWater)
{
SAFE_DELETE(objectCore->water);
objectCore->water = new Water(objectCore->pad->getPosition().y);
}
play = false;
}
Gameplay::~Gameplay()
{
SAFE_DELETE(eventSystem);
SAFE_DELETE(camera);
SAFE_DELETE(objectCore);
//SAFE_DELETE(water);
SAFE_DELETE(mapLoading);
}
}
|
b09677310504a60ad6765e81c68e619e754b57e1
|
d5dff0883b223b183a8ee839fdc73c3dc77cb0b2
|
/include/lotus/components/scene.h
|
d91314dcb3b0ab96a46ef9da67dfb7d045c5d68e
|
[
"MIT"
] |
permissive
|
srthkdb/lotus
|
6735cbc33e46c56662b333e0d837e6641bd7f223
|
97b46a8c2f2a20ef63f4e1f29d26bbb7182da6fb
|
refs/heads/master
| 2022-12-19T05:18:27.820838
| 2020-09-12T17:28:03
| 2020-09-12T17:28:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 406
|
h
|
scene.h
|
#pragma once
#include "lotus/physics.h"
#include <string>
namespace Lotus
{
struct CTransform
{
Vector3f Position {0.0f, 0.0f, 0.0f};
Vector3f Rotation {0.0f, -90.0f, 0.0f};
Vector3f Scale {1.0f, 1.0f, 1.0f};
};
struct CScript
{
std::string Path;
};
struct CCamera
{
bool IsActive = false;
float FOV = 45;
};
}
|
4b7cde0b280d7880cf0a84cafb96c1f6ef175694
|
96ae4303816d8f76323d6101675a09011dfaa6cf
|
/node.cpp
|
2f9373567542e2b55abeb1a53fd1d51e6eb98a13
|
[] |
no_license
|
bndoarn/Shortestpath
|
25971a34ae9ac634f565c70d1833fd79b02e192d
|
ddbecedabe24a64ea8f7a7e3e4996c5eab8d3c74
|
refs/heads/master
| 2020-12-24T15:14:23.323057
| 2013-12-13T05:54:34
| 2013-12-13T05:54:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 707
|
cpp
|
node.cpp
|
//implementation of node class
#include "node.h"
node::node(int k)
{
key = k;
start_time = 0;
finish_time = 0;
visit = false;
}
void node::setKey(int k)
{
key = k;
}
void node::setStartTime(int t)
{
start_time = t;
}
void node::setFinishTime(int t)
{
finish_time = t;
}
void node::setDistance(int d)
{
distance = d;
}
int node::getKey() const
{
return key;
}
int node::getStartTime()
{
return start_time;
}
int node::getFinishTime()
{
return finish_time;
}
int node::getDistance() const
{
return distance;
}
bool node::visited()
{
return visit;
}
void node::markVisited()
{
visit = true;
}
void node::markUnvisited()
{
visit= false;
}
|
2cecb4ddece98c6586c59b1c2bbbc899f72521bf
|
2ef63705ea1ab3e22c3055e78043aa6b930a4861
|
/Test_PostgreSQL/code/gemcore/new_configdb/configdb/main.cpp
|
bc9991a4fe4774f0e8db53d7baa3e825768929e9
|
[] |
no_license
|
TravellerOnCode/CERN_GEM_DAQ
|
49a55503cd219ca73bc40c3aa31d32e6c61556e5
|
28d65b46b6639a507f2afcf695fe9bb5c6124c25
|
refs/heads/master
| 2023-03-04T20:28:23.552193
| 2021-02-15T07:15:02
| 2021-02-15T07:15:02
| 298,824,821
| 2
| 2
| null | 2021-02-15T05:19:28
| 2020-09-26T13:54:31
|
C++
|
UTF-8
|
C++
| false
| false
| 4,358
|
cpp
|
main.cpp
|
#include "./interface/database_utils.h"
#include "./interface/vfat_configurations.h"
#include "./interface/vfat_settings.h"
#include "./interface/vfat_indexes.h"
int main(int argc, char** argv)
{
try {
///database info
std::string DBNAME = "gemdatabase3";
std::string USER = "postgres";
std::string PASSWORD = "linuxos16";
std::string IP = "127.0.0.1";
std::string PORT = "5432";
/// connect to the database
pqxx::connection db_client(std::string("dbname = ") + DBNAME + "\
user = "
+ USER + "\
password = "
+ PASSWORD + " \
hostaddr = "
+ IP + "\
port = "
+ PORT);
if (db_client.is_open())
std::cout << "Opened database successfully: " << db_client.dbname() << std::endl;
else {
std::cout << "Can't open database" << std::endl;
return 1;
}
//---------------------------------------------------------------------------
// DECLARING NECESSARY OBJECTS AND std::VECTORS
database_utils ob;
pqxx::result r;
vfat_configurations obj1;
vfat_settings obj2;
vfat_indexes obj3;
std::vector<vfat_configurations> configurations;
std::vector<vfat_settings> vfat_data; // Store data from current JSON
std::vector<vfat_settings> vfat_data_ref; // Store data from reference JSON
std::vector<vfat_indexes> indexes;
//---------------------------------------------------------------------------
// creating tables
obj1.create_table(&db_client);
obj2.create_table(&db_client);
obj3.create_table(&db_client);
//---------------------------------------------------------------------------
std::string filepath = argv[1]; // Read Input JSON File
// std::string config_id = filename1.substr(3,filename1.length()-4);
std::string config_id = ob.extract_configid(filepath);
//---------------------------------------------------------------------------
vfat_data = ob.get_VFAT_settings(filepath);
configurations = ob.get_config_ids();
// indexes = ob.Index_json_to_vec();
std::cout << "All JSON converted to object std::Vectors" << std::endl;
//---------------------------------------------------------------------------
if (argc > 2) {
long reference_config = std::stoi(argv[2]); // Read Reference JSON Name
vfat_data_ref = ob.get_reference_VFAT_settings(
&db_client, reference_config); // Getting Data stored in Reference JSON
// obj2.display_results(vfat_data_ref); //Displaying the results
obj1.insert_data(&db_client, configurations);
vfat_data = obj2.get_new_settings(&db_client, vfat_data, vfat_data_ref,
stoi(config_id));
obj2.insert_data(&db_client, vfat_data, stoi(config_id));
} else {
// Data Insertion (in this particular order data -> config -> index)
obj1.insert_data(&db_client, configurations);
obj2.insert_data(&db_client, vfat_data, stoi(config_id));
//*****obj3.insert_data(&C,indexes);
}
//---------------------------------------------------------------------------
// std::cout << "JSON 1 DATA INSERTED ! " << std::endl;
//---------------------------------------------------------------------------
// PLACED HERE FOR TESTING PURPOSE
// vfat_data_ref = ob.GET_DATA_FROM_REFCONFIG(&C,reference_config);
// //Getting Data stored in Reference JSON
// obj2.display_results(vfat_data_ref); //Displaying the results
//---------------------------------------------------------------------------
std::string query = std::string("select * from ") + "SETTINGS_TABLE" + ";"; // + " where vfat_id = 1000";
r = ob.query_response(&db_client, query);
// RETURNS A std::VECTOR OF OBJECTS
vfat_data = obj2.row_to_object(r);
obj2.display_results(vfat_data);
// db_client.disconnect();
} catch (const std::exception& e) {
std::cerr << e.what() << std::endl;
}
return 0;
}
|
1a62beb354bee5712f930a844bb0211e43575c6e
|
6b409f00aed90b228ead0f79770bc7e4b1b48818
|
/ScreenCapture/include/ScreenCapture/SCCanvasStartWin.h
|
6788c9ffbcd95a5c8494769784eb46f10967ded8
|
[] |
no_license
|
fengjixuchui/old-code
|
7ed6b797930020d242a38566d80b961944f1bc09
|
241ccb529fe2240bdd98661e8d93eb9c25830282
|
refs/heads/master
| 2020-05-25T09:51:13.007953
| 2018-01-02T12:44:55
| 2018-01-02T12:44:55
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,046
|
h
|
SCCanvasStartWin.h
|
#pragma once
#include "HYUtilBase.h"
#include "HYUIBase.h"
#include "HYAutoPtr.h"
#include "SCCanvasControl.h"
#include "SCCanvasSkin.h"
#define SC_MASK_COLOR RGB(255, 0, 255)
typedef CWinTraits<WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, WS_EX_TOPMOST | WS_EX_TOOLWINDOW> CSCStartWinTraits;
class CSCCanvasStartWin: public CWindowImpl<CSCCanvasStartWin, CWindow, CSCStartWinTraits>,
public CHYBkgndDrawMap<CSCCanvasStartWin>,
public CRefCountBase,
public CHYAeroWindowMap<CSCCanvasStartWin, SC_MASK_COLOR, 50>
{
public:
DECLARE_WND_CLASS(_T("SCCanvasStartWin"))
typedef CHYAeroWindowMap<CSCCanvasStartWin, SC_MASK_COLOR, 50> theBase1;
BEGIN_MSG_MAP(CSCCanvasStartWin)
CHAIN_MSG_MAP(CHYBkgndDrawMap<CSCCanvasStartWin>)
MESSAGE_HANDLER(WM_NCCREATE, OnNCCreate)
CHAIN_MSG_MAP(theBase1)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
MESSAGE_HANDLER(WM_COMMAND, OnCommand)
MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
MESSAGE_HANDLER(WM_SIZE, OnSize)
MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown)
MESSAGE_HANDLER(WM_HOTKEY, OnHotKey)
REFLECT_NOTIFICATIONS()
END_MSG_MAP()
CSCCanvasStartWin();
~CSCCanvasStartWin();
protected:
LRESULT OnNCCreate(UINT, WPARAM, LPARAM, BOOL&);
LRESULT OnCreate(UINT, WPARAM, LPARAM, BOOL&);
LRESULT OnCommand(UINT, WPARAM, LPARAM, BOOL&);
LRESULT OnDestroy(UINT, WPARAM, LPARAM, BOOL&);
LRESULT OnSize(UINT, WPARAM, LPARAM, BOOL&);
LRESULT OnLButtonDown(UINT, WPARAM, LPARAM, BOOL&);
LRESULT OnHotKey(UINT, WPARAM wParam, LPARAM lParam, BOOL&);
protected:
VOID LoadResource();
VOID FreeResource();
VOID CreateControl();
VOID DestroyControl();
VOID LayoutControl();
BOOL SetupHotKey();
VOID UnInstallHotKey();
protected:
CTsButton m_StartBtn;
CTsButton m_CloseBtn;
CBitmap m_bmpStartBtnBK;
CImageList m_imgStartBtn;
CString m_strStartBtnText;
CBitmap m_bmpCloseBtnBK;
CImageList m_imgCloseBtn;
CString m_strCloseBtnTip;
CBitmap m_bmpAero;
CFont m_fntBtn;
};
typedef CWinTraitsOR<0, WS_EX_TRANSPARENT, CAeroWinTraits> CHelpTipTraits;
class CSCHelpTipWindow: public CWindowImpl<CSCHelpTipWindow, CWindow, CHelpTipTraits>,
public CRefCountBase,
public CHYAeroWindowMap<CSCHelpTipWindow, RGB(0, 0, 0), 150, FALSE>,
public CHYBkgndDrawMap<CSCHelpTipWindow>,
public CSCSkinObserver<CSCHelpTipWindow>
{
public:
DECLARE_WND_CLASS(_T("SCHelpTipWindow"))
typedef CHYAeroWindowMap<CSCHelpTipWindow, RGB(0, 0, 0), 150, FALSE> theBase;
BEGIN_MSG_MAP(CSCHelpTipWindow)
CHAIN_MSG_MAP(CHYBkgndDrawMap<CSCHelpTipWindow>)
CHAIN_MSG_MAP(CSCSkinObserver<CSCHelpTipWindow>)
CHAIN_MSG_MAP(theBase)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
MESSAGE_HANDLER(WM_HY_PAINT, OnPaint)
END_MSG_MAP()
CSCHelpTipWindow();
VOID UpdateRender();
void DoUIDataChanged(WPARAM wParam, LPARAM lParam);
protected:
LRESULT OnCreate(UINT, WPARAM, LPARAM, BOOL&);
LRESULT OnPaint(UINT, WPARAM, LPARAM, BOOL&);
protected:
VOID GetIdealWinPos(CPoint& pt);
VOID DrawText(CDCHandle dc);
VOID DrawZoomBmp(CDCHandle dc);
VOID GetTextRect(CRect& rtText);
VOID GetZoomRect(CRect& rtZoom);
VOID LoadResource();
private:
CRect m_rtSelect;
COLORREF m_clrCursor;
CString m_strHelpTip;
CPoint m_ptCursor;
};
class CSCInfoBubbleTip: public CWindowImpl<CSCInfoBubbleTip>,
public CHYBmpWindowMap<CSCInfoBubbleTip>,
public CRefCountBase,
public CSCSkinObserver<CSCInfoBubbleTip>
{
public:
DECLARE_WND_CLASS(_T("CSCInfoBubbleTip"))
BEGIN_MSG_MAP(CSCInfoBubbleTip)
CHAIN_MSG_MAP(CHYBmpWindowMap<CSCInfoBubbleTip>)
CHAIN_MSG_MAP(CSCSkinObserver<CSCInfoBubbleTip>)
MESSAGE_HANDLER(WM_HY_PAINT, OnPaint)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
END_MSG_MAP()
CSCInfoBubbleTip();
~CSCInfoBubbleTip();
void DoUIDataChanged(WPARAM wParam, LPARAM lParam);
protected:
LRESULT OnCreate(UINT, WPARAM, LPARAM, BOOL&);
LRESULT OnPaint(UINT, WPARAM wParam, LPARAM, BOOL&);
protected:
VOID LoadResource();
VOID FreeResource();
VOID ApplyResource();
protected:
CBitmap m_bmpBK;
CString m_strText;
CFont m_fntText;
};
|
0ee2ea83e9e65ad16d856529cfa5368e3a4cb30a
|
feedbfdf62022782c433bfd33ababa39d3265963
|
/generated/zml_wss_bird/zml_wss_bird.ino
|
8f733ec076a82b3a591118f082dc4e2a01089cfb
|
[
"MIT"
] |
permissive
|
jblb/zml_wsserver
|
a12d86d7bcd717a709a82c53c669aed23664a003
|
abc5be99d6eda86ff694429e6d957ecc24d8b500
|
refs/heads/master
| 2021-09-05T10:46:15.652018
| 2018-01-13T22:43:51
| 2018-01-13T22:43:51
| 116,972,858
| 0
| 0
| null | 2018-01-10T15:07:51
| 2018-01-10T15:07:51
| null |
UTF-8
|
C++
| false
| false
| 16,932
|
ino
|
zml_wss_bird.ino
|
/*
* ZML WebSocket Server
*
*/
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <WebSocketsServer.h>
#include <Hash.h>
#include <Adafruit_NeoPixel.h>
#include "router_config.h"
#include "wifi_host_config.h"
#include "leds_layout.h"
#define USE_SERIAL Serial
#define CMD_PIN D2
#define BIG_TICK 42
#define HEART_TICK 42
#define MAX_SPEED_DIVISOR 50
//ESP8266WiFiMulti WiFiMulti;
WebSocketsServer webSocket = WebSocketsServer(81);
Adafruit_NeoPixel pixels(NUM_PIXELS, CMD_PIN, NEO_GRB | NEO_KHZ800);
uint8_t *gLAST_LED_OF_GROUP;
void (*gCurrentAction)();
long gNextActionTime = -1;
unsigned int gCurStep = 0;
const uint32_t COLOR_BLACK = pixels.Color(0, 0, 0);
const uint32_t COLOR_PURPLE = pixels.Color(169, 0, 255);
const uint32_t COLOR_ORANGE = pixels.Color(255, 130, 0);
//uint8_t gColorR, gColorG, gColorB;
//uint32_t gColor = pixels.Color(0, 0, 0);
uint32_t gColor = COLOR_PURPLE;
// gLastColor MUST be different than gColor
uint32_t gLastColor = COLOR_BLACK;
const uint16_t MAX_VARIABLE_DELAY = 2000; // ms
uint16_t gVariableBlinkDelay = 1000; //ms
uint16_t gVariableChaseDelay = 2000;
uint16_t gVariableDChaseDelay = 2000;
void initLedLayoutData() {
gLAST_LED_OF_GROUP = new uint8_t[NB_LED_GROUPS];
uint8_t iled = -1;
for (uint8_t i = 0; i < NB_LED_GROUPS; i++) {
iled = -1;
uint8_t j = 0;
while (j < NB_LED_MAX_PER_GROUP && LEDS_LAYOUT[i][j] >= 0) {
iled++;
j++;
}
gLAST_LED_OF_GROUP[i] = iled;
}
}
void printLedLayoutData() {
USE_SERIAL.printf("led layout: number of group: %d\n", NB_LED_GROUPS);
USE_SERIAL.printf("led layout - max number of led by group: %d\n",
NB_LED_MAX_PER_GROUP);
USE_SERIAL.println("LEDS_LAYOUT: ");
for (uint8_t i = 0; i < NB_LED_GROUPS; i++) {
USE_SERIAL.print("{");
for (uint8_t j = 0; j < NB_LED_MAX_PER_GROUP; j++) {
USE_SERIAL.printf("%d", LEDS_LAYOUT[i][j]);
if (j < NB_LED_MAX_PER_GROUP - 1)
USE_SERIAL.print(", ");
}
USE_SERIAL.println("}");
}
USE_SERIAL.print("gLAST_LED_OF_GROUP: {");
for (uint8_t i = 0; i < NB_LED_GROUPS; i++) {
USE_SERIAL.printf("%d", gLAST_LED_OF_GROUP[i]);
if (i < NB_LED_GROUPS - 1)
USE_SERIAL.print(", ");
}
USE_SERIAL.println("}");
USE_SERIAL.println();
}
void showAllPixels(uint32_t aColor) {
for (uint8_t i = 0; i < NUM_PIXELS; i++) {
pixels.setPixelColor(i, aColor);
}
pixels.show();
}
void showAllPixels(uint8_t aR, uint8_t aG, uint8_t aB) {
showAllPixels(pixels.Color(aR, aG, aB));
}
void blackOut() {
showAllPixels(0);
}
void setDelay(long aDelay) {
if (aDelay < 0)
gNextActionTime = -1;
else
gNextActionTime = millis() + aDelay;
}
void doContinuous() {
gCurrentAction = &continuous;
continuous();
}
void continuous() {
if (gColor != gLastColor) {
showAllPixels(gColor);
gLastColor = gColor;
}
setDelay(BIG_TICK);
}
int setSpeedDivisor(uint8_t aDivisor) {
if (aDivisor > MAX_SPEED_DIVISOR)
aDivisor = MAX_SPEED_DIVISOR;
return aDivisor;
}
int setVariableBlinkSpeed(uint8_t aDivisor) {
aDivisor = setSpeedDivisor(aDivisor);
if (aDivisor == 0)
gVariableBlinkDelay = -1;
else
gVariableBlinkDelay = MAX_VARIABLE_DELAY / aDivisor;
}
int setVariableChaseSpeed(uint8_t aDivisor) {
aDivisor = setSpeedDivisor(aDivisor);
if (aDivisor == 0)
gVariableChaseDelay = -1;
else
gVariableChaseDelay = MAX_VARIABLE_DELAY / aDivisor;
}
int setVariableDoubleChaseSpeed(uint8_t aDivisor) {
aDivisor = setSpeedDivisor(aDivisor);
if (aDivisor == 0)
gVariableDChaseDelay = -1;
else
gVariableDChaseDelay = MAX_VARIABLE_DELAY / aDivisor;
}
void helloPixels() {
showAllPixels(100, 100, 100);
delay(100);
blackOut();
USE_SERIAL.print("Leds should have blinked\n");
}
void doBlink() {
gCurStep = 0;
gCurrentAction = &blink;
gCurrentAction();
}
void blink() {
switch (gCurStep) {
case 0:
showAllPixels(gColor);
setDelay(gVariableBlinkDelay);
break;
case 1:
blackOut();
setDelay(gVariableBlinkDelay);
break;
}
gCurStep++;
if (gCurStep > 1)
gCurStep = 0;
}
//int16_t gChaseLastLedOn = -1;
int8_t *gChaseLastILed;
void doChase() {
blackOut();
gCurrentAction = &chase;
//gChaseLastLedOn = -1;
for (uint8_t i = 0; i < NB_LED_GROUPS; i++) {
gChaseLastILed[i] = -1;
}
chase();
}
void chase() {
for (uint8_t i = 0; i < NB_LED_GROUPS; i++) {
if (gChaseLastILed[i] >= 0)
pixels.setPixelColor(LEDS_LAYOUT[i][gChaseLastILed[i]], 0);
gChaseLastILed[i]++;
if (gChaseLastILed[i] >= gLAST_LED_OF_GROUP[i])
gChaseLastILed[i] = 0;
pixels.setPixelColor(LEDS_LAYOUT[i][gChaseLastILed[i]], gColor);
}
pixels.show();
setDelay(gVariableChaseDelay);
}
uint8_t *gDoubleChaseDir; // 0: up, black1: down
void doDoubleChase() {
blackOut();
gCurrentAction = &doubleChase;
for (uint8_t i = 0; i < NB_LED_GROUPS; i++) {
gChaseLastILed[i] = -1;
gDoubleChaseDir[i] = 0;
}
doubleChase();
}
void doubleChase() {
for (uint8_t i = 0; i < NB_LED_GROUPS; i++) {
if (gChaseLastILed[i] >= 0)
pixels.setPixelColor(LEDS_LAYOUT[i][gChaseLastILed[i]], 0);
if (gDoubleChaseDir[i] == 0) {
gChaseLastILed[i]++;
if (gChaseLastILed[i] >= gLAST_LED_OF_GROUP[i]) {
gDoubleChaseDir[i] = -1;
gChaseLastILed[i]++;
if (gLAST_LED_OF_GROUP[i] > 1)
gChaseLastILed[i]++;
}
} else {
gChaseLastILed[i]--;
if (gChaseLastILed[i] < 0) {
gDoubleChaseDir[i] = 0;
if (gLAST_LED_OF_GROUP[i] > 1)
gChaseLastILed[i] = 1;
else
gChaseLastILed[i] = 0;
}
}
pixels.setPixelColor(LEDS_LAYOUT[i][gChaseLastILed[i]], gColor);
}
pixels.show();
setDelay(gVariableDChaseDelay);
}
#define MAX_STEP_FACTOR_GB4 100
void setStepFactorGB4(uint8_t aFactor, uint8_t &aStepFactor) {
if (aFactor == aStepFactor)
return;
if (aFactor < 1)
aStepFactor = 1;
else if (aFactor > MAX_STEP_FACTOR_GB4)
aStepFactor = MAX_STEP_FACTOR_GB4;
else
aStepFactor = aFactor;
}
void gradientsBy4
(uint32_t aColor1, uint8_t aNbSteps1, uint32_t aColor2, uint8_t aNbSteps2,
uint32_t aColor3, uint8_t aNbSteps3, uint32_t aColor4, uint8_t aNbSteps4,
uint16_t &aLastStep, uint8_t &aStepFactor, uint8_t &aLastStepFactor) {
if (aStepFactor != aLastStepFactor) {
aLastStep = aLastStep * aStepFactor / aLastStepFactor;
aLastStepFactor = aStepFactor;
}
aLastStep++;
uint16_t step = aLastStep;
uint32_t color, color1, color2;
uint8_t nbSteps;
if (step >= (aNbSteps1 + aNbSteps2 + aNbSteps3 + aNbSteps4) * aStepFactor) {
step = 0;
aLastStep = 0;
}
if (step < aNbSteps1 * aStepFactor) {
color1 = aColor1;
color2 = aColor2;
nbSteps = aNbSteps1 * aStepFactor;
} else if (step < (aNbSteps1 + aNbSteps2) * aStepFactor) {
color1 = aColor2;
color2 = aColor3;
step = step - aNbSteps1 * aStepFactor;
nbSteps = aNbSteps2 * aStepFactor;
} else if (step < (aNbSteps1 + aNbSteps2 + aNbSteps3) * aStepFactor) {
color1 = aColor3;
color2 = aColor4;
step = step - (aNbSteps1 + aNbSteps2) * aStepFactor;
nbSteps = aNbSteps3 * aStepFactor;
} else if (step < (aNbSteps1 + aNbSteps2 + aNbSteps3 + aNbSteps4) * aStepFactor) {
color1 = aColor4;
color2 = aColor1;
step = step - (aNbSteps1 + aNbSteps2 + aNbSteps3) * aStepFactor;
nbSteps = aNbSteps4 * aStepFactor;
}
if (step == 0) {
color = color1;
} else {
uint8_t r1 = (uint8_t) (color1 >> 16);
uint8_t g1 = (uint8_t) (color1 >> 8);
uint8_t b1 = (uint8_t) color1;
uint8_t r2 = (uint8_t) (color2 >> 16);
uint8_t g2 = (uint8_t) (color2 >> 8);
uint8_t b2 = (uint8_t) color2;
uint8_t r = r1 + step * (r2 - r1) / (nbSteps + 2);
uint8_t g = g1 + step * (g2 - g1) / (nbSteps + 2);
uint8_t b = b1 + step * (b2 - b1) / (nbSteps + 2);
color = pixels.Color(r, g, b);
}
showAllPixels(color);
}
uint16_t gLastStepHeart = 0;
uint8_t gStepFactorHeart = 10;
uint8_t gLastStepFactorHeart = 10;
uint32_t gColorBlack = pixels.Color(0, 0, 0);
uint32_t gColorHeart1 = pixels.Color(153, 0, 15);
uint32_t gColorHeart2 = pixels.Color(184, 0, 18);
void setHeartStepFactor(uint8_t aFactor) {
setStepFactorGB4(aFactor, gStepFactorHeart);
}
void doHeart() {
gLastStepHeart = 0;
gCurrentAction = &heart;
heart();
}
void heart() {
gradientsBy4(gColorBlack, 1, gColorHeart1, 1, gColorBlack, 1, gColorHeart2,
3, gLastStepHeart, gStepFactorHeart, gLastStepFactorHeart);
setDelay(HEART_TICK);
}
double h2rgb(double aV1, double aV2, uint8_t aH) {
if (aH < 0) aH += 6;
if (aH > 6) aH -= 6;
if (aH < 1)
return aV1 + (aV2 - aV1) * aH;
if (aH < 3)
return aV2;
if (aH < 4)
return aV1 + (aV2 - aV1) * (4 - aH);
return aV1;
}
const double TINT2RGB_S = 1;
const double TINT2RGB_L = 0.5;
double TINT2RGB_V1, TINT2RGB_V2;
void initTint2rgb() {
if (TINT2RGB_L < 0.5)
TINT2RGB_V2 = TINT2RGB_L * (1 + TINT2RGB_S);
else
TINT2RGB_V2 = TINT2RGB_L + TINT2RGB_S - (TINT2RGB_L * TINT2RGB_S);
TINT2RGB_V1 = (2 * TINT2RGB_L - TINT2RGB_V2);
}
uint32_t tint2rgb(uint16_t aTint) {
if (aTint > 360)
aTint = 360;
// simplified hsl to rgb conversion, because s and l are fixed and > 0
uint8_t hr = aTint / 60;
uint8_t r = (uint8_t) (255 * h2rgb(TINT2RGB_V1, TINT2RGB_V2, (hr + 2)));
uint8_t g = (uint8_t) (255 * h2rgb(TINT2RGB_V1, TINT2RGB_V2, hr));
uint8_t b = (uint8_t) (255 * h2rgb(TINT2RGB_V1, TINT2RGB_V2, (hr - 2)));
Serial.printf("r: %d, g: %d, b: %d", r, g, b);
return pixels.Color(r, g, b);
}
void paintRandomColors() {
uint32_t color;
for (uint8_t i = 0; i < NUM_PIXELS; i++) {
color = tint2rgb(random(0, 360));
pixels.setPixelColor(i, color);
}
pixels.show();
}
void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t lenght) {
switch(type) {
case WStype_DISCONNECTED:
USE_SERIAL.printf("[%u] Disconnected!\n", num);
break;
case WStype_CONNECTED: {
IPAddress ip = webSocket.remoteIP(num);
USE_SERIAL.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload); webSocket.sendTXT(num, "Connected");
break;
}
case WStype_TEXT: {
String text = String((char *) &payload[0]);
const char* chars_payload = (const char *) payload;
int text_length = strlen(chars_payload);
USE_SERIAL.printf("[%u] get command: %s\n", num, payload);
// send message to client
webSocket.sendTXT(num, "received command: " + text);
int r, g, b;
int s;
int res;
if (text == "ping") {
webSocket.sendTXT(num, "pong");
} else if (text == "black" || text == "blackout") {
gCurrentAction = &blackOut;
blackOut();
setDelay(-1);
USE_SERIAL.print("all leds should be turned off now...\n");
} else if (text == "continuous") {
doContinuous();
} else if (text == "color:purple") {
gColor = COLOR_PURPLE;
} else if (text == "color:orange") {
gColor = COLOR_ORANGE;
} else if (text == "blink") {
doBlink();
} else if (text == "chase") {
doChase();
} else if (text == "doublechase") {
doDoubleChase();
} else if (text == "heart") {
doHeart();
} else if (text == "random") {
USE_SERIAL.print("receive random command\n");
paintRandomColors();
setDelay(-1);
USE_SERIAL.print("random pixel colors should be painted...\n");
} else if (text_length == 12 || text_length == 13) {
USE_SERIAL.print("text_length = 12 or 13\n");
res = sscanf(chars_payload, "color:#%02x%02x%02x", &r, &g, &b);
if (res == 3) {
USE_SERIAL.printf("found: %u, r: %u, g: %u, b: %u\n",
res, r, g, b);
gColor = pixels.Color((uint8_t) r,
(uint8_t) g,
(uint8_t) b);
} else {
res = sscanf(chars_payload, "blinkspeed:%d", &s);
if (res == 1) {
USE_SERIAL.printf("blinkspeed: %d\n", s);
setVariableBlinkSpeed(s);
} else {
res = sscanf(chars_payload, "chasespeed:%d", &s);
if (res == 1) {
USE_SERIAL.printf("chasespeed: %d\n", s);
setVariableChaseSpeed(s);
} else {
res = sscanf(chars_payload, "dchsespeed:%d", &s);
if (res == 1) {
USE_SERIAL.printf("dchsespeed: %d\n", s);
setVariableDoubleChaseSpeed(s);
} else {
res = sscanf(chars_payload, "heartspeed:%d", &s);
if (res == 1) {
USE_SERIAL.printf("heartspeed: %d\n", s);
// we want in fact the opposite of s
setHeartStepFactor(-s);
}
}
}
}
}
}
// send data to all connected clients
// webSocket.broadcastTXT("message here");
break;
}
case WStype_BIN:
USE_SERIAL.printf("[%u] get binary lenght: %u\n", num, lenght);
hexdump(payload, lenght);
// send message to client
// webSocket.sendBIN(num, payload, lenght);
break;
}
}
void setup() {
// USE_SERIAL.begin(921600);
USE_SERIAL.begin(115200);
//USE_SERIAL.setDebugOutput(true);
USE_SERIAL.println();
USE_SERIAL.println();
USE_SERIAL.println();
gCurrentAction = &blackOut;
initLedLayoutData();
gChaseLastILed = new int8_t[NB_LED_GROUPS];
gDoubleChaseDir = new uint8_t[NB_LED_GROUPS];
//printLedLayoutData();
for(uint8_t t = 4; t > 0; t--) {
USE_SERIAL.printf("[SETUP] BOOT WAIT %d...\n", t);
USE_SERIAL.flush();
delay(1000);
}
WiFi.disconnect();
pixels.begin();
helloPixels();
WiFi.hostname(MY_HOSTNAME);
WiFi.mode(WIFI_STA);
Serial.printf("Wi-Fi mode set to WIFI_STA %s\n", WiFi.mode(WIFI_STA) ? "" : "Failed!");
#if USE_STATIC_IP
// Doc says it should be faster
WiFi.config(staticIP, gateway, subnet);
#endif
WiFi.begin(MY_SSID, MY_PASSWORD);
while(WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println();
helloPixels();
Serial.print("Connected, IP address: ");
Serial.println(WiFi.localIP());
Serial.print("MAC: ");
Serial.println(WiFi.macAddress());
Serial.print("hostname: ");
Serial.println(MY_HOSTNAME);
Serial.printf("Gateway IP: %s\n", WiFi.gatewayIP().toString().c_str());
Serial.print("subnet mask: ");
Serial.println(WiFi.subnetMask());
Serial.printf("Connection status: %d\n", WiFi.status());
// WiFiMulti.addAP("MY_SSID", "MY_PASSWORD");
// while(WiFiMulti.run() != WL_CONNECTED) {
// delay(100);
// }
initTint2rgb();
webSocket.begin();
webSocket.onEvent(webSocketEvent);
}
void loop() {
webSocket.loop();
if (gNextActionTime != -1 && gNextActionTime <= millis()) {
gCurrentAction();
}
}
|
90c6fc2202de2597d5aeac29eda906edb0a50bfd
|
e01e342e460c113af02fc85a74adf9459dacfb7f
|
/Change The Files Name Customly/main.cpp
|
707e89a2dd357446d68ec9a26a3421419b215668
|
[] |
no_license
|
hbtalha/My-Utilities
|
4549912ce45622d18630cd40b75689c154a60023
|
e9044c9a8a1e1f68f93010779099f936313db96e
|
refs/heads/master
| 2023-08-10T19:47:40.481529
| 2021-09-30T12:23:06
| 2021-09-30T12:23:06
| 300,035,620
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,048
|
cpp
|
main.cpp
|
#include <iostream>
#include <filesystem>
#include <dirent.h>
#include <windows.h>
#include <boost/algorithm/string.hpp>
using namespace std;
using namespace std::filesystem;
/*
for ( unsigned int i = 0; i < rstr.size(); i++)
{
// cout << rstr[i];
if (isspace(rstr[i]) && isspace(rstr[i+1]))
{
rstr.erase(i, i - (i - 1));
// cout << "found ";
// getch();
i = -1;
}
}
*/
void changeFilesNamesCustomly()
{
DIR *dp;
struct dirent *ep;
const char* path = "D:\\Videos\\TV Shows\\The Big Bang Theory\\Season 11\\";
dp = opendir(path);
while ((ep = readdir(dp)))
{
string file_name = ep->d_name;
string _path = path;
string old_name = _path + ep->d_name;
const char* old_path_name = old_name.data();
boost::erase_all(file_name, "The Big Bang Theory ");
string new_name = _path + file_name;
const char* new_path_name = new_name.data();
rename(old_path_name, new_path_name);
}
}
void changeFilesNamesInABatch(path file_path, string to_erase)
{
for(auto iter : directory_iterator(file_path))
{
string filename = iter.path().filename().string();
if(filename.find(to_erase) != string::npos)
{
boost::erase_all(filename, to_erase);
filesystem::rename(iter.path().string(), file_path.string() + filename);
cout << iter.path().string() << " -> " + file_path.string() + filename << endl;
}
}
}
int main()
{
const char* path = "D:/Videos\\TV Shows\\The Big Bang Theory\\Season 1\\S01E02 The Big Bran Hypothesis.mkv";
SetFileAttributesA(path, FILE_ATTRIBUTE_NORMAL);
filesystem::path file_path = "D:/Desktop/4 Your Eyez Only (2016) - Copy/";
changeFilesNamesInABatch(file_path, "J. Cole - ");
//changeFilesNamesCustomly();
return 0;
}
|
5bd01cba439d48c0dcafe7ebbf022b8abad35586
|
ebd585fdafb22d31fcd6d04b209f81e88d1a2083
|
/boot_images/modem/rfa/pmic/application/vbatt/common/inc/vbatt_adc.h
|
00901a03343740a5162c9d07694f2856efe0f5e8
|
[
"Apache-2.0"
] |
permissive
|
xusl/android-wilhelm
|
fd28144253cd9d7de0646f96ff27a1f4a9bec6e3
|
13c59cb5b0913252fe0b5c672d8dc2bf938bb720
|
refs/heads/master
| 2018-04-03T21:46:10.195170
| 2017-04-20T10:17:49
| 2017-04-20T10:17:49
| 88,847,837
| 11
| 10
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,850
|
h
|
vbatt_adc.h
|
#ifndef VBATT_ADC_H
#define VBATT_ADC_H
/*! \file
* \n
* \brief vbatt_adc.h ----
* \details This header file contains class declarations of the VbattAdc
* class.
* \n
* \n © 2010 QUALCOMM Technologies Incorporated, All Rights Reserved
*/
#include "ivbatt_adc.h"
#include "DDIAdc.h"
namespace PmicObjects
{
namespace Application
{
namespace Vbatt
{
/*===========================================================================
FORWARD DECLARATION
===========================================================================*/
class VbattComparator;
class VbattFactory;
class VbattDal;
/*===========================================================================
TYPE AND CONSTANT DEFINITIONS
===========================================================================*/
/**
* The supoorting ADC channels
*/
typedef enum
{
VBATT_ADC_VBATT,
VBATT_ADC_VBATT_MV,
VBATT_ADC_BATT_ID_MV,
VBATT_ADC_BATT_THERM_DEGC,
VBATT_ADC_PMIC_THERM_DEGC,
VBATT_ADC_ICHG_OUT_MV,
VBATT_ADC_ICHG_MV,
VBATT_ADC_VCHG_MV,
VBATT_ADC_CHG_THERM_DEGC,
VBATT_ADC_USB_VBUS,
VBATT_ADC_CHANNEL_MAX
} vbattAdcChannelType;
/**
* This structure contains the (constant) ADC channel name and a place
* to keep the channel property information that is filled in by the
* call to vbatt_dalAdc_init()
*/
typedef struct
{
/**
* The VBATT ADC channel name
*/
const char *channel_name;
/**
* The DAL ADC input properties for this channel
*/
AdcInputPropertiesType AdcInputProps;
/**
* TRUE if the channel is available, FALSE if not
*/
boolean channel_is_available;
}vbattAdcChannelInfoType;
// blocking read request client object
typedef struct
{
DalDeviceHandle *phDev; /* Handle to DAL ADC */
AdcResultType *pAdcResult;
DALSYSEventHandle hCallbackEvent; /* ADC call back event */
DALSYSEventHandle hSignalEvent; /* Used in ADC read to tell when
the ADC conversion is complete */
DALSYSSyncHandle hSynchronization; /* Used in ADC read to avoid data corruption */
DALSYS_EVENT_OBJECT(callbackEventObject);
} vbattAdcBlockingReadObjType;
/***************************/
/* class VbattAdc */
/***************************/
/*! \class VbattAdc vbatt_adc.h
* \brief
*
* \details
*
* \note
*
* <b>Handles the following</b>
* \n None
*
* <b>Listens for the following events</b>
* \n None
*
* <b>Generates the following events</b>
* \n None
*/
class VbattAdc: IVbattAdc
{
public:
/*! \brief This member function called to notify the VBATT task
* of a CHG event.
* \return void
*/
virtual void QueryBatteryAdcParameters(battery_adc_params_type *batt_ptr);
/*! \brief This member function reads the current battery level.
* \return uint16 The battery voltage
*/
virtual uint16 ReadMv(void);
/*! \brief This member function reads the current battery temperature.
* \return int16 The battery temperature
*/
virtual int16 ReadTemperature(void);
/*! \brief This member function reads the current PMIC temperature.
* \return int32 The PMIC temperature
*/
virtual int32 ReadPmicTemperature(void);
/*! \brief This member function reads the handset supply voltage
* (Vdd) determining current leaving the battery
* \return int32 The charge current leaving the battery
*/
virtual int32 ReadIchgOutMv(void);
/*! \brief This member function reads the charger temperature.
* \return int32 The Charger temperature
*/
virtual int32 ReadChgTemperature(void);
/*! \brief This member function reads the USB VBUS voltage.
* \return int32 The USB VBUS voltage
*/
virtual int32 ReadUsbVbus(void);
/*! \brief This member function reads the voltage across the current
* sense resistor.
* \return int32 The voltage across the current sense resistor.
*/
virtual int32 ReadIchgMv(void);
/*! \brief This member function reads the battery ID.
* \return int32 The battery ID
*/
virtual int32 ReadBatteryId(void);
/*! \brief This member function reads the charger voltage.
* \return int32 The charger voltage
*/
virtual int32 ReadChgMv(void);
/**
* \brief Use this function to update various battery parameters.
*
* @return void
*/
virtual pm_err_flag_type VbattUpdateAdcBatteryParams ( void ) ;
protected:
battery_adc_params_type mBatteryAdcParameters;
protected:
/*! \brief A contructor.
* \param none
* \return NA
*/
VbattAdc(PmicObjects::PmicDevices::PmicDevice* pmicDevice);
virtual ~VbattAdc();
private:
/**
* @brief Initialize the VBATT DAL ADC interface
*
* Initialize the properties for each of the ADC channels used by
* VBATT.
*
* @return DAL_SUCCESS if successful
*/
DALBOOL dalAdcInit(void);
/**
* @brief Initialize an object to be used by the DAL ADC driver
*
* @param phDev
* @param pObj
*
* @return DALResult
*/
DALResult dalAdcInitBlockingReadObj(DalDeviceHandle *phDev,
vbattAdcBlockingReadObjType *pObj);
/**
* @brief This function is called from the DAL ADC driver when
* the blocking read is complete.
*
* @param pObj
* @param dwParam
* @param pPayload
* @param nPayloadSize
*/
static void dalAdcBlockingReadCompleteCb(vbattAdcBlockingReadObjType *pObj,
uint32 dwParam,
void *pPayload,
uint32 nPayloadSize);
/**
* @brief Do a blocking read of one of the DAL ADC channels
* @param pObj
* @param pAdcInputProps
* @param pAdcResult
*
* @return DALResult
*/
DALResult dalAdcBlockingRead(vbattAdcBlockingReadObjType *pObj,
AdcInputPropertiesType *pAdcInputProps,
AdcResultType *pAdcResult);
/**
* @brief Read one of the VBATT ADC channels
*
* @param channel
* @param adc_result
*
* @return boolean
*/
DALBOOL dalAdcReadChannel(vbattAdcChannelType, AdcResultType *adc_result);
/* \brief declare a pointer to ADC device handle */
DalDeviceHandle *mphVbattAdcDev;
/* \brief declare an object to use with ADC reads */
vbattAdcBlockingReadObjType mVbattAdcBlockingReadObj;
/* \brief VBATT ADC channel information */
vbattAdcChannelInfoType mpAdcChannelInfo[VBATT_ADC_CHANNEL_MAX];
/*! \brief friend class VbattFactory
* \details Declare VbattFactory as a friend, so it could create an instance of
* this class.
*/
friend class VbattFactory;
/*! \brief friend class VbattFactory
* \details Declare VbattFactory as a friend, so it could call its private
* member function updateBatteryAdcParameters().
*/
friend class VbattComparator;
/*! \brief friend class VbattFactory
* \details Declare VbattFactory as a friend, so it could call its private
* member function updateBatteryAdcParameters().
*/
friend class VbattDal;
};
}
}
}
#endif /* VBATT_ADC_H */
|
8a6705d6803c907b6fa42782f454ff5fb7ef47ed
|
2f1604f4fb2fda00d0c3663b7f963b107d46d841
|
/National/게임 소스 코드/Sound.h
|
e87d31412e1656bc0c7fba4cd0287183a3ed5ce9
|
[] |
no_license
|
daramkun/World-Skills-2009
|
deeeb53a1dab345281166466196be57a32b751d2
|
dff1d5f4b1b37023970f81cd1dbd3eabd4c24be8
|
refs/heads/master
| 2020-05-25T05:59:06.593964
| 2019-05-20T14:45:05
| 2019-05-20T14:45:05
| 187,658,747
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 361
|
h
|
Sound.h
|
#pragma once
#include "DxUtil.h"
#include <dshow.h>
#pragma comment (lib, "strmiids.lib")
class CSound
{
private:
IGraphBuilder *m_graphBuilder;
IMediaControl *m_mediaControl;
IMediaPosition *m_mediaPosition;
bool m_isPlay;
bool m_isLoop;
public:
CSound(wchar_t *filename);
~CSound(void);
void Play(bool isLoop);
void Stop();
void Update();
};
|
57692f2133e33aed3c1c7649b484b0b6bc907a65
|
5a4fd7072ae71d912a7a2b8a34e83260bdcd75ed
|
/TDB_API/TDB_API_helper.inl
|
b0b7b7ef2a0ba79b2697f8b03622d35ab5409f06
|
[
"Apache-2.0"
] |
permissive
|
chenhq/q_Wind
|
e62d8a9a8fca56f2b7fa38a3ca665178d243b9a9
|
90581d2a18ef703bfbdd5d84f647abb3ba30fc1a
|
refs/heads/master
| 2021-01-19T06:31:01.916726
| 2015-07-17T09:59:17
| 2015-07-17T09:59:17
| 39,283,667
| 1
| 0
| null | 2015-07-18T02:27:07
| 2015-07-18T02:27:06
|
C++
|
UTF-8
|
C++
| false
| false
| 1,982
|
inl
|
TDB_API_helper.inl
|
#ifndef __TDB_API_HELPER_H__
static_assert(0, "Include TDB_API/TDB_API_helper.h instead!");
#endif
#include "util.h"
#include "kdb+.util/type_convert.h"
#include <cassert>
template <typename FieldTraits>
void TDB::parseIndicators(K indicators, std::vector<typename FieldTraits::field_accessor const*>& accessors)
throw(std::string)
{
assert(accessors.empty());
std::vector<std::string> const list = q::qList2String(indicators);
accessors.reserve(list.size());
for (auto i = list.cbegin(); i != list.cend(); ++i) {
auto const accessor = (*FieldTraits::accessor_map::getInstance())[*i];
assert(accessor != NULL);
accessors.push_back(accessor);
}
}
template <typename TdbReq>
void TDB::parseTdbReq(K windCode, K begin, K end, TdbReq& req) throw(std::string) {
std::memset(&req, 0, sizeof(TdbReq));
std::string const code = q::q2String(windCode);
if (code.size() >= sizeof(req.chCode)) {
throw std::string("windCode too long");
}
std::copy(code.begin(), code.end(), req.chCode);
req.chCode[code.size()] = '\0';
util::tm2DateTime(q::q2tm(begin), req.nBeginDate, req.nBeginTime);
util::tm2DateTime(q::q2tm(end), req.nEndDate, req.nEndTime);
}
template <typename FieldTraits, typename TdbReq>
K TDB::runQuery(::THANDLE tdb, TdbReq const& req,
std::vector<typename FieldTraits::field_accessor const*> const& indis,
int(*tdbCall)(::THANDLE, TdbReq const*, typename FieldTraits::tdb_result_type**, int*))
{
int arrayLen = 0;
typename FieldTraits::tdb_result_type* dataArray = NULL;
::TDB_ERROR const result = static_cast<::TDB_ERROR>(tdbCall(tdb, &req, &dataArray, &arrayLen));
TDB::Ptr<typename FieldTraits::tdb_result_type> data(dataArray);
if (result != TDB_SUCCESS) {
return q::error2q(TDB::getError(result));
}
assert(arrayLen >= 0);
assert(data);
// Convert each requested field
q::K_ptr out(ktn(0, indis.size()));
for (size_t i = 0; i < indis.size(); ++i) {
kK(out)[i] = indis[i]->extract(dataArray, arrayLen);
}
return out.release();
}
|
3c0575018988a52ab1ac875b436a502a551034e9
|
819f124011a19d788284197ca80e045ef0e429fc
|
/tvset.cpp
|
4973ef163fd7f8698c6a1ee77e9c46625e9a1e45
|
[] |
no_license
|
velfor/tv_set
|
d959acc3b253080333b2e6b35cffa69cbe031248
|
c9bea6c4ad0b175a60d15607f7d33dc6e0f1aaa8
|
refs/heads/master
| 2023-01-27T13:41:28.227663
| 2020-12-15T15:05:37
| 2020-12-15T15:05:37
| 320,313,381
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 816
|
cpp
|
tvset.cpp
|
#include "tvset.h"
#include <iostream>
TVSet::TVSet() {
isOn = false;
for (int i = 0; i < channelQty; i++) channelList[i] = ' ';
}
void TVSet::turnOn() { isOn = true; channelNum = 1; }
void TVSet::turnOff() { isOn = false; }
void TVSet::showStatus() {
if (isOn) {
std::cout << "TV is on, channel " << channelNum << ' '
<< channelList[channelNum - 1] << std::endl;
}
else std::cout << "TV is off" << std::endl;
}
void TVSet::setChannelNum(unsigned int fNum) {
channelNum = fNum;
}
void TVSet::increaseChannelNum() {
channelNum++;
if (channelNum > channelQty) channelNum = 1;
}
void TVSet::decreaseChannelNum() {
channelNum--;
if (channelNum < 1) channelNum = channelQty;
}
void TVSet::setChannelList(std::string fList[], int size) {
for (int i = 0; i < size; i++) {
channelList[i] = fList[i];
}
}
|
47d991d4fbbe9720f6d68c2eb11ff86419e2e6b5
|
52124740605e99267a49d7a33da467e123c4a05d
|
/TD8/SUBST1.cpp
|
20b476ac182a6ab0e5eb9cea1a346a314e200efd
|
[] |
no_license
|
joaopfg/Competitive-programming
|
582c68084f8d3963e356cdcaaa269f4606b35405
|
9266a753fc552619bf4b3ee7c8abb26575e69790
|
refs/heads/master
| 2022-08-03T00:11:17.431331
| 2020-05-29T20:16:29
| 2020-05-29T20:16:29
| 267,943,202
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 754
|
cpp
|
SUBST1.cpp
|
#include <bits/stdc++.h>
#define rep(i,begin,end) for(int i=begin;i<=end;i++)
#define repi(i,end,begin) for(int i=end;i>=begin;i--)
#define fio ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
using namespace std;
int cases;
int prefMax(string (&s)){
int sz = (int)s.size();
vector<int> sPref(sz);
sPref[0] = 0;
rep(i,1,sz-1){
int j = sPref[i-1];
while(j > 0 && s[i] != s[j]) j = sPref[j-1];
if(s[i] == s[j]) j++;
sPref[i] = j;
}
return sPref[sz-1];
}
int main(){
fio
cin >> cases;
while(cases--){
int ans = 0;
string s, aux;
cin >> s;
rep(i,0,(int)s.size() - 1){
aux.push_back(s[i]);
reverse(aux.begin(),aux.end());
ans += i+1-prefMax(aux);
reverse(aux.begin(),aux.end());
}
cout << ans << endl;
}
return 0;
}
|
4ed78403e35ffa191d028a31a57541e262b64e33
|
95ab32af4659971fcd5a76840d500d0fa181dda9
|
/Linked-List/Single-Linked-List/6_detectLoopSLL.cpp
|
b50f80989d7563c3aa60e7d01245dd8278bcc856
|
[] |
no_license
|
piyushkumar96/Data-Structure-Programs
|
b7c418900b90d2502068699972255e22aabdba51
|
bd8c2e1cd6f53a37c0c964df48bd80b60a7a078d
|
refs/heads/master
| 2020-04-22T10:26:45.665753
| 2019-09-26T12:31:13
| 2019-09-26T12:31:13
| 170,305,866
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,318
|
cpp
|
6_detectLoopSLL.cpp
|
/**
* author:- piyushkumar96
* description:- Detect Loop in Linked List (Floyd's Cycle and Hashing Method)
**/
#include<bits/stdc++.h>
using namespace std;
struct Node{
int item;
struct Node* next;
Node(int item){
this->item=item;
next=NULL;
}
};
struct LinkedList {
Node* HEAD, *LAST;
LinkedList(){
HEAD=NULL;
LAST=NULL;
}
void insert(int item){
if(HEAD == NULL){
//cout<<"Linked list is empty "<<"\n";
Node* newnode = new Node(item);
HEAD=newnode;
LAST=newnode;
cout<<"Successfully Inserted "<<"\n";
}else {
Node* CURR = HEAD;
while(CURR->next != NULL){
CURR=CURR->next;
}
Node* newnode = new Node(item);
CURR->next=newnode;
LAST=newnode;
cout<<"Successfully Inserted "<<"\n";
}
}
// Method1 using Floyd's Cycle Algo
void detectLoopM1(){
if(HEAD == NULL){
cout<<"Linked List is empty "<<"\n";
}else {
Node* SLOW = HEAD;
Node* FAST = HEAD;
while((SLOW != NULL) && (FAST != NULL) && (FAST->next != NULL)){
FAST = FAST->next->next;
SLOW = SLOW->next;
if(SLOW == FAST){
cout<<" Loop Deteted" <<"\n";
return;
}
}
cout<<"No Loop Detected"<<"\n";
}
}
// Method2 using Hashing
void detectLoopM2(){
if(HEAD == NULL){
cout<<"Linked List is empty "<<"\n";
}else {
unordered_set<struct Node*> s;
struct Node* CURR = HEAD;
while(CURR != NULL){
if(s.find(CURR) != s.end()){
cout<<" Loop Deteted" <<"\n";
return;
}
s.insert(CURR);
CURR = CURR->next;
}
}
}
void createLoop(){
LAST->next = HEAD->next->next->next;
cout<<" Loop is Created"<<"\n";
}
void printLL(){
Node* CURR = HEAD;
if(CURR == NULL){
cout<<" Linked List is empty. Please insert element first"<<"\n";
}else {
cout<<"Linked List:- ";
while(CURR != NULL){
cout<<CURR->item<<" ";
CURR=CURR->next;
}
cout<<"\n";
}
}
};
int main(){
//ios::sync_with_stdio(false);
//cin.tie(0);
int i, item;
LinkedList ll;
ll.insert(1);
ll.insert(2);
ll.insert(3);
ll.insert(4);
ll.insert(5);
ll.insert(6);
ll.insert(7);
ll.insert(8);
ll.createLoop();
while(1){
cout<<"\nSimple Linked List \n 1. Floyd's Cycle Algo Method (Loop Detection) \n 2. Hashing Method (Loop Detection) \n 3. Display \n Press any key to Exit \n";
cin>>i;
switch (i)
{
case 1: ll.detectLoopM1();
break;
case 2: ll.detectLoopM2();
break;
case 3: ll.printLL();
break;
default: exit(1);
break;
}
}
return 0;
}
|
158c0b2e18c889c2900501ae1915f57f8709008e
|
077bae5fedcb7b6f5a8c4f1284482c3ad215e088
|
/client/crystalSpace/include/csparser/loadinfo.h
|
23391a9c7dca84968eda79fd132e8709aa6742e2
|
[] |
no_license
|
runngezhang/archived-chime3
|
7d59aef8c7fda432342cfdb7e68fba2a45b028da
|
a3b8592117436144b092922130cb2248b6a515d6
|
refs/heads/master
| 2021-01-23T23:46:37.708039
| 2002-05-11T21:32:02
| 2002-05-11T21:32:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,484
|
h
|
loadinfo.h
|
/*
Copyright (C) 1998 by Ivan Avramovic <ivan@avramovic.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef __CS_LOADINFO_H__
#define __CS_LOADINFO_H__
#include "csgeom/transfrm.h"
class csMaterialWrapper;
class csTextureList;
class PSLoadInfo
{
public:
csMaterialWrapper* default_material;
float default_texlen;
bool use_mat_set;
char* mat_set_name;
csReversibleTransform hard_trans;
bool do_hard_trans;
///
PSLoadInfo () : default_material (NULL),
default_texlen (1),
use_mat_set (false), mat_set_name (NULL),
do_hard_trans (false) {}
void SetTextureSet (const char* name)
{
if (mat_set_name) delete [] mat_set_name;
mat_set_name = new char [strlen (name) + 1];
strcpy (mat_set_name, name);
}
};
#endif // __CS_LOADINFO_H__
|
390f423260a6a7fbe0b78faed1980d2faeea6cc2
|
0b070626740788d5af23fcd1cd095e56033308de
|
/448.cpp
|
dd82ebdcbcf9bdffe9184317fd5739cdb1d2b48c
|
[] |
no_license
|
xis19/leetcode
|
71cb76c5764f8082155d31abcb024b25fd90bc75
|
fb35fd050d69d5d8abf6794ae4bed174aaafb001
|
refs/heads/master
| 2021-03-24T12:53:34.379480
| 2020-02-24T04:25:36
| 2020-02-24T04:25:36
| 76,006,015
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 465
|
cpp
|
448.cpp
|
#include <cstdlib>
#include <vector>
std::vector<int> findDisappearedNumbers(std::vector<int>& nums) {
// We use the index of the array to store the existing values
const int N = nums.size();
for(int i = 0; i < N; ++i) {
auto absValue = std::abs(nums[i]) - 1;
if (nums[absValue] > 0) nums[absValue] *= -1;
}
std::vector<int> result;
for(int i = 0; i < N; ++i) if (nums[i] > 0) result.push_back(i + 1);
return result;
}
|
6469af157d22a3282f6d88ea15b493d5c11168dc
|
fae3156a0c94ea31b77f6b83e9e57b21e3cf37ea
|
/SunPlayer_DuiLib/SunPlayer/MediaPlay.cpp
|
40a908a3db2c9f4153a9890dd6046bec03d2c178
|
[] |
no_license
|
Lufeiguo/SunPlayer_DuiLib
|
34f4acd0282a95e6b6d4088bc22817b8f48d6fef
|
3a50d835a4311bbf929bd6e340cf89d83f1fe635
|
refs/heads/master
| 2022-01-17T02:40:37.154224
| 2017-04-19T03:36:54
| 2017-04-19T03:36:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,587
|
cpp
|
MediaPlay.cpp
|
#include "stdafx.h"
#include "MediaPlay.h"
CMediaPlay::CMediaPlay()
:m_hplayer(NULL),
m_hWnd(NULL),
m_bPlaying(false),
m_nRenderType(VDEV_RENDER_TYPE_GDI),
m_nAudioVolume(0),
m_llDuration(0),
m_nVideoWidth(0),
m_nVideoHeight(0),
m_nIndex(0),
m_rect({0,0,0,0})
{
}
CMediaPlay::~CMediaPlay()
{
}
void CMediaPlay::SetHwnd(HWND hWnd)
{
m_hWnd = hWnd;
}
void CMediaPlay::SetDisplayArea(RECT rect)
{
m_rect = rect;
if (m_hplayer)
{
player_setrect(m_hplayer, 0, m_rect.left, m_rect.top, m_rect.right - m_rect.left, m_rect.bottom - m_rect.top);
player_setrect(m_hplayer, 1, m_rect.left, m_rect.top, m_rect.right - m_rect.left, m_rect.bottom - m_rect.top);
}
}
bool CMediaPlay::Play(CDuiString strFileName)
{
if(!::IsWindow(m_hWnd))
{
return false;
}
Stop();
m_hplayer = player_open(const_cast<char*>(WStringToString(strFileName.GetData()).c_str()),m_hWnd);
player_getparam(m_hplayer, PARAM_VIDEO_WIDTH, &m_nVideoWidth);
player_getparam(m_hplayer, PARAM_VIDEO_HEIGHT, &m_nVideoHeight);
player_getparam(m_hplayer, PARAM_MEDIA_DURATION, &m_llDuration);
player_setparam(m_hplayer, PARAM_VDEV_RENDER_TYPE, &m_nRenderType);
player_setparam(m_hplayer, PARAM_AUDIO_VOLUME, &m_nAudioVolume);
player_play(m_hplayer);
m_bPlaying = true;
return true;
}
bool CMediaPlay::Play(int nIndex)
{
if(nIndex >= m_vecFileNames.size() || nIndex < 0)
{
return false;
}
m_nIndex = nIndex;
return Play(m_vecFileNames[nIndex]);
}
void CMediaPlay::Stop()
{
if (m_hplayer)
{
player_close(m_hplayer);
m_hplayer = NULL;
}
m_bPlaying = false;
m_llDuration = 0;
m_nVideoWidth = 0;
m_nVideoHeight = 0;
}
void CMediaPlay::Pause()
{
if (m_hplayer && m_bPlaying)
{
player_pause(m_hplayer);
m_bPlaying = false;
}
}
void CMediaPlay::Play()
{
if (m_hplayer)
{
// continue to play
player_play(m_hplayer);
m_bPlaying = true;
}
}
bool CMediaPlay::Next()
{
return Play(m_nIndex + 1);
}
bool CMediaPlay::Previous()
{
return Play(m_nIndex - 1);
}
void CMediaPlay::Seek(LONGLONG ms)
{
if (m_hplayer)
{
ms = ms > m_llDuration ? m_llDuration : ms;
if (ms < 0)
ms = 0;
player_seek(m_hplayer, ms);
}
}
bool CMediaPlay::IsPlaying()
{
return m_bPlaying;
}
bool CMediaPlay::IsOpenFile()
{
return m_hplayer ? true : false;
}
CDuiString CMediaPlay::GetPlayingFileName()
{
CDuiString strFileName;
if (m_nIndex >= 0 && m_nIndex < m_vecFileNames.size())
{
CDuiString strFilePath = m_vecFileNames[m_nIndex];
strFileName = strFilePath.Mid(strFilePath.ReverseFind(_T('\\')) + 1);
}
return strFileName;
}
int CMediaPlay::GetPlayListCount()
{
return m_vecFileNames.size();
}
int CMediaPlay::GetCurIndex()
{
return m_nIndex;
}
void CMediaPlay::AddToPlayList(vector<CDuiString>& vecFileNames)
{
m_vecFileNames.insert(m_vecFileNames.end(), vecFileNames.begin(), vecFileNames.end());
}
void CMediaPlay::SetRenderType(int nRenderType)
{
m_nRenderType = nRenderType;
if (m_hplayer)
player_setparam(m_hplayer, PARAM_VDEV_RENDER_TYPE, &m_nRenderType);
}
void CMediaPlay::SetAudioVolume(int nAudioVolume)
{
m_nAudioVolume = nAudioVolume;
if (m_hplayer)
player_setparam(m_hplayer, PARAM_AUDIO_VOLUME, &m_nAudioVolume);
}
int CMediaPlay::GetAudioVolume()
{
return m_nAudioVolume;
}
LONGLONG CMediaPlay::GetVideoDuration()
{
return m_llDuration;
}
LONGLONG CMediaPlay::GetCurPosition()
{
LONGLONG position = 0;
if (m_hplayer)
player_getparam(m_hplayer, PARAM_MEDIA_POSITION, &position);
return position;
}
int CMediaPlay::GetVideoWidth()
{
return m_nVideoWidth;
}
int CMediaPlay::GetVideoHeight()
{
return m_nVideoHeight;
}
|
58a623d04c9fa8ec0ca63181e76147145a291358
|
3aa028649f6e9a26454a1caa4d0b89cbe341d660
|
/BRAINSABC/qhull/testqh.cxx
|
02f906b48d18240bdd910e1b369665b99e4d02cd
|
[] |
no_license
|
jcfr/BRAINSStandAlone
|
2738b83213235c35148f291ad57d07bdeb30de07
|
db8a912bbd19734968e4cf83752cb1facdba10eb
|
refs/heads/master
| 2021-01-16T21:03:02.734435
| 2011-10-26T18:30:54
| 2011-10-26T18:30:54
| 2,634,574
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 869
|
cxx
|
testqh.cxx
|
#include "vtkQhullDelaunay3D.h"
#include "vtkUnstructuredGridWriter.h"
int main(int argc, char * *argv)
{
vtkPoints *pts = vtkPoints::New();
double c = 2.0;
/*
for (double x = -c; x <= c; x += 1.0)
for (double y = -c; y <= c; y += 1.0)
for (double z = -c; z <= c; z += 1.0)
*/
for( double x = 0; x <= c; x += 1.0 )
{
for( double y = 0; y <= c; y += 1.0 )
{
for( double z = 0; z <= c; z += 1.0 )
{
double p[3];
p[0] = x;
p[1] = y;
p[2] = z;
pts->InsertNextPoint(p);
}
}
}
vtkUnstructuredGrid *mesh = vtkQhullDelaunay3D(pts);
vtkUnstructuredGridWriter *meshWriter = vtkUnstructuredGridWriter::New();
meshWriter->SetFileTypeToBinary();
meshWriter->SetFileName("testqh.vtk");
meshWriter->SetInput(mesh);
meshWriter->Update();
return 0;
}
|
7f81701cbe644bad7fe734aa3e4d0a26f5cc60a1
|
fe5f0b9604b9199ae6b51a688e435e825b7cd21e
|
/Algorithms/LeetCode/133_clone_graph.cpp
|
2ea55c281ef13d3a73559c1846b62db28954533d
|
[] |
no_license
|
leeo1116/CodeBlocks
|
06ca12aea2e56ae0f464e59eb98076944c600203
|
3a6a601c11cf40cc0e4cec2a5edda44bf14602d1
|
refs/heads/master
| 2020-12-09T04:39:51.963226
| 2016-11-01T06:09:00
| 2016-11-01T06:09:00
| 47,295,356
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,302
|
cpp
|
133_clone_graph.cpp
|
#include "Leetcode.h"
UndirectedGraphNode *UndirectedGraphNode::CloneGraphBFS(UndirectedGraphNode *startNode){
if(!startNode) return NULL;
UndirectedGraphNode *startNodeCopy = new UndirectedGraphNode(startNode->label);
graphMap[startNode] = startNodeCopy;
queue<UndirectedGraphNode *> toVisit;
toVisit.push(startNode);
while(!toVisit.empty()){
UndirectedGraphNode *currentNode = toVisit.front();
toVisit.pop();
for(UndirectedGraphNode *n : currentNode->neighbors){
// if cannot find neighbor
if(graphMap.find(n) == graphMap.end()){
UndirectedGraphNode *nCopy = new UndirectedGraphNode(n->label);
graphMap[n] = nCopy;
toVisit.push(n);
}
graphMap[currentNode]->neighbors.push_back(graphMap[n]);
}
}
return startNodeCopy;
}
UndirectedGraphNode *UndirectedGraphNode::CloneGraphDFS(UndirectedGraphNode *startNode){
if(!startNode) return NULL;
if(graphMap.find(startNode) == graphMap.end()){
graphMap[startNode] = new UndirectedGraphNode(startNode->label);
for(UndirectedGraphNode *n : startNode->neighbors)
graphMap[startNode]->neighbors.push_back(CloneGraphDFS(n));
}
return graphMap[startNode];
}
|
18c3363b5f686a513d8ac446a7bc5eb04c67ed74
|
c12fba29b0cbb5071dca39ddbe67da9607b77d65
|
/Engine/Source/Components/ComponentManager.cpp
|
6d381352e7280e71a9d4013f344121a4655fb282
|
[] |
no_license
|
satellitnorden/Catalyst-Engine
|
55666b2cd7f61d4e5a311297ccbad754e901133e
|
c8064856f0be6ed81a5136155ab6b9b3352dca5c
|
refs/heads/master
| 2023-08-08T04:59:54.887284
| 2023-08-07T13:33:08
| 2023-08-07T13:33:08
| 116,288,917
| 21
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,651
|
cpp
|
ComponentManager.cpp
|
//Header file.
#include <Components/Core/ComponentManager.h>
//Entities.
#include <Entities/Types/Entity.h>
/*
* Defines an entity class with with one component.
*/
#define DEFINE_ENTITY_CLASS_WITH_ONE_COMPONENT(ENTITY_CLASS, FIRST_COMPONENT) \
DynamicArray<Entity *RESTRICT> ComponentManager::_ ## ENTITY_CLASS ## Entities; \
DynamicArray<FIRST_COMPONENT> ComponentManager::_ ## ENTITY_CLASS ## FIRST_COMPONENT ## s; \
NO_DISCARD uint64 ComponentManager::GetNew ## ENTITY_CLASS ## ComponentsIndex(Entity *const RESTRICT entity) NOEXCEPT \
{ \
_ ## ENTITY_CLASS ## Entities.Emplace(entity); \
_ ## ENTITY_CLASS ## FIRST_COMPONENT ## s.Emplace(); \
\
return _ ## ENTITY_CLASS ## Entities.LastIndex(); \
} \
RESTRICTED NO_DISCARD DynamicArray<Entity *RESTRICT> *const RESTRICT ComponentManager::Get ## ENTITY_CLASS ## Entities() NOEXCEPT \
{ \
return &_ ## ENTITY_CLASS ## Entities; \
} \
NO_DISCARD uint64 ComponentManager::GetNumberOf ## ENTITY_CLASS ## Components() NOEXCEPT \
{ \
return _ ## ENTITY_CLASS ## Entities.Size(); \
} \
RESTRICTED NO_DISCARD FIRST_COMPONENT *const RESTRICT ComponentManager::Get ## ENTITY_CLASS ## FIRST_COMPONENT ## s() NOEXCEPT \
{ \
return _ ## ENTITY_CLASS ## FIRST_COMPONENT ## s.Data(); \
} \
void ComponentManager::Return ## ENTITY_CLASS ## ComponentsIndex(const uint64 componentsIndex) NOEXCEPT \
{ \
_ ## ENTITY_CLASS ## Entities.Back()->_ComponentsIndex = componentsIndex; \
\
_ ## ENTITY_CLASS ## Entities.EraseAt<false>(componentsIndex); \
_ ## ENTITY_CLASS ## FIRST_COMPONENT ## s.EraseAt<false>(componentsIndex); \
}
/*
* Defines an entity class with with two components.
*/
#define DEFINE_ENTITY_CLASS_WITH_TWO_COMPONENTS(ENTITY_CLASS, FIRST_COMPONENT, SECOND_COMPONENT) \
DynamicArray<Entity *RESTRICT> ComponentManager::_ ## ENTITY_CLASS ## Entities; \
DynamicArray<FIRST_COMPONENT> ComponentManager::_ ## ENTITY_CLASS ## FIRST_COMPONENT ## s; \
DynamicArray<SECOND_COMPONENT> ComponentManager::_ ## ENTITY_CLASS ## SECOND_COMPONENT ## s; \
NO_DISCARD uint64 ComponentManager::GetNew ## ENTITY_CLASS ## ComponentsIndex(Entity *const RESTRICT entity) NOEXCEPT \
{ \
_ ## ENTITY_CLASS ## Entities.Emplace(entity); \
_ ## ENTITY_CLASS ## FIRST_COMPONENT ## s.Emplace(); \
_ ## ENTITY_CLASS ## SECOND_COMPONENT ## s.Emplace(); \
\
return _ ## ENTITY_CLASS ## Entities.LastIndex(); \
} \
RESTRICTED NO_DISCARD DynamicArray<Entity *RESTRICT> *const RESTRICT ComponentManager::Get ## ENTITY_CLASS ## Entities() NOEXCEPT \
{ \
return &_ ## ENTITY_CLASS ## Entities; \
} \
NO_DISCARD uint64 ComponentManager::GetNumberOf ## ENTITY_CLASS ## Components() NOEXCEPT \
{ \
return _ ## ENTITY_CLASS ## Entities.Size(); \
} \
RESTRICTED NO_DISCARD FIRST_COMPONENT *const RESTRICT ComponentManager::Get ## ENTITY_CLASS ## FIRST_COMPONENT ## s() NOEXCEPT \
{ \
return _ ## ENTITY_CLASS ## FIRST_COMPONENT ## s.Data(); \
} \
RESTRICTED NO_DISCARD SECOND_COMPONENT *const RESTRICT ComponentManager::Get ## ENTITY_CLASS ## SECOND_COMPONENT ## s() NOEXCEPT \
{ \
return _ ## ENTITY_CLASS ## SECOND_COMPONENT ## s.Data(); \
} \
void ComponentManager::Return ## ENTITY_CLASS ## ComponentsIndex(const uint64 componentsIndex) NOEXCEPT \
{ \
_ ## ENTITY_CLASS ## Entities.Back()->_ComponentsIndex = componentsIndex; \
\
_ ## ENTITY_CLASS ## Entities.EraseAt<false>(componentsIndex); \
_ ## ENTITY_CLASS ## FIRST_COMPONENT ## s.EraseAt<false>(componentsIndex); \
_ ## ENTITY_CLASS ## SECOND_COMPONENT ## s.EraseAt<false>(componentsIndex); \
}
DEFINE_ENTITY_CLASS_WITH_ONE_COMPONENT(AnimatedModel, AnimatedModelComponent);
DEFINE_ENTITY_CLASS_WITH_ONE_COMPONENT(DistanceTrigger, DistanceTriggerComponent);
DEFINE_ENTITY_CLASS_WITH_ONE_COMPONENT(DynamicModel, DynamicModelComponent);
DEFINE_ENTITY_CLASS_WITH_ONE_COMPONENT(InstancedImpostor, InstancedImpostorComponent);
DEFINE_ENTITY_CLASS_WITH_ONE_COMPONENT(InstancedStaticModel, InstancedStaticModelComponent);
DEFINE_ENTITY_CLASS_WITH_ONE_COMPONENT(Light, LightComponent);
DEFINE_ENTITY_CLASS_WITH_TWO_COMPONENTS(ParticleSystem, ParticleSystemComponent, ParticleSystemRenderComponent);
DEFINE_ENTITY_CLASS_WITH_ONE_COMPONENT(Sound, SoundComponent);
DEFINE_ENTITY_CLASS_WITH_ONE_COMPONENT(StaticModel, StaticModelComponent);
DEFINE_ENTITY_CLASS_WITH_TWO_COMPONENTS(Terrain, TerrainGeneralComponent, TerrainRenderComponent);
DEFINE_ENTITY_CLASS_WITH_ONE_COMPONENT(UserInterface, UserInterfaceComponent);
|
a45a8ecbbaaa834550b0a58a8c3f3c2ea89617c6
|
7ce91a98ae434dbb48099699b0b6bcaa705ba693
|
/TestModule/HK1/Users/20110224/bai1.cpp
|
809ab6e1d480808be18420a17e2a24ea2ab64343
|
[] |
no_license
|
ngthvan1612/OJCore
|
ea2e33c1310c71f9375f7c5cd0a7944b53a1d6bd
|
3ec0752a56c6335967e5bb4c0617f876caabecd8
|
refs/heads/master
| 2023-04-25T19:41:17.050412
| 2021-05-12T05:29:40
| 2021-05-12T05:29:40
| 357,612,534
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 700
|
cpp
|
bai1.cpp
|
#include <stdio.h>
void Play(int &na, int &nb, int x, int y) {
if (x == 1) { //keo
if (y == 1) { //keo
na++;
nb++;
}
else if (y == 2) { //bua
nb += 3;
}
else { //bao
na += 3;
}
}
else if (x == 2) { //bua
if (y == 1) { //keo
na += 3;
}
else if (y == 2) {
na++;
nb++;
}
else { //bao
nb += 3;
}
}
else { //bao
if (y == 1) { //keo
nb += 3;
}
else if (y == 2) { //bua
na += 3;
}
else {
na++;
nb++;
}
}
}
int main() {
int x, y, z, t, u, v;
scanf("%d%d%d%d%d%d", &x, &y, &z, &t, &u, &v);
int a, b, c;
a = 0;
b = 0;
c = 0;
Play(a, b, x, y);
Play(a, c, z, t);
Play(b, c, u, v);
printf("%d %d %d", a, b,c);
return 0;
}
|
c7565afb33eca872af28bf5a722233bde06b9c98
|
74e6964ea88ed259f03ca13b5289e94105139fb6
|
/Chapter 4/Section 4.2.cpp
|
90594ca60b890ca5d64e470995ac744da6a20cb2
|
[] |
no_license
|
fwhidje/C-primer-5th-ed.
|
5ef842a18b84b94086befd67ef4ecb7ef47e4970
|
11e4a9b35bea3f9938558b16f2eb0bed7830de38
|
refs/heads/master
| 2020-06-12T20:05:10.318600
| 2017-01-19T20:45:15
| 2017-01-19T20:45:15
| 75,756,766
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 667
|
cpp
|
Section 4.2.cpp
|
#include <iostream>
using namespace::std;
//Exercise 4.4
void eval() {
cout << 12 / 3 * 4 + 5 * 15 + 24 % 4 / 2 << endl;
cout << ((12 / 3) * 4) + (5 * 15) + ((24 % 4) / 2) << endl;
}
//Exercise 4.6
bool is_odd(const int i) {
return i % 2;
}
//Exercise 4.6 - variation
bool is_odd2(int i) {
return (i & 1);
}
//Exercise 4.7
void overflow() {
unsigned short i = 65535;
short j = i;
cout << "unsigned short i: " << i << ", short j = i: " << j << endl;
unsigned short k = i + 1;
cout << "unsigned short i: " << i << ", unsigned short k = i + 1: " << k << endl;
}
int main() {
eval();
cout << is_odd2(3);
overflow();
}
|
6e7abe6b1abf5d98d8084e32067e7faab5932f8c
|
ddf89aad4e4f30ccc4c0436c9dd13c9360949240
|
/atcoder/agc034_b.cpp
|
a927f00ba4b39ae0361dc45ca5e5780561148032
|
[
"MIT"
] |
permissive
|
k124k3n/competitive-programming-answer
|
99a7b5b9397915f0bad59a40fcec5f7833fbc719
|
69b7dbdc081cdb094cb110a72bc0c9242d3d344d
|
refs/heads/master
| 2022-03-29T23:06:57.287336
| 2019-12-28T10:14:54
| 2019-12-28T10:14:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 538
|
cpp
|
agc034_b.cpp
|
#include <bits/stdc++.h>
using namespace std;
int main(){
string str;
getline(cin, str);
int count = 0, count_ = -1;
bool rep = false;
size_t index = 0;
while (true){
if(count == 0){
break;
}
count_ = 0;
while (true) {
index = str.find("ABC", index);
if (index == string::npos) break;
str.replace(index, 3, "BCA");
index += 3;
count++;
count_++;
}
}
cout << count << '\n';
}
|
4b98e131f60c1e46c512d9b4ec98613736c5886f
|
3b856314443c48096dfca831a440eb5fae1be7d3
|
/include/Image/GenericImage.hpp
|
3ab9f9a72e4d824dccfd10403c0c9ef05e6185b1
|
[
"Zlib"
] |
permissive
|
alex-justes/jimlib
|
e489e5814b819b55573fcd3419ca29d55ec5d8d8
|
7622b50e9eb597f1e8109ef845feb5f92b45fd08
|
refs/heads/master
| 2021-01-18T21:08:10.152245
| 2017-08-07T13:46:10
| 2017-08-07T13:46:10
| 43,775,741
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 29,864
|
hpp
|
GenericImage.hpp
|
/*
* jimlib -- generic image and-image algorithms library
* Copyright (C) 2015 Alexey Titov
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors 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 software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* 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 software.
* 3. This notice may not be removed or altered from any source distribution.
*
* Alexey Titov
* alex.justes@gmail.com
* https://github.com/alex-justes/jimlib
*/
/*!
* \file
* \brief GenericImage<PixelType> class specification.
* \author Alexey Titov
* \date September 2015
* \copyright zlib
*
* Full specification of the GenericImage<PixelType> class and underlying iterator.
*/
#ifndef JIMLIB_GENERICIMAGE_HPP
#define JIMLIB_GENERICIMAGE_HPP
#include <cstring>
#include "Utils/CheckTypes.hpp"
#include "Image/GenericPixel.hpp"
/*!
* \brief Class GenericImage<PixelType> provides general-purpose generic interface for storing
* and processing different image types.
*
* The main goal of the GenericImage<PixelType> is to provide generic, fast and as compile-time type safe
* as it could be interface for storing and processing different data which can be represented as
* matrix of N-dimensions vectors.
*
* GenericImage<PixelType> provides dynamicaly allocated storage with static compile-time checks to
* ensure that all operations are type-safe (as much as possible).
*
* It uses no overhead in storing complicated data-types and provides simple iterator-like interface
* for accessing underlying data.
*
* Before speaking about in-memory representation let's define some things:
* 1. Image is a set of Pixels.
* 2. Pixel is a set of the fixed amount of the fixed-sized Plants.
* 3. Plant is a fixed-sized storage for any data-type.
* 4. Size of the Plant in bits should be divisible by 8 (integer amount of bytes).
*
* For example RGB24 pixel has 3 plants: R, G, B, each plant occupies 8 bits.
*
* Those definitions are not limiting you to use it only for image types:
* Consider you need to hold some complicated data in the matrix form, i.e. vectors with N dimensions.
* You can define Plant as a dimension of the vector(dimension could be any type, i.e. double or
* any abstract type), so Pixel would hold the entire vector(N dimensions).
*
* The only restriction is the Size of the Plant. For example if you need less than a byte to hold
* value(i.e. binary image) you need to use the smallest sized plant - 1 byte plant.
*
* All needed memory allocated dynamicaly and in one piece. Images' in-memory representation is linear
* row-based set of pixels. So, provided X and Y as coordinates of some pixel in the Image the desired
* location would be Y * Width * sizeof(Pixel) + X.
*
* The internal representaion of the underlying iterator is simple pointer to some location in the Image memory,
* so using iterators for a linear access shows no overhead.
*
* Random access is a little slower but still pretty fast (just because we need to compute Y * Width * sizeof(Pixel) + X
* every time).
*/
namespace jimlib
{
template<typename Pixel>
class GenericImage
{
public:
typedef Pixel Type; //< Pixel type
static const uint8_t Plants = Pixel::Plants; //< Amount of plants
static const uint32_t SizeOfPlant = sizeof(typename Pixel::Type); //< Size of Plant in bytes
static const uint32_t SizeOfPixel = Pixel::Plants * sizeof(typename Pixel::Type); //< Size of Pixel in bytes
/*!
* Empty default constructor. Checks that Pixel is derived from GenericPixel (static_assert).
*/
GenericImage();
/*!
* Destructor. Frees allocated storage.
*/
virtual ~GenericImage();
/*!
* \return Width of the image.
*/
uint32_t GetWidth() const;
/*!
* \return Height of the image.
*/
uint32_t GetHeight() const;
/*!
* \return Offset in bytes between two successive rows
*/
uint32_t GetOffset() const;
size_t GetSize() const;
/*!
* Get Pixel[Plant] value located at the (x, y)
* \param[in] x X Coordinate
* \param[in] y Y Coordinate
* \param[in] Plant Image plant
* \return Value of the Pixel[Plant]
*/
const typename Pixel::Type &GetPixel(uint32_t x, uint32_t y, uint8_t Plant) const;
typename Pixel::Type &GetPixel(uint32_t x, uint32_t y, uint8_t Plant);
/*!
* Set Pixel[Plant] value located at the (x, y)
* \param[in] x X Coordinate
* \param[in] y Y Coordinate
* \param[in] Plant Image plant
* \param[in] Value Value to be set
*/
void SetPixel(uint32_t x, uint32_t y, uint8_t Plant, const typename Pixel::Type &Value);
/*!
* Get Pixel value located at the (x, y)
* \param[in] x X Coordinate
* \param[in] y Y Coordinate
* \return Pixel value
*/
const Pixel GetPixel(uint32_t x, uint32_t y) const;
/*!
* Get pointer to Pixel located at the (x, y)
* \param[in] x X Coordinate
* \param[in] y Y Coordinate
* \return pointer to Pixel
*/
typename Pixel::Type * GetPixel(uint32_t x, uint32_t y);
/*!
* Set Pixel value located at the (x, y)
* \param[in] x X Coordinate
* \param[in] y Y Coordinate
* \param[in] Value Value to be set
*/
void SetPixel(uint32_t x, uint32_t y, const Pixel &Value);
/*!
* Allocate buffer for the WidthXHeight Image.
* \param[in] Width Witdh of the Image
* \param[in] Height Height of the Image
*/
void Create(uint32_t Width, uint32_t Height);
/*!
* Allocate buffer for the WidthXHeight Image and fill it with Value.
* \param[in] Width Witdh of the Image
* \param[in] Height Height of the Image
* \param[in] Value Value to be set
*/
void Create(uint32_t Width, uint32_t Height, const Pixel &Value);
/*!
* Resize Dst Image to the current Width and Height, then copy internal buffer to it.
* \param[in] Dst Destination Image.
* \warning It is unsafe! Use it only it specific bottlenecks, wheng you are sure,
* that types are same! (i.e. BinaryImage should contain only 1 or 0 pixels, and GrayImage - 0..255,
* but underlying type is Mono8, so it possible to copy one to another with this function!).
*/
void CopyTo_Unsafe(GenericImage<Pixel> &Dst) const;
/*!
* Resize Current Image to the Src Width and Height, then copy it to own internal buffer.
* \param[in] Src Source Image.
* \warning It is unsafe! Use it only it specific bottlenecks, wheng you are sure,
* that types are same! (i.e. BinaryImage should contain only 1 or 0 pixels, and GrayImage - 0..255,
* but underlying type is Mono8, so it possible to copy one to another with this function!).
*/
void CopyFrom_Unsafe(const GenericImage<Pixel> &Src);
class const_oterator;
/*!
* Provides iterator-like interface for Image data.
*/
class iterator
{
friend class const_iterator;
public:
/*!
* Empty default constructor.
*/
iterator();
/*!
* Create iterator and set its' position.
* \param[in] pRawData Pointer to internal buffer.
* \param[in] idx Offset from the start of the buffer.
*/
iterator(uint8_t *pRawData, uint32_t idx);
/*!
* Create iterator from another iterator.
* \paran[in] it another iterator
*/
iterator(const iterator &it);
/*!
* Move to next pixel.
*/
iterator &operator++();
/*!
* Move to +offset pixels from current position.
* \param[in] offset offset from from current position.
*/
void operator+=(uint32_t offset);
/*!
* Move to -offset pixels from current position.
* \param[in] offset offset from from current position.
*/
void operator-=(uint32_t offset);
/*!
* Move to previous pixel.
*/
iterator &operator--();
/*!
* Get pointer to the current position in the internal buffer.
* \return Pointer to the current position in the internal buffer.
*/
typename Pixel::Type *operator*();
/*!
* Get value of the current Pixel[Plant].
* \return value of the current Pixel[Plant].
*/
typename Pixel::Type &operator[](int8_t Plant);
/*!
* Check if iterators are equal.
* \return true if equal, false otherwise.
*/
bool operator==(const iterator &it) const;
/*!
* Check if iterators are not equal.
* \return true if not equal, false otherwise.
*/
bool operator!=(const iterator &it) const;
/*!
* Check if iterators are equal.
* \return true if equal, false otherwise.
*/
bool operator==(const typename GenericImage<Pixel>::const_iterator &it) const;
/*!
* Check if iterators are not equal.
* \return true if not equal, false otherwise.
*/
bool operator!=(const typename GenericImage<Pixel>::const_iterator &it) const;
static const uint32_t SizeOfPixel = Pixel::SizeOfPixel; //< Size of the underlying Pixel
private:
uint8_t *m_RawData; //< Pointer to the current position in the internal buffer.
};
/*!
* Provides iterator-like interface for Image data.
*/
class const_iterator
{
friend class iterator;
public:
/*!
* Empty default constructor.
*/
const_iterator();
/*!
* Create iterator and set its' position.
* \param[in] pRawData Pointer to internal buffer.
* \param[in] idx Offset from the start of the buffer.
*/
const_iterator(uint8_t *pRawData, uint32_t idx);
/*!
* Create iterator from another iterator.
* \paran[in] it another iterator
*/
const_iterator(const iterator &it);
/*!
* Create iterator from another iterator.
* \paran[in] it another iterator
*/
const_iterator(const const_iterator &it);
/*!
* Move to next pixel.
*/
const_iterator &operator++();
/*!
* Move to +offset pixels from current position.
* \param[in] offset offset from from current position.
*/
void operator+=(uint32_t offset);
/*!
* Move to -offset pixels from current position.
* \param[in] offset offset from from current position.
*/
void operator-=(uint32_t offset);
/*!
* Move to previous pixel.
*/
const_iterator &operator--();
/*!
* Get pointer to the current position in the internal buffer.
* \return Pointer to the current position in the internal buffer.
*/
const typename Pixel::Type *operator*() const;
/*!
* Get value of the current Pixel[Plant].
* \return value of the current Pixel[Plant].
*/
const typename Pixel::Type &operator[](int8_t Plant) const;
/*!
* Check if iterators are equal.
* \return true if equal, false otherwise.
*/
bool operator==(const const_iterator &it) const;
/*!
* Check if iterators are not equal.
* \return true if not equal, false otherwise.
*/
bool operator!=(const const_iterator &it) const;
/*!
* Check if iterators are equal.
* \return true if equal, false otherwise.
*/
bool operator==(const iterator &it) const;
/*!
* Check if iterators are not equal.
* \return true if not equal, false otherwise.
*/
bool operator!=(const iterator &it) const;
static const uint32_t SizeOfPixel = Pixel::SizeOfPixel; //< Size of the underlying Pixel
private:
const uint8_t *m_RawData; //< Pointer to the current position in the internal buffer.
};
/*!
* Get iterator pointed to the begining of the Image.
* \return iterator pointed to the begining of the Image.
*/
iterator begin();
/*!
* Get iterator pointed to the end of the Image.
* \return iterator pointed to the end of the Image.
*/
iterator end();
/*!
* Get iterator pointed to the begining of the specified row.
* \param[in] Row Row of the Image.
* \return iterator pointed to the begining of the specified row.
*/
iterator GetRow(uint32_t Row);
/*!
* Get iterator pointed to the (column, row).
* \param[in] Col Column of the Image.
* \param[in] Row Row of the Image.
* \return iterator pointed to the (column, row).
*/
iterator GetColRow(uint32_t Col, uint32_t Row);
/*!
* Get const_iterator pointed to the begining of the Image.
* \return iterator pointed to the begining of the Image.
*/
const_iterator begin() const;
/*!
* Get const_iterator pointed to the end of the Image.
* \return iterator pointed to the end of the Image.
*/
const_iterator end() const;
/*!
* Get const_iterator pointed to the begining of the specified row.
* \param[in] Row Row of the Image.
* \return iterator pointed to the begining of the specified row.
*/
const_iterator GetRow(uint32_t Row) const;
/*!
* Get const_iterator pointed to the (column, row).
* \param[in] Col Column of the Image.
* \param[in] Row Row of the Image.
* \return iterator pointed to the (column, row).
*/
const_iterator GetColRow(uint32_t Col, uint32_t Row) const;
protected:
/*!
* Resize Dst Image to the current Width and Height, then copy internal buffer to it.
* \param[in] Dst Destination Image.
* \attention It is protected so that derived classes can check types.
*/
void CopyToInternal(GenericImage<Pixel> &Dst) const;
/*!
* Resize Current Image to the Src Width and Height, then copy it to own internal buffer.
* \param[in] Src Source Image.
* \attention It is protected so that derived classes can check types.
*/
void CopyFromInternal(const GenericImage<Pixel> &Src);
/*!
* Allocate buffer for the WidthXHeight Image. Internal function.
* \todo If new buffer size is less-or-equal to current buffer size, don't call DeleteRawData()
* \param[in] Width Witdh of the Image
* \param[in] Height Height of the Image
*/
void AllocateRawData(uint32_t Width, uint32_t Height);
/*!
* Frees allocated buffer.
*/
void DeleteRawData();
uint32_t m_Width; //< Current Width
uint32_t m_Height; //< Current Height
uint32_t m_BufSize; //< Current Buffer size
uint32_t m_Offset; //< Offset to the next row
uint8_t *m_RawData; //< Image buffer
};
// =======================================================
template<typename Pixel>
GenericImage<Pixel>::GenericImage()
: m_Width(0),
m_Height(0),
m_BufSize(0),
m_Offset(0),
m_RawData(nullptr)
{
static_assert(CheckTypes<GenericPixel<typename Pixel::Type, Pixel::Plants>,
typename Pixel::ParentType>::areSame,
"Type is not GenericPixel<T, uint8_t Plants>!");
}
template<typename Pixel>
GenericImage<Pixel>::~GenericImage()
{
if (m_RawData)
{
delete[] m_RawData;
}
}
template<typename Pixel>
void GenericImage<Pixel>::Create(uint32_t Width, uint32_t Height)
{
AllocateRawData(Width, Height);
}
template<typename Pixel>
void GenericImage<Pixel>::Create(uint32_t Width, uint32_t Height, const Pixel &Value)
{
Create(Width, Height);
typename GenericImage<Pixel>::iterator it = begin();
for (; it != end(); ++it)
{
memcpy(*it, Value.m_Buffer, Value.SizeOfPixel);
}
}
template<typename Pixel>
void GenericImage<Pixel>::CopyToInternal(GenericImage<Pixel> &Dst) const
{
Dst.Create(GetWidth(), GetHeight());
memcpy(Dst.m_RawData, m_RawData, m_BufSize);
}
template<typename Pixel>
void GenericImage<Pixel>::CopyFromInternal(const GenericImage<Pixel> &Src)
{
Create(Src.GetWidth(), Src.GetHeight());
memcpy(m_RawData, Src.m_RawData, m_BufSize);
}
template<typename Pixel>
void GenericImage<Pixel>::CopyTo_Unsafe(GenericImage<Pixel> &Dst) const
{
Dst.Create(GetWidth(), GetHeight());
memcpy(Dst.m_RawData, m_RawData, m_BufSize);
}
template<typename Pixel>
void GenericImage<Pixel>::CopyFrom_Unsafe(const GenericImage<Pixel> &Src)
{
Create(Src.GetWidth(), Src.GetHeight());
memcpy(m_RawData, Src.m_RawData, m_BufSize);
}
template<typename Pixel>
void GenericImage<Pixel>::AllocateRawData(uint32_t Width, uint32_t Height)
{
uint32_t DataSize = Width * Height * Plants * SizeOfPlant;
m_Width = Width;
m_Height = Height;
m_Offset = m_Width * SizeOfPixel;
if (DataSize != m_BufSize)
{
DeleteRawData();
m_BufSize = DataSize;
m_RawData = new uint8_t[m_BufSize];
}
}
template<typename Pixel>
void GenericImage<Pixel>::DeleteRawData()
{
if (m_RawData)
{
delete[] m_RawData;
m_RawData = nullptr;
}
}
template<typename Pixel>
unsigned int GenericImage<Pixel>::GetWidth() const
{
return m_Width;
}
template<typename Pixel>
unsigned int GenericImage<Pixel>::GetHeight() const
{
return m_Height;
}
template<typename Pixel>
unsigned int GenericImage<Pixel>::GetOffset() const
{
return m_Offset;
}
template<typename Pixel>
size_t GenericImage<Pixel>::GetSize() const
{
return m_BufSize;
}
template<typename Pixel>
const typename Pixel::Type &GenericImage<Pixel>::GetPixel(uint32_t x, uint32_t y, uint8_t Plant) const
{
assert(Plant < Plants);
return *(reinterpret_cast<typename Pixel::Type *>(m_RawData + y * m_Offset + x * SizeOfPixel) + Plant);
}
template<typename Pixel>
typename Pixel::Type &GenericImage<Pixel>::GetPixel(uint32_t x, uint32_t y, uint8_t Plant)
{
assert(Plant < Plants);
return *(reinterpret_cast<typename Pixel::Type *>(m_RawData + y * m_Offset + x * SizeOfPixel) + Plant);
}
template<typename Pixel>
const Pixel GenericImage<Pixel>::GetPixel(uint32_t x, uint32_t y) const
{
Pixel pix;
typename GenericImage<Pixel>::const_iterator it = GetColRow(x, y);
memcpy(pix.m_Buffer, *it, pix.SizeOfPixel);
return pix;
}
template<typename Pixel>
typename Pixel::Type * GenericImage<Pixel>::GetPixel(uint32_t x, uint32_t y)
{
return (*GetColRow(x,y));
}
template<typename Pixel>
void GenericImage<Pixel>::SetPixel(uint32_t x, uint32_t y, uint8_t Plant, const typename Pixel::Type &Value)
{
assert(Plant < Plants);
*(reinterpret_cast<typename Pixel::Type *>(m_RawData + y * m_Offset + x * SizeOfPixel) + Plant) = Value;
}
template<typename Pixel>
void GenericImage<Pixel>::SetPixel(uint32_t x, uint32_t y, const Pixel &Value)
{
typename GenericImage<Pixel>::iterator it = GetColRow(x, y);
memcpy(*it, Value.m_Buffer, Value.SizeOfPixel);
}
template<typename Pixel>
typename GenericImage<Pixel>::iterator GenericImage<Pixel>::begin()
{
GenericImage<Pixel>::iterator it(m_RawData, 0);
return it;
}
template<typename Pixel>
typename GenericImage<Pixel>::iterator GenericImage<Pixel>::end()
{
GenericImage<Pixel>::iterator it(m_RawData, m_BufSize);
return it;
}
template<typename Pixel>
typename GenericImage<Pixel>::iterator GenericImage<Pixel>::GetRow(uint32_t Row)
{
GenericImage<Pixel>::iterator it(m_RawData, m_Offset * Row);
return it;
}
template<typename Pixel>
typename GenericImage<Pixel>::iterator GenericImage<Pixel>::GetColRow(uint32_t Col, uint32_t Row)
{
GenericImage<Pixel>::iterator it(m_RawData, m_Offset * Row + SizeOfPixel * Col);
return it;
}
template<typename Pixel>
typename GenericImage<Pixel>::const_iterator GenericImage<Pixel>::begin() const
{
GenericImage<Pixel>::const_iterator it(m_RawData, 0);
return it;
}
template<typename Pixel>
typename GenericImage<Pixel>::const_iterator GenericImage<Pixel>::end() const
{
GenericImage<Pixel>::const_iterator it(m_RawData, m_BufSize);
return it;
}
template<typename Pixel>
typename GenericImage<Pixel>::const_iterator GenericImage<Pixel>::GetRow(uint32_t Row) const
{
GenericImage<Pixel>::const_iterator it(m_RawData, m_Offset * Row);
return it;
}
template<typename Pixel>
typename GenericImage<Pixel>::const_iterator GenericImage<Pixel>::GetColRow(uint32_t Col, uint32_t Row) const
{
GenericImage<Pixel>::const_iterator it(m_RawData, m_Offset * Row + SizeOfPixel * Col);
return it;
}
template<typename Pixel>
GenericImage<Pixel>::iterator::iterator()
: m_RawData(nullptr)
{
}
template<typename Pixel>
GenericImage<Pixel>::iterator::iterator(uint8_t *pRawData, uint32_t idx)
: m_RawData(pRawData)
{
assert(m_RawData != nullptr);
m_RawData += idx;
}
template<typename Pixel>
GenericImage<Pixel>::iterator::iterator(const iterator &it)
: m_RawData(it.m_RawData)
{
assert(m_RawData != nullptr);
}
template<typename Pixel>
typename GenericImage<Pixel>::iterator &GenericImage<Pixel>::iterator::operator++()
{
assert(m_RawData != nullptr);
m_RawData += SizeOfPixel;
return (*this);
}
template<typename Pixel>
typename GenericImage<Pixel>::iterator &GenericImage<Pixel>::iterator::operator--()
{
assert(m_RawData != nullptr);
m_RawData -= SizeOfPixel;
return (*this);
}
template<typename Pixel>
void GenericImage<Pixel>::iterator::operator+=(uint32_t offset)
{
assert(m_RawData != nullptr);
m_RawData += offset * SizeOfPixel;
}
template<typename Pixel>
void GenericImage<Pixel>::iterator::operator-=(uint32_t offset)
{
assert(m_RawData != nullptr);
m_RawData -= offset * SizeOfPixel;
}
template<typename Pixel>
bool GenericImage<Pixel>::iterator::operator==(const typename GenericImage<Pixel>::iterator &it) const
{
return (this->m_RawData == it.m_RawData);
}
template<typename Pixel>
bool GenericImage<Pixel>::iterator::operator!=(const typename GenericImage<Pixel>::iterator &it) const
{
return (this->m_RawData != it.m_RawData);
}
template<typename Pixel>
bool GenericImage<Pixel>::iterator::operator==(const typename GenericImage<Pixel>::const_iterator &it) const
{
return (this->m_RawData == it.m_RawData);
}
template<typename Pixel>
bool GenericImage<Pixel>::iterator::operator!=(const typename GenericImage<Pixel>::const_iterator &it) const
{
return (this->m_RawData != it.m_RawData);
}
template<typename Pixel>
typename Pixel::Type *GenericImage<Pixel>::iterator::operator*()
{
return reinterpret_cast<typename Pixel::Type *>(m_RawData);
}
template<typename Pixel>
typename Pixel::Type &GenericImage<Pixel>::iterator::operator[](int8_t Plant)
{
assert(Plant < Pixel::Plants);
assert(m_RawData != nullptr);
return reinterpret_cast<typename Pixel::Type *>(m_RawData)[Plant];
}
template<typename Pixel>
GenericImage<Pixel>::const_iterator::const_iterator()
: m_RawData(nullptr)
{
}
template<typename Pixel>
GenericImage<Pixel>::const_iterator::const_iterator(uint8_t *pRawData, uint32_t idx)
: m_RawData(pRawData)
{
assert(m_RawData != nullptr);
m_RawData += idx;
}
template<typename Pixel>
GenericImage<Pixel>::const_iterator::const_iterator(const const_iterator &it)
: m_RawData(it.m_RawData)
{
assert(m_RawData != nullptr);
}
template<typename Pixel>
GenericImage<Pixel>::const_iterator::const_iterator(const iterator &it)
: m_RawData(it.m_RawData)
{
assert(m_RawData != nullptr);
}
template<typename Pixel>
typename GenericImage<Pixel>::const_iterator &GenericImage<Pixel>::const_iterator::operator++()
{
assert(m_RawData != nullptr);
m_RawData += SizeOfPixel;
return (*this);
}
template<typename Pixel>
typename GenericImage<Pixel>::const_iterator &GenericImage<Pixel>::const_iterator::operator--()
{
assert(m_RawData != nullptr);
m_RawData -= SizeOfPixel;
return (*this);
}
template<typename Pixel>
void GenericImage<Pixel>::const_iterator::operator+=(uint32_t offset)
{
assert(m_RawData != nullptr);
m_RawData += offset * SizeOfPixel;
}
template<typename Pixel>
void GenericImage<Pixel>::const_iterator::operator-=(uint32_t offset)
{
assert(m_RawData != nullptr);
m_RawData -= offset * SizeOfPixel;
}
template<typename Pixel>
bool GenericImage<Pixel>::const_iterator::operator==(const typename GenericImage<Pixel>::const_iterator &it) const
{
return (this->m_RawData == it.m_RawData);
}
template<typename Pixel>
bool GenericImage<Pixel>::const_iterator::operator!=(const typename GenericImage<Pixel>::const_iterator &it) const
{
return (this->m_RawData != it.m_RawData);
}
template<typename Pixel>
bool GenericImage<Pixel>::const_iterator::operator==(const typename GenericImage<Pixel>::iterator &it) const
{
return (this->m_RawData == it.m_RawData);
}
template<typename Pixel>
bool GenericImage<Pixel>::const_iterator::operator!=(const typename GenericImage<Pixel>::iterator &it) const
{
return (this->m_RawData != it.m_RawData);
}
template<typename Pixel>
const typename Pixel::Type *GenericImage<Pixel>::const_iterator::operator*() const
{
return reinterpret_cast<const typename Pixel::Type *>(m_RawData);
}
template<typename Pixel>
const typename Pixel::Type &GenericImage<Pixel>::const_iterator::operator[](int8_t Plant) const
{
assert(Plant < Pixel::Plants);
assert(m_RawData != nullptr);
return (reinterpret_cast<const typename Pixel::Type *>(m_RawData)[Plant]);
}
};
#endif //JIMLIB_GENERICIMAGE_HPP
|
e8133eac333323f1633d7e5336bb2c4546259a67
|
606688234266e08c18d44cd4826f16afa39f9eb8
|
/tpls/staq/libs/mockturtle/views/fanout_view.hpp
|
454acb76b165ff3928e9f2a2f8d67ccb794620e7
|
[
"BSD-3-Clause",
"EPL-1.0",
"BSL-1.0",
"Apache-2.0",
"BSD-2-Clause",
"MPL-2.0",
"LicenseRef-scancode-generic-export-compliance",
"MIT"
] |
permissive
|
eclipse/xacc
|
f285f2a20d88fbc4c8f7f1fc14f86bf170ae59e6
|
d1edaa7ae53edc7e335f46d33160f93d6020aaa3
|
refs/heads/master
| 2023-09-01T12:36:22.324158
| 2023-08-01T21:44:29
| 2023-08-01T21:44:29
| 104,096,218
| 159
| 125
|
BSD-3-Clause
| 2023-08-25T04:55:34
| 2017-09-19T15:56:59
|
C++
|
UTF-8
|
C++
| false
| false
| 4,903
|
hpp
|
fanout_view.hpp
|
/* mockturtle: C++ logic network library
* Copyright (C) 2018-2019 EPFL
*
* 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.
*/
/*!
\file fanout_view.hpp
\brief Implements fanout for a network
\author Heinz Riener
*/
#pragma once
#include <cstdint>
#include <vector>
#include "../traits.hpp"
#include "../networks/detail/foreach.hpp"
#include "../utils/node_map.hpp"
#include "immutable_view.hpp"
namespace mockturtle {
/*! \brief Implements `foreach_fanout` methods for networks.
*
* This view computes the fanout of each node of the network.
* It implements the network interface method `foreach_fanout`. The
* fanout are computed at construction and can be recomputed by
* calling the `update_fanout` method.
*
* **Required network functions:**
* - `foreach_node`
* - `foreach_fanin`
*
*/
template <typename Ntk, bool has_fanout_interface = has_foreach_fanout_v<Ntk>>
class fanout_view {};
template <typename Ntk>
class fanout_view<Ntk, true> : public Ntk {
public:
fanout_view(Ntk const& ntk) : Ntk(ntk) {}
};
template <typename Ntk>
class fanout_view<Ntk, false> : public Ntk {
public:
using storage = typename Ntk::storage;
using node = typename Ntk::node;
using signal = typename Ntk::signal;
fanout_view(Ntk const& ntk) : Ntk(ntk), _fanout(ntk) {
static_assert(is_network_type_v<Ntk>, "Ntk is not a network type");
static_assert(has_foreach_node_v<Ntk>,
"Ntk does not implement the foreach_node method");
static_assert(has_foreach_fanin_v<Ntk>,
"Ntk does not implement the foreach_fanin method");
update_fanout();
}
template <typename Fn>
void foreach_fanout(node const& n, Fn&& fn) const {
assert(n < this->size());
detail::foreach_element(_fanout[n].begin(), _fanout[n].end(), fn);
}
void update_fanout() { compute_fanout(); }
void resize_fanout() { _fanout.resize(); }
std::vector<node> fanout(node const& n) const /* deprecated */
{
return _fanout[n];
}
void set_fanout(node const& n, std::vector<node> const& fanout) {
_fanout[n] = fanout;
}
void add_fanout(node const& n, node const& p) {
_fanout[n].emplace_back(p);
}
void remove_fanout(node const& n, node const& p) {
auto& f = _fanout[n];
f.erase(std::remove(f.begin(), f.end(), p), f.end());
}
void substitute_node_of_parents(std::vector<node> const& parents,
node const& old_node,
signal const& new_signal) /* deprecated */
{
Ntk::substitute_node_of_parents(parents, old_node, new_signal);
std::vector<node> old_node_fanout = _fanout[old_node];
std::sort(old_node_fanout.begin(), old_node_fanout.end());
std::vector<node> parents_copy(parents);
std::sort(parents_copy.begin(), parents_copy.end());
_fanout[old_node] = {};
std::vector<node> intersection;
std::set_intersection(parents_copy.begin(), parents_copy.end(),
old_node_fanout.begin(), old_node_fanout.end(),
std::back_inserter(intersection));
resize_fanout();
set_fanout(this->get_node(new_signal), intersection);
}
private:
void compute_fanout() {
_fanout.reset();
this->foreach_gate([&](auto const& n) {
this->foreach_fanin(n, [&](auto const& c) {
auto& fanout = _fanout[c];
if (std::find(fanout.begin(), fanout.end(), n) ==
fanout.end()) {
fanout.push_back(n);
}
});
});
}
node_map<std::vector<node>, Ntk> _fanout;
};
template <class T>
fanout_view(T const&)->fanout_view<T>;
} // namespace mockturtle
|
2b02761795becc3bf2fd411a95d3dc2b46024ce2
|
999ad5439026ee8481f30f4cdf3a4a623467a4f3
|
/nebula2/code/mangalore/ui/window.cc
|
beb9d82325c15967472cd80a19bc14ade3404d48
|
[] |
no_license
|
TalonBraveInfo/mirror-nd2
|
056a6b9b16ab15035ab254d1400700a66ee29423
|
5377d038124679ca936e5486a881f639e38895da
|
refs/heads/main
| 2023-03-17T22:52:43.865612
| 2021-03-15T09:51:17
| 2021-03-15T09:51:17
| 347,916,033
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,120
|
cc
|
window.cc
|
//------------------------------------------------------------------------------
// ui/window.cc
// (C) 2005 Radon Labs GmbH
//------------------------------------------------------------------------------
#include "ui/window.h"
#include "ui/server.h"
#include "ui/event.h"
namespace UI
{
ImplementRtti(UI::Window, Foundation::RefCounted);
ImplementFactory(UI::Window);
//------------------------------------------------------------------------------
/**
*/
Window::Window() :
isOpen(false),
closedFromEventHandler(true)
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
Window::~Window()
{
n_assert(!this->IsOpen());
}
//------------------------------------------------------------------------------
/**
This method can be used before Open() to preload the graphics resources
required by the window.
*/
void
Window::PreloadResource()
{
n_assert(!this->gfxResource.isvalid());
this->gfxResource = Graphics::Resource::Create();
this->gfxResource->SetName(this->resName);
this->gfxResource->Load();
}
//------------------------------------------------------------------------------
/**
Opens the window. This will register the window with the
UI::Server, make the window visible and start to process UI
messages.
*/
void
Window::Open()
{
n_assert(!this->IsOpen());
n_assert(this->resName.IsValid());
this->isOpen = true;
this->closedFromEventHandler = false;
// create the canvas for the window
this->canvas = Canvas::Create();
this->canvas->SetResourceName(this->resName);
this->canvas->OnCreate(0);
// attach the window to the UI::Server
UI::Server::Instance()->AttachWindow(this);
}
//------------------------------------------------------------------------------
/**
Closes the window. This will make the window invisible, stop processing
UI events and unregister the window from the UI::Server.
*/
void
Window::Close()
{
n_assert(this->IsOpen());
this->isOpen = false;
this->closedFromEventHandler = false;
this->canvas->OnDestroy();
this->canvas = 0;
UI::Server::Instance()->RemoveWindow(this);
}
//------------------------------------------------------------------------------
/**
Use this method if the window is closed from within the event handler.
This will actually close the window after event handling has happened,
so that a valid object is available during the event handling!
*/
void
Window::CloseFromEventHandler()
{
this->closedFromEventHandler = true;
}
//------------------------------------------------------------------------------
/**
This method is called by this window's event handler when an event
should be processed. You can override this method if you are
interested in events emitted by elements in this window.
*/
void
Window::HandleEvent(Event* e)
{
n_assert(e);
n_printf("Window::HandleEvent: %s\n", e->GetEventName().Get());
if (this->extEventHandler.isvalid())
{
this->extEventHandler->HandleEvent(e);
}
}
//------------------------------------------------------------------------------
/**
This method is called per-frame by the UI::Server as long as the
window is open. You may override the method to implement
your own per-frame stuff there.
*/
void
Window::OnFrame()
{
if (this->closedFromEventHandler)
{
this->Close();
}
else if (this->IsOpen())
{
this->canvas->OnFrame();
}
}
//------------------------------------------------------------------------------
/**
This method is called by the UI::Server when the window should
render itself.
*/
void
Window::OnRender()
{
if (this->IsOpen())
{
this->canvas->OnRender();
}
}
//------------------------------------------------------------------------------
/**
Return true if the mouse is within the window.
*/
bool
Window::Inside(const vector2& mousePos)
{
if (this->IsOpen())
{
return this->canvas->Inside(mousePos);
}
else
{
return false;
}
}
} // namespace UI
|
969a9e78099db6e58a05a8497f8cdf880e0d93fc
|
06bed8ad5fd60e5bba6297e9870a264bfa91a71d
|
/tests/logixng/logixngtest.cpp
|
dd9f5af15b516f4f62e4eec486045ac17a9273ba
|
[] |
no_license
|
allenck/DecoderPro_app
|
43aeb9561fe3fe9753684f7d6d76146097d78e88
|
226c7f245aeb6951528d970f773776d50ae2c1dc
|
refs/heads/master
| 2023-05-12T07:36:18.153909
| 2023-05-10T21:17:40
| 2023-05-10T21:17:40
| 61,044,197
| 4
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 34,177
|
cpp
|
logixngtest.cpp
|
#include "logixngtest.h"
#include "instancemanager.h"
#include "assert1.h"
#include "logixng_thread.h"
#include "defaultlogixngmanager.h"
#include "junitappender.h"
#include "defaultconditionalngmanager.h"
#include "junitutil.h"
#include "defaultlogixng.h"
/**
* Test LogixNG
*
* @author Daniel Bergqvist 2018
*/
///*public*/ class LogixNGTest {
//@Test
/*public*/ void LogixNGTest::testContains() {
QSet<LogixNG*> set = QSet<LogixNG*>();
DefaultLogixNG* logixNG1 = (DefaultLogixNG*)((DefaultLogixNGManager*)InstanceManager::getDefault("LogixNG_Manager"))->createLogixNG("A new logix1 for test"); // NOI18N
DefaultLogixNG* logixNG2 = (DefaultLogixNG*)((DefaultLogixNGManager*)InstanceManager::getDefault("LogixNG_Manager"))->createLogixNG("A new logix2 for test"); // NOI18N
LogixNG* logixNG3 = ((DefaultLogixNGManager*)InstanceManager::getDefault("LogixNG_Manager"))->createLogixNG("A new logix3 for test"); // NOI18N
DefaultLogixNG* logixNG4 = (DefaultLogixNG*)((DefaultLogixNGManager*)InstanceManager::getDefault("LogixNG_Manager"))->createLogixNG("A new logix4 for test"); // NOI18N
DefaultLogixNG* logixNG5 = (DefaultLogixNG*)((DefaultLogixNGManager*)InstanceManager::getDefault("LogixNG_Manager"))->createLogixNG("A new logix5 for test"); // NOI18N
set.insert(logixNG1);
set.insert(logixNG3);
set.insert(logixNG5);
Assert::assertTrue("set size = 3", set.size() == 3,__FILE__, __LINE__);
Assert::assertTrue("contains is true", set.contains(logixNG1),__FILE__, __LINE__);
Assert::assertTrue("contains is true", set.contains(logixNG3),__FILE__, __LINE__);
Assert::assertTrue("contains is true", set.contains(logixNG5),__FILE__, __LINE__);
Assert::assertFalse("contains is false", set.contains(logixNG2),__FILE__, __LINE__);
}
//@Test
/*public*/ void LogixNGTest::testSetParent() {
DefaultLogixNG* logixNG = (DefaultLogixNG*)((DefaultLogixNGManager*)InstanceManager::getDefault("LogixNG_Manager"))->createLogixNG("A new logix for test"); // NOI18N
bool hasThrown = false;
try {
logixNG->setParent(nullptr);
} catch (UnsupportedOperationException* e) {
hasThrown = true;
}
Assert::assertTrue("exception thrown", hasThrown, __FILE__, __LINE__);
}
//@Test
/*public*/ void LogixNGTest::testGetParent() {
DefaultLogixNG* logixNG = (DefaultLogixNG*)((DefaultLogixNGManager*)InstanceManager::getDefault("LogixNG_Manager"))->createLogixNG("A new logix for test"); // NOI18N
Assert::assertNull("getParent() returns null", (QObject*)logixNG->getParent(), __FILE__, __LINE__);
}
//@Test
/*public*/ void LogixNGTest::testState() /*throws JmriException*/ {
DefaultLogixNG* logixNG = (DefaultLogixNG*)((DefaultLogixNGManager*)InstanceManager::getDefault("LogixNG_Manager"))->createLogixNG("A new logix for test"); // NOI18N
Assert::assertTrue("getState() returns UNKNOWN", logixNG->getState() == LogixNG::UNKNOWN, __FILE__, __LINE__);
JUnitAppender::assertWarnMessage("Unexpected call to getState in DefaultLogixNG.", __FILE__, __LINE__);
logixNG->setState(LogixNG::INCONSISTENT);
JUnitAppender::assertWarnMessage("Unexpected call to setState in DefaultLogixNG.", __FILE__, __LINE__);
Assert::assertTrue("getState() returns UNKNOWN", logixNG->getState() == LogixNG::UNKNOWN, __FILE__, __LINE__);
JUnitAppender::assertWarnMessage("Unexpected call to getState in DefaultLogixNG.", __FILE__, __LINE__);
}
//@Test
/*public*/ void LogixNGTest::testShortDescription() {
DefaultLogixNG* logixNG = (DefaultLogixNG*)((DefaultLogixNGManager*)InstanceManager::getDefault("LogixNG_Manager"))->createLogixNG("A new logix for test"); // NOI18N
Assert::assertEquals("getShortDescription() returns correct value",
"LogixNG", logixNG->getShortDescription(QLocale()), __FILE__, __LINE__);
}
//@Test
/*public*/ void LogixNGTest::testLongDescription() {
DefaultLogixNG* logixNG = (DefaultLogixNG*)((DefaultLogixNGManager*)InstanceManager::getDefault("LogixNG_Manager"))->createLogixNG("A new logix for test"); // NOI18N
Assert::assertEquals("getLongDescription() returns correct value",
"LogixNG: A new logix for test", logixNG->getLongDescription(QLocale()), __FILE__, __LINE__);
}
//@Test
/*public*/ void LogixNGTest::testGetChild() {
DefaultLogixNG* logixNG = (DefaultLogixNG*)((DefaultLogixNGManager*)InstanceManager::getDefault("LogixNG_Manager"))->createLogixNG("A new logix for test"); // NOI18N
bool hasThrown = false;
try {
logixNG->getChild(0);
} catch (UnsupportedOperationException* e) {
hasThrown = true;
}
Assert::assertTrue("exception thrown", hasThrown, __FILE__, __LINE__);
}
//@Test
/*public*/ void LogixNGTest::testGetChildCount() {
DefaultLogixNG* logixNG = (DefaultLogixNG*)((DefaultLogixNGManager*)InstanceManager::getDefault("LogixNG_Manager"))->createLogixNG("A new logix for test"); // NOI18N
bool hasThrown = false;
try {
logixNG->getChildCount();
} catch (UnsupportedOperationException* e) {
hasThrown = true;
}
Assert::assertTrue("exception thrown", hasThrown, __FILE__, __LINE__);
}
//@Test
/*public*/ void LogixNGTest::testGetCategory() {
DefaultLogixNG* logixNG = (DefaultLogixNG*)((DefaultLogixNGManager*)InstanceManager::getDefault("LogixNG_Manager"))->createLogixNG("A new logix for test"); // NOI18N
bool hasThrown = false;
try {
logixNG->getCategory();
} catch (UnsupportedOperationException* e) {
hasThrown = true;
}
Assert::assertTrue("exception thrown", hasThrown, __FILE__, __LINE__);
}
//@Test
/*public*/ void LogixNGTest::testSwapConditionalNG() {
DefaultLogixNG* logixNG = (DefaultLogixNG*)((DefaultLogixNGManager*)InstanceManager::getDefault("LogixNG_Manager"))->createLogixNG("A new logix for test"); // NOI18N
ConditionalNG* conditionalNG_1 = ((DefaultConditionalNGManager*)InstanceManager::getDefault("ConditionalNG_Manager"))->createConditionalNG(logixNG, "A conditionalNG"); // NOI18N
ConditionalNG* conditionalNG_2 = ((DefaultConditionalNGManager*)InstanceManager::getDefault("ConditionalNG_Manager"))->createConditionalNG(logixNG, "A second conditionalNG"); // NOI18N
ConditionalNG* conditionalNG_3 = ((DefaultConditionalNGManager*)InstanceManager::getDefault("ConditionalNG_Manager"))->createConditionalNG(logixNG, "A third conditionalNG"); // NOI18N
ConditionalNG* conditionalNG_4 = ((DefaultConditionalNGManager*)InstanceManager::getDefault("ConditionalNG_Manager"))->createConditionalNG(logixNG, "A forth conditionalNG"); // NOI18N
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_1 == logixNG->getConditionalNG(0), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_2 == logixNG->getConditionalNG(1), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_3 == logixNG->getConditionalNG(2), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_4 == logixNG->getConditionalNG(3), __FILE__, __LINE__);
logixNG->swapConditionalNG(0, 0);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_1 == logixNG->getConditionalNG(0), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_2 == logixNG->getConditionalNG(1), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_3 == logixNG->getConditionalNG(2), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_4 == logixNG->getConditionalNG(3), __FILE__, __LINE__);
logixNG->swapConditionalNG(1, 0);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_1 == logixNG->getConditionalNG(0), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_2 == logixNG->getConditionalNG(1), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_3 == logixNG->getConditionalNG(2), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_4 == logixNG->getConditionalNG(3), __FILE__, __LINE__);
logixNG->swapConditionalNG(0, 1);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_2 == logixNG->getConditionalNG(0), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_1 == logixNG->getConditionalNG(1), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_3 == logixNG->getConditionalNG(2), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_4 == logixNG->getConditionalNG(3), __FILE__, __LINE__);
logixNG->swapConditionalNG(0, 2);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_3 == logixNG->getConditionalNG(0), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_2 == logixNG->getConditionalNG(1), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_1 == logixNG->getConditionalNG(2), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_4 == logixNG->getConditionalNG(3), __FILE__, __LINE__);
logixNG->swapConditionalNG(2, 3);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_3 == logixNG->getConditionalNG(0), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_2 == logixNG->getConditionalNG(1), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_4 == logixNG->getConditionalNG(2), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_1 == logixNG->getConditionalNG(3), __FILE__, __LINE__);
}
//@Test
/*public*/ void LogixNGTest::testGetConditionalNG() {
DefaultLogixNG* logixNG = (DefaultLogixNG*)((DefaultLogixNGManager*)InstanceManager::getDefault("LogixNG_Manager"))->createLogixNG("A new logix for test"); // NOI18N
ConditionalNG* conditionalNG_1 = ((DefaultConditionalNGManager*)InstanceManager::getDefault("ConditionalNG_Manager"))->createConditionalNG(logixNG, "A conditionalNG"); // NOI18N
ConditionalNG* conditionalNG_2 = ((DefaultConditionalNGManager*)InstanceManager::getDefault("ConditionalNG_Manager"))->createConditionalNG(logixNG, "A second conditionalNG"); // NOI18N
ConditionalNG* conditionalNG_3 = ((DefaultConditionalNGManager*)InstanceManager::getDefault("ConditionalNG_Manager"))->createConditionalNG(logixNG, "A third conditionalNG"); // NOI18N
ConditionalNG* conditionalNG_4 = ((DefaultConditionalNGManager*)InstanceManager::getDefault("ConditionalNG_Manager"))->createConditionalNG(logixNG, "A forth conditionalNG"); // NOI18N
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_1 == logixNG->getConditionalNG(0), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_2 == logixNG->getConditionalNG(1), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_3 == logixNG->getConditionalNG(2), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_4 == logixNG->getConditionalNG(3), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", nullptr == logixNG->getConditionalNG(-1), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", nullptr == logixNG->getConditionalNG(4), __FILE__, __LINE__);
}
// //@Test
// /*public*/ void testAddConditionalNG() {
// LogixNG logixNG = ((DefaultLogixNGManager*)InstanceManager::getDefault("LogixNG_Manager"))->createLogixNG("A new logix for test"); // NOI18N
// ConditionalNG* conditionalNG_1 = ((DefaultConditionalNGManager*)InstanceManager::getDefault("ConditionalNG_Manager"))->createConditionalNG(logixNG, null);
// // Assert::assertTrue("conditionalNG added", logixNG->addConditionalNG(conditionalNG_1));
// ConditionalNG* conditionalNG_2 =
// new DefaultConditionalNG(conditionalNG_1.getSystemName(), null);
// Assert::assertFalse("conditionalNG not added", logixNG->addConditionalNG(conditionalNG_2));
// JUnitAppender::.assertWarnMessage("ConditionalNG* 'IQC:AUTO:0001' has already been added to LogixNG 'IQ:AUTO:0001'");
// ConditionalNG* conditionalNG_3 = ((DefaultConditionalNGManager*)InstanceManager::getDefault("ConditionalNG_Manager"))->createConditionalNG(logixNG, null);
// Assert::assertTrue("conditionalNG added", logixNG->addConditionalNG(conditionalNG_3));
// }
//@Test
/*public*/ void LogixNGTest::testGetConditionalNGByUserName() {
DefaultLogixNG* logixNG = (DefaultLogixNG*)((DefaultLogixNGManager*)InstanceManager::getDefault("LogixNG_Manager"))->createLogixNG("A new logix for test"); // NOI18N
ConditionalNG* conditionalNG_1 = ((DefaultConditionalNGManager*)InstanceManager::getDefault("ConditionalNG_Manager"))->createConditionalNG(logixNG, "Abc"); // NOI18N
ConditionalNG* conditionalNG_2 = ((DefaultConditionalNGManager*)InstanceManager::getDefault("ConditionalNG_Manager"))->createConditionalNG(logixNG, "Def"); // NOI18N
ConditionalNG* conditionalNG_3 = ((DefaultConditionalNGManager*)InstanceManager::getDefault("ConditionalNG_Manager"))->createConditionalNG(logixNG, "Ghi"); // NOI18N
ConditionalNG* conditionalNG_4 = ((DefaultConditionalNGManager*)InstanceManager::getDefault("ConditionalNG_Manager"))->createConditionalNG(logixNG, "Jkl"); // NOI18N
Assert::assertTrue("ConditionalNG* is correct",
conditionalNG_1 == logixNG->getConditionalNGByUserName("Abc"), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct",
conditionalNG_2 == logixNG->getConditionalNGByUserName("Def"), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct",
conditionalNG_3 == logixNG->getConditionalNGByUserName("Ghi"), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct",
conditionalNG_4 == logixNG->getConditionalNGByUserName("Jkl"), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct",
nullptr == logixNG->getConditionalNGByUserName("Non existing bean"), __FILE__, __LINE__);
}
//@Test
/*public*/ void LogixNGTest::testDeleteConditionalNG() {
DefaultLogixNG* logixNG = (DefaultLogixNG*)((DefaultLogixNGManager*)InstanceManager::getDefault("LogixNG_Manager"))->createLogixNG("A new logix for test"); // NOI18N
ConditionalNG* conditionalNG_1 = ((DefaultConditionalNGManager*)InstanceManager::getDefault("ConditionalNG_Manager"))->createConditionalNG(logixNG, "A first conditionalNG"); // NOI18N
ConditionalNG* conditionalNG_2 = ((DefaultConditionalNGManager*)InstanceManager::getDefault("ConditionalNG_Manager"))->createConditionalNG(logixNG, "A second conditionalNG"); // NOI18N
ConditionalNG* conditionalNG_3 = ((DefaultConditionalNGManager*)InstanceManager::getDefault("ConditionalNG_Manager"))->createConditionalNG(logixNG, "A third conditionalNG"); // NOI18N
ConditionalNG* conditionalNG_4 = ((DefaultConditionalNGManager*)InstanceManager::getDefault("ConditionalNG_Manager"))->createConditionalNG(logixNG, "A forth conditionalNG"); // NOI18N
ConditionalNG* conditionalNG_5 = ((DefaultConditionalNGManager*)InstanceManager::getDefault("ConditionalNG_Manager"))->createConditionalNG(logixNG, "A fifth conditionalNG"); // NOI18N
ConditionalNG* conditionalNG_6 = ((DefaultConditionalNGManager*)InstanceManager::getDefault("ConditionalNG_Manager"))->createConditionalNG(logixNG, "A sixth conditionalNG"); // NOI18N
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_1 == logixNG->getConditionalNG(0), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_2 == logixNG->getConditionalNG(1), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_3 == logixNG->getConditionalNG(2), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_4 == logixNG->getConditionalNG(3), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_5 == logixNG->getConditionalNG(4), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_6 == logixNG->getConditionalNG(5), __FILE__, __LINE__);
logixNG->deleteConditionalNG(conditionalNG_1);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_2 == logixNG->getConditionalNG(0), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_3 == logixNG->getConditionalNG(1), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_4 == logixNG->getConditionalNG(2), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_5 == logixNG->getConditionalNG(3), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_6 == logixNG->getConditionalNG(4), __FILE__, __LINE__);
logixNG->deleteConditionalNG(conditionalNG_1);
JUnitAppender::assertErrorMessage("attempt to delete ConditionalNG not in LogixNG: IQC:AUTO:0001", __FILE__, __LINE__);
logixNG->deleteConditionalNG(conditionalNG_6);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_2 == logixNG->getConditionalNG(0), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_3 == logixNG->getConditionalNG(1), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_4 == logixNG->getConditionalNG(2), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_5 == logixNG->getConditionalNG(3), __FILE__, __LINE__);
logixNG->deleteConditionalNG(conditionalNG_3);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_2 == logixNG->getConditionalNG(0), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_4 == logixNG->getConditionalNG(1), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_5 == logixNG->getConditionalNG(2), __FILE__, __LINE__);
logixNG->deleteConditionalNG(conditionalNG_4);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_2 == logixNG->getConditionalNG(0), __FILE__, __LINE__);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_5 == logixNG->getConditionalNG(1), __FILE__, __LINE__);
logixNG->deleteConditionalNG(conditionalNG_2);
Assert::assertTrue("ConditionalNG* is correct", conditionalNG_5 == logixNG->getConditionalNG(0), __FILE__, __LINE__);
logixNG->deleteConditionalNG(conditionalNG_5);
Assert::assertTrue("LogixNG has no more conditionalNGs", 0 == logixNG->getNumConditionalNGs(), __FILE__, __LINE__);
logixNG->deleteConditionalNG(conditionalNG_5);
JUnitAppender::assertErrorMessage("attempt to delete ConditionalNG not in LogixNG: IQC:AUTO:0005", __FILE__, __LINE__);
}
//@Test
/*public*/ void LogixNGTest::testActivateLogixNG() {
DefaultLogixNG* logixNG = (DefaultLogixNG*)((DefaultLogixNGManager*)InstanceManager::getDefault("LogixNG_Manager"))->createLogixNG("A new logix for test"); // NOI18N
MyConditionalNG* conditionalNG_1 = new MyConditionalNG("IQC1", "");
logixNG->addConditionalNG(conditionalNG_1);
conditionalNG_1->setEnabled(false);
MyConditionalNG* conditionalNG_2 = new MyConditionalNG("IQC2", "");
logixNG->addConditionalNG(conditionalNG_2);
conditionalNG_2->setEnabled(true);
MyConditionalNG* conditionalNG_3 = new MyConditionalNG("IQC3", "");
logixNG->addConditionalNG(conditionalNG_3);
conditionalNG_3->setEnabled(false);
if (! logixNG->setParentForAllChildren(new QList<QString>())) throw new RuntimeException();
Assert::assertFalse("conditionalNG_1 is enabled", conditionalNG_1->isEnabled(), __FILE__, __LINE__);
Assert::assertTrue("conditionalNG_2 is enabled", conditionalNG_2->isEnabled(), __FILE__, __LINE__);
Assert::assertFalse("conditionalNG_3 is enabled", conditionalNG_3->isEnabled(), __FILE__, __LINE__);
Assert::assertFalse("listeners for conditionalNG_1 are not registered", conditionalNG_1->listenersAreRegistered, __FILE__, __LINE__);
Assert::assertFalse("listeners for conditionalNG_2 are not registered", conditionalNG_2->listenersAreRegistered, __FILE__, __LINE__);
Assert::assertFalse("listeners for conditionalNG_3 are not registered", conditionalNG_3->listenersAreRegistered, __FILE__, __LINE__);
logixNG->setEnabled(true);
Assert::assertFalse("listeners for conditionalNG_1 are not registered", conditionalNG_1->listenersAreRegistered, __FILE__, __LINE__);
Assert::assertTrue("listeners for conditionalNG_2 are registered", conditionalNG_2->listenersAreRegistered, __FILE__, __LINE__);
Assert::assertFalse("listeners for conditionalNG_3 are not registered", conditionalNG_3->listenersAreRegistered, __FILE__, __LINE__);
// Activate LogixNG multiple times should not be a problem
logixNG->setEnabled(true);
Assert::assertFalse("listeners for conditionalNG_1 are not registered", conditionalNG_1->listenersAreRegistered, __FILE__, __LINE__);
Assert::assertTrue("listeners for conditionalNG_2 are registered", conditionalNG_2->listenersAreRegistered, __FILE__, __LINE__);
Assert::assertFalse("listeners for conditionalNG_3 are not registered", conditionalNG_3->listenersAreRegistered, __FILE__, __LINE__);
logixNG->setEnabled(false);
Assert::assertFalse("listeners for conditionalNG_1 are not registered", conditionalNG_1->listenersAreRegistered, __FILE__, __LINE__);
Assert::assertFalse("listeners for conditionalNG_2 are not registered", conditionalNG_2->listenersAreRegistered, __FILE__, __LINE__);
Assert::assertFalse("listeners for conditionalNG_3 are not registered", conditionalNG_3->listenersAreRegistered, __FILE__, __LINE__);
// DeActivate LogixNG multiple times should not be a problem
logixNG->setEnabled(false);
Assert::assertFalse("listeners for conditionalNG_1 are not registered", conditionalNG_1->listenersAreRegistered, __FILE__, __LINE__);
Assert::assertFalse("listeners for conditionalNG_2 are not registered", conditionalNG_2->listenersAreRegistered, __FILE__, __LINE__);
Assert::assertFalse("listeners for conditionalNG_3 are not registered", conditionalNG_3->listenersAreRegistered, __FILE__, __LINE__);
}
//@Test
/*public*/ void LogixNGTest::testGetConditionalNG_WithoutParameters() {
DefaultLogixNG* logixNG = (DefaultLogixNG*)((DefaultLogixNGManager*)InstanceManager::getDefault("LogixNG_Manager"))->createLogixNG("A new logix for test"); // NOI18N
bool hasThrown = false;
try {
((AbstractBase*)logixNG->bself())->getConditionalNG();
} catch (UnsupportedOperationException* e) {
hasThrown = true;
}
Assert::assertTrue("exception thrown", hasThrown, __FILE__, __LINE__);
}
//@Test
/*public*/ void LogixNGTest::testGetLogixNG() {
DefaultLogixNG* logixNG = (DefaultLogixNG*)((DefaultLogixNGManager*)InstanceManager::getDefault("LogixNG_Manager"))->createLogixNG("A new logix for test"); // NOI18N
Assert::assertTrue("logixNG is correct", logixNG == logixNG->getLogixNG(), __FILE__, __LINE__);
}
//@Test
/*public*/ void LogixNGTest::testGetRoot() {
DefaultLogixNG* logixNG = (DefaultLogixNG*)((DefaultLogixNGManager*)InstanceManager::getDefault("LogixNG_Manager"))->createLogixNG("A new logix for test"); // NOI18N
Assert::assertTrue("root is correct", logixNG == logixNG->getRoot(), __FILE__, __LINE__);
}
#if 0
//@Test
/*public*/ void testPrintTree() {
final String newLine = System.lineSeparator();
StringBuilder expectedResult = new StringBuilder();
expectedResult
.append("LogixNG: A new logix for test").append(newLine)
.append("...ConditionalNG: A conditionalNG").append(newLine)
.append("......! A").append(newLine)
.append(".........Many ::: Use default").append(newLine)
.append("............! A1").append(newLine)
.append("...............If Then Else. Execute on change ::: Use default").append(newLine)
.append("..................? If").append(newLine)
.append(".....................Socket not connected").append(newLine)
.append("..................! Then").append(newLine)
.append(".....................Socket not connected").append(newLine)
.append("..................! Else").append(newLine)
.append(".....................Socket not connected").append(newLine)
.append("............! A2").append(newLine)
.append("...............Socket not connected").append(newLine);
StringWriter writer = new StringWriter();
LogixNG logixNG = ((DefaultLogixNGManager*)InstanceManager::getDefault("LogixNG_Manager"))->createLogixNG("A new logix for test"); // NOI18N
ConditionalNG* conditionalNG = ((DefaultConditionalNGManager*)InstanceManager::getDefault("ConditionalNG_Manager"))->createConditionalNG(logixNG, "A conditionalNG"); // NOI18N
setupInitialConditionalNGTree(conditionalNG);
logixNG->printTree(new PrintWriter(writer), "...", new MutableInt(0));
String resultStr = writer.toString();
/*
System.err.format("=======================================%n");
System.err.format("=======================================%n");
System.err.format("=======================================%n");
System.err.format("=======================================%n");
System.err.format(expectedResult.toString());
System.err.format("=======================================%n");
System.err.format("=======================================%n");
System.err.format(resultStr);
System.err.format("=======================================%n");
System.err.format("=======================================%n");
System.err.format("=======================================%n");
*/
Assert::assertEquals("Strings matches", expectedResult.toString(), resultStr);
}
//@Test
/*public*/ void testBundleClass() {
Assert::assertTrue("bundle is correct", "Test Bundle bb aa cc".equals(Bundle.getMessage("TestBundle", "aa", "bb", "cc")));
Assert::assertTrue("bundle is correct", "Generic".equals(Bundle.getMessage(Locale.US, "SocketTypeGeneric")));
Assert::assertTrue("bundle is correct", "Test Bundle bb aa cc".equals(Bundle.getMessage(Locale.US, "TestBundle", "aa", "bb", "cc")));
}
//@Test
/*public*/ void testCategory() {
Assert::assertTrue("isChangeableByUser is correct", "Item".equals(Category.ITEM.toString()));
Assert::assertTrue("isChangeableByUser is correct", "Common".equals(Category.COMMON.toString()));
Assert::assertTrue("isChangeableByUser is correct", "Other".equals(Category.OTHER.toString()));
}
/*public*/ void setupInitialConditionalNGTree(ConditionalNG* conditionalNG) {
try {
DigitalActionManager digitalActionManager =
InstanceManager::getDefault(DigitalActionManager.class);
FemaleSocket femaleSocket = conditionalNG.getFemaleSocket();
MaleDigitalActionSocket actionManySocket =
InstanceManager::getDefault(DigitalActionManager.class)
.registerAction(new DigitalMany(digitalActionManager.getAutoSystemName(), null));
femaleSocket.connect(actionManySocket);
// femaleSocket.setLock(Base.Lock.HARD_LOCK);
femaleSocket = actionManySocket.getChild(0);
MaleDigitalActionSocket actionIfThenSocket =
InstanceManager::getDefault(DigitalActionManager.class)
.registerAction(new IfThenElse(digitalActionManager.getAutoSystemName(), null));
femaleSocket.connect(actionIfThenSocket);
} catch (SocketAlreadyConnectedException e) {
// This should never be able to happen.
throw new RuntimeException(e);
}
}
//@Test
/*public*/ void testManagers() throws SocketAlreadyConnectedException {
String systemName;
LogixNG logixNG = ((DefaultLogixNGManager*)InstanceManager::getDefault("LogixNG_Manager"))->createLogixNG("A new logix for test"); // NOI18N
ConditionalNG* conditionalNG = ((DefaultConditionalNGManager*)InstanceManager::getDefault("ConditionalNG_Manager"))->createConditionalNG(logixNG, "A conditionalNG"); // NOI18N
setupInitialConditionalNGTree(conditionalNG);
MaleSocket many = conditionalNG.getChild(0).getConnectedSocket();
// System.err.format("aa: %s%n", many.getLongDescription());
Assert::assertTrue("description is correct", "Many".equals(many.getLongDescription()));
MaleSocket ifThen = many.getChild(0).getConnectedSocket();
// System.err.format("aa: %s%n", ifThen.getLongDescription());
Assert::assertTrue("description is correct", "If Then Else. Execute on change".equals(ifThen.getLongDescription()));
systemName = InstanceManager::getDefault(DigitalExpressionManager.class).getAutoSystemName();
DigitalExpressionBean expression = new ExpressionTurnout(systemName, "An expression for test"); // NOI18N
MaleSocket digitalExpressionBean = InstanceManager::getDefault(DigitalExpressionManager.class).registerExpression(expression);
ifThen.getChild(0).connect(digitalExpressionBean);
// InstanceManager::getDefault(jmri.DigitalExpressionManager.class).addExpression(new ExpressionTurnout(systemName, "LogixNG 102, DigitalExpressionBean 26")); // NOI18N
systemName = InstanceManager::getDefault(DigitalActionManager.class).getAutoSystemName();
DigitalActionBean action = new ActionTurnout(systemName, "An action for test"); // NOI18N
MaleSocket digitalActionBean = InstanceManager::getDefault(DigitalActionManager.class).registerAction(action);
ifThen.getChild(1).connect(digitalActionBean);
if (! logixNG->setParentForAllChildren(new ArrayList<>())) throw new RuntimeException();
Assert::assertTrue("conditionalng is correct", conditionalNG == digitalActionBean.getConditionalNG());
Assert::assertTrue("conditionalng is correct", conditionalNG == conditionalNG.getConditionalNG());
Assert::assertTrue("logixlng is correct", logixNG == digitalActionBean.getLogixNG());
Assert::assertTrue("logixlng is correct", logixNG == logixNG->getLogixNG());
}
//@Test
/*public*/ void testSetup() throws SocketAlreadyConnectedException {
LogixNG logixNG = InstanceManager::getDefault(LogixNG_Manager.class)
.createLogixNG("A new logix for test"); // NOI18N
DefaultConditionalNG* conditionalNG =
(DefaultConditionalNG) InstanceManager::getDefault(ConditionalNG_Manager.class)
.createConditionalNG(logixNG, "A conditionalNG"); // NOI18N
String systemName = InstanceManager::getDefault(DigitalActionManager.class).getAutoSystemName();
DigitalActionBean action = new ActionTurnout(systemName, "An action for test"); // NOI18N
MaleSocket digitalActionBean = InstanceManager::getDefault(DigitalActionManager.class).registerAction(action);
conditionalNG.setSocketSystemName(systemName);
logixNG->setup();
if (! logixNG->setParentForAllChildren(new ArrayList<>())) throw new RuntimeException();
Assert::assertTrue("conditionalng child is correct",
"Set turnout '' to state Thrown"
.equals(conditionalNG.getChild(0).getConnectedSocket().getLongDescription()));
Assert::assertEquals("conditionalng is correct", conditionalNG, digitalActionBean.getConditionalNG());
Assert::assertEquals("logixlng is correct", logixNG, digitalActionBean.getLogixNG());
}
//@Test
/*public*/ void testExceptions() {
new SocketAlreadyConnectedException().getMessage();
}
//@Test
/*public*/ void testBundle() {
Assert::assertTrue("bean type is correct", "LogixNG".equals(new DefaultLogixNG("IQ55", null).getBeanType()));
Assert::assertTrue("bean type is correct", "Digital action".equals(new IfThenElse("IQDA321", null).getBeanType()));
Assert::assertTrue("bean type is correct", "Digital expression".equals(new And("IQDE321", null).getBeanType()));
}
#endif
// The minimal setup for log4J
//@Before
/*public*/ void LogixNGTest::setUp() {
JUnitUtil::setUp();
JUnitUtil::resetInstanceManager();
JUnitUtil::resetProfileManager();
JUnitUtil::initConfigureManager();
JUnitUtil::initInternalSensorManager();
JUnitUtil::initInternalTurnoutManager();
JUnitUtil::initLogixNGManager();
}
//@After
/*public*/ void LogixNGTest::tearDown() {
LogixNG_Thread::stopAllLogixNGThreads();
JUnitUtil::tearDown();
}
|
13a80c9164318eca9486944ebef62dad4f5babf9
|
1354e777845709e1560f17352397c37a160ea47d
|
/abc168/1.answer.cpp
|
91c65e35953963ad7173c1bfeed05d690569a9eb
|
[] |
no_license
|
segamiken/atcoder
|
c060ab883bee4fe6e75b9259bc25e910f2980343
|
6b0d4f66a8c5a76534e27cf85f50db16fea1d7cf
|
refs/heads/master
| 2022-11-10T01:49:07.150630
| 2020-06-29T14:06:37
| 2020-06-29T14:06:37
| 266,495,151
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 341
|
cpp
|
1.answer.cpp
|
#include<iostream>
using namespace std;
int main() {
int N;
cin >> N;
//1の桁の数
int count = N % 10;
if (count == 3) {
cout << "bon";
} else if (count == 0 or count == 1 or count == 6 or count == 8) {
cout << "pon";
} else {
cout << "hon";
}
return 0;
}
|
ca5891f492e2166d7f3c90669913e19b37aa06b3
|
d23ff5fba3e829054e2b04d0e0ecfe7940afdf24
|
/Player/S3DShowWizard.h
|
42b766f7ac0613a62353ae9411dd28dc254cb819
|
[] |
no_license
|
progmalover/vc-evrplayer
|
51b35d2b3d5191f75231aa8cb98aad99724af6b3
|
2292e495ce3450028bc405e2512fe94a7c364cf2
|
refs/heads/master
| 2021-04-29T05:16:23.525609
| 2017-01-04T05:40:58
| 2017-01-04T05:40:58
| 77,984,577
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,062
|
h
|
S3DShowWizard.h
|
#pragma once
class S3RenderMixer;
class S3RenderEngine;
#define VIDEO_SOURCE_TAG 0x533301
interface S3DShowWizard : public IUnknown
{
public:
S3DShowWizard(void);
virtual ~S3DShowWizard(void);
/*** IUnknown methods ***/
STDMETHOD(QueryInterface)(THIS_ REFIID riid, void** ppvObj) PURE;
STDMETHOD_(ULONG,AddRef)(THIS) PURE;
STDMETHOD_(ULONG,Release)(THIS) PURE;
// S3DShowWizard implementation
virtual HRESULT Initialize(
DWORD dwFlags,
HWND hWnd,
S3RenderEngine *pRenderEngine);
// terminate wizard
virtual HRESULT Terminate();
virtual HRESULT Attach(IBaseFilter* pRenderFilter, DWORD_PTR* pdwID);
virtual HRESULT Detach(DWORD_PTR dwID);
virtual HRESULT BeginDeviceLoss();
virtual HRESULT EndDeviceLoss(IDirect3DDevice9* pDevice);
virtual HRESULT VerifyID(DWORD_PTR dwID);
virtual HRESULT GetGraph(DWORD_PTR dwID, IFilterGraph** ppGraph);
virtual HRESULT GetRenderEngine(S3RenderEngine** pRenderEngine);
virtual HRESULT GetMixerControl(S3RenderMixer** ppMixerControl);
virtual HRESULT GetTexture(DWORD_PTR dwID,LPDIRECT3DTEXTURE9* ppTexture);
virtual HRESULT ReleaseTexture(DWORD_PTR dwID);
virtual HRESULT StopPresenting(DWORD_PTR dwID, BOOL bStop);
virtual HRESULT GetVideoSize(DWORD_PTR dwID, LONG* plWidth, LONG* plHeight, LONG* preferedx, LONG* preferedy);
virtual HRESULT EnableSFRUpload(DWORD_PTR dwID, BOOL bEnabled, BOOL bSplit, RECT* pDisplayRect, FLOAT RotateDegree);
// Private classes
protected:
class S3VR_VideoSource
{
public:
S3VR_VideoSource();
~S3VR_VideoSource();
// methods
void DeleteSurfaces();
HRESULT DisconnectPins();
HRESULT AllocateSurfaceBuffer( DWORD dwN );
HRESULT SetVideoSize( LONG lImageW,
LONG lImageH );
// data
// we use this tag to verify that (S3VR_VideoSource*)(void*)pVideoSource
// is really S3VR_VideoSource
DWORD_PTR dwTag;
DWORD_PTR dwID;
DWORD dwNumBuf;
DWORD dwNumBufActuallyAllocated;
LONG lImageWidth;
LONG lImageHeight;
LONG lPreferedx;
LONG lPreferedy;
BOOL m_UserNV12RT;
LPDIRECT3DTEXTURE9 pTexturePriv;
LPDIRECT3DSURFACE9 pTempSurfacePriv;
IDirect3DSurface9 **ppSurface;
VOID **ppSurfaceMem;
IUnknown *pVideoAllocator;
VOID *pVideoPresenter;
IFilterGraph *pGraph;
IBaseFilter *pRender;
BOOL bTextureInited;
volatile LONG updateCount;
volatile BOOL bStop;
DWORD dwLast;
CCritSec updateMutex;
};
typedef enum RenderThreadStatus
{
eNotStarted = 0x0,
eRunning,
eWaitingToStop,
eFinished,
} RenderThreadStatus;
// Private methods
protected:
HRESULT StartRenderingThread_();
HRESULT StopRenderingThread_();
void Clean_();
HRESULT GetSourceInfo_(DWORD_PTR dwID, S3VR_VideoSource** ppsource );
static DWORD WINAPI RenderThreadProc_( LPVOID lpParameter );
// Private data
protected:
HWND m_hwnd; // video window
CCritSec m_WizardObjectLock; // this object has to be thread-safe
BOOL m_bInitialized; // true if Initialize() was called and succeeded
volatile RenderThreadStatus m_RenderThreadStatus; // 0: not started, 1: running, 2: requested to stop, 3: stopped
CCritSec m_threadMutex;
DWORD m_dwConfigFlags; // configuration flags
DWORD m_maxVideoFPS;
S3RenderEngine* m_pRenderEngine; // render engine
list<S3VR_VideoSource*> m_listVideoSources;
};
|
08163c76703e65ac1fba492d803cf471711dd90f
|
425963de819e446a75441ff901adbfe5f1c5dea6
|
/chrome/browser/plugins/flash_download_interception.cc
|
a8b2140dac37c5cb04aa8a4025dfeae0cfbca27e
|
[
"BSD-3-Clause"
] |
permissive
|
Igalia/chromium
|
06590680bcc074cf191979c496d84888dbb54df6
|
261db3a6f6a490742786cf841afa92e02a53b33f
|
refs/heads/ozone-wayland-dev
| 2022-12-06T16:31:09.335901
| 2019-12-06T21:11:21
| 2019-12-06T21:11:21
| 85,595,633
| 123
| 25
|
NOASSERTION
| 2019-02-05T08:04:47
| 2017-03-20T15:45:36
| null |
UTF-8
|
C++
| false
| false
| 7,202
|
cc
|
flash_download_interception.cc
|
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/plugins/flash_download_interception.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/no_destructor.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/content_settings/tab_specific_content_settings.h"
#include "chrome/browser/permissions/permission_manager.h"
#include "chrome/browser/plugins/plugin_utils.h"
#include "chrome/browser/plugins/plugins_field_trial.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_features.h"
#include "components/content_settings/core/common/content_settings_types.h"
#include "components/navigation_interception/intercept_navigation_throttle.h"
#include "components/navigation_interception/navigation_params.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/web_contents.h"
#include "third_party/blink/public/mojom/permissions/permission_status.mojom.h"
#include "third_party/re2/src/re2/re2.h"
#include "url/origin.h"
using content::BrowserThread;
using content::NavigationHandle;
using content::NavigationThrottle;
namespace {
const RE2& GetFlashURLCanonicalRegex() {
static const base::NoDestructor<RE2> re("(?i)get2?\\.adobe\\.com/.*flash.*");
return *re;
}
const RE2& GetFlashURLSecondaryGoRegex() {
static const base::NoDestructor<RE2> re(
"(?i)(www\\.)?(adobe|macromedia)\\.com/go/"
"((?i).*get[-_]?flash|getfp10android|.*fl(ash)player|.*flashpl|"
".*flash_player|flash_completion|flashpm|.*flashdownload|d65_flplayer|"
"fp_jp|runtimes_fp|[a-z_-]{3,6}h-m-a-?2|chrome|download_player|"
"gnav_fl|pdcredirect).*");
return *re;
}
const RE2& GetFlashURLSecondaryDownloadRegex() {
static const base::NoDestructor<RE2> re(
"(?i)(www\\.)?(adobe|macromedia)\\.com/shockwave/download/download.cgi");
return *re;
}
const char kGetFlashURLSecondaryDownloadQuery[] =
"P1_Prod_Version=ShockwaveFlash";
bool InterceptNavigation(
const GURL& source_url,
content::WebContents* source,
const navigation_interception::NavigationParams& params) {
FlashDownloadInterception::InterceptFlashDownloadNavigation(source,
source_url);
return true;
}
} // namespace
// static
void FlashDownloadInterception::InterceptFlashDownloadNavigation(
content::WebContents* web_contents,
const GURL& source_url) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
Profile* profile =
Profile::FromBrowserContext(web_contents->GetBrowserContext());
HostContentSettingsMap* host_content_settings_map =
HostContentSettingsMapFactory::GetForProfile(profile);
ContentSetting flash_setting = PluginUtils::GetFlashPluginContentSetting(
host_content_settings_map, url::Origin::Create(source_url), source_url,
nullptr);
flash_setting = PluginsFieldTrial::EffectiveContentSetting(
host_content_settings_map, CONTENT_SETTINGS_TYPE_PLUGINS, flash_setting);
if (flash_setting == CONTENT_SETTING_DETECT_IMPORTANT_CONTENT) {
PermissionManager* manager = PermissionManager::Get(profile);
manager->RequestPermission(
CONTENT_SETTINGS_TYPE_PLUGINS, web_contents->GetMainFrame(),
web_contents->GetLastCommittedURL(), true, base::DoNothing());
} else if (flash_setting == CONTENT_SETTING_BLOCK) {
auto* settings = TabSpecificContentSettings::FromWebContents(web_contents);
if (settings)
settings->FlashDownloadBlocked();
}
// If the content setting has been already changed, do nothing.
}
// static
bool FlashDownloadInterception::ShouldStopFlashDownloadAction(
HostContentSettingsMap* host_content_settings_map,
const GURL& source_url,
const GURL& target_url,
bool has_user_gesture) {
if (!PluginUtils::ShouldPreferHtmlOverPlugins(host_content_settings_map))
return false;
if (!has_user_gesture)
return false;
url::Replacements<char> replacements;
replacements.ClearQuery();
replacements.ClearRef();
replacements.ClearUsername();
replacements.ClearPassword();
// If the navigation source is already the Flash download page, don't
// intercept the download. The user may be trying to download Flash.
std::string source_url_str =
source_url.ReplaceComponents(replacements).GetContent();
std::string target_url_str =
target_url.ReplaceComponents(replacements).GetContent();
// Early optimization since RE2 is expensive. http://crbug.com/809775
if (target_url_str.find("adobe.com") == std::string::npos &&
target_url_str.find("macromedia.com") == std::string::npos)
return false;
if (RE2::PartialMatch(source_url_str, GetFlashURLCanonicalRegex()))
return false;
if (RE2::FullMatch(target_url_str, GetFlashURLCanonicalRegex()) ||
RE2::FullMatch(target_url_str, GetFlashURLSecondaryGoRegex()) ||
(RE2::FullMatch(target_url_str, GetFlashURLSecondaryDownloadRegex()) &&
target_url.query() == kGetFlashURLSecondaryDownloadQuery)) {
ContentSetting flash_setting = PluginUtils::GetFlashPluginContentSetting(
host_content_settings_map, url::Origin::Create(source_url), source_url,
nullptr);
flash_setting = PluginsFieldTrial::EffectiveContentSetting(
host_content_settings_map, CONTENT_SETTINGS_TYPE_PLUGINS,
flash_setting);
return flash_setting == CONTENT_SETTING_DETECT_IMPORTANT_CONTENT ||
flash_setting == CONTENT_SETTING_BLOCK;
}
return false;
}
// static
std::unique_ptr<NavigationThrottle>
FlashDownloadInterception::MaybeCreateThrottleFor(NavigationHandle* handle) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// Browser initiated navigations like the Back button or the context menu
// should never be intercepted.
if (!handle->IsRendererInitiated())
return nullptr;
// The source URL may be empty, it's a new tab. Intercepting that navigation
// would lead to a blank new tab, which would be bad.
GURL source_url = handle->GetWebContents()->GetLastCommittedURL();
if (source_url.is_empty())
return nullptr;
// Always treat main-frame navigations as having a user gesture. We have to do
// this because the user gesture system can be foiled by popular JavaScript
// analytics frameworks that capture the click event. crbug.com/678097
bool has_user_gesture = handle->HasUserGesture() || handle->IsInMainFrame();
Profile* profile = Profile::FromBrowserContext(
handle->GetWebContents()->GetBrowserContext());
HostContentSettingsMap* host_content_settings_map =
HostContentSettingsMapFactory::GetForProfile(profile);
if (!ShouldStopFlashDownloadAction(host_content_settings_map, source_url,
handle->GetURL(), has_user_gesture)) {
return nullptr;
}
return std::make_unique<navigation_interception::InterceptNavigationThrottle>(
handle, base::Bind(&InterceptNavigation, source_url),
navigation_interception::SynchronyMode::kSync);
}
|
d369daf98ab0144ea3721aa4512140617f8d4711
|
d333f611a5ff915f535921ecc9ca6a1da4dcd660
|
/2019.12~2020.1@3Dゾンビゲーム/プログラムソースコード/GameUI.cpp
|
924fa5a31e0bf05f5f7c2d93624cad254c5567a9
|
[] |
no_license
|
kosyunrin/skMYGAMES
|
92e0961c483edc1ee4d37fa6fbffdea1955df081
|
bab00c257560d0f788a102f33fedd2ac681e97e5
|
refs/heads/master
| 2022-12-12T18:56:23.027856
| 2020-09-12T04:29:35
| 2020-09-12T04:29:35
| 276,560,866
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,473
|
cpp
|
GameUI.cpp
|
#include"B_header.h"
#include"CPolygon.h"
#include"texture.h"
#include"input.h"
GameUI::GameUI()
{
BlueDrawUI.BuleDraw = true;
}
GameUI::~GameUI()
{
}
void GameUI::Init()
{
Go_texture = new CTexture();
Go_textures = new CTexture();
Go_texture->LoadALLTga();
Go_textures->LoadAnyJpgPng();
Go_polygon = new CPolygon();
Go_polygon->Init();
}
void GameUI::Uninit()
{
Go_texture->UnloadAllTga();
Go_textures->UnloadAllJpgPng();
delete Go_texture;
delete Go_textures;
Go_polygon->Uninit();
delete Go_polygon;
}
void GameUI::Update(float dt)
{
}
void GameUI::Draw()
{
SoldierHouseBlue* g_s = CManager::GetScene()->GetGmeobjs<SoldierHouseBlue>(_solderHouseblue);
cnt += 0.3f;
int pattern = (int)cnt % 2;
Go_polygon->DrawJpgPng(30.0f, 910.0f, 50.0f, 50.0f, 1.0f, 1.0f, 1.0f, 1.0f, 2);
Go_polygon->Draw(100.0f, 0.0f, 200.0f, 200.0f, pattern*Go_texture->Texture_GetWidth(6) / 1, pattern / 1* Go_texture->Texture_GetHeight(6) / 2,
Go_texture->Texture_GetWidth(6) / 1, Go_texture->Texture_GetHeight(6) / 2, 6);
Go_polygon->Draw_animation2D(500.0f, 0.0f, 200.0f, 200.0f,6, 1, 2, 0.3f);
//Go_polygon->Draw(300.0f, 0.0f, 200.0f, 200.0f, pattern*Go_texture->Texture_GetWidth(5) / 5, pattern / 5 * Go_texture->Texture_GetHeight(5) / 3,
//Go_texture->Texture_GetWidth(5) / 5, Go_texture->Texture_GetHeight(5) / 3, 5);
Go_polygon->DrawJpgPng(0.0f, 900.0f, 500.0f, 100.0f, 1.0f,1.0f,1.0f,1.0f,1);
}
DrawUI * GameUI::getUiDraw()
{
return &BlueDrawUI;
}
|
11862ca421187814ebb0aa451c4b4ee8528b4ad3
|
63b9c964164f7f99e766d25606bcdb7c3dbbaeb9
|
/GeneratedFiles/ui_qgssinglebandpseudocolorrendererwidgetbase.h
|
5198a9ea82eac31b5056b0d179a12f7bd3d5d374
|
[] |
no_license
|
RenShuYuan/UAVplatform
|
cd3ffa45edd4840dfae34ee4acf66097bd7ac197
|
22cd1899cb0d56a0283ba439db0a67d023118d46
|
refs/heads/master
| 2021-01-09T20:32:26.148657
| 2016-10-20T15:39:29
| 2016-10-20T15:39:29
| 71,480,773
| 5
| 2
| null | 2016-10-31T12:09:51
| 2016-10-20T16:09:06
|
C++
|
UTF-8
|
C++
| false
| false
| 20,484
|
h
|
ui_qgssinglebandpseudocolorrendererwidgetbase.h
|
/********************************************************************************
** Form generated from reading UI file 'qgssinglebandpseudocolorrendererwidgetbase.ui'
**
** Created by: Qt User Interface Compiler version 4.8.6
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_QGSSINGLEBANDPSEUDOCOLORRENDERERWIDGETBASE_H
#define UI_QGSSINGLEBANDPSEUDOCOLORRENDERERWIDGETBASE_H
#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QCheckBox>
#include <QtGui/QComboBox>
#include <QtGui/QGridLayout>
#include <QtGui/QGroupBox>
#include <QtGui/QHBoxLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QLabel>
#include <QtGui/QLineEdit>
#include <QtGui/QPushButton>
#include <QtGui/QSpacerItem>
#include <QtGui/QSpinBox>
#include <QtGui/QToolButton>
#include <QtGui/QTreeWidget>
#include <QtGui/QVBoxLayout>
#include <QtGui/QWidget>
#include "qgscolorrampcombobox.h"
QT_BEGIN_NAMESPACE
class Ui_QgsSingleBandPseudoColorRendererWidgetBase
{
public:
QHBoxLayout *horizontalLayout_5;
QVBoxLayout *verticalLayout;
QGridLayout *gridLayout;
QLabel *mBandLabel;
QComboBox *mBandComboBox;
QComboBox *mColorInterpolationComboBox;
QLabel *mColorInterpolationLabel;
QHBoxLayout *horizontalLayout_3;
QToolButton *mAddEntryButton;
QToolButton *mDeleteEntryButton;
QToolButton *mSortButton;
QToolButton *mLoadFromBandButton;
QToolButton *mLoadFromFileButton;
QToolButton *mExportToFileButton;
QSpacerItem *horizontalSpacer;
QTreeWidget *mColormapTreeWidget;
QCheckBox *mClipCheckBox;
QVBoxLayout *verticalLayout_3;
QGroupBox *grpGenerateColorMap;
QVBoxLayout *verticalLayout_4;
QHBoxLayout *horizontalLayout_2;
QgsColorRampComboBox *mColorRampComboBox;
QPushButton *mButtonEditRamp;
QCheckBox *mInvertCheckBox;
QHBoxLayout *horizontalLayout;
QLabel *mClassificationModeLabel;
QComboBox *mClassificationModeComboBox;
QLabel *mNumberOfEntriesLabel;
QSpinBox *mNumberOfEntriesSpinBox;
QSpacerItem *horizontalSpacer_6;
QHBoxLayout *horizontalLayout_4;
QLabel *mMinLabel;
QLineEdit *mMinLineEdit;
QLabel *mMaxLabel;
QLineEdit *mMaxLineEdit;
QSpacerItem *horizontalSpacer_3;
QPushButton *mClassifyButton;
QGridLayout *gridLayout_3;
QLabel *mMinMaxOriginLabel;
QSpacerItem *horizontalSpacer_4;
QLabel *label_2;
QWidget *mMinMaxContainerWidget;
QSpacerItem *verticalSpacer;
void setupUi(QWidget *QgsSingleBandPseudoColorRendererWidgetBase)
{
if (QgsSingleBandPseudoColorRendererWidgetBase->objectName().isEmpty())
QgsSingleBandPseudoColorRendererWidgetBase->setObjectName(QString::fromUtf8("QgsSingleBandPseudoColorRendererWidgetBase"));
QgsSingleBandPseudoColorRendererWidgetBase->resize(616, 422);
horizontalLayout_5 = new QHBoxLayout(QgsSingleBandPseudoColorRendererWidgetBase);
horizontalLayout_5->setObjectName(QString::fromUtf8("horizontalLayout_5"));
verticalLayout = new QVBoxLayout();
verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
gridLayout = new QGridLayout();
gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
mBandLabel = new QLabel(QgsSingleBandPseudoColorRendererWidgetBase);
mBandLabel->setObjectName(QString::fromUtf8("mBandLabel"));
gridLayout->addWidget(mBandLabel, 0, 0, 1, 1);
mBandComboBox = new QComboBox(QgsSingleBandPseudoColorRendererWidgetBase);
mBandComboBox->setObjectName(QString::fromUtf8("mBandComboBox"));
gridLayout->addWidget(mBandComboBox, 0, 1, 1, 1);
mColorInterpolationComboBox = new QComboBox(QgsSingleBandPseudoColorRendererWidgetBase);
mColorInterpolationComboBox->setObjectName(QString::fromUtf8("mColorInterpolationComboBox"));
gridLayout->addWidget(mColorInterpolationComboBox, 1, 1, 1, 1);
mColorInterpolationLabel = new QLabel(QgsSingleBandPseudoColorRendererWidgetBase);
mColorInterpolationLabel->setObjectName(QString::fromUtf8("mColorInterpolationLabel"));
gridLayout->addWidget(mColorInterpolationLabel, 1, 0, 1, 1);
verticalLayout->addLayout(gridLayout);
horizontalLayout_3 = new QHBoxLayout();
horizontalLayout_3->setObjectName(QString::fromUtf8("horizontalLayout_3"));
mAddEntryButton = new QToolButton(QgsSingleBandPseudoColorRendererWidgetBase);
mAddEntryButton->setObjectName(QString::fromUtf8("mAddEntryButton"));
QIcon icon;
icon.addFile(QString::fromUtf8(":/images/themes/default/symbologyAdd.svg"), QSize(), QIcon::Normal, QIcon::Off);
mAddEntryButton->setIcon(icon);
horizontalLayout_3->addWidget(mAddEntryButton);
mDeleteEntryButton = new QToolButton(QgsSingleBandPseudoColorRendererWidgetBase);
mDeleteEntryButton->setObjectName(QString::fromUtf8("mDeleteEntryButton"));
QIcon icon1;
icon1.addFile(QString::fromUtf8(":/images/themes/default/symbologyRemove.svg"), QSize(), QIcon::Normal, QIcon::Off);
mDeleteEntryButton->setIcon(icon1);
horizontalLayout_3->addWidget(mDeleteEntryButton);
mSortButton = new QToolButton(QgsSingleBandPseudoColorRendererWidgetBase);
mSortButton->setObjectName(QString::fromUtf8("mSortButton"));
QIcon icon2;
icon2.addFile(QString::fromUtf8(":/images/themes/default/mActionArrowDown.png"), QSize(), QIcon::Normal, QIcon::Off);
mSortButton->setIcon(icon2);
horizontalLayout_3->addWidget(mSortButton);
mLoadFromBandButton = new QToolButton(QgsSingleBandPseudoColorRendererWidgetBase);
mLoadFromBandButton->setObjectName(QString::fromUtf8("mLoadFromBandButton"));
QIcon icon3;
icon3.addFile(QString::fromUtf8(":/images/themes/default/mActionDraw.svg"), QSize(), QIcon::Normal, QIcon::Off);
mLoadFromBandButton->setIcon(icon3);
horizontalLayout_3->addWidget(mLoadFromBandButton);
mLoadFromFileButton = new QToolButton(QgsSingleBandPseudoColorRendererWidgetBase);
mLoadFromFileButton->setObjectName(QString::fromUtf8("mLoadFromFileButton"));
QIcon icon4;
icon4.addFile(QString::fromUtf8(":/images/themes/default/mActionFileOpen.svg"), QSize(), QIcon::Normal, QIcon::Off);
mLoadFromFileButton->setIcon(icon4);
horizontalLayout_3->addWidget(mLoadFromFileButton);
mExportToFileButton = new QToolButton(QgsSingleBandPseudoColorRendererWidgetBase);
mExportToFileButton->setObjectName(QString::fromUtf8("mExportToFileButton"));
QIcon icon5;
icon5.addFile(QString::fromUtf8(":/images/themes/default/mActionFileSaveAs.svg"), QSize(), QIcon::Normal, QIcon::Off);
mExportToFileButton->setIcon(icon5);
horizontalLayout_3->addWidget(mExportToFileButton);
horizontalSpacer = new QSpacerItem(48, 28, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_3->addItem(horizontalSpacer);
verticalLayout->addLayout(horizontalLayout_3);
mColormapTreeWidget = new QTreeWidget(QgsSingleBandPseudoColorRendererWidgetBase);
mColormapTreeWidget->setObjectName(QString::fromUtf8("mColormapTreeWidget"));
QSizePolicy sizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Expanding);
sizePolicy.setHorizontalStretch(0);
sizePolicy.setVerticalStretch(0);
sizePolicy.setHeightForWidth(mColormapTreeWidget->sizePolicy().hasHeightForWidth());
mColormapTreeWidget->setSizePolicy(sizePolicy);
mColormapTreeWidget->header()->setDefaultSectionSize(70);
mColormapTreeWidget->header()->setMinimumSectionSize(10);
mColormapTreeWidget->header()->setStretchLastSection(true);
verticalLayout->addWidget(mColormapTreeWidget);
mClipCheckBox = new QCheckBox(QgsSingleBandPseudoColorRendererWidgetBase);
mClipCheckBox->setObjectName(QString::fromUtf8("mClipCheckBox"));
verticalLayout->addWidget(mClipCheckBox);
horizontalLayout_5->addLayout(verticalLayout);
verticalLayout_3 = new QVBoxLayout();
verticalLayout_3->setObjectName(QString::fromUtf8("verticalLayout_3"));
grpGenerateColorMap = new QGroupBox(QgsSingleBandPseudoColorRendererWidgetBase);
grpGenerateColorMap->setObjectName(QString::fromUtf8("grpGenerateColorMap"));
verticalLayout_4 = new QVBoxLayout(grpGenerateColorMap);
verticalLayout_4->setObjectName(QString::fromUtf8("verticalLayout_4"));
horizontalLayout_2 = new QHBoxLayout();
horizontalLayout_2->setObjectName(QString::fromUtf8("horizontalLayout_2"));
mColorRampComboBox = new QgsColorRampComboBox(grpGenerateColorMap);
mColorRampComboBox->setObjectName(QString::fromUtf8("mColorRampComboBox"));
horizontalLayout_2->addWidget(mColorRampComboBox);
mButtonEditRamp = new QPushButton(grpGenerateColorMap);
mButtonEditRamp->setObjectName(QString::fromUtf8("mButtonEditRamp"));
horizontalLayout_2->addWidget(mButtonEditRamp);
mInvertCheckBox = new QCheckBox(grpGenerateColorMap);
mInvertCheckBox->setObjectName(QString::fromUtf8("mInvertCheckBox"));
horizontalLayout_2->addWidget(mInvertCheckBox);
verticalLayout_4->addLayout(horizontalLayout_2);
horizontalLayout = new QHBoxLayout();
horizontalLayout->setObjectName(QString::fromUtf8("horizontalLayout"));
mClassificationModeLabel = new QLabel(grpGenerateColorMap);
mClassificationModeLabel->setObjectName(QString::fromUtf8("mClassificationModeLabel"));
horizontalLayout->addWidget(mClassificationModeLabel);
mClassificationModeComboBox = new QComboBox(grpGenerateColorMap);
mClassificationModeComboBox->setObjectName(QString::fromUtf8("mClassificationModeComboBox"));
horizontalLayout->addWidget(mClassificationModeComboBox);
mNumberOfEntriesLabel = new QLabel(grpGenerateColorMap);
mNumberOfEntriesLabel->setObjectName(QString::fromUtf8("mNumberOfEntriesLabel"));
horizontalLayout->addWidget(mNumberOfEntriesLabel);
mNumberOfEntriesSpinBox = new QSpinBox(grpGenerateColorMap);
mNumberOfEntriesSpinBox->setObjectName(QString::fromUtf8("mNumberOfEntriesSpinBox"));
QSizePolicy sizePolicy1(QSizePolicy::Fixed, QSizePolicy::Fixed);
sizePolicy1.setHorizontalStretch(0);
sizePolicy1.setVerticalStretch(0);
sizePolicy1.setHeightForWidth(mNumberOfEntriesSpinBox->sizePolicy().hasHeightForWidth());
mNumberOfEntriesSpinBox->setSizePolicy(sizePolicy1);
mNumberOfEntriesSpinBox->setMaximum(255);
mNumberOfEntriesSpinBox->setValue(0);
horizontalLayout->addWidget(mNumberOfEntriesSpinBox);
horizontalSpacer_6 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout->addItem(horizontalSpacer_6);
verticalLayout_4->addLayout(horizontalLayout);
horizontalLayout_4 = new QHBoxLayout();
horizontalLayout_4->setObjectName(QString::fromUtf8("horizontalLayout_4"));
mMinLabel = new QLabel(grpGenerateColorMap);
mMinLabel->setObjectName(QString::fromUtf8("mMinLabel"));
horizontalLayout_4->addWidget(mMinLabel);
mMinLineEdit = new QLineEdit(grpGenerateColorMap);
mMinLineEdit->setObjectName(QString::fromUtf8("mMinLineEdit"));
horizontalLayout_4->addWidget(mMinLineEdit);
mMaxLabel = new QLabel(grpGenerateColorMap);
mMaxLabel->setObjectName(QString::fromUtf8("mMaxLabel"));
horizontalLayout_4->addWidget(mMaxLabel);
mMaxLineEdit = new QLineEdit(grpGenerateColorMap);
mMaxLineEdit->setObjectName(QString::fromUtf8("mMaxLineEdit"));
horizontalLayout_4->addWidget(mMaxLineEdit);
horizontalSpacer_3 = new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);
horizontalLayout_4->addItem(horizontalSpacer_3);
verticalLayout_4->addLayout(horizontalLayout_4);
mClassifyButton = new QPushButton(grpGenerateColorMap);
mClassifyButton->setObjectName(QString::fromUtf8("mClassifyButton"));
verticalLayout_4->addWidget(mClassifyButton);
gridLayout_3 = new QGridLayout();
gridLayout_3->setObjectName(QString::fromUtf8("gridLayout_3"));
gridLayout_3->setVerticalSpacing(6);
mMinMaxOriginLabel = new QLabel(grpGenerateColorMap);
mMinMaxOriginLabel->setObjectName(QString::fromUtf8("mMinMaxOriginLabel"));
QSizePolicy sizePolicy2(QSizePolicy::Expanding, QSizePolicy::Preferred);
sizePolicy2.setHorizontalStretch(0);
sizePolicy2.setVerticalStretch(0);
sizePolicy2.setHeightForWidth(mMinMaxOriginLabel->sizePolicy().hasHeightForWidth());
mMinMaxOriginLabel->setSizePolicy(sizePolicy2);
gridLayout_3->addWidget(mMinMaxOriginLabel, 1, 1, 1, 1);
horizontalSpacer_4 = new QSpacerItem(6, 20, QSizePolicy::Fixed, QSizePolicy::Minimum);
gridLayout_3->addItem(horizontalSpacer_4, 1, 0, 1, 1);
label_2 = new QLabel(grpGenerateColorMap);
label_2->setObjectName(QString::fromUtf8("label_2"));
gridLayout_3->addWidget(label_2, 0, 0, 1, 2);
verticalLayout_4->addLayout(gridLayout_3);
verticalLayout_3->addWidget(grpGenerateColorMap);
mMinMaxContainerWidget = new QWidget(QgsSingleBandPseudoColorRendererWidgetBase);
mMinMaxContainerWidget->setObjectName(QString::fromUtf8("mMinMaxContainerWidget"));
verticalLayout_3->addWidget(mMinMaxContainerWidget);
verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
verticalLayout_3->addItem(verticalSpacer);
horizontalLayout_5->addLayout(verticalLayout_3);
QWidget::setTabOrder(mBandComboBox, mColorInterpolationComboBox);
QWidget::setTabOrder(mColorInterpolationComboBox, mAddEntryButton);
QWidget::setTabOrder(mAddEntryButton, mDeleteEntryButton);
QWidget::setTabOrder(mDeleteEntryButton, mSortButton);
QWidget::setTabOrder(mSortButton, mLoadFromBandButton);
QWidget::setTabOrder(mLoadFromBandButton, mLoadFromFileButton);
QWidget::setTabOrder(mLoadFromFileButton, mExportToFileButton);
QWidget::setTabOrder(mExportToFileButton, mColormapTreeWidget);
QWidget::setTabOrder(mColormapTreeWidget, mClipCheckBox);
QWidget::setTabOrder(mClipCheckBox, mColorRampComboBox);
QWidget::setTabOrder(mColorRampComboBox, mButtonEditRamp);
QWidget::setTabOrder(mButtonEditRamp, mInvertCheckBox);
QWidget::setTabOrder(mInvertCheckBox, mClassificationModeComboBox);
QWidget::setTabOrder(mClassificationModeComboBox, mNumberOfEntriesSpinBox);
QWidget::setTabOrder(mNumberOfEntriesSpinBox, mMinLineEdit);
QWidget::setTabOrder(mMinLineEdit, mMaxLineEdit);
QWidget::setTabOrder(mMaxLineEdit, mClassifyButton);
retranslateUi(QgsSingleBandPseudoColorRendererWidgetBase);
QMetaObject::connectSlotsByName(QgsSingleBandPseudoColorRendererWidgetBase);
} // setupUi
void retranslateUi(QWidget *QgsSingleBandPseudoColorRendererWidgetBase)
{
QgsSingleBandPseudoColorRendererWidgetBase->setWindowTitle(QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "Form", 0, QApplication::UnicodeUTF8));
mBandLabel->setText(QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "Band", 0, QApplication::UnicodeUTF8));
mColorInterpolationLabel->setText(QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "Color interpolation", 0, QApplication::UnicodeUTF8));
#ifndef QT_NO_TOOLTIP
mAddEntryButton->setToolTip(QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "Add values manually", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
mAddEntryButton->setText(QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "...", 0, QApplication::UnicodeUTF8));
#ifndef QT_NO_TOOLTIP
mDeleteEntryButton->setToolTip(QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "Remove selected row", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
mDeleteEntryButton->setText(QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "...", 0, QApplication::UnicodeUTF8));
#ifndef QT_NO_TOOLTIP
mSortButton->setToolTip(QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "Sort colormap items", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
mSortButton->setText(QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "...", 0, QApplication::UnicodeUTF8));
#ifndef QT_NO_TOOLTIP
mLoadFromBandButton->setToolTip(QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "Load color map from band", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
mLoadFromBandButton->setText(QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "...", 0, QApplication::UnicodeUTF8));
#ifndef QT_NO_TOOLTIP
mLoadFromFileButton->setToolTip(QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "Load color map from file", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
mLoadFromFileButton->setText(QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "...", 0, QApplication::UnicodeUTF8));
#ifndef QT_NO_TOOLTIP
mExportToFileButton->setToolTip(QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "Export color map to file", 0, QApplication::UnicodeUTF8));
#endif // QT_NO_TOOLTIP
mExportToFileButton->setText(QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "...", 0, QApplication::UnicodeUTF8));
QTreeWidgetItem *___qtreewidgetitem = mColormapTreeWidget->headerItem();
___qtreewidgetitem->setText(2, QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "Label", 0, QApplication::UnicodeUTF8));
___qtreewidgetitem->setText(1, QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "Color", 0, QApplication::UnicodeUTF8));
___qtreewidgetitem->setText(0, QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "Value", 0, QApplication::UnicodeUTF8));
mClipCheckBox->setText(QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "Clip", 0, QApplication::UnicodeUTF8));
grpGenerateColorMap->setTitle(QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "Generate new color map", 0, QApplication::UnicodeUTF8));
mButtonEditRamp->setText(QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "Edit", 0, QApplication::UnicodeUTF8));
mInvertCheckBox->setText(QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "Invert", 0, QApplication::UnicodeUTF8));
mClassificationModeLabel->setText(QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "Mode", 0, QApplication::UnicodeUTF8));
mNumberOfEntriesLabel->setText(QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "Classes", 0, QApplication::UnicodeUTF8));
mMinLabel->setText(QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "Min", 0, QApplication::UnicodeUTF8));
mMaxLabel->setText(QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "Max", 0, QApplication::UnicodeUTF8));
mClassifyButton->setText(QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "Classify", 0, QApplication::UnicodeUTF8));
mMinMaxOriginLabel->setText(QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "Min / Max origin", 0, QApplication::UnicodeUTF8));
label_2->setText(QApplication::translate("QgsSingleBandPseudoColorRendererWidgetBase", "Min / max origin:", 0, QApplication::UnicodeUTF8));
} // retranslateUi
};
namespace Ui {
class QgsSingleBandPseudoColorRendererWidgetBase: public Ui_QgsSingleBandPseudoColorRendererWidgetBase {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_QGSSINGLEBANDPSEUDOCOLORRENDERERWIDGETBASE_H
|
8bae94336bdffbcdb13922864c274c0bc7635950
|
012d280967aae334c63fec3b1983c103efd41cb6
|
/robominton/src/disp.cpp
|
48320782c2b756462316c781de13348839273829
|
[
"MIT"
] |
permissive
|
ukaana99/nhk2015_back_ros
|
b282068ccb7acaee957c2dfc71f31d1016c555db
|
abf0bdd81c452c104627c91a9a061d6e33264387
|
refs/heads/master
| 2021-05-28T19:23:01.846782
| 2015-06-17T04:55:01
| 2015-06-17T04:55:01
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,692
|
cpp
|
disp.cpp
|
#include <ros/ros.h>
#include <std_msgs/Int32.h>
#include <std_msgs/Float32.h>
#include <sensor_msgs/Imu.h>
#include <geometry_msgs/PoseStamped.h>
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
float motor1 = 0.0f;
float motor2 = 0.0f;
float enc1 = 0.0f;
float enc2 = 0.0f;
void motor1callback(const std_msgs::Float32::ConstPtr& msg){
motor1 = msg->data;
}
void motor2callback(const std_msgs::Float32::ConstPtr& msg){
motor2 = msg->data;
}
void enc1callback(const std_msgs::Float32::ConstPtr& msg){
enc1 = msg->data;
}
void enc2callback(const std_msgs::Float32::ConstPtr& msg){
enc2 = msg->data;
}
void timerCallback(const ros::TimerEvent&){
cv::Mat img = cv::Mat::zeros(300, 600, CV_8UC3);
cv::line(img, cv::Point(300+300*motor1, 150), cv::Point( 300+300*motor1+100*cos(CV_PI/2-motor2) , 150-100*sin(CV_PI/2-motor2) ), cv::Scalar(200,0,0), 10, CV_AA);
cv::line(img, cv::Point(300+300*enc1, 150), cv::Point( 300+300*enc1+100*cos(CV_PI/2-enc2) , 150-100*sin(CV_PI/2-enc2) ), cv::Scalar(0,200,200), 10, CV_AA);
cv::imshow("drawing", img);
cv::waitKey(1);
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "racketDisp");
ros::NodeHandle n;
ros::Subscriber subMotor1 = n.subscribe("/mb1/motor1", 10, motor1callback);
ros::Subscriber subMotor2 = n.subscribe("/mb1/motor2", 10, motor2callback);
ros::Subscriber subEnc1 = n.subscribe("/mb1/enc1", 10, enc1callback);
ros::Subscriber subEnc2 = n.subscribe("/mb1/enc2", 10, enc2callback);
ros::Timer timer = n.createTimer(ros::Duration(0.033), timerCallback);
cv::namedWindow("drawing", CV_WINDOW_AUTOSIZE|CV_WINDOW_FREERATIO);
ros::spin();
return 0;
}
|
153737e8cd16547dcc4840ff54dbfe8c7201e5e3
|
888a60218590e7eccca08252798016d8ff14530f
|
/cutplant2.cpp
|
48061c87fb747d6e0131c1dacc5e785567c2e822
|
[] |
no_license
|
codermaddy/competitive_programming
|
46bbbbe390d557e6822b20e8700b28c60e0d0c35
|
7762dd72a18e1aab25a46962d61c7dbb0cb90b9d
|
refs/heads/master
| 2020-08-27T07:03:05.089999
| 2019-10-24T11:10:03
| 2019-10-24T11:10:03
| 217,278,221
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,375
|
cpp
|
cutplant2.cpp
|
//partial
//april long'18
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll A[100005],B[100005];
ll calc(int u,int v,ll limit){
int i;
bool abc=0;
ll ans=0;
//all are equal?
for(i=u;i<=v;i++){
if(A[i]!=B[i]){
abc=1;
break;
}
}
if(abc==0)
return 0;
else{
for(i=u;i<=v;i++){
ans+=limit-B[i];
}
return ans+1;
}
}
int main(){
int T,N,i,start,end;
ll low,high,high_tmp,sum;
bool flag;
cin>>T;
while(T--){
//entry
cin>>N;
for(i=0;i<N;i++){
cin>>A[i];
}
for(i=0;i<N;i++){
cin>>B[i];
}
//checking for -1
flag=0;
for(i=0;i<N;i++){
if(A[i]<B[i])
flag=1;
}
if(flag==1)
cout<<-1<<"\n";
else{
i=0;
sum=0;
while(i<N){
start=i;
low=A[i];
high=B[i];
high_tmp=B[i];
while(i<N){
if(A[i]<high){
end=--i;
break;
}
if(high<B[i])
high_tmp=B[i];
if(low>A[i])
low=A[i];
if(high_tmp>low){
end=--i;
break;
}
high=high_tmp;
i++;
}
if(i==N)
sum+=calc(start,N-1,high);
else
sum+=calc(start,end,high);
i++;
}
cout<<sum<<"\n";
}
}
return 0;
}
|
f70d978d947c95a7a6b091d9767f21630e7bdc22
|
0b139653ca5290fb6133e306fefa8300842227e2
|
/OTB/xml/XMLParser.h
|
5e8dc7096cf1f53a15b3687c81cb52d45492b053
|
[] |
no_license
|
speedoog/off-the-ball
|
f37525b0dcfb6d81016271ed183360e93bc54a05
|
eb6dcc68e32fd79d0a3113657a0015e8e6a1fea0
|
refs/heads/master
| 2021-01-20T10:55:29.737544
| 2019-10-21T11:48:30
| 2019-10-21T11:48:30
| 33,539,397
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 856
|
h
|
XMLParser.h
|
//----------------------------------------------------------
//
//
//
//
// XML_PARSER
//
//
//
//
//----------------------------------------------------------
#ifndef __XML_XMLPARSER_H__
#define __XML_XMLPARSER_H__
#pragma once
#include "DynamicBuffer.h"
#include "XmlAttribute.h"
#include "XmlElement.h"
class XML_PARSER
{
public:
enum XMLRC
{
XP_NO_ERROR = 0,
XP_CANT_OPEN_FILE,
XP_PARSER_ERROR,
XP_NO_TREE
};
XML_PARSER();
~XML_PARSER();
XMLRC LoadFromFile(const char* pFileName);
XMLRC SaveToFile(const char* pFileName);
XML_ELEMENT* FindElement(char* pName, bool bRecursiveSearch=true);
inline XML_ELEMENT* GetRoot(void) { return _Root; }
XML_ELEMENT* CreateRootElement(char *pName);
protected:
XML_ELEMENT* _Root;
};
#endif //__XML_XMLPARSER_H__
|
6f0a1433d3d390a5fa1e8dc41b5aa1efc10c7039
|
a32e48c6f5ab467343bf92368731bd6b2b9a7492
|
/Alloy Engine/Alloy Engine/Src/Mesh.h
|
1765d68bdcbccb01bcf3777c3675804865ccbc80
|
[
"MIT"
] |
permissive
|
TomTurner2/ATP-Fur_Shader
|
0845c7b4f730f1762c459a7bf3c6fdaf783ddb71
|
81dd1fc1c193aecad278121888d03edbbc9c646a
|
refs/heads/master
| 2021-03-24T12:05:23.681511
| 2018-06-27T19:32:20
| 2018-06-27T19:32:20
| 106,966,781
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 798
|
h
|
Mesh.h
|
#pragma once
#include "GameObject.h"
#include "Vertex.h"
#include <d3d11.h>
#include "Material.h"
#include <vector>
class Renderer;
class Mesh : public GameObject
{
public:
Mesh(std::string _name);
~Mesh() = default;
std::string GetName() const;
Material* GetMaterial() const;
unsigned int GetVertexCount()const;
unsigned int GetIndiceCount()const;
void SetMaterial(Material* _material);
void CreateMesh(const std::vector<Vertex3D>& _vertices,
const std::vector<unsigned int>& _indicies, Renderer& _renderer);
void Draw(Renderer& _renderer) override;
private:
std::string m_name = "";
Material* m_material { nullptr };
ID3D11Buffer* m_vertex_buffer { nullptr };
ID3D11Buffer* m_index_buffer{ nullptr };
unsigned int m_indice_count = 0;
unsigned int m_vertex_count = 0;
};
|
0e80fe61689bac2878cd824485807f658ad0377d
|
f986e6aad322515718989ee337a8c1b5c7778466
|
/Baekjoon/10162_전자레인지.cpp
|
e192e9e05e88113f77692228db834369b5713527
|
[] |
no_license
|
wh2per/Baekjoon-Algorithm
|
bf611ae9c87dfc1af3f66b79f0c2d21db75c0df1
|
04f721f59b497f81452216ff0becbc3a620bbd0c
|
refs/heads/master
| 2021-11-24T09:23:31.327854
| 2021-11-11T05:56:54
| 2021-11-11T05:56:54
| 165,788,406
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 449
|
cpp
|
10162_전자레인지.cpp
|
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <algorithm>
#include <vector>
#include <climits>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
freopen("input.txt", "r", stdin);
int t;
cin >> t;
int a, b, c;
int ans = 0;
a = t / 300;
t %= 300;
b = t / 60;
t %= 60;
c = t / 10;
t %= 10;
if (t != 0)
cout << -1;
else
cout << a << " "<<b<<" "<<c;
return 0;
}
|
33fee5c7ac883941caccfa4d638a8266fb3a2209
|
2e2b2b8e7dcfac00379591e796f652d534181e7a
|
/CODEFORCES/1355/1335E.cpp
|
8f183de2a9eb781de7885add0a82ad9cc8cba3da
|
[] |
no_license
|
bansalshaleen/C-
|
caf6eea6a7c8271c646304677b384a20c35a5e2c
|
276d676ed7dd9923772e67e5ff84267af41c13cb
|
refs/heads/master
| 2023-06-10T09:58:21.430225
| 2021-07-04T11:25:36
| 2021-07-04T11:25:36
| 264,470,320
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,323
|
cpp
|
1335E.cpp
|
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
using namespace __gnu_pbds;
using namespace std;
typedef long long int ll;
typedef unsigned long long int sll;
typedef double ld;
#define A 1000000007ll
#define D 1000000000ll
#define B 998244353ll
#define C 1000000000000000000ll
#define FAST ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define oset tree<pair<ll,ll>, null_type,less<pair<ll,ll>>, rb_tree_tag,tree_order_statistics_node_update>
#define pb push_back
#define puf push_front
#define pob pop_back
#define pof pop_front
#define mxe(v) *max_element(v.begin(),v.end())
#define mne(v) *min_element(v.begin(),v.end())
#define bs binary_search
#define lb lower_bound
#define ub upper_bound
#define ve vector
#define br break
#define PI 3.14159265358979323
int main()
{
FAST;
ll n,a,r,m;
cin>>n>>a>>r>>m;
ve<ll> v(n,0);
for (ll i = 0; i < n; i++)
{
cin>>v[i];
}
sort(v.begin(),v.end());
ll mn=0, mx=0;
for (ll i = 0; i < n; i++)
{
mx+=v[n-1]-v[i];
mn+=v[i]-v[0];
}
ll ans=0;
if(m>a+r)
{
if(a*mx>r*mn)
{
ans=r*mn;
}
else
{
ans=a*mx;
}
}
else if(2*min(a,r)<m)
{
}
else
{
}
}
|
1d22a472432d1abebf3e754f6f560541978b3525
|
017478797a79e9b710110f0ded61b465896b2c93
|
/device.cpp
|
fe12c0bbdff299ec5a7ae9736e2b38bb8c3a5812
|
[] |
no_license
|
JMarlin/816
|
ad4198f9754546fa76ae55f395badcb8e88bef95
|
999e200ab553a884bea65d9fbd23fab6d5f0acec
|
refs/heads/master
| 2021-07-14T17:19:25.086375
| 2018-12-25T18:29:06
| 2018-12-25T18:29:06
| 105,568,089
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,807
|
cpp
|
device.cpp
|
#include "device.h"
Device::Device() {
this->_InitOk = false;
this->_ResponseRanges = new std::list<ResponseRange*>();
}
Device::~Device() {
for(auto iter = this->_ResponseRanges->begin(); iter != this->_ResponseRanges->end(); iter++)
delete *iter;
delete this->_ResponseRanges;
}
bool Device::GetInitOk() {
return this->_InitOk;
}
bool Device::TryReadByte(word32 address, word32 timestamp, word32 emulFlags, byte &b) {
auto range = this->_MatchRange(address, false);
if(range == NULL) {
b = 0xFF;
return false;
}
auto callback = range->GetReadCallback();
if(callback == NULL)
return this->_InternalReadByte(address, timestamp, emulFlags, range, b);
return callback(this, address, timestamp, emulFlags, range, b);
}
bool Device::TryWriteByte(word32 address, word32 timestamp, byte b) {
auto range = this->_MatchRange(address, true);
if(range == NULL)
return false;
auto callback = range->GetWriteCallback();
if(callback == NULL)
return this->_InternalWriteByte(address, timestamp, range, b);
return callback(this, address, timestamp, range, b);
}
ResponseRange* Device::AddResponseRange(word32 start, word32 end, byte rw_mask) {
return this->AddResponseRange(start, end, rw_mask, NULL, NULL);
}
ResponseRange* Device::AddResponseRange(word32 start, word32 end, byte rw_mask, ResponseRange::ReadCallback read_callback, ResponseRange::WriteCallback write_callback) {
auto range = new ResponseRange(start, end, rw_mask, read_callback, write_callback);
this->_ResponseRanges->push_back(range);
return range;
}
ResponseRange* Device::_MatchRange(word32 address, bool write) {
for(auto iter = this->_ResponseRanges->begin(); iter != this->_ResponseRanges->end(); iter++)
if((*iter)->RespondsToAddress(address, write))
return *iter;
return NULL;
}
|
c341a2120b7104b163181b5fa1f79aca5d9a7a59
|
ad730fcf89b0b4c51117dfd4e4a5c37b95f5bd89
|
/cpp/Dynamic_Memory_Allocation/heap.cpp
|
7209c02f69b2c2c10b8591ea1567b15eccfb0b87
|
[] |
no_license
|
Ashwin0512/Cpp_Ashwin
|
5e8eb70d68897149ca5dc4475449d339d4a6e521
|
e9401297d9e76d081acc593e515a6dbd0e0c5c59
|
refs/heads/main
| 2023-07-27T23:00:43.053468
| 2021-09-11T11:26:23
| 2021-09-11T11:26:23
| 346,825,005
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 435
|
cpp
|
heap.cpp
|
#include<bits/stdc++.h>
using namespace std;
int main() {
int a=10; //stored in stack
int *p = new int(); //allocate memory in heap
*p = 10;
delete(p); // deallocate memory from heap, but the pointer reamins
// in stack (DANGLING POINTER), can be used to allocate something in heap
p = new int[4]; //allocates an array in heap
delete[]p;
p = NULL; // deletes the pointer p
}
|
c9a5de18ca87d397e339a45002859d3af8c00ce7
|
38d571f0806b4e75db51685c5279414154ed51b3
|
/cpp/frameReceiver/include/FrameReceiverDefaults.h
|
cec11ddaddc909d0cedcd935ecc1f57bcdf0d0b2
|
[
"Apache-2.0"
] |
permissive
|
odin-detector/odin-data
|
007168d09fa3680004f7f94822bb03fbebcecfc8
|
75b06f33b8a9434d73e0fa5989d85805c4954136
|
refs/heads/master
| 2023-08-30T13:03:57.677587
| 2023-08-07T08:47:41
| 2023-08-07T08:47:41
| 76,046,833
| 7
| 8
|
Apache-2.0
| 2023-08-07T09:14:33
| 2016-12-09T15:28:08
|
C++
|
UTF-8
|
C++
| false
| false
| 1,369
|
h
|
FrameReceiverDefaults.h
|
/*
* FrameReceiverDefaults.h
*
* Created on: Feb 4, 2015
* Author: Tim Nicholls, STFC Application Engineering Group
*/
#ifndef FRAMERECEIVERDEFAULTS_H_
#define FRAMERECEIVERDEFAULTS_H_
#include <cstddef>
#include <stdint.h>
#include <string>
#ifndef BUILD_DIR
#define BUILD_DIR "."
#endif
namespace FrameReceiver
{
namespace Defaults
{
enum RxType
{
RxTypeIllegal = -1,
RxTypeUDP,
RxTypeZMQ,
};
const std::size_t default_max_buffer_mem = 1048576;
const std::string default_decoder_path = std::string(BUILD_DIR) + "/lib/";
const std::string default_decoder_type = "unknown";
const RxType default_rx_type = RxTypeUDP;
const std::string default_rx_port_list = "8989,8990";
const std::string default_rx_address = "0.0.0.0";
#ifdef __APPLE__
const int default_rx_recv_buffer_size = 1048576;
#else
const int default_rx_recv_buffer_size = 30000000;
#endif
const std::string default_rx_chan_endpoint = "inproc://rx_channel";
const std::string default_ctrl_chan_endpoint = "tcp://127.0.0.1:5000";
const unsigned int default_frame_timeout_ms = 1000;
const bool default_enable_packet_logging = false;
const bool default_force_reconfig = false;
}
} // namespace FrameReceiver
#endif /* FRAMERECEIVERDEFAULTS_H_ */
|
c0ecdcb94c7d2c086ea623234b66d24dc04da607
|
71a4032478b863e0bd43e639d76d560a8f56d255
|
/src/config.hpp
|
385fd6b240f62663604880268f8fbeedc020a0de
|
[] |
no_license
|
JohnHush/Caffe2Windows
|
c9a57922794a6c069f56895fabccf08930358491
|
36c62a089b932bd723afe172786a755f8fcb6c5f
|
refs/heads/master
| 2020-06-14T13:50:29.763495
| 2017-07-12T07:20:17
| 2017-07-12T07:20:17
| 75,174,948
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 456
|
hpp
|
config.hpp
|
#ifndef __JohnHush_CONFIG_H
#define __JohnHush_CONFIG_H
// define the header to build .dll in WINDOWS
#ifdef _WINDOWS
#define OCRAPI __declspec(dllexport)
#else
#define OCRAPI
#endif
// system file operation function include file
#ifdef _WINDOWS
// silent the min & max fun. in windows.h
#define NOMINMAX
#define NO_STRICT
#include <windows.h>
#endif
#ifdef APPLE
#include <mach-o/dyld.h>
#endif
#ifdef UNIX
#include <unistd.h>
#endif
#endif
|
91392b65c357338e62aaf9c7c5fe8d774155cb23
|
954499e39af8706506040f10dbbce783407a39c2
|
/Examples/FONT_SIZE/asc_string/asc_string.ino
|
65c510ba72501d74cb5b7acb3f3793de1dcbaec1
|
[] |
no_license
|
NickChungVietNam/st7565_library_arduino
|
995c58d6e75992c5ffe05fd88f17fd7beb9a092e
|
85789c812e740a0dd432d997af30e9357ba127fa
|
refs/heads/master
| 2020-12-30T15:54:25.755254
| 2018-05-04T13:44:03
| 2018-05-04T13:44:03
| 91,182,778
| 3
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 539
|
ino
|
asc_string.ino
|
#include "ST7565_homephone.h"
ST7565 lcd(3,4,5,6);//RST, SCLK, A0, SID
void setup() {
lcd.ON();
lcd.SET(23,0,0,0,4);
}
void loop(){
//c1:
lcd.Asc_String(0,0,Asc("Size 1"),1, BLACK);
lcd.Asc_String(0,12,Asc("Size 2"),2, BLACK);
lcd.Asc_String(0,30,Asc("Size 3"),3, BLACK);
lcd.display();
}
//void Asc_String(int x1, int y1,unsigned char c[] ,byte he_so_phong_to, bool color);
//x1,y1: tọa độ con trỏ của chữ cái đầu tiên
// c: mảng kí tự dạng chuỗi kí tự
//he_so_phong_to: phóng to
|
e9a18c319daa575865796c23946951b0c9e18ab8
|
7c3e20abc274d49f2bead8d9fe7ae06382d274c3
|
/Gui/Label.h
|
a05b77e2c5ea025e70547be7efaa9ac1cf49755a
|
[] |
no_license
|
oliewalcp/Rapid
|
8ca6f87f794a94e5c36fac6b3183fb4e077741d7
|
b2e0a15cf92f94433cc77e781554f9c41ebfbe31
|
refs/heads/master
| 2020-03-21T01:53:25.550197
| 2019-11-04T00:58:04
| 2019-11-04T00:58:04
| 137,967,881
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 439
|
h
|
Label.h
|
#ifndef LABEL_H
#define LABEL_H
#include "Widget.h"
namespace rapid
{
class Label : public WinWidget
{
private:
void __init(WinWidget *parent, const char *text);
public:
Label(WinWidget *parent = nullptr, const char *text = "")
{ __init(parent, text); }
Label(const char *text)
{ __init(nullptr, text); }
void set_text(const char *text)
{ set_string(text); }
virtual ~Label();
};
}
#endif // LABEL_H
|
42d7a59aa78f2509373a530198a05a226847869c
|
6ab81ff69f08ae39ea9d062d3e81c4d9e32f3e65
|
/Comp Graphics/CompGraph_lab1/wave1.cpp
|
46e32e1b7cfad0ed75d47528bedc4cf9ee0c87a6
|
[] |
no_license
|
SozinovAP/NNGU_labs
|
5955dba9c5c7b57e5737e1ce3c1fe56800ef8f7d
|
436d3cc51d8892487970756c15534beff69f9782
|
refs/heads/master
| 2023-05-03T19:39:40.051163
| 2021-05-30T15:48:59
| 2021-05-30T15:48:59
| 371,925,901
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 329
|
cpp
|
wave1.cpp
|
#include "wave1.h"
QColor Wave1Filter::CalculNewColor(pixel _point)
{
int x = static_cast<int>(_point.x + 20 * sin(2 * M_PI * _point.x / 60));
int y = _point.y;
return resimg.pixel(Clamp(x, 0, resimg.width() - 1), Clamp(y, 0, resimg.height() - 1));
}
Wave1Filter::Wave1Filter(const QPixmap& pix) : Filter(pix)
{
}
|
8af79e4189ef42f609979254010fe30fbe357c37
|
d7869995141b8809ebb300c4aff54ced0c17e057
|
/hdogs/hdogs.cpp
|
a6b7bf4c31ca66fed52cc721140c2eb559a1a7c0
|
[] |
no_license
|
Kirinosama/code
|
8d9e76f3fe70a2166dbe81e12b250dadcbc91bf7
|
584cea66c22201546259e3490c42afe5eb8c6e09
|
refs/heads/master
| 2021-06-11T18:46:05.096966
| 2019-09-25T12:56:05
| 2019-09-25T12:56:05
| 115,096,572
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 566
|
cpp
|
hdogs.cpp
|
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
#define ii pair<int,int>
#define INF 0x3f3f3f3f
typedef long long ll;
int T;
int f(int x,int y){
if(x%y==0) return 0;
if(y==1) return 0;
if(x>y) return f(x%y,y);
if(y%x==0) return x*(y/x-1);
else return y/x*x+f(x,y-y/x*x);
}
int main(){
freopen("hdogs.in","r",stdin);
freopen("hdogs.out","w",stdout);
cin>>T;
while(T--){
int x,y;scanf("%d%d",&x,&y);
cout<<f(x,y)<<endl;
}
return 0;
}
|
e219d79a203a217a6d165453ce351b6f42ff071e
|
3957b1c3e8e9274e2363e092488583c3926751ac
|
/Linked List/LLMergeSort.cpp
|
933eb092baf4d8136009d3330c6768f255a15436
|
[] |
no_license
|
angadjot/Data-Structure-Questions
|
626c1ef9d2c3fbe0d5a0d746f1e4f76222980b2d
|
92fa8f318dec0895b558a43717378112f3bae7cd
|
refs/heads/master
| 2021-01-19T14:00:44.254350
| 2017-08-20T17:00:04
| 2017-08-20T17:00:04
| 100,875,785
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,454
|
cpp
|
LLMergeSort.cpp
|
/*input
15
10
5
20
3
2
-1
*/
#include <iostream>
using namespace std;
struct node{
int data;
node *next;
};
node *createNode(int val);
void insert(node **headRef,int val);
void MergeSort(node **headRef);
node* SortedMerge(node *a,node *b);
void FrontBackSplit(node *source,node **frontRef,node **backRef);
void traverse(node **headRef);
int main(){
node *head = NULL;
int value;
while(true) {
cout<<"Press -1 to exit insert"<<endl;
cin>>value;
if(value == -1) {
break;
}
insert(&head,value);
}
cout<<"Linked List : ";
traverse(&head);
MergeSort(&head);
cout<<"After SortedMerge : Linked List : ";
traverse(&head);
return 0;
}
void traverse(node **headRef){
if(*headRef == NULL) {
return ;
}
node *current = *headRef;
while(current != NULL) {
cout<<current->data<<" ";
current = current->next;
}
cout<<endl;
}
node *createNode(int val){
node *temp = new node;
temp->data = val;
temp->next = NULL;
return temp;
}
void insert(node **headRef,int val){
if(*headRef == NULL){
*headRef = createNode(val);
return;
}
node *temp = createNode(val);
temp->next = *headRef;
*headRef = temp;
}
void MergeSort(node **headRef){
node *head = *headRef;
node *a;
node *b;
if(head == NULL || head->next == NULL)
return ;
FrontBackSplit(head,&a,&b);
MergeSort(&a);
MergeSort(&b);
*headRef = SortedMerge(a,b);
}
node* SortedMerge(node *a,node *b){
node *result = NULL;
if(a == NULL)
return b;
if(b == NULL)
return a;
if(a->data <= b->data) {
result = a;
result->next = SortedMerge(a->next,b);
}
else{
result = b;
result->next = SortedMerge(a,b->next);
}
return result;
}
void FrontBackSplit(node *source,node **frontRef,node **backRef){
node *fast;
node *slow;
if(source == NULL || source->next == NULL){
*frontRef = source;
*backRef = NULL;
}
else{
slow = source;
fast = slow->next;
while(fast != NULL) {
fast = fast->next;
if(fast != NULL) {
fast = fast->next;
slow = slow->next;
}
}
*frontRef = source;
*backRef = slow->next;
slow->next = NULL;
}
}
|
90a9d24bfbbe4158a13d9ad1ad8b5bf4d0c01595
|
657328727af2aac98a264cca638c1d67a714e7da
|
/arduino/Global_Frame_Serial/Global_Frame_Serial.ino
|
5a4a1be031e05d938cc8cf878ccc52f45fb914d8
|
[] |
no_license
|
Nickick-ICRS/dmt_project
|
afb4dd4a8633f47e0a9504a24214189420b13ac7
|
ae69ad0a72d9de08d690de11d8c0596b931422b3
|
refs/heads/master
| 2020-04-17T04:30:40.620736
| 2019-06-04T16:51:56
| 2019-06-04T16:51:56
| 166,233,035
| 0
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 15,472
|
ino
|
Global_Frame_Serial.ino
|
// ROS stuff will only compile if the libraries etc. are installed in the correct locations.
// Commenting this out will result in none of the ROS dependencies being included in the compile
#define USE_ROS
#ifdef USE_ROS
#include <ros.h>
#include <cynaptix/FrameMeasuredData.h>
#include <cynaptix/FrameTarget.h>
#endif // USE_ROS
/*
* ##################
* NORMAL DEFINITIONS
* ##################
*/
//----------------------------------------------------------------------------------------
//THE FOLLOWING PROGRAM CONTROLS THE ENTIRE ROBOT FRAME AND CALCULATES THE TORQUE FROM EACH MOTOR
#include <PID_v1.h>
#include <Encoder.h>
#include <Servo.h>
#define ENCODER_OPTIMIZE_INTERRUPTS
Servo Rotation; //initialise servo
#define in1X 4 //input pin 1 for X motor set on PWM pin of arduino
#define in2X 5 //input pin 2 for X motor set on digital pin of arduino
#define in1Y 6
#define in2Y 7
#define in1Z 8
#define in2Z 9
#define in1Grab 10
#define in2Grab 11
#define inRot 12
#define encod1X 2 //encoder input channel A
#define encod2X 22 //encoder input channel B
#define encod1Y 3
#define encod2Y 24
#define encod1Z 18
#define encod2Z 19
#define encod1Grab 20
#define encod2Grab 21
#define zero_switchX 42 //pullup pin for switch
#define zero_switchY 40
#define zero_switchZ 38
#define zero_switchGrab 36
#define current_pinX A0 //analogue pin for current sensor
#define current_pinY A1
#define current_pinZ A2
#define current_pinGrab A3
#define current_pinRot A4
//PID controller setup
double encod_countX; //encoder position in mm
double encod_countY;
double encod_countZ;
double encod_countGrab;
double speed_X; //output //current position is constantly updated
double speed_Y;
double speed_Z;
double speed_Grab;
double targetX; //setpoint, target will be given
double targetY;
double targetZ;
double targetGrab;
double targetRot;
double KpX=4, KiX=2, KdX=0;
double KpY=6, KiY=3, KdY=0;
double KpZ=1, KiZ=0, KdZ=0;
double KpGrab=0.7, KiGrab=0.52, KdGrab=0;
char switch_statusX; //0 if off, 1 if on
char switch_statusY;
char switch_statusZ;
char switch_statusGrab;
double currentX = 0; //current calculated from current sensor
double currentY = 0;
double currentZ = 0;
double currentGrab = 0;
double currentRot = 0;
double torqueX = 0; //torque calculated from current
double torqueY = 0;
double torqueZ = 0;
double torqueGrab = 0;
double torqueRot = 0;
int VoutX = 0; //voltage output from current sensor
int VoutY = 0;
int VoutZ = 0;
int VoutGrab = 0;
int VoutRot = 0;
//PID instance
PID myPIDX(&encod_countX, &speed_X, &targetX, KpX, KiX, KdX, DIRECT);
PID myPIDY(&encod_countY, &speed_Y, &targetY, KpY, KiY, KdY, DIRECT);
PID myPIDZ(&encod_countZ, &speed_Z, &targetZ, KpZ, KiZ, KdZ, DIRECT);
PID myPIDGrab(&encod_countGrab, &speed_Grab, &targetGrab, KpGrab, KiGrab, KdGrab, DIRECT);
Encoder myEncX(encod1X,encod2X);
Encoder myEncY(encod1Y,encod2Y);
Encoder myEncZ(encod1Z,encod2Z);
Encoder myEncGrab(encod1Grab,encod2Grab);
//----------------------------------------------------------------------------------------
/*
* ###############
* ROS DEFINITIONS
* ###############
*/
#ifdef USE_ROS
// Uncomment this to average all readings since the last message when sending data to frame
// Comment this to send only the latest measured position when sending data to the frame
#define AVERAGE_READINGS
// Communication frequency with the server (Hz)
#define PUBLISH_FREQ 10
// Callback for when we receive new callbacks
void frame_target_callback(const cynaptix::FrameTarget& msg);
// Node handle to interface with ROS
ros::NodeHandle nh;
// Data we have measured message
cynaptix::FrameMeasuredData measured_data_msg;
// Target positions message
cynaptix::FrameTarget target_msg;
// Publisher
ros::Publisher pub("frame_measured_data", &measured_data_msg);
// Subscriber
ros::Subscriber<cynaptix::FrameTarget> sub("frame_target", &frame_target_callback);
// Timer variable to control publish rate
unsigned long ros_timer;
// Variable used to count the number of messages since the previous send when averaging
#ifdef AVERAGE_READINGS
int average_counter;
#endif // AVERAGE_READINGS
#endif // USE_ROS
// Function forward declarations
void setup_ros();
double update_x_pos();
double update_y_pos();
double update_z_pos();
double update_yaw_pos();
double update_grab_pos();
double measure_x_trq();
double measure_y_trq();
double measure_z_trq();
double measure_yaw_trq();
double measure_grab_trq();
void update_ros(double x_pos, double y_pos, double z_pos, double yaw_pos, double grab_pos,
double x_trq, double y_trq, double z_trq, double yaw_trq, double grab_trq);
void setup() {
// Setup other shit, inc. home axis if we're implementing that
// Setup ROS - do this last
setup_ros();
pinMode(in1X, OUTPUT); //input driver pin set to output
pinMode(in2X, OUTPUT); //input driver pin set to output
pinMode(in1Y, OUTPUT);
pinMode(in2Y, OUTPUT);
pinMode(in1Z, OUTPUT);
pinMode(in2Z, OUTPUT);
pinMode(in1Grab, OUTPUT);
pinMode(in2Grab, OUTPUT);
pinMode(encod1X, INPUT_PULLUP); //encoder pin set to input
pinMode(encod2X, INPUT_PULLUP);
pinMode(encod1Y, INPUT_PULLUP);
pinMode(encod2Y, INPUT_PULLUP);
pinMode(encod1Z, INPUT_PULLUP);
pinMode(encod2Z, INPUT_PULLUP);
pinMode(encod1Grab, INPUT_PULLUP);
pinMode(encod2Grab, INPUT_PULLUP);
pinMode(zero_switchX, INPUT_PULLUP); //switch pin set to input
pinMode(zero_switchY, INPUT_PULLUP);
pinMode(zero_switchZ, INPUT_PULLUP);
pinMode(zero_switchGrab, INPUT_PULLUP);
pinMode(current_pinX, INPUT); //current sensor set to analogue input
pinMode(current_pinY, INPUT);
pinMode(current_pinZ, INPUT);
pinMode(current_pinGrab, INPUT);
pinMode(current_pinRot, INPUT);
Rotation.attach(inRot); //enable servo pin
Rotation.write(0); //initially set to 0deg
Serial.begin(57600); //enable serial communication for debugging
myPIDX.SetMode(AUTOMATIC); //turn PID on
myPIDY.SetMode(AUTOMATIC);
myPIDZ.SetMode(AUTOMATIC);
myPIDGrab.SetMode(AUTOMATIC);
myPIDX.SetTunings(KpX, KiX, KdX); //adjust PID gains
myPIDY.SetTunings(KpY, KiY, KdY);
myPIDZ.SetTunings(KpZ, KiZ, KdZ);
myPIDGrab.SetTunings(KpGrab, KiGrab, KdGrab);
switch_statusX = digitalRead(zero_switchX);
switch_statusY = digitalRead(zero_switchY);
switch_statusZ = digitalRead(zero_switchZ);
switch_statusGrab = digitalRead(zero_switchGrab);
// while(switch_statusX == 0){ //send motor to initial position touching switch
// analogWrite(in2X, 255); //backwards
// digitalWrite(in1X, LOW); //new value of speed
// }
// myEncX.write(0); //zero encoder position
//
// while(switch_statusY == 0){ //send motor to initial position touching switch
// analogWrite(in2Y, 255); //backwards
// digitalWrite(in1Y, LOW); //new value of speed
// }
// myEncY.write(0); //zero encoder position
//
// while(switch_statusZ == 0){ //send motor to initial position touching switch
// analogWrite(in2Z, 255); //backwards
// digitalWrite(in1Z, LOW); //new value of speed
// }
// myEncZ.write(0); //zero encoder position
//
// while(switch_statusGrab == 0){ //send motor to initial position touching switch
// analogWrite(in2Grab, 255); //backwards
// digitalWrite(in1Grab, LOW); //new value of speed
// }
// myEncGrab.write(0); //zero encoder position
}
void loop() {
// update the motor positions
double x_pos = update_x_pos();
double y_pos = update_y_pos();
double z_pos = update_z_pos();
double yaw_pos = update_yaw_pos();
double grab_pos = update_grab_pos();
// measure the currents
double x_trq = measure_x_trq();
double y_trq = measure_y_trq();
double z_trq = measure_z_trq();
double yaw_trq = measure_yaw_trq();
double grab_trq = measure_grab_trq();
// Update ROS
update_ros(x_pos, y_pos, z_pos, yaw_pos, grab_pos,
x_trq, y_trq, z_trq, yaw_trq, grab_trq);
}
void setup_ros() {
#ifdef USE_ROS
// This is all that goes here for now
nh.initNode();
nh.advertise(pub);
nh.subscribe(sub);
#ifdef AVERAGE_READINGS
measured_data_msg.x_pos = 0;
measured_data_msg.y_pos = 0;
measured_data_msg.z_pos = 0;
measured_data_msg.theta_pos = 0;
measured_data_msg.grabber_pos = 0;
measured_data_msg.x_torque = 0;
measured_data_msg.y_torque = 0;
measured_data_msg.z_torque = 0;
measured_data_msg.theta_torque = 0;
measured_data_msg.grabber_torque = 0;
average_counter = 0;
#endif // AVERAGE_READINGS
ros_timer = millis();
#endif // USE_ROS
}
void update_ros(double x_pos, double y_pos, double z_pos, double yaw_pos, double grab_pos,
double x_trq, double y_trq, double z_trq, double yaw_trq, double grab_trq) {
#ifdef USE_ROS
#ifdef AVERAGE_READINGS
measured_data_msg.x_pos += x_pos;
measured_data_msg.y_pos += y_pos;
measured_data_msg.z_pos += z_pos;
measured_data_msg.theta_pos += yaw_pos;
measured_data_msg.grabber_pos += grab_pos;
measured_data_msg.x_torque += x_pos;
measured_data_msg.y_torque += y_pos;
measured_data_msg.z_torque += z_pos;
measured_data_msg.theta_torque += yaw_pos;
measured_data_msg.grabber_torque += grab_pos;
average_counter++;
#else
measured_data_msg.x_pos = x_pos;
measured_data_msg.y_pos = y_pos;
measured_data_msg.z_pos = z_pos;
measured_data_msg.theta_pos = yaw_pos;
measured_data_msg.grabber_pos = grab_pos;
measured_data_msg.x_torque = x_trq;
measured_data_msg.y_torque = y_trq;
measured_data_msg.z_torque = z_trq;
measured_data_msg.theta_torque = yaw_trq;
measured_data_msg.grabber_torque = grab_trq;
#endif // AVERAGE_READINGS
if(millis() - ros_timer > 1.0f / PUBLISH_FREQ) {
ros_timer = millis();
#ifdef AVERAGE_READINGS
measured_data_msg.x_pos /= (double)average_counter;
measured_data_msg.y_pos /= (double)average_counter;
measured_data_msg.z_pos /= (double)average_counter;
measured_data_msg.theta_pos /= (double)average_counter;
measured_data_msg.grabber_pos /= (double)average_counter;
measured_data_msg.x_torque /= (double)average_counter;
measured_data_msg.y_torque /= (double)average_counter;
measured_data_msg.z_torque /= (double)average_counter;
measured_data_msg.theta_torque /= (double)average_counter;
measured_data_msg.grabber_torque /= (double)average_counter;
#endif // AVERAGE_READINGS
pub.publish(&measured_data_msg);
#ifdef AVERAGE_READINGS
measured_data_msg.x_pos = 0;
measured_data_msg.y_pos = 0;
measured_data_msg.z_pos = 0;
measured_data_msg.theta_pos = 0;
measured_data_msg.grabber_pos = 0;
measured_data_msg.x_torque = 0;
measured_data_msg.y_torque = 0;
measured_data_msg.z_torque = 0;
measured_data_msg.theta_torque = 0;
measured_data_msg.grabber_torque = 0;
average_counter = 0;
#endif // AVERAGE_READINGS
}
// Check for new messages
nh.spinOnce();
#endif // USE_ROS
}
#ifdef USE_ROS
void frame_target_callback(const cynaptix::FrameTarget& msg) {
targetX = msg.x_pos;
targetY = msg.y_pos;
targetZ = msg.z_pos;
targetRot = msg.theta_pos;
targetGrab = msg.grabber_pos;
char buf[64];
memset(buf, '\0', 64);
sprintf(buf, "Received msg: [%d, %d, %d, %d, %d]", (int)targetX, (int)targetY, (int)targetZ, (int)targetRot, (int)targetGrab);
nh.loginfo(buf);
}
#endif // USE_ROS
double update_x_pos() {
encod_countX = myEncX.read(); //get instantaneous position
if (encod_countX != targetX){
myPIDX.Compute(); //calculate PID output
if (encod_countX < targetX){
analogWrite(in2X, speed_X); //backwards
digitalWrite(in1X, LOW); //new value of speed
} else {
analogWrite(in2X, speed_X); //forwards
digitalWrite(in1X, HIGH); //new value of speed
}
} else {
digitalWrite(in1X, LOW);
digitalWrite(in2X, LOW);
}
return encod_countX;
}
double update_y_pos() {
encod_countY = myEncY.read(); //get instantaneous position
if (encod_countY != targetY){
myPIDY.Compute(); //calculate PID output
if (encod_countY < targetY){
analogWrite(in2Y, speed_Y); //backwards
digitalWrite(in1Y, LOW); //new value of speed
} else {
analogWrite(in2Y, speed_Y); //forwards
digitalWrite(in1Y, HIGH); //new value of speed
}
} else {
digitalWrite(in1Y, LOW);
digitalWrite(in2Y, LOW);
}
return encod_countY;
}
double update_z_pos() {
encod_countZ = myEncZ.read(); //get instantaneous position
if (encod_countZ != targetZ){
myPIDZ.Compute(); //calculate PID output
if (encod_countZ < targetZ){
analogWrite(in2Z, speed_Z); //backwards
digitalWrite(in1Z, LOW); //new value of speed
} else {
analogWrite(in2Z, speed_Z); //forwards
digitalWrite(in1Z, HIGH); //new value of speed
}
} else {
digitalWrite(in1Z, LOW);
digitalWrite(in2Z, LOW);
}
return encod_countZ;
}
double update_yaw_pos() {
Rotation.write(targetRot); //send servo to target angle between 0-180deg
return 0;
}
double update_grab_pos() {
encod_countGrab = myEncGrab.read(); //get instantaneous position
if (encod_countGrab != targetGrab){
myPIDGrab.Compute(); //calculate PID output
if (encod_countGrab < targetGrab){
analogWrite(in2Grab, speed_Grab); //backwards
digitalWrite(in1Grab, LOW); //new value of speed
} else {
analogWrite(in2Grab, speed_Grab); //forwards
digitalWrite(in1Grab, HIGH); //new value of speed
}
} else {
digitalWrite(in1Grab, LOW);
digitalWrite(in2Grab, LOW);
}
return encod_countGrab;
}
double measure_x_trq() {
VoutX = analogRead(current_pinX); //read voltage output from current sensor
currentX = VoutX * (5.0/1023.0) * 0.4; //convert Vout into current measured
torqueX = currentX * 1;//?; //multiply current by motor constant to get torque
return torqueX;
}
double measure_y_trq() {
VoutY = analogRead(current_pinY); //read voltage output from current sensor
currentY = VoutY * (5.0/1023.0) * 0.4; //convert Vout into current measured
torqueY = currentY * 1;//?; //multiply current by motor constant to get torque
return torqueY;
}
double measure_z_trq() {
VoutZ = analogRead(current_pinZ); //read voltage output from current sensor
currentZ = VoutZ * (5.0/1023.0) * 0.4; //convert Vout into current measured
torqueZ = currentZ * 1;//?; //multiply current by motor constant to get torque
return torqueZ;
}
double measure_yaw_trq() {
VoutRot = analogRead(current_pinRot); //read voltage output from current sensor
currentRot = VoutRot * (5.0/1023.0) * 0.4; //convert Vout into current measured
torqueRot = currentRot * 1;//?; //multiply current by motor constant to get torque
return torqueRot;
}
double measure_grab_trq() {
VoutGrab = analogRead(current_pinGrab); //read voltage output from current sensor
currentGrab = VoutGrab * (5.0/1023.0) * 0.4; //convert Vout into current measured
torqueGrab = currentGrab * 1;//?; //multiply current by motor constant to get torque
return torqueGrab;
}
|
2511f1a51b52c67d90810464ea4c5660cc68422c
|
f0eeb6724147908e6903a07cd524472938d5cdba
|
/Baekjoon/3048_개미.cpp
|
9b73fa480451242ada7cfa06d8056f7a4c5d36fc
|
[] |
no_license
|
paperfrog1228/Algorithm
|
bb338e51169d2b9257116f8e9c23afc147e65e27
|
14b0da325f317d36537a1254bc178bed32337829
|
refs/heads/master
| 2022-09-22T23:58:28.824408
| 2022-09-09T07:01:41
| 2022-09-09T07:01:41
| 152,889,184
| 3
| 0
| null | 2019-03-24T14:49:13
| 2018-10-13T16:04:45
|
C++
|
UTF-8
|
C++
| false
| false
| 646
|
cpp
|
3048_개미.cpp
|
#include <stdio.h>
struct Ant{char a;int dir;};
Ant ant[30];
int a,b,t;
int main(){
scanf("%d %d",&a,&b);
for(int i=a;i>0;i--){
scanf(" %c ",&ant[i].a);
ant[i].dir=1;
}
for(int i=a+1;i<=a+b;i++){
scanf(" %c ",&ant[i].a);
ant[i].dir=2;
}
scanf("%d",&t);
for(int j=1;j<=t;j++){
for(int i=1;i<a+b;i++){
if(ant[i].dir==1&&ant[i+1].dir==2){
Ant temp=ant[i];
ant[i]=ant[i+1];
ant[i+1]=temp;
i++;
}
}
}
for(int i=1;i<=a+b;i++)
printf("%c",ant[i].a);
}
|
ab7bbeedc08cedf0a7ebf549cd17e4e9a9eb554c
|
4598524620d159bd0d6e2fc2f390299b55ec9bc0
|
/UVa/uva_11955.cpp
|
07edc1d055f4b3f0edd7d63cebedf3142624aca9
|
[] |
no_license
|
skyu0221/Kattis-UVa
|
a586c15851063828f8b78c66f93b833af1c27fcd
|
bd3a0835d4bb9a6ab50fca6e0db3c8df7cc4ed1b
|
refs/heads/master
| 2021-08-22T17:39:57.172371
| 2021-01-13T00:15:58
| 2021-01-13T00:15:58
| 69,905,949
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,477
|
cpp
|
uva_11955.cpp
|
/* UVa problem: 11955
*
* Topic: Arithmetic
*
* Level: 1 point
*
* Brief problem description:
*
* ...
*
* Solution Summary:
*
* Mainly math problem
*
* Used Resources:
*
* ...
*
* I hereby certify that I have produced the following solution myself
* using the resources listed above in accordance with the CMPUT 403
* collaboration policy.
*
* --- Tianyu Zhang
*/
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
long long C( int i, int k ) {
long long result = 1;
if ( i > k / 2 ) i = k - i;
for ( int j = 0; j < i; j++ ) {
result = result * ( k - j ) / ( j + 1 );
}
return result;
}
int main() {
int test_case;
cin >> test_case;
for ( int i = 0; i < test_case; i++ ) {
string line, a, b, c;
stringstream ss;
int power;
cin >> line;
a = line.substr( 1, line.find('+') - 1 );
b = line.substr( line.find('+') + 1,
line.find(')') - line.find('+') - 1 );
ss << line.substr( line.find('^') + 1 );
ss >> power;
cout << "Case " << i + 1 << ": ";
for ( int j = 0; j < power + 1; j++ ) {
if ( C(j,power) != 1 ) {
cout << C(j,power) << "*";
}
if ( j != power ) {
cout << a;
if ( power - j != 1 ) {
cout << "^" << power - j;
}
}
if ( j != 0 && j != power ) cout << "*";
if ( j != 0 ) {
cout << b;
if ( j != 1 ) {
cout << "^" << j;
}
}
if ( j != power ) cout << "+";
}
cout << endl;
}
return 0;
}
|
29f30fba8eea29c87d3a55269fa90efa535e1fac
|
5395d97da423150cb6471f868e8b2fe1a5d61a3e
|
/LO21/lo21-projet/code/ProjectCalendar/GUI/editecheance.h
|
797c95cdcad85541d8c18b19f1c8d5d2cf4ccb3a
|
[] |
no_license
|
rpellerin/UTC-UV
|
0d241a4ee63022bc8793d127bc94421e57c4424d
|
fd85350af0d78658b98d438332b7e4361e5ab9d7
|
refs/heads/master
| 2021-08-06T20:42:07.602409
| 2021-02-07T22:38:53
| 2021-02-07T22:38:53
| 36,667,704
| 2
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 645
|
h
|
editecheance.h
|
#ifndef EDITECHEANCE_H
#define EDITECHEANCE_H
#include <QDialog>
namespace Ui {
class editecheance;
}
class editecheance : public QDialog
{
Q_OBJECT
public:
//! Constructeur de editecheance
explicit editecheance(QWidget *parent = 0);
//! Destructeur de editecheance
~editecheance();
/**
* @brief setDate permer d'attribuer une date au widget
* @param d la date a attribuer
*/
void setDate(QDate d);
/**
* @brief getDate permet de recuperer la date du widget
* @return la date
*/
const QDate getDate() const;
private:
Ui::editecheance *ui;
};
#endif // EDITECHEANCE_H
|
80029181f119e8e6c52f0cad1205edcd3b0941e9
|
be5f4d79910e4a93201664270916dcea51d3b9ee
|
/rovers/fastdownward/src/search/potentials/potential_function.cc
|
222f793210a1ef4f07d1f5198704c0d83e26d461
|
[
"MIT",
"GPL-1.0-or-later",
"GPL-3.0-or-later"
] |
permissive
|
mehrdadzakershahrak/Online-Explanation-Generation
|
17c3ab727c2a4a60381402ff44e95c0d5fd0e283
|
e41ad9b5a390abdaf271562a56105c191e33b74d
|
refs/heads/master
| 2022-12-09T15:49:45.709080
| 2019-12-04T10:23:23
| 2019-12-04T10:23:23
| 184,834,004
| 0
| 0
|
MIT
| 2022-12-08T17:42:50
| 2019-05-04T00:04:59
|
Python
|
UTF-8
|
C++
| false
| false
| 800
|
cc
|
potential_function.cc
|
#include "potential_function.h"
#include "../task_proxy.h"
#include "../utils/collections.h"
#include <cmath>
using namespace std;
namespace potentials {
PotentialFunction::PotentialFunction(
const vector<vector<double>> &fact_potentials)
: fact_potentials(fact_potentials) {
}
int PotentialFunction::get_value(const State &state) const {
double heuristic_value = 0.0;
for (FactProxy fact : state) {
int var_id = fact.get_variable().get_id();
int value = fact.get_value();
assert(utils::in_bounds(var_id, fact_potentials));
assert(utils::in_bounds(value, fact_potentials[var_id]));
heuristic_value += fact_potentials[var_id][value];
}
const double epsilon = 0.01;
return static_cast<int>(ceil(heuristic_value - epsilon));
}
}
|
c646e728c76408c98a2bf5bbd76aefa51a370aa4
|
38bb20de12b93e9c99a11f70270759e2253f9e50
|
/Project/Source/MessageManager.cpp
|
cf17c0190e92a7f8656011eb46061e9190d81432
|
[] |
no_license
|
bullfrognz/Pool
|
c8eadf533791123b2e6cbe2aa221bb41e6ce23b1
|
9d2a5a2b0fa1ba3c6e6102d335c6f79e10a3e5b9
|
refs/heads/master
| 2020-04-06T03:51:46.140025
| 2014-05-24T03:30:06
| 2014-05-24T03:30:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,635
|
cpp
|
MessageManager.cpp
|
//
// Diploma of Interactive Gaming
// Game Development Faculty
// Media Design School
// Auckland
// New Zealand
//
// (c) 2011 Media Design School
//
// File Name : MessageManager.cpp
// Description : Template for implementation (source) files
// Author : Bryce Booth
// Mail : bryce.booth@mediadesign.school.nz
//
// Library Includes
// Local Includes
#include "MessageTarget.h"
// This Include
#include "MessageManager.h"
// Static Variables
// Static Function Prototypes
// Implementation
CMessageManager::CMessageManager()
{
//Empty
}
CMessageManager::~CMessageManager()
{
//Empty
}
bool
CMessageManager::AddMsgTarget(EKeyCode _iMsgCommand, IMessageTarget* _pLogTarget)
{
m_mmapTargetContainer.insert( std::pair<EKeyCode,IMessageTarget*>(_iMsgCommand,_pLogTarget) );
return (true);
}
bool
CMessageManager::RemoveMsgTarget(IMessageTarget* _pLogTarget)
{
std::multimap<EKeyCode,IMessageTarget*>::iterator Iter;
for (Iter = m_mmapTargetContainer.begin(); Iter != m_mmapTargetContainer.end(); )
{
if ((*Iter).second == _pLogTarget)
{
Iter = m_mmapTargetContainer.erase(Iter);
}
else
{
++Iter;
}
}
return (true);
}
bool
CMessageManager::ClearMsgTargets()
{
m_mmapTargetContainer.clear();
return true;
}
void
CMessageManager::SendMsgToTargets(EKeyCode _EKeyCode, WPARAM _wParam, LPARAM _lParam)
{
std::multimap<EKeyCode,IMessageTarget*>::iterator Iter;
for (Iter = m_mmapTargetContainer.begin(); Iter != m_mmapTargetContainer.end(); ++Iter )
{
if ((*Iter).first == _EKeyCode)
{
(*Iter).second->HandleMessage(_EKeyCode, _wParam, _lParam);
}
}
}
|
544aa49fb4207499ca749f233fc7e0d62aec8e3b
|
669951b6fc45543581f452a75831eaae77c3627c
|
/766-E/766-E-41612820.cpp
|
cf1c544c1ac7c22b99f6035458d9bbce03e12941
|
[] |
no_license
|
atharva-sarage/Codeforces-Competitive-Programming
|
4c0d65cb7f892ba8fa9fc58e539d1b50d0d7a9cb
|
c718f0693e905e97fbb48eb05981eeddafde108e
|
refs/heads/master
| 2020-06-10T01:12:17.336028
| 2019-06-24T16:43:32
| 2019-06-24T16:43:32
| 193,542,627
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 976
|
cpp
|
766-E-41612820.cpp
|
// nice one
#include<bits/stdc++.h>
using namespace std;
#define mx 100005
typedef int long long ll;
vector<ll> adj[mx];
ll dp[mx][30];
ll below[mx];
ll val[mx][30];
ll ans=0;
void addedge(ll u,ll v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
void dfs(ll u,ll par)
{
below[u]=1;
for(ll i=0;i<26;i++)
dp[u][i]=val[u][i];
for(ll i=0;i<adj[u].size();i++)
{
ll v=adj[u][i];
if(v==par)
continue;
dfs(v,u);
for(ll j=0;j<26;j++)
{
ans+=(1<<j)*dp[u][j]*(below[v]-dp[v][j]);
ans+=(1<<j)*dp[v][j]*(below[u]-dp[u][j]);
if(val[u][j]==0)
dp[u][j]+=dp[v][j];
else
dp[u][j]+=below[v]-dp[v][j];
}
below[u]+=below[v];
}
}
int main()
{
ll n,x,i,j,u,v;
cin>>n;
for(i=1;i<=n;i++)
{
cin>>x;
ans+=x;
j=0;
while(x)
{
if(x%2)
{
val[i][j]=1;
}
j++;
x/=2;
}
}
for(i=1;i<n;i++)
{
cin>>u>>v;
addedge(u,v);
}
dfs(1,-1);
cout<<ans<<endl;
}
|
b3797e90ab36ed606c4a1feca49b4037e5d6c8a4
|
04b1803adb6653ecb7cb827c4f4aa616afacf629
|
/third_party/blink/renderer/platform/fonts/canvas_rotation_in_vertical.h
|
62d6bb25c3f7f326ab6bb0395bbd49a6313f4826
|
[
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] |
permissive
|
Samsung/Castanets
|
240d9338e097b75b3f669604315b06f7cf129d64
|
4896f732fc747dfdcfcbac3d442f2d2d42df264a
|
refs/heads/castanets_76_dev
| 2023-08-31T09:01:04.744346
| 2021-07-30T04:56:25
| 2021-08-11T05:45:21
| 125,484,161
| 58
| 49
|
BSD-3-Clause
| 2022-10-16T19:31:26
| 2018-03-16T08:07:37
| null |
UTF-8
|
C++
| false
| false
| 437
|
h
|
canvas_rotation_in_vertical.h
|
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_FONTS_CANVAS_ROTATION_IN_VERTICAL_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_FONTS_CANVAS_ROTATION_IN_VERTICAL_H_
namespace blink {
enum class CanvasRotationInVertical : char { kRegular, kRotateCanvasUpright };
}
#endif
|
6c383d2d6316d87366a850092d40c3c3f8e72617
|
6f53e715ab0edeafc89cbf33941228314181c4cb
|
/Classes/Utility/Definition.h
|
9cae273dfda9f457a5b9cf7309569470a7e5df56
|
[] |
no_license
|
HuyenPhuong/mini
|
859a9b4450117ddc6ffea0b723a231d2787ea72e
|
e3a29eecebb5cdf2b2d5c34c801e17bdab8fdce2
|
refs/heads/master
| 2021-01-23T21:35:35.789464
| 2015-06-26T15:59:28
| 2015-06-26T15:59:28
| 38,119,254
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 459
|
h
|
Definition.h
|
#ifndef UTILITY_DEFINITION_H_
#define UTILITY_DEFINITION_H_
#define DISTANCE_SPAWN_MAX 280
#define DISTANCE_SPAWN_MIN 115
#define PILLAR_COLLISION 0x000001
#define NINJA_COLLISION 0x000002
#define WALL_COLLISION 0x000003
#define GROUND_COLLISION 0x000004
#define SPRING_COLLISION 0x000005
#define SCORE_COLLISION 0x000006
#include "cocos2d.h"
USING_NS_CC;
class Definition {
public:
Definition();
virtual ~Definition();
Point * buttonStart;
};
#endif
|
f649ac043239b57a8e0fd914fda2941fb7c14ec9
|
a42eb03dc1a430875b91c098d39c5e1c09f0b2a5
|
/include/TTable.h
|
a319bf29685fd51f6d9a299b1666b5183b06f5a5
|
[] |
no_license
|
unn-student-2ndyear/mp2-lab7-tables
|
fcf7100beee4bfee84218f8584d0185222a8df9a
|
3ca91312ba49d1d558af5558b13629430c591875
|
refs/heads/master
| 2020-05-29T20:29:38.659963
| 2019-05-30T06:01:20
| 2019-05-30T06:01:20
| 189,351,700
| 0
| 0
| null | 2019-05-30T05:34:15
| 2019-05-30T05:34:15
| null |
UTF-8
|
C++
| false
| false
| 1,673
|
h
|
TTable.h
|
#ifndef _TTABLE_H
#define _TTABLE_H
#include<iostream>
#include"TTabRecord.h"
#include"tdatacom.h"
using namespace std;
#define TabOK 0
#define TabEmpty -101
#define TabFull -102
#define TabNoRec -103
#define TabRecDbl -104
#define TabNoMem -105
class TTable : public TDataCom
{
protected:
int DataCount;
int Efficiency;
public:
TTable() { DataCount = 0; Efficiency = 0; }
virtual ~TTable() {};
// информационные методы
int GetDataCount() const { return DataCount; } // к-во записей
int GetEfficiency() const { return Efficiency; } // эффективность
int IsEmpty() const { return DataCount == 0; } //пуста?
virtual int IsFull() const = 0; // заполнена?
// основные методы
virtual PTDatValue FindRecord(TKey k) = 0; // найти запись
virtual void InsRecord(TKey k, PTDatValue pVal) = 0; // вставить
virtual void DelRecord(TKey k) = 0; // удалить запись
// навигация
virtual int Reset(void) = 0; // установить на первую запись
virtual int IsTabEnded(void) const = 0; // таблица завершена?
virtual int GoNext(void) = 0; // переход к следующей записи
// (=1 после применения для последней записи таблицы)
virtual TKey GetKey(void) const = 0;
virtual PTDatValue GetValuePTR(void) const = 0;
friend ostream & operator<<(ostream &os, TTable &tab)
{
cout << "Table" << endl;
for (tab.Reset(); !tab.IsTabEnded(); tab.GoNext())
{
os << "Name: " << tab.GetKey();
}
return os;
}
};
#endif
|
fd013ae158f4e5120bcaabe30a280ae19a3f51e2
|
5a02eac79d5b8590a88209dcc6cd5741323bb5de
|
/PAT/第一轮/第九章_树/并查集/书上例题/main.cpp
|
5f3079fdbfaae38280c09d34b18bad7ea2ea22c3
|
[] |
no_license
|
qiatongxueshaonianC/CaiZebin-Code_warehouse
|
ddac8252afb207d9580856cfbb7e14f868432716
|
25e1f32c7d86d81327a0d9f08cd7462209e9fec2
|
refs/heads/master
| 2023-03-20T03:36:49.088871
| 2021-03-16T15:40:11
| 2021-03-16T15:40:11
| 348,395,087
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 677
|
cpp
|
main.cpp
|
#include<bits/stdc++.h>
using namespace std;
const int maxn=110;
int father[maxn];
int findFather(int s){
if(father[s]==s) return s;
int temp=findFather(father[s]);
father[s]=temp;
return temp;
}
int main() {
int n,m,isRoot[maxn];
iota(father,father+maxn,0);
scanf("%d%d",&n,&m);
int u,v;
for(int i=0;i<m;i++){
scanf("%d%d",&u,&v);
int fa=findFather(u);
int fb=findFather(v);
if(fa!=fb){
father[fb]=fa;
}
}
memset(isRoot,0,sizeof(isRoot));
for(int i=1;i<=n;i++)
isRoot[findFather(i)]++;
printf("%d",n-count(isRoot+1,isRoot+n+1,0)); //左闭右开,由于下标是从1开始,所以要n+1
return 0;
}
/*
4 2
1 4
2 3
7 5
1 2
2 3
3 1
1 4
5 6
*/
|
00157a5a3d82fdb384f744b93498d930521a2091
|
12cc19461c3c4f2cac0105ada2baae26bd58bc9e
|
/src/core/ChSmartpointers.h
|
07cf882949960fa8f83b2b96ec313b127dad4b14
|
[
"BSD-3-Clause"
] |
permissive
|
giovannifortese/chrono
|
b3fc96882ace6fdf0ff1a9fc266a553e90d05e41
|
16204177fd72b48c2eb7cc3f7a0e702e831d6234
|
refs/heads/develop
| 2021-01-16T21:38:57.995094
| 2015-02-03T22:41:02
| 2015-02-03T22:41:02
| 30,302,090
| 1
| 0
| null | 2015-02-04T14:17:47
| 2015-02-04T14:17:46
| null |
UTF-8
|
C++
| false
| false
| 18,363
|
h
|
ChSmartpointers.h
|
//
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2010-2012 Alessandro Tasora
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file at the top level of the distribution
// and at http://projectchrono.org/license-chrono.txt.
//
#ifndef CHSMARTPOINTERS_H
#define CHSMARTPOINTERS_H
//////////////////////////////////////////////////
//
// ChSmartpointers.h
//
// ------------------------------------------------
// www.deltaknowledge.com
// ------------------------------------------------
///////////////////////////////////////////////////
#include <stdexcept>
namespace chrono
{
/// [See nice article on shared pointers at:
/// http://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one.
/// See also the chrono demo demo_sharedptr.cpp]
/// The class ChSmartPtr wraps a 'bare' C++ pointer in order
/// to manage the lifetime of the object being pointed to by the
/// bare pointer. With 'bare' C++ pointers, the programmer has to
/// explicitly destroy the object when it is no longer useful.
/// A ChSmartPtr object by comparison defines a policy
/// as to when the object pointed to by the bare pointer is
/// to be destroyed. You still have to create the object, but
/// you no longer have to worry about destroying it.
/// It should be initialized in one of the following two ways:
/// ChSmartPtr<MyClass> foo_pointer(new MyClass);
/// or
/// ChSmartPtr<MyClass> foo_pointer(another_smart_pointer);
/// In doing so, you will _never_ need to call 'delete', because
/// the reference count mechanism will automatically delete the
/// 'bare' pointer when no other smart pointer reference it.
/// NOTE1: When copied, a ChSmartPtr object does not perform copy
/// of the data pointed to by the 'bare' pointer.
/// NOTE2: Unlike with the ChSharedPtr class, the 'bare' pointer
/// does not need to point to an object that inherits from
/// ChShared because ChSmartPtr uses an auxiliary reference counter
/// that is allocated on the heap.
template <class T>
class ChSmartPtr
{
// Make all ChSmartPtr as friend classes, so that they can access each other itsCounter quickly, in casting
template <typename TT> friend class ChSmartPtr;
public:
typedef T element_type;
/// Constructor for initializing with dynamically allocated data, with new()
/// Mandatory way of using it:
/// ChSmartPtr<MyClass> pointerA(new MyClass);
/// Thank to automatic reference counting, you never have to call delete()!
explicit ChSmartPtr(T* p = 0)
: itsCounter(0)
{
if (p) itsCounter = new ChCounter (p);
}
/// Copy constructor for the case
/// ChSmartPtr<MyClassA> pointerA(pointerB);
ChSmartPtr(const ChSmartPtr& r) throw()
{
acquire(r);
}
/// Copy constructor and converter for the case
/// ChSmartPtr<MyClassA> pointerA(pointerB);
/// when pointerB comes from a class MyClassB which is inherited from MyClassA.
template <class T_other>
ChSmartPtr(const ChSmartPtr<T_other>& r) throw()
{
acquire (r);
}
/// Destructor decrements the reference count and automatically delete only
/// when the last reference is destroyed
~ChSmartPtr()
{
release();
}
/// Bool type casting, true if the pointer is still bound to an object, or
/// false if unbound and invalidated (ex. after unsuccesfull casting). Example:
/// if(mysharedptr) {...}
// Trick to avoid problems as in http://www.artima.com/cppsource/safebool2.html
// In future C++0x will be simply:
// explicit operator bool() const { return ptr!=0; }
typedef void (ChSmartPtr::*bool_type)() const;
void this_type_does_not_support_comparisons() const {}
operator bool_type() const
{
if (itsCounter)
return itsCounter->ptr!=0 ? &ChSmartPtr::this_type_does_not_support_comparisons : 0;
else
return 0;
}
/// Assignment form for an already-constructed smart-pointer.
ChSmartPtr& operator=(const ChSmartPtr& r)
{
if (this != &r) {
release();
acquire(r);
}
return *this;
}
/// Dereference the smart pointer to get the object, as in the form *p1
T& operator*() throw() {return *itsCounter->ptr;}
const T& operator*() const throw() {return *itsCounter->ptr;}
/// Used for member access to the contained object,
/// e.g. pointer->Print() calls T::Print()
T* operator->() throw() {return itsCounter->ptr;}
const T* operator->(void) const throw() {return itsCounter->ptr;}
/// Tells if this is shared by no one else.
bool IsUnique() const throw()
{return (itsCounter ? itsCounter->count == 1 : true);}
/// Returns the raw pointer to pointed instance.
/// Note: If a correct programming style is used, you should
/// never need to use this.
T* get_ptr() const throw() {return itsCounter ? itsCounter->ptr : 0;}
T* get() const throw() {return itsCounter ? itsCounter->ptr : 0;}
/// Occasionally, the shared pointer can be invalidated (unbound from
/// object), for instance if you create it with null default
/// ChSharedPtr<MyClass> pointerA; instead of typical
/// ChSharedPtr<MyClass> pointerA(new MyClass);
bool IsNull() const throw() {return itsCounter ? itsCounter->ptr==0 : true;};
/// Unbind the shared pointer from referenced shared object,
/// and automatically delete in case of last reference. It should
/// be used sparingly, because this unbinding already happens automatically
/// when the shared pointer dies. Use this only to 'force' premature unbinding.
void SetNull() { this->release(); }
/// Tells if the referenced object is inherited from a specific class
/// and can be cast with copy constructor, for example
/// if (ptrA.IsType<classB>() ) { ChSharedPtr<classB> ptrB (ptrA); }
/// NOTE: this requires polymorphism: classA & classB MUST have 'virtual' destructors
template <class T_other>
bool IsType() { return itsCounter ? dynamic_cast<T_other*>(this->get_ptr()) : false ;}
/// This works like dynamic_cast, but for shared pointers.
/// If it does not succeed, returns an empty pointer.
/// For example
/// ChSharedPtr<classA> ma = mb.DynamicCastTo<classA>();
/// NOTE: this requires polymorphism: classA & classB MUST have 'virtual' destructors
template <class T_other>
ChSmartPtr<T_other> DynamicCastTo() const
{
ChSmartPtr<T_other> result;
if (itsCounter)
{
if (dynamic_cast<T_other*>(this->itsCounter->ptr))
{
result.itsCounter = ((ChSmartPtr<T_other>*)this)->itsCounter; // This casting is a weird hack, might be improved..
++itsCounter->count;
}
}
return result;
}
/// This works like static_cast, but for shared pointers.
/// For example
/// ChSharedPtr<classA> ma = mb.StaticCastTo<classA>();
/// NOTE: no check on correctness of casting (use DynamicCastTo if this is required)
template <class T_other>
ChSmartPtr<T_other> StaticCastTo() const
{
ChSmartPtr<T_other> result;
if (itsCounter)
{
static_cast<T_other*>(this->itsCounter->ptr); // just to popup errors in compile time.
{
result.itsCounter = ((ChSmartPtr<T_other>*)this)->itsCounter; // This casting is a weird hack, might be improved..
++itsCounter->count;
}
}
return result;
}
/// Tells how many references to the pointed object. (Return 0 if empty pointer).
int ReferenceCounter() { return itsCounter ? itsCounter->count : 0 ;}
private:
class ChCounter
{
public:
ChCounter(T* p = 0, unsigned int c = 1) : ptr(p), count(c) {}
T* ptr;
unsigned int count;
}* itsCounter;
// increment the count
template <class T_other>
void acquire(const ChSmartPtr<T_other> &r) throw()
{
T_other* source_ptr=0; T* dest_ptr = source_ptr; // Just to popup compile-time cast errors.
itsCounter = ((ChSmartPtr<T>*)&r)->itsCounter; // This casting is a weird hack, might be improved..
if (itsCounter) ++itsCounter->count;
}
// decrement the count, delete if it is 0
void release()
{
if (itsCounter) {
if (--itsCounter->count == 0)
{
delete (T*)(itsCounter->ptr);
delete itsCounter;
}
itsCounter = 0;
}
}
};
// Equivalent of dynamic_cast<>() for the ChSmartPtr
template<typename Tout, typename Tin>
inline ChSmartPtr<Tout>
dynamic_cast_chshared(const ChSmartPtr<Tin>& __r)
{
return __r.template DynamicCastTo<Tout>();
}
// Equivalent of static_cast<>() for the ChSmartPtr
template<typename Tout, typename Tin>
inline ChSmartPtr<Tout>
static_cast_chshared(const ChSmartPtr<Tin>& __r)
{
return __r.template StaticCastTo<Tout>();
}
// Comparisons operators are required for using the shared pointer
// class in an STL container
template<typename T>
bool operator==(const ChSmartPtr<T>& left, const ChSmartPtr<T>& right)
{
if (left.get_ptr() == right.get_ptr()) return true;
return *left == *right;
}
template<typename T>
bool operator<(const ChSmartPtr<T>& left, const ChSmartPtr<T>& right)
{
if (left.get_ptr() == right.get_ptr()) return false;
return *left < *right;
}
// Trick to avoid problems as in http://www.artima.com/cppsource/safebool2.html
// Not needed in future C++0x when we'll use simply:
// explicit operator bool() const { return ptr!=0; }
template <typename T, typename R >
bool operator!=(const ChSmartPtr< T >& lhs,const R& rhs) {
lhs.this_type_does_not_support_comparisons();
return false;
}
template <typename T, typename R >
bool operator==(const ChSmartPtr< T >& lhs,const R& rhs) {
lhs.this_type_does_not_support_comparisons();
return false;
}
/////////////////////////////////////////////////////////////////////
/// [See nice article on shared pointers at:
/// http://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one.
/// See also the chrono demo demo_sharedptr.cpp]
/// The class ChSharedPtr wraps a 'bare' C++ pointer in order
/// to manage the lifetime of the object being pointed to by the
/// bare pointer. With 'bare' C++ pointers, the programmer has to
/// explicitly destroy the object when it is no longer useful.
/// A ChSharedPtr object by comparison defines a policy
/// as to when the object pointed to by the bare pointer is
/// to be destroyed. You still have to create the object, but
/// you no longer have to worry about destroying it.
/// It should be initialized in one of the following two ways:
/// ChSharedPtr<MyClass> foo_pointer(new MyClass);
/// or
/// ChSharedPtr<MyClass> foo_pointer(another_shared_pointer);
/// In doing so, you will _never_ need to call 'delete', because
/// the reference count mechanism will automatically delete the
/// 'bare' pointer when no other smart pointer reference it.
/// NOTE1: When copied, a ChSharedPtr object does not perform copy
/// of the data pointed to by the 'bare' pointer.
/// NOTE2: Unlike with the ChSmartPtr class, which can manage
/// any 'bare' pointer at the price of some overhead (counter
/// placed on the heap), the ChSharedPtr only works for 'bare'
/// pointers that point to an object that inherits from
/// ChShared.
template <class T>
class ChSharedPtr
{
// Make all ChSharedPtr as friend classes, so that they can access each other ptr quickly, in casting
template <typename TT> friend class ChSharedPtr;
public:
typedef T element_type;
/// Constructor for initializing with dynamically allocated data, with new()
/// Mandatory way of using it:
/// ChSharedPtr<MyClass> pointerA(new MyClass);
/// Thank to automatic reference counting, you never have to call delete()!
explicit ChSharedPtr(T* p = 0)
{
ptr = p;
}
/// Copy constructor for the case
/// ChSharedPtr<MyClassA> pointerA(pointerB);
ChSharedPtr(const ChSharedPtr& r) throw()
{
acquire(r);
}
/// Copy constructor and converter for the case
/// ChSharedPtr<MyClassA> pointerA(pointerB);
/// when pointerB type is a class MyClassB which is inherited from MyClassA.
template <class T_other>
ChSharedPtr(const ChSharedPtr<T_other>& r) throw()
{
acquire (r);
}
/// Destructor decrements the reference count and automatically delete only
/// when the last reference is destroyed
~ChSharedPtr()
{
release();
}
/// Bool type casting, true if the pointer is still bound to an object, or
/// false if unbound and invalidated (ex. after unsuccesfull casting). Example:
/// if(mysharedptr) {...}
// Trick to avoid problems as in http://www.artima.com/cppsource/safebool2.html
// In future C++0x will be simply:
// explicit operator bool() const { return ptr!=0; }
typedef void (ChSharedPtr::*bool_type)() const;
void this_type_does_not_support_comparisons() const {}
operator bool_type() const
{
return ptr!=0 ? &ChSharedPtr::this_type_does_not_support_comparisons : 0;
}
/// Assignment form for an already-constructed smart-pointer.
ChSharedPtr& operator=(const ChSharedPtr& r)
{
if (this != &r)
{
release();
acquire(r);
}
return *this;
}
/// Dereference the smart pointer to get the object, as in the form *p1
T& operator*() throw() {return *ptr;}
const T& operator*() const throw() {return *ptr;}
/// Used for member access to the contained object,
/// e.g. pointer->Print() calls T::Print()
T* operator->() throw() {return ptr;}
const T* operator->(void) const throw() {return ptr;}
/// Tells if this is shared by no one else.
bool IsUnique() const throw()
{return (ptr ? ptr->ReferenceCount() == 1 : true);}
/// Returns the raw pointer to pointed instance.
/// Note: If a correct programming style is used, you should
/// never need to use this.
T* get_ptr() const throw() {return ptr;}
T* get() const throw() {return ptr;}
/// Occasionally, the shared pointer can be invalidated (unbound from
/// object), for instance if you create it with null default
/// ChSharedPtr<MyClass> pointerA; instead of typical
/// ChSharedPtr<MyClass> pointerA(new MyClass);
bool IsNull() const throw() {return ptr == 0;};
/// Unbind the shared pointer from referenced shared object,
/// and automatically delete in case of last reference. It should
/// be used sparingly, because this unbinding already happens automatically
/// when the shared pointer dies. Use this only to 'force' premature unbinding.
void SetNull() { this->release(); ptr =0;}
/// Tells if the referenced object is inherited from a specific class
/// and can be cast with copy constructor, for example
/// if (ptrA.IsType<classB>() ) { ChSharedPtr<classB> ptrB (ptrA); }
/// NOTE: this requires polymorphism: classA & classB MUST have 'virtual' destructors
template <class T_other>
bool IsType() { if (dynamic_cast<T_other*>(ptr)) return true; else return false; }
/// This works like dynamic_cast, but for shared pointers.
/// If it does not succeed, returns an empty pointer.
/// For example
/// ChSharedPtr<classA> ma = mb.DynamicCastTo<classA>();
/// NOTE: this requires polymorphism: classA & classB MUST have 'virtual' destructors
template <class T_other>
ChSharedPtr<T_other> DynamicCastTo() const
{
ChSharedPtr<T_other> result;
if ( (result.ptr = dynamic_cast<T_other*>(this->ptr)) )
{
result.ptr->AddRef();
}
return result;
}
/// This works like static_cast, but for shared pointers.
/// For example
/// ChSharedPtr<classA> ma = mb.StaticCastTo<classA>();
/// NOTE: no runtime check on correctness of casting (use DynamicCastTo if required)
template <class T_other>
ChSharedPtr<T_other> StaticCastTo() const
{
ChSharedPtr<T_other> result;
result.ptr = static_cast<T_other*>(this->ptr);
result.ptr->AddRef();
return result;
}
/// Tells how many references to the pointed object. (Return 0 if empty pointer).
int ReferenceCounter() { return ptr ? ptr->ReferenceCount() : 0 ;}
private:
T* ptr;
// increment the count
template <class T_other>
void acquire(const ChSharedPtr<T_other>& r) throw()
{
ptr = r.ptr;
if (ptr)
{
ptr->AddRef();
}
}
// decrement the count, delete if it is 0
void release()
{
// this should automatically delete the object when its ref.counter goes to 0.
if (ptr)
{
ptr->RemoveRef();
}
}
};
/// Equivalent of dynamic_cast<>() for the ChSharedPtr, for example:
/// ChSharedPtr<classB> pB = dynamic_cast_chshared<classB>(pA);
/// NOTE: this requires polymorphism: classA & classB MUST have 'virtual' destructors
template<typename Tout, typename Tin>
inline ChSharedPtr<Tout>
dynamic_cast_chshared(const ChSharedPtr<Tin>& __r)
{
return __r.template DynamicCastTo<Tout>();
}
/// Equivalent of static_cast<>() for the ChSharedPtr, for example:
/// ChSharedPtr<classB> pB = static_cast_chshared<classB>(pA);
template<typename Tout, typename Tin>
inline ChSharedPtr<Tout>
static_cast_chshared(const ChSharedPtr<Tin>& __r)
{
return __r.template StaticCastTo<Tout>();
}
// Comparisons operators are required for using the shared pointer
// class in an STL container
template<typename T>
bool operator==(const ChSharedPtr<T>& left, const ChSharedPtr<T>& right)
{
if (left.get_ptr() == right.get_ptr()) return true;
return *left == *right;
}
template<typename T>
bool operator<(const ChSharedPtr<T>& left, const ChSharedPtr<T>& right)
{
if (left.get_ptr() == right.get_ptr()) return false;
return *left < *right;
}
// Trick to avoid problems as in http://www.artima.com/cppsource/safebool2.html
// Not needed in future C++0x when we'll use simply:
// explicit operator bool() const { return ptr!=0; }
template <typename T, typename R >
bool operator!=(const ChSharedPtr< T >& lhs,const R& rhs) {
lhs.this_type_does_not_support_comparisons();
return false;
}
template <typename T, typename R >
bool operator==(const ChSharedPtr< T >& lhs,const R& rhs) {
lhs.this_type_does_not_support_comparisons();
return false;
}
} // END_OF_NAMESPACE____
#endif
|
9a8d30523b52ce87981f045876562810ed933137
|
a2c19e2746d6b5f18a01ae1aa5222a4e61d021c3
|
/tunnel_graph/src/Tunnel/Tunnel.cpp
|
65d659aeb091aebc0305cbbca1fdb0c70a9578d4
|
[] |
no_license
|
przemyslawkrajewski/Ziemniaki
|
78c009a982fcf586e822d99bd04eb8b8cc8ba4d1
|
8a92a8a02d1aaf6aafd13c30d2fc00f169a26ea7
|
refs/heads/master
| 2020-03-06T18:52:57.473017
| 2018-05-22T19:56:30
| 2018-05-22T19:56:30
| 127,015,829
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,970
|
cpp
|
Tunnel.cpp
|
/*
* Tunnel.cpp
*
* Created on: 5 maj 2018
* Author: przemo
*/
#include "Tunnel.h"
Tunnel::Tunnel()
{
//Temporary for testing
tunnelNodes.push_back(TunnelNode(Point(50,200,0),10));
tunnelNodes.push_back(TunnelNode(Point(200,50,0),10));
tunnelNodes.push_back(TunnelNode(Point(200,400,0),10));
tunnelNodes.push_back(TunnelNode(Point(400,200,0),10));
tunnelNodes.push_back(TunnelNode(Point(600,50,0),10));
tunnelNodes.push_back(TunnelNode(Point(600,400,0),10));
std::vector<TunnelNode*> ptrs;
for(auto it = tunnelNodes.begin(); it != tunnelNodes.end() ;it++)
{
ptrs.push_back(&(*it));
}
tunnelLinks.push_back(TunnelLink(ptrs[0],ptrs[1],5));
tunnelLinks.push_back(TunnelLink(ptrs[0],ptrs[2],5));
tunnelLinks.push_back(TunnelLink(ptrs[1],ptrs[2],5));
tunnelLinks.push_back(TunnelLink(ptrs[1],ptrs[3],5));
tunnelLinks.push_back(TunnelLink(ptrs[2],ptrs[3],5));
tunnelLinks.push_back(TunnelLink(ptrs[4],ptrs[3],5));
tunnelLinks.push_back(TunnelLink(ptrs[2],ptrs[5],5));
tunnelLinks.push_back(TunnelLink(ptrs[4],ptrs[5],5));
}
//TODO to remove later
void Tunnel::printTunnels()
{
cv::Mat img;
img = cv::Mat(1000, 800, CV_8UC3);
for(int y = 0 ; y < img.rows ; y++)
{
uchar* ptr = img.ptr((int)y);
for(int x = 0 ; x < img.cols*3 ; x++)
{
*ptr=0;
ptr = ptr+1;
}
}
for(auto it = tunnelNodes.begin(); it != tunnelNodes.end() ;it++)
{
cv::Point p;
p.x = it->getCoordinates().x;
p.y = it->getCoordinates().y;
cv::circle(img, p,it->getRadius(), cv::Scalar(255,255,255), CV_FILLED);
}
for(auto it = tunnelLinks.begin(); it != tunnelLinks.end() ;it++)
{
cv::Point p1;
p1.x = it->getNodes()->first->getCoordinates().x;
p1.y = it->getNodes()->first->getCoordinates().y;
cv::Point p2;
p2.x = it->getNodes()->second->getCoordinates().x;
p2.y = it->getNodes()->second->getCoordinates().y;
cv::line(img, p1, p2, cv::Scalar(255,255,255), it->getWidth());
}
imshow("Tunnels", img);
cv::waitKey(20000);
}
|
44eb191005e73e94c1fbce18d4044af389ee4023
|
244231ebd1a44da9e9b3a2394e2a9d018c824bdf
|
/数据结构、算法与应用-C++语言描述(第二版)/Chapter_6 线性表-链式描述/binSort.h
|
05149b2b3fcabd8db5bbb141cc30c94e09d5f808
|
[] |
no_license
|
lchy1037/Algorithm-Notes
|
df7e4576a4fe040f579ff27217c915ea2d7e158a
|
5c0516fc1da685dc0b6b51ecd82166705482f3b3
|
refs/heads/master
| 2021-01-20T07:18:46.951135
| 2017-09-20T12:05:46
| 2017-09-20T12:05:46
| 101,531,372
| 3
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,259
|
h
|
binSort.h
|
#ifndef BIN_SORT_H
#define BIN_SORT_H
// 箱子排序:首先把分数相同的节点放在同一个箱子里,然后把箱子链接起来就得到有序的链表
#include <iostream>
#include <string>
#include "chain.h"
using namespace std;
struct studentRecord{
int score;
string *name;
int operator!=(const studentRecord& x) const {return (score != x.score);}
operator int() const {return score;}
};
ostream& operator<<(ostream& out, const studentrecord& x){
out << x.score << " " << *x.name << endl;
return out;
}
void binSort(chain<studentRecord>& theChain, int range){ // 按分数排序
// 对箱子初始化
chain<studentRecord> *bin;
bin = new chain<studentRecord>[range+1];
// 把学生记录从链表中取出,然后分配到箱子里
int numberOfElements = theChain.size();
for (int i = 0; i < numberOfElements; ++i){
studentRecord x = theChain.get(0);
theChain.erase(0);
bin[x.score].insert(0, x);
}
// 从箱子中收集元素
for (int j = range; j >= 0; --j){
while (!bin[j].empty()){
studentRecord x = bin[j].get(0);
bin[j].erase(0);
theChain.insert(0, x);
}
}
delete [] bin;
}
#endif
|
5ac7e1f050a52e37f165f956aaeaf1a2f227a6e6
|
c818531460ce87a6e6874fd154f2998dcac29fbe
|
/tablemodel.h
|
8e250bcba3e58de489db225468c68531d6714024
|
[] |
no_license
|
Junyang-Xie/XJYsSniffer
|
48e36fa5a56b33571297ec0205a89c4f61792ef4
|
ed9836282e5dedb0a8b09829267bacb3a30d0b6a
|
refs/heads/master
| 2021-05-06T05:51:33.732071
| 2017-12-23T12:41:23
| 2017-12-23T12:41:23
| 115,177,658
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 871
|
h
|
tablemodel.h
|
#ifndef TABLEVIEW_H
#define TABLEVIEW_H
#include "necessary.h"
#include <QStandardItemModel>
#include <QList>
#include <QStandardItem>
#include <QItemSelection>
class tableModel:public QObject{
Q_OBJECT
private:
int colNum;
QStandardItemModel M;
QList<const unsigned char*> rawData;
int index;
public:
QList<QList<QString>> sniffered;
QList<QList<QStandardItem*>> treeData;
tableModel(QList<QString> *sList);
QList<SnifferData *> Data;
tableModel();
~tableModel();
void addItemList(QList<QString> *New);
void addItemTree(QStandardItem *New);
void clearAll();
void clearTable();
void reBuild();
int showIndex();
QStandardItemModel *Model();
void selectRowChanged(const QItemSelection &selected);
signals:
void treeViewUpgrade(QList<QStandardItem *> *treeItem);
};
#endif // TABLEVIEW_H
|
683998acb65118712ae77cd5f8577cb51b20b104
|
ab513fbacf6f85853cccaa04e295cc8083f51482
|
/2nd Semester/Object Oriented Programming /Lecture/Code/Lecture9_demo/Lecture9_demo_Hello_world/lecture9_demo_hello_world.h
|
879776432f78bbe2ac928c0309cf9113a92ed28c
|
[] |
no_license
|
galoscar07/college2k16-2k19
|
1ee23e6690e4e5ac3ab9a8ed9792ebbeaecddbf6
|
a944bdbc13977aa6782e9eb83a97000aa58a9a93
|
refs/heads/master
| 2023-01-09T15:59:07.882933
| 2019-06-24T12:06:32
| 2019-06-24T12:06:32
| 167,170,983
| 1
| 1
| null | 2023-01-04T18:21:31
| 2019-01-23T11:22:29
|
Python
|
UTF-8
|
C++
| false
| false
| 395
|
h
|
lecture9_demo_hello_world.h
|
#ifndef LECTURE9_DEMO_HELLO_WORLD_H
#define LECTURE9_DEMO_HELLO_WORLD_H
#include <QtWidgets/QMainWindow>
#include "ui_lecture9_demo_hello_world.h"
class Lecture9_demo_Hello_world : public QMainWindow
{
Q_OBJECT
public:
Lecture9_demo_Hello_world(QWidget *parent = 0);
~Lecture9_demo_Hello_world();
private:
Ui::Lecture9_demo_Hello_worldClass ui;
};
#endif // LECTURE9_DEMO_HELLO_WORLD_H
|
348f50e4dbe62ff6a3a67b8de246bd77929ee7a9
|
f699576e623d90d2e07d6c43659a805d12b92733
|
/WTLOnline-SDK/SDK/WTLOnline_UI_PDA_QuestLog_RequiredMonsterKill_classes.hpp
|
212f9aea9b5a89c4c62e6c65d8102fcd90a529df
|
[] |
no_license
|
ue4sdk/WTLOnline-SDK
|
2309620c809efeb45ba9ebd2fc528fa2461b9ca0
|
ff244cd4118c54ab2048ba0632b59ced111c405c
|
refs/heads/master
| 2022-07-12T13:02:09.999748
| 2019-04-22T08:22:35
| 2019-04-22T08:22:35
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 850
|
hpp
|
WTLOnline_UI_PDA_QuestLog_RequiredMonsterKill_classes.hpp
|
#pragma once
// Will To Live Online (0.57) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "WTLOnline_UI_PDA_QuestLog_RequiredMonsterKill_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// WidgetBlueprintGeneratedClass UI_PDA_QuestLog_RequiredMonsterKill.UI_PDA_QuestLog_RequiredMonsterKill_C
// 0x0000 (0x0250 - 0x0250)
class UUI_PDA_QuestLog_RequiredMonsterKill_C : public UWTLPDAQuestLogRequiredMonsterKill
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindObject<UClass>(_xor_("WidgetBlueprintGeneratedClass UI_PDA_QuestLog_RequiredMonsterKill.UI_PDA_QuestLog_RequiredMonsterKill_C"));
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
1b610666013db730ad384ebb237f7cd229751738
|
2cbe5aa318b15cad457d70361f35cbb1e18702a3
|
/lib/arduino/MP_SDM_SERIAL2/MP_SDM_SERIAL2.cpp
|
79aded9aab2787880bf4f2d181a7b130c4042227
|
[] |
no_license
|
MakerPlayground/MakerPlayground_Library
|
ae27fb2b17d5784698d3623a419fc36430c83b9d
|
d427453f0a785e3be0282a25fb0b81b8b91ffcfe
|
refs/heads/master
| 2022-12-22T04:05:38.819260
| 2020-09-10T09:09:22
| 2020-09-10T09:09:22
| 143,995,795
| 0
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,312
|
cpp
|
MP_SDM_SERIAL2.cpp
|
#include "MP_SDM_SERIAL2.h"
MP_SDM_SERIAL2::MP_SDM_SERIAL2()
: sdm(SDM(Serial2, 9600, NOT_A_PIN, SERIAL_8N1, false))
{
}
int MP_SDM_SERIAL2::init()
{
sdm.begin();
return MP_ERR_OK;
}
void MP_SDM_SERIAL2::update(unsigned long current_time)
{
current = sdm.readVal(SDM220T_CURRENT);
voltage = sdm.readVal(SDM220T_VOLTAGE);
power = sdm.readVal(SDM220T_POWER);
frequency = sdm.readVal(SDM220T_FREQUENCY);
active_apparent_power = sdm.readVal(SDM220T_ACTIVE_APPARENT_POWER);
reactive_apparent_power = sdm.readVal(SDM220T_REACTIVE_APPARENT_POWER);
total_active_energy = sdm.readVal(SDM220T_TOTAL_ACTIVE_ENERGY);
total_reactive_energy = sdm.readVal(SDM220T_TOTAL_REACTIVE_ENERGY);
power_factor = sdm.readVal(SDM220T_POWER_FACTOR);
phase_angle = sdm.readVal(SDM220T_PHASE_ANGLE);
}
void MP_SDM_SERIAL2::printStatus()
{
Serial.print(F("current = "));
Serial.println(current, 3);
Serial.print(F("voltage = "));
Serial.println(voltage, 3);
Serial.print(F("power = "));
Serial.println(power, 3);
Serial.print(F("frequency = "));
Serial.println(frequency, 3);
Serial.print(F("active_apparent_power = "));
Serial.println(active_apparent_power, 3);
Serial.print(F("reactive_apparent_power = "));
Serial.println(reactive_apparent_power, 3);
Serial.print(F("total_active_energy = "));
Serial.println(total_active_energy, 3);
Serial.print(F("total_reactive_energy = "));
Serial.println(total_reactive_energy, 3);
Serial.print(F("power_factor = "));
Serial.println(power_factor, 3);
Serial.print(F("phase_angle = "));
Serial.println(phase_angle, 3);
}
double MP_SDM_SERIAL2::getCurrent()
{
return current;
}
double MP_SDM_SERIAL2::getVoltage()
{
return voltage;
}
double MP_SDM_SERIAL2::getPower()
{
return power;
}
double MP_SDM_SERIAL2::getFrequency()
{
return frequency;
}
double MP_SDM_SERIAL2::getActive_Apparent_Power()
{
return active_apparent_power;
}
double MP_SDM_SERIAL2::getReactive_Apparent_Power()
{
return reactive_apparent_power;
}
double MP_SDM_SERIAL2::getTotal_Active_Energy()
{
return total_active_energy;
}
double MP_SDM_SERIAL2::getTotal_Reactive_Energy()
{
return total_reactive_energy;
}
double MP_SDM_SERIAL2::getPower_Factor()
{
return power_factor;
}
double MP_SDM_SERIAL2::getPhase_Angle()
{
return phase_angle;
}
|
a9c3b2b01eac5f0787dc961c60021f79ff5860d4
|
494ce6c9d87abb4e21916a761a11656e0d90a10a
|
/Library.cpp
|
f302d252b6e6101f8adaf8d81f6912e852e54f9d
|
[] |
no_license
|
parenoj/Library-Simulator
|
76c46492b55385e7f5bc8c32a6587a1402f56496
|
429eb16fef2fe2a01715a77b3384fd1280333849
|
refs/heads/master
| 2021-01-24T06:13:10.683996
| 2015-04-09T07:10:30
| 2015-04-09T07:10:30
| 33,653,793
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 14,960
|
cpp
|
Library.cpp
|
/*************************************************************
* Author: Justin Pareno
* Date: March 11, 2015
* Description: This is the Library class implementation file.
*************************************************************/
#include "Library.hpp"
#include "Patron.hpp"
#include "Book.hpp"
#include <iostream>
#include <iomanip>
using namespace std;
Library::Library() //Default Constructor
{
currentDate = 0;
holdings.reserve(100); //Increased capacity to 100
members.reserve(100); //Increased capacity to 100
}
/**************************************************
* Description: The addBook function adds a book object
* to the Library's holdings vector. It
* checks that the ID is unique.
* Parameters: none.
**************************************************/
void Library::addBook()
{
string tempIdCode, tempTitle, tempAuthor; //Temporary variables for object creation.
cout << "You've chosen to add a book to the Library's holdings." << endl;
cout << "Please enter a unique ID Code for this book: ";
getline(cin, tempIdCode);
//Check that ID is Unique
if(uniqueBook(tempIdCode))
{
cout << "Please enter the book's title: ";
getline(cin, tempTitle);
cout << "Please enter the book's author: ";
getline(cin, tempAuthor);
Book tempBook(tempIdCode, tempTitle, tempAuthor); //create object with user-inputted information
holdings.push_back(tempBook); //add object to the holdings vector
}
else
{
cout << "Book ID already in use." << endl;
}
}
/*************************************************
* Description: The addMember function adds a Patron
* object to the Library's members vector.
* It checks that the ID is unique.
* Parameters: none.
**************************************************/
void Library::addMember()
{
string tempIdCode, tempName; //Temporary variables for object creation.
cout << "You've chosen to add a Patron to the Library's system." << endl;
cout << "Please enter a unique ID Code for the Patron: ";
getline(cin, tempIdCode);
//Check that ID is Unique
if(uniquePatron(tempIdCode))
{
cout << "Please enter the Patron's name: ";
getline(cin, tempName);
Patron tempPatron(tempIdCode, tempName); //create object with user-inputted information
members.push_back(tempPatron); //add object to the members vector
}
else
{
cout << "Patron ID already in use." << endl;
}
}
/***************************************************
* Description: the checkOutBook function allows the
* user to check out a specified book to
* a specified patron. It also takes into
* account if the book is on request or
* already checked out.
* Parameters: patron ID of the patron wanting to check
* out a book and the book ID of the book
* being checked out.
*****************************************************/
void Library::checkOutBook(string patronId, string bookId)
{
//Check for Valid Patron ID and Book ID
if(!validPatron(patronId) || !validBook(bookId))
{
cout << "Invalid ID." << endl;
}
for(int index = 0; index < holdings.size(); index++) //Iterate through holdings
{
if(holdings[index].getIdCode() == bookId) //to find a match with the book ID
{
if(holdings[index].getLocation() == CHECKED_OUT) //If book is already checked out
{
cout << "Book Already Checked Out." << endl;
}
else if(holdings[index].getLocation() == ON_HOLD_SHELF && holdings[index].getRequestedBy()->getIdNum() == patronId) //If book is on hold for patron wanting to check it out
{
holdings[index].setLocation(CHECKED_OUT); //update Location
holdings[index].getRequestedBy()->addBook(&holdings[index]); //add book to Patron's checked out books vector
holdings[index].setCheckedOutBy(holdings[index].getRequestedBy()); //update who has book checked out
holdings[index].setDateCheckedOut(currentDate); //set checked out date
cout << holdings[index].getTitle() << " has been checked out to " << holdings[index].getRequestedBy()->getName() << endl;
holdings[index].setRequestedBy(NULL); //reset requestedBy
}
else if(holdings[index].getLocation() == ON_HOLD_SHELF && holdings[index].getRequestedBy()->getIdNum() != patronId) //If book is on hold for another Patron
{
cout << "Book is on hold for another Patron." << endl;
}
else if(holdings[index].getLocation() == ON_SHELF) //If book is available
{
for(int i = 0; i < members.size(); i++) //Iterate through members
{
if(members[i].getIdNum() == patronId) //to find a match with the patron ID
{
holdings[index].setLocation(CHECKED_OUT); //update Location
members[i].addBook(&holdings[index]); //add book to Patron's checked out books vector
holdings[index].setCheckedOutBy(&members[i]); //update who has book checked out
holdings[index].setDateCheckedOut(currentDate); //set checked out date
cout << holdings[index].getTitle() << " has been checked out to " << members[i].getName() << endl;
}
}
}
}
}
}
/************************************************
* Description: The returnBook function allows the
* user to return a book that has been
* checked out.
* Parameters: The book ID that is being returned.
**************************************************/
void Library::returnBook(string bookID)
{
//Check for Valid Book ID
if(!validBook(bookID))
{
cout << "Invalid Book ID." << endl;
}
else
{
for(int index = 0; index < holdings.size(); index++) //Iterate through holdings
{
if(holdings[index].getIdCode() == bookID) //to find a match for the book ID
{
if(holdings[index].getLocation() != CHECKED_OUT) //If book is not checked out
{
cout << "Book is not Checked Out." << endl;
}
else
{
holdings[index].getCheckedOutBy()->removeBook(&holdings[index]); //remove the book from the Patron's checkedOut vector
if(holdings[index].getRequestedBy() != NULL) //If book is requested by another Patron
{
holdings[index].setLocation(ON_HOLD_SHELF); //put it on the hold shelf
}
else //otherwise
{
holdings[index].setLocation(ON_SHELF); //put it back on the shelf
}
holdings[index].setCheckedOutBy(NULL); //reset checkedOutBy
cout << holdings[index].getTitle() << " has been returned." << endl;
}
}
}
}
}
/**********************************************************
* Description: The requestBook function allows for
* a book to be requested. If the book is
* already checked out, it will be put on
* hold when it is returned, otherwise it
* is put on hold immediately.
* Parameters: the Patron ID that is requesting the book
* and the book ID of the book being requested.
**********************************************************/
void Library::requestBook(string patronID, string bookID)
{
//Check for Valid Patron ID and Book ID
if(!validPatron(patronID) || !validBook(bookID))
{
cout << "Invalid ID." << endl;
}
else
{
for(int index = 0; index < holdings.size(); index++) //Iterate through holdings
{
if(holdings[index].getIdCode() == bookID) //to find the book matching the Book ID
{
if(holdings[index].getRequestedBy() != NULL) //If book is already requested by someone else
{
cout << "Book is already requested by another Patron" << endl;
}
else if(holdings[index].getCheckedOutBy() != NULL && holdings[index].getCheckedOutBy()->getIdNum() == patronID) //If book is checked out by person trying to request
{
cout << "Book is Checked Out to Patron requesting." << endl;
}
else //otherwise
{
for(int i = 0; i < members.size(); i++) //Iterate through members
{
if(members[i].getIdNum() == patronID) //to find the matching Patron ID
{
holdings[index].setRequestedBy(&members[i]); //set requestedBy
if(holdings[index].getLocation() == ON_SHELF) //If book is on shelf
{
holdings[index].setLocation(ON_HOLD_SHELF); //place on hold shelf
}
cout << "Book is requested." << endl;
}
}
}
}
}
}
}
/**********************************************
* Description: The incrementCurrentDate function
* advances the current date by 1 and
* checks for overdue books. If any books
* are overdue, the amendFine function is
* called.
* Parameters: none.
*************************************************/
void Library::incrementCurrentDate()
{
currentDate = currentDate + 1;
cout << "Date advanced. " << endl;
for(int index = 0; index < members.size(); index++) //Iterate through members
{
for(int i = 0; i < members[index].getCheckedOutBooks().size(); i++) //Iterate through every member's checked out books
{
if((currentDate - members[index].getCheckedOutBooks()[i]->getDateCheckedOut()) > Book::CHECK_OUT_LENGTH) //looking for any that are overdue
{
members[index].amendFine(0.1); //if found, add 10 cents to their fine
}
}
}
}
/******************************************************
* Description: The payFine function allows for
* a Patron's fine to be paid down by
* a specific amount.
* Parameters: the ID of the Patron paying their fines
* and the payment amount.
* ****************************************************/
void Library::payFine(string patronID, double payment)
{
payment = 0 - payment; //Make payment a negative so it can be subtracted from the fine
if(!validPatron(patronID))
{
cout << "Invalid Patron ID." << endl;
}
else
{
for(int index = 0; index < members.size(); index++) //Iterate through members
{
if(members[index].getIdNum() == patronID) //to find the matching Patron ID
{
members[index].amendFine(payment); //apply payment toward fine
}
}
}
}
/***************************************************
* Description: The viewPatronInfo function displays
* Patron information.
* Parameters: the Patron ID for the patron info that
* is to be displayed.
****************************************************/
void Library::viewPatronInfo(string patronID)
{
if(!validPatron(patronID))
{
cout << "Invalid Patron ID." << endl;
}
else
{
for(int index = 0; index < members.size(); index++) //Iterate through members
{
if(members[index].getIdNum() == patronID) //to find a matching ID
{
cout << "ID: " << members[index].getIdNum() << endl;
cout << "Name: " << members[index].getName() << endl;
cout << "Checked Out Books: ";
for(int i = 0; i < members[index].getCheckedOutBooks().size(); i++) //Iterate through checkedOutBooks
{
cout << members[index].getCheckedOutBooks()[i]->getTitle() << ". ";
}
cout << endl;
cout << fixed << showpoint << setprecision(2);
cout << "Fines: $" << members[index].getFineAmount() << endl;
}
}
}
}
/***************************************************************
* Description: The viewBookInfo function displays information
* about a book.
* Parameters: the book ID for the book info that is to be
* displayed.
**************************************************************/
void Library::viewBookInfo(string bookID)
{
if(!validBook(bookID))
{
cout << "Invalid Book ID." << endl;
}
else
{
for(int index = 0; index < holdings.size(); index ++) //Iterate through holdings
{
if(holdings[index].getIdCode() == bookID) //to find a matching book ID
{
cout << "ID: " << holdings[index].getIdCode() << endl;
cout << "Title: " << holdings[index].getTitle() << endl;
cout << "Author: " << holdings[index].getAuthor() << endl;
if (holdings[index].getLocation() == ON_SHELF)
{
cout << "Location: On Shelf" << endl;
}
else if(holdings[index].getLocation() == ON_HOLD_SHELF)
{
cout << "Location: On Hold Shelf" << endl;
}
else
{
cout << "Location: Checked Out" << endl;
}
if(holdings[index].getRequestedBy() != NULL)
{
cout << "Requested By: " << holdings[index].getRequestedBy()->getName() << endl;
}
if(holdings[index].getCheckedOutBy() != NULL)
{
cout << "Checked Out By: " << holdings[index].getCheckedOutBy()->getName() << endl;
}
if(holdings[index].getLocation() == CHECKED_OUT)
{
if((holdings[index].getDateCheckedOut() + Book::CHECK_OUT_LENGTH) - currentDate >= 0)
{
cout << "Due in: " << (holdings[index].getDateCheckedOut() + Book::CHECK_OUT_LENGTH) - currentDate << " days" << endl; //Display how long until book is due
}
else if((holdings[index].getDateCheckedOut() + Book::CHECK_OUT_LENGTH) - currentDate < 0) //unless its overdue
{
cout << "OVERDUE" << endl;
}
}
}
}
}
}
/********************************************************
* Description: The validPatron function checks to
* see if the Patron exists in the Library.
* If yes, it returns true, otherwise false.
* Parameters: the Patron ID to be checked.
* ******************************************************/
bool Library::validPatron(string patronId)
{
for(int index = 0; index < members.size(); index++) //Iterate through members
{
if(members[index].getIdNum() == patronId) //to find a match
{
return true;
}
}
return false;
}
/********************************************************
* Description: The validBook function checks to
* see if the book exists in the Library.
* If yes, it returns true, otherwise false.
* Parameters: the Book ID to be checked.
* ******************************************************/
bool Library::validBook(string bookId)
{
for(int index = 0; index < holdings.size(); index++) //Iterate through holdings
{
if(holdings[index].getIdCode() == bookId) //to find a match
{
return true;
}
}
return false;
}
/*******************************************************
* Description: The uniquePatron function verifies that
* the given Patron ID is unique and not
* already present in the Library.
* Parameters: the Patron ID to be checked.
******************************************************/
bool Library::uniquePatron(string patronID)
{
for(int index = 0; index < members.size(); index++) //Iterate through members
{
if(members[index].getIdNum() == patronID) //If a match is found
{
return false; //return false because ID is already in use
}
}
return true;
}
/*******************************************************
* Description: The uniqueBook function verifies that
* the given Book ID is unique and not
* already present in the Library.
* Parameters: the Book ID to be checked.
******************************************************/
bool Library::uniqueBook(string bookID)
{
for(int index = 0; index < holdings.size(); index++) //Iterate through holdings
{
if(holdings[index].getIdCode() == bookID) //If a match is found
{
return false; //return false because ID is already in use
}
}
return true;
}
|
ee576ac34a03dbfa5c2bc7a2b0f5337cccd99fc8
|
3b52957226a012ec352f3f73192fd77828ad501c
|
/UVA/10954 - Add All.cpp
|
45e153127047d1c8915ff9ac90642d01ccb33f3b
|
[] |
no_license
|
jishnusaha/Competetive-Programming
|
8912aa92962d4c72712de44449f6e9ac8f34fbbf
|
5535ee9d67a37def87541639f488e328ba579a97
|
refs/heads/master
| 2021-06-30T00:18:26.959910
| 2020-12-21T18:18:37
| 2020-12-21T18:18:37
| 204,193,372
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 501
|
cpp
|
10954 - Add All.cpp
|
#include<bits/stdc++.h>
using namespace std;
#define loop(i,n1) for(int l=i;l<=n1;l++)
#define pi acos(-1)
#define ll long long
int main()
{
int n,i;
while(cin >> n)
{
if(n==0) break;
int a[n];
loop(0,n-1)
{
cin >> a[l];
}
sort(a,a+n);
ll sum=0,s;
loop(1,n-1)
{
s=a[l]+a[l-1];
sum+=s;
a[l]=s;
sort(a+l,a+n);
}
cout << sum << endl;
}
}
|
bb765ab108ff8fea99311763e69afbc6c4fbdfa8
|
b9bfebe568f1afd9b90f83f3067e2aa1f266a8ee
|
/finally/C/var.cpp
|
a154fec1f207a625f841df22fe331a867b67f69d
|
[] |
no_license
|
ZrcLeibniz/Java
|
fa7c737840d33e572e5d8d87951b6ccd609a38af
|
cfc3119712844dd8856009101575c819874d89f0
|
refs/heads/master
| 2023-06-21T01:49:48.132730
| 2021-07-23T07:07:42
| 2021-07-23T07:07:42
| 267,491,828
| 0
| 0
| null | 2020-10-13T02:18:30
| 2020-05-28T04:20:10
|
Java
|
UTF-8
|
C++
| false
| false
| 231
|
cpp
|
var.cpp
|
#include<stdio.h>
int global = 100;
int main() {
int global = 200;
printf("global: %d\n", global);
int num1 = 0;
int num2 = 0;
scanf("%d %d", &num1, &num2);
int num3 = num1 + num2;
printf("num3: %d\n", num3);
return 0;
}
|
33cd4fff4e504b27cb870599a1b7dbda69e9f62c
|
4a634ad6eddcc372b7b02f0e0dfef93b74ac2879
|
/acm/oj/codeforce/contest/5.11/b.cpp
|
6519fa16b64d0174755804037e53d2ba88eca3a5
|
[] |
no_license
|
chilogen/workspace
|
6e46d0724f7ce4f932a2c904e82d5cc6a6237e14
|
31f780d8e7c7020dbdece7f96a628ae8382c2703
|
refs/heads/master
| 2021-01-25T13:36:36.574867
| 2019-02-18T14:25:13
| 2019-02-18T14:25:13
| 123,596,604
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 702
|
cpp
|
b.cpp
|
#include <cstdio>
#include <queue>
#include <vector>
long int p[200000];
struct cmp
{
bool operator()(const int &a,const int &b)
{
return p[a]>p[b];
}
};
using namespace std;
int main()
{
int n,i,j,k;
long min;
priority_queue <int,vector<int>,cmp> c[3];
scanf("%d",&n);
for(i=0;i<n;i++) scanf("%ld",&p[i]);
for(i=0;i<n;i++)
{
scanf("%d",&j);
c[j-1].push(i);
}
for(i=0;i<n;i++)
{
scanf("%d",&j);
c[j-1].push(i);
}
scanf("%d",&n);
while(n--)
{
min=-1;k=-1;
scanf("%d",&j);
while(!c[j-1].empty())
{
if(p[c[j-1].top()]==0) c[j-1].pop();
else {min=p[c[j-1].top()]; break;}
}
if(min!=-1) {p[c[j-1].top()]=0; c[j-1].pop();}
printf("%ld ",min);
}
return 0;
}
|
11574399ed70466e986ce01cddeefd48ce89eca3
|
141744c5cdcc7b6bca16d89ca4773e2ce10ceb43
|
/BTC++/bai161/bai161.cpp
|
b6929f90648b8433c1dca6b49c63babe096a863c
|
[] |
no_license
|
truong02bp/C-
|
d193b1f6f28d22c5c57f74d397b7785378eff102
|
82971ec24602ce84c652e04b1f7eb487a882aa1c
|
refs/heads/master
| 2023-03-07T16:25:59.091612
| 2020-08-08T07:28:21
| 2020-08-08T07:28:21
| 263,206,451
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 975
|
cpp
|
bai161.cpp
|
#include<iostream>
using namespace std;
bool check(string s , int k);
long long count(string s, int k);
int main()
{
int t;
cin >> t;
while (t--)
{
int k;
string s;
cin >> s >> k;
cout << count(s,k) << endl;
}
return 0;
}
bool check(string s , int k)
{
int count=0;
bool check[10001];
for (int i=0;i<s.length();i++)
check[s[i]-'0']=false;
for (int i=0;i<s.length();i++)
{
if (check[s[i]-'0']==false)
{
count++;
check[s[i]-'0']=true;
}
if (count > k)
return false;
}
return (count==k);
}
long long count(string s, int k)
{
int counter=0;
for (int i=0;i<s.length();i++)
{
string temp="";
for (int j=i;j<s.length();j++)
{
temp+=s[j];
if (check(temp,k)==true)
{
counter++;
}
}
}
return counter;
}
|
77368fe69de0354f2a4ac9b565ebceeff6d58d09
|
5dfe3265612e8155ba096d0ba9f168789020874c
|
/solution_checker.cpp
|
72d87790b7c5af83863f2ba553945cb7117e9edb
|
[] |
no_license
|
ranjan103/Parallel-Graph-Colouring-
|
66bf9aefe5047bdef086cf6196ec7173986e7065
|
b4ee9970d0be0c6bbb4ad549381b432f76107f4e
|
refs/heads/master
| 2020-08-08T19:05:22.667129
| 2019-10-09T11:14:16
| 2019-10-09T11:14:16
| 213,895,991
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,023
|
cpp
|
solution_checker.cpp
|
#include <bits/stdc++.h>
using namespace std;
int main(int argc, char *argv[]) {
if(argc != 3) {
cout << "Try ./a.out <graph> <colouring>\n";
return 0;
}
int n, m, u, v, C=0;
ifstream graph(argv[1]);
ifstream colour(argv[2]);
graph >> n >> m;
vector<int> *g = new vector<int>[n];
for(int i=0; i<n; i++) {
graph >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
int *colours = new int[n];
for(int i=0; i<n; i++) {
colour >> colours[i];
if(colours[i] <= 0) {
cout << "WA\n";
return 0;
}
C = max(C, colours[i]);
}
colour.close();
graph.close();
bool AC = 1;
for(int i=0; i<n; i++)
for(int node : g[i])
if(colours[i] == colours[node]) {
AC = 0;
break;
}
if(AC == 0) {
cout << "WA\n";
return 0;
}
delete[] g, colours;
cout << "AC\nNumber of colours used : " << C << endl;
}
|
a1cb5ee6d78458a63b3dce24607fc18c5fe0e678
|
5bcb9c443543a046b0fb79f8ab02d21752f25b0f
|
/server/characters/Guard.hpp
|
dcbad3021a9375252a85accf9832c651b875fd16
|
[] |
no_license
|
jordansavant/roguezombie
|
69739a2cd6f86345ba808adc2b9287b3b9e37e3d
|
01cf466eeab7dbf108886eb11f8063c82932a0d7
|
refs/heads/master
| 2020-04-18T19:35:56.803764
| 2019-01-27T14:08:47
| 2019-01-27T14:08:47
| 167,715,791
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 416
|
hpp
|
Guard.hpp
|
#pragma once
#ifndef RZ_GUARD_H
#define RZ_GUARD_H
#include "SFML/Graphics.hpp"
#include "SFML/Network.hpp"
#include "../../bitengine/Game.hpp"
#include "../../bitengine/Network.hpp"
#include "../Character.hpp"
class DialogNode;
class Guard : public Character
{
public:
Guard();
virtual void load(Level* level, unsigned int id, float x, float y);
virtual void update(sf::Time &gameTime);
};
#endif
|
e32886f4f4629f0bbc5e54f5a4d57e5cb81635f2
|
c8f7e1beffa9b0baf06e82c9a0e8a198bf5e23c5
|
/Arrays/Add one to number.cpp
|
7b2802cc3d9ecbb6c6021052ab98c8ed24cef36f
|
[] |
no_license
|
umanshi/Interviewbit-Solutions
|
555d362226e412feec74fca024120d8016adba0e
|
21be4a042e416779196cab57e02ebe01c562f25d
|
refs/heads/master
| 2021-07-12T21:45:17.702598
| 2020-06-07T17:19:52
| 2020-06-07T17:19:52
| 142,772,303
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 574
|
cpp
|
Add one to number.cpp
|
vector<int> Solution::plusOne(vector<int> &A)
{
int e = A.size()-1;
int carry = 0;
if(A[e]<9)
A[e] = A[e]+1;
else if (A[e]==9)
{
A[e] = 0;
carry = 1;
for (int i=A.size()-2; i>=0; i--)
{
A[i]+=carry;
if(A[i]==10)
{
A[i] = 0;
carry = 1;
}
else
carry = 0;
}
if(carry == 1)
A.insert(A.begin(), 1);
}
while(A[0] == 0)
A.erase (A.begin());
return A;
}
|
690b52c9dec470f4fb0278e52ae354f14b635364
|
977c82ec23f2f8f2b0da5c57984826e16a22787d
|
/src/IceRay/main/interface/python/core/geometry/complex/intersect.cpp
|
b125490a2a6e3bc65cec343ff09bc4f317a69ce6
|
[
"MIT-0"
] |
permissive
|
dmilos/IceRay
|
47ce08e2920171bc20dbcd6edcf9a6393461c33e
|
84fe8d90110c5190c7f58c4b2ec3cdae8c7d86ae
|
refs/heads/master
| 2023-04-27T10:14:04.743094
| 2023-04-20T14:33:45
| 2023-04-20T15:07:18
| 247,471,987
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,317
|
cpp
|
intersect.cpp
|
#include <boost/python.hpp>
#include "../../../def_submodule.hpp"
#include "../../../../../../geometry/_pure/_base.hpp"
#include "../../../../../../geometry/complex/intersect.hpp"
void expose_IceRay_geometry_complex_intersect()
{
//MAKE_SUBMODULE( IceRay );
MAKE_SUBMODULE( core );
MAKE_SUBMODULE( geometry );
typedef GS_DDMRM::S_IceRay::S_type::S_coord::GT_scalar3D Tf_coord3D;
typedef GS_DDMRM::S_IceRay::S_geometry::S__pure::GC__base Tf__base;
typedef GS_DDMRM::S_IceRay::S_geometry::S_complex::S_CSG::GC_intersect Tf_intersect;
typedef bool (Tf_intersect::*Tf_setSmall)( Tf__base * P_right );
typedef bool (Tf_intersect::*Tf_setFull )( Tf__base * P_right, Tf_intersect::T_location const& P_orientation );
Tf_setSmall I_setSmallLeft = &Tf_intersect::F_left;
Tf_setFull I_setFullLeft = &Tf_intersect::F_left;
Tf_setSmall I_setSmallRight = &Tf_intersect::F_right;
Tf_setFull I_setFullRight = &Tf_intersect::F_right;
boost::python::class_< Tf_intersect, boost::python::bases<Tf__base> >( "GeometryComplexIntersect" )
.def( boost::python::init<>() )
.def("left", I_setSmallLeft )
.def("left", I_setFullLeft )
.def("right", I_setSmallRight )
.def("right", I_setFullRight )
;
}
|
9e0e46297ab9456e658580362c71d3ab0cd8863a
|
2674ddde200c5cded2170ec563a37652f1ae47a4
|
/AddrSearch/IniFile.h
|
06cb94cabdccd558c298be82ae11968c3a718252
|
[] |
no_license
|
geekxiaoxiao/AddrSearch
|
acbd3c3c1a33f298d1bac2f8a370daeb2935f782
|
158716e295f596be7f6bee295525a8540642c4a9
|
refs/heads/master
| 2023-07-06T01:20:10.360766
| 2023-07-01T08:53:55
| 2023-07-01T08:53:55
| 211,758,970
| 64
| 26
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 880
|
h
|
IniFile.h
|
// IniFile.h: interface for the CIniFile class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_INIFILE_H__4D7A97DE_A567_431A_AC27_1A3D608B70F0__INCLUDED_)
#define AFX_INIFILE_H__4D7A97DE_A567_431A_AC27_1A3D608B70F0__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
class CIniFile
{
public:
virtual ~CIniFile();
static CIniFile* GetInstance();
void RegisterModule(CString strName);
void SetValue(CString strKey, CString strValue);
void GetValue(CString strKey, CString &strValue,CString strDefault="");
void SetValue(CString strKey, int nValue);
void GetValue(CString strKey, int &nValue, int nDefault=0);
private:
static CIniFile* m_pInstance;
CString m_strModuleName;
CIniFile();
CString GetAppPath();
};
#endif // !defined(AFX_INIFILE_H__4D7A97DE_A567_431A_AC27_1A3D608B70F0__INCLUDED_)
|
e259b2d549e09f25adcf9f5897466d696ff9e259
|
192a97954827dad0e87b2ccf71d8b883287c05e2
|
/src/rc-visual/objects/Pixel.h
|
6c655f0428379a80faef709d7baf9bf082fba963
|
[] |
no_license
|
danomatika/rc-visual
|
e3f7832ce84702c2752fd4aab37249d0ad5bb7e8
|
d2841cdd559c5bd9e4e340a553a9976510f6a679
|
refs/heads/master
| 2020-12-24T14:26:47.019606
| 2017-01-25T09:17:58
| 2017-01-25T09:17:58
| 2,255,594
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,201
|
h
|
Pixel.h
|
/*==============================================================================
Pixel.h
rc-visual: a simple, osc-controlled 2d graphics engine
Copyright (C) 2007, 2010 Dan Wilcox <danomatika@gmail.com>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
==============================================================================*/
#ifndef PIXEL_H
#define PIXEL_H
#include "Config.h"
#include "DrawableObject.h"
class Pixel : public DrawableObject
{
public:
Pixel(string name, string parentOscAddress) :
DrawableObject("pixel", name, parentOscAddress), pos(0, 0)
{
// add variables to Xml
addXmlAttribute("x", "position", XML_TYPE_FLOAT, &pos.x);
addXmlAttribute("y", "position", XML_TYPE_FLOAT, &pos.y);
}
void draw()
{
if(bVisible)
{
visual::Graphics::stroke(color);
visual::Graphics::point(pos.x, pos.y);
}
}
string getType() {return "pixel";}
protected:
bool processOscMessage(const osc::ReceivedMessage& message,
const osc::MessageSource& source)
{
// call the base class
if(DrawableObject::processOscMessage(message, source))
{
return true;
}
else if(message.path() == getOscRootAddress() + "/position")
{
message.tryNumber(&pos.x, 0);
message.tryNumber(&pos.y, 1);
return true;
}
else if(message.path() == getOscRootAddress() + "/position/x")
{
message.tryNumber(&pos.x, 0);
return true;
}
else if(message.path() == getOscRootAddress() + "/position/y")
{
message.tryNumber(&pos.y, 0);
return true;
}
return false;
}
visual::Point pos;
};
#endif // PIXEL_H
|
30b0483a768f244ad8be0bcac54b8b00a8b1e4e3
|
ad85bf7f2c06a10b1347a7bc7c99e1adf164bcf5
|
/Classes/GameObject.cpp
|
b4df83f16e996066821550220895df39084e1a36
|
[] |
no_license
|
giginet/LuaBindSample
|
9d59699b3f4fa7a75e9a06d02bb2378a8e9d2934
|
772b2bd36a1865f98aaf5b357b69c9f669c6a4e3
|
refs/heads/master
| 2021-01-19T04:51:02.970235
| 2013-12-15T19:25:38
| 2013-12-15T19:25:38
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 183
|
cpp
|
GameObject.cpp
|
//
// GameObject.cpp
// HelloLua
//
// Created by giginet on 2013/12/16.
//
//
#include "GameObject.h"
GameObject::GameObject(float x, float y) {
}
void GameObject::method() {
}
|
2a9992d4409172c17bf7122760b15ed1b1c517d1
|
af0ecafb5428bd556d49575da2a72f6f80d3d14b
|
/CodeJamCrawler/dataset/12_8879_35.cpp
|
c5f238718ed073b9d9c26beda257d87511015fa8
|
[] |
no_license
|
gbrlas/AVSP
|
0a2a08be5661c1b4a2238e875b6cdc88b4ee0997
|
e259090bf282694676b2568023745f9ffb6d73fd
|
refs/heads/master
| 2021-06-16T22:25:41.585830
| 2017-06-09T06:32:01
| 2017-06-09T06:32:01
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,137
|
cpp
|
12_8879_35.cpp
|
/*
* File: b.cc
* Author: cheshire
*
* Created on 14 Апрель 2012 г., 16:46
*/
#if 1
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <algorithm>
#include <bitset>
#include <complex>
#include <functional>
#include <fstream>
#include <iostream>
#include <limits>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
using namespace std;
typedef long long LL;
typedef long double LD;
typedef pair<int, int> pii;
typedef vector<int> veci;
typedef vector<veci> graph;
const LD eps = 1e-9;
const LD pi = acos(-1.0);
const int inf = 1000 * 1000 * 1000;
const LL inf64 = LL(inf) * inf;
#define pb push_back
#define mp make_pair
#define X first
#define Y second
#ifdef DEBUG
#define dbg(x) { cerr << #x << " = " << x << endl; }
#define dbgv(x) { cerr << #x << " = {"; for(size_t _i = 0; _i < (x).size(); ++_i) { if(_i) cerr << ", "; cerr << (x)[_i]; } cerr << "}" << endl; }
#define dbgi(start, end, label) {cerr << #label << " = {"; for (auto _it = start; _it != end; ++ _it) { if (_it != start) cerr << ", "; cerr << *(_it);} << cerr << "}" << endl; }
#else
#define dbg(x)
#define dbgv(x)
#define dbgi(start, end, label)
#endif
#define PROBLEM "B-large"
#define all(x) (x).begin(), (x).end()
#define START clock_t _clock = clock();
#define END cerr << (clock() - _clock) / (LD) CLOCKS_PER_SEC << endl;
/*
*
*/
void solve (int test)
{
int n, s, p;
cin >> n >> s >> p;
int res = 0;
int tmp = 0;
for (int i = 0; i < n; ++ i)
{
cin >> tmp;
if (tmp > 3 * p - 3)
res ++;
else if (tmp > 3 * p - 5 && tmp > 1 && s)
s --, res ++;
}
cout << "Case #" << test << ": " << res << endl;
return;
}
int main() {
START;
freopen(PROBLEM ".in", "r", stdin); freopen(PROBLEM ".out", "w", stdout);
//freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout);
int n;
cin >> n;
for (int test = 1; test <= n; ++ test)
solve(test);
END;
return (EXIT_SUCCESS);
}
#endif
|
e035236e8e0c0fcf8470413c8eaf2f244275273c
|
46d080ea08657bc6d812defd0c461493330fd0e4
|
/small_net/main.cpp
|
4958a011f5e5bd0fb4afbc06c9bfd44dc0e50e94
|
[] |
no_license
|
qinjian623/plib
|
fdbd650f042f7b2e9617e83b6ca07deea7a2378f
|
4cd12669b98e618f3000bbf67a4aabf28b4fec2e
|
refs/heads/master
| 2021-01-22T10:36:06.609715
| 2017-04-19T01:34:12
| 2017-04-19T01:34:12
| 8,453,401
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,852
|
cpp
|
main.cpp
|
#include "main.h"
int main()
{
cout << "Program start." << endl;
Net* n = load_model("/home/qin/model.txt");
int training_size = 50000;
int test_size = 5000;
int ta[6] = {30*30, 30*30, 30*30/4, 30*30/8, 1, 1};
vector<int> arch(&ta[0], &ta[0]+5);
ActivationFunction taf[9] = {TANH, TANH, TANH, TANH, TANH, TANH, ReLU, ReLU, TANH};
vector<ActivationFunction> afs(&taf[0], &taf[0]+4);
//Net net(arch, afs);
//net.prepare_training(0.001);
cout << "Loading dataset..." << endl;
vector< pair<Matrix2D*, Matrix2D*> > dataset;
read_vector_file(string("/home/qin/workspace_c/qt_1/build-mat_dump-Desktop_Qt_Qt_Version_GCC_64bit-Debug/all_shuf.txt"), dataset, training_size + test_size + 3);
cout << "OK" << endl;
//std::random_shuffle(dataset.begin(), dataset.end());
//train_model(net, dataset, training_size);
//cout << "Close test:" << endl;
//test_model(*n, dataset.begin(), dataset.begin()+training_size);
cout << "Open test:" << endl;
test_model(*n, dataset.begin()+training_size, dataset.begin()+training_size+100);
cout << "----------------------------------------------------------------" << endl;
//net.dump();
// Open test
/*size_t in_size[2] = {1, ta[0]};
size_t out_size[2] = {1, 1};
Matrix2D in(&in_size[0]);
in.random();
//in.fill(1);
Matrix2D out(&out_size[0]);*/
/*vector<Matrix2D*> xs;
vector<Matrix2D*> ys;
build_xor_training_set(xs, ys);
std::srand(time(NULL));
net.dump();
net.forward(in, out);
cout << in.to_string() << endl;
cout << out.to_string() << endl;
for (int var = 0; var < 700000; ++var) {
int i= var%4;//std::rand()%4;
//cout << "Input & Label ====================" << endl;
//
//net.forward(*xs[i], out);
//cout << out.to_string() << endl;
net.train(*xs[i], *ys[i]);
}
//cout << "Network dumping ...." << endl;
//net.dump();
//exit(0);
//cout << in.to_string() << endl;
clock_t t = clock();
for(int i = 0; i < 4; ++i){
net.forward(*xs[i], out);
cout << "--------------------------------"<<endl;
cout << "X = ";
cout << xs[i]->to_string() << endl;
cout << "Y = ";
cout << ys[i]->to_string() << endl;
cout << "H(x) = ";
cout << out.to_string() << endl;
}
//net.forward(in, out);
t = clock() - t;
printf ("It took me %ld clicks (%f seconds).\n",t,((float)t)/CLOCKS_PER_SEC);
return 0;*/
}
|
d0259f1846be1e3abd4fc4d9e59fada52ad3cd30
|
9c7e207304e9ad5a9f0863ab611a619035773575
|
/menghitung luas lingkaran.cpp
|
818ee0aed908ae693daf38c16786c30646642088
|
[] |
no_license
|
MeilaniAgistia/M
|
882cf8f2cf13ebce34ec539f8080ef9d190d53b5
|
93fc8f25539eb2cb477ee6a827080a2c2e8a9319
|
refs/heads/master
| 2023-09-05T18:15:41.274554
| 2021-10-28T15:08:05
| 2021-10-28T15:08:05
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 422
|
cpp
|
menghitung luas lingkaran.cpp
|
#include <iostream>
using namespace std;
//Compiler version g++ 6.3.0
int main()
{
std:cout<<"Meilani Agistia \n";
float luas, a= 4.5;
luas, b= 3.2;
luas, c= 2.1;
int r;
cout<<"masukan nilai jari-jari : " ;
cin>>r;
cout<<"luas lingkaran : " ;
cin>>luas;
luas = a * r * r;
return 0;
}
|
17bfb7be7c488c24be330aa8f40c17159c29ef52
|
f853b52091ffc09dbeebca5b3a1469981ad587ec
|
/TSE/Assignment 3/GPUMandelbrot/GPUMandelbrot/GPUMandelbrot.cpp
|
7e4bc2b81362b3267260415f55ccfcee3d89e33c
|
[] |
no_license
|
corruptpony/S6T
|
819daa02adbff9214ad83ff65103ffdf23f71e38
|
9e10048f4da1a6b4072c744c2df3d39ef87e7a26
|
refs/heads/master
| 2021-01-19T12:05:08.802299
| 2017-06-20T11:03:43
| 2017-06-20T11:03:52
| 82,283,895
| 0
| 1
| null | 2017-03-06T09:35:43
| 2017-02-17T10:04:50
|
C++
|
UTF-8
|
C++
| false
| false
| 4,785
|
cpp
|
GPUMandelbrot.cpp
|
#define _CRT_SECURE_NO_WARNINGS
#define _SCL_SECURE_NO_WARNINGS
#include "opencl_utils.h"
#include <windows.h>
#include <stdio.h>
#include <iostream>
#include <CL/cl.h>
#include <stdlib.h>
int main() {
/* Define GPU parameters */
cl_device_id device_id = NULL;
cl_context context = NULL;
cl_command_queue command_queue = NULL;
cl_program program = NULL;
cl_kernel kernel = NULL;
cl_platform_id platform_id[3];
/* return values for extra info */
cl_uint ret_num_devices;
cl_uint ret_num_platforms;
cl_int ret;
/* Declare device mem */
cl_mem dev_gdata;
cl_mem dev_sdata;
/* Parameters for testing */
char fileName[] = "./kernel2.cl";
const int GLOBAL_SIZE = 512 * 512 * 512;
const int LOCAL_SIZE = 512;
/* Fill array with test data */
int* dataArray = (int*)malloc(sizeof(int) * GLOBAL_SIZE);
for (int i = 0; i < GLOBAL_SIZE; i++)
{
dataArray[i] = i % 10;
}
/* Get current time before calculating the array with CPU */
LARGE_INTEGER freqCPU, startCPU, endCPU;
QueryPerformanceFrequency(&freqCPU);
QueryPerformanceCounter(&startCPU);
int sum = 0;
for (int i = 0; i < GLOBAL_SIZE; i++)
{
sum += dataArray[i];
}
/* Get current time after calculating the array with CPU */
QueryPerformanceCounter(&endCPU);
/* Get Platform and Device Info */
char* info;
size_t infoSize;
ret = clGetPlatformIDs(3, platform_id, &ret_num_platforms);
checkError(ret, "Couldn't get platform ids");
ret = clGetDeviceIDs(platform_id[2], CL_DEVICE_TYPE_DEFAULT, 1, &device_id, &ret_num_devices);
checkError(ret, "Couldn't get device ids");
ret = clGetPlatformInfo(platform_id[2], CL_PLATFORM_NAME, 0, NULL, &infoSize);
checkError(ret, "Couldn't get platform info");
info = (char*)malloc(infoSize);
ret = clGetPlatformInfo(platform_id[2], CL_PLATFORM_NAME, infoSize, info, NULL);
checkError(ret, "Couldn't get platform attribute value");
printf("Running on %s\n\n", info);
/* Create OpenCL Context */
context = clCreateContext(NULL, 1, &device_id, NULL, NULL, &ret);
checkError(ret, "Couldn't create context");
/* Create command queue */
command_queue = clCreateCommandQueue(context, device_id, 0, &ret);
checkError(ret, "Couldn't create commandqueue");
/* Allocate memory for arrays on the Compute Device */
dev_gdata = clCreateBuffer(context, CL_MEM_READ_ONLY, GLOBAL_SIZE * sizeof(cl_int), NULL, &ret);
checkError(ret, "Couldn't create gdata on device");
/* Create kernel program */
program = build_program(context, device_id, fileName);
checkError(ret, "Couldn't compile");
/* Create OpenCL kernel from the compiled program */
kernel = clCreateKernel(program, "reduction", &ret);
checkError(ret, "Couldn't create kernel");
/* Set OpenCL kernel arguments */
ret = clSetKernelArg(kernel, 0, sizeof(cl_mem), (void *)&dev_gdata);
checkError(ret, "Couldn't set arg gdata");
/* Get current time before calculating the array with GPU */
LARGE_INTEGER freq, start;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&start);
/* Write new bit of data to GPU */
ret = clEnqueueWriteBuffer(command_queue, dev_gdata, CL_TRUE, 0, GLOBAL_SIZE * sizeof(cl_int), dataArray, 0, NULL, NULL);
checkError(ret, "Couldn't write array on device");
size_t globalSize[] = { GLOBAL_SIZE };
size_t localSize[] = { LOCAL_SIZE };
/* Set local size */
ret = clSetKernelArg(kernel, 1, localSize[0] * sizeof(cl_int), NULL);
checkError(ret, "Couldn't set arg sdata");
for (int i = 0; i < 3; i++)
{
/* Activate OpenCL kernel on the Compute Device */
ret = clEnqueueNDRangeKernel(command_queue,
kernel,
1, // 1D array
NULL,
globalSize,
localSize,
0,
NULL,
NULL);
checkError(ret, "Could not activate kernel");
clFinish(command_queue);
globalSize[0] = globalSize[0] / 512;
}
/* Transfer result back to host */
ret = clEnqueueReadBuffer(command_queue, dev_gdata, CL_TRUE, 0, sizeof(int), dataArray, 0, NULL, NULL);
checkError(ret, "Couldn't get data from host");
/* Get current time after calculating the array on GPU */
LARGE_INTEGER end;
QueryPerformanceCounter(&end);
/* Print elapsed time */
printf("Elapsed time CPU: %f msec\n", (double)(endCPU.QuadPart - startCPU.QuadPart) / freqCPU.QuadPart * 1000.0);
printf("Elapsed time GPU: %f msec\n", (double)(end.QuadPart - start.QuadPart) / freq.QuadPart * 1000.0);
printf("result CPU: %i\n", sum);
printf("result GPU: %i\n", dataArray[0]);
/* Finalization */
ret = clFlush(command_queue);
ret = clFinish(command_queue);
ret = clReleaseKernel(kernel);
ret = clReleaseProgram(program);
ret = clReleaseMemObject(dev_gdata);
ret = clReleaseCommandQueue(command_queue);
ret = clReleaseContext(context);
free(dataArray);
/* Blocking to show result */
printf("Press ENTER to continue...\n");
getchar();
return 0;
}
|
408175a411786af85d8a8d4602d8562cddd2adcc
|
dea33eab2279bfff0b54ba1409b9d7896d08bbfe
|
/matrixmultiplicationomp/MatrixMultiplication/MatrixMultiplication/MatrixMultiplication.cpp
|
93645b4bca919a5b4a98e45cd4d5f39bdada8e8c
|
[] |
no_license
|
alextoropu/ADP
|
0405200a9385b47274ec71a8a118f02e4261b506
|
20904f89b679975b49a1eb851280fb63d0e31aa5
|
refs/heads/master
| 2022-01-15T07:30:56.114649
| 2017-05-31T11:41:09
| 2017-05-31T11:41:09
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,214
|
cpp
|
MatrixMultiplication.cpp
|
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include "stdafx.h"
void transpose(double *A, double *B, int n) {
int i, j;
for (i = 0; i<n; i++) {
for (j = 0; j<n; j++) {
B[j*n + i] = A[i*n + j];
}
}
}
void gemm(double *A, double *B, double *C, int n)
{
int i, j, k;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
double dot = 0;
for (k = 0; k < n; k++) {
dot += A[i*n + k] * B[k*n + j];
}
C[i*n + j] = dot;
}
}
}
void gemm_omp(double *A, double *B, double *C, int n)
{
#pragma omp parallel
{
int i, j, k;
#pragma omp for
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
double dot = 0;
for (k = 0; k < n; k++) {
dot += A[i*n + k] * B[k*n + j];
}
C[i*n + j] = dot;
}
}
}
}
void gemmT(double *A, double *B, double *C, int n)
{
int i, j, k;
double *B2;
B2 = (double*)malloc(sizeof(double)*n*n);
transpose(B, B2, n);
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
double dot = 0;
for (k = 0; k < n; k++) {
dot += A[i*n + k] * B2[j*n + k];
}
C[i*n + j] = dot;
}
}
free(B2);
}
void gemmT_omp(double *A, double *B, double *C, int n)
{
double *B2;
B2 = (double*)malloc(sizeof(double)*n*n);
transpose(B, B2, n);
#pragma omp parallel
{
int i, j, k;
#pragma omp for
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
double dot = 0;
for (k = 0; k < n; k++) {
dot += A[i*n + k] * B2[j*n + k];
}
C[i*n + j] = dot;
}
}
}
free(B2);
}
int main() {
int i, n;
double *A, *B, *C, dtime;
n = 512;
A = (double*)malloc(sizeof(double)*n*n);
B = (double*)malloc(sizeof(double)*n*n);
C = (double*)malloc(sizeof(double)*n*n);
for (i = 0; i<n*n; i++) { A[i] = rand() / RAND_MAX; B[i] = rand() / RAND_MAX; }
dtime = omp_get_wtime();
gemm(A, B, C, n);
dtime = omp_get_wtime() - dtime;
printf("%f\n", dtime);
dtime = omp_get_wtime();
gemm_omp(A, B, C, n);
dtime = omp_get_wtime() - dtime;
printf("%f\n", dtime);
dtime = omp_get_wtime();
gemmT(A, B, C, n);
dtime = omp_get_wtime() - dtime;
printf("%f\n", dtime);
dtime = omp_get_wtime();
gemmT_omp(A, B, C, n);
dtime = omp_get_wtime() - dtime;
printf("%f\n", dtime);
return 0;
system("pause");
}
|
73cb81b6d7fa6c97227d89526a277e5842b4d3f6
|
7c3d724d136a7e08e9ea78aa934daab85da1bc9b
|
/Øving5/Øving5/BlackJack.h
|
42df2011845d879ce82bc6f8a963ba833f970f5f
|
[] |
no_license
|
TheLarsinator/NTNU
|
3836eaed64a506d81cc67fca0f29267d74671deb
|
d7155ec499ecf98f90c69e8c21b45a807480c125
|
refs/heads/master
| 2021-01-10T15:11:41.714500
| 2017-01-15T21:18:41
| 2017-01-15T21:18:41
| 52,882,016
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 576
|
h
|
BlackJack.h
|
#pragma once
#include "Card.h"
#include "CardDeck.h"
class BlackJack
{
private:
CardDeck deck;
int playerHand;
int dealerHand;
int playerCardsDrawn;
int dealerCardsDrawn;
Card dealerCards[10];
Card playerCards[10];
void printIntroduction(bool withBets);
public:
bool isAce(Card *card);
int getCardValue(Card *card);
int getPlayerCardValue(Card *card);
int getDealerCardValue(Card *card, int dealerHand);
bool askPlayerDrawCard();
void drawInitialCards(CardDeck *deck);
bool playGame(CardDeck deck, bool firstGame);
void playBlackJackWithBets(CardDeck deck);
};
|
5fd564b3f8830136d60e5a8d93b5ca17e77fd0c8
|
e24a91336211ae32f0752f63d0f749efe3ae85bd
|
/src/kalman_filter.cpp
|
65303e132ae0c5a3bb98cab27c698b81b859636d
|
[] |
no_license
|
prakharsharma/CarND-Extended-Kalman-Filter-Project
|
a3b0b75200289dadca115f1a1429687dc40291ff
|
18438b14f1ac8efc18c881ef5299592f1c2bdaeb
|
refs/heads/master
| 2021-01-22T23:26:05.483887
| 2017-03-22T22:40:10
| 2017-03-22T22:40:10
| 85,637,461
| 0
| 0
| null | 2017-03-20T23:27:36
| 2017-03-20T23:27:36
| null |
UTF-8
|
C++
| false
| false
| 1,956
|
cpp
|
kalman_filter.cpp
|
#include <iostream>
#include "kalman_filter.h"
using namespace std;
using Eigen::MatrixXd;
using Eigen::VectorXd;
KalmanFilter::KalmanFilter() {}
KalmanFilter::~KalmanFilter() {}
void KalmanFilter::Predict() {
x_ = F_ * x_;
MatrixXd Ft = F_.transpose();
P_ = F_ * P_ * Ft + Q_;
}
void KalmanFilter::Update(const VectorXd &z) {
VectorXd z_pred = H_laser_ * x_;
// cout << "predicted measurement: " << z_pred << endl;
VectorXd y = z - z_pred;
MatrixXd Ht = H_laser_.transpose();
MatrixXd S = H_laser_ * P_ * Ht + R_laser_;
MatrixXd Si = S.inverse();
MatrixXd PHt = P_ * Ht;
MatrixXd K = PHt * Si;
//new estimate
x_ = x_ + (K * y);
long x_size = x_.size();
MatrixXd I = MatrixXd::Identity(x_size, x_size);
P_ = (I - K * H_laser_) * P_;
}
void KalmanFilter::UpdateEKF(const VectorXd &z) {
double px = x_(0);
double py = x_(1);
double vx = x_(2);
double vy = x_(3);
double c1 = px * px + py *py;
double c2 = sqrt(c1);
double c3 = (c1 * c2);
if (fabs(c1) < 0.00001) {
cerr << "Avoiding division by zero, skipping radar "
"measurement" << endl;
return;
}
double range = sqrt(c1);
double bearing = atan2(py, px);
double range_rate = (px * vx + py * vy)/range;
// cout << "range: " << range << ", bearing: " << bearing
// << ", range_rate: " << range_rate << endl;
VectorXd z_pred(3);
z_pred << range, bearing, range_rate;
// cout << "predicted measurement: " << z_pred << endl;
VectorXd y = z - z_pred;
Hj_ << (px/c2), (py/c2), 0, 0,
-(py/c1), (px/c1), 0, 0,
py*(vx*py - vy*px)/c3, px*(px*vy - py*vx)/c3, px/c2, py/c2;
// cout << "Updated Jacobian: " << Hj_ << endl;
MatrixXd Hjt = Hj_.transpose();
MatrixXd S = Hj_ * P_ * Hjt + R_radar_;
MatrixXd Si = S.inverse();
MatrixXd K = P_ * Hjt * Si;
// new estimate
x_ = x_ + K * y;
long x_size = x_.size();
MatrixXd I = MatrixXd::Identity(x_size, x_size);
P_= (I - K * Hj_) * P_;
}
|
6e8cbe6fd22af39ef7b5bd33ca44b72f08301717
|
f03e82604c4753ff2ea23565186e3cc0be0644fd
|
/cpp/GCR_py_wrap.cpp
|
029b4f32d54e7e510204b722355205a4bb445b92
|
[] |
no_license
|
Call1st0/dft-based-watermarking-method-with-GCR-masking
|
2b2eca0dff6fbc00f37cf43b84a7f684404d1db4
|
86dfbbc24f6c6353d9c6a0ea1bd7ef58293f4728
|
refs/heads/master
| 2022-11-11T16:45:18.242417
| 2020-07-09T10:10:26
| 2020-07-09T10:10:26
| 189,598,034
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,881
|
cpp
|
GCR_py_wrap.cpp
|
#include"armadillo"
#include"Gamut.h"
#include"RevInt.h"
#include<string>
//Function declarations
extern "C"
{
//Gamut mapping
void *makegma(double *Lab, size_t no_Lab, int *ch, size_t no_ch);
void map(void *gma, double *Lab_set, double *Lab_set_new, size_t no_Lab_set, unsigned short *outgamarr, pfnPrintProgress PrintCallback);
void deletegma(void *gma);
//Revese interpolation
void *makeRevInt(const char* prof, int nogrdpts, int noclpts);
void interp(void *rev, double *Lab, size_t no_Lab, double *kvals, size_t no_kvals);
void interpex(void *rev, double *Lab, size_t no_Lab, double *kvals, size_t no_kvals);
void interpLut(void *rev, double *lutcmykarr, unsigned short *outgamarr, double* kminmax, int nogrdpts);
void getLabExtmRng(void *rev, double *labextmarr, double *rangearr);
void *makegammapForm(float *LUTvals, unsigned int nogrdpts);
void *makelab2kForm(float *LUTvals, unsigned int nogrdpts);
void *makelabk2cmykForm(float *LUTvals, size_t nogrdpts);
void applygammapForm(void *gammapform, double* LabIn, double* LabOut, size_t size);
void applylab2kForm(void *lab2kform, double* LabIn, double* Kout, size_t size);
void applylabk2cmykForm(void *labk2cmykform, double* LabKin, double* CMYKout, size_t size);
void deletegammapForm(void *gammapform);
void deletelab2kForm(void *labk2kform);
void deletelabk2cmykForm(void *labk2cmykform);
void deleteRevInt(void *rev);
}
//Function definitons
extern "C" void *makegma(double *Lab, size_t no_Lab, int *ch, size_t no_ch)
{
Gamut *gma = new Gamut(Lab, no_Lab, ch, no_ch);
return reinterpret_cast<void *>(gma);
}
extern "C" void map(void *gma, double *Lab_set, double *Lab_set_new, size_t no_Lab_set, unsigned short *outgamarr, pfnPrintProgress PrintCallback)
{
try
{
reinterpret_cast<Gamut*>(gma)->map(Lab_set, Lab_set_new, no_Lab_set, outgamarr, PrintCallback);
}
catch (const std::exception& ex)
{
std::ofstream out("GCR_py_wrap.txt");
std::string str(ex.what());
out << str;
out.close();
}
}
extern "C" void deletegma(void *gma)
{
reinterpret_cast<Gamut*>(gma)->~Gamut();
}
extern "C" void *makeRevInt(const char* prof, int nogrdpts, int noclpts)
{
RevInt *rev = new RevInt(prof, nogrdpts, noclpts);
return reinterpret_cast<void *>(rev);
}
extern "C" void interp(void *rev, double *Lab, size_t no_Lab, double *kvals, size_t no_kvals)
{
vec kvalsvec(kvals, no_kvals);
mat res(3, no_Lab*no_kvals);
size_t count = 0;
for (size_t i = 0; i < no_Lab * 3; i += 3)
{
vec labpt(Lab[i], 3);
res(span(0, 2), span(count*no_kvals, count*no_kvals + no_kvals - 1)) =
reinterpret_cast<RevInt*>(rev)->interp(labpt, kvalsvec);
count++;
}
}
extern "C" void interpex(void *rev, double *Lab, size_t no_Lab, double *kvals, size_t no_kvals)
{
vec kvalsvec(kvals, no_kvals);
mat res(3, no_Lab*no_kvals);
size_t count = 0;
for (size_t i = 0; i < no_Lab * 3; i += 3)
{
vec labpt(Lab[i], 3);
res(span(0, 2), span(count*no_kvals, count*no_kvals + no_kvals - 1)) =
reinterpret_cast<RevInt*>(rev)->interpex(labpt, kvalsvec);
count++;
}
}
extern "C" void interpLut(void *rev, double *lutcmykarr, unsigned short *outgamarr, double* kminmax, int nogrdpts)
{
reinterpret_cast<RevInt*>(rev)->interpLut(lutcmykarr, outgamarr, kminmax, nogrdpts);
}
extern "C" void getLabExtmRng(void *rev, double *labextmarr, double *rangearr)
{
reinterpret_cast<RevInt*>(rev)->getLabExtmRng(labextmarr, rangearr);
}
extern "C" void *makegammapForm(float *LUTvals, unsigned int nogrdpts)
{
return reinterpret_cast<void*>(RevInt::makegammapForm(LUTvals, nogrdpts));
}
extern "C" void *makelab2kForm(float *LUTvals, unsigned int nogrdpts)
{
return reinterpret_cast<void*>(RevInt::makelab2kForm(LUTvals, nogrdpts));
}
extern "C" void *makelabk2cmykForm(float *LUTvals, size_t nogrdpts)
{
return reinterpret_cast<void*>(RevInt::makelabk2cmykForm(LUTvals, nogrdpts));
}
extern "C" void applygammapForm(void *gammapform, double* LabIn, double* LabOut, size_t size)
{
cmsDoTransform(reinterpret_cast<cmsHTRANSFORM>(gammapform), LabIn, LabOut, size);
}
extern "C" void applylab2kForm(void *lab2kform, double* LabIn, double* Kout, size_t size)
{
cmsDoTransform(reinterpret_cast<cmsHTRANSFORM>(lab2kform), LabIn, Kout, size);
}
extern "C" void applylabk2cmykForm(void *labk2cmykform, double* LabKin, double* CMYKout, size_t size)
{
cmsDoTransform(reinterpret_cast<cmsHTRANSFORM>(labk2cmykform), LabKin, CMYKout, size);
}
extern "C" void deletegammapForm(void *gammapform)
{
cmsDeleteTransform(reinterpret_cast<cmsHTRANSFORM>(gammapform));
}
extern "C" void deletelab2kForm(void *labk2kform)
{
cmsDeleteTransform(reinterpret_cast<cmsHTRANSFORM>(labk2kform));
}
extern "C" void deletelabk2cmykForm(void *labk2cmykform)
{
cmsDeleteTransform(reinterpret_cast<cmsHTRANSFORM>(labk2cmykform));
}
extern "C" void deleteRevInt(void *rev)
{
reinterpret_cast<RevInt*>(rev)->~RevInt();
}
|
e0c54dde36d61b7c77c3a9a0d6672c99f25b178a
|
d0a5efa8f028b8eaccc8c536f01e61a8ab32accf
|
/include/majreco/Configuration.h
|
7b1471a3a8d65398099a002b81203b9424314de6
|
[] |
no_license
|
hcsullivan12/Majorana
|
f9faab5e84ffe79947e62030808263be3b5d0207
|
b5f15f48bb87f034ba0ce6fac17c1131b21a903d
|
refs/heads/master
| 2021-06-24T02:30:23.124268
| 2019-11-26T11:40:56
| 2019-11-26T11:40:56
| 164,157,853
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,449
|
h
|
Configuration.h
|
/**
* @file Configuration.h
* @author H. Sullivan (hsulliva@fnal.gov)
* @brief Singleton to hold user configuration for simulation
* and reconstruction.
* @date 07-04-2019
*
*/
#ifndef MAJRECO_CONFIGURATION_H
#define MAJRECO_CONFIGURATION_H
#include <string>
#include <array>
#include <vector>
#include <iostream>
#include "G4SystemOfUnits.hh"
#include "G4PhysicalConstants.hh"
#include "G4Types.hh"
namespace majreco
{
class Configuration
{
public:
static Configuration* Instance();
static Configuration* CreateInstance();
~Configuration();
/**
* @brief Initialize our configuration.
*
* @param configPath The path to the configuration file.
*/
void Initialize(const std::string& configPath);
/**
* @brief Validate the configuration.
*
*/
void CheckConfiguration();
void PrintConfiguration();
size_t PenalizedStopId() const { return fPenalizedStopId; }
size_t UnpenalizedStopId() const { return fUnpenalizedStopId; }
float Gamma() const { return fGamma; }
bool DoPenalized() const { return fDoPenalized; };
std::string SimulateOutputPath() const { return fSimulateOutputPath; };
std::string PixelizationPath() const { return fPixelizationPath; };
std::string OpReferenceTablePath() const { return fOpReferenceTablePath; };
std::string RecoOutputPath() const { return fRecoOutputPath; };
private:
Configuration();
static Configuration* instance;
/**
* @brief Read the configuration file that's passed at runtime
*
*/
void ReadConfigFile();
std::string fConfigPath; ///< Path to configuration file
std::string fSimulateOutputPath; ///< Output path for simulation
std::string fRecoOutputPath; ///< Output path for reconstruction anatree
std::string fPixelizationPath; ///< Path to pixelization scheme
std::string fOpReferenceTablePath; ///< Path to optical lookup table
size_t fPenalizedStopId; ///< Iteration number to stop penalized reconstruction
size_t fUnpenalizedStopId; ///< Iteration number to stop unpenalized reconstruction
float fGamma; ///< Strength parameter used for penalized reconstruction
bool fDoPenalized; ///< Option to run penalized reconstruction
};
}
#endif
|
e1555cf7af99c971e64b275a2023bde55a884abf
|
6b2a8dd202fdce77c971c412717e305e1caaac51
|
/solutions_1480487_0/C++/Tokiru/main.cpp
|
a0565c5526827714d324490ddfb80bf12e5cd67b
|
[] |
no_license
|
alexandraback/datacollection
|
0bc67a9ace00abbc843f4912562f3a064992e0e9
|
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
|
refs/heads/master
| 2021-01-24T18:27:24.417992
| 2017-05-23T09:23:38
| 2017-05-23T09:23:38
| 84,313,442
| 2
| 4
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,261
|
cpp
|
main.cpp
|
#include <iostream>
#include <fstream>
#include <algorithm>
#include <iomanip>
#include <assert.h>
using namespace std;
const int MN = 242;
int n;
int result [MN];
int main()
{
ifstream in ("input.txt");
ofstream out ("output.txt");
int T;
in >> T;
for (int t=1; t <= T; t++) {
in >> n;
double sum = 0;
for (int i=1; i <= n; i++) {
in >> result [i];
sum += result [i];
}
double Sum = sum;
out << "Case #" << t << ": ";
for (int i=1; i <= n; i++) {
double minans = 0;
double maxans = 1;
for (int it=0; it < 100; it++) {
double ans = (maxans + minans) / 2;
double x = Sum*ans + result [i];
double sumk = 0;
for (int j=1; j <= n; j++) {
if (i != j) {
if (x > result [j]) {
sumk += (x - result [j]) / Sum;
}
}
}
if (sumk + ans <= 1) minans = ans; else maxans = ans;
}
out << 100*(minans + maxans) / 2;
if (i != n) out << " ";
}
out << endl;
}
}
|
bebe51e3c17d7b225c9ad48375790a771c8c5c17
|
99f93e73e266589f9be1595e98bb6de72d953f5d
|
/cppCode/main.h
|
6d7d85bb534b9b23551c1add1ba0a49a10c4eea1
|
[] |
no_license
|
rob521/Gone-Fishin
|
a5c25227a2b03d2673837df8505db39b6cd342f0
|
a7be9b36c8969e1901ea84e9ea0547933a808d95
|
refs/heads/master
| 2021-01-21T13:25:45.648951
| 2016-06-02T20:19:25
| 2016-06-02T20:19:25
| 55,574,918
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 660
|
h
|
main.h
|
#ifndef _MAIN_
#define _MAIN_
#include<iostream>
using namespace std;
const bool userTest = false;
const char fileName[] = "Fish.csv";
const int BUFFER = 200,
delaystabalize = 10000, // 50 sec delay
csvOffset = 425;
const char port[] = "COM3",
matlab[] = "matlabCode.exe";
Serial arduino((char *)port);
enum sendCommands{stepper1, stepper2, servo1, servo2};
enum recieveCommands{up, down, stop, start};
struct location{
int xAxis, yAxis;
};
const struct location dropoffLoc{-200, 0};//*********************************************
//Functions
void moveBot(int, int);
#endif // _MAIN_
|
ab7e4488bce91036275a8bd9f6584da02a69ce9f
|
c637a256bb914409836f821dc972bff8d60aaaf2
|
/tests/cedet/ede/src/generic/gen_make/sub/test.cpp
|
e76ab160448bbced4bb05a14611f1e8f495abbfe
|
[] |
no_license
|
abo-abo/cedet
|
17bf0ebd7ef018fe3b7dffcbaa9892a54e1357e1
|
56e75b0323b87a0c32becd4e0f24bf69ff6f951c
|
refs/heads/master
| 2021-01-18T22:33:58.682998
| 2015-04-29T08:47:54
| 2016-05-11T11:50:50
| 32,517,164
| 7
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 30
|
cpp
|
test.cpp
|
// C file in generic project.
|
31ea62c99d8e5c0d45f788dbdf6710e0c14a0c70
|
031116cb55dfcdf629fc9dbe6230d399ee108d09
|
/dictionary.h
|
4a989ca76e5ee6fa41ef3c47f9eedcf376ecedf4
|
[] |
no_license
|
qeqs/Dictionary
|
fd7519bd219a5e879dadd019e2c7ef187b3ab8f8
|
deed72ece26c5cab516968b4f7f675292798af90
|
refs/heads/master
| 2021-01-19T08:18:01.539941
| 2017-04-16T18:19:50
| 2017-04-16T18:19:50
| 87,618,551
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 926
|
h
|
dictionary.h
|
#ifndef DICTIONARY_H
#define DICTIONARY_H
#include "map"
#include "list"
#include "string"
#include "initializer.h"
#include "wordlinker.h"
using namespace std;
class Dictionary
{
public:
Dictionary();
void create_new(string name, string name2, map<string,string>* words);
void update_one(string name, string name2, map<string,string>* words);
void delete_one(string name);
void reload();
string find(string name, string name2, string word);
map<string,string>* find_many(string name, string name2, list<string>* words);
~Dictionary()
{
delete wordLinker;
delete initializer;
for(pair<string, map<long,string>*> const &ent : dictionaries) {
delete ent.second;
}
delete dictionaries;
}
private:
map<string, map<long,string>*>* dictionaries;
Initializer* initializer;
WordLinker* wordLinker;
};
#endif // DICTIONARY_H
|
fa5039e51498309f2e1a20c8d9421e99c50c3442
|
aca6b5bd57c7eb0f403cd2caf799e827d60f7b08
|
/globals.h
|
46349c7b5ae201fc8e9e17dbcba5667fb7e3467c
|
[] |
no_license
|
hamishHay/ODIS
|
d99691d075b637945674c39874f1ada1a01f9a8b
|
4411f453c3a83463cfb80b486bd95956206216d7
|
refs/heads/master
| 2022-03-24T14:14:10.586056
| 2017-03-20T19:00:02
| 2017-03-20T19:00:02
| 37,612,898
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,288
|
h
|
globals.h
|
// FILE: globals.h
// DESCRIPTION: Header file for the globals class. Globals is an object designed
// to store useful model constants that, if necessary, are accessible
// anywhere in the code. These are listed and defined below in the
// public section of the class below, but include useful quantities
// like planetary radius, rotation rate, drag coefficient, etc. Each
// variable is of type GlobalVar (defined in globalVar.h), with the
// corresponding machine type held therein.
//
// Version Date Programmer
// 0.1 | 13/09/2016 | H. Hay |
// ---- Initial version of ODIS, described in Hay and Matsuyama (2016)
#ifndef GLOBALS_H
#define GLOBALS_H
#ifdef _WIN32
#define SEP "\\"
#elif _WIN64
#define SEP "\\"
#elif __linux__
#define SEP "/"
#else
#error "OS not supported!"
#endif
#include <string>
#include <array>
#include <vector>
#include "globalVar.h"
#include "outFiles.h"
// define pi here - c++ has no built in value of pi, so it is explicitly defined
// here
const double pi = 3.1415926535897932384626433832795028841971693993751058;
const double radConv = pi / 180.0; // global constant for converting deg --> rad
const int PATH = 512; // global int for number of characters in the system path
enum Friction { LINEAR, QUADRATIC }; // enumerate for drag type, selected by user
//Class stores all global values
class Globals {
private:
// Two member functions for setting all constants (default is for Titan)
void SetDefault(void);
void OutputConsts(void); // Print all constants to output file.
public:
// Class containing functions to output errors and messages, or terminate ODIS.
OutFiles Output;
// Vector to store a 'list' of all global constants.
// Note that it stores the template IGlobalVar pointer rather than GlobalVar.
// This is allows multiple types to be stored in one vector instance.
std::vector<IGlobalVar *> allGlobals;
Friction fric_type;
// Stringstream for composing outgoing messages, which is then passed to Output.
std::ostringstream outstring;
// string to store path of current simulation.
std::string path;
// character array for identical string from 'path'
char cpath[PATH];
GlobalVar<double> angVel; // Angular velocity
GlobalVar<double> radius; // Body radius
GlobalVar<double> loveK2; // k_2 Love Number
GlobalVar<double> loveH2; // h_2 Love Number
GlobalVar<double> loveReduct; //Love's reduction factor
GlobalVar<double> h; //Ocean thickness
GlobalVar<double> g; //Surface Gravity
GlobalVar<double> a; //SemiMajor Axis
GlobalVar<double> e; //Eccentricity
GlobalVar<double> theta; // obliquity
GlobalVar<double> timeStep; // Simulation timestep
GlobalVar<double> alpha; // drag coefficient
GlobalVar<int> l_max; //Maximum spherical harmonic degree for expansions
GlobalVar<double> dLat; //NUMBER of cells in latitude
GlobalVar<double> dLon; //NUMBER of cells in longitude
GlobalVar<double> period; // orbital period (=rotation period), assuming syncronous rotation.
GlobalVar<double> endTime; // maximum simulation run time
GlobalVar<std::string> potential; // string for tidal potential type
GlobalVar<std::string> friction; // string for drag type
GlobalVar<bool> init; // boolean for using initial conditions
GlobalVar<double> converge; // convergence criteria for ODIS.
// Variables to switch on or off output of certain Variables
// i.e., setting kinetic to true outputs global averaged kinetic energy
GlobalVar<bool> diss; // dissipated energy
GlobalVar<bool> kinetic; // kinetic energy
GlobalVar<bool> work; // work flux - currently not implemented.
GlobalVar<bool> field_displacement_output;
GlobalVar<bool> field_velocity_output;
GlobalVar<bool> field_diss_output;
GlobalVar<bool> sh_coeff_output;
// Time in fraction of orbital period for output of all parameters
GlobalVar<double> outputTime;
// constructor to initialise and/or read all variables from input file.
Globals();
Globals(int action); // action is either 1 (use defaults) or 0 (read input)
// Member function to read global variables from input.in file.
int ReadGlobals(void);
};
#endif
|
0864a167f5c8e6d88853f420f1cf796fe3dee3fc
|
e38674d871d484bfd69ea96d786a18200f237da4
|
/Search & Sort/find_missing_and_repeating.cpp
|
9825df12f50dca0ad0257b91e2effce28b940f30
|
[] |
no_license
|
r0cket007/450_DSA_Question
|
9cc2019277040fedac7e31613a98890d010b0296
|
d3354ea703452bfb844dbce65d2706b68ac2fdf7
|
refs/heads/master
| 2023-06-20T20:04:18.609746
| 2021-07-28T17:58:57
| 2021-07-28T17:58:57
| 360,415,728
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,356
|
cpp
|
find_missing_and_repeating.cpp
|
/*
Find Missing And Repeating
Link: https://practice.geeksforgeeks.org/problems/find-missing-and-repeating2512/1#
*/
#include<bits/stdc++.h>
#define int long long
using namespace std ;
//---------------------------------------------------------------------------
class Solution{
public:
long long *findTwoElement(int *arr, int n)
{
long long repeated = 1;
long long missing = 0;
long long sum = 0;
for(int i = 0; i < n; i ++)
{
if( arr[abs(arr[i]) - 1] < 0 )
{
repeated = abs(arr[i]);
}
else arr[abs(arr[i]) - 1] = -arr[abs(arr[i]) - 1];
sum += abs(arr[i]);
}
long long temp = ((long long)n * (n + 1)) / 2;
sum -= repeated;
missing = temp - sum;
long long *ans = new long long[2];
ans[0] = repeated;
ans[1] = missing;
return ans;
}
};
//---------------------------------------------------------------------------
signed main( )
{
int testcases = 1 ;
cin >> testcases ;
while( testcases -- )
{
int n ;
int arr[] = {1, 2, 3, 4, 4, 5, 6, 7};
n = 7;
Solution obj;
int *ans = obj.findTwoElement(arr, n);
cout << endl ;
}
return 0 ;
}
|
8a619de1be05e0ddddaf57ae3492ac81ee44fb84
|
485303ba578e154b2c0c110f8e0fec758d921ed0
|
/week-06/exam/Exercise3/PaperbackBooks.cpp
|
a1efc3cdfc6060819952bf1768735f52ce7d4eb8
|
[] |
no_license
|
green-fox-academy/mazurgab
|
0b6e3c3a7fe0a4940ff80c4e25f9f386b408ab7b
|
1eae9aae0338122a3d1536fecd2eb15dc7871a3e
|
refs/heads/master
| 2020-04-02T17:22:07.998691
| 2019-04-28T21:52:14
| 2019-04-28T21:52:14
| 154,655,053
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 301
|
cpp
|
PaperbackBooks.cpp
|
#include "PaperbackBooks.h"
PaperbackBooks::PaperbackBooks(const std::string &title, const std::string &author, int releaseYear, int pageNumber)
: Books(title, author, releaseYear, pageNumber) {}
int PaperbackBooks::getWeight() {
_weight = 20 + (_pageNumber * 10);
return _weight;
}
|
c0845459ee3b7d1011c85231c16b80df13a15615
|
ead0f3f313bdd574545794b0c372eca6bbca9830
|
/12844XOR.cpp
|
74c95fc3f9119f707254723ed3388c69b74ebd75
|
[] |
no_license
|
tomcruse/algorithm
|
fe237ea40d6c29add4b124b84f8714f846a8e385
|
3029b7ea498c9b63c145f5d5bda26dfd7a17a447
|
refs/heads/master
| 2021-06-23T00:23:38.983751
| 2017-08-19T17:14:56
| 2017-08-19T17:14:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,646
|
cpp
|
12844XOR.cpp
|
#include<cstdio>
#include<algorithm>
using namespace std;
int seg[2002000], lazy[2002000];
int init(int pos, int val, int node, int l, int r) {
if (pos<l || pos>r) return seg[node];
if (l == r) return seg[node] = val;
int mid = (l + r) >> 1;
return seg[node] = init(pos, val, node * 2, l, mid) ^ init(pos, val, node * 2 + 1, mid + 1, r);
}
void lazy_func(int node, int l, int r) {
if (lazy[node]) {
seg[node] ^= ((r - l + 1) & 1)*lazy[node];
if (l != r) {
lazy[node * 2] ^= lazy[node];
lazy[node * 2 + 1] ^= lazy[node];
}
lazy[node] = 0;
}
}
int update(int lo, int hi, int val, int node, int l, int r) {
lazy_func(node, l, r);
if (lo > r || l > hi) return seg[node];
if (lo <= l && hi >= r) {
seg[node] ^= ((r - l + 1) & 1)*val;
if (l != r) {
lazy[node * 2] ^= val;
lazy[node * 2 + 1] ^= val;
}
return seg[node];
}
int mid = (l + r) >> 1;
return seg[node] = update(lo, hi, val, node * 2, l, mid) ^ update(lo, hi, val, node * 2 + 1, mid + 1, r);
}
int query(int lo, int hi, int node, int l, int r) {
lazy_func(node, l, r);
if (lo > r || l > hi) return 0;
if (lo <= l && hi >= r) return seg[node];
int mid = (l + r) >> 1;
return query(lo, hi, node * 2, l, mid) ^ query(lo, hi, node * 2 + 1, mid + 1, r);
}
int main() {
int n, m;
scanf("%d", &n);
for (int i = 0; i < n; i++) {
int val;
scanf("%d", &val);
init(i, val, 1, 0, n - 1);
}
scanf("%d", &m);
for (int i = 0; i < m; i++) {
int t, a, b, c;
scanf("%d%d%d", &t, &a, &b);
if (a > b) swap(a, b);
if (--t)
printf("%d\n", query(a, b, 1, 0, n - 1));
else {
scanf("%d", &c);
update(a, b, c, 1, 0, n - 1);
}
}
return 0;
}
|
88f74b3f00a9862dc7a1f7978da1b3b981e68091
|
28c89d3ee00a86d4b9c3b6f043a87d1f238ed4b9
|
/io/filter/indent_output.hpp
|
aac7251e27a5ea39f8aeb57b0fd4639e8ea970b9
|
[] |
no_license
|
rsenn/libborg
|
9063f2077b2637e36e7c6402daa90f7ecdc94335
|
2476468f8e16c47a773ae6c37fec5af4866b494d
|
refs/heads/master
| 2020-04-05T23:45:57.718334
| 2016-02-03T04:06:32
| 2016-02-03T04:06:32
| 21,788,373
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,094
|
hpp
|
indent_output.hpp
|
//----------------------------------------------------------------------------
//! \file indent_output.hpp
//! \brief Implements indent_output.
//! \svn $Id: wrapper.hpp 42 2007-03-23 01:49:14Z nexbyte $
//----------------------------------------------------------------------------
#ifndef INDENT_OUTPUT_HPP
#define INDENT_OUTPUT_HPP
#include <boost/iostreams/filter/newline.hpp>
#include <io/filter/detail/indentation_state.hpp>
#include <string>
#include <cctype>
namespace io { namespace filter {
using namespace boost;
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
class indent_output : public iostreams::output_filter
{
public:
explicit
indent_output(char const indent_char = ' ',
bool const leading_space = true) :
m_indent(indent_char),
m_leading_space(leading_space),
m_newline(true)
{}
template<typename Sink>
bool
put(Sink &dest, int c)
{
using std::isspace;
using iostreams::newline::CR;
using iostreams::newline::LF;
if(c == CR || c == LF)
m_newline = true;
else if(m_newline)
{
if(m_leading_space == false)
{
if(isspace(c))
return true;
}
m_newline = false;
int n = m_state.get();
for(int i = 0; i < n; ++i)
{
if(iostreams::put(dest, m_indent) == false)
return false;
}
}
return iostreams::put(dest, c);
}
template<typename Sink>
void
close(Sink &dest)
{
m_newline = true;
m_state.set(0);
}
detail::indentation_state &
state()
{
return m_state;
}
private:
char const m_indent;
bool const m_leading_space;
bool m_newline;
detail::indentation_state m_state;
};
//----------------------------------------------------------------------------
BOOST_IOSTREAMS_PIPABLE(indent_output, 0)
}} // namespace io::filter
//----------------------------------------------------------------------------
#endif //ndef INDENT_OUTPUT_HPP
|
ec9dab326973c3830845d8caac99751a72455938
|
8700d558b948dc42c422f5b7760cf4d32b91f538
|
/src/mcapi/dmalloc/dmalloc.cpp
|
8ebaa3d22c77d29f27a633ae190c9ac02809bd84
|
[] |
no_license
|
lubing521/mcapi
|
6594faf85494d51b28b934f537925a06235a8e26
|
b0b9bada1e307ee347e2d7d8486319d9fc63bfce
|
refs/heads/master
| 2020-12-31T05:56:07.260336
| 2012-04-09T01:29:39
| 2012-04-09T01:29:39
| null | 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 6,764
|
cpp
|
dmalloc.cpp
|
/*
* Copyright (c) 2006-2008
* Author: Weiming Zhou
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation.
*/
#ifdef _WIN32
#define _WIN32_WINNT 0x0403
#include <windows.h>
#else
#include <sys/sysinfo.h>
#endif
#include <omp.h>
#include "CapiGlobal.h"
#include "CScopedLock.h"
#include "BigMemory.h"
#include "FreeList.h"
#include "MemoryPool.h"
#include "CLocalQueue.h"
#include "CSharedQueue.h"
#ifdef _WIN32
#define DLLAPI __declspec(dllexport)
#else
#define DLLAPI
#endif
#ifdef _WIN32
#define TlsGetValueFunc TlsGetValue
#define TlsSetValueFunc TlsSetValue
#else
#define TlsGetValueFunc pthread_getspecific
#define TlsSetValueFunc pthread_setspecific
#endif
// 箱子结构体定义
// 一个箱子中包含管理不同尺寸内存的多个FreeLists
typedef struct BIN_st {
FREELISTS aFreeLists[MAX_MEMORY_CLASS];
} BIN;
extern "C" void ThreadExit_Notification(void* arg);
#ifdef _WIN32
static DWORD g_TlsPointer; // 线程本地存储索引指针
#else
pthread_key_t g_TlsPointer;
#endif
// 全局的箱子队列,主要为箱子重复利用而设计
CSharedQueue<BIN *, CLocalQueue<BIN *> > g_BinQueue(8);
LONG volatile g_InitFlag = 0;
LONG volatile g_dmalloc_init_finished_flag = 0;
CFastLock g_InitdmallocFastLock;
/** 初始化线程本地存储
@return void - 无
*/
static void ThreadTls_Init(void)
{
#ifdef _WIN32
g_TlsPointer = TlsAlloc();
#else
pthread_key_create( &g_TlsPointer, ThreadExit_Notification );
#endif
}
/** 创建一个箱子
@return BIN * - 返回创建的箱子指针
*/
static BIN *CreateBin()
{
BIN *pBin = new BIN;
UINT i;
for ( i = 0; i < MAX_MEMORY_CLASS; i++)
{
FreeLists_Init(&(pBin->aFreeLists[i]), g_auMemSize[i] );
}
return pBin;
}
/** 获取当前线程对应的箱子指针函数
通过访问线程本地存储来取得箱子指针
@return BIN * - 获取当前线程对应的箱子指针
*/
static BIN * GetBinOfCurThread(void)
{
BIN *pBin;
pBin = (BIN *)TlsGetValueFunc(g_TlsPointer);
if ( pBin == (BIN *)0 )
{
if ( g_BinQueue.DeQueue(pBin) == CAPI_FAILED )
{
pBin = CreateBin();
}
TlsSetValueFunc(g_TlsPointer, (void *)pBin);
}
return pBin;
}
/** 初始化分布式内存管理器
主要是初始化线程本地存储、初始化大块内存管理器,
创建一定数量的箱子并加入到箱子队列中
@param int nMaxThreads - 初始线程数量,初始线程数量决定着初始预创建好的箱子数量,
初始箱子数量比线程数量少时,线程初始化时会创建新的箱子,
因此初始线程数量不能超出最大线程数量,否则会造成箱子数量的浪费。
@return void - 无
*/
static void Init_dmalloc(int nMaxThreads)
{
BIN *pBin;
// 初始化线程本地存储
ThreadTls_Init();
#ifdef _WIN32
//获取系统内存的大小
MEMORYSTATUS stat;
GlobalMemoryStatus (&stat);
// 初始化大块内存管理器,使用可用物理内存
// 如果需要,可以改成使用可用虚拟内存
BigMemory_Init(stat.dwAvailPhys/BIG_MEMORY_SIZE);
#else
struct sysinfo s_info;
sysinfo(&s_info);
BigMemory_Init(s_info.freeram/BIG_MEMORY_SIZE);
#endif
// 初始化内存池
MemoryPool_Init();
int i;
// 可以考虑将下面循环并行化执行
for ( i = 0; i < nMaxThreads; i++ )
{
// 创建箱子,并加入箱子队列中
pBin = CreateBin();
g_BinQueue.EnQueue(pBin);
}
}
static void CheckInit_dmalloc()
{
CScopedLock<CFastLock> slock(g_InitdmallocFastLock);
if ( 0 == g_InitFlag )
{
// flag 等于1表明是第1个将g_InitFlag变量进行原子加1的线程
// 这样确保了Init_dmalloc()只被执行一次。
Init_dmalloc(omp_get_num_procs());
g_InitFlag = 1;
AtomicIncrement(&g_dmalloc_init_finished_flag);
}
}
/** 分布式内存管理的内存分配函数
@param UINT uSize - 要分配的内存大小
@return void * - 返回分配到的内存指针,如果系统内存不够用时会返回NULL
*/
extern "C" DLLAPI void * dmalloc(UINT uSize)
{
BIN *pBin;
if ( 0 == g_dmalloc_init_finished_flag )
{
CheckInit_dmalloc();
}
// 先通过线程本地存储找到箱子指针
pBin = GetBinOfCurThread();
// 通过内存大小获取箱子中的FreeLists索引
int index = MemoryPool_GetMemSizeIndex(uSize);
// 从FreeLists中分配内存
void * p = FreeLists_Alloc( &(pBin->aFreeLists[index]));
return p;
}
/** 分布式内存管理的内存释放函数
@param void *p - 要释放的内存
@return void - 无
*/
extern "C" DLLAPI void dfree(void *p)
{
BIN * pBin;
BLOCK * pBlock = BigMemory_GetBlockPtr(p);
pBin = GetBinOfCurThread();
int index = MemoryPool_GetMemSizeIndex(pBlock->uMemSize);
FreeLists_Free(&(pBin->aFreeLists[index]), p);
return;
}
/** 关闭分布式内存管理
这个函数最好不要轻易使用
除非能够确定所有分配的内存都在调用这个函数前被释放了
当有全局的类变量并且类中采用dmalloc分配了内存时,
那么程序退出时还有内存在使用,就不能调用这个函数了,
而要让进程自动去释放内存。
@return void - 无
*/
extern "C" DLLAPI void Close_dmalloc()
{
BIN *pBin;
while ( g_BinQueue.DeQueue(pBin) != CAPI_FAILED )
{
delete pBin;
}
BigMemory_Close();
#ifdef USE_WINTHREAD
TlsFree(g_TlsPointer);
#endif
return;
}
/** 线程退出时的处理函数
主要为线程退出时处理线程本地存储而设计
可用作pthread_key_create的回调函数,
在Windows中则用作DLL入口函数中的DLL_THREAD_DETACH消息中使用
@param void* arg - 参数,不使用
@return void - 无
*/
extern "C" void ThreadExit_Notification(void* arg)
{
if ( g_dmalloc_init_finished_flag == 0 )
{
return;
}
BIN * pBin = GetBinOfCurThread();
if ( pBin )
{
// 将退出线程的箱子放入队列中便于其他线程重复使用
g_BinQueue.EnQueue(pBin);
}
return;
}
|
b0b9885a7c150faba0d3a50b539155ea22a77e52
|
bbac388eb6b53daec63190e2f271a18fe9bfb163
|
/apc001/D.cpp
|
c3cbf13d887d55f8525cbe3bbe9c7d5fc50f0e02
|
[] |
no_license
|
tatsumack/atcoder
|
8d94cf29160b6553b0c089cb795c54efd3fb0f7b
|
fbe1e1eab80c4c0680ec046acdc6214426b19650
|
refs/heads/master
| 2023-06-17T23:09:54.056132
| 2021-07-04T13:03:59
| 2021-07-04T13:03:59
| 124,963,709
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,420
|
cpp
|
D.cpp
|
#include <limits.h>
#include <algorithm>
#include <bitset>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <functional>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
#include <queue>
#include <unordered_map>
#include <unordered_set>
#define int long long
#define REP(i, n) for (int i = 0, i##_len = (n); i < i##_len; ++i)
#define REPS(i, n) for (int i = 1, i##_len = (n); i <= i##_len; ++i)
#define FOR(i, a, b) for (int i = (a), i##_len = (b); i <= i##_len; ++i)
#define REV(i, a, b) for (int i = (a); i >= (b); --i)
#define CLR(a, b) memset((a), (b), sizeof(a))
#define DUMP(x) cout << #x << " = " << (x) << endl;
#define INF 1001001001001001001ll
#define fcout cout << fixed << setprecision(10)
using namespace std;
template<typename T>
vector<T> make_v(size_t a) { return vector<T>(a); }
template<typename T, typename... Ts>
auto make_v(size_t a, Ts... ts) {
return vector<decltype(make_v<T>(ts...))>(a, make_v<T>(ts...));
}
template<typename T, typename V>
typename enable_if<is_class<T>::value == 0>::type
fill_v(T& t, const V& v) { t = v; }
template<typename T, typename V>
typename enable_if<is_class<T>::value != 0>::type
fill_v(T& t, const V& v) {
for (auto& e:t) fill_v(e, v);
}
typedef pair<int, int> P;
struct UnionFind {
vector<int> par;
vector<int> rank;
vector<int> vsize;
UnionFind(int size) : par(size), rank(size), vsize(size) {
REP(i, size) {
par[i] = i;
rank[i] = 0;
vsize[i] = 1;
}
}
int find(int x) {
if (par[x] == x) {
return x;
} else {
return par[x] = find(par[x]);
}
}
void unite(int x, int y) {
x = find(x), y = find(y);
if (x == y) return;
if (rank[x] < rank[y]) {
par[x] = y;
} else {
par[y] = x;
if (rank[x] == rank[y]) rank[x]++;
}
vsize[x] += vsize[y];
vsize[y] = vsize[x];
}
bool same(int x, int y) { return find(x) == find(y); }
int getSize(int x) { return vsize[find(x)]; }
};
signed main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int N, M;
cin >> N >> M;
vector<int> a(N);
REP(i, N) cin >> a[i];
UnionFind uf(N);
REP(i, M) {
int x, y;
cin >> x >> y;
uf.unite(x, y);
}
if (M == N - 1) {
cout << 0 << endl;
return 0;
}
unordered_map<int, priority_queue<P, vector<P>, greater<P>>> pqs;
vector<P> v;
REP(i, N) {
int par = uf.find(i);
pqs[par].push({a[i], i});
v.emplace_back(a[i], i);
}
int g = pqs.size();
if (2 * (g - 1) > N) {
cout << "Impossible" << endl;
return 0;
}
int res = 0;
vector<bool> used(N);
for (auto& kv : pqs) {
auto& pq = kv.second;
res += pq.top().first;
used[pq.top().second] = true;
}
int cnt = g;
sort(v.begin(), v.end());
REP(i, N) {
int t = v[i].second;
if (used[t]) continue;
if (cnt == 2 * (g - 1)) break;
res += v[i].first;
cnt++;
}
cout << res << endl;
return 0;
}
|
32f0689b8b0d872652604e79815f92277bb854be
|
fad834bfe162796b77f1023b9f3a0ccddb0dd9ab
|
/include/splines/splines_aux.h
|
879c69d9d619dfff10c6cb8f5bd724390232c614
|
[] |
no_license
|
xpPaul/splines
|
e0765e7d83086c152644ead827188d4e22231884
|
9b9ec2e7035f654059dfc5067937734e0e1b58a3
|
refs/heads/master
| 2020-04-26T00:15:01.794446
| 2014-12-24T17:28:36
| 2014-12-24T17:28:36
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,479
|
h
|
splines_aux.h
|
///////////////////////////////////////////////////////////////////////////////
/// common definitions and auxiliary stuff
#pragma once
#include <stdexcept>
namespace gsl
{
typedef size_t size_type;
// ----------------------------------------------------------------
/// gsl exceptions base class
class exception : public std::runtime_error
{
public:
explicit exception( const std::string & msg ) : std::runtime_error(msg) {}
};
// ----------------------------------------------------------------
/// Derived segment decorators should use this macros to provide constructing ability
#define GSL_SEGMENT_DECORATOR(decorator) \
decorator () {} \
template < class Seg > decorator( const Seg & rhs ) : Base(rhs) {} \
template < class Seg > decorator& operator= ( const Seg & rhs ) { return *this = decorator(rhs); } \
template < typename InIt > decorator ( InIt first, InIt last ) : Base(first, last) {} \
typedef typename Base::parameter_type parameter_type; \
typedef typename Base::value_type value_type;
// ----------------------------------------------------------------
/// Derived spline decorators should use this macros to provide constructing ability
#define GSL_SPLINE_DECORATOR(decorator) \
decorator () {} \
template < typename InIt > decorator( InIt first, InIt last ) : Base::template apply<S>::type(first, last) {} \
template < typename OtherS > struct apply { typedef spline_arclength<Base, OtherS> type; }; \
template < class OtherS > decorator( const OtherS & rhs ) : Base::template apply<S>::type(rhs.begin(), rhs.end()) {} \
template < class OtherS > decorator& operator= ( const OtherS & rhs ) { return *this = decorator(rhs); } \
typedef S segment_type; \
typedef typename segment_type::parameter_type parameter_type; \
typedef typename segment_type::value_type value_type;
// ----------------------------------------------------------------
namespace details
{
inline size_type d_coef( size_type n, size_type k )
{
if ( k > n ) return 0;
if ( k == 0 ) return 1;
size_t ret = n;
while ( --k )
ret *= --n;
return ret;
}
template < class T > T fac( size_type n )
{
T res = 1;
for ( size_type i = 2; i <= n; i++ )
res *= i;
return res;
}
template < class T, class Fn > T golden_section( T a, T b, T accuracy, Fn f )
{
T s1 = (3 - sqrt(5.)) / 2;
T s2 = (sqrt(5.) - 1) / 2;
T u1 = a + s1 * (b - a);
T u2 = a + s2 * (b - a);
T fu1 = f(u1);
T fu2 = f(u2);
while ( fabs(a - b) > accuracy )
{
if ( fu1 <= fu2 )
{
b = u2;
u2 = u1;
fu2 = fu1;
u1 = a + s1 * (b - a);
fu1 = f(u1);
}
else
{
a = u1;
u1 = u2;
fu1 = fu2;
u2 = a + s2 * (b - a);
fu2 = f(u2);
}
}
return (fu1 < fu2) ? a : b;
}
// @todo refactor this
inline double norm_( double p )
{
return p;
}
inline bool eq_zero( double x )
{
return x < 1e-8;
}
// @todo move to value_type_traits ???
template < class value_type >
inline double norm_( const value_type & p )
{
return norm(p);
}
template < class value_type >
inline value_type perp_( const value_type & dir )
{
return perp(dir);
}
template < class value_type >
inline value_type normalized_( const value_type & p )
{
return normalized(p);
}
}
}
|
ad436dc64570a76efcc95d90e53c35bdc2beaa87
|
b783502faf6fda33eb03575c054a198306541f81
|
/PSME/agent/storage/src/command/get_network_interface_info.cpp
|
81732acbbde079e4c0e8a98c0efef66bdba2b6ae
|
[
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"MIT",
"JSON",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-other-permissive"
] |
permissive
|
intelsdi-x/intelRSD
|
53f763e386de0b1cb9c50427d76943327e2b6315
|
de77af174608d3b30232625e0f0e6e7cbbae8b59
|
refs/heads/master
| 2022-11-23T03:14:50.978516
| 2022-11-07T23:02:34
| 2022-11-07T23:02:34
| 153,187,714
| 0
| 0
| null | 2018-10-15T22:06:10
| 2018-10-15T22:06:09
| null |
UTF-8
|
C++
| false
| false
| 1,347
|
cpp
|
get_network_interface_info.cpp
|
/*!
* @brief Implementation of getNetworkInterfaceInfo command.
*
* @header{License}
* @copyright Copyright (c) 2018 Intel Corporation
*
* 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.
*
* @header{Filesystem}
* @file get_network_interface_info.cpp
*/
#include "agent-framework/module/common_components.hpp"
#include "agent-framework/command/registry.hpp"
#include "agent-framework/command/storage_commands.hpp"
using namespace agent_framework;
using namespace agent_framework::command;
REGISTER_COMMAND(GetNetworkInterfaceInfo, [](const GetNetworkInterfaceInfo::Request& request,
GetNetworkInterfaceInfo::Response& response) {
log_debug("storage-agent", "Getting network interface info.");
response = module::get_manager<model::NetworkInterface>().get_entry(request.get_uuid());
});
|
7a759f3312facc4ed38cfc4f2bc5a16cd7292f7a
|
5d6e6beb365e5e52db41394826ccfbc3e51bcfb7
|
/nanosrv/nanosoft/core/netdaemon.h
|
148d5cfac29f67523c74d866d12a710b883c99c7
|
[
"MIT"
] |
permissive
|
zolotov-av/nanosoft
|
86d600d60ec74ae5b456a9d5afd7697883ac57ee
|
2aebb09d7d8a424d4de9b57d7586dbb72eed9fa0
|
refs/heads/master
| 2021-03-19T08:37:57.683170
| 2020-05-27T14:34:29
| 2020-05-27T14:39:26
| 97,500,048
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,477
|
h
|
netdaemon.h
|
#ifndef NANOSOFT_NETDAEMON_H
#define NANOSOFT_NETDAEMON_H
#include <nanosoft/core/object.h>
#include <nanosoft/core/netobject.h>
#include <sys/epoll.h>
#include <unistd.h>
#include <stdio.h>
#include <time.h>
/**
* Callback таймера
*/
typedef void (*timer_callback_t)();
/**
* Главный класс сетевого демона
*/
class NetDaemon
{
private:
/**
* Файловый дескриптор epoll
*/
int epoll;
/**
* Максимальное число обслуживаемых объектов
*/
size_t limit;
/**
* Текущее число объектов
*/
size_t count;
/**
* Карта объектов (fd -> AsyncObject)
*/
ptr<NetObject> *objects;
/**
* Состояние демона
*/
enum daemon_state_t {
/**
* Поток не запущен
*/
INACTIVE,
/**
* Поток в обычном рабочем цикле
*/
ACTIVE
};
daemon_state_t state;
/**
* Текущее время в секундах (Unix time)
*/
time_t tm;
/**
* Обработка системной ошибки
*/
void stderror();
/**
* Возобновить работу с асинхронным объектом
*/
bool resetObject(ptr<NetObject> &object);
public:
/**
* Установка таймера (вызывается примерно раз в секунду)
*/
timer_callback_t timer;
/**
* Конструктор демона
* @param aLimit максимальное число одновременных виртуальных потоков
*/
NetDaemon(int aLimit);
/**
* Деструктор демона
*/
virtual ~NetDaemon();
/**
* Вернуть число подконтрольных объектов
*/
int getObjectCount() const { return count; }
/**
* Вернуть максимальное число подконтрольных объектов
*/
int getObjectLimit() const { return limit; }
/**
* Добавить асинхронный объект
*/
bool addObject(ptr<NetObject> object);
/**
* Уведомить NetDaemon, что объект изменил свою маску
*/
void modifyObject(ptr<NetObject> object);
/**
* Удалить асинхронный объект
*/
bool removeObject(ptr<NetObject> object);
/**
* Запустить демона
*/
void run();
/**
* Завершить работу демона
*/
void terminate();
};
#endif // NANOSOFT_NETDAEMON_H
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.