blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e8e8968cabe7ef635c028c0bb345c101ec9d6f4d | e8ffccf6bf7c85f9ceb35eda423bcd0620b5423a | /http_libco/http_1.0/co_routine.cpp | d1d1e628742d474fba1a7ac11eda9ff897b78963 | [] | no_license | lanke0720/my_tinyproject | 96898e8cc8355ed15211bf3d08a56c718b877a8b | 4a13c6b28ef73a44f503028f2511821279ff5e25 | refs/heads/master | 2021-01-16T21:41:55.251617 | 2017-09-05T10:00:23 | 2017-09-05T10:00:23 | 100,245,505 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,724 | cpp | /*
* Tencent is pleased to support the open source community by making Libco available.
* Copyright (C) 2014 THL A29 Limited, a Tencent company. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "co_routine.h"
#include "co_routine_inner.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <string>
#include <map>
#include <poll.h>
#include <sys/epoll.h>
#include <sys/time.h>
#include <errno.h>
#include <assert.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/syscall.h>
#include <unistd.h>
extern "C"
{//协程切换
extern void coctx_swap( coctx_t *,coctx_t* ) asm("coctx_swap");
};
using namespace std;
stCoRoutine_t *GetCurrCo( stCoRoutineEnv_t *env );
struct stCoEpoll_t;
//保存协程运行环境,同一线程下的所有协程共享该结构
//全局的协程环境管理抽象体
struct stCoRoutineEnv_t
{ //协程栈,管理协程运行
stCoRoutine_t *pCallStack[ 128 ];
int iCallStackSize;
//epoll抽象体,管理所有事件
stCoEpoll_t *pEpoll;
};
//int socket(int domain, int type, int protocol);
void co_log_err( const char *fmt,... )
{
}
static unsigned long long counter(void);
static unsigned long long getCpuKhz()
{
FILE *fp = fopen("/proc/cpuinfo","r");
if(!fp) return 1;
char buf[4096] = {0};
fread(buf,1,sizeof(buf),fp);
fclose(fp);
char *lp = strstr(buf,"cpu MHz");
if(!lp) return 1;
lp += strlen("cpu MHz");
while(*lp == ' ' || *lp == '\t' || *lp == ':')
{
++lp;
}
double mhz = atof(lp);
unsigned long long u = (unsigned long long)(mhz * 1000);
return u;
}
static unsigned long long GetTickMS()
{
static uint32_t khz = getCpuKhz();
return counter() / khz;
}
static unsigned long long counter(void)
{
register uint32_t lo, hi;
register unsigned long long o;
__asm__ __volatile__ (
"rdtscp" : "=a"(lo), "=d"(hi)
);
o = hi;
o <<= 32;
return (o | lo);
}
static pid_t GetPid()
{
static __thread pid_t pid = 0;
static __thread pid_t tid = 0;
if( !pid || !tid || pid != getpid() )
{
pid = getpid();
tid = syscall( __NR_gettid );
}
return tid;
}
/*
static pid_t GetPid()
{
char **p = (char**)pthread_self();
return p ? *(pid_t*)(p + 18) : getpid();
}
*/
template <class T,class TLink>
void RemoveFromLink(T *ap)
{
TLink *lst = ap->pLink;
if(!lst) return ;
assert( lst->head && lst->tail );
if( ap == lst->head )
{
lst->head = ap->pNext;
if(lst->head)
{
lst->head->pPrev = NULL;
}
}
else
{
if(ap->pPrev)
{
ap->pPrev->pNext = ap->pNext;
}
}
if( ap == lst->tail )
{
lst->tail = ap->pPrev;
if(lst->tail)
{
lst->tail->pNext = NULL;
}
}
else
{
ap->pNext->pPrev = ap->pPrev;
}
ap->pPrev = ap->pNext = NULL;
ap->pLink = NULL;
}
template <class TNode,class TLink>
void inline AddTail(TLink*apLink,TNode *ap)
{
if( ap->pLink )
{
return ;
}
if(apLink->tail)
{
apLink->tail->pNext = (TNode*)ap;
ap->pNext = NULL;
ap->pPrev = apLink->tail;
apLink->tail = ap;
}
else
{
apLink->head = apLink->tail = ap;
ap->pNext = ap->pPrev = NULL;
}
ap->pLink = apLink;
}
template <class TNode,class TLink>
void inline PopHead( TLink*apLink )
{
if( !apLink->head )
{
return ;
}
TNode *lp = apLink->head;
if( apLink->head == apLink->tail )
{
apLink->head = apLink->tail = NULL;
}
else
{
apLink->head = apLink->head->pNext;
}
lp->pPrev = lp->pNext = NULL;
lp->pLink = NULL;
if( apLink->head )
{
apLink->head->pPrev = NULL;
}
}
template <class TNode,class TLink>
void inline Join( TLink*apLink,TLink *apOther )
{
//printf("apOther %p\n",apOther);
if( !apOther->head )
{
return ;
}
TNode *lp = apOther->head;
while( lp )
{
lp->pLink = apLink;
lp = lp->pNext;
}
lp = apOther->head;
if(apLink->tail)
{
apLink->tail->pNext = (TNode*)lp;
lp->pPrev = apLink->tail;
apLink->tail = apOther->tail;
}
else
{
apLink->head = apOther->head;
apLink->tail = apOther->tail;
}
apOther->head = apOther->tail = NULL;
}
// ----------------------------------------------------------------------------
struct stTimeoutItemLink_t;
struct stTimeoutItem_t;
//全局的epoll抽象体,所有协程共享一个。
//处理事件, 网络IO,超时,以及信号量事件
struct stCoEpoll_t
{
int iEpollFd; //epoll 监听套接字
static const int _EPOLL_SIZE = 1024 * 10;//最大事件数
struct stTimeout_t *pTimeout;//时间定时器
struct stTimeoutItemLink_t *pstTimeoutList;/* 保存已经超时的事件列表 */
struct stTimeoutItemLink_t *pstActiveList;/* 保存epoll_wait得到的就绪事件和定时器超时事件 */
};
typedef void (*OnPreparePfn_t)( stTimeoutItem_t *,struct epoll_event &ev, stTimeoutItemLink_t *active );
typedef void (*OnProcessPfn_t)( stTimeoutItem_t *);
struct stTimeoutItem_t
{
enum
{
eMaxTimeout = 20 * 1000 //20s
};
stTimeoutItem_t *pPrev;
stTimeoutItem_t *pNext;
stTimeoutItemLink_t *pLink;
unsigned long long ullExpireTime;
OnPreparePfn_t pfnPrepare;
OnProcessPfn_t pfnProcess;
void *pArg; // routine
bool bTimeout;
};
struct stTimeoutItemLink_t
{
stTimeoutItem_t *head;
stTimeoutItem_t *tail;
};
struct stTimeout_t
{
stTimeoutItemLink_t *pItems;
int iItemSize;
unsigned long long ullStart;
long long llStartIdx;
};
stTimeout_t *AllocTimeout( int iSize )
{
stTimeout_t *lp = (stTimeout_t*)calloc( 1,sizeof(stTimeout_t) );
lp->iItemSize = iSize;
lp->pItems = (stTimeoutItemLink_t*)calloc( 1,sizeof(stTimeoutItemLink_t) * lp->iItemSize );
lp->ullStart = GetTickMS();
lp->llStartIdx = 0;
return lp;
}
void FreeTimeout( stTimeout_t *apTimeout )
{
free( apTimeout->pItems );
free ( apTimeout );
}
int AddTimeout( stTimeout_t *apTimeout,stTimeoutItem_t *apItem ,unsigned long long allNow )
{
if( apTimeout->ullStart == 0 )
{
apTimeout->ullStart = allNow;
apTimeout->llStartIdx = 0;
}
if( allNow < apTimeout->ullStart )
{
co_log_err("CO_ERR: AddTimeout line %d allNow %llu apTimeout->ullStart %llu",
__LINE__,allNow,apTimeout->ullStart);
return __LINE__;
}
if( apItem->ullExpireTime < allNow )
{
co_log_err("CO_ERR: AddTimeout line %d apItem->ullExpireTime %llu allNow %llu apTimeout->ullStart %llu",
__LINE__,apItem->ullExpireTime,allNow,apTimeout->ullStart);
return __LINE__;
}
int diff = apItem->ullExpireTime - apTimeout->ullStart;
if( diff >= apTimeout->iItemSize )
{
co_log_err("CO_ERR: AddTimeout line %d diff %d",
__LINE__,diff);
return __LINE__;
}
AddTail( apTimeout->pItems + ( apTimeout->llStartIdx + diff ) % apTimeout->iItemSize , apItem );
return 0;
}
inline void TakeAllTimeout( stTimeout_t *apTimeout,unsigned long long allNow,stTimeoutItemLink_t *apResult )
{
if( apTimeout->ullStart == 0 )
{
apTimeout->ullStart = allNow;
apTimeout->llStartIdx = 0;
}
if( allNow < apTimeout->ullStart )
{
return ;
}
int cnt = allNow - apTimeout->ullStart + 1;
if( cnt > apTimeout->iItemSize )
{
cnt = apTimeout->iItemSize;
}
if( cnt < 0 )
{
return;
}
for( int i = 0;i<cnt;i++)
{
int idx = ( apTimeout->llStartIdx + i) % apTimeout->iItemSize;
Join<stTimeoutItem_t,stTimeoutItemLink_t>( apResult,apTimeout->pItems + idx );
}
apTimeout->ullStart = allNow;
apTimeout->llStartIdx += cnt - 1;
}
static int CoRoutineFunc( stCoRoutine_t *co,void * )
{
if( co->pfn )
{
co->pfn( co->arg );
}
co->cEnd = 1;
stCoRoutineEnv_t *env = co->env;
co_yield_env( env );
return 0;
}
struct stCoRoutine_t *co_create_env( stCoRoutineEnv_t * env,pfn_co_routine_t pfn,void *arg )
{
stCoRoutine_t *lp = (stCoRoutine_t*)malloc( sizeof(stCoRoutine_t) );
memset( lp,0,(long)((stCoRoutine_t*)0)->sRunStack );
lp->env = env;
lp->pfn = pfn;
lp->arg = arg;
lp->ctx.ss_sp = lp->sRunStack ;
lp->ctx.ss_size = sizeof(lp->sRunStack) ;
return lp;
}
int co_create( stCoRoutine_t **ppco,const stCoRoutineAttr_t *attr,pfn_co_routine_t pfn,void *arg )
{
if( !co_get_curr_thread_env() )
{
co_init_curr_thread_env();//初始化环境变量
}
stCoRoutine_t *co = co_create_env( co_get_curr_thread_env(),pfn,arg );
*ppco = co;
return 0;
}
void co_free( stCoRoutine_t *co )
{
free( co );
}
void co_release( stCoRoutine_t *co )
{
if( co->cEnd )
{
free( co );
}
}
void co_resume( stCoRoutine_t *co )
{
stCoRoutineEnv_t *env = co->env;
stCoRoutine_t *lpCurrRoutine = env->pCallStack[ env->iCallStackSize - 1 ];
if( !co->cStart )
{
coctx_make( &co->ctx,(coctx_pfn_t)CoRoutineFunc,co,0 );
co->cStart = 1;
}
env->pCallStack[ env->iCallStackSize++ ] = co;
coctx_swap( &(lpCurrRoutine->ctx),&(co->ctx) );
}
void co_yield_env( stCoRoutineEnv_t *env )
{
stCoRoutine_t *last = env->pCallStack[ env->iCallStackSize - 2 ];
stCoRoutine_t *curr = env->pCallStack[ env->iCallStackSize - 1 ];
env->iCallStackSize--;
coctx_swap( &curr->ctx, &last->ctx );
}
void co_yield_ct()
{
co_yield_env( co_get_curr_thread_env() );
}
void co_yield( stCoRoutine_t *co )
{
co_yield_env( co->env );
}
//int poll(struct pollfd fds[], nfds_t nfds, int timeout);
// { fd,events,revents }
struct stPollItem_t ;
struct stPoll_t : public stTimeoutItem_t
{
struct pollfd *fds;
nfds_t nfds; // typedef unsigned long int nfds_t;
stPollItem_t *pPollItems;
int iAllEventDetach;
int iEpollFd;
int iRaiseCnt;
};
struct stPollItem_t : public stTimeoutItem_t
{
struct pollfd *pSelf;
stPoll_t *pPoll;
struct epoll_event stEvent;
};
/*
* EPOLLPRI POLLPRI // There is urgent data to read.
* EPOLLMSG POLLMSG
*
* POLLREMOVE
* POLLRDHUP
* POLLNVAL
*
* */
static uint32_t PollEvent2Epoll( short events )
{
uint32_t e = 0;
if( events & POLLIN ) e |= EPOLLIN;
if( events & POLLOUT ) e |= EPOLLOUT;
if( events & POLLHUP ) e |= EPOLLHUP;
if( events & POLLERR ) e |= EPOLLERR;
return e;
}
static short EpollEvent2Poll( uint32_t events )
{
short e = 0;
if( events & EPOLLIN ) e |= POLLIN;
if( events & EPOLLOUT ) e |= POLLOUT;
if( events & EPOLLHUP ) e |= POLLHUP;
if( events & EPOLLERR ) e |= POLLERR;
return e;
}
static stCoRoutineEnv_t* g_arrCoEnvPerThread[ 102400 ] = { 0 };
void co_init_curr_thread_env()
{
pid_t pid = GetPid();
g_arrCoEnvPerThread[ pid ] = (stCoRoutineEnv_t*)calloc( 1,sizeof(stCoRoutineEnv_t) );
stCoRoutineEnv_t *env = g_arrCoEnvPerThread[ pid ];
printf("init pid %ld env %p\n",(long)pid,env);
env->iCallStackSize = 0;
struct stCoRoutine_t *self = co_create_env( env,NULL,NULL );
self->cIsMain = 1;
coctx_init( &self->ctx );
env->pCallStack[ env->iCallStackSize++ ] = self;
stCoEpoll_t *ev = AllocEpoll();
SetEpoll( env,ev );
}
stCoRoutineEnv_t *co_get_curr_thread_env()
{
return g_arrCoEnvPerThread[ GetPid() ];
}
void OnPollProcessEvent( stTimeoutItem_t * ap )
{
stCoRoutine_t *co = (stCoRoutine_t*)ap->pArg;
co_resume( co );
}
void OnPollPreparePfn( stTimeoutItem_t * ap,struct epoll_event &e,stTimeoutItemLink_t *active )
{
stPollItem_t *lp = (stPollItem_t *)ap;
lp->pSelf->revents = EpollEvent2Poll( e.events );
stPoll_t *pPoll = lp->pPoll;
pPoll->iRaiseCnt++;
if( !pPoll->iAllEventDetach )
{
pPoll->iAllEventDetach = 1;
RemoveFromLink<stTimeoutItem_t,stTimeoutItemLink_t>( pPoll );
AddTail( active,pPoll );
}
}
void co_eventloop( stCoEpoll_t *ctx,pfn_co_eventloop_t pfn,void *arg )
{
epoll_event *result = (epoll_event*)calloc(1, sizeof(epoll_event) * stCoEpoll_t::_EPOLL_SIZE );
for(;;)
{
int ret = epoll_wait( ctx->iEpollFd,result,stCoEpoll_t::_EPOLL_SIZE, 1 );
stTimeoutItemLink_t *active = (ctx->pstActiveList);
stTimeoutItemLink_t *timeout = (ctx->pstTimeoutList);
memset( active,0,sizeof(stTimeoutItemLink_t) );
memset( timeout,0,sizeof(stTimeoutItemLink_t) );
for(int i=0;i<ret;i++)
{
stTimeoutItem_t *item = (stTimeoutItem_t*)result[i].data.ptr;
if( item->pfnPrepare )
{
item->pfnPrepare( item,result[i],active );
}
else
{
AddTail( active,item );
}
}
unsigned long long now = GetTickMS();
TakeAllTimeout( ctx->pTimeout,now,timeout );
stTimeoutItem_t *lp = timeout->head;
while( lp )
{
//printf("raise timeout %p\n",lp);
lp->bTimeout = true;
lp = lp->pNext;
}
Join<stTimeoutItem_t,stTimeoutItemLink_t>( active,timeout );
lp = active->head;
while( lp )
{
PopHead<stTimeoutItem_t,stTimeoutItemLink_t>( active );
if( lp->pfnProcess )
{
lp->pfnProcess( lp );
}
lp = active->head;
}
if( pfn )
{
if( -1 == pfn( arg ) )
{
break;
}
}
}
free( result );
result = 0;
}
void OnCoroutineEvent( stTimeoutItem_t * ap )
{
stCoRoutine_t *co = (stCoRoutine_t*)ap->pArg;
co_resume( co );
}
stCoEpoll_t *AllocEpoll()
{
stCoEpoll_t *ctx = (stCoEpoll_t*)calloc( 1,sizeof(stCoEpoll_t) );
ctx->iEpollFd = epoll_create( stCoEpoll_t::_EPOLL_SIZE );
ctx->pTimeout = AllocTimeout( 60 * 1000 );
ctx->pstActiveList = (stTimeoutItemLink_t*)calloc( 1,sizeof(stTimeoutItemLink_t) );
ctx->pstTimeoutList = (stTimeoutItemLink_t*)calloc( 1,sizeof(stTimeoutItemLink_t) );
return ctx;
}
void FreeEpoll( stCoEpoll_t *ctx )
{
if( ctx )
{
free( ctx->pstActiveList );
free( ctx->pstTimeoutList );
FreeTimeout( ctx->pTimeout );
}
free( ctx );
}
stCoRoutine_t *GetCurrCo( stCoRoutineEnv_t *env )
{
return env->pCallStack[ env->iCallStackSize - 1 ];
}
stCoRoutine_t *GetCurrThreadCo( )
{
stCoRoutineEnv_t *env = co_get_curr_thread_env();
if( !env ) return 0;
return GetCurrCo(env);
}
int co_poll( stCoEpoll_t *ctx,struct pollfd fds[], nfds_t nfds, int timeout )
{
if( timeout > stTimeoutItem_t::eMaxTimeout )
{
timeout = stTimeoutItem_t::eMaxTimeout;
}
int epfd = ctx->iEpollFd;
//1.struct change
stPoll_t arg;
memset( &arg,0,sizeof(arg) );
arg.iEpollFd = epfd;
arg.fds = fds;
arg.nfds = nfds;
stPollItem_t arr[2];
if( nfds < sizeof(arr) / sizeof(arr[0]) )
{
arg.pPollItems = arr;
}
else
{
arg.pPollItems = (stPollItem_t*)malloc( nfds * sizeof( stPollItem_t ) );
}
memset( arg.pPollItems,0,nfds * sizeof(stPollItem_t) );
arg.pfnProcess = OnPollProcessEvent;
arg.pArg = GetCurrCo( co_get_curr_thread_env() );
//2.add timeout
unsigned long long now = GetTickMS();
arg.ullExpireTime = now + timeout;
int ret = AddTimeout( ctx->pTimeout,&arg,now );
if( ret != 0 )
{
co_log_err("CO_ERR: AddTimeout ret %d now %lld timeout %d arg.ullExpireTime %lld",
ret,now,timeout,arg.ullExpireTime);
errno = EINVAL;
return -__LINE__;
}
//3. add epoll
for(nfds_t i=0;i<nfds;i++)
{
arg.pPollItems[i].pSelf = fds + i;
arg.pPollItems[i].pPoll = &arg;
arg.pPollItems[i].pfnPrepare = OnPollPreparePfn;
struct epoll_event &ev = arg.pPollItems[i].stEvent;
if( fds[i].fd > -1 )
{
ev.data.ptr = arg.pPollItems + i;
ev.events = PollEvent2Epoll( fds[i].events );
epoll_ctl( epfd,EPOLL_CTL_ADD, fds[i].fd, &ev );
}
//if fail,the timeout would work
}
co_yield_env( co_get_curr_thread_env() );
RemoveFromLink<stTimeoutItem_t,stTimeoutItemLink_t>( &arg );
for(nfds_t i = 0;i < nfds;i++)
{
int fd = fds[i].fd;
if( fd > -1 )
{
epoll_ctl( epfd,EPOLL_CTL_DEL,fd,&arg.pPollItems[i].stEvent );
}
}
if( arg.pPollItems != arr )
{
free( arg.pPollItems );
arg.pPollItems = NULL;
}
return arg.iRaiseCnt;
}
void SetEpoll( stCoRoutineEnv_t *env,stCoEpoll_t *ev )
{
env->pEpoll = ev;
}
stCoEpoll_t *co_get_epoll_ct()
{
if( !co_get_curr_thread_env() )
{
co_init_curr_thread_env();
}
return co_get_curr_thread_env()->pEpoll;
}
struct stHookPThreadSpec_t
{
stCoRoutine_t *co;
void *value;
enum
{
size = 1024
};
};
void *co_getspecific(pthread_key_t key)
{
stCoRoutine_t *co = GetCurrThreadCo();
if( !co || co->cIsMain )
{
return pthread_getspecific( key );
}
return co->aSpec[ key ].value;
}
int co_setspecific(pthread_key_t key, const void *value)
{
stCoRoutine_t *co = GetCurrThreadCo();
if( !co || co->cIsMain )
{
return pthread_setspecific( key,value );
}
co->aSpec[ key ].value = (void*)value;
return 0;
}
void co_disable_hook_sys()
{
stCoRoutine_t *co = GetCurrThreadCo();
if( co )
{
co->cEnableSysHook = 0;
}
}
bool co_is_enable_sys_hook()
{
stCoRoutine_t *co = GetCurrThreadCo();
return ( co && co->cEnableSysHook );
}
stCoRoutine_t *co_self()
{
return GetCurrThreadCo();
}
| [
"1600977813@qq.com"
] | 1600977813@qq.com |
0b92a9c16288e38a5be43cdedc40bb628c1942b2 | ccd7a4f9698244f2f86bdf9c380bc9d2da59d6d7 | /apartments.cpp | d22e234e183267ebeac0d5b4f3b218f9c0e2ddd8 | [] | no_license | kamal-20/cses | ae6d6b9fe02c3ac7365e06cc82301872caa47175 | 6d2d1c8c6222cf95205381b344a6f25895c4dd9d | refs/heads/master | 2023-04-05T23:08:08.359994 | 2021-04-16T09:06:29 | 2021-04-16T09:06:29 | 330,699,801 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,172 | cpp | #pragma GCC optimize("Ofast")
#pragma GCC target("avx,avx2,fma")
#pragma GCC optimization("unroll-loops")
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<ll> vl;
typedef pair<ll,ll> pl;
typedef map<ll,ll> mll;
typedef map<ll,vector<ll>> mlvl;
typedef map<ll,string> mls;
typedef map<string,string> mss;
#define F first
#define S second
#define PB push_back
#define MP make_pair
#define mod 1000000007
#define rep(i, n) for(ll i = 0;i<n;++i)
#define repf(i,k,n) for (ll i = k; i <= n; ++i)
#define repr(i,k,n) for (ll i = k; i >= n; --i)
#define T ll cases; cin>>cases; while(cases--)
#define inar(a,n) rep(i,n) {cin>>a[i];}
#define inv(v,n) ll val; rep(i,n){cin>>val; v.PB(val);}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
{
ll n,m,k;
cin>>n>>m>>k;
ll a[n],b[m];
inar(a,n)
inar(b,m)
sort(a,a+n);
sort(b,b+m);
int i=0,j=0;
ll cnt=0;
while (i<n && j<m){
if (abs(a[i]-b[j])<=k){
++i; ++j;
++cnt;
}
else{
if (a[i]-b[j]>k){
++j;
}
else ++i;
}
}
cout << cnt << "\n";
}
}
| [
"421kamlendra@gmail.com"
] | 421kamlendra@gmail.com |
da6593035d97e0ef12ac78f386ecf2a15a07679e | 22e41aa2ddce01f0ce0cbaedbc456a4102ac475d | /MainQueryPlaner.cc | 343c1d7d3dd86e1fffab8bfb50f7633b6e39a3fc | [] | no_license | GayathriManognaIsireddy/DataBase-System-Implementation | 65a916c58d4bebc9786ed74349cacc0fe5c6b9f6 | 19e7f4c49e9cb842902babf751a08e5225661926 | refs/heads/master | 2022-12-02T19:04:39.014734 | 2020-08-02T00:55:20 | 2020-08-02T00:55:20 | 284,356,464 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 31,084 | cc | #include "MainQueryPlaner.h"
using namespace std;
QueryTreeNode :: QueryTreeNode()
{
queryNode.leftChild=NULL;
queryNode.rightChild=NULL;
queryNode.parentNode=NULL;
nodeSchema = NULL;
operatorCNF = NULL;
order = NULL;
cnf = NULL;
function = NULL;
literal = new Record();
funcOperator = NULL;
leftPipe.pipeID = 0;
leftPipe.queryPipe = NULL;
rightPipe.pipeID = 0;
rightPipe.queryPipe = NULL;
outputPipes.pipeID = 0;
outputPipes.queryPipe = NULL;
}
QueryTreeNode::QueryTreeNode(QueryTreeNode * lChild, NodeType nodetype, FuncOperator *opr, AndList *list, int opPipeID)
{
leftPipe.pipeID = 0;
leftPipe.queryPipe = NULL;
rightPipe.pipeID = 0;
rightPipe.queryPipe = NULL;
outputPipes.pipeID = 0;
outputPipes.queryPipe = NULL;
operatorCNF = NULL;
nodeSchema = lChild->nodeSchema;
literal = new Record();
cnf = list;
type = nodetype;
if(nodetype != PROJECT)
setType(nodetype);
funcOperator = opr;
queryNode.leftChild = lChild;
queryNode.rightChild = NULL;
leftPipe.pipeID = lChild->outputPipes.pipeID;
leftPipe.queryPipe = lChild->outputPipes.queryPipe;
outputPipes.pipeID = opPipeID;
queryNode.parentNode = NULL;
if(opr!=NULL){
function = new Function();
function->GrowFromParseTree(funcOperator, *nodeSchema);
}
}
QueryTreeNode :: QueryTreeNode(QueryTreeNode * lChild, QueryTreeNode * rChild, NodeType nodetype, AndList * list,int opPipeID)
{
leftPipe.pipeID = 0;
leftPipe.queryPipe = NULL;
rightPipe.pipeID = 0;
rightPipe.queryPipe = NULL;
outputPipes.pipeID = 0;
outputPipes.queryPipe = NULL;
cnf = list;
type = nodetype;
literal = new Record();
leftPipe.pipeID = lChild->outputPipes.pipeID;
rightPipe.pipeID = rChild->outputPipes.pipeID;
leftPipe.queryPipe = lChild->outputPipes.queryPipe;
rightPipe.queryPipe = rChild->outputPipes.queryPipe;
operatorCNF = NULL;
outputPipes.pipeID = opPipeID;
queryNode.leftChild = lChild;
queryNode.rightChild = rChild;
queryNode.parentNode = NULL;
if (nodetype == JOIN){
createJoinSchema();
operatorCNF = new CNF();
operatorCNF->GrowFromParseTree(cnf, queryNode.leftChild->nodeSchema, queryNode.rightChild->nodeSchema, *literal);
}
setType(nodetype);
}
void QueryTreeNode::Run(){
switch (type){
case SELECTFILE:
cout << "Running select file" << endl;
sf->Run(*dbFile, *outputPipes.queryPipe, *operatorCNF, *literal);
break;
case SELECTPIPE:
cout << "Running select pipe" << endl;
sp->Run(*leftPipe.queryPipe, *outputPipes.queryPipe, *operatorCNF, *literal);
break;
case PROJECT:
cout << "Running project" << endl;
p->Run(*leftPipe.queryPipe, *outputPipes.queryPipe, attsToKeep, numAttsIn, numAttsOut);
break;
case JOIN:
cout << "Running join" << endl;
j->Run(*leftPipe.queryPipe, *rightPipe.queryPipe, *outputPipes.queryPipe, *operatorCNF, *literal);
break;
case SUM:
cout << "Running SUM " << endl;
s->Run(*leftPipe.queryPipe, *outputPipes.queryPipe, *function);
break;
case GROUPBY:
cout << "RUnning Groupby" << endl;
gb->Run(*leftPipe.queryPipe, *outputPipes.queryPipe, *order, *function );
break;
case DIST:
cout << "Running duplicate removal " << endl;
d->Run(*leftPipe.queryPipe, *outputPipes.queryPipe, *nodeSchema);
break;
case WRITEOUT:
break;
}
}
void QueryTreeNode::WaitUntilDone(){
switch (type){
case SELECTFILE:
sf->WaitUntilDone();
break;
case SELECTPIPE:
sp->WaitUntilDone();
break;
case PROJECT:
p->WaitUntilDone();
break;
case JOIN:
j->WaitUntilDone();
break;
case SUM:
s->WaitUntilDone();
break;
case GROUPBY:
gb->WaitUntilDone();
break;
case DIST:
d->WaitUntilDone();
break;
case WRITEOUT:
break;
}
}
void QueryTreeNode::setType(NodeType setter){
outputPipes.queryPipe = new Pipe(100);
switch (type){
case SELECTFILE:
cout << "incase " << SELECTFILE << endl;
dbFile = new DBFile();
cout << "******************** Selecting the path " << path.c_str() << endl;
dbFile->Open((char*)(path.c_str()));
sf = new SelectFile();
sf->Use_n_Pages(100);
break;
case SELECTPIPE:
sp = new SelectPipe();
operatorCNF = new CNF();
operatorCNF->GrowFromParseTree(cnf, nodeSchema, *literal);
sp->Use_n_Pages(100);
break;
case PROJECT:
p = new Project();
numAttsToKeep = (int) aTK.size();
attsToKeep = new int[numAttsToKeep];
for (int i = 0; i < numAttsToKeep; i++){
attsToKeep[i] = aTK[i];
}
p->Use_n_Pages(100);
break;
case JOIN:
j = new Join();
j->Use_n_Pages(100);
break;
case SUM:
s = new Sum();
s->Use_n_Pages(100);
break;
case GROUPBY:
gb = new GroupBy();
gb->Use_n_Pages(100);
break;
case DIST:
d = new DuplicateRemoval();
d->Use_n_Pages(100);
break;
case WRITEOUT:
break;
}
}
void QueryTreeNode::createJoinSchema()
{
int leftAttCount = queryNode.leftChild->nodeSchema->GetNumAtts();
int rightAttCount = queryNode.rightChild->nodeSchema->GetNumAtts();
int numOfAttr = leftAttCount+rightAttCount;
Attribute *leftAttr = queryNode.leftChild->nodeSchema->GetAtts();
Attribute *rightAttr = queryNode.rightChild->nodeSchema->GetAtts();
Attribute mergedAtt[numOfAttr];
int mergeAttPos = 0;
for(; mergeAttPos<numOfAttr; mergeAttPos++){
if(mergeAttPos<leftAttCount){
mergedAtt[mergeAttPos] = leftAttr[mergeAttPos];
}
else{
mergedAtt[mergeAttPos] = rightAttr[mergeAttPos-leftAttCount];
}
}
nodeSchema = new Schema("Join" , numOfAttr, mergedAtt);
}
// Prints the select(File/Pipe) operation node.
void QueryTreeNode::selectPrinter(string operationType){
cout << "SELECT "<< operationType <<" OPERATION" << endl;
cout << "INPUT "<< operationType <<" " << leftPipe.pipeID << endl;
cout << "OUTPUT "<< operationType <<" " << outputPipes.pipeID << endl;
cout << "OUTPUT SCHEMA: " << endl;
schemaPrinter(nodeSchema->GetNumAtts(), nodeSchema->GetAtts());
cnfPrinter();
}
// Prints the aggrigate function node
void QueryTreeNode::aggrigatePrinter(string operationType){
cout << operationType << endl;
cout << "LEFT INPUT PIPE " << leftPipe.pipeID << endl;
cout << "OUTPUT PIPE " << outputPipes.pipeID << endl;
cout << "OUTPUT SCHEMA: " << endl;
schemaPrinter(nodeSchema->GetNumAtts(), nodeSchema->GetAtts());
cout << endl << "FUNCTION: " << endl;
function->Print();
}
// Prints the Join operation node
void QueryTreeNode::joinPrinter(){
cout << "JOIN" << endl;
cout << "LEFT INPUT PIPE " << leftPipe.pipeID << endl;
cout << "RIGHT INPUT PIPE " << rightPipe.pipeID << endl;
cout << "OUTPUT PIPE " << outputPipes.pipeID << endl;
cout << "OUTPUT SCHEMA: " << endl;
schemaPrinter(nodeSchema->GetNumAtts(), nodeSchema->GetAtts());
cnfPrinter();
cout << endl;
}
// Prints the groupBy operation node
void QueryTreeNode::groupByPrinter(){
cout << "GROUPBY" << endl;
cout << "LEFT INPUT PIPE " << leftPipe.pipeID << endl;
cout << "OUTPUT PIPE " << outputPipes.pipeID << endl;
cout << "OUTPUT SCHEMA: " << endl;
schemaPrinter(nodeSchema->GetNumAtts(), nodeSchema->GetAtts());
cout << endl << "GROUPING ON " << endl;
order->Print();
cout << endl << "FUNCTION " << endl;
function->Print();
}
// Prints the final projection
void QueryTreeNode::projectPrinter(){
cout << "PROJECT" << endl;
cout << "INPUT PIPE " << leftPipe.pipeID << endl;
cout << "OUTPUT PIPE "<< outputPipes.pipeID << endl;
cout << "OUTPUT SCHEMA: " << endl;
//order->Print();
schemaPrinter(nodeSchema->GetNumAtts(), nodeSchema->GetAtts());
}
// Print writeout
void QueryTreeNode::writeOuttePrinter(){
cout << "WRITE" << endl;
cout << "LEFT INPUT PIPE " << leftPipe.pipeID << endl;
cout << "OUTPUT FILE " << path << endl;
}
void QueryTreeNode::schemaPrinter(int numAtts, Attribute *schemaAttributes){
for(int i=0; i < numAtts; i++)
{
cout << "\t" << "Att " << schemaAttributes[i].name<<": ";
if(schemaAttributes[i].myType == 0)
cout << "INT" << endl;
else if(schemaAttributes[i].myType == 1)
cout << "DOUBLE" << endl;
else
cout << "STRING" << endl;
}
}
// Prints the current node basing on its nodeType
void QueryTreeNode::nodePrinter(){
cout << " ****************** " << endl;
switch (type){
case SELECTFILE:
selectPrinter("FILE");
break;
case SELECTPIPE:
selectPrinter("PIPE");
break;
case SUM:
aggrigatePrinter("SUM");
break;
case DIST:
aggrigatePrinter("DISTINCT");
break;
case JOIN:
joinPrinter();
break;
case GROUPBY:
groupByPrinter();
break;
case PROJECT:
projectPrinter();
break;
case WRITEOUT:
writeOuttePrinter();
break;
}
cout << " ****************** " << endl;
}
// To print the CNF of a Node operation if present
void QueryTreeNode::cnfPrinter()
{
string str;
if(cnf)
{
struct AndList *andList = cnf;
while(andList!=NULL)
{
struct OrList *orList = andList->left;
if(andList->left)
{
str.append("(");
}
while(orList)
{
struct ComparisonOp *comparisonOp = orList->left;
if(comparisonOp)
{
if(comparisonOp->left)
{
str.append(comparisonOp->left->value);
}
str.append(comparisonOp->code == LESS_THAN ? "<" : comparisonOp->code == GREATER_THAN ? ">":"=");
if(comparisonOp->right)
{
str.append(comparisonOp->right->value);
}
}
if(orList->rightOr)
{
str.append("OR");
}
orList = orList->rightOr;
}
if(andList->left)
{
str.append(")");
}
if(andList->rightAnd)
{
str.append("AND");
}
andList = andList->rightAnd;
}
cout << endl << "CNF: " << endl;
cout<< str << endl;
}
}
void QueryTreeNode::GenerateSchema(NameList * selectAttr)
{
vector<int> indexOfAttsToKeep;
string attribute;
while (selectAttr != 0) {
attribute = selectAttr->name;
//nodeSchema->Print();
indexOfAttsToKeep.push_back(nodeSchema->Find(const_cast<char*>(attribute.c_str())));
selectAttr = selectAttr->next;
}
Attribute *attr = nodeSchema->GetAtts();
Attribute *newAttr = new Attribute[indexOfAttsToKeep.size()];
for (int i = 0; i < indexOfAttsToKeep.size(); i++)
{
cout << i << endl;
newAttr[i] = attr[indexOfAttsToKeep[i]];
}
nodeSchema = new Schema("Distinct", indexOfAttsToKeep.size(), newAttr);
}
void QueryTreeNode::setOrderMaker(int numAtts, int *groupAtt, Type *attType){
order = new OrderMaker();
order->SetAttributes(numAtts, groupAtt, attType);
}
MainQueryPlaner::MainQueryPlaner(FuncOperator *finalFunction, TableList *tables, AndList *boolean, NameList *groupingAtts, NameList *attsToSelect, int distinctAtts, int distinctFunc){
this->finalFunction=finalFunction;
this->tables=tables;
this->boolean=boolean;
this->groupingAtts=groupingAtts;
this->attsToSelect=attsToSelect;
this->distinctAtts=distinctAtts;
this->distinctFunc=distinctFunc;
lastInserted=NULL;
statistics = new Statistics();
statistics->Read("Statistics.txt");
}
int MainQueryPlaner::emptyPipe (Pipe &in_pipe, Schema *schema) {
Record rec;
int cnt = 0;
while (in_pipe.Remove (&rec)) {
rec.Print (schema);
cnt++;
}
return cnt;
}
int MainQueryPlaner::emptyPipeWithFunction (Pipe &in_pipe, Schema *schema, Function &function) {
Record rec;
int cnt = 0;
double sum = 0;
cout<< "In sume clear pipe "<<endl;
while (in_pipe.Remove (&rec)) {
cout<< "In while clear pipe "<<endl;
int ival = 0; double dval = 0;
function.Apply (rec, ival, dval);
sum += (ival + dval);
cnt++;
cout << " Sum: " << sum << endl;
cout<< "In while clear pipe end "<<endl;
}
return cnt;
}
// Return the join operations list by iterating trough the boolean
vector<AndList> MainQueryPlaner::getJoinList(){
AndList *currAndList= boolean;
vector<AndList> joinList;
while(currAndList!=0){
OrList *curOrList=currAndList->left;
AndList tmpAndList = *currAndList;
if (curOrList && curOrList->left->code == EQUALS && curOrList->left->left->code == NAME
&& curOrList->left->right->code == NAME)
{
tmpAndList.rightAnd = 0;
joinList.push_back(tmpAndList);
//break;
}
currAndList=currAndList->rightAnd;
}
return joinList;
}
// Constructos the where and having list by iterating trough the boolean
void MainQueryPlaner::getWhereHavingList(vector<AndList> &havingList, vector<AndList> &whereList){
AndList *currAndList= boolean;
while(currAndList!=0){
OrList *curOrList=currAndList->left;
AndList tmpAndList = *currAndList;
if(curOrList&&curOrList->left==0){
tmpAndList.rightAnd = 0;
whereList.push_back(tmpAndList);
//break;
}
else if(curOrList==0 || curOrList->left->code != EQUALS || curOrList->left->left->code != NAME
|| curOrList->left->right->code != NAME){
vector<string> orTables;
while (curOrList != 0)
{
Operand *operand = curOrList->left->left;
if (operand->code != NAME)
operand = curOrList->left->right;
string str= operand->value;
string tableName = str.substr(0, str.find("."));
if (find(orTables.begin(), orTables.end(), tableName) == orTables.end())
orTables.push_back(tableName);
curOrList = curOrList->rightOr;
}
AndList newAnd = *currAndList;
newAnd.rightAnd = 0;
if (orTables.size() <= 1) {
whereList.push_back(newAnd);
}
else {
havingList.push_back(newAnd);
//break;
}
}
currAndList=currAndList->rightAnd;
}
}
// Optimizes the join operations vector
vector<AndList> MainQueryPlaner::optmizeJoins(Statistics *statistics, vector<AndList> joinsVector)
{
if(joinsVector.size()==0) return joinsVector;
vector<AndList> optimizedList;
while (joinsVector.size() > 0)
{
int maxEstimateIndex = 0;
double maxCost = -1;
for (int i = 0; i < joinsVector.size(); i++)
{
double curCost = 0.0;
string leftValue = joinsVector[i].left->left->left->value;
string leftTable = leftValue.substr(0, leftValue.find("."));
string rightValue = joinsVector[i].left->left->right->value;
string rightTable = rightValue.substr(0, rightValue.find("."));
char* tableList[] = { (char*)leftTable.c_str(), (char*)rightTable.c_str() };
curCost = statistics->Estimate(&joinsVector[i], tableList, 2);
if (i == 0 || maxCost > curCost)
{
maxCost = curCost;
maxEstimateIndex = i;
}
}
optimizedList.push_back(joinsVector[maxEstimateIndex]);
joinsVector.erase(joinsVector.begin() + maxEstimateIndex);
}
return optimizedList;
}
void MainQueryPlaner::nodeOrderPrinter(QueryTreeNode *lastInserted){
stack<QueryTreeNode*> st;
stack<QueryTreeNode*> postOrderSt;
st.push(lastInserted);
while(!st.empty()){
QueryTreeNode *current = st.top();
st.pop();
postOrderSt.push(current);
if(current->queryNode.leftChild) st.push(current->queryNode.leftChild);
if(current->queryNode.rightChild) st.push(current->queryNode.rightChild);
}
while(!postOrderSt.empty()){
QueryTreeNode *current = postOrderSt.top();
postOrderSt.pop();
current->nodePrinter();
}
}
void MainQueryPlaner::nodeOrderExecution(QueryTreeNode *lastInserted){
stack<QueryTreeNode*> st;
stack<QueryTreeNode*> postOrderSt;
st.push(lastInserted);
while(!st.empty()){
QueryTreeNode *current = st.top();
st.pop();
postOrderSt.push(current);
if(current->queryNode.leftChild) st.push(current->queryNode.leftChild);
if(current->queryNode.rightChild) st.push(current->queryNode.rightChild);
}
while(!postOrderSt.empty()){
QueryTreeNode *current = postOrderSt.top();
postOrderSt.pop();
current->Run();
}
}
// Return the parent node of where list node
QueryTreeNode *MainQueryPlaner::currentParent(AndList tempWhere, map<string, QueryTreeNode*> leafNodes, Statistics *statistics){
string tablename = tempWhere.left->left->left->code == NAME? tempWhere.left->left->left->value:
tempWhere.left->left->right->value;
tablename = tablename.substr(0, tablename.find("."));
QueryTreeNode *tmpNode;
tmpNode = leafNodes[tablename];
while (tmpNode->queryNode.parentNode != NULL)
{
tmpNode = tmpNode->queryNode.parentNode;
}
char *tempTableName = strdup(tablename.c_str());
statistics->Apply(&tempWhere, &tempTableName, 1);
return tmpNode;
}
// Returns the parent node of join node corresponding to the table node in leafNodes map
QueryTreeNode *MainQueryPlaner::joinParentNode(string tableName, map<string, QueryTreeNode*> leafNodes){
QueryTreeNode *curPlanNode;
string curTable = tableName.substr(0, tableName.find("."));
curPlanNode = leafNodes[curTable];
while (curPlanNode->queryNode.parentNode != NULL)
curPlanNode = curPlanNode->queryNode.parentNode;
return curPlanNode;
}
void MainQueryPlaner::planGenerator(int output, string outputFile)
{
int pipeID = 1;
//cout << "Enter the Query followed by Ctrl + D:" << endl;
Statistics *stats = new Statistics();
stats->Read("Statistics.txt");
TableList *tempTblList = tables;
map<string, QueryTreeNode*> leafNodes;
QueryTreeNode *lastInserted = NULL;
while (tempTblList)
{
string curTableName = tempTblList->aliasAs!=0?tempTblList->aliasAs:tempTblList->tableName;
char * tableName = tempTblList->tableName;
string tablePath = string(tableName).append(".bin");
cout<< "table name -- :"<< tablePath << endl;
leafNodes.insert(std::pair<string, QueryTreeNode*>(curTableName, new QueryTreeNode()));
QueryTreeNode *curNode = leafNodes[tempTblList->aliasAs];
curNode->nodeSchema = new Schema("catalog", tempTblList->tableName);
if(tempTblList->aliasAs!=0){
stats->CopyRel(tempTblList->tableName, tempTblList->aliasAs);
curNode->nodeSchema->updateName(curTableName);
}
curNode->path = tablePath;
cout << "Settign the path " << curNode->path << endl;
curNode->outputPipes.pipeID = pipeID++;
curNode->type = SELECTFILE;
curNode->setType(SELECTFILE);
tempTblList = tempTblList->next;
lastInserted = curNode;
}
vector<AndList> joinlist = getJoinList();
vector<AndList> havingList;
vector<AndList> whereList;
getWhereHavingList(havingList, whereList);
for (unsigned i = 0; i < whereList.size(); i++)
{
QueryTreeNode *tmpNode = currentParent(whereList[i], leafNodes, stats);
//topnode
QueryTreeNode *newNode = new QueryTreeNode(tmpNode, SELECTPIPE, NULL, &whereList[i], pipeID++);
tmpNode->queryNode.parentNode = newNode;
lastInserted = newNode;
}
if (joinlist.size() > 1) {
joinlist = optmizeJoins(stats, joinlist);
}
for (int i = 0; i < joinlist.size(); i++)
{
QueryTreeNode *curLeftParent = joinParentNode(joinlist[i].left->left->left->value, leafNodes);
QueryTreeNode *curRightParent = joinParentNode(joinlist[i].left->left->right->value, leafNodes);
QueryTreeNode *newNode = new QueryTreeNode(curLeftParent, curRightParent, JOIN, &joinlist[i], pipeID++);
curLeftParent->queryNode.parentNode = newNode;
curRightParent->queryNode.parentNode = newNode;
lastInserted = newNode;
}
// Tree nodes for having
for (int i = 0; i < havingList.size(); i++)
{
cout<< "Inside having one" << endl;
QueryTreeNode *tmpNode = lastInserted;
QueryTreeNode *curNode = new QueryTreeNode(tmpNode, SELECTPIPE, NULL, &havingList[i], pipeID++);
tmpNode->queryNode.parentNode = curNode;
lastInserted = curNode;
}
// Distinct(Duplicate) nodes
bool distFlag = false;
if (finalFunction != NULL&&distinctFunc == 1)
{
cout<< "Inside Dist one" << endl;
QueryTreeNode *tmpNode = lastInserted;
QueryTreeNode *curNode = new QueryTreeNode(tmpNode, DIST, NULL, NULL, pipeID++);
tmpNode->queryNode.parentNode = curNode;
lastInserted = curNode;
}
// Tree node for aggrigate functions
bool groupingFlag = groupingAtts!=NULL;
if (finalFunction != NULL)
{
cout<< "Inside Aggrigate one" << endl;
NodeType curType = groupingAtts == NULL ? SUM: GROUPBY;
QueryTreeNode *curparent = lastInserted;
QueryTreeNode *curNode = new QueryTreeNode(curparent, curType, finalFunction, NULL, pipeID++);
curparent->queryNode.parentNode = curNode;
lastInserted = curNode;
curparent = lastInserted;
if(groupingAtts != NULL){
Schema *nodeSchema = curparent->nodeSchema;
int groupAttCount = 0;
vector<int> attsToGroup;
vector<Type> whichType;
while (groupingAtts) {
groupAttCount++;
cout<<" group attribute: " << groupingAtts->name<< endl;
attsToGroup.push_back(nodeSchema->Find(groupingAtts->name));
whichType.push_back(nodeSchema->FindType(groupingAtts->name));
groupingAtts = groupingAtts->next;
}
curNode->setOrderMaker(groupAttCount, &attsToGroup[0], &whichType[0]);
}
}
//Creating distinct nodes
if (distinctAtts != 0)
{
distFlag = true;
QueryTreeNode *tmpNode = lastInserted;
QueryTreeNode *newNode = new QueryTreeNode(tmpNode, DIST, NULL, NULL, pipeID++);
tmpNode->queryNode.parentNode = newNode;
lastInserted = newNode;
}
//Creating Project nodes
if (attsToSelect != NULL) {
QueryTreeNode *tmpNode = lastInserted;
cout << " Creating the PROJECT NOde " << endl;
QueryTreeNode *newNode = new QueryTreeNode(tmpNode, PROJECT, NULL, NULL, pipeID++);
tmpNode->queryNode.parentNode = newNode;
//newNode->GenerateSchema(attsToSelect);
int counter=0;
Attribute *newAttr = new Attribute[counter];
vector<int> attIndexes;
NameList *tempAttsToSelect = attsToSelect;
while (tempAttsToSelect != 0) {
string attribute = tempAttsToSelect->name;
attIndexes.push_back(newNode->nodeSchema->Find(const_cast<char*>(attribute.c_str())));
counter++;
tempAttsToSelect = tempAttsToSelect->next;
}
Attribute *attr = newNode->nodeSchema->GetAtts();
for (int i = 0; i < counter; i++)
{
newAttr[i] = attr[attIndexes[i]];
}
newNode->nodeSchema = new Schema("ProjectSchems", counter, newAttr);
cout<< "Number of selects: "<< counter<< endl;
cout<< "Number of joins: "<<joinlist.size()<< endl;
if(groupingFlag) cout<< "GROUPING ON ";
Schema *nodeSchema = tmpNode->nodeSchema;
NameList *attsTraverse = attsToSelect;
string attribute;
vector<int> indexOfAttsToKeep;
Schema *oldSchema = tmpNode->nodeSchema;
while(attsTraverse != 0)
{
attribute = attsTraverse->name;
indexOfAttsToKeep.push_back(oldSchema->Find(const_cast<char*>(attribute.c_str())));
attsTraverse = attsTraverse->next;
}
Schema *newSchema = new Schema(oldSchema, indexOfAttsToKeep);
newNode->nodeSchema = newSchema;
newNode->numAttsIn = tmpNode->nodeSchema->GetNumAtts();
newNode->numAttsOut = newNode->nodeSchema->GetNumAtts();
newNode->aTK = indexOfAttsToKeep;
newNode->setType(PROJECT);
lastInserted = newNode;
}
if(output == PIPE_NONE)
{
if(lastInserted != NULL)
{
nodeOrderPrinter(lastInserted);
}
}
else if(output == PIPE_STDOUT)
{
nodeOrderPrinter(lastInserted);
cout << "*************************************************" << endl;
cout << "Running the Tree" << endl;
//lastInserted->RunInOrder();
nodeOrderExecution(lastInserted);
int count = 0;
lastInserted->nodeSchema->Print();
cout << "Schema type " << lastInserted->type<<endl;
if(lastInserted->type == SUM)
count = emptyPipeWithFunction(*(lastInserted->outputPipes.queryPipe), lastInserted->nodeSchema, *lastInserted->function);
else
count = emptyPipe(*(lastInserted->outputPipes.queryPipe), lastInserted->nodeSchema);
lastInserted->WaitUntilDone();
clog << "Result records: " << count << endl;
}
}
QueryHandler::QueryHandler(){
}
QueryHandler::QueryHandler(FuncOperator *finalFunction, TableList *tables, AndList *boolean, NameList *groupingAtts, NameList *attsToSelect,
NameList *sortAtts, int distinctAtts, int distinctFunc, InOutPipe *io, string createTableName, string createTableType,
vector<string> atts, vector<string> attTypes, int queryType){
this->finalFunction = finalFunction;
this->tables = tables;
this->boolean = boolean;
this->groupingAtts = groupingAtts;
this->attsToSelect = attsToSelect;
this->sortAtts = sortAtts;
this->distinctAtts = distinctAtts;
this->distinctFunc = distinctFunc;
this->io = io;
this->createTableName = createTableName;
this->createTableType = createTableType;
this->atts = atts;
this->attTypes = attTypes;
this->queryType = queryType;
}
int QueryHandler::StartQuery(){
int output = PIPE_STDOUT;
string outputFile = "";
GetLocations();
//cout<< "IN start Query"<< endl;
cout << "Done reading the catalog, bin and tpch file locations" << endl;
int option;
bool started=false;
cout<<"jkbejhfhkuhskuf================== "<< queryType<< endl;
switch (queryType){
case QUERY_CREATE:
{
CreateTable();
cout << "Table " << createTableName.c_str() << " created " << endl;
atts.clear();
attTypes.clear();
}
break;
case QUERY_SELECT:
{
MainQueryPlaner *mainQPObject= new MainQueryPlaner(finalFunction, tables, boolean, groupingAtts, attsToSelect, distinctAtts, distinctFunc);
mainQPObject->planGenerator(output, outputFile);
}
break;
case QUERY_DROP:
{
DropTable(tables->tableName);
cout << "Table " << tables->tableName << " is dropped " << endl;
free(tables);
}
break;
case QUERY_SET:
{
output = io->type;
if(output == PIPE_FILE)
{
outputFile = io->file;
}
free(io);
}
break;
case QUERY_INSERT:
{
InsertToTable();
}
break;
case QUERY_QUIT:
{
cout << "Shutting down the database" << endl;
}
break;
}
clear();
}
int QueryHandler::InsertToTable(){
bool statusFlag=true;
DBFile table;
char *tableBinPath = new char[100];
sprintf(tableBinPath, "%s%s.%s", dbfile_dir, io->src, "bin");
Schema schema("catalog", io->src);
ifstream curFile(io->file);
cout << "Data file: " << io->file << endl;
cout << "Table bin path: " << tableBinPath << endl;
if (curFile.is_open())
{
table.Open(tableBinPath);
table.Load(schema, io->file);
table.Close();
cout << "Data loaded: " << io->src << " From: " << io->file << "." << endl;
}
else
{
statusFlag = false;
cout << "File is missing" << endl;
}
curFile.close();
free(io);
delete[] tableBinPath;
return statusFlag==true;
}
void QueryHandler::GetLocations()
{
const char *locations = "test.cat";
FILE *filePaths = fopen(locations, "r");
if(!filePaths)
{
cerr << " Test settings files 'test.cat' missing \n";
exit (1);
}
else
{
char *mem = (char *) malloc(80 * 3);
catalog_path = &mem[0];
dbfile_dir = &mem[80];
tpch_dir = &mem[160];
char line[80];
fgets (line, 80, filePaths);
sscanf (line, "%s\n", catalog_path);
fgets (line, 80, filePaths);
sscanf (line, "%s\n", dbfile_dir);
fgets (line, 80, filePaths);
sscanf (line, "%s\n", tpch_dir);
fclose (filePaths);
if (! (catalog_path && dbfile_dir && tpch_dir)) {
cerr << " Test settings file 'test.cat' not in correct format.\n";
free (mem);
exit (1);
}
}
}
void QueryHandler::DropTable(string table)
{
bool copyData = true;
string readLine;
string hold = "";
ifstream catalog("catalog");
ofstream tempCatalog("tempCatalog");
if(catalog.is_open())
{
while(catalog.good())
{
getline(catalog, readLine);
if (readLine.compare("BEGIN") == 0 && hold.compare("") != 0)
{
if(tempCatalog.good() && copyData)
{
tempCatalog << hold;
}
hold = "";
hold.append(readLine);
hold.append("\n");
}
else if(copyData == false && readLine.compare("END") == 0)
{
copyData = true;
continue;
}
else if(readLine.compare(table) == 0)
{
hold = "";
copyData = false;
}
else if(copyData)
{
hold.append(readLine);
hold.append("\n");
}
}
if(tempCatalog.good() && copyData)
{
tempCatalog << hold;
}
rename("tempCatalog", "catalog");
catalog.close();
char *file = new char[100];
sprintf(file, "%s%s.%s", dbfile_dir, (char*)table.c_str(), "bin");
remove(file);
delete[] file;
}
}
int QueryHandler::CreateTable()
{
int createStatus=0;
string curSchema;
string type;
int size = (int) atts.size();
ofstream create("catalog", ios::out | ios::app);
curSchema = "BEGIN\n";
curSchema.append(createTableName.c_str());
curSchema.append("\n");
curSchema.append(createTableName.c_str());
curSchema.append(".tbl\n");
for (int i = 0; i < size; i++)
{
curSchema.append(atts[i]);
if (attTypes[i].compare("INTEGER") == 0){
type = " Int";
}
else if (attTypes[i].compare("DOUBLE") == 0){
type = " Double";
}
else {
type = " String";
}
curSchema.append(type);
curSchema.append("\n");
}
curSchema.append("END\n\n");
if(create.is_open() && create.good())
{
create << curSchema;
}
create.close();
char *binary = new char[100];
cout << "table Type:" << (char*)createTableType.c_str() << endl;
DBFile dbFile;
sprintf(binary, "%s%s.%s", dbfile_dir, (char*) createTableName.c_str(), "bin");
cout << "The path to the binary files is " << binary << endl;
struct NameList *sortkeys = sortAtts;
fType ftype = heap;
if(sortAtts != NULL && sortAtts != 0)
{
int i = 0;
OrderMaker om = OrderMaker();
int attList[MAX_ANDS];
Type attType[MAX_ANDS];
Schema *s = new Schema("catalog", (char*)createTableName.c_str());
while (sortkeys != NULL)
{
int res = s->Find(sortkeys->name);
int restype = s->FindType(sortkeys->name);
if (res != -1)
{
attList[i] = res;
attTypes[i] = restype;
i++;
}
sortkeys = sortkeys->next;
}
om.SetAttributes(i, attList, attType);
struct { OrderMaker *o; int l; } startup = { &om, 5 };
ftype = sorted;
createStatus = dbFile.Create(binary, ftype, &startup);
}
else
createStatus = dbFile.Create(binary, ftype, NULL);
dbFile.Close();
delete[] binary;
return createStatus;
}
void QueryHandler::clear() {
tables = NULL;
boolean = NULL;
groupingAtts = NULL;
attsToSelect = NULL;
sortAtts = NULL;
io = NULL;
queryType = -1;
distinctAtts = distinctFunc = 0;
} | [
"manogna.isireddy01@gmail.com"
] | manogna.isireddy01@gmail.com |
d2d4adc3d1bc956bc5925ce2e4cb32c51b320aba | e25c215dc77270db7f0b0facef9f1f782b19b58b | /src/carchitect.h | e5bffa513f77a4d1f5bf653c98f5b968c574d820 | [
"MIT"
] | permissive | RodrigoGM/CNT-MD | d534594cd4ab2b6cb092f5b31eb0ad352c206ca8 | a23b0c4dcafad4453ef5f215e0df1b40827022d3 | refs/heads/master | 2023-06-01T14:59:24.190519 | 2018-12-03T15:38:22 | 2018-12-03T15:38:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,267 | h | #ifndef _CARCHITECT_H_
#define _CARCHITECT_H_
#include "basecarchitect.h"
ILOSTLBEGIN
/// This class represent the architect that builds the ILP model for solving the
/// problem when the given input is composed of a collection of leaves and an
/// integer e representing the maximum copy-number.
class CArchitect : public BaseCArchitect
{
public:
CArchitect(const InputInstance& inputInstance,
const DoubleMatrix& M,
const IntMatrix &e,
const int Z,
const unsigned int k,
const bool rootNotFixed,
const bool forceDiploid);
/// Get solution cost
int getDelta();
static HotStart firstCompleteHotStart(const InputInstance& inputInstance, const IntMatrix& e, const unsigned int k);
protected:
/// TODO
IloBoolVar3Array _bar_y;
/// TODO
IntMatrix _num_z;
/// TODO
IloBoolVar4Array _z;
/// TODO
IloIntVar4Array _a;
/// TODO
IloIntVar4Array _d;
/// TODO
IloIntVar4Array _bar_a;
/// TODO
IloIntVar4Array _bar_d;
/// Build variables
void buildVariables();
/// Build constraints
virtual void buildConstraints();
/// Construct tree
void constructTree();
};
#endif // _CARCHITECT_H_
| [
"simozacca@gmail.com"
] | simozacca@gmail.com |
b020e7426251a5f33d5643c9514c88deaa4487d0 | 8d1345522a63c184604f116b9874f82040b9529e | /DFS/922.按奇偶排序数组-ii.cpp | f23eedb3c6e226759e03791bc2bffbd075be33eb | [] | no_license | SherlockUnknowEn/leetcode | cf283431a9e683b6c2623eb207b5bfad506f8257 | 4ca9df3b5d093a467963640e2d2eb17fc640d4bd | refs/heads/master | 2023-01-22T14:24:30.938355 | 2023-01-18T14:37:36 | 2023-01-18T14:37:36 | 93,287,101 | 36 | 11 | null | null | null | null | UTF-8 | C++ | false | false | 907 | cpp | /*
* @lc app=leetcode.cn id=922 lang=cpp
*
* [922] 按奇偶排序数组 II
*/
// @lc code=start
class Solution {
public:
vector<int> sortArrayByParityII(vector<int>& nums) {
int i = 0;
int j = 1;
for (int n : nums) {
int o = n & 0xFFFF;
// cout << n << " " << o << " " << i << " " << j << " ";
if (o % 2 == 0) {
o = o << 16;
// cout << o << endl;
nums[i] = nums[i] | o;
i += 2;
} else {
o = o << 16;
// cout << o << endl;
nums[j] = nums[j] | o;
j += 2;
}
}
for (int i = 0; i < nums.size(); i++) {
// cout << i << "." << nums[i] << " " << (nums[i] >> 16) << endl;
nums[i] = nums[i] >> 16;
}
return nums;
}
};
// @lc code=end
| [
"fjie666@outlook.com"
] | fjie666@outlook.com |
b0bbb573d412b5349d886e6ce19f985b3577292a | 7d15668ec8107eabc3cf18ae5a4c90df6ac51fbe | /24. linked list/5. taking input.cpp | c2776c201d5c8512573c9863ae008217078d5045 | [] | no_license | gittysachin/Interview-Prep-CPP | 5826f274d48a9cbbb020dc298929c30ded9a7279 | a9f13fe80131832f6387a67affad9bbe2c650f3f | refs/heads/master | 2023-01-01T21:20:00.843418 | 2020-09-30T08:43:07 | 2020-09-30T08:43:07 | 260,518,840 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 847 | cpp | #include<iostream>
using namespace std;
class node {
public:
int data;
node *next;
// constructor
node(int d){
data = d;
next = NULL;
}
};
void print(node *head){
node *temp = head;
while(temp != NULL){
cout << temp->data << " ";
temp = temp->next;
}
}
void insertAtTail(node *&head, int data){
if(head == NULL){
head = new node(data);
return;
}
node *tail = head;
while(tail->next != NULL){
tail = tail->next;
}
tail -> next = new node(data);
return;
}
void buildList(node *&head){
int data;
cin >> data;
while(data != -1){
insertAtTail(head, data);
cin >> data;
}
}
int main(){
node *head = NULL;
buildList(head);
print(head);
return 0;
} | [
"34537025+gittysachin@users.noreply.github.com"
] | 34537025+gittysachin@users.noreply.github.com |
8ec5b91182d24ccbe6c59023d3782afb55ea0e07 | b89e63338c0cf78412f405ac270d2b3f26f7d3de | /Hashing/Easy_problems/Number of subarrays having sum exactly equal to k.cpp | 6c3abdb39c4044c874b7e2337b3b592aad940f2f | [] | no_license | abaran803/Data-Structures | b79c41dca1470a8c402dc268e1997188ae9da51d | cfebc843ec7dc82270cc48f905db4291b183d2c7 | refs/heads/master | 2023-01-07T11:41:00.068782 | 2020-11-04T04:30:10 | 2020-11-04T04:30:10 | 296,395,317 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,578 | cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<ll> vi;
typedef pair<ll,ll> pi;
#define F first
#define S second
#define PB push_back
#define MP make_pair
int findSubarraySum(int arr[], int n, int sum)
{
// STL map to store number of subarrays
// starting from index zero having
// particular value of sum.
unordered_map<int, int> prevSum;
int res = 0;
// Sum of elements so far.
int currsum = 0;
for (int i = 0; i < n; i++) {
// Add current element to sum so far.
currsum += arr[i];
// If currsum is equal to desired sum,
// then a new subarray is found. So
// increase count of subarrays.
if (currsum == sum)
res++;
// currsum exceeds given sum by currsum
// - sum. Find number of subarrays having
// this sum and exclude those subarrays
// from currsum by increasing count by
// same amount.
if (prevSum.find(currsum - sum) !=
prevSum.end())
{
res += (prevSum[currsum - sum]);
}
// Add currsum value to count of
// different values of sum.
prevSum[currsum]++;
}
return res;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("inp.txt","r",stdin);
freopen("out.txt","w",stdout);
#endif
int n;
cin >> n;
int arr[n];
for(int i=0;i<n;i++)
cin >> arr[i];
int k;
cin >> k;
cout << findSubarraySum(arr,n,k);
return 0;
} | [
"abaran803@gmail.com"
] | abaran803@gmail.com |
24baa89264a6645a949a994a034ac96f1d7f56e3 | 03913ec23aaced99ecf4ba60abab2d1fd61a100b | /heap/ideone_JVzzO9.cpp | c48fef1033284f13daf89ce3a73a0fe0134f45f5 | [] | no_license | QLingx/TechieDelight | 049c53ff1bd28862e893f13a4dbf5ec8a4237957 | c7270782a1765819bb30861edeeb392ed671f6d7 | refs/heads/master | 2021-01-19T17:07:08.237825 | 2017-10-13T02:28:35 | 2017-10-13T02:28:35 | 101,050,784 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,468 | cpp | #include <bits/stdc++.h>
using namespace std;
// M arrays of size N each
#define N 4
#define M 5
// A min-heap node
struct Node
{
// val stores the element,
// i stores list number of the element,
// index stores column number of ith list from which element was taken
int val, i, index;
};
// Comparison object to be used to order the min-heap
struct comp
{
bool operator()(const Node lhs, const Node rhs) const
{
return lhs.val > rhs.val;
}
};
// Function to merge M sorted lists each of size N and
// print them in ascending order
void printSorted(int list[][N])
{
// create an empty min-heap
priority_queue<Node, std::vector<Node>, comp> pq;
// push first element of each list into the min-heap
// along with list number and their index in the list
for (int i = 0; i < M; i++)
pq.push({list[i][0], i, 0});
// run till min-heap is not empty
while (!pq.empty())
{
// extract minimum node from the min-heap
Node min = pq.top();
pq.pop();
// print the minimum element
cout << min.val << " ";
// take next element from "same" list and
// insert it into the min-heap
if (min.index + 1 < N)
{
min.index += 1;
min.val = list[min.i][min.index];
pq.push(min);
}
}
}
int main()
{
// M lists of size N each in the form of 2D-matrix
int list[M][N] =
{
{ 10, 20, 30, 40 },
{ 15, 25, 35, 45 },
{ 27, 29, 37, 48 },
{ 32, 33, 39, 50 },
{ 16, 18, 22, 28 }
};
printSorted(list);
return 0;
}
| [
"270547728@qq.com"
] | 270547728@qq.com |
0f565e6e9dbe8664ff8829147e084a173850409c | 94d64a460c83268a8c19d1bd41a3b332108e9849 | /ProjectEndGame/Flee.cpp | e556a8ea686db7600b47f3dec0ae571c86766d7e | [
"MIT"
] | permissive | BobEh/Game-Engine | cbf5f2e1d95f3dfdbc4f822b211d602b4962e2ae | 2086336c8e0d4b49166b8f9c8b8c1db99728e206 | refs/heads/master | 2021-03-05T02:21:31.121858 | 2020-04-26T04:31:57 | 2020-04-26T04:31:57 | 246,948,323 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,291 | cpp | #include "Flee.h"
Flee::Flee(iObject* agent, iObject* target) : mAgent(agent), mTarget(target)
{
}
Flee::~Flee(void)
{
}
void Flee::update(float dt)
{
if (mAgent == 0 || mTarget == 0) return;
/*calculates the desired velocity */
/*Seek uses target position - current position*/
/*Flee uses current position - target position*/
glm::vec3 desiredVelocity = (mTarget->getPositionXYZ() - mAgent->getPositionXYZ()) * glm::vec3(-1.0f);
/* get the distance from target */
float dist = glm::distance(mAgent->getPositionXYZ(), mTarget->getPositionXYZ());
glm::normalize(desiredVelocity);
float maxVelocity = 3.0f;
float slowingRadius = 5.0f;
/*is the game object within the radius around the target */
if (dist > slowingRadius)
{
/* game object is approaching the target and slows down*/
desiredVelocity = desiredVelocity * maxVelocity * (dist / slowingRadius);
}
else
{
/* target is far away from game object*/
desiredVelocity *= maxVelocity;
}
/*calculate the steering force */
glm::vec3 steer = desiredVelocity - mAgent->getVelocity();
/* add steering force to current velocity*/
mAgent->setVelocity(steer * 0.03f);
if (glm::length(mAgent->getVelocity()) > maxVelocity)
{
mAgent->setVelocity(glm::normalize(mAgent->getVelocity()) * maxVelocity);
}
} | [
"Bobby@DESKTOP-L8U4I2V"
] | Bobby@DESKTOP-L8U4I2V |
2e8cff6e0e7893314de177f7518461698460a9d6 | d26dec917ab9b5faf895ac44377146d9c479fdfe | /GeeksForGeeks_Problems/Amazon_Prep/possible_group_size_2_3_of_3_multiple.cpp | 330aeb4539ae33f055cf310f8de230fd5d74b42a | [] | no_license | cpuggal/Data-Structures | ce46567bea72f91a7c08abea5ef6f2a57bead871 | 146840f6305424ab1140402c469faf854e526d71 | refs/heads/master | 2022-01-09T15:25:21.830677 | 2022-01-02T14:52:04 | 2022-01-02T14:52:04 | 97,984,024 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 996 | cpp | // https://www.geeksforgeeks.org/count-possible-groups-size-2-3-sum-multiple-3/
//
// Input = {3, 6, 7, 2, 9}
// Output = 8
//
#include <iostream>
#include <bits/stdc++.h>
#include <typeinfo>
using namespace std;
#define DEBUG 0
int findgroups(int arr[], int n)
{
int count[3];
int i = 0;
for (i = 0; i < 3; i++)
count[i] = 0;
for (i = 0; i < n; i++)
{
count[arr[i] % 3]++;
}
int x = count[0];
int y = count[1];
int z = count[2];
int two_pair_count = (x * (x-1))/2 + // all from x
y * z; // one from y one from z
int three_pair_count = (x * (x - 1) * (x -2))/6 + // all from x
(y * (y - 1) * (y -2))/6 + // all from y
(z * (z - 1) * (z -2))/6 + // all from x
(x * y * z); // one from each group
return two_pair_count + three_pair_count;
}
int main()
{
int arr[] = {3, 6, 7, 2, 9};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Required number of groups are "
<< findgroups(arr,n) << endl;
return 0;
}
| [
"Chandan.p@greyorange.sg"
] | Chandan.p@greyorange.sg |
5746240776395ab09ff944324a722de5e193c9a3 | 9da899bf6541c6a0514219377fea97df9907f0ae | /Editor/MergeActors/Private/SMergeActorsToolbar.cpp | 48343c18db1f50906af1ac9bbc11fbfb1d6bdc1f | [] | no_license | peichangliang123/UE4 | 1aa4df3418c077dd8f82439ecc808cd2e6de4551 | 20e38f42edc251ee96905ed8e96e1be667bc14a5 | refs/heads/master | 2023-08-17T11:31:53.304431 | 2021-09-15T00:31:03 | 2021-09-15T00:31:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,613 | cpp | // Copyright Epic Games, Inc. All Rights Reserved.
#include "SMergeActorsToolbar.h"
#include "IMergeActorsTool.h"
#include "Modules/ModuleManager.h"
#include "Widgets/SBoxPanel.h"
#include "Styling/SlateTypes.h"
#include "Widgets/Layout/SBorder.h"
#include "Widgets/Images/SImage.h"
#include "Widgets/Layout/SBox.h"
#include "Widgets/Input/SButton.h"
#include "Widgets/Layout/SScrollBox.h"
#include "Widgets/Input/SCheckBox.h"
#include "Widgets/Input/STextComboBox.h"
#include "EditorStyleSet.h"
#include "Editor/UnrealEdEngine.h"
#include "UnrealEdGlobals.h"
#include "LevelEditor.h"
#include "IDocumentation.h"
#include "Styling/ToolBarStyle.h"
#define LOCTEXT_NAMESPACE "SMergeActorsToolbar"
//////////////////////////////////////////////////////////////
void SMergeActorsToolbar::Construct(const FArguments& InArgs)
{
// Important: We use raw bindings here because we are releasing our binding in our destructor (where a weak pointer would be invalid)
// It's imperative that our delegate is removed in the destructor for the level editor module to play nicely with reloading.
FLevelEditorModule& LevelEditor = FModuleManager::GetModuleChecked<FLevelEditorModule>("LevelEditor");
LevelEditor.OnActorSelectionChanged().AddRaw(this, &SMergeActorsToolbar::OnActorSelectionChanged);
RegisteredTools = InArgs._ToolsToRegister;
ChildSlot
[
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.AutoHeight()
.Padding(0, 0, 0, 0)
[
SAssignNew(ToolbarContainer, SBorder)
.BorderImage(FEditorStyle::GetBrush("ToolPanel.GroupBorder"))
.Padding(10)
]
+ SVerticalBox::Slot()
.FillHeight(1.0f)
.Padding(0, 0, 0, 0)
[
SNew(SBorder)
.BorderImage(FStyleDefaults::GetNoBrush())
.Padding(0.f)
.IsEnabled(this, &SMergeActorsToolbar::GetContentEnabledState)
[
SNew(SScrollBox)
+SScrollBox::Slot()
[
SAssignNew(InlineContentHolder, SBox)
]
]
]
+ SVerticalBox::Slot()
.AutoHeight()
.VAlign(VAlign_Bottom)
[
SNew(SBorder)
.BorderImage(FEditorStyle::GetBrush("ToolPanel.GroupBorder"))
.Padding(10)
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.HAlign(HAlign_Left)
.Padding(FEditorStyle::GetMargin("StandardDialog.ContentPadding"))
[
SNew(SCheckBox)
.Type(ESlateCheckBoxType::CheckBox)
.IsChecked_Lambda([this]() { return this->RegisteredTools[CurrentlySelectedTool]->GetReplaceSourceActors() ? ECheckBoxState::Checked : ECheckBoxState::Unchecked; })
.OnCheckStateChanged_Lambda([this](ECheckBoxState NewValue) { this->RegisteredTools[CurrentlySelectedTool]->SetReplaceSourceActors(NewValue == ECheckBoxState::Checked); })
.Content()
[
SNew(STextBlock)
.Text(LOCTEXT("ReplaceSourceActorsLabel", "Replace Source Actors"))
.Font(FEditorStyle::GetFontStyle("StandardDialog.SmallFont"))
]
]
+ SHorizontalBox::Slot()
.HAlign(HAlign_Right)
.Padding(4, 4, 10, 4)
[
SNew(SButton)
.ButtonStyle(FEditorStyle::Get(), "PrimaryButton")
.TextStyle(FEditorStyle::Get(), "DialogButtonText")
.Text(LOCTEXT("MergeActors", "Merge Actors"))
.OnClicked(this, &SMergeActorsToolbar::OnMergeActorsClicked)
.IsEnabled_Lambda([this]() -> bool { return this->RegisteredTools[CurrentlySelectedTool]->CanMergeFromWidget(); })
]
]
]
];
UpdateToolbar();
// Update selected actor state for the first time
GUnrealEd->UpdateFloatingPropertyWindows();
}
SMergeActorsToolbar::~SMergeActorsToolbar()
{
FLevelEditorModule& LevelEditor = FModuleManager::GetModuleChecked<FLevelEditorModule>("LevelEditor");
LevelEditor.OnActorSelectionChanged().RemoveAll(this);
}
void SMergeActorsToolbar::OnActorSelectionChanged(const TArray<UObject*>& NewSelection, bool bForceRefresh)
{
SelectedObjects = NewSelection;
bIsContentEnabled = (NewSelection.Num() > 0);
}
void SMergeActorsToolbar::OnToolSelectionChanged(TSharedPtr<FDropDownItem> NewSelection, ESelectInfo::Type SelectInfo)
{
int32 Index = 0;
if (ToolDropDownEntries.Find(NewSelection, Index) && Index != CurrentlySelectedTool)
{
CurrentlySelectedTool = Index;
UpdateInlineContent();
}
}
FReply SMergeActorsToolbar::OnMergeActorsClicked()
{
if (CurrentlySelectedTool >= 0 && CurrentlySelectedTool < RegisteredTools.Num())
{
RegisteredTools[CurrentlySelectedTool]->RunMergeFromWidget();
}
return FReply::Handled();
}
bool SMergeActorsToolbar::GetContentEnabledState() const
{
return bIsContentEnabled;
}
void SMergeActorsToolbar::AddTool(IMergeActorsTool* Tool)
{
check(!RegisteredTools.Contains(Tool));
RegisteredTools.Add(Tool);
UpdateToolbar();
}
void SMergeActorsToolbar::RemoveTool(IMergeActorsTool* Tool)
{
int32 IndexToRemove = RegisteredTools.Find(Tool);
if (IndexToRemove != INDEX_NONE)
{
RegisteredTools.RemoveAt(IndexToRemove);
if (CurrentlySelectedTool > IndexToRemove)
{
CurrentlySelectedTool--;
}
UpdateToolbar();
}
}
SMergeActorsToolbar::FDropDownItem::FDropDownItem(const FText& InName, const FName& InIconName)
: Name(InName), IconName(InIconName)
{}
void SMergeActorsToolbar::UpdateToolbar()
{
// Build tools entries data for the drop-down
ToolDropDownEntries.Empty();
for(int32 ToolIndex = 0; ToolIndex < RegisteredTools.Num(); ++ToolIndex)
{
const IMergeActorsTool* Tool = RegisteredTools[ToolIndex];
ToolDropDownEntries.Add(MakeShareable(new FDropDownItem(Tool->GetTooltipText(), Tool->GetIconName())));
}
// Build combo box
const ISlateStyle& StyleSet = FEditorStyle::Get();
TSharedRef <SComboBox<TSharedPtr<FDropDownItem> > > ComboBox =
SNew(SComboBox<TSharedPtr<FDropDownItem> >)
.OptionsSource(&ToolDropDownEntries)
.OnGenerateWidget(this, &SMergeActorsToolbar::MakeWidgetFromEntry)
.InitiallySelectedItem(ToolDropDownEntries[CurrentlySelectedTool])
.OnSelectionChanged(this, &SMergeActorsToolbar::OnToolSelectionChanged)
.Content()
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
.VAlign(VAlign_Center)
[
SNew(SImage)
.Image_Lambda([this](){
return FEditorStyle::Get().GetBrush(ToolDropDownEntries[CurrentlySelectedTool]->IconName);
})
]
+ SHorizontalBox::Slot()
.FillWidth(1)
.VAlign(VAlign_Center)
.Padding(5.0, 0, 0, 0)
[
SNew(STextBlock)
.Text_Lambda([this]() -> FText {
return ToolDropDownEntries[CurrentlySelectedTool]->Name;
})
]
];
TSharedRef<SHorizontalBox> ToolbarContent =
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.HAlign(HAlign_Left)
.VAlign(VAlign_Center)
.AutoWidth()
[
SNew(STextBlock)
.Text(LOCTEXT("MergeMethodLabel", "Merge Method"))
]
+ SHorizontalBox::Slot()
.VAlign(VAlign_Center)
.Padding(10.0, 0, 0, 0)
[
ComboBox
]
// Filler so that the combo box is just the right size
+ SHorizontalBox::Slot()
[
SNew(SBorder)
.BorderImage(FStyleDefaults::GetNoBrush())
];
ToolbarContainer->SetContent(ToolbarContent);
UpdateInlineContent();
}
TSharedRef<SWidget> SMergeActorsToolbar::MakeWidgetFromEntry(TSharedPtr<FDropDownItem> InItem)
{
return SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
.VAlign(VAlign_Center)
[
SNew(SImage)
.Image(FEditorStyle::Get().GetBrush(InItem->IconName))
]
+ SHorizontalBox::Slot()
.FillWidth(1)
.VAlign(VAlign_Center)
.Padding(5.0, 0, 0, 0)
[
SNew(STextBlock)
.Text(InItem->Name)
];
}
void SMergeActorsToolbar::UpdateInlineContent()
{
if (CurrentlySelectedTool >= 0 && CurrentlySelectedTool < RegisteredTools.Num())
{
InlineContentHolder->SetContent(RegisteredTools[CurrentlySelectedTool]->GetWidget());
}
}
#undef LOCTEXT_NAMESPACE
| [
"ouczbs@qq.com"
] | ouczbs@qq.com |
7d9d27cda3a3cbfa2310d7b4cadeaa63039c2811 | 85bfa469d58bc52c6d39e1dbdfc02b4b63ca6ac7 | /arduPi/user-Modbus-app.cpp | 757e88a304a4dc95045f31e6ff01c72fa71cf26f | [] | no_license | mjjudge/modbus | 91926ffe4f991d90703bc74522dff077a1d1344f | 597a5ad6d7c1fb8ad006fbf195f5eb93613fce1b | refs/heads/master | 2021-05-09T19:27:26.925183 | 2018-01-30T12:29:59 | 2018-01-30T12:29:59 | 118,642,470 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,255 | cpp | /*
* ModBus Module
*
* Copyright (C) Libelium Comunicaciones Distribuidas S.L.
* http://www.libelium.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.
* a
* 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/.
*
* Version: 1.0
* Design: David Gascón
* Implementation: Ahmad Saad
*/
// Include these libraries for using the RS-485 and Modbus functions
#include "ModbusMaster485.h"
#include "arduPi.h"
// Instantiate ModbusMaster object as slave ID 1
ModbusMaster485 node(17);
// Define one addres for reading
#define address 6
// Define the number of bytes to read
#define bytesQty 2
void setup()
{
pinMode(5, OUTPUT);
digitalWrite(5, LOW);
// Power on the USB for viewing data in the serial monitor
//Serial.begin(115200);
delay(100);
// Initialize Modbus communication baud rate
node.begin(9600);
// Print hello message
printf("Modbus communication over RS-485\n");
delay(100);
}
void loop()
{
// This variable will store the result of the communication
// result = 0 : no errors
// result = 1 : error occurred
// for (int i;i<2;i++)
//{
int result = node.readHoldingRegisters(address, bytesQty);
if (result != 0) {
// If no response from the slave, print an error message
printf("Communication error\n");
delay(1000);
}
else {
// If all OK
printf("Read value: \n");
// Print the read data from the slave
printf("%d\n", node.getResponseBuffer(0));
delay(1000);
}
printf("\n");
delay(2000);
// Clear the response buffer
node.clearResponseBuffer();
}
int main (){
setup();
while(1){
loop();
}
return (0);
}
| [
"marcus.judge@gmail.com"
] | marcus.judge@gmail.com |
0378d1a1d6b9b83a817dc120b4f213ce344ff7fe | 4e8d98aa156e34e4e95f9374fcb02aa7f65f3057 | /examples/site_with_db/include/calculate.h | b27602517f1141203725cb44f9559e4017f6c908 | [
"MIT"
] | permissive | akrava/web-framework | bfdb3aef95628d821c548c3805ec45f9e0ef6918 | 109902c662ab33552c62d8b3a8533191068b1d43 | refs/heads/master | 2020-03-19T20:21:34.423730 | 2019-08-18T14:38:08 | 2019-08-18T14:38:08 | 136,898,157 | 6 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 206 | h | #pragma once
#include <akrava/web-server/handler.h>
class HandlerCalculate : public Handler {
public:
HandlerCalculate(const char * ds, HTTP::Method m) : Handler(ds, m) {}
void exec() override;
}; | [
"arkadiy@ex.ua"
] | arkadiy@ex.ua |
cb712cd06d26dcd0c02ddaa5da6f58a98d5609dc | ddefeb02ed8634c8d3ad2181e1722638b341ac9e | /models/Password.h | cc10a2aea3bf6087092228c814160965a384475a | [] | no_license | kenloque/AA_Caso7 | 9f7ba36a489e8231b4cf108cdee1cb5dffda887e | d2ed1350b205e2bc33b202cdbbd08b36899bfc5c | refs/heads/main | 2023-05-06T23:44:35.516733 | 2021-06-07T03:21:38 | 2021-06-07T03:21:38 | 374,516,738 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 278 | h | #ifndef PASSWORD_H_
#define PASSWORD_H_
#include "../utils/IConst.h"
/*
Abstracción de una contraseña
Es un arreglo de caracteres
*/
class Password {
public:
void addChar(char pChar);
void print();
private:
char value[MAX_CHAR_AMOUNT];
short int lastChar;
};
#endif
| [
"kendalllq161113@estudiantec.cr"
] | kendalllq161113@estudiantec.cr |
d526bffd37a2da67f44bf54e855b430dd5f0ece6 | 8dc84558f0058d90dfc4955e905dab1b22d12c08 | /third_party/blink/renderer/core/animation/interpolation_effect.h | 335800e8d71b24e830e4a655be6c71b10c5d9f10 | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause",
"LGPL-2.0-only",
"BSD-2-Clause",
"LGPL-2.1-only"
] | permissive | meniossin/src | 42a95cc6c4a9c71d43d62bc4311224ca1fd61e03 | 44f73f7e76119e5ab415d4593ac66485e65d700a | refs/heads/master | 2022-12-16T20:17:03.747113 | 2020-09-03T10:43:12 | 2020-09-03T10:43:12 | 263,710,168 | 1 | 0 | BSD-3-Clause | 2020-05-13T18:20:09 | 2020-05-13T18:20:08 | null | UTF-8 | C++ | false | false | 2,949 | h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_INTERPOLATION_EFFECT_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_INTERPOLATION_EFFECT_H_
#include "third_party/blink/renderer/core/animation/interpolation.h"
#include "third_party/blink/renderer/core/animation/keyframe.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/platform/animation/timing_function.h"
namespace blink {
// Stores all adjacent pairs of keyframes (represented by Interpolations) in a
// KeyframeEffectModel with keyframe offset data preprocessed for more efficient
// active keyframe pair sampling.
class CORE_EXPORT InterpolationEffect {
DISALLOW_NEW_EXCEPT_PLACEMENT_NEW();
public:
InterpolationEffect() : is_populated_(false) {}
bool IsPopulated() const { return is_populated_; }
void SetPopulated() { is_populated_ = true; }
void Clear() {
is_populated_ = false;
interpolations_.clear();
}
void GetActiveInterpolations(double fraction,
double iteration_duration,
Vector<scoped_refptr<Interpolation>>&) const;
void AddInterpolation(scoped_refptr<Interpolation> interpolation,
scoped_refptr<TimingFunction> easing,
double start,
double end,
double apply_from,
double apply_to) {
interpolations_.push_back(InterpolationRecord(std::move(interpolation),
std::move(easing), start, end,
apply_from, apply_to));
}
void AddInterpolationsFromKeyframes(
const PropertyHandle&,
const Keyframe::PropertySpecificKeyframe& keyframe_a,
const Keyframe::PropertySpecificKeyframe& keyframe_b,
double apply_from,
double apply_to);
private:
struct InterpolationRecord {
InterpolationRecord(scoped_refptr<Interpolation> interpolation,
scoped_refptr<TimingFunction> easing,
double start,
double end,
double apply_from,
double apply_to)
: interpolation_(std::move(interpolation)),
easing_(std::move(easing)),
start_(start),
end_(end),
apply_from_(apply_from),
apply_to_(apply_to) {}
scoped_refptr<Interpolation> interpolation_;
scoped_refptr<TimingFunction> easing_;
double start_;
double end_;
double apply_from_;
double apply_to_;
};
bool is_populated_;
Vector<InterpolationRecord> interpolations_;
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_ANIMATION_INTERPOLATION_EFFECT_H_
| [
"arnaud@geometry.ee"
] | arnaud@geometry.ee |
7105b71c24a2c9121c7f00fa8d208af2d382d925 | c94a4a67e925a8c1d185857d89e92b02c2ce8a2b | /src/solver/ode_solver.h | 10321216116da0adf1494d975fa471098738b0fd | [] | no_license | pedrororo/Droplets_2D | 99572681fb6b34a146a8f98bdebeb07f9ac1ef06 | 358ebba02fc979aff6559335aa0b097905cc2e47 | refs/heads/master | 2021-02-13T20:15:11.776699 | 2020-03-11T20:38:39 | 2020-03-11T20:38:39 | 244,729,071 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 570 | h |
#ifndef ODE_SOLVER_H
#define ODE_SOLVER_H
#include <cstdio>
#include <cstdlib>
#include <cstdbool>
#include <cstdint>
#include <cstring>
// FHN CONSTANT
const double a = 0.2;
const double b = 0.5;
const double k_F = 80.0;
const double test_K = 0.0011;
struct solver_ode
{
double dt;
double tmax;
double time_new;
};
struct solver_ode* new_solver_ode();
void configure_ode_solver (struct solver_ode *s, const double tmax, const double dt);
void solve_ode_system_FHN (double **U, double **V, const double dt, const uint32_t nx, const uint32_t ny);
#endif
| [
"pedro@localhost-106.localdomain"
] | pedro@localhost-106.localdomain |
b723e86b2e3c016095ce279c12702787cf29213c | 6f998bc0963dc3dfc140475a756b45d18a712a1e | /Source/AnimationLib/PudgeDeathByGooState.h | 576712d42e2a2836631b1730c2bd9da9b640121a | [] | no_license | iomeone/PudgeNSludge | d4062529053c4c6d31430e74be20e86f9d04e126 | 55160d94f9ef406395d26a60245df1ca3166b08d | refs/heads/master | 2021-06-11T09:45:04.035247 | 2016-05-25T05:57:08 | 2016-05-25T05:57:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 567 | h | #ifndef PUDGEDEATHBYGOOSTATE_H_
#define PUDGEDEATHBYGOOSTATE_H_
#include "State.h"
__declspec(align(32))
class PudgeDeathByGooState : public State
{
private:
PudgeDeathByGooState(void){}
PudgeDeathByGooState( const PudgeDeathByGooState& ) {}
const PudgeDeathByGooState& operator = (const PudgeDeathByGooState& ) {}
public:
~PudgeDeathByGooState(void);
static PudgeDeathByGooState* GetState();
void Enter(CComponent_Animation* pComponent);
void Execute(CComponent_Animation* pComponent, float fTime);
void Exit(CComponent_Animation* pComponent);
};
#endif | [
"ethanthecrazy@gmail.com"
] | ethanthecrazy@gmail.com |
3bd80d8b86d4c0419218be627e0323e390c86a1c | 78549596df6dea622a4a815f6568f97970b69118 | /SDEngine/Source/ShaderManager.cpp | 0955e6a3a7ed88419bcd8b4bd45cd9423248b940 | [] | no_license | OscarGame/SDEngine | c9cf79e01ecbd0b953b8a2849d606c69c6f66cf2 | 4f17916c291f5ee24c919ca888309374b89f1d2f | refs/heads/master | 2020-03-27T00:28:17.952199 | 2018-08-11T15:50:15 | 2018-08-11T15:50:15 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 8,574 | cpp |
#include "ShaderManager.h"
ShaderManager::ShaderManager()
{
Init();
}
ShaderManager::~ShaderManager()
{
}
ShaderManager::ShaderManager(const ShaderManager& other)
{
}
bool ShaderManager::Init()
{
mDiffuseNormalShader = shared_ptr<DiffuseNormalShader>(new
DiffuseNormalShader(L"Resource/Shader/DiffuseNormalShader.fx", L"Resource/Shader/DiffuseNormalShader.fx"));
mDiffuseNormalSpecShader = shared_ptr<DiffuseNormalSpecShader>(new
DiffuseNormalSpecShader(L"Resource/Shader/DiffuseNormalSpecularShader.fx", L"Resource/Shader/DiffuseNormalSpecularShader.fx"));
//´´½¨ÒÔ¼°³õʼ»¯mPhongShader
mDiffuseShader = shared_ptr<DiffuseShader>(new
DiffuseShader(L"Resource/Shader/DiffuseShader.fx", L"Resource/Shader/DiffuseShader.fx"));
//´´½¨ÒÔ¼°³õʼ»¯mPhongShader
mDefferDirLightShader = shared_ptr<DefferedDirLightShader>(new
DefferedDirLightShader(L"Resource/Shader/DefferedDirLightShader.fx", L"Resource/Shader/DefferedDirLightShader.fx"));
mDefferPointLightShader = shared_ptr<DefferedPointLightShader>(new
DefferedPointLightShader(L"Resource/Shader/DefferedPointLightShader.fx", L"Resource/Shader/DefferedPointLightShader.fx"));
mDepthShader = shared_ptr<DepthShader>(new
DepthShader(L"Resource/Shader/DepthShader.fx", L"Resource/Shader/DepthShader.fx"));
mPureColorShader = shared_ptr<PureColorShader>(new
PureColorShader(L"Resource/Shader/PureColorShader.fx", L"Resource/Shader/PureColorShader.fx"));
mUIShader = shared_ptr<UIShader>(new
UIShader(L"Resource/Shader/UIShader.fx", L"Resource/Shader/UIShader.fx"));
mGraphcisBlitShader = shared_ptr<GraphcisBlitShader>(new
GraphcisBlitShader(L"Resource/Shader/GraphicsBlitShader.fx", L"Resource/Shader/GraphicsBlitShader.fx"));
mDOFShader = shared_ptr<DOFShader>(new
DOFShader(L"Resource/Shader/DOFShader.fx", L"Resource/Shader/DOFShader.fx"));
mBlurShader = shared_ptr<BlurShader>(new
BlurShader(L"Resource/Shader/BlurShader.fx", L"Resource/Shader/BlurShader.fx"));
mSSRShader = shared_ptr<SSRShader>(new
SSRShader(L"Resource/Shader/ScreenSpaceReflectShader.fx", L"Resource/Shader/ScreenSpaceReflectShader.fx"));
mForwardPureColorShader = shared_ptr<PureColorShader>(new
PureColorShader(L"Resource/Shader/ForwardPureColorShader.fx",
L"Resource/Shader/ForwardPureColorShader.fx"));
mDepthGetShader = shared_ptr<Shader_3D>(new Shader_3D(L"Resource/Shader/DepthGetShader.fx",
L"Resource/Shader/DepthGetShader.fx"));
mSSRGBufferShader = shared_ptr<SSRGBufferShader>(new SSRGBufferShader(L"Resource/Shader/SSRGBuffer.fx",
L"Resource/Shader/SSRGBuffer.fx"));
mWaveShader = shared_ptr<WaveShader>(new
WaveShader(L"Resource/Shader/WaveShader.fx", L"Resource/Shader/WaveShader.fx"));
return true;
}
bool ShaderManager::SetDiffuseShader(CXMMATRIX worldMatrix,ID3D11ShaderResourceView* diffsuseTexture)
{
bool result;
result = mDiffuseShader->SetShaderParamsExtern(worldMatrix, diffsuseTexture);
if (!result)
{
MessageBox(NULL, L"DiffuseShader render ʧ°Ü", NULL, MB_OK);
return false;
}
return true;
}
bool ShaderManager::SetDiffuseNormalShader(CXMMATRIX worldMatrix,
ID3D11ShaderResourceView* diffuseSRV, ID3D11ShaderResourceView* normalSRV)
{
bool result;
result = mDiffuseNormalShader->SetShaderParamsExtern(worldMatrix,diffuseSRV,normalSRV);
if (!result)
{
MessageBox(NULL, L"DiffuseNormalShader render ʧ°Ü", NULL, MB_OK);
return false;
}
return true;
}
bool ShaderManager::SetDiffuseNormalSpecShader(CXMMATRIX worldMatrix,
ID3D11ShaderResourceView* diffuseSRV, ID3D11ShaderResourceView* normalSRV,
ID3D11ShaderResourceView* specSRV)
{
bool result;
result = mDiffuseNormalSpecShader->SetShaderParamsExtern(worldMatrix, diffuseSRV,
normalSRV,specSRV);
if (!result)
{
MessageBox(NULL, L"DiffuseNormalSpecShader render ʧ°Ü", NULL, MB_OK);
return false;
}
return true;
}
bool ShaderManager::SetUIShader(ID3D11ShaderResourceView* diffuseTexture)
{
bool result;
result = mUIShader->SetShaderParams(diffuseTexture);
if (!result)
{
MessageBox(NULL, L"mUIShader render ʧ°Ü", NULL, MB_OK);
return false;
}
return true;
}
bool ShaderManager::SetDepthShader(ID3D11ShaderResourceView* depthTexture)
{
bool result;
result = mDepthShader->SetShaderParams(depthTexture);
if (!result)
{
MessageBox(NULL, L" depth shader render ʧ°Ü", NULL, MB_OK);
return false;
}
return true;
}
shared_ptr<ShaderManager> ShaderManager::Get()
{
if (nullptr == m_spShaderManager)
{
m_spShaderManager = shared_ptr<ShaderManager>(new ShaderManager());
}
return m_spShaderManager;
}
bool ShaderManager::SetPureColorShader(CXMMATRIX worldMatrix, FXMVECTOR surfaceColor)
{
bool result;
result = mPureColorShader->SetShaderParamsExtern(worldMatrix, surfaceColor);
if (!result)
{
MessageBox(NULL, L" mPureColorShader render ʧ°Ü", NULL, MB_OK);
return false;
}
return true;
}
bool ShaderManager::SetForwardPureColorShader(CXMMATRIX worldMatrix, FXMVECTOR surfaceColor)
{
bool result;
result = mForwardPureColorShader->SetShaderParamsExtern(worldMatrix, surfaceColor);
if (!result)
{
MessageBox(NULL, L" mForwardPureColorShader render ʧ°Ü", NULL, MB_OK);
return false;
}
return true;
}
bool ShaderManager::SetDiffuseSpecShader(CXMMATRIX worldMatrix,
ID3D11ShaderResourceView* diffuseSRV, ID3D11ShaderResourceView* specSRV)
{
bool result;
result = mDiffuseSpecShader->SetShaderParamsExtern(worldMatrix,
diffuseSRV, specSRV);
if (!result)
{
MessageBox(NULL, L"DiffuseNormalSpecShader render ʧ°Ü", NULL, MB_OK);
return false;
}
return true;
}
bool ShaderManager::SetGraphcisBlitShader(ID3D11ShaderResourceView* screenRT)
{
bool result;
result = mGraphcisBlitShader->SetShaderParams(screenRT);
if (!result)
{
MessageBox(NULL, L"mGraphcisBlitShader render ʧ°Ü", NULL, MB_OK);
return false;
}
return true;
}
bool ShaderManager::SetDOFShader(ID3D11ShaderResourceView* screenRT, ID3D11ShaderResourceView* screenBlurRT,
ID3D11ShaderResourceView* depthRT,
float dofStart, float dofRange, float farPlane, float nearPlane)
{
bool result;
result = mDOFShader->SetShaderParams(screenRT, screenBlurRT, depthRT,
dofStart, dofRange, farPlane,nearPlane);
if (!result)
{
MessageBox(NULL, L"DOFShader render ʧ°Ü", NULL, MB_OK);
return false;
}
return true;
}
bool ShaderManager::SetBlurShader(ID3D11ShaderResourceView* screenRT)
{
bool result;
result = mBlurShader->SetShaderParams(screenRT);
if (!result)
{
MessageBox(NULL, L"mBlurShader render ʧ°Ü", NULL, MB_OK);
return false;
}
return true;
}
bool ShaderManager::SetSSRShader(CXMMATRIX worldMatrix, ID3D11ShaderResourceView* arraySRV[5],
XMFLOAT2 perspectiveValue)
{
bool result;
result = mSSRShader->SetShaderParams(worldMatrix, arraySRV, perspectiveValue);
if (!result)
{
MessageBox(NULL, L"mSSRShader render ʧ°Ü", NULL, MB_OK);
return false;
}
return true;
}
bool ShaderManager::SetDepthGetShader(CXMMATRIX worldMatrix)
{
bool result;
result = mDepthGetShader->SetShaderParams(worldMatrix);
if (!result)
{
MessageBox(NULL, L"DepthGetShader render ʧ°Ü", NULL, MB_OK);
return false;
}
return true;
}
bool ShaderManager::SetSSRGBufferShader(ID3D11ShaderResourceView* gBuffer[2])
{
bool result;
result = mSSRGBufferShader->SetShaderParams(gBuffer);
if (!result)
{
MessageBox(NULL, L"SSRGBufferShader render ʧ°Ü", NULL, MB_OK);
return false;
}
return true;
}
bool ShaderManager::SetWaveShader(CXMMATRIX worldMatrix, FXMVECTOR surfaceColor,
ID3D11ShaderResourceView* diffuse, ID3D11ShaderResourceView* normal)
{
bool result;
result = mWaveShader->SetShaderParamsExtern(worldMatrix, surfaceColor, diffuse, normal);
if (!result)
{
MessageBox(NULL, L"mWaveShader render ʧ°Ü", NULL, MB_OK);
return false;
}
return true;
}
bool ShaderManager::SetDefferedDirLightShader(ID3D11ShaderResourceView* gBuffer[4], int nDirLightIndex)
{
bool result;
result = mDefferDirLightShader->SetShaderParams(gBuffer, nDirLightIndex);
if (!result)
{
MessageBox(NULL, L"mDefferDirLightShader render ʧ°Ü", NULL, MB_OK);
return false;
}
return true;
}
bool ShaderManager::SetDefferedPointLightShader(ID3D11ShaderResourceView* gBuffer[4], int nPointLightIndex)
{
bool result;
result = mDefferPointLightShader->SetShaderParams(gBuffer, nPointLightIndex);
if (!result)
{
MessageBox(NULL, L"mDefferPointLightShader render ʧ°Ü", NULL, MB_OK);
return false;
}
return true;
}
shared_ptr<ShaderManager> ShaderManager::m_spShaderManager = nullptr;
| [
"2047241149@qq.com"
] | 2047241149@qq.com |
f6e4baf1064e56eee8595ff2918facea258bdedd | 8a4c24de1230bbb060d96340485cf63824b501e1 | /DeusServer/GameLogicServer.cpp | 6d008ab700f28d5dcb92c18d596711f532309d5b | [
"MIT"
] | permissive | Suliac/ProjectDeusServer | c9b46c3fbb86d14bb0bc36eaaec2c0bdf76b25e5 | b7af922a6bc2596c733665898b6aefd989bf2270 | refs/heads/master | 2020-03-22T15:52:22.600876 | 2018-10-30T00:17:06 | 2018-10-30T00:17:06 | 140,285,371 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,408 | cpp | #include "GameLogicServer.h"
#include "GameObjectFactory.h"
#include "PacketObjectChangeCell.h"
#include "PacketCellFirePacket.h"
#include "PositionTimeLineComponent.h"
#include "HealthTimeLineComponent.h"
#include "SkillTimeLineComponent.h"
#include "DeusCore/Logger.h"
#include "DeusCore/Packets.h"
#include "DeusCore/EventManagerHandler.h"
#include "DeusCore/ResourcesHandler.h"
namespace DeusServer
{
GameLogicServer::GameLogicServer(Id gameId)
{
m_gameId = gameId;
m_name = "Logic Server " + std::to_string(gameId);
DeusCore::Logger::Instance()->Log(m_name, "New " + m_name);
DeusCore::DeusEventDeleguate messageInterpretDeleguate = fastdelegate::MakeDelegate(this, &GameLogicServer::InterpretPacket);
DeusCore::EventManagerHandler::Instance()->AddListener(m_gameId, messageInterpretDeleguate, DeusCore::Packet::EMessageType::StartGame);
DeusCore::EventManagerHandler::Instance()->AddListener(m_gameId, messageInterpretDeleguate, DeusCore::Packet::EMessageType::Disconnect);
DeusCore::EventManagerHandler::Instance()->AddListener(m_gameId, messageInterpretDeleguate, DeusCore::Packet::EMessageType::LeaveGameRequest);
DeusCore::EventManagerHandler::Instance()->AddListener(m_gameId, messageInterpretDeleguate, DeusCore::Packet::EMessageType::UpdateMovementRequest);
DeusCore::EventManagerHandler::Instance()->AddListener(m_gameId, messageInterpretDeleguate, DeusCore::Packet::EMessageType::UseSkillRequest);
}
GameLogicServer::~GameLogicServer()
{
if (!m_isStopped)
Stop();
}
void GameLogicServer::OnUpdate(double deltatimeMs)
{
m_cellLock.lock();
for (const auto& cellGameObjects : m_cellsGameObjects)
{
for (const auto& gameObj : cellGameObjects.second)
gameObj.second->Update(deltatimeMs);
}
m_cellLock.unlock();
}
void GameLogicServer::OnStart()
{
m_cellLock.lock();
for (const auto& cellGameObjects : m_cellsGameObjects)
{
//m_gameObjLocker[cellGameObjects.first - 1].lock(); // <-----------LOCK
for (const auto& gameObj : cellGameObjects.second)
{
gameObj.second->Start();
}
//m_gameObjLocker[cellGameObjects.first - 1].unlock(); // <-----------UNLOCK
}
m_cellLock.unlock();
}
void GameLogicServer::OnStop()
{
DeusCore::DeusEventDeleguate messageInterpretDeleguate = fastdelegate::MakeDelegate(this, &GameLogicServer::InterpretPacket);
DeusCore::EventManagerHandler::Instance()->RemoveListener(m_gameId, messageInterpretDeleguate, DeusCore::Packet::EMessageType::StartGame);
DeusCore::EventManagerHandler::Instance()->RemoveListener(m_gameId, messageInterpretDeleguate, DeusCore::Packet::EMessageType::Disconnect);
DeusCore::EventManagerHandler::Instance()->RemoveListener(m_gameId, messageInterpretDeleguate, DeusCore::Packet::EMessageType::LeaveGameRequest);
DeusCore::EventManagerHandler::Instance()->RemoveListener(m_gameId, messageInterpretDeleguate, DeusCore::Packet::EMessageType::UpdateMovementRequest);
DeusCore::EventManagerHandler::Instance()->RemoveListener(m_gameId, messageInterpretDeleguate, DeusCore::Packet::EMessageType::UseSkillRequest);
m_cellsGameObjects.clear();
m_playerWithGameObject.clear();
DeusCore::Logger::Instance()->Log(m_name, "Stopped");
}
bool GameLogicServer::AddObject(std::shared_ptr<GameObject> p_objectToAdd, Id cellId)
{
m_cellLock.lock();
if (m_cellsGameObjects[cellId].find(p_objectToAdd->GetId()) != m_cellsGameObjects[cellId].end())
{
m_cellLock.unlock();
return false; // Already existing game object !
}
p_objectToAdd->Start();
//DeusCore::Logger::Instance()->Log(m_name, "Create GameObject : " + std::to_string(p_objectToAdd->GetId()));
m_cellsGameObjects[cellId].insert(std::make_pair(p_objectToAdd->GetId(), p_objectToAdd));
m_cellLock.unlock();
return true;
}
bool GameLogicServer::RemoveObject(uint32_t objectToDeleteId)
{
m_cellLock.lock();
for (auto& cellGameObjects : m_cellsGameObjects)
{
const auto& gameObjIt = cellGameObjects.second.find(objectToDeleteId);
if (gameObjIt != cellGameObjects.second.end())
{
gameObjIt->second->Stop();
cellGameObjects.second.erase(gameObjIt);
m_cellLock.unlock();
return true;
}
}
m_cellLock.unlock();
return false;
}
void GameLogicServer::InterpretPacket(DeusCore::DeusEventSPtr p_packet)
{
switch (p_packet->second->GetType())
{
case DeusCore::Packet::EMessageType::StartGame:
StartNewGame(((DeusCore::PacketStartGame*)p_packet->second.get())->GetPlayerConnectionId());
break;
case DeusCore::Packet::EMessageType::Disconnect:
PlayerDisconnected(p_packet->first);
break;
case DeusCore::Packet::EMessageType::LeaveGameRequest:
PlayerDisconnected(p_packet->first);
break;
case DeusCore::Packet::EMessageType::UpdateMovementRequest:
UpdatePlayerDirection(p_packet->first, std::dynamic_pointer_cast<DeusCore::PacketUpdateMovementRequest>(p_packet->second)->GetComponentId(), std::dynamic_pointer_cast<DeusCore::PacketUpdateMovementRequest>(p_packet->second)->GetNewPosition());
break;
case DeusCore::Packet::EMessageType::UseSkillRequest:
PlayerUseSkill(p_packet->first, std::dynamic_pointer_cast<DeusCore::PacketUseSkillRequest>(p_packet->second));
break;
}
}
void GameLogicServer::StartNewGame(const std::vector<uint32_t>& playerIds)
{
//DeusCore::Logger::Instance()->Log(m_name, "Yo");
// 1 - Init cells
for (size_t i = 0; i < NUMBER_CELLS; i++)
{
// We start Cells id at 1
m_cellsGameObjects.insert(std::make_pair(i + 1, ServerGameObjects()));
}
// 2 - Create a GameObject for each player
for (const auto id : playerIds)
{
if (m_playerWithGameObject.find(id) != m_playerWithGameObject.end())
continue;// already init this player
std::shared_ptr<GameObject> p_gameObj = GameObjectFactory::Create(GameObject::EObjectType::Player, m_gameId);
m_playerWithGameObject[id] = p_gameObj->GetId();
AddObject(p_gameObj, DEFAULT_CELL_ID); // give ownership
// TODO : Manage this in futur PositionComponent -> manage enter/leave cell
// Get already existing data
std::vector<std::shared_ptr<const GameObject>> objectInCellsLeft;
std::vector<std::shared_ptr<const GameObject>> objectInCellsEntered;
GetGameObjectOnChangeCells(id, 0, DEFAULT_CELL_ID, objectInCellsLeft, objectInCellsEntered);
DeusCore::PacketSPtr p_packet = std::shared_ptr<PacketObjectChangeCell>(new PacketObjectChangeCell(id, p_gameObj, 0, DEFAULT_CELL_ID, objectInCellsLeft, objectInCellsEntered, true));
DeusCore::EventManagerHandler::Instance()->QueueEvent(m_gameId, 0, p_packet);
}
for (const auto pGo : m_playerWithGameObject)
DeusCore::Logger::Instance()->Log(m_name, "Player : " + std::to_string(pGo.first) + " | GameObj : " + std::to_string(pGo.second));
// 3 - Start the game logic
Start();
// 4 - notify players
DeusCore::PacketSPtr p_packetGameStarted = std::shared_ptr<DeusCore::PacketGameStarted>(new DeusCore::PacketGameStarted());
DeusCore::EventManagerHandler::Instance()->QueueEvent(m_gameId, 0, p_packetGameStarted);
DeusCore::Logger::Instance()->Log(m_name, "End start new game");
}
void GameLogicServer::PlayerDisconnected(Id clientId)
{
Id objectId = 0;
m_playersLocker.lock(); // <---------- LOCK
// Delete player disconnected
PlayerInfos::iterator playerIt = m_playerWithGameObject.find(clientId);
if (playerIt != m_playerWithGameObject.end())
{
objectId = playerIt->second;
m_playerWithGameObject.erase(playerIt);
}
m_playersLocker.unlock(); // <---------- UNLOCK
if (objectId > 0)
{
Id cellId = 0; // 0 = error, ids start at 1
m_cellLock.lock();
for (auto& cellGameObjects : m_cellsGameObjects)
{
const auto& gameObjIt = cellGameObjects.second.find(objectId);
if (gameObjIt != cellGameObjects.second.end())
{
//////////////////////////////////////////////
m_playersLocker.lock(); // <---------- LOCK
if (m_playerWithGameObject.size() > 0)
{
DeusCore::PacketSPtr p_packet = std::shared_ptr<PacketObjectChangeCell>(new PacketObjectChangeCell(clientId, gameObjIt->second, cellGameObjects.first, (Id)0));
DeusCore::EventManagerHandler::Instance()->QueueEvent(m_gameId, 0, p_packet);
}
m_playersLocker.unlock(); // <---------- UNLOCK
//GameObject found, delete it and send infos
cellGameObjects.second.erase(gameObjIt);
//////////////////////////////////////////////
break;
}
}
m_cellLock.unlock();
}
}
void GameLogicServer::UpdatePlayerDirection(Id clientId, Id componentId, DeusCore::DeusVector2 destination)
{
//DeusCore::Logger::Instance()->Log(m_name, "|----------------------------------------------------------------- |");
GameObjectId objectId = 0;
m_playersLocker.lock(); // <----------- LOCK
// Find object
if (m_playerWithGameObject.find(clientId) != m_playerWithGameObject.end())
{
objectId = m_playerWithGameObject[clientId];
}
m_playersLocker.unlock(); // <----------- UNLOCK
if (objectId > 0)
{
try
{
m_cellLock.lock();
for (auto& cellGameObjects : m_cellsGameObjects)
{
// Search for object
const auto& gameObjIt = cellGameObjects.second.find(objectId);
if (gameObjIt != cellGameObjects.second.end())
{
// Search for PositionComponent
std::shared_ptr<GameObjectComponent> compo = gameObjIt->second->GetComponent(componentId);
if (compo != nullptr)
{
// 1 - Validate current position : position of the object in DELAY ms
uint32_t currentMs = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count() + DELAY_MS;
std::shared_ptr<const DeusCore::DeusVector2> p_posAtUpdate = std::dynamic_pointer_cast<PositionTimeLineComponent>(compo)->GetValue(currentMs);
assert(p_posAtUpdate);
std::dynamic_pointer_cast<PositionTimeLineComponent>(compo)->InsertData(p_posAtUpdate, currentMs);
// 2 - Extrapolate time to go to destination and insert futur data
float sqrtDist = DeusCore::DeusVector2::SqrtMagnitude(*p_posAtUpdate, destination);
uint32_t dtReachDestinationMs = sqrtDist / SPEED_MS; // t = d / s
//DeusCore::Logger::Instance()->Log(m_name, "reach destination in : "+std::to_string(dtReachDestinationMs)+"ms at : "+std::to_string(currentMs + dtReachDestinationMs));
std::dynamic_pointer_cast<PositionTimeLineComponent>(compo)->InsertData(std::make_shared<const DeusCore::DeusVector2>(destination), currentMs + dtReachDestinationMs);
// 3 - Send messages to clients
std::unique_ptr<DeusCore::PacketUpdateMovementAnswer> movementFeedback = std::unique_ptr<DeusCore::PacketUpdateMovementAnswer>(new DeusCore::PacketUpdateMovementAnswer(objectId, componentId, *p_posAtUpdate, currentMs, destination, currentMs + dtReachDestinationMs));
DeusCore::PacketSPtr p_cellFirePacket = std::shared_ptr<CellFirePacket>(new CellFirePacket(cellGameObjects.first, objectId, std::move(movementFeedback)));
DeusCore::EventManagerHandler::Instance()->QueueEvent(m_gameId, 0, p_cellFirePacket);
break;
}
}
}
m_cellLock.unlock();
}
catch (const std::system_error& e)
{
DeusCore::Logger::Instance()->Log(m_name, e.what());
}
}
}
void GameLogicServer::PlayerUseSkill(Id clientId, std::shared_ptr<DeusCore::PacketUseSkillRequest> p_packet)
{
DeusCore::Logger::Instance()->Log(m_name, "Player " + std::to_string(clientId) + " request to use skill " + std::to_string(p_packet->GetSkillId()));
m_cellLock.lock(); // <----------- LOCK
Id cellId = 0;
std::shared_ptr<GameObject> gameObj = GetObject(clientId, cellId);
std::shared_ptr<SkillTimeLineComponent> skillCompo = std::dynamic_pointer_cast<SkillTimeLineComponent>(gameObj->GetComponent(p_packet->GetComponentId()));
std::shared_ptr<PositionTimeLineComponent> posCompo = std::dynamic_pointer_cast<PositionTimeLineComponent>(gameObj->GetComponent(GameObjectComponent::EComponentType::PositionComponent));
if (skillCompo != nullptr && posCompo != nullptr)
{
uint32_t currentMs = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count() + DELAY_MS;
std::shared_ptr<const DeusCore::SkillInfos> p_skillInfos = skillCompo->GetValue(currentMs);
std::shared_ptr<const DeusCore::DeusVector2> p_pos = posCompo->GetValue(currentMs);
// 1 - Check if the player can use the skill requested
// That means :
// a) a skill isn't used at that time
// b) Skill used in right scope
// c) [TODO] Player has enough mana
// d) [TODO] Player has the minimum level requested and has unlocked the skill
bool canLaunch = true;
// a) Skill already launching ?
if (p_skillInfos != nullptr && p_skillInfos->GetTotalTime() >= currentMs) // a skill is already used !
canLaunch = false;
// b) Scope OK ?
if (DeusCore::DeusVector2::SqrtMagnitude(*p_pos, p_packet->GetSkillPosition()) > p_skillInfos->GetMaxScope()) // skill too far from player
canLaunch = false;
// c) TODO : Mana check
// d) TODO : Level check
// 2 - Insert datas
if (canLaunch)
{
DeusCore::Logger::Instance()->Log(m_name, "Can launch");
DeusCore::SkillPtr currentSkillModel = DeusCore::ResourcesHandler::Instance()->GetSkill(p_packet->GetSkillId());
std::shared_ptr<DeusCore::SkillInfos> p_newSkillInfos = std::make_shared<DeusCore::SkillInfos>(*(currentSkillModel), currentMs, p_packet->GetSkillPosition());
skillCompo->InsertData(p_newSkillInfos, currentMs);
// 3 - Send answer to clients
std::unique_ptr<DeusCore::PacketUseSkillAnswer> skillFeedBack = std::make_unique<DeusCore::PacketUseSkillAnswer>(gameObj->GetId(), p_newSkillInfos->GetId(), p_newSkillInfos->GetLaunchPosition(), p_newSkillInfos->GetLaunchTime());
DeusCore::PacketSPtr p_cellFirePacket = std::shared_ptr<CellFirePacket>(new CellFirePacket(cellId, gameObj->GetId(), std::move(skillFeedBack)));
DeusCore::EventManagerHandler::Instance()->QueueEvent(m_gameId, 0, p_cellFirePacket);
}
}
m_cellLock.unlock(); // <----------- UNLOCK
DeusCore::Logger::Instance()->Log(m_name, "End skill request");
}
//-------------------------------------------------------------------------------------------------------------
Id GameLogicServer::GetCellIdOfGameObject(Id objectId)
{
Id cellId = 0; // 0 = error, ids start at 1
m_cellLock.lock(); // <-----------LOCK
for (auto& cellGameObjects : m_cellsGameObjects)
{
const auto& gameObjIt = cellGameObjects.second.find(objectId);
if (gameObjIt != cellGameObjects.second.end())
{
cellId = cellGameObjects.first;
m_cellLock.unlock();
return cellId;
}
}
m_cellLock.unlock(); // <-----------UNLOCK
return cellId;
}
//-------------------------------------------------------------------------------------------------------------
void GameLogicServer::GetGameObjectOnChangeCells(Id playerId, Id cellLeavedId, Id cellEnteredId, std::vector<std::shared_ptr<const GameObject>>& objectInCellsLeft, std::vector<std::shared_ptr<const GameObject>>& objectInCellsEntered)
{
// TODO : Interest management here !
// For now, we juste assert that there is 1 cell
if (cellEnteredId > 0 && cellEnteredId < NUMBER_CELLS + 1)
{
m_cellLock.lock();
for (const auto& gameObj : m_cellsGameObjects[cellEnteredId])
{
if (gameObj.second->GetId() != m_playerWithGameObject[playerId])
objectInCellsEntered.push_back(gameObj.second);
}
m_cellLock.unlock();
}
}
std::shared_ptr<GameObjectComponent> GameLogicServer::GetObjectComponent(Id clientId, Id componentId, Id& cellId)
{
std::shared_ptr<GameObject> gameObj = GetObject(clientId, cellId);
if (gameObj != nullptr)
{
m_cellLock.lock(); // <----------- LOCK
std::shared_ptr<GameObjectComponent> result = gameObj->GetComponent(componentId);
m_cellLock.unlock(); // <----------- UNLOCK
return result;
}
return nullptr;
}
std::shared_ptr<GameObject> GameLogicServer::GetObject(Id clientId, Id& cellId)
{
GameObjectId objectId = 0;
m_playersLocker.lock(); // <----------- LOCK
// Find object
if (m_playerWithGameObject.find(clientId) != m_playerWithGameObject.end())
{
objectId = m_playerWithGameObject[clientId];
}
m_playersLocker.unlock(); // <----------- UNLOCK
if (objectId > 0)
{
try
{
m_cellLock.lock(); // <----------- LOCK
for (auto& cellGameObjects : m_cellsGameObjects)
{
// Search for object
const auto& gameObjIt = cellGameObjects.second.find(objectId);
if (gameObjIt != cellGameObjects.second.end())
{
cellId = cellGameObjects.first;
m_cellLock.unlock(); // <----------- UNLOCK
return gameObjIt->second;
}
}
m_cellLock.unlock(); // <----------- UNLOCK
}
catch (const std::system_error& e)
{
DeusCore::Logger::Instance()->Log(m_name, e.what());
}
}
return nullptr;
}
}
| [
"suliac.blineau@orange.fr"
] | suliac.blineau@orange.fr |
cfdf20086ef0ce54446bf79273a34db4ea99c8c4 | 48fed430795c99c8b23daf8c2f9a86fb51358328 | /templatemethod/basewater.h | 06b0bf5209f6f1398403dab7eb838d2b8080d643 | [] | no_license | jundahzijone/design_pattern | e31ae435e4567e82141ce6d50e863de983b151dc | d030f19ea0490bd40c12c2f6f14aca8f63c1c315 | refs/heads/master | 2021-01-10T09:28:33.430396 | 2016-04-06T06:25:35 | 2016-04-06T06:25:35 | 55,578,439 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 279 | h | #ifndef BASEWATER_H
#define BASEWATER_H
class BaseWater
{
public:
BaseWater();
void prepareRecipe();
virtual void boilWater() final;
virtual void pourInCup()=0;
virtual void addGradient()=0;
virtual void stir() final;
};
#endif // BASEWATER_H
| [
"h659742940@126.com"
] | h659742940@126.com |
24d231b2280b8c6f06814947f2c9dea4a9c7c5d5 | 4df8055d92200482e57126b3a9243c63725e2d8e | /PAT甲级/1011. World Cup Betting (20).cpp | e8b77df5a3f4b7627adce89253d7e5101ca065e8 | [] | no_license | tekikesyo/PAT | 47afa12e0852c011b412cd494182a888fd9a67e9 | 3f8c9e960477b4cb5521a3a894a67a348093f2b5 | refs/heads/master | 2020-05-24T14:59:09.825371 | 2018-02-21T14:54:56 | 2018-02-21T14:54:56 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,262 | cpp | /*
1011. World Cup Betting (20)
With the 2010 FIFA World Cup running, football fans the world over were becoming increasingly excited as the best players from the best teams doing battles for the World Cup trophy in South Africa. Similarly, football betting fans were putting their money where their mouths were, by laying all manner of World Cup bets.
Chinese Football Lottery provided a "Triple Winning" game.
The rule of winning was simple:
first select any three of the games.
Then for each selected game, bet on one of the three possible results -- namely W for win, T for tie, and L for lose.
There was an odd assigned to each result. The winner's odd would be the product of the three odds times 65%.
For example, 3 games' odds are given as the following:
W T L
1.1 2.5 1.7
1.2 3.0 1.6
4.1 1.2 1.1
To obtain the maximum profit, one must buy W for the 3rd game, T for the 2nd game, and T for the 1st game. If each bet takes 2 yuans, then the maximum profit would be (4.1*3.0*2.5*65%-1)*2 = 37.98 yuans (accurate up to 2 decimal places).
Input
Each input file contains one test case. Each case contains the betting information of 3 games. Each game occupies a line with three distinct odds corresponding to W, T and L.
Output
For each test case, print in one line the best bet of each game, and the maximum profit accurate up to 2 decimal places. The characters and the number must be separated by one space.
Sample Input
1.1 2.5 1.7
1.2 3.0 1.6
4.1 1.2 1.1
Sample Output
T T W 37.98
*/
/*
题目大意:简单模拟。
给出三场比赛以及每场比赛的W、T、L的赔率,选取每一场比赛中赔率最大的三个数a b c,
先输出三行各自选择的是W、T、L中的哪一个,然后根据计算公式 (a * b * c * 0.65 – 1) * 2 得出最大收益。
*/
#include <cstdio>
#include <iostream>
#include <string>
using namespace std;
int main() {
char c[4] = {"WTL"};
double ans = 1.0;
for(int i = 0; i < 3; i++) {
double maxvalue = 0.0;
int maxchar = 0;
for(int j = 0; j < 3; j++) {
double temp;
scanf("%lf", &temp);
if(maxvalue <= temp) {
maxvalue = temp;
maxchar = j;
}
}
ans *= maxvalue;
printf("%c ", c[maxchar]);
}
printf("%.2f", (ans * 0.65 - 1) * 2);
return 0;
} | [
"hushhw@sina.cn"
] | hushhw@sina.cn |
c0106c9dc13c015922d1e589aae12bd4685bf69c | f3a9174535cd7e76d1c1e0f0fa1a3929751fb48d | /SDK/PVR_ToolTip_Reload_parameters.hpp | ead855c4e41dfec3875b1b13ae60044d5d5e977f | [] | no_license | hinnie123/PavlovVRSDK | 9fcdf97e7ed2ad6c5cb485af16652a4c83266a2b | 503f8d9a6770046cc23f935f2df1f1dede4022a8 | refs/heads/master | 2020-03-31T05:30:40.125042 | 2020-01-28T20:16:11 | 2020-01-28T20:16:11 | 151,949,019 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,403 | hpp | #pragma once
// PavlovVR (Dumped by Hinnie) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function ToolTip_Reload.ToolTip_Reload_C.UserConstructionScript
struct AToolTip_Reload_C_UserConstructionScript_Params
{
};
// Function ToolTip_Reload.ToolTip_Reload_C.ReceiveBeginPlay
struct AToolTip_Reload_C_ReceiveBeginPlay_Params
{
};
// Function ToolTip_Reload.ToolTip_Reload_C.OnDestroyed_Event_1
struct AToolTip_Reload_C_OnDestroyed_Event_1_Params
{
class AActor* DestroyedActor; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function ToolTip_Reload.ToolTip_Reload_C.CustomEvent_1
struct AToolTip_Reload_C_CustomEvent_1_Params
{
};
// Function ToolTip_Reload.ToolTip_Reload_C.ExecuteUbergraph_ToolTip_Reload
struct AToolTip_Reload_C_ExecuteUbergraph_ToolTip_Reload_Params
{
int EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"hsibma02@gmail.com"
] | hsibma02@gmail.com |
bfb78b1ef8b3ce707f141cf63856c6f323035222 | a589fafb7bd7d147fd7ca37902e3ea55118477c0 | /codeforces/1400/E.cpp | 20deb2464aaedaaafa59c7ce19a5545627f8d7b3 | [] | no_license | fextivity/codeforces-submissions | 01bd05fe868525e625b40068b8e1e99858b1c765 | d7d09395a8f914aaa45f450a4c1acf4e378d6bc5 | refs/heads/master | 2023-02-03T17:23:10.906023 | 2017-11-10T14:17:00 | 2020-12-23T02:56:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 578 | cpp | #include <bits/stdc++.h>
using namespace std;
#define endl '\n'
int n;
int a[5005];
int cal(int l, int r, int val){
if (l > r){
return 0;
}
int mn = 1000000007, idx = 0;
for (int i = l; i <= r; i++){
if (a[i] < mn){
mn = a[i];
idx = i;
}
}
return min(r - l + 1, cal(l, idx - 1, mn) + cal(idx + 1, r, mn) + mn - val);
}
signed main(){
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
cin >> n;
for (int i = 0; i < n; i++){
cin >> a[i];
}
cout << cal(0, n - 1, 0);
} | [
"trxbach135@gmail.com"
] | trxbach135@gmail.com |
d1e496823f68d6680abe0bfdb1339bba5099a845 | 11351870905c52454934b23b27ace5e3306c4107 | /NHSPC17/a/1.cpp | 27113e5198d83c43c59887a34818e1fa45c224db | [] | no_license | IvanAli/ACMICPC2017Training | 65cbe9a47788ab38026134dfe41ef7132801d8c5 | 0a274f41d9b4300fdfbc9160cd171c5edf265cbc | refs/heads/master | 2021-08-29T15:42:24.789100 | 2017-12-14T05:49:03 | 2017-12-14T05:49:03 | 114,207,562 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 448 | cpp | #include <bits/stdc++.h>
#define fst first
#define snd second
#define pb push_back
#define eb emplace_back
#define mt make_tuple
using namespace std;
const int N = 100005;
int T;
int n, m;
int main() {
scanf("%d", &T);
for (int tc = 0; tc < T; tc++) {
scanf("%d%d", &n, &m);
long long ans = 0;
for (int i = 0; i < n; i++) {
int foo; scanf("%d", &foo);
if (foo % m) ans += m - (foo % m);
}
printf("%lld\n", ans);
}
return 0;
} | [
"ivanali@outlook.com"
] | ivanali@outlook.com |
430e36721f9ba4c13d330a3900c578dafe071770 | 59faa32eea7914fb62dafea88e3ceb277a1d832c | /Greedy Snake.cpp | 644fd6a952b3409eefffdba3409c57f2a9b0ce37 | [] | no_license | qiaofengmarco/Greedy-Snake | aeada0ef5cf1c2a14394177824055f6ae00398bc | dc21b5083325347af546e131d34bc6542aff1641 | refs/heads/master | 2021-01-19T12:12:02.156572 | 2017-04-12T08:11:14 | 2017-04-12T08:11:14 | 88,026,522 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 340 | cpp | #include<iostream>
#include<cstdlib>
#include<ctime>
#include<conio.h>
#include<Windows.h>
#include"Snake.h"
#include"Environment.h"
#include"Game.h"
using namespace std;
int main()
{
Game Game1;
while (true)
{
Game1.Play();
if (Game1.End())
{
Game1.Show();
break;
}
}
system("pause");
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
334ea5cc7f14af8a8435755c616118f64a719ac9 | b3e23215f26e1b2b5df70fd30dc61bd7e44822e2 | /hackathon/XuanZhao/dynamicApp2/app2/fastmarching_tree.h | a24bb0b04a30510c737d307c7aa1ee96021b9279 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | ruanzongcai/vaa3d_tools | 16ce8923eb73b10a7c94dc034085c4de3def3904 | 6cd87b867be8d6ce887b463506b420c1cf45f212 | refs/heads/master | 2023-01-12T09:34:22.534606 | 2020-11-12T21:04:04 | 2020-11-12T21:07:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 49,575 | h | //last change: by PHC, 2013-02-13. adjust memory allocation to make it more robust
/*****************************************************************
* file : fastmarching_tree.h, Hang Xiao, Jan 18, 2012
*
* fastmarching_tree
* fastmarching_tracing
*
* **************************************************************/
#ifndef __FAST_MARCHING_TREE_H__
#define __FAST_MARCHING_TREE_H__
#include <cstdlib>
#include <cmath>
#include <vector>
#include <map>
#include <iostream>
#include <QString>
#include "stackutil.h"
#include "my_surf_objs.h"
#include "heap.h"
#include "upwind_solver.h"
#include "fastmarching_macro.h"
#include "volimg_proc_declare.h"
#include "hierarchy_prune.h"
using namespace std;
#ifndef ABS
#define ABS(x) ((x) > 0 ? (x) : (-(x)))
#endif
#ifndef MAX
#define MAX(x,y) ((x) > (y) ? (x) : (y))
#endif
#ifndef MIN
#define MIN(x,y) ((x) < (y) ? (x) : (y))
#endif
struct HeapElemXX : public HeapElem
{
MyMarker * parent_marker;
HeapElemXX(long _ind, double _value, MyMarker * _parent_marker) : HeapElem(_ind, _value)
{
parent_marker = _parent_marker;
}
};
/*********************************************************************
* Function : fastmarching_linear_tree
*
* Features :
* 1. Create fast marcing tree from root marker only
* 2. Background (intensity less than bkg_thresh) will be ignored.
* 3. The distance is the sum of intensity ***
*
* Input : root root marker
* inimg1d original 8bit image
*
* Output : tree output swc
* phi the distance for each pixels
* *******************************************************************/
template<class T> bool fastmarching_linear_tree(MyMarker root, T * inimg1d, vector<MyMarker*> &outtree, int sz0, int sz1, int sz2, int cnn_type = 3, double bkg_thresh = 1)
{
enum{ALIVE = -1, TRIAL = 0, FAR = 1};
long tol_sz = sz0 * sz1 * sz2;
long sz01 = sz0 * sz1;
//int cnn_type = 3; // ?
float * phi = new float[tol_sz]; for(long i = 0; i < tol_sz; i++){phi[i] = INF;}
long * parent = new long[tol_sz]; for(long i = 0; i < tol_sz; i++) parent[i] = i; // each pixel point to itself at the beginning
// GI parameter min_int, max_int, li
double max_int = 0; // maximum intensity, used in GI
double min_int = INF;
for(long i = 0; i < tol_sz; i++)
{
if(inimg1d[i] > max_int) max_int = inimg1d[i];
if(inimg1d[i] < min_int) min_int = inimg1d[i];
}
max_int -= min_int;
double li = 10;
// initialization
char * state = new char[tol_sz];
for(long i = 0; i < tol_sz; i++) state[i] = FAR;
// init state and phi for root
int rootx = root.x + 0.5;
int rooty = root.y + 0.5;
int rootz = root.z + 0.5;
long root_ind = rootz*sz01 + rooty*sz0 + rootx;
state[root_ind] = ALIVE;
phi[root_ind] = 0.0;
BasicHeap<HeapElemX> heap;
map<long, HeapElemX*> elems;
// init heap
{
long index = root_ind;
HeapElemX *elem = new HeapElemX(index, phi[index]);
elem->prev_ind = index;
heap.insert(elem);
elems[index] = elem;
}
// loop
int time_counter = 1;
double process1 = 0;
while(!heap.empty())
{
double process2 = (time_counter++)*10000.0/tol_sz;
if(process2 - process1 >= 1)
{
cout<<"\r"<<((int)process2)/100.0<<"%";cout.flush(); process1 = process2;
}
HeapElemX* min_elem = heap.delete_min();
elems.erase(min_elem->img_ind);
long min_ind = min_elem->img_ind;
long prev_ind = min_elem->prev_ind;
delete min_elem;
parent[min_ind] = prev_ind;
state[min_ind] = ALIVE;
int i = min_ind % sz0;
int j = (min_ind/sz0) % sz1;
int k = (min_ind/sz01) % sz2;
int w, h, d;
for(int kk = -1; kk <= 1; kk++)
{
d = k+kk;
if(d < 0 || d >= sz2) continue;
for(int jj = -1; jj <= 1; jj++)
{
h = j+jj;
if(h < 0 || h >= sz1) continue;
for(int ii = -1; ii <= 1; ii++)
{
w = i+ii;
if(w < 0 || w >= sz0) continue;
int offset = ABS(ii) + ABS(jj) + ABS(kk);
if(offset == 0 || offset > cnn_type) continue;
double factor = (offset == 1) ? 1.0 : ((offset == 2) ? 1.414214 : ((offset == 3) ? 1.732051 : 0.0));
long index = d*sz01 + h*sz0 + w;
if(inimg1d[index] <= bkg_thresh) continue;
if(state[index] != ALIVE)
{
double new_dist = phi[min_ind] + (1.0 - (inimg1d[index] - min_ind)/max_int)*1000.0;
long prev_ind = min_ind;
if(state[index] == FAR)
{
phi[index] = new_dist;
HeapElemX * elem = new HeapElemX(index, phi[index]);
elem->prev_ind = prev_ind;
heap.insert(elem);
elems[index] = elem;
state[index] = TRIAL;
}
else if(state[index] == TRIAL)
{
if(phi[index] > new_dist)
{
phi[index] = new_dist;
HeapElemX * elem = elems[index];
heap.adjust(elem->heap_id, phi[index]);
elem->prev_ind = prev_ind;
}
}
}
}
}
}
}
// save current swc tree
if(1)
{
int i = -1, j = -1, k = -1;
map<long, MyMarker*> tmp_map;
for(long ind = 0; ind < tol_sz; ind++)
{
i++; if(i%sz0 == 0){i=0;j++; if(j%sz1 == 0) {j=0; k++;}}
if(state[ind] != ALIVE) continue;
MyMarker * marker = new MyMarker(i,j,k);
tmp_map[ind] = marker;
outtree.push_back(marker);
}
i=-1; j = -1; k = -1;
for(long ind = 0; ind < tol_sz; ind++)
{
i++; if(i%sz0 == 0){i=0; j++; if(j%sz1==0){j=0; k++;}}
if(state[ind] != ALIVE) continue;
long ind2 = parent[ind];
MyMarker * marker1 = tmp_map[ind];
MyMarker * marker2 = tmp_map[ind2];
if(marker1 == marker2) marker1->parent = 0;
else marker1->parent = marker2;
//tmp_map[ind]->parent = tmp_map[ind2];
}
}
// over
map<long, HeapElemX*>::iterator mit = elems.begin(); while(mit != elems.end()){HeapElemX * elem = mit->second; delete elem; mit++;}
if(phi){delete [] phi; phi = 0;}
if(parent){delete [] parent; parent = 0;}
if(state) {delete [] state; state = 0;}
return true;
}
/*********************************************************************
* Function : fastmarching_tree
*
* Features :
* 1. Create fast marcing tree from root marker only
* 2. Background (intensity 0) will be ignored.
* 3. Graph augumented distance is used
*
* Input : root root marker
* inimg1d original 8bit image
*
* Output : tree output swc
* phi the distance for each pixels
* *******************************************************************/
template<class T> bool fastmarching_tree(MyMarker root,
T * inimg1d,
vector<MyMarker*> &outtree,
long sz0,
long sz1,
long sz2,
int cnn_type = 3,
double bkg_thresh = 20,
bool is_break_accept = false)
{
enum{ALIVE = -1, TRIAL = 0, FAR = 1};
long tol_sz = sz0 * sz1 * sz2;
long sz01 = sz0 * sz1;
long i;
//int cnn_type = 3; // ?
float * phi = 0;
long * parent = 0;
char * state = 0;
try
{
phi = new float[tol_sz];
parent = new long[tol_sz];
state = new char[tol_sz];
for(i = 0; i < tol_sz; i++)
{
phi[i] = INF;
parent[i] = i; // each pixel point to itself at the statements beginning
state[i] = FAR;
}
}
catch (...)
{
cout << "********* Fail to allocate memory. quit fastmarching_tree()." << endl;
if (phi) {delete []phi; phi=0;}
if (parent) {delete []parent; parent=0;}
if (state) {delete []state; state=0;}
return false;
}
// GI parameter min_int, max_int, li
double max_int = 0; // maximum intensity, used in GI
double min_int = INF;
for(i = 0; i < tol_sz; i++)
{
if (inimg1d[i] > max_int) max_int = inimg1d[i];
else if (inimg1d[i] < min_int) min_int = inimg1d[i];
}
max_int -= min_int;
double li = 10;
// initialization
// init state and phi for root
long rootx = root.x + 0.5;
long rooty = root.y + 0.5;
long rootz = root.z + 0.5;
long root_ind = rootz*sz01 + rooty*sz0 + rootx;
state[root_ind] = ALIVE;
phi[root_ind] = 0.0;
BasicHeap<HeapElemX> heap;
map<long, HeapElemX*> elems;
// init heap
{
long index = root_ind;
HeapElemX *elem = new HeapElemX(index, phi[index]);
elem->prev_ind = index;
heap.insert(elem);
elems[index] = elem;
}
// loop
int time_counter = 1;
double process1 = 0;
while(!heap.empty())
{
double process2 = (time_counter++)*10000.0/tol_sz;
//cout<<"\r"<<((int)process2)/100.0<<"%";cout.flush();
if(process2 - process1 >= 1)
{
cout<<"\r"<<((int)process2)/100.0<<"%";cout.flush(); process1 = process2;
}
HeapElemX* min_elem = heap.delete_min();
elems.erase(min_elem->img_ind);
long min_ind = min_elem->img_ind;
long prev_ind = min_elem->prev_ind;
delete min_elem;
parent[min_ind] = prev_ind;
state[min_ind] = ALIVE;
int i = min_ind % sz0;
int j = (min_ind/sz0) % sz1;
int k = (min_ind/sz01) % sz2;
int w, h, d;
for(int kk = -1; kk <= 1; kk++)
{
d = k+kk;
if(d < 0 || d >= sz2) continue;
for(int jj = -1; jj <= 1; jj++)
{
h = j+jj;
if(h < 0 || h >= sz1) continue;
for(int ii = -1; ii <= 1; ii++)
{
w = i+ii;
if(w < 0 || w >= sz0) continue;
int offset = ABS(ii) + ABS(jj) + ABS(kk);
if(offset == 0 || offset > cnn_type) continue;
double factor = (offset == 1) ? 1.0 : ((offset == 2) ? 1.414214 : ((offset == 3) ? 1.732051 : 0.0));
long index = d*sz01 + h*sz0 + w;
if (is_break_accept)
{
if(inimg1d[index] <= bkg_thresh &&
inimg1d[min_ind] <= bkg_thresh)
continue;
}
else
{
if(inimg1d[index] <= bkg_thresh)
continue;
}
if(state[index] != ALIVE)
{
double new_dist = phi[min_ind] + (GI(index) + GI(min_ind))*factor*0.5;
long prev_ind = min_ind;
if(state[index] == FAR)
{
phi[index] = new_dist;
HeapElemX * elem = new HeapElemX(index, phi[index]);
elem->prev_ind = prev_ind;
heap.insert(elem);
elems[index] = elem;
state[index] = TRIAL;
}
else if(state[index] == TRIAL)
{
if (phi[index] > new_dist)
{
phi[index] = new_dist;
HeapElemX * elem = elems[index];
heap.adjust(elem->heap_id, phi[index]);
elem->prev_ind = prev_ind;
}
}
}
}
}
}
}
// save current swc tree
if (1)
{
int i = -1, j = -1, k = -1;
map<long, MyMarker*> tmp_map;
for(long ind = 0; ind < tol_sz; ind++)
{
i++; if(i%sz0 == 0){i=0;j++; if(j%sz1 == 0) {j=0; k++;}}
if(state[ind] != ALIVE) continue;
MyMarker * marker = new MyMarker(i,j,k);
tmp_map[ind] = marker;
outtree.push_back(marker);
}
i=-1; j = -1; k = -1;
for(long ind = 0; ind < tol_sz; ind++)
{
i++; if(i%sz0 == 0){i=0; j++; if(j%sz1==0){j=0; k++;}}
if(state[ind] != ALIVE) continue;
long ind2 = parent[ind];
MyMarker * marker1 = tmp_map[ind];
MyMarker * marker2 = tmp_map[ind2];
if(marker1 == marker2) marker1->parent = 0;
else marker1->parent = marker2;
//tmp_map[ind]->parent = tmp_map[ind2];
}
}
// over
map<long, HeapElemX*>::iterator mit = elems.begin();
while (mit != elems.end())
{
HeapElemX * elem = mit->second; delete elem; mit++;
}
if(phi){delete [] phi; phi = 0;}
if(parent){delete [] parent; parent = 0;}
if(state) {delete [] state; state = 0;}
return true;
}
/*********************************************************************
* Function : fastmarching_tree
*
* Features :
* 1. Create fast marcing tree from root marker
* 2. Background (intensity 0) will be ignored.
* 3. Euclidean distance is used
*
* Input : root root marker
* inimg1d original 8bit image
*
* Output : tree output swc
* phi the distance for each pixels
* *******************************************************************/
// inimg1d is binary
template<class T> bool fastmarching_tree_old(MyMarker root, T * inimg1d, vector<MyMarker*> &tree, double * & phi, int sz0, int sz1, int sz2)
{
enum{ALIVE = -1, TRIAL = 0, FAR = 1};
long tol_sz = sz0 * sz1 * sz2;
long sz01 = sz0 * sz1;
int rootx = (int)(root.x + 0.5);
int rooty = (int)(root.y + 0.5);
int rootz = (int)(root.z + 0.5);
long root_ind = rootz*sz01 + rooty*sz0 + rootx;
if(inimg1d[root_ind] == 0){cerr<<"the root position is not in forground"<<endl; return false;}
int cnn_type = 1; // cnn_type should be 1
phi = new double[tol_sz];
for(long i = 0; i < tol_sz; i++) phi[i] = INF;
// initialization
char * state = new char[tol_sz];
for(long i = 0; i < tol_sz; i++) state[i] = FAR;
state[root_ind] = ALIVE; phi[root_ind] = 0.0;
BasicHeap<HeapElemXX> heap;
map<long, HeapElemXX*> elems;
// init state around root
int i = rootx, j = rooty, k = rootz;
MyMarker * root_node = new MyMarker(i,j,k);
tree.push_back(root_node);
int w, h, d;
for(int kk = -1; kk <= 1; kk++)
{
d = k + kk;
if(d < 0 || d >= sz2) continue;
for(int jj = -1; jj <= 1; jj++)
{
h = j + jj;
if(h < 0 || h >= sz1) continue;
for(int ii = -1; ii <= 1; ii++)
{
w = i + ii;
if(w < 0 || w >= sz0) continue;
int offset = ABS(ii) + ABS(jj) + ABS(kk);
if(offset == 0 || offset > cnn_type) continue;
long index = d*sz01 + h*sz0 + w;
if(inimg1d[index] == 0) continue;
if(state[index] == FAR)
{
state[index] = TRIAL;
double u1 = INF;
double u2 = INF;
double u3 = INF;
if(w - 1 >= 0 && state[index - 1] == ALIVE) u1 = u1 < phi[index - 1]? u1: phi[index -1 ];
if(w + 1 < sz0 && state[index + 1] == ALIVE) u1 = u1 < phi[index + 1] ? u1: phi[index + 1];
if(h - 1 >= 0 && state[index - sz0] == ALIVE) u2 = u2 < phi[index - sz0] ? u2:phi[index-sz0];
if(h + 1 < sz1 && state[index + sz0] == ALIVE) u2 = u2 < phi[index + sz0] ? u2:phi[index + sz0];
if(d - 1 >=0 && state[index - sz0*sz1] == ALIVE) u3 = u3 < phi[index - sz0*sz1] ? u3: phi[index -sz0*sz1];
if(d + 1 < sz2 && state[index + sz0*sz1] == ALIVE) u3 = u3 < phi[index + sz0*sz1] ? u3: phi[index + sz0*sz1];
vector<double> parameters;
if( u1 != INF) parameters.push_back(u1);
if( u2 != INF) parameters.push_back(u2);
if( u3 != INF) parameters.push_back(u3);
phi[index] = upwind_solver(parameters);
HeapElemXX *elem = new HeapElemXX(index, phi[index], root_node);
heap.insert(elem);
elems[index] = elem;
}
}
}
}
// loop
int time_counter = 1;
int process1 = 0, process2 = 0;
while(!heap.empty())
{
double process2 = (time_counter++)*1000.0/tol_sz;
if(process2 - process1 >= 1)
{
cout<<"\r"<<((int)process2)/10.0<<"%";cout.flush(); process1 = process2;
}
HeapElemXX* min_elem = heap.delete_min();
elems.erase(min_elem->img_ind);
long min_ind = min_elem->img_ind;
state[min_ind] = ALIVE;
int i = min_ind % sz0;
int j = (min_ind/sz0) % sz1;
int k = (min_ind/sz01) % sz2;
MyMarker * cur_marker = new MyMarker(i,j,k);
cur_marker->parent = min_elem->parent_marker;
tree.push_back(cur_marker);
delete min_elem;
int w, h, d;
for(int kk = -1; kk <= 1; kk++)
{
d = k+kk;
if(d < 0 || d >= sz2) continue;
for(int jj = -1; jj <= 1; jj++)
{
h = j+jj;
if(h < 0 || h >= sz1) continue;
for(int ii = -1; ii <= 1; ii++)
{
w = i+ii;
if(w < 0 || w >= sz0) continue;
int offset = ABS(ii) + ABS(jj) + ABS(kk);
if(offset == 0 || offset > cnn_type) continue;
long index = d*sz01 + h*sz0 + w;
if(inimg1d[index] == 0) continue;
if(state[index] != ALIVE)
{
double u1 = INF;
double u2 = INF;
double u3 = INF;
if(w - 1 >= 0 && state[index - 1] == ALIVE) u1 = u1 < phi[index - 1]? u1: phi[index -1 ];
if(w + 1 < sz0 && state[index + 1] == ALIVE) u1 = u1 < phi[index + 1] ? u1: phi[index + 1];
if(h - 1 >= 0 && state[index - sz0] == ALIVE) u2 = u2 < phi[index - sz0] ? u2:phi[index-sz0];
if(h + 1 < sz1 && state[index + sz0] == ALIVE) u2 = u2 < phi[index + sz0] ? u2:phi[index + sz0];
if(d - 1 >=0 && state[index - sz0*sz1] == ALIVE) u3 = u3 < phi[index - sz0*sz1] ? u3: phi[index -sz0*sz1];
if(d + 1 < sz2 && state[index + sz0*sz1] == ALIVE) u3 = u3 < phi[index + sz0*sz1] ? u3: phi[index + sz0*sz1];
vector<double> parameters;
if( u1 != INF) parameters.push_back(u1);
if( u2 != INF) parameters.push_back(u2);
if( u3 != INF) parameters.push_back(u3);
double solver_result = upwind_solver(parameters);
if(state[index] == FAR)
{
phi[index] = solver_result;
HeapElemXX * elem = new HeapElemXX(index, phi[index], cur_marker);
heap.insert(elem);
elems[index] = elem;
state[index] = TRIAL;
}
else if(state[index] == TRIAL)
{
if(phi[index] > solver_result)
{
phi[index] = solver_result;
HeapElemXX * elem = elems[index];
heap.adjust(elem->heap_id, phi[index]);
elem->parent_marker = cur_marker;
}
}
}
}
}
}
}
for(long i = 0; i < tol_sz; i++) if(phi[i] == INF) phi[i] = 0;
if(state) {delete [] state; state = 0;}
return true;
}
/******************************************************************************
* Fast marching based tree construction
* 1. use graph augmented distance (GD)
* 2. stop when all target marker are marched
*
* Input : root root marker
* target the set of target markers
* inimg1d original input image
*
* Output : outtree output tracing result
*
* Notice :
* 1. the input pixel number should not be larger than 2G if sizeof(long) == 4
* 2. target markers should not contain root marker
* 3. the root marker in outswc, is point to itself
* 4. the cnn_type is default 3
* *****************************************************************************/
template<class T> bool fastmarching_tree(MyMarker root, vector<MyMarker> &target, T * inimg1d, vector<MyMarker*> &outtree, long sz0, long sz1, long sz2, int cnn_type = 3)
{
enum{ALIVE = -1, TRIAL = 0, FAR = 1};
long tol_sz = sz0 * sz1 * sz2;
long sz01 = sz0 * sz1;
//int cnn_type = 3; // ?
//float * phi = new float[tol_sz]; for(long i = 0; i < tol_sz; i++){phi[i] = INF;}
//long * parent = new long[tol_sz]; for(long i = 0; i < tol_sz; i++) parent[i] = i; // each pixel point to itself at the beginning
long i;
float * phi = 0;
long * parent = 0;
char * state = 0;
try
{
phi = new float[tol_sz];
parent = new long[tol_sz];
state = new char[tol_sz];
for(i = 0; i < tol_sz; i++)
{
phi[i] = INF;
parent[i] = i; // each pixel point to itself at the statements beginning
state[i] = FAR;
}
}
catch (...)
{
cout << "********* Fail to allocate memory. quit fastmarching_tree()." << endl;
if (phi) {delete []phi; phi=0;}
if (parent) {delete []parent; parent=0;}
if (state) {delete []state; state=0;}
return false;
}
// GI parameter min_int, max_int, li
double max_int = 0; // maximum intensity, used in GI
double min_int = INF;
for(long i = 0; i < tol_sz; i++)
{
if(inimg1d[i] > max_int) max_int = inimg1d[i];
if(inimg1d[i] < min_int) min_int = inimg1d[i];
}
max_int -= min_int;
double li = 10;
// initialization
//char * state = new char[tol_sz];
//for(long i = 0; i < tol_sz; i++) state[i] = FAR;
// init state and phi for root
int rootx = root.x + 0.5;
int rooty = root.y + 0.5;
int rootz = root.z + 0.5;
long root_ind = rootz*sz01 + rooty*sz0 + rootx;
state[root_ind] = ALIVE;
phi[root_ind] = 0.0;
vector<long> target_inds;
for(long t = 0; t < target.size(); t++) {
int i = target[t].x + 0.5;
int j = target[t].y + 0.5;
int k = target[t].z + 0.5;
long ind = k*sz01 + j*sz0 + i;
target_inds.push_back(ind);
//if(ind == root_ind) {cerr<<"please remove root marker from target markers"<<endl; exit(0);}
}
BasicHeap<HeapElemX> heap;
map<long, HeapElemX*> elems;
// init heap
{
long index = root_ind;
HeapElemX *elem = new HeapElemX(index, phi[index]);
elem->prev_ind = index;
heap.insert(elem);
elems[index] = elem;
}
// loop
int time_counter = 1;
double process1 = 0;
while(!heap.empty())
{
double process2 = (time_counter++)*100000.0/tol_sz;
if(process2 - process1 >= 1)
{
cout<<"\r"<<((int)process2)/1000.0<<"%";cout.flush(); process1 = process2;
bool is_break = true; for(int t = 0; t < target_inds.size(); t++){long tind = target_inds[t]; if(parent[tind] == tind && tind != root_ind) {is_break = false; break;}}
if(is_break) break;
}
HeapElemX* min_elem = heap.delete_min();
elems.erase(min_elem->img_ind);
long min_ind = min_elem->img_ind;
long prev_ind = min_elem->prev_ind;
delete min_elem;
parent[min_ind] = prev_ind;
state[min_ind] = ALIVE;
int i = min_ind % sz0;
int j = (min_ind/sz0) % sz1;
int k = (min_ind/sz01) % sz2;
int w, h, d;
for(int kk = -1; kk <= 1; kk++)
{
d = k+kk;
if(d < 0 || d >= sz2) continue;
for(int jj = -1; jj <= 1; jj++)
{
h = j+jj;
if(h < 0 || h >= sz1) continue;
for(int ii = -1; ii <= 1; ii++)
{
w = i+ii;
if(w < 0 || w >= sz0) continue;
int offset = ABS(ii) + ABS(jj) + ABS(kk);
if(offset == 0 || offset > cnn_type) continue;
double factor = (offset == 1) ? 1.0 : ((offset == 2) ? 1.414214 : ((offset == 3) ? 1.732051 : 0.0));
long index = d*sz01 + h*sz0 + w;
if(state[index] != ALIVE)
{
double new_dist = phi[min_ind] + (GI(index) + GI(min_ind))*factor*0.5;
long prev_ind = min_ind;
if(state[index] == FAR)
{
phi[index] = new_dist;
HeapElemX * elem = new HeapElemX(index, phi[index]);
elem->prev_ind = prev_ind;
heap.insert(elem);
elems[index] = elem;
state[index] = TRIAL;
}
else if(state[index] == TRIAL)
{
if(phi[index] > new_dist)
{
phi[index] = new_dist;
HeapElemX * elem = elems[index];
heap.adjust(elem->heap_id, phi[index]);
elem->prev_ind = prev_ind;
}
}
}
}
}
}
}
// save current swc tree
if(1)
{
int i = -1, j = -1, k = -1;
map<long, MyMarker*> tmp_map;
for(long ind = 0; ind < tol_sz; ind++)
{
i++; if(i%sz0 == 0){i=0;j++; if(j%sz1 == 0) {j=0; k++;}}
if(state[ind] != ALIVE) continue;
MyMarker * marker = new MyMarker(i,j,k);
tmp_map[ind] = marker;
outtree.push_back(marker);
}
i=-1; j = -1; k = -1;
for(long ind = 0; ind < tol_sz; ind++)
{
i++; if(i%sz0 == 0){i=0; j++; if(j%sz1==0){j=0; k++;}}
if(state[ind] != ALIVE) continue;
long ind2 = parent[ind];
MyMarker * marker1 = tmp_map[ind];
MyMarker * marker2 = tmp_map[ind2];
if(marker1 == marker2) marker1->parent = 0;
else marker1->parent = marker2;
//tmp_map[ind]->parent = tmp_map[ind2];
}
}
// over
map<long, HeapElemX*>::iterator mit = elems.begin(); while(mit != elems.end()){HeapElemX * elem = mit->second; delete elem; mit++;}
if(phi){delete [] phi; phi = 0;}
if(parent){delete [] parent; parent = 0;}
if(state) {delete [] state; state = 0;}
return true;
}
/******************************************************************************
* Fast marching based manual tracing, with root marker and a set of target marker
*
* Input : root root marker
* target the set of target markers
* inimg1d original input image
*
* Output : outswc output tracing result
* phi finial distance value for each pixel [todo : replace INF to 0]
*
* Notice :
* 1. the input pixel number should not be larger than 2G if sizeof(long) == 4
* 2. target markers should not contain root marker
* 3. the root marker in outswc, is point to itself
* 4. the cnn_type is default 3
* *****************************************************************************/
template<class T1, class T2> bool fastmarching_tracing(MyMarker root, vector<MyMarker> &target, T1 * inimg1d, vector<MyMarker*> &outswc, T2 * &phi, int sz0, int sz1, int sz2, int cnn_type = 3)
{
int rootx = root.x + 0.5;
int rooty = root.y + 0.5;
int rootz = root.z + 0.5;
if(rootx < 0 || rootx >= sz0 || rooty < 0 || rooty >= sz1 || rootz < 0 || rootz >= sz2)
{
cerr<<"Invalid root marker("<<root.x<<","<<root.y<<","<<root.z<<")"<<endl; return false;
}
enum{ALIVE = -1, TRIAL = 0, FAR = 1};
long tol_sz = sz0 * sz1 * sz2;
long sz01 = sz0 * sz1;
//int cnn_type = 3; // ?
if(phi == 0) phi = new T2[tol_sz]; for(long i = 0; i < tol_sz; i++){phi[i] = INF;}
long * parent = new long[tol_sz]; for(long i = 0; i < tol_sz; i++) parent[i] = i; // each pixel point to itself at the beginning
// GI parameter min_int, max_int, li
double max_int = 0; // maximum intensity, used in GI
double min_int = INF;
for(long i = 0; i < tol_sz; i++)
{
if(inimg1d[i] > max_int) max_int = inimg1d[i];
if(inimg1d[i] < min_int) min_int = inimg1d[i];
}
max_int -= min_int;
double li = 10;
// initialization
char * state = new char[tol_sz];
for(long i = 0; i < tol_sz; i++) state[i] = FAR;
long root_ind = rootz*sz01 + rooty*sz0 + rootx;
state[root_ind] = ALIVE;
phi[root_ind] = 0.0;
vector<long> target_inds;
for(long t = 0; t < target.size(); t++) {
int i = target[t].x + 0.5;
int j = target[t].y + 0.5;
int k = target[t].z + 0.5;
if(i < 0 || i >= sz0 || j < 0 || j >= sz1 || k < 0 || k >= sz2)
{
cerr<<"t = "<<t+1<<", invalid target marker("<<target[t].x<<","<<target[t].y<<","<<target[t].z<<")"<<endl;
continue;
}
long ind = k*sz01 + j*sz0 + i;
target_inds.push_back(ind);
//if(ind == root_ind) {cerr<<"please remove root marker from target markers"<<endl; exit(0);}
}
BasicHeap<HeapElemX> heap;
map<long, HeapElemX*> elems;
// init heap
{
long index = root_ind;
HeapElemX *elem = new HeapElemX(index, phi[index]);
elem->prev_ind = index;
heap.insert(elem);
elems[index] = elem;
}
// loop
int time_counter = 1;
double process1 = 0;
while(!heap.empty())
{
double process2 = (time_counter++)*100000.0/tol_sz;
if(process2 - process1 >= 1)
{
cout<<"\r"<<((int)process2)/1000.0<<"%";cout.flush(); process1 = process2;
bool is_break = true; for(int t = 0; t < target_inds.size(); t++){long tind = target_inds[t]; if(parent[tind] == tind && tind != root_ind) {is_break = false; break;}}
if(is_break) break;
}
HeapElemX* min_elem = heap.delete_min();
elems.erase(min_elem->img_ind);
long min_ind = min_elem->img_ind;
long prev_ind = min_elem->prev_ind;
delete min_elem;
parent[min_ind] = prev_ind;
state[min_ind] = ALIVE;
int i = min_ind % sz0;
int j = (min_ind/sz0) % sz1;
int k = (min_ind/sz01) % sz2;
int w, h, d;
for(int kk = -1; kk <= 1; kk++)
{
d = k+kk;
if(d < 0 || d >= sz2) continue;
for(int jj = -1; jj <= 1; jj++)
{
h = j+jj;
if(h < 0 || h >= sz1) continue;
for(int ii = -1; ii <= 1; ii++)
{
w = i+ii;
if(w < 0 || w >= sz0) continue;
int offset = ABS(ii) + ABS(jj) + ABS(kk);
if(offset == 0 || offset > cnn_type) continue;
double factor = (offset == 1) ? 1.0 : ((offset == 2) ? 1.414214 : ((offset == 3) ? 1.732051 : 0.0));
long index = d*sz01 + h*sz0 + w;
if(state[index] != ALIVE)
{
double new_dist = phi[min_ind] + (GI(index) + GI(min_ind))*factor*0.5;
long prev_ind = min_ind;
if(state[index] == FAR)
{
phi[index] = new_dist;
HeapElemX * elem = new HeapElemX(index, phi[index]);
elem->prev_ind = prev_ind;
heap.insert(elem);
elems[index] = elem;
state[index] = TRIAL;
}
else if(state[index] == TRIAL)
{
if(phi[index] > new_dist)
{
phi[index] = new_dist;
HeapElemX * elem = elems[index];
heap.adjust(elem->heap_id, phi[index]);
elem->prev_ind = prev_ind;
}
}
}
}
}
}
}
// extract the tree nodes containing target markers
map<long, MyMarker *> marker_map;
for(int t = 0; t < target_inds.size(); t++)
{
long tind = target_inds[t];
long p = tind;
while(true)
{
if(marker_map.find(p) != marker_map.end()) break;
int i = p % sz0;
int j = p/sz0 % sz1;
int k = p/sz01 % sz2;
MyMarker * marker = new MyMarker(i,j,k);
marker_map[p] = marker;
if(p == parent[p])
{
assert(p == root.ind(sz0,sz01));
assert(marker_map.find(root.ind(sz0,sz01)) != marker_map.end());
break;
}
else p = parent[p];
}
}
if(marker_map.find(root.ind(sz0,sz01)) == marker_map.end())
{
cout<<"break here"<<endl;
}
map<long, MyMarker*>::iterator it = marker_map.begin();
V3DLONG in_sz[4] = {sz0, sz1, sz2, 1};
while(it != marker_map.end())
{
long tind = it->first;
MyMarker * marker = it->second;
MyMarker * parent_marker = marker_map[parent[tind]];
marker->parent = parent_marker;
marker->radius = markerRadius(inimg1d, in_sz, *marker, 20);
outswc.push_back(marker);
it++;
}
map<long, HeapElemX*>::iterator mit = elems.begin();
while(mit != elems.end()){HeapElemX * elem = mit->second; delete elem; mit++;}
if(parent){delete [] parent; parent = 0;}
if(state) {delete [] state; state = 0;}
return true;
}
/*********************************************************************
* Function : fastmarching_tree_constraint
*
* Features :
* 1. Create fast marcing tree from root marker only
* 2. Background (intensity 0) will be ignored.
* 3. Graph augumented distance is used
*
* Input : root root marker
* inimg1d original 8bit image
*
* Output : tree output swc
* phi the distance for each pixels
* *******************************************************************/
template<class T> bool fastmarching_tree_constraint(MyMarker root,
T * inimg1d,
vector<MyMarker*> &outtree,
long sz0,
long sz1,
long sz2,
int cnn_type = 3,
double bkg_thresh = 20,
bool is_break_accept = false,
double length = 50)
{
enum{ALIVE = -1, TRIAL = 0, FAR = 1};
long tol_sz = sz0 * sz1 * sz2;
long sz01 = sz0 * sz1;
long i;
//int cnn_type = 3; // ?
float * phi = 0;
long * parent = 0;
char * state = 0;
float * path = 0;
try
{
phi = new float[tol_sz];
parent = new long[tol_sz];
state = new char[tol_sz];
path = new float[tol_sz];
for(i = 0; i < tol_sz; i++)
{
phi[i] = INF;
parent[i] = i; // each pixel point to itself at the statements beginning
state[i] = FAR;
path[i] = 0;
}
}
catch (...)
{
cout << "********* Fail to allocate memory. quit fastmarching_tree()." << endl;
if (phi) {delete []phi; phi=0;}
if (parent) {delete []parent; parent=0;}
if (state) {delete []state; state=0;}
if (path) {delete []path; path=0;}
return false;
}
// GI parameter min_int, max_int, li
double max_int = 0; // maximum intensity, used in GI
double min_int = INF;
for(i = 0; i < tol_sz; i++)
{
if (inimg1d[i] > max_int) max_int = inimg1d[i];
else if (inimg1d[i] < min_int) min_int = inimg1d[i];
}
max_int -= min_int;
double li = 10;
// initialization
// init state and phi for root
long rootx = root.x + 0.5;
long rooty = root.y + 0.5;
long rootz = root.z + 0.5;
long root_ind = rootz*sz01 + rooty*sz0 + rootx;
state[root_ind] = ALIVE;
phi[root_ind] = 0.0;
BasicHeap<HeapElemX> heap;
map<long, HeapElemX*> elems;
// init heap
{
long index = root_ind;
HeapElemX *elem = new HeapElemX(index, phi[index]);
elem->prev_ind = index;
heap.insert(elem);
elems[index] = elem;
}
// loop
int time_counter = 1;
double process1 = 0;
while(!heap.empty())
{
double process2 = (time_counter++)*10000.0/tol_sz;
//cout<<"\r"<<((int)process2)/100.0<<"%";cout.flush();
if(process2 - process1 >= 1)
{
cout<<"\r"<<((int)process2)/100.0<<"%";cout.flush(); process1 = process2;
}
HeapElemX* min_elem = heap.delete_min();
elems.erase(min_elem->img_ind);
long min_ind = min_elem->img_ind;
long prev_ind = min_elem->prev_ind;
delete min_elem;
parent[min_ind] = prev_ind;
state[min_ind] = ALIVE;
int i = min_ind % sz0;
int j = (min_ind/sz0) % sz1;
int k = (min_ind/sz01) % sz2;
int pi = prev_ind % sz0;
int pj = (prev_ind/sz0) % sz1;
int pk = (prev_ind/sz01) % sz2;
path[min_ind] = path[prev_ind] + dist(MyMarker(i,j,k),MyMarker(pi,pj,pk));
if(path[min_ind]>length){
while (!heap.empty()) {
HeapElemX* tmp_elem = heap.delete_min();
elems.erase(tmp_elem->img_ind);
delete tmp_elem;
}
break;
}
int w, h, d;
for(int kk = -1; kk <= 1; kk++)
{
d = k+kk;
if(d < 0 || d >= sz2) continue;
for(int jj = -1; jj <= 1; jj++)
{
h = j+jj;
if(h < 0 || h >= sz1) continue;
for(int ii = -1; ii <= 1; ii++)
{
w = i+ii;
if(w < 0 || w >= sz0) continue;
int offset = ABS(ii) + ABS(jj) + ABS(kk);
if(offset == 0 || offset > cnn_type) continue;
double factor = (offset == 1) ? 1.0 : ((offset == 2) ? 1.414214 : ((offset == 3) ? 1.732051 : 0.0));
long index = d*sz01 + h*sz0 + w;
if (is_break_accept)
{
if(inimg1d[index] <= bkg_thresh &&
inimg1d[min_ind] <= bkg_thresh)
continue;
}
else
{
if(inimg1d[index] <= bkg_thresh)
continue;
}
if(state[index] != ALIVE)
{
double new_dist = phi[min_ind] + (GI(index) + GI(min_ind))*factor*0.5;
long prev_ind = min_ind;
if(state[index] == FAR)
{
phi[index] = new_dist;
HeapElemX * elem = new HeapElemX(index, phi[index]);
elem->prev_ind = prev_ind;
heap.insert(elem);
elems[index] = elem;
state[index] = TRIAL;
}
else if(state[index] == TRIAL)
{
if (phi[index] > new_dist)
{
phi[index] = new_dist;
HeapElemX * elem = elems[index];
heap.adjust(elem->heap_id, phi[index]);
elem->prev_ind = prev_ind;
}
}
}
}
}
}
}
// save current swc tree
if (1)
{
int i = -1, j = -1, k = -1;
map<long, MyMarker*> tmp_map;
for(long ind = 0; ind < tol_sz; ind++)
{
i++; if(i%sz0 == 0){i=0;j++; if(j%sz1 == 0) {j=0; k++;}}
if(state[ind] != ALIVE) continue;
MyMarker * marker = new MyMarker(i,j,k);
tmp_map[ind] = marker;
outtree.push_back(marker);
}
i=-1; j = -1; k = -1;
for(long ind = 0; ind < tol_sz; ind++)
{
i++; if(i%sz0 == 0){i=0; j++; if(j%sz1==0){j=0; k++;}}
if(state[ind] != ALIVE) continue;
long ind2 = parent[ind];
MyMarker * marker1 = tmp_map[ind];
MyMarker * marker2 = tmp_map[ind2];
if(marker1 == marker2) marker1->parent = 0;
else marker1->parent = marker2;
//tmp_map[ind]->parent = tmp_map[ind2];
}
}
// over
map<long, HeapElemX*>::iterator mit = elems.begin();
while (mit != elems.end())
{
HeapElemX * elem = mit->second; delete elem; mit++;
}
if(phi){delete [] phi; phi = 0;}
if(parent){delete [] parent; parent = 0;}
if(state) {delete [] state; state = 0;}
if (path) {delete []path; path=0;}
return true;
}
/*********************************************************************
* Function : fastmarching_tree_line
*
* Features :
* 1. Create fast marcing tree from root marker only
* 2. Background (intensity 0) will be ignored.
* 3. Graph augumented distance is used
*
* Input : root root marker
* inimg1d original 8bit image
*
* Output : tree output swc
* phi the distance for each pixels
* *******************************************************************/
template<class T> bool fastmarching_line(MyMarker root,
T * inimg1d,
vector<MyMarker*> &outtree,
long sz0,
long sz1,
long sz2,
int cnn_type = 3,
double bkg_thresh = 20,
bool is_break_accept = false,
double length = 50)
{
is_break_accept = true;
bkg_thresh = 0;
enum{ALIVE = -1, TRIAL = 0, FAR = 1, FINAL = 2};
long tol_sz = sz0 * sz1 * sz2;
long sz01 = sz0 * sz1;
long i;
//int cnn_type = 3; // ?
float * phi = 0;
long * parent = 0;
char * state = 0;
float * path = 0;
try
{
phi = new float[tol_sz];
parent = new long[tol_sz];
state = new char[tol_sz];
path = new float[tol_sz];
for(i = 0; i < tol_sz; i++)
{
phi[i] = INF;
parent[i] = i; // each pixel point to itself at the statements beginning
state[i] = FAR;
path[i] = 0;
}
}
catch (...)
{
cout << "********* Fail to allocate memory. quit fastmarching_tree()." << endl;
if (phi) {delete []phi; phi=0;}
if (parent) {delete []parent; parent=0;}
if (state) {delete []state; state=0;}
if (path) {delete []path; path=0;}
return false;
}
// GI parameter min_int, max_int, li
double max_int = 0; // maximum intensity, used in GI
double min_int = INF;
for(i = 0; i < tol_sz; i++)
{
if (inimg1d[i] > max_int) max_int = inimg1d[i];
else if (inimg1d[i] < min_int) min_int = inimg1d[i];
}
max_int -= min_int;
double li = 10;
// initialization
// init state and phi for root
long rootx = root.x + 0.5;
long rooty = root.y + 0.5;
long rootz = root.z + 0.5;
long root_ind = rootz*sz01 + rooty*sz0 + rootx;
state[root_ind] = ALIVE;
phi[root_ind] = 0.0;
BasicHeap<HeapElemX> heap;
map<long, HeapElemX*> elems;
// init heap
{
long index = root_ind;
HeapElemX *elem = new HeapElemX(index, phi[index]);
elem->prev_ind = index;
heap.insert(elem);
elems[index] = elem;
}
int t = 1;
int stopFlag = 0;
while (stopFlag < 2) {
cout<<"t: "<<t<<endl;
stopFlag += 1;
// loop
int time_counter = 1;
double process1 = 0;
while(!heap.empty())
{
double process2 = (time_counter++)*10000.0/tol_sz;
//cout<<"\r"<<((int)process2)/100.0<<"%";cout.flush();
if(process2 - process1 >= 1)
{
cout<<"\r"<<((int)process2)/100.0<<"%";cout.flush(); process1 = process2;
}
HeapElemX* min_elem = heap.delete_min();
elems.erase(min_elem->img_ind);
long min_ind = min_elem->img_ind;
long prev_ind = min_elem->prev_ind;
delete min_elem;
parent[min_ind] = prev_ind;
state[min_ind] = ALIVE;
int i = min_ind % sz0;
int j = (min_ind/sz0) % sz1;
int k = (min_ind/sz01) % sz2;
int pi = prev_ind % sz0;
int pj = (prev_ind/sz0) % sz1;
int pk = (prev_ind/sz01) % sz2;
path[min_ind] = path[prev_ind] + dist(MyMarker(i,j,k),MyMarker(pi,pj,pk));
if((i<1 || i>=sz0-1 || j<1 || j>=sz1-1 || k<1 || k>=sz2-1) && t != 1){
stopFlag = 2;
while (!heap.empty()) {
HeapElemX* tmp_elem = heap.delete_min();
elems.erase(tmp_elem->img_ind);
delete tmp_elem;
}
break;
}
if(path[min_ind]>length){
stopFlag = 0;
while (!heap.empty()) {
HeapElemX* tmp_elem = heap.delete_min();
elems.erase(tmp_elem->img_ind);
delete tmp_elem;
}
break;
}
// qDebug()<<"path[min_ind]: "<<path[min_ind];
int w, h, d;
for(int kk = -1; kk <= 1; kk++)
{
d = k+kk;
if(d < 0 || d >= sz2) continue;
for(int jj = -1; jj <= 1; jj++)
{
h = j+jj;
if(h < 0 || h >= sz1) continue;
for(int ii = -1; ii <= 1; ii++)
{
w = i+ii;
if(w < 0 || w >= sz0) continue;
int offset = ABS(ii) + ABS(jj) + ABS(kk);
if(offset == 0 || offset > cnn_type) continue;
double factor = (offset == 1) ? 1.0 : ((offset == 2) ? 1.414214 : ((offset == 3) ? 1.732051 : 0.0));
long index = d*sz01 + h*sz0 + w;
if (is_break_accept)
{
if(inimg1d[index] <= bkg_thresh &&
inimg1d[min_ind] <= bkg_thresh)
continue;
}
else
{
if(inimg1d[index] <= bkg_thresh)
continue;
}
// qDebug()<<"state[index]: "<<(int)state[index];
if(state[index] != ALIVE && state[index] != FINAL)
{
double new_dist = phi[min_ind] + (GI(index) + GI(min_ind))*factor*0.5;
long prev_ind = min_ind;
if(state[index] == FAR)
{
phi[index] = new_dist;
HeapElemX * elem = new HeapElemX(index, phi[index]);
elem->prev_ind = prev_ind;
heap.insert(elem);
elems[index] = elem;
state[index] = TRIAL;
}
else if(state[index] == TRIAL)
{
if (phi[index] > new_dist)
{
phi[index] = new_dist;
HeapElemX * elem = elems[index];
heap.adjust(elem->heap_id, phi[index]);
elem->prev_ind = prev_ind;
}
}
}
}
}
}
}
qDebug()<<"-------find next startPoint----------";
vector<MyMarker*> tmptree = vector<MyMarker*>();
// save current swc tree
if (1)
{
int i = -1, j = -1, k = -1;
map<long, MyMarker*> tmp_map;
for(long ind = 0; ind < tol_sz; ind++)
{
i++; if(i%sz0 == 0){i=0;j++; if(j%sz1 == 0) {j=0; k++;}}
if(state[ind] != ALIVE) continue;
MyMarker * marker = new MyMarker(i,j,k);
tmp_map[ind] = marker;
tmptree.push_back(marker);
// outtree.push_back(marker);
}
i=-1; j = -1; k = -1;
for(long ind = 0; ind < tol_sz; ind++)
{
i++; if(i%sz0 == 0){i=0; j++; if(j%sz1==0){j=0; k++;}}
if(state[ind] == TRIAL)
state[ind] = FAR;
if(state[ind] != ALIVE) continue;
state[ind] = FINAL; //set final
long ind2 = parent[ind];
MyMarker * marker1 = tmp_map[ind];
MyMarker * marker2 = tmp_map[ind2];
if(marker1 == marker2) marker1->parent = 0;
else marker1->parent = marker2;
//tmp_map[ind]->parent = tmp_map[ind2];
}
}
QString s = "C:\\Users\\admin\\Desktop\\testCross\\sc\\3\\test\\" + QString::number(t) + ".swc";
saveSWC_file(s.toStdString(),tmptree);
qDebug()<<"tmpTree size: "<<tmptree.size();
if(tmptree.size()<2){
break;
}
MyMarker* rootMarker;
for(int i=0; i<tmptree.size(); i++){
if(tmptree[i]->parent == 0)
rootMarker = tmptree[i];
}
vector<HierarchySegment*> segs = vector<HierarchySegment*>();
swc2topo_segs<unsigned char>(tmptree,segs,1);
int segMaxLength = 0;
int segMaxIndex = -1;
for(int i=0; i<segs.size(); i++){
if(segs[i]->root_marker == rootMarker && segs[i]->length>segMaxLength){
segMaxLength = segs[i]->length;
segMaxIndex = i;
}
}
qDebug()<<"segMaxLength: "<<segMaxLength;
// init heap
{
MyMarker* leafMarker = segs[segMaxIndex]->leaf_marker;
long index = leafMarker->z*sz01 + leafMarker->y*sz0 +leafMarker->x;
phi[index] = 0;
// parent[index] = index;
path[index] = 0;
HeapElemX *elem = new HeapElemX(index, phi[index]);
elem->prev_ind = index;
heap.insert(elem);
elems[index] = elem;
}
qDebug()<<"----init heap end-----";
vector<MyMarker*> markers = vector<MyMarker*>();
segs[segMaxIndex]->get_markers(markers);
MyMarker* pMarker = 0;
bkg_thresh = INT_MAX;
int* grays = new int[markers.size()];
for(int i=markers.size()-1; i>=0; i--){
MyMarker* marker = new MyMarker(markers[i]->x,markers[i]->y,markers[i]->z);
marker->parent = pMarker;
pMarker = marker;
if(t != 1 && i == markers.size()-1)
pMarker = outtree.back();
long ind = marker->z*sz01 + marker->y*sz0 + marker->x;
grays[i] = inimg1d[ind];
if(inimg1d[ind]<bkg_thresh){
bkg_thresh = inimg1d[ind];
}
if(i != markers.size()-1 || (i == markers.size()-1 && t == 1)){
outtree.push_back(marker);
}
}
double b_mean,b_std;
mean_and_std(grays,markers.size(),b_mean,b_std);
qDebug()<<"b_mean: "<<b_mean<<" b_std: "<<b_std;
double td = MIN(7,b_std);
bkg_thresh = b_mean - b_std*3;//b_std*0.5;
bkg_thresh = 0;
qDebug()<<"bkg_thres: "<<bkg_thresh;
if(stopFlag == 1){
bkg_thresh = 0;
}else if(stopFlag == 2){
while (!heap.empty()) {
HeapElemX* tmp_elem = heap.delete_min();
elems.erase(tmp_elem->img_ind);
delete tmp_elem;
}
}
for(int i=0; i<tmptree.size(); i++){
if(tmptree[i]){
delete tmptree[i];
}
}
tmptree.clear();
qDebug()<<"----clear tmpTree end----";
t++;
}
// over
map<long, HeapElemX*>::iterator mit = elems.begin();
while (mit != elems.end())
{
HeapElemX * elem = mit->second; delete elem; mit++;
}
if(phi){delete [] phi; phi = 0;}
if(parent){delete [] parent; parent = 0;}
if(state) {delete [] state; state = 0;}
if(path) {delete []path; path=0;}
return true;
}
#endif
| [
"1320435719@qq.com"
] | 1320435719@qq.com |
224d7589e572b3e417637ba726fa327c446f704b | a55cec32c0191f3f99752749f8323a517be46638 | /ProfessionalC++/FunctionObjects/bind.cpp | b914e598c1c6b2f54b9464e8b5157a4cc39b6c07 | [
"Apache-2.0"
] | permissive | zzragida/CppExamples | e0b0d1609b2e485cbac22e0878e00cc8ebce6a94 | d627b097efc04209aa4012f7b7f9d82858da3f2d | refs/heads/master | 2021-01-18T15:06:57.286097 | 2016-03-08T00:23:31 | 2016-03-08T00:23:31 | 49,173,497 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 505 | cpp | #include <iostream>
#include <string>
#include <functional>
using namespace std;
using namespace std::placeholders;
void func(int num, const string& str)
{
cout << "func(" << num << ", " << str << ")" << endl;
}
void overloaded(int num) {}
void overloaded(float f) {}
int main()
{
string str = "abc";
auto f1 = bind(func, _1, str);
f1(16);
auto f2 = bind(func, _2, _1);
f2("Test", 32);
//auto f3 = bind(overloaded, _1); // error
auto f4 = bind((void(*)(float))overloaded, _1);
return 0;
}
| [
"zzragida@gmail.com"
] | zzragida@gmail.com |
bef6dd4250d66c5592d567b1af420d1c063af0cb | 11890e51fa9447ee4b544b8c422e0d9fbce0c74a | /Classes/Pragwork/Manager/LocalDBManager.hpp | 88b4fdffd8e24f6b1db16417696e04ea6b843f23 | [] | no_license | DoooReyn/Pragwork | fca832c3c2547ce9c2390bdfbc488081d50b1de1 | feea41492c8d447075d123a2ee59dc0f5debf413 | refs/heads/master | 2021-01-21T07:03:47.193036 | 2017-03-07T15:40:58 | 2017-03-07T15:40:58 | 83,307,322 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 753 | hpp | //
// LocalDBManager.hpp
// Pragwork
//
// Created by Reyn-Mac on 2017/3/3.
//
//
#ifndef LocalDBManager_hpp
#define LocalDBManager_hpp
#include "CocoSupport.h"
class LocalDBManager {
private:
bool m_bconnected;
static LocalDBManager* m_pInstance;
public:
static LocalDBManager* getInstance();
static void destroyInstance();
bool connect();
bool insert(const std::string key, const std::string value);
bool remove(const std::string key);
bool clear();
const std::string select(const std::string key);
const map<std::string, std::string> multiselect(const vector<std::string> keys);
bool disconnect();
protected:
LocalDBManager();
~LocalDBManager();
};
#endif /* LocalDBManager_hpp */
| [
"jl88744653@gmail.com"
] | jl88744653@gmail.com |
fe9b22d6aeae0083c4a3bb14cfbba46aafdc8be0 | cb393fe99ef421b9ea87f1a91d8fff7a74e2ddaa | /C言語プログラミング/5-1配列_List5-2.cpp | c2c8eddaf1eac11502ecbb57f9a8971c03bbc514 | [] | no_license | yutatanaka/C_Programing | d1e8f8f5a88f53f7bc01375eb8f8c5a41faed6f7 | df8e2249ca512a76f0fd843f72b9c771da7e3a33 | refs/heads/master | 2021-01-20T19:19:35.239946 | 2017-02-02T15:09:23 | 2017-02-02T15:09:23 | 63,483,652 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 403 | cpp |
/*
配列の走査
配列の各要素に先頭から順に1, 2, 3, 4, 5を代入して表示
*/
#include <stdio.h>
int main()
{
int v[5]; /* int[5]型の配列 */
v[0] = 1;
v[1] = 2;
v[2] = 3;
v[3] = 4;
v[4] = 5;
printf("v[0] = %d\n", v[0]);
printf("v[1] = %d\n", v[1]);
printf("v[2] = %d\n", v[2]);
printf("v[3] = %d\n", v[3]);
printf("v[4] = %d\n", v[4]);
getchar();
return 0;
} | [
"koryotennis99@gmail.com"
] | koryotennis99@gmail.com |
c03b811652f77fafa4edb3d0779d3d28ac65410c | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/61/9a66c9259a64dd/main.cpp | ed9559cc128dee0d4c55fd3fc27cbd98e291c647 | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,937 | cpp | #include <iostream>
#include <string>
#include <regex>
#include <utility>
// extract tag and value from <tag>value</tag> and return a pair of strings{tag,value}
std::pair<std::string,std::string> extract( const std::string& text )
{
// a very simple regex
// "\S+" => non-space character, repeated one or more times
// "\s*" => space repeated zero or more times
// "/\1" => a slash, followed by the first subgroup that was captured
// ie. if the first subgroup "(\S+)"was "Name", then "/Name"
// match "<tag>text</tag> "<(\S+)>(\S+)</\1>"
// with zero or more spaces (\s*) allowed between components
std::regex re( R"#(\s*<\s*(\S+)\s*>\s*(\S+)\s*<\s*/\1\s*>\s*)#" ) ; // C++11 raw string literal
std::smatch match_results ;
if( std::regex_match( text, match_results, re ) && match_results.size() == 3 )
return { match_results[1].str(), match_results[2].str() } ;
// the first subgroup catured is the tag, the second one is the value
return {} ; // failed
}
int main()
{
const std::string text[] = { "<baseQueueName>Hello</baseQueueName>", "< baseQueueName > Hello < /baseQueueName > ",
"<amount>123.45</amount>", " < amount > 123.45 </amount > ",
"<baseQueueName>Hello</QueueName>", "<amount>123.45</Name>"};
for( const std::string& txt : text )
{
const auto pair = extract(txt) ;
static const char quote = '"' ;
std::cout << "text: " << quote << txt << quote ;
if( !pair.first.empty() )
{
std::cout << " tag: " << quote << pair.first << quote
<< " value: " << quote << pair.second << quote << "\n\n" ;
}
else std::cerr << " **** badly formed string ****\n\n" ;
}
}
| [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
d68e60143d82c37d010dd19bd2512f611eb97d08 | 2e7097f6af8ff4c176ffcac8cc776df9d432d3aa | /algo/remove_dup_unittest.cc | f769d9b6aa45093cc59f647faaae61b92b462063 | [] | no_license | morefreeze/leetcode | 9ce8c49d83c3a554ce4a4e94b0a43d219d4e7769 | 9118c11d1facaa977fb6ecbd2f7cb610a30f76af | refs/heads/master | 2022-05-20T21:55:04.914140 | 2022-05-07T06:27:13 | 2022-05-07T06:27:13 | 36,644,202 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 273 | cc | #include <gtest/gtest.h>
#include "remove_dup.cpp"
class RemoveDupTest: public testing::Test{
protected:
Solution sol;
};
TEST_F(RemoveDupTest, Small){
int a[] = {1,1,2};
VI vl(a, a+sizeof(a)/sizeof(int));
EXPECT_EQ(2, sol.removeDuplicates(vl));
}
| [
"liuchenxing@acfun.tv"
] | liuchenxing@acfun.tv |
fcc27da38d1023636502864b9397c05a5278c35d | 1e29330fbf4d53cf5dfac6f0290f660647109da7 | /yss/inc/drv/timer/drv_maxim_timer_type_A_define.h | 3c611a1c0f498b6ece87b5ff83ca553774637e1f | [] | no_license | bluelife85/yss | 2c9807bba61723a6fa578f80edadd9e8d6f9d1a9 | 1ada1bcc8579bf17e53d6f31525960703ef2f6b9 | refs/heads/master | 2023-01-16T02:12:26.099052 | 2020-11-26T01:18:43 | 2020-11-26T01:18:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,536 | h | ////////////////////////////////////////////////////////////////////////////////////////
//
// 저작권 표기 License_ver_2.0
// 본 소스코드의 소유권은 yss Embedded Operating System 네이버 카페 관리자와 운영진에게 있습니다.
// 운영진이 임의로 코드의 권한을 타인에게 양도할 수 없습니다.
// 본 소스코드는 아래 사항에 동의할 경우에 사용 가능합니다.
// 아래 사항에 대해 동의하지 않거나 이해하지 못했을 경우 사용을 금합니다.
// 본 소스코드를 사용하였다면 아래 사항을 모두 동의하는 것으로 자동 간주 합니다.
// 본 소스코드의 상업적 또는 비상업적 이용이 가능합니다.
// 본 소스코드의 내용을 임의로 수정하여 재배포하는 행위를 금합니다.
// 본 소스코드의 내용을 무단 전재하는 행위를 금합니다.
// 본 소스코드의 사용으로 인해 발생하는 모든 사고에 대해서 어떤한 법적 책임을 지지 않습니다.
//
// Home Page : http://cafe.naver.com/yssoperatingsystem
// Copyright 2020. yss Embedded Operating System all right reserved.
//
// 주담당자 : 아이구 (mymy49@nate.com) 2016.04.30 ~ 현재
// 부담당자 : -
//
////////////////////////////////////////////////////////////////////////////////////////
#ifndef YSS_DRV_TIMER_ST_TYPE_A_DEFINE__H_
#define YSS_DRV_TIMER_ST_TYPE_A_DEFINE__H_
#if defined(MAX32660)
#include <drv/drv_Gpio.h>
namespace define
{
namespace timer
{
}
}
#endif
#endif
| [
"mymy49@nate.com"
] | mymy49@nate.com |
c85eef6e1ebafd5e6d6ca6b76a9cfaf43fcb1704 | 9d425064b3ffa07a047456ba73d54c52763e6431 | /include/component/chipset/Component4040.hpp | b988f2cc76997f2a18ef8fd5f77b4229d569eeb7 | [] | no_license | Skyrize/OOP_nanotekspice_2018 | 8c9aec41d00154b70d904010538d3adf8eea9af3 | d774c97c42b2157dcae8c2d6288e4d6f947abe31 | refs/heads/master | 2020-04-25T23:02:20.092466 | 2019-02-24T19:01:55 | 2019-02-24T19:01:55 | 173,131,202 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 889 | hpp | /*
** EPITECH PROJECT, 2019
** OOP_nanotekspice_2018
** File description: Created on: 30 janv. 2019
** Component4040.hpp
*/
#ifndef SRC_COMPONENT_CHIPSET_COMPONENT4040_HPP_
#define SRC_COMPONENT_CHIPSET_COMPONENT4040_HPP_
#include "Component.hpp"
namespace nts {
class Component4040: public Component {
protected:
int memoryClock = 0;
int openPin = 0;
Tristate previousClockState = Tristate::UNDEFINED;
public:
Component4040(const std::string& name);
virtual ~Component4040();
void incrementMemoryClock();
void resetMemoryClock();
bool isClockStarting() {
if (this->previousClockState == Tristate::UNDEFINED)
return true;
return false;
};
Tristate getOutputStatus(size_t outputPin);
void setPreviousClockState(Tristate state);
Tristate getPreviousClockState();
};
} /* namespace nts */
#endif /* SRC_COMPONENT_CHIPSET_COMPONENT4040_HPP_ */
| [
"clement.baudonnel@epitech.eu"
] | clement.baudonnel@epitech.eu |
12e2f6b999a6dd61e2caae43938a13dea48cbd4f | 315b4721a030871f23aa68b29e81dead78d93a82 | /lj7428.cpp | 514406a230fcb259c2d1636157c65768aecebbf4 | [] | no_license | ArutoriaWhite/Competitive-programming | ce71166ac51929ed6d37761256dfdfee7ebd207e | e19642bd76f1fa12b1162930c4a7f3b199cd2573 | refs/heads/master | 2023-06-16T21:58:01.308407 | 2021-07-19T12:07:12 | 2021-07-19T12:07:12 | 216,078,983 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,141 | cpp | #include <bits/stdc++.h>
#define int long long
#define de(x) cout << #x << '=' << x << ", "
#define dd cout << endl;
#define endl '\n'
#define pui ios::sync_with_stdio(0), cin.tie(0);
#define rep(i,j,k) for (int i=j; i<=k; i++)
#define ff first
#define ss second
#define pb push_back
using namespace std;
typedef pair<int,int> pii;
const int N = 25e3+10;
vector<int> G[N];
int colo[N], idx[N], T, n, m, deg[N];
signed main()
{
cin >> T;
while (T--)
{
memset(colo,0,sizeof(colo));
cin >> n >> m;
rep(i,1,n) idx[i] = i;
rep(i,1,m)
{
int u, v;
cin >> u >> v;
G[u].pb(v);
G[v].pb(u);
deg[u]++, deg[v]++;
}
sort(idx+1,idx+1+n,[](int i, int j){return deg[i]>deg[j];});
while (1)
{
int ex = 1;
rep(i,1,n)
{
int x = idx[i];
int cnt[5] = {0};
for (auto v: G[x])
cnt[colo[v]]++;
rep(j,1,4)
{
if (cnt[j] < 2)
{
colo[x] = j;
break;
}
}
if (colo[x] == 0)
{
ex = 0;
break;
}
}
if (ex)
{
rep(i,1,n) cout << (char)('a'+colo[i]-1) << "\n "[i+1<=n];
break;
}
else
random_shuffle(idx+1,idx+1+n);
}
}
}
| [
"aatroxvanz@gmail.com"
] | aatroxvanz@gmail.com |
bc8aa79a5e912c207525f759dd22abf452f3c450 | 7396ebd54ae4b391bc71ae5132d3d4961c0871fa | /RPC11/g.cpp | c3df651e032c6c7ed22aef01cf5b8abc8c573732 | [] | no_license | luis201420/competitiveProgramming | 41db36ea165bfe089ef20ce7c3dbd32abc7eda54 | 930ddfe54dd5c4bb2e9f7c28921d3159177dd0c1 | refs/heads/master | 2020-09-20T18:03:01.659246 | 2019-11-28T03:43:06 | 2019-11-28T03:43:06 | 224,554,177 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 824 | cpp | #include <bits/stdc++.h>
#define fst first
#define snd second
#define fore(i,a,b) for(int i=a, ThxDem=b; i<ThxDem; ++i)
#define pb push_back
#define ALL(s) s.begin(),s.end()
#define FIN ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define SZ(s) int(s.size())
#define DBG(x) cerr <<#x << " = " << (x) << "\n"
#define SQR(x) ((x) * (x))
#define PI 3.1415926535897932385
#define INF 1000111222
#define eps 1e-7
#define maxN 11
using namespace std;
typedef long long ll;
typedef vector<ll> vll;
typedef pair<ll,ll> pll;
typedef pair<int,int> pii;
typedef vector<string> vstr;
typedef vector<vll> vvll;
typedef vector<bool> vbool;
typedef vector<pll> vpll;
typedef vector<vpll> vvpll;
typedef vector<vbool> vvbool;
int main(){FIN
string s;
cin >> s;
cout << "h"+string((SZ(s)-2)*2,'e')+"y\n";
return 0;
}
| [
"luisito.luis16.lm@gmial.com"
] | luisito.luis16.lm@gmial.com |
90692f3696f2bc9d1370b75d7ea9263ba7aeac54 | 877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a | /app/src/main/cpp/dir7941/dir7942/dir8062/dir8063/dir12766/dir12767/dir13029/dir13714/dir13715/file13761.cpp | e9a06661169cb9ef877b8f97eb9cf4056dbe62c2 | [] | no_license | tgeng/HugeProject | 829c3bdfb7cbaf57727c41263212d4a67e3eb93d | 4488d3b765e8827636ce5e878baacdf388710ef2 | refs/heads/master | 2022-08-21T16:58:54.161627 | 2020-05-28T01:54:03 | 2020-05-28T01:54:03 | 267,468,475 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 115 | cpp | #ifndef file13761
#error "macro file13761 must be defined"
#endif
static const char* file13761String = "file13761"; | [
"tgeng@google.com"
] | tgeng@google.com |
caf2384b15fc9fa330d96c37bcabf5a779652904 | d52d5fdbcd848334c6b7799cad7b3dfd2f1f33e4 | /third_party/folly/folly/logging/LogConfig.cpp | 8bb8c32f7ab96323de0661c31a0a76a6258c9b94 | [
"Apache-2.0"
] | permissive | zhiliaoniu/toolhub | 4109c2a488b3679e291ae83cdac92b52c72bc592 | 39a3810ac67604e8fa621c69f7ca6df1b35576de | refs/heads/master | 2022-12-10T23:17:26.541731 | 2020-07-18T03:33:48 | 2020-07-18T03:33:48 | 125,298,974 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,720 | cpp | /*
* Copyright 2017-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/logging/LogConfig.h>
#include <folly/Conv.h>
namespace folly {
bool LogConfig::operator==(const LogConfig& other) const {
return handlerConfigs_ == other.handlerConfigs_ &&
categoryConfigs_ == other.categoryConfigs_;
}
bool LogConfig::operator!=(const LogConfig& other) const {
return !(*this == other);
}
void LogConfig::update(const LogConfig& other) {
// Update handlerConfigs_ with all of the entries from the other LogConfig.
// Any entries already present in our handlerConfigs_ are replaced wholesale.
for (const auto& entry : other.handlerConfigs_) {
if (entry.second.type.hasValue()) {
// This is a complete LogHandlerConfig that should be inserted
// or completely replace an existing handler config with this name.
auto result = handlerConfigs_.insert(entry);
if (!result.second) {
result.first->second = entry.second;
}
} else {
// This config is updating an existing LogHandlerConfig rather than
// completely replacing it.
auto iter = handlerConfigs_.find(entry.first);
if (iter == handlerConfigs_.end()) {
throw std::invalid_argument(to<std::string>(
"cannot update configuration for unknown log handler \"",
entry.first,
"\""));
}
iter->second.update(entry.second);
}
}
// Update categoryConfigs_ with all of the entries from the other LogConfig.
//
// Any entries already present in our categoryConfigs_ are merged: if the new
// configuration does not include handler settings our entry's settings are
// maintained.
for (const auto& entry : other.categoryConfigs_) {
auto result = categoryConfigs_.insert(entry);
if (!result.second) {
auto* existingEntry = &result.first->second;
auto oldHandlers = std::move(existingEntry->handlers);
*existingEntry = entry.second;
if (!existingEntry->handlers.hasValue()) {
existingEntry->handlers = std::move(oldHandlers);
}
}
}
}
} // namespace folly
| [
"yangshengzhi1@bigo.sg"
] | yangshengzhi1@bigo.sg |
255ded137f61aa3b9e589327ff16a7f54af493bc | d4e82c245fc21083416b772381aa4f2d45f6355b | /Juna/Lyrics/LyricsViewer.h | 0f89ab3d315000ef12f2840025275e3f4757c65e | [] | no_license | Juna-Idler/LyricsView | 8dcd4c671e998c06291b2cf97ac5b84fe4cdbca3 | 64e751dede3227536e05a6e3f4fe0a0029222577 | refs/heads/master | 2023-03-31T05:03:14.336553 | 2021-04-06T21:11:33 | 2021-04-06T21:11:33 | 355,179,389 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,307 | h | #pragma once
#include "LyricsContainer.h"
#include "LyricsDrawParameter.h"
#include "TextLyricsDraw.h"
#include "LyricsScrollDraw.h"
#include "KaraokeDraw.h"
#include "RubyKaraokeContainer.h"
#include "../Picture/DIBImage.h"
namespace Juna {
namespace Lyrics {
class LyricsViewer
{
class C_BackGroundImage
{
public:
C_BackGroundImage(void) :
SourceImage(), DisplayImage(), Filter(0,0,0,0),TranslucentAlpha(256),
LimitDisplayX(true), LimitDisplayY(true),
LimitSourceX(true), LimitSourceY(true),
LimitMaxX(true), LimitMaxY(true), MaxX(300), MaxY(300),
Position(5)
{}
Juna::Picture::DIBImage SourceImage;
Juna::Picture::Image DisplayImage;
Juna::Picture::ARGB Filter;
int TranslucentAlpha;
bool LimitDisplayX;
bool LimitDisplayY;
bool LimitSourceX;
bool LimitSourceY;
bool LimitMaxX;
bool LimitMaxY;
int MaxX;
int MaxY;
int Position;
void Update(Juna::Picture::I_Image &target,const Juna::Picture::Rect &target_rect);
void Terminalize(void)
{
SourceImage.Terminalize();
DisplayImage.Terminalize();
}
};
class C_InformationText
{
TextContainer Text;
Juna::Picture::BufferedOutlineFont Font;
public:
const TextContainer &GetText(void) const {return Text;}
TextDrawParameter Param;
Juna::Picture::Color Color;
Juna::Picture::Color OutlineColor;
bool SetFont(unsigned int fontquality,Juna::Picture::OutlineFont &font, unsigned outlinethickness);
void SetText(const std::wstring &text);
void Terminalize(void)
{
Text.Terminalize();
Font.Terminalize();
}
};
class C_FrameImage
{
public:
C_FrameImage(void) : SourceImage() {}
Juna::Picture::DIBImage SourceImage;
void Draw(Juna::Picture::I_Image &target);
void Terminalize(void)
{
SourceImage.Terminalize();
}
};
public:
LyricsViewer(void) :
Canvas(),
BGColor(0,0,0),
NTTTextColor(255,255,255),
NTTTextOutlineColor(0,0,0),
LyricsMode(LM_Null),
Lyrics(),
Karaoke(),
Text(),
RubyKaraoke(),
Parameter(),
Font(), RubyFont(),
BGImage(),
InfoText(),
LyricsLayoutRect(0,0,0,0),
BGImageLayoutRect(0,0,0,0),
TextLayoutRect(0,0,0,0),
LastDrawPoint(),
ForceRedraw(true)
{
LastDrawPoint.index = 0;
LastDrawPoint.scroll_y = 0;
LastDrawPoint.scroll_rate = 0;
LastDrawPoint.playtime_ms = 0;
}
enum enumLyricsMode {LM_Null = 0,LM_Lyrics = 1,LM_Karaoke = 2,LM_Text = 3,LM_RubyKaraoke = 4};
private:
Juna::Picture::DIBImage Canvas;
enumLyricsMode LyricsMode;
LyricsContainer Lyrics;
KaraokeContainer Karaoke;
TextContainer Text;
RubyKaraokeContainer RubyKaraoke;
Juna::Picture::BufferedOutlineFont Font;
Juna::Picture::BufferedOutlineFont RubyFont;
Juna::Lyrics::ScrollDraw::DrawPoint LastDrawPoint;
bool ForceRedraw;
KaraokeDrawer KDrawer;
void FillBGColor(void);
public:
LyricsDrawParameter Parameter;
Juna::Picture::ARGB BGColor;
Juna::Picture::Color NTTTextColor;
Juna::Picture::Color NTTTextOutlineColor;
C_BackGroundImage BGImage;
C_InformationText InfoText;
C_FrameImage FrameImage;
Juna::Picture::Rect LyricsLayoutRect;
Juna::Picture::Rect BGImageLayoutRect;
Juna::Picture::Rect TextLayoutRect;
bool IsValid(void) const {return (Lyrics.IsValid() || Karaoke.IsValid() || Text.IsValid() || RubyKaraoke.IsValid()) && Parameter.IsValid();}
enumLyricsMode GetLyricsMode(void) const {return LyricsMode;}
void SetLyrics(const std::wstring &text);
void SetKaraoke(const std::wstring &text,bool keephead = false);
void SetText(const std::wstring &text);
void SetRubyKaraoke(const std::wstring &text,bool keephead = false);
bool SetFont(unsigned int fontquality,Juna::Picture::OutlineFont &font,int outlinethickness);
void Terminalize(void)
{
Lyrics.Terminalize();
Karaoke.Terminalize();
Text.Terminalize();
RubyKaraoke.Terminalize();
RubyFont.Terminalize();
Font.Terminalize();
Canvas.Terminalize();
BGImage.Terminalize();
InfoText.Terminalize();
FrameImage.Terminalize();
}
void Resize(int width,int height);
bool Update(int playtime_ms);
bool UpdateContinuousScroll(int playtime_ms);
const Juna::Picture::DIBImage &GetCanvas(void) const {return Canvas;}
void SetForceRedraw(void) {ForceRedraw = true;}
bool UpdateKaraoke(int playtime_ms,int bottom_margin);
};
}//namespace Lyrics
}//namespace Juna
| [
"juna.idler@gmail.com"
] | juna.idler@gmail.com |
787cb9394709b447e7bd4e1cafb37b2c3f0c3556 | b3ad18312b892772804f25f0f093845d99874965 | /Project 6 Code/invmenu.cpp | 3a555997c3b23336a2c4950f5c2a19c3ed81891d | [] | no_license | bwiersma65/CMSC226Projects | 89306e4340c5ec91547b1a1b2fd7690c488aed30 | e45a694c8a961b794944400112831c403b12b97b | refs/heads/master | 2022-04-26T09:25:31.140436 | 2020-04-20T02:43:36 | 2020-04-20T02:43:36 | 255,445,737 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,232 | cpp | //
// invmenu.cpp
// Semester Project
//
// Created by Ben Wiersma on 2/10/20.
// Copyright © 2020 Ben Wiersma. All rights reserved.
//
#include <iostream>
#include <string>
// header files
#include "invmenu.h"
#include "bookinfo.h"
using namespace std;
/*
Global arrays for holding data on each book
*/
const int NUM_OF_ITEMS = 20;
const int TITLE_LENGTH = 51, ISBN_LENGTH = 14, NAME_LENGTH = 31, DATE_LENGTH = 11;
extern char bookTitle[NUM_OF_ITEMS][TITLE_LENGTH], isbn[NUM_OF_ITEMS][ISBN_LENGTH], author[NUM_OF_ITEMS][NAME_LENGTH], publisher[NUM_OF_ITEMS][NAME_LENGTH], dateAdded[NUM_OF_ITEMS][DATE_LENGTH];
extern int qtyOnHand[NUM_OF_ITEMS];
extern double wholesale[NUM_OF_ITEMS], retail[NUM_OF_ITEMS];
extern int bookCounter;
int invMenu()
{
int input = 0;
do {
// Menu Screen
cout << "\n////////////////////////////////////////////////////////////////////////////";
cout << "\n\t\t\tSerendipity Booksellers\n\t\t\t Inventory Database" << endl;
cout << "\n\t\t\t1. Look Up a Book" << endl;
cout << "\t\t\t2. Add a Book" << endl;
cout << "\t\t\t3. Edit a Book's Record" << endl;
cout << "\t\t\t4. Delete a Book" << endl;
cout << "\t\t\t5. Return to the Main Menu" << endl;
cout << "\n\t\t\tEnter Your Choice: ";
cin >> input;
// Input Validation
while (input < 1 || 5 < input)
{
cout << "\n\t\t\tPlease enter a number in the range 1 - 5" << endl;
cout << "\n\t\t\tEnter Your Choice: ";
cin >> input;
}
/*
Menu selection
*/
switch (input)
{
case 1: lookUpBook();
break;
case 2: addBook();
break;
case 3: editBook();
break;
case 4: deleteBook();
break;
case 5: cout << "\n\t\t\tYou selected item 5\n";
}
}
while (input != 5);
return 0;
}
/*
Searches for book with given title, then prints book info
*/
void lookUpBook()
{
cout << "\n////////////////////////////////////////////////////////////////////////////";
char searchTitle[TITLE_LENGTH];
bool found;
int index, i = 0;
char *titlePtr = nullptr;
char correct = 'q', kontinue = 'z';
do {
cin.ignore();
cout << "\nPlease enter book title: ";
cin.getline(searchTitle, TITLE_LENGTH);
strUpper(searchTitle);
index = -1;
found = false;
while (!found && i < bookCounter) {
/*
Check if input text matches portion of book title from inventory
*/
titlePtr = strstr(bookTitle[i], searchTitle);
if (titlePtr != nullptr) {
found = true;
index = i;
}
i++;
}
/*
Check to ensure this is book user wants
*/
if (found) {
cout << "Is this the book you're looking for? (Y/N): ";
cout << bookTitle[index] << endl;
cin >> correct;
if (correct == 'N' || correct == 'n')
found = false;
}
/*
Print error msg if title matching text could not be found in database
*/
else {
i = 0;
cout << "Book could not be found, try again? (Y/N): ";
cin >> kontinue;
}
}
while ((correct == 'N' || correct == 'n' || kontinue == 'Y' || kontinue == 'y') && i < bookCounter);
/*
Book not found and end of inventory reached
*/
if (!found && i == bookCounter) {
cout << "\nBook with given title could not be found" << endl;
return;
}
/*
Prints book info
*/
else
bookInfo(isbn[index], bookTitle[index], author[index], publisher[index], dateAdded[index], qtyOnHand[index], wholesale[index], retail[index]);
}
/*
Searches for empty space in inventory database, then requests input for data of the book being entered
*/
void addBook()
{
char titleTemp[TITLE_LENGTH], isbnTemp[ISBN_LENGTH], authorTemp[NAME_LENGTH], pubTemp[NAME_LENGTH];
cin.ignore();
cout << "\n////////////////////////////////////////////////////////////////////////////";
/*
Searches array for empty slot
*/
int index = -1;
for (int i = 0; i < 20; i++) {
if (strcmp(bookTitle[i], "") == 0) {
index = i;
break;
}
}
/*
Database full
*/
if (index == -1) {
cout << "\nThe array is full. No more books may be added" << endl;
return;
}
/*
Prompts for book data to be added to program array
*/
else {
cout << "\nPlease enter the following informatin:\n" << endl;
cout << "Book Title: ";
cin.getline(titleTemp, TITLE_LENGTH);
strUpper(titleTemp);
strcpy(bookTitle[index], titleTemp);
cout << "\nISBN Number: ";
//getline(cin, isbn[index]);
//cin.getline(isbn[index], ISBN_LENGTH);
cin.getline(isbnTemp, ISBN_LENGTH);
strUpper(isbnTemp);
strcpy(isbn[index], isbnTemp);
cout << "\nAuthor's Name: ";
//getline(cin, author[index]);
cin.getline(authorTemp, NAME_LENGTH);
strUpper(authorTemp);
strcpy(author[index], authorTemp);
cout << "\nPublisher's Name: ";
//getline(cin, publisher[index]);
cin.getline(pubTemp, NAME_LENGTH);
strUpper(pubTemp);
strcpy(publisher[index], pubTemp);
cout << "\nDate book was added to inventory (MM-DD-YYYY): ";
//getline(cin, dateAdded[index]);
cin.getline(dateAdded[index], DATE_LENGTH);
cout << "\nQuantity of book being added: ";
cin >> qtyOnHand[index];
cout << "\nWholesale cost of (single) book: ";
cin >> wholesale[index];
cout << "\nRetail price of (single) book: ";
cin >> retail[index];
/*
Increments counter to reflect new book has been added to database
*/
bookCounter++;
}
}
/*
Searches for book in array, then asks if user would like to edit piece of book data
*/
void editBook()
{
cout << "\n////////////////////////////////////////////////////////////////////////////";
char title[TITLE_LENGTH], isbnTemp[ISBN_LENGTH], titleTemp[TITLE_LENGTH], authorTemp[NAME_LENGTH], pubTemp[NAME_LENGTH];
int menuChoice;
char kontinue = 'z';
bool found;
int index = -1;
char *titlePtr = nullptr;
char correct = 'q';
do {
cin.ignore();
cout << "\nPlease enter book title: ";
cin.getline(title, TITLE_LENGTH);
strUpper(title);
found = false;
/*
Check if input text matches portion of title from database
*/
while (!found && index < bookCounter)
{
titlePtr = strstr(bookTitle[index], title);
if (titlePtr != nullptr)
found = true;
else
index++;
}
/*
Check to ensure this is book user wants
*/
if (found) {
cout << "Is this the book you're looking for? (Y/N): " << endl;
cout << bookTitle[index] << endl;
cin >> correct;
}
/*
Book title could not be found in database
*/
else {
index = 0;
cout << "Book could not be found. Try again? (Y/N): " << endl;
cin >> kontinue;
}
}
while ((correct == 'N' || correct == 'n' || kontinue == 'Y' || kontinue == 'y') && index < bookCounter);
/*
Book not found and inventory exhausted
*/
if (!found && index == bookCounter) {
cout << "\nBook with given title could not be found" << endl;
return;
}
else {
do {
/*
Print current book info
*/
bookInfo(isbn[index], bookTitle[index], author[index], publisher[index], dateAdded[index], qtyOnHand[index], wholesale[index], retail[index]);
menuChoice = -1;
/*
Prompt for book datum to be changed
*/
cout << "\nWhich fields would you like changed?\n\n";
cout << "1 - ISBN" << endl;
cout << "2 - Title" << endl;
cout << "3 - Author" << endl;
cout << "4 - Publisher" << endl;
cout << "5 - Date Added" << endl;
cout << "6 - Quantity-on-Hand" << endl;
cout << "7 - Wholesale Cost" << endl;
cout << "8 - Retail Price" << endl;
cout << "9 - Cancel" << endl;
cout << "\nSelection: ";
cin >> menuChoice;
switch (menuChoice)
{
case 1:
cin.ignore();
cout << "\nEnter the new ISBN: ";
cin.getline(isbnTemp, ISBN_LENGTH);
strUpper(isbnTemp);
strcpy(isbn[index], isbnTemp);
break;
case 2:
cin.ignore();
cout << "\nEnter the new Title: ";
//getline(cin, bookTitle[index]);
cin.getline(titleTemp, TITLE_LENGTH);
strUpper(titleTemp);
strcpy(bookTitle[index], titleTemp);
break;
case 3:
cin.ignore();
cout << "\nEnter the new Author: ";
//getline(cin, author[index]);
cin.getline(authorTemp, NAME_LENGTH);
strUpper(authorTemp);
strcpy(author[index], authorTemp);
break;
case 4:
cin.ignore();
cout << "\nEnter the new Publisher: ";
//getline(cin, publisher[index]);
cin.getline(pubTemp, NAME_LENGTH);
strUpper(pubTemp);
strcpy(publisher[index], pubTemp);
break;
case 5:
cin.ignore();
cout << "\nEnter the new Date Added: ";
//cin >> dateAdded[index];
cin.getline(dateAdded[index], DATE_LENGTH);
break;
case 6:
cout << "\nEnter the new Quantity-On-Hand: ";
cin >> qtyOnHand[index];
break;
case 7:
cout << "\nEnter the new Wholesale Cost: ";
cin >> wholesale[index];
break;
case 8:
cout << "\nEnter the new Retail Price: ";
cin >> retail[index];
break;
case 9:
break;
}
/*
Reprint new book data
*/
bookInfo(isbn[index], bookTitle[index], author[index], publisher[index], dateAdded[index], qtyOnHand[index], wholesale[index], retail[index]);
/*
Prompt for loop
*/
cout << "\nWould you like to change another field? (Y/N): ";
cin >> kontinue;
}
while (kontinue == 'Y' || kontinue == 'y');
}
}
/*
Deletes given book and its data from inventory
*/
void deleteBook()
{
cout << "\n////////////////////////////////////////////////////////////////////////////";
char title[TITLE_LENGTH];
/*
Searches array for book with given title
*/
bool found;
int index = -1;
char *titlePtr = nullptr;
char correct = 'q', kontinue = 'r', erase = 'z';
do {
cin.ignore();
cout << "\nPlease enter book title: ";
//getline(cin, title);
cin.getline(title, TITLE_LENGTH);
strUpper(title);
found = false;
/*
Check if input text matches portion of title from inventory
*/
while (!found && index < bookCounter)
{
titlePtr = strstr(bookTitle[index], title);
if (titlePtr != nullptr)
found = true;
else
index++;
}
/*
Check to ensure this is book user wants
*/
if (found) {
cout << "Is this the book you're looking for? (Y/N): " << endl;
cout << bookTitle[index] << endl;
cin >> correct;
}
/*
Title not found in inventory database
*/
else {
index = 0;
cout << "Book could not be found. Try again? (Y/N): " << endl;
cin >> kontinue;
}
}
while ((correct == 'N' || correct == 'n' || kontinue == 'Y' || kontinue == 'y') && index < bookCounter);
/*
Book not found and inventory exhausted
*/
if (!found && index == bookCounter) {
cout << "\nBook with given title could not be found" << endl;
return;
}
else {
bookInfo(isbn[index], bookTitle[index], author[index], publisher[index], dateAdded[index], qtyOnHand[index], wholesale[index], retail[index]);
cout << "\nAre you sure this book is to be deleted from inventory? (Y/N): ";
cin >> erase;
/*
Sets book data to default values (empty string or 0)
*/
if (erase == 'Y' || erase == 'y') {
//bookTitle[index] = "";
strcpy(bookTitle[index], "");
//isbn[index] = "";
strcpy(isbn[index], "");
//author[index] = "";
strcpy(author[index], "");
//publisher[index] = "";
strcpy(publisher[index], "");
//dateAdded[index] = "";
strcpy(dateAdded[index], "");
qtyOnHand[index] = 0;
wholesale[index] = 0;
retail[index] = 0;
bookCounter--;
cout << "\nThe book has been deleted" << endl;
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
aa7732f47edd675ebf5684fc825d2577ef93d334 | 88483bbcd6b6b3038233d0a7ebda6c493e4ef589 | /C-2018/补充内容/pointer.cpp | 12569e9f753c64c3ab2c124ccb04104ef826e636 | [] | no_license | tjy1985001/Teaching | 5760eab3cd3e6c4cd1332c80fcf8098c160a7deb | 31e090c866493443b5a944c043fbfb2f1c90c372 | refs/heads/master | 2020-06-06T22:37:51.921889 | 2018-12-10T03:45:51 | 2018-12-10T03:45:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 160 | cpp | #include <stdio.h>
int main()
{
int a = 10;
int *p = &a;
printf("address: %d\n", p);
printf("content: %d\n", *p);
return 0;
}
| [
"847315251@qq.com"
] | 847315251@qq.com |
1919c4e6b291a76d8f196d3111ca932b9970431a | 8fb115a29224528b419f2b40d642dfb0ecc0b990 | /src/qt/transactionrecord.cpp | 1b19b611ab3516fab72cf555fcdee9912e97e4d1 | [
"MIT"
] | permissive | BramandUn/pallycoin | 53d5b8f4b07d7336b28a63c2a9ff251b4eed9e68 | c2c862028648d4a649d661d1160f4e19b668445c | refs/heads/master | 2020-04-11T13:30:20.243100 | 2018-12-14T17:26:28 | 2018-12-14T17:26:28 | 158,978,110 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,085 | cpp | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Pallycoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "transactionrecord.h"
#include "base58.h"
#include "timedata.h"
#include "wallet.h"
#include "darksend.h"
#include "instantx.h"
#include <stdint.h>
/* Return positive answer if transaction should be shown in list.
*/
bool TransactionRecord::showTransaction(const CWalletTx &wtx)
{
if (wtx.IsCoinBase())
{
// Ensures we show generated coins / mined transactions at depth 1
if (!wtx.IsInMainChain())
{
return false;
}
}
return true;
}
/*
* Decompose CWallet transaction to model transaction records.
*/
QList<TransactionRecord> TransactionRecord::decomposeTransaction(const CWallet *wallet, const CWalletTx &wtx)
{
QList<TransactionRecord> parts;
int64_t nTime = wtx.GetTxTime();
CAmount nCredit = wtx.GetCredit(ISMINE_ALL);
CAmount nDebit = wtx.GetDebit(ISMINE_ALL);
CAmount nNet = nCredit - nDebit;
uint256 hash = wtx.GetHash();
std::map<std::string, std::string> mapValue = wtx.mapValue;
if (nNet > 0 || wtx.IsCoinBase())
{
//
// Credit
//
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
isminetype mine = wallet->IsMine(txout);
if(mine)
{
TransactionRecord sub(hash, nTime);
CTxDestination address;
sub.idx = parts.size(); // sequence number
sub.credit = txout.nValue;
sub.involvesWatchAddress = mine == ISMINE_WATCH_ONLY;
if (ExtractDestination(txout.scriptPubKey, address) && IsMine(*wallet, address))
{
// Received by Pallycoin Address
sub.type = TransactionRecord::RecvWithAddress;
sub.address = CBitcoinAddress(address).ToString();
}
else
{
// Received by IP connection (deprecated features), or a multisignature or other non-simple transaction
sub.type = TransactionRecord::RecvFromOther;
sub.address = mapValue["from"];
}
if (wtx.IsCoinBase())
{
// Generated
sub.type = TransactionRecord::Generated;
}
parts.append(sub);
}
}
}
else
{
bool fAllFromMeDenom = true;
int nFromMe = 0;
bool involvesWatchAddress = false;
isminetype fAllFromMe = ISMINE_SPENDABLE;
BOOST_FOREACH(const CTxIn& txin, wtx.vin)
{
if(wallet->IsMine(txin)) {
fAllFromMeDenom = fAllFromMeDenom && wallet->IsDenominated(txin);
nFromMe++;
}
isminetype mine = wallet->IsMine(txin);
if(mine == ISMINE_WATCH_ONLY) involvesWatchAddress = true;
if(fAllFromMe > mine) fAllFromMe = mine;
}
isminetype fAllToMe = ISMINE_SPENDABLE;
bool fAllToMeDenom = true;
int nToMe = 0;
BOOST_FOREACH(const CTxOut& txout, wtx.vout) {
if(wallet->IsMine(txout)) {
fAllToMeDenom = fAllToMeDenom && wallet->IsDenominatedAmount(txout.nValue);
nToMe++;
}
isminetype mine = wallet->IsMine(txout);
if(mine == ISMINE_WATCH_ONLY) involvesWatchAddress = true;
if(fAllToMe > mine) fAllToMe = mine;
}
if(fAllFromMeDenom && fAllToMeDenom && nFromMe * nToMe) {
parts.append(TransactionRecord(hash, nTime, TransactionRecord::DarksendDenominate, "", -nDebit, nCredit));
parts.last().involvesWatchAddress = false; // maybe pass to TransactionRecord as constructor argument
}
else if (fAllFromMe && fAllToMe)
{
// Payment to self
// TODO: this section still not accurate but covers most cases,
// might need some additional work however
TransactionRecord sub(hash, nTime);
// Payment to self by default
sub.type = TransactionRecord::SendToSelf;
sub.address = "";
if(mapValue["DS"] == "1")
{
sub.type = TransactionRecord::Darksent;
CTxDestination address;
if (ExtractDestination(wtx.vout[0].scriptPubKey, address))
{
// Sent to Pallycoin Address
sub.address = CBitcoinAddress(address).ToString();
}
else
{
// Sent to IP, or other non-address transaction like OP_EVAL
sub.address = mapValue["to"];
}
}
else
{
for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++)
{
const CTxOut& txout = wtx.vout[nOut];
sub.idx = parts.size();
if(wallet->IsCollateralAmount(txout.nValue)) sub.type = TransactionRecord::DarksendMakeCollaterals;
if(wallet->IsDenominatedAmount(txout.nValue)) sub.type = TransactionRecord::DarksendCreateDenominations;
if(nDebit - wtx.GetValueOut() == DARKSEND_COLLATERAL) sub.type = TransactionRecord::DarksendCollateralPayment;
}
}
CAmount nChange = wtx.GetChange();
sub.debit = -(nDebit - nChange);
sub.credit = nCredit - nChange;
parts.append(sub);
parts.last().involvesWatchAddress = involvesWatchAddress; // maybe pass to TransactionRecord as constructor argument
}
else if (fAllFromMe)
{
//
// Debit
//
CAmount nTxFee = nDebit - wtx.GetValueOut();
for (unsigned int nOut = 0; nOut < wtx.vout.size(); nOut++)
{
const CTxOut& txout = wtx.vout[nOut];
TransactionRecord sub(hash, nTime);
sub.idx = parts.size();
sub.involvesWatchAddress = involvesWatchAddress;
if(wallet->IsMine(txout))
{
// Ignore parts sent to self, as this is usually the change
// from a transaction sent back to our own address.
continue;
}
CTxDestination address;
if (ExtractDestination(txout.scriptPubKey, address))
{
// Sent to Pallycoin Address
sub.type = TransactionRecord::SendToAddress;
sub.address = CBitcoinAddress(address).ToString();
}
else
{
// Sent to IP, or other non-address transaction like OP_EVAL
sub.type = TransactionRecord::SendToOther;
sub.address = mapValue["to"];
}
if(mapValue["DS"] == "1")
{
sub.type = TransactionRecord::Darksent;
}
CAmount nValue = txout.nValue;
/* Add fee to first output */
if (nTxFee > 0)
{
nValue += nTxFee;
nTxFee = 0;
}
sub.debit = -nValue;
parts.append(sub);
}
}
else
{
//
// Mixed debit transaction, can't break down payees
//
parts.append(TransactionRecord(hash, nTime, TransactionRecord::Other, "", nNet, 0));
parts.last().involvesWatchAddress = involvesWatchAddress;
}
}
return parts;
}
void TransactionRecord::updateStatus(const CWalletTx &wtx)
{
AssertLockHeld(cs_main);
// Determine transaction status
// Find the block the tx is in
CBlockIndex* pindex = NULL;
BlockMap::iterator mi = mapBlockIndex.find(wtx.hashBlock);
if (mi != mapBlockIndex.end())
pindex = (*mi).second;
// Sort order, unrecorded transactions sort to the top
status.sortKey = strprintf("%010d-%01d-%010u-%03d",
(pindex ? pindex->nHeight : std::numeric_limits<int>::max()),
(wtx.IsCoinBase() ? 1 : 0),
wtx.nTimeReceived,
idx);
status.countsForBalance = wtx.IsTrusted() && !(wtx.GetBlocksToMaturity() > 0);
status.depth = wtx.GetDepthInMainChain();
status.cur_num_blocks = chainActive.Height();
status.cur_num_ix_locks = nCompleteTXLocks;
if (!IsFinalTx(wtx, chainActive.Height() + 1))
{
if (wtx.nLockTime < LOCKTIME_THRESHOLD)
{
status.status = TransactionStatus::OpenUntilBlock;
status.open_for = wtx.nLockTime - chainActive.Height();
}
else
{
status.status = TransactionStatus::OpenUntilDate;
status.open_for = wtx.nLockTime;
}
}
// For generated transactions, determine maturity
else if(type == TransactionRecord::Generated)
{
if (wtx.GetBlocksToMaturity() > 0)
{
status.status = TransactionStatus::Immature;
if (wtx.IsInMainChain())
{
status.matures_in = wtx.GetBlocksToMaturity();
// Check if the block was requested by anyone
if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
status.status = TransactionStatus::MaturesWarning;
}
else
{
status.status = TransactionStatus::NotAccepted;
}
}
else
{
status.status = TransactionStatus::Confirmed;
}
}
else
{
if (status.depth < 0)
{
status.status = TransactionStatus::Conflicted;
}
else if (GetAdjustedTime() - wtx.nTimeReceived > 2 * 60 && wtx.GetRequestCount() == 0)
{
status.status = TransactionStatus::Offline;
}
else if (status.depth == 0)
{
status.status = TransactionStatus::Unconfirmed;
}
else if (status.depth < RecommendedNumConfirmations)
{
status.status = TransactionStatus::Confirming;
}
else
{
status.status = TransactionStatus::Confirmed;
}
}
}
bool TransactionRecord::statusUpdateNeeded()
{
AssertLockHeld(cs_main);
return status.cur_num_blocks != chainActive.Height() || status.cur_num_ix_locks != nCompleteTXLocks;
}
QString TransactionRecord::getTxID() const
{
return formatSubTxId(hash, idx);
}
QString TransactionRecord::formatSubTxId(const uint256 &hash, int vout)
{
return QString::fromStdString(hash.ToString() + strprintf("-%03d", vout));
}
| [
"41528243+BramandUn@users.noreply.github.com"
] | 41528243+BramandUn@users.noreply.github.com |
124634c4a7ffbbe3d584665ce865736d2566d949 | fd9728ede8da6121ad699e87b889d259193ea600 | /src/widgets/autotests/customdebuglistviewtest.h | 5f437d820498ec8cacce173648b880a9d54f90cd | [
"BSD-3-Clause",
"CC0-1.0"
] | permissive | KDE/kdebugsettings | 70a8f78f34f09e98adf1a466dc284e928e5d23cb | 371cdbdfb30c0c5045212fcdc61d7075ec403cf3 | refs/heads/master | 2023-08-17T06:34:05.023894 | 2023-08-16T20:58:05 | 2023-08-16T20:58:12 | 42,719,354 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 396 | h | /*
SPDX-FileCopyrightText: 2023 Laurent Montel <montel@kde.org>
SPDX-License-Identifier: LGPL-2.0-or-later
*/
#pragma once
#include <QObject>
class CustomDebugListViewTest : public QObject
{
Q_OBJECT
public:
explicit CustomDebugListViewTest(QObject *parent = nullptr);
~CustomDebugListViewTest() override = default;
private Q_SLOTS:
void shouldHaveDefaultValues();
};
| [
"montel@kde.org"
] | montel@kde.org |
47826d75a9654045c1dc1a98d31d90c26fba9d67 | 568eb464f617548275d6611d6d86914c5263910c | /base/thread_local.h | 7b3c3daacf51d1746f1f31eca74a4b6ce73c4125 | [
"BSD-3-Clause"
] | permissive | bluebellzhy/chromium | c27cba0ca182189745d282d78cf7b0928f6d47b3 | 008c4fef2676506869a0404239da31e83fd6ccc7 | refs/heads/master | 2021-01-15T19:03:37.018631 | 2008-10-24T21:13:14 | 2008-10-24T21:13:14 | 67,454 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,783 | h | // Copyright (c) 2006-2008 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.
// WARNING: Thread local storage is a bit tricky to get right. Please make
// sure that this is really the proper solution for what you're trying to
// achieve. Don't prematurely optimize, most likely you can just use a Lock.
//
// These classes implement a warpper around the platform's TLS storage
// mechanism. On construction, they will allocate a TLS slot, and free the
// TLS slot on destruction. No memory management (creation or destruction) is
// handled. This means for uses of ThreadLocalPointer, you must correctly
// manage the memory yourself, these classes will not destroy the pointer for
// you. There are no at-thread-exit actions taken by these classes.
//
// ThreadLocalPointer<Type> wraps a Type*. It performs no creation or
// destruction, so memory management must be handled elsewhere. The first call
// to Get() on a thread will return NULL. You can update the pointer with a
// call to Set().
//
// ThreadLocalBoolean wraps a bool. It will default to false if it has never
// been set otherwise with Set().
//
// Thread Safety: An instance of ThreadLocalStorage is completely thread safe
// once it has been created. If you want to dynamically create an instance,
// you must of course properly deal with safety and race conditions. This
// means a function-level static initializer is generally inappropiate.
//
// Example usage:
// // My class is logically attached to a single thread. We cache a pointer
// // on the thread it was created on, so we can implement current().
// MyClass::MyClass() {
// DCHECK(Singleton<ThreadLocalPointer<MyClass> >::get()->Get() == NULL);
// Singleton<ThreadLocalPointer<MyClass> >::get()->Set(this);
// }
//
// MyClass::~MyClass() {
// DCHECK(Singleton<ThreadLocalPointer<MyClass> >::get()->Get() != NULL);
// Singleton<ThreadLocalPointer<MyClass> >::get()->Set(NULL);
// }
//
// // Return the current MyClass associated with the calling thread, can be
// // NULL if there isn't a MyClass associated.
// MyClass* MyClass::current() {
// return Singleton<ThreadLocalPointer<MyClass> >::get()->Get();
// }
#ifndef BASE_THREAD_LOCAL_H_
#define BASE_THREAD_LOCAL_H_
#include "base/basictypes.h"
#if defined(OS_POSIX)
#include <pthread.h>
#endif
namespace base {
// Helper functions that abstract the cross-platform APIs. Do not use directly.
struct ThreadLocalPlatform {
#if defined(OS_WIN)
typedef int SlotType;
#elif defined(OS_POSIX)
typedef pthread_key_t SlotType;
#endif
static void AllocateSlot(SlotType& slot);
static void FreeSlot(SlotType& slot);
static void* GetValueFromSlot(SlotType& slot);
static void SetValueInSlot(SlotType& slot, void* value);
};
template <typename Type>
class ThreadLocalPointer {
public:
ThreadLocalPointer() : slot_() {
ThreadLocalPlatform::AllocateSlot(slot_);
}
~ThreadLocalPointer() {
ThreadLocalPlatform::FreeSlot(slot_);
}
Type* Get() {
return static_cast<Type*>(ThreadLocalPlatform::GetValueFromSlot(slot_));
}
void Set(Type* ptr) {
ThreadLocalPlatform::SetValueInSlot(slot_, ptr);
}
private:
typedef ThreadLocalPlatform::SlotType SlotType;
SlotType slot_;
DISALLOW_COPY_AND_ASSIGN(ThreadLocalPointer<Type>);
};
class ThreadLocalBoolean {
public:
ThreadLocalBoolean() { }
~ThreadLocalBoolean() { }
bool Get() {
return tlp_.Get() != NULL;
}
void Set(bool val) {
tlp_.Set(reinterpret_cast<void*>(val ? 1 : 0));
}
private:
ThreadLocalPointer<void> tlp_;
DISALLOW_COPY_AND_ASSIGN(ThreadLocalBoolean);
};
} // namespace base
#endif // BASE_THREAD_LOCAL_H_
| [
"deanm@google.com@4ff67af0-8c30-449e-8e8b-ad334ec8d88c"
] | deanm@google.com@4ff67af0-8c30-449e-8e8b-ad334ec8d88c |
56112b70c8186e07b0a06d8323c70d09b21c0bf7 | b586cdffba52f45dcc518e918a71f4f34054ed41 | /dht11Summer.ino | 16499edc428cec7edef4431759c407431d985491 | [] | no_license | jumblies/dht11Summer | 9cebf712d2c7a33a52d03114970d739483b60b51 | d59ed6f472751677a687f037e81b12929904cb7f | refs/heads/master | 2021-01-23T07:50:31.254578 | 2017-03-31T20:09:45 | 2017-03-31T20:09:45 | 86,455,374 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,017 | ino | // DS1307 RTC ENTRIES ++++++++++++++++
// Date and time functions using a DS1307 RTC connected via I2C and Wire lib
#include <Wire.h>
#include "RTClib.h"
#include <TimeLord.h>
RTC_DS1307 rtc;
char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
// DHT11 Temperature and Humidity Sensors
#include "DHT.h" //include DHT library
#define DHTPIN 13 //define as DHTPIN the Pin 10 used to connect the Sensor
#define DHTTYPE DHT11 //define the sensor used(DHT11)
#define REDPIN 5
#define GREENPIN 6
#define BLUEPIN 3
unsigned long previousMillis = 0; //last time it was changed
unsigned long interval = 3000; //time delay between color changes to debounce temp variation 5min = 300,000
//problem currenty is to turn it on to start but not delay too much for the first color change.
// what is our longitude (west values negative) and latitude (south values negative)
// Greensboro, NC Latitude: 36.145833 | Longitude: -79.801728
float const LONGITUDE = -79.80;
float const LATITUDE = 36.14;
DHT dht(DHTPIN, DHTTYPE);//create an instance of DHT
/*setup*/
void setup() {
Serial.begin(9600); //initialize the Serial communication
// Critical setupline for establishing correct serial comms
while (!Serial); // for Leonardo/Micro/Zero
Serial.begin(9600);
if (! rtc.begin()) {
Serial.println("Couldn't find RTC");
while (1);
}
pinMode(A2, OUTPUT); //Setting the A2-A4 pins to output
digitalWrite(A2, LOW); //digital mode to power the RTC
pinMode(A3, OUTPUT); //without wires!
digitalWrite(A3, HIGH);
pinMode(12, OUTPUT);
digitalWrite(12, HIGH);
TimeLord tardis;
tardis.TimeZone(-4 * 60); // tell TimeLord what timezone your RTC is synchronized to. You can ignore DST
// as long as the RTC never changes back and forth between DST and non-DST
tardis.Position(LATITUDE, LONGITUDE); // tell TimeLord where in the world we are
// byte today[] = { 0, 0, 12, 29, 03, 2017 }; // store today's date (at noon) in an array for TimeLord to use
DateTime now = rtc.now();
byte today[] = {now.second(), now.minute(), now.hour(), now.day(), now.month(), now.year() };
Serial.print(now.year(), DEC);
Serial.print('/');
Serial.print(now.month(), DEC);
Serial.print('/');
Serial.print(now.day(), DEC);
Serial.print(" (");
Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
Serial.print(") ");
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.print(now.minute(), DEC);
Serial.print(':');
Serial.print(now.second(), DEC);
Serial.println();
delay(1000); //wait 1 seconds
Serial.println("Temperature and Humidity test!");//print on Serial monitor
Serial.println("T(F) \tH(%)"); //print on Serial monitor
dht.begin(); //initialize the Serial communication
//Turn the lights on so I know it's working
analogWrite(REDPIN, 255);
analogWrite(BLUEPIN, 255);
analogWrite(GREENPIN, 255);
}
/*loop*/
void loop() {
TimeLord tardis;
tardis.TimeZone(-4 * 60); // tell TimeLord what timezone your RTC is synchronized to. You can ignore DST
// as long as the RTC never changes back and forth between DST and non-DST
tardis.Position(LATITUDE, LONGITUDE); // tell TimeLord where in the world we are
// byte today[] = { 0, 0, 12, 29, 03, 2017 }; // store today's date (at noon) in an array for TimeLord to use
DateTime now = rtc.now();
byte today[] = {now.second(), now.minute(), now.hour(), now.day(), now.month(), now.year() };
//TimeLord Library Print times at init
if (tardis.SunRise(today)) // if the sun will rise today (it might not, in the [ant]arctic)
{
Serial.print("Sunrise: ");
Serial.print((int) today[tl_hour]);
Serial.print(":");
Serial.print((int) today[tl_minute]);
Serial.print(" ");
}
int sunriseHour = ((int) today[tl_hour]);
int sunriseMinute = ((int) today[tl_minute]);
if (tardis.SunSet(today)) // if the sun will set today (it might not, in the [ant]arctic)
{
Serial.print("Sunset: ");
Serial.print((int) today[tl_hour]);
Serial.print(":");
Serial.println((int) today[tl_minute]);
}
int sunsetHour = (int) today[tl_hour];
int sunsetMinute = (int) today[tl_minute];
float h = dht.readHumidity(); // reading Humidity
float t = dht.readTemperature(); // read Temperature as Celsius (the default)
// check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor!");
return;
}
t = (32 + (9 * t) / 5);
float farenheight = t;
Serial.print("Current conditions (Temp/Hum): "); //print current environmental conditions
Serial.print(t, 2); //print the temperature
Serial.print("\t");
Serial.println(h, 2); //print the humidity
delay(2000); //wait 2 seconds
Serial.print("Human time = ");
Serial.print(now.hour(), DEC);
Serial.print(':');
Serial.println(now.minute(), DEC);
Serial.print("Unixtime = ");
Serial.print(now.unixtime());
Serial.println("s");
Serial.print("Morning Lights from: ");
Serial.print(sunriseHour);
Serial.print(" until ");
Serial.println(sunriseHour + 2);
Serial.print("Evening Lights from: ");
Serial.print(sunsetHour);
Serial.print(":");
Serial.print(sunsetMinute);
Serial.print(" until ");
Serial.print(sunsetHour + 2);
Serial.print(":");
Serial.println(sunsetMinute);
if ((now.hour() >= sunsetHour && now.minute() >= sunsetMinute) && (now.hour() <= (sunsetHour + 2) && now.minute() <= sunsetMinute) || ((now.hour() >= sunriseHour && now.hour() <= (sunriseHour + 2)))) //kept simple for sunrise.
{
Serial.println("turn on the lights");
//Turn the lights on so I know it's working
analogWrite(REDPIN, 255);
analogWrite(BLUEPIN, 255);
analogWrite(GREENPIN, 255);
//Winter Version
if (farenheight > 85) {
analogWrite(REDPIN, 255);
analogWrite(BLUEPIN, 0);
analogWrite(GREENPIN, 0);
}
else if (farenheight <= 85 && farenheight >= 80) {
analogWrite(GREENPIN, 255);
analogWrite(BLUEPIN, 0);
analogWrite(REDPIN, 255);
}
else if (farenheight <= 80 && farenheight >= 70) {
analogWrite(GREENPIN, 150);
analogWrite(BLUEPIN, 150);
analogWrite(REDPIN, 0);
}
else if (farenheight <= 70 && farenheight >= 60) {
analogWrite(GREENPIN, 255);
analogWrite(BLUEPIN, 0);
analogWrite(REDPIN, 0);
}
else if (farenheight <= 60 && farenheight >= 50) {
analogWrite(GREENPIN, 0);
analogWrite(BLUEPIN, 150);
analogWrite(REDPIN, 150);
}
else {
analogWrite(BLUEPIN, 255);
analogWrite(REDPIN, 255);
analogWrite(GREENPIN, 255);
}
}
else { //Shut the lights off if the above conditions are not met
analogWrite(REDPIN, 0); //Meaning that it's not time for them to be on.
analogWrite(BLUEPIN, 0);
analogWrite(GREENPIN, 0);
}
}
| [
"glamke@gmail.com"
] | glamke@gmail.com |
0b9eaf4592d95336168486a6606620e0224525f6 | 57775b4c245723078fd43abc35320cb16f0d4cb6 | /UVA/12372.cpp | ed2a38d7c15f629f8175200c93aec464f70bc976 | [] | no_license | farhapartex/code-ninja | 1757a7292ac4cdcf1386fe31235d315a4895f072 | 168fdc915a4e3d3e4d6f051c798dee6ee64ea290 | refs/heads/master | 2020-07-31T16:10:43.329468 | 2020-06-18T07:00:34 | 2020-06-18T07:00:34 | 210,668,245 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 417 | cpp | #include<iostream>
#include<cstdio>
#include<stack>
#include<queue>
#include<map>
using namespace std;
int main()
{
int test,l,w,h;
scanf("%d",&test);
for(int i=1 ; i<=test; i++)
{
scanf("%d %d %d",&l, &w, &h);
if(l<=20 && w<=20 && h<=20)
{
printf("Case %d: good\n",i);
}
else
{
printf("Case %d: bad\n",i);
}
}
}
| [
"farhapartex@gmail.com"
] | farhapartex@gmail.com |
629d83ada6cca1feae21a95cfac99e05721028f0 | e55c376ba7258831a19cdaef7e77f2607dfa7215 | /Trees/ChildrenSum.cpp | f39fcf89a6c317d94041f954851d357c99c5639b | [] | no_license | abhishek2x/Data-Structures | f2ee9a4b3098bb650efe09f02edc0e757f007321 | 3dcd60310e54a3ac084af8a1f8e6b792ca8ef7ee | refs/heads/main | 2023-02-26T00:31:42.847361 | 2021-01-26T14:46:42 | 2021-01-26T14:46:42 | 325,213,596 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 798 | cpp | // Sum of children = parent data
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node *left, *right;
Node(int value) {
data = value;
left = NULL;
right = NULL;
}
};
bool IsCProperty(Node* root) {
if(root == NULL) {
return true;
}
if(root->left == NULL && root->right == NULL) {
return true;
}
int sum = 0;
if(root->left) {
sum += root->left->data;
}
if(root->right) {
sum += root->right->data;
}
if(root->data == sum && IsCProperty(root->left) && IsCProperty(root->right)) {
return true;
}
return false;
}
int main(){
Node *root = new Node(10);
root->left = new Node(5);
root->right = new Node(5);
root->left->left = new Node(2);
root->left->right = new Node(3);
cout << IsCProperty(root);
} | [
"abhisheksrivastavabbn@gmail.com"
] | abhisheksrivastavabbn@gmail.com |
46a2c29d3beb8ed635b2884c11c11046a97b95b3 | 8f27ca75187c121d9a815b00517175bc523f1801 | /Plugins/Voxel/Source/Voxel/Public/VoxelWorld.h | e6409ff9efa0502197b8d505c9dfa8adc7f4460a | [
"MIT"
] | permissive | Maverrin/FirstGame | 9991e84df316fef6afe7606b29d01f1eb8c375de | 9ff0eeb0948a4f223d31e03b2cbf35a955db9e9e | refs/heads/master | 2022-05-09T17:45:15.904563 | 2019-11-08T18:14:45 | 2019-11-08T18:14:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 36,306 | h | // Copyright 2018 Phyronnaz
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Templates/SubclassOf.h"
#include "Materials/MaterialInstanceDynamic.h"
#include "PhysicsEngine/BodyInstance.h"
#include "VoxelValue.h"
#include "VoxelMaterial.h"
#include "IntBox.h"
#include "VoxelSave.h"
#include "VoxelSpawners/VoxelGrassSpawner.h"
#include "VoxelSpawners/VoxelActorSpawner.h"
#include "VoxelRender/VoxelRenderFactory.h"
#include "VoxelRender/VoxelIntermediateChunk.h"
#include "VoxelConfigEnums.h"
#include "VoxelWorldGeneratorPicker.h"
#include "VoxelWorldGenerator.h"
#include "VoxelUtilities.h"
#include "VoxelPoolManager.h"
#include "VoxelWorld.generated.h"
class IVoxelRender;
class FVoxelData;
class FVoxelActorOctreeManager;
class UVoxelInvokerComponent;
class AVoxelWorldEditorInterface;
class AVoxelActor;
class UVoxelMaterialCollection;
class FVoxelPool;
class UVoxelMaterialInterface;
class AVoxelChunksOwner;
struct FVoxelActorSpawnInfo;
class UCurveFloat;
class FVoxelActorComputedChunksOctree;
class UHierarchicalInstancedStaticMeshComponent;
DECLARE_DYNAMIC_MULTICAST_DELEGATE(FOnClientConnection);
DECLARE_DYNAMIC_MULTICAST_DELEGATE(FOnWorldLoaded);
/**
* Voxel World actor class
*/
UCLASS()
class VOXEL_API AVoxelWorld : public AActor
{
GENERATED_BODY()
public:
UPROPERTY(BlueprintAssignable)
FOnClientConnection OnClientConnection;
UPROPERTY(BlueprintAssignable)
FOnWorldLoaded OnWorldLoaded;
UPROPERTY()
FVoxelMaterialsRefHolder MaterialsRef;
public:
AVoxelWorld();
public:
void AddActorInfos(const TArray<FVoxelActorSpawnInfo>& ActorInfos);
bool HaveActorsBeenCreated(const FIntBox& Bounds) const;
void NotifyActorsAreCreated(const FIntBox& Bounds);
UFUNCTION(BlueprintCallable, Category = "Voxel")
void EnableFloatingActorsInArea(const FIntBox& Bounds, TArray<AVoxelActor*>& OutActors);
UFUNCTION(BlueprintCallable, Category = "Voxel")
void EnableActorsInArea(const FIntBox& Bounds, TArray<AVoxelActor*>& OutActors);
UFUNCTION(BlueprintCallable, Category = "Voxel")
AVoxelActor* EnableInstanceInArea(UHierarchicalInstancedStaticMeshComponent* Component, const FIntBox& Bounds, int InstanceIndex);
UFUNCTION(BlueprintCallable, Category = "Voxel")
UClass* GetActorClassFromHISM(UHierarchicalInstancedStaticMeshComponent* Component);
UFUNCTION(BlueprintCallable, Category = "Voxel")
void AddInstance(TSubclassOf<AVoxelActor> VoxelActorClass, FTransform Transform);
UFUNCTION(BlueprintCallable, Category = "Voxel")
void RemoveInstance(UHierarchicalInstancedStaticMeshComponent* Component, const FIntBox& Bounds, int InstanceIndex);
public:
UFUNCTION(BlueprintCallable, Category = "Voxel")
void CreateWorld();
UFUNCTION(BlueprintCallable, Category = "Voxel")
void DestroyWorld(bool bClearMeshes = true);
// Create the world when in editor (not PIE)
void CreateInEditor(UClass* VoxelWorldEditorClass);
// Destroy the world when in editor (not PIE)
void DestroyInEditor();
void Recreate();
public:
void UpdateCollisionProfile();
public:
inline bool IsEditor() const { return PlayType == EPlayType::Editor; }
inline TSharedRef<FVoxelData, ESPMode::ThreadSafe> GetDataSharedPtr() const { return Data.ToSharedRef(); }
inline FVoxelData* GetData() const { return Data.Get(); }
inline FVoxelPool* GetPool() const { return Pool.Get(); }
inline UMaterialInstanceDynamic* GetMaterialInstance() const { return MaterialInstance; }
inline const FVoxelWorldGeneratorPicker GetWorldGeneratorPicker() const { return WorldGenerator; }
inline bool GetColorTransitions() const { return bColorTransitions; }
FVoxelWorldGeneratorInit GetInitStruct() const;
FVector GetChunkRelativePosition(const FIntVector& Position) const;
inline bool IsTessellationEnabled(int InLOD) const
{
return GetEnableTessellation() && InLOD <= GetTessellationMaxLOD();
}
inline const TArray<TWeakObjectPtr<UVoxelInvokerComponent>>& GetInvokers() const { return Invokers; }
inline bool IsDedicatedServer() const { return bIsDedicatedServer; }
inline TSharedPtr<const FVoxelGrassSpawner_ThreadSafe, ESPMode::ThreadSafe> GetGrassSpawnerThreadSafe() const { return GrassSpawnerThreadSafe; }
inline TSharedPtr<const FVoxelActorSpawner_ThreadSafe, ESPMode::ThreadSafe> GetActorSpawnerThreadSafe() const { return ActorSpawnerThreadSafe; }
UMaterialInterface* GetVoxelMaterial(const FVoxelBlendedMaterial& Index) const;
UMaterialInterface* GetVoxelMaterialWithTessellation(const FVoxelBlendedMaterial& Index) const;
inline UMaterialInterface* GetVoxelMaterial(int InLOD, const FVoxelBlendedMaterial& Index) const
{
return IsTessellationEnabled(InLOD) ? GetVoxelMaterialWithTessellation(Index) : GetVoxelMaterial(Index);
}
inline UMaterialInterface* GetVoxelMaterial(int InLOD) const
{
auto* Result = IsTessellationEnabled(InLOD) ? GetVoxelMaterialWithTessellation() : GetVoxelMaterial();
return Result ? Result : MissingMaterial;
}
public:
/** Set a MID scalar (float) parameter value */
UFUNCTION(BlueprintCallable, meta=(Keywords = "SetFloatParameterValue"), Category="Rendering|Material")
void SetScalarParameterValue(FName ParameterName, float Value);
/** Set an MID texture parameter value */
UFUNCTION(BlueprintCallable, Category="Rendering|Material")
void SetTextureParameterValue(FName ParameterName, UTexture* Value);
/** Set an MID vector parameter value */
UFUNCTION(BlueprintCallable, meta=(Keywords = "SetColorParameterValue"), Category="Rendering|Material")
void SetVectorParameterValue(FName ParameterName, FLinearColor Value);
public:
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|General")
void SetOctreeDepth(int NewDepth);
UFUNCTION(BlueprintCallable, Category = "Voxel|General")
int GetOctreeDepth() const;
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|General")
void SetOverrideBounds(bool bNewOverrideBounds);
UFUNCTION(BlueprintCallable, Category = "Voxel|General")
bool GetOverrideBounds() const;
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|General")
void SetWorldBounds(FIntBox NewWorldBounds);
UFUNCTION(BlueprintCallable, Category = "Voxel|General")
FIntBox GetWorldBounds() const;
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|General")
void SetLODLimit(int NewLODLimit);
UFUNCTION(BlueprintCallable, Category = "Voxel|General")
int GetLODLimit() const;
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
void SetChunkCullingLOD(int NewChunkCullingLOD);
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
int GetChunkCullingLOD() const;
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|General")
void SetVoxelSize(float NewSize);
UFUNCTION(BlueprintCallable, Category = "Voxel|General")
float GetVoxelSize() const;
// CAN be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|General")
void SetVoxelMassMultiplierInKg(float NewVoxelMassMultiplierInKg);
UFUNCTION(BlueprintCallable, Category = "Voxel|General")
float GetVoxelMassMultiplierInKg() const;
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|General")
void SetWorldGeneratorObject(UVoxelWorldGenerator* NewGenerator);
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|General")
void SetWorldGeneratorClass(TSubclassOf<UVoxelWorldGenerator> NewGeneratorClass);
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|General")
void SetSaveObject(UVoxelWorldSaveObject* NewSaveObject);
UFUNCTION(BlueprintCallable, Category = "Voxel|General")
UVoxelWorldSaveObject* GetSaveObject() const;
// CAN be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|General")
void SetCreateWorldAutomatically(bool bNewCreateWorldAutomatically);
UFUNCTION(BlueprintCallable, Category = "Voxel|General")
bool GetCreateWorldAutomatically() const;
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|General")
void SetEnableUndoRedo(bool bNewEnableUndoRedo);
UFUNCTION(BlueprintCallable, Category = "Voxel|General")
bool GetEnableUndoRedo() const;
// CAN be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
void SetWaitForOtherChunksToAvoidHoles(bool bNewWaitForOtherChunksToAvoidHoles);
bool GetWaitForOtherChunksToAvoidHoles() const;
// CANNOT be called when created. Add to existing seeds
UFUNCTION(BlueprintCallable, Category = "Voxel|General")
void AddSeeds(const TMap<FString, int>& NewSeeds);
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|General")
void AddSeed(FString Name, int Value);
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|General")
void ClearSeeds();
UFUNCTION(BlueprintCallable, Category = "Voxel|General")
TMap<FString, int> GetSeeds() const;
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|General")
void SetEnableWorldRebasing(bool bNewEnableWorldRebasing);
UFUNCTION(BlueprintCallable, Category = "Voxel|General")
bool GetEnableWorldRebasing() const;
///////////////////////////////////////////////////////////////////////////////
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
void SetRenderType(EVoxelRenderType Type);
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
EVoxelRenderType GetRenderType() const;
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
void SetUVConfig(EVoxelUVConfig Config);
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
EVoxelUVConfig GetUVConfig() const;
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
void SetNormalConfig(EVoxelNormalConfig Config);
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
EVoxelNormalConfig GetNormalConfig() const;
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
void SetMaterialConfig(EVoxelMaterialConfig Config);
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
EVoxelMaterialConfig GetMaterialConfig() const;
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering", meta = (DisplayName = "Set VoxelWorld Material"))
void SetVoxelMaterial(UMaterialInterface* NewMaterial);
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering", meta = (DisplayName = "Get VoxelWorld Material"))
UMaterialInterface* GetVoxelMaterial() const;
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering", meta = (DisplayName = "Set VoxelWorld Material With Tessellation"))
void SetVoxelMaterialWithTessellation(UMaterialInterface* NewMaterial);
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering", meta = (DisplayName = "Get VoxelWorld Material With Tessellation"))
UMaterialInterface* GetVoxelMaterialWithTessellation() const;
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
void SetMaterialCollection(UVoxelMaterialCollection* NewMaterialCollection);
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
UVoxelMaterialCollection* GetMaterialCollection() const;
// CAN be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
void SetChunksFadeDuration(float NewChunksFadeDuration);
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
float GetChunksFadeDuration() const;
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
void SetEnableTessellation(bool NewEnableTessellation);
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
bool GetEnableTessellation() const;
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
void SetBoundsExtension(float NewBoundsExtension);
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
float GetBoundsExtension() const;
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
void SetTessellationMaxLOD(int NewTessellationMaxLOD);
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
int GetTessellationMaxLOD() const;
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
void SetGrassSpawner(UVoxelGrassSpawner* Spawner);
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
UVoxelGrassSpawner* GetGrassSpawner() const;
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
void SetActorSpawner(UVoxelActorSpawner* Spawner);
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
UVoxelActorSpawner* GetActorSpawner() const;
// CAN be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
void SetMaxGrassChunkLOD(int NewMaxGrassChunkLOD);
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
int GetMaxGrassChunkLOD() const;
// CAN be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
void SetMaxActorChunkLOD(int NewMaxActorChunkLOD);
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
int GetMaxActorChunkLOD() const;
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
void SetEnableGrassWhenEditing(bool bNewEnableGrassWhenEditing);
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
bool GetEnableGrassWhenEditing() const;
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering", meta = (DisplayName = "Set Distance Between Actor HISM In Voxels"))
void SetDistanceBetweenActorHISMInVoxels(int NewDistanceBetweenActorHISMInVoxels);
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering", meta = (DisplayName = "Get Distance Between Actor HISM In Voxels"))
int GetDistanceBetweenActorHISMInVoxels() const;
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
void SetLightingChannels(FLightingChannels NewLightingChannels);
UFUNCTION(BlueprintCallable, Category = "Voxel|Rendering")
FLightingChannels GetLightingChannels() const;
///////////////////////////////////////////////////////////////////////////////
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Collisions")
void SetMaxCollisionsLOD(int NewMaxCollisionsLOD);
UFUNCTION(BlueprintCallable, Category = "Voxel|Collisions")
int GetMaxCollisionsLOD() const;
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Collisions")
void SetCollisionPresets(FBodyInstance NewCollisionPresets);
UFUNCTION(BlueprintCallable, Category = "Voxel|Collisions")
FBodyInstance GetCollisionPresets() const;
///////////////////////////////////////////////////////////////////////////////
// CAN be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Performance")
void SetLODUpdateRate(float NewLODUpdateRate);
UFUNCTION(BlueprintCallable, Category = "Voxel|Performance")
float GetLODUpdateRate() const;
// CAN be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Performance")
void SetActorCullingUpdateRate(float NewActorCullingUpdateRate);
UFUNCTION(BlueprintCallable, Category = "Voxel|Performance")
float GetActorCullingUpdateRate() const;
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Performance")
void SetDontUseGlobalPool(bool bNewDontUseGlobalPool);
UFUNCTION(BlueprintCallable, Category = "Voxel|Performance")
bool GetDontUseGlobalPool() const;
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Performance")
void SetMeshThreadCount(int NewMeshThreadCount);
UFUNCTION(BlueprintCallable, Category = "Voxel|Performance")
int GetMeshThreadCount() const;
// CAN be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Performance")
void SetLODCurve(UCurveFloat* NewCurve);
UFUNCTION(BlueprintCallable, Category = "Voxel|Performance")
UCurveFloat* GetLODCurve() const;
// CAN be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Performance")
void SetOptimizeIndices(bool bNewOptimizeIndices);
UFUNCTION(BlueprintCallable, Category = "Voxel|Performance")
bool GetOptimizeIndices() const;
///////////////////////////////////////////////////////////////////////////////
// CANNOT be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Multiplayer")
void SetMultiplayer(bool bNewMultiplayer);
UFUNCTION(BlueprintCallable, Category = "Voxel|Multiplayer")
bool GetMultiplayer() const;
// CAN be called when created
UFUNCTION(BlueprintCallable, Category = "Voxel|Multiplayer")
void SetMultiplayerSyncRate(float NewMultiplayerSyncRate);
UFUNCTION(BlueprintCallable, Category = "Voxel|Multiplayer")
float GetMultiplayerSyncRate() const;
public:
// Is this world created?
UFUNCTION(BlueprintCallable, Category = "Voxel")
bool IsCreated() const;
// Bounds of this world
UFUNCTION(BlueprintCallable, Category = "Voxel")
FIntBox GetBounds() const;
// Number of mesh processing tasks not finished
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "Voxel")
int32 GetTaskCount() const;
public:
/**
* Convert position from world space to voxel space
* @param Position Position in world space
* @return Position in voxel space
*/
UFUNCTION(BlueprintCallable, Category = "Voxel")
FIntVector GlobalToLocal(const FVector& Position) const;
// Precision errors with large world offset
UFUNCTION(BlueprintCallable, Category = "Voxel")
FVector GlobalToLocalFloat(const FVector& Position) const;
/**
* Convert position from voxel space to world space
* @param Position Position in voxel space
* @return Position in world space
*/
UFUNCTION(BlueprintCallable, Category = "Voxel")
FVector LocalToGlobal(const FIntVector& Position) const;
// Precision errors with large world offset
UFUNCTION(BlueprintCallable, Category = "Voxel")
FVector LocalToGlobalFloat(const FVector& Position) const;
/**
* Get the 8 neighbors in voxel space of GlobalPosition
* @param GlobalPosition The position in world space
* @return The 8 neighbors in voxel space
*/
UFUNCTION(BlueprintCallable, Category = "Voxel")
TArray<FIntVector> GetNeighboringPositions(const FVector& GlobalPosition) const;
public:
/**
* Add chunks at position to update queue
* @param Position Position in voxel space
*/
UFUNCTION(BlueprintCallable, Category = "Voxel")
void UpdateChunksAtPosition(const FIntVector& Position);
/**
* Add chunks overlapping box to update queue
* @param Box Box
*/
UFUNCTION(BlueprintCallable, Category = "Voxel")
void UpdateChunksOverlappingBox(const FIntBox& Box, bool bRemoveHoles);
void UpdateChunksOverlappingBox(const FIntBox& Box, TFunction<void()> CallbackWhenUpdated);
/**
* Update all the chunks
*/
UFUNCTION(BlueprintCallable, Category = "Voxel")
void UpdateAll();
public:
// Get the render chunks LOD at Position
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "Voxel")
int GetLODAt(const FIntVector& Position) const;
// Is position in this world?
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "Voxel")
bool IsInWorld(const FIntVector& Position) const;
/**
* Is the position inside the world mesh? If false then it's outside, if true then it might inside
* @param Position Position in global space
*/
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "Voxel")
bool IsInside(const FVector& Position) const;
/**
* Get the intersection using voxel data. Doesn't depend on LOD. Useful for short distances, but really expensive for big ones
* @param Start The start of the raycast. The start and the end must have only one coordinate not in common
* @param End The end of the raycast. The start and the end must have only one coordinate not in common
* @param GlobalPosition The world position of the intersection if found
* @param VoxelPosition The voxel position of the intersection if found
* @return Has intersected?
*/
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "Voxel")
bool GetIntersection(const FIntVector& Start, const FIntVector& End, FVector& GlobalPosition, FIntVector& VoxelPosition) const;
/**
* Get the normal at the voxel position Position using gradient. May differ from the mesh normal
* @param Position Position in voxel space
*/
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "Voxel")
FVector GetNormal(const FIntVector& Position) const;
public:
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "Voxel")
float GetValue(const FIntVector& Position) const;
UFUNCTION(BlueprintCallable, Category = "Voxel")
void SetValue(const FIntVector& Position, float Value, bool bUpdateRender = true);
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "Voxel")
FVoxelMaterial GetMaterial(const FIntVector& Position) const;
UFUNCTION(BlueprintCallable, Category = "Voxel")
void SetMaterial(const FIntVector& Position, const FVoxelMaterial& Material, bool bUpdateRender = true);
public:
/**
* Get a save of the current world
* @return SaveArray
*/
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "Voxel")
void GetSave(FVoxelUncompressedWorldSave& OutSave) const;
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "Voxel")
void GetCompressedSave(FVoxelCompressedWorldSave& OutSave) const;
/**
* Load world from save
* @param Save Save to load from
* @param bReset Reset existing world? Set to false only if current world is unmodified
*/
UFUNCTION(BlueprintCallable, Category = "Voxel", meta = (AdvancedDisplay = "1"))
void LoadFromSave(const FVoxelUncompressedWorldSave& Save);
UFUNCTION(BlueprintCallable, Category = "Voxel", meta = (AdvancedDisplay = "1"))
void LoadFromCompressedSave(UPARAM(ref) FVoxelCompressedWorldSave& Save);
public:
/**
* Connect to the server
* @param Ip The ip of the server
* @param Port The port of the server
*/
UFUNCTION(BlueprintCallable, Category = "Voxel")
bool ConnectClient(const FString& Ip = TEXT("127.0.0.1"), int32 Port = 10000);
/**
* Start the server
* @param Ip The IP to accept connection. 0.0.0.0 to accept all
* @param Port The port of the server
*/
UFUNCTION(BlueprintCallable, Category = "Voxel")
void StartServer(const FString& Ip = TEXT("0.0.0.0"), int32 Port = 10000);
public:
// Undo last frame. bEnableUndoRedo must be true, and SaveFrame must have been called after any edits
UFUNCTION(BlueprintCallable, Category = "Voxel")
void Undo();
// Redo last undone frame. bEnableUndoRedo must be true, and SaveFrame must have been called after any edits
UFUNCTION(BlueprintCallable, Category = "Voxel")
void Redo();
// Save the edits since the last call to SaveFrame/Undo/Redo and clear the redo stack. bEnableUndoRedo must be true
UFUNCTION(BlueprintCallable, Category = "Voxel")
void SaveFrame();
// Clear all the frames. bEnableUndoRedo must be true
UFUNCTION(BlueprintCallable, Category = "Voxel")
void ClearFrames();
public:
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "Voxel")
void DrawDebugIntBox(const FIntBox& Box, float Lifetime = 1, float Thickness = 10, FLinearColor Color = FLinearColor::Red) const;
void DrawDebugIntBox(const FIntBox& Box, float Lifetime = 1, float Thickness = 10, FColor Color = FColor::Red, float BorderOffset = 0) const;
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "Voxel")
void DebugVoxelsInsideBox(FIntBox Box, FLinearColor Color = FLinearColor::Red, float Lifetime = 1, float Thickness = 1, bool bDebugDensities = true, FLinearColor TextColor = FLinearColor::Black) const;
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "Voxel")
void ClearCache(const TArray<FIntBox>& BoundsToKeepCached);
UFUNCTION(BlueprintCallable, BlueprintPure = false, Category = "Voxel")
void Cache(const TArray<FIntBox>& BoundsToCache);
UFUNCTION(BlueprintCallable, Category = "Voxel")
void AddOffset(const FIntVector& OffsetInVoxels, bool bMoveActor = true);
UFUNCTION(BlueprintCallable, Category = "Voxel")
void AddWorms(float Radius = 25, int Seed = 2727, FVector RotationAmplitude = FVector(10, 10, 90), FVector NoiseDir = FVector(1, 1, 1), float NoiseSegmentLength = 10, FVector Start = FVector(0, 0,0), FVector InitialDir = FVector(1, 1, -1), float VoxelSegmentLength = 50, int NumSegments = 100, float SplitProbability = 0.1, float SplitProbabilityGain = 0.1, int BranchMeanSize = 25, int BranchSizeVariation = 10);
public:
//~ Begin AActor Interface
void BeginPlay() override;
void EndPlay(EEndPlayReason::Type EndPlayReason) override;
void Tick(float DeltaTime) override;
void Serialize(FArchive& Ar) override;
void ApplyWorldOffset(const FVector& InOffset, bool bWorldShift) override;
void PostLoad() override;
#if WITH_EDITOR
bool ShouldTickIfViewportsOnly() const override;
bool CanEditChange(const UProperty* InProperty) const override;
void PostEditChangeProperty(FPropertyChangedEvent& PropertyChangedEvent) override;
#endif // WITH_EDITOR
//~ End AActor Interface
protected:
// WorldSizeInVoxel = CHUNK_SIZE * 2^Depth. Has little impact on performance
UPROPERTY(EditAnywhere, Category = "Voxel|General", meta = (ClampMin = "1", ClampMax = "25", UIMin = "1", UIMax = "25"))
int OctreeDepth = 10;
UPROPERTY()
int LOD_DEPRECATED;
// Size of an edge of the world
UPROPERTY(EditAnywhere, Category = "Voxel|General", meta = (ClampMin = "1"))
int WorldSizeInVoxel = FVoxelUtilities::GetSizeFromDepth<CHUNK_SIZE>(9);
UPROPERTY(EditAnywhere, Category = "Voxel|General")
bool bOverrideBounds = false;
UPROPERTY(EditAnywhere, Category = "Voxel|General", meta = (ClampMax = "-1", EditCondition = "bOverrideBounds"))
FIntBox WorldBounds;
// Chunks can't have a LOD higher than this. Useful is background has a too low resolution. WARNING: Don't set this too low, 5 under Octree Depth should be safe
UPROPERTY(EditAnywhere, Category = "Voxel|General", meta = (ClampMin = "0", ClampMax = "25", UIMin = "0", UIMax = "25", DisplayName = "LOD Limit"))
int LODLimit = MAX_WORLD_DEPTH - 1;
// Chunks with a LOD strictly higher than this won't be rendered
UPROPERTY(EditAnywhere, Category = "Voxel|General", meta = (ClampMin = "0", ClampMax = "25", UIMin = "0", UIMax = "25"))
int ChunkCullingLOD = MAX_WORLD_DEPTH - 1;
// Size of a voxel in cm
UPROPERTY(EditAnywhere, Category = "Voxel|General")
float VoxelSize = 100;
// Mass in kg of a voxel (multiplied by its density)
UPROPERTY(EditAnywhere, Category = "Voxel|General")
float VoxelMassMultiplierInKg = 1;
// Generator of this world
UPROPERTY(EditAnywhere, Category = "Voxel|General")
FVoxelWorldGeneratorPicker WorldGenerator;
// Automatically loaded on creation
UPROPERTY(EditAnywhere, Category = "Voxel|General")
UVoxelWorldSaveObject* SaveObject = nullptr;
UPROPERTY(EditAnywhere, Category = "Voxel|General")
bool bCreateWorldAutomatically = false;
// Keep all the changes in memory to enable undo/redo. Can be expensive
UPROPERTY(EditAnywhere, Category = "Voxel|General")
bool bEnableUndoRedo = false;
// Less holes, but might look more laggy
UPROPERTY(EditAnywhere, Category = "Voxel|General")
bool bWaitForOtherChunksToAvoidHoles = true;
UPROPERTY(EditAnywhere, Category = "Voxel|General", meta = (ClampMin = "1", UIMin = "1"))
TMap<FString, int> Seeds;
// If true, the voxel world will try to stay near its original coordinates when rebasing, and will offset the voxel coordinates instead
UPROPERTY(EditAnywhere, Category = "Voxel|General")
bool bEnableWorldRebasing = false;
//////////////////////////////////////////////////////////////////////////////
UPROPERTY(EditAnywhere, Category = "Voxel|Rendering")
EVoxelRenderType RenderType = EVoxelRenderType::MarchingCubes;
UPROPERTY(EditAnywhere, Category = "Voxel|Rendering")
EVoxelUVConfig UVConfig = EVoxelUVConfig::GlobalUVs;
UPROPERTY(EditAnywhere, Category = "Voxel|Rendering")
EVoxelNormalConfig NormalConfig = EVoxelNormalConfig::GradientNormal;
UPROPERTY(EditAnywhere, Category = "Voxel|Rendering")
EVoxelMaterialConfig MaterialConfig = EVoxelMaterialConfig::RGB;
// The material of the world
UPROPERTY(EditAnywhere, Category = "Voxel|Rendering", meta = (DisplayName = "VoxelWorld Material"))
UMaterialInterface* VoxelMaterial = nullptr;
UPROPERTY(EditAnywhere, Category = "Voxel|Rendering", meta = (DisplayName = "VoxelWorld Material With Tessellation", EditCondition ="bEnableTessellation"))
UMaterialInterface* VoxelMaterialWithTessellation = nullptr;
UPROPERTY(EditAnywhere, Category = "Voxel|Rendering")
UVoxelMaterialCollection* MaterialCollection;
UPROPERTY(EditAnywhere, Category = "Voxel|Rendering")
bool bEnableTessellation = false;
// Increases the chunks bounding boxes, useful when using tessellation
UPROPERTY(EditAnywhere, Category = "Voxel|Rendering", meta = (EditCondition ="bEnableTessellation"))
float BoundsExtension = 0;
// Inclusive. Chunks with a LOD higher than that will use a non tessellated material
UPROPERTY(EditAnywhere, Category = "Voxel|Rendering", meta = (ClampMin = "0", ClampMax = "25", UIMin = "0", UIMax = "25", EditCondition ="bEnableTessellation"))
int TessellationMaxLOD = 0;
UPROPERTY(EditAnywhere, Category = "Voxel|Rendering", meta = (ClampMin = "0", UIMin = "0"))
float ChunksFadeDuration = 1;
UPROPERTY(EditAnywhere, Category = "Voxel|Rendering")
UVoxelGrassSpawner* GrassSpawner = nullptr;
UPROPERTY(EditAnywhere, Category = "Voxel|Rendering")
UVoxelActorSpawner* ActorSpawner = nullptr;
// Chunks with a LOD higher than this won't have any grass
UPROPERTY(EditAnywhere, Category = "Voxel|Rendering", meta = (ClampMin = "0", UIMin = "0"))
int MaxGrassChunkLOD = 0;
// Chunks with a LOD higher than this won't have any actor spawned. Warning: setting this too high will create precision errors
UPROPERTY(EditAnywhere, Category = "Voxel|Rendering", meta = (ClampMin = "0", UIMin = "0"))
int MaxActorChunkLOD = 0;
UPROPERTY(EditAnywhere, Category = "Voxel|Rendering")
bool bEnableGrassWhenEditing = false;
// Distance Between Actor Hierarchical Instanced Static Mesh Components In Voxels
UPROPERTY(EditAnywhere, Category = "Voxel|Rendering", meta = (DisplayName = "Distance Between Actor HISM In Voxels"))
int DistanceBetweenActorHISMInVoxels = 256;
UPROPERTY(EditAnywhere, Category = "Voxel|Rendering")
FLightingChannels LightingChannels;
//////////////////////////////////////////////////////////////////////////////
// Max LOD to compute collisions on. Inclusive.
UPROPERTY(EditAnywhere, Category = "Voxel|Collisions", meta = (ClampMin = "0", UIMin = "0"))
int MaxCollisionsLOD = 3;
UPROPERTY(EditAnywhere, Category = "Voxel|Collisions", meta = (ShowOnlyInnerProperties))
FBodyInstance CollisionPresets;
//////////////////////////////////////////////////////////////////////////////
// Number of LOD update per second
UPROPERTY(EditAnywhere, Category = "Voxel|Performance", meta = (ClampMin = "0.000001", UIMin = "0.000001"), DisplayName = "LOD Update Rate")
float LODUpdateRate = 15;
// Number of actor culling update per second
UPROPERTY(EditAnywhere, Category = "Voxel|Performance", meta = (ClampMin = "0.000001", UIMin = "0.000001"))
float ActorCullingUpdateRate = 1;
UPROPERTY(EditAnywhere, Category = "Voxel|Performance")
bool bDontUseGlobalPool = true;
// Number of threads allocated for the mesh processing. Setting it too high may impact performance
UPROPERTY(EditAnywhere, Category = "Voxel|Performance", meta = (ClampMin = "1", UIMin = "1", EditCondition = "bDontUseGlobalPool"))
int MeshThreadCount = 2;
// X = distance in voxels, Y = LOD (rounded up). Expensive, if you can leave it unset
UPROPERTY(EditAnywhere, Category = "Voxel|Performance")
UCurveFloat* LODCurve;
// If true, the mesh indices will be sorted to improve GPU cache performance. Adds a cost to the async mesh building. If you don't see any perf difference, leave it off
UPROPERTY(EditAnywhere, Category = "Voxel|Performance")
bool bOptimizeIndices = false;
//////////////////////////////////////////////////////////////////////////////
// Is this world multiplayer?
UPROPERTY(EditAnywhere, Category = "Voxel|Multiplayer")
bool bMultiplayer = false;
// Number of sync per second
UPROPERTY(EditAnywhere, Category = "Voxel|Multiplayer", meta = (EditCondition = "bMultiplayer"))
float MultiplayerSyncRate = 15;
//////////////////////////////////////////////////////////////////////////////
public:
UPROPERTY(EditAnywhere, Category = "Voxel|Debug")
bool bShowWorldBounds = false;
UPROPERTY(EditAnywhere, Category = "Voxel|Debug")
bool bShowAllRenderChunks = false;
UPROPERTY(EditAnywhere, Category = "Voxel|Debug")
bool bColorTransitions = false;
UPROPERTY(EditAnywhere, Category = "Voxel|Debug", meta = (EditCondition = "bShowWorldBounds"))
float WorldBoundsThickness = 100;
UPROPERTY(EditAnywhere, Category = "Voxel|Debug")
bool bShowInvokersBounds = false;
UPROPERTY(EditAnywhere, Category = "Voxel|Debug", meta = (EditCondition = "bShowInvokersBounds"))
float InvokersBoundsThickness = 100;
UPROPERTY(EditAnywhere, Category = "Voxel|Debug")
bool bShowDataOctreeLeavesStatus = false;
UPROPERTY(EditAnywhere, Category = "Voxel|Debug", meta = (EditCondition = "bShowDataOctreeLeavesStatus"))
bool bHideEmptyDataOctreeLeaves = true;
UPROPERTY(EditAnywhere, Category = "Voxel|Debug", meta = (EditCondition = "bShowDataOctreeLeavesStatus"))
float DataOctreeLeavesThickness = 50;
UPROPERTY(EditAnywhere, Category = "Voxel|Debug")
bool bShowUpdatedChunks = false;
UPROPERTY(EditAnywhere, Category = "Voxel|Debug", meta = (EditCondition = "bShowUpdatedChunks"))
float UpdatedChunksThickness = 50;
UPROPERTY(EditAnywhere, Category = "Voxel|Debug", meta = (EditCondition = "bMultiplayer"))
bool bDebugMultiplayer = false;
private:
UPROPERTY()
UMaterialInterface* MissingMaterial;
UPROPERTY(Transient)
AVoxelWorldEditorInterface* VoxelWorldEditor;
// Material to copy interp param from
UPROPERTY(Transient)
UMaterialInstanceDynamic* MaterialInstance;
enum class EPlayType
{
Destroyed,
Editor,
Normal
};
EPlayType PlayType = EPlayType::Destroyed;
FVoxelPoolRef Pool;
TSharedPtr<FVoxelData, ESPMode::ThreadSafe> Data;
TSharedPtr<IVoxelRender> Render;
TSharedPtr<class FVoxelCacheManager> CacheManager;
bool bIsCreated = false;
int InvokerComponentChangeVersion = -1;
bool bWorldLoadAlreadyFinished = false;
bool bIsDedicatedServer = false;
FTimerHandle CacheDebugHandle;
TArray<TWeakObjectPtr<UVoxelInvokerComponent>> Invokers;
// Position of the voxel world actor in voxel space
FIntVector WorldOffset = FIntVector::ZeroValue;
private:
TSharedPtr<class FVoxelTcpSocket> Socket;
TSharedPtr<class FVoxelNetworkingServer> NetworkServer;
TSharedPtr<class FVoxelNetworkingClient> NetworkClient;
FThreadSafeCounter OnClientConnectionTrigger;
TSharedPtr<FVoxelGrassSpawner_ThreadSafe, ESPMode::ThreadSafe> GrassSpawnerThreadSafe;
TSharedPtr<FVoxelActorSpawner_ThreadSafe, ESPMode::ThreadSafe> ActorSpawnerThreadSafe;
float NextSyncTime = 0;
float NextActorCullingUpdateTime = 0;
TSharedPtr<FVoxelActorOctreeManager> ActorOctree;
TSharedPtr<FVoxelActorComputedChunksOctree> ActorComputedChunksOctree;
private:
// Create the world
void CreateWorldInternal(
EPlayType InPlayType,
UVoxelGrassSpawner* InGrassSpawner,
UVoxelActorSpawner* InActorSpawner,
bool bInMultiplayer,
bool bInEnableUndoRedo,
bool bInDontUseGlobalPool);
// Destroy the world
void DestroyWorldInternal();
// Receive data from server
void ReceiveData();
// Send data to clients
void SendData();
void TriggerOnClientConnection();
};
/**
* Interface to use the VoxelWorldEditor in the VoxelEditor module
*/
UCLASS(notplaceable, HideCategories = ("Tick", "Replication", "Input", "Actor", "Rendering", "Hide"))
class VOXEL_API AVoxelWorldEditorInterface : public AActor
{
GENERATED_BODY()
public:
virtual void Init(TWeakObjectPtr<AVoxelWorld> NewWorld) {}
}; | [
"eigrads@hotmail.com"
] | eigrads@hotmail.com |
e95fc32f1d76b507775324e784bcdb773f6b1ba2 | 332afb2e008ad048274c1e65705c96f9a891b420 | /Timer/Timer/timer.h | af365106cdc3299f9d2cde52eaf2fbc82ec731b3 | [] | no_license | jkfly100/osg_test | 9957ce8ed8b8be31e4a8eb542f0676daa36c04f7 | 97a6453aeed38e81c7084ab0e88d6847819afe72 | refs/heads/master | 2020-09-01T13:21:07.265938 | 2019-11-06T02:32:25 | 2019-11-06T02:32:25 | 218,967,006 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 587 | h | #pragma once
#ifndef __TIMER_H__
#define __TIMER_H__
#include <Windows.h>
#include <iostream>
#include <functional>
#include <Windows.h>
namespace test
{
class timer
{
using timerCallBack = std::function<void(void)>;
public:
timer(int initilaTime, int periodicTime, timer::timerCallBack && cb);
~timer();
void start();
void stop();
private:
int creatThread();
void setTimer(int initialTime, int periodicTime);
private:
timerCallBack _cb;
int _fd;
int _initialTime;
int _periodicTime;
bool _isStart;
timerCallBack _cb;
};
}
#endif // !__TIMER_H__
| [
"641261684@qq.com"
] | 641261684@qq.com |
a26b6c82e7a5cd83f1a8f6d7463befc9c5ae05ab | 17e3c01e957d8aec59fade0d7987ef6042804195 | /Constructors/static_count.cpp | 6ad50fff9b00bb6fc834f4c9d1fbf58f959cf4a7 | [] | no_license | shashank-simha/CPP-Lab | 706113a70c018d2c11f864dbe1e845d6d4e56a92 | 7e3156f15e62aee7625c23a93f7b5a864c84c1d8 | refs/heads/master | 2020-04-20T05:41:43.237951 | 2019-02-15T07:54:22 | 2019-02-15T07:54:22 | 168,662,422 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 285 | cpp | #include<iostream>
using namespace std;
class counter
{
static int number;
public: counter()
{
++number;
cout<<"number of objects created is"<<counter::number<<endl;
}
};
int counter::number=0;
int main()
{
counter obj1,obj2,obj3;
return 0;
}
| [
"shashanksimha183@gmail.com"
] | shashanksimha183@gmail.com |
f9728177c51a2be19fd1d539b52e7dd9734a3afd | b22588340d7925b614a735bbbde1b351ad657ffc | /athena/Database/APR/FileCatalog/src/FCSystemTools.cpp | 25385a4c1008c0952b3846a615ecc1b50088c45d | [] | no_license | rushioda/PIXELVALID_athena | 90befe12042c1249cbb3655dde1428bb9b9a42ce | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | refs/heads/master | 2020-12-14T22:01:15.365949 | 2020-01-19T03:59:35 | 2020-01-19T03:59:35 | 234,836,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 650 | cpp | /*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
#include "FileCatalog/FCSystemTools.h"
#include <sys/stat.h>
#include <cstdlib>
#ifndef POOL_URIPARSER_H
#include "FileCatalog/URIParser.h"
#endif
#include <sstream>
namespace pool{
const char* FCSystemTools::GetEnv(const char* key){
return getenv(key);
}
bool FCSystemTools::FileExists(const char* filename){
struct stat fs;
if(stat(filename, &fs) != 0) {
return false;
}else{
return true;
}
}
std::string FCSystemTools::itostr(const int i){
std::ostringstream ost;
ost<<i;
return ost.str();
}
} // ns pool
| [
"rushioda@lxplus754.cern.ch"
] | rushioda@lxplus754.cern.ch |
94afdab49d77f096e0c07f88f8314802524f0ede | 3228ed23b07cef997713a36438629f3562557ea0 | /Codeforces/Codeforces Round 690 Div. 3/F_The_Treasure_of_The_Segments/F_The_Treasure_of_The_Segments.cpp | 20bade7c17117d05aad2d753a1e41b65acce8525 | [] | no_license | Janmansh/CompetitiveProgramming | 6069c295e183c2cd18582dc4f008de8529ec7dd1 | 6d35a30a8c44fd36dc5eafe46389a071c59333a0 | refs/heads/main | 2023-08-22T10:17:40.142484 | 2021-10-15T16:20:36 | 2021-10-15T16:20:36 | 372,047,169 | 1 | 3 | null | 2021-10-04T21:01:04 | 2021-05-29T18:42:44 | C++ | UTF-8 | C++ | false | false | 1,583 | cpp | #include<bits/stdc++.h>
using namespace std;
#define ll long long
#define int long long
#define pb push_back
#define mod 1000000007
#define mp make_pair
ll fact[200005];
ll powermod(ll x,ll y){
if(y==0) return 1;
ll temp = powermod( x,y/2 )%mod;
if( y%2 ){
return (((temp*temp)%mod)*x%mod);
}
return (temp*temp)%mod;
}
ll power(ll x,ll y){
if(y==0) return 1;
ll temp = power( x,y/2 );
if( y%2 ){
return (((temp*temp))*x);
}
return (temp*temp);
}
int gcd (int a, int b) {
return b ? gcd (b, a % b) : a;
}
ll inv(ll a, ll p){
return powermod(a,mod-2);
}
ll nCr(ll n, ll r, ll p){
if(r > n) return 0;
ll t1 = fact[n];
ll t2 = inv(fact[r],p);
ll t3 = inv(fact[n-r],p);
return (((t1*t2)%p)*t3)%p;
}
void solve(){
ll n,i,j; cin>>n;
vector<pair<int,int>>v;
ll l,r;
vector<int>le,ri;
for(i=0;i<n;i++){
cin>>l>>r;
v.pb(mp(l,r));
le.pb(l);
ri.pb(r);
}
sort(le.begin(),le.end());
sort(ri.begin(),ri.end());
ll ans=n;
for(i=0;i<n;i++){
ll k1,k2;
//auto it1 = lower_bound(ri.begin(),ri.end(),v[i].first);
k1=distance(ri.begin(), lower_bound(ri.begin(),ri.end(),v[i].first));
//it1--;
//k1 = it1-ri.begin();
k2=distance(le.begin(),upper_bound(le.begin(),le.end(),v[i].second));
k2=n-k2;
ans=min(ans,k1+k2);
}
cout<<ans<<"\n";
return;
}
signed main(){
ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
ll t=1;
cin>>t;
fact[0]=1;
for(int i=1;i<200001;i++){
fact[i]=i*fact[i-1];
fact[i]%=mod;
}
while (t--){
solve();
}
return 0;
} | [
"janmansh.191cs205@nitk.edu.in"
] | janmansh.191cs205@nitk.edu.in |
7a2ae583df123526a1076dd27fbde956b1f5878e | a3da88064ce11eef6094078db7cecf40facda99b | /benchmark/Voter_txns.hh | cbd958fdb471cacb5f3437c275cccf9f240e2908 | [
"MIT"
] | permissive | readablesystems/sto | e472d4eb6669a6cef5d1bf60a2ca5d5de0e6aaff | e477fd6abc9f084583366213441499a6b969162d | refs/heads/master | 2023-04-03T10:41:51.484877 | 2021-09-28T23:51:48 | 2021-09-28T23:51:48 | 121,050,178 | 48 | 23 | MIT | 2022-08-25T10:54:08 | 2018-02-10T20:11:13 | C++ | UTF-8 | C++ | false | false | 3,127 | hh | #pragma once
#include "Voter_bench.hh"
namespace voter {
template <typename DBParams>
void voter_runner<DBParams>::run_txn_vote(const phone_number_str& tel, int32_t contestant_number) {
TRANSACTION {
bool success = vote_inner(tel, contestant_number);
TXN_DO(success);
} RETRY(true);
}
template <typename DBParams>
bool voter_runner<DBParams>::vote_inner(const phone_number_str& tel, int32_t id) {
bool success, result;
uintptr_t row;
const void *value;
// check contestant number
std::tie(success, result, std::ignore, std::ignore) = db.tbl_contestant().select_row(contestant_key(id), RowAccess::None);
if (!success)
return false;
if (!result)
return true;
// check and maintain view: votes by phone number
std::tie(success, result, row, value) = db.view_votes_by_phone().select_row(v_votes_phone_key(tel), RowAccess::UpdateValue);
if (!success)
return false;
if (result) {
auto v_ph_row = reinterpret_cast<const v_votes_phone_row *>(value);
auto new_row = Sto::tx_alloc(v_ph_row);
if (new_row->count >= constants::max_votes_per_phone_number) {
db.view_votes_by_phone().update_row(row, new_row);
return true;
} else {
new_row->count += 1;
db.view_votes_by_phone().update_row(row, new_row);
}
} else {
auto temp_row = Sto::tx_alloc<v_votes_phone_row>();
temp_row->count = 0;
std::tie(success, result) = db.view_votes_by_phone().insert_row(v_votes_phone_key(tel), temp_row);
if (!success)
return false;
assert(!result);
}
// look up state
std::tie(success, result, std::ignore, value) = db.tbl_areacode_state().select_row(area_code_state_key(tel.area_code), RowAccess::None);
if (!success)
return false;
assert(result);
auto st_row = reinterpret_cast<const area_code_state_row *>(value);
// insert vote
auto vote_id = (int32_t)db.tbl_votes().gen_key();
votes_key vk(vote_id);
auto vr = Sto::tx_alloc<votes_row>();
vr->state = st_row->state;
vr->tel.area_code = tel.area_code;
vr->tel.number = tel.number;
vr->contestant_number = id;
vr->created = "null";
std::tie(success, result) = db.tbl_votes().insert_row(vk, vr);
if (!success)
return false;
assert(!result);
// maintain view: votes by id and state
std::tie(success, result, row, value) = db.view_votes_by_id_state().select_row(v_votes_id_state_key(id, vr->state), RowAccess::UpdateValue);
if (!success)
return false;
if (result) {
auto new_row = Sto::tx_alloc(reinterpret_cast<const v_votes_id_state_row *>(value));
new_row->count += 1;
db.view_votes_by_id_state().update_row(row, new_row);
} else {
auto new_row = Sto::tx_alloc<v_votes_id_state_row>();
std::tie(success, result) = db.view_votes_by_id_state().insert_row(v_votes_id_state_key(id, vr->state), new_row);
if (!success)
return false;
assert(!result);
}
return true;
}
};
| [
"yihehuang@g.harvard.edu"
] | yihehuang@g.harvard.edu |
55c6db5ece149840b45f8d811e188ecaafffa822 | 25cc5431b5d30c0f58042e4a6f114873a5a6140a | /atcoder/abc/115/c.cpp | e9c07754739d38efdd74a3a47704e2d03f9c2d19 | [] | no_license | r-chiba/competitive_programming | bf488cb61a404913771dd87e5cb4a8ce59d883ab | 8ffc0950739eb179e7cc9b6ccb9a5985efb21db0 | refs/heads/master | 2021-07-16T20:18:10.662719 | 2020-06-13T05:26:36 | 2020-06-13T05:26:36 | 172,166,016 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,489 | cpp | // {{{
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <complex>
#include <vector>
#include <list>
#include <set>
#include <queue>
#include <stack>
#include <map>
#include <string>
#include <algorithm>
#include <numeric>
using namespace std;
#define fi first
#define se second
#define pb push_back
#define mp make_pair
#define FOR(i, a, b) for(ll i = static_cast<ll>(a); i < static_cast<ll>(b); i++)
#define FORR(i, a, b) for(ll i = static_cast<ll>(a); i >= static_cast<ll>(b); i--)
#define REP(i, n) for(ll i = 0ll; i < static_cast<ll>(n); i++)
#define REPR(i, n) for(ll i = static_cast<ll>(n); i >= 0ll; i--)
#define ALL(x) (x).begin(), (x).end()
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> P;
typedef pair<ll, ll> LP;
typedef pair<int, P> IP;
typedef pair<ll, LP> LLP;
const int dx[] = {1, -1, 0, 0};
const int dy[] = {0, 0, 1, -1};
constexpr int INF = 100000000;
constexpr ll LINF = 10000000000000000ll;
constexpr int MOD = static_cast<int>(1e9 + 7);
constexpr double EPS = 1e-9;
// }}}
ll N, K;
ll h[100000];
void init()
{
}
void solve()
{
ll ret = LINF;
sort(h, h+N);
REP(i, N-K+1){
ret = min(ret, h[i+K-1]-h[i]);
}
cout << ret << endl;
}
int main()
{
cin.tie(0);
ios::sync_with_stdio(false);
cin >> N >> K;
REP(i, N){
cin >> h[i];
}
solve();
return 0;
}
// vim:set foldmethod=marker:
| [
"ryuichiro.chiba@gmail.com"
] | ryuichiro.chiba@gmail.com |
2d73aa3482ec0560f8d1370eef70f87b5463c7e2 | 0c24202e9e2ec494dd86f95c7eef6dbad10b938d | /source/homework_STEP/copy_constructor/src/main.cpp | f424cbcdd6fb1a57ac1378156c7a94cf88dbf861 | [] | no_license | AlexanderLukashuk/MyRepository | 78aee7e8cb064211435cb35b8cf2d1ff95817c29 | 3e5070cd7c9beda6264b67b9f3c56a78b0fd35a9 | refs/heads/master | 2022-05-03T12:42:51.504274 | 2022-03-10T16:34:47 | 2022-03-10T16:34:47 | 220,230,823 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 180 | cpp | #include <iostream>
#include "../include/copy.hpp"
using namespace std;
int main()
{
Book book1;
Book book2("1984", "George Orwell", 320);
cout << book2.toString();
} | [
"sanya@Sergejs-MacBook-Air.local"
] | sanya@Sergejs-MacBook-Air.local |
f98290fc64880a64bd466eeac7f5473843b9548b | 6aaa710db4d0ff2999c7b60bb593d4379365f996 | /Source/130429ReadFiles/Tree.h | 09aed602f7515a886b0eac5ed53bfd4a65e9a0c6 | [] | no_license | PhuongHoangMinh/FlockSimulation | b936bdaff5f6b932bb6f11c81017bca7ae6defe2 | 4b2de5df9e2b91e31ce0b33419b4a49e94aab61d | refs/heads/master | 2020-07-10T09:54:22.245496 | 2017-04-12T07:07:32 | 2017-04-12T07:07:32 | 68,710,728 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,553 | h | #ifndef TREE_H
#define TREE_H
#include <vector>
#include "Mesh.h"
#include "GameWorld.h"
#include "AABB.h"
#include <gl/glut.h>
#include <gl/gl.h>
class GameWorld;
class AABB;
class Tree
{
private:
GLfloat x;
GLfloat y;
GLfloat z;
Mesh m_pMesh;
bool m_bFired;
GameWorld* m_pWorld;
GLuint m_iID; // ID from glGenList()
//GLuint m_iIDNoText;
GLfloat scale;
AABB* m_Bounding;
public:
Tree(float valx,
float valy,
float valz,
Mesh mesh,
GameWorld* world,
float fscale): m_pWorld(world), m_pMesh(mesh), x(valx), y(valy), z(valz), scale(fscale)
{
setFired(false);
m_iID = glGenLists(1);
glNewList(m_iID, GL_COMPILE);
this->Render();
glEndList();
/*m_iIDNoText = glGenLists(1);
glNewList(m_iIDNoText, GL_COMPILE);
this->RenderNoText();
glEndList();*/
Vector3D posB(this->x, this->y, this->z);
Vector3D radius(0.4, 0.125, 0.25);
m_Bounding = new AABB(posB, radius);
}
Mesh getMesh()const {return m_pMesh;}
void setMesh(const Mesh valMesh) {m_pMesh = valMesh;}
GLfloat getX()const {return x;}
GLfloat getY()const {return y;}
GLfloat getZ()const {return z;}
bool isFired()const {return m_bFired;}
GLuint getID()const{ return m_iID;}
AABB* getAABB()const{return m_Bounding;}
//GLuint getIDNoText()const{return m_iIDNoText;}
void setAABB(AABB* val) {m_Bounding = val;}
void setFired(bool val) {m_bFired = val;}
void setX(GLfloat val) {x = val;}
void setY(GLfloat val) {y = val;}
void setZ(GLfloat val) {z = val;}
//void Update();
void Render();
};
#endif | [
"phuonghm@postech.ac.kr"
] | phuonghm@postech.ac.kr |
35bdcba0dcbb50bc10f8b09653ab30aa3baac13b | 2b891759cc3db01eedbe4111b5cae5820efdcd84 | /841.钥匙和房间.cpp | 37aec5f0c166f448ebb08e81cb37cdc15271d9af | [] | no_license | fxianglong/leetcode | 84d7fb1fbfee5a4e7907b36d846aa45145646b20 | a2a20079354c03867edd59fc974d5f3d1a5e2b61 | refs/heads/master | 2023-05-07T04:10:22.559292 | 2021-05-29T14:03:47 | 2021-05-29T14:03:47 | 278,635,307 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 355 | cpp | class Solution {
public:
vector<int> vis;
int num;
void dfs(vector<vector<int>>& rooms, int x) {
vis[x] = true;
num++;
for (auto& it : rooms[x]) {
if (!vis[it]) {
dfs(rooms, it);
}
}
}
bool canVisitAllRooms(vector<vector<int>>& rooms) {
int n = rooms.size();
num = 0;
vis.resize(n);
dfs(rooms, 0);
return num == n;
}
}; | [
"1244190336@qq.com"
] | 1244190336@qq.com |
1a927a41f10e0d825d08d054aaf043404e025328 | 9460ff0dd7b7cc09b2330da534414c34e2132ffb | /server.h | 8850392b72996cd52ea6c188164b782d271a39a3 | [] | no_license | entrnickvana/like_a_g9 | b5675392610617f1540bd54df348d43c22472577 | e91ec38227b8ae7218dab1c25f4460f36e44efad | refs/heads/master | 2020-03-25T00:37:30.661556 | 2018-08-01T18:50:17 | 2018-08-01T18:50:17 | 143,195,497 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 348 | h | #ifndef SERVER_H
#define SERVER_H
#include <QObject>
#include <QDebug>
#include <QTcpServer>
#include <QTcpSocket>
#include <iostream>
class Server : public QObject
{
Q_OBJECT
public:
explicit Server(QObject *parent = nullptr);
signals:
public slots:
void newConnection();
private:
QTcpServer* server;
};
#endif // SERVER_H
| [
"Nick.jwl123@gmail.com"
] | Nick.jwl123@gmail.com |
0cedb1f3f16569eeb1696a1ab36d01a906175234 | b22167cc6b06d3029056aa1fbd2e5905667658ce | /TP3/Test.cpp | b6e2cd887fb7304b3467028238a9570c743ac4c9 | [] | no_license | leonorcm/AEDA_tps | b2db0f06d77728c06b2af69ec4830821af52da06 | 2b4c8a55f24205f093b9e1946033af4f1ce969b6 | refs/heads/master | 2020-04-01T08:03:45.569617 | 2018-10-28T19:15:12 | 2018-10-28T19:15:12 | 153,015,970 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 5,431 | cpp | #include "cute.h"
#include "ide_listener.h"
#include "cute_runner.h"
#include "zoo.h"
#include <fstream>
using namespace std;
void test_a_criarAnimais() {
Animal *a1=new Cao("kurika",10,"estrela"); //nome, idade, raça
Animal *a2=new Morcego("bobo",2,70,2); //nome, idade, velocidade_maxima, altura_maxima
Animal *a3=new Cao("bobby",3,"rafeiro");
Animal *a4=new Cao("fly",7,"dalmata");
Animal *a5=new Morcego("timao",7,80,4);
ASSERT_EQUAL("kurika", a1->getNome());
ASSERT_EQUAL("bobo", a2->getNome());
ASSERT_EQUAL("bobby", a3->getNome());
ASSERT_EQUAL("fly", a4->getNome());
ASSERT_EQUAL("timao", a5->getNome());
ASSERT_EQUAL(true, a3->eJovem());
ASSERT_EQUAL(false, a4->eJovem());
ASSERT_EQUAL(true, a2->eJovem());
ASSERT_EQUAL(false, a5->eJovem());
ASSERT_EQUAL(2, Animal::getMaisJovem());
}
void test_b_adicionarAnimais() {
Zoo z1;
Animal *a1=new Cao("kurika",10,"estrela"); //nome, idade, raça
Animal *a2=new Morcego("bobo",2,70,2); //nome, idade, velocidade_maxima, altura_maxima
Animal *a3=new Cao("bobby",3,"rafeiro");
Animal *a4=new Cao("fly",7,"dalmata");
Animal *a5=new Morcego("timao",7,80,4);
z1.adicionaAnimal(a1);
z1.adicionaAnimal(a2);
z1.adicionaAnimal(a3);
z1.adicionaAnimal(a4);
z1.adicionaAnimal(a5);
ASSERT_EQUAL(5, z1.numAnimais());
}
void test_c_imprimirAnimais() {
Zoo z1;
Animal *a1=new Cao("kurika",10,"estrela"); //nome, idade, raça
ASSERT_EQUAL("kurika, 10, estrela", a1->getInformacao());
Animal *a2=new Morcego("bobo",2,70,2); //nome, idade, velocidade_maxima, altura_maxima
ASSERT_EQUAL("bobo, 2, 70, 2", a2->getInformacao());
z1.adicionaAnimal(a1);
z1.adicionaAnimal(a2);
cout << z1.getInformacao();
}
void test_d_verificarAnimalJovem() {
Zoo z1;
Animal *a1=new Cao("kurika",10,"estrela"); //nome, idade, raça
Animal *a2=new Morcego("bobo",2,70,2); //nome, idade, velocidade_maxima, altura_maxima
z1.adicionaAnimal(a1);
z1.adicionaAnimal(a2);
ASSERT_EQUAL(false, z1.animalJovem("kurika"));
ASSERT_EQUAL(true, z1.animalJovem("bobo"));
}
void test_e_alocarVeterinarios() {
/*Zoo z1;
Animal *a1=new Cao("kurika",10,"estrela"); //nome, idade, raça
Animal *a2=new Morcego("bobo",2,70,2); //nome, idade, velocidade_maxima, altura_maxima
Animal *a3=new Cao("bobby",3,"rafeiro");
Animal *a4=new Cao("fly",7,"dalmata");
Animal *a5=new Morcego("timao",7,80,4);
z1.adicionaAnimal(a1);
z1.adicionaAnimal(a2);
z1.adicionaAnimal(a3);
z1.adicionaAnimal(a4);
z1.adicionaAnimal(a5);
//TODO trocar o caminho do ficheiro para o caminho correcto; caminho relativo não funciona!
ifstream fVet("vets.txt");
if (!fVet) cout << "Ficheiro de veterinarios inexistente!\n";
else z1.alocaVeterinarios(fVet);
fVet.close();
ASSERT_EQUAL(5, z1.numAnimais());
ASSERT_EQUAL(3, z1.numVeterinarios());
ASSERT_EQUAL("kurika, 10, Rui Silva, 1234, estrela", a1->getInformacao());*/
}
void test_f_removerVeterinario() {
/* Zoo z1;
Animal *a1=new Cao("kurika",10,"estrela"); //nome, idade, raça
Animal *a2=new Morcego("bobo",2,70,2); //nome, idade, velocidade_maxima, altura_maxima
Animal *a3=new Cao("bobby",3,"rafeiro");
Animal *a4=new Cao("fly",7,"dalmata");
Animal *a5=new Morcego("timao",7,80,4);
z1.adicionaAnimal(a1);
z1.adicionaAnimal(a2);
z1.adicionaAnimal(a3);
z1.adicionaAnimal(a4);
z1.adicionaAnimal(a5);
//TODO trocar o caminho do ficheiro para o caminho correcto; caminho relativo não funciona!
ifstream fVet("vets.txt");
if (!fVet) cerr << "Ficheiro de veterinarios inexistente!\n";
else z1.alocaVeterinarios(fVet);
fVet.close();
ASSERT_EQUAL(5, z1.numAnimais());
ASSERT_EQUAL(3, z1.numVeterinarios());
ASSERT_EQUAL("kurika, 10, Rui Silva, 1234, estrela", a1->getInformacao());
z1.removeVeterinario("Rui Silva");
ASSERT_EQUAL("kurika, 10, Artur Costa, 3542, estrela", a1->getInformacao());*/
}
void test_h_compararZoos() {
/*Zoo z1;
Animal *a1=new Cao("kurika",10,"estrela"); //nome, idade, raça
Animal *a2=new Morcego("bobo",2,70,2); //nome, idade, velocidade_maxima, altura_maxima
Animal *a3=new Cao("bobby",3,"rafeiro");
Animal *a4=new Cao("fly",7,"dalmata");
Animal *a5=new Morcego("timao",7,80,4);
z1.adicionaAnimal(a1);
z1.adicionaAnimal(a2);
z1.adicionaAnimal(a3);
z1.adicionaAnimal(a4);
z1.adicionaAnimal(a5);
Zoo z2;
Animal *b1=new Cao("kurika",10,"estrela"); //nome, idade, raça
Animal *b2=new Morcego("bobo",2,70,2); //nome, idade, velocidade_maxima, altura_maxima
Animal *b3=new Cao("bobby",3,"rafeiro");
Animal *b4=new Cao("fly",7,"dalmata");
z2.adicionaAnimal(b1);
z2.adicionaAnimal(b2);
z2.adicionaAnimal(b3);
z2.adicionaAnimal(b4);
ASSERT_EQUAL(true, z2 < z1);*/
}
void runSuite(){
cute::suite s;
//TODO add your test here
std::cout << "fadsfasdf" << std::endl;
s.push_back(CUTE(test_a_criarAnimais));
s.push_back(CUTE(test_b_adicionarAnimais));
s.push_back(CUTE(test_c_imprimirAnimais));
s.push_back(CUTE(test_d_verificarAnimalJovem));
s.push_back(CUTE(test_e_alocarVeterinarios));
s.push_back(CUTE(test_f_removerVeterinario));
s.push_back(CUTE(test_h_compararZoos));
cute::ide_listener<> lis;
cute::makeRunner(lis)(s, "AEDA 2018/2019 - Aula Pratica 3");
std::cout << "fadsfasdf" << std::endl;
}
int main(){
runSuite();
return 0;
}
| [
"leonor_martins99@hotmail.com"
] | leonor_martins99@hotmail.com |
80d084fd9cd5dda6164901b43eca81e07ee65800 | f580fd53d3d035fc4b6b1c0abb41470a91544236 | /led_multicolor/led_multicolor.ino | 9e0048c093295646662dd11e7a5d736f714243cb | [] | no_license | gatoherz11/Arduino_projects | b9536770e0f400380daeb41a925f3dae352b3672 | 874e6f2bcf521e8592f9f9a07c88f2e47eed19ee | refs/heads/master | 2022-11-11T16:14:57.350004 | 2020-07-05T00:14:02 | 2020-07-05T00:14:02 | 277,204,241 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 623 | ino | byte redPin = 2;
byte greenPin = 3;
byte bluePin = 4;
int t= 2000;
void setup() {
pinMode(redPin, OUTPUT);
pinMode(greenPin, OUTPUT);
pinMode(bluePin, OUTPUT);
}
void loop() {
Color (255, 0,0); //rojo
delay(t);
Color (0, 255, 0);//verde
delay(t);
Color (0, 0, 255);//azul
delay(t);
Color (80, 0, 80);//morado
delay(t);
Color (0, 255, 255);//aqua
delay(t);
Color (255, 255, 255);//blanco
delay(t);
Color (255, 255, 0);
delay(t);
Color (255, 100, 70);
delay(t);
}
void Color (byte red, byte green, byte blue)
{
analogWrite(redPin, red);
analogWrite(greenPin, green);
analogWrite(bluePin, blue);
}
| [
"64179143+gatoherz11@users.noreply.github.com"
] | 64179143+gatoherz11@users.noreply.github.com |
9312eabb99004bb35e4697a5c89d50e0b76bad7d | 22a72dbcc5f7aa3eb240d11565990ec28a67f5bc | /Code/Rcpp18.cpp | 51c618b5f759bf81bd1a73f3d758d6759150fd8c | [] | no_license | Farheen2302/RCPP_Code | 3564db1287377df962cb6108a61d883b5af30af1 | 8125dcaa4303830a4bbf7721e60d018e1af928c4 | refs/heads/master | 2020-03-28T19:08:47.074831 | 2015-08-21T17:16:15 | 2015-08-21T17:16:15 | 37,806,113 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 445 | cpp | #include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
IntegerVector findInterval2(NumericVector a, NumericVector y)
{
IntegerVector out(a.size());
NumericVector::iterator it, pos;
IntegerVector::iterator out_it;
for(it = a.begin(), out_it = out.begin(); it != a.end(); ++it,++out_it)
{
pos = std::upper_bound(y.begin(),y.end(),*it);
*out_it = std::distance(y.begin(),pos);
}
return out;
} | [
"farheenfnilofer@gmail.com"
] | farheenfnilofer@gmail.com |
338666949aec356983a93a288e215525311065d5 | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Source/ThirdParty/CryptoPP/5.6.2/include/cryptlib.h | 4068722327fa5f96c093ce1fb810e47996f91f1c | [
"MIT",
"LicenseRef-scancode-proprietary-license",
"BSL-1.0",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | windystrife/UnrealEngine_NVIDIAGameWorks | c3c7863083653caf1bc67d3ef104fb4b9f302e2a | b50e6338a7c5b26374d66306ebc7807541ff815e | refs/heads/4.18-GameWorks | 2023-03-11T02:50:08.471040 | 2022-01-13T20:50:29 | 2022-01-13T20:50:29 | 124,100,479 | 262 | 179 | MIT | 2022-12-16T05:36:38 | 2018-03-06T15:44:09 | C++ | UTF-8 | C++ | false | false | 74,684 | h | // cryptlib.h - written and placed in the public domain by Wei Dai
/*! \file
This file contains the declarations for the abstract base
classes that provide a uniform interface to this library.
*/
/*! \mainpage Crypto++ Library 5.6.2 API Reference
<dl>
<dt>Abstract Base Classes<dd>
cryptlib.h
<dt>Authenticated Encryption<dd>
AuthenticatedSymmetricCipherDocumentation
<dt>Symmetric Ciphers<dd>
SymmetricCipherDocumentation
<dt>Hash Functions<dd>
SHA1, SHA224, SHA256, SHA384, SHA512, Tiger, Whirlpool, RIPEMD160, RIPEMD320, RIPEMD128, RIPEMD256, Weak1::MD2, Weak1::MD4, Weak1::MD5
<dt>Non-Cryptographic Checksums<dd>
CRC32, Adler32
<dt>Message Authentication Codes<dd>
VMAC, HMAC, CBC_MAC, CMAC, DMAC, TTMAC, GCM (GMAC)
<dt>Random Number Generators<dd>
NullRNG(), LC_RNG, RandomPool, BlockingRng, NonblockingRng, AutoSeededRandomPool, AutoSeededX917RNG, #DefaultAutoSeededRNG
<dt>Password-based Cryptography<dd>
PasswordBasedKeyDerivationFunction
<dt>Public Key Cryptosystems<dd>
DLIES, ECIES, LUCES, RSAES, RabinES, LUC_IES
<dt>Public Key Signature Schemes<dd>
DSA2, GDSA, ECDSA, NR, ECNR, LUCSS, RSASS, RSASS_ISO, RabinSS, RWSS, ESIGN
<dt>Key Agreement<dd>
#DH, DH2, #MQV, ECDH, ECMQV, XTR_DH
<dt>Algebraic Structures<dd>
Integer, PolynomialMod2, PolynomialOver, RingOfPolynomialsOver,
ModularArithmetic, MontgomeryRepresentation, GFP2_ONB,
GF2NP, GF256, GF2_32, EC2N, ECP
<dt>Secret Sharing and Information Dispersal<dd>
SecretSharing, SecretRecovery, InformationDispersal, InformationRecovery
<dt>Compression<dd>
Deflator, Inflator, Gzip, Gunzip, ZlibCompressor, ZlibDecompressor
<dt>Input Source Classes<dd>
StringSource, #ArraySource, FileSource, SocketSource, WindowsPipeSource, RandomNumberSource
<dt>Output Sink Classes<dd>
StringSinkTemplate, ArraySink, FileSink, SocketSink, WindowsPipeSink, RandomNumberSink
<dt>Filter Wrappers<dd>
StreamTransformationFilter, HashFilter, HashVerificationFilter, SignerFilter, SignatureVerificationFilter
<dt>Binary to Text Encoders and Decoders<dd>
HexEncoder, HexDecoder, Base64Encoder, Base64Decoder, Base32Encoder, Base32Decoder
<dt>Wrappers for OS features<dd>
Timer, Socket, WindowsHandle, ThreadLocalStorage, ThreadUserTimer
<dt>FIPS 140 related<dd>
fips140.h
</dl>
In the DLL version of Crypto++, only the following implementation class are available.
<dl>
<dt>Block Ciphers<dd>
AES, DES_EDE2, DES_EDE3, SKIPJACK
<dt>Cipher Modes (replace template parameter BC with one of the block ciphers above)<dd>
ECB_Mode\<BC\>, CTR_Mode\<BC\>, CBC_Mode\<BC\>, CFB_FIPS_Mode\<BC\>, OFB_Mode\<BC\>, GCM\<AES\>
<dt>Hash Functions<dd>
SHA1, SHA224, SHA256, SHA384, SHA512
<dt>Public Key Signature Schemes (replace template parameter H with one of the hash functions above)<dd>
RSASS\<PKCS1v15, H\>, RSASS\<PSS, H\>, RSASS_ISO\<H\>, RWSS\<P1363_EMSA2, H\>, DSA, ECDSA\<ECP, H\>, ECDSA\<EC2N, H\>
<dt>Message Authentication Codes (replace template parameter H with one of the hash functions above)<dd>
HMAC\<H\>, CBC_MAC\<DES_EDE2\>, CBC_MAC\<DES_EDE3\>, GCM\<AES\>
<dt>Random Number Generators<dd>
#DefaultAutoSeededRNG (AutoSeededX917RNG\<AES\>)
<dt>Key Agreement<dd>
#DH
<dt>Public Key Cryptosystems<dd>
RSAES\<OAEP\<SHA1\> \>
</dl>
<p>This reference manual is a work in progress. Some classes are still lacking detailed descriptions.
<p>Click <a href="CryptoPPRef.zip">here</a> to download a zip archive containing this manual.
<p>Thanks to Ryan Phillips for providing the Doxygen configuration file
and getting me started with this manual.
*/
#ifndef CRYPTOPP_CRYPTLIB_H
#define CRYPTOPP_CRYPTLIB_H
#include "config.h"
#include "stdcpp.h"
NAMESPACE_BEGIN(CryptoPP)
// forward declarations
class Integer;
class RandomNumberGenerator;
class BufferedTransformation;
//! used to specify a direction for a cipher to operate in (encrypt or decrypt)
enum CipherDir {ENCRYPTION, DECRYPTION};
//! used to represent infinite time
const unsigned long INFINITE_TIME = ULONG_MAX;
// VC60 workaround: using enums as template parameters causes problems
template <typename ENUM_TYPE, int VALUE>
struct EnumToType
{
static ENUM_TYPE ToEnum() {return (ENUM_TYPE)VALUE;}
};
enum ByteOrder {LITTLE_ENDIAN_ORDER = 0, BIG_ENDIAN_ORDER = 1};
typedef EnumToType<ByteOrder, LITTLE_ENDIAN_ORDER> LittleEndian;
typedef EnumToType<ByteOrder, BIG_ENDIAN_ORDER> BigEndian;
//! base class for all exceptions thrown by Crypto++
class CRYPTOPP_DLL Exception : public std::exception
{
public:
//! error types
enum ErrorType {
//! a method is not implemented
NOT_IMPLEMENTED,
//! invalid function argument
INVALID_ARGUMENT,
//! BufferedTransformation received a Flush(true) signal but can't flush buffers
CANNOT_FLUSH,
//! data integerity check (such as CRC or MAC) failed
DATA_INTEGRITY_CHECK_FAILED,
//! received input data that doesn't conform to expected format
INVALID_DATA_FORMAT,
//! error reading from input device or writing to output device
IO_ERROR,
//! some error not belong to any of the above categories
OTHER_ERROR
};
explicit Exception(ErrorType errorType, const std::string &s) : m_errorType(errorType), m_what(s) {}
virtual ~Exception() throw() {}
const char *what() const throw() {return (m_what.c_str());}
const std::string &GetWhat() const {return m_what;}
void SetWhat(const std::string &s) {m_what = s;}
ErrorType GetErrorType() const {return m_errorType;}
void SetErrorType(ErrorType errorType) {m_errorType = errorType;}
private:
ErrorType m_errorType;
std::string m_what;
};
//! exception thrown when an invalid argument is detected
class CRYPTOPP_DLL InvalidArgument : public Exception
{
public:
explicit InvalidArgument(const std::string &s) : Exception(INVALID_ARGUMENT, s) {}
};
//! exception thrown when input data is received that doesn't conform to expected format
class CRYPTOPP_DLL InvalidDataFormat : public Exception
{
public:
explicit InvalidDataFormat(const std::string &s) : Exception(INVALID_DATA_FORMAT, s) {}
};
//! exception thrown by decryption filters when trying to decrypt an invalid ciphertext
class CRYPTOPP_DLL InvalidCiphertext : public InvalidDataFormat
{
public:
explicit InvalidCiphertext(const std::string &s) : InvalidDataFormat(s) {}
};
//! exception thrown by a class if a non-implemented method is called
class CRYPTOPP_DLL NotImplemented : public Exception
{
public:
explicit NotImplemented(const std::string &s) : Exception(NOT_IMPLEMENTED, s) {}
};
//! exception thrown by a class when Flush(true) is called but it can't completely flush its buffers
class CRYPTOPP_DLL CannotFlush : public Exception
{
public:
explicit CannotFlush(const std::string &s) : Exception(CANNOT_FLUSH, s) {}
};
//! error reported by the operating system
class CRYPTOPP_DLL OS_Error : public Exception
{
public:
OS_Error(ErrorType errorType, const std::string &s, const std::string& operation, int errorCode)
: Exception(errorType, s), m_operation(operation), m_errorCode(errorCode) {}
~OS_Error() throw() {}
// the operating system API that reported the error
const std::string & GetOperation() const {return m_operation;}
// the error code return by the operating system
int GetErrorCode() const {return m_errorCode;}
protected:
std::string m_operation;
int m_errorCode;
};
//! used to return decoding results
struct CRYPTOPP_DLL DecodingResult
{
explicit DecodingResult() : isValidCoding(false), messageLength(0) {}
explicit DecodingResult(size_t len) : isValidCoding(true), messageLength(len) {}
bool operator==(const DecodingResult &rhs) const {return isValidCoding == rhs.isValidCoding && messageLength == rhs.messageLength;}
bool operator!=(const DecodingResult &rhs) const {return !operator==(rhs);}
bool isValidCoding;
size_t messageLength;
#ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
operator size_t() const {return isValidCoding ? messageLength : 0;}
#endif
};
//! interface for retrieving values given their names
/*! \note This class is used to safely pass a variable number of arbitrarily typed arguments to functions
and to read values from keys and crypto parameters.
\note To obtain an object that implements NameValuePairs for the purpose of parameter
passing, use the MakeParameters() function.
\note To get a value from NameValuePairs, you need to know the name and the type of the value.
Call GetValueNames() on a NameValuePairs object to obtain a list of value names that it supports.
Then look at the Name namespace documentation to see what the type of each value is, or
alternatively, call GetIntValue() with the value name, and if the type is not int, a
ValueTypeMismatch exception will be thrown and you can get the actual type from the exception object.
*/
class CRYPTOPP_NO_VTABLE NameValuePairs
{
public:
virtual ~NameValuePairs() {}
//! exception thrown when trying to retrieve a value using a different type than expected
class CRYPTOPP_DLL ValueTypeMismatch : public InvalidArgument
{
public:
ValueTypeMismatch(const std::string &name, const std::type_info &stored, const std::type_info &retrieving)
: InvalidArgument("NameValuePairs: type mismatch for '" + name + "', stored '" + stored.name() + "', trying to retrieve '" + retrieving.name() + "'")
, m_stored(stored), m_retrieving(retrieving) {}
const std::type_info & GetStoredTypeInfo() const {return m_stored;}
const std::type_info & GetRetrievingTypeInfo() const {return m_retrieving;}
private:
const std::type_info &m_stored;
const std::type_info &m_retrieving;
};
//! get a copy of this object or a subobject of it
template <class T>
bool GetThisObject(T &object) const
{
return GetValue((std::string("ThisObject:")+typeid(T).name()).c_str(), object);
}
//! get a pointer to this object, as a pointer to T
template <class T>
bool GetThisPointer(T *&p) const
{
return GetValue((std::string("ThisPointer:")+typeid(T).name()).c_str(), p);
}
//! get a named value, returns true if the name exists
template <class T>
bool GetValue(const char *name, T &value) const
{
return GetVoidValue(name, typeid(T), &value);
}
//! get a named value, returns the default if the name doesn't exist
template <class T>
T GetValueWithDefault(const char *name, T defaultValue) const
{
GetValue(name, defaultValue);
return defaultValue;
}
//! get a list of value names that can be retrieved
CRYPTOPP_DLL std::string GetValueNames() const
{std::string result; GetValue("ValueNames", result); return result;}
//! get a named value with type int
/*! used to ensure we don't accidentally try to get an unsigned int
or some other type when we mean int (which is the most common case) */
CRYPTOPP_DLL bool GetIntValue(const char *name, int &value) const
{return GetValue(name, value);}
//! get a named value with type int, with default
CRYPTOPP_DLL int GetIntValueWithDefault(const char *name, int defaultValue) const
{return GetValueWithDefault(name, defaultValue);}
//! used by derived classes to check for type mismatch
CRYPTOPP_DLL static void CRYPTOPP_API ThrowIfTypeMismatch(const char *name, const std::type_info &stored, const std::type_info &retrieving)
{if (stored != retrieving) throw ValueTypeMismatch(name, stored, retrieving);}
template <class T>
void GetRequiredParameter(const char *className, const char *name, T &value) const
{
if (!GetValue(name, value))
throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'");
}
CRYPTOPP_DLL void GetRequiredIntParameter(const char *className, const char *name, int &value) const
{
if (!GetIntValue(name, value))
throw InvalidArgument(std::string(className) + ": missing required parameter '" + name + "'");
}
//! to be implemented by derived classes, users should use one of the above functions instead
CRYPTOPP_DLL virtual bool GetVoidValue(const char *name, const std::type_info &valueType, void *pValue) const =0;
};
//! namespace containing value name definitions
/*! value names, types and semantics:
ThisObject:ClassName (ClassName, copy of this object or a subobject)
ThisPointer:ClassName (const ClassName *, pointer to this object or a subobject)
*/
DOCUMENTED_NAMESPACE_BEGIN(Name)
// more names defined in argnames.h
DOCUMENTED_NAMESPACE_END
//! empty set of name-value pairs
extern CRYPTOPP_DLL const NameValuePairs &g_nullNameValuePairs;
// ********************************************************
//! interface for cloning objects, this is not implemented by most classes yet
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Clonable
{
public:
virtual ~Clonable() {}
//! this is not implemented by most classes yet
virtual Clonable* Clone() const {throw NotImplemented("Clone() is not implemented yet.");} // TODO: make this =0
};
//! interface for all crypto algorithms
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE Algorithm : public Clonable
{
public:
/*! When FIPS 140-2 compliance is enabled and checkSelfTestStatus == true,
this constructor throws SelfTestFailure if the self test hasn't been run or fails. */
Algorithm(bool checkSelfTestStatus = true);
//! returns name of this algorithm, not universally implemented yet
virtual std::string AlgorithmName() const {return "unknown";}
};
//! keying interface for crypto algorithms that take byte strings as keys
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyingInterface
{
public:
virtual ~SimpleKeyingInterface() {}
//! returns smallest valid key length in bytes */
virtual size_t MinKeyLength() const =0;
//! returns largest valid key length in bytes */
virtual size_t MaxKeyLength() const =0;
//! returns default (recommended) key length in bytes */
virtual size_t DefaultKeyLength() const =0;
//! returns the smallest valid key length in bytes that is >= min(n, GetMaxKeyLength())
virtual size_t GetValidKeyLength(size_t n) const =0;
//! returns whether n is a valid key length
virtual bool IsValidKeyLength(size_t n) const
{return n == GetValidKeyLength(n);}
//! set or reset the key of this object
/*! \param params is used to specify Rounds, BlockSize, etc. */
virtual void SetKey(const byte *key, size_t length, const NameValuePairs ¶ms = g_nullNameValuePairs);
//! calls SetKey() with an NameValuePairs object that just specifies "Rounds"
void SetKeyWithRounds(const byte *key, size_t length, int rounds);
//! calls SetKey() with an NameValuePairs object that just specifies "IV"
void SetKeyWithIV(const byte *key, size_t length, const byte *iv, size_t ivLength);
//! calls SetKey() with an NameValuePairs object that just specifies "IV"
void SetKeyWithIV(const byte *key, size_t length, const byte *iv)
{SetKeyWithIV(key, length, iv, IVSize());}
enum IV_Requirement {UNIQUE_IV = 0, RANDOM_IV, UNPREDICTABLE_RANDOM_IV, INTERNALLY_GENERATED_IV, NOT_RESYNCHRONIZABLE};
//! returns the minimal requirement for secure IVs
virtual IV_Requirement IVRequirement() const =0;
//! returns whether this object can be resynchronized (i.e. supports initialization vectors)
/*! If this function returns true, and no IV is passed to SetKey() and CanUseStructuredIVs()==true, an IV of all 0's will be assumed. */
bool IsResynchronizable() const {return IVRequirement() < NOT_RESYNCHRONIZABLE;}
//! returns whether this object can use random IVs (in addition to ones returned by GetNextIV)
bool CanUseRandomIVs() const {return IVRequirement() <= UNPREDICTABLE_RANDOM_IV;}
//! returns whether this object can use random but possibly predictable IVs (in addition to ones returned by GetNextIV)
bool CanUsePredictableIVs() const {return IVRequirement() <= RANDOM_IV;}
//! returns whether this object can use structured IVs, for example a counter (in addition to ones returned by GetNextIV)
bool CanUseStructuredIVs() const {return IVRequirement() <= UNIQUE_IV;}
virtual unsigned int IVSize() const {throw NotImplemented(GetAlgorithm().AlgorithmName() + ": this object doesn't support resynchronization");}
//! returns default length of IVs accepted by this object
unsigned int DefaultIVLength() const {return IVSize();}
//! returns minimal length of IVs accepted by this object
virtual unsigned int MinIVLength() const {return IVSize();}
//! returns maximal length of IVs accepted by this object
virtual unsigned int MaxIVLength() const {return IVSize();}
//! resynchronize with an IV. ivLength=-1 means use IVSize()
virtual void Resynchronize(const byte *iv, int ivLength=-1) {throw NotImplemented(GetAlgorithm().AlgorithmName() + ": this object doesn't support resynchronization");}
//! get a secure IV for the next message
/*! This method should be called after you finish encrypting one message and are ready to start the next one.
After calling it, you must call SetKey() or Resynchronize() before using this object again.
This method is not implemented on decryption objects. */
virtual void GetNextIV(RandomNumberGenerator &rng, byte *IV);
protected:
virtual const Algorithm & GetAlgorithm() const =0;
virtual void UncheckedSetKey(const byte *key, unsigned int length, const NameValuePairs ¶ms) =0;
void ThrowIfInvalidKeyLength(size_t length);
void ThrowIfResynchronizable(); // to be called when no IV is passed
void ThrowIfInvalidIV(const byte *iv); // check for NULL IV if it can't be used
size_t ThrowIfInvalidIVLength(int size);
const byte * GetIVAndThrowIfInvalid(const NameValuePairs ¶ms, size_t &size);
inline void AssertValidKeyLength(size_t length) const
{assert(IsValidKeyLength(length));}
};
//! interface for the data processing part of block ciphers
/*! Classes derived from BlockTransformation are block ciphers
in ECB mode (for example the DES::Encryption class), which are stateless.
These classes should not be used directly, but only in combination with
a mode class (see CipherModeDocumentation in modes.h).
*/
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockTransformation : public Algorithm
{
public:
//! encrypt or decrypt inBlock, xor with xorBlock, and write to outBlock
virtual void ProcessAndXorBlock(const byte *inBlock, const byte *xorBlock, byte *outBlock) const =0;
//! encrypt or decrypt one block
/*! \pre size of inBlock and outBlock == BlockSize() */
void ProcessBlock(const byte *inBlock, byte *outBlock) const
{ProcessAndXorBlock(inBlock, NULL, outBlock);}
//! encrypt or decrypt one block in place
void ProcessBlock(byte *inoutBlock) const
{ProcessAndXorBlock(inoutBlock, NULL, inoutBlock);}
//! block size of the cipher in bytes
virtual unsigned int BlockSize() const =0;
//! returns how inputs and outputs should be aligned for optimal performance
virtual unsigned int OptimalDataAlignment() const;
//! returns true if this is a permutation (i.e. there is an inverse transformation)
virtual bool IsPermutation() const {return true;}
//! returns true if this is an encryption object
virtual bool IsForwardTransformation() const =0;
//! return number of blocks that can be processed in parallel, for bit-slicing implementations
virtual unsigned int OptimalNumberOfParallelBlocks() const {return 1;}
enum {BT_InBlockIsCounter=1, BT_DontIncrementInOutPointers=2, BT_XorInput=4, BT_ReverseDirection=8, BT_AllowParallel=16} FlagsForAdvancedProcessBlocks;
//! encrypt and xor blocks according to flags (see FlagsForAdvancedProcessBlocks)
/*! /note If BT_InBlockIsCounter is set, last byte of inBlocks may be modified. */
virtual size_t AdvancedProcessBlocks(const byte *inBlocks, const byte *xorBlocks, byte *outBlocks, size_t length, word32 flags) const;
inline CipherDir GetCipherDirection() const {return IsForwardTransformation() ? ENCRYPTION : DECRYPTION;}
};
//! interface for the data processing part of stream ciphers
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE StreamTransformation : public Algorithm
{
public:
//! return a reference to this object, useful for passing a temporary object to a function that takes a non-const reference
StreamTransformation& Ref() {return *this;}
//! returns block size, if input must be processed in blocks, otherwise 1
virtual unsigned int MandatoryBlockSize() const {return 1;}
//! returns the input block size that is most efficient for this cipher
/*! \note optimal input length is n * OptimalBlockSize() - GetOptimalBlockSizeUsed() for any n > 0 */
virtual unsigned int OptimalBlockSize() const {return MandatoryBlockSize();}
//! returns how much of the current block is used up
virtual unsigned int GetOptimalBlockSizeUsed() const {return 0;}
//! returns how input should be aligned for optimal performance
virtual unsigned int OptimalDataAlignment() const;
//! encrypt or decrypt an array of bytes of specified length
/*! \note either inString == outString, or they don't overlap */
virtual void ProcessData(byte *outString, const byte *inString, size_t length) =0;
//! for ciphers where the last block of data is special, encrypt or decrypt the last block of data
/*! For now the only use of this function is for CBC-CTS mode. */
virtual void ProcessLastBlock(byte *outString, const byte *inString, size_t length);
//! returns the minimum size of the last block, 0 indicating the last block is not special
virtual unsigned int MinLastBlockSize() const {return 0;}
//! same as ProcessData(inoutString, inoutString, length)
inline void ProcessString(byte *inoutString, size_t length)
{ProcessData(inoutString, inoutString, length);}
//! same as ProcessData(outString, inString, length)
inline void ProcessString(byte *outString, const byte *inString, size_t length)
{ProcessData(outString, inString, length);}
//! implemented as {ProcessData(&input, &input, 1); return input;}
inline byte ProcessByte(byte input)
{ProcessData(&input, &input, 1); return input;}
//! returns whether this cipher supports random access
virtual bool IsRandomAccess() const =0;
//! for random access ciphers, seek to an absolute position
virtual void Seek(lword n)
{
assert(!IsRandomAccess());
throw NotImplemented("StreamTransformation: this object doesn't support random access");
}
//! returns whether this transformation is self-inverting (e.g. xor with a keystream)
virtual bool IsSelfInverting() const =0;
//! returns whether this is an encryption object
virtual bool IsForwardTransformation() const =0;
};
//! interface for hash functions and data processing part of MACs
/*! HashTransformation objects are stateful. They are created in an initial state,
change state as Update() is called, and return to the initial
state when Final() is called. This interface allows a large message to
be hashed in pieces by calling Update() on each piece followed by
calling Final().
*/
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE HashTransformation : public Algorithm
{
public:
//! return a reference to this object, useful for passing a temporary object to a function that takes a non-const reference
HashTransformation& Ref() {return *this;}
//! process more input
virtual void Update(const byte *input, size_t length) =0;
//! request space to write input into
virtual byte * CreateUpdateSpace(size_t &size) {size=0; return NULL;}
//! compute hash for current message, then restart for a new message
/*! \pre size of digest == DigestSize(). */
virtual void Final(byte *digest)
{TruncatedFinal(digest, DigestSize());}
//! discard the current state, and restart with a new message
virtual void Restart()
{TruncatedFinal(NULL, 0);}
//! size of the hash/digest/MAC returned by Final()
virtual unsigned int DigestSize() const =0;
//! same as DigestSize()
unsigned int TagSize() const {return DigestSize();}
//! block size of underlying compression function, or 0 if not block based
virtual unsigned int BlockSize() const {return 0;}
//! input to Update() should have length a multiple of this for optimal speed
virtual unsigned int OptimalBlockSize() const {return 1;}
//! returns how input should be aligned for optimal performance
virtual unsigned int OptimalDataAlignment() const;
//! use this if your input is in one piece and you don't want to call Update() and Final() separately
virtual void CalculateDigest(byte *digest, const byte *input, size_t length)
{Update(input, length); Final(digest);}
//! verify that digest is a valid digest for the current message, then reinitialize the object
/*! Default implementation is to call Final() and do a bitwise comparison
between its output and digest. */
virtual bool Verify(const byte *digest)
{return TruncatedVerify(digest, DigestSize());}
//! use this if your input is in one piece and you don't want to call Update() and Verify() separately
virtual bool VerifyDigest(const byte *digest, const byte *input, size_t length)
{Update(input, length); return Verify(digest);}
//! truncated version of Final()
virtual void TruncatedFinal(byte *digest, size_t digestSize) =0;
//! truncated version of CalculateDigest()
virtual void CalculateTruncatedDigest(byte *digest, size_t digestSize, const byte *input, size_t length)
{Update(input, length); TruncatedFinal(digest, digestSize);}
//! truncated version of Verify()
virtual bool TruncatedVerify(const byte *digest, size_t digestLength);
//! truncated version of VerifyDigest()
virtual bool VerifyTruncatedDigest(const byte *digest, size_t digestLength, const byte *input, size_t length)
{Update(input, length); return TruncatedVerify(digest, digestLength);}
protected:
void ThrowIfInvalidTruncatedSize(size_t size) const;
};
typedef HashTransformation HashFunction;
//! interface for one direction (encryption or decryption) of a block cipher
/*! \note These objects usually should not be used directly. See BlockTransformation for more details. */
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BlockCipher : public SimpleKeyingInterface, public BlockTransformation
{
protected:
const Algorithm & GetAlgorithm() const {return *this;}
};
//! interface for one direction (encryption or decryption) of a stream cipher or cipher mode
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SymmetricCipher : public SimpleKeyingInterface, public StreamTransformation
{
protected:
const Algorithm & GetAlgorithm() const {return *this;}
};
//! interface for message authentication codes
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE MessageAuthenticationCode : public SimpleKeyingInterface, public HashTransformation
{
protected:
const Algorithm & GetAlgorithm() const {return *this;}
};
//! interface for for one direction (encryption or decryption) of a stream cipher or block cipher mode with authentication
/*! The StreamTransformation part of this interface is used to encrypt/decrypt the data, and the MessageAuthenticationCode part of this
interface is used to input additional authenticated data (AAD, which is MAC'ed but not encrypted), and to generate/verify the MAC. */
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedSymmetricCipher : public MessageAuthenticationCode, public StreamTransformation
{
public:
//! this indicates that a member function was called in the wrong state, for example trying to encrypt a message before having set the key or IV
class BadState : public Exception
{
public:
explicit BadState(const std::string &name, const char *message) : Exception(OTHER_ERROR, name + ": " + message) {}
explicit BadState(const std::string &name, const char *function, const char *state) : Exception(OTHER_ERROR, name + ": " + function + " was called before " + state) {}
};
//! the maximum length of AAD that can be input before the encrypted data
virtual lword MaxHeaderLength() const =0;
//! the maximum length of encrypted data
virtual lword MaxMessageLength() const =0;
//! the maximum length of AAD that can be input after the encrypted data
virtual lword MaxFooterLength() const {return 0;}
//! if this function returns true, SpecifyDataLengths() must be called before attempting to input data
/*! This is the case for some schemes, such as CCM. */
virtual bool NeedsPrespecifiedDataLengths() const {return false;}
//! this function only needs to be called if NeedsPrespecifiedDataLengths() returns true
void SpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength=0);
//! encrypt and generate MAC in one call. will truncate MAC if macSize < TagSize()
virtual void EncryptAndAuthenticate(byte *ciphertext, byte *mac, size_t macSize, const byte *iv, int ivLength, const byte *header, size_t headerLength, const byte *message, size_t messageLength);
//! decrypt and verify MAC in one call, returning true iff MAC is valid. will assume MAC is truncated if macLength < TagSize()
virtual bool DecryptAndVerify(byte *message, const byte *mac, size_t macLength, const byte *iv, int ivLength, const byte *header, size_t headerLength, const byte *ciphertext, size_t ciphertextLength);
// redeclare this to avoid compiler ambiguity errors
virtual std::string AlgorithmName() const =0;
protected:
const Algorithm & GetAlgorithm() const {return *static_cast<const MessageAuthenticationCode *>(this);}
virtual void UncheckedSpecifyDataLengths(lword headerLength, lword messageLength, lword footerLength) {}
};
#ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
typedef SymmetricCipher StreamCipher;
#endif
//! interface for random number generators
/*! All return values are uniformly distributed over the range specified.
*/
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE RandomNumberGenerator : public Algorithm
{
public:
//! update RNG state with additional unpredictable values
virtual void IncorporateEntropy(const byte *input, size_t length) {throw NotImplemented("RandomNumberGenerator: IncorporateEntropy not implemented");}
//! returns true if IncorporateEntropy is implemented
virtual bool CanIncorporateEntropy() const {return false;}
//! generate new random byte and return it
virtual byte GenerateByte();
//! generate new random bit and return it
/*! Default implementation is to call GenerateByte() and return its lowest bit. */
virtual unsigned int GenerateBit();
//! generate a random 32 bit word in the range min to max, inclusive
virtual word32 GenerateWord32(word32 a=0, word32 b=0xffffffffL);
//! generate random array of bytes
virtual void GenerateBlock(byte *output, size_t size);
//! generate and discard n bytes
virtual void DiscardBytes(size_t n);
//! generate random bytes as input to a BufferedTransformation
virtual void GenerateIntoBufferedTransformation(BufferedTransformation &target, const std::string &channel, lword length);
//! randomly shuffle the specified array, resulting permutation is uniformly distributed
template <class IT> void Shuffle(IT begin, IT end)
{
for (; begin != end; ++begin)
std::iter_swap(begin, begin + GenerateWord32(0, end-begin-1));
}
#ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
byte GetByte() {return GenerateByte();}
unsigned int GetBit() {return GenerateBit();}
word32 GetLong(word32 a=0, word32 b=0xffffffffL) {return GenerateWord32(a, b);}
word16 GetShort(word16 a=0, word16 b=0xffff) {return (word16)GenerateWord32(a, b);}
void GetBlock(byte *output, size_t size) {GenerateBlock(output, size);}
#endif
};
//! returns a reference that can be passed to functions that ask for a RNG but doesn't actually use it
CRYPTOPP_DLL RandomNumberGenerator & CRYPTOPP_API NullRNG();
class WaitObjectContainer;
class CallStack;
//! interface for objects that you can wait for
class CRYPTOPP_NO_VTABLE Waitable
{
public:
virtual ~Waitable() {}
//! maximum number of wait objects that this object can return
virtual unsigned int GetMaxWaitObjectCount() const =0;
//! put wait objects into container
/*! \param callStack is used for tracing no wait loops, example:
something.GetWaitObjects(c, CallStack("my func after X", 0));
- or in an outer GetWaitObjects() method that itself takes a callStack parameter:
innerThing.GetWaitObjects(c, CallStack("MyClass::GetWaitObjects at X", &callStack)); */
virtual void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack) =0;
//! wait on this object
/*! same as creating an empty container, calling GetWaitObjects(), and calling Wait() on the container */
bool Wait(unsigned long milliseconds, CallStack const& callStack);
};
//! the default channel for BufferedTransformation, equal to the empty string
extern CRYPTOPP_DLL const std::string DEFAULT_CHANNEL;
//! channel for additional authenticated data, equal to "AAD"
extern CRYPTOPP_DLL const std::string AAD_CHANNEL;
//! interface for buffered transformations
/*! BufferedTransformation is a generalization of BlockTransformation,
StreamTransformation, and HashTransformation.
A buffered transformation is an object that takes a stream of bytes
as input (this may be done in stages), does some computation on them, and
then places the result into an internal buffer for later retrieval. Any
partial result already in the output buffer is not modified by further
input.
If a method takes a "blocking" parameter, and you
pass "false" for it, the method will return before all input has been processed if
the input cannot be processed without waiting (for network buffers to become available, for example).
In this case the method will return true
or a non-zero integer value. When this happens you must continue to call the method with the same
parameters until it returns false or zero, before calling any other method on it or
attached BufferedTransformation. The integer return value in this case is approximately
the number of bytes left to be processed, and can be used to implement a progress bar.
For functions that take a "propagation" parameter, propagation != 0 means pass on the signal to attached
BufferedTransformation objects, with propagation decremented at each step until it reaches 0.
-1 means unlimited propagation.
\nosubgrouping
*/
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE BufferedTransformation : public Algorithm, public Waitable
{
public:
// placed up here for CW8
static const std::string &NULL_CHANNEL; // same as DEFAULT_CHANNEL, for backwards compatibility
BufferedTransformation() : Algorithm(false) {}
//! return a reference to this object, useful for passing a temporary object to a function that takes a non-const reference
BufferedTransformation& Ref() {return *this;}
//! \name INPUT
//@{
//! input a byte for processing
size_t Put(byte inByte, bool blocking=true)
{return Put(&inByte, 1, blocking);}
//! input multiple bytes
size_t Put(const byte *inString, size_t length, bool blocking=true)
{return Put2(inString, length, 0, blocking);}
//! input a 16-bit word
size_t PutWord16(word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
//! input a 32-bit word
size_t PutWord32(word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
//! request space which can be written into by the caller, and then used as input to Put()
/*! \param size is requested size (as a hint) for input, and size of the returned space for output */
/*! \note The purpose of this method is to help avoid doing extra memory allocations. */
virtual byte * CreatePutSpace(size_t &size) {size=0; return NULL;}
virtual bool CanModifyInput() const {return false;}
//! input multiple bytes that may be modified by callee
size_t PutModifiable(byte *inString, size_t length, bool blocking=true)
{return PutModifiable2(inString, length, 0, blocking);}
bool MessageEnd(int propagation=-1, bool blocking=true)
{return !!Put2(NULL, 0, propagation < 0 ? -1 : propagation+1, blocking);}
size_t PutMessageEnd(const byte *inString, size_t length, int propagation=-1, bool blocking=true)
{return Put2(inString, length, propagation < 0 ? -1 : propagation+1, blocking);}
//! input multiple bytes for blocking or non-blocking processing
/*! \param messageEnd means how many filters to signal MessageEnd to, including this one */
virtual size_t Put2(const byte *inString, size_t length, int messageEnd, bool blocking) =0;
//! input multiple bytes that may be modified by callee for blocking or non-blocking processing
/*! \param messageEnd means how many filters to signal MessageEnd to, including this one */
virtual size_t PutModifiable2(byte *inString, size_t length, int messageEnd, bool blocking)
{return Put2(inString, length, messageEnd, blocking);}
//! thrown by objects that have not implemented nonblocking input processing
struct BlockingInputOnly : public NotImplemented
{BlockingInputOnly(const std::string &s) : NotImplemented(s + ": Nonblocking input is not implemented by this object.") {}};
//@}
//! \name WAITING
//@{
unsigned int GetMaxWaitObjectCount() const;
void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack);
//@}
//! \name SIGNALS
//@{
virtual void IsolatedInitialize(const NameValuePairs ¶meters) {throw NotImplemented("BufferedTransformation: this object can't be reinitialized");}
virtual bool IsolatedFlush(bool hardFlush, bool blocking) =0;
virtual bool IsolatedMessageSeriesEnd(bool blocking) {return false;}
//! initialize or reinitialize this object
virtual void Initialize(const NameValuePairs ¶meters=g_nullNameValuePairs, int propagation=-1);
//! flush buffered input and/or output
/*! \param hardFlush is used to indicate whether all data should be flushed
\note Hard flushes must be used with care. It means try to process and output everything, even if
there may not be enough data to complete the action. For example, hard flushing a HexDecoder would
cause an error if you do it after inputing an odd number of hex encoded characters.
For some types of filters, for example ZlibDecompressor, hard flushes can only
be done at "synchronization points". These synchronization points are positions in the data
stream that are created by hard flushes on the corresponding reverse filters, in this
example ZlibCompressor. This is useful when zlib compressed data is moved across a
network in packets and compression state is preserved across packets, as in the ssh2 protocol.
*/
virtual bool Flush(bool hardFlush, int propagation=-1, bool blocking=true);
//! mark end of a series of messages
/*! There should be a MessageEnd immediately before MessageSeriesEnd. */
virtual bool MessageSeriesEnd(int propagation=-1, bool blocking=true);
//! set propagation of automatically generated and transferred signals
/*! propagation == 0 means do not automaticly generate signals */
virtual void SetAutoSignalPropagation(int propagation) {}
//!
virtual int GetAutoSignalPropagation() const {return 0;}
public:
#ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
void Close() {MessageEnd();}
#endif
//@}
//! \name RETRIEVAL OF ONE MESSAGE
//@{
//! returns number of bytes that is currently ready for retrieval
/*! All retrieval functions return the actual number of bytes
retrieved, which is the lesser of the request number and
MaxRetrievable(). */
virtual lword MaxRetrievable() const;
//! returns whether any bytes are currently ready for retrieval
virtual bool AnyRetrievable() const;
//! try to retrieve a single byte
virtual size_t Get(byte &outByte);
//! try to retrieve multiple bytes
virtual size_t Get(byte *outString, size_t getMax);
//! peek at the next byte without removing it from the output buffer
virtual size_t Peek(byte &outByte) const;
//! peek at multiple bytes without removing them from the output buffer
virtual size_t Peek(byte *outString, size_t peekMax) const;
//! try to retrieve a 16-bit word
size_t GetWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER);
//! try to retrieve a 32-bit word
size_t GetWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER);
//! try to peek at a 16-bit word
size_t PeekWord16(word16 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
//! try to peek at a 32-bit word
size_t PeekWord32(word32 &value, ByteOrder order=BIG_ENDIAN_ORDER) const;
//! move transferMax bytes of the buffered output to target as input
lword TransferTo(BufferedTransformation &target, lword transferMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL)
{TransferTo2(target, transferMax, channel); return transferMax;}
//! discard skipMax bytes from the output buffer
virtual lword Skip(lword skipMax=LWORD_MAX);
//! copy copyMax bytes of the buffered output to target as input
lword CopyTo(BufferedTransformation &target, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
{return CopyRangeTo(target, 0, copyMax, channel);}
//! copy copyMax bytes of the buffered output, starting at position (relative to current position), to target as input
lword CopyRangeTo(BufferedTransformation &target, lword position, lword copyMax=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL) const
{lword i = position; CopyRangeTo2(target, i, i+copyMax, channel); return i-position;}
#ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
unsigned long MaxRetrieveable() const {return MaxRetrievable();}
#endif
//@}
//! \name RETRIEVAL OF MULTIPLE MESSAGES
//@{
//!
virtual lword TotalBytesRetrievable() const;
//! number of times MessageEnd() has been received minus messages retrieved or skipped
virtual unsigned int NumberOfMessages() const;
//! returns true if NumberOfMessages() > 0
virtual bool AnyMessages() const;
//! start retrieving the next message
/*!
Returns false if no more messages exist or this message
is not completely retrieved.
*/
virtual bool GetNextMessage();
//! skip count number of messages
virtual unsigned int SkipMessages(unsigned int count=UINT_MAX);
//!
unsigned int TransferMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL)
{TransferMessagesTo2(target, count, channel); return count;}
//!
unsigned int CopyMessagesTo(BufferedTransformation &target, unsigned int count=UINT_MAX, const std::string &channel=DEFAULT_CHANNEL) const;
//!
virtual void SkipAll();
//!
void TransferAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL)
{TransferAllTo2(target, channel);}
//!
void CopyAllTo(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL) const;
virtual bool GetNextMessageSeries() {return false;}
virtual unsigned int NumberOfMessagesInThisSeries() const {return NumberOfMessages();}
virtual unsigned int NumberOfMessageSeries() const {return 0;}
//@}
//! \name NON-BLOCKING TRANSFER OF OUTPUT
//@{
//! upon return, byteCount contains number of bytes that have finished being transfered, and returns the number of bytes left in the current transfer block
virtual size_t TransferTo2(BufferedTransformation &target, lword &byteCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) =0;
//! upon return, begin contains the start position of data yet to be finished copying, and returns the number of bytes left in the current transfer block
virtual size_t CopyRangeTo2(BufferedTransformation &target, lword &begin, lword end=LWORD_MAX, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true) const =0;
//! upon return, messageCount contains number of messages that have finished being transfered, and returns the number of bytes left in the current transfer block
size_t TransferMessagesTo2(BufferedTransformation &target, unsigned int &messageCount, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true);
//! returns the number of bytes left in the current transfer block
size_t TransferAllTo2(BufferedTransformation &target, const std::string &channel=DEFAULT_CHANNEL, bool blocking=true);
//@}
//! \name CHANNELS
//@{
struct NoChannelSupport : public NotImplemented
{NoChannelSupport(const std::string &name) : NotImplemented(name + ": this object doesn't support multiple channels") {}};
struct InvalidChannelName : public InvalidArgument
{InvalidChannelName(const std::string &name, const std::string &channel) : InvalidArgument(name + ": unexpected channel name \"" + channel + "\"") {}};
size_t ChannelPut(const std::string &channel, byte inByte, bool blocking=true)
{return ChannelPut(channel, &inByte, 1, blocking);}
size_t ChannelPut(const std::string &channel, const byte *inString, size_t length, bool blocking=true)
{return ChannelPut2(channel, inString, length, 0, blocking);}
size_t ChannelPutModifiable(const std::string &channel, byte *inString, size_t length, bool blocking=true)
{return ChannelPutModifiable2(channel, inString, length, 0, blocking);}
size_t ChannelPutWord16(const std::string &channel, word16 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
size_t ChannelPutWord32(const std::string &channel, word32 value, ByteOrder order=BIG_ENDIAN_ORDER, bool blocking=true);
bool ChannelMessageEnd(const std::string &channel, int propagation=-1, bool blocking=true)
{return !!ChannelPut2(channel, NULL, 0, propagation < 0 ? -1 : propagation+1, blocking);}
size_t ChannelPutMessageEnd(const std::string &channel, const byte *inString, size_t length, int propagation=-1, bool blocking=true)
{return ChannelPut2(channel, inString, length, propagation < 0 ? -1 : propagation+1, blocking);}
virtual byte * ChannelCreatePutSpace(const std::string &channel, size_t &size);
virtual size_t ChannelPut2(const std::string &channel, const byte *begin, size_t length, int messageEnd, bool blocking);
virtual size_t ChannelPutModifiable2(const std::string &channel, byte *begin, size_t length, int messageEnd, bool blocking);
virtual bool ChannelFlush(const std::string &channel, bool hardFlush, int propagation=-1, bool blocking=true);
virtual bool ChannelMessageSeriesEnd(const std::string &channel, int propagation=-1, bool blocking=true);
virtual void SetRetrievalChannel(const std::string &channel);
//@}
//! \name ATTACHMENT
/*! Some BufferedTransformation objects (e.g. Filter objects)
allow other BufferedTransformation objects to be attached. When
this is done, the first object instead of buffering its output,
sents that output to the attached object as input. The entire
attachment chain is deleted when the anchor object is destructed.
*/
//@{
//! returns whether this object allows attachment
virtual bool Attachable() {return false;}
//! returns the object immediately attached to this object or NULL for no attachment
virtual BufferedTransformation *AttachedTransformation() {assert(!Attachable()); return 0;}
//!
virtual const BufferedTransformation *AttachedTransformation() const
{return const_cast<BufferedTransformation *>(this)->AttachedTransformation();}
//! delete the current attachment chain and replace it with newAttachment
virtual void Detach(BufferedTransformation *newAttachment = 0)
{assert(!Attachable()); throw NotImplemented("BufferedTransformation: this object is not attachable");}
//! add newAttachment to the end of attachment chain
virtual void Attach(BufferedTransformation *newAttachment);
//@}
protected:
static int DecrementPropagation(int propagation)
{return propagation != 0 ? propagation - 1 : 0;}
private:
byte m_buf[4]; // for ChannelPutWord16 and ChannelPutWord32, to ensure buffer isn't deallocated before non-blocking operation completes
};
//! returns a reference to a BufferedTransformation object that discards all input
BufferedTransformation & TheBitBucket();
//! interface for crypto material, such as public and private keys, and crypto parameters
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoMaterial : public NameValuePairs
{
public:
//! exception thrown when invalid crypto material is detected
class CRYPTOPP_DLL InvalidMaterial : public InvalidDataFormat
{
public:
explicit InvalidMaterial(const std::string &s) : InvalidDataFormat(s) {}
};
//! assign values from source to this object
/*! \note This function can be used to create a public key from a private key. */
virtual void AssignFrom(const NameValuePairs &source) =0;
//! check this object for errors
/*! \param level denotes the level of thoroughness:
0 - using this object won't cause a crash or exception (rng is ignored)
1 - this object will probably function (encrypt, sign, etc.) correctly (but may not check for weak keys and such)
2 - make sure this object will function correctly, and do reasonable security checks
3 - do checks that may take a long time
\return true if the tests pass */
virtual bool Validate(RandomNumberGenerator &rng, unsigned int level) const =0;
//! throws InvalidMaterial if this object fails Validate() test
virtual void ThrowIfInvalid(RandomNumberGenerator &rng, unsigned int level) const
{if (!Validate(rng, level)) throw InvalidMaterial("CryptoMaterial: this object contains invalid values");}
// virtual std::vector<std::string> GetSupportedFormats(bool includeSaveOnly=false, bool includeLoadOnly=false);
//! save key into a BufferedTransformation
virtual void Save(BufferedTransformation &bt) const
{throw NotImplemented("CryptoMaterial: this object does not support saving");}
//! load key from a BufferedTransformation
/*! \throws KeyingErr if decode fails
\note Generally does not check that the key is valid.
Call ValidateKey() or ThrowIfInvalidKey() to check that. */
virtual void Load(BufferedTransformation &bt)
{throw NotImplemented("CryptoMaterial: this object does not support loading");}
//! \return whether this object supports precomputation
virtual bool SupportsPrecomputation() const {return false;}
//! do precomputation
/*! The exact semantics of Precompute() is varies, but
typically it means calculate a table of n objects
that can be used later to speed up computation. */
virtual void Precompute(unsigned int n)
{assert(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
//! retrieve previously saved precomputation
virtual void LoadPrecomputation(BufferedTransformation &storedPrecomputation)
{assert(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
//! save precomputation for later use
virtual void SavePrecomputation(BufferedTransformation &storedPrecomputation) const
{assert(!SupportsPrecomputation()); throw NotImplemented("CryptoMaterial: this object does not support precomputation");}
// for internal library use
void DoQuickSanityCheck() const {ThrowIfInvalid(NullRNG(), 0);}
#if (defined(__SUNPRO_CC) && __SUNPRO_CC < 0x590)
// Sun Studio 11/CC 5.8 workaround: it generates incorrect code when casting to an empty virtual base class
char m_sunCCworkaround;
#endif
};
//! interface for generatable crypto material, such as private keys and crypto parameters
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE GeneratableCryptoMaterial : virtual public CryptoMaterial
{
public:
//! generate a random key or crypto parameters
/*! \throws KeyingErr if algorithm parameters are invalid, or if a key can't be generated
(e.g., if this is a public key object) */
virtual void GenerateRandom(RandomNumberGenerator &rng, const NameValuePairs ¶ms = g_nullNameValuePairs)
{throw NotImplemented("GeneratableCryptoMaterial: this object does not support key/parameter generation");}
//! calls the above function with a NameValuePairs object that just specifies "KeySize"
void GenerateRandomWithKeySize(RandomNumberGenerator &rng, unsigned int keySize);
};
//! interface for public keys
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKey : virtual public CryptoMaterial
{
};
//! interface for private keys
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKey : public GeneratableCryptoMaterial
{
};
//! interface for crypto prameters
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE CryptoParameters : public GeneratableCryptoMaterial
{
};
//! interface for asymmetric algorithms
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AsymmetricAlgorithm : public Algorithm
{
public:
//! returns a reference to the crypto material used by this object
virtual CryptoMaterial & AccessMaterial() =0;
//! returns a const reference to the crypto material used by this object
virtual const CryptoMaterial & GetMaterial() const =0;
//! for backwards compatibility, calls AccessMaterial().Load(bt)
void BERDecode(BufferedTransformation &bt)
{AccessMaterial().Load(bt);}
//! for backwards compatibility, calls GetMaterial().Save(bt)
void DEREncode(BufferedTransformation &bt) const
{GetMaterial().Save(bt);}
};
//! interface for asymmetric algorithms using public keys
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PublicKeyAlgorithm : public AsymmetricAlgorithm
{
public:
// VC60 workaround: no co-variant return type
CryptoMaterial & AccessMaterial() {return AccessPublicKey();}
const CryptoMaterial & GetMaterial() const {return GetPublicKey();}
virtual PublicKey & AccessPublicKey() =0;
virtual const PublicKey & GetPublicKey() const {return const_cast<PublicKeyAlgorithm *>(this)->AccessPublicKey();}
};
//! interface for asymmetric algorithms using private keys
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PrivateKeyAlgorithm : public AsymmetricAlgorithm
{
public:
CryptoMaterial & AccessMaterial() {return AccessPrivateKey();}
const CryptoMaterial & GetMaterial() const {return GetPrivateKey();}
virtual PrivateKey & AccessPrivateKey() =0;
virtual const PrivateKey & GetPrivateKey() const {return const_cast<PrivateKeyAlgorithm *>(this)->AccessPrivateKey();}
};
//! interface for key agreement algorithms
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE KeyAgreementAlgorithm : public AsymmetricAlgorithm
{
public:
CryptoMaterial & AccessMaterial() {return AccessCryptoParameters();}
const CryptoMaterial & GetMaterial() const {return GetCryptoParameters();}
virtual CryptoParameters & AccessCryptoParameters() =0;
virtual const CryptoParameters & GetCryptoParameters() const {return const_cast<KeyAgreementAlgorithm *>(this)->AccessCryptoParameters();}
};
//! interface for public-key encryptors and decryptors
/*! This class provides an interface common to encryptors and decryptors
for querying their plaintext and ciphertext lengths.
*/
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_CryptoSystem
{
public:
virtual ~PK_CryptoSystem() {}
//! maximum length of plaintext for a given ciphertext length
/*! \note This function returns 0 if ciphertextLength is not valid (too long or too short). */
virtual size_t MaxPlaintextLength(size_t ciphertextLength) const =0;
//! calculate length of ciphertext given length of plaintext
/*! \note This function returns 0 if plaintextLength is not valid (too long). */
virtual size_t CiphertextLength(size_t plaintextLength) const =0;
//! this object supports the use of the parameter with the given name
/*! some possible parameter names: EncodingParameters, KeyDerivationParameters */
virtual bool ParameterSupported(const char *name) const =0;
//! return fixed ciphertext length, if one exists, otherwise return 0
/*! \note "Fixed" here means length of ciphertext does not depend on length of plaintext.
It usually does depend on the key length. */
virtual size_t FixedCiphertextLength() const {return 0;}
//! return maximum plaintext length given the fixed ciphertext length, if one exists, otherwise return 0
virtual size_t FixedMaxPlaintextLength() const {return 0;}
#ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
size_t MaxPlainTextLength(size_t cipherTextLength) const {return MaxPlaintextLength(cipherTextLength);}
size_t CipherTextLength(size_t plainTextLength) const {return CiphertextLength(plainTextLength);}
#endif
};
//! interface for public-key encryptors
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Encryptor : public PK_CryptoSystem, public PublicKeyAlgorithm
{
public:
//! exception thrown when trying to encrypt plaintext of invalid length
class CRYPTOPP_DLL InvalidPlaintextLength : public Exception
{
public:
InvalidPlaintextLength() : Exception(OTHER_ERROR, "PK_Encryptor: invalid plaintext length") {}
};
//! encrypt a byte string
/*! \pre CiphertextLength(plaintextLength) != 0 (i.e., plaintext isn't too long)
\pre size of ciphertext == CiphertextLength(plaintextLength)
*/
virtual void Encrypt(RandomNumberGenerator &rng,
const byte *plaintext, size_t plaintextLength,
byte *ciphertext, const NameValuePairs ¶meters = g_nullNameValuePairs) const =0;
//! create a new encryption filter
/*! \note The caller is responsible for deleting the returned pointer.
\note Encoding parameters should be passed in the "EP" channel.
*/
virtual BufferedTransformation * CreateEncryptionFilter(RandomNumberGenerator &rng,
BufferedTransformation *attachment=NULL, const NameValuePairs ¶meters = g_nullNameValuePairs) const;
};
//! interface for public-key decryptors
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Decryptor : public PK_CryptoSystem, public PrivateKeyAlgorithm
{
public:
//! decrypt a byte string, and return the length of plaintext
/*! \pre size of plaintext == MaxPlaintextLength(ciphertextLength) bytes.
\return the actual length of the plaintext, indication that decryption failed.
*/
virtual DecodingResult Decrypt(RandomNumberGenerator &rng,
const byte *ciphertext, size_t ciphertextLength,
byte *plaintext, const NameValuePairs ¶meters = g_nullNameValuePairs) const =0;
//! create a new decryption filter
/*! \note caller is responsible for deleting the returned pointer
*/
virtual BufferedTransformation * CreateDecryptionFilter(RandomNumberGenerator &rng,
BufferedTransformation *attachment=NULL, const NameValuePairs ¶meters = g_nullNameValuePairs) const;
//! decrypt a fixed size ciphertext
DecodingResult FixedLengthDecrypt(RandomNumberGenerator &rng, const byte *ciphertext, byte *plaintext, const NameValuePairs ¶meters = g_nullNameValuePairs) const
{return Decrypt(rng, ciphertext, FixedCiphertextLength(), plaintext, parameters);}
};
#ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
typedef PK_CryptoSystem PK_FixedLengthCryptoSystem;
typedef PK_Encryptor PK_FixedLengthEncryptor;
typedef PK_Decryptor PK_FixedLengthDecryptor;
#endif
//! interface for public-key signers and verifiers
/*! This class provides an interface common to signers and verifiers
for querying scheme properties.
*/
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_SignatureScheme
{
public:
//! invalid key exception, may be thrown by any function in this class if the private or public key has a length that can't be used
class CRYPTOPP_DLL InvalidKeyLength : public Exception
{
public:
InvalidKeyLength(const std::string &message) : Exception(OTHER_ERROR, message) {}
};
//! key too short exception, may be thrown by any function in this class if the private or public key is too short to sign or verify anything
class CRYPTOPP_DLL KeyTooShort : public InvalidKeyLength
{
public:
KeyTooShort() : InvalidKeyLength("PK_Signer: key too short for this signature scheme") {}
};
virtual ~PK_SignatureScheme() {}
//! signature length if it only depends on the key, otherwise 0
virtual size_t SignatureLength() const =0;
//! maximum signature length produced for a given length of recoverable message part
virtual size_t MaxSignatureLength(size_t recoverablePartLength = 0) const {return SignatureLength();}
//! length of longest message that can be recovered, or 0 if this signature scheme does not support message recovery
virtual size_t MaxRecoverableLength() const =0;
//! length of longest message that can be recovered from a signature of given length, or 0 if this signature scheme does not support message recovery
virtual size_t MaxRecoverableLengthFromSignatureLength(size_t signatureLength) const =0;
//! requires a random number generator to sign
/*! if this returns false, NullRNG() can be passed to functions that take RandomNumberGenerator & */
virtual bool IsProbabilistic() const =0;
//! whether or not a non-recoverable message part can be signed
virtual bool AllowNonrecoverablePart() const =0;
//! if this function returns true, during verification you must input the signature before the message, otherwise you can input it at anytime */
virtual bool SignatureUpfront() const {return false;}
//! whether you must input the recoverable part before the non-recoverable part during signing
virtual bool RecoverablePartFirst() const =0;
};
//! interface for accumulating messages to be signed or verified
/*! Only Update() should be called
on this class. No other functions inherited from HashTransformation should be called.
*/
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_MessageAccumulator : public HashTransformation
{
public:
//! should not be called on PK_MessageAccumulator
unsigned int DigestSize() const
{throw NotImplemented("PK_MessageAccumulator: DigestSize() should not be called");}
//! should not be called on PK_MessageAccumulator
void TruncatedFinal(byte *digest, size_t digestSize)
{throw NotImplemented("PK_MessageAccumulator: TruncatedFinal() should not be called");}
};
//! interface for public-key signers
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Signer : public PK_SignatureScheme, public PrivateKeyAlgorithm
{
public:
//! create a new HashTransformation to accumulate the message to be signed
virtual PK_MessageAccumulator * NewSignatureAccumulator(RandomNumberGenerator &rng) const =0;
virtual void InputRecoverableMessage(PK_MessageAccumulator &messageAccumulator, const byte *recoverableMessage, size_t recoverableMessageLength) const =0;
//! sign and delete messageAccumulator (even in case of exception thrown)
/*! \pre size of signature == MaxSignatureLength()
\return actual signature length
*/
virtual size_t Sign(RandomNumberGenerator &rng, PK_MessageAccumulator *messageAccumulator, byte *signature) const;
//! sign and restart messageAccumulator
/*! \pre size of signature == MaxSignatureLength()
\return actual signature length
*/
virtual size_t SignAndRestart(RandomNumberGenerator &rng, PK_MessageAccumulator &messageAccumulator, byte *signature, bool restart=true) const =0;
//! sign a message
/*! \pre size of signature == MaxSignatureLength()
\return actual signature length
*/
virtual size_t SignMessage(RandomNumberGenerator &rng, const byte *message, size_t messageLen, byte *signature) const;
//! sign a recoverable message
/*! \pre size of signature == MaxSignatureLength(recoverableMessageLength)
\return actual signature length
*/
virtual size_t SignMessageWithRecovery(RandomNumberGenerator &rng, const byte *recoverableMessage, size_t recoverableMessageLength,
const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength, byte *signature) const;
};
//! interface for public-key signature verifiers
/*! The Recover* functions throw NotImplemented if the signature scheme does not support
message recovery.
The Verify* functions throw InvalidDataFormat if the scheme does support message
recovery and the signature contains a non-empty recoverable message part. The
Recovery* functions should be used in that case.
*/
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE PK_Verifier : public PK_SignatureScheme, public PublicKeyAlgorithm
{
public:
//! create a new HashTransformation to accumulate the message to be verified
virtual PK_MessageAccumulator * NewVerificationAccumulator() const =0;
//! input signature into a message accumulator
virtual void InputSignature(PK_MessageAccumulator &messageAccumulator, const byte *signature, size_t signatureLength) const =0;
//! check whether messageAccumulator contains a valid signature and message, and delete messageAccumulator (even in case of exception thrown)
virtual bool Verify(PK_MessageAccumulator *messageAccumulator) const;
//! check whether messageAccumulator contains a valid signature and message, and restart messageAccumulator
virtual bool VerifyAndRestart(PK_MessageAccumulator &messageAccumulator) const =0;
//! check whether input signature is a valid signature for input message
virtual bool VerifyMessage(const byte *message, size_t messageLen,
const byte *signature, size_t signatureLength) const;
//! recover a message from its signature
/*! \pre size of recoveredMessage == MaxRecoverableLengthFromSignatureLength(signatureLength)
*/
virtual DecodingResult Recover(byte *recoveredMessage, PK_MessageAccumulator *messageAccumulator) const;
//! recover a message from its signature
/*! \pre size of recoveredMessage == MaxRecoverableLengthFromSignatureLength(signatureLength)
*/
virtual DecodingResult RecoverAndRestart(byte *recoveredMessage, PK_MessageAccumulator &messageAccumulator) const =0;
//! recover a message from its signature
/*! \pre size of recoveredMessage == MaxRecoverableLengthFromSignatureLength(signatureLength)
*/
virtual DecodingResult RecoverMessage(byte *recoveredMessage,
const byte *nonrecoverableMessage, size_t nonrecoverableMessageLength,
const byte *signature, size_t signatureLength) const;
};
//! interface for domains of simple key agreement protocols
/*! A key agreement domain is a set of parameters that must be shared
by two parties in a key agreement protocol, along with the algorithms
for generating key pairs and deriving agreed values.
*/
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE SimpleKeyAgreementDomain : public KeyAgreementAlgorithm
{
public:
//! return length of agreed value produced
virtual unsigned int AgreedValueLength() const =0;
//! return length of private keys in this domain
virtual unsigned int PrivateKeyLength() const =0;
//! return length of public keys in this domain
virtual unsigned int PublicKeyLength() const =0;
//! generate private key
/*! \pre size of privateKey == PrivateKeyLength() */
virtual void GeneratePrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
//! generate public key
/*! \pre size of publicKey == PublicKeyLength() */
virtual void GeneratePublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
//! generate private/public key pair
/*! \note equivalent to calling GeneratePrivateKey() and then GeneratePublicKey() */
virtual void GenerateKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
//! derive agreed value from your private key and couterparty's public key, return false in case of failure
/*! \note If you have previously validated the public key, use validateOtherPublicKey=false to save time.
\pre size of agreedValue == AgreedValueLength()
\pre length of privateKey == PrivateKeyLength()
\pre length of otherPublicKey == PublicKeyLength()
*/
virtual bool Agree(byte *agreedValue, const byte *privateKey, const byte *otherPublicKey, bool validateOtherPublicKey=true) const =0;
#ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
bool ValidateDomainParameters(RandomNumberGenerator &rng) const
{return GetCryptoParameters().Validate(rng, 2);}
#endif
};
//! interface for domains of authenticated key agreement protocols
/*! In an authenticated key agreement protocol, each party has two
key pairs. The long-lived key pair is called the static key pair,
and the short-lived key pair is called the ephemeral key pair.
*/
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE AuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm
{
public:
//! return length of agreed value produced
virtual unsigned int AgreedValueLength() const =0;
//! return length of static private keys in this domain
virtual unsigned int StaticPrivateKeyLength() const =0;
//! return length of static public keys in this domain
virtual unsigned int StaticPublicKeyLength() const =0;
//! generate static private key
/*! \pre size of privateKey == PrivateStaticKeyLength() */
virtual void GenerateStaticPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
//! generate static public key
/*! \pre size of publicKey == PublicStaticKeyLength() */
virtual void GenerateStaticPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
//! generate private/public key pair
/*! \note equivalent to calling GenerateStaticPrivateKey() and then GenerateStaticPublicKey() */
virtual void GenerateStaticKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
//! return length of ephemeral private keys in this domain
virtual unsigned int EphemeralPrivateKeyLength() const =0;
//! return length of ephemeral public keys in this domain
virtual unsigned int EphemeralPublicKeyLength() const =0;
//! generate ephemeral private key
/*! \pre size of privateKey == PrivateEphemeralKeyLength() */
virtual void GenerateEphemeralPrivateKey(RandomNumberGenerator &rng, byte *privateKey) const =0;
//! generate ephemeral public key
/*! \pre size of publicKey == PublicEphemeralKeyLength() */
virtual void GenerateEphemeralPublicKey(RandomNumberGenerator &rng, const byte *privateKey, byte *publicKey) const =0;
//! generate private/public key pair
/*! \note equivalent to calling GenerateEphemeralPrivateKey() and then GenerateEphemeralPublicKey() */
virtual void GenerateEphemeralKeyPair(RandomNumberGenerator &rng, byte *privateKey, byte *publicKey) const;
//! derive agreed value from your private keys and couterparty's public keys, return false in case of failure
/*! \note The ephemeral public key will always be validated.
If you have previously validated the static public key, use validateStaticOtherPublicKey=false to save time.
\pre size of agreedValue == AgreedValueLength()
\pre length of staticPrivateKey == StaticPrivateKeyLength()
\pre length of ephemeralPrivateKey == EphemeralPrivateKeyLength()
\pre length of staticOtherPublicKey == StaticPublicKeyLength()
\pre length of ephemeralOtherPublicKey == EphemeralPublicKeyLength()
*/
virtual bool Agree(byte *agreedValue,
const byte *staticPrivateKey, const byte *ephemeralPrivateKey,
const byte *staticOtherPublicKey, const byte *ephemeralOtherPublicKey,
bool validateStaticOtherPublicKey=true) const =0;
#ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
bool ValidateDomainParameters(RandomNumberGenerator &rng) const
{return GetCryptoParameters().Validate(rng, 2);}
#endif
};
// interface for password authenticated key agreement protocols, not implemented yet
#if 0
//! interface for protocol sessions
/*! The methods should be called in the following order:
InitializeSession(rng, parameters); // or call initialize method in derived class
while (true)
{
if (OutgoingMessageAvailable())
{
length = GetOutgoingMessageLength();
GetOutgoingMessage(message);
; // send outgoing message
}
if (LastMessageProcessed())
break;
; // receive incoming message
ProcessIncomingMessage(message);
}
; // call methods in derived class to obtain result of protocol session
*/
class ProtocolSession
{
public:
//! exception thrown when an invalid protocol message is processed
class ProtocolError : public Exception
{
public:
ProtocolError(ErrorType errorType, const std::string &s) : Exception(errorType, s) {}
};
//! exception thrown when a function is called unexpectedly
/*! for example calling ProcessIncomingMessage() when ProcessedLastMessage() == true */
class UnexpectedMethodCall : public Exception
{
public:
UnexpectedMethodCall(const std::string &s) : Exception(OTHER_ERROR, s) {}
};
ProtocolSession() : m_rng(NULL), m_throwOnProtocolError(true), m_validState(false) {}
virtual ~ProtocolSession() {}
virtual void InitializeSession(RandomNumberGenerator &rng, const NameValuePairs ¶meters) =0;
bool GetThrowOnProtocolError() const {return m_throwOnProtocolError;}
void SetThrowOnProtocolError(bool throwOnProtocolError) {m_throwOnProtocolError = throwOnProtocolError;}
bool HasValidState() const {return m_validState;}
virtual bool OutgoingMessageAvailable() const =0;
virtual unsigned int GetOutgoingMessageLength() const =0;
virtual void GetOutgoingMessage(byte *message) =0;
virtual bool LastMessageProcessed() const =0;
virtual void ProcessIncomingMessage(const byte *message, unsigned int messageLength) =0;
protected:
void HandleProtocolError(Exception::ErrorType errorType, const std::string &s) const;
void CheckAndHandleInvalidState() const;
void SetValidState(bool valid) {m_validState = valid;}
RandomNumberGenerator *m_rng;
private:
bool m_throwOnProtocolError, m_validState;
};
class KeyAgreementSession : public ProtocolSession
{
public:
virtual unsigned int GetAgreedValueLength() const =0;
virtual void GetAgreedValue(byte *agreedValue) const =0;
};
class PasswordAuthenticatedKeyAgreementSession : public KeyAgreementSession
{
public:
void InitializePasswordAuthenticatedKeyAgreementSession(RandomNumberGenerator &rng,
const byte *myId, unsigned int myIdLength,
const byte *counterPartyId, unsigned int counterPartyIdLength,
const byte *passwordOrVerifier, unsigned int passwordOrVerifierLength);
};
class PasswordAuthenticatedKeyAgreementDomain : public KeyAgreementAlgorithm
{
public:
//! return whether the domain parameters stored in this object are valid
virtual bool ValidateDomainParameters(RandomNumberGenerator &rng) const
{return GetCryptoParameters().Validate(rng, 2);}
virtual unsigned int GetPasswordVerifierLength(const byte *password, unsigned int passwordLength) const =0;
virtual void GeneratePasswordVerifier(RandomNumberGenerator &rng, const byte *userId, unsigned int userIdLength, const byte *password, unsigned int passwordLength, byte *verifier) const =0;
enum RoleFlags {CLIENT=1, SERVER=2, INITIATOR=4, RESPONDER=8};
virtual bool IsValidRole(unsigned int role) =0;
virtual PasswordAuthenticatedKeyAgreementSession * CreateProtocolSession(unsigned int role) const =0;
};
#endif
//! BER Decode Exception Class, may be thrown during an ASN1 BER decode operation
class CRYPTOPP_DLL BERDecodeErr : public InvalidArgument
{
public:
BERDecodeErr() : InvalidArgument("BER decode error") {}
BERDecodeErr(const std::string &s) : InvalidArgument(s) {}
};
//! interface for encoding and decoding ASN1 objects
class CRYPTOPP_DLL CRYPTOPP_NO_VTABLE ASN1Object
{
public:
virtual ~ASN1Object() {}
//! decode this object from a BufferedTransformation, using BER (Basic Encoding Rules)
virtual void BERDecode(BufferedTransformation &bt) =0;
//! encode this object into a BufferedTransformation, using DER (Distinguished Encoding Rules)
virtual void DEREncode(BufferedTransformation &bt) const =0;
//! encode this object into a BufferedTransformation, using BER
/*! this may be useful if DEREncode() would be too inefficient */
virtual void BEREncode(BufferedTransformation &bt) const {DEREncode(bt);}
};
#ifdef CRYPTOPP_MAINTAIN_BACKWARDS_COMPATIBILITY
typedef PK_SignatureScheme PK_SignatureSystem;
typedef SimpleKeyAgreementDomain PK_SimpleKeyAgreementDomain;
typedef AuthenticatedKeyAgreementDomain PK_AuthenticatedKeyAgreementDomain;
#endif
NAMESPACE_END
#endif
| [
"tungnt.rec@gmail.com"
] | tungnt.rec@gmail.com |
a5eb52ec89a118b58f59fb2833e8ec8bba65cdb1 | 4d238f669a483255fbc9ea4a2322f9a1a5737013 | /LAB4/robots/Unit.cpp | d259181e3dc84fa985630ceae0369382441c6d5e | [] | no_license | chanleii/TDDD86-Labs-Completed | 93755cf45b45536cc2ccf1e8f874fdd2d4ff9ad5 | 6b78979436caa91dbebead9815777ab98ae5165e | refs/heads/master | 2023-07-06T11:14:14.534976 | 2023-06-29T10:37:54 | 2023-06-29T10:38:25 | 297,643,255 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,176 | cpp | /**
* Copyright (C) David Wolfe, 1999. All rights reserved.
* Ported to Qt and adapted for TDDD86, 2015.
*/
#include "Unit.h"
#include "constants.h"
#include "utilities.h"
#include <cstdlib>
#include <cmath>
Unit::Unit() {
teleport();
}
Unit::Unit(const Unit& u) {
x = u.x;
y = u.y;
}
Unit::Unit(const Point& p) {
x = p.x;
y = p.y;
}
Point Unit::asPoint() const {
return Point{x, y};
}
bool Unit::at(const Unit& u) const {
return (x == u.x && y == u.y);
}
bool Unit::attacks(const Unit& u) const {
return (abs(x - u.x) <= 1 &&
abs(y - u.y) <= 1);
}
void Unit::moveTowards(const Unit& u) {
if (x > u.x) x--;
if (x < u.x) x++;
if (y > u.y) y--;
if (y < u.y) y++;
checkBounds();
}
void Unit::teleport() {
x = rand_int (MIN_X, MAX_X);
y = rand_int (MIN_Y, MAX_Y);
}
double Unit::distanceTo(const Unit& u) const {
double dx = u.x - x;
double dy = u.y - y;
return sqrt(dx * dx + dy * dy);
}
void Unit::checkBounds() {
if (x < MIN_X) x = MIN_X;
if (x > MAX_X) x = MAX_X;
if (y < MIN_Y) y = MIN_Y;
if (y > MAX_Y) y = MAX_Y;
}
void Unit::draw(QGraphicsScene* scene) {}
| [
"channie.d98@gmail.com"
] | channie.d98@gmail.com |
979f7108fca2390f6b17cd3b5b77ca4ebddda36f | 0577a46d8d28e1fd8636893bbdd2b18270bb8eb8 | /update_notifier/thirdparty/wxWidgets/tests/test.cpp | 44e0dae1f15e0089484a8924fad5f4144574a3b6 | [
"BSD-3-Clause"
] | permissive | ric2b/Vivaldi-browser | 388a328b4cb838a4c3822357a5529642f86316a5 | 87244f4ee50062e59667bf8b9ca4d5291b6818d7 | refs/heads/master | 2022-12-21T04:44:13.804535 | 2022-12-17T16:30:35 | 2022-12-17T16:30:35 | 86,637,416 | 166 | 41 | BSD-3-Clause | 2021-03-31T18:49:30 | 2017-03-29T23:09:05 | null | UTF-8 | C++ | false | false | 18,722 | cpp | ///////////////////////////////////////////////////////////////////////////////
// Name: test.cpp
// Purpose: Test program for wxWidgets
// Author: Mike Wetherell
// Copyright: (c) 2004 Mike Wetherell
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
// For compilers that support precompilation, includes "wx/wx.h"
// and "catch.hpp"
#include "testprec.h"
// Suppress some warnings in catch_impl.hpp.
wxCLANG_WARNING_SUPPRESS(missing-braces)
wxCLANG_WARNING_SUPPRESS(logical-op-parentheses)
wxCLANG_WARNING_SUPPRESS(inconsistent-missing-override)
// This file needs to get the CATCH definitions in addition to the usual
// assertion macros declarations from catch.hpp included by testprec.h.
// Including an internal file like this is ugly, but there doesn't seem to be
// any better way, see https://github.com/philsquared/Catch/issues/1061
#include "internal/catch_impl.hpp"
wxCLANG_WARNING_RESTORE(missing-braces)
wxCLANG_WARNING_RESTORE(logical-op-parentheses)
wxCLANG_WARNING_RESTORE(inconsistent-missing-override)
// This probably could be done by predefining CLARA_CONFIG_MAIN, but at the
// point where we are, just define this global variable manually.
namespace Catch { namespace Clara { UnpositionalTag _; } }
// Also define our own global variables.
namespace wxPrivate
{
std::string wxTheCurrentTestClass, wxTheCurrentTestMethod;
}
// for all others, include the necessary headers
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
#include "wx/apptrait.h"
#include "wx/cmdline.h"
#include <exception>
#include <iostream>
#ifdef __WINDOWS__
#include "wx/msw/msvcrt.h"
#endif
#ifdef __WXOSX__
#include "wx/osx/private.h"
#endif
#if wxUSE_GUI
#include "testableframe.h"
#ifdef __WXGTK__
#include <glib.h>
#endif // __WXGTK__
#endif // wxUSE_GUI
#include "wx/socket.h"
#include "wx/evtloop.h"
using namespace std;
// ----------------------------------------------------------------------------
// helper classes
// ----------------------------------------------------------------------------
// exception class for MSVC debug CRT assertion failures
#ifdef wxUSE_VC_CRTDBG
struct CrtAssertFailure
{
CrtAssertFailure(const char *message) : m_msg(message) { }
const wxString m_msg;
wxDECLARE_NO_ASSIGN_CLASS(CrtAssertFailure);
};
CATCH_TRANSLATE_EXCEPTION(CrtAssertFailure& e)
{
return "CRT assert failure: " + e.m_msg.ToStdString(wxConvUTF8);
}
#endif // wxUSE_VC_CRTDBG
#if wxDEBUG_LEVEL
// Information about the last not yet handled assertion.
static wxString s_lastAssertMessage;
static wxString FormatAssertMessage(const wxString& file,
int line,
const wxString& func,
const wxString& cond,
const wxString& msg)
{
wxString str;
str << wxASCII_STR("wxWidgets assert: ") << cond
<< wxASCII_STR(" failed at ") << file << wxASCII_STR(":") << line
<< wxASCII_STR(" in ") << func << wxASCII_STR(" with message '")
<< msg << wxASCII_STR("'");
return str;
}
static void TestAssertHandler(const wxString& file,
int line,
const wxString& func,
const wxString& cond,
const wxString& msg)
{
// Determine whether we can safely throw an exception to just make the test
// fail or whether we need to abort (in this case "msg" will contain the
// explanation why did we decide to do it).
wxString abortReason;
const wxString
assertMessage = FormatAssertMessage(file, line, func, cond, msg);
if ( !wxIsMainThread() )
{
// Exceptions thrown from worker threads are not caught currently and
// so we'd just die without any useful information -- abort instead.
abortReason << assertMessage << wxASCII_STR(" in a worker thread.");
}
#if __cplusplus >= 201703L || wxCHECK_VISUALC_VERSION(14)
else if ( uncaught_exceptions() )
#else
else if ( uncaught_exception() )
#endif
{
// Throwing while already handling an exception would result in
// terminate() being called and we wouldn't get any useful information
// about why the test failed then.
if ( s_lastAssertMessage.empty() )
{
abortReason << assertMessage
<< wxASCII_STR("while handling an exception");
}
else // In this case the exception is due to a previous assert.
{
abortReason << s_lastAssertMessage
<< wxASCII_STR("\n and another ") << assertMessage
<< wxASCII_STR(" while handling it.");
}
}
else // Can "safely" throw from here.
{
// Remember this in case another assert happens while handling this
// exception: we want to show the original assert as it's usually more
// useful to determine the real root of the problem.
s_lastAssertMessage = assertMessage;
throw TestAssertFailure(file, line, func, cond, msg);
}
#if wxUSE_STACKWALKER
const wxString& stackTrace = wxApp::GetValidTraits().GetAssertStackTrace();
if ( !stackTrace.empty() )
abortReason << wxASCII_STR("\n\nAssert call stack:\n") << stackTrace;
#endif // wxUSE_STACKWALKER
wxFputs(abortReason, stderr);
fflush(stderr);
_exit(-1);
}
CATCH_TRANSLATE_EXCEPTION(TestAssertFailure& e)
{
wxString desc = e.m_msg;
if ( desc.empty() )
desc.Printf(wxASCII_STR("Condition \"%s\" failed"), e.m_cond);
desc += wxString::Format(wxASCII_STR(" in %s() at %s:%d"), e.m_func, e.m_file, e.m_line);
return desc.ToStdString(wxConvUTF8);
}
#endif // wxDEBUG_LEVEL
#if wxUSE_GUI
typedef wxApp TestAppBase;
typedef wxGUIAppTraits TestAppTraitsBase;
#else
typedef wxAppConsole TestAppBase;
typedef wxConsoleAppTraits TestAppTraitsBase;
#endif
// The application class
//
class TestApp : public TestAppBase
{
public:
TestApp();
// standard overrides
virtual bool OnInit() wxOVERRIDE;
virtual int OnExit() wxOVERRIDE;
#ifdef __WIN32__
virtual wxAppTraits *CreateTraits() wxOVERRIDE
{
// Define a new class just to customize CanUseStderr() behaviour.
class TestAppTraits : public TestAppTraitsBase
{
public:
// We want to always use stderr, tests are also run unattended and
// in this case we really don't want to show any message boxes, as
// wxMessageOutputBest, used e.g. from the default implementation
// of wxApp::OnUnhandledException(), would do by default.
virtual bool CanUseStderr() wxOVERRIDE { return true; }
// Overriding CanUseStderr() is not enough, we also need to
// override this one to avoid returning false from it.
virtual bool WriteToStderr(const wxString& text) wxOVERRIDE
{
wxFputs(text, stderr);
fflush(stderr);
// Intentionally ignore any errors, we really don't want to
// show any message boxes in any case.
return true;
}
};
return new TestAppTraits;
}
#endif // __WIN32__
// Also override this method to avoid showing any dialogs from here -- and
// show some details about the exception along the way.
virtual bool OnExceptionInMainLoop() wxOVERRIDE
{
wxFprintf(stderr, wxASCII_STR("Unhandled exception in the main loop: %s\n"),
wxASCII_STR(Catch::translateActiveException().c_str()));
throw;
}
// used by events propagation test
virtual int FilterEvent(wxEvent& event) wxOVERRIDE;
virtual bool ProcessEvent(wxEvent& event) wxOVERRIDE;
void SetFilterEventFunc(FilterEventFunc f) { m_filterEventFunc = f; }
void SetProcessEventFunc(ProcessEventFunc f) { m_processEventFunc = f; }
// In console applications we run the tests directly from the overridden
// OnRun(), but in the GUI ones we run them when we get the first call to
// our EVT_IDLE handler to ensure that we do everything from inside the
// main event loop. This is especially important under wxOSX/Cocoa where
// the main event loop is different from the others but it's also safer to
// do it like this in the other ports as we test the GUI code in the same
// context as it's used usually, in normal programs, and it might behave
// differently without the event loop.
#if wxUSE_GUI
void OnIdle(wxIdleEvent& event)
{
if ( m_runTests )
{
m_runTests = false;
#ifdef __WXOSX__
// we need to wait until the window is activated and fully ready
// otherwise no events can be posted
wxEventLoopBase* const loop = wxEventLoop::GetActive();
if ( loop )
{
loop->DispatchTimeout(1000);
loop->Yield();
}
#endif // __WXOSX__
m_exitcode = RunTests();
ExitMainLoop();
}
event.Skip();
}
virtual int OnRun() wxOVERRIDE
{
if ( TestAppBase::OnRun() != 0 )
m_exitcode = EXIT_FAILURE;
return m_exitcode;
}
#else // !wxUSE_GUI
virtual int OnRun() wxOVERRIDE
{
return RunTests();
}
#endif // wxUSE_GUI/!wxUSE_GUI
private:
int RunTests();
// flag telling us whether we should run tests from our EVT_IDLE handler
bool m_runTests;
// event handling hooks
FilterEventFunc m_filterEventFunc;
ProcessEventFunc m_processEventFunc;
#if wxUSE_GUI
// the program exit code
int m_exitcode;
#endif // wxUSE_GUI
};
wxIMPLEMENT_APP_NO_MAIN(TestApp);
// ----------------------------------------------------------------------------
// global functions
// ----------------------------------------------------------------------------
#ifdef wxUSE_VC_CRTDBG
static int TestCrtReportHook(int reportType, char *message, int *)
{
if ( reportType != _CRT_ASSERT )
return FALSE;
throw CrtAssertFailure(message);
}
#endif // wxUSE_VC_CRTDBG
int main(int argc, char **argv)
{
// tests can be ran non-interactively so make sure we don't show any assert
// dialog boxes -- neither our own nor from MSVC debug CRT -- which would
// prevent them from completing
#if wxDEBUG_LEVEL
wxSetAssertHandler(TestAssertHandler);
#endif // wxDEBUG_LEVEL
#ifdef wxUSE_VC_CRTDBG
_CrtSetReportHook(TestCrtReportHook);
#endif // wxUSE_VC_CRTDBG
return wxEntry(argc, argv);
}
extern void SetFilterEventFunc(FilterEventFunc func)
{
wxGetApp().SetFilterEventFunc(func);
}
extern void SetProcessEventFunc(ProcessEventFunc func)
{
wxGetApp().SetProcessEventFunc(func);
}
extern bool IsNetworkAvailable()
{
// Somehow even though network is available on Travis CI build machines,
// attempts to open remote URIs sporadically fail, so don't run these tests
// under Travis to avoid false positives.
static int s_isTravis = -1;
if ( s_isTravis == -1 )
s_isTravis = wxGetEnv(wxASCII_STR("TRAVIS"), NULL);
if ( s_isTravis )
return false;
// NOTE: we could use wxDialUpManager here if it was in wxNet; since it's in
// wxCore we use a simple rough test:
wxSocketBase::Initialize();
wxIPV4address addr;
if (!addr.Hostname(wxASCII_STR("www.google.com")) || !addr.Service(wxASCII_STR("www")))
{
wxSocketBase::Shutdown();
return false;
}
wxSocketClient sock;
sock.SetTimeout(10); // 10 secs
bool online = sock.Connect(addr);
wxSocketBase::Shutdown();
return online;
}
extern bool IsAutomaticTest()
{
static int s_isAutomatic = -1;
if ( s_isAutomatic == -1 )
{
// Allow setting an environment variable to emulate buildslave user for
// testing.
wxString username;
if ( !wxGetEnv(wxASCII_STR("WX_TEST_USER"), &username) )
username = wxGetUserId();
username.MakeLower();
s_isAutomatic = username == wxASCII_STR("buildbot") ||
username.Matches(wxASCII_STR("sandbox*"));
// Also recognize various CI environments.
if ( !s_isAutomatic )
{
s_isAutomatic = wxGetEnv(wxASCII_STR("TRAVIS"), NULL) ||
wxGetEnv(wxASCII_STR("GITHUB_ACTIONS"), NULL) ||
wxGetEnv(wxASCII_STR("APPVEYOR"), NULL);
}
}
return s_isAutomatic == 1;
}
extern bool IsRunningUnderXVFB()
{
static int s_isRunningUnderXVFB = -1;
if ( s_isRunningUnderXVFB == -1 )
{
wxString value;
s_isRunningUnderXVFB = wxGetEnv(wxASCII_STR("wxUSE_XVFB"), &value) && value == wxASCII_STR("1");
}
return s_isRunningUnderXVFB == 1;
}
#ifdef __LINUX__
extern bool IsRunningInLXC()
{
// We're supposed to be able to detect running in LXC by checking for
// /dev/lxd existency, but this doesn't work under Travis for some reason,
// so just rely on having the environment variable defined for the
// corresponding builds in our .travis.yml.
wxString value;
return wxGetEnv("wxLXC", &value) && value == "1";
}
#endif // __LINUX__
#if wxUSE_GUI
bool EnableUITests()
{
static int s_enabled = -1;
if ( s_enabled == -1 )
{
// Allow explicitly configuring this via an environment variable under
// all platforms.
wxString enabled;
if ( wxGetEnv(wxASCII_STR("WX_UI_TESTS"), &enabled) )
{
if ( enabled == wxASCII_STR("1") )
s_enabled = 1;
else if ( enabled == wxASCII_STR("0") )
s_enabled = 0;
else
wxFprintf(stderr, wxASCII_STR("Unknown \"WX_UI_TESTS\" value \"%s\" ignored.\n"), enabled);
}
if ( s_enabled == -1 )
{
#if defined(__WXMSW__) || defined(__WXGTK__)
s_enabled = 1;
#else // !(__WXMSW__ || __WXGTK__)
s_enabled = 0;
#endif // (__WXMSW__ || __WXGTK__)
}
}
return s_enabled == 1;
}
void DeleteTestWindow(wxWindow* win)
{
if ( !win )
return;
wxWindow* const capture = wxWindow::GetCapture();
if ( capture )
{
if ( capture == win ||
capture->GetMainWindowOfCompositeControl() == win )
capture->ReleaseMouse();
}
delete win;
}
#ifdef __WXGTK__
#ifdef GDK_WINDOWING_X11
#include "X11/Xlib.h"
extern "C"
int wxTestX11ErrorHandler(Display*, XErrorEvent*)
{
fprintf(stderr, "\n*** X11 error while running %s(): ",
wxGetCurrentTestName().c_str());
return 0;
}
#endif // GDK_WINDOWING_X11
extern "C"
void
wxTestGLogHandler(const gchar* domain,
GLogLevelFlags level,
const gchar* message,
gpointer data)
{
// Check if debug messages in this domain will be logged.
if ( level == G_LOG_LEVEL_DEBUG )
{
static const char* const allowed = getenv("G_MESSAGES_DEBUG");
// By default debug messages are dropped, but if G_MESSAGES_DEBUG is
// defined, they're logged for the domains specified in it and if it
// has the special value "all", then all debug messages are shown.
//
// Note that the check here can result in false positives, e.g. domain
// "foo" would pass it even if G_MESSAGES_DEBUG only contains "foobar",
// but such cases don't seem to be important enough to bother
// accounting for them.
if ( !allowed ||
(strcmp(allowed, "all") != 0 && !strstr(allowed, domain)) )
{
return;
}
}
fprintf(stderr, "\n*** GTK log message while running %s(): ",
wxGetCurrentTestName().c_str());
g_log_default_handler(domain, level, message, data);
}
#endif // __WXGTK__
#endif // wxUSE_GUI
// ----------------------------------------------------------------------------
// TestApp
// ----------------------------------------------------------------------------
TestApp::TestApp()
{
m_runTests = true;
m_filterEventFunc = NULL;
m_processEventFunc = NULL;
#if wxUSE_GUI
m_exitcode = EXIT_SUCCESS;
#endif // wxUSE_GUI
}
// Init
//
bool TestApp::OnInit()
{
// Hack: don't call TestAppBase::OnInit() to let CATCH handle command line.
// Output some important information about the test environment.
#if wxUSE_GUI
cout << "Test program for wxWidgets GUI features\n"
#else
cout << "Test program for wxWidgets non-GUI features\n"
#endif
<< "build: " << WX_BUILD_OPTIONS_SIGNATURE << "\n"
<< "running under " << wxGetOsDescription()
<< " as " << wxGetUserId()
<< ", locale is " << setlocale(LC_ALL, NULL)
<< std::endl;
#if wxUSE_GUI
// create a parent window to be used as parent for the GUI controls
new wxTestableFrame();
Connect(wxEVT_IDLE, wxIdleEventHandler(TestApp::OnIdle));
#ifdef __WXGTK20__
g_log_set_default_handler(wxTestGLogHandler, NULL);
#endif // __WXGTK__
#ifdef GDK_WINDOWING_X11
XSetErrorHandler(wxTestX11ErrorHandler);
#endif // GDK_WINDOWING_X11
#endif // wxUSE_GUI
return true;
}
// Event handling
int TestApp::FilterEvent(wxEvent& event)
{
if ( m_filterEventFunc )
return (*m_filterEventFunc)(event);
return TestAppBase::FilterEvent(event);
}
bool TestApp::ProcessEvent(wxEvent& event)
{
if ( m_processEventFunc )
return (*m_processEventFunc)(event);
return TestAppBase::ProcessEvent(event);
}
// Run
//
int TestApp::RunTests()
{
#if wxUSE_LOG
// Switch off logging to avoid interfering with the tests output unless
// WXTRACE is set, as otherwise setting it would have no effect while
// running the tests.
if ( !wxGetEnv(wxASCII_STR("WXTRACE"), NULL) )
wxLog::EnableLogging(false);
else
wxLog::SetTimestamp("%Y-%m-%d %H:%M:%S.%l");
#endif
// Cast is needed under MSW where Catch also provides an overload taking
// wchar_t, but as it simply converts arguments to char internally anyhow,
// we can just as well always use the char version.
return Catch::Session().run(argc, static_cast<char**>(argv));
}
int TestApp::OnExit()
{
#if wxUSE_GUI
delete GetTopWindow();
#endif // wxUSE_GUI
return TestAppBase::OnExit();
}
| [
"mathieu.caroff@free.fr"
] | mathieu.caroff@free.fr |
a4008e33a74e46a9235efab216c3a316d1bbf1ee | 9c0ee473dd13cdf546f98638ad9288981531b368 | / newelisserver --username EmpireDaniel/Queue.h | dfe910403d716dd541787c5022d8f62eff063b10 | [] | no_license | empiredan/newelisserver | 288cd534d648be00878410eaa3ddfbbc1a2c6e74 | 42b7311d96f76139ac0976e7c59775fd6ee4b37e | refs/heads/master | 2016-09-10T04:26:54.540327 | 2010-05-06T12:35:06 | 2010-05-06T12:35:06 | 32,517,255 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,372 | h | #ifndef Queue_h
#define Queue_h
#include <deque>
#include <afxtempl.h>
#include <afxmt.h>
#include "Data.h"
using namespace std;
//目前主流编译器不支持分离编译
//也就是不支持模板声明写到h文件中,实现写到cpp文件中
//C++标准倒是规定有分离编译
//不过对于编译器来说实现比较困难所以大多数编译器不支持(包括vc全系列)
template<class DATA_TYPE>
class CDataQueue
{
public:
CDataQueue();
~CDataQueue();
public:
void enQueue(DATA_TYPE* data);
DATA_TYPE* deQueue();
public:
CList<DATA_TYPE*, DATA_TYPE*> dataQueue;
public:
CMutex dataMtx;
CEvent dataEvt;
};
template<class DATA_TYPE>
CDataQueue<DATA_TYPE>::CDataQueue():dataMtx(), dataEvt()
{
}
template<class DATA_TYPE>
CDataQueue<DATA_TYPE>::~CDataQueue()
{
POSITION p=dataQueue.GetHeadPosition();
while (p!=NULL)
{
delete dataQueue.GetNext(p);
}
}
template<class DATA_TYPE>
void CDataQueue<DATA_TYPE>::enQueue(DATA_TYPE* data)
{
CSingleLock l(&dataMtx);
if(l.Lock()) {
dataQueue.AddTail(data);
dataEvt.SetEvent();
}
l.Unlock();
}
template<class DATA_TYPE>
DATA_TYPE* CDataQueue<DATA_TYPE>::deQueue()
{
DATA_TYPE* d;
CSingleLock l(&dataMtx);
while(dataQueue.IsEmpty()) {
//AfxMessageBox(_T("MasterDataQueue empty, waitting!"));
::WaitForSingleObject(dataEvt.m_hObject, 3000);
}
if(l.Lock()) {
//DATA_TYPE* elem = dataQueue.GetHead();
d = dataQueue.RemoveHead();
}
l.Unlock();
return d;
}
/////////////////////////////////////////////////////////////////
template<class DATA_TYPE>
class MasterDataQueue:public CDataQueue<DATA_TYPE>
{
public:
MasterDataQueue();
~MasterDataQueue();
};
template<class DATA_TYPE>
MasterDataQueue<DATA_TYPE>::MasterDataQueue():CDataQueue<DATA_TYPE>()
{
}
template<class DATA_TYPE>
MasterDataQueue<DATA_TYPE>::~MasterDataQueue() {
}
/////////////////////////////////////////////////////////////////
template<class DATA_TYPE>
class FrontDataQueue:public CDataQueue<DATA_TYPE>
{
public:
FrontDataQueue();
~FrontDataQueue();
};
template<class DATA_TYPE>
FrontDataQueue<DATA_TYPE>::FrontDataQueue():CDataQueue<DATA_TYPE>()
{
}
template<class DATA_TYPE>
FrontDataQueue<DATA_TYPE>::~FrontDataQueue() {
}
#endif | [
"EmpireDaniel@c766ca94-0bef-11df-9441-b1846cd9856d"
] | EmpireDaniel@c766ca94-0bef-11df-9441-b1846cd9856d |
ee87476df328fcfc4b29c51b1ea1b7e7b5741d33 | 2d03501d5aa82af90527d05dbdbf7ce0ff96f99e | /2. Add Two Numbers/Solution.h | 798281c3841f2bb517f9a0fc0270d116c42157ae | [] | no_license | baitian0521/LeetCode | c1b2ba2f9fe4073dcda9a4ef9141e37668afa08c | d1fdea114d936ed0193f45c975effcf1068d062d | refs/heads/master | 2020-03-21T02:08:00.004911 | 2018-06-21T15:08:36 | 2018-06-21T15:08:36 | 137,981,810 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,479 | h |
#include <iostream>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode *b = NULL;
ListNode *back = NULL;
int value = 0;
int index = 0;
bool isFrist = false;
while (l1 != NULL && l2 != NULL) {
int sum = (l1->val + l2->val) + index;
value = sum % 10;
sum / 10 == 1 ? index = 1 : index = 0;
if (back == NULL) {
back = new ListNode(value);
b = back;
} else {
back->next = new ListNode(value);
back = back->next;
}
l1 = l1->next;
l2 = l2->next;
}
while (l1 != NULL) {
int sum = (l1->val + 0) + index;
value = sum % 10;
sum / 10 == 1 ? index = 1 : index = 0;
back->next = new ListNode(value);
back = back->next;
l1 = l1->next;
}
while (l2 != NULL) {
int sum = (l2->val + 0) + index;
value = sum % 10;
sum / 10 == 1 ? index = 1 : index = 0;
back->next = new ListNode(value);
back = back->next;
l2 = l2->next;
}
if (index != 0) {
back->next = new ListNode(index);
back = back->next;
}
return b;
}
}; | [
"white.bai@dianping.com"
] | white.bai@dianping.com |
16736fa1730136a82cca6faa7716c3eda150cfa4 | 77a37559730c9228c6ae9c530dc80b8488080c23 | /src/my_plagin/src/moveToDestiny.cpp | 429f00ae4e03714f9c5574d87022bd05a1bdf1a4 | [] | no_license | tdtce/quadrotor | f01e889ef1252ef5e28fc146521a057ead6fa62e | 64677c9c0c461f5bc7ef73b922d5cd912c2e6783 | refs/heads/master | 2020-03-10T17:06:53.133096 | 2018-05-19T16:42:21 | 2018-05-19T16:42:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,363 | cpp | #include <iostream>
#include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <geometry_msgs/Vector3.h>
#include <nav_msgs/Odometry.h>
#include <cmath>
#include <geometry_msgs/Quaternion.h>
#include "std_msgs/Bool.h"
// #include<pcl/point_cloud.h>
// #include<pcl_conversions/pcl_conversions.h>
// #include<sensor_msgs/PointCloud2.h>
// #include<pcl/io/pcd_io.h>
// #include <octomap/octomap.h>
// #include <octomap/OcTree.h>
// #include <octomap_msgs/conversions.h>
// #include <octomap_msgs/Octomap.h>
static void toEulerAngle(const geometry_msgs::Quaternion& q, double& roll, double& pitch, double& yaw)
{
// roll (x-axis rotation)
double sinr = +2.0 * (q.w * q.x + q.y * q.z);
double cosr = +1.0 - 2.0 * (q.x * q.x + q.y * q.y);
roll = atan2(sinr, cosr);
// pitch (y-axis rotation)
double sinp = +2.0 * (q.w * q.y - q.z * q.x);
if (fabs(sinp) >= 1)
pitch = copysign(M_PI / 2, sinp); // use 90 degrees if out of range
else
pitch = asin(sinp);
// yaw (z-axis rotation)
double siny = +2.0 * (q.w * q.z + q.x * q.y);
double cosy = +1.0 - 2.0 * (q.y * q.y + q.z * q.z);
yaw = atan2(siny, cosy);
}
class SubscribeAndPublish
{
public:
SubscribeAndPublish()
{
//Topic for publish
pub_ = n_.advertise<geometry_msgs::Twist>("/cmd_vel", 1);
pubFinish_ = n_.advertise<std_msgs::Bool>("/is_finish", 1);
//Topic for subscribe
subDestiny_ = n_.subscribe("/intermediate_state", 1, &SubscribeAndPublish::callbackDestiny, this);
sub_ = n_.subscribe("/ground_truth/state", 1, &SubscribeAndPublish::callback1, this);
}
void callback(const nav_msgs::Odometry& input)
{
geometry_msgs::Twist output;
std_msgs::Bool isFinish;
isFinish.data = false;
geometry_msgs::Vector3 locGoal;
geometry_msgs::Vector3 locPos;
geometry_msgs::Vector3 orient;
toEulerAngle(input.pose.pose.orientation, orient.x, orient.y, orient.z);
// determinate goal point in local system coordinate
locPos.x = cos(orient.z)*input.pose.pose.position.x + sin(orient.z)*input.pose.pose.position.y;
locPos.y = -sin(orient.z)*input.pose.pose.position.x + cos(orient.z)*input.pose.pose.position.y;
locGoal.x = cos(orient.z)*goal_.x + sin(orient.z)*goal_.y - locPos.x;
locGoal.y = -sin(orient.z)*goal_.x + cos(orient.z)*goal_.y - locPos.y;
locGoal.z = goal_.z - input.pose.pose.position.z;
// angular speed
double distanceForGoalxy = pow((pow(locGoal.x, 2) + pow(locGoal.y, 2)),0.5);
double dYaw = std::atan2(locGoal.y/distanceForGoalxy, locGoal.x/distanceForGoalxy);
if (std::abs(dYaw) < 0.03)
{
output.angular.z = 0;
// linear speed
if ((std::abs(locGoal.x) < deviation_) &&
(std::abs(locGoal.y) < deviation_) &&
(std::abs(locGoal.z) < deviation_))
{
output.linear.x = 0;
output.linear.y = 0;
output.linear.z = 0;
isFinish.data = true;
}
else
{
double maxDeviation = std::max(std::abs(locGoal.x), std::abs(locGoal.z));
output.linear.x = speed_*locGoal.x/maxDeviation;
output.linear.z = speed_*locGoal.z/maxDeviation;
}
}
else
{
output.linear.x = 0;
output.linear.y = 0;
output.linear.z = 0;
if (dYaw>0)
{
output.angular.z = speed_*2 ;
}
else
{
output.angular.z = -speed_*2 ;
}
}
double varible = sin(orient.z);
pub_.publish(output);
pubFinish_.publish(isFinish);
}
void callback1(const nav_msgs::Odometry& input)
{
geometry_msgs::Twist output;
std_msgs::Bool isFinish;
isFinish.data = false;
geometry_msgs::Vector3 locGoal;
geometry_msgs::Vector3 locPos;
geometry_msgs::Vector3 orient;
toEulerAngle(input.pose.pose.orientation, orient.x, orient.y, orient.z);
locPos.x = cos(orient.z)*input.pose.pose.position.x + sin(orient.z)*input.pose.pose.position.y;
locPos.y = -sin(orient.z)*input.pose.pose.position.x + cos(orient.z)*input.pose.pose.position.y;
locGoal.x = cos(orient.z)*goal_.x + sin(orient.z)*goal_.y - locPos.x;
locGoal.y = -sin(orient.z)*goal_.x + cos(orient.z)*goal_.y - locPos.y;
locGoal.z = goal_.z - input.pose.pose.position.z;
geometry_msgs::Vector3 dCoordinate;
// linear speed
if ((std::abs(locGoal.x) < deviation_) &&
(std::abs(locGoal.y) < deviation_) &&
(std::abs(locGoal.z) < deviation_))
{
output.linear.x = 0;
output.linear.y = 0;
output.linear.z = 0;
isFinish.data = true;
}
else
{
double maxDeviation = std::max(std::abs(locGoal.x), std::abs(locGoal.y));
maxDeviation = std::max(std::abs(maxDeviation), std::abs(locGoal.z));
output.linear.x = (locGoal.x / maxDeviation) * speed_;
output.linear.y = (locGoal.y / maxDeviation) * speed_;
output.linear.z = (locGoal.z / maxDeviation) * speed_;
}
// angular speed
double distanceForGoalxy =pow((pow(locGoal.x, 2) + pow(locGoal.y, 2)),0.5);
double dYaw = std::atan2(locGoal.y/distanceForGoalxy, locGoal.x/distanceForGoalxy);
if (std::abs(dYaw) < deviation_ / 5 )
{
output.angular.z = 0;
}
else
{
if (dYaw>0)
{
output.angular.z = speed_ ;
}
else
{
output.angular.z = -speed_ ;
}
}
pubFinish_.publish(isFinish);
pub_.publish(output);
}
void callbackDestiny(const geometry_msgs::Vector3& input)
{
goal_.x = input.x;
goal_.y = input.y;
goal_.z = input.z;
}
void setSpeed (double speed)
{
speed_ = speed;
}
void setDeviation (double deviation)
{
deviation_ = deviation;
}
private:
ros::NodeHandle n_;
ros::Publisher pub_;
ros::Publisher pubFinish_;
ros::Subscriber sub_;
ros::Subscriber subDestiny_;
geometry_msgs::Vector3 goal_;
double speed_ = 0.4;
double deviation_ = 0.2;
};//End of class SubscribeAndPublish
int main(int argc, char **argv)
{
//Initiate ROS
ros::init(argc, argv, "goToDestiny");
//Create an object of class SubscribeAndPublish that will take care of everything
SubscribeAndPublish SAPObject;
ros::spin();
return 0;
}
| [
"fantaa499@gmail.com"
] | fantaa499@gmail.com |
cb463626c6c5793474f226959a3803433740b96a | 34b02bdc74ffd35caf0ced89612e413e43ef9e70 | /project/QtTomato/src/appcfg.h | a857b0ff6f2f781e7a7b31b3f6b48f1db87a40ba | [] | no_license | Makmanfu/CppNote | 693f264e3984c6e2e953e395b836306197cc9632 | e1c76e036df4a9831618704e9ccc0ad22cd4b748 | refs/heads/master | 2020-03-26T01:11:51.613952 | 2018-08-10T06:52:21 | 2018-08-10T06:52:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,452 | h | //********************************************************************
//
// 配置文件管理工具
// @阿甘2016-05-12
//
//********************************************************************/
#ifndef APPCFG_H
#define APPCFG_H
#include "QPublic.h"
//Ini数据字段
struct IniDat
{
bool SupenShow; //悬浮窗显示
int SuspenPaint; //悬浮窗是否坑锯齿
bool SuspenExit; //是否退出到托盘
bool GoodGif; //显示彩蛋
bool Clock; //显示悬浮clock
float SuspenPtX, SuspenPtY; //悬浮窗默认位置
bool AxisStyle; //坐标轴风格
IniDat()
{
SupenShow = SuspenPaint = SuspenExit = GoodGif = 0;
SuspenPtX = SuspenPtY = 0.0;
Clock = AxisStyle = 1;
};
};
//配置文件管理
class Appcfg
{
private:
static Appcfg* _instance;
QString inifile; //ini文件
protected:
Appcfg(void);
public:
static Appcfg* Instance()
{
if (NULL == _instance)
_instance = new Appcfg();
return _instance;
};
virtual ~Appcfg();
bool CreateIni(QString _name);
void ReadDataIni(void);
void WriteDataIni(void);
void setSdat(IniDat& _Sdat);
public:
IniDat Sdat; //数据
};
#endif
| [
"xhamigua@163.com"
] | xhamigua@163.com |
3c1431d6100756d4feaa7fcf51701d447c3f24c3 | c92d3646b37b7866b07699444ce691abd7c34903 | /mediaLibTest/src/tests/mCachedFileReaderTest.cpp | cf2878d7d9903d9bb105b94de7792c71b442c3ca | [
"MIT"
] | permissive | rainerzufalldererste/mediaLib | a2ba5646aa0b7d226a82c0eddf439e09accca7c6 | 8b670c57079a941cc60567cc3ba8a5e7aee5e8e6 | refs/heads/master | 2023-07-01T18:57:36.748659 | 2023-06-13T23:14:22 | 2023-06-13T23:14:22 | 142,741,786 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,787 | cpp | #include "mTestLib.h"
#include "mFile.h"
#include "mCachedFileReader.h"
mTEST(mCachedFileReader, TestRead)
{
mTEST_ALLOCATOR_SETUP();
const size_t fileSize = 1024 * 12;
const size_t maxCacheSize = 1024;
const mString filename = "mCachedFileReaderTest.bin";
size_t *pData = nullptr;
mDEFER_CALL_2(mAllocator_FreePtr, pAllocator, &pData);
mTEST_ASSERT_SUCCESS(mAllocator_AllocateZero(pAllocator, &pData, fileSize));
for (size_t i = 0; i < fileSize; i++)
pData[i] = i;
mTEST_ASSERT_SUCCESS(mFile_WriteRaw(filename, pData, fileSize));
mDEFER(mFile_Delete(filename));
mPtr<mCachedFileReader> fileReader;
mDEFER_CALL(&fileReader, mCachedFileReader_Destroy);
mTEST_ASSERT_SUCCESS(mCachedFileReader_Create(&fileReader, pAllocator, filename, maxCacheSize));
size_t actualFileSize = 0;
mTEST_ASSERT_SUCCESS(mCachedFileReader_GetSize(fileReader, &actualFileSize));
mTEST_ASSERT_EQUAL(actualFileSize, fileSize * sizeof(size_t));
// Read from various places in the file.
for (size_t run = 0; run < 2; run++)
{
for (size_t i = 0; i < fileSize; i++)
{
size_t value;
mTEST_ASSERT_SUCCESS(mCachedFileReader_ReadAt(fileReader, i * sizeof(size_t), sizeof(size_t), (uint8_t *)&value));
mTEST_ASSERT_EQUAL(i, value);
const size_t size = fileReader->cacheSize / sizeof(size_t);
const size_t offset = fileReader->cachePosition / sizeof(size_t);
for (size_t index = 0; index < size; index++)
mTEST_ASSERT_EQUAL(index + offset, ((size_t *)fileReader->pCache)[index]);
}
}
for (size_t run = 0; run < 2; run++)
{
for (int64_t i = fileSize - 1; i >= 0; i--)
{
size_t value;
mTEST_ASSERT_SUCCESS(mCachedFileReader_ReadAt(fileReader, i * sizeof(size_t), sizeof(size_t), (uint8_t *)&value));
mTEST_ASSERT_EQUAL((size_t)i, value);
const size_t size = fileReader->cacheSize / sizeof(size_t);
const size_t offset = fileReader->cachePosition / sizeof(size_t);
for (size_t index = 0; index < size; index++)
mTEST_ASSERT_EQUAL(index + offset, ((size_t *)fileReader->pCache)[index]);
}
}
for (size_t run = 0; run < 2; run++)
{
for (size_t i = 0; i < fileSize; i++)
{
size_t *pValue = nullptr;
mTEST_ASSERT_SUCCESS(mCachedFileReader_PointerAt(fileReader, i * sizeof(size_t), sizeof(size_t), (uint8_t **)&pValue));
mTEST_ASSERT_EQUAL(i, *pValue);
const size_t size = fileReader->cacheSize / sizeof(size_t);
const size_t offset = fileReader->cachePosition / sizeof(size_t);
for (size_t index = 0; index < size; index++)
mTEST_ASSERT_EQUAL(index + offset, ((size_t *)fileReader->pCache)[index]);
}
}
for (size_t run = 0; run < 2; run++)
{
for (int64_t i = fileSize - 1; i >= 0; i--)
{
size_t *pValue = nullptr;
mTEST_ASSERT_SUCCESS(mCachedFileReader_PointerAt(fileReader, i * sizeof(size_t), sizeof(size_t), (uint8_t **)&pValue));
mTEST_ASSERT_EQUAL((size_t)i, *pValue);
const size_t size = fileReader->cacheSize / sizeof(size_t);
const size_t offset = fileReader->cachePosition / sizeof(size_t);
for (size_t index = 0; index < size; index++)
mTEST_ASSERT_EQUAL(index + offset, ((size_t *)fileReader->pCache)[index]);
}
}
uint8_t unusedValue;
uint8_t *pBuffer = nullptr;
mPtr<mCachedFileReader> nullFileReader = nullptr;
mDEFER_CALL(&nullFileReader, mSharedPointer_Destroy);
mTEST_ASSERT_EQUAL(mR_EndOfStream, mCachedFileReader_ReadAt(fileReader, fileSize * sizeof(size_t), 1, &unusedValue));
mTEST_ASSERT_EQUAL(mR_EndOfStream, mCachedFileReader_PointerAt(fileReader, fileSize * sizeof(size_t), 1, &pBuffer));
mTEST_ASSERT_EQUAL(mR_ArgumentNull, mCachedFileReader_ReadAt(fileReader, 0, 1, nullptr));
mTEST_ASSERT_EQUAL(mR_ArgumentNull, mCachedFileReader_ReadAt(nullFileReader, 0, 1, &unusedValue));
mTEST_ASSERT_EQUAL(mR_ArgumentNull, mCachedFileReader_PointerAt(fileReader, 0, 1, nullptr));
mTEST_ASSERT_EQUAL(mR_ArgumentNull, mCachedFileReader_PointerAt(nullFileReader, 0, 1, &pBuffer));
mTEST_ASSERT_EQUAL(mR_ArgumentOutOfBounds, mCachedFileReader_PointerAt(fileReader, 0, maxCacheSize + 1, &pBuffer));
mTEST_ASSERT_SUCCESS(mMemset(pData, fileSize, 0));
mTEST_ASSERT_SUCCESS(mCachedFileReader_ReadAt(fileReader, 0, sizeof(size_t) * fileSize, (uint8_t *)pData));
for (size_t i = 0; i < fileSize; i++)
mTEST_ASSERT_EQUAL(i, pData[i]);
mTEST_ASSERT_SUCCESS(mMemset(pData, fileSize, 0));
mTEST_ASSERT_SUCCESS(mCachedFileReader_ReadAt(fileReader, sizeof(size_t) * maxCacheSize, sizeof(size_t) * (fileSize - maxCacheSize), (uint8_t *)(pData + maxCacheSize)));
for (size_t i = maxCacheSize; i < fileSize; i++)
mTEST_ASSERT_EQUAL(i, pData[i]);
mTEST_ALLOCATOR_ZERO_CHECK();
}
| [
"c.stiller@live.de"
] | c.stiller@live.de |
672cf776cc866a826735c79a7f319924852b6a97 | aaad707ef9845b3018d2e8c79b5bff1c8120677e | /include/mainwindow.h | 9c97815ebaee1b3302e107c22bde725529078c24 | [] | no_license | evgeny-bunya/japanese-crossword | 184bf5816081c7ad56025f3761acb034fce23a56 | 4bbcd55a17eb652fb2f523bae9d9e86a411d99c1 | refs/heads/master | 2022-04-25T15:07:43.836682 | 2020-05-11T20:29:57 | 2020-05-11T20:29:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 448 | h | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "crossword_data.h"
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
void paintEvent(QPaintEvent *event);
void draw(QRect &rect);
Ui::MainWindow *ui;
CrosswordData crossword;
};
#endif // MAINWINDOW_H
| [
"bunya.evgeniy@gmail.com"
] | bunya.evgeniy@gmail.com |
6ddc93669d682af63e45b950700792ac959d2134 | 855edfadb4a79658f21f34fb040892a7b5b72b57 | /examples/cholmod/sym/csymshf.cc | 68e6fd45939a525c2d3a01e2ea1bdb8312328aab | [
"BSD-3-Clause"
] | permissive | stephenhky/arpackpp | 33b8dff090410c56a3ed363fb3a0746a8c8c5562 | 68d7825f3a6ae1dd26ba34c00151d780514848ab | refs/heads/master | 2022-07-17T22:33:35.637798 | 2020-05-18T15:45:31 | 2020-05-18T15:45:31 | 264,984,352 | 1 | 0 | NOASSERTION | 2020-05-18T15:38:55 | 2020-05-18T15:38:54 | null | UTF-8 | C++ | false | false | 2,509 | cc | /*
ARPACK++ v1.2 2/20/2000
c++ interface to ARPACK code.
MODULE CSymShf.cc.
Example program that illustrates how to solve a real symmetric
standard eigenvalue problem in shift and invert mode using the
ARluSymStdEig class.
1) Problem description:
In this example we try to solve A*x = x*lambda in shift and
invert mode, where A is derived from the central difference
discretization of the one-dimensional Laplacian on [0, 1]
with zero Dirichlet boundary conditions.
2) Data structure used to represent matrix A:
{nnz, irow, pcol, A}: lower triangular part of matrix A
stored in CSC format.
3) Library called by this example:
The UMFPACK package is called by ARluSymStdEig to solve
some linear systems involving (A-sigma*I). This is needed to
implement the shift and invert strategy.
4) Included header files:
File Contents
----------- --------------------------------------------
lsmatrxa.h SymmetricMatrixB, a function that generates
matrix A in CSC format.
arcsmat.h The ARumSymMatrix class definition.
arcssym.h The ARluSymStdEig class definition.
lsymsol.h The Solution function.
5) ARPACK Authors:
Richard Lehoucq
Kristyn Maschhoff
Danny Sorensen
Chao Yang
Dept. of Computational & Applied Mathematics
Rice University
Houston, Texas
*/
#include "lsmatrxb.h"
#include "arcsmat.h"
#include "arcssym.h"
#include "lsymsol.h"
int main()
{
// Defining variables;
int n; // Dimension of the problem.
int nnz; // Number of nonzero elements in A.
int* irow; // pointer to an array that stores the row
// indices of the nonzeros in A.
int* pcol; // pointer to an array of pointers to the
// beginning of each column of A in vector A.
double* A; // pointer to an array that stores the
// nonzero elements of A.
// Creating a 100x100 matrix.
n = 100;
SymmetricMatrixB(n, nnz, A, irow, pcol);
ARchSymMatrix<double> matrix(n, nnz, A, irow, pcol);
// Defining what we need: the four eigenvectors of A nearest to 1.0.
ARluSymStdEig<double> dprob(4L, matrix, 1.0);
// Finding eigenvalues and eigenvectors.
dprob.FindEigenvectors();
// Printing solution.
Solution(matrix, dprob);
} // main
| [
"reuter@mit.edu"
] | reuter@mit.edu |
f66c07a41f334ca624cda0bb4a47572c2f8b4574 | 2912c183f360d6982c2a6dee4aa477f9ada22b61 | /Internal/Net/PacketHeader.h | fcaf8b60010ad84cc74947e5872ee23186ef192b | [] | no_license | Jettford/DarkitectPublic | 26171ccbb13d5f77ce804525acafeee778133f38 | f2c7c5da109516ddd0dba0ca2d7d395c7ac5f383 | refs/heads/main | 2023-03-19T13:20:46.337912 | 2021-03-17T23:56:04 | 2021-03-17T23:56:04 | 348,883,854 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 195 | h | #pragma once
#include <cstdint>
#pragma pack(push, 1)
struct PacketHeader {
uint8_t RakPacketID;
uint16_t RemoteConnection;
uint32_t PacketID;
private:
uint8_t Padding;
};
#pragma pack(pop) | [
"17jbradford@tqacademy.co.uk"
] | 17jbradford@tqacademy.co.uk |
1acb99de9d5e6b84579c0b8a2d2b1dd341bf84cd | 29b9751d7bed351ecfbfc2f1e2bbfd68abf621d1 | /Mini-test/test.cpp | 8e502333d7f753ea2dd684ac7c91bc61f7c23b77 | [] | no_license | KeltorHD/lr_visual_programming | bd4008fb62cbe963f49a11aa47ab6bdd31439eff | a8c22c9830cf6cbcf2281a92829bdf3eeec93764 | refs/heads/main | 2023-04-09T03:47:26.019802 | 2021-04-04T13:41:42 | 2021-04-04T13:41:42 | 348,686,964 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,869 | cpp | #include "test.h"
#include <QRandomGenerator>
#include <algorithm>
void Test::init()
{
QFile file(":/questions.txt");
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
throw "not open file";
QTextStream file_stream(&file);
size_t count{file.readLine().toULongLong()};
for (size_t i = 0; i < count; i++)
{
int type{file_stream.readLine().toInt()};
qDebug() << type;
Question_base* base{};
switch (type)
{
case int(test_type::one_of_four):
base = new One_of_four;
break;
case int(test_type::some_of_four):
base = new Some_of_four;
break;
case int(test_type::write_answer):
base = new Write_answer;
break;
case int(test_type::installation_of_correspondence):
base = new Installation_of_correspondence;
break;
}
if (base)
{
base->input(file_stream);
base->set_type(test_type(type));
this->questions[i].first = base;
}
}
}
void Test::reset()
{
this->current_index = 0;
for (size_t i = 0; i < 10; i++)
{
this->answers[i] = false;
this->questions[i].second = false;
}
std::random_shuffle(this->questions.begin(), this->questions.end());
}
size_t Test::get_counter_answers() const
{
size_t counter{};
for (size_t i = 0; i < this->answers.size(); i++)
{
if (this->answers[i])
counter++;
}
return counter;
}
size_t Test::get_counter_correct_answers() const
{
size_t counter{};
for (size_t i = 0; i < this->questions.size(); i++)
{
if (this->questions[i].second)
counter++;
}
return counter;
}
const test_type &Test::get_current_type() const
{
return this->questions[this->current_index].first->get_type();
}
std::array<QString, 4> Test::get_answers_1() const
{
One_of_four* q {dynamic_cast<One_of_four*>(this->questions[this->current_index].first)};
return q->get_answers();
}
std::array<QString, 4> Test::get_answers_2() const
{
Some_of_four* q {dynamic_cast<Some_of_four*>(this->questions[this->current_index].first)};
return q->get_answers();
}
std::pair<std::array<QString, 4>, std::array<QString, 4> > Test::get_answers_4() const
{
Installation_of_correspondence* q {dynamic_cast<Installation_of_correspondence*>(this->questions[this->current_index].first)};
return q->get_answers();
}
void Test::check_answer1(size_t answer)
{
One_of_four* q {dynamic_cast<One_of_four*>(this->questions[this->current_index].first)};
if (q->get_correct_answer() == answer)
{
this->questions[this->current_index].second = true;
}
q->set_current_answer(answer);
this->answers[this->current_index] = true;
}
void Test::check_answer2(std::vector<int> answers)
{
Some_of_four* q {dynamic_cast<Some_of_four*>(this->questions[this->current_index].first)};
try
{
for (size_t i = 0; i < std::max(answers.size(), q->get_correct_answer().size()); i++)
{
if (answers.at(i) != q->get_correct_answer().at(i))
throw std::logic_error("");
}
this->questions[this->current_index].second = true;
}
catch (std::exception& e)
{
}
q->set_current_answer(answers);
this->answers[this->current_index] = true;
}
void Test::check_answer3(QString answer)
{
Write_answer* q {dynamic_cast<Write_answer*>(this->questions[this->current_index].first)};
if (q->get_correct_answer() == answer.toLower())
this->questions[this->current_index].second = true;
q->set_current_answer(answer);
this->answers[this->current_index] = true;
}
void Test::check_answer4(std::array<QString, 4> answer)
{
Installation_of_correspondence* q {dynamic_cast<Installation_of_correspondence*>(this->questions[this->current_index].first)};
try
{
for (size_t i = 0; i < 4; i++)
{
if (q->get_correct_answer()[i] != answer[i])
throw std::logic_error("");
}
this->questions[this->current_index].second = true;
}
catch (std::exception& e)
{
}
q->set_current_answer(answer);
this->answers[this->current_index] = true;
}
size_t Test::get_closed_answer1() const
{
One_of_four* q {dynamic_cast<One_of_four*>(this->questions[this->current_index].first)};
return q->get_current_answer();
}
std::vector<int> Test::get_closed_answer2() const
{
Some_of_four* q {dynamic_cast<Some_of_four*>(this->questions[this->current_index].first)};
return q->get_current_answer();
}
QString Test::get_closed_answer3() const
{
Write_answer* q {dynamic_cast<Write_answer*>(this->questions[this->current_index].first)};
return q->get_current_answer();
}
std::array<QString, 4> Test::get_closed_answer4() const
{
Installation_of_correspondence* q {dynamic_cast<Installation_of_correspondence*>(this->questions[this->current_index].first)};
return q->get_current_answer();
}
size_t Test::get_correct_answer1() const
{
One_of_four* q {dynamic_cast<One_of_four*>(this->questions[this->current_index].first)};
return q->get_correct_answer();
}
std::vector<int> Test::get_correct_answer2() const
{
Some_of_four* q {dynamic_cast<Some_of_four*>(this->questions[this->current_index].first)};
return q->get_correct_answer();
}
QString Test::get_correct_answer3() const
{
Write_answer* q {dynamic_cast<Write_answer*>(this->questions[this->current_index].first)};
return q->get_correct_answer();
}
std::array<QString, 4> Test::get_correct_answer4() const
{
Installation_of_correspondence* q {dynamic_cast<Installation_of_correspondence*>(this->questions[this->current_index].first)};
return q->get_correct_answer();
}
| [
"keltorplaylife@gmail.com"
] | keltorplaylife@gmail.com |
f202a923a8feaac525b313df8a1b45cab05c8ff8 | 1a85fdb9dcc03b9f7796477df350834183a0e8c3 | /src/qt/openuridialog.cpp | d6032ad919f14c1f75c208bb0eb70cea39c3cc59 | [
"MIT"
] | permissive | Jetro-Costa/martexcoin | 9f8208336bd7ac7f5c4bc820f79229f92d2c6676 | 5b62b802b51b8ecd624f5ff96c6b92b7da92ef90 | refs/heads/master | 2023-02-22T04:22:03.831213 | 2020-09-28T15:35:58 | 2020-09-28T15:35:58 | 279,694,852 | 0 | 0 | MIT | 2021-01-27T16:18:38 | 2020-07-14T21:17:22 | C++ | UTF-8 | C++ | false | false | 1,284 | cpp | // Copyright (c) 2011-2014 The Bitcoin Core developers
// Copyright (c) 2014-2019 The MarteX Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "openuridialog.h"
#include "ui_openuridialog.h"
#include "guiutil.h"
#include "walletmodel.h"
#include <QUrl>
OpenURIDialog::OpenURIDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::OpenURIDialog)
{
ui->setupUi(this);
#if QT_VERSION >= 0x040700
ui->uriEdit->setPlaceholderText("martex:");
#endif
}
OpenURIDialog::~OpenURIDialog()
{
delete ui;
}
QString OpenURIDialog::getURI()
{
return ui->uriEdit->text();
}
void OpenURIDialog::accept()
{
SendCoinsRecipient rcp;
if(GUIUtil::parseBitcoinURI(getURI(), &rcp))
{
/* Only accept value URIs */
QDialog::accept();
} else {
ui->uriEdit->setValid(false);
}
}
void OpenURIDialog::on_selectFileButton_clicked()
{
QString filename = GUIUtil::getOpenFileName(this, tr("Select payment request file to open"), "", "", NULL);
if(filename.isEmpty())
return;
QUrl fileUri = QUrl::fromLocalFile(filename);
ui->uriEdit->setText("martex:?r=" + QUrl::toPercentEncoding(fileUri.toString()));
}
| [
"marcianovc@gmail.com"
] | marcianovc@gmail.com |
5cfca8ba0535e14a9de96bca4b035dbd90e21a76 | 1a9bc42f503382877cceb540784726bcfae0d600 | /readjson.cpp | 55cf429702eac8ba75623c69a6ae925db71e9f1f | [] | no_license | Jantero93/Qt_Harkka | 25727761087bd52dcbef3930705acba8154b581c | 461ac316157550a4ae0b962cc5d1b736c7a00b5a | refs/heads/master | 2023-08-01T15:27:35.319822 | 2021-04-19T05:22:34 | 2021-04-19T05:22:34 | 352,635,649 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,764 | cpp | #include "readjson.h"
#include <QDebug>
#include <QFile>
#include <QIODevice>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QVector>
#include <QException>
QVector<Car> get_cars_from_json_file() {
//const QString FILE_NAME("CARS_data.json");
//QFile file;
//file.setFileName(FILE_NAME);
QFile file(":CARS_data.json");
file.open(QIODevice::ReadOnly | QIODevice::Text);
QByteArray json_text = file.readAll();
file.close();
QJsonParseError parseError;
QJsonDocument document = QJsonDocument::fromJson(json_text, &parseError);
// check parse errors
if (parseError.error != QJsonParseError::NoError){
qDebug() << "Parse error on fetching data from json file, error msg: " << parseError.errorString();
}
// array from root object
QJsonArray car_json_array = document.array();
QVector<Car> car_list;
foreach (const QJsonValue& value, car_json_array) {
car_list.append(parse_car_from_jsonArray(value));
}
/*
foreach(const Car car, car_list){
std::cout << car.m_id << std::endl;
std::cout << car.m_make.toStdString() << std::endl;
std::cout << car.m_model.toStdString() << std::endl;
std::cout << car.m_year << std::endl;
std::cout << std::endl;
}
*/
return car_list;
}
Car parse_car_from_jsonArray(const QJsonValue value)
{
int year = value.toObject().value("year").toInt();
int horsepower = value.toObject().value("horsepower").toInt();
int price = value.toObject().value("price").toInt();
QString make(value.toObject().value("make").toString());
QString model(value.toObject().value("model").toString());
return Car(year, horsepower, make, model, price);
}
| [
"janzku1993@hotmail.com"
] | janzku1993@hotmail.com |
46d6312d438f547713bff5dfc88a108bb7bafbdc | d1c61a634879157c053c48bf3a1a95355a551971 | /teevid-client-native/include/teevid_sdk/SourceType.h | 95c3bee8a906ecc8711527d7b8b76af29c5add22 | [] | no_license | TeeVid/sdk_samples | 7c925dc6a5515b5fd196d8c477719414acd1e507 | 96b499fbb86de61d5d6daf712e4082a85ec4cf36 | refs/heads/master | 2022-09-27T02:50:44.101730 | 2022-04-12T08:48:51 | 2022-04-12T08:48:51 | 165,918,527 | 3 | 6 | null | 2021-09-27T06:43:28 | 2019-01-15T20:27:11 | Objective-C | UTF-8 | C++ | false | false | 321 | h | //
// Created by root on 20.05.20.
//
#ifndef _SOURCETYPE_H_
#define _SOURCETYPE_H_
namespace teevid_sdk
{
typedef enum {
eAudio = 0,
eVideo = 1
} SourceType;
typedef struct{
SourceType type;
int deviceId;
std::string name;
}SourceInfo;
}
#endif //_SOURCETYPE_H_
| [
"noreply@github.com"
] | noreply@github.com |
35cf13172b7091de44bd637384c4a33c6d3bd025 | 21c5124f67a864f09aaf473cff45be5b521b9907 | /Simulate3DFibres/Code.cxx | 4f633c295f5be07d513f4230fe4a54e413e86838 | [] | no_license | chivertj/fibsim | 739c441027cb3172f8adb7678fd745959b63aabb | e389acb3b978aac49ea7421160e05b8d853baf3b | refs/heads/master | 2021-07-13T03:29:02.968970 | 2018-04-17T14:26:33 | 2018-04-17T14:26:33 | 96,053,383 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,795 | cxx | #include "itkImageFileReader.h"
#include "itkImageFileWriter.h"
#include "itkImage.h"
#include "itkMersenneTwisterRandomVariateGenerator.h"
#include "../itkCentralProcessing/itkhelpers.hxx"
#include "../itkCentralProcessing/vectorfileread.hxx"
#include "../itkCentralProcessing/itkprocessing.hxx"
#include "../itkCentralProcessing/itkfibresimulator.hxx"
#include "../itkCentralProcessing/vectorfileread.hxx"
int main(int argc, char *argv[] ) {
typedef itk::ImageFileReader< MidImageType > ImageReaderType;
if (argc < 19) {
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << "\n\t[1] dim0\n\t[2] dim1\n\t[3] dim2\n\t[4] spacing0\n\t[5] spacing1\n\t[6] spacing2\n\t[7] size0\n\t[8] size1\n\t[9] size2\n\t[10] upsample rate(>1)\n\t[11] interplane downsample rate(>1)\n\t[12] #fibres\n\t[13] max delta theta\n\t[14] max delta phi\n\t[15] theta quantization\n\t[16] phi quantization\n\t[17] fibrelengths\n\t[18] fibre thickness (radius in upsample pixels)\n\t[19] background pixel mean value\n\t[20] fibre pixel mean value\n\t[21] noise standard deviation \n\t[22]op filename" << std::endl;
return EXIT_FAILURE;
}
//createimage from itkhelpers (at rel high res)
//add fibres
//add noise
//downsample
//export
//X,Y,Z
int dims[3]={atoi(argv[1]), atoi(argv[2]), atoi(argv[3])};
float spacing[3]={atof(argv[4]), atof(argv[5]), atof(argv[6])}; //inclusive of size
float size[3]={atof(argv[7]), atof(argv[8]), atof(argv[9])};
float upsamplerate=atof(argv[10]),interplanedownsamplerate=atof(argv[11]);
int Nfibres=atoi(argv[12]);
int maxdeltaangles[2]={atoi(argv[13]),atoi(argv[14])};
int Nquantizations[2]={atoi(argv[15]),atoi(argv[16])};
bool usefixedlength=true;
float fibrelengths=atof(argv[17]);
if (fibrelengths<varepsilon)
usefixedlength=false;
int fibrethickness=atoi(argv[18]);
unsigned short backgroundpixelvalue=atoi(argv[19]);
unsigned short fibrepixelvalue=atoi(argv[20]);
double noiseparamval=pow(atof(argv[21]),2);
string opfilename(argv[22]);
MidImageType::RegionType::SizeType highres;
MidImageType::SpacingType highres_spacing,lowres_spacing;
for (int i=0;i<2;i++) {
lowres_spacing[i]=spacing[i];
highres[i]=int(dims[i]*upsamplerate);
highres_spacing[i]=spacing[i]/upsamplerate;
}
lowres_spacing[2]=spacing[2];
highres_spacing[2]=spacing[2]/interplanedownsamplerate;
highres[2]=int(dims[2]*interplanedownsamplerate);
MidImageType::Pointer highresimage=MidImageType::New();
std::cout <<"Creating first image..."<<highres[0]<<","<<highres[1]<<","<<highres[2]<<","<<std::endl;
CreateImage<MidImageType>(highres,highres_spacing,highresimage);
std::cout <<"Created first image..."<<std::endl;
///////////////////////////////////////////////////
//setting up random for both points and noise
//////////////////////////////////////////////////
typedef itk::Statistics::MersenneTwisterRandomVariateGenerator GeneratorType;
GeneratorType::Pointer generator = GeneratorType::New();
generator->Initialize();
///////////////////////////////////////////////////
//setting background values
//////////////////////////////////////////////////
SetBackgroundValue(highresimage,backgroundpixelvalue);
///////////////////////////////////////////////////
//adding fibres
//////////////////////////////////////////////////
FRC::VOL_T fibres=AddFibres(highresimage,highres,highres_spacing,fibrepixelvalue,Nfibres,fibrelengths,maxdeltaangles,Nquantizations);
FRC::vectorfilewrite("fibrepoints.csv",fibres);
///////////////////////////////////////////////////
int RETURNVAL=0;
#if(1)
// MidImageType::Pointer linevol=SubSampler(highresimage,highres_spacing,upsamplerate,interplanedownsamplerate);
MidImageType::Pointer linevol=DownSampleVolume(highresimage,size,highres_spacing,upsamplerate,interplanedownsamplerate);
RETURNVAL=ExportVolume(linevol,"linevolume.mhd");
if (RETURNVAL!=0)
return RETURNVAL;
#endif
///////////////////////////////////////////////////
//dilating fibres
//////////////////////////////////////////////////
highresimage=DilateFibres(highresimage,fibrethickness,fibrepixelvalue);
///////////////////////////////////////////////////
//setting noise values
//////////////////////////////////////////////////
SetNoise(highresimage,noiseparamval);
///////////////////////////////////////////////////
//downsampling
//////////////////////////////////////////////////
MidImageType::Pointer lowresimage=DownSampleVolume(highresimage,size,highres_spacing,upsamplerate,interplanedownsamplerate);
///////////////////////////////////////////////////
//saving volume
//////////////////////////////////////////////////
RETURNVAL=ExportVolume(lowresimage,opfilename);
return RETURNVAL;
}
| [
"john.chiverton@port.ac.uk"
] | john.chiverton@port.ac.uk |
1e5bd8c94daea05c67c6101caf7bdbc26ca7f4e7 | dc7601d6e0b27d680ddfe409ef6c0aed7a8e8547 | /include/hexastore/query_iterator.h | 98bcded72b29462c4b695dc6ba73c53c9c814ab5 | [
"MIT"
] | permissive | colinsongf/hexastore-2 | 775bf03250df350e185f870fc9d7b144647140a9 | a8449ac0eb66d95df23ede438ed2ed66fc0b97a2 | refs/heads/master | 2020-12-23T15:30:42.170547 | 2016-10-30T04:39:30 | 2016-10-30T04:39:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,234 | h | #ifndef _HEXASTORE_QUERY_ITERATOR_H_
#define _HEXASTORE_QUERY_ITERATOR_H_
#include <hexastore/internals.h>
#include <hexastore/hexastore.h>
#include <hexastore/subquery_iterator.h>
// An iterator which operates on a hexastore and increments according to a list of Functor objects.
//
// This class maintains a chain of subQueryIterator objects each of which contributes two elements
// to the returned QueryChain object. Each subQueryIterator in the chain has its own Functor which controls
// how it is incremented.
//
// When the iterator is incremented (with calls to next()) this will increment the lowest subQueryIterator
// first. Then, the iterator will check to see if the functors along the chain return true. If not,
// it is incremented again. This continues until a valid chain is found, which is what is returned with
// through calls to next(). If a SubQueryIterator reaches the end of its available data, this will
// propagate upwards in the chain before the state is tested using the Functors.
//
// You may wonder why I did not use the C++ idiom for iterators: (begin(), end()). I generally prefer to
// define my iterators using the begin() -> end() style, but in this case that would have made the design
// more difficult. It requires that I define a state representing the end() iterator which can be tested
// for equality so that the client can know when to stop iterating. In this class, that is somewhat difficult
// to define due to the nature of the structure, so I chose more of a Java-style iterator interface.
template <class Functor, class ...Args>
class QueryIterator
{
public:
// Construct a QueryIterator operating on a hexastore, parameterized with a variadic
// list of functors. The number of functors specified will dictate the length of the chain.
// For example QueryIterator<AcceptAll, AcceptAll, AcceptAll> will return all the chains
// of length 3 within the hexastore.
QueryIterator(const Hexastore& hexastore, Functor& functor, Args... args);
// Return the next element in the iteration and increments the iterator.
QueryChain next();
// If true, a value can be obtained from the iterator.
bool hasNext();
private:
// Check if the current state of the iterator satisfies all of its functors.
bool incrementNecessary();
// Increment the iterator to the next valid state. If there's no valid state the
// iterator will end up in a state where hasNext() evaluates to false.
void increment();
const Hexastore& hexastore;
// Iterates over the root nodes in the hexastore and provides the first entry in
// the returned QueryChains.
RootNode::const_iterator rootIterator;
// A recursive structure in which each element generates the next two elements in
// the returned QueryChains.
SubQueryIterator<Functor, Args...> subQueryIterator;
};
template <class ...Functors>
std::vector<QueryChain> getQueryResults(const Hexastore& hexastore, Functors... functors)
{
std::vector<QueryChain> toReturn;
QueryIterator<Functors...> queryIterator(hexastore, functors...);
while (queryIterator.hasNext())
{
toReturn.push_back(queryIterator.next());
}
return toReturn;
}
// Implementation
#include <hexastore/query_iterator.hpp>
#endif
| [
"sebastian@bobsweep.com"
] | sebastian@bobsweep.com |
e78170f011c2429d11d4cfd2bfbd80f349ae82c5 | 1abd8852158451ffe4dbe0d885e2be0ed1dd50d8 | /exp/logic_cpp/alice_likes_bob.cpp | 30f35dca35888f8455b58ba84691be25c171d9cb | [
"Unlicense"
] | permissive | akalenuk/wordsandbuttons | f7c1479ce08fc9f01d1043ed54b2dbd330003e79 | ef0c89ec06452a0b1913d849039b399708eae957 | refs/heads/master | 2023-08-30T04:07:14.672481 | 2023-08-24T07:18:04 | 2023-08-24T07:18:04 | 110,279,805 | 440 | 25 | Unlicense | 2020-05-22T15:58:51 | 2017-11-10T18:30:49 | HTML | UTF-8 | C++ | false | false | 562 | cpp | // people
class Alice{};
class Bob{};
class George{};
class Steven{};
// languages
class Cpp{};
class Prolog{};
class Assembly{};
// facts
void kind(Bob);
void kind(George);
void kind(Steven);
void intelligent(Bob);
void intelligent(Steven);
void writes(Bob, Cpp);
void writes(Bob, Assembly);
void writes(George, Cpp);
void writes(Steven, Prolog);
// rule
template <typename Person> void likes(Alice, Person person)
{
kind(person);
intelligent(person);
writes(person, Cpp());
}
// check the rule for Bob
int main()
{
likes(Alice(), Bob());
}
| [
"akalenuk@gmail.com"
] | akalenuk@gmail.com |
d5284453f2d7ed8f5468f1912b7643a2e7555c49 | 4a75db23165e35b5e64ee45223f80b37e6b42a86 | /TDT4102 - Procedural and Object-Oriented Programming/Oving3/std_lib_facilities_mac/main.cpp | eb38d7ba37fe1f2c1bbaee8937f4e20366328a98 | [] | no_license | andersfagerli/NTNU | 621445132569915d4646d9be2a7ef6631eb1d9a1 | 84fcd79f86d5fce0b7d444e941961901dec6ea37 | refs/heads/master | 2022-01-19T03:28:53.062445 | 2021-09-02T07:46:05 | 2021-09-02T07:46:05 | 166,543,290 | 2 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 584 | cpp | #include "std_lib_facilities.h"
#include "cannonball.hpp"
void testDeviation(double compareOperand, double toOperand, double maxError, std::string name);
int main() {
srand(int(time(nullptr)));
//playTargetPractice();
return 0;
}
void testDeviation(double compareOperand, double toOperand, double maxError, std::string name) {
if (abs(compareOperand-toOperand) > maxError) {
std::cout << name << " and " << toOperand << " are not equal\n";
}
else {
std::cout << name << " and " << toOperand << " are equal\n";
}
}
| [
"anderstf@stud.ntnu.no"
] | anderstf@stud.ntnu.no |
fb9bb7f71a8e08aa0888d52e9c12c6552a9b2dcd | 9263ff5e0557349132d9ecd9f67d4df5661426cb | /EC_CONB.cpp | a2eef1450bbbed2ff0de4bb076498e81b1b9dc7e | [] | no_license | sidfour/spoj-solutions | 5ddf8af2a05622c67c3ffc85a32054e72ef47eca | afbbba0943d2fcc2c23f71a46c93abee00bb32f3 | refs/heads/master | 2020-03-19T03:35:52.148361 | 2018-06-01T16:57:02 | 2018-06-01T16:57:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 654 | cpp | #include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define ll long long
#define ull unsigned long long
#define endl '\n'
#define size 100000+1
#define loop(i,n) for(ll i=0;i<n;i++)
#define loop1(i,n) for(ll i=1;i<=n;i++)
using namespace std;
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t,n,ans,p;
int a[64];
cin>>t;
while(t--){
cin>>n;
if(n&1)cout<<n<<endl;
else{
ans=0;
p=0;
while(n>0){
if(n&1)
a[p++]=1;
else
a[p++]=0;
n/=2;
}
n=1;
for(int i=p-1;i>=0;i--){
if(a[i]==1)
ans+=n;
n*=2;
}
cout<<ans<<endl;
}
}
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
8baac24dab9e02bb3b85f58caaa91ffa7a22d8b0 | 8c114792636e9336c70fcaf4abc83eb25679d894 | /src/core-master/cpp/fp_NIST256.h | 96fced818bd709c7f4c1da2137e17ba47af37f0c | [
"BSD-3-Clause",
"AGPL-3.0-only"
] | permissive | cri-lab-hbku/auth-ais | c7cfeb1dee74c6947a9cc8530a01fb59994c94c5 | 9283c65fbe961ba604aab0f3cb35ddea99277c34 | refs/heads/master | 2023-03-23T00:22:29.430698 | 2021-03-12T18:53:27 | 2021-03-12T18:53:27 | 250,838,562 | 0 | 0 | BSD-3-Clause | 2021-03-12T18:53:28 | 2020-03-28T16:10:17 | C++ | UTF-8 | C++ | false | false | 8,873 | h | /*
Copyright (C) 2019 MIRACL UK Ltd.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
https://www.gnu.org/licenses/agpl-3.0.en.html
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
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.
You can be released from the requirements of the license by purchasing
a commercial license. Buying such a license is mandatory as soon as you
develop commercial activities involving the MIRACL Core Crypto SDK
without disclosing the source code of your own applications, or shipping
the MIRACL Core Crypto SDK with a closed source product.
*/
#ifndef FP_NIST256_H
#define FP_NIST256_H
#include "big_B256_56.h"
#include "config_field_NIST256.h"
using namespace core;
#define MODBITS_NIST256 MBITS_NIST256
#define TBITS_NIST256 (MBITS_NIST256%BASEBITS_B256_56) /**< Number of active bits in top word */
#define TMASK_NIST256 (((chunk)1<<TBITS_NIST256)-1) /**< Mask for active bits in top word */
#define FEXCESS_NIST256 (((sign32)1<<MAXXES_NIST256)-1) /**< 2^(BASEBITS*NLEN-MODBITS) - normalised BIG can be multiplied by less than this before reduction */
#define OMASK_NIST256 (-((chunk)(1)<<TBITS_NIST256)) /**< for masking out overflow bits */
namespace NIST256 {
/**
@brief FP Structure - quadratic extension field
*/
typedef struct
{
B256_56::BIG g; /**< Big representation of field element */
sign32 XES; /**< Excess */
} FP;
/* Field Params - see rom.c */
extern const B256_56::BIG Modulus; /**< Actual Modulus set in rom_field*.c */
extern const B256_56::BIG ROI; /**< Root of Unity set in rom_field*.c */
extern const B256_56::BIG R2modp; /**< Montgomery constant */
extern const chunk MConst; /**< Constant associated with Modulus - for Montgomery = 1/p mod 2^BASEBITS */
//extern const int BTset; /**< Set Bit in Generalised Mersenne */
extern const B256_56::BIG Fra; /**< real part of Pairing-friendly curve Frobenius Constant */
extern const B256_56::BIG Frb; /**< imaginary part of Pairing-friendly curve Frobenius Constant */
//#define FUSED_MODMUL
//#define DEBUG_REDUCE
/* FP prototypes */
/** @brief Create FP from integer
*
@param x FP to be initialised
@param a integer
*/
extern void FP_from_int(FP *x,int a);
/** @brief Tests for FP equal to zero mod Modulus
*
@param x FP number to be tested
@return 1 if zero, else returns 0
*/
extern int FP_iszilch(FP *x);
/** @brief Tests for FP equal to one mod Modulus
*
@param x FP number to be tested
@return 1 if one, else returns 0
*/
extern int FP_isunity(FP *x);
/** @brief Set FP to zero
*
@param x FP number to be set to 0
*/
extern void FP_zero(FP *x);
/** @brief Copy an FP
*
@param y FP number to be copied to
@param x FP to be copied from
*/
extern void FP_copy(FP *y, FP *x);
/** @brief Copy from ROM to an FP
*
@param y FP number to be copied to
@param x BIG to be copied from ROM
*/
extern void FP_rcopy(FP *y, const B256_56::BIG x);
/** @brief Compares two FPs
*
@param x FP number
@param y FP number
@return 1 if equal, else returns 0
*/
extern int FP_equals(FP *x, FP *y);
/** @brief Conditional constant time swap of two FP numbers
*
Conditionally swaps parameters in constant time (without branching)
@param x an FP number
@param y another FP number
@param s swap takes place if not equal to 0
*/
extern void FP_cswap(FP *x, FP *y, int s);
/** @brief Conditional copy of FP number
*
Conditionally copies second parameter to the first (without branching)
@param x an FP number
@param y another FP number
@param s copy takes place if not equal to 0
*/
extern void FP_cmove(FP *x, FP *y, int s);
/** @brief Converts from BIG integer to residue form mod Modulus
*
@param x BIG number to be converted
@param y FP result
*/
extern void FP_nres(FP *y, B256_56::BIG x);
/** @brief Converts from residue form back to BIG integer form
*
@param y FP number to be converted to BIG
@param x BIG result
*/
extern void FP_redc(B256_56::BIG x, FP *y);
/** @brief Sets FP to representation of unity in residue form
*
@param x FP number to be set equal to unity.
*/
extern void FP_one(FP *x);
/** @brief returns "sign" of an FP
*
@param x FP number
@return 0 for positive, 1 for negative
*/
extern int FP_sign(FP *x);
/** @brief Reduces DBIG to BIG exploiting special form of the modulus
*
This function comes in different flavours depending on the form of Modulus that is currently in use.
@param r BIG number, on exit = d mod Modulus
@param d DBIG number to be reduced
*/
extern void FP_mod(B256_56::BIG r, B256_56::DBIG d);
#ifdef FUSED_MODMUL
extern void FP_modmul(B256_56::BIG, B256_56::BIG, B256_56::BIG);
#endif
/** @brief Fast Modular multiplication of two FPs, mod Modulus
*
Uses appropriate fast modular reduction method
@param x FP number, on exit the modular product = y*z mod Modulus
@param y FP number, the multiplicand
@param z FP number, the multiplier
*/
extern void FP_mul(FP *x, FP *y, FP *z);
/** @brief Fast Modular multiplication of an FP, by a small integer, mod Modulus
*
@param x FP number, on exit the modular product = y*i mod Modulus
@param y FP number, the multiplicand
@param i a small number, the multiplier
*/
extern void FP_imul(FP *x, FP *y, int i);
/** @brief Fast Modular squaring of an FP, mod Modulus
*
Uses appropriate fast modular reduction method
@param x FP number, on exit the modular product = y^2 mod Modulus
@param y FP number, the number to be squared
*/
extern void FP_sqr(FP *x, FP *y);
/** @brief Modular addition of two FPs, mod Modulus
*
@param x FP number, on exit the modular sum = y+z mod Modulus
@param y FP number
@param z FP number
*/
extern void FP_add(FP *x, FP *y, FP *z);
/** @brief Modular subtraction of two FPs, mod Modulus
*
@param x FP number, on exit the modular difference = y-z mod Modulus
@param y FP number
@param z FP number
*/
extern void FP_sub(FP *x, FP *y, FP *z);
/** @brief Modular division by 2 of an FP, mod Modulus
*
@param x FP number, on exit =y/2 mod Modulus
@param y FP number
*/
extern void FP_div2(FP *x, FP *y);
/** @brief Fast Modular exponentiation of an FP, to the power of a BIG, mod Modulus
*
@param x FP number, on exit = y^z mod Modulus
@param y FP number
@param z BIG number exponent
*/
extern void FP_pow(FP *x, FP *y, B256_56::BIG z);
/** @brief Inverse square root precalculation
*
@param r FP number, on exit = x^(p-2*e-1)/2^(e+1) mod Modulus
@param x FP number
*/
extern void FP_invsqrt(FP *r,FP *x);
/** @brief Fast Modular square root of a an FP, mod Modulus
*
@param x FP number, on exit = sqrt(y) mod Modulus
@param y FP number, the number whose square root is calculated
@param h an optional precalculation
*/
extern void FP_sqrt(FP *x, FP *y, FP *h);
/** @brief Modular negation of a an FP, mod Modulus
*
@param x FP number, on exit = -y mod Modulus
@param y FP number
*/
extern void FP_neg(FP *x, FP *y);
/** @brief Outputs an FP number to the console
*
Converts from residue form before output
@param x an FP number
*/
extern void FP_output(FP *x);
/** @brief Outputs an FP number to the console, in raw form
*
@param x a BIG number
*/
extern void FP_rawoutput(FP *x);
/** @brief Reduces possibly unreduced FP mod Modulus
*
@param x FP number, on exit reduced mod Modulus
*/
extern void FP_reduce(FP *x);
/** @brief normalizes FP
*
@param x FP number, on exit normalized
*/
extern void FP_norm(FP *x);
/** @brief Tests for FP a quadratic residue mod Modulus
*
@param x FP number to be tested
@param h an optional precalculation
@return 1 if quadratic residue, else returns 0 if quadratic non-residue
*/
extern int FP_qr(FP *x,FP *h);
/** @brief Modular inverse of a an FP, mod Modulus
*
@param x FP number, on exit = 1/y mod Modulus
@param y FP number
*/
extern void FP_inv(FP *x, FP *y);
/** @brief Special exponent of an FP, mod Modulus
*
@param x FP number, on exit = x^s mod Modulus
@param y FP number
*/
extern void FP_fpow(FP *x, FP *y);
}
#endif
| [
"ahmedaziz.nust@hotmail.com"
] | ahmedaziz.nust@hotmail.com |
e9f2b183c41697bc7153edba86541fad9afb4f0c | cf9f9ecba5c34c1839ece33cf30f653c0076a368 | /nvse/nvse/CommandTable.cpp | 42116c6ff846c2a9a56f39378a0f40fd5168e762 | [] | no_license | rethesda/Improved-Console-NVSE | 9d04c3a7e3af08343d6a53502df26a80a87740e1 | 7e09eb0ed8998bfe84fd2467e52e835297dd6f59 | refs/heads/master | 2023-03-16T12:58:44.305693 | 2021-02-11T04:34:14 | 2021-02-11T04:34:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,439 | cpp | #include "CommandTable.h"
#include "SafeWrite.h"
#include "GameAPI.h"
#include "GameData.h"
#include "GameObjects.h"
#include "GameEffects.h"
#include "GameExtraData.h"
#include "GameForms.h"
#include "GameProcess.h"
#include "GameRTTI.h"
#include "GameSettings.h"
#include "GameUI.h"
#include <string>
#include "Utilities.h"
#include "PluginManager.h"
CommandTable g_consoleCommands;
CommandTable g_scriptCommands;
#if RUNTIME
#if RUNTIME_VERSION == RUNTIME_VERSION_1_4_0_525
// 1.4.0.525 runtime
UInt32 g_offsetConsoleCommandsStart = 0x0118E8E0;
UInt32 g_offsetConsoleCommandsLast = 0x011908C0;
UInt32 g_offsetScriptCommandsStart = 0x01190910;
UInt32 g_offsetScriptCommandsLast = 0x01196D10;
static const Cmd_Parse g_defaultParseCommand = (Cmd_Parse)0x005B1BA0;
#elif RUNTIME_VERSION == RUNTIME_VERSION_1_4_0_525ng
// 1.4.0.525 nogore runtime
UInt32 g_offsetConsoleCommandsStart = 0x0118E8E0;
UInt32 g_offsetConsoleCommandsLast = 0x011908C0;
UInt32 g_offsetScriptCommandsStart = 0x01190910;
UInt32 g_offsetScriptCommandsLast = 0x01196D10;
static const Cmd_Parse g_defaultParseCommand = (Cmd_Parse)0x005B1C40;
#else
#error
#endif
#else
// 1.4.0.518 editor
UInt32 g_offsetConsoleCommandsStart = 0x00E9DB88;
UInt32 g_offsetConsoleCommandsLast = 0x00E9FB90;
UInt32 g_offsetScriptCommandsStart = 0x00E9FBB8;
UInt32 g_offsetScriptCommandsLast = 0x00EA5FB8;
static const Cmd_Parse g_defaultParseCommand = (Cmd_Parse)0x005C67E0;
#endif
struct PatchLocation
{
UInt32 ptr;
UInt32 offset;
UInt32 type;
};
#if RUNTIME
#if RUNTIME_VERSION == RUNTIME_VERSION_1_4_0_525
static const PatchLocation kPatch_ScriptCommands_Start[] =
{
{ 0x005B1172, 0x00 },
{ 0x005B19B1, 0x00 },
{ 0x005B19CE, 0x04 },
{ 0x005B19F8, 0x08 },
{ 0x005BCC0A, 0x0C },
{ 0x005BCC2D, 0x00 },
{ 0x005BCC50, 0x04 },
{ 0x005BCC70, 0x0C },
{ 0x005BCC86, 0x0C },
{ 0x005BCCA6, 0x04 },
{ 0x005BCCB8, 0x04 },
{ 0x005BCCD4, 0x0C },
{ 0x005BCCE4, 0x04 },
{ 0x005BCCF4, 0x00 },
{ 0x005BCD13, 0x0C },
{ 0x005BCD23, 0x00 },
{ 0x005BCD42, 0x04 },
{ 0x005BCD54, 0x04 },
{ 0x005BCD70, 0x04 },
{ 0x005BCD80, 0x00 },
{ 0x005BCD9F, 0x00 },
{ 0x0068170B, 0x20 },
{ 0x00681722, 0x10 },
{ 0x00681752, 0x20 },
{ 0x00681AEB, 0x20 },
{ 0x00681CDE, 0x00 },
{ 0x006820FF, 0x14 },
{ 0x0068228D, 0x12 },
{ 0x006822FF, 0x14 },
{ 0x00682352, 0x14 },
{ 0x006823B2, 0x14 },
{ 0x0087A909, 0x12 },
{ 0x0087A948, 0x14 },
{ 0 },
};
static const PatchLocation kPatch_ScriptCommands_End[] =
{
{ 0x005AEA59, 0x08 },
{ 0 },
};
// 127B / 027B
// 1280 / 0280
static const PatchLocation kPatch_ScriptCommands_MaxIdx[] =
{
{ 0x00593909 + 1, 0 },
{ 0x005AEA57 + 6, 0 },
{ 0x005B115B + 3, 0 },
{ 0x005B19A0 + 3, (UInt32)(-0x1000) },
{ 0x005BCBDD + 6, (UInt32)(-0x1000) },
#if 0
// ### investigate this function
{ 0x0067F0B8 + 3, 0 },
{ 0x0067F0D5 + 3, (UInt32)(-0x1000) },
{ 0x0067F0F4 + 3, (UInt32)(-0x1000) },
#endif
{ 0 },
};
#elif RUNTIME_VERSION == RUNTIME_VERSION_1_4_0_525ng
static const PatchLocation kPatch_ScriptCommands_Start[] =
{
{ 0x005B1212, 0x00 },
{ 0x005B1A51, 0x00 },
{ 0x005B1A6E, 0x04 },
{ 0x005B1A98, 0x08 },
{ 0x005BCC7A, 0x0C },
{ 0x005BCC9D, 0x00 },
{ 0x005BCCC0, 0x04 },
{ 0x005BCCE0, 0x0C },
{ 0x005BCCF6, 0x0C },
{ 0x005BCD16, 0x04 },
{ 0x005BCD28, 0x04 },
{ 0x005BCD44, 0x0C },
{ 0x005BCD54, 0x04 },
{ 0x005BCD64, 0x00 },
{ 0x005BCD83, 0x0C },
{ 0x005BCD93, 0x00 },
{ 0x005BCDB2, 0x04 },
{ 0x005BCDC4, 0x04 },
{ 0x005BCDE0, 0x04 },
{ 0x005BCDF0, 0x00 },
{ 0x005BCE0F, 0x00 },
{ 0x0068128B, 0x20 },
{ 0x006812A2, 0x10 },
{ 0x006812D2, 0x20 },
{ 0x0068166B, 0x20 },
{ 0x0068185E, 0x00 },
{ 0x00681C7F, 0x14 },
{ 0x00681E0D, 0x12 },
{ 0x00681E7F, 0x14 },
{ 0x00681ED2, 0x14 },
{ 0x00681F32, 0x14 },
{ 0x0087A469, 0x12 },
{ 0x0087A4A8, 0x14 },
{ 0 },
};
static const PatchLocation kPatch_ScriptCommands_End[] =
{
{ 0x005AEAF9, 0x08 },
{ 0 },
};
// 127B / 027B
// 1280 / 0280
static const PatchLocation kPatch_ScriptCommands_MaxIdx[] =
{
{ 0x00593AF9 + 1, 0 },
{ 0x005AEAF7 + 6, 0 },
{ 0x005B11FB + 3, 0 },
{ 0x005B1A40 + 3, (UInt32)(-0x1000) },
{ 0x005BCC4D + 6, (UInt32)(-0x1000) },
{ 0 },
};
#else
#error
#endif
void ApplyPatchEditorOpCodeDataList(void) {
}
#else
static const PatchLocation kPatch_ScriptCommands_Start[] =
{
{ 0x004072AF, 0x00 },
{ 0x004073FA, 0x00 },
{ 0x004A2374, 0x24 },
{ 0x004A23E8, 0x24 },
{ 0x004A2B9B, 0x00 },
{ 0x004A3CE2, 0x20 },
{ 0x004A3CF2, 0x10 },
{ 0x004A431A, 0x00 },
{ 0x004A474A, 0x20 },
{ 0x004A485F, 0x00 },
{ 0x004A4ED1, 0x00 },
{ 0x004A5134, 0x00 },
{ 0x004A58B4, 0x12 },
{ 0x004A58F5, 0x12 },
{ 0x004A5901, 0x14 },
{ 0x004A593E, 0x12 },
{ 0x004A5949, 0x14 },
{ 0x004A5A26, 0x12 },
{ 0x004A5A6D, 0x12 },
{ 0x004A5A79, 0x14 },
{ 0x004A5AD6, 0x12 },
{ 0x004A5B1D, 0x12 },
{ 0x004A5B29, 0x14 },
{ 0x004A5B7C, 0x12 },
{ 0x004A5BD9, 0x12 },
{ 0x004A5C28, 0x12 },
{ 0x004A5C34, 0x14 },
{ 0x004A600C, 0x14 },
{ 0x004A6704, 0x12 },
{ 0x004A6749, 0x12 },
{ 0x004A6755, 0x14 },
{ 0x004A684C, 0x12 },
{ 0x004A6A8F, 0x12 },
{ 0x004A6A9F, 0x14 },
{ 0x004A6BDF, 0x12 },
{ 0x004A6D30, 0x14 },
{ 0x004A6D74, 0x14 },
{ 0x004A703B, 0x12 },
{ 0x004A716D, 0x12 },
{ 0x004A71B5, 0x14 },
{ 0x004A7268, 0x14 },
{ 0x004A735A, 0x12 },
{ 0x004A7536, 0x14 },
{ 0x0059C532, 0x20 },
{ 0x0059C53B, 0x24 },
{ 0x0059C6BA, 0x24 },
{ 0x005C53F4, 0x04 },
{ 0x005C548D, 0x08 },
{ 0x005C6636, 0x00 },
{ 0x005C9499, 0x00 },
{ 0 },
};
static const PatchLocation kPatch_ScriptCommands_End[] =
{
{ 0x004A433B, 0x00 },
{ 0x0059C710, 0x24 },
{ 0x005C5372, 0x08 },
{ 0x005C541F, 0x04 },
{ 0 },
};
// 280 / 1280 / 27F
static const PatchLocation kPatch_ScriptCommands_MaxIdx[] =
{
{ 0x004A2B87 + 2, (UInt32)(-0x1000) },
{ 0x0059C576 + 2, (UInt32)(-0x1000) },
{ 0x005B1817 + 1, 0 },
{ 0x005C5370 + 6, 0 },
{ 0x004A439D + 2, (UInt32)(-0x1000) - 1 },
{ 0x004A43AD + 1, (UInt32)(-0x1000) - 1 },
{ 0x004A43B9 + 2, (UInt32)(-0x1000) - 1 },
{ 0x005C6625 + 1, (UInt32)(-0x1000) - 1 },
{ 0x005C948B + 2, (UInt32)(-0x1000) - 1 },
{ 0 },
};
#define OpCodeDataListAddress 0x004A4390 // The function containing the fith element of array kPatch_ScriptCommands_MaxIdx
#define hookOpCodeDataListAddress 0x004A5562 // call hookOpCodeDataList. This is the second reference to the function.
static void* OpCodeDataListFunc = (void*)OpCodeDataListAddress;
int __fastcall hookOpCodeDataList(UInt32 ECX, UInt32 EDX, UInt32 opCode) { // Replacement for the vanilla version that truncate opCode by 1000
_asm {
mov eax, opCode
add eax, 0x01000
push eax
call OpCodeDataListFunc // baseOpCodeDataList // ecx and edx are still in place
}
}
void ApplyPatchEditorOpCodeDataList(void) {
SInt32 RelativeAddress = (UInt32)(&hookOpCodeDataList) - hookOpCodeDataListAddress - 5 /* EIP after instruction that we modify*/;
SafeWrite32(hookOpCodeDataListAddress+1, (UInt32)RelativeAddress);
}
#endif
static void ApplyPatch(const PatchLocation * patch, UInt32 newData)
{
for(; patch->ptr; ++patch)
{
switch(patch->type)
{
case 0:
SafeWrite32(patch->ptr, newData + patch->offset);
break;
case 1:
SafeWrite16(patch->ptr, newData + patch->offset);
break;
}
}
}
bool Cmd_Default_Execute(COMMAND_ARGS)
{
return true;
}
bool Cmd_Default_Eval(COMMAND_ARGS_EVAL)
{
return true;
}
bool Cmd_Default_Parse(UInt32 numParams, ParamInfo * paramInfo, ScriptLineBuffer * lineBuf, ScriptBuffer * scriptBuf)
{
return g_defaultParseCommand(numParams, paramInfo, lineBuf, scriptBuf);
}
#if RUNTIME
bool Cmd_GetNVSEVersion_Eval(COMMAND_ARGS_EVAL)
{
*result = NVSE_VERSION_INTEGER;
if (IsConsoleMode()) {
Console_Print("NVSE version: %d", NVSE_VERSION_INTEGER);
}
return true;
}
bool Cmd_GetNVSEVersion_Execute(COMMAND_ARGS)
{
return Cmd_GetNVSEVersion_Eval(thisObj, 0, 0, result);
}
bool Cmd_GetNVSERevision_Eval(COMMAND_ARGS_EVAL)
{
*result = NVSE_VERSION_INTEGER_MINOR;
if (IsConsoleMode()) {
Console_Print("NVSE revision: %d", NVSE_VERSION_INTEGER_MINOR);
}
return true;
}
bool Cmd_GetNVSERevision_Execute(COMMAND_ARGS)
{
return Cmd_GetNVSERevision_Eval(thisObj, 0, 0, result);
}
bool Cmd_GetNVSEBeta_Eval(COMMAND_ARGS_EVAL)
{
*result = NVSE_VERSION_INTEGER_BETA;
if (IsConsoleMode()) {
Console_Print("NVSE beta: %d", NVSE_VERSION_INTEGER_BETA);
}
return true;
}
bool Cmd_GetNVSEBeta_Execute(COMMAND_ARGS)
{
return Cmd_GetNVSEBeta_Eval(thisObj, 0, 0, result);
}
bool Cmd_DumpDocs_Execute(COMMAND_ARGS)
{
if (IsConsoleMode()) {
Console_Print("Dumping Command Docs");
}
g_scriptCommands.DumpCommandDocumentation();
if (IsConsoleMode()) {
Console_Print("Done Dumping Command Docs");
}
return true;
}
bool Cmd_tcmd_Execute(COMMAND_ARGS)
{
_MESSAGE("tcmd");
Console_Print("hello world");
Debug_DumpMenus();
Debug_DumpTraits();
*result = 0;
return true;
}
bool Cmd_tcmd2_Execute(COMMAND_ARGS)
{
UInt32 arg;
_MESSAGE("tcmd2");
if(ExtractArgs(EXTRACT_ARGS, &arg))
{
Console_Print("hello args: %d", arg);
}
else
{
Console_Print("hello args: failed");
}
*result = 0;
return true;
}
class Dumper {
UInt32 m_sizeToDump;
public:
Dumper(UInt32 sizeToDump = 512) : m_sizeToDump(sizeToDump) {}
bool Accept(void *addr) {
if (addr) {
DumpClass(addr, m_sizeToDump);
}
return true;
}
};
bool Cmd_tcmd3_Execute(COMMAND_ARGS)
{
return true;
}
#endif
static ParamInfo kTestArgCommand_Params[] =
{
{ "int", kParamType_Integer, 0 },
};
static ParamInfo kTestDumpCommand_Params[] =
{
{ "form", kParamType_ObjectID, 1},
};
DEFINE_CMD_COND(GetNVSEVersion, returns the installed version of NVSE, 0, NULL);
DEFINE_CMD_COND(GetNVSERevision, returns the numbered revision of the installed version of NVSE, 0, NULL);
DEFINE_CMD_COND(GetNVSEBeta, returns the numbered beta of the installed version of NVSE, 0, NULL);
DEFINE_COMMAND(DumpDocs, , 0, 0, NULL);
DEFINE_COMMAND(tcmd, test, 0, 0, NULL);
DEFINE_CMD_ALT(tcmd2, testargcmd ,test, 0, 1, kTestArgCommand_Params);
DEFINE_CMD_ALT(tcmd3, testdump, dump info, 0, 1, kTestDumpCommand_Params);
#define ADD_CMD(command) Add(&kCommandInfo_ ## command )
#define ADD_CMD_RET(command, rtnType) Add(&kCommandInfo_ ## command, rtnType )
#define REPL_CMD(command) Replace(GetByName(command)->opcode, &kCommandInfo_ ## command )
CommandTable::CommandTable() { }
CommandTable::~CommandTable() { }
void CommandTable::Init(void)
{
}
void CommandTable::Read(CommandInfo * start, CommandInfo * end)
{
UInt32 numCommands = end - start;
m_commands.reserve(m_commands.size() + numCommands);
for(; start != end; ++start)
Add(start);
}
void CommandTable::Add(CommandInfo * info, CommandReturnType retnType, UInt32 parentPluginOpcodeBase)
{
UInt32 backCommandID = m_baseID + m_commands.size(); // opcode of the next command to add
info->opcode = m_curID;
if(m_curID == backCommandID)
{
// adding at the end?
m_commands.push_back(*info);
}
else if(m_curID < backCommandID)
{
// adding to existing data?
ASSERT(m_curID >= m_baseID);
m_commands[m_curID - m_baseID] = *info;
}
else
{
HALT("CommandTable::Add: adding past the end");
}
m_curID++;
CommandMetadata * metadata = &m_metadata[info->opcode];
metadata->parentPlugin = parentPluginOpcodeBase;
metadata->returnType = retnType;
}
bool CommandTable::Replace(UInt32 opcodeToReplace, CommandInfo* replaceWith)
{
for (CommandList::iterator iter = m_commands.begin(); iter != m_commands.end(); ++iter)
{
if (iter->opcode == opcodeToReplace)
{
*iter = *replaceWith;
iter->opcode = opcodeToReplace;
return true;
}
}
return false;
}
static CommandInfo kPaddingCommand =
{
"", "",
0,
"command used for padding",
0,
0,
NULL,
Cmd_Default_Execute,
Cmd_Default_Parse,
NULL,
NULL
};
void CommandTable::PadTo(UInt32 id, CommandInfo * info)
{
if(!info) info = &kPaddingCommand;
while(m_baseID + m_commands.size() < id)
{
info->opcode = m_baseID + m_commands.size();
m_commands.push_back(*info);
}
m_curID = id;
}
void CommandTable::Dump(void)
{
for(CommandList::iterator iter = m_commands.begin(); iter != m_commands.end(); ++iter)
{
_DMESSAGE("%08X %04X %s %s", iter->opcode, iter->needsParent, iter->longName, iter->shortName);
gLog.Indent();
#if 0
for(UInt32 i = 0; i < iter->numParams; i++)
{
ParamInfo * param = &iter->params[i];
_DMESSAGE("%08X %08X %s", param->typeID, param->isOptional, param->typeStr);
}
#endif
gLog.Outdent();
}
}
void CommandTable::DumpAlternateCommandNames(void)
{
for (CommandList::iterator iter= m_commands.begin(); iter != m_commands.end(); ++iter)
{
if (iter->shortName)
_MESSAGE("%s", iter->shortName);
}
}
const char* SimpleStringForParamType(UInt32 paramType)
{
switch(paramType) {
case kParamType_String: return "string";
case kParamType_Integer: return "integer";
case kParamType_Float: return "float";
case kParamType_ObjectID: return "ref";
case kParamType_ObjectRef: return "ref";
case kParamType_ActorValue: return "actorValue";
case kParamType_Actor: return "ref";
case kParamType_SpellItem: return "ref";
case kParamType_Axis: return "axis";
case kParamType_Cell: return "ref";
case kParamType_AnimationGroup: return "animGroup";
case kParamType_MagicItem: return "ref";
case kParamType_Sound: return "ref";
case kParamType_Topic: return "ref";
case kParamType_Quest: return "ref";
case kParamType_Race: return "ref";
case kParamType_Class: return "ref";
case kParamType_Faction: return "ref";
case kParamType_Sex: return "sex";
case kParamType_Global: return "global";
case kParamType_Furniture: return "ref";
case kParamType_TESObject: return "ref";
case kParamType_VariableName: return "string";
case kParamType_QuestStage: return "short";
case kParamType_MapMarker: return "ref";
case kParamType_ActorBase: return "ref";
case kParamType_Container: return "ref";
case kParamType_WorldSpace: return "ref";
case kParamType_CrimeType: return "crimeType";
case kParamType_AIPackage: return "ref";
case kParamType_CombatStyle: return "ref";
case kParamType_MagicEffect: return "ref";
case kParamType_FormType: return "formType";
case kParamType_WeatherID: return "ref";
case kParamType_NPC: return "ref";
case kParamType_Owner: return "ref";
case kParamType_EffectShader: return "ref";
case kParamType_FormList: return "ref";
case kParamType_MenuIcon: return "ref";
case kParamType_Perk: return "ref";
case kParamType_Note: return "ref";
case kParamType_MiscellaneousStat: return "ref";
case kParamType_ImageSpaceModifier: return "ref";
case kParamType_ImageSpace: return "ref";
case kParamType_EncounterZone: return "ref";
case kParamType_Message: return "ref";
case kParamType_InvObjOrFormList: return "ref";
case kParamType_Alignment: return "ref";
case kParamType_EquipType: return "ref";
case kParamType_NonFormList: return "ref";
case kParamType_SoundFile: return "ref";
case kParamType_CriticalStage: return "ref";
case kParamType_LeveledOrBaseChar: return "ref";
case kParamType_LeveledOrBaseCreature: return "ref";
case kParamType_LeveledChar: return "ref";
case kParamType_LeveledCreature: return "ref";
case kParamType_LeveledItem: return "ref";
case kParamType_AnyForm: return "ref";
case kParamType_Reputation: return "ref";
case kParamType_Casino: return "ref";
case kParamType_CasinoChip: return "ref";
case kParamType_Challenge: return "ref";
case kParamType_CaravanMoney: return "ref";
case kParamType_CaravanCard: return "ref";
case kParamType_CaravanDeck: return "ref";
case kParamType_Region: return "ref";
// custom NVSE types
// kParamType_StringVar is same as Integer
case kParamType_Array: return "array_var";
default: return "<unknown>";
}
}
const char* StringForParamType(UInt32 paramType)
{
switch(paramType) {
case kParamType_String: return "String";
case kParamType_Integer: return "Integer";
case kParamType_Float: return "Float";
case kParamType_ObjectID: return "ObjectID";
case kParamType_ObjectRef: return "ObjectRef";
case kParamType_ActorValue: return "ActorValue";
case kParamType_Actor: return "Actor";
case kParamType_SpellItem: return "SpellItem";
case kParamType_Axis: return "Axis";
case kParamType_Cell: return "Cell";
case kParamType_AnimationGroup: return "AnimationGroup";
case kParamType_MagicItem: return "MagicItem";
case kParamType_Sound: return "Sound";
case kParamType_Topic: return "Topic";
case kParamType_Quest: return "Quest";
case kParamType_Race: return "Race";
case kParamType_Class: return "Class";
case kParamType_Faction: return "Faction";
case kParamType_Sex: return "Sex";
case kParamType_Global: return "Global";
case kParamType_Furniture: return "Furniture";
case kParamType_TESObject: return "Object";
case kParamType_VariableName: return "VariableName";
case kParamType_QuestStage: return "QuestStage";
case kParamType_MapMarker: return "MapMarker";
case kParamType_ActorBase: return "ActorBase";
case kParamType_Container: return "Container";
case kParamType_WorldSpace: return "WorldSpace";
case kParamType_CrimeType: return "CrimeType";
case kParamType_AIPackage: return "AIPackage";
case kParamType_CombatStyle: return "CombatStyle";
case kParamType_MagicEffect: return "MagicEffect";
case kParamType_FormType: return "FormType";
case kParamType_WeatherID: return "WeatherID";
case kParamType_NPC: return "NPC";
case kParamType_Owner: return "Owner";
case kParamType_EffectShader: return "EffectShader";
case kParamType_FormList: return "FormList";
case kParamType_MenuIcon: return "MenuIcon";
case kParamType_Perk: return "Perk";
case kParamType_Note: return "Note";
case kParamType_MiscellaneousStat: return "MiscStat";
case kParamType_ImageSpaceModifier: return "ImageSpaceModifier";
case kParamType_ImageSpace: return "ImageSpace";
case kParamType_Unhandled2D: return "unk2D";
case kParamType_Unhandled2E: return "unk2E";
case kParamType_EncounterZone: return "EncounterZone";
case kParamType_Unhandled30: return "unk30";
case kParamType_Message: return "Message";
case kParamType_InvObjOrFormList: return "InvObjectOrFormList";
case kParamType_Alignment: return "Alignment";
case kParamType_EquipType: return "EquipType";
case kParamType_NonFormList: return "NonFormList";
case kParamType_SoundFile: return "SoundFile";
case kParamType_CriticalStage: return "CriticalStage";
case kParamType_LeveledOrBaseChar: return "LeveledOrBaseChar";
case kParamType_LeveledOrBaseCreature: return "LeveledOrBaseCreature";
case kParamType_LeveledChar: return "LeveledChar";
case kParamType_LeveledCreature: return "LeveledCreature";
case kParamType_LeveledItem: return "LeveledItem";
case kParamType_AnyForm: return "AnyForm";
case kParamType_Reputation: return "Reputation";
case kParamType_Casino: return "Casino";
case kParamType_CasinoChip: return "CasinoChip";
case kParamType_Challenge: return "Challenge";
case kParamType_CaravanMoney: return "CaravanMoney";
case kParamType_CaravanCard: return "CaravanCard";
case kParamType_CaravanDeck: return "CaravanDeck";
case kParamType_Region: return "Region";
// custom NVSE types
// kParamType_StringVar is same as Integer
case kParamType_Array: return "ArrayVar";
default: return "<unknown>";
}
}
void CommandTable::DumpCommandDocumentation(UInt32 startWithID)
{
_MESSAGE("NVSE Commands from: %#x", startWithID);
_MESSAGE("<br><b>Function Quick Reference</b>");
CommandList::iterator itEnd = m_commands.end();
for (CommandList::iterator iter = m_commands.begin();iter != itEnd; ++iter) {
if (iter->opcode >= startWithID) {
iter->DumpFunctionDef();
}
}
_MESSAGE("<hr><br><b>Functions In Detail</b>");
for (CommandList::iterator iter = m_commands.begin();iter != itEnd; ++iter) {
if (iter->opcode >= startWithID) {
iter->DumpDocs();
}
}
}
void CommandInfo::DumpDocs() const
{
_MESSAGE("<p><a name=\"%s\"></a><b>%s</b> ", longName, longName);
_MESSAGE("<br><b>Alias:</b> %s<br><b>Parameters:</b>%d", (strlen(shortName) != 0) ? shortName : "none", numParams);
if (numParams > 0) {
for(UInt32 i = 0; i < numParams; i++)
{
ParamInfo * param = ¶ms[i];
const char* paramTypeName = StringForParamType(param->typeID);
if (param->isOptional != 0) {
_MESSAGE("<br> <i>%s:%s</i> ", param->typeStr, paramTypeName);
} else {
_MESSAGE("<br> %s:%s ", param->typeStr, paramTypeName);
}
}
}
_MESSAGE("<br><b>Return Type:</b> FixMe<br><b>Opcode:</b> %#4x (%d)<br><b>Condition Function:</b> %s<br><b>Description:</b> %s</p>", opcode, opcode, eval ? "Yes" : "No",helpText);
}
void CommandInfo::DumpFunctionDef() const
{
_MESSAGE("<br>(FixMe) %s<a href=\"#%s\">%s</a> ", needsParent > 0 ? "reference." : "", longName, longName);
if (numParams > 0) {
for(UInt32 i = 0; i < numParams; i++)
{
ParamInfo * param = ¶ms[i];
const char* paramTypeName = StringForParamType(param->typeID);
if (param->isOptional != 0) {
_MESSAGE("<i>%s:%s</i> ", param->typeStr, paramTypeName);
} else {
_MESSAGE("%s:%s ", param->typeStr, paramTypeName);
}
}
}
}
CommandInfo * CommandTable::GetByName(const char * name)
{
for(CommandList::iterator iter = m_commands.begin(); iter != m_commands.end(); ++iter)
if(!_stricmp(name, iter->longName) || (iter->shortName && !_stricmp(name, iter->shortName)))
return &(*iter);
return NULL;
}
CommandInfo* CommandTable::GetByOpcode(UInt32 opcode)
{
// could do binary search here but padding command has opcode 0
for (CommandList::iterator iter = m_commands.begin(); iter != m_commands.end(); ++iter)
if (iter->opcode == opcode)
return &(*iter);
return NULL;
}
CommandReturnType CommandTable::GetReturnType(const CommandInfo* cmd)
{
CommandMetadata * metadata = NULL;
if (cmd)
metadata = &m_metadata[cmd->opcode];
if (metadata)
return metadata->returnType;
return kRetnType_Default;
}
void CommandTable::SetReturnType(UInt32 opcode, CommandReturnType retnType)
{
CommandInfo* cmdInfo = GetByOpcode(opcode);
if (!cmdInfo)
_MESSAGE("CommandTable::SetReturnType() - cannot locate command with opcode %04X", opcode);
else {
CommandMetadata * metadata = &m_metadata[opcode];
if (metadata)
metadata->returnType = retnType;
}
}
void CommandTable::RecordReleaseVersion(void)
{
m_opcodesByRelease.push_back(GetCurID());
}
UInt32 CommandTable::GetRequiredNVSEVersion(const CommandInfo* cmd)
{
UInt32 ver = 0;
if (cmd) {
if (cmd->opcode < m_opcodesByRelease[0]) // vanilla cmd
ver = 0;
else if (cmd->opcode >= kNVSEOpcodeTest) // plugin cmd, we have no way of knowing
ver = -1;
else {
for (UInt32 i = 0; i < m_opcodesByRelease.size(); i++) {
if (cmd->opcode >= m_opcodesByRelease[i]) {
ver = i;
}
else {
break;
}
}
}
}
return ver;
}
void CommandTable::RemoveDisabledPlugins(void)
{
for (CommandList::iterator iter = m_commands.begin(); iter != m_commands.end(); ++iter)
{
CommandMetadata * metadata = &m_metadata[iter->opcode];
if (metadata)
// plugin failed to load but still registered some commands?
// realistically the game is going to go down hard if this happens anyway
if(g_pluginManager.LookupHandleFromBaseOpcode(metadata->parentPlugin) == kPluginHandle_Invalid)
Replace(iter->opcode, &kPaddingCommand);
}
}
static char * kNVSEname = "NVSE";
static PluginInfo g_NVSEPluginInfo =
{
PluginInfo::kInfoVersion,
kNVSEname,
NVSE_VERSION_INTEGER,
};
PluginInfo * CommandTable::GetParentPlugin(const CommandInfo * cmd)
{
if (!cmd->opcode || cmd->opcode<kNVSEOpcodeStart)
return NULL;
if (cmd->opcode < kNVSEOpcodeTest)
return &g_NVSEPluginInfo;
CommandMetadata * metadata = &m_metadata[cmd->opcode];
if (metadata) {
PluginInfo * info = g_pluginManager.GetInfoFromBase(metadata->parentPlugin);
if (info)
return info;
}
return NULL;
}
void ImportConsoleCommand(const char * name)
{
CommandInfo * info = g_consoleCommands.GetByName(name);
if(info)
{
CommandInfo infoCopy = *info;
std::string newName;
newName = std::string("con_") + name;
infoCopy.shortName = "";
infoCopy.longName = _strdup(newName.c_str());
g_scriptCommands.Add(&infoCopy);
// _MESSAGE("imported console command %s", name);
}
else
{
_WARNING("couldn't find console command (%s)", name);
// pad it
g_scriptCommands.Add(&kPaddingCommand);
}
}
// internal commands added at the end
void CommandTable::AddDebugCommands()
{
}
void CommandTable::AddCommandsV1()
{
}
void CommandTable::AddCommandsV3s()
{
}
namespace PluginAPI {
const CommandInfo* GetCmdTblStart() { return g_scriptCommands.GetStart(); }
const CommandInfo* GetCmdTblEnd() { return g_scriptCommands.GetEnd(); }
const CommandInfo* GetCmdByOpcode(UInt32 opcode) { return g_scriptCommands.GetByOpcode(opcode); }
const CommandInfo* GetCmdByName(const char* name) { return g_scriptCommands.GetByName(name); }
UInt32 GetCmdRetnType(const CommandInfo* cmd) { return g_scriptCommands.GetReturnType(cmd); }
UInt32 GetReqVersion(const CommandInfo* cmd) { return g_scriptCommands.GetRequiredNVSEVersion(cmd); }
const PluginInfo* GetCmdParentPlugin(const CommandInfo* cmd) { return g_scriptCommands.GetParentPlugin(cmd); }
}
| [
"korri123@gmail.com"
] | korri123@gmail.com |
fd31211e31951fa9a2e27215ec39bc9cd179952b | d6bd9ac261ef7eb8f20a6751fbd815c2fc0764c8 | /Sources/Elastos/LibCore/tests/ElDroidSDK/ElastosRTSDK/elastosrtsdk/src/main/jni/elastos/Elastos.CoreLibrary.h | 014f73cfae5bb27848d27399d9d1025d6a201e7f | [
"Apache-2.0"
] | permissive | fjq123456/Elastos.RT | 67db847dbb0bd5b4ca8db8968d2254dcd03b4b56 | 6b1ec5e9ce25bd53222b0393cc85a21ca419a01f | refs/heads/master | 2021-08-14T18:58:52.327381 | 2017-11-16T12:26:41 | 2017-11-16T14:18:12 | 111,059,509 | 1 | 0 | null | 2017-11-17T04:52:08 | 2017-11-17T04:52:08 | null | UTF-8 | C++ | false | false | 26,247 | h | #ifndef __CAR_ELASTOS_CORELIBRARY_H__
#define __CAR_ELASTOS_CORELIBRARY_H__
#ifndef _NO_INCLIST
#include <elastos.h>
using namespace Elastos;
#endif // !_NO_INCLIST
namespace Elastos {
namespace Core {
interface ICharSequence;
EXTERN const _ELASTOS InterfaceID EIID_ICharSequence;
interface IAppendable;
EXTERN const _ELASTOS InterfaceID EIID_IAppendable;
interface ICloneable;
EXTERN const _ELASTOS InterfaceID EIID_ICloneable;
interface IComparable;
EXTERN const _ELASTOS InterfaceID EIID_IComparable;
interface IComparator;
EXTERN const _ELASTOS InterfaceID EIID_IComparator;
interface IStringBuilder;
EXTERN const _ELASTOS InterfaceID EIID_IStringBuilder;
interface IStringBuffer;
EXTERN const _ELASTOS InterfaceID EIID_IStringBuffer;
interface IArrayOf;
EXTERN const _ELASTOS InterfaceID EIID_IArrayOf;
interface INumber;
EXTERN const _ELASTOS InterfaceID EIID_INumber;
interface IBoolean;
EXTERN const _ELASTOS InterfaceID EIID_IBoolean;
interface IByte;
EXTERN const _ELASTOS InterfaceID EIID_IByte;
interface IChar32;
EXTERN const _ELASTOS InterfaceID EIID_IChar32;
interface IInteger16;
EXTERN const _ELASTOS InterfaceID EIID_IInteger16;
interface IInteger32;
EXTERN const _ELASTOS InterfaceID EIID_IInteger32;
interface IInteger64;
EXTERN const _ELASTOS InterfaceID EIID_IInteger64;
interface IFloat;
EXTERN const _ELASTOS InterfaceID EIID_IFloat;
interface IDouble;
EXTERN const _ELASTOS InterfaceID EIID_IDouble;
interface IString;
EXTERN const _ELASTOS InterfaceID EIID_IString;
interface IRunnable;
EXTERN const _ELASTOS InterfaceID EIID_IRunnable;
interface ISynchronize;
EXTERN const _ELASTOS InterfaceID EIID_ISynchronize;
interface IThreadUncaughtExceptionHandler;
EXTERN const _ELASTOS InterfaceID EIID_IThreadUncaughtExceptionHandler;
interface IThread;
EXTERN const _ELASTOS InterfaceID EIID_IThread;
interface IThreadGroup;
EXTERN const _ELASTOS InterfaceID EIID_IThreadGroup;
interface IClassLoader;
EXTERN const _ELASTOS InterfaceID EIID_IClassLoader;
interface IThrowable;
EXTERN const _ELASTOS InterfaceID EIID_IThrowable;
interface IStackTraceElement;
EXTERN const _ELASTOS InterfaceID EIID_IStackTraceElement;
interface IBlockGuardPolicy;
EXTERN const _ELASTOS InterfaceID EIID_IBlockGuardPolicy;
interface IBlockGuard;
EXTERN const _ELASTOS InterfaceID EIID_IBlockGuard;
interface ICloseGuardReporter;
EXTERN const _ELASTOS InterfaceID EIID_ICloseGuardReporter;
interface ICloseGuard;
EXTERN const _ELASTOS InterfaceID EIID_ICloseGuard;
interface ICloseGuardHelper;
EXTERN const _ELASTOS InterfaceID EIID_ICloseGuardHelper;
interface IEnum;
EXTERN const _ELASTOS InterfaceID EIID_IEnum;
interface IThreadLocal;
EXTERN const _ELASTOS InterfaceID EIID_IThreadLocal;
interface ICObjectClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICObjectClassObject;
interface ICThreadClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICThreadClassObject;
interface ICThreadGroupClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICThreadGroupClassObject;
interface ICPathClassLoaderClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICPathClassLoaderClassObject;
interface ICStringClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICStringClassObject;
interface ICBooleanClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICBooleanClassObject;
interface ICByteClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICByteClassObject;
interface ICChar32ClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICChar32ClassObject;
interface ICInteger16ClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICInteger16ClassObject;
interface ICInteger32ClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICInteger32ClassObject;
interface ICInteger64ClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICInteger64ClassObject;
interface ICFloatClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICFloatClassObject;
interface ICDoubleClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICDoubleClassObject;
interface ICArrayOfClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICArrayOfClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CObject;
EXTERN const _ELASTOS ClassID ECLSID_CObjectClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CThread;
EXTERN const _ELASTOS ClassID ECLSID_CThreadClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CThreadGroup;
EXTERN const _ELASTOS ClassID ECLSID_CThreadGroupClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CPathClassLoader;
EXTERN const _ELASTOS ClassID ECLSID_CPathClassLoaderClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CString;
EXTERN const _ELASTOS ClassID ECLSID_CStringClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CBoolean;
EXTERN const _ELASTOS ClassID ECLSID_CBooleanClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CByte;
EXTERN const _ELASTOS ClassID ECLSID_CByteClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CChar32;
EXTERN const _ELASTOS ClassID ECLSID_CChar32ClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CInteger16;
EXTERN const _ELASTOS ClassID ECLSID_CInteger16ClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CInteger32;
EXTERN const _ELASTOS ClassID ECLSID_CInteger32ClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CInteger64;
EXTERN const _ELASTOS ClassID ECLSID_CInteger64ClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CFloat;
EXTERN const _ELASTOS ClassID ECLSID_CFloatClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CDouble;
EXTERN const _ELASTOS ClassID ECLSID_CDoubleClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CArrayOf;
EXTERN const _ELASTOS ClassID ECLSID_CArrayOfClassObject;
}
}
namespace Elastos {
namespace IO {
interface ISerializable;
EXTERN const _ELASTOS InterfaceID EIID_ISerializable;
}
}
namespace Elastos {
namespace Math {
interface IMathContext;
EXTERN const _ELASTOS InterfaceID EIID_IMathContext;
interface IMathContextHelper;
EXTERN const _ELASTOS InterfaceID EIID_IMathContextHelper;
interface IBigDecimal;
EXTERN const _ELASTOS InterfaceID EIID_IBigDecimal;
interface IBigDecimalHelper;
EXTERN const _ELASTOS InterfaceID EIID_IBigDecimalHelper;
interface IBigInteger;
EXTERN const _ELASTOS InterfaceID EIID_IBigInteger;
interface IBigIntegerHelper;
EXTERN const _ELASTOS InterfaceID EIID_IBigIntegerHelper;
interface ICBigDecimalClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICBigDecimalClassObject;
interface ICBigDecimalHelperClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICBigDecimalHelperClassObject;
interface ICBigIntegerClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICBigIntegerClassObject;
interface ICBigIntegerHelperClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICBigIntegerHelperClassObject;
interface ICMathContextClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICMathContextClassObject;
interface ICMathContextHelperClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICMathContextHelperClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CBigDecimal;
EXTERN const _ELASTOS ClassID ECLSID_CBigDecimalClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CBigDecimalHelper;
EXTERN const _ELASTOS ClassID ECLSID_CBigDecimalHelperClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CBigInteger;
EXTERN const _ELASTOS ClassID ECLSID_CBigIntegerClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CBigIntegerHelper;
EXTERN const _ELASTOS ClassID ECLSID_CBigIntegerHelperClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CMathContext;
EXTERN const _ELASTOS ClassID ECLSID_CMathContextClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CMathContextHelper;
EXTERN const _ELASTOS ClassID ECLSID_CMathContextHelperClassObject;
}
}
namespace Elastos {
namespace Utility {
interface IBitSet;
EXTERN const _ELASTOS InterfaceID EIID_IBitSet;
interface IBitSetHelper;
EXTERN const _ELASTOS InterfaceID EIID_IBitSetHelper;
interface IDate;
EXTERN const _ELASTOS InterfaceID EIID_IDate;
interface IDateHelper;
EXTERN const _ELASTOS InterfaceID EIID_IDateHelper;
interface IIterable;
EXTERN const _ELASTOS InterfaceID EIID_IIterable;
interface ICollection;
EXTERN const _ELASTOS InterfaceID EIID_ICollection;
interface IList;
EXTERN const _ELASTOS InterfaceID EIID_IList;
interface ILocale;
EXTERN const _ELASTOS InterfaceID EIID_ILocale;
interface IBuilder;
EXTERN const _ELASTOS InterfaceID EIID_IBuilder;
interface ILocaleHelper;
EXTERN const _ELASTOS InterfaceID EIID_ILocaleHelper;
interface ILocaleBuilder;
EXTERN const _ELASTOS InterfaceID EIID_ILocaleBuilder;
interface IMapEntry;
EXTERN const _ELASTOS InterfaceID EIID_IMapEntry;
interface IMap;
EXTERN const _ELASTOS InterfaceID EIID_IMap;
interface IHashMap;
EXTERN const _ELASTOS InterfaceID EIID_IHashMap;
interface IHashSet;
EXTERN const _ELASTOS InterfaceID EIID_IHashSet;
interface IEnumeration;
EXTERN const _ELASTOS InterfaceID EIID_IEnumeration;
interface IHashTable;
EXTERN const _ELASTOS InterfaceID EIID_IHashTable;
interface IIdentityHashMap;
EXTERN const _ELASTOS InterfaceID EIID_IIdentityHashMap;
interface ILinkedHashMap;
EXTERN const _ELASTOS InterfaceID EIID_ILinkedHashMap;
interface ILinkedHashSet;
EXTERN const _ELASTOS InterfaceID EIID_ILinkedHashSet;
interface ILinkedList;
EXTERN const _ELASTOS InterfaceID EIID_ILinkedList;
interface IDictionary;
EXTERN const _ELASTOS InterfaceID EIID_IDictionary;
interface IGregorianCalendar;
EXTERN const _ELASTOS InterfaceID EIID_IGregorianCalendar;
interface IIterator;
EXTERN const _ELASTOS InterfaceID EIID_IIterator;
interface IListIterator;
EXTERN const _ELASTOS InterfaceID EIID_IListIterator;
interface IQueue;
EXTERN const _ELASTOS InterfaceID EIID_IQueue;
interface IDeque;
EXTERN const _ELASTOS InterfaceID EIID_IDeque;
interface IWeakHashMap;
EXTERN const _ELASTOS InterfaceID EIID_IWeakHashMap;
interface ITreeMap;
EXTERN const _ELASTOS InterfaceID EIID_ITreeMap;
interface ITreeSet;
EXTERN const _ELASTOS InterfaceID EIID_ITreeSet;
interface IRandomAccess;
EXTERN const _ELASTOS InterfaceID EIID_IRandomAccess;
interface ICurrency;
EXTERN const _ELASTOS InterfaceID EIID_ICurrency;
interface ICurrencyHelper;
EXTERN const _ELASTOS InterfaceID EIID_ICurrencyHelper;
interface IUUID;
EXTERN const _ELASTOS InterfaceID EIID_IUUID;
interface IUUIDHelper;
EXTERN const _ELASTOS InterfaceID EIID_IUUIDHelper;
interface IArrayList;
EXTERN const _ELASTOS InterfaceID EIID_IArrayList;
interface IFormattableFlags;
EXTERN const _ELASTOS InterfaceID EIID_IFormattableFlags;
interface IFormatter;
EXTERN const _ELASTOS InterfaceID EIID_IFormatter;
interface IFormattable;
EXTERN const _ELASTOS InterfaceID EIID_IFormattable;
interface IArrayDeque;
EXTERN const _ELASTOS InterfaceID EIID_IArrayDeque;
interface IEventListener;
EXTERN const _ELASTOS InterfaceID EIID_IEventListener;
interface IEventListenerProxy;
EXTERN const _ELASTOS InterfaceID EIID_IEventListenerProxy;
interface IEventObject;
EXTERN const _ELASTOS InterfaceID EIID_IEventObject;
interface ISortedMap;
EXTERN const _ELASTOS InterfaceID EIID_ISortedMap;
interface INavigableMap;
EXTERN const _ELASTOS InterfaceID EIID_INavigableMap;
interface ISet;
EXTERN const _ELASTOS InterfaceID EIID_ISet;
interface ISortedSet;
EXTERN const _ELASTOS InterfaceID EIID_ISortedSet;
interface INavigableSet;
EXTERN const _ELASTOS InterfaceID EIID_INavigableSet;
interface IObserver;
EXTERN const _ELASTOS InterfaceID EIID_IObserver;
interface IObservable;
EXTERN const _ELASTOS InterfaceID EIID_IObservable;
interface IPriorityQueue;
EXTERN const _ELASTOS InterfaceID EIID_IPriorityQueue;
interface IEnumSet;
EXTERN const _ELASTOS InterfaceID EIID_IEnumSet;
interface IEnumSetHelper;
EXTERN const _ELASTOS InterfaceID EIID_IEnumSetHelper;
interface IHugeEnumSet;
EXTERN const _ELASTOS InterfaceID EIID_IHugeEnumSet;
interface IMiniEnumSet;
EXTERN const _ELASTOS InterfaceID EIID_IMiniEnumSet;
interface IServiceLoader;
EXTERN const _ELASTOS InterfaceID EIID_IServiceLoader;
interface IServiceLoaderHelper;
EXTERN const _ELASTOS InterfaceID EIID_IServiceLoaderHelper;
interface IVector;
EXTERN const _ELASTOS InterfaceID EIID_IVector;
interface IStack;
EXTERN const _ELASTOS InterfaceID EIID_IStack;
interface IStringTokenizer;
EXTERN const _ELASTOS InterfaceID EIID_IStringTokenizer;
interface IUnsafeArrayList;
EXTERN const _ELASTOS InterfaceID EIID_IUnsafeArrayList;
interface IPropertyPermission;
EXTERN const _ELASTOS InterfaceID EIID_IPropertyPermission;
interface IReverseComparator;
EXTERN const _ELASTOS InterfaceID EIID_IReverseComparator;
interface IReverseComparator2;
EXTERN const _ELASTOS InterfaceID EIID_IReverseComparator2;
interface ICollections;
EXTERN const _ELASTOS InterfaceID EIID_ICollections;
interface IEnumMap;
EXTERN const _ELASTOS InterfaceID EIID_IEnumMap;
interface ICStringTokenizerClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICStringTokenizerClassObject;
interface ICArrayDequeClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICArrayDequeClassObject;
interface ICArrayListClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICArrayListClassObject;
interface ICArrayListIteratorClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICArrayListIteratorClassObject;
interface ICSimpleListIteratorClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICSimpleListIteratorClassObject;
interface ICFullListIteratorClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICFullListIteratorClassObject;
interface ICSubAbstractListIteratorClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICSubAbstractListIteratorClassObject;
interface ICSubAbstractListClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICSubAbstractListClassObject;
interface ICRandomAccessSubListClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICRandomAccessSubListClassObject;
interface ICBitSetClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICBitSetClassObject;
interface ICBitSetHelperClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICBitSetHelperClassObject;
interface ICEnumMapClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICEnumMapClassObject;
interface ICHashMapClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICHashMapClassObject;
interface ICHashSetClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICHashSetClassObject;
interface ICHashTableClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICHashTableClassObject;
interface ICLinkedHashMapClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICLinkedHashMapClassObject;
interface ICLinkedHashSetClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICLinkedHashSetClassObject;
interface ICLinkedListClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICLinkedListClassObject;
interface ICVectorClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICVectorClassObject;
interface ICStackClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICStackClassObject;
interface ICWeakHashMapClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICWeakHashMapClassObject;
interface ICTreeMapClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICTreeMapClassObject;
interface ICTreeSetClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICTreeSetClassObject;
interface ICPriorityQueueClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICPriorityQueueClassObject;
interface ICHugeEnumSetClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICHugeEnumSetClassObject;
interface ICMiniEnumSetClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICMiniEnumSetClassObject;
interface ICUnsafeArrayListClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICUnsafeArrayListClassObject;
interface ICCollectionsClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICCollectionsClassObject;
interface ICEnumSetHelperClassObject;
EXTERN const _ELASTOS InterfaceID EIID_ICEnumSetHelperClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CStringTokenizer;
EXTERN const _ELASTOS ClassID ECLSID_CStringTokenizerClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CArrayDeque;
EXTERN const _ELASTOS ClassID ECLSID_CArrayDequeClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CArrayList;
EXTERN const _ELASTOS ClassID ECLSID_CArrayListClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CArrayListIterator;
EXTERN const _ELASTOS ClassID ECLSID_CArrayListIteratorClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CSimpleListIterator;
EXTERN const _ELASTOS ClassID ECLSID_CSimpleListIteratorClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CFullListIterator;
EXTERN const _ELASTOS ClassID ECLSID_CFullListIteratorClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CSubAbstractListIterator;
EXTERN const _ELASTOS ClassID ECLSID_CSubAbstractListIteratorClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CSubAbstractList;
EXTERN const _ELASTOS ClassID ECLSID_CSubAbstractListClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CRandomAccessSubList;
EXTERN const _ELASTOS ClassID ECLSID_CRandomAccessSubListClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CBitSet;
EXTERN const _ELASTOS ClassID ECLSID_CBitSetClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CBitSetHelper;
EXTERN const _ELASTOS ClassID ECLSID_CBitSetHelperClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CEnumMap;
EXTERN const _ELASTOS ClassID ECLSID_CEnumMapClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CHashMap;
EXTERN const _ELASTOS ClassID ECLSID_CHashMapClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CHashSet;
EXTERN const _ELASTOS ClassID ECLSID_CHashSetClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CHashTable;
EXTERN const _ELASTOS ClassID ECLSID_CHashTableClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CLinkedHashMap;
EXTERN const _ELASTOS ClassID ECLSID_CLinkedHashMapClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CLinkedHashSet;
EXTERN const _ELASTOS ClassID ECLSID_CLinkedHashSetClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CLinkedList;
EXTERN const _ELASTOS ClassID ECLSID_CLinkedListClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CVector;
EXTERN const _ELASTOS ClassID ECLSID_CVectorClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CStack;
EXTERN const _ELASTOS ClassID ECLSID_CStackClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CWeakHashMap;
EXTERN const _ELASTOS ClassID ECLSID_CWeakHashMapClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CTreeMap;
EXTERN const _ELASTOS ClassID ECLSID_CTreeMapClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CTreeSet;
EXTERN const _ELASTOS ClassID ECLSID_CTreeSetClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CPriorityQueue;
EXTERN const _ELASTOS ClassID ECLSID_CPriorityQueueClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CHugeEnumSet;
EXTERN const _ELASTOS ClassID ECLSID_CHugeEnumSetClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CMiniEnumSet;
EXTERN const _ELASTOS ClassID ECLSID_CMiniEnumSetClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CUnsafeArrayList;
EXTERN const _ELASTOS ClassID ECLSID_CUnsafeArrayListClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CCollections;
EXTERN const _ELASTOS ClassID ECLSID_CCollectionsClassObject;
EXTERN const _ELASTOS ClassID ECLSID_CEnumSetHelper;
EXTERN const _ELASTOS ClassID ECLSID_CEnumSetHelperClassObject;
}
}
#ifndef E_OUT_OF_MEMORY_ERROR
#define E_OUT_OF_MEMORY_ERROR 0xa1010000
#endif
#ifndef E_ASSERTION_ERROR
#define E_ASSERTION_ERROR 0xa1020000
#endif
#ifndef E_INTERNAL_ERROR
#define E_INTERNAL_ERROR 0xa1030000
#endif
#ifndef E_ILLEGAL_ACCESS_ERROR
#define E_ILLEGAL_ACCESS_ERROR 0xa1040000
#endif
#ifndef E_VERIFY_ERROR
#define E_VERIFY_ERROR 0xa1050000
#endif
#ifndef E_UNKNOWN_ERROR
#define E_UNKNOWN_ERROR 0xa1060000
#endif
#ifndef E_ABSTRACET_METHOD_ERROR
#define E_ABSTRACET_METHOD_ERROR 0xa1070000
#endif
#ifndef E_ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION
#define E_ARRAY_INDEX_OUT_OF_BOUNDS_EXCEPTION 0xa0010000
#endif
#ifndef E_ILLEGAL_ARGUMENT_EXCEPTION
#define E_ILLEGAL_ARGUMENT_EXCEPTION 0xa0020000
#endif
#ifndef E_INDEX_OUT_OF_BOUNDS_EXCEPTION
#define E_INDEX_OUT_OF_BOUNDS_EXCEPTION 0xa0030000
#endif
#ifndef E_NULL_POINTER_EXCEPTION
#define E_NULL_POINTER_EXCEPTION 0xa0040000
#endif
#ifndef E_RUNTIME_EXCEPTION
#define E_RUNTIME_EXCEPTION 0xa0050000
#endif
#ifndef E_ILLEGAL_STATE_EXCEPTION
#define E_ILLEGAL_STATE_EXCEPTION 0xa0060000
#endif
#ifndef E_ILLEGAL_THREAD_STATE_EXCEPTION
#define E_ILLEGAL_THREAD_STATE_EXCEPTION 0xa0070000
#endif
#ifndef E_UNSUPPORTED_OPERATION_EXCEPTION
#define E_UNSUPPORTED_OPERATION_EXCEPTION 0xa0080000
#endif
#ifndef E_SECURITY_EXCEPTION
#define E_SECURITY_EXCEPTION 0xa0090000
#endif
#ifndef E_STRING_INDEX_OUT_OF_BOUNDS_EXCEPTION
#define E_STRING_INDEX_OUT_OF_BOUNDS_EXCEPTION 0xa00a0000
#endif
#ifndef E_NO_SUCH_METHOD_EXCEPTION
#define E_NO_SUCH_METHOD_EXCEPTION 0xa00b0000
#endif
#ifndef E_ILLEGAL_MONITOR_STATE_EXCEPTION
#define E_ILLEGAL_MONITOR_STATE_EXCEPTION 0xa00c0000
#endif
#ifndef E_INTERRUPTED_EXCEPTION
#define E_INTERRUPTED_EXCEPTION 0xa00d0000
#endif
#ifndef E_ARITHMETIC_EXCEPTION
#define E_ARITHMETIC_EXCEPTION 0xa00e0000
#endif
#ifndef E_REMOTE_EXCEPTION
#define E_REMOTE_EXCEPTION 0x801c0000
#endif
#ifndef E_NOT_FOUND_EXCEPTION
#define E_NOT_FOUND_EXCEPTION 0xa0100000
#endif
#ifndef E_SUPER_NOT_CALLED_EXCEPTION
#define E_SUPER_NOT_CALLED_EXCEPTION 0xa0110000
#endif
#ifndef E_CLASS_NOT_FOUND_EXCEPTION
#define E_CLASS_NOT_FOUND_EXCEPTION 0xa0120000
#endif
#ifndef E_NEGATIVE_ARRAY_SIZE_EXCEPTION
#define E_NEGATIVE_ARRAY_SIZE_EXCEPTION 0xa0130000
#endif
#ifndef E_NUMBER_FORMAT_EXCEPTION
#define E_NUMBER_FORMAT_EXCEPTION 0xa0140000
#endif
#ifndef E_PATTERN_SYNTAX_EXCEPTION
#define E_PATTERN_SYNTAX_EXCEPTION 0xa0150000
#endif
#ifndef E_CLONE_NOT_SUPPORTED_EXCEPTION
#define E_CLONE_NOT_SUPPORTED_EXCEPTION 0xa0160000
#endif
#ifndef E_NAGATIVE_ARRAY_SIZE_EXCEPTION
#define E_NAGATIVE_ARRAY_SIZE_EXCEPTION 0xa0170000
#endif
#ifndef E_ILLEGAL_ACCESS_EXCEPTION
#define E_ILLEGAL_ACCESS_EXCEPTION 0xa0180000
#endif
#ifndef E_NO_SUCH_FIELD_EXCEPTION
#define E_NO_SUCH_FIELD_EXCEPTION 0xa0190000
#endif
#ifndef E_CLASS_CAST_EXCEPTION
#define E_CLASS_CAST_EXCEPTION 0xa0200000
#endif
#ifndef E_ARRAY_STORE_EXCEPTION
#define E_ARRAY_STORE_EXCEPTION 0xa0210000
#endif
#ifndef E_NO_SUCH_ELEMENT_EXCEPTION
#define E_NO_SUCH_ELEMENT_EXCEPTION 0xab000000
#endif
#ifndef E_CONCURRENT_MODIFICATION_EXCEPTION
#define E_CONCURRENT_MODIFICATION_EXCEPTION 0xa7000000
#endif
#ifndef E_FORMATTER_CLOSED_EXCEPTION
#define E_FORMATTER_CLOSED_EXCEPTION 0xa7000001
#endif
#ifndef E_MISSING_FORMAT_ARGUMENT_EXCEPTION
#define E_MISSING_FORMAT_ARGUMENT_EXCEPTION 0xa7000002
#endif
#ifndef E_ILLEGAL_FORMAT_CONVERSION_EXCEPTION
#define E_ILLEGAL_FORMAT_CONVERSION_EXCEPTION 0xa7000003
#endif
#ifndef E_ILLEGAL_FORMAT_FLAGS_EXCEPTION
#define E_ILLEGAL_FORMAT_FLAGS_EXCEPTION 0xa7000004
#endif
#ifndef E_UNKNOWN_FORMAT_CONVERSION_EXCEPTION
#define E_UNKNOWN_FORMAT_CONVERSION_EXCEPTION 0xa7000005
#endif
#ifndef E_FORMAT_FLAGS_CONVERSION_MISMATCH_EXCEPTION
#define E_FORMAT_FLAGS_CONVERSION_MISMATCH_EXCEPTION 0xa7000006
#endif
#ifndef E_MISSING_FORMAT_WIDTH_EXCEPTION
#define E_MISSING_FORMAT_WIDTH_EXCEPTION 0xa7000007
#endif
#ifndef E_ILLEGAL_FORMAT_PRECISION_EXCEPTION
#define E_ILLEGAL_FORMAT_PRECISION_EXCEPTION 0xa7000008
#endif
#ifndef E_ILLEGAL_FORMAT_WIDTH_EXCEPTION
#define E_ILLEGAL_FORMAT_WIDTH_EXCEPTION 0xa7000009
#endif
#ifndef E_EMPTY_STACK_EXCEPTION
#define E_EMPTY_STACK_EXCEPTION 0xa700000a
#endif
#ifndef E_INPUT_MISMATCH_EXCEPTION
#define E_INPUT_MISMATCH_EXCEPTION 0xa700000b
#endif
#ifndef E_MISSING_RESOURCE_EXCEPTION
#define E_MISSING_RESOURCE_EXCEPTION 0xa700000c
#endif
#ifndef E_BROKEN_BARRIER_EXCEPTION
#define E_BROKEN_BARRIER_EXCEPTION 0xa700000d
#endif
#ifndef E_ILLFORMED_LOCALE_EXCEPTION
#define E_ILLFORMED_LOCALE_EXCEPTION 0xa700000e
#endif
#ifndef E_BACKING_STORE_EXCEPTION
#define E_BACKING_STORE_EXCEPTION 0xa700000f
#endif
#ifndef E_CHECKED_ARITHMETIC_EXCEPTION
#define E_CHECKED_ARITHMETIC_EXCEPTION 0xa7000010
#endif
#ifndef E_INVALID_PREFERENCES_FORMAT_EXCEPTION
#define E_INVALID_PREFERENCES_FORMAT_EXCEPTION 0xa7000011
#endif
#ifndef E_JAR_EXCEPTION
#define E_JAR_EXCEPTION 0xa7000012
#endif
#ifndef E_AEAD_BAD_TAG_EXCEPTION
#define E_AEAD_BAD_TAG_EXCEPTION 0xb0010000
#endif
#ifndef E_BAD_PADDING_EXCEPTION
#define E_BAD_PADDING_EXCEPTION 0xb0020000
#endif
#ifndef E_EXEMPTION_MECHANISM_EXCEPTION
#define E_EXEMPTION_MECHANISM_EXCEPTION 0xb0030000
#endif
#ifndef E_ILLEGAL_BLOCK_SIZE_EXCEPTION
#define E_ILLEGAL_BLOCK_SIZE_EXCEPTION 0xb0040000
#endif
#ifndef E_NO_SUCH_PADDING_EXCEPTION
#define E_NO_SUCH_PADDING_EXCEPTION 0xb0050000
#endif
#ifndef E_SHORT_BUFFER_EXCEPTION
#define E_SHORT_BUFFER_EXCEPTION 0xb0060000
#endif
#ifndef E_DATATYPE_CONFIGURATION_EXCEPTION
#define E_DATATYPE_CONFIGURATION_EXCEPTION 0xb0070000
#endif
#ifndef E_FACTORY_CONFIGURATION_EXCEPTION
#define E_FACTORY_CONFIGURATION_EXCEPTION 0xb0080000
#endif
#ifndef E_INVALID_TRANSFORMATION
#define E_INVALID_TRANSFORMATION 0xb0090000
#endif
#ifndef E_PROVIDER_EXCEPTION
#define E_PROVIDER_EXCEPTION 0xb00a0000
#endif
#ifndef E_XPATH_EXCEPTION
#define E_XPATH_EXCEPTION 0xb0070000
#endif
#ifndef E_XPATH_EXPRESSION_EXCEPTION
#define E_XPATH_EXPRESSION_EXCEPTION 0xb0080000
#endif
#ifndef E_SSL_PEER_UNVERIFIED_EXCEPTION
#define E_SSL_PEER_UNVERIFIED_EXCEPTION 0xb1010000
#endif
#ifndef E_SSL_EXCEPTION
#define E_SSL_EXCEPTION 0xb1020000
#endif
#ifndef E_SSL_PROTOCOL_EXCEPTION
#define E_SSL_PROTOCOL_EXCEPTION 0xb1030000
#endif
#ifndef E_SSL_KEY_EXCEPTION
#define E_SSL_KEY_EXCEPTION 0xb1040000
#endif
#ifndef E_SSL_HANDSHAKE_EXCEPTION
#define E_SSL_HANDSHAKE_EXCEPTION 0xb1050000
#endif
#ifndef __ENUM_Elastos_Core_ThreadState__
#define __ENUM_Elastos_Core_ThreadState__
namespace Elastos {
namespace Core {
enum {
ThreadState_NEW = 0,
ThreadState_RUNNABLE = 1,
ThreadState_BLOCKED = 2,
ThreadState_WAITING = 3,
ThreadState_TIMED_WAITING = 4,
ThreadState_TERMINATED = 5,
};
typedef _ELASTOS Int32 ThreadState;
}
}
#endif //__ENUM_Elastos_Core_ThreadState__
#ifndef __ENUM_Elastos_Math_RoundingMode__
#define __ENUM_Elastos_Math_RoundingMode__
namespace Elastos {
namespace Math {
enum {
RoundingMode_UP = 0,
RoundingMode_DOWN = 1,
RoundingMode_CEILING = 2,
RoundingMode_FLOOR = 3,
RoundingMode_HALF_UP = 4,
RoundingMode_HALF_DOWN = 5,
RoundingMode_HALF_EVEN = 6,
RoundingMode_UNNECESSARY = 7,
};
typedef _ELASTOS Int32 RoundingMode;
}
}
#endif //__ENUM_Elastos_Math_RoundingMode__
typedef _ELASTOS PVoid LocalPtr;
#ifdef __ELASTOS_CORELIBRARY_USER_TYPE_H__
#include "Elastos.CoreLibrary_user_type.h"
#endif
#endif // __CAR_ELASTOS_CORELIBRARY_H__
| [
"song.sjun@hotmail.com"
] | song.sjun@hotmail.com |
963f13abb0ee0796535f95fea098699cc42808dd | ae8e784a6c55227fddc9bb9c87af84e8e0a45a4c | /ui/widgets/utils/element_list_widget.cpp | 363cede4b310f0eaedf694960e6a1833bfc57afa | [
"Apache-2.0"
] | permissive | BrnSlr/CuteBoard | 43cd1bad442fa3a0497ac77f149e23a624f05be6 | 00beb783e234c9a08f9a53baa0fe10744452f755 | refs/heads/master | 2022-01-18T22:16:15.967424 | 2022-01-04T09:43:37 | 2022-01-04T09:43:37 | 205,393,706 | 79 | 31 | null | null | null | null | UTF-8 | C++ | false | false | 1,653 | cpp | #include "element_list_widget.h"
#include "ui/board/board.h"
ElementListWidget::ElementListWidget(QWidget *parent) : QTreeWidget(parent)
{
setDragEnabled(true);
setSelectionBehavior( QAbstractItemView::SelectItems );
setSelectionMode( QAbstractItemView::SingleSelection );
setIconSize(QSize(48,48));
setHeaderHidden(true);
mDraggedPixmap = QPixmap(128,72);
mDraggedPixmap.fill(QApplication::palette().mid().color());
}
void ElementListWidget::dragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasFormat(Board::elementNameMimeType()))
event->accept();
else
event->ignore();
}
void ElementListWidget::dragMoveEvent(QDragMoveEvent *event)
{
if (event->mimeData()->hasFormat(Board::elementNameMimeType())) {
event->accept();
} else {
event->ignore();
}
}
void ElementListWidget::startDrag(Qt::DropActions supportedActions)
{
Q_UNUSED(supportedActions)
QList<QTreeWidgetItem*> list = selectedItems();
if(list.count() > 0) {
QTreeWidgetItem* item = list.at(0);
if(item->parent()) {
QMimeData *mimeData = new QMimeData;
mimeData->setData(Board::elementNameMimeType(),item->text(0).toUtf8());
mDraggedPixmap = QPixmap(128,72);
mDraggedPixmap.fill(QApplication::palette().mid().color());
QPainter p(&mDraggedPixmap);
p.drawPixmap(51,24, item->icon(0).pixmap(25,25));
p.end();
QDrag *drag = new QDrag(this);
drag->setMimeData(mimeData);
drag->setPixmap(mDraggedPixmap);
drag->exec();
}
}
}
| [
"43877975+BrnSlr@users.noreply.github.com"
] | 43877975+BrnSlr@users.noreply.github.com |
74b6f2b0a67ee9526d247a4c3ef74466fca4785c | 01e6591e5a01601465d8ae23411d909de0fd57a5 | /chrome/browser/signin/easy_unlock_service_regular.cc | 17ee0ff4db4edb1b736cf7731988a74fbbe08c7d | [
"BSD-3-Clause"
] | permissive | CapOM/chromium | 712a689582c418d15c2fe7777cba06ee2e52a91f | e64bf2b8f9c00e3acb2f55954c36de9f3c43d403 | refs/heads/master | 2021-01-12T22:11:06.433874 | 2015-06-25T23:49:07 | 2015-06-25T23:49:34 | 38,643,354 | 1 | 0 | null | 2015-07-06T20:13:18 | 2015-07-06T20:13:18 | null | UTF-8 | C++ | false | false | 14,694 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/signin/easy_unlock_service_regular.h"
#include "base/bind.h"
#include "base/logging.h"
#include "base/prefs/pref_service.h"
#include "base/prefs/scoped_user_pref_update.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/signin/proximity_auth_facade.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/common/extensions/api/easy_unlock_private.h"
#include "chrome/common/extensions/extension_constants.h"
#include "chrome/common/pref_names.h"
#include "chromeos/login/user_names.h"
#include "components/pref_registry/pref_registry_syncable.h"
#include "components/proximity_auth/cryptauth/cryptauth_access_token_fetcher.h"
#include "components/proximity_auth/cryptauth/cryptauth_client_impl.h"
#include "components/proximity_auth/screenlock_bridge.h"
#include "components/proximity_auth/switches.h"
#include "components/signin/core/browser/signin_manager.h"
#include "content/public/browser/browser_thread.h"
#include "extensions/browser/event_router.h"
#include "extensions/common/constants.h"
#include "google_apis/gaia/gaia_auth_util.h"
#if defined(OS_CHROMEOS)
#include "apps/app_lifetime_monitor_factory.h"
#include "base/thread_task_runner_handle.h"
#include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_key_manager.h"
#include "chrome/browser/chromeos/login/easy_unlock/easy_unlock_reauth.h"
#include "chrome/browser/chromeos/login/session/user_session_manager.h"
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "components/user_manager/user_manager.h"
#endif
namespace {
// Key name of the local device permit record dictonary in kEasyUnlockPairing.
const char kKeyPermitAccess[] = "permitAccess";
// Key name of the remote device list in kEasyUnlockPairing.
const char kKeyDevices[] = "devices";
} // namespace
EasyUnlockServiceRegular::EasyUnlockServiceRegular(Profile* profile)
: EasyUnlockService(profile),
turn_off_flow_status_(EasyUnlockService::IDLE),
will_unlock_using_easy_unlock_(false),
lock_screen_last_shown_timestamp_(base::TimeTicks::Now()),
weak_ptr_factory_(this) {
}
EasyUnlockServiceRegular::~EasyUnlockServiceRegular() {
}
EasyUnlockService::Type EasyUnlockServiceRegular::GetType() const {
return EasyUnlockService::TYPE_REGULAR;
}
std::string EasyUnlockServiceRegular::GetUserEmail() const {
const SigninManagerBase* signin_manager =
SigninManagerFactory::GetForProfileIfExists(profile());
// |profile| has to be a signed-in profile with SigninManager already
// created. Otherwise, just crash to collect stack.
DCHECK(signin_manager);
const std::string user_email = signin_manager->GetAuthenticatedUsername();
return user_email.empty() ? user_email : gaia::CanonicalizeEmail(user_email);
}
void EasyUnlockServiceRegular::LaunchSetup() {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
#if defined(OS_CHROMEOS)
// Force the user to reauthenticate by showing a modal overlay (similar to the
// lock screen). The password obtained from the reauth is cached for a short
// period of time and used to create the cryptohome keys for sign-in.
if (short_lived_user_context_ && short_lived_user_context_->user_context()) {
OpenSetupApp();
} else {
bool reauth_success = chromeos::EasyUnlockReauth::ReauthForUserContext(
base::Bind(&EasyUnlockServiceRegular::OnUserContextFromReauth,
weak_ptr_factory_.GetWeakPtr()));
if (!reauth_success)
OpenSetupApp();
}
#else
OpenSetupApp();
#endif
}
#if defined(OS_CHROMEOS)
void EasyUnlockServiceRegular::OnUserContextFromReauth(
const chromeos::UserContext& user_context) {
DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
short_lived_user_context_.reset(new chromeos::ShortLivedUserContext(
user_context, apps::AppLifetimeMonitorFactory::GetForProfile(profile()),
base::ThreadTaskRunnerHandle::Get().get()));
OpenSetupApp();
// Use this opportunity to clear the crytohome keys if it was not already
// cleared earlier.
const base::ListValue* devices = GetRemoteDevices();
if (!devices || devices->empty()) {
chromeos::EasyUnlockKeyManager* key_manager =
chromeos::UserSessionManager::GetInstance()->GetEasyUnlockKeyManager();
key_manager->RefreshKeys(
user_context, base::ListValue(),
base::Bind(&EasyUnlockServiceRegular::SetHardlockAfterKeyOperation,
weak_ptr_factory_.GetWeakPtr(),
EasyUnlockScreenlockStateHandler::NO_PAIRING));
}
}
void EasyUnlockServiceRegular::SetHardlockAfterKeyOperation(
EasyUnlockScreenlockStateHandler::HardlockState state_on_success,
bool success) {
if (success)
SetHardlockStateForUser(GetUserEmail(), state_on_success);
// Even if the refresh keys operation suceeded, we still fetch and check the
// cryptohome keys against the keys in local preferences as a sanity check.
CheckCryptohomeKeysAndMaybeHardlock();
}
#endif
const base::DictionaryValue* EasyUnlockServiceRegular::GetPermitAccess() const {
const base::DictionaryValue* pairing_dict =
profile()->GetPrefs()->GetDictionary(prefs::kEasyUnlockPairing);
const base::DictionaryValue* permit_dict = NULL;
if (pairing_dict &&
pairing_dict->GetDictionary(kKeyPermitAccess, &permit_dict))
return permit_dict;
return NULL;
}
void EasyUnlockServiceRegular::SetPermitAccess(
const base::DictionaryValue& permit) {
DictionaryPrefUpdate pairing_update(profile()->GetPrefs(),
prefs::kEasyUnlockPairing);
pairing_update->SetWithoutPathExpansion(kKeyPermitAccess, permit.DeepCopy());
}
void EasyUnlockServiceRegular::ClearPermitAccess() {
DictionaryPrefUpdate pairing_update(profile()->GetPrefs(),
prefs::kEasyUnlockPairing);
pairing_update->RemoveWithoutPathExpansion(kKeyPermitAccess, NULL);
}
const base::ListValue* EasyUnlockServiceRegular::GetRemoteDevices() const {
const base::DictionaryValue* pairing_dict =
profile()->GetPrefs()->GetDictionary(prefs::kEasyUnlockPairing);
const base::ListValue* devices = NULL;
if (pairing_dict && pairing_dict->GetList(kKeyDevices, &devices))
return devices;
return NULL;
}
void EasyUnlockServiceRegular::SetRemoteDevices(
const base::ListValue& devices) {
DictionaryPrefUpdate pairing_update(profile()->GetPrefs(),
prefs::kEasyUnlockPairing);
if (devices.empty())
pairing_update->RemoveWithoutPathExpansion(kKeyDevices, NULL);
else
pairing_update->SetWithoutPathExpansion(kKeyDevices, devices.DeepCopy());
#if defined(OS_CHROMEOS)
// TODO(tengs): Investigate if we can determine if the remote devices were set
// from sync or from the setup app.
if (short_lived_user_context_ && short_lived_user_context_->user_context()) {
// We may already have the password cached, so proceed to create the
// cryptohome keys for sign-in or the system will be hardlocked.
chromeos::UserSessionManager::GetInstance()
->GetEasyUnlockKeyManager()
->RefreshKeys(
*short_lived_user_context_->user_context(), devices,
base::Bind(&EasyUnlockServiceRegular::SetHardlockAfterKeyOperation,
weak_ptr_factory_.GetWeakPtr(),
EasyUnlockScreenlockStateHandler::NO_HARDLOCK));
} else {
CheckCryptohomeKeysAndMaybeHardlock();
}
#else
CheckCryptohomeKeysAndMaybeHardlock();
#endif
}
void EasyUnlockServiceRegular::RunTurnOffFlow() {
if (turn_off_flow_status_ == PENDING)
return;
DCHECK(!cryptauth_client_);
SetTurnOffFlowStatus(PENDING);
scoped_ptr<proximity_auth::CryptAuthClientFactory> factory =
CreateCryptAuthClientFactory();
cryptauth_client_ = factory->CreateInstance();
cryptauth::ToggleEasyUnlockRequest request;
request.set_enable(false);
request.set_apply_to_all(true);
cryptauth_client_->ToggleEasyUnlock(
request,
base::Bind(&EasyUnlockServiceRegular::OnToggleEasyUnlockApiComplete,
weak_ptr_factory_.GetWeakPtr()),
base::Bind(&EasyUnlockServiceRegular::OnToggleEasyUnlockApiFailed,
weak_ptr_factory_.GetWeakPtr()));
}
void EasyUnlockServiceRegular::ResetTurnOffFlow() {
cryptauth_client_.reset();
SetTurnOffFlowStatus(IDLE);
}
EasyUnlockService::TurnOffFlowStatus
EasyUnlockServiceRegular::GetTurnOffFlowStatus() const {
return turn_off_flow_status_;
}
std::string EasyUnlockServiceRegular::GetChallenge() const {
return std::string();
}
std::string EasyUnlockServiceRegular::GetWrappedSecret() const {
return std::string();
}
void EasyUnlockServiceRegular::RecordEasySignInOutcome(
const std::string& user_id,
bool success) const {
NOTREACHED();
}
void EasyUnlockServiceRegular::RecordPasswordLoginEvent(
const std::string& user_id) const {
NOTREACHED();
}
void EasyUnlockServiceRegular::StartAutoPairing(
const AutoPairingResultCallback& callback) {
if (!auto_pairing_callback_.is_null()) {
LOG(ERROR)
<< "Start auto pairing when there is another auto pairing requested.";
callback.Run(false, std::string());
return;
}
auto_pairing_callback_ = callback;
scoped_ptr<base::ListValue> args(new base::ListValue());
scoped_ptr<extensions::Event> event(new extensions::Event(
extensions::events::UNKNOWN,
extensions::api::easy_unlock_private::OnStartAutoPairing::kEventName,
args.Pass()));
extensions::EventRouter::Get(profile())->DispatchEventWithLazyListener(
extension_misc::kEasyUnlockAppId, event.Pass());
}
void EasyUnlockServiceRegular::SetAutoPairingResult(
bool success,
const std::string& error) {
DCHECK(!auto_pairing_callback_.is_null());
auto_pairing_callback_.Run(success, error);
auto_pairing_callback_.Reset();
}
void EasyUnlockServiceRegular::InitializeInternal() {
GetScreenlockBridgeInstance()->AddObserver(this);
registrar_.Init(profile()->GetPrefs());
registrar_.Add(
prefs::kEasyUnlockAllowed,
base::Bind(&EasyUnlockServiceRegular::OnPrefsChanged,
base::Unretained(this)));
registrar_.Add(prefs::kEasyUnlockProximityRequired,
base::Bind(&EasyUnlockServiceRegular::OnPrefsChanged,
base::Unretained(this)));
OnPrefsChanged();
}
void EasyUnlockServiceRegular::ShutdownInternal() {
#if defined(OS_CHROMEOS)
short_lived_user_context_.reset();
#endif
turn_off_flow_status_ = EasyUnlockService::IDLE;
registrar_.RemoveAll();
GetScreenlockBridgeInstance()->RemoveObserver(this);
}
bool EasyUnlockServiceRegular::IsAllowedInternal() const {
#if defined(OS_CHROMEOS)
user_manager::UserManager* user_manager = user_manager::UserManager::Get();
if (!user_manager->IsLoggedInAsUserWithGaiaAccount())
return false;
// TODO(tengs): Ephemeral accounts generate a new enrollment every time they
// are added, so disable Smart Lock to reduce enrollments on server. However,
// ephemeral accounts can be locked, so we should revisit this use case.
if (user_manager->IsCurrentUserNonCryptohomeDataEphemeral())
return false;
if (!chromeos::ProfileHelper::IsPrimaryProfile(profile()))
return false;
if (!profile()->GetPrefs()->GetBoolean(prefs::kEasyUnlockAllowed))
return false;
return true;
#else
// TODO(xiyuan): Revisit when non-chromeos platforms are supported.
return false;
#endif
}
void EasyUnlockServiceRegular::OnWillFinalizeUnlock(bool success) {
will_unlock_using_easy_unlock_ = success;
}
void EasyUnlockServiceRegular::OnSuspendDone() {
lock_screen_last_shown_timestamp_ = base::TimeTicks::Now();
}
void EasyUnlockServiceRegular::OnScreenDidLock(
proximity_auth::ScreenlockBridge::LockHandler::ScreenType screen_type) {
will_unlock_using_easy_unlock_ = false;
lock_screen_last_shown_timestamp_ = base::TimeTicks::Now();
}
void EasyUnlockServiceRegular::OnScreenDidUnlock(
proximity_auth::ScreenlockBridge::LockHandler::ScreenType screen_type) {
// Notifications of signin screen unlock events can also reach this code path;
// disregard them.
if (screen_type != proximity_auth::ScreenlockBridge::LockHandler::LOCK_SCREEN)
return;
// Only record metrics for users who have enabled the feature.
if (IsEnabled()) {
EasyUnlockAuthEvent event =
will_unlock_using_easy_unlock_
? EASY_UNLOCK_SUCCESS
: GetPasswordAuthEvent();
RecordEasyUnlockScreenUnlockEvent(event);
if (will_unlock_using_easy_unlock_) {
RecordEasyUnlockScreenUnlockDuration(
base::TimeTicks::Now() - lock_screen_last_shown_timestamp_);
}
}
will_unlock_using_easy_unlock_ = false;
}
void EasyUnlockServiceRegular::OnFocusedUserChanged(
const std::string& user_id) {
// Nothing to do.
}
void EasyUnlockServiceRegular::OnPrefsChanged() {
SyncProfilePrefsToLocalState();
UpdateAppState();
}
void EasyUnlockServiceRegular::SetTurnOffFlowStatus(TurnOffFlowStatus status) {
turn_off_flow_status_ = status;
NotifyTurnOffOperationStatusChanged();
}
void EasyUnlockServiceRegular::OnToggleEasyUnlockApiComplete(
const cryptauth::ToggleEasyUnlockResponse& response) {
cryptauth_client_.reset();
SetRemoteDevices(base::ListValue());
SetTurnOffFlowStatus(IDLE);
ReloadAppAndLockScreen();
}
void EasyUnlockServiceRegular::OnToggleEasyUnlockApiFailed(
const std::string& error_message) {
LOG(WARNING) << "Failed to turn off Smart Lock: " << error_message;
SetTurnOffFlowStatus(FAIL);
}
void EasyUnlockServiceRegular::SyncProfilePrefsToLocalState() {
PrefService* local_state =
g_browser_process ? g_browser_process->local_state() : NULL;
PrefService* profile_prefs = profile()->GetPrefs();
if (!local_state || !profile_prefs)
return;
// Create the dictionary of Easy Unlock preferences for the current user. The
// items in the dictionary are the same profile prefs used for Easy Unlock.
scoped_ptr<base::DictionaryValue> user_prefs_dict(
new base::DictionaryValue());
user_prefs_dict->SetBooleanWithoutPathExpansion(
prefs::kEasyUnlockProximityRequired,
profile_prefs->GetBoolean(prefs::kEasyUnlockProximityRequired));
DictionaryPrefUpdate update(local_state,
prefs::kEasyUnlockLocalStateUserPrefs);
std::string user_email = GetUserEmail();
update->SetWithoutPathExpansion(user_email, user_prefs_dict.Pass());
}
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
e3b232578b6d0bd4d202642b8beb84fce3694858 | e7428bcf823db625cdd988f9a2a57e146f3b74d8 | /src/obfuscation-relay.h | d59168cf3ffc5c2864bd74327062fbea007ba41d | [
"MIT"
] | permissive | 4XT-Forex-Trading/4xt | bf8ddcc7df0d76f7def4531a3e37b8c16ee0ca50 | ab8d27b4e760281e8e4d974044e1ddca4ae626f0 | refs/heads/master | 2021-05-17T01:32:43.492049 | 2020-03-27T14:34:59 | 2020-03-27T14:34:59 | 250,557,908 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,364 | h | // Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2019 The PIVX developers
// Copyright (c) 2020 The Forex Trading developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef OBFUSCATION_RELAY_H
#define OBFUSCATION_RELAY_H
#include "activemasternode.h"
#include "main.h"
#include "masternodeman.h"
class CObfuScationRelay
{
public:
CTxIn vinMasternode;
vector<unsigned char> vchSig;
vector<unsigned char> vchSig2;
int nBlockHeight;
int nRelayType;
CTxIn in;
CTxOut out;
CObfuScationRelay();
CObfuScationRelay(CTxIn& vinMasternodeIn, vector<unsigned char>& vchSigIn, int nBlockHeightIn, int nRelayTypeIn, CTxIn& in2, CTxOut& out2);
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(vinMasternode);
READWRITE(vchSig);
READWRITE(vchSig2);
READWRITE(nBlockHeight);
READWRITE(nRelayType);
READWRITE(in);
READWRITE(out);
}
std::string ToString();
bool Sign(std::string strSharedKey);
bool VerifyMessage(std::string strSharedKey);
void Relay();
void RelayThroughNode(int nRank);
};
#endif
| [
"4XT-Forex-Trading@users.noreply.github.com"
] | 4XT-Forex-Trading@users.noreply.github.com |
09f322940e3e2b5ca53b9678eacda11652bd31b0 | 2cbdcb198b63dbdc63b9d3ec6f3c7741283b0e71 | /src/networklayer/manetrouting/dymo/dymo_msg_struct.cc | d9233e575d6edb6a53acf5557c5233817f8abc62 | [] | no_license | lasfar1008/inetmanet-2.0 | 2a4245ae864ee5222d601ce32bc0c94cd7fdf63d | 6691287e2c2c03025c2ab238ed3ffd967bad0ec2 | refs/heads/master | 2021-01-16T09:51:11.479991 | 2011-11-05T12:30:30 | 2011-11-05T12:30:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,754 | cc |
#include <string.h>
#include "dymo_msg_struct.h"
#include "IPv4Address.h"
#define DYMO_RE_TYPE 1
#define DYMO_RERR_TYPE 2
#define DYMO_UERR_TYPE 3
#define DYMO_HELLO_TYPE 4
Register_Class(DYMO_element);
DYMO_element::DYMO_element(const DYMO_element& m) : cPacket()
{
setName(m.getName());
operator=(m);
}
DYMO_element& DYMO_element::operator=(const DYMO_element& msg)
{
if (this==&msg) return *this;
cPacket::operator=(msg);
m = msg.m;
h = msg.h;
type = msg.type;
len = msg.len;
ttl = msg.ttl;
i = msg.i;
res = msg.res;
notify_addr=msg.notify_addr;
target_addr=msg.target_addr;
blockAddressGroup=msg.blockAddressGroup;
extensionsize = msg.extensionsize;
previousStatic=msg.previousStatic;
#ifdef STATIC_BLOCK
memset(extension,0,STATIC_BLOCK_SIZE);
#else
if (extensionsize==0)
{
extension = NULL;
return *this;
}
extension = new char[extensionsize];
#endif
memcpy(extension,msg.extension,extensionsize);
return *this;
}
void DYMO_element:: clearExtension()
{
if (extensionsize==0)
{
return;
}
#ifdef STATIC_BLOCK
memset(extension,0,STATIC_BLOCK_SIZE);
#else
delete [] extension;
#endif
extensionsize=0;
}
DYMO_element::~DYMO_element()
{
#ifndef STATIC_BLOCK
clearExtension();
#endif
}
char * DYMO_element::addExtension(int len)
{
char * extension_aux;
if (len<0)
{
return NULL;
}
#ifndef STATIC_BLOCK
extension_aux = new char [extensionsize+len];
memcpy(extension_aux,extension,extensionsize);
delete [] extension;
extension = extension_aux;
#endif
extensionsize+=len;
//setBitLength(getBitLength ()+(len*8));
return extension;
}
char * DYMO_element::delExtension(int len)
{
char * extension_aux;
if (len<0)
{
return NULL;
}
#ifndef STATIC_BLOCK
extension_aux = new char [extensionsize-len];
memcpy(extension_aux,extension,extensionsize-len);
delete [] extension;
extension = extension_aux;
#endif
extensionsize -= len;
// setBitLength(getBitLength ()-(len*8));
return extension;
}
//=== registration
Register_Class(Dymo_RE);
Dymo_RE::Dymo_RE (const char *name) : DYMO_element (name)
{
//int bs = RE_BASIC_SIZE;
// int size = bs*8;
// setBitLength(size);
re_blocks = (struct re_block *)extension;
}
//=========================================================================
Dymo_RE::Dymo_RE(const Dymo_RE& m) : DYMO_element()
{
setName(m.getName());
operator=(m);
}
Dymo_RE& Dymo_RE::operator=(const Dymo_RE& msg)
{
if (this==&msg) return *this;
DYMO_element::operator=(msg);
target_seqnum = msg.target_seqnum;
thopcnt = msg.thopcnt;
a = msg.a;
s = msg.s;
res1= msg.res1;
res2= msg.res2;
re_blocks = (struct re_block *)extension;
setBitLength(msg.getBitLength ());
return *this;
}
void Dymo_RE::newBocks(int n)
{
if (n<=0)
return;
int new_add_size;
if (ceil((double)extensionsize/(double)sizeof(struct re_block))+n>MAX_RERR_BLOCKS)
new_add_size = (int)((MAX_RERR_BLOCKS - ceil((double)extensionsize/(double)sizeof(struct re_block)))*sizeof(struct re_block));
else
new_add_size = n*sizeof(struct re_block);
re_blocks = (struct re_block *) addExtension (new_add_size);
}
void Dymo_RE::delBocks(int n)
{
if (n<=0)
return;
int del_blk;
if (((unsigned int) n * sizeof(struct re_block))>extensionsize)
del_blk = extensionsize;
else
del_blk = n*sizeof(struct re_block);
re_blocks = (struct re_block *) delExtension (del_blk);
}
void Dymo_RE::delBlockI(int blockIndex)
{
if (blockIndex<=0)
return;
if (((unsigned int) blockIndex * sizeof(struct re_block))>extensionsize)
return;
else
{
int new_add_size;
new_add_size = extensionsize-sizeof(struct re_block);
#ifdef STATIC_BLOCK
char extensionAux[STATIC_BLOCK_SIZE];
memcpy(extensionAux,extension,STATIC_BLOCK_SIZE);
#else
char *extensionAux = new char[new_add_size];
memcpy(extensionAux,extension,new_add_size);
#endif
struct re_block *re_blocksAux = (struct re_block *) extensionAux;
int numBloks;
if ((extensionsize) % sizeof(struct re_block) != 0)
{
opp_error("re size error");
}
else
numBloks = extensionsize/ sizeof(struct re_block);
int n = numBloks - blockIndex - 1;
memmove(&re_blocksAux[blockIndex], &re_blocks[blockIndex+1],
n * sizeof(struct re_block));
#ifdef STATIC_BLOCK
memset(extension,0,STATIC_BLOCK_SIZE);
memcpy(extension,extensionAux,new_add_size);
#else
delete [] extension;
extension = extensionAux;
re_blocks =(struct re_block *) extension;
#endif
extensionsize = new_add_size;
}
}
Register_Class(Dymo_UERR);
Dymo_UERR::UERR(const Dymo_UERR& m) : DYMO_element()
{
setName(m.getName());
operator=(m);
}
Dymo_UERR& Dymo_UERR::operator=(const Dymo_UERR& msg)
{
if (this==&msg) return *this;
DYMO_element::operator=(msg);
uelem_target_addr = msg.uelem_target_addr;
uerr_node_addr=msg.uerr_node_addr;
uelem_type=msg.uelem_type;
setBitLength(msg.getBitLength ());
return *this;
}
Register_Class(Dymo_RERR);
//=========================================================================
Dymo_RERR::Dymo_RERR(const Dymo_RERR& m) : DYMO_element()
{
setName(m.getName());
operator=(m);
}
Dymo_RERR& Dymo_RERR::operator=(const Dymo_RERR& msg)
{
if (this==&msg) return *this;
DYMO_element::operator=(msg);
rerr_blocks = (struct rerr_block *)extension;
setBitLength(msg.getBitLength ());
return *this;
}
void Dymo_RERR::newBocks(int n)
{
if (n<=0)
return;
int new_add_size;
if (ceil((double)extensionsize/(double)sizeof(struct rerr_block))+n>sizeof(struct rerr_block))
new_add_size = (int)((MAX_RERR_BLOCKS - ceil((double)extensionsize/(double)sizeof(struct rerr_block)))*sizeof(struct rerr_block));
else
new_add_size = n*sizeof(struct rerr_block);
rerr_blocks = (struct rerr_block *) addExtension (new_add_size);
}
void Dymo_RERR::delBocks(int n)
{
if (n<=0)
return;
int del_blk;
if ((n * sizeof(struct rerr_block))>extensionsize)
del_blk = (int) extensionsize;
else
del_blk = n*sizeof(struct rerr_block);
rerr_blocks = (struct rerr_block *) delExtension (del_blk);
}
std::string DYMO_element::detailedInfo() const
{
std::stringstream out;
Dymo_RE *re_type =NULL;
Dymo_UERR *uerr_type=NULL;
Dymo_RERR *rerr_type=NULL;
Dymo_HELLO *hello_type=NULL;
switch (type)
{
case DYMO_RE_TYPE:
re_type = (Dymo_RE*) (this);
if (re_type->a)
out << "type : RE rreq ttl : "<< ttl << "\n";
else
out << "type : RE rrep ttl : "<< ttl << "\n";
break;
case DYMO_RERR_TYPE:
rerr_type = (Dymo_RERR*) (this);
out << "type : RERR ttl : "<< ttl << "\n";
break;
case DYMO_UERR_TYPE:
uerr_type = (Dymo_UERR*) (this);
out << "type : RERR ttl : "<< ttl << "\n";
break;
case DYMO_HELLO_TYPE:
hello_type = (Dymo_HELLO*) (this);
out << "type : HELLO ttl : "<< ttl << "\n";
break;
}
if (re_type)
{
IPv4Address addr = re_type->target_addr.getIPAddress ();
out << " target :" << addr <<" " << addr.getInt() <<"\n";
for (int i = 0; i <re_type->numBlocks(); i++)
{
out << " --------------- block : " << i << "------------------ \n";
out << "g : " << re_type->re_blocks[i].g << "\n";
out << "prefix : " <<re_type->re_blocks[i].prefix<< "\n";
out << "res : " <<re_type->re_blocks[i].res<< "\n";
out << "re_hopcnt : " <<re_type->re_blocks[i].re_hopcnt<< "\n";
IPv4Address addr = re_type->re_blocks[i].re_node_addr.getIPAddress ();
out << "re_node_addr : " << addr << " " << addr.getInt() << "\n";
out << "re_node_seqnum : " << re_type->re_blocks[i].re_node_seqnum << "\n";
}
}
else if (rerr_type)
{
IPv4Address naddr ((uint32_t) notify_addr);
out << " Notify address " << naddr << "\n"; // Khmm
for (int i = 0; i < rerr_type->numBlocks(); i++)
{
IPv4Address addr = rerr_type->rerr_blocks[i].unode_addr.getIPAddress ();
out << "unode_addr : " <<addr << "\n";
out << "unode_seqnum : " << rerr_type->rerr_blocks[i].unode_seqnum << "\n";
}
}
return out.str();
}
| [
"alfonso@alfonso-System-Product-Name.(none)"
] | alfonso@alfonso-System-Product-Name.(none) |
1c2abfdd05daaa0f81708f2b8325e99b2d0af9b6 | 88833d4256fc65a206a4505685b77dd66f4879e5 | /extent_server.h | 6456e313e0a43f049b8c3a010035b6085782967b | [] | no_license | dsieberger/ASD | 0a88593d6b9a33f0e9c005ae9f5de92f1197f1e8 | 6c9ca54ff44ecd623f019374564d79b9f51fb33b | refs/heads/master | 2021-03-12T22:23:44.828283 | 2014-11-13T18:12:48 | 2014-11-13T18:12:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 728 | h | // this is the extent server
#ifndef extent_server_h
#define extent_server_h
#include <string>
#include <map>
#include "extent_protocol.h"
class file_obj {
public:
std::string file;
extent_protocol::attr attr;
bool valid;
public:
file_obj(){
valid = true;
}
};
class extent_server {
protected:
std::map<extent_protocol::extentid_t, file_obj> map;
public:
extent_server();
int put(extent_protocol::extentid_t id, std::string, int &);
int get(extent_protocol::extentid_t id, std::string &);
int getattr(extent_protocol::extentid_t id, extent_protocol::attr &);
int remove(extent_protocol::extentid_t id, int &);
int setSize(extent_protocol::extentid_t id, int newSize, int &);
};
#endif
| [
"d.sieberger@campus.fct.unl.pt"
] | d.sieberger@campus.fct.unl.pt |
d2e90a387d876afffc7d5a6a90d59f590aa083d8 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/git/gumtree/git_patch_hunk_1659.cpp | 6b68970a67e70903f5e75d67ea21124de9a37824 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 390 | cpp | fputc('\n', stdout);
}
void fast_export_data(uint32_t mode, off_t len, struct line_buffer *input)
{
assert(len >= 0);
- if (mode == REPO_MODE_LNK) {
+ if (mode == S_IFLNK) {
/* svn symlink blobs start with "link " */
if (len < 5)
die("invalid dump: symlink too short for \"link\" prefix");
len -= 5;
if (buffer_skip_bytes(input, 5) != 5)
die_short_read(input);
| [
"993273596@qq.com"
] | 993273596@qq.com |
655503ff059c86d78df5f36759de852145c45fe3 | a0c4ed3070ddff4503acf0593e4722140ea68026 | /source/XPOS/GDI/MATH/I386/EFLOAT.HXX | e733dbbde1f14aab09089b40e5dbf59ef997a3bf | [] | no_license | cjacker/windows.xp.whistler | a88e464c820fbfafa64fbc66c7f359bbc43038d7 | 9f43e5fef59b44e47ba1da8c2b4197f8be4d4bc8 | refs/heads/master | 2022-12-10T06:47:33.086704 | 2020-09-19T15:06:48 | 2020-09-19T15:06:48 | 299,932,617 | 0 | 1 | null | 2020-09-30T13:43:42 | 2020-09-30T13:43:41 | null | UTF-8 | C++ | false | false | 10,950 | hxx | /******************************Module*Header*******************************\
* Module Name: efloat.hxx *
* *
* Contains internal floating point objects and methods. *
* *
* Created: 12-Nov-1990 16:45:01 *
* Author: Wendy Wu [wendywu] *
* *
* Copyright (c) 1990 Microsoft Corporation *
\**************************************************************************/
#define BOOL_TRUNCATE 0
#define BOOL_ROUND 1
typedef struct _FLOATINTERN
{
LONG lMant;
LONG lExp;
} FLOATINTERN;
class EFLOAT;
#ifndef DOS_PLATFORM
extern "C" {
#endif //DOS_PLATFORM
BOOL eftol_c(EFLOAT *, PLONG, LONG);
BOOL eftofx_c(EFLOAT *, PFIX);
LONG eftof_c(EFLOAT *);
VOID ltoef_c(LONG, EFLOAT *);
VOID fxtoef_c(FIX, EFLOAT *);
VOID ftoef_c(FLOAT, EFLOAT *);
// New style floating point support routines. The first pointer specifies
// where to put the return value. The first pointer is the return value.
EFLOAT *addff3_c(EFLOAT *,EFLOAT *,EFLOAT *);
EFLOAT *subff3_c(EFLOAT *,EFLOAT *,EFLOAT *);
EFLOAT *mulff3_c(EFLOAT *,const EFLOAT *,const EFLOAT *);
EFLOAT *divff3_c(EFLOAT *,EFLOAT *,EFLOAT *);
EFLOAT *sqrtf2_c(const EFLOAT *,const EFLOAT *);
EFLOAT *fraction_c(EFLOAT *,EFLOAT *);
#ifndef DOS_PLATFORM
};
#endif //DOS_PLATFORM
class POINTFL;
/*********************************Class************************************\
* class EFLOAT *
* *
* Energized floating point object. *
* *
* The floating point object defined below has 32 bits of signed mantissa *
* and 16 bits of signed exponent. The decimal point is before the MSB *
* of mantissa. The value of a number is determined by the following *
* equation: *
* value = 0.mantissa * 2^exponent *
* *
* Zero has only one unique representation with mantissa and exponent both *
* zero. *
* *
* History: *
* 12-Nov-1990 -by- Wendy Wu [wendywu] *
* Wrote it. *
\**************************************************************************/
class EFLOAT
{
public: // has to be public in order for
FLOATINTERN i; // MAKEEFLOAT to do initializations
public:
// Operator+= -- Add two EFLOAT numbers together. Caller is responsible for
// overflow checking.
VOID operator+=(EFLOAT& ef) {addff3_c(this,this,&ef);}
// Operator-= -- Substract an EFLOAT number from another. Caller is
// responsible for overflow checkings.
VOID operator-=(EFLOAT& ef) {subff3_c(this,this,&ef);}
// Operator*= -- Multiply two EFLOAT numbers together. Caller is responsible for
// overflow checkings.
VOID operator*=(EFLOAT& ef) {mulff3_c(this,this,&ef);}
// vTimes16 -- Multiply an EFLOAT number by 16.
VOID vTimes16() { if (i.lMant != 0) i.lExp += 4; }
// Operator/ -- Divide an EFLOAT number by another. Caller is responsible for
// overflow checkings.
VOID operator/=(EFLOAT& ef) {divff3_c(this,this,&ef);}
// vDivBy16 -- Divide an EFLOAT number by 16.
VOID vDivBy16() { if (i.lMant != 0) i.lExp -= 4; }
// vNegate - Negate an EFLOAT number.
VOID vNegate()
{
if (i.lMant != 0x80000000)
i.lMant = -i.lMant;
else
{
i.lMant = 0x40000000;
i.lExp += 1;
}
}
// operator> -- Signed compare two numbers. See if an EFLOAT number is
// greater than a given number.
// Is there a better way to do this???
BOOL operator>(EFLOAT& ef)
{
LONG lsignSrc = ef.i.lMant >> 31, lsignDest = i.lMant >> 31;
BOOL bReturn = FALSE;
if (lsignSrc < lsignDest) // src is negative, dest is positive
bReturn = TRUE;
else if (lsignSrc > lsignDest) // src is positive, dest is negative
;
else if (i.lExp == ef.i.lExp) // same sign, same exp, comp mantissa
bReturn = i.lMant > ef.i.lMant;
else if (lsignSrc == 0) // both src and dest are positive
{
if (((i.lExp > ef.i.lExp) && (i.lMant != 0)) || ef.i.lMant == 0)
bReturn = TRUE;
}
else // both negative
{
if (i.lExp < ef.i.lExp) // zero won't reach here
bReturn = TRUE;
}
return bReturn;
}
// operator<=,>,>=,== -- Compare two EFLOAT numbers.
BOOL operator<=(EFLOAT& ef) { return(!((*this) > ef)); }
BOOL operator<(EFLOAT& ef) { return(ef > (*this)); }
BOOL operator>=(EFLOAT& ef) { return(ef <= (*this)); }
BOOL operator==(EFLOAT& ef)
{
return((i.lMant == ef.i.lMant) && (i.lExp == ef.i.lExp));
}
// Operator= -- Assign a value to an EFLOAT number.
VOID operator=(LONG l) {ltoef_c(l,this);}
VOID operator=(FLOAT f) {ftoef_c(f,this);}
// vFxToEf -- Convert a FIX number to an EFLOAT number.
// This could have been another operator=(FIX fx). However, since
// FIX is defined as LONG. The compiler doesn't accept the second
// definition.
VOID vFxToEf(FIX fx) {fxtoef_c(fx,this);}
// bEfToL -- Convert an EFLOAT number to a LONG integer. Fractions of 0.5 or
// greater are rounded up.
BOOL bEfToL(LONG &l) { return(eftol_c(this, &l, BOOL_ROUND)); }
// bEfToLTruncate -- Convert an EFLOAT number to a LONG integer. The fractions
// are truncated.
BOOL bEfToLTruncate(LONG &l){ return(eftol_c(this, &l, BOOL_TRUNCATE)); }
// lEfToF -- Convert an EFLOAT number to an IEEE FLOAT number. The return
// value is placed in eax. We want to treat it as a LONG to
// avoid any fstp later.
LONG lEfToF() { return(eftof_c(this)); }
VOID vEfToF(FLOAT &e) { LONG l = eftof_c(this); e = *((PFLOAT) (&l)); }
// bEfToFx -- Convert an EFLOAT number to a FIX number.
BOOL bEfToFx(FIX &fx) { return(eftofx_c(this, &fx)); }
// bIsZero -- See if an EFLOAT number is zero.
BOOL bIsZero() { return((i.lMant == 0) && (i.lExp == 0)); }
// bIs16 -- Quick way to check the value of an EFLOAT number.
BOOL bIs16() { return((i.lMant == 0x040000000) && (i.lExp == 6)); }
BOOL bIsNeg16() { return((i.lMant == 0x0c0000000) && (i.lExp == 6)); }
BOOL bIs1() { return((i.lMant == 0x040000000) && (i.lExp == 2)); }
BOOL bIsNeg1() { return((i.lMant == 0x0c0000000) && (i.lExp == 2)); }
BOOL bIs1Over16() { return((i.lMant == 0x040000000) && (i.lExp == -2)); }
BOOL bIsNeg1Over16() { return((i.lMant == 0x0c0000000) && (i.lExp == -2)); }
// vDivBy2 -- Divide an EFLOAT number by 2.
VOID vDivBy2() { i.lExp -= 1; }
VOID vMultByPowerOf2(INT ii) { i.lExp += (LONG) ii; }
// vSetToZero -- Set the value of an EFLOAT number to zero.
VOID vSetToZero() { i.lMant = 0; i.lExp = 0; }
// vSetToOne -- Set the value of an EFLOAT number to one.
VOID vSetToOne() {i.lMant=0x040000000; i.lExp=2;}
// bIsNegative -- See if an EFLOAT number is negative.
BOOL bIsNegative() { return(i.lMant < 0); }
// signum -- Return a LONG representing the sign of the number.
LONG lSignum() {return((i.lMant > 0) - (i.lMant < 0));}
// vAbs -- Compute the absolute value.
VOID vAbs() { if (bIsNegative()) vNegate(); }
// vFraction -- Get the fraction part of an EFLOAT number. The result is
// stored in the passed in parameter.
//!!! This looks backwards. [chuckwh]
VOID vFraction(EFLOAT& ef) {fraction_c(&ef,this);}
// bExpInRange -- See if the exponent of an EFLOAT number is within the
// given range.
BOOL bExpLessThan(LONG max)
{
return(i.lExp <=max);
}
// vSqrt -- Takes the square root.
VOID vSqrt() {sqrtf2_c(this,this);}
// New style math routines.
//
// Usage example: EFLOAT z,t; z.eqAdd(x,t.eqSqrt(y));
// This would be the same as: EFLOAT z,t; z = x + (t = sqrt(y));
//
// I.e. you can build complex expressions, but you must declare your own
// temporaries.
EFLOAT& eqSqrt(const EFLOAT& ef)
{
return(*sqrtf2_c(this,&ef));
}
EFLOAT& eqAdd(EFLOAT& efA,EFLOAT& efB)
{
return(*addff3_c(this,&efA,&efB));
}
EFLOAT& eqSub(EFLOAT& efA,EFLOAT& efB)
{
return(*subff3_c(this,&efA,&efB));
}
EFLOAT& eqMul(const EFLOAT& efA,const EFLOAT& efB)
{
return(*mulff3_c(this,&efA,&efB));
}
EFLOAT& eqDiv(EFLOAT& efA,EFLOAT& efB)
{
return(*divff3_c(this,&efA,&efB));
}
EFLOAT& eqFraction(EFLOAT& ef)
{
return(*fraction_c(this,&ef));
}
EFLOAT& eqAbs(EFLOAT& ef)
{
i.lExp = ef.i.lExp;
i.lMant = ef.i.lMant;
if (i.lMant < 0)
{
if (i.lMant != 0x80000000)
{
i.lMant = -i.lMant;
}
else
{
i.lMant = 0x40000000;
i.lExp++;
}
}
return(*this);
}
// eqDot -- Dot product of two vectors.
EFLOAT eqDot(const POINTFL&,const POINTFL&);
// eqCross -- Cross product of two vectors. (A scaler in 2 dimensions.)
EFLOAT eqCross(const POINTFL&,const POINTFL&);
// eqLength -- Length of a vector.
EFLOAT eqLength(const POINTFL&);
};
#define EFLOAT_0 {0, 0}
#define EFLOAT_1Over16 {0x040000000, -2}
#define EFLOAT_1 {0x040000000, 2}
#define EFLOAT_16 {0x040000000, 6}
class EFLOATEXT: public EFLOAT {
public:
EFLOATEXT() {}
EFLOATEXT(LONG l) {ltoef_c(l,this);}
EFLOATEXT(FLOAT e) {ftoef_c(e,this);}
VOID operator=(const EFLOAT& ef) {*(EFLOAT*) this = ef;}
VOID operator=(LONG l) {*(EFLOAT*) this = l;}
VOID operator*=(LONG l)
{
EFLOATEXT efT(l);
mulff3_c(this,this,&efT);
}
VOID operator*=(EFLOAT& ef)
{
*(EFLOAT*)this *= ef;
}
VOID operator/=(EFLOAT& ef)
{
*(EFLOAT*)this /= ef;
}
VOID operator/=(LONG l)
{
EFLOATEXT efT(l);
divff3_c(this,this,&efT);
}
};
extern "C" LONG lCvt(EFLOAT ef,LONG ll);
| [
"71558585+window-chicken@users.noreply.github.com"
] | 71558585+window-chicken@users.noreply.github.com |
be0df2bad3cf706f18498df133942294a10a5dab | 5bee4d061cde89efa4585a6e440fb96ae4f18561 | /1/main.cpp | 185ee166d2893365b4d82c76cb500ffb693d8c31 | [] | no_license | necromaner/c-primer-plus | ea8e79bbe8aca665abbf05ce5ca4f2bba83c3f24 | 605b0f5f4cf7c533456c21325d86465a869421da | refs/heads/master | 2021-01-12T15:08:56.480751 | 2016-11-06T14:45:57 | 2016-11-06T14:45:57 | 71,714,522 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 315 | cpp | using namespace std;
#include <iostream>
#include <cstring>
int main()
{
char a[100];
int sum=0;
cout<<"Enter words (to stop,type the word done):\n";
cin>>a;
while(strcmp(a,"done"))
{
sum++;
cin>>a;
}
cout<<"You entered a total of "<<sum<<" words.\n";
return 0;
} | [
"necromaner@foxmail.com"
] | necromaner@foxmail.com |
7c00f0e20ca86f1cc067af1bc83cba597f1bf926 | e680718836cc68a9845ede290e033d2099629c9f | /xwzgServerSource/MsgServer/MSGSERVER/WORLDKERNEL/MapList.cpp | 77759f705342c7bc52e947fd7fb005280f3ca101 | [] | no_license | liu-jack/sxkmgf | 77ebe2de8113b8bb7d63b87d71d721df0af86da8 | 5aa37b3efe49c3573a9169bcf0888f6ba8517254 | refs/heads/master | 2020-06-28T21:41:05.823423 | 2018-09-28T17:30:26 | 2018-09-28T17:30:26 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,873 | cpp | // UserList.cpp: implementation of the CMapList class.
//
//////////////////////////////////////////////////////////////////////
#include "MessagePort.h"
#include "common.h"
#include "NetMsg.h"
#include "../../GameBaseCodeMT/I_mydb.h"
#include "protocol.h"
using namespace world_kernel;
#include "MapList.h"
#include "WorldKernel.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CMapList::CMapList()
{
}
CMapList::~CMapList()
{
for(int i = 0; i < m_setMap.size(); i++)
{
delete m_setMap[i];
}
}
//////////////////////////////////////////////////////////////////////
bool CMapList::Create(IDatabase* pDb)
{
CHECKF(pDb);
char szSQL[1024];
sprintf(szSQL, "SELECT id,mapgroup FROM %s LIMIT 1234567890", _TBL_MAP);
IRecordset* pRes = pDb->CreateNewRecordset(szSQL);
CHECKF(pRes);
for(int i = 0; i < pRes->RecordCount(); i++)
{
CMapSt* pMap = new CMapSt;
if(pMap)
{
pMap->idMap = pRes->LoadDWord("id");
pMap->idxMapGroup = pRes->LoadDWord("mapgroup");
m_setMap.push_back(pMap);
}
pRes->MoveNext();
}
pRes->Release();
return true;
}
//////////////////////////////////////////////////////////////////////
PROCESS_ID CMapList::GetMapProcessID(OBJID idMap)
{
for(int i = 0; i < m_setMap.size(); i++)
{
if(m_setMap[i])
{
if(m_setMap[i]->idMap == idMap)
return m_setMap[i]->idxMapGroup + MSGPORT_MAPGROUP_FIRST;
}
}
//goto 新玩家地图分配处理
if (idMap==ID_NONE)
return MSGPORT_MAPGROUP_FIRST;
return MSGPORT_MAPGROUP_INSTANCE;
}
//////////////////////////////////////////////////////////////////////
CMapSt* CMapList::GetMap(OBJID idMap)
{
for(int i = 0; i < m_setMap.size(); i++)
{
if(m_setMap[i] && m_setMap[i]->idMap == idMap)
return m_setMap[i];
}
return NULL;
}
| [
"43676169+pablones@users.noreply.github.com"
] | 43676169+pablones@users.noreply.github.com |
627a580b80117c74c53235a1bccb6d54bfb849cd | 50e6f027bfa869723e2357c85b69bfe4a0b56418 | /11-CStrings/pigLatin.cpp | b7971086e16311611e5a5d5a0b594d02569611ee | [] | no_license | JacobLetko/IntroToCpp | cde8d1a6980b3b370197cb1562723c823ccbe1c6 | 15d346af1fbe1fee4d55dffae0c735b5eb2b9d15 | refs/heads/master | 2021-06-25T07:13:33.251506 | 2017-09-06T16:31:56 | 2017-09-06T16:31:56 | 100,304,227 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 303 | cpp | #include "pigLatin.h"
#include <iostream>
void pigLatin(char word[])
{
char newWord[] = "";
for (int i = 2; i < strlen(word); i++)
{
for (int k = 0; k < strlen(word); k++)
{
newWord[k] = word[i];
if (i >= strlen(word)-2)
newWord[k] = 'w';
}
}
std::cout << newWord << std::endl;
}
| [
"jacobletko@outlook.com"
] | jacobletko@outlook.com |
9694abe421dbf9c5b2bdd9b719f66ccf204ba367 | 0061c805788b9d7f53d9be064a53dc76d1f6c82f | /17_Empregado/main_empregado.cpp | aa0309977bc2803f5fd66215a2ab1a1f3f8a4444 | [] | no_license | Vitorluca/Atividades-Orientacao-A-Objeto | 40dbd0ca4b27508a94af0e575c41507b7e3ceb12 | e25e5e21fa8bd0b2eb7ff14b0f4d03e979d48222 | refs/heads/main | 2023-02-23T05:48:55.781768 | 2021-01-22T04:01:45 | 2021-01-22T04:01:45 | 331,830,786 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,365 | cpp | /*
programa cria um objeto funcionario e define algumas de suas caracteristicas como nome e CPF
alem de calcular seu salario
DESENVOLVEDOR: VITOR LUCAS DOS SANTOS TEIXEIRA
MATRICULA: 119110521
DATA: 23 / 10 / 2020;
COMPILADOR UTILIZADO: gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
IDE: Visual Studio Code
*/
#include<iostream> //inclui a bibilhoteca basica de entrada e saida de informação
#include<clocale> //bibilhoteca de configuração especificas da localidade
#include<cstring>
using namespace std; //define que o escopo utilizado é o std
#include "metodos_pessoa.cpp" // inclui o arquivo metodos_pessoa.cpp
#include "metodos_empregado.cpp" // inclui o arquivo metodos_empregado.cpp
void Fmenu( void ); //protitipo da função menu
void Fselecao(int &menu , empregado &funcionario); //prototipo da função seleção
int main( void ){ //função principal
setlocale(LC_ALL, "portuguese"); //define que utilização cacacteres e especificidades do portugues
int menu(0); //criação da variavel inteira menu
empregado funcionario( "ROCKY BALBOA", 741258963 ); //estanciamento do objeto funcionario
do{ // loop que executa seu conteudo primeiro para depois testar sua condição
Fmenu(); // função menu é chamada pela main
cin >> menu; // variavel menu recebe um valor
if( menu <= 4 && menu >= 1 ){ // garante que a variavel menu comtemple os valores esperados
funcionario.calcularSalario(); //calcula o salario liquido do funcionario
Fselecao( menu, funcionario ); //função seleção é chamada na main
}
if( menu > 5 && menu < 1 ){ //testa se o valor de menu esta fora do esperado
cout << "ERRO, digite um numero valido" << endl; //imprime na tela uma mensagem de erro
}
}while( menu != 5 ); //executa o teste que mantem ou não o loop
return 0; // retorna 0 caso o programa funcione como previsto
}
void Fmenu( void ){ //possui um conjunto de strings que apresenta ao usuario suas opções
cout << "Digite o numero que corresponde a ação desejada" << endl;
cout << " " << endl;
cout << "1- Alterar o numero da seção do funcionario" << endl;
cout << "2- Alterar salario base" << endl;
cout << "3- alterar imposto de renda sobre o salario" << endl;
cout << "4- ficha do funcionario" << endl;
cout << "5- fechar programa" << endl;
}
//define que de acordo com o valor digitado uma rotina especifica será eexecutada
void Fselecao(int &menu , empregado &funcionario){
int numeroSecao(0); //criação de uma variavel auxiliar que armazena o numero de seção
long double salario(0); //criação de uma variavel auxiliar que armazena o salario
float imposto(0); //criação de uma variavel auxiliar que armazena o imposto
string pausa = " "; //criação de uma variavel "sentinela"
system("clear"); //função nativa do UBUNTU( no WINDOWS subistituisse "clear" por "cls" )
switch ( menu ) // estrutura de seleção de rotina
{
case 1: //rotina caso menu seja igual a 1
cout << "Insira o novo numero da seção: " << endl; //descreve a ação pedida
cin >> numeroSecao; //numero seção recebe um valor
funcionario.setNumeroSecao( numeroSecao ); //metodo do objeto que altera o numero seção é chamado
system("clear"); //função nativa do UBUNTU( no WINDOWS subistituisse "clear" por "cls" )
break; // encerra a estrutura de seleção switch
case 2: //rotina caso menu seja igual a 2
cout << "Insira o novo salario do funcionario: " << endl;//descreve a ação pedida
cin >> salario; //salario recebe um valor
funcionario.setSalarioBase( salario ); //metodo do objeto que altera o salario é chamado
system("clear"); //função nativa do UBUNTU( no WINDOWS subistituisse "clear" por "cls" )
break; // encerra a estrutura de seleção switch
case 3: //rotina caso menu seja igual a 3
//descreve a ação pedida
cout << "Insira o imposto sobre o salario( o imposto pode variar de 0 a 100% ): " << endl;
cin >> imposto; //imposto recebe um valor
funcionario.setIR( imposto ); //metodo do objeto que altera o imposto é chamado
system("clear"); //função nativa do UBUNTU( no WINDOWS subistituisse "clear" por "cls" )
break; // encerra a estrutura de seleção switch
case 4:
cout << "Ficha do funcionario" << endl; //descreve a ação que sera executada
funcionario.imprimeLiquidoSecao( ); // chama o metodo que enprime os atributos do objeto
do{ // loop que executa seu conteudo primeiro para depois testar sua condição
cout << "-------------------------------------------------------" << endl;//somente estética
cout << "Digite enter para finalizara a visualização" << endl; //informa ao usuario a ação
getline(cin, pausa); //pausa recebe uma string
}while( cin.peek() != '\n' );//verifica se a tecla digitada foi o ENTER
system("clear");//função nativa do UBUNTU( no WINDOWS subistituisse "clear" por "cls" )
break; // encerra a estrutura de seleção switch
default: //executado caso nehum dos casos esperados seja executado
break;// encerra a estrutura de seleção switch
}
} | [
"noreply@github.com"
] | noreply@github.com |
8c9a43de983f5c6d1a87977ef0c7697d171cb29b | f739d48dadf4e6714deeaece1e10efa18041c2ea | /pump_main.ino | d821ccd0fd084fa50625cbd8f4d88c579c4eaedd | [] | no_license | Marouchka/DAC | 7f6779e28bef0d5c800d05c82d8ecca4eded5784 | 675d318eb0f2127b66c229ab3a3889a9770c551e | refs/heads/master | 2020-09-09T20:53:05.558792 | 2017-06-14T21:19:48 | 2017-06-14T21:19:48 | 94,446,283 | 0 | 0 | null | 2017-06-15T14:14:44 | 2017-06-15T14:14:43 | null | UTF-8 | C++ | false | false | 3,238 | ino | #include <DAC.h>
const float refVoltage=4.85; //Set this value depending on exact input voltage from source (ie USB)
const int numDacs=4; //user input: how many DACS do you have?
float pInVoltage =0; // initialize inlet pressure
float pIn=0;
//float pAtm=101.8; //kPa -- this also should be extern, referenced in .cpp file in DAC::read()
//must use these pins, unless also changing them in the header file -- how to use extern variables with arduino??
//DAC pins
const int SS1=22;
const int SS2=24;
const int SS3=26;
const int SS4=28;
//ADC pins
const int SS5=30;
const int SS6=32;
//built in ADC pin
const int pRead = 1; //analog input
//DAC name (pinNumber, referenceVoltage)
DAC DAC1 (SS1,refVoltage);
DAC DAC2 (SS2,refVoltage);
DAC DAC3 (SS3,refVoltage);
DAC DAC4 (SS4,refVoltage);
//ADC name (pinNumber, referenceVoltage)
DAC ADC1 (SS5, refVoltage);
DAC ADC2 (SS6, refVoltage);
//to control using allDacs
DAC * allDacs [4];
DAC * objectPointer;
//Relay pins
const int rSolPin = 2; //solenoid valve
const int rTPin = 3; //transducer pin
//relay NAME (pin)
relay solenoid (rSolPin);
relay transducers (rTPin);
float cal1,cal2,cal3,cal4; //calibration variables
//**this section is temporary to test the analog read functionality
float testRead=0;
int testPin=9;
//**
void setup() {
//to control using allDacs
for (int i=0; i<numDacs; i++){
objectPointer = new DAC (SS1+2*i, refVoltage);
allDacs[i]= objectPointer;
}
pinMode(rSolPin, OUTPUT); //initialize solenoid valve pin
pinMode(rTPin, OUTPUT); //initialized transducers pins
pinMode (pRead, INPUT); //initialize inlet pressure reading (from analog in pin built into board)
pinMode (testPin, INPUT); //**temporary to test analog read values
Serial.begin(250000);
cal1=ADC1.calibrate(0);
cal2=ADC1.calibrate(1);
cal3=ADC2.calibrate(0);
cal4=ADC2.calibrate(1);
}
void loop() {
//Uncomment following block to control all DACS at once
//MAKE THIS INTO ITS OWN "ALLDACS-OFF, ALLDACS-ON" CLASS -----
// for (int i=0; i<numDacs; i++){
// allDacs[i]->on(1.2345);
// }
solenoid.on();
pIn=readInlet(); //returns psi of inlet valve
if (pIn>41){ //if the inlet pressure is greater than 41 psi, turn on the transducer relays
transducers.on();
}else{
transducers.off();
}
//DACX.on(psi_value) or DAC.off()
DAC1.off();
DAC2.on(30);
DAC3.on(25);
DAC4.on(23);
//ADCX.read(channel, calibration_value)
//ADC1.read(0,cal1);
ADC1.read(1,cal2);
ADC2.read(0,cal3);
ADC2.read(1,cal4);
Serial.print("\n");
//*temporary to test analog read
testRead=analogRead(testPin);
Serial.print(testRead);
Serial.print("\n");
/*
Serial.print("pIn: ");
Serial.print(pIn,2);
Serial.print("\n");
*/
}
float readInlet (){
pInVoltage = analogRead(pRead)/1024.0*refVoltage; //using built-in MEGA analog ADC therefore only 10 bit (1024)
pIn=((pInVoltage/refVoltage+0.00842)/0.002421-101.8)*0.145037738; //gauge pressure using transfer function of MPXH6400A pressure sensor, subtract atmospheric pressure, convert to psi
//change 101.8 to pAtm (needs to be extern variable)
return pIn;
}
| [
"noreply@github.com"
] | noreply@github.com |
3e1f7e3d10f9203465f6061f5ce5b8bef6796116 | a3e944b54aa8fd8081668ef0decd91d024979000 | /Assignments/Assignment 1/Assignment 1 - Part A/io/ElevatorWidget.cpp | c1cc21655a515f460b9a07364d29721cc9cb931c | [] | no_license | Gigahawk/cpen333 | 7d3eb8ba1b3cc73d60be455ba49af52bfcea5d7a | 6fb7b9ec523e4d55c6d757bd5cd3f512257b9592 | refs/heads/master | 2023-01-28T06:48:00.579097 | 2020-12-05T07:55:31 | 2020-12-05T07:55:31 | 294,577,843 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28 | cpp | #include "ElevatorWidget.h"
| [
"JAschan@sierrawireless.com"
] | JAschan@sierrawireless.com |
fed1288273c99ccafac1807f894f4af0d3f46694 | e21c237ce008345df683f212c0dab89db5734499 | /macrorecorder/mrCommonLib/desktop/win/GdiObject.h | 9e8fc1ed7a728d692584d439b62f447c68ae076d | [] | no_license | layerfsd/Automation | ae361e6a3f3898a956c923cb586aa4d80dd7f505 | a1f866f773196a44511c275a55cda5fc20063a14 | refs/heads/master | 2023-03-14T02:04:59.547761 | 2021-03-07T00:15:53 | 2021-03-07T00:15:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,680 | h | #pragma once
namespace mrCommonLib
{
namespace desktop
{
namespace win
{
template<class T, class Traits>
class CGDIObject
{
public:
CGDIObject() = default;
explicit CGDIObject(T object)
: m_object(object)
{}
~CGDIObject() { Traits::Close(m_object); }
T Get() { return m_object; }
void Reset(T object = nullptr)
{
if (m_object && object != m_object)
Traits::Close(m_object);
m_object = object;
}
CGDIObject& operator=(T object)
{
Reset(object);
return *this;
}
T Release()
{
T object = m_object;
m_object = nullptr;
return object;
}
operator T() { return m_object; }
private:
T m_object = nullptr;
};
template <typename T>
class TDeleteObjectTraits
{
public:
static void Close(T handle)
{
if (handle)
DeleteObject(handle);
}
};
using HBITMAPObj = CGDIObject<HBITMAP, TDeleteObjectTraits<HBITMAP>>;
using HRGNObj = CGDIObject<HRGN, TDeleteObjectTraits<HRGN>>;
using HFONTObj = CGDIObject<HFONT, TDeleteObjectTraits<HFONT>>;
using HBRUSHObj = CGDIObject<HBRUSH, TDeleteObjectTraits<HBRUSH>>;
class CScopedSelectObject
{
public:
CScopedSelectObject(HDC hdc, HGDIOBJ object)
: m_hdc(hdc),
m_oldobj(SelectObject(hdc, object))
{
}
~CScopedSelectObject()
{
HGDIOBJ object = SelectObject(m_hdc, m_oldobj);
//(GetObjectType(m_oldobj) != OBJ_REGION && object != nullptr) ||
// (GetObjectType(m_oldobj) == OBJ_REGION && object != HGDI_ERROR);
}
private:
HDC m_hdc;
HGDIOBJ m_oldobj;
};
}
}
} | [
"nk.viacheslav@gmail.com"
] | nk.viacheslav@gmail.com |
cfab34112e7223d74fbda8af4b7c6d664365f552 | 363f01b2d8b4a8197accec32da542055ffd08661 | /Remote_Control/robot_controller/graphicstofsensor.cpp | 442d7ab1eecbc3791310c442954b28799f91ddd5 | [] | no_license | magnocube/minitron | 2d70c22b4eb9a0adab435cb6c862c37ca9897204 | 6859329ed9ee01e9a84ff73e9c05764a56a2e6b3 | refs/heads/master | 2020-04-22T10:02:55.058906 | 2019-04-08T12:31:35 | 2019-04-08T12:31:35 | 170,292,267 | 0 | 0 | null | 2019-04-08T12:31:36 | 2019-02-12T09:44:13 | C | UTF-8 | C++ | false | false | 830 | cpp | #include "graphicstofsensor.h"
graphicsTOFSensor::graphicsTOFSensor()
{
distance = -1;
}
QRectF graphicsTOFSensor::boundingRect() const
{
return QRectF(0,0,width,heigth);
}
void graphicsTOFSensor::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
QRectF rect = boundingRect();
QBrush brush(Qt::red);
QPen pen(Qt::black);
QFont f;
f.setPointSize(30);
painter->setFont(f);
QString i;
i.append("TOF Sensor: ");\
if(distance == -1)
{
i.append("ERROR sensor not working");
}
else {
i.append(QString::number(distance));
i.append(" mm");
}
painter->drawText(2,365,i);
//painter->fillRect(rect,brush);
// painter->drawRect(rect);
}
void graphicsTOFSensor::setDistance(int d)
{
distance = d;
}
| [
"rene@twtg.io"
] | rene@twtg.io |
cf6554544fcd56adeab305049be832b2393460b3 | 465dcd58f8a1a7031951be153ae570250bf460d4 | /GameEngine/src/GameEngine/Layer.h | 4976877aea399b72b07168c971d2a38864b489ef | [
"Apache-2.0"
] | permissive | Denis-Moreira/GameEngine | b5b4a5f6c02d130432aca26c9129ccfef3e5bcc5 | 1843d7c2b3eab9cb0ce0bec2aaee33a8976d808f | refs/heads/master | 2022-11-15T15:53:02.523015 | 2020-07-11T01:15:08 | 2020-07-11T01:15:08 | 278,104,021 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 476 | h | #pragma once
#include "GameEngine/Core.h"
#include "GameEngine/Events/Event.h"
namespace GameEngine {
class GE_API Layer
{
public:
Layer(const std::string& name = "Layer");
virtual ~Layer();
virtual void OnAttach() {}
virtual void OnDetach() {}
virtual void OnUpdate() {}
virtual void OnImGuiRender() {}
virtual void OnEvent(Event& event) {}
inline const std::string& GetName() const { return m_DebugName; }
protected:
std::string m_DebugName;
};
} | [
"denis.vgm@outlook.com"
] | denis.vgm@outlook.com |
94a5a4276bea58cdfbadcb3d9ac6be2c483617ea | e79fe203fecbdbd87f0c356e7d82695418fefb2d | /deps/gdal/ogr/ogrsf_frmts/sxf/ogrsxfdatasource.cpp | c13c61caee51bae52ade406a34d6e2b9c0aff3ed | [
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"MIT",
"SunPro",
"LicenseRef-scancode-info-zip-2005-02",
"BSD-3-Clause"
] | permissive | psandbrook/white-star | 26ebac4321b0d0f3ee9e8acbed7041565fc8f609 | e256bd262c0545d971569c7d1cd502eb5c94c62b | refs/heads/master | 2023-07-04T05:34:30.681116 | 2021-08-03T19:54:52 | 2021-08-03T19:54:52 | 361,380,447 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 40,999 | cpp | /******************************************************************************
*
* Project: SXF Translator
* Purpose: Definition of classes for OGR SXF Datasource.
* Author: Ben Ahmed Daho Ali, bidandou(at)yahoo(dot)fr
* Dmitry Baryshnikov, polimax@mail.ru
* Alexandr Lisovenko, alexander.lisovenko@gmail.com
*
******************************************************************************
* Copyright (c) 2011, Ben Ahmed Daho Ali
* Copyright (c) 2013, NextGIS
* Copyright (c) 2014, Even Rouault <even dot rouault at spatialys.com>
* Copyright (c) 2019, NextGIS, <info@nextgis.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
****************************************************************************/
#include "cpl_conv.h"
#include "ogr_sxf.h"
#include "cpl_string.h"
#include "cpl_multiproc.h"
#include <math.h>
#include <map>
#include <string>
CPL_CVSID("$Id: ogrsxfdatasource.cpp 78f3bf72654dc87dc9f73c731edac98639f2ad41 2020-05-10 22:29:46 +0200 Even Rouault $")
// EPSG code range http://gis.stackexchange.com/a/18676/9904
constexpr int MIN_EPSG = 1000;
constexpr int MAX_EPSG = 32768;
/************************************************************************/
/* OGRSXFDataSource() */
/************************************************************************/
OGRSXFDataSource::OGRSXFDataSource() :
papoLayers(nullptr),
nLayers(0),
fpSXF(nullptr),
hIOMutex(nullptr)
{
oSXFPassport.stMapDescription.pSpatRef = nullptr;
}
/************************************************************************/
/* ~OGRSXFDataSource() */
/************************************************************************/
OGRSXFDataSource::~OGRSXFDataSource()
{
for( size_t i = 0; i < nLayers; i++ )
delete papoLayers[i];
CPLFree( papoLayers );
if (nullptr != oSXFPassport.stMapDescription.pSpatRef)
{
oSXFPassport.stMapDescription.pSpatRef->Release();
}
CloseFile();
if (hIOMutex != nullptr)
{
CPLDestroyMutex(hIOMutex);
hIOMutex = nullptr;
}
}
/************************************************************************/
/* CloseFile() */
/************************************************************************/
void OGRSXFDataSource::CloseFile()
{
if (nullptr != fpSXF)
{
VSIFCloseL( fpSXF );
fpSXF = nullptr;
}
}
/************************************************************************/
/* TestCapability() */
/************************************************************************/
int OGRSXFDataSource::TestCapability( CPL_UNUSED const char * pszCap )
{
return FALSE;
}
/************************************************************************/
/* GetLayer() */
/************************************************************************/
OGRLayer *OGRSXFDataSource::GetLayer( int iLayer )
{
if( iLayer < 0 || iLayer >= (int)nLayers )
return nullptr;
else
return papoLayers[iLayer];
}
/************************************************************************/
/* Open() */
/************************************************************************/
int OGRSXFDataSource::Open(const char * pszFilename, bool bUpdateIn,
const char* const* papszOpenOpts)
{
if( bUpdateIn )
{
return FALSE;
}
pszName = pszFilename;
fpSXF = VSIFOpenL(pszName, "rb");
if ( fpSXF == nullptr )
{
CPLError(CE_Warning, CPLE_OpenFailed, "SXF open file %s failed", pszFilename);
return FALSE;
}
//read header
const int nFileHeaderSize = sizeof(SXFHeader);
SXFHeader stSXFFileHeader;
const size_t nObjectsRead =
VSIFReadL(&stSXFFileHeader, nFileHeaderSize, 1, fpSXF);
if (nObjectsRead != 1)
{
CPLError(CE_Failure, CPLE_None, "SXF head read failed");
CloseFile();
return FALSE;
}
CPL_LSBPTR32(&(stSXFFileHeader.nHeaderLength));
CPL_LSBPTR32(&(stSXFFileHeader.nCheckSum));
//check version
oSXFPassport.version = 0;
if (stSXFFileHeader.nHeaderLength > 256) //if size == 400 then version >= 4
{
oSXFPassport.version = stSXFFileHeader.nFormatVersion[2];
}
else
{
oSXFPassport.version = stSXFFileHeader.nFormatVersion[1];
}
if ( oSXFPassport.version < 3 )
{
CPLError(CE_Failure, CPLE_NotSupported , "SXF File version not supported");
CloseFile();
return FALSE;
}
// read description
if (ReadSXFDescription(fpSXF, oSXFPassport) != OGRERR_NONE)
{
CPLError(CE_Failure, CPLE_NotSupported, "SXF. Wrong description.");
CloseFile();
return FALSE;
}
//read flags
if (ReadSXFInformationFlags(fpSXF, oSXFPassport) != OGRERR_NONE)
{
CPLError(CE_Failure, CPLE_NotSupported, "SXF. Wrong state of the data.");
CloseFile();
return FALSE;
}
if(oSXFPassport.version == 3 &&
oSXFPassport.informationFlags.bProjectionDataCompliance == false)
{
CPLError( CE_Failure, CPLE_NotSupported,
"SXF. Data does not correspond to the projection." );
CloseFile();
return FALSE;
}
//read spatial data
if (ReadSXFMapDescription(fpSXF, oSXFPassport, papszOpenOpts) != OGRERR_NONE)
{
CPLError(CE_Failure, CPLE_NotSupported, "SXF. Wrong state of the data.");
CloseFile();
return FALSE;
}
if(oSXFPassport.informationFlags.bRealCoordinatesCompliance == false )
{
CPLError( CE_Warning, CPLE_NotSupported,
"SXF. Given material may be rotated in the conditional system of coordinates" );
}
/*---------------- TRY READ THE RSC FILE HEADER -----------------------*/
CPLString soRSCRileName;
const char* pszRSCRileName =
CSLFetchNameValueDef(papszOpenOpts, "SXF_RSC_FILENAME",
CPLGetConfigOption("SXF_RSC_FILENAME", ""));
if (pszRSCRileName != nullptr && CPLCheckForFile((char *)pszRSCRileName, nullptr) == TRUE)
{
soRSCRileName = pszRSCRileName;
}
if(soRSCRileName.empty())
{
pszRSCRileName = CPLResetExtension(pszFilename, "rsc");
if (CPLCheckForFile((char *)pszRSCRileName, nullptr) == TRUE)
{
soRSCRileName = pszRSCRileName;
}
}
if(soRSCRileName.empty())
{
pszRSCRileName = CPLResetExtension(pszFilename, "RSC");
if (CPLCheckForFile((char *)pszRSCRileName, nullptr) == TRUE)
{
soRSCRileName = pszRSCRileName;
}
}
// 1. Create layers from RSC file or create default set of layers from
// gdal_data/default.rsc.
if(soRSCRileName.empty())
{
pszRSCRileName = CPLFindFile( "gdal", "default.rsc" );
if (nullptr != pszRSCRileName)
{
soRSCRileName = pszRSCRileName;
}
else
{
CPLDebug( "OGRSXFDataSource", "Default RSC file not found" );
}
}
if (soRSCRileName.empty())
{
CPLError(CE_Warning, CPLE_None, "RSC file for %s not exist", pszFilename);
}
else
{
VSILFILE* fpRSC = VSIFOpenL(soRSCRileName, "rb");
if (fpRSC == nullptr)
{
CPLError(CE_Warning, CPLE_OpenFailed, "RSC file %s open failed",
soRSCRileName.c_str());
}
else
{
CPLDebug( "OGRSXFDataSource", "RSC Filename: %s",
soRSCRileName.c_str() );
CreateLayers(fpRSC, papszOpenOpts);
VSIFCloseL(fpRSC);
}
}
if (nLayers == 0)//create default set of layers
{
CreateLayers();
}
FillLayers();
return TRUE;
}
OGRErr OGRSXFDataSource::ReadSXFDescription(VSILFILE* fpSXFIn, SXFPassport& passport)
{
// int nObjectsRead = 0;
if (passport.version == 3)
{
//78
GByte buff[62];
/* nObjectsRead = */ VSIFReadL(&buff, 62, 1, fpSXFIn);
char date[3] = { 0 };
//read year
memcpy(date, buff, 2);
passport.dtCrateDate.nYear = static_cast<GUInt16>(atoi(date));
if (passport.dtCrateDate.nYear < 50)
passport.dtCrateDate.nYear += 2000;
else
passport.dtCrateDate.nYear += 1900;
memcpy(date, buff + 2, 2);
passport.dtCrateDate.nMonth = static_cast<GUInt16>(atoi(date));
memcpy(date, buff + 4, 2);
passport.dtCrateDate.nDay = static_cast<GUInt16>(atoi(date));
char szName[26] = { 0 };
memcpy(szName, buff + 8, 24);
szName[ sizeof(szName) - 1 ] = '\0';
char* pszRecoded = CPLRecode(szName, "CP1251", CPL_ENC_UTF8);// szName + 2
passport.sMapSheet = pszRecoded; //TODO: check the encoding in SXF created in Linux
CPLFree(pszRecoded);
memcpy(&passport.nScale, buff + 32, 4);
CPL_LSBPTR32(&passport.nScale);
memcpy(szName, buff + 36, 26);
szName[ sizeof(szName) - 1 ] = '\0';
pszRecoded = CPLRecode(szName, "CP866", CPL_ENC_UTF8);
passport.sMapSheetName = pszRecoded; //TODO: check the encoding in SXF created in Linux
CPLFree(pszRecoded);
}
else if (passport.version == 4)
{
//96
GByte buff[80];
/* nObjectsRead = */ VSIFReadL(&buff, 80, 1, fpSXFIn);
char date[5] = { 0 };
//read year
memcpy(date, buff, 4);
passport.dtCrateDate.nYear = static_cast<GUInt16>(atoi(date));
memcpy(date, buff + 4, 2);
memset(date+2, 0, 3);
passport.dtCrateDate.nMonth = static_cast<GUInt16>(atoi(date));
memcpy(date, buff + 6, 2);
passport.dtCrateDate.nDay = static_cast<GUInt16>(atoi(date));
char szName[32] = { 0 };
memcpy(szName, buff + 12, 32);
szName[ sizeof(szName) - 1 ] = '\0';
char* pszRecoded = CPLRecode(szName, "CP1251", CPL_ENC_UTF8); //szName + 2
passport.sMapSheet = pszRecoded; //TODO: check the encoding in SXF created in Linux
CPLFree(pszRecoded);
memcpy(&passport.nScale, buff + 44, 4);
CPL_LSBPTR32(&passport.nScale);
memcpy(szName, buff + 48, 32);
szName[ sizeof(szName) - 1 ] = '\0';
pszRecoded = CPLRecode(szName, "CP1251", CPL_ENC_UTF8);
passport.sMapSheetName = pszRecoded; //TODO: check the encoding in SXF created in Linux
CPLFree(pszRecoded);
}
SetMetadataItem("SHEET", passport.sMapSheet);
SetMetadataItem("SHEET_NAME", passport.sMapSheetName);
SetMetadataItem("SHEET_CREATE_DATE", CPLSPrintf( "%.2u-%.2u-%.4u",
passport.dtCrateDate.nDay,
passport.dtCrateDate.nMonth,
passport.dtCrateDate.nYear ));
SetMetadataItem("SXF_VERSION", CPLSPrintf("%u", passport.version));
SetMetadataItem("SCALE", CPLSPrintf("1 : %u", passport.nScale));
return OGRERR_NONE;
}
OGRErr OGRSXFDataSource::ReadSXFInformationFlags(VSILFILE* fpSXFIn, SXFPassport& passport)
{
// int nObjectsRead = 0;
GByte val[4];
/* nObjectsRead = */ VSIFReadL(&val, 4, 1, fpSXFIn);
if (!(CHECK_BIT(val[0], 0) && CHECK_BIT(val[0], 1))) // xxxxxx11
{
return OGRERR_UNSUPPORTED_OPERATION;
}
if (CHECK_BIT(val[0], 2)) // xxxxx0xx or xxxxx1xx
{
passport.informationFlags.bProjectionDataCompliance = true;
}
else
{
passport.informationFlags.bProjectionDataCompliance = false;
}
if (CHECK_BIT(val[0], 4))
{
passport.informationFlags.bRealCoordinatesCompliance = true;
}
else
{
passport.informationFlags.bRealCoordinatesCompliance = false;
}
if (CHECK_BIT(val[0], 6))
{
passport.informationFlags.stCodingType = SXF_SEM_TXT;
}
else
{
if (CHECK_BIT(val[0], 5))
{
passport.informationFlags.stCodingType = SXF_SEM_HEX;
}
else
{
passport.informationFlags.stCodingType = SXF_SEM_DEC;
}
}
if (CHECK_BIT(val[0], 7))
{
passport.informationFlags.stGenType = SXF_GT_LARGE_SCALE;
}
else
{
passport.informationFlags.stGenType = SXF_GT_SMALL_SCALE;
}
//version specific
if (passport.version == 3)
{
//degrees are ints * 100 000 000
//meters are ints / 10
passport.informationFlags.stEnc = SXF_ENC_DOS;
passport.informationFlags.stCoordAcc = SXF_COORD_ACC_DM;
passport.informationFlags.bSort = false;
}
else if (passport.version == 4)
{
passport.informationFlags.stEnc = (SXFTextEncoding)val[1];
passport.informationFlags.stCoordAcc = (SXFCoordinatesAccuracy)val[2];
if (CHECK_BIT(val[3], 0))
{
passport.informationFlags.bSort = true;
}
else
{
passport.informationFlags.bSort = false;
}
}
return OGRERR_NONE;
}
void OGRSXFDataSource::SetVertCS(const long iVCS, SXFPassport& passport,
const char* const* papszOpenOpts)
{
const char* pszSetVertCS =
CSLFetchNameValueDef(papszOpenOpts,
"SXF_SET_VERTCS",
CPLGetConfigOption("SXF_SET_VERTCS", "NO"));
if (!CPLTestBool(pszSetVertCS))
return;
passport.stMapDescription.pSpatRef->importVertCSFromPanorama(static_cast<int>(iVCS));
}
OGRErr OGRSXFDataSource::ReadSXFMapDescription(VSILFILE* fpSXFIn, SXFPassport& passport,
const char* const* papszOpenOpts)
{
// int nObjectsRead = 0;
passport.stMapDescription.Env.MaxX = -100000000;
passport.stMapDescription.Env.MinX = 100000000;
passport.stMapDescription.Env.MaxY = -100000000;
passport.stMapDescription.Env.MinY = 100000000;
bool bIsX = true;// passport.informationFlags.bRealCoordinatesCompliance; //if real coordinates we need to swap x & y
//version specific
if (passport.version == 3)
{
short nNoObjClass, nNoSemClass;
/* nObjectsRead = */ VSIFReadL(&nNoObjClass, 2, 1, fpSXFIn);
/* nObjectsRead = */ VSIFReadL(&nNoSemClass, 2, 1, fpSXFIn);
GByte baMask[8];
/* nObjectsRead = */ VSIFReadL(&baMask, 8, 1, fpSXFIn);
int nCorners[8];
//get projected corner coords
/* nObjectsRead = */ VSIFReadL(&nCorners, 32, 1, fpSXFIn);
for( int i = 0; i < 8; i++ )
{
CPL_LSBPTR32(&nCorners[i]);
passport.stMapDescription.stProjCoords[i] = double(nCorners[i]) / 10.0;
if (bIsX) //X
{
if (passport.stMapDescription.Env.MaxY < passport.stMapDescription.stProjCoords[i])
passport.stMapDescription.Env.MaxY = passport.stMapDescription.stProjCoords[i];
if (passport.stMapDescription.Env.MinY > passport.stMapDescription.stProjCoords[i])
passport.stMapDescription.Env.MinY = passport.stMapDescription.stProjCoords[i];
}
else
{
if (passport.stMapDescription.Env.MaxX < passport.stMapDescription.stProjCoords[i])
passport.stMapDescription.Env.MaxX = passport.stMapDescription.stProjCoords[i];
if (passport.stMapDescription.Env.MinX > passport.stMapDescription.stProjCoords[i])
passport.stMapDescription.Env.MinX = passport.stMapDescription.stProjCoords[i];
}
bIsX = !bIsX;
}
//get geographic corner coords
/* nObjectsRead = */ VSIFReadL(&nCorners, 32, 1, fpSXFIn);
for( int i = 0; i < 8; i++ )
{
CPL_LSBPTR32(&nCorners[i]);
passport.stMapDescription.stGeoCoords[i] = double(nCorners[i]) * 0.00000057295779513082; //from radians to degree * 100 000 000
}
}
else if (passport.version == 4)
{
int nEPSG = 0;
/* nObjectsRead = */ VSIFReadL(&nEPSG, 4, 1, fpSXFIn);
CPL_LSBPTR32(&nEPSG);
if (nEPSG >= MIN_EPSG && nEPSG <= MAX_EPSG) //TODO: check epsg valid range
{
passport.stMapDescription.pSpatRef = new OGRSpatialReference();
passport.stMapDescription.pSpatRef->importFromEPSG(nEPSG);
}
double dfCorners[8];
/* nObjectsRead = */ VSIFReadL(&dfCorners, 64, 1, fpSXFIn);
for( int i = 0; i < 8; i++ )
{
CPL_LSBPTR64(&dfCorners[i]);
passport.stMapDescription.stProjCoords[i] = dfCorners[i];
if (bIsX) //X
{
if (passport.stMapDescription.Env.MaxY < passport.stMapDescription.stProjCoords[i])
passport.stMapDescription.Env.MaxY = passport.stMapDescription.stProjCoords[i];
if (passport.stMapDescription.Env.MinY > passport.stMapDescription.stProjCoords[i])
passport.stMapDescription.Env.MinY = passport.stMapDescription.stProjCoords[i];
}
else
{
if (passport.stMapDescription.Env.MaxX < passport.stMapDescription.stProjCoords[i])
passport.stMapDescription.Env.MaxX = passport.stMapDescription.stProjCoords[i];
if (passport.stMapDescription.Env.MinX > passport.stMapDescription.stProjCoords[i])
passport.stMapDescription.Env.MinX = passport.stMapDescription.stProjCoords[i];
}
bIsX = !bIsX;
}
//get geographic corner coords
/* nObjectsRead = */ VSIFReadL(&dfCorners, 64, 1, fpSXFIn);
for( int i = 0; i < 8; i++ )
{
CPL_LSBPTR64(&dfCorners[i]);
passport.stMapDescription.stGeoCoords[i] = dfCorners[i] * TO_DEGREES; // to degree
}
}
if (nullptr != passport.stMapDescription.pSpatRef)
{
return OGRERR_NONE;
}
GByte anData[8] = { 0 };
/* nObjectsRead = */ VSIFReadL(&anData, 8, 1, fpSXFIn);
long iEllips = anData[0];
long iVCS = anData[1];
long iProjSys = anData[2];
/* long iDatum = anData[3]; Unused. */
double dfProjScale = 1;
double adfPrjParams[8] = { 0 };
if (passport.version == 3)
{
switch (anData[4])
{
case 1:
passport.stMapDescription.eUnitInPlan = SXF_COORD_MU_DECIMETRE;
break;
case 2:
passport.stMapDescription.eUnitInPlan = SXF_COORD_MU_CENTIMETRE;
break;
case 3:
passport.stMapDescription.eUnitInPlan = SXF_COORD_MU_MILLIMETRE;
break;
case 130:
passport.stMapDescription.eUnitInPlan = SXF_COORD_MU_RADIAN;
break;
case 129:
passport.stMapDescription.eUnitInPlan = SXF_COORD_MU_DEGREE;
break;
default:
passport.stMapDescription.eUnitInPlan = SXF_COORD_MU_METRE;
break;
}
VSIFSeekL(fpSXFIn, 212, SEEK_SET);
struct _buff{
GUInt32 nRes;
GInt16 anFrame[8];
// cppcheck-suppress unusedStructMember
GUInt32 nFrameCode;
} buff;
/* nObjectsRead = */ VSIFReadL(&buff, 20, 1, fpSXFIn);
CPL_LSBPTR32(&buff.nRes);
CPL_LSBPTR32(&buff.nFrameCode);
passport.stMapDescription.nResolution = buff.nRes; //resolution
for( int i = 0; i < 8; i++ )
{
CPL_LSBPTR16(&(buff.anFrame[i]));
passport.stMapDescription.stFrameCoords[i] = buff.anFrame[i];
}
int anParams[5];
/* nObjectsRead = */ VSIFReadL(&anParams, 20, 1, fpSXFIn);
for(int i = 0; i < 5; i++)
{
CPL_LSBPTR32(&anParams[i]);
}
if (anParams[0] != -1)
dfProjScale = double(anParams[0]) / 100000000.0;
if (anParams[2] != -1)
passport.stMapDescription.dfXOr = double(anParams[2]) / 100000000.0 * TO_DEGREES;
else
passport.stMapDescription.dfXOr = 0;
if (anParams[3] != -1)
passport.stMapDescription.dfYOr = double(anParams[2]) / 100000000.0 * TO_DEGREES;
else
passport.stMapDescription.dfYOr = 0;
passport.stMapDescription.dfFalseNorthing = 0;
passport.stMapDescription.dfFalseEasting = 0;
//adfPrjParams[0] = double(anParams[0]) / 100000000.0; // to radians
//adfPrjParams[1] = double(anParams[1]) / 100000000.0;
//adfPrjParams[2] = double(anParams[2]) / 100000000.0;
//adfPrjParams[3] = double(anParams[3]) / 100000000.0;
adfPrjParams[4] = dfProjScale;//?
//adfPrjParams[5] = 0;//?
//adfPrjParams[6] = 0;//?
//adfPrjParams[7] = 0;// importFromPanorama calc it by itself
}
else if (passport.version == 4)
{
switch (anData[4])
{
case 64:
passport.stMapDescription.eUnitInPlan = SXF_COORD_MU_RADIAN;
break;
case 65:
passport.stMapDescription.eUnitInPlan = SXF_COORD_MU_DEGREE;
break;
default:
passport.stMapDescription.eUnitInPlan = SXF_COORD_MU_METRE;
break;
}
VSIFSeekL(fpSXFIn, 312, SEEK_SET);
GUInt32 buff[10];
/* nObjectsRead = */ VSIFReadL(&buff, 40, 1, fpSXFIn);
for(int i = 0; i < 10; i++)
{
CPL_LSBPTR32(&buff[i]);
}
passport.stMapDescription.nResolution = buff[0]; //resolution
for( int i = 0; i < 8; i++ )
passport.stMapDescription.stFrameCoords[i] = buff[1 + i];
double adfParams[6] = {};
/* nObjectsRead = */ VSIFReadL(&adfParams, 48, 1, fpSXFIn);
for(int i = 0; i < 6; i++)
{
CPL_LSBPTR64(&adfParams[i]);
}
if (adfParams[1] != -1)
dfProjScale = adfParams[1];
passport.stMapDescription.dfXOr = adfParams[2] * TO_DEGREES;
passport.stMapDescription.dfYOr = adfParams[3] * TO_DEGREES;
passport.stMapDescription.dfFalseNorthing = adfParams[4];
passport.stMapDescription.dfFalseEasting = adfParams[5];
//adfPrjParams[0] = adfParams[0]; // to radians
//adfPrjParams[1] = adfParams[1];
//adfPrjParams[2] = adfParams[2];
//adfPrjParams[3] = adfParams[3];
adfPrjParams[4] = dfProjScale;//?
//adfPrjParams[5] = adfParams[4];
//adfPrjParams[6] = adfParams[5];
//adfPrjParams[7] = 0;// importFromPanorama calc it by itself
}
passport.stMapDescription.dfScale = passport.nScale;
double dfCoeff = double(passport.stMapDescription.dfScale) / passport.stMapDescription.nResolution;
passport.stMapDescription.bIsRealCoordinates = passport.informationFlags.bRealCoordinatesCompliance;
passport.stMapDescription.stCoordAcc = passport.informationFlags.stCoordAcc;
if (!passport.stMapDescription.bIsRealCoordinates)
{
if (passport.stMapDescription.stFrameCoords[0] == 0 && passport.stMapDescription.stFrameCoords[1] == 0 && passport.stMapDescription.stFrameCoords[2] == 0 && passport.stMapDescription.stFrameCoords[3] == 0 && passport.stMapDescription.stFrameCoords[4] == 0 && passport.stMapDescription.stFrameCoords[5] == 0 && passport.stMapDescription.stFrameCoords[6] == 0 && passport.stMapDescription.stFrameCoords[7] == 0)
{
passport.stMapDescription.bIsRealCoordinates = true;
}
else
{
//origin
passport.stMapDescription.dfXOr = passport.stMapDescription.stProjCoords[1] - passport.stMapDescription.stFrameCoords[1] * dfCoeff;
passport.stMapDescription.dfYOr = passport.stMapDescription.stProjCoords[0] - passport.stMapDescription.stFrameCoords[0] * dfCoeff;
}
}
//normalize some coordintatessystems
if ((iEllips == 1 || iEllips == 0 ) && iProjSys == 1) // Pulkovo 1942 / Gauss-Kruger
{
double dfCenterLongEnv = passport.stMapDescription.stGeoCoords[1] + fabs(passport.stMapDescription.stGeoCoords[5] - passport.stMapDescription.stGeoCoords[1]) / 2;
int nZoneEnv = (int)( (dfCenterLongEnv + 3.0) / 6.0 + 0.5 );
if (nZoneEnv > 1 && nZoneEnv < 33)
{
int nEPSG = 28400 + nZoneEnv;
passport.stMapDescription.pSpatRef = new OGRSpatialReference();
passport.stMapDescription.pSpatRef->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
OGRErr eErr = passport.stMapDescription.pSpatRef->importFromEPSG(nEPSG);
SetVertCS(iVCS, passport, papszOpenOpts);
return eErr;
}
else
{
adfPrjParams[7] = nZoneEnv;
if (adfPrjParams[5] == 0)//False Easting
{
if (passport.stMapDescription.Env.MaxX < 500000)
adfPrjParams[5] = 500000;
else
adfPrjParams[5] = nZoneEnv * 1000000 + 500000;
}
}
}
else if (iEllips == 9 && iProjSys == 17) // WGS84 / UTM
{
double dfCenterLongEnv = passport.stMapDescription.stGeoCoords[1] + fabs(passport.stMapDescription.stGeoCoords[5] - passport.stMapDescription.stGeoCoords[1]) / 2;
int nZoneEnv = (int)(30 + (dfCenterLongEnv + 3.0) / 6.0 + 0.5);
bool bNorth = passport.stMapDescription.stGeoCoords[6] + (passport.stMapDescription.stGeoCoords[2] - passport.stMapDescription.stGeoCoords[6]) / 2 < 0;
int nEPSG = 0;
if( bNorth )
{
nEPSG = 32600 + nZoneEnv;
}
else
{
nEPSG = 32700 + nZoneEnv;
}
passport.stMapDescription.pSpatRef = new OGRSpatialReference();
passport.stMapDescription.pSpatRef->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
OGRErr eErr = passport.stMapDescription.pSpatRef->importFromEPSG(nEPSG);
SetVertCS(iVCS, passport, papszOpenOpts);
return eErr;
}
else if (iEllips == 45 && iProjSys == 35) //Mercator 3857 on sphere wgs84
{
passport.stMapDescription.pSpatRef = new OGRSpatialReference("PROJCS[\"WGS 84 / Pseudo-Mercator\",GEOGCS[\"WGS 84\",DATUM[\"WGS_1984\",SPHEROID[\"WGS 84\",6378137,298.257223563,AUTHORITY[\"EPSG\",\"7030\"]],AUTHORITY[\"EPSG\",\"6326\"]],PRIMEM[\"Greenwich\",0,AUTHORITY[\"EPSG\",\"8901\"]],UNIT[\"degree\",0.0174532925199433,AUTHORITY[\"EPSG\",\"9122\"]],AUTHORITY[\"EPSG\",\"4326\"]],PROJECTION[\"Mercator_1SP\"],PARAMETER[\"central_meridian\",0],PARAMETER[\"scale_factor\",1],PARAMETER[\"false_easting\",0],PARAMETER[\"false_northing\",0],UNIT[\"metre\",1,AUTHORITY[\"EPSG\",\"9001\"]],AXIS[\"X\",EAST],AXIS[\"Y\",NORTH],EXTENSION[\"PROJ4\",\"+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs\"],AUTHORITY[\"EPSG\",\"3857\"]]");
passport.stMapDescription.pSpatRef->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
OGRErr eErr = OGRERR_NONE; //passport.stMapDescription.pSpatRef->importFromEPSG(3857);
SetVertCS(iVCS, passport, papszOpenOpts);
return eErr;
}
else if (iEllips == 9 && iProjSys == 35) //Mercator 3395 on ellips wgs84
{
passport.stMapDescription.pSpatRef = new OGRSpatialReference();
passport.stMapDescription.pSpatRef->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
OGRErr eErr = passport.stMapDescription.pSpatRef->importFromEPSG(3395);
SetVertCS(iVCS, passport, papszOpenOpts);
return eErr;
}
else if (iEllips == 9 && iProjSys == 34) //Miller 54003 on sphere wgs84
{
passport.stMapDescription.pSpatRef = new OGRSpatialReference("PROJCS[\"World_Miller_Cylindrical\",GEOGCS[\"GCS_GLOBE\", DATUM[\"GLOBE\", SPHEROID[\"GLOBE\", 6367444.6571, 0.0]],PRIMEM[\"Greenwich\",0],UNIT[\"Degree\",0.017453292519943295]],PROJECTION[\"Miller_Cylindrical\"],PARAMETER[\"False_Easting\",0],PARAMETER[\"False_Northing\",0],PARAMETER[\"Central_Meridian\",0],UNIT[\"Meter\",1],AUTHORITY[\"EPSG\",\"54003\"]]");
passport.stMapDescription.pSpatRef->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
OGRErr eErr = OGRERR_NONE; //passport.stMapDescription.pSpatRef->importFromEPSG(3395);
//OGRErr eErr = passport.stMapDescription.pSpatRef->importFromEPSG(54003);
SetVertCS(iVCS, passport, papszOpenOpts);
return eErr;
}
else if (iEllips == 9 && iProjSys == 33 &&
passport.stMapDescription.eUnitInPlan == SXF_COORD_MU_DEGREE)
{
passport.stMapDescription.pSpatRef = new OGRSpatialReference(SRS_WKT_WGS84_LAT_LONG);
passport.stMapDescription.pSpatRef->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
OGRErr eErr = OGRERR_NONE;
SetVertCS(iVCS, passport, papszOpenOpts);
return eErr;
}
//TODO: Need to normalize more SRS:
//PAN_PROJ_WAG1
//PAN_PROJ_MERCAT
//PAN_PROJ_PS
//PAN_PROJ_POLYC
//PAN_PROJ_EC
//PAN_PROJ_LCC
//PAN_PROJ_STEREO
//PAN_PROJ_AE
//PAN_PROJ_GNOMON
//PAN_PROJ_MOLL
//PAN_PROJ_LAEA
//PAN_PROJ_EQC
//PAN_PROJ_CEA
//PAN_PROJ_IMWP
//
passport.stMapDescription.pSpatRef = new OGRSpatialReference();
passport.stMapDescription.pSpatRef->SetAxisMappingStrategy(OAMS_TRADITIONAL_GIS_ORDER);
OGRErr eErr = passport.stMapDescription.pSpatRef->importFromPanorama(anData[2], anData[3], anData[0], adfPrjParams);
SetVertCS(iVCS, passport, papszOpenOpts);
return eErr;
}
void OGRSXFDataSource::FillLayers()
{
CPLDebug("SXF","Create layers");
//2. Read all records (only classify code and offset) and add this to correspondence layer
int nObjectsRead = 0;
vsi_l_offset nOffset = 0;
//get record count
GUInt32 nRecordCountMax = 0;
if (oSXFPassport.version == 3)
{
VSIFSeekL(fpSXF, 288, SEEK_SET);
nObjectsRead = static_cast<int>(VSIFReadL(&nRecordCountMax, 4, 1, fpSXF));
nOffset = 300;
CPL_LSBPTR32(&nRecordCountMax);
}
else if (oSXFPassport.version == 4)
{
VSIFSeekL(fpSXF, 440, SEEK_SET);
nObjectsRead = static_cast<int>(VSIFReadL(&nRecordCountMax, 4, 1, fpSXF));
nOffset = 452;
CPL_LSBPTR32(&nRecordCountMax);
}
/* else nOffset and nObjectsRead will be 0 */
if (nObjectsRead != 1)
{
CPLError(CE_Failure, CPLE_FileIO, "Get record count failed");
return;
}
VSIFSeekL(fpSXF, nOffset, SEEK_SET);
for( GUInt32 nFID = 0; nFID < nRecordCountMax; nFID++ )
{
GInt32 buff[6];
nObjectsRead = static_cast<int>(VSIFReadL(&buff, 24, 1, fpSXF));
for( int i = 0; i < 6; i++ )
{
CPL_LSBPTR32(&buff[i]);
}
if (nObjectsRead != 1 || buff[0] != IDSXFOBJ)
{
CPLError(CE_Failure, CPLE_FileIO, "Read record %d failed", nFID);
return;
}
bool bHasSemantic = CHECK_BIT(buff[5], 9);
if (bHasSemantic) //check has attributes
{
//we have already 24 byte read
vsi_l_offset nOffsetSemantic = 8 + buff[2];
VSIFSeekL(fpSXF, nOffsetSemantic, SEEK_CUR);
}
int nSemanticSize = buff[1] - 32 - buff[2];
if( nSemanticSize < 0 )
{
CPLError(CE_Failure, CPLE_AppDefined, "Invalid value");
break;
}
for( size_t i = 0; i < nLayers; i++ )
{
OGRSXFLayer* pOGRSXFLayer = (OGRSXFLayer*)papoLayers[i];
if (pOGRSXFLayer && pOGRSXFLayer->AddRecord(nFID, buff[3], nOffset, bHasSemantic, nSemanticSize) == TRUE)
{
break;
}
}
nOffset += buff[1];
VSIFSeekL(fpSXF, nOffset, SEEK_SET);
}
//3. delete empty layers
for( size_t i = 0; i < nLayers; i++ )
{
OGRSXFLayer* pOGRSXFLayer = (OGRSXFLayer*)papoLayers[i];
if (pOGRSXFLayer && pOGRSXFLayer->GetFeatureCount() == 0)
{
delete pOGRSXFLayer;
size_t nDeletedLayerIndex = i;
while (nDeletedLayerIndex < nLayers - 1)
{
papoLayers[nDeletedLayerIndex] = papoLayers[nDeletedLayerIndex + 1];
nDeletedLayerIndex++;
}
nLayers--;
i--;
}
else if (pOGRSXFLayer)
pOGRSXFLayer->ResetReading();
}
}
OGRSXFLayer* OGRSXFDataSource::GetLayerById(GByte nID)
{
for (size_t i = 0; i < nLayers; i++)
{
OGRSXFLayer* pOGRSXFLayer = (OGRSXFLayer*)papoLayers[i];
if (pOGRSXFLayer && pOGRSXFLayer->GetId() == nID)
{
return pOGRSXFLayer;
}
}
return nullptr;
}
void OGRSXFDataSource::CreateLayers()
{
//default layers set
papoLayers = (OGRLayer**)CPLRealloc(papoLayers, sizeof(OGRLayer*)* (nLayers + 1));
OGRSXFLayer* pLayer = new OGRSXFLayer(fpSXF, &hIOMutex, 0, CPLString("SYSTEM"), oSXFPassport.version, oSXFPassport.stMapDescription);
papoLayers[nLayers] = pLayer;
nLayers++;
//default codes
for (unsigned int i = 1000000001; i < 1000000015; i++)
{
pLayer->AddClassifyCode(i);
}
pLayer->AddClassifyCode(91000000);
papoLayers = (OGRLayer**)CPLRealloc(papoLayers, sizeof(OGRLayer*)* (nLayers + 1));
papoLayers[nLayers] = new OGRSXFLayer(fpSXF, &hIOMutex, 255, CPLString("Not_Classified"), oSXFPassport.version, oSXFPassport.stMapDescription);
nLayers++;
}
void OGRSXFDataSource::CreateLayers(VSILFILE* fpRSC, const char* const* papszOpenOpts)
{
RSCHeader stRSCFileHeader;
int nObjectsRead = static_cast<int>(VSIFReadL(&stRSCFileHeader, sizeof(stRSCFileHeader), 1, fpRSC));
if (nObjectsRead != 1)
{
CPLError(CE_Warning, CPLE_None, "RSC head read failed");
return;
}
CPL_LSBPTR32(&(stRSCFileHeader.nFileLength));
CPL_LSBPTR32(&(stRSCFileHeader.nVersion));
CPL_LSBPTR32(&(stRSCFileHeader.nEncoding));
CPL_LSBPTR32(&(stRSCFileHeader.nFileState));
CPL_LSBPTR32(&(stRSCFileHeader.nFileModState));
CPL_LSBPTR32(&(stRSCFileHeader.nLang));
CPL_LSBPTR32(&(stRSCFileHeader.nNextID));
CPL_LSBPTR32(&(stRSCFileHeader.nScale));
#define SWAP_SECTION(x) \
CPL_LSBPTR32(&(x.nOffset)); \
CPL_LSBPTR32(&(x.nLength)); \
CPL_LSBPTR32(&(x.nRecordCount));
SWAP_SECTION(stRSCFileHeader.Objects);
SWAP_SECTION(stRSCFileHeader.Semantic);
SWAP_SECTION(stRSCFileHeader.ClassifySemantic);
SWAP_SECTION(stRSCFileHeader.Defaults);
SWAP_SECTION(stRSCFileHeader.Semantics);
SWAP_SECTION(stRSCFileHeader.Layers);
SWAP_SECTION(stRSCFileHeader.Limits);
SWAP_SECTION(stRSCFileHeader.Parameters);
SWAP_SECTION(stRSCFileHeader.Print);
SWAP_SECTION(stRSCFileHeader.Palettes);
SWAP_SECTION(stRSCFileHeader.Fonts);
SWAP_SECTION(stRSCFileHeader.Libs);
SWAP_SECTION(stRSCFileHeader.ImageParams);
SWAP_SECTION(stRSCFileHeader.Tables);
CPL_LSBPTR32(&(stRSCFileHeader.nFontEnc));
CPL_LSBPTR32(&(stRSCFileHeader.nColorsInPalette));
GByte szLayersID[4];
struct _layer{
GUInt32 nLength;
char szName[32];
char szShortName[16];
GByte nNo;
// cppcheck-suppress unusedStructMember
GByte nPos;
// cppcheck-suppress unusedStructMember
GUInt16 nSemanticCount;
};
VSIFSeekL(fpRSC, stRSCFileHeader.Layers.nOffset - sizeof(szLayersID), SEEK_SET);
VSIFReadL(&szLayersID, sizeof(szLayersID), 1, fpRSC);
vsi_l_offset nOffset = stRSCFileHeader.Layers.nOffset;
_layer LAYER;
for( GUInt32 i = 0; i < stRSCFileHeader.Layers.nRecordCount; ++i )
{
VSIFReadL(&LAYER, sizeof(LAYER), 1, fpRSC);
CPL_LSBPTR32(&(LAYER.nLength));
CPL_LSBPTR16(&(LAYER.nSemanticCount));
papoLayers = (OGRLayer**)CPLRealloc(papoLayers, sizeof(OGRLayer*)* (nLayers + 1));
bool bLayerFullName = CPLTestBool(
CSLFetchNameValueDef(papszOpenOpts,
"SXF_LAYER_FULLNAME",
CPLGetConfigOption("SXF_LAYER_FULLNAME", "NO")));
char* pszRecoded = nullptr;
if (bLayerFullName)
{
if(LAYER.szName[0] == 0)
pszRecoded = CPLStrdup("Unnamed");
else if (stRSCFileHeader.nFontEnc == 125)
pszRecoded = CPLRecode(LAYER.szName, "KOI8-R", CPL_ENC_UTF8);
else if (stRSCFileHeader.nFontEnc == 126)
pszRecoded = CPLRecode(LAYER.szName, "CP1251", CPL_ENC_UTF8);
else
pszRecoded = CPLStrdup(LAYER.szName);
papoLayers[nLayers] = new OGRSXFLayer(fpSXF, &hIOMutex, LAYER.nNo, CPLString(pszRecoded), oSXFPassport.version, oSXFPassport.stMapDescription);
}
else
{
if(LAYER.szShortName[0] == 0)
pszRecoded = CPLStrdup("Unnamed");
else if (stRSCFileHeader.nFontEnc == 125)
pszRecoded = CPLRecode(LAYER.szShortName, "KOI8-R", CPL_ENC_UTF8);
else if (stRSCFileHeader.nFontEnc == 126)
pszRecoded = CPLRecode(LAYER.szShortName, "CP1251", CPL_ENC_UTF8);
else
pszRecoded = CPLStrdup(LAYER.szShortName);
papoLayers[nLayers] = new OGRSXFLayer(fpSXF, &hIOMutex, LAYER.nNo, CPLString(pszRecoded), oSXFPassport.version, oSXFPassport.stMapDescription);
}
CPLFree(pszRecoded);
nLayers++;
nOffset += LAYER.nLength;
VSIFSeekL(fpRSC, nOffset, SEEK_SET);
}
papoLayers = (OGRLayer**)CPLRealloc(papoLayers, sizeof(OGRLayer*)* (nLayers + 1));
papoLayers[nLayers] = new OGRSXFLayer(fpSXF, &hIOMutex, 255, CPLString("Not_Classified"), oSXFPassport.version, oSXFPassport.stMapDescription);
nLayers++;
char szObjectsID[4];
struct _object{
unsigned nLength;
unsigned nClassifyCode;
// cppcheck-suppress unusedStructMember
unsigned nObjectNumber;
// cppcheck-suppress unusedStructMember
unsigned nObjectCode;
char szShortName[32];
char szName[32];
// cppcheck-suppress unusedStructMember
char szGeomType;
char szLayernNo;
// cppcheck-suppress unusedStructMember
char szUnimportantSeg[14];
};
VSIFSeekL(fpRSC, stRSCFileHeader.Objects.nOffset - sizeof(szObjectsID), SEEK_SET);
VSIFReadL(&szObjectsID, sizeof(szObjectsID), 1, fpRSC);
nOffset = stRSCFileHeader.Objects.nOffset;
_object OBJECT;
for( GUInt32 i = 0; i < stRSCFileHeader.Objects.nRecordCount; ++i )
{
VSIFReadL(&OBJECT, sizeof(_object), 1, fpRSC);
CPL_LSBPTR32(&(OBJECT.nLength));
CPL_LSBPTR32(&(OBJECT.nClassifyCode));
CPL_LSBPTR32(&(OBJECT.nObjectNumber));
CPL_LSBPTR32(&(OBJECT.nObjectCode));
OGRSXFLayer* pLayer = GetLayerById(OBJECT.szLayernNo);
if (nullptr != pLayer)
{
char* pszRecoded = nullptr;
if(OBJECT.szName[0] == 0)
pszRecoded = CPLStrdup("Unnamed");
else if (stRSCFileHeader.nFontEnc == 125)
pszRecoded = CPLRecode(OBJECT.szName, "KOI8-R", CPL_ENC_UTF8);
else if (stRSCFileHeader.nFontEnc == 126)
pszRecoded = CPLRecode(OBJECT.szName, "CP1251", CPL_ENC_UTF8);
else
pszRecoded = CPLStrdup(OBJECT.szName); //already in CPL_ENC_UTF8
pLayer->AddClassifyCode(OBJECT.nClassifyCode, pszRecoded);
//printf("%d;%s\n", OBJECT.nClassifyCode, OBJECT.szName);
CPLFree(pszRecoded);
}
nOffset += OBJECT.nLength;
VSIFSeekL(fpRSC, nOffset, SEEK_SET);
}
}
| [
"paul.sandbrook.0@gmail.com"
] | paul.sandbrook.0@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.