text
stringlengths
8
6.88M
#include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <ctime> #include <memory.h> #include <cmath> #include <string> #include <cstring> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> #include <complex> typedef long double ld; typedef long long ll; typedef unsigned long long ull; typedef unsigned int uint; const double PI = 3.1415926535897932384626433832795; template<typename T> T sqr(T x) { return x * x; } using namespace std; int B[111], Mib[111], tb = 0, was[111]; void ERR() { puts("No"); exit(0); } int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); int n; cin >> n; for (int i = 0; i < n; ++i) { string s; cin >> s; int mib = 0, b = 0; for (int j = 0; j < s.length(); ++j) { if (s[j] == '(') { ++b; } else { --b; } if (b < mib) mib = b; } Mib[i] = mib; B[i] = b; tb += b; } if (tb != 0) ERR(); int b = 0; for (int i = 0; i < n; ++i) { int mab = int(-2e9), mabi; for (int j = 0; j < n; ++j) if (!was[j] && b + Mib[j] >= 0 && B[j] - Mib[j] > mab) { mab = B[j] - Mib[j]; mabi = j; } if (mab == int(-2e9)) ERR(); was[mabi] = 1; b += B[mabi]; } puts("Yes"); return 0; }
#include "../inc/SEMath.h" template <class T> const SEVec3<T> SEMathUtil<T>::UNIT_X_3 = SEVec3<T>(1,0,0); template <class T> const SEVec3<T> SEMathUtil<T>::UNIT_Y_3 = SEVec3<T>(0,1,0); template <class T> const SEVec3<T> SEMathUtil<T>::UNIT_Z_3 = SEVec3<T>(0,0,1); template <class T> const SEVec4<T> SEMathUtil<T>::UNIT_X_4 = SEVec4<T>(1,0,0,0); template <class T> const SEVec4<T> SEMathUtil<T>::UNIT_Y_4 = SEVec4<T>(0,1,0,0); template <class T> const SEVec4<T> SEMathUtil<T>::UNIT_Z_4 = SEVec4<T>(0,0,1,0); template <class T> const SEVec4<T> SEMathUtil<T>::UNIT_W_4 = SEVec4<T>(0,0,0,1); template <class T> const SEQuaternion<T> SEMathUtil<T>::IDENTITY_QUAT = SEQuaternion<T>(); template <class T> const SEQuaternion<T> SEMathUtil<T>::R90X = SEQuaternion<T>(PIOVER4,1,0,0); template <class T> const SEQuaternion<T> SEMathUtil<T>::R90Y = SEQuaternion<T>(PIOVER4,0,1,0); template <class T> const SEQuaternion<T> SEMathUtil<T>::R90Z = SEQuaternion<T>(PIOVER4,0,0,1); template <class T> const SEQuaternion<T> SEMathUtil<T>::R180X = SEQuaternion<T>(PIOVER2,1,0,0); template <class T> const SEQuaternion<T> SEMathUtil<T>::R180Y = SEQuaternion<T>(PIOVER2,0,1,0); template <class T> const SEQuaternion<T> SEMathUtil<T>::R180Z = SEQuaternion<T>(PIOVER2,0,0,1); template <class T> const SEMat3<T> SEMathUtil<T>::IDENTITY_3 = SEMat3<T> (1, 0, 0, 0, 1, 0, 0, 0, 1); template <class T> const SEMat4<T> SEMathUtil<T>::IDENTITY_4 = SEMat4<T> (1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1);
// KC Text Adventure Framework - (c) Rachel J. Morris, 2012 - 2013. zlib license. Moosader.com #ifndef _GAMEOUTPUT #define _GAMEOUTPUT #include <iostream> // Gameplay output will use these functions so I can do any necessary // formatting or other things later. namespace Go // "Game Output" { void Out( std::string text ); void OutLine( std::string text = "" ); void Type( std::string text ); void DisplayHorizBar(); void ClearScreen(); } #endif
#pragma once #include "../MsgClient/MsgClient.h" class TestExecutive { public: TestExecutive() {} };
#ifndef ARRAY_HEAD_FILE #define ARRAY_HEAD_FILE ////////////////////////////////////////////////////////////////////////////////// //数组模板类 template <class TYPE, class ARG_TYPE=const TYPE &> class CWHArray { //变量定义 protected: TYPE * m_pData; //数组指针 int64_t m_nMaxCount; //缓冲数目 int64_t m_nGrowCount; //增长数目 int64_t m_nElementCount; //元素数目 //函数定义 public: //构造函数 CWHArray(); //析构函数 virtual ~CWHArray(); //信息函数 public: //是否空组 bool IsEmpty() const; //获取数目 int64_t GetCount() const; //功能函数 public: //获取缓冲 TYPE * GetData(); //获取缓冲 const TYPE * GetData() const; //增加元素 int64_t Add(ARG_TYPE newElement); //拷贝数组 void Copy(const CWHArray & Src); //追加数组 int64_t Append(const CWHArray & Src); //获取元素 TYPE & GetAt(int64_t nIndex); //获取元素 const TYPE & GetAt(int64_t nIndex) const; //获取元素 TYPE & ElementAt(int64_t nIndex); //获取元素 const TYPE & ElementAt(int64_t nIndex) const; //操作函数 public: //设置大小 void SetSize(int64_t nNewSize); //设置元素 void SetAt(int64_t nIndex, ARG_TYPE newElement); //设置元素 void SetAtGrow(int64_t nIndex, ARG_TYPE newElement); //插入数据 void InsertAt(int64_t nIndex, const CWHArray & Src, ARG_TYPE newElement); //插入数据 void InsertAt(int64_t nIndex, ARG_TYPE newElement, int64_t nCount=1); //删除数据 void RemoveAt(int64_t nIndex, int64_t nCount=1); //删除元素 void RemoveAll(); //操作重载 public: //操作重载 TYPE & operator[](int64_t nIndex); //操作重载 const TYPE & operator[](int64_t nIndex) const; //内存函数 public: //释放内存 void FreeMemory(); //申请内存 void AllocMemory(int64_t nNewCount); }; ////////////////////////////////////////////////////////////////////////////////// // CWHArray<TYPE, ARG_TYPE> 内联函数 //是否空组 template<class TYPE, class ARG_TYPE> bool CWHArray<TYPE, ARG_TYPE>::IsEmpty() const { return (m_nElementCount==0); } //获取数目 template<class TYPE, class ARG_TYPE> int64_t CWHArray<TYPE, ARG_TYPE>::GetCount() const { return m_nElementCount; } //增加元素 template<class TYPE, class ARG_TYPE> int64_t CWHArray<TYPE,ARG_TYPE>::Add(ARG_TYPE newElement) { int64_t nIndex=m_nElementCount; SetAtGrow(nIndex,newElement); return nIndex; } //操作重载 template<class TYPE, class ARG_TYPE> TYPE & CWHArray<TYPE, ARG_TYPE>::operator[](int64_t nIndex) { return ElementAt(nIndex); } //操作重载 template<class TYPE, class ARG_TYPE> const TYPE & CWHArray<TYPE, ARG_TYPE>::operator[](int64_t nIndex) const { return GetAt(nIndex); } ////////////////////////////////////////////////////////////////////////////////// // CWHArray<TYPE, ARG_TYPE> 外联函数 //构造函数 template<class TYPE, class ARG_TYPE> CWHArray<TYPE, ARG_TYPE>::CWHArray() { m_pData=NULL; m_nMaxCount=0; m_nGrowCount=0; m_nElementCount=0; return; } //构造函数 template<class TYPE, class ARG_TYPE> CWHArray<TYPE,ARG_TYPE>::~CWHArray() { if (m_pData!=NULL) { for (int64_t i=0;i<m_nElementCount;i++) (m_pData+i)->~TYPE(); delete [] (BYTE *)m_pData; m_pData=NULL; } return; } //获取缓冲 template<class TYPE, class ARG_TYPE> TYPE * CWHArray<TYPE,ARG_TYPE>::GetData() { return m_pData; } //获取缓冲 template<class TYPE, class ARG_TYPE> const TYPE * CWHArray<TYPE,ARG_TYPE>::GetData() const { return m_pData; } //拷贝数组 template<class TYPE, class ARG_TYPE> void CWHArray<TYPE,ARG_TYPE>::Copy(const CWHArray & Src) { //效验参数 ASSERT(this!=&Src); if (this==&Src) return; //拷贝数组 AllocMemory(Src.m_nElementCount); if (m_nElementCount>0) { for (int64_t i=0;i<m_nElementCount;i++) (m_pData+i)->~TYPE(); memset(m_pData,0,m_nElementCount*sizeof(TYPE)); } for (int64_t i=0;i<Src.m_nElementCount;i++) m_pData[i]=Src.m_pData[i]; m_nElementCount=Src.m_nElementCount; return; } //追加数组 template<class TYPE, class ARG_TYPE> int64_t CWHArray<TYPE,ARG_TYPE>::Append(const CWHArray & Src) { //效验参数 ASSERT(this!=&Src); //if (this==&Src) AfxThrowInvalidArgException(); //拷贝数组 if (Src.m_nElementCount>0) { int64_t nOldCount=m_nElementCount; AllocMemory(m_nElementCount+Src.m_nElementCount); for (int64_t i=0;i<Src.m_nElementCount;i++) m_pData[m_nElementCount+i]=Src.m_pData[i]; m_nElementCount+=Src.m_nElementCount; } return m_nElementCount; } //获取元素 template<class TYPE, class ARG_TYPE> TYPE & CWHArray<TYPE,ARG_TYPE>::GetAt(int64_t nIndex) { ASSERT((nIndex>=0)&&(nIndex<m_nElementCount)); //if ((nIndex<0)||(nIndex>=m_nElementCount)) AfxThrowInvalidArgException(); return m_pData[nIndex]; } //获取元素 template<class TYPE, class ARG_TYPE> const TYPE & CWHArray<TYPE,ARG_TYPE>::GetAt(int64_t nIndex) const { ASSERT((nIndex>=0)&&(nIndex<m_nElementCount)); //if ((nIndex<0)||(nIndex>=m_nElementCount)) AfxThrowInvalidArgException(); return m_pData[nIndex]; } //获取元素 template<class TYPE, class ARG_TYPE> TYPE & CWHArray<TYPE,ARG_TYPE>::ElementAt(int64_t nIndex) { ASSERT((nIndex>=0)&&(nIndex<m_nElementCount)); //if ((nIndex<0)&&(nIndex>=m_nElementCount)) AfxThrowInvalidArgException(); return m_pData[nIndex]; } //获取元素 template<class TYPE, class ARG_TYPE> const TYPE & CWHArray<TYPE,ARG_TYPE>::ElementAt(int64_t nIndex) const { ASSERT((nIndex>=0)&&(nIndex<m_nElementCount)); //if ((nIndex<0)&&(nIndex>=m_nElementCount)) AfxThrowInvalidArgException(); return m_pData[nIndex]; } //设置大小 template<class TYPE, class ARG_TYPE> void CWHArray<TYPE,ARG_TYPE>::SetSize(int64_t nNewSize) { //效验参数 ASSERT(nNewSize>=0); //if (nNewSize<0) AfxThrowInvalidArgException(); //设置大小 AllocMemory(nNewSize); if (nNewSize>m_nElementCount) { for (int64_t i=m_nElementCount;i<nNewSize;i++) new ((void *)(m_pData+i)) TYPE; } else if (nNewSize<m_nElementCount) { for (int64_t i=nNewSize;i<m_nElementCount;i++) (m_pData+i)->~TYPE(); memset(m_pData+nNewSize,0,(m_nElementCount-nNewSize)*sizeof(TYPE)); } m_nElementCount=nNewSize; return; } //设置元素 template<class TYPE, class ARG_TYPE> void CWHArray<TYPE,ARG_TYPE>::SetAt(int64_t nIndex, ARG_TYPE newElement) { ASSERT((nIndex>=0)&&(nIndex<m_nElementCount)); if ((nIndex>=0)&&(nIndex<m_nElementCount)) m_pData[nIndex]=newElement; else { //AfxThrowInvalidArgException(); } return; } //设置元素 template<class TYPE, class ARG_TYPE> void CWHArray<TYPE,ARG_TYPE>::SetAtGrow(int64_t nIndex, ARG_TYPE newElement) { //效验参数 ASSERT(nIndex>=0); //if (nIndex<0) AfxThrowInvalidArgException(); //设置元素 if (nIndex>=m_nElementCount) SetSize(m_nElementCount+1); m_pData[nIndex]=newElement; return; } //插入数据 template<class TYPE, class ARG_TYPE> void CWHArray<TYPE,ARG_TYPE>::InsertAt(int64_t nIndex, const CWHArray & Src, ARG_TYPE newElement) { //效验参数 ASSERT(nIndex >=0); //if (nStartIndex<0) AfxThrowInvalidArgException(); if (Src.m_nElementCount>0) { int64_t nCount = Src.m_nElementCount; //申请数组 if (nIndex<m_nElementCount) { int64_t nOldCount=m_nElementCount; SetSize(m_nElementCount+Src.m_nElementCount); for (int64_t i=0;i<nCount;i++) (m_pData+nOldCount+i)->~TYPE(); memmove(m_pData+nIndex+nCount,m_pData+nIndex,(nOldCount-nIndex)*sizeof(TYPE)); memset(m_pData+nIndex,0,Src.m_nElementCount*sizeof(TYPE)); for (int64_t i=0;i<Src.m_nElementCount;i++) new (m_pData+nIndex+i) TYPE(); } else SetSize(nIndex+nCount); //拷贝数组 ASSERT((nIndex+Src.m_nElementCount)<=m_nElementCount); while (nCount--) m_pData[nIndex++]=newElement; } return; } //插入数据 template<class TYPE, class ARG_TYPE> void CWHArray<TYPE,ARG_TYPE>::InsertAt(int64_t nIndex, ARG_TYPE newElement, int64_t nCount) { //效验参数 ASSERT(nIndex>=0); ASSERT(nCount>0); //if ((nIndex<0)||(nCount<=0)) AfxThrowInvalidArgException(); //申请数组 if (nIndex<m_nElementCount) { int64_t nOldCount=m_nElementCount; SetSize(m_nElementCount+nCount); for (int64_t i=0;i<nCount;i++) (m_pData+nOldCount+i)->~TYPE(); memmove(m_pData+nIndex+nCount,m_pData+nIndex,(nOldCount-nIndex)*sizeof(TYPE)); memset(m_pData+nIndex,0,nCount*sizeof(TYPE)); for (int64_t i=0;i<nCount;i++) new (m_pData+nIndex+i) TYPE(); } else SetSize(nIndex+nCount); //拷贝数组 ASSERT((nIndex+nCount)<=m_nElementCount); while (nCount--) m_pData[nIndex++]=newElement; return; } //删除数据 template<class TYPE, class ARG_TYPE> void CWHArray<TYPE,ARG_TYPE>::RemoveAt(int64_t nIndex, int64_t nCount) { //效验参数 ASSERT(nIndex>=0); ASSERT(nCount>=0); ASSERT(nIndex+nCount<=m_nElementCount); //if ((nIndex<0)||(nCount<0)||((nIndex+nCount>m_nElementCount))) AfxThrowInvalidArgException(); //删除数据 int64_t nMoveCount=m_nElementCount-(nIndex+nCount); for (int64_t i=0;i<nCount;i++) (m_pData+nIndex+i)->~TYPE(); if (nMoveCount>0) memmove(m_pData+nIndex,m_pData+nIndex+nCount,nMoveCount*sizeof(TYPE)); m_nElementCount-=nCount; return; } //删除元素 template<class TYPE, class ARG_TYPE> void CWHArray<TYPE,ARG_TYPE>::RemoveAll() { if (m_nElementCount>0) { for (int64_t i=0;i<m_nElementCount;i++) (m_pData+i)->~TYPE(); memset(m_pData,0,m_nElementCount*sizeof(TYPE)); m_nElementCount=0; } return; } //释放内存 template<class TYPE, class ARG_TYPE> void CWHArray<TYPE,ARG_TYPE>::FreeMemory() { if (m_nElementCount!=m_nMaxCount) { TYPE * pNewData=NULL; if (m_nElementCount!=0) { pNewData=(TYPE *) new BYTE[m_nElementCount*sizeof(TYPE)]; memcpy(pNewData,m_pData,m_nElementCount*sizeof(TYPE)); } delete [] (BYTE *)m_pData; m_pData=pNewData; m_nMaxCount=m_nElementCount; } return; } //申请内存 template<class TYPE, class ARG_TYPE> void CWHArray<TYPE,ARG_TYPE>::AllocMemory(int64_t nNewCount) { //效验参数 ASSERT(nNewCount>=0); if (nNewCount>m_nMaxCount) { //计算数目 int64_t nGrowCount=m_nGrowCount; if (nGrowCount==0) { nGrowCount=m_nElementCount/8; nGrowCount=(nGrowCount<4)?4:((nGrowCount>1024)?1024:nGrowCount); } nNewCount+=nGrowCount; //申请内存 TYPE * pNewData=(TYPE *) new BYTE[nNewCount*sizeof(TYPE)]; memcpy(pNewData,m_pData,m_nElementCount*sizeof(TYPE)); memset(pNewData+m_nElementCount,0,(nNewCount-m_nElementCount)*sizeof(TYPE)); delete [] (BYTE *)m_pData; //设置变量 m_pData=pNewData; m_nMaxCount=nNewCount; } return; } ////////////////////////////////////////////////////////////////////////////////// #endif
#include<iostream> #include<cstdio> #include<map> #include<set> #include<vector> #include<stack> #include<queue> #include<string> #include<cstring> #include<sstream> #include<algorithm> #include<cmath> using namespace std; int a[1010]; int main() { int t,n; scanf("%d",&t); while (t--) { memset(a,0,sizeof(a)); scanf("%d",&n); int ans = 0,k; for (int i = 1;i <= n; i++) { for (int j = i+1;j <= n; j++) { scanf("%d",&k); if (k) { a[i]++;a[j]++; } } ans += a[i]*(n-1-a[i]); } ans = n*(n-1)*(n-2)/6 - ans/2; printf("%d\n",ans); } return 0; }
#pragma once #include "IO.h" #include "IDT.h" #include "typedefs.h" class Task{ //friend class private: uint8_t stack[4096]; cpustate* }
#ifndef TOMATO_TIME_H #define TOMATO_TIME_H #include <QObject> class QTimer; class TomatoTimer : public QObject { Q_OBJECT public: TomatoTimer( void ); ~TomatoTimer( void ); void setTime( int workTime, int restTime ); signals: void finishWork(); void finishRest(); void displayTime( int time ); public slots: void start(); private slots: void timeout(); private: QTimer* timer; int remainingTime; int restTime; int workTime; }; #endif
#include "GnMeshPCH.h" #include "GnGamePCH.h" #include "GMainGameInterfaceLayer.h" #include "GnIButton.h" #include "GEnergyBar.h" #include "GnIProgressBar.h" #include "GGameDefine.h" #include "GItemInfo.h" #include "GPlayingDataManager.h" #include "GUserHaveItem.h" GMainGameInterfaceLayer::GMainGameInterfaceLayer() : mForcesButtonInfos( GInterfaceLayer::FORCESBT_NUM ) , mpForcesButtonGroup( NULL ), mpSkillButtonGroup( NULL ), mpForcesEnergyBar( NULL ) , mForcesInputEvent( this, &GMainGameInterfaceLayer::InputForcesButton ) { } GnInterfaceGroup* GMainGameInterfaceLayer::CreateInterface(gtuint uiIndex , GnBaseSlot2<GnInterface*, GnIInputEvent*>* pReceiveSlot) { GnInterfaceGroup* pGroup = NULL; switch (uiIndex) { case UI_MAIN_CONTROLLERS: { pGroup = CreateMainController(); } break; case UI_MAIN_FORCESBUTTONS: { pGroup = CreateMainForcesButtons(); pGroup->SubscribeClickedEvent( &mForcesInputEvent ); mpForcesButtonGroup = pGroup; } break; case UI_MAIN_SKILL: { pGroup = CreateMainSkillButtons(); mpSkillButtonGroup = pGroup; } break; case UI_MAIN_OTHERUI: { pGroup = CreateMainMenu(); } break; case UI_MAIN_DLG_PAUSE: pGroup = CreatePauseDialog(); break; case UI_MAIN_DLG_WINSCORE: pGroup = CreateWinScoreDialog(); break; case UI_MAIN_DLG_LOSE: pGroup = CreateLoseDialog(); break; } if( pGroup ) { pGroup->SubscribeClickedEvent( pReceiveSlot ); } return pGroup; } void GMainGameInterfaceLayer::Update(float fTime) { if( mpForcesButtonGroup ) mpForcesButtonGroup->Update( fTime ); if( mpSkillButtonGroup ) mpSkillButtonGroup->Update( fTime ); UpdateButtonState(); } GnInterfaceGroup* GMainGameInterfaceLayer::CreateMainMenu() { GnInterfaceGroup* group = GnNew GnInterfaceGroup(); GnIButton* buttons = NULL; buttons = GnNew GnIButton( "Controll/454_0.png", NULL, NULL ); SetUIPosition( buttons, 454.0f, 0.0f ); group->AddChild( buttons ); group->AddPersonalChild( buttons ); AddChild( group, 1 ); return group; } GnInterfaceGroup* GMainGameInterfaceLayer::CreateMainController() { GnInterfaceGroup* pGroup = GnNew GnInterfaceGroup(); pGroup->SetIsEnablePushMove( true ); pGroup->SetIsAllPush( true ); pGroup->SetRect( 0.5f, 210.0f, 0.5f+115.0f, 210.0f+104.0f ); // GnIButton* buttons[MOVE_NUM]; // buttons[MOVELEFT] = GnNew GnIButton( "Controll/3_247.png", "Controll/3_247 on.png", NULL ); // SetUIPosition( buttons[MOVELEFT], 3, 247 ); // // buttons[MOVERIGHT] = GnNew GnIButton( "Controll/58_247.png", "Controll/58_247 on.png", NULL ); // SetUIPosition( buttons[MOVERIGHT], 58, 247 ); // // buttons[MOVEUP] = GnNew GnIButton( "Controll/37_223.png", "Controll/37_223 on.png", NULL ); // SetUIPosition( buttons[MOVEUP], 37, 223 ); // // buttons[MOVEDOWN] = GnNew GnIButton( "Controll/38_268.png", "Controll/38_268 on.png", NULL ); // SetUIPosition( buttons[MOVEDOWN], 38, 268 ); // // buttons[MOVELEFTUP] = GnNew GnIButton( "Controll/3_224.png" ); // SetUIPosition( buttons[MOVELEFTUP], 3, 224 ); // // buttons[MOVERIGHTUP] = GnNew GnIButton( "Controll/78_224.png" ); // SetUIPosition( buttons[MOVERIGHTUP], 78, 224 ); // // buttons[MOVELEFTDOWN] = GnNew GnIButton( "Controll/3_287.png" ); // SetUIPosition( buttons[MOVELEFTDOWN], 3, 287 ); // // buttons[MOVERIGHTDOWN] = GnNew GnIButton( "Controll/78_287.png" ); // SetUIPosition( buttons[MOVERIGHTDOWN], 78, 287 ); GnIButton* buttons[MOVE_NUM]; // buttons[MOVELEFTUP] = GnNew GnIButton( "Controll/8_206.png" ); // SetUIPosition( buttons[MOVELEFTUP], 9, 206 ); // buttons[MOVELEFTUPSMALL] = GnNew GnIButton( "Controll/47_241.png" ); // SetUIPosition( buttons[MOVELEFTUPSMALL], 49, 241 ); // // buttons[MOVERIGHTUP] = GnNew GnIButton( "Controll/88_206.png" ); // SetUIPosition( buttons[MOVERIGHTUP], 88, 206 ); // buttons[MOVERIGHTUPSMALL] = GnNew GnIButton( "Controll/75_241.png" ); // SetUIPosition( buttons[MOVERIGHTUPSMALL], 74, 241 ); // // buttons[MOVELEFTDOWN] = GnNew GnIButton( "Controll/8_278.png" ); // SetUIPosition( buttons[MOVELEFTDOWN], 9, 278 ); // buttons[MOVELEFTDOWNSMALL] = GnNew GnIButton( "Controll/47_266.png" ); // SetUIPosition( buttons[MOVELEFTDOWNSMALL], 49, 266 ); // // buttons[MOVERIGHTDOWN] = GnNew GnIButton( "Controll/88_278.png" ); // SetUIPosition( buttons[MOVERIGHTDOWN], 88, 278 ); // buttons[MOVERIGHTDOWNSMALL] = GnNew GnIButton( "Controll/75_266.png" ); // SetUIPosition( buttons[MOVERIGHTDOWNSMALL], 74 , 266 ); // // buttons[MOVELEFT] = GnNew GnIButton( "Controll/8_241.png" ); // SetUIPosition( buttons[MOVELEFT], 9, 241 ); // buttons[MOVELEFTSMALL] = GnNew GnIButton( "Controll/47_253.png" ); // SetUIPosition( buttons[MOVELEFTSMALL], 48, 253 ); // // buttons[MOVERIGHT] = GnNew GnIButton( "Controll/88_241.png" ); // SetUIPosition( buttons[MOVERIGHT], 88, 241 ); // buttons[MOVERIGHTSMALL] = GnNew GnIButton( "Controll/75_253.png" ); // SetUIPosition( buttons[MOVERIGHTSMALL], 75, 253 ); // // buttons[MOVEUP] = GnNew GnIButton( "Controll/47_206.png" ); // SetUIPosition( buttons[MOVEUP], 48, 206 ); // buttons[MOVEUPSMALL] = GnNew GnIButton( "Controll/60_241.png" ); // SetUIPosition( buttons[MOVEUPSMALL], 60, 241 ); // // buttons[MOVEDOWN] = GnNew GnIButton( "Controll/47_278.png" ); // SetUIPosition( buttons[MOVEDOWN], 48, 278 ); // buttons[MOVEDOWNSMALL] = GnNew GnIButton( "Controll/60_266.png" ); // SetUIPosition( buttons[MOVEDOWNSMALL], 60, 266 ); buttons[MOVELEFTUP] = GnNew GnIButton( "Controll/8_206.png" ); SetUIPosition( buttons[MOVELEFTUP], 8, 206 ); buttons[MOVELEFTUPSMALL] = GnNew GnIButton( "Controll/48_241.png" ); SetUIPosition( buttons[MOVELEFTUPSMALL], 48, 241 ); buttons[MOVERIGHTUP] = GnNew GnIButton( "Controll/89_206.png" ); SetUIPosition( buttons[MOVERIGHTUP], 89, 206 ); buttons[MOVERIGHTUPSMALL] = GnNew GnIButton( "Controll/75_241.png" ); SetUIPosition( buttons[MOVERIGHTUPSMALL], 75, 241 ); buttons[MOVELEFTDOWN] = GnNew GnIButton( "Controll/8_278.png" ); SetUIPosition( buttons[MOVELEFTDOWN], 8, 278 ); buttons[MOVELEFTDOWNSMALL] = GnNew GnIButton( "Controll/48_266.png" ); SetUIPosition( buttons[MOVELEFTDOWNSMALL], 48, 266 ); buttons[MOVERIGHTDOWN] = GnNew GnIButton( "Controll/89_278.png" ); SetUIPosition( buttons[MOVERIGHTDOWN], 89, 278 ); buttons[MOVERIGHTDOWNSMALL] = GnNew GnIButton( "Controll/75_266.png" ); SetUIPosition( buttons[MOVERIGHTDOWNSMALL], 75, 266 ); buttons[MOVELEFT] = GnNew GnIButton( "Controll/8_241.png" ); SetUIPosition( buttons[MOVELEFT], 8, 241 ); buttons[MOVELEFTSMALL] = GnNew GnIButton( "Controll/48_253.png" ); SetUIPosition( buttons[MOVELEFTSMALL], 48, 253 ); buttons[MOVERIGHT] = GnNew GnIButton( "Controll/89_241.png" ); SetUIPosition( buttons[MOVERIGHT], 89, 241 ); buttons[MOVERIGHTSMALL] = GnNew GnIButton( "Controll/75_253.png" ); SetUIPosition( buttons[MOVERIGHTSMALL], 75, 253 ); buttons[MOVEUP] = GnNew GnIButton( "Controll/48_206.png" ); SetUIPosition( buttons[MOVEUP], 48, 206 ); buttons[MOVEUPSMALL] = GnNew GnIButton( "Controll/60_241.png" ); SetUIPosition( buttons[MOVEUPSMALL], 60, 241 ); buttons[MOVEDOWN] = GnNew GnIButton( "Controll/48_278.png" ); SetUIPosition( buttons[MOVEDOWN], 48, 278 ); buttons[MOVEDOWNSMALL] = GnNew GnIButton( "Controll/60_266.png" ); SetUIPosition( buttons[MOVEDOWNSMALL], 60, 266 ); for (gtuint i = 0; i < MOVE_NUM ; i++ ) { pGroup->AddChild( buttons[i] ); } GnIButton* center = GnNew GnIButton( "Controll/60_253.png" ); SetUIPosition( center, 60, 253 ); pGroup->AddChild( center ); AddChild( pGroup, 1 ); return pGroup; } GnInterfaceGroup* GMainGameInterfaceLayer::CreateMainForcesButtons() { GnInterfaceGroup* group = GnNew GnInterfaceGroup(); group->SetIsAllPush( true ); group->SetRect( 135.0f, 210.0f, 135.0f+240.0f, 210.0f+100.0f ); GnIButton* buttons[FORCESBT_NUM]; buttons[BT_C2] = GnNew GnIButton( "Controll/125_223.png", NULL, "Controll/125_223G.png" ); SetUIPosition( buttons[BT_C2], 143.0f, 223.0f, eIndexC2 ); buttons[BT_C3] = GnNew GnIButton( "Controll/170_223.png", NULL, "Controll/170_223G.png" ); SetUIPosition( buttons[BT_C3], 188.0f, 223.0f, eIndexC3 ); buttons[BT_C4] = GnNew GnIButton( "Controll/215_223.png", NULL, "Controll/215_223G.png" ); SetUIPosition( buttons[BT_C4], 233.0f, 223.0f, eIndexC4 ); buttons[BT_C5] = GnNew GnIButton( "Controll/260_223.png", NULL, "Controll/260_223G.png" , GnIButton::TYPE_DISABLE ); SetUIPosition( buttons[BT_C5], 278.0f, 223.0f, eIndexC5 ); buttons[BT_C6] = GnNew GnIButton( "Controll/305_223.png", NULL, "Controll/305_223G.png" , GnIButton::TYPE_DISABLE ); SetUIPosition( buttons[BT_C6], 323.0f, 223.0f, eIndexC6 ); buttons[BT_C7] = GnNew GnIButton( "Controll/125_268.png", NULL, "Controll/125_268G.png" ,GnIButton::TYPE_DISABLE ); SetUIPosition( buttons[BT_C7], 143.0f, 268.0f, eIndexC7 ); buttons[BT_C8] = GnNew GnIButton( "Controll/170_268.png", NULL, "Controll/170_268G.png" , GnIButton::TYPE_DISABLE ); SetUIPosition( buttons[BT_C8], 188.0f, 268.0f, eIndexC8 ); buttons[BT_C9] = GnNew GnIButton( "Controll/215_268.png", NULL, "Controll/215_268G.png", GnIButton::TYPE_DISABLE ); SetUIPosition( buttons[BT_C9], 233.0f, 268.0f, eIndexC9 ); buttons[BT_C10] = GnNew GnIButton( "Controll/260_268.png", NULL, "Controll/260_268G.png", GnIButton::TYPE_DISABLE ); SetUIPosition( buttons[BT_C10], 278.0f, 268.0f, eIndexC10 ); guint32 maxFDLevel = GUserAbility::GetAbilityLevel( eIndexMaxFD ); guint32 fillFDLevel = GUserAbility::GetAbilityLevel( eIndexFillFD ); buttons[BT_C11] = GEnergyBar::Create( 50 + ( maxFDLevel * 15 ), 0.7 - ( fillFDLevel * 0.02f ), "Controll/305_268.png" ); SetUIPosition( buttons[BT_C11], 323.0f, 268.0f ); mpForcesEnergyBar = (GEnergyBar*)buttons[BT_C11]; for (gtuint i = 0; i < FORCESBT_NUM; i++ ) group->AddChild( buttons[i] ); GnInterface* energyBarLine = GnNew GnInterface( "Controll/309_288.png" ); SetUIPosition( energyBarLine, 327.0f, 288.0f ); group->AddChild( energyBarLine ); AddChild( group, 1 ); SetForcesButtonInfo( buttons ); return group; } GnInterfaceGroup* GMainGameInterfaceLayer::CreateMainSkillButtons() { static const float position[4][2] = { { 384.0f, 223.0f }, { 429.0f, 223.0f }, { 384.0f, 268.0f }, { 429.0f, 268.0f } }; GnInterfaceGroup* group = GnNew GnInterfaceGroup(); group->SetIsAllPush( true ); group->SetRect( 362.0f, 218.0f, 362.0f+120.0f, 218.0f+100.0f ); gstring filename = GetFullPath( "ItemInfo.sqlite" ); GnSQLite sqlite( filename.c_str() ); GUserHaveItem* haveItem = GPlayingDataManager::GetSingleton()->GetPlayingHaveItem(); GPlayingData* playingData = GPlayingDataManager::GetSingleton()->GetPlayingPlayerData(); haveItem->OpenPlayerItem( playingData->GetPlayerName() ); GnList<GUserHaveItem::Item> haveItems; haveItem->GetItems( eEquip, haveItems ); GnListIterator<GUserHaveItem::Item> iter = haveItems.GetIterator(); gtuint itemCount = 0; while( iter.Valid() ) { GUserHaveItem::Item& item = iter.Item(); gtuint itemIndex = item.mIndex; GnSQLiteQuery query = sqlite.ExecuteSingleQuery( "SELECT * FROM GameItem WHERE idx=%d", item.mIndex ); if( query.IsEof() ) { GnLogA( "error execute query - getting UnitButton %d", item.mIndex ); continue; } float cooltime = query.GetFloatField( 2 ); GnIButton* buttons = GnNew GnIButton( GetItemInfo()->GetGameIconFileName( itemIndex ) ); buttons->SetTegID( item.mIndex ); buttons->SetIsDisableCantpushBlind( false ); buttons->SetIsEnableCoolTime( true ); buttons->SetCoolTime( cooltime ); SetUIPosition( buttons, position[itemCount][0], position[itemCount][1] ); group->AddChild( buttons ); iter.Forth(); ++itemCount; if( ENABLE_MAX_EQUIP <= itemCount ) break; } for ( ; itemCount < 4 ; itemCount++ ) { GnIButton* buttons = GnNew GnIButton( NULL, NULL, "375_223G.png" ); SetUIPosition( buttons, position[itemCount][0], position[itemCount][1] ); group->AddChild( buttons ); } haveItem->Close(); AddChild( group, 1 ); // GnInterface* energyBarLine = GnNew GnInterface( "Controll/309_288.png" ); // SetUIPosition( energyBarLine, 425.0f, 288.0f ); // group->AddChild( energyBarLine ); return group; } GnInterfaceGroup* GMainGameInterfaceLayer::CreatePauseDialog() { float scale = GetGameState()->GetGameScale(); GetGameState()->SetGameScale( 1.0f ); GnInterfaceGroup* group = GnNew GnInterfaceGroup(); group->SetRect( 0.0f, 0.0f, GetGameState()->GetGameWidth(), GetGameState()->GetGameHeight() ); GnInterface* label = NULL; label = GnNew GnInterface( "Controll/pause/354_26.png" ); SetUIPosition( label, 354.0f, 26.0f ); group->AddChild( label ); GnIButton* buttons = NULL; // next button buttons = GnNew GnIButton( "Controll/pause/368_80.png", NULL, NULL ); buttons->SetTegID( DIALOG_LEVELSELECT_BUTTON ); SetUIPosition( buttons, 368.0f, 80.0f ); group->AddChild( buttons ); // prev button buttons = GnNew GnIButton( "Controll/pause/381_43.png", NULL, NULL ); buttons->SetTegID( DIALOG_RESUME_BUTTON ); SetUIPosition( buttons, 381.0f, 43.0f ); group->AddChild( buttons ); GetGameState()->SetGameScale( scale ); return group; } GnInterfaceGroup* GMainGameInterfaceLayer::CreateWinScoreDialog() { float scale = GetGameState()->GetGameScale(); GetGameState()->SetGameScale( 1.0f ); GnInterfaceGroup* group = GnNew GnInterfaceGroup(); group->SetRect( 0.0f, 0.0f, GetGameState()->GetGameWidth(), GetGameState()->GetGameHeight() ); // background GnInterface* back = NULL; back = GnNew GnInterface( "Controll/score/143_50.png" ); SetUIPosition( back, 143.0f, 26.0f ); group->AddChild( back ); GnIButton* buttons = NULL; // replay button buttons = GnNew GnIButton( "Controll/score/165_142.png", "Controll/score/165_142a.png", NULL ); buttons->SetTegID( DIALOG_REPLAY_BUTTON ); SetUIPosition( buttons, 165.0f, 120.0f ); group->AddChild( buttons ); // next button buttons = GnNew GnIButton( "Controll/score/251_142.png", "Controll/score/251_142a.png", NULL ); buttons->SetTegID( DIALOG_NEXT_BUTTON ); SetUIPosition( buttons, 251.0f, 120.0f ); group->AddChild( buttons ); gstring fullPath; GetFullPathFromWorkPath( "Controll/score/232_113.png", fullPath ); GnINumberLabel* label = GnNew GnINumberLabel( NULL, 10 ); label->Init( "0", fullPath.c_str(), 12, 14, '.' ); label->SetTegID( DIALOG_TIME_NUM ); SetUIPosition( label, 232.0f, 78.0f ); group->AddChild( label ); GetFullPathFromWorkPath( "Controll/score/232_113.png", fullPath ); label = GnNew GnINumberLabel( NULL, 10 ); label->Init( "0", fullPath.c_str(), 12, 14, '.' ); label->SetTegID( DIALOG_MONEY_NUM ); SetUIPosition( label, 232.0f, 97.0f ); group->AddChild( label ); GetGameState()->SetGameScale( scale ); return group; } GnInterfaceGroup* GMainGameInterfaceLayer::CreateLoseDialog() { float scale = GetGameState()->GetGameScale(); GetGameState()->SetGameScale( 1.0f ); GnInterfaceGroup* group = GnNew GnInterfaceGroup(); group->SetRect( 0.0f, 0.0f, GetGameState()->GetGameWidth(), GetGameState()->GetGameHeight() ); // background GnInterface* back = NULL; back = GnNew GnInterface( "Controll/score/143_50a.png" ); SetUIPosition( back, 143.0f, 26.0f ); group->AddChild( back ); GnIButton* buttons = NULL; // replay button buttons = GnNew GnIButton( "Controll/score/165_142.png", "Controll/score/165_142a.png", NULL ); buttons->SetTegID( DIALOG_REPLAY_BUTTON ); SetUIPosition( buttons, 165.0f, 120.0f ); group->AddChild( buttons ); // next button buttons = GnNew GnIButton( "Controll/score/251_142.png", "Controll/score/251_142a.png", NULL ); buttons->SetTegID( DIALOG_NEXT_BUTTON ); SetUIPosition( buttons, 251.0f, 120.0f ); group->AddChild( buttons ); gstring fullPath; GetFullPathFromWorkPath( "Controll/score/232_113.png", fullPath ); GnINumberLabel* label = GnNew GnINumberLabel( NULL, 10 ); label->Init( "0", fullPath.c_str(), 12, 14, '.' ); SetUIPosition( label, 232.0f, 78.0f, DIALOG_TIME_NUM ); group->AddChild( label ); GetFullPathFromWorkPath( "Controll/score/232_113.png", fullPath ); label = GnNew GnINumberLabel( NULL, 10 ); label->Init( "0", fullPath.c_str(), 12, 14, '.' ); SetUIPosition( label, 232.0f, 97.0f, DIALOG_MONEY_NUM ); group->AddChild( label ); GetGameState()->SetGameScale( scale ); return group; } bool GMainGameInterfaceLayer::SetForcesButtonInfo(GnIButton** ppButtons) { GUserHaveItem* haveItem = GetCurrentHaveItem(); gstring filename = GetFullPath( "ItemInfo.sqlite" ); GnSQLite sqlite( filename.c_str() ); for (gtuint i = 0; i < FORCESBT_NUM - 1 ; i++ ) { GnSQLiteQuery query = sqlite.ExecuteSingleQuery( "SELECT * FROM GameItem WHERE idx=%d", i + INDEX_UNIT + 1 ); if( query.IsEof() ) { GnLogA( "error execute query - getting UnitButton %d", i + INDEX_UNIT + 1 ); continue; } guint32 itemLevel = haveItem->GetItemLevel( ppButtons[i]->GetTegID() ); if( itemLevel > 0 ) ppButtons[i]->SetIsDisable( false ); else ppButtons[i]->SetIsDisable( true ); float energy = query.GetFloatField( 1 ); float cooltime = query.GetFloatField( 2 ); ppButtons[i]->SetIsDisableCantpushBlind( false ); ppButtons[i]->SetIsCantPush( true ); ppButtons[i]->SetIsEnableCoolTime( true ); ppButtons[i]->SetCoolTime( cooltime ); ButtonInfo& btInfo = mForcesButtonInfos.GetAt( i ); btInfo.SetButton( ppButtons[i] ); btInfo.SetCanPushEnergy( energy ); btInfo.SetCoolTime( cooltime ); btInfo.SetItemLevel( itemLevel ); } haveItem->Close(); return true; } void GMainGameInterfaceLayer::UpdateButtonState() { const gtuint num = FORCESBT_NUM - 1; for (gtuint i = 0; i < num ; i++ ) { ButtonInfo& btInfo = mForcesButtonInfos.GetAt( i ); if( btInfo.GetButton()->IsDisable() ) continue; if( mpForcesEnergyBar->GetCurrentEnergy() >= btInfo.GetCanPushEnergy() ) { btInfo.GetButton()->SetIsCantPush( false ); } else { if( btInfo.GetButton()->IsCantPush() == false ) btInfo.GetButton()->SetIsCantPush( true ); } } } void GMainGameInterfaceLayer::InputForcesButton(GnInterface* pInterface, GnIInputEvent* pEvent) { if( pEvent->GetEventType() == GnIInputEvent::PUSH ) { for (gtuint i = 0; i < FORCESBT_NUM ; i++ ) { ButtonInfo& btInfo = mForcesButtonInfos.GetAt( i ); if( btInfo.GetButton() == pInterface ) { mpForcesEnergyBar->SetCurrentEnergy( mpForcesEnergyBar->GetCurrentEnergy() - btInfo.GetCanPushEnergy() ); break; } } } }
/* -*- coding: utf-8 -*- !@time: 2020-03-04 03:23 !@author: superMC @email: 18758266469@163.com !@fileName: 0044_reverse_words.cpp */ #include <environment.h> #include <utility> class Solution { public: string ReverseSentence(string str) { if (str.empty()) return str; vector<string> words = splitString(std::move(str)); string ret; for (vector<string>::const_iterator iter = words.cend() - 1; iter != words.cbegin() - 1; iter--) { ret += *iter; if (iter != words.cbegin()) ret += " "; } return ret; } vector<string> splitString(const string &str) { vector<string> words; stringstream ss; ss.str(str); string item; char delim = ' '; while (getline(ss, item, delim)) { words.push_back(item); } return words; } string ReverseSentence_template(string str) { string res, tmp; for(char i : str){ if(i == ' ') res = " " + tmp + res, tmp = ""; else tmp += i; } if(!tmp.empty()) res = tmp + res; return res; } }; int fun() { string str = "world! hello"; str = Solution().ReverseSentence(str); printf("%s", str.c_str()); return 0; }
// // Created by giofnk on 15/02/20. // #include "FormuleTest.h" void FormuleTest::SetUp(){ table=new Table(10,10); formulaSum=new FormulaSum; formulaMax=new FormulaMax; formulaMin=new FormulaMin; formulaMean=new FormulaMean; table->setCellValue(10.5,0,0); table->setCellValue(20.5,0,1); table->setCellValue(30,0,2); table->getCell(0,0)->attach(formulaSum); table->getCell(0,0)->attach(formulaMin); // cella in posizione 0,0 iscritta a ForumulaSum e ForumulaMin table->getCell(0,1)->attach(formulaMin); table->getCell(0,1)->attach(formulaMax); table->getCell(0,1)->attach(formulaMean);// cella in posizione 0,1 iscritta a ForumulaMin, ForumulaMax e ForumulaMean table->getCell(0,2)->attach(formulaSum); table->getCell(0,2)->attach(formulaMin); table->getCell(0,2)->attach(formulaMean); // cella in posizione 0,2 iscritta a ForumulaSum, ForumulaMin e ForumulaMean }; TEST_F(FormuleTest, FormulaMax){ ASSERT_EQ(dynamic_cast<FormulaMax*>(formulaMax)->calculate(),20.5); } TEST_F(FormuleTest,FormulaMin){ ASSERT_EQ(dynamic_cast<FormulaMin*>(formulaMin)->calculate(),10.5); } TEST_F(FormuleTest,FormulaMean){ ASSERT_EQ(dynamic_cast<FormulaMean*>(formulaMean)->calculate(),((20.5+30)/2)); } TEST_F(FormuleTest,FormulaSum){ ASSERT_EQ(dynamic_cast<FormulaSum*>(formulaSum)->calculate(),40.5); }
/* 2016Äê2ÔÂ5ÈÕ10:52:34 */ #include <stdio.h> #include <iostream> #include <string.h> using std::cout; using std::cin; using std::endl; int need[510] = { 0 }; int value[510] = { 0 }; int dp[510][100010] = { 0 };//10^5/500 int main() { freopen("../test.txt", "r", stdin); int N, M; int i, j, k; cin >> N >> M; for (i = 1; i <= N; ++i) { cin >> need[i] >> value[i]; } for (i = 1; i <= N; ++i) { for (j = 1; j <= M; ++j) { int maxK = j / need[i]; for (k = 0; k <= maxK; ++k) { int tmp = (value[i] * k + dp[i - 1][j - need[i] * k]); if (tmp > dp[i][j]) { dp[i][j] = tmp; } } } } cout << dp[N][M] << endl; return 0; }
#include "UniversalForce.h" #include "Object.h" #include "Define.h" #include <iostream> UniversalForce::UniversalForce(Object* obj) : Force::Force(Vector(0, 0, 0)) { this->object = obj; } UniversalForce::UniversalForce(const UniversalForce& uniForce) : Force::Force(dynamic_cast<const Force&>(uniForce)) { this->object = uniForce.object; } UniversalForce::~UniversalForce(void) { this->object = NULL; } void UniversalForce::exec(void) { if (object->getVelocity().getMagnitude() < SPEED_MAX) object->push(*this); } bool UniversalForce::isDone(void) { return false; } Vector UniversalForce::getForcePoint(void) { return this->object->getGravityCenter(); } void UniversalForce::changeObject(Object* obj) { this->object = obj; }
/** * @file mp_map_util.h * @brief motion planning map util */ #include <motion_primitive_library/planner/env_map.h> #include <motion_primitive_library/planner/mp_base_util.h> using linkedHashMap = std::unordered_map<int, std::vector<std::pair<MPL::Key, int>>>; /** * @brief Motion primitive planner in voxel map */ template <int Dim> class MPMapUtil : public MPBaseUtil<Dim> { public: /** * @brief Simple constructor * @param verbose enable debug messages */ MPMapUtil(bool verbose); ///Set map util void setMapUtil(std::shared_ptr<MPL::MapUtil<Dim>>& map_util); ///Get linked voxels vec_Vecf<Dim> getLinkedNodes() const; /** * @brief Update edge costs according to the new blocked nodes * @param pns the new occupied voxels * * The function returns affected primitives for debug purpose */ vec_E<Primitive<Dim>> updateBlockedNodes(const vec_Veci<Dim>& pns); /** * @brief Update edge costs according to the new cleared nodes * @param pns the new cleared voxels * * The function returns affected primitives for debug purpose */ vec_E<Primitive<Dim>> updateClearedNodes(const vec_Veci<Dim>& pns); protected: ///Map util std::shared_ptr<MPL::MapUtil<Dim>> map_util_; ///Linked table that records voxel and corresponding primitives passed through it mutable linkedHashMap lhm_; }; ///Planner for 2D OccMap typedef MPMapUtil<2> MPMap2DUtil; ///Planner for 3D VoxelMap typedef MPMapUtil<3> MPMap3DUtil;
#include <iostream> using namespace std; int N, r, c; int cnt = 0; void devide(int num, int row, int col); int main() { cin >> N >> r >> c; devide(N, r, c); cout << cnt; } void devide(int num, int row, int col) { int num1 = 1; for (int i = 0; i < num; i++) { num1 *= 2; } int start2 = num1 / 2; if (num == 1) { if (row % 2 == 0) { if (col % 2 == 0) { cnt += 0; } else { cnt += 1; } } else { if (col % 2 == 0) { cnt += 2; } else { cnt += 3; } } return; } if (row < start2 && col < start2) { cnt += 0; devide(num-1, row, col); } else if (row >= start2 && col <start2) { cnt += start2 * start2 * 2; devide(num-1, row-start2, col); } else if (row <start2 && col >= start2) { cnt += start2 * start2 * 1; devide(num-1, row, col-start2); } else { cnt += start2 * start2 * 3; devide(num-1, row-start2, col-start2); } }
#ifndef SRC_Qt_messageBox_h #define SRC_Qt_messageBox_h //#ifndef _WIN32 //#pragma once #include <iostream> #include <QtWidgets/qmessagebox.h> #include <QtWidgets/qapplication.h> #include <QtWidgets/qpushbutton.h> #include <QtWidgets/qstylefactory.h> #include <QtWidgets/qlayoutitem.h> #include <QtWidgets/qgridlayout.h> #include "myUtils.h" #ifdef _WIN32 #include <Windows.h> #define GetCurrentDir _getcwd #else #include<unistd.h> #endif using namespace std; string extern back_slash; string extern Sys_language; string extern Time; string extern Data; #include "Logging.h" inline int messageBox(const char * classifier, int type, int argc = 0, char** argv = NULL); /* inline QMessageBox * QtMessageBoxCreatorError(){ z QMessageBox *msgBox = new QMessageBox(0); msgBox->setText("Test\n Allora funziona?"); msgBox->setWindowModality(Qt::NonModal); msgBox->setInformativeText("Do you want to save your changes?"); msgBox->setStandardButtons(QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); msgBox->setDefaultButton(QMessageBox::Save); msgBox->setWindowTitle("WARNING!"); msgBox->setIcon(QMessageBox::Critical); msgBox->setStyle(QStyleFactory::create("Fusion")); QPalette darkPalette; darkPalette.setColor(QPalette::Window, QColor(53,53,53)); darkPalette.setColor(QPalette::WindowText, Qt::white); darkPalette.setColor(QPalette::Base, QColor(25,25,25)); darkPalette.setColor(QPalette::AlternateBase, QColor(53,53,53)); darkPalette.setColor(QPalette::ToolTipBase, Qt::white); darkPalette.setColor(QPalette::ToolTipText, Qt::white); darkPalette.setColor(QPalette::Text, Qt::white); darkPalette.setColor(QPalette::Button, QColor(53,53,53)); darkPalette.setColor(QPalette::ButtonText, Qt::white); darkPalette.setColor(QPalette::BrightText, Qt::red); darkPalette.setColor(QPalette::Link, QColor(42, 130, 218)); darkPalette.setColor(QPalette::Highlight, QColor(42, 130, 218)); darkPalette.setColor(QPalette::HighlightedText, Qt::black); qApp->setPalette(darkPalette); qApp->setStyleSheet("QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }"); return msgBox; } */ inline QMessageBox* QtMessageBoxCreatorErrorCascadeOrWebcam(const char * classifier, int type) { //char buffer [50]; //int n, a=5, b=3; //n=sprintf (buffer, "%d plus %d is %d", a, b, a+b); QMessageBox *msgBox = new QMessageBox(0); //const char cascade[]="resources\eye_left_18x12.xml"; if (type == 0) { char all[100]; if (Sys_language == "IT") sprintf(all, "CASCADE NON TROVATO: %s\n", classifier); else sprintf(all, "CASCADE NOT FOUND: %s\n", classifier); msgBox->setText(all); } else { if (Sys_language == "IT") msgBox->setText(classifier); else msgBox->setText("WEB-CAM NOT AVAIBLE FOR OPENING!"); } msgBox->setWindowModality(Qt::NonModal); if (Sys_language == "IT") msgBox->setInformativeText("Programma terminato con errore"); else msgBox->setInformativeText("Program exited with errors"); //msgBox->setStandardButtons(QMessageBox::Escape); //QSpacerItem* horizontalSpacer = new QSpacerItem(1000, 0, QSizePolicy::Minimum, QSizePolicy::Expanding); //QGridLayout* layout = (QGridLayout*)msgBox->layout(); //layout->addItem(horizontalSpacer, layout->rowCount(), 0, 1, layout->columnCount()); //msgBox->setBaseSize(QSize(600, 520)); //msgBox->setFixedSize ( 500,500); QAbstractButton* exit = msgBox->addButton("Esci", QMessageBox::NoRole); //QAbstractButton* moreInfo =msgBox->addButton("Altre info", QMessageBox::NoRole); char logPath[500]; char detaileString[1000]; #ifdef _WIN32 GetCurrentDir(logPath, sizeof(logPath)); string current_path = logPath; //cout<<"cuurent path last: "<<current_path<<endl; #else getcwd(logPath, sizeof(logPath)); //string current_path = logPath; #endif if (Sys_language == "IT") { sprintf(detaileString, "Impossibile caricare il file di cascade al seguente percorso:\n" "%s.\n\nVerificare che lo stesso non sia stato accidentalmente rimosso.\n\n" "File di log generato al seguente percorso: %s", classifier, logPath); } else { sprintf(detaileString, "Cascade file cannot being loaded at followng path:\n" "%s.\n\nVerify the one not being accidentally removed.\n\n" "File-log generated at following path: %s", classifier, logPath); } msgBox->setDetailedText(detaileString); QIcon icon("resources/icons/trainer.ico"); msgBox->setWindowIcon(icon); msgBox->setWindowFlags(msgBox->windowFlags() & Qt::WindowCloseButtonHint); // se metto così levva la x //msgBox->setWindowFlags(msgBox->windowFlags() & ~Qt::WindowCloseButtonHint); //QAbstractButton* open=msgBox->addButton("Apri", QMessageBox::NoRole); msgBox->setDefaultButton(0); if (Sys_language == "IT") msgBox->setWindowTitle("ERRORE CRITCO"); else msgBox->setWindowTitle("CRITICAL ERROR"); msgBox->setIcon(QMessageBox::Critical); msgBox->setStyle(QStyleFactory::create("Fusion")); msgBox->setFixedSize(542, 503); //msgBox->move((window_w-message.width())/2,(window_h-message.height())/2); QPalette darkPalette; darkPalette.setColor(QPalette::Window, QColor(53, 53, 53)); darkPalette.shadow(); darkPalette.setColor(QPalette::WindowText, Qt::white); darkPalette.setColor(QPalette::Base, QColor(25, 25, 25)); darkPalette.setColor(QPalette::AlternateBase, QColor(53, 53, 53)); darkPalette.setColor(QPalette::ToolTipBase, Qt::white); darkPalette.setColor(QPalette::ToolTipText, Qt::white); darkPalette.setColor(QPalette::Text, Qt::white); darkPalette.setColor(QPalette::Button, QColor(53, 53, 53)); #ifdef _WIN32 darkPalette.setColor(QPalette::ButtonText, QColor(25, 25, 25)); #else darkPalette.setColor(QPalette::ButtonText, Qt::white); #endif darkPalette.setColor(QPalette::BrightText, Qt::red); darkPalette.setColor(QPalette::Link, QColor(42, 130, 218)); darkPalette.setColor(QPalette::Highlight, QColor(42, 130, 218)); darkPalette.setColor(QPalette::HighlightedText, Qt::black); qApp->setPalette(darkPalette); qApp->setStyleSheet("QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }"); return msgBox; } inline QMessageBox * QtMessageBoxCreatorErrorTrainRequest(string classifier) { QMessageBox *msgBox = new QMessageBox(0); //char all[100]; //sprintf(all,"CASCADE NON TROVATO: %s\n",classifier); QString labelText = "<P><b><center><FONT COLOR='#E0E0E0'><br><br>"; labelText.append("FACE AUTHNTICATION SYSTEM "); labelText.append("</center></P></b><b><br><br><br><br><br><br><FONT COLOR='#5ddffe'>"); //labelText.append("</center></P></b><b><br><br><br><br><br><br><FONT COLOR='#bdfffe'>"); //labelText.append("<center><u><b><p align='justify'>Si sta per avviare una nuova procedura di enrollment.</p></b></u><br><br><br>"); //labelText.append(classifier); labelText.append("<center><FONT COLOR='#b4b4b6' FONT SIZE=4><br><br><br><br>ATTENZIONE:</center><br>"); labelText.append("<center><u><FONT COLOR='#36d6f6'>SI STA PER AVVIARE UNA NUOVA SESSIONE DI ENROLLMENT</u></center><br><br>"); labelText.append("<p align='justify'><FONT COLOR='#E0E0E0' FONT SIZE=4><br><br>Verrà effettato uno scanning facciale necessario per poter essere successivamente autenticati dal sistema.<br>Proseguendo, i dati relativi a sessioni di training precedenti saranno sovrascritti ed andranno perduti.<br>"); labelText.append("Interrompendo prematuramente la procedura non sarà più possibile autenticarsi sino al nuovo enrollment.<br></p>"); labelText.append("<FONT COLOR='#b4b4b6' FONT SIZE=4>Proseguire solo se si è effettivamente certi della scelta.</p>"); labelText.append("</b></P>"); //QLabel label->setText(labelText); msgBox->setText(labelText); msgBox->setWindowModality(Qt::NonModal); //labelText = "<FONT COLOR='#E0E0E0' FONT SIZE=3><br><br><br><br><br><br><br><p><center><b>N.B.: <FONT COLOR='#408fdd' FONT SIZE=2><u>"; labelText = "<FONT COLOR='#E0E0E0' FONT SIZE=4><br><br><br><br><br><br><br><br><br><br><br><p><center><b><b><br><br><br>N.B.: <FONT COLOR='#b4b4b6' FONT SIZE=3><u>"; if (Sys_language == "IT") { //msgBox->setInformativeText(labelText); //labelText.append("Al termine, i dati precedenti verranno sovrascritti."); if (classifier!="") labelText.append("Su questa macchina risulta già effettuata una sessione di training."); else labelText.append("Non risultano al momento effettuate altre sessioni di enrollment."); } else //msgBox->setInformativeText("All previous data won't be removed"); labelText.append("Take attention: previous data will be removed"); labelText.append("</u></center></p></b>"); msgBox->setInformativeText(labelText); QIcon icon("resources/icons/trainer.ico"); msgBox->setWindowIcon(icon); msgBox->setWindowModality(Qt::NonModal); msgBox->setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); msgBox->setDefaultButton(QMessageBox::Ok); if (Sys_language == "IT") msgBox->setWindowTitle("SISTEMA DI TRAINING FACCIALE"); else msgBox->setWindowTitle("FACE TRAINING SYSTEM"); //msgBox->setIcon(QMessageBox::Question); //msgBox->setIconPixmap(QPixmap("resources/icons/QA.png")); msgBox->setIconPixmap(QPixmap("resources/icons/Face-scanning.jpg")); //msgBox->setStyle(QStyleFactory::create("Fusion")); //msgBox->setIcon(QMessageBox::Question); msgBox->setStyle(QStyleFactory::create("Fusion")); //msgBox->setFixedSize(542, 503); //msgBox->move((window_w-message.width())/2,(window_h-message.height())/2); QPalette darkPalette; darkPalette.setColor(QPalette::Window, QColor(53, 53, 53)); darkPalette.shadow(); darkPalette.setColor(QPalette::Button, QColor(53, 53, 53)); darkPalette.setColor(QPalette::ButtonText, QColor(42, 130, 218)); darkPalette.setColor(QPalette::WindowText, Qt::white); //qApp->setStyleSheet("QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }"); qApp->setPalette(darkPalette); msgBox->setStyleSheet("QToolTip { }"); //msgBox->setPalette(darkPalette); //qApp->setStyleSheet("QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }"); return msgBox; } inline QMessageBox * QtMessageBoxCreatorInstructions() { QMessageBox *msgBox = new QMessageBox(0); //char all[100]; //sprintf(all,"CASCADE NON TROVATO: %s\n",classifier); QString labelText = "<P><b><center><FONT COLOR='#E0E0E0' FONT SIZE=4><br><br>"; labelText.append("FACE AUTHNTICATION SYSTEM "); labelText.append("<br><br><FONT SIZE=3 FONT COLOR= '#5ddffe'><u>"); labelText.append("Note per il corretto utilizzo:</u></center>"); labelText.append("<br><br><br>"); labelText.append("<b><FONT COLOR='#b8fffc' FONT SIZE=4>"); //labelText.append("<b><FONT COLOR='#5ddffe' FONT SIZE=4>"); labelText.append("<ul>"); labelText.append("<li><p align='justify'>Nel corso del count-down posizonarsi al meglio all'interno della finestra.</li>"); labelText.append("<li><p align='justify'>Nel caso ci si posizioni ad una distanza non corretta il count-down verrà sospeso e la procedura non potrà avere inizio sino al corretto riposizionamento del volto.</li>"); labelText.append("<li><p align='justify'>Al temine del count-down, verrà avviata la fase di scanning del volto. L'intera pocedura durerà solo pochi secondi. Si consiglia di mantenere la posizione assunta durante il count-down per l'intera durata del processo.</li>"); labelText.append("<li><p align='justify'>Si consiglia di rimanere sempre al centro dell'immagine video.</li>"); labelText.append("<li><p align='justify'><u><FONT COLOR= '#5ddffe'><strong>Lo sguardo deve unicamente essere rivolto verso l'obiettivo della camera e non sull'immagine visibile a schermo.</strong></u></li>"); labelText.append("<li><p align='justify'><FONT COLOR='#b8fffc'>Nella fase di scanning, nel caso si assuma inavvertitamente una posizione non corretta la procerdura verrà momentaneamente sospesa sino al corretto riposizionamento.</li>"); labelText.append("<li><p align='justify'>E' possibile interrompere in qualsiasi momento la procedura tenendo premuto il tasto ESC sulla tastiera.</li>"); labelText.append("</ul></p>"); //labelText.append("</center></P></b><b><br><br><br><br><br><br><FONT COLOR='#E0E0E0'>"); labelText.append("</center></P></b><b><br>"); labelText.append("</b></P>"); //QLabel label->setText(labelText); msgBox->setText(labelText); msgBox->setWindowModality(Qt::NonModal); //labelText = "<FONT COLOR='#408fdd' FONT SIZE=3><br><br><br><br><br><br><br><p><center><b>N.B.: <FONT COLOR='#408fdd' FONT SIZE=3><u>"; labelText = "<FONT COLOR='#E0E0E0' FONT SIZE=3><br><br><br><br><p><center><b>N.B.: <FONT COLOR='#5ddffe' FONT SIZE=3><u>"; if (Sys_language == "IT") { //msgBox->setInformativeText(labelText); labelText.append("La pocedura può essere ripetuta in qualsiasi momento"); } else //msgBox->setInformativeText("All previous data won't be removed"); labelText.append("Take attention: previous data will be removed"); labelText.append("</u></center></p></b><br><br>"); msgBox->setInformativeText(labelText); QIcon icon("resources/icons/trainer.ico"); msgBox->setWindowIcon(icon); msgBox->setWindowModality(Qt::NonModal); msgBox->setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel | QMessageBox::Discard); msgBox->setDefaultButton(QMessageBox::Ok); if (Sys_language == "IT") msgBox->setWindowTitle("SISTEMA DI TRAINING FACCIALE"); else msgBox->setWindowTitle("FACE TRAINING SYSTEM"); //msgBox->setIcon(QMessageBox::Question); //msgBox->setIconPixmap(QPixmap("resources/icons/QA.png")); msgBox->setIconPixmap(QPixmap("resources/icons/a.png")); //msgBox->setStyle(QStyleFactory::create("Fusion")); //msgBox->setIcon(QMessageBox::Question); msgBox->setStyle(QStyleFactory::create("Fusion")); //msgBox->setFixedSize(542, 503); //msgBox->move((window_w-message.width())/2,(window_h-message.height())/2); QPalette darkPalette; darkPalette.setColor(QPalette::Window, QColor(53, 53, 53)); darkPalette.shadow(); darkPalette.setColor(QPalette::Button, QColor(53, 53, 53)); darkPalette.setColor(QPalette::ButtonText, QColor(42, 130, 218)); darkPalette.setColor(QPalette::WindowText, Qt::white); //qApp->setStyleSheet("QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }"); qApp->setPalette(darkPalette); msgBox->setStyleSheet("QToolTip { }"); //msgBox->setPalette(darkPalette); //qApp->setStyleSheet("QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }"); return msgBox; } inline QMessageBox * QtMessageBoxCreatorErrorTrainRequestAlreadyDone(const char * classifier) { QMessageBox *msgBox = new QMessageBox(0); //char all[100]; //sprintf(all,"CASCADE NON TROVATO: %s\n",classifier); QString labelText = "<P><b><center><FONT COLOR='#E0E0E0'<br><br>"; labelText.append("FACE AUTHNTICATION SYSTEM "); labelText.append("</center></P></b><b><br><br><br><br><br><br><FONT COLOR='#E0E0E0'>"); labelText.append("Prima di iniziare è necessario effettuare una sessione di training."); labelText.append("</b></P>"); //QLabel label->setText(labelText); msgBox->setText(labelText); msgBox->setWindowModality(Qt::NonModal); labelText = "<FONT COLOR='#E0E0E0' FONT SIZE=3><br><br><br><br><br><br><br><p><center>N.B.: <u><b>"; if (Sys_language == "IT") { //msgBox->setInformativeText(labelText); labelText.append("Non risultano al momento effettuate altre sessioni di enrollment"); } else //msgBox->setInformativeText("All previous data won't be removed"); labelText.append("Take attention: previous data will be removed"); labelText.append("</u></center></p></b>"); msgBox->setInformativeText(labelText); QIcon icon("resources/icons/trainer.ico"); msgBox->setWindowIcon(icon); msgBox->setWindowModality(Qt::NonModal); msgBox->setStandardButtons(QMessageBox::Ok | QMessageBox::Cancel); msgBox->setDefaultButton(QMessageBox::Ok); if (Sys_language == "IT") msgBox->setWindowTitle("SISTEMA DI TRAINING FACCIALE"); else msgBox->setWindowTitle("FACE TRAINING SYSTEM"); //msgBox->setIcon(QMessageBox::Question); msgBox->setIconPixmap(QPixmap("resources/icons/QA.png")); //msgBox->setStyle(QStyleFactory::create("Fusion")); //msgBox->setIcon(QMessageBox::Question); msgBox->setStyle(QStyleFactory::create("Fusion")); //msgBox->setFixedSize(542, 503); //msgBox->move((window_w-message.width())/2,(window_h-message.height())/2); QPalette darkPalette; darkPalette.setColor(QPalette::Window, QColor(53, 53, 53)); darkPalette.shadow(); darkPalette.setColor(QPalette::Button, QColor(53, 53, 53)); darkPalette.setColor(QPalette::ButtonText, QColor(42, 130, 218)); darkPalette.setColor(QPalette::WindowText, Qt::white); //qApp->setStyleSheet("QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }"); qApp->setPalette(darkPalette); msgBox->setStyleSheet("QToolTip { }"); //msgBox->setPalette(darkPalette); //qApp->setStyleSheet("QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }"); return msgBox; } inline QMessageBox * QtMessageBoxCreatorTrainCompleted() { QMessageBox *msgBox = new QMessageBox(0); //QString labelText = "<FONT COLOR = '#009245'><h2><br><p><center>"; QString labelText = ""; if (Sys_language == "IT") { //labelText.append(" Premere ok per terminare... "); labelText.append("<FONT SIZE=5 FONT COLOR= '#E0E0E0'><u><b><center>Training completato con successo.</center></b></u>"); labelText.append("<br><br><FONT SIZE=4 FONT COLOR= '#E0E0E0'><br><br><br><p align='justify'><b>Da ora è possible autentcarsi nel sistema con l'applicativo apposito.<br><br>"); labelText.append("<br><FONT SIZE=4 FONT COLOR= '#9bbfd9'><b>In caso non si siano seguite le indicazioni d'uso elencate nella grafica iniziale di disclaimer o si ritenga vi siano intercorsi degli errori nel corso della procedura di enrollment o, semplicemente, non si sia sodidsfatti dell'operato del recognizer, è possibile ripetere la sessione di training appena conclusasi in qualsiasi momento.</b></p>"); labelText.append("<br>"); } else { //labelText.append(" Press ok for exiting... "); labelText.append(" Training data successfully ended... "); } labelText.append(""); msgBox->setInformativeText(labelText); /* if (Sys_language=="IT"){ msgBox->setText(classifier); msgBox->setInformativeText("\n\n Premere ok per terminare...\n"); }else{ msgBox->setText("T R A I N I N G C O M P L E T E D !"); msgBox->setInformativeText("\n\nPress ok button for exiting..."); } */ msgBox->setWindowModality(Qt::NonModal); msgBox->setStandardButtons(QMessageBox::Ok); msgBox->setDefaultButton(QMessageBox::No); //c("SISTEMA DI TRAINING"); QIcon icon("resources/icons/trainer.ico"); msgBox->setWindowIcon(icon); //msgBox->setIconPixmap(QPixmap("resources/icons/QA.png")); msgBox->setIconPixmap(QPixmap("resources/icons/nec-facialrecognition.jpg")); msgBox->setStyle(QStyleFactory::create("Fusion")); msgBox->setStyle(QStyleFactory::create("Fusion")); //msgBox->setFixedSize(542, 503); //msgBox->move((window_w-message.width())/2,(window_h-message.height())/2); QPalette darkPalette; darkPalette.setColor(QPalette::Window, QColor(53, 53, 53)); darkPalette.shadow(); darkPalette.setColor(QPalette::Button, QColor(53, 53, 53)); darkPalette.setColor(QPalette::ButtonText, QColor(42, 130, 218)); darkPalette.setColor(QPalette::WindowText, Qt::white); //qApp->setStyleSheet("QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }"); qApp->setPalette(darkPalette); msgBox->setStyleSheet("QToolTip { }"); //msgBox->setPalette(darkPalette); //qApp->setStyleSheet("QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }"); return msgBox; } inline QMessageBox* QtMessageBox_SetupNotDone(const char * classifier) { //char buffer [50]; //int n, a=5, b=3; //n=sprintf (buffer, "%d plus %d is %d", a, b, a+b); QMessageBox *msgBox = new QMessageBox(0); //const char cascade[]="resources\eye_left_18x12.xml"; QString labelText; labelText.append("<P><b><center><FONT COLOR='#cc0000' FONT SIZE = 5><u>ATTENZIONE:</u><br><br></b></P></center>"); labelText.append("<P><b><FONT COLOR='#ffffff' FONT SIZE = 4>"); labelText.append(classifier); labelText.append("</P></b>"); msgBox->setText(labelText); //msgBox->setInformativeText("\n\nScegliere No per cambiare directory..."); msgBox->setWindowModality(Qt::NonModal); labelText = "<br><br>N:B.:&emsp;&emsp; <FONT COLOR='#ffff00'><u>Eseguire l'apposita applicazione di setup e rieseguire il programma</u>"; msgBox->setInformativeText(labelText); //msgBox->setStandardButtons(QMessageBox::Escape); //QSpacerItem* horizontalSpacer = new QSpacerItem(1000, 0, QSizePolicy::Minimum, QSizePolicy::Expanding); //QGridLayout* layout = (QGridLayout*)msgBox->layout(); //layout->addItem(horizontalSpacer, layout->rowCount(), 0, 1, layout->columnCount()); //msgBox->setBaseSize(QSize(600, 520)); //msgBox->setFixedSize ( 500,500); msgBox->setStandardButtons(QMessageBox::Ok); //msgBox->setDefaultButton(QMessageBox::Ok); QIcon icon(("files" + back_slash + "trainer.ico").c_str()); msgBox->setWindowIcon(icon); msgBox->setWindowTitle("ERRORE IRREVERSIBILE"); msgBox->setIcon(QMessageBox::Critical); msgBox->setStyle(QStyleFactory::create("Fusion")); msgBox->setFixedSize(542, 503); //msgBox->move((window_w-message.width())/2,(window_h-message.height())/2); QPalette darkPalette; darkPalette.setColor(QPalette::Window, QColor(53, 53, 53)); darkPalette.shadow(); darkPalette.setColor(QPalette::Button, QColor(53, 53, 53)); darkPalette.setColor(QPalette::ButtonText, QColor(42, 130, 218)); darkPalette.setColor(QPalette::WindowText, Qt::white); //qApp->setStyleSheet("QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }"); qApp->setPalette(darkPalette); msgBox->setStyleSheet("QToolTip { }"); //msgBox->setPalette(darkPalette); //qApp->setStyleSheet("QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }"); return msgBox; } inline int messageBox(const char * classifier, int type, int argc, char** argv) { //QApplication app(argc, argv); QMessageBox * msgBox = NULL; //QIcon icon("resources/icons/success.png"); if (type == 0 || type == 1) { if (Sys_language == "IT") { msgBox = QtMessageBoxCreatorErrorCascadeOrWebcam(classifier, type); FileLoggingITA(Data, Time, type, classifier); } else if (Sys_language == "EN") FileLoggingENG(Data, Time, type, classifier); } else if (type == 2) msgBox = QtMessageBoxCreatorErrorTrainRequest(classifier); else if (type == 6) { msgBox = QtMessageBoxCreatorErrorTrainRequestAlreadyDone(""); myUtils::playSound("bell.wav"); } else if (type == 7) { msgBox = QtMessageBoxCreatorInstructions(); myUtils::playSound("bell.wav"); } else if (type == 3) { msgBox = QtMessageBoxCreatorTrainCompleted(); if (Sys_language == "IT") FileLoggingITA(Data, Time, type, classifier); else if (Sys_language == "EN") FileLoggingENG(Data, Time, type, classifier); } if (type == 0 || type == 1) //system("aplay resources/sounds/dialog-error.wav --quiet"); myUtils::playSound("bell.wav"); else if (type == 2) //system("aplay resources/sounds/dialog-question.wav --quiet"); myUtils::playSound("bell.wav"); else if (type == 3) //system("aplay resources/sounds/bell.wav --quiet"); //myUtils::playSound("bell.wav"); myUtils::playSound("end.wav",1); else if (type == 5) { msgBox = QtMessageBox_SetupNotDone(classifier); myUtils::playSound("bell.wav"); } int ret = msgBox->exec(); return ret; } #endif
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*- * * Copyright (C) 1995-2011 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #include "modules/logdoc/src/html5/html5tokenbuffer.h" void HTML5TokenBuffer::ResetL() { Clear(); if (m_buffer_length > m_initial_size) FreeBuffer(); EnsureCapacityL(m_initial_size); } void HTML5TokenBuffer::TakeOver(HTML5TokenBuffer& take_over_from) { OP_ASSERT(!m_buffer && !m_buffer_length); m_buffer = take_over_from.m_buffer; m_buffer_length = take_over_from.m_buffer_length; m_used = take_over_from.m_used; m_hash_base = take_over_from.m_hash_base; m_hash_value = take_over_from.m_hash_value; // Set the other buffer to be empty take_over_from.m_buffer = NULL; take_over_from.m_buffer_length = take_over_from.m_used = 0; } void HTML5TokenBuffer::CopyL(const HTML5TokenBuffer *copy_from) { uni_char *new_buf = OP_NEWA_L(uni_char, copy_from->m_used + 1); op_memcpy(new_buf, copy_from->m_buffer, UNICODE_SIZE(copy_from->m_used)); OP_DELETEA(m_buffer); m_buffer = new_buf; m_used = copy_from->m_used; m_buffer_length = m_used + 1; m_buffer[m_used] = 0; // termination, doesn't count as used. m_hash_value = copy_from->m_hash_value; } void HTML5TokenBuffer::AppendL(const uni_char *str, unsigned str_len) { EnsureCapacityL(str_len); op_memcpy(m_buffer + m_used, str, UNICODE_SIZE(str_len)); m_used += str_len; } void HTML5TokenBuffer::GrowL(unsigned added_length) { unsigned new_size = MAX(m_used + added_length, m_buffer_length + m_initial_size); uni_char *new_buf = OP_NEWA_L(uni_char, new_size); op_memcpy(new_buf, m_buffer, m_used * sizeof(uni_char)); OP_DELETEA(m_buffer); m_buffer = new_buf; m_buffer_length = new_size; }
#include <algorithm> #include <cassert> #include <iostream> #include <string> #include <vector> template <typename T> class Matrix { public: Matrix(T n, T m) : n(n), m(m), mat(n, std::vector<T>(m)) { // Do nothing. } Matrix(const Matrix<T>& matrix) : n(matrix.n), m(matrix.m), mat(matrix.mat) { // Do nothing. } Matrix<T> operator*(const Matrix<T>& rhs) { assert(m == rhs.n); Matrix<T> result(n, rhs.m); for (int i = 0; i < n; ++i) { for (int j = 0; j < rhs.m; ++j) { result.mat[i][j] = 0; for (int k = 0; k < m; ++k) { result.mat[i][j] += mat[i][k] * rhs.mat[k][j]; } } } return result; } Matrix<T> operator+(const Matrix<T>& rhs) const { assert(m == rhs.m && n == rhs.n); Matrix<T> result(n, m); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { result.mat[i][j] = mat[i][j] + rhs.mat[i][j]; } } return result; } Matrix<T>& operator%=(T rhs) { for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { mat[i][j] %= rhs; } } return *this; } template <typename U> friend std::ostream& operator<<(std::ostream& os, const Matrix<U>& mat) { for (int i = 0; i < mat.n; ++i) { for (int j = 0; j < mat.m; ++j) { std::cout << mat.mat[i][j] << ' '; } std::cout << '\n'; } return os; } T n, m; std::vector<std::vector<T>> mat; }; int main() { std::ios_base::sync_with_stdio(false); std::cin.tie(0); std::cout.tie(0); int n, m; std::cin >> n >> m; Matrix a(n, m), b(n, m); for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { std::cin >> a.mat[i][j]; } } for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { std::cin >> b.mat[i][j]; } } std::cout << a + b << '\n'; return 0; }
#pragma once #include <math.h> #include "STDUNC.h" struct mat4 { mat4 (); mat4 (float a, float b, float c, float d, float e, float f, float g, float h, float i, float j, float k, float l, float mm, float n, float o, float p);/* vec4 operator* (const vec4& rhs);*/ mat4 operator* (const mat4& rhs); /*mat4& operator= (const mat4& rhs);*/ float m[16]; }; /* struct vec3 { vec3 (); vec3 (float x, float y, float z); void normalize(); float v[3]; }; struct vec2 { vec2(); vec2(float x, float y); vec2(vec2&); bool operator== (vec2&); float dot(vec2); float dot(float x, float y); void normalize(); float x; float y; }; */ class MatMath { public: MatMath(void); ~MatMath(void); static mat4 identity_mat4(); static mat4 zero_mat4 (); static mat4 translate(const mat4& m, const vec3& v); static float dot(float x1, float y1, float z1, float x2, float y2, float z2); };
#pragma once #include "TreeNode.h" #include <iostream> #include <stack> #include <vector> using namespace std; class BinarySearchTree { friend class TransferWindowManager; private: TreeNode * m_root; vector<SoccerPlayerData> v; public: BinarySearchTree() { m_root = NULL; } ~BinarySearchTree() { deleteTree(m_root); } void insert(SoccerPlayerData& data); void deletion(int ability); // ability = key void deleteTree(TreeNode* node) { if (node) { deleteTree(node->m_left); deleteTree(node->m_right); delete node; } } static void inorder(TreeNode* node) { if (node) { inorder(node->m_left); cout << node; inorder(node->m_right); } } friend std::ostream& operator<<(std::ostream& os, const BinarySearchTree& tree) { TreeNode* root = tree.m_root; inorder(root); return os; //stack<TreeNode*> s; //TreeNode* curr = tree.m_root; //while (true) //{ // // Search leftmost node and push node // // L // while (curr != NULL) // { // s.push(curr); // curr = curr->getLeftNode(); // } // // Execute, if element exists in stack // if (!s.empty()) // { // // curr = leftmost node // curr = s.top(); // s.pop(); // // V // os << curr; // // R // curr = curr->getRightNode(); // } // else // break; //} } void print_v(); };
#include "treeface/scene/Scene.h" #include "treeface/scene/guts/Scene_guts.h" #include "treeface/scene/Geometry.h" #include "treeface/scene/GeometryManager.h" #include "treeface/scene/SceneNode.h" #include "treeface/scene/SceneNodeManager.h" #include "treeface/misc/Errors.h" #include "treeface/misc/PropertyValidator.h" #include "treeface/base/PackageManager.h" #include <treecore/AlignedMalloc.h> #include "treeface/graphics/ImageManager.h" #include "treeface/scene/MaterialManager.h" #include "treeface/base/PackageManager.h" #include <treecore/DynamicObject.h> #include <treecore/RefCountHolder.h> #include <treecore/JSON.h> #include <treecore/MemoryBlock.h> #include <treecore/NamedValueSet.h> #include <treecore/Result.h> #include <treecore/RefCountSingleton.h> #include <treecore/Variant.h> using namespace treecore; namespace treeface { Scene::Scene( GeometryManager* geo_mgr, MaterialManager* mat_mgr ) : m_guts( new Guts() ) { m_guts->geo_mgr = geo_mgr != nullptr ? geo_mgr : new GeometryManager(); m_guts->mat_mgr = mat_mgr != nullptr ? mat_mgr : new MaterialManager(); m_guts->node_mgr = new SceneNodeManager( m_guts->geo_mgr, m_guts->mat_mgr ); } Scene::Scene( const treecore::var& root, GeometryManager* geo_mgr, MaterialManager* mat_mgr ) : m_guts( new Guts() ) { m_guts->geo_mgr = geo_mgr != nullptr ? geo_mgr : new GeometryManager(); m_guts->mat_mgr = mat_mgr != nullptr ? mat_mgr : new MaterialManager(); m_guts->node_mgr = new SceneNodeManager( m_guts->geo_mgr, m_guts->mat_mgr ); build( root ); } Scene::Scene( const treecore::String& data_name, GeometryManager* geo_mgr, MaterialManager* mat_mgr ): m_guts( new Guts() ) { m_guts->geo_mgr = geo_mgr != nullptr ? geo_mgr : new GeometryManager(); m_guts->mat_mgr = mat_mgr != nullptr ? mat_mgr : new MaterialManager(); m_guts->node_mgr = new SceneNodeManager( m_guts->geo_mgr, m_guts->mat_mgr ); var data_root = PackageManager::getInstance()->get_item_json( data_name ); if (!data_root) throw ConfigParseError( "no package item named \"" + data_name + "\"" ); build( data_root ); } Scene::~Scene() { if (m_guts) delete m_guts; } SceneNode* Scene::get_root_node() noexcept { return m_guts->root_node.get(); } SceneNode* Scene::get_node( const treecore::String& name ) noexcept { return m_guts->node_mgr->get_node( name ); } GeometryManager* Scene::get_geometry_manager() noexcept { return m_guts->geo_mgr.get(); } MaterialManager* Scene::get_material_manager() noexcept { return m_guts->mat_mgr.get(); } const Vec4f& Scene::get_global_light_color() const noexcept { return m_guts->global_light_color; } void Scene::set_global_light_color( float r, float g, float b, float a ) noexcept { m_guts->global_light_color.set( r, g, b, a ); } void Scene::set_global_light_color( const Vec4f& value ) noexcept { m_guts->global_light_color = value; } const Vec4f& Scene::get_global_light_direction() const noexcept { return m_guts->global_light_direction; } void Scene::set_global_light_direction( float x, float y, float z ) noexcept { m_guts->global_light_direction.set( x, y, z, 0 ); m_guts->global_light_direction.normalize(); } void Scene::set_global_light_direction( const Vec4f& value ) noexcept { m_guts->global_light_direction = value; m_guts->global_light_direction.normalize(); } const Vec4f& Scene::get_global_light_ambient() const noexcept { return m_guts->global_light_ambient; } void Scene::set_global_light_ambient( float r, float g, float b, float a ) noexcept { m_guts->global_light_ambient.set( r, g, b, a ); } void Scene::set_global_light_ambient( const Vec4f& value ) noexcept { m_guts->global_light_ambient = value; } #define KEY_GLOBAL_LIGHT_DIRECTION "global_light_direction" #define KEY_GLOBAL_LIGHT_COLOR "global_light_color" #define KEY_GLOBAL_LIGHT_AMB "global_light_ambient" #define KEY_NODES "nodes" struct ScenePropertyValidator: public PropertyValidator, public RefCountSingleton<ScenePropertyValidator> { public: ScenePropertyValidator() { add_item( KEY_GLOBAL_LIGHT_DIRECTION, PropertyValidator::ITEM_ARRAY, false ); add_item( KEY_GLOBAL_LIGHT_COLOR, PropertyValidator::ITEM_ARRAY, false ); add_item( KEY_GLOBAL_LIGHT_AMB, PropertyValidator::ITEM_ARRAY, false ); add_item( KEY_NODES, PropertyValidator::ITEM_ARRAY, true ); } virtual ~ScenePropertyValidator() {} }; void Scene::build( const treecore::var& root ) { // // validate root node // if ( !root.isObject() ) throw ConfigParseError( "Scene: root node is not KV" ); const NamedValueSet& root_kv = root.getDynamicObject()->getProperties(); { Result re = ScenePropertyValidator::getInstance()->validate( root_kv ); if (!re) throw ConfigParseError( "Scene: property validation failed\n" + re.getErrorMessage() ); } // // load properties // // direction of global light if ( root_kv.contains( KEY_GLOBAL_LIGHT_DIRECTION ) ) { Array<var>* values = root_kv[KEY_GLOBAL_LIGHT_DIRECTION].getArray(); if (values->size() != 4) throw ConfigParseError( "Scene: global light direction is not an array of 4 values" ); m_guts->global_light_direction.set( float( (*values)[0] ), float( (*values)[1] ), float( (*values)[2] ), float( (*values)[3] ) ); } // color of global light if ( root_kv.contains( KEY_GLOBAL_LIGHT_COLOR ) ) { Array<var>* values = root_kv[KEY_GLOBAL_LIGHT_COLOR].getArray(); if (values->size() != 4) throw ConfigParseError( "Scene: global light color is not an array of 4 values" ); m_guts->global_light_color.set( float( (*values)[0] ), float( (*values)[1] ), float( (*values)[2] ), float( (*values)[3] ) ); } // global light intensities if ( root_kv.contains( KEY_GLOBAL_LIGHT_AMB ) ) { Array<var>* values = root_kv[KEY_GLOBAL_LIGHT_AMB].getArray(); if (values->size() != 4) throw ConfigParseError( "Scene: global light ambient is not an array of 4 values" ); m_guts->global_light_ambient.set( float( (*values)[0] ), float( (*values)[1] ), float( (*values)[2] ), float( (*values)[3] ) ); } // scene graph Array<var>* scenenode_nodes = root_kv[KEY_NODES].getArray(); for (int i = 0; i < scenenode_nodes->size(); i++) { const var& scenenode_data = (*scenenode_nodes)[i]; SceneNode* node = m_guts->node_mgr->add_nodes( scenenode_data );; m_guts->root_node->add_child( node ); } } } // namespace treeface
# include<iostream> #include <vector> using namespace std; int gcd (int a, int b) { if (a==b) return (a); if (a>b) return (gcd(a-b,b)); return (gcd(b-a,a)); } void swap( int *a, int *b) { int temp = *a; *a = *b; *b = temp; } void print_array(vector<int> &a) { for (int i = 0; i < a.size(); i++) { cout << a[i] << " "; } cout << endl; } class rotate_array { int find_pivot (vector<int> &a) { int l = 0, h = a.size()-1; int mid; while(1) { mid = (l+h)/2; if (a[mid] > a[mid+1]) { return mid; } else if (a[mid] < a[l]) { h = mid; } else if (a[mid] > a[h]) { l = mid; } else { break; } } return (a.size()-1); } public: int search (vector<int> &a, int l, int h, int target) { if (h < l) return (-1); int mid = (l+h)/2; if (a[mid] == target) { return (mid); } else if (a[l] < a[mid]) { if (a[l] <= target && a[mid] > target) { return search(a, l, mid-1, target); } else { return search(a, mid+1, h, target); } } else if (a[mid] < a[h]) { if (a[mid] < target && a[h] >= target) { return search(a, mid+1, h, target); } else { return search(a, l, mid-1, target); } } else { if (a[l] == a[mid] && a[mid] != a[h]) { return search(a, mid+1, h, target); } int t1 = search(a, l, mid-1, target); int t2 = search(a, mid+1, h, target); if (t1 >= 0 || t2 >= 0) return (1); return (-1); } return (-1); } bool sum (vector<int> &a, int target) { int pivot = find_pivot(a); int l = pivot+1, h = pivot, numsize = a.size(); while(l!=h) { if (l > numsize) l = l-numsize; if (h<0) h = h+numsize; if (a[l] + a[h] == target) { return (1); } else if (a[l] + a[h] < target) { l++; } else { h--; } } return (0); } void split_and_add_back (vector<int> &a, int k) // juggling algo { int sets = gcd(a.size(), k); cout << "GCD of " << a.size() << " and " << k << " is " << sets << endl; for (int i = 0; i < sets; i++) { int j = i, temp = a[j]; for (; ;) { int d = j + k; if (d > a.size()-1) { d = d - a.size(); } if (d == i) break; a[j] = a[d]; j = d; } a[j] = temp; } } void split_and_add_back (vector<int> &a, int k, int i) // reversal algo { cout << "Using reversal algo" << endl; for (int i = 0, j = a.size()-1; j >= i; i++, j--) { swap(&a[i], &a[j]); } //this->print_array(a); for (int i = 0, j = a.size()-1-k; j >= i; i++, j--) { swap(&a[i], &a[j]); } for (int i = a.size()-k, j = a.size()-1; j >= i; i++, j--) { swap(&a[i], &a[j]); } } }; class rearrange { public: void index_as_value_at_index (vector<int> &a) { int arr_size = a.size(); sort(a.begin(), a.end()); for (int i = 0, j = 0; i < arr_size && j < arr_size; ) { if (a[j] == i) { a[i] = i; i++; j++; } if (a[j] > i) { a[i] = -1; i++; } if (a[j] < i) { j++; } } } void index_as_value_at_index (vector<int> &a, int k) { int i = 0; while (i < a.size()) { if (a[i] != -1 && a[i] != i) { a[a[i]] = a[i]; a[i] = -1; } i++; } } void larger_even_smaller_odd (vector<int> &a) { vector<int> arr = a; sort(arr.begin(), arr.end()); //print_array(arr); int even_index = a.size() - a.size()/2; for (int i = 1; i < arr.size(); i+=2) { a[i] = arr[even_index++]; } int odd_index = a.size() - a.size()/2 - 1; for (int i = 0; i < arr.size(); i+=2) { a[i] = arr[odd_index--]; } return; } void alternate_pos_neg (vector<int> &a) { int j = -1; for (int i = 0; i < a.size(); i++) { if (a[i] >= 0) { swap(&a[++j], &a[i]); } } int pivot = j; cout << "After modified partition" << endl; print_array(a); for (int i = 1, j = a.size()-1; i <= pivot ; i+=2, j--) { swap(&a[i], &a[j]); } return; } void alternate_pos_neg (vector<int> &a, int k) { for (int i = 0; i < a.size(); i++) { if (i%2 == 0 && a[i] >= 0) { // element misplaced int j; for (j = i+1; j < a.size() && a[j] >=0; j++); if (j >= a.size()) break; int temp = a[j]; while(j!=i) { a[j] = a[j-1]; j--; } a[j] = temp; } else if (i%2 && a[i] < 0) { int j; for (j = i+1; j < a.size() && a[j] < 0; j++); int temp = a[j]; while (j!=i) { a[j] = a[j-1]; j--; } a[j] = temp; } } return; } void move_zeros_to_end (vector<int> &a) { int zero_iter = -1; for (int i = 0; i < a.size(); i++) { if (a[i] != 0) { swap(&a[i], &a[++zero_iter]); } } return; } int swaps_to_bring_elems_together (vector<int> &a, int k) { /* Find number of elements to chunk together */ int chunk = 0; for (int i = 0; i < a.size(); i++) { if (a[i] <= k) chunk++; } /* Establish baseline in the first window */ int greater = 0; for (int i = 0; i < chunk; i++) { if (a[i] > k) greater++; } int min_swaps = greater; /* Now move the sliding windown to find the min value of greater */ for (int i = 1, j = i + chunk; j < a.size(); i++, j++) { if (a[i-i] <= k) greater--; if (a[j] <= k) greater++; if (min_swaps < greater) min_swaps = greater; } return (min_swaps); } }; int main () { int arr_help[] = {4,5,6,8,9,10}; vector<int> arr (arr_help, arr_help + sizeof(arr_help)/sizeof(int)); rotate_array r; //cout << r.search(arr, 0, arr.size()-1, 3); /* cout << "Sum found "; if (r.sum(arr, 16)) { cout << "Yes" << endl; } else { cout << "No" << endl; } */ r.split_and_add_back(arr, 2,1); print_array(arr); cout << "Rearrangement problems begin " << endl; rearrange re; int arr_help1[] = {1,9,8,4,0,0,2,7,0,6,0}; vector<int> arr1(arr_help1, arr_help1 + sizeof(arr_help1)/sizeof(int)); //re.index_as_value_at_index(arr1, 1); //re.larger_even_smaller_odd (arr1); //re.alternate_pos_neg(arr1,1); re.move_zeros_to_end(arr1); print_array(arr1); return (0); }
#include<stdio.h> int main(){ int n,sum=1; scanf("%d",&n); for(int i=1;i<=n;i++) sum=sum*i; printf("%d\n",sum); }
/**************************************************************************/ /* */ /* Copyright (c) 2013-2022 Orbbec 3D Technology, Inc */ /* */ /* PROPRIETARY RIGHTS of Orbbec 3D Technology are involved in the */ /* subject matter of this material. All manufacturing, reproduction, use, */ /* and sales rights pertaining to this subject matter are governed by the */ /* license agreement. The recipient of this software implicitly accepts */ /* the terms of the license. */ /* */ /**************************************************************************/ #include "astra_camera/ob_camera_node.h" namespace astra_camera { void OBCameraNode::setupCameraCtrlServices() { for (const auto& stream_index : IMAGE_STREAMS) { if (!enable_[stream_index] || !device_->hasSensor(stream_index.first)) { ROS_INFO_STREAM("Stream " << stream_name_[stream_index] << " is disabled"); continue; } auto stream_name = stream_name_[stream_index]; std::string service_name = "get_" + stream_name + "_exposure"; get_exposure_srv_[stream_index] = nh_.advertiseService<GetInt32Request, GetInt32Response>( service_name, [this, stream_index = stream_index](auto&& request, auto&& response) { response.success = this->getExposureCallback(request, response, stream_index); return response.success; }); service_name = "set_" + stream_name + "_exposure"; set_exposure_srv_[stream_index] = nh_.advertiseService<SetInt32Request, SetInt32Response>( service_name, [this, stream_index = stream_index](auto&& request, auto&& response) { response.success = this->setExposureCallback(request, response, stream_index); return response.success; }); service_name = "get_" + stream_name + "_gain"; get_gain_srv_[stream_index] = nh_.advertiseService<GetInt32Request, GetInt32Response>( service_name, [this, stream_index = stream_index](auto&& request, auto&& response) { response.success = this->getGainCallback(request, response, stream_index); return response.success; }); service_name = "set_" + stream_name + "_gain"; set_gain_srv_[stream_index] = nh_.advertiseService<SetInt32Request, SetInt32Response>( service_name, [this, stream_index = stream_index](auto&& request, auto&& response) { response.success = this->setGainCallback(request, response, stream_index); return response.success; }); service_name = "set_" + stream_name + "_mirror"; set_mirror_srv_[stream_index] = nh_.advertiseService<std_srvs::SetBoolRequest, std_srvs::SetBoolResponse>( service_name, [this, stream_index = stream_index](auto&& request, auto&& response) { response.success = this->setMirrorCallback(request, response, stream_index); return response.success; }); service_name = "set_" + stream_name + "_auto_exposure"; set_auto_exposure_srv_[stream_index] = nh_.advertiseService<std_srvs::SetBoolRequest, std_srvs::SetBoolResponse>( service_name, [this, stream_index = stream_index](auto&& request, auto&& response) { response.success = this->setAutoExposureCallback(request, response, stream_index); return response.success; }); service_name = "toggle_" + stream_name; toggle_sensor_srv_[stream_index] = nh_.advertiseService<std_srvs::SetBoolRequest, std_srvs::SetBoolResponse>( service_name, [this, stream_index = stream_index](auto&& request, auto&& response) { response.success = this->toggleSensorCallback(request, response, stream_index); return response.success; }); service_name = "get_" + stream_name + "_supported_video_modes"; get_supported_video_modes_srv_[stream_index] = nh_.advertiseService<GetStringRequest, GetStringResponse>( service_name, [this, stream_index = stream_index](auto&& request, auto&& response) { response.success = this->getSupportedVideoModesCallback(request, response, stream_index); return response.success; }); } get_white_balance_srv_ = nh_.advertiseService<GetInt32Request, GetInt32Response>( "get_auto_white_balance", [this](auto&& request, auto&& response) { response.success = this->getAutoWhiteBalanceEnabledCallback(request, response, COLOR); return response.success; }); set_white_balance_srv_ = nh_.advertiseService<SetInt32Request, SetInt32Response>( "set_auto_white_balance", [this](auto&& request, auto&& response) { response.success = this->setAutoWhiteBalanceEnabledCallback(request, response); return response.success; }); set_fan_enable_srv_ = nh_.advertiseService<std_srvs::SetBoolRequest, std_srvs::SetBoolResponse>( "set_fan", [this](auto&& request, auto&& response) { response.success = this->setFanEnableCallback(request, response); return response.success; }); set_laser_enable_srv_ = nh_.advertiseService<std_srvs::SetBoolRequest, std_srvs::SetBoolResponse>( "set_laser", [this](auto&& request, auto&& response) { response.success = this->setLaserEnableCallback(request, response); return response.success; }); set_ldp_enable_srv_ = nh_.advertiseService<std_srvs::SetBoolRequest, std_srvs::SetBoolResponse>( "set_ldp", [this](auto&& request, auto&& response) { response.success = this->setLdpEnableCallback(request, response); return response.success; }); get_ldp_status_srv_ = nh_.advertiseService<GetBoolRequest, GetBoolResponse>( "get_ldp_status", [this](auto&& request, auto&& response) { response.success = this->getLdpStatusCallback(request, response); return response.success; }); get_device_srv_ = nh_.advertiseService<GetDeviceInfoRequest, GetDeviceInfoResponse>( "get_device_info", [this](auto&& request, auto&& response) { response.success = this->getDeviceInfoCallback(request, response); return response.success; }); get_sdk_version_srv_ = nh_.advertiseService<GetStringRequest, GetStringResponse>( "get_version", [this](auto&& request, auto&& response) { response.success = this->getSDKVersionCallback(request, response); return response.success; }); get_camera_info_srv_ = nh_.advertiseService<GetCameraInfoRequest, GetCameraInfoResponse>( "get_camera_info", [this](auto&& request, auto&& response) { response.success = this->getCameraInfoCallback(request, response); return response.success; }); switch_ir_camera_srv_ = nh_.advertiseService<SetStringRequest, SetStringResponse>( "switch_ir_camera", [this](auto&& request, auto&& response) { response.success = this->switchIRCameraCallback(request, response); return response.success; }); get_camera_params_srv_ = nh_.advertiseService<GetCameraParamsRequest, GetCameraParamsResponse>( "get_camera_params", [this](auto&& request, auto&& response) { response.success = this->getCameraParamsCallback(request, response); return response.success; }); get_device_type_srv_ = nh_.advertiseService<GetStringRequest, GetStringResponse>( "get_device_type", [this](auto&& request, auto&& response) { response.success = this->getDeviceTypeCallback(request, response); return response.success; }); get_serial_srv_ = nh_.advertiseService<GetStringRequest, GetStringResponse>( "get_serial", [this](auto&& request, auto&& response) { response.success = this->getSerialNumberCallback(request, response); return response.success; }); save_images_srv_ = nh_.advertiseService<std_srvs::EmptyRequest, std_srvs::EmptyResponse>( "save_images", [this](auto&& request, auto&& response) { return this->saveImagesCallback(request, response); }); reset_ir_exposure_srv_ = nh_.advertiseService<std_srvs::EmptyRequest, std_srvs::EmptyResponse>( "reset_ir_exposure", [this](auto&& request, auto&& response) { return this->resetIRExposureCallback(request, response); }); reset_ir_gain_srv_ = nh_.advertiseService<std_srvs::EmptyRequest, std_srvs::EmptyResponse>( "reset_ir_gain", [this](auto&& request, auto&& response) { return this->resetIRGainCallback(request, response); }); set_ir_flood_srv_ = nh_.advertiseService<std_srvs::SetBoolRequest, std_srvs::SetBoolResponse>( "set_ir_flood", [this](auto&& request, auto&& response) { response.success = this->setIRFloodCallback(request, response); return response.success; }); } bool OBCameraNode::setMirrorCallback(std_srvs::SetBoolRequest& request, std_srvs::SetBoolResponse& response, const stream_index_pair& stream_index) { (void)response; if (!stream_started_[stream_index] || !device_->hasSensor(stream_index.first)) { std::stringstream ss; ss << "Stream " << stream_name_[stream_index] << " is not started or does not have a sensor"; response.message = ss.str(); ROS_ERROR_STREAM(response.message); return false; } auto stream = streams_.at(stream_index); stream->setMirroringEnabled(request.data); return true; } bool OBCameraNode::getExposureCallback(GetInt32Request& request, GetInt32Response& response, const stream_index_pair& stream_index) { (void)request; if (!stream_started_[stream_index] || !device_->hasSensor(stream_index.first)) { std::stringstream ss; ss << "Stream " << stream_name_[stream_index] << " is not started or does not have a sensor"; response.message = ss.str(); ROS_ERROR_STREAM(response.message); return false; } if (stream_index == COLOR) { auto stream = streams_.at(stream_index); auto camera_settings = stream->getCameraSettings(); if (camera_settings == nullptr) { response.data = 0; response.success = false; response.message = stream_name_[stream_index] + " Camera settings not available"; return false; } response.data = camera_settings->getExposure(); } else if (stream_index == INFRA1 || stream_index == INFRA2 || stream_index == DEPTH) { response.data = getIRExposure(); return true; } else { response.message = "Stream not supported get exposure"; return false; } return true; } bool OBCameraNode::setExposureCallback(SetInt32Request& request, SetInt32Response& response, const stream_index_pair& stream_index) { if (!stream_started_[stream_index] || !device_->hasSensor(stream_index.first)) { std::stringstream ss; ss << "Stream " << stream_name_[stream_index] << " is not started or does not have a sensor"; response.message = ss.str(); ROS_ERROR_STREAM(response.message); return false; } if (stream_index == COLOR) { auto stream = streams_.at(stream_index); auto camera_settings = stream->getCameraSettings(); if (camera_settings == nullptr) { response.success = false; response.message = stream_name_[stream_index] + " Camera settings not available"; return false; } auto rc = camera_settings->setExposure(request.data); std::stringstream ss; if (rc != openni::STATUS_OK) { ss << "Couldn't set color exposure: " << openni::OpenNI::getExtendedError(); response.message = ss.str(); ROS_ERROR_STREAM(response.message); return false; } else { return true; } } else if (stream_index == INFRA1 || stream_index == INFRA2 || stream_index == DEPTH) { auto data = static_cast<uint32_t>(request.data); setIRExposure(data); return true; } else { response.message = "stream not support get gain"; return false; } } bool OBCameraNode::getGainCallback(GetInt32Request& request, GetInt32Response& response, const stream_index_pair& stream_index) { (void)request; if (!stream_started_[stream_index] || !device_->hasSensor(stream_index.first)) { std::stringstream ss; ss << "Stream " << stream_name_[stream_index] << " is not started or does not have a sensor"; response.message = ss.str(); ROS_ERROR_STREAM(response.message); return false; } if (stream_index == COLOR) { auto stream = streams_.at(stream_index); auto camera_settings = stream->getCameraSettings(); if (camera_settings == nullptr) { response.success = false; response.message = stream_name_[stream_index] + " Camera settings not available"; return false; } response.data = camera_settings->getGain(); } else if (stream_index == INFRA1 || stream_index == INFRA2 || stream_index == DEPTH) { response.data = getIRGain(); } else { response.message = "stream not support get gain"; return false; } return true; } bool OBCameraNode::setGainCallback(SetInt32Request& request, SetInt32Response& response, const stream_index_pair& stream_index) { (void)response; if (!stream_started_[stream_index] || !device_->hasSensor(stream_index.first)) { std::stringstream ss; ss << "Stream " << stream_name_[stream_index] << " is not started or does not have a sensor"; response.message = ss.str(); ROS_ERROR_STREAM(response.message); return false; } if (stream_index == COLOR) { auto stream = streams_.at(stream_index); auto camera_settings = stream->getCameraSettings(); if (camera_settings == nullptr) { response.success = false; response.message = stream_name_[stream_index] + " Camera settings not available"; return false; } camera_settings->setGain(request.data); } else if (stream_index == INFRA1 || stream_index == INFRA2 || stream_index == DEPTH) { setIRGain(request.data); } return true; } int OBCameraNode::getIRExposure() { int data = 0; int data_size = 4; std::lock_guard<decltype(device_lock_)> lock(device_lock_); device_->getProperty(openni::OBEXTENSION_ID_IR_EXP, (uint32_t*)&data, &data_size); return data; } void OBCameraNode::setIRExposure(uint32_t data) { std::lock_guard<decltype(device_lock_)> lock(device_lock_); device_->setProperty(openni::OBEXTENSION_ID_IR_EXP, data); } int OBCameraNode::getIRGain() { int data = 0; int data_size = 4; std::lock_guard<decltype(device_lock_)> lock(device_lock_); device_->getProperty(openni::OBEXTENSION_ID_IR_GAIN, (uint8_t*)&data, &data_size); return data; } void OBCameraNode::setIRGain(int data) { int data_size = 4; std::lock_guard<decltype(device_lock_)> lock(device_lock_); device_->setProperty(openni::OBEXTENSION_ID_IR_GAIN, (uint8_t*)&data, data_size); } std::string OBCameraNode::getSerialNumber() { char serial_number_str[128] = {0}; int data_size = sizeof(serial_number_str); std::lock_guard<decltype(device_lock_)> lock(device_lock_); device_->getProperty(openni::OBEXTENSION_ID_SERIALNUMBER, (uint8_t*)&serial_number_str, &data_size); return serial_number_str; } bool OBCameraNode::getAutoWhiteBalanceEnabledCallback(GetInt32Request& request, GetInt32Response& response, const stream_index_pair& stream_index) { (void)request; if (!stream_started_[stream_index] || !device_->hasSensor(stream_index.first)) { std::stringstream ss; ss << "Stream " << stream_name_[stream_index] << " is not started or does not have a sensor"; response.message = ss.str(); ROS_ERROR_STREAM(response.message); return false; } auto stream = streams_.at(stream_index); auto camera_settings = stream->getCameraSettings(); if (camera_settings == nullptr) { response.data = 0; response.message = stream_name_[stream_index] + " Camera settings not available"; return false; } response.data = camera_settings->getAutoWhiteBalanceEnabled(); return true; } bool OBCameraNode::setAutoWhiteBalanceEnabledCallback(SetInt32Request& request, SetInt32Response& response) { if (!device_->hasSensor(openni::SENSOR_COLOR)) { response.message = "Color sensor not available"; ROS_ERROR_STREAM(response.message); return false; } auto stream = streams_.at(COLOR); auto camera_settings = stream->getCameraSettings(); if (camera_settings == nullptr) { response.message = stream_name_[COLOR] + " Camera settings not available"; ROS_ERROR_STREAM(response.message); return false; } auto data = request.data; auto rc = camera_settings->setAutoWhiteBalanceEnabled(data); if (rc != openni::STATUS_OK) { std::stringstream ss; ss << " Couldn't set auto white balance: " << openni::OpenNI::getExtendedError(); response.message = ss.str(); ROS_ERROR_STREAM(ss.str()); return false; } else { return true; } } bool OBCameraNode::setAutoExposureCallback(std_srvs::SetBoolRequest& request, std_srvs::SetBoolResponse& response, const stream_index_pair& stream_index) { if (!stream_started_[stream_index] || !device_->hasSensor(stream_index.first)) { std::stringstream ss; ss << "Stream " << stream_name_[stream_index] << " is not started or does not have a sensor"; response.message = ss.str(); ROS_ERROR_STREAM(response.message); return false; } openni::Status status; if (stream_index == COLOR) { auto stream = streams_.at(stream_index); auto camera_settings = stream->getCameraSettings(); if (camera_settings == nullptr) { response.success = false; response.message = stream_name_[stream_index] + " Camera settings not available"; ROS_ERROR_STREAM(response.message); return false; } status = camera_settings->setAutoExposureEnabled(request.data); } else if (stream_index == INFRA1 || stream_index == INFRA2 || stream_index == DEPTH) { std::lock_guard<decltype(device_lock_)> lock(device_lock_); status = device_->setProperty(XN_MODULE_PROPERTY_AE, request.data); } else { response.message = "Stream not supported set auto exposure"; return false; } if (status != openni::STATUS_OK) { std::stringstream ss; ss << "Couldn't set auto exposure: " << openni::OpenNI::getExtendedError(); response.message = ss.str(); ROS_ERROR_STREAM(response.message); return false; } else { return true; } } bool OBCameraNode::setLaserEnableCallback(std_srvs::SetBoolRequest& request, std_srvs::SetBoolResponse& response) { std::lock_guard<decltype(device_lock_)> lock(device_lock_); device_->setProperty(openni::OBEXTENSION_ID_LASER_EN, request.data); device_->setProperty(XN_MODULE_PROPERTY_EMITTER_STATE, request.data); response.success = true; return true; } bool OBCameraNode::setIRFloodCallback(std_srvs::SetBoolRequest& request, std_srvs::SetBoolResponse& response) { (void)response; std::lock_guard<decltype(device_lock_)> lock(device_lock_); ROS_INFO_STREAM("Setting IR flood to " << (request.data ? "true" : "false")); int data = static_cast<int>(request.data); device_->setProperty(XN_MODULE_PROPERTY_IRFLOOD_STATE, data); return true; } bool OBCameraNode::setLdpEnableCallback(std_srvs::SetBoolRequest& request, std_srvs::SetBoolResponse& response) { (void)response; stopStreams(); std::lock_guard<decltype(device_lock_)> lock(device_lock_); auto status = device_->setProperty(XN_MODULE_PROPERTY_LDP_ENABLE, request.data); startStreams(); if (status != openni::STATUS_OK) { std::stringstream ss; ss << "Couldn't set LDP enable: " << openni::OpenNI::getExtendedError(); ROS_ERROR_STREAM(ss.str()); response.message = ss.str(); return false; } else { return true; } } bool OBCameraNode::setFanEnableCallback(std_srvs::SetBoolRequest& request, std_srvs::SetBoolResponse& response) { std::lock_guard<decltype(device_lock_)> lock(device_lock_); device_->setProperty(XN_MODULE_PROPERTY_FAN_ENABLE, request.data); response.success = true; return true; } bool OBCameraNode::getDeviceInfoCallback(GetDeviceInfoRequest& request, GetDeviceInfoResponse& response) { (void)request; std::lock_guard<decltype(device_lock_)> lock(device_lock_); auto device_info = device_->getDeviceInfo(); response.info.name = device_info.getName(); response.info.pid = device_info.getUsbProductId(); response.info.vid = device_info.getUsbVendorId(); char serial_number[64]; int data_size = sizeof(serial_number); auto rc = device_->getProperty(openni::OBEXTENSION_ID_SERIALNUMBER, serial_number, &data_size); if (rc == openni::STATUS_OK) { response.info.serial_number = serial_number; } else { response.info.serial_number = ""; } return true; } bool OBCameraNode::getCameraInfoCallback(GetCameraInfoRequest& request, GetCameraInfoResponse& response) { (void)request; std::lock_guard<decltype(device_lock_)> lock(device_lock_); auto camera_info = getColorCameraInfo(); response.info = camera_info; return true; } bool OBCameraNode::getSDKVersionCallback(GetStringRequest& request, GetStringResponse& response) { (void)request; nlohmann::json data; data["ros_sdk_version"] = OB_ROS_VERSION_STR; data["openni_version"] = ONI_VERSION_STRING; char buffer[128] = {0}; int data_size = sizeof(buffer); std::lock_guard<decltype(device_lock_)> lock(device_lock_); device_->getProperty(XN_MODULE_PROPERTY_SENSOR_PLATFORM_STRING, buffer, &data_size); data["firmware_version"] = buffer; response.data = data.dump(2); return true; } bool OBCameraNode::getDeviceTypeCallback(GetStringRequest& request, GetStringResponse& response) { (void)request; char device_type_str[128] = {0}; int data_size = sizeof(device_type_str); std::lock_guard<decltype(device_lock_)> lock(device_lock_); device_->getProperty(openni::OBEXTENSION_ID_DEVICETYPE, (uint8_t*)&device_type_str, &data_size); response.data = device_type_str; return true; } bool OBCameraNode::getSerialNumberCallback(GetStringRequest& request, GetStringResponse& response) { (void)request; response.data = getSerialNumber(); return true; } bool OBCameraNode::switchIRCameraCallback(SetStringRequest& request, SetStringResponse& response) { const int data_size = 4; int data; std::lock_guard<decltype(device_lock_)> lock(device_lock_); if (request.data == "left") { data = 0; device_->setProperty(XN_MODULE_PROPERTY_SWITCH_IR, (uint8_t*)&data, data_size); } else if (request.data == "right") { data = 1; device_->setProperty(XN_MODULE_PROPERTY_SWITCH_IR, (uint8_t*)&data, data_size); } else { response.message = "Invalid IR camera name"; ROS_ERROR_STREAM(response.message); return false; } return true; } bool OBCameraNode::getCameraParamsCallback(GetCameraParamsRequest& request, GetCameraParamsResponse& response) { (void)request; auto camera_params = getCameraParams(); for (int i = 0; i < 9; i++) { response.r2l_r[i] = camera_params.r2l_r[i]; if (i < 4) { response.l_intr_p[i] = camera_params.l_intr_p[i]; response.r_intr_p[i] = camera_params.r_intr_p[i]; } if (i < 3) { response.r2l_t[i] = camera_params.r2l_t[i]; } if (i < 5) { response.l_k[i] = camera_params.l_k[i]; response.r_k[i] = camera_params.r_k[i]; } } return true; } bool OBCameraNode::toggleSensorCallback(std_srvs::SetBoolRequest& request, std_srvs::SetBoolResponse& response, const stream_index_pair& stream_index) { if (request.data) { ROS_INFO_STREAM(stream_name_[stream_index] << " ON"); } else { ROS_INFO_STREAM(stream_name_[stream_index] << " OFF"); } response.success = toggleSensor(stream_index, request.data, response.message); return true; } bool OBCameraNode::saveImagesCallback(std_srvs::EmptyRequest& request, std_srvs::EmptyResponse& response) { (void)request; (void)response; ROS_INFO_STREAM("Saving images"); if (enable_[INFRA1]) { save_images_[INFRA1] = true; } if (enable_[COLOR]) { save_images_[COLOR] = true; } if (enable_[DEPTH]) { save_images_[DEPTH] = true; } return true; } bool OBCameraNode::getSupportedVideoModesCallback(GetStringRequest& request, GetStringResponse& response, const stream_index_pair& stream_index) { (void)request; if (!supported_video_modes_.count(stream_index)) { response.data = ""; response.message = "No supported video modes"; return false; } else { auto modes = supported_video_modes_[stream_index]; nlohmann::json data; for (auto& mode : modes) { std::stringstream ss; ss << mode.getResolutionX() << "x" << mode.getResolutionY() << "@" << mode.getFps(); if (data.empty() || data.back() != ss.str()) { data.push_back(ss.str()); } } response.data = data.dump(2); return true; } } bool OBCameraNode::getLdpStatusCallback(GetBoolRequest& request, GetBoolResponse& response) { (void)request; std::lock_guard<decltype(device_lock_)> lock(device_lock_); int data = 0; int data_size = 4; device_->getProperty(XN_MODULE_PROPERTY_LDP_ENABLE, (uint8_t*)&data, &data_size); response.data = data; return true; } bool OBCameraNode::resetIRGainCallback(std_srvs::EmptyRequest& request, std_srvs::EmptyResponse& response) { (void)request; (void)response; ROS_INFO_STREAM("Resetting IR gain"); setIRGain(init_ir_gain_); return true; } bool OBCameraNode::resetIRExposureCallback(std_srvs::EmptyRequest& request, std_srvs::EmptyResponse& response) { (void)request; (void)response; ROS_INFO_STREAM("Resetting IR exposure"); setIRExposure(init_ir_exposure_); return true; } bool OBCameraNode::toggleSensor(const stream_index_pair& stream_index, bool enabled, std::string& msg) { std::lock_guard<decltype(device_lock_)> lock(device_lock_); if (!device_->hasSensor(stream_index.first)) { std::stringstream ss; ss << "doesn't have " << stream_name_[stream_index]; msg = ss.str(); ROS_WARN_STREAM(msg); return false; } if (enabled) { enable_[stream_index] = true; } else { enable_[stream_index] = false; } stopStreams(); startStreams(); return true; } } // namespace astra_camera
#include <type_traits> int main(int argc, char** argv) { // make sure we have c++11 enabled using returnv = std::integral_constant<int, 0>; return returnv::value; }
// Copyright (c) 2007-2013 Hartmut Kaiser // Copyright (c) 2016 Thomas Heller // // SPDX-License-Identifier: BSL-1.0 // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // // The algorithm was taken from http://locklessinc.com/articles/barriers/ #pragma once #include <pika/config.hpp> #include <pika/assert.hpp> #include <pika/concurrency/spinlock.hpp> #include <pika/synchronization/detail/condition_variable.hpp> #include <pika/thread_support/assert_owns_lock.hpp> #include <chrono> #include <climits> #include <cstddef> #include <cstdint> #include <utility> #include <pika/config/warnings_prefix.hpp> /////////////////////////////////////////////////////////////////////////////// namespace pika { namespace detail { struct empty_oncompletion { inline void operator()() noexcept {} }; } // namespace detail // A barrier is a thread coordination mechanism whose lifetime consists of // a sequence of barrier phases, where each phase allows at most an // expected number of threads to block until the expected number of threads // arrive at the barrier. [ Note: A barrier is useful for managing repeated // tasks that are handled by multiple threads. - end note ] // Each barrier phase consists of the following steps: // - The expected count is decremented by each call to arrive or // arrive_and_drop. // - When the expected count reaches zero, the phase completion step is // run. For the specialization with the default value of the // CompletionFunction template parameter, the completion step is run // as part of the call to arrive or arrive_and_drop that caused the // expected count to reach zero. For other specializations, the // completion step is run on one of the threads that arrived at the // barrier during the phase. // - When the completion step finishes, the expected count is reset to // what was specified by the expected argument to the constructor, // possibly adjusted by calls to arrive_and_drop, and the next phase // starts. // // Each phase defines a phase synchronization point. Threads that arrive // at the barrier during the phase can block on the phase synchronization // point by calling wait, and will remain blocked until the phase // completion step is run. // The phase completion step that is executed at the end of each phase has // the following effects: // - Invokes the completion function, equivalent to completion(). // - Unblocks all threads that are blocked on the phase synchronization // point. // The end of the completion step strongly happens before the returns from // all calls that were unblocked by the completion step. For // specializations that do not have the default value of the // CompletionFunction template parameter, the behavior is undefined if any // of the barrier object's member functions other than wait are called // while the completion step is in progress. // // Concurrent invocations of the member functions of barrier, other than // its destructor, do not introduce data races. The member functions // arrive and arrive_and_drop execute atomically. // // CompletionFunction shall meet the Cpp17MoveConstructible (Table 28) and // Cpp17Destructible (Table 32) requirements. // std::is_nothrow_invocable_v<CompletionFunction&> shall be true. // // The default value of the CompletionFunction template parameter is an // unspecified type, such that, in addition to satisfying the requirements // of CompletionFunction, it meets the Cpp17DefaultConstructible // requirements (Table 27) and completion() has no effects. // // barrier::arrival_token is an unspecified type, such that it meets the // Cpp17MoveConstructible (Table 28), Cpp17MoveAssignable (Table 30), and // Cpp17Destructible (Table 32) requirements. template <typename OnCompletion = detail::empty_oncompletion> class barrier { public: PIKA_NON_COPYABLE(barrier); private: using mutex_type = pika::concurrency::detail::spinlock; public: using arrival_token = bool; // Returns: The maximum expected count that the implementation // supports. static constexpr std::ptrdiff_t(max)() noexcept { return (std::numeric_limits<std::ptrdiff_t>::max)(); } // Preconditions: expected >= 0 is true and expected <= max() is true. // Effects: Sets both the initial expected count for each // barrier phase and the current expected count for the // first phase to expected. Initializes completion with // PIKA_MOVE(f). Starts the first phase. [Note: If // expected is 0 this object can only be destroyed.- // end note] // Throws: Any exception thrown by CompletionFunction's move // constructor. barrier(std::ptrdiff_t expected, OnCompletion completion = OnCompletion()) : expected_(expected) , arrived_(expected) , completion_(PIKA_MOVE(completion)) , phase_(false) { PIKA_ASSERT(expected >= 0 && expected <= (max) ()); } private: [[nodiscard]] arrival_token arrive_locked( std::unique_lock<mutex_type>& l, std::ptrdiff_t update = 1) { PIKA_ASSERT_OWNS_LOCK(l); PIKA_ASSERT(arrived_ >= update); bool const old_phase = phase_; std::ptrdiff_t const result = (arrived_ -= update); std::ptrdiff_t const new_expected = expected_; if (result == 0) { completion_(); arrived_ = new_expected; phase_ = !old_phase; cond_.notify_all(PIKA_MOVE(l)); } return old_phase; } public: // Preconditions: update > 0 is true, and update is less than or equal // to the expected count for the current barrier phase. // Effects: Constructs an object of type arrival_token that is // associated with the phase synchronization point for // the current phase. Then, decrements the expected // count by update. // Synchronization: The call to arrive strongly happens before the // start of the phase completion step for the current // phase. // Returns: The constructed arrival_token object. // Throws: system_error when an exception is required // ([thread.req.exception]). // Error conditions: Any of the error conditions allowed for mutex // types([thread.mutex.requirements.mutex]). // [Note: This call can cause the completion step for the current phase // to start.- end note] [[nodiscard]] arrival_token arrive(std::ptrdiff_t update = 1) { std::unique_lock<mutex_type> l(mtx_); return arrive_locked(l, update); } // Preconditions: arrival is associated with the phase synchronization // point for the current phase or the immediately // preceding phase of the same barrier object. // Effects: Blocks at the synchronization point associated with // PIKA_MOVE(arrival) until the phase completion step // of the synchronization point's phase is run. [ Note: // If arrival is associated with the synchronization // point for a previous phase, the call returns // immediately. - end note ] // Throws: system_error when an exception is required // ([thread.req.exception]). // Error conditions: Any of the error conditions allowed for mutex // types ([thread.mutex.requirements.mutex]). void wait(arrival_token&& old_phase, std::chrono::duration<double> busy_wait_timeout = std::chrono::duration<double>( 0.0)) const { bool const do_busy_wait = busy_wait_timeout > std::chrono::duration<double>(0.0); if (do_busy_wait && pika::util::detail::yield_while_timeout( [&]() { std::unique_lock<mutex_type> l(mtx_); return phase_ == old_phase; }, busy_wait_timeout, "barrier::wait", false)) { return; } std::unique_lock<mutex_type> l(mtx_); if (phase_ == old_phase) { cond_.wait(l, "barrier::wait"); } PIKA_ASSERT(phase_ != old_phase); } /// Effects: Equivalent to: wait(arrive()). void arrive_and_wait( std::chrono::duration<double> busy_wait_timeout = std::chrono::duration<double>(0.0)) { wait(arrive(), busy_wait_timeout); } // Preconditions: The expected count for the current barrier phase is // greater than zero. // Effects: Decrements the initial expected count for all // subsequent phases by one. Then decrements the // expected count for the current phase by one. // Synchronization: The call to arrive_and_drop strongly happens before // the start of the phase completion step for the // current phase. // Throws: system_error when an exception is required // ([thread.req.exception]). // Error conditions: Any of the error conditions allowed for mutex // types ([thread.mutex.requirements.mutex]). // [Note: This call can cause the completion step for the current // phase to start.- end note] void arrive_and_drop() { std::unique_lock<mutex_type> l(mtx_); PIKA_ASSERT(expected_ > 0); --expected_; PIKA_UNUSED(arrive_locked(l, 1)); } private: mutable mutex_type mtx_; mutable pika::detail::condition_variable cond_; std::ptrdiff_t expected_; std::ptrdiff_t arrived_; OnCompletion completion_; bool phase_; }; } // namespace pika #include <pika/config/warnings_suffix.hpp>
#include <iostream> #include <vector> #include <queue> #define MAX 1001 #define INF 1000000000 using namespace std; int n, m; class Com{ public: int idx, dist, post; vector<pair<int, int>> next; Com(int i = 0, int d = INF, int p = -1) :idx(i), dist(d), post(p) {} bool operator < (const Com &c) const { return dist > c.dist; } }; Com com[MAX]; bool visited[MAX][MAX]; vector<pair<int, int>> ret; void dijkstra(){ priority_queue<Com> pq; com[1].dist = 0; pq.push(com[1]); while(!pq.empty()){ Com curCom = pq.top(); pq.pop(); for(pair<int, int> p : curCom.next){ if(com[p.second].dist > curCom.dist + p.first){ com[p.second].dist = curCom.dist + p.first; com[p.second].post = curCom.idx; pq.push(com[p.second]); } } } for(int i = 2; i <= n; i++){ Com tpc = com[i]; while(tpc.dist != 0){ if(!visited[tpc.idx][tpc.post]){ ret.push_back(make_pair(tpc.idx, tpc.post)); visited[tpc.idx][tpc.post] = true; visited[tpc.post][tpc.idx] = true; } tpc = com[tpc.post]; } } } int main(){ ios_base::sync_with_stdio(false); cin.tie(0); cin >> n >> m; for(int i = 1; i <= n; i++){ com[i].idx = i; } while(m--){ int i, j, w; cin >> i >> j >> w; com[i].next.push_back(make_pair(w, j)); com[j].next.push_back(make_pair(w, i)); } dijkstra(); cout << ret.size() << '\n'; for(pair<int, int> p : ret){ cout << p.first << " " << p.second << '\n'; } return 0; }
#include <bits/stdc++.h> using namespace std; #define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0) #define MAXN 100 #define INF 0x3f3f3f3f #define DEVIATION 0.00000005 typedef long long LL; int main(int argc, char const *argv[]) { int kase; scanf("%d",&kase); double A,B; double pi = acos(-1.0); while( kase-- ){ scanf("%lf %lf",&A,&B); if( A == 0.0 && B == 0.0 ){ printf("0.00 0.00\n"); continue; } double radian; double F = sqrt(A*A+B*B); for(radian = atan(A/B) ; radian <= 2*pi ; radian += pi/2 ) if( fabs(A*sin(radian)+B*cos(radian)-F) < 0.01 && radian >= 0 ) break; printf("%.2lf %.2lf\n",radian,F); } return 0; }
#include<iostream> #include<vector> #include<algorithm> # using namespace std; long n; long checkPossible(vector<long> machines,long goal,long days) { for(int a:machines) { goal=goal-(days/a); } return goal; } // Complete the minTime function below. long minTime(vector<long> machines, long goal) { sort(machines.begin(),machines.end()); long max=machines[n-1]*goal; long min=1,mid; //cout<<max<<endl; while(min!=max) { mid=(min+max)/2; long a=checkPossible(machines,goal,mid); // cout<<mid<<endl; if(a>0) min=mid+1; else if(a<=0) max=mid; } return min; } int main() { long goal; vector<long> machines; cin>>n>>goal; for(long i=0;i<n;i++) { long a; cin>>a; machines.push_back(a); } cout<<minTime(machines,goal); return 0; }
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4; -*- * * Copyright (C) 2011 Opera Software ASA. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ group "hardcore.component.syncmessenger"; language c++; require MESSAGELOOP_RUNSLICE_SUPPORT; include "modules/hardcore/component/OpSyncMessenger.h"; include "modules/hardcore/src/generated/g_message_hardcore_messages.h"; global { /** * Simple message listener bouncing select messages back to the tests. */ class Responder : public OpMessageListener { public: OP_STATUS Construct(); OP_STATUS ProcessMessage(const OpTypedMessage* message); OpMessageAddress GetAddress() { return m_channel.GetAddress(); } bool GetNestedSyncActivated() { return m_is_nested_sync_activated; } void SetNestedSyncActivated(bool value) { m_is_nested_sync_activated = value; } private: OpChannel m_channel; bool m_is_nested_sync_activated; } g_responder; OP_STATUS Responder::Construct() { RETURN_IF_ERROR(m_channel.Construct()); RETURN_IF_ERROR(m_channel.AddMessageListener(this)); return OpStatus::OK; } OP_STATUS Responder::ProcessMessage(const OpTypedMessage* message) { if (message->GetType() == OpTextMessage::Type) { OpTextMessage* m = OpTextMessage::Cast(message); if (m->GetText() == UNI_L("echo")) return m->Reply(OpTextMessage::Create(m->GetText())); if (m->GetText() == UNI_L("ignore")) return OpStatus::OK; if (m->GetText() == UNI_L("text followed by number")) { RETURN_IF_ERROR(m->Reply(OpTextMessage::Create(m->GetText()))); return m->Reply(OpNumberMessage::Create(29)); } if (m->GetText() == UNI_L("nest")) { /* Create 10 msec delayed message, guaranteed to be delivered after the 1s timeout * set in test("Nested timeout"). */ OpTextMessage* message = OpTextMessage::Create(OpMessageAddress(), OpMessageAddress(), 10); RETURN_OOM_IF_NULL(message); RETURN_IF_ERROR(message->SetText(UNI_L("echo"))); SetNestedSyncActivated(true); /* Send message with no timeout. */ OpSyncMessenger sync(g_component->CreateChannel(GetAddress())); OP_STATUS s = sync.SendMessage(message); switch(s) { case OpStatus::ERR_YIELD: /* Correct behavior. Inner timeout forced by outer timeout. */ return OpStatus::OK; case OpStatus::OK: /* Forced timeout failed. This is a serious error. */ return OpStatus::ERR_OUT_OF_RANGE; default: /* Transmit failed or we experienced OOM. */ return s; } } } return OpStatus::ERR; }; } test("Channel creation") { verify_success(g_responder.Construct()); } test("Convenience path, channel OOM") { OpSyncMessenger sync(NULL); verify_status(OpStatus::ERR_NO_MEMORY, sync.SendMessage(OpNumberMessage::Create(0))); } test("Convenience path, message OOM") require success "Channel creation"; { OpSyncMessenger sync(g_component->CreateChannel(g_responder.GetAddress())); verify_status(OpStatus::ERR_NO_MEMORY, sync.SendMessage(NULL)); } test("Message exchange") require success "Channel creation"; { OpTextMessage* message = OpTextMessage::Create(); verify_not_oom(message); verify_success(message->SetText(UNI_L("echo"))); OpSyncMessenger sync(g_component->CreateChannel(g_responder.GetAddress())); verify_success(sync.SendMessage(message)); verify(OpTextMessage::Cast(sync.GetResponse())->GetText() == UNI_L("echo")); } test("Response type restriction") require success "Channel creation"; { OpTextMessage* message = OpTextMessage::Create(); verify_not_oom(message); verify_success(message->SetText(UNI_L("text followed by number"))); OpSyncMessenger sync(g_component->CreateChannel(g_responder.GetAddress())); sync.AcceptResponse(OpNumberMessage::Type); verify_success(sync.SendMessage(message)); verify(sync.GetResponse()->GetType() == OpNumberMessage::Type); verify(OpNumberMessage::Cast(sync.GetResponse())->GetNumber() == 29); } test("Response type restriction and extension") require success "Channel creation"; { OpTextMessage* message = OpTextMessage::Create(); verify_not_oom(message); verify_success(message->SetText(UNI_L("text followed by number"))); OpSyncMessenger sync(g_component->CreateChannel(g_responder.GetAddress())); sync.AcceptResponse(OpNumberMessage::Type); sync.AcceptResponse(OpTextMessage::Type); verify_success(sync.SendMessage(message)); verify(sync.GetResponse()->GetType() == OpTextMessage::Type); } test("Basic timeout") require success "Channel creation"; { OpTextMessage* message = OpTextMessage::Create(); verify_not_oom(message); verify_success(message->SetText(UNI_L("ignore"))); OpSyncMessenger sync(g_component->CreateChannel(g_responder.GetAddress())); verify_status(OpStatus::ERR_YIELD, sync.SendMessage(message, true, 1)); } /* * The purpose of this test is to verify that if two OpSyncMessengers::SendMessage() exist on the * call stack and a timeout occurs in the OpSyncMessenger associated with the outer stack frame, * then the OpSyncMessenger associated with the inner stack frame receives an immediate timeout, * regardless of its time status. */ test("Nested timeout") require success "Channel creation"; { OpTextMessage* message = OpTextMessage::Create(); verify_not_oom(message); verify_success(message->SetText(UNI_L("nest"))); OpSyncMessenger sync(g_component->CreateChannel(g_responder.GetAddress())); g_responder.SetNestedSyncActivated(false); verify_status(OpStatus::ERR_YIELD, sync.SendMessage(message, true, 1)); verify(g_responder.GetNestedSyncActivated()); }
#include "stdafx.h" #include "tilemap.h" #include "level_properties.h" #include "level_style.h" #include "rom_file.h" #include "tile.h" int RareDecompress(Buffer& dst, const Buffer& src); TileParts::TileParts() { tile_count_ = 0; } TileParts::~TileParts() { } bool TileParts::Load(CartFile& cart, HDC hdc, const LevelProperties& prop, const LevelStyle& style) { CartFile::Scope scope(cart); /* Load the position of the tile parts */ if (!cart.FollowPtr3(0x35BB2E, style.map_id_ * 3)) { return false; } Buffer tile_map(false); int tile_map_size; if (!tile_map.Alloc(32768)) { return false; } tile_map_size = RareDecompress(tile_map, cart); if (tile_map_size <= 0 || (tile_map_size % 32)) { return false; } tile_count_ = tile_map_size / 32; if (!cart.FollowPtr2(0x3D819A, style.graphics_ * 2)) { return false; } /* Load the tile graphics */ Buffer gfx_data(true); BYTE bank; WORD addr, op, size, size1, size2; UINT offset; DWORD addr1 = 0, addr2 = 0; bool compressed = false; while (1) { if (!cart.Readf("BHHH", &bank, &addr, &op, &size)) { return false; } if (bank == 0) { break ; } offset = (bank << 16) | addr; if (offset <= 0xC00000) { return false; } offset -= 0xC00000; switch (op) { case 0xA000: addr1 = offset; compressed = true; break ; case 0x2000: addr1 = offset; compressed = false; size1 = size; break ; case 0x4420: addr2 = offset; compressed = false; size2 = size; break ; } } if (addr1 == 0) { return false; } cart.Seek(addr1); if (!gfx_data.Alloc(1024)) { return false; } int gfx_size; UINT gfx_count; if (compressed) { gfx_size = RareDecompress(gfx_data, cart); if (gfx_size <= 0) { return false; } } else { if (size1 >= 0x4840) { return false; } gfx_size = 0x4840 + size2; gfx_data.Write(0, cart, size1); if (addr2 != 0) { cart.Seek(addr2); gfx_data.Seek(0x4840); gfx_data.Write(0x4840, cart, size2); } } if (gfx_size % 32 != 0) { return false; } gfx_count = gfx_size / 32; TilePalette palette; DWORD def_palette; def_palette = style.palette_; if (!def_palette) { if (!cart.Read(0x35BC2A + style.map_id_ * 2, &def_palette, 2)) { return false; } } def_palette |= 0x3D0000; palette.LoadPalette(cart, def_palette); switch (style.routine1_) { case 0x00: palette.LoadSubPalette(cart, 0x3D1710, 0, 128); break ; case 0x01: palette.LoadSubPalette(cart, 0x3D268E, 16, 16); break ; case 0x02: palette.LoadPalette(cart, 0x3D2AEE); break ; case 0x03: palette.LoadPalette(cart, 0x3D29EE); break ; case 0x04: palette.LoadSubPalette(cart, 0x3D324E, 0, 128); break ; case 0x05: palette.LoadSubPalette(cart, 0x3D304E, 0, 128); break ; case 0x06: palette.LoadSubPalette(cart, 0x3D2EEE, 0, 128); break ; case 0x07: palette.LoadSubPalette(cart, 0x3D15F0, 12, 16); break ; case 0x08: palette.LoadSubPalette(cart, 0x3D0DD0, 0, 16); break ; case 0x0A: palette.LoadSubPalette(cart, 0x3D326E, 16, 16); break ; case 0x0C: palette.LoadSubPalette(cart, 0x3D2BEE, 0, 128); break ; case 0x0D: palette.LoadSubPalette(cart, 0x3D07F0, 0, 128); break ; case 0x0E: palette.LoadSubPalette(cart, 0x3D268E, 112, 16); break ; case 0x10: palette.LoadSubPalette(cart, 0x3D3A4E, 0, 128); break ; case 0x12: palette.LoadSubPalette(cart, 0x3D2DCE, 0, 16); break ; case 0x14: palette.LoadPalette(cart, 0x3D1610); break ; } // Set transparency for (UINT i = 0; i < 128; i += 16) { palette.SetTransparent(i, true); } if (!CreateDC(hdc) || !CreateBM(hdc, tile_count_ * 32, 32) || !CreateMask(hdc)) { return false; } tile_map.Seek(0); for (UINT i = 0; i < tile_count_; i++) { for (UINT j = 0; j < 16; j++) { UINT x = ((j % 4) * 8) + (i * 32), y = (j / 4) * 8; WORD tile_info; tile_map.ReadWord(tile_info); WORD gfx_index = (tile_info & 0x03FF); BYTE pal_index = (tile_info & 0x1C00) >> 6; bool flip_horz = (tile_info & 0x4000) == 0x4000, flip_vert = (tile_info & 0x8000) == 0x8000; if (gfx_index >= gfx_count) { gfx_index = 0; } BYTE tile_data[32]; gfx_data.Seek(gfx_index * 32); gfx_data.Read(tile_data, 32); DrawTile8x8(*this, palette, pal_index, x, y, tile_data, flip_horz, flip_vert ); } } return true; } TileMap::TileMap() { } TileMap::~TileMap() { } bool TileMap::Load(CartFile& cart, const LevelProperties& prop, const LevelStyle& style) { map_.clear(); map_id_ = style.map_id_; map_index_ = prop.map_index_; if (!cart.Read(0x35BC54 + map_id_ * 2, &tilemap_type_, 2)) { return false; } if (!cart.FollowPtr2(0x35BC7E, map_id_ * 2, 0x35)) { return false; } if (!cart.ReadAddr(tilemap_addr_, 0x35BAEF + map_id_ * 3)) { return false; } if (!cart.Readf("HH", &map_x_, &map_y_)) { return false; } cart.Skip(map_index_ * 10); if (!cart.Readf("HHHHH", &map_left_, &map_right_, &map_top_, &map_bottom_, &map_code_)) { return false; } map_width_ = map_right_ - map_left_, map_height_ = map_bottom_ - map_top_; cart.Seek(tilemap_addr_); Buffer tilemap(true); int tilemap_size; if (tilemap_type_ & 0x0400) { tilemap.Alloc(1024); tilemap_size = RareDecompress(tilemap, cart); if (tilemap_size <= 0) { return false; } } else { tilemap_size = 256; tilemap.Write(0, cart, tilemap_size); } bool vert = false; switch (map_code_) { case 0x0004: case 0x0005: case 0x0006: case 0x0007: vert = true; } tilemap.Seek(0); for (int x = 0, ix = map_left_; ix < map_right_; x++, ix += 32) { for (int y = 0, iy = map_top_; iy < map_bottom_; y++, iy += 32) { Tile tile; WORD tile_info; int bx = ix, by = iy, bh = map_height_; DWORD index = MAKELONG(bx, by); if (vert) { tilemap.Seek(((bx / 32) + (by / 32) * (map_x_ / 32)) * 2); index = MAKELONG(bx, by); } else { tilemap.Seek(((bx / 32) * (map_y_ / 32) + (by / 32)) * 2); } tilemap.ReadWord(tile_info); tile.flip_horz = (tile_info & 0x4000) == 0x4000; tile.flip_vert = (tile_info & 0x8000) == 0x8000; tile.part_id = (tile_info & 0x03FF); map_[index] = tile; } } return true; } bool TileMap::Draw(BitmapSurface& bm, TileParts& parts, const RECT& clip) { if (map_.size() == 0) { return true; } int ix = -clip.left; ix -= ix % 32; for (; ix < clip.right; ix += 32) { int iy = -clip.top; iy -= iy % 32; for (; iy < clip.bottom; iy += 32) { int to_x = ix + clip.left, to_y = iy + clip.top; Map::iterator i; i = map_.find(MAKELONG(ix + map_left_, iy + map_top_)); if (i == map_.end()) { break ; } Tile& tile = i->second; int src_x = tile.part_id * 32, src_y = 0; int tile_width = 32, tile_height = 32; if (tile.flip_horz) { tile_width *= -1; //src_x += 32; } if (tile.flip_vert) { tile_height *= -1; //src_y += 32; } parts.Draw(bm, to_x, to_y, tile_width, tile_height, src_x, src_y); } } return true; }
#include<bits/stdc++.h> using namespace std; int main(){ int n,k; scanf("%d%d",&n,&k); if(n==1&&k==1){ printf("a"); } else if(k==1){ printf("-1"); } else if(k>n){ printf("-1"); } else if(k==n){ for(int i=0;i<n;i++){ printf("%c",'a'+i); } } else if(k<n&&k>=2){ int num=n-(k-2); bool change=true; for(int i=0;i<num;i++){ if(change){ putchar('a'); change=false; } else if(!change){ putchar('b'); change=true; } } for(int i=0;i<k-2;i++){ putchar('c'+i); } } return 0; }
class FirstNotRepeatingCharSolver { public: int FirstNotRepeatingChar(string str) { if (str == "") return -1; map<char, int> memo; for (auto& i : str) { if (memo.count(i) == 0) memo[i] = 1; else memo[i]++; } for (int i = 0; i < str.size(); ++i) { if (memo[str[i]] == 1) { return i; } } return -1; } void test() { vector<string> test_cases = { "bacdefg", "bbfcdcfaggfd", "", "bbfcdcfggfd" }; for (auto& i : test_cases) { int ans = FirstNotRepeatingChar(i); cout << i << " ==> " << (ans != -1 ? to_string(i[ans]) : to_string(-1)) << endl; } } };
void setup() { } void loop() { int delaytime=1000; int z=0; int y=0; volatile unsigned char cube[4][4]; for (z=0;z<4;z++) { for (y=0;y<4;y++) { cube[z][y]=0x01; delay(delaytime); cube[z][y]=0x03; delay(delaytime); cube[z][y]=0x07; delay(delaytime); cube[z][y]=0x0f; delay(delaytime); } } }
#include "util/Occasionally.h" using namespace std; using namespace Poco; using namespace BeeeOn; Occasionally::Occasionally(unsigned int max, const Timestamp::TimeDiff delayMax): m_count(0), m_max(max), m_delayMax(delayMax) { } void Occasionally::execute(const function<void ()> &func) { FastMutex::ScopedLock guard(m_lock); bool run = false; if (m_max > 0) run = run || m_count == 0; else if (m_delayMax > 0) run = run || m_lastTimestamp.isElapsed(m_delayMax); if (run) { func(); m_lastTimestamp.update(); m_count = 1; } else { m_count = (m_count + 1) % m_max; } }
/** * @file AudioListener.cpp * @brief Source file for Engine::AudioListener * * @author Gemuele (Gem) Aludino * @date 09 Dec 2019 */ /** * Copyright © 2019 Gemuele Aludino * * 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 "AudioListener.h" #include "TaskerPerf/perftimer.h" #include <QDebug> #include <cstdio> using Engine::AudioListener; using Engine::Listener; /** * @brief AudioListener::AudioListener */ AudioListener::AudioListener() : Listener::Listener(), audioListenerState(AudioListenerState::OFF), audioThread(nullptr), audioThreshold(0.0) { audioThreshold = 0.01; } /** * @brief AudioListener::~AudioListener */ AudioListener::~AudioListener() { // ~Listener(); qDebug() << "AudioListener destructor"; } /** * @brief AudioListener::setAudioThreshold * @param audioThreshold */ void AudioListener::setAudioThreshold(qreal audioThreshold) { this->audioThreshold = audioThreshold; } /** * @brief AudioListener::getAudioThreshold * @return */ qreal &AudioListener::getAudioThreshold() { return audioThreshold; } /** * @brief AudioListener::start */ void AudioListener::start() { // start listening startListening(); } /** * @brief AudioListener::end */ void AudioListener::end() { // stop listening, for end of session audioThread->getQThread().exit(); audioListenerState = AudioListenerState::OFF; } /** * @brief AudioListener::pause */ void AudioListener::pause() { // TODO pause // suspend listening, but don't quit } /** * @brief AudioListener::update */ void AudioListener::update() { // TODO update // change input device } /** * @brief AudioListener::cleanup */ void AudioListener::cleanup() { delete audioThread; } /** * @brief AudioListener::listen * @return */ Listener::ListenerState AudioListener::listen() { return Listener::getState(); } /** * @brief AudioListener::startListening * @param delay * @return */ int AudioListener::startListening(unsigned long int delay) { audioThread = new AudioThread; // must pass in audio device type at some point to thread. // connect(address of thread object, &thisThread, // signal want to run, &QThread::finished, // object that contains slot, this // function i want to run, &AudioListener::cleanup); connect(&audioThread->getQThread(), &QThread::finished, this, &AudioListener::cleanup); // connect(); qDebug()<<"From startListening on Listener.cpp: "<<QThread::currentThreadId(); audioThread->moveToThread(&audioThread->getQThread()); qDebug()<<"From startListening on Listener.cpp: after connect:%d" <<QThread::currentThreadId(); audioListenerState = AudioListenerState::ON; audioThread->getQThread().start(); while (true) { if (audioThread->getAudioMachine()) { if (audioThread->getAudioMachine()->getAudioDevice()) { audioThread->getAudioMachine()->getQAudioInput()->setVolume(0.0); while (audioThread->getAudioMachine()->getAudioDevice()->getDeviceLevel() == 0.0) { } audioThread->getAudioMachine()->getAudioDevice()->setMinAmplitude( audioThread->getAudioMachine()->getAudioDevice()->getDeviceLevel()); audioThread->getAudioMachine()->getQAudioInput()->setVolume(1.0); break; } } } qDebug()<<"AudioListener updateState() thread id: %d"<< QThread::currentThreadId(); while (true) { ListenerState state; state = audioThread->getAudioLevel() > audioThreshold ? ListenerState::productive : ListenerState::unproductive; setState(state); // qDebug() << "listener level: " << audioThread->getAudioLevel(); if (state == ListenerState::productive) { qDebug("status: productive"); } else { qDebug("status: unproductive"); } QThread::sleep(BASE_DELAY + delay); } return EXIT_SUCCESS; }
#include <iostream> using namespace std; struct Monkey { int num; //猴子的编号 struct Monkey *next; //下一只猴子 }; int main() { int m,n,i,j,king; Monkey *head, *p1,*p2; cin>>m>>n; if(n==1) { king=m; } else { //建立猴子围成的圆圈 p1=p2=new Monkey; head = p1; p1->num=1; for(i=1; i<m; i++) //其余m-1只猴子 { p1=new Monkey; //p1是新增加的 p1->num=i+1; p2->next=p1; p2=p1; //p2总是上一只 } p2->next=head; //最后一只再指向第一只,成了一个圆圈 //下面要开始数了 p1=head; for(i=1; i<m; i++) //循环m-1次,淘汰m-1只猴子 { //从p1开始,数n-1只就找到第n只了 for(j=1; j<n-1; j++) //实际先找到第n-1只,下一只将是被淘汰的 p1=p1->next; //围成圈的,可能再开始从第一只数,如果还未被淘汰的话 //找到了, p2=p1->next; //p2将被删除 //cout<<"第"<<i<<"轮淘汰"<<p2->num<<endl; //可以这样观察中间结果 p1->next=p2->next; //p2就这样被“架空了” p1=p2->next; //下一轮数数的新起点 delete p2; //将不在链表中的结点放弃掉 } king=p1->num; delete p1; } cout<<king<<endl; return 0; }
// // Room.cpp // Crapenstein // // Created by Bruno Caceiro on 24/06/14. // Copyright (c) 2014 Bruno Caceiro. All rights reserved. // #include "Room.h" #include "Wall.h" //Constructor Room::Room(GLfloat roomPosX, GLfloat roomPosY, GLfloat roomPosZ, GLfloat leftWallWidth, GLfloat roomHeight, GLfloat backWallWidth, bool isLeftWallActive, bool isBackWallActive, bool isRightWallActive, bool isFrontWallActive) { posX = roomPosX; posY = roomPosY; posZ = roomPosZ; leftWidth = leftWallWidth; height = roomHeight; backWidth = backWallWidth; leftWallActive = isLeftWallActive; backWallActive = isBackWallActive; rightWallActive = isRightWallActive; frontWallActive = isFrontWallActive; } void Room::buildRoom() { if(leftWallActive) { leftWall = new Wall (posX, posY, posZ, leftWidth, height, 1); collidableObjects.push_back(leftWall); } if(backWallActive) { backWall = new Wall(posX, posY, posZ, backWidth, height, 2); collidableObjects.push_back(backWall); } if(rightWallActive) { rightWall = new Wall (posX, posY, posZ + backWidth, leftWidth, height, 1); collidableObjects.push_back(rightWall); } if(frontWallActive) { frontWall = new Wall(posX + leftWidth,posY,posZ,backWidth,height,2); collidableObjects.push_back(frontWall); } floor = new Wall (posX,posY,posZ, leftWidth,backWidth,0); collidableObjects.push_back(floor); } void Room::update() { if(leftWallActive) leftWall->draw(); if(backWallActive) backWall->draw(); if(rightWallActive) rightWall->draw(); if(frontWallActive) frontWall->draw(); floor->draw(); }
#include<bits/stdc++.h> using namespace std; using ll=long long; ll n,k; vector<ll> v; int main(){ ios::sync_with_stdio(false); cin.tie(0); cin>>n>>k; for(ll i=1;i*i<=n;i++){ if(n%i==0){ v.push_back(i); if(n/i!=i){ v.push_back(n/i); } } } sort(v.begin(),v.end()); if(v.size()<k) cout<<-1<<"\n"; else{ cout<<v[k-1]<<"\n"; } return 0; }
/** \file sonarRight.hpp \author UnBeatables \date LARC2018 \name sonarRight */ #pragma once /* * sonarRight inherited from BehaviorBase. */ #include <BehaviorBase.hpp> /** \brief This class is responsable for robot`s behavior when sonar detects presence in the right. */ class sonarRight : public BehaviorBase { private: static sonarRight *instance; int sonarOutput; public: /** \brief Class constructor. \details Inicialize class parameters. */ sonarRight(); /** \brief Sets sonarRight as current instance. \return Current instance. */ static BehaviorBase* Behavior(); /** \brief This function determines sonarRight transition. \details Transitions to sonarLeft if sonar is detecting presence in the left. <br> Transitions to sonarMiddle if sonar is detecting presence in the middle. <br> Transitions to lastBehavior or Start if sonar is detecting no presence. \param _ub void pointer for UnBoard. \return Transition state. */ BehaviorBase* transition(void*); /** \brief This function is responsable for robot`s action when the sonar detects object in the right. \details The robot will move left. \param _ub void pointer for UnBoard. */ void action(void*); };
#include<iostream> using namespace std; int talbai(int c, int d){ int l; l=c*d; return l; } main(){ int a,b,s; cin>>a; cin>>b; s=talbai(a,b); cout<<s; }
#include "Simulacion.h" #include <ctime> #include <iomanip> #include <vector> #include <iostream> #include "carga.h" void Simulacion::generar_cargas() { std::vector<carga> vector_cargas; srand(time(0)); for(int i=0;i<=2;i++){ // genera 3 cargas en posiciones random //printf("random value: %d \n", (rand()%6)); int value_x = (rand()%10); int value_y = (rand()%10); int value_q = (rand()%21)-10; printf("value x: %d value y: %d carga: %d \n", value_x, value_y, value_q); vector_cargas.push_back(carga(value_x, value_y, value_q)); } //Lee las cargas generadas desde el vector /* std::cout << "Lee las cargas generadas desde el vector" << std::endl; std::vector<carga>::iterator ptr; for(ptr = vector_cargas.begin(); ptr < vector_cargas.end(); ptr++){ std::cout << "value x: " << ptr->x << ", value y: " << ptr->y << ", carga: " << ptr->q << std::endl; }*/ }
#include "Orange.h" Orange::Orange() { points = ORANGE_DATA::POINTS; } void Orange::Update() { } void Orange::Draw() { } Orange::~Orange() { }
float const aVCC = 3.346; // Az AVCC pin-en mért feszültség. Az Arduino az 3.3 V-os tápfeszültséget használja referenciának a mérések során. (Névleges érték = 3,3 V, Valódi érték 3,292 V) const int AnalogInPin_T1 = A0; // A0 analóg pinről olvassa be az 1. reaktor hőmérséklet távadójának értékét. int SensorValue_T1[10]; // A távadóró beolvasott hőmérsékletértéket tárolja már digitális formában (0-1023). float Temperature_1; // Kalibráció szerinti hőmérséklet adatot tárolja. float Voltage_T1; // A hőmérséklet távadón eső feszültséget tároló változó. int AvarageBits_T1; // 10 mintázás eredményének értékét tartalmazó változó (digitális érték). const int AnalogInPin_p1 = A1; // ugyanez csak az 1. reaktor nyomás távadójára. int SensorValue_p1[10]; float Pressure_1; float Voltage_p1; int AvarageBits_p1; void setup () { Serial.begin(9600); // Soros kommunikáció megnyitása. } void loop() { analogReference(EXTERNAL); // Az ADC referencia a lap 3.3 V-os tápfeszültséget használja referenciának a feszültségméréshez. --> ehhez az kell, hogy a a 3.3V pin össze legyen kötve az AREF pin-nel. // NAGYON FONTOS! Az analogReference() parancs semmiképpen sem lehet default beállításon, mert akkor megsüti az Arduino-t. burn8readings(A0); // Az Analóg/Digitál konverter nem lehet folyamatosan bekapcsolva, mert akkor nagyon sok hő diszcipálódik rajta --> Tűzveszélyes és a változó ellenállások miatt a mérést is meghamisítja. // Az fejlesztőkörnyezetbe táplált analogRead() parancsot miután végrehajtotta a board, az ADC-t kikapcsolja. Az újabb mérés során való bekapcsolásakkor, azonban magának az ADC-nek a bekapcsolása viszonylag nagy zajforrás lehet. // Emiatt nagyon fontos, hogy pár "vakmintát" csináltassunk az Arduinoval, hogy amely mintázásoknak viszonylag nagy lesz a zajtartalma. Azt javasolták, hogy ez kb. 4-5 mérés. Én azért ráküldtem nyolcat. Ezen már ne múljon... for(int i = 0; i < 10; i++) // 10-szer egymás után mintázza az egyes analóg bemeneteket, amiket 10-10 tagú tömbökben tárol el. { SensorValue_T1[i] = analogRead(AnalogInPin_T1); SensorValue_p1[i] = analogRead(AnalogInPin_p1); } AvarageBits_T1 = Avarage_Bits(SensorValue_T1, 10); // A tíz beolvasott digitális mérést átlagolja (jobb jel-zaj viszony), amely értékekből számoljuk majd ki a hőmérséklet és nyomás értékeket a kalibrációs egyenes segítségével. AvarageBits_p1 = Avarage_Bits(SensorValue_p1, 10); Temperature_1 = 0.1648 * AvarageBits_T1 - 65,198; // Kalibrációs egyenesek. !!!444!!! A végső vezetékelés kialaításánál a vezetékek hossza és minősége (lásd ellenállása) elméletileg megváltoztathatja a kalibrációs egyenes metszetét. Pressure_1 = 0.3418 * AvarageBits_p1 - 74,013; // A minél pontosabb értékek elérésének érdekében a kalibrációt érdemes a végső kialakításnál elvégezni. Voltage_T1 = (((float)AvarageBits_T1)/(1023)) * aVCC; // Feszültség értékek számolt értéke a felhasznált referencia pontos értékének ismeretében. Voltage_p1 = ((float)(AvarageBits_p1)/(1023)) * aVCC; Serial.print("T1");Serial.println(Temperature_1 , 2); Serial.print("p1");Serial.println(Pressure_1 , 2); Serial.print("U1T");Serial.println(Voltage_T1 , 2); Serial.print("U1p");Serial.println(Voltage_p1 , 2); Serial.print("bit1T");Serial.println(AvarageBits_T1); Serial.print("bit1p");Serial.println(AvarageBits_p1); delay (1000); // 1 másodpercet vár minden mérés között } float Avarage_Bits (int * array, int len) // bit-ek átlagát kiszámoló függvény. { long sum = 0L ; for (int i = 0 ; i < len ; i++) sum += array [i] ; return ((float) sum) / len ; } int burn8readings(const int CurrentAnalogPin) // 8 vakmérést végző függvény. { int TemporaryRead[8]; for(int i = 0; i < 8; i++) { TemporaryRead[i] = analogRead(CurrentAnalogPin); } memset(TemporaryRead, 0, 8); }
// Created on: 2005-04-10 // Created by: Andrey BETENEV // Copyright (c) 2005-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _Standard_Mutex_HeaderFile #define _Standard_Mutex_HeaderFile #include <Standard_Integer.hxx> #include <Standard_Boolean.hxx> #include <Standard_ErrorHandler.hxx> #include <NCollection_Shared.hxx> #if defined(_WIN32) #include <windows.h> #else #include <pthread.h> #include <unistd.h> #include <time.h> #endif /** * @brief Mutex: a class to synchronize access to shared data. * * This is simple encapsulation of tools provided by the * operating system to synchronize access to shared data * from threads within one process. * * Current implementation is very simple and straightforward; * it is just a wrapper around POSIX pthread library on UNIX/Linux, * and CRITICAL_SECTIONs on Windows NT. It does not provide any * advanced functionality such as recursive calls to the same mutex from * within one thread (such call will freeze the execution). * * Note that all the methods of that class are made inline, in order * to keep maximal performance. This means that a library using the mutex * might need to be linked to threads library directly. * * The typical use of this class should be as follows: * - create instance of the class Standard_Mutex in the global scope * (whenever possible, or as a field of your class) * - create instance of class Standard_Mutex::Sentry using that Mutex * when entering critical section * * Note that this class provides one feature specific to Open CASCADE: * safe unlocking the mutex when signal is raised and converted to OCC * exceptions (Note that with current implementation of this functionality * on UNIX and Linux, C longjumps are used for that, thus destructors of * classes are not called automatically). * * To use this feature, call RegisterCallback() after Lock() or successful * TryLock(), and UnregisterCallback() before Unlock() (or use Sentry classes). */ class Standard_Mutex : public Standard_ErrorHandler::Callback { public: /** * @brief Simple sentry class providing convenient interface to mutex. * * Provides automatic locking and unlocking a mutex in its constructor * and destructor, thus ensuring correct unlock of the mutex even in case of * raising an exception or signal from the protected code. * * Create instance of that class when entering critical section. */ class Sentry { public: //! Constructor - initializes the sentry object by reference to a //! mutex (which must be initialized) and locks the mutex immediately Sentry (Standard_Mutex& theMutex) : myMutex (&theMutex) { Lock(); } //! Constructor - initializes the sentry object by pointer to a //! mutex and locks the mutex if its pointer is not NULL Sentry (Standard_Mutex* theMutex) : myMutex (theMutex) { if (myMutex != NULL) { Lock(); } } //! Destructor - unlocks the mutex if already locked. ~Sentry() { if (myMutex != NULL) { Unlock(); } } private: //! Lock the mutex void Lock() { myMutex->Lock(); myMutex->RegisterCallback(); } //! Unlock the mutex void Unlock() { myMutex->UnregisterCallback(); myMutex->Unlock(); } //! This method should not be called (prohibited). Sentry (const Sentry &); //! This method should not be called (prohibited). Sentry& operator = (const Sentry &); private: Standard_Mutex* myMutex; }; public: //! Constructor: creates a mutex object and initializes it. //! It is strongly recommended that mutexes were created as //! static objects whenever possible. Standard_EXPORT Standard_Mutex (); //! Destructor: destroys the mutex object Standard_EXPORT ~Standard_Mutex (); //! Method to lock the mutex; waits until the mutex is released //! by other threads, locks it and then returns Standard_EXPORT void Lock (); //! Method to test the mutex; if the mutex is not hold by other thread, //! locks it and returns True; otherwise returns False without waiting //! mutex to be released. Standard_EXPORT Standard_Boolean TryLock (); //! Method to unlock the mutex; releases it to other users void Unlock (); private: //! Callback method to unlock the mutex if OCC exception or signal is raised Standard_EXPORT virtual void DestroyCallback() Standard_OVERRIDE; //! This method should not be called (prohibited). Standard_Mutex (const Standard_Mutex &); //! This method should not be called (prohibited). Standard_Mutex& operator = (const Standard_Mutex &); private: #if (defined(_WIN32) || defined(__WIN32__)) CRITICAL_SECTION myMutex; #else pthread_mutex_t myMutex; #endif }; typedef NCollection_Shared<Standard_Mutex> Standard_HMutex; // Implementation of the method Unlock is inline, since it is // just a shortcut to system function inline void Standard_Mutex::Unlock () { #if (defined(_WIN32) || defined(__WIN32__)) LeaveCriticalSection (&myMutex); #else pthread_mutex_unlock (&myMutex); #endif } #endif /* _Standard_Mutex_HeaderFile */
#include <stdio.h> #include <iostream> #include <string.h> #include <sys/socket.h> #include <thread> #include <chrono> #include "TCPServer.h" #define MAX_PACKET_LEN 1024 #define SERVER_PORT 6400 void handle_connection(const int client_sock, const char* client_ip, const int client_port) { char buffer[MAX_PACKET_LEN]; while (true) { memset(&buffer, 0, MAX_PACKET_LEN); int bytes_received = recv(client_sock, buffer, sizeof(buffer), 0); if (bytes_received < 0) { std::cout << "Error reading message from " << client_ip << ":" << client_port << std::endl; break; } if (bytes_received == 0) { std::cout << "Client " << client_ip << ":" << client_port << " disconnected" << std::endl; break; } std::cout << client_ip << ":" << client_port << " - " << buffer << std::endl; const char* response = "Here is your data"; int bytes_sent = send(client_sock, response, sizeof(response), 0); if (bytes_sent < 0) { std::cout << "Error sending message to " << client_ip << ":" << client_port << std::endl; break; } } shutdown(client_sock, SHUT_RDWR); } int main() { TCPServer* server = new TCPServer(SERVER_PORT, handle_connection, true); while (true) { //Do other stuff std::this_thread::sleep_for (std::chrono::seconds(1)); } }
#ifndef __HiroCat__GMobController__ #define __HiroCat__GMobController__ class GEnemyController : public GActorController { private: GnMemberSlot1<GEnemyController, Gn2DActor::TimeEvent*> mCallbackActorEventSlot; public: static GEnemyController* Create(const gchar* pcID, guint32 uiLevel); protected: GEnemyController(); protected: bool InitController(); bool InitActionComponents(); bool InitInfoCompenent(const gchar* pcID, guint32 uiLevel); void ActorCallbackFunc(Gn2DActor::TimeEvent* pEvent); }; #endif
#include <iostream> #include <bs/ewma.hpp> #include <bs/frame_range.hpp> #include <bs/utils.hpp> #include <bs/temporal_median.hpp> #include <boost/make_shared.hpp> #include <boost/program_options.hpp> namespace po = boost::program_options; #include <range/v3/front.hpp> #include <range/v3/action/take.hpp> #include <range/v3/view/take.hpp> #include <options.hpp> #include <run.hpp> // // options_t::options_t is specific to each example: // options_t::options_t (int argc, char** argv) { { auto tmp = std::make_pair ( "program", po::variable_value (std::string (argv [0]), false)); map_.insert (tmp); } po::options_description generic ("Generic options"); po::options_description config ("Configuration options"); generic.add_options () ("version", "version") ("help", "this"); config.add_options () ("display,d", "display frames.") ("input,i", po::value< std::string > ()->default_value ("0"), "input (file or stream index).") ("lambda", po::value< double > ()->default_value (7), "a threshold multiplier (2)") ("history-size", po::value< size_t > ()->default_value (9), "length of frame history buffer (9)") ("frame-interval", po::value< size_t > ()->default_value (16), "interval between frames sampled for history buffer (16)") ("lo", po::value< size_t > ()->default_value (2), "distance from median for low threshold(2)") ("hi", po::value< size_t > ()->default_value (4), "distance from median for high threshold (4)"); desc_ = boost::make_shared< po::options_description > (); desc_->add (generic); desc_->add (config); store (po::command_line_parser (argc, argv).options (*desc_).run (), map_); notify (map_); } //////////////////////////////////////////////////////////////////////// static void program_options_from (int& argc, char** argv) { bool complete_invocation = false; options_t program_options (argc, argv); if (program_options.have ("version")) { std::cout << "OpenCV v3.1\n"; complete_invocation = true; } if (program_options.have ("help")) { std::cout << program_options.description () << std::endl; complete_invocation = true; } if (complete_invocation) exit (0); global_options (program_options); } //////////////////////////////////////////////////////////////////////// static cv::Mat bootstrap (cv::VideoCapture& cap) { using namespace ranges; // // The bootstrapping function: // bs::ewma_t f; // // Learn the background over 15 frames: // auto frames = bs::getframes_from (cap); for (auto frame : (frames | view::take (15))) { f (bs::scale_frame (frame)); } return f.value (); } static void process_temporal_median_background (cv::VideoCapture& cap, const options_t& opts) { const bool display = opts.have ("display"); auto background_model = bootstrap (cap); bs::temporal_median_t temporal_median ( background_model, opts ["history-size" ].as< size_t > (), opts ["frame-interval" ].as< size_t > (), opts ["lo" ].as< size_t > (), opts ["hi" ].as< size_t > ()); for (auto& frame : bs::getframes_from (cap)) { bs::frame_delay temp { 10 }; auto mask = temporal_median (bs::scale_frame (frame)); if (display) imshow ("Temporal median", mask); if (temp.wait_for_key (27)) break; } } //////////////////////////////////////////////////////////////////////// int main (int argc, char** argv) { program_options_from (argc, argv); return run_with (process_temporal_median_background, global_options ()), 0; }
#pragma once class LockGuard { public: LockGuard() { InitializeCriticalSection(&m_lock); } ~LockGuard() { DeleteCriticalSection(&m_lock); } void Lock() { EnterCriticalSection(&m_lock); } void Unlock() { LeaveCriticalSection(&m_lock); } private: CRITICAL_SECTION m_lock; }; class AutoLock { public: AutoLock(LockGuard &lockGuard) : m_lock(lockGuard) { m_lock.Lock(); } ~AutoLock() { m_lock.Unlock(); } private: LockGuard &m_lock; };
#include <stdio.h> #include <iostream> #include <math.h> #include <glut.h> #include <string.h> #include "Hud.h" using namespace std; Hud::Hud(void) { } Hud::~Hud(void) { } void Hud::drawHud(Camera &cam, int width, int height) { float x, z, y; w = width; h = height; glPushMatrix(); glLoadIdentity(); setOrthographicProjection(width, height); drawCrosshair(width/2, height/2, 10); cam.GetPos(x, y, z); // Draw coords on screen drawLocation(x, y, z); cam.GetDirectionVector(x, y, z); drawLookAt(x, y, z); glPopMatrix(); restorePerspectiveProjection(); } void Hud::setOrthographicProjection(int width, int height) { glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); gluOrtho2D(0, width, height, 0); glMatrixMode(GL_MODELVIEW); } void Hud::restorePerspectiveProjection() { glMatrixMode(GL_PROJECTION); // restore previous projection matrix glPopMatrix(); // get back to modelview mode glMatrixMode(GL_MODELVIEW); } void Hud::renderBitmapString(float x, float y, void *font, const char *string) { const char *c; glRasterPos2f(x, y); for (c = string; *c != '\0'; c++) { glutBitmapCharacter(font, *c); } } // draw location relative to 2D plane void Hud::drawLocation(float x, float y, float z) { char loc[50]; sprintf(loc, "%4.2f, %4.2f, %4.2f", x, y, z); glColor3f(0.0f,1.0f,1.0f); renderBitmapString(w-150.0, 35.0, GLUT_BITMAP_HELVETICA_18, loc); } void Hud::drawCrosshair(float x, float y, int size) { glColor3f(1, 0, 0); glBegin(GL_LINES); glVertex2f(x - size, y); glVertex2f(x + size, y); glEnd(); glBegin(GL_LINES); glVertex2f(x, y - size); glVertex2f(x, y + size); glEnd(); } void Hud::drawLookAt(float x, float y, float z) { char dir[5]; switch (getDirection(x * 100, z * 100)) { case Direction::NORTH: sprintf(dir, "N"); break; case Direction::NORTHEAST: sprintf(dir, "NE"); break; case Direction::EAST: sprintf(dir, "E"); break; case Direction::SOUTHEAST: sprintf(dir, "SE"); break; case Direction::SOUTH: sprintf(dir, "S"); break; case Direction::SOUTHWEST: sprintf(dir, "SW"); break; case Direction::WEST: sprintf(dir, "W"); break; case Direction::NORTHWEST: sprintf(dir, "NW"); break; } char loc[50]; sprintf(loc, "%4.0f %4.0f %4.0f", x*100, y*100, z*100); glColor3f(0.0f, 1.0f, 1.0f); renderBitmapString(10.0, 35.0, GLUT_BITMAP_HELVETICA_18, loc); renderBitmapString((w/2.0)-2, 35.0, GLUT_BITMAP_HELVETICA_18, dir); } Direction Hud::getDirection(float x, float z) { Direction facing = Direction::NORTH; if (x > -35) { if (x < 35) // W or E { if (z > 0) // E facing = Direction::EAST; else // W facing = Direction::WEST; } else // NW, N or NE { if (x >= 85) // N facing = Direction::NORTH; else if (z < 0) // NW facing = Direction::NORTHWEST; else // NE facing = Direction::NORTHEAST; } } else // x <= -35 SW, S or SE { if (x <= -85) // S facing = Direction::SOUTH; else if (z < 0) // SW facing = Direction::SOUTHWEST; else // SE facing = Direction::SOUTHEAST; } return facing; }
#include "AvatarLogicCalculator.h" AvatarLogicCalculator::AvatarLogicCalculator() { } AvatarLogicCalculator::~AvatarLogicCalculator() { } void AvatarLogicCalculator::correctStepsDueToWallCollisions() { //in case of collision we stop the movement in that direction float stepX,stepY; m_avatarModel->getStep(&stepX,&stepY); if(collidesOnRight() == true && stepX > 0) {stepX = 0;} if(collidesOnLeft() == true && stepX < 0) {stepX = 0;} if(collidesOnCeiling() == true && stepY > 0 ) {stepY = 0;} if(collidesOnFloor() == true && stepY < 0 ) {stepY = 0;} m_avatarModel->setStep(stepX,stepY); } std::pair<float,float> AvatarLogicCalculator::computeDirection(float destinationX, float destinationY) { float avatarX = m_avatarModel->getTerrainPosition()[0]; float avatarY = m_avatarModel->getTerrainPosition()[1]; float hypo = std::sqrtf( (avatarX-destinationX)* (avatarX-destinationX) + (avatarY-destinationY)* (avatarY-destinationY) ); float stepX = (destinationX-avatarX)/hypo; float stepY = (destinationY-avatarY)/hypo; return std::make_pair(stepX,stepY); } void AvatarLogicCalculator::computeAndSetDirection(float destinationX, float destinationY) { std::pair<float,float> directions = computeDirection(destinationX, destinationY); m_avatarModel->setStep(directions.first,directions.second); } void AvatarLogicCalculator::setAttackAction() { float stepX; float stepY; m_avatarModel->getStep(&stepX,&stepY); //the following sets the action according to the angle between the avatar and the click //for this we devide 2pi radians into pi/4 rad slices starting at +pi/8 rads. //We compare stepX to the cos of the angle and we look at the sign of stepY to find out if //The click took part over the avatar or under it. if(stepX > 0.92387953251) { m_avatarModel->setAction(AvatarModel::AvatarAction::AVATAR_ACTION_ATTACK_RIGHT); } else if(stepX > 0.38268343236 && stepX<= 0.92387953251) { if(stepY > 0) { m_avatarModel->setAction(AvatarModel::AvatarAction::AVATAR_ACTION_ATTACK_UP_RIGHT); } else { m_avatarModel->setAction(AvatarModel::AvatarAction::AVATAR_ACTION_ATTACK_DOWN_RIGHT); } } else if( stepX > -0.38268343236 && stepX <= 0.38268343236) { if(stepY > 0) { m_avatarModel->setAction(AvatarModel::AvatarAction::AVATAR_ACTION_ATTACK_UP); } else { m_avatarModel->setAction(AvatarModel::AvatarAction::AVATAR_ACTION_ATTACK_DOWN); } } else if(stepX > -0.92387953251 && stepX<= -0.38268343236) { if(stepY > 0) { m_avatarModel->setAction(AvatarModel::AvatarAction::AVATAR_ACTION_ATTACK_UP_LEFT); } else { m_avatarModel->setAction(AvatarModel::AvatarAction::AVATAR_ACTION_ATTACK_DOWN_LEFT); } } else if (stepX <= -0.92387953251) { m_avatarModel->setAction(AvatarModel::AvatarAction::AVATAR_ACTION_ATTACK_LEFT); } } void AvatarLogicCalculator::setMoveAction() { float stepX; float stepY; m_avatarModel->getStep(&stepX,&stepY); //the following sets the action according to the angle between the avatar and the click //for this we devide 2pi radians into pi/4 rad slices starting at +pi/8 rads. //We compare stepX to the cos of the angle and we look at the sign of stepY to find out if //The click took part over the avatar or under it. if(stepX > 0.92387953251) { m_avatarModel->setAction(AvatarModel::AvatarAction::AVATAR_ACTION_MOVE_RIGHT); } else if(stepX > 0.38268343236 && stepX<= 0.92387953251) { if(stepY > 0) { m_avatarModel->setAction(AvatarModel::AvatarAction::AVATAR_ACTION_MOVE_UP_RIGHT); } else { m_avatarModel->setAction(AvatarModel::AvatarAction::AVATAR_ACTION_MOVE_DOWN_RIGHT); } } else if( stepX > -0.38268343236 && stepX <= 0.38268343236) { if(stepY > 0) { m_avatarModel->setAction(AvatarModel::AvatarAction::AVATAR_ACTION_MOVE_UP); } else { m_avatarModel->setAction(AvatarModel::AvatarAction::AVATAR_ACTION_MOVE_DOWN); } } else if(stepX > -0.92387953251 && stepX<= -0.38268343236) { if(stepY > 0) { m_avatarModel->setAction(AvatarModel::AvatarAction::AVATAR_ACTION_MOVE_UP_LEFT); } else { m_avatarModel->setAction(AvatarModel::AvatarAction::AVATAR_ACTION_MOVE_DOWN_LEFT); } } else if (stepX <= -0.92387953251) { m_avatarModel->setAction(AvatarModel::AvatarAction::AVATAR_ACTION_MOVE_LEFT); } } bool AvatarLogicCalculator::collidesOnRight() { //get avatar logical location int avatarX = m_avatarModel->getTerrainPosition()[0]; int avatarY = m_avatarModel->getTerrainPosition()[1]; //get the right position of the sprite in logical position int xRightWall = m_avatarModel->getTerrainPosition()[0] + (m_avatarModel->getPixelWidth()/PIXELS_PER_METER)/2; //get reference tile x and y int tile_x = (xRightWall) / (m_levelModel->getTileSetTileWidth()/ PIXELS_PER_METER); int tile_y = avatarY / (m_levelModel->getTileSetTileHeight()/ PIXELS_PER_METER); //get number of vertical tiles in which the avatar can be divided int numVerticalTiles = (m_avatarModel->getPixelHeight()/m_levelModel->getTileSetTileHeight()) ; for(int verticalTile = 0 ; verticalTile < numVerticalTiles ; verticalTile++) { //check for solidity of tile matching right border if(m_levelModel->getTileSolidity(tile_x ,tile_y + verticalTile) == 9) {return true;} } return false; } bool AvatarLogicCalculator::collidesOnLeft() { //get avatar logical location int avatarX = m_avatarModel->getTerrainPosition()[0]; int avatarY = m_avatarModel->getTerrainPosition()[1]; //get the right position of the sprite in logical position int xLeftWall = m_avatarModel->getTerrainPosition()[0] - (m_avatarModel->getPixelWidth()/PIXELS_PER_METER)/2; //get reference tile x and y int tile_x = (xLeftWall) / (m_levelModel->getTileSetTileWidth()/ PIXELS_PER_METER); int tile_y = avatarY / (m_levelModel->getTileSetTileHeight()/ PIXELS_PER_METER); //get number of vertical tiles in which the avatar can be divided int numVerticalTiles = (m_avatarModel->getPixelHeight()/m_levelModel->getTileSetTileHeight()) ; for(int verticalTile = 0 ; verticalTile < numVerticalTiles ; verticalTile++) { if(m_levelModel->getTileSolidity(tile_x ,tile_y + verticalTile) == 9) {return true;} } return false; } bool AvatarLogicCalculator::collidesOnCeiling() { int avatarX = m_avatarModel->getTerrainPosition()[0]; float yCeiling= m_avatarModel->getTerrainPosition()[1] + (m_levelModel->getTileSetTileWidth()/PIXELS_PER_METER)/2; //get reference tile x and y int tile_x = avatarX / (m_levelModel->getTileSetTileWidth()/ PIXELS_PER_METER); int tile_y = yCeiling / (m_levelModel->getTileSetTileHeight()/ PIXELS_PER_METER); //get number of horizontal tiles in which the avatar can be divided int numHorizontalTiles = (m_avatarModel->getPixelWidth()/m_levelModel->getTileSetTileWidth()) ; if( (avatarX % ((int)(m_levelModel->getTileSetTileWidth()/PIXELS_PER_METER)) ) != 0) numHorizontalTiles++; //check using only central tiles int i=0; if(numHorizontalTiles >2) { i =1; numHorizontalTiles--; } else { numHorizontalTiles = 1; } while( (i<numHorizontalTiles)) { if(m_levelModel->getTileSolidity(tile_x + i,tile_y) == 9) {return true;} i++; } return false; } bool AvatarLogicCalculator::collidesOnFloor() { float avatarX = m_avatarModel->getTerrainPosition()[0]; //we use tileset tile width to correct the collision on purpose. Otherwise the player might get stuck when path-walking //This probably should be done differently for the other avatars. float yFloor= m_avatarModel->getTerrainPosition()[1] - (m_levelModel->getTileSetTileHeight()/PIXELS_PER_METER)/2; //get reference tile x and y conversion to int intended int tile_x = avatarX / (m_levelModel->getTileSetTileWidth()/ PIXELS_PER_METER); int tile_y = yFloor / (m_levelModel->getTileSetTileHeight()/ PIXELS_PER_METER); //get number of horizontal tiles in which the avatar can be divided int numHorizontalTiles = (m_avatarModel->getPixelWidth()/m_levelModel->getTileSetTileWidth()) ; if( ((int)avatarX % ((int)(m_levelModel->getTileSetTileWidth()/PIXELS_PER_METER)) ) != 0) numHorizontalTiles++; //check using only central tiles int i=0; if(numHorizontalTiles >2) { i =1; numHorizontalTiles--; } else { numHorizontalTiles = 1; } while( (i<numHorizontalTiles)) { if(m_levelModel->getTileSolidity(tile_x + i,tile_y) == 9) {return true;} i++; } return false; } bool AvatarLogicCalculator::collides(const AvatarModel::Rect& rect) { return (((m_avatarModel->getRect().left>=rect.left) && (m_avatarModel->getRect().left<=rect.right) && (m_avatarModel->getRect().bottom<=rect.bottom) && (m_avatarModel->getRect().top>=rect.bottom)) || ((m_avatarModel->getRect().left<=rect.left) && (m_avatarModel->getRect().right>=rect.left) && (m_avatarModel->getRect().bottom<=rect.bottom) && (m_avatarModel->getRect().top>=rect.bottom)) || ((m_avatarModel->getRect().left>=rect.left) && (m_avatarModel->getRect().left<=rect.right) && (m_avatarModel->getRect().bottom>=rect.bottom) && (m_avatarModel->getRect().bottom<=rect.top))|| ((m_avatarModel->getRect().left<=rect.left) && (m_avatarModel->getRect().right>=rect.left) && (m_avatarModel->getRect().bottom>=rect.bottom) && (m_avatarModel->getRect().bottom<=rect.top)) ); }
#include <cstdlib> #include <iostream> #include <stack> using namespace std; int main(){ stack <int> a; int i; for(i=1; i < 5; i++){ a.push(i); } while( a.empty() ) { cout<<"Esta vacia"; break; } cout << "El ultimo elemento es: "<<a.top() ; a.pop(); cout<<"\nEl nuevo ultimo elemento es: "<<a.top(); }
// Created by: Peter KURNEV // Copyright (c) 2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _BRepAlgoAPI_BuilderAlgo_HeaderFile #define _BRepAlgoAPI_BuilderAlgo_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <Standard_Handle.hxx> #include <BOPAlgo_GlueEnum.hxx> #include <BOPAlgo_PPaveFiller.hxx> #include <BOPAlgo_PBuilder.hxx> #include <BRepAlgoAPI_Algo.hxx> #include <BRepTools_History.hxx> #include <Precision.hxx> #include <Standard_Real.hxx> #include <TopTools_ListOfShape.hxx> //! The class contains API level of the General Fuse algorithm.<br> //! //! Additionally to the options defined in the base class, the algorithm has //! the following options:<br> //! - *Safe processing mode* - allows to avoid modification of the input //! shapes during the operation (by default it is off); //! - *Gluing options* - allows to speed up the calculation of the intersections //! on the special cases, in which some sub-shapes are coinciding. //! - *Disabling the check for inverted solids* - Disables/Enables the check of the input solids //! for inverted status (holes in the space). The default value is TRUE, //! i.e. the check is performed. Setting this flag to FALSE for inverted solids, //! most likely will lead to incorrect results. //! - *Disabling history collection* - allows disabling the collection of the history //! of shapes modifications during the operation. //! //! It returns the following Error statuses:<br> //! - 0 - in case of success;<br> //! - *BOPAlgo_AlertTooFewArguments* - in case there are no enough arguments to perform the operation;<br> //! - *BOPAlgo_AlertIntersectionFailed* - in case the intersection of the arguments has failed;<br> //! - *BOPAlgo_AlertBuilderFailed* - in case building of the result shape has failed.<br> //! //! Warnings statuses from underlying DS Filler and Builder algorithms //! are collected in the report. //! //! The class provides possibility to simplify the resulting shape by unification //! of the tangential edges and faces. It is performed by the method *SimplifyResult*. //! See description of this method for more details. //! class BRepAlgoAPI_BuilderAlgo : public BRepAlgoAPI_Algo { public: DEFINE_STANDARD_ALLOC public: //! @name Constructors //! Empty constructor Standard_EXPORT BRepAlgoAPI_BuilderAlgo(); Standard_EXPORT virtual ~BRepAlgoAPI_BuilderAlgo(); //! Constructor with prepared Filler object Standard_EXPORT BRepAlgoAPI_BuilderAlgo(const BOPAlgo_PaveFiller& thePF); public: //! @name Setting/Getting data for the algorithm //! Sets the arguments void SetArguments (const TopTools_ListOfShape& theLS) { myArguments = theLS; } //! Gets the arguments const TopTools_ListOfShape& Arguments() const { return myArguments; } public: //! @name Setting options //! Sets the flag that defines the mode of treatment. //! In non-destructive mode the argument shapes are not modified. Instead //! a copy of a sub-shape is created in the result if it is needed to be updated. void SetNonDestructive(const Standard_Boolean theFlag) { myNonDestructive = theFlag; } //! Returns the flag that defines the mode of treatment. //! In non-destructive mode the argument shapes are not modified. Instead //! a copy of a sub-shape is created in the result if it is needed to be updated. Standard_Boolean NonDestructive() const { return myNonDestructive; } //! Sets the glue option for the algorithm, //! which allows increasing performance of the intersection //! of the input shapes. void SetGlue(const BOPAlgo_GlueEnum theGlue) { myGlue = theGlue; } //! Returns the glue option of the algorithm BOPAlgo_GlueEnum Glue() const { return myGlue; } //! Enables/Disables the check of the input solids for inverted status void SetCheckInverted(const Standard_Boolean theCheck) { myCheckInverted = theCheck; } //! Returns the flag defining whether the check for input solids on inverted status //! should be performed or not. Standard_Boolean CheckInverted() const { return myCheckInverted; } public: //! @name Performing the operation //! Performs the algorithm Standard_EXPORT virtual void Build(const Message_ProgressRange& theRange = Message_ProgressRange()) Standard_OVERRIDE; public: //! @name Result simplification //! Simplification of the result shape is performed by the means of //! *ShapeUpgrade_UnifySameDomain* algorithm. The result of the operation will //! be overwritten with the simplified result. //! //! The simplification is performed without creation of the Internal shapes, //! i.e. shapes connections will never be broken. //! //! Simplification is performed on the whole result shape. Thus, if the input //! shapes contained connected tangent edges or faces unmodified during the operation //! they will also be unified. //! //! After simplification, the History of result simplification is merged into the main //! history of operation. So, it is taken into account when asking for Modified, //! Generated and Deleted shapes. //! //! Some options of the main operation are passed into the Unifier: //! - Fuzzy tolerance of the operation is given to the Unifier as the linear tolerance. //! - Non destructive mode here controls the safe input mode in Unifier. //! //! @param theUnifyEdges Controls the edges unification. TRUE by default. //! @param theUnifyFaces Controls the faces unification. TRUE by default. //! @param theAngularTol Angular criteria for tangency of edges and faces. //! Precision::Angular() by default. Standard_EXPORT void SimplifyResult(const Standard_Boolean theUnifyEdges = Standard_True, const Standard_Boolean theUnifyFaces = Standard_True, const Standard_Real theAngularTol = Precision::Angular()); public: //! @name History support //! Returns the shapes modified from the shape <theS>. //! If any, the list will contain only those splits of the //! given shape, contained in the result. Standard_EXPORT virtual const TopTools_ListOfShape& Modified(const TopoDS_Shape& theS) Standard_OVERRIDE; //! Returns the list of shapes generated from the shape <theS>. //! In frames of Boolean Operations algorithms only Edges and Faces //! could have Generated elements, as only they produce new elements //! during intersection: //! - Edges can generate new vertices; //! - Faces can generate new edges and vertices. Standard_EXPORT virtual const TopTools_ListOfShape& Generated(const TopoDS_Shape& theS) Standard_OVERRIDE; //! Checks if the shape <theS> has been completely removed from the result, //! i.e. the result does not contain the shape itself and any of its splits. //! Returns TRUE if the shape has been deleted. Standard_EXPORT virtual Standard_Boolean IsDeleted(const TopoDS_Shape& aS) Standard_OVERRIDE; //! Returns true if any of the input shapes has been modified during operation. Standard_EXPORT virtual Standard_Boolean HasModified() const; //! Returns true if any of the input shapes has generated shapes during operation. Standard_EXPORT virtual Standard_Boolean HasGenerated() const; //! Returns true if any of the input shapes has been deleted during operation. //! Normally, General Fuse operation should not have Deleted elements, //! but all derived operation can have. Standard_EXPORT virtual Standard_Boolean HasDeleted() const; public: //! @name Enabling/Disabling the history collection. //! Allows disabling the history collection void SetToFillHistory(const Standard_Boolean theHistFlag) { myFillHistory = theHistFlag; } //! Returns flag of history availability Standard_Boolean HasHistory() const { return myFillHistory; } public: //! @name Getting the section edges //! Returns a list of section edges. //! The edges represent the result of intersection between arguments of operation. Standard_EXPORT const TopTools_ListOfShape& SectionEdges(); public: //! @name Getting tools performing the job //! Returns the Intersection tool const BOPAlgo_PPaveFiller& DSFiller() const { return myDSFiller; } //! Returns the Building tool const BOPAlgo_PBuilder& Builder() const { return myBuilder; } //! History tool Handle(BRepTools_History) History() const { return myFillHistory ? myHistory : NULL; } protected: //! @name Setting options to the Intersection tool //! Sets options (available in child classes) for the intersection tool. //! Here it does nothing. virtual void SetAttributes() {} protected: //! @name Protected methods for shapes intersection and building result //! Intersects the given shapes with the intersection tool Standard_EXPORT void IntersectShapes(const TopTools_ListOfShape& theArgs, const Message_ProgressRange& theRange); //! Builds the resulting shape Standard_EXPORT void BuildResult(const Message_ProgressRange& theRange = Message_ProgressRange()); protected: //! @name Clearing the contents of the algorithm //! Clears the algorithm from previous runs Standard_EXPORT virtual void Clear() Standard_OVERRIDE; protected: //! @name Fields // Inputs TopTools_ListOfShape myArguments; //!< Arguments of the operation // Options Standard_Boolean myNonDestructive; //!< Non-destructive mode management BOPAlgo_GlueEnum myGlue; //!< Gluing mode management Standard_Boolean myCheckInverted; //!< Check for inverted solids management Standard_Boolean myFillHistory; //!< Controls the history collection // Tools Standard_Boolean myIsIntersectionNeeded; //!< Flag to control whether the intersection //! of arguments should be performed or not BOPAlgo_PPaveFiller myDSFiller; //!< Intersection tool performs intersection of the //! argument shapes. BOPAlgo_PBuilder myBuilder; //!< Building tool performs construction of the result //! basing on the results of intersection Handle(BRepTools_History) myHistory; //!< General History tool, containing all History of //! shapes modifications during the operation //! (including result simplification) Handle(BRepTools_History) mySimplifierHistory; //!< History of result shape simplification }; #endif // _BRepAlgoAPI_BuilderAlgo_HeaderFile
#include<bits/stdc++.h> using namespace std; int main() { int n; cin >> n; for (int i=1; i <= n; i++) { for (int j=1; j <= n-i ; j++) cout << "~"; for (int j=1; j <= 2*i-1 ; j++) cout << "*"; cout << endl; } for (int i=n-1; i >=1 ; i--) { for (int j=n-i; j >= 1 ; j--) cout << "~"; for (int j=2*i-1; j >= 1 ; j--) cout << "*"; cout << endl; } return 0 ; }
// Created on: 1992-03-26 // Created by: Laurent BUCHARD // Copyright (c) 1992-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IntCurve_IConicTool_HeaderFile #define _IntCurve_IConicTool_HeaderFile #include <Standard.hxx> #include <Standard_DefineAlloc.hxx> #include <gp_Ax22d.hxx> #include <GeomAbs_CurveType.hxx> #include <gp_Trsf2d.hxx> class gp_Elips2d; class gp_Lin2d; class gp_Circ2d; class gp_Parab2d; class gp_Hypr2d; class gp_Pnt2d; class gp_Vec2d; //! Implementation of the ImpTool from IntImpParGen //! for conics of gp. class IntCurve_IConicTool { public: DEFINE_STANDARD_ALLOC Standard_EXPORT IntCurve_IConicTool(); Standard_EXPORT IntCurve_IConicTool(const IntCurve_IConicTool& IT); Standard_EXPORT IntCurve_IConicTool(const gp_Elips2d& E); Standard_EXPORT IntCurve_IConicTool(const gp_Lin2d& L); Standard_EXPORT IntCurve_IConicTool(const gp_Circ2d& C); Standard_EXPORT IntCurve_IConicTool(const gp_Parab2d& P); Standard_EXPORT IntCurve_IConicTool(const gp_Hypr2d& H); Standard_EXPORT gp_Pnt2d Value (const Standard_Real X) const; Standard_EXPORT void D1 (const Standard_Real U, gp_Pnt2d& P, gp_Vec2d& T) const; Standard_EXPORT void D2 (const Standard_Real U, gp_Pnt2d& P, gp_Vec2d& T, gp_Vec2d& N) const; //! Computes the value of the signed distance between //! the point P and the implicit curve. Standard_EXPORT Standard_Real Distance (const gp_Pnt2d& P) const; //! Computes the Gradient of the Signed Distance //! between a point and the implicit curve, at the //! point P. Standard_EXPORT gp_Vec2d GradDistance (const gp_Pnt2d& P) const; //! Returns the parameter U of the point on the implicit curve corresponding to the point P. //! The correspondence between P and the point P(U) on the //! implicit curve must be coherent with the way of determination of the signed distance. Standard_EXPORT Standard_Real FindParameter (const gp_Pnt2d& P) const; private: Standard_Real prm1; Standard_Real prm2; Standard_Real prm3; gp_Ax22d Axis; GeomAbs_CurveType type; gp_Trsf2d Abs_To_Object; }; #endif // _IntCurve_IConicTool_HeaderFile
#ifndef LINEPIECE_H #define LINEPIECE_H #include "abstracttetrispiece.h" class LinePiece : public AbstractTetrisPiece<LinePiece> { public: LinePiece( const TetrisCoordinate& centerCoordinate, int orientation = 0); virtual TetrisConstants::TetrisCellColor color() const override; virtual int numOrientations() const override; }; #endif // LINEPIECE_H
// Created on: 2000-06-15 // Created by: Edward AGAPOV // Copyright (c) 2000-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _XCAFDoc_ShapeTool_HeaderFile #define _XCAFDoc_ShapeTool_HeaderFile #include <Standard.hxx> #include <XCAFDoc_DataMapOfShapeLabel.hxx> #include <Standard_Boolean.hxx> #include <TDataStd_NamedData.hxx> #include <TDataStd_GenericEmpty.hxx> #include <TDF_LabelMap.hxx> #include <TDF_LabelSequence.hxx> #include <Standard_Integer.hxx> #include <Standard_OStream.hxx> #include <TColStd_SequenceOfHAsciiString.hxx> #include <TDF_AttributeSequence.hxx> #include <TopTools_SequenceOfShape.hxx> class Standard_GUID; class TDF_Label; class TopoDS_Shape; class TopLoc_Location; class XCAFDoc_GraphNode; class XCAFDoc_ShapeTool; DEFINE_STANDARD_HANDLE(XCAFDoc_ShapeTool, TDataStd_GenericEmpty) //! A tool to store shapes in an XDE //! document in the form of assembly structure, and to maintain this structure. //! Attribute containing Shapes section of DECAF document. //! Provide tools for management of Shapes section. //! The API provided by this class allows to work with this //! structure regardless of its low-level implementation. //! All the shapes are stored on child labels of a main label which is //! XCAFDoc_DocumentTool::LabelShapes(). The label for assembly also has //! sub-labels, each of which represents the instance of //! another shape in that assembly (component). Such sub-label //! stores reference to the label of the original shape in the form //! of TDataStd_TreeNode with GUID XCAFDoc::ShapeRefGUID(), and its //! location encapsulated into the NamedShape. //! For correct work with an XDE document, it is necessary to use //! methods for analysis and methods for working with shapes. //! For example: //! if ( STool->IsAssembly(aLabel) ) //! { Standard_Boolean subchilds = Standard_False; (default) //! Standard_Integer nbc = STool->NbComponents //! (aLabel[,subchilds]); //! } //! If subchilds is True, commands also consider sub-levels. By //! default, only level one is checked. //! In this example, number of children from the first level of //! assembly will be returned. Methods for creation and initialization: //! Constructor: //! XCAFDoc_ShapeTool::XCAFDoc_ShapeTool() //! Getting a guid: //! Standard_GUID GetID (); //! Creation (if does not exist) of ShapeTool on label L: //! Handle(XCAFDoc_ShapeTool) XCAFDoc_ShapeTool::Set(const TDF_Label& L) //! Analyze whether shape is a simple shape or an instance or a //! component of an assembly or it is an assembly ( methods of analysis). //! For example: //! STool->IsShape(aLabel) ; //! Analyze that the label represents a shape (simple //! shape, assembly or reference) or //! STool->IsTopLevel(aLabel); //! Analyze that the label is a label of a top-level shape. //! Work with simple shapes, assemblies and instances ( //! methods for work with shapes). //! For example: //! Add shape: //! Standard_Boolean makeAssembly; //! // True to interpret a Compound as an Assembly, False to take it //! as a whole //! aLabel = STool->AddShape(aShape, makeAssembly); //! Get shape: //! TDF_Label aLabel... //! // A label must be present if //! (aLabel.IsNull()) { ... no such label : abandon .. } //! TopoDS_Shape aShape; //! aShape = STool->GetShape(aLabel); //! if (aShape.IsNull()) //! { ... this label is not for a Shape ... } //! To get a label from shape. //! Standard_Boolean findInstance = Standard_False; //! (this is default value) //! aLabel = STool->FindShape(aShape [,findInstance]); //! if (aLabel.IsNull()) //! { ... no label found for this shape ... } class XCAFDoc_ShapeTool : public TDataStd_GenericEmpty { public: Standard_EXPORT static const Standard_GUID& GetID(); //! Create (if not exist) ShapeTool from XCAFDoc on <L>. Standard_EXPORT static Handle(XCAFDoc_ShapeTool) Set (const TDF_Label& L); //! Creates an empty tool //! Creates a tool to work with a document <Doc> //! Attaches to label XCAFDoc::LabelShapes() Standard_EXPORT XCAFDoc_ShapeTool(); //! Returns True if the label is a label of top-level shape, //! as opposed to component of assembly or subshape Standard_EXPORT Standard_Boolean IsTopLevel (const TDF_Label& L) const; //! Returns True if the label is not used by any assembly, i.e. //! contains sublabels which are assembly components //! This is relevant only if IsShape() is True //! (There is no Father TreeNode on this <L>) Standard_EXPORT static Standard_Boolean IsFree (const TDF_Label& L); //! Returns True if the label represents a shape (simple shape, //! assembly or reference) Standard_EXPORT static Standard_Boolean IsShape (const TDF_Label& L); //! Returns True if the label is a label of simple shape Standard_EXPORT static Standard_Boolean IsSimpleShape (const TDF_Label& L); //! Return true if <L> is a located instance of other shape //! i.e. reference Standard_EXPORT static Standard_Boolean IsReference (const TDF_Label& L); //! Returns True if the label is a label of assembly, i.e. //! contains sublabels which are assembly components //! This is relevant only if IsShape() is True Standard_EXPORT static Standard_Boolean IsAssembly (const TDF_Label& L); //! Return true if <L> is reference serving as component //! of assembly Standard_EXPORT static Standard_Boolean IsComponent (const TDF_Label& L); //! Returns True if the label is a label of compound, i.e. //! contains some sublabels //! This is relevant only if IsShape() is True Standard_EXPORT static Standard_Boolean IsCompound (const TDF_Label& L); //! Return true if <L> is subshape of the top-level shape Standard_EXPORT static Standard_Boolean IsSubShape (const TDF_Label& L); //! Checks whether shape <sub> is subshape of shape stored on //! label shapeL Standard_EXPORT Standard_Boolean IsSubShape (const TDF_Label& shapeL, const TopoDS_Shape& sub) const; Standard_EXPORT Standard_Boolean SearchUsingMap (const TopoDS_Shape& S, TDF_Label& L, const Standard_Boolean findWithoutLoc, const Standard_Boolean findSubshape) const; //! General tool to find a (sub) shape in the document //! * If findInstance is True, and S has a non-null location, //! first tries to find the shape among the top-level shapes //! with this location //! * If not found, and findComponent is True, tries to find the shape //! among the components of assemblies //! * If not found, tries to find the shape without location //! among top-level shapes //! * If not found and findSubshape is True, tries to find a //! shape as a subshape of top-level simple shapes //! Returns False if nothing is found Standard_EXPORT Standard_Boolean Search (const TopoDS_Shape& S, TDF_Label& L, const Standard_Boolean findInstance = Standard_True, const Standard_Boolean findComponent = Standard_True, const Standard_Boolean findSubshape = Standard_True) const; //! Returns the label corresponding to shape S //! (searches among top-level shapes, not including subcomponents //! of assemblies and subshapes) //! If findInstance is False (default), search for the //! input shape without location //! If findInstance is True, searches for the //! input shape as is. //! Return True if <S> is found. Standard_EXPORT Standard_Boolean FindShape (const TopoDS_Shape& S, TDF_Label& L, const Standard_Boolean findInstance = Standard_False) const; //! Does the same as previous method //! Returns Null label if not found Standard_EXPORT TDF_Label FindShape (const TopoDS_Shape& S, const Standard_Boolean findInstance = Standard_False) const; //! To get TopoDS_Shape from shape's label //! For component, returns new shape with correct location //! Returns False if label does not contain shape Standard_EXPORT static Standard_Boolean GetShape (const TDF_Label& L, TopoDS_Shape& S); //! To get TopoDS_Shape from shape's label //! For component, returns new shape with correct location //! Returns Null shape if label does not contain shape Standard_EXPORT static TopoDS_Shape GetShape (const TDF_Label& L); //! Gets shape from a sequence of shape's labels //! @param[in] theLabels a sequence of labels to get shapes from //! @return original shape in case of one label and a compound of shapes in case of more Standard_EXPORT static TopoDS_Shape GetOneShape(const TDF_LabelSequence& theLabels); //! Gets shape from a sequence of all top-level shapes which are free //! @return original shape in case of one label and a compound of shapes in case of more Standard_EXPORT TopoDS_Shape GetOneShape() const; //! Creates new (empty) top-level shape. //! Initially it holds empty TopoDS_Compound Standard_EXPORT TDF_Label NewShape() const; //! Sets representation (TopoDS_Shape) for top-level shape. Standard_EXPORT void SetShape (const TDF_Label& L, const TopoDS_Shape& S); //! Adds a new top-level (creates and returns a new label) //! If makeAssembly is True, treats TopAbs_COMPOUND shapes //! as assemblies (creates assembly structure). //! NOTE: <makePrepare> replace components without location //! in assembly by located components to avoid some problems. //! If AutoNaming() is True then automatically attaches names. Standard_EXPORT TDF_Label AddShape (const TopoDS_Shape& S, const Standard_Boolean makeAssembly = Standard_True, const Standard_Boolean makePrepare = Standard_True); //! Removes shape (whole label and all its sublabels) //! If removeCompletely is true, removes complete shape //! If removeCompletely is false, removes instance(location) only //! Returns False (and does nothing) if shape is not free //! or is not top-level shape Standard_EXPORT Standard_Boolean RemoveShape (const TDF_Label& L, const Standard_Boolean removeCompletely = Standard_True) const; //! set hasComponents into false Standard_EXPORT void Init(); //! Sets auto-naming mode to <V>. If True then for added //! shapes, links, assemblies and SHUO's, the TDataStd_Name attribute //! is automatically added. For shapes it contains a shape type //! (e.g. "SOLID", "SHELL", etc); for links it has a form //! "=>[0:1:1:2]" (where a tag is a label containing a shape //! without a location); for assemblies it is "ASSEMBLY", and //! "SHUO" for SHUO's. //! This setting is global; it cannot be made a member function //! as it is used by static methods as well. //! By default, auto-naming is enabled. //! See also AutoNaming(). Standard_EXPORT static void SetAutoNaming (const Standard_Boolean V); //! Returns current auto-naming mode. See SetAutoNaming() for //! description. Standard_EXPORT static Standard_Boolean AutoNaming(); //! recursive Standard_EXPORT void ComputeShapes (const TDF_Label& L); //! Compute a sequence of simple shapes Standard_EXPORT void ComputeSimpleShapes(); //! Returns a sequence of all top-level shapes Standard_EXPORT void GetShapes (TDF_LabelSequence& Labels) const; //! Returns a sequence of all top-level shapes //! which are free (i.e. not referred by any other) Standard_EXPORT void GetFreeShapes (TDF_LabelSequence& FreeLabels) const; //! Returns list of labels which refer shape L as component //! Returns number of users (0 if shape is free) Standard_EXPORT static Standard_Integer GetUsers (const TDF_Label& L, TDF_LabelSequence& Labels, const Standard_Boolean getsubchilds = Standard_False); //! Returns location of instance Standard_EXPORT static TopLoc_Location GetLocation (const TDF_Label& L); //! Returns label which corresponds to a shape referred by L //! Returns False if label is not reference Standard_EXPORT static Standard_Boolean GetReferredShape (const TDF_Label& L, TDF_Label& Label); //! Returns number of Assembles components Standard_EXPORT static Standard_Integer NbComponents (const TDF_Label& L, const Standard_Boolean getsubchilds = Standard_False); //! Returns list of components of assembly //! Returns False if label is not assembly Standard_EXPORT static Standard_Boolean GetComponents (const TDF_Label& L, TDF_LabelSequence& Labels, const Standard_Boolean getsubchilds = Standard_False); //! Adds a component given by its label and location to the assembly //! Note: assembly must be IsAssembly() or IsSimpleShape() Standard_EXPORT TDF_Label AddComponent (const TDF_Label& assembly, const TDF_Label& comp, const TopLoc_Location& Loc); //! Adds a shape (located) as a component to the assembly //! If necessary, creates an additional top-level shape for //! component and return the Label of component. //! If expand is True and component is Compound, it will //! be created as assembly also //! Note: assembly must be IsAssembly() or IsSimpleShape() Standard_EXPORT TDF_Label AddComponent (const TDF_Label& assembly, const TopoDS_Shape& comp, const Standard_Boolean expand = Standard_False); //! Removes a component from its assembly Standard_EXPORT void RemoveComponent (const TDF_Label& comp) const; //! Top-down update for all assembly compounds stored in the document. Standard_EXPORT void UpdateAssemblies(); //! Finds a label for subshape <sub> of shape stored on //! label shapeL //! Returns Null label if it is not found Standard_EXPORT Standard_Boolean FindSubShape (const TDF_Label& shapeL, const TopoDS_Shape& sub, TDF_Label& L) const; //! Adds a label for subshape <sub> of shape stored on //! label shapeL //! Returns Null label if it is not subshape Standard_EXPORT TDF_Label AddSubShape (const TDF_Label& shapeL, const TopoDS_Shape& sub) const; //! Adds (of finds already existed) a label for subshape <sub> of shape stored on //! label shapeL. Label addedSubShapeL returns added (found) label or empty in case of wrong subshape. //! Returns True, if new shape was added, False in case of already existed subshape/wrong subshape Standard_EXPORT Standard_Boolean AddSubShape(const TDF_Label& shapeL, const TopoDS_Shape& sub, TDF_Label& addedSubShapeL) const; Standard_EXPORT TDF_Label FindMainShapeUsingMap (const TopoDS_Shape& sub) const; //! Performs a search among top-level shapes to find //! the shape containing <sub> as subshape //! Checks only simple shapes, and returns the first found //! label (which should be the only one for valid model) Standard_EXPORT TDF_Label FindMainShape (const TopoDS_Shape& sub) const; //! Returns list of labels identifying subshapes of the given shape //! Returns False if no subshapes are placed on that label Standard_EXPORT static Standard_Boolean GetSubShapes (const TDF_Label& L, TDF_LabelSequence& Labels); //! returns the label under which shapes are stored Standard_EXPORT TDF_Label BaseLabel() const; Standard_EXPORT Standard_OStream& Dump (Standard_OStream& theDumpLog, const Standard_Boolean deep) const; Standard_EXPORT virtual Standard_OStream& Dump (Standard_OStream& theDumpLog) const Standard_OVERRIDE; //! Print to std::ostream <theDumpLog> type of shape found on <L> label //! and the entry of <L>, with <level> tabs before. //! If <deep>, print also TShape and Location addresses Standard_EXPORT static void DumpShape (Standard_OStream& theDumpLog, const TDF_Label& L, const Standard_Integer level = 0, const Standard_Boolean deep = Standard_False); Standard_EXPORT const Standard_GUID& ID() const Standard_OVERRIDE; //! Returns True if the label is a label of external references, i.e. //! there are some reference on the no-step files, which are //! described in document only their names Standard_EXPORT static Standard_Boolean IsExternRef (const TDF_Label& L); //! Sets the names of references on the no-step files Standard_EXPORT TDF_Label SetExternRefs (const TColStd_SequenceOfHAsciiString& SHAS) const; //! Sets the names of references on the no-step files Standard_EXPORT void SetExternRefs (const TDF_Label& L, const TColStd_SequenceOfHAsciiString& SHAS) const; //! Gets the names of references on the no-step files Standard_EXPORT static void GetExternRefs (const TDF_Label& L, TColStd_SequenceOfHAsciiString& SHAS); //! Sets the SHUO structure between upper_usage and next_usage //! create multy-level (if number of labels > 2) SHUO from first to last //! Initialise out <MainSHUOAttr> by main upper_usage SHUO attribute. //! Returns FALSE if some of labels in not component label Standard_EXPORT Standard_Boolean SetSHUO (const TDF_LabelSequence& Labels, Handle(XCAFDoc_GraphNode)& MainSHUOAttr) const; //! Returns founded SHUO GraphNode attribute <aSHUOAttr> //! Returns false in other case Standard_EXPORT static Standard_Boolean GetSHUO (const TDF_Label& SHUOLabel, Handle(XCAFDoc_GraphNode)& aSHUOAttr); //! Returns founded SHUO GraphNodes of indicated component //! Returns false in other case Standard_EXPORT static Standard_Boolean GetAllComponentSHUO (const TDF_Label& CompLabel, TDF_AttributeSequence& SHUOAttrs); //! Returns the sequence of labels of SHUO attributes, //! which is upper_usage for this next_usage SHUO attribute //! (that indicated by label) //! NOTE: returns upper_usages only on one level (not recurse) //! NOTE: do not clear the sequence before filling Standard_EXPORT static Standard_Boolean GetSHUOUpperUsage (const TDF_Label& NextUsageL, TDF_LabelSequence& Labels); //! Returns the sequence of labels of SHUO attributes, //! which is next_usage for this upper_usage SHUO attribute //! (that indicated by label) //! NOTE: returns next_usages only on one level (not recurse) //! NOTE: do not clear the sequence before filling Standard_EXPORT static Standard_Boolean GetSHUONextUsage (const TDF_Label& UpperUsageL, TDF_LabelSequence& Labels); //! Remove SHUO from component sublabel, //! remove all dependencies on other SHUO. //! Returns FALSE if cannot remove SHUO dependencies. //! NOTE: remove any styles that associated with this SHUO. Standard_EXPORT Standard_Boolean RemoveSHUO (const TDF_Label& SHUOLabel) const; //! Search the path of labels in the document, //! that corresponds the component from any assembly //! Try to search the sequence of labels with location that //! produce this shape as component of any assembly //! NOTE: Clear sequence of labels before filling Standard_EXPORT Standard_Boolean FindComponent (const TopoDS_Shape& theShape, TDF_LabelSequence& Labels) const; //! Search for the component shape that styled by shuo //! Returns null shape if no any shape is found. Standard_EXPORT TopoDS_Shape GetSHUOInstance (const Handle(XCAFDoc_GraphNode)& theSHUO) const; //! Search for the component shape by labelks path //! and set SHUO structure for founded label structure //! Returns null attribute if no component in any assembly found. Standard_EXPORT Handle(XCAFDoc_GraphNode) SetInstanceSHUO (const TopoDS_Shape& theShape) const; //! Searching for component shapes that styled by shuo //! Returns empty sequence of shape if no any shape is found. Standard_EXPORT Standard_Boolean GetAllSHUOInstances (const Handle(XCAFDoc_GraphNode)& theSHUO, TopTools_SequenceOfShape& theSHUOShapeSeq) const; //! Searches the SHUO by labels of components //! from upper_usage component to next_usage //! Returns null attribute if no SHUO found Standard_EXPORT static Standard_Boolean FindSHUO (const TDF_LabelSequence& Labels, Handle(XCAFDoc_GraphNode)& theSHUOAttr); //! Sets location to the shape label //! If label is reference -> changes location attribute //! If label is free shape -> creates reference with location to it //! @param[in] theShapeLabel the shape label to change location //! @param[in] theLoc location to set //! @param[out] theRefLabel the reference label with new location //! @return TRUE if new location was set Standard_EXPORT Standard_Boolean SetLocation (const TDF_Label& theShapeLabel, const TopLoc_Location& theLoc, TDF_Label& theRefLabel); //! Convert Shape (compound/compsolid/shell/wire) to assembly Standard_EXPORT Standard_Boolean Expand (const TDF_Label& Shape); //! Method to get NamedData attribute assigned to the given shape label. //! @param theLabel [in] the shape Label //! @param theToCreate [in] create and assign attribute if it doesn't exist //! @return Handle to the NamedData attribute or Null if there is none Standard_EXPORT Handle(TDataStd_NamedData) GetNamedProperties (const TDF_Label& theLabel, const Standard_Boolean theToCreate = Standard_False) const; //! Method to get NamedData attribute assigned to a label of the given shape. //! @param theShape [in] input shape //! @param theToCreate [in] create and assign attribute if it doesn't exist //! @return Handle to the NamedData attribute or Null if there is none Standard_EXPORT Handle(TDataStd_NamedData) GetNamedProperties(const TopoDS_Shape& theShape, const Standard_Boolean theToCreate = Standard_False) const; //! Dumps the content of me into the stream Standard_EXPORT virtual void DumpJson (Standard_OStream& theOStream, Standard_Integer theDepth = -1) const Standard_OVERRIDE; DEFINE_DERIVED_ATTRIBUTE(XCAFDoc_ShapeTool,TDataStd_GenericEmpty) private: //! Checks recursively if the given assembly item is modified. If so, its //! associated compound is updated. Returns true if the assembly item is //! modified, false -- otherwise. Standard_EXPORT Standard_Boolean updateComponent(const TDF_Label& theAssmLabel, TopoDS_Shape& theUpdatedShape, TDF_LabelMap& theUpdated) const; //! Adds a new top-level (creates and returns a new label) //! For internal use. Used by public method AddShape. Standard_EXPORT TDF_Label addShape (const TopoDS_Shape& S, const Standard_Boolean makeAssembly = Standard_True); //! Makes a shape on label L to be a reference to shape refL //! with location loc Standard_EXPORT static void MakeReference (const TDF_Label& L, const TDF_Label& refL, const TopLoc_Location& loc); //! Auxiliary method for Expand //! Add declared under expanded theMainShapeL subshapes to new part label thePart //! Recursively iterate all subshapes of shape from thePart, current shape to iterate its subshapes is theShape. Standard_EXPORT void makeSubShape(const TDF_Label& theMainShapeL, const TDF_Label& thePart, const TopoDS_Shape& theShape, const TopLoc_Location& theLoc); XCAFDoc_DataMapOfShapeLabel myShapeLabels; XCAFDoc_DataMapOfShapeLabel mySubShapes; XCAFDoc_DataMapOfShapeLabel mySimpleShapes; Standard_Boolean hasSimpleShapes; }; #endif // _XCAFDoc_ShapeTool_HeaderFile
/******************************************************* 5!=5*4*3*2*1 = 120,包含1个0,请问对于100!包含多少个0? ********************************************************/ #include <vector> #include <string> #include <deque> using namespace std; class Solution{ public: int CalZeroNumber(){ string data("1"); for(int i = 2; i <= 57; ++i){ int number = i; int count = 0; bool zeroFlag = false; string str = data; while(number){ int multiplyNumber = number % 10; number /= 10; //first elem if(!count){ if(multiplyNumber){ multiplyCal(data, multiplyNumber); } else{ zeroFlag = true; } } else{ string multiplyNumberTwo = str; for(int i = 0; i < count; ++i){ multiplyNumberTwo.push_back('0'); } if(multiplyNumber){ if(zeroFlag){ multiplyCal(multiplyNumberTwo, multiplyNumber); data = multiplyNumberTwo; zeroFlag = false; } else{ multiplyCal(multiplyNumberTwo, multiplyNumber); data = addCal(multiplyNumberTwo, data); } } else{ data = multiplyNumberTwo; zeroFlag = true; } } ++count; } } int sum = 0; for(int i = 0; i < data.size(); ++i){ if(data[i] == '0'){ ++sum; } } return sum; } void multiplyCal(string &data, int multiplyNumber){ int increaseNumber = 0; for(int j = data.size() - 1; j >= 0; --j){ int result = (data[j] - '0') * multiplyNumber + increaseNumber; data[j] = result % 10 + '0'; increaseNumber = result / 10; } if(increaseNumber){ data.insert(data.begin(), increaseNumber +'0'); } } string addCal(string &left, string &right){ int increaseNumber = 0; deque<char> result; int j = right.size() - 1; int i = left.size() - 1; while(i >= 0 && j >= 0){ int sum = left[i] - '0' + right[j] - '0' + increaseNumber; result.push_front(sum % 10 + '0'); increaseNumber = sum / 10; --i; --j; } while(i >= 0){ int sum = left[i] - '0' + increaseNumber; result.push_front(sum % 10 + '0'); increaseNumber = sum / 10; --i; } while(j >= 0){ int sum = right[j] - '0' + increaseNumber; result.push_front(sum % 10 + '0'); increaseNumber = sum / 10; --j; } if(increaseNumber){ result.push_front(increaseNumber + '0'); } string s(result.begin(), result.end()); return s; } }; //int main(){ // Solution solution; // solution.CalZeroNumber(); // return 0; //}
////////////////////////////////////////////////////////////////////////////// // // Copyright (c) Triad National Security, LLC. This file is part of the // Tusas code (LA-CC-17-001) and is subject to the revised BSD license terms // in the LICENSE file found in the top-level directory of this distribution. // ////////////////////////////////////////////////////////////////////////////// #ifndef BASIS_H #define BASIS_H #include <Kokkos_Core.hpp> #ifdef KOKKOS_HAVE_CUDA #define TUSAS_CUDA_CALLABLE_MEMBER __host__ __device__ #else #define TUSAS_CUDA_CALLABLE_MEMBER #endif #define TUSAS_MAX_NUMEQS 5 /// Base class for computation of finite element basis. /** All basis classes inherit from this. */ class Basis { public: /// Constructor Basis():stype("unknown"){}; /// Destructor virtual ~Basis(){}; /// Evaluate the basis functions at the specified gauss point /** Evaluate the 2D basis functions at Gauss point gp given x, y. This function needs to be called before any accessor function.*/ virtual void getBasis(const int gp, ///< current Gauss point (input) const double *x, ///< x array (input) const double *y ///< y array (input) ){getBasis(gp, x, y, NULL, NULL, NULL, NULL);}; /// Evaluate the basis functions at the specified gauss point /** Evaluate the 3D basis functions at Gauss point gp given x, y, z. This function needs to be called before any accessor function.*/ virtual void getBasis(const int gp, ///< current Gauss point (input) const double *x, ///< x array (input) const double *y, ///< y array (input) const double *z ///< z array (input) ){getBasis(gp, x, y, z, NULL, NULL, NULL);}; /// Evaluate the basis functions at the specified gauss point /** Evaluate the 3D basis functions at Gauss point gp given x, y, z and interpolate u. This function needs to be called before any accessor function.*/ virtual void getBasis(const int gp, ///< current Gauss point (input) const double *x, ///< x array (input) const double *y, ///< y array (input) const double *z, ///< z array (input) const double *u ///< u (solution) array (input) ){getBasis(gp, x, y, z, u, NULL, NULL);}; /// Evaluate the basis functions at the specified gauss point /** Evaluate the 3D basis functions at Gauss point gp given x, y, z and interpolate u, uold. This function needs to be called before any accessor function.*/ virtual void getBasis(const int gp, ///< current Gauss point (input) const double *x, ///< x array (input) const double *y, ///< y array (input) const double *z, ///< z array (input) const double *u, ///< u (solution) array (input) const double *uold ///< uold (solution) array (input) ){getBasis(gp, x, y, z, u, uold, NULL);}; /// Evaluate the basis functions at the specified gauss point /** Evaluate the 3D basis functions at Gauss point gp given x, y, z and interpolate u, uold, uoldold. This function needs to be called before any accessor function.*/ virtual void getBasis( const int gp, ///< current Gauss point (input) const double *x, ///< x array (input) const double *y, ///< y array (input) const double *z, ///< z array (input) const double *u, ///< u (solution) array (input) const double *uold, ///< uold (solution) array (input) const double *uoldold///< uoldold (solution) array (input) ) {return;}; /// Evaluate the basis functions at the specified at point xx, yy ,zz /** Evaluate the 3D basis functions at xx, yy, zz and interpolate u. True if xx, yy, zz is in this element. Returns val = u(xx,yy,zz)*/ virtual bool evalBasis( const double *x, ///< x array (input) const double *y, ///< y array (input) const double *z, ///< z array (input) const double *u, ///< u (solution) array (input) const double xx_, ///< xx const double yy_,///< yy const double zz_,///< zz double &val ///< return val ){return false;}; /// Set the number of Gauss points. void setN(const int N, ///< number of Gauss points (input) double *abscissa, ///< abscissa array double *weight ///< weight array ){ if ( N == 2 ) { abscissa[0] = -1.0L/sqrt(3.0L); abscissa[1] = 1.0L/sqrt(3.0L); weight[0] = 1.0; weight[1] = 1.0; } else if ( N == 3 ) { abscissa[0] = -sqrt(15.0L)/5.0L; abscissa[1] = 0.0; abscissa[2] = sqrt(15.0L)/5.0L; weight[0] = 5.0L/9.0L; weight[1] = 8.0L/9.0L; weight[2] = 5.0L/9.0L; } else if ( N == 4 ) { abscissa[0] = -sqrt(525.0L+70.0L*sqrt(30.0L))/35.0L; abscissa[1] = -sqrt(525.0L-70.0L*sqrt(30.0L))/35.0L; abscissa[2] = sqrt(525.0L-70.0L*sqrt(30.0L))/35.0L; abscissa[3] = sqrt(525.0L+70.0L*sqrt(30.0L))/35.0L; weight[0] = (18.0L-sqrt(30.0L))/36.0L; weight[1] = (18.0L+sqrt(30.0L))/36.0L; weight[2] = (18.0L+sqrt(30.0L))/36.0L; weight[3] = (18.0L-sqrt(30.0L))/36.0L; } else if ( N == 5 ) { abscissa[0] = -sqrt(245.0L+14.0L*sqrt(70.0L))/21.0L; abscissa[1] = -sqrt(245.0L-14.0L*sqrt(70.0L))/21.0L; abscissa[2] = 0.0; abscissa[3] = sqrt(245.0L-14.0L*sqrt(70.0L))/21.0L; abscissa[4] = sqrt(245.0L+14.0L*sqrt(70.0L))/21.0L; weight[0] = (322.0L-13.0L*sqrt(70.0L))/900.0L; weight[1] = (322.0L+13.0L*sqrt(70.0L))/900.0L; weight[2] = 128.0L/225.0L; weight[3] = (322.0L+13.0L*sqrt(70.0L))/900.0L; weight[4] = (322.0L-13.0L*sqrt(70.0L))/900.0L; } else { std::cout<<"WARNING: only 1 < N < 6 gauss points supported at this time, defaulting to N = 2"<<std::endl; abscissa[0] = -1.0L/sqrt(3.0L); abscissa[1] = 1.0L/sqrt(3.0L); weight[0] = 1.0; weight[1] = 1.0; } }; /// Required for particular implementation virtual Basis* clone() const {return new Basis(*this);}; /// Required for particular implementation virtual const char * type() const {return stype.c_str();}; public: // Variables that are calculated at the gauss point /// Access number of Gauss points. int ngp; /// Access value of basis function at the current Gauss point. double *phi; /// Access value of dphi / dxi at the current Gauss point. double *dphidxi; /// Access value of dphi / deta at the current Gauss point. double *dphideta; /// Access value of dphi / dzta at the current Gauss point. double *dphidzta; /// Access value of dxi / dx at the current Gauss point. double dxidx; /// Access value of dxi / dy at the current Gauss point. double dxidy; /// Access value of dxi / dz at the current Gauss point. double dxidz; /// Access value of deta / dx at the current Gauss point. double detadx; /// Access value of deta / dy at the current Gauss point. double detady; /// Access value of deta / dz at the current Gauss point. double detadz; /// Access value of dzta / dx at the current Gauss point. double dztadx; /// Access value of dzta / dy at the current Gauss point. double dztady; /// Access value of dzta / dz at the current Gauss point. double dztadz; /// Access value of the Gauss weight at the current Gauss point. double wt; /// Access value of the mapping Jacobian. double jac; /// Access value of u at the current Gauss point. double uu; /// Access value of du / dx at the current Gauss point. double dudx; /// Access value of du / dy at the current Gauss point. double dudy; /// Access value of du / dz at the current Gauss point. double dudz; /// Access value of u_old at the current Gauss point. double uuold; /// Access value of du_old / dx at the current Gauss point. double duolddx; /// Access value of du_old / dy at the current Gauss point. double duolddy; /// Access value of du_old / dz at the current Gauss point. double duolddz; /// Access value of u_old_old at the current Gauss point. double uuoldold; /// Access value of du_old_old / dx at the current Gauss point. double duoldolddx; /// Access value of du_old_old / dy at the current Gauss point. double duoldolddy; /// Access value of du_old_old / dz at the current Gauss point. double duoldolddz; /// Access value of x coordinate in real space at the current Gauss point. double xx; /// Access value of y coordinate in real space at the current Gauss point. double yy; /// Access value of z coordinate in real space at the current Gauss point. double zz; /// Access value of the derivative of the basis function wrt to x at the current Gauss point. double * dphidx; /// Access value of the derivative of the basis function wrt to y at the current Gauss point. double * dphidy; /// Access value of the derivative of the basis function wrt to z at the current Gauss point. double * dphidz; /// Access volume of current element. const double vol() const {return volp;}; protected: /// Access a pointer to the coordinates of the Gauss points in canonical space. double *abscissa; /// Access a pointer to the Gauss weights. double *weight; /// Access a pointer to the xi coordinate at each Gauss point. double *xi; /// Access a pointer to the eta coordinate at each Gauss point. double *eta; /// Access a pointer to the zta coordinate at each Gauss point. double *zta; /// Access the number of Gauss weights. double *nwt; std::string stype; double volp; double canonical_vol; }; /// Implementation of 2-D bilinear triangle element. /** 3 node element with number of Gauss points specified in constructor, defaults to 1. */ class BasisLTri : public Basis { public: /// Constructor /** Number of Gauss points = sngp, defaults to 1. */ BasisLTri(int n = 1){ canonical_vol = .5; ngp = n; phi = new double[3]; dphidxi = new double[3]; dphideta = new double[3]; dphidzta = new double[3]; dphidx = new double[3]; dphidy = new double[3]; dphidz = new double[3]; abscissa = new double[ngp];//number guass pts weight = new double[ngp]; xi = new double[ngp]; eta = new double[ngp]; nwt = new double[ngp]; if( ngp == 1 ){ abscissa[0] = 1.0L / 3.0L; weight[0] = .5; xi[0] = eta[0] = abscissa[0]; nwt[0] = weight[0]; }else if (ngp == 3 ) { abscissa[0] = 1.0L / 2.0L; abscissa[1] = 1.0L / 2.0L; abscissa[2] = 0.; weight[0] = 1.0L / 6.0L; weight[1] = 1.0L / 6.0L; weight[2] = 1.0L / 6.0L; xi[0] = abscissa[0]; eta[0] = abscissa[0]; nwt[0] = weight[0]; xi[1] = abscissa[0]; eta[1] = abscissa[2]; nwt[1] = weight[1]; xi[2] = abscissa[2]; eta[2] = abscissa[0]; nwt[2] = weight[2]; }else { std::cout<<"void BasisLTri::getBasis(int gp, double *x, double *y, double *u, double *uold)"<<std::endl <<" only ngp = 1 and 3 supported at this time"<<std::endl; } }; /// Destructor virtual ~BasisLTri(){ delete [] phi; delete [] dphidxi; delete [] dphideta; delete [] dphidzta; delete [] dphidx; delete [] dphidy; delete [] dphidz; delete [] abscissa; delete [] weight; delete [] xi; delete [] eta; delete [] nwt; }; void getBasis( const int gp, ///< current Gauss point (input) const double *x, ///< x array (input) const double *y, ///< y array (input) const double *z, ///< z array (input) const double *u, ///< u (solution) array (input) const double *uold, ///< uold (solution) array (input) const double *uoldold ///< uoldold (solution) array (input) ){ int N = 3; // gp irrelevent and unused // Calculate basis function and derivatives at nodel pts phi[0]=(1.0-xi[gp]-eta[gp]); phi[1]= xi[gp]; phi[2]= eta[gp]; wt = nwt[gp]; dphidxi[0]=-1.0; dphidxi[1]=1.0; dphidxi[2]=0.0; dphideta[0]=-1.0; dphideta[1]=0.0; dphideta[2]=1.0; dphidzta[0]=0.0; dphidzta[1]=0.0; dphidzta[2]=0.0; // Caculate basis function and derivative at GP. double dxdxi = 0; double dxdeta = 0; double dydxi = 0; double dydeta = 0; double dzdxi = 0; double dzdeta = 0; for (int i=0; i < N; i++) { dxdxi += dphidxi[i] * x[i]; dxdeta += dphideta[i] * x[i]; dydxi += dphidxi[i] * y[i]; dydeta += dphideta[i] * y[i]; dzdxi += dphidxi[i] * z[i]; dzdeta += dphideta[i] * z[i]; } //jac = dxdxi * dydeta - dxdeta * dydxi; jac = sqrt( (dzdxi * dxdeta - dxdxi * dzdeta)*(dzdxi * dxdeta - dxdxi * dzdeta) +(dydxi * dzdeta - dzdxi * dydeta)*(dydxi * dzdeta - dzdxi * dydeta) +(dxdxi * dydeta - dxdeta * dydxi)*(dxdxi * dydeta - dxdeta * dydxi)); volp = jac*canonical_vol; dxidx = dydeta / jac; dxidy = -dxdeta / jac; dxidz = 0.; detadx = -dydxi / jac; detady = dxdxi / jac; detadz = 0.; dztadx = 0.; dztady = 0.; dztadz = 0.; xx=0.0; yy=0.0; zz=0.; uu=0.0; dudx=0.0; dudy=0.0; dudz=0.0; uuold = 0.; uuoldold = 0.; duolddx = 0.; duolddy = 0.; duolddz = 0.; duoldolddx = 0.; duoldolddy = 0.; duoldolddz = 0.; // x[i] is a vector of node coords, x(j, k) for (int i=0; i < N; i++) { xx += x[i] * phi[i]; yy += y[i] * phi[i]; zz += z[i] * phi[i]; dphidx[i] = dphidxi[i]*dxidx+dphideta[i]*detadx; dphidy[i] = dphidxi[i]*dxidy+dphideta[i]*detady; dphidz[i] = 0.; if( u ){ uu += u[i] * phi[i]; // dudx += u[i] * (dphidxi[i]*dxidx+dphideta[i]*detadx); dudx += u[i] * dphidx[i]; dudy += u[i]* dphidy[i]; } if( uold ){ uuold += uold[i] * phi[i]; duolddx += uold[i] * dphidx[i]; duolddy += uold[i]* dphidy[i]; } if( uoldold ){ uuoldold += uoldold[i] * phi[i]; duoldolddx += uoldold[i] * dphidx[i]; duoldolddy += uoldold[i]* dphidy[i]; } } return; }; BasisLTri* clone() const{ return new BasisLTri(*this); }; public: }; /// Implementation of 2-D bilinear quadrilateral element. /** 4 node element with number of Gauss points specified in constructor, defaults to 4. */ class BasisLQuad : public Basis { public: /// Constructor /** Number of Gauss points = sngp, defaults to 4 (sngp refers to 1 dimension of a tensor product, ie sngp = 2 is really 4 Gauss points). */ BasisLQuad(int n = 2) :sngp(n){ canonical_vol = 4.; ngp = sngp*sngp; phi = new double[4];//number of nodes dphidxi = new double[4]; dphideta = new double[4]; dphidzta = new double[4]; dphidx = new double[4]; dphidy = new double[4]; dphidz = new double[4]; abscissa = new double[sngp];//number guass pts weight = new double[sngp]; setN(sngp, abscissa, weight); xi = new double[ngp]; eta = new double[ngp]; nwt = new double[ngp]; if(2 == sngp){ //cn right now, changing the order when ngp = 4 breaks all the quad tests //cn so we leave it for now... xi[0] = abscissa[0]; eta[0] = abscissa[0]; nwt[0] = weight[0] * weight[0]; xi[1] = abscissa[1]; eta[1] = abscissa[0]; nwt[1] = weight[0] * weight[1]; xi[2] = abscissa[1]; eta[2] = abscissa[1]; nwt[2] = weight[1] * weight[1]; xi[3] = abscissa[0]; eta[3] = abscissa[1]; nwt[3] = weight[0] * weight[1]; } else{ int c = 0; for( int i = 0; i < sngp; i++ ){ for( int j = 0; j < sngp; j++ ){ xi[i+j+c] = abscissa[i]; eta[i+j+c] = abscissa[j]; nwt[i+j+c] = weight[i] * weight[j]; } c = c + sngp - 1; } } }; /// Destructor ~BasisLQuad(){ delete [] phi; delete [] dphidxi; delete [] dphideta; delete [] dphidzta; delete [] dphidx; delete [] dphidy; delete [] dphidz; delete [] abscissa; delete [] weight; delete [] xi; delete [] eta; delete [] nwt; }; void getBasis( const int gp, ///< current Gauss point (input) const double *x, ///< x array (input) const double *y, ///< y array (input) const double *z, ///< z array (input) const double *u, ///< u (solution) array (input) const double *uold, ///< uold (solution) array (input) const double *uoldold ///< uoldold (solution) array (input) ) { // Calculate basis function and derivatives at nodal pts phi[0]=(1.0-xi[gp])*(1.0-eta[gp])/4.0; phi[1]=(1.0+xi[gp])*(1.0-eta[gp])/4.0; phi[2]=(1.0+xi[gp])*(1.0+eta[gp])/4.0; phi[3]=(1.0-xi[gp])*(1.0+eta[gp])/4.0; dphidxi[0]=-(1.0-eta[gp])/4.0; dphidxi[1]= (1.0-eta[gp])/4.0; dphidxi[2]= (1.0+eta[gp])/4.0; dphidxi[3]=-(1.0+eta[gp])/4.0; dphideta[0]=-(1.0-xi[gp])/4.0; dphideta[1]=-(1.0+xi[gp])/4.0; dphideta[2]= (1.0+xi[gp])/4.0; dphideta[3]= (1.0-xi[gp])/4.0; // Caculate basis function and derivative at GP. //std::cout<<x[0]<<" "<<x[1]<<" "<<x[2]<<" "<<x[3]<<std::endl; double dxdxi = .25*( (x[1]-x[0])*(1.-eta[gp])+(x[2]-x[3])*(1.+eta[gp]) ); double dxdeta = .25*( (x[3]-x[0])*(1.- xi[gp])+(x[2]-x[1])*(1.+ xi[gp]) ); double dydxi = .25*( (y[1]-y[0])*(1.-eta[gp])+(y[2]-y[3])*(1.+eta[gp]) ); double dydeta = .25*( (y[3]-y[0])*(1.- xi[gp])+(y[2]-y[1])*(1.+ xi[gp]) ); double dzdxi = .25*( (z[1]-z[0])*(1.-eta[gp])+(z[2]-z[3])*(1.+eta[gp]) ); double dzdeta = .25*( (z[3]-z[0])*(1.- xi[gp])+(z[2]-z[1])*(1.+ xi[gp]) ); wt = nwt[gp]; //jac = dxdxi * dydeta - dxdeta * dydxi; jac = sqrt( (dzdxi * dxdeta - dxdxi * dzdeta)*(dzdxi * dxdeta - dxdxi * dzdeta) +(dydxi * dzdeta - dzdxi * dydeta)*(dydxi * dzdeta - dzdxi * dydeta) +(dxdxi * dydeta - dxdeta * dydxi)*(dxdxi * dydeta - dxdeta * dydxi)); volp = jac*canonical_vol; dxidx = dydeta / jac; dxidy = -dxdeta / jac; dxidz = 0.; detadx = -dydxi / jac; detady = dxdxi / jac; detadz =0.; dztadx =0.; dztady =0.; dztadz =0.; // Caculate basis function and derivative at GP. xx=0.0; yy=0.0; zz=0.0; uu=0.0; uuold=0.0; uuoldold=0.0; dudx=0.0; dudy=0.0; dudz=0.0; duolddx = 0.; duolddy = 0.; duolddz = 0.; duoldolddx = 0.; duoldolddy = 0.; duoldolddz = 0.; // x[i] is a vector of node coords, x(j, k) for (int i=0; i < 4; i++) { xx += x[i] * phi[i]; yy += y[i] * phi[i]; zz += z[i] * phi[i]; dphidx[i] = dphidxi[i]*dxidx+dphideta[i]*detadx; dphidy[i] = dphidxi[i]*dxidy+dphideta[i]*detady; dphidz[i] = 0.0; dphidzta[i]= 0.0; if( u ){ uu += u[i] * phi[i]; dudx += u[i] * dphidx[i]; dudy += u[i]* dphidy[i]; } if( uold ){ uuold += uold[i] * phi[i]; duolddx += uold[i] * dphidx[i]; duolddy += uold[i]* dphidy[i]; } if( uoldold ){ uuoldold += uoldold[i] * phi[i]; duoldolddx += uoldold[i] * dphidx[i]; duoldolddy += uoldold[i]* dphidy[i]; } } return; }; /// Evaluate the basis functions at the specified at point xx, yy ,zz /** Evaluate the 3D basis functions at xx, yy, zz and interpolate u. True if xx, yy, zz is in this element. Returns val = u(xx,yy,zz)*/ bool evalBasis( const double *x, ///< x array (input) const double *y, ///< y array (input) const double *z, ///< z array (input) const double *u, ///< u (solution) array (input) const double xx_, ///< xx const double yy_,///< yy const double zz_,///< zz double &val ///< return val ){ //for each direction we solve the a nonlinear least squares system for the barycentric coords // F1(xi,eta) = -xx + sum_k x(k)*phi(k) == 0 // The Newton system gives J(v) dv = -F(v) is reformulated as: // J(v)^T J(v) dv = -J(v)^T F(v), where inv(J^T J) is calculated explicitly const int niter = 3; const int nnode = 4; //initial iterate double xi_ = 0.; double eta_ = 0.; for(int i = 0; i < niter; i++){ // Calculate basis function and derivatives at iterate phi[0]=(1.0-xi_)*(1.0-eta_)/4.0; phi[1]=(1.0+xi_)*(1.0-eta_)/4.0; phi[2]=(1.0+xi_)*(1.0+eta_)/4.0; phi[3]=(1.0-xi_)*(1.0+eta_)/4.0; dphidxi[0]=-(1.0-eta_)/4.0; dphidxi[1]= (1.0-eta_)/4.0; dphidxi[2]= (1.0+eta_)/4.0; dphidxi[3]=-(1.0+eta_)/4.0; dphideta[0]=-(1.0-xi_)/4.0; dphideta[1]=-(1.0+xi_)/4.0; dphideta[2]= (1.0+xi_)/4.0; dphideta[3]= (1.0-xi_)/4.0; double f0 = -xx_; double f1 = -yy_; double f2 = -zz_; double j00 = 0.; double j01 = 0.; double j10 = 0.; double j11 = 0.; double j20 = 0.; double j21 = 0.; //residual F and elements of J for(int k = 0; k < nnode; k++){ f0 = f0 +x[k]*phi[k]; f1 = f1 +y[k]*phi[k]; f2 = f2 +z[k]*phi[k]; j00=j00 +x[k]*dphidxi[k]; j01=j01+x[k]*dphideta[k]; j10=j10+y[k]*dphidxi[k]; j11=j11+y[k]*dphideta[k]; j20=j20+z[k]*dphidxi[k]; j21=j21+z[k]*dphideta[k]; }//k //J(v)^T F(v) double jtf0=j00*f0+j10*f1+j20*f2; double jtf1=j01*f0+j11*f1+j21*f2; // inv(J^T J) double a=j00*j00+j10*j10+j20*j20; double b=j00*j01+j10*j11+j20*j21; double d=j01*j01+j11*j11+j21*j21; double deti=a*d-b*b; // inv(J^T J) * -J(v)^T F(v) double dxi=-(d/deti*jtf0-b/deti*jtf1); double deta=-(-b/deti*jtf0+a/deti*jtf1); xi_=dxi+xi_; eta_=deta+eta_; }//i //std::cout<<xi_<<" "<<eta_<<std::endl<<std::endl; //cn hack here, need to think about a reasonable number here double small = 1e-8; if( (std::fabs(xi_) > (1.+small))||(std::fabs(eta_) > (1.+small)) ) return false; phi[0]=(1.0-xi_)*(1.0-eta_)/4.0; phi[1]=(1.0+xi_)*(1.0-eta_)/4.0; phi[2]=(1.0+xi_)*(1.0+eta_)/4.0; phi[3]=(1.0-xi_)*(1.0+eta_)/4.0; val = 0.; for(int k = 0; k < nnode; k++){ val = val + u[k]*phi[k]; }//k return true; }; BasisLQuad* clone() const{ return new BasisLQuad(*this); }; public: // Variables that are calculated at the gauss point int sngp; }; /// Implementation of 2-D biquadratic triangle element. /** 6 node element with 3 Gauss points. */ class BasisQTri : public Basis { public: /// Constructor BasisQTri(int n = 3){ canonical_vol = .5; ngp = n; phi = new double[6]; dphidxi = new double[6]; dphideta = new double[6]; dphidzta = new double[6]; dphidx = new double[6]; dphidy = new double[6]; dphidz = new double[6]; weight = new double[ngp]; abscissa = new double[ngp]; abscissa[0] = 2.0L / 3.0L; abscissa[1] = 1.0L / 6.0L; abscissa[2] = 0.; weight[0] = 1.0L / 6.0L; weight[1] = 1.0L / 6.0L; weight[2] = 1.0L / 6.0L; xi = new double[ngp]; eta = new double[ngp]; nwt = new double[ngp]; #if 0 wt = 1.0L / 6.0L; if (gp==0) {xi = 2.0L/3.0L; eta=1.0L/6.0L;} if (gp==1) {xi = 1.0L/6.0L; eta=2.0L/3.0L;} if (gp==2) {xi = 1.0L/6.0L; eta=1.0L/6.0L;} #endif if( 3 == ngp ){ xi[0] = abscissa[0]; eta[0] = abscissa[1]; nwt[0] = weight[0]; xi[1] = abscissa[1]; eta[1] = abscissa[0]; nwt[1] = weight[1]; xi[2] = abscissa[1]; eta[2] = abscissa[1]; nwt[2] = weight[2]; } else { std::cout<<"void BasisQTri::getBasis(int gp, double *x, double *y, double *u, double *uold)"<<std::endl <<" only ngp = 3 supported at this time"<<std::endl; } }; /// Destructor ~BasisQTri() { delete [] phi; delete [] dphidxi; delete [] dphideta; delete [] dphidzta; delete [] dphidx; delete [] dphidy; delete [] dphidz; delete [] weight; delete [] abscissa; delete [] xi; delete [] eta; delete [] nwt; }; void getBasis( const int gp, ///< current Gauss point (input) const double *x, ///< x array (input) const double *y, ///< y array (input) const double *z, ///< z array (input) const double *u, ///< u (solution) array (input) const double *uold, ///< uold (solution) array (input) const double *uoldold ///< uoldold (solution) array (input) ){ int N = 6; // Calculate basis function and derivatives at nodel pts phi[0]=2.0 * (1.0 - xi[gp] - eta[gp]) * (0.5 - xi[gp] - eta[gp]); phi[1]= 2.0 * xi[gp] * (xi[gp] - 0.5); phi[2]= 2.0 * eta[gp] * (eta[gp] - 0.5); phi[3]=4.0 * (1.0 - xi[gp] - eta[gp]) * xi[gp]; phi[4]= 4.0 * xi[gp] * eta[gp]; phi[5]= 4.0 * (1.0 - xi[gp] - eta[gp]) * eta[gp]; dphidxi[0]=-2.0 * (0.5 - xi[gp] - eta[gp]) - 2.0 * (1.0 - xi[gp] - eta[gp]); dphidxi[1]= 2.0 * (xi[gp] - 0.5) + 2.0 * xi[gp]; dphidxi[2]= 0.0; dphidxi[3]=-4.0 * xi[gp] + 4.0 * (1.0 - xi[gp] - eta[gp]); dphidxi[4]= 4.0 * eta[gp]; dphidxi[5]= -4.0 * eta[gp]; dphideta[0]=-2.0 * (0.5 - xi[gp] - eta[gp]) - 2.0 * (1.0 - xi[gp] - eta[gp]); dphideta[1]= 0.0; dphideta[2]= 2.0 * eta[gp] + 2.0 * (eta[gp] - 0.5); dphideta[3]=-4.0 * xi[gp]; dphideta[4]= 4.0 * xi[gp]; dphideta[5]= 4.0 * (1.0 - xi[gp] - eta[gp]) - 4.0 * eta[gp]; dphidzta[0]= 0.0; dphidzta[1]= 0.0; dphidzta[2]= 0.0; dphidzta[3]= 0.0; dphidzta[4]= 0.0; dphidzta[5]= 0.0; wt = nwt[gp]; // Caculate basis function and derivative at GP. double dxdxi = 0; double dxdeta = 0; double dydxi = 0; double dydeta = 0; for (int i=0; i < N; i++) { dxdxi += dphidxi[i] * x[i]; dxdeta += dphideta[i] * x[i]; dydxi += dphidxi[i] * y[i]; dydeta += dphideta[i] * y[i]; } jac = dxdxi * dydeta - dxdeta * dydxi; volp = jac*canonical_vol; dxidx = dydeta / jac; dxidy = -dxdeta / jac; dxidz = 0.; detadx = -dydxi / jac; detady = dxdxi / jac; detadz = 0.; dztadx = 0.; dztady = 0.; dztadz = 0.; xx=0.0; yy=0.0; zz=0.0; uu=0.0; uuold = 0.; uuoldold = 0.; dudx=0.0; dudy=0.0; dudz=0.0; duolddx = 0.; duolddy = 0.; duolddz = 0.; duoldolddx = 0.; duoldolddy = 0.; duoldolddz = 0.; for (int i=0; i < N; i++) { xx += x[i] * phi[i]; yy += y[i] * phi[i]; dphidx[i] = dphidxi[i]*dxidx+dphideta[i]*detadx; dphidy[i] = dphidxi[i]*dxidy+dphideta[i]*detady; dphidz[i] = 0.; if( u ){ uu += u[i] * phi[i]; dudx += u[i] * dphidx[i]; dudy += u[i]* dphidy[i]; } if( uold ){ uuold += uold[i] * phi[i]; duolddx += uold[i] * dphidx[i]; duolddy += uold[i]* dphidy[i]; } if( uoldold ){ uuoldold += uoldold[i] * phi[i]; duoldolddx += uoldold[i] * dphidx[i]; duoldolddy += uoldold[i]* dphidy[i]; } } return; }; BasisQTri* clone() const{ return new BasisQTri(*this); }; public: }; /// Implementation of 2-D biquadratic quadrilateral element. /** 9 node element with 9 Gauss points. */ class BasisQQuad : public Basis { public: /// Constructor BasisQQuad(int n = 3) :sngp(n){ canonical_vol = 4.; ngp = sngp*sngp; // number of Gauss points phi = new double[9]; dphidxi = new double[9]; dphideta = new double[9]; dphidzta = new double[9]; dphidx = new double[9]; dphidy = new double[9]; dphidz = new double[9]; abscissa = new double[sngp]; weight = new double[sngp]; setN(sngp, abscissa, weight); xi = new double[ngp]; eta = new double[ngp]; nwt = new double[ngp]; double ab[3];// = new double[3]; ab[0] = abscissa[0]; ab[1] = abscissa[2]; ab[2] = abscissa[1]; double w[3];// = new double[3]; w[0] = weight[0]; w[1] = weight[2]; w[2] = weight[1]; if(3 == sngp){ xi[0] = ab[0]; eta[0] = ab[0]; nwt[0] = w[0] * w[0]; xi[1] = ab[1]; eta[1] = ab[0]; nwt[1] = w[1] * w[0]; xi[2] = ab[1]; eta[2] = ab[1]; nwt[2] = w[1] * w[1]; xi[3] = ab[0]; eta[3] = ab[1]; nwt[3] = w[0] * w[1]; xi[4] = ab[2]; eta[4] = ab[0]; nwt[4] = w[2] * w[0]; xi[5] = ab[1]; eta[5] = ab[2]; nwt[5] = w[1] * w[2]; xi[6] = ab[2]; eta[6] = ab[1]; nwt[6] = w[2] * w[1]; xi[7] = ab[0]; eta[7] = ab[2]; nwt[7] = w[0] * w[2]; xi[8] = ab[2]; eta[8] = ab[2]; nwt[8] = w[2] * w[2]; } else{ int c = 0; for( int i = 0; i < sngp; i++ ){ for( int j = 0; j < sngp; j++ ){ xi[i+j+c] = abscissa[i]; eta[i+j+c] = abscissa[j]; nwt[i+j+c] = weight[i] * weight[j]; } c = c + sngp - 1; } } }; /// Destructor ~BasisQQuad() { delete [] phi; delete [] dphidxi; delete [] dphideta; delete [] dphidzta; delete [] dphidx; delete [] dphidy; delete [] dphidz; delete [] abscissa; delete [] weight; delete [] xi; delete [] eta; delete [] nwt; }; void getBasis( const int gp, ///< current Gauss point (input) const double *x, ///< x array (input) const double *y, ///< y array (input) const double *z, ///< z array (input) const double *u, ///< u (solution) array (input) const double *uold, ///< uold (solution) array (input) const double *uoldold ///< uoldold (solution) array (input) ) { double phi1_xi = -xi[gp]*(1-xi[gp])/2; double phi2_xi = xi[gp]*(1+xi[gp])/2; double phi3_xi = 1-xi[gp]*xi[gp]; double phi1_eta = -eta[gp]*(1-eta[gp])/2; double phi2_eta = eta[gp]*(1+eta[gp])/2; double phi3_eta = 1-eta[gp]*eta[gp]; //double phi_xi[3] = [phi1_xi,phi2_xi,phi3_xi]; //double phi_eta[3] = [phi1_eta,phi2_eta,phi3_eta]; //printf("gp = %d\n",gp); //printf("_xi %f %f %f:\n", phi1_xi, phi2_xi, phi3_xi); //printf("_eta %f %f %f:\n\n", phi1_eta, phi2_eta, phi3_eta); phi[0] = (-xi[gp]*(1-xi[gp])/2)*(-eta[gp]*(1-eta[gp])/2); phi[1] = (xi[gp]*(1+xi[gp])/2)*(-eta[gp]*(1-eta[gp])/2); phi[2] = (xi[gp]*(1+xi[gp])/2)*(eta[gp]*(1+eta[gp])/2); phi[3] = (-xi[gp]*(1-xi[gp])/2)*(eta[gp]*(1+eta[gp])/2); phi[4] = (1-xi[gp]*xi[gp])*(-eta[gp]*(1-eta[gp])/2); phi[5] = (xi[gp]*(1+xi[gp])/2)*(1-eta[gp]*eta[gp]); phi[6] = (1-xi[gp]*xi[gp])*(eta[gp]*(1+eta[gp])/2); phi[7] = (-xi[gp]*(1-xi[gp])/2)*(1-eta[gp]*eta[gp]); phi[8] = (1-xi[gp]*xi[gp])*(1-eta[gp]*eta[gp]); double dphi1dxi = (-1+2*xi[gp])/2; double dphi2dxi = (1+2*xi[gp])/2; double dphi3dxi = (-2*xi[gp]); double dphi1deta = (-1+2*eta[gp])/2; double dphi2deta = (1+2*eta[gp])/2; double dphi3deta = -2*eta[gp]; dphidxi[0] = ((-1+2*xi[gp])/2)*(-eta[gp]*(1-eta[gp])/2); dphidxi[1] = ((1+2*xi[gp])/2)*(-eta[gp]*(1-eta[gp])/2); dphidxi[2] = ((1+2*xi[gp])/2)*(eta[gp]*(1+eta[gp])/2); dphidxi[3] = ((-1+2*xi[gp])/2)*(eta[gp]*(1+eta[gp])/2); dphidxi[4] = (-2*xi[gp])*(-eta[gp]*(1-eta[gp])/2); dphidxi[5] = ((1+2*xi[gp])/2)*(1-eta[gp]*eta[gp]); dphidxi[6] = (-2*xi[gp])*(eta[gp]*(1+eta[gp])/2); dphidxi[7] = ((-1+2*xi[gp])/2)*(1-eta[gp]*eta[gp]); dphidxi[8] = (-2*xi[gp])*(1-eta[gp]*eta[gp]); dphideta[0] = (-xi[gp]*(1-xi[gp])/2)*((-1+2*eta[gp])/2); dphideta[1] = (xi[gp]*(1+xi[gp])/2)*((-1+2*eta[gp])/2); dphideta[2] = (xi[gp]*(1+xi[gp])/2)*((1+2*eta[gp])/2); dphideta[3] = (-xi[gp]*(1-xi[gp])/2)*((1+2*eta[gp])/2); dphideta[4] = (1-xi[gp]*xi[gp])*((-1+2*eta[gp])/2); dphideta[5] = (xi[gp]*(1+xi[gp])/2)*(-2*eta[gp]); dphideta[6] = (1-xi[gp]*xi[gp])*((1+2*eta[gp])/2); dphideta[7] = (-xi[gp]*(1-xi[gp])/2)*(-2*eta[gp]); dphideta[8] = (1-xi[gp]*xi[gp])*(-2*eta[gp]); wt = nwt[gp]; /*dphidx[0]=-(1.0-eta)/4.0; dphidx[1]= (1.0-eta)/4.0; dphidx[2]= (1.0+eta)/4.0; dphidx[3]=-(1.0+eta)/4.0;*/ /*dphide[0]=-(1.0-xi)/4.0; dphide[1]=-(1.0+xi)/4.0; dphide[2]= (1.0+xi)/4.0; dphide[3]= (1.0-xi)/4.0;*/ // Caculate basis function and derivative at GP. /*double dxdxi = .25*( (x[1]-x[0])*(1.-eta)+(x[2]-x[3])*(1.+eta) ); double dxdeta = .25*( (x[3]-x[0])*(1.- xi)+(x[2]-x[1])*(1.+ xi) ); double dydxi = .25*( (y[1]-y[0])*(1.-eta)+(y[2]-y[3])*(1.+eta) ); double dydeta = .25*( (y[3]-y[0])*(1.- xi)+(y[2]-y[1])*(1.+ xi) );*/ double dxdxi = dphi1dxi *(x[0]*phi1_eta+x[3]*phi2_eta + x[7]*phi3_eta) + dphi2dxi *(x[1]*phi1_eta+x[2]*phi2_eta + x[5]*phi3_eta) + dphi3dxi *(x[4]*phi1_eta+x[6]*phi2_eta + x[8]*phi3_eta); double dydxi = dphi1dxi *(y[0]*phi1_eta+y[3]*phi2_eta + y[7]*phi3_eta) + dphi2dxi *(y[1]*phi1_eta+y[2]*phi2_eta + y[5]*phi3_eta) + dphi3dxi *(y[4]*phi1_eta+y[6]*phi2_eta + y[8]*phi3_eta); double dxdeta = dphi1deta *(x[0]*phi1_xi+x[1]*phi2_xi + x[4]*phi3_xi) + dphi2deta *(x[3]*phi1_xi+x[2]*phi2_xi + x[6]*phi3_xi) + dphi3deta *(x[7]*phi1_xi+x[5]*phi2_xi + x[8]*phi3_xi); double dydeta = dphi1deta *(y[0]*phi1_xi+y[1]*phi2_xi + y[4]*phi3_xi) + dphi2deta *(y[3]*phi1_xi+y[2]*phi2_xi + y[6]*phi3_xi) + dphi3deta *(y[7]*phi1_xi+y[5]*phi2_xi + y[8]*phi3_xi); /*printf("%f + %f + %f\n",dphi1dxi *(x[0]*phi1_eta+x[3]*phi2_eta + x[7]*phi3_eta),dphi2dxi *(x[1]*phi1_eta+x[2]*phi2_eta + x[5]*phi3_eta),dphi3dxi *(x[4]*phi1_eta+x[6]*phi2_eta + x[8]*phi3_eta));*/ // printf("%f %f %f %f\n",dxdxi,dydeta,dxdeta,dydxi); jac = dxdxi * dydeta - dxdeta * dydxi; //printf("jacobian = %f\n\n",jac); // if (jac <= 0){ // printf("\n\n\n\n\n\nnonpositive jacobian \n\n\n\n\n\n"); // } //printf("_deta : %f %f %f\n",phi1_eta,phi2_eta,phi3_eta); // printf("_deta : %f %f %f\n",dphi1deta,dphi2deta,dphi3deta); //printf("_xi : %f %f %f\n\n",dphi1dxi,dphi2dxi,dphi3dxi); volp = jac*canonical_vol; dxidx = dydeta / jac; dxidy = -dxdeta / jac; dxidz = 0.; detadx = -dydxi / jac; detady = dxdxi / jac; detadz =0.; dztadx =0.; dztady =0.; dztadz =0.; xx=0.0; yy=0.0; zz=0.0; uu=0.0; uuold=0.0; uuoldold=0.0; dudx=0.0; dudy=0.0; dudz=0.0; duolddx = 0.; duolddy = 0.; duolddz = 0.; duoldolddx = 0.; duoldolddy = 0.; duoldolddz = 0.; for (int i=0; i < 9; i++) { xx += x[i] * phi[i]; yy += y[i] * phi[i]; dphidx[i] = dphidxi[i]*dxidx+dphideta[i]*detadx; dphidy[i] = dphidxi[i]*dxidy+dphideta[i]*detady; dphidz[i] = 0.0; dphidzta[i]= 0.0; if( u ){ uu += u[i] * phi[i]; dudx += u[i] * dphidx[i]; dudy += u[i]* dphidy[i]; } if( uold ){ uuold += uold[i] * phi[i]; duolddx += uold[i] * dphidx[i]; duolddy += uold[i]* dphidy[i]; } if( uoldold ){ uuoldold += uoldold[i] * phi[i]; duoldolddx += uoldold[i] * dphidx[i]; duoldolddy += uoldold[i]* dphidy[i]; } } //printf("getBasis done\n"); return; }; BasisQQuad* clone() const{ return new BasisQQuad(*this); }; public: // Variables that are calculated at the gauss point int sngp; }; /// Implementation of 3-D bilinear hexahedral element. /** 8 node element with number of Gauss points specified in constructor, defaults to 8. */ class BasisLHex : public Basis { public: /// Constructor /** Number of Gauss points = sngp (sngp refers to 1 dimension of a tensor product, ie sngp = 2 is really 8 Gauss points). */ BasisLHex(int n = 2): sngp(n){ canonical_vol = 8.; ngp = sngp*sngp*sngp; phi = new double[ngp]; dphidxi = new double[8]; dphideta = new double[8]; dphidzta = new double[8]; dphidx = new double[8]; dphidy = new double[8]; dphidz = new double[8]; abscissa = new double[sngp]; weight = new double[sngp]; setN(sngp, abscissa, weight); xi = new double[ngp]; eta = new double[ngp]; zta = new double[ngp]; nwt = new double[ngp]; if ( 2 == sngp ){ xi[0] = abscissa[0]; // 0, 0, 0 eta[0] = abscissa[0]; zta[0] = abscissa[0]; nwt[0] = weight[0] * weight[0] * weight[0]; xi[1] = abscissa[1]; // 1, 0, 0 eta[1] = abscissa[0]; zta[1] = abscissa[0]; nwt[1] = weight[0] * weight[1] * weight[0]; xi[2] = abscissa[1]; // 1, 1, 0 eta[2] = abscissa[1]; zta[2] = abscissa[0]; nwt[2] = weight[1] * weight[1] * weight[0]; xi[3] = abscissa[0]; //0, 1, 0 eta[3] = abscissa[1]; zta[3] = abscissa[0]; nwt[3] = weight[0] * weight[1] * weight[0]; xi[4] = abscissa[0]; // 0, 0, 1 eta[4] = abscissa[0]; zta[4] = abscissa[1]; nwt[4] = weight[0] * weight[0] * weight[1]; xi[5] = abscissa[1]; // 1, 0, 1 eta[5] = abscissa[0]; zta[5] = abscissa[1]; nwt[5] = weight[0] * weight[1] * weight[1]; xi[6] = abscissa[1]; // 1, 1, 1 eta[6] = abscissa[1]; zta[6] = abscissa[1]; nwt[6] = weight[1] * weight[1] * weight[1]; xi[7] = abscissa[0]; //0, 1, 1 eta[7] = abscissa[1]; zta[7] = abscissa[1]; nwt[7] = weight[0] * weight[1] * weight[1]; } else{ int c = 0; for( int i = 0; i < sngp; i++ ){ for( int j = 0; j < sngp; j++ ){ for( int k = 0; k < sngp; k++ ){ xi[i+j+k+c] = abscissa[i]; eta[i+j+k+c] = abscissa[j]; zta[i+j+k+c] = abscissa[k]; nwt[i+j+k+c] = weight[i] * weight[j] * weight[k]; } c = c + sngp - 1; } c = c + sngp - 1; } } }; /// Destructor ~BasisLHex() { delete [] phi; delete [] dphideta; delete [] dphidxi; delete [] dphidzta; delete [] dphidx; delete [] dphidy; delete [] dphidz; delete [] abscissa; delete [] weight; delete [] xi; delete [] eta; delete [] zta; delete [] nwt; }; void getBasis( const int gp, ///< current Gauss point (input) const double *x, ///< x array (input) const double *y, ///< y array (input) const double *z, ///< z array (input) const double *u, ///< u (solution) array (input) const double *uold, ///< uold (solution) array (input) const double *uoldold ///< uoldold (solution) array (input) ) { // Calculate basis function and derivatives at nodal pts phi[0] = 0.125 * (1.0 - xi[gp]) * (1.0 - eta[gp]) * (1.0 - zta[gp]); phi[1] = 0.125 * (1.0 + xi[gp]) * (1.0 - eta[gp]) * (1.0 - zta[gp]); phi[2] = 0.125 * (1.0 + xi[gp]) * (1.0 + eta[gp]) * (1.0 - zta[gp]); phi[3] = 0.125 * (1.0 - xi[gp]) * (1.0 + eta[gp]) * (1.0 - zta[gp]); phi[4] = 0.125 * (1.0 - xi[gp]) * (1.0 - eta[gp]) * (1.0 + zta[gp]); phi[5] = 0.125 * (1.0 + xi[gp]) * (1.0 - eta[gp]) * (1.0 + zta[gp]); phi[6] = 0.125 * (1.0 + xi[gp]) * (1.0 + eta[gp]) * (1.0 + zta[gp]); phi[7] = 0.125 * (1.0 - xi[gp]) * (1.0 + eta[gp]) * (1.0 + zta[gp]); // ksi-derivatives dphidxi[0] = -0.125 * (1.0 - eta[gp]) * (1.0 - zta[gp]); dphidxi[1] = 0.125 * (1.0 - eta[gp]) * (1.0 - zta[gp]); dphidxi[2] = 0.125 * (1.0 + eta[gp]) * (1.0 - zta[gp]); dphidxi[3] = -0.125 * (1.0 + eta[gp]) * (1.0 - zta[gp]); dphidxi[4] = -0.125 * (1.0 - eta[gp]) * (1.0 + zta[gp]); dphidxi[5] = 0.125 * (1.0 - eta[gp]) * (1.0 + zta[gp]); dphidxi[6] = 0.125 * (1.0 + eta[gp]) * (1.0 + zta[gp]); dphidxi[7] = -0.125 * (1.0 + eta[gp]) * (1.0 + zta[gp]); // eta-derivatives dphideta[0] = -0.125 * (1.0 - xi[gp]) * (1.0 - zta[gp]); dphideta[1] = -0.125 * (1.0 + xi[gp]) * (1.0 - zta[gp]); dphideta[2] = 0.125 * (1.0 + xi[gp]) * (1.0 - zta[gp]); dphideta[3] = 0.125 * (1.0 - xi[gp]) * (1.0 - zta[gp]); dphideta[4] = -0.125 * (1.0 - xi[gp]) * (1.0 + zta[gp]); dphideta[5] = -0.125 * (1.0 + xi[gp]) * (1.0 + zta[gp]); dphideta[6] = 0.125 * (1.0 + xi[gp]) * (1.0 + zta[gp]); dphideta[7] = 0.125 * (1.0 - xi[gp]) * (1.0 + zta[gp]); // zeta-derivatives dphidzta[0] = -0.125 * (1.0 - xi[gp]) * (1.0 - eta[gp]); dphidzta[1] = -0.125 * (1.0 + xi[gp]) * (1.0 - eta[gp]); dphidzta[2] = -0.125 * (1.0 + xi[gp]) * (1.0 + eta[gp]); dphidzta[3] = -0.125 * (1.0 - xi[gp]) * (1.0 + eta[gp]); dphidzta[4] = 0.125 * (1.0 - xi[gp]) * (1.0 - eta[gp]); dphidzta[5] = 0.125 * (1.0 + xi[gp]) * (1.0 - eta[gp]); dphidzta[6] = 0.125 * (1.0 + xi[gp]) * (1.0 + eta[gp]); dphidzta[7] = 0.125 * (1.0 - xi[gp]) * (1.0 + eta[gp]); // Caculate basis function and derivative at GP. double dxdxi = 0.125*( (x[1]-x[0])*(1.-eta[gp])*(1.-zta[gp]) + (x[2]-x[3])*(1.+eta[gp])*(1.-zta[gp]) + (x[5]-x[4])*(1.-eta[gp])*(1.+zta[gp]) + (x[6]-x[7])*(1.+eta[gp])*(1.+zta[gp]) ); double dxdeta = 0.125*( (x[3]-x[0])*(1.- xi[gp])*(1.-zta[gp]) + (x[2]-x[1])*(1.+ xi[gp])*(1.-zta[gp]) + (x[7]-x[4])*(1.- xi[gp])*(1.+zta[gp]) + (x[6]-x[5])*(1.+ xi[gp])*(1.+zta[gp]) ); double dxdzta = 0.125*( (x[4]-x[0])*(1.- xi[gp])*(1.-eta[gp]) + (x[5]-x[1])*(1.+ xi[gp])*(1.-eta[gp]) + (x[6]-x[2])*(1.+ xi[gp])*(1.+eta[gp]) + (x[7]-x[3])*(1.- xi[gp])*(1.+eta[gp]) ); double dydxi = 0.125*( (y[1]-y[0])*(1.-eta[gp])*(1.-zta[gp]) + (y[2]-y[3])*(1.+eta[gp])*(1.-zta[gp]) + (y[5]-y[4])*(1.-eta[gp])*(1.+zta[gp]) + (y[6]-y[7])*(1.+eta[gp])*(1.+zta[gp]) ); double dydeta = 0.125*( (y[3]-y[0])*(1.- xi[gp])*(1.-zta[gp]) + (y[2]-y[1])*(1.+ xi[gp])*(1.-zta[gp]) + (y[7]-y[4])*(1.- xi[gp])*(1.+zta[gp]) + (y[6]-y[5])*(1.+ xi[gp])*(1.+zta[gp]) ); double dydzta = 0.125*( (y[4]-y[0])*(1.- xi[gp])*(1.-eta[gp]) + (y[5]-y[1])*(1.+ xi[gp])*(1.-eta[gp]) + (y[6]-y[2])*(1.+ xi[gp])*(1.+eta[gp]) + (y[7]-y[3])*(1.- xi[gp])*(1.+eta[gp]) ); double dzdxi = 0.125*( (z[1]-z[0])*(1.-eta[gp])*(1.-zta[gp]) + (z[2]-z[3])*(1.+eta[gp])*(1.-zta[gp]) + (z[5]-z[4])*(1.-eta[gp])*(1.+zta[gp]) + (z[6]-z[7])*(1.+eta[gp])*(1.+zta[gp]) ); double dzdeta = 0.125*( (z[3]-z[0])*(1.- xi[gp])*(1.-zta[gp]) + (z[2]-z[1])*(1.+ xi[gp])*(1.-zta[gp]) + (z[7]-z[4])*(1.- xi[gp])*(1.+zta[gp]) + (z[6]-z[5])*(1.+ xi[gp])*(1.+zta[gp]) ); double dzdzta = 0.125*( (z[4]-z[0])*(1.- xi[gp])*(1.-eta[gp]) + (z[5]-z[1])*(1.+ xi[gp])*(1.-eta[gp]) + (z[6]-z[2])*(1.+ xi[gp])*(1.+eta[gp]) + (z[7]-z[3])*(1.- xi[gp])*(1.+eta[gp]) ); wt = nwt[gp]; jac = dxdxi*(dydeta*dzdzta - dydzta*dzdeta) - dxdeta*(dydxi*dzdzta - dydzta*dzdxi) + dxdzta*(dydxi*dzdeta - dydeta*dzdxi); volp = jac*canonical_vol; dxidx = (-dydzta*dzdeta + dydeta*dzdzta) / jac; dxidy = ( dxdzta*dzdeta - dxdeta*dzdzta) / jac; dxidz = (-dxdzta*dydeta + dxdeta*dydzta) / jac; detadx = ( dydzta*dzdxi - dydxi*dzdzta) / jac; detady = (-dxdzta*dzdxi + dxdxi*dzdzta) / jac; detadz = ( dxdzta*dydxi - dxdxi*dydzta) / jac; dztadx = ( dydxi*dzdeta - dydeta*dzdxi) / jac; dztady = (-dxdxi*dzdeta + dxdeta*dzdxi) / jac; dztadz = ( dxdxi*dydeta - dxdeta*dydxi) / jac; // Caculate basis function and derivative at GP. xx=0.0; yy=0.0; zz=0.0; uu=0.0; uuold=0.0; uuoldold=0.0; dudx=0.0; dudy=0.0; dudz=0.0; duolddx = 0.; duolddy = 0.; duolddz = 0.; duoldolddx = 0.; duoldolddy = 0.; duoldolddz = 0.; // x[i] is a vector of node coords, x(j, k) for (int i=0; i < 8; i++) { xx += x[i] * phi[i]; yy += y[i] * phi[i]; zz += z[i] * phi[i]; dphidx[i] = dphidxi[i]*dxidx+dphideta[i]*detadx+dphidzta[i]*dztadx; dphidy[i] = dphidxi[i]*dxidy+dphideta[i]*detady+dphidzta[i]*dztady; dphidz[i] = dphidxi[i]*dxidz+dphideta[i]*detadz+dphidzta[i]*dztadz; if( u ){ uu += u[i] * phi[i]; dudx += u[i] * (dphidxi[i]*dxidx+dphideta[i]*detadx+dphidzta[i]*dztadx); dudy += u[i] * (dphidxi[i]*dxidy+dphideta[i]*detady+dphidzta[i]*dztady); dudz += u[i] * (dphidxi[i]*dxidz+dphideta[i]*detadz+dphidzta[i]*dztadz); } if( uold ){ uuold += uold[i] * phi[i]; duolddx += uold[i] * (dphidxi[i]*dxidx+dphideta[i]*detadx+dphidzta[i]*dztadx); duolddy += uold[i] * (dphidxi[i]*dxidy+dphideta[i]*detady+dphidzta[i]*dztady); duolddz += uold[i] * (dphidxi[i]*dxidz+dphideta[i]*detadz+dphidzta[i]*dztadz); //exit(0); } if( uoldold ){ uuoldold += uoldold[i] * phi[i]; duoldolddx += uoldold[i] * (dphidxi[i]*dxidx+dphideta[i]*detadx+dphidzta[i]*dztadx); duoldolddy += uoldold[i] * (dphidxi[i]*dxidx+dphideta[i]*detadx+dphidzta[i]*dztadx); duoldolddz += uoldold[i] * (dphidxi[i]*dxidx+dphideta[i]*detadx+dphidzta[i]*dztadx); } } return; }; /// Evaluate the basis functions at the specified at point xx, yy ,zz /** Evaluate the 3D basis functions at xx, yy, zz and interpolate u. True if xx, yy, zz is in this element. Returns val = u(xx,yy,zz)*/ bool evalBasis( const double *x, ///< x array (input) const double *y, ///< y array (input) const double *z, ///< z array (input) const double *u, ///< u (solution) array (input) const double xx_, ///< xx const double yy_,///< yy const double zz_,///< zz double &val ///< return val ){ //for each direction we solve the a nonlinear system for the barycentric coords // F1(xi,eta) = -xx + sum_k x(k)*phi(k) == 0 // The Newton system gives J(v) dv = -F(v) , where inv(J) is calculated explicitly const int niter = 3; const int nnode = 8; //initial iterate double xi_ = 0.0; double eta_ = 0.0; double zta_ = 0.0; for(int i = 0; i < niter; i++){ // Calculate basis function and derivatives at iterate phi[0] = 0.125 * (1.0 - xi_) * (1.0 - eta_) * (1.0 - zta_); phi[1] = 0.125 * (1.0 + xi_) * (1.0 - eta_) * (1.0 - zta_); phi[2] = 0.125 * (1.0 + xi_) * (1.0 + eta_) * (1.0 - zta_); phi[3] = 0.125 * (1.0 - xi_) * (1.0 + eta_) * (1.0 - zta_); phi[4] = 0.125 * (1.0 - xi_) * (1.0 - eta_) * (1.0 + zta_); phi[5] = 0.125 * (1.0 + xi_) * (1.0 - eta_) * (1.0 + zta_); phi[6] = 0.125 * (1.0 + xi_) * (1.0 + eta_) * (1.0 + zta_); phi[7] = 0.125 * (1.0 - xi_) * (1.0 + eta_) * (1.0 + zta_); dphidxi[0] = -0.125 * (1.0 - eta_) * (1.0 - zta_); dphidxi[1] = 0.125 * (1.0 - eta_) * (1.0 - zta_); dphidxi[2] = 0.125 * (1.0 + eta_) * (1.0 - zta_); dphidxi[3] = -0.125 * (1.0 + eta_) * (1.0 - zta_); dphidxi[4] = -0.125 * (1.0 - eta_) * (1.0 + zta_); dphidxi[5] = 0.125 * (1.0 - eta_) * (1.0 + zta_); dphidxi[6] = 0.125 * (1.0 + eta_) * (1.0 + zta_); dphidxi[7] = -0.125 * (1.0 + eta_) * (1.0 + zta_); dphideta[0] = -0.125 * (1.0 - xi_) * (1.0 - zta_); dphideta[1] = -0.125 * (1.0 + xi_) * (1.0 - zta_); dphideta[2] = 0.125 * (1.0 + xi_) * (1.0 - zta_); dphideta[3] = 0.125 * (1.0 - xi_) * (1.0 - zta_); dphideta[4] = -0.125 * (1.0 - xi_) * (1.0 + zta_); dphideta[5] = -0.125 * (1.0 + xi_) * (1.0 + zta_); dphideta[6] = 0.125 * (1.0 + xi_) * (1.0 + zta_); dphideta[7] = 0.125 * (1.0 - xi_) * (1.0 + zta_); dphidzta[0] = -0.125 * (1.0 - xi_) * (1.0 - eta_); dphidzta[1] = -0.125 * (1.0 + xi_) * (1.0 - eta_); dphidzta[2] = -0.125 * (1.0 + xi_) * (1.0 + eta_); dphidzta[3] = -0.125 * (1.0 - xi_) * (1.0 + eta_); dphidzta[4] = 0.125 * (1.0 - xi_) * (1.0 - eta_); dphidzta[5] = 0.125 * (1.0 + xi_) * (1.0 - eta_); dphidzta[6] = 0.125 * (1.0 + xi_) * (1.0 + eta_); dphidzta[7] = 0.125 * (1.0 - xi_) * (1.0 + eta_); double f0 = -xx_; double f1 = -yy_; double f2 = -zz_; double j00 = 0.; double j01 = 0.; double j02 = 0.; double j10 = 0.; double j11 = 0.; double j12 = 0.; double j20 = 0.; double j21 = 0.; double j22 = 0.; //residual F and elements of J for(int k = 0; k < nnode; k++){ f0 = f0 +x[k]*phi[k]; f1 = f1 +y[k]*phi[k]; f2 = f2 +z[k]*phi[k]; j00=j00 +x[k]*dphidxi[k]; j01=j01 +x[k]*dphideta[k]; j02=j02 +x[k]*dphidzta[k]; j10=j10 +y[k]*dphidxi[k]; j11=j11 +y[k]*dphideta[k]; j12=j12 +y[k]*dphidzta[k]; j20=j20 +z[k]*dphidxi[k]; j21=j21 +z[k]*dphideta[k]; j22=j22 +z[k]*dphidzta[k]; }//k double deti=j00*j11*j22 + j10*j21*j02 + j20*j01*j12 - j00*j21*j12 - j20*j11*j02 - j10*j01*j22; double a00=j11*j22-j12*j21; double a01=j02*j21-j01*j22; double a02=j01*j12-j02*j11; double a10=j12*j20-j10*j22; double a11=j00*j22-j02*j20; double a12=j02*j10-j00*j12; double a20=j10*j21-j11*j20; double a21=j01*j20-j00*j21; double a22=j00*j11-j01*j10; double dxi= -(a00*f0+a01*f1+a02*f2)/deti; double deta= -(a10*f0+a11*f1+a12*f2)/deti; double dzta= -(a20*f0+a21*f1+a22*f2)/deti; xi_=dxi+xi_; eta_=deta+eta_; zta_=dzta+zta_; }//i //std::cout<<xi_<<" "<<eta_<<" "<<zta_<<std::endl; //cn hack here, need to think about a reasonable number here double small = 1e-8; if( (std::fabs(xi_) > (1.+small))||(std::fabs(eta_) > (1.+small))||(std::fabs(zta_) > (1.+small)) ) return false; phi[0] = 0.125 * (1.0 - xi_) * (1.0 - eta_) * (1.0 - zta_); phi[1] = 0.125 * (1.0 + xi_) * (1.0 - eta_) * (1.0 - zta_); phi[2] = 0.125 * (1.0 + xi_) * (1.0 + eta_) * (1.0 - zta_); phi[3] = 0.125 * (1.0 - xi_) * (1.0 + eta_) * (1.0 - zta_); phi[4] = 0.125 * (1.0 - xi_) * (1.0 - eta_) * (1.0 + zta_); phi[5] = 0.125 * (1.0 + xi_) * (1.0 - eta_) * (1.0 + zta_); phi[6] = 0.125 * (1.0 + xi_) * (1.0 + eta_) * (1.0 + zta_); phi[7] = 0.125 * (1.0 - xi_) * (1.0 + eta_) * (1.0 + zta_); val = 0.; for(int k = 0; k < nnode; k++){ val = val + u[k]*phi[k]; }//k return true; }; BasisLHex* clone() const{ return new BasisLHex(*this); }; // Calculates the values of u and x at the specified gauss point void getBasis(const int gp, ///< current Gauss point (input) const double *x, ///< x array (input) const double *y ///< y array (input) ){ std::cout<<"BasisLHex::getBasis(int gp, double *x, double *y) is not implemented"<<std::endl; //exit(0); }; public: // Variables that are calculated at the gauss point int sngp; }; /// Implementation of 3-D bilinear tetrahedral element. /** 4 node element with 4 Gauss points. */ class BasisLTet : public Basis { public: /// Constructor BasisLTet(){ //cn we can have 1 or 4 guass points; 4 will be default canonical_vol = 1./6.; #if 0 sngp = 1; ngp = 1; #endif sngp = 2; ngp = 4; phi = new double[ngp]; dphidxi = new double[ngp]; dphideta = new double[ngp]; dphidzta = new double[ngp]; dphidx = new double[ngp]; dphidy = new double[ngp]; dphidz = new double[ngp]; abscissa = new double[sngp]; weight = new double[sngp]; //setN(sngp, abscissa, weight); #if 0 abscissa[0] = 0.25000000; weight[0] = 0.16666667; #endif abscissa[0] = 0.13819660; abscissa[1] = 0.58541020; weight[0] = 0.041666666667; weight[1] = 0.041666666667; xi = new double[ngp]; eta = new double[ngp]; zta = new double[ngp]; nwt = new double[ngp]; #if 0 if(0 == gp){ xi = abscissa[0]; // 0, 0, 0 eta = abscissa[0]; zta = abscissa[0]; //wt = weight[0] * weight[0] * weight[0]; }else if (1 == gp){ xi = abscissa[1]; // 1, 0, 0 eta = abscissa[0]; zta = abscissa[0]; //wt = weight[0] * weight[1] * weight[0]; }else if (2 == gp){ xi = abscissa[0]; // 1, 1, 0 eta = abscissa[1]; zta = abscissa[0]; //wt = weight[1] * weight[1] * weight[0]; }else if (3 == gp){ xi = abscissa[0]; //0, 1, 0 eta = abscissa[0]; zta = abscissa[1]; //wt = weight[0] * weight[1] * weight[0]; } wt=weight[0];//cn each wt = .25/6=0.041666666667 #endif xi[0] = abscissa[0]; // 0, 0, 0 eta[0] = abscissa[0]; zta[0] = abscissa[0]; nwt[0] = weight[0]; xi[1] = abscissa[1]; // 1, 0, 0 eta[1] = abscissa[0]; zta[1] = abscissa[0]; nwt[1] = weight[0]; xi[2] = abscissa[0]; // 1, 1, 0 eta[2] = abscissa[1]; zta[2] = abscissa[0]; nwt[2] = weight[0]; xi[3]= abscissa[0]; //0, 1, 0 eta[3] = abscissa[0]; zta [3]= abscissa[1]; nwt[3] = weight[0]; }; // BasisLTet(int sngp); /// Destructor ~BasisLTet(){ delete [] phi; delete [] dphideta; delete [] dphidxi; delete [] dphidzta; delete [] dphidx; delete [] dphidy; delete [] dphidz; delete [] abscissa; delete [] weight; delete [] xi; delete [] eta; delete [] zta; delete [] nwt; }; BasisLTet* clone() const{ return new BasisLTet(*this); }; void getBasis( const int gp, ///< current Gauss point (input) const double *x, ///< x array (input) const double *y, ///< y array (input) const double *z, ///< z array (input) const double *u, ///< u (solution) array (input) const double *uold, ///< uold (solution) array (input) const double *uoldold ///< uoldold (solution) array (input) ) { // Calculate basis function and derivatives at nodal pts phi[0] = 1.0 - xi[gp] - eta[gp] - zta[gp]; phi[1] = xi[gp]; phi[2] = eta[gp]; phi[3] = zta[gp]; // ksi-derivatives dphidxi[0] = -1.; dphidxi[1] = 1.; dphidxi[2] = 0.; dphidxi[3] = 0.; // eta-derivatives dphideta[0] = -1.; dphideta[1] = 0.; dphideta[2] = 1.; dphideta[3] = 0.; // zeta-derivatives dphidzta[0] = -1.; dphidzta[1] = 0.; dphidzta[2] = 0.; dphidzta[3] = 1.; wt = nwt[gp]; // Caculate basis function and derivative at GP. double dxdxi = (x[1]-x[0]); double dxdeta = (x[2]-x[0]); double dxdzta = (x[3]-x[0]); double dydxi = (y[1]-y[0]); double dydeta = (y[2]-y[0]); double dydzta = (y[3]-y[0]); double dzdxi = (z[1]-z[0]); double dzdeta = (z[2]-z[0]); double dzdzta = (z[3]-z[0]); jac = dxdxi*(dydeta*dzdzta - dydzta*dzdeta) - dxdeta*(dydxi*dzdzta - dydzta*dzdxi) + dxdzta*(dydxi*dzdeta - dydeta*dzdxi); volp = jac*canonical_vol; dxidx = (-dydzta*dzdeta + dydeta*dzdzta) / jac; dxidy = ( dxdzta*dzdeta - dxdeta*dzdzta) / jac; dxidz = (-dxdzta*dydeta + dxdeta*dydzta) / jac; detadx = ( dydzta*dzdxi - dydxi*dzdzta) / jac; detady = (-dxdzta*dzdxi + dxdxi*dzdzta) / jac; detadz = ( dxdzta*dydxi - dxdxi*dydzta) / jac; dztadx = ( dydxi*dzdeta - dydeta*dzdxi) / jac; dztady = (-dxdxi*dzdeta + dxdeta*dzdxi) / jac; dztadz = ( dxdxi*dydeta - dxdeta*dydxi) / jac; // Caculate basis function and derivative at GP. xx=0.0; yy=0.0; zz=0.0; uu=0.0; uuold=0.0; uuoldold=0.0; dudx=0.0; dudy=0.0; dudz=0.0; duolddx = 0.; duolddy = 0.; duolddz = 0.; duoldolddx = 0.; duoldolddy = 0.; duoldolddz = 0.; // x[i] is a vector of node coords, x(j, k) for (int i=0; i < ngp; i++) { xx += x[i] * phi[i]; yy += y[i] * phi[i]; zz += z[i] * phi[i]; dphidx[i] = dphidxi[i]*dxidx+dphideta[i]*detadx+dphidzta[i]*dztadx; dphidy[i] = dphidxi[i]*dxidy+dphideta[i]*detady+dphidzta[i]*dztady; dphidz[i] = dphidxi[i]*dxidz+dphideta[i]*detadz+dphidzta[i]*dztadz; if( u ){ uu += u[i] * phi[i]; dudx += u[i] * (dphidxi[i]*dxidx+dphideta[i]*detadx+dphidzta[i]*dztadx); dudy += u[i] * (dphidxi[i]*dxidy+dphideta[i]*detady+dphidzta[i]*dztady); dudz += u[i] * (dphidxi[i]*dxidz+dphideta[i]*detadz+dphidzta[i]*dztadz); } if( uold ){ uuold += uold[i] * phi[i]; duolddx += uold[i] * (dphidxi[i]*dxidx+dphideta[i]*detadx+dphidzta[i]*dztadx); duolddy += uold[i] * (dphidxi[i]*dxidy+dphideta[i]*detady+dphidzta[i]*dztady); duolddz += uold[i] * (dphidxi[i]*dxidz+dphideta[i]*detadz+dphidzta[i]*dztadz); //exit(0); } if( uoldold ){ uuoldold += uoldold[i] * phi[i]; duoldolddx += uoldold[i] * (dphidxi[i]*dxidx+dphideta[i]*detadx+dphidzta[i]*dztadx); duoldolddy += uoldold[i] * (dphidxi[i]*dxidy+dphideta[i]*detady+dphidzta[i]*dztady); duoldolddz += uoldold[i] * (dphidxi[i]*dxidz+dphideta[i]*detadz+dphidzta[i]*dztadz); } } return; }; // Calculates the values of u and x at the specified gauss point void getBasis(const int gp, ///< current Gauss point (input) const double *x, ///< x array (input) const double *y ///< y array (input) ) { std::cout<<"BasisLTet::getBasis(int gp, double *x, double *y) is not implemented"<<std::endl; //exit(0); }; public: // Variables that are calculated at the gauss point int sngp; }; /// Implementation of 1-D linear bar element. /** 2 node element with number of Gauss points specified in constructor, defaults to 2. */ class BasisLBar : public Basis { public: /// Constructor /** Number of Gauss points = sngp; default 2. */ BasisLBar(int n = 2) :sngp(n){ ngp = sngp; phi = new double[2];//number of nodes dphidxi = new double[2]; dphideta = new double[2]; dphidzta = new double[2]; dphidx = new double[2]; dphidy = new double[2]; dphidz = new double[2]; abscissa = new double[sngp];//number guass pts weight = new double[sngp]; setN(sngp, abscissa, weight); xi = new double[ngp]; nwt = new double[ngp]; for(int i = 0; i < sngp; i++){ xi[i] = abscissa[i]; nwt[i] = weight[i]; } }; /// Destructor ~BasisLBar() { delete [] phi; delete [] dphidxi; delete [] dphideta; delete [] dphidzta; delete [] dphidx; delete [] dphidy; delete [] dphidz; delete [] abscissa; delete [] weight; delete [] xi; delete [] nwt; }; void getBasis( const int gp, ///< current Gauss point (input) const double *x, ///< x array (input) const double *y, ///< y array (input) const double *z, ///< z array (input) const double *u, ///< u (solution) array (input) const double *uold, ///< uold (solution) array (input) const double *uoldold ///< uoldold (solution) array (input) ) { // Calculate basis function and derivatives at nodal pts phi[0]=(1.0-xi[gp])/2.0; phi[1]=(1.0+xi[gp])/2.0; dphidxi[0]= -1.0/2.0; dphidxi[1]= 1.0/2.0; dphideta[0]= 0.0; dphideta[1]= 0.0; dphidzta[0] = 0.0; dphidzta[1]= 0.0; // Caculate basis function and derivative at GP. //std::cout<<x[0]<<" "<<x[1]<<" "<<x[2]<<" "<<x[3]<<std::endl; double dxdxi = .5* (x[1]-x[0]); //double dxdeta = .25*( (x[3]-x[0])*(1.- xi)+(x[2]-x[1])*(1.+ xi) ); //double dydxi = .25*( (y[1]-y[0])*(1.-eta)+(y[2]-y[3])*(1.+eta) ); double dydxi = .5*(y[1]-y[0]); //double dydeta = .25*( (y[3]-y[0])*(1.- xi)+(y[2]-y[1])*(1.+ xi) ); double dzdxi = .5*(z[1]-z[0]); wt = nwt[gp]; jac = sqrt(dxdxi*dxdxi+dydxi*dydxi+dzdxi*dzdxi); dxidx = 1. / dxdxi; dxidy = 1. / dydxi; dxidz = 1. / dzdxi; detadx = 0.; detady = 0.; detadz =0.; dztadx =0.; dztady =0.; dztadz =0.; // Caculate basis function and derivative at GP. xx=0.0; yy=0.0; zz=0.0; uu=0.0; uuold=0.0; uuoldold=0.0; dudx=0.0; dudy=0.0; dudz=0.0; duolddx = 0.; duolddy = 0.; duolddz = 0.; duoldolddx = 0.; duoldolddy = 0.; duoldolddz = 0.; // x[i] is a vector of node coords, x(j, k) for (int i=0; i < 2; i++) { xx += x[i] * phi[i]; yy += y[i] * phi[i]; zz += z[i] * phi[i]; dphidx[i] = dphidxi[i]*dxidx; dphidy[i] = dphidxi[i]*dxidy; dphidz[i] = dphidxi[i]*dxidz; if( u ){ uu += u[i] * phi[i]; dudx += u[i] * dphidx[i]; dudy += u[i]* dphidy[i]; } if( uold ){ uuold += uold[i] * phi[i]; duolddx += uold[i] * dphidx[i]; duolddy += uold[i]* dphidy[i]; } if( uoldold ){ uuoldold += uoldold[i] * phi[i]; duoldolddx += uoldold[i] * dphidx[i]; duoldolddy += uoldold[i]* dphidy[i]; } } return; }; BasisLBar* clone() const{ return new BasisLBar(*this); }; public: // Variables that are calculated at the gauss point int sngp; }; /// Implementation of 1-D quadratic bar element. /** 3 node element with number of Gauss points specified in constructor, defaults to 3. */ class BasisQBar : public Basis { public: /// Constructor /** Number of Gauss points = sngp; default 3. */ BasisQBar(int n = 3) :sngp(n){ ngp = sngp; phi = new double[3];//number of nodes dphidxi = new double[3]; dphideta = new double[3]; dphidzta = new double[3]; dphidx = new double[3]; dphidy = new double[3]; dphidz = new double[3]; abscissa = new double[sngp];//number guass pts weight = new double[sngp]; setN(sngp, abscissa, weight); xi = new double[ngp]; nwt = new double[ngp]; for(int i = 0; i < sngp; i++){ xi[i] = abscissa[i]; nwt[i] = weight[i]; } }; /// Destructor ~BasisQBar(){ delete [] phi; delete [] dphidxi; delete [] dphideta; delete [] dphidzta; delete [] dphidx; delete [] dphidy; delete [] dphidz; delete [] abscissa; delete [] weight; delete [] xi; delete [] nwt; }; void getBasis( const int gp, ///< current Gauss point (input) const double *x, ///< x array (input) const double *y, ///< y array (input) const double *z, ///< z array (input) const double *u, ///< u (solution) array (input) const double *uold, ///< uold (solution) array (input) const double *uoldold ///< uoldold (solution) array (input) ) { // Calculate basis function and derivatives at nodal pts phi[0]=-xi[gp]*(1.0-xi[gp])/2.0; phi[1]=xi[gp]*(1.0+xi[gp])/2.0; phi[2]=(1.0-xi[gp]*xi[gp]); dphidxi[0]=-1.0/2.0 + xi[gp]; dphidxi[1]= 1.0/2.0 + xi[gp]; dphidxi[2]=-2.0*xi[gp]; dphideta[0]= 0.0; dphideta[1]= 0.0; dphideta[2]= 0.0; dphidzta[0] = 0.0; dphidzta[1]= 0.0; dphidzta[2]= 0.0; // Caculate basis function and derivative at GP. double dxdxi = dphidxi[0]*x[0] + dphidxi[1]*x[1] + dphidxi[2]*x[2]; double dydxi = dphidxi[0]*y[0] + dphidxi[1]*y[1] + dphidxi[2]*y[2]; double dzdxi = dphidxi[0]*z[0] + dphidxi[1]*z[1] + dphidxi[2]*z[2]; wt = nwt[gp]; jac = sqrt(dxdxi*dxdxi+dydxi*dydxi+dzdxi*dzdxi); dxidx = 1. / dxdxi; dxidy = 1. / dydxi; dxidz = 1. / dzdxi; detadx = 0.; detady = 0.; detadz =0.; dztadx =0.; dztady =0.; dztadz =0.; // Caculate basis function and derivative at GP. xx=0.0; yy=0.0; zz=0.0; uu=0.0; uuold=0.0; uuoldold=0.0; dudx=0.0; dudy=0.0; dudz=0.0; duolddx = 0.; duolddy = 0.; duolddz = 0.; duoldolddx = 0.; duoldolddy = 0.; duoldolddz = 0.; // x[i] is a vector of node coords, x(j, k) for (int i=0; i < 3; i++) { xx += x[i] * phi[i]; yy += y[i] * phi[i]; zz += z[i] * phi[i]; dphidx[i] = dphidxi[i]*dxidx; dphidy[i] = dphidxi[i]*dxidy; dphidz[i] = dphidxi[i]*dxidz; if( u ){ //uu += u[i] * phi[i]; //dudx += u[i] * dphidx[i]; //dudy += u[i]* dphidy[i]; } if( uold ){ //uuold += uold[i] * phi[i]; //duolddx += uold[i] * dphidx[i]; //duolddy += uold[i]* dphidy[i]; } if( uoldold ){ //uuoldold += uoldold[i] * phi[i]; //duoldolddx += uoldold[i] * dphidx[i]; //duoldolddy += uoldold[i]* dphidy[i]; } } return; }; BasisQBar* clone() const{ return new BasisQBar(*this); }; public: // Variables that are calculated at the gauss point int sngp; }; class OMPBasisLQuad{ public: int sngp; /// Access number of Gauss points. int ngp; OMPBasisLQuad(){ sngp =2; ngp = sngp*sngp; //phi = new double[4];//number of nodes //dphidxi = new double[4]; //dphideta = new double[4]; //dphidzta = new double[4]; //dphidx = new double[4]; //dphidy = new double[4]; //dphidz = new double[4]; //abscissa = new double[sngp];//number guass pts //weight = new double[sngp]; //setN(sngp, abscissa, weight); abscissa[0] = -1.0L/1.732050807568877; abscissa[1] = 1.0L/1.732050807568877; weight[0] = 1.0; weight[1] = 1.0; //xi = new double[ngp]; //eta = new double[ngp]; //nwt = new double[ngp]; //cn right now, changing the order when ngp = 4 breaks all the quad tests //cn so we leave it for now... xi[0] = abscissa[0]; eta[0] = abscissa[0]; nwt[0] = weight[0] * weight[0]; xi[1] = abscissa[1]; eta[1] = abscissa[0]; nwt[1] = weight[0] * weight[1]; xi[2] = abscissa[1]; eta[2] = abscissa[1]; nwt[2] = weight[1] * weight[1]; xi[3] = abscissa[0]; eta[3] = abscissa[1]; nwt[3] = weight[0] * weight[1]; // Calculate basis function and derivatives at nodal pts for (int i=0; i < 4; i++) { phi1[0][i]=(1.0-xi[i])*(1.0-eta[i])/4.0; phi1[1][i]=(1.0+xi[i])*(1.0-eta[i])/4.0; phi1[2][i]=(1.0+xi[i])*(1.0+eta[i])/4.0; phi1[3][i]=(1.0-xi[i])*(1.0+eta[i])/4.0; dphidxi1[0][i]=-(1.0-eta[i])/4.0; dphidxi1[1][i]= (1.0-eta[i])/4.0; dphidxi1[2][i]= (1.0+eta[i])/4.0; dphidxi1[3][i]=-(1.0+eta[i])/4.0; dphideta1[0][i]=-(1.0-xi[i])/4.0; dphideta1[1][i]=-(1.0+xi[i])/4.0; dphideta1[2][i]= (1.0+xi[i])/4.0; dphideta1[3][i]= (1.0-xi[i])/4.0; } } KOKKOS_INLINE_FUNCTION void getBasis(const int gp,const double x[4], const double y[4], const double z[4],const double u[4],const double uold[4]) const { return; } void getBasis(const int gp,const double x[4], const double y[4], const double z[4],const double u[4],const double uold[4],const double uoldold[4]) { // Caculate basis function and derivative at GP. double dxdxi = .25*( (x[1]-x[0])*(1.-eta[gp])+(x[2]-x[3])*(1.+eta[gp]) ); double dxdeta = .25*( (x[3]-x[0])*(1.- xi[gp])+(x[2]-x[1])*(1.+ xi[gp]) ); double dydxi = .25*( (y[1]-y[0])*(1.-eta[gp])+(y[2]-y[3])*(1.+eta[gp]) ); double dydeta = .25*( (y[3]-y[0])*(1.- xi[gp])+(y[2]-y[1])*(1.+ xi[gp]) ); double dzdxi = .25*( (z[1]-z[0])*(1.-eta[gp])+(z[2]-z[3])*(1.+eta[gp]) ); double dzdeta = .25*( (z[3]-z[0])*(1.- xi[gp])+(z[2]-z[1])*(1.+ xi[gp]) ); wt = nwt[gp]; jac = dxdxi * dydeta - dxdeta * dydxi; // jac = sqrt( (dzdxi * dxdeta - dxdxi * dzdeta)*(dzdxi * dxdeta - dxdxi * dzdeta) // +(dydxi * dzdeta - dzdxi * dydeta)*(dydxi * dzdeta - dzdxi * dydeta) // +(dxdxi * dydeta - dxdeta * dydxi)*(dxdxi * dydeta - dxdeta * dydxi)); dxidx = dydeta / jac; dxidy = -dxdeta / jac; dxidz = 0.; detadx = -dydxi / jac; detady = dxdxi / jac; detadz =0.; dztadx =0.; dztady =0.; dztadz =0.; // Caculate basis function and derivative at GP. xx=0.0; yy=0.0; zz=0.0; uu=0.0; uuold=0.0; uuoldold=0.0; dudx=0.0; dudy=0.0; dudz=0.0; duolddx = 0.; duolddy = 0.; duolddz = 0.; duoldolddx = 0.; duoldolddy = 0.; duoldolddz = 0.; // x[i] is a vector of node coords, x(j, k) for (int i=0; i < 4; i++) { xx += x[i] * phi1[i][gp]; yy += y[i] * phi1[i][gp]; zz += z[i] * phi1[i][gp]; dphidx[i] = dphidxi1[i][gp]*dxidx+dphideta1[i][gp]*detadx; dphidy[i] = dphidxi1[i][gp]*dxidy+dphideta1[i][gp]*detady; dphidz[i] = 0.0; dphidzta[i]= 0.0; uu += u[i] * phi1[i][gp]; dudx += u[i] * dphidx[i]; dudy += u[i]* dphidy[i]; uuold += uold[i] * phi1[i][gp]; duolddx += uold[i] * dphidx[i]; duolddy += uold[i]* dphidy[i]; uuoldold += uoldold[i] * phi1[i][gp]; duoldolddx += uoldold[i] * dphidx[i]; duoldolddy += uoldold[i]* dphidy[i]; } return; } // Variables that are calculated at the gauss point /// Access value of basis function at the current Gauss point. double phi1[4][4]; /// Access value of dphi / dxi at the current Gauss point. double dphidxi1[4][4]; /// Access value of dphi / deta at the current Gauss point. double dphideta1[4][4]; /// Access value of dphi / dzta at the current Gauss point. double dphidzta[4]; /// Access value of dxi / dx at the current Gauss point. double dxidx; /// Access value of dxi / dy at the current Gauss point. double dxidy; /// Access value of dxi / dz at the current Gauss point. double dxidz; /// Access value of deta / dx at the current Gauss point. double detadx; /// Access value of deta / dy at the current Gauss point. double detady; /// Access value of deta / dz at the current Gauss point. double detadz; /// Access value of dzta / dx at the current Gauss point. double dztadx; /// Access value of dzta / dy at the current Gauss point. double dztady; /// Access value of dzta / dz at the current Gauss point. double dztadz; /// Access value of the Gauss weight at the current Gauss point. double wt; /// Access value of the mapping Jacobian. double jac; /// Access value of u at the current Gauss point. double uu; /// Access value of du / dx at the current Gauss point. double dudx; /// Access value of du / dy at the current Gauss point. double dudy; /// Access value of du / dz at the current Gauss point. double dudz; /// Access value of u_old at the current Gauss point. double uuold; /// Access value of du_old / dx at the current Gauss point. double duolddx; /// Access value of du_old / dy at the current Gauss point. double duolddy; /// Access value of du_old / dz at the current Gauss point. double duolddz; /// Access value of u_old_old at the current Gauss point. double uuoldold; /// Access value of du_old_old / dx at the current Gauss point. double duoldolddx; /// Access value of du_old_old / dy at the current Gauss point. double duoldolddy; /// Access value of du_old_old / dz at the current Gauss point. double duoldolddz; /// Access value of x coordinate in real space at the current Gauss point. double xx; /// Access value of y coordinate in real space at the current Gauss point. double yy; /// Access value of z coordinate in real space at the current Gauss point. double zz; /// Access value of the derivative of the basis function wrt to x at the current Gauss point. double dphidx[4]; /// Access value of the derivative of the basis function wrt to y at the current Gauss point. double dphidy[4]; /// Access value of the derivative of the basis function wrt to z at the current Gauss point. double dphidz[4]; //protected: /// Access a pointer to the coordinates of the Gauss points in canonical space. double abscissa[4]; /// Access a pointer to the Gauss weights. double weight[4]; /// Access a pointer to the xi coordinate at each Gauss point. double xi[4]; //double *xi; /// Access a pointer to the eta coordinate at each Gauss point. double eta[4]; /// Access a pointer to the zta coordinate at each Gauss point. double zta[4]; /// Access the number of Gauss weights. double nwt[4]; }; //#define BASIS_NODES_PER_ELEM 27 #define BASIS_NODES_PER_ELEM 8 #define BASIS_NGP_PER_ELEM 64 //#define BASIS_NGP_PER_ELEM 8 #define BASIS_SNGP_PER_ELEM 4 class Unified { public: #ifdef KOKKOS_HAVE_CUDA /** Allocate instances in CPU/GPU unified memory */ void *operator new(size_t len) { void *ptr; cudaMallocManaged(&ptr, len); cudaDeviceSynchronize(); return ptr; } void operator delete(void *ptr) { cudaDeviceSynchronize(); cudaFree(ptr); } /** Allocate all arrays in CPU/GPU unified memory */ void* operator new[] (std::size_t size) { void *ptr; cudaMallocManaged(&ptr,size); cudaDeviceSynchronize(); return ptr; } void operator delete[] (void* ptr) { cudaDeviceSynchronize(); cudaFree(ptr); } #endif }; //class GPUBasis:public Unified{ class GPUBasis{ public: TUSAS_CUDA_CALLABLE_MEMBER GPUBasis(){//printf("GPUBasis()\n"); }; TUSAS_CUDA_CALLABLE_MEMBER virtual ~GPUBasis(){//printf("~GPUBasis()\n"); }; TUSAS_CUDA_CALLABLE_MEMBER virtual double getBasis(const int gp, const double x[BASIS_NODES_PER_ELEM], const double y[BASIS_NODES_PER_ELEM], const double z[BASIS_NODES_PER_ELEM], const double u[BASIS_NODES_PER_ELEM], const double uold[BASIS_NODES_PER_ELEM], const double uoldold[BASIS_NODES_PER_ELEM]) {}; //we could compute and return jac here TUSAS_CUDA_CALLABLE_MEMBER virtual void computeElemData( const double x[BASIS_NODES_PER_ELEM], const double y[BASIS_NODES_PER_ELEM], const double z[BASIS_NODES_PER_ELEM]) {}; /// Access number of Gauss points. KOKKOS_INLINE_FUNCTION const int ngp() const {return ngpp;}; double phi[BASIS_NODES_PER_ELEM]; /// Access value of u at the current Gauss point. double uu; /// Access value of u_old at the current Gauss point. double uuold; /// Access value of du / dx at the current Gauss point. double dudx; /// Access value of du / dy at the current Gauss point. double dudy; /// Access value of the derivative of the basis function wrt to x at the current Gauss point. double dphidx[BASIS_NODES_PER_ELEM]; /// Access value of the derivative of the basis function wrt to y at the current Gauss point. double dphidy[BASIS_NODES_PER_ELEM]; // Variables that are calculated at the gauss point /// Access value of dphi / dzta at the current Gauss point. double dphidzta[BASIS_NODES_PER_ELEM]; /// Access value of du / dz at the current Gauss point. double dudz; /// Access value of du_old / dx at the current Gauss point. double duolddx; /// Access value of du_old / dy at the current Gauss point. double duolddy; /// Access value of du_old / dz at the current Gauss point. double duolddz; /// Access value of u_old_old at the current Gauss point. double uuoldold; /// Access value of du_old_old / dx at the current Gauss point. double duoldolddx; /// Access value of du_old_old / dy at the current Gauss point. double duoldolddy; /// Access value of du_old_old / dz at the current Gauss point. double duoldolddz; /// Access value of x coordinate in real space at the current Gauss point. double xx; /// Access value of y coordinate in real space at the current Gauss point. double yy; /// Access value of z coordinate in real space at the current Gauss point. double zz; /// Access value of the derivative of the basis function wrt to z at the current Gauss point. double dphidz[BASIS_NODES_PER_ELEM]; double phinew[BASIS_NGP_PER_ELEM][BASIS_NODES_PER_ELEM]; double dphidxinew[BASIS_NGP_PER_ELEM][BASIS_NODES_PER_ELEM]; double dphidetanew[BASIS_NGP_PER_ELEM][BASIS_NODES_PER_ELEM]; double dphidztanew[BASIS_NGP_PER_ELEM][BASIS_NODES_PER_ELEM]; /// Access volume of current element. KOKKOS_INLINE_FUNCTION const double vol() const {return volp;}; //we could also do phi[BASIS_NODES_PER_ELEM] and set each element explicity below... //double *phi; //also looks like abscissa[2], wt[2], xi[4],...,nwt[4] //for linear quad. need to change this below //in general probably want abscissa[3] (or more) and xi[3*3*3], etc protected: /// Access a pointer to the coordinates of the Gauss points in canonical space. double abscissa[BASIS_SNGP_PER_ELEM]; /// Access a pointer to the Gauss weights. double weight[BASIS_SNGP_PER_ELEM]; /// Access a pointer to the xi coordinate at each Gauss point. double xi[BASIS_NGP_PER_ELEM]; /// Access a pointer to the eta coordinate at each Gauss point. double eta[BASIS_NGP_PER_ELEM]; /// Access a pointer to the zta coordinate at each Gauss point. double zta[BASIS_NGP_PER_ELEM]; /// Access the number of Gauss weights. double nwt[BASIS_NGP_PER_ELEM]; /// difference in nodal coordinates double nodaldiff[36];//12 for lquad, 36 for lhex double volp; double canonical_vol; /// Access value of the Gauss weight at the current Gauss point. double wt; /// Access value of the mapping Jacobian. double jac; /// Access number of Gauss points. int sngp; int ngpp; /// Access value of dxi / dx at the current Gauss point. double dxidx; /// Access value of dxi / dy at the current Gauss point. double dxidy; /// Access value of dxi / dz at the current Gauss point. double dxidz; /// Access value of deta / dx at the current Gauss point. double detadx; /// Access value of deta / dy at the current Gauss point. double detady; /// Access value of deta / dz at the current Gauss point. double detadz; /// Access value of dzta / dx at the current Gauss point. double dztadx; /// Access value of dzta / dy at the current Gauss point. double dztady; /// Access value of dzta / dz at the current Gauss point. double dztadz; }; //note that quadrature is exact for polynomials of degree 2*sngp - 1 class GPUBasisLQuad:public GPUBasis{ public: TUSAS_CUDA_CALLABLE_MEMBER GPUBasisLQuad(const int n = 2){ canonical_vol = 4.; sngp = n; if( 3 == n){ abscissa[0] = -3.872983346207417/5.0; abscissa[1] = 0.0; abscissa[2] = 3.872983346207417/5.0; weight[0] = 5.0/9.0; weight[1] = 8.0/9.0; weight[2] = 5.0/9.0; } else if ( 4 == n ) { abscissa[0] = -30.13977090579184/35.0; abscissa[1] = -11.89933652546997/35.0; abscissa[2] = 11.89933652546997/35.0; abscissa[3] = 30.13977090579184/35.0; weight[0] = (18.0-5.477225575051661)/36.0; weight[1] = (18.0+5.477225575051661)/36.0; weight[2] = (18.0+5.477225575051661)/36.0; weight[3] = (18.0-5.477225575051661)/36.0; } else { sngp = 2; abscissa[0] = -1.0/1.732050807568877; abscissa[1] = 1.0/1.732050807568877; weight[0] = 1.0; weight[1] = 1.0; } ngpp = sngp*sngp; int c = 0; for( int i = 0; i < sngp; i++ ){ for( int j = 0; j < sngp; j++ ){ //std::cout<<i+j+c<<" "<<i<<" "<<j<<std::endl; xi[i+j+c] = abscissa[i]; eta[i+j+c] = abscissa[j]; nwt[i+j+c] = weight[i] * weight[j]; } c = c + sngp - 1; } for(int gp = 0; gp < ngpp; gp++){ phinew[gp][0]=(1.0-xi[gp])*(1.0-eta[gp])/4.0; phinew[gp][1]=(1.0+xi[gp])*(1.0-eta[gp])/4.0; phinew[gp][2]=(1.0+xi[gp])*(1.0+eta[gp])/4.0; phinew[gp][3]=(1.0-xi[gp])*(1.0+eta[gp])/4.0; dphidxinew[gp][0]=-(1.0-eta[gp])/4.0; dphidxinew[gp][1]= (1.0-eta[gp])/4.0; dphidxinew[gp][2]= (1.0+eta[gp])/4.0; dphidxinew[gp][3]=-(1.0+eta[gp])/4.0; dphidetanew[gp][0]=-(1.0-xi[gp])/4.0; dphidetanew[gp][1]=-(1.0+xi[gp])/4.0; dphidetanew[gp][2]= (1.0+xi[gp])/4.0; dphidetanew[gp][3]= (1.0-xi[gp])/4.0; } } TUSAS_CUDA_CALLABLE_MEMBER ~GPUBasisLQuad(){} TUSAS_CUDA_CALLABLE_MEMBER void computeElemData( const double x[BASIS_NODES_PER_ELEM], const double y[BASIS_NODES_PER_ELEM], const double z[BASIS_NODES_PER_ELEM]) { //std::cout<<"lquad 1"<<std::endl; nodaldiff[0] = x[1]-x[0]; nodaldiff[1] = x[3]-x[0]; nodaldiff[2] = y[1]-y[0]; nodaldiff[3] = y[3]-y[0]; nodaldiff[4] = z[1]-z[0]; nodaldiff[5] = z[3]-z[0]; nodaldiff[6] = x[2]-x[3]; nodaldiff[7] = x[2]-x[1]; nodaldiff[8] = y[2]-y[3]; nodaldiff[9] = y[2]-y[1]; nodaldiff[10] = z[2]-z[3]; nodaldiff[11] = z[2]-z[1]; //std::cout<<"lquad 2"<<std::endl; } TUSAS_CUDA_CALLABLE_MEMBER double getBasis(const int gp, const double x[BASIS_NODES_PER_ELEM], const double y[BASIS_NODES_PER_ELEM], const double z[BASIS_NODES_PER_ELEM], const double u[BASIS_NODES_PER_ELEM], const double uold[BASIS_NODES_PER_ELEM], const double uoldold[BASIS_NODES_PER_ELEM]) { // Calculate basis function and derivatives at nodal pts // phi[0]=(1.0-xi[gp])*(1.0-eta[gp])/4.0; // phi[1]=(1.0+xi[gp])*(1.0-eta[gp])/4.0; // phi[2]=(1.0+xi[gp])*(1.0+eta[gp])/4.0; // phi[3]=(1.0-xi[gp])*(1.0+eta[gp])/4.0; //phi=phinew[gp]; for (int i=0; i < 4; i++) { phi[i]=phinew[gp][i]; } // dphidxi[0]=-(1.0-eta[gp])/4.0; // dphidxi[1]= (1.0-eta[gp])/4.0; // dphidxi[2]= (1.0+eta[gp])/4.0; // dphidxi[3]=-(1.0+eta[gp])/4.0; // dphideta[0]=-(1.0-xi[gp])/4.0; // dphideta[1]=-(1.0+xi[gp])/4.0; // dphideta[2]= (1.0+xi[gp])/4.0; // dphideta[3]= (1.0-xi[gp])/4.0; // Caculate basis function and derivative at GP. //std::cout<<x[0]<<" "<<x[1]<<" "<<x[2]<<" "<<x[3]<<std::endl; // double dxdxi = .25*( (x[1]-x[0])*(1.-eta[gp])+(x[2]-x[3])*(1.+eta[gp]) ); // double dxdeta = .25*( (x[3]-x[0])*(1.- xi[gp])+(x[2]-x[1])*(1.+ xi[gp]) ); // double dydxi = .25*( (y[1]-y[0])*(1.-eta[gp])+(y[2]-y[3])*(1.+eta[gp]) ); // double dydeta = .25*( (y[3]-y[0])*(1.- xi[gp])+(y[2]-y[1])*(1.+ xi[gp]) ); // double dzdxi = .25*( (z[1]-z[0])*(1.-eta[gp])+(z[2]-z[3])*(1.+eta[gp]) ); // double dzdeta = .25*( (z[3]-z[0])*(1.- xi[gp])+(z[2]-z[1])*(1.+ xi[gp]) ); //we could make these protected, ove this jac and volp to computeElemData as an optimization double dxdxi = .25*( (nodaldiff[0])*(1.-eta[gp])+(nodaldiff[6])*(1.+eta[gp]) ); double dxdeta = .25*( (nodaldiff[1])*(1.- xi[gp])+(nodaldiff[7])*(1.+ xi[gp]) ); double dydxi = .25*( (nodaldiff[2])*(1.-eta[gp])+(nodaldiff[8])*(1.+eta[gp]) ); double dydeta = .25*( (nodaldiff[3])*(1.- xi[gp])+(nodaldiff[9])*(1.+ xi[gp]) ); double dzdxi = .25*( (nodaldiff[4])*(1.-eta[gp])+(nodaldiff[10])*(1.+eta[gp]) ); double dzdeta = .25*( (nodaldiff[5])*(1.- xi[gp])+(nodaldiff[11])*(1.+ xi[gp]) ); wt = nwt[gp]; //jac = dxdxi * dydeta - dxdeta * dydxi; jac = sqrt( (dzdxi * dxdeta - dxdxi * dzdeta)*(dzdxi * dxdeta - dxdxi * dzdeta) +(dydxi * dzdeta - dzdxi * dydeta)*(dydxi * dzdeta - dzdxi * dydeta) +(dxdxi * dydeta - dxdeta * dydxi)*(dxdxi * dydeta - dxdeta * dydxi)); volp = jac*canonical_vol; dxidx = dydeta / jac; dxidy = -dxdeta / jac; dxidz = 0.; detadx = -dydxi / jac; detady = dxdxi / jac; detadz =0.; dztadx =0.; dztady =0.; dztadz =0.; // Caculate basis function and derivative at GP. xx=0.0; yy=0.0; zz=0.0; uu=0.0; uuold=0.0; uuoldold=0.0; dudx=0.0; dudy=0.0; dudz=0.0; duolddx = 0.; duolddy = 0.; duolddz = 0.; duoldolddx = 0.; duoldolddy = 0.; duoldolddz = 0.; // x[i] is a vector of node coords, x(j, k) for (int i=0; i < 4; i++) { xx += x[i] * phinew[gp][i]; yy += y[i] * phinew[gp][i]; zz += z[i] * phi[i]; dphidx[i] = dphidxinew[gp][i]*dxidx+dphidetanew[gp][i]*detadx; dphidy[i] = dphidxinew[gp][i]*dxidy+dphidetanew[gp][i]*detady; dphidz[i] = 0.0; dphidzta[i]= 0.0; if( u ){ uu += u[i] * phinew[gp][i]; dudx += u[i] * dphidx[i]; dudy += u[i]* dphidy[i]; } if( uold ){ uuold += uold[i] * phinew[gp][i]; duolddx += uold[i] * dphidx[i]; duolddy += uold[i]* dphidy[i]; } if( uoldold ){ uuoldold += uoldold[i] * phi[i]; duoldolddx += uoldold[i] * dphidx[i]; duoldolddy += uoldold[i]* dphidy[i]; } } return jac*wt; } }; class GPUBasisLHex:public GPUBasis{ public: TUSAS_CUDA_CALLABLE_MEMBER GPUBasisLHex(const int n = 2){ canonical_vol = 8.; sngp = n; if( 3 == n){ abscissa[0] = -3.872983346207417/5.0; abscissa[1] = 0.0; abscissa[2] = 3.872983346207417/5.0; weight[0] = 5.0/9.0; weight[1] = 8.0/9.0; weight[2] = 5.0/9.0; } else if ( 4 == n ) { abscissa[0] = -30.13977090579184/35.0; abscissa[1] = -11.89933652546997/35.0; abscissa[2] = 11.89933652546997/35.0; abscissa[3] = 30.13977090579184/35.0; weight[0] = (18.0-5.477225575051661)/36.0; weight[1] = (18.0+5.477225575051661)/36.0; weight[2] = (18.0+5.477225575051661)/36.0; weight[3] = (18.0-5.477225575051661)/36.0; } else { sngp = 2; abscissa[0] = -1.0/1.732050807568877; abscissa[1] = 1.0/1.732050807568877; weight[0] = 1.0; weight[1] = 1.0; } ngpp = sngp*sngp*sngp; #if 0 xi[0] = abscissa[0]; // 0, 0, 0 eta[0] = abscissa[0]; zta[0] = abscissa[0]; nwt[0] = weight[0] * weight[0] * weight[0]; xi[1] = abscissa[1]; // 1, 0, 0 eta[1] = abscissa[0]; zta[1] = abscissa[0]; nwt[1] = weight[0] * weight[1] * weight[0]; xi[2] = abscissa[1]; // 1, 1, 0 eta[2] = abscissa[1]; zta[2] = abscissa[0]; nwt[2] = weight[1] * weight[1] * weight[0]; xi[3] = abscissa[0]; //0, 1, 0 eta[3] = abscissa[1]; zta[3] = abscissa[0]; nwt[3] = weight[0] * weight[1] * weight[0]; xi[4] = abscissa[0]; // 0, 0, 1 eta[4] = abscissa[0]; zta[4] = abscissa[1]; nwt[4] = weight[0] * weight[0] * weight[1]; xi[5] = abscissa[1]; // 1, 0, 1 eta[5] = abscissa[0]; zta[5] = abscissa[1]; nwt[5] = weight[0] * weight[1] * weight[1]; xi[6] = abscissa[1]; // 1, 1, 1 eta[6] = abscissa[1]; zta[6] = abscissa[1]; nwt[6] = weight[1] * weight[1] * weight[1]; xi[7] = abscissa[0]; //0, 1, 1 eta[7] = abscissa[1]; zta[7] = abscissa[1]; nwt[7] = weight[0] * weight[1] * weight[1]; #endif int c = 0; for( int i = 0; i < sngp; i++ ){ for( int j = 0; j < sngp; j++ ){ for( int k = 0; k < sngp; k++ ){ //std::cout<<i+j+k+c<<" "<<i<<" "<<j<<" "<<k<<std::endl; xi[i+j+k+c] = abscissa[i]; eta[i+j+k+c] = abscissa[j]; zta[i+j+k+c] = abscissa[k]; nwt[i+j+k+c] = weight[i] * weight[j] * weight[k]; } c = c + sngp - 1; } c = c + sngp - 1; } //exit(0); for(int gp = 0; gp < ngpp; gp++){ phinew[gp][0] = 0.125 * (1.0 - xi[gp]) * (1.0 - eta[gp]) * (1.0 - zta[gp]); phinew[gp][1] = 0.125 * (1.0 + xi[gp]) * (1.0 - eta[gp]) * (1.0 - zta[gp]); phinew[gp][2] = 0.125 * (1.0 + xi[gp]) * (1.0 + eta[gp]) * (1.0 - zta[gp]); phinew[gp][3] = 0.125 * (1.0 - xi[gp]) * (1.0 + eta[gp]) * (1.0 - zta[gp]); phinew[gp][4] = 0.125 * (1.0 - xi[gp]) * (1.0 - eta[gp]) * (1.0 + zta[gp]); phinew[gp][5] = 0.125 * (1.0 + xi[gp]) * (1.0 - eta[gp]) * (1.0 + zta[gp]); phinew[gp][6] = 0.125 * (1.0 + xi[gp]) * (1.0 + eta[gp]) * (1.0 + zta[gp]); phinew[gp][7] = 0.125 * (1.0 - xi[gp]) * (1.0 + eta[gp]) * (1.0 + zta[gp]); dphidxinew[gp][0] = -0.125 * (1.0 - eta[gp]) * (1.0 - zta[gp]); dphidxinew[gp][1] = 0.125 * (1.0 - eta[gp]) * (1.0 - zta[gp]); dphidxinew[gp][2] = 0.125 * (1.0 + eta[gp]) * (1.0 - zta[gp]); dphidxinew[gp][3] = -0.125 * (1.0 + eta[gp]) * (1.0 - zta[gp]); dphidxinew[gp][4] = -0.125 * (1.0 - eta[gp]) * (1.0 + zta[gp]); dphidxinew[gp][5] = 0.125 * (1.0 - eta[gp]) * (1.0 + zta[gp]); dphidxinew[gp][6] = 0.125 * (1.0 + eta[gp]) * (1.0 + zta[gp]); dphidxinew[gp][7] = -0.125 * (1.0 + eta[gp]) * (1.0 + zta[gp]); dphidetanew[gp][0] = -0.125 * (1.0 - xi[gp]) * (1.0 - zta[gp]); dphidetanew[gp][1] = -0.125 * (1.0 + xi[gp]) * (1.0 - zta[gp]); dphidetanew[gp][2] = 0.125 * (1.0 + xi[gp]) * (1.0 - zta[gp]); dphidetanew[gp][3] = 0.125 * (1.0 - xi[gp]) * (1.0 - zta[gp]); dphidetanew[gp][4] = -0.125 * (1.0 - xi[gp]) * (1.0 + zta[gp]); dphidetanew[gp][5] = -0.125 * (1.0 + xi[gp]) * (1.0 + zta[gp]); dphidetanew[gp][6] = 0.125 * (1.0 + xi[gp]) * (1.0 + zta[gp]); dphidetanew[gp][7] = 0.125 * (1.0 - xi[gp]) * (1.0 + zta[gp]); dphidztanew[gp][0] = -0.125 * (1.0 - xi[gp]) * (1.0 - eta[gp]); dphidztanew[gp][1] = -0.125 * (1.0 + xi[gp]) * (1.0 - eta[gp]); dphidztanew[gp][2] = -0.125 * (1.0 + xi[gp]) * (1.0 + eta[gp]); dphidztanew[gp][3] = -0.125 * (1.0 - xi[gp]) * (1.0 + eta[gp]); dphidztanew[gp][4] = 0.125 * (1.0 - xi[gp]) * (1.0 - eta[gp]); dphidztanew[gp][5] = 0.125 * (1.0 + xi[gp]) * (1.0 - eta[gp]); dphidztanew[gp][6] = 0.125 * (1.0 + xi[gp]) * (1.0 + eta[gp]); dphidztanew[gp][7] = 0.125 * (1.0 - xi[gp]) * (1.0 + eta[gp]); } //printf("GPUBasisLHex()\n"); } TUSAS_CUDA_CALLABLE_MEMBER ~GPUBasisLHex(){//printf("~GPUBasisLHex()\n"); } TUSAS_CUDA_CALLABLE_MEMBER void computeElemData( const double x[BASIS_NODES_PER_ELEM], const double y[BASIS_NODES_PER_ELEM], const double z[BASIS_NODES_PER_ELEM]) { nodaldiff[0] = x[1]-x[0]; nodaldiff[1] = x[3]-x[0]; nodaldiff[2] = x[4]-x[0]; nodaldiff[3] = y[1]-y[0]; nodaldiff[4] = y[3]-y[0]; nodaldiff[5] = y[4]-y[0]; nodaldiff[6] = z[1]-z[0]; nodaldiff[7] = z[3]-z[0]; nodaldiff[8] = z[4]-z[0]; nodaldiff[9] = x[2]-x[3]; nodaldiff[10] = x[2]-x[1]; nodaldiff[11] = x[5]-x[1]; nodaldiff[12] = y[2]-y[3]; nodaldiff[13] = y[2]-y[1]; nodaldiff[14] = y[5]-y[1]; nodaldiff[15] = z[2]-z[3]; nodaldiff[16] = z[2]-z[1]; nodaldiff[17] = z[5]-z[1]; nodaldiff[18] = x[5]-x[4]; nodaldiff[19] = x[7]-x[4]; nodaldiff[20] = x[6]-x[2]; nodaldiff[21] = y[5]-y[4]; nodaldiff[22] = y[7]-y[4]; nodaldiff[23] = y[6]-y[2]; nodaldiff[24] = z[5]-z[4]; nodaldiff[25] = z[7]-z[4]; nodaldiff[26] = z[6]-z[2]; nodaldiff[27] = x[6]-x[7]; nodaldiff[28] = x[6]-x[5]; nodaldiff[29] = x[7]-x[3]; nodaldiff[30] = y[6]-y[7]; nodaldiff[31] = y[6]-y[5]; nodaldiff[32] = y[7]-y[3]; nodaldiff[33] = z[6]-z[7]; nodaldiff[34] = z[6]-z[5]; nodaldiff[35] = z[7]-z[3]; //std::cout<<"lhex"<<std::endl; } TUSAS_CUDA_CALLABLE_MEMBER virtual double getBasis(const int gp, const double x[BASIS_NODES_PER_ELEM], const double y[BASIS_NODES_PER_ELEM], const double z[BASIS_NODES_PER_ELEM], const double u[BASIS_NODES_PER_ELEM], const double uold[BASIS_NODES_PER_ELEM], const double uoldold[BASIS_NODES_PER_ELEM]) { for (int i=0; i < 8; i++) { phi[i]=phinew[gp][i]; } // Caculate basis function and derivative at GP. // double dxdxi = 0.125*( (x[1]-x[0])*(1.-eta[gp])*(1.-zta[gp]) + (x[2]-x[3])*(1.+eta[gp])*(1.-zta[gp]) // + (x[5]-x[4])*(1.-eta[gp])*(1.+zta[gp]) + (x[6]-x[7])*(1.+eta[gp])*(1.+zta[gp]) ); // double dxdeta = 0.125*( (x[3]-x[0])*(1.- xi[gp])*(1.-zta[gp]) + (x[2]-x[1])*(1.+ xi[gp])*(1.-zta[gp]) // + (x[7]-x[4])*(1.- xi[gp])*(1.+zta[gp]) + (x[6]-x[5])*(1.+ xi[gp])*(1.+zta[gp]) ); // double dxdzta = 0.125*( (x[4]-x[0])*(1.- xi[gp])*(1.-eta[gp]) + (x[5]-x[1])*(1.+ xi[gp])*(1.-eta[gp]) // + (x[6]-x[2])*(1.+ xi[gp])*(1.+eta[gp]) + (x[7]-x[3])*(1.- xi[gp])*(1.+eta[gp]) ); // double dydxi = 0.125*( (y[1]-y[0])*(1.-eta[gp])*(1.-zta[gp]) + (y[2]-y[3])*(1.+eta[gp])*(1.-zta[gp]) // + (y[5]-y[4])*(1.-eta[gp])*(1.+zta[gp]) + (y[6]-y[7])*(1.+eta[gp])*(1.+zta[gp]) ); // double dydeta = 0.125*( (y[3]-y[0])*(1.- xi[gp])*(1.-zta[gp]) + (y[2]-y[1])*(1.+ xi[gp])*(1.-zta[gp]) // + (y[7]-y[4])*(1.- xi[gp])*(1.+zta[gp]) + (y[6]-y[5])*(1.+ xi[gp])*(1.+zta[gp]) ); // double dydzta = 0.125*( (y[4]-y[0])*(1.- xi[gp])*(1.-eta[gp]) + (y[5]-y[1])*(1.+ xi[gp])*(1.-eta[gp]) // + (y[6]-y[2])*(1.+ xi[gp])*(1.+eta[gp]) + (y[7]-y[3])*(1.- xi[gp])*(1.+eta[gp]) ); // double dzdxi = 0.125*( (z[1]-z[0])*(1.-eta[gp])*(1.-zta[gp]) + (z[2]-z[3])*(1.+eta[gp])*(1.-zta[gp]) // + (z[5]-z[4])*(1.-eta[gp])*(1.+zta[gp]) + (z[6]-z[7])*(1.+eta[gp])*(1.+zta[gp]) ); // double dzdeta = 0.125*( (z[3]-z[0])*(1.- xi[gp])*(1.-zta[gp]) + (z[2]-z[1])*(1.+ xi[gp])*(1.-zta[gp]) // + (z[7]-z[4])*(1.- xi[gp])*(1.+zta[gp]) + (z[6]-z[5])*(1.+ xi[gp])*(1.+zta[gp]) ); // double dzdzta = 0.125*( (z[4]-z[0])*(1.- xi[gp])*(1.-eta[gp]) + (z[5]-z[1])*(1.+ xi[gp])*(1.-eta[gp]) // + (z[6]-z[2])*(1.+ xi[gp])*(1.+eta[gp]) + (z[7]-z[3])*(1.- xi[gp])*(1.+eta[gp]) ); double dxdxi = 0.125*( (nodaldiff[0])*(1.-eta[gp])*(1.-zta[gp]) + (nodaldiff[9])*(1.+eta[gp])*(1.-zta[gp]) + (nodaldiff[18])*(1.-eta[gp])*(1.+zta[gp]) + (nodaldiff[27])*(1.+eta[gp])*(1.+zta[gp]) ); double dxdeta = 0.125*( (nodaldiff[1])*(1.- xi[gp])*(1.-zta[gp]) + (nodaldiff[10])*(1.+ xi[gp])*(1.-zta[gp]) + (nodaldiff[19])*(1.- xi[gp])*(1.+zta[gp]) + (nodaldiff[28])*(1.+ xi[gp])*(1.+zta[gp]) ); double dxdzta = 0.125*( (nodaldiff[2])*(1.- xi[gp])*(1.-eta[gp]) + (nodaldiff[11])*(1.+ xi[gp])*(1.-eta[gp]) + (nodaldiff[20])*(1.+ xi[gp])*(1.+eta[gp]) + (nodaldiff[29])*(1.- xi[gp])*(1.+eta[gp]) ); double dydxi = 0.125*( (nodaldiff[3])*(1.-eta[gp])*(1.-zta[gp]) + (nodaldiff[12])*(1.+eta[gp])*(1.-zta[gp]) + (nodaldiff[21])*(1.-eta[gp])*(1.+zta[gp]) + (nodaldiff[30])*(1.+eta[gp])*(1.+zta[gp]) ); double dydeta = 0.125*( (nodaldiff[4])*(1.- xi[gp])*(1.-zta[gp]) + (nodaldiff[13])*(1.+ xi[gp])*(1.-zta[gp]) + (nodaldiff[22])*(1.- xi[gp])*(1.+zta[gp]) + (nodaldiff[31])*(1.+ xi[gp])*(1.+zta[gp]) ); double dydzta = 0.125*( (nodaldiff[5])*(1.- xi[gp])*(1.-eta[gp]) + (nodaldiff[14])*(1.+ xi[gp])*(1.-eta[gp]) + (nodaldiff[23])*(1.+ xi[gp])*(1.+eta[gp]) + (nodaldiff[32])*(1.- xi[gp])*(1.+eta[gp]) ); double dzdxi = 0.125*( (nodaldiff[6])*(1.-eta[gp])*(1.-zta[gp]) + (nodaldiff[15])*(1.+eta[gp])*(1.-zta[gp]) + (nodaldiff[24])*(1.-eta[gp])*(1.+zta[gp]) + (nodaldiff[33])*(1.+eta[gp])*(1.+zta[gp]) ); double dzdeta = 0.125*( (nodaldiff[7])*(1.- xi[gp])*(1.-zta[gp]) + (nodaldiff[16])*(1.+ xi[gp])*(1.-zta[gp]) + (nodaldiff[25])*(1.- xi[gp])*(1.+zta[gp]) + (nodaldiff[34])*(1.+ xi[gp])*(1.+zta[gp]) ); double dzdzta = 0.125*( (nodaldiff[8])*(1.- xi[gp])*(1.-eta[gp]) + (nodaldiff[17])*(1.+ xi[gp])*(1.-eta[gp]) + (nodaldiff[26])*(1.+ xi[gp])*(1.+eta[gp]) + (nodaldiff[35])*(1.- xi[gp])*(1.+eta[gp]) ); wt = nwt[gp]; jac = dxdxi*(dydeta*dzdzta - dydzta*dzdeta) - dxdeta*(dydxi*dzdzta - dydzta*dzdxi) + dxdzta*(dydxi*dzdeta - dydeta*dzdxi); //std::cout<<jac<<" "<<wt<<" "<<gp<<std::endl; volp = jac*canonical_vol; dxidx = (-dydzta*dzdeta + dydeta*dzdzta) / jac; dxidy = ( dxdzta*dzdeta - dxdeta*dzdzta) / jac; dxidz = (-dxdzta*dydeta + dxdeta*dydzta) / jac; detadx = ( dydzta*dzdxi - dydxi*dzdzta) / jac; detady = (-dxdzta*dzdxi + dxdxi*dzdzta) / jac; detadz = ( dxdzta*dydxi - dxdxi*dydzta) / jac; dztadx = ( dydxi*dzdeta - dydeta*dzdxi) / jac; dztady = (-dxdxi*dzdeta + dxdeta*dzdxi) / jac; dztadz = ( dxdxi*dydeta - dxdeta*dydxi) / jac; // Caculate basis function and derivative at GP. xx=0.0; yy=0.0; zz=0.0; uu=0.0; uuold=0.0; uuoldold=0.0; dudx=0.0; dudy=0.0; dudz=0.0; duolddx = 0.; duolddy = 0.; duolddz = 0.; duoldolddx = 0.; duoldolddy = 0.; duoldolddz = 0.; // x[i] is a vector of node coords, x(j, k) for (int i=0; i < 8; i++) { xx += x[i] * phinew[gp][i]; yy += y[i] * phinew[gp][i]; zz += z[i] * phinew[gp][i]; dphidx[i] = dphidxinew[gp][i]*dxidx+dphidetanew[gp][i]*detadx+dphidztanew[gp][i]*dztadx; dphidy[i] = dphidxinew[gp][i]*dxidy+dphidetanew[gp][i]*detady+dphidztanew[gp][i]*dztady; dphidz[i] = dphidxinew[gp][i]*dxidz+dphidetanew[gp][i]*detadz+dphidztanew[gp][i]*dztadz; if( u ){ uu += u[i] * phinew[gp][i]; dudx += u[i] * dphidx[i]; dudy += u[i] * dphidy[i]; dudz += u[i] * dphidz[i]; } if( uold ){ uuold += uold[i] * phinew[gp][i]; duolddx += uold[i] * dphidx[i]; duolddy += uold[i] * dphidy[i]; duolddz += uold[i] * dphidz[i]; //exit(0); } if( uoldold ){ uuoldold += uoldold[i] * phinew[gp][i]; duoldolddx += uoldold[i] * dphidx[i]; duoldolddy += uoldold[i] * dphidy[i]; duoldolddz += uoldold[i] * dphidz[i]; } } return jac*wt; } }; #endif
/**************************************************************************** ** Copyright (c) 2006 - 2011, the LibQxt project. ** See the Qxt AUTHORS file for a list of authors and copyright holders. ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** * Neither the name of the LibQxt project nor the ** names of its contributors may be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED ** WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE ** DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY ** DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ** (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; ** LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ** ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ** <http://libqxt.org> <foundation@libqxt.org> *****************************************************************************/ /*! \class QxtFifo \inmodule QxtCore \brief The QxtFifo class provides a simple loopback QIODevice. read and write to the same object emits a readyRead Signal. useful for loopback tests where QBuffer does not work. \code QxtFifo fifo; QTextStream (&fifo)<<QString("foo"); QString a; QTextStream(&fifo)>>a; qDebug()<<a; \endcode */ #include "qxtfifo.h" #include <string.h> #include <limits.h> #include <QDebug> #include <QQueue> #include <qatomic.h> #if QT_VERSION >= 0x50000 # define QXT_EXCHANGE(x) fetchAndStoreOrdered(x) # define QXT_EXCHANGE_(x) fetchAndStoreOrdered(x.load()) # define QXT_ADD fetchAndAddOrdered #elif QT_VERSION >= 0x040400 # include <qbasicatomic.h> # define QXT_EXCHANGE fetchAndStoreOrdered # define QXT_EXCHANGE_ QXT_EXCHANGE # define QXT_ADD fetchAndAddOrdered #else typedef QBasicAtomic QBasicAtomicInt; # define QXT_EXCHANGE exchange # define QXT_EXCHANGE_ QXT_EXCHANGE # define QXT_ADD fetchAndAdd #endif struct QxtFifoNode { QxtFifoNode(const char* data, int size) : content(data, size) { #if QT_VERSION >= 0x50000 next.store(0); #else next = NULL; #endif } QxtFifoNode(const QByteArray &data) : content(data) { #if QT_VERSION >= 0x50000 next.store(0); #else next = NULL; #endif } QByteArray content; QBasicAtomicPointer<QxtFifoNode> next; }; class QxtFifoPrivate : public QxtPrivate<QxtFifo> { public: QXT_DECLARE_PUBLIC(QxtFifo) QxtFifoPrivate() { QxtFifoNode *n = new QxtFifoNode(NULL, 0); #if QT_VERSION >= 0x50000 head.store(n); tail.store(n); #else head = n; tail = n; #endif #if QT_VERSION >= 0x50000 available.store(0); #else available = 0; #endif } QBasicAtomicPointer<QxtFifoNode> head, tail; QBasicAtomicInt available; }; /*! Constructs a new QxtFifo with \a parent. */ QxtFifo::QxtFifo(QObject *parent) : QIODevice(parent) { QXT_INIT_PRIVATE(QxtFifo); setOpenMode(QIODevice::ReadWrite); } /*! Constructs a new QxtFifo with \a parent and initial content from \a prime. */ QxtFifo::QxtFifo(const QByteArray &prime, QObject *parent) : QIODevice(parent) { QXT_INIT_PRIVATE(QxtFifo); setOpenMode(QIODevice::ReadWrite); // Since we're being constructed, access to the internals is safe QxtFifoNode* node; #if QT_VERSION >= 0x50000 node = qxt_d().head.load(); #else node = qxt_d().head; #endif node->content = prime; qxt_d().available.QXT_ADD( prime.size() ); } /*! \reimp */ qint64 QxtFifo::readData ( char * data, qint64 maxSize ) { int bytes, step; #if QT_VERSION >= 0x50000 bytes = qxt_d().available.load(); #else bytes = qxt_d().available; #endif if(!bytes) return 0; if(bytes > maxSize) bytes = maxSize; int written = bytes; char* writePos = data; QxtFifoNode* node; while(bytes > 0) { #if QT_VERSION >= 0x50000 node = qxt_d().head.load(); #else node = qxt_d().head; #endif step = node->content.size(); if(step >= bytes) { int rem = step - bytes; memcpy(writePos, node->content.constData(), bytes); step = bytes; node->content = node->content.right(rem); } else { memcpy(writePos, node->content.constData(), step); qxt_d().head.QXT_EXCHANGE_(node->next); delete node; #if QT_VERSION >= 0x50000 node = qxt_d().head.load(); #else node = qxt_d().head; #endif } writePos += step; bytes -= step; } qxt_d().available.QXT_ADD(-written); return written; } /*! \reimp */ qint64 QxtFifo::writeData ( const char * data, qint64 maxSize ) { if(maxSize > 0) { if(maxSize > INT_MAX) maxSize = INT_MAX; // qint64 could easily exceed QAtomicInt, so let's play it safe QxtFifoNode* newData = new QxtFifoNode(data, maxSize); #if QT_VERSION >= 0x50000 qxt_d().tail.load()->next.QXT_EXCHANGE(newData); #else qxt_d().tail->next.QXT_EXCHANGE(newData); #endif qxt_d().tail.QXT_EXCHANGE(newData); qxt_d().available.QXT_ADD(maxSize); QMetaObject::invokeMethod(this, "bytesWritten", Qt::QueuedConnection, Q_ARG(qint64, maxSize)); QMetaObject::invokeMethod(this, "readyRead", Qt::QueuedConnection); } return maxSize; } /*! \reimp */ bool QxtFifo::isSequential () const { return true; } /*! \reimp */ qint64 QxtFifo::bytesAvailable () const { #if QT_VERSION >= 0x50000 return qxt_d().available.load() + QIODevice::bytesAvailable(); #else return qxt_d().available + QIODevice::bytesAvailable(); #endif } /*! */ void QxtFifo::clear() { qxt_d().available.QXT_EXCHANGE(0); qxt_d().tail.QXT_EXCHANGE_(qxt_d().head); #if QT_VERSION >= 0x50000 QxtFifoNode* node = qxt_d().head.load()->next.QXT_EXCHANGE(NULL); #else QxtFifoNode* node = qxt_d().head->next.QXT_EXCHANGE(NULL); #endif #if QT_VERSION >= 0x50000 while (node && node->next.load()) #else while (node && node->next) #endif { QxtFifoNode* next = node->next.QXT_EXCHANGE(NULL); delete node; node = next; } #if QT_VERSION >= 0x50000 qxt_d().head.load()->content = QByteArray(); #else qxt_d().head->content = QByteArray(); #endif }
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: bool isPalindrome(ListNode* head) { /* O(n) time O(n) space vector<int> vec; while(head) { vec.push_back(head->val); head = head->next; } for(int i = 0; i < vec.size()/2; i++) { if(vec[i] != vec[vec.size() - i - 1]) return false; } return true; */ // O(n) time O(1) space ListNode* mid = findMid(head); //ListNode* head2 = reverse(mid); ListNode* head2 = reverseInIterative(mid); while(head2) { if(head->val != head2->val) return false; head = head->next; head2 = head2->next; } return true; } ListNode* findMid(ListNode* head) { ListNode* fast = head; ListNode* slow = head; while(fast) { fast = fast->next; slow = slow->next; if(fast == NULL) break; fast = fast->next; } return slow; } ListNode* reverse(ListNode* cur) { if(cur == NULL || cur->next == NULL) return cur; ListNode* tail = reverse(cur->next); cur->next->next = cur; cur->next = NULL; return tail; } ListNode* reverseInIterative(ListNode* head) { if(head == NULL || head->next == NULL) return head; ListNode* pre = NULL; while(head) { ListNode* cur = head; head = head->next; cur->next = pre; pre = cur; } return pre; } };
void setup() { P1DIR |= BIT6; // P1.6 to output CCR0 = 65536-1; // PWM Period CCTL1 = OUTMOD_7; // CCR1 reset/set CCR1 = 100; // CCR1 PWM duty cycle TACTL = TASSEL_2 + MC_1 + ID_3; // SMCLK, up mode, divide clock by 8 CCTL0 = CCIE; //Enable timer interrupts _BIS_SR(LPM0_bits); // Enter LPM0 } void loop() { //Don't do anything here...we are waiting for interrupts! } #pragma vector=TIMER0_A0_VECTOR //These two lines say this is an ISR __interrupt void Timer_A(void) { //cont. P1OUT ^= BIT6; //Toggle pin 1.0 }
#include <gtest/gtest.h> #include "Nodes/MultipleInputLayerNodes/PassThroughMultipleInputLayerNode.hpp" struct PassThroughMultipleInputLayerNodeTest : testing::Test { }; struct CustomComputationNode : ComputationNode<float> { CustomComputationNode(float v) : output(v) {} ArrayView<float const> getOutputValues() const override { return output; } std::size_t getNumOutputs() const override { return 1; } void backPropagate(ArrayView<float const> v) override { std::cout << "propagated error " << v[0] << std::endl; } void backPropagationPass() override { std::cout << "backPropagationPass " << std::endl; } float output; }; TEST_F(PassThroughMultipleInputLayerNodeTest, PassThroughTest) { CustomComputationNode first{5}, second{7}; std::vector<NotNull<ComputationNode<float>>> inputs = { &first, &second }; PassThroughMultipleInputLayerNode<float> sut{inputs}; sut.forwardPass(); EXPECT_EQ(sut.getOutputValues()[0], first.output); EXPECT_EQ(sut.getOutputValues()[1], second.output); std::vector<float> errors = { 1, 2 }; sut.backPropagate(errors); }
#pragma once #include <EventType.h> #include <string> namespace breakout { enum struct EGameState { IDLE, MAIN_MENU, GAME, PAUSE, CLOSE_APP, GAME_OVER, GAME_WIN, }; class GameStateChangeEvent : public BaseEvent { public: EGameState mPrevState; EGameState mNewState; GameStateChangeEvent(EEventType eventType, EGameState prevState, EGameState newState) : BaseEvent::BaseEvent(eventType) , mPrevState(prevState) , mNewState(newState) {}; ~GameStateChangeEvent() {}; }; class GameStateManager { public: static GameStateManager& Get(); void Init(); void SwitchState(EGameState newState); EGameState GetCurrentState() const; static std::string ConvertGameStateToString(EGameState gameState); protected: bool IsPossibleToChangeState(EGameState newState) const; private: GameStateManager(); ~GameStateManager(); GameStateManager(GameStateManager&) = delete; GameStateManager(GameStateManager&&) = delete; void operator=(GameStateManager&) = delete; void operator=(GameStateManager&&) = delete; EGameState m_currentState = EGameState::MAIN_MENU; }; }
#pragma once #include <stdint.h> /* specify the precalcuated tables */ #define TABLES_320 #define SCREEN_WIDTH (uint16_t) 320 #define SCREEN_HEIGHT (uint16_t) 256 #define SCREEN_SCALE 2 #define FOV (double) (M_PI / 2) #define INV_FACTOR (float) (SCREEN_WIDTH * 95.0f / 320.0f) #define LOOKUP_TBL #define LOOKUP8(tbl, offset) tbl[offset] #define LOOKUP16(tbl, offset) tbl[offset] #define MAP_X (uint8_t) 32 #define MAP_XS (uint8_t) 5 #define MAP_Y (uint8_t) 32 #define INV_FACTOR_INT ((uint16_t)(SCREEN_WIDTH * 75)) #define MIN_DIST (int) ((150 * ((float) SCREEN_WIDTH / (float) SCREEN_HEIGHT))) #define HORIZON_HEIGHT (SCREEN_HEIGHT / 2) #define INVERT(x) (uint8_t)((x ^ 255) + 1) #define ABS(x) (x < 0 ? -x : x) class RayCaster { public: virtual void Start(uint16_t playerX, uint16_t playerY, int16_t playerA) = 0; virtual void Trace(uint16_t screenX, uint8_t *screenY, uint8_t *textureNo, uint8_t *textureX, uint16_t *textureY, uint16_t *textureStep) = 0; RayCaster(){}; ~RayCaster(){}; };
#include "colormodel2d.h" #include "render/mesh.h" void ColorModel2D::addData(const AbstractMesh &mesh) { auto colorMesh = dynamic_cast<const ColorMesh &>(mesh); genVAO(); addVBO(2, colorMesh.vertexPositions); addVBO(4, colorMesh.vertexColors); addEBO(colorMesh.indices); }
#include <assert.h> #include "Cell.h" namespace Minesweeper { bool Cell::isVisible() const { return this->_isVisible; } bool Cell::hasMine() const { return this->_hasMine; } bool Cell::isMarked() const { return this->_isMarked; } int Cell::numOfMinesAround() const { return this->_numOfMinesAround; } void Cell::incrNumOfMinesAround() { ++(this->_numOfMinesAround); assert(this->_numOfMinesAround >= 0 && this->_numOfMinesAround < 9); } void Cell::makeVisible() { this->_isVisible = true; } void Cell::putMine() { this->_hasMine = true; } void Cell::markCell() { assert(this->_isMarked != true); this->_isMarked = true; } void Cell::unmarkCell() { assert(this->_isMarked != false); this->_isMarked = false; } }
#include <lwr4p_bhand_test/utils.h> double err_thres = 1e-2; void PRINT_INFO_MSG(const std::string &msg) { std::cerr << "\033[1m\033[34m" << "[INFO]: " << msg << "\033[0m\n"; } void PRINT_ERR_MSG(const std::string &msg) { std::cerr << "\033[1m\033[31m" << "[ERROR]: " << msg << "\033[0m\n"; } void lwrRobotRun(LwrExecArgs *args) { arma::vec q1 = args->q1; arma::vec q2 = args->q2; double total_time = args->total_time; lwr4p_::RobotArm *robot = args->robot; const bool *run = args->run; arma::vec qT; // ====================================================== // =========== Set Joints trajectory ================= // ====================================================== std::cerr << "=====================================\n"; PRINT_INFO_MSG("==> Moving with Joints Trajectory..."); qT = q1; bool reached_target = robot->setJointsTrajectory(qT, total_time); if (reached_target) PRINT_INFO_MSG("==> Reached target pose!"); else PRINT_ERR_MSG("==> Failed to reach target pose!\n"); if (!robot->isOk()) { PRINT_ERR_MSG("==> " + robot->getErrMsg()); robot->enable(); } std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // ====================================================== // =========== Joint Position Control ================ // ====================================================== std::cerr << "=====================================\n"; PRINT_INFO_MSG("==> Setting the robot to JOINT_POS_CONTROL..."); robot->setMode(lwr4p_::JOINT_POS_CONTROL); PRINT_INFO_MSG("==> Moving with joint position control..."); robot->update(); double Ts = robot->getCtrlCycle(); arma::vec q = robot->getJointsPosition(); arma::vec q0 = q; double t = 0; qT = q2; while (arma::norm(qT-q)>err_thres && robot->isOk()) { if (!(*run)) exit(-1); t += Ts; arma::vec q_ref = lwr4p_::get5thOrder(t, q0, qT, total_time)[0]; robot->setJointsPosition(q_ref); robot->update(); q = robot->getJointsPosition(); } if (!robot->isOk()) { PRINT_ERR_MSG("[ERROR]: " + robot->getErrMsg()); robot->enable(); } else PRINT_INFO_MSG("==> Reached target pose!"); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // ========================================= // =========== FREEDIRVE ================ // ========================================= std::cerr << "=====================================\n"; PRINT_INFO_MSG("==> Setting the robot to FREEDRIVE..."); robot->setMode(lwr4p_::FREEDRIVE); PRINT_INFO_MSG("==> The robot is in FREEDIRVE. Move it wherever you want. Press ctrl+C to exit..."); while ((*run) && robot->isOk()) { robot->update(); } if (!robot->isOk()) { PRINT_INFO_MSG("[ERROR]: " + robot->getErrMsg()); robot->enable(); } } void bhRobotRun(BhExecArgs *args) { arma::vec q1 = args->q1; arma::vec q2 = args->q2; double total_time = args->total_time; bhand_::RobotHand *robot = args->robot; const bool *run = args->run; arma::vec qT; // ====================================================== // =========== Set Joints trajectory ================= // ====================================================== std::cerr << "=====================================\n"; PRINT_INFO_MSG("==> Moving with Joints Trajectory..."); qT = q1; bool reached_target = robot->setJointsTrajectory(qT, total_time); if (reached_target) PRINT_INFO_MSG("==> Reached target pose!"); else PRINT_ERR_MSG("==> Failed to reach target pose!\n"); if (!robot->isOk()) { PRINT_ERR_MSG("==> " + robot->getErrMsg()); robot->enable(); } std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // ====================================================== // =========== Joint Position Control ================ // ====================================================== std::cerr << "=====================================\n"; PRINT_INFO_MSG("==> Setting the robot to JOINT_POS_CONTROL..."); robot->setMode(bhand_::JOINT_POS_CONTROL); PRINT_INFO_MSG("==> Moving with joint position control..."); robot->update(); double Ts = robot->getCtrlCycle(); arma::vec q = robot->getJointsPosition(); arma::vec q0 = q; double t = 0; qT = q2; while (arma::norm(qT-q)>err_thres && robot->isOk()) { if (!(*run)) exit(-1); t += Ts; arma::vec q_ref = bhand_::get5thOrder(t, q0, qT, total_time)[0]; robot->setJointsPosition(q_ref); robot->update(); q = robot->getJointsPosition(); } if (!robot->isOk()) { PRINT_ERR_MSG("[ERROR]: " + robot->getErrMsg()); robot->enable(); } else PRINT_INFO_MSG("==> Reached target pose!"); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // ====================================================== // =========== Joint Velocity Control ================ // ====================================================== std::cerr << "=====================================\n"; PRINT_INFO_MSG("==> Setting the robot to JOINT_VEL_CONTROL..."); robot->setMode(bhand_::JOINT_VEL_CONTROL); PRINT_INFO_MSG("==> Moving with joint velocity control..."); robot->update(); q = robot->getJointsPosition(); q0 = q; double k_click = 0.1; t = 0; qT = q1; while (arma::norm(qT-q)>err_thres && robot->isOk()) { if (!ros::ok()) exit(-1); t += Ts; arma::vec q_ref = bhand_::get5thOrder(t, q0, qT, total_time)[0]; arma::vec dq_ref = bhand_::get5thOrder(t, q0, qT, total_time)[1]; robot->setJointsVelocity(dq_ref + k_click*(q_ref-q)); robot->update(); q = robot->getJointsPosition(); } if (!robot->isOk()) { PRINT_ERR_MSG("[ERROR]: " + robot->getErrMsg()); robot->enable(); } else PRINT_INFO_MSG("==> Reached target pose!"); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); // ========================================= // =========== FREEDIRVE ================ // ========================================= std::cerr << "=====================================\n"; PRINT_INFO_MSG("==> Setting the robot to FREEDRIVE..."); robot->setMode(bhand_::FREEDRIVE); PRINT_INFO_MSG("==> The robot is in FREEDIRVE. Move it wherever you want. Press ctrl+C to exit..."); while ((*run) && robot->isOk()) { robot->update(); } if (!robot->isOk()) { PRINT_INFO_MSG("[ERROR]: " + robot->getErrMsg()); robot->enable(); } }
#include <iostream> #include <algorithm> #include <cstdio> #include <cstdlib> #include <ctime> #include <memory.h> #include <cmath> #include <string> #include <cstring> #include <queue> #include <vector> #include <set> #include <deque> #include <map> #include <functional> #include <numeric> #include <sstream> #include <complex> #include <cassert> typedef long double LD; typedef long long LL; typedef unsigned long long ULL; typedef unsigned int uint; #define PI 3.1415926535897932384626433832795 #define sqr(x) ((x)*(x)) using namespace std; struct Tp { int x; char y; } a[111111]; int main() { // freopen(".in", "r", stdin); // freopen(".out", "w", stdout); int T; scanf("%d", &T); while (T--) { int n; scanf("%d\n", &n); LL cnt[2] = {0, 0}; for (int i = 0; i < n; ++i) { scanf("%d %c\n", &a[i].x, &a[i].y); cnt[a[i].y == 'B'] += a[i].x; } if (cnt[0] == 0 || cnt[1] == 0) { cout << cnt[0] + cnt[1] << "\n"; continue; } LL c[2] = {0, 0}; int ans = 1; LL total = 0; for (int i = 0; i < n; ++i) { int col = (a[i].y == 'B'); if ( (cnt[col] * c[1 - col]) % cnt[1 - col] == 0 ) { LL x = cnt[col] * c[1 - col] / cnt[1 - col] - c[col]; if (x >= 0 && x < a[i].x && total + x > 0) { ++ans; a[i].x -= x; c[0] = c[1] = 0; total = 0; } } c[col] += a[i].x; total += a[i].x; } printf("%d\n", ans); } return 0; }
#include <iostream> #include <string> #include <vector> #include <map> #include "Checker.h" using namespace std; Checker :: Checker(){} Checker :: Checker(map<string, int> Dic){ Dictionary = Dic; } void Checker :: setDictionary(map<string, int> Dic){ Dictionary = Dic; } void Checker::functionAlteration(string word){ string letters = "abcdefghijklmnopqrstuvwxyz"; string temp; for(int i=0; i<word.length(); i++) { for(int j=0; j<26; j++) { temp = word; temp[i] = letters[j]; if(Dictionary[temp]>0) { this->Matches.push_back(temp); } } } } void Checker::functionDeletion(string word){ string a = word; int w = a.length(); string s[w]; for (int i=0; i<w; i++) { s[i]=a[i]; } for (int i=0; i<w; i++) { for (int i=0; i<w; i++) { s[i]=a[i]; } s[i] = ""; string ConcatWord=""; for (int o=0; o<w; o++) { ConcatWord += s[o]; } if(Dictionary[ConcatWord]>0) { this->Matches.push_back(ConcatWord); } } } void Checker::functionInsertion(string word){ string letters = "abcdefghijklmnopqrstuvwxyz"; int word_size = word.size(); int i = 0; string w; for(int j=0; j<=word_size; j++) { int length1 = j; int length2 = word_size-j; for(int x=0; x<letters.size(); x++) { w = word.substr(0, length1)+letters[x]+word.substr(j, length2); if(Dictionary[w]>0) { this->Matches.push_back(w); } i++; } } } void Checker :: functionTransposition(string word){ string a = word; int lw; lw = a.length(); string s[lw]; for (int i=0; i<lw; i++) { s[i]=a[i]; } string temp; for (int j=0; j<(lw-1); j++) { temp = s[j]; s[j] = s[j+1]; s[j+1] = temp; string ConcatWord=""; for (int o=0; o<lw; o++) { ConcatWord += s[o]; } if(Dictionary[ConcatWord]>0) { this->Matches.push_back(ConcatWord); } for (int i=0; i<lw; i++) { s[i]=a[i]; } } } vector<string> Checker :: getMatches(string word){ Matches.clear(); if(Dictionary[word] > 0) { Matches.push_back(word); Checker :: wordWithHighestOccurence(); Checker::functionAlteration(word); Checker::functionDeletion(word); Checker::functionInsertion(word); Checker::functionTransposition(word); } else { Checker::functionAlteration(word); Checker::functionDeletion(word); Checker::functionInsertion(word); Checker::functionTransposition(word); if(Matches.size() == 0) Matches.push_back(" [INVALID WORD]"); Checker :: wordWithHighestOccurence(); } return Matches; } string Checker :: wordWithHighestOccurence() { int PrevCount = 0; string ApparentPerfectMatch; ApparentPerfectMatch = this->Matches.at(0); map<string, int>::iterator it; for (it = Dictionary.begin(); it != Dictionary.end(); it++) { if (ApparentPerfectMatch == it->first) { PrevCount = it ->second; } } for (int i = 0; i<Matches.size() ;i++) { for (it = Dictionary.begin(); it != Dictionary.end(); it++) { if (sizeof(this->Matches.at(i)) == sizeof(it->first)) { if(it->first == (this->Matches.at(i)) ) { if (it->second > PrevCount) { ApparentPerfectMatch = this->Matches.at(i); PrevCount = it ->second; } } } } } wordWithHigestOcurrence = ApparentPerfectMatch; return ApparentPerfectMatch; } string Checker::getWordWithHighestOccurence() { return wordWithHigestOcurrence; } Checker :: ~Checker(){}
// Created on: 1992-04-06 // Created by: Christian CAILLET // Copyright (c) 1992-1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _IGESData_IGESModel_HeaderFile #define _IGESData_IGESModel_HeaderFile #include <IGESData_GlobalSection.hxx> #include <Interface_InterfaceModel.hxx> class IGESData_IGESEntity; class Interface_Check; class Standard_Transient; class TCollection_HAsciiString; class IGESData_IGESModel; DEFINE_STANDARD_HANDLE(IGESData_IGESModel, Interface_InterfaceModel) //! Defines the file header and //! entities for IGES files. These headers and entities result from //! a complete data translation using the IGES data exchange processor. //! Each entity is contained in a single model only and has a //! unique identifier. You can access this identifier using the method Number. //! Gives an access to the general data in the Start and the Global //! sections of an IGES file. //! The IGES file includes the following sections: //! -Start, //! -Global, //! -Directory Entry, //! -Parameter Data, //! -Terminate class IGESData_IGESModel : public Interface_InterfaceModel { public: Standard_EXPORT IGESData_IGESModel(); //! Erases all data specific to IGES file Header (Start + Global) Standard_EXPORT void ClearHeader() Standard_OVERRIDE; //! Prints the IGES file header //! (Start and Global Sections) to the log file. The integer //! parameter is intended to be used as a level indicator but is not used at present. Standard_EXPORT void DumpHeader (Standard_OStream& S, const Standard_Integer level = 0) const Standard_OVERRIDE; //! Returns Model's Start Section (list of comment lines) Standard_EXPORT Handle(TColStd_HSequenceOfHAsciiString) StartSection() const; //! Returns the count of recorded Start Lines Standard_EXPORT Standard_Integer NbStartLines() const; //! Returns a line from the IGES file //! Start section by specifying its number. An empty string is //! returned if the number given is out of range, the range being //! from 1 to NbStartLines. Standard_EXPORT Standard_CString StartLine (const Standard_Integer num) const; //! Clears the IGES file Start Section Standard_EXPORT void ClearStartSection(); //! Sets a new Start section from a list of strings. //! If copy is false, the Start section will be shared. Any //! modifications made to the strings later on, will have an effect on //! the Start section. If copy is true (default value), //! an independent copy of the strings is created and used as //! the Start section. Any modifications made to the strings //! later on, will have no effect on the Start section. Standard_EXPORT void SetStartSection (const Handle(TColStd_HSequenceOfHAsciiString)& list, const Standard_Boolean copy = Standard_True); //! Adds a new string to the existing //! Start section at the end if atnum is 0 or not given, or before //! atnumth line. Standard_EXPORT void AddStartLine (const Standard_CString line, const Standard_Integer atnum = 0); //! Returns the Global section of the IGES file. const IGESData_GlobalSection& GlobalSection() const { return theheader; } //! Returns the Global section of the IGES file. IGESData_GlobalSection& ChangeGlobalSection() { return theheader; } //! Sets the Global section of the IGES file. Standard_EXPORT void SetGlobalSection (const IGESData_GlobalSection& header); //! Sets some of the Global section //! parameters with the values defined by the translation //! parameters. param may be: //! - receiver (value read in XSTEP.iges.header.receiver), //! - author (value read in XSTEP.iges.header.author), //! - company (value read in XSTEP.iges.header.company). //! The default value for param is an empty string. //! Returns True when done and if param is given, False if param is //! unknown or empty. Note: Set the unit in the IGES //! file Global section via IGESData_BasicEditor class. Standard_EXPORT Standard_Boolean ApplyStatic (const Standard_CString param = ""); //! Returns an IGES entity given by its rank number. Standard_EXPORT Handle(IGESData_IGESEntity) Entity (const Standard_Integer num) const; //! Returns the equivalent DE Number for an Entity, i.e. //! 2*Number(ent)-1 , or 0 if <ent> is unknown from <me> //! This DE Number is used for File Writing for instance Standard_EXPORT Standard_Integer DNum (const Handle(IGESData_IGESEntity)& ent) const; //! gets Header (GlobalSection) from another Model Standard_EXPORT void GetFromAnother (const Handle(Interface_InterfaceModel)& other) Standard_OVERRIDE; //! Returns a New Empty Model, same type as <me> i.e. IGESModel Standard_EXPORT Handle(Interface_InterfaceModel) NewEmptyModel() const Standard_OVERRIDE; //! Checks that the IGES file Global //! section contains valid data that conforms to the IGES specifications. Standard_EXPORT virtual void VerifyCheck (Handle(Interface_Check)& ach) const Standard_OVERRIDE; //! Sets LineWeights of contained Entities according header data //! (MaxLineWeight and LineWeightGrad) or to a default value for //! undefined weights Standard_EXPORT void SetLineWeights (const Standard_Real defw); //! erases specific labels, i.e. does nothing Standard_EXPORT void ClearLabels() Standard_OVERRIDE; //! Prints label specific to IGES norm for a given entity, i.e. //! its directory entry number (2*Number-1) Standard_EXPORT void PrintLabel (const Handle(Standard_Transient)& ent, Standard_OStream& S) const Standard_OVERRIDE; //! Prints label specific to IGES norm for a given -- -- //! entity, i.e. its directory entry number (2*Number-1) //! in the log file format. Standard_EXPORT virtual void PrintToLog (const Handle(Standard_Transient)& ent, Standard_OStream& S) const Standard_OVERRIDE; //! Prints label specific to IGES norm for a given entity, i.e. //! its directory entry number (2*Number-1) Standard_EXPORT void PrintInfo (const Handle(Standard_Transient)& ent, Standard_OStream& S) const; //! Returns a string with the label attached to a given entity, //! i.e. a string "Dnn" with nn = directory entry number (2*N-1) Standard_EXPORT Handle(TCollection_HAsciiString) StringLabel (const Handle(Standard_Transient)& ent) const Standard_OVERRIDE; DEFINE_STANDARD_RTTIEXT(IGESData_IGESModel,Interface_InterfaceModel) protected: private: Handle(TColStd_HSequenceOfHAsciiString) thestart; IGESData_GlobalSection theheader; }; #endif // _IGESData_IGESModel_HeaderFile
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- * * Copyright (C) 1995-2007 Opera Software AS. All rights reserved. * * This file is part of the Opera web browser. * It may not be distributed under any circumstances. */ #include "core/pch.h" #include "adjunct/quick_toolkit/widgets/OpTreeView/ItemDrawArea.h" #include "adjunct/quick_toolkit/widgets/OpTreeView/TreeViewModelItem.h" #include "adjunct/quick_toolkit/widgets/OpTreeView/OpTreeView.h" #include "adjunct/quick_toolkit/widgets/OpTreeView/Column.h" /*********************************************************************************** ** ** ** ***********************************************************************************/ void TreeViewModelItem::Clear() { if (m_column_cache) { RemoveCustomCellWidget(); OP_DELETEA(m_column_cache); m_column_cache = NULL; OP_DELETE(m_associated_text); m_associated_text = NULL; OP_DELETE(m_associated_image); m_associated_image = NULL; OP_DELETE(m_widget_image); m_widget_image = NULL; } } /*********************************************************************************** ** ** ** ***********************************************************************************/ ItemDrawArea* TreeViewModelItem::GetAssociatedText(OpTreeView* view) { ItemData item_data(ASSOCIATED_TEXT_QUERY); OpString string; item_data.associated_text_query_data.text = &string; item_data.column_query_data.column_text_color = OP_RGB(0, 0, 0); if(!m_associated_text) GetItemData(&item_data); if(item_data.associated_text_query_data.text->HasContent()) { if(!m_associated_text) m_associated_text = OP_NEW(ItemDrawArea, ()); if(m_associated_text) { // Maybe this shouldn't be ignored? OpStatus::Ignore(SetDrawAreaText(view, string, m_associated_text)); m_associated_text->m_color = item_data.associated_text_query_data.text_color; m_associated_text->m_indentation = item_data.associated_text_query_data.associated_text_indentation; m_associated_text->m_flags = item_data.flags; } } return m_associated_text; } /*********************************************************************************** ** ** ** ***********************************************************************************/ ItemDrawArea* TreeViewModelItem::GetAssociatedImage(OpTreeView* view) { ItemData item_data(ASSOCIATED_IMAGE_QUERY, view); OpString8 string; item_data.associated_image_query_data.image = &string; GetItemData(&item_data); if(item_data.associated_image_query_data.image->HasContent()) { if(!m_associated_image) m_associated_image = OP_NEW(ItemDrawArea, ()); if(m_associated_image) { if(OpStatus::IsSuccess(m_associated_image_skin_elm.Set(item_data.associated_image_query_data.image->CStr()))) { m_associated_image->m_image = m_associated_image_skin_elm.CStr(); } m_associated_image->m_image_state = item_data.associated_image_query_data.skin_state; } } else { OP_DELETE(m_associated_image); m_associated_image = NULL; } return m_associated_image; } const char *TreeViewModelItem::GetSkin(OpTreeView* view) { ItemData item_data(SKIN_QUERY, view); item_data.flags = m_flags; GetItemData(&item_data); return item_data.skin_query_data.skin; } /*********************************************************************************** ** ** GetItemDrawArea ** ***********************************************************************************/ ItemDrawArea* TreeViewModelItem::GetItemDrawArea(OpTreeView* view, INT32 column, BOOL paint) { INT32 count = view->GetTreeModel()->GetColumnCount(); if (m_column_cache == NULL) { m_column_cache = OP_NEWA(ItemDrawArea, count); if (!m_column_cache) { return NULL; } } ItemDrawArea* cache = &m_column_cache[column]; if (!(cache->m_flags & FLAG_FETCHED) || (paint && cache->m_flags & FLAG_NO_PAINT)) { ItemData item_data(COLUMN_QUERY,view); OpString string; item_data.column_query_data.column = column; item_data.column_query_data.column_text = &string; item_data.column_query_data.column_text_color = OP_RGB(0, 0, 0); item_data.flags = m_flags; item_data.column_query_data.custom_cell_widget = cache->m_custom_cell_widget; if (!paint) { item_data.flags |= FLAG_NO_PAINT; } GetItemData(&item_data); // The disabled state needs to be propagated to the treeviewmodelitem, since it // influences the behavior of the item (not just drawing behavior) if (item_data.flags & FLAG_DISABLED) m_flags |= FLAG_DISABLED; else m_flags &= ~FLAG_DISABLED; if (item_data.flags & FLAG_CUSTOM_CELL_WIDGET) m_flags |= FLAG_CUSTOM_CELL_WIDGET; else m_flags &= ~FLAG_CUSTOM_CELL_WIDGET; // Formatting can be changed in an extisting item if (item_data.flags & FLAG_FORMATTED_TEXT) m_flags |= FLAG_FORMATTED_TEXT; else m_flags &= ~FLAG_FORMATTED_TEXT; cache->m_image = item_data.column_query_data.column_image; cache->m_image_2 = item_data.column_query_data.column_image_2; cache->m_color = item_data.column_query_data.column_text_color; cache->m_sort_order = item_data.column_query_data.column_sort_order; cache->m_flags = item_data.flags; cache->m_progress = item_data.column_query_data.column_progress; cache->m_indentation = item_data.column_query_data.column_indentation; cache->m_column_span = item_data.column_query_data.column_span; cache->m_custom_cell_widget = item_data.column_query_data.custom_cell_widget; OpStatus::Ignore(SetDrawAreaText(view, string, cache)); cache->m_string_prefix_length = item_data.column_query_data.column_text_prefix; cache->m_flags |= FLAG_FETCHED; cache->m_bitmap_image = item_data.column_bitmap; } return cache; } /*********************************************************************************** ** ** SetDrawAreaText ** ***********************************************************************************/ OP_STATUS TreeViewModelItem::SetDrawAreaText(OpTreeView* view, OpString & string, ItemDrawArea* cache) { // break at newline, but not until we have something to display (so // we want to skip leading newlines). uni_char* cur_pos = string.CStr(); uni_char* start_pos = cur_pos; while (cur_pos && *cur_pos) { const BOOL is_newline = (*cur_pos == '\n' || *cur_pos == '\r'); if (cur_pos > start_pos && is_newline) { *cur_pos = 0; break; } else if (cur_pos == start_pos && is_newline) start_pos = cur_pos + 1; cur_pos++; } if (IsFormattedText()) return ParseFormattedText(view, cache, start_pos); else return cache->m_strings.m_string.Set(start_pos, view); } /*********************************************************************************** ** ** ParseFormattedText ** ** Checks the string for some predefined HTML tags: ** <i></i> Italic ** <b></b> Bold ** <o></o> Overstrike ** <c=353253></c> Colored text ** ***********************************************************************************/ OP_STATUS TreeViewModelItem::ParseFormattedText(OpTreeView* view, ItemDrawArea* cache, const OpStringC& formatted_text) { if (formatted_text.IsEmpty()) return OpStatus::OK; ItemDrawArea::StringList* current_string = &cache->m_strings; ItemDrawArea::StringList* prev_string = current_string; const uni_char* text_ptr = formatted_text.CStr(); const uni_char* next_ptr = uni_strchr(text_ptr, '<'); OpString text_part; int color = 0; // Cleanup previous strings OP_DELETE(current_string->m_next); current_string->m_next = NULL; if (!text_part.Reserve(formatted_text.Length())) return OpStatus::ERR_NO_MEMORY; int count = 0; int string_flags = 0; bool use_line_through = false; bool use_new = true; // See if we found a tag while (text_ptr && *text_ptr) { use_new = true; // Make new string if necessary if (!current_string) { current_string = OP_NEW(ItemDrawArea::StringList, ()); if (!current_string) return OpStatus::ERR_NO_MEMORY; prev_string->m_next = current_string; prev_string = current_string; } // FIXME: The current highlithing approach is incompatible with BiDi. // Force LTR for now, fix DSK-359759 better later. current_string->m_string.SetForceLTR(TRUE); if (next_ptr != text_ptr) { // get the text if (next_ptr) { RETURN_IF_ERROR(text_part.Set(text_ptr, next_ptr - text_ptr)); RETURN_IF_ERROR(current_string->m_string.Set(text_part.CStr(), view)); } else { RETURN_IF_ERROR(current_string->m_string.Set(text_ptr, view)); } text_ptr = next_ptr; } else if (*text_ptr == UNI_L('<')) { // get the tag if (*(text_ptr + 1) != '\0' && *(text_ptr + 2) == UNI_L('>')) { switch(*(text_ptr + 1)) { case UNI_L('b'): string_flags |= ItemDrawArea::FLAG_BOLD; break; case UNI_L('i'): string_flags |= ItemDrawArea::FLAG_ITALIC; break; case UNI_L('o'): use_line_through = true; break; default: OP_ASSERT(!"Unknown tag"); } text_ptr = text_ptr + 3; next_ptr = text_ptr; } else if (*(text_ptr + 1) == UNI_L('/') && *(text_ptr + 2) != '\0' && *(text_ptr + 3) == UNI_L('>')) { switch(*(text_ptr + 2)) { case 'b': string_flags &= ~ItemDrawArea::FLAG_BOLD; break; case 'i': string_flags &= ~ItemDrawArea::FLAG_ITALIC; break; case 'c': string_flags &= ~ItemDrawArea::FLAG_COLOR; break; case 'o': use_line_through = false; break; default: OP_ASSERT(!"Unknown tag"); } string_flags &= ~ItemDrawArea::FLAG_BOLD; text_ptr = text_ptr + 4; next_ptr = text_ptr; } else if (*(text_ptr + 1) == UNI_L('c') && *(text_ptr + 2) == UNI_L('=') && uni_sscanf(text_ptr+3, UNI_L("%d>%n"), &color, &count) == 1 ) { string_flags |= ItemDrawArea::FLAG_COLOR; text_ptr += 3 + count; next_ptr = text_ptr; } else { next_ptr++; } use_new = false; } if (current_string && use_new) { current_string->m_string_flags = string_flags; if (use_line_through) current_string->m_string.SetTextDecoration(WIDGET_LINE_THROUGH, TRUE); if (string_flags & ItemDrawArea::FLAG_COLOR) current_string->m_string_color = color; } if (use_new) current_string = NULL; if (next_ptr) next_ptr = uni_strchr(next_ptr, '<'); } return OpStatus::OK; } /*********************************************************************************** ** ** TreeViewModelItem::OnAdded ** ***********************************************************************************/ void TreeViewModelItem::OnAdded() { TreeViewModel* model = GetModel(); if (model->m_resorting) return; model->m_hash_table.Add(m_model_item, this); } /*********************************************************************************** ** ** TreeViewModelItem::OnRemoving ** ***********************************************************************************/ void TreeViewModelItem::OnRemoving() { TreeViewModel* model = GetModel(); if (model->m_resorting) return; void* data = NULL; model->m_hash_table.Remove(m_model_item, &data); if (IsCustomWidget() && model->GetView()) { model->GetView()->OnCustomWidgetItemRemoving(this); } RemoveCustomCellWidget(); } /*********************************************************************************** ** ** RemoveCustomCellWidget ** ***********************************************************************************/ void TreeViewModelItem::RemoveCustomCellWidget() { TreeViewModel* model = GetModel(); if (HasCustomCellWidget() && model && model->GetView() && m_column_cache) { INT32 count = model->GetView()->GetColumnCount(); for (INT32 i = 0; i < count; i++) { if (m_column_cache[i].m_custom_cell_widget) { model->GetView()->OnCustomWidgetItemRemoving(this, m_column_cache[i].m_custom_cell_widget); } } } } /*********************************************************************************** ** ** TreeViewModelItem::~TreeViewModelItem ** ***********************************************************************************/ TreeViewModelItem::~TreeViewModelItem() { Clear(); #ifdef ACCESSIBILITY_EXTENSION_SUPPORT OP_DELETE(m_text_objects); #endif } #ifdef ACCESSIBILITY_EXTENSION_SUPPORT /*********************************************************************************** ** ** ** ***********************************************************************************/ void TreeViewModelItem::SetViewModel(TreeViewModel* view_model) { m_view_model = view_model; } /*********************************************************************************** ** ** ** ***********************************************************************************/ OP_STATUS TreeViewModelItem::CreateTextObjectsIfNeeded() { if (!m_text_objects) { m_text_objects = OP_NEW(OpAutoVector<AccessibleTextObject>, ()); if (!m_text_objects) return OpStatus::ERR; } int count = m_view_model->GetModel()->GetColumnCount(); for (INT32 i = 0; i < count; i++) { AccessibleTextObject* obj = OP_NEW(AccessibleTextObject, (this, i)); if (obj) m_text_objects->Add(obj); } return OpStatus::OK; } OP_STATUS TreeViewModelItem::AccessibilityClicked() { // m_view_model->SetFocusToItem(GetIndex()); OpTreeView* view = m_view_model->GetView(); INT32 index = GetIndex(); if (index >= 0 && view) { view->SetFocus(FOCUS_REASON_OTHER); if (CanOpen()) { view->OpenItem(index, !IsOpen()); } view->SelectItem(index, FALSE, FALSE, FALSE, TRUE); if (view->GetListener()) { view->GetListener()->OnMouseEvent(view, index, -1, -1, MOUSE_BUTTON_1, TRUE, 1); view->GetListener()->OnMouseEvent(view, index, -1, -1, MOUSE_BUTTON_1, FALSE, 1); } } return OpStatus::OK; } /*********************************************************************************** ** ** ** ***********************************************************************************/ BOOL TreeViewModelItem::AccessibilitySetFocus() { m_view_model->SetFocusToItem(GetIndex()); return TRUE; } /*********************************************************************************** ** ** ** ***********************************************************************************/ OP_STATUS TreeViewModelItem::AccessibilityGetText(OpString& str) { // implement: find important column return GetTextOfObject(0, str); } /*********************************************************************************** ** ** ** ***********************************************************************************/ OP_STATUS TreeViewModelItem::AccessibilityGetDescription(OpString& str) { // switch (GetType()) // { // case FOLDER_TYPE: // return g_languageManager->GetString(Str::S_FOLDER_TYPE, str); // default: str.Empty(); return OpStatus::ERR; // } } /*********************************************************************************** ** ** ** ***********************************************************************************/ OP_STATUS TreeViewModelItem::AccessibilityGetAbsolutePosition(OpRect &rect) { OpRect off_rect; int index = GetIndex(); m_view_model->GetView()->GetItemRect(index, rect, FALSE); m_view_model->GetView()->AccessibilityGetAbsolutePosition(off_rect); rect.x += off_rect.x; rect.y += off_rect.y; return OpStatus::OK; } /*********************************************************************************** ** ** ** ***********************************************************************************/ OP_STATUS TreeViewModelItem::AccessibilityGetValue(int &value) { int index = GetIndex(); value = -1; do { value++; index = m_view_model->GetView()->GetParent(index); } while (index >= 0); return OpStatus::OK; } /*********************************************************************************** ** ** ** ***********************************************************************************/ BOOL TreeViewModelItem::AccessibilitySetExpanded(BOOL expanded) { if (CanOpen()) { int index = GetIndex(); m_view_model->GetView()->OpenItem(index, expanded); return TRUE; } return FALSE; } /*********************************************************************************** ** ** ** ***********************************************************************************/ Accessibility::ElementKind TreeViewModelItem::AccessibilityGetRole() const { return Accessibility::kElementKindListRow; } /*********************************************************************************** ** ** ** ***********************************************************************************/ Accessibility::State TreeViewModelItem::GetUnfilteredState() { Accessibility::State state = m_view_model->GetUnfilteredState(); if (IsSelected()) { state |= Accessibility::kAccessibilityStateCheckedOrSelected; } if (!IsFocused()) { state &= ~Accessibility::kAccessibilityStateFocused; } if (CanOpen()) { state |= Accessibility::kAccessibilityStateExpandable; if (IsOpen()) { state |= Accessibility::kAccessibilityStateExpanded; } } if (!m_view_model->GetView()->IsItemVisible(GetIndex())) { state |= Accessibility::kAccessibilityStateInvisible; } return state; } /*********************************************************************************** ** ** ** ***********************************************************************************/ Accessibility::State TreeViewModelItem::AccessibilityGetState() { return GetUnfilteredState(); } /*********************************************************************************** ** ** ** ***********************************************************************************/ int TreeViewModelItem::GetAccessibleChildrenCount() { int n = m_view_model->GetView()->GetColumnCount(); int children = 0; for (int i = 0; i < n; i++) { OpTreeView::Column* col = m_view_model->GetView()->GetColumnByIndex(i); if (col->IsColumnVisible()) children++; } return children; } /*********************************************************************************** ** ** ** ***********************************************************************************/ OpAccessibleItem* TreeViewModelItem::GetAccessibleChild(int child_nr) { int n = m_view_model->GetView()->GetColumnCount(); int children = -1; int i; for (i = 0; i < n && children < child_nr; i++) { OpTreeView::Column* col = m_view_model->GetView()->GetColumnByIndex(i); if (col->IsColumnVisible()) children++; } if (children < child_nr) return NULL; if (OpStatus::IsError(this->CreateTextObjectsIfNeeded())) return NULL; AccessibleTextObject* obj = m_text_objects ? m_text_objects->Get(i-1) : NULL; if (obj) return obj; return NULL; } /*********************************************************************************** ** ** ** ***********************************************************************************/ int TreeViewModelItem::GetAccessibleChildIndex(OpAccessibleItem* child) { int n = m_view_model->GetView()->GetColumnCount(); int children = -1; int i; for (i = 0; i < n; i++) { OpTreeView::Column* col = m_view_model->GetView()->GetColumnByIndex(i); if (col->IsColumnVisible()) { if (child == m_text_objects->Get(i-1)) return children; children++; } } return Accessibility::NoSuchChild; } /*********************************************************************************** ** ** ** ***********************************************************************************/ OpAccessibleItem* TreeViewModelItem::GetAccessibleChildOrSelfAt(int x, int y) { if (m_view_model) { int i = m_view_model->GetView()->GetColumnAt(x, y); if (OpStatus::IsError(this->CreateTextObjectsIfNeeded())) return NULL; AccessibleTextObject* obj = m_text_objects ? m_text_objects->Get(i) : NULL; if (obj) return obj; } return this; } /*********************************************************************************** ** ** ** ***********************************************************************************/ OpAccessibleItem* TreeViewModelItem::GetAccessibleFocusedChildOrSelf() { if (IsFocused()) { if (OpStatus::IsError(this->CreateTextObjectsIfNeeded())) return NULL; AccessibleTextObject* obj = m_text_objects ? m_text_objects->Get(m_focused_col) : NULL; if (obj) return obj; return this; } return NULL; } /*********************************************************************************** ** ** ** ***********************************************************************************/ OP_STATUS TreeViewModelItem::GetAbsolutePositionOfObject(int i, OpRect& rect) { OpRect parent_rect; OpRect column_rect; AccessibilityGetAbsolutePosition(parent_rect); OpTreeView::Column* column = m_view_model->GetView()->GetColumnByIndex(i); column->AccessibilityGetAbsolutePosition(column_rect); rect.y = parent_rect.y; rect.height= parent_rect.height; if (column_rect.IsEmpty()) { rect.x = parent_rect.x; rect.width = column->m_width; } else { rect.x = column_rect.x; rect.width = column_rect.width; } return OpStatus::OK; } /*********************************************************************************** ** ** ** ***********************************************************************************/ OP_STATUS TreeViewModelItem::SetFocusToObject(int i) { AccessibilitySetFocus(); m_focused_col = i; return OpStatus::OK; } /*********************************************************************************** ** ** ** ***********************************************************************************/ OP_STATUS TreeViewModelItem::GetTextOfObject(int i, OpString& str) { ItemDrawArea* item = GetItemDrawArea(m_view_model->GetView(), i, FALSE); if (item) { for (ItemDrawArea::StringList* string = &item->m_strings; string; string = string->m_next) { RETURN_IF_ERROR(str.Append(string->m_string.Get())); } return OpStatus::OK; } return OpStatus::ERR; } /*********************************************************************************** ** ** ** ***********************************************************************************/ OP_STATUS TreeViewModelItem::GetDecriptionOfObject(int i, OpString& str) { return AccessibilityGetDescription(str); } /*********************************************************************************** ** ** ** ***********************************************************************************/ Accessibility::State TreeViewModelItem::GetStateOfObject(int i) { Accessibility::State state = GetUnfilteredState(); if (m_focused_col != i) state &= ~Accessibility::kAccessibilityStateFocused; return state; } /*********************************************************************************** ** ** ** ***********************************************************************************/ OP_STATUS TreeViewModelItem::ObjectClicked(int i) { // FIXME, if click in checkbox column, toggle checkbox. return AccessibilityClicked(); } /*********************************************************************************** ** ** ** ***********************************************************************************/ OpAccessibleItem* TreeViewModelItem::GetAccessibleParentOfObject() { return this; } #endif // ACCESSIBILITY_EXTENSION_SUPPORT
#include "treeface/graphics/VectorGraphicsMaterial.h" using namespace treecore; #define UNI_NAME_LINE_WIDTH "line_width" #define UNI_NAME_SKLT_MIN "skeleton_min" #define UNI_NAME_SKLT_MAX "skeleton_max" namespace treeface { const Identifier VectorGraphicsMaterial::UNIFORM_LINE_WIDTH( UNI_NAME_LINE_WIDTH ); const Identifier VectorGraphicsMaterial::UNIFORM_SKELETON_MIN( UNI_NAME_SKLT_MIN ); const Identifier VectorGraphicsMaterial::UNIFORM_SKELETON_MAX( UNI_NAME_SKLT_MAX ); VectorGraphicsMaterial::VectorGraphicsMaterial() {} VectorGraphicsMaterial::~VectorGraphicsMaterial() {} treecore::String VectorGraphicsMaterial::get_shader_source_addition() const noexcept { return SceneGraphMaterial::get_shader_source_addition() + String( "uniform highp float " UNI_NAME_LINE_WIDTH ";\n" "uniform highp vec2 " UNI_NAME_SKLT_MIN ";\n" "uniform highp vec2 " UNI_NAME_SKLT_MAX ";\n" "\n" ); } } // namespace treeface
// // Created by Nikita Kruk on 08.08.18. // #ifndef SPRAPPROXIMATEBAYESIANCOMPUTATION_BOUNDARYCONDITIONSCONFIGURATION_HPP #define SPRAPPROXIMATEBAYESIANCOMPUTATION_BOUNDARYCONDITIONSCONFIGURATION_HPP #include "../Definitions.hpp" #include "Vector2D.hpp" #include <vector> class BoundaryConditionsConfiguration { public: BoundaryConditionsConfiguration(Real x_size, Real y_size); virtual ~BoundaryConditionsConfiguration(); void SetNewBoundaries(Real x_size, Real y_size); virtual void ClassAEffectiveParticleDistance(Real x_i, Real y_i, Real x_j, Real y_j, Real &dx, Real &dy) = 0; virtual void ClassAEffectiveParticleDistance(const Vector2D &r_i, const Vector2D &r_j, Vector2D &dr_ij) = 0; virtual void ClassBEffectiveParticleDistance_signed(Real x_i, Real y_i, Real x_j, Real y_j, Real &dx, Real &dy) = 0; virtual void ClassBEffectiveParticleDistance_unsigned(Real x_i, Real y_i, Real x_j, Real y_j, Real &dx, Real &dy) = 0; virtual void ClassBEffectiveParticleDistance_signed(const Vector2D &r_i, const Vector2D &r_j, Vector2D &dr_ij) = 0; virtual void ClassBEffectiveParticleDistance_unsigned(const Vector2D &r_i, const Vector2D &r_j, Vector2D &dr_ij) = 0; virtual void ClassCEffectiveParticleDistance_signed(Real x_i, Real y_i, Real x_j, Real y_j, Real &dx, Real &dy) = 0; virtual void ClassCEffectiveParticleDistance_unsigned(Real x_i, Real y_i, Real x_j, Real y_j, Real &dx, Real &dy) = 0; virtual void ClassCEffectiveParticleDistance_signed(const Vector2D &r_i, const Vector2D &r_j, Vector2D &dr_ij) = 0; virtual void ClassCEffectiveParticleDistance_unsigned(const Vector2D &r_i, const Vector2D &r_j, Vector2D &dr_ij) = 0; virtual void ApplyPeriodicBoundaryConditions(Real x, Real y, Real &x_pbc, Real &y_pbc) = 0; virtual void ApplyPeriodicBoundaryConditions(std::vector<Real> &system_state, int N) = 0; virtual void ApplyPeriodicBoundaryConditions(const Vector2D &r, Vector2D &r_pbc) = 0; protected: Real x_size_; Real y_size_; Real x_rsize_; Real y_rsize_; }; #endif //SPRAPPROXIMATEBAYESIANCOMPUTATION_BOUNDARYCONDITIONSCONFIGURATION_HPP
#include "Interface.h" #include "RealImplementation.h" Interface::Interface(const std::string& text, float value):m_Pimpl(std::make_unique<RealImplementation>(text, value)) { } Interface::~Interface() { } Interface::Interface(Interface&& interface):m_Pimpl(std::move(interface.m_Pimpl)) { } Interface& Interface::operator=(Interface&& interface) { if(this != &interface) { m_Pimpl = std::move(interface.m_Pimpl); } return *this; } void Interface::AddText(const std::string& string) { if(m_Pimpl) { m_Pimpl->AddText(string); } } void Interface::ClearText() { if(m_Pimpl) { m_Pimpl->ClearText(); } } float Interface::operator*(float op) { if(m_Pimpl) { return m_Pimpl->operator*(op); } return -1; } float Interface::operator-(float op) { if(m_Pimpl) { return m_Pimpl->operator-(op); } return -1; } float Interface::operator+(float op) { if(m_Pimpl) { return m_Pimpl->operator+(op); } return -1; } float Interface::operator/(float op) { if(m_Pimpl) { return m_Pimpl->operator/(op); } return -1; } float Interface::operator=(float value) { if(m_Pimpl) { return m_Pimpl->operator=(value); } return 0; } std::string Interface::ToString() const { if(m_Pimpl) { return m_Pimpl->ToString(); } return "null pimpl"; }
/* * Copyright 2019 LogMeIn * * 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. * * SPDX-License-Identifier: Apache-2.0 */ #include "gmock/gmock.h" #include "boost/chrono.hpp" #include "boost/thread.hpp" #include "boost/thread/future.hpp" #include <future> #include <thread> #include "asyncly/executor/InlineExecutor.h" #include "asyncly/executor/ThreadPoolExecutorController.h" namespace asyncly { using namespace testing; class ThreadPoolExecutorTest : public Test { public: void SetUp() override { } }; TEST_F(ThreadPoolExecutorTest, shouldInitializeWithOneThread) { ThreadPoolExecutorController::create(1); } TEST_F(ThreadPoolExecutorTest, shouldInializeWithMultipleThreads) { ThreadPoolExecutorController::create(10); } TEST_F(ThreadPoolExecutorTest, DISABLED_shouldRunClosuresOnMultipleThreads) { const auto numThreads = 5; std::array<boost::promise<std::thread::id>, numThreads> threadIdPromises; std::array<boost::shared_future<std::thread::id>, numThreads> threadIdFutures; std::transform( threadIdPromises.begin(), threadIdPromises.end(), threadIdFutures.begin(), [](boost::promise<std::thread::id>& p) { return p.get_future(); }); auto closure = [&threadIdPromises, &threadIdFutures](int i) { auto threadId = std::this_thread::get_id(); threadIdPromises[i].set_value(threadId); boost::wait_for_all(threadIdFutures.begin(), threadIdFutures.end()); }; { auto executorController = ThreadPoolExecutorController::create(numThreads); auto executor = executorController->get_executor(); for (auto i = 0; i < numThreads; i++) { executor->post(std::bind(closure, i)); } } boost::wait_for_all(threadIdFutures.begin(), threadIdFutures.end()); std::array<std::thread::id, numThreads> threadIds; std::transform( threadIdFutures.begin(), threadIdFutures.end(), threadIds.begin(), [](boost::shared_future<std::thread::id>& f) { return f.get(); }); std::sort(threadIds.begin(), threadIds.end()); EXPECT_EQ(threadIds.end(), std::adjacent_find(threadIds.begin(), threadIds.end())); } TEST_F(ThreadPoolExecutorTest, shouldSupportDestructionInWorkerThread) { for (int i = 0; i < 1000; i++) { std::promise<std::thread::id> p; { auto executorController = ThreadPoolExecutorController::create(1); auto executor = executorController->get_executor(); executor->post([executor, &p]() { executor->post([executor, &p]() { executor->post([executor, &p]() { p.set_value(std::this_thread::get_id()); }); }); }); } EXPECT_NE(p.get_future().get(), std::this_thread::get_id()); } } TEST_F(ThreadPoolExecutorTest, shouldFinishAllTasksBeforeDestruction) { auto executorController = ThreadPoolExecutorController::create(1); auto executor = executorController->get_executor(); std::promise<void> sync; std::function<void(int)> recurse = [&recurse, &sync](int i) { if (i < 1000) { this_thread::get_current_executor()->post(std::bind(recurse, i + 1)); } else { sync.set_value(); } }; executor->post([recurse]() { recurse(0); }); executor.reset(); EXPECT_NO_THROW(sync.get_future().get()); } TEST_F(ThreadPoolExecutorTest, shouldFinishAllThreadsBeforeExecutorDestruction) { auto executorController = ThreadPoolExecutorController::create(1); auto executor = executorController->get_executor(); std::promise<void> sync; std::future<void> fsync = sync.get_future(); std::promise<void> sync_done; std::future<void> fsync_done = sync_done.get_future(); auto done = std::make_shared<bool>(false); auto payload = std::shared_ptr<bool>(new bool(true), [&done, &sync_done](bool* b) mutable { delete b; // make it somewhat more likely to fail boost::this_thread::sleep_for(boost::chrono::milliseconds(100)); *done = true; sync_done.set_value(); }); executor->post([&fsync, payload]() { fsync.get(); }); payload.reset(); executor.reset(); // makes sure external executor pointer has been released, before task is executed (and possibly // destroyed) sync.set_value(); executorController->finish(); EXPECT_TRUE(*done); // don't crash in case of error fsync_done.get(); } TEST_F(ThreadPoolExecutorTest, shouldSupportNonCopyableTask) { auto executorController = ThreadPoolExecutorController::create(1); auto executor = executorController->get_executor(); std::promise<void> sync; auto future = sync.get_future(); executor->post([promise{ std::move(sync) }]() mutable { promise.set_value(); }); executor.reset(); EXPECT_NO_THROW(future.get()); } TEST_F(ThreadPoolExecutorTest, shouldNotThrowOnGetCurrentExecutorInNestedTasks) { // this case can just happen with the "inline executor" which is currently used in multiple // tests, I would question the "inline executor" in general, is it still an executor? auto executor = ::asyncly::InlineExecutor::create(); std::promise<void> promiseFinished; executor->post([&executor, &promiseFinished]() { executor->post([]() {}); EXPECT_NO_THROW(::asyncly::this_thread::get_current_executor()); promiseFinished.set_value(); }); promiseFinished.get_future().wait(); } }
#include <iostream> #include <cstdio> using namespace std; int main(){ float x, y; scanf("%f", &x); if( x <= 15) y = 4 * x / 3; else y = 2.5 * x - 17.5; printf("%.2f", y); return 0; }
/* * Author: Elijah De Vera * Created on January 23, 2021 * Purpose: Factorial Problem */ //System Libraries #include <iostream> using namespace std; //User Libraries //Global Constants - Math/Physics Constants, Conversions, // 2-D Array Dimensions //Function Prototypes int fctrl(int);//Function to write for this problem //Execution Begins Here int main(int argc, char** argv) { //Program TItle cout<<"This program calculates the factorial using a function prototype found in the template for this problem."<<endl; //Declare Variables int inp; //Initialize Variables cout<<"Input the number for the function."<<endl; cin>>inp; //Process/Map inputs to outputs //Output data cout<<inp<<"! = "<<fctrl(inp); //Exit stage right! return 0; } int fctrl( int inp ) { int sltn = 1; for ( int i = 1; i <= inp; i++ ) { sltn*=i; } return sltn; }
#include <benchmark/benchmark.h> #include "matrix.hpp" #include "task_4_lib.cpp" static void Block_striped_decomposition(benchmark::State &state) { int size = 800; for (auto _: state) { state.PauseTiming(); Matrix<uint64_t> A(size); randomizeMatrix(A); Matrix<uint64_t> B(size); randomizeMatrix(B); state.ResumeTiming(); prodBS(A, B, state.range(0)); } } static void Checkerboard_decomposition(benchmark::State &state) { int size = 800; for (auto _: state) { state.PauseTiming(); Matrix<uint64_t> A(size); randomizeMatrix(A); Matrix<uint64_t> B(size); randomizeMatrix(B); state.ResumeTiming(); prodCB(A, B, state.range(0)); } } BENCHMARK(Block_striped_decomposition) ->DenseRange(1, 8) ->Iterations(5); BENCHMARK(Checkerboard_decomposition) ->DenseRange(1, 8) ->Iterations(5); BENCHMARK_MAIN();
#pragma once #include "bricks/core/types.h" #define BRICKS_SFINAE_TRUE(x) (sizeof(x) == sizeof(Bricks::SFINAE::True)) #define BRICKS_SFINAE_FALSE(x) (sizeof(x) == sizeof(Bricks::SFINAE::False)) namespace Bricks { namespace SFINAE { class IncompleteType; typedef struct { u8 value[3]; } True; typedef struct { u8 value[5]; } False; struct AnyType { template<typename T> AnyType(const T&); }; template<bool, typename T = void> struct EnableIf { }; template<typename T> struct EnableIf<true, T> { typedef T Type; }; template<bool, typename T = void> struct DisableIf { }; template<typename T> struct DisableIf<false, T> { typedef T Type; }; template<typename T, T t> struct ConfirmType { typedef T Type; }; template<typename T> struct IsConst { static const bool Value = false; }; template<typename T> struct IsConst<const T> { static const bool Value = true; }; template<typename T> struct IsConst<const T&> { static const bool Value = true; }; template<typename T> struct IsReference { static const bool Value = false; }; template<typename T> struct IsReference<T&> { static const bool Value = true; }; template<typename T, typename E = void> struct MakePointerType { typedef T* Type; }; template<typename T> struct MakePointerType<T, typename EnableIf<IsReference<T>::Value>::Type> { typedef IncompleteType* Type; }; template<typename T> typename MakePointerType<T>::Type MakePointer(); template<typename T> T MakeValue(); template<typename T> T& MakeReference(); template<typename T> const T& MakeConstReference(); template<typename T> struct MakeValueType { typedef T Type; }; template<typename T> struct MakeValueType<T*> { typedef T Type; }; template<typename T, typename U> struct IsSameType { static True ConditionT(U*); static False ConditionT(...); static True ConditionU(T*); static False ConditionU(...); static const bool Value = BRICKS_SFINAE_TRUE(ConditionU(MakePointer<U>())) && BRICKS_SFINAE_TRUE(ConditionT(MakePointer<T>())); }; template<typename T, typename U> struct IsCompatibleType { static True Condition(T*); static False Condition(...); static const bool Value = BRICKS_SFINAE_TRUE(Condition(MakePointer<U>())); }; template<typename T, typename U> struct IsCompatibleBaseType { static True Condition(T); static False Condition(...); static const bool Value = BRICKS_SFINAE_TRUE(Condition(MakeReference<U>())); }; template<typename T> struct IsClassType { template<typename U> static True Condition(void (U::*)()); template<typename U> static False Condition(...); static const bool Value = BRICKS_SFINAE_TRUE(Condition<T>(NULL)); }; namespace Internal { template<typename T, typename U> static False operator ==(const T&, const U&); template<typename T, typename U> static False operator >(const T&, const U&); template<typename T, typename U> static False operator <(const T&, const U&); template<typename T, typename U> struct HasEqualityOperator { static True Condition(...); static False Condition(False); static const bool Value = BRICKS_SFINAE_TRUE(Condition(MakeConstReference<T>() == MakeConstReference<U>())); }; template<typename T, typename U> struct HasGreaterThanOperator { static True Condition(...); static False Condition(False); static const bool Value = BRICKS_SFINAE_TRUE(Condition(MakeConstReference<T>() > MakeConstReference<U>())); }; template<typename T, typename U> struct HasLessThanOperator { static True Condition(...); static False Condition(False); static const bool Value = BRICKS_SFINAE_TRUE(Condition(MakeConstReference<T>() < MakeConstReference<U>())); }; } template<typename T, typename U = T> struct HasEqualityOperator { static const bool Value = Internal::HasEqualityOperator<T, U>::Value; }; template<typename T, typename U = T> struct HasGreaterThanOperator { static const bool Value = Internal::HasGreaterThanOperator<T, U>::Value; }; template<typename T, typename U = T> struct HasLessThanOperator { static const bool Value = Internal::HasLessThanOperator<T, U>::Value; }; template<typename T> struct HasConstructor { template<int U> struct DummySize { }; template<typename U> static True Condition(DummySize<sizeof U()>* dummy); template<typename U> static False Condition(...); static const bool Value = BRICKS_SFINAE_TRUE(Condition<T>(NULL)); }; template<typename T> struct IsIntegerNumber { static const bool Value = false; }; template<> struct IsIntegerNumber<s8> { static const bool Value = true; }; template<> struct IsIntegerNumber<u8> { static const bool Value = true; }; template<> struct IsIntegerNumber<s16> { static const bool Value = true; }; template<> struct IsIntegerNumber<u16> { static const bool Value = true; }; template<> struct IsIntegerNumber<s32> { static const bool Value = true; }; template<> struct IsIntegerNumber<u32> { static const bool Value = true; }; template<> struct IsIntegerNumber<s64> { static const bool Value = true; }; template<> struct IsIntegerNumber<u64> { static const bool Value = true; }; template<typename T> struct IsFloatingPointNumber { static const bool Value = false; }; template<> struct IsFloatingPointNumber<f32> { static const bool Value = true; }; template<> struct IsFloatingPointNumber<f64> { static const bool Value = true; }; template<typename T> struct NumericTraits { }; #define BRICKS_INTERNAL_NUMERIC_TRAITS(t, min, max) template<> struct NumericTraits<t> { static const t MinimumValue = min; static const t MaximumValue = max; } BRICKS_INTERNAL_NUMERIC_TRAITS(s8, -0x7F, 0x80); BRICKS_INTERNAL_NUMERIC_TRAITS(u8, 0, 0xFF); BRICKS_INTERNAL_NUMERIC_TRAITS(s16, -0x7FFF, 0x8000); BRICKS_INTERNAL_NUMERIC_TRAITS(u16, 0, 0xFFFF); BRICKS_INTERNAL_NUMERIC_TRAITS(s32, -0x7FFFFFFF, 0x80000000); BRICKS_INTERNAL_NUMERIC_TRAITS(u32, 0, 0xFFFFFFFF); BRICKS_INTERNAL_NUMERIC_TRAITS(s64, -0x7FFFFFFFFFFFFFFFULL, 0x8000000000000000ULL); BRICKS_INTERNAL_NUMERIC_TRAITS(u64, 0, 0xFFFFFFFFFFFFFFFFULL); #undef BRICKS_INTERNAL_NUMERIC_TRAITS } }
// Copyright (c) 2015 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _StdLPersistent_Value_HeaderFile #define _StdLPersistent_Value_HeaderFile #include <StdObjMgt_Attribute.hxx> #include <StdLPersistent_HString.hxx> #include <TDataStd_Integer.hxx> #include <TDF_TagSource.hxx> #include <TDF_Reference.hxx> #include <TDataStd_UAttribute.hxx> #include <TDataStd_Name.hxx> #include <TDataStd_Comment.hxx> #include <TDataStd_AsciiString.hxx> class StdLPersistent_Value { template <class AttribClass> class integer : public StdObjMgt_Attribute<AttribClass>::SingleInt { public: //! Import transient attribute from the persistent data. Standard_EXPORT virtual void ImportAttribute(); }; template <class AttribClass, class HStringClass = StdLPersistent_HString::Extended> class string : public StdObjMgt_Attribute<AttribClass>::SingleRef { public: //! Import transient attribute from the persistent data. Standard_EXPORT virtual void ImportAttribute(); }; public: class TagSource : public integer <TDF_TagSource> { public: Standard_CString PName() const { return "PDF_TagSource"; } }; class Reference : public string <TDF_Reference> { public: Standard_CString PName() const { return "PDF_Reference"; } }; class Comment : public string <TDataStd_Comment> { public: Standard_CString PName() const { return "PDF_Comment"; } }; class UAttribute : public string <TDataStd_UAttribute> { public: //! Create an empty transient attribute Standard_EXPORT virtual Handle(TDF_Attribute) CreateAttribute(); Standard_CString PName() const { return "PDataStd_UAttribute"; } }; class Integer : public integer <TDataStd_Integer> { public: //! Create an empty transient attribute Standard_EXPORT virtual Handle(TDF_Attribute) CreateAttribute(); Standard_CString PName() const { return "PDataStd_Integer"; } }; class Name : public string <TDataStd_Name> { public: //! Create an empty transient attribute Standard_EXPORT virtual Handle(TDF_Attribute) CreateAttribute(); Standard_CString PName() const { return "PDataStd_Name"; } }; class AsciiString : public string <TDataStd_AsciiString, StdLPersistent_HString::Ascii> { public: //! Create an empty transient attribute Standard_EXPORT virtual Handle(TDF_Attribute) CreateAttribute(); Standard_CString PName() const { return "PDataStd_AsciiString"; } }; }; template<> template<> inline Standard_CString StdObjMgt_Attribute<TDF_TagSource>::Simple<Standard_Integer>::PName() const { return "PDF_TagSource"; } template<> template<> inline Standard_CString StdObjMgt_Attribute<TDF_Reference>::Simple<Handle(StdObjMgt_Persistent)>::PName() const { return "PDF_Reference"; } template<> template<> inline Standard_CString StdObjMgt_Attribute<TDataStd_Comment>::Simple<Handle(StdObjMgt_Persistent)>::PName() const { return "PDataStd_Comment"; } #endif
#include <iostream> #include <iomanip> #include <vector> #include <cctype> #include "freqan.hpp" // FrequencyAnalyzer class public methods // method parses text buffer void FrequencyAnalyzer::readBuffer(const std::string& buf) { text_buffer = ""; // clear text buffer - it's nice to be able to reuse methods! int n = 0; for (int i = 0; i < buf.length(); i++) if (isalpha(buf[i])) { text_buffer += toupper(buf[i]); ++n; } compute_frequencies(); } // public accessor method retrieves index of coincidence computation float FrequencyAnalyzer::indexOfCoincidence() const { return index_of_coincidence(); } // public accessor method retrieves english plaintext correlation computation float FrequencyAnalyzer::englishCorrelation() const { return english_correlation(); } // display freqency analysis stats in html list format void FrequencyAnalyzer::showStats() const { // emit html list std::cout << std::fixed; std::cout.precision(3); std::cout << "<ul>\n"; std::cout << "<li>no. of characters processed = " << n << "</li>\n"; std::cout << "<li>index of coincidence = " << indexOfCoincidence() << "</li>\n"; std::cout << "<li>english plaintext correlation = " << englishCorrelation() << "</li>\n"; std::cout << "</ul>\n"; } // display raw count of counted occurences of letters void FrequencyAnalyzer::showCounts() const { std::cout << std::fixed; std::cout.precision(3); std::cout << "<table class='gradienttable'>\n"; std::cout << "<tr><th>letter</th><th>count</th><th>frequency</th><th>english</th></tr>\n"; for (char letter = 'A'; letter <= 'Z'; letter++) { int idx = letter - 65; std::cout << "<tr><td>" << letter << "</td>"; std::cout << "<td>" << count[idx] << "</td>"; std::cout << "<td>" << frequency[idx] << "</td>"; std::cout << "<td>" << english[idx] << "</td></tr>\n"; } std::cout << "</table>\n"; } void FrequencyAnalyzer::cipherReport(const Cipher& cipher_) { // input buffer computations text_buffer = cipher_.inbuf; // set text buffer to input buffer compute_frequencies(); float inioc = indexOfCoincidence(); float inept = englishCorrelation(); std::vector<int> incount(count, count + C); std::vector<float> infreq(frequency, frequency + C); std::cout << std::fixed; // output buffer computations text_buffer = cipher_.outbuf; // set text buffer to output buffer compute_frequencies(); float outioc = indexOfCoincidence(); float outept = englishCorrelation(); std::vector<int> outcount(count, count + C); std::vector<float> outfreq(frequency, frequency + C); // emit html list std::cout.precision(3); std::cout << "<ul>\n"; std::cout << "<li>no. of characters processed = " << n << "</li>\n"; std::cout << "<li>input index of coincidence = " << inioc << "</li>\n"; std::cout << "<li>input english plaintext correlation = " << inept << "</li>\n"; std::cout << "<li>output index of coincidence = " << outioc << "</li>\n"; std::cout << "<li>output english plaintext correlation = " << outept << "</li>\n"; std::cout << "</ul>\n"; // emit html table std::cout << "<table class='gradienttable'>\n"; std::cout << "<tr><th>letter</th><th>input count</th><th>input frequency</th><th>english</th>"; std::cout << "<th>output frequency</th><th>output count</th></tr>\n"; for (char letter = 'A'; letter <= 'Z'; letter++) { int idx = letter - 65; std::cout << "<tr><td>" << letter << "</td>"; std::cout << "<td>" << incount[idx] << "</td>"; std::cout << "<td>" << infreq[idx] << "</td>"; std::cout << "<td>" << english[idx] << "</td>"; std::cout << "<td>" << outfreq[idx] << "</td>"; std::cout << "<td>" << outcount[idx] << "</td></tr>\n"; } std::cout << "</table>\n"; } // FrequencyAnalyzer class private methods // method counts no. of occurrences of each letter of the alphabet void FrequencyAnalyzer::compute_frequencies() { n = 0; // set char count to zero // set counting table to all zeros for (int i = 0; i < C; i++) count[i] = 0; // count occurrences of letters of the alphabet for (int i = 0; i < text_buffer.length(); i++) { if (isalpha(text_buffer[i])) { ++n; int idx; if (islower(text_buffer[i])) idx = text_buffer[i] - 97; else idx = text_buffer[i] - 65; ++(count[idx]); } } // compute frequencies for (int i = 0; i < C; i++) frequency[i] = (float)count[i] / (float)n; } // method computes index of coincidence of text buffer float FrequencyAnalyzer::index_of_coincidence() const { float s = 0; for (int i = 0; i < C; i++) s += (float)count[i] * (float)(count[i] - 1); float ioc = s / ((float)n * (float)(n - 1) / (float)C); return ioc; } // method computes english plaintext correlation of text buffer float FrequencyAnalyzer::english_correlation() const { float corr = 0; for (int i = 0; i < C; i++) corr += english[i] * frequency[i]; return corr; }
#include <iostream> using namespace std; long long arr[101][10] = { 0 }; int main() { int N; cin >> N; for (int i = 1; i <= 9; i++) arr[1][i] = 1; for (int i = 2; i <= N; i++) { for (int j = 0; j <= 9; j++) { if (j - 1 >= 0) arr[i][j] += arr[i - 1][j - 1]; if (j + 1 <= 9) arr[i][j] += arr[i - 1][j + 1]; arr[i][j] %= 1000000000; } } long long res=0; for (int i = 0; i <= 9; i++) res += arr[N][i]; res %= 1000000000; cout << res << endl; return 0; }
// Fill out your copyright notice in the Description page of Project Settings. #include "NotePlayerController.h" #include <cmath> ANotePlayerController::ANotePlayerController() { noteAudioComponent = CreateDefaultSubobject<UAudioComponent>(TEXT("Note Audio Component")); noteAudioComponent->bAutoActivate = false; static ConstructorHelpers::FObjectFinder<UDataTable>GameObjectLookupDataTable_BP(TEXT("DataTable'/Game/DIVAR/Script/pv_724_extreme.pv_724_extreme'")); noteSource = GameObjectLookupDataTable_BP.Object; //static ConstructorHelpers::FObjectFinder<TSubclassOf<class UUserWidget>>LookUpCircleWidget(TEXT("UserWidget'/Game/UserInterface/Note/UIW_Note_Circle.UIW_Note_Circle'")); //CircleWidget = *LookUpCircleWidget.Object; } void ANotePlayerController::PostInitializeComponents() { Super::PostInitializeComponents(); if (noteAudioCue->IsValidLowLevelFast()) noteAudioComponent->SetSound(noteAudioCue); } void ANotePlayerController::BeginPlay() { Super::BeginPlay(); static const FString ContextString(TEXT("GENERAL")); TArray<FNoteTable*> noteTables; IngameUI = CreateWidget<UWidgetIngame>(this, IngameUIWidget); IngameUI->AddToViewport(); IngameUI->SongTitle = NSLOCTEXT("Your Namespace", "123", "Test song"); IngameUI->LyricText = NSLOCTEXT("Your Namespace", "345", "This is a normal song lyric"); for (auto rowName : noteSource->GetRowNames()) noteTables.Add(noteSource->FindRow<FNoteTable>(rowName, ContextString)); for (auto currentNote : noteTables) { CreateNoteTime(*currentNote); } } void ANotePlayerController::Tick(float deltaTime) { Super::Tick(deltaTime); GEngine->AddOnScreenDebugMessage(-1, 0, FColor::Yellow, "Tests"); if (Notes.Num() > 0) { if (Notes[0]->flyProgress < -0.1 && !Notes[0]->bIsHold) { //GEngine->AddOnScreenDebugMessage(-1, 5, FColor::Blue, "Remove"); CreateGrade(EGrade::MISS); Notes[0]->RemoveFromParent(); Notes.RemoveAt(0); Combo = 0; } } } /////////////////////////////////////////////////////////////////////// void ANotePlayerController::SetupInputComponent() { Super::SetupInputComponent(); UInputComponent* Input = this->InputComponent; Input->BindAction("Circle", IE_Pressed, this, &ANotePlayerController::HitNote<EType::CIRCLE, false, true>); Input->BindAction("Circle", IE_Released, this, &ANotePlayerController::HitNote<EType::CIRCLE, false, false>); Input->BindAction("PAD-Right", IE_Pressed, this, &ANotePlayerController::HitNote<EType::CIRCLE, true, true>); Input->BindAction("PAD-Right", IE_Released, this, &ANotePlayerController::HitNote<EType::CIRCLE, true, false>); Input->BindAction("Cross", IE_Pressed, this, &ANotePlayerController::HitNote<EType::CROSS, false, true>); Input->BindAction("Cross", IE_Released, this, &ANotePlayerController::HitNote<EType::CROSS, false, false>); Input->BindAction("PAD-Down", IE_Pressed, this, &ANotePlayerController::HitNote<EType::CROSS, true, true>); Input->BindAction("PAD-Down", IE_Released, this, &ANotePlayerController::HitNote<EType::CROSS, true, false>); Input->BindAction("Square", IE_Pressed, this, &ANotePlayerController::HitNote<EType::SQUARE, false, true>); Input->BindAction("Square", IE_Released, this, &ANotePlayerController::HitNote<EType::SQUARE, false, false>); Input->BindAction("PAD-Left", IE_Pressed, this, &ANotePlayerController::HitNote<EType::SQUARE, true, true>); Input->BindAction("PAD-Left", IE_Released, this, &ANotePlayerController::HitNote<EType::SQUARE, true, false>); Input->BindAction("Triangle", IE_Pressed, this, &ANotePlayerController::HitNote<EType::TRIANGLE, false, true>); Input->BindAction("Triangle", IE_Released, this, &ANotePlayerController::HitNote<EType::TRIANGLE, false, false>); Input->BindAction("PAD-Up", IE_Pressed, this, &ANotePlayerController::HitNote<EType::TRIANGLE, true, true>); Input->BindAction("PAD-Up", IE_Released, this, &ANotePlayerController::HitNote<EType::TRIANGLE, true, false>); Input->BindAction("RIGHT_Flick", IE_Pressed, this, &ANotePlayerController::HitNote<EType::STAR, false, true>); Input->BindAction("RIGHT_Flick", IE_Released, this, &ANotePlayerController::HitNote<EType::STAR, false, false>); Input->BindAction("LEFT_FLICK", IE_Pressed, this, &ANotePlayerController::HitNote<EType::STAR, true, true>); Input->BindAction("LEFT_FLICK", IE_Released, this, &ANotePlayerController::HitNote<EType::STAR, true, false>); } /////////////////////////////////////////////////////////////////////// void ANotePlayerController::CreateNoteTime(FNoteTable noteData) { FTimerHandle NoteCreateHandler; FTimerHandle NotePlayHandler; FTimerDelegate TimeDel; TimeDel.BindUFunction(this, FName("CreateNote"), noteData); GetWorldTimerManager().SetTimer(NoteCreateHandler, TimeDel, noteData.timestamp, false); GetWorldTimerManager().SetTimer(NotePlayHandler, this, &ANotePlayerController::HitNote, noteData.timestamp + noteData.timeout, false); } void ANotePlayerController::CreateNote(FNoteTable noteData) { auto type = noteData.type; auto timeout = noteData.timeout; auto position = FVector2D(noteData.posX, noteData.posY); UWidgetNoteBase* note = CreateWidget<UWidgetNoteBase>(this, CircleWidget); switch (type) { case EType::CIRCLE: note = CreateWidget<UWidgetNoteBase>(this, CircleWidget); break; case EType::CIRCLE_DOUBLE: note = CreateWidget<UWidgetNoteBase>(this, CircleDoubleWidget); break; case EType::CIRCLE_HOLD: note = CreateWidget<UWidgetNoteBase>(this, CircleHoldWidget); break; case EType::CROSS: note = CreateWidget<UWidgetNoteBase>(this, CrossWidget); break; case EType::CROSS_DOUBLE: note = CreateWidget<UWidgetNoteBase>(this, CrossDoubleWidget); break; case EType::SQUARE: note = CreateWidget<UWidgetNoteBase>(this, SquareWidget); break; case EType::SQUARE_DOUBLE: note = CreateWidget<UWidgetNoteBase>(this, SquareDoubleWidget); break; case EType::TRIANGLE: note = CreateWidget<UWidgetNoteBase>(this, TriangleWidget); break; case EType::TRIANGLE_DOUBLE: note = CreateWidget<UWidgetNoteBase>(this, TriangleDoubleWidget); break; case EType::STAR: note = CreateWidget<UWidgetNoteBase>(this, StarWidget); break; case EType::LINKED_STAR: note = CreateWidget<UWidgetNoteBase>(this, StarWidget); break; case EType::LINKED_STAR_END: note = CreateWidget<UWidgetNoteBase>(this, StarWidget); break; case EType::STAR_DOUBLE: note = CreateWidget<UWidgetNoteBase>(this, StarDoubleWidget); break; default: note = CreateWidget<UWidgetNoteBase>(this, CircleWidget); break; } note->type = type; if (type == EType::CIRCLE_HOLD || type == EType::CROSS_HOLD || type == EType::SQUARE_HOLD || type == EType::TRIANGLE_HOLD) note->bIsHold = true; if (noteData.bIsHoldEnd) note->bIsHold = false; note->bIsHold = false; switch (type) { case EType::CIRCLE_HOLD: type = EType::CIRCLE; break; case EType::CROSS_HOLD: type = EType::CROSS; break; case EType::SQUARE_HOLD: type = EType::SQUARE; break; case EType::TRIANGLE_HOLD: type = EType::TRIANGLE; break; } if (type == EType::LINKED_STAR || type == EType::LINKED_STAR_END || type == EType::CHANCE_STAR) note->type = EType::STAR; if (type == EType::CIRCLE_HOLD || type == EType::CROSS_HOLD || type == EType::SQUARE_HOLD || type == EType::TRIANGLE_HOLD) note->type = EType::CIRCLE; note->entryAngle = noteData.entryAngle; note->timeOut = timeout; note->AddToViewport(); note->SetPosition(position); Notes.Add(note); } void ANotePlayerController::HitNote() { IConsoleManager::Get().RegisterConsoleVariable(TEXT("AutoPlay"), 0, TEXT("Playes the incoming notes as cool.\n") TEXT("0 = Normal play") TEXT("1 = Autoplay"), ECVF_Cheat); static const auto CVar = IConsoleManager::Get().FindConsoleVariable(TEXT("AutoPlay")); auto bAutoPlayNotes = CVar->GetInt(); if (Notes.Num() != 0 && bAutoPlayNotes == 1) { noteAudioComponent->Play(); HitNoteBurst = CreateWidget<UUserWidget>(this, HitNoteWidget); HitNoteBurst->AddToViewport(); HitNoteBurst->SetPositionInViewport(Notes[0]->position, false); ++Combo; CreateGrade(EGrade::COOL); DestroyNote(); } } void ANotePlayerController::OnHitNote(EType type) { noteAudioComponent->Play(); if (Notes.Num() != 0) { bool typeCondition = Notes[0]->type == type; switch (type) { case EType::CIRCLE_DOUBLE: typeCondition = typeCondition || Notes[0]->type == EType::CIRCLE; break; case EType::CROSS_DOUBLE: typeCondition = typeCondition || Notes[0]->type == EType::CROSS; break; case EType::SQUARE_DOUBLE: typeCondition = typeCondition || Notes[0]->type == EType::SQUARE; break; case EType::TRIANGLE_DOUBLE: typeCondition = typeCondition || Notes[0]->type == EType::TRIANGLE; break; case EType::STAR_DOUBLE: typeCondition = typeCondition || Notes[0]->type == EType::STAR; break; } bool bIsDouble = Notes[0]->type == EType::CIRCLE_DOUBLE || Notes[0]->type == EType::CROSS_DOUBLE || Notes[0]->type == EType::SQUARE_DOUBLE || Notes[0]->type == EType::TRIANGLE_DOUBLE; //DIVA COOL=0.03 FINE=0.07 SAFE=0.10 SAD=0.13 float hitTime = Notes[0]->flyProgress; int coolScore = 200; int goodScore = 200; if (typeCondition && hitTime <= 0.13) { if (abs(hitTime) <= 0.03) { CreateGrade(EGrade::COOL); score += coolScore; } else if (abs(hitTime) <= 0.07) { CreateGrade(EGrade::FINE); } else if (abs(hitTime) <= 0.10) { CreateGrade(EGrade::SAFE); } else if (abs(hitTime) <= 0.13) { CreateGrade(EGrade::BAD); } else { CreateGrade(EGrade::MISS); } HitNoteBurst = CreateWidget<UUserWidget>(this, HitNoteWidget); HitNoteBurst->AddToViewport(); HitNoteBurst->SetPositionInViewport(Notes[0]->position, false); ++Combo; DestroyNote(); } /* if (Notes[0]->flyProgress < 0.035 && typeCondition) { HitNote(); return; } else if (Notes[0]->flyProgress < 0.035 && !bIsDouble) { CreateGrade(EGrade::MISS); DestroyNote(); } */ } } void ANotePlayerController::DestroyNote(int NoteIndex) { if (Notes.Num() > NoteIndex) { Notes[NoteIndex]->RemoveFromParent(); Notes.RemoveAt(NoteIndex); } } void ANotePlayerController::CreateGrade(EGrade grade) { if (NoteGrade) { NoteGrade->RemoveFromParent(); } NoteGrade = CreateWidget<UWidgetNoteGradeBase>(this, GradeWidget); if (grade == EGrade::MISS) Combo = 0; NoteGrade->combo = Combo; NoteGrade->grade = grade; NoteGrade->AddToViewport(); NoteGrade->SetPositionInViewport(Notes[0]->position, false); }
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class Solution { public: vector<Interval> merge(vector<Interval>& intervals) { vector<Interval> ret; if(intervals.empty()) return ret; sort(intervals.begin(),intervals.end(),cmp); ret.push_back(intervals[0]); for(int i=1; i<intervals.size(); ++i){ if(ret.back().end < intervals[i].start){ ret.push_back(intervals[i]); }else{ ret.back().end = max(ret.back().end,intervals[i].end); } } return ret; } static const bool cmp(const Interval &T1,const Interval &T2){ return T1.start <T2.start; } };
#pragma once #include "ofMain.h" #include <kinect.h> #include <Kinect.Face.h> #include <Windows.h> #include "ofxOpenCv.h" #include <iostream> #include <vector> template<class Interface> inline void SafeRelease( Interface *& pInterfaceToRelease ) { if( pInterfaceToRelease != NULL ){ pInterfaceToRelease->Release(); pInterfaceToRelease = NULL; } } static const DWORD c_FaceFrameFeatures = FaceFrameFeatures::FaceFrameFeatures_BoundingBoxInColorSpace | FaceFrameFeatures::FaceFrameFeatures_PointsInColorSpace | FaceFrameFeatures::FaceFrameFeatures_RotationOrientation | FaceFrameFeatures::FaceFrameFeatures_Happy | FaceFrameFeatures::FaceFrameFeatures_RightEyeClosed | FaceFrameFeatures::FaceFrameFeatures_LeftEyeClosed | FaceFrameFeatures::FaceFrameFeatures_MouthOpen | FaceFrameFeatures::FaceFrameFeatures_MouthMoved | FaceFrameFeatures::FaceFrameFeatures_LookingAway | FaceFrameFeatures::FaceFrameFeatures_Glasses | FaceFrameFeatures::FaceFrameFeatures_FaceEngagement; class KinectWrapper { public: KinectWrapper(); ~KinectWrapper(); bool initEverything(); bool openKinect(); bool openColorStream(); bool openDepthStream(); bool openBodyStream(); bool openFaceStream(); bool openHdFaceStream(); void updateColorFrame(); bool updateDepthFrame(); void updateSkeleton(); Joint * getJointData( unsigned int bodyIndex, JointType jointType ); void updateFace(); IFaceFrame * getFaceFrame( unsigned int faceId ); IFaceFrameResult * getFaceFrameResult( unsigned int faceId ); void releaseFaceFrame( unsigned int faceId ); void releaseFaceFrameResult( unsigned int faceId ); void updateHdFace(); IHighDefinitionFaceFrame * getHdFaceFrame( unsigned int faceId ); void releaseHdFaceFrame( unsigned int faceId ); IKinectSensor * pSensor; // color IColorFrameSource * pColorSource; IColorFrameReader * pColorReader; IFrameDescription * pColorDescription; //IColorFrame * pColorFrame; int colorWidth, colorHeight, colorBufferSize; cv::Mat * colorBufferMat, *colorMat; ofxCvColorImage colorscaleImage; // depth IDepthFrameSource* pDepthSource; IDepthFrameReader* pDepthReader; IFrameDescription* pDepthDescription; int depthWidth, depthHeight; unsigned int depthBufferSize; cv::Mat * bufferMat, *depthMat; ofxCvGrayscaleImage grayscaleImage; // body IBodyFrameSource* pBodySource; IBodyFrameReader* pBodyReader; IBodyFrame * pBodyFrame; IBody* pBodies[ BODY_COUNT ]; Joint * pJoints[ BODY_COUNT ][ JointType::JointType_Count ]; HRESULT UpdateBodyData( IBody** ppBodies ); bool pHaveBodyData; // face IFaceFrameSource* pFaceSource[ BODY_COUNT ]; IFaceFrameReader *pFaceReader[ BODY_COUNT ]; IFaceFrame * pFaceFrame[ BODY_COUNT ]; IFaceFrameResult * pFaceFrameResult[ BODY_COUNT ]; // hd face IHighDefinitionFaceFrameSource *pHdFaceSource[ BODY_COUNT ]; IHighDefinitionFaceFrameReader *pHdFaceReader[ BODY_COUNT ]; IHighDefinitionFaceFrame * pHdFaceFrame[ BODY_COUNT ]; IFaceModelBuilder * pHdFaceModelBuilder[ BODY_COUNT ]; IFaceAlignment* pFaceAlignment[ BODY_COUNT ]; IFaceModel* pFaceModel[ BODY_COUNT ]; ICoordinateMapper* pCoordinateMapper; UINT32 pFaceVertexCount; std::vector< std::vector< float > > deformations; std::vector< CameraSpacePoint > pHdFacePoints[ BODY_COUNT ]; bool produce[ BODY_COUNT ]; };
#include "configwindow.h" #include "ui_configwindow.h" ConfigWindow::ConfigWindow(QWidget *parent) : QWidget(parent), ui(new Ui::ConfigWindow) { ui->setupUi(this); } ConfigWindow::~ConfigWindow() { delete ui; }
#include <iostream> #include <vector> #include <algorithm> using namespace std; int n, m, ans1, ans2, ans3; vector<pair<int, int>> v; bool compSet(const pair<int, int> &pa, const pair<int, int> &pb){ return pa.first < pb.first; } bool compOne(const pair<int, int> &pa, const pair<int, int> &pb){ return pa.second < pb.second; } int main(){ ios_base::sync_with_stdio(false); cin.tie(0); cin >> n >> m; for(int i = 0; i < m; i++){ int a, b; cin >> a >> b; v.push_back(make_pair(a, b)); } sort(v.begin(), v.end(), compSet); ans3 = (n / 6 + 1) * v[0].first; ans1 = (n / 6) * v[0].first; sort(v.begin(), v.end(), compOne); ans1 += (n - (n / 6) * 6) * v[0].second; ans2 = n * v[0].second; int ans = (ans1 > ans2) ? ans2 : ans1; ans = (ans > ans3) ? ans3 : ans; cout << ans << '\n'; return 0; }
/*************************************************************************** * Sketch Name: Xively Publish * Description: This sketch illustrates how Arduino Yun can publish data to Xively channels * Created On: March 01, 2016 * Author: Adeel Javed * Book: Building Arduino Projects for the Internet of Things * Chapter: Chapter 12 - IoT Platforms * Website: http://codifythings.com **************************************************************************/ /*************************************************************************** * External Libraries **************************************************************************/ #include <Process.h> #include <YunClient.h> #include <HttpClient.h>; #include <Xively.h>; /*************************************************************************** * Internet Connectivity Setup - Variables & Functions **************************************************************************/ // Yun client already connected to the internet YunClient client; void printConnectionInformation() { // Initialize a new process Process wifiCheck; // Run Command wifiCheck.runShellCommand("/usr/bin/pretty-wifi-info.lua"); // Print Connection Information while (wifiCheck.available() > 0) { char c = wifiCheck.read(); Serial.print(c); } Serial.println("-----------------------------------------------"); Serial.println(""); } /*************************************************************************** * Sensor Setup - Variables & Functions **************************************************************************/ int MOISTURE_SENSOR_PIN = A0; float moistureSensorValue = 0.0; void readSensorData() { //Read Mositure Sensor Value moistureSensorValue = analogRead(MOISTURE_SENSOR_PIN); //Display Readings Serial.print("[INFO] Moisture Sensor Reading: "); Serial.println(moistureSensorValue); } /*************************************************************************** * Data Publish - Variables & Functions **************************************************************************/ // API Key - required for data upload char xivelyKey[] = "YOUR_API_KEY"; #define xivelyFeed 1725577605 // Feed ID char moistureSensorChannel[] = "SoilMoistureSensor1"; //Channel Name // Datastream/Channel IDs XivelyDatastream datastreams[] = { XivelyDatastream(moistureSensorChannel, strlen(moistureSensorChannel), DATASTREAM_FLOAT), }; // Create Feed XivelyFeed feed(xivelyFeed, datastreams, 1); // Number of Channels // in Datastream XivelyClient xivelyclient(client); void transmitData() { //Set Xively Datastream datastreams[0].setFloat(moistureSensorValue); //Transmit Data to Xively Serial.println("[INFO] Transmitting Data to Xively"); int ret = xivelyclient.put(feed, xivelyKey); Serial.print("[INFO] Xively Response (xivelyclient.put): "); Serial.println(ret); Serial.println("-----------------------------------------------"); } /*************************************************************************** * Standard Functions - setup(), loop() **************************************************************************/ void setup() { // Initialize serial port Serial.begin(9600); // Do nothing until serial monitor is opened while (!Serial); // Contact the Linux processor Bridge.begin(); // Print connection information printConnectionInformation(); } void loop() { readSensorData(); transmitData(); //Delay delay(6000); }
#pragma once #include "GameLogic.h" class GameLogic; class BallPhysics { GameLogic* gameLogic; Ogre::Vector3 position; Ogre::Vector3 speed; Ogre::Vector3 spin; Ogre::Vector3 gravity; bool out; public: BallPhysics(GameLogic* gameLogic); ~BallPhysics(); void update(float deltaT); void setSpeed(Ogre::Vector3 speed); void setPosition(Ogre::Vector3 position); void setSpin(Ogre::Vector3 spin); Ogre::Vector3 getPosition(); Ogre::Vector3 getSpeed(); bool isOverTable(); };
#include <iostream> #include <iomanip> #include <NTL/GF2X.h> #include <stdint.h> #include "xsadd.h" #include "xsadd.c" // to check static functions using namespace NTL; using namespace std; static void uztostring16(char * str, uz * x) { int p = 0; int first = 1; for (int i = UZ_ARRAY_SIZE - 1; i >= 0; i--) { if (first) { if (x->ar[i] != 0) { first = 0; sprintf(str, "%x", x->ar[i]); p = strlen(str); } } else { sprintf(str + p, "%04x", x->ar[i]); p = p + 4; } } if (first) { strcpy(str, "0"); } } //static const char * const characteristic_polynomial //= "100000000008101840085118000000001"; void xsadd_calculate_jump_polynomial_debug(char *jump_str, uint32_t mul_step, const char * base_step) { f2_polynomial jump_poly; f2_polynomial charcteristic; f2_polynomial tee; uz base; uz mul; uz step; char buff[200]; strtopolynomial(&charcteristic, characteristic_polynomial); clear(&tee); tee.ar[0] = 2; string16touz(&base, base_step); uint32touz(&mul, mul_step); uztostring16(buff, &mul); cout << "mul:" << buff << endl; uztostring16(buff, &base); cout << "base:" << buff << endl; uz_mul(&step, &mul, &base); uztostring16(buff, &step); cout << "step:" << buff << endl; polynomial_power_mod(&jump_poly, &tee, &step, &charcteristic); polynomialtostr(jump_str, &jump_poly); } void xsadd_jump_by_polynomial_debug(xsadd_t *xsadd, const char * jump_str) { f2_polynomial jump_poly; xsadd_t work_z; xsadd_t * work = &work_z; cout << "xsadd_jump_by_polynomial_debug: step1" << endl; *work = *xsadd; for (int i = 0; i < 4; i++) { work->state[i] = 0; } strtopolynomial(&jump_poly, jump_str); cout << "xsadd_jump_by_polynomial_debug: step2" << endl; char buff[200]; polynomialtostr(buff, &jump_poly); cout << "jump_poly:" << buff << endl; for (int i = 0; i < POLYNOMIAL_ARRAY_SIZE; i++) { for (int j = 0; j < 32; j++) { //cout << "(i,j) = (" << dec << i << "," << j << ")" << endl; uint32_t mask = 1 << j; if ((jump_poly.ar[i] & mask) != 0) { xsadd_add(work, xsadd); } xsadd_uint32(xsadd); } } cout << "xsadd_jump_by_polynomial_debug: step3" << endl; *xsadd = *work; } void xsadd_jump_debug(xsadd_t *xsadd, uint32_t mul_step, const char * base_step) { char jump_str[200]; cout << "step1" << endl; xsadd_calculate_jump_polynomial_debug(jump_str, mul_step, base_step); cout << "jump_str:" << jump_str << endl; cout << "step2" << endl; xsadd_jump_by_polynomial_debug(xsadd, jump_str); cout << "step3" << endl; } void test_xsadd_jump_debug() { const char * base_step = "0"; uint32_t step = 139; uint32_t seed = 1791095845; xsadd_t xsadd; xsadd_init(&xsadd, seed); xsadd_jump_debug(&xsadd, step, base_step); cout << "debug end" << endl; } int main() { test_xsadd_jump_debug(); }
#include "droute.h" #include <fstream> #include <iostream> #include "DataStructure.h" #define INF 9999 extern struct city graph; extern struct route line1[10]; extern struct route line2[10]; extern struct route temp; extern struct passenger passer; extern struct order *command,*end; extern int ll; int _min(int a,int b,int c) { int mini=INF; int k; for(int i=0;i<graph.edgnum[a][b];i++)//假设判断是正确的 if (graph.matrix[a][b][i].DeTime>=c&&(graph.matrix[a][b][i].DeTime-c)<mini) { mini = graph.matrix[a][b][i].DeTime-c; k = i; } else if(graph.matrix[a][b][i].DeTime<c&&(graph.matrix[a][b][i].DeTime+24-c)<mini) { mini = graph.matrix[a][b][i].DeTime+24-c; k = i; } if(mini!=INF) { temp.Artime=graph.matrix[a][b][k].ArTime; temp.tool=graph.matrix[a][b][k].tool; temp.finish=a; temp.Detime=graph.matrix[a][b][k].DeTime; } return mini==INF?INF:mini*(int)(graph.danger[a]*10); } void plan(int fi) { if(fi==passer.start) { line2[ll].finish=passer.start; line2[ll].Artime=0; } else { plan(line1[fi].finish); ll++; line2[ll].finish=fi; line2[ll].Artime=line1[fi].Artime; line2[ll].tool=line1[fi].tool;//到fi的交通工具是line1的tool以及出发时间和到达时间 line2[ll].Detime=line1[fi].Detime; }//逻辑是对的 } void design() { if(command->strategy==0) { int i,j,k; int min; int tmp; int flag[10]; // flag[i]=1表示"顶点vs"到"顶点i"的最短路径已成功获取。 int vs=passer.start; // 初始化 // int prev[10]; int dist[10]; for (i = 0; i < 10; i++) { flag[i] = 0; // 顶点i的最短路径还没获取到。 //prev[i] = 0; // 顶点i的前驱顶点为0。 dist[i] = _min(vs,i,0);// 顶点i的最短路径为"顶点vs"到"顶点i"的权。 line1[i].finish=vs;//顶点的前驱节点 if(dist[i]!=INF) { line1[i].Artime=temp.Artime; line1[i].tool=temp.tool; line1[i].Detime=temp.Detime; } } // 对"顶点vs"自身进行初始化 flag[vs] = 1; dist[vs] = 0; // 遍历G.vexnum-1次;每次找出一个顶点的最短路径。 for (i = 1; i <10; i++) { // 寻找当前最小的路径; // 即,在未获取最短路径的顶点中,找到离vs最近的顶点(k)。 min = INF; for (j = 0; j <10; j++) { if (flag[j]==0 && dist[j]<min) { min = dist[j]; k = j; } } // 标记"顶点k"为已经获取到最短路径 flag[k] = 1; // 修正当前最短路径和前驱顶点 // 即,当已经"顶点k的最短路径"之后,更新"未获取最短路径的顶点的最短路径和前驱顶点"。 for (j = 0; j < 10; j++) { if(graph.edgnum[k][j]==0) tmp=INF; else tmp=min+_min(k,j,line1[k].Artime); //防止溢出 if (flag[j] == 0 && (tmp < dist[j]) ) { dist[j] = tmp; //prev[j] = k; line1[j].finish=k; line1[j].Artime= temp.Artime; line1[j].tool=temp.tool; line1[j].Detime=temp.Detime; } } } int fi=command->finish; plan(fi); //没有写出风险值 } else { //限制时间策略 } }
/* * Copyright (C) 2018 David C. Harrison. All right reserved. * * You may not use, distribute, publish, or modify this code without * the express written permission of the copyright holder. https://classes.soe.ucsc.edu/cmps109/Spring18/SECURE/12.Distributed2.pdf https://classes.soe.ucsc.edu/cmps109/Spring18/SECURE/13.Distributed3.pdf https://classes.soe.ucsc.edu/cmps109/Spring18/SECURE/14.Distributed4.pdf */ #include "radix.h" #include <iostream> #include <string> #include <vector> #include <list> #include <thread> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <unistd.h> #include <netdb.h> #include <stdio.h> #include <stdlib.h> #include <strings.h> #include <string.h> const int R = 2 << 8; static int charAt(std::string s, int i){ if ((unsigned)i<s.length()) return s.at(i); return -1; } static void sort(std::vector<unsigned int> (&s), unsigned int aux[], int lo, int hi, int at){ if (hi<=lo) return; int count[R+2]; for (int i = 0; i < R+2; i++) count[i] = 0; for (int i = lo; i<=hi; ++i) count[charAt(std::to_string(s[i]), at)+2]++; for (int i = 0; i<R+1; ++i) count[i+1] += count[i]; for (int i = lo; i<=hi; ++i) aux[count[charAt(std::to_string(s[i]), at)+1]++] = s[i]; for (int i = lo; i<=hi; ++i) s[i] = aux[i-lo]; for (int r = 0; r<R; ++r) sort(s, aux, lo+count[r], lo+count[r+1]-1, at+1); } static void sort2(std::vector<unsigned int> (&s), int len){ unsigned int aux[len]; int lo = 0; int hi = len-1; int at = 0; sort(s, aux, lo, hi, at); } void ParallelRadixSort::msd(std::vector<std::reference_wrapper<std::vector<unsigned int>>> &lists, const unsigned int cores) { std::vector<std::thread*> threads; unsigned int threadTotal = 0; for (std::vector<unsigned int> &list : lists){ threads.push_back(new std::thread{[&list]{ sort2(list, list.size()); }}); threadTotal++; if (threads.size() == cores || threadTotal == lists.size()){ for (std::thread *thread : threads) thread->join(); threads.clear(); } } } RadixServer::RadixServer(const int port, const unsigned int cores) { std::vector<unsigned int> myList; int sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) exit(-1); struct sockaddr_in server_addr; bzero((char*) &server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = INADDR_ANY; server_addr.sin_port = htons(port); if (bind(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) exit (-1); listen(sockfd, 5); struct sockaddr_in client_addr; socklen_t len = sizeof(client_addr); int newsockfd = accept(sockfd, (struct sockaddr *) &client_addr, &len); if (newsockfd < 0) exit (-1); for (;;){ unsigned int test = 0; int rc = recv(newsockfd, (void*)&test, sizeof(unsigned int), 0); unsigned int local = ntohl(test); unsigned int zero = htonl(0); if (rc < 0){ printf("What the"); } else if (rc == 0){ close(newsockfd); close(sockfd); break; } if (local != 0){ myList.push_back(local); } if (local == 0){ sort2(myList, myList.size()); for (unsigned int i = 0; i<myList.size(); i++){ unsigned int bruh = htonl(myList[i]); send(newsockfd, (void*)&bruh, sizeof(unsigned int), 0); } send(newsockfd, (void*)&zero, sizeof(unsigned int), 0); myList.clear(); } } } void RadixClient::msd(const char *hostname, const int port, std::vector<std::reference_wrapper<std::vector<unsigned int>>> &lists) { int sockfd = socket(AF_INET, SOCK_STREAM, 0); std::vector<unsigned int> myList; struct hostent *server = gethostbyname(hostname); if (server == NULL) exit (-1); struct sockaddr_in serv_addr; bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length); serv_addr.sin_port = htons(port); if (connect(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) exit (-1); for (unsigned int i = 0; i<lists.size(); i++){ for (unsigned int j = 0; j < lists[i].get().size(); j++){ unsigned int sentNum = htonl(lists[i].get()[j]); send(sockfd, (void*)&sentNum, sizeof(unsigned int), 0); } unsigned int zero = htonl(0); send(sockfd, (void*)&zero, sizeof(unsigned int), 0); for (;;){ unsigned int test = 0; int rc = recv(sockfd, (void*)&test, sizeof(unsigned int), 0); if (rc < 0 || test == 0){ break; } unsigned int local = ntohl(test); myList.push_back(local); } for (unsigned int k = 0; k < lists[i].get().size(); k++){ lists[i].get()[k] = myList[k]; } myList.clear(); } close(sockfd); }
#include <iostream> using namespace std; /* (3 p) 3. Fie lista simplu inlantuita C. Sa se distribuie elementele din C in doua liste simplu inlatuite A si B, astfel: A contine elementele de pe pozitiile impare din C, iar B contine elementele din C de pe pozitiile pare. Nu se va folosi memorie suplimentara. */ struct Element { Element *urm; int info; }; struct Lista { Element* primul = NULL; Element* ultimul = NULL; Lista() { if (!primul) return; if (primul == ultimul) { delete primul; primul = ultimul = NULL; return; } Element* precedent = primul; for (Element* element = primul->urm; element; element = element->urm) { delete precedent; precedent = element; } if (ultimul) delete ultimul; primul = ultimul = NULL; } void Adauga(int element) { Element* elementNou = new Element; elementNou->info = element; elementNou->urm = NULL; if (!primul && !ultimul) { primul = elementNou; ultimul = elementNou; } else { ultimul->urm = elementNou; ultimul = elementNou; } } void Afiseaza() { for (Element* element = primul; element; element = element->urm) cout<<element->info<<" "; cout<<endl; } }; int main() { Lista a, b, c; int n,i,k; cout<<"Cate elemente va avea lista C?\n"; cin>>n; for(int i=0;i<n;i++) { cout<<"Element ce urmeaza sa fie adaugat in lista C: "; cin>>k; c.Adauga(k); } cout<<"Lista C arata astfel: "; c.Afiseaza(); Element *elementC = c.primul; i=1; while (elementC) { if (i%2!=0) { a.Adauga(elementC->info); elementC = elementC->urm; } else { b.Adauga(elementC->info); elementC = elementC->urm; } i++; } cout<<"Lista A arata astfel: "; a.Afiseaza(); cout<<"Lista B arata astfel: "; b.Afiseaza(); return 0; }
#ifndef EDITORAPPLICATION_HPP #define EDITORAPPLICATION_HPP #include <QApplication> #include "LevelManager.hpp" #include "TextureManager.hpp" namespace Maint { class MainWindow; class EditorApplication : public QApplication { Q_OBJECT /** * @brief The application's main window. */ MainWindow* mainWindow; /** * @brief The application's level manager. */ LevelManager* levelManager; /** * @brief The application's texture manager. */ TextureManager* textureManager; public: explicit EditorApplication(int argc, char** argv, int flags = ApplicationFlags); /** * @return Returns the application's main window. */ MainWindow* GetMainWindow(); /** * @brief Returns the application's level manager. */ LevelManager* GetLevelManager(); /** * @brief Returns the application's texture manager. * @return */ TextureManager* GetTextureManager(); signals: public slots: }; } #endif // EDITORAPPLICATION_HPP
#include "graphics.hpp" std::map<std::string, shader_t> GFX_SHADERS; std::map<std::string, model_t> GFX_MODELS; std::map<std::string, texture_t> GFX_TEXTURES; void use_shader(shader_t *shader) { static shader_t *current_shader = NULL; assert(shader); if ( shader != current_shader ) { glUseProgram(shader->id); shader->in_use = true; if ( current_shader ) { current_shader->in_use = false; } current_shader = shader; } } GLint get_uniform_location(shader_t *shader, std::string name) { GLint location = -1; if ( shader->uniform_locations.find(name) == shader->uniform_locations.end() ) { location = glGetUniformLocation(shader->id, name.c_str()); shader->uniform_locations[name] = location; } else { location = shader->uniform_locations[name]; } return location; } void draw_model(model_t *model) { // glBindVertexArray(model->VAO); glDrawArrays(GL_TRIANGLES, 0, model->mesh.vertices.size()); // glBindVertexArray(0); } GLuint create_shader(GLenum shader_type, std::string shader_source) { GLuint shader = glCreateShader(shader_type); char *source = (char*)shader_source.c_str(); int size = shader_source.size(); glShaderSource(shader, 1, (GLchar **)&source, &size); glCompileShader(shader); int compilation_result = 0; glGetShaderiv(shader, GL_COMPILE_STATUS, &compilation_result); if ( compilation_result == GL_FALSE ) { #ifdef SLOW int log_length = 0; glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &log_length); std::vector<char> log(log_length); glGetShaderInfoLog(shader, log_length, NULL, (GLchar *)(&log[0])); std::cout << "[ERROR] shader compilation error in shader " << shader_type << std::endl << &log[0] << std::endl; #endif return 0; } return shader; } void create_shader_program(shader_t *shader, char const * vertex_shader_path, char const * fragment_shader_path) { #ifdef SLOW std::cout << "creating shader with: " << vertex_shader_path << " " << fragment_shader_path << std::endl; #endif std::string vertex_shader_source = read_file(vertex_shader_path); std::string fragment_shader_source = read_file(fragment_shader_path); #ifdef SLOW std::cout << "compiling vertex shader: " << std::endl << vertex_shader_source << std::endl; #endif GLuint vertex_shader = create_shader(GL_VERTEX_SHADER, vertex_shader_source); assert(vertex_shader); #ifdef SLOW std::cout << "compiling fragment shader: " << std::endl << fragment_shader_source << std::endl; #endif GLuint fragment_shader = create_shader(GL_FRAGMENT_SHADER, fragment_shader_source); assert(fragment_shader); GLuint program = glCreateProgram(); glAttachShader(program, vertex_shader); glAttachShader(program, fragment_shader); glLinkProgram(program); int link_result = 0; glGetProgramiv(program, GL_LINK_STATUS, &link_result); if ( link_result == GL_FALSE ) { #ifdef SLOW int log_length = 0; glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_length); std::vector<char> log(log_length); glGetProgramInfoLog(program, log_length, NULL, &log[0]); std::cout << "[ERROR] shader link error in shader: " << &log[0] << std::endl; #endif return; } assert(shader); shader->id = program; shader->in_use = false; #ifdef SLOW std::cout << "shader compile successfully" << std::endl; #endif return; } void create_model(model_t *model, mesh_t mesh, shader_t *shader, texture_t *texture) { static int ids = 0; assert(model); assert(shader); model->id = ++ids; model->mesh = mesh; model->shader = shader; model->texture = texture; glGenVertexArrays(1, &model->VAO); #ifdef SLOW if ( !model->VAO ) { std::cout << "[ERROR] Could not create VAO for model object" << std::endl; assert(model->VAO); } #endif assert(model->VAO); glBindVertexArray(model->VAO); glGenBuffers(1, &model->VBO); #ifdef SLOW if ( !model->VBO ) { std::cout << "[ERROR] Could not create VBO for model object" << std::endl; assert(model->VBO); } #endif assert(model->VAO); glBindBuffer(GL_ARRAY_BUFFER, model->VBO); glBufferData(GL_ARRAY_BUFFER, (model->mesh.vertices.size()*GFX_VERTEX_SIZE), &model->mesh.vertices[0], GL_STATIC_DRAW); glEnableVertexAttribArray(SHADER_ATTRIBUTE_POSITION); glEnableVertexAttribArray(SHADER_ATTRIBUTE_NORMAL); glEnableVertexAttribArray(SHADER_ATTRIBUTE_COLOR); glEnableVertexAttribArray(SHADER_ATTRIBUTE_UV); #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Winvalid-offsetof" glVertexAttribPointer(SHADER_ATTRIBUTE_POSITION, 3, GL_FLOAT, GL_FALSE, GFX_VERTEX_SIZE, (GLvoid*)offsetof(vertex_definition_t, position)); glVertexAttribPointer(SHADER_ATTRIBUTE_NORMAL, 3, GL_FLOAT, GL_FALSE, GFX_VERTEX_SIZE, (GLvoid*)offsetof(vertex_definition_t, normal)); glVertexAttribPointer(SHADER_ATTRIBUTE_COLOR, 3, GL_FLOAT, GL_FALSE, GFX_VERTEX_SIZE, (GLvoid*)offsetof(vertex_definition_t, color)); glVertexAttribPointer(SHADER_ATTRIBUTE_UV, 2, GL_FLOAT, GL_FALSE, GFX_VERTEX_SIZE, (GLvoid*)offsetof(vertex_definition_t, uv)); #pragma GCC diagnostic pop glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); } void create_texture(texture_t *texture, char const * image_path) { SDL_Surface *tmp_sdl_surface = IMG_Load(image_path); create_texture_raw(texture, tmp_sdl_surface->w, tmp_sdl_surface->h, tmp_sdl_surface->pixels); } void create_texture_raw(texture_t *texture, unsigned long width, unsigned long height, GLvoid *data, GLenum ex_internal_format, GLenum ex_format, GLenum ex_type, GLenum ex_wrap ) { assert(texture); glActiveTexture(GL_TEXTURE0); glGenTextures(1, &texture->id); assert(texture->id); texture->width = width; texture->height = height; glBindTexture(GL_TEXTURE_2D, texture->id); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); // NOTE(Brett):assume bytes are in the corect order for now glTexImage2D(GL_TEXTURE_2D, 0, ex_internal_format, texture->width, texture->height, 0, ex_format, ex_type, data); glBindTexture(GL_TEXTURE_2D, 0); } void use_texture(texture_t *texture, GLint unit) { assert(texture); glActiveTexture(GL_TEXTURE0+unit); glBindTexture(GL_TEXTURE_2D, texture->id); }
#if !defined(_PSP_VER) #include "Vector2.h" Vector2& Vector2::operator =(const Vector2 &rhs) { _vec = rhs._vec; return *this; } Vector2 Vector2::operator +(const Vector2& rhs) const { Vector2 ret; D3DXVec2Add( &ret._vec, &_vec, &rhs._vec ); return ret; } Vector2 Vector2::operator- (const Vector2& rhs) const { Vector2 ret; D3DXVec2Subtract( &ret._vec, &_vec, &rhs._vec ); return ret; } Vector2 Vector2::operator* (const float scalar) const { Vector2 ret; D3DXVec2Scale( &ret._vec, &_vec, scalar ); return ret; } Vector2& Vector2::operator+= (const Vector2& rhs) { D3DXVec2Add( &_vec, &_vec, &rhs._vec ); return *this; } Vector2& Vector2::operator-= (const Vector2& rhs) { D3DXVec2Subtract( &_vec, &_vec, &rhs._vec ); return *this; } Vector2& Vector2::operator*= (const float scalar) { D3DXVec2Scale( &_vec, &_vec, scalar ); return *this; } bool Vector2::operator== (const Vector2& rhs) { if ( _vec == rhs._vec ) return true; else return false; } bool Vector2::operator!= (const Vector2& rhs) { return !( *this == rhs ); } void Vector2::Add(const Vector2& rhs) { _vec += rhs._vec; } void Vector2::Add(const Vector2& vec1, const Vector2& vec2, Vector2& out) { D3DXVec2Add( &out._vec, &vec1._vec, &vec2._vec ); } void Vector2::Subtract(const Vector2& rhs) { _vec = _vec - rhs._vec; } void Vector2::Subtract(const Vector2& vec1, const Vector2& vec2, Vector2& out) { D3DXVec2Subtract( &out._vec, &vec1._vec, &vec2._vec ); } void Vector2::Multiply(const Vector2& rhs) { _vec.x *= rhs._vec.x; _vec.y *= rhs._vec.y; } void Vector2::Multiply(float scalar) { _vec *= scalar; } void Vector2::Multiply(const Vector2& vec1, const Vector2& vec2, Vector2& out) { out._vec.x = vec1._vec.x * vec2._vec.x; out._vec.y = vec1._vec.y * vec2._vec.y; } void Vector2::Multiply(float scalar, Vector2& in, Vector2& out) { out._vec = in._vec * scalar; } void Vector2::Divide(const Vector2& rhs) { _vec.x /= rhs._vec.x; _vec.y /= rhs._vec.y; } void Vector2::Divide(const Vector2& vec1, const Vector2& vec2, Vector2& out) { out._vec.x = vec1._vec.x / vec2._vec.x; out._vec.y = vec1._vec.y / vec2._vec.y; } void Vector2::Normalize() { D3DXVec2Normalize( &_vec, &_vec ); } void Vector2::Normalize(const Vector2& in, Vector2& out) { D3DXVec2Normalize( &out._vec, &in._vec ); } float Vector2::MagnitudeSquare(void) { return D3DXVec2LengthSq( &_vec ); } float Vector2::MagnitudeSquare(const Vector2& rhs) { return D3DXVec2LengthSq( &rhs._vec ); } Vector2 Vector2::Lerp(Vector2 &start, Vector2 &end, float amount) { Vector2 ret; D3DXVec2Lerp( &ret._vec, &start._vec, &end._vec, amount ); return ret; } void Vector2::Lerp(Vector2 &start, Vector2 &end, float amount, Vector2 &out) { D3DXVec2Lerp( &out._vec, &start._vec, &end._vec, amount ); } float Vector2::DotProduct(const Vector2& rhs) { return D3DXVec2Dot( &_vec, &rhs._vec ); } float Vector2::DotProduct(const Vector2& vec1, const Vector2& vec2) { return D3DXVec2Dot( &vec1._vec, &vec2._vec ); } void Vector2::Zero() { _vec.x = 0; _vec.y = 0; } void Vector2::Zero(Vector2 &out) { out._vec.x = 0; out._vec.y = 0; } #endif
#include<bits/stdc++.h> #define rep(i,n) for (int i =0; i <(n); i++) using namespace std; using ll = long long; int main(){ int a,b; cin >> a >> b; char a1,b1; a1 = a + '0'; b1 = b + '0'; string x; rep(i,b)x.push_back(a1); string y; rep(i,a)y.push_back(b1); if( x > y)cout << y << endl; else cout << x << endl; return 0; }
#include <iostream> #include <cstring> #include <string> #include <vector> #include <algorithm> #define MAX 53 #define MAXLINE 2503 int n, m, X[MAX][MAX], Y[MAX][MAX], d[MAXLINE]; char map[MAX][MAX]; std::vector<int> adj[MAXLINE]; bool check[MAXLINE]; bool dfs(int i) { if(check[i]) { return false; } check[i] = true; for(auto j : adj[i]) { if(d[j] == 0 || dfs(d[j])) { d[j] = i; return true; } } return false; } int main() { std::cin.sync_with_stdio(false); std::cin.tie(NULL); std::cin >> n >> m; for(int i = 1; i <= n; i++) { std::string tmp; std::cin >> tmp; for(int j = 1; j <= m; j++) { map[i][j] = tmp[j - 1]; } } int L_MAX = 0; for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { if(map[i][j] == '.') { continue; } if(map[i][j - 1] != '*') { L_MAX++; } X[i][j] = L_MAX; } } int R_MAX = 0; for(int j = 1; j <= m; j++) { for(int i = 1; i <= n; i++) { if(map[i][j] == '.') { continue; } if(map[i - 1][j] != '*') { R_MAX++; } Y[i][j] = R_MAX; } } for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { if(map[i][j] == '.') { continue; } adj[X[i][j]].push_back(Y[i][j]); } } int ans = 0; for(int i = 1; i <= L_MAX; i++) { std::memset(check, 0, sizeof(check)); if(dfs(i)) { ans++; } } std::cout << ans << '\n'; return 0; }
#include "../head/load_data.h" #include <opencv2/opencv.hpp> //包含头文件 #include <iostream> #include"../head/QRCodeDrawer.h" #include"../head/Video.h" void usage(); int main(int argc, char* argv[]) { if (argc != 4) { usage(); return 1; } load_data load_data; QRCodeDrawer Drawer; string input_file = argv[1]; string video_name = argv[2]; string len = argv[3]; int length =stoi(len); cout << "正在读取文件..." << endl; load_data.load_from(input_file,length); string data = load_data.get_data(); cout << "文件读取完成!" << endl; Drawer.set_data(load_data.get_data()); cout << "正在生成帧..." << endl; Drawer.generate_code("./"); cout << "帧生成完成!" << endl; cout << "正在生成视频..." << endl; Image_TO_Video(Drawer.getCode_num(), video_name, length); cout << "视频生成完毕!" << endl; //namedWindow("test opencv setup", WINDOW_AUTOSIZE); //创建窗口,自动大小 //imshow("test opencv setup", code); //显示图像到指定的窗口 //waitKey(); } void usage() { cout << "========================================================================================================="<<endl; cout << "请正确使用编码程序:encode input_file_name video_file_name video_length(ms)" << endl; cout << "For example:encode in.bin in.mp4 1000" << endl; cout << "本程序将生成一个名为source.bin的文件作为比对标准,在解码时请将其放入decode.exe的同一目录下" << endl; cout << "========================================================================================================="<<endl; }