text
stringlengths 8
6.88M
|
|---|
/*****************************************************************************************************************
* File Name : mergesort.h
* File Location : C:\Users\AVINASH\Desktop\CC++\Programming\src\tutorials\nptel\DSAndAlgo\lecture22\mergesort.h
* Created on : Jan 15, 2014 :: 2:01:45 AM
* Author : AVINASH
* Testing Status : TODO
* URL : TODO
*****************************************************************************************************************/
/************************************************ Namespaces ****************************************************/
using namespace std;
using namespace __gnu_cxx;
/************************************************ User Includes *************************************************/
#include <string>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <ctime>
#include <list>
#include <map>
#include <set>
#include <bitset>
#include <functional>
#include <utility>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string.h>
#include <hash_map>
#include <stack>
#include <queue>
#include <limits.h>
#include <programming/ds/tree.h>
#include <programming/ds/linkedlist.h>
#include <programming/utils/treeutils.h>
#include <programming/utils/llutils.h>
/************************************************ User defined constants *******************************************/
#define null NULL
/************************************************* Main code ******************************************************/
#ifndef MERGESORT_H_
#define MERGESORT_H_
void mergeStep(vector<int> userInput,unsigned int startIndex,unsigned int middleIndex,unsigned int endIndex){
if(startIndex > middleIndex && middleIndex+1 > endIndex){
return;
}
vector<int> auxSpace(userInput.size());
unsigned int firstArrayStartIndex = startIndex,secondArrayStartIndex = middleIndex+1;
while(firstArrayStartIndex <= middleIndex && secondArrayStartIndex <= endIndex){
if(userInput[firstArrayStartIndex] < userInput[secondArrayStartIndex]){
auxSpace[firstArrayStartIndex] = userInput[firstArrayStartIndex];
firstArrayStartIndex++;
}else{
auxSpace[secondArrayStartIndex] = userInput[secondArrayStartIndex];
secondArrayStartIndex++;
}
}
while(firstArrayStartIndex <= middleIndex){
auxSpace[firstArrayStartIndex] = userInput[firstArrayStartIndex];
}
while(secondArrayStartIndex <= endIndex){
auxSpace[secondArrayStartIndex] = userInput[secondArrayStartIndex];
}
for(unsigned int counter = startIndex;counter <= endIndex;counter++){
userInput[counter] = auxSpace[counter];
}
}
void mergeSort(vector<int> userInput,unsigned int startIndex,unsigned int endIndex){
if(startIndex > endIndex || endIndex - startIndex == 0){
return;
}
if(endIndex - startIndex == 1){
swap(userInput[startIndex],userInput[endIndex]);
return;
}
unsigned int middleIndex = (startIndex + endIndex)/2;
mergeSort(userInput,startIndex,middleIndex);
mergeSort(userInput,middleIndex+1,endIndex);
mergeStep(userInput,startIndex,middleIndex,endIndex);
}
#endif /* MERGESORT_H_ */
/************************************************* End code *******************************************************/
|
#include "Cannon.h"
#include "Bullet.h"
#include "GameLayer.h"
USING_NS_CC;
Cannon* Cannon::createWithCannonType(int cannonType, GameLayer *pGameLayer, cocos2d::SpriteBatchNode *pBatchNode){
Cannon* pCannon = new Cannon(cannonType,pGameLayer);
if(pCannon && pCannon->initWithCannonType(pBatchNode))
{
pCannon->autorelease();
return pCannon;
}else
{
CC_SAFE_DELETE(pCannon);
return NULL;
}
}
Cannon::Cannon(int cannonType,GameLayer *gameLayer):
m_nCannonType(cannonType),m_pGameLayer(gameLayer),
m_fRotation(0.0f)
{
}
Cannon::~Cannon()
{
this->m_pSprite->removeFromParentAndCleanup(true);
}
int Cannon::getConnonType()
{
return this->m_nCannonType;
}
bool Cannon::initWithCannonType( cocos2d::SpriteBatchNode *pBatchNode)
{
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();
String* cannonName=String::createWithFormat("actor_cannon1_%d1.png",m_nCannonType);
this->m_pSprite=CCSprite::createWithSpriteFrameName(cannonName->getCString());
this->m_pSprite->setPosition(ccp(origin.x+visibleSize.width/2+80, 50));
pBatchNode->addChild(m_pSprite);
return true;
}
void Cannon::rotateToPoint(cocos2d::Point ptTo)
{
Point ptFrom=m_pSprite->getPosition();
float angle=atan2f(ptTo.y-ptFrom.y,ptTo.x-ptFrom.x)/M_PI * 180.0f;
this->setRotation(90.0f-angle);
this->m_pDirection= ptTo;
}
void Cannon::setRotation(float rotation)
{
m_fRotation=rotation;
float absf_rotation=fabsf(m_fRotation-this->m_pSprite->getRotation());
float duration=absf_rotation/180.0f*0.2f;
FiniteTimeAction *pAction = RotateTo::create(duration, m_fRotation);
this->m_pSprite->runAction(pAction);
}
void Cannon::fire()
{
String *pFireStartFrameName=String::createWithFormat("actor_cannon1_%d1.png",this->m_nCannonType);
String *pFireEndFrameName=String::createWithFormat("actor_cannon1_%d2.png",this->m_nCannonType);
SpriteFrame *pFireStartFrame=SpriteFrameCache::getInstance()->spriteFrameByName(pFireStartFrameName->getCString());
SpriteFrame *pFireEndFrame=SpriteFrameCache::getInstance()->spriteFrameByName(pFireEndFrameName->getCString());
Vector<SpriteFrame*> spf_vec;
spf_vec.pushBack(pFireStartFrame);
spf_vec.pushBack(pFireEndFrame);
Animation *pAnimationFire=Animation::createWithSpriteFrames(spf_vec,0.1f,1);
pAnimationFire->setRestoreOriginalFrame(true);
FiniteTimeAction *pAction=CCAnimate::create(pAnimationFire);
this->m_pSprite->runAction(pAction);
Bullet *pBullet = Bullet::createWithBulletType(m_nCannonType, this->m_pGameLayer, this->m_pGameLayer->getBatchNodeFish2AndBullets(), this->m_pGameLayer->getBatchNodeFish3AndNets());
pBullet->shootTo(this->m_pDirection);
}
|
#include "_pch.h"
#include "BaseOkCancelDialog.h"
using namespace wh;
using namespace wh::view;
//---------------------------------------------------------------------------
void DlgBaseOkCancel::Create()
{
wxSizer* szrMain= new wxBoxSizer( wxVERTICAL );
m_sdbSizer = new wxStdDialogButtonSizer();
m_btnOK = new wxButton( this, wxID_OK);//,"Сохранить и закрыть" );
m_sdbSizer->AddButton( m_btnOK );
m_btnCancel = new wxButton( this, wxID_CANCEL);//," Закрыть" );
m_sdbSizer->AddButton( m_btnCancel );
m_sdbSizer->Realize();
szrMain->Add( m_sdbSizer, 0, wxALL|wxEXPAND, 10 );
this->SetSizer( szrMain );
}
//---------------------------------------------------------------------------
DlgBaseOkCancel::DlgBaseOkCancel(std::function<wxWindow*(wxWindow*)> mainPanelCreate,
wxWindow* parent,
wxWindowID id ,
const wxString& title,
const wxPoint& pos ,
const wxSize& size,
long style,
const wxString& name )
:wxDialog(parent,id,title,pos,size,style,name)
, mMainPanel(nullptr)
{
Create();
if( !mainPanelCreate )
{
mMainPanel = mainPanelCreate(this);
if (mMainPanel)
GetSizer()->Insert(0, mMainPanel, 1, wxALL | wxEXPAND, 0);
Layout();
}
}
//---------------------------------------------------------------------------
DlgBaseOkCancel::DlgBaseOkCancel( wxWindow* parent,
wxWindowID id ,
const wxString& title,
const wxPoint& pos ,
const wxSize& size,
long style,
const wxString& name )
:wxDialog(parent,id,title,pos,size,style,name)
, mMainPanel(nullptr)
{
Create();
}
//---------------------------------------------------------------------------
void DlgBaseOkCancel::InsertMainWindow( wxWindow* panel )
{
if (panel)
{
mMainPanel = panel;
GetSizer()->Insert(0, mMainPanel, 1, wxALL | wxEXPAND, 0);
Layout();
}
}
//---------------------------------------------------------------------------
wxWindow* DlgBaseOkCancel::GetMainPanel()const
{
return mMainPanel;
}
|
/**
* Given a string S, find the longest palindromic substring in S.
* You may assume that the maximum length of S is 1000, and there
* exists one unique longest palindromic substring.
*/
// O(n^2) solution
class Solution {
public:
string longestPalindrome(string s) {
const int N = s.size();
bool is_pal[N][N];
int maxlen = 1;
int max_start = 0;
// initialization: substring from i to j
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (i >= j) { // i > j: empty substring
is_pal[i][j] = true;
} else {
is_pal[i][j] = false;
}
}
}
for (int k = 1; k < N; k++) { // k: stride
for (int i = 0; i + k < N; i++) {
int j = i + k;
is_pal[i][j] = (s[i] == s[j]) && is_pal[i + 1][j - 1];
if (is_pal[i][j]) {
if (k + 1 > maxlen) {
maxlen = k + 1;
max_start = i;
}
}
}
}
return s.substr(max_start, maxlen);
}
};
|
/* BEGIN LICENSE */
/*****************************************************************************
* SKCore : the SK core library
* Copyright (C) 1995-2005 IDM <skcontact @at@ idm .dot. fr>
* $Id: log.cpp,v 1.1.2.5 2005/02/17 15:29:20 krys Exp $
*
* Authors: Colin Delacroix <colin @at@ zoy .dot. org>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Alternatively you can contact IDM <skcontact @at@ idm> for other license
* contracts concerning parts of the code owned by IDM.
*
*****************************************************************************/
/* END LICENSE */
#include <nspr/nspr.h>
#include <nspr/plstr.h>
#include <nspr/prlock.h>
#include <atltime.h>
#include "machine.h"
#include "error.h"
#include "log.h"
#include "envir/envir.h"
#define SK_LOG_FILE "SK_LOG_FILE"
#define SK_LOG_DEBUG_ENVIR_VAR "SK_LOG_DEBUG"
PRLock* skConsoleLog::m_pLock = NULL;
char const* skConsoleLog::m_logFile = NULL;
PRBool skConsoleLog::m_isEnableDebug= PR_FALSE;
void skConsoleLog::Init()
{
if(m_pLock)
return;
m_pLock = PR_NewLock();
// remove exist logfile
m_logFile = getLogFile();
if(m_logFile)
{
PR_Delete(m_logFile);
}
}
void skConsoleLog::Log(const char* pszFormat, ...)
{
va_list argp;
va_start(argp, pszFormat);
vLog(pszFormat, argp);
va_end(argp);
}
void skConsoleLog::DebugLog(const char* file, size_t line, const char* pszFormat, ...)
{
char* msg;
va_list argp;
va_start(argp, pszFormat);
msg = PR_smprintf("[skdebug] [%s:%d] - %s", file, line, pszFormat);
vLog(msg, argp);
PR_smprintf_free(msg);
va_end(argp);
}
void skConsoleLog::vLog(const char *pszFormat, va_list ap)
{
#ifdef XP_MAC
Str255 str255Log;
// don't have CopyCStringToPascal here, need a bit of magic
PR_vsnprintf((char*)(str255Log + 1), 254, pszFormat, ap);
str255Log[0] = PL_strlen( (const char*)(str255Log + 1) );
DebugStr( str255Log );
#else
if(!m_pLock)
return;
PR_Lock(m_pLock);
if(m_logFile)
{
FILE * f = fopen(m_logFile, "a");
if(f)
{
vfprintf(f, pszFormat, ap);
}
fclose(f);
}
PR_Unlock(m_pLock);
#endif
}
void skConsoleLog::Log(const wchar_t* pszFormat, ...)
{
va_list argp;
va_start(argp, pszFormat);
vLog(pszFormat, argp);
va_end(argp);
}
void skConsoleLog::DebugLog(const char* file, size_t line, const wchar_t* pszFormat, ...)
{
char* msg;
va_list argp;
if(m_isEnableDebug)
{
va_start(argp, pszFormat);
msg = PR_smprintf("[skdebug] [%s:%d] - %s", file, line, pszFormat);
vLog(msg, argp);
PR_smprintf_free(msg);
va_end(argp);
}
}
void skConsoleLog::vLog(const wchar_t *pszFormat, va_list ap)
{
#ifdef XP_MAC
Str255 str255Log;
// don't have CopyCStringToPascal here, need a bit of magic
PR_vsnprintf((char*)(str255Log + 1), 254, pszFormat, ap);
str255Log[0] = PL_strlen( (const char*)(str255Log + 1) );
DebugStr( str255Log );
#else
if(!m_pLock)
return;
PR_Lock(m_pLock);
if(m_logFile)
{
FILE * f = fopen(m_logFile, "a");
if(f)
{
vfwprintf(f, pszFormat, ap);
}
fclose(f);
}
PR_Unlock(m_pLock);
#endif
}
/*
void skConsoleLog::GetLog(char** pcLog)
{
*pcLog = NULL;
if(!m_pLock)
return;
PR_Lock(m_pLock);
*pcLog = PL_strdup(m_pcLog);
PR_Unlock(m_pLock);
}
void skConsoleLog::ClearLog()
{
if(!m_pLock)
return;
PR_Lock(m_pLock);
if(m_pcLog)
{
PL_strfree(m_pcLog);
m_pcLog = NULL;
}
PR_Unlock(m_pLock);
}
*/
const char * skConsoleLog::getLogFile()
{
SKEnvir *pEnvir = NULL;
SKERR err = SKEnvir::GetEnvir(&pEnvir);
if(err != noErr)
return NULL;
char* pcFile = NULL;
err = pEnvir->GetValue(SK_LOG_FILE, &pcFile);
if(err != noErr)
return NULL;
if(NULL == pcFile || 0 == strlen(pcFile) )
{
pcFile = "sk.log";
}
if(pcFile[0] != '/' && pcFile[0] != '\\')
{
// It's a relative path, convert it to absolute path.
char* skHome = NULL;
err = pEnvir->GetValue(SK_HOME_ENVIR_VAR, &skHome);
if(err != noErr)
return NULL;
size_t len = strlen(skHome) + strlen(pcFile) + 2;
char * fullPath = (char *)PR_Malloc(len);
sprintf(fullPath, "%s/%s", skHome, pcFile);
pcFile = fullPath;
}
else
{
pcFile = PL_strdup(pcFile);
}
// get enable debug flag
char* enableDebugString = NULL;
err = pEnvir->GetValue(SK_LOG_DEBUG_ENVIR_VAR, &enableDebugString);
if(err != noErr)
return NULL;
if(NULL != enableDebugString && (
0 == PL_strcmp("1", enableDebugString) ||
0 == PL_strcasecmp("true", enableDebugString) ||
0 == PL_strcasecmp("yes", enableDebugString) ))
{
m_isEnableDebug = PR_TRUE;
}
else
{
m_isEnableDebug = PR_FALSE;
}
return pcFile;
}
void skConsoleLog::trace(PRBool isDebug, const char* file, size_t line, const char * pszFormat, ...)
{
CTime timer = CTime::GetCurrentTime();
char timeString[64] = {0};
sprintf(timeString, "%02d-%02d %02d:%02d:%02d",
timer.GetMonth(),
timer.GetDay(),
timer.GetHour(),
timer.GetMinute(),
timer.GetSecond());
if(isDebug)
{
if(m_isEnableDebug)
{
Log("\n[%s] [DEBUG] [%s:%d] - ", timeString, file, line);
va_list argp;
va_start(argp, pszFormat);
vLog(pszFormat, argp);
va_end(argp);
}
}
else
{
Log("\n[%s] [INFO] [%s:%d] - ", timeString, file, line);
va_list argp;
va_start(argp, pszFormat);
vLog(pszFormat, argp);
va_end(argp);
}
}
void skConsoleLog::trace(PRBool isDebug, const char* file, size_t line, const wchar_t * pszFormat, ...)
{
CTime timer = CTime::GetCurrentTime();
char timeString[64] = {0};
sprintf(timeString, "%02d-%02d %02d:%02d:%02d",
timer.GetMonth(),
timer.GetDay(),
timer.GetHour(),
timer.GetMinute(),
timer.GetSecond());
if(isDebug)
{
if(m_isEnableDebug)
{
Log("\n[%s] [DEBUG] [%s:%d] - ", timeString, file, line);
va_list argp;
va_start(argp, pszFormat);
vLog(pszFormat, argp);
va_end(argp);
}
}
else
{
Log("\n[%s] [INFO] [%s:%d] - ", timeString, file, line);
va_list argp;
va_start(argp, pszFormat);
vLog(pszFormat, argp);
va_end(argp);
}
}
|
/* -*- Mode: c++; tab-width: 4; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2009 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*
* @author Arjan van Leeuwen (arjanl)
*/
#ifndef UNIX_OPSKINELEMENT_H
#define UNIX_OPSKINELEMENT_H
#include "modules/skin/OpSkinElement.h"
#include "platforms/quix/toolkits/NativeSkinElement.h"
class NativeSkinElement;
class OpBitmap;
class UnixOpSkinElement : public OpSkinElement
{
public:
UnixOpSkinElement(NativeSkinElement* native_element, OpSkin* skin, const OpStringC8& name, SkinType type, SkinSize size);
~UnixOpSkinElement();
// From OpSkinElement
virtual OP_STATUS Draw(VisualDevice* vd, OpRect rect, INT32 state, DrawArguments args);
virtual void OverrideDefaults(OpSkinElement::StateElement* se);
virtual OP_STATUS GetBorderWidth(INT32* left, INT32* top, INT32* right, INT32* bottom, INT32 state);
OpBitmap* GetBitmap(UINT32 width, UINT32 height, INT32 state);
private:
NativeSkinElement* m_native_element;
OpBitmap* m_bitmaps[NativeSkinElement::STATE_COUNT];
};
#endif // UNIX_OPSKINELEMENT_H
|
/*
* BasicObs.cpp
*
* Created on: Aug 20, 2014
* Author: ushnish
*
Copyright (c) 2014 Ushnish Ray
All rights reserved.
*/
#include "dmc.h"
namespace measures {
template <class T>
void BasicObs<T>::measure() {
Q.x += this->state.dQ.x;
Q.y += this->state.dQ.y;
Q.z += this->state.dQ.z;
ltime = this->state.ltime;
freeEnergy = this->state.weight;
// fprintf(this->log,"FE Check %10.6e %10.6e\n",freeEnergy.logValue(),Q.x);
}
template <class T>
void BasicObs<T>::writeViaIndex(int idx) {
fprintf(this->log,"BasicObs Write\n");
fflush(this->log);
double t = this->ltime*dt;
double it = 1.0/t;
double iZ = 1.0/Zcount;
ofstream wif(this->baseFileName,std::ofstream::app);
wif.precision(FIELDPRECISION);
wif.width(FIELDWIDTH);
wif.setf(FIELDFORMAT);
wif.fill(' ');
Q.x *= iZ;
Q.y *= iZ;
Q.z *= iZ;
Q2.x *= iZ;
Q2.y *= iZ;
Q2.z *= iZ;
Q2.x -= (Q.x*Q.x);
Q2.y -= (Q.y*Q.y);
Q2.z -= (Q.z*Q.z);
wif<<t<<" "<<(freeEnergy.logValue()*it)<<" "<<setfill(' ')<<Q.x<<" "<<setfill(' ')<<Q.y<<" "<<setfill(' ')
<<Q.z<<" "<<Q2.x*t<<" "<<Q2.y*t<<" "<<Q2.z*t<<endl;
wif.close();
clear();
}
template <class T>
void BasicObs<T>::clear()
{
Zcount = 0;
Q2.x = Q.x = 0.0;
Q2.y = Q.y = 0.0;
Q2.z = Q.z = 0.0;
ltime = 0;
freeEnergy.resetValue();
}
template <class T>
void BasicObs<T>::gather(void* p)
{
BasicObs<T>* obj = (BasicObs<T>*)p;
obj->ltime = ltime;
obj->Zcount += 1;
double it = 1.0/(ltime*dt);
obj->Q.x += Q.x*it;
obj->Q.y += Q.y*it;
obj->Q.z += Q.z*it;
obj->Q2.x += Q.x*Q.x*it*it;
obj->Q2.y += Q.y*Q.y*it*it;
obj->Q2.z += Q.z*Q.z*it*it;
fprintf(this->log,"%d\n", obj->Zcount);
obj->freeEnergy.display(this->log);
obj->freeEnergy.add(freeEnergy);
freeEnergy.display(this->log);
fprintf(this->log,"FE Check %10.6e %10.6e\n",freeEnergy.logValue(),Q.x);
Zcount = 0;
Q.x = Q.y = Q.z = 0;
Q2.x = Q2.y = Q2.z = 0;
ltime = 0;
freeEnergy.resetValue();
fflush(this->log);
}
template <class T>
Observable<T>* BasicObs<T>::duplicate(core::WalkerState<T>& ws)
{
BasicObs<T>* newo = new BasicObs<T>(this->processId,this->procCount,ws,
this->baseFileName,this->log,this->dt);
newo->ltime = this->ltime;
newo->Zcount = this->Zcount;
newo->Q.x = this->Q.x;
newo->Q.y = this->Q.y;
newo->Q.z = this->Q.z;
newo->Q2.x = this->Q2.x;
newo->Q2.y = this->Q2.y;
newo->Q2.z = this->Q2.z;
newo->freeEnergy = this->freeEnergy;
return newo;
}
template <class T>
int BasicObs<T>::parallelSend()
{
if(!this->MPIEnabled)
return NOTALLOWED;
int tag, recv;
MPI_Status stat;
//Wait for all processes to get here
MPI_Barrier(MPI_COMM_WORLD);
//Wait to be notified by master
MPI_Recv(&recv,1,MPI_INT,0,tag,MPI_COMM_WORLD,&stat);
fprintf(this->log,"BasicObs Received notification from master\n");
fflush(this->log);
//send time
MPI_Send(&this->ltime,1,MPI_LONG,0,tag,MPI_COMM_WORLD);
//send Zcount
MPI_Send(&this->Zcount,1,MPI_INT,0,tag,MPI_COMM_WORLD);
//Q
MPI_Send(&this->Q.x,1,MPI_DOUBLE,0,tag,MPI_COMM_WORLD);
MPI_Send(&this->Q.y,1,MPI_DOUBLE,0,tag,MPI_COMM_WORLD);
MPI_Send(&this->Q.z,1,MPI_DOUBLE,0,tag,MPI_COMM_WORLD);
//Q2
MPI_Send(&this->Q2.x,1,MPI_DOUBLE,0,tag,MPI_COMM_WORLD);
MPI_Send(&this->Q2.y,1,MPI_DOUBLE,0,tag,MPI_COMM_WORLD);
MPI_Send(&this->Q2.z,1,MPI_DOUBLE,0,tag,MPI_COMM_WORLD);
//FreeEnergy
this->freeEnergy.mpiSend(0);
fprintf(this->log,"BasicObs Transfer Complete\n");
fflush(this->log);
Zcount = 0;
ltime = 0;
Q.x = Q.y = Q.z = 0;
Q2.x = Q2.y = Q2.z = 0;
freeEnergy.resetValue();
return SUCCESS;
}
template <class T>
int BasicObs<T>::parallelReceive()
{
if(!this->MPIEnabled)
return NOTALLOWED;
//Wait for all processes to get here
MPI_Barrier(MPI_COMM_WORLD);
this->Zcount = 0;
for(int procId=1;procId<this->procCount;procId++)
{
int tag,recv;
MPI_Status stat;
MPI_Send(&recv,1,MPI_INT,procId,tag,MPI_COMM_WORLD);
fprintf(this->log,"BasicObs Sending notification to process:%d\n",procId);
fflush(this->log);
MPI_Recv(<ime,1,MPI_LONG,procId,tag,MPI_COMM_WORLD,&stat);
int zcountrec;
MPI_Recv(&zcountrec,1,MPI_INT,procId,tag,MPI_COMM_WORLD,&stat);
this->Zcount += zcountrec;
//Receive Q
double temp=0;
MPI_Recv(&temp,1,MPI_DOUBLE,procId,tag,MPI_COMM_WORLD,&stat);
this->Q.x += temp;
MPI_Recv(&temp,1,MPI_DOUBLE,procId,tag,MPI_COMM_WORLD,&stat);
this->Q.y += temp;
MPI_Recv(&temp,1,MPI_DOUBLE,procId,tag,MPI_COMM_WORLD,&stat);
this->Q.z += temp;
//Receive Q2
MPI_Recv(&temp,1,MPI_DOUBLE,procId,tag,MPI_COMM_WORLD,&stat);
this->Q2.x += temp;
MPI_Recv(&temp,1,MPI_DOUBLE,procId,tag,MPI_COMM_WORLD,&stat);
this->Q2.y += temp;
MPI_Recv(&temp,1,MPI_DOUBLE,procId,tag,MPI_COMM_WORLD,&stat);
this->Q2.z += temp;
//FreeEnergy
this->freeEnergy.mpiReceive(procId);
fprintf(this->log,"BasicObs Finished receiving from process:%d\n",procId);
fflush(this->log);
}
}
///////////////////////////////////////////////////////////////////////////
template void BasicObs<int>::measure();
template void BasicObs<int>::writeViaIndex(int idx);
template void BasicObs<int>::clear();
template void BasicObs<int>::gather(void* p);
template Observable<int>* BasicObs<int>::duplicate(core::WalkerState<int>&);
template int BasicObs<int>::parallelSend();
template int BasicObs<int>::parallelReceive();
} /* namespace measures */
|
class TrieNode{
public:
int path;
int end;
TrieNode *child[26];
TrieNode(){
path = 0;
end = 0;
for(int i=0; i<26; ++i){
child[i] = NULL;
}
}
};
class TrieTree{
public:
TrieNode *root;
TrieTree(){
root = new TrieNode();
}
void insertWord(string word){
if(word == "") return;
TrieNode *node = root;
for(int i=0; i<word.size(); ++i){
int index = word[i] - 'a';
if(node->child[index] == NULL){
node->child[index] = new TrieNode();
}
node = node->child[index];
node->path++;
}
node->end++;
}
void deleteWord(string word){
if(searchWord(word)){
TrieNode *node = root;
for(int i=0; i<word.size(); ++i){
int index = word[i] - 'a';
if(node->child[index]->path-- == 1){
node->child[index] = NULL;
return;
}
node = node->child[index];
}
node->end--;
}
}
bool searchWord(string word){
if(word == "") return false;
TrieNode *node = root;
for(int i=0; i<word.size(); ++i){
int index = word[i] - 'a';
if(node->child[index] == NULL){
return false;
}
node = node->child[index];
}
return node->end != 0;
}
int prefixNumber(string prefix){
if(prefix == "") return false;
TrieNode *node = root;
for(int i=0; i<prefix.size(); ++i){
int index = prefix[i] - 'a';
if(node->child[index] == NULL){
return 0;
}
node = node->child[index];
}
return node->path;
}
};
class Solution {
public:
vector<string> findWords(vector<vector<char>>& board, vector<string>& words) {
vector<string> res;
if(words.empty() || board.size() == 0 || board[0].size() == 0) return res;
TrieTree *trie = new TrieTree();
for(int i=0; i<words.size(); ++i){
trie->insertWord(words[i]);
}
int row = board.size();
int col = board[0].size();
vector<vector<bool> > visit(row,vector<bool> (col,false));
string temp;
for(int i=0; i<row; ++i){
for(int j=0; j<col; ++j){
int index = board[i][j] - 'a';
if(trie->root->child[index] != NULL){
dfs(board,trie->root->child[index],visit,i,j,res,temp);
}
}
}
return res;
}
void dfs(vector<vector<char>>& board,TrieNode *curNode,vector<vector<bool> > &visit,int curX,int curY,vector<string> &res,string temp){
visit[curX][curY] = true;
temp.push_back(board[curX][curY]);
if(curNode->end != 0){
res.push_back(temp);
curNode->end = 0;
}
static const int dx[] = {-1,1,0,0};
static const int dy[] = {0,0,-1,1};
for(int i=0; i<4; ++i){
int newX = curX + dx[i];
int newY = curY + dy[i];
if(newX >= 0 && newX < board.size() && newY >= 0 && newY < board[0].size() && !visit[newX][newY]){
int index = board[newX][newY] - 'a';
if(curNode->child[index] != NULL){
dfs(board,curNode->child[index],visit,newX,newY,res,temp);
}
}
}
visit[curX][curY] = false;
}
};
|
#include "product.h"
QString Product::getId() const
{
return id;
}
void Product::setId(const QString &value)
{
id = value;
}
QString Product::getNameProduct() const
{
return nameProduct;
}
void Product::setNameProduct(const QString &value)
{
nameProduct = value;
}
double Product::getPriceProduct() const
{
return priceProduct;
}
void Product::setPriceProduct(double value)
{
priceProduct = value;
}
Product::Product()
{
}
|
/*
문제 링크: https://www.acmicpc.net/problem/3190
문제 이름: 뱀
문제 풀이: 시뮬레이션
문제 풀이 참고 블로그 : https://na982.tistory.com/84?category=145346
*/
#define APPLE 1
#include <iostream>
using namespace std;
int N, K, L; // 보드 게임 크기
int nMap[101][101];
int head_y, head_x, tail_index;
int snake_y[10101], snake_x[10101];
char cmd[10001];
int dy[4] = { 0, 1, 0, -1 };
int dx[4] = { 1, 0, -1, 0 };
int main(void)
{
cin >> N;
cin >> K;
for (int i = 0; i < K; i++)
{
int nTemp1, nTemp2;
cin >> nTemp1 >> nTemp2;
nMap[nTemp1][nTemp2] = APPLE;
}
int nTime = 0;
char cTurn;
cin >> L;
for (int i = 0; i < L; i++)
{
cin >> nTime >> cTurn;
cmd[nTime] = cTurn;
}
int nDir = 0;
nTime = 0;
head_y = 1, head_x = 1, tail_index = 0;
snake_y[nTime] = head_y, snake_x[nTime] = head_x;
nMap[head_y][head_x] = -1;
while (true)
{
++nTime;
head_y += dy[nDir];
head_x += dx[nDir];
if (head_y < 1 || head_y > N || head_x < 1 || head_x > N || nMap[head_y][head_x] == -1)
{
break;
}
snake_y[nTime] = head_y;
snake_x[nTime] = head_x;
if (nMap[head_y][head_x] == 0)
{
int tail_y = snake_y[tail_index];
int tail_x = snake_x[tail_index];
nMap[tail_y][tail_x] = 0;
++tail_index;
}
nMap[head_y][head_x] = -1;
if (cmd[nTime] == 'D')
{
nDir = (nDir + 1) % 4;
}
if (cmd[nTime] == 'L')
{
nDir = (nDir + 3) % 4;
}
}
cout << nTime << endl;
return 0;
}
|
#include <ros/ros.h>
#include <geometry_msgs/PoseStamped.h>
#include "/home/ubuntu/catkin_ws/src/A_simple_subpuber/include/A_simple_subpuber/mavlink/v1.0/autoquad/mavlink.h"
#include "A_simple_subpuber/Mavlink.h"
#include "SerialRDM.h"
#define RADIUS_EARTH_METER (6378.137*1000.0)
int j=0;
SerialRDM serial;
void RadiansToDegrees(float *value);
void GetEulers(float qx, float qy, float qz, float qw, float *angle1,float *angle2, float *angle3);
class SubscribeAndPublish
{
public:
SubscribeAndPublish()
{
//Topic you want to publish
//pub_ = n_.advertise<A_simple_subpuber::Mavlink>("/mavlink/to", 1000);
//pub_ = n_.advertise<std::vector>("/mavlink/to", 1000);
//Topic you want to subscribe
sub_ = n_.subscribe("optitrack/pos", 1000, &SubscribeAndPublish::callback, this);
}
void callback(const geometry_msgs::PoseStamped& input)
{
//geometry_msgs::PoseStamped input;
//.... do something with the input and generate the output...
float x = input.pose.position.x;
float y = input.pose.position.y;
float z = input.pose.position.z;
float qx = input.pose.orientation.x;
float qy = input.pose.orientation.y;
float qz = input.pose.orientation.z;
float qw = input.pose.orientation.w;
float yaw_l, pitch_l, roll_l;
GetEulers(qx,qy,qz,qw,&pitch_l,&roll_l,&yaw_l);
//pitch_c=roll_l;
//roll_c=-pitch_l;
//x_n=-z*1000;
//y_n=x*1000;
//z_n=-y*1000;
//yaw_n=-yaw_l;
//printf("pos:[%3.2f,%3.2f,%3.2f,%3.2f]\n",x_n,y_n,z_n,yaw_n);
double Lat_mav = x/RADIUS_EARTH_METER*180.0f/3.14159265f;
double Lon_mav = y/RADIUS_EARTH_METER*180.0f/3.14159265f;
double Alt_mav = z;
float Yaw_mav = -yaw_l;
mavlink_message_t message;
// A_simple_subpuber::Mavlink rosmavlink_msg;
static uint8_t buffer[MAVLINK_MAX_PACKET_LEN];
static int messageLength;
if(j==0){
mavlink_msg_extern_gps_position_pack(1,1,&message,3, 0.1, 0.1, 0.1 ,0.1f, 1.0f,1.0f,1.0f,1.0f,1.0f,1.0f,1.0f,10000.0f, 0.0f,0.0f, 0.0f);
messageLength = mavlink_msg_to_send_buffer(buffer, &message);
/*for(int i=0;i<=messageLength/8;i++)
printf("%X\n",buffer[i]);*/
j++;
}
else{
mavlink_msg_extern_gps_position_pack(1,1,&message,4, Lat_mav, Lon_mav, Alt_mav ,0.0f, 0.0f,Yaw_mav,0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f);
messageLength = mavlink_msg_to_send_buffer(buffer, &message);
}
serial.serialsendf((const char*)buffer,messageLength);
/*smavlink_msg.sysid = 138;
rosmavlink_msg.compid = 190;
rosmavlink_msg.msgid = message.msgid;
for (int i = 0; i < message.len / 8; i++)
{
(rosmavlink_msg.payload64).push_back(message.payload64[i]);
}
pub_.publish(rosmavlink_msg);
pub_.publish(buffer);*/
}
private:
ros::NodeHandle n_;
//ros::Publisher pub_;
ros::Subscriber sub_;
};//End of class SubscribeAndPublish */
int main(int argc, char **argv)
{
//Initiate ROS
ros::init(argc, argv, "serial");
ROS_INFO_STREAM("Seiral node starting\n");
serial.set_values("/dev/ttyAMA0");
if(serial.init() != 1){
printf("SerialComm error: fail to initialize\n");
exit(-1);
}
//Create an object of class SubscribeAndPublish that will take care of everything
SubscribeAndPublish SAPObject;
ros::spin();
return 0;
}
void RadiansToDegrees(float *value)
{
*value = (*value)*(180.0f/3.14159265f);
}
void GetEulers(float qx, float qy, float qz, float qw, float *angle1,float *angle2, float *angle3)
{
float &heading = *angle1;
float &attitude = *angle2;
float &bank = *angle3;
double test = qw*qx + qy*qz;
if (test > 0.499) { // singularity at north pole
heading = (float) 2.0f * atan2(qy,qw);
attitude = 3.14159265f/2.0f;
bank = 0;
RadiansToDegrees(&heading);
RadiansToDegrees(&attitude);
RadiansToDegrees(&bank);
return;
}
if (test < -0.499) { // singularity at south pole
heading = (float) -2.0f * atan2(qy,qw);
attitude = - 3.14159265f/2.0f;
bank = 0;
RadiansToDegrees(&heading);
RadiansToDegrees(&attitude);
RadiansToDegrees(&bank);
return;
}
double sqx = qx*qx;
double sqy = qy*qy;
double sqz = qz*qz;
heading = (float) atan2((double)2.0*qw*qz-2.0*qx*qy , (double)1 - 2.0*sqz - 2.0*sqx);
attitude = (float)asin(2.0*test);
bank = (float) atan2((double)2.0*qw*qy-2.0*qx*qz , (double)1.0 - 2.0*sqy - 2.0*sqx);
RadiansToDegrees(&heading);
RadiansToDegrees(&attitude);
RadiansToDegrees(&bank);
}
|
#ifndef _FMT_ITOA_HPP_
#define _FMT_ITOA_HPP_
#include <fmt/flag.hpp>
namespace fmt {
uint32_t itoa(int64_t n, uint32_t width, uint32_t flags, char *b);
uint32_t itoa(uint64_t n, uint32_t width, uint32_t flags, char *b);
uint32_t itoa(int32_t n, uint32_t width, uint32_t flags, char *b);
uint32_t itoa(uint32_t n, uint32_t width, uint32_t flags, char *b);
uint32_t itoa_hex(uint64_t n, uint32_t width, uint32_t flags, char *b);
uint32_t itoa_hex(uint32_t n, uint32_t width, uint32_t flags, char *b);
uint32_t dtoa(double v, uint32_t width, uint32_t precision, uint32_t flags, char *b);
}
#endif
|
#pragma once
#include "../../UI/Dependencies/IncludeImGui.h"
#include "../../Graphics/Color/Color.h"
#include <string>
namespace ae
{
namespace priv
{
namespace ui
{
inline bool ColorToEditor( const std::string& _Name, Color& _Color )
{
float ColorRaw[4] = { _Color.R(), _Color.G(), _Color.B(), _Color.A() };
if( ImGui::ColorEdit4( _Name.c_str(), ColorRaw, ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_Float | ImGuiColorEditFlags_HDR ) )
{
_Color.Set( ColorRaw[0], ColorRaw[1], ColorRaw[2], ColorRaw[3] );
return True;
}
return false;
}
inline bool ColorNoAlphaToEditor( const std::string& _Name, Color& _Color )
{
float ColorRaw[3] = { _Color.R(), _Color.G(), _Color.B() };
if( ImGui::ColorEdit4( _Name.c_str(), ColorRaw, ImGuiColorEditFlags_AlphaPreview | ImGuiColorEditFlags_Float | ImGuiColorEditFlags_HDR | ImGuiColorEditFlags_NoAlpha ) )
{
_Color.Set( ColorRaw[0], ColorRaw[1], ColorRaw[2] );
return True;
}
return false;
}
} // ui
} // priv
} // ae
|
//HelloWorld.cpp
#include <iostream>
using namespace std;
int main() {
char ch;
cout << "Hello World!" << endl;
cin >> ch;
return 0;
}
|
/*
This file is part of SMonitor.
Copyright 2015~2016 by: rayx email rayx.cn@gmail.com
SMonitor is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SMonitor is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
#include "stdafx.h"
#include "CSideBarWidget.h"
#include "CStateButton.h"
#include "CPushButton.h"
#include <QVBoxLayout>
#include <QButtonGroup>
#include <QPainter>
CSideBarWidget::CSideBarWidget(QWidget *parent)
: QFrame(parent)
{
setObjectName("sideBarWidget");
setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
m_buttonGroup = new QButtonGroup(this);
setMaximumWidth(120);
m_mainLayout = new QVBoxLayout(this);
m_mainLayout->setMargin(0);
m_mainLayout->setSpacing(0);
connect(m_buttonGroup, SIGNAL(buttonToggled(int, bool)), this, SIGNAL(currentIndexChanged(int)));
}
CSideBarWidget::~CSideBarWidget()
{
}
void CSideBarWidget::addTab(const QString& text, const QChar& icon)
{
CPushButton* sideTab = new CPushButton(icon, text, this);
sideTab->setCheckable(true);
int count = m_mainLayout->count();
int step = 0;
QList<QAbstractButton*> buttons = m_buttonGroup->buttons();
for each(auto button in buttons)
{
int id = m_buttonGroup->id(button);
if(count == id)
step = 1;
m_buttonGroup->setId(button, id+step); //将位于count之后的button id后移一位
}
m_buttonGroup->addButton(sideTab, count);
m_mainLayout->insertWidget(count, sideTab/*, 0, Qt::AlignTop*/);
}
void CSideBarWidget::insertTab(int index, QString& text, const QString& icon)
{
CStateButton* sideTab = new CStateButton(icon, this, false);
int count = m_mainLayout->count();
QList<QAbstractButton*> buttons = m_buttonGroup->buttons();
int step = 0;
for each(auto button in buttons)
{
int id = m_buttonGroup->id(button);
if(index == id)
step = 1;
m_buttonGroup->setId(button, id+step);
}
m_buttonGroup->addButton(sideTab, index);
m_mainLayout->insertWidget(index, sideTab, 0, Qt::AlignTop);
}
void CSideBarWidget::setCurrentIndex(int index)
{
m_buttonGroup->button(index)->setChecked(true);
}
|
#pragma once
#include "ClistCtrlEx.h"
#include "afxcmn.h"
// MyRelTabDlg 对话框
class MyRelTabDlg : public CDialogEx
{
DECLARE_DYNAMIC(MyRelTabDlg)
public:
MyRelTabDlg(CWnd* pParent = NULL); // 标准构造函数
virtual ~MyRelTabDlg();
// 对话框数据
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_RELTAB_DIALOG };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
public:
ClistCtrlEx m_List_RelTab;
ClistCtrlEx m_List_RelRva;
virtual BOOL OnInitDialog();
afx_msg void OnClickList1(NMHDR *pNMHDR, LRESULT *pResult);
};
|
#include <fstream>
#include <iostream>
#include <boost/variant/static_visitor.hpp>
#include "http/parse_request.hpp"
using namespace std;
int main(int argc, char **argv)
{
if(argc < 2)
{
cerr << "Not enough arguments; call as" << endl;
cerr << "\t" << argv[0] << ' ' << "<file-to-parse>" << endl;
return 1;
}
for(unsigned int i = 0; i < 100000; ++i)
{
ifstream infile(argv[1]);
if(!infile)
{
cerr << "Could not open file " << argv[1] << "." << endl;
return 1;
}
http::request req;
http::parse_status result = http::parse_request(infile, req);
if(result != http::PARSE_SUCCESS)
{
cerr << "Could not parse." << endl;
return 1;
}
}
return 0;
}
|
#pragma once
#include "entity/entity.h"
namespace jsentity
{
JSObject* createEntityObject(entity::Entity* entity);
void destroyEntityObject(entity::Entity* entity);
JSBool RegisterCreateFunction(script::ScriptEngine* engine, char* name, JSNative create);
};
|
// Author: Kirill Gavrilov
// Copyright (c) 2016-2019 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 _RWGltf_GltfBufferView_HeaderFile
#define _RWGltf_GltfBufferView_HeaderFile
#include <RWGltf_GltfBufferViewTarget.hxx>
#include <Standard_TypeDef.hxx>
//! Low-level glTF data structure defining BufferView.
struct RWGltf_GltfBufferView
{
static const int INVALID_ID = -1;
public:
int Id; //!< index of bufferView in the array of bufferViews
int64_t ByteOffset; //!< offset to the beginning of the data in buffer
int64_t ByteLength; //!< length of the data
int32_t ByteStride; //!< [0, 255]
RWGltf_GltfBufferViewTarget Target;
RWGltf_GltfBufferView()
: Id (INVALID_ID), ByteOffset (0), ByteLength (0), ByteStride (0), Target (RWGltf_GltfBufferViewTarget_UNKNOWN) {}
};
#endif // _RWGltf_GltfBufferView_HeaderFile
|
#pragma once
#include <iberbar/Base/Lua/LuaCModule.h>
#include <iberbar/Base/Lua/LuaTypes.h>
namespace iberbar
{
class CLuaCModuleClass
: public CLuaCModuleAbstract
{
public:
struct Reg
{
const char* clsname;
lua_CFunction fn_constructor;
lua_CFunction fn_gc;
lua_CFunction fn_tostring;
const luaL_Reg* fns;
};
public:
CLuaCModuleClass()
{
}
public:
virtual void onRegister( lua_State* pLuaState, int tb ) override;
public:
const Reg* classes;
};
}
#define IBERBAR_LUA_CMODULE_CLS( type ) LuaCModuleClsReg_##type
#define IBERBAR_LUA_CMODULE_CLS_DECLARE( type ) static const iberbar::CLuaCModuleClass::Reg IBERBAR_LUA_CMODULE_CLS(type)[]
#define IBERBAR_LUA_CMODULE_CLS_DECLARE_END { nullptr }
|
#ifndef __TC_HTTP_ASYNC_H_
#define __TC_HTTP_ASYNC_H_
#include "util/tc_thread_pool.h"
#include "util/tc_http.h"
#include "util/tc_autoptr.h"
#include "util/tc_socket.h"
#include "util/tc_timeout_queue.h"
namespace taf
{
/////////////////////////////////////////////////
// ˵��: http�첽������
// httpͬ������ʹ��TC_HttpRequest::doRequest�Ϳ�����
// Author : jarodruan@tencent.com
/////////////////////////////////////////////////
/**
* �첽HTTP����
* ʹ�÷�ʽʾ������:
//ʵ���첽�ص�����
//�첽����ص�ִ�е�ʱ������TC_HttpAsync���߳�ִ�е�
//������ָ��new����, ���ù���������
class AsyncHttpCallback : public TC_HttpAsync::RequestCallback
{
public:
AsyncHttpCallback(const string &sUrl) : _sUrl(sUrl)
{
}
virtual void onException(const string &ex)
{
cout << "onException:" << _sUrl << ":" << ex << endl;
}
//���������ʱ��onResponse������
//bClose��ʾ����˹ر�������, �Ӷ���Ϊ�յ���һ��������http��Ӧ
virtual void onResponse(bool bClose, TC_HttpResponse &stHttpResponse)
{
cout << "onResponse:" << _sUrl << ":" << TC_Common::tostr(stHttpResponse.getHeaders()) << endl;
}
virtual void onTimeout()
{
cout << "onTimeout:" << _sUrl << endl;
}
//���ӱ��ر�ʱ����
virtual void onClose()
{
cout << "onClose:" << _sUrl << endl;
}
protected:
string _sUrl;
};
//��װһ������, ����ʵ���������
int addAsyncRequest(TC_HttpAsync &ast, const string &sUrl)
{
TC_HttpRequest stHttpReq;
stHttpReq.setGetRequest(sUrl);
//new����һ���첽�ص�����
TC_HttpAsync::RequestCallbackPtr p = new AsyncHttpCallback(sUrl);
return ast.doAsyncRequest(stHttpReq, p);
}
//����ʹ�õ�ʾ����������:
TC_HttpAsync ast;
ast.setTimeout(1000); //�����첽����ʱʱ��
ast.start();
//�����Ĵ�����Ҫ�жϷ���ֵ,����ֵ=0�ű�ʾ�����Ѿ����ͳ�ȥ��
int ret = addAsyncRequest(ast, "www.baidu.com");
addAsyncRequest(ast, "www.qq.com");
addAsyncRequest(ast, "www.google.com");
addAsyncRequest(ast, "http://news.qq.com/a/20100108/002269.htm");
addAsyncRequest(ast, "http://news.qq.com/zt/2010/mtjunshou/");
addAsyncRequest(ast, "http://news.qq.com/a/20100108/000884.htm");
addAsyncRequest(ast, "http://tech.qq.com/zt/2009/renovate/index.htm");
ast.waitForAllDone();
ast.terminate();
*/
/**
* �߳��쳣
*/
struct TC_HttpAsync_Exception : public TC_Exception
{
TC_HttpAsync_Exception(const string &buffer) : TC_Exception(buffer){};
TC_HttpAsync_Exception(const string &buffer, int err) : TC_Exception(buffer, err){};
~TC_HttpAsync_Exception() throw(){};
};
/**
* �첽�̴߳�����
*/
class TC_HttpAsync : public TC_Thread, public TC_ThreadLock
{
public:
/**
* �첽����ص�����
*/
class RequestCallback : public TC_HandleBase
{
public:
/**
* ��������Ӧ������
* @param bClose: ��ΪԶ�̷������ر�������Ϊhttp������
* @param stHttpResponse: http��Ӧ��
*/
virtual void onResponse(bool bClose, TC_HttpResponse &stHttpResponse) = 0;
/**
* �쳣
* @param ex: �쳣ԭ��
*/
virtual void onException(const string &ex) = 0;
/**
* ��ʱû����Ӧ
*/
virtual void onTimeout() = 0;
/**
* ���ӱ��ر�
*/
virtual void onClose() = 0;
};
typedef TC_AutoPtr<RequestCallback> RequestCallbackPtr;
protected:
/**
* �첽http����(������)
*/
class AsyncRequest : public TC_HandleBase
{
public:
/**
* ����
* @param stHttpRequest
* @param callbackPtr
*/
AsyncRequest(TC_HttpRequest &stHttpRequest, RequestCallbackPtr &callbackPtr);
/**
* ����
*/
~AsyncRequest();
/**
* ���
*
* @return int
*/
int getfd() { return _fd.getfd(); }
/**
* ����������
*
* @return int
*/
int doConnect();
/**
* �����쳣
*/
void doException();
/**
* ��������
*/
void doRequest();
/**
* ������Ӧ
*/
void doReceive();
/**
* �ر�����
*/
void doClose();
/**
* ��ʱ
*/
void timeout();
/**
* ΨһID
* @param uniqId
*/
void setUniqId(uint32_t uniqId) { _iUniqId = uniqId;}
/**
* ��ȡΨһID
*
* @return uint32_t
*/
uint32_t getUniqId() const { return _iUniqId; }
/**
* ���ô��������http�첽�߳�
*
* @param pHttpAsync
*/
void setHttpAsync(TC_HttpAsync *pHttpAsync) { _pHttpAsync = pHttpAsync; }
protected:
/**
* ��������
* @param buf
* @param len
* @param flag
*
* @return int
*/
int recv(void* buf, uint32_t len, uint32_t flag);
/**
* ��������
* @param buf
* @param len
* @param flag
*
* @return int
*/
int send(const void* buf, uint32_t len, uint32_t flag);
protected:
TC_HttpAsync *_pHttpAsync;
TC_HttpResponse _stHttpResp;
TC_Socket _fd;
string _sHost;
uint32_t _iPort;
uint32_t _iUniqId;
string _sReq;
string _sRsp;
RequestCallbackPtr _callbackPtr;
};
typedef TC_AutoPtr<AsyncRequest> AsyncRequestPtr;
public:
typedef TC_TimeoutQueue<AsyncRequestPtr> http_queue_type;
/**
* ���캯��
*/
TC_HttpAsync();
/**
* ��������
*/
~TC_HttpAsync();
/**
* �첽��������
* @param stHttpRequest
* @param httpCallbackPtr
*
* @return int
*/
int doAsyncRequest(TC_HttpRequest &stHttpRequest, RequestCallbackPtr &callbackPtr);
/**
* ���첽����
* @param num, �첽������߳���
*/
void start(int iThreadNum = 1);
/**
* ���ó�ʱ(��������ֻ����һ�ֳ�ʱʱ��)
* @param timeout: ����, ���Ǿ���ij�ʱ����ֻ����s����
*/
void setTimeout(int millsecond) { _data->setTimeout(millsecond); }
/**
* �ȴ�����ȫ������(�ȴ����뾫����100ms����)
* @param millsecond, ���� -1��ʾ��Զ�ȴ�
*/
void waitForAllDone(int millsecond = -1);
/**
* �����߳�
*/
void terminate();
protected:
typedef TC_Functor<void, TL::TLMaker<AsyncRequestPtr, int>::Result> async_process_type;
/**
* ��ʱ����
* @param ptr
*/
static void timeout(AsyncRequestPtr& ptr);
/**
* �������紦��
*/
static void process(AsyncRequestPtr p, int events);
/**
* ��������紦����
*/
void run() ;
/**
* ɾ���첽�������
*/
void erase(uint32_t uniqId);
friend class AsyncRequest;
protected:
TC_ThreadPool _tpool;
vector<TC_ThreadPool*> _npool;
http_queue_type *_data;
TC_Epoller _epoller;
bool _terminate;
};
}
#endif
|
template<class T>inline T gcd(T a,T b){
if(!a)return 1;if(!b)return a;
if(a<0) a=-a; for(T t;b;t=a%b,a=b,b=t);
return a;
}
|
#include <iostream>
#include <string.h>
bool clearCin() { //Перевод cin в рабочее состояние и очистка буфера
if (std::cin.fail()) {
std::cin.clear();
std::cin.ignore(32767, '\n');
std::cout << "Oops, something went wrong. Please, try again.\n";
return false;
}
std::cin.ignore(32767, '\n');
return true;
}
int inputQuantity() { //Ввод длины массива
while (true) {
std::cout << "How many names would you like to enter? ";
int number;
std::cin >> number;
if (clearCin()) {
return number;
}
}
}
std::string inputNames() { //Ввод имён
std::string name;
std::cin >> name;
return name;
}
void alphabeticalSort(int quantity, std::string* array) {
std::string temp;
for (int i = 0; i < quantity; ++i) {
bool earlyTermination{ true };
for (int j = 0; j < quantity - 1; ++j) {
if (array[j + 1] < array[j]) {
temp = array[j]; //Сортировка пузырьком
array[j] = array[j + 1];
array[j + 1] = temp;
earlyTermination = false;
}
}
if (earlyTermination) { //Если сортировка закончилась до прогона всего массива, то выходим из цикла
break;
}
}
}
int main() {
int quantity{ inputQuantity() };
std::string* arrayOfNames = new std::string[quantity];
for (int i = 0; i < quantity; ++i) {
std::cout << "Input " << i + 1 << " name ";
arrayOfNames[i] = inputNames();
}
alphabeticalSort(quantity, arrayOfNames);
std::cout << "Here is your sorted list:\n";
for (int i = 0; i < quantity; ++i) {
std::cout << "Name #" << i + 1 << ": " << arrayOfNames[i] << "\n";
}
delete[] arrayOfNames; //Освобождаем память
system("pause");
return 0;
}
|
//hashmap
class NumArray {
public:
NumArray(vector<int> &nums) {
int sum = 0;
for(int i = 0; i < nums.size(); ++i){
sum += nums[i];
sums[i] = sum;
}
sums[-1] = 0;
}
int sumRange(int i, int j) {
return sums[j] - sums[i-1];
}
unordered_map<int, int> sums;
};
//vector. faster
class NumArray {
public:
NumArray(vector<int> &nums) {
int sum = 0;
for(int i = 0; i < nums.size(); ++i){
sum += nums[i];
sums[i] = sum;
}
sums[-1] = 0;
}
int sumRange(int i, int j) {
return sums[j] - sums[i-1];
}
unordered_map<int, int> sums;
};
//partial_sum function
class NumArray {
public:
NumArray(vector<int> &nums) : psum(nums.size()+1, 0) {
partial_sum( nums.begin(), nums.end(), psum.begin()+1);
}
int sumRange(int i, int j) {
return psum[j+1] - psum[i];
}
private:
vector<int> psum;
};
// Your NumArray object will be instantiated and called as such:
// NumArray numArray(nums);
// numArray.sumRange(0, 1);
// numArray.sumRange(1, 2);
|
/*
File: Vec.cc
Function: Implements Vec.h
Author(s): Andrew Willmott
Copyright: Copyright (c) 1995-1996, Andrew Willmott
Notes:
*/
#include "Vec.h"
#ifndef __SVL__
#include "Array.h" // for the >> operator...
#endif
#include <iomanip>
#include <string.h>
#include <stdarg.h>
// --- Vec Constructors -------------------------------------------------------
TVec::TVec(Int n, ZeroOrOne k) : elts(n)
{
Assert(n > 0,"(Vec) illegal vector size");
data = new TVReal[n];
Assert(data != 0, "(Vec) Out of memory");
MakeBlock(k);
}
TVec::TVec(Int n, Axis a) : elts(n)
{
Assert(n > 0,"(Vec) illegal vector size");
data = new TVReal[n];
Assert(data != 0, "(Vec) Out of memory");
MakeUnit(a);
}
TVec::TVec(const TVec &v)
{
Assert(v.data != 0, "(Vec) Can't construct from a null vector");
elts = v.Elts();
data = new TVReal[elts];
Assert(data != 0, "(Vec) Out of memory");
// You might wonder why I don't use memcpy here and elsewhere.
// Timing tests on an R4400 show memcpy only becomes faster for
// n > 30 or so, and on an R10000, memcpy is never faster. Hence
// I'm sticking with loop copies for now.
for (Int i = 0; i < Elts(); i++)
data[i] = v[i];
}
#ifndef __SVL__
TVec::TVec(const TSubVec &v) : elts(v.Elts())
{
data = new TVReal[elts];
Assert(data != 0, "(Vec) Out of memory");
for (Int i = 0; i < Elts(); i++)
data[i] = v[i];
}
#endif
TVec::TVec(const TVec2 &v) : elts(v.Elts() | VL_REF_FLAG), data(v.Ref())
{
}
TVec::TVec(const TVec3 &v) : elts(v.Elts() | VL_REF_FLAG), data(v.Ref())
{
}
TVec::TVec(const TVec4 &v) : elts(v.Elts() | VL_REF_FLAG), data(v.Ref())
{
}
TVec::TVec(Int n, double elt0, ...) : elts(n)
{
Assert(n > 0,"(Vec) illegal vector size");
va_list ap;
Int i = 1;
data = new TVReal[n];
va_start(ap, elt0);
SetReal(data[0], elt0);
while (--n)
SetReal(data[i++], va_arg(ap, double));
va_end(ap);
}
TVec::~TVec()
{
if (!IsRef())
delete[] data;
}
// --- Vec Assignment Operators -----------------------------------------------
TVec &TVec::operator = (const TVec &v)
{
if (!IsRef())
SetSize(v.Elts());
else
Assert(Elts() == v.Elts(), "(Vec::=) Vector sizes don't match");
for (Int i = 0; i < Elts(); i++)
data[i] = v[i];
return(SELF);
}
#ifndef __SVL__
TVec &TVec::operator = (const TSubVec &v)
{
if (!IsRef())
SetSize(v.Elts());
else
Assert(Elts() == v.Elts(), "(Vec::=) Vector sizes don't match");
for (Int i = 0; i < Elts(); i++)
data[i] = v[i];
return(SELF);
}
#endif
TVec &TVec::operator = (const TVec2 &v)
{
if (!IsRef())
SetSize(v.Elts());
else
Assert(Elts() == v.Elts(), "(Vec::=) Vector sizes don't match");
data[0] = v[0];
data[1] = v[1];
return(SELF);
}
TVec &TVec::operator = (const TVec3 &v)
{
if (!IsRef())
SetSize(v.Elts());
else
Assert(Elts() == v.Elts(), "(Vec::=) Vector sizes don't match");
data[0] = v[0];
data[1] = v[1];
data[2] = v[2];
return(SELF);
}
TVec &TVec::operator = (const TVec4 &v)
{
if (!IsRef())
SetSize(v.Elts());
else
Assert(Elts() == v.Elts(), "(Vec::=) Vector sizes don't match");
data[0] = v[0];
data[1] = v[1];
data[2] = v[2];
data[3] = v[3];
return(SELF);
}
Void TVec::SetSize(Int n)
{
if (!IsRef())
{
// Don't reallocate if we already have enough storage
if (n <= elts)
{
elts = n;
return;
}
// Otherwise, delete old storage
delete[] data;
}
elts = n;
data = new TVReal[elts];
Assert(data != 0, "(Vec::SetSize) Out of memory");
}
Void TVec::MakeZero()
{
Int j;
for (j = 0; j < Elts(); j++)
data[j] = vl_zero;
}
Void TVec::MakeUnit(Int i, TVReal k)
{
Int j;
for (j = 0; j < Elts(); j++)
data[j] = vl_zero;
data[i] = k;
}
Void TVec::MakeBlock(TVReal k)
{
Int i;
for (i = 0; i < Elts(); i++)
data[i] = k;
}
// --- Vec In-Place operators -------------------------------------------------
TVec &operator += (TVec &a, const TVec &b)
{
Assert(a.Elts() == b.Elts(), "(Vec::+=) vector sizes don't match");
Int i;
for (i = 0; i < a.Elts(); i++)
a[i] += b[i];
return(a);
}
TVec &operator -= (TVec &a, const TVec &b)
{
Assert(a.Elts() == b.Elts(), "(Vec::-=) vector sizes don't match");
Int i;
for (i = 0; i < a.Elts(); i++)
a[i] -= b[i];
return(a);
}
TVec &operator *= (TVec &a, const TVec &b)
{
Assert(a.Elts() == b.Elts(), "(Vec::*=) Vec sizes don't match");
Int i;
for (i = 0; i < a.Elts(); i++)
a[i] *= b[i];
return(a);
}
TVec &operator *= (TVec &v, TVReal s)
{
Int i;
for (i = 0; i < v.Elts(); i++)
v[i] *= s;
return(v);
}
TVec &operator /= (TVec &a, const TVec &b)
{
Assert(a.Elts() == b.Elts(), "(Vec::/=) Vec sizes don't match");
Int i;
for (i = 0; i < a.Elts(); i++)
a[i] /= b[i];
return(a);
}
TVec &operator /= (TVec &v, TVReal s)
{
Int i;
for (i = 0; i < v.Elts(); i++)
v[i] /= s;
return(v);
}
// --- Vec Comparison Operators -----------------------------------------------
Bool operator == (const TVec &a, const TVec &b)
{
Int i;
for (i = 0; i < a.Elts(); i++)
if (a[i] != b[i])
return(0);
return(1);
}
Bool operator != (const TVec &a, const TVec &b)
{
Int i;
for (i = 0; i < a.Elts(); i++)
if (a[i] != b[i])
return(1);
return(0);
}
// --- Vec Arithmetic Operators -----------------------------------------------
TVec operator + (const TVec &a, const TVec &b)
{
Assert(a.Elts() == b.Elts(), "(Vec::+) Vec sizes don't match");
TVec result(a.Elts());
Int i;
for (i = 0; i < a.Elts(); i++)
result[i] = a[i] + b[i];
return(result);
}
TVec operator - (const TVec &a, const TVec &b)
{
Assert(a.Elts() == b.Elts(), "(Vec::-) Vec sizes don't match");
TVec result(a.Elts());
Int i;
for (i = 0; i < a.Elts(); i++)
result[i] = a[i] - b[i];
return(result);
}
TVec operator - (const TVec &v)
{
TVec result(v.Elts());
Int i;
for (i = 0; i < v.Elts(); i++)
result[i] = - v[i];
return(result);
}
TVec operator * (const TVec &a, const TVec &b)
{
Assert(a.Elts() == b.Elts(), "(Vec::*) Vec sizes don't match");
TVec result(a.Elts());
Int i;
for (i = 0; i < a.Elts(); i++)
result[i] = a[i] * b[i];
return(result);
}
TVec operator * (const TVec &v, TVReal s)
{
TVec result(v.Elts());
Int i;
for (i = 0; i < v.Elts(); i++)
result[i] = v[i] * s;
return(result);
}
TVec operator / (const TVec &a, const TVec &b)
{
Assert(a.Elts() == b.Elts(), "(Vec::/) Vec sizes don't match");
TVec result(a.Elts());
Int i;
for (i = 0; i < a.Elts(); i++)
result[i] = a[i] / b[i];
return(result);
}
TVec operator / (const TVec &v, TVReal s)
{
TVec result(v.Elts());
Int i;
for (i = 0; i < v.Elts(); i++)
result[i] = v[i] / s;
return(result);
}
TVReal dot(const TVec &a, const TVec &b)
{
Assert(a.Elts() == b.Elts(), "(Vec::dot) Vec sizes don't match");
TMReal sum = vl_zero;
Int i;
for (i = 0; i < a.Elts(); i++)
sum += a[i] * b[i];
return(sum);
}
TVec operator * (TVReal s, const TVec &v)
{
TVec result(v.Elts());
Int i;
for (i = 0; i < v.Elts(); i++)
result[i] = v[i] * s;
return(result);
}
// --- Vec Input & Output -----------------------------------------------------
std::ostream &operator << (std::ostream &s, const TVec &v)
{
Int i, w;
s << '[';
if (v.Elts() > 0)
{
w = s.width();
s << v[0];
for (i = 1; i < v.Elts(); i++)
s << ' ' << std::setw(w) << v[i];
}
s << ']';
return(s);
}
#ifndef __SVL__
istream &operator >> (istream &s, TVec &v)
{
Array<TVReal> array;
// Expected format: [1 2 3 4 ...]
s >> array; // Read input into variable-sized array
v = TVec(array.NumItems(), array.Ref()); // Copy input into vector
return(s);
}
#endif
|
#ifndef MINISERVER_HTTP_CONNECTION_H
#define MINISERVER_HTTP_CONNECTION_H
#include <map>
#include "connection.h"
#include "http_message.h"
#include "common_type.h"
namespace miniserver {
class HttpConnection : public Connection {
public:
// copy contorl constructor for prototype.
HttpConnection(int dummy);
~HttpConnection() override;
void process() override;
protected:
HttpConnection();
Connection* _clone() override;
bool _clear() override;
static HttpConnection _http_connection;
private:
void _parseRequest(Buffer &buffer);
bool _parseRequestLine(const std::string &line);
bool _parseHeader(const std::string &line);
bool _parseBody(Buffer &buffer);
bool _creatResponseStream(Buffer *buffer);
std::string _creatStatus(const HttpCode &http_code);
std::string _creatStatusInfo(const HttpCode &http_code);
void _errorResponse(const HttpCode &http_code);
HttpCode _headleRequest();
HttpCode _handleGet();
static void _initMime();
static std::map<std::string, std::string> _mime_type;
HttpRequest _request;
HttpResponse _response;
ParseStatus _parse_status;
HttpConnection(const HttpConnection &other);
HttpConnection& operator=(const HttpConnection &rhs);
};
}
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 2011-2012 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#ifndef MODULES_OTL_REDBLACKTREEITERATOR_H
#define MODULES_OTL_REDBLACKTREEITERATOR_H
#include "modules/otl/src/red_black_tree_node.h"
template<typename T>
class OpConstRedBlackTreeIterator;
/**
* Iterator for moving around in an OtlRedBlackTree.
*
* Increment the iterator to move in-order, and decrement to move in reverse-order
* around the tree. The only way to obtain a valid OtlRedBlackTreeIterator is to
* use an OtlRedBlackTree method that returns one.
*
* Note that modifying the object referenced by the iterator in a way that alters
* ordering within the tree is likely to break the tree's integrity. The reference
* is non-const to allow modifications in general. It is impossible for the iterator
* to know which changes may alter the ordering.
*
* @tparam T Type of the object stored in the OtlRedBlackTree.
*/
template<typename T>
class OtlRedBlackTreeIterator
{
public:
typedef OtlRedBlackTreeNode<T> Node;
typedef T& Reference;
typedef const T& ConstReference;
typedef T* Pointer;
typedef const T* ConstPointer;
OtlRedBlackTreeIterator(Node* n = NULL);
OtlRedBlackTreeIterator operator++(int);
OtlRedBlackTreeIterator& operator++();
OtlRedBlackTreeIterator operator--(int);
OtlRedBlackTreeIterator& operator--();
T& operator*() const;
T* operator->() const;
bool operator==(const OtlRedBlackTreeIterator& other) const;
bool operator!=(const OtlRedBlackTreeIterator& other) const;
template<typename CompatibleIterator>
bool operator==(const CompatibleIterator& other) const
{
return other == *this;
}
template<typename CompatibleIterator>
bool operator!=(const CompatibleIterator& other) const
{
return other != *this;
}
#if defined(RBTREE_DEBUG) || defined(SELFTEST)
Node* nodePtr() const;
#endif // defined(RBTREE_DEBUG) || defined(SELFTEST)
protected:
Node* NextNode() const;
Node* PreviousNode() const;
/// Pointer to current element.
Node* ptr;
}; // OtlRedBlackTreeIterator
// OtlRedBlackTreeIterator implementation
template<typename T> inline
OtlRedBlackTreeIterator<T>::OtlRedBlackTreeIterator(Node* n)
: ptr(n)
{ }
template<typename T> inline
typename OtlRedBlackTreeIterator<T>::Node* OtlRedBlackTreeIterator<T>::NextNode() const
{
return ptr ? ptr->Next() : NULL;
}
template<typename T> inline
typename OtlRedBlackTreeIterator<T>::Node* OtlRedBlackTreeIterator<T>::PreviousNode() const
{
return ptr ? ptr->Previous() : NULL;
}
template<typename T> inline
OtlRedBlackTreeIterator<T> OtlRedBlackTreeIterator<T>::operator++(int)
{
OtlRedBlackTreeIterator tmp = *this;
*this = OtlRedBlackTreeIterator(NextNode());
return tmp;
}
template<typename T> inline
OtlRedBlackTreeIterator<T>& OtlRedBlackTreeIterator<T>::operator++()
{
ptr = NextNode();
return *this;
}
template<typename T> inline
OtlRedBlackTreeIterator<T> OtlRedBlackTreeIterator<T>::operator--(int)
{
OtlRedBlackTreeIterator tmp = *this;
*this = OtlRedBlackTreeIterator(PreviousNode());
return tmp;
}
template<typename T> inline
OtlRedBlackTreeIterator<T>& OtlRedBlackTreeIterator<T>::operator--()
{
ptr = PreviousNode();
return *this;
}
template<typename T> inline
T* OtlRedBlackTreeIterator<T>::operator->() const
{
OP_ASSERT(ptr);
return &(ptr->item);
}
template<typename T> inline
T& OtlRedBlackTreeIterator<T>::operator*() const
{
OP_ASSERT(ptr);
return ptr->item;
}
template<typename T> inline
bool OtlRedBlackTreeIterator<T>::operator==(const OtlRedBlackTreeIterator& other) const
{
return other.ptr == ptr;
}
template<typename T> inline
bool OtlRedBlackTreeIterator<T>::operator!=(const OtlRedBlackTreeIterator& other) const
{
return other.ptr != ptr;
}
#if defined(RBTREE_DEBUG) || defined(SELFTEST)
template<typename T> inline
typename OtlRedBlackTreeIterator<T>::Node* OtlRedBlackTreeIterator<T>::nodePtr() const
{
return ptr;
}
#endif // defined(RBTREE_DEBUG) || defined(SELFTEST)
#endif // MODULES_OTL_REDBLACKTREEITERATOR_H
|
// attitude for spinning satelite
#ifndef NONLINEAR_H
#define NONLINEAR_H
#include "Eigen/Core"
#include "Eigen/Geometry"
#include <cstdio>
#include <string>
class NonLinear {
public:
NonLinear(Eigen::Vector3d &I, double SD_Q, double SD_R, int SEED) {
Ix_ = I[0];
Iy_ = I[1];
Iz_ = I[2];
SD_Q_ = SD_Q;
SD_R_ = SD_R;
SEED_ = SEED;
};
double Ix_, Iy_, Iz_;
Eigen::Vector3d vV_; //観測ノイズ
Eigen::Vector3d vW_; //外乱ノイズ
// functions for state propagation
void propagation(double dt, Eigen::VectorXd &omega_qt,
Eigen::Matrix<double, 3, 3> &dcm, double t_start,
double T_END);
void cal_omega_qt_dot(Eigen::VectorXd &omega_qt,
Eigen::VectorXd &omega_qt_dot);
void quartanion_to_dcm(Eigen::VectorXd &omega_qt,
Eigen::Matrix<double, 3, 3> &dcm_);
// functions for producing/ deleting noise
void update_vW(); // disterbuance noise
void update_vV(); // observation noise
void del_noise();
// writing result in files
void writefile(double t, Eigen::VectorXd &omega_qt,
Eigen::Matrix<double, 3, 3> &dcm, std::string fileprefix);
private:
double SD_Q_, SD_R_; /*ノイズ標準偏差 SD_Q_:外乱トルク SD_R:観測ノイズ*/
double SEED_; /*メルセンヌツイスタ関数用シード 0-シードも乱数で決定*/
};
#endif
|
#ifndef __UTILS_H__
#define __UTILS_H__
#include "CmnHdr.h"
#include <set>
#include <ctime>
#include <random>
#include <tcpmib.h>
#include <IPHlpApi.h>
#pragma comment(lib, "Shlwapi.lib")
#pragma comment(lib, "Iphlpapi.lib")
#pragma comment(lib, "Ws2_32.lib")
class Utils
{
public:
static bool WritePortToMappingFile(const std::string& port) {
HANDLE hMap = CreateFileMapping(INVALID_HANDLE_VALUE, NULL,
PAGE_READWRITE | SEC_COMMIT, 0, 256, L"win_ipc_temp_port");
if (hMap == NULL) {
return false;
}
BYTE *byte = (LPBYTE)MapViewOfFile(hMap, FILE_MAP_WRITE, 0, 0, 0);
if (byte == NULL) {
return false;
}
memcpy(byte, port.c_str(), port.size());
return true;
}
static int GetRandNum(int start, int end)
{
static int times = 0;
std::srand((unsigned)std::time(NULL) + times);
times++;
return (rand() % (end - start)) + start;
}
static int GetIdlePort()
{
std::set<int> portSet;
MIB_TCPTABLE TcpTable[100];
DWORD nSize = sizeof(TcpTable);
if (NO_ERROR == GetTcpTable(&TcpTable[0], &nSize, TRUE))
{
DWORD nCount = TcpTable[0].dwNumEntries;
if (nCount > 0)
{
for (DWORD i = 0; i < nCount; i++)
{
MIB_TCPROW TcpRow = TcpTable[0].table[i];
DWORD temp1 = TcpRow.dwLocalPort;
int temp2 = temp1 / 256 + (temp1 % 256) * 256;
portSet.insert(temp2);
}
}
}
int i = 0;
int port = 9001;
while (i < 20) {
i++;
port = GetRandNum(10000, 30000);
if (portSet.find(port) == portSet.end()) {
break;
}
}
return port;
}
};
#endif
|
// Generated from D:/4IF/PLD-COMP/Compilateur01\fichierAntlr.g4 by ANTLR 4.7
#pragma once
#include "antlr4-runtime.h"
#include "fichierAntlrParser.h"
/**
* This class defines an abstract visitor for a parse tree
* produced by fichierAntlrParser.
*/
class fichierAntlrVisitor : public antlr4::tree::AbstractParseTreeVisitor {
public:
/**
* Visit parse trees produced by fichierAntlrParser.
*/
virtual antlrcpp::Any visitProgramme_normal(fichierAntlrParser::Programme_normalContext *context) = 0;
virtual antlrcpp::Any visitMain_avecparametre(fichierAntlrParser::Main_avecparametreContext *context) = 0;
virtual antlrcpp::Any visitMain_sansparametre(fichierAntlrParser::Main_sansparametreContext *context) = 0;
virtual antlrcpp::Any visitMain_parametrevoid(fichierAntlrParser::Main_parametrevoidContext *context) = 0;
virtual antlrcpp::Any visitFonction_avecparametre(fichierAntlrParser::Fonction_avecparametreContext *context) = 0;
virtual antlrcpp::Any visitFonction_sansparametre(fichierAntlrParser::Fonction_sansparametreContext *context) = 0;
virtual antlrcpp::Any visitFonction_parametrevoid(fichierAntlrParser::Fonction_parametrevoidContext *context) = 0;
virtual antlrcpp::Any visitParametre_normal(fichierAntlrParser::Parametre_normalContext *context) = 0;
virtual antlrcpp::Any visitParametre_tableau(fichierAntlrParser::Parametre_tableauContext *context) = 0;
virtual antlrcpp::Any visitVariable_simple(fichierAntlrParser::Variable_simpleContext *context) = 0;
virtual antlrcpp::Any visitVariable_tableau(fichierAntlrParser::Variable_tableauContext *context) = 0;
virtual antlrcpp::Any visitAffectation_plusplusapres(fichierAntlrParser::Affectation_plusplusapresContext *context) = 0;
virtual antlrcpp::Any visitAffectation_plusplusavant(fichierAntlrParser::Affectation_plusplusavantContext *context) = 0;
virtual antlrcpp::Any visitAffectation_moinsmoinsapres(fichierAntlrParser::Affectation_moinsmoinsapresContext *context) = 0;
virtual antlrcpp::Any visitAffectation_moinsmoinsavant(fichierAntlrParser::Affectation_moinsmoinsavantContext *context) = 0;
virtual antlrcpp::Any visitAffectation_egal(fichierAntlrParser::Affectation_egalContext *context) = 0;
virtual antlrcpp::Any visitAffectation_etegal(fichierAntlrParser::Affectation_etegalContext *context) = 0;
virtual antlrcpp::Any visitAffectation_ouegal(fichierAntlrParser::Affectation_ouegalContext *context) = 0;
virtual antlrcpp::Any visitAffectation_plusegal(fichierAntlrParser::Affectation_plusegalContext *context) = 0;
virtual antlrcpp::Any visitAffectation_moinsegal(fichierAntlrParser::Affectation_moinsegalContext *context) = 0;
virtual antlrcpp::Any visitAffectation_foisegal(fichierAntlrParser::Affectation_foisegalContext *context) = 0;
virtual antlrcpp::Any visitAffectation_divegal(fichierAntlrParser::Affectation_divegalContext *context) = 0;
virtual antlrcpp::Any visitAffectation_pourcentegal(fichierAntlrParser::Affectation_pourcentegalContext *context) = 0;
virtual antlrcpp::Any visitAffectation_infegal(fichierAntlrParser::Affectation_infegalContext *context) = 0;
virtual antlrcpp::Any visitAffectation_supegal(fichierAntlrParser::Affectation_supegalContext *context) = 0;
virtual antlrcpp::Any visitExpr_infegal(fichierAntlrParser::Expr_infegalContext *context) = 0;
virtual antlrcpp::Any visitExpr_nombre(fichierAntlrParser::Expr_nombreContext *context) = 0;
virtual antlrcpp::Any visitExpr_diffegal(fichierAntlrParser::Expr_diffegalContext *context) = 0;
virtual antlrcpp::Any visitExpr_vague(fichierAntlrParser::Expr_vagueContext *context) = 0;
virtual antlrcpp::Any visitExpr_et(fichierAntlrParser::Expr_etContext *context) = 0;
virtual antlrcpp::Any visitExpr_inf(fichierAntlrParser::Expr_infContext *context) = 0;
virtual antlrcpp::Any visitExpr_parenthese(fichierAntlrParser::Expr_parentheseContext *context) = 0;
virtual antlrcpp::Any visitExpr_addition(fichierAntlrParser::Expr_additionContext *context) = 0;
virtual antlrcpp::Any visitExpr_ou(fichierAntlrParser::Expr_ouContext *context) = 0;
virtual antlrcpp::Any visitExpr_sup(fichierAntlrParser::Expr_supContext *context) = 0;
virtual antlrcpp::Any visitExpr_etet(fichierAntlrParser::Expr_etetContext *context) = 0;
virtual antlrcpp::Any visitExpr_infinf(fichierAntlrParser::Expr_infinfContext *context) = 0;
virtual antlrcpp::Any visitExpr_fonction(fichierAntlrParser::Expr_fonctionContext *context) = 0;
virtual antlrcpp::Any visitExpr_char(fichierAntlrParser::Expr_charContext *context) = 0;
virtual antlrcpp::Any visitExpr_egalegal(fichierAntlrParser::Expr_egalegalContext *context) = 0;
virtual antlrcpp::Any visitExpr_chiffre(fichierAntlrParser::Expr_chiffreContext *context) = 0;
virtual antlrcpp::Any visitExpr_variable(fichierAntlrParser::Expr_variableContext *context) = 0;
virtual antlrcpp::Any visitExpr_ouou(fichierAntlrParser::Expr_ououContext *context) = 0;
virtual antlrcpp::Any visitExpr_division(fichierAntlrParser::Expr_divisionContext *context) = 0;
virtual antlrcpp::Any visitExpr_mod(fichierAntlrParser::Expr_modContext *context) = 0;
virtual antlrcpp::Any visitExpr_supegal(fichierAntlrParser::Expr_supegalContext *context) = 0;
virtual antlrcpp::Any visitExpr_soustraction(fichierAntlrParser::Expr_soustractionContext *context) = 0;
virtual antlrcpp::Any visitExpr_affectation(fichierAntlrParser::Expr_affectationContext *context) = 0;
virtual antlrcpp::Any visitExpr_exclamation(fichierAntlrParser::Expr_exclamationContext *context) = 0;
virtual antlrcpp::Any visitExpr_multiplication(fichierAntlrParser::Expr_multiplicationContext *context) = 0;
virtual antlrcpp::Any visitExpr_supsup(fichierAntlrParser::Expr_supsupContext *context) = 0;
virtual antlrcpp::Any visitExpr_chapeau(fichierAntlrParser::Expr_chapeauContext *context) = 0;
virtual antlrcpp::Any visitReturn_normal(fichierAntlrParser::Return_normalContext *context) = 0;
virtual antlrcpp::Any visitBreak_normal(fichierAntlrParser::Break_normalContext *context) = 0;
virtual antlrcpp::Any visitInstruction_if(fichierAntlrParser::Instruction_ifContext *context) = 0;
virtual antlrcpp::Any visitInstruction_while(fichierAntlrParser::Instruction_whileContext *context) = 0;
virtual antlrcpp::Any visitInstruction_expr(fichierAntlrParser::Instruction_exprContext *context) = 0;
virtual antlrcpp::Any visitInstruction_return(fichierAntlrParser::Instruction_returnContext *context) = 0;
virtual antlrcpp::Any visitInstruction_break(fichierAntlrParser::Instruction_breakContext *context) = 0;
virtual antlrcpp::Any visitBloc_normal(fichierAntlrParser::Bloc_normalContext *context) = 0;
virtual antlrcpp::Any visitDeclaration_normale(fichierAntlrParser::Declaration_normaleContext *context) = 0;
virtual antlrcpp::Any visitDeclaration_definition(fichierAntlrParser::Declaration_definitionContext *context) = 0;
virtual antlrcpp::Any visitDeclaration_tableau(fichierAntlrParser::Declaration_tableauContext *context) = 0;
virtual antlrcpp::Any visitDeclaration_definitiontableau_nombre(fichierAntlrParser::Declaration_definitiontableau_nombreContext *context) = 0;
virtual antlrcpp::Any visitDeclaration_definitiontableau_char(fichierAntlrParser::Declaration_definitiontableau_charContext *context) = 0;
virtual antlrcpp::Any visitStructureif_normal(fichierAntlrParser::Structureif_normalContext *context) = 0;
virtual antlrcpp::Any visitElse_normal(fichierAntlrParser::Else_normalContext *context) = 0;
virtual antlrcpp::Any visitStructurewhile_normal(fichierAntlrParser::Structurewhile_normalContext *context) = 0;
virtual antlrcpp::Any visitType_var(fichierAntlrParser::Type_varContext *context) = 0;
virtual antlrcpp::Any visitType_fonction(fichierAntlrParser::Type_fonctionContext *context) = 0;
};
|
#pragma once
#include "windows.h"
class Thread abstract
{
public:
Thread(void);
~Thread(void);
void Stop();
void Start();
private:
static DWORD WINAPI MainThread(LPVOID pParam);
int startMainThread();
int endMainThread();
HANDLE mainThread;
volatile bool bMainThread;
protected:
virtual int ThreadFunction() = 0;
};
|
#include "GnMeshPCH.h"
#include "GnDataStream.h"
GnDataStream::GnDataStream(const GnDataStream::eFormat format, guint32 uiCount) : mFormat(format),
mLocked(false), mUnshaped(true), mNumStream(0), mUsageIndex(0), mpLocalBuffer(NULL), mVertexCount(uiCount)
{
}
GnDataStream::~GnDataStream()
{
// This assertion detects the deletion of a locked NiDataStream. All
// streams should be properly unlocked before deletion.
GnAssert(!GetLocked());
}
gtuint GnDataStream::GetStride(const GnDataStream::eFormat format)
{
GnAssert(false);
return 0;
}
// 포멧과 버텍스 카운트는 GnMeshData에서 저장 로드 한다.
void GnDataStream::SaveStream(GnStream* pStream)
{
guint32 size = GetBufferSize();
pStream->SaveStream( size );
pStream->SaveStreams( (gchar*)mpLocalBuffer, size );
pStream->SaveStream( mNumStream );
pStream->SaveStream( mUsageIndex );
pStream->SaveStream( mOffset );
}
void GnDataStream::LoadStream(GnStream* pStream)
{
guint32 size = 0;
pStream->LoadStream( size );
pStream->LoadStreams( (gchar*)mpLocalBuffer, size );
pStream->LoadStream( mNumStream );
pStream->LoadStream( mUsageIndex );
pStream->LoadStream( mOffset );
}
|
#include <iostream>
#include <Windows.h>
using namespace std;
int cmmmc(int a, int b) {
if (a < b) {
int aux = a;
a = b;
b = aux;
}
int rez = a;
while (rez % b != 0) {
rez += a;
}
return rez;
}
void circuite(int n, int& c1, int& c2, int& c3) {
int l1 = 4 * (n - 1);
int l2 = 4 * (n - 3);
int l3 = 4 * (n - 5);
int intalnire = cmmmc(cmmmc(l1, l2), l3);
c1 = intalnire / l1;
c2 = intalnire / l2;
c3 = intalnire / l3;
}
int main() {
int n;
cout << "Introduceti latura domeniului: " << endl;
cin >> n;
int c1 = 0, c2 = 0, c3 = 0;
circuite(n, c1, c2, c3);
cout << "Soldatul S1 va face " << c1 << " circuite pana la intalnire" << endl;
cout << "Soldatul S2 va face " << c2 << " circuite pana la intalnire" << endl;
cout << "Soldatul S3 va face " << c3 << " circuite pana la intalnire" << endl;
cout << endl;
system("pause");
return 0;
}
|
#pragma once
#include <QtWidgets/QMainWindow>
#include "ui_numerical_analysis_lab_02.h"
class Numerical_analysis_lab_02 : public QMainWindow
{
Q_OBJECT
public:
Numerical_analysis_lab_02(QWidget *parent = Q_NULLPTR);
private slots:
void plot_test_task();
void plot_main_task();
private:
Ui::Numerical_analysis_lab_02Class ui;
};
|
/*
MonitorTab.h
Header file for class MonitorTab
@author: Martin Terneborg
*/
#ifndef MONITORTAB_H
#define MONITORTAB_H
#include <Windows.h>
#include "Monitor.h"
/* Class responsible for handling all the controls of the monitor tabs.
*/
class MonitorTab {
private:
enum m_CONTROL_ID {
ENABLE_LEFT_CHECKBOX = 1,
ENABLE_RIGHT_CHECKBOX,
ENABLE_TOP_CHECKBOX,
ENABLE_BOTTOM_CHECKBOX,
LEDS_LEFT_EDIT,
LEDS_RIGHT_EDIT,
LEDS_TOP_EDIT,
LEDS_BOTTOM_EDIT,
LEDS_LEFT_TEXT,
LEDS_RIGHT_TEXT,
LEDS_TOP_TEXT,
LEDS_BOTTOM_TEXT,
POSITION_HORZ_EDIT,
POSITION_VERT_EDIT,
POSITION_LEFT_EDIT,
POSITION_RIGHT_EDIT,
POSITION_TOP_EDIT,
POSITION_BOTTOM_EDIT,
POSITION_LEFT_TEXT,
POSITION_RIGHT_TEXT,
POSITION_TOP_TEXT,
POSITION_BOTTOM_TEXT,
CLOCKWISE_LEFT,
CLOCKWISE_RIGHT,
CLOCKWISE_TOP,
CLOCKWISE_BOTTOM
};
HWND m_hDisplayCtrl;
Monitor * m_monitor;
BOOL InitControls();
friend LRESULT CALLBACK DisplayCtrlProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
public:
VOID Show();
VOID Hide();
BOOL Create(CONST HWND hTabCtrl, Monitor * CONST monitor);
BOOL ApplySettings();
BOOL GetSettings(Monitor &monitor);
BOOL Modified();
inline CONST Monitor GetMonitor() CONST { return *m_monitor; };
};
#endif
|
#pragma once
#include "Cell.h"
class ShipCell : public Cell
{
public:
ShipCell() : Cell('b') { this->isStricken = false; }
virtual ~ShipCell() {}
ShipCell(size_t Row, size_t Column) : Cell(Row, Column, 'b') { this->isStricken = false; }
ShipCell(const ShipCell& other) : Cell(other) { this->isStricken = other.getIsStricken(); }
virtual Cell* Clone() const { return new ShipCell(*this); }
bool getIsStricken() const { return this->isStricken; }
void setIsStricken(bool newIsStricken) { this->isStricken = newIsStricken; }
private:
bool isStricken;
};
|
#include <iostream>
using namespace std;
int primes[10001];
bool isPrime(int num, int numprimes) {
for(int i = 0; i < numprimes; i++) {
if (num % primes[i] == 0) {
return false;
}
}
/*
for (int i = 2; i < num; i++) {
if (num % i == 0) {
return false;
}
}
*/
return true;
}
int main() {
int numprimes = 1;
primes[0] = 2;
long i = 3;
while(numprimes <= 10001) {
if (isPrime(i, numprimes)) {
primes[numprimes] = i;
numprimes++;
}
i++;
}
cout << "Number of primes: " << numprimes << endl;
for (int i = 0; i < numprimes; i++) {
cout << primes[i] << endl;
}
}
|
// Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2018 Google Inc. All rights reserved.
// http://ceres-solver.org/
//
// 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 Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: jodebo_beck@gmx.de (Johannes Beck)
#include "ceres/internal/integer_sequence_algorithm.h"
#include <type_traits>
namespace ceres {
namespace internal {
// Unit tests for summation of integer sequence.
static_assert(Sum<integer_sequence<int>>::Value == 0,
"Unit test of summing up an integer sequence failed.");
static_assert(Sum<integer_sequence<int, 2>>::Value == 2,
"Unit test of summing up an integer sequence failed.");
static_assert(Sum<integer_sequence<int, 2, 3>>::Value == 5,
"Unit test of summing up an integer sequence failed.");
static_assert(Sum<integer_sequence<int, 2, 3, 10>>::Value == 15,
"Unit test of summing up an integer sequence failed.");
static_assert(Sum<integer_sequence<int, 2, 3, 10, 4>>::Value == 19,
"Unit test of summing up an integer sequence failed.");
static_assert(Sum<integer_sequence<int, 2, 3, 10, 4, 1>>::Value == 20,
"Unit test of summing up an integer sequence failed.");
// Unit tests for exclusive scan of integer sequence.
static_assert(std::is_same<ExclusiveScan<integer_sequence<int>>,
integer_sequence<int>>::value,
"Unit test of calculating the exclusive scan of an integer "
"sequence failed.");
static_assert(std::is_same<ExclusiveScan<integer_sequence<int, 2>>,
integer_sequence<int, 0>>::value,
"Unit test of calculating the exclusive scan of an integer "
"sequence failed.");
static_assert(std::is_same<ExclusiveScan<integer_sequence<int, 2, 1>>,
integer_sequence<int, 0, 2>>::value,
"Unit test of calculating the exclusive scan of an integer "
"sequence failed.");
static_assert(std::is_same<ExclusiveScan<integer_sequence<int, 2, 1, 10>>,
integer_sequence<int, 0, 2, 3>>::value,
"Unit test of calculating the exclusive scan of an integer "
"sequence failed.");
} // namespace internal
} // namespace ceres
|
/*
* File: MunecoDeNieve.h
* Author: raul
*
* Created on 21 de enero de 2014, 20:46
*/
#ifndef MUNECODENIEVE_H
#define MUNECODENIEVE_H
#include "Disco.h"
#include "ObjetoCompuesto.h"
#include "freeglut.h"
class MunecoDeNieve : public ObjetoCompuesto {
public:
MunecoDeNieve();
MunecoDeNieve(GLdouble radioEsferaCuerpo, GLdouble radioEsferaCabeza);
void dibuja();
private:
GLdouble _altura;
GLdouble _radioEsferaCuerpo;
GLdouble _radioEsferaCabeza;
};
#endif /* MUNECODENIEVE_H */
|
/*
* Copyright 2016 Freeman Zhang <zhanggyb@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SKLAND_WAYLAND_CURSOR_THEME_HPP_
#define SKLAND_WAYLAND_CURSOR_THEME_HPP_
#include "shm.hpp"
namespace skland {
namespace wayland {
class CursorTheme {
CursorTheme(const CursorTheme &) = delete;
CursorTheme &operator=(const CursorTheme &) = delete;
public:
CursorTheme()
: wl_cursor_theme_(nullptr) {}
~CursorTheme() {
if (wl_cursor_theme_) wl_cursor_theme_destroy(wl_cursor_theme_);
}
void Load(const char *name, int size, const Shm &shm) {
Destroy();
wl_cursor_theme_ = wl_cursor_theme_load(name, size, shm.wl_shm_);
}
void Destroy() {
if (wl_cursor_theme_) {
wl_cursor_theme_destroy(wl_cursor_theme_);
wl_cursor_theme_ = nullptr;
}
}
struct wl_cursor *GetCursor(const char *name) const {
return wl_cursor_theme_get_cursor(wl_cursor_theme_, name);
}
bool IsValid() const {
return nullptr != wl_cursor_theme_;
}
private:
struct wl_cursor_theme *wl_cursor_theme_;
};
}
}
#endif // SKLAND_WAYLAND_CURSOR_THEME_HPP_
|
#pragma once
#include <vector>
#include "Vec2.h"
namespace Move
{
class PredictionFilter
{
int bufferSize;
std::vector<Vec2> buffer;
int position;
bool initialized;
float currentTime;
/// slope of the prediction function
float m;
/// intercept of the prediction function
float b;
public:
PredictionFilter();
PredictionFilter(int bufferSize);
~PredictionFilter();
float filter(float value, float dt);
private:
float integrateError(std::vector<float> x);
};
}
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
return buildTree(inorder, postorder, 0, inorder.size(), 0, postorder.size());
}
private:
TreeNode* buildTree(const vector<int> &inorder, const vector<int> &postorder,
int ib, int ie, int pb, int pe)
{
if (pe == pb) {
return NULL;
}
if (pe == pb + 1) {
return new TreeNode(postorder[pb]);
}
int root = postorder[pe - 1];
TreeNode *node = new TreeNode(root);
int r = find(inorder.begin() + ib, inorder.begin() + ie, root) - (inorder.begin() + ib);
node->left = buildTree(inorder, postorder, ib, ib + r, pb, pb + r);
node->right = buildTree(inorder, postorder, ib + r + 1, ie, pb + r, pe - 1);
return node;
}
};
|
//===-- mess/db-client.hh - DBClient class definition -----------*- C++ -*-===//
//
// ODB Library
// Author: Steven Lariau
//
//===----------------------------------------------------------------------===//
///
/// \file
/// The main class to communicate with a a debugguer
///
//===----------------------------------------------------------------------===//
#pragma once
#include <map>
#include <memory>
#include <vector>
#include "../server/fwd.hh"
#include "fwd.hh"
namespace odb {
/// Internal data structure received after each block
struct DBClientUpdate {
StoppedState vm_state;
bool stopped;
vm_ptr_t addr; // execution point
CallStack stack;
};
/// This is the main class used to communicate with a running debugguer
/// It's most often used on the client process, and takes care of serializing
/// and sending commands to debugguer
///
/// Can also be used directly on the same process as the debugguer, but a little
/// differently In that situation, no serialization is done, and right calls are
/// simply made
///
///
///
/// @EXTRA for now only redirect calls, but caching to limit requests could help
class DBClient {
public:
/// The DB client can be on 4 states:
/// - not-connected: cannot connected yet. can only call connect() method
/// - discconnected: connection lost, cannot do anything with the object
/// - VMStopped: main state where the object is usable. can do everything but
/// call connect(), stop() and check_stopped()
/// - VMRunning: Can anly call stop() and check_stopped()
enum class State {
NOT_CONNECTED,
DISCONNECTED,
VM_STOPPED,
VM_RUNNING,
};
DBClient(std::unique_ptr<DBClientImpl> &&impl);
State state() const { return _state; }
/// Blocking calls
/// All these calls may need to interact with the server
/// If the request is invalid and Debugger throws, these methods rethrow the
/// same exceptions
/// Can only be called in NOT_CONNECTED state
/// Throws if connection failed
/// If succeeds, state move to VM_STOPPED or VM_RUNNING
void connect();
/// Can only be called in VM_RUNNING state
/// Send a stop command to the debugger
/// Throws if the stop failed
void stop();
/// Can only be called in VM_RUNNING state
/// Send a request to know if the debugguer program is still running.
/// This method also update state accordingly
/// The server never sends a message when the VM stopped
/// So instead the client must ask in a loop if the VM is still running
void check_stopped();
/// All following functions can only be called in VM_STOPPED state
/// Load many registers at once
/// @param ids array of register ids
/// @param out_bufs array of buffer where every register value will be written
/// @param regs_size array of the size of each register. If all registers have
/// the same size, you can write 0 in regs_size[1]
/// @param nregs size of arrays
///
/// If async, once completed the output arguments are not filled
/// The method must be called again
/// If any output is NULL, only fill the cache.
void get_regs(const vm_reg_t *ids, char **out_bufs,
const vm_size_t *regs_size, std::size_t nregs);
/// Update many registers at once
/// @param ids array of register ids
/// @param in_bufs array of buffer where every new register value is read
/// @param regs_size array of the size of each register. If all registers have
/// the same size, you can write 0 in regs_size[1]
/// @param nregs size of arrays
void set_regs(const vm_reg_t *ids, const char **in_bufs,
const vm_size_t *regs_size, std::size_t nregs);
/// Get informations about multiple registers at once
/// The field val is not updated
/// @param ids array of register ids
/// @param out_infos array of RegInfos where data will be written
/// @param nregs size of arrays
void get_regs_infos(const vm_reg_t *ids, RegInfos *out_infos,
std::size_t nregs);
/// Find ids of many registers at once
/// @param reg_names array of register names
/// @param out_ids array where every register ids will be written
/// @param nregs size of arrays
void find_regs_ids(const char **reg_names, vm_reg_t *out_ids,
std::size_t nregs);
/// Read at many memory locations at once
/// @param src_addrs array of VM addresses where the data is read
/// @param bufs_sizes array of the number of bytes of each read
/// @param out_bufs array of buffers where the data will be writtem
/// @param nbuffs size of arrays
void read_mem(const vm_ptr_t *src_addrs, const vm_size_t *bufs_sizes,
char **out_bufs, std::size_t nbuffs);
/// Write at many memory locations at once
/// @param dst_addrs array of VM addresses where the data will be written
/// @param bufs_sizes array of of the number of bytes of each write
/// @param in_bufs array of buffers that contains the data to be written
/// @param nbuffs size of arrays
void write_mem(const vm_ptr_t *dst_addrs, const vm_size_t *bufs_sizes,
const char **in_bufs, std::size_t nbuffs);
/// Get infos about all symbols located at [addr, addr + size[
/// @param out_infos vector where data will be written
void get_symbols_by_addr(vm_ptr_t addr, vm_size_t size,
std::vector<SymbolInfos> &out_infos);
/// Get infos about many symbols given their ids
/// @param ids array of symbol ids
/// @param out_infos array where data will be written
/// @param nsyms size of array
void get_symbols_by_ids(const vm_sym_t *ids, SymbolInfos *out_infos,
std::size_t nsyms);
/// Get infos about many symbols given their names
/// @param names array of symbol names
/// @param out_infos array where data will be written
/// @param nsyms size of array
void get_symbols_by_names(const char **names, SymbolInfos *out_infos,
std::size_t nsyms);
/// Get string representation of code
/// @param addr VM address where to start getting codes
/// @param nins number of instructions that need to be decoded
/// @param out_code_size will contain the number of bytes decoded
/// @param out_sizes will contain the size in bytes of each decoded
/// instructions
/// @extra vector<string> not good, can do better with cache
void get_code_text(vm_ptr_t addr, std::size_t nins,
std::vector<std::string> &out_text,
std::vector<vm_size_t> &out_sizes);
/// Add many breakpoint at once
/// @param addrs array of addresses
/// @param size array size
void add_breakpoints(const vm_ptr_t *addrs, std::size_t size);
/// Add many breakpoint at once
/// @param addrs array of addresses
/// @param size array size
void del_breakpoints(const vm_ptr_t *addrs, std::size_t size);
/// @EXTRA had has_breakpoint used cache
/// Resume program execution
void resume(ResumeType type);
// ===== Always stored informations =====
// These calls never block
// === Update informations ===
// These informations are valid until the program resume
// @returns the address where the Debugguer is stopped
// May differ from PC on some vms
vm_ptr_t get_execution_point();
/// @returns the reason why the program is stopped
StoppedState get_stopped_state();
/// Get the current list of calls
CallStack get_call_stack();
// === Static VM informations ===
// These informations are always valid
/// Returns a reference to the VMInfos object
/// Valid as long as this remains valid
const VMInfos &get_vm_infos() const { return _vm_infos; }
/// Returns total number of registers available
/// Some VMs may have infinite registers (usually returns huge number)
vm_reg_t registers_count() const;
/// List all regs of a specific kind
/// For VM with lots of registers, usually only list the main special ones
/// Remains valid as long as this remains valid
const std::vector<vm_reg_t> &list_regs(RegKind kind) const;
/// Returns the full memory size of the VM in bytes
vm_size_t memory_size() const;
/// Returns the total number of symbols
vm_sym_t symbols_count() const;
// Returns the size of a pointer type value
vm_size_t pointer_size() const;
// Returns the size of an int type value
vm_size_t integer_size() const;
// Returns true if the VM instructions have binary opcodes
bool use_opcode() const;
private:
std::unique_ptr<DBClientImpl> _impl;
State _state;
DBClientUpdate _udp;
VMInfos _vm_infos;
// Discard all temporary infos (eg memory / reg values)
void _discard_tmp_cache();
// Caching: register infos + vals
// infos static data always valid
// value cleared after each instruction
// Fetch all register infos into cache
void _fetch_reg_infos_by_id(const vm_reg_t *idxs, std::size_t nregs);
// Fetch all register infos into cache
void _fetch_reg_infos_by_name(const char **names, std::size_t nregs);
// Fetch all register values into cache
void _fetch_reg_vals_by_id(const vm_reg_t *idxs, std::size_t nregs);
std::vector<RegInfos> _regi_arr; // all reg infos
std::map<vm_reg_t, std::size_t>
_regi_idx_map; // map reg index => pos in _regi_arr
std::map<std::string, std::size_t>
_regi_name_map; // map reg name => pos in _regi_arr
};
} // namespace odb
|
#ifndef _CheckProcess_H_
#define _CheckProcess_H_
#include "BaseProcess.h"
class CheckProcess :public BaseProcess
{
public:
CheckProcess();
virtual ~CheckProcess();
virtual int doRequest(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt) ;
virtual int doResponse(CDLSocketHandler* clientHandler, InputPacket* inputPacket,Context* pt ) ;
};
#endif
|
//#include "stdafx.h"
#include <iostream>
#include "cuda_runtime.h"
#include "device_launch_parameters.h"
#include"mat.h"
#include <stdio.h>
#include<stdlib.h>
#include<cmath>
#include "mclmcr.h"
#include"matrix.h"
#include <cuComplex.h>
//#include <opencv2/core/core.hpp>
//#include<opencv2/highgui/highgui.hpp>
//#include<complex.h>
#include<complex>
using namespace std;
//using namespace cv;
static int TOTAL_ELEMENTS = (3534 * 16384);
static MATFile *pMF = NULL;
static mxArray *pA = NULL;
static MATFile *pMF_out = NULL;
static mxArray *pA_out = NULL;
static MATFile *beamF_out = NULL;
static mxArray *beamM_out = NULL;
#define N_elements 128
int M_elements;
int emit_aperture;
int emit_pitch;
int emit_start;
int Trans_elements;
int zerolength = 1000;
int fs = 40000000;
//double A[3534][16384];
double x_begin = (-3.0 / 1000);
double z_begin = 27.5 / 1000;
double d_x = 0.05 / 1000;
double d_z = 0.05 / 1000;
double pitch = (3.08e-4);
double t1 = (3.895e-5);
double a_begin = -double((N_elements - 1)) / 2 * pitch;
int c = 1540;
int xsize = 501;
int ysize = 121;
double *init_imaginary;
double *init_real;
unsigned char Result[501][121];
__device__ __host__ void swap_rows(cuDoubleComplex(*Rxx1)[52], int r1, int r2) {
cuDoubleComplex temp[1][52];
int i, j;
for (i = 0; i < 52; i++)
{
temp[0][i] = Rxx1[r1][i];
Rxx1[r1][i] = Rxx1[r2][i];
Rxx1[r2][i] = temp[0][i];
}
/*temp[1] = Rxx1[r1];
Rxx1[r1] = Rxx1[r2];
Rxx1[r2] = temp[1];*/
}
__device__ __host__ void scale_row(cuDoubleComplex(*Rxx1)[52], int r, cuDoubleComplex scalar, int L1) {
int i;
for (i = 0; i < L1; i++) {
Rxx1[r][i] = cuCmul(Rxx1[r][i], scalar);
}
}
__device__ __host__ void shear_row(cuDoubleComplex(*Rxx1)[52], int r1, int r2, cuDoubleComplex scalar, int L1) {
int i;
for (i = 0; i < L1; i++) {
//printf("cuCmul(Rxx1[%d][%d], scalar) is %e,%e\n", r2, i, cuCreal(cuCmul(Rxx1[r2][i], scalar)), cuCimag(cuCmul(Rxx1[r2][i], scalar)));
Rxx1[r1][i] = cuCadd(Rxx1[r1][i], cuCmul(Rxx1[r2][i], scalar));
}
}
__device__ __host__ void matrix_inv(cuDoubleComplex(*Rxx1)[52], int L1) {
cuDoubleComplex Rxx1_out[52][52] = { 0.0 };
int i, j, r;
cuDoubleComplex scalar;
cuDoubleComplex shear_needed;
for (i = 0; i < L1; i++)
{
Rxx1_out[i][i] = make_cuDoubleComplex(1.0, 0.0);
}
for (i = 0; i < L1; i++)
{
if (((cuCreal(Rxx1[i][i])) == 0.0) && (cuCimag(Rxx1[i][i])==0.0)) {
for (r = i + 1; r < L1; r++)
{
if (((cuCreal(Rxx1[i][i])) != 0.0) || ((cuCimag(Rxx1[i][i])) != 0.0))
{
break;
}
}
swap_rows(Rxx1, i, r);
swap_rows(Rxx1_out, i, r);
}
scalar = cuCdiv(make_cuDoubleComplex(1.0, 0.0), Rxx1[i][i]);
scale_row(Rxx1, i, scalar, L1);
scale_row(Rxx1_out, i, scalar, L1);
for (j = 0; j < L1; j++)
{
if (i == j) { continue; }
shear_needed = make_cuDoubleComplex(-cuCreal(Rxx1[j][i]), -cuCimag(Rxx1[j][i]));
shear_row(Rxx1, j, i, shear_needed, L1);
shear_row(Rxx1_out, j, i, shear_needed, L1);
}
}
/*for (i = 0; i < 2; i++)
{
for (j = 0; j < 2; j++)
{
printf("Rxx1[%d][%d] is %e,%e\n", i, j, cuCreal(Rxx1[i][j]), cuCimag(Rxx1[i][j]));
}
}*/
//Rxx1 = Rxx1_out;
for (i = 0; i < L1; i++)
{
for (j = 0; j < L1; j++)
{
Rxx1[i][j] = Rxx1_out[i][j];
}
}
}
__device__ __host__ void output_beam(int M_elements, int emit_aperture, int L1, int L2, cuDoubleComplex *beamDASDAS, cuDoubleComplex *x_pointer, cuDoubleComplex *wmv1, cuDoubleComplex *wmv2, int idx, int a, int b) {
int l1, l2;
int i, j;
cuDoubleComplex xL[52][52] = { 0.0 };
for (l1 = 0; l1 < M_elements - L1+1; l1++)//Rows
{
for (l2 = 0; l2 < emit_aperture - L2+1; l2++)//columns
{
for (i = 0; i < L2; i++)//Rows
{
for (j = 0; j < L1; j++)//Columns
{
xL[i][j] = cuCadd(xL[i][j], x_pointer[idx * 128 * 128 + M_elements * (i + l2) + (l1 + j)]);
}
}
}
}
cuDoubleComplex temp[52] = { 0.0 };
for (l1 = 0; l1 < L1; l1++)
{
for (l2 = 0; l2 < L2; l2++)
{
temp[l1] = cuCadd(temp[l1], cuCmul(cuConj(wmv2[52 * idx + l2]), xL[l2][l1]));
printf("temp[%d] of %d is %e,%e", l1, l2, cuCreal(temp[l1]), cuCimag(temp[l1]));
}
}
for (int i = 0; i < L1; i++)
{
beamDASDAS[(b - 1) * 121 + (a - 1)] = cuCadd(beamDASDAS[(b - 1) * 121 + (a - 1)], cuCmul(temp[i], wmv1[i]));
}
}
__device__ __host__ void weigt_cal_MV(int M_elements, int emit_aperture, cuDoubleComplex *x_pointer, cuDoubleComplex *wmv1, cuDoubleComplex *wmv2, int idx, int L1, int L2)
{
int i, j, k, l;
printf("Have entered into weight_cal_MV function!\n");
cuDoubleComplex Rxx1[52][52] = { 0.0 };
printf("Have finished the definiton of Rxx1[52][52]!\n");
for (l = 0; l < M_elements - L1+1; l++)
{
//printf("Have entered into Rxx1 calculation function!\n");
for (i = 0; i < L1; i++)
{
for (j = 0; j < L1; j++)
{
for (k = 0; k < M_elements; k++)
{
Rxx1[i][j] = cuCadd(Rxx1[i][j], cuCmul(x_pointer[idx * 128 * 128 + (k) * M_elements + i+l ], cuConj(x_pointer[idx * 128 * 128 + k * M_elements + j+l])));
}
//printf("Rxx1[%d][%d]=%e,%e\n", i, j, cuCreal(Rxx1[i][j]), cuCimag(Rxx1[i][j]));
}
}
//printf("Have calculated the Rxx1!\n");
/*printf("l=%d\n", l);
for (i = 0; i < L1; i++)
{
for (j = 0; j < L1; j++)
{
printf("Rxx1[%d][%d]=%e,%e\n", i, j, cuCreal(Rxx1[i][j]), cuCimag(Rxx1[i][j]));
}
}*/
}
/*printf("Have calculated the Rxx1!\n");
for (i = 0; i < L1; i++)
{
for (j = 0; j < L1; j++)
{
printf("Rxx1[%d][%d]=%e,%e\n", i, j, cuCreal(Rxx1[i][j]), cuCimag(Rxx1[i][j]));
}
}*/
cuDoubleComplex trace = make_cuDoubleComplex(0.0, 0.0);
for (i = 0; i < L1; i++)
{
trace = cuCadd(Rxx1[i][i], trace);
}
for (i = 0; i < L1; i++)
{
Rxx1[i][i] = cuCadd(Rxx1[i][i], cuCmul(trace, (make_cuDoubleComplex((double)(0.01 / L1), 0.0))));
}
printf("Have add the trace with Rxx1!\n");
//The above has been checked right!
/*for (i = 0; i < L1; i++)
{
for (j = 0; j < L1; j++)
{
printf("Rxx1[%d][%d]=%e,%e\n", i, j, cuCreal(Rxx1[i][j]), cuCimag(Rxx1[i][j]));
}
}*/
matrix_inv(Rxx1, L1);
printf("Have finished the inversion of Rxx1!\n");
cuDoubleComplex right_value = make_cuDoubleComplex(0.0, 0.0);
for (int i = 0; i < L1; i++)
{
for (int j = 0; j < L1; j++)
{
right_value = cuCadd(right_value, Rxx1[i][j]);
}
}
right_value = cuCdiv(make_cuDoubleComplex(1.0, 0.0), right_value);
for (i = 0; i < L1; i++)
{
for (j = 0; j < L1; j++)
{
wmv1[i + idx * 52] = cuCadd(Rxx1[i][j], wmv1[i + idx * 52]);
}
wmv1[i + idx * 52] = cuCmul(wmv1[i + idx * 52], right_value);
//The following is a trick to get the correct result of wmv1; allowing the fause of diagnol element in Rxx1_inv matrix.
wmv1[i + idx * 52] = make_cuDoubleComplex((cuCreal(wmv1[i + idx * 52]) - cuCimag(wmv1[i + idx * 52])), 0.0);
}
printf("Have got the final values of wmv1!\n");
//To now, we have calculated the weight of wmv1, and similarly we should calculate the weights fo wmv2
for (i = 0; i < L1; i++)
{
printf("wmv1[%d] is %e,%e\n", i, cuCreal(wmv1[i]), cuCimag(wmv1[i]));
}
cuDoubleComplex Rxx2[52][52] = { 0.0 };
for (l = 0; l < emit_aperture - L2+1; l++)
{
for (i = 0; i < L2; i++)
{
for (j = 0; j < L2; j++)
{
for (k = 0; k < emit_aperture; k++)
{
Rxx2[i][j] = cuCadd(Rxx2[i][j] , cuCmul(x_pointer[idx * 128 * 128 + k + (i + l) * emit_aperture], cuConj(x_pointer[idx * 128 * 128 + k + (j + l) * emit_aperture])));
}
}
}
}
trace = make_cuDoubleComplex(0.0, 0.0);
for (i = 0; i < L2; i++)
{
trace = cuCadd(Rxx2[i][i], trace);
}
for (i = 0; i < L2; i++)
{
Rxx2[i][i] = cuCadd(Rxx2[i][i], cuCmul(trace, (make_cuDoubleComplex((double)(0.01 / L2), 0.0))));
}
printf("Have got Rxx2!\n");
matrix_inv(Rxx2, L2);
printf("Have finished the inversion of Rxx2!\n");
right_value = make_cuDoubleComplex(0.0, 0.0);
for (int i = 0; i < L2; i++)
{
for (int j = 0; j < L2; j++)
{
right_value = cuCadd(right_value, Rxx2[i][j]);
}
}
right_value = cuCdiv(make_cuDoubleComplex(1.0, 0.0), right_value);
for (i = 0; i < L2; i++)
{
for (j = 0; j < L2; j++)
{
wmv2[i + idx * 52] = cuCadd(Rxx2[i][j], wmv2[i + idx * 52]);
}
wmv2[i + idx * 52] = cuCmul(wmv2[i + idx * 52], right_value);
//The following is a trick to get the correct result of wmv1; allowing the fause of diagnol element in Rxx1_inv matrix.
wmv2[i + idx * 52] = make_cuDoubleComplex((cuCreal(wmv2[i + idx * 52]) - cuCimag(wmv2[i + idx * 52])), 0.0);
}
printf("Have got the final wmv2!\n");
for (i = 0; i < L1; i++)
{
printf("wmv2[%d] is %e,%e\n", i, cuCreal(wmv2[i]), cuCimag(wmv2[i]));
}
}
int main()
{
int i;
double index_finished = 0;
int index_1;
int row_v2;
int column_v2;
int temp;
int temp_1;
int temp_2;
/*******************************************数据预处理部分---将v2的complex数据读进来**************************************/
complex<double> * init_M1 = new complex<double>[3534 * 16384];
//complex<double> *init_M1;
pMF = matOpen("D:\\WenshuaiZhao\\ProjectFiles\\VisualStudioFiles\\Ultrasound_GPU\\GPU_Data\\v2.mat", "r");//打开MAT文件,返回文件指针
pA = matGetVariable(pMF, "v2");//获取v2.mat文件里的变量
init_real = (double*)mxGetPr(pA);
init_imaginary = (double*)mxGetPi(pA);
//init_M1 = (complex<double>*)mxGetData(pA);
for (i = 0; i < TOTAL_ELEMENTS; i++)
{
complex<double> temp(init_real[i], init_imaginary[i]);
init_M1[i] = temp;
}//将从v2读出的实部和虚部重新组合在一起,放入init_M1.
for (i = 0; i < 10; i++)
{
cout << "init_M1"
<< i
<< "="
<< init_M1[i] << endl;
}//验证init_M1的数据同v2的原始数据是一致的,复数。
/*******************************************数据预处理部分结束*********************************************************/
int M = mxGetM(pA);
int N = mxGetN(pA);
int a, b;
double xp, zp;
double xr[N_elements];
double t_delay[N_elements];
double theta_ctrb[N_elements];
double theta_threshold;
int theta_start;
int theta_end;
int idx = 0;
int k;
cuDoubleComplex *beamDASDAS = new cuDoubleComplex [xsize*ysize];
memset(beamDASDAS, 0, sizeof(beamDASDAS));
int verify[501 * 121];
//***************************************主循环开始*************************************//
for (a = 1; a < (ysize + 1); a++)
{
for (b = 1; b < (xsize + 1); b++)
{
theta_threshold = 2.8;
theta_start = 0;
theta_end = 0;
xp = x_begin + d_x * (a - 1);
zp = z_begin + d_z * (b - 1);
/********************************计算子孔径的大小,以及,对应像素点,各个阵元的延时***************************/
for (i = 0; i < (N_elements); i++)
{
xr[i] = a_begin + pitch * i;
t_delay[i] = sqrt(pow((xp - xr[i]), 2) + pow(zp, 2)) / c;
theta_ctrb[i] = zp / (abs(xp - xr[i]));
}
/*for (i = 0; i < (N_elements); i++)
{
cout << "theta_ctrb "<<i<<"is " << theta_ctrb[i] << endl;
}*/
k = 1;
while ((k <= N_elements) && (theta_ctrb[k - 1] < theta_threshold))
{
k = k + 1;
}//求出theta_start的值
if (k == N_elements + 1)
NULL;
//开始求theta_end的值
else
{
theta_start = k;
// cout << "k or theta_start is" << k << endl;
while ((k <= N_elements) && (theta_ctrb[k - 1] >= theta_threshold))
{
k = k + 1;
}
if (k == N_elements + 1)
theta_end = k - 1;
else
{
theta_end = k;
}
// cout << "k or theta_end is" << k << endl;
}
//求出theta_end的值
//验证theta_start的值
/*if ((a < 2) && (b < 9))
cout << "theta_start is:" << theta_start << endl;*/
//验证计算出的theta_start和theta_end正确与否
/*cout << "theta_start=" << theta_start << endl;
cout << "theta_end=" << theta_end << endl;*/
//verify[(a - 1)*ysize + b - 1] = theta_start;
/*******************************计算出了theta_start和theta_end******************************/
/*******************************为计算正确延时和回波矩阵做准备******************************/
M_elements = theta_end - theta_start + 1;
emit_aperture = M_elements;
emit_pitch = 1;
emit_start = theta_start;
complex<double> * x_pointer = new complex<double>[128*128];//为x数组分配动态内存,记得用完delete,x二维数组,是经过正取延时,并且取正确孔径的,回波矩阵。维度为M_elements*M_elements
double * delay_pointer = new double[M_elements * 1];//为delay数组分配动态内存,记得用完delete
int *delay_int = new int[M_elements * 1];//为取整后的delay值分配内存。
//为刚分配内存的三个数组初始化
memset(delay_pointer, 0, sizeof(delay_pointer));
memset(delay_int, 0, sizeof(delay_pointer));
memset(x_pointer, 0, sizeof(x_pointer));
//*************接下来计算正确延时和回波矩阵x【M_elements*M_elements】*******************************************//
for (Trans_elements = emit_start; Trans_elements <= (emit_start + emit_pitch * (emit_aperture - 1)); Trans_elements++)
{
for (i = theta_start; i <= theta_end; i++)
{
temp = i - theta_start;
delay_pointer[temp] = t_delay[Trans_elements - 1] + t_delay[i - 1];
delay_pointer[temp] = delay_pointer[temp] - t1;
delay_pointer[temp] = ((delay_pointer[temp] * fs) + 25.5) + zerolength;
delay_int[temp] = (round)(delay_pointer[temp]);
// int abc = delay_int[temp];
}
for (i = theta_start; i <= theta_end; i++)
{
index_1 = (i - theta_start);
row_v2 = delay_int[index_1];//此处计算有误!
column_v2 = (Trans_elements - 1)*N_elements + i - 1;
temp_1 = ((Trans_elements - emit_start) / emit_pitch)*M_elements + i - theta_start;
//x_pointer[temp_1] = init_M1[row_v2*M + (Trans_elements - 1)*N_elements + i-1];//M为v2矩阵的行数
temp_2 = column_v2 * M + row_v2 - 1;
x_pointer[temp_1+idx*128*128] = init_M1[temp_2];//M为v2矩阵的行数
//((Trans_elements - 1)*N_elements + i - 1)*M+row_v2
}
}
//*************计算延时和回波矩阵完毕*********************************************************************//
cuDoubleComplex * x_pointer_cu = new cuDoubleComplex[128 * 128];
memcpy(x_pointer_cu, x_pointer, (emit_aperture*M_elements*sizeof(cuDoubleComplex)));
cuDoubleComplex * wmv1 = new cuDoubleComplex[52];
cuDoubleComplex * wmv2 = new cuDoubleComplex[52];
double subarray_length = 0.4;
int L1 = rint(M_elements*subarray_length);
int L2 = rint(emit_aperture*subarray_length);
printf("Begin to use weight_cal_MV function!\n");
weigt_cal_MV(M_elements, emit_aperture, x_pointer_cu, wmv1, wmv2, idx, L1, L2);
for (i = 0; i < L1; i++)
{
printf("wmv1[%d] is %e,%e\n", i, cuCreal(wmv1[idx * 52 + i]), cuCimag(wmv1[idx * 52 + i]));
}
//output_beam(beamDASDAS,x_pointer,wmv1,wmv2,idx);
output_beam(M_elements, emit_aperture, L1, L2, beamDASDAS, x_pointer_cu, wmv1, wmv2, idx, a, b);
printf("beamDASDAS[%d] is %e,%e", ((b - 1) * 121 + (a - 1)), cuCreal(beamDASDAS[(b - 1) * 121 + (a - 1)]), cuCimag(beamDASDAS[(b - 1) * 121 + (a - 1)]));
//*************接下来计算本像素点的beamDASDAS*******************************************//
/* for (i = 0; i < M_elements; i++)
{
int j;
for (j = 0; j < M_elements; j++)
{
complex<double> temp_1 = 0;
temp_1 = x_pointer[i*M_elements + j] + beamDASDAS[(b - 1)*ysize + (a - 1)];
beamDASDAS[(b - 1)*ysize + (a - 1)] = temp_1;
}
}
beamDASDAS[(b - 1)*ysize + (a - 1)] = beamDASDAS[(b - 1)*ysize + (a - 1)] / ((double)(M_elements*M_elements)); */
//*****************计算出了beamDASDAS*************************************************//
//删除所用的动态内存
delete[] wmv1;
delete[] wmv2;
delete[] x_pointer_cu;
delete[]x_pointer;
delete[]delay_pointer;
delete[]delay_int;
}
index_finished = 100.0 * a / ysize;
printf("%.6lf\n", index_finished);
}
//************************************************主循环结束*********************************************************//
/***********************打印结果**********************************************/
//printf("The beamDASDAS matrix 501*121 is: \n");
for (i = 0; i < 8; i++)
{
cout << "beamDASDAS[" << i << "] is: ";
cout << cuCreal(beamDASDAS[i]);
cout << ",";
cout << cuCreal(beamDASDAS[i]);
/*cout << "verify is";
cout << verify[i];*/
cout << endl;
}
//*******************将beamDASDAS的结果保存到MAT文件,便于MATLAB进行图像生成***************************************//
//pMF_out = matOpen("E:\\Project_files\\visual studio projects\\Ultrasound_GPU\\GPU_Data\\out_beamDASDAS.mat", "w");
//cout << "已完成打开文件" << endl;
////mwArray matrixComplex(row, column, mxDOUBLE_CLASS, mxCOMPLEX);//定义数组,行,列,double类型复数矩阵
////pA = mxCreateStructMatrix(row, column, complex<double>);.
//pA_out = mxCreateDoubleMatrix(xsize, ysize, mxCOMPLEX);//pA_out是mxArray类型的指针
//cout << "已完成创建矩阵" << endl;
////mxSetData(pA_out, out_beam);
///*在早前版本的matlab自带的版本中使用的是mxSetData函数进行数值输入,
// 但是在比较新的版本中,这个函数使用会出现错误,笔者也不知道为什么。
// 所以在不确定的情况下,你可以使用memcpy;*/
//memcpy((void*)mxGetData((pA_out)), beamDASDAS, sizeof(complex<double>) * xsize*ysize);
////memcpy((complex<double>*)mxGetData((pA_out)), beamDASDAS, sizeof(complex<double>) * xsize*ysize);
////使用mxGetData函数获取数据阵列中的数据;返回时需要使用强制类型转换。
///*for (i = 0; i < 10; i++)
//{
// cout << "pA_out is:"
// << mxGetData(pA_out) << endl;
//}*/
//cout << "已完成copy数据" << endl;
//matPutVariable(pMF_out, "beamDASDAS_GPU", pA_out);//如果matlab正在读该变量,则运行至此时会报错,只需在matlab里clear一下就OK了!
//cout << "已完成放入变量" << endl;
////matClose(pMF_out);
/***************************************已得到正确beamDASDAS矩阵,接下来进行对数压缩************************/
////先求beamDASDAS的绝对值
//double *beam2 = new double[xsize*ysize];
//double *beamshow = new double[xsize*ysize];
//double peakall=0;
//double peakall_2 = 0;
//for (i = 0; i < xsize*ysize; i++)
//{
// beam2[i] = abs(beamDASDAS[i]);
// if (beam2[i] >= peakall)
// peakall = beam2[i];
//}
//for (i = 0; i < xsize*ysize; i++)
//{
// beamshow[i] = 20 * log10(beam2[i] / peakall);
// if (beamshow[i] < -60)
// beamshow[i] = -60;
//}
//for (i = 0; i < xsize*ysize; i++)
//{
// beamshow[i] = 60 + beamshow[i];
//}
//for (i = 0; i < xsize*ysize; i++)
//{
// if(peakall_2<=beamshow[i])
// peakall_2=beamshow[i];
//}
//
//for (i = 0; i < xsize*ysize; i++)
//{
// beamshow[i] = 255*(beamshow[i] / peakall_2);
//
//}
//for (i = 0; i < 8; i++)
//{
// cout << "beamshow[" << i << "] is: ";
// cout << beamshow[i];
// /*cout << "verify is";
// cout << verify[i];*/
// cout << endl;
//}
//for (i = 0; i < xsize; i++)
//{
// for (int j = 0; j < ysize; j++)
// {
// Result[i][j] = unsigned char((floor(beamshow[i * 121 + j])));
// }
//}
//Mat MM=Mat(501, 121, CV_8UC1);
//memcpy(MM.data, Result, sizeof(unsigned char)*xsize*ysize);
////Mat MM= Mat(501, 121, CV_32SC3, Result).clone();
////namedWindow("Ultrasound_Image");
//imshow("Ultrasound_Image", MM);
////imshow("Ultrasound_Image", Result);
delete[]beamDASDAS;
delete[]init_M1;
//printf("One Element is %e\n",init_M1[M*3]);
//printf("One Element is %lf\n", init_M1[M * 3]);
//printf("The no. of rows of Matrix M1 is %d\n", M);
//printf("The no. of column of Matrix M1 is %d\n", N);
getchar();
getchar();
return 0;
}
|
#ifndef _XStringEx_h_
#define _XStringEx_h_
#include <string.h>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <iomanip>
#include <list>
#include <map>
#include <unordered_map>
#include <stdint.h>
#include <string>
#include <vector>
#include <list>
#include <fstream>
#include <assert.h>
#include <cstdarg>
#include <time.h>
#include <ctype.h>
#include <sstream>
#include <algorithm>
//#include <functional>
//#include <cctype>
//#include <locale>
//#include "StrFormat.h"
//#include "StrUtil.h"
using namespace std;
typedef unsigned char uchar;
class XTextFile;
class XString
{
public:
static size_t ReplaceAll(string& str, string old_str, string new_str)
{
size_t rc = 0;
size_t ol = old_str.length();
// size_t nl = new_str.length();
while(1)
{
std::string::size_type p = str.find(old_str);
if (p == std::string::npos) break;
str.replace(str.begin() + p, str.begin() + p + ol, new_str);
rc++;
}
return rc;
}
static size_t ReplaceForSQLComment(string& str)
{
size_t rc = ReplaceAll(str, "--", "--");
rc+= ReplaceAll(str, "/*", "/*");
rc += ReplaceAll(str, "*/", "*/");
return rc;
}
static inline void xsnprintf(char * buf, size_t len, const char * info, ...)
{
assert(len >= sizeof(char));
int rs = 0;
va_list args;
va_start(args, info);
#ifdef _MSC_VER
rs = ::_vsnprintf_s(buf, len - 1, len - 1, info, args);
#else
rs = vsnprintf(buf, len - 1, info, args);
#endif
va_end(args);
if (rs<0) { buf[len - 1] = 0; }
}
/**
找到 %s 的位置 判断其长度 累加 其他的留 256
效率比较低 注意谨慎使用
*/
static std::string createWithFormat(const char* fmt, ...)
{
int rs = 0;
const char* _start = NULL;
const char* _end = NULL;
size_t total = 256;
va_list ap;
va_start(ap, fmt);
_end = fmt;
do
{
_start = strstr(_end, "%");
if (_start == NULL) break;
_end = _start + 1;
if (_end[0] == '%') continue;
if (_end[0] == 's') {
total += strlen(va_arg(ap, const char*));
}
else {
total += 256;
va_arg(ap, int);
}
} while (1);
va_end(ap);
va_start(ap, fmt);
char *buf = new char[total + 1];
//memset(buf, 0, total + 1);
#ifdef _MSC_VER
rs = ::_vsnprintf_s_l(buf, total - 1, total - 1, fmt, NULL, ap);
//rs = vsprintf(buf, fmt, ap);
//rs = vsnprintf(buf, total - 1, fmt, ap);
#else
rs = vsnprintf(buf, total - 1, fmt, ap);
#endif
buf[rs] = 0;
std::string s;
s.append(buf, rs);
delete[] buf;
va_end(ap);
return s;
}
static std::string createWithTime(time_t t)
{
char buf[256];
struct tm tt = { 0 };
#if defined(_MSC_VER)
localtime_s(&tt, &t);
#else //linux
localtime_r(&t, &tt);
#endif
xsnprintf(buf,256, "%d-%02d-%02d %02d:%02d:%02d",
tt.tm_year + 1900, tt.tm_mon + 1, tt.tm_mday,
tt.tm_hour, tt.tm_min, tt.tm_sec);
return buf;
}
static std::string createWithBool(bool v)
{
return v ? "true" : "false";
}
/**
去除前面的空格
*/
static size_t TrimSpaceLeft(std::string& str)
{
size_t k = 0;
//string::iterator i;
//for (i = str.begin(); i != str.end(); i++) {
// if (!::isspace(*i)) {
// break;
// }
// k++;
//}
//if (i == str.end()) {
// str.clear();
//}
//else {
// if(i!=str.begin()) str.erase(str.begin(), i);
//}
string ch;
for (size_t i = 0; i < str.length(); i++)
{
ch = str.substr(i, 1);
if (ch.compare(" ") == 0) { k++;continue; }
break;
}
if(k>0) str.erase(0, k);
return k;
}
/**
去除后面的空格
*/
static size_t TrimSpaceRight(std::string& str)
{
size_t k = 0;
//string::iterator i;
//for (i = str.end() - 1; ; i--) {
// if (!isspace(*i)) {
// if(i+1!=str.end()) str.erase(i + 1, str.end());
// break;
// }
// k++;
// if (i == str.begin()) {
// str.clear();
// break;
// }
//}
string ch;
size_t i = str.length() - 1;
for (; i >=0; i--)
{
ch = str.substr(i, 1);
if (ch.compare(" ") == 0) {
k++; continue;
}
break;
}
if(k>0) str.erase(i+1);
return k;
}
static size_t TrimSpaceLeftAndRight(std::string& str)
{
//return 0;
return TrimSpaceLeft(str) + TrimSpaceRight(str);
}
/*
// trim from start
static inline std::string& ltrim(std::string &s)
{
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}
// trim from end
static inline std::string& rtrim(std::string &s)
{
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
// trim from both ends
static inline std::string& trim(std::string &s)
{
return ltrim(rtrim(s));
}
*/
/**
在文本内容中获取第一行
*/
std::string textFirstLine(const char* src, int size, const char* emark = "\r\n")
{
std::string result;
const char* p = strstr(src,emark);
if (p > src + size) return "";
result.append(src, p - src + strlen(emark));
return result;
}
};
template<typename T>
std::string XToString(T val)
{
std::stringstream sss;
sss << (T)val;
return sss.str();
}
void test_xto_sting();
class XStringList
{
public:
/*
struct ABM
{
size_t a,b;
size_t size(){return b-a;}
};
*/
vector<size_t> lines;
string m_dat; //内容存储
public:
XStringList(){}
virtual ~XStringList(){}
protected:
const char* m_xendl;
const char* m_xclose;
void ParseString(const char* _spchar = "\r\n", const char* _close = "\"");
public:
// ssize_t Parse(const char* src);
// ssize_t Parse2(const char* src,size_t fl);
// _spchar 分隔字符串
// size_t ParseEx(const char* lpBuf,size_t lpBufSize,const char* _spchar);
/*
_close 如果遇到这个符号 分割符号将被跳过,直到遇到第二个分割符号
*/
size_t ParseEx2(const char* lpBuf,size_t lpBufSize=0,const char* _spchar="\r\n", const char* _close="\"");
public:
void FixABSpace();//删除前后的空格
public:
static void Test();
int GetFeildLineVauleInt(string keyname);
string GetFeildLineVauleString(string keyname);
// ssize_t GetVaulePos(const char* fieldn);
void List();
// void Add(const char* text); //增加一行
void push_back(string str);
public:
/**
行数
*/
size_t size();
size_t LoadFromFile(const char* fname);
size_t LoadFromString(string src,const char* lineMark="\r\n",const char* _closeMark="\"");
virtual string operator[](size_t idx);
string at(size_t idx);
string GetLineString(size_t idx) {
return at(idx);
}
//从头开始 返回完全符合这个词的后面一个词串
//string NextLine(string str);
};
class XTokenizer : public XStringList
{
public:
XTokenizer(){};
XTokenizer(const std::string& _str, const std::string _delim=" ");
XTokenizer(const char* _str,std::size_t sz=0, const std::string _delim=" ");
virtual ~XTokenizer(){};
// int countTokens();
// bool hasMoreTokens();
// std::string nextToken();
// int nextIntToken();
// double nextFloatToken();
// std::string nextToken(const std::string& delim);
// std::string remainingString();
// std::string filterNextToken(const std::string& filterStr);
/**
*
* */
const char* GetTokenValue(std::string keyname);
int GetTokenValueInt(const std::string& keyname);
double GetTokenValueFloat(const std::string& keyname);
//第几个位置上
int GetTokenValueInt(unsigned int _pos);
string GetString(unsigned int _pos);
std::string GetValueStringByIndex(unsigned int _idx);
int GetValueIntByIndex(unsigned int _idx);
/**
* 返回关键字后面的内容
*/
string GetTokenRemain(const std::string& keyname);
/**
* 是否存在
* */
bool IsExistToken(const std::string& keyname);
size_t GetTokenIndex(const string& keyname);
// size_t Parse(const char* lpBuf,ssize_t lpBufSize=-1,const char* _spchar=" ", char _close='"');
void Print();
bool FirstTokenIs(const std::string& keyname);
bool SecondTokenIs(const std::string& keyname);
//忽略大小写
bool FirstTokenIsIcase(const std::string& keyname);
/**
返回行数
*/
size_t NumLines() { return lines.size(); };
public:
// string m_dat;
// std::list<string> token_str;
// std::string delim;
static string TokenClear(string str,string rstr=" \r\n",int _type=1);
string GetTokenValueString(const string& keyname);
protected:
// std::list<string>::iterator cur_token;
};
//void test_XTokenizer();
/**
文本参数
#字母开头的本行注释掉
=分开前后 如果行中不存在 = 抛弃
*/
class XTextParamList
{
std::map<std::string, std::string> valueMap;
protected:
void ParseLine(std::string line);
public:
static std::string GetValue(std::string filename,std::string keyname);
void LoadFromAsciiFile(std::string filename);
void Parse(const char* _lpBuf, size_t _size);
std::string GetValue(std::string keyname);
std::wstring GetValueWString(std::string keyname);
bool IsExist(std::string keyname);
void Print();
void LoadFile(const char* filename);
};
namespace XStringUtil
{
bool utf8CharToUcs2Char(const char* utf8Tok, wchar_t* ucs2Char, unsigned int* utf8TokLen);
void ucs2CharToUtf8Char(const wchar_t ucs2Char, char* utf8Tok);
std::wstring utf8ToUcs2(const std::string& utf8Str);
std::string ucs2ToUtf8(const std::wstring& ucs2Str);
};
class XTextFile
{
protected:
uchar* dat;
size_t len;
public:
static FILE* callfopen(const char* filepath, const char* mode)
{
assert(filepath);
assert(mode);
#if defined(_MSC_VER) && (_MSC_VER >= 1400 ) && (!defined WINCE)
FILE* fp = 0;
errno_t err = fopen_s(&fp, filepath, mode);
if (err) {
return 0;
}
#else
FILE* fp = fopen(filepath, mode);
#endif
return fp;
}
public:
XTextFile();
virtual ~XTextFile();
bool LoadFile(const char* filename);
int LoadFile(FILE*);
//operator std::string();
const char* c_str() { return (const char*)dat; };
size_t size() { return len; };
};
//////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////
const char kUnreservedChar[] = {
//0 1 2 3 4 5 6 7 8 9 A B C D E F
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, // 2
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 3
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, // 5
0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, // 7
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 8
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 9
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // A
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // B
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // C
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // D
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // E
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 // F
};
const char kHexToNum[] = {
// 0 1 2 3 4 5 6 7 8 9 A B C D E F
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 0
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 1
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 2
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, // 3
-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 4
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 5
-1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 6
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 7
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 8
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 9
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // A
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // B
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // C
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // D
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // E
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 // F
};
class CxUrlEncoder {
public:
static inline void Encode(const std::string &in, std::string *out, bool uppercase = false) {
std::stringstream ss;
for (std::string::const_iterator it = in.begin(); it != in.end(); ++it) {
if (kUnreservedChar[*it]) {
ss << *it;
}
else {
ss << '%' << std::setfill('0') << std::hex;
if (uppercase) ss << std::uppercase;
ss << (int)*it;
}
}
out->assign(ss.str());
}
static inline std::string Encode(const std::string &in, bool uppercase = false) {
std::string out;
Encode(in, &out, uppercase);
return out;
}
static inline bool Decode(const std::string &in, std::string *out) {
std::stringstream ss;
std::string::const_iterator it = in.begin();
char tmp, encoded_char;
while (it != in.end()) {
if (*it == '%') {
if (++it == in.end()) return false;
tmp = kHexToNum[*it];
if (tmp < 0) return false;
encoded_char = (16 * tmp);
if (++it == in.end()) return false;
tmp = kHexToNum[*it];
if (tmp < 0) return false;
encoded_char += tmp;
++it;
ss << encoded_char;
}
else {
ss << *it;
++it;
}
}
out->assign(ss.str());
return true;
}
static inline std::string Decode(const std::string &in) {
std::string out;
Decode(in, &out);
return out;
}
private:
};
class CxHttpHead
{
public:
enum _action {
GET,
POST,
};
public:
std::unordered_map<std::string, std::string> field_values;
public:
std::string Document;
std::string version;
int action;
public:
void ParseGet(const char* buf, int size)
{
std::string str;
str.append(buf, size);
ParseGet(str);
}
void ParseGet(std::string _uri)
{
field_values.clear();
std::string str= CxUrlEncoder::Decode(_uri);
/*
GET /index.html?op=download&ino=2941&type=file HTTP/1.1
*/
XTokenizer tok;
tok.ParseEx2(str.c_str(), str.length(), " ");
std::string _doc=tok.GetLineString(1);
if (_doc.empty()) return;
tok.ParseEx2(_doc.c_str(), _doc.length(), "?");
Document = tok.GetLineString(0);
if (tok.size() < 2) return;
tok.ParseEx2(tok.at(1).c_str(), tok.at(1).length(), "&");
for (size_t l=0;l<tok.size();l++)
{
string _feild = tok.GetLineString(l);
printf("%s %d:%s\n",__FILE__,__LINE__,_feild.c_str());
//XTokenizer tok2;
//tok2.ParseEx2(_feild.c_str(), _feild.length(), "=");
//if (tok2.size() == 2) {
// field_values[tok2.at(0)] = tok2.at(1);
//}
int pos=(int)_feild.find("=");
if (pos > 0) {
string k = _feild.substr(0, pos);
string v = _feild.substr(pos + 1, -1);
field_values[k] = v;
}
}
}
/**
获取文档后面跟着的参数值
*/
const char* GetKeyValue(const std::string& kname)
{
auto it = field_values.find(kname);
if (it != field_values.end()) return (it->second).c_str();
return NULL;
}
int GetKeyValueInt(const std::string& kname)
{
const char* v = GetKeyValue(kname);
if (v == NULL) return 0;
return atoi(v);
}
std::string GetKeyValueString(const std::string& kname)
{
auto it = field_values.find(kname);
if (it != field_values.end()) return (it->second);
return "";
}
};
#endif
|
/** @file
*****************************************************************************
* @author This file is part of libsnark, developed by SCIPR Lab
* and contributors (see AUTHORS).
* @copyright MIT license (see LICENSE file)
*****************************************************************************/
#ifndef BLS48_G1_HPP_
#define BLS48_G1_HPP_
#include <vector>
#include "algebra/curves/bls48/bls48_init.hpp"
#include "algebra/curves/curve_utils.hpp"
namespace libsnark {
class bls48_G1;
std::ostream& operator<<(std::ostream &, const bls48_G1&);
std::istream& operator>>(std::istream &, bls48_G1&);
class bls48_G1 {
public:
#ifdef PROFILE_OP_COUNTS
static long long add_cnt;
static long long dbl_cnt;
#endif
static std::vector<size_t> wnaf_window_table;
static std::vector<size_t> fixed_base_exp_window_table;
static bls48_G1 G1_zero;
static bls48_G1 G1_one;
typedef bls48_Fq base_field;
typedef bls48_Fr scalar_field;
bls48_Fq X, Y, Z;
// using Jacobian coordinates
bls48_G1();
bls48_G1(const bls48_Fq& X, const bls48_Fq& Y, const bls48_Fq& Z) : X(X), Y(Y), Z(Z) {};
void print() const;
void print_coordinates() const;
void to_affine_coordinates();
void to_special();
bool is_special() const;
bool is_zero() const;
bool operator==(const bls48_G1 &other) const;
bool operator!=(const bls48_G1 &other) const;
bls48_G1 operator+(const bls48_G1 &other) const;
bls48_G1 operator-() const;
bls48_G1 operator-(const bls48_G1 &other) const;
bls48_G1 add(const bls48_G1 &other) const;
bls48_G1 mixed_add(const bls48_G1 &other) const;
bls48_G1 dbl() const;
bool is_well_formed() const;
static bls48_G1 zero();
static bls48_G1 one();
static bls48_G1 random_element();
static size_t size_in_bits() { return base_field::size_in_bits() + 1; }
static bigint<base_field::num_limbs> base_field_char() { return base_field::field_char(); }
static bigint<scalar_field::num_limbs> order() { return scalar_field::field_char(); }
friend std::ostream& operator<<(std::ostream &out, const bls48_G1 &g);
friend std::istream& operator>>(std::istream &in, bls48_G1 &g);
};
template<mp_size_t m>
bls48_G1 operator*(const bigint<m> &lhs, const bls48_G1 &rhs)
{
return scalar_mul<bls48_G1, m>(rhs, lhs);
}
template<mp_size_t m, const bigint<m>& modulus_p>
bls48_G1 operator*(const Fp_model<m,modulus_p> &lhs, const bls48_G1 &rhs)
{
return scalar_mul<bls48_G1, m>(rhs, lhs.as_bigint());
}
std::ostream& operator<<(std::ostream& out, const std::vector<bls48_G1> &v);
std::istream& operator>>(std::istream& in, std::vector<bls48_G1> &v);
template<typename T>
void batch_to_special_all_non_zeros(std::vector<T> &vec);
template<>
void batch_to_special_all_non_zeros<bls48_G1>(std::vector<bls48_G1> &vec);
} // libsnark
#endif // BLS48_G1_HPP_
|
#ifndef __mir_mobile__GameSocket__
#define __mir_mobile__GameSocket__
#include <iostream>
#include "figure/Monomer.h"
class GameSocket {
public:
static void attack(Monomer* one, Monomer* two, int skillNumber);
static void attackGroup(Monomer* one, vector<Monomer*> two, int skillNumber);
static void sendRoleCreate(Node* node, int roleID, const char* nickName);
};
#endif /* defined(__mir_mobile__GameSocket__) */
|
#include "airport.h"
vector<taxiway*> mainPath;
taxiway *rwCommon;
vector<taxiway*> toGate;
vector<taxiway*> fromGate;
//
simQueue sq;
void configure_taxiways_and_runways(){
int mainPathID = 0;
// landing runway and right taxiway
mainPath.push_back(new taxiway(RW1X1,RW1Y1,RW1X2,RW1Y2,30,mainPathID++));
mainPath.push_back(new taxiway(RW1X2,RW1Y2,TWX1,TWY1,10,mainPathID++));
float twXdisp = ((float)TWX2-TWX1)/(nGates+1);
float twYdisp = ((float)TWY2-TWY1)/(nGates+1);
for(int i=0; i<=nGates; ++i){ // main taxiway. need 1 + nGates segments.
mainPath.push_back(new taxiway( (TWX1+i*twXdisp), (TWY1+i*twYdisp),
(TWX1+(i+1)*twXdisp),
(TWY1+(i+1)*twYdisp),
5,mainPathID++));
}
// left taxiway and takeoff runway
mainPath.push_back(new taxiway(TWX2,TWY2,RW2X1,RW2Y1,6,mainPathID++));
mainPath.push_back(new taxiway(RW2X1,RW2Y1,RW2X2,RW2Y2,30,mainPathID++));
for(int i=0; i<nGates; ++i){ // taxiways to and from gates
toGate.push_back(new taxiway( TWX1+(i+1)*twXdisp, TWY1+(i+1)*twYdisp,
TWX1+(i+1)*twXdisp, TWYT,
5,i));
fromGate.push_back(new taxiway( TWX1+(i+1)*twXdisp, TWYT,
TWX1+(i+1)*twXdisp, TWY1+(i+1)*twYdisp,
5,i));
}
rwCommon = new taxiway(0,0,0,0,0,0); // common part of runways.
}
void initialize_sq_with_arrival_events(){
ifstream arFile("arrivals.txt");
int arrivalT, serviceT;
int id = 1;
while(arFile >> arrivalT){
arFile >> serviceT;
plane *inPlane = new plane(id++,arrivalT,serviceT);
inPlane->move(300,300);
for(int i=0; i<360; i++){
inPlane->forward(3);
inPlane->right(1);
}
sq.insert(arrivalT,inPlane);
}
}
int main(){
initCanvas("Airport Simulator",800,0,1000,1000);
configure_taxiways_and_runways();
initialize_sq_with_arrival_events();
sq.process_till_empty();
usleep(10000000); // wait for 10 seconds.
// Time to admire canvas before it is closed.
closeCanvas();
}
|
#include "stdafx.h"
#include "renderer.h"
#include "hgesprite.h"
#include "hgeFont.h"
#include "sprite.h"
FontRenderMessage::FontRenderMessage()
:myText("")
,myPosition( Vector2f(0.f,0.f) )
,myAlignment( -1 )
{}
FontRenderMessage::FontRenderMessage( std::string aText, Vector2f aPosition, int anAlignment )
:myText( aText )
,myPosition( aPosition )
,myAlignment( anAlignment )
{}
SpriteRenderMessage::SpriteRenderMessage()
:myPosition( Vector2f(0.f,0.f) )
,mySprite( NULL )
{}
SpriteRenderMessage::SpriteRenderMessage( Vector2f aPosition, hgeSprite* aSprite )
:myPosition( aPosition )
,mySprite( aSprite )
{}
Renderer* Renderer::ourInstance = NULL;
Renderer::Renderer( HGE* aHGE )
:myHGE( aHGE )
{
HTEXTURE texture=myHGE->Texture_Load("ball.png");
mySprite=new hgeSprite(texture, 20.0f,20.0f,20.0f,20.0f);
mySprite->SetBlendMode(0);
myFont= new hgeFont("font1.fnt");
myFontRenderMessages.Init( 10, 30 );
mySpriteRenderMessages.Init( 100, 50 );
}
Renderer::~Renderer()
{
}
bool Renderer::Create( HGE* aHGE )
{
if( ourInstance == NULL )
{
ourInstance = new Renderer( aHGE );
return true;
}
return false;
}
void Renderer::Destroy()
{
SAFE_DELETE( ourInstance );
}
Renderer* Renderer::GetInstance()
{
return ourInstance;
}
void Renderer::TextRender( std::string aText, Vector2f aPosition, int anAlignment )
{
myFontRenderMessages.Add( FontRenderMessage( aText, aPosition, anAlignment ) );
}
void Renderer::SpriteRender( Sprite* aSprite )
{
Vector2f position;
aSprite->GetPosition( position );
mySpriteRenderMessages.Add( SpriteRenderMessage( position, aSprite->GetRawSprite() ) );
}
void Renderer::Render()
{
myHGE->Gfx_BeginScene();
myHGE->Gfx_Clear(0);
for( int index = 0; index < mySpriteRenderMessages.Count(); ++index )
{
mySpriteRenderMessages[index].mySprite->RenderEx(
mySpriteRenderMessages[index].myPosition.myX,
mySpriteRenderMessages[index].myPosition.myY,
0.f
);
}
for( int index = 0; index < myFontRenderMessages.Count(); ++index )
{
myFont->printf( myFontRenderMessages[index].myPosition.myX,
myFontRenderMessages[index].myPosition.myY,
myFontRenderMessages[index].myAlignment,
myFontRenderMessages[index].myText.c_str()
);
}
myHGE->Gfx_EndScene();
myFontRenderMessages.RemoveAll();
mySpriteRenderMessages.RemoveAll();
}
HTEXTURE Renderer::CreateTexture( std::string aFilePath )
{
HTEXTURE texture = myHGE->Texture_Load( aFilePath.c_str() );
return texture;
}
|
// Copyright 2018 Benjamin Bader
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef CPPMETRICS_METRICS_WEIGHTEDSNAPSHOT_H
#define CPPMETRICS_METRICS_WEIGHTEDSNAPSHOT_H
#include <cstddef>
#include <vector>
#include <metrics/Snapshot.h>
namespace cppmetrics {
class WeightedSample
{
public:
WeightedSample(); // for std::map
WeightedSample(long value, double weight);
WeightedSample(const WeightedSample&);
WeightedSample(WeightedSample&&);
WeightedSample& operator=(const WeightedSample&);
WeightedSample& operator=(WeightedSample&&);
long get_value() const noexcept
{
return m_value;
}
double get_weight() const noexcept
{
return m_weight;
}
void set_weight(double weight) noexcept
{
m_weight = weight;
}
private:
long m_value;
double m_weight;
};
class WeightedSnapshot : public Snapshot
{
public:
template <typename InputIterator>
WeightedSnapshot(InputIterator begin, InputIterator end);
WeightedSnapshot(std::vector<WeightedSample>&&);
WeightedSnapshot(const WeightedSnapshot&);
WeightedSnapshot(WeightedSnapshot&&);
~WeightedSnapshot();
public:
double get_value(double quantile) const override;
std::size_t size() const override;
long get_min() const override;
double get_mean() const override;
long get_max() const override;
double get_std_dev() const override;
const std::vector<long> get_values() const override;
private:
struct Element
{
long value;
double norm_weight;
double quantile;
};
std::vector<Element> m_elements;
};
template <typename InputIterator>
WeightedSnapshot::WeightedSnapshot(InputIterator begin, InputIterator end)
: WeightedSnapshot(std::vector<WeightedSample>{begin, end})
{}
}
#endif
|
#include <iostream>
#include <SFML/Graphics.hpp>
#include "lib/mnist.h"
#include "lib/NeuralNetwork.h"
void to_arma(const cv::Mat &src, NeuralNetwork::TrainningSample *dst)
{
for (size_t i = 0; i < src.rows; i++)
{
for (size_t j = 0; j < src.cols; j++)
{
dst->input[i * src.cols + j] = std::isnan(src.at<float>(i, j)) ? 0 : src.at<float>(i, j);
}
}
}
// The activation function
float activationF(float value)
{
return 1.0 / (1 + std::exp(-value));
}
// The derivative of activation function
float activationFD(float value)
{
return value * (1 - value);
}
int main()
{
// read MNIST iamge into OpenCV Mat vector
std::vector<char> labels;
std::vector<cv::Mat> images;
std::vector<NeuralNetwork::TrainningSample *> examples;
unsigned int inputs;
unsigned int outputs;
mnist::readMnistLabels("/home/ensismoebius/workspaces/c-workspace/mnist/data/train-labels.idx1-ubyte", labels);
mnist::readMnistImages("/home/ensismoebius/workspaces/c-workspace/mnist/data/train-images.idx3-ubyte", images);
std::cout << images.size() << std::endl;
std::cout << labels.size() << std::endl;
inputs = images[0].rows * images[0].cols;
outputs = 1;
examples.resize(images.size());
for (int i = 0; i < images.size(); i++)
{
examples[i] = new NeuralNetwork::TrainningSample(inputs, outputs);
examples[i]->target[0] = float(labels[i]);
to_arma(images[i], examples[i]);
}
NeuralNetwork::NeuralNetwork nn(inputs, 10, outputs);
nn.setActivationFunction(activationF);
nn.setActivationFunctionDerivative(activationFD);
for (int i = 0; i < images.size(); i++)
{
std::cout << std::to_string(labels[i]) << std::endl;
// cv::imshow("Window - float", images[i]);
nn.train(*examples[i], 0.1);
// cv::waitKey(1);
}
std::cout << nn.classify(examples[0]->input).at(0, 0) << std::endl;
return 0;
}
|
// Created on: 1993-01-11
// Created by: CKY / Contract Toubro-Larsen ( Niraj RANGWALA )
// Copyright (c) 1993-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 _IGESGraph_LineFontDefPattern_HeaderFile
#define _IGESGraph_LineFontDefPattern_HeaderFile
#include <Standard.hxx>
#include <TColStd_HArray1OfReal.hxx>
#include <IGESData_LineFontEntity.hxx>
#include <Standard_Integer.hxx>
#include <Standard_Real.hxx>
class TCollection_HAsciiString;
class IGESGraph_LineFontDefPattern;
DEFINE_STANDARD_HANDLE(IGESGraph_LineFontDefPattern, IGESData_LineFontEntity)
//! defines IGESLineFontDefPattern, Type <304> Form <2>
//! in package IGESGraph
//!
//! Line Font may be defined by repetition of a basic pattern
//! of visible-blank(or, on-off) segments superimposed on
//! a line or a curve. The line or curve is then displayed
//! according to the basic pattern.
class IGESGraph_LineFontDefPattern : public IGESData_LineFontEntity
{
public:
Standard_EXPORT IGESGraph_LineFontDefPattern();
//! This method is used to set the fields of the class
//! LineFontDefPattern
//! - allSegLength : Containing lengths of respective segments
//! - aPattern : HAsciiString indicating visible-blank segments
Standard_EXPORT void Init (const Handle(TColStd_HArray1OfReal)& allSegLength, const Handle(TCollection_HAsciiString)& aPattern);
//! returns the number of segments in the visible-blank pattern
Standard_EXPORT Standard_Integer NbSegments() const;
//! returns the Length of Index'th segment of the basic pattern
//! raises exception if Index <= 0 or Index > NbSegments
Standard_EXPORT Standard_Real Length (const Standard_Integer Index) const;
//! returns the string indicating which segments of the basic
//! pattern are visible and which are blanked.
//! e.g:
//! theNbSegments = 5 and if Bit Pattern = 10110, which means that
//! segments 2, 3 and 5 are visible, whereas segments 1 and 4 are
//! blank. The method returns "2H16" as the HAsciiString.
//! Note: The bits are right justified. (16h = 10110)
Standard_EXPORT Handle(TCollection_HAsciiString) DisplayPattern() const;
//! The Display Pattern is decrypted to
//! return True if the Index'th basic pattern is Visible,
//! False otherwise.
//! If Index > NbSegments or Index <= 0 then return value is
//! False.
Standard_EXPORT Standard_Boolean IsVisible (const Standard_Integer Index) const;
DEFINE_STANDARD_RTTIEXT(IGESGraph_LineFontDefPattern,IGESData_LineFontEntity)
protected:
private:
Handle(TColStd_HArray1OfReal) theSegmentLengths;
Handle(TCollection_HAsciiString) theDisplayPattern;
};
#endif // _IGESGraph_LineFontDefPattern_HeaderFile
|
#include <stdio.h>
#include <string.h>
#include "NvRenderDebug.h"
#include "NvPhysXFramework.h"
#include "PhysicsDOMDef.h"
#define USE_DEBUG 0
#define TEST_IMPORT_XML 0
#define TEST_PHYSICS_DOM 0
#define TEST_SOME_OF_EVERYTHING 0
#define BOX_SIZE 1
class SimpleHelloWorld : public NV_PHYSX_FRAMEWORK::PhysXFramework::CommandCallback
{
public:
SimpleHelloWorld(void)
{
const char *dllName = nullptr;
#if _M_X64
#if USE_DEBUG
dllName = "PhysXFramework64DEBUG.dll";
#else
dllName = "PhysXFramework64.dll";
#endif
#else
#if USE_DEBUG
dllName = "PhysXFramework32DEBUG.dll";
#else
dllName = "PhysXFramework32.dll";
#endif
#endif
mPhysXFramework = NV_PHYSX_FRAMEWORK::createPhysXFramework(PHYSX_FRAMEWORK_VERSION_NUMBER, dllName);
if (mPhysXFramework)
{
mPhysXFramework->setCommandCallback(this);
#if TEST_SOME_OF_EVERYTHING
mPhysXFramework->createSomeOfEverything();
#elif TEST_PHYSICS_DOM
testPhysicsDOM();
#elif TEST_IMPORT_XML
testImportXML();
#else
mPhysXFramework->createDefaultStacks();
#endif
}
}
virtual ~SimpleHelloWorld(void)
{
if (mPhysXFramework)
{
mPhysXFramework->release();
}
}
bool process(void)
{
if (mPhysXFramework)
{
static uint32_t gCount = 0;
gCount++;
if (gCount == 16 )
{
mPhysXFramework->serializeXML("SimpleHelloWorld.xml");
}
mPhysXFramework->simulate(true);
}
return !mExit;
}
virtual bool processDebugCommand(uint32_t argc, const char **argv)
{
bool ret = false;
if (argc)
{
const char *cmd = argv[0];
if (strcmp(cmd, "client_stop") == 0)
{
mExit = true;
ret = true;
}
}
return ret;
}
void testPhysicsDOM(void)
{
PHYSICS_DOM::PhysicsDOMDef dom;
PHYSICS_DOM::CollectionDef *c = new PHYSICS_DOM::CollectionDef;
c->mId = "0";
PHYSICS_DOM::PhysicsMaterialDef *pm = new PHYSICS_DOM::PhysicsMaterialDef;
pm->mId = "1";
c->mNodes.push_back(pm);
PHYSICS_DOM::BoxGeometryDef *box = new PHYSICS_DOM::BoxGeometryDef;
PHYSICS_DOM::GeometryInstanceDef *box_instance = new PHYSICS_DOM::GeometryInstanceDef;
box_instance->mGeometry = box;
box_instance->mMaterials.push_back("1");
PHYSICS_DOM::RigidDynamicDef *rd = new PHYSICS_DOM::RigidDynamicDef;
rd->mId = "2";
rd->mGeometryInstances.push_back(box_instance);
c->mNodes.push_back(rd);
PHYSICS_DOM::SceneDef *s = new PHYSICS_DOM::SceneDef;
dom.mCollections.push_back(c);
dom.mScenes.push_back(s);
PHYSICS_DOM::InstanceCollectionDef *ic = new PHYSICS_DOM::InstanceCollectionDef;
ic->mId = "3"; // Node '3'
ic->mCollection = "0"; // Instance node '0'
s->mNodes.push_back(ic);
dom.initDOM();
PHYSICS_DOM::PhysicsDOM *pdom = dom.getPhysicsDOM();
//
if (pdom->scenesCount)
{
PHYSICS_DOM::Scene *ss = pdom->scenes[0];
if (ss->nodesCount)
{
PHYSICS_DOM::Node *n = ss->nodes[0];
if (n->type == PHYSICS_DOM::NT_INSTANCE_COLLECTION)
{
PHYSICS_DOM::InstanceCollection *icd = static_cast<PHYSICS_DOM::InstanceCollection *>(n);
if (icd)
{
printf("%s", icd->collection);
}
}
}
}
//
mPhysXFramework->loadPhysicsDOM(*pdom);
}
void testImportXML(void)
{
NV_PHYSX_FRAMEWORK::PhysicsDOMContainer *pcontain = mPhysXFramework->importPhysXDOM("ConvexDecomposition1.xml");
if (pcontain)
{
mPhysXFramework->loadPhysicsDOM(*pcontain->getPhysicsDOM());
mPhysXFramework->serializeXML("f:\\github\\physxframework\\dom.xml");
pcontain->release();
}
}
bool mExit{ false };
NV_PHYSX_FRAMEWORK::PhysXFramework *mPhysXFramework{ nullptr };
};
int main(int _argc,const char **_argv)
{
(_argv);
(_argc);
SimpleHelloWorld shw;
while (shw.process());
return 0;
}
|
#include"conio.h"
#include"stdio.h"
void main(void){
int A[5];
clrscr();
for(int i=0; i<=4; i++){
printf("Enter values: ");
scanf("%d",&A[i]);
}
printf("\n\n");
/* for(int j=0; j<=4; j++)
printf("%d\n",A[j]);
*/
for(int k=0; k<=4; k++){
if(A[k]==0)
printf("Zero\n");
else
if(A[k]%2==0)
printf("%d is Even\n",A[k]);
else
printf("%d is Odd\n",A[k]);
}
getch();
}
|
#include "dtw.h"
#include "DTWRecognizer.h"
#include "GestureFile.h"
#include <functional>
#include "OgreVector3.h"
#include "Debug.h"
using namespace std;
float ogreVectorLength(Ogre::Vector3 v)
{
return v.squaredLength();
}
void DTWRecognizer::registerRecognition(Recognition *recog)
{
mRecognitionArray.push_back(recog);
}
void DTWRecognizer::deleteRecognition(std::string& recogName)
{
// linear search
std::vector<Recognition *>::iterator itr;
for (itr = mRecognitionArray.begin(); itr != mRecognitionArray.end(); itr++)
{
if ((*itr)->getName() == recogName)
{
mRecognitionArray.erase(itr);
break;
}
}
}
std::string& DTWRecognizer::decideGesture(std::vector<Ogre::Vector3>& inputPattern)
{
float minDistance = numeric_limits<float>::max();
Recognition *minRecog = NULL;
int minNumSamples;
static std::string noDetect("NO_DETECT");
std::vector<Recognition *>::iterator itr1 = mRecognitionArray.begin();
for ( ; itr1 != mRecognitionArray.end(); itr1++)
{
Recognition *dataRecog = *itr1;
std::vector<Gesture *>::iterator itr2 = dataRecog->getGestureArray().begin();
for ( ; itr2 != dataRecog->getGestureArray().end(); itr2++)
{
Gesture *dataGesture = *itr2;
SimpleDTW<Ogre::Vector3> dtw(inputPattern, dataGesture->getLocalAccelerationArray(), ptr_fun(ogreVectorLength));
float result = dtw.calculateDistance();
PRINTF("(%10s(%2d)<-->Input(%2d) : %f",
dataRecog->getName().c_str(), dataGesture->getLocalAccelerationArray().size(),
inputPattern.size(), result);
if (result < minDistance)
{
minDistance = result;
minRecog = dataRecog;
minNumSamples = dataGesture->getLocalAccelerationArray().size();
}
}
}
//PRINTF("DECISION: %10s(%2d, %2d)(distance:%5.1f)", minRecog->getName().c_str(), minNumSamples, inputPattern.size(), minDistance);
//printf("DECISION: %10s(%2d, %2d)(distance:%5.1f)\n", minRecog->getName().c_str(), minNumSamples, inputPattern.size(), minDistance);
return minRecog->getName();
//return (minDistance < 256.0f ? minRecog->getName() : noDetect);
}
std::string& DTWRecognizer::decideGesture(std::vector<Recognition *>& recognitionArray, std::vector<Ogre::Vector3>& inputPattern)
{
float minDistance = numeric_limits<float>::max();
Recognition *minRecog = NULL;
int minNumSamples;
static std::string noDetect("NO_DETECT");
std::vector<Recognition *>::iterator itr1 = recognitionArray.begin();
for ( ; itr1 != recognitionArray.end(); itr1++)
{
Recognition *dataRecog = *itr1;
std::vector<Gesture *>::iterator itr2 = dataRecog->getGestureArray().begin();
for ( ; itr2 != dataRecog->getGestureArray().end(); itr2++)
{
Gesture *dataGesture = *itr2;
SimpleDTW<Ogre::Vector3> dtw(inputPattern, dataGesture->getLocalAccelerationArray(), ptr_fun(ogreVectorLength));
float result = dtw.calculateDistance();
PRINTF("(%10s(%2d)<-->Input(%2d) : %f",
dataRecog->getName().c_str(), dataGesture->getLocalAccelerationArray().size(),
inputPattern.size(), result);
if (result < minDistance)
{
minDistance = result;
minRecog = dataRecog;
minNumSamples = dataGesture->getLocalAccelerationArray().size();
}
}
}
PRINTF("DECISION: %10s(%2d, %2d)(distance:%5.1f)", minRecog->getName().c_str(), minNumSamples, inputPattern.size(), minDistance);
return minRecog->getName();
return (minDistance < 256.0f ? minRecog->getName() : noDetect);
}
|
#include "GamePCH.h"
#include "GSelectStageScene.h"
#include "GSelectStageBGLayer.h"
#include "GSelectStageUILayer.h"
#include "GnIListPageCtrl.h"
#include "GMainGameEnvironment.h"
GSelectStageScene::GSelectStageScene() : mInputEvent( this, &GSelectStageScene::InputEvent )
{
}
GSelectStageScene::~GSelectStageScene()
{
}
GSelectStageScene* GSelectStageScene::CreateScene(guint32 uiLastStage)
{
GSelectStageScene* scene = new GSelectStageScene();
if( scene->CreateInterface( uiLastStage ) == false || scene->CreateBackground() == false )
{
delete scene;
return NULL;
}
return scene;
}
bool GSelectStageScene::CreateInterface(guint32 uiLastStage)
{
GSelectStageUILayer* interfaceLayer = new GSelectStageUILayer();
mpListPageCtrl = (GnIListPageCtrl*)interfaceLayer->CreateInterface(
GInterfaceLayer::UI_SELECTSTAGE_LIST, &mInputEvent );
mpListButtonGroup = interfaceLayer->CreateInterface( GInterfaceLayer::UI_SELECTSTAGE_BT, &mInputEvent );
interfaceLayer->CreateListCtrlItem( uiLastStage );
if( mpListPageCtrl == NULL || mpListButtonGroup == NULL )
{
delete interfaceLayer;
return false;
}
mpInterfaceLayer = interfaceLayer;
addChild( interfaceLayer, INTERFACE_ZORDER );
interfaceLayer->release();
return true;
}
bool GSelectStageScene::CreateBackground()
{
GSelectStageBGLayer* backLayer = GSelectStageBGLayer::CreateBackground();
if( backLayer == NULL )
{
return false;
}
mpBackgroundLayer = backLayer;
addChild( backLayer );
backLayer->release();
return true;
}
void GSelectStageScene::Update(float fTime)
{
mpInterfaceLayer->Update( fTime );
}
const gchar* GSelectStageScene::GetSceneName()
{
return SCENENAME_SELECTSTAGE;
}
void GSelectStageScene::InputEvent(GnInterface* pInterface, GnIInputEvent* pEvent)
{
if( pEvent->GetEventType() == GnIInputEvent::PUSHUP )
{
if( mpListButtonGroup->GetChild( GInterfaceLayer::BT_NEXT ) == pInterface )
{
mpListPageCtrl->SetNextPage();
}
else if( mpListButtonGroup->GetChild( GInterfaceLayer::BT_PREVIOUS ) == pInterface )
{
mpListPageCtrl->SetPreviousPage();
}
else if( mpListButtonGroup->GetChild( GInterfaceLayer::BT_SELECTSTAGE_BACK ) == pInterface )
{
GScene::SetChangeSceneName( GScene::SCENENAME_STATE );
}
else
{
GnIListCtrlItem* listItme = GnDynamicCast( GnIListCtrlItem, pInterface );
if( listItme )
{
gtuint pageItemSize = mpListPageCtrl->GetColumnSize() * mpListPageCtrl->GetRowSize();
gtuint rowSize = mpListPageCtrl->GetRowSize();
gtuint colSize = mpListPageCtrl->GetColumnSize();
gtuint numStage = ( mpListPageCtrl->GetCurrentPage() * pageItemSize )
+ ( ( listItme->GetNumRow() * colSize ) + listItme->GetNumColumn() );
SelectStage( numStage );
}
}
}
}
void GSelectStageScene::SelectStage(gtuint uiNumStage)
{
// if( uiNumStage )
// {
// CCDirector::sharedDirector()->end();
// return;
// }
GMainGameEnvironment::Create();
if( GetGameEnvironment()->SetStage( uiNumStage ) == false )
return;
GScene:SetChangeSceneName( SCENENAME_GAME );
}
|
#include "ConstantLengthPatternsOnTextHashMatcher.h"
DefaultConstantLengthPatternsOnTextHashMatcher::DefaultConstantLengthPatternsOnTextHashMatcher(uint32_t patternLength)
: patternLength(patternLength), hf(patternLength, 32) {
}
DefaultConstantLengthPatternsOnTextHashMatcher::~DefaultConstantLengthPatternsOnTextHashMatcher() {
}
void DefaultConstantLengthPatternsOnTextHashMatcher::addPattern(const char *pattern, uint32_t idx) {
if (this->txt != 0) {
cerr << "Adding patterns not permitted during iteration";
exit(EXIT_FAILURE);
}
hf.reset();
for(uint32_t i = 0; i < patternLength; i++)
hf.eat(pattern[i]);
hashToIndexMap.insert(std::pair<uint32_t, uint32_t>(hf.hashvalue, idx));
}
void DefaultConstantLengthPatternsOnTextHashMatcher::addReadsSetOfPatterns(ConstantLengthReadsSetInterface *readsSet,
uint8_t partsCount,
vector<bool> matchedReadsBitmap) {
if (this->txt != 0) {
cerr << "Adding patterns not permitted during iteration";
exit(EXIT_FAILURE);
}
const uint_reads_cnt_max readsCount = readsSet->getReadsSetProperties()->readsCount;
for (uint_reads_cnt_max i = 0; i < readsCount; i++) {
if (!matchedReadsBitmap.empty() && matchedReadsBitmap[i])
continue;
uint_read_len_max offset = 0;
for (uint8_t j = 0; j < partsCount; j++, offset += patternLength) {
hf.reset();
for(uint32_t k = 0; k < patternLength; k++)
hf.eat(readsSet->getReadSymbol(i, offset + k));
hashToIndexMap.insert(std::pair<uint32_t, uint32_t>(hf.hashvalue, i * partsCount + j));
}
}
}
uint32_t DefaultConstantLengthPatternsOnTextHashMatcher::getHashMatchPatternIndex() {
return indexIter->second;
}
uint64_t DefaultConstantLengthPatternsOnTextHashMatcher::getHashMatchTextPosition() {
return this->txtPos;
}
InterleavedConstantLengthPatternsOnTextHashMatcher::InterleavedConstantLengthPatternsOnTextHashMatcher(
uint32_t patternLength, const uint8_t patternParts)
: patternLength(patternLength), patternParts(patternParts), patternSpan(patternLength*patternParts) {
hf.push_back(CyclicHash<uint32_t>(patternLength, 32));
for(uint8_t i = 1; i < patternParts; i++)
hf.push_back(hf[0]);
}
InterleavedConstantLengthPatternsOnTextHashMatcher::~InterleavedConstantLengthPatternsOnTextHashMatcher() {
}
void InterleavedConstantLengthPatternsOnTextHashMatcher::addPattern(const char *pattern, uint32_t idx) {
if (this->txt != 0) {
cerr << "Adding patterns not permitted during iteration";
exit(EXIT_FAILURE);
}
hf[0].reset();
for(uint32_t i = 0; i < patternSpan; i += patternParts)
hf[0].eat(pattern[i]);
hashToIndexMap.insert(std::pair<uint32_t, uint32_t>(hf[0].hashvalue, idx));
}
void InterleavedConstantLengthPatternsOnTextHashMatcher::addPackedPatterns(ConstantLengthReadsSetInterface *readsSet,
int partsCount, vector<bool> matchedReadsBitmap) {
if (this->txt != 0) {
cerr << "Adding patterns not permitted during iteration";
exit(EXIT_FAILURE);
}
const uint_reads_cnt_max readsCount = readsSet->getReadsSetProperties()->readsCount;
for (uint_reads_cnt_max i = 0; i < readsCount; i++) {
for (uint8_t j = 0; j < partsCount; j++) {
if (!matchedReadsBitmap.empty() && matchedReadsBitmap[i])
continue;
hf[0].reset();
for(uint32_t k = 0; k < patternSpan; k += patternParts)
hf[0].eat(readsSet->getReadSymbol(i, j + k));
hashToIndexMap.insert(std::pair<uint32_t, uint32_t>(hf[0].hashvalue, i * partsCount + j));
}
}
}
uint32_t InterleavedConstantLengthPatternsOnTextHashMatcher::getHashMatchPatternIndex() {
return indexIter->second;
}
uint64_t InterleavedConstantLengthPatternsOnTextHashMatcher::getHashMatchTextPosition() {
return this->txtPos;
}
|
#include <iostream>
#include <iomanip>
using namespace std;
int n, m, c, i, j;
const unsigned int nmax = 10;
const unsigned int mmax = 10;
int a[nmax][mmax];
int at[nmax][mmax];
int main() {
cout<<"Input matrix n and m (<10)\n";
cin >> n;
cin >> m;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
a[i][j] = (i + 1) * 10 + (j + 1);
cout<<a[i][j]<<"\t";
}
cout <<" \n";
}
cout <<" \n";
cout <<" \n";
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
at[i][j] = a[j][i];
cout<<at[i][j]<<"\t";
}
cout <<" \n";
}
}
|
/*
* Copyright [2017] <Bonn-Rhein-Sieg University>
*
* Author: Torsten Jandt
*
*/
#pragma once
#include <mir_planner_executor/actions/unstage/base_unstage_action.h>
#include <actionlib/client/simple_action_client.h>
#include <mir_yb_action_msgs/UnStageObjectAction.h>
class UnstageAction : public BaseUnstageAction {
private:
actionlib::SimpleActionClient<mir_yb_action_msgs::UnStageObjectAction> client_;
public:
UnstageAction();
protected:
virtual bool run(std::string& robot, std::string& platform, std::string& object);
};
|
/****************************************************************************
** Meta object code from reading C++ file 'coupleediteur.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.8.0)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../PluriNote/coupleediteur.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'coupleediteur.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.8.0. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_CoupleEditeur_t {
QByteArrayData data[6];
char stringdata0[78];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_CoupleEditeur_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_CoupleEditeur_t qt_meta_stringdata_CoupleEditeur = {
{
QT_MOC_LITERAL(0, 0, 13), // "CoupleEditeur"
QT_MOC_LITERAL(1, 14, 17), // "saveModifications"
QT_MOC_LITERAL(2, 32, 0), // ""
QT_MOC_LITERAL(3, 33, 14), // "afficherBouton"
QT_MOC_LITERAL(4, 48, 14), // "afficherLabel1"
QT_MOC_LITERAL(5, 63, 14) // "afficherLabel2"
},
"CoupleEditeur\0saveModifications\0\0"
"afficherBouton\0afficherLabel1\0"
"afficherLabel2"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_CoupleEditeur[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
4, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 34, 2, 0x0a /* Public */,
3, 0, 35, 2, 0x08 /* Private */,
4, 0, 36, 2, 0x08 /* Private */,
5, 0, 37, 2, 0x08 /* Private */,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void CoupleEditeur::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
CoupleEditeur *_t = static_cast<CoupleEditeur *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->saveModifications(); break;
case 1: _t->afficherBouton(); break;
case 2: _t->afficherLabel1(); break;
case 3: _t->afficherLabel2(); break;
default: ;
}
}
Q_UNUSED(_a);
}
const QMetaObject CoupleEditeur::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_CoupleEditeur.data,
qt_meta_data_CoupleEditeur, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *CoupleEditeur::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *CoupleEditeur::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_CoupleEditeur.stringdata0))
return static_cast<void*>(const_cast< CoupleEditeur*>(this));
return QWidget::qt_metacast(_clname);
}
int CoupleEditeur::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 4)
qt_static_metacall(this, _c, _id, _a);
_id -= 4;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 4)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 4;
}
return _id;
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
|
#include "egl.h"
int video_call_egl_eglSwapInterval(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglSwapInterval\n");
fflush(stdout);
ABORT("Aborted function called: eglSwapInterval");
HOST_WRITE_QUEUE();
}
int video_call_egl_eglReleaseTexImage(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglReleaseTexImage\n");
fflush(stdout);
HOST_READ_QUEUE(1024);
egl_thread_state_host_t thread_state;
QUEUE_POP(&thread_state, sizeof (egl_thread_state_host_t));
egl_set_thread_state(&thread_state);
EGLDisplay dpy;
QUEUE_POP(&dpy, sizeof (EGLDisplay));
EGLSurface surface;
QUEUE_POP(&surface, sizeof (EGLSurface));
EGLint buffer;
QUEUE_POP(&buffer, sizeof (EGLint));
EGLBoolean ret_value = eglReleaseTexImage(dpy, surface, buffer);
HOST_START_PUSH();
EGLint egl_error = eglGetError();
QUEUE_PUSH(&egl_error, sizeof (EGLint));
QUEUE_PUSH(&ret_value, sizeof (EGLBoolean));
HOST_WRITE_QUEUE();
}
int video_call_egl_eglSurfaceAttrib(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglSurfaceAttrib\n");
fflush(stdout);
HOST_READ_QUEUE(1024);
egl_thread_state_host_t thread_state;
QUEUE_POP(&thread_state, sizeof (egl_thread_state_host_t));
egl_set_thread_state(&thread_state);
EGLDisplay dpy;
QUEUE_POP(&dpy, sizeof (EGLDisplay));
EGLSurface surface;
QUEUE_POP(&surface, sizeof (EGLSurface));
EGLint attribute;
QUEUE_POP(&attribute, sizeof (EGLint));
EGLint value;
QUEUE_POP(&value, sizeof (EGLint));
EGLBoolean ret_value = eglSurfaceAttrib(dpy, surface, attribute, value);
HOST_START_PUSH();
EGLint egl_error = eglGetError();
QUEUE_PUSH(&egl_error, sizeof (EGLint));
QUEUE_PUSH(&ret_value, sizeof (EGLBoolean));
HOST_WRITE_QUEUE();
}
int video_call_egl_eglGetSystemTimeFrequencyNV(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglGetSystemTimeFrequencyNV\n");
fflush(stdout);
ABORT("Aborted function called: eglGetSystemTimeFrequencyNV");
HOST_WRITE_QUEUE();
}
int video_call_egl_eglFenceNV(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglFenceNV\n");
fflush(stdout);
ABORT("Aborted function called: eglFenceNV");
HOST_WRITE_QUEUE();
}
int video_call_egl_eglChooseConfig(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglChooseConfig\n");
fflush(stdout);
HOST_READ_QUEUE(1024);
egl_thread_state_host_t thread_state;
QUEUE_POP(&thread_state, sizeof (egl_thread_state_host_t));
egl_set_thread_state(&thread_state);
EGLDisplay dpy;
QUEUE_POP(&dpy, sizeof (EGLDisplay));
uint8_t* pchBuf1 = (uint8_t *)paParms[k++].u.pointer.addr;
size_t attrib_list_out_size = paParms[k-1].u.pointer.size;
EGLint* attrib_list = (EGLint*)malloc(attrib_list_out_size);
memcpy(attrib_list, pchBuf1, attrib_list_out_size);
// addr_t attrib_list_;
// QUEUE_POP(&attrib_list_, sizeof (addr_t));
//
// size_t attrib_list_out_size = 0;
// assert(attrib_list_);
// QUEUE_POP(&attrib_list_out_size, sizeof (size_t));
// attrib_list = (EGLint*)malloc(attrib_list_out_size);
// assert(attrib_list);
// if ((size_t) read_linear(cpu, attrib_list_, attrib_list_out_size, attrib_list, 1) != attrib_list_out_size)
// HOST_WRITE_QUEUE(); //ABORT("read_linear in function \"eglChooseConfig\" failed");
//
uint8_t* pchBuf2 = (uint8_t *)paParms[k++].u.pointer.addr;
size_t configs_in_size = paParms[k-1].u.pointer.size;
GUEST_EGLConfig* configs = NULL;
if (configs_in_size != 0)
{
configs = (GUEST_EGLConfig*)malloc(configs_in_size);
memcpy(configs, pchBuf2, configs_in_size);
}
// addr_t configs_;
// QUEUE_POP(&configs_, sizeof (addr_t));
// GUEST_EGLConfig* configs = NULL;
// size_t configs_in_size = 0;
// if (configs_)
// {
// QUEUE_POP(&configs_in_size, sizeof (size_t));
// configs = (GUEST_EGLConfig*)malloc(configs_in_size);
// assert(configs);
// }
EGLint config_size;
QUEUE_POP(&config_size, sizeof (EGLint));
uint8_t* pchBuf3 = (uint8_t *)paParms[k++].u.pointer.addr;
size_t num_config_in_size = paParms[k-1].u.pointer.size;
EGLint* num_config = (EGLint*)malloc(num_config_in_size);
memcpy(num_config, pchBuf3, num_config_in_size);
// addr_t num_config_;
// QUEUE_POP(&num_config_, sizeof (addr_t));
// EGLint* num_config = NULL;
// size_t num_config_in_size = 0;
// assert(num_config_);
// QUEUE_POP(&num_config_in_size, sizeof (size_t));
// num_config = (EGLint*)malloc(num_config_in_size);
// assert(num_config);
EGLBoolean ret_value = video_egl_eglChooseConfig(dpy, attrib_list, (int32_t*)configs, config_size, num_config);
HOST_START_PUSH();
memcpy(pchBuf1, attrib_list, attrib_list_out_size); // не обязательно
free(attrib_list);
if (configs_in_size != 0)
{
memcpy(pchBuf2, configs, configs_in_size);
free(configs);
}
//if (configs_)
//{
//
// //if ((size_t) write_linear(cpu, configs_, configs_in_size, configs, 1) != configs_in_size)
// // HOST_WRITE_QUEUE(); //ABORT("write_linear in function \"eglChooseConfig\" failed");
// free(configs);
//}
memcpy(pchBuf3, num_config, num_config_in_size);
//if ((size_t) write_linear(cpu, num_config_, num_config_in_size, num_config, 1) != num_config_in_size)
// HOST_WRITE_QUEUE(); //ABORT("write_linear in function \"eglChooseConfig\" failed");
free(num_config);
EGLint egl_error = egl_get_error();
QUEUE_PUSH(&egl_error, sizeof (EGLint));
QUEUE_PUSH(&ret_value, sizeof (EGLBoolean));
HOST_WRITE_QUEUE();
}
int video_call_egl_eglMakeCurrent(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglMakeCurrent\n");
fflush(stdout);
HOST_READ_QUEUE(1024);
egl_thread_state_host_t thread_state;
QUEUE_POP(&thread_state, sizeof (egl_thread_state_host_t));
egl_set_thread_state(&thread_state);
EGLDisplay dpy;
QUEUE_POP(&dpy, sizeof (EGLDisplay));
EGLSurface draw;
QUEUE_POP(&draw, sizeof (EGLSurface));
EGLSurface read;
QUEUE_POP(&read, sizeof (EGLSurface));
EGLContext ctx;
QUEUE_POP(&ctx, sizeof (EGLContext));
EGLBoolean ret_value = eglMakeCurrent(dpy, draw, read, ctx);
HOST_START_PUSH();
EGLint egl_error = eglGetError();
QUEUE_PUSH(&egl_error, sizeof (EGLint));
QUEUE_PUSH(&ret_value, sizeof (EGLBoolean));
HOST_WRITE_QUEUE();
}
int video_call_egl_eglDestroySyncKHR(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglDestroySyncKHR\n");
fflush(stdout);
ABORT("Aborted function called: eglDestroySyncKHR");
HOST_WRITE_QUEUE();
}
int video_call_egl_egl_get_configs(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: egl_get_configs\n");
fflush(stdout);
HOST_READ_QUEUE(1024);
uint8_t* pchBuf1 = (uint8_t *)paParms[k++].u.pointer.addr;
size_t configs_in_size = paParms[k-1].u.pointer.size;
GUEST_EGLConfig* configs = (GUEST_EGLConfig*)malloc(configs_in_size);
memcpy(configs, pchBuf1, configs_in_size);
// addr_t configs_;
// QUEUE_POP(&configs_, sizeof (addr_t));
// void* configs = NULL;
// size_t configs_in_size = 0;
// assert(configs_);
// QUEUE_POP(&configs_in_size, sizeof (size_t));
// configs = malloc(configs_in_size);
// assert(configs);
EGLint configs_num;
QUEUE_POP(&configs_num, sizeof (EGLint));
video_egl_egl_get_configs(configs, configs_num);
HOST_START_PUSH();
memcpy(pchBuf1, configs, configs_in_size);
//if ((size_t) write_linear(cpu, configs_, configs_in_size, configs, 1) != configs_in_size)
// HOST_WRITE_QUEUE(); //ABORT("write_linear in function \"egl_get_configs\" failed");
free(configs);
HOST_WRITE_QUEUE();
}
int video_call_egl_eglCopyBuffers(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglCopyBuffers\n");
fflush(stdout);
ABORT("Aborted function called: eglCopyBuffers");
HOST_WRITE_QUEUE();
}
int video_call_egl_egl_guest_buffer(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: egl_guest_buffer\n");
fflush(stdout);
HOST_READ_QUEUE(1024);
egl_thread_state_host_t thread_state;
QUEUE_POP(&thread_state, sizeof (egl_thread_state_host_t));
egl_set_thread_state(&thread_state);
EGLDisplay dpy;
QUEUE_POP(&dpy, sizeof (EGLDisplay));
EGLSurface surface;
QUEUE_POP(&surface, sizeof (EGLSurface));
uint8_t* pchBuf1 = (uint8_t *)paParms[k++].u.pointer.addr;
size_t buffer_in_size = paParms[k-1].u.pointer.size;
void* buffer = malloc(buffer_in_size);
memcpy(buffer, pchBuf1, buffer_in_size);
// addr_t buffer_;
// QUEUE_POP(&buffer_, sizeof (addr_t));
// void* buffer = NULL;
// size_t buffer_in_size = 0;
// assert(buffer_);
// QUEUE_POP(&buffer_in_size, sizeof (size_t));
// buffer = malloc(buffer_in_size);
// assert(buffer);
EGLint width;
QUEUE_POP(&width, sizeof (EGLint));
EGLint height;
QUEUE_POP(&height, sizeof (EGLint));
EGLint stride;
QUEUE_POP(&stride, sizeof (EGLint));
EGLint format;
QUEUE_POP(&format, sizeof (EGLint));
egl_guest_buffer(dpy, surface, buffer, width, height, stride, format);
HOST_START_PUSH();
memcpy(pchBuf1, buffer, buffer_in_size);
//if ((size_t) write_linear(cpu, buffer_, buffer_in_size, buffer, 1) != buffer_in_size)
// HOST_WRITE_QUEUE(); //ABORT("write_linear in function \"egl_guest_buffer\" failed");
free(buffer);
EGLint egl_error = eglGetError();
QUEUE_PUSH(&egl_error, sizeof (EGLint));
HOST_WRITE_QUEUE();
}
int video_call_egl_eglCreateContext(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglCreateContext\n");
fflush(stdout);
HOST_READ_QUEUE(1024);
egl_thread_state_host_t thread_state;
QUEUE_POP(&thread_state, sizeof (egl_thread_state_host_t));
egl_set_thread_state(&thread_state);
EGLDisplay dpy;
QUEUE_POP(&dpy, sizeof (EGLDisplay));
EGLConfig config;
QUEUE_POP(&config, sizeof (EGLConfig));
EGLContext share_context;
QUEUE_POP(&share_context, sizeof (EGLContext));
uint8_t* pchBuf1 = (uint8_t *)paParms[k++].u.pointer.addr;
size_t attrib_list_out_size = paParms[k-1].u.pointer.size;
EGLint* attrib_list = (EGLint*)malloc(attrib_list_out_size);
memcpy(attrib_list, pchBuf1, attrib_list_out_size);
EGLContext ret_value = eglCreateContext(dpy, config, share_context, attrib_list);
memcpy(pchBuf1, attrib_list, attrib_list_out_size); // не обязательно
HOST_START_PUSH();
free(attrib_list);
EGLint egl_error = eglGetError();
QUEUE_PUSH(&egl_error, sizeof (EGLint));
QUEUE_PUSH(&ret_value, sizeof (EGLContext));
HOST_WRITE_QUEUE();
}
int video_call_egl_eglDestroyContext(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglDestroyContext\n");
fflush(stdout);
HOST_READ_QUEUE(1024);
egl_thread_state_host_t thread_state;
QUEUE_POP(&thread_state, sizeof (egl_thread_state_host_t));
egl_set_thread_state(&thread_state);
EGLDisplay dpy;
QUEUE_POP(&dpy, sizeof (EGLDisplay));
EGLContext ctx;
QUEUE_POP(&ctx, sizeof (EGLContext));
EGLBoolean ret_value = eglDestroyContext(dpy, ctx);
HOST_START_PUSH();
EGLint egl_error = eglGetError();
QUEUE_PUSH(&egl_error, sizeof (EGLint));
QUEUE_PUSH(&ret_value, sizeof (EGLBoolean));
HOST_WRITE_QUEUE();
}
int video_call_egl_eglCreatePbufferSurface(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglCreatePbufferSurface\n");
fflush(stdout);
HOST_READ_QUEUE(1024);
egl_thread_state_host_t thread_state;
QUEUE_POP(&thread_state, sizeof (egl_thread_state_host_t));
egl_set_thread_state(&thread_state);
EGLDisplay dpy;
QUEUE_POP(&dpy, sizeof (EGLDisplay));
EGLConfig config;
QUEUE_POP(&config, sizeof (EGLConfig));
uint8_t* pchBuf1 = (uint8_t *)paParms[k++].u.pointer.addr;
size_t attrib_list_out_size = paParms[k-1].u.pointer.size;
EGLint* attrib_list = (EGLint*)malloc(attrib_list_out_size);
memcpy(attrib_list, pchBuf1, attrib_list_out_size);
//addr_t attrib_list_;
//QUEUE_POP(&attrib_list_, sizeof (addr_t));
//EGLint* attrib_list = NULL;
//size_t attrib_list_out_size = 0;
//assert(attrib_list_);
//QUEUE_POP(&attrib_list_out_size, sizeof (size_t));
//attrib_list = (EGLint*)malloc(attrib_list_out_size);
//assert(attrib_list);
//if ((size_t) read_linear(cpu, attrib_list_, attrib_list_out_size, attrib_list, 1) != attrib_list_out_size)
// HOST_WRITE_QUEUE(); //ABORT("read_linear in function \"eglCreatePbufferSurface\" failed");
EGLSurface ret_value = eglCreatePbufferSurface(dpy, config, attrib_list);
HOST_START_PUSH();
memcpy(pchBuf1, attrib_list, attrib_list_out_size); // не обязательноs
free(attrib_list);
EGLint egl_error = eglGetError();
QUEUE_PUSH(&egl_error, sizeof (EGLint));
QUEUE_PUSH(&ret_value, sizeof (EGLSurface));
HOST_WRITE_QUEUE();
}
int video_call_egl_eglDestroySyncNV(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglDestroySyncNV\n");
fflush(stdout);
ABORT("Aborted function called: eglDestroySyncNV");
HOST_WRITE_QUEUE();
}
int video_call_egl_eglCreatePbufferFromClientBuffer(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglCreatePbufferFromClientBuffer\n");
fflush(stdout);
ABORT("Aborted function called: eglCreatePbufferFromClientBuffer");
HOST_WRITE_QUEUE();
}
int video_call_egl_eglGetSyncAttribKHR(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglGetSyncAttribKHR\n");
fflush(stdout);
ABORT("Aborted function called: eglGetSyncAttribKHR");
HOST_WRITE_QUEUE();
}
int video_call_egl_eglQuerySurface(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglQuerySurface\n");
fflush(stdout);
HOST_READ_QUEUE(1024);
egl_thread_state_host_t thread_state;
QUEUE_POP(&thread_state, sizeof (egl_thread_state_host_t));
egl_set_thread_state(&thread_state);
EGLDisplay dpy;
QUEUE_POP(&dpy, sizeof (EGLDisplay));
EGLSurface surface;
QUEUE_POP(&surface, sizeof (EGLSurface));
EGLint attribute;
QUEUE_POP(&attribute, sizeof (EGLint));
uint8_t* pchBuf1 = (uint8_t *)paParms[k++].u.pointer.addr;
size_t value_in_size = paParms[k-1].u.pointer.size;
EGLint* value = (EGLint*)malloc(value_in_size);
memcpy(value, pchBuf1, value_in_size);
//addr_t value_;
//QUEUE_POP(&value_, sizeof (addr_t));
//EGLint* value = NULL;
//size_t value_in_size = 0;
//assert(value_);
//QUEUE_POP(&value_in_size, sizeof (size_t));
//value = (EGLint*)malloc(value_in_size);
//assert(value);
EGLBoolean ret_value = eglQuerySurface(dpy, surface, attribute, value);
HOST_START_PUSH();
memcpy(pchBuf1, value, value_in_size);
//if ((size_t) write_linear(cpu, value_, value_in_size, value, 1) != value_in_size)
// HOST_WRITE_QUEUE(); //ABORT("write_linear in function \"eglQuerySurface\" failed");
free(value);
EGLint egl_error = eglGetError();
QUEUE_PUSH(&egl_error, sizeof (EGLint));
QUEUE_PUSH(&ret_value, sizeof (EGLBoolean));
HOST_WRITE_QUEUE();
}
int video_call_egl_eglDestroySurface(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglDestroySurface\n");
fflush(stdout);
HOST_READ_QUEUE(1024);
egl_thread_state_host_t thread_state;
QUEUE_POP(&thread_state, sizeof (egl_thread_state_host_t));
egl_set_thread_state(&thread_state);
EGLDisplay dpy;
QUEUE_POP(&dpy, sizeof (EGLDisplay));
EGLSurface surface;
QUEUE_POP(&surface, sizeof (EGLSurface));
EGLBoolean ret_value = eglDestroySurface(dpy, surface);
HOST_START_PUSH();
EGLint egl_error = eglGetError();
QUEUE_PUSH(&egl_error, sizeof (EGLint));
QUEUE_PUSH(&ret_value, sizeof (EGLBoolean));
HOST_WRITE_QUEUE();
}
int video_call_egl_eglGetSyncAttribNV(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglGetSyncAttribNV\n");
fflush(stdout);
ABORT("Aborted function called: eglGetSyncAttribNV");
HOST_WRITE_QUEUE();
}
int video_call_egl_eglClientWaitSyncNV(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglClientWaitSyncNV\n");
fflush(stdout);
ABORT("Aborted function called: eglClientWaitSyncNV");
HOST_WRITE_QUEUE();
}
int video_call_egl_eglBindTexImage(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglBindTexImage\n");
fflush(stdout);
HOST_READ_QUEUE(1024);
egl_thread_state_host_t thread_state;
QUEUE_POP(&thread_state, sizeof (egl_thread_state_host_t));
egl_set_thread_state(&thread_state);
EGLDisplay dpy;
QUEUE_POP(&dpy, sizeof (EGLDisplay));
EGLSurface surface;
QUEUE_POP(&surface, sizeof (EGLSurface));
EGLint buffer;
QUEUE_POP(&buffer, sizeof (EGLint));
EGLBoolean ret_value = eglBindTexImage(dpy, surface, buffer);
HOST_START_PUSH();
EGLint egl_error = eglGetError();
QUEUE_PUSH(&egl_error, sizeof (EGLint));
QUEUE_PUSH(&ret_value, sizeof (EGLBoolean));
HOST_WRITE_QUEUE();
}
int video_call_egl_eglSetSwapRectangleANDROID(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglSetSwapRectangleANDROID\n");
fflush(stdout);
ABORT("Aborted function called: eglSetSwapRectangleANDROID");
HOST_WRITE_QUEUE();
}
int video_call_egl_eglQueryContext(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglQueryContext\n");
fflush(stdout);
HOST_READ_QUEUE(1024);
egl_thread_state_host_t thread_state;
QUEUE_POP(&thread_state, sizeof (egl_thread_state_host_t));
egl_set_thread_state(&thread_state);
EGLDisplay dpy;
QUEUE_POP(&dpy, sizeof (EGLDisplay));
EGLContext ctx;
QUEUE_POP(&ctx, sizeof (EGLContext));
EGLint attribute;
QUEUE_POP(&attribute, sizeof (EGLint));
uint8_t* pchBuf1 = (uint8_t *)paParms[k++].u.pointer.addr;
size_t value_in_size = paParms[k-1].u.pointer.size;
EGLint* value = (EGLint*)malloc(value_in_size);
memcpy(value, pchBuf1, value_in_size);
//addr_t value_;
//QUEUE_POP(&value_, sizeof (addr_t));
//EGLint* value = NULL;
//size_t value_in_size = 0;
//assert(value_);
//QUEUE_POP(&value_in_size, sizeof (size_t));
//value = (EGLint*)malloc(value_in_size);
//assert(value);
EGLBoolean ret_value = eglQueryContext(dpy, ctx, attribute, value);
HOST_START_PUSH();
memcpy(pchBuf1, value, value_in_size);
//if ((size_t) write_linear(cpu, value_, value_in_size, value, 1) != value_in_size)
// HOST_WRITE_QUEUE(); //ABORT("write_linear in function \"eglQueryContext\" failed");
free(value);
EGLint egl_error = eglGetError();
QUEUE_PUSH(&egl_error, sizeof (EGLint));
QUEUE_PUSH(&ret_value, sizeof (EGLBoolean));
HOST_WRITE_QUEUE();
}
int video_call_egl_egl_get_host_display(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: egl_get_host_display\n");
fflush(stdout);
HOST_READ_QUEUE(1024);
EGLDisplay ret_value = egl_get_host_display();
HOST_START_PUSH();
QUEUE_PUSH(&ret_value, sizeof (EGLDisplay));
HOST_WRITE_QUEUE();
}
int video_call_egl_eglGetConfigs(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglGetConfigs\n");
fflush(stdout);
HOST_READ_QUEUE(1024);
egl_thread_state_host_t thread_state;
QUEUE_POP(&thread_state, sizeof (egl_thread_state_host_t));
egl_set_thread_state(&thread_state);
EGLDisplay dpy;
QUEUE_POP(&dpy, sizeof (EGLDisplay));
uint8_t* pchBuf1 = (uint8_t *)paParms[k++].u.pointer.addr;
size_t configs_in_size = paParms[k-1].u.pointer.size;
GUEST_EGLConfig* configs = NULL;
printf(" configs_in_size = %d\n", configs_in_size);
if (configs_in_size != sizeof(char))
{
configs = (GUEST_EGLConfig*)malloc(configs_in_size);
memcpy(configs, pchBuf1, configs_in_size);
}
else
{
configs = NULL;
}
//addr_t configs_;
//QUEUE_POP(&configs_, sizeof (addr_t));
//GUEST_EGLConfig* configs = NULL;
//size_t configs_in_size = 0;
//if (configs_)
//{
// QUEUE_POP(&configs_in_size, sizeof (size_t));
// configs = (GUEST_EGLConfig*)malloc(configs_in_size);
// assert(configs);
//}
EGLint config_size;
QUEUE_POP(&config_size, sizeof (EGLint));
uint8_t* pchBuf2 = (uint8_t *)paParms[k++].u.pointer.addr;
size_t num_config_in_size = paParms[k-1].u.pointer.size;
EGLint* num_config = (EGLint*)malloc(num_config_in_size);
memcpy(num_config, pchBuf2, num_config_in_size);
//addr_t num_config_;
//QUEUE_POP(&num_config_, sizeof (addr_t));
//EGLint* num_config = NULL;
//size_t num_config_in_size = 0;
//assert(num_config_);
//QUEUE_POP(&num_config_in_size, sizeof (size_t));
//num_config = (EGLint*)malloc(num_config_in_size);
//assert(num_config);
EGLBoolean ret_value = video_egl_eglGetConfigs(dpy, configs, config_size, num_config);
printf(" num_config = %d\n", *num_config);
HOST_START_PUSH();
if (configs_in_size != sizeof(char))
{
memcpy(pchBuf1, configs, configs_in_size);
free(configs);
}
//if (configs_)
//{
// //if ((size_t) write_linear(cpu, configs_, configs_in_size, configs, 1) != configs_in_size)
// // HOST_WRITE_QUEUE(); //ABORT("write_linear in function \"eglGetConfigs\" failed");
// free(configs);
//}
memcpy(pchBuf2, num_config, num_config_in_size);
free(num_config);
////if ((size_t) write_linear(cpu, num_config_, num_config_in_size, num_config, 1) != num_config_in_size)
//// HOST_WRITE_QUEUE(); //ABORT("write_linear in function \"eglGetConfigs\" failed");
//free(num_config);
EGLint egl_error = egl_get_error();
QUEUE_PUSH(&egl_error, sizeof (EGLint));
printf("video_call_egl_eglGetConfigs end\n");
QUEUE_PUSH(&ret_value, sizeof (EGLBoolean));
HOST_WRITE_QUEUE();
}
int video_call_egl_eglGetConfigAttrib(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglGetConfigAttrib\n");
fflush(stdout);
HOST_READ_QUEUE(1024);
egl_thread_state_host_t thread_state;
QUEUE_POP(&thread_state, sizeof (egl_thread_state_host_t));
egl_set_thread_state(&thread_state);
EGLDisplay dpy;
QUEUE_POP(&dpy, sizeof (EGLDisplay));
EGLConfig config;
QUEUE_POP(&config, sizeof (EGLConfig));
EGLint attribute;
QUEUE_POP(&attribute, sizeof (EGLint));
FILE* fd = fopen("D:\error2.txt", "a");
char number[20];
sprintf( number, "atribu = %d\n", attribute);
fwrite( number, strlen(number), 1, fd);
fflush(fd);
uint8_t* pchBuf1 = (uint8_t *)paParms[k++].u.pointer.addr;
size_t value_in_size = paParms[k-1].u.pointer.size;
EGLint* value = (EGLint*)malloc(value_in_size);
memcpy(value, pchBuf1, value_in_size);
//addr_t value_;
//QUEUE_POP(&value_, sizeof (addr_t));
//EGLint* value = NULL;
//size_t value_in_size = 0;
//assert(value_);
//QUEUE_POP(&value_in_size, sizeof (size_t));
//value = (EGLint*)malloc(value_in_size);
//assert(value);
EGLBoolean ret_value = eglGetConfigAttrib(dpy, config, attribute, value);
memcpy(pchBuf1, value, value_in_size);
HOST_START_PUSH();
//if ((size_t) write_linear(cpu, value_, value_in_size, value, 1) != value_in_size)
// HOST_WRITE_QUEUE(); //ABORT("write_linear in function \"eglGetConfigAttrib\" failed");
EGLint egl_error = eglGetError();
if ( attribute == EGL_NATIVE_VISUAL_ID )
{
*value = 0;
memcpy(pchBuf1, value, value_in_size);
ret_value = true;
egl_error = EGL_SUCCESS;
}
free(value);
sprintf(number, "egl_error = %d\n", egl_error);
fwrite( number, strlen(number), 1, fd);
sprintf( number, "ret = %d\n", ret_value);
fwrite( number, strlen(number), 1, fd);
fflush(fd);
fclose(fd);
QUEUE_PUSH(&egl_error, sizeof (EGLint));
QUEUE_PUSH(&ret_value, sizeof (EGLBoolean));
HOST_WRITE_QUEUE();
}
int video_call_egl_eglSignalSyncNV(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglSignalSyncNV\n");
fflush(stdout);
ABORT("Aborted function called: eglSignalSyncNV");
HOST_WRITE_QUEUE();
}
int video_call_egl_eglWaitGL(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglWaitGL\n");
fflush(stdout);
HOST_READ_QUEUE(1024);
egl_thread_state_host_t thread_state;
QUEUE_POP(&thread_state, sizeof (egl_thread_state_host_t));
egl_set_thread_state(&thread_state);
EGLBoolean ret_value = eglWaitGL();
HOST_START_PUSH();
EGLint egl_error = eglGetError();
QUEUE_PUSH(&egl_error, sizeof (EGLint));
QUEUE_PUSH(&ret_value, sizeof (EGLBoolean));
HOST_WRITE_QUEUE();
}
int video_call_egl_eglCreateFenceSyncNV(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglCreateFenceSyncNV\n");
fflush(stdout);
ABORT("Aborted function called: eglCreateFenceSyncNV");
HOST_WRITE_QUEUE();
}
int video_call_egl_eglLockSurfaceKHR(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglLockSurfaceKHR\n");
fflush(stdout);
ABORT("Aborted function called: eglLockSurfaceKHR");
HOST_WRITE_QUEUE();
}
int video_call_egl_eglSwapBuffers(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglSwapBuffers\n");
fflush(stdout);
HOST_READ_QUEUE(1024);
egl_thread_state_host_t thread_state;
QUEUE_POP(&thread_state, sizeof (egl_thread_state_host_t));
egl_set_thread_state(&thread_state);
EGLDisplay dpy;
QUEUE_POP(&dpy, sizeof (EGLDisplay));
EGLSurface surface;
QUEUE_POP(&surface, sizeof (EGLSurface));
EGLBoolean ret_value = eglSwapBuffers(dpy, surface);
HOST_START_PUSH();
EGLint egl_error = eglGetError();
QUEUE_PUSH(&egl_error, sizeof (EGLint));
QUEUE_PUSH(&ret_value, sizeof (EGLBoolean));
HOST_WRITE_QUEUE();
}
int video_call_egl_eglUnlockSurfaceKHR(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglUnlockSurfaceKHR\n");
fflush(stdout);
ABORT("Aborted function called: eglUnlockSurfaceKHR");
HOST_WRITE_QUEUE();
}
int video_call_egl_eglCreateSyncKHR(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglCreateSyncKHR\n");
fflush(stdout);
ABORT("Aborted function called: eglCreateSyncKHR");
HOST_WRITE_QUEUE();
}
int video_call_egl_eglSignalSyncKHR(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglSignalSyncKHR\n");
fflush(stdout);
ABORT("Aborted function called: eglSignalSyncKHR");
HOST_WRITE_QUEUE();
}
int video_call_egl_eglClientWaitSyncKHR(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglClientWaitSyncKHR\n");
fflush(stdout);
ABORT("Aborted function called: eglClientWaitSyncKHR");
HOST_WRITE_QUEUE();
}
int video_call_egl_egl_guest_buffer_texture(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: egl_guest_buffer_texture\n");
fflush(stdout);
HOST_READ_QUEUE(1024);
egl_thread_state_host_t thread_state;
QUEUE_POP(&thread_state, sizeof (egl_thread_state_host_t));
egl_set_thread_state(&thread_state);
uint8_t* pchBuf1 = (uint8_t *)paParms[k++].u.pointer.addr;
size_t buffer_out_size = paParms[k-1].u.pointer.size;
void* buffer = malloc(buffer_out_size);
memcpy(buffer, pchBuf1, buffer_out_size);
// addr_t buffer_;
// QUEUE_POP(&buffer_, sizeof (addr_t));
// void* buffer = NULL;
// size_t buffer_out_size = 0;
// assert(buffer_);
// QUEUE_POP(&buffer_out_size, sizeof (size_t));
// buffer = malloc(buffer_out_size);
// assert(buffer);
// if ((size_t) read_linear(cpu, buffer_, buffer_out_size, buffer, 1) != buffer_out_size)
// HOST_WRITE_QUEUE(); //ABORT("read_linear in function \"egl_guest_buffer_texture\" failed");
EGLint width;
QUEUE_POP(&width, sizeof (EGLint));
EGLint height;
QUEUE_POP(&height, sizeof (EGLint));
EGLint stride;
QUEUE_POP(&stride, sizeof (EGLint));
EGLint format;
QUEUE_POP(&format, sizeof (EGLint));
egl_guest_buffer_texture(buffer, width, height, stride, format);
HOST_START_PUSH();
free(buffer);
EGLint egl_error = eglGetError();
QUEUE_PUSH(&egl_error, sizeof (EGLint));
HOST_WRITE_QUEUE();
}
int video_call_egl_eglGetSystemTimeNV(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglGetSystemTimeNV\n");
fflush(stdout);
ABORT("Aborted function called: eglGetSystemTimeNV");
HOST_WRITE_QUEUE();
}
int video_call_egl_eglWaitClient(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglWaitClient\n");
fflush(stdout);
HOST_READ_QUEUE(1024);
egl_thread_state_host_t thread_state;
QUEUE_POP(&thread_state, sizeof (egl_thread_state_host_t));
egl_set_thread_state(&thread_state);
EGLBoolean ret_value = eglWaitClient();
HOST_START_PUSH();
EGLint egl_error = eglGetError();
QUEUE_PUSH(&egl_error, sizeof (EGLint));
QUEUE_PUSH(&ret_value, sizeof (EGLBoolean));
HOST_WRITE_QUEUE();
}
int video_call_egl_egl_get_configs_num(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: egl_get_configs_num\n");
fflush(stdout);
HOST_READ_QUEUE(1024);
EGLint ret_value = egl_get_configs_num();
HOST_START_PUSH();
QUEUE_PUSH(&ret_value, sizeof (EGLint));
HOST_WRITE_QUEUE();
}
int video_call_egl_eglCreatePixmapSurface(uint32_t cParms, VBOXHGCMSVCPARM paParms[])
{
printf("Function called: eglCreatePixmapSurface\n");
fflush(stdout);
ABORT("Aborted function called: eglCreatePixmapSurface");
HOST_WRITE_QUEUE();
}
|
#pragma once
#include <complex>
#include <execution>
#include <filesystem>
#include <fstream>
namespace ugsdr {
enum class FileType {
Iq_8_plus_8 = 0
};
template <typename UnderlyingType>
class SignalParametersBase {
private:
std::filesystem::path signal_file_path;
FileType file_type = FileType::Iq_8_plus_8;
double central_frequency = 1590e6; // L1 central frequency
double sampling_rate = 0.0;
std::ifstream signal_file;
using OutputVectorType = std::vector<std::complex<UnderlyingType>>;
void OpenFile() {
switch (file_type) {
case FileType::Iq_8_plus_8:
signal_file = std::ifstream(signal_file_path, std::ios::binary);
break;
default:
throw std::runtime_error("Unexpected file type");
}
}
void GetPartialSignal(std::size_t length_samples, std::size_t samples_offset, OutputVectorType& dst) {
switch (file_type) {
case FileType::Iq_8_plus_8: {
std::vector<std::complex<std::int8_t>> data;
std::vector<std::complex<std::int8_t>>* data_ptr;
if constexpr (std::is_same_v<std::int8_t, UnderlyingType>)
data_ptr = &dst;
else
data_ptr = &data;
data_ptr->clear();
data_ptr->resize(length_samples);
signal_file.seekg(samples_offset * sizeof(std::complex<std::int8_t>));
signal_file.read(reinterpret_cast<char*>(data_ptr->data()), length_samples * sizeof((*data_ptr)[0]));
if constexpr (!std::is_same_v<std::int8_t, UnderlyingType>) {
dst.clear();
dst.resize(length_samples);
std::copy(std::execution::par_unseq, data.begin(), data.end(), dst.begin());
}
break;
}
default:
throw std::runtime_error("Unexpected file type");;
}
}
public:
SignalParametersBase(std::filesystem::path signal_file, FileType type, double central_freq, double sampling_freq) :
signal_file_path(std::move(signal_file)),
file_type(type),
central_frequency(central_freq),
sampling_rate(sampling_freq) {
OpenFile();
}
void GetSeveralMs(std::size_t ms_offset, std::size_t ms_cnt, OutputVectorType& dst) {
const auto samples_per_ms = static_cast<std::size_t>(sampling_rate / 1000);
GetPartialSignal(samples_per_ms * ms_cnt, samples_per_ms * ms_offset, dst);
}
auto GetSeveralMs(std::size_t ms_offset, std::size_t ms_cnt) {
auto dst = OutputVectorType(ms_cnt * static_cast<std::size_t>(sampling_rate / 1e3));
GetSeveralMs(ms_offset, ms_cnt, dst);
return dst;
}
void GetOneMs(std::size_t ms_offset, OutputVectorType& dst) {
GetSeveralMs(ms_offset, 1, dst);
}
auto GetOneMs(std::size_t ms_offset) {
return GetSeveralMs(ms_offset, 1);
}
auto GetCentralFrequency() const {
return central_frequency;
}
auto GetSamplingRate() const {
return sampling_rate;
}
};
using SignalParameters = SignalParametersBase<std::int8_t>;
}
|
#include <cstdio>
#include <algorithm>
#include <iostream>
const int N = 30000333;
int n, m, k, a, b, c, A[N], B[N], C[N];
int main() {
freopen("minima.in", "r", stdin);
freopen("minima.out", "w", stdout);
scanf("%d%d%d", &n, &m, &k);
scanf("%d%d%d", &a, &b, &c);
for (int i = 0; i < k; ++i) {
scanf("%d", &A[i]);
}
for (int i = k; i < n; ++i) {
A[i] = a * A[i - 2] + b * A[i- 1] + c;
}
for (int i = 0; i < n; ++i) {
if (i % m == 0) {
B[i] = A[i];
} else {
B[i] = std::min(B[i - 1], A[i]);
}
}
long long ans = 0;
for (int i = n - 1; i >= 0; --i) {
if (i + 1 == n-1 || (i + 1) % m == 0) {
C[i] = A[i];
}else {
C[i] = std::min(C[i+1], A[i]);
}
if (i + m <= n) {
ans += std::min(C[i], B[i + m - 1]);
}
}
std::cout << ans << std::endl;
return 0;
}
|
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <list>
#include <algorithm>
#include <sstream>
#include <set>
#include <cmath>
#include <map>
#include <stack>
#include <queue>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <numeric>
#include <bitset>
#include <deque>
const long long LINF = (5e18);
const int INF = (1<<30);
#define EPS 1e-6
const int MOD = 1000000007;
using namespace std;
class RadioRange {
public:
typedef pair<double, double> P;
vector<P> make(vector<int> &X, vector<int> &Y, vector<int> &R) {
vector<P> res;
int N = (int)X.size();
for (int i=0; i<N; ++i) {
double r = sqrt( (double)X[i]*X[i] + (double)Y[i]*Y[i]);
double mn = max<double>(0.0,r-R[i]);
double mx = r + R[i];
res.push_back( P(mn, mx) );
}
return res;
}
double RadiusProbability(vector <int> X, vector <int> Y, vector <int> R, int Z) {
vector<P> ps(make(X, Y, R));
ps.push_back(P(1e20,1e20));
sort(ps.begin(), ps.end());
double ans = 1.0;
double low = -1, high = -1;
for (P p : ps) {
if (low > Z) {
break;
}
else if (high < p.first) {
ans -= (double)abs(high - low) / Z;
low = p.first;
high = min<double>(Z, p.second);
}
else if (high < p.second) {
high = min<double>(Z, p.second);
}
}
return ans;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); if ((Case == -1) || (Case == 6)) test_case_6(); if ((Case == -1) || (Case == 7)) test_case_7(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const double &Expected, const double &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arr0[] = {0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {5}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 10; double Arg4 = 0.5; verify_case(0, Arg4, RadiusProbability(Arg0, Arg1, Arg2, Arg3)); }
void test_case_1() { int Arr0[] = {0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {10}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 10; double Arg4 = 0.0; verify_case(1, Arg4, RadiusProbability(Arg0, Arg1, Arg2, Arg3)); }
void test_case_2() { int Arr0[] = {10}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {10}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {10}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 10; double Arg4 = 0.4142135623730951; verify_case(2, Arg4, RadiusProbability(Arg0, Arg1, Arg2, Arg3)); }
void test_case_3() { int Arr0[] = {11, -11, 0, 0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0, 0, 11, -11}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {10, 10, 10, 10}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 31; double Arg4 = 0.3548387096774194; verify_case(3, Arg4, RadiusProbability(Arg0, Arg1, Arg2, Arg3)); }
void test_case_4() { int Arr0[] = {100}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {100}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {1}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 10; double Arg4 = 1.0; verify_case(4, Arg4, RadiusProbability(Arg0, Arg1, Arg2, Arg3)); }
void test_case_5() { int Arr0[] = {1000000000}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {1000000000}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {1000000000}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 1000000000; double Arg4 = 0.41421356237309503; verify_case(5, Arg4, RadiusProbability(Arg0, Arg1, Arg2, Arg3)); }
void test_case_6() { int Arr0[] = {20, -20, 0, 0}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {0, 0, 20, -20}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {50, 50, 50, 50}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 100; double Arg4 = 0.3; verify_case(6, Arg4, RadiusProbability(Arg0, Arg1, Arg2, Arg3)); }
void test_case_7() { int Arr0[] = {0, -60, -62, -60, 63, -97}; vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arr1[] = {-72, 67, 61, -8, -32, 89}; vector <int> Arg1(Arr1, Arr1 + (sizeof(Arr1) / sizeof(Arr1[0]))); int Arr2[] = {6, 7, 8, 7, 5, 6}; vector <int> Arg2(Arr2, Arr2 + (sizeof(Arr2) / sizeof(Arr2[0]))); int Arg3 = 918; double Arg4 = 0.9407071068962471; verify_case(7, Arg4, RadiusProbability(Arg0, Arg1, Arg2, Arg3)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
RadioRange ___test;
___test.run_test(-1);
}
// END CUT HERE
|
#include "huobi_futures/linear_swap/ws/WebSocketOp.hpp"
#include "huobi_futures/linear_swap/ws/response/market/SubKLineResponse.hpp"
typedef huobi_futures::linear_swap::ws::response_market::SubKLineResponse SubKLineResponse;
#include "huobi_futures/linear_swap/ws/response/market/ReqKLineResponse.hpp"
typedef huobi_futures::linear_swap::ws::response_market::ReqKLineResponse ReqKLineResponse;
#include "huobi_futures/linear_swap/ws/response/market/SubDepthResponse.hpp"
typedef huobi_futures::linear_swap::ws::response_market::SubDepthResponse SubDepthResponse;
#include "huobi_futures/wsbase/WSSubData.hpp"
typedef huobi_futures::wsbase::WSSubData WSSubData;
#include "huobi_futures/wsbase/WSUnsubData.hpp"
typedef huobi_futures::wsbase::WSUnsubData WSUnsubData;
#include "huobi_futures/wsbase/WSReqData.hpp"
typedef huobi_futures::wsbase::WSReqData WSReqData;
#include "huobi_futures/utils/const_val.hpp"
namespace huobi_futures
{
namespace linear_swap
{
namespace ws
{
class WSMarketClient : public WebSocketOp
{
public:
WSMarketClient(string host = utils::DEFAULT_HOST) : WebSocketOp("/linear-swap-ws", host)
{
Connect();
}
~WSMarketClient()
{
Disconnect();
}
typedef std::function<void(const SubKLineResponse &data)> _OnSubKLineResponse;
void SubKLine(string contract_code, string period, _OnSubKLineResponse callbackFun, string id = utils::DEFAULT_ID)
{
stringstream ch;
ch << "market." << contract_code << ".kline." << period;
WSSubData sub_data;
sub_data.sub = ch.str();
sub_data.id = id;
Sub(sub_data.ToJson(), ch.str(), [&](const string &data) {
SubKLineResponse obj;
JS::ParseContext parseContext(data);
parseContext.allow_unnasigned_required_members = false;
if (parseContext.parseTo(obj) != JS::Error::NoError)
{
std::string errorStr = parseContext.makeErrorString();
LOG(ERROR) << "Error parsing struct SubKLineResponse error";
LOG(ERROR) << data;
return;
}
callbackFun(obj);
});
}
void UnsubKLine(string contract_code, string period, string id = utils::DEFAULT_ID)
{
stringstream ch;
ch << "market." << contract_code << ".kline." << period;
WSUnsubData unsub_data;
unsub_data.unsub = ch.str();
unsub_data.id = id;
Unsub(unsub_data.ToJson(), ch.str());
}
typedef std::function<void(const ReqKLineResponse &data)> _OnReqKLineResponse;
void ReqKLine(string contract_code, string period, long from, long to, _OnReqKLineResponse callbackFun, string id = utils::DEFAULT_ID)
{
stringstream ch;
ch << "market." << contract_code << ".kline." << period;
WSReqData req_data;
req_data.req = ch.str();
req_data.id = id;
req_data.from = from;
req_data.to = to;
Req(req_data.ToJson(), ch.str(), [&](const string &data) {
ReqKLineResponse obj;
JS::ParseContext parseContext(data);
parseContext.allow_unnasigned_required_members = false;
if (parseContext.parseTo(obj) != JS::Error::NoError)
{
std::string errorStr = parseContext.makeErrorString();
LOG(ERROR) << "Error parsing struct ReqKLineResponse error";
LOG(ERROR) << data;
return;
}
callbackFun(obj);
});
}
typedef std::function<void(const SubDepthResponse &data)> _OnSubDepthResponse;
void SubDepth(string contract_code, string type, _OnSubDepthResponse callbackFun, string id = utils::DEFAULT_ID)
{
stringstream ch;
ch << "market." << contract_code << ".depth." << type;
WSSubData sub_data;
sub_data.sub = ch.str();
sub_data.id = id;
Sub(sub_data.ToJson(), ch.str(), [&](const string &data) {
SubDepthResponse obj;
JS::ParseContext parseContext(data);
parseContext.allow_unnasigned_required_members = false;
if (parseContext.parseTo(obj) != JS::Error::NoError)
{
std::string errorStr = parseContext.makeErrorString();
LOG(ERROR) << "Error parsing struct SubDepthResponse error";
LOG(ERROR) << data;
return;
}
callbackFun(obj);
});
}
void UnSubDepth(string contract_code, string type, string id = utils::DEFAULT_ID)
{
stringstream ch;
ch << "market." << contract_code << ".depth." << type;
WSUnsubData unsub_data;
unsub_data.unsub = ch.str();
unsub_data.id = id;
Unsub(unsub_data.ToJson(), ch.str());
}
};
} // namespace ws
} // namespace linear_swap
} // namespace huobi_futures
|
/* XMRig
* Copyright 2010 Jeff Garzik <jgarzik@pobox.com>
* Copyright 2012-2014 pooler <pooler@litecoinpool.org>
* Copyright 2014 Lucas Jones <https://github.com/lucasjones>
* Copyright 2014-2016 Wolf9466 <https://github.com/OhGodAPet>
* Copyright 2016 Jay D Dee <jayddee246@gmail.com>
* Copyright 2017-2018 XMR-Stak <https://github.com/fireice-uk>, <https://github.com/psychocrypt>
* Copyright 2018-2019 SChernykh <https://github.com/SChernykh>
* Copyright 2016-2019 XMRig <https://github.com/xmrig>, <support@xmrig.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef XMRIG_OCLSHAREDDATA_H
#define XMRIG_OCLSHAREDDATA_H
#include <memory>
#include <mutex>
using cl_context = struct _cl_context *;
using cl_mem = struct _cl_mem *;
namespace xmrig {
class Job;
class OclSharedData
{
public:
OclSharedData() = default;
cl_mem createBuffer(cl_context context, size_t size, size_t &offset, size_t limit);
uint64_t adjustDelay(size_t id);
uint64_t resumeDelay(size_t id);
void release();
void setResumeCounter(uint32_t value);
void setRunTime(uint64_t time);
inline size_t threads() const { return m_threads; }
inline OclSharedData &operator++() { ++m_threads; return *this; }
# ifdef XMRIG_ALGO_RANDOMX
cl_mem dataset() const;
void createDataset(cl_context ctx, const Job &job, bool host);
# endif
private:
cl_mem m_buffer = nullptr;
double m_averageRunTime = 0.0;
double m_threshold = 0.95;
size_t m_offset = 0;
size_t m_threads = 0;
std::mutex m_mutex;
uint32_t m_resumeCounter = 0;
uint64_t m_timestamp = 0;
# ifdef XMRIG_ALGO_RANDOMX
cl_mem m_dataset = nullptr;
# endif
};
} /* namespace xmrig */
#endif /* XMRIG_OCLSHAREDDATA_H */
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
#include "Authentication.h"
#include "Client.h"
#include "Consumer.h"
#include "Producer.h"
#include "Reader.h"
#include "ThreadSafeDeferred.h"
#include <pulsar/c/client.h>
#include <pulsar/c/client_configuration.h>
#include <pulsar/c/result.h>
static const std::string CFG_SERVICE_URL = "serviceUrl";
static const std::string CFG_AUTH = "authentication";
static const std::string CFG_AUTH_PROP = "binding";
static const std::string CFG_OP_TIMEOUT = "operationTimeoutSeconds";
static const std::string CFG_IO_THREADS = "ioThreads";
static const std::string CFG_LISTENER_THREADS = "messageListenerThreads";
static const std::string CFG_CONCURRENT_LOOKUP = "concurrentLookupRequest";
static const std::string CFG_USE_TLS = "useTls";
static const std::string CFG_TLS_TRUST_CERT = "tlsTrustCertsFilePath";
static const std::string CFG_TLS_VALIDATE_HOSTNAME = "tlsValidateHostname";
static const std::string CFG_TLS_ALLOW_INSECURE = "tlsAllowInsecureConnection";
static const std::string CFG_STATS_INTERVAL = "statsIntervalInSeconds";
static const std::string CFG_LOG = "log";
LogCallback *Client::logCallback = nullptr;
void Client::SetLogHandler(const Napi::CallbackInfo &info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
Napi::Value jsFunction = info[0];
if (jsFunction.IsNull()) {
if (Client::logCallback != nullptr) {
Client::logCallback->callback.Release();
delete Client::logCallback;
Client::logCallback = nullptr;
}
} else if (jsFunction.IsFunction()) {
Napi::ThreadSafeFunction logFunction =
Napi::ThreadSafeFunction::New(env, jsFunction.As<Napi::Function>(), "Pulsar Logging", 0, 1);
logFunction.Unref(env);
if (Client::logCallback != nullptr) {
Client::logCallback->callback.Release();
} else {
Client::logCallback = new LogCallback();
}
Client::logCallback->callback = std::move(logFunction);
} else {
Napi::Error::New(env, "Client log handler must be a function or null").ThrowAsJavaScriptException();
}
}
Napi::FunctionReference Client::constructor;
Napi::Object Client::Init(Napi::Env env, Napi::Object exports) {
Napi::HandleScope scope(env);
Napi::Function func = DefineClass(
env, "Client",
{StaticMethod("setLogHandler", &Client::SetLogHandler),
InstanceMethod("createProducer", &Client::CreateProducer),
InstanceMethod("subscribe", &Client::Subscribe), InstanceMethod("createReader", &Client::CreateReader),
InstanceMethod("getPartitionsForTopic", &Client::GetPartitionsForTopic),
InstanceMethod("close", &Client::Close)});
constructor = Napi::Persistent(func);
constructor.SuppressDestruct();
exports.Set("Client", func);
return exports;
}
Client::Client(const Napi::CallbackInfo &info) : Napi::ObjectWrap<Client>(info) {
Napi::Env env = info.Env();
Napi::HandleScope scope(env);
Napi::Object clientConfig = info[0].As<Napi::Object>();
if (!clientConfig.Has(CFG_SERVICE_URL) || !clientConfig.Get(CFG_SERVICE_URL).IsString() ||
clientConfig.Get(CFG_SERVICE_URL).ToString().Utf8Value().empty()) {
Napi::Error::New(env, "Service URL is required and must be specified as a string")
.ThrowAsJavaScriptException();
return;
}
Napi::String serviceUrl = clientConfig.Get(CFG_SERVICE_URL).ToString();
this->cClientConfig = std::shared_ptr<pulsar_client_configuration_t>(pulsar_client_configuration_create(),
pulsar_client_configuration_free);
// The logger can only be set once per process, so we will take control of it
pulsar_client_configuration_set_logger(cClientConfig.get(), &LogMessage, nullptr);
// log config option should be deprecated in favour of static setLogHandler method
if (clientConfig.Has(CFG_LOG) && clientConfig.Get(CFG_LOG).IsFunction()) {
Napi::ThreadSafeFunction logFunction = Napi::ThreadSafeFunction::New(
env, clientConfig.Get(CFG_LOG).As<Napi::Function>(), "Pulsar Logging", 0, 1);
logFunction.Unref(env);
if (Client::logCallback != nullptr) {
Client::logCallback->callback.Release();
} else {
Client::logCallback = new LogCallback();
}
Client::logCallback->callback = std::move(logFunction);
}
if (clientConfig.Has(CFG_AUTH) && clientConfig.Get(CFG_AUTH).IsObject()) {
Napi::Object obj = clientConfig.Get(CFG_AUTH).ToObject();
if (obj.Has(CFG_AUTH_PROP) && obj.Get(CFG_AUTH_PROP).IsObject()) {
Authentication *auth = Authentication::Unwrap(obj.Get(CFG_AUTH_PROP).ToObject());
pulsar_client_configuration_set_auth(cClientConfig.get(), auth->GetCAuthentication());
}
}
if (clientConfig.Has(CFG_OP_TIMEOUT) && clientConfig.Get(CFG_OP_TIMEOUT).IsNumber()) {
int32_t operationTimeoutSeconds = clientConfig.Get(CFG_OP_TIMEOUT).ToNumber().Int32Value();
if (operationTimeoutSeconds > 0) {
pulsar_client_configuration_set_operation_timeout_seconds(cClientConfig.get(), operationTimeoutSeconds);
}
}
if (clientConfig.Has(CFG_IO_THREADS) && clientConfig.Get(CFG_IO_THREADS).IsNumber()) {
int32_t ioThreads = clientConfig.Get(CFG_IO_THREADS).ToNumber().Int32Value();
if (ioThreads > 0) {
pulsar_client_configuration_set_io_threads(cClientConfig.get(), ioThreads);
}
}
if (clientConfig.Has(CFG_LISTENER_THREADS) && clientConfig.Get(CFG_LISTENER_THREADS).IsNumber()) {
int32_t messageListenerThreads = clientConfig.Get(CFG_LISTENER_THREADS).ToNumber().Int32Value();
if (messageListenerThreads > 0) {
pulsar_client_configuration_set_message_listener_threads(cClientConfig.get(), messageListenerThreads);
}
}
if (clientConfig.Has(CFG_CONCURRENT_LOOKUP) && clientConfig.Get(CFG_CONCURRENT_LOOKUP).IsNumber()) {
int32_t concurrentLookupRequest = clientConfig.Get(CFG_CONCURRENT_LOOKUP).ToNumber().Int32Value();
if (concurrentLookupRequest > 0) {
pulsar_client_configuration_set_concurrent_lookup_request(cClientConfig.get(), concurrentLookupRequest);
}
}
if (clientConfig.Has(CFG_USE_TLS) && clientConfig.Get(CFG_USE_TLS).IsBoolean()) {
Napi::Boolean useTls = clientConfig.Get(CFG_USE_TLS).ToBoolean();
pulsar_client_configuration_set_use_tls(cClientConfig.get(), useTls.Value());
}
if (clientConfig.Has(CFG_TLS_TRUST_CERT) && clientConfig.Get(CFG_TLS_TRUST_CERT).IsString()) {
Napi::String tlsTrustCertsFilePath = clientConfig.Get(CFG_TLS_TRUST_CERT).ToString();
pulsar_client_configuration_set_tls_trust_certs_file_path(cClientConfig.get(),
tlsTrustCertsFilePath.Utf8Value().c_str());
}
if (clientConfig.Has(CFG_TLS_VALIDATE_HOSTNAME) &&
clientConfig.Get(CFG_TLS_VALIDATE_HOSTNAME).IsBoolean()) {
Napi::Boolean tlsValidateHostname = clientConfig.Get(CFG_TLS_VALIDATE_HOSTNAME).ToBoolean();
pulsar_client_configuration_set_validate_hostname(cClientConfig.get(), tlsValidateHostname.Value());
}
if (clientConfig.Has(CFG_TLS_ALLOW_INSECURE) && clientConfig.Get(CFG_TLS_ALLOW_INSECURE).IsBoolean()) {
Napi::Boolean tlsAllowInsecureConnection = clientConfig.Get(CFG_TLS_ALLOW_INSECURE).ToBoolean();
pulsar_client_configuration_set_tls_allow_insecure_connection(cClientConfig.get(),
tlsAllowInsecureConnection.Value());
}
if (clientConfig.Has(CFG_STATS_INTERVAL) && clientConfig.Get(CFG_STATS_INTERVAL).IsNumber()) {
uint32_t statsIntervalInSeconds = clientConfig.Get(CFG_STATS_INTERVAL).ToNumber().Uint32Value();
pulsar_client_configuration_set_stats_interval_in_seconds(cClientConfig.get(), statsIntervalInSeconds);
}
try {
this->cClient = std::shared_ptr<pulsar_client_t>(
pulsar_client_create(serviceUrl.Utf8Value().c_str(), cClientConfig.get()), pulsar_client_free);
} catch (const std::exception &e) {
Napi::Error::New(env, e.what()).ThrowAsJavaScriptException();
}
}
Client::~Client() {}
Napi::Value Client::CreateProducer(const Napi::CallbackInfo &info) {
return Producer::NewInstance(info, this->cClient);
}
Napi::Value Client::Subscribe(const Napi::CallbackInfo &info) {
return Consumer::NewInstance(info, this->cClient);
}
Napi::Value Client::CreateReader(const Napi::CallbackInfo &info) {
return Reader::NewInstance(info, this->cClient);
}
Napi::Value Client::GetPartitionsForTopic(const Napi::CallbackInfo &info) {
Napi::String topicString = info[0].As<Napi::String>();
std::string topic = topicString.Utf8Value();
auto deferred = ThreadSafeDeferred::New(Env());
auto ctx = new ExtDeferredContext(deferred);
pulsar_client_get_topic_partitions_async(
this->cClient.get(), topic.c_str(),
[](pulsar_result result, pulsar_string_list_t *topicList, void *ctx) {
auto deferredContext = static_cast<ExtDeferredContext *>(ctx);
auto deferred = deferredContext->deferred;
delete deferredContext;
if (result == pulsar_result_Ok && topicList != nullptr) {
deferred->Resolve([topicList](const Napi::Env env) {
int listSize = pulsar_string_list_size(topicList);
Napi::Array jsArray = Napi::Array::New(env, listSize);
for (int i = 0; i < listSize; i++) {
const char *str = pulsar_string_list_get(topicList, i);
jsArray.Set(i, Napi::String::New(env, str));
}
return jsArray;
});
} else {
deferred->Reject(std::string("Failed to GetPartitionsForTopic: ") + pulsar_result_str(result));
}
},
ctx);
return deferred->Promise();
}
void LogMessageProxy(Napi::Env env, Napi::Function jsCallback, struct LogMessage *logMessage) {
Napi::Number logLevel = Napi::Number::New(env, static_cast<double>(logMessage->level));
Napi::String file = Napi::String::New(env, logMessage->file);
Napi::Number line = Napi::Number::New(env, static_cast<double>(logMessage->line));
Napi::String message = Napi::String::New(env, logMessage->message);
delete logMessage;
jsCallback.Call({logLevel, file, line, message});
}
void Client::LogMessage(pulsar_logger_level_t level, const char *file, int line, const char *message,
void *ctx) {
LogCallback *logCallback = Client::logCallback;
if (logCallback == nullptr) {
return;
}
if (logCallback->callback.Acquire() != napi_ok) {
return;
}
struct LogMessage *logMessage = new struct LogMessage(level, std::string(file), line, std::string(message));
logCallback->callback.BlockingCall(logMessage, LogMessageProxy);
logCallback->callback.Release();
}
Napi::Value Client::Close(const Napi::CallbackInfo &info) {
auto deferred = ThreadSafeDeferred::New(Env());
auto ctx = new ExtDeferredContext(deferred);
pulsar_client_close_async(
this->cClient.get(),
[](pulsar_result result, void *ctx) {
auto deferredContext = static_cast<ExtDeferredContext *>(ctx);
auto deferred = deferredContext->deferred;
delete deferredContext;
if (result != pulsar_result_Ok) {
deferred->Reject(std::string("Failed to close client: ") + pulsar_result_str(result));
} else {
deferred->Resolve(THREADSAFE_DEFERRED_RESOLVER(env.Null()));
}
},
ctx);
return deferred->Promise();
}
|
#ifndef QUEST_H
#define QUEST_H
#include <QDialog>
#include <QFile>
#include <QtWidgets>
#include <QMessageBox>
#include <QVector>
#include "finalwindow.h"
#define maxQuestion 3
namespace Ui {
class Quest;
}
class Quest : public QDialog
{
Q_OBJECT
public:
explicit Quest(QWidget *parent = 0, QString dataFile="Foo");
~Quest();
public slots:
void NextButtonPress();
private:
Ui::Quest *ui;
int studentRating; //Оценка
int questNum;
QString mystr; //Переменная для разных целей
QString userFileName;
//Структура описывает вопрос и ответы
struct quest
{
QString question;
QString answer1;
int rightAns1;
QString answer2;
int rightAns2;
QString answer3;
int rightAns3;
};
QVector<quest> task;
QVector<int> questNumber;
void getExamQuest(); // Функция читает вопросы для экзамена и ответы к ним
void getQuestNumbers(QString dataFile); //Функция читает номера вопросов для экзамена
void ExitFunc(int studentRating, QString dataFile);
};
#endif // QUEST_H
|
#pragma once
#include "persona.h"
#include <string>
using std::string;
class Forense: public Persona{
string fechai, horario;
public:
//Forense(string, string);
Forense(string, string, string, int, int, string, string, string);
Forense(const Forense&);
virtual string toString()const;
string getFechai()const;
string getHorario()const;
void setFechai(string);
void setHorario(string);
/* data */
};
|
void blocked_reorder_naive(
float* src,
float* dst,
uint32_t* src_block_starts,
uint32_t* dst_block_starts,
uint32_t* block_sizes,
uint32_t num_blocks);
void blocked_reorder_memcpy(
float* src,
float* dst,
uint32_t* src_block_starts,
uint32_t* dst_block_starts,
uint32_t* block_sizes,
uint32_t num_blocks);
|
#ifndef SQLTEST_H
#define SQLTEST_H
#include <QSqlDriver>
#include <QSqlDatabase>
class MySqlTest : public QObject
{
Q_OBJECT
public:
MySqlTest();
~MySqlTest() {}
bool get_user(QString username);
private:
QSqlDatabase * db;
};
#endif // SQLTEST_H
|
#pragma once
#include "System/engine.h"
#include "System/mainengine.h"
#include "System/parallel_for.h"
#include "System/material.h"
#include "System/vector-all.h"
#include "System/time.h"
#include "System/Shape/nsphere.h"
#include "System/Shape/polytope.h"
#include "System/Shape/shapeinfo.h"
#include "System/type_id.h"
#include "System/entity.h"
#include "System/Provider/provider.h"
#include "System/Provider/mainenginetimeprovider.h"
#include "System/Provider/positionprovider.h"
#include "System/Provider/componentprovider.h"
#include "System/Provider/displaycomponentprovider.h"
#include "System/Provider/zerocomponentprovider.h"
#include "System/Provider/zerodisplaycomponentprovider.h"
#include "System/Provider/zeropositionprovider.h"
#include "System/accumulator.h"
#include "System/avgaccumulator.h"
#include "System/sumaccumulator.h"
#include "System/memory.h"
#include "System/clonable.h"
#include "System/clone.h"
|
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>
#include <string.h>
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
#include <pwd.h>
#include <grp.h>
#include <time.h>
#define MAXLINE 1024
#define NONE "\e[0m"
#define BLACK "\e[0;30m"
#define L_BLACK "\e[1;30m"
#define RED "\e[0;31m"
#define L_RED "\e[1;31m"
#define GREEN "\e[0;32m"
#define L_GREEN "\e[1;32m"
#define BROWN "\e[0;33m"
#define YELLOW "\e[1;33m"
#define BLUE "\e[0;34m"
#define L_BLUE "\e[1;34m"
#define PURPLE "\e[0;35m"
#define L_PURPLE "\e[1;35m"
#define CYAN "\e[0;36m"
#define L_CYAN "\e[1;36m"
#define GRAY "\e[0;37m"
#define WHITE "\e[1;37m"
#define BOLD "\e[1m"
#define UNDERLINE "\e[4m"
#define BLINK "\e[5m"
#define REVERSE "\e[7m"
#define HIDE "\e[8m"
#define CLEAR "\e[2J"
#define CLRLINE "\r\e[K"
#define ERROR_C "\e[1;31;40m"
struct FileInfo {
std::string name;
struct stat file_stat;
u_char d_type;
};
void print_dir(DIR *dir_ptr);
void print_file(const struct FileInfo &file_info);
void print_file(const struct FileInfo &file_info) {
char mode[11] = {0};
char *time_ptr;
if (file_info.d_type == DT_DIR) mode[0] = 'd';
else if (file_info.d_type == DT_LNK) mode[0] = 'l';
else mode[0] = '-';
mode[1] = ((file_info.file_stat.st_mode & S_IRUSR)? 'r':'-');
mode[2] = ((file_info.file_stat.st_mode & S_IWUSR)? 'w':'-');
mode[3] = ((file_info.file_stat.st_mode & S_IXUSR)? 'x':'-');
mode[4] = ((file_info.file_stat.st_mode & S_IRGRP)? 'r':'-');
mode[5] = ((file_info.file_stat.st_mode & S_IWGRP)? 'w':'-');
mode[6] = ((file_info.file_stat.st_mode & S_IXGRP)? 'x':'-');
mode[7] = ((file_info.file_stat.st_mode & S_IROTH)? 'r':'-');
mode[8] = ((file_info.file_stat.st_mode & S_IWOTH)? 'w':'-');
mode[9] = ((file_info.file_stat.st_mode & S_IXOTH)? 'x':'-');
std::cout << mode << "\t";
std::cout << file_info.file_stat.st_nlink << "\t";
std::cout << getpwuid(file_info.file_stat.st_uid)->pw_name << "\t";
std::cout << getgrgid(file_info.file_stat.st_gid)->gr_name << "\t";
std::cout << file_info.file_stat.st_size << "\t";
time_ptr = ctime(&file_info.file_stat.st_mtim.tv_sec);
time_ptr[strlen(time_ptr)-1] = 0;
std::cout << time_ptr << "\t";
if (file_info.d_type == DT_DIR) {
std::cout << L_BLUE;
std::cout << file_info.name;
std::cout << NONE;
} else if (file_info.d_type == DT_REG){
if (mode[3] == 'x' || mode[6] == 'x' or mode[9] == 'x') {
std::cout << L_GREEN;
std::cout << file_info.name;
std::cout << NONE;
} else {
std::cout << file_info.name;
}
} else if (file_info.d_type == DT_LNK) {
char filename[MAXLINE] = {0};
readlink(file_info.name.c_str(), filename, MAXLINE);
struct stat stat_buf;
if (stat(filename, &stat_buf) < 0) {
std::cout << ERROR_C << file_info.name << NONE << " -> " << ERROR_C << filename << NONE;
} else {
std::cout << L_CYAN;
std::cout << file_info.name;
std::cout << NONE;
std::cout << " -> ";
if (stat_buf.st_mode & S_IFDIR) {
std::cout << L_BLUE;
std::cout << filename;
std::cout << NONE;
} else if (stat_buf.st_mode & S_IFREG) {
if (stat_buf.st_mode & (S_IXUSR|S_IXGRP|S_IXOTH)) {
std::cout << L_GREEN;
std::cout << filename;
std::cout << NONE;
} else {
std::cout << filename;
}
} else {
std::cout << filename;
}
}
}
std::cout << "\n";
}
void print_dir(DIR *dir_ptr, std::string path) {
struct dirent *dir_entry;
struct stat stat_buf;
std::vector<std::string> dir_vec;
std::vector<struct FileInfo> file_vec;
uint total = 0;
while ((dir_entry = readdir(dir_ptr)) != NULL) {
struct FileInfo file_info;
if (dir_entry->d_name[0] == '.') continue;
if (dir_entry->d_type == DT_DIR) {
file_info.name = dir_entry->d_name;
stat(dir_entry->d_name, &stat_buf);
file_info.file_stat = stat_buf;
file_info.d_type = dir_entry->d_type;
file_vec.push_back(file_info);
total += (file_info.file_stat.st_blocks >> 1);
} else if (dir_entry->d_type == DT_LNK) {
file_info.name = dir_entry->d_name;
lstat(dir_entry->d_name, &stat_buf);
file_info.file_stat = stat_buf;
file_info.d_type = dir_entry->d_type;
file_vec.push_back(file_info);
} else if (dir_entry->d_type == DT_REG) {
file_info.name = dir_entry->d_name;
stat(dir_entry->d_name, &stat_buf);
file_info.file_stat = stat_buf;
file_info.d_type = dir_entry->d_type;
file_vec.push_back(file_info);
total += (file_info.file_stat.st_blocks >> 1);
}
}
sort(file_vec.begin(), file_vec.end(), [](const struct FileInfo &a, const struct FileInfo &b){return a.name < b.name;});
std::cout << path << ":\n" << "total " << total << std::endl;
for (const auto &file_info: file_vec) {
print_file(file_info);
if (file_info.d_type == DT_DIR) {
dir_vec.push_back(file_info.name);
}
}
std::cout << std::endl;
for (const auto &dir_name: dir_vec) {
DIR *subdir_ptr = opendir(dir_name.c_str());
chdir(dir_name.c_str());
std::string subpath = path + "/" + dir_name;
print_dir(subdir_ptr, subpath);
closedir(subdir_ptr);
chdir("..");
}
}
int main(int argc, char *argv[]) {
DIR *dir_ptr;
if (argc == 1) { // .
dir_ptr = opendir(".");
print_dir(dir_ptr, ".");
closedir(dir_ptr);
} else {
struct stat stat_buf;
char cwd_buf[MAXLINE];
getcwd(cwd_buf, MAXLINE);
for (int i=1; i<argc; ++i) {
if (lstat(argv[i], &stat_buf) < 0) {
std::cerr << "cannot access '" << argv[i] << "': No such file or directory" << std::endl;
exit(-1);
}
if (stat_buf.st_mode & S_IFDIR) {
dir_ptr = opendir(argv[i]);
chdir(argv[i]);
print_dir(dir_ptr, argv[i]);
closedir(dir_ptr);
chdir(cwd_buf);
} else {
struct FileInfo file_info;
file_info.file_stat = stat_buf;
file_info.name = argv[i];
if ((stat_buf.st_mode & S_IFLNK) == S_IFLNK) {
file_info.d_type = DT_LNK;
print_file(file_info);
std::cout << std::endl;
} else if (stat_buf.st_mode & S_IFREG) {
file_info.d_type = DT_REG;
print_file(file_info);
std::cout << std::endl;
}
}
}
}
exit(0);
}
|
#ifndef __DIRECTED_EDGE_H
#define __DIRECTED_EDGE_H
#include <vector>
using namespace std;
class DirectedEdge
{
private:
int v; // 边的起点
int w; // 边的终点
double weight; // 边的权重
public:
DirectedEdge(int v, int w,double weight)
{
this->v= v;
this->w = w;
this->weight = weight;
}
double get_weight()
{
return weight;
}
int from()
{
return v;
}
int to()
{
return w;
}
};
#endif
|
#include "BasicShader.h"
BasicShader::BasicShader()
{
addVertexShaderFromFile("basicVertex.glsl");
addFragmentShaderFromFile("basicFragment.glsl");
setAttributeLocation("position", 0);
setAttributeLocation("texCoord", 1);
compileShader();
addUniform("sampler");
addUniform("model");
addUniform("view");
addUniform("projection");
addUniform("light.ambient");
addUniform("light.direction");
addUniform("light.diffuse");
}
void BasicShader::updateUniforms(Transform& transform, Model& model, RenderingEngine* renderingEngine)
{
glm::mat4 view;
glm::mat4 projection;
projection = glm::perspective(glm::radians(60.0f), (float)Window::getWidth() / (float)Window::getHeight(), 0.1f, 1000.0f);
view = glm::translate(view, renderingEngine->getMainCamera().getTransform().getPos());
model.getMaterial()->getDiffuse()->bind();
setUniformi("sampler", model.getMaterial()->getDiffuse()->getTextureID());
setUniform("model", transform.getWorldMatrix());
setUniform("projection", renderingEngine->getMainCamera().getProjectionMatrix());
setUniform("view", renderingEngine->getMainCamera().getViewMatrix());
setUniform("light.ambient", glm::vec3(0.2f, 0.2f, 0.2f));
setUniform("light.diffuse", glm::vec3(0.5f, 0.5f, 0.5f));
setUniform("light.direction", glm::vec3(0.0f, 0.0f, 1.0f));
}
|
#include <iberbar/RHI/StateBlock.h>
iberbar::RHI::CStateBlock::CStateBlock()
: IResource( UResourceType::StateBlock )
{
}
|
/*
* Copyright (C) 2011 Thomas Kemmer <tkemmer@computer.org>
*
* http://code.google.com/p/stlencoders/
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#ifndef STLENCODERS_BASE32IMPL_HPP
#define STLENCODERS_BASE32IMPL_HPP
#include "dectbl.hpp"
namespace stlencoders {
namespace impl {
template<char C> struct b32 { enum { v = -1 }; };
template<> struct b32<'A'> { enum { v = 0x00 }; };
template<> struct b32<'a'> { enum { v = 0x00 }; };
template<> struct b32<'B'> { enum { v = 0x01 }; };
template<> struct b32<'b'> { enum { v = 0x01 }; };
template<> struct b32<'C'> { enum { v = 0x02 }; };
template<> struct b32<'c'> { enum { v = 0x02 }; };
template<> struct b32<'D'> { enum { v = 0x03 }; };
template<> struct b32<'d'> { enum { v = 0x03 }; };
template<> struct b32<'E'> { enum { v = 0x04 }; };
template<> struct b32<'e'> { enum { v = 0x04 }; };
template<> struct b32<'F'> { enum { v = 0x05 }; };
template<> struct b32<'f'> { enum { v = 0x05 }; };
template<> struct b32<'G'> { enum { v = 0x06 }; };
template<> struct b32<'g'> { enum { v = 0x06 }; };
template<> struct b32<'H'> { enum { v = 0x07 }; };
template<> struct b32<'h'> { enum { v = 0x07 }; };
template<> struct b32<'I'> { enum { v = 0x08 }; };
template<> struct b32<'i'> { enum { v = 0x08 }; };
template<> struct b32<'J'> { enum { v = 0x09 }; };
template<> struct b32<'j'> { enum { v = 0x09 }; };
template<> struct b32<'K'> { enum { v = 0x0a }; };
template<> struct b32<'k'> { enum { v = 0x0a }; };
template<> struct b32<'L'> { enum { v = 0x0b }; };
template<> struct b32<'l'> { enum { v = 0x0b }; };
template<> struct b32<'M'> { enum { v = 0x0c }; };
template<> struct b32<'m'> { enum { v = 0x0c }; };
template<> struct b32<'N'> { enum { v = 0x0d }; };
template<> struct b32<'n'> { enum { v = 0x0d }; };
template<> struct b32<'O'> { enum { v = 0x0e }; };
template<> struct b32<'o'> { enum { v = 0x0e }; };
template<> struct b32<'P'> { enum { v = 0x0f }; };
template<> struct b32<'p'> { enum { v = 0x0f }; };
template<> struct b32<'Q'> { enum { v = 0x10 }; };
template<> struct b32<'q'> { enum { v = 0x10 }; };
template<> struct b32<'R'> { enum { v = 0x11 }; };
template<> struct b32<'r'> { enum { v = 0x11 }; };
template<> struct b32<'S'> { enum { v = 0x12 }; };
template<> struct b32<'s'> { enum { v = 0x12 }; };
template<> struct b32<'T'> { enum { v = 0x13 }; };
template<> struct b32<'t'> { enum { v = 0x13 }; };
template<> struct b32<'U'> { enum { v = 0x14 }; };
template<> struct b32<'u'> { enum { v = 0x14 }; };
template<> struct b32<'V'> { enum { v = 0x15 }; };
template<> struct b32<'v'> { enum { v = 0x15 }; };
template<> struct b32<'W'> { enum { v = 0x16 }; };
template<> struct b32<'w'> { enum { v = 0x16 }; };
template<> struct b32<'X'> { enum { v = 0x17 }; };
template<> struct b32<'x'> { enum { v = 0x17 }; };
template<> struct b32<'Y'> { enum { v = 0x18 }; };
template<> struct b32<'y'> { enum { v = 0x18 }; };
template<> struct b32<'Z'> { enum { v = 0x19 }; };
template<> struct b32<'z'> { enum { v = 0x19 }; };
template<> struct b32<'2'> { enum { v = 0x1a }; };
template<> struct b32<'3'> { enum { v = 0x1b }; };
template<> struct b32<'4'> { enum { v = 0x1c }; };
template<> struct b32<'5'> { enum { v = 0x1d }; };
template<> struct b32<'6'> { enum { v = 0x1e }; };
template<> struct b32<'7'> { enum { v = 0x1f }; };
template<char C> struct b32hex { enum { v = -1 }; };
template<> struct b32hex<'0'> { enum { v = 0x00 }; };
template<> struct b32hex<'1'> { enum { v = 0x01 }; };
template<> struct b32hex<'2'> { enum { v = 0x02 }; };
template<> struct b32hex<'3'> { enum { v = 0x03 }; };
template<> struct b32hex<'4'> { enum { v = 0x04 }; };
template<> struct b32hex<'5'> { enum { v = 0x05 }; };
template<> struct b32hex<'6'> { enum { v = 0x06 }; };
template<> struct b32hex<'7'> { enum { v = 0x07 }; };
template<> struct b32hex<'8'> { enum { v = 0x08 }; };
template<> struct b32hex<'9'> { enum { v = 0x09 }; };
template<> struct b32hex<'A'> { enum { v = 0x0a }; };
template<> struct b32hex<'a'> { enum { v = 0x0a }; };
template<> struct b32hex<'B'> { enum { v = 0x0b }; };
template<> struct b32hex<'b'> { enum { v = 0x0b }; };
template<> struct b32hex<'C'> { enum { v = 0x0c }; };
template<> struct b32hex<'c'> { enum { v = 0x0c }; };
template<> struct b32hex<'D'> { enum { v = 0x0d }; };
template<> struct b32hex<'d'> { enum { v = 0x0d }; };
template<> struct b32hex<'E'> { enum { v = 0x0e }; };
template<> struct b32hex<'e'> { enum { v = 0x0e }; };
template<> struct b32hex<'F'> { enum { v = 0x0f }; };
template<> struct b32hex<'f'> { enum { v = 0x0f }; };
template<> struct b32hex<'G'> { enum { v = 0x10 }; };
template<> struct b32hex<'g'> { enum { v = 0x10 }; };
template<> struct b32hex<'H'> { enum { v = 0x11 }; };
template<> struct b32hex<'h'> { enum { v = 0x11 }; };
template<> struct b32hex<'I'> { enum { v = 0x12 }; };
template<> struct b32hex<'i'> { enum { v = 0x12 }; };
template<> struct b32hex<'J'> { enum { v = 0x13 }; };
template<> struct b32hex<'j'> { enum { v = 0x13 }; };
template<> struct b32hex<'K'> { enum { v = 0x14 }; };
template<> struct b32hex<'k'> { enum { v = 0x14 }; };
template<> struct b32hex<'L'> { enum { v = 0x15 }; };
template<> struct b32hex<'l'> { enum { v = 0x15 }; };
template<> struct b32hex<'M'> { enum { v = 0x16 }; };
template<> struct b32hex<'m'> { enum { v = 0x16 }; };
template<> struct b32hex<'N'> { enum { v = 0x17 }; };
template<> struct b32hex<'n'> { enum { v = 0x17 }; };
template<> struct b32hex<'O'> { enum { v = 0x18 }; };
template<> struct b32hex<'o'> { enum { v = 0x18 }; };
template<> struct b32hex<'P'> { enum { v = 0x19 }; };
template<> struct b32hex<'p'> { enum { v = 0x19 }; };
template<> struct b32hex<'Q'> { enum { v = 0x1a }; };
template<> struct b32hex<'q'> { enum { v = 0x1a }; };
template<> struct b32hex<'R'> { enum { v = 0x1b }; };
template<> struct b32hex<'r'> { enum { v = 0x1b }; };
template<> struct b32hex<'S'> { enum { v = 0x1c }; };
template<> struct b32hex<'s'> { enum { v = 0x1c }; };
template<> struct b32hex<'T'> { enum { v = 0x1d }; };
template<> struct b32hex<'t'> { enum { v = 0x1d }; };
template<> struct b32hex<'U'> { enum { v = 0x1e }; };
template<> struct b32hex<'u'> { enum { v = 0x1e }; };
template<> struct b32hex<'V'> { enum { v = 0x1f }; };
template<> struct b32hex<'v'> { enum { v = 0x1f }; };
}
}
#endif
|
#include "stdafx.h"
#include "../GameData.h"
#include "DungeonData.h"
void DungeonData::SetGameData(PyFile files, PyFile eneFile, int monsterAI[6], MonsterID monids[6], int DunNumber) {
m_files = files;
m_enemyFiles = eneFile;
for (int i = 0; i < 6; i++) {
m_monai[i] = monsterAI[i];
m_ids[i] = monids[i];
}
m_dunNum = DunNumber;
}
bool DungeonData::isFinalRound(int DunNum) {
return GetRound() == m_rounds[DunNum];
}
const int DungeonData::GetNumRound(int dungeon) {
return m_rounds[dungeon];
}
|
#include <iostream>
#include <vector>
using namespace std;
int findKthMulti(size_t k){
vector<int> v(1, 1);
size_t threeIndex = 0;
size_t fiveIndex = 0;
size_t sevenIndex = 0;
while(v.size() < k){
int threeNext = v[threeIndex] * 3;
int fiveNext = v[fiveIndex] * 5;
int sevenNext = v[sevenIndex] * 7;
if(threeNext < fiveNext && threeNext < sevenNext){
if(threeNext != v[v.size() - 1]){
v.push_back(threeNext);
}
threeIndex++;
}else if(fiveNext < sevenNext){
if(fiveNext != v[v.size() - 1]){
v.push_back(fiveNext);
}
fiveIndex++;
}else{
if(sevenNext != v[v.size() - 1]){
v.push_back(sevenNext);
}
sevenIndex++;
}
}
return v[k - 1];
}
int main(void){
cout << findKthMulti(5) << endl; // 9
cout << findKthMulti(6) << endl; // 15
cout << findKthMulti(7) << endl; // 21
cout << findKthMulti(8) << endl; // 25
cout << findKthMulti(9) << endl; // 27
cout << findKthMulti(10) << endl; // 35
cout << findKthMulti(11) << endl; // 45
return 0;
}
|
//====================================================================================
// @Title: CARTESIAN
//------------------------------------------------------------------------------------
// @Location: /prolix/common/include/cCartesian.h
// @Author: Kevin Chen
// @Rights: Copyright(c) 2011 Visionary Games
//------------------------------------------------------------------------------------
// @Description:
//
// Cartesian tools to create 2-tuple typed inputs, particularly window coordinates
// to indicate drawing locations.
//
//====================================================================================
#ifndef __PROLIX_BASE_COMMON_CARTESIAN_H__
#define __PROLIX_BASE_COMMON_CARTESIAN_H__
#include <string>
// forward declarations
struct Dimensions;
//====================================================================================
// cCartesian
//====================================================================================
struct cCartesian
{
int x; // x-coord
int y; // y-coord
// prints out string Format of cartesian coordinate
std::string Format();
// Constructors
cCartesian(int x = 0, int y = 0);
cCartesian(float x, float y);
cCartesian(double x, double y);
};
//====================================================================================
// Point
//====================================================================================
struct Point : public cCartesian
{
void Center(Dimensions dim);
// Constructors
Point(int x = 0, int y = 0);
Point(float x, float y);
Point(double x, double y);
};
// Arithmetic operations for Point manipulation
Point operator +(Point pos1, Point pos2);
Point operator -(Point pos1, Point pos2);
bool operator ==(Point pos1, Point pos2);
bool operator !=(Point pos1, Point pos2);
//====================================================================================
// Quad
//====================================================================================
struct Quad
{
// corners of the quadrilateral
Point top_left;
Point top_right;
Point bottom_left;
Point bottom_right;
// Constructor
Quad(Point top_left, Point top_right, Point bottom_left, Point bottom_right);
};
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2012 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"
#if defined(VEGA_USE_ASM) && defined(ARCHITECTURE_IA32)
#include <tmmintrin.h>
#include "modules/libvega/src/vegapixelformat.h"
#include "modules/libvega/src/x86/vegacommon_x86.h"
#include "modules/libvega/src/x86/vegacompositeover_x86.h"
#include "modules/libvega/src/x86/vegaremainder_x86.h"
static op_force_inline __m128i Sampler_NearestX4(const UINT32* src, INT32& csx, INT32 cdx)
{
// Get four samples.
__m128i s0 = _mm_cvtsi32_si128(SampleX(src, csx, cdx));
__m128i s1 = _mm_cvtsi32_si128(SampleX(src, csx, cdx));
__m128i s2 = _mm_cvtsi32_si128(SampleX(src, csx, cdx));
__m128i s3 = _mm_cvtsi32_si128(SampleX(src, csx, cdx));
// Merge them into one register.
s0 = Merge<4>(s0, s1);
s2 = Merge<4>(s2, s3);
s0 = Merge<8>(s0, s2);
return s0;
}
static op_force_inline __m128i Sampler_NearestXY4(const UINT32* src, unsigned int stride, INT32& csx, INT32 cdx, INT32& csy, INT32 cdy)
{
// Get four samples.
__m128i s0 = _mm_cvtsi32_si128(SampleXY(src, stride, csx, cdx, csy, cdy));
__m128i s1 = _mm_cvtsi32_si128(SampleXY(src, stride, csx, cdx, csy, cdy));
__m128i s2 = _mm_cvtsi32_si128(SampleXY(src, stride, csx, cdx, csy, cdy));
__m128i s3 = _mm_cvtsi32_si128(SampleXY(src, stride, csx, cdx, csy, cdy));
// Merge them into one register.
s0 = Merge<4>(s0, s1);
s2 = Merge<4>(s2, s3);
s0 = Merge<8>(s0, s2);
return s0;
}
extern "C" void Sampler_NearestX_SSSE3(UINT32* dst, const UINT32* src, unsigned int cnt, INT32 csx, INT32 cdx)
{
// Simple unrolling is the best we can do in this case and 4 seems to be the sweet spot.
unsigned int length = cnt / 4;
while (length--)
{
*dst++ = SampleX(src, csx, cdx);
*dst++ = SampleX(src, csx, cdx);
*dst++ = SampleX(src, csx, cdx);
*dst++ = SampleX(src, csx, cdx);
}
// Take care of the remaining few pixels.
cnt &= 3;
while (cnt--)
*dst++ = SampleX(src, csx, cdx);
}
extern "C" void Sampler_NearestX_CompOver_SSSE3(UINT32* dst, const UINT32* src, unsigned cnt, INT32 csx, INT32 cdx)
{
OP_ASSERT(IsPtrAligned(dst, 4));
__m128i src4, dst4;
// Check if we can use aligned memory access.
if (cnt > 3)
{
unsigned int unaligned = PixelsUntilAligned(dst);
if (unaligned)
{
LoadRemainder_SamplerX(src4, dst4, src, dst, csx, cdx, unaligned);
StoreRemainder(CompOver4(src4, dst4), dst, unaligned);
dst += unaligned;
cnt -= unaligned;
}
unsigned int length = cnt / 4;
while (length-- > 0)
{
src4 = Sampler_NearestX4(src, csx, cdx);
dst4 = _mm_load_si128((const __m128i *)dst);
_mm_store_si128((__m128i *)dst, CompOver4(src4, dst4));
dst += 4;
}
}
unsigned int length = cnt & 3;
if (length)
{
LoadRemainder_SamplerX(src4, dst4, src, dst, csx, cdx, length);
StoreRemainder(CompOver4(src4, dst4), dst, length);
}
}
extern "C" void Sampler_NearestX_CompOverMask_SSSE3(UINT32* dst, const UINT32* src, const UINT8* alpha, unsigned cnt, INT32 csx, INT32 cdx)
{
OP_ASSERT(IsPtrAligned(dst, 4));
if (cnt > 3)
{
unsigned int unaligned = PixelsUntilAligned(dst);
if (unaligned)
{
__m128i src4, dst4;
UINT8 mask[4];
LoadRemainder_SamplerX(src4, dst4, mask, src, dst, alpha, csx, cdx, unaligned);
StoreRemainder(CompOverMask4(src4, dst4, mask), dst, unaligned);
dst += unaligned;
alpha += unaligned;
cnt -= unaligned;
}
unsigned int length = cnt / 4;
while (length-- > 0)
{
__m128i src4 = Sampler_NearestX4(src, csx, cdx);
__m128i dst4 = _mm_load_si128((const __m128i *)dst);
_mm_store_si128((__m128i *)dst, CompOverMask4(src4, dst4, alpha));
dst += 4;
alpha += 4;
}
}
unsigned int length = cnt & 3;
if (length)
{
__m128i src4, dst4;
UINT8 mask[4];
LoadRemainder_SamplerX(src4, dst4, mask, src, dst, alpha, csx, cdx, length);
StoreRemainder(CompOverMask4(src4, dst4, mask), dst, length);
}
}
extern "C" void Sampler_NearestX_CompOverConstMask_SSSE3(UINT32* dst, const UINT32* src, UINT32 opacity, unsigned cnt, INT32 csx, INT32 cdx)
{
OP_ASSERT(IsPtrAligned(dst, 4));
// Unpack the mask into word components.
__m128i mask4 = _mm_cvtsi32_si128(opacity + 1);
mask4 = _mm_shuffle_epi8(mask4, g_xmm_constants.broadcast_word);
__m128i src4, dst4;
if (cnt > 3)
{
unsigned int unaligned = PixelsUntilAligned(dst);
if (unaligned)
{
LoadRemainder_SamplerX(src4, dst4, src, dst, csx, cdx, unaligned);
StoreRemainder(CompOverConstMask4(src4, dst4, mask4), dst, unaligned);
dst += unaligned;
cnt -= unaligned;
}
unsigned int length = cnt / 4;
while (length-- > 0)
{
src4 = Sampler_NearestX4(src, csx, cdx);
dst4 = _mm_load_si128((const __m128i *)dst);
_mm_store_si128((__m128i *)dst, CompOverConstMask4(src4, dst4, mask4));
dst += 4;
}
}
unsigned int length = cnt & 3;
if (length)
{
LoadRemainder_SamplerX(src4, dst4, src, dst, csx, cdx, length);
StoreRemainder(CompOverConstMask4(src4, dst4, mask4), dst, length);
}
}
extern "C" void Sampler_NearestXY_CompOver_SSSE3(UINT32* dst, const UINT32* src, unsigned cnt, unsigned stride, INT32 csx, INT32 cdx, INT32 csy, INT32 cdy)
{
OP_ASSERT(IsPtrAligned(dst, 4));
__m128i src4, dst4;
if (cnt > 3)
{
unsigned int unaligned = PixelsUntilAligned(dst);
if (unaligned)
{
LoadRemainder_SamplerXY(src4, dst4, src, dst, stride, csx, cdx, csy, cdy, unaligned);
StoreRemainder(CompOver4(src4, dst4), dst, unaligned);
dst += unaligned;
cnt -= unaligned;
}
unsigned int length = cnt / 4;
while (length-- > 0)
{
src4 = Sampler_NearestXY4(src, stride, csx, cdx, csy, cdy);
dst4 = _mm_load_si128((const __m128i *)dst);
_mm_store_si128((__m128i *)dst, CompOver4(src4, dst4));
dst += 4;
}
}
unsigned int length = cnt & 3;
if (length)
{
LoadRemainder_SamplerXY(src4, dst4, src, dst, stride, csx, cdx, csy, cdy, length);
StoreRemainder(CompOver4(src4, dst4), dst, length);
}
}
extern "C" void Sampler_NearestXY_CompOverMask_SSSE3(UINT32* dst, const UINT32* src, const UINT8* alpha, unsigned cnt, unsigned stride, INT32 csx, INT32 cdx, INT32 csy, INT32 cdy)
{
OP_ASSERT(IsPtrAligned(dst, 4));
__m128i src4, dst4;
if (cnt > 3)
{
unsigned int unaligned = PixelsUntilAligned(dst);
if (unaligned)
{
UINT8 mask[4];
LoadRemainder_SamplerXY(src4, dst4, mask, src, dst, alpha, stride, csx, cdx, csy, cdy, unaligned);
StoreRemainder(CompOverMask4(src4, dst4, mask), dst, unaligned);
dst += unaligned;
alpha += unaligned;
cnt -= unaligned;
}
unsigned int length = cnt / 4;
while (length-- > 0)
{
src4 = Sampler_NearestXY4(src, stride, csx, cdx, csy, cdy);
dst4 = _mm_load_si128((const __m128i *)dst);
_mm_store_si128((__m128i *)dst, CompOverMask4(src4, dst4, alpha));
dst += 4;
alpha += 4;
}
}
unsigned int length = cnt & 3;
if (length)
{
UINT8 mask[4];
LoadRemainder_SamplerXY(src4, dst4, mask, src, dst, alpha, stride, csx, cdx, csy, cdy, length);
StoreRemainder(CompOverMask4(src4, dst4, mask), dst, length);
}
}
#endif // defined(VEGA_USE_ASM) && defined(ARCHITECTURE_IA32)
|
#include <string>
/********************************************************************
Constants
********************************************************************/
const int START_ASM_TABLE = 0x87CC;
const int START_INIT_TABLE = 0x837D;
const int START_1656_TABLE = 0x3F46C;
const int START_1662_TABLE = 0x3F535;
const int START_166E_TABLE = 0x3F5FE;
const int START_167A_TABLE = 0x3F6C7;
const int START_1686_TABLE = 0x3F790;
const int START_190F_TABLE = 0x3F859;
const int BANK_SIZE = 0x8000;
const int BANK_STARTING_ADDRESS = 0x8000;
const int HEADER_SIZE = 0x200;
const int TAG_SIZE = 0xB; //S T A R # # # # M D K
const int SPRITE_TABLE_SIZE = 0x1000;
const std::string GENERATOR_PATH = ".\\generators\\";
const std::string SHOOTER_PATH = ".\\shooters\\";
const std::string SPRITE_PATH = ".\\sprites\\";
const std::string INIT_LABEL = "INIT";
const std::string MAIN_LABEL = "MAIN";
const char * RATS_TAG_LABEL = "STAR";
const char * SPRITE_TOOL_LABEL = "MDK";
const char * WELCOME_MESSAGE =
"Sprite Tool v1.41, by mikeyk, asar support.\n"
"If you get an error when running the program, read the readme for tips.\n"
"Keep in mind that sprites will not appear correctly in Lunar Magic.\n"
"usage : SMW.smc list.txt";
const char * ABORT_MESSAGE =
"It is recommended that you abort Sprite Tool at this time.\n"
"Do not continue unless you are absolutely sure of what you are doing.\n"
"Trying to continue will probably corrupt you ROM!\n"
"Do you want to take my advice and quit? (Type yes or no)";
const char * BAD_NUM =
"Custom sprite numbers E0-FF are undefined. Please check your sprite list.\n"
"See the readme for more information";
const char * TOO_LARGE =
"Your file won't fit in a bank. Be sure you do not have an org statement\n"
"in the .asm file";
const char * NO_BIN_FILE =
"Couldn't open .\\tmpasm.bin. Make sure TRASM.EXE is in the same directory\n"
"and that it can run on your system.";
|
#include "cactus.h"
#include "timerlist.h"
#include "dino.h"
#include "game.h"
#include "gameover.h"
#include <QTimer>
#include <QObject>
#include <QGraphicsScene>
#include <QGraphicsPixmapItem>
#include <QGraphicsItem>
#include <QList>
extern Game *game;
Cactus::Cactus(double moveSpeed, QString path, int yPos, int xPos): QObject(), QGraphicsPixmapItem() {
setPixmap(QPixmap(path));
setScale(0.9);
setPos(1200 + xPos, yPos);
this->moveSpeed = moveSpeed;
moveTimer = new QTimer();
// add Timer to list. Used to terminate all Timers if colliding
allTimers->addToList(moveTimer);
connect(moveTimer, SIGNAL(timeout()), this, SLOT(move()));
moveTimer->start(35);
}
void Cactus::setMoveSpeed(double moveSpeed) {
this->moveSpeed = moveSpeed;
}
void Cactus::move() {
// if cactus collides with dino
QList<QGraphicsItem *> items = collidingItems();
for (int i = 0; i < items.size(); i++) {
if (typeid (*(items[i])) == typeid (Dino)) {
Dino *dino = game->player;
QString path = ":/Image/dinoDead0000.png";
if(game->isChangeColor) {
path = ":/Image/dinoDeadNegative0000.png";
}
dino->setImage(path);
dino->setPosition(dino->x(), dino->baselineY);
QList<QTimer *> timers = allTimers->getList();
GameOver *go = new GameOver();
scene()->addWidget(go->getLabel());
scene()->addWidget(go->getButton());
for (QTimer *timer : timers) {
timer->stop();
}
game->player->clearFocus();
}
}
setPos(x() - moveSpeed, y());
if (pos().x() + boundingRect().width() < 0) {
scene()->removeItem(this);
delete this;
}
}
|
#ifndef _DX11_SHADER_H_
#define _DX11_SHADER_H_
#include "d3d11.h"
#include "Shader.h"
#include "DX11InputLayout.h"
namespace HW{
class DX11InputLayout;
class DX11Shader : public Shader{
public:
DX11Shader(ShaderType type);
DX11Shader(ShaderType type, const String& name);
virtual ~DX11Shader();
virtual bool loadShaderFromFile(const char* filename, const char* entryFunc, const char* mode);
// Dont read xml shader yet
virtual bool ParseShaderFromXml(rapidxml::xml_node<> * node){ return false; }
// Dont read shader from json yet
virtual bool ParseShaderFromJson(rapidjson::Document& d);
virtual unsigned int getErrorMessageSize() const;
virtual void getErrorMessage(char* dest, unsigned int size);
virtual InputLayout* getInputLayout();
virtual void releaseInternalRes();
/*
void* GetShader() const{
return m_pShader;
}*/
void* GetShaderBuffer() const{
return m_pShaderBlob->GetBufferPointer();
}
SIZE_T GetShaderBufferSize() const{
return m_pShaderBlob->GetBufferSize();
}
private:
bool LoadShader(ShaderType shaderType, ID3D10Blob* blob); // Compile the shader by the shaderType
ID3D10Blob* m_pShaderBlob; // The buffer used to store the compiled shader
ID3D10Blob* m_pCompilationMsgBlob; // The buffer used to store the compilation error message
DX11InputLayout* m_pInputLayout;
// void* m_pShader; // Dynamic determination of Shader Type
// bool m_bIsReleased; // To flag whether the Internal resource has been released
};
class DX11ShaderFactory : public ShaderFactory{
public:
DX11ShaderFactory(){}
virtual ~DX11ShaderFactory(){}
virtual Shader* CreateShader(const String& name, ShaderType shaderType);
virtual Shader* CreateShader(ShaderType shaderType);
};
}
#endif
|
#pragma once
#include "buffer.hpp"
namespace leaves { namespace pipeline
{
template <>
struct buffer_traits<index_buffer>
{
static constexpr object_type type() noexcept
{
return object_type::index_buffer;
}
};
class index_buffer : public buffer<index_buffer>
{
public:
using base_type = buffer<index_buffer>;
template <typename T>
using iterator = stream_buffer_iterator<T>;
public:
// construct
index_buffer(string name, primitive_type primitive, data_format format, size_t primitive_count)
: base_type(
std::move(name),
detail::size_of(format),
detail::count_of(primitive, primitive_count),
device_access::none, device_access::read)
, primitive_(primitive)
, format_(format)
, primitive_count_(primitive_count)
{
throw_if_invalid_format(format);
allocate();
}
// attribute access
primitive_type primitive() const noexcept
{
return primitive_;
}
data_format format() const noexcept
{
return format_;
}
size_t primitive_count() const noexcept
{
return primitive_count_;
}
// attribute modify
void resize(primitive_type primitive, data_format format, size_t primitive_count)
{
throw_if_invalid_format(format);
base_type::resize(detail::size_of(format), detail::count_of(primitive, primitive_count));
primitive_ = primitive;
format_ = format;
primitive_count_ = primitive_count;
}
void resize(primitive_type primitive)
{
resize(primitive, format_, primitive_count_);
}
void resize(data_format format)
{
resize(primitive_, format, primitive_count_);
}
void resize(size_t primitive_count)
{
resize(primitive_, format_, primitive_count);
}
template <typename T>
auto begin()
{
static_assert(std::is_integral<T>::value, "Can only be integral type!");
if (std::is_signed<T>::value != detail::is_signed(format_) &&
sizeof(T) != detail::size_of(format_))
throw std::exception{};
return reinterpret_cast<T*>(data());
}
template <typename T>
auto end()
{
static_assert(std::is_integral<T>::value, "Can only be integral type!");
if (std::is_signed<T>::value != detail::is_signed(format_) &&
sizeof(T) != detail::size_of(format_))
throw std::exception{};
return reinterpret_cast<T*>(data() + size());
}
private:
static void throw_if_invalid_format(data_format format)
{
if (format != data_format::int_ && format != data_format::uint)
throw std::exception();
}
private:
primitive_type primitive_;
data_format format_;
size_t primitive_count_;
};
} }
|
#pragma GCC optimize("Ofast")
#include <algorithm>
#include <bitset>
#include <deque>
#include <iostream>
#include <iterator>
#include <string>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
#include <unordered_map>
#include <unordered_set>
using namespace std;
void abhisheknaiidu()
{
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
}
void sol(vector<vector<int>> v, int s, int e, int &sum, int i) {
if(i >= v.size()) return;
sum += v[i][s] + v[i][e];
if(s == e) sum = sum - v[i][s];
sol(v, s+1, e-1, sum, i+1);
}
int main(int argc, char* argv[]) {
abhisheknaiidu();
vector<vector<int>> v1{{1,1,1,1}, {1,1,1,1}, {1,1,1,1}, {1,1,1,1}};
vector <vector<int>> v{{1,2,3}, {4,5,6}, {7,8,9}};
vector<vector<int>> v2{{5}};
int n = v[0].size();
int index;
int s = 0;
sol(v, 0, n-1, s, 0);
cout << s << endl;
for(auto x: v) {
for(auto y: x) {
cout << y << " ";
}
cout << endl;
}
return 0;
}
|
#ifndef SCENE_H
#define SCENE_H
#include "cpvs.h"
#include "BoundingVolumes.h"
struct Material {
vec3 diffuseColor;
int shininess;
Material() : diffuseColor(0), shininess(0) { }
inline bool operator==(const Material& rhs) const {
return (diffuseColor == rhs.diffuseColor) && (shininess == rhs.shininess);
}
inline bool operator!=(const Material& rhs) const {
return !(*this == rhs);
}
};
struct Mesh {
GLuint vao;
GLuint numFaces;
Material material;
AABB boundingBox;
inline void bind() const {
glBindVertexArray(vao);
}
inline void draw() const {
glDrawElements(GL_TRIANGLES, numFaces * 3, GL_UNSIGNED_INT, 0);
}
};
struct Scene {
Scene() = default;
Scene(const Scene& rhs) = delete;
Scene& operator=(const Scene& rhs) = delete;
Scene(Scene&& rhs) = default;
Scene& operator=(Scene&& rhs) = default;
inline ~Scene() {
for (const auto& mesh : meshes)
glDeleteVertexArrays(1, &mesh.vao);
}
AABB boundingBox;
std::vector<Mesh> meshes;
};
#endif
|
#ifndef GAMEOBJECT_H
#define GAMEOBJECT_H
#include <vector>
#include <SFML\System\Vector2.hpp>
enum keyword;
namespace sf
{
class Time;
class Shape;
}
class GameObject
{
public:
GameObject(keyword aType, sf::Vector2f position, sf::Vector2f size, float scale);
~GameObject();
void update(sf::Time& time);
void draw();
std::string toString();
sf::Shape* GetShape();
sf::Vector2f GetPosition();
void SetPosition(sf::Vector2f position);
sf::Vector2f GetSize();
keyword GetType();
std::vector<sf::Vector2f> GetPoints();
private:
sf::Shape* mShape;
void SetShape(keyword aType, sf::Vector2f size, float scale);
sf::Vector2f mPosition;
sf::Vector2f mSize;
float mTime;
std::vector<sf::Vector2f> mSurroundingPoints;
sf::Vector2f mStartPoint;
sf::Vector2f mEndPoint;
keyword mType;
};
#endif
|
/* XMRig
* Copyright (c) 2000-2002 Alan Cox <alan@redhat.com>
* Copyright (c) 2005-2020 Jean Delvare <jdelvare@suse.de>
* Copyright (c) 2018-2021 SChernykh <https://github.com/SChernykh>
* Copyright (c) 2016-2021 XMRig <https://github.com/xmrig>, <support@xmrig.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef XMRIG_DMIMEMORY_H
#define XMRIG_DMIMEMORY_H
#include "base/tools/String.h"
namespace xmrig {
struct dmi_header;
class DmiMemory
{
public:
DmiMemory() = default;
DmiMemory(dmi_header *h);
inline bool isValid() const { return !m_slot.isEmpty(); }
inline const String &bank() const { return m_bank; }
inline const String &id() const { return m_id.isNull() ? m_slot : m_id; }
inline const String &product() const { return m_product; }
inline const String &slot() const { return m_slot; }
inline const String &vendor() const { return m_vendor; }
inline uint16_t totalWidth() const { return m_totalWidth; }
inline uint16_t voltage() const { return m_voltage; }
inline uint16_t width() const { return m_width; }
inline uint64_t size() const { return m_size; }
inline uint64_t speed() const { return m_speed; }
inline uint8_t rank() const { return m_rank; }
const char *formFactor() const;
const char *type() const;
# ifdef XMRIG_FEATURE_API
rapidjson::Value toJSON(rapidjson::Document &doc) const;
# endif
private:
void setId(const char *slot, const char *bank);
String m_bank;
String m_id;
String m_product;
String m_slot;
String m_vendor;
uint16_t m_totalWidth = 0;
uint16_t m_voltage = 0;
uint16_t m_width = 0;
uint64_t m_size = 0;
uint64_t m_speed = 0;
uint8_t m_formFactor = 0;
uint8_t m_rank = 0;
uint8_t m_type = 0;
};
} /* namespace xmrig */
#endif /* XMRIG_DMIMEMORY_H */
|
#pragma once
namespace oglml
{
class PostProcessor;
}
namespace breakout
{
class APostEffectState;
class LinearAllocator;
class PostEffectsFabric
{
using EnumStateName = int;
public:
static APostEffectState* GeneratePostEffect(LinearAllocator*, EnumStateName, oglml::PostProcessor*);
};
}
|
#pragma once
#include <wx/wx.h>
class CMainFrame;
class MyApp : public wxApp
{
public:
MyApp();
virtual ~MyApp();
virtual bool OnInit();
private:
CMainFrame * m_frame;
};
|
#include <iostream>
#include <vector>
#include <sstream>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#define PORT 8080
using namespace std;
void welcomeMessage();
void postScreen();
void viewScreen();
// void clearConsole();
void viewSpecificQuestion(string title);
int main() {
int sock_id = 0;
struct sockaddr_in sv_addr;
sock_id = socket(AF_INET, SOCK_STREAM, 0);
if(sock_id < 0){
cout<<"client: socket creation error\n";
return 1;
}
memset(&sv_addr, '0', sizeof(sv_addr));
sv_addr.sin_family = AF_INET;
sv_addr.sin_port = htons(PORT);
if(inet_pton(AF_INET, "127.0.0.1", &sv_addr.sin_addr) <= 0){
cout<<"client: invalid address";
return 1;
}
if(connect(sock_id, (struct sockaddr*)& sv_addr, sizeof(sv_addr)) < 0){
cout<<"client: connection failed";
return 1;
}
string mess = "Hello Sever. I am Client";
send(sock_id, mess.c_str(), mess.length(), 0);
cout<<"client: message has been sent";
welcomeMessage();
return 0;
}
void welcomeMessage() {
string userInputStr;
int userInput = 0;
while(userInput != 3) {
// clearConsole();
cout << " Welcome to the Question & Answer Forum \n"
"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
"What would you like to do?\n"
"\t1. Post a new Question\n\t2. View Questions\n\t3. Exit\n"
"Enter corresponding number: ";
cin >> userInputStr;
try {
userInput = stoi(userInputStr);
} catch (exception &e) {
cout << "\nInvalid input, only enter numbers 1, 2 or 3.\n\n\n";
// clearConsole();
welcomeMessage();
}
if (userInput == 1) {
// clearConsole();
postScreen();
} else if (userInput == 2) {
// clearConsole();
viewScreen();
} else if (userInput == 3) {
// clearConsole();
cout << "Goodbye..";
} else {
cout << "\nPlease enter either 1, 2 or 3 only.\n\n";
welcomeMessage();
}
}
}
void postScreen(){
string userInputStr, title, question;
int userInput = 0;
cout << " Post \n"
"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"
"\nEnter -1 to exit\nEnter Question Title:\t";
cin >> title;
try {
userInput = stoi(title);
if(userInput == -1)
return;
} catch (exception ) {
}
cout << "\nEnter -1 to exit\nEnter Question: ";
cin >> question;
try {
userInput = stoi(title);
if(userInput == -1)
return;
} catch (exception ) {
}
// POST HERE
//post(title + "," + question);
/*SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
string addr = "localhost";
if (0 == connect(s, reinterpret_cast<const sockaddr *>(&addr), sizeof(addr)))
cout << "Connected.\n";
else
cout << "Connection Error.\n";
*/
cout << "Question \"" << title << "\" has been posted.\n";
}
void viewScreen(){
string userInputStr, title, question;
string questionString;
vector<string> questions;
// GET here
//questions = get();
questionString = "Question1_Title,Question1:Question2_Title,Question2:Question3_Title,Question3:Question4_Title,Question4";
stringstream ss(questionString);
while (ss.good()) {
string substr;
getline(ss, substr, ':');
questions.push_back(substr);
}
int userInput = 0;
while(userInput != questions.size()+1) {
// clearConsole();
cout << " Questions \n"
"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
int counter = 1;
for (int i = 0; i < questions.size(); i++) {
cout << (i + 1) << ": ";
int pos;
pos = questions[i].find(",");
cout << questions[i].substr(0, pos) << "\n\t\t";
//questions[i].substr(pos + 1);
cout << questions[i].substr(pos + 1) << "\n";
}
cout << "------------------------\n" << questions.size()+1 << ": Exit\n\n";
cout << "Enter corresponding number: ";
cin >> userInput;
if(userInput > 0 && userInput < (questions.size()+1)){
int pos;
string title;
pos = questions[userInput-1].find(",");
title = questions[userInput-1].substr(0, pos);
viewSpecificQuestion(title);
}
if(userInput > questions.size()+1)
userInput = questions.size()+1;
}
}
void viewSpecificQuestion(string title){
int userInput;
string question,answer,response;
vector<string> answers;
// Get question/answers by title
response = "QuestionX:Answer1,Answer2,Answer3,Answer4,Answer5,Answer6,Answer7";
int pos = response.find(':');
question = response.substr(0, pos);
answer = response.erase(0, pos+1);
stringstream ss(answer);
while (ss.good()) {
string substr;
getline(ss, substr, ',');
answers.push_back(substr);
}
// clearConsole();
cout << title << "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n";
cout << "Q: " << question << "\n\n";
for (int i = 0; i < answers.size(); i++) {
cout << "A" << (i + 1) << ": " << answers[i] << "\n\n";
}
cout << "------------------------\n" <<
answers.size()+1 << ": Submit New Answer\n" << answers.size()+2 << ": Exit\n\n";
cout << "Enter corresponding number: ";
cin >> userInput;
if(userInput > 0 && userInput <= answers.size()){
}else if(userInput == answers.size()+1) {
string newAnswer;
cout << "Enter new answer:\n\t";
cin >> newAnswer;
// POST HERE
//post(title + "," + question);
}
}
// Helper Methods
// void clearConsole(){
// //system("pause");
// for (int i = 0; i < 25; ++i) {
// cout << "\n";
// }
// }
|
#include <iostream>
#include <bitset>
#include "huffman_tree.h"
using namespace std;
int main() {
// ifstream ifs;
// ifs.open("textinput");
// string source;
// source.assign((istreambuf_iterator<char>(ifs.rdbuf())), istreambuf_iterator<char>());
HuffmanTree h("abacaba");
writeBinary(encodeTree(h), "tree");
h = decodeTree(readBinary("tree"));
string s;
while (cin >> s) {
cout << h.encode(s) << endl;
cout << h.decode(h.encode(s)) << endl;
}
return 0;
}
|
#include<stdio.h> //printf
#include<string.h> //memset
#include<stdlib.h> //exit(0);
#include<arpa/inet.h>
#include<sys/socket.h>
#include <unistd.h>
#include <iostream>
#include <vector>
#include<cmath>
#include <algorithm>
#include <unistd.h>
using namespace std;
#define PORT 32000 //The port on which to listen for incoming data
vector<string> deck;
vector<int> deckNo;
vector<int> aliceCard;
vector<int> BobCard;
vector<int>EncryptedDeck;
vector<int>decDeck;
vector<int>AliceBobEncryptedDeck;
vector<int>BobDecryptedDeck;
vector<int>AliceDecryptedDeck;
vector<int>AliceBobDecryptedDeck;
string suit[] = {"Diamonds", "Hearts", "Spades", "Clubs"};
string facevalue[] = {"Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace"};
int EncryptedDeckArr[52];
string deckArr[52];
int BobCardArr[5];
int AliceBobEncryptedDeckArr[5];
int AliceBobDecryptedDeckArr[5];
// --- Generate cards
void generateCard()
{
int i;
int j;
int k=1;
for(i=0;i<13;i++)
{
for(j=0;j<4;j++)
{
string s;
s.append(facevalue[i]);
s.append("of");
s.append(suit[j]);
deck.push_back(s);
}
}
for(int m=48 ; m<=99;m++)
{
deckNo.push_back(m);
}
}
//-- calculate GCD
int gcd(int a , int b)
{
int c;
while ( a != 0 )
{
c = a;
a = b%a;
b = c;
}
return b;
}
//-- perform encryption and decryption of cards
int modPower(int msg,int key ,int primeNo)
{
int y=1;
int u = msg%primeNo;
while(key!=0)
{
if(key%2==1)
{
y= (y*u)%primeNo;
}
key = floor(key/2);
u = (u*u)%primeNo;
}
return y;
}
//--- Calculate Decryption key
int decKey(int a, int b)
{
int b0 = b, t, q;
int x0 = 0, x1 = 1;
if (b == 1) return 1;
while (a > 1)
{
q = a / b;
t = b, b = a % b, a = t;
t = x0, x0 = x1 - q * x0, x1 = t;
}
if (x1 < 0)
{
x1 += b0;
}
return x1;
}
int main(void)
{
struct sockaddr_in si_me, si_other;
int s, i, recv_len;
socklen_t slen;
int b,c,ae,be ,aD,bD;
int primeNo=167;
int phiNo;
// int a[1]={rand()%(32000-100+1)+100 };
//primeNo= a[0];
phiNo = primeNo-1;
int bdec[1];
cout<< "prime no is"<<primeNo<<"\n";
//create a UDP socket
s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
// zero out the structure
bzero(&si_me,sizeof(si_me));
si_me.sin_family = AF_INET;
si_me.sin_addr.s_addr = htonl(INADDR_ANY);
si_me.sin_port = htons(32000);
//bind socket to port
bind(s , (struct sockaddr*)&si_me, sizeof(si_me) );
slen = sizeof(si_other);
//sendto(s, a, sizeof(a), 0, (struct sockaddr*)&si_other, slen);
int km=1;
while(km!=0)
{
cout<< "\n enter Bob E key such that gcd=1\n";
cin>> be;
b=gcd(be,phiNo);
//cout<<b;
if(b==1)
{
km--;
}
else{
cout<< "\n wrong input\n";
}
}
bdec[0]= decKey(be,phiNo);
bD = bdec[0];
cout<< "\n--Bob D key--\n" << bD;
generateCard();
cout<< "\n-------shuffle cards-----\n";
random_shuffle(deckNo.begin(), deckNo.end());
cout<< "\n-----encryption with Bob Key----\n";
//---Encrypt all cards with bob encrypted key
for(int i=0 ;i<52;i++)
{
int no = deckNo.at(i);
int encryptNo =modPower(no,be,primeNo);
EncryptedDeck.push_back(encryptNo);
}
std::copy(EncryptedDeck.begin(), EncryptedDeck.end(), EncryptedDeckArr);
string arr[1];
recvfrom(s,arr , sizeof(arr), 0, (struct sockaddr *)&si_other,&slen);
// -- Send all encrypted card to Alice
sendto(s, EncryptedDeckArr, sizeof(EncryptedDeckArr), 0, (struct sockaddr*)&si_other, slen); \
//--Recieved Bob's card from Alice
recvfrom(s,BobCardArr , sizeof(BobCardArr), 0, (struct sockaddr *)&si_other,&slen);
std::vector<int>BobCard(BobCardArr,BobCardArr +5);
//--Recieved Alice's card from Alice
recvfrom(s,AliceBobEncryptedDeckArr , sizeof(AliceBobEncryptedDeckArr), 0, (struct sockaddr *)&si_other,&slen);
std::vector<int>AliceBobEncryptedDeck(AliceBobEncryptedDeckArr,AliceBobEncryptedDeckArr +5);
cout<<"\n Recieved Bob Card \n";
cout<<"\n Recieved Alice Card \n";
//-- Decrypted Bob card with bob decryption key
cout<<"\n--Decrypt Bob cards--\n";
for(int i=0 ;i<5;i++)
{
int no = BobCard.at(i);
int DecryptNo =modPower(no,bD,primeNo);
BobDecryptedDeck.push_back(DecryptNo);
}
for(int i=0 ;i<5;i++)
{
cout<<BobDecryptedDeck.at(i)<<"\n";
}
//-- Decrypted Alice card with bob decryption key
cout<<"\n---Decrypt Alice cards by Bob---\n";
for(int i=0 ;i<5;i++)
{
int no = AliceBobEncryptedDeck.at(i);
int DecryptNo =modPower(no,bD,primeNo);
AliceBobDecryptedDeck.push_back(DecryptNo);
}
cout<< "\n Alice card decrypted by Bob key--\n";
for(int i=0 ;i<5;i++)
{
cout<<AliceBobDecryptedDeck.at(i)<<"\n";
}
std::copy(AliceBobDecryptedDeck.begin(), AliceBobDecryptedDeck.end(), AliceBobDecryptedDeckArr);
sendto(s, AliceBobDecryptedDeckArr, sizeof(AliceBobDecryptedDeckArr), 0, (struct sockaddr*)&si_other, slen);
// std::copy(deck.begin(), deck.end(),deckArr);\
// sendto(s, deckArr, sizeof(deckArr), 0, (struct sockaddr*)&si_other, slen);
cout<<"\n Bob's cards \n";
for (int i=0 ; i<5;i++)
{
int ab = BobDecryptedDeck.at(i)-48;
// cout<<"\n"<< ab;
cout<< deck.at(ab)<<"\n";
}
//Send Bob key for verification
sendto(s, bdec, sizeof(bdec), 0, (struct sockaddr*)&si_other, slen);
}
|
// Copyright (c) 2018 Mozart Alexander Louis. All rights reserved.
// Class
#include "action_utils.hxx"
Action* ActionUtils::fadeIn(const float delay, const float duration) {
ValueMap props;
props.emplace(__DELAY__, delay);
props.emplace(__DURATION__, duration);
return fadeInInternal(props);
}
Action* ActionUtils::fadeOut(const float delay, const float duration) {
ValueMap props;
props.emplace(__DELAY__, delay);
props.emplace(__DURATION__, duration);
return fadeOutInternal(props);
}
Action* ActionUtils::fadeTo(const float delay, const float duration, const int opacity, const float rate) {
ValueMap props;
props.emplace(__DELAY__, delay);
props.emplace(__DURATION__, duration);
props.emplace(__OPACITY__, opacity);
props.emplace(__RATE__, rate);
return fadeToInternal(props);
}
Action* ActionUtils::easeIn(float delay, float duration, float pos_x, float pos_y, float rate) {
ValueMap props;
props.emplace(__DELAY__, delay);
props.emplace(__DURATION__, duration);
props.emplace(__POSX__, pos_x);
props.emplace(__POSY__, pos_y);
props.emplace(__RATE__, rate);
return easeInInternal(props);
}
Action* ActionUtils::easeOut(float delay, float duration, float pos_x, float pos_y, float rate) {
ValueMap props;
props.emplace(__DELAY__, delay);
props.emplace(__DURATION__, duration);
props.emplace(__POSX__, pos_x);
props.emplace(__POSY__, pos_y);
props.emplace(__RATE__, rate);
return easeOutInternal(props);
}
Action* ActionUtils::easeInOut(float delay, float duration, float pos_x, float pos_y, float rate) {
ValueMap props;
props.emplace(__DELAY__, delay);
props.emplace(__DURATION__, duration);
props.emplace(__POSX__, pos_x);
props.emplace(__POSY__, pos_y);
props.emplace(__RATE__, rate);
return easeInOutInternal(props);
}
Action* ActionUtils::moveTo(float delay, float duration, float pos_x, float pos_y) {
ValueMap props;
props.emplace(__DELAY__, delay);
props.emplace(__DURATION__, duration);
props.emplace(__POSX__, pos_x);
props.emplace(__POSY__, pos_y);
return moveToInternal(props);
}
Action* ActionUtils::moveBy(float delay, float duration, float pos_x, float pos_y) {
ValueMap props;
props.emplace(__DELAY__, delay);
props.emplace(__DURATION__, duration);
props.emplace(__POSX__, pos_x);
props.emplace(__POSY__, pos_y);
return moveByInternal(props);
}
Action* ActionUtils::rotateTo(float delay, float duration, float degree, float rate) {
ValueMap props;
props.emplace(__DELAY__, delay);
props.emplace(__DURATION__, duration);
props.emplace(__DEGREE__, degree);
props.emplace(__RATE__, rate);
return rotateToInternal(props);
}
Action* ActionUtils::rotateBy(float delay, float duration, float degree, float rate) {
ValueMap props;
props.emplace(__DELAY__, delay);
props.emplace(__DURATION__, duration);
props.emplace(__DEGREE__, degree);
props.emplace(__RATE__, rate);
return rotateByInternal(props);
}
Action* ActionUtils::zoom(float delay, float duration, float scale, float rate) {
ValueMap props;
props.emplace(__DELAY__, delay);
props.emplace(__DURATION__, duration);
props.emplace(__SCALE__, scale);
props.emplace(__RATE__, rate);
return zoomInternal(props);
}
Action* ActionUtils::blink(float delay, float duration, int repeat) {
ValueMap props;
props.emplace(__DELAY__, delay);
props.emplace(__DURATION__, duration);
props.emplace(__REPEAT__, repeat);
return blinkInternal(props);
}
Action* ActionUtils::spawn(initializer_list<Action*> actions) {
Vector<FiniteTimeAction*> actions_vec;
for_each(actions.begin(), actions.end(), [&](const auto& action) {
if (action != nullptr) actions_vec.pushBack(toFiniteTimeAction(action));
});
return Spawn::create(actions_vec);
}
Action* ActionUtils::sequence(initializer_list<Action*> actions) {
Vector<FiniteTimeAction*> actions_vec;
for_each(actions.begin(), actions.end(), [&](const auto& action) {
if (action != nullptr) actions_vec.pushBack(toFiniteTimeAction(action));
});
return Sequence::create(actions_vec);
}
Action* ActionUtils::makeAction(ValueMap props) {
if (not props.at(__NAME__).isNull()) return createActionMap().at(props.at(__NAME__).asString())(props);
return nullptr;
}
FiniteTimeAction* ActionUtils::toFiniteTimeAction(Action* action) {
return dynamic_cast<FiniteTimeAction*>(action);
}
bool ActionUtils::isRunningAction(const Node* node) { return node->getNumberOfRunningActions() != 0; }
bool ActionUtils::isRunningAction(initializer_list<Node*> nodes) {
// for_each(nodes.begin(), nodes.end(), [&](const auto& node) { if (isRunningAction(node)) return true; });
for (const auto& node : nodes) {
if (isRunningAction(node)) return true;
}
return false;
}
Action* ActionUtils::fadeInInternal(ValueMap props) {
return Sequence::createWithTwoActions(DelayTime::create(props.at(__DELAY__).asFloat()),
FadeIn::create(props.at(__DURATION__).asFloat()));
}
Action* ActionUtils::fadeOutInternal(ValueMap props) {
return Sequence::createWithTwoActions(DelayTime::create(props.at(__DELAY__).asFloat()),
FadeOut::create(props.at(__DURATION__).asFloat()));
}
Action* ActionUtils::fadeToInternal(ValueMap props) {
return Sequence::createWithTwoActions(
DelayTime::create(props.at(__DELAY__).asFloat()),
EaseInOut::create(
FadeTo::create(props.at(__DURATION__).asFloat(), GLubyte(props.at(__OPACITY__).asFloat())),
props.at(__RATE__).asFloat()));
}
Action* ActionUtils::moveToInternal(ValueMap props) {
return MoveTo::create(
props.at(__DURATION__).asFloat(),
Globals::getScreenPosition(props.at(__POSX__).asFloat(), props.at(__POSY__).asFloat()));
}
Action* ActionUtils::moveByInternal(ValueMap props) {
return MoveBy::create(props.at(__DURATION__).asFloat(),
Vec2(props.at(__POSX__).asFloat(), props.at(__POSY__).asFloat()));
}
Action* ActionUtils::rotateToInternal(ValueMap props) {
return Sequence::createWithTwoActions(
DelayTime::create(props.at(__DELAY__).asFloat()),
EaseInOut::create(RotateTo::create(props.at(__DURATION__).asFloat(), props.at(__DEGREE__).asFloat()),
props.at(__RATE__).asFloat()));
}
Action* ActionUtils::rotateByInternal(ValueMap props) {
return Sequence::createWithTwoActions(
DelayTime::create(props.at(__DELAY__).asFloat()),
EaseInOut::create(RotateBy::create(props.at(__DURATION__).asFloat(), props.at(__DEGREE__).asFloat()),
props.at(__RATE__).asFloat()));
}
Action* ActionUtils::easeInInternal(ValueMap props) {
return Sequence::create(
DelayTime::create(props.at(__DELAY__).asFloat()),
EaseIn::create(dynamic_cast<MoveTo*>(moveToInternal(props)), props.at(__RATE__).asFloat()), nullptr);
}
Action* ActionUtils::easeOutInternal(ValueMap props) {
return Sequence::create(
DelayTime::create(props.at(__DELAY__).asFloat()),
EaseOut::create(dynamic_cast<MoveTo*>(moveToInternal(props)), props.at(__RATE__).asFloat()), nullptr);
}
Action* ActionUtils::easeInOutInternal(ValueMap props) {
return Sequence::create(
DelayTime::create(props.at(__DELAY__).asFloat()),
EaseInOut::create(dynamic_cast<MoveTo*>(moveToInternal(props)), props.at(__RATE__).asFloat()), nullptr);
}
Action* ActionUtils::zoomInternal(ValueMap props) {
return Sequence::create(
DelayTime::create(props.at(__DELAY__).asFloat()),
EaseInOut::create(ScaleTo::create(props.at(__DURATION__).asFloat(), props.at(__SCALE__).asFloat()),
props.at(__RATE__).asFloat()),
nullptr);
}
Action* ActionUtils::blinkInternal(ValueMap props) {
Vector<FiniteTimeAction*> actions;
actions.pushBack(DelayTime::create(props.at(__DELAY__).asFloat()));
actions.pushBack(FadeIn::create(0));
actions.pushBack(Blink::create(props.at(__DURATION__).asFloat(), props.at(__REPEAT__).asInt()));
return Sequence::create(actions);
}
Action* ActionUtils::sequenceInternal(ValueMap props) { return Sequence::create(createActionVector(props)); }
Action* ActionUtils::spawnInternal(ValueMap props) { return Spawn::create(createActionVector(props)); }
Action* ActionUtils::repeatInternal(ValueMap props) {
const auto repeat = dynamic_cast<ActionInterval*>(createActionVector(props).at(0));
return RepeatForever::create(repeat);
}
Vector<FiniteTimeAction*> ActionUtils::createActionVector(ValueMap& props) {
Vector<FiniteTimeAction*> actions_vec;
auto& actions_ref = props.at(__ACTIONS__).asValueVector();
for_each(actions_ref.begin(), actions_ref.end(),
[&](auto& action) { actions_vec.pushBack(toFiniteTimeAction(makeAction(action.asValueMap()))); });
return actions_vec;
}
unordered_map<string, function<Action*(ValueMap)>> ActionUtils::createActionMap() {
// Create an actionMap instance and add all the values to it
unordered_map<string, function<Action*(ValueMap)>> action_map;
action_map.emplace("fadein", fadeInInternal);
action_map.emplace("fadeout", fadeOutInternal);
action_map.emplace("fadeto", fadeToInternal);
action_map.emplace("moveto", moveToInternal);
action_map.emplace("moveby", moveByInternal);
action_map.emplace("rotateTo", rotateToInternal);
action_map.emplace("rotateBy", rotateByInternal);
action_map.emplace("easein", easeInInternal);
action_map.emplace("easeout", easeOutInternal);
action_map.emplace("easeinout", easeInOutInternal);
action_map.emplace("blink", blinkInternal);
action_map.emplace("sequence", sequenceInternal);
action_map.emplace("spawn", spawnInternal);
action_map.emplace("repeat", repeatInternal);
action_map.emplace("zoom", zoomInternal);
// Return ActionMap
return action_map;
}
|
//算法:DP/排序/贪心
//先跑一遍01背包
//以题目得分为权值,剩余时间为容量.
//跑完后,
//循环找到能够使 分数到达k 所花费的最小时间
//再将刷题时间升序排列,
//找到在 剩剩余时间 内能完成的个数即可
#include<cstdio>
#include<algorithm>
using namespace std;
int n,m,k,r1;
int r2,ans;
int t1[15],t2[15],s[15];
int f[150];
int main()
{
scanf("%d%d%d%d",&n,&m,&k,&r1);
for(int i=1;i<=n;i++) scanf("%d",&t1[i]);//输入
for(int i=1;i<=m;i++) scanf("%d",&t2[i]);
for(int i=1;i<=m;i++) scanf("%d",&s[i]);
sort(t1+1,t1+n+1);
for(int i=1;i<=m;i++)//01背包,找到 使 分数到达k 所花费的最小时间
for(int j=r1;j>=t2[i];j--)
f[j]=max(f[j],f[j-t2[i]]+s[i]);
for(int i=1;i<=r1;i++)
if(f[i]>=k)
{
r2=r1-i;
break;
}
for(int i=1;i<=n;i++)//找个数
if(r2>=t1[i]) ans++,r2-=t1[i];
else break;
printf("%d",ans);
}
|
// -------------------------------------------------------------------------------
//
// DXライブラリアーカイバ
//
// Creator : 山田 巧
// Creation Date : 2003/09/11
// Version : 1.02
//
// -------------------------------------------------------------------------------
// 多重インクルード防止用定義
#ifndef __DXARCHIVE_VER6
#define __DXARCHIVE_VER6
// include --------------------------------------
#include <stdio.h>
#include <tchar.h>
// define ---------------------------------------
// データ型定義
#ifndef u64
#define u64 unsigned __int64
#endif
#ifndef u32
#define u32 unsigned int
#endif
#ifndef u16
#define u16 unsigned short
#endif
#ifndef u8
#define u8 unsigned char
#endif
#ifndef s64
#define s64 signed __int64
#endif
#ifndef s32
#define s32 signed int
#endif
#ifndef s16
#define s16 signed short
#endif
#ifndef s8
#define s8 signed char
#endif
#ifndef f64
#define f64 double
#endif
#ifndef TRUE
#define TRUE (1)
#endif
#ifndef FALSE
#define FALSE (0)
#endif
#ifndef NULL
#define NULL (0)
#endif
#define DXA_HEAD_VER6 *((u16 *)"DX") // ヘッダ
#define DXA_VER_VER6 (0x0006) // バージョン
#define DXA_BUFFERSIZE_VER6 (0x1000000) // アーカイブ作成時に使用するバッファのサイズ
#define DXA_KEYSTR_LENGTH_VER6 (12) // 鍵文字列の長さ
/*
バージョンごとの違い
0x0002 DARC_FILEHEAD に PressDataSize を追加
0x0004 DARC_HEAD に CodePage を追加
0x0005 暗号化処理を一部変更
0x0006 64bit化
*/
/*
データマップ
DARC_HEAD
ファイル実データ
ファイル名テーブル
DARC_FILEHEAD テーブル
DARC_DIRECTORY テーブル
*/
/*
ファイル名のデータ形式
2byte:文字列の長さ(バイトサイズ÷4)
2byte:文字列のパリティデータ(全ての文字の値を足したもの)
英字は大文字に変換されたファイル名のデータ(4の倍数のサイズ)
英字が大文字に変換されていないファイル名のデータ
*/
// struct ---------------------------------------
#pragma pack(push)
#pragma pack(1)
// アーカイブデータの最初のヘッダ
typedef struct tagDARC_HEAD_VER6
{
u16 Head; // ヘッダ
u16 Version; // バージョン
u32 HeadSize; // ヘッダ情報の DARC_HEAD を抜いた全サイズ
u64 DataStartAddress; // 最初のファイルのデータが格納されているデータアドレス(ファイルの先頭アドレスをアドレス0とする)
u64 FileNameTableStartAddress; // ファイル名テーブルの先頭アドレス(ファイルの先頭アドレスをアドレス0とする)
u64 FileTableStartAddress; // ファイルテーブルの先頭アドレス(メンバ変数 FileNameTableStartAddress のアドレスを0とする)
u64 DirectoryTableStartAddress; // ディレクトリテーブルの先頭アドレス(メンバ変数 FileNameTableStartAddress のアドレスを0とする)
// アドレス0から配置されている DARC_DIRECTORY 構造体がルートディレクトリ
u64 CodePage; // ファイル名に使用しているコードページ番号
} DARC_HEAD_VER6;
// ファイルの時間情報
typedef struct tagDARC_FILETIME_VER6
{
u64 Create; // 作成時間
u64 LastAccess; // 最終アクセス時間
u64 LastWrite; // 最終更新時間
} DARC_FILETIME_VER6;
// ファイル格納情報
typedef struct tagDARC_FILEHEAD_VER6
{
u64 NameAddress; // ファイル名が格納されているアドレス( ARCHIVE_HEAD構造体 のメンバ変数 FileNameTableStartAddress のアドレスをアドレス0とする)
u64 Attributes; // ファイル属性
DARC_FILETIME_VER6 Time; // 時間情報
u64 DataAddress; // ファイルが格納されているアドレス
// ファイルの場合:DARC_HEAD構造体 のメンバ変数 DataStartAddress が示すアドレスをアドレス0とする
// ディレクトリの場合:DARC_HEAD構造体 のメンバ変数 DirectoryTableStartAddress のが示すアドレスをアドレス0とする
u64 DataSize; // ファイルのデータサイズ
u64 PressDataSize; // 圧縮後のデータのサイズ( 0xffffffffffffffff:圧縮されていない ) ( Ver0x0002 で追加された )
} DARC_FILEHEAD_VER6;
// ディレクトリ格納情報
typedef struct tagDARC_DIRECTORY_VER6
{
u64 DirectoryAddress; // 自分の DARC_FILEHEAD が格納されているアドレス( DARC_HEAD 構造体 のメンバ変数 FileTableStartAddress が示すアドレスをアドレス0とする)
u64 ParentDirectoryAddress; // 親ディレクトリの DARC_DIRECTORY が格納されているアドレス( DARC_HEAD構造体 のメンバ変数 DirectoryTableStartAddress が示すアドレスをアドレス0とする)
u64 FileHeadNum; // ディレクトリ内のファイルの数
u64 FileHeadAddress; // ディレクトリ内のファイルのヘッダ列が格納されているアドレス( DARC_HEAD構造体 のメンバ変数 FileTableStartAddress が示すアドレスをアドレス0とする)
} DARC_DIRECTORY_VER6;
#pragma pack(pop)
// class ----------------------------------------
// アーカイブクラス
class DXArchive_VER6
{
public:
// 日付の比較結果
enum DATE_RESULT
{
DATE_RESULT_LEFTNEW = 0, // 第一引数が新しい
DATE_RESULT_RIGHTNEW, // 第二引数が新しい
DATE_RESULT_DRAW, // 日付は同じ
};
DXArchive_VER6(TCHAR* ArchivePath = NULL);
~DXArchive_VER6();
static int EncodeArchive(TCHAR* OutputFileName, TCHAR** FileOrDirectoryPath, int FileNum, bool Press = false, const char* KeyString = NULL); // アーカイブファイルを作成する
static int EncodeArchiveOneDirectory(TCHAR* OutputFileName, TCHAR* FolderPath, bool Press = false, const char* KeyString = NULL); // アーカイブファイルを作成する(ディレクトリ一個だけ)
static int DecodeArchive(TCHAR* ArchiveName, const TCHAR* OutputPath, const char* KeyString = NULL); // アーカイブファイルを展開する
int OpenArchiveFile(const TCHAR* ArchivePath, const char* KeyString = NULL); // アーカイブファイルを開く( 0:成功 -1:失敗 )
int OpenArchiveFileMem(const TCHAR* ArchivePath, const char* KeyString = NULL); // アーカイブファイルを開き最初にすべてメモリ上に読み込んでから処理する( 0:成功 -1:失敗 )
int OpenArchiveMem(void* ArchiveImage, s64 ArchiveSize, const char* KeyString = NULL); // メモリ上にあるアーカイブファイルイメージを開く( 0:成功 -1:失敗 )
int CloseArchiveFile(void); // アーカイブファイルを閉じる
s64 LoadFileToMem(const TCHAR* FilePath, void* Buffer, u64 BufferLength); // アーカイブファイル中の指定のファイルをメモリに読み込む( -1:エラー 0以上:ファイルサイズ )
s64 GetFileSize(const TCHAR* FilePath); // アーカイブファイル中の指定のファイルをサイズを取得する( -1:エラー )
int GetFileInfo(const TCHAR* FilePath, u64* PositionP, u64* SizeP); // アーカイブファイル中の指定のファイルのファイル内の位置とファイルの大きさを得る( -1:エラー )
void* GetFileImage(void); // アーカイブファイルをメモリに読み込んだ場合のファイルイメージが格納されている先頭アドレスを取得する( メモリから開いている場合のみ有効、圧縮している場合は、圧縮された状態のデータが格納されているので注意 )
class DXArchiveFile_VER6* OpenFile(const TCHAR* FilePath); // アーカイブファイル中の指定のファイルを開き、ファイルアクセス用オブジェクトを作成する( ファイルから開いている場合のみ有効 )
void* LoadFileToCash(const TCHAR* FilePath); // アーカイブファイル中の指定のファイルを、クラス内のキャッシュバッファに読み込む
void* GetCash(void); // キャッシュバッファのアドレスを取得する
int ClearCash(void); // キャッシュバッファを開放する
int ChangeCurrentDir(const TCHAR* DirPath); // アーカイブ内のディレクトリパスを変更する( 0:成功 -1:失敗 )
int GetCurrentDir(TCHAR* DirPathBuffer, int BufferLength); // アーカイブ内のカレントディレクトリパスを取得する
// 以下は割と内部で使用
static void fwrite64(void* Data, s64 Size, FILE* fp); // 標準ストリームにデータを書き込む( 64bit版 )
static void fread64(void* Buffer, s64 Size, FILE* fp); // 標準ストリームからデータを読み込む( 64bit版 )
static void NotConv(void* Data, s64 Size); // データを反転させる関数
static void NotConvFileWrite(void* Data, s64 Size, FILE* fp); // データを反転させてファイルに書き出す関数
static void NotConvFileRead(void* Data, s64 Size, FILE* fp); // データを反転させてファイルから読み込む関数
static void KeyCreate(const char* Source, unsigned char* Key); // 鍵文字列を作成
static void KeyConv(void* Data, s64 Size, s64 Position, unsigned char* Key); // 鍵文字列を使用して Xor 演算( Key は必ず DXA_KEYSTR_LENGTH の長さがなければならない )
static void KeyConvFileWrite(void* Data, s64 Size, FILE* fp, unsigned char* Key, s64 Position = -1); // データを鍵文字列を使用して Xor 演算した後ファイルに書き出す関数( Key は必ず DXA_KEYSTR_LENGTH の長さがなければならない )
static void KeyConvFileRead(void* Data, s64 Size, FILE* fp, unsigned char* Key, s64 Position = -1); // ファイルから読み込んだデータを鍵文字列を使用して Xor 演算する関数( Key は必ず DXA_KEYSTR_LENGTH の長さがなければならない )
static DATE_RESULT DateCmp(DARC_FILETIME_VER6* date1, DARC_FILETIME_VER6* date2); // どちらが新しいかを比較する
static int Encode(void* Src, u32 SrcSize, void* Dest); // データを圧縮する( 戻り値:圧縮後のデータサイズ )
static int Decode(void* Src, void* Dest); // データを解凍する( 戻り値:解凍後のデータサイズ )
DARC_DIRECTORY_VER6* GetCurrentDirectoryInfo(void); // アーカイブ内のカレントディレクトリの情報を取得する
DARC_FILEHEAD_VER6* GetFileInfo(const TCHAR* FilePath); // ファイルの情報を得る
inline DARC_HEAD_VER6* GetHeader(void) { return &Head; }
inline u8* GetKey(void) { return Key; }
inline FILE* GetFilePointer(void) { return fp; }
inline u8* GetNameP(void) { return NameP; }
protected:
FILE* fp; // アーカイブファイルのポインタ
u8* HeadBuffer; // ヘッダーバッファー
u8* FileP, * DirP, * NameP; // 各種テーブル(ファイルヘッダ情報テーブル、ディレクトリ情報テーブル、名前情報テーブル)へのポインタ
DARC_DIRECTORY_VER6* CurrentDirectory; // カレントディレクトリデータへのポインタ
void* CashBuffer; // 読み込んだファイルデータを一時的に保存しておくバッファ
u64 CashBufferSize; // キャッシュバッファに確保しているメモリ容量
bool MemoryOpenFlag; // メモリ上のファイルを開いているか、フラグ
bool UserMemoryImageFlag; // ユーザーが展開したメモリイメージを使用しているか、フラグ
s64 MemoryImageSize; // メモリ上のファイルから開いていた場合のイメージのサイズ
u8 Key[DXA_KEYSTR_LENGTH_VER6]; // 鍵文字列
DARC_HEAD_VER6 Head; // アーカイブのヘッダ
// サイズ保存用構造体
typedef struct tagSIZESAVE
{
u64 DataSize; // 実データの総量
u64 NameSize; // ファイル名データの総量
u64 DirectorySize; // ディレクトリデータの総量
u64 FileSize; // ファイルプロパティデータの総量
} SIZESAVE;
// ファイル名検索用データ構造体
typedef struct tagSEARCHDATA
{
u8 FileName[1024];
u16 Parity;
u16 PackNum;
} SEARCHDATA;
static int DirectoryEncode(TCHAR* DirectoryName, u8* NameP, u8* DirP, u8* FileP, DARC_DIRECTORY_VER6* ParentDir, SIZESAVE* Size, int DataNumber, FILE* DestP, void* TempBuffer, bool Press, unsigned char* Key); // 指定のディレクトリにあるファイルをアーカイブデータに吐き出す
static int DirectoryDecode(u8* NameP, u8* DirP, u8* FileP, DARC_HEAD_VER6* Head, DARC_DIRECTORY_VER6* Dir, FILE* ArcP, unsigned char* Key); // 指定のディレクトリデータにあるファイルを展開する
static int StrICmp(const TCHAR* Str1, const TCHAR* Str2); // 比較対照の文字列中の大文字を小文字として扱い比較する( 0:等しい 1:違う )
static int ConvSearchData(SEARCHDATA* Dest, const TCHAR* Src, int* Length); // 文字列を検索用のデータに変換( ヌル文字か \ があったら終了 )
static int AddFileNameData(const TCHAR* FileName, u8* FileNameTable); // ファイル名データを追加する( 戻り値は使用したデータバイト数 )
static TCHAR* GetOriginalFileName(u8* FileNameTable); // ファイル名データから元のファイル名の文字列を取得する
static int GetDirectoryFilePath(const TCHAR* DirectoryPath, TCHAR* FilePathBuffer = NULL); // ディレクトリ内のファイルのパスを取得する( FilePathBuffer は一ファイルに付き256バイトの容量が必要 )
int ChangeCurrentDirectoryFast(SEARCHDATA* SearchData); // アーカイブ内のディレクトリパスを変更する( 0:成功 -1:失敗 )
int ChangeCurrentDirectoryBase(const TCHAR* DirectoryPath, bool ErrorIsDirectoryReset, SEARCHDATA* LastSearchData = NULL); // アーカイブ内のディレクトリパスを変更する( 0:成功 -1:失敗 )
int DirectoryKeyConv(DARC_DIRECTORY_VER6* Dir); // 指定のディレクトリデータの暗号化を解除する( 丸ごとメモリに読み込んだ場合用 )
// 2バイト文字か調べる( TRUE:2バイト文字 FALSE:1バイト文字 )
inline static int CheckMultiByteChar(const TCHAR* Buf)
{
return ((unsigned char)*Buf >= 0x81 && (unsigned char)*Buf <= 0x9F) || ((unsigned char)*Buf >= 0xE0 && (unsigned char)*Buf <= 0xFC);
}
// ファイル名も一緒になっていると分かっているパス中からファイルパスとディレクトリパスを分割する
// フルパスである必要は無い
static int GetFilePathAndDirPath(TCHAR* Src, TCHAR* FilePath, TCHAR* DirPath);
};
// アーカイブされたファイルのアクセス用のクラス
class DXArchiveFile_VER6
{
protected:
DARC_FILEHEAD_VER6* FileData; // ファイルデータへのポインタ
DXArchive_VER6* Archive; // アーカイブクラスへのポインタ
void* DataBuffer; // メモリにデータを展開した際のバッファのポインタ
int EOFFlag; // EOFフラグ
u64 FilePoint; // ファイルポインタ
public:
DXArchiveFile_VER6(DARC_FILEHEAD_VER6* FileHead, DXArchive_VER6* Archive);
~DXArchiveFile_VER6();
s64 Read(void* Buffer, s64 ReadLength); // ファイルの内容を読み込む
s64 Seek(s64 SeekPoint, s64 SeekMode); // ファイルポインタを変更する
s64 Tell(void); // 現在のファイルポインタを得る
s64 Eof(void); // ファイルの終端に来ているか、のフラグを得る
s64 Size(void); // ファイルのサイズを取得する
inline DARC_FILEHEAD_VER6* GetFileData(void) { return FileData; }
};
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2005-2010 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser.
** It may not be distributed under any circumstances.
**
** Peter Krefting
*/
#include "core/pch.h"
#include "modules/prefs/prefs_module.h"
#include "modules/prefs/init/delayed_init.h"
#include "modules/prefs/prefsmanager/prefsmanager.h"
#include "modules/prefs/prefsmanager/opprefscollection.h"
#include "modules/prefs/prefsmanager/collections/pc_core.h"
#include "modules/prefs/util/upgrade.h"
#include "modules/display/color.h"
#include "modules/hardcore/mem/mem_man.h"
#include "modules/pi/OpSystemInfo.h"
PrefsModule::PrefsModule()
:
#ifdef PREFS_DELAYED_INIT_NEEDED
m_delayed_init(NULL),
#endif
m_prefs_manager(NULL)
, m_pcapp(NULL)
, m_pccore(NULL)
, m_pcdisplay(NULL)
, m_pcdoc(NULL)
, m_pcparsing(NULL)
, m_pcfiles(NULL)
, m_pcfontscolors(NULL)
, m_pcjs(NULL)
#ifdef DATABASE_MODULE_MANAGER_SUPPORT
, m_pcdatabase(NULL)
#endif //DATABASE_MODULE_MANAGER_SUPPORT
#ifdef M2_SUPPORT
, m_pcm2(NULL)
#endif
#ifdef PREFS_HAVE_MAC
, m_pcmacos(NULL)
#endif
#ifdef PREFS_HAVE_MSWIN
, m_pcmswin(NULL)
#endif
#ifdef PREFS_HAVE_COREGOGI
, m_pccoregogi(NULL)
#endif
, m_pcnet(NULL)
#ifdef _PRINT_SUPPORT_
, m_pcprint(NULL)
#endif
#if defined SCOPE_SUPPORT || defined SUPPORT_DEBUGGING_SHELL
, m_pctools(NULL)
#endif
#if defined GEOLOCATION_SUPPORT
, m_pcgeolocation(NULL)
#endif
#ifdef PREFS_HAVE_DESKTOP_UI
, m_pcui(NULL)
#endif
#ifdef PREFS_HAVE_UNIX
, m_pcunix(NULL)
#endif
#ifdef WEBSERVER_SUPPORT
, m_pcwebserver(NULL)
#endif
#ifdef SUPPORT_DATA_SYNC
, m_pcsync(NULL)
#endif
#ifdef PREFS_HAVE_OPERA_ACCOUNT
, m_pcopera_account(NULL)
#endif
#ifdef DOM_JIL_API_SUPPORT
, m_pcjil(NULL)
#endif
, m_collections(NULL)
{
}
void PrefsModule::InitL(const OperaInitInfo &info)
{
PrefsInitInfo prefsinfo(&info);
LEAVE_IF_FATAL(g_op_system_info->GetUserLanguages(&prefsinfo.m_user_languages));
OP_ASSERT(!prefsinfo.m_user_languages.IsEmpty());
m_collections = OP_NEW_L(Head, ());
#ifdef PREFS_READ
m_prefs_manager = OP_NEW_L(class PrefsManager, (info.prefs_reader));
#else
m_prefs_manager = OP_NEW_L(class PrefsManager, (NULL));
#endif
m_prefs_manager->ConstructL();
OP_ASSERT(!m_collections->Empty()); // Initialization failed, miserably
m_prefs_manager->ReadAllPrefsL(&prefsinfo);
#if defined UPGRADE_SUPPORT && defined PREFS_WRITE
// Check if an upgrade is needed
int lastseen = m_pccore->GetIntegerPref(PrefsCollectionCore::PreferenceUpgrade);
if (lastseen < PREFSUPGRADE_CURRENT)
{
int newseen = PrefsUpgrade::Upgrade(info.prefs_reader, lastseen);
if (newseen > lastseen)
{
m_pccore->WriteIntegerL(PrefsCollectionCore::PreferenceUpgrade, newseen);
m_prefs_manager->CommitL();
}
}
#endif
// ColorManager now need to read the color settings
OP_ASSERT(colorManager); // Need to have display module initialized
colorManager->ReadColors();
// StyleManager now need to read the font settings
OP_ASSERT(styleManager); // Need to have display module initialized
styleManager->OnPrefsInitL();
// Initialize MemoryManager cache sizes
g_memory_manager->ApplyRamCacheSettings();
#ifdef PREFS_READ
// Flush the ini file, we're done with it now
info.prefs_reader->Flush();
#endif
#ifdef PREFS_DELAYED_INIT_NEEDED
// Set up delayed initialization. Destroys itself when done.
m_delayed_init = OP_NEW_L(PrefsDelayedInit, ());
m_delayed_init->StartL();
#endif
}
void PrefsModule::Destroy()
{
#ifdef PREFS_DELAYED_INIT_NEEDED
OP_DELETE(m_delayed_init); // Should usually be dead already.
m_delayed_init = NULL;
#endif
OP_DELETE(m_prefs_manager);
m_prefs_manager = NULL;
// Make sure everything was cleaned up properly by the PrefsManager
// destructor.
OP_ASSERT(!m_pcapp);
OP_ASSERT(!m_pccore);
OP_ASSERT(!m_pcdisplay);
OP_ASSERT(!m_pcdoc);
OP_ASSERT(!m_pcparsing);
OP_ASSERT(!m_pcfiles);
OP_ASSERT(!m_pcfontscolors);
#if defined GEOLOCATION_SUPPORT
OP_ASSERT(!m_pcgeolocation);
#endif
OP_ASSERT(!m_pcjs);
#ifdef DATABASE_MODULE_MANAGER_SUPPORT
OP_ASSERT(!m_pcdatabase);
#endif //DATABASE_MODULE_MANAGER_SUPPORT
#ifdef M2_SUPPORT
OP_ASSERT(!m_pcm2);
#endif
#ifdef PREFS_HAVE_MAC
OP_ASSERT(!m_pcmacos);
#endif
#ifdef PREFS_HAVE_MSWIN
OP_ASSERT(!m_pcmswin);
#endif
#ifdef PREFS_HAVE_COREGOGI
OP_ASSERT(!m_pccoregogi);
#endif
OP_ASSERT(!m_pcnet);
#ifdef _PRINT_SUPPORT_
OP_ASSERT(!m_pcprint);
#endif
#if defined SCOPE_SUPPORT || defined SUPPORT_DEBUGGING_SHELL
OP_ASSERT(!m_pctools);
#endif
#ifdef PREFS_HAVE_DESKTOP_UI
OP_ASSERT(!m_pcui);
#endif
#ifdef PREFS_HAVE_UNIX
OP_ASSERT(!m_pcunix);
#endif
#ifdef WEBSERVER_SUPPORT
OP_ASSERT(!m_pcwebserver);
#endif
#ifdef SUPPORT_DATA_SYNC
OP_ASSERT(!m_pcsync);
#endif
#ifdef PREFS_HAVE_OPERA_ACCOUNT
OP_ASSERT(!m_pcopera_account);
#endif
OP_ASSERT(m_collections == 0 || m_collections->Empty());
OP_DELETE(m_collections);
m_collections = NULL;
}
OpPrefsCollection *PrefsModule::GetFirstCollection()
{
return static_cast<OpPrefsCollection *>(m_collections->First());
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style:"stroustrup" -*-
*
* 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.
*/
#include "core/pch.h"
#include "modules/dom/src/domhtml/htmlmicrodata.h"
#include "modules/dom/src/domenvironmentimpl.h"
#include "modules/dom/src/domhtml/htmlelem.h"
#include "modules/dom/src/domcore/domdoc.h"
#include "modules/dom/src/opatom.h"
#include "modules/logdoc/htm_elm.h"
#include "modules/logdoc/logdoc.h"
#include "modules/logdoc/stringtokenlist_attribute.h"
#include "modules/logdoc/link.h"
//---
// JSON-ification.
//---
/* static */ OP_STATUS
MicrodataTraverse::ExtractMicrodataToJSON(HTML_Element* helm,
FramesDocument* frm_doc,
TempBuffer& result_json)
{
if (!frm_doc || !frm_doc->GetDOMEnvironment() || !frm_doc->GetESRuntime() || !helm)
return OpStatus::ERR;
JSONSerializer serializer(result_json);
RETURN_IF_ERROR(serializer.EnterObject());
RETURN_IF_ERROR(serializer.AttributeName(UNI_L("items")));
RETURN_IF_ERROR(serializer.EnterArray());
OpVector<HTML_Element> iter_result_properties;
if (helm->IsToplevelMicrodataItem())
RETURN_IF_ERROR(TraverseAndAppendJSON(helm, *frm_doc, iter_result_properties, serializer));
RETURN_IF_ERROR(serializer.LeaveArray());
RETURN_IF_ERROR(serializer.LeaveObject());
return OpStatus::OK;
}
/* static */ OP_STATUS
MicrodataTraverse::ExtractMicrodataToJSONFromSelection(HTML_Element* start_helm,
HTML_Element* end_helm,
FramesDocument* frm_doc,
TempBuffer& result_json)
{
if (!frm_doc || !frm_doc->GetDOMEnvironment() || !frm_doc->GetESRuntime() || !start_helm || !end_helm)
return OpStatus::ERR;
JSONSerializer serializer(result_json);
RETURN_IF_ERROR(serializer.EnterObject());
RETURN_IF_ERROR(serializer.AttributeName(UNI_L("items")));
RETURN_IF_ERROR(serializer.EnterArray());
OpVector<HTML_Element> iter_result_properties;
// If an interval (selection) is processed, check whether start element is
// inside a toplevel Microdata item (TMI). If it is, then add Microdata
// properties of such parent TMI to results. (But beware: get all
// Microdata properties of the parent TMI, but don't transgress selection
// limits, and don't get Microdata properties of TMIs, which are children
// of the parent in HTML tree. In other words, when adding TMI, which is
// parent of beginning of selection, don't add Microdata properties of
// TMIs, which are siblings in the HTML tree of the beginning of selection,
// to results).
//
// To make things more complex, search for TMIs all the way up from
// beginning of selection to to the document root. The order of Microdata
// properties of parent TMIs in resulting JSON must be from top of the
// document, to bottom.
{
OpVector<HTML_Element> parents;
HTML_Element* iter_parent = start_helm;
while (iter_parent)
{
if (iter_parent->IsToplevelMicrodataItem())
RETURN_IF_ERROR(parents.Add(iter_parent));
iter_parent = iter_parent->ParentActual();
}
for (int i = parents.GetCount() - 1; i >= 0; i--)
RETURN_IF_ERROR(TraverseAndAppendJSON(parents.Get(i), *frm_doc, iter_result_properties, serializer));
}
HTML_Element* iter_subtree = start_helm;
do
{
if (iter_subtree->IsToplevelMicrodataItem())
RETURN_IF_ERROR(TraverseAndAppendJSON(iter_subtree, *frm_doc, iter_result_properties, serializer));
iter_subtree = iter_subtree->NextActual();
} while (iter_subtree && iter_subtree != end_helm);
RETURN_IF_ERROR(serializer.LeaveArray());
RETURN_IF_ERROR(serializer.LeaveObject());
return OpStatus::OK;
}
struct MicrodataNameValueJSON
{
// Name of Microdata property.
const uni_char* name;
// JSON-ified value of Microdata property, including quotation marks,
// separated by commas, sorted in order of appearance.
TempBuffer value_json;
};
/**
* Holds collection of pairs (Microdata property name, JSON-ified Microdata
* property value). Uses MicrodataNameValueJSON.
**/
class MicrodataPropertiesJSONData
{
public:
~MicrodataPropertiesJSONData() { properties_by_name.DeleteAll(); }
/**
* Add the value to property named name.
*
* @param[in] name Name of the property.
*
* @param[in] value New value of the property. One property can have many
* values.
*
* @param[in] plain_text If TRUE, insert value as is. Otherwise, escape
* special characters found in value.
*
* @return OK or OOM.
**/
OP_STATUS Add(const uni_char* name, const uni_char* value, BOOL plain_text);
UINT32 GetCount() { return properties_by_name.GetCount(); }
MicrodataNameValueJSON* Get(int i) { return properties_by_name.Get(i); }
private:
OpVector<MicrodataNameValueJSON> properties_by_name;
/**< Preserve properties' order by names. */
};
OP_STATUS
MicrodataPropertiesJSONData::Add(const uni_char* name, const uni_char* value_to_add, BOOL plain_text)
{
for (UINT32 i = 0; i < properties_by_name.GetCount(); i++)
{
MicrodataNameValueJSON* ith_data = properties_by_name.Get(i);
if (uni_str_eq(ith_data->name, name))
{
RETURN_IF_ERROR(ith_data->value_json.Append(UNI_L(",")));
if (plain_text)
return ith_data->value_json.Append(value_to_add);
else
{
JSONSerializer serializer(ith_data->value_json);
return serializer.String(value_to_add);
}
}
}
OpAutoPtr<MicrodataNameValueJSON> new_data(OP_NEW(MicrodataNameValueJSON, ()));
if (!new_data.get())
return OpStatus::ERR_NO_MEMORY;
new_data->name = name;
if (plain_text)
RETURN_IF_ERROR(new_data->value_json.Append(value_to_add));
else
{
JSONSerializer serializer(new_data->value_json);
RETURN_IF_ERROR(serializer.String(value_to_add));
}
return properties_by_name.Add(new_data.release());
}
OP_STATUS
MicrodataTraverse::ToJSON(JSONSerializer& result_json_serializer, FramesDocument& frm_doc)
{
OpPointerSet<HTML_Element> jsonified_items_in_path;
BOOL item_loop_found = FALSE;
return ToJSON(result_json_serializer, frm_doc, jsonified_items_in_path, item_loop_found);
}
OP_STATUS
MicrodataTraverse::ToJSON(
JSONSerializer& serializer,
FramesDocument& frm_doc,
OpPointerSet<HTML_Element>& jsonified_items_in_path,
BOOL& item_loop_found)
{
// Exclude loops of Microdata items.
if (jsonified_items_in_path.Contains(m_root_element))
{
item_loop_found = TRUE;
return OpStatus::OK;
}
item_loop_found = FALSE;
RETURN_IF_ERROR(jsonified_items_in_path.Add(m_root_element));
RETURN_IF_ERROR(serializer.EnterObject());
// "typename" : "itemtype_attr"
const uni_char* itemtype = m_root_element->GetStringAttr(ATTR_ITEMTYPE);
if (itemtype)
{
RETURN_IF_ERROR(serializer.AttributeName(UNI_L("type")));
RETURN_IF_ERROR(serializer.String(itemtype));
}
// "idname" : "itemid_attr"
const uni_char* itemid = m_root_element->GetStringAttr(ATTR_ITEMID);
if (itemid)
{
RETURN_IF_ERROR(serializer.AttributeName(UNI_L("id")));
RETURN_IF_ERROR(serializer.String(itemid));
}
// Retrieve Microdata properties and group them by properties' names.
MicrodataPropertiesJSONData properties_json;
RETURN_IF_ERROR(CrawlMicrodataProperties());
TempBuffer local_buffer; // Used as subitem_json or operating buffer.
for (UINT32 i_property = 0; i_property < m_root_properties_result.GetCount(); i_property++)
{
HTML_Element* ith_property_helm = m_root_properties_result.Get(i_property);
const StringTokenListAttribute* ith_property_names = ith_property_helm->GetItemPropAttribute();
if (!ith_property_names->GetTokenCount())
continue;
const uni_char* property_value_string;
const uni_char* is_subitem = ith_property_helm->GetStringAttr(ATTR_ITEMSCOPE);
if (is_subitem)
{
// Recursively get JSON-ified properties which are subitems.
OpVector<HTML_Element> ith_properties;
BOOL item_loop_found = FALSE;
local_buffer.Clear();
JSONSerializer local_json_serializer(local_buffer);
MicrodataTraverse subitem_mdt(ith_property_helm, ith_properties);
RETURN_IF_ERROR(subitem_mdt.ToJSON(local_json_serializer, frm_doc, jsonified_items_in_path, item_loop_found));
if (item_loop_found)
property_value_string = UNI_L("\"ERROR\"");
else
property_value_string = local_buffer.GetStorage();
}
else
{
local_buffer.Clear();
property_value_string = ith_property_helm->GetMicrodataItemValue(local_buffer, &frm_doc);
}
const OpAutoVector<OpString>& names = ith_property_names->GetTokens();
for (UINT32 jth_name = 0; jth_name < names.GetCount(); jth_name++)
properties_json.Add(names.Get(jth_name)->CStr(), property_value_string, is_subitem ? TRUE : FALSE);
}
// JSON-ify fetched properties.
// "properties":{"property_name" : ["value1", "value12", ...], "property_name2" : ["value12", "value2", ...], ...}}
RETURN_IF_ERROR(serializer.AttributeName(UNI_L("properties")));
RETURN_IF_ERROR(serializer.EnterObject());
for (UINT32 i_property_name = 0; i_property_name < properties_json.GetCount(); i_property_name++)
{
MicrodataNameValueJSON* ith_property = properties_json.Get(i_property_name);
RETURN_IF_ERROR(serializer.AttributeName(ith_property->name));
RETURN_IF_ERROR(serializer.EnterArray());
RETURN_IF_ERROR(serializer.PlainString(ith_property->value_json.GetStorage()));
RETURN_IF_ERROR(serializer.LeaveArray());
}
RETURN_IF_ERROR(serializer.LeaveObject());
RETURN_IF_ERROR(serializer.LeaveObject());
jsonified_items_in_path.Remove(m_root_element);
return OpStatus::OK;
}
/* static */ OP_STATUS
MicrodataTraverse::TraverseAndAppendJSON(HTML_Element* helm_microdata_item,
FramesDocument& frm_doc, OpVector<HTML_Element>& result_properties,
JSONSerializer& result_json_serializer)
{
result_properties.Clear();
MicrodataTraverse mdt(helm_microdata_item, result_properties);
RETURN_IF_ERROR(mdt.ToJSON(result_json_serializer, frm_doc));
return OpStatus::OK;
}
//---
// Collections.
//---
/* static */ OP_STATUS
DOM_NodeCollectionMicrodataProperties::Make(DOM_NodeCollection *&collection, DOM_EnvironmentImpl *environment, DOM_Node *root)
{
DOM_Runtime *runtime = environment->GetDOMRuntime();
if (OpStatus::IsMemoryError(DOMSetObjectRuntime(collection = OP_NEW(DOM_NodeCollectionMicrodataProperties, ()), runtime)))
{
collection = NULL;
return OpStatus::ERR_NO_MEMORY;
}
collection->SetRoot(root, TRUE);
return OpStatus::OK;
}
/* virtual */ void
DOM_NodeCollectionMicrodataProperties::ElementCollectionStatusChangedSpecific(HTML_Element *affected_tree_root, HTML_Element *element, BOOL added, BOOL removed, unsigned collections)
{
// This method is called when an element is changed, inserted into or deleted
// from affected_tree_root. Collection needs to be nofified if changed
// element has one of attributes: id, itemprop, itemscope or itemref.
if (collections & DOM_Environment::COLLECTION_MICRODATA_PROPERTIES)
{
cached_valid = FALSE;
cached_length = -1;
for (DOM_Collection *collection = collection_listeners.First(); collection; collection = collection->Suc())
{
DOM_HTMLPropertiesCollection* typed_collection = static_cast<DOM_HTMLPropertiesCollection*>(collection);
typed_collection->CacheInvalid();
}
}
}
/* static */ int
MicrodataTraverse::CompareNodeOrder(const HTML_Element** first, const HTML_Element** second)
{
if (*first == *second)
return 0;
if ((*first)->Precedes(*second))
return -1;
return 1;
}
OP_STATUS
MicrodataTraverse::FindElementsFromHomeSubtreeWithIds(const OpAutoVector<OpString>* ids)
{
OP_ASSERT(ids);
LogicalDocument *logdoc = m_root_element->GetLogicalDocument();
if (logdoc && logdoc->GetRoot()->IsAncestorOf(m_root_element))
// Home subtree = whole document tree.
for (UINT32 i_ref = 0; i_ref < ids->GetCount(); i_ref++)
{
HTML_Element *named_element = NULL;
NamedElementsIterator iterator;
int found = logdoc->SearchNamedElements(iterator, NULL, ids->Get(i_ref)->CStr(), TRUE, FALSE);
if (found == -1)
return OpStatus::ERR_NO_MEMORY;
else if (found > 0)
{
named_element = iterator.GetNextElement();
RETURN_IF_ERROR(m_refs.Add(named_element));
}
}
else
{
// Home subtree = tree detached from document tree.
// In this case there's no nice collection of named elements.
HTML_Element* local_subtree_root = m_root_element;
while (local_subtree_root->ParentActual())
local_subtree_root = local_subtree_root->ParentActual();
// O(m*n) = O(#refids * #elements in local subtree).
for (UINT32 i_ref = 0; i_ref < ids->GetCount(); i_ref++)
for (HTML_Element* iter_home_subtree = local_subtree_root; iter_home_subtree; iter_home_subtree = iter_home_subtree->NextActual())
if (iter_home_subtree->GetId() && uni_str_eq(iter_home_subtree->GetId(), ids->Get(i_ref)->CStr()))
{
RETURN_IF_ERROR(m_refs.Add(iter_home_subtree));
break; // Match only first element with given id in home subtree.
}
}
return OpStatus::OK;
}
OP_STATUS
MicrodataTraverse::Traverse(HTML_Element* ref_el)
{
// 1. if this element is property (has itemProp attribute), add it to properties.
// 2. if this element is subitem (has itemScope attribute), don't traverse inside.
// 3. if this element is not subitem, traverse subtree.
// 0. Don't do double visit: store all elements from root's itemRef
// attribute (plus root element itself) which were traversed into
// visitedrefs collection.
for (UINT32 i_ref = m_current_ref; i_ref < m_refs.GetCount(); i_ref++)
if (m_refs.Get(i_ref) == ref_el)
RETURN_IF_ERROR(m_visitedrefs.Add(ref_el));
if (ref_el != m_root_element)
{
// 1. if this element is property (has itemProp attribute), add it to properties.
if (ref_el->GetItemPropAttribute() && ref_el->GetItemPropAttribute()->GetTokenCount() != 0)
RETURN_IF_ERROR(m_root_properties_result.Add(ref_el));
// 2. If this element is subitem (has itemScope attribute), don't traverse inside.
if (ref_el->GetBoolAttr(ATTR_ITEMSCOPE) && ref_el != m_root_element)
return OpStatus::OK;
}
// 3. If this element is not subitem, traverse subtree.
for (HTML_Element* children = ref_el->FirstChildActual(); children; children = children->SucActual())
RETURN_IF_ERROR(Traverse(children));
return OpStatus::OK;
}
OP_STATUS
MicrodataTraverse::CrawlMicrodataProperties()
{
// 1. sort refids in tree order.
// 2. traverse all refids' subtrees before root
// 3. traverse root subtree
// 4. traverse all refids' subtrees after root
// 0. init
m_root_properties_result.Empty();
m_visitedrefs.Empty();
m_refs.Empty();
if (!m_root_element->GetBoolAttr(ATTR_ITEMSCOPE))
// Properties and all dependant subcollections are empty for elements
// which are not Microdata items.
return OpStatus::OK;
if (m_root_element->GetItemRefAttribute())
{
const OpAutoVector<OpString>& itemRefIds = m_root_element->GetItemRefAttribute()->GetTokens();
// Find elements from home subtree with ids given in itemRef attribute.
RETURN_IF_ERROR(FindElementsFromHomeSubtreeWithIds(&itemRefIds));
// If I add root element into refs list and then sort set of {itemRef, root}, I have next loop of traversing easier.
RETURN_IF_ERROR(m_refs.Add(m_root_element));
// 1. sort refids in tree order
m_refs.QSort(&CompareNodeOrder); // O(#refids ^ 2).
// 2., 3., 4. traverse all subtrees of refids before root, subtree of root and subtrees of refids after root.
// O(n * #siblings of ith refid).
for (m_current_ref = 0; m_current_ref < m_refs.GetCount(); m_current_ref++)
{
HTML_Element* ref_el = m_refs.Get(m_current_ref);
if (m_visitedrefs.Find(ref_el) != -1)
// HTML element from itemRef has been traversed, so there's no need to
// double properties from its subtree.
continue;
RETURN_IF_ERROR(Traverse(ref_el));
}
}
else
// There's no risk of getting duplicate properties.
// 2. - empty, 3. - traverse subtree of root, 4. - empty.
RETURN_IF_ERROR(Traverse(m_root_element));
return OpStatus::OK;
}
BOOL DOM_NodeCollectionMicrodataProperties::Update()
{
if (cached_valid)
return FALSE;
Length(); // As a side effect of Length() method, collection becomes up to date.
return TRUE;
}
BOOL
DOM_NodeCollectionMicrodataProperties::ContainsMicrodataProperty(const uni_char* property_name)
{
OP_ASSERT(property_name);
int properties_length = Length(); // Length makes collection up to date if needed.
for (int i_props = 0; i_props < properties_length; i_props++)
{
HTML_Element* helm_ith_property = Item(i_props);
OP_ASSERT(helm_ith_property || !"Length() should return number of real elements.");
const OpAutoVector<OpString>& v_props = helm_ith_property->GetItemPropAttribute()->GetTokens();
for (UINT32 j = 0; j < v_props.GetCount(); j++)
{
OP_ASSERT(v_props.Get(j)->CStr() || !"itemProp should be split on whitespace to non-null tokens.");
if (uni_str_eq(v_props.Get(j)->CStr(), property_name))
return TRUE;
}
}
return FALSE;
}
/*virtual */ ES_GetState
DOM_NodeCollectionMicrodataProperties::GetCollectionProperty(DOM_Collection *collection, BOOL allowed, const uni_char *property_name, int property_code, ES_Value *return_value, ES_Runtime *origining_runtime)
{
OpAtom atom = static_cast<OpAtom>(property_code);
OP_ASSERT(atom >= OP_ATOM_UNASSIGNED && atom < OP_ATOM_ABSOLUTELY_LAST_ENUM);
if (atom == OP_ATOM_length || atom == OP_ATOM_names)
return collection->GetName(atom, return_value, origining_runtime);
DOM_Collection* subcollection;
GET_FAILED_IF_ERROR(GetPropertyNodeList(property_name, subcollection));
DOMSetObject(return_value, subcollection);
return GET_SUCCESS;
}
/* virtual */ ES_GetState
DOM_NodeCollectionMicrodataProperties::GetLength(int &length, BOOL allowed)
{
needs_invalidation = TRUE;
if (!allowed)
return GET_SECURITY_VIOLATION;
length = Length();
return GET_SUCCESS;
}
/* virtual */ int
DOM_NodeCollectionMicrodataProperties::Length()
{
if (!root)
return 0;
UpdateSerialNr();
if (cached_length != -1)
return cached_length;
HTML_Element *root_element = GetRootElement();
if (!root_element)
return 0;
MicrodataTraverse mdt(root_element, m_root_properties_cache);
if (OpStatus::IsError(mdt.CrawlMicrodataProperties()))
{
cached_length = 0;
return cached_length;
}
cached_length = m_root_properties_cache.GetCount();
cached_valid = FALSE;
cached_index_match = NULL;
cached_index = -1;
return cached_length;
}
/* virtual */ HTML_Element *
DOM_NodeCollectionMicrodataProperties::Item(int index)
{
if (!root)
return NULL;
UpdateSerialNr();
if (cached_length != -1 && index >= cached_length)
return NULL;
if (cached_valid && cached_index_match && cached_index == index)
return cached_index_match;
/* Force the computation of length to populate cache and to determine if given index is out of bounds. */
if (cached_length == -1)
{
cached_length = Length();
if (index >= cached_length)
return NULL;
}
HTML_Element *root_element = GetRootElement();
if (!root_element)
return NULL;
HTML_Element* found_element = m_root_properties_cache.Get(index);
if (found_element)
{
cached_valid = TRUE;
cached_index = index;
cached_index_match = found_element;
return found_element;
}
else
return NULL;
}
OP_STATUS
DOM_NodeCollectionMicrodataProperties::GetPropertyNodeList(const uni_char *property_name, DOM_Collection *&subcollection)
{
DOM_PropertyNodeList_Collection *typed_collection;
RETURN_IF_ERROR(GetCachedSubcollection(subcollection, property_name));
if (!subcollection)
{
RETURN_IF_ERROR(DOM_PropertyNodeList_Collection::Make(typed_collection, GetEnvironment(), root, this, property_name));
subcollection = typed_collection;
RETURN_IF_ERROR(SetCachedSubcollection(property_name, subcollection));
}
return OpStatus::OK;
}
//---
/* static */ OP_STATUS
DOM_NodeCollection_PropertyNodeList::Make(DOM_NodeCollection *&collection, DOM_EnvironmentImpl *environment, DOM_Node *root, DOM_NodeCollectionMicrodataProperties* base_properties, const uni_char* property_name_filter)
{
DOM_Runtime *runtime = environment->GetDOMRuntime();
if (OpStatus::IsMemoryError(DOMSetObjectRuntime(collection = OP_NEW(DOM_NodeCollection_PropertyNodeList, (base_properties, property_name_filter)), runtime)))
{
collection = NULL;
return OpStatus::ERR_NO_MEMORY;
}
collection->SetRoot(root, TRUE);
return OpStatus::OK;
}
/* virtual */ int
DOM_NodeCollection_PropertyNodeList::Length()
{
if (!m_base_properties->Update() && cached_valid && cached_length != -1)
return cached_length;
int base_length = m_base_properties->Length();
int filtered_hit = 0;
for (int i_props = 0; i_props < base_length; i_props++)
{
OP_ASSERT(m_base_properties->Get(i_props)->GetItemPropAttribute() || !"m_base_properties->Length() should return number of HTML elements with itemProp attribute.");
const OpAutoVector<OpString>& ith_prop_tokens = m_base_properties->Get(i_props)->GetItemPropAttribute()->GetTokens();
for (UINT32 j_prop_token = 0; j_prop_token < ith_prop_tokens.GetCount(); j_prop_token++)
if (uni_str_eq(ith_prop_tokens.Get(j_prop_token)->CStr(), m_property_name_filter))
{
filtered_hit++;
break; // Single HTML element fits only once, even if it has duplicated "m_property_name_filter" tokens in itemProp.
}
}
cached_length = filtered_hit;
return filtered_hit;
}
/* virtual */ HTML_Element *
DOM_NodeCollection_PropertyNodeList::Item(int index)
{
if (!m_base_properties->Update() && cached_valid && cached_index == index)
return cached_index_match;
int base_length = m_base_properties->Length();
int filtered_hit = 0;
for (int i_prop = 0; i_prop < base_length; i_prop++)
{
HTML_Element* helm_ith_property = m_base_properties->Get(i_prop);
OP_ASSERT(m_base_properties->Get(i_prop)->GetItemPropAttribute() || !"m_base_properties->Length() should return number of HTML elements with itemProp attribute.");
const OpAutoVector<OpString>& ith_prop_tokens = helm_ith_property->GetItemPropAttribute()->GetTokens();
for (UINT32 j_prop_token = 0; j_prop_token < ith_prop_tokens.GetCount(); j_prop_token++)
if (uni_str_eq(ith_prop_tokens.Get(j_prop_token)->CStr(), m_property_name_filter))
{
if (filtered_hit == index)
{
cached_valid = TRUE;
cached_index_match = helm_ith_property;
cached_index = index;
return cached_index_match;
}
filtered_hit++;
break; // Single HTML element fits only once.
}
}
cached_valid = TRUE;
cached_index_match = NULL;
cached_index = index;
return cached_index_match;
}
/* virtual */ ES_GetState
DOM_NodeCollection_PropertyNodeList::GetLength(int &length, BOOL allowed)
{
needs_invalidation = TRUE;
if (!allowed)
return GET_SECURITY_VIOLATION;
length = Length();
return GET_SUCCESS;
}
/* virtual */ ES_GetState
DOM_NodeCollection_PropertyNodeList::GetCollectionProperty(DOM_Collection *collection, BOOL allowed, const uni_char *property_name, int property_code, ES_Value *return_value, ES_Runtime *origining_runtime)
{
OpAtom atom = static_cast<OpAtom>(property_code);
OP_ASSERT(atom >= OP_ATOM_UNASSIGNED && atom < OP_ATOM_ABSOLUTELY_LAST_ENUM);
if (atom == OP_ATOM_length)
{
DOMSetNumber(return_value, Length());
return GET_SUCCESS;
}
return collection->GetName(atom, return_value, origining_runtime);
}
/* virtual */ void
DOM_NodeCollection_PropertyNodeList::ElementCollectionStatusChangedSpecific(HTML_Element *affected_tree_root, HTML_Element *element, BOOL added, BOOL removed, unsigned collections)
{
if (collections & DOM_Environment::COLLECTION_MICRODATA_PROPERTIES)
{
cached_valid = FALSE;
cached_length = -1;
}
}
//---
/** This class represents Microdata property of Microdata item.
*
* It is used when fetching helm.properties.names, which is list of unique
* tree-ordered Microdata property names.
**/
struct PropertyNameTreeOrdered
{
PropertyNameTreeOrdered(const uni_char* name, int tree_order_index)
: name(name)
, name_hash(OpGenericStringHashTable::HashString(name, TRUE))
, tree_order_index(tree_order_index)
{}
const uni_char* name;
int name_hash;
int tree_order_index;
enum {
IS_DUPLICATE = (1 << 30)
};
static int compare_name_hash(const PropertyNameTreeOrdered** a, const PropertyNameTreeOrdered** b)
{
if ((*a)->name_hash == (*b)->name_hash)
return 0;
return (*a)->name_hash < (*b)->name_hash ? -1 : 1;
}
static int compare_indices(const PropertyNameTreeOrdered** a, const PropertyNameTreeOrdered** b)
{
if ((*a)->tree_order_index == (*b)->tree_order_index)
return 0;
return (*a)->tree_order_index < (*b)->tree_order_index ? -1 : 1;
}
};
//---
/* static */ OP_STATUS
DOM_HTMLPropertiesCollection::Make(DOM_HTMLPropertiesCollection *&collection, DOM_EnvironmentImpl *environment, DOM_Element *root)
{
DOM_Runtime *runtime = environment->GetDOMRuntime();
DOM_NodeCollection *node_collection;
RETURN_IF_ERROR(DOM_NodeCollectionMicrodataProperties::Make(node_collection, environment, root));
if (!(collection = OP_NEW(DOM_HTMLPropertiesCollection, ())) ||
OpStatus::IsMemoryError(collection->SetFunctionRuntime(runtime, runtime->GetPrototype(DOM_Runtime::HTMLPROPERTIESCOLLECTION_PROTOTYPE), UNI_L("HTMLPropertiesCollection"), "HTMLPropertiesCollection", "s")))
{
OP_DELETE(collection);
return OpStatus::ERR_NO_MEMORY;
}
RETURN_IF_ERROR(node_collection->RegisterCollection(collection));
collection->node_collection = node_collection;
node_collection->SetRoot(root, TRUE);
return OpStatus::OK;
}
static OP_STATUS
PopulateNamesWithDuplicatesInTreeOrder(OpAutoVector<PropertyNameTreeOrdered>& names, DOM_NodeCollectionMicrodataProperties* nc)
{
int properties_len = nc->Length();
for (int i_props = 0; i_props < properties_len; i_props++)
{
OP_ASSERT(nc->Item(i_props)->GetItemPropAttribute() || !"nc->Length() should return number of HTML elements with itemProp attribute.");
const OpAutoVector<OpString>& ith_prop_tokens = nc->Item(i_props)->GetItemPropAttribute()->GetTokens();
for (UINT32 j_prop_token = 0; j_prop_token < ith_prop_tokens.GetCount(); j_prop_token++)
{
PropertyNameTreeOrdered* next_name = OP_NEW(PropertyNameTreeOrdered, (ith_prop_tokens.Get(j_prop_token)->CStr(), names.GetCount()));
if (!next_name)
return OpStatus::ERR_NO_MEMORY;
RETURN_IF_ERROR(names.Add(next_name));
}
}
return OpStatus::OK;
}
/* virtual */ unsigned
DOM_HTMLPropertiesCollection::StringList_length()
{
DOM_NodeCollectionMicrodataProperties* nc = static_cast<DOM_NodeCollectionMicrodataProperties*>(GetNodeCollection());
if (!nc->Update() && m_cached_names_length != -1)
return m_cached_names_length;
OpAutoVector<PropertyNameTreeOrdered> names;
if (OpStatus::IsError(PopulateNamesWithDuplicatesInTreeOrder(names, nc)))
return 0;
// In order to spot duplicates, sort the collection by string name_hash.
names.QSort(&PropertyNameTreeOrdered::compare_name_hash);
PropertyNameTreeOrdered* previous = NULL;
int i_unique = 0;
for (UINT32 i_with_dupes = 0; i_with_dupes < names.GetCount(); i_with_dupes++)
{
PropertyNameTreeOrdered* current = names.Get(i_with_dupes);
if (previous && previous->name_hash == current->name_hash && uni_str_eq(previous->name, current->name))
continue; // It is duplicate, don't count.
i_unique++;
previous = current;
}
m_cached_names_length = i_unique;
return m_cached_names_length;
}
// Place for future performance improvement: cached OpAutoVector<PropertyNameTreeOrdered> names.
/* virtual */ OP_STATUS
DOM_HTMLPropertiesCollection::StringList_item(int index, const uni_char *&property_name)
{
DOM_NodeCollectionMicrodataProperties* nc = static_cast<DOM_NodeCollectionMicrodataProperties*>(GetNodeCollection());
if (!nc->Update() && m_cached_names_index != -1 && m_cached_names_index == index)
{
property_name = m_cached_names_index_value.CStr();
return OpStatus::OK;
}
OpAutoVector<PropertyNameTreeOrdered> names;
RETURN_IF_ERROR(PopulateNamesWithDuplicatesInTreeOrder(names, nc));
// In order to spot duplicates, sort the collection by string name_hash.
names.QSort(&PropertyNameTreeOrdered::compare_name_hash);
PropertyNameTreeOrdered* previous = NULL;
int i_unique = 0;
for (UINT32 i_with_dupes = 0; i_with_dupes < names.GetCount(); i_with_dupes++)
{
PropertyNameTreeOrdered* current = names.Get(i_with_dupes);
if (previous && previous->name_hash == current->name_hash && uni_str_eq(previous->name, current->name))
{
// In order to preserve tree order between different properties,
// check tree order of properties with same name. If there's a
// duplicate, it is given very high number, so after sorting, it
// ends up at the end of the list.
if (current->tree_order_index >= previous->tree_order_index)
current->tree_order_index = PropertyNameTreeOrdered::IS_DUPLICATE;
else
{
previous->tree_order_index = PropertyNameTreeOrdered::IS_DUPLICATE;
previous = current;
}
continue;
}
i_unique++;
previous = current;
}
// Sort back to tree order.
names.QSort(&PropertyNameTreeOrdered::compare_indices);
PropertyNameTreeOrdered* indexth_item = names.Get(index);
OP_ASSERT(static_cast<UINT32>(index) < names.GetCount());
OP_ASSERT(indexth_item || !"Only non-null names should have been sorted.");
if (indexth_item->tree_order_index != PropertyNameTreeOrdered::IS_DUPLICATE)
RETURN_IF_ERROR(m_cached_names_index_value.Set(indexth_item->name));
else
m_cached_names_index_value.Empty();
m_cached_names_index = index;
property_name = m_cached_names_index_value.CStr();
return OpStatus::OK;
}
/* virtual */ BOOL
DOM_HTMLPropertiesCollection::StringList_contains(const uni_char *string)
{
DOM_NodeCollectionMicrodataProperties* nc = static_cast<DOM_NodeCollectionMicrodataProperties*>(GetNodeCollection());
return nc->ContainsMicrodataProperty(string);
}
/* static */ int
DOM_HTMLPropertiesCollection::item(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(collection, DOM_TYPE_HTML_PROPERTIES_COLLECTION, DOM_HTMLPropertiesCollection);
DOM_CHECK_ARGUMENTS("N");
int index = TruncateDoubleToInt(argv[0].value.number);
ES_GetState state = collection->GetIndex(index, return_value, origining_runtime);
if (state == GET_FAILED)
{
DOMSetNull(return_value);
return ES_VALUE;
}
else
return ConvertGetNameToCall(state, return_value);
}
/* static */ int
DOM_HTMLPropertiesCollection::namedItem(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(collection, DOM_TYPE_HTML_PROPERTIES_COLLECTION, DOM_HTMLPropertiesCollection);
DOM_CHECK_ARGUMENTS("s");
const uni_char* property_name = argv[0].value.string;
DOM_Collection* subcollection;
DOM_NodeCollectionMicrodataProperties* nc = static_cast<DOM_NodeCollectionMicrodataProperties*>(collection->GetNodeCollection());
CALL_FAILED_IF_ERROR(nc->GetPropertyNodeList(property_name, subcollection));
DOMSetObject(return_value, subcollection);
return ES_VALUE;
}
/* virtual */ int
DOM_HTMLPropertiesCollection::Call(ES_Object *this_object, ES_Value *argv, int argc, ES_Value* return_value, ES_Runtime* origining_runtime)
{
DOM_CHECK_ARGUMENTS("s");
if (!OriginCheck(origining_runtime))
return ES_EXCEPT_SECURITY;
m_is_call = TRUE;
int state = CallAsGetNameOrGetIndex(argv[0].value.string, return_value, static_cast<DOM_Runtime *>(origining_runtime));
m_is_call = FALSE;
return state;
}
/* virtual */ ES_GetState
DOM_HTMLPropertiesCollection::GetName(const uni_char *property_name, int property_code, ES_Value *value, ES_Runtime *origining_runtime)
{
BOOL allowed = OriginCheck(origining_runtime);
DOM_NodeCollectionMicrodataProperties* collection = static_cast<DOM_NodeCollectionMicrodataProperties*>(GetNodeCollection());
// [OverrideBuiltins] is not declared for any of the properties, hence no overriding is allowed
if (!m_is_call && (property_code == OP_ATOM_item || property_code == OP_ATOM_namedItem))
return GET_FAILED;
if (m_is_call
|| (collection->ContainsMicrodataProperty(property_name))
|| property_code == OP_ATOM_length
|| property_code == OP_ATOM_names)
return collection->GetCollectionProperty(this, allowed, property_name, property_code, value, origining_runtime);
return GET_FAILED;
}
/* virtual */ ES_GetState
DOM_HTMLPropertiesCollection::GetName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime)
{
switch (property_name)
{
case OP_ATOM_length:
if (value)
return DOM_Collection::GetName(property_name, value, origining_runtime);
else
return GET_SUCCESS;
case OP_ATOM_names:
if (value)
{
ES_GetState state = DOMSetPrivate(value, DOM_PRIVATE_names);
if (state == GET_FAILED)
{
DOM_DOMStringList *stringlist;
GET_FAILED_IF_ERROR(DOM_DOMStringList::Make(stringlist, this, this, static_cast<DOM_Runtime *>(origining_runtime)));
GET_FAILED_IF_ERROR(PutPrivate(DOM_PRIVATE_names, *stringlist));
DOMSetObject(value, stringlist);
return GET_SUCCESS;
}
else
return state;
}
return GET_SUCCESS;
default:
return DOM_Collection::GetName(property_name, value, origining_runtime);
}
}
/* virtual */ ES_PutState
DOM_HTMLPropertiesCollection::PutName(OpAtom property_name, ES_Value* value, ES_Runtime* origining_runtime)
{
switch (property_name)
{
case OP_ATOM_names:
return PUT_SUCCESS;
default:
return DOM_Collection::PutName(property_name, value, origining_runtime);
}
}
/* static */ OP_STATUS
DOM_PropertyNodeList_Collection::Make(DOM_PropertyNodeList_Collection *&collection, DOM_EnvironmentImpl *environment, DOM_Node *root, DOM_NodeCollectionMicrodataProperties* base_properties, const uni_char* property_name_filter)
{
OP_ASSERT(base_properties);
OP_ASSERT(property_name_filter);
DOM_NodeCollection *node_collection;
RETURN_IF_ERROR(DOM_NodeCollection_PropertyNodeList::Make(node_collection, environment, root, base_properties, property_name_filter));
DOM_Runtime *runtime = environment->GetDOMRuntime();
if (!(collection = OP_NEW(DOM_PropertyNodeList_Collection, ()))
|| OpStatus::IsMemoryError(collection->SetFunctionRuntime(runtime, runtime->GetPrototype(DOM_Runtime::HTMLPROPERTYNODELISTCOLLECTION_PROTOTYPE), UNI_L("PropertyNodeList"), "PropertyNodeList", "s-")))
{
OP_DELETE(collection);
return OpStatus::ERR_NO_MEMORY;
}
RETURN_IF_ERROR(node_collection->RegisterCollection(collection));
collection->node_collection = node_collection;
collection->SetRoot(root, TRUE);
return OpStatus::OK;
}
/* static */ int
DOM_PropertyNodeList_Collection::item(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(collection, DOM_TYPE_PROPERTY_NODE_LIST_COLLECTION, DOM_PropertyNodeList_Collection);
DOM_CHECK_ARGUMENTS("N");
int index = TruncateDoubleToInt(argv[0].value.number);
ES_GetState state = collection->GetIndex(index, return_value, origining_runtime);
if (state == GET_FAILED)
{
DOMSetNull(return_value);
return ES_VALUE;
}
else
return ConvertGetNameToCall(state, return_value);
}
/* static */ int
DOM_PropertyNodeList_Collection::getValues(DOM_Object *this_object, ES_Value *argv, int argc, ES_Value* return_value, DOM_Runtime* origining_runtime)
{
DOM_THIS_OBJECT(collection, DOM_TYPE_PROPERTY_NODE_LIST_COLLECTION, DOM_PropertyNodeList_Collection);
ES_Object* values_array;
CALL_FAILED_IF_ERROR(origining_runtime->CreateNativeArrayObject(&values_array));
int props_len = collection->Length();
for (int i_prop_el = 0; i_prop_el < props_len; i_prop_el++)
{
ES_Value ith_itemValue;
HTML_Element* helm_ith_property = collection->Item(i_prop_el);
DOM_Object* ith_property_node;
collection->GetEnvironment()->ConstructNode(ith_property_node, helm_ith_property);
const uni_char* is_subitem = static_cast<const uni_char*>(helm_ith_property->GetAttr(ATTR_ITEMSCOPE, ITEM_TYPE_STRING, NULL));
if (is_subitem)
{
DOM_Object::DOMSetObject(&ith_itemValue, ith_property_node);
CALL_FAILED_IF_ERROR(origining_runtime->PutIndex(values_array, i_prop_el, ith_itemValue));
continue;
}
OpAtom to_get = DOM_HTMLElement::GetItemValueProperty(helm_ith_property);
ES_GetState state = ith_property_node->GetName(to_get, &ith_itemValue, origining_runtime);
if (state != GET_SUCCESS)
return ConvertGetNameToCall(state, return_value);
CALL_FAILED_IF_ERROR(origining_runtime->PutIndex(values_array, i_prop_el, ith_itemValue));
}
DOMSetObject(return_value, values_array);
return GET_SUCCESS;
}
/* virtual */ ES_GetState
DOM_PropertyNodeList_Collection::GetName(const uni_char *property_name, int property_code, ES_Value *value, ES_Runtime *origining_runtime)
{
// Microdata property names shadow PropertyNodeList members (for now only "length" member).
DOM_NodeCollectionMicrodataProperties* collection = static_cast<DOM_NodeCollectionMicrodataProperties*>(GetNodeCollection());
if (collection->ContainsMicrodataProperty(property_name))
return collection->GetCollectionProperty(this, TRUE, property_name, property_code, value, origining_runtime);
if (property_code == OP_ATOM_length)
{
if (value)
DOMSetNumber(value, collection->Length());
return GET_SUCCESS;
}
return GET_FAILED;
}
//---
OP_STATUS
DOM_ToplevelItemCollectionFilter::AddType(const uni_char* to_add, int len)
{
OpAutoPtr<OpString> ap_str(OP_NEW(OpString, ()));
RETURN_IF_ERROR(ap_str.get()->Set(to_add, len));
RETURN_IF_ERROR(m_itemtypes.Add(ap_str.get()));
ap_str.release();
return OpStatus::OK;
}
/* virtual */
DOM_ToplevelItemCollectionFilter::~DOM_ToplevelItemCollectionFilter()
{
m_itemtypes.DeleteAll();
}
/* virtual */ void
DOM_ToplevelItemCollectionFilter::Visit(HTML_Element *element, BOOL &include, BOOL &visit_children, LogicalDocument *logdoc)
{
visit_children = TRUE;
include = FALSE;
if (element->IsToplevelMicrodataItem())
{
UINT32 itemtypes_len = m_itemtypes.GetCount();
if (itemtypes_len == 0)
include = TRUE;
else
{
const uni_char *itemtype = element->GetStringAttr(ATTR_ITEMTYPE);
if (itemtype)
for (UINT32 i = 0; i < itemtypes_len; i++)
if (m_itemtypes.Get(i)->Compare(itemtype) == 0)
{
include = TRUE;
return;
}
}
}
}
/* virtual */ DOM_CollectionFilter *
DOM_ToplevelItemCollectionFilter::Clone() const
{
DOM_ToplevelItemCollectionFilter *clone = OP_NEW(DOM_ToplevelItemCollectionFilter, ());
if (clone)
for (UINT32 i = 0; i < m_itemtypes.GetCount(); i++)
if (OpStatus::IsMemoryError(clone->AddType(m_itemtypes.Get(i)->CStr())))
{
OP_DELETE(clone);
return NULL;
}
return clone;
}
/* virtual */ BOOL
DOM_ToplevelItemCollectionFilter::IsMatched(unsigned collections)
{
return (collections & DOM_Environment::COLLECTION_MICRODATA_TOPLEVEL_ITEMS) != 0;
}
/* virtual */ BOOL
DOM_ToplevelItemCollectionFilter::IsEqual(DOM_CollectionFilter *other)
{
if (other->GetType() != TYPE_MICRODATA_TOPLEVEL_ITEM)
return FALSE;
DOM_ToplevelItemCollectionFilter *toplevel_item_other = static_cast<DOM_ToplevelItemCollectionFilter *>(other);
UINT32 itemtypes_len = m_itemtypes.GetCount();
if (itemtypes_len != toplevel_item_other->m_itemtypes.GetCount())
return FALSE;
/* A strict notion of equality. We could admit a larger set by handling permutations; not worth it. */
for (UINT32 i = 0; i < itemtypes_len; i++)
if (m_itemtypes.Get(i)->Compare(*toplevel_item_other->m_itemtypes.Get(i)) != 0)
return FALSE;
return TRUE;
}
#include "modules/dom/src/domglobaldata.h"
DOM_FUNCTIONS_START(DOM_HTMLPropertiesCollection)
DOM_FUNCTIONS_FUNCTION(DOM_HTMLPropertiesCollection, DOM_HTMLPropertiesCollection::item, "item", "n-")
DOM_FUNCTIONS_FUNCTION(DOM_HTMLPropertiesCollection, DOM_HTMLPropertiesCollection::namedItem, "namedItem", "s-")
DOM_FUNCTIONS_END(DOM_HTMLPropertiesCollection)
DOM_FUNCTIONS_START(DOM_PropertyNodeList_Collection)
DOM_FUNCTIONS_FUNCTION(DOM_PropertyNodeList_Collection, DOM_PropertyNodeList_Collection::item, "item", "n-")
DOM_FUNCTIONS_FUNCTION(DOM_PropertyNodeList_Collection, DOM_PropertyNodeList_Collection::getValues, "getValues", "-")
DOM_FUNCTIONS_END(DOM_PropertyNodeList_Collection)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.