blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
de5422e6c6ebc6f32daee7f0269d6d580643b719 | 3b489debb4be72101cce7fe45432ec6a8e2c823d | /src/Platform/OSX/System/Ipv4Resolver.cpp | eddff7e60f405fd40fc7c538cd06072a79275919 | [
"LicenseRef-scancode-unknown-license-reference",
"BSD-3-Clause"
] | permissive | AmericanCoinAMC/Core | 72f75bac3b68c0dfbd9073db5684d22719b8fee6 | f8498c6c355e0035ff80f11fbb259ae7181ff4a6 | refs/heads/master | 2021-01-19T01:36:35.760046 | 2017-06-12T23:58:59 | 2017-06-12T23:58:59 | 87,250,520 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,090 | cpp | // Copyright (c) 2011-2016 The Cryptonote developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "Ipv4Resolver.h"
#include <cassert>
#include <random>
#include <stdexcept>
#include <netdb.h>
#include <System/Dispatcher.h>
#include <System/ErrorMessage.h>
#include <System/InterruptedException.h>
#include <System/Ipv4Address.h>
namespace System {
Ipv4Resolver::Ipv4Resolver() : dispatcher(nullptr) {
}
Ipv4Resolver::Ipv4Resolver(Dispatcher& dispatcher) : dispatcher(&dispatcher) {
}
Ipv4Resolver::Ipv4Resolver(Ipv4Resolver&& other) : dispatcher(other.dispatcher) {
if (dispatcher != nullptr) {
other.dispatcher = nullptr;
}
}
Ipv4Resolver::~Ipv4Resolver() {
}
Ipv4Resolver& Ipv4Resolver::operator=(Ipv4Resolver&& other) {
dispatcher = other.dispatcher;
if (dispatcher != nullptr) {
other.dispatcher = nullptr;
}
return *this;
}
Ipv4Address Ipv4Resolver::resolve(const std::string& host) {
assert(dispatcher != nullptr);
if (dispatcher->interrupted()) {
throw InterruptedException();
}
addrinfo hints = { 0, AF_INET, SOCK_STREAM, IPPROTO_TCP, 0, NULL, NULL, NULL };
addrinfo* addressInfos;
int result = getaddrinfo(host.c_str(), NULL, &hints, &addressInfos);
if (result != 0) {
throw std::runtime_error("Ipv4Resolver::resolve, getaddrinfo failed, " + errorMessage(result));
}
std::size_t count = 0;
for (addrinfo* addressInfo = addressInfos; addressInfo != nullptr; addressInfo = addressInfo->ai_next) {
++count;
}
std::mt19937 generator{ std::random_device()() };
std::size_t index = std::uniform_int_distribution<std::size_t>(0, count - 1)(generator);
addrinfo* addressInfo = addressInfos;
for (std::size_t i = 0; i < index; ++i) {
addressInfo = addressInfo->ai_next;
}
Ipv4Address address(ntohl(reinterpret_cast<sockaddr_in*>(addressInfo->ai_addr)->sin_addr.s_addr));
freeaddrinfo(addressInfo);
return address;
}
}
| [
"jessmanny19@gmail.com"
] | jessmanny19@gmail.com |
14bc8905dcd93dc9ec39d70cb03151cc5416095b | 4f0a96aa4642a735f71704c360beb2a5d4dd9a9e | /src/Core/Filters/GridFilter.cpp | 2be3ebd1ac1298a84b794872f3fb2e98b3efea67 | [] | no_license | longyangzz/OpenVizEarth | 79f3f2873329d92b5749500c0dfbde128e0cfb13 | e8477ba4c7a48be37e6246cd98836895b086ae7d | refs/heads/master | 2022-09-18T19:58:33.747036 | 2022-08-07T07:05:52 | 2022-08-07T07:05:52 | 192,552,174 | 33 | 19 | null | 2019-10-06T11:37:56 | 2019-06-18T14:05:21 | C++ | GB18030 | C++ | false | false | 6,376 | cpp | #include "GridFilter.h"
#include <QFileDialog>
#include <QFile>
#include <QString>
#include <QFileInfo>
#include "QTextStream"
#include "QFile"
#include "QRegExp"
#include "QStringList"
#include "qglobal.h"
#include <algorithm>
#include <string>
#include <memory>
#include <cmath>
#include <fstream> // std::ifstream
#include <iostream> // std::cout
#include <array>
//liblas
#include "liblas/point.hpp"
#include "liblas/reader.hpp"
#include "liblas/writer.hpp"
#include "liblas/factory.hpp"
using namespace std;
GridFilter::GridFilter(std::vector<DCVector3D> inPutPoint, QString fileOut)
: m_inPutPoint(inPutPoint)
{
m_fileOut = fileOut;
}
GridFilter::GridFilter(QString fileIn, QString fileOut)
{
m_fileIn = fileIn;
m_fileOut = fileOut;
}
GridFilter::~GridFilter()
{
}
void GridFilter::SetFBL(double xFBL, double yFBL)
{
XFBL = xFBL;
YFBL = yFBL;
}
void GridFilter::GetOutput(std::vector<DCVector3D> & points)
{
points = m_LowerPoint;
m_LowerPoint.clear();
}
void GridFilter::DoFilter()
{
QFileInfo fileInfo(m_fileIn);
QString exten = fileInfo.suffix();
bool readState = false;
if ("LAS" == exten.toUpper())
{
readState = ReadLasFile(m_fileIn);
}
else if ("DAT" == exten.toUpper() )
{
readState = ReadTXTAscii(m_fileIn);
}
if (!readState)
{
return;
}
Fastfast(m_inPutPoint, 0);
WriteDatAsccii(m_fileOut);
}
void GridFilter::Fastfast(std::vector<DCVector3D> & points, unsigned num)
{
//根据选择的投影面,进行相应的分区处理
double tempXfbl = XFBL + num * XFBL/2.0;
double tempYfbl = YFBL + num * YFBL/2.0;
m_LowerPoint.clear();
//求该块点云x,y,z的最大最小值
std::vector<double> Maxminxyz;
std::sort(points.begin(),points.end(),[](DCVector3D v1,DCVector3D v2)->bool{return (v1.x() < v2.x());});
Maxminxyz.push_back(points[0].x() + 0);
Maxminxyz.push_back(points[points.size()-1].x());
std::sort(points.begin(),points.end(),[](DCVector3D v1,DCVector3D v2)->bool{return (v1.y() < v2.y());});
Maxminxyz.push_back(points[0].y() + 0);
Maxminxyz.push_back(points[points.size()-1].y());
std::sort(points.begin(),points.end(),[](DCVector3D v1,DCVector3D v2)->bool{return (v1.z() < v2.z());});
Maxminxyz.push_back(points[0].z());
Maxminxyz.push_back(points[points.size()-1].z());
double zxxz = floor(Maxminxyz[0]);
double zxyz = floor(Maxminxyz[2]);
double zxzz = floor(Maxminxyz[4]);
//第三步:求出该点云的行号、列号、层号的最大值
int xnum = floor((Maxminxyz[1]-zxxz)/tempXfbl)+1;
int ynum = floor((Maxminxyz[3]-zxyz)/tempYfbl)+1;
//int znum = floor((Maxminxyz[5]-zxzz)/ZFBL)+1;
//第四步:求出区总数、一层的区总数、总点数
int allbox = xnum*ynum;
int quzs = xnum*ynum;
int Psum = points.size();
//第五步:初始化存放各区点的容器
m_fq32.clear();
for (int i=0;i<allbox;i++)
{
std::vector<DCVector3D> point1;
fq32 pxzb;
pxzb.quhao=i;
pxzb.m_px32=point1;
m_fq32.push_back(pxzb);
}
//第六步:将点放在各分区中
//for (auto i=m_points.begin();i<m_points.end();i++)
for (unsigned i=0; i < points.size();i++)
{
int COLUMNNUM = floor(( (points[i])[0]-zxxz )/tempXfbl);
int ROWNUM = floor(( (points[i])[1]-zxyz )/tempYfbl);
//int LAYERNUM = floor(( (points[i])[2]-zxzz )/ZFBL);
int index = ROWNUM*xnum+COLUMNNUM+1;
m_fq32[index-1].m_px32.push_back((points[i]));
}
//第七步:将有点的区只保留高程最低的点放到另一容器中
for (int i=0;i<allbox;i++)
{
//先求每块的Z值的最低点
std::vector<DCVector3D> point1;
point1=m_fq32.at(i).m_px32;
if (point1.size()>0)
{
//当前分区z排序
std::sort(point1.begin(),point1.end(),[](DCVector3D v1,DCVector3D v2)->bool{return (v1.z() < v2.z());});
//从当前分区中删除大于1/3的部分高程点
m_LowerPoint.push_back(point1.at(0));
}
}
m_inPutPoint = m_LowerPoint;
}
bool GridFilter::ReadTXTAscii(QString qFilename)
{
QFile inFile(qFilename);
if (!inFile.open(QIODevice::ReadOnly))
{
return false;
}
char currentLine[500];
auto readLines = inFile.readLine(currentLine, 500);
if (readLines < 0)
{
return false;
}
while(readLines > 0)
{
QStringList list = QString(currentLine).split(QRegExp(",|\\s+"), QString::SkipEmptyParts);
if (list.size() >= 3)
{
float vx = list[0].toFloat();
float vy = list[1].toFloat();
float vz = list[2].toFloat();
m_inPutPoint.push_back(osg::Vec3f(vx,vy,vz));
}
readLines = inFile.readLine(currentLine, 500);
}
if (m_inPutPoint.size() > 0)
{
return true;
}
return false;
}
bool GridFilter::ReadLasFile(QString fileIn)
{
QFile inFile(fileIn);
if (!inFile.exists())
{
return nullptr;
}
//! 解析las、laz文件
//打开文件
ifstream ifs;
ifs.open(qPrintable(fileIn), std::ios::in | std::ios::binary);
if (ifs.fail())
{
return false;
}
liblas::Reader* reader = 0;
unsigned nbOfPoints = 0;
try
{
reader = new liblas::Reader(liblas::ReaderFactory().CreateWithStream(ifs));
//处理压缩与非压缩文件
liblas::Header const& header = reader->GetHeader();
//获取点个数
nbOfPoints = header.GetPointRecordsCount();
if (nbOfPoints == 0)
{
delete reader;
ifs.close();
return nullptr;
}
m_inPutPoint.clear();
while (reader->ReadNextPoint())
{
liblas::Point const& p = reader->GetPoint();
float vx = p.GetX();
float vy = p.GetY();
float vz = p.GetZ();
m_inPutPoint.push_back(osg::Vec3f(vx,vy,vz));
}
}
catch(...)
{
return false;
}
if (m_inPutPoint.size() > 0)
{
return true;
}
return false;
}
/**
*格式 : 序号, 代码(省略), 东坐标, 北坐标, 高程
*/
bool GridFilter::WriteDatAsccii(QString fileOut)
{
QFile oFile(fileOut);
if (!oFile.open(QIODevice::ReadWrite))
{
return false;
}
int i=0;
for (auto itPoint = m_LowerPoint.begin(); itPoint != m_LowerPoint.end(); itPoint++ )
{
QString line;
line.append(QString("%1").arg(i++));
line.append(","); //添加分隔符
line.append(","); //添加分隔符
line.append(QString("%1").arg((*itPoint).x(), 0, 'f', 6));
line.append(","); //添加分隔符
line.append(QString("%1").arg((*itPoint).y(), 0, 'f', 6));
line.append(","); //添加分隔符
line.append(QString("%1").arg((*itPoint).z(), 0, 'f', 3));
oFile.write(line.toStdString().c_str());
oFile.write("\n");
}
//关闭句柄
oFile.close();
} | [
"451215954@qq.com"
] | 451215954@qq.com |
e20540a1a4f166abe06b520b68f2bb7e733f470e | 8268bc1a2d543b9b6cf536b4a98ae8f2b4e0e22a | /app/src/main/jni/base/cxbase.h | 02b62071c257a432d8975bd0f1b590d1f2b2b230 | [] | no_license | binsvivi/SyberUnifyId | 826ff1e191fa85a549af05231af6d89edb3c9904 | ff38584c559f0b7b02b6a90b1f1b337b71d412dc | refs/heads/master | 2020-04-23T01:37:24.271493 | 2019-02-15T07:59:51 | 2019-02-15T07:59:51 | 170,818,273 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,071 | h | #ifndef CXBASE_H
#define CXBASE_H
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <fstream>
//#define CXDF_QT
#define CXDF_CESHI
#define CXDFCLEARFREE( a ) if ( a ) { \
a->clear(); \
free( a ); \
a = NULL; \
}
#define CXDFFREE( a ) if ( a ) { \
free( a ); \
a = NULL; \
}
#define CXDFMATFREE( a, n ) if ( a ) { \
for ( int i = 0; i < n; i++ ) \
free( a[i] ); \
free( a ); \
a = NULL; \
}
#define CXDFDELETE( a ) if ( a ) { \
delete a; \
a = NULL; \
}
class memManager{
public:
memManager() {}
static void print();
static int refInt;
static int refFloat;
static int refDouble;
static int refPointer;
};
void** MallocPointers( int n );
void FreePointers( void **ptr );
int* MallocInt( int n );
void FreeInt( int *ptr );
float* MallocFloat( int n );
void FreeFloat( float *ptr );
double* MallocDouble( int n );
void FreeDouble( double *ptr );
#ifdef CXDF_CESHI
#define CXDFMallocPoints(type,a) (type **)( MallocPointers(a) )
#define CXDFFreePointers( a ) FreePointers( (void**)a ); a = NULL;
#define CXDFMallocInt( a ) MallocInt( a )
#define CXDFMallocFloat( a ) MallocFloat( a )
#define CXDFMallocDouble( a ) MallocDouble( a )
#define CXDFFreeInt( a ) FreeInt( a ); a = NULL
#define CXDFFreeFloat( a ) FreeFloat( a ); a = NULL
#define CXDFFreeDouble( a ) FreeDouble( a ); a = NULL
#else
#define CXDFMallocPoints(type,a) (type **)malloc( sizeof(void*) *a )
#define CXDFFreePointers( a ) CXDFFREE( a )
#define CXDFMallocInt( a ) (int*)malloc( sizeof(int) *a )
#define CXDFMallocFloat( a ) (float*)malloc( sizeof(float) *a )
#define CXDFMallocDouble( a ) (double*)malloc( sizeof(double) *a )
#define CXDFFreeInt( a ) CXDFFREE( a )
#define CXDFFreeFloat( a ) CXDFFREE( a )
#define CXDFFreeDouble( a ) CXDFFREE( a )
#endif
extern const float MIN_FVAR;
enum {
line_normal,
line_vertical,
line_horizontal,
};
enum {
CXEN_TEX_LINE = 0,
CXEN_TEX_POINT,
CXEN_TEX_TRIANGLEX,
// CXEN_TEX_TRIANGLEY,
CXEN_TEX_NUM
};
enum {
CXEN_BASE_CLASS = 0,
};
enum SensorType {
SENSOR_TOUCH = 0, //touch
SENSOR_GRAV, //gravity
SENSOR_ACCS, //accerleration
SENSOR_GYRO, //gyroscope
SENSOR_MAGN, //magnetics
SENSOR_NUM
};
enum {
feature_std = 0,
feature_del,
feature_acc,
feature_num,
};
struct cxPointF;
struct cxPoint3F;
bool isEqualF( float fval1, float fval2 );
typedef struct SCSize {
SCSize() {
min = 0.;
max = 0.;
size = -1.;
}
void clear() {
min = 0.;
max = 0.;
size = -1.;
}
union {
struct {
double min;
double max;
double size;
};
struct {
double val[3];
};
};
}SCSize;
typedef struct SCTimeSize {
SCTimeSize() {
minT = maxT = sizeT = 0;
local.minT = local.maxT = local.sizeT = 0;
local.baseTime = -1;
}
void clear() {
minT = maxT = sizeT = 0;
local.minT = local.maxT = local.sizeT = 0;
local.baseTime = -1;
}
union {
struct {
int64_t minT;
int64_t maxT;
int64_t sizeT;
};
struct {
int64_t val[3];
};
};
struct {
union {
struct {
int64_t minT;
int64_t maxT;
int64_t sizeT;
};
struct {
int64_t val[3];
};
};
int64_t baseTime;
} local;
}SCTimeSize;
typedef struct cxPointF {
cxPointF() {
fx = 0.f;
fy = 0.f;
}
cxPointF( float _x, float _y ) {
fx = _x;
fy = _y;
}
cxPointF& operator = ( const cxPointF &pt ) {
fx = pt.fx;
fy = pt.fy;
return *this;
}
union {
struct {
float fx;
float fy;
};
struct {
float length;
float width;
};
struct {
float wide;
float height;
};
float fval[2];
};
}cxPointF;
typedef struct cxPoint3F {
cxPoint3F() {
clear();
}
void clear() {
fx = fy = fz = 0.;
}
cxPoint3F( float _x, float _y , float _z) {
fx = _x;
fy = _y;
fz = _z;
}
cxPoint3F& operator = ( const cxPoint3F &pt ) {
fx = pt.fx;
fy = pt.fy;
fz = pt.fz;
return *this;
}
cxPoint3F& operator -= ( const cxPoint3F &pt ) {
fx -= pt.fx;
fy -= pt.fy;
fz -= pt.fz;
return *this;
}
const cxPoint3F operator - ( const cxPoint3F &pt ) {
cxPoint3F ret = *this;
ret.fx -= pt.fx;
ret.fy -= pt.fy;
ret.fz -= pt.fz;
return ret;
}
union {
struct {
float fx;
float fy;
float fz;
};
float fval[3];
};
}cxPoint3F;
typedef struct cxLineDesc {
cxLineDesc() {
k = b = fx = fy = 0.f;
type = line_normal;
}
float k;
float b;
float fx;
float fy;
int type;
}cxLineDesc;
typedef struct cxLine3dDesc {
cxLine3dDesc() {
m = n = p = t = fx = fy = fz = 0.f;
type = line_normal;
}
float m;
float n;
float p;
float t;
float fx;
float fy;
float fz;
int type;
}cxLine3dDesc;
typedef struct cxLineF {
cxLineF() {
construct();
}
void construct() {
start = vals;
end = start + 1;
rect = end + 1;
length = 0.f;
}
cxPointF *start;
cxPointF *end;
cxPointF *rect;
cxPointF vals[3];
float length;
} cxLineF;
typedef struct cxArcF {
cxArcF() {
construct();
}
void construct() {
start = vals;
end = start + 1;
ldp = end + 1;
arcRect = ldp + 1;
length[0] = length[1] = length[2] = 0.f;
}
cxPointF *start; //start point
cxPointF *end; //end point
cxPointF *ldp; //largest deviation point
cxPointF *arcRect; //length, wide
cxPointF vals[4];
float length[2]; //start
}cxArcF;
typedef struct cxVector3d {
cxVector3d() {
init();
}
void init() {
length = 0.f;
directFxy = directFyz = directFxz = 0.f;
directxy = directxz = directyz = -1;
}
float length;
float directFxy;
float directFyz;
float directFxz;
int directxy;
int directyz;
int directxz;
}cxVector3d;
typedef struct cxVector {
cxVector() {
init();
}
void init() {
length = 0.f;
directF = 0.f;
direct = -1;
}
float length;
float directF;
int direct;
}cxVector;
typedef struct cxLVector {
cxLVector() {
construct();
}
void construct() {
start = pts;
end = start + 1;
}
cxPointF *start;
cxPointF *end;
cxVector vector;
cxPointF pts[2];
}cxLineVector;
typedef struct SFeature {
SFeature() {
construct();
}
void construct() {
std = feats;
del = std + 1;
acc = del + 1;
}
void clear() {
memset( feats, 0, sizeof(cxPoint3F) * feature_num );
}
cxPointF position() {
return cxPointF( std->fx, std->fy );
}
float pressure() {
return std->fz;
}
cxPointF velocity() {
return cxPointF( del->fx, del->fy );
}
float delPressure() {
return del->fz;
}
cxPointF accelerate() {
return cxPointF( acc->fx, acc->fy );
}
float accPressure() {
return del->fz;
}
cxPoint3F *std;
cxPoint3F *del;
cxPoint3F *acc;
cxPoint3F feats[feature_num];
}SensorFeature;
typedef struct cxFeature{
cxFeature() {}
void clear() {
for ( int i = 0; i < SENSOR_NUM; i++ )
features[i].clear();
}
SensorFeature features[SENSOR_NUM];
}cxFeature;
typedef struct cxIntF {
cxIntF() {
min = max = 0.f;
}
cxIntF( float fval ) {
min = max = fval;
}
void reset( float fval ) {
min = max = fval;
}
void compare( float fval ) {
if ( min > fval )
min = fval;
if ( max < fval )
max = fval;
}
float min;
float max;
}cxIntervalF;
typedef struct cxVecInt2D {
cxVecInt2D() {}
cxIntF fx;
cxIntF fy;
} cxVectorInterval2D;
typedef struct cxVecInt3D {
cxVecInt3D() {}
void reset( float _x, float _y, float _z ) {
fx.reset( _x );
fy.reset( _y );
fz.reset( _z );
}
void reset( float *fval ) {
fx.reset( fval[0] );
fy.reset( fval[1] );
fz.reset( fval[2] );
}
void compare( float _x, float _y, float _z ) {
fx.compare( _x );
fy.compare( _y );
fz.compare( _z );
}
void compare( float *fval ) {
fx.compare( fval[0] );
fy.compare( fval[1] );
fz.compare( fval[2] );
}
cxIntF fx;
cxIntF fy;
cxIntF fz;
} cxVectorInterval3D;
//class CXBaseClass
//{
//public:
// CXBaseClass() {}
// virtual void clear() {}
// virtual int classType() {
// return 0;
// }
//};
#endif // CXBASE_H
| [
"shabin@syberos.com"
] | shabin@syberos.com |
6bf0cdd3db16ffede4924badb14a4690bb981e28 | 24fc9a99b3aee24c3fa77fcb46a3df5f2a0549c3 | /RotateVectors.h | 578be43bca4404ff29b2e8ac0f6d4898b815ec80 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | daviddoria/CriminisiLidarInpainting | b3f359a29d832d0c7ff41bf17ca8b86936369b23 | e599d9bf4732b1d94991f6348ad1c8cf6e8bce30 | refs/heads/master | 2020-05-05T07:55:05.910569 | 2012-04-26T18:58:55 | 2012-04-26T18:58:55 | 2,387,730 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,425 | h | /*=========================================================================
*
* Copyright David Doria 2011 daviddoria@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.txt
*
* 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 RotateVectors_h
#define RotateVectors_h
#include "itkImage.h"
#include "itkCovariantVector.h"
#include "itkRigid2DTransform.h"
template< class TInput, class TOutput>
class RotateVectors
{
public:
RotateVectors() {};
~RotateVectors() {};
bool operator!=( const RotateVectors & ) const
{
return false;
}
bool operator==( const RotateVectors & other ) const
{
return !(*this != other);
}
inline TOutput operator()( const TInput & A ) const
{
// Rotate the vector by 90 degrees.
TInput output;
output[0] = -A[1];
output[1] = A[0];
return output;
}
};
#endif | [
"daviddoria@gmail.com"
] | daviddoria@gmail.com |
23a2ffd694470f672c2885da5d84fe90b619bab7 | 88ae8695987ada722184307301e221e1ba3cc2fa | /third_party/webrtc/net/dcsctp/public/mock_dcsctp_socket.h | 0fd572bd94a3fa5c9c789151ef4514a7bee0f930 | [
"BSD-3-Clause",
"LicenseRef-scancode-google-patent-license-webrtc",
"LicenseRef-scancode-google-patent-license-webm",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 2,710 | h | /*
* Copyright (c) 2021 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#ifndef NET_DCSCTP_PUBLIC_MOCK_DCSCTP_SOCKET_H_
#define NET_DCSCTP_PUBLIC_MOCK_DCSCTP_SOCKET_H_
#include "net/dcsctp/public/dcsctp_socket.h"
#include "test/gmock.h"
namespace dcsctp {
class MockDcSctpSocket : public DcSctpSocketInterface {
public:
MOCK_METHOD(void,
ReceivePacket,
(rtc::ArrayView<const uint8_t> data),
(override));
MOCK_METHOD(void, HandleTimeout, (TimeoutID timeout_id), (override));
MOCK_METHOD(void, Connect, (), (override));
MOCK_METHOD(void,
RestoreFromState,
(const DcSctpSocketHandoverState&),
(override));
MOCK_METHOD(void, Shutdown, (), (override));
MOCK_METHOD(void, Close, (), (override));
MOCK_METHOD(SocketState, state, (), (const, override));
MOCK_METHOD(const DcSctpOptions&, options, (), (const, override));
MOCK_METHOD(void, SetMaxMessageSize, (size_t max_message_size), (override));
MOCK_METHOD(void,
SetStreamPriority,
(StreamID stream_id, StreamPriority priority),
(override));
MOCK_METHOD(StreamPriority,
GetStreamPriority,
(StreamID stream_id),
(const, override));
MOCK_METHOD(SendStatus,
Send,
(DcSctpMessage message, const SendOptions& send_options),
(override));
MOCK_METHOD(ResetStreamsStatus,
ResetStreams,
(rtc::ArrayView<const StreamID> outgoing_streams),
(override));
MOCK_METHOD(size_t, buffered_amount, (StreamID stream_id), (const, override));
MOCK_METHOD(size_t,
buffered_amount_low_threshold,
(StreamID stream_id),
(const, override));
MOCK_METHOD(void,
SetBufferedAmountLowThreshold,
(StreamID stream_id, size_t bytes),
(override));
MOCK_METHOD(absl::optional<Metrics>, GetMetrics, (), (const, override));
MOCK_METHOD(HandoverReadinessStatus,
GetHandoverReadiness,
(),
(const, override));
MOCK_METHOD(absl::optional<DcSctpSocketHandoverState>,
GetHandoverStateAndClose,
(),
(override));
};
} // namespace dcsctp
#endif // NET_DCSCTP_PUBLIC_MOCK_DCSCTP_SOCKET_H_
| [
"jengelh@inai.de"
] | jengelh@inai.de |
2eeab28f25d370d3f613c209f9c756f9becfbd7d | b409736df413f58391c289df73a1a6e7ae44f5b3 | /Register.h | 95580a6c331d3b9ef40d9a028f6cc15b9d9fd9ad | [] | no_license | LisaUccini00/RegisterActivities | f064b41e2942a73df2a2ea9e559225d71e9fbbdf | b56cee1d9bd9577778d8184daa65af7957875c41 | refs/heads/master | 2022-11-13T11:17:43.211483 | 2020-07-05T16:14:25 | 2020-07-05T16:14:25 | 274,951,992 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,965 | h | //
//Created by Innocenti Uccini Lisa
//
#ifndef REGISTERACTIVITIES_REGISTER_H
#define REGISTERACTIVITIES_REGISTER_H
#include <iostream>
#include <map>
#include <list>
#include <algorithm>
#include <wx/wx.h>
using namespace std;
struct Time{
int hours, minutes, seconds;
Time(int h, int m, int s): hours(h), minutes(m), seconds(s){}
bool operator!=(Time& uncorrect){
if(hours != uncorrect.hours || minutes != uncorrect.minutes || seconds != uncorrect.seconds){
return true;
}
return false;
}
bool operator==(const Time right)const{
if(hours == right.hours && minutes == right.minutes && seconds == right.seconds){
return true;
}
return false;
}
bool operator<(Time right) {
if (hours < right.hours) {
return true;
} else if (hours == right.hours) {
if (minutes < right.minutes) {
return true;
} else if (minutes == right.minutes && seconds < right.seconds) {
return true;
}
}
return false;
}
string toString(){
return std::to_string(hours)+":"+std::to_string(minutes)+":"+std::to_string(seconds);
}
};
struct Activity{
string description, title;
Time start, stop;
Activity(string titolo, string descrizione, Time inizio, Time fine):
title(titolo), description(descrizione), start(inizio), stop(fine){}
bool operator==( const Activity right)const{
if(description == right.description && title == right.title && start == right.start && stop == right.stop){
return true;
}
return false;
}
};
class Register{
private:
map<string, list <Activity>> activities; //format date: d/m/y
public:
bool addActivity(string d, Activity& a);
list<Activity> getActivities(const string& d);
void deleteActivity(string d);
};
#endif //REGISTERACTIVITIES_REGISTER_H
| [
"lisa.innocenti2@stud.unifi.it"
] | lisa.innocenti2@stud.unifi.it |
26d4900f0e271dcb2b03da4578d2075c068b9599 | 4a1d0fd0d64416fc4454567143d7b960a68b0bd2 | /Chapter-7/7-2-7.cc | 74d88e843cfac001c245fa60f37ae8efede06c59 | [] | no_license | power321/ProgrammerInterview | bf393cd4da8ba949709015e2bf132dffd1e5cdd9 | 33b1e9e70c74f7e6ff9c4ed940363f27984fa9b2 | refs/heads/master | 2021-01-10T05:18:26.711167 | 2017-02-26T13:55:41 | 2017-02-26T13:55:41 | 52,147,851 | 0 | 0 | null | 2016-02-23T11:07:11 | 2016-02-20T10:19:42 | C++ | UTF-8 | C++ | false | false | 282 | cc | #include <iostream>
#include <stdio.h>
using namespace std;
class A
{
public:
int _a;
A()
{
_a = 1;
}
void print()
{
printf("%d", _a);
}
};
class B : public A
{
public:
int _a;
B()
{
_a = 2;
}
};
int main()
{
B b;
b.print();
printf("%d\n", b._a);
return 0;
}
| [
"chenxian_0@163.com"
] | chenxian_0@163.com |
8d0c66dbe01c9965f432202bd4539e535bd99964 | 3c916c55951b7815df4966676f143bc9476f1564 | /src/main.cpp | 60868addf9d06f8ed1cecae7a50a0b6f728b1805 | [] | no_license | 42684271/hello-world | d995178857599cd576e2a74f4712bf115353e76f | ac73c21bcc78d618283e043e4a2a9949a09e8fbc | refs/heads/master | 2020-04-27T16:50:52.021314 | 2019-11-11T05:30:08 | 2019-11-11T05:30:08 | 174,495,204 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 37 | cpp | ////////////////////
///////////////
| [
"42684271@qq.com"
] | 42684271@qq.com |
c4cf557d1d38c9f01ebea6781016e35d78a99d2f | 2dc9ab0ec71fd31900173fb15a6f2c85753180c4 | /fuchsia/runners/cast/api_bindings_client.h | 8cb11926837c07dbf0fc6811aa3a8c505448b13d | [
"BSD-3-Clause"
] | permissive | Forilan/chromium | ec337c30d23c22d11fbdf814a40b9b4c26000d78 | 562b20b68672e7831054ec8f160d5f7ae940eae4 | refs/heads/master | 2023-02-28T02:43:17.744240 | 2020-05-12T02:23:44 | 2020-05-12T02:23:44 | 231,539,724 | 0 | 0 | BSD-3-Clause | 2020-05-12T02:23:45 | 2020-01-03T07:52:37 | null | UTF-8 | C++ | false | false | 2,379 | h | // Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef FUCHSIA_RUNNERS_CAST_API_BINDINGS_CLIENT_H_
#define FUCHSIA_RUNNERS_CAST_API_BINDINGS_CLIENT_H_
#include <fuchsia/web/cpp/fidl.h>
#include <vector>
#include "base/macros.h"
#include "base/optional.h"
#include "fuchsia/fidl/chromium/cast/cpp/fidl.h"
#include "fuchsia/runners/cast/named_message_port_connector.h"
// Injects scripts received from the ApiBindings service, and provides connected
// ports to the Agent.
class ApiBindingsClient {
public:
// Reads bindings definitions from |bindings_service_| at construction time.
// |on_initialization_complete| is invoked when either the initial bindings
// have been received, or on failure. The caller should use HasBindings()
// to verify that bindings were received, and may then use AttachToFrame().
ApiBindingsClient(
fidl::InterfaceHandle<chromium::cast::ApiBindings> bindings_service,
base::OnceClosure on_initialization_complete);
~ApiBindingsClient();
// Injects APIs and handles channel connections on |frame|.
// |on_error_closure|: Invoked in the event of an unrecoverable error (e.g.
// lost connection to the Agent). The callback must
// remain valid for the entire lifetime of |this|.
void AttachToFrame(fuchsia::web::Frame* frame,
NamedMessagePortConnector* connector,
base::OnceClosure on_error_callback);
// Indicates that bindings were successfully received from
// |bindings_service_|.
bool HasBindings() const;
private:
// Called when ApiBindings::GetAll() has responded.
void OnBindingsReceived(std::vector<chromium::cast::ApiBinding> bindings);
// Called when |connector_| has connected a port.
void OnPortConnected(base::StringPiece port_name,
fidl::InterfaceHandle<fuchsia::web::MessagePort> port);
base::Optional<std::vector<chromium::cast::ApiBinding>> bindings_;
fuchsia::web::Frame* frame_ = nullptr;
NamedMessagePortConnector* connector_ = nullptr;
chromium::cast::ApiBindingsPtr bindings_service_;
base::OnceClosure on_initialization_complete_;
DISALLOW_COPY_AND_ASSIGN(ApiBindingsClient);
};
#endif // FUCHSIA_RUNNERS_CAST_API_BINDINGS_CLIENT_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
c4ad52ae8440e05e0ce93a31fb16fd769fca9f5e | 7db7455b1046e731d87785ad3da7bf64f99a4088 | /GPUTool/GPUTool.cpp | 7093e53adab25512d8477aa58febca8d4047bda2 | [] | no_license | yangchenglin815/GPUTools | 95445c4e487150506ab7f70950c1529bcc848e37 | aee8d977fe645a20fdc63f9eb0731fd013b47962 | refs/heads/master | 2022-07-05T06:11:05.030937 | 2020-05-15T02:29:42 | 2020-05-15T02:29:42 | 264,076,279 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 6,689 | cpp | #include "GPUTool.h"
#include <QDebug>
#include <QVector>
#include <CPtr.h>
#include "Windows.h"
#include "DXGI.h"
using namespace std;
static const IID dxgiFactory2 =
{ 0x50c83a1c, 0xe072, 0x4c48,{ 0x87, 0xb0, 0x36, 0x30, 0xfa, 0x36, 0xa6, 0xd0 } };
string WStringToString(const wstring &wstr)
{
string str(wstr.length(), ' ');
copy(wstr.begin(), wstr.end(), str.begin());
return str;
}
GPUTool::GPUTool(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
connect(ui.pushButton, SIGNAL(clicked()), this, SLOT(onGetGPUInfo()));
connect(ui.pushButton_1, SIGNAL(clicked()), this, SLOT(onGetGPUInfo1()));
}
void GPUTool::onGetGPUInfo()
{
ui.textEdit->clear();
// 参数定义
IDXGIFactory * pFactory;
IDXGIAdapter * pAdapter;
QVector<IDXGIAdapter*> vAdapters; // 显卡
// 显卡的数量
int iAdapterNum = 0;
QString infoMsg;
// 创建一个DXGI工厂
HRESULT hr = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)(&pFactory));
if (FAILED(hr))
return;
// 枚举适配器
while (pFactory->EnumAdapters(iAdapterNum, &pAdapter) != DXGI_ERROR_NOT_FOUND) {
vAdapters.push_back(pAdapter);
++iAdapterNum;
}
// 信息输出
ui.textEdit->append(QStringLiteral("===============获取到%1块显卡===============").arg(iAdapterNum));
for (auto &it : vAdapters) {
//获取信息
DXGI_ADAPTER_DESC adapterDesc;
it->GetDesc(&adapterDesc);
wstring wstr(adapterDesc.Description);
std::string str = WStringToString(wstr);
//输出显卡信息
ui.textEdit->append(QStringLiteral("系统视频内存: %1 M").arg(adapterDesc.DedicatedSystemMemory / 1024 / 1024));
ui.textEdit->append(QStringLiteral("专用视频内存: %1 M").arg(adapterDesc.DedicatedVideoMemory / 1024 / 1024));
ui.textEdit->append(QStringLiteral("共享系统内存: %1 M").arg(adapterDesc.SharedSystemMemory / 1024 / 1024));
ui.textEdit->append(QStringLiteral("设备描述: %1").arg(str.c_str()));
ui.textEdit->append(QStringLiteral("设备ID: %1").arg(adapterDesc.DeviceId));
ui.textEdit->append(QStringLiteral("PCI ID修正版本: %1").arg(adapterDesc.Revision));
ui.textEdit->append(QStringLiteral("子系统PIC ID: %1").arg(adapterDesc.SubSysId));
ui.textEdit->append(QStringLiteral("厂商编号: %1").arg(adapterDesc.VendorId));
// 输出设备
IDXGIOutput * pOutput;
QVector<IDXGIOutput*> vOutputs;
// 输出设备数量
int iOutputNum = 0;
while (it->EnumOutputs(iOutputNum, &pOutput) != DXGI_ERROR_NOT_FOUND) {
vOutputs.push_back(pOutput);
iOutputNum++;
}
ui.textEdit->append(QStringLiteral("-----------------------------------------"));
ui.textEdit->append(QStringLiteral("获取到%1个显示设备: ").arg(iOutputNum));
for (auto &iter : vOutputs)
{
// 获取显示设备信息
DXGI_OUTPUT_DESC outputDesc;
iter->GetDesc(&outputDesc);
// 获取设备支持
UINT uModeNum = 0;
DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM;
UINT flags = DXGI_ENUM_MODES_INTERLACED;
iter->GetDisplayModeList(format, flags, &uModeNum, 0);
DXGI_MODE_DESC * pModeDescs = new DXGI_MODE_DESC[uModeNum];
iter->GetDisplayModeList(format, flags, &uModeNum, pModeDescs);
ui.textEdit->append(QStringLiteral("显示设备名称: %1").arg(WStringToString(outputDesc.DeviceName).c_str()));
ui.textEdit->append(QStringLiteral("显示设备当前分辨率: %1 * %2").arg(outputDesc.DesktopCoordinates.right - outputDesc.DesktopCoordinates.left)
.arg(outputDesc.DesktopCoordinates.bottom - outputDesc.DesktopCoordinates.top));
// 所支持的分辨率信息
ui.textEdit->append(QStringLiteral("分辨率信息: "));
for (UINT m = 0; m < uModeNum; m++) {
ui.textEdit->append(QStringLiteral("== 分辨率: %1 * %2 刷新率: %3").arg(pModeDescs[m].Width).arg(pModeDescs[m].Height)
.arg((pModeDescs[m].RefreshRate.Numerator) / (pModeDescs[m].RefreshRate.Denominator)));
}
}
ui.textEdit->append(QStringLiteral("-----------------------------------------"));
vOutputs.clear();
}
vAdapters.clear();
}
void GPUTool::onGetGPUInfo1()
{
ui.textEdit->clear();
CPtr<IDXGIFactory1> factory;
CPtr<IDXGIAdapter1> adapter;
// 参数定义
IDXGIFactory1 * pFactory;
IDXGIAdapter1 * pAdapter;
QVector<IDXGIAdapter1*> vAdapters; // 显卡
IID factoryIID = dxgiFactory2;
// 显卡的数量
int iAdapterNum = 0;
// 创建一个DXGI工厂
HRESULT hr = CreateDXGIFactory1(factoryIID, (void**)factory.Assign());
if (FAILED(hr))
return;
ui.textEdit->append("Available Video Adapters: ");
while (factory->EnumAdapters1(iAdapterNum++, adapter.Assign()) == S_OK) {
DXGI_ADAPTER_DESC desc;
char name[512] = "";
hr = adapter->GetDesc(&desc);
if (FAILED(hr))
continue;
/* ignore Microsoft's 'basic' renderer' */
if (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c)
continue;
wstring wstr(desc.Description);
std::string str = WStringToString(wstr);
//输出显卡信息
ui.textEdit->append(QStringLiteral("系统视频内存: %1 M").arg(desc.DedicatedSystemMemory / 1024 / 1024));
ui.textEdit->append(QStringLiteral("专用视频内存: %1 M").arg(desc.DedicatedVideoMemory / 1024 / 1024));
ui.textEdit->append(QStringLiteral("共享系统内存: %1 M").arg(desc.SharedSystemMemory / 1024 / 1024));
ui.textEdit->append(QStringLiteral("设备描述: %1").arg(str.c_str()));
ui.textEdit->append(QStringLiteral("设备ID: %1").arg(desc.DeviceId));
ui.textEdit->append(QStringLiteral("PCI ID修正版本: %1").arg(desc.Revision));
ui.textEdit->append(QStringLiteral("子系统PIC ID: %1").arg(desc.SubSysId));
ui.textEdit->append(QStringLiteral("厂商编号: %1").arg(desc.VendorId));
ui.textEdit->append(QStringLiteral("-----------------------------------------"));
// 输出设备
IDXGIOutput * pOutput;
QVector<IDXGIOutput*> vOutputs;
CPtr<IDXGIOutput> output;
// 输出设备数量
int iOutputNum = 0;
while (pAdapter->EnumOutputs(iOutputNum++, &output) == S_OK) {
DXGI_OUTPUT_DESC desc;
output->GetDesc(&desc);
RECT rect = desc.DesktopCoordinates;
ui.textEdit->append(QString("output %1:").arg(iOutputNum));
ui.textEdit->append(QString("pos={%1, %2}").arg(rect.left).arg(rect.top));
ui.textEdit->append(QString("size={%1, %2}").arg(rect.right - rect.left).arg(rect.bottom - rect.top));
ui.textEdit->append(QString("attached=%1").arg(desc.AttachedToDesktop ? "true" : "false"));
ui.textEdit->append(QStringLiteral("=========================================="));
}
}
}
| [
"ycldream815@gmail.com"
] | ycldream815@gmail.com |
63236254362f9fce70dca506c12b931401ef9b61 | 81f8d87a8bbeb4dd4b05d09952166426b2f530cb | /src/net.cpp | 254f5aa943792a53b099ffa3628a647dbfc880a0 | [
"MIT"
] | permissive | othila-crypto/Othila | d88c5843335525acc03f946654003caa3ff3d8f0 | 6a82036659dd6a99f941b4f13454dda61736fe07 | refs/heads/master | 2020-07-06T18:43:39.262915 | 2020-06-08T18:59:43 | 2020-06-08T18:59:43 | 203,107,917 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 74,469 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2018 The PIVX developers
// Copyright (c) 2019 The Othila developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/othila-config.h"
#endif
#include "net.h"
#include "addrman.h"
#include "chainparams.h"
#include "clientversion.h"
#include "miner.h"
#include "obfuscation.h"
#include "primitives/transaction.h"
#include "scheduler.h"
#include "ui_interface.h"
#include "wallet.h"
#ifdef WIN32
#include <string.h>
#else
#include <fcntl.h>
#endif
#ifdef USE_UPNP
#include <miniupnpc/miniupnpc.h>
#include <miniupnpc/miniwget.h>
#include <miniupnpc/upnpcommands.h>
#include <miniupnpc/upnperrors.h>
#endif
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>
// Dump addresses to peers.dat every 15 minutes (900s)
#define DUMP_ADDRESSES_INTERVAL 900
#if !defined(HAVE_MSG_NOSIGNAL) && !defined(MSG_NOSIGNAL)
#define MSG_NOSIGNAL 0
#endif
// Fix for ancient MinGW versions, that don't have defined these in ws2tcpip.h.
// Todo: Can be removed when our pull-tester is upgraded to a modern MinGW version.
#ifdef WIN32
#ifndef PROTECTION_LEVEL_UNRESTRICTED
#define PROTECTION_LEVEL_UNRESTRICTED 10
#endif
#ifndef IPV6_PROTECTION_LEVEL
#define IPV6_PROTECTION_LEVEL 23
#endif
#endif
using namespace boost;
using namespace std;
namespace
{
const int MAX_OUTBOUND_CONNECTIONS = 16;
struct ListenSocket {
SOCKET socket;
bool whitelisted;
ListenSocket(SOCKET socket, bool whitelisted) : socket(socket), whitelisted(whitelisted) {}
};
}
//
// Global state variables
//
bool fDiscover = true;
bool fListen = true;
uint64_t nLocalServices = NODE_NETWORK;
CCriticalSection cs_mapLocalHost;
map<CNetAddr, LocalServiceInfo> mapLocalHost;
static bool vfLimited[NET_MAX] = {};
static CNode* pnodeLocalHost = NULL;
uint64_t nLocalHostNonce = 0;
static std::vector<ListenSocket> vhListenSocket;
CAddrMan addrman;
int nMaxConnections = 125;
bool fAddressesInitialized = false;
std::string strSubVersion;
vector<CNode*> vNodes;
CCriticalSection cs_vNodes;
map<CInv, CDataStream> mapRelay;
deque<pair<int64_t, CInv> > vRelayExpiration;
CCriticalSection cs_mapRelay;
limitedmap<CInv, int64_t> mapAlreadyAskedFor(MAX_INV_SZ);
static deque<string> vOneShots;
CCriticalSection cs_vOneShots;
set<CNetAddr> setservAddNodeAddresses;
CCriticalSection cs_setservAddNodeAddresses;
vector<std::string> vAddedNodes;
CCriticalSection cs_vAddedNodes;
NodeId nLastNodeId = 0;
CCriticalSection cs_nLastNodeId;
static CSemaphore* semOutbound = NULL;
boost::condition_variable messageHandlerCondition;
// Signals for message handling
static CNodeSignals g_signals;
CNodeSignals& GetNodeSignals() { return g_signals; }
void AddOneShot(string strDest)
{
LOCK(cs_vOneShots);
vOneShots.push_back(strDest);
}
unsigned short GetListenPort()
{
return (unsigned short)(GetArg("-port", Params().GetDefaultPort()));
}
// find 'best' local address for a particular peer
bool GetLocal(CService& addr, const CNetAddr* paddrPeer)
{
if (!fListen)
return false;
int nBestScore = -1;
int nBestReachability = -1;
{
LOCK(cs_mapLocalHost);
for (map<CNetAddr, LocalServiceInfo>::iterator it = mapLocalHost.begin(); it != mapLocalHost.end(); it++) {
int nScore = (*it).second.nScore;
int nReachability = (*it).first.GetReachabilityFrom(paddrPeer);
if (nReachability > nBestReachability || (nReachability == nBestReachability && nScore > nBestScore)) {
addr = CService((*it).first, (*it).second.nPort);
nBestReachability = nReachability;
nBestScore = nScore;
}
}
}
return nBestScore >= 0;
}
// Get best local address for a particular peer as a CAddress
// otherwise, return the unroutable 0.0.0.0 but filled in with
// the normal parameters, since the IP may be changed to a useful
// one by discovery.
CAddress GetLocalAddress(const CNetAddr* paddrPeer)
{
CAddress ret(CService("0.0.0.0", GetListenPort()), 0);
CService addr;
if (GetLocal(addr, paddrPeer)) {
ret = CAddress(addr);
}
ret.nServices = nLocalServices;
ret.nTime = GetAdjustedTime();
return ret;
}
bool RecvLine(SOCKET hSocket, string& strLine)
{
strLine = "";
while (true) {
char c;
int nBytes = recv(hSocket, &c, 1, 0);
if (nBytes > 0) {
if (c == '\n')
continue;
if (c == '\r')
return true;
strLine += c;
if (strLine.size() >= 9000)
return true;
} else if (nBytes <= 0) {
boost::this_thread::interruption_point();
if (nBytes < 0) {
int nErr = WSAGetLastError();
if (nErr == WSAEMSGSIZE)
continue;
if (nErr == WSAEWOULDBLOCK || nErr == WSAEINTR || nErr == WSAEINPROGRESS) {
MilliSleep(10);
continue;
}
}
if (!strLine.empty())
return true;
if (nBytes == 0) {
// socket closed
LogPrint("net", "socket closed\n");
return false;
} else {
// socket error
int nErr = WSAGetLastError();
LogPrint("net", "recv failed: %s\n", NetworkErrorString(nErr));
return false;
}
}
}
}
int GetnScore(const CService& addr)
{
LOCK(cs_mapLocalHost);
if (mapLocalHost.count(addr) == LOCAL_NONE)
return 0;
return mapLocalHost[addr].nScore;
}
// Is our peer's addrLocal potentially useful as an external IP source?
bool IsPeerAddrLocalGood(CNode* pnode)
{
return fDiscover && pnode->addr.IsRoutable() && pnode->addrLocal.IsRoutable() &&
!IsLimited(pnode->addrLocal.GetNetwork());
}
// pushes our own address to a peer
void AdvertizeLocal(CNode* pnode)
{
if (fListen && pnode->fSuccessfullyConnected) {
CAddress addrLocal = GetLocalAddress(&pnode->addr);
// If discovery is enabled, sometimes give our peer the address it
// tells us that it sees us as in case it has a better idea of our
// address than we do.
if (IsPeerAddrLocalGood(pnode) && (!addrLocal.IsRoutable() ||
GetRand((GetnScore(addrLocal) > LOCAL_MANUAL) ? 8 : 2) == 0)) {
addrLocal.SetIP(pnode->addrLocal);
}
if (addrLocal.IsRoutable()) {
LogPrintf("AdvertizeLocal: advertizing address %s\n", addrLocal.ToString());
pnode->PushAddress(addrLocal);
}
}
}
// learn a new local address
bool AddLocal(const CService& addr, int nScore)
{
if (!addr.IsRoutable())
return false;
if (!fDiscover && nScore < LOCAL_MANUAL)
return false;
if (IsLimited(addr))
return false;
LogPrintf("AddLocal(%s,%i)\n", addr.ToString(), nScore);
{
LOCK(cs_mapLocalHost);
bool fAlready = mapLocalHost.count(addr) > 0;
LocalServiceInfo& info = mapLocalHost[addr];
if (!fAlready || nScore >= info.nScore) {
info.nScore = nScore + (fAlready ? 1 : 0);
info.nPort = addr.GetPort();
}
}
return true;
}
bool AddLocal(const CNetAddr& addr, int nScore)
{
return AddLocal(CService(addr, GetListenPort()), nScore);
}
bool RemoveLocal(const CService& addr)
{
LOCK(cs_mapLocalHost);
LogPrintf("RemoveLocal(%s)\n", addr.ToString());
mapLocalHost.erase(addr);
return true;
}
/** Make a particular network entirely off-limits (no automatic connects to it) */
void SetLimited(enum Network net, bool fLimited)
{
if (net == NET_UNROUTABLE)
return;
LOCK(cs_mapLocalHost);
vfLimited[net] = fLimited;
}
bool IsLimited(enum Network net)
{
LOCK(cs_mapLocalHost);
return vfLimited[net];
}
bool IsLimited(const CNetAddr& addr)
{
return IsLimited(addr.GetNetwork());
}
/** vote for a local address */
bool SeenLocal(const CService& addr)
{
{
LOCK(cs_mapLocalHost);
if (mapLocalHost.count(addr) == 0)
return false;
mapLocalHost[addr].nScore++;
}
return true;
}
/** check whether a given address is potentially local */
bool IsLocal(const CService& addr)
{
LOCK(cs_mapLocalHost);
return mapLocalHost.count(addr) > 0;
}
/** check whether a given network is one we can probably connect to */
bool IsReachable(enum Network net)
{
LOCK(cs_mapLocalHost);
return !vfLimited[net];
}
/** check whether a given address is in a network we can probably connect to */
bool IsReachable(const CNetAddr& addr)
{
enum Network net = addr.GetNetwork();
return IsReachable(net);
}
void AddressCurrentlyConnected(const CService& addr)
{
addrman.Connected(addr);
}
uint64_t CNode::nTotalBytesRecv = 0;
uint64_t CNode::nTotalBytesSent = 0;
CCriticalSection CNode::cs_totalBytesRecv;
CCriticalSection CNode::cs_totalBytesSent;
CNode* FindNode(const CNetAddr& ip)
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes)
if ((CNetAddr)pnode->addr == ip)
return (pnode);
return NULL;
}
CNode* FindNode(const CSubNet& subNet)
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes)
if (subNet.Match((CNetAddr)pnode->addr))
return (pnode);
return NULL;
}
CNode* FindNode(const std::string& addrName)
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes)
if (pnode->addrName == addrName)
return (pnode);
return NULL;
}
CNode* FindNode(const CService& addr)
{
LOCK(cs_vNodes);
for (CNode* pnode : vNodes) {
if (Params().NetworkID() == CBaseChainParams::REGTEST) {
//if using regtest, just check the IP
if ((CNetAddr)pnode->addr == (CNetAddr)addr)
return (pnode);
} else {
if (pnode->addr == addr)
return (pnode);
}
}
return NULL;
}
CNode* ConnectNode(CAddress addrConnect, const char* pszDest, bool obfuScationMaster)
{
if (pszDest == NULL) {
// We clean masternode connections in CMasternodeMan::ProcessMasternodeConnections()
// so should be safe to skip this and connect to local Hot MN on CActiveMasternode::ManageStatus()
if (IsLocal(addrConnect) && !obfuScationMaster)
return NULL;
// Look for an existing connection
CNode* pnode = FindNode((CService)addrConnect);
if (pnode) {
pnode->fObfuScationMaster = obfuScationMaster;
pnode->AddRef();
return pnode;
}
}
// Debug print
LogPrint("net", "trying connection %s lastseen=%.1fhrs\n",
pszDest ? pszDest : addrConnect.ToString(),
pszDest ? 0.0 : (double)(GetAdjustedTime() - addrConnect.nTime) / 3600.0);
// Connect
SOCKET hSocket;
bool proxyConnectionFailed = false;
if (pszDest ? ConnectSocketByName(addrConnect, hSocket, pszDest, Params().GetDefaultPort(), nConnectTimeout, &proxyConnectionFailed) :
ConnectSocket(addrConnect, hSocket, nConnectTimeout, &proxyConnectionFailed)) {
if (!IsSelectableSocket(hSocket)) {
LogPrintf("Cannot create connection: non-selectable socket created (fd >= FD_SETSIZE ?)\n");
CloseSocket(hSocket);
return NULL;
}
addrman.Attempt(addrConnect);
// Add node
CNode* pnode = new CNode(hSocket, addrConnect, pszDest ? pszDest : "", false);
pnode->AddRef();
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
pnode->nTimeConnected = GetTime();
if (obfuScationMaster) pnode->fObfuScationMaster = true;
return pnode;
} else if (!proxyConnectionFailed) {
// If connecting to the node failed, and failure is not caused by a problem connecting to
// the proxy, mark this as an attempt.
addrman.Attempt(addrConnect);
}
return NULL;
}
void CNode::CloseSocketDisconnect()
{
fDisconnect = true;
if (hSocket != INVALID_SOCKET) {
LogPrint("net", "disconnecting peer=%d\n", id);
CloseSocket(hSocket);
}
// In case this fails, we'll empty the recv buffer when the CNode is deleted
TRY_LOCK(cs_vRecvMsg, lockRecv);
if (lockRecv)
vRecvMsg.clear();
}
bool CNode::DisconnectOldProtocol(int nVersionRequired, string strLastCommand)
{
fDisconnect = false;
if (nVersion < nVersionRequired) {
LogPrintf("%s : peer=%d using obsolete version %i; disconnecting\n", __func__, id, nVersion);
PushMessage("reject", strLastCommand, REJECT_OBSOLETE, strprintf("Version must be %d or greater", ActiveProtocol()));
fDisconnect = true;
}
return fDisconnect;
}
void CNode::PushVersion()
{
int nBestHeight = g_signals.GetHeight().get_value_or(0);
// When NTP implemented, change to just nTime = GetAdjustedTime()
int64_t nTime = (fInbound ? GetAdjustedTime() : GetTime());
CAddress addrYou = (addr.IsRoutable() && !IsProxy(addr) ? addr : CAddress(CService("0.0.0.0", 0)));
CAddress addrMe = GetLocalAddress(&addr);
GetRandBytes((unsigned char*)&nLocalHostNonce, sizeof(nLocalHostNonce));
if (fLogIPs)
LogPrint("net", "send version message: version %d, blocks=%d, us=%s, them=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), addrYou.ToString(), id);
else
LogPrint("net", "send version message: version %d, blocks=%d, us=%s, peer=%d\n", PROTOCOL_VERSION, nBestHeight, addrMe.ToString(), id);
PushMessage("version", PROTOCOL_VERSION, nLocalServices, nTime, addrYou, addrMe,
nLocalHostNonce, strSubVersion, nBestHeight, true);
}
banmap_t CNode::setBanned;
CCriticalSection CNode::cs_setBanned;
bool CNode::setBannedIsDirty;
void CNode::ClearBanned()
{
{
LOCK(cs_setBanned);
setBanned.clear();
setBannedIsDirty = true;
}
DumpBanlist(); // Store banlist to Disk
uiInterface.BannedListChanged();
}
bool CNode::IsBanned(CNetAddr ip)
{
bool fResult = false;
{
LOCK(cs_setBanned);
for (banmap_t::iterator it = setBanned.begin(); it != setBanned.end(); it++)
{
CSubNet subNet = (*it).first;
CBanEntry banEntry = (*it).second;
if(subNet.Match(ip) && GetTime() < banEntry.nBanUntil)
fResult = true;
}
}
return fResult;
}
bool CNode::IsBanned(CSubNet subnet)
{
bool fResult = false;
{
LOCK(cs_setBanned);
banmap_t::iterator i = setBanned.find(subnet);
if (i != setBanned.end()) {
CBanEntry banEntry = (*i).second;
if (GetTime() < banEntry.nBanUntil)
fResult = true;
}
}
return fResult;
}
void CNode::Ban(const CNetAddr& addr, const BanReason &banReason, int64_t bantimeoffset, bool sinceUnixEpoch)
{
CSubNet subNet(addr);
Ban(subNet, banReason, bantimeoffset, sinceUnixEpoch);
}
void CNode::Ban(const CSubNet& subNet, const BanReason &banReason, int64_t bantimeoffset, bool sinceUnixEpoch)
{
CBanEntry banEntry(GetTime());
banEntry.banReason = banReason;
if (bantimeoffset <= 0)
{
bantimeoffset = GetArg("-bantime", 60*60*24); // Default 24-hour ban
sinceUnixEpoch = false;
}
banEntry.nBanUntil = (sinceUnixEpoch ? 0 : GetTime() )+bantimeoffset;
{
LOCK(cs_setBanned);
if (setBanned[subNet].nBanUntil < banEntry.nBanUntil) {
setBanned[subNet] = banEntry;
setBannedIsDirty = true;
}
else
return;
}
uiInterface.BannedListChanged();
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes) {
if (subNet.Match((CNetAddr)pnode->addr))
pnode->fDisconnect = true;
}
}
if(banReason == BanReasonManuallyAdded)
DumpBanlist(); //store banlist to disk immediately if user requested ban
}
bool CNode::Unban(const CNetAddr &addr)
{
CSubNet subNet(addr);
return Unban(subNet);
}
bool CNode::Unban(const CSubNet &subNet)
{
{
LOCK(cs_setBanned);
if (!setBanned.erase(subNet))
return false;
setBannedIsDirty = true;
}
uiInterface.BannedListChanged();
DumpBanlist(); // Store banlist to disk immediately
return true;
}
void CNode::GetBanned(banmap_t &banMap)
{
LOCK(cs_setBanned);
banMap = setBanned; // Create a thread safe copy
}
void CNode::SetBanned(const banmap_t &banMap)
{
LOCK(cs_setBanned);
setBanned = banMap;
setBannedIsDirty = true;
}
void CNode::SweepBanned()
{
int64_t now = GetTime();
bool notifyUI = false;
{
LOCK(cs_setBanned);
banmap_t::iterator it = setBanned.begin();
while(it != setBanned.end())
{
CSubNet subNet = (*it).first;
CBanEntry banEntry = (*it).second;
if(now > banEntry.nBanUntil)
{
setBanned.erase(it++);
setBannedIsDirty = true;
notifyUI = true;
LogPrint("net", "%s: Removed banned node ip/subnet from banlist.dat: %s\n", __func__, subNet.ToString());
}
else
++it;
}
}
// Update UI
if(notifyUI) {
uiInterface.BannedListChanged();
}
}
bool CNode::BannedSetIsDirty()
{
LOCK(cs_setBanned);
return setBannedIsDirty;
}
void CNode::SetBannedSetDirty(bool dirty)
{
LOCK(cs_setBanned); // Reuse setBanned lock for the isDirty flag
setBannedIsDirty = dirty;
}
std::vector<CSubNet> CNode::vWhitelistedRange;
CCriticalSection CNode::cs_vWhitelistedRange;
bool CNode::IsWhitelistedRange(const CNetAddr& addr)
{
LOCK(cs_vWhitelistedRange);
BOOST_FOREACH (const CSubNet& subnet, vWhitelistedRange) {
if (subnet.Match(addr))
return true;
}
return false;
}
void CNode::AddWhitelistedRange(const CSubNet& subnet)
{
LOCK(cs_vWhitelistedRange);
vWhitelistedRange.push_back(subnet);
}
#undef X
#define X(name) stats.name = name
void CNode::copyStats(CNodeStats& stats)
{
stats.nodeid = this->GetId();
X(nServices);
X(nLastSend);
X(nLastRecv);
X(nTimeConnected);
X(nTimeOffset);
X(addrName);
X(nVersion);
X(cleanSubVer);
X(fInbound);
X(nStartingHeight);
X(nSendBytes);
X(nRecvBytes);
X(fWhitelisted);
// It is common for nodes with good ping times to suddenly become lagged,
// due to a new block arriving or other large transfer.
// Merely reporting pingtime might fool the caller into thinking the node was still responsive,
// since pingtime does not update until the ping is complete, which might take a while.
// So, if a ping is taking an unusually long time in flight,
// the caller can immediately detect that this is happening.
int64_t nPingUsecWait = 0;
if ((0 != nPingNonceSent) && (0 != nPingUsecStart)) {
nPingUsecWait = GetTimeMicros() - nPingUsecStart;
}
// Raw ping time is in microseconds, but show it to user as whole seconds (OTH users should be well used to small numbers with many decimal places by now :)
stats.dPingTime = (((double)nPingUsecTime) / 1e6);
stats.dPingWait = (((double)nPingUsecWait) / 1e6);
// Leave string empty if addrLocal invalid (not filled in yet)
stats.addrLocal = addrLocal.IsValid() ? addrLocal.ToString() : "";
}
#undef X
// requires LOCK(cs_vRecvMsg)
bool CNode::ReceiveMsgBytes(const char* pch, unsigned int nBytes)
{
while (nBytes > 0) {
// Get current incomplete message, or create a new one
if (vRecvMsg.empty() ||
vRecvMsg.back().complete())
vRecvMsg.push_back(CNetMessage(SER_NETWORK, nRecvVersion));
CNetMessage& msg = vRecvMsg.back();
// Absorb network data
int handled;
if (!msg.in_data)
handled = msg.readHeader(pch, nBytes);
else
handled = msg.readData(pch, nBytes);
if (handled < 0)
return false;
if (msg.in_data && msg.hdr.nMessageSize > MAX_PROTOCOL_MESSAGE_LENGTH) {
LogPrint("net", "Oversized message from peer=%i, disconnecting", GetId());
return false;
}
pch += handled;
nBytes -= handled;
if (msg.complete()) {
msg.nTime = GetTimeMicros();
messageHandlerCondition.notify_one();
}
}
return true;
}
int CNetMessage::readHeader(const char* pch, unsigned int nBytes)
{
// Copy data to temporary parsing buffer
unsigned int nRemaining = 24 - nHdrPos;
unsigned int nCopy = std::min(nRemaining, nBytes);
memcpy(&hdrbuf[nHdrPos], pch, nCopy);
nHdrPos += nCopy;
// If header incomplete, exit
if (nHdrPos < 24)
return nCopy;
// Deserialize to CMessageHeader
try {
hdrbuf >> hdr;
} catch (const std::exception&) {
return -1;
}
// Reject messages larger than MAX_SIZE
if (hdr.nMessageSize > MAX_SIZE)
return -1;
// Switch state to reading message data
in_data = true;
return nCopy;
}
int CNetMessage::readData(const char* pch, unsigned int nBytes)
{
unsigned int nRemaining = hdr.nMessageSize - nDataPos;
unsigned int nCopy = std::min(nRemaining, nBytes);
if (vRecv.size() < nDataPos + nCopy) {
// Allocate up to 256 KiB ahead, but never more than the total message size.
vRecv.resize(std::min(hdr.nMessageSize, nDataPos + nCopy + 256 * 1024));
}
memcpy(&vRecv[nDataPos], pch, nCopy);
nDataPos += nCopy;
return nCopy;
}
void SocketSendData(CNode* pnode)
{
std::deque<CSerializeData>::iterator it = pnode->vSendMsg.begin();
while (it != pnode->vSendMsg.end()) {
const CSerializeData& data = *it;
assert(data.size() > pnode->nSendOffset);
int nBytes = send(pnode->hSocket, &data[pnode->nSendOffset], data.size() - pnode->nSendOffset, MSG_NOSIGNAL | MSG_DONTWAIT);
if (nBytes > 0) {
pnode->nLastSend = GetTime();
pnode->nSendBytes += nBytes;
pnode->nSendOffset += nBytes;
pnode->RecordBytesSent(nBytes);
if (pnode->nSendOffset == data.size()) {
pnode->nSendOffset = 0;
pnode->nSendSize -= data.size();
it++;
} else {
// Could not send full message; stop sending more
break;
}
} else {
if (nBytes < 0) {
// Error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) {
LogPrintf("socket send error %s\n", NetworkErrorString(nErr));
pnode->CloseSocketDisconnect();
}
}
// Couldn't send anything at all
break;
}
}
if (it == pnode->vSendMsg.end()) {
assert(pnode->nSendOffset == 0);
assert(pnode->nSendSize == 0);
}
pnode->vSendMsg.erase(pnode->vSendMsg.begin(), it);
}
static list<CNode*> vNodesDisconnected;
void ThreadSocketHandler()
{
unsigned int nPrevNodeCount = 0;
while (true) {
//
// Disconnect nodes
//
{
LOCK(cs_vNodes);
// Disconnect unused nodes
vector<CNode*> vNodesCopy = vNodes;
BOOST_FOREACH (CNode* pnode, vNodesCopy) {
if (pnode->fDisconnect ||
(pnode->GetRefCount() <= 0 && pnode->vRecvMsg.empty() && pnode->nSendSize == 0 && pnode->ssSend.empty())) {
// Remove from vNodes
vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end());
// Release outbound grant (if any)
pnode->grantOutbound.Release();
// Close socket and cleanup
pnode->CloseSocketDisconnect();
// Hold in disconnected pool until all refs are released
if (pnode->fNetworkNode || pnode->fInbound)
pnode->Release();
vNodesDisconnected.push_back(pnode);
}
}
}
{
// Delete disconnected nodes
list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
BOOST_FOREACH (CNode* pnode, vNodesDisconnectedCopy) {
// Wait until threads are done using it
if (pnode->GetRefCount() <= 0) {
bool fDelete = false;
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend) {
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv) {
TRY_LOCK(pnode->cs_inventory, lockInv);
if (lockInv)
fDelete = true;
}
}
}
if (fDelete) {
vNodesDisconnected.remove(pnode);
delete pnode;
}
}
}
}
size_t vNodesSize;
{
LOCK(cs_vNodes);
vNodesSize = vNodes.size();
}
if(vNodesSize != nPrevNodeCount) {
nPrevNodeCount = vNodesSize;
uiInterface.NotifyNumConnectionsChanged(nPrevNodeCount);
}
//
// Find which sockets have data to receive
//
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 50000; // frequency to poll pnode->vSend
fd_set fdsetRecv;
fd_set fdsetSend;
fd_set fdsetError;
FD_ZERO(&fdsetRecv);
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
SOCKET hSocketMax = 0;
bool have_fds = false;
BOOST_FOREACH (const ListenSocket& hListenSocket, vhListenSocket) {
FD_SET(hListenSocket.socket, &fdsetRecv);
hSocketMax = max(hSocketMax, hListenSocket.socket);
have_fds = true;
}
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes) {
if (pnode->hSocket == INVALID_SOCKET)
continue;
FD_SET(pnode->hSocket, &fdsetError);
hSocketMax = max(hSocketMax, pnode->hSocket);
have_fds = true;
// Implement the following logic:
// * If there is data to send, select() for sending data. As this only
// happens when optimistic write failed, we choose to first drain the
// write buffer in this case before receiving more. This avoids
// needlessly queueing received data, if the remote peer is not themselves
// receiving data. This means properly utilizing TCP flow control signalling.
// * Otherwise, if there is no (complete) message in the receive buffer,
// or there is space left in the buffer, select() for receiving data.
// * (if neither of the above applies, there is certainly one message
// in the receiver buffer ready to be processed).
// Together, that means that at least one of the following is always possible,
// so we don't deadlock:
// * We send some data.
// * We wait for data to be received (and disconnect after timeout).
// * We process a message in the buffer (message handler thread).
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend && !pnode->vSendMsg.empty()) {
FD_SET(pnode->hSocket, &fdsetSend);
continue;
}
}
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv && (pnode->vRecvMsg.empty() || !pnode->vRecvMsg.front().complete() ||
pnode->GetTotalRecvSize() <= ReceiveFloodSize()))
FD_SET(pnode->hSocket, &fdsetRecv);
}
}
}
int nSelect = select(have_fds ? hSocketMax + 1 : 0,
&fdsetRecv, &fdsetSend, &fdsetError, &timeout);
boost::this_thread::interruption_point();
if (nSelect == SOCKET_ERROR) {
if (have_fds) {
int nErr = WSAGetLastError();
LogPrintf("socket select error %s\n", NetworkErrorString(nErr));
for (unsigned int i = 0; i <= hSocketMax; i++)
FD_SET(i, &fdsetRecv);
}
FD_ZERO(&fdsetSend);
FD_ZERO(&fdsetError);
MilliSleep(timeout.tv_usec / 1000);
}
//
// Accept new connections
//
BOOST_FOREACH (const ListenSocket& hListenSocket, vhListenSocket) {
if (hListenSocket.socket != INVALID_SOCKET && FD_ISSET(hListenSocket.socket, &fdsetRecv)) {
struct sockaddr_storage sockaddr;
socklen_t len = sizeof(sockaddr);
SOCKET hSocket = accept(hListenSocket.socket, (struct sockaddr*)&sockaddr, &len);
CAddress addr;
int nInbound = 0;
if (hSocket != INVALID_SOCKET)
if (!addr.SetSockAddr((const struct sockaddr*)&sockaddr))
LogPrintf("Warning: Unknown socket family\n");
bool whitelisted = hListenSocket.whitelisted || CNode::IsWhitelistedRange(addr);
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes)
if (pnode->fInbound)
nInbound++;
}
if (hSocket == INVALID_SOCKET) {
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK)
LogPrintf("socket error accept failed: %s\n", NetworkErrorString(nErr));
} else if (!IsSelectableSocket(hSocket)) {
LogPrintf("connection from %s dropped: non-selectable socket\n", addr.ToString());
CloseSocket(hSocket);
} else if (nInbound >= nMaxConnections - MAX_OUTBOUND_CONNECTIONS) {
LogPrint("net", "connection from %s dropped (full)\n", addr.ToString());
CloseSocket(hSocket);
} else if (CNode::IsBanned(addr) && !whitelisted) {
LogPrintf("connection from %s dropped (banned)\n", addr.ToString());
CloseSocket(hSocket);
} else {
CNode* pnode = new CNode(hSocket, addr, "", true);
pnode->AddRef();
pnode->fWhitelisted = whitelisted;
{
LOCK(cs_vNodes);
vNodes.push_back(pnode);
}
}
}
}
//
// Service each socket
//
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH (CNode* pnode, vNodesCopy)
pnode->AddRef();
}
BOOST_FOREACH (CNode* pnode, vNodesCopy) {
boost::this_thread::interruption_point();
//
// Receive
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetRecv) || FD_ISSET(pnode->hSocket, &fdsetError)) {
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv) {
{
// typical socket buffer is 8K-64K
char pchBuf[0x10000];
int nBytes = recv(pnode->hSocket, pchBuf, sizeof(pchBuf), MSG_DONTWAIT);
if (nBytes > 0) {
if (!pnode->ReceiveMsgBytes(pchBuf, nBytes))
pnode->CloseSocketDisconnect();
pnode->nLastRecv = GetTime();
pnode->nRecvBytes += nBytes;
pnode->RecordBytesRecv(nBytes);
} else if (nBytes == 0) {
// socket closed gracefully
if (!pnode->fDisconnect)
LogPrint("net", "socket closed\n");
pnode->CloseSocketDisconnect();
} else if (nBytes < 0) {
// error
int nErr = WSAGetLastError();
if (nErr != WSAEWOULDBLOCK && nErr != WSAEMSGSIZE && nErr != WSAEINTR && nErr != WSAEINPROGRESS) {
if (!pnode->fDisconnect)
LogPrintf("socket recv error %s\n", NetworkErrorString(nErr));
pnode->CloseSocketDisconnect();
}
}
}
}
}
//
// Send
//
if (pnode->hSocket == INVALID_SOCKET)
continue;
if (FD_ISSET(pnode->hSocket, &fdsetSend)) {
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
SocketSendData(pnode);
}
//
// Inactivity checking
//
int64_t nTime = GetTime();
if (nTime - pnode->nTimeConnected > 60) {
if (pnode->nLastRecv == 0 || pnode->nLastSend == 0) {
LogPrint("net", "socket no message in first 60 seconds, %d %d from %d\n", pnode->nLastRecv != 0, pnode->nLastSend != 0, pnode->id);
pnode->fDisconnect = true;
} else if (nTime - pnode->nLastSend > TIMEOUT_INTERVAL) {
LogPrintf("socket sending timeout: %is\n", nTime - pnode->nLastSend);
pnode->fDisconnect = true;
} else if (nTime - pnode->nLastRecv > (pnode->nVersion > BIP0031_VERSION ? TIMEOUT_INTERVAL : 90 * 60)) {
LogPrintf("socket receive timeout: %is\n", nTime - pnode->nLastRecv);
pnode->fDisconnect = true;
} else if (pnode->nPingNonceSent && pnode->nPingUsecStart + TIMEOUT_INTERVAL * 1000000 < GetTimeMicros()) {
LogPrintf("ping timeout: %fs\n", 0.000001 * (GetTimeMicros() - pnode->nPingUsecStart));
pnode->fDisconnect = true;
}
}
}
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodesCopy)
pnode->Release();
}
}
}
#ifdef USE_UPNP
void ThreadMapPort()
{
std::string port = strprintf("%u", GetListenPort());
const char* multicastif = 0;
const char* minissdpdpath = 0;
struct UPNPDev* devlist = 0;
char lanaddr[64];
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0);
#elif MINIUPNPC_API_VERSION < 14
/* miniupnpc 1.6 */
int error = 0;
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, &error);
#else
/* miniupnpc 1.9.20150730 */
int error = 0;
devlist = upnpDiscover(2000, multicastif, minissdpdpath, 0, 0, 2, &error);
#endif
struct UPNPUrls urls;
struct IGDdatas data;
int r;
r = UPNP_GetValidIGD(devlist, &urls, &data, lanaddr, sizeof(lanaddr));
if (r == 1) {
if (fDiscover) {
char externalIPAddress[40];
r = UPNP_GetExternalIPAddress(urls.controlURL, data.first.servicetype, externalIPAddress);
if (r != UPNPCOMMAND_SUCCESS)
LogPrintf("UPnP: GetExternalIPAddress() returned %d\n", r);
else {
if (externalIPAddress[0]) {
LogPrintf("UPnP: ExternalIPAddress = %s\n", externalIPAddress);
AddLocal(CNetAddr(externalIPAddress), LOCAL_UPNP);
} else
LogPrintf("UPnP: GetExternalIPAddress failed.\n");
}
}
string strDesc = "OTH " + FormatFullVersion();
try {
while (true) {
#ifndef UPNPDISCOVER_SUCCESS
/* miniupnpc 1.5 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0);
#else
/* miniupnpc 1.6 */
r = UPNP_AddPortMapping(urls.controlURL, data.first.servicetype,
port.c_str(), port.c_str(), lanaddr, strDesc.c_str(), "TCP", 0, "0");
#endif
if (r != UPNPCOMMAND_SUCCESS)
LogPrintf("AddPortMapping(%s, %s, %s) failed with code %d (%s)\n",
port, port, lanaddr, r, strupnperror(r));
else
LogPrintf("UPnP Port Mapping successful.\n");
;
MilliSleep(20 * 60 * 1000); // Refresh every 20 minutes
}
} catch (boost::thread_interrupted) {
r = UPNP_DeletePortMapping(urls.controlURL, data.first.servicetype, port.c_str(), "TCP", 0);
LogPrintf("UPNP_DeletePortMapping() returned : %d\n", r);
freeUPNPDevlist(devlist);
devlist = 0;
FreeUPNPUrls(&urls);
throw;
}
} else {
LogPrintf("No valid UPnP IGDs found\n");
freeUPNPDevlist(devlist);
devlist = 0;
if (r != 0)
FreeUPNPUrls(&urls);
}
}
void MapPort(bool fUseUPnP)
{
static boost::thread* upnp_thread = NULL;
if (fUseUPnP) {
if (upnp_thread) {
upnp_thread->interrupt();
upnp_thread->join();
delete upnp_thread;
}
upnp_thread = new boost::thread(boost::bind(&TraceThread<void (*)()>, "upnp", &ThreadMapPort));
} else if (upnp_thread) {
upnp_thread->interrupt();
upnp_thread->join();
delete upnp_thread;
upnp_thread = NULL;
}
}
#else
void MapPort(bool)
{
// Intentionally left blank.
}
#endif
void ThreadDNSAddressSeed()
{
// goal: only query DNS seeds if address need is acute
if ((addrman.size() > 0) &&
(!GetBoolArg("-forcednsseed", false))) {
MilliSleep(11 * 1000);
LOCK(cs_vNodes);
if (vNodes.size() >= 2) {
LogPrintf("P2P peers available. Skipped DNS seeding.\n");
return;
}
}
const vector<CDNSSeedData>& vSeeds = Params().DNSSeeds();
int found = 0;
LogPrintf("Loading addresses from DNS seeds (could take a while)\n");
BOOST_FOREACH (const CDNSSeedData& seed, vSeeds) {
if (HaveNameProxy()) {
AddOneShot(seed.host);
} else {
vector<CNetAddr> vIPs;
vector<CAddress> vAdd;
if (LookupHost(seed.host.c_str(), vIPs)) {
BOOST_FOREACH (CNetAddr& ip, vIPs) {
int nOneDay = 24 * 3600;
CAddress addr = CAddress(CService(ip, Params().GetDefaultPort()));
addr.nTime = GetTime() - 3 * nOneDay - GetRand(4 * nOneDay); // use a random age between 3 and 7 days old
vAdd.push_back(addr);
found++;
}
}
addrman.Add(vAdd, CNetAddr(seed.name, true));
}
}
LogPrintf("%d addresses found from DNS seeds\n", found);
}
void DumpAddresses()
{
int64_t nStart = GetTimeMillis();
CAddrDB adb;
adb.Write(addrman);
LogPrint("net", "Flushed %d addresses to peers.dat %dms\n",
addrman.size(), GetTimeMillis() - nStart);
}
void DumpData()
{
DumpAddresses();
DumpBanlist();
}
void static ProcessOneShot()
{
string strDest;
{
LOCK(cs_vOneShots);
if (vOneShots.empty())
return;
strDest = vOneShots.front();
vOneShots.pop_front();
}
CAddress addr;
CSemaphoreGrant grant(*semOutbound, true);
if (grant) {
if (!OpenNetworkConnection(addr, &grant, strDest.c_str(), true))
AddOneShot(strDest);
}
}
void ThreadOpenConnections()
{
// Connect to specific addresses
if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) {
for (int64_t nLoop = 0;; nLoop++) {
ProcessOneShot();
BOOST_FOREACH (string strAddr, mapMultiArgs["-connect"]) {
CAddress addr;
OpenNetworkConnection(addr, NULL, strAddr.c_str());
for (int i = 0; i < 10 && i < nLoop; i++) {
MilliSleep(500);
}
}
MilliSleep(500);
}
}
// Initiate network connections
int64_t nStart = GetTime();
while (true) {
ProcessOneShot();
MilliSleep(500);
CSemaphoreGrant grant(*semOutbound);
boost::this_thread::interruption_point();
// Add seed nodes if DNS seeds are all down (an infrastructure attack?).
if (addrman.size() == 0 && (GetTime() - nStart > 60)) {
static bool done = false;
if (!done) {
LogPrintf("Adding fixed seed nodes as DNS doesn't seem to be available.\n");
addrman.Add(Params().FixedSeeds(), CNetAddr("127.0.0.1"));
done = true;
}
}
//
// Choose an address to connect to based on most recently seen
//
CAddress addrConnect;
// Only connect out to one peer per network group (/16 for IPv4).
// Do this here so we don't have to critsect vNodes inside mapAddresses critsect.
int nOutbound = 0;
set<vector<unsigned char> > setConnected;
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes) {
if (!pnode->fInbound) {
setConnected.insert(pnode->addr.GetGroup());
nOutbound++;
}
}
}
int64_t nANow = GetAdjustedTime();
int nTries = 0;
while (true) {
CAddrInfo addr = addrman.Select();
// if we selected an invalid address, restart
if (!addr.IsValid() || setConnected.count(addr.GetGroup()) || IsLocal(addr))
break;
// If we didn't find an appropriate destination after trying 100 addresses fetched from addrman,
// stop this loop, and let the outer loop run again (which sleeps, adds seed nodes, recalculates
// already-connected network ranges, ...) before trying new addrman addresses.
nTries++;
if (nTries > 100)
break;
if (IsLimited(addr))
continue;
// only consider very recently tried nodes after 30 failed attempts
if (nANow - addr.nLastTry < 600 && nTries < 30)
continue;
// do not allow non-default ports, unless after 50 invalid addresses selected already
if (addr.GetPort() != Params().GetDefaultPort() && nTries < 50)
continue;
addrConnect = addr;
break;
}
if (addrConnect.IsValid())
OpenNetworkConnection(addrConnect, &grant);
}
}
void ThreadOpenAddedConnections()
{
{
LOCK(cs_vAddedNodes);
vAddedNodes = mapMultiArgs["-addnode"];
}
if (HaveNameProxy()) {
while (true) {
list<string> lAddresses(0);
{
LOCK(cs_vAddedNodes);
BOOST_FOREACH (string& strAddNode, vAddedNodes)
lAddresses.push_back(strAddNode);
}
BOOST_FOREACH (string& strAddNode, lAddresses) {
CAddress addr;
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(addr, &grant, strAddNode.c_str());
MilliSleep(500);
}
MilliSleep(120000); // Retry every 2 minutes
}
}
for (unsigned int i = 0; true; i++) {
list<string> lAddresses(0);
{
LOCK(cs_vAddedNodes);
BOOST_FOREACH (string& strAddNode, vAddedNodes)
lAddresses.push_back(strAddNode);
}
list<vector<CService> > lservAddressesToAdd(0);
BOOST_FOREACH (string& strAddNode, lAddresses) {
vector<CService> vservNode(0);
if (Lookup(strAddNode.c_str(), vservNode, Params().GetDefaultPort(), fNameLookup, 0)) {
lservAddressesToAdd.push_back(vservNode);
{
LOCK(cs_setservAddNodeAddresses);
BOOST_FOREACH (CService& serv, vservNode)
setservAddNodeAddresses.insert(serv);
}
}
}
// Attempt to connect to each IP for each addnode entry until at least one is successful per addnode entry
// (keeping in mind that addnode entries can have many IPs if fNameLookup)
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes)
for (list<vector<CService> >::iterator it = lservAddressesToAdd.begin(); it != lservAddressesToAdd.end(); it++)
BOOST_FOREACH (CService& addrNode, *(it))
if (pnode->addr == addrNode) {
it = lservAddressesToAdd.erase(it);
it--;
break;
}
}
BOOST_FOREACH (vector<CService>& vserv, lservAddressesToAdd) {
CSemaphoreGrant grant(*semOutbound);
OpenNetworkConnection(CAddress(vserv[i % vserv.size()]), &grant);
MilliSleep(500);
}
MilliSleep(120000); // Retry every 2 minutes
}
}
// if successful, this moves the passed grant to the constructed node
bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant* grantOutbound, const char* pszDest, bool fOneShot)
{
//
// Initiate outbound network connection
//
boost::this_thread::interruption_point();
if (!pszDest) {
if (IsLocal(addrConnect) ||
FindNode((CNetAddr)addrConnect) || CNode::IsBanned(addrConnect) ||
FindNode(addrConnect.ToStringIPPort()))
return false;
} else if (FindNode(pszDest))
return false;
CNode* pnode = ConnectNode(addrConnect, pszDest);
boost::this_thread::interruption_point();
if (!pnode)
return false;
if (grantOutbound)
grantOutbound->MoveTo(pnode->grantOutbound);
pnode->fNetworkNode = true;
if (fOneShot)
pnode->fOneShot = true;
return true;
}
void ThreadMessageHandler()
{
boost::mutex condition_mutex;
boost::unique_lock<boost::mutex> lock(condition_mutex);
SetThreadPriority(THREAD_PRIORITY_BELOW_NORMAL);
while (true) {
vector<CNode*> vNodesCopy;
{
LOCK(cs_vNodes);
vNodesCopy = vNodes;
BOOST_FOREACH (CNode* pnode, vNodesCopy) {
pnode->AddRef();
}
}
// Poll the connected nodes for messages
CNode* pnodeTrickle = NULL;
if (!vNodesCopy.empty())
pnodeTrickle = vNodesCopy[GetRand(vNodesCopy.size())];
bool fSleep = true;
BOOST_FOREACH (CNode* pnode, vNodesCopy) {
if (pnode->fDisconnect)
continue;
// Receive messages
{
TRY_LOCK(pnode->cs_vRecvMsg, lockRecv);
if (lockRecv) {
if (!g_signals.ProcessMessages(pnode))
pnode->CloseSocketDisconnect();
if (pnode->nSendSize < SendBufferSize()) {
if (!pnode->vRecvGetData.empty() || (!pnode->vRecvMsg.empty() && pnode->vRecvMsg[0].complete())) {
fSleep = false;
}
}
}
}
boost::this_thread::interruption_point();
// Send messages
{
TRY_LOCK(pnode->cs_vSend, lockSend);
if (lockSend)
g_signals.SendMessages(pnode, pnode == pnodeTrickle || pnode->fWhitelisted);
}
boost::this_thread::interruption_point();
}
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodesCopy)
pnode->Release();
}
if (fSleep)
messageHandlerCondition.timed_wait(lock, boost::posix_time::microsec_clock::universal_time() + boost::posix_time::milliseconds(100));
}
}
// ppcoin: stake minter thread
void static ThreadStakeMinter()
{
boost::this_thread::interruption_point();
LogPrintf("ThreadStakeMinter started\n");
CWallet* pwallet = pwalletMain;
try {
BitcoinMiner(pwallet, true);
boost::this_thread::interruption_point();
} catch (std::exception& e) {
LogPrintf("ThreadStakeMinter() exception \n");
} catch (...) {
LogPrintf("ThreadStakeMinter() error \n");
}
LogPrintf("ThreadStakeMinter exiting,\n");
}
bool BindListenPort(const CService& addrBind, string& strError, bool fWhitelisted)
{
strError = "";
int nOne = 1;
// Create socket for listening for incoming connections
struct sockaddr_storage sockaddr;
socklen_t len = sizeof(sockaddr);
if (!addrBind.GetSockAddr((struct sockaddr*)&sockaddr, &len)) {
strError = strprintf("Error: Bind address family for %s not supported", addrBind.ToString());
LogPrintf("%s\n", strError);
return false;
}
SOCKET hListenSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP);
if (hListenSocket == INVALID_SOCKET) {
strError = strprintf("Error: Couldn't open socket for incoming connections (socket returned error %s)", NetworkErrorString(WSAGetLastError()));
LogPrintf("%s\n", strError);
return false;
}
if (!IsSelectableSocket(hListenSocket)) {
strError = "Error: Couldn't create a listenable socket for incoming connections";
LogPrintf("%s\n", strError);
return false;
}
#ifndef WIN32
#ifdef SO_NOSIGPIPE
// Different way of disabling SIGPIPE on BSD
setsockopt(hListenSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&nOne, sizeof(int));
#endif
// Allow binding if the port is still in TIME_WAIT state after
// the program was closed and restarted. Not an issue on windows!
setsockopt(hListenSocket, SOL_SOCKET, SO_REUSEADDR, (void*)&nOne, sizeof(int));
#endif
// Set to non-blocking, incoming connections will also inherit this
if (!SetSocketNonBlocking(hListenSocket, true)) {
strError = strprintf("BindListenPort: Setting listening socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError()));
LogPrintf("%s\n", strError);
return false;
}
// some systems don't have IPV6_V6ONLY but are always v6only; others do have the option
// and enable it by default or not. Try to enable it, if possible.
if (addrBind.IsIPv6()) {
#ifdef IPV6_V6ONLY
#ifdef WIN32
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (const char*)&nOne, sizeof(int));
#else
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_V6ONLY, (void*)&nOne, sizeof(int));
#endif
#endif
#ifdef WIN32
int nProtLevel = PROTECTION_LEVEL_UNRESTRICTED;
setsockopt(hListenSocket, IPPROTO_IPV6, IPV6_PROTECTION_LEVEL, (const char*)&nProtLevel, sizeof(int));
#endif
}
if (::bind(hListenSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) {
int nErr = WSAGetLastError();
if (nErr == WSAEADDRINUSE)
strError = strprintf(_("Unable to bind to %s on this computer. Othila Core is probably already running."), addrBind.ToString());
else
strError = strprintf(_("Unable to bind to %s on this computer (bind returned error %s)"), addrBind.ToString(), NetworkErrorString(nErr));
LogPrintf("%s\n", strError);
CloseSocket(hListenSocket);
return false;
}
LogPrintf("Bound to %s\n", addrBind.ToString());
// Listen for incoming connections
if (listen(hListenSocket, SOMAXCONN) == SOCKET_ERROR) {
strError = strprintf(_("Error: Listening for incoming connections failed (listen returned error %s)"), NetworkErrorString(WSAGetLastError()));
LogPrintf("%s\n", strError);
CloseSocket(hListenSocket);
return false;
}
vhListenSocket.push_back(ListenSocket(hListenSocket, fWhitelisted));
if (addrBind.IsRoutable() && fDiscover && !fWhitelisted)
AddLocal(addrBind, LOCAL_BIND);
return true;
}
void static Discover(boost::thread_group& threadGroup)
{
if (!fDiscover)
return;
#ifdef WIN32
// Get local host IP
char pszHostName[256] = "";
if (gethostname(pszHostName, sizeof(pszHostName)) != SOCKET_ERROR) {
vector<CNetAddr> vaddr;
if (LookupHost(pszHostName, vaddr)) {
BOOST_FOREACH (const CNetAddr& addr, vaddr) {
if (AddLocal(addr, LOCAL_IF))
LogPrintf("%s: %s - %s\n", __func__, pszHostName, addr.ToString());
}
}
}
#else
// Get local host ip
struct ifaddrs* myaddrs;
if (getifaddrs(&myaddrs) == 0) {
for (struct ifaddrs* ifa = myaddrs; ifa != NULL; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == NULL) continue;
if ((ifa->ifa_flags & IFF_UP) == 0) continue;
if (strcmp(ifa->ifa_name, "lo") == 0) continue;
if (strcmp(ifa->ifa_name, "lo0") == 0) continue;
if (ifa->ifa_addr->sa_family == AF_INET) {
struct sockaddr_in* s4 = (struct sockaddr_in*)(ifa->ifa_addr);
CNetAddr addr(s4->sin_addr);
if (AddLocal(addr, LOCAL_IF))
LogPrintf("%s: IPv4 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
} else if (ifa->ifa_addr->sa_family == AF_INET6) {
struct sockaddr_in6* s6 = (struct sockaddr_in6*)(ifa->ifa_addr);
CNetAddr addr(s6->sin6_addr);
if (AddLocal(addr, LOCAL_IF))
LogPrintf("%s: IPv6 %s: %s\n", __func__, ifa->ifa_name, addr.ToString());
}
}
freeifaddrs(myaddrs);
}
#endif
}
void StartNode(boost::thread_group& threadGroup, CScheduler& scheduler)
{
uiInterface.InitMessage(_("Loading addresses..."));
// Load addresses for peers.dat
int64_t nStart = GetTimeMillis();
{
CAddrDB adb;
if (!adb.Read(addrman))
LogPrintf("Invalid or missing peers.dat; recreating\n");
}
//try to read stored banlist
CBanDB bandb;
banmap_t banmap;
if (!bandb.Read(banmap))
LogPrintf("Invalid or missing banlist.dat; recreating\n");
CNode::SetBanned(banmap); //thread save setter
CNode::SetBannedSetDirty(false); //no need to write down just read or nonexistent data
CNode::SweepBanned(); //sweap out unused entries
// Initialize random numbers. Even when rand() is only usable for trivial use-cases most nodes should have a different
// seed after all the file-IO done at this point. Should be good enough even when nodes are started via scripts.
srand(time(NULL));
LogPrintf("Loaded %i addresses from peers.dat %dms\n",
addrman.size(), GetTimeMillis() - nStart);
fAddressesInitialized = true;
if (semOutbound == NULL) {
// initialize semaphore
int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, nMaxConnections);
semOutbound = new CSemaphore(nMaxOutbound);
}
if (pnodeLocalHost == NULL)
pnodeLocalHost = new CNode(INVALID_SOCKET, CAddress(CService("127.0.0.1", 0), nLocalServices));
Discover(threadGroup);
//
// Start threads
//
if (!GetBoolArg("-dnsseed", true))
LogPrintf("DNS seeding disabled\n");
else
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "dnsseed", &ThreadDNSAddressSeed));
// Map ports with UPnP
MapPort(GetBoolArg("-upnp", DEFAULT_UPNP));
// Send and receive from sockets, accept connections
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "net", &ThreadSocketHandler));
// Initiate outbound connections from -addnode
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "addcon", &ThreadOpenAddedConnections));
// Initiate outbound connections
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "opencon", &ThreadOpenConnections));
// Process messages
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "msghand", &ThreadMessageHandler));
// Dump network addresses
scheduler.scheduleEvery(&DumpData, DUMP_ADDRESSES_INTERVAL);
// ppcoin:mint proof-of-stake blocks in the background
if (GetBoolArg("-staking", true))
threadGroup.create_thread(boost::bind(&TraceThread<void (*)()>, "stakemint", &ThreadStakeMinter));
}
bool StopNode()
{
LogPrintf("StopNode()\n");
MapPort(false);
if (semOutbound)
for (int i = 0; i < MAX_OUTBOUND_CONNECTIONS; i++)
semOutbound->post();
if (fAddressesInitialized) {
DumpData();
fAddressesInitialized = false;
}
return true;
}
class CNetCleanup
{
public:
CNetCleanup() {}
~CNetCleanup()
{
// Close sockets
BOOST_FOREACH (CNode* pnode, vNodes)
if (pnode->hSocket != INVALID_SOCKET)
CloseSocket(pnode->hSocket);
BOOST_FOREACH (ListenSocket& hListenSocket, vhListenSocket)
if (hListenSocket.socket != INVALID_SOCKET)
if (!CloseSocket(hListenSocket.socket))
LogPrintf("CloseSocket(hListenSocket) failed with error %s\n", NetworkErrorString(WSAGetLastError()));
// clean up some globals (to help leak detection)
BOOST_FOREACH (CNode* pnode, vNodes)
delete pnode;
BOOST_FOREACH (CNode* pnode, vNodesDisconnected)
delete pnode;
vNodes.clear();
vNodesDisconnected.clear();
vhListenSocket.clear();
delete semOutbound;
semOutbound = NULL;
delete pnodeLocalHost;
pnodeLocalHost = NULL;
#ifdef WIN32
// Shutdown Windows Sockets
WSACleanup();
#endif
}
} instance_of_cnetcleanup;
void CExplicitNetCleanup::callCleanup()
{
// Explicit call to destructor of CNetCleanup because it's not implicitly called
// when the wallet is restarted from within the wallet itself.
CNetCleanup* tmp = new CNetCleanup();
delete tmp; // Stroustrup's gonna kill me for that
}
void RelayTransaction(const CTransaction& tx)
{
CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);
ss.reserve(10000);
ss << tx;
RelayTransaction(tx, ss);
}
void RelayTransaction(const CTransaction& tx, const CDataStream& ss)
{
CInv inv(MSG_TX, tx.GetHash());
{
LOCK(cs_mapRelay);
// Expire old relay messages
while (!vRelayExpiration.empty() && vRelayExpiration.front().first < GetTime()) {
mapRelay.erase(vRelayExpiration.front().second);
vRelayExpiration.pop_front();
}
// Save original serialized message so newer versions are preserved
mapRelay.insert(std::make_pair(inv, ss));
vRelayExpiration.push_back(std::make_pair(GetTime() + 15 * 60, inv));
}
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes) {
if (!pnode->fRelayTxes)
continue;
LOCK(pnode->cs_filter);
if (pnode->pfilter) {
if (pnode->pfilter->IsRelevantAndUpdate(tx))
pnode->PushInventory(inv);
} else
pnode->PushInventory(inv);
}
}
void RelayTransactionLockReq(const CTransaction& tx, bool relayToAll)
{
CInv inv(MSG_TXLOCK_REQUEST, tx.GetHash());
//broadcast the new lock
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes) {
if (!relayToAll && !pnode->fRelayTxes)
continue;
pnode->PushMessage("ix", tx);
}
}
void RelayInv(CInv& inv)
{
LOCK(cs_vNodes);
BOOST_FOREACH (CNode* pnode, vNodes){
if((pnode->nServices==NODE_BLOOM_WITHOUT_MN) && inv.IsMasterNodeType())continue;
if (pnode->nVersion >= ActiveProtocol())
pnode->PushInventory(inv);
}
}
void CNode::RecordBytesRecv(uint64_t bytes)
{
LOCK(cs_totalBytesRecv);
nTotalBytesRecv += bytes;
}
void CNode::RecordBytesSent(uint64_t bytes)
{
LOCK(cs_totalBytesSent);
nTotalBytesSent += bytes;
}
uint64_t CNode::GetTotalBytesRecv()
{
LOCK(cs_totalBytesRecv);
return nTotalBytesRecv;
}
uint64_t CNode::GetTotalBytesSent()
{
LOCK(cs_totalBytesSent);
return nTotalBytesSent;
}
void CNode::Fuzz(int nChance)
{
if (!fSuccessfullyConnected) return; // Don't fuzz initial handshake
if (GetRand(nChance) != 0) return; // Fuzz 1 of every nChance messages
switch (GetRand(3)) {
case 0:
// xor a random byte with a random value:
if (!ssSend.empty()) {
CDataStream::size_type pos = GetRand(ssSend.size());
ssSend[pos] ^= (unsigned char)(GetRand(256));
}
break;
case 1:
// delete a random byte:
if (!ssSend.empty()) {
CDataStream::size_type pos = GetRand(ssSend.size());
ssSend.erase(ssSend.begin() + pos);
}
break;
case 2:
// insert a random byte at a random position
{
CDataStream::size_type pos = GetRand(ssSend.size());
char ch = (char)GetRand(256);
ssSend.insert(ssSend.begin() + pos, ch);
}
break;
}
// Chance of more than one change half the time:
// (more changes exponentially less likely):
Fuzz(2);
}
//
// CAddrDB
//
CAddrDB::CAddrDB()
{
pathAddr = GetDataDir() / "peers.dat";
}
bool CAddrDB::Write(const CAddrMan& addr)
{
// Generate random temporary filename
unsigned short randv = 0;
GetRandBytes((unsigned char*)&randv, sizeof(randv));
std::string tmpfn = strprintf("peers.dat.%04x", randv);
// serialize addresses, checksum data up to that point, then append csum
CDataStream ssPeers(SER_DISK, CLIENT_VERSION);
ssPeers << FLATDATA(Params().MessageStart());
ssPeers << addr;
uint256 hash = Hash(ssPeers.begin(), ssPeers.end());
ssPeers << hash;
// open output file, and associate with CAutoFile
boost::filesystem::path pathAddr = GetDataDir() / "peers.dat";
FILE* file = fopen(pathAddr.string().c_str(), "wb");
CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("%s : Failed to open file %s", __func__, pathAddr.string());
// Write and commit header, data
try {
fileout << ssPeers;
} catch (std::exception& e) {
return error("%s : Serialize or I/O error - %s", __func__, e.what());
}
FileCommit(fileout.Get());
fileout.fclose();
return true;
}
bool CAddrDB::Read(CAddrMan& addr)
{
// open input file, and associate with CAutoFile
FILE* file = fopen(pathAddr.string().c_str(), "rb");
CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
if (filein.IsNull())
return error("%s : Failed to open file %s", __func__, pathAddr.string());
// use file size to size memory buffer
uint64_t fileSize = boost::filesystem::file_size(pathAddr);
uint64_t dataSize = fileSize - sizeof(uint256);
// Don't try to resize to a negative number if file is small
if (fileSize >= sizeof(uint256))
dataSize = fileSize - sizeof(uint256);
vector<unsigned char> vchData;
vchData.resize(dataSize);
uint256 hashIn;
// read data and checksum from file
try {
filein.read((char*)&vchData[0], dataSize);
filein >> hashIn;
} catch (std::exception& e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
filein.fclose();
CDataStream ssPeers(vchData, SER_DISK, CLIENT_VERSION);
// verify stored checksum matches input data
uint256 hashTmp = Hash(ssPeers.begin(), ssPeers.end());
if (hashIn != hashTmp)
return error("%s : Checksum mismatch, data corrupted", __func__);
unsigned char pchMsgTmp[4];
try {
// de-serialize file header (network specific magic number) and ..
ssPeers >> FLATDATA(pchMsgTmp);
// ... verify the network matches ours
if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
return error("%s : Invalid network magic number", __func__);
// de-serialize address data into one CAddrMan object
ssPeers >> addr;
} catch (std::exception& e) {
return error("%s : Deserialize or I/O error - %s", __func__, e.what());
}
return true;
}
unsigned int ReceiveFloodSize() { return 1000 * GetArg("-maxreceivebuffer", 5 * 1000); }
unsigned int SendBufferSize() { return 1000 * GetArg("-maxsendbuffer", 1 * 1000); }
CNode::CNode(SOCKET hSocketIn, CAddress addrIn, std::string addrNameIn, bool fInboundIn) : ssSend(SER_NETWORK, INIT_PROTO_VERSION), setAddrKnown(5000)
{
nServices = 0;
hSocket = hSocketIn;
nRecvVersion = INIT_PROTO_VERSION;
nLastSend = 0;
nLastRecv = 0;
nSendBytes = 0;
nRecvBytes = 0;
nTimeConnected = GetTime();
nTimeOffset = 0;
addr = addrIn;
addrName = addrNameIn == "" ? addr.ToStringIPPort() : addrNameIn;
nVersion = 0;
strSubVer = "";
fWhitelisted = false;
fOneShot = false;
fClient = false; // set by version message
fInbound = fInboundIn;
fNetworkNode = false;
fSuccessfullyConnected = false;
fDisconnect = false;
nRefCount = 0;
nSendSize = 0;
nSendOffset = 0;
hashContinue = 0;
nStartingHeight = -1;
fGetAddr = false;
fRelayTxes = false;
setInventoryKnown.max_size(SendBufferSize() / 1000);
pfilter = new CBloomFilter();
nPingNonceSent = 0;
nPingUsecStart = 0;
nPingUsecTime = 0;
fPingQueued = false;
fObfuScationMaster = false;
{
LOCK(cs_nLastNodeId);
id = nLastNodeId++;
}
if (fLogIPs)
LogPrint("net", "Added connection to %s peer=%d\n", addrName, id);
else
LogPrint("net", "Added connection peer=%d\n", id);
// Be shy and don't send version until we hear
if (hSocket != INVALID_SOCKET && !fInbound)
PushVersion();
GetNodeSignals().InitializeNode(GetId(), this);
}
CNode::~CNode()
{
CloseSocket(hSocket);
if (pfilter)
delete pfilter;
GetNodeSignals().FinalizeNode(GetId());
}
void CNode::AskFor(const CInv& inv)
{
if (mapAskFor.size() > MAPASKFOR_MAX_SZ)
return;
// We're using mapAskFor as a priority queue,
// the key is the earliest time the request can be sent
int64_t nRequestTime;
limitedmap<CInv, int64_t>::const_iterator it = mapAlreadyAskedFor.find(inv);
if (it != mapAlreadyAskedFor.end())
nRequestTime = it->second;
else
nRequestTime = 0;
LogPrint("net", "askfor %s %d (%s) peer=%d\n", inv.ToString(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime / 1000000), id);
// Make sure not to reuse time indexes to keep things in the same order
int64_t nNow = GetTimeMicros() - 1000000;
static int64_t nLastTime;
++nLastTime;
nNow = std::max(nNow, nLastTime);
nLastTime = nNow;
// Each retry is 2 minutes after the last
nRequestTime = std::max(nRequestTime + 2 * 60 * 1000000, nNow);
if (it != mapAlreadyAskedFor.end())
mapAlreadyAskedFor.update(it, nRequestTime);
else
mapAlreadyAskedFor.insert(std::make_pair(inv, nRequestTime));
mapAskFor.insert(std::make_pair(nRequestTime, inv));
}
void CNode::BeginMessage(const char* pszCommand) EXCLUSIVE_LOCK_FUNCTION(cs_vSend)
{
ENTER_CRITICAL_SECTION(cs_vSend);
assert(ssSend.size() == 0);
ssSend << CMessageHeader(pszCommand, 0);
LogPrint("net", "sending: %s ", SanitizeString(pszCommand));
}
void CNode::AbortMessage() UNLOCK_FUNCTION(cs_vSend)
{
ssSend.clear();
LEAVE_CRITICAL_SECTION(cs_vSend);
LogPrint("net", "(aborted)\n");
}
void CNode::EndMessage() UNLOCK_FUNCTION(cs_vSend)
{
// The -*messagestest options are intentionally not documented in the help message,
// since they are only used during development to debug the networking code and are
// not intended for end-users.
if (mapArgs.count("-dropmessagestest") && GetRand(GetArg("-dropmessagestest", 2)) == 0) {
LogPrint("net", "dropmessages DROPPING SEND MESSAGE\n");
AbortMessage();
return;
}
if (mapArgs.count("-fuzzmessagestest"))
Fuzz(GetArg("-fuzzmessagestest", 10));
if (ssSend.size() == 0) {
LEAVE_CRITICAL_SECTION(cs_vSend);
return;
}
// Set the size
unsigned int nSize = ssSend.size() - CMessageHeader::HEADER_SIZE;
memcpy((char*)&ssSend[CMessageHeader::MESSAGE_SIZE_OFFSET], &nSize, sizeof(nSize));
// Set the checksum
uint256 hash = Hash(ssSend.begin() + CMessageHeader::HEADER_SIZE, ssSend.end());
unsigned int nChecksum = 0;
memcpy(&nChecksum, &hash, sizeof(nChecksum));
assert(ssSend.size() >= CMessageHeader::CHECKSUM_OFFSET + sizeof(nChecksum));
memcpy((char*)&ssSend[CMessageHeader::CHECKSUM_OFFSET], &nChecksum, sizeof(nChecksum));
LogPrint("net", "(%d bytes) peer=%d\n", nSize, id);
std::deque<CSerializeData>::iterator it = vSendMsg.insert(vSendMsg.end(), CSerializeData());
ssSend.GetAndClear(*it);
nSendSize += (*it).size();
// If write queue empty, attempt "optimistic write"
if (it == vSendMsg.begin())
SocketSendData(this);
LEAVE_CRITICAL_SECTION(cs_vSend);
}
//
// CBanDB
//
CBanDB::CBanDB()
{
pathBanlist = GetDataDir() / "banlist.dat";
}
bool CBanDB::Write(const banmap_t& banSet)
{
// Generate random temporary filename
unsigned short randv = 0;
GetRandBytes((unsigned char*)&randv, sizeof(randv));
std::string tmpfn = strprintf("banlist.dat.%04x", randv);
// serialize banlist, checksum data up to that point, then append csum
CDataStream ssBanlist(SER_DISK, CLIENT_VERSION);
ssBanlist << FLATDATA(Params().MessageStart());
ssBanlist << banSet;
uint256 hash = Hash(ssBanlist.begin(), ssBanlist.end());
ssBanlist << hash;
// open temp output file, and associate with CAutoFile
boost::filesystem::path pathTmp = GetDataDir() / tmpfn;
FILE *file = fopen(pathTmp.string().c_str(), "wb");
CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("%s: Failed to open file %s", __func__, pathTmp.string());
// Write and commit header, data
try {
fileout << ssBanlist;
}
catch (const std::exception& e) {
return error("%s: Serialize or I/O error - %s", __func__, e.what());
}
FileCommit(fileout.Get());
fileout.fclose();
// replace existing banlist.dat, if any, with new banlist.dat.XXXX
if (!RenameOver(pathTmp, pathBanlist))
return error("%s: Rename-into-place failed", __func__);
return true;
}
bool CBanDB::Read(banmap_t& banSet)
{
// open input file, and associate with CAutoFile
FILE *file = fopen(pathBanlist.string().c_str(), "rb");
CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
if (filein.IsNull())
return error("%s: Failed to open file %s", __func__, pathBanlist.string());
// use file size to size memory buffer
uint64_t fileSize = boost::filesystem::file_size(pathBanlist);
uint64_t dataSize = 0;
// Don't try to resize to a negative number if file is small
if (fileSize >= sizeof(uint256))
dataSize = fileSize - sizeof(uint256);
vector<unsigned char> vchData;
vchData.resize(dataSize);
uint256 hashIn;
// read data and checksum from file
try {
filein.read((char *)&vchData[0], dataSize);
filein >> hashIn;
}
catch (const std::exception& e) {
return error("%s: Deserialize or I/O error - %s", __func__, e.what());
}
filein.fclose();
CDataStream ssBanlist(vchData, SER_DISK, CLIENT_VERSION);
// verify stored checksum matches input data
uint256 hashTmp = Hash(ssBanlist.begin(), ssBanlist.end());
if (hashIn != hashTmp)
return error("%s: Checksum mismatch, data corrupted", __func__);
unsigned char pchMsgTmp[4];
try {
// de-serialize file header (network specific magic number) and ..
ssBanlist >> FLATDATA(pchMsgTmp);
// ... verify the network matches ours
if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
return error("%s: Invalid network magic number", __func__);
// de-serialize address data into one CAddrMan object
ssBanlist >> banSet;
}
catch (const std::exception& e) {
return error("%s: Deserialize or I/O error - %s", __func__, e.what());
}
return true;
}
void DumpBanlist()
{
CNode::SweepBanned(); // clean unused entries (if bantime has expired)
if (!CNode::BannedSetIsDirty())
return;
int64_t nStart = GetTimeMillis();
CBanDB bandb;
banmap_t banmap;
CNode::GetBanned(banmap);
if (bandb.Write(banmap)) {
CNode::SetBannedSetDirty(false);
}
LogPrint("net", "Flushed %d banned node ips/subnets to banlist.dat %dms\n",
banmap.size(), GetTimeMillis() - nStart);
}
| [
"cryptojoehodler@gmail.com"
] | cryptojoehodler@gmail.com |
d93194bc49b5180769ca64028963b7080a093e0e | 39eae5cc024b6631a3a77853afed6983d8af31fe | /mix/workspace_vs/YY_WJX/Win32Timer_QT_TEST/qt_test.cpp | f9fbea0278ad180ffab9c8a7e296cd4e1df05d14 | [] | no_license | SniperXiaoJun/mix-src | cd83fb5fedf99b0736dd3a5a7e24e86ab49c4c3b | 4d05804fd03894fa7859b4837c50b3891fc45619 | refs/heads/master | 2020-03-30T06:21:14.855395 | 2018-09-28T03:32:55 | 2018-09-28T03:32:55 | 150,854,539 | 1 | 0 | null | 2018-09-29T10:44:41 | 2018-09-29T10:44:41 | null | UTF-8 | C++ | false | false | 534 | cpp | #include "qt_test.h"
QT_Test::QT_Test(QWidget *parent, Qt::WFlags flags)
: QMainWindow(parent, flags)
{
ui.setupUi(this);
m_pNetWork = new CNetwork("128.1.1.121", 8888);
m_pNetWork->SetSendAddr("127.0.0.1");
m_pNetWork->SetSendPort(8888);
m_pNetWork->SetCallback(this);
m_pNetWork->ReadUDP();
m_pNetWork->SendUDP((const Byte *)"aaa", 4);
}
QT_Test::~QT_Test()
{
}
void QT_Test::HandleReceiveData(const Byte *pMsg, u32 ulLen)
{
int i = 0;
}
void QT_Test::HandleError(void)
{
int j = 0;
}
| [
"244540499@qq.com"
] | 244540499@qq.com |
0beb34ef0188aa9e8d9dd74922085c2eb7cd6c9d | 5cad8d9664c8316cce7bc57128ca4b378a93998a | /CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/gnu/java/nio/SelectorProviderImpl.h | e2ad8e41d91035cfb58abf62c5ff482ce3e37777 | [
"LicenseRef-scancode-unknown-license-reference",
"GPL-2.0-only",
"GPL-3.0-only",
"curl",
"Zlib",
"LicenseRef-scancode-warranty-disclaimer",
"OpenSSL",
"GPL-1.0-or-later",
"MIT",
"LicenseRef-scancode-other-copyleft",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows",
"BSD-3-... | permissive | huaweicloud/huaweicloud-sdk-c-obs | 0c60d61e16de5c0d8d3c0abc9446b5269e7462d4 | fcd0bf67f209cc96cf73197e9c0df143b1d097c4 | refs/heads/master | 2023-09-05T11:42:28.709499 | 2023-08-05T08:52:56 | 2023-08-05T08:52:56 | 163,231,391 | 41 | 21 | Apache-2.0 | 2023-06-28T07:18:06 | 2018-12-27T01:15:05 | C | UTF-8 | C++ | false | false | 1,248 | h |
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*-
#ifndef __gnu_java_nio_SelectorProviderImpl__
#define __gnu_java_nio_SelectorProviderImpl__
#pragma interface
#include <java/nio/channels/spi/SelectorProvider.h>
extern "Java"
{
namespace gnu
{
namespace java
{
namespace nio
{
class SelectorProviderImpl;
}
}
}
namespace java
{
namespace nio
{
namespace channels
{
class DatagramChannel;
class Pipe;
class ServerSocketChannel;
class SocketChannel;
namespace spi
{
class AbstractSelector;
}
}
}
}
}
class gnu::java::nio::SelectorProviderImpl : public ::java::nio::channels::spi::SelectorProvider
{
public:
SelectorProviderImpl();
virtual ::java::nio::channels::DatagramChannel * openDatagramChannel();
virtual ::java::nio::channels::Pipe * openPipe();
virtual ::java::nio::channels::spi::AbstractSelector * openSelector();
virtual ::java::nio::channels::ServerSocketChannel * openServerSocketChannel();
virtual ::java::nio::channels::SocketChannel * openSocketChannel();
static ::java::lang::Class class$;
};
#endif // __gnu_java_nio_SelectorProviderImpl__
| [
"xiangshijian1@huawei.com"
] | xiangshijian1@huawei.com |
4b94eb7805df52814b6179a7e480bb69ab8ac99b | d4da977bb5f060d6b4edebfdf32b98ee91561b16 | /Archive/Topcoder/SRM/CatAndMice.cpp | aa76bf825593e43161dce697ab358cdc3fdad926 | [] | no_license | lychees/ACM-Training | 37f9087f636d9e4eead6c82c7570e743d82cf68e | 29fb126ad987c21fa204c56f41632e65151c6c23 | refs/heads/master | 2023-08-05T11:21:22.362564 | 2023-07-21T17:49:53 | 2023-07-21T17:49:53 | 42,499,880 | 100 | 22 | null | null | null | null | UTF-8 | C++ | false | false | 5,562 | cpp | /* &*#()&*#)&E*F& */
#include <iostream>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <cmath>
#include <algorithm>
#include <sstream>
#include <string>
#include <vector>
#include <map>
using namespace std;
#define REP(I, N) for (int I=0;I<int(N);++I)
#define FOR(I, A, B) for (int I=int(A);I<int(B);++I)
#define DWN(I, B, A) for (int I=int(B-1);I>=int(A);--I)
#define ECH(it, A) for (typeof(A.begin()) it=A.begin(); it != A.end(); ++it)
#define ALL(A) A.begin(), A.end()
#define CLR(A) A.clear()
#define CPY(A, B) memcpy(A, B, sizeof(A))
#define INS(A, P, B) A.insert(A.begin() + P, B)
#define ERS(A, P) A.erase(A.begin() + P)
#define SRT(A) sort(ALL(A))
#define SZ(A) int(A.size())
#define PB push_back
#define MP(A, B) make_pair(A, B)
typedef long long LL;
typedef double DB;
template<class T> inline void RST(T &A){memset(A, 0, sizeof(A));}
template<class T> inline void FLC(T &A, int x){memset(A, x, sizeof(A));}
template<class T> inline void checkMin(T &a, T b){if (b<a) a=b;}
template<class T> inline void checkMax(T &a, T b){if (b>a) a=b;}
/* -&$&#*( &#*@)^$@&*)*/
const int MOD = 1000000007;
const int INF = 0x3f3f3f3f;
const int N = 50;
class CatAndMice {
public:
long long countDirections(int N, int C) {
long long res = 0;
return res;
}
};
// BEGIN CUT HERE
namespace moj_harness {
int run_test_case(int);
void run_test(int casenum = -1, bool quiet = false) {
if (casenum != -1) {
if (run_test_case(casenum) == -1 && !quiet) {
cerr << "Illegal input! Test case " << casenum << " does not exist." << endl;
}
return;
}
int correct = 0, total = 0;
for (int i=0;; ++i) {
int x = run_test_case(i);
if (x == -1) {
if (i >= 100) break;
continue;
}
correct += x;
++total;
}
if (total == 0) {
cerr << "No test cases run." << endl;
} else if (correct < total) {
cerr << "Some cases FAILED (passed " << correct << " of " << total << ")." << endl;
} else {
cerr << "All " << total << " tests passed!" << endl;
}
}
int verify_case(int casenum, const long long &expected, const long long &received, clock_t elapsed) {
cerr << "Example " << casenum << "... ";
string verdict;
vector<string> info;
char buf[100];
if (elapsed > CLOCKS_PER_SEC / 200) {
sprintf(buf, "time %.2fs", elapsed * (1.0/CLOCKS_PER_SEC));
info.push_back(buf);
}
if (expected == received) {
verdict = "PASSED";
} else {
verdict = "FAILED";
}
cerr << verdict;
if (!info.empty()) {
cerr << " (";
for (int i=0; i<(int)info.size(); ++i) {
if (i > 0) cerr << ", ";
cerr << info[i];
}
cerr << ")";
}
cerr << endl;
if (verdict == "FAILED") {
cerr << " Expected: " << expected << endl;
cerr << " Received: " << received << endl;
}
return verdict == "PASSED";
}
int run_test_case(int casenum) {
switch (casenum) {
case 0: {
int N = 2;
int C = 2;
long long expected__ = 8;
clock_t start__ = clock();
long long received__ = CatAndMice().countDirections(N, C);
return verify_case(casenum, expected__, received__, clock()-start__);
}
case 1: {
int N = 2;
int C = 1;
long long expected__ = 8;
clock_t start__ = clock();
long long received__ = CatAndMice().countDirections(N, C);
return verify_case(casenum, expected__, received__, clock()-start__);
}
case 2: {
int N = 19;
int C = 3;
long long expected__ = 48;
clock_t start__ = clock();
long long received__ = CatAndMice().countDirections(N, C);
return verify_case(casenum, expected__, received__, clock()-start__);
}
case 3: {
int N = 1234;
int C = 3;
long long expected__ = 180608;
clock_t start__ = clock();
long long received__ = CatAndMice().countDirections(N, C);
return verify_case(casenum, expected__, received__, clock()-start__);
}
case 4: {
int N = 1234;
int C = 1212;
long long expected__ = 0;
clock_t start__ = clock();
long long received__ = CatAndMice().countDirections(N, C);
return verify_case(casenum, expected__, received__, clock()-start__);
}
// custom cases
/* case 5: {
int N = ;
int C = ;
long long expected__ = ;
clock_t start__ = clock();
long long received__ = CatAndMice().countDirections(N, C);
return verify_case(casenum, expected__, received__, clock()-start__);
}*/
/* case 6: {
int N = ;
int C = ;
long long expected__ = ;
clock_t start__ = clock();
long long received__ = CatAndMice().countDirections(N, C);
return verify_case(casenum, expected__, received__, clock()-start__);
}*/
/* case 7: {
int N = ;
int C = ;
long long expected__ = ;
clock_t start__ = clock();
long long received__ = CatAndMice().countDirections(N, C);
return verify_case(casenum, expected__, received__, clock()-start__);
}*/
default:
return -1;
}
}
}
int main(int argc, char *argv[]) {
if (argc == 1) {
moj_harness::run_test();
} else {
for (int i=1; i<argc; ++i)
moj_harness::run_test(atoi(argv[i]));
}
}
// END CUT HERE
| [
"251815992@qq.com"
] | 251815992@qq.com |
1316e367932a8c4c43312a178bbf1662cdd0fac3 | ab453496bc92c2b357e25d3a552e1f2480a45214 | /Project02/Kruskal/Main.cpp | 387c3cc5cd0996a0c76e9bc7a217673ec123fe04 | [] | no_license | kellisonjk/AED2-UFRPE-UAG | 682d05f46930bdfd190986398f67f69c333bce94 | 627de67968d8ff1fbfbf6935928b2b8d11f72b76 | refs/heads/master | 2020-03-27T23:45:45.458242 | 2018-01-10T00:34:28 | 2018-01-10T00:34:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,623 | cpp | /*
* Main.cpp
*
* Author: Kellison
*
*/
#include <iostream>
#include <stdio.h>
#include "Kruskal.hpp"
using namespace std;
int main(int argc, char* argv[]){
char op;
vector<int> a;
a.push_back(0);
a.push_back(1);
a.push_back(2);
a.push_back(3);
a.push_back(4);
a.push_back(5);
Graph<int> g("new", a);
printf("\n %c%c%c%c%c%c%c TRABALHANDO COM GRAFOS - ALG. DE KRUSKAL %c%c%c%c%c%c%c \n\n",
205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205);
g.showAllVertex();
cout << endl << " Matriz de Adjacencias (com custos): " << endl << endl;
g.setEdge(0, 1, 5);
g.setEdge(0, 2, 6);
g.setEdge(0, 3, 4);
g.setEdge(1, 2, 1);
g.setEdge(1, 3, 2);
g.setEdge(2, 3, 2);
g.setEdge(2, 5, 3);
g.setEdge(2, 4, 6);
g.setEdge(3, 5, 4);
g.setEdge(4, 5, 4);
g.showMatriz();
Kruskal<int> k;
//Kruskal<int> k(g); // Gera erro
k.graph = g;
// Gera a MST (arvore gerdore minima)
//k.createMST();
vector< Edge<int> > vec = k.getMST();
printf("\n\n Algoritmo de Kruskal %c%c%c%c%c%c%c%c%c%c%c%c%c%c%c", 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205, 205);
cout << endl << " - Arvore Geradora Minima:" << endl;
k.printEdges();
k.saveEdgesFile();
/*cout << endl << endl << " Visualizar o grafo? 1 - SIM: ";
op = cin.get();
if (op == '1'){
g.showGraphView();
cout << " Abrindo arquivo ..." << endl << endl << "Execucao finalizada." << endl;
}
else{
cout << endl << endl << " (Pressione <ENTER> para encerrar>" << endl;
cin.get();
} */
cout << endl << endl << " (Pressione <ENTER> para encerrar>" << endl;
cin.get();
return 0;
} | [
"kellisonjk@gmail.com"
] | kellisonjk@gmail.com |
885858b221cac7d559808fdb5a13119a933be965 | 408fb0c173fd8703e359d88e8a2e34990dd9b7f9 | /src/QtGeography/nGeolocation.cpp | fcdb25c1c1421f6914761012242d15af7fcc3c2f | [
"MIT"
] | permissive | Vladimir-Lin/QtGeography | 4294fd907843d726b3c1232a5d912d599a8f38a6 | e1932c51bea7c32dc1bb6603384d24e969c95543 | refs/heads/main | 2023-05-29T04:16:27.486481 | 2021-06-16T15:13:16 | 2021-06-16T15:13:16 | 377,538,254 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 159 | cpp | #include <qtgeography.h>
N::Geolocation:: Geolocation(void)
{
longitude = 0 ;
latitude = 0 ;
height = 0 ;
}
N::Geolocation::~Geolocation(void)
{
}
| [
"lin.vladimir@gmail.com"
] | lin.vladimir@gmail.com |
7644d21f08b0eca4f4b04e19bc1d4acfe6362e6b | 367774c3855fa5fed4c244b9a66dac4bf24a883c | /src/poker.h | 86929941a1016d2448b833b927082579ba28fb67 | [] | no_license | kenoyer130/jpoker | 215828f06cfce84067f58f8472b6d08f0b9ff157 | d80e0122bf09a19247cae692b2cd27cf4c576ec3 | refs/heads/master | 2020-04-27T00:46:51.041512 | 2014-08-25T02:10:56 | 2014-08-25T02:10:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 642 | h | #ifndef Poker_H
#define Poker_H
#include "enums.h"
#include "deck.h"
using namespace std;
class Poker {
public:
Poker(bool automode);
void StartGame();
private:
bool autoMode {false};
Deck deck {};
std::unique_ptr<Players> players;
std::vector<Card> cards;
int currentbet {0};
GameState gameState;
double Pot;
int bigBlind {0};
int smallBlind {0};
int handBlinds {0};
int handCount {0};
void resetPlayers();
void takeActions();
void printState();
void startHand();
void dealHoleCards();
void dealCards(int number);
void handOver();
void playerWon(int playerIndex);
void clearScreen();
};
#endif
| [
"kenoyer130@gmail.com"
] | kenoyer130@gmail.com |
386b484ef607230dcaccea35f4fac6b51f35b43f | 36ed85609e97bc73c8c7f2dc257ba69507e6abd2 | /Heap/sortKsortedArray_sortNearlySortedArray.cpp | ac7242d4c46e70d0bac90a7929febd475e63f9a6 | [] | no_license | rk946/cpp | 464f57cab02001fd0a79f1354cce682a32d368bd | 256d175b0bc49e3e51eb828dbd637eaac43b603b | refs/heads/master | 2023-07-14T05:49:13.764214 | 2021-08-16T12:32:12 | 2021-08-16T12:32:12 | 275,735,567 | 0 | 0 | null | 2021-08-16T09:29:23 | 2020-06-29T05:06:07 | C++ | UTF-8 | C++ | false | false | 768 | cpp | #include <bits/stdc++.h>
using namespace std;
void sortKsortedArray(int *arr, int n, int k)
{
priority_queue<int,vector<int>,greater<int>> minh;
int j=0;
for(int i=0;i<n;i++)
{
minh.push(arr[i]);
if(minh.size()>k)
{
arr[j] = minh.top();
minh.pop();
j++;
}
}
// cout <<endl<<minh.size()<<endl;
// for(int i=n-k;i<n;i++)
// while(j<n)
while(minh.size()>0)
{
// cout <<endl<<minh.size()<<endl;
// cout << "call";
arr[j] = minh.top();
minh.pop();
j++;
}
}
int main()
{
int arr[] = {6,5,3,2,8,10,9};
int k=3;
int n =sizeof(arr)/sizeof(int);
for(int i=0;i<n;i++)
{
cout << arr[i] <<" ";
}
cout << endl;
sortKsortedArray(arr,n,k);
for(int i=0;i<n;i++)
{
cout << arr[i] <<" ";
}
return 0;
} | [
"rakeshs@cdot.in"
] | rakeshs@cdot.in |
31566a67e326511f13079b9b309e1ebc1fd6bdd1 | 184e9e7e2f7808f3494a6f27085e1ab5aa0839ae | /Cpp17-NewFeature-07-InlineVariables/main.cpp | d603769c7c02e5f02b96a4acff2772bb8ebff9c2 | [
"MIT"
] | permissive | LU-JIANGZHOU/Cpp17-NewFeatures | f36bbdc86d64e0e50638d1f5e3078aa5e21a265e | c3cdbc89e258898d7ea9e2a7ab2eafe8324a5b29 | refs/heads/master | 2023-02-20T19:26:41.050151 | 2021-01-22T15:49:11 | 2021-01-22T15:49:11 | 325,994,402 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 289 | cpp | #include <iostream>
using namespace std;
class A
{
public:
A()
{
++num;
}
~A()
{
--num;
}
inline static int num = 1;
};
int main()
{
cout << "to demonstrate the inline variables" << endl;
cout << "The static value is: " << A::num << "\n";
return EXIT_SUCCESS;
} | [
"jiangzhoulu@outlook.com"
] | jiangzhoulu@outlook.com |
edfd0ac2a25006b82729ee1973452ccf2f002a94 | 73120b2ea453de06ba71dcf0a4c582ad21a70914 | /Project2/ball_chaser/src/process_image.cpp | 7b81d26864109c1727cdb7ea95ccd8e3f9c5a823 | [] | no_license | enriquea52/Robotics_Software_Engineer_Udacity | db25167dbe814e3678afaed9915dfe9f5d48af11 | 7aae3dcbace2dbb7c9824e03bb29edc59076eba6 | refs/heads/master | 2022-11-15T19:20:30.227858 | 2020-07-11T21:36:23 | 2020-07-11T21:36:23 | 278,785,251 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,301 | cpp | #include "ros/ros.h"
#include "ball_chaser/DriveToTarget.h"
#include <sensor_msgs/Image.h>
#include <stdio.h>
// Define a global client that can request services
ros::ServiceClient client;
// This function calls the command_robot service to drive the robot in the specified direction
void drive_robot(float lin_x, float ang_z)
{
ball_chaser::DriveToTarget srv;
srv.request.linear_x = lin_x;
srv.request.angular_z = ang_z;
if(!client.call(srv))
{
ROS_ERROR("Failed to call service command robot");
}
}
// This callback function continuously executes and reads the image data
void process_image_callback(const sensor_msgs::Image img)
{
int white_pixel = 255;
// TODO: Loop through each pixel in the image and check if there's a bright white one
// Then, identify if this pixel falls in the left, mid, or right side of the image
// Depending on the white ball position, call the drive_bot function and pass velocities to it
// Request a stop when there's no white ball seen by the camera
int segment = (img.step)/3.0;
bool ball_detected = false;
for(int i =0; i<img.height*img.step;i++)
{
if(img.data[i] == 255 && img.data[i+2] == 255 && img.data[i+2] == 255)
{
ball_detected = true;
if(i % img.step < segment-200)
{
drive_robot(0.0,0.5);
//printf("LEFT\n");
}
if(segment-200 < i % img.step && i% img.step < 2*segment+200)
{
drive_robot(1.0,0.0);
//printf("CENTER\n");
}
if(i % img.step > 2*segment+200)
{
drive_robot(0.0,-0.5);
//printf("RIGHT\n");
}
break;
}
}
if(ball_detected == false)
{
drive_robot(0.0,0.0);
//printf("No ball\n");
}
}
int main(int argc, char** argv)
{
// Initialize the process_image node and create a handle to it
ros::init(argc, argv, "process_image");
ros::NodeHandle n;
// Define a client service capable of requesting services from command_robot
client = n.serviceClient<ball_chaser::DriveToTarget>("/ball_chaser/command_robot");
// Subscribe to /camera/rgb/image_raw topic to read the image data inside the process_image_callback function
ros::Subscriber sub1 = n.subscribe("/camera/rgb/image_raw", 10, process_image_callback);
// Handle ROS communication events
ros::spin();
return 0;
}
| [
"JesusAleman@Jesuss-iMac.local"
] | JesusAleman@Jesuss-iMac.local |
80e5fb7722f453f29fad91be53fea18601de4541 | ecf47b47279fcf3b12ef8b0550f9b4fe35155aa6 | /src/Corrade/Containers/String.h | 50b0eb916d6b8b2b4c284fffd4afe0407bcac7ff | [
"MIT",
"Unlicense",
"LicenseRef-scancode-public-domain"
] | permissive | mgood7123/corrade | b4d9f6ff2cbf5c84ac3dfb8e02437fe977208826 | b048d6868f096d3ea5b162ed45d36aff9a9f5427 | refs/heads/master | 2023-05-13T21:04:53.651253 | 2021-06-11T13:21:29 | 2021-06-11T13:21:29 | 376,030,041 | 0 | 0 | NOASSERTION | 2021-06-11T13:13:00 | 2021-06-11T13:12:59 | null | UTF-8 | C++ | false | false | 36,857 | h | #ifndef Corrade_Containers_String_h
#define Corrade_Containers_String_h
/*
This file is part of Corrade.
Copyright © 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016,
2017, 2018, 2019, 2020, 2021
Vladimír Vondruš <mosra@centrum.cz>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/** @file
* @brief Class @ref Corrade::Containers::String, tag type @ref Corrade::Containers::AllocatedInitT, tag @ref Corrade::Containers::AllocatedInit
* @m_since_latest
*/
#include <cstddef>
#include <cstdint>
#include <type_traits>
#include <utility>
#include "Corrade/Containers/Containers.h"
#include "Corrade/Containers/StringView.h" /* needs to be included for
comparison operators */
#include "Corrade/Utility/Utility.h"
#include "Corrade/Utility/visibility.h"
namespace Corrade { namespace Containers {
namespace Implementation {
template<class> struct StringConverter;
enum: std::size_t { SmallStringSize = sizeof(std::size_t)*3 - 1 };
}
/**
@brief Allocated initialization tag type
@m_since_latest
Used to distinguish @ref String construction that bypasses small string
optimization.
@see @ref AllocatedInit, @ref Containers-String-usage-sso
*/
/* Explicit constructor to avoid ambiguous calls when using {} */
struct AllocatedInitT {
#ifndef DOXYGEN_GENERATING_OUTPUT
struct Init{};
constexpr explicit AllocatedInitT(Init) {}
#endif
};
/**
@brief Allocated initialization tag
@m_since_latest
Use for @ref String construction that bypasses small string optimization.
@ref Containers-String-usage-sso
*/
constexpr AllocatedInitT AllocatedInit{AllocatedInitT::Init{}};
/**
@brief String
@m_since_latest
A lightweight non-templated alternative to @ref std::string with support for
custom deleters. A non-owning version of this container is a
@ref BasicStringView "StringView".
@section Containers-String-usage Usage
It's recommended to prefer using @ref BasicStringView "StringView" in most
cases, and only create a @ref String instance if you need to extend lifetime of
the data or mutate it. The @ref String is implicitly convertible from C string
literals, but the designated way to instantiate a string is using the
@link operator""_s() @endlink literal. While both expressions are *mostly*
equivalent, the implicit conversion has some runtime impact due to
@ref std::strlen(), and it won't preserve zero bytes inside the string:
@snippet Containers.cpp String-usage-literal-null
@ref String instances are implicitly convertible from and to
(mutable) @ref BasicStringView "StringView", all instances (including an empty
string) are guaranteed to be null-terminated, which means a conversion to
@ref BasicStringView "StringView" will always have
@ref StringViewFlag::NullTerminated set.
As with @ref BasicStringView "StringView", the class is implicitly convertible
to @ref ArrayView. In addition it's also move-convertible to @ref Array, transferring the ownership of the internal data array to it. Ownership transfer
in the other direction is not provided because it's not possible to implicitly
guarantee null termination of the input @ref Array --- use the explicit
@ref String(char*, std::size_t, Deleter) constructor together with
@ref Array::release() in that case.
@subsection Containers-String-usage-sso Small string optimization
The class stores data size, data pointer and a deleter pointer, which is 24
bytes on 64-bit platforms (and 12 bytes on 32-bit). To avoid allocations for
small strings, small strings up to 22 bytes on 64-bit (23 including the null
terminator) and up to 10 bytes on 32-bit (11 including the null terminator) are
by default stored inside the class.
Such optimization is completely transparent to the user, the only difference is
that @ref deleter() and @ref release() can't be called on SSO strings, as there
is nothing to delete / release. Presence of SSO on an instance can be queried
using @ref isSmall(). In cases where SSO isn't desired (for example when
storing pointers to string contents stored in a growable array), the string can
be constructed using the @ref AllocatedInit tag (for example with
@ref String(AllocatedInitT, const char*)), which bypasses this optimization and
always allocates.
@attention For consistency with @ref StringView and in order to allow the small
string optimization, on 32-bit systems the size is limited to 1 GB. That
should be more than enough for real-world strings (as opposed to arbitrary
binary data), if you need more please use an @ref Array instead.
@subsection Containers-String-usage-initialization String initialization
In addition to creating a @ref String from an existing string (literal) or
wrapping an externally allocated memory as mentioned above, explicit
initialization constructors are provided, similarly to the @ref Array class:
- @ref String(ValueInitT, std::size_t) zero-initializes the string, meaning
each of its characters is @cpp '\0' @ce. For heap-allocated strings this is
equivalent to @cpp new char[size + 1]{} @ce (the one extra character is
for the null terminator).
- @ref String(DirectInitT, std::size_t, char) fills the whole string with
given character and zero-initializes the null terminator. For
heap-allocated strings this is equivalent to
@cpp new char[size + 1]{c, c, c, …, '\0'} @ce.
- @ref String(NoInitT, std::size_t) keeps the contents uninitialized, except
for the null terminator. Equivalent to @cpp new char[size + 1] @ce followed
by @cpp string[size] = '\0' @ce.
@section Containers-String-stl STL compatibility
Instances of @ref String are *implicitly* convertible from and to
@ref std::string if you include @ref Corrade/Containers/StringStl.h. The
conversion is provided in a separate header to avoid unconditional @cpp
#include <string> @ce, which significantly affects compile times. The following
table lists allowed conversions:
Corrade type | ↭ | STL type
------------------------------- | - | ---------------------
@ref String | ⇆ | @ref std::string
Example:
@snippet Containers-stl.cpp String
Because @ref std::string doesn't provide any way to transfer ownership of its
underlying memory, conversion either way always involves an allocation and a
copy. To mitigate the conversion impact, it's recommended to convert
@ref std::string instances to @ref BasicStringView "StringView" instead where
possible.
@experimental
*/
class CORRADE_UTILITY_EXPORT String {
public:
typedef void(*Deleter)(char*, std::size_t); /**< @brief Deleter type */
/**
* @brief Turn a view into a null-terminated string
*
* If the view is @ref StringViewFlag::NullTerminated, returns a
* non-owning reference to it without any extra allocations or copies
* involved. Otherwise allocates a null-terminated owning copy using
* @ref String(StringView).
*
* This function is primarily meant for efficiently passing
* @ref BasicStringView "StringView" instances to APIs that expect
* null-terminated @cpp const char* @ce. Mutating the result in any way
* is undefined behavior.
* @see @ref nullTerminatedGlobalView()
*/
static String nullTerminatedView(StringView view);
/**
* @brief Turn a view into a null-terminated global string
*
* If the view is both @ref StringViewFlag::NullTerminated and
* @ref StringViewFlag::Global, returns a non-owning reference to it
* without any extra allocations or copies involved. Otherwise
* allocates a null-terminated owning copy using
* @ref String(StringView).
*
* This function is primarily meant for efficiently storing
* @ref BasicStringView "StringView" instances, ensuring the
* memory stays in scope and then passing them to APIs that expect
* null-terminated @cpp const char* @ce. Mutating the result in any way
* is undefined behavior.
* @see @ref nullTerminatedView()
*/
static String nullTerminatedGlobalView(StringView view);
/**
* @brief Default constructor
*
* Creates an empty string.
*/
/*implicit*/ String() noexcept;
/**
* @brief Construct from a string view
*
* Creates a null-terminated owning copy of @p view. Contrary to the
* behavior of @ref std::string, @p view is allowed to be
* @cpp nullptr @ce, but only if it's size is zero. Depending on the
* size, it's either stored allocated or in a SSO.
* @see @ref Containers-String-usage-sso,
* @ref String(AllocatedInitT, StringView)
*/
/*implicit*/ String(StringView view);
/*implicit*/ String(Containers::ArrayView<const char> view); /**< @overload */
/* Without these there's ambiguity between StringView / ArrayView and
char* */
/*implicit*/ String(MutableStringView view); /**< @overload */
/*implicit*/ String(Containers::ArrayView<char> view); /**< @overload */
/**
* @brief Construct from a null-terminated C string
*
* Creates a null-terminated owning copy of @p data. Contrary to the
* behavior of @ref std::string, @p data is allowed to be
* @cpp nullptr @ce --- in that case an empty string is constructed.
* Depending on the size, it's either stored allocated or in a SSO.
* @see @ref Containers-String-usage-sso,
* @ref String(AllocatedInitT, const char*)
*/
/*implicit*/ String(const char* data);
/**
* @brief Construct from a sized C string
*
* Creates a null-terminated owning copy of @p data. Contrary to the
* behavior of @ref std::string, @p data is allowed to be
* @cpp nullptr @ce, but only if @p size is zero. Depending on the
* size, it's either stored allocated or in a SSO.
* @see @ref Containers-String-usage-sso,
* @ref String(AllocatedInitT, const char*, std::size_t)
*/
/*implicit*/ String(const char* data, std::size_t size);
/**
* @brief Construct from a string view, bypassing SSO
*
* Compared to @ref String(StringView) the data is always allocated.
* @see @ref Containers-String-usage-sso
*/
explicit String(AllocatedInitT, StringView view);
explicit String(AllocatedInitT, Containers::ArrayView<const char> view); /**< @overload */
/* Without these there's ambiguity between StringView / ArrayView and
char* */
explicit String(AllocatedInitT, MutableStringView view); /**< @overload */
explicit String(AllocatedInitT, Containers::ArrayView<char> view); /**< @overload */
/**
* @brief Construct from a null-terminated C string, bypassing SSO
*
* Compared to @ref String(const char*) the data is always allocated.
* @see @ref Containers-String-usage-sso
*/
explicit String(AllocatedInitT, const char* data);
/**
* @brief Construct from a sized C string
*
* Compared to @ref String(const char*, std::size_t) the data is always
* allocated.
* @see @ref Containers-String-usage-sso
*/
explicit String(AllocatedInitT, const char* data, std::size_t size);
/**
* @brief Take ownership of an external data array
* @param data String
* @param size Size of the string, excluding the null terminator
* @param deleter Deleter. Use @cpp nullptr @ce for the standard
* @cpp delete[] @ce.
*
* Since the @ref String class provides a guarantee of null-terminated
* strings, the @p data array is expected to be null-terminated (which
* implies @p data *can't* be @cpp nullptr @ce), but the null
* terminator not being included in @p size. For consistency and
* interoperability with @ref Array this in turn means the size passed
* to @p deleter is one byte less than the actual memory size, and if
* the deleter does sized deallocation, it has to account for that.
*/
explicit String(char* data, std::size_t size, Deleter deleter) noexcept;
/**
* @brief Take ownership of an immutable external data array
*
* Casts away the @cpp const @ce and delegates to
* @ref String(char*, std::size_t, Deleter). This constructor is
* provided mainly to allow a @ref String instance to reference global
* immutable data (such as C string literals) without having to
* allocate a copy, it's the user responsibility to avoid mutating the
* data in any way.
* @see @ref nullTerminatedView(), @ref nullTerminatedGlobalView()
*/
explicit String(const char* data, std::size_t size, Deleter deleter) noexcept: String{const_cast<char*>(data), size, deleter} {}
/**
* @brief Taking ownership of a null pointer is not allowed
*
* Since the @ref String class provides a guarantee of null-terminated
* strings, @p data *can't* be @cpp nullptr @ce.
*/
explicit String(std::nullptr_t, std::size_t size, Deleter deleter) = delete;
/**
* @brief Create a zero-initialized string of given size
* @param size Size excluding the null terminator
*
* A @ref DefaultInitT overload isn't provided to prevent accidents ---
* its behavior would be the same to @ref String(NoInitT, std::size_t).
* @see @ref String(DirectInitT, std::size_t, char)
*/
explicit String(Corrade::ValueInitT, std::size_t size);
/**
* @brief Create a string initialized to a particular character
* @param size Size excluding the null terminator
* @param c Character value
*
* @see @ref String(ValueInitT, std::size_t),
* @ref String(NoInitT, std::size_t)
*/
explicit String(Corrade::DirectInitT, std::size_t size, char c);
/**
* @brief Create an uninitialized string
* @param size Size excluding the null terminator
*
* While the string contents are left untouched, the null terminator
* *does* get initialized to @cpp '\0' @ce. Useful if you're going to
* overwrite the contents anyway.
*/
explicit String(Corrade::NoInitT, std::size_t size);
/** @todo combined AllocatedInit + Value/Direct/NoInit constructors */
/**
* @brief Construct a view on an external type / from an external representation
*
* @see @ref Containers-String-stl
*/
/* There's no restriction that would disallow creating StringView from
e.g. std::string<T>&& because that would break uses like
`consume(foo());`, where `consume()` expects a view but `foo()`
returns a std::vector. Besides that, to simplify the implementation,
there's no const-adding conversion. Instead, the implementer is
supposed to add an ArrayViewConverter variant for that. */
template<class T, class = decltype(Implementation::StringConverter<typename std::decay<T&&>::type>::from(std::declval<T&&>()))> /*implicit*/ String(T&& other) noexcept: String{Implementation::StringConverter<typename std::decay<T&&>::type>::from(std::forward<T>(other))} {}
/**
* @brief Destructor
*
* Calls @ref deleter() on the owned @ref data(); in case of a SSO does
* nothing.
* @see @ref Containers-String-usage-sso, @ref isSmall()
*/
~String();
/** @brief Copy constructor */
String(const String& other);
/** @brief Move constructor */
String(String&& other) noexcept;
/** @brief Copy assignment */
String& operator=(const String& other);
/** @brief Move assignment */
String& operator=(String&& other) noexcept;
/**
* @brief Convert to a const @ref ArrayView
*
* The resulting view has the same size as this string @ref size() ---
* the null terminator is not counted into it.
*/
/*implicit*/ operator ArrayView<const char>() const noexcept;
/*implicit*/ operator ArrayView<const void>() const noexcept; /**< @overload */
/**
* @brief Convert to an @ref ArrayView
*
* The resulting view has the same size as this string @ref size() ---
* the null terminator is not counted into it.
*/
/*implicit*/ operator ArrayView<char>() noexcept;
/*implicit*/ operator ArrayView<void>() noexcept; /**< @overload */
/**
* @brief Convert the view to external representation
*
* @see @ref Containers-String-stl
*/
/* To simplify the implementation, there's no const-adding conversion.
Instead, the implementer is supposed to add an StringViewConverter
variant for that. */
template<class T, class = decltype(Implementation::StringConverter<T>::to(std::declval<String>()))> /*implicit*/ operator T() const {
return Implementation::StringConverter<T>::to(*this);
}
/**
* @brief Whether the string is stored using small string optimization
*
* It's not allowed to call @ref deleter() or @ref release() on a SSO
* instance. See @ref Containers-String-usage-sso for more information.
*/
bool isSmall() const { return _small.size & 0x80; }
/**
* @brief String data
*
* The pointer is always guaranteed to be non-null and the data to be
* null-terminated, however note that the actual string might contain
* null bytes earlier than at the end.
*/
char* data();
const char* data() const; /**< @overload */
/**
* @brief String deleter
*
* If set to @cpp nullptr @ce, the contents are deleted using standard
* @cpp operator delete[] @ce. Can be called only if the string is not
* stored using SSO --- see @ref Containers-String-usage-sso for more
* information.
* @see @ref String(char*, std::size_t, Deleter)
*/
Deleter deleter() const;
/** @brief Whether the string is empty */
bool isEmpty() const;
/**
* @brief String size
*
* Excludes the null terminator.
* @see @ref isEmpty()
*/
std::size_t size() const;
/**
* @brief Pointer to the first byte
*
* @see @ref front()
*/
char* begin();
const char* begin() const; /**< @overload */
const char* cbegin() const; /**< @overload */
/**
* @brief Pointer to (one item after) the last byte
*
* @see @ref back()
*/
char* end();
const char* end() const; /**< @overload */
const char* cend() const; /**< @overload */
/**
* @brief First byte
*
* Expects there is at least one byte.
* @see @ref begin()
*/
char& front();
char front() const; /**< @overload */
/**
* @brief Last byte
*
* Expects there is at least one byte.
* @see @ref end()
*/
char& back();
char back() const; /**< @overload */
/** @brief Element access */
char& operator[](std::size_t i);
char operator[](std::size_t i) const; /**< @overload */
/**
* @brief String slice
*
* Equivalent to @ref BasicStringView::slice(). Both arguments are
* expected to be in range. If @p end points to (one item after) the
* end of the original (null-terminated) string, the result has
* @ref StringViewFlag::NullTerminated set.
* @m_keywords{substr()}
*/
MutableStringView slice(char* begin, char* end);
StringView slice(const char* begin, const char* end) const; /**< @overload */
MutableStringView slice(std::size_t begin, std::size_t end); /**< @overload */
StringView slice(std::size_t begin, std::size_t end) const; /**< @overload */
/**
* @brief String prefix
*
* Equivalent to @ref BasicStringView::prefix().
*/
MutableStringView prefix(char* end);
StringView prefix(const char* end) const; /**< @overload */
MutableStringView prefix(std::size_t end); /**< @overload */
StringView prefix(std::size_t end) const; /**< @overload */
/**
* @brief String suffix
*
* Equivalent to @ref BasicStringView::suffix().
*/
MutableStringView suffix(char* begin);
StringView suffix(const char* begin) const; /**< @overload */
MutableStringView suffix(std::size_t begin); /**< @overload */
StringView suffix(std::size_t begin) const; /**< @overload */
/**
* @brief String suffix
*
* Equivalent to @ref BasicStringView::except().
*/
MutableStringView except(std::size_t count);
StringView except(std::size_t count) const; /**< @overload */
/**
* @brief Split on given character
*
* Equivalent to @ref BasicStringView::split(). Not allowed to be
* called on a rvalue since the returned views would become dangling.
*/
Array<MutableStringView> split(char delimiter) &;
Array<StringView> split(char delimiter) const &; /**< @overload */
/**
* @brief Split on given character, removing empty parts
*
* Equivalent to @ref BasicStringView::splitWithoutEmptyParts(char) const.
* Not allowed to be called on a rvalue since the returned views would
* become dangling.
*/
Array<MutableStringView> splitWithoutEmptyParts(char delimiter) &;
Array<StringView> splitWithoutEmptyParts(char delimiter) const &; /**< @overload */
/**
* @brief Split on any character from given set, removing empty parts
*
* Equivalent to @ref BasicStringView::splitWithoutEmptyParts(StringView) const.
* Not allowed to be called on a rvalue since the returned views would
* become dangling.
*/
Array<MutableStringView> splitWithoutEmptyParts(StringView delimiters) &;
Array<StringView> splitWithoutEmptyParts(StringView delimiters) const &; /**< @overload */
/**
* @brief Split on whitespace, removing empty parts
*
* Equivalent to @ref BasicStringView::splitWithoutEmptyParts() const.
* Not allowed to be called on a rvalue since the returned views would
* become dangling.
*/
Array<MutableStringView> splitWithoutEmptyParts() &;
Array<StringView> splitWithoutEmptyParts() const &; /**< @overload */
/**
* @brief Partition
*
* Equivalent to @ref BasicStringView::partition(). Not allowed to be
* called on a rvalue since the returned views would become dangling.
*/
Array3<MutableStringView> partition(char separator) &;
Array3<StringView> partition(char separator) const &; /**< @overload */
/**
* @brief Join strings with this view as the delimiter
*
* Equivalent to @ref BasicStringView::join().
* @todo a mutable && overload that reuses the growable string storage
* instead of allocating new, when growable strings are a thing
*/
String join(ArrayView<const StringView> strings) const;
/** @overload */
String join(std::initializer_list<StringView> strings) const;
/**
* @brief Join strings with this view as the delimiter, skipping empty parts
*
* Equivalent to @ref BasicStringView::joinWithoutEmptyParts().
*/
String joinWithoutEmptyParts(ArrayView<const StringView> strings) const;
/** @overload */
String joinWithoutEmptyParts(std::initializer_list<StringView> strings) const;
/**
* @brief Whether the string begins with given prefix
*
* Equivalent to @ref BasicStringView::hasPrefix().
* @see @ref exceptPrefix()
*/
bool hasPrefix(StringView prefix) const;
/**
* @brief Whether the string ends with given suffix
*
* Equivalent to @ref BasicStringView::hasSuffix().
* @see @ref exceptSuffix()
*/
bool hasSuffix(StringView suffix) const;
/**
* @brief View with given prefix stripped
*
* Equivalent to @ref BasicStringView::exceptPrefix(). Not allowed to
* be called on a r-value since the returned view would become
* dangling.
* @see @ref hasPrefix()
*/
MutableStringView exceptPrefix(StringView prefix) &;
StringView exceptPrefix(StringView prefix) const &; /**< @overload */
#ifdef CORRADE_BUILD_DEPRECATED
/**
* @brief @copybrief exceptPrefix()
* @m_deprecated_since_latest Deprecated due to confusing naming that
* could imply the original instance gets modified. Use
* @ref exceptPrefix() instead.
*/
CORRADE_DEPRECATED("use exceptPrefix() instead") MutableStringView stripPrefix(StringView prefix) & {
return exceptPrefix(prefix);
}
/**
* @brief @copybrief exceptPrefix()
* @m_deprecated_since_latest Deprecated due to confusing naming that
* could imply the original instance gets modified. Use
* @ref exceptPrefix() instead.
*/
CORRADE_DEPRECATED("use exceptPrefix() instead") StringView stripPrefix(StringView prefix) const & {
return exceptPrefix(prefix);
}
#endif
/**
* @brief View with given suffix stripped
*
* Equivalent to @ref BasicStringView::exceptSuffix(). Not allowed to
* be called on a r-value since the returned view would become
* dangling.
* @see @ref hasSuffix()
*/
MutableStringView exceptSuffix(StringView suffix) &;
StringView exceptSuffix(StringView suffix) const &; /**< @overload */
#ifdef CORRADE_BUILD_DEPRECATED
/**
* @brief @copybrief exceptSuffix()
* @m_deprecated_since_latest Deprecated due to confusing naming that
* could imply the original instance gets modified. Use
* @ref exceptSuffix() instead.
*/
CORRADE_DEPRECATED("use exceptSuffix() instead") MutableStringView stripSuffix(StringView suffix) & {
return exceptSuffix(suffix);
}
/**
* @brief @copybrief exceptSuffix()
* @m_deprecated_since_latest Deprecated due to confusing naming that
* could imply the original instance gets modified. Use
* @ref exceptSuffix() instead.
*/
CORRADE_DEPRECATED("use exceptSuffix() instead") StringView stripSuffix(StringView suffix) const & {
return exceptSuffix(suffix);
}
#endif
/**
* @brief View with given characters trimmed from prefix and suffix
*
* Equivalent to @ref BasicStringView::trimmed(StringView) const. Not
* allowed to be called on a r-value since the returned view would
* become dangling.
* @see @ref trimmedPrefix(), @ref trimmedSuffix()
*/
MutableStringView trimmed(StringView characters) &;
StringView trimmed(StringView characters) const &; /**< @overload */
/**
* @brief View with whitespace trimmed from prefix and suffix
*
* Equivalent to @ref BasicStringView::trimmed() const. Not allowed to
* be called on a r-value since the returned view would become
* dangling.
* @see @ref trimmedPrefix(), @ref trimmedSuffix()
*/
MutableStringView trimmed() &;
StringView trimmed() const &; /**< @overload */
/**
* @brief View with given characters trimmed from prefix
*
* Equivalent to @ref BasicStringView::trimmedPrefix(StringView) const.
* Not allowed to be called on a r-value since the returned view would
* become dangling.
* @see @ref trimmed(), @ref trimmedSuffix()
*/
MutableStringView trimmedPrefix(StringView characters) &;
StringView trimmedPrefix(StringView characters) const &; /**< @overload */
/**
* @brief View with whitespace trimmed from prefix
*
* Equivalent to @ref BasicStringView::trimmedPrefix() const. Not
* allowed to be called on a r-value since the returned view would
* become dangling.
* @see @ref trimmed(), @ref trimmedSuffix()
*/
MutableStringView trimmedPrefix() &;
StringView trimmedPrefix() const &; /**< @overload */
/**
* @brief View with given characters trimmed from suffix
*
* Equivalent to @ref BasicStringView::trimmedSuffix(StringView) const.
* Not allowed to be called on a r-value since the returned view would
* become dangling.
* @see @ref trimmed(), @ref trimmedPrefix()
*/
MutableStringView trimmedSuffix(StringView characters) &;
StringView trimmedSuffix(StringView characters) const &; /**< @overload */
/**
* @brief View with whitespace trimmed from suffix
*
* Equivalent to @ref BasicStringView::trimmedSuffix() const. Not
* allowed to be called on a r-value since the returned view would
* become dangling.
* @see @ref trimmed(), @ref trimmedPrefix()
*/
MutableStringView trimmedSuffix() &;
StringView trimmedSuffix() const &; /**< @overload */
/**
* @brief Find a substring
*
* Equivalent to @ref BasicStringView::find(). Not allowed to be called
* on a r-value since the returned view would become dangling.
* @see @ref contains()
*/
MutableStringView find(StringView substring) &;
StringView find(StringView substring) const &; /**< @overload */
/**
* @brief Whether the view contains a substring
*
* Equivalent to @ref BasicStringView::contains().
*/
bool contains(StringView substring) const;
/**
* @brief Release data storage
*
* Returns the data pointer and resets data pointer, size and deleter
* to be equivalent to a default-constructed instance. Can be called
* only if the string is not stored using SSO --- see
* @ref Containers-String-usage-sso for more information. Deleting the
* returned array is user responsibility --- note the string might have
* a custom @ref deleter() and so @cpp delete[] @ce might not be always
* appropriate.
*/
char* release();
private:
CORRADE_UTILITY_LOCAL void construct(Corrade::NoInitT, std::size_t size);
CORRADE_UTILITY_LOCAL void construct(const char* data, std::size_t size);
CORRADE_UTILITY_LOCAL void destruct();
CORRADE_UTILITY_LOCAL std::pair<const char*, std::size_t> dataInternal() const;
/* Small string optimization. Following size restrictions from
StringView (which uses the top two bits for marking global and
null-terminated views), we can use the highest bit to denote a small
string. The second highest bit is currently unused, as it wouldn't
make sense to allow a String to be larger than StringView, since
these are two mutually convertible and interchangeable in many
cases. In case of a large string, there's size, data pointer and
deleter pointer, either 24 (or 12) bytes in total. In case of a
small string, we can store the size only in one byte out of 8 (or
4), which then gives us 23 (or 11) bytes for storing the actual
data, excluding the null terminator that's at most 22 / 10 ASCII
chars. With the two topmost bits reserved, it's still 6 bits left
for the size, which is more than enough in this case.
On LE the layout is as follows (bits inside a byte are flipped for
clarity as well):
+-------------------------------+---------+
| string | si | 01 |
| data | ze | |
| 23B/11B | 6b | 2b |
+-------------------+-----+++++++---------+
| LSB ||||||| MSB |
+---------+---------+-----+++++++---------+
| data | data | size | 00 |
| pointer | deleter | | |
| 8B/4B | 8B/4B | 56b/24b | 6b | 2b |
+---------+---------+-----------+---------+
On BE it's like this:
+---------+-------------------------------+
| 10 | si | string |
| | ze | data |
| 2b | 6b | 23B/11B |
+---------+++++++-----+-------------------+
| MSB ||||||| LSB |
+---------+++++++-----+---------+---------+
| 00 | size | data | data |
| | | pointer | deleter |
| 2b | 6b | 56b/24b | 8B/4B | 8B/4B |
+---------+-----------+---------+---------+
I originally tried storing the "small string" bit in the lowest bit
of the deleter pointer, but function pointers apparently can have
odd addresses on some platforms as well:
http://lists.llvm.org/pipermail/llvm-dev/2018-March/121953.html
The above approach is consistent with StringView, which is the
preferrable solution after all. */
struct Small {
#ifdef CORRADE_TARGET_BIG_ENDIAN
std::uint8_t size;
char data[Implementation::SmallStringSize];
#else
char data[Implementation::SmallStringSize];
std::uint8_t size;
#endif
};
struct Large {
#ifdef CORRADE_TARGET_BIG_ENDIAN
std::size_t size;
char* data;
void(*deleter)(char*, std::size_t);
#else
char* data;
void(*deleter)(char*, std::size_t);
std::size_t size;
#endif
};
union {
Small _small;
Large _large;
};
};
/* operator<<(Debug&, const String&) implemented directly in Debug; comparison
operators used from StringView (otherwise we would need several overloads
enumerating all possible combinations including conversion from char arrays
and external representations to avoid ambiguity, which is not feasible) */
}}
#endif
| [
"mosra@centrum.cz"
] | mosra@centrum.cz |
5fb47259723b34c6d0ff91a7e6da9c680d4ee602 | 74c8da5b29163992a08a376c7819785998afb588 | /NetAnimal/Game/wheel/UnitTest/include/UITest.h | 9a7897b90a3cf57222734e505cdada9109643b79 | [] | no_license | dbabox/aomi | dbfb46c1c9417a8078ec9a516cc9c90fe3773b78 | 4cffc8e59368e82aed997fe0f4dcbd7df626d1d0 | refs/heads/master | 2021-01-13T14:05:10.813348 | 2011-06-07T09:36:41 | 2011-06-07T09:36:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,289 | h | #ifndef __Orz_UnitTest_UITest__
#define __Orz_UnitTest_UITest__
#include "UnitTestConfig.h"
#include <CEGUI/cegui.h>
/*
#include "Engine.h"
#include "KeyToMessage.h"
#include "SingleChipToMessage.h"*/
BOOST_AUTO_TEST_CASE(UITest)
{
using namespace CEGUI;
//CEGUI::SchemeManager::getSingleton().create("TaharezLook.scheme");
//CEGUI::SchemeManager::getSingleton().create("VanillaSkin.scheme");
ImagesetManager::getSingleton().create("UI1.imageset");
ImagesetManager::getSingleton().create("UI2.imageset");
ImagesetManager::getSingleton().create("UI3.imageset");
//ImagesetManager::getSingleton().create("UI4.imageset");
CEGUI::System::getSingleton().setGUISheet(CEGUI::WindowManager::getSingleton().loadWindowLayout("AnimalUI.layout"));
CEGUI::System::getSingleton().updateWindowContainingMouse();
CEGUI::Window * _win= CEGUI::WindowManager::getSingleton().loadWindowLayout("dan.layout");
_win->setAlwaysOnTop(true);
_win->hide();
CEGUI::Window * f = CEGUI::WindowManager::getSingleton().getWindow("AnimalUI");
f->addChildWindow(_win);
_win->show();
CEGUI::System::getSingleton().updateWindowContainingMouse();
UnitTestEnvironmen::system->run();
UnitTestEnvironmen::system->run();
UnitTestEnvironmen::system->run();
}
#endif | [
"ogre3d@yeah.net"
] | ogre3d@yeah.net |
cd20f1e8ac63f897c0acad0be2361a2199944ea2 | 886c9b0d58bcc336c0e6714df4d20e6e98b74aa7 | /projects/NarutoSenki/Classes/GameMode/Impl/Deathmatch.hpp | c1167d33ce8a8a4c2dc7f36c54da1bff27d8777d | [] | no_license | Fansirsqi/NarutoSenki-V2 | 6e990cb10c50ef6b5a495e65673d75d70624efaa | 093caa9be474f500b95a13d1cfdf9030cd7bed81 | refs/heads/master | 2023-08-23T17:41:13.307163 | 2021-10-15T08:44:43 | 2021-10-15T08:44:43 | 417,427,912 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 436 | hpp | #pragma once
#include "GameMode/IGameModeHandler.hpp"
class ModeDeathmatch : public IGameModeHandler
{
public:
void init()
{
CCLOG("Enter Deathmatch mode.");
gd.isHardCore = true;
}
void onInitHeros()
{
initHeros(3, 3);
}
void onGameStart()
{
}
void onGameOver()
{
}
void onCharacterInit(CharacterBase *c)
{
}
void onCharacterDead(CharacterBase *c)
{
}
void onCharacterReborn(CharacterBase *c)
{
}
};
| [
"reaperofblack@gmail.com"
] | reaperofblack@gmail.com |
56f1c6e0c8b54a2cb2d86d78d63f52d9776702a1 | 22d707162a486ac2ed9d4b35de860c491bbe8a82 | /Devil's bones/SourceTest.cpp | 78987680946d925775f7a399fe7078beb2fe967e | [] | no_license | PawelWedmedev/Games-on- | 2c134c4e39893ec0871234fddd2c39ab932ab2f0 | bde527f78b19a4c26fd9fdbe5e897bb5cfe80974 | refs/heads/master | 2021-01-01T17:39:46.938511 | 2017-07-24T11:04:29 | 2017-07-24T11:04:29 | 98,125,874 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 37,723 | cpp | #include <iostream>
#include <ctime>
#include <Windows.h>
#include <iomanip>
#include <conio.h>
#include <string.h>
using namespace std;
void GotoXY(int X, int Y)
{
HANDLE hConsole;
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
COORD coord = { X, Y };
SetConsoleCursorPosition(hStdOut, coord);
}
void gotoxy(short x, short y)
{
COORD coord = { x, y };
HANDLE h = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleCursorPosition(h, coord);
}
enum ConsoleColor
{
Black, Blue, Green, Cyan, Red, Magenta, Brown, LightGray, DarkGray, LightBlue,
LightGreen, LightCyan, LightRed, LightMagenta, Yellow, White
};
void SetColor(int text, int background = Black)
{
HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdOut, (WORD)((background << 4) | text));
}
void main()
{
setlocale(LC_ALL, "");
srand(time(NULL));
int count_s = 3;
int k = 1;
int kr = 1;
char en = 0;
int ex = 0;
int b;
int ar[5];
int a;
char name[] = { " " };
char name2[] = { " " };
short coursechoices, coursechoices1;
//************************переменные человек
short sum, sum1 = 0, sum2 = 0, sumS = 0;
short number = 0, numbersum = 0;
//************************переменные комп
short sumk, sum1k = 0, sum2k = 0, sumSk = 0;
short numberk = 0, numbersumk = 0;
//************************переменные игрок № 1
short sum3, sum13 = 0, sum23 = 0, sumS3 = 0;
short number3 = 0, numbersum3 = 0;
//************************переменные игрок № 2
short sumk2, sum1k2 = 0, sum2k2 = 0, sumSk2 = 0;
short numberk2 = 0, numbersumk2 = 0;
cout << endl;
SetColor(1, 0);
cout << " $$ $$ $$ $$ $$$$$ $$ $$ $$ $$ $$ $$ $$ $$ $$$$" << endl;
cout << " $$ $$ $$ $$ $$ $$ $$ $$ $$ $$ $$ $$ $$ $$ $$" << endl;
SetColor(14, 0);
cout << " $$$$ $$$$ $$$$$ $$ $$$ $$$$ $$ $$$ $$ $$ $$$$$$" << endl;
cout << " $$ $$ $$ $$ $$ $$$ $$ $$ $$ $$$ $$ $$ $$ $$ $$" << endl;
cout << " $$ $$ $$$ $$$$$ $$ $$ $$ $$ $$ $$ $$ $$$$ $$ $$" << endl;
SetColor(14, 0);
cout << endl << endl << endl << endl;
cout << "\t\t\t Введите Ваше имя _";
cin>> name;
system("cls");
do
{
cout << endl;
if (en == 80)
{
k++;
if (k == 6)
k = 1;
}
if (en == 72)
{
k--;
if (k == 0)
k = 5;
}
if (en == 13)
{
// ***************игра одному, меню №1
if (k == 1)
{
//************* первое меню игра с компом
SetColor(1, 0);
gotoxy(22, 13);
cout << " Выберите кто первый начинает игру" << endl;
SetColor(14, 0);
gotoxy(4, 16);
cout << name << endl;
gotoxy(2, 17);
cout<<"нажмите " << endl;
//*****************1
SetColor(1, 0);
gotoxy(2, 19);
cout << " $$" << endl;
gotoxy(2, 20);
cout << " $$$$" << endl;
gotoxy(2, 21);
cout << " $$" << endl;
gotoxy(2, 22);
cout << " $$" << endl;
gotoxy(2, 23);
cout << " $$" << endl;
//****************2
SetColor(14, 0);
gotoxy(65,15);
cout << " противник " << endl;
gotoxy(66, 16);
cout<<" нажмите" << endl;
SetColor(1, 0);
gotoxy(63, 18);
cout << " $$$$" << endl;
gotoxy(63, 19);
cout << " $$ $$" << endl;
gotoxy(63, 20);
cout << " $$" << endl;
gotoxy(63 ,21);
cout << " $$" << endl;
gotoxy(63, 22);
cout << " $$$$$$" << endl;
SetColor(14, 0);
gotoxy(39, 19);
cin >> coursechoices;
// выбираем очередность
if (coursechoices == 1)
{
for (int i(0); i < 5; i++)
{
SetColor(14, 0);
gotoxy(23, 20);
cout<< name << ", для броска нажмите пробел..." << endl;
system("pause>>NUL");
system("cls");
// бросок человека
for (int i(0); i <= 10; i++)
{
sum = 0;
int a = rand() % 6 + 1;
switch (a)
{
case 1: GotoXY(20, 5);
SetColor(12, 0);
cout << "***************" << endl;
GotoXY(20, 6);
cout << "* *" << endl;
GotoXY(20, 7);
cout << "* *" << endl;
GotoXY(20, 8);
cout << "* O *" << endl;
GotoXY(20, 9);
cout << "* *" << endl;
GotoXY(20, 10);
cout << "* *" << endl;
GotoXY(20, 11);
cout << "***************" << endl;
sum1 = 1;
break;
case 2: GotoXY(20, 5);
SetColor(12, 0);
cout << "***************" << endl;
GotoXY(20, 6);
cout << "* 0 *" << endl;
GotoXY(20, 7);
cout << "* *" << endl;
GotoXY(20, 8);
cout << "* *" << endl;
GotoXY(20, 9);
cout << "* *" << endl;
GotoXY(20, 10);
cout << "* 0 *" << endl;
GotoXY(20, 11);
cout << "***************" << endl;
sum1 = 2;
break;
case 3: GotoXY(20, 5);
SetColor(12, 0);
cout << "***************" << endl;
GotoXY(20, 6);
cout << "* 0 *" << endl;
GotoXY(20, 7);
cout << "* *" << endl;
GotoXY(20, 8);
cout << "* 0 *" << endl;
GotoXY(20, 9);
cout << "* *" << endl;
GotoXY(20, 10);
cout << "* 0 *" << endl;
GotoXY(20, 11);
cout << "***************" << endl;
sum1 = 3;
break;
case 4: GotoXY(20, 5);
SetColor(12, 0);
cout << "***************" << endl;
GotoXY(20, 6);
cout << "* 0 0 *" << endl;
GotoXY(20, 7);
cout << "* *" << endl;
GotoXY(20, 8);
cout << "* *" << endl;
GotoXY(20, 9);
cout << "* *" << endl;
GotoXY(20, 10);
cout << "* 0 0 *" << endl;
GotoXY(20, 11);
cout << "***************" << endl;
sum1 = 4;
break;
case 5: GotoXY(20, 5);
SetColor(12, 0);
cout << "***************" << endl;
GotoXY(20, 6);
cout << "* 0 0 *" << endl;
GotoXY(20, 7);
cout << "* *" << endl;
GotoXY(20, 8);
cout << "* 0 *" << endl;
GotoXY(20, 9);
cout << "* *" << endl;
GotoXY(20, 10);
cout << "* 0 0 *" << endl;
GotoXY(20, 11);
cout << "***************" << endl;
sum1 = 5;
break;
case 6: GotoXY(20, 5);
SetColor(12, 0);
cout << "***************" << endl;
GotoXY(20, 6);
cout << "* 0 0 *" << endl;
GotoXY(20, 7);
cout << "* *" << endl;
GotoXY(20, 8);
cout << "* 0 0 *" << endl;
GotoXY(20, 9);
cout << "* *" << endl;
GotoXY(20, 10);
cout << "* 0 0 *" << endl;
GotoXY(20, 11);
cout << "***************" << endl;
sum1 = 6;
break;
}
int b = rand() % 6 + 1;
switch (b)
{
case 1: GotoXY(45, 5);
SetColor(12, 0);
cout << "***************" << endl;
GotoXY(45, 6);
cout << "* *" << endl;
GotoXY(45, 7);
cout << "* *" << endl;
GotoXY(45, 8);
cout << "* O *" << endl;
GotoXY(45, 9);
cout << "* *" << endl;
GotoXY(45, 10);
cout << "* *" << endl;
GotoXY(45, 11);
cout << "***************" << endl;
sum2 = 1;
break;
case 2: GotoXY(45, 5);
SetColor(12, 0);
cout << "***************" << endl;
GotoXY(45, 6);
cout << "* 0 *" << endl;
GotoXY(45, 7);
cout << "* *" << endl;
GotoXY(45, 8);
cout << "* *" << endl;
GotoXY(45, 9);
cout << "* *" << endl;
GotoXY(45, 10);
cout << "* 0 *" << endl;
GotoXY(45, 11);
cout << "***************" << endl;
sum2 = 2;
break;
case 3: GotoXY(45, 5);
SetColor(12, 0);
cout << "***************" << endl;
GotoXY(45, 6);
cout << "* 0 *" << endl;
GotoXY(45, 7);
cout << "* *" << endl;
GotoXY(45, 8);
cout << "* 0 *" << endl;
GotoXY(45, 9);
cout << "* *" << endl;
GotoXY(45, 10);
cout << "* 0 *" << endl;
GotoXY(45, 11);
cout << "***************" << endl;
sum2 = 3;
break;
case 4: GotoXY(45, 5);
SetColor(12, 0);
cout << "***************" << endl;
GotoXY(45, 6);
cout << "* 0 0 *" << endl;
GotoXY(45, 7);
cout << "* *" << endl;
GotoXY(45, 8);
cout << "* *" << endl;
GotoXY(45, 9);
cout << "* *" << endl;
GotoXY(45, 10);
cout << "* 0 0 *" << endl;
GotoXY(45, 11);
cout << "***************" << endl;
sum2 = 4;
break;
case 5:GotoXY(45, 5);
SetColor(12, 0);
cout << "***************" << endl;
GotoXY(45, 6);
cout << "* 0 0 *" << endl;
GotoXY(45, 7);
cout << "* *" << endl;
GotoXY(45, 8);
cout << "* 0 *" << endl;
GotoXY(45, 9);
cout << "* *" << endl;
GotoXY(45, 10);
cout << "* 0 0 *" << endl;
GotoXY(45, 11);
cout << "***************" << endl;
sum2 = 5;
break;
case 6: GotoXY(45, 5);
SetColor(12, 0);
cout << "***************" << endl;
GotoXY(45, 6);
cout << "* 0 0 *" << endl;
GotoXY(45, 7);
cout << "* *" << endl;
GotoXY(45, 8);
cout << "* 0 0 *" << endl;
GotoXY(45, 9);
cout << "* *" << endl;
GotoXY(45, 10);
cout << "* 0 0 *" << endl;
GotoXY(45, 11);
cout << "***************" << endl;
sum2 = 6;
break;
}
sum = sum1 + sum2;
}
number++;
numbersum += number;
sumS += sum;
SetColor(12, 0);
GotoXY(20, 1);
cout << "За " << number << " бросок " << name << " зарабатываете " << sum << " очков " << endl;
GotoXY(25, 2);
cout << "Всего очков за " << numbersum << " бросков = " << sumS << endl;
numbersum = 0;
SetColor(14, 0);
if (numberk == 5)
break;
cout << endl;
Sleep(1350);
m1:
//********************************** бросок комп
for (int i(0); i <= 10; i++)
{
sumk = 0;
int a = rand() % 6 + 1;
switch (a)
{
case 1: GotoXY(20, 5);
SetColor(9, 0);
cout << "***************" << endl;
GotoXY(20, 6);
cout << "* *" << endl;
GotoXY(20, 7);
cout << "* *" << endl;
GotoXY(20, 8);
cout << "* O *" << endl;
GotoXY(20, 9);
cout << "* *" << endl;
GotoXY(20, 10);
cout << "* *" << endl;
GotoXY(20, 11);
cout << "***************" << endl;
sum1k = 1;
break;
case 2: GotoXY(20, 5);
SetColor(9, 0);
cout << "***************" << endl;
GotoXY(20, 6);
cout << "* 0 *" << endl;
GotoXY(20, 7);
cout << "* *" << endl;
GotoXY(20, 8);
cout << "* *" << endl;
GotoXY(20, 9);
cout << "* *" << endl;
GotoXY(20, 10);
cout << "* 0 *" << endl;
GotoXY(20, 11);
cout << "***************" << endl;
sum1k = 2;
break;
case 3: GotoXY(20, 5);
SetColor(9, 0);
cout << "***************" << endl;
GotoXY(20, 6);
cout << "* 0 *" << endl;
GotoXY(20, 7);
cout << "* *" << endl;
GotoXY(20, 8);
cout << "* 0 *" << endl;
GotoXY(20, 9);
cout << "* *" << endl;
GotoXY(20, 10);
cout << "* 0 *" << endl;
GotoXY(20, 11);
cout << "***************" << endl;
sum1k = 3;
break;
case 4: GotoXY(20, 5);
SetColor(9, 0);
cout << "***************" << endl;
GotoXY(20, 6);
cout << "* 0 0 *" << endl;
GotoXY(20, 7);
cout << "* *" << endl;
GotoXY(20, 8);
cout << "* *" << endl;
GotoXY(20, 9);
cout << "* *" << endl;
GotoXY(20, 10);
cout << "* 0 0 *" << endl;
GotoXY(20, 11);
cout << "***************" << endl;
sum1k = 4;
break;
case 5: GotoXY(20, 5);
SetColor(9, 0);
cout << "***************" << endl;
GotoXY(20, 6);
cout << "* 0 0 *" << endl;
GotoXY(20, 7);
cout << "* *" << endl;
GotoXY(20, 8);
cout << "* 0 *" << endl;
GotoXY(20, 9);
cout << "* *" << endl;
GotoXY(20, 10);
cout << "* 0 0 *" << endl;
GotoXY(20, 11);
cout << "***************" << endl;
sum1k = 5;
break;
case 6: GotoXY(20, 5);
SetColor(9, 0);
cout << "***************" << endl;
GotoXY(20, 6);
cout << "* 0 0 *" << endl;
GotoXY(20, 7);
cout << "* *" << endl;
GotoXY(20, 8);
cout << "* 0 0 *" << endl;
GotoXY(20, 9);
cout << "* *" << endl;
GotoXY(20, 10);
cout << "* 0 0 *" << endl;
GotoXY(20, 11);
cout << "***************" << endl;
sum1k = 6;
break;
}
int b = rand() % 6 + 1;
switch (b)
{
case 1: GotoXY(45, 5);
SetColor(9, 0);
cout << "***************" << endl;
GotoXY(45, 6);
cout << "* *" << endl;
GotoXY(45, 7);
cout << "* *" << endl;
GotoXY(45, 8);
cout << "* O *" << endl;
GotoXY(45, 9);
cout << "* *" << endl;
GotoXY(45, 10);
cout << "* *" << endl;
GotoXY(45, 11);
cout << "***************" << endl;
sum2k = 1;
break;
case 2: GotoXY(45, 5);
SetColor(9, 0);
cout << "***************" << endl;
GotoXY(45, 6);
cout << "* 0 *" << endl;
GotoXY(45, 7);
cout << "* *" << endl;
GotoXY(45, 8);
cout << "* *" << endl;
GotoXY(45, 9);
cout << "* *" << endl;
GotoXY(45, 10);
cout << "* 0 *" << endl;
GotoXY(45, 11);
cout << "***************" << endl;
sum2k = 2;
break;
case 3: GotoXY(45, 5);
SetColor(9, 0);
cout << "***************" << endl;
GotoXY(45, 6);
cout << "* 0 *" << endl;
GotoXY(45, 7);
cout << "* *" << endl;
GotoXY(45, 8);
cout << "* 0 *" << endl;
GotoXY(45, 9);
cout << "* *" << endl;
GotoXY(45, 10);
cout << "* 0 *" << endl;
GotoXY(45, 11);
cout << "***************" << endl;
sum2k = 3;
break;
case 4: GotoXY(45, 5);
SetColor(9, 0);
cout << "***************" << endl;
GotoXY(45, 6);
cout << "* 0 0 *" << endl;
GotoXY(45, 7);
cout << "* *" << endl;
GotoXY(45, 8);
cout << "* *" << endl;
GotoXY(45, 9);
cout << "* *" << endl;
GotoXY(45, 10);
cout << "* 0 0 *" << endl;
GotoXY(45, 11);
cout << "***************" << endl;
sum2k = 4;
break;
case 5:GotoXY(45, 5);
SetColor(9, 0);
cout << "***************" << endl;
GotoXY(45, 6);
cout << "* 0 0 *" << endl;
GotoXY(45, 7);
cout << "* *" << endl;
GotoXY(45, 8);
cout << "* 0 *" << endl;
GotoXY(45, 9);
cout << "* *" << endl;
GotoXY(45, 10);
cout << "* 0 0 *" << endl;
GotoXY(45, 11);
cout << "***************" << endl;
sum2k = 5;
break;
case 6: GotoXY(45, 5);
SetColor(9, 0);
cout << "***************" << endl;
GotoXY(45, 6);
cout << "* 0 0 *" << endl;
GotoXY(45, 7);
cout << "* *" << endl;
GotoXY(45, 8);
cout << "* 0 0 *" << endl;
GotoXY(45, 9);
cout << "* *" << endl;
GotoXY(45, 10);
cout << "* 0 0 *" << endl;
GotoXY(45, 11);
cout << "***************" << endl;
sum2k = 6;
break;
}
sumk = sum1k + sum2k;
}
numberk++;
numbersumk += numberk;
sumSk += sumk;
GotoXY(20, 15);
cout << "За " << numberk << " бросок компьютер зарабатывает " << sumk << " очков " << endl;
GotoXY(25, 16);
cout << "Всего очков за " << numbersumk << " бросков = " << sumSk << endl;
numbersumk = 0;
cout << endl;
SetColor(1, 0);
gotoxy(36, 19);
cout << " Ваш ход " << endl;
if (numberk == 6)
break;
}
}
else {system("cls");goto m1;}
Sleep(1350);
goto a1;
}
// ***************игра вдвоем, меню №2
if (k == 2)
{
cout << "\t\t\t Введите имя второго игрока _";
cin >> name2;
SetColor(1, 0);
gotoxy(22, 13);
cout << " Выберите кто первый начинает игру" << endl;
SetColor(14, 0);
gotoxy(4, 16);
cout << name << endl;
gotoxy(2, 17);
cout << "нажмите " << endl;
//*****************1
SetColor(1, 0);
gotoxy(2, 19);
cout << " $$" << endl;
gotoxy(2, 20);
cout << " $$$$" << endl;
gotoxy(2, 21);
cout << " $$" << endl;
gotoxy(2, 22);
cout << " $$" << endl;
gotoxy(2, 23);
cout << " $$" << endl;
//****************2
SetColor(14, 0);
gotoxy(68, 15);
cout << name2 << endl;
gotoxy(66, 16);
cout << " нажмите" << endl;
SetColor(1, 0);
gotoxy(63, 18);
cout << " $$$$" << endl;
gotoxy(63, 19);
cout << " $$ $$" << endl;
gotoxy(63, 20);
cout << " $$" << endl;
gotoxy(63, 21);
cout << " $$" << endl;
gotoxy(63, 22);
cout << " $$$$$$" << endl;
SetColor(14, 0);
gotoxy(39, 19);
cin >> coursechoices1;
// выбираем очередность
if (coursechoices1 == 1)
{
for (int i(0); i < 5; i++)
{
SetColor(14, 0);
gotoxy(23, 20);
cout << name << ", для броска нажмите пробел..." << endl;
system("pause>>NUL");
system("cls");
// бросок человека № 1
for (int i(0); i <= 10; i++)
{
sum3 = 0;
int a = rand() % 6 + 1;
switch (a)
{
case 1: GotoXY(20, 5);
SetColor(12, 0);
cout << "***************" << endl;
GotoXY(20, 6);
cout << "* *" << endl;
GotoXY(20, 7);
cout << "* *" << endl;
GotoXY(20, 8);
cout << "* O *" << endl;
GotoXY(20, 9);
cout << "* *" << endl;
GotoXY(20, 10);
cout << "* *" << endl;
GotoXY(20, 11);
cout << "***************" << endl;
sum13 = 1;
break;
case 2: GotoXY(20, 5);
SetColor(12, 0);
cout << "***************" << endl;
GotoXY(20, 6);
cout << "* 0 *" << endl;
GotoXY(20, 7);
cout << "* *" << endl;
GotoXY(20, 8);
cout << "* *" << endl;
GotoXY(20, 9);
cout << "* *" << endl;
GotoXY(20, 10);
cout << "* 0 *" << endl;
GotoXY(20, 11);
cout << "***************" << endl;
sum13 = 2;
break;
case 3: GotoXY(20, 5);
SetColor(12, 0);
cout << "***************" << endl;
GotoXY(20, 6);
cout << "* 0 *" << endl;
GotoXY(20, 7);
cout << "* *" << endl;
GotoXY(20, 8);
cout << "* 0 *" << endl;
GotoXY(20, 9);
cout << "* *" << endl;
GotoXY(20, 10);
cout << "* 0 *" << endl;
GotoXY(20, 11);
cout << "***************" << endl;
sum13 = 3;
break;
case 4: GotoXY(20, 5);
SetColor(12, 0);
cout << "***************" << endl;
GotoXY(20, 6);
cout << "* 0 0 *" << endl;
GotoXY(20, 7);
cout << "* *" << endl;
GotoXY(20, 8);
cout << "* *" << endl;
GotoXY(20, 9);
cout << "* *" << endl;
GotoXY(20, 10);
cout << "* 0 0 *" << endl;
GotoXY(20, 11);
cout << "***************" << endl;
sum13 = 4;
break;
case 5: GotoXY(20, 5);
SetColor(12, 0);
cout << "***************" << endl;
GotoXY(20, 6);
cout << "* 0 0 *" << endl;
GotoXY(20, 7);
cout << "* *" << endl;
GotoXY(20, 8);
cout << "* 0 *" << endl;
GotoXY(20, 9);
cout << "* *" << endl;
GotoXY(20, 10);
cout << "* 0 0 *" << endl;
GotoXY(20, 11);
cout << "***************" << endl;
sum13 = 5;
break;
case 6: GotoXY(20, 5);
SetColor(12, 0);
cout << "***************" << endl;
GotoXY(20, 6);
cout << "* 0 0 *" << endl;
GotoXY(20, 7);
cout << "* *" << endl;
GotoXY(20, 8);
cout << "* 0 0 *" << endl;
GotoXY(20, 9);
cout << "* *" << endl;
GotoXY(20, 10);
cout << "* 0 0 *" << endl;
GotoXY(20, 11);
cout << "***************" << endl;
sum13 = 6;
break;
}
int b = rand() % 6 + 1;
switch (b)
{
case 1: GotoXY(45, 5);
SetColor(12, 0);
cout << "***************" << endl;
GotoXY(45, 6);
cout << "* *" << endl;
GotoXY(45, 7);
cout << "* *" << endl;
GotoXY(45, 8);
cout << "* O *" << endl;
GotoXY(45, 9);
cout << "* *" << endl;
GotoXY(45, 10);
cout << "* *" << endl;
GotoXY(45, 11);
cout << "***************" << endl;
sum23 = 1;
break;
case 2: GotoXY(45, 5);
SetColor(12, 0);
cout << "***************" << endl;
GotoXY(45, 6);
cout << "* 0 *" << endl;
GotoXY(45, 7);
cout << "* *" << endl;
GotoXY(45, 8);
cout << "* *" << endl;
GotoXY(45, 9);
cout << "* *" << endl;
GotoXY(45, 10);
cout << "* 0 *" << endl;
GotoXY(45, 11);
cout << "***************" << endl;
sum23 = 2;
break;
case 3: GotoXY(45, 5);
SetColor(12, 0);
cout << "***************" << endl;
GotoXY(45, 6);
cout << "* 0 *" << endl;
GotoXY(45, 7);
cout << "* *" << endl;
GotoXY(45, 8);
cout << "* 0 *" << endl;
GotoXY(45, 9);
cout << "* *" << endl;
GotoXY(45, 10);
cout << "* 0 *" << endl;
GotoXY(45, 11);
cout << "***************" << endl;
sum23 = 3;
break;
case 4: GotoXY(45, 5);
SetColor(12, 0);
cout << "***************" << endl;
GotoXY(45, 6);
cout << "* 0 0 *" << endl;
GotoXY(45, 7);
cout << "* *" << endl;
GotoXY(45, 8);
cout << "* *" << endl;
GotoXY(45, 9);
cout << "* *" << endl;
GotoXY(45, 10);
cout << "* 0 0 *" << endl;
GotoXY(45, 11);
cout << "***************" << endl;
sum23 = 4;
break;
case 5:GotoXY(45, 5);
SetColor(12, 0);
cout << "***************" << endl;
GotoXY(45, 6);
cout << "* 0 0 *" << endl;
GotoXY(45, 7);
cout << "* *" << endl;
GotoXY(45, 8);
cout << "* 0 *" << endl;
GotoXY(45, 9);
cout << "* *" << endl;
GotoXY(45, 10);
cout << "* 0 0 *" << endl;
GotoXY(45, 11);
cout << "***************" << endl;
sum23 = 5;
break;
case 6: GotoXY(45, 5);
SetColor(12, 0);
cout << "***************" << endl;
GotoXY(45, 6);
cout << "* 0 0 *" << endl;
GotoXY(45, 7);
cout << "* *" << endl;
GotoXY(45, 8);
cout << "* 0 0 *" << endl;
GotoXY(45, 9);
cout << "* *" << endl;
GotoXY(45, 10);
cout << "* 0 0 *" << endl;
GotoXY(45, 11);
cout << "***************" << endl;
sum23 = 6;
break;
}
sum3 = sum13 + sum23;
}
number3++;
numbersum3 += number3;
sumS3 += sum3;
SetColor(12, 0);
GotoXY(20, 1);
cout << "За " << number3 << " бросок " << name << " зарабатываете " << sum3 << " очков " << endl;
GotoXY(25, 2);
cout << "Всего очков за " << numbersum3 << " бросков = " << sumS3 << endl;
numbersum3 = 0;
cout << endl;
SetColor(1, 0);
gotoxy(36, 19);
cout << " Ваш ход " << endl;
if (numberk2 == 5)
break;
cout << endl;
Sleep(1050);
//********************************** бросок игрок № 2
m2:
SetColor(14, 0);
gotoxy(23, 20);
cout << name2 << ", для броска нажмите пробел..." << endl;
system("pause>>NUL");
system("cls");
for (int i(0); i <= 10; i++)
{
sumk2 = 0;
int a = rand() % 6 + 1;
switch (a)
{
case 1: GotoXY(20, 5);
SetColor(9, 0);
cout << "***************" << endl;
GotoXY(20, 6);
cout << "* *" << endl;
GotoXY(20, 7);
cout << "* *" << endl;
GotoXY(20, 8);
cout << "* O *" << endl;
GotoXY(20, 9);
cout << "* *" << endl;
GotoXY(20, 10);
cout << "* *" << endl;
GotoXY(20, 11);
cout << "***************" << endl;
sum1k2 = 1;
break;
case 2: GotoXY(20, 5);
SetColor(9, 0);
cout << "***************" << endl;
GotoXY(20, 6);
cout << "* 0 *" << endl;
GotoXY(20, 7);
cout << "* *" << endl;
GotoXY(20, 8);
cout << "* *" << endl;
GotoXY(20, 9);
cout << "* *" << endl;
GotoXY(20, 10);
cout << "* 0 *" << endl;
GotoXY(20, 11);
cout << "***************" << endl;
sum1k2 = 2;
break;
case 3: GotoXY(20, 5);
SetColor(9, 0);
cout << "***************" << endl;
GotoXY(20, 6);
cout << "* 0 *" << endl;
GotoXY(20, 7);
cout << "* *" << endl;
GotoXY(20, 8);
cout << "* 0 *" << endl;
GotoXY(20, 9);
cout << "* *" << endl;
GotoXY(20, 10);
cout << "* 0 *" << endl;
GotoXY(20, 11);
cout << "***************" << endl;
sum1k2 = 3;
break;
case 4: GotoXY(20, 5);
SetColor(9, 0);
cout << "***************" << endl;
GotoXY(20, 6);
cout << "* 0 0 *" << endl;
GotoXY(20, 7);
cout << "* *" << endl;
GotoXY(20, 8);
cout << "* *" << endl;
GotoXY(20, 9);
cout << "* *" << endl;
GotoXY(20, 10);
cout << "* 0 0 *" << endl;
GotoXY(20, 11);
cout << "***************" << endl;
sum1k2 = 4;
break;
case 5: GotoXY(20, 5);
SetColor(9, 0);
cout << "***************" << endl;
GotoXY(20, 6);
cout << "* 0 0 *" << endl;
GotoXY(20, 7);
cout << "* *" << endl;
GotoXY(20, 8);
cout << "* 0 *" << endl;
GotoXY(20, 9);
cout << "* *" << endl;
GotoXY(20, 10);
cout << "* 0 0 *" << endl;
GotoXY(20, 11);
cout << "***************" << endl;
sum1k2 = 5;
break;
case 6: GotoXY(20, 5);
SetColor(9, 0);
cout << "***************" << endl;
GotoXY(20, 6);
cout << "* 0 0 *" << endl;
GotoXY(20, 7);
cout << "* *" << endl;
GotoXY(20, 8);
cout << "* 0 0 *" << endl;
GotoXY(20, 9);
cout << "* *" << endl;
GotoXY(20, 10);
cout << "* 0 0 *" << endl;
GotoXY(20, 11);
cout << "***************" << endl;
sum1k2 = 6;
break;
}
int b = rand() % 6 + 1;
switch (b)
{
case 1: GotoXY(45, 5);
SetColor(9, 0);
cout << "***************" << endl;
GotoXY(45, 6);
cout << "* *" << endl;
GotoXY(45, 7);
cout << "* *" << endl;
GotoXY(45, 8);
cout << "* O *" << endl;
GotoXY(45, 9);
cout << "* *" << endl;
GotoXY(45, 10);
cout << "* *" << endl;
GotoXY(45, 11);
cout << "***************" << endl;
sum2k2 = 1;
break;
case 2: GotoXY(45, 5);
SetColor(9, 0);
cout << "***************" << endl;
GotoXY(45, 6);
cout << "* 0 *" << endl;
GotoXY(45, 7);
cout << "* *" << endl;
GotoXY(45, 8);
cout << "* *" << endl;
GotoXY(45, 9);
cout << "* *" << endl;
GotoXY(45, 10);
cout << "* 0 *" << endl;
GotoXY(45, 11);
cout << "***************" << endl;
sum2k2 = 2;
break;
case 3: GotoXY(45, 5);
SetColor(9, 0);
cout << "***************" << endl;
GotoXY(45, 6);
cout << "* 0 *" << endl;
GotoXY(45, 7);
cout << "* *" << endl;
GotoXY(45, 8);
cout << "* 0 *" << endl;
GotoXY(45, 9);
cout << "* *" << endl;
GotoXY(45, 10);
cout << "* 0 *" << endl;
GotoXY(45, 11);
cout << "***************" << endl;
sum2k2 = 3;
break;
case 4: GotoXY(45, 5);
SetColor(9, 0);
cout << "***************" << endl;
GotoXY(45, 6);
cout << "* 0 0 *" << endl;
GotoXY(45, 7);
cout << "* *" << endl;
GotoXY(45, 8);
cout << "* *" << endl;
GotoXY(45, 9);
cout << "* *" << endl;
GotoXY(45, 10);
cout << "* 0 0 *" << endl;
GotoXY(45, 11);
cout << "***************" << endl;
sum2k2 = 4;
break;
case 5:GotoXY(45, 5);
SetColor(9, 0);
cout << "***************" << endl;
GotoXY(45, 6);
cout << "* 0 0 *" << endl;
GotoXY(45, 7);
cout << "* *" << endl;
GotoXY(45, 8);
cout << "* 0 *" << endl;
GotoXY(45, 9);
cout << "* *" << endl;
GotoXY(45, 10);
cout << "* 0 0 *" << endl;
GotoXY(45, 11);
cout << "***************" << endl;
sum2k2 = 5;
break;
case 6: GotoXY(45, 5);
SetColor(9, 0);
cout << "***************" << endl;
GotoXY(45, 6);
cout << "* 0 0 *" << endl;
GotoXY(45, 7);
cout << "* *" << endl;
GotoXY(45, 8);
cout << "* 0 0 *" << endl;
GotoXY(45, 9);
cout << "* *" << endl;
GotoXY(45, 10);
cout << "* 0 0 *" << endl;
GotoXY(45, 11);
cout << "***************" << endl;
sum2k2 = 6;
break;
}
sumk2 = sum1k2 + sum2k2;
}
numberk2++;
numbersumk2 += numberk2;
sumSk2 += sumk2;
GotoXY(20, 15);
cout << "За " << numberk2 << " бросок " << name2 << " зарабатываете " << sumk2 << " очков " << endl;
GotoXY(25, 16);
cout << "Всего очков за " << numbersumk2 << " бросков = " << sumSk2 << endl;
numbersumk2 = 0;
cout << endl;
SetColor(1, 0);
gotoxy(36, 19);
cout << " Ваш ход " << endl;
if (numberk2 == 6)
break;
cout << endl;
}
}
else goto m2;
Sleep(1350);
goto a1;
}
// *******************************правила
if (k == 3)
{
system("cls");
gotoxy(11, 10);
cout << "Правила просты и понятны, попробуйте играть и следуйте указаниям," << endl;
gotoxy(11, 11);
cout << "и если вам понравится, то приятный и веселый вечер вам обеспечен." << endl;
gotoxy(11,12);
cout << "Удачных бросков Вам и послушных костей!" << endl;
}
//*************************************результаты
if (k == 4)
{
gotoxy(15, 11);
a1:
system("cls");
SetColor(14, 0);
//********************************* вывод результатов после игры с компом
if (k == 1)
{
cout << "За игру " << name << " зарабатывает " << sumS << " очков " << endl;
cout << endl;
cout << "За игру компьютер зарабатывает " << sumSk << " очков " << endl;
if (sumS > sumSk)
cout << "Поздравляем " << name << ", он победитель !!!" << endl;
else if (sumS == sumSk)
cout << "Ничья..." << endl;
else if (sumS < sumSk)
cout << name << " проиграл." << endl;
}
//************************ вывод результатов после игры с другим человеком
if (k == 2)
{
cout << "За игру " << name << " зарабатывает " << sumS3 << " очков " << endl;
cout << endl;
cout << "За игру " << name2 << " зарабатывает " << sumSk2 << " очков " << endl;
if (sumS3 > sumSk2)
cout << "Поздравляем " << name << ", он победитель !!!" << endl;
else if (sumS3 == sumSk2)
cout << "Ничья..." << endl;
else if (sumS3 < sumSk2)
{cout << name << " проиграл." << endl; cout << name2 << " победитель !!! " << endl;}
}
cout << endl;
cout << "Для возврата в меню нажмите любую клавишу" << endl;
system("pause>>NUL");
system("cls");
}
}
gotoxy(38,3);
SetColor(14, 0);
cout << "***";
if (k == 1)
SetColor(1, 0);
gotoxy(28, 4);
cout << "В игру играет один игрок " << endl;
SetColor(14, 0);
if (k == 2)
SetColor(1, 0);
gotoxy(28,5);
cout << "В игру играет два игрока " << endl;
SetColor(14, 0);
if (k == 3)
SetColor(1, 0);
gotoxy(36, 6);
cout << "Правила " << endl;
SetColor(14, 0);
if (k == 4)
SetColor(1, 0);
gotoxy(34.8, 7);
cout << "Результаты " << endl;
SetColor(14, 0);
if (k == 5)
SetColor(1, 0);
gotoxy(37, 8);
cout << "Выход " << endl;
SetColor(14, 0);
} while (en = _getch());
//getchar();
}
| [
"30377456+PawelWedmedev@users.noreply.github.com"
] | 30377456+PawelWedmedev@users.noreply.github.com |
ad8139ee5d86f09b9c67c4f4296b20ee5fcd2c37 | 97dba80026128e9296e575bb58b9cc7867bbc77f | /topcoder/SRM664/BearPlaysDiv2.cpp | dd0d1b91beba5d218ee08f6fb9f5ceefdab691ec | [] | no_license | intfloat/AlgoSolutions | 5272be3dfd72485ff78888325a98c25b2623e3cb | 2f7b2f3c4c8a25eb46322e7f8894263ecd286248 | refs/heads/master | 2021-12-23T08:18:32.176193 | 2021-11-01T05:53:27 | 2021-11-01T05:53:27 | 9,474,989 | 18 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,721 | cpp | #include <vector>
#include <list>
#include <map>
#include <queue>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <string.h>
using namespace std;
typedef pair<int, int> point;
class BearPlaysDiv2 {
public:
string equalPiles(int, int, int);
point get(int x, int y) {
if (x > y) swap(x, y);
y -= x;
x += x;
if (x > y) swap(x, y);
return make_pair(x, y);
}
};
string BearPlaysDiv2::equalPiles(int A, int B, int C) {
if ((A + B + C) % 3) {
return "impossible";
}
int avg = (A + B + C) / 3;
bool dp[1505][1505];
memset(dp, false, sizeof dp);
queue<point> q;
q.push(make_pair(min(A, B), max(A, B)));
dp[min(A, B)][max(A, B)] = true;
while (!q.empty()) {
point tp = q.front();
q.pop();
point cur = get(tp.first, tp.second);
if (!dp[cur.first][cur.second]) {
dp[cur.first][cur.second] = true;
q.push(cur);
}
cur = get(tp.first, A + B + C - tp.first - tp.second);
if (!dp[cur.first][cur.second]) {
dp[cur.first][cur.second] = true;
q.push(cur);
}
cur = get(tp.second, A + B + C - tp.first - tp.second);
if (!dp[cur.first][cur.second]) {
dp[cur.first][cur.second] = true;
q.push(cur);
}
}
if (dp[avg][avg]) {
return "possible";
}
else return "impossible";
}
// <%:testing-code%>
//Powered by [KawigiEdit] 2.0!
| [
"wangliangpeking@gmail.com"
] | wangliangpeking@gmail.com |
b08004eafdf92290d4b80875eda7311619f8d674 | b001c2ceff80451e6aa2198972112ea134c8954c | /clientMain.cpp | 70c99204e274f9bd9ed6a5b977d6f8abc94c4dc7 | [] | no_license | chetan-anand/FTP_server_client | 50520e6da9d9060ccebb67c5f664de2dac05ee3f | 861c938b69b4f35fefd93bcfa0b38780f0d24b9a | refs/heads/master | 2020-12-24T17:35:46.572031 | 2014-04-24T18:52:29 | 2014-04-24T18:52:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,595 | cpp |
#include <string>
#include <iostream>
#include <unistd.h>
#include <errno.h>
#include <cstdio>
#include <cstring>
#include <dirent.h>
#include <sys/types.h>
#include <sstream>
#include <errno.h>
#include <sys/stat.h>
using namespace std;
namespace sys
{
inline bool isRegularFile(string path)
{
struct stat s;
if (stat(path.c_str(), &s)!=0) return false;
return (bool) (s.st_mode & S_IFREG);
}
inline string pwd()
{
char cwd[1024];
errno = 0;
getcwd(cwd, sizeof(cwd));
if(errno) return string(strerror(errno));
return string(cwd);
}
inline bool cd(string dir)
{
return chdir(dir.c_str()) != -1;
}
inline bool setRootDir(string dir)
{
errno = 0;
chroot(dir.c_str());
if(errno) false;
return true;
}
inline string ls(string arg)
{
string cmd = "ls";
if(arg != "") cmd += " " + arg;
cmd += " 2>&1\n";
errno = 0;
FILE* file = popen(cmd.c_str(), "r");
if(errno) return string(strerror(errno));
char buffer[1024];
stringstream fileList;
int n;
while((n=fread(buffer, 1, 1024, file))>0)
{
for (int i=0; i<n; i++)
{
if (buffer[i]=='\n') fileList<<'\r';
fileList<<buffer[i];
}
}
pclose(file);
return fileList.str();
}
inline string syst()
{
return string("UNIX");
}
}
/////////////////////////////////////includes/tcpSocket.h/////////////////////
#include<stdio.h>
#include <iostream>
#include <string>
#include <sstream>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
using namespace std;
class tcpSocket
{
private:
int m_sd; //socket file descriptor
string m_dest_addr;
unsigned short m_dest_port, m_src_port;
bool m_passive;
const static int RECV_STR_BUF_SIZE = 1024;
public:
tcpSocket();
tcpSocket(int sd);
unsigned short getSrcPort();
string getSrcHostname();
unsigned short getDestPort();
string getDestHostname();
bool connect(string hostname, unsigned short port);
bool bind();
bool bind(unsigned short port);
bool listen();
tcpSocket accept();
int sendString(string data);
int sendData(char* buffer, int size);
string recvString(int max_bytes);
string recvString();
int recvData(char* buffer, int size);
void close();
};
////////////////////////////////////////////////////////////////////////////////
tcpSocket::tcpSocket():
m_sd(0)
{}
tcpSocket::tcpSocket(int sd):
m_sd(sd)
{}
unsigned short tcpSocket::getSrcPort()
{
struct sockaddr_in localAddress;
socklen_t addressLength = sizeof(localAddress);
getsockname(m_sd, (struct sockaddr*)&localAddress, &addressLength);
return ntohs(localAddress.sin_port);
}
string tcpSocket::getSrcHostname()
{
struct sockaddr_in localAddress;
socklen_t addressLength = sizeof(localAddress);
getsockname(m_sd, (struct sockaddr*)&localAddress, &addressLength);
return string(inet_ntoa( localAddress.sin_addr));
//return string("127.0.0.1");
}
unsigned short tcpSocket::getDestPort()
{
struct sockaddr_in localAddress;
socklen_t addressLength = sizeof(localAddress);
getpeername(m_sd, (struct sockaddr*)&localAddress, &addressLength);
return ntohs(localAddress.sin_port);
}
string tcpSocket::getDestHostname()
{
struct sockaddr_in localAddress;
socklen_t addressLength = sizeof(localAddress);
getpeername(m_sd, (struct sockaddr*)&localAddress, &addressLength);
return string(inet_ntoa( localAddress.sin_addr));
//return string("127.0.0.1");
}
bool tcpSocket::connect(string hostname, unsigned short port)
{
stringstream strport;
strport<<port;
struct addrinfo hints, *res;
// first, load up address structs with getaddrinfo():
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
getaddrinfo(hostname.c_str(), strport.str().c_str(), &hints, &res);
// make a socket:
m_sd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
// connect!
return ::connect(m_sd, res->ai_addr, res->ai_addrlen) != -1;
}
bool tcpSocket::bind(unsigned short port)
{
stringstream strport;
strport<<port;
struct addrinfo hints, *res;
// first, load up address structs with getaddrinfo():
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; // use IPv4 or IPv6, whichever
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE; // fill in my IP for me
getaddrinfo(NULL, strport.str().c_str(), &hints, &res);
// make a socket:
m_sd = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
// bind it to the port we passed in to getaddrinfo():
bool success = ::bind(m_sd, res->ai_addr, res->ai_addrlen) != -1;
return success;
}
bool tcpSocket::bind()
{
return tcpSocket::bind(0);
}
bool tcpSocket::listen()
{
return ::listen(m_sd, 10) !=-1;
}
tcpSocket tcpSocket::accept()
{
struct sockaddr_storage their_addr;
socklen_t addr_size;
return tcpSocket(::accept(m_sd, (struct sockaddr *)&their_addr, &addr_size));
}
int tcpSocket::sendString(string data)
{
//if socket is uninitialized
if (m_sd <= 0)
{
return -1;
}
return send(m_sd, data.c_str(), data.length(), 0);
}
int tcpSocket::sendData(char* buffer, int size)
{
//if socket is uninitialized
if (m_sd <= 0)
{
return -1;
}
return send(m_sd, buffer, size, 0);
}
string tcpSocket::recvString(int max_bytes)
{
//if socket is uninitialized
if (m_sd <= 0)
{
return "";
}
char* buffer = new char[max_bytes];
int bytes_recveived = recv(m_sd, buffer, max_bytes-1, 0);
buffer[bytes_recveived] = '\0';
return string(buffer);
}
string tcpSocket::recvString()
{
return recvString(RECV_STR_BUF_SIZE);
}
int tcpSocket::recvData(char* buffer, int size)
{
//if socket is uninitialized
if (m_sd <= 0)
{
return -1;
}
return recv(m_sd, buffer, size, 0);
}
void tcpSocket::close()
{
::close(m_sd);
}
///////////////////////////////includes/ftpRequest.h/////////////////////////////////
#include <string>
#include <vector>
#include <sstream>
#include <cstdlib>
using namespace std;
class ftpRequest
{
private:
string m_cmd;
string m_arg;
public:
ftpRequest();
ftpRequest(string cmd);
ftpRequest(string cmd, string arg);
static ftpRequest parseFtpRequest(string s);
string toString();
string getCmd();
string getArg();
void setCmd(string cmd);
void setArg(string arg);
/// input: xx.yy.zz.ww:1234
/// output: xx,yy,zz,ww,high_byte(1234),low_byte(1234)
static string splitPortArg(string portArg);
/// input: xx,yy,zz,ww,high_byte(1234),low_byte(1234)
/// output: xx.yy.zz.ww:1234
static string combinePortArg(string portArg);
};
//#endif
///////////////////////////////////////////////////////////////////////////////
//#include "../includes/ftpRequest.h"
ftpRequest::ftpRequest() {}
ftpRequest::ftpRequest(string cmd)
{
m_cmd = cmd;
m_arg = string("");
}
ftpRequest::ftpRequest(string cmd, string arg)
{
m_cmd = cmd;
m_arg = arg;
}
/// input: string containing request from socket
/// output: ftpRequest object
ftpRequest ftpRequest::parseFtpRequest(string s)
{
int i = 0;
string cmd,arg;
cmd = "";
while(s[i] != ' ' && s[i] != '\r')
{
cmd += s[i];
i++;
}
arg = "";
if(s[i] == '\r') return ftpRequest(cmd,arg);
for(i += 1; s[i] != '\r'; i++)
{
arg += s[i];
}
if(cmd == "PORT")
{
arg = combinePortArg(arg);
}
return ftpRequest(cmd,arg);
}
string ftpRequest::toString()
{
if(m_arg == "")
{
return m_cmd + "\r\n";
}
else if(m_cmd == "PORT")
{
return m_cmd + " " + splitPortArg(m_arg) + "\r\n";
}
else
{
return m_cmd + " " + m_arg + "\r\n";
}
}
/// input: xx.yy.zz.ww:1234
/// output: xx,yy,zz,ww,high_byte(1234),low_byte(1234)
string ftpRequest::splitPortArg(string portArg)
{
int port;
stringstream convert;
for(int i=0;i<portArg.length();i++)
{
if(portArg[i]=='.') portArg[i] = ',';
if(portArg[i]==':')
{
portArg[i] = ',';
port = atoi(portArg.substr(i+1,portArg.length()-1-i).c_str());
portArg = portArg.substr(0,i+1);
convert << port/256 << "," << port%256;
portArg += convert.str();
break;
}
}
return portArg;
}
/// input: xx,yy,zz,ww,high_byte(1234),low_byte(1234)
/// output: xx.yy.zz.ww:1234
string ftpRequest::combinePortArg(string portArg)
{
int cnt = 0,port = 0, portTemp=0;
stringstream convert;
for(int i=0;i<portArg.length();i++)
{
if(portArg[i]==',')
{
cnt++;
if(cnt < 4)
{
portArg[i] = '.';
}
else if(cnt == 4)
{
portArg[i] = ':';
for(int j=i+1;j<portArg.length();j++)
{
if(portArg[j]==',')
{
port = port*256 + portTemp;
portTemp=0;
}
else if (isdigit(portArg[j]))
{
portTemp = portTemp*10 + (portArg[j]-'0');
}
else
{
port = port*256 + portTemp;
portTemp=0;
break;
}
}
port = port*256 + portTemp;
portTemp=0;
portArg = portArg.substr(0,i+1);
convert << port;
portArg += convert.str();
break;
}
}
}
return portArg;
}
string ftpRequest::getCmd()
{
return m_cmd;
}
string ftpRequest::getArg()
{
return m_arg;
}
void ftpRequest::setCmd(string cmd)
{
m_cmd = cmd;
}
void ftpRequest::setArg(string arg)
{
m_arg = arg;
}
//////////////////////////////////////includes/ftpResponse.h//////////////////////////
//#ifndef H_FTPRESPONSE
//#define H_FTPRESPONSE
#include <string>
#include <iostream>
#include <cstdlib>
using namespace std;
class ftpResponse
{
private:
int m_code;
string m_msg;
public:
ftpResponse();
ftpResponse(int code, string msg);
int getCode();
string getMessage();
void setCode(int code);
void setMessage(string msg);
/// input: string containing response from socket
/// output: ftpResponse object
static ftpResponse parseFtpResponse(string s);
string toString();
};
//#endif
//////////////////////////////////////////////////////////////////////////////////
//#include "../includes/ftpResponse.h"
#include <sstream>
ftpResponse::ftpResponse() {}
ftpResponse::ftpResponse(int code, string msg):
m_code(code),
m_msg(msg)
{}
int ftpResponse::getCode()
{
return m_code;
}
string ftpResponse::getMessage()
{
return m_msg;
}
void ftpResponse::setCode(int code)
{
m_code = code;
}
void ftpResponse::setMessage(string msg)
{
m_msg = msg;
}
/// input: string containing response from socket
/// output: ftpResponse object
ftpResponse ftpResponse::parseFtpResponse(string s)
{
int code;
string msg;
for (int i=0; i<s.length(); i++)
{
//split at space
if (s[i]==' ')
{
code = atoi(s.substr(0, i).c_str());
int j;
//end at "\r\n"
for (j=i+2; j<s.length() && !(s[j-1]=='\r' && s[j]=='\n'); j++);
msg = s.substr(i+1, j-1 - (i+1));
break;
}
}
return ftpResponse(code, msg);
}
string ftpResponse::toString()
{
stringstream s;
s<<m_code<<" "<<m_msg<<"\r\n";
return s.str();
}
//////////////////////////////////////////ftpclient.h////////////////////
//#ifndef H_FTPCLIENT
//#define H_FTPCLIENT
//#include "ftpResponse.h"
//#include "ftpRequest.h"
//#include "tcpSocket.h"
//#include "sys.h"
#include <ostream>
#include <iostream>
#define FILE_BLOCK_SIZE 1024
using namespace std;
class ftpClient
{
private:
unsigned short m_data_port;
unsigned short m_server_port;
string m_server_hostname;
tcpSocket m_control_socket;
tcpSocket m_data_socket;
ostream& m_log;
public:
ftpClient(string server_hostname, unsigned short server_port, ostream& log);
void setDataPort(unsigned short data_port);
void setServerPort(unsigned short server_port);
void setServerName(string server_hostname);
unsigned short getDataPort();
unsigned short getServerPort();
string getServerName();
tcpSocket getDataSocket();
tcpSocket getControlSocket();
ostream& getLog();
bool setupDataPort();
bool sendRequest(ftpRequest request);
ftpResponse recvResponse();
bool connect();
void sendUsername(string username);
bool sendPassword(string password);
void pwd();
void cd(string pathname);
void ls(string dir);
bool get(string filename, ostream& f);
bool put(string filename, istream& f);
void quit();
};
//#endif
/////////////////////////////////////////////////////////////////////////////////
//#include "../includes/ftpClient.h"
ftpClient::ftpClient(string server_hostname, unsigned short server_port, ostream& log):
m_log(log)
{
m_server_hostname = server_hostname;
m_server_port = server_port;
}
void ftpClient::setServerPort(unsigned short server_port)
{
m_server_port = server_port;
}
void ftpClient::setDataPort(unsigned short data_port)
{
m_data_port = data_port;
}
void ftpClient::setServerName(string server_hostname)
{
m_server_hostname = server_hostname;
}
unsigned short ftpClient::getDataPort()
{
return m_data_port;
}
unsigned short ftpClient::getServerPort()
{
return m_server_port;
}
string ftpClient::getServerName()
{
return m_server_hostname;
}
tcpSocket ftpClient::getDataSocket()
{
return m_data_socket;
}
tcpSocket ftpClient::getControlSocket()
{
return m_control_socket;
}
ostream& ftpClient::getLog()
{
return m_log;
}
bool ftpClient::setupDataPort()
{
if(m_data_socket.bind() && m_data_socket.listen())
{
m_data_port = m_data_socket.getSrcPort();
return true;
}
return false;
};
bool ftpClient::sendRequest(ftpRequest request)
{
return (m_control_socket.sendString(request.toString())>0);
}
ftpResponse ftpClient::recvResponse()
{
return ftpResponse::parseFtpResponse(m_control_socket.recvString());
}
bool ftpClient::connect()
{
if(!m_control_socket.connect(m_server_hostname,m_server_port))
{
ftpResponse response = recvResponse();
cout << response.getMessage() << endl;
return false;
}
else
{
ftpResponse response = recvResponse();
cout << response.getMessage() << endl;
return true;
}
}
void ftpClient::sendUsername(string username)
{
sendRequest(ftpRequest(string("USER"), username));
ftpResponse response = recvResponse();
cout << response.getMessage() << endl;
}
bool ftpClient::sendPassword(string password)
{
sendRequest(ftpRequest(string("PASS"), password));
ftpResponse response = recvResponse();
cout << response.getMessage() << endl;
if(response.getCode() == 230) return true;
else return false;
}
void ftpClient::pwd()
{
sendRequest(ftpRequest(string("PWD")));
ftpResponse response = recvResponse();
cout << response.getMessage() << endl;
}
void ftpClient::cd(string pathname)
{
sendRequest(ftpRequest(string("CWD"), pathname));
ftpResponse response = recvResponse();
cout << response.getMessage() << endl;
}
void ftpClient::ls(string dir)
{
stringstream clientInfo;
clientInfo << m_control_socket.getSrcHostname() << ":" << m_data_port;
sendRequest(ftpRequest(string("PORT"),clientInfo.str()));
tcpSocket cur_data_socket = m_data_socket.accept();
ftpResponse response = recvResponse();
cout << response.getMessage() << endl;
if(response.getCode() != 200) return;
sendRequest(ftpRequest(string("LIST ") + dir));
response = recvResponse();
cout << response.getMessage() << endl;
string s;
while((s = cur_data_socket.recvString()).length() > 0)
{
//cout << s << endl;
printf("%s", s.c_str());
}
cur_data_socket.close();
response = recvResponse();
cout << response.getMessage() << endl;
}
bool ftpClient::get(string filename, ostream& f)
{
sendRequest(ftpRequest(string("TYPE"), string("I")));
ftpResponse response = recvResponse();
cout << response.getMessage() << endl;
stringstream clientInfo;
clientInfo << m_control_socket.getSrcHostname() << ":" << m_data_port;
sendRequest(ftpRequest(string("PORT"), clientInfo.str()));
tcpSocket cur_data_socket = m_data_socket.accept();
response = recvResponse();
cout << response.getMessage() << endl;
if(response.getCode() != 200) return false;
sendRequest(ftpRequest(string("RETR"), filename));
response = recvResponse();
cout << response.getMessage() << endl;
if(response.getCode() != 150) return false;
string s;
char buffer[FILE_BLOCK_SIZE];
int bytes_received;
while((bytes_received = cur_data_socket.recvData(buffer,FILE_BLOCK_SIZE)) > 0)
{
f.write(buffer, bytes_received);
}
//cur_data_socket.close();
response = recvResponse();
cout << response.getMessage() << endl;
return true;
}
bool ftpClient::put(string filename, istream& f)
{
if (!sys::isRegularFile(filename))
{
cout << "File not present." << endl;
return false;
}
sendRequest(ftpRequest(string("TYPE"), string("I")));
ftpResponse response = recvResponse();
cout << response.getMessage() << endl;
stringstream clientInfo;
clientInfo << m_control_socket.getSrcHostname() << ":" << m_data_port;
sendRequest(ftpRequest(string("PORT"), clientInfo.str()));
tcpSocket cur_data_socket = m_data_socket.accept();
response = recvResponse();
cout << response.getMessage() << endl;
if(response.getCode() != 200) return false;
sendRequest(ftpRequest(string("STOR"), filename));
response = recvResponse();
cout << response.getMessage() << endl;
if(response.getCode() != 150) return false;
string s;
char buffer[FILE_BLOCK_SIZE];
while(!f.eof())
{
f.read(buffer, FILE_BLOCK_SIZE);
cur_data_socket.sendData(buffer, f.gcount());
}
cur_data_socket.close();
response = recvResponse();
cout << response.getMessage() << endl;
return true;
}
void ftpClient::quit()
{
sendRequest(ftpRequest(string("QUIT")));
ftpResponse response = recvResponse();
cout << response.getMessage() << endl;
}
////////////////////////////////////////////////////sys.h///////////////////
//#endif
/////////////////////////////////////////////////////////////////////////////////////
#include <unistd.h>
#include <iostream>
#include <cstdio>
#include <fstream>
#include <cstring>
#include <cctype>
/*#include "../includes/sys.h"
#include "../includes/ftpClient.h"
#include "../includes/ftpResponse.h"
#include "../includes/ftpRequest.h"
#include "../includes/tcpSocket.h"*/
using namespace std;
int main(int argc, char* argv[])
{
string hostname;
unsigned short port = 21;
if(argc<2)
{
printf("Specify hostname\n");
return 0;
}
hostname = string(argv[1]);
if(argc>2)
{
if(strlen(argv[2]) > 5)
{
printf("Invalid Port\n");
return 0;
}
port = 0;
for(int i=0; i<strlen(argv[2]); i++)
{
if(!isdigit(argv[2][i]))
{
printf("Invalid Port\n");
return 0;
}
port = port*10 + (argv[2][i] - '0');
}
}
ftpClient client(hostname,port,cout);
if(!client.connect()) printf("----------------Could not connect to server--------------------\n");
else
{
char username[100]="key";
char *password="123";
do
{
//printf("Enter Username: ");
//fgets(username, 100, stdin);
username[strlen(username)-1] = '\0';
client.sendUsername(username);
//password = getpass("Enter Password: ");
}while(!client.sendPassword(password));
if(!client.setupDataPort())
{
printf("Unable to setup data port\n");
return 0;
}
string cmd = "";
char buffer[100];
while(true)
{
printf("ftp> ");
*buffer=0;
fgets(buffer, 100, stdin);
cmd = string(strtok(buffer," \t\r\n"));
if(cmd == "pwd")
{
client.pwd();
}
else if(cmd == "ls")
{
char* dir = strtok(NULL,"\n");
if(dir) client.ls(dir);
else client.ls("");
}
else if(cmd == "cd")
{
char* dir = strtok(NULL,"\n");
if(dir) client.cd(dir);
}
else if(cmd == "get")
{
char* filename = strtok(NULL,"\n");
filebuf fb;
fb.open (filename, ios::out);
ostream os(&fb);
//ofstream f(filename);
if (fb.is_open()) client.get(filename, os);
else printf("Unable to create file\n");
fb.close();
}
else if(cmd == "put")
{
char* filename = strtok(NULL,"\n");
filebuf fb;
fb.open (filename, ios::in);
istream is(&fb);
//ifstream f(filename);
if (fb.is_open()) client.put(filename, is);
else printf("Unable to open file\n");
fb.close();
}
else if(cmd == "quit")
{
client.quit();
break;
}
else if(cmd == "!pwd")
{
cout << sys::pwd() << endl;
}
else if(cmd == "!ls")
{
char* dir = strtok(NULL,"\n");
if(dir) cout << sys::ls(dir) << endl;
else cout << sys::ls("") << endl;
}
else if(cmd == "!cd")
{
char* dir = strtok(NULL,"\n");
if(dir)
{
if(sys::cd(dir)) cout << "-----------------Directory successfully changed-----------------------------" << endl;
else cout << "Failed to change directory." << endl;
}
}
else
{
cout<<"Invalid command operation"<<endl;
}
}
}
return 0;
}
| [
"chetan.iitg@gmail.com"
] | chetan.iitg@gmail.com |
261be6ac49a5707ad825e1d0f7d5eec70b25fd7d | 5de4c4471ef8513ddbffe2d8b588ce42fbb9f8d9 | /String/q1.cpp | 2caffeefb69991279ceeedc51f45cf87df287b40 | [] | no_license | ayushgarg2702/CompitativePrograming | e89a608b08627fef5a31be3294cbf01fe5d3c831 | a6ad5f4b56b8bbb9e3efe1d1cfcf567c5958de33 | refs/heads/master | 2023-07-08T21:00:14.503515 | 2021-08-19T19:16:22 | 2021-08-19T19:16:22 | 391,043,787 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 884 | cpp | // Next largest lexicographically permutation for string
#include<bits/stdc++.h>
using namespace std;
void swap(char &a, char &b){
char temp = a;
a = b;
b = temp;
}
void interchange(string &str,int l, int h){
while(l<=h){
swap(str[l++],str[h--]);
}
}
string next_lexicographically_p(string &str){
int len = str.length();
int i = 0;
for(i = len-2; i >=0 ;i--){
if(str[i]<str[i+1]){
break;
}
}
if(i < 0){
return "no answer";
}
else{
int index;
for(int j = len - 1; j > 0; j--){
if(str[i]<str[j]){
index = j;
break;
}
}
swap(str[i],str[index]);
interchange(str,i+1,index);
}
return str;
}
int main(void){
string str = "bdc";
cout<< next_lexicographically_p(str);
return 0;
} | [
"ayush.garg1@celebaltech.com"
] | ayush.garg1@celebaltech.com |
f336b74a013a9e5ad672376262fcf951d6f58086 | 81617c2d561cc3d8b9eefaaa6deceb295634945b | /Rudy_Dustin_Asst09.cpp | c7c54fe94e150e2df1ccb56e624bb6458ba693bc | [] | no_license | dustinrudy/CS135 | 0a89a3e198fc7a750d32d57bb2360bf6d888b39b | 236a54b9dafa1e2ffaa0a46b4f7ef1fdff98fdee | refs/heads/master | 2020-04-03T05:03:34.583523 | 2018-10-28T03:55:52 | 2018-10-28T03:55:52 | 155,033,147 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,701 | cpp | #include <iostream>
#include <fstream>
#include <string>
using namespace std;
const int ROWS = 4;
const int COLS = 4;
///////// --------- Function Prototypes -------- //////////
void populateArray(ifstream&, char array[ROWS][COLS]);
void outputBoard(char charArray[ROWS][COLS], bool boolArray[ROWS][COLS]);
bool makeAMatch(char char_array[ROWS][COLS], bool bool_array[ROWS][COLS]);
int main() {
ifstream inFile;
char charArr[ROWS][COLS];
bool boolArr[ROWS][COLS] = {{false}};
int matches = 0;
int moves = 0;
bool result;
populateArray(inFile, charArr);
while(matches < 8) {
cout << "Moves Made: " << moves << endl;
cout << endl;
result = makeAMatch(charArr, boolArr);
if(result == true) {
matches++;
moves++;
} else {
moves++;
}
}
return 0;
}
/*
FUNCTION NAME: makeAMatch
PARAMETERS: the char 2darray from the file input stream, an 2darray of bool values;
RETURN TYPE: bool - if the characters are equal returns true; if characters are not equal returns false;
DESCRIPTION: this function will loop through and error check the inputs for x y coordinate system and make assignments to 2d bool array
if there is isn't a match or not a match and passing those values into outputBoard() which will output the matches or non matches;
*/
bool makeAMatch(char _char[ROWS][COLS], bool _bool[ROWS][COLS]) {
int x, y, x2, y2;
bool isInvalid = false;
bool result;
int move = 0;
outputBoard(_char, _bool);
cout << endl;
cout << "Part 1 Enter row and column index (1-4): ";
cin >> x >> y;
cout << endl;
x = x - 1;
y = y - 1;
isInvalid = false;
while(!isInvalid) {
if (_bool[x][y] == true) {
cin.clear();
cin.ignore(100, '\n');
cerr << "Invalid: (YA ALREADY PICKED IT!)" << endl;
cout << "Part 1 Enter row and column index (1-4): ";
cin >> x >> y;
cout << endl;
x = x - 1;
y = y - 1;
}
else if(x < 0 || y < 0) {
cin.clear();
cin.ignore(100, '\n');
cerr << "Invalid: (Enter Positive Integers)" << endl;
cout << "Part 1 Enter row and column index (1-4): ";
cin >> x >> y;
cout << endl;
x = x - 1;
y = y - 1;
} else if(cin.fail()) {
cin.clear();
cin.ignore(100, '\n');
cerr << "Invalid: (Enter Positive Integers)" << endl;
cout << "Part 1 Enter row and column index (1-4): ";
cin >> x >> y;
cout << endl;
x = x - 1;
y = y - 1;
} else if(x > 3 || y > 3) {
cin.clear();
cin.ignore(100, '\n');
cerr << "Invalid: (Number Out of Range)" << endl;
cout << "Part 1 Enter row and column index (1-4): ";
cout << endl;
cin >> x >> y;
x = x - 1;
y = y - 1;
} else if(x == x2 && y == y2) {
cin.clear();
cin.ignore(100, '\n');
cerr << "Invalid: Already Entered" << endl;
cout << "Part 1 Enter row and column index (1-4): ";
cin >> x >> y;
cout << endl;
x = x - 1;
y = y - 1;
}
else {
_bool[x][y] = true;
isInvalid = true;
}
}
outputBoard(_char, _bool);
cout << endl;
cout << "Part 2 Enter row and column index (1-4): ";
cin >> x2 >> y2;
cout << endl;
x2 = x2 - 1;
y2 = y2 - 1;
isInvalid = false;
while(!isInvalid) {
if (_bool[x2][y2] == true) {
cin.clear();
cin.ignore(100, '\n');
cerr << "Invalid: (YA ALREADY PICKED IT!)" << endl;
cout << "Part 2 Enter row and column index (1-4): ";
cin >> x2 >> y2;
cout << endl;
x2 = x2 - 1;
y2 = y2 - 1;
} else if(x2 < 0 || y2 < 0) {
cin.clear();
cin.ignore(100, '\n');
cerr << "Invalid: (Enter Positive Integers)" << endl;
cout << "Part 2 Enter row and column index (1-4): ";
cin >> x2 >> y2;
cout << endl;
x2 = x2 - 1;
y2 = y2 - 1;
} else if(cin.fail()) {
cin.clear();
cin.ignore(100, '\n');
cerr << "Invalid: (Enter Positive Integers)" << endl;
cout << "Part 2 Enter row and column index (1-4): ";
cin >> x2 >> y2;
cout << endl;
x2 = x2 - 1;
y2 = y2 - 1;
} else if (x2 > 3 || y2 > 3) {
cin.clear();
cin.ignore(100, '\n');
cerr << "Invalid: (Number Out of Range)" << endl;
cout << "Part 2 Enter row and column index (1-4): ";
cin >> x2 >> y2;
cout << endl;
x2 = x2 - 1;
y2 = y2 - 1;
} else if(x == x2 && y == y2) {
cin.clear();
cin.ignore(100, '\n');
cerr << "Invalid: Already Entered" << endl;
cout << "Part 2 Enter row and column index (1-4): ";
cin >> x >> y;
cout << endl;
x = x - 1;
y = y - 1;
}
else {
_bool[x2][y2] = true;
isInvalid = true;
}
}
if (_char[x][y] == _char[x2][y2]) {
_bool[x][y] = true;
_bool[x2][y2] = true;
outputBoard(_char, _bool);
cout << endl;
cout << "Match found!" << endl;
result = true;
} else if(_char[x][y] != _char[x2][y2]) {
_bool[x][y] = true;
_bool[x2][y2] = true;
outputBoard(_char, _bool);
cout << endl;
cout << "No match found!" << endl;
_bool[x][y] = false;
_bool[x2][y2] = false;
result = false;
}
return result;
}
/*
FUNCTION NAME: populateArray
PARAMETERS: ifstream variable containing txt file, an array of char values;
RETURN TYPE: void;
DESCRIPTION: this function will take in the .txt file stream and check for errors in case the file doesn't exist
if the file exists it recursivley call the function and loop through the txt file and assign into char array;
*/
void populateArray(ifstream&, char ARR[ROWS][COLS]) {
ifstream inFile;
string inputFile;
cout << "Enter input file: ";
cin >> inputFile;
inFile.open(inputFile);
while(!inFile.eof()) {
if(inFile.fail()) {
cin.clear();
cin.ignore(100, '\n');
inFile.clear();
inFile.ignore(100, '\n');
cerr << "File not found"<< endl;
populateArray(inFile, ARR);
} else {
for(int i = 0; i < ROWS; i++) {
for(int j = 0; j < COLS; j++) {
inFile >> ARR[i][j];
}
}
}
}
inFile.close();
return;
}
/*
FUNCTION NAME: outputBoard
PARAMETERS: the char array from the file input stream, an array of bool values
RETURN TYPE: void - used in makeAMatch function;
DESCRIPTION: this function will loop and output the contents of the char array and do a check with a
bool value in the bool array. If the bool val is false return an "_", otherwise return the character if true;
*/
void outputBoard(char charARR[ROWS][COLS], bool boolARR[ROWS][COLS]) {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (boolARR[i][j] == false) {
cout << "_" << " ";
} else if (boolARR[i][j] == true) {
cout << charARR[i][j] << " ";
}
}
cout << endl;
}
return;
} | [
"drudyprop@gmail.com"
] | drudyprop@gmail.com |
2c257a4c59f200987afd722b0792d829fa0eebad | b00321fc049be5e57e729a456eefb53d4543183a | /reaction.cpp | 55e79714da832089c76a9a74d31d5b2d65098ede | [] | no_license | BAS215/dom_clean | 826ffa8edc4e04f98a10e84efa2cf95b9b398760 | 6ff8840180e514bc4b577428f2eac8c1dfb0dded | refs/heads/master | 2020-04-06T04:38:38.370863 | 2016-02-11T20:13:40 | 2016-02-11T20:13:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 48,697 | cpp | #include "reaction.h"
double const reaction::pi = acos(-1.);
bool nonloc2 = true;
//*********************************************************************
/**
*constructor reads in data from file
* Set falg to zero is class used only to gives optical model potential
\param title0 for input data
\param flag0 indicates integrating of wavefunctions takes place
\param typeN0 - type of nonlocality
*/
reaction::reaction(string *title0,bool flag0, int typeN0)
{
typeN = typeN0;
bprint = 1;
for (int i=0;i<NlevelMax;i++) LevelTh[i].SpectFunction = NULL;
Esf = NULL;
NXdata = 0;
NTotXdata = 0;
DOM = 1;
flag = flag0;
//directory = "/home/bob/DOMA/";
directory = "Data/";
string input_dir = "Input/";
string line;
title = *title0;
string filename(input_dir + title + ".inp");
if (flag) cout << filename << endl;
ifstream file (filename.c_str(),ios::in);
// if one cannot open file quit
if (file.fail())
{
cout << "couldn't open data file " << filename << " " << title << endl;
abort();
}
file >> Zp >> Z >> A >> Efermi >> readCoulomb;
file >> Nfermi;
if (Nfermi < 1 || Nfermi > 2) cout << "Nfermi not possible" << endl;
file >> ValenceHole.N >> ValenceHole.j >> ValenceHole.l >>
ValenceHole.energy;
if (Nfermi == 2)
file >> ValenceParticle.N >> ValenceParticle.j >> ValenceParticle.l
>> ValenceParticle.energy;
file >> gap >> gapOther;
gapMin = min(gap,gapOther);
Wstart = gap/2. + gapMin;
//Wstart = 0.9*gap;
asymmetry = (A-2.*Z)/A;
if (Zp == 1.) sign = 1;
else if (Zp == 0.) sign = -1.;
else cout << " unknown Zp " << endl;
if (file.bad()) cout << "problem with input file" << endl;
if (file.eof()) cout << "eof with input file" << endl;
file.close();
file.clear();
//asymmetry
AsyVolume = 1; // asymmetry for volume
//alphaVolume = 1.65;
//EaVolume = 140.;
//EaVolume = 60.;
double rmax = 12;
int ham_pts = 180; // number of points used in construction of hamiltonian
int Lmax = 5;
//create class for nonlocal potential energy
//int typeN = 1; // set to U((r1+r2)/2) form
//int typeN = 0; // set to U*sqrt(f(r1)*f(r2)) form
int typeN = 1;
Pot = new pot(typeN);
Pot->init(Z, Zp, A, readCoulomb ); //initialize
prepare(); //load potential parameters into Pot
// constructor for Rspace scttering calculations
ScatterRspace = new scatterRspace(Z,Zp,A,Pot,title0);
BoundRspace = new boundRspace( rmax, ham_pts, Efermi, gap, Lmax, Z,Zp,A,Pot);
if (flag == 0) return;
//___________________________________________________________________
//read elastic scattering data
int iData = 0;
Ndata = 0;
DegreesOfFreedom = 0;
xsecMax = 0.;
xsecMin = 1.E32;
//open data file
filename = directory + title + ".data";
ifstream fileData (filename.c_str(),ios::in);
// if one cannot open file quit
if (fileData.fail())
{
cout << "couldn't open data file" << fileData << endl;
}
else
{
for(;;)
{
int n;
string xa;
double Elab;
int nfit;
fileData >> Elab >> nfit;
// if nfit ==1 data is included in fit, =0 plotted but not fitted
//=-1 data is ignored
//=2 data is ratio to ruth and in fit
if (Elab < 0.) break;
getline(fileData,line);
getline(fileData,line);
cout << line << endl;
if (nfit >= 0)
{
data[iData].energyLab = Elab;
data[iData].name = line;
data[iData].fit = nfit;
double Ecm = energyLab2Cm(Elab);
data[iData].energyCM = Ecm;
// if we need to calculate rutherford, load in the Ecm to
ScatterRspace->newEnergy(Ecm,Elab);
}
if (fileData.eof()) break;
if (fileData.bad())
{
cout << "trouble reading file" << endl;
break;
}
if (nfit >= 0) Ndata++;
//make room for cross xsection data
fileData >> n >> xa;
//cout << "n = " << n << " xa = " << xa << endl;
if (xa != "X") cout << "X problem for Elab = " << Elab << endl;
if (nfit >= 0) data[iData].nX = n;
if (n > 0)
{
if (nfit >= 0)
{
data[iData].Xtheta = new double[n];
data[iData].xsec = new double[n];
data[iData].Xsigma = new double[n];
}
double theta, xsec, sigma;
for (int i=0;i<n;i++)
{
fileData >> theta >> xsec >> sigma;
if (nfit >= 0)
{
data[iData].Xtheta[i] = theta;
data[iData].xsec[i] = xsec;
data[iData].Xsigma[i] = sigma;
// input data is given as ratio to rutherford
if( nfit == 2)
{
double ruth =ScatterRspace->Rutherford(theta*pi/180.);
data[iData].xsec[i]*= ruth;
if (sigma > 0) data[iData].Xsigma[i] *= ruth;
}
if (data[iData].Xsigma[i] < 0.)
data[iData].Xsigma[i] *= -data[iData].xsec[i]/100.;
if (data[iData].Xsigma[i] < data[iData].xsec[i]*.1)
data[iData].Xsigma[i] = data[iData].xsec[i]*.1;
if ( Zp == 0 && A == 92 && Elab > 10 )
data[iData].Xsigma[i] /= 5.;
if ( Zp == 1 && Elab > 14. && Elab < 100 &&
(A==48 || A==44))
data[iData].Xsigma[i] /= 5.;
if ( Elab > 14. && Elab < 50 && Z == 28)
data[iData].Xsigma[i] /= 5.;
if ( Zp == 1 && Elab > 100. && A==9)
data[iData].Xsigma[i] /= 5.;
if ( Zp == 1 && Elab > 40. && Elab < 100. && A==208)
data[iData].Xsigma[i] /= 5.;
//if ( Zp == 1 && Elab > 40. && Elab < 100. && A==92)
//data[iData].Xsigma[i] /= 5.;
if ( Zp == 0 && Elab > 20. && Elab < 40. && A==208)
data[iData].Xsigma[i] /= 5.;
if ( Zp == 0 && Elab > 20. && Elab < 40. && A==9)
data[iData].Xsigma[i] /= 5.;
if (nfit) DegreesOfFreedom++;
xsecMax = max(data[iData].xsec[i],xsecMax);
xsecMin = min(data[iData].xsec[i],xsecMin);
}
}
}
//analysing power data
fileData >> n >> xa;
if (xa != "A") cout << "A problem for Elab = " << Elab << endl;
if (nfit >= 0) data[iData].nA = n;
if (n > 0)
{
if (nfit >= 0)
{
data[iData].Atheta = new double[n];
data[iData].anal = new double[n];
data[iData].Asigma = new double[n];
}
double theta, pol, sigma;
for (int i=0;i<n;i++)
{
fileData >> theta >> pol >> sigma;
if (nfit >=0)
{
data[iData].Atheta[i] = theta;
data[iData].anal[i] = pol;
if (sigma < 0.05) sigma = 0.05; //****** ******
data[iData].Asigma[i] = sigma;
if (data[iData].energyLab > 50 && data[iData].energyLab
< 100) data[iData].Asigma[i] /= 4.;
DegreesOfFreedom++;
}
}
}
if (nfit >=0 )
{
iData++;
if (Ndata > NdataMax)
{
cout << "increase NdataMax" << endl;
abort();
break;
}
}
}
cout << Ndata << " blocks of data read from file " << filename << endl;
cout << " degrees of freedom= " << DegreesOfFreedom << endl;
cout << " Max xsection = " << xsecMax << endl;
cout << " Min xsection = " << xsecMin << endl;
fileData.close();
}
//////////////////////////////////////////////
//////////////////////////////////////////////
//--------------------- read in levels
//read in levels
filename = directory + title + ".lev";
cout << filename << endl;
ifstream fileLevel (filename.c_str(),ios::in);
// if one cannot open file quit
if (fileLevel.fail())
{
cout << "couldn't open data file" << endl;
NFitLevels = 0;
Nlevel = 0;
LevelDegreesOfFreedom = 0;
}
else
{
getline(fileLevel,line);
cout << line << endl;
getline(fileLevel,line);
//cout << line << endl;
int Ilevel=0;
LevelDegreesOfFreedom = 0;
NFitLevels = 0;
for (;;)
{
fileLevel >> Level[Ilevel].Energy >> Level[Ilevel].SigmaEnergy >>
Level[Ilevel].N >>
Level[Ilevel].j >> Level[Ilevel].l >> Level[Ilevel].color >>
Level[Ilevel].Efit >>
Level[Ilevel].Rrms >> Level[Ilevel].SigmaRrms >>
Level[Ilevel].Rfit >>
Level[Ilevel].Delta >> Level[Ilevel].SigmaDelta >>
Level[Ilevel].Dfit >>
Level[Ilevel].SpectFactor >> Level[Ilevel].SigmaSpect >>
Level[Ilevel].Sfit;
//if (A >= 40.) Level[Ilevel].SigmaSpect /= 2.;
if (fileLevel.eof()) break;
if (Level[Ilevel].Efit)
{
LevelDegreesOfFreedom++;
NFitLevels++;
}
if (Level[Ilevel].Rfit) LevelDegreesOfFreedom++;
if (Level[Ilevel].Dfit) LevelDegreesOfFreedom++;
if (Level[Ilevel].Sfit) LevelDegreesOfFreedom++;
if (Ilevel == NlevelMax-1)
{
cout << "increase NlevelMax" << endl;
Ilevel++;
break;
}
Ilevel++;
}
Nlevel = Ilevel;
cout << Nlevel << " levels read in " << endl;
fileLevel.close();
}
//prepare for spectral functions
Nsf = 440;
for (int i=0;i<NlevelMax;i++) LevelTh[i].SpectFunction = new double [Nsf];
Elow = Efermi - 22.;
Ehigh = Efermi;
Esf = new double[Nsf];
for (int i=0;i<Nsf;i++) Esf[i] = -(double)i/4.+30;
XsecDegreesOfFreedom = 0;
//readin reaction xsection data --------
filename = directory+title + ".xsec";
cout << filename << endl;
file.open(filename.c_str(),ios::in);
// if one cannot open file quit
if (file.fail())
{
cout << "couldn't open reaction *.xsec file" << endl;
cout << " no reaction xsec in fit" << endl;
NXdata = 0;
}
else
{
getline(file,line);
getline(file,line);
file >> NXdata;
XsecDegreesOfFreedom += NXdata;
Xdata = new xdata [NXdata];
for (int i=0;i<NXdata;i++)
{
file >> Xdata[i].energyLab >> Xdata[i].xsec >> Xdata[i].sigma;
double Elab = Xdata[i].energyLab;
double Ecm = energyLab2Cm(Elab);
Xdata[i].energyCM = Ecm;
}
}
file.close();
file.clear();
cout << "xsec points = " << NXdata << endl;
if (Zp == 0.) //for neutrons total cross section data
{
filename = directory+title + ".txsec";
cout << filename << endl;
file.open(filename.c_str(),ios::in);
// if one cannot open file quit
if (file.fail())
{
cout << "couldn't open reaction *.txsec file" << endl;
cout << " no total xsec in fit" << endl;
NTotXdata = 0;
}
else
{
getline(file,line);
getline(file,line);
file >> NTotXdata;
XsecDegreesOfFreedom += NTotXdata;
TotXdata = new xdata [NTotXdata];
for (int i=0;i<NTotXdata;i++)
{
file >> TotXdata[i].energyLab >>
TotXdata[i].xsec >> TotXdata[i].sigma;
//make sure the error bars are not too small
if (TotXdata[i].sigma < TotXdata[i].xsec*.02)
TotXdata[i].sigma = 0.02*TotXdata[i].xsec;
double Elab = TotXdata[i].energyLab;
double Ecm = energyLab2Cm(Elab);
//if (A == 208 && Elab > 25 ) TotXdata[i].sigma /= 5;
TotXdata[i].energyCM = Ecm;
if (TotXdata[i].sigma < 0.) TotXdata[i].sigma *=
-TotXdata[i].xsec/100.;
}
}
}
else NTotXdata = 0;
cout << "tot xsec points" << NTotXdata << endl;
file.close();
file.clear();
//readin integrated moments
filename = directory+title + ".Vint";
cout << filename << endl;
file.open(filename.c_str(),ios::in);
// if one cannot open file quit
if (file.fail())
{
cout << "couldn't open integtaed moment *.Vint file" << endl;
cout << " no moments in fit" << endl;
Nmoment = 0;
}
else
{
getline(file,line);
int flag;
file >> Nmoment >> flag;
cout << Nmoment << " " << flag << endl;
if (flag == 0) Nmoment = 0;
if (Nmoment > 0)
{
string ref;
for (int i=0;i<Nmoment;i++)
{
file >> Moment[i].EnergyLab >> Moment[i].Jreal >>
Moment[i].Jimag >> Moment[i].RMSreal >> Moment[i].RMSimag >>
Moment[i].Jso >> Moment[i].RMSso;
getline(file,ref);
Moment[i].EnergyCM = energyLab2Cm(Moment[i].EnergyLab);
cout << Moment[i].EnergyLab << " " << Moment[i].EnergyCM << endl;
}
}
}
file.close();
file.clear();
// read in charge distribution
//reading boundrspace data to calculate chi squared//
std::ifstream filein("ca48_bound_chd.dat");
filein >> Chi_Squared_data.r_0 >> Chi_Squared_data.ch_den_0_exp
>> Chi_Squared_data.err_0_exp >> Chi_Squared_data.r_middle_exp
>> Chi_Squared_data.ch_den_middle_exp >> Chi_Squared_data.err_middle_exp
>> Chi_Squared_data.R_rms_exp >> Chi_Squared_data.err_R_rms_exp;
filein.close();
}
//******************************************************************
/**
* Destructor
*/
reaction::~reaction()
{
delete BoundRspace;
delete ScatterRspace;
delete Pot;
cout << "destroying reaction" << endl;
if (flag == 0) return;
for (int i=0;i<Ndata;i++)
{
if (data[i].nX > 0)
{
delete [] data[i].Xtheta;
delete [] data[i].xsec;
delete [] data[i].Xsigma;
}
if(data[i].nA > 0)
{
delete [] data[i].Atheta;
delete [] data[i].anal;
delete [] data[i].Asigma;
}
}
for (int i=0;i<NlevelMax;i++)
{
if (LevelTh[i].SpectFunction == NULL) continue;
delete [] LevelTh[i].SpectFunction;
}
delete [] Esf;
if (NXdata > 0) delete [] Xdata;
if (NTotXdata > 0) delete [] TotXdata;
cout << " reaction distroyed" << endl;
}
//*****************************************************************
/**
* loads in in new parameters for the potential
*/
bool reaction::prepare()
{
Pot->load( Rc, VHFvol, VHFsur, RHF, aHF, RHFs, aHFs, beta_nl_R0, AHF,
beta_nl_R1, RsurfaceAbove, RsurfaceBelow, asurfaceAbove, asurfaceBelow, Asurface_A,
Asurface_B, BsurfaceA, CsurfaceA, DsurfaceA, Bsurface, Csurface, Dsurface,
Wstart*fGap_A, Wstart*fGap_B, Efermi, beta_nl_I0, beta_nl_I1, beta_nl_I0_sur, beta_nl_I1_sur,
RvolumeAbove,RvolumeBelow, deltaRvolume, expRvolume,
avolumeAbove,avolumeBelow, Avolume_A, Avolume_B, BvolumeAbove, BvolumeBelow ,
EpvolumeAbove,EpvolumeBelow, mvolume, AsyVolume, alphaVolume, EaVolume_a,
EaVolume_b, Rso, aso, Vso, AWso, BWso , V_wine , R_wine , rho_wine);
return true;
return AdjustFermi();
}
//******************************************************************
/**
* returns chi squared per degree of freedom of the fit
*/
double reaction::ChiSquared()
{
double sum = 0.;
double sumXsec = 0.;
//loop over number of energies in fit
//
for(int i=0;i<Ndata;i++)
{
if (data[i].fit == 0 ) continue;
double Ecm =data[i].energyCM;
double Elab =data[i].energyLab;
//std::cout<<"Energy cm = "<< Ecm << " " << "Elab = "<< Elab<<std::endl;
// integrate wavefunction and find phaseshifts
if (ScatterRspace->getSmatrix(Ecm,Elab)==0) return 1.e6;
//add prepare compound elastic
if (Ecm < 15.) ScatterRspace->statistical(ScatterRspace->konst,Ecm);
//std::cout<<"Cross section"<<std::endl;
// loop over angles
for (int j=0;j<data[i].nX;j++)
{
if ( data[i].Xtheta[j] >115. ) continue;
double angle = data[i].Xtheta[j]*pi/180.;
double xsecTheory = ScatterRspace->DifferentialXsection(angle);
// add in compound elastic
if (Ecm < 15.) xsecTheory += ScatterRspace->DifferentialXsectionCE(angle);
//add to chi squared
sum += pow(xsecTheory-data[i].xsec[j],2)/
pow(data[i].Xsigma[j],2);
///////////////////////////////////////
///////////////////////////////////////
// if ( pow(xsecTheory-data[i].xsec[j],2)/pow(data[i].Xsigma[j],2) > 10000. ) {cout<<angle*180./pi<<" "<< pow(xsecTheory-data[i].xsec[j],2)/pow(data[i].Xsigma[j],2)<<endl;}
///////////////////////////////////////
///////////////////////////////////////
}
//cout<<"Xsec tion sum for "<<Ecm<< "is "<<sum<<cout;
// std::cout<<"Analyzing"<<std::endl;
for (int j=0;j<data[i].nA;j++)
{
double angle = data[i].Atheta[j]*pi/180.;
double xsecTheory = ScatterRspace->DifferentialXsection(angle);
//add to chi squared
double A = ScatterRspace->AnalyzePower;
if (Ecm < 15.)
{
double shape = ScatterRspace->DifferentialXsectionCE(angle);
A *= xsecTheory/(xsecTheory+shape);
}
sum += pow(ScatterRspace->AnalyzePower-data[i].anal[j],2)/
pow(data[i].Asigma[j],2);
///////////////////////////////////////
///////////////////////////////////////
// std::cout<<angle*180. /pi<<" "<< pow(ScatterRspace->AnalyzePower-data[i].anal[j],2)/pow(data[i].Asigma[j],2) <<std::endl;
///////////////////////////////////////
///////////////////////////////////////
}
}
//sum *= 10.; //rjc used for fitting n+48Ca
//-------------------------------------------------------------------
// sum /=DegreesOfFreedom;
// chidif = sum;
//fit absorption cross section for protons
double xsec = ScatterRspace->AbsorptionXsection(); //protons
double const error = 5.;
cout << sum << " " << xsec << " " << sum + pow((xsec-543.)/error,2) << endl;
// return sum + pow((xsec-543.)/error,2); //fix
// reaction xsections
for(int i=0;i<NXdata;i++)
{
double Ecm = Xdata[i].energyCM;
double Elab = Xdata[i].energyLab;
// integrate wavefunction and find phaseshifts
ScatterRspace->getSmatrix(Ecm,Elab);
double xsec = ScatterRspace->AbsorptionXsection(); //protons
//remove compound elastic part
if (Ecm < 15.) xsec -= - ScatterRspace->statistical(ScatterRspace->konst,Ecm);
sumXsec += pow(((xsec-Xdata[i].xsec)/(Xdata[i].sigma)),2); //RJC
}
//total cross section
// sumXsec = sumXsec * 10. ;
if (NTotXdata > 0 && Zp == 0.)
{
for(int i=0;i<NTotXdata;i++)
{
double Ecm = TotXdata[i].energyCM;
double Elab = TotXdata[i].energyLab;
// integrate wavefunctions and find S matrices
ScatterRspace->getSmatrix(Ecm,Elab);
//fit total cross section for neutrons
double xsec = ScatterRspace->TotXsection(); //neutrons
sumXsec += pow((xsec-TotXdata[i].xsec)/TotXdata[i].sigma,2); //RJC
}
}
double total = 0.;
double chiPoint[4] = {0.,0.,0.,0.};
if (DegreesOfFreedom >0)
{
chiPoint[0] = sum/DegreesOfFreedom*10.;
// total += chiPoint[0];
}
if (XsecDegreesOfFreedom > 0)
{
chiPoint[2] = sumXsec/XsecDegreesOfFreedom*10.;
// total += chiPoint[2];
}
if (bprint)
{
cout <<"elastic and analyzing power chisq="<< chiPoint[0] << " " << "reaction xsection="<< chiPoint[2] << endl;
}
total = 0.;
total += BoundChiSquared();
cout <<" total="<< total <<endl;
return total;
}
// bound state chisquared//
//********************************
double reaction::BoundChiSquared()
{
double Emax = 2.*Efermi ;//- Wstart * fGap_B; // Energy where continuum begins
double Emin = -200 + Emax;
std::vector< double > rmesh = BoundRspace->make_rmesh();
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
// used to get differen result generated by fitting program and the domgen, so that thi fitting would fit sth else on the data///
// I plot and compare the potentilas and the hamiltonian generated from ./chisq .....(inputfile) x with ./domgenII
// I wrote down my results , the real nonlocal Potential was different in tow cases
// /////////////////////////////21 Aug 2013 Notes///////////////////////////////////////////////
//testing the hamiltonian
//
//
/* std::string hamil_reaction="pot_test/hamil_reaction.out";
std::ofstream hamilreaction(hamil_reaction.c_str() );
for (int ii = 0 ;ii<rmesh.size();++ii){
for (int kk= 0 ; kk< rmesh.size(); ++kk) {
hamilreaction<<rmesh[ii]<<" "<< rmesh[kk] << " " << BoundRspace->re_hamiltonian(rmesh,-30,0,.5)(ii,kk)<<std::endl;
}
}
//potential test
std::string fyek_reaction="pot_test/file1_reaction.out";
std::ofstream fyekreaction(fyek_reaction.c_str() );
Pot->setAM(0,.5);
std::cout<< "V_beta Above "<< Pot->VolumeAbove.beta << " "<<"V_beta_below" <<Pot->VolumeBelow.beta<<std::endl;
std::cout<<"HF beta0 = "<< Pot->HartreeFock.beta0 << " "<<"HF beta1 = "<< Pot->HartreeFock.beta1 <<std::endl;
Pot->setEnergy(-30);
for (int makann = 0 ; makann<rmesh.size();++makann){
fyekreaction <<rmesh[makann]<<" "<< imag(Pot->nonlocalPart(rmesh[makann],rmesh[makann]))
<<" "<< imag( Pot->localPart(rmesh[makann]) )
<<" "<< real( Pot->nonlocalPart(rmesh[makann],rmesh[makann] ))
<<" "<< real( Pot->localPart(rmesh[makann]) )
<<" "<< Pot->nonlocalIM(rmesh[makann],rmesh[makann])
<<" "<< Pot->nonlocalHF(rmesh[makann],rmesh[makann])
<<" "<< Pot->localHF(rmesh[makann])
<<" "<< Pot-> HartreeFock.U1(rmesh[makann],rmesh[makann])
<<" "<< Pot-> HartreeFock.U0(rmesh[makann],rmesh[makann])
<<" "<< real(Pot-> SurfaceAbove.U(rmesh[makann],rmesh[makann]))
<<" "<< real(Pot-> SurfaceBelow.U(rmesh[makann],rmesh[makann]))
<<" "<< real(Pot-> VolumeAbove.U(rmesh[makann],rmesh[makann]))
<<" "<< real(Pot-> VolumeBelow.U(rmesh[makann],rmesh[makann]))
<<" "<< imag(Pot-> SurfaceAbove.U(rmesh[makann],rmesh[makann]))
<<" "<< imag(Pot-> SurfaceBelow.U(rmesh[makann],rmesh[makann]))
<<" "<< imag(Pot-> VolumeAbove.U(rmesh[makann],rmesh[makann]))
<<" "<< imag(Pot-> VolumeBelow.U(rmesh[makann],rmesh[makann]))<< std::endl;
}
fyekreaction.close();
cout<< "S_beta Above " << Pot->SurfaceAbove.betas << endl;
cout<< "S_beta Belowe "<< Pot->SurfaceBelow.betas << endl;
cout<< "a Belowe "<< Pot->SurfaceBelow.a << endl;
cout<< "a Above "<< Pot->SurfaceAbove.a << endl;
cout<< "R Belowe "<< Pot->SurfaceBelow.R << endl;
cout<< "R Above "<< Pot->SurfaceAbove.R << endl;
cout<< "A Belowe "<< Pot->SurfaceBelow.A << endl;
cout<< "A Above "<< Pot->SurfaceAbove.A << endl;
cout<< "B Belowe "<< Pot->SurfaceBelow.B << endl;
cout<< "B Above "<< Pot->SurfaceAbove.B << endl;
cout<< "D Belowe "<< Pot->SurfaceBelow.C << endl;
cout<< "D Above "<< Pot->SurfaceAbove.C << endl;
cout<< "D Belowe "<< Pot->SurfaceBelow.D << endl;
cout<< "D Above "<< Pot->SurfaceAbove.D << endl;
cout<< "Wb "<< Pot->SurfaceBelow.Wstart << endl;
cout<< "W "<< Pot->SurfaceAbove.Wstart << endl;
std::cout<<"DONE the POT test"<<std::endl;
*/
////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////End of the test///////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////////////
// Get bound levels
double tol = 0.01;
int L_test = 0;
double J_test = 0.5;
int N_orbit=0;
std::vector< lj_eigen_t > bound_levels =
BoundRspace->get_bound_levels( rmesh, tol );
// Create energy meshes
std::vector< mesh_t > emesh_vec =
BoundRspace->get_emeshes( rmesh, Emin, Emax, bound_levels );
// Calculate propagators
std::vector< prop_t > prop_vec =
BoundRspace->get_propagators( rmesh, emesh_vec );
/// Calculates the Width of 0s1/2//
eigen_t bound_info = BoundRspace->find_boundstate( rmesh, Efermi, N_orbit,
L_test, J_test, tol );
std::vector< double > e_values =
BoundRspace->get_lj_energy_vector( L_test, J_test, emesh_vec );
std::vector< double > s_of_E_QH =
BoundRspace->spectral_strength_QH( L_test, J_test, rmesh, emesh_vec,
prop_vec, bound_info.second );
double gamma1 = BoundRspace->find_width( e_values, s_of_E_QH );
// Calculating the mid point of charge distribution and Particle number as well as R_rms from Point_charge distribution function//
std::vector<double> PointDist =
BoundRspace->point_distribution( rmesh, Emax, emesh_vec, prop_vec,
bound_levels);
//std::cout << "PointDist at r = " << rmesh[0] << "is : "<< PointDist[0]<<" "<<"Emx = "<<Emax << std::endl;
////
//the charge distribution points getting ready to be fit
/////
////
double middlehalf=0.476667;// .5;
double middleone=1.01;
double middleonehalf=1.47667;//1.5;
double middle=2.01;
double middle2half=2.54;
double middlethree=3.0;
double middlethree1=3.48;
double middlefour=4.0;
double middlefour1=4.48;
double middlefive=5.0;
double middlefive1=5.48;
/////
////the unfolded experimental Point(charge) distribution for 14 points(the file: unfolded.out) :
//for r=01,.47,1.01,1.47,2.01 ....
//
//
double unfld[15] = { .0924699 , .0896617 , .0841989 ,
.081314 , .0791672, .0739352 ,
.0636165 , .0475881 , .0275904 ,
.0141982 , .00548428 , .00204393 ,
.000574189 , .00019305 };
//Now we should find where the above point are
//since the rmesh in the unfolded exp data is diff from what we are generationg so we have to find the
//closest rmesh[i] to the above rmeshes in the "unfolded.out" then assign the density there to the density we are generationg and then fit
//well, it is not the best way to do it, it should be optimized, we need to do it once not in each iteration
int half_index=0;
int one_index=0;
int onehalf_index=0;
int middle_index=0;
int middle2half_index=0;
int three_index=0;
int three1_index=0;
int four_index=0;
int four1_index=0;
int five_index=0;
int five1_index=0;
//////
double ParticleNumber=0;
double minnhalf=100.0;
double minnone=100.0;
double minnonehalf=100.0;
double minn=100.0;
double minn2half=100.0;
double minnthree=100.0;
double minnthree1=100.0;
double minnfour=100.0;
double minnfour1=100.0;
double minnfive=100.0;
double minnfive1=100.0;
std::vector< double > rweights;
for ( unsigned int i = 0; i < rmesh.size(); ++i ) {
rweights.push_back( BoundRspace->rdelt );
}
double pParticleNumber = 0;
double nParticleNumber = 0;
std::vector<double> proton_folding =
folded_ch_density( rmesh, rweights, PointDist, 0.5, A );
std::vector<double> neutron_folding =
folded_ch_density( rmesh, rweights, PointDist, -0.5, A );
//finding indexes for rgrids
//
for (int i=0; i < rmesh.size() ;++i)
{
if (std::abs(rmesh[i]-middlehalf)<minnhalf)
{ half_index=i;
minnhalf=std::abs(rmesh[i]-middlehalf); }
if (std::abs(rmesh[i]-middleone)<minnone)
{ one_index=i;
minnone=std::abs(rmesh[i]-middleone); }
if (std::abs(rmesh[i]-middleonehalf)<minnonehalf)
{ onehalf_index=i;
minnonehalf=std::abs(rmesh[i]-middleonehalf); }
if (std::abs(rmesh[i]-middle)<minn)
{ middle_index=i;
minn=std::abs(rmesh[i]-middle); }
if (std::abs(rmesh[i]-middle2half)<minn2half)
{ middle2half_index=i;
minn2half=std::abs(rmesh[i]-middle2half); }
if (std::abs(rmesh[i]-middlethree)<minnthree)
{ three_index=i;
minnthree=std::abs(rmesh[i]-middlethree); }
if (std::abs(rmesh[i]-middlethree1)<minnthree1)
{ three1_index=i;
minnthree1=std::abs(rmesh[i]-middlethree1); }
if (std::abs(rmesh[i]-middlefour)<minnfour)
{ four_index=i;
minnfour=std::abs(rmesh[i]-middlefour); }
if (std::abs(rmesh[i]-middlefour1)<minnfour1)
{ four1_index=i;
minnfour1=std::abs(rmesh[i]-middlefour1); }
if (std::abs(rmesh[i]-middlefive)<minnfive)
{ five_index=i;
minnfive=std::abs(rmesh[i]-middlefive); }
if (std::abs(rmesh[i]-middlefive1)<minnfive1)
{ five1_index=i;
minnfive1=std::abs(rmesh[i]-middlefive1); }
ParticleNumber += 4 * M_PI * PointDist[i] * std::pow(rmesh[i],2)
* rweights[i];
std::cout << rmesh[i] << "\t"<< PointDist[i] <<std::endl;
pParticleNumber += 4 * M_PI * proton_folding[i] * std::pow(rmesh[i],2)
* rweights[i];
nParticleNumber += 4 * M_PI * neutron_folding[i] * std::pow(rmesh[i],2)
* rweights[i];
}
cout<<"N number form Chisq "<<ParticleNumber<<endl;
std::vector< double > chdf; // folded charge density
std::vector< double > chdfnew; // folded charge density
double summs = 0;
for ( unsigned int i = 0; i < rmesh.size(); ++i ) {
double normednew = ( proton_folding[i] + neutron_folding[i] );
double normed = Z * ( proton_folding[i] + neutron_folding[i] )
/ ParticleNumber;
chdf.push_back( normed );
chdfnew.push_back( normednew );
summs += normed * 4 * M_PI * std::pow(rmesh[i],4) * rweights[i];
}
double R_rms=std::sqrt( summs / Z ); // Root-mean-square radius
//Calculating Bound ChiSquared
/* double ch_den_chisq = std::pow( (chdf[0] - 0.0867255)
/(.1 * (0.000867255)), 2 );
double ch_den_half_chisq = std::pow( ( chdf[half_index] - 0.085527 )
/ (0.000855276), 2 );
double ch_den_one_chisq = std::pow( ( chdf[one_index] - 0.0825104)
/ ( 0.000825104 ), 2 );
double ch_den_onehalf_chisq = std::pow( ( chdf[onehalf_index] - 0.0800167)
/ (0.000800167), 2 );
double ch_den_middle_chisq = std::pow( ( chdf[middle_index] - 0.0770948 )
/(.000770948), 2 );
double ch_den_middle2half_chisq = std::pow( ( chdf[middle2half_index] - 0.0709657)
/(0.000709657), 2 );
double ch_den_three_chisq = std::pow( ( chdf[three_index] - 0.0605082 )
/ ( 0.000605082), 2 );
double ch_den_three1_chisq = std::pow( ( chdf[three1_index] - 0.0457602 )
/ ( 0.000457602), 2 );
double ch_den_four_chisq = 2. * std::pow( ( chdf[four_index] - 0.0278664 )
/ ( 0.000278664), 2 );
double ch_den_four1_chisq = .5 * std::pow( ( chdf[four1_index] - 0.0153698 )
/ ( 0.000153698), 2 );
double ch_den_five_chisq = .02 * std::pow( ( chdf[five_index] - 0.00658348 )
/ ( 0.0000658348), 2 );
double ch_den_five1_chisq = .005 * std::pow( ( chdf[five1_index] - 0.00274881 )
/ ( 0.0000274881), 2 );
*/
//
//the UNFOLDED charge distribution is being fitted here
//the unfolded experimental data are in the unfolded.out
//
double ch_den_chisq = std::pow( (PointDist[0] -unfld[0])
/( (unfld[0]/1000.0)), 2 );
double ch_den_half_chisq = std::pow( ( PointDist[half_index] - unfld[1] )
/ (unfld[1]/1000.0), 2 );
double ch_den_one_chisq = std::pow( ( PointDist[one_index] - unfld[2])
/ (unfld[2]/100.0 ), 2 );
double ch_den_onehalf_chisq = std::pow( ( PointDist[onehalf_index] - unfld[3])
/ (unfld[3]/100.0), 2 );
double ch_den_middle_chisq = std::pow( ( PointDist[middle_index] - unfld[4] )
/(unfld[4]/100.0), 2 );
double ch_den_middle2half_chisq = std::pow( ( PointDist[middle2half_index] - unfld[5])
/(unfld[5]/500.), 2 );
double ch_den_three_chisq = std::pow( ( PointDist[three_index] - unfld[6] )
/ ( unfld[6]/100.0), 2 );
double ch_den_three1_chisq = std::pow( ( PointDist[three1_index] - unfld[7] )
/ ( unfld[7]/100.0), 2 );
double ch_den_four_chisq = 2. * std::pow( ( PointDist[four_index] - unfld[8] )
/ ( unfld[8]/100.0), 2 );
double ch_den_four1_chisq = .5 * std::pow( ( PointDist[four1_index] - unfld[9] )
/ ( unfld[9]/100.0), 2 );
double ch_den_five_chisq = .02 * std::pow( ( PointDist[five_index] - unfld[10] )
/ ( unfld[10]/100.0), 2 );
double ch_den_five1_chisq = .005 * std::pow( ( PointDist[five1_index] - unfld[11] )
/ ( unfld[11]/100.0), 2 );
double R_rms_chisq = std::pow( ( R_rms - Chi_Squared_data.R_rms_exp )
/(.2 * Chi_Squared_data.err_R_rms_exp), 2 );
double gamma1_chisq = std::pow( ( gamma1 - 21.3 ) / 0.9, 2 );
//*****************************************************************************************************************************************
//*****************************************************************************************************************************************
//*****************************************************************************************************************************************
//********************************alculating the missing S(E,P) Chi Squared***************************************************************
//*****************************************************************************************************************************************
//*****************************************************************************************************************************************
//*****************************************************************************************************************************************
//*****************************************************************************************************************************************
std::string input_dir = "Input/";
int num_lj = 11;
std::string p_filename = input_dir + "pca40.inp";
// Create Nuclear Parameter Objects
NuclearParameters Nu_p = read_nucleus_parameters( p_filename );
std::vector< NuclearParameters > Nu_vec;
Nu_vec.push_back( Nu_p );
std::string parameters_filename = "hosfit.inp";
// Read in DOM parameters
std::ifstream pfile( parameters_filename.c_str() );
if ( pfile.is_open() !=1 ) {
std::cout << "could not open file " << parameters_filename << std::endl;
std::abort();
}
pfile.close();
pfile.clear();
int lmax = 5;
int nu=0;
double tz = .5 ; //nu - 0.5; // +0.5 for protons, -0.5 for neutrons
double calc_norm = 20 ;
// Create momentum space grid for E-slice
std::vector<double> kmesh2; // wave number in units of fm^{-1}
std::vector<double> pmesh; // momentum in units of MeV / c
double pmin = 250;
double pmax = 650;
double deltap = 80;
int ppts = static_cast<int> ( ( pmax - pmin ) / deltap ) + 1;
double p=0;
for ( int i = 0; i < ppts; ++i ) {
p = pmin + i * deltap;
pmesh.push_back( p );
double k = p / hbarc;
kmesh2.push_back( k );
}
// Nucleus Object
const NuclearParameters &Nu = Nu_vec[0];
// Construct Parameters Object
Parameters pap = get_parameters( parameters_filename, Nu.A, Nu.Z,1 );
// Construct Potential Object
// type=1
pot U = get_bobs_pot2( 1 , 4, 1, tz, Nu, pap );
pot *U1 = &U;
// Construct Object for calculating bound-state properties
boundRspace B(12.0, 180 , Nu.Ef, Nu.ph_gap, lmax, Nu.Z, 1, Nu.A, U1 );
// Create Energy grid for E-slice
double Emin2 = -300;
double Emax2 = -25;
double deltaE2 = 2;
int epts2 = static_cast<int>( ( Emax2 - Emin2 ) / deltaE2 ) + 1;
std::vector<double> emesh2;
for ( int i = 0; i < epts2; ++i ) {
emesh2.push_back( Emin2 + i * deltaE2 );
}
matrix_t S_of_kE_mtx2( kmesh2.size(), emesh2.size() );
// intialize matrices to zero
for ( unsigned int i = 0; i < kmesh2.size(); ++i ) {
for ( unsigned int j = 0; j < emesh2.size(); ++j ) {
S_of_kE_mtx2( i, j ) = 0;
}
}
// Loop over lj channels
for ( int L = 0; L < lmax + 1; ++L ) {
for( int up = -1; up < 2; up+=2 ) {
double xj = L + up / 2.0;
int j_index = ( up - 1 ) / 2;
if ( xj < 0 ) continue;
// Create Bessel Function matrix in k and r
matrix_t bess_mtx2( kmesh2.size(), rmesh.size() );
for( unsigned int nk = 0; nk < kmesh2.size(); ++nk ) {
for( unsigned int nr = 0; nr < rmesh.size(); ++nr ) {
double rho = kmesh2[nk] * rmesh[nr];
bess_mtx2( nk, nr ) = gsl_sf_bessel_jl( L, rho );
}
}
// Calculate S( k; E ) for E-slice
for ( unsigned int m = 0; m < emesh2.size(); ++m ) {
double E = emesh2[m];
// Propagator
cmatrix_t G = BoundRspace->propagator( rmesh, E, L, xj );
// if (L==0 && m==0){std::cout<<"G(0,0)="<< G(0,0)<<std::endl;}
// Spectral Function in momentum space, S( k; E )
for( unsigned int nk = 0; nk < kmesh2.size(); ++nk ) {
double rsums = 0;
for( unsigned int i = 0; i < rmesh.size(); ++i ) {
double jl1 = bess_mtx2( nk, i );
for( unsigned int j = 0; j < rmesh.size(); ++j ) {
double jl2 = bess_mtx2( nk, j );
rsums -= rmesh[i] * jl1 * imag( G( i, j ) )
* rmesh[j] * jl2 *BoundRspace->rdelt * 2 / M_PI / M_PI;
}
} // end loop over radial coordinates
S_of_kE_mtx2( nk, m ) += ( 2 * xj + 1 ) * rsums;
} // end loop over k
} // end loop over energy
}// end loop over j
} // end loop over L
// write in units of MeV^-4 sr^-1
double fac = std::pow( hbarc, 3 ) * 4 * M_PI;
// S(E_m,P_m) Chi squared COnstruction
int point250 [] = {124 , 118 , 113, 106 , 101 , 95 , 89 , 83 , 77};
int point650 [] = {119 , 106 , 93, 81, 67 , 53 , 41};
double point250_data [] = {1.6803e-11 , 1.2703e-11, 9.7322e-12, 7.212e-12 ,
5.5253e-12 , 4.2899e-12, 3.3753e-12, 2.7274e-12, 2.3556e-12 };
double point650_data [] = {1.6746e-14 , 2.581e-14 , 2.7952e-14 , 2.5291e-14 , 2.7942e-14 , 2.2278e-14 , 2.3966e-14 };
double err_250 = 1e-13;
double err_650 = 1e-13;
std::vector <double> chisq_p_250;
std::vector <double> S_missing_250;
double tot_chisq_p_250 = 0;
std::vector <double> chisq_p_650;
std::vector <double> S_missing_650;
double tot_chisq_p_650 = 0;
for (int i = 0 ; i < 9 ; ++i) {
S_missing_250.push_back(S_of_kE_mtx2( 0, point250[i]-1 ) / fac / calc_norm);
chisq_p_250.push_back(pow(((S_missing_250[i]-point250_data[i]) / err_250) , 2));
tot_chisq_p_250 += chisq_p_250[i];
// std::cout << chisq_p_250[i] << " " << "calculated 250"<< " " << i << " = "
// << S_missing_250[i] << " " << "Daniela 250 " << i << " = "
// << point250_data[i] <<std::endl;
}
for (int i = 0 ; i < 7 ; ++i) {
S_missing_650.push_back(S_of_kE_mtx2( 0, point650[i]-1 ) / fac / calc_norm);
chisq_p_650.push_back(pow(((S_missing_650[i]-point650_data[i]) / err_650) , 2));
tot_chisq_p_650 += chisq_p_650[i];
// std::cout << chisq_p_650[i] << " " << "calculated 650"<< " " << i << " = "
// << S_missing_650[i] << " " << "Daniela 650 " << i << " = "
// << point650_data[i] <<std::endl;
}
tot_chisq_p_250 = tot_chisq_p_250 ;
std::cout<<"total 250 chisq = "<<" "<<tot_chisq_p_250<<std::endl;
tot_chisq_p_650 = tot_chisq_p_650 ;
std::cout<<"total 650 chisq = "<<" "<<tot_chisq_p_650<<std::endl;
//*****************************************************************************************************************************************
//*****************************************************************************************************************************************
//*****************************************************************************************************************************************
//*****************************************************************************************************************************************
/// Energy levels Chisq
cout<<Nlevel<<endl;
double Energy_chisq = 0;
for (int i = 0 ; i < Nlevel ; ++i) {
if (Level[i].Efit == 1) {
eigen_t Th_Energy = BoundRspace->find_boundstate( rmesh, Efermi, Level[i].N,
Level[i].l , Level[i].j , tol );
std::cout<<i<<" "<<"theory E is = "<< " " << Th_Energy.first<< "\t "<< " exp Energy is = " << " "<< Level[i].Energy<<std::endl;
Energy_chisq += std::pow( ( Th_Energy.first - Level[i].Energy )
/ (3.0 * Level[i].SigmaEnergy ), 2 );
}
}
///////
// determine experimental particle number (make it a little less
// to decrease the chance of the calculated number going over the
// experimental one)
double exp_particle_number;
double err_particle_number = 0.02;
if ( Zp == 1 ) exp_particle_number = Z - 0.01;
else exp_particle_number = A - Z - 0.01;
double particle_chisq = std::pow((( ParticleNumber - exp_particle_number )
/(3. * err_particle_number)), 2 );
// Add all the pieces together
//
double BoundChisquared = particle_chisq;
// double BoundChisquared = ch_den_chisq + ch_den_half_chisq + ch_den_one_chisq +
// ch_den_onehalf_chisq + ch_den_middle_chisq + ch_den_middle2half_chisq + Energy_chisq;
// double BoundChisquared = ch_den_chisq + ch_den_five1_chisq+R_rms_chisq + particle_chisq ;
// double BoundChisquared = ch_den_five1_chisq ;
//////
//Printing out the results to check and observe
//////
//
cout << "charge density at 0 = " << PointDist[0] << " "
<< "chisq = " << ch_den_chisq << " "<< "exp = "<< unfld[0] << endl;
cout << "charge density at 0.5 = " << PointDist[half_index] << " "
<< "chisq = " << ch_den_half_chisq << " "<< "exp = "<< unfld[1] << endl;
cout << "charge density at 1 = " << PointDist[one_index] << " "
<< "chisq = " << ch_den_one_chisq << " "<< "exp = "<< unfld[2] << endl;
cout << "charge density at 1.5 = " << PointDist[onehalf_index] << " "
<< "chisq = " << ch_den_onehalf_chisq << " "<< "exp = "<< unfld[3] << endl;
cout << "charge density at 2 = " << PointDist[middle_index] << " "
<< "chisq = " << ch_den_middle_chisq << " "<< "exp = "<< unfld[4] << endl;
cout << "charge density at 2.5 = " << PointDist[middle2half_index] << " "
<< "chisq = " << ch_den_middle2half_chisq << " "<< "exp = "<< unfld[5] << endl;
cout << " charge density at 3 = " << PointDist[three_index] << " "
<< "chisq = " << ch_den_three_chisq << " "<< "exp = "<< unfld[6] <<endl;
cout << " charge density at 3.5 = " << PointDist[three1_index] << " "
<< "chisq = " << ch_den_three1_chisq << " "<< "exp = "<< unfld[7] <<endl;
cout << " charge density at 4 = " << PointDist[four_index] << " "
<< "chisq = " << ch_den_four_chisq << " "<< "exp = "<< unfld[8] <<endl;
cout << " charge density at 4.5 = " << PointDist[four1_index] << " "
<< "chisq = " << ch_den_four1_chisq << " "<< "exp = "<< unfld[9] <<endl;
cout << " charge density at 5 = " << PointDist[five_index] << " "
<< "chisq = " << ch_den_five_chisq << " "<< "exp = "<< unfld[10] <<endl;
cout << " charge density at 5.5 = " << PointDist[five1_index] << " "
<< "chisq = " << ch_den_five1_chisq << " "<< "exp = "<< unfld[11] <<endl;
cout << Nlevel << " " << "Energy chisq = " << Energy_chisq << endl;
cout << " " <<endl;
cout << " " <<endl;
cout << "R_rms = " << R_rms << " "
<< "R_rms_chisq = " << R_rms_chisq << endl ;
cout << " " <<endl;
cout << "particle number = " << ParticleNumber << " "
<< "particle_chisq = " << particle_chisq << endl ;
cout << " " <<endl;
cout << "gamma1 = "<< gamma1 << " "
<< "gamma1_chisq = " << gamma1_chisq << endl ;
cout << " " <<endl;
cout << "total bound chisq = " << BoundChisquared << endl ;
cout << " " <<endl;
//p(n)ParticleNumber is from folding
cout << "Chisq250" << " " << tot_chisq_p_250 << " " << "Chisq 650" << " "<< tot_chisq_p_650 << endl;
/////
//////saving the Point Dist in a file, it could be useful for checking especially in the first iteration, I used it
/////
//
std::string akbar="akbarr.out";
std::ofstream filedist(akbar.c_str() );
for (int kk=0; kk < rmesh.size() ; kk++) {
filedist << rmesh[kk] << " " << PointDist[kk] <<std::endl;
}
filedist.close();
// cout << PointDist[0] << " " << proton_folding[0] << " " << neutron_folding[0] << " " << nParticleNumber << " " << pParticleNumber << endl ;
return BoundChisquared;
}
//*********************************************************************
/**
*relativistic conversion from Lab kinetic energyto total CM kinetic energy
\param Elab energ in laboratory frame [MeV]
*/
double reaction::energyLab2Cm(double Elab)
{
if (Elab < 0.) return Elab*A/(1.+A);
// center of mass velocity in units of c
double vcm = sqrt(Elab*(Elab+2.*scatterRspace::m0))/(Elab+(1.+A)*
scatterRspace::m0);
//gamma factor for this velocity
double gam = 1./sqrt(1.-std::pow(vcm,2));
double Ecm = (gam-1.)*(1.+A)*scatterRspace::m0 +
gam*Elab*(A-1.)*scatterRspace::m0/((A+1.)*
scatterRspace::m0+Elab);
return Ecm;
}
//**********************************************************************
/**
*relativistic conversion from Lab kinetic energy to total CM kinetic energy
\param Ecm is energy in the center-of-mass frame
*/
double reaction::energyCm2Lab(double Ecm)
{
if (Ecm < 0.) return Ecm/A*(1.+A);
//find momentum of projecile, also momentum of target
double pc = sqrt(Ecm)*sqrt((Ecm+2.*scatterRspace::m0)*(Ecm+2.*A*
scatterRspace::m0)*
(Ecm+2.*(A+1.)*scatterRspace::m0))/2./(Ecm+(A+1)
*scatterRspace::m0);
//velocity of target in units of c
double vtarget = pc/sqrt(pow(pc,2)+pow(A*scatterRspace::m0,2));
//gamma factor for this velocity
double gam = 1./sqrt(1.-pow(vtarget,2));
// tot energy of projectile (neutron or proton in com frame)
double Eproj = sqrt(pow(scatterRspace::m0,2)+pow(pc,2));
double Elab = (Eproj + vtarget*pc)*gam;
//this energy contains rest mass , so remove it
Elab -= scatterRspace::m0;
return Elab;
}
void reaction::Print_DiffXsection( double Elab ) {
double Ecm = energyLab2Cm( Elab );
ScatterRspace->getSmatrix(Ecm,Elab);
double theta_min = 10;
double theta_max = 180;
double theta_pts = 100;
double delta_theta = ( theta_max - theta_min ) / theta_pts;
ofstream file( "diff_cross_section.out" );
for ( int i = 0; i < theta_pts; i++) {
double theta_deg = theta_min + i * delta_theta; // angle in degrees
double theta_rad = theta_deg * pi/180.; // angle in radians
file << theta_deg << " "
<< ScatterRspace->DifferentialXsection( theta_rad ) << endl;
}
file.close();
file.clear();
}
| [
"matkinson@wustl.edu"
] | matkinson@wustl.edu |
db1f0f8b7e95e36aeeac5582815d6490ae9562b7 | bfed570d24468df3994eb876758253b70c3d375e | /src/hzip_core/runtime/cache_provider.h | 5b0a9a5f1db6602b71533151daaba872283354f6 | [] | no_license | hybridzip/hybridzip | 624fc67a498c004ca2a26b0b433cccdcf953151b | 8ed98b1c2058860bd5fe356320b6debbf589c37b | refs/heads/master | 2023-08-04T13:12:13.604343 | 2023-07-21T06:30:01 | 2023-07-21T06:30:01 | 177,826,931 | 1 | 1 | null | 2023-07-21T06:30:03 | 2019-03-26T16:22:56 | C++ | UTF-8 | C++ | false | false | 709 | h | #ifndef HZIP_CORE_RUNTIME_CACHE_PROVIDER_H
#define HZIP_CORE_RUNTIME_CACHE_PROVIDER_H
#include <cstdint>
#include <vector>
#include <mutex>
#include <string>
#include <rainman/cache.h>
namespace hzruntime {
class CacheProvider {
private:
static uint64_t _rainman_cache_count;
static uint64_t _rainman_cache_index;
static std::vector<rainman::cache> _rainman_caches;
static std::vector<std::mutex> _rainman_cache_mutexes;
static std::mutex _rainman_cache_mutex;
public:
static void init_cache(const std::string &filename, uint64_t count, uint64_t page_size);
static std::pair<rainman::cache &, std::mutex &> get_cache();
};
}
#endif
| [
"vishaals2000@gmail.com"
] | vishaals2000@gmail.com |
9f5730eebfebb64c4addb027312bb4bb8aebd9a8 | 3bcfadfd05d4691ac43d76089a99d0cbb20d8900 | /cmake_make_gtest_cppunit/LinkedList.h | 3ae3f30143703585cf6ede95bee4a99b3113bd73 | [] | no_license | Vinograduss/technopark_cpp | 8ba00c3091cb547851c42954e0dab0a4d5f0948f | 67a4697b7d5d362d515491a48fe6fdadfb1a18bf | refs/heads/master | 2021-12-09T15:24:43.147666 | 2021-11-16T14:31:09 | 2021-11-16T14:31:09 | 224,828,324 | 0 | 3 | null | 2019-11-29T10:07:42 | 2019-11-29T10:07:41 | null | UTF-8 | C++ | false | false | 684 | h | #ifndef LECTURE2_LINKEDLIST_H_
#define LECTURE2_LINKEDLIST_H_
struct Node {
Node()
: data(0),
next(nullptr),
prev(nullptr) {}
int data;
Node* next;
Node* prev;
};
// http://ru.cppreference.com/w/cpp/container/list
class LinkedList {
public:
LinkedList();
virtual ~LinkedList();
void PushBack(int val);
void Display();
Node* Front() const { return head_; };
Node* Back() const { return tail_; };
Node* Search(int val);
Node* InsertAfter(Node* node, int data);
bool DeteleAt(Node* node);
static void Union(LinkedList* list1, LinkedList* list2);
private:
Node* head_;
Node* tail_;
};
#endif // LECTURE2_LINKEDLIST_H_
| [
"i.saneev@corp.mail.ru"
] | i.saneev@corp.mail.ru |
53849759c4a04cd61afe9072326a23b234f98048 | 987084195af62f2bd88a2a7990a4b660e35a9a0f | /Bridges/BridgeV3_FromYarp_GridMap2D/smartsoft/src/ParameterStateStruct.cc | c92adf9d04821281e9e3eb4b4a129966c7df3a83 | [
"BSD-3-Clause"
] | permissive | CARVE-ROBMOSYS/Yarp-SmartSoft-Integration | e1b1584d17c8a10efddbd3fddd0fd54a8d1f63d2 | 4023602f5540d1e66804b3d0db80f63aac536f8b | refs/heads/master | 2021-06-26T16:35:35.098019 | 2019-04-23T09:33:18 | 2019-04-23T09:33:53 | 129,261,900 | 2 | 0 | null | 2019-04-09T20:41:46 | 2018-04-12T14:12:59 | C++ | UTF-8 | C++ | false | false | 1,475 | cc | //--------------------------------------------------------------------------
// Code generated by the SmartSoft MDSD Toolchain
// The SmartSoft Toolchain has been developed by:
//
// Service Robotics Research Center
// University of Applied Sciences Ulm
// Prittwitzstr. 10
// 89075 Ulm (Germany)
//
// Information about the SmartSoft MDSD Toolchain is available at:
// www.servicerobotik-ulm.de
//
// This file is generated once. Modify this file to your needs.
// If you want the toolchain to re-generate this file, please
// delete it before running the code generator.
//--------------------------------------------------------------------------
#include "ParameterStateStruct.hh"
#include "BridgeV3_FromYarp_GridMap2D.hh"
SmartACE::ParamResponseType ParameterStateStruct::handleCOMMIT(const ParameterStateStruct &commitState) {
// implement any consistency checks here which ensure that the incoming parameter meets components
// internal constraints. If the current parameter violates any consistency checks, return
// SmartACE::ParamResponseType::INVALID, which will result in this commitState to be rejected (not
// copied into the globalState) and the corresponding response type is communicated back to the
// ParameterMaster. Be aware, that you should avoid blocking calls here. If you need blocking
// calls, use an active trigger in combination with commit.
return SmartACE::ParamResponseType::OK;
}
// implement your custom getter methods here
| [
"alberto.cardellino@iit.it"
] | alberto.cardellino@iit.it |
3f1faed5d1d325afb824b42378fe61783ec26311 | 9c4c41c05baed5a60b47d3ac674cdf4344f427d0 | /src/qt/signverifymessagedialog.cpp | 409605783a56c19c9bd45ba16c7f63e693c74cee | [
"MIT"
] | permissive | DeCrypt0/bashcoin | b662d12f3ed2f7f2794d929b70e1a6b4abbf980b | f0b29e480d014cb5f1ddac3fe1906ba257d5c7da | refs/heads/master | 2020-03-19T07:00:34.776141 | 2018-01-27T08:40:30 | 2018-01-27T08:40:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,825 | cpp | #include "signverifymessagedialog.h"
#include "ui_signverifymessagedialog.h"
#include "addressbookpage.h"
#include "base58.h"
#include "guiutil.h"
#include "init.h"
#include "main.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include "wallet.h"
#include <QClipboard>
#include <string>
#include <vector>
SignVerifyMessageDialog::SignVerifyMessageDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::SignVerifyMessageDialog),
model(0)
{
ui->setupUi(this);
#if (QT_VERSION >= 0x040700)
/* Do not move this to the XML file, Qt before 4.7 will choke on it */
ui->addressIn_SM->setPlaceholderText(tr("Enter a BashCoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)"));
ui->signatureOut_SM->setPlaceholderText(tr("Click \"Sign Message\" to generate signature"));
ui->addressIn_VM->setPlaceholderText(tr("Enter a BashCoin address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)"));
ui->signatureIn_VM->setPlaceholderText(tr("Enter BashCoin signature"));
#endif
GUIUtil::setupAddressWidget(ui->addressIn_SM, this);
GUIUtil::setupAddressWidget(ui->addressIn_VM, this);
ui->addressIn_SM->installEventFilter(this);
ui->messageIn_SM->installEventFilter(this);
ui->signatureOut_SM->installEventFilter(this);
ui->addressIn_VM->installEventFilter(this);
ui->messageIn_VM->installEventFilter(this);
ui->signatureIn_VM->installEventFilter(this);
ui->signatureOut_SM->setFont(GUIUtil::bitcoinAddressFont());
ui->signatureIn_VM->setFont(GUIUtil::bitcoinAddressFont());
}
SignVerifyMessageDialog::~SignVerifyMessageDialog()
{
delete ui;
}
void SignVerifyMessageDialog::setModel(WalletModel *model)
{
this->model = model;
}
void SignVerifyMessageDialog::setAddress_SM(QString address)
{
ui->addressIn_SM->setText(address);
ui->messageIn_SM->setFocus();
}
void SignVerifyMessageDialog::setAddress_VM(QString address)
{
ui->addressIn_VM->setText(address);
ui->messageIn_VM->setFocus();
}
void SignVerifyMessageDialog::showTab_SM(bool fShow)
{
ui->tabWidget->setCurrentIndex(0);
if (fShow)
this->show();
}
void SignVerifyMessageDialog::showTab_VM(bool fShow)
{
ui->tabWidget->setCurrentIndex(1);
if (fShow)
this->show();
}
void SignVerifyMessageDialog::on_addressBookButton_SM_clicked()
{
if (model && model->getAddressTableModel())
{
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec())
{
setAddress_SM(dlg.getReturnValue());
}
}
}
void SignVerifyMessageDialog::on_pasteButton_SM_clicked()
{
setAddress_SM(QApplication::clipboard()->text());
}
void SignVerifyMessageDialog::on_signMessageButton_SM_clicked()
{
if (!model)
return;
/* Clear old signature to ensure users don't get confused on error with an old signature displayed */
ui->signatureOut_SM->clear();
CBashCoincoinAddress addr(ui->addressIn_SM->text().toStdString());
if (!addr.IsValid())
{
ui->addressIn_SM->setValid(false);
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
return;
}
CKeyID keyID;
if (!addr.GetKeyID(keyID))
{
ui->addressIn_SM->setValid(false);
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
return;
}
WalletModel::UnlockContext ctx(model->requestUnlock());
if (!ctx.isValid())
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled."));
return;
}
CKey key;
if (!pwalletMain->GetKey(keyID, key))
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(tr("Private key for the entered address is not available."));
return;
}
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << ui->messageIn_SM->document()->toPlainText().toStdString();
std::vector<unsigned char> vchSig;
if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig))
{
ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>"));
return;
}
ui->statusLabel_SM->setStyleSheet("QLabel { color: green; }");
ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>"));
ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size())));
}
void SignVerifyMessageDialog::on_copySignatureButton_SM_clicked()
{
QApplication::clipboard()->setText(ui->signatureOut_SM->text());
}
void SignVerifyMessageDialog::on_clearButton_SM_clicked()
{
ui->addressIn_SM->clear();
ui->messageIn_SM->clear();
ui->signatureOut_SM->clear();
ui->statusLabel_SM->clear();
ui->addressIn_SM->setFocus();
}
void SignVerifyMessageDialog::on_addressBookButton_VM_clicked()
{
if (model && model->getAddressTableModel())
{
AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if (dlg.exec())
{
setAddress_VM(dlg.getReturnValue());
}
}
}
void SignVerifyMessageDialog::on_verifyMessageButton_VM_clicked()
{
CBashCoincoinAddress addr(ui->addressIn_VM->text().toStdString());
if (!addr.IsValid())
{
ui->addressIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
return;
}
CKeyID keyID;
if (!addr.GetKeyID(keyID))
{
ui->addressIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
return;
}
bool fInvalid = false;
std::vector<unsigned char> vchSig = DecodeBase64(ui->signatureIn_VM->text().toStdString().c_str(), &fInvalid);
if (fInvalid)
{
ui->signatureIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The signature could not be decoded.") + QString(" ") + tr("Please check the signature and try again."));
return;
}
CDataStream ss(SER_GETHASH, 0);
ss << strMessageMagic;
ss << ui->messageIn_VM->document()->toPlainText().toStdString();
CPubKey pubkey;
if (!pubkey.RecoverCompact(Hash(ss.begin(), ss.end()), vchSig))
{
ui->signatureIn_VM->setValid(false);
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(tr("The signature did not match the message digest.") + QString(" ") + tr("Please check the signature and try again."));
return;
}
if (!(CBashCoincoinAddress(pubkey.GetID()) == addr))
{
ui->statusLabel_VM->setStyleSheet("QLabel { color: red; }");
ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verification failed.") + QString("</nobr>"));
return;
}
ui->statusLabel_VM->setStyleSheet("QLabel { color: green; }");
ui->statusLabel_VM->setText(QString("<nobr>") + tr("Message verified.") + QString("</nobr>"));
}
void SignVerifyMessageDialog::on_clearButton_VM_clicked()
{
ui->addressIn_VM->clear();
ui->signatureIn_VM->clear();
ui->messageIn_VM->clear();
ui->statusLabel_VM->clear();
ui->addressIn_VM->setFocus();
}
bool SignVerifyMessageDialog::eventFilter(QObject *object, QEvent *event)
{
if (event->type() == QEvent::MouseButtonPress || event->type() == QEvent::FocusIn)
{
if (ui->tabWidget->currentIndex() == 0)
{
/* Clear status message on focus change */
ui->statusLabel_SM->clear();
/* Select generated signature */
if (object == ui->signatureOut_SM)
{
ui->signatureOut_SM->selectAll();
return true;
}
}
else if (ui->tabWidget->currentIndex() == 1)
{
/* Clear status message on focus change */
ui->statusLabel_VM->clear();
}
}
return QDialog::eventFilter(object, event);
}
| [
"niubiduang@gmail.com"
] | niubiduang@gmail.com |
5669a9121ac0ee6236a659df241296fbe93d3000 | b268c986b8c3ad58cef649b123844f4cc9a904bc | /GTRACT/Common/itkDtiGraphSearchTrackingFilter.h | 20b5b03998c0c3735f44bdad6cfeb2e28b689586 | [] | no_license | Slicer/BRAINSTools | c0848684e68bd0b85d1b33e9a5caeb749ec81262 | c658c752a053ab2006929489d5f0e9297857ba18 | refs/heads/slicer-2015-08-21-v4.5.0 | 2021-01-18T07:32:41.051518 | 2015-10-06T21:10:16 | 2015-11-03T16:30:19 | 21,228,900 | 5 | 5 | null | 2017-12-05T23:04:13 | 2014-06-26T05:19:24 | C++ | UTF-8 | C++ | false | false | 4,494 | h | /*=========================================================================
*
* Copyright SINAPSE: Scalable Informatics for Neuroscience, Processing and Software Engineering
* The University of Iowa
*
* 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.txt
*
* 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.
*
*=========================================================================*/
/*=========================================================================
Program: GTRACT (Guided Tensor Restore Anatomical Connectivity Tractography)
Module: $RCSfile: $
Language: C++
Date: $Date: 2006/03/29 14:53:40 $
Version: $Revision: 1.9 $
Copyright (c) University of Iowa Department of Radiology. All rights reserved.
See GTRACT-Copyright.txt or http://mri.radiology.uiowa.edu/copyright/GTRACT-Copyright.txt
for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#ifndef __itkDtiGraphSearchTrackingFilter_h
#define __itkDtiGraphSearchTrackingFilter_h
#include "itkObject.h"
#include "itkImage.h"
#include "itkImageToImageFilter.h"
#include "itkIOCommon.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkVectorLinearInterpolateImageFunction.h"
#include "itkImageRegionConstIteratorWithIndex.h"
#include "itkPointSet.h"
#include "itkBlobSpatialObject.h"
#include "itkMersenneTwisterRandomVariateGenerator.h"
#include "itkDtiTrackingFilterBase.h"
#include "algo.h"
#include "GtractTypes.h"
#include "gtractCommonWin32.h"
#include <map>
#include <string>
namespace itk
{
/** \class DtiGraphSearchTrackingFilter
*/
template <class TTensorImageType, class TAnisotropyImageType, class TMaskImageType>
class DtiGraphSearchTrackingFilter : public itk::DtiTrackingFilterBase<TTensorImageType,
TAnisotropyImageType,
TMaskImageType>
{
public:
/** Standard class typedefs. */
typedef DtiGraphSearchTrackingFilter Self;
typedef itk::DtiTrackingFilterBase<TTensorImageType, TAnisotropyImageType, TMaskImageType> Superclass;
typedef SmartPointer<Self> Pointer;
typedef SmartPointer<const Self> ConstPointer;
typedef itk::Statistics::MersenneTwisterRandomVariateGenerator RandomGeneratorType;
typedef RandomGeneratorType::Pointer RandomGeneratorPointer;
/** Standard New method. */
itkNewMacro(Self);
/** Runtime information support. */
itkTypeMacro(DtiGraphSearchTrackingFilter, itk::DtiTrackingFilterBase);
itkSetMacro(AnisotropyBranchingValue, float);
itkSetMacro(RandomSeed, int);
itkSetMacro(MaximumBranches, unsigned int);
itkSetMacro(UseRandomWalk, bool);
itkSetMacro(RandomWalkAngle, double);
itkGetMacro(RandomWalkAngle, double);
itkSetMacro(CurvatureBranchAngle, double);
itkGetMacro(CurvatureBranchAngle, double);
typename itk::Point<double, 3> InitializeCenterOfMask();
void Update();
protected:
DtiGraphSearchTrackingFilter();
~DtiGraphSearchTrackingFilter()
{
}
private:
DtiGraphSearchTrackingFilter(const Self &); // purposely not implemented
void operator=(const Self &); // purposely not implemented
RandomGeneratorPointer m_RandomGenerator;
float m_AnisotropyBranchingValue;
double m_CurvatureBranchAngle;
unsigned int m_MaximumBranches;
bool m_UseRandomWalk;
double m_RandomWalkAngle;
int m_RandomSeed;
}; // end of class
} // end namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
#include "itkDtiGraphSearchTrackingFilter.hxx"
#endif
#endif
| [
"hans-johnson@uiowa.edu"
] | hans-johnson@uiowa.edu |
64cf7bbd0ebbff9cabab2d16f6da543de53ad981 | 1880ae99db197e976c87ba26eb23a20248e8ee51 | /ecm/include/tencentcloud/ecm/v20190719/model/Internet.h | 34078065e2ac169c38b69d37b7a55df39c0b0355 | [
"Apache-2.0"
] | permissive | caogenwang/tencentcloud-sdk-cpp | 84869793b5eb9811bb1eb46ed03d4dfa7ce6d94d | 6e18ee6622697a1c60a20a509415b0ddb8bdeb75 | refs/heads/master | 2023-08-23T12:37:30.305972 | 2021-11-08T01:18:30 | 2021-11-08T01:18:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,894 | h | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef TENCENTCLOUD_ECM_V20190719_MODEL_INTERNET_H_
#define TENCENTCLOUD_ECM_V20190719_MODEL_INTERNET_H_
#include <string>
#include <vector>
#include <map>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
#include <tencentcloud/core/AbstractModel.h>
#include <tencentcloud/ecm/v20190719/model/PrivateIPAddressInfo.h>
#include <tencentcloud/ecm/v20190719/model/PublicIPAddressInfo.h>
#include <tencentcloud/ecm/v20190719/model/InstanceNetworkInfo.h>
namespace TencentCloud
{
namespace Ecm
{
namespace V20190719
{
namespace Model
{
/**
* 实例的网络相关信息。
*/
class Internet : public AbstractModel
{
public:
Internet();
~Internet() = default;
void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const;
CoreInternalOutcome Deserialize(const rapidjson::Value &value);
/**
* 获取实例的内网相关信息列表。顺序为主网卡在前,辅助网卡按绑定先后顺序排列。
注意:此字段可能返回 null,表示取不到有效值。
* @return PrivateIPAddressSet 实例的内网相关信息列表。顺序为主网卡在前,辅助网卡按绑定先后顺序排列。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::vector<PrivateIPAddressInfo> GetPrivateIPAddressSet() const;
/**
* 设置实例的内网相关信息列表。顺序为主网卡在前,辅助网卡按绑定先后顺序排列。
注意:此字段可能返回 null,表示取不到有效值。
* @param PrivateIPAddressSet 实例的内网相关信息列表。顺序为主网卡在前,辅助网卡按绑定先后顺序排列。
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetPrivateIPAddressSet(const std::vector<PrivateIPAddressInfo>& _privateIPAddressSet);
/**
* 判断参数 PrivateIPAddressSet 是否已赋值
* @return PrivateIPAddressSet 是否已赋值
*/
bool PrivateIPAddressSetHasBeenSet() const;
/**
* 获取实例的公网相关信息列表。顺序为主网卡在前,辅助网卡按绑定先后顺序排列。
注意:此字段可能返回 null,表示取不到有效值。
* @return PublicIPAddressSet 实例的公网相关信息列表。顺序为主网卡在前,辅助网卡按绑定先后顺序排列。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::vector<PublicIPAddressInfo> GetPublicIPAddressSet() const;
/**
* 设置实例的公网相关信息列表。顺序为主网卡在前,辅助网卡按绑定先后顺序排列。
注意:此字段可能返回 null,表示取不到有效值。
* @param PublicIPAddressSet 实例的公网相关信息列表。顺序为主网卡在前,辅助网卡按绑定先后顺序排列。
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetPublicIPAddressSet(const std::vector<PublicIPAddressInfo>& _publicIPAddressSet);
/**
* 判断参数 PublicIPAddressSet 是否已赋值
* @return PublicIPAddressSet 是否已赋值
*/
bool PublicIPAddressSetHasBeenSet() const;
/**
* 获取实例网络相关信息。
注意:此字段可能返回 null,表示取不到有效值。
* @return InstanceNetworkInfoSet 实例网络相关信息。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::vector<InstanceNetworkInfo> GetInstanceNetworkInfoSet() const;
/**
* 设置实例网络相关信息。
注意:此字段可能返回 null,表示取不到有效值。
* @param InstanceNetworkInfoSet 实例网络相关信息。
注意:此字段可能返回 null,表示取不到有效值。
*/
void SetInstanceNetworkInfoSet(const std::vector<InstanceNetworkInfo>& _instanceNetworkInfoSet);
/**
* 判断参数 InstanceNetworkInfoSet 是否已赋值
* @return InstanceNetworkInfoSet 是否已赋值
*/
bool InstanceNetworkInfoSetHasBeenSet() const;
private:
/**
* 实例的内网相关信息列表。顺序为主网卡在前,辅助网卡按绑定先后顺序排列。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::vector<PrivateIPAddressInfo> m_privateIPAddressSet;
bool m_privateIPAddressSetHasBeenSet;
/**
* 实例的公网相关信息列表。顺序为主网卡在前,辅助网卡按绑定先后顺序排列。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::vector<PublicIPAddressInfo> m_publicIPAddressSet;
bool m_publicIPAddressSetHasBeenSet;
/**
* 实例网络相关信息。
注意:此字段可能返回 null,表示取不到有效值。
*/
std::vector<InstanceNetworkInfo> m_instanceNetworkInfoSet;
bool m_instanceNetworkInfoSetHasBeenSet;
};
}
}
}
}
#endif // !TENCENTCLOUD_ECM_V20190719_MODEL_INTERNET_H_
| [
"tencentcloudapi@tenent.com"
] | tencentcloudapi@tenent.com |
43eaa8f115d455a6c6e2e8bcf9ee1c9398b24c05 | fe247fc5d869339efdef242f0e0cf1145e879b00 | /MinLib/compiler.hpp | 1c6456ab25ddf181d02b8dba7a616214f1c8e6df | [] | no_license | tonybillings/minlib | 1320602cc0daf23022934c0c45005e5f867e9d41 | 0cedaeb0fda6df0763d32d83c7544c7571b735b8 | refs/heads/main | 2023-07-14T17:09:11.921178 | 2021-08-25T09:09:28 | 2021-08-25T09:09:28 | 399,754,456 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 368 | hpp | #pragma once
#include <map>
#include <vector>
#include <string>
#include "lib_bundle.hpp"
class compiler
{
private:
static const char* msvc_template;
static const char* gcc_template;
public:
static void run_preprocessor(std::map<std::string, std::string> param_map);
static lib_bundle parse_preprocessor_output(std::map<std::string, std::string> param_map);
}; | [
"tony@optios.com"
] | tony@optios.com |
d7a214401d4814b7f2ab215e8b07c909f6cc3c78 | bd5506edd980530dbf580c9db8ca9538e0219836 | /Game1001_Assignment1/Source.cpp | baf409c38b1d6d988450e1342b322b82ceeaf8f9 | [] | no_license | Rohamx12/Game1001_Assignment1_phase2 | b3c23fbbfea2cb2902dec59d8265ee6eb75cccea | 4bccebe2bd1dfb27447ca792380e1fa8d835ae9f | refs/heads/master | 2023-06-12T00:01:56.769113 | 2021-06-25T22:12:16 | 2021-06-25T22:12:16 | 380,161,148 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,564 | cpp | //Roham Ali 101344253
//Kenneth Rodriguez 101345891
#include <iostream>
#include <sstream>
#include <time.h>
#include <cstdlib>
using namespace std;
class BaseCharacter
{
protected:
string name;
int maxHp;
int presentHp;
int strenght;
int intelligence;
int basedamage;
int agility;
int dodgechance;
int secondarydamage;
public:
BaseCharacter(string n, int maxHp, int str, int intel, int baseDam, int agl, int dc, int secDam)
{
this->name = n;
this->maxHp = maxHp;
presentHp = maxHp;
strenght = str;
intelligence = intel;
basedamage = baseDam;
agility = agl;
dodgechance = dc;
secondarydamage = secDam;
}
string getName() const
{
return name;
}
int getStrenght() const
{
return strenght;
}
int getAgility() const
{
return agility;
}
int getMaxHp() const
{
return maxHp;
}
int getPresentHp() const
{
return presentHp;
}
int getAttackValue() const
{
return basedamage;
}
void takedamage(int amt)
{
presentHp -= amt;
if (presentHp < 0)
{
presentHp = 0;
}
}
int dodge()
{
if (agility > 10)
{
int chance = rand() % 100 + 1;
return chance;
}
}
int war = 100;
int castFireBall()
{
return basedamage + war;
}
int castHeal()
{
presentHp += war;
if (presentHp > maxHp)
{
presentHp = maxHp;
}
return war;
}
string toString()
{
stringstream s;
s << "Name: " << name << endl;
s << "Max HP: " << maxHp << endl;
s << "PresentHp: " << presentHp << endl;
s << "strenght: " << strenght << endl;
s << "Intellegence: " << intelligence << endl;
s << "Agility" << agility << endl << endl << endl;
return s.str();
}
};
class Warrior :public BaseCharacter
{
public:
Warrior(string n, int maxHp, int str, int intel, int baseDam ,int agl,int dc, int secdam) :BaseCharacter(n, maxHp, str, intel, baseDam, agl, dc, secdam) {}
int getAttackValue()
{
return basedamage + strenght / 2;
}
int getSecDam()
{
return secondarydamage;
}
};
class Mage :public BaseCharacter {
private:
int mana;
public:
Mage(string n, int maxHp, int str, int intel, int baseDam, int mana, int agl, int dc, int secdam) :BaseCharacter(n, maxHp, str, intel, baseDam, agl, dc, secdam)
{
this->mana = mana;
}
};
class Priest :public BaseCharacter {
private:
int mana;
public:
Priest(string n, int maxHp, int str, int intel, int baseDam, int mana, int agl, int dc, int secdam) :BaseCharacter(n, maxHp, str, intel, baseDam, agl, dc, secdam)
{
this->mana = mana;
}
};
void ArenaManager(BaseCharacter* player1 , BaseCharacter* player2)
{
int round = 1, roll, damage, secdamage;
system("CLS");
while (player1->getPresentHp() > 0 && player2->getPresentHp() > 0)
{
cout << "Battle Field: " << player1->getName() << " And " << player2->getName() << "!!!" << endl;
cout << "-------- Round: " << round << " ---------\n\n\n";
roll = rand() % 100 + 1;
if (roll > 50)
{
//Warrior go first
damage = player1->getAttackValue();
if (roll > 90)
{
player2->takedamage(damage/2);
cout << player1->getName() << " Used his Secondary weapon on " << player2->getName() << " for " << damage /2 << " damage \n\n";
}
else
{
player2->takedamage(damage);
cout << player1->getName() << " Used his Primary weapon on " << player2->getName() << " for " << damage << " damage \n\n";
}
if (player2->getPresentHp() > 0)
{
roll = rand() % 100 + 1;
if (roll < 60)
{
damage = player2->getAttackValue();
if (player1->dodge() < 50)
{
if (roll > 90)
{
player1->takedamage(damage/2);
cout << player2->getName() << " Used his Secondary weapon on " << player1->getName() << " for " << damage << " damage \n\n";
}
else
{
player1->takedamage(damage);
cout << player2->getName() << " Used his Primary weapon on " << player1->getName() << " for " << damage << " damage \n\n";
}
}
else
{
cout << player1->getName() << " Dodged the attack" << endl;
}
}
else if (roll <= 90)
{
damage = player2->castFireBall();
if (player1->dodge() < 50)
{
player1->takedamage(damage);
cout << player2->getName() << " hits " << player1->getName() << " With a *fire ball* for " << damage << " damage \n\n";
}
else
{
cout << player1->getName() << " Dodged the *fire ball*" << endl;
}
}
else
{
player2->castHeal();
cout << player2->getName() << " Healed up for " << player2->castHeal() << endl;
}
}
}
else
{
//player2e goes first
roll = rand() % 100 + 1;
if (roll < 60)
{
damage = player2->getAttackValue();
if (player1->dodge() < 50)
{
if (roll > 90)
{
player1->takedamage(damage/2);
cout << player2->getName() << " Used his Secondary weapon on " << player1->getName() << " for " << damage / 2 << " damage \n\n";
}
else
{
player1->takedamage(damage);
cout << player2->getName() << " Used his Primary weapon on " << player1->getName() << " for " << damage << " damage \n\n";
}
}
else
{
cout << player1->getName() << " Dodged the attack" << endl;
}
}
else if (roll <= 90)
{
damage = player2->castFireBall();
if (player1->dodge() < 50)
{
player1->takedamage(damage);
cout << player2->getName() << " hits " << player1->getName() << " with a *fire ball* for " << damage << " damage \n\n";
}
else
{
cout << player1->getName() << " Dodged the *fire ball*" << endl;
}
}
else
{
player2->castHeal();
cout << player2->getName() << " Healed up for " << player2->castHeal() << endl;
}
if (player2->getPresentHp() > 0)
{
damage = player1->getAttackValue();
if (roll > 90)
{
player2->takedamage(damage/2);
cout << player1->getName() << " Used his Secondary weapon on " << player2->getName() << " for " << damage /2<< " damage \n\n";
}
else
{
player2->takedamage(damage);
cout << player1->getName() << " Used his Primary weapon on " << player2->getName() << " for " << damage << " damage \n\n";
}
}
else
{
cout << player1->getName() << " Dodged the attack" << endl;
}
}
cout << "End of round stats: \n" << player1->getName() << "HP: (" << player1->getPresentHp() << ")\n" << player2->getName() << "HP: (" << player2->getPresentHp() << ")\n\n\n";
round++;
cout << "Press any key to skip this round... \n\n";
system("Pause");
}
if (player1->getPresentHp() > 0)
{
cout << "=======" << player1->getName() << " Wins!" << "=======" << endl;
}
else
{
cout << "=======" << player2->getName() << " Wins!" << "=======" << endl;
}
}
int main()
{
int pick, wp, wpdmg = 0, stg, agil;
string name;
int picked,view;
for (int i = 0; i <= 10; i++)
{
cout << "Pick your First fighter:\n 1.Warrior ==> 200hp === 20 intelligence\n 2.Mage ==> 185hp === 15 intelligence\n 3.Priest ==> 150hp === 10 intelligence\n";
cin >> pick;
if (pick == 1)
{
cout << "You picked a Warrior\n";
cout << "Your fighter's name:";
cin >> name;
for (int i = 0; i <= 10; i++)
{
cout << "choose your fighter's weapon:\n";
cout << "1.Sword ===> 30 damage\n2.Wand ===> 25\n3.Cross ===> 20\n";
cin >> wp;
if (wp >= 4 && wp <= 0)
{
cout << "You picked the wrong weapon\n";
}
if (wp == 1)
{
cout << "You picked Sword\n";
wpdmg = 30;
break;
}
else if (wp == 2)
{
cout << "You picked Wand\n";
wpdmg = 25;
break;
}
else if (wp == 3)
{
cout << "You picked Cross\n";
wpdmg = 20;
break;
}
}
cout << "Pick your characters strength:(0 to 50)\n";
cin >> stg;
if (stg < 0 || stg >50)
{
cout << "You picked the wrong number\n The character will have the default value(25)\n";
stg = 25;
}
cout << "Enter your character agility:(0 to 50)\n";
cin >> agil;
if (agil < 0 || agil >50)
{
cout << "You picked the wrong number\n The character will have the default value(25)\n";
agil = 25;
}
Warrior* soldier1 = new Warrior(name, 200, stg, 20, wpdmg, agil, 0, 20);
cout << "Enter number (1) to view your fighter\n";
cin >> view;
if(view == 1)
{
cout << "*Fighter:*\n" << soldier1->toString();
system("Pause");
}
picked = 1;
break;
}
if (pick == 2)
{
cout << "You picked a Mage\n";
cout << "Your fighter's name:";
cin >> name;
for (int i = 0; i <= 10; i++)
{
cout << "choose your fighter's weapon:\n";
cout << "1.Sword ===> 30 damage\n2.Wand ===> 25\n3.Cross ===> 20\n";
cin >> wp;
if (wp >= 4 && wp <= 0)
{
cout << "You picked the wrong weapon\n";
}
if (wp == 1)
{
cout << "You picked Sword\n";
wpdmg = 30;
break;
}
else if (wp == 2)
{
cout << "You picked Wand\n";
wpdmg = 25;
break;
}
else if (wp == 3)
{
cout << "You picked Cross\n";
wpdmg = 20;
break;
}
}
cout << "Pick your characters strength:(0 to 50)\n";
cin >> stg;
if (stg < 0 || stg >50)
{
cout << "You picked the wrong number\n The character will have the default value(25)\n";
stg = 25;
}
cout << "Enter your character agility:(0 to 50)\n";
cin >> agil;
if (agil < 0 || agil >50)
{
cout << "You picked the wrong number\n The character will have the default value(25)\n";
agil = 25;
}
Mage* mag = new Mage(name, 185, stg, 15, wpdmg, 80, agil, 0, 20);
cout << "Enter number (1) to view your fighter";
cin >> view;
if (view == 1)
{
cout << "*Fighter:*\n" << mag->toString();
system("Pause");
}
picked = 2;
break;
}
if (pick == 3)
{
cout << "You picked a Priest\n";
cout << "Your fighter's name:";
cin >> name;
for (int i = 0; i <= 10; i++)
{
cout << "choose your fighter's weapon:\n";
cout << "1.Sword ===> 30 damage\n2.Wand ===> 25\n3.Cross ===> 20\n";
cin >> wp;
if (wp >= 4 && wp <= 0)
{
cout << "You picked the wrong weapon\n";
}
if (wp == 1)
{
cout << "You picked Sword\n";
wpdmg = 30;
break;
}
else if (wp == 2)
{
cout << "You picked Wand\n";
wpdmg = 25;
break;
}
else if (wp == 3)
{
cout << "You picked Cross\n";
wpdmg = 20;
break;
}
}
cout << "Pick your characters strength:(0 to 50)\n";
cin >> stg;
if (stg < 0 || stg >50)
{
cout << "You picked the wrong number\n The character will have the default value for strength(25)\n";
stg = 25;
}
cout << "Enter your character agility:(0 to 50)\n";
cin >> agil;
if (agil < 0 || agil >50)
{
cout << "You picked the wrong number\n The character will have the default value(25)\n";
agil = 25;
}
Priest* father = new Priest(name, 150, stg, 10, wpdmg, 80, agil, 0, 20);
cout << "Enter number (1) to view your fighter";
cin >> view;
if (view == 1)
{
cout << "*Fighter:*\n" << father->toString();
system("Pause");
}
picked = 3;
break;
}
else
{
cout << "You picked the wrong number. choose again\n\n";
}
}
Warrior* soldier1 = new Warrior(name, 200, stg, 20, wpdmg, agil, 0, 20);
Mage* mag = new Mage(name, 185, stg, 15, wpdmg, 80, agil, 0, 20);
Priest* father = new Priest(name, 150, stg, 10, wpdmg, 80, agil, 0, 20);
////////////////////////////
int pick1, wp1, wpdmg1 = 0, stg1, agil1;
string name1;
int picked2;
for (int i = 0; i <= 10; i++)
{
cout << "Pick your Second fighter:\n 1.Warrior ==> 200hp === 20 intelligence\n 2.Mage ==> 185hp === 15 intelligence\n 3.Priest ==> 150hp === 10 intelligence\n";
cin >> pick1;
if (pick1 == 1)
{
cout << "You picked a Warrior\n";
cout << "Your Second fighter's name:";
cin >> name1;
for (int i = 0; i <= 10; i++)
{
cout << "choose your fighter's weapon:\n";
cout << "1.Sword ===> 30 damage\n2.Wand ===> 25\n3.Cross ===> 20\n";
cin >> wp1;
if (wp1 >= 4 && wp1 <= 0)
{
cout << "You picked the wrong weapon\n";
}
if (wp1 == 1)
{
cout << "You picked Sword\n";
wpdmg1 = 30;
break;
}
else if (wp1 == 2)
{
cout << "You picked Wand\n";
wpdmg1 = 25;
break;
}
else if (wp1 == 3)
{
cout << "You picked Cross\n";
wpdmg1 = 20;
break;
}
}
cout << "Pick your characters strength:(0 to 50)\n";
cin >> stg1;
if (stg1 < 0 || stg1 >50)
{
cout << "You picked the wrong number\n The character will have the default value(25)\n";
stg1 = 25;
}
cout << "Enter your character agility:(0 to 50)\n";
cin >> agil1;
if (agil1 < 0 || agil1 >50)
{
cout << "You picked the wrong number\n The character will have the default value(25)\n";
agil1 = 25;
}
Warrior* soldier2 = new Warrior(name1, 200, stg1, 20, wpdmg1, agil1, 0, 20);
cout << "Enter number (1) to view your fighter";
cin >> view;
if (view == 1)
{
cout << "*Fighter:*\n" << soldier2->toString();
system("Pause");
}
picked2 = 1;
break;
}
else if (pick1 == 2)
{
cout << "You picked a Mage\n";
cout << "Your fighter's name:";
cin >> name1;
for (int i = 0; i <= 10; i++)
{
cout << "choose your fighter's weapon:\n";
cout << "1.Sword ===> 30 damage\n2.Wand ===> 25\n3.Cross ===> 20\n";
cin >> wp1;
if (wp1 >= 4 && wp1 <= 0)
{
cout << "You picked the wrong weapon\n";
}
if (wp1 == 1)
{
cout << "You picked Sword\n";
wpdmg1 = 30;
break;
}
else if (wp1 == 2)
{
cout << "You picked Wand\n";
wpdmg1 = 25;
break;
}
else if (wp == 3)
{
cout << "You picked Cross\n";
wpdmg1 = 20;
break;
}
}
cout << "Pick your characters strength:(0 to 50)\n";
cin >> stg1;
if (stg1 < 0 || stg1 >50)
{
cout << "You picked the wrong number\n The character will have the default value(25)\n";
stg1 = 25;
}
cout << "Enter your character agility:(0 to 50)\n";
cin >> agil1;
if (agil1 < 0 || agil1 >50)
{
cout << "You picked the wrong number\n The character will have the default value(25)\n";
agil1 = 25;
}
Mage* mag2 = new Mage(name1, 185, stg1, 15, wpdmg1, 80, agil1, 0, 20);
cout << "Enter number (1) to view your fighter";
cin >> view;
if (view == 1)
{
cout << "*Fighter:*\n" << mag2->toString();
system("Pause");
}
picked2 = 2;
break;
}
else if (pick1 == 3)
{
cout << "You picked a Priest\n";
cout << "Your fighter's name:";
cin >> name1;
for (int i = 0; i <= 10; i++)
{
cout << "choose your fighter's weapon:\n";
cout << "1.Sword ===> 30 damage\n2.Wand ===> 25\n3.Cross ===> 20\n";
cin >> wp1;
if (wp1 >= 4 && wp1 <= 0)
{
cout << "You picked the wrong weapon\n";
}
if (wp1 == 1)
{
cout << "You picked Sword\n";
wpdmg1 = 30;
break;
}
else if (wp1 == 2)
{
cout << "You picked Wand\n";
wpdmg1 = 25;
break;
}
else if (wp1 == 3)
{
cout << "You picked Cross\n";
wpdmg1 = 20;
break;
}
}
cout << "Pick your characters strength:(0 to 50)\n";
cin >> stg1;
if (stg1 < 0 || stg1 >50)
{
cout << "You picked the wrong number\n The character will have the default value for strength(25)\n";
stg1 = 25;
}
cout << "Enter your character agility:(0 to 50)\n";
cin >> agil1;
if (agil1 < 0 || agil1 >50)
{
cout << "You picked the wrong number\n The character will have the default value(25)\n";
agil1 = 25;
}
Priest* father2 = new Priest(name1, 150, stg1, 10, wpdmg1, 80, agil1, 0, 20);
cout << "Enter number (1) to view your fighter";
cin >> view;
if (view == 1)
{
cout << "*Fighter:*\n" << father2->toString();
system("Pause");
}
picked2 = 3;
break;
}
else
{
cout << "You picked the wrong number. choose again\n\n";
}
}
srand(time(NULL));
Warrior* soldier2 = new Warrior(name1, 200, stg1, 20, wpdmg1, agil1, 0, 20);
Mage* mag2 = new Mage(name1, 185, stg1, 15, wpdmg1, 80, agil1, 0, 20);
Priest* father2 = new Priest(name1, 150, stg1, 10, wpdmg1, 80, agil1, 0, 20);
int press, fight;
if (picked == 1 && picked2 == 1)
{
cout << "To view all of the contenders Enter number (1)... \n Enter any key to continue\n";
cin >> press;
if (press == 1)
{
cout << "*Contender 1:*\n" << soldier1->toString();
cout << "*Contender 2:*\n" << soldier2->toString();
system("Pause");
}
ArenaManager(soldier1, soldier2);
}
if (picked == 2 && picked2 == 1)
{
cout << "To view all of the contenders Enter number (1)... \n Enter any key to continue\n";
cin >> press;
if (press == 1)
{
cout << "*Contender 1:*\n" << mag->toString();
cout << "*Contender 2:*\n" << soldier2->toString();
system("Pause");
}
ArenaManager(mag, soldier2);
}
if (picked == 3 && picked2 == 1)
{
cout << "To view all of the contenders Enter number (1)... \n Enter any key to continue\n";
cin >> press;
if (press == 1)
{
cout << "*Contender 1:*\n" << father->toString();
cout << "*Contender 2:*\n" << soldier2->toString();
system("Pause");
}
ArenaManager(father, soldier2);
}
if (picked == 2 && picked2 == 2)
{
cout << "To view all of the contenders Enter number (1)... \n Enter any key to continue\n";
cin >> press;
if (press == 1)
{
cout << "*Contender 1:*\n" << mag->toString();
cout << "*Contender 2:*\n" << mag2->toString();
system("Pause");
}
ArenaManager(mag, mag2);
}
if (picked == 3 && picked2 == 2)
{
cout << "To view all of the contenders Enter number (1)... \n Enter any key to continue\n";
cin >> press;
if (press == 1)
{
cout << "*Contender 1:*\n" << mag->toString();
cout << "*Contender 2:*\n" << mag2->toString();
system("Pause");
}
ArenaManager(father, mag2);
}
if (picked == 1 && picked2 == 2)
{
cout << "To view all of the contenders Enter number (1)... \n Enter any key to continue\n";
cin >> press;
if (press == 1)
{
cout << "*Contender 1:*\n" << soldier1->toString();
cout << "*Contender 2:*\n" << mag2->toString();
system("Pause");
}
ArenaManager(soldier1, mag2);
}
if (picked == 1 && picked2 == 3)
{
cout << "To view all of the contenders Enter number (1)... \n Enter any key to continue\n";
cin >> press;
if (press == 1)
{
cout << "*Contender 1:*\n" << soldier1->toString();
cout << "*Contender 2:*\n" << father2->toString();
system("Pause");
}
ArenaManager(soldier1, father2);
}
if (picked == 2 && picked2 == 3)
{
cout << "To view all of the contenders Enter number (1)... \n Enter any key to continue\n";
cin >> press;
if (press == 1)
{
cout << "*Contender 1:*\n" << mag->toString();
cout << "*Contender 2:*\n" << father2->toString();
system("Pause");
}
ArenaManager(mag, father2);
}
if (picked == 3 && picked2 == 3)
{
cout << "To view all of the contenders Enter number (1)... \n Enter any key to continue\n";
cin >> press;
if (press == 1)
{
cout << "*Contender 1:*\n" << father->toString();
cout << "*Contender 2:*\n" << father2->toString();
system("Pause");
}
ArenaManager(father, father2);
}
return 0;
}
| [
"roham.rl.roham@gmail.com"
] | roham.rl.roham@gmail.com |
cfc732556beaa8bd2136d42c122bdc15c58b8aa5 | a465df25e3b5fcb68444563992ccb8063d3d27af | /Source/UdemyTestingGrounds/UdemyTestingGroundsHUD.cpp | f725262799dedee41947effbdadbdb187abf861c | [] | no_license | Massacre87/UdemyTestingGrounds | 194785f3fe2eac6aa518bff2c0e1fe8664ed142d | f0916d8c0f130dc6bde8d16712d367d5bfd5a191 | refs/heads/master | 2020-03-24T12:16:14.347389 | 2018-07-28T20:47:13 | 2018-07-28T20:47:13 | 142,709,167 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,096 | cpp | // Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#include "UdemyTestingGroundsHUD.h"
#include "Engine/Canvas.h"
#include "Engine/Texture2D.h"
#include "TextureResource.h"
#include "CanvasItem.h"
#include "UObject/ConstructorHelpers.h"
AUdemyTestingGroundsHUD::AUdemyTestingGroundsHUD()
{
// Set the crosshair texture
static ConstructorHelpers::FObjectFinder<UTexture2D> CrosshairTexObj(TEXT("/Game/FirstPerson/Textures/FirstPersonCrosshair"));
CrosshairTex = CrosshairTexObj.Object;
}
void AUdemyTestingGroundsHUD::DrawHUD()
{
Super::DrawHUD();
// Draw very simple crosshair
// find center of the Canvas
const FVector2D Center(Canvas->ClipX * 0.5f, Canvas->ClipY * 0.5f);
// offset by half the texture's dimensions so that the center of the texture aligns with the center of the Canvas
const FVector2D CrosshairDrawPosition( (Center.X),
(Center.Y + 20.0f));
// draw the crosshair
FCanvasTileItem TileItem( CrosshairDrawPosition, CrosshairTex->Resource, FLinearColor::White);
TileItem.BlendMode = SE_BLEND_Translucent;
Canvas->DrawItem( TileItem );
}
| [
""
] | |
a47642e0dbb6f98c7221606cb046edf2ae25f00a | 4cd7c56656e31d1148063bbfcc56d4b134947690 | /smacc/src/smacc/introspection/string_type_walker.cpp | 2d613ef79c2b5ed2020851a686ee5c5611174052 | [
"BSD-3-Clause"
] | permissive | Chipato1/SMACC | b57b29cf4f0d5a2cd7158e8c9832ca7d7511ad4e | 767096c1124d62a8dc7f20b7bb012d69f05abe92 | refs/heads/master | 2020-12-08T11:00:16.832237 | 2020-01-08T21:19:21 | 2020-01-08T21:19:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,810 | cpp | #include <smacc/introspection/string_type_walker.h>
#include <regex>
#include <memory>
#include <map>
#include <set>
#include <iostream>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/find_iterator.hpp>
#include <algorithm>
#include <boost/algorithm/string/trim.hpp>
#include <smacc/common.h>
namespace smacc
{
namespace introspection
{
bool replace(std::string &str, const std::string &from, const std::string &to)
{
size_t start_pos = str.find(from);
if (start_pos == std::string::npos)
return false;
str.replace(start_pos, from.length(), to);
return true;
}
std::string replace_back(std::string roottype, std::map<std::string, std::string> &typesdict)
{
while (roottype.find("$") != std::string::npos)
{
for (auto &t : typesdict)
{
auto &tkey = t.first;
auto &tval = t.second;
replace(roottype, tkey, tval);
}
}
return roottype;
// def replace_back(roottype, typesdict):
// # replace back
// while "$" in roottype:
// #print roottype
// for tkey in typesdict:
// tval = typesdict[tkey]
// roottype = roottype.replace(tkey, tval)
// return roottype
}
std::map<std::string, TypeInfo::Ptr> TypeInfo::typeInfoDatabase;
TypeInfo::Ptr TypeInfo::getTypeInfoFromTypeid(const std::type_info &tid)
{
return TypeInfo::getTypeInfoFromString(demangleSymbol(tid.name()));
}
TypeInfo::Ptr TypeInfo::getTypeInfoFromString(std::string inputtext)
{
auto it = typeInfoDatabase.find(inputtext);
if (it != typeInfoDatabase.end())
return typeInfoDatabase[inputtext];
bool ok = false;
int typecount = 0;
std::string originalinputtext = inputtext;
std::map<std::string, std::string> typesdict;
std::map<std::string, std::string> typesdict_content;
while (!ok)
{
//simpletypeRE = r"[^<>,\s]+<[^<>]+>"
//print ("input: " + inputtext)
const char *simpletypeRE = "[^\\<\\>,\\s]+\\<[^\\<\\>]+\\>";
//std::cout << inputtext << std::endl;
std::smatch matches;
std::regex regex(simpletypeRE); // matches words beginning by "sub"
//matches = [m for m in enumerate(re.finditer(simpletypeRE, inputtext))]
std::regex_search(inputtext, matches, regex);
// if len(matches) == 0:
// if len(typesdict) == 0:
// tkey = "$T" + str(typecount)
// typesdict[tkey] = inputtext
// break
if (matches.size() == 0)
{
if (typesdict.size() == 0)
{
auto tkey = "$T" + std::to_string(typecount);
typesdict[tkey] = inputtext;
}
break;
}
// for i, m in matches:
// tstr = m.group(0)
// tkey = "$T" + str(typecount)
// inputtext = inputtext.replace(tstr, tkey)
// print("updating input text: " + inputtext)
// typecount += 1
// typesdict[tkey] = tstr
int i = 0;
for (auto &m : matches)
{
std::string tstr = m;
auto tkey = "$T" + std::to_string(typecount);
replace(inputtext, tstr, tkey);
//std::cout << "updating input text:" << inputtext << std::endl;
typecount++;
typesdict[tkey] = tstr;
i++;
}
}
// allbasetypes = set()
// for tkey in typesdict.keys():
// flat = typesdict[tkey]
// print flat
// startindex = flat.index("<")
// flat = flat[startindex + 1:-1]
// basetypes = [t.strip() for t in flat.split(",")]
// for b in basetypes:
// if not "$" in b:
// allbasetypes.add(b)
std::set<std::string> allbasetypes;
for (auto &typeentry : typesdict)
{
auto flat = typeentry.second;
//std::cout << flat << std::endl;
size_t startindex = flat.find("<");
size_t endindex = flat.find(">");
if (startindex != std::string::npos)
{
flat = flat.substr(startindex + 1, endindex - startindex - 1);
//std::cout << typeentry.first <<":" << flat << std::endl;
typesdict_content[typeentry.first] = flat;
std::vector<std::string> localbasetypes;
std::istringstream iss(flat);
std::string token;
while (std::getline(iss, token, ','))
{
boost::trim(token);
localbasetypes.push_back(token);
//std::cout << "base type: " << token << std::endl;
}
for (auto &b : localbasetypes)
{
size_t found = b.find("$");
if (found == std::string::npos)
{
allbasetypes.insert(b);
}
}
}
// for b in allbasetypes:
// typesdict[b] = b
//refresh
for (auto &b : allbasetypes)
{
typesdict[b] = b;
}
}
// types = []
// for tkey in typesdict:
// finaltype = replace_back(typesdict[tkey], typesdict)
// t = TypeInfo(tkey, typesdict[tkey], finaltype)
// types.append(t)
// print t
//std::cout << "---------- TYPES -------" << std::endl;
std::vector<TypeInfo::Ptr> types;
std::vector<std::string> tokens;
for (auto t : typesdict)
{
//auto t = *it;
auto &tkey = t.first;
auto &tval = t.second;
auto finaltype = replace_back(tval, typesdict);
auto tinfo = std::make_shared<TypeInfo>(tkey, tval, finaltype);
types.push_back(tinfo);
tokens.push_back(tkey);
//std::cout << "replacing back: " << finaltype << std::endl;
}
TypeInfo::Ptr roottype = nullptr;
for (auto &t : types)
{
if (t->finaltype == originalinputtext)
{
roottype = t;
break;
}
}
// std::sort(types.begin(), types.end(),[](auto& a, auto& b)
// {
// return a->getFullName().size() > b->getFullName().size();
// });
/*
std::cout<<"types order:" << std::endl;
for(auto t: types)
{
std::cout<< t->codedtype << std::endl;
}
std::cout<<"---------" << std::endl;
std::cout<<"types order:" << std::endl;
for(auto t: types)
{
std::cout<< t->finaltype << std::endl;
}
std::cout<<"---------" << std::endl;
*/
for (int i=0; i< types.size();i++)
{
auto t= types[i];
auto ttoken = tokens[i];
//auto t = types[it1];
std::vector<std::pair<int, TypeInfo::Ptr>> unorderedTemplateParameters;
//std::cout << "original typestr: " << codedtypecopy << std::endl;
//auto codedtypecopy = t->codedtype;
auto codedtypecopy = typesdict_content[ttoken];
// std::cout << "original typestr: " << codedtypecopy << std::endl;
// std::cout << "original token: " << ttoken << std::endl;
// std::cout << "original typestr: " << typesdict_content[ttoken] << std::endl;
// size_t startindex = codedtypecopy.find("<");
// size_t endindex = codedtypecopy.find(">");
// if (startindex != std::string::npos)
// {
// codedtypecopy = codedtypecopy.substr(startindex + 1, endindex - startindex - 1);
// }
//std::cout << "original typestr: " << codedtypecopy << std::endl;
for (auto &t2 : types)
//for (auto it2= types.size() -1; it2 >=0; it2--)
{
//std::cout << it2 << std::endl;
//auto t2 = types[it2];
//std::cout << t2->getFullName() << std::endl;
if (t == t2)
continue;
auto index = codedtypecopy.find(t2->tkey);
if (index != std::string::npos)
{
//auto pair = std::make_pair(index, t2);
auto pair = std::make_pair(0, t2);
//std::cout << "matches: " << t2->tkey <<std::endl;
unorderedTemplateParameters.push_back(pair);
replace(codedtypecopy,t2->tkey,""); // consume token
//std::cout << "codedtypecopy: " << codedtypecopy << std::endl;
}
}
std::sort(unorderedTemplateParameters.begin(), unorderedTemplateParameters.end(),
[](auto &a, auto &b) -> bool {
return a.first <= b.first;
});
ROS_DEBUG_STREAM("------------------");
ROS_DEBUG_STREAM("CREATING TYPE:" << t->getFullName());
for (auto &item : unorderedTemplateParameters)
{
ROS_DEBUG_STREAM(" - template paramter: " << item.second->getFullName());
t->templateParameters.push_back(item.second);
}
ROS_DEBUG_STREAM("------------------");
}
ROS_DEBUG_STREAM("ADDING TYPE TO DATABASE: " << inputtext);
ROS_DEBUG_STREAM("Current Database");
for (auto &en : typeInfoDatabase)
{
ROS_DEBUG_STREAM("- " << en.first);
}
typeInfoDatabase[originalinputtext] = roottype;
return roottype;
}
/*
print (typesdict)
roottype = [t for t in types if t.finaltype == originalinputtext][0]
print "---------------------------------"
# fill template parameters
for t in types:
for t2 in types:
if t2.tkey in t.codedtype:
index = t.codedtype.index(t2.tkey)
t.template_parameters.append((index, t2))
t.template_parameters = [x[1] for x in sorted(
t.template_parameters, key=lambda e: e[0])]
return roottype
}
*/
} // namespace introspection
} // namespace smacc | [
"pibgeus@gmail.com"
] | pibgeus@gmail.com |
d6de086d9552c12ad172ddab6c75d9b83370b76c | 17c6289537851347c691c46570efe98a47f57169 | /src/ComplexField/Yfunc_Field_3D.cpp | 371b4e491ffbfe8c26e5ef37c9f9f23ab0811ce4 | [] | no_license | miiya369/analysisHAL_miya | 67516fb7192ce7c3d0a0c5bace3f3e1b4c850d26 | 76a6d80bb4a7f24c0deeca770f60efd440b72f3c | refs/heads/master | 2020-03-09T09:17:51.926630 | 2018-10-04T10:44:45 | 2018-10-04T10:44:45 | 99,018,105 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,735 | cpp | //--------------------------------------------------------------------------
/**
* @file
* @ingroup ComplexField
* @brief The spherical harmonics as field in 3-dimension space
* @author Takaya Miyamoto
* @since Thu Sep 15 00:10:27 JST 2016
*/
//--------------------------------------------------------------------------
#include <ComplexField_Sub.h>
ComplexField_XYZ sfunc::cfield_Ylm(const int L, const int M, const int Lsize) {
DEBUG_LOG
typedef cdouble (*Y_FUNC)(const int, const int, const int);
Y_FUNC Ylm;
switch (L) {
case 0:
switch (M) {
case 0: Ylm = Y_0_0; break;
default: ERROR_COMMENTS("Unknown z-component of angular momentum.");
}; break;
case 1:
switch (M) {
case -1: Ylm = Y_1_m1; break;
case 0: Ylm = Y_1_0 ; break;
case +1: Ylm = Y_1_p1; break;
default: ERROR_COMMENTS("Unknown z-component of angular momentum.");
}; break;
case 2:
switch (M) {
case -2: Ylm = Y_2_m2; break;
case -1: Ylm = Y_2_m1; break;
case 0: Ylm = Y_2_0 ; break;
case +1: Ylm = Y_2_p1; break;
case +2: Ylm = Y_2_p2; break;
default: ERROR_COMMENTS("Unknown z-component of angular momentum.");
}; break;
case 3:
switch (M) {
case -3: Ylm = Y_3_m3; break;
case -2: Ylm = Y_3_m2; break;
case -1: Ylm = Y_3_m1; break;
case 0: Ylm = Y_3_0 ; break;
case +1: Ylm = Y_3_p1; break;
case +2: Ylm = Y_3_p2; break;
case +3: Ylm = Y_3_p3; break;
default: ERROR_COMMENTS("Unknown z-component of angular momentum.");
}; break;
case 4:
switch (M) {
case -4: Ylm = Y_4_m4; break;
case -3: Ylm = Y_4_m3; break;
case -2: Ylm = Y_4_m2; break;
case -1: Ylm = Y_4_m1; break;
case 0: Ylm = Y_4_0 ; break;
case +1: Ylm = Y_4_p1; break;
case +2: Ylm = Y_4_p2; break;
case +3: Ylm = Y_4_p3; break;
case +4: Ylm = Y_4_p4; break;
default: ERROR_COMMENTS("Unknown z-component of angular momentum.");
}; break;
default:
ERROR_COMMENTS("Unknown angular momentum.");
}
ComplexField_XYZ ret(Lsize);
int XYZ[3], XYZsize[3] = {Lsize, Lsize, Lsize};
for ( int x=0; x<Lsize; x++)
for ( int y=0; y<Lsize; y++)
for (int z=0; z<Lsize; z++) {
int xyz[3] = {x,y,z};
anaHAL::convert_origin(xyz, XYZ, XYZsize, 3);
ret(x,y,z) = (*Ylm)(XYZ[0], XYZ[1], XYZ[2]);
}
return ret;
}
| [
"miiya369@gmail.com"
] | miiya369@gmail.com |
e0523dcfc73008a5c4a886bbd8661a87b7194cff | 5de0142acff63cadb9289dbc19956759de8c59a4 | /src/pbrt/test/testmarschner.cpp | 922d77d685494b37f85bdd64647ce496e62d68db | [] | no_license | jlemein/hair-rendering-thesis | 013a8e40fe3e79e8a68ef0b6e8ecdfd25307d278 | 9a7205d0c3b52c61eb82a88abc29b86d3d48a4d6 | refs/heads/master | 2022-11-24T09:34:21.305011 | 2020-07-28T11:49:30 | 2020-07-28T11:49:30 | 127,464,317 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,077 | cpp |
#include "tests/gtest/gtest.h"
#include "pbrt.h"
#include "sampler.h"
#include "materials/marschner.cpp"
#include <atomic>
#include <vector>
using namespace pbrt;
class DepressedCubic {
public:
Float a, b, c;
DepressedCubic(Float a, Float b, Float c) : a(a), b(b), c(c) {
}
Float operator()(Float x) {
return a * x * x * x + b * x + c;
}
};
// Set up sample phis for testing
static const int SAMPLE_SIZE = 100;
static Float EvaluateCubic(Float a, Float b, Float c, Float x) {
return a * x * x * x + b * x + c;
}
/**
This test assures that when we wrap gamma around its boundaries, that
the root h = sin(gamma) still holds.
**/
TEST(Marschner, RangeBoundGammaInversed) {
for (Float gammaI = -Pi; gammaI < Pi; gammaI += 0.01) {
EXPECT_NEAR(sin(gammaI), sin(RangeBoundGammaInversed(gammaI)), 1e-5);
}
}
TEST(Marschner, EtaEccentricityIdentity) {
EXPECT_FLOAT_EQ(1.55, EtaEccentricity(1.0, 1.55, 0.0));
EXPECT_FLOAT_EQ(1.55, EtaEccentricity(1.0, 1.55, -.5 * Pi));
EXPECT_FLOAT_EQ(1.55, EtaEccentricity(1.0, 1.55, .5 * Pi));
}
TEST(Marschner, EtaEccentricity) {
EXPECT_GT(EtaEccentricity(0.9, 1.55, 0.0), 1.0);
EXPECT_GT(EtaEccentricity(0.9, 1.55, -.5 * Pi), 1.0);
EXPECT_GT(EtaEccentricity(0.9, 1.55, .5 * Pi), 1.0);
}
//
//TEST(Marschner, RangeBoundGamma) {
// EXPECT_FLOAT_EQ(.5 * Pi - 0.1, RangeBoundGamma(.5 * Pi - 0.1));
// EXPECT_FLOAT_EQ(.5 * Pi - 0.1, RangeBoundGamma(.5 * Pi + 0.1));
// EXPECT_FLOAT_EQ(.5 * Pi - 0.1, RangeBoundGamma(-1.5 * Pi - 0.1));
// EXPECT_FLOAT_EQ(.5 * Pi - 0.1, RangeBoundGamma(-1.5 * Pi + 0.1));
//
// EXPECT_FLOAT_EQ(-.5 * Pi + 0.1, RangeBoundGamma(-.5 * Pi - 0.1));
// EXPECT_FLOAT_EQ(-.5 * Pi + 0.1, RangeBoundGamma(-.5 * Pi + 0.1));
// EXPECT_FLOAT_EQ(-.5 * Pi + 0.1, RangeBoundGamma(1.5 * Pi + 0.1));
// EXPECT_FLOAT_EQ(-.5 * Pi + 0.1, RangeBoundGamma(1.5 * Pi - 0.1));
//
// EXPECT_FLOAT_EQ(-.5 * Pi + 0.1, RangeBoundGamma(-.5 * Pi - 0.1));
// EXPECT_FLOAT_EQ(-.5 * Pi + 0.1, RangeBoundGamma(-.5 * Pi + 0.1));
//
//
// EXPECT_FLOAT_EQ(.0, RangeBoundGamma(Pi));
// EXPECT_FLOAT_EQ(.0, RangeBoundGamma(2.0 * Pi));
// EXPECT_FLOAT_EQ(.0, RangeBoundGamma(-2.0 * Pi));
//
// // testing with near, because of precision errors
// EXPECT_NEAR(.0, RangeBoundGamma(3.0 * Pi), 1e-3);
// EXPECT_NEAR(.0, RangeBoundGamma(-3.0 * Pi), 1e-3);
// EXPECT_NEAR(.0, RangeBoundGamma(4.0 * Pi), 1e-3);
// EXPECT_NEAR(.0, RangeBoundGamma(-4.0 * Pi), 1e-3);
//}
//
TEST(Marschner, SolveRoot) {
Float a = 16.0;
Float b = 0.0;
Float c = -6.0;
Float d = -9.0;
// ax^3 + bx^2 -c = d
Float root;
int nRoots = SolveDepressedCubic(a, c, d, &root);
EXPECT_EQ(1, nRoots);
EXPECT_NEAR(0.0, EvaluateCubic(a, c, d, root), 1e-5);
}
//
//TEST(Marschner, SolveRootsForTT) {
// Float eta = 1.55;
// const Float C = asin(1.0 / eta);
//
// for (int i = 0; i < SAMPLE_SIZE; ++i) {
// Float phi = -Pi + (i / (Float) SAMPLE_SIZE) * 2.0 * Pi;
//
// // make sure that phi stays between [-Pi, Pi] due to floating point
// // precision errors
// phi = Clamp(phi, -Pi, Pi);
//
// // depressed cubic equation: ax^3 + cx + d = 0
// Float a = -8.0 * C / (Pi * Pi * Pi);
// Float c = 6.0 * C / Pi - 2.0;
// Float d = Pi - phi;
//
// Float root;
// int nRoots = SolveDepressedCubic(a, c, d, &root);
//
// // always expect 1 root for TT scattering components
// EXPECT_EQ(1, nRoots);
//
// // result should always be 0, we check here for smaller than 1e-5
// Float result = EvaluateCubic(a, c, d, root);
// EXPECT_NEAR(fabs(result), 0.0, 1e-4);
// }
//}
//
//TEST(Marschner, SolveRootsForTT2) {
// Float eta = 1.55;
//
// for (int i = 0; i < SAMPLE_SIZE; ++i) {
// Float phi = -Pi + (i / (Float) SAMPLE_SIZE) * 2.0 * Pi;
// Float gammaI = SolveGammaRoot_TT(phi, eta);
//
// // always expect 1 root for TT scattering components
// EXPECT_LE(gammaI, .5 * Pi);
// EXPECT_GE(gammaI, -.5 * Pi);
//
// // transforming the root should roughly be equal to the phi for which
// // we found the root.
//
// //EXPECT_NEAR(phi, ClampPhi(Phi(1, gammaI, GammaT(gammaI, eta))), 1e-5);
// }
//}
//
//TEST(Marschner, SolveEquationWithThreeRoots) {
//
// Float a = 1.0;
// Float c = -15.0;
// Float d = -4.0;
// DepressedCubic fn(a, c, d);
//
// // ax^3 + bx^2 -c = d
// Float roots[3];
// int nRoots = SolveDepressedCubic(a, c, d, roots);
// EXPECT_EQ(3, nRoots);
//
// EXPECT_NEAR(fabs(fn(roots[0])), .0, 1e-4);
// EXPECT_NEAR(fabs(fn(roots[1])), .0, 1e-4);
// EXPECT_NEAR(fabs(fn(roots[2])), .0, 1e-4);
//}
//
//TEST(Marschner, SolveRootsForTRT) {
// //Float eta = 1.55;
// //const Float C = asin(1.0 / eta);
// //const Float a = -8.0 * 2.0 * C / (Pi * Pi * Pi);
// //const Float c = 6.0 * 2.0 * C / Pi - 2.0;
//
// const Float a = -0.352144;
// const Float c = 0.606644;
// // const Float d = 0.024114;
//
// // walk around cylinder for incoming phi values
// for (Float phi = -Pi; phi <= Pi; phi += 0.01) {
//
// // make sure that phi stays between [-Pi, Pi] due to floating point
// // precision errors
// phi = Clamp(phi, -Pi, Pi);
//
// // depressed cubic equation: ax^3 + cx + d = 0
// Float d = 2.0 * Pi - phi;
//
// Float roots[3];
// int nRoots = SolveDepressedCubic(a, c, d, roots);
//
// printf("roots: %d\n", nRoots);
// if (nRoots == 3) {
// printf("phi = %f\n", phi);
// printf("roots: %f -- %f -- %f\n\n", roots[0], roots[1], roots[2]);
// }
//
// // TRT could result in one or three roots
// EXPECT_TRUE(nRoots == 1 || nRoots == 3);
//
// for (int i = 0; i < nRoots; ++i) {
// // expect evaluation of function to be zero
//
// EXPECT_LT(fabs(EvaluateCubic(a, c, d, roots[i])), 1e-3);
// }
// }
//}
TEST(Marschner, SolveThreeRootsForTRT) {
const Float a = -0.352144;
const Float c = 0.606644;
const Float d = 0.024114;
Float roots[3];
int nRoots = SolveDepressedCubic(a, c, d, roots);
printf("roots: %d\n", nRoots);
if (nRoots == 3) {
//printf("phi = %f\n", phi);
printf("roots: %f -- %f -- %f\n\n", roots[0], roots[1], roots[2]);
}
// TRT could result in one or three roots
EXPECT_TRUE(nRoots == 3);
for (int i = 0; i < nRoots; ++i) {
// expect evaluation of function to be zero
EXPECT_LT(fabs(EvaluateCubic(a, c, d, roots[i])), 1e-3);
}
}
TEST(Marschner, SolveThreeOutOfBoundsRootsForTRT) {
const Float etaPerp = 1.550605;
const Float phi = 0.346892;
const Float a = -0.361684;
const Float c = 0.677259;
const Float d = -phi;
Float roots[3];
int nRoots = SolveDepressedCubic(a, c, d, roots);
printf("roots: %d\n", nRoots);
if (nRoots == 3) {
//printf("phi = %f\n", phi);
printf("roots: %f -- %f -- %f\n\n", roots[0], roots[1], roots[2]);
}
// TRT could result in one or three roots
//EXPECT_TRUE(nRoots == 3);
for (int i = 0; i < nRoots; ++i) {
EXPECT_LT(fabs(EvaluateCubic(a, c, d, roots[i])), 1e-3);
EXPECT_NEAR(PhiApprox(2, roots[i], etaPerp), phi, 1e-5);
}
}
//
//TEST(Marschner, SolveRootsForTRT_LowEta) {
// Float eta = 2.5;
// const Float C = asin(1.0 / eta);
// const Float a = -8.0 * 2.0 * C / (Pi * Pi * Pi);
// const Float c = 6.0 * 2.0 * C / Pi - 2.0;
//
// // walk around cylinder for incoming phi values
// for (Float phi = -Pi; phi <= Pi; phi += 0.2 * Pi) {
//
// // make sure that phi stays between [-Pi, Pi] due to floating point
// // precision errors
// phi = Clamp(phi, -Pi, Pi);
//
// // depressed cubic equation: ax^3 + cx + d = 0
// Float d = 2.0 * Pi - phi;
//
// Float roots[3];
// int nRoots = SolveDepressedCubic(a, c, d, roots);
//
// // TRT could result in one or three roots
// EXPECT_TRUE(nRoots == 1 || nRoots == 3);
//
// for (int i = 0; i < nRoots; ++i) {
// // expect evaluation of function to be zero
//
// EXPECT_LT(fabs(EvaluateCubic(a, c, d, roots[i])), 1e-4);
// }
// }
//}
//
//TEST(Marschner, Fresnel) {
// Float etaPerp = 1.55;
// Float etaPar = 1.55;
//
// for (Float gammaI = -0.5 * Pi; gammaI <= 0.5 * Pi; gammaI += 0.01 * Pi) {
//
// Float frDielectric = FrDielectric(cos(gammaI), 1.0, 1.55);
// Float fresnel = Fresnel(etaPerp, etaPar, gammaI);
//
// EXPECT_FLOAT_EQ(frDielectric, fresnel);
// }
//}
//
//// TODO:
//// * test if dphidh(0, gamma, etaPerp) equals dphidh_r
//// * test if dphi comes close to gradient and is always above 0
//// * check if gammaRoots equals gammaRoots_TT for p = 1
//// * check solutions for caustics and see if in between is the switch for 1 solution vs 3 solutions
//
//TEST(Marschner, RelativeAzimuth) {
//
// // test all variants where difference is 0 degrees
// EXPECT_FLOAT_EQ(0.0, RelativeAzimuth(-2.0 * Pi, -2.0 * Pi));
// EXPECT_FLOAT_EQ(0.0, RelativeAzimuth(-2.0 * Pi, 2.0 * Pi));
// EXPECT_FLOAT_EQ(0.0, RelativeAzimuth(-2.0 * Pi, 0.0));
//
// EXPECT_FLOAT_EQ(0.0, RelativeAzimuth(2.0 * Pi, -2.0 * Pi));
// EXPECT_FLOAT_EQ(0.0, RelativeAzimuth(2.0 * Pi, 2.0 * Pi));
// EXPECT_FLOAT_EQ(0.0, RelativeAzimuth(2.0 * Pi, 0.0));
//
// EXPECT_FLOAT_EQ(0.0, RelativeAzimuth(0.0, 0.0));
// EXPECT_FLOAT_EQ(0.0, RelativeAzimuth(0.0, 2.0 * Pi));
// EXPECT_FLOAT_EQ(0.0, RelativeAzimuth(0.0, -2.0 * Pi));
//
// // test difference of 180 degrees (-pi)
// EXPECT_FLOAT_EQ(-0.99 * Pi, RelativeAzimuth(0.0, -0.99 * Pi));
// EXPECT_FLOAT_EQ(0.99 * Pi, RelativeAzimuth(0.0, 0.99 * Pi));
// EXPECT_FLOAT_EQ(Pi, fabs(RelativeAzimuth(0.0, -Pi)));
// EXPECT_FLOAT_EQ(Pi, fabs(RelativeAzimuth(0.0, Pi)));
//
// EXPECT_FLOAT_EQ(0.99 * Pi, RelativeAzimuth(-0.99 * Pi, 0.0));
// EXPECT_FLOAT_EQ(-0.99 * Pi, RelativeAzimuth(0.99 * Pi, 0.0));
// EXPECT_FLOAT_EQ(Pi, fabs(RelativeAzimuth(-Pi, 0.0)));
// EXPECT_FLOAT_EQ(Pi, fabs(RelativeAzimuth(Pi, 0.0)));
//
// // test difference of 90 degrees (pi/2)
// EXPECT_FLOAT_EQ(.5 * Pi, RelativeAzimuth(.0, .5 * Pi));
// EXPECT_FLOAT_EQ(.5 * Pi, RelativeAzimuth(2 * Pi, .5 * Pi));
// EXPECT_FLOAT_EQ(.5 * Pi, RelativeAzimuth(-2 * Pi, .5 * Pi));
//
// EXPECT_FLOAT_EQ(-.5 * Pi, RelativeAzimuth(.0, -.5 * Pi));
// EXPECT_FLOAT_EQ(-.5 * Pi, RelativeAzimuth(2 * Pi, -.5 * Pi));
// EXPECT_FLOAT_EQ(-.5 * Pi, RelativeAzimuth(-2 * Pi, -.5 * Pi));
//
// EXPECT_FLOAT_EQ(-.5 * Pi, RelativeAzimuth(.5 * Pi, .0));
// EXPECT_FLOAT_EQ(-.5 * Pi, RelativeAzimuth(.5 * Pi, 2 * Pi));
// EXPECT_FLOAT_EQ(-.5 * Pi, RelativeAzimuth(.5 * Pi, -2 * Pi));
//
// EXPECT_FLOAT_EQ(.5 * Pi, RelativeAzimuth(-.5 * Pi, 0.0));
// EXPECT_FLOAT_EQ(.5 * Pi, RelativeAzimuth(-.5 * Pi, 2 * Pi));
// EXPECT_FLOAT_EQ(.5 * Pi, RelativeAzimuth(-.5 * Pi, -2 * Pi));
//
// // test wrapping around (tests are failing because Pi is not precise enough
// // but this is no problem for us, since wrapping does not occur)
// // EXPECT_FLOAT_EQ(0.0, RelativeAzimuth(-2.0 * Pi, 4.0 * Pi));
// // EXPECT_FLOAT_EQ(0.0, RelativeAzimuth(4.0 * Pi, -2.0 * Pi));
// // EXPECT_FLOAT_EQ(Pi, fabs(RelativeAzimuth(-Pi, 4.0 * Pi)));
// // EXPECT_FLOAT_EQ(Pi, fabs(RelativeAzimuth(4.0 * Pi, -Pi)));
//}
static double _integrateMonteCarloFront(const Vector3f& wi, std::function<double(const Vector3f&, const Vector3f&) > f, int nSamples) {
std::default_random_engine generator;
std::uniform_real_distribution<double> distribution(0.0, 1.0);
double V = 2.0 * Pi;
double sum = .0;
for (int i = 0; i < nSamples; ++i) {
//Vector3f wi = Vector3f(-1.0, 0.0, 0.0);
Vector3f wr = SampleFrontHemisphere(Point2f(distribution(generator), distribution(generator)));
sum += f(wr, wi);
}
return V / static_cast<double> (nSamples) * sum;
}
static double _integrateMonteCarloBack(const Vector3f& wi, std::function<double(const Vector3f&, const Vector3f&) > f, int nSamples) {
std::default_random_engine generator;
std::uniform_real_distribution<double> distribution(0.0, 1.0);
double V = 2.0 * Pi;
double sum = .0;
for (int i = 0; i < nSamples; ++i) {
//Vector3f wi = Vector3f(-1.0, 0.0, 0.0);
Vector3f wr = SampleBackHemisphere(Point2f(distribution(generator), distribution(generator)));
sum += f(wr, wi);
}
return V / static_cast<double> (nSamples) * sum;
}
static Vector3f UniformSampleSphere(const Point2f &u) {
Float z = 1 - 2 * u[0];
Float r = std::sqrt(std::max((Float) 0, (Float) 1 - z * z));
Float phi = 2 * Pi * u[1];
return Vector3f(r * std::cos(phi), r * std::sin(phi), z);
}
static double _integrateMonteCarlo(const Vector3f& wi, std::function<double(const Vector3f&, const Vector3f&) > f, int nSamples) {
std::default_random_engine generator;
std::uniform_real_distribution<double> distribution(0.0, 1.0);
double V = 4.0 * Pi;
double sum = .0;
for (int i = 0; i < nSamples; ++i) {
//Vector3f wi = Vector3f(-1.0, 0.0, 0.0);
Vector3f wr = UniformSampleSphere(Point2f(distribution(generator), distribution(generator)));
sum += f(wr, wi);
}
return V / static_cast<double> (nSamples) * sum;
}
static double _integrateMonteCarlo(std::function<double(const Float) > f, int nSamples) {
std::default_random_engine generator;
std::uniform_real_distribution<double> distribution(.0, 1.0);
double V = Pi;
double sum = .0;
for (int i = 0; i < nSamples; ++i) {
//Vector3f wi = Vector3f(-1.0, 0.0, 0.0);
Float x = -.5 * Pi + distribution(generator) * Pi;
sum += f(x);
}
return V / static_cast<double> (nSamples) * sum;
}
//alphaR: 0.0523599 alphaTT: -0.0261799 alphaTRT: -0.0785398 betaR: 0.244346 betaTT: 0.139626 betaTRT: 0.383972
//causticFadeRange: 0.3 causticIntensityLimit: 0.5 causticWidth: 0.174533
//eccentricity: 0.9 eta: 1.55 glintScaleFactor: 0.4 hairRadius: 1
//sigmaA: 0.432, 0.612, 0.98
const Float eta = 1.55;
const Float eccentricity = 0.9;
const Vector3f alpha = Vector3f(0.0523599, -0.0261799, -0.0785398);
const Vector3f alphaSquared = Vector3f(alpha.x*alpha.x, alpha.y*alpha.y, alpha.z*alpha.z);
const Vector3f alphaSqrt = Vector3f(sqrt(alpha.x), sqrt(alpha.y), sqrt(alpha.z));
const Vector3f beta = Vector3f(0.244346, 0.139626, 0.383972);
const Vector3f betaSquared = Vector3f(beta.x*beta.x, beta.y*beta.y, beta.z*beta.z);
const Vector3f betaSqrt = Vector3f(sqrt(beta.x), sqrt(beta.y), sqrt(beta.z));
const Float glintScale = 0.4;
const Float causticWidth = 0.174533;
const Float causticFade = 0.3;
const Float causticIntensityLimit = 0.5;
const Float hairRadius = 1.0;
const Float sigmaARgb[3] = {.0, .0, .0};
const Spectrum sigmaA = Spectrum::FromRGB(sigmaARgb);
const SurfaceInteraction si = SurfaceInteraction();
MarschnerBSDF* marschner = new MarschnerBSDF(si, alpha[0], alpha[1], alpha[2], beta[0], beta[1], beta[2], hairRadius, eta, sigmaA, eccentricity, glintScale, causticWidth, causticFade, causticIntensityLimit);
MarschnerBSDF* marschnerSquared = new MarschnerBSDF(si, alphaSquared[0], alphaSquared[1], alphaSquared[2], betaSquared[0], betaSquared[1], betaSquared[2], hairRadius, eta, sigmaA, eccentricity, glintScale, causticWidth, causticFade, causticIntensityLimit);
MarschnerBSDF* marschnerSqrt = new MarschnerBSDF(si, alphaSqrt[0], alphaSqrt[1], alphaSqrt[2], betaSqrt[0], betaSqrt[1], betaSqrt[2], hairRadius, eta, sigmaA, eccentricity, glintScale, causticWidth, causticFade, causticIntensityLimit);
TEST(Marschner, BsdfShouldBeEnergyConservant) {
MyRandomSampler sampler(0.0, 1.0);
auto fn = [&](const Vector3f wr, const Vector3f wi){
Float cosAngle = Dot(wr, wi);
return marschner->f(wr, wi).y(); // * fabs(cosAngle);
};
auto fnSquared = [&](const Vector3f wr, const Vector3f wi){
Float cosAngle = Dot(wr, wi);
return marschnerSquared->f(wr, wi).y() * fabs(cosAngle);
};
auto fnSqrt = [&](const Vector3f wr, const Vector3f wi){
Float cosAngle = Dot(wr, wi);
return marschnerSqrt->f(wr, wi).y() * fabs(cosAngle);
};
auto fnSphereSurface = [&](const Vector3f wr, const Vector3f wi){
return 1.0;
};
Vector3f wii = SampleBackHemisphere(0.0, sampler.next());
Float sphere = _integrateMonteCarlo(wii, fn, 10000);
printf("integrated BSDF energy: %f\n", sphere);
EXPECT_LE(sphere, 1.2);
EXPECT_GE(sphere, .8);
}
TEST(Marschner, NormalizedGaussianSumsToOne) {
MyRandomSampler sampler(0.0, 1.0);
auto fn = [&](const Float thetaH){
return Gaussian(beta.x, thetaH);
};
Float area = _integrateMonteCarlo(fn, 10000);
printf("area under normalized gaussian graph: %f\n", area);
EXPECT_NEAR(1.0, area, 0.03);
}
| [
"jeffrey.lemein@gmail.com"
] | jeffrey.lemein@gmail.com |
c760764347ff93500d55e909dda0a37b093ff5d5 | 0429c52bbf4a5b9bafd502e720461b19e692cc91 | /AssignmentTwo/Classes/GT/Actions/GTFollowNodeAction.h | 5ed14e2a178e81e5a4fb52c0643845cb22ea32ae | [] | no_license | sekheng/ProgGameEngine | 5d51185a0a85d9e9cfd16cf889f5e54863f6ece4 | 31f01dce49476e37f43bab858ade8d16a1e4aae0 | refs/heads/master | 2021-09-06T21:46:48.043273 | 2018-02-12T01:46:24 | 2018-02-12T01:46:24 | 107,355,216 | 0 | 0 | null | 2018-02-11T15:10:28 | 2017-10-18T03:37:10 | C++ | UTF-8 | C++ | false | false | 2,423 | h | #ifndef GT_FOLLOWSPRITE_H
#define GT_FOLLOWSPRITE_H
// Include Cocos
#include "cocos2d.h"
// Include GT
#include "../../GT/Common/GTMacros.h"
// Include MK
#include "../../MK/Common/MKMathsHelper.h"
// Include STL
#include <cmath>
NS_GT_BEGIN
class GTFollowNodeAction : public cocos2d::ActionInterval
{
typedef cocos2d::ActionInterval Super;
public:
enum FollowAxis
{
X,
Y,
ALL,
};
protected:
FollowAxis m_FollowAxis = FollowAxis::ALL;
cocos2d::Node* m_FollowedNode = nullptr;
cocos2d::Vec2 m_Offset;
public:
static GTFollowNodeAction* Create(gtF32 _duration, cocos2d::Node* _followedNode, FollowAxis _followAxis, const cocos2d::Vec2& _offset = cocos2d::Vec2::ZERO)
{
GTFollowNodeAction* newAction = new (std::nothrow) GTFollowNodeAction();
if (newAction && newAction->initWithDuration(_duration, _followedNode, _followAxis, _offset))
{
newAction->autorelease();
return newAction;
}
CC_SAFE_DELETE(newAction);
return nullptr;
}
virtual void update(float _percentageComplete)
{
Super::update(_percentageComplete);
if (_target == nullptr || m_FollowedNode == nullptr) { return; }
cocos2d::Vec2 followNodePosition = m_FollowedNode->getPosition();
cocos2d::Vec2 targetNodePosition = _target->getPosition();
switch (m_FollowAxis)
{
case GinTama::GTFollowNodeAction::X:
_target->setPosition(cocos2d::Vec2(followNodePosition.x, targetNodePosition.y) + m_Offset);
break;
case GinTama::GTFollowNodeAction::Y:
_target->setPosition(cocos2d::Vec2(targetNodePosition.x, followNodePosition.y) + m_Offset);
break;
case GinTama::GTFollowNodeAction::ALL:
_target->setPosition(followNodePosition + m_Offset);
break;
default:
CC_ASSERT(0);
break;
}
}
CC_CONSTRUCTOR_ACCESS:
GTFollowNodeAction() {}
virtual ~GTFollowNodeAction() {}
gtBool initWithDuration(gtF32 _duration, cocos2d::Node* _followedNode, FollowAxis _followAxis, const cocos2d::Vec2& _offset)
{
if (!Super::initWithDuration(_duration)) { return false; }
m_FollowedNode = _followedNode;
m_Offset = _offset;
m_FollowAxis = _followAxis;
return true;
}
};
NS_GT_END
#endif | [
"lnxterry@gmail.com"
] | lnxterry@gmail.com |
ba5d61b09b57c9adb9f3d8d60e10b35a89c82cfb | c05bc1c96979107eeb1d1463a7fc01b5144452c8 | /SRT/Servers/SRTMinorServo/include/DerotatorImpl.h | 09620e99a274863c83394de3cc614e3bb3febb59 | [] | no_license | discos/discos | 1587604ae737d8301f10011d21bfa012dd3c411f | 87dc57a160f3b122af46a9927ee6abb62fdf4159 | refs/heads/master | 2023-08-30T21:39:55.339786 | 2023-06-21T13:39:20 | 2023-06-21T13:39:20 | 87,530,078 | 4 | 4 | null | 2023-09-07T07:57:43 | 2017-04-07T09:37:08 | C++ | UTF-8 | C++ | false | false | 4,634 | h | /*******************************************************************************\
* Author Infos
* ============
* Name: Marco Buttu
* E-mail: mbuttu@oa-cagliari.inaf.it
* Personal Web: http://www.pypeople.com/
\*******************************************************************************/
#ifndef __DEROTATORIMPL__H
#define __DEROTATORIMPL__H
#ifndef __cplusplus
#error This is a C++ include file and cannot be used from plain C
#endif
#include <baciCharacteristicComponentImpl.h>
#include <baciSmartPropertyPointer.h>
#include <baciRWdouble.h>
#include <baciROdouble.h>
#include <baciROlong.h>
#include <baciROpattern.h>
#include <baciROuLongLong.h>
#include <acsncSimpleSupplier.h>
#include <enumpropROImpl.h>
#include <ComponentErrors.h>
#include <LogFilter.h>
#include "sensorSocket.h"
#include "icdSocket.h"
#include <MinorServoS.h>
using namespace baci;
class DerotatorImpl: public CharacteristicComponentImpl, public virtual POA_MinorServo::Derotator {
public:
DerotatorImpl(const ACE_CString &CompName,maci::ContainerServices *containerServices);
virtual ~DerotatorImpl();
/**
* Get the parameter from CDB and create a sensorSocket and a CSecureArea.
* Initialize the socket calling its Init method.
*
* @throw ComponentErrors::CDBAccessExImpl
* @throw ACSErr::ACSbaseExImpl
*/
virtual void initialize() throw (ComponentErrors::CDBAccessExImpl, ACSErr::ACSbaseExImpl);
/**
* @throw ACSErr::ACSbaseExImpl
*/
virtual void execute() throw (ACSErr::ACSbaseExImpl);
/**
* Called by the container before destroying the server in a normal situation.
* This function takes charge of releasing all resources.
*/
virtual void cleanUp();
/**
* Called by the container in case of error or emergency situation.
* This function tries to free all resources even though there is no warranty that the function
* is completely executed before the component is destroyed.
*/
virtual void aboutToAbort();
/**
* Return a reference to the sensor postition property implementation of IDL interface.
*
* @return pointer to read-only double property position
* @throw CORBA::SystemException
*/
virtual ACS::ROdouble_ptr sensor_position() throw (CORBA::SystemException);
/**
* Return a reference to the icd position property (physical position)implementation
* of IDL interface.
*
* @return pointer to read-write double property position
* @throw CORBA::SystemException
*/
virtual ACS::RWdouble_ptr icd_position() throw (CORBA::SystemException);
/**
* Return a reference to the ICD verbose status property implementation of IDL interface.
*
* @return pointer to read-only pattern property verbose status
* @throw CORBA::SystemException
*/
virtual ACS::ROpattern_ptr icd_verbose_status() throw (CORBA::SystemException);
/**
* Return a reference to the ICD summary status property implementation of IDL interface.
*
* @return pointer to read-only pattern property summary status
* @throw CORBA::SystemException
*/
virtual ACS::ROpattern_ptr icd_summary_status() throw (CORBA::SystemException);
/**
* Return the ICD target position (double) in the user's reference system
*
* @return ICD target position (double) in the user's reference system
* @throw CORBA::SystemException
*/
void getIcdTargetPosition(CORBA::Double_out target_position) ;
/**
* Return the ICD position (double) in the user's reference system
*
* @return ICD position (double) in the user's reference system
* @throw CORBA::SystemException
*/
void getIcdURSPosition(CORBA::Double_out icd_urs_position) ;
/**
* Return the sensor position (double) in the user's reference system
*
* @return sensor position (double) in the user's reference system
* @throw CORBA::SystemException
*/
void getSensorURSPosition(CORBA::Double_out sensor_urs_position) ;
private:
CSecureArea<sensorSocket> *m_sensorLink;
CSecureArea<icdSocket> *m_icdLink;
// Sensor position property
SmartPropertyPointer<ROdouble> m_sensor_position;
// ICD position property
SmartPropertyPointer<RWdouble> m_icd_position;
// ICD Verbose Status
SmartPropertyPointer<ROpattern> m_icd_verbose_status;
//
// ICD Summary Status
SmartPropertyPointer<ROpattern> m_icd_summary_status;
void operator=(const DerotatorImpl&);
};
#endif
| [
"mbuttu@oa-cagliari.inaf.it"
] | mbuttu@oa-cagliari.inaf.it |
c1104fd4c36e372c60936f674d472079e864a329 | 54a03bb6129a298b27b9afdff9713edba3131200 | /include/locic/AST/RequireSpecifier.hpp | b6e3475a74c68265bb340ad6b262367ceeef04a5 | [
"NCSA",
"MIT"
] | permissive | rnshah9/mayhem-locic | d45874a944dfce6ba2d5ca5f8ab06b24d323d8ff | a24bb380e17f8af69e7389acf8ce354c91a2abf3 | refs/heads/master | 2023-03-20T03:47:28.405108 | 2019-12-15T16:41:24 | 2019-12-15T16:41:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 927 | hpp | #ifndef LOCIC_AST_REQUIRESPECIFIER_HPP
#define LOCIC_AST_REQUIRESPECIFIER_HPP
#include <string>
#include <locic/AST/Node.hpp>
#include <locic/AST/PredicateDecl.hpp>
namespace locic {
namespace AST {
class RequireSpecifier {
public:
enum Kind {
NONE,
NOPREDICATE,
EXPR
};
// Not specified.
static RequireSpecifier* None();
// Specified without a predicate.
static RequireSpecifier* NoPredicate();
// Specified with a predicate.
static RequireSpecifier* Expr(Node<PredicateDecl> expr);
Kind kind() const;
bool isNone() const;
bool isNoPredicate() const;
bool isExpr() const;
const Node<PredicateDecl>& expr() const;
std::string toString() const;
private:
Kind kind_;
Node<PredicateDecl> predicate_;
RequireSpecifier(const Kind pKind) : kind_(pKind) { }
};
}
}
#endif
| [
"scross@scross.co.uk"
] | scross@scross.co.uk |
85d33ba4ab498d6d81a4eb47662b27500df2bbcd | dab16faeec5a1882c3aa65d823fa669e5e832111 | /CommonUtl/utl/UI/PathItemListCtrl.cpp | f6fd328138b48ea94da9ebd7e0412c0e3605d49b | [] | no_license | paul-hc/DevTools | adaa6b20bedfb941a6114c70b97c2776c543946c | 84be93c23d8d2a272b6d5d09c4129a6cd87a2aa4 | refs/heads/master | 2023-08-31T18:17:21.143856 | 2023-08-31T17:51:12 | 2023-08-31T17:51:12 | 116,268,930 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,023 | cpp |
#include "pch.h"
#include "PathItemListCtrl.h"
#include "PathItemBase.h"
#include "MenuUtilities.h"
#include "StringUtilities.h"
#include "StdColors.h"
#include "WndUtils.h"
#include "resource.h"
#include "utl/TextClipboard.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
#include "ReportListControl.hxx"
CPathItemListCtrl::CPathItemListCtrl( UINT columnLayoutId /*= 0*/, DWORD listStyleEx /*= lv::DefaultStyleEx*/ )
: CReportListControl( columnLayoutId, listStyleEx )
, m_missingFileColor( color::ScarletRed )
{
SetCustomFileGlyphDraw();
SetPopupMenu( Nowhere, &GetStdPathListPopupMenu( Nowhere ) );
SetPopupMenu( OnSelection, &GetStdPathListPopupMenu( OnSelection ) );
AddRecordCompare( pred::NewComparator( pred::TCompareCode() ) ); // default row item comparator
}
CPathItemListCtrl::~CPathItemListCtrl()
{
}
CMenu& CPathItemListCtrl::GetStdPathListPopupMenu( ListPopup popupType )
{
if ( OnGroup == popupType )
return __super::GetStdPopupMenu( popupType );
static CMenu s_stdPopupMenu[ _ListPopupCount ];
CMenu& rMenu = s_stdPopupMenu[ popupType ];
if ( nullptr == rMenu.GetSafeHmenu() )
ui::LoadPopupMenu( &rMenu, IDR_STD_CONTEXT_MENU, ui::CPopupIndexPath( ui::ListView, OnSelection == popupType ? lv::PathItemOnSelectionSubPopup : lv::PathItemNowhereSubPopup ) );
return rMenu;
}
CMenu* CPathItemListCtrl::GetPopupMenu( ListPopup popupType )
{
CMenu* pSrcPopupMenu = __super::GetPopupMenu( popupType );
if ( pSrcPopupMenu != nullptr && OnSelection == popupType && UseShellContextMenu() )
{
std::vector<fs::CPath> selFilePaths;
if ( QuerySelectedItemPaths( selFilePaths ) )
if ( CMenu* pContextPopup = MakeContextMenuHost( pSrcPopupMenu, selFilePaths ) )
return pContextPopup;
}
return pSrcPopupMenu;
}
bool CPathItemListCtrl::TrackContextMenu( ListPopup popupType, const CPoint& screenPos )
{
if ( CMenu* pPopupMenu = GetPopupMenu( popupType ) )
{
DoTrackContextMenu( pPopupMenu, screenPos );
return true; // handled
}
return false;
}
void CPathItemListCtrl::CombineTextEffectAt( ui::CTextEffect& rTextEffect, LPARAM rowKey, int subItem, CListLikeCtrlBase* pCtrl ) const
{
ASSERT( this == pCtrl );
if ( 0 == subItem && m_missingFileColor != CLR_NONE )
if ( const utl::ISubject* pObject = AsPtr<utl::ISubject>( rowKey ) )
{
const fs::CPath filePath( pObject->GetCode() );
if ( !filePath.FileExist() )
rTextEffect.m_textColor = m_missingFileColor; // highlight in red text the missing file/directory
}
__super::CombineTextEffectAt( rTextEffect, rowKey, subItem, pCtrl );
}
BOOL CPathItemListCtrl::OnCmdMsg( UINT id, int code, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo )
{
if ( HandleCmdMsg( id, code, pExtra, pHandlerInfo ) )
return true;
return __super::OnCmdMsg( id, code, pExtra, pHandlerInfo );
}
// message handlers
BEGIN_MESSAGE_MAP( CPathItemListCtrl, CReportListControl )
ON_NOTIFY_REFLECT_EX( NM_DBLCLK, OnLvnDblclk_Reflect )
ON_COMMAND( ID_ITEM_COPY_FILENAMES, OnCopyFilenames )
ON_UPDATE_COMMAND_UI( ID_ITEM_COPY_FILENAMES, OnUpdateAnySelected )
ON_COMMAND( ID_ITEM_COPY_FOLDERS, OnCopyFolders )
ON_UPDATE_COMMAND_UI( ID_ITEM_COPY_FOLDERS, OnUpdateAnySelected )
ON_COMMAND( ID_FILE_PROPERTIES, OnFileProperties )
ON_UPDATE_COMMAND_UI( ID_FILE_PROPERTIES, OnUpdateAnySelected )
END_MESSAGE_MAP()
BOOL CPathItemListCtrl::OnLvnDblclk_Reflect( NMHDR* pNmHdr, LRESULT* pResult )
{
NMITEMACTIVATE* pNmItemActivate = (NMITEMACTIVATE*)pNmHdr;
if ( !ParentHandlesWmNotify( NM_DBLCLK ) )
{
*pResult = 0;
UINT flags;
int itemIndex = HitTest( pNmItemActivate->ptAction, &flags );
if ( itemIndex != -1 && !HasFlag( flags, LVHT_ONITEMSTATEICON ) ) // on item but not checkbox
if ( utl::ISubject* pCaretObject = GetSubjectAt( pNmItemActivate->iItem ) )
return ShellInvokeDefaultVerb( std::vector<fs::CPath>( 1, pCaretObject->GetCode() ) );
}
return FALSE; // raise the notification to parent
}
void CPathItemListCtrl::OnCopyFilenames( void )
{
std::vector<std::tstring> selFilePaths;
QuerySelectedItemPaths( selFilePaths );
ASSERT( !selFilePaths.empty() );
fs::CPath commonDirPath = path::ExtractCommonParentPath( selFilePaths );
if ( !commonDirPath.IsEmpty() )
for ( std::vector<std::tstring>::iterator itFilePath = selFilePaths.begin(); itFilePath != selFilePaths.end(); ++itFilePath )
path::StripPrefix( *itFilePath, commonDirPath.GetPtr() );
if ( !CTextClipboard::CopyToLines( selFilePaths, m_hWnd ) )
ui::BeepSignal( MB_ICONWARNING );
}
void CPathItemListCtrl::OnCopyFolders( void )
{
std::vector<fs::CPath> selFilePaths;
QuerySelectedItemPaths( selFilePaths );
ASSERT( !selFilePaths.empty() );
std::vector<fs::CPath> parentDirPaths;
path::QueryParentPaths( parentDirPaths, selFilePaths );
if ( !CTextClipboard::CopyToLines( parentDirPaths, m_hWnd ) )
ui::BeepSignal( MB_ICONWARNING );
}
void CPathItemListCtrl::OnFileProperties( void )
{
std::vector<fs::CPath> selFilePaths;
QuerySelectedItemPaths( selFilePaths );
ShellInvokeProperties( selFilePaths );
}
| [
"phc.2nd@gmail.com"
] | phc.2nd@gmail.com |
2643736890d0e372a56b16e8ab0c5154b1015333 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/httpd/gumtree/httpd_patch_hunk_2887.cpp | ccaa57aad84359589997da2abee9603d309e88a6 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 507 | cpp | * might have more than one network address. The RFC1413 etc.
* client sends only port numbers; the server takes the IP
* addresses from the query socket.
*/
if ((rv = apr_socket_bind(*newsock, localsa)) != APR_SUCCESS) {
- ap_log_error(APLOG_MARK, APLOG_CRIT, rv, srv,
+ ap_log_error(APLOG_MARK, APLOG_CRIT, rv, srv, APLOGNO(01496)
"rfc1413: Error binding query socket to local port");
apr_socket_close(*newsock);
return rv;
}
/*
| [
"993273596@qq.com"
] | 993273596@qq.com |
79fac68b7b7a1721b13fbcfbbf6a1667fbb33155 | af9dfcad721a1ecc185f791fa2da922b744a9d28 | /lowest_common_ancester.cpp | 5fc355c244885a403451640e903f9224f1ce3b47 | [] | no_license | nishitm/c0de | eb58b1fab0d12d03e49906031086a7bb2636d08c | 8a12c85f914fa10fa87ed36a9915ee6ac04c6540 | refs/heads/master | 2021-01-12T13:09:27.628627 | 2016-11-23T08:13:59 | 2016-11-23T08:13:59 | 68,672,133 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,322 | cpp | // Problem::Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tree.
//
// According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).”
//
// _______3______
// / \
// ___5__ ___1__
// / \ / \
// 6 _2 0 8
// / \
// 7 4
// For example, the lowest common ancestor (LCA) of nodes 5 and 1 is 3. Another example is LCA of nodes 5 and 4 is 5, since a node can be a descendant of itself according to the LCA definition.
/**
* 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* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NULL || root==p || root==q)
return root;
TreeNode* l = lowestCommonAncestor(root->left,p,q);
TreeNode* r= lowestCommonAncestor(root->right,p,q);
if(!l)
return r;
if(!r)
return l;
return root;
}
};
| [
"nishitm@cse.iitk.ac.in"
] | nishitm@cse.iitk.ac.in |
d5985f0e4efe3c74cc54079278c87b74d3bc6eff | 12d637401ccfd0241a574a2caaca14cc06943c68 | /karia2.cpp | d5747f601e3a29c2e8bbfdbfc2d5481b9b244766 | [] | no_license | stlcours/karia2 | 8eb42950814aa3ace28221b71e3ded951012d2dd | 0dcbda4c79cdb9203e95879bf78919b494e0f06c | refs/heads/master | 2021-05-27T03:16:02.888881 | 2014-03-08T23:27:16 | 2014-03-08T23:27:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 130,412 | cpp | // karia2.cpp ---
//
// Author: liuguangzhao
// Copyright (C) 2007-2013 liuguangzhao@users.sf.net
// URL:
// Created: 2010-04-03 22:27:02 +0800
// Version: $Id: karia2.cpp 226 2013-10-19 04:03:38Z drswinghead $
//
#include <QtCore>
#include <QtGui>
#include <QtWidgets>
#include "ui_karia2.h"
#include "utility.h"
#include "karia2.h"
#include "asynctask.h"
#include "aboutdialog.h"
#include "dropzone.h"
#include "taskinfodlg.h"
#include "sqlitecategorymodel.h"
#include "sqlitestorage.h"
#include "sqlitetaskmodel.h"
#include "sqlitesegmentmodel.h"
#include "segmentlogmodel.h"
#include "taskitemdelegate.h"
#include "optionmanager.h"
#include "catmandlg.h"
#include "catpropdlg.h"
#include "preferencesdialog.h"
#include "dmstatusbar.h"
#include "batchjobmandlg.h"
#include "webpagelinkdlg.h"
#include "taskqueue.h"
#include "taskballmapwidget.h"
#include "instantspeedhistogramwnd.h"
#include "walksitewndex.h"
#include "torrentpeermodel.h"
#include "taskservermodel.h"
#include "seedfilemodel.h"
#include "seedfilesdialog.h"
//////
#include "libng/html-parse.h"
//labspace
#include "labspace.h"
#if !defined(Q_OS_WIN32)
#include <X11/Xlib.h>
#include <X11/extensions/XTest.h>
#endif
#include "simplelog.h"
//#include "ariaman.h"
//#include "maiaXmlRpcClient.h"
#include "emaria2c.h"
#include "karia2statcalc.h"
#include "aria2manager.h"
#include "aria2managerfactory.h"
#include "metauri.h"
//#include "skype.h"
//#include "skypetunnel.h"
//#include "skypetracer.h"
extern QHash<QString, QString> gMimeHash;
////////////////////////////////////////////////
//main window
////////////////////////////////////////////////
Karia2::Karia2(int argc, char **argv, QWidget *parent, Qt::WindowFlags flags)
: QMainWindow(parent, flags)
, mainUI(new Ui::Karia2())
, mAtask(NULL)
, mTaskMan(NULL)
// , mEAria2Man(NULL)
, mAria2Manager(NULL), mLogFile(NULL)
, mStatusBar(NULL)
, m_argc(argc), m_argv(argv)
// , mSkypeTracer(NULL)
{
// QDir().setCurrent(qApp->applicationDirPath()); // why do this?可能是打开文件夹时的目录问题
mainUI->setupUi(this);
firstShowEvent = true;
/////////////
orginalPalette = QApplication::palette();
//dynamic language switch
qmLocale = QLocale::system().name();
qmPath = qApp->applicationDirPath() + QString("/translations");
qLogx()<<"Switch Langague to: "<<qmLocale;
qApp->installTranslator(&appTranslator);
qApp->installTranslator(&qtTranslator);
appTranslator.load(QString("karia2_") + qmLocale , qmPath );
qtTranslator.load(QString("qt_") + qmLocale , qmPath );
this->retranslateUi();
if (qmLocale.startsWith("zh_CN")) {
this->mainUI->action_Chinese_simple->setChecked(true);
} else if (qmLocale.startsWith("zh_TW")) {
this->mainUI->action_Chinese_trad->setChecked(true);
} else {
this->mainUI->action_English->setChecked(true);
}
qLogx()<<"";
}
/**
* first show adjust window layout
* TODO 改进,主线程加载界面组件,异步任务线程加载数据组件,初始化非gui对象。
*/
void Karia2::firstShowHandler()
{
qLogx()<<"";
QMenu *addTaskMenuList = new QMenu(this);
addTaskMenuList->addAction(this->mainUI->action_New_Download);
addTaskMenuList->addAction(this->mainUI->action_New_Bittorrent);
addTaskMenuList->addAction(this->mainUI->action_New_Metalink);
addTaskMenuList->addAction(this->mainUI->actionAdd_batch_download); // batch
this->mAddOtherTaskButton = new QToolButton(this);
this->mAddOtherTaskButton->setPopupMode(QToolButton::MenuButtonPopup); // new, nice
this->mAddOtherTaskButton->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
this->mainUI->toolBar->insertWidget(this->mainUI->action_Delete_task, this->mAddOtherTaskButton);
this->mAddOtherTaskButton->setMenu(addTaskMenuList);
this->mAddOtherTaskButton->setDefaultAction(this->mainUI->action_New_Download);
this->mISHW = new InstantSpeedHistogramWnd(this->mainUI->speed_histogram_toolBar);
this->mainUI->speed_histogram_toolBar->addWidget(this->mISHW);
this->mDropZone = new DropZone(); // little float window
QScrollArea *sa = new QScrollArea(this->mainUI->tab_4);
this->mainUI->tab_4->setLayout(new QVBoxLayout());
this->mainUI->tab_4->layout()->addWidget(sa);
// database inited here???
TaskBallMapWidget *wg = TaskBallMapWidget::instance(sa);
//sa->setLayout(new QVBoxLayout());
sa->setWidget(wg);
sa->setWidgetResizable(false);
sa->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
//
this->initPopupMenus();
this->initStatusBar();
this->initSystemTray();
this->initAppIcons();
this->initialMainWindow();
this->update();
///////
// init base storage db
// this->mStorage = SqliteStorage::instance(this);
// QObject::connect(this->mStorage, SIGNAL(opened()), this, SLOT(onStorageOpened()));
// this->mStorage->open();
//
this->mCatView = this->mainUI->mui_tv_category;
this->mTaskListView = this->mainUI->mui_tv_task_list;
this->mSegListView = this->mainUI->mui_tv_seg_list;
this->mSegLogListView = this->mainUI->mui_tv_seg_log_list;
this->mSegLogListView->setModel(SegmentLogModel::instance(0, 0, this));
// 初始化任务队列管理实例
// this->mTaskMan = TaskQueue::instance();
this->update();
// select the downloading cat Automaticly
this->mSeedFileDelegate = new SeedFileItemDelegate();
this->mSeedFileView = this->mainUI->treeView_2;
this->mSeedFileView->setItemDelegate(this->mSeedFileDelegate);
///////////////一些lazy模式实例化的类指针初始化。
this->mWalkSiteWnd = 0;
this->mWalkSiteDockWidget = 0;
this->mHWalkSiteWndEx = 0;
this->mainUI->action_Pause->setEnabled(false);
this->mainUI->action_Start->setEnabled(false);
this->mainUI->action_Delete_task->setEnabled(false);
// this->onUpdateJobMenuEnableProperty();
//
this->connectAllSignalAndSlog();
//this->showMaximized();
///////
this->hideUnimplementUiElement();
this->hideUnneededUiElement();
// this->initUserOptionSetting();
qLogx()<<"";
// this->mSkype = new Skype("karia2");
// QObject::connect(this->mSkype, SIGNAL(skypeError(int, QString)),
// this, SLOT(onSkypeError(int, QString)));
// bool cok = this->mSkype->connectToSkype();
// qLogx()<<"skype connect status:"<<cok;
// QObject::connect(this->mainUI->actionSkype_Tracer_2, SIGNAL(triggered(bool)),
// this, SLOT(onShowSkypeTracer(bool)));
// QObject::connect(this->mainUI->pushButton, SIGNAL(clicked()),
// this, SLOT(onChatWithSkype()));
// QObject::connect(this->mainUI->pushButton_2, SIGNAL(clicked()),
// this, SLOT(onSendPackage()));
// QObject::connect(this->mainUI->pushButton_4, SIGNAL(clicked()),
// this, SLOT(onCallSkype()));
// SkypeTunnel *tun = new SkypeTunnel(this);
// tun->setSkype(this->mSkype);
this->asyncFirstShowHandler();
}
void Karia2::asyncFirstShowHandler()
{
// init base storage db
this->mStorage = SqliteStorage::instance(this);
QObject::connect(this->mStorage, SIGNAL(opened()), this, SLOT(onStorageOpened()));
this->mStorage->open();
// 初始化任务队列管理实例
this->mTaskMan = TaskQueue::instance();
//// start embeded backed
qRegisterMetaType<QMap<int, QVariant> >("QMap<int, QVariant>");
qRegisterMetaType<QList<QMap<QString, QString> > >("QList<QMap<QString, QString> >");
/*
this->mEAria2Man = EAria2Man::instance();
QObject::connect(this->mEAria2Man, &EAria2Man::taskStatChanged, this->mTaskMan, &TaskQueue::onTaskStatusNeedUpdate2);
QObject::connect(this->mEAria2Man, &EAria2Man::taskServerStatChanged, this->mTaskMan,
&TaskQueue::onTaskServerStatusNeedUpdate);
QObject::connect(this->mEAria2Man, &EAria2Man::taskFinished, this, &Karia2::onTaskDone);
*/
this->mLogFile = new QFile("/tmp/karia2.log");
if (!this->mLogFile->open(QIODevice::ReadWrite | QIODevice::Unbuffered)) {
qLogx()<<"Open log catch file error:"<<this->mLogFile->error();
} else {
this->mLogFile->resize(0);
this->mLogFile->seek(this->mLogFile->size());
this->mLogWatcher = new QFileSystemWatcher();
this->mLogWatcher->addPath("/tmp/karia2.log");
QObject::connect(this->mLogWatcher, &QFileSystemWatcher::fileChanged, this, &Karia2::onLogAppended);
// QDir().remove("/tmp/karia2.log");
}
// this->mAria2Manager = Aria2ManagerFactory::createManager(Aria2Manager::BT_EMBEDED);
// this->mAria2Manager = Aria2ManagerFactory::createManager(Aria2Manager::BT_LIBARIA2);
// this->mAria2Manager = Aria2ManagerFactory::createManager(Aria2Manager::BT_XMLRPC_HTTP);
// this->mAria2Manager = Aria2ManagerFactory::createManager(Aria2Manager::BT_JSONRPC_HTTP);
this->mAria2Manager = Aria2ManagerFactory::createManager(Aria2Manager::BT_JSONRPC_WS);
QObject::connect(this->mAria2Manager, &Aria2Manager::taskStatChanged, this->mTaskMan, &TaskQueue::onTaskStatusNeedUpdate2);
QObject::connect(this->mAria2Manager, &Aria2Manager::taskServerStatChanged,
this->mTaskMan, &TaskQueue::onTaskServerStatusNeedUpdate);
QObject::connect(this->mAria2Manager, &Aria2Manager::taskFinished, this, &Karia2::onTaskDone);
QObject::connect(this->mAria2Manager, &Aria2Manager::globalStatChanged, this, &Karia2::onAria2GlobalStatChanged);
this->initUserOptionSetting();
// process arguments
this->handleArguments();
//test area ---------begin-----------------
LabSpace *labspace = new LabSpace(this);
//labspace->show();
Q_UNUSED(labspace);
#ifdef Q_OS_WIN32
// register system hot key
if (!::RegisterHotKey(this->winId(), 'C', MOD_CONTROL|MOD_SHIFT, 'C')) {
qLogx()<<"::RegisterHotKey faild";
}
#else
#endif
//test area ---------end-----------------
}
Karia2::~Karia2()
{
// this->mAriaMan->stop();
// delete this->mAriaMan;
}
/**
* init main window size, split size
*/
void Karia2::initialMainWindow()
{
//qLogx()<<__FUNCTION__;
//set split on humanable postion , but not middle
QList<int> splitSize;
float goldRate = 0.718, goldRate2 = 0.618;
int twidth;
splitSize = this->mainUI->splitter_4->sizes();
twidth = splitSize[0] + splitSize[1];
splitSize[1] = (int)(twidth * goldRate);
splitSize[0] = twidth - splitSize[1];
this->mainUI->splitter_4->setSizes(splitSize);
splitSize = this->mainUI->splitter_3->sizes();
splitSize[0] -= 60;
splitSize[1] += 60;
this->mainUI->splitter_3->setSizes(splitSize);
splitSize = this->mainUI->splitter_2->sizes();
splitSize[0] -= 50;
splitSize[1] += 50;
//this->mainUI->splitter_2->setSizes(splitSize);
splitSize = this->mainUI->splitter->sizes();
//qLogx()<<splitSize;
splitSize[0] += 80;
// splitSize[1] -= 80; // no log section now
this->mainUI->splitter->setSizes(splitSize);
//this->onSwitchToWindowsXPStyle(true);
}
void Karia2::moveEvent (QMoveEvent * event )
{
QPoint cp = event->pos();
QPoint op = event->oldPos();
QSize winSize = this->size();
QRect winRect = this->rect();
QPoint pos = this->pos();
int dtwidth = QApplication::desktop()->width();
int dtheight = QApplication::desktop()->height();
//qLogx()<<event->pos()<<event->oldPos()<<"W: "<<dtwidth<<" H:"<<dtheight;
//top
QMainWindow::moveEvent(event);
}
void Karia2::initPopupMenus()
{
//action groups
QActionGroup *group = new QActionGroup(this);
QObject::connect(group, SIGNAL(triggered(QAction *)), this, SLOT(onSwitchSpeedMode(QAction*)));
group->addAction(mainUI->action_Unlimited);
group->addAction(mainUI->action_Manual);
group->addAction(mainUI->action_Automatic);
// should dynamic check available styles
//window style : "windows", "motif", "cde", "plastique", "windowsxp", or "macintosh" , "cleanlooks"
group = new QActionGroup(this);
// automatic check supported style
QStringList styleKeys = QStyleFactory::keys();
QStyle *defaultStyle = QApplication::style();
// qLogx()<<QApplication::style()<<styleKeys;
for (int i = 0; i < styleKeys.count(); ++i) {
QAction *styleAction = new QAction(styleKeys.at(i), this->mainUI->menuStyle);
styleAction->setData(styleKeys.at(i));
styleAction->setCheckable(true);
if (styleKeys.at(i).toLower() == defaultStyle->objectName()) {
styleAction->setChecked(true);
}
this->mainUI->menuStyle->addAction(styleAction);
group->addAction(styleAction);
}
QObject::connect(group, SIGNAL(triggered(QAction *)), this, SLOT(onSwitchWindowStyle(QAction*)));
//supported languages: en_US , zh_CN , zh_TW
group = new QActionGroup(this);
mainUI->action_Chinese_simple->setData("zh_CN");
mainUI->action_Chinese_trad->setData("zh_TW");
mainUI->action_English->setData("en_US");
group->addAction(mainUI->action_Chinese_simple);
group->addAction(mainUI->action_Chinese_trad);
group->addAction(mainUI->action_English);
QObject::connect(group, SIGNAL(triggered(QAction *)), this, SLOT(onSwitchLanguage(QAction*)));
//mainUI->action_English->setChecked(true);
/////skin
group = new QActionGroup(this);
group->addAction(mainUI->actionNone);
group->addAction(mainUI->actionNormal);
group->addAction(mainUI->actionXP_Luna);
group->addAction(mainUI->actionXP_Luna_Gradient);
group->addAction(mainUI->actionSkype_Gradient);
group->addAction(mainUI->actionCustom_Background);
group->addAction(mainUI->actionImageBk);
QObject::connect(group, SIGNAL(triggered(QAction *)), this, SLOT(onSwitchSkinType(QAction*)));
/////// all popups
this->mTaskPopupMenu = new QMenu("&Task", this);
QList<QAction*> actionList;
actionList.append(this->mainUI->action_Start);
actionList.append(this->mainUI->action_Pause);
actionList.append(this->mainUI->action_Start_All);
actionList.append(this->mainUI->action_Pause_All);
actionList.append(this->mainUI->action_Schedule);
this->mTaskPopupMenu->addActions(actionList);
this->mTaskPopupMenu->addSeparator();
actionList.clear();
this->mTaskPopupMenu->addAction(this->mainUI->action_Move_top);
this->mTaskPopupMenu->addAction(this->mainUI->action_Move_bottom);
this->mTaskPopupMenu->addSeparator();
this->mTaskPopupMenu->addAction(this->mainUI->action_Delete_task);
this->mTaskPopupMenu->addSeparator();
this->mTaskPopupMenu->addAction(this->mainUI->action_Properties);
this->mTaskPopupMenu->addAction(this->mainUI->action_Site_Properties);
this->mTaskPopupMenu->addAction(this->mainUI->action_Comment);
this->mTaskPopupMenu->addAction(this->mainUI->action_Browse_Referer );
this->mTaskPopupMenu->addAction(this->mainUI->action_Browse_With_Site_Explorer );
this->mTaskPopupMenu->addSeparator();
this->mTaskPopupMenu->addAction(this->mainUI->action_Download_Again );
this->mTaskPopupMenu->addSeparator();
this->mTaskPopupMenu->addAction(this->mainUI->action_Copy_URL_To_ClipBoard );
/////////////
this->mTaskPopupMenu->addActions(actionList);
actionList.clear();
actionList.append(this->mainUI->action_Seg_Log_Copy);
actionList.append(this->mainUI->actionSelect_All);
actionList.append(this->mainUI->action_Seg_Log_Save_To_File);
actionList.append(this->mainUI->action_Clear_Seg_Log);
this->mLogPopupMenu = new QMenu("&SegLog", this);
this->mLogPopupMenu->addActions(actionList);
actionList.clear();
actionList.append(this->mainUI->action_Seg_List_Start);
actionList.append(this->mainUI->action_Seg_List_Stop);
actionList.append(this->mainUI->action_Seg_List_Restart);
actionList.append(this->mainUI->action_Increase_split_parts);
actionList.append(this->mainUI->action_Decrease_split_parts);
this->mSegmentPopupMenu = new QMenu("&SegList", this);
this->mSegmentPopupMenu->addActions(actionList);
this->mCatPopupMenu = new QMenu("&Category", this);
actionList.clear();
actionList.append(this->mainUI->actionNew_Cagegory);
actionList.append(this->mainUI->action_Delete_cat);
actionList.append(this->mainUI->action_cat_Move_To);
actionList.append(this->mainUI->action_Cat_Property);
this->mCatPopupMenu->addActions(actionList);
//drop zone
this->mDropZonePopupMenu = new QMenu("&DropZone", this);
this->mDropZonePopupMenu->addAction(this->mainUI->action_Show_Hide_Main_Widow);
this->mDropZonePopupMenu->addSeparator ();
this->mDropZonePopupMenu->addAction(this->mainUI->action_Monitor_Clipboard);
this->mDropZonePopupMenu->addAction(this->mainUI->action_Disable_Browser_Monitor);
this->mDropZonePopupMenu->addSeparator ();
this->mDropZonePopupMenu->addAction(this->mainUI->action_Start_All);
this->mDropZonePopupMenu->addAction(this->mainUI->action_Pause_All);
this->mDropZonePopupMenu->addSeparator ();
this->mDropZonePopupMenu->addAction(this->mainUI->action_New_Download);
this->mDropZonePopupMenu->addAction(this->mainUI->actionAdd_batch_download);
this->mDropZonePopupMenu->addAction(this->mainUI->actionPaste_URL);
this->mDropZonePopupMenu->addSeparator ();
this->mDropZonePopupMenu->addMenu(this->mainUI->menuSpeed_Limit_Mode);
this->mDropZonePopupMenu->addSeparator ();
this->mDropZonePopupMenu->addMenu(this->mainUI->menu_Search);
this->mDropZonePopupMenu->addAction(this->mainUI->action_Site_Explorer);
this->mDropZonePopupMenu->addSeparator ();
this->mDropZonePopupMenu->addAction(this->mainUI->action_Options);
this->mDropZonePopupMenu->addAction(this->mainUI->action_About_Karia2);
this->mDropZonePopupMenu->addSeparator ();
this->mDropZonePopupMenu->addAction(this->mainUI->actionQuit);
//mSysTrayMenu
this->mSysTrayMenu = new QMenu("NullTray", this);
this->mSysTrayMenu->addAction(this->mainUI->action_Show_Hide_Main_Widow);
this->mSysTrayMenu->addSeparator();
this->mSysTrayMenu->addAction(this->mainUI->actionQuit);
this->mSysTrayMenu->addAction(this->mainUI->actionAbout_Qt);
}
void Karia2::initStatusBar()
{
//进度条初始化状态应该从配置读取出来才对。开始结束的最大值也从配置文件来。
QSize osize = this->statusBar()->size();
// new custom statusbar
this->setStatusBar(this->mStatusBar = new DMStatusBar(0));
QSize nsize = this->statusBar()->size();
qLogx()<<osize<<nsize;
}
/**
*
*/
void Karia2::initSystemTray()
{
//init system tray icon
this->mSysTrayIcon = new QSystemTrayIcon(this);
this->mSysTrayIcon->setToolTip(tr("karia2 Icon Tray Control"));
//this->mSysTrayIcon->setContextMenu(this->mSysTrayMenu);
this->mSysTrayIcon->setContextMenu(this->mDropZonePopupMenu);
QString iconname;
int index = 0;
switch (index) {
default:
case 0:
//iconname = QString(qApp->applicationDirPath()+"/"+"resources/icon_16x16.png");
// break;
case 1:
//iconname = QString(qApp->applicationDirPath()+"/"+"resources/icon_22x22.png");
//break;
case 2:
// iconname = QString(qApp->applicationDirPath() + "/Resources/karia2-1.png");
iconname = QString(qApp->applicationDirPath() + "/" +"Resources/karia2.png");
break;
}
QPixmap pix(iconname);
this->mSysTrayIcon->setIcon(QIcon(pix));
this->mSysTrayIcon->show();
//this->setWindowIcon(QIcon(qApp->applicationDirPath()+"/"+"resources/icon_16x16.png"));
// this->setWindowIcon(QIcon(qApp->applicationDirPath()+"/Resources/karia2-1.png"));
this->setWindowIcon(QIcon(qApp->applicationDirPath()+"/Resources/karia2.png"));
}
void Karia2::initAppIcons()
{
QString dir = qApp->applicationDirPath() + "/icons";
this->mainUI->action_Start->setIcon(QIcon(dir + "/media-playback-start.png"));
this->mainUI->action_Pause->setIcon(QIcon(dir + "/media-playback-pause.png"));
this->mainUI->action_New_Download->setIcon(QIcon(dir + "/list-add.png"));
this->mainUI->action_Delete_task->setIcon(QIcon(dir + "/list-remove.png"));
this->mainUI->action_Properties->setIcon(QIcon(dir + "/document-properties.png"));
this->mainUI->actionMove_Up->setIcon(QIcon(dir + "/arrow-up.png"));
this->mainUI->actionMove_Down->setIcon(QIcon(dir + "/arrow-down.png"));
this->mainUI->actionOpen_Exec_download_file->setIcon(QIcon(dir + "/system-run.png"));
this->mainUI->actionOpen_de_stination_directory->setIcon(QIcon(dir + "/document-open-folder.png"));
this->mainUI->actionFind->setIcon(QIcon(dir + "/edit-find.png"));
this->mainUI->actionFind_next->setIcon(QIcon(dir + "/go-down-search.png"));
// this->mainUI->actionDefault_Download_Properties->setIcon(QIcon(dir + "/configure.png"));
this->mainUI->action_Options->setIcon(QIcon(dir + "/preferences-system.png"));
this->mainUI->actionQuit->setIcon(QIcon(dir + "/system-shutdown.png"));
this->mainUI->label->setPixmap(QPixmap(dir + "/status/unknown.png"));
}
void Karia2::connectAllSignalAndSlog()
{
QObject::connect(this->mainUI->actionDrop_zone, SIGNAL(triggered(bool)), this->mDropZone,SLOT(setVisible(bool)));
//file action
//QObject::connect(this->mainUI->action_New_Database, SIGNAL(triggered()), this, SLOT(onNewDatabase()));
//QObject::connect(this->mainUI->action_Open_Database, SIGNAL(triggered()), this, SLOT(onOpenDatabase()));
//QObject::connect(this->mainUI->action_Save_Database, SIGNAL(triggered()), this, SLOT(onSaveAllTask()));
//QObject::connect(this->mainUI->actionSave_As, SIGNAL(triggered()), this, SLOT(onSaveAllTaskAs()));
QObject::connect(this->mainUI->actionProcess_Web_Page_File, SIGNAL(triggered()), this, SLOT(showProcessWebPageInputDiglog()));
//editr
QObject::connect(this->mainUI->actionPaste_URL , SIGNAL(triggered()), this, SLOT(showNewDownloadDialog()));
QObject::connect(this->mainUI->actionSelect_All, SIGNAL(triggered()), this, SLOT(onEditSelectAll()));
QObject::connect(this->mainUI->actionInvert_Select, SIGNAL(triggered()), this, SLOT(onEditInvertSelect()));
//cat action
QObject::connect(this->mainUI->actionNew_Cagegory , SIGNAL(triggered()), this, SLOT(onNewCategory()));
QObject::connect(this->mainUI->action_Cat_Property , SIGNAL(triggered()), this, SLOT(onShowCategoryProperty()));
QObject::connect(this->mainUI->action_Delete_cat, SIGNAL(triggered()), this, SLOT(onDeleteCategory()));
QObject::connect(this->mainUI->action_cat_Move_To , SIGNAL(triggered()), this, SLOT(onCategoryMoveTo()));
//view
QObject::connect(this->mainUI->action_Show_Columns_Editor, SIGNAL(triggered()), this, SLOT(onShowColumnEditor()));
QObject::connect(this->mainUI->actionShow_Text, SIGNAL(triggered(bool)), this, SLOT(onShowToolbarText(bool) ) );
//job action
QObject::connect(this->mainUI->menu_Jobs, SIGNAL(aboutToShow()), this, SLOT(onTaskListMenuPopup()));
QObject::connect(this->mainUI->action_New_Download, SIGNAL(triggered()), this, SLOT(showNewDownloadDialog()));
QObject::connect(this->mainUI->action_New_Bittorrent, SIGNAL(triggered()), this, SLOT(showNewBittorrentFileDialog()));
QObject::connect(this->mainUI->action_New_Metalink, SIGNAL(triggered()), this, SLOT(showNewMetalinkFileDialog()));
QObject::connect(this->mainUI->actionAdd_batch_download, SIGNAL(triggered()), this, SLOT(showBatchDownloadDialog()));
QObject::connect(this->mainUI->action_Start , SIGNAL(triggered()), this, SLOT(onStartTask()));
QObject::connect(this->mainUI->action_Pause , SIGNAL(triggered()), this, SLOT(onPauseTask()));
QObject::connect(this->mainUI->action_Start_All , SIGNAL(triggered()), this, SLOT(onStartTaskAll()));
QObject::connect(this->mainUI->action_Pause_All , SIGNAL(triggered()), this, SLOT(onPauseTaskAll()));
QObject::connect(this->mainUI->action_Delete_task, SIGNAL(triggered()), this, SLOT(onDeleteTask()));
QObject::connect(this->mainUI->action_Properties, SIGNAL(triggered()), this, SLOT(onShowTaskProperty()));
QObject::connect(this->mainUI->actionOpen_de_stination_directory, SIGNAL(triggered()), this, SLOT(onOpenDistDirector()));
QObject::connect(this->mainUI->actionOpen_Exec_download_file, SIGNAL(triggered()), this, SLOT(onOpenExecDownloadedFile()));
QObject::connect(this->mainUI->action_Browse_Referer, SIGNAL(triggered()), this, SLOT(onOpenRefererUrl()));
//tools
QObject::connect(this->mainUI->action_Options, SIGNAL(triggered()), this, SLOT(onShowOptions()));
// QObject::connect(this->mainUI->actionDefault_Download_Properties , SIGNAL(triggered()), this, SLOT(onShowDefaultDownloadProperty()));
//statusbar
QObject::connect(this->mStatusBar, &DMStatusBar::speedChanged, this, &Karia2::onManualSpeedChanged);
QObject::connect(this->mainUI->action_Remember, SIGNAL(triggered(bool)),
this, SLOT(onRememberSpeedLimitSetting(bool)));
//help action
this->connect(this->mainUI->action_Go_to_Karia2_Home_Page, SIGNAL(triggered()), this, SLOT(onGotoHomePage()));
this->connect(this->mainUI->action_About_Karia2, SIGNAL(triggered()), this, SLOT(showAboutDialog()));
QObject::connect(this->mainUI->actionAbout_Qt, SIGNAL(triggered()), this, SLOT(onAboutQt()));
//centrol
QObject::connect(this->mainUI->mui_tv_task_list, SIGNAL(customContextMenuRequested (const QPoint & )),
this, SLOT(onTaskListMenuPopup(/*const QPoint &*/)));
QObject::connect(this->mainUI->mui_tv_task_list, SIGNAL(entered(const QModelIndex & )) ,
this, SLOT(onShowTaskPropertyDigest(const QModelIndex & ) ) );
QObject::connect(this->mainUI->mui_tv_seg_log_list, SIGNAL(customContextMenuRequested (const QPoint & )),
this, SLOT(onLogListMenuPopup(const QPoint &)));
QObject::connect(this->mainUI->mui_tv_seg_list, SIGNAL(customContextMenuRequested (const QPoint & )),
this, SLOT(onSegListMenuPopup(const QPoint &)));
QObject::connect(this->mainUI->mui_tv_category, SIGNAL(customContextMenuRequested (const QPoint & )),
this, SLOT(onCateMenuPopup(const QPoint &)));
QObject::connect(this->mDropZone, SIGNAL(doubleclicked()), this, SLOT(onDropZoneDoubleClicked()));
QObject::connect(this->mainUI->action_Show_Hide_Main_Widow, SIGNAL(triggered()), this, SLOT(onDropZoneDoubleClicked()));
QObject::connect(this->mDropZone, SIGNAL(customContextMenuRequested(const QPoint &)),
this, SLOT(onDropZoneCustomMenu(const QPoint &)));
//seg log menu
QObject::connect(this->mainUI->action_Seg_Log_Copy, SIGNAL(triggered()), this, SLOT(onCopySelectSegLog()));
QObject::connect(this->mainUI->action_Seg_Log_Save_To_File, SIGNAL(triggered()), this, SLOT(onSaveSegLog()));
QObject::connect(this->mainUI->action_Clear_Seg_Log, SIGNAL(triggered()), this, SLOT(onClearSegLog()));
//toolbar //在UI设计器中将信号传递到标准菜单中。
//QObject::connect(this->mainUI->mui_tb_properties, SIGNAL(triggered()), this, SLOT(onShowTaskProperty()));
//QObject::connect(this->mainUI->mui_tb_open_dir, SIGNAL(triggered()), this, SLOT(onOpenDistDirector()));
//QObject::connect(this->mainUI->mui_tb_exec_file, SIGNAL(triggered()), this, SLOT(onOpenExecDownloadedFile()));
//other
QObject::connect(this->mainUI->action_Copy_URL_To_ClipBoard, SIGNAL(triggered()), this, SLOT(onCopyUrlToClipboard()));
QObject::connect(QApplication::clipboard(), SIGNAL(dataChanged()), this, SLOT(onClipBoardDataChanged()));
QObject::connect(this->mainUI->actionWalk_Site, SIGNAL(triggered()), this, SLOT(onShowWalkSiteWindow()));
QObject::connect(this->mSysTrayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(onActiveTrayIcon(QSystemTrayIcon::ActivationReason)));
QObject::connect(this->mSysTrayIcon, SIGNAL(messageClicked()), this, SLOT(onBallonClicked()));
//test it
//this->connect(this->mainUI->pushButton_3, SIGNAL(clicked()), this, SLOT(testFunc()));
//QObject::connect(QApplication::instance(), SIGNAL(aboutToQuit () ), this, SLOT(testFunc2()));
}
//temporary 临时用于隐藏没有实现功能用户界面的代码。
void Karia2::hideUnimplementUiElement()
{
this->mainUI->menu_Search->menuAction()->setVisible(false);
this->mainUI->menu_Plugins->menuAction()->setVisible(false);
// action
this->mainUI->action_New_Database->setVisible(false);
this->mainUI->action_Open_Database->setVisible(false);
this->mainUI->action_Merge_Database->setVisible(false);
this->mainUI->action_Save_Database->setVisible(false);
this->mainUI->actionSave_As->setVisible(false);
this->mainUI->actionImport_Previous_File->setVisible(false);
this->mainUI->actionImport_Previous_Batch_File->setVisible(false);
this->mainUI->action_Export_Information->setVisible(false);
this->mainUI->action_Export->setVisible(false);
this->mainUI->actionImport_Broken_D_ownloads->setVisible(false);
this->mainUI->actionImport_list->setVisible(false);
this->mainUI->action_Export_list->setVisible(false);
this->mainUI->action_Recently_Downloaded_Files->setVisible(false);
this->mainUI->actionProcess_Web_Page_File->setVisible(false);
//cat
this->mainUI->action_cat_Move_To->setVisible(false);
//edit
this->mainUI->actionFind->setVisible(false);
this->mainUI->actionFind_next->setVisible(false);
//view
this->mainUI->actionDetail->setVisible(false);
this->mainUI->actionGrid->setVisible(false);
this->mainUI->menuSkin->menuAction()->setVisible(false);
this->mainUI->actionButtons->setVisible(false);
//task
this->mainUI->action_Move_bottom->setVisible(false);
this->mainUI->action_Move_top->setVisible(false);
this->mainUI->action_task_Move_To->setVisible(false);
this->mainUI->actionMove_Down->setVisible(false);
this->mainUI->actionMove_Up->setVisible(false);
this->mainUI->action_Check_for_update->setVisible(false);
//tool
this->mainUI->action_Browse_With_Site_Explorer->setVisible(false);
this->mainUI->action_Site_Explorer->setVisible(false);
this->mainUI->actionWalk_Site->setVisible(false);
this->mainUI->action_Download_Rules->setVisible(false);
// this->mainUI->action_Save_as_default->setVisible(false);
//help
this->mainUI->action_User_Manual_in_Internet->setVisible(false);
this->mainUI->action_Manual_Karia2->setVisible(false);
this->mainUI->actionC_heck_for_a_new_version->setVisible(false);
this->mainUI->actionFAQ_in_Internet->setVisible(false);
//other
this->mainUI->action_Seg_List_Restart->setVisible(false);
}
void Karia2::onStorageOpened()
{
qLogx()<<"";
//
this->mCatView = this->mainUI->mui_tv_category;
this->mCatView->setSelectionMode(QAbstractItemView::SingleSelection );
this->mCatViewModel = SqliteCategoryModel::instance(0);
this->mCatView->setModel(this->mCatViewModel);
this->mCatView->setRootIndex(this->mCatViewModel->index(0, 0)); // root is the topest node
this->mCatView->expandAll();
// 设置特殊列的大小
this->mCatView->resizeColumnToContents(0);
this->update();
////
this->mTaskListView = this->mainUI->mui_tv_task_list;
this->mTaskItemDelegate = new TaskItemDelegate();
this->mTaskListView->setItemDelegate(this->mTaskItemDelegate);
this->mTaskTreeViewModel = SqliteTaskModel::instance(ng::cats::downloading, this);
this->mTaskListView->setModel(this->mTaskTreeViewModel);
this->mTaskListView->setEditTriggers(QAbstractItemView::NoEditTriggers);
this->mTaskListView->setSelectionMode(QAbstractItemView::ExtendedSelection);
this->mTaskListView->setAlternatingRowColors(true);
// QObject::connect(this->mTaskListView->selectionModel(),
// SIGNAL(selectionChanged (const QItemSelection & , const QItemSelection & )),
// this, SLOT(onTaskListSelectChange(const QItemSelection & , const QItemSelection & ) ) );
this->mSegListView = this->mainUI->mui_tv_seg_list;
this->mSegListView->setSelectionMode(QAbstractItemView::SingleSelection );
this->mSegListView->setAlternatingRowColors(true);
//this->mSegListView ->setModel(mdl);
this->mSegLogListView = this->mainUI->mui_tv_seg_log_list;
this->mSegLogListView->setSelectionMode(QAbstractItemView::ExtendedSelection );
//cat view
QObject::connect(this->mCatView->selectionModel(), SIGNAL(selectionChanged (const QItemSelection &, const QItemSelection &)),
this, SLOT(onCatListSelectChange(const QItemSelection & , const QItemSelection & ) ) );
// select the default cat model
{
// cacl the downloading model index
QItemSelection readySelect, readDeselect;
QModelIndex topCatIdx = this->mCatViewModel->index(0, 0);
qLogx()<<topCatIdx.data();
int l2RowCount = this->mCatViewModel->rowCount(topCatIdx);
qLogx()<<l2RowCount;
for (int r = 0 ; r < l2RowCount ; r ++) {
QModelIndex currCatIdx = this->mCatViewModel->index(r, ng::cats::cat_id, topCatIdx);
qLogx()<<currCatIdx;
if (currCatIdx.data().toInt() == ng::cats::downloading) {
// for (int c = 0; c <= ng::cats::dirty; c ++) {
// QModelIndex readyIndex = this->mCatViewModel->index(r, c, topCatIdx);
// readySelect.select(readyIndex, readyIndex);
// }
readySelect.select(this->mCatViewModel->index(r, 0, topCatIdx),
this->mCatViewModel->index(r, ng::cats::dirty, topCatIdx));
break;
}
}
this->mCatView->selectionModel()->select(readySelect, QItemSelectionModel::Select);
}
}
void Karia2::hideUnneededUiElement()
{
}
void Karia2::initUserOptionSetting()
{
OptionManager *om = NULL;
om = OptionManager::instance();
//////
QStringList colList;
QString taskShowColumns = om->getTaskShowColumns();
// qLogx()<<__FUNCTION__<<taskShowColumns<<(ng::tasks::aria_gid);
if (taskShowColumns != "") {
colList = taskShowColumns.split(',');
for (int i = ng::tasks::task_id ; i <= ng::tasks::aria_gid; ++i) {
// qLogx()<<"show col:"<<colList.contains(QString::number(i));
if (!colList.contains(QString::number(i))) {
this->mainUI->mui_tv_task_list->setColumnHidden(i, true);
}
}
if (this->mCustomTaskShowColumns != taskShowColumns) {
this->mCustomTaskShowColumns = taskShowColumns;
}
}
//////
QString rememberSpeedLimit = om->getRememberSpeedLimit();
if (rememberSpeedLimit == "true") {
this->mainUI->action_Remember->setChecked(true);
QString speedLimitType = om->getSpeedLimitType();
if (speedLimitType == "unlimited") {
} else if (speedLimitType == "manual") {
this->mainUI->action_Manual->setChecked(true);
QString speedLImitSpeed = om->getSpeedLimitSpeed();
this->onManualSpeedChanged(speedLImitSpeed.toInt()/1000);
this->mStatusBar->setSliderValue(speedLImitSpeed.toInt()/1000);
this->onSwitchSpeedMode(this->mainUI->action_Manual);
} else if (speedLimitType == "auto") {
this->mainUI->action_Automatic->setChecked(true);
this->onSwitchSpeedMode(this->mainUI->action_Automatic);
}
}
}
void Karia2::testFunc()
{
qLogx()<<__FUNCTION__;
// int count = 7;
this->mTaskPopupMenu->popup(QCursor::pos ());
return;
this->onStartTask();
return;
return;
QString url = "http://localhost/mtv.wmv";
int nRet = 0;
qLogx() <<nRet;
}
void Karia2::testFunc2()
{
qLogx()<<__FUNCTION__;
return;
// QStandardItemModel *model = mConfigDatabase->createCatModel();
// this->mCatView->setModel( model );
// this->mCatView->expand(model->index(0,0));
return;
this->onPauseTask();
}
// TODO, handle multi row select case
void Karia2::onStartTask()
{
qLogx()<<__FUNCTION__<<__LINE__;
QAbstractItemView *view = this->mTaskListView;
QAbstractItemModel *model = view->model();
int step = model->columnCount();
int taskId = -1;
QString url;
QModelIndexList smil = view->selectionModel()->selectedIndexes();
//qLogx()<<smil.size();
if (smil.size() == 0) {
return;
}
// this->initXmlRpc();
for (int row = 0; row < smil.count() ; row += step) {
TaskOption *taskOptions = TaskOption::fromModelRow(model, smil.at(row).row());
taskId = smil.value(row + ng::tasks::task_id).data().toInt();
url = smil.value(row + ng::tasks::org_url).data().toString();
TaskBallMapWidget::instance()->startPaint(true);
// if running
// if (this->mRunningMap.contains(taskId)) {
// continue;
// }
QMap<QString, QVariant> payload;
QVariantList args;
QList<QVariant> uris;
QMap<QString, QVariant> options;
QString aria2RpcMethod;
{
// create task object first
payload["taskId"] = QString("%1").arg(taskId);
payload["url"] = url;
this->createTask(taskId, taskOptions);
}
if (url.startsWith("file://") && url.endsWith(".torrent")) {
aria2RpcMethod = QString("aria2.addTorrent");
QFile torrentFile(url.right(url.length() - 7));
torrentFile.open(QIODevice::ReadOnly);
QByteArray torrentConntent = torrentFile.readAll();
torrentFile.close();
args.insert(0, torrentConntent);
args.insert(1, uris);
// options["split"] = QString("5");
options["split"] = taskOptions->mSplitCount;
options["dir"] = taskOptions->mSavePath;
args.insert(2, options);
} else if (url.startsWith("file://") && url.endsWith(".metalink")) {
aria2RpcMethod = QString("aria2.addMetalink");
QFile metalinkFile(url.right(url.length() - 7));
metalinkFile.open(QIODevice::ReadOnly);
QByteArray metalinkContent = metalinkFile.readAll();
metalinkFile.close();
args.insert(0, metalinkContent);
// options["split"] = QString("5");
options["split"] = taskOptions->mSplitCount;
options["dir"] = taskOptions->mSavePath;
args.insert(1, options);
} else {
aria2RpcMethod = QString("aria2.addUri");
uris << QString(url);
args.insert(0, uris);
// options["split"] = QString("3");
options["split"] = taskOptions->mSplitCount;
options["dir"] = taskOptions->mSavePath;
args.insert(1, options);
}
this->mAria2Manager->addTask(taskId, url, taskOptions);
// this->mEAria2Man->addUri(taskId, url, taskOptions);
// this->mAriaRpc->call(aria2RpcMethod, args, QVariant(payload),
// this, SLOT(onAriaAddUriResponse(QVariant &, QVariant &)),
// this, SLOT(onAriaAddUriFault(int, QString, QVariant &)));
// if (!this->mAriaUpdater.isActive()) {
// this->mAriaUpdater.setInterval(3000);
// QObject::connect(&this->mAriaUpdater, SIGNAL(timeout()), this, SLOT(onAriaUpdaterTimeout()));
// this->mAriaUpdater.start();
// }
// if (!this->mAriaTorrentUpdater.isActive()) {
// this->mAriaTorrentUpdater.setInterval(4000);
// QObject::connect(&this->mAriaTorrentUpdater, SIGNAL(timeout()), this, SLOT(onAriaTorrentUpdaterTimeout()));
// this->mAriaTorrentUpdater.start();
// }
delete taskOptions; taskOptions = NULL;
}
}
void Karia2::onStartTaskAll()
{
qLogx()<<__FUNCTION__;
TaskQueue * hTask = 0;
// int taskCount;
// int retrCount;
//taskCount = this->mTaskQueue.size();
//for (int i = 0; i < taskCount; i ++)
{
//hTask = this->mTaskQueue[i];
if (hTask != 0 )
{
//this->onStartTask(hTask->mTaskId);
//this->onStartTask(hTask );
}
}
}
void Karia2::onPauseTask()
{
qLogx()<<__FUNCTION__;
QAbstractItemView *view = this->mTaskListView;
QAbstractItemModel *model = view->model(); // SqliteTaskModel::instance(ng::cats::downloading, this);
int step = model->columnCount();
int taskId = -1;
QString ariaGid;
QModelIndexList smil = view->selectionModel()->selectedIndexes();
qLogx()<<__FUNCTION__<<"selectedIndexes count:"<<smil.size();
if (smil.size() == 0) {
return;
}
// this->initXmlRpc();
// Q_ASSERT(this->mAriaRpc != NULL);
for (int i = 0; i < smil.size(); i += step) {
taskId = smil.value(i).data().toInt();
ariaGid = smil.value(i + ng::tasks::aria_gid).data().toString();
qLogx()<<__FUNCTION__<<smil.value(i)<<taskId;
// this->mEAria2Man->pauseTask(taskId);
this->mAria2Manager->pauseTask(taskId);
// // check if running
// if (!this->mRunningMap.contains(taskId)) {
// continue;
// }
// QVariantList args;
// args << ariaGid;
// this->mAriaRpc->call(QString("aria2.remove"), args, QVariant(taskId),
// this, SLOT(onAriaRemoveResponse(QVariant &, QVariant&)),
// this, SLOT(onAriaRemoveFault(int, QString, QVariant&)));
}
}
void Karia2::onPauseTask(int pTaskId )
{
qLogx()<<__FUNCTION__;
Q_UNUSED(pTaskId);
// int retrCount;
TaskQueue * hTask = this->mTaskMan;
if (hTask == 0) {
return;
} else {
//this->onPauseTask(hTask);
}
return;
}
void Karia2::onPauseTaskAll()
{
qLogx()<<__FUNCTION__;
TaskQueue * hTask = 0;
// int taskCount;
//taskCount = this->mTaskQueue.size();
//for (int i = 0; i < taskCount; i ++)
{
// hTask = this->mTaskQueue[i];
if (hTask != 0 )
{
// this->onPauseTask(hTask->mTaskId);
}
}
}
/////delete option
/**
* 将任务数据移动到删除队列
*/
void Karia2::onDeleteTask()
{
qLogx()<<__FUNCTION__;
SqliteTaskModel * from_model = 0 , * to_model = 0;
QModelIndex idx;
QItemSelectionModel * sim = 0;
QModelIndexList mil;
// int rowCount = 0;
// int row = -1;
int colcnt = -1;
QList<int> deleteModelRows;
from_model = static_cast<SqliteTaskModel*>(this->mTaskListView->model());
to_model = static_cast<SqliteTaskModel*>(SqliteTaskModel::instance(ng::cats::deleted, 0));
colcnt = from_model->columnCount();
sim = this->mTaskListView->selectionModel();
mil = sim->selectedIndexes();
QApplication::setOverrideCursor(Qt::WaitCursor);
int rowcnt = mil.size() / colcnt;
for (int row = rowcnt - 1; row >= 0; row --) {
int mrow = mil.value(row * colcnt + ng::tasks::task_id).row();
// qLogx()<<"prepare delete ROW:"<<mrow<<" All ROW:"<<rowcnt;
// int taskId = from_model->data(mil.value(row * colcnt + ng::tasks::task_id)).toInt();
QString ariaGid = from_model->data(mil.value(row * colcnt + ng::tasks::aria_gid)).toString();
// int srcCatId = from_model->data(mil.value(row * colcnt + ng::tasks::sys_cat_id)).toInt();
// qLogx()<<"DDDD:"<<taskId<<ariaGid<<srcCatId;
deleteModelRows<<mrow;
continue;
// QModelIndexList rmil;
// for (int col = 0; col < colcnt; col ++) {
// rmil.append(mil.at(row * colcnt + col));
// }
// if (srcCatId == ng::cats::deleted) {
// // delete it directly
// from_model->removeRows(mil.value(row * colcnt).row(), 1);
// //在system tray 显示移动任务消息
// this->mSysTrayIcon->showMessage(tr("Delete Task ."), QString(tr("Delete permanently. TaskId: %1")).arg(taskId),
// QSystemTrayIcon::Information, 5000);
// } else {
// int rv = from_model->moveTasks(srcCatId, ng::cats::deleted, rmil);
// //在system tray 显示移动任务消息
// this->mSysTrayIcon->showMessage(tr("Move Task ."), QString(tr("Move To Trash Now. TaskId: %1")).arg(taskId),
// QSystemTrayIcon::Information, 5000);
// }
}
// because current order depend user's select order, we reorder it here
qSort(deleteModelRows);
for (int i = deleteModelRows.count() - 1; i >= 0; --i) {
int mrow = deleteModelRows.at(i);
int taskId = from_model->data(from_model->index(mrow, ng::tasks::task_id)).toInt();
QString ariaGid = from_model->data(from_model->index(mrow, ng::tasks::aria_gid)).toString();
int srcCatId = from_model->data(from_model->index(mrow, ng::tasks::sys_cat_id)).toInt();
qLogx()<<"DDDD:"<<mrow<<taskId<<ariaGid<<srcCatId;
QModelIndexList rmil;
for (int col = 0; col < colcnt; col ++) {
rmil.append(from_model->index(mrow, col));
}
if (srcCatId == ng::cats::deleted) {
// delete it directly
from_model->removeRows(mrow, 1, QModelIndex(), false);
//在system tray 显示移动任务消息
this->mSysTrayIcon->showMessage(tr("Delete Task ."),
QString(tr("Delete permanently. TaskId: %1")).arg(taskId),
QSystemTrayIcon::Information, 5000);
} else {
int rv = from_model->moveTasks(srcCatId, ng::cats::deleted, rmil, false);
if (rv <= 0) {
}
//在system tray 显示移动任务消息
this->mSysTrayIcon->showMessage(tr("Move Task ."), QString(tr("Move To Trash Now. TaskId: %1")).arg(taskId),
QSystemTrayIcon::Information, 5000);
}
}
QApplication::restoreOverrideCursor();
}
void Karia2::onDeleteTaskAll()
{
qLogx()<<__FUNCTION__;
QModelIndex index;
QAbstractItemModel *model;
// int rowCount = -1;
model = SqliteTaskModel::instance(ng::cats::downloading, this);
for (int i = 0; i < model->rowCount(); ++ i) {
index = model->index(i,0);
int taskId = model->data(index).toInt();
// this->onDeleteTask(taskId);
Q_UNUSED(taskId);
}
}
QModelIndex findCatModelIndexByCatId(QAbstractItemModel *mdl, QModelIndex parent, int catId)
{
QModelIndex idx;
if (parent.isValid()) {
QModelIndex catIdx = mdl->index(parent.row(), ng::cats::cat_id, parent.parent());
if (catIdx.data().toInt() == catId) {
return parent;
} else {
int childRowCount = mdl->rowCount(parent);
QModelIndex childIdx;
for (int i = 0 ; i < childRowCount; i ++) {
childIdx = mdl->index(i, 0, parent);
idx = findCatModelIndexByCatId(mdl, childIdx, catId);
if (idx.isValid()) {
return idx;
}
}
}
} else {
QModelIndex topCatIdx = mdl->index(0, 0);
return findCatModelIndexByCatId(mdl, topCatIdx, catId);
}
return idx;
}
void Karia2::onTaskDone(int pTaskId, int code)
{
qLogx()<<__FUNCTION__;
SqliteTaskModel *mdl = SqliteTaskModel::instance(ng::cats::downloading);
//QDateTime bTime , eTime ;
//bTime = QDateTime::currentDateTime();
QModelIndexList mil = mdl->match(mdl->index(0, ng::tasks::task_id), Qt::DisplayRole,
QVariant(QString("%1").arg(pTaskId)), 1, Qt::MatchExactly | Qt::MatchWrap);
QModelIndex idx;
int destCatId = 0;
if (mil.count() == 1) {
idx = mil.at(0);
QModelIndexList moveModels;
for (int i = 0 ; i < mdl->columnCount(); ++i) {
moveModels << mdl->index(idx.row(), i);
}
destCatId = mdl->data(mdl->index(idx.row(), ng::tasks::user_cat_id)).toInt();
mdl->moveTasks(ng::cats::downloading, destCatId, moveModels, false);
// cacl the downloading model index
QItemSelection readySelect, readDeselect;
QModelIndex readyIdx = findCatModelIndexByCatId(this->mCatViewModel, QModelIndex(), destCatId);
qLogx()<<"find cat recursive:"<<destCatId<<readyIdx;
readySelect.select(this->mCatViewModel->index(readyIdx.row(), 0, readyIdx.parent()),
this->mCatViewModel->index(readyIdx.row(), ng::cats::dirty, readyIdx.parent()));
this->mCatView->selectionModel()->select(readySelect, QItemSelectionModel::ClearAndSelect);
}
return;
}
void Karia2::onShutdown()
{
qLogx()<<__FUNCTION__<<" shutdown OS now";
}
// has crash!!!
void Karia2::onLogAppended(const QString &path)
{
return;
QByteArray aba = this->mLogFile->readAll();
QList<QByteArray> laba = aba.split('\n');
// 2013-10-05 09:02:26.127331 [INFO] [BackupIPv4ConnectCommand.cc:87] CUID#8 - Backup connection canceled
QRegExp exp("(.{20,26}) .([A-Z]{4,6}). (.*)");
QStringList caps;
QString line;
int type;
QString ltime;
QString log;
QString tid, segid;
for (int i = 0; i < laba.size(); i++) {
line = QString(laba.at(i).trimmed());
if (exp.exactMatch(line)) {
caps = exp.capturedTexts();
ltime = caps[1];
log = caps[3];
if (caps[2] == "INFO") {
type = ng::logs::INFO_MSG;
} else if (caps[2] == "DEBUG") {
type = ng::logs::DEBUG_MSG;
} else if (caps[2] == "ERROR") {
type = ng::logs::ERROR_MSG;
} else if (caps[2] == "NOTICE") {
type = ng::logs::INFO_MSG;
} else {
type = ng::logs::INFO_MSG;
}
} else {
log = line;
type = ng::logs::DEBUG_MSG;
ltime = "0:0:0:0:0";
}
QAbstractItemModel * mdl = SegmentLogModel::instance(0, 0, this);
int row = mdl->rowCount();
if (row > 30) {
mdl->removeRows(0, row - 10);
}
row = mdl->rowCount();
mdl->insertRows(row, 1);
QModelIndex mi;
mdl->setData(mdl->index(row, 0), type);
mdl->setData(mdl->index(row, 1), ltime);
mdl->setData(mdl->index(row, 2), log);
mdl->setData(mdl->index(row, 3), "0");
mdl->setData(mdl->index(row, 4), "0");
mdl->setData(mdl->index(row, 5), "false");
}
}
//////ui op
void Karia2::onNewCategory()
{
CatManDlg * dlg = new CatManDlg (this );
QAbstractItemModel * aim;
QItemSelectionModel * ism;
QModelIndexList mil;
int rv = dlg->exec();
if (rv == QDialog::Accepted) {
QModelIndex idx;
QString dir;
QString catname;
int row;
dir = dlg->getNewCatDir();
catname = dlg->getNewCatName();
ism = dlg->getSelectionModel();
aim = dlg->getCatModel();
//qLogx()<<dlg->getCatModel();
//
mil = ism->selectedIndexes();
qLogx()<<__FUNCTION__<<mil.size();
if (mil.size() > 0 ) {
row = mil.at(0).model()->rowCount(mil.at(0));
aim->insertRows(row, 1, mil.at(0));
idx = aim->index(row, ng::cats::display_name, mil.at(0));
aim->setData(idx, catname);
idx = aim->index(row, ng::cats::path, mil.at(0));
aim->setData(idx, dir);
qLogx()<<"insertt "<<row<<aim->data(idx);
//this->mCatView->collapse(mil.at(0)); // open the new cate
//this->mCatView->expand(mil.at(0));
this->mCatView->expandAll();
this->mCatView->resizeColumnToContents(0);
aim->submit();
}
} else {
}
if (dlg != NULL ) delete dlg; dlg = NULL;
}
void Karia2::onShowCategoryProperty()
{
int er;
QItemSelectionModel * ism = this->mCatView->selectionModel();
if (ism->selectedIndexes().size() == 0 ) return;
CatPropDlg * dlg = new CatPropDlg (this );
dlg->setCategoryModel(this->mCatView->selectionModel()->selectedIndexes().at(0));
SqliteStorage * storage = SqliteStorage::instance(this);
int cat_id = this->mCatView->selectionModel()->selectedIndexes().at(ng::cats::cat_id).data().toInt();
dlg->setCategoryParameters(
storage->getSubCatCountById(cat_id),
storage->getTotalFileCountById(cat_id),
storage->getDownloadedFileCountById(cat_id),
storage->getTotalDownloadedLength(cat_id)
);
er = dlg->exec(); //show it
if (er == QDialog::Accepted) {
//qLogx()<<dlg->getCatModel();
} else {
}
delete dlg;
}
void Karia2::onDeleteCategory()
{
// QItemSelectionModel * ism;
QModelIndexList mil;
QModelIndex idx , parent;
mil = this->mCatView->selectionModel()->selectedIndexes();
if (mil.size() > 0) {
idx = mil.at(0);
if (idx == this->mCatViewModel->index(0,0)) return; //can not delete the default category
if (idx == this->mCatViewModel->index(0,0, this->mCatViewModel->index(0,0))) return;
if (idx == this->mCatViewModel->index(1,0, this->mCatViewModel->index(0,0))) return;
if (idx == this->mCatViewModel->index(2,0, this->mCatViewModel->index(0,0))) return;
if (QMessageBox::question(this, tr("Delete Category:"),
tr("Delete the Category and All sub Category?"),
QMessageBox::Ok, QMessageBox::Cancel) == QMessageBox::Cancel) {
return;
}
parent = idx.parent();
this->mCatViewModel->removeRows(idx.row(),1,parent);
//this->mCatView->collapse(parent);
//this->mCatView->expand(parent);
}
}
void Karia2::onCategoryMoveTo()
{
// QItemSelectionModel * ism;
QModelIndexList mil , milto;
QModelIndex idx , parent;
mil = this->mCatView->selectionModel()->selectedIndexes();
if (mil.size() > 0)
{
idx = mil.at(0);
if (idx == this->mCatViewModel->index(0,0)) return; //不移动系统默认分类。
if (idx == this->mCatViewModel->index(0,0, this->mCatViewModel->index(0,0))) return;
if (idx == this->mCatViewModel->index(1,0, this->mCatViewModel->index(0,0))) return;
if (idx == this->mCatViewModel->index(2,0, this->mCatViewModel->index(0,0))) return;
CatManDlg * cmd = new CatManDlg(this);
cmd ->changeMoveToState(mil);
if (cmd->exec() == QDialog::Accepted)
{
milto = cmd->getSelectionModel()->selectedIndexes();
if (milto.size() == 0 ) return; // no cat selected
if (milto == mil ) return;
//if milto is child of subchild of from , then return; do this in next line function .
//this->mCatViewModel->rowMoveTo(mil.at(0),milto.at(0));
parent = idx.parent();
this->mCatView->collapse(parent);
this->mCatView->expand(parent);
this->mCatView->collapse(milto.at(0));
this->mCatView->expand(milto.at(0));
this->mCatView->resizeColumnToContents(0);
}
delete cmd;
}
}
void Karia2::onShowColumnEditor()
{
QDialog *dlg = new ColumnsManDlg(this);
QObject::connect(dlg, SIGNAL(taskShowColumnsChanged(QString)),
this, SLOT(onTaskShowColumnsChanged(QString)));
dlg->exec();
delete dlg;
}
//void Karia2::initXmlRpc()
//{
// if (this->mAriaRpc == NULL) {
// // the default port is 6800 on best case, change to 6800+ if any exception.
// this->mAriaRpc = new MaiaXmlRpcClient(QUrl(QString("http://127.0.0.1:%1/rpc").arg(this->mAriaMan->rpcPort())));
// // get version and session
// // use aria2's multicall method. note: has moved to AriaMan
// // QVariantMap getVersion;
// // QVariantMap getSession;
// // QVariantList gargs;
// // QVariantList args;
// // QVariantMap options;
// // QVariant payload;
// // getVersion["methodName"] = QString("aria2.getVersion");
// // getVersion["params"] = QVariant(options);
// // getSession["methodName"] = QString("aria2.getSessionInfo");
// // getSession["params"] = QVariant(options);
// // args.insert(0, getVersion);
// // args.insert(1, getSession);
// // gargs.insert(0, args);
// // this->mAriaRpc->call(QString("system.multicall"), gargs, payload,
// // this, SLOT(onAriaMultiCallVersionSessionResponse(QVariant&, QVariant&)),
// // this, SLOT(onAriaMultiCallVersionSessionFault(int, QString, QVariant &)));
// }
//}
//QMap<QString, QVariant> Karia2::taskOptionToAria2RpcOption(TaskOption *to)
//{
// Q_ASSERT(to != NULL);
// QMap<QString, QVariant> aopts;
// if (!to->mReferer.isEmpty()) {
// aopts["referer"] = to->mReferer;
// } else {
// aopts["referer"] = to->mTaskUrl;
// }
// if (!to->mSavePath.isEmpty()) {
// aopts["dir"] = to->mSavePath;
// }
// if (to->mSplitCount > 0) {
// aopts["split"] = QString("%1").arg(to->mSplitCount);
// }
// if (!to->mCookies.isEmpty()) {
// QVariantList header;
// header << QString("Cookie: %1").arg(to->mCookies);
// aopts["header"] = header;
// if (!to->mReferer.isEmpty()) {
// header << QString("Referer: %1").arg(to->mReferer);
// }
// if (!to->mAgent.isEmpty()) {
// header << QString("User-Agent: %1").arg(to->mAgent);
// }
// }
// return aopts;
//}
/////////////
void Karia2::onShowOptions()
{
QDialog *dlg = new PreferencesDialog(this);
dlg->exec();
delete dlg;
}
// void Karia2::onShowConnectOption()
// {
// OptionDlg *dlg = new OptionDlg(this);
// dlg->exec();
// delete dlg;
// }
// void Karia2::onShowDefaultDownloadProperty()
// {
// taskinfodlg *tid = new taskinfodlg(0,0);
// //tid->setRename(fname);
// int er = tid->exec();
// delete tid;
// }
void Karia2::onEditSelectAll()
{
qLogx()<<__FUNCTION__;
QWidget * wg = focusWidget ();
if (wg == this->mainUI->mui_tv_task_list) {
this->mainUI->mui_tv_task_list->selectAll();
} else if (wg == this->mainUI->mui_tv_seg_log_list ) {
this->mainUI->mui_tv_seg_log_list->selectAll();
}
qLogx()<<wg;
}
void Karia2::onEditInvertSelect()
{
qLogx()<<__FUNCTION__;
QWidget * wg = focusWidget ();
QModelIndex idx;
QTreeView *tv;
QItemSelectionModel *sm;
if (wg == this->mainUI->mui_tv_task_list)
{
tv = this->mainUI->mui_tv_task_list;
}
else if (wg == this->mainUI->mui_tv_seg_log_list )
{
tv = this->mainUI->mui_tv_seg_log_list;
}
else
{
return;
}
sm = tv->selectionModel();
QList<int> subrows;
int rows = tv->model()->rowCount();
// int cols = tv->model()->columnCount();
for (int i = 0;i < rows; i ++ )
{
idx = tv->model()->index(i,0);
if (sm->isRowSelected(i,QModelIndex()) )
{
}
else
{
subrows.append(i);
}
}
sm->clear();
for (int i = 0; i < subrows.size();i ++)
{
sm->select(tv->model()->index(subrows[i],0),QItemSelectionModel::Select|QItemSelectionModel::Rows);
}
qLogx()<<wg;
}
void Karia2::onShowToolbarText(bool show)
{
if (show )
{
this->setToolButtonStyle(Qt::ToolButtonTextUnderIcon);
}
else
{
this->setToolButtonStyle(Qt::ToolButtonIconOnly);
}
}
void Karia2::onCopyUrlToClipboard()
{
qLogx()<<__FUNCTION__;
QItemSelectionModel * ism = 0;
QModelIndexList mil;
ism = this->mTaskListView->selectionModel();
if (ism != 0) {
mil = ism->selectedIndexes();
QString url = mil.at(ng::tasks::real_url).data().toString();
QClipboard * cb = QApplication::clipboard();
cb->setText(url);
}
}
////////////
void Karia2::onCopySelectSegLog()
{
qLogx()<<__FUNCTION__;
QModelIndex idx;
// QTreeView *tv;
QItemSelectionModel *sm;
QString text;
QModelIndexList mil;
int cols = 0;
if (this->mSegLogListView->model() != 0 )
{
cols = this->mSegLogListView->model()->columnCount();
sm = this->mSegLogListView->selectionModel();
mil = sm->selectedIndexes();
for (int r = 0; r < mil.size()/cols; r++ )
{
for (int c = 0; c < cols; ++c )
{
text += mil.value(r+c*mil.size()/cols).data().toString();
text += '\t';
}
text += "\r\n";
}
if (text.endsWith("\r\n"))
text = text.left(text.length()-2);
//
QClipboard *cb = QApplication::clipboard();
cb->setText(text);
}
qLogx()<<cols<<text <<mil.size();
}
void Karia2::onSaveSegLog()
{
QModelIndex idx;
// QTreeView *tv;
// QItemSelectionModel *sm;
QString text;
QModelIndexList mil;
QAbstractItemModel * model = 0;
int cols = 0;
model = this->mSegLogListView->model();
if (model != 0 )
{
cols = model->columnCount();
for (int r = 0; r < model->rowCount(); ++r)
{
for (int c = 0; c < cols; ++ c)
{
text += model->data(model->index(r,c)).toString();
text += '\t';
}
text += "\r\n";
}
if (text.endsWith("\r\n"))
text = text.left(text.length()-2);
//
QString fname = QFileDialog::getSaveFileName(this);
if (! fname.isNull() )
{
QFile fi(fname);
fi.open(QIODevice::WriteOnly|QIODevice::Unbuffered);
fi.write(text.toLatin1());
//fi.waitForBytesWritten();
fi.close();
}
}
}
/**
* 清除线程日志视图中的LOG信息。
*/
void Karia2::onClearSegLog() //
{
QAbstractItemModel * aim = 0;
int row;
aim = this->mSegLogListView->model();
if (aim == 0 ) return; //没有日志,直接返回
row = aim->rowCount();
for (int i = row - 1; i >=0; i --)
{
aim->removeRows(i,1);
}
// replace or short stmt
row = aim->rowCount();
if (row > 0 )
aim->removeRows(0,row);
}
/////language
/**
* Qt 的这种语言处理方式不能在程序运行时动态修改,需要另一种比较麻烦的方法实现,详见Qt 手册。
* 已经修改为支持动态语言切换了
*/
void Karia2::onSwitchLanguage(QAction* action)
{
QString lang = "en_US"; //默认
//if (action == this->mainUI->action_Chinese_simple)
//{
// qLogx()<<"switch lang: zh_CN";
// lang = "zh_CN";
//}
//if (action == this->mainUI->action_English)
//{
// qLogx()<<"switch lang: en_US";
// lang = "en_US";
//}
lang = action->data().toString();
if (lang.isEmpty() )
lang = "en_US"; //默认
//QTranslator translator;
//translator.load(QString("karia2_")+lang);
//qApp->installTranslator(&translator);
QString langFile = QString("karia2_")+lang;
appTranslator.load(langFile , qmPath );
//qLogx()<<"Loading file :"<<langFile;
langFile = "qt_"+lang;
qtTranslator.load(langFile,qmPath);
//qLogx()<<"Loading file :"<<langFile;
if (! action->isChecked()) {
action->setChecked(true);
}
this->retranslateUi();
}
void Karia2::onSwitchSkinType(QAction* action)
{
Q_UNUSED(action);
}
////////////style
//"windows", "motif", "cde", "plastique", "windowsxp", or "macintosh"
// ("Bespin", "Oxygen", "Windows", "Motif", "CDE", "Plastique", "GTK+", "Cleanlooks")
void Karia2::onSwitchWindowStyle(QAction * action )
{
qLogx()<<__FUNCTION__<<":"<<__LINE__<<" typeL "<< action->data().toString()
<< this->sender();
// QStringList styleKeys = QStyleFactory::keys();
// qLogx()<<styleKeys;
QApplication::setStyle(action->data().toString());
if (mainUI->action_Default_Palette->isChecked()) {
QApplication::setPalette(this->orginalPalette);
} else {
QApplication::setPalette(QApplication::style()->standardPalette());
}
if (! action->isChecked()) {
action->setChecked(true);
}
}
void Karia2::onSwitchSpeedMode(QAction *action)
{
qLogx()<<__FUNCTION__;
QString speedLimitType = "unlimited";
if (action == mainUI->action_Unlimited) {
this->onManualSpeedChanged(0); // set no limit
this->mStatusBar->displaySpeedModeControl(speedLimitType);
} else if (action == mainUI->action_Manual) {
// TODO 弹出设置速度对话框
speedLimitType = "manual";
this->mStatusBar->displaySpeedModeControl(speedLimitType);
} else if (action == mainUI->action_Automatic ) {
this->onManualSpeedChanged(0); // no limit now
speedLimitType = "auto";
this->mStatusBar->displaySpeedModeControl(speedLimitType);
}
if (this->mainUI->action_Remember->isChecked()) {
OptionManager::instance()->saveSpeedLimitType(speedLimitType);
}
}
void Karia2::onRememberSpeedLimitSetting(bool checked)
{
OptionManager *om = NULL;
QString value;
om = OptionManager::instance();
value = om->getRememberSpeedLimit();
if (checked && value == "false") {
om->saveRememberSpeedLimit("true");
if (this->mainUI->action_Unlimited->isChecked()) {
om->saveSpeedLimitType("unlimited");
} else if (this->mainUI->action_Manual->isChecked()) {
om->saveSpeedLimitType("manual");
om->saveSpeedLimitSpeed(QString::number(this->mStatusBar->speedValue()));
} else if (this->mainUI->action_Automatic->isChecked()) {
om->saveSpeedLimitType("auto");
}
}
if (!checked && value == "true") {
om->saveRememberSpeedLimit("false");
}
}
// TODO call many time when drap the speed slider bar
// need a accelerate slider
void Karia2::onManualSpeedChanged(int value)
{
//qLogx()<<__FUNCTION__;
// GlobalOption::instance()->mMaxLimitSpeed = value * 1024; //the value is KB in unit
//this->initXmlRpc();
QVariant payload;
QVariantList args;
QVariantMap options;
options["max-overall-download-limit"] = QString("%1K").arg(value); // .arg(value * 1024);
payload = QString("max-overall-download-limit");
args.insert(0, options);
// this->mAriaRpc->call("aria2.changeGlobalOption", args, payload,
// this, SLOT(onAriaChangeGlobalOptionResponse(QVariant &, QVariant &)),
// this, SLOT(onAriaChangeGlobalOptionFault(int, QString, QVariant &)));
int revalue = value * 1000; // ::cos(value * 0.01);
this->mAria2Manager->setSpeedLimit(revalue, revalue); // 参数单位:B/s
if (this->mainUI->action_Remember->isChecked()) {
OptionManager::instance()->saveSpeedLimitSpeed(QString::number(revalue));
}
}
////////////
void Karia2::showAboutDialog()
{
AboutDialog *pAboutDialog = new AboutDialog(this);
pAboutDialog->exec();
delete pAboutDialog;
}
void Karia2::onGotoHomePage()
{
QString homepage = "http://www.qtchina.net/";
QDesktopServices::openUrl(homepage);
}
/**
* 隐藏或者显示主窗口。
* 这是一个翻转开关,是显示还是隐藏依赖于主窗口当前是否显示。
*/
void Karia2::onDropZoneDoubleClicked()
{
qLogx()<<__FUNCTION__;
if (this->isHidden () )
{
this->setHidden(false);
this->showNormal();
this->setFocus();
this->raise();
this->activateWindow();
}
else
{
this->showMinimized();
this->setHidden(true);
}
}
void Karia2::onDropZoneCustomMenu(const QPoint & pos)
{
Q_UNUSED(pos);
this->mDropZonePopupMenu->popup(QCursor::pos());
}
void Karia2::onOpenDistDirector()
{
qLogx()<<__FUNCTION__;
QString openner;
QString tmp;
QString dir;
int taskId = -1;
int catId = -1;
QItemSelectionModel * ism = 0;
QModelIndexList mil;
QString durl;
ism = this->mTaskListView->selectionModel();
mil = ism->selectedIndexes();
if (mil.size() > 0) {
taskId = mil.at(ng::tasks::task_id).data().toString().toInt();
catId = mil.at(ng::tasks::user_cat_id).data().toString().toInt();
dir = mil.at(ng::tasks::save_path).data().toString();
if (dir.startsWith("~")) {
dir = QDir::homePath() + dir.right(dir.length() - 1);
}
durl = dir;
bool opened = QDesktopServices::openUrl(durl); //only qt >= 4.2
if (!opened) {
opened = QDesktopServices::openUrl(QUrl("file://" + durl));
}
} else {
QMessageBox::warning(this, tr("No Task Selected"), tr("Please Select a Task For Operation"));
}
}
void Karia2::onOpenExecDownloadedFile()
{
qLogx()<<__FUNCTION__;
QString tmp;
QString dir, fname;
int taskId = -1;
int catId = -1;
QItemSelectionModel * ism = 0;
QModelIndexList mil;
QString durl;
ism = this->mTaskListView->selectionModel();
mil = ism->selectedIndexes();
if (mil.size() > 0) {
taskId = mil.at(ng::tasks::task_id).data().toString().toInt();
//this->mTaskListViewModel->data(mil.at(0)).toInt();
catId = mil.at(ng::tasks::user_cat_id).data().toString().toInt();
fname = mil.at(ng::tasks::file_name).data().toString();
dir = mil.at(ng::tasks::save_path).data().toString();
if (dir.startsWith("~")) {
dir = QDir::homePath() + dir.right(dir.length() - 1);
}
durl = dir + QString("/") + fname;
QString fullUrl = QDir().absoluteFilePath(durl);
if (fname .length() == 0 || ! QDir().exists(fullUrl)) {
QMessageBox::warning(this, tr("Notice:"),
QString(tr("File <b>%1</b> not found, has it downloaded already?")).arg(fullUrl));
} else {
//QProcess::execute(openner);
bool opened = QDesktopServices::openUrl(fullUrl); //only qt >= 4.2
if (!opened) {
opened = QDesktopServices::openUrl(QUrl("file://" + fullUrl));
}
}
} else {
QMessageBox::warning(this, tr("No Task Selected"), tr("Please Select a Task For Operation"));
}
}
void Karia2::onOpenRefererUrl()
{
QString tmp;
QString dir, fname, referer;
int taskId = -1;
int catId = -1;
QItemSelectionModel * ism = 0;
QModelIndexList mil;
QString durl;
ism = this->mTaskListView->selectionModel();
mil = ism->selectedIndexes();
if (mil.size() > 0) {
taskId = mil.at(ng::tasks::task_id).data().toString().toInt();
catId = mil.at(ng::tasks::user_cat_id).data().toString().toInt();
fname = mil.at(ng::tasks::file_name).data().toString();
referer = mil.at(ng::tasks::referer).data().toString();
QDesktopServices::openUrl(QUrl(referer));
} else {
QMessageBox::warning(this, tr("No Task Selected"), tr("Please Select a Task For Operation"));
}
}
//////////private
//
void Karia2::onClipBoardDataChanged()
{
QClipboard *cb = QApplication::clipboard();
QString text = cb->text();
qLogx()<<cb->mimeData()->formats();
if (text.length() > 0) {
QUrl uu(text);
if (uu.scheme().toUpper().compare("HTTP") == 0
|| uu.scheme().toUpper().compare("HTTPS") == 0
|| uu.scheme().toUpper().compare("FTP") == 0
|| text.startsWith("magnet:?", Qt::CaseInsensitive)
|| text.startsWith("flashget", Qt::CaseInsensitive)
|| text.startsWith("qqdl:", Qt::CaseInsensitive)
|| text.startsWith("thunder:", Qt::CaseInsensitive)
|| text.startsWith("karia2://", Qt::CaseInsensitive)) {
// this->showNewDownloadDialog(); // Open sometime later
}
if (text.startsWith("karia2://", Qt::CaseInsensitive)) {
this->showNewDownloadDialog(); // this should be karia2 passed from browser, force handle it
}
}
qLogx()<<text;
}
void Karia2::paintEvent (QPaintEvent * event )
{
Q_UNUSED(event);
QPainter painter(this);
QPoint p(0, 0);
if (this->image.isNull()) {
this->image =QImage("4422b46f9b7e5389963077_zVzR8Bc2kwIf.jpg");
//qLogx()<<this->mCatView->windowOpacity();
//this->mCatView->setWindowOpacity(0.5);
//qLogx()<<this->mCatView->windowOpacity();
this->mainUI->splitter_4->setWindowOpacity(0.3);
this->mainUI->splitter_3->setWindowOpacity(0.5);
this->mainUI->splitter_2->setWindowOpacity(0.8);
this->mainUI->splitter->setWindowOpacity(0.6);
//this->setWindowOpacity(0.7);
// QPixmap pixmap("4422b46f9b7e5389963077_zVzR8Bc2kwIf.jpg");
//this->mCatView->setPixmap(pixmap);
}
//painter.drawImage(p, this->image );
//this->setWindowOpacity(0.6); //ok
}
/**
*
* show user exit.
* clean data, save state
*/
void Karia2::closeEvent (QCloseEvent * event )
{
qLogx()<<this->sender();
//qLogx()<< static_cast<QApplication*>(QApplication::instance())->quitOnLastWindowClosed ();
if (this->sender() == 0) {
// 点击右上角的X号, 或者Alt+F4,将该行为转成窗口最小化,隐藏到系统托盘区域
this->mainUI->action_Show_Hide_Main_Widow->trigger();
event->setAccepted(false);
} else if (this->sender()->objectName() == "actionQuit") {
event->setAccepted(true); //不再传递了
qApp->quit();
return;
} else {//通过点击退出菜单,可认为用户是想退出的。
//if (QMessageBox::question(this,"Are you sure?","Exit Karia2 Now.",QMessageBox::Ok,QMessageBox::Cancel) == QMessageBox::Cancel )
{
// event->setAccepted(false); //不再传递了
// return;
}
if (this->mWalkSiteWnd != 0) { //the other main window , close it here
this->mWalkSiteWnd->close();
delete this->mWalkSiteWnd;
this->mWalkSiteWnd = 0;
}
if (this->mHWalkSiteWndEx != 0) { //the other main window , close it here
this->mHWalkSiteWndEx->close();
delete this->mHWalkSiteWndEx;
this->mHWalkSiteWndEx = 0;
}
//清理托盘图标
delete this->mSysTrayIcon;this->mSysTrayIcon = 0;
QApplication::setQuitOnLastWindowClosed(true);
event->setAccepted(true );
QMainWindow::closeEvent(event);
}
}
void Karia2::showEvent (QShowEvent * event )
{
QWidget::showEvent(event);
qLogx()<<__FUNCTION__<<__LINE__<<"first show";
//qLogx()<<__FUNCTION__<<__LINE__<<rand();
if (firstShowEvent == true) {
firstShowEvent = false;
//添加首次显示要处理的工作
qLogx()<<__FUNCTION__<<__LINE__<<"first show";
//this->firstShowHandler();
// QTimer::singleShot(30, this, SLOT(firstShowHandler()));
this->mAtask = new AsyncTask(this);
this->mAtask->start();
}
}
/*
#if defined(Q_OS_WIN)
bool Karia2::winEvent (MSG * msg, long * result )
{
//qLogx()<<__FUNCTION__<<__LINE__<<rand();
//whereis MOD_CONTROL ???
// shutcut: CTRL+SHIFT+C
if (msg->message == WM_HOTKEY) {
switch(msg->wParam) {
case 'C':
//做想做的事。我想用它抓图,哈哈,完全可以啊。
this->shootScreen();
qLogx()<<msg->message <<"xxx"<<(int)('G')<<":"<<msg->wParam<<" lp:"<< msg->lParam;
break;
default:
break;
}
}
return QMainWindow::winEvent(msg, result);
}
#elif defined(Q_OS_MAC)
bool Karia2::macEvent (EventHandlerCallRef caller, EventRef event )
{
return QMainWindow::macEvent(caller, event);
}
#else
bool Karia2::x11Event (XEvent * event )
{
//qLogx()<<"XEvent->type:"<< event->type;
if (event->type == PropertyNotify) {
//qLogx()<<"dont push button";
}
return QMainWindow::x11Event(event);
}
void Karia2::keyReleaseEvent (QKeyEvent * event )
{
// shortcut: CTRL+G
if (event->modifiers() == Qt::ControlModifier) {
//qLogx()<<"with ctrl key ";
if (event->key() == Qt::Key_G) {
//qLogx()<<"key released: " << event->text();
this->shootScreen();
}
}
return QMainWindow::keyReleaseEvent(event);
}
#endif
*/
bool Karia2::nativeEvent(const QByteArray &eventType, void *message, long *result)
{
return QMainWindow::nativeEvent(eventType, message, result);
}
void Karia2::shootScreen()
{
QPixmap screenSnapShot = QPixmap::grabWindow(QApplication::desktop()->winId());
QString format = "png";
QString fileName = QString("abcd" ) + "."+format;
if (! QFile::exists(fileName)) {
QFile ff(fileName);
ff.open(QIODevice::ReadWrite|QIODevice::Unbuffered);
ff.close();
}
if (! screenSnapShot.save(fileName, format.toLatin1())) {
qLogx()<< "save screen snap shot error:"<<fileName;
}
}
//system tray slot handler
void Karia2::onActiveTrayIcon(QSystemTrayIcon::ActivationReason index )
{
qLogx()<<__FUNCTION__ << index;
if (index == QSystemTrayIcon::DoubleClick )
{
this->mainUI->action_Show_Hide_Main_Widow->trigger();
this->raise();
}
else if (index == QSystemTrayIcon::Context )
{
}
else if (index == QSystemTrayIcon::Trigger )
{
}
else if (index == QSystemTrayIcon::Unknown )
{
}
}
/**
* 系统托盘弹出的泡泡状消息窗口被点击时处理函数
*/
void Karia2::onBallonClicked()
{
qLogx()<<__FUNCTION__;
}
void Karia2::onShowWalkSiteWindow()
{
//将搜索窗口集成到主窗口中,不再需要显示这个窗口了。将下面到hide几行删除,release编译出来的程序会小60多K。
//if (this->mWalkSiteWnd == 0 )
//{
// this->mWalkSiteWnd = new WalkSiteWnd(this);
//}
//this->mWalkSiteWnd->showMinimized();
//this->mWalkSiteWnd->hide();
if (this->mHWalkSiteWndEx == 0 )
{
this->mHWalkSiteWndEx = new WalkSiteWndEx(this);
//本模块接收音乐下载的信号
}
this->mHWalkSiteWndEx->showMinimized();
this->mHWalkSiteWndEx->hide();
//////////停靠窗口重叠属性为可以重叠
if (! this->isDockNestingEnabled() )
{
this->setDockNestingEnabled(true);
}
//先将窗口最大化,如果不是的话。
if (! this->isMaximized() )
{
//this->showMaximized();
}
///next 集成到主窗口的依靠窗口的搜索窗口初始化/显示。
if (this->mWalkSiteDockWidget == 0 )
{
//this->mWalkSiteDockWidget = new QDockWidget(tr(" Site Crawler "), this);
this->mWalkSiteDockWidget = new QDockWidget(this->mHWalkSiteWndEx->windowTitle(), this);
this->mWalkSiteDockWidget->setAllowedAreas(Qt::BottomDockWidgetArea);
this->mWalkSiteDockWidget->setFeatures(QDockWidget::DockWidgetClosable|QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable);
this->mWalkSiteDockWidget->setFloating(false);
this->addDockWidget(Qt::BottomDockWidgetArea, this->mWalkSiteDockWidget,Qt::Horizontal);
this->mWalkSiteDockWidget->showMinimized();
this->mWalkSiteDockWidget->showNormal();
//如果检测到有另一个窗口存在,可以浮动起来该窗口,再检测一个合适的位置停靠,估计能实现那种带TAB的浮动窗口效果。
}
if (this->mWalkSiteDockWidget->widget() != this->mHWalkSiteWndEx )
{
this->mWalkSiteDockWidget->setWidget(this->mHWalkSiteWndEx);
}
this->mHWalkSiteWndEx->showMinimized();
qLogx()<< this->mWalkSiteDockWidget->isHidden();
if (this->mWalkSiteDockWidget->isHidden() )
this->mWalkSiteDockWidget->showMinimized();
}
void Karia2::onTaskLogArrived(QString log)
{
if (log.length() <= 2) {
return;
}
// this->mainUI->plainTextEdit->appendPlainText(log.trimmed());
}
/////////////////////
//// task ui
/////////////////////
/**
* access private
*/
int Karia2::getNextValidTaskId()
{
int taskId = -1;
SqliteStorage * storage = SqliteStorage::instance(this);
// storage->open();
taskId = storage->getNextValidTaskID();
if (taskId <= 0) {
qLogx()<<"Invalid new task id:" << taskId;
exit(-1);
}
return taskId;
}
/**
* overload method
*/
int Karia2::createTask(TaskOption *option)
{
//precondition:
assert(option != 0 );
int taskId = -1;
taskId = this->getNextValidTaskId();
//qLogx()<<this->mTaskQueue << __FUNCTION__ << "in " <<__FILE__;
if (taskId >= 0) {
// cacl the downloading model index
QItemSelection readySelect, readDeselect;
QModelIndex topCatIdx = this->mCatViewModel->index(0, 0);
qLogx()<<topCatIdx.data();
int l2RowCount = this->mCatViewModel->rowCount(topCatIdx);
qLogx()<<l2RowCount;
for (int r = 0 ; r < l2RowCount ; r ++) {
QModelIndex currCatIdx = this->mCatViewModel->index(r, ng::cats::cat_id, topCatIdx);
qLogx()<<currCatIdx;
if (currCatIdx.data().toInt() == ng::cats::downloading) {
// for (int c = 0; c <= ng::cats::dirty; c ++) {
// QModelIndex readyIndex = this->mCatViewModel->index(r, c, topCatIdx);
// readySelect.select(readyIndex, readyIndex);
// }
readySelect.select(this->mCatViewModel->index(r, 0, topCatIdx),
this->mCatViewModel->index(r, ng::cats::dirty, topCatIdx));
break;
}
}
this->mCatView->selectionModel()->select(readySelect, QItemSelectionModel::ClearAndSelect);
////将任务信息添加到 task list view 中
//QModelIndex index;
//QAbstractItemModel * mdl = 0; //SqliteTaskModel::instance(ng::cats::downloading, this);
// TaskQueue::addTaskModel(taskId, option);
this->mTaskMan->addTaskModel(taskId, option);
//在这里可以查看当前活动的任务数,并看是否需要启动该任务。
//而在onTaskDone槽中可以查看当前活动的任务数,看是否需要调度执行其他的正在等待的任务。
// this->onStartTask(taskId); //为了简单我们直接启动这个任务
//
}
return taskId;
}
int Karia2::createTask(int taskId, TaskOption *option)
{
this->mTaskMan->addTaskModel(taskId, option);
return taskId;
}
void Karia2::onTaskShowColumnsChanged(QString columns)
{
//////
QStringList colList;
QString taskShowColumns = columns;
// qLogx()<<__FUNCTION__<<taskShowColumns<<(ng::tasks::aria_gid);
if (taskShowColumns != "") {
colList = taskShowColumns.split(',');
for (int i = ng::tasks::task_id ; i <= ng::tasks::aria_gid; ++i) {
// qLogx()<<"show col:"<<colList.contains(QString::number(i));
if (!colList.contains(QString::number(i))) {
this->mainUI->mui_tv_task_list->setColumnHidden(i, true);
} else {
this->mainUI->mui_tv_task_list->setColumnHidden(i, false);
}
}
if (this->mCustomTaskShowColumns != columns) {
this->mCustomTaskShowColumns = columns;
}
}
}
void Karia2::onAddTaskList(QStringList list)
{
////建立任务
QString taskUrl = list.at(0);
TaskOption * to = 0; //创建任务属性。
taskinfodlg *tid = new taskinfodlg(this);
tid->setTaskUrl(taskUrl);
int er = tid->exec();
//taskUrl = tid->taskUrl();
//segcnt = tid->segmentCount();
//to = tid->getOption(); //
if (er == QDialog::Accepted)
{
//this->createTask(url,segcnt);
//这里先假设用户使用相同的设置。
//delete to; to = 0;
for (int t = 0; t <list.size(); ++ t )
{
taskUrl = list.at(t);
qLogx()<<taskUrl;
tid->setTaskUrl(taskUrl );
to = tid->getOption();
this->createTask(to );
}
}
else
{
//delete to; to = 0;
}
delete tid;
}
QString Karia2::decodeThunderUrl(QString enUrl)
{
// like thunder://QUFodHRwOi8vZG93bi41MnouY29tLy9kb3duL3JhbWRpc2sgdjEuOC4yMDAgZm9yIHdpbnhwIMbGveKw5i5yYXJaWg==
QTextCodec *u8codec = QTextCodec::codecForName("GBK");
Q_ASSERT(u8codec != NULL);
QByteArray bUrl = QByteArray::fromBase64(enUrl.right(enUrl.length() - 10).toLatin1());
QString deUrl = (u8codec == NULL) ? bUrl : u8codec->toUnicode(bUrl);
deUrl = deUrl.mid(2, deUrl.length() - 4);
return deUrl;
}
QString Karia2::decodeQQdlUrl(QString enUrl)
{
// like: qqdl://aHR0cDovL3d3dy5sZXZpbC5jbg== , “[url]http://www.levil.cn[/url]”
QTextCodec *u8codec = QTextCodec::codecForName("GBK");
Q_ASSERT(u8codec != NULL);
int pos = enUrl.indexOf("&");
QString enArgs;
if (pos != -1) {
enArgs = enUrl.right(enUrl.length() - pos);
enUrl = enUrl.left(pos);
}
QByteArray bUrl = QByteArray::fromBase64(enUrl.right(enUrl.length() - 7).toLatin1());
QString deUrl = (u8codec == NULL) ? bUrl : u8codec->toUnicode(bUrl);
deUrl = deUrl.mid(7, deUrl.length() - 15);
return deUrl;
return QString();
}
QString Karia2::decodeFlashgetUrl(QString enUrl)
{
// like flashget://W0ZMQVNIR0VUXWZ0cDovL2R5Z29kMTpkeWdvZDFAZDAzMy5keWdvZC5vcmc6MTA1OS8lRTUlQTQlQUElRTUlQjklQjMlRTYlQjQlOEIlRTYlODglOTglRTQlQkElODklNUIxMDI0JUU1JTg4JTg2JUU4JUJFJUE4JUU3JThFJTg3LiVFNCVCOCVBRCVFOCU4QiVCMSVFNSU4RiU4QyVFNSVBRCU5NyU1RC8lNUIlRTclOTQlQjUlRTUlQkQlQjElRTUlQTQlQTklRTUlQTAlODJ3d3cuZHkyMDE4Lm5ldCU1RCVFNSVBNCVBQSVFNSVCOSVCMyVFNiVCNCU4QiVFNiU4OCU5OCVFNCVCQSU4OSVFNyVBQyVBQzA0JUU5JTlCJTg2JTVCJUU0JUI4JUFEJUU4JThCJUIxJUU1JThGJThDJUU1JUFEJTk3JTVELnJtdmJbRkxBU0hHRVRd&18859&1270484198847
QTextCodec *u8codec = QTextCodec::codecForName("GBK");
Q_ASSERT(u8codec != NULL);
int pos = enUrl.indexOf("&");
QString enArgs;
if (pos != -1) {
enArgs = enUrl.right(enUrl.length() - pos);
enUrl = enUrl.left(pos);
}
QByteArray bUrl = QByteArray::fromBase64(enUrl.right(enUrl.length() - 11).toLatin1());
QString deUrl = (u8codec == NULL) ? bUrl : u8codec->toUnicode(bUrl);
deUrl = deUrl.mid(10, deUrl.length() - 20);
if (deUrl.toLower().startsWith("flashget://")) {
deUrl = decodeFlashgetUrl(deUrl);
}
if (deUrl.toLower().startsWith("flashgetx://")) {
qLogx()<<"Unsupported protocol type."<<deUrl;
}
return deUrl;
}
QString Karia2::decodeEncodeUrl(QString enUrl)
{
if (enUrl.toLower().startsWith("thunder://")) {
return decodeThunderUrl(enUrl);
}
if (enUrl.toLower().startsWith("flashget://")) {
return decodeFlashgetUrl(enUrl);
}
if (enUrl.toLower().startsWith("qqdl://")) {
return decodeQQdlUrl(enUrl);
}
return enUrl;
}
/////////////
/**
*
*/
void Karia2::showNewDownloadDialog()
{
QString url;
int segcnt = 7;
TaskOption * to = 0; //创建任务属性。
taskinfodlg *tid = new taskinfodlg(this);
int er = tid->exec();
url = tid->taskUrl();
segcnt = tid->segmentCount();
to = tid->getOption(); //
delete tid;
QString deUrl = decodeEncodeUrl(url);
qLogx()<<"Decode url: "<<segcnt<<url<<deUrl;
if (url != deUrl) {
to->setUrl(deUrl);
url = deUrl;
}
if (er == QDialog::Accepted) {
int taskId = this->createTask(to);
qLogx()<<segcnt<<url<<taskId;
//this->initXmlRpc();
// payload type
QMap<QString, QVariant> payload;
payload["taskId"] = QString("%1").arg(taskId);
payload["url"] = url;
QVariantList args;
QList<QVariant> uris;
uris << QString(url);
args.insert(0, uris);
QMap<QString, QVariant> options ;//= this->taskOptionToAria2RpcOption(to);
// options["split"] = QString("2");
args.insert(1, options);
// this->mAriaRpc->call(QString("aria2.addUri"), args, QVariant(payload),
// this, SLOT(onAriaAddUriResponse(QVariant &, QVariant &)),
// this, SLOT(onAriaAddUriFault(int, QString, QVariant &)));
// if (!this->mAriaUpdater.isActive()) {
// this->mAriaUpdater.setInterval(3000);
// QObject::connect(&this->mAriaUpdater, SIGNAL(timeout()), this, SLOT(onAriaUpdaterTimeout()));
// this->mAriaUpdater.start();
// }
// this->mEAria2Man->addUri(taskId, url, to);
this->mAria2Manager->addTask(taskId, url, to);
} else {
delete to; to = 0;
}
qLogx()<<segcnt<<url;
}
// TODO, test with a invalid torrent file
void Karia2::showNewBittorrentFileDialog()
{
QString url;
url = QFileDialog::getOpenFileName(this, tr("Open a .torrent file..."), QString(),
tr("Torrent File (*.torrent)"), NULL, 0);
if (url == QString::null) {
// cancel
} else if (url.isEmpty()) {
// select 0 file?
} else {
TaskOption *to = new TaskOption(); // TODO get option from GlobalOption
to->setDefaultValue();
to->mCatId = ng::cats::downloading;
to->setUrl("file://" + url); //转换成本地文件协议
int taskId = this->createTask(to);
qLogx()<<__FUNCTION__<<url<<taskId;
//this->initXmlRpc();
QMap<QString, QVariant> payload;
payload["taskId"] = taskId;
payload["url"] = "file://" + url;
payload["cmd"] = QString("torrent_get_files");
// payload["taskOption"] = to->toBase64Data();
QFile torrentFile(url);
torrentFile.open(QIODevice::ReadOnly);
QByteArray torrentConntent = torrentFile.readAll();
torrentFile.close();
QVariantList args;
QList<QVariant> uris;
args.insert(0, torrentConntent);
args.insert(1, uris);
QMap<QString, QVariant> options;
// options["split"] = QString("1");
options["bt-max-peers"] = QString("1");
options["all-proxy"] = QString("127.0.0.1:65532"); // use a no usable proxy, let aria2 stop quick
options["select-file"] = QString("1");
options["dir"] = QDir::tempPath();
options["file-allocation"] = "none";
args.insert(2, options);
// this->mAriaRpc->call(QString("aria2.addTorrent"), args, QVariant(payload),
// this, SLOT(onAriaParseTorrentFileResponse(QVariant &, QVariant &)),
// this, SLOT(onAriaParseTorrentFileFault(int, QString, QVariant &)));
// this->mAriaRpc->call(QString("aria2.addTorrent"), args, QVariant(payload),
// this, SLOT(onAriaAddUriResponse(QVariant &, QVariant &)),
// this, SLOT(onAriaAddUriFault(int, QString, QVariant &)));
// if (!this->mAriaUpdater.isActive()) {
// this->mAriaUpdater.setInterval(3000);
// QObject::connect(&this->mAriaUpdater, SIGNAL(timeout()), this, SLOT(onAriaUpdaterTimeout()));
// this->mAriaUpdater.start();
// }
// if (!this->mAriaTorrentUpdater.isActive()) {
// this->mAriaTorrentUpdater.setInterval(4000);
// QObject::connect(&this->mAriaTorrentUpdater, SIGNAL(timeout()), this, SLOT(onAriaTorrentUpdaterTimeout()));
// this->mAriaTorrentUpdater.start();
// }
}
}
void Karia2::showNewMetalinkFileDialog()
{
QString url;
url = QFileDialog::getOpenFileName(this, tr("Open a .metalink file..."), QString(),
tr("Metalink File (*.metalink)"), NULL, 0);
if (url == QString::null) {
// cancel
} else if (url.isEmpty()) {
// select 0 file?
} else {
TaskOption *to = new TaskOption(); // TODO get option from GlobalOption
to->setDefaultValue();
to->setUrl("file://" + url); //转换成本地文件协议
int taskId = this->createTask(to);
qLogx()<<url<<taskId;
//this->initXmlRpc();
QMap<QString, QVariant> payload;
payload["taskId"] = taskId;
payload["url"] = "file://" + url;
QFile metalinkFile(url);
metalinkFile.open(QIODevice::ReadOnly);
QByteArray metalinkConntent = metalinkFile.readAll();
metalinkFile.close();
QVariantList args;
args.insert(0, metalinkConntent);
QMap<QString, QVariant> options;
options["split"] = QString("5");
args.insert(1, options);
// this->mAriaRpc->call(QString("aria2.addMetalink"), args, QVariant(payload),
// this, SLOT(onAriaAddUriResponse(QVariant &, QVariant &)),
// this, SLOT(onAriaAddUriFault(int, QString, QVariant &)));
// if (!this->mAriaUpdater.isActive()) {
// this->mAriaUpdater.setInterval(3000);
// QObject::connect(&this->mAriaUpdater, SIGNAL(timeout()), this, SLOT(onAriaUpdaterTimeout()));
// this->mAriaUpdater.start();
// }
// if (!this->mAriaTorrentUpdater.isActive()) {
// this->mAriaTorrentUpdater.setInterval(4000);
// QObject::connect(&this->mAriaTorrentUpdater, SIGNAL(timeout()), this, SLOT(onAriaTorrentUpdaterTimeout()));
// this->mAriaTorrentUpdater.start();
// }
}
}
void Karia2::showBatchDownloadDialog()
{
QString url;
int segcnt = 7;
TaskOption * to = 0; //创建任务属性。
QStringList sl;
BatchJobManDlg *bjd = new BatchJobManDlg(this);
int er = bjd->exec();
sl = bjd->getUrlList();
delete bjd;
if (er == QDialog::Accepted) {
qLogx()<<segcnt<<url;
taskinfodlg *tid = new taskinfodlg(this);
for (int i = 0; i < sl.count(); ++i) {
tid->setTaskUrl(sl.at(i));
to = tid->getOption();
this->createTask(to );
}
delete tid;
}
else
{
delete to; to = 0;
}
}
void Karia2::showProcessWebPageInputDiglog() //处理WEB页面,取其中链接并下载
{
QStringList urlList , srcList ,resultList;
QString url;
QUrl u;
QString htmlcode;
int er = QDialog::Rejected;
int ulcount;
int linkCount = 0;
char ** linkList = 0;
WebPageUrlInputDlg * wpid = 0;
WebPageLinkDlg * wpld = 0;
wpid = new WebPageUrlInputDlg(this);
er = wpid->exec();
if (er == QDialog::Accepted )
{
url = wpid->getLinkList();
urlList = url.split("\"+\"");
ulcount = urlList.size();
for (int i = 0; i < ulcount; ++i)
{
if (i == 0 && urlList.at(0).startsWith("\""))
{
urlList[0] = urlList.at(0).right(urlList.at(0).length()-1);
}
if (i == ulcount-1 && urlList.at(i).endsWith("\""))
{
urlList[i] = urlList.at(i).left(urlList.at(i).length()-1);
}
}
qLogx()<<urlList;
if (urlList.size() > 0 )
{
for (int i = 0; i < ulcount; ++i)
{
u = urlList.at(i);
if (u.scheme().toUpper().compare("HTTP") == 0
|| u.scheme().toUpper().compare("HTTPS") == 0 )
{
//是否需要我们自己从HTTP服务器读取文件内容呢。
//windows 不需要.UNIX的各资源管理器还不清楚是否支持打开HTTP的功能。
}
else if (u.scheme().toUpper().length() == 1 ) // C D E and so on for win , / for unix
{
QFile f(urlList.at(0));
f.open(QIODevice::ReadOnly);
htmlcode = QString(f.readAll().data());
f.close();
}
else
{
//not supported page file access way
}
//test
linkCount = 0;
linkList = html_parse_get_all_link(htmlcode.toLatin1().data() , &linkCount );
qLogx()<<linkCount;
for (int j = 0; j < linkCount; j ++ )
{
srcList.append(QString(linkList[j]));
}
html_parse_free_link_mt(linkList,linkCount);
} //end for (int i = 0; i < ulcount; ++i)
}
//////
if (srcList.size() > 0 )
{
wpld = new WebPageLinkDlg(this);
wpld->setSourceUrlList(srcList);
if (wpld->exec() == QDialog::Accepted)
{
resultList = wpld->getResultUrlList();
qLogx()<<resultList;
}
delete wpld; wpld = 0;
}
else // no url found in user input webpage file
{
QMessageBox::warning(this, tr("Process Weg Page :"), tr("No URL(s) Found In the Weg Page File/Given URL"));
}
///建立新任务。
if (resultList.size() > 0 )
{
////建立任务
QString taskUrl = resultList.at(0);
TaskOption * to = 0; //创建任务属性。
taskinfodlg *tid = new taskinfodlg(this);
tid->setTaskUrl(taskUrl);
int er = tid->exec();
//taskUrl = tid->taskUrl();
//segcnt = tid->segmentCount();
//to = tid->getOption(); //
if (er == QDialog::Accepted)
{
//this->createTask(url,segcnt);
//这里先假设用户使用相同的设置。
//delete to; to = 0;
for (int t = 0; t < resultList.size(); ++ t )
{
taskUrl = resultList.at(t);
qLogx()<<taskUrl;
tid->setTaskUrl(taskUrl );
to = tid->getOption();
this->createTask(to );
}
}
else
{
//delete to; to = 0;
}
delete tid;
} //end if (resultList.size() > 0 )
else
{
QMessageBox::warning(this, tr("Process Weg Page :"), tr("No URL(s) Selected"));
} //end if (resultList.size() > 0 ) else
}
if (wpid != 0 ) delete wpid;
if (wpld != 0 ) delete wpld;
}
// void Karia2::onShowDefaultDownloadProperty()
// {
// taskinfodlg *tid = new taskinfodlg(0,0);
// //tid->setRename(fname);
// int er = tid->exec();
// delete tid;
// }
QPair<QString, QString> Karia2::getFileTypeByFileName(QString fileName)
{
QPair<QString,QString> ftype("unknown", "unknown.png");
// if (fileName.isEmpty()) {
// return ftype;
// }
#if defined(Q_OS_WIN)
QString path = "icons/crystalsvg/128x128/mimetypes/";
#elif defined(Q_OS_MAC)
QString path = "icons/crystalsvg/128x128/mimetypes/";
#else // *nix
QString path = QString("/usr/share/icons/%1/128x128/mimetypes/").arg(QIcon::themeName());
if (!QDir().exists(path)) {
path = QString("/usr/share/icons/gnome/32x32/mimetypes/gnome-mime-");
}
#endif
QStringList fileParts = fileName.toLower().split(".");
QString fileExtName = fileParts.at(fileParts.count() - 1);
ftype.first = fileExtName;
if (gMimeHash.contains(fileExtName)) {
ftype.second = path + gMimeHash.value(fileExtName) + ".png";
} else {
ftype.second = path + ftype.second;
}
// ("/usr/share/icons", "/usr/local/share/icons", "/usr/share/icons", ":/home/gzleo/.kde4/share/icons", ":/icons")
// qLogx()<<QIcon::themeSearchPaths();
return ftype;
}
void Karia2::onShowTaskProperty()
{
qLogx()<<__FUNCTION__;
// QItemSelectionModel * sim;
TaskQueue *tq = NULL;
QModelIndexList mil;
//在运行队列中查找。
mil = this->mTaskListView->selectionModel()->selectedIndexes();
if (this->mTaskListView->model() != 0 &&
mil.size() == this->mTaskListView->model()->columnCount()) {
//only selected one ,可以处理,其他多选的不予处理。
int taskId = mil.at(0).data().toInt();
if (taskId <= 0) {
}
// tq = this->mTaskMan->findTaskById(taskId);
if (tq == 0) {
// tq = this->mTaskMan->findTaskById(taskId);
}
}
//根据不同的位置显示不同的任务属性。
if (tq != 0) {
// QString url = tq->mTaskUrl;
// int segcnt = tq->mTotalSegmentCount;
QString url;
int segcnt = 5;
QString fname;//= tq->mTaskOption->mSaveName;
taskinfodlg *tid = new taskinfodlg(0, this);
tid->setTaskUrl(url);
tid->setSegmentCount(segcnt);
tid->setRename(fname);
int er = tid->exec();
Q_UNUSED(er);
delete tid;
}
}
void Karia2::onShowTaskProperty(int pTaskId)
{
Q_UNUSED(pTaskId);
}
void Karia2::onShowTaskPropertyDigest(const QModelIndex & index )
{
//qLogx()<<__FUNCTION__ << index.data();
// int taskId;
this->mSwapPoint = QCursor::pos();
this->mSwapModelIndex = index;
QTimer::singleShot(1000, this, SLOT(onShowTaskPropertyDigest()));
}
void Karia2::onShowTaskPropertyDigest( )
{
//qLogx()<<__FUNCTION__;
QString tips = tr("<html><head><meta name=\"qrichtext\" content=\"1\" /></head><body style=\" white-space: pre-wrap; font-family:宋体; font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;\"><table width=\"100%\" height=\"100%\" border=\"1\"> <tr> <td width=\"97\"> <img name=\"\" src=\"%1\" width=\"80\" height=\"80\" alt=\"\"></td> <td height=\"100%\" ><b>%2</b><br>-------------------------------<br>File Size: %3<br>File Type: .%4<br>Completed: %5<br>-------------------------------<br>Save Postion: %6<br>URL: %7<br>Refferer: %8<br>Comment: %9<br>-------------------------------<br>Create Time: %10<br>------------------------------- </td> </tr></table></body></html>");
QPoint np = this->mainUI->mui_tv_task_list->viewport()->mapFromGlobal(QCursor::pos());
QModelIndex nidx = this->mainUI->mui_tv_task_list->indexAt(np);
QModelIndex tidx;
// TaskQueue * tq = 0;
// int catId = -1;
if (this->mainUI->mui_tv_task_list->viewport()->underMouse()&&
this->mSwapModelIndex.isValid() && nidx.isValid() && nidx == this->mSwapModelIndex ) {
int row = nidx.row();
QString id , url , ftype, name , path , gotlength , totallength , refferer, comment ,createtime , fimg;
tidx = nidx.model()->index(row,0);
id = tidx.data().toString();
//tq = TaskQueue::findTaskById(id.toInt());
//if (tq != 0 )
//{
// //path = tq->mTaskOption->mSavePath;
//}
//else
//{
// path = ".";
//}
tidx = nidx.model()->index(row,ng::tasks::user_cat_id);
path = SqliteStorage::instance(this)->getSavePathByCatId(tidx.data().toInt());
tidx = nidx.model()->index(row, ng::tasks::org_url);
url = tidx.data().toString();
tidx = nidx.model()->index(row, ng::tasks::file_name);
name = tidx.data().toString();
tidx = nidx.model()->index(row, ng::tasks::abtained_length);
gotlength = tidx.data().toString();
tidx = nidx.model()->index(row, ng::tasks::file_size);
totallength = tidx.data().toString();
tidx = nidx.model()->index(row, ng::tasks::referer);
refferer = tidx.data().toString();
tidx = nidx.model()->index(row, ng::tasks::comment);
comment = tidx.data().toString();
tidx = nidx.model()->index(row, ng::tasks::create_time);
createtime = tidx.data().toString();
//ftype = "unknown";
//fimg = "cubelogo.png";
QPair<QString , QString> guessedFileType = this->getFileTypeByFileName(name);
ftype = guessedFileType.first;
fimg = guessedFileType.second;
//qLogx()<<"show digest"<<this->mSwapModelIndex.data();
//QToolTip * tt = new QToolTip();
tips = tips.arg(fimg);
tips = tips.arg(name);
tips = tips.arg(totallength);
tips = tips.arg(ftype); //get file type by file name , or get file type by file content , later
tips = tips.arg(gotlength);
tips = tips.arg(path);
tips = tips.arg(url);
tips = tips.arg(refferer);
tips = tips.arg(comment);
tips = tips.arg(createtime);
QToolTip::showText(QCursor::pos(),tips );
//delete tt;
}
this->mSwapPoint = QPoint(0,0);
this->mSwapModelIndex = QModelIndex();
}
void Karia2::onSegmentListSelectChange(const QItemSelection & selected, const QItemSelection & deselected )
{
qLogx()<<__FUNCTION__;
Q_UNUSED(deselected);
int taskId;
int segId;
QString segName;
QModelIndexList mil = selected.indexes();
taskId = mil.at(1).data().toInt();
segId = mil.at(0).data().toInt();
segName = mil.at(2).data().toString();
qLogx()<<taskId<<segName<<segId;
//seach log model by taskid and seg id
QAbstractItemModel * mdl = SegmentLogModel::instance(taskId , segId, this);
this->mSegLogListView->setModel(0);
if (mdl != 0 ) {
this->mSegLogListView->setModel(mdl);
this->mSegLogListView->resizeColumnToContents(2);
this->mSegLogListView->scrollToBottom();
} else {
qLogx()<<__FUNCTION__<<" model mSegLogListView = 0 ";
}
}
void Karia2::onTaskListSelectChange(const QItemSelection & selected, const QItemSelection & deselected)
{
Q_UNUSED(deselected);
int taskId;
// int segId;
QString segName;
//更新JOB相关菜单enable状态。
this->onUpdateJobMenuEnableProperty();
///
QModelIndexList mil = selected.indexes();
if (selected.size() == 0 ) {
//不能简单的退出,而应该做点什么吧, 看看它的表现 。
//在没有任务选中的时候,是否应该清除线程列表及线程日志中的内容。
return; //no op needed
}
taskId = mil.at(ng::tasks::task_id).data().toInt();
qLogx()<<__FUNCTION__<<taskId<<segName;
QModelIndex index;
QAbstractItemModel *mdl = 0;
// update task ball and peer view
if (this->mTaskMan->isTorrentTask(taskId)) {
mdl = this->mTaskMan->torrentPeerModel(taskId);
this->mainUI->peersView->setModel(0);
this->mainUI->peersView->setModel(mdl);
mdl = this->mTaskMan->torrentTrackerModel(taskId);
this->mainUI->trackersView->setModel(mdl);
mdl = this->mTaskMan->taskSeedFileModel(taskId);
this->mSeedFileView->setModel(mdl);
QWidget *w = this->mSeedFileView->cornerWidget();
if (w == NULL) {
w = new QToolButton();
static_cast<QToolButton*>(w)->setText("");
this->mSeedFileView->setCornerWidget(w);
}
QObject::connect(mdl, SIGNAL(reselectFile(int, bool)), this, SLOT(onReselectFile(int, bool)));
} else {
mdl = this->mTaskMan->torrentPeerModel(taskId);
this->mainUI->peersView->setModel(0);
this->mainUI->peersView->setModel(mdl);
mdl = this->mTaskMan->torrentTrackerModel(taskId);
this->mainUI->trackersView->setModel(mdl);
mdl = this->mTaskMan->taskSeedFileModel(taskId);
this->mSeedFileView->setModel(mdl);
}
{
mdl = this->mTaskMan->taskServerModel(taskId);
this->mSegListView->setModel(mdl);
}
qLogx()<<__FUNCTION__<<"Ball Ball"<<taskId<<mdl<<(mdl ? mdl->rowCount() : 0);
TaskBallMapWidget::instance()->onRunTaskCompleteState(taskId, true);
{
// update task summary view
QString fileName = mil.at(ng::tasks::file_name).data().toString();
QString fileSize = mil.at(ng::tasks::file_size).data().toString();
QString speed = mil.at(ng::tasks::average_speed).data().toString();
QString blocks = mil.at(ng::tasks::block_activity).data().toString();
QString savePath = mil.at(ng::tasks::save_path).data().toString();
QString refer = mil.at(ng::tasks::referer).data().toString();
QPair<QString, QString> mimeIconPosition = this->getFileTypeByFileName(fileName);
this->mainUI->label_2->setText(fileName);
this->mainUI->label_2->setToolTip(fileName);
this->mainUI->label_3->setText(fileSize);
this->mainUI->label_5->setText(speed);
this->mainUI->label_7->setText(blocks);
this->mainUI->label_9->setText(QString("<a href=\"%1\">%1</a>").arg(savePath));
this->mainUI->label_9->setToolTip(QString(tr("Location: %1")).arg(savePath));
// calc how much charactors the label can show
QFontInfo fontInfo = this->mainUI->label_11->fontInfo();
int laWidth = this->mainUI->mui_tw_segment_graph_log->width();
int fpSize = fontInfo.pixelSize();
// int fppSize = fontInfo.pointSize();
int chcnt = laWidth * 2/ fpSize;
// qLogx()<<"calc chcnt:"<<laWidth<<fpSize<<chcnt<<fppSize<<refer.length();
if (refer.length() > chcnt) {
this->mainUI->label_11->setText(QString("<a href=\"%1\">%2</a>")
.arg(refer, refer.left(chcnt) + "..."));
} else {
this->mainUI->label_11->setText(QString("<a href=\"%1\">%1</a>").arg(refer));
}
this->mainUI->label_11->setToolTip(QString(tr("Location: %1")).arg(refer));
if (fileName.isEmpty()) {
QString dir = qApp->applicationDirPath() + "/icons";
this->mainUI->label->setPixmap(QPixmap(dir + "/status/unknown.png").scaled(32, 32));
} else {
this->mainUI->label->setPixmap(QPixmap(mimeIconPosition.second).scaled(32, 32));
}
}
}
void Karia2::onCatListSelectChange(const QItemSelection &selected, const QItemSelection &deselected)
{
qLogx()<<__FUNCTION__<<selected;
// has case selected.size() > 1
if (selected.size() != 1) {
return;
}
QModelIndex currentIndex;
currentIndex = selected.at(0).indexes().at(0);
qLogx()<<currentIndex;
QModelIndex catIDIndex = selected.at(0).indexes().at(ng::cats::cat_id);
int catID = catIDIndex.model()->data(catIDIndex ).toInt();
// qLogx()<<"My cat id is: "<<catIDIndex.model()->data(catIDIndex).toString();
this->mTaskListView->setModel(0);
if (catIDIndex.model()->data(catIDIndex).toString() == "0") {
//this->mCatView->clearSelection(); // 不让选择树根也不合适啊。
QAbstractItemModel *mdl = SqliteTaskModel::instance(catID, this);
this->mTaskListView->setModel(mdl);
} else {
QAbstractItemModel *mdl = SqliteTaskModel::instance(catID, this);
this->mTaskListView->setModel(mdl);
}
QObject::connect(this->mTaskListView->selectionModel(),
SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection &)),
this, SLOT(onTaskListSelectChange(const QItemSelection &, const QItemSelection &)));
// qLogx()<<"colums should show:"<<this->mCustomTaskShowColumns;
if (!this->mCustomTaskShowColumns.isEmpty()) {
this->onTaskShowColumnsChanged(this->mCustomTaskShowColumns);
}
// clean up
// qLogx()<<deselected;
// qLogx()<<deselected.count();
// qDebug<<deselected.at(0); //.indexes();
if (deselected.count() > 0) {
QModelIndex deCatIdIndex = deselected.at(0).indexes().at(ng::cats::cat_id);
if (deCatIdIndex.data().toInt() == ng::cats::downloading
|| deCatIdIndex.data().toInt() == ng::cats::deleted) {
} else {
int deCatId = deCatIdIndex.model()->data(deCatIdIndex).toInt();
SqliteTaskModel::removeInstance(deCatId);
}
}
}
void Karia2::onTaskListMenuPopup(/* const QPoint & pos */)
{
//qLogx()<<__FUNCTION__;
//将菜单项进行使合适的变灰
QModelIndex idx;
QString assumeCategory = "Download";
if (this->mCatView->selectionModel()->selectedIndexes().size() == 0 ) {
} else if (this->mCatView->selectionModel()->selectedIndexes().size() > 0 ) {
idx = this->mCatView->selectionModel()->selectedIndexes().at(0);
if (idx.data().toString().compare("Download")!=0
&& idx.data().toString().compare("Downloaded")!=0
&& idx.data().toString().compare("Deleted")!=0 ) {
} else {
assumeCategory = idx.data().toString();
}
}
if (assumeCategory.compare("Downloaded") == 0 ) {
this->mainUI->action_Start->setEnabled(false);
this->mainUI->action_Pause->setEnabled(false);
this->mainUI->action_Schedule->setEnabled(false);
this->mainUI->action_Delete_task->setEnabled(false);
if (this->mTaskListView->selectionModel()->selectedIndexes().size()>0) {
//this->mainUI->action_Start->setEnabled(true);
//this->mainUI->action_Pause->setEnabled(true);
//this->mainUI->action_Schedule->setEnabled(true);
//this->mainUI->action_Delete_task->setEnabled(true);
this->mainUI->action_Properties->setEnabled(true);
this->mainUI->action_Comment->setEnabled(true);
this->mainUI->action_Copy_URL_To_ClipBoard->setEnabled(true);
this->mainUI->action_Browse_Referer->setEnabled(true);
this->mainUI->action_Browse_With_Site_Explorer->setEnabled(true);
this->mainUI->actionMove_Down->setEnabled(true);
this->mainUI->actionMove_Up->setEnabled(true);
this->mainUI->action_Move_bottom->setEnabled(true);
this->mainUI->action_Move_top->setEnabled(true);
this->mainUI->action_Site_Properties->setEnabled(true);
} else {
//this->mainUI->action_Start->setEnabled(false);
//this->mainUI->action_Pause->setEnabled(false);
//this->mainUI->action_Schedule->setEnabled(false);
//this->mainUI->action_Delete_task->setEnabled(false);
this->mainUI->action_Properties->setEnabled(false);
this->mainUI->action_Comment->setEnabled(false);
this->mainUI->action_Copy_URL_To_ClipBoard->setEnabled(false);
this->mainUI->action_Browse_Referer->setEnabled(false);
this->mainUI->action_Browse_With_Site_Explorer->setEnabled(false);
this->mainUI->actionMove_Down->setEnabled(false);
this->mainUI->actionMove_Up->setEnabled(false);
this->mainUI->action_Move_bottom->setEnabled(false);
this->mainUI->action_Move_top->setEnabled(false);
this->mainUI->action_Site_Properties->setEnabled(false);
}
} else if (assumeCategory.compare("Deleted") == 0 ) {
this->mainUI->action_Start->setEnabled(false);
this->mainUI->action_Pause->setEnabled(false);
this->mainUI->action_Schedule->setEnabled(false);
this->mainUI->action_Delete_task->setEnabled(false);
if (this->mTaskListView->selectionModel()->selectedIndexes().size() > 0) {
//this->mainUI->action_Start->setEnabled(true);
//this->mainUI->action_Pause->setEnabled(true);
//this->mainUI->action_Schedule->setEnabled(true);
//this->mainUI->action_Delete_task->setEnabled(true);
this->mainUI->action_Properties->setEnabled(true);
this->mainUI->action_Comment->setEnabled(true);
this->mainUI->action_Copy_URL_To_ClipBoard->setEnabled(true);
this->mainUI->action_Browse_Referer->setEnabled(true);
this->mainUI->action_Browse_With_Site_Explorer->setEnabled(true);
this->mainUI->actionMove_Down->setEnabled(true);
this->mainUI->actionMove_Up->setEnabled(true);
this->mainUI->action_Move_bottom->setEnabled(true);
this->mainUI->action_Move_top->setEnabled(true);
this->mainUI->action_Site_Properties->setEnabled(true);
} else {
//this->mainUI->action_Start->setEnabled(false);
//this->mainUI->action_Pause->setEnabled(false);
//this->mainUI->action_Schedule->setEnabled(false);
//this->mainUI->action_Delete_task->setEnabled(false);
this->mainUI->action_Properties->setEnabled(false);
this->mainUI->action_Comment->setEnabled(false);
this->mainUI->action_Copy_URL_To_ClipBoard->setEnabled(false);
this->mainUI->action_Browse_Referer->setEnabled(false);
this->mainUI->action_Browse_With_Site_Explorer->setEnabled(false);
this->mainUI->actionMove_Down->setEnabled(false);
this->mainUI->actionMove_Up->setEnabled(false);
this->mainUI->action_Move_bottom->setEnabled(false);
this->mainUI->action_Move_top->setEnabled(false);
this->mainUI->action_Site_Properties->setEnabled(false);
}
} else {//if (assumeCategory.compare("Download") == 0 )
if (this->mTaskListView->selectionModel()->selectedIndexes().size() > 0) {
this->mainUI->action_Start->setEnabled(true);
this->mainUI->action_Pause->setEnabled(true);
this->mainUI->action_Schedule->setEnabled(true);
this->mainUI->action_Delete_task->setEnabled(true);
this->mainUI->action_Properties->setEnabled(true);
this->mainUI->action_Comment->setEnabled(true);
this->mainUI->action_Copy_URL_To_ClipBoard->setEnabled(true);
this->mainUI->action_Browse_Referer->setEnabled(true);
this->mainUI->action_Browse_With_Site_Explorer->setEnabled(true);
this->mainUI->actionMove_Down->setEnabled(true);
this->mainUI->actionMove_Up->setEnabled(true);
this->mainUI->action_Move_bottom->setEnabled(true);
this->mainUI->action_Move_top->setEnabled(true);
this->mainUI->action_Site_Properties->setEnabled(true);
} else {
this->mainUI->action_Start->setEnabled(false);
this->mainUI->action_Pause->setEnabled(false);
this->mainUI->action_Schedule->setEnabled(false);
this->mainUI->action_Delete_task->setEnabled(false);
this->mainUI->action_Properties->setEnabled(false);
this->mainUI->action_Comment->setEnabled(false);
this->mainUI->action_Copy_URL_To_ClipBoard->setEnabled(false);
this->mainUI->action_Browse_Referer->setEnabled(false);
this->mainUI->action_Browse_With_Site_Explorer->setEnabled(false);
this->mainUI->actionMove_Down->setEnabled(false);
this->mainUI->actionMove_Up->setEnabled(false);
this->mainUI->action_Move_bottom->setEnabled(false);
this->mainUI->action_Move_top->setEnabled(false);
this->mainUI->action_Site_Properties->setEnabled(false);
}
}
if (this->mTaskListView == sender() ) {
this->mTaskPopupMenu->popup(QCursor::pos());
} else {
//不是任务视图控件发送来的。
}
}
void Karia2::onUpdateJobMenuEnableProperty()
{
qLogx()<<__FUNCTION__;
//将菜单项进行使合适的变灰
QModelIndex idx;
// QString assumeCategory = "Download";
int catId = ng::cats::downloading;
if (this->mCatView->selectionModel()->selectedIndexes().size() == 0) {
} else if (this->mCatView->selectionModel()->selectedIndexes().size() > 0) {
idx = this->mCatView->selectionModel()->selectedIndexes().at(ng::cats::cat_id);
catId = idx.data().toInt();
// if (idx.data().toString().compare("Download")!=0
// && idx.data().toString().compare("Downloaded")!=0
// && idx.data().toString().compare("Deleted")!=0 ) {
// } else {
// assumeCategory = idx.data().toString();
// }
}
if (catId == ng::cats::downloaded) { // (assumeCategory.compare("Downloaded") == 0 ) {
this->mainUI->action_Start->setEnabled(false);
this->mainUI->action_Pause->setEnabled(false);
this->mainUI->action_Schedule->setEnabled(false);
this->mainUI->action_Delete_task->setEnabled(false);
if (this->mTaskListView->selectionModel()->selectedIndexes().size()>0) {
//this->mainUI->action_Start->setEnabled(true);
//this->mainUI->action_Pause->setEnabled(true);
//this->mainUI->action_Schedule->setEnabled(true);
this->mainUI->action_Delete_task->setEnabled(true);
this->mainUI->action_Properties->setEnabled(true);
this->mainUI->action_Comment->setEnabled(true);
this->mainUI->action_Copy_URL_To_ClipBoard->setEnabled(true);
this->mainUI->action_Browse_Referer->setEnabled(true);
this->mainUI->action_Browse_With_Site_Explorer->setEnabled(true);
this->mainUI->actionMove_Down->setEnabled(true);
this->mainUI->actionMove_Up->setEnabled(true);
this->mainUI->action_Move_bottom->setEnabled(true);
this->mainUI->action_Move_top->setEnabled(true);
this->mainUI->action_Site_Properties->setEnabled(true);
} else {
//this->mainUI->action_Start->setEnabled(false);
//this->mainUI->action_Pause->setEnabled(false);
//this->mainUI->action_Schedule->setEnabled(false);
//this->mainUI->action_Delete_task->setEnabled(false);
this->mainUI->action_Properties->setEnabled(false);
this->mainUI->action_Comment->setEnabled(false);
this->mainUI->action_Copy_URL_To_ClipBoard->setEnabled(false);
this->mainUI->action_Browse_Referer->setEnabled(false);
this->mainUI->action_Browse_With_Site_Explorer->setEnabled(false);
this->mainUI->actionMove_Down->setEnabled(false);
this->mainUI->actionMove_Up->setEnabled(false);
this->mainUI->action_Move_bottom->setEnabled(false);
this->mainUI->action_Move_top->setEnabled(false);
this->mainUI->action_Site_Properties->setEnabled(false);
}
} else if (catId == ng::cats::deleted) { // (assumeCategory.compare("Deleted") == 0 )
this->mainUI->action_Start->setEnabled(false);
this->mainUI->action_Pause->setEnabled(false);
this->mainUI->action_Schedule->setEnabled(false);
this->mainUI->action_Delete_task->setEnabled(false);
if (this->mTaskListView->selectionModel()->selectedIndexes().size()>0) {
//this->mainUI->action_Start->setEnabled(true);
//this->mainUI->action_Pause->setEnabled(true);
//this->mainUI->action_Schedule->setEnabled(true);
//this->mainUI->action_Delete_task->setEnabled(true);
this->mainUI->action_Properties->setEnabled(true);
this->mainUI->action_Comment->setEnabled(true);
this->mainUI->action_Copy_URL_To_ClipBoard->setEnabled(true);
this->mainUI->action_Browse_Referer->setEnabled(true);
this->mainUI->action_Browse_With_Site_Explorer->setEnabled(true);
this->mainUI->actionMove_Down->setEnabled(true);
this->mainUI->actionMove_Up->setEnabled(true);
this->mainUI->action_Move_bottom->setEnabled(true);
this->mainUI->action_Move_top->setEnabled(true);
this->mainUI->action_Site_Properties->setEnabled(true);
} else {
//this->mainUI->action_Start->setEnabled(false);
//this->mainUI->action_Pause->setEnabled(false);
//this->mainUI->action_Schedule->setEnabled(false);
//this->mainUI->action_Delete_task->setEnabled(false);
this->mainUI->action_Properties->setEnabled(false);
this->mainUI->action_Comment->setEnabled(false);
this->mainUI->action_Copy_URL_To_ClipBoard->setEnabled(false);
this->mainUI->action_Browse_Referer->setEnabled(false);
this->mainUI->action_Browse_With_Site_Explorer->setEnabled(false);
this->mainUI->actionMove_Down->setEnabled(false);
this->mainUI->actionMove_Up->setEnabled(false);
this->mainUI->action_Move_bottom->setEnabled(false);
this->mainUI->action_Move_top->setEnabled(false);
this->mainUI->action_Site_Properties->setEnabled(false);
}
}
else //if (assumeCategory.compare("Downloading") == 0 )
{
if (this->mTaskListView->selectionModel()->selectedIndexes().size()>0) {
this->mainUI->action_Start->setEnabled(true);
this->mainUI->action_Pause->setEnabled(true);
this->mainUI->action_Schedule->setEnabled(true);
this->mainUI->action_Delete_task->setEnabled(true);
this->mainUI->action_Properties->setEnabled(true);
this->mainUI->action_Comment->setEnabled(true);
this->mainUI->action_Copy_URL_To_ClipBoard->setEnabled(true);
this->mainUI->action_Browse_Referer->setEnabled(true);
this->mainUI->action_Browse_With_Site_Explorer->setEnabled(true);
this->mainUI->actionMove_Down->setEnabled(true);
this->mainUI->actionMove_Up->setEnabled(true);
this->mainUI->action_Move_bottom->setEnabled(true);
this->mainUI->action_Move_top->setEnabled(true);
this->mainUI->action_Site_Properties->setEnabled(true);
} else {
this->mainUI->action_Start->setEnabled(false);
this->mainUI->action_Pause->setEnabled(false);
this->mainUI->action_Schedule->setEnabled(false);
this->mainUI->action_Delete_task->setEnabled(false);
this->mainUI->action_Properties->setEnabled(false);
this->mainUI->action_Comment->setEnabled(false);
this->mainUI->action_Copy_URL_To_ClipBoard->setEnabled(false);
this->mainUI->action_Browse_Referer->setEnabled(false);
this->mainUI->action_Browse_With_Site_Explorer->setEnabled(false);
this->mainUI->actionMove_Down->setEnabled(false);
this->mainUI->actionMove_Up->setEnabled(false);
this->mainUI->action_Move_bottom->setEnabled(false);
this->mainUI->action_Move_top->setEnabled(false);
this->mainUI->action_Site_Properties->setEnabled(false);
}
}
}
void Karia2::onLogListMenuPopup(const QPoint & pos )
{
Q_UNUSED(pos);
this->mLogPopupMenu->popup(QCursor::pos());
}
void Karia2::onSegListMenuPopup(const QPoint & pos)
{
// this->mSegmentPopupMenu->popup(QCursor::pos());
Q_UNUSED(pos);
}
void Karia2::onCateMenuPopup(const QPoint & pos)
{
Q_UNUSED(pos);
this->mCatPopupMenu->popup(QCursor::pos());
}
///////////////////////////////////////////
///////// end task ui
//////////////////////////////////////////
void Karia2::onReselectFile(int row, bool selected)
{
SeedFileModel *model = static_cast<SeedFileModel*>(this->mSeedFileView->model());
QToolButton *btn = static_cast<QToolButton*>(this->mSeedFileView->cornerWidget());
btn->setText("*");
btn->setToolTip(tr("Click to apply reselected files"));
QObject::connect(btn, SIGNAL(clicked()), this, SLOT(applyReselectFile()));
}
void Karia2::applyReselectFile()
{
SeedFileModel *model = static_cast<SeedFileModel*>(this->mSeedFileView->model());
QString reselectedIndexes = model->clearReselectFiles();
q_debug()<<reselectedIndexes;
QToolButton *btn = static_cast<QToolButton*>(this->mSeedFileView->cornerWidget());
QObject::disconnect(btn, SIGNAL(clicked()), this, SLOT(applyReselectFile()));
btn->setText("");
btn->setToolTip(tr("No Change"));
// now tell aria2 back reselected files
}
void Karia2::handleArguments()
{
int argc = this->m_argc;
char **argv = this->m_argv; // qApp->argv();
this->handleArguments(argc, argv);
}
QString Karia2::showCommandLineArguments()
{
QString cmdLine;
cmdLine =
"Karia2 command line arguments:\n"
" -u --uri url\n"
" -r --refer url\n"
" -c --cookie cookie_str\n"
" -m --metafile file_path\n"
" -a --agent host:port\n"
"\n";
;
qLogx()<<cmdLine;
return cmdLine;
}
#include "getopt_pp_standalone.h"
void Karia2::handleArguments(int argc, char **argv)
{
for (int i = 0 ; i < argc ; i ++) {
qLogx()<<"Arg no: "<<i<<argv[i];
}
int rargc = argc;
char **rargv = argv;
char *targv[100] = {0};
std::string noprefix_metafile;
/*
opera for win send this format arguments:
no: 0 Z:\cross\karia2-svn\release\Karia2.exe
no: 1 --uri http://down.sandai.net/Thunder5.9.19.1390.exe --refer http://dl.xunlei.com/index.htm?tag=1
Karia2::handleArguments No uri specified.
*/
// maybe opera
#if defined(Q_OS_WIN)
if (argc == 2 && (argv[1][0] == argv[1][1] && argv[1][1] == '-')) {
rargc = 0;
rargv = targv;
qLogx()<<"Reformat arguments for handle properly. "; // ktyytc11
char *farg = argv[1];
char *ptr = 0;
rargc += 1;
targv[0] = argv[0];
while (*farg == ' ') { farg++; } ; // ltrim
while (true && farg != NULL) {
ptr = strchr(farg, ' ');
qLogx()<<"here:"<<ptr;
if (ptr == NULL) {
targv[rargc++] = farg;
break;
} else {
targv[rargc++] = farg;
farg = ptr + 1;
*ptr = '\0';
}
}
for (int i = 0 ; i < rargc ; i ++) {
qLogx()<<"rArg no: "<<i<<rargv[i];
}
} else if (argc == 2) {
// windows metafile arguments, no --metafile prefix
GetOpt::GetOpt_pp args(rargc, rargv);
args >> GetOpt::Option(GetOpt::GetOpt_pp::EMPTY_OPTION, noprefix_metafile);
}
#elif defined(Q_OS_MAC)
Q_UNUSED(targv);
#else
Q_UNUSED(targv);
// Fixed opera 10.54 for linux/unix change
if (argc == 2) {
// linux/unix metafile arguments, no --metafile prefix
GetOpt::GetOpt_pp args(rargc, rargv);
args >> GetOpt::Option(GetOpt::GetOpt_pp::EMPTY_OPTION, noprefix_metafile);
}
#endif
std::string std_uri, std_refer, std_metafile, std_cookies, std_agent;
// GetOpt::GetOpt_pp args(argc, argv);
GetOpt::GetOpt_pp args(rargc, rargv);
args >> GetOpt::Option('u', "uri", std_uri);
args >> GetOpt::Option('r', "refer", std_refer);
args >> GetOpt::Option('c', "cookie", std_cookies);
args >> GetOpt::Option('m', "metafile", std_metafile);
args >> GetOpt::Option('a', "agent", std_agent);
if (noprefix_metafile.length() > 0) {
std_metafile = noprefix_metafile;
}
QString uri, refer, metafile, cookies, agent;
uri = QString::fromStdString(std_uri);
refer = QString::fromStdString(std_refer);
cookies = QString::fromStdString(std_cookies);
metafile = QString::fromStdString(std_metafile);
agent = QString::fromStdString(std_agent);
if (metafile.length() > 0) {
QFile file(metafile);
file.open(QIODevice::ReadOnly);
QByteArray metaData = file.readAll().trimmed();
QList<QByteArray> metaInfo = metaData.split('\n');
if (metaInfo.count() != 5) {
qLogx()<<__FUNCTION__<<"Not a valid metfile.";
return;
}
uri = metaInfo.at(1);
refer = metaInfo.at(2);
cookies = metaInfo.at(3);
agent = metaInfo.at(4);
}
if (uri.length() == 0) {
qLogx()<<__FUNCTION__<<"No uri specified.";
return;
}
// fix for opera %l or %u give the error url
if (uri.startsWith("http:/", Qt::CaseInsensitive)
&& !uri.startsWith("http://", Qt::CaseInsensitive)) {
uri = uri.replace("http:/", "http://");
} else if (uri.startsWith("ftp:/", Qt::CaseInsensitive)
&& !uri.startsWith("ftp://", Qt::CaseInsensitive)) {
uri = uri.replace("ftp:/", "ftp://");
}
// fix for opera %l or %u give the error url
if (refer.startsWith("http:/", Qt::CaseInsensitive)
&& !refer.startsWith("http://", Qt::CaseInsensitive)) {
refer = refer.replace("http:/", "http://");
} else if (refer.startsWith("ftp:/", Qt::CaseInsensitive)
&& !refer.startsWith("ftp://", Qt::CaseInsensitive)) {
refer = refer.replace("ftp:/", "ftp://");
}
// convect to TaskOption raw data formats, for passive more data
TaskOption options;
options.mTaskUrl = uri;
options.mReferer = refer;
options.mCookies = cookies;
options.mAgent = agent;
QString ngetUri = "karia2://" + options.toBase64Data();
QClipboard *cb = QApplication::clipboard();
cb->setText(ngetUri);
qLogx()<<__FUNCTION__<<"uri:"<<uri<<"cbtext:"<<cb->text()<<ngetUri;
// this->mainUI->action_New_Download->trigger();
qApp->setActiveWindow(this);
this->setFocus(Qt::MouseFocusReason);
}
void Karia2::handleArguments(QStringList args)
{
QString uri, uri2;
QString refer, refer2;
QString shortArgName;
QString longArgName;
QString defaultArgValue = QString::null;
// args.takeFirst(); // it is app name
int argc = args.count();
char *argv[100] = {0};
for (int i = 0; i < argc; i ++) {
argv[i] = strdup(args.at(i).toLatin1().data());
}
this->handleArguments(argc, argv);
for (int i = 0; i < argc; i++) {
free(argv[i]);
}
//
return;
}
void Karia2::onOtherKaria2MessageRecived(const QString &msg)
{
QStringList args;
if (msg.startsWith("sayhello:")) {
qLogx()<<__FUNCTION__<<"You says: "<<msg;
} else if (msg.startsWith("cmdline:")) {
args = msg.right(msg.length() - 8).split(" ");
if (!args.at(1).startsWith("--")) {
QString arg2;
for (int i = 1; i < args.count(); ++i) {
arg2 += args.at(i) + " ";
}
args.erase(++args.begin(), args.end());
args << arg2.trimmed();
Q_ASSERT(args.count() == 2);
}
this->handleArguments(args);
} else {
qLogx()<<__FUNCTION__<<"Unknown message type: "<<msg;
}
}
//dynamic language switch
void Karia2::retranslateUi()
{
this->mainUI->retranslateUi(this); //不调用它还不行,不知道为什么呢。
//还有一个问题,怎么把程序中所有的字符串都放在这个函数中呢。
}
void Karia2::onObjectDestroyed(QObject *obj)
{
qLogx()<<__FUNCTION__<<__LINE__<<" "<< obj->objectName();
obj->dumpObjectInfo ();
obj->dumpObjectTree ();
}
//void Karia2::onSkypeError(int errNo, QString msg)
//{
// qLogx()<<errNo<<msg;
//}
//void Karia2::onShowSkypeTracer(bool checked)
//{
// // if (this->mSkypeTracer == NULL) {
// // this->mSkypeTracer = new SkypeTracer(this);
// // QObject::connect(this->mSkype, SIGNAL(commandRequest(QString)),
// // this->mSkypeTracer, SLOT(onCommandRequest(QString)));
// // QObject::connect(this->mSkype, SIGNAL(commandResponse(QString)),
// // this->mSkypeTracer, SLOT(onCommandResponse(QString)));
// // QObject::connect(this->mSkypeTracer, SIGNAL(commandRequest(QString)),
// // this->mSkype, SLOT(onCommandRequest(QString)));
// // }
// // this->mSkypeTracer->setVisible(!this->mSkypeTracer->isVisible());
//}
//void Karia2::onChatWithSkype()
//{
// // QString skypeName = this->mainUI->lineEdit->text();
// // QStringList contacts = this->mSkype->getContacts();
// // qLogx()<<skypeName<<contacts;
// // this->mSkype->newStream(skypeName);
// // this->mSkype->newStream("drswinghead");
//}
//void Karia2::onSendPackage()
//{
// MetaUri mu;
// mu.url = "http://sourceforge.net/projects/nullfxp/files/nullfxp/nullfxp-2.0.2/nullfxp-2.0.2.tar.bz2/download";
// mu.nameMd5 = "aceo732lksdf93sf32983rwe";
// mu.contentMd5 = "is832rj9dvsdklfwwewfwf8sd2";
// mu.fileSize = 12342432812LL;
// mu.owner = "liuguangzhao";
// mu.valid = true;
// mu.mtime = 1234556789;
// // QString muStr = mu.toString();
// // SkypePackage sp;
// // sp.seq = SkypeCommand::nextID().toInt();
// // sp.type = SkypePackage::SPT_MU_ADD;
// // sp.data = muStr;
// // QString spStr = sp.toString();
// // qLogx()<<muStr<<spStr;
// // this->mSkype->sendPackage(this->mainUI->lineEdit->text(), spStr);
//}
//void Karia2::onCallSkype()
//{
// // QString num = this->mainUI->lineEdit_2->text();
// // SkypePackage sp;
// // sp.seq = SkypeCommand::nextID().toInt();
// // sp.type = SkypePackage::SPT_GW_SELECT;
// // sp.data = num;
// // QString spStr = sp.toString();
// // qLogx()<<spStr;
// // this->mSkype->sendPackage(this->mainUI->lineEdit->text(), spStr);
//}
//QAXFACTORY_DEFAULT(Karia2,
// "{074AA25F-F544-401E-8A2A-5C81F01264EF}",
// "{4351FA96-A922-4D76-B4AD-A0A4CF0ED8AA}",
// "{DBEF3F59-305C-4A58-9491-F7E56ADBB0B0}",
// "{9D6E015B-02EF-4FF6-A862-4B26250FCF57}",
// "{E0D9ECBF-2E40-4E94-A37B-0E4FB1ADBBB9}")
//////////end of karia2.cpp
| [
"liuguangzhao@users.sf.net"
] | liuguangzhao@users.sf.net |
18c5cbf171a2f982f67c987d629d18e527197011 | 6f0b249aeec54eb1ff70ff366e337dcea71af00f | /aws-cpp-sdk-docdb/include/aws/docdb/model/ModifyDBClusterParameterGroupRequest.h | 1d6ecf00a0537f2c60211032648c6a457908c619 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | phrocker/aws-sdk-cpp | 04d6e894d59445d514414b6067ae4a6b0586b09c | 352852a088161573f320ae9c6b58b27696fcf057 | refs/heads/master | 2020-05-16T08:32:11.091036 | 2019-04-23T02:19:19 | 2019-04-23T02:19:19 | 182,906,953 | 0 | 0 | Apache-2.0 | 2019-04-23T02:18:20 | 2019-04-23T02:18:19 | null | UTF-8 | C++ | false | false | 5,833 | h | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
#pragma once
#include <aws/docdb/DocDB_EXPORTS.h>
#include <aws/docdb/DocDBRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/docdb/model/Parameter.h>
#include <utility>
namespace Aws
{
namespace DocDB
{
namespace Model
{
/**
* <p>Represents the input to <a>ModifyDBClusterParameterGroup</a>.</p><p><h3>See
* Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/docdb-2014-10-31/ModifyDBClusterParameterGroupMessage">AWS
* API Reference</a></p>
*/
class AWS_DOCDB_API ModifyDBClusterParameterGroupRequest : public DocDBRequest
{
public:
ModifyDBClusterParameterGroupRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "ModifyDBClusterParameterGroup"; }
Aws::String SerializePayload() const override;
protected:
void DumpBodyToUrl(Aws::Http::URI& uri ) const override;
public:
/**
* <p>The name of the DB cluster parameter group to modify.</p>
*/
inline const Aws::String& GetDBClusterParameterGroupName() const{ return m_dBClusterParameterGroupName; }
/**
* <p>The name of the DB cluster parameter group to modify.</p>
*/
inline bool DBClusterParameterGroupNameHasBeenSet() const { return m_dBClusterParameterGroupNameHasBeenSet; }
/**
* <p>The name of the DB cluster parameter group to modify.</p>
*/
inline void SetDBClusterParameterGroupName(const Aws::String& value) { m_dBClusterParameterGroupNameHasBeenSet = true; m_dBClusterParameterGroupName = value; }
/**
* <p>The name of the DB cluster parameter group to modify.</p>
*/
inline void SetDBClusterParameterGroupName(Aws::String&& value) { m_dBClusterParameterGroupNameHasBeenSet = true; m_dBClusterParameterGroupName = std::move(value); }
/**
* <p>The name of the DB cluster parameter group to modify.</p>
*/
inline void SetDBClusterParameterGroupName(const char* value) { m_dBClusterParameterGroupNameHasBeenSet = true; m_dBClusterParameterGroupName.assign(value); }
/**
* <p>The name of the DB cluster parameter group to modify.</p>
*/
inline ModifyDBClusterParameterGroupRequest& WithDBClusterParameterGroupName(const Aws::String& value) { SetDBClusterParameterGroupName(value); return *this;}
/**
* <p>The name of the DB cluster parameter group to modify.</p>
*/
inline ModifyDBClusterParameterGroupRequest& WithDBClusterParameterGroupName(Aws::String&& value) { SetDBClusterParameterGroupName(std::move(value)); return *this;}
/**
* <p>The name of the DB cluster parameter group to modify.</p>
*/
inline ModifyDBClusterParameterGroupRequest& WithDBClusterParameterGroupName(const char* value) { SetDBClusterParameterGroupName(value); return *this;}
/**
* <p>A list of parameters in the DB cluster parameter group to modify.</p>
*/
inline const Aws::Vector<Parameter>& GetParameters() const{ return m_parameters; }
/**
* <p>A list of parameters in the DB cluster parameter group to modify.</p>
*/
inline bool ParametersHasBeenSet() const { return m_parametersHasBeenSet; }
/**
* <p>A list of parameters in the DB cluster parameter group to modify.</p>
*/
inline void SetParameters(const Aws::Vector<Parameter>& value) { m_parametersHasBeenSet = true; m_parameters = value; }
/**
* <p>A list of parameters in the DB cluster parameter group to modify.</p>
*/
inline void SetParameters(Aws::Vector<Parameter>&& value) { m_parametersHasBeenSet = true; m_parameters = std::move(value); }
/**
* <p>A list of parameters in the DB cluster parameter group to modify.</p>
*/
inline ModifyDBClusterParameterGroupRequest& WithParameters(const Aws::Vector<Parameter>& value) { SetParameters(value); return *this;}
/**
* <p>A list of parameters in the DB cluster parameter group to modify.</p>
*/
inline ModifyDBClusterParameterGroupRequest& WithParameters(Aws::Vector<Parameter>&& value) { SetParameters(std::move(value)); return *this;}
/**
* <p>A list of parameters in the DB cluster parameter group to modify.</p>
*/
inline ModifyDBClusterParameterGroupRequest& AddParameters(const Parameter& value) { m_parametersHasBeenSet = true; m_parameters.push_back(value); return *this; }
/**
* <p>A list of parameters in the DB cluster parameter group to modify.</p>
*/
inline ModifyDBClusterParameterGroupRequest& AddParameters(Parameter&& value) { m_parametersHasBeenSet = true; m_parameters.push_back(std::move(value)); return *this; }
private:
Aws::String m_dBClusterParameterGroupName;
bool m_dBClusterParameterGroupNameHasBeenSet;
Aws::Vector<Parameter> m_parameters;
bool m_parametersHasBeenSet;
};
} // namespace Model
} // namespace DocDB
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
af292a22ab34dd6f2aadd21930d6fe121b425df6 | 41f52b15ab4c256ed5579f65520d1dee949613b8 | /tensorflow/compiler/xla/tests/client_library_test_base.cc | 9f3b66e256dbb351b76a2e66912d3100495101be | [
"Apache-2.0"
] | permissive | ychen404/TensorFlowPlus | c029ad2a77850cc6f141c13a4c10925e0a92d771 | d4fcbe7278b983b6f736acf2d948e1f7954ca7e6 | refs/heads/master | 2022-10-15T16:59:37.683864 | 2017-10-04T23:28:02 | 2017-10-04T23:28:02 | 210,258,338 | 1 | 0 | Apache-2.0 | 2022-10-04T23:54:20 | 2019-09-23T03:37:58 | C++ | UTF-8 | C++ | false | false | 17,117 | cc | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/tests/client_library_test_base.h"
#include <string>
#include "tensorflow/compiler/xla/client/client_library.h"
#include "tensorflow/compiler/xla/client/computation.h"
#include "tensorflow/compiler/xla/client/local_client.h"
#include "tensorflow/compiler/xla/execution_options_util.h"
#include "tensorflow/compiler/xla/literal_util.h"
#include "tensorflow/compiler/xla/ptr_util.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/statusor.h"
#include "tensorflow/compiler/xla/test_helpers.h"
#include "tensorflow/core/lib/strings/str_util.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/types.h"
namespace se = ::perftools::gputools;
namespace xla {
namespace {
// Wrapper function that creates a nicer error message (than a bare
// ValueOrDie()) if the platform we intend to test is not available.
Client* GetOrCreateLocalClientOrDie(const LocalClientOptions& client_options) {
StatusOr<Client*> result =
ClientLibrary::GetOrCreateLocalClient(client_options);
TF_CHECK_OK(result.status()) << "could not create local client for testing";
return result.ValueOrDie();
}
} // namespace
ClientLibraryTestBase::ClientLibraryTestBase(
perftools::gputools::Platform* platform,
const LocalClientOptions& client_options)
: client_(GetOrCreateLocalClientOrDie(client_options)),
execution_options_(CreateDefaultExecutionOptions()) {
CHECK_EQ(platform, client_options.platform());
// Disabling constant_folding so that tests (usually written using Constants)
// will exercise the intended code paths, instead of being constant folded.
//
// TODO(b/38354253): Constant folding is currently disabled. Change tests to
// use Parameters instead of Constants, and re-enable constant folding by
// default.
execution_options_.mutable_debug_options()->add_xla_disable_hlo_passes(
"constant_folding");
}
ClientLibraryTestBase::ClientLibraryTestBase(se::Platform* platform)
: execution_options_(CreateDefaultExecutionOptions()) {
LocalClientOptions default_options;
default_options.set_platform(platform);
client_ = GetOrCreateLocalClientOrDie(default_options);
execution_options_.mutable_debug_options()->add_xla_disable_hlo_passes(
"constant_folding");
}
string ClientLibraryTestBase::TestName() const {
return ::testing::UnitTest::GetInstance()->current_test_info()->name();
}
StatusOr<std::unique_ptr<GlobalData>> ClientLibraryTestBase::Execute(
ComputationBuilder* builder,
tensorflow::gtl::ArraySlice<GlobalData*> arguments) {
// Build the computation, as a convenience.
TF_ASSIGN_OR_RETURN(auto computation, builder->Build());
return client_->Execute(computation, arguments, &execution_options_);
}
StatusOr<std::unique_ptr<Literal>> ClientLibraryTestBase::ExecuteAndTransfer(
const Computation& computation,
tensorflow::gtl::ArraySlice<GlobalData*> arguments,
const Shape* shape_with_output_layout) {
ExecutionOptions execution_options = execution_options_;
if (shape_with_output_layout != nullptr) {
*execution_options.mutable_shape_with_output_layout() =
*shape_with_output_layout;
}
return client_->ExecuteAndTransfer(computation, arguments,
&execution_options);
}
StatusOr<std::unique_ptr<Literal>> ClientLibraryTestBase::ExecuteAndTransfer(
ComputationBuilder* builder,
tensorflow::gtl::ArraySlice<GlobalData*> arguments,
const Shape* shape_with_output_layout) {
// Build the computation, as a convenience.
TF_ASSIGN_OR_RETURN(auto computation, builder->Build());
return ExecuteAndTransfer(computation, arguments, shape_with_output_layout);
}
std::unique_ptr<GlobalData> ClientLibraryTestBase::ExecuteOrDie(
ComputationBuilder* builder,
tensorflow::gtl::ArraySlice<GlobalData*> arguments) {
return Execute(builder, arguments).ConsumeValueOrDie();
}
std::unique_ptr<Literal> ClientLibraryTestBase::ExecuteAndTransferOrDie(
ComputationBuilder* builder,
tensorflow::gtl::ArraySlice<GlobalData*> arguments) {
return ExecuteAndTransfer(builder, arguments).ConsumeValueOrDie();
}
string ClientLibraryTestBase::ExecuteToString(
ComputationBuilder* builder,
tensorflow::gtl::ArraySlice<GlobalData*> arguments) {
StatusOr<Computation> computation_status = builder->Build();
if (!computation_status.ok()) {
return computation_status.status().ToString();
}
Computation computation = computation_status.ConsumeValueOrDie();
auto result =
client_->ExecuteAndTransfer(computation, arguments, &execution_options_);
if (!result.ok()) {
return result.status().ToString();
} else {
return result.ValueOrDie()->ToString();
}
}
void ClientLibraryTestBase::ComputeAndCompareR1(
ComputationBuilder* builder, const tensorflow::core::Bitmap& expected,
tensorflow::gtl::ArraySlice<GlobalData*> arguments) {
std::unique_ptr<Literal> expected_literal = Literal::CreateR1(expected);
ClientLibraryTestBase::ComputeAndCompareLiteral(builder, *expected_literal,
arguments);
}
void ClientLibraryTestBase::ComputeAndCompareLiteral(
ComputationBuilder* builder, const Literal& expected,
tensorflow::gtl::ArraySlice<GlobalData*> arguments,
const Shape* shape_with_layout) {
EXPECT_IS_OK(ComputeAndCompareLiteralWithStatus(builder, expected, arguments,
shape_with_layout));
}
void ClientLibraryTestBase::ComputeAndCompareLiteral(
ComputationBuilder* builder, const Literal& expected,
tensorflow::gtl::ArraySlice<GlobalData*> arguments, ErrorSpec error,
const Shape* shape_with_layout) {
EXPECT_IS_OK(ComputeAndCompareLiteralWithStatus(builder, expected, arguments,
error, shape_with_layout));
}
tensorflow::Status
ClientLibraryTestBase::ComputeAndCompareLiteralWithAllOutputLayouts(
const xla::Computation& computation, const Literal& expected,
tensorflow::gtl::ArraySlice<GlobalData*> arguments,
const std::function<void(const Literal& actual,
const string& error_message)>& verify_output) {
// Try with no layout requirement.
TF_ASSIGN_OR_RETURN(auto actual, ExecuteAndTransfer(computation, arguments));
verify_output(*actual, "");
// Try with all output layouts.
std::vector<int64> minor_to_major(ShapeUtil::Rank(expected.shape()));
std::iota(minor_to_major.begin(), minor_to_major.end(), 0);
do {
auto layout = ShapeUtil::MakeShapeWithLayout(
expected.shape().element_type(),
AsInt64Slice(expected.shape().dimensions()), minor_to_major);
TF_ASSIGN_OR_RETURN(auto actual,
ExecuteAndTransfer(computation, arguments, &layout));
verify_output(*actual, tensorflow::strings::StrCat(
"Test with output layout: ",
ShapeUtil::HumanStringWithLayout(layout)));
} while (std::next_permutation(minor_to_major.begin(), minor_to_major.end()));
return tensorflow::Status::OK();
}
tensorflow::Status
ClientLibraryTestBase::ComputeAndCompareLiteralWithAllInputLayouts(
const xla::Computation& computation, const Literal& expected,
tensorflow::gtl::ArraySlice<GlobalData*> arguments,
const std::function<void(const Literal& actual,
const string& error_message)>& verify_output,
const Shape* output_with_layout) {
std::vector<GlobalData*> arguments_with_layout;
std::vector<string> layout_strings;
// This is a recursive function. It's an std::function instead of a lambda
// because it needs to capture itself. The index is the index of the argument
// to try all layouts for.
std::function<tensorflow::Status(int64)> choose;
choose = [&, this](int64 index) -> tensorflow::Status {
if (index < arguments.size()) {
// Try out all layouts for the operand.
TF_ASSIGN_OR_RETURN(auto literal,
client_->Transfer(*arguments[index], nullptr));
// Skip tuples because they don't have a rank.
if (ShapeUtil::IsTuple(literal->shape())) {
layout_strings.push_back(
ShapeUtil::HumanStringWithLayout(literal->shape()));
arguments_with_layout.push_back(arguments[index]);
TF_RETURN_IF_ERROR(choose(index + 1));
arguments_with_layout.pop_back();
layout_strings.pop_back();
return tensorflow::Status::OK();
}
std::vector<int64> minor_to_major(ShapeUtil::Rank(literal->shape()));
std::iota(minor_to_major.begin(), minor_to_major.end(), 0);
do {
auto literal_relayout =
literal->Relayout(LayoutUtil::MakeLayout(minor_to_major));
layout_strings.push_back(
ShapeUtil::HumanStringWithLayout(literal_relayout->shape()));
TF_ASSIGN_OR_RETURN(auto data,
client_->TransferToServer(*literal_relayout));
arguments_with_layout.push_back(data.get());
TF_RETURN_IF_ERROR(choose(index + 1));
arguments_with_layout.pop_back();
layout_strings.pop_back();
} while (
std::next_permutation(minor_to_major.begin(), minor_to_major.end()));
return tensorflow::Status::OK();
}
// Every argument has an assigned layout.
TF_ASSIGN_OR_RETURN(
auto actual,
ExecuteAndTransfer(
computation,
tensorflow::gtl::ArraySlice<GlobalData*>(arguments_with_layout),
output_with_layout));
string error_message = "Test with input layouts: ";
for (const auto& str : layout_strings) {
tensorflow::strings::StrAppend(&error_message, str, " ");
}
verify_output(*actual, error_message);
return tensorflow::Status::OK();
};
return choose(0);
}
tensorflow::Status ClientLibraryTestBase::ComputeAndCompareLiteralWithStatus(
ComputationBuilder* builder, const Literal& expected,
tensorflow::gtl::ArraySlice<GlobalData*> arguments,
const Shape* shape_with_layout) {
TF_ASSIGN_OR_RETURN(auto computation, builder->Build());
if (ShapeUtil::ElementIsFloating(expected.shape())) {
LOG(WARNING) << "performing exact comparison of floating point numbers";
} else {
TF_RET_CHECK(ShapeUtil::ElementIsIntegral(expected.shape()) ||
expected.shape().element_type() == PRED)
<< ShapeUtil::HumanString(expected.shape());
}
auto expect_equal = [&](const Literal& actual, const string& error_message) {
LiteralTestUtil::ExpectEqual(expected, actual, error_message);
};
if (execution_options_.debug_options().xla_test_all_output_layouts()) {
return ComputeAndCompareLiteralWithAllOutputLayouts(
computation, expected, arguments, expect_equal);
}
if (execution_options_.debug_options().xla_test_all_input_layouts()) {
return ComputeAndCompareLiteralWithAllInputLayouts(
computation, expected, arguments, expect_equal, shape_with_layout);
}
TF_ASSIGN_OR_RETURN(auto actual, ExecuteAndTransfer(computation, arguments,
shape_with_layout));
LiteralTestUtil::ExpectEqual(expected, *actual);
return tensorflow::Status::OK();
}
tensorflow::Status ClientLibraryTestBase::ComputeAndCompareLiteralWithStatus(
ComputationBuilder* builder, const Literal& expected,
tensorflow::gtl::ArraySlice<GlobalData*> arguments, ErrorSpec error,
const Shape* shape_with_layout) {
TF_RET_CHECK(ShapeUtil::ElementIsFloating(expected.shape()));
TF_ASSIGN_OR_RETURN(auto computation, builder->Build());
auto expect_near = [&](const Literal& actual, const string& error_message) {
LiteralTestUtil::ExpectNear(expected, actual, error, error_message);
};
if (execution_options_.debug_options().xla_test_all_output_layouts()) {
return ComputeAndCompareLiteralWithAllOutputLayouts(computation, expected,
arguments, expect_near);
}
if (execution_options_.debug_options().xla_test_all_input_layouts()) {
return ComputeAndCompareLiteralWithAllInputLayouts(
computation, expected, arguments, expect_near, shape_with_layout);
}
TF_ASSIGN_OR_RETURN(auto actual, ExecuteAndTransfer(computation, arguments,
shape_with_layout));
LiteralTestUtil::ExpectNear(expected, *actual, error);
return tensorflow::Status::OK();
}
void ClientLibraryTestBase::ComputeAndCompareR1U8(
ComputationBuilder* builder, tensorflow::StringPiece expected,
tensorflow::gtl::ArraySlice<GlobalData*> arguments) {
auto actual_status = ExecuteAndTransfer(builder, arguments);
EXPECT_IS_OK(actual_status.status());
if (!actual_status.ok()) {
return;
}
auto actual = actual_status.ConsumeValueOrDie();
// Turn the expected value into a literal.
std::unique_ptr<Literal> expected_literal = Literal::CreateR1U8(expected);
VLOG(1) << "expected: " << expected_literal->ToString();
VLOG(1) << "actual: " << actual->ToString();
EXPECT_EQ(expected, actual->u8s_string());
}
void ClientLibraryTestBase::ComputeAndCompareTuple(
ComputationBuilder* builder, const Literal& expected,
tensorflow::gtl::ArraySlice<GlobalData*> arguments) {
auto actual_status = ExecuteAndTransfer(builder, arguments);
EXPECT_IS_OK(actual_status.status());
if (!actual_status.ok()) {
return;
}
auto actual = actual_status.ConsumeValueOrDie();
LiteralTestUtil::ExpectEqualTuple(expected, *actual);
}
void ClientLibraryTestBase::ComputeAndCompareTuple(
ComputationBuilder* builder, const Literal& expected,
tensorflow::gtl::ArraySlice<GlobalData*> arguments, ErrorSpec error) {
auto actual_status = ExecuteAndTransfer(builder, arguments);
EXPECT_IS_OK(actual_status.status());
if (!actual_status.ok()) {
return;
}
auto actual = actual_status.ConsumeValueOrDie();
LiteralTestUtil::ExpectNearTuple(expected, *actual, error);
}
Computation ClientLibraryTestBase::CreateScalarRelu() {
ComputationBuilder builder(client_, "relu");
auto z_value = builder.Parameter(0, ShapeUtil::MakeShape(F32, {}), "z_value");
auto zero = builder.ConstantR0<float>(0.0);
builder.Max(z_value, zero);
auto computation_status = builder.Build();
TF_CHECK_OK(computation_status.status());
return computation_status.ConsumeValueOrDie();
}
Computation ClientLibraryTestBase::CreateScalarMax() {
ComputationBuilder builder(client_, "max");
auto x = builder.Parameter(0, ShapeUtil::MakeShape(F32, {}), "x");
auto y = builder.Parameter(1, ShapeUtil::MakeShape(F32, {}), "y");
builder.Max(x, y);
auto computation_status = builder.Build();
TF_CHECK_OK(computation_status.status());
return computation_status.ConsumeValueOrDie();
}
Computation ClientLibraryTestBase::CreateScalarReluSensitivity() {
ComputationBuilder builder(client_, "relu_sensitivity");
auto activation =
builder.Parameter(0, ShapeUtil::MakeShape(F32, {}), "activation");
auto backprop =
builder.Parameter(1, ShapeUtil::MakeShape(F32, {}), "backprop");
auto zero = builder.ConstantR0<float>(0.0);
auto activation_gtz = builder.Gt(activation, zero);
builder.Select(activation_gtz, /*on_true=*/backprop, /*on_false=*/zero);
auto computation_status = builder.Build();
TF_CHECK_OK(computation_status.status());
return computation_status.ConsumeValueOrDie();
}
std::unique_ptr<Array2D<float>> ClientLibraryTestBase::CreatePatternedMatrix(
int rows, int cols, float offset) {
auto array = MakeUnique<Array2D<float>>(rows, cols);
for (int64 row = 0; row < rows; ++row) {
for (int64 col = 0; col < cols; ++col) {
(*array)(row, col) = col + (row * 1000.0f) + offset;
}
}
return array;
}
std::unique_ptr<Array2D<float>>
ClientLibraryTestBase::CreatePatternedMatrixWithZeroPadding(int rows, int cols,
int rows_padded,
int cols_padded) {
CHECK_GE(rows_padded, rows);
CHECK_GE(cols_padded, cols);
auto array = MakeUnique<Array2D<float>>(rows_padded, cols_padded, 0.0);
for (int64 row = 0; row < rows; ++row) {
for (int64 col = 0; col < cols; ++col) {
(*array)(row, col) = col + (row * 1000.0f);
}
}
return array;
}
} // namespace xla
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
e228b859eee712c12417cca8deef170a982d6f81 | b2e4e7e536330d1cae5201cf3000089ae743a808 | /hands-on/threads/pstl2018_20180822oss/include/pstl/internal/glue_algorithm_impl.h | c9c58afac959ef36493b9d8ce5d4f86f6cef5fcd | [
"CC-BY-4.0"
] | permissive | MircoT/esc18 | a5c88fe493dfbae076653975a2be56351979d3e0 | 7ea7cc9c3b755085cdc149405baa602808eb229f | refs/heads/master | 2020-04-02T06:02:11.389466 | 2018-12-18T09:55:15 | 2018-12-18T09:55:15 | 154,124,331 | 0 | 0 | NOASSERTION | 2018-10-22T10:21:43 | 2018-10-22T10:21:36 | null | UTF-8 | C++ | false | false | 53,008 | h | /*
Copyright (c) 2017-2018 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef __PSTL_glue_algorithm_impl_H
#define __PSTL_glue_algorithm_impl_H
#include <functional>
#include "execution_defs.h"
#include "utils.h"
#include "algorithm_impl.h"
#include "numeric_impl.h" /* count and count_if use pattern_transform_reduce */
namespace std {
// [alg.any_of]
template<class ExecutionPolicy, class ForwardIterator, class Predicate>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, bool>
any_of(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, Predicate pred) {
using namespace pstl::internal;
return pattern_any_of( first, last, pred,
is_vectorization_preferred<ExecutionPolicy,ForwardIterator>(exec),
is_parallelization_preferred<ExecutionPolicy,ForwardIterator>(exec));
}
// [alg.all_of]
template<class ExecutionPolicy, class ForwardIterator, class Pred>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, bool>
all_of(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, Pred pred) {
return !any_of(std::forward<ExecutionPolicy>(exec), first, last, pstl::internal::not_pred<Pred>(pred));
}
// [alg.none_of]
template<class ExecutionPolicy, class ForwardIterator, class Predicate>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, bool>
none_of(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, Predicate pred) {
return !any_of( std::forward<ExecutionPolicy>(exec), first, last, pred );
}
// [alg.foreach]
template<class ExecutionPolicy, class ForwardIterator, class Function>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, void>
for_each(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, Function f) {
using namespace pstl::internal;
pattern_walk1(
first, last, f,
is_vectorization_preferred<ExecutionPolicy,ForwardIterator>(exec),
is_parallelization_preferred<ExecutionPolicy,ForwardIterator>(exec));
}
template<class ExecutionPolicy, class ForwardIterator, class Size, class Function>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
for_each_n(ExecutionPolicy&& exec, ForwardIterator first, Size n, Function f) {
using namespace pstl::internal;
return pattern_walk1_n(first, n, f,
is_vectorization_preferred<ExecutionPolicy,ForwardIterator>(exec),
is_parallelization_preferred<ExecutionPolicy,ForwardIterator>(exec));
}
// [alg.find]
template<class ExecutionPolicy, class ForwardIterator, class Predicate>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
find_if(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, Predicate pred) {
using namespace pstl::internal;
return pattern_find_if( first, last, pred,
is_vectorization_preferred<ExecutionPolicy,ForwardIterator>(exec),
is_parallelization_preferred<ExecutionPolicy,ForwardIterator>(exec));
}
template<class ExecutionPolicy, class ForwardIterator, class Predicate>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
find_if_not(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last,
Predicate pred) {
return find_if(std::forward<ExecutionPolicy>(exec), first, last, pstl::internal::not_pred<Predicate>(pred));
}
template<class ExecutionPolicy, class ForwardIterator, class T>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
find(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last,
const T& value) {
return find_if(std::forward<ExecutionPolicy>(exec), first, last, pstl::internal::equal_value<T>(value));
}
// [alg.find.end]
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator1>
find_end(ExecutionPolicy &&exec, ForwardIterator1 first, ForwardIterator1 last, ForwardIterator2 s_first, ForwardIterator2 s_last, BinaryPredicate pred) {
using namespace pstl::internal;
return pattern_find_end(first, last, s_first, s_last, pred,
is_vectorization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec));
}
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator1>
find_end(ExecutionPolicy&& exec, ForwardIterator1 first, ForwardIterator1 last, ForwardIterator2 s_first, ForwardIterator2 s_last) {
return find_end(std::forward<ExecutionPolicy>(exec), first, last, s_first, s_last, pstl::internal::pstl_equal());
}
// [alg.find_first_of]
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator1>
find_first_of(ExecutionPolicy&& exec, ForwardIterator1 first, ForwardIterator1 last, ForwardIterator2 s_first, ForwardIterator2 s_last, BinaryPredicate pred) {
using namespace pstl::internal;
return pattern_find_first_of(first, last, s_first, s_last, pred,
is_vectorization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec));
}
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator1>
find_first_of(ExecutionPolicy&& exec, ForwardIterator1 first, ForwardIterator1 last, ForwardIterator2 s_first, ForwardIterator2 s_last) {
return find_first_of(std::forward<ExecutionPolicy>(exec), first, last, s_first, s_last, pstl::internal::pstl_equal());
}
// [alg.adjacent_find]
template< class ExecutionPolicy, class ForwardIterator >
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
adjacent_find(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last) {
using namespace pstl::internal;
return pattern_adjacent_find(first, last, pstl::internal::pstl_equal(),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator>(exec),
is_vectorization_preferred<ExecutionPolicy, ForwardIterator>(exec), /*first_semantic*/ false);
}
template< class ExecutionPolicy, class ForwardIterator, class BinaryPredicate>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
adjacent_find(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, BinaryPredicate pred) {
using namespace pstl::internal;
return pattern_adjacent_find(first, last, pred,
is_parallelization_preferred<ExecutionPolicy, ForwardIterator>(exec),
is_vectorization_preferred<ExecutionPolicy, ForwardIterator>(exec), /*first_semantic*/ false);
}
// [alg.count]
// Implementation note: count and count_if call the pattern directly instead of calling std::transform_reduce
// so that we do not have to include <numeric>.
template<class ExecutionPolicy, class ForwardIterator, class T>
pstl::internal::enable_if_execution_policy<ExecutionPolicy,typename iterator_traits<ForwardIterator>::difference_type>
count(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, const T& value) {
typedef typename iterator_traits<ForwardIterator>::reference value_type;
using namespace pstl::internal;
return pattern_count(first, last, [&value](const value_type x) {return value==x;},
is_parallelization_preferred<ExecutionPolicy, ForwardIterator>(exec),
is_vectorization_preferred<ExecutionPolicy, ForwardIterator>(exec));
}
template<class ExecutionPolicy, class ForwardIterator, class Predicate>
pstl::internal::enable_if_execution_policy<ExecutionPolicy,typename iterator_traits<ForwardIterator>::difference_type>
count_if(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, Predicate pred) {
using namespace pstl::internal;
return pattern_count(first, last, pred,
is_parallelization_preferred<ExecutionPolicy, ForwardIterator>(exec),
is_vectorization_preferred<ExecutionPolicy, ForwardIterator>(exec));
}
// [alg.search]
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator1>
search(ExecutionPolicy&& exec, ForwardIterator1 first, ForwardIterator1 last, ForwardIterator2 s_first, ForwardIterator2 s_last, BinaryPredicate pred) {
using namespace pstl::internal;
return pattern_search(first, last, s_first, s_last, pred,
is_vectorization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec));
}
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator1>
search(ExecutionPolicy&& exec, ForwardIterator1 first, ForwardIterator1 last, ForwardIterator2 s_first, ForwardIterator2 s_last) {
return search(std::forward<ExecutionPolicy>(exec), first, last, s_first, s_last, pstl::internal::pstl_equal());
}
template<class ExecutionPolicy, class ForwardIterator, class Size, class T, class BinaryPredicate>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
search_n(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, Size count, const T& value, BinaryPredicate pred) {
using namespace pstl::internal;
return pattern_search_n(first, last, count, value, pred,
is_vectorization_preferred<ExecutionPolicy, ForwardIterator>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator>(exec));
}
template<class ExecutionPolicy, class ForwardIterator, class Size, class T>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
search_n(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, Size count, const T& value) {
return search_n(std::forward<ExecutionPolicy>(exec), first, last, count, value, pstl::internal::pstl_equal());
}
// [alg.copy]
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2>
pstl::internal::enable_if_execution_policy<ExecutionPolicy,ForwardIterator2>
copy(ExecutionPolicy&& exec, ForwardIterator1 first, ForwardIterator1 last, ForwardIterator2 result) {
using namespace pstl::internal;
const auto is_vector = is_vectorization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec);
return pattern_walk2_brick(first, last, result, [is_vector](ForwardIterator1 begin, ForwardIterator1 end, ForwardIterator2 res){
return brick_copy(begin, end, res, is_vector);
}, is_parallelization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec));
}
template<class ExecutionPolicy, class ForwardIterator1, class Size, class ForwardIterator2>
pstl::internal::enable_if_execution_policy<ExecutionPolicy,ForwardIterator2>
copy_n(ExecutionPolicy&& exec, ForwardIterator1 first, Size n, ForwardIterator2 result) {
using namespace pstl::internal;
const auto is_vector = is_vectorization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec);
return pattern_walk2_brick_n(first, n, result, [is_vector](ForwardIterator1 begin, Size sz, ForwardIterator2 res){
return brick_copy_n(begin, sz, res, is_vector);
}, is_parallelization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec));
}
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class Predicate>
pstl::internal::enable_if_execution_policy<ExecutionPolicy,ForwardIterator2>
copy_if(ExecutionPolicy&& exec,
ForwardIterator1 first, ForwardIterator1 last,
ForwardIterator2 result, Predicate pred) {
using namespace pstl::internal;
return pattern_copy_if(
first, last, result, pred,
is_vectorization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec));
}
// [alg.swap]
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator2>
swap_ranges(ExecutionPolicy&& exec, ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2) {
using namespace pstl::internal;
typedef typename iterator_traits<ForwardIterator1>::reference reference_type1;
typedef typename iterator_traits<ForwardIterator2>::reference reference_type2;
return pattern_walk2(first1, last1, first2,
[](reference_type1 x, reference_type2 y) {
using std::swap;
swap(x, y);
},
is_vectorization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec));
}
// [alg.transform]
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class UnaryOperation>
pstl::internal::enable_if_execution_policy<ExecutionPolicy,ForwardIterator2>
transform( ExecutionPolicy&& exec, ForwardIterator1 first, ForwardIterator1 last, ForwardIterator2 result, UnaryOperation op ) {
typedef typename iterator_traits<ForwardIterator1>::reference input_type;
typedef typename iterator_traits<ForwardIterator2>::reference output_type;
using namespace pstl::internal;
return pattern_walk2(first, last, result,
[op](input_type x, output_type y ) mutable { y = op(x);},
is_vectorization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec));
}
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class ForwardIterator, class BinaryOperation>
pstl::internal::enable_if_execution_policy<ExecutionPolicy,ForwardIterator>
transform( ExecutionPolicy&& exec, ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator result, BinaryOperation op ) {
typedef typename iterator_traits<ForwardIterator1>::reference input1_type;
typedef typename iterator_traits<ForwardIterator2>::reference input2_type;
typedef typename iterator_traits<ForwardIterator>::reference output_type;
using namespace pstl::internal;
return pattern_walk3(first1, last1, first2, result, [op](input1_type x, input2_type y, output_type z) mutable {z = op(x,y);},
is_vectorization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2,ForwardIterator>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2,ForwardIterator>(exec));
}
// [alg.replace]
template<class ExecutionPolicy, class ForwardIterator, class UnaryPredicate, class T>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, void>
replace_if(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, UnaryPredicate pred, const T& new_value) {
using namespace pstl::internal;
typedef typename iterator_traits<ForwardIterator>::reference element_type;
pattern_walk1(first, last, [&pred, &new_value] (element_type elem) {
if (pred(elem)) {
elem = new_value;
}
},
is_vectorization_preferred<ExecutionPolicy, ForwardIterator>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator>(exec));
}
template<class ExecutionPolicy, class ForwardIterator, class T>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, void>
replace(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, const T& old_value, const T& new_value) {
replace_if(std::forward<ExecutionPolicy>(exec), first, last, pstl::internal::equal_value<T>(old_value), new_value);
}
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class UnaryPredicate, class T>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator2>
replace_copy_if(ExecutionPolicy&& exec, ForwardIterator1 first, ForwardIterator1 last, ForwardIterator2 result, UnaryPredicate pred, const T& new_value) {
typedef typename iterator_traits<ForwardIterator1>::reference input_type;
typedef typename iterator_traits<ForwardIterator2>::reference output_type;
using namespace pstl::internal;
return pattern_walk2(
first, last, result,
[pred, &new_value](input_type x, output_type y) mutable { y = pred(x) ? new_value : x; },
is_vectorization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec));
}
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class T>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator2>
replace_copy(ExecutionPolicy&& exec, ForwardIterator1 first, ForwardIterator1 last, ForwardIterator2 result, const T& old_value, const T& new_value) {
return replace_copy_if(std::forward<ExecutionPolicy>(exec), first, last, result, pstl::internal::equal_value<T>(old_value), new_value);
}
// [alg.fill]
template <class ExecutionPolicy, class ForwardIterator, class T>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, void>
fill( ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, const T& value ) {
using namespace pstl::internal;
pattern_fill(first, last, value,
is_parallelization_preferred<ExecutionPolicy,ForwardIterator>(exec),
is_vectorization_preferred<ExecutionPolicy, ForwardIterator>(exec));
}
template< class ExecutionPolicy, class ForwardIterator, class Size, class T>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
fill_n( ExecutionPolicy&& exec, ForwardIterator first, Size count, const T& value ) {
if(count <= 0)
return first;
using namespace pstl::internal;
return pattern_fill_n(first, count, value,
is_parallelization_preferred<ExecutionPolicy, ForwardIterator>(exec),
is_vectorization_preferred<ExecutionPolicy, ForwardIterator>(exec));
}
// [alg.generate]
template< class ExecutionPolicy, class ForwardIterator, class Generator>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, void>
generate( ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, Generator g ) {
using namespace pstl::internal;
pattern_generate(first, last, g,
is_parallelization_preferred<ExecutionPolicy,ForwardIterator>(exec),
is_vectorization_preferred<ExecutionPolicy, ForwardIterator>(exec));
}
template< class ExecutionPolicy, class ForwardIterator, class Size, class Generator>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
generate_n( ExecutionPolicy&& exec, ForwardIterator first, Size count, Generator g ) {
if(count <= 0)
return first;
using namespace pstl::internal;
return pattern_generate_n(first, count, g,
is_parallelization_preferred<ExecutionPolicy, ForwardIterator>(exec),
is_vectorization_preferred<ExecutionPolicy, ForwardIterator>(exec));
}
// [alg.remove]
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class Predicate>
pstl::internal::enable_if_execution_policy<ExecutionPolicy,ForwardIterator2>
remove_copy_if(ExecutionPolicy&& exec, ForwardIterator1 first, ForwardIterator1 last, ForwardIterator2 result, Predicate pred) {
return copy_if( std::forward<ExecutionPolicy>(exec), first, last, result, pstl::internal::not_pred<Predicate>(pred));
}
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class T>
pstl::internal::enable_if_execution_policy<ExecutionPolicy,ForwardIterator2>
remove_copy(ExecutionPolicy&& exec, ForwardIterator1 first, ForwardIterator1 last, ForwardIterator2 result, const T& value) {
return copy_if( std::forward<ExecutionPolicy>(exec), first, last, result, pstl::internal::not_equal_value<T>(value));
}
template<class ExecutionPolicy, class ForwardIterator, class UnaryPredicate>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
remove_if(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, UnaryPredicate pred) {
using namespace pstl::internal;
return pattern_remove_if(first, last, pred,
is_vectorization_preferred<ExecutionPolicy, ForwardIterator>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator>(exec));
}
template<class ExecutionPolicy, class ForwardIterator, class T>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
remove(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, const T& value) {
return remove_if(std::forward<ExecutionPolicy>(exec), first, last, pstl::internal::equal_value<T>(value));
}
// [alg.unique]
template<class ExecutionPolicy, class ForwardIterator, class BinaryPredicate>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
unique(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, BinaryPredicate pred) {
using namespace pstl::internal;
return pattern_unique(first, last, pred,
is_vectorization_preferred<ExecutionPolicy, ForwardIterator>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator>(exec));
}
template<class ExecutionPolicy, class ForwardIterator>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
unique(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last) {
return unique(std::forward<ExecutionPolicy>(exec), first, last, pstl::internal::pstl_equal());
}
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>
pstl::internal::enable_if_execution_policy<ExecutionPolicy,ForwardIterator2>
unique_copy(ExecutionPolicy&& exec, ForwardIterator1 first, ForwardIterator1 last, ForwardIterator2 result, BinaryPredicate pred) {
using namespace pstl::internal;
return pattern_unique_copy(first, last, result, pred,
is_vectorization_preferred<ExecutionPolicy,ForwardIterator1,ForwardIterator2>(exec),
is_parallelization_preferred<ExecutionPolicy,ForwardIterator1,ForwardIterator2>(exec));
}
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2>
pstl::internal::enable_if_execution_policy<ExecutionPolicy,ForwardIterator2>
unique_copy(ExecutionPolicy&& exec, ForwardIterator1 first, ForwardIterator1 last, ForwardIterator2 result) {
return unique_copy(std::forward<ExecutionPolicy>(exec), first, last, result, pstl::internal::pstl_equal() );
}
// [alg.reverse]
template<class ExecutionPolicy, class BidirectionalIterator>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, void>
reverse(ExecutionPolicy&& exec, BidirectionalIterator first, BidirectionalIterator last) {
using namespace pstl::internal;
pattern_reverse(first, last,
is_vectorization_preferred<ExecutionPolicy, BidirectionalIterator>(exec),
is_parallelization_preferred<ExecutionPolicy, BidirectionalIterator>(exec));
}
template<class ExecutionPolicy, class BidirectionalIterator, class ForwardIterator>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
reverse_copy(ExecutionPolicy&& exec, BidirectionalIterator first, BidirectionalIterator last, ForwardIterator d_first) {
using namespace pstl::internal;
return pattern_reverse_copy(first, last, d_first,
is_vectorization_preferred<ExecutionPolicy, BidirectionalIterator, ForwardIterator>(exec),
is_parallelization_preferred<ExecutionPolicy, BidirectionalIterator, ForwardIterator>(exec));
}
// [alg.rotate]
template<class ExecutionPolicy, class ForwardIterator>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
rotate(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator middle, ForwardIterator last) {
using namespace pstl::internal;
return pattern_rotate(first, middle, last,
is_vectorization_preferred<ExecutionPolicy, ForwardIterator>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator>(exec));
}
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator2>
rotate_copy(ExecutionPolicy&& exec, ForwardIterator1 first, ForwardIterator1 middle, ForwardIterator1 last, ForwardIterator2 result) {
using namespace pstl::internal;
return pattern_rotate_copy(first, middle, last, result,
is_vectorization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec));
}
// [alg.partitions]
template<class ExecutionPolicy, class ForwardIterator, class UnaryPredicate>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, bool>
is_partitioned(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, UnaryPredicate pred) {
using namespace pstl::internal;
return pattern_is_partitioned(first, last, pred,
is_vectorization_preferred<ExecutionPolicy, ForwardIterator>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator>(exec));
}
template<class ExecutionPolicy, class ForwardIterator, class UnaryPredicate>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
partition(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, UnaryPredicate pred) {
using namespace pstl::internal;
return pattern_partition(first, last, pred,
is_vectorization_preferred<ExecutionPolicy, ForwardIterator>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator>(exec));
}
template<class ExecutionPolicy, class BidirectionalIterator, class UnaryPredicate>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, BidirectionalIterator>
stable_partition(ExecutionPolicy&& exec, BidirectionalIterator first, BidirectionalIterator last, UnaryPredicate pred) {
using namespace pstl::internal;
return pattern_stable_partition(first, last, pred,
is_vectorization_preferred<ExecutionPolicy, BidirectionalIterator>(exec),
is_parallelization_preferred<ExecutionPolicy, BidirectionalIterator>(exec));
}
template<class ExecutionPolicy, class ForwardIterator, class ForwardIterator1, class ForwardIterator2, class UnaryPredicate>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, std::pair<ForwardIterator1, ForwardIterator2>>
partition_copy(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, ForwardIterator1 out_true, ForwardIterator2 out_false, UnaryPredicate pred) {
using namespace pstl::internal;
return pattern_partition_copy(first, last, out_true, out_false, pred,
is_vectorization_preferred<ExecutionPolicy, ForwardIterator, ForwardIterator1, ForwardIterator2>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator, ForwardIterator1, ForwardIterator2>(exec));
}
// [alg.sort]
template<class ExecutionPolicy, class RandomAccessIterator, class Compare>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, void>
sort(ExecutionPolicy&& exec, RandomAccessIterator first, RandomAccessIterator last, Compare comp) {
typedef typename iterator_traits<RandomAccessIterator>::value_type input_type;
using namespace pstl::internal;
return pattern_sort(first, last, comp,
is_vectorization_preferred<ExecutionPolicy,RandomAccessIterator>(exec),
is_parallelization_preferred<ExecutionPolicy,RandomAccessIterator>(exec),
typename std::is_move_constructible<input_type>::type());
}
template<class ExecutionPolicy, class RandomAccessIterator>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, void>
sort(ExecutionPolicy&& exec, RandomAccessIterator first, RandomAccessIterator last) {
typedef typename iterator_traits<RandomAccessIterator>::value_type input_type;
sort(std::forward<ExecutionPolicy>(exec), first, last, std::less<input_type>());
}
// [stable.sort]
template<class ExecutionPolicy, class RandomAccessIterator, class Compare>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, void>
stable_sort(ExecutionPolicy&& exec, RandomAccessIterator first, RandomAccessIterator last, Compare comp) {
using namespace pstl::internal;
return pattern_stable_sort(first, last, comp,
is_vectorization_preferred<ExecutionPolicy,RandomAccessIterator>(exec),
is_parallelization_preferred<ExecutionPolicy,RandomAccessIterator>(exec));
}
template<class ExecutionPolicy, class RandomAccessIterator>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, void>
stable_sort(ExecutionPolicy&& exec, RandomAccessIterator first, RandomAccessIterator last) {
typedef typename iterator_traits<RandomAccessIterator>::value_type input_type;
stable_sort(std::forward<ExecutionPolicy>(exec), first, last, std::less<input_type>());
}
// [mismatch]
template< class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class BinaryPredicate >
pstl::internal::enable_if_execution_policy<ExecutionPolicy, std::pair<ForwardIterator1, ForwardIterator2>>
mismatch(ExecutionPolicy&& exec, ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate pred) {
using namespace pstl::internal;
return pattern_mismatch(first1, last1, first2, last2, pred,
is_vectorization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec));
}
template< class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class BinaryPredicate >
pstl::internal::enable_if_execution_policy<ExecutionPolicy, std::pair<ForwardIterator1, ForwardIterator2>>
mismatch(ExecutionPolicy&& exec, ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, BinaryPredicate pred) {
return mismatch(std::forward<ExecutionPolicy>(exec), first1, last1, first2, std::next(first2, std::distance(first1, last1)), pred);
}
template< class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2 >
pstl::internal::enable_if_execution_policy<ExecutionPolicy, std::pair<ForwardIterator1, ForwardIterator2>>
mismatch(ExecutionPolicy&& exec, ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2) {
return mismatch(std::forward<ExecutionPolicy>(exec), first1, last1, first2, last2, pstl::internal::pstl_equal());
}
template< class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2 >
pstl::internal::enable_if_execution_policy<ExecutionPolicy, std::pair<ForwardIterator1, ForwardIterator2>>
mismatch(ExecutionPolicy&& exec, ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2) {
return mismatch(std::forward<ExecutionPolicy>(exec), first1, last1, first2, std::next(first2, std::distance(first1, last1)));
}
// [alg.equal]
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, bool>
equal(ExecutionPolicy&& exec, ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, BinaryPredicate p) {
using namespace pstl::internal;
return pattern_equal(first1, last1, first2, p,
is_vectorization_preferred<ExecutionPolicy, ForwardIterator1>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator1>(exec)
);
}
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, bool>
equal(ExecutionPolicy&& exec, ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2) {
return equal(std::forward<ExecutionPolicy>(exec), first1, last1, first2, pstl::internal::pstl_equal());
}
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, bool>
equal(ExecutionPolicy&& exec, ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, BinaryPredicate p) {
if ( std::distance(first1, last1) == std::distance(first2, last2) )
return std::equal(std::forward<ExecutionPolicy>(exec), first1, last1, first2, p);
else
return false;
}
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, bool>
equal(ExecutionPolicy&& exec, ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2) {
return equal(std::forward<ExecutionPolicy>(exec), first1, last1, first2, pstl::internal::pstl_equal());
}
// [alg.move]
template< class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2 >
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator2>
move(ExecutionPolicy&& exec, ForwardIterator1 first, ForwardIterator1 last, ForwardIterator2 d_first) {
using namespace pstl::internal;
const auto is_vector = is_vectorization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec);
return pattern_walk2_brick(first, last, d_first, [is_vector](ForwardIterator1 begin, ForwardIterator1 end, ForwardIterator2 res) {
return brick_move(begin, end, res, is_vector);
}, is_parallelization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec));
}
// [partial.sort]
template<class ExecutionPolicy, class RandomAccessIterator, class Compare>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, void>
partial_sort(ExecutionPolicy&& exec, RandomAccessIterator first, RandomAccessIterator middle, RandomAccessIterator last, Compare comp) {
using namespace pstl::internal;
pattern_partial_sort(first, middle, last, comp,
is_vectorization_preferred<ExecutionPolicy, RandomAccessIterator>(exec),
is_parallelization_preferred<ExecutionPolicy, RandomAccessIterator>(exec));
}
template<class ExecutionPolicy, class RandomAccessIterator>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, void>
partial_sort(ExecutionPolicy&& exec, RandomAccessIterator first, RandomAccessIterator middle, RandomAccessIterator last) {
typedef typename iterator_traits<RandomAccessIterator>::value_type input_type;
partial_sort(exec, first, middle, last, std::less<input_type>());
}
// [partial.sort.copy]
template<class ExecutionPolicy, class ForwardIterator, class RandomAccessIterator, class Compare>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, RandomAccessIterator>
partial_sort_copy(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, RandomAccessIterator d_first, RandomAccessIterator d_last, Compare comp) {
using namespace pstl::internal;
return pattern_partial_sort_copy(first, last, d_first, d_last, comp,
is_vectorization_preferred<ExecutionPolicy, ForwardIterator, RandomAccessIterator>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator, RandomAccessIterator>(exec));
}
template<class ExecutionPolicy, class ForwardIterator, class RandomAccessIterator>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, RandomAccessIterator>
partial_sort_copy(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, RandomAccessIterator d_first, RandomAccessIterator d_last) {
return partial_sort_copy(std::forward<ExecutionPolicy>(exec), first, last, d_first, d_last, pstl::internal::pstl_less());
}
// [is.sorted]
template<class ExecutionPolicy, class ForwardIterator, class Compare>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
is_sorted_until(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, Compare comp) {
using namespace pstl::internal;
const ForwardIterator res = pattern_adjacent_find(first, last, pstl::internal::reorder_pred<Compare>(comp),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator>(exec),
is_vectorization_preferred<ExecutionPolicy, ForwardIterator>(exec), /*first_semantic*/ false);
return res==last ? last : std::next(res);
}
template<class ExecutionPolicy, class ForwardIterator>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
is_sorted_until(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last) {
typedef typename iterator_traits<ForwardIterator>::value_type input_type;
return is_sorted_until(exec, first, last, std::less<input_type>());
}
template<class ExecutionPolicy, class ForwardIterator, class Compare>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, bool>
is_sorted(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, Compare comp) {
using namespace pstl::internal;
return pattern_adjacent_find(first, last, reorder_pred<Compare>(comp),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator>(exec),
is_vectorization_preferred<ExecutionPolicy, ForwardIterator>(exec), /*or_semantic*/ true)==last;
}
template<class ExecutionPolicy, class ForwardIterator>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, bool>
is_sorted(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last) {
typedef typename iterator_traits<ForwardIterator>::value_type input_type;
return is_sorted(exec, first, last, std::less<input_type>());
}
// [alg.nth.element]
template<class ExecutionPolicy, class RandomAccessIterator, class Compare>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, void>
nth_element(ExecutionPolicy&& exec, RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last, Compare comp) {
using namespace pstl::internal;
pattern_nth_element(first, nth, last, comp,
is_vectorization_preferred<ExecutionPolicy, RandomAccessIterator>(exec),
is_parallelization_preferred<ExecutionPolicy, RandomAccessIterator>(exec));
}
template<class ExecutionPolicy, class RandomAccessIterator>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, void>
nth_element(ExecutionPolicy&& exec, RandomAccessIterator first, RandomAccessIterator nth, RandomAccessIterator last) {
typedef typename iterator_traits<RandomAccessIterator>::value_type input_type;
nth_element(exec, first, nth, last, std::less<input_type>());
}
// [alg.merge]
template< class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class ForwardIterator, class Compare>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
merge(ExecutionPolicy&& exec, ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, ForwardIterator d_first, Compare comp) {
using namespace pstl::internal;
return pattern_merge(first1, last1, first2, last2, d_first, comp,
is_vectorization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2, ForwardIterator>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2, ForwardIterator>(exec));
}
template< class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class ForwardIterator>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
merge(ExecutionPolicy&& exec, ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, ForwardIterator d_first) {
return merge(std::forward<ExecutionPolicy>(exec), first1, last1, first2, last2, d_first, pstl::internal::pstl_less());
}
template< class ExecutionPolicy, class BidirectionalIterator, class Compare>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, void>
inplace_merge(ExecutionPolicy&& exec, BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last, Compare comp) {
using namespace pstl::internal;
pattern_inplace_merge(first, middle, last, comp,
is_vectorization_preferred<ExecutionPolicy, BidirectionalIterator>(exec),
is_parallelization_preferred<ExecutionPolicy, BidirectionalIterator>(exec));
}
template< class ExecutionPolicy, class BidirectionalIterator>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, void>
inplace_merge(ExecutionPolicy&& exec, BidirectionalIterator first, BidirectionalIterator middle, BidirectionalIterator last) {
typedef typename iterator_traits<BidirectionalIterator>::value_type input_type;
inplace_merge(exec, first, middle, last, std::less<input_type>());
}
// [includes]
template< class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class Compare>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, bool>
includes(ExecutionPolicy&& exec, ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, Compare comp) {
using namespace pstl::internal;
return pattern_includes(first1, last1, first2, last2, comp,
is_vectorization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec));
}
template< class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, bool>
includes(ExecutionPolicy&& exec, ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2) {
return includes(std::forward<ExecutionPolicy>(exec), first1, last1, first2, last2, pstl::internal::pstl_less());
}
// [set.union]
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class ForwardIterator, class Compare>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
set_union(ExecutionPolicy&& exec, ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, ForwardIterator result, Compare comp) {
using namespace pstl::internal;
return pattern_set_union(first1, last1, first2, last2, result, comp,
is_vectorization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2, ForwardIterator>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2, ForwardIterator>(exec));
}
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class ForwardIterator>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
set_union(ExecutionPolicy&& exec, ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2,
ForwardIterator2 last2, ForwardIterator result) {
return set_union(std::forward<ExecutionPolicy>(exec), first1, last1, first2, last2, result, pstl::internal::pstl_less());
}
// [set.intersection]
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class ForwardIterator, class Compare>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
set_intersection(ExecutionPolicy&& exec, ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, ForwardIterator result, Compare comp) {
using namespace pstl::internal;
return pattern_set_intersection(first1, last1, first2, last2, result, comp,
is_vectorization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2, ForwardIterator>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2, ForwardIterator>(exec));
}
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class ForwardIterator>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
set_intersection(ExecutionPolicy&& exec, ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, ForwardIterator result) {
return set_intersection(std::forward<ExecutionPolicy>(exec), first1, last1, first2, last2, result, pstl::internal::pstl_less());
}
// [set.difference]
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class ForwardIterator, class Compare>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
set_difference(ExecutionPolicy&& exec, ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, ForwardIterator result, Compare comp) {
using namespace pstl::internal;
return pattern_set_difference(first1, last1, first2, last2, result, comp,
is_vectorization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2, ForwardIterator>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2, ForwardIterator>(exec));
}
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class ForwardIterator>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
set_difference(ExecutionPolicy&& exec, ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, ForwardIterator result) {
return set_difference(std::forward<ExecutionPolicy>(exec), first1, last1, first2, last2, result, pstl::internal::pstl_less());
}
// [set.symmetric.difference]
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class ForwardIterator, class Compare>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
set_symmetric_difference(ExecutionPolicy&& exec, ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, ForwardIterator result, Compare comp) {
using namespace pstl::internal;
return pattern_set_symmetric_difference(first1, last1, first2, last2, result, comp,
is_vectorization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2, ForwardIterator>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2, ForwardIterator>(exec));
}
template<class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class ForwardIterator>
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
set_symmetric_difference(ExecutionPolicy&& exec, ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, ForwardIterator result) {
return set_symmetric_difference(std::forward<ExecutionPolicy>(exec), first1, last1, first2, last2, result, pstl::internal::pstl_less());
}
// [is.heap]
template< class ExecutionPolicy, class RandomAccessIterator, class Compare >
pstl::internal::enable_if_execution_policy<ExecutionPolicy, RandomAccessIterator>
is_heap_until(ExecutionPolicy&& exec, RandomAccessIterator first, RandomAccessIterator last, Compare comp) {
using namespace pstl::internal;
return pattern_is_heap_until(first, last, comp,
is_vectorization_preferred<ExecutionPolicy, RandomAccessIterator>(exec),
is_parallelization_preferred<ExecutionPolicy, RandomAccessIterator>(exec));
}
template< class ExecutionPolicy, class RandomAccessIterator >
pstl::internal::enable_if_execution_policy<ExecutionPolicy, RandomAccessIterator>
is_heap_until(ExecutionPolicy&& exec, RandomAccessIterator first, RandomAccessIterator last) {
typedef typename iterator_traits<RandomAccessIterator>::value_type input_type;
return is_heap_until(std::forward<ExecutionPolicy>(exec), first, last, std::less<input_type>());
}
template< class ExecutionPolicy, class RandomAccessIterator, class Compare >
pstl::internal::enable_if_execution_policy<ExecutionPolicy, bool>
is_heap(ExecutionPolicy&& exec, RandomAccessIterator first, RandomAccessIterator last, Compare comp) {
return is_heap_until(std::forward<ExecutionPolicy>(exec), first, last, comp) == last;
}
template< class ExecutionPolicy, class RandomAccessIterator >
pstl::internal::enable_if_execution_policy<ExecutionPolicy, bool>
is_heap(ExecutionPolicy&& exec, RandomAccessIterator first, RandomAccessIterator last) {
typedef typename iterator_traits<RandomAccessIterator>::value_type input_type;
return is_heap(std::forward<ExecutionPolicy>(exec), first, last, std::less<input_type>());
}
// [alg.min.max]
template< class ExecutionPolicy, class ForwardIterator, class Compare >
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
min_element(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, Compare comp) {
using namespace pstl::internal;
return pattern_min_element(first, last, comp,
is_vectorization_preferred<ExecutionPolicy, ForwardIterator>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator>(exec));
}
template< class ExecutionPolicy, class ForwardIterator >
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
min_element(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last) {
typedef typename iterator_traits<ForwardIterator>::value_type input_type;
return min_element(std::forward<ExecutionPolicy>(exec), first, last, std::less<input_type>());
}
template< class ExecutionPolicy, class ForwardIterator, class Compare >
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
max_element(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, Compare comp) {
using namespace pstl::internal;
return pattern_min_element(first, last, pstl::internal::reorder_pred<Compare>(comp),
is_vectorization_preferred<ExecutionPolicy, ForwardIterator>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator>(exec));
}
template< class ExecutionPolicy, class ForwardIterator >
pstl::internal::enable_if_execution_policy<ExecutionPolicy, ForwardIterator>
max_element(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last) {
typedef typename iterator_traits<ForwardIterator>::value_type input_type;
return min_element(std::forward<ExecutionPolicy>(exec), first, last, pstl::internal::reorder_pred<std::less<input_type> >(std::less<input_type>()));
}
template< class ExecutionPolicy, class ForwardIterator, class Compare >
pstl::internal::enable_if_execution_policy<ExecutionPolicy, std::pair<ForwardIterator, ForwardIterator>>
minmax_element(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last, Compare comp) {
using namespace pstl::internal;
return pattern_minmax_element(first, last, comp,
is_vectorization_preferred<ExecutionPolicy, ForwardIterator>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator>(exec));
}
template< class ExecutionPolicy, class ForwardIterator >
pstl::internal::enable_if_execution_policy<ExecutionPolicy, std::pair<ForwardIterator, ForwardIterator>>
minmax_element(ExecutionPolicy&& exec, ForwardIterator first, ForwardIterator last) {
typedef typename iterator_traits<ForwardIterator>::value_type value_type;
return minmax_element(std::forward<ExecutionPolicy>(exec), first, last, std::less<value_type>());
}
// [alg.lex.comparison]
template< class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2, class Compare >
pstl::internal::enable_if_execution_policy<ExecutionPolicy, bool>
lexicographical_compare(ExecutionPolicy&& exec, ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2, Compare comp) {
using namespace pstl::internal;
return pattern_lexicographical_compare(first1, last1, first2, last2, comp,
is_vectorization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec),
is_parallelization_preferred<ExecutionPolicy, ForwardIterator1, ForwardIterator2>(exec));
}
template< class ExecutionPolicy, class ForwardIterator1, class ForwardIterator2 >
pstl::internal::enable_if_execution_policy<ExecutionPolicy, bool>
lexicographical_compare(ExecutionPolicy&& exec, ForwardIterator1 first1, ForwardIterator1 last1, ForwardIterator2 first2, ForwardIterator2 last2) {
return lexicographical_compare(std::forward<ExecutionPolicy>(exec), first1, last1, first2, last2, pstl::internal::pstl_less());
}
} // namespace std
#endif /* __PSTL_glue_algorithm_impl_H */
| [
"mirco.theone@gmail.com"
] | mirco.theone@gmail.com |
614fcbfcbdc10917ab3d84c8207f1a1b963218b5 | b0ae45be462527e82dbf2a46187b466acd0d92a5 | /ugt3d/Files/Source Examples (C++)/Chapter 16/ex1.h | 44d52429d93e55c4dd8dd1faeee0b35b597095ed | [] | no_license | Torque-Dump/TorqueResourcesDump | 1c97e03da503c2667012dfeb097dae12eb4b90d3 | 5e0b50d1b6c5938d7132475ca9837331a1867b8f | refs/heads/master | 2022-05-18T02:10:47.835191 | 2019-12-09T21:22:23 | 2019-12-09T21:32:34 | 226,960,161 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 210 | h | /**
The Ultimate Guide To Torque 3D
Chapter 16
By: Robert C Fritzen
ex1.h
**/
#include <iostream>
using namespace std;
#ifndef _MYFILE_H_
#define _MYFILE_H_
int addEm(int a, int b = 20);
#endif //_MYFILE_H_ | [
"marc@bloodknightstudios.co.uk"
] | marc@bloodknightstudios.co.uk |
e153d132ad3ca0430792eec428ece37826c2e406 | a4a26652f87ea97a4452100dd44a6ca94e7dea1f | /11-sorting-and-searching/11-8.cpp | f9fb9bf459d05c865ce4a0cef835504817e8a3b8 | [] | no_license | talentlei/CTCI150 | b8f342a808dd8c998fc2207b188db24b352cd26b | d0eb8947e45ade1058bf5497889d382521795de0 | refs/heads/master | 2021-01-25T12:01:50.563964 | 2015-07-23T12:09:54 | 2015-07-23T12:09:54 | 33,870,438 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 931 | cpp |
class rankNode{
public :
int left_size;
int val;
rankNode* left;
rankNode* right;
explicit rankNode(int _val,int 0)
:val(_val),left_size(0),left(nullptr),right(nullptr){};
}
class rankTree{
public :
void track(int val){
_track(val,root);
}
int getRank(int val){
return _getRank(val,root);
}
private:
void _track(int val,rankNode* root){
if(root==nullptr){
return new rankNode(val);
}
if(val<=root->val){
(root->left_size)++;
_track(val,root->left);
}else _track(val,root->right);
return root;
}
int _getRank(int val,rankNode* root){
if(root==nullptr) return -1;
if(root->val==val) return root->left_size;
if(root->val>val)
return _getRank(val,root->left);
else {
int rank_right = _getRank(root->right)
if(rank_right==-1) return -1;
return root->left_size+1+ rank_right;
}
}
rankNode* root = nullptr;
}
| [
"chenlei_0630@163.com"
] | chenlei_0630@163.com |
f4e4a539a4b3de15c4b4419f868d76f438aefa8e | 751bdc3d365a64b18d78e8c2fb9f6ea00452764f | /acme/exception/aaa_range.h | 9d9e3bb674fb7cdabdfd542b2ea00a9ea297c50b | [] | no_license | ca2/app | b1de035566d9664aa7c5c9a94378cc352b1836ec | afdedd20df2f6dce81c63bc8a9db6de14503076e | refs/heads/main | 2023-08-27T07:19:45.584624 | 2023-08-26T12:28:28 | 2023-08-26T12:28:28 | 98,031,531 | 19 | 7 | null | 2017-08-14T11:13:14 | 2017-07-22T12:59:27 | C++ | UTF-8 | C++ | false | false | 322 | h | #pragma once
class CLASS_DECL_ACME range_exception :
public ::exception
{
// acme class for resource-critical acme API exceptions
// handles composite and initialization of an error message
public:
range_exception(const ::scoped_string & scopedstrMessage = nullptr);
virtual ~range_exception();
};
| [
"camilosasuketbs@gmail.com"
] | camilosasuketbs@gmail.com |
b912e7e5cba9aab45e8b5761123728128908e79c | c1735457611ad09785755fe71f116468a6b4d89b | /vivado_proj/Zybo-Z7-20-pcam-5c.sdk/pcam_vdma_hdmi/src/main.cc | 7692d652e39003ce53e7f9e972f3313c34c02a70 | [] | no_license | xSmokeAndMirrorsx/Zybo-Z7-10-pcam-SeniorDesign | 16a60e3afd4e019cb4832cf9d5893daa85bd7940 | bcf5284105492d89478f34cc51978138c52f504d | refs/heads/master | 2023-03-11T16:41:22.267009 | 2021-03-01T22:06:27 | 2021-03-01T22:06:27 | 343,569,391 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 12,617 | cc | #include "xparameters.h"
#include "platform/platform.h"
#include "ov5640/OV5640.h"
#include "ov5640/ScuGicInterruptController.h"
#include "ov5640/PS_GPIO.h"
#include "ov5640/AXI_VDMA.h"
#include "ov5640/PS_IIC.h"
#include "xil_printf.h"
#include "MIPI_D_PHY_RX.h"
#include "MIPI_CSI_2_RX.h"
#define IRPT_CTL_DEVID XPAR_PS7_SCUGIC_0_DEVICE_ID
#define GPIO_DEVID XPAR_PS7_GPIO_0_DEVICE_ID
#define GPIO_IRPT_ID XPAR_PS7_GPIO_0_INTR
#define CAM_I2C_DEVID XPAR_PS7_I2C_0_DEVICE_ID
#define CAM_I2C_IRPT_ID XPAR_PS7_I2C_0_INTR
#define VDMA_DEVID XPAR_AXIVDMA_0_DEVICE_ID
#define VDMA_MM2S_IRPT_ID XPAR_FABRIC_AXI_VDMA_0_MM2S_INTROUT_INTR
#define VDMA_S2MM_IRPT_ID XPAR_FABRIC_AXI_VDMA_0_S2MM_INTROUT_INTR
#define CAM_I2C_SCLK_RATE 100000
#define DDR_BASE_ADDR XPAR_DDR_MEM_BASEADDR
#define MEM_BASE_ADDR (DDR_BASE_ADDR + 0x0A000000)
#define GAMMA_BASE_ADDR XPAR_AXI_GAMMACORRECTION_0_BASEADDR
using namespace digilent;
void pipeline_mode_change(AXI_VDMA<ScuGicInterruptController>& vdma_driver, OV5640& cam, VideoOutput& vid, Resolution res, OV5640_cfg::mode_t mode)
{
//Bring up input pipeline back-to-front
{
vdma_driver.resetWrite();
MIPI_CSI_2_RX_mWriteReg(XPAR_MIPI_CSI_2_RX_0_S_AXI_LITE_BASEADDR, CR_OFFSET, (CR_RESET_MASK & ~CR_ENABLE_MASK));
MIPI_D_PHY_RX_mWriteReg(XPAR_MIPI_D_PHY_RX_0_S_AXI_LITE_BASEADDR, CR_OFFSET, (CR_RESET_MASK & ~CR_ENABLE_MASK));
cam.reset();
}
{
vdma_driver.configureWrite(timing[static_cast<int>(res)].h_active, timing[static_cast<int>(res)].v_active);
Xil_Out32(GAMMA_BASE_ADDR, 3); // Set Gamma correction factor to 1/1.8
//TODO CSI-2, D-PHY config here
cam.init();
}
{
vdma_driver.enableWrite();
MIPI_CSI_2_RX_mWriteReg(XPAR_MIPI_CSI_2_RX_0_S_AXI_LITE_BASEADDR, CR_OFFSET, CR_ENABLE_MASK);
MIPI_D_PHY_RX_mWriteReg(XPAR_MIPI_D_PHY_RX_0_S_AXI_LITE_BASEADDR, CR_OFFSET, CR_ENABLE_MASK);
cam.set_mode(mode);
cam.set_awb(OV5640_cfg::awb_t::AWB_ADVANCED);
}
//Bring up output pipeline back-to-front
{
vid.reset();
vdma_driver.resetRead();
}
{
vid.configure(res);
vdma_driver.configureRead(timing[static_cast<int>(res)].h_active, timing[static_cast<int>(res)].v_active);
}
{
vid.enable();
vdma_driver.enableRead();
}
}
int main()
{
//xil_printf("Hello");
init_platform();
ScuGicInterruptController irpt_ctl(IRPT_CTL_DEVID);
PS_GPIO<ScuGicInterruptController> gpio_driver(GPIO_DEVID, irpt_ctl, GPIO_IRPT_ID);
PS_IIC<ScuGicInterruptController> iic_driver(CAM_I2C_DEVID, irpt_ctl, CAM_I2C_IRPT_ID, 100000);
OV5640 cam(iic_driver, gpio_driver);
AXI_VDMA<ScuGicInterruptController> vdma_driver(VDMA_DEVID, MEM_BASE_ADDR, irpt_ctl,
VDMA_MM2S_IRPT_ID,
VDMA_S2MM_IRPT_ID);
VideoOutput vid(XPAR_VTC_0_DEVICE_ID, XPAR_VIDEO_DYNCLK_DEVICE_ID);
pipeline_mode_change(vdma_driver, cam, vid, Resolution::R1920_1080_60_PP, OV5640_cfg::mode_t::MODE_1080P_1920_1080_30fps);
xil_printf("Video init done.\r\n");
// Liquid lens control
uint8_t read_char0 = 0;
uint8_t read_char1 = 0;
uint8_t read_char2 = 0;
uint8_t read_char4 = 0;
uint8_t read_char5 = 0;
uint16_t reg_addr;
uint8_t reg_value;
while (1) {
xil_printf("\r\n\r\n\r\nPcam 5C MAIN OPTIONS\r\n");
xil_printf("\r\nPlease press the key corresponding to the desired option:");
xil_printf("\r\n a. Change Resolution");
xil_printf("\r\n b. Change Liquid Lens Focus");
xil_printf("\r\n d. Change Image Format (Raw or RGB)");
xil_printf("\r\n e. Write a Register Inside the Image Sensor");
xil_printf("\r\n f. Read a Register Inside the Image Sensor");
xil_printf("\r\n g. Change Gamma Correction Factor Value");
xil_printf("\r\n h. Change AWB Settings\r\n\r\n");
read_char0 = getchar();
getchar();
xil_printf("Read: %d\r\n", read_char0);
switch(read_char0) {
case 'a':
xil_printf("\r\n Please press the key corresponding to the desired resolution:");
xil_printf("\r\n 1. 1280 x 720, 60fps");
xil_printf("\r\n 2. 1920 x 1080, 15fps");
xil_printf("\r\n 3. 1920 x 1080, 30fps");
read_char1 = getchar();
getchar();
xil_printf("\r\nRead: %d", read_char1);
switch(read_char1) {
case '1':
pipeline_mode_change(vdma_driver, cam, vid, Resolution::R1280_720_60_PP, OV5640_cfg::mode_t::MODE_720P_1280_720_60fps);
xil_printf("Resolution change done.\r\n");
break;
case '2':
pipeline_mode_change(vdma_driver, cam, vid, Resolution::R1920_1080_60_PP, OV5640_cfg::mode_t::MODE_1080P_1920_1080_15fps);
xil_printf("Resolution change done.\r\n");
break;
case '3':
pipeline_mode_change(vdma_driver, cam, vid, Resolution::R1920_1080_60_PP, OV5640_cfg::mode_t::MODE_1080P_1920_1080_30fps);
xil_printf("Resolution change done.\r\n");
break;
default:
xil_printf("\r\n Selection is outside the available options! Please retry...");
}
break;
case 'b':
xil_printf("\r\n\r\nPlease enter value of liquid lens register, in hex, with small letters: 0x");
//A, B, C,..., F need to be entered with small letters
while (read_char1 < 48) {
read_char1 = getchar();
}
while (read_char2 < 48) {
read_char2 = getchar();
}
getchar();
// If character is a digit, convert from ASCII code to a digit between 0 and 9
if (read_char1 <= 57) {
read_char1 -= 48;
}
// If character is a letter, convert ASCII code to a number between 10 and 15
else {
read_char1 -= 87;
}
// If character is a digit, convert from ASCII code to a digit between 0 and 9
if (read_char2 <= 57) {
read_char2 -= 48;
}
// If character is a letter, convert ASCII code to a number between 10 and 15
else {
read_char2 -= 87;
}
cam.writeRegLiquid((uint8_t) (16*read_char1 + read_char2));
xil_printf("\r\nWrote to liquid lens controller: %x", (uint8_t) (16*read_char1 + read_char2));
break;
case 'd':
xil_printf("\r\n Please press the key corresponding to the desired setting:");
xil_printf("\r\n 1. Select image format to be RGB, output still Raw");
xil_printf("\r\n 2. Select image format & output to both be Raw");
read_char1 = getchar();
getchar();
xil_printf("\r\nRead: %d", read_char1);
switch(read_char1) {
case '1':
cam.set_isp_format(OV5640_cfg::isp_format_t::ISP_RGB);
xil_printf("Settings change done.\r\n");
break;
case '2':
cam.set_isp_format(OV5640_cfg::isp_format_t::ISP_RAW);
xil_printf("Settings change done.\r\n");
break;
default:
xil_printf("\r\n Selection is outside the available options! Please retry...");
}
break;
case 'e':
xil_printf("\r\nPlease enter address of image sensor register, in hex, with small letters: \r\n");
//A, B, C,..., F need to be entered with small letters
while (read_char1 < 48) {
read_char1 = getchar();
}
while (read_char2 < 48) {
read_char2 = getchar();
}
while (read_char4 < 48) {
read_char4 = getchar();
}
while (read_char5 < 48) {
read_char5 = getchar();
}
getchar();
// If character is a digit, convert from ASCII code to a digit between 0 and 9
if (read_char1 <= 57) {
read_char1 -= 48;
}
// If character is a letter, convert ASCII code to a number between 10 and 15
else {
read_char1 -= 87;
}
// If character is a digit, convert from ASCII code to a digit between 0 and 9
if (read_char2 <= 57) {
read_char2 -= 48;
}
// If character is a letter, convert ASCII code to a number between 10 and 15
else {
read_char2 -= 87;
}
// If character is a digit, convert from ASCII code to a digit between 0 and 9
if (read_char4 <= 57) {
read_char4 -= 48;
}
// If character is a letter, convert ASCII code to a number between 10 and 15
else {
read_char4 -= 87;
}
// If character is a digit, convert from ASCII code to a digit between 0 and 9
if (read_char5 <= 57) {
read_char5 -= 48;
}
// If character is a letter, convert ASCII code to a number between 10 and 15
else {
read_char5 -= 87;
}
reg_addr = 16*(16*(16*read_char1 + read_char2)+read_char4)+read_char5;
xil_printf("Desired Register Address: %x\r\n", reg_addr);
read_char1 = 0;
read_char2 = 0;
xil_printf("\r\nPlease enter value of image sensor register, in hex, with small letters: \r\n");
//A, B, C,..., F need to be entered with small letters
while (read_char1 < 48) {
read_char1 = getchar();
}
while (read_char2 < 48) {
read_char2 = getchar();
}
getchar();
// If character is a digit, convert from ASCII code to a digit between 0 and 9
if (read_char1 <= 57) {
read_char1 -= 48;
}
// If character is a letter, convert ASCII code to a number between 10 and 15
else {
read_char1 -= 87;
}
// If character is a digit, convert from ASCII code to a digit between 0 and 9
if (read_char2 <= 57) {
read_char2 -= 48;
}
// If character is a letter, convert ASCII code to a number between 10 and 15
else {
read_char2 -= 87;
}
reg_value = 16*read_char1 + read_char2;
xil_printf("Desired Register Value: %x\r\n", reg_value);
cam.writeReg(reg_addr, reg_value);
xil_printf("Register write done.\r\n");
break;
case 'f':
xil_printf("Please enter address of image sensor register, in hex, with small letters: \r\n");
//A, B, C,..., F need to be entered with small letters
while (read_char1 < 48) {
read_char1 = getchar();
}
while (read_char2 < 48) {
read_char2 = getchar();
}
while (read_char4 < 48) {
read_char4 = getchar();
}
while (read_char5 < 48) {
read_char5 = getchar();
}
getchar();
// If character is a digit, convert from ASCII code to a digit between 0 and 9
if (read_char1 <= 57) {
read_char1 -= 48;
}
// If character is a letter, convert ASCII code to a number between 10 and 15
else {
read_char1 -= 87;
}
// If character is a digit, convert from ASCII code to a digit between 0 and 9
if (read_char2 <= 57) {
read_char2 -= 48;
}
// If character is a letter, convert ASCII code to a number between 10 and 15
else {
read_char2 -= 87;
}
// If character is a digit, convert from ASCII code to a digit between 0 and 9
if (read_char4 <= 57) {
read_char4 -= 48;
}
// If character is a letter, convert ASCII code to a number between 10 and 15
else {
read_char4 -= 87;
}
// If character is a digit, convert from ASCII code to a digit between 0 and 9
if (read_char5 <= 57) {
read_char5 -= 48;
}
// If character is a letter, convert ASCII code to a number between 10 and 15
else {
read_char5 -= 87;
}
reg_addr = 16*(16*(16*read_char1 + read_char2)+read_char4)+read_char5;
xil_printf("Desired Register Address: %x\r\n", reg_addr);
cam.readReg(reg_addr, reg_value);
xil_printf("Value of Desired Register: %x\r\n", reg_value);
break;
case 'g':
xil_printf(" Please press the key corresponding to the desired Gamma factor:\r\n");
xil_printf(" 1. Gamma Factor = 1\r\n");
xil_printf(" 2. Gamma Factor = 1/1.2\r\n");
xil_printf(" 3. Gamma Factor = 1/1.5\r\n");
xil_printf(" 4. Gamma Factor = 1/1.8\r\n");
xil_printf(" 5. Gamma Factor = 1/2.2\r\n");
read_char1 = getchar();
getchar();
xil_printf("Read: %d\r\n", read_char1);
// Convert from ASCII to numeric
read_char1 = read_char1 - 48;
if ((read_char1 > 0) && (read_char1 < 6)) {
Xil_Out32(GAMMA_BASE_ADDR, read_char1-1);
xil_printf("Gamma value changed to 1.\r\n");
}
else {
xil_printf(" Selection is outside the available options! Please retry...\r\n");
}
break;
case 'h':
xil_printf(" Please press the key corresponding to the desired AWB change:\r\n");
xil_printf(" 1. Enable Advanced AWB\r\n");
xil_printf(" 2. Enable Simple AWB\r\n");
xil_printf(" 3. Disable AWB\r\n");
read_char1 = getchar();
getchar();
xil_printf("Read: %d\r\n", read_char1);
switch(read_char1) {
case '1':
cam.set_awb(OV5640_cfg::awb_t::AWB_ADVANCED);
xil_printf("Enabled Advanced AWB\r\n");
break;
case '2':
cam.set_awb(OV5640_cfg::awb_t::AWB_SIMPLE);
xil_printf("Enabled Simple AWB\r\n");
break;
case '3':
cam.set_awb(OV5640_cfg::awb_t::AWB_DISABLED);
xil_printf("Disabled AWB\r\n");
break;
default:
xil_printf(" Selection is outside the available options! Please retry...\r\n");
}
break;
default:
xil_printf(" Selection is outside the available options! Please retry...\r\n");
}
read_char1 = 0;
read_char2 = 0;
read_char4 = 0;
read_char5 = 0;
}
cleanup_platform();
return 0;
}
| [
"46545831+xSmokeAndMirrorsx@users.noreply.github.com"
] | 46545831+xSmokeAndMirrorsx@users.noreply.github.com |
ced33c30f55690d59a9d170c36867f587c0c4117 | 59273b0d26838c005dbf89b35daf503093c95692 | /src/goo_types.cpp | be514f4b132c41ac1629c666f98001ab9176091e | [
"MIT",
"LicenseRef-scancode-unknown"
] | permissive | CrankOne/Goo | 40818bbf028b27cf74f43c294c626a1c764dd2a9 | b909c72a5c87cd11d9c27d42b8332c1b5694cfe0 | refs/heads/development | 2021-01-13T11:32:37.176836 | 2019-10-01T09:54:31 | 2019-10-01T09:54:31 | 77,113,739 | 0 | 0 | MIT | 2018-02-21T13:32:55 | 2016-12-22T05:02:49 | C++ | UTF-8 | C++ | false | false | 1,830 | cpp | /*
* Copyright (c) 2016 Renat R. Dusaev <crank@qcrypt.org>
* Author: Renat R. Dusaev <crank@qcrypt.org>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
# include <unordered_map>
# include <type_traits>
# include <cstring>
# include "goo_exception.hpp"
# include "goo_types.h"
# ifdef ENABLE_GDS
# include "gds/interpreter.h"
# endif
namespace goo {
# define implement_typeid_getter( num, cnm, hnm, gdsnm ) \
template<> AtomicTypeID get_atomic_typeid< cnm >() { return num; }
for_all_atomic_datatypes(implement_typeid_getter)
# undef implement_typeid_getter
# ifdef ENABLE_GDS
extern "C" {
void gds_error(
struct gds_Parser * P,
const char * details ) {
emraise( gdsError, "Parser %p / %s", P, details);
}
} // extern "C"
# endif
// Parser error
} // namespace goo
| [
"crank@qcrypt.org"
] | crank@qcrypt.org |
f33f1a44f432176c0b2d0ecbeead3e699d5022e7 | 09a706649c84e549edcbf20025b0c7758c9a023c | /andador.ino | f2fb664ba9e4c996865de5ec6548401369066b00 | [
"MIT"
] | permissive | Marrquito/Smart_Walker_Project | 6d8ed021b07c19e3595c0d310bf2116749387278 | 4ac11fdd19866c7ae389b2e2be3a5317a2e86ae4 | refs/heads/main | 2023-05-30T23:16:40.209570 | 2021-06-28T21:51:24 | 2021-06-28T21:51:24 | 375,199,977 | 6 | 3 | MIT | 2021-06-28T21:51:25 | 2021-06-09T02:17:49 | C++ | UTF-8 | C++ | false | false | 2,224 | ino | #include <LiquidCrystal.h>
LiquidCrystal LCD(12,11,5,4,3,2); // iniciando a lib do LCD
int button = 13;
int buttonStart = 0;
int buttonEnd = 0;
int ledRed = 10;
float calculaCelsius(){ // func para calcular °C
int tmp;
float voltage, milliVolt, celsius;
// serie de conversoes retiradas da documentacao do sensor
tmp = analogRead(A0); // tmp recebe o valor lido da porta analogica A0
voltage = (tmp * 5.0) / 1024;
milliVolt = voltage * 1000;
celsius = (milliVolt - 500 ) / 10;
return celsius;
}
void VerificaCelsiusCM(){
LCD.print("Celsius: ");
LCD.print(calculaCelsius());
delay(700);
LCD.clear();
delay(700);
}
/* void VerificaCelsiusSM(float *celsius){
LCD.print(calculaCelsius());
delay(500);
LCD.clear();
delay(500);
*celsius = calculaCelsius();
}
*/
void setup(){
pinMode(button, INPUT);
pinMode(ledRed, OUTPUT);
LCD.begin(18, 4); // inicia os pixels da telinha
LCD.setCursor(0, 1); // onde a telinha inicia
pinMode(A0, INPUT); // sensor de temperatura
pinMode(27, OUTPUT); // porta do sensor de temperatura
Serial.begin(9600);
}
void loop(){
int i, press = 1, press2 = 1;
float celsius;
buttonStart = digitalRead(button);
celsius = calculaCelsius();
if(celsius >= 35.5){
while(1){
press = 1;
if(celsius >= 35.5 && press == 1){ // veio botou a mao = ligou
celsius = calculaCelsius();
VerificaCelsiusCM();
press2 = 1;
}else if(celsius < 35.5){ // tirou a mao = desligado ( precisa enviar msg )
LCD.print("stand-by...");
delay(1000);
LCD.clear();
while(press2){
for(i = 60; i >= 0; i--){
if(celsius >= 35.5) break;
buttonStart = digitalRead(button);
if(buttonStart == HIGH){
delay(1000);
LCD.print("Desligando...");
delay(1000);
press2 = 0;
break;
}else{
celsius = calculaCelsius();
//VerificaCelsiusSM(&celsius);
LCD.print("DESATIVE...");
delay(1000);
}
digitalWrite(ledRed, HIGH);
delay(1000);
digitalWrite(ledRed, LOW);
}
}
// envia mensagem pro ctt de emergencia aqui
celsius = calculaCelsius();
}
celsius = calculaCelsius();
}
}
} | [
"marcossetin@hotmail.com"
] | marcossetin@hotmail.com |
52c2805c383aef01a4dfa0abf7fff33e399772f3 | df0d7d165d8f83ecafaccfca5c566bc00d01d8af | /algo-W6-vectorField_wParticles-space_kittens/src/particle.cpp | 4515b45cc29f067c3c4b4a2fe48996fe3bcc7e99 | [] | no_license | esrutledge/Algo_Fall_2011 | defeeb153db26a8b91528a1a4fe0e7e29e2bca61 | 04c676a6a8dbdd7184a1fb0f57ad9c42846f4f71 | refs/heads/master | 2021-01-22T09:48:48.563745 | 2011-12-24T03:17:37 | 2011-12-24T03:17:37 | 2,362,295 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,415 | cpp | #include "particle.h"
#include "ofMain.h"
//------------------------------------------------------------
particle::particle(){
setInitialCondition(0,0,0,0);
damping = 0.08f;
whichCat = floor(ofRandom(4.9999));
std::stringstream ss;
ss << "cat" << whichCat + 1 << ".png";
std::string fileName = ss.str();
catImg.loadImage(fileName);
}
//------------------------------------------------------------
void particle::resetForce(){
// we reset the forces every frame
frc.set(0,0);
}
//------------------------------------------------------------
void particle::addForce(float x, float y){
// add in a force in X and Y for this frame.
frc.x = frc.x + x;
frc.y = frc.y + y;
}
//------------------------------------------------------------
void particle::addDampingForce(){
// the usual way to write this is vel *= 0.99
// basically, subtract some part of the velocity
// damping is a force operating in the oposite direction of the
// velocity vector
frc.x = frc.x - vel.x * damping;
frc.y = frc.y - vel.y * damping;
}
//------------------------------------------------------------
void particle::setInitialCondition(float px, float py, float vx, float vy){
pos.set(px,py);
vel.set(vx,vy);
}
//------------------------------------------------------------
void particle::update(){
vel = vel + frc;
pos = pos + vel;
}
//------------------------------------------------------------
void particle::draw(){
// ofCircle(pos.x, pos.y, 3);
catImg.draw(pos.x, pos.y);
}
//------------------------------------------------------------
void particle::bounceOffWalls(){
// sometimes it makes sense to damped, when we hit
bool bDampedOnCollision = true;
bool bDidICollide = false;
// what are the walls
float minx = 0;
float miny = 0;
float maxx = ofGetWidth();
float maxy = ofGetHeight();
if (pos.x > maxx){
pos.x = maxx; // move to the edge, (important!)
vel.x *= -1;
bDidICollide = true;
} else if (pos.x < minx){
pos.x = minx; // move to the edge, (important!)
vel.x *= -1;
bDidICollide = true;
}
if (pos.y > maxy){
pos.y = maxy; // move to the edge, (important!)
vel.y *= -1;
bDidICollide = true;
} else if (pos.y < miny){
pos.y = miny; // move to the edge, (important!)
vel.y *= -1;
bDidICollide = true;
}
if (bDidICollide == true && bDampedOnCollision == true){
vel *= 0.3;
}
}
| [
"liz@expandtheroom.com"
] | liz@expandtheroom.com |
7a2adbc982dc16e1e236c726ddaf995caf5fab0a | 54af716ec2dfec37696cc48f60a463d4873246de | /fem2D/Constraint/CorotateFEMConstraint.cpp | e7a2a3d5bcb68fb09f726641f047ef432dd74971 | [
"Apache-2.0"
] | permissive | snumrl/volcon2D | 4d3f6e531867e9914ea37df411cc164cadedb515 | 4b4277cef2caa0f62429781acedc71d9f8b6bd0d | refs/heads/master | 2022-03-19T05:56:37.827918 | 2019-12-06T08:28:27 | 2019-12-06T08:28:27 | 107,930,334 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,584 | cpp | #include "CorotateFEMConstraint.h"
#include <Eigen/SVD>
#include <Eigen/LU>
#include <iostream>
using namespace FEM;
void SVD2x2(const Eigen::Matrix2d& F,Eigen::Matrix2d& U, Eigen::Matrix2d& D, Eigen::Matrix2d& V,Eigen::Matrix2d& R)
{
double EE = (F(0,0)+F(1,1))*0.5;
double FF = (F(0,0)-F(1,1))*0.5;
double GG = (F(1,0)+F(0,1))*0.5;
double HH = (F(1,0)-F(0,1))*0.5;
double QQ = sqrt(EE*EE+HH*HH);
double RR = sqrt(FF*FF+GG*GG);
D(0,0) = QQ+RR;
D(1,1) = QQ-RR;
if(QQ-RR<0)
exit(0);
double alpha = atan2(GG,FF);
double beta = atan2(HH,EE);
double phi = (alpha+beta)*(-0.5);
double theta = (alpha-beta)*(-0.5);
double cphi = cos(phi);
double sphi = sin(phi);
double cthe = cos(theta);
double sthe = sin(theta);
U(0,0) = cphi;
U(0,1) = sphi;
U(1,0) = -sphi;
U(1,1) = cphi;
V(0,0) = cthe;
V(0,1) = sthe;
V(1,0) = -sthe;
V(1,1) = cthe;
R(0,0) = cphi*cthe+sphi*sthe;
R(0,1) = sphi*cthe-cphi*sthe;
R(1,1) = R(0,0);
R(1,0) = -R(0,1);
}
bool
CorotateFEMConstraint::
ComputeDeformationGradient(const Eigen::VectorXd& x)
{
FEMConstraint::ComputeDeformationGradient(x);
ComputeSVD(mCacheF);
return true;
}
void
CorotateFEMConstraint::
ComputeSVD(const Eigen::Matrix2d& F)
{
Eigen::JacobiSVD<Eigen::Matrix2d> svd(F, Eigen::ComputeFullU | Eigen::ComputeFullV);
auto D = svd.singularValues();
mCacheD(0,0) = D[0];
mCacheD(1,1) = D[1];
mCacheU = svd.matrixU();
mCacheV = svd.matrixV();
mCacheR = mCacheU*mCacheV.transpose();
// SVD2x2(F,mCacheU,mCacheD,mCacheV,mCacheR);
mCacheF = F;
}
void
CorotateFEMConstraint::
ComputedP(const Eigen::Matrix2d& dF,Eigen::Matrix2d& dP)
{
Eigen::Matrix2d dR;
ComputedR(dF,dR);
dP = mMu*(dF - dR) +
mLambda*(
(dR.transpose()*mCacheF+mCacheR.transpose()*dF).trace()*mCacheR +
(mCacheR.transpose()*mCacheF-Eigen::Matrix2d::Identity()).trace()*dR
);
}
void
CorotateFEMConstraint::
ComputedR(const Eigen::Matrix2d& dF,Eigen::Matrix2d& dR)
{
double d1 = mCacheD(0,0);
double d2 = mCacheD(1,1);
if(fabs(d1-d2)<1E-6){
Eigen::Matrix2d off_diag_M,M;
M = mCacheU.transpose()* dF * mCacheV;
off_diag_M = M;
off_diag_M(0,0) = 0.0;
off_diag_M(1,1) = 0.0;
off_diag_M *= (1.0/d1);
dR = mCacheU*off_diag_M*(mCacheV.transpose());
}
else
{
Eigen::Matrix2d Ainv;
Eigen::Vector2d uv_tilda,m1221;
Eigen::Matrix2d U_tilda,V_tilda;
Ainv << d2,d1,
d1,d2;
Ainv *= (1.0/(d2*d2-d1*d1));
U_tilda.setZero();
V_tilda.setZero();
Eigen::Matrix2d M = mCacheU.transpose()*dF*mCacheV;
m1221[0] = M(0,1);
m1221[1] = M(1,0);
uv_tilda = Ainv*m1221;
U_tilda(0,1) = uv_tilda[0];
U_tilda(1,0) = -uv_tilda[0];
V_tilda(0,1) = uv_tilda[1];
V_tilda(1,0) = -uv_tilda[1];
U_tilda = mCacheU*U_tilda; //dU
V_tilda = mCacheV*V_tilda; //dV
dR = (U_tilda*(mCacheV.transpose()) + mCacheU*(V_tilda.transpose()));
}
}
CorotateFEMConstraint::
CorotateFEMConstraint(const double& stiffness,const double& poisson_ratio,int i0,int i1,int i2,double vol,const Eigen::Matrix2d& invDm)
:FEMConstraint(stiffness,poisson_ratio,i0,i1,i2,vol,invDm),
mCacheU(Eigen::Matrix2d::Zero()),
mCacheV(Eigen::Matrix2d::Zero()),
mCacheD(Eigen::Matrix2d::Zero()),
mCacheR(Eigen::Matrix2d::Zero())
{
}
double
CorotateFEMConstraint::
EvalPotentialEnergy(const Eigen::VectorXd& x)
{
ComputeDeformationGradient(x);
double vol_preserve_sqrt = (mCacheD-Eigen::Matrix2d::Identity()).trace();
return mVol*(0.5*mMu*((mCacheF - mCacheR).norm())+0.5*mLambda*vol_preserve_sqrt*vol_preserve_sqrt);
}
void
CorotateFEMConstraint::
EvalGradient(const Eigen::VectorXd& x, Eigen::VectorXd& gradient)
{
auto p0 = x.block<2,1>(mi0*2,0);
auto p1 = x.block<2,1>(mi1*2,0);
auto p2 = x.block<2,1>(mi2*2,0);
auto d01 = p1 - p0;
auto d02 = p2 - p0;
// std::cout<<d01[0]*d02[1] - d01[1]*d02[0]<<std::endl;
// std::cout<<d01[0]*d02[1] - d01[1]*d02[0]<<std::endl;
// std::cout<<mCacheF.determinant()<<std::endl;
ComputeDeformationGradient(x);
Eigen::Matrix2d P = mMu*(mCacheF - mCacheR) + mLambda*((mCacheR.transpose()*mCacheF-Eigen::Matrix2d::Identity()).trace())*mCacheR;
P = mVol*P*(mInvDm.transpose());
gradient.block<2,1>(mi0*2,0) += -(P.block<2,1>(0,0) + P.block<2,1>(0,1));
gradient.block<2,1>(mi1*2,0) += P.block<2,1>(0,0);
gradient.block<2,1>(mi2*2,0) += P.block<2,1>(0,1);
}
void
CorotateFEMConstraint::
EvalHessian(const Eigen::VectorXd& x, const Eigen::VectorXd& dx, Eigen::VectorXd& dg)
{
ComputeDeformationGradient(x);
Eigen::Matrix2d dDs,dF,dP;
Eigen::Vector2d dx0(dx.block<2,1>(mi0*2,0));
dDs.block<2,1>(0,0) = dx.block<2,1>(mi1*2,0)-dx0;
dDs.block<2,1>(0,1) = dx.block<2,1>(mi2*2,0)-dx0;
dF = dDs*(mInvDm);
ComputedP(dF,dP);
dP = mVol * dP * (mInvDm.transpose());
dg.block<2,1>(mi0*2,0) += -(dP.block<2,1>(0,0) + dP.block<2,1>(0,1));
dg.block<2,1>(mi1*2,0) += dP.block<2,1>(0,0);
dg.block<2,1>(mi2*2,0) += dP.block<2,1>(0,1);
}
void
CorotateFEMConstraint::
EvaluateDVector(int index, const Eigen::VectorXd& x,Eigen::VectorXd& d)
{
ComputeDeformationGradient(x);
double a1,a2,d1,d2;
Eigen::Matrix2d D;
a1 = mCacheD(0,0);
a2 = mCacheD(1,1);
D.setZero();
for(int i=0;i<10;i++)
{
d1 = D(0,0);
d2 = D(1,1);
double S = (d1*d2 - a1*a2 + 1)/(a1*a1 + a2*a2 + d1*d1 + d2*d2 + 2*a1*d1 + 2*a2*d2);
D(0,0) = S*(a2 + d2);
D(1,1) = S*(a1 + d1);
}
auto R_star = (0.1*mCacheR + 0.9*mCacheU*(D+mCacheD)*(mCacheV.transpose()));
// auto R_star = mCacheR;
d.block<2,1>(2*index,0) = R_star.block<2,1>(0,0);
d.block<2,1>(2*index+2,0) = R_star.block<2,1>(0,1);
}
void
CorotateFEMConstraint::
EvaluateJMatrix(int index, std::vector<Eigen::Triplet<double>>& J_triplets)
{
Eigen::MatrixXd Ai(2*2,2*3);
double d11 = mInvDm(0,0);
double d12 = mInvDm(0,1);
double d21 = mInvDm(1,0);
double d22 = mInvDm(1,1);
Ai<<
-d11-d21,0,d11,0,d21,0,
0,-d11-d21,0,d11,0,d21,
-d12-d22,0,d12,0,d22,0,
0,-d12-d22,0,d12,0,d22;
auto MuAiT = 10.0*mMu*mVol*Ai.transpose();
J_triplets.push_back(Eigen::Triplet<double>(2*mi0+0, 2*index+0, MuAiT(2*0+0,2*0+0)));
J_triplets.push_back(Eigen::Triplet<double>(2*mi0+0, 2*index+1, MuAiT(2*0+0,2*0+1)));
J_triplets.push_back(Eigen::Triplet<double>(2*mi0+0, 2*index+2, MuAiT(2*0+0,2*0+2)));
J_triplets.push_back(Eigen::Triplet<double>(2*mi0+0, 2*index+3, MuAiT(2*0+0,2*0+3)));
J_triplets.push_back(Eigen::Triplet<double>(2*mi0+1, 2*index+0, MuAiT(2*0+1,2*0+0)));
J_triplets.push_back(Eigen::Triplet<double>(2*mi0+1, 2*index+1, MuAiT(2*0+1,2*0+1)));
J_triplets.push_back(Eigen::Triplet<double>(2*mi0+1, 2*index+2, MuAiT(2*0+1,2*0+2)));
J_triplets.push_back(Eigen::Triplet<double>(2*mi0+1, 2*index+3, MuAiT(2*0+1,2*0+3)));
J_triplets.push_back(Eigen::Triplet<double>(2*mi1+0, 2*index+0, MuAiT(2*1+0,2*0+0)));
J_triplets.push_back(Eigen::Triplet<double>(2*mi1+0, 2*index+1, MuAiT(2*1+0,2*0+1)));
J_triplets.push_back(Eigen::Triplet<double>(2*mi1+0, 2*index+2, MuAiT(2*1+0,2*0+2)));
J_triplets.push_back(Eigen::Triplet<double>(2*mi1+0, 2*index+3, MuAiT(2*1+0,2*0+3)));
J_triplets.push_back(Eigen::Triplet<double>(2*mi1+1, 2*index+0, MuAiT(2*1+1,2*0+0)));
J_triplets.push_back(Eigen::Triplet<double>(2*mi1+1, 2*index+1, MuAiT(2*1+1,2*0+1)));
J_triplets.push_back(Eigen::Triplet<double>(2*mi1+1, 2*index+2, MuAiT(2*1+1,2*0+2)));
J_triplets.push_back(Eigen::Triplet<double>(2*mi1+1, 2*index+3, MuAiT(2*1+1,2*0+3)));
J_triplets.push_back(Eigen::Triplet<double>(2*mi2+0, 2*index+0, MuAiT(2*2+0,2*0+0)));
J_triplets.push_back(Eigen::Triplet<double>(2*mi2+0, 2*index+1, MuAiT(2*2+0,2*0+1)));
J_triplets.push_back(Eigen::Triplet<double>(2*mi2+0, 2*index+2, MuAiT(2*2+0,2*0+2)));
J_triplets.push_back(Eigen::Triplet<double>(2*mi2+0, 2*index+3, MuAiT(2*2+0,2*0+3)));
J_triplets.push_back(Eigen::Triplet<double>(2*mi2+1, 2*index+0, MuAiT(2*2+1,2*0+0)));
J_triplets.push_back(Eigen::Triplet<double>(2*mi2+1, 2*index+1, MuAiT(2*2+1,2*0+1)));
J_triplets.push_back(Eigen::Triplet<double>(2*mi2+1, 2*index+2, MuAiT(2*2+1,2*0+2)));
J_triplets.push_back(Eigen::Triplet<double>(2*mi2+1, 2*index+3, MuAiT(2*2+1,2*0+3)));
}
void
CorotateFEMConstraint::
EvaluateLMatrix(std::vector<Eigen::Triplet<double>>& L_triplets)
{
Eigen::MatrixXd Ai(2*2,2*3);
double d11 = mInvDm(0,0);
double d12 = mInvDm(0,1);
double d21 = mInvDm(1,0);
double d22 = mInvDm(1,1);
Ai<<
-d11-d21,0,d11,0,d21,0,
0,-d11-d21,0,d11,0,d21,
-d12-d22,0,d12,0,d22,0,
0,-d12-d22,0,d12,0,d22;
auto MuAiTAi = 10.0*mMu*mVol*((Ai.transpose())*Ai);
L_triplets.push_back(Eigen::Triplet<double>(2*mi0+0,2*mi0+0,MuAiTAi(2*0+0, 2*0+0)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi0+0,2*mi0+1,MuAiTAi(2*0+0, 2*0+1)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi0+1,2*mi0+0,MuAiTAi(2*0+1, 2*0+0)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi0+1,2*mi0+1,MuAiTAi(2*0+1, 2*0+1)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi0+0,2*mi1+0,MuAiTAi(2*0+0, 2*1+0)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi0+0,2*mi1+1,MuAiTAi(2*0+0, 2*1+1)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi0+1,2*mi1+0,MuAiTAi(2*0+1, 2*1+0)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi0+1,2*mi1+1,MuAiTAi(2*0+1, 2*1+1)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi0+0,2*mi2+0,MuAiTAi(2*0+0, 2*2+0)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi0+0,2*mi2+1,MuAiTAi(2*0+0, 2*2+1)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi0+1,2*mi2+0,MuAiTAi(2*0+1, 2*2+0)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi0+1,2*mi2+1,MuAiTAi(2*0+1, 2*2+1)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi1+0,2*mi0+0,MuAiTAi(2*1+0, 2*0+0)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi1+0,2*mi0+1,MuAiTAi(2*1+0, 2*0+1)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi1+1,2*mi0+0,MuAiTAi(2*1+1, 2*0+0)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi1+1,2*mi0+1,MuAiTAi(2*1+1, 2*0+1)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi1+0,2*mi1+0,MuAiTAi(2*1+0, 2*1+0)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi1+0,2*mi1+1,MuAiTAi(2*1+0, 2*1+1)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi1+1,2*mi1+0,MuAiTAi(2*1+1, 2*1+0)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi1+1,2*mi1+1,MuAiTAi(2*1+1, 2*1+1)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi1+0,2*mi2+0,MuAiTAi(2*1+0, 2*2+0)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi1+0,2*mi2+1,MuAiTAi(2*1+0, 2*2+1)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi1+1,2*mi2+0,MuAiTAi(2*1+1, 2*2+0)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi1+1,2*mi2+1,MuAiTAi(2*1+1, 2*2+1)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi2+0,2*mi0+0,MuAiTAi(2*2+0, 2*0+0)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi2+0,2*mi0+1,MuAiTAi(2*2+0, 2*0+1)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi2+1,2*mi0+0,MuAiTAi(2*2+1, 2*0+0)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi2+1,2*mi0+1,MuAiTAi(2*2+1, 2*0+1)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi2+0,2*mi1+0,MuAiTAi(2*2+0, 2*1+0)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi2+0,2*mi1+1,MuAiTAi(2*2+0, 2*1+1)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi2+1,2*mi1+0,MuAiTAi(2*2+1, 2*1+0)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi2+1,2*mi1+1,MuAiTAi(2*2+1, 2*1+1)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi2+0,2*mi2+0,MuAiTAi(2*2+0, 2*2+0)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi2+0,2*mi2+1,MuAiTAi(2*2+0, 2*2+1)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi2+1,2*mi2+0,MuAiTAi(2*2+1, 2*2+0)));
L_triplets.push_back(Eigen::Triplet<double>(2*mi2+1,2*mi2+1,MuAiTAi(2*2+1, 2*2+1)));
}
ConstraintType
CorotateFEMConstraint::
GetType()
{
return ConstraintType::COROTATE;
}
| [
"lsw9021@snu.ac.kr"
] | lsw9021@snu.ac.kr |
03b409df3591dced7e3b3c061e89780770dcb04b | 5571c726df6cd5b90739e99bd5e8c4d80710b0ff | /librf/src/unix/coroutine.h | f56c1afeb80c6f97523cbfd79d9ee1865791cf5a | [
"Apache-2.0"
] | permissive | HungMingWu/librf | 0597ac1b292db94ed6706d357fd80b2fb03aa2e6 | d3c568ca8c717e6e6d9607aee55e3da219a33c1e | refs/heads/master | 2021-07-06T06:40:16.063719 | 2020-06-20T06:53:57 | 2020-07-08T02:14:20 | 129,230,713 | 0 | 0 | Apache-2.0 | 2018-04-12T09:57:13 | 2018-04-12T09:57:13 | null | UTF-8 | C++ | false | false | 7,993 | h | //===----------------------------- coroutine -----------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#ifndef _LIBCPP_EXPERIMENTAL_COROUTINE
#define _LIBCPP_EXPERIMENTAL_COROUTINE
#define _EXPERIMENTAL_COROUTINE_
#include <new>
#include <type_traits>
#include <functional>
#include <memory> // for hash<T*>
#include <cstddef>
#include <cassert>
#include <compare>
#if defined(__clang__)
#include "clang_builtin.h"
#elif defined(__GNUC__)
#include "gcc_builtin.h"
#endif
#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
#pragma GCC system_header
#endif
#ifndef _LIBCPP_HAS_NO_COROUTINES
namespace std {
#if defined(__GNUC__)
inline
#endif
namespace experimental {
template <class _Tp, class = void>
struct __coroutine_traits_sfinae {};
template <class _Tp>
struct __coroutine_traits_sfinae<_Tp, void_t<typename _Tp::promise_type>>
{
using promise_type = typename _Tp::promise_type;
};
// 17.12.2, coroutine traits
template <typename _Ret, typename... _Args>
struct coroutine_traits : public __coroutine_traits_sfinae<_Ret>
{
};
// 17.12.3, coroutine handle
template <typename _Promise = void>
class coroutine_handle;
template <>
class coroutine_handle<void>
{
public:
// 17.12.3.1, construct/reset
constexpr coroutine_handle() noexcept : __handle_(nullptr) {}
constexpr coroutine_handle(nullptr_t) noexcept : __handle_(nullptr) {}
coroutine_handle& operator=(nullptr_t) noexcept {
__handle_ = nullptr;
return *this;
}
// 17.12.3.2, export/import
constexpr void* address() const noexcept { return __handle_; }
static constexpr coroutine_handle from_address(void* __addr) noexcept {
coroutine_handle __tmp;
__tmp.__handle_ = __addr;
return __tmp;
}
// FIXME: Should from_address(nullptr) be allowed?
static constexpr coroutine_handle from_address(nullptr_t) noexcept {
return coroutine_handle(nullptr);
}
template <class _Tp, bool _CallIsValid = false>
static coroutine_handle from_address(_Tp*) {
static_assert(_CallIsValid,
"coroutine_handle<void>::from_address cannot be called with "
"non-void pointers");
}
// 17.12.3.3, observers
constexpr explicit operator bool() const noexcept {
return __handle_ != nullptr;
}
bool done() const {
return __builtin_coro_done(__handle_);
}
// 17.12.3.4, resumption
void operator()() const { resume(); }
void resume() const {
__builtin_coro_resume(__handle_);
}
void destroy() const{
__builtin_coro_destroy(__handle_);
}
private:
bool __is_suspended() const noexcept {
// FIXME actually implement a check for if the coro is suspended.
return __handle_;
}
template <class _PromiseT>
friend class coroutine_handle;
void* __handle_;
};
// 17.12.3.6, comparison operators
inline bool operator==(coroutine_handle<> __x, coroutine_handle<> __y) noexcept {
return __x.address() == __y.address();
}
inline bool operator!=(coroutine_handle<> __x, coroutine_handle<> __y) noexcept {
return __x.address() != __y.address();
}
inline bool operator<(coroutine_handle<> __x, coroutine_handle<> __y) noexcept {
return __x.address() < __y.address();
}
inline bool operator>(coroutine_handle<> __x, coroutine_handle<> __y) noexcept {
return __x.address() > __y.address();
}
inline bool operator<=(coroutine_handle<> __x, coroutine_handle<> __y) noexcept {
return __x.address() <= __y.address();
}
inline bool operator>=(coroutine_handle<> __x, coroutine_handle<> __y) noexcept {
return __x.address() >= __y.address();
}
template <typename _Promise>
class coroutine_handle : public coroutine_handle<>
{
using _Base = coroutine_handle<>;
public:
// 17.12.3.1, construct/reset
using coroutine_handle<>::coroutine_handle;
coroutine_handle& operator=(nullptr_t) noexcept {
_Base::operator=(nullptr);
return *this;
}
// 17.12.3.5, promise access
_Promise& promise() const {
return *static_cast<_Promise*>(
__builtin_coro_promise(this->__handle_, alignof(_Promise), false));
}
public:
// 17.12.3.2, export/import
static constexpr coroutine_handle from_address(void* __addr) noexcept {
coroutine_handle __tmp;
__tmp.__handle_ = __addr;
return __tmp;
}
// NOTE: this overload isn't required by the standard but is needed so
// the deleted _Promise* overload doesn't make from_address(nullptr)
// ambiguous.
// FIXME: should from_address work with nullptr?
static constexpr coroutine_handle from_address(nullptr_t) noexcept {
return coroutine_handle(nullptr);
}
template <class _Tp, bool _CallIsValid = false>
static coroutine_handle from_address(_Tp*) {
static_assert(_CallIsValid,
"coroutine_handle<promise_type>::from_address cannot be called with "
"non-void pointers");
}
template <bool _CallIsValid = false>
static coroutine_handle from_address(_Promise*) {
static_assert(_CallIsValid,
"coroutine_handle<promise_type>::from_address cannot be used with "
"pointers to the coroutine's promise type; use 'from_promise' instead");
}
static coroutine_handle from_promise(_Promise& __promise) noexcept {
typedef typename remove_cv<_Promise>::type _RawPromise;
coroutine_handle __tmp;
__tmp.__handle_ = __builtin_coro_promise(
std::addressof(const_cast<_RawPromise&>(__promise)),
alignof(_Promise), true);
return __tmp;
}
};
// 17.12.4, no-op coroutines
#if __has_builtin(__builtin_coro_noop)
struct noop_coroutine_promise {};
template <>
class coroutine_handle<noop_coroutine_promise> : public coroutine_handle<>
{
using _Base = coroutine_handle<>;
using _Promise = noop_coroutine_promise;
public:
// 17.12.4.2.3, promise access
_Promise& promise() const noexcept {
return *static_cast<_Promise*>(
__builtin_coro_promise(this->__handle_, alignof(_Promise), false));
}
// 17.12.4.2.4, address
constexpr void* address() const noexcept {
return this->__handle_;
}
// 17.12.4.2.1, observers
constexpr explicit operator bool() const noexcept { return true; }
constexpr bool done() const noexcept { return false; }
// 17.12.4.2.2, resumption
constexpr void operator()() const noexcept {}
constexpr void resume() const noexcept {}
constexpr void destroy() const noexcept {}
private:
friend coroutine_handle<noop_coroutine_promise> noop_coroutine() noexcept;
coroutine_handle() noexcept {
this->__handle_ = __builtin_coro_noop();
}
};
using noop_coroutine_handle = coroutine_handle<noop_coroutine_promise>;
inline noop_coroutine_handle noop_coroutine() noexcept {
return noop_coroutine_handle();
}
#endif // __has_builtin(__builtin_coro_noop)
// 17.12.5, trivial awaitables
struct suspend_never {
constexpr bool await_ready() const noexcept { return true; }
constexpr void await_suspend(coroutine_handle<>) const noexcept {}
constexpr void await_resume() const noexcept {}
};
struct suspend_always {
constexpr bool await_ready() const noexcept { return false; }
constexpr void await_suspend(coroutine_handle<>) const noexcept {}
constexpr void await_resume() const noexcept {}
};
}
// 17.12.3.7, hash support
template <class _Tp>
struct hash<experimental::coroutine_handle<_Tp>> {
using argument_type = experimental::coroutine_handle<_Tp>;
using result_type = size_t;
using __arg_type = experimental::coroutine_handle<_Tp>;
size_t operator()(__arg_type const& __v) const noexcept
{
return hash<void*>()(__v.address());
}
};
}
#endif // !defined(_LIBCPP_HAS_NO_COROUTINES)
#endif /* _LIBCPP_EXPERIMENTAL_COROUTINE */ | [
"tearshark@163.com"
] | tearshark@163.com |
e0cc7bf29a593fc0bd718f885c77cbc7eb2c7ff8 | 6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849 | /sstd_boost/sstd/boost/mpl/aux_/adl_barrier.hpp | a6cf18c8fa5f44cd96b57be4f78df4536f8f1e26 | [
"BSL-1.0"
] | permissive | KqSMea8/sstd_library | 9e4e622e1b01bed5de7322c2682539400d13dd58 | 0fcb815f50d538517e70a788914da7fbbe786ce1 | refs/heads/master | 2020-05-03T21:07:01.650034 | 2019-04-01T00:10:47 | 2019-04-01T00:10:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,575 | hpp |
#ifndef BOOST_MPL_AUX_ADL_BARRIER_HPP_INCLUDED
#define BOOST_MPL_AUX_ADL_BARRIER_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2002-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id$
// $Date$
// $Revision$
#include <sstd/boost/mpl/aux_/config/adl.hpp>
#include <sstd/boost/mpl/aux_/config/gcc.hpp>
#include <sstd/boost/mpl/aux_/config/workaround.hpp>
#if !defined(BOOST_MPL_CFG_NO_ADL_BARRIER_NAMESPACE)
# define BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE mpl_
# define BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_OPEN namespace mpl_ {
# define BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_CLOSE }
# define BOOST_MPL_AUX_ADL_BARRIER_DECL(type) \
namespace boost { namespace mpl { \
using ::BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE::type; \
} } \
/**/
#if !defined(BOOST_MPL_PREPROCESSING_MODE)
namespace BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE { namespace aux {} }
namespace boost { namespace mpl { using namespace BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE;
namespace aux { using namespace BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE::aux; }
}}
#endif
#else // BOOST_MPL_CFG_NO_ADL_BARRIER_NAMESPACE
# define BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE boost::mpl
# define BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_OPEN namespace boost { namespace mpl {
# define BOOST_MPL_AUX_ADL_BARRIER_NAMESPACE_CLOSE }}
# define BOOST_MPL_AUX_ADL_BARRIER_DECL(type) /**/
#endif
#endif // BOOST_MPL_AUX_ADL_BARRIER_HPP_INCLUDED
| [
"zhaixueqiang@hotmail.com"
] | zhaixueqiang@hotmail.com |
51ac8469421f658e1b46e27fc1f5573e7fc28f65 | fc585e577235a03b2ec749f5a947e2e3cde9c97f | /src/Externals/spire/es-log/trace-log.cc | 06ca8834b011f37e1394092e27ff8569ed8b983c | [
"MIT"
] | permissive | gongch/SCIRun | 670b85f8aa45681580fa7406dc9cc91ca550a1f2 | d8b26d69ebb3b087dcdd861bed2da115133a468f | refs/heads/master | 2021-01-03T18:52:56.346016 | 2020-02-12T16:05:55 | 2020-02-12T16:05:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,942 | cc | /*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2015 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <es-log/trace-log.h>
using namespace spire;
//using namespace SCIRun::Core::Logging;
//SCIRun::Core::Logging::Logger2 RendererLog::logger_;
//
//const char* RendererLog::name()
//{
// return "renderer";
//}
//
//Logger2 RendererLog::get()
//{
// static bool first = true;
//
// if (first)
// {
// //first = false;
// //#ifdef RENDERER_TRACE_ON
// //logger_ = spdlog::basic_logger_mt(name(), "renderer.log");
// //#else
// //logger_ = spdlog::stdout_color_mt(name());
// //#endif
// //logger_->set_level(spdlog::level::trace);
// //logger_->flush_on(spdlog::level::info);
// //logger_->info("Start of Renderer log.");
// }
// return logger_;
//}
| [
"dwhite@sci.utah.edu"
] | dwhite@sci.utah.edu |
4f5a0cc69571cc2ff7c6b33779233403cc9a4173 | 1783b6714c5614155c7584bcad0a028345100cbe | /Functions/MathFunctions.cpp | ff08e01187a1ef7ace742886abcf7023de741d43 | [] | no_license | ShreyaDhir/Cpp | 203d637ab5e9033ba01a37a16379b2d1f8c3f108 | 8c8ccee62d748f30a596c3eb6116074def958bf8 | refs/heads/master | 2023-01-20T01:13:59.202682 | 2020-11-29T11:38:47 | 2020-11-29T11:38:47 | 271,291,203 | 1 | 2 | null | 2020-10-03T07:09:27 | 2020-06-10T13:56:47 | C++ | UTF-8 | C++ | false | false | 715 | cpp | // Math Functions
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
double num{};
cout<<"Enter any number(double): "<<endl;
cin>>num;
cout<<"Sqrt of "<<num<<" is "<<sqrt(num)<<endl;
cout<<"Cube root of "<<num<<" is "<<cbrt(num)<<endl;
cout<<"Sine of "<<num<<" is "<<sin(num)<<endl;
cout<<"Cosine of "<<num<<" is "<<cos(num)<<endl;
cout<<"Ceil of "<<num<<" is "<<ceil(num)<<endl;
cout<<"Floor of "<<num<<" is "<<floor(num)<<endl;
cout<<"Round of "<<num<<" is "<<round(num)<<endl;
double power{};
cout<<"Enter the number to be raised to: ";
cin>>power;
cout<<"The number "<<num<<" raised to the power "<<power<<" is "
<<pow(num,power)<<endl;
return 0;
}
| [
"dhirshreya@gmail.com"
] | dhirshreya@gmail.com |
1aa918e62bc432c803ddbfb368b724f52f1ebad1 | 4634e53c16603e1ab727c0ccfbeaefdec3323eac | /src/qt/miningpage.cpp | c0f0f0e4393b5dea3dd9dc09c9e59ccafecdd5f9 | [
"OpenSSL",
"MIT"
] | permissive | peeejayz/DopeCoin | b233467e4ba293f834025627860b9e513182bea5 | 4153513f7ceef9ae72486b9a3331ddaed347501d | refs/heads/master | 2021-01-01T15:36:13.145316 | 2014-02-10T12:51:27 | 2014-02-10T12:51:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,678 | cpp | #include "miningpage.h"
#include "ui_miningpage.h"
MiningPage::MiningPage(QWidget *parent) :
QWidget(parent),
ui(new Ui::MiningPage)
{
ui->setupUi(this);
setFixedSize(400, 420);
minerActive = false;
minerProcess = new QProcess(this);
minerProcess->setProcessChannelMode(QProcess::MergedChannels);
readTimer = new QTimer(this);
acceptedShares = 0;
rejectedShares = 0;
roundAcceptedShares = 0;
roundRejectedShares = 0;
initThreads = 0;
connect(readTimer, SIGNAL(timeout()), this, SLOT(readProcessOutput()));
connect(ui->startButton, SIGNAL(pressed()), this, SLOT(startPressed()));
connect(ui->typeBox, SIGNAL(currentIndexChanged(int)), this, SLOT(typeChanged(int)));
connect(ui->debugCheckBox, SIGNAL(toggled(bool)), this, SLOT(debugToggled(bool)));
connect(minerProcess, SIGNAL(started()), this, SLOT(minerStarted()));
connect(minerProcess, SIGNAL(error(QProcess::ProcessError)), this, SLOT(minerError(QProcess::ProcessError)));
connect(minerProcess, SIGNAL(finished(int,QProcess::ExitStatus)), this, SLOT(minerFinished()));
connect(minerProcess, SIGNAL(readyRead()), this, SLOT(readProcessOutput()));
}
MiningPage::~MiningPage()
{
minerProcess->kill();
delete ui;
}
void MiningPage::setModel(ClientModel *model)
{
this->model = model;
loadSettings();
bool pool = model->getMiningType() == ClientModel::PoolMining;
ui->threadsBox->setValue(model->getMiningThreads());
ui->typeBox->setCurrentIndex(pool ? 1 : 0);
// if (model->getMiningStarted())
// startPressed();
}
void MiningPage::startPressed()
{
initThreads = ui->threadsBox->value();
if (minerActive == false)
{
saveSettings();
if (getMiningType() == ClientModel::SoloMining)
minerStarted();
else
startPoolMining();
}
else
{
if (getMiningType() == ClientModel::SoloMining)
minerFinished();
else
stopPoolMining();
}
}
void MiningPage::startPoolMining()
{
QStringList args;
QString url = ui->serverLine->text();
if (!url.contains("http://"))
url.prepend("http://");
QString urlLine = QString("%1:%2").arg(url, ui->portLine->text());
QString userpassLine = QString("%1:%2").arg(ui->usernameLine->text(), ui->passwordLine->text());
args << "--algo" << "scrypt";
args << "--scantime" << ui->scantimeBox->text().toAscii();
args << "--url" << urlLine.toAscii();
args << "--userpass" << userpassLine.toAscii();
args << "--threads" << ui->threadsBox->text().toAscii();
args << "--retries" << "-1"; // Retry forever.
args << "-P"; // This is needed for this to work correctly on Windows. Extra protocol dump helps flush the buffer quicker.
threadSpeed.clear();
acceptedShares = 0;
rejectedShares = 0;
roundAcceptedShares = 0;
roundRejectedShares = 0;
// If minerd is in current path, then use that. Otherwise, assume minerd is in the path somewhere.
QString program = QDir::current().filePath("minerd");
if (!QFile::exists(program))
program = "minerd";
if (ui->debugCheckBox->isChecked())
ui->list->addItem(args.join(" ").prepend(" ").prepend(program));
ui->mineSpeedLabel->setText("Speed: N/A");
ui->shareCount->setText("Accepted: 0 - Rejected: 0");
minerProcess->start(program,args);
minerProcess->waitForStarted(-1);
readTimer->start(500);
}
void MiningPage::stopPoolMining()
{
ui->mineSpeedLabel->setText("");
minerProcess->kill();
readTimer->stop();
}
void MiningPage::saveSettings()
{
model->setMiningDebug(ui->debugCheckBox->isChecked());
model->setMiningScanTime(ui->scantimeBox->value());
model->setMiningServer(ui->serverLine->text());
model->setMiningPort(ui->portLine->text());
model->setMiningUsername(ui->usernameLine->text());
model->setMiningPassword(ui->passwordLine->text());
}
void MiningPage::loadSettings()
{
ui->debugCheckBox->setChecked(model->getMiningDebug());
ui->scantimeBox->setValue(model->getMiningScanTime());
ui->serverLine->setText(model->getMiningServer());
ui->portLine->setText(model->getMiningPort());
ui->usernameLine->setText(model->getMiningUsername());
ui->passwordLine->setText(model->getMiningPassword());
}
void MiningPage::readProcessOutput()
{
QByteArray output;
minerProcess->reset();
output = minerProcess->readAll();
QString outputString(output);
if (!outputString.isEmpty())
{
QStringList list = outputString.split("\n", QString::SkipEmptyParts);
int i;
for (i=0; i<list.size(); i++)
{
QString line = list.at(i);
// Ignore protocol dump
if (!line.startsWith("[") || line.contains("JSON protocol") || line.contains("HTTP hdr"))
continue;
if (ui->debugCheckBox->isChecked())
{
ui->list->addItem(line.trimmed());
ui->list->scrollToBottom();
}
if (line.contains("(yay!!!)"))
reportToList("Share accepted", SHARE_SUCCESS, getTime(line));
else if (line.contains("(booooo)"))
reportToList("Share rejected", SHARE_FAIL, getTime(line));
else if (line.contains("LONGPOLL detected new block"))
reportToList("LONGPOLL detected a new block", LONGPOLL, getTime(line));
else if (line.contains("Supported options:"))
reportToList("Miner didn't start properly. Try checking your settings.", ERROR, NULL);
else if (line.contains("The requested URL returned error: 403"))
reportToList("Couldn't connect. Please check your username and password.", ERROR, NULL);
else if (line.contains("HTTP request failed"))
reportToList("Couldn't connect. Please check pool server and port.", ERROR, NULL);
else if (line.contains("JSON-RPC call failed"))
reportToList("Couldn't communicate with server. Retrying in 30 seconds.", ERROR, NULL);
else if (line.contains("thread ") && line.contains("khash/s"))
{
QString threadIDstr = line.at(line.indexOf("thread ")+7);
int threadID = threadIDstr.toInt();
int threadSpeedindx = line.indexOf(",");
QString threadSpeedstr = line.mid(threadSpeedindx);
threadSpeedstr.chop(8);
threadSpeedstr.remove(", ");
threadSpeedstr.remove(" ");
threadSpeedstr.remove('\n');
double speed=0;
speed = threadSpeedstr.toDouble();
threadSpeed[threadID] = speed;
updateSpeed();
}
}
}
}
void MiningPage::minerError(QProcess::ProcessError error)
{
if (error == QProcess::FailedToStart)
{
reportToList("Miner failed to start. Make sure you have the minerd executable and libraries in the same directory as dopecoin-Qt.", ERROR, NULL);
}
}
void MiningPage::minerFinished()
{
if (getMiningType() == ClientModel::SoloMining)
reportToList("Solo mining stopped.", ERROR, NULL);
else
reportToList("Miner exited.", ERROR, NULL);
ui->list->addItem("");
minerActive = false;
resetMiningButton();
model->setMining(getMiningType(), false, initThreads, 0);
}
void MiningPage::minerStarted()
{
if (!minerActive)
if (getMiningType() == ClientModel::SoloMining)
reportToList("Solo mining started.", ERROR, NULL);
else
reportToList("Miner started. You might not see any output for a few minutes.", STARTED, NULL);
minerActive = true;
resetMiningButton();
model->setMining(getMiningType(), true, initThreads, 0);
}
void MiningPage::updateSpeed()
{
double totalSpeed=0;
int totalThreads=0;
QMapIterator<int, double> iter(threadSpeed);
while(iter.hasNext())
{
iter.next();
totalSpeed += iter.value();
totalThreads++;
}
// If all threads haven't reported the hash speed yet, make an assumption
if (totalThreads != initThreads)
{
totalSpeed = (totalSpeed/totalThreads)*initThreads;
}
QString speedString = QString("%1").arg(totalSpeed);
QString threadsString = QString("%1").arg(initThreads);
QString acceptedString = QString("%1").arg(acceptedShares);
QString rejectedString = QString("%1").arg(rejectedShares);
QString roundAcceptedString = QString("%1").arg(roundAcceptedShares);
QString roundRejectedString = QString("%1").arg(roundRejectedShares);
if (totalThreads == initThreads)
ui->mineSpeedLabel->setText(QString("Speed: %1 khash/sec - %2 thread(s)").arg(speedString, threadsString));
else
ui->mineSpeedLabel->setText(QString("Speed: ~%1 khash/sec - %2 thread(s)").arg(speedString, threadsString));
ui->shareCount->setText(QString("Accepted: %1 (%3) - Rejected: %2 (%4)").arg(acceptedString, rejectedString, roundAcceptedString, roundRejectedString));
model->setMining(getMiningType(), true, initThreads, totalSpeed*1000);
}
void MiningPage::reportToList(QString msg, int type, QString time)
{
QString message;
if (time == NULL)
message = QString("[%1] - %2").arg(QTime::currentTime().toString(), msg);
else
message = QString("[%1] - %2").arg(time, msg);
switch(type)
{
case SHARE_SUCCESS:
acceptedShares++;
roundAcceptedShares++;
updateSpeed();
break;
case SHARE_FAIL:
rejectedShares++;
roundRejectedShares++;
updateSpeed();
break;
case LONGPOLL:
roundAcceptedShares = 0;
roundRejectedShares = 0;
break;
default:
break;
}
ui->list->addItem(message);
ui->list->scrollToBottom();
}
// Function for fetching the time
QString MiningPage::getTime(QString time)
{
if (time.contains("["))
{
time.resize(21);
time.remove("[");
time.remove("]");
time.remove(0,11);
return time;
}
else
return NULL;
}
void MiningPage::enableMiningControls(bool enable)
{
ui->typeBox->setEnabled(enable);
ui->threadsBox->setEnabled(enable);
ui->scantimeBox->setEnabled(enable);
ui->serverLine->setEnabled(enable);
ui->portLine->setEnabled(enable);
ui->usernameLine->setEnabled(enable);
ui->passwordLine->setEnabled(enable);
}
void MiningPage::enablePoolMiningControls(bool enable)
{
ui->scantimeBox->setEnabled(enable);
ui->serverLine->setEnabled(enable);
ui->portLine->setEnabled(enable);
ui->usernameLine->setEnabled(enable);
ui->passwordLine->setEnabled(enable);
}
ClientModel::MiningType MiningPage::getMiningType()
{
if (ui->typeBox->currentIndex() == 0) // Solo Mining
{
return ClientModel::SoloMining;
}
else if (ui->typeBox->currentIndex() == 1) // Pool Mining
{
return ClientModel::PoolMining;
}
return ClientModel::SoloMining;
}
void MiningPage::typeChanged(int index)
{
if (index == 0) // Solo Mining
{
enablePoolMiningControls(false);
}
else if (index == 1) // Pool Mining
{
enablePoolMiningControls(true);
}
}
void MiningPage::debugToggled(bool checked)
{
model->setMiningDebug(checked);
}
void MiningPage::resetMiningButton()
{
ui->startButton->setText(minerActive ? "Stop Mining" : "Start Mining");
enableMiningControls(!minerActive);
}
| [
"lexerom@gmail.com"
] | lexerom@gmail.com |
d6fb1f4b3193706546f3542aa60213ead67f4543 | 6beecae61b6cf917ea4acd90f4064a13375d4457 | /cob_roboskin_exp/src/trajectory_export_data.cpp | 236b1712876be9d66b0d4870bde97570a55fd251 | [] | no_license | ipa-rmb-mo/cob_bringup_sandbox | f1d0fd1f4d5fa239be27380efdfd12566eb99ecc | da256f1ef78d0e3e985685dd17d7930c56360414 | refs/heads/master | 2020-05-29T11:57:54.578091 | 2016-11-07T01:51:38 | 2016-11-07T01:51:38 | 56,847,368 | 0 | 1 | null | 2016-04-22T10:24:06 | 2016-04-22T10:24:06 | null | UTF-8 | C++ | false | false | 536 | cpp | #include "ros/ros.h"
#include "pr2_controllers_msgs/JointTrajectoryControllerState.h"
using namespace std;
void chatterCallback(const pr2_controllers_msgs::JointTrajectoryControllerState msg)
{
cout << ros::Time::now() << " ";
for (int i=0;i<7;i++){
cout << msg.actual.velocities[i] << " ";
}
cout << "\n";
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "listener8");
ros::NodeHandle n1;
ros::Subscriber sub1 = n1.subscribe("arm_controller/state", 10000, chatterCallback);
ros::spin();
return 0;
}
| [
"nadia.hammoudeh-garcia@ipa.fraunhofer.de"
] | nadia.hammoudeh-garcia@ipa.fraunhofer.de |
f84eb4218c1f7d8e86da2860cca73edd274c7940 | a9effd0e63e65382ab2c3c5fbb5c5116f4306033 | /FCollada/FUtils/FUPluginManager.cpp | 109e1e10dd055516d2e64f1878685a25afa8694e | [
"LicenseRef-scancode-x11-xconsortium-veillard",
"MIT"
] | permissive | jwthomp/OGE | 7cdf8ce96d0c44ea1bfcac063b6a2a745cf23a60 | ddf059dea71c0879cb44c1c62ba4df1d6086b721 | refs/heads/master | 2022-11-19T21:54:57.073795 | 2020-07-22T17:21:16 | 2020-07-22T17:21:16 | 281,739,974 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,507 | cpp | /*
Copyright (C) 2005-2007 Feeling Software Inc.
Portions of the code are:
Copyright (C) 2005-2007 Sony Computer Entertainment America
MIT License: http://www.opensource.org/licenses/mit-license.php
*/
#include "StdAfx.h"
#include "FUtils/FUPlugin.h"
#include "FUtils/FUPluginManager.h"
#include "FUtils/FUFileManager.h"
#ifdef WIN32
#include <io.h>
#if defined(UNICODE)
#define ffinddata _wfinddata_t
#define ffindfirst _wfindfirst
#define ffindclose _findclose
#define ffindnext _wfindnext
#else // UNICODE
#define ffinddata _finddata_t
#define ffindfirst _findfirst
#define ffindclose _findclose
#define ffindnext _findnext
#endif
#elif defined(MAC_TIGER) || defined(LINUX)
#include <dlfcn.h>
#include <dirent.h>
#endif //WIN32
//
// FUPlugin
//
ImplementObjectType(FUPlugin);
//
// FUPluginManager
//
FUPluginManager::FUPluginManager(const fchar* _filter)
{
fstring applicationFolderName = FUFileManager::GetApplicationFolderName();
// Append the wanted extension for the plugins.
FUStringBuilder pluginFolder(applicationFolderName);
fchar lastChar = applicationFolderName[pluginFolder.length() - 1];
if (lastChar != '\\' && lastChar != '/') pluginFolder.append((fchar) '/');
pluginFolder.append(FC("Plugins/"));
pluginFolderName = pluginFolder.ToString();
if (_filter == NULL || _filter[0] == 0) _filter = FC("*.*");
do
{
const fchar* nextFilter = fstrchr(_filter, '|');
fstring filter(_filter);
if (nextFilter != NULL)
{
filter.erase(nextFilter - _filter);
++nextFilter; // skip the pipe.
}
_filter = nextFilter;
// Windows-only for now.
#if defined(WIN32)
// Iterate over all the filtered files within the given folder.
ffinddata folderIterator;
fstring searchString = pluginFolderName + filter;
intptr_t folderHandle = ffindfirst(searchString.c_str(), &folderIterator);
if (folderHandle != -1L)
{
int32 isDone = FALSE;
while (isDone == FALSE)
{
bool keep = false;
PluginLibrary* library = new PluginLibrary();
library->filename = pluginFolderName + folderIterator.name;
library->module = LoadLibrary(library->filename.c_str());
if (library->module != NULL)
{
// Retrieve the necessary callbacks
library->getPluginCount = (GetPluginCount) GetProcAddress(library->module, "GetPluginCount");
library->getPluginType = (GetPluginType) GetProcAddress(library->module, "GetPluginType");
library->createPlugin = (CreatePlugin) GetProcAddress(library->module, "CreatePlugin");
keep = library->createPlugin != NULL && library->getPluginType != NULL && library->getPluginCount != NULL;
}
// This is a valid library.
if (keep) loadedLibraries.push_back(library);
else { SAFE_DELETE(library); }
isDone = ffindnext(folderHandle, &folderIterator);
}
ffindclose(folderHandle);
}
#elif defined(MAC_TIGER) || defined(LINUX)
fm::string s_filter = TO_STRING(filter);
if (s_filter.length() > 0 && s_filter.front() == '*') s_filter.erase(0, 1);
if (s_filter.length() > 0 && s_filter.back() == '*') s_filter.pop_back();
DIR* directory = opendir(TO_STRING(pluginFolderName).c_str());
if (directory == NULL) continue;
dirent* directoryEntry;
while ((directoryEntry = readdir(directory)) != NULL)
{
if (directoryEntry->d_type == DT_DIR) continue; // skip sub-folders.
if (strstr((const char*) directoryEntry->d_name, s_filter.c_str()) != NULL)
{
// We have a match.
bool keep = false;
PluginLibrary* library = new PluginLibrary();
library->filename = pluginFolderName + TO_FSTRING((const char*) directoryEntry->d_name);
fm::string libraryModuleFilename = TO_STRING(library->filename);
DEBUG_OUT1("Found dynamic library: %s\n", libraryModuleFilename.c_str());
library->module = dlopen(libraryModuleFilename.c_str(), RTLD_NOW);
if (library->module != NULL)
{
// Retrieve the necessary callbacks
library->getPluginCount = (GetPluginCount) dlsym(library->module, "GetPluginCount");
library->getPluginType = (GetPluginType) dlsym(library->module, "GetPluginType");
library->createPlugin = (CreatePlugin) dlsym(library->module, "CreatePlugin");
keep = library->createPlugin != NULL && library->getPluginType != NULL && library->getPluginCount != NULL;
}
// This is a valid library.
if (keep) loadedLibraries.push_back(library);
else { SAFE_DELETE(library); }
}
}
closedir(directory);
#endif // WIN32
} while (_filter != NULL);
}
FUPluginManager::~FUPluginManager()
{
UnloadPlugins();
FUAssert(loadedPlugins.empty(), return);
// Detach all the plugin libraries.
for (PluginLibraryList::iterator it = loadedLibraries.begin(); it != loadedLibraries.end(); ++it)
{
#if defined(WIN32)
if ((*it)->module != NULL) FreeLibrary((*it)->module);
#elif defined(LINUX) || defined(MAC_TIGER)
if ((*it)->module != NULL) dlclose((*it)->module);
#endif // WIN32
}
CLEAR_POINTER_VECTOR(loadedLibraries);
}
void FUPluginManager::LoadPlugins(const FUObjectType& pluginType)
{
for (PluginLibraryList::iterator it = loadedLibraries.begin(); it != loadedLibraries.end(); ++it)
{
#ifndef _DEBUG
try
#endif // _DEBUG
{
DEBUG_OUT1("Loading plug-in: %s\n", (*it)->filename.c_str());
FUAssert((*it)->createPlugin != NULL && (*it)->getPluginType != NULL && (*it)->getPluginCount != NULL, continue);
uint32 pluginCount = (*((*it)->getPluginCount))();
for (uint32 i = 0; i < pluginCount; ++i)
{
// Retrieve the types of all the plug-ins within this library.
// Compare them against the wanted types and create the wanted plug-ins.
const FUObjectType* type = (*((*it)->getPluginType))(i);
if (type->Includes(pluginType))
{
FUPlugin* plugin = (*((*it)->createPlugin))(i);
if (plugin == NULL) continue;
loadedPlugins.push_back(plugin);
}
}
}
#ifndef _DEBUG
catch (...)
{
fm::string _filename = TO_STRING((*it)->filename);
ERROR_OUT1("Unhandled exception when loading plugin: %s.", _filename.c_str());
}
#endif // _DEBUG
}
}
void FUPluginManager::AddPluginLibrary(FUPluginManager::GetPluginCount fnGetPluginCount, FUPluginManager::GetPluginType fnGetPluginType, FUPluginManager::CreatePlugin fnCreatePlugin)
{
PluginLibrary* library = new PluginLibrary();
library->getPluginCount = fnGetPluginCount;
library->getPluginType = fnGetPluginType;
library->createPlugin = fnCreatePlugin;
loadedLibraries.push_back(library);
}
void FUPluginManager::UnloadPlugins()
{
loadedPlugins.clear();
}
| [
"jeffthompson@granular.ag"
] | jeffthompson@granular.ag |
83d54da377c9002f18951c7659c74d57b1f18070 | df4cbdd5af2c1dee8e293c2315f73478433c68ae | /functions.h | 282806cd45aea913818b410f680b577d40506a08 | [] | no_license | AlmazKo/WoodCube | bf99b8fea8af988f606fb6f53272c807d86a7c29 | 877e58fc6de899f7d21463ec71f17a7b5a3571c1 | refs/heads/master | 2021-01-24T06:13:12.524914 | 2012-03-25T05:25:03 | 2012-03-25T05:25:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,059 | h | #ifndef FUNCTIONS_H
#define FUNCTIONS_H
#include <iostream>
#include <string.h>
namespace wood_cube {
const short matrix[4][3][3] = {};
const short PLANCH_LEVEL = 8;
const short BUSY_ITEM = 1;
const short ITEMS = 6;
const short items[ITEMS][3][3] = {
{
{0, 0, 1},
{0 | PLANCH_LEVEL, 0 | PLANCH_LEVEL, 1 | PLANCH_LEVEL},
{0, 0, 0}
},
{
{0, 1, 0},
{0 | PLANCH_LEVEL, 1 | PLANCH_LEVEL, 1 | PLANCH_LEVEL},
{0, 0, 1}
},
{
{0, 1, 0},
{1 | PLANCH_LEVEL, 1 | PLANCH_LEVEL, 0 | PLANCH_LEVEL},
{1, 0, 0}
},
{
{1, 0, 0},
{1 | PLANCH_LEVEL, 0 | PLANCH_LEVEL, 1 | PLANCH_LEVEL},
{0, 0, 1}
},
{
{0, 1, 0},
{1 | PLANCH_LEVEL, 1 | PLANCH_LEVEL, 1 | PLANCH_LEVEL},
{1, 0, 1}
},
{
{1, 1, 0},
{1 | PLANCH_LEVEL, 1 | PLANCH_LEVEL, 1 | PLANCH_LEVEL},
{0, 0, 1}
},
};
struct successfull
{
bool ready;
short item;
short position;
short turn;
short turn_upside_down;
successfull() :
ready(false), item(0), position(0), turn(0), turn_upside_down(0)
{
}
};
typedef short planch[3][3];
typedef short box[4][3][3];
const short ALL_ITEMS_SIZE = sizeof (items);
const short ITEMS_SIZE = sizeof (planch);
const short MATRIX_SIZE = sizeof (box);
const short RESULT_SIZE = sizeof (successfull) * ITEMS;
bool start(successfull result[ITEMS], box current_matrix);
void turn(const planch item, planch out);
void turn_upside_down(const planch item, planch out);
void add_planch(const short position, const planch item, box out_matrix, short);
bool check_box(const box matrix);
bool check_result(const successfull result[ITEMS]);
bool in_result(const short id, const successfull result[ITEMS]);
void show_planch(const planch item);
void show_box(const box matrix);
void show_result(const successfull result[ITEMS]);
void show_binary(unsigned dec);
void show_solution(const successfull result[ITEMS], const box matrix, int found);
}
#endif // FUNCTIONS_H
| [
"almaz@Almaz-comp.(none)"
] | almaz@Almaz-comp.(none) |
d58d6528000a70cd15637d3c14e69041fffbc62f | 9b3a63fcd4d5aae16806186836068682c2281c6b | /StereoKitC/sk_math.h | c646fc13ba9f4c2e0b86293eb843b4682bbd4f8c | [
"MIT"
] | permissive | cwule/StereoKit | 04c0ac8bb9bc7361b9638ce36b4f8a7790fa475d | 99aaa4fb71c0420519a903e15deb3da9875e0f99 | refs/heads/master | 2023-06-11T17:26:26.155391 | 2021-05-14T22:53:47 | 2021-05-14T22:53:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,027 | h | #pragma once
#include "stereokit.h"
#ifndef _MSC_VER
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunknown-pragmas"
#endif
#include <DirectXMath.h>
#ifndef _MSC_VER
#pragma clang diagnostic pop
#endif
#define MATH_PI 3.1415926535898f
namespace sk {
void matrix_mul(const matrix &a, const matrix &b, DirectX::XMMATRIX &out_matrix);
void matrix_mul(const matrix &a, const DirectX::XMMATRIX &b, DirectX::XMMATRIX &out_matrix);
vec3 matrix_mul_point (const DirectX::XMMATRIX &transform, const vec3 &point);
vec3 matrix_mul_direction(const DirectX::XMMATRIX &transform, const vec3 &direction);
///////////////////////////////////////////
inline DirectX::XMVECTOR math_vec3_to_fast(const vec3 &vector) {
return DirectX::XMLoadFloat3((DirectX::XMFLOAT3 *)&vector);
}
///////////////////////////////////////////
inline DirectX::XMVECTOR math_quat_to_fast(const quat &quaternion) {
return DirectX::XMLoadFloat4((DirectX::XMFLOAT4 *)&quaternion);
}
///////////////////////////////////////////
inline vec3 math_fast_to_vec3(const DirectX::XMVECTOR &a) {
vec3 result;
DirectX::XMStoreFloat3((DirectX::XMFLOAT3 *)&result, a);
return result;
}
///////////////////////////////////////////
inline quat math_fast_to_quat(const DirectX::XMVECTOR &a) {
quat result;
DirectX::XMStoreFloat4((DirectX::XMFLOAT4 *)&result, a);
return result;
}
///////////////////////////////////////////
inline void math_matrix_to_fast(const matrix &mat, DirectX::XMMATRIX *out_matrix) {
*out_matrix = DirectX::XMLoadFloat4x4((DirectX::XMFLOAT4X4 *)&mat.row);
}
///////////////////////////////////////////
inline void math_fast_to_matrix(const DirectX::XMMATRIX &mat, matrix *out_matrix) {
DirectX::XMStoreFloat4x4((DirectX::XMFLOAT4X4 *)out_matrix, mat);
}
///////////////////////////////////////////
inline int32_t maxi(int32_t a, int32_t b) { return a > b ? a : b; }
inline uint32_t maxi(uint32_t a, uint32_t b) { return a > b ? a : b; }
inline int64_t maxi(int64_t a, int64_t b) { return a > b ? a : b; }
inline uint64_t maxi(uint64_t a, uint64_t b) { return a > b ? a : b; }
inline int32_t mini(int32_t a, int32_t b) { return a < b ? a : b; }
inline uint32_t mini(uint32_t a, uint32_t b) { return a < b ? a : b; }
inline int64_t mini(int64_t a, int64_t b) { return a < b ? a : b; }
inline uint64_t mini(uint64_t a, uint64_t b) { return a < b ? a : b; }
inline float math_lerp (float a, float b, float t) { return a + (b - a) * t; }
inline float math_lerp_cl (float a, float b, float t) { return a + (b - a) * fminf(1,t); }
inline float math_saturate(float x) { return fmaxf(0, fminf(1, x)); }
inline float math_ease_overshoot(float a, float b, float overshoot, float t) { t = 1 - t; return math_lerp(a,b, 1-(t*t * ((overshoot + 1) * t - overshoot))); }
inline float math_ease_hop (float a, float peak, float t) { return a+(peak-a)*sinf(t*MATH_PI); }
vec3 bounds_corner (const bounds_t &bounds, int32_t index8);
vec3 math_cubemap_corner(int i);
} // namespace sk | [
"programmerpichu@gmail.com"
] | programmerpichu@gmail.com |
37ba5c84f16c785b54480641456a6a8699cc294a | e54fb4ef0578756841a3704c1746e57e01b26d74 | /Assignment3.cpp | 14bf20b22ed325419bc2bbc97100ea21734d4583 | [] | no_license | phamtuan0946621237/FPT-Aptech | 74867163de8fc5f902837057eb696d551cc00d80 | c663e5d204070131b43ff8fbf7344b5ac9d22892 | refs/heads/master | 2020-09-23T00:28:02.555286 | 2019-12-25T12:44:15 | 2019-12-25T12:44:15 | 225,353,666 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,812 | cpp |
#include <stdio.h>
int main() {
// 1. Nhập vào 2 số nguyên a,b. Nếu a >= b thì in ra kết quả của a/b, ngược lại thì in ra kết quả của a*b
int a;
int b;
scanf("%d",&a);
scanf("%d",&b);
if(a>=b){
printf("%d/%d\n",a,b);
}else{
printf("%d * %d\n",a,b );
}
// 2. Nhập vào 1 số nguyên, in ra là đó thứ mấy hoặc ko phải ngày trong tuần.
int number;
scanf("%d",&number);
if(number <= 7){
printf(" thứ %d là ngày trong tuần",number);
}else{
printf(" đây không phải ngày trong tuần");
}
// 3. Nhập 2 số là giá trị của tháng và ngày. Kiểm tra xem đó là ngày thứ bao nhiêu trong năm, và đó là đang thứ mấy. Với giả sử rằng: ngày 1/1 là ngày thứ 2 và năm không nhuận
int c;
int d;
scanf("%d",&c);
scanf("%d",&d);
if(d<=7){
if(d%2=0){
ngay= (a/2)*31 + (a/2 -1)*30 -2 + d;
printf("ngày %d tháng %d là ngày số %d trong năm",c,d,ngay);
thumay= ngay % 7;
printf(" ngày %d là thứ %d trong năm",thumay );
}else{
ngay= [(a-1)/2]*31 + [(a-1)/2]*30 -2 + d;
printf("ngày %d tháng %d là ngày số %d trong năm",c,d,ngay);
thumay= ngay % 7;
printf(" ngày %d là thứ %d trong năm",thumay );
}
}else{
if(d%2=0){
ngay = (d/2)*31+ [(a/2)-2]*30 -2 + d;
printf("ngày %d tháng %d là ngày số %d trong năm",c,d,ngay);
thumay= ngay % 7;
printf(" ngày %d là thứ %d trong năm",thumay );
}else{
ngay = [(d+1)/2]*31+ [(a/2)-3]*30 -2 + d;
printf("ngày %d tháng %d là ngày số %d trong năm",c,d,ngay);
thumay= ngay % 7;
printf(" ngày %d là thứ %d trong năm",thumay );
}
}
// 4.- Nhập vào 3 số nguyên a,b,c. Kiểm tra xem đây có phải 3 cạnh của 1 tam giác hay không
// Ở ý trên nếu là 3 cạnh tam giác, tính và in ra chu vi - diện tích tam giác.
float canh1;
float canh2;
float canh3;
float chieucao1;
scanf("%f",&canh1);
scanf("%f",&canh2);
scanf("%f",&canh3);
if((canh1 + canh2 > canh3) || (canh1 + canh3 > canh2) || (canh3 + canh2 > canh1)){
prinntf("đây là 1 tam giác\n");
float chieucao;
float dientich= (chieucao1 + canh1)/2;
float chuvi = canh1 + canh2 + canh3;
printf(" chu vi của tam giác là %f\n",chuvi);
printf("dien tich tam giác là %f\n", dientich);
if((canh1=canh2) && (canh1=canh3) && (canh3=canh2)) {
printf(" đây là tam giác đều\n");
}else if ( (canh1=canh2) || (canh1=canh3) || (canh3=canh2)){
printf(" đây là tam giác cân \n");
}else if ( (canh1*canh1 = canh2*canh2 + canh3*canh3) ||(canh2*canh2 = canh1*canh1 + canh3*canh3) ||(canh3*canh3 = canh2*canh2 + canh1*canh1) )
printf(" đây là tam giác vuông ");
}
}else{
printf("đây không phải tam giác");
}
} | [
"phamtuannd200997@gmail.com"
] | phamtuannd200997@gmail.com |
96e550c3caa025e27611bdfc386b4d7d47433ef9 | bf876e45eee0d83b595651b7214e9e8fe3168d43 | /challenge/2.18.cpp | fe3a347949b0a80141ff46faf38e431e68c62095 | [] | no_license | samwensko/COMS-171 | a61b933994e3c265c9145f6c74cb3ee781265e86 | 127240ba249d9cb6fe619231735c8da7cc6717e8 | refs/heads/master | 2020-03-28T13:25:53.974885 | 2018-11-14T01:10:40 | 2018-11-14T01:10:40 | 148,394,813 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 772 | cpp | #include <iostream>
using namespace std;
//In a survery of 16,500 customers, 15% purchase one or more energy drinks per week.
//Of those who purchase energy drinks, 58% of them prefer citrus flavor.
//Calculate and display the following:
//The approximate number of customers who purchase one or more energy drinks
//The approximate number of customers who prefer citrus flavor.
int main() {
int surveyedCustomers = 16500,
purchasedEnergyDrinks = 0.15 * surveyedCustomers,
preferCitrus = 0.58 * (0.15 * surveyedCustomers);
cout << "Out of 16,500 customers surveyed, " <<
purchasedEnergyDrinks <<
" purchase energy drinks at least once per week. Of those who purchase energy drinks, " <<
preferCitrus <<
" of them prefer citrus flavored drinks.\n";
}
| [
"samwensko@gmail.com"
] | samwensko@gmail.com |
13f5e1b584d33263114dabdcaf9b1ea58d297235 | 3a9f2b3d79cf214704829427ee280f4b49dca70a | /mycode/qt/day6/waitconditon/waitcondition.h | 968d6522c38aeb4aae409797b59f9ef557d38d61 | [] | no_license | jichunwei/MyGitHub-1 | ae0c1461fe0a337ef459da7c0d24d4cf8d4a4791 | f826fc89a030c6c4e08052d2d43af0b1b4b410e3 | refs/heads/master | 2021-01-21T10:19:22.900905 | 2016-08-20T03:34:52 | 2016-08-20T03:34:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 403 | h | #ifndef WAITCONDITION_H
#define WAITCONDITION_H
#include <qthread.h>
#include <qmutex.h>
#include <qwaitcondition.h>
#include <qdebug.h>
static int global = 0;
static QMutex mutex;
static QWaitCondition waitcondition;
class Wait : public QThread
{
Q_OBJECT
protected:
void run();
};
class Wakeup : public QThread{
Q_OBJECT
protected:
void run();
};
#endif // WAITCONDITION_H
| [
"tan@xx.com"
] | tan@xx.com |
1120e671d5f3a2bf1098f13177259dd4c694887b | d4a2ec86c5b8a564ee7f7ceb27277d25e5454cb5 | /Qt/TrainBoom/logindialog.h | 1f12e1ac1fee921df8de2f7a24345a6fa5f3931d | [] | no_license | zidaneandmessi/TrainBoom_FrontEnd | 8ef62587340312f84fc19f3c496ad403e842c6f2 | fbccf33519cee32f390f598749186adfda7abebd | refs/heads/master | 2021-01-20T14:53:14.382944 | 2017-05-16T13:49:20 | 2017-05-16T13:49:20 | 90,684,345 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 457 | h | #ifndef LOGINDIALOG_H
#define LOGINDIALOG_H
#include <QDialog>
#include <QJsonObject>
namespace Ui {
class LoginDialog;
}
class LoginDialog : public QDialog
{
Q_OBJECT
public:
explicit LoginDialog(QWidget *parent = 0);
~LoginDialog();
QJsonObject sendUser();
signals:
private slots:
void on_loginBtn_clicked();
void on_regBtn_clicked();
private:
Ui::LoginDialog *ui;
QJsonObject usrInfo;
};
#endif // LOGINDIALOG_H
| [
"dimar@qq.com"
] | dimar@qq.com |
df0b21e886aa22926f96a082dde0371ed52ce480 | 5f4e1dcd7abdc113a72c828e6483cf1c45a5a044 | /prog_pki.cpp | 67498735e68a5d5209b916ccf31418a801ab2bfb | [] | no_license | nagir80/PKI_Soft | 1f96b7717ee11d2f92bbb99d0d20dcdba793eb8d | 2dfa060fe85574afbd774ffae3bd7c15e6fcd01d | refs/heads/master | 2021-01-10T06:58:50.641978 | 2015-10-29T11:31:22 | 2015-10-29T11:31:22 | 45,173,590 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 849 | cpp | //---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include <tchar.h>
//---------------------------------------------------------------------------
USEFORM("ProgPKI\main_pp.cpp", Form1);
//---------------------------------------------------------------------------
int WINAPI _tWinMain(HINSTANCE, HINSTANCE, LPTSTR, int)
{
try
{
Application->Initialize();
Application->MainFormOnTaskBar = true;
Application->CreateForm(__classid(TForm1), &Form1);
Application->Run();
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
catch (...)
{
try
{
throw Exception("");
}
catch (Exception &exception)
{
Application->ShowException(&exception);
}
}
return 0;
}
//---------------------------------------------------------------------------
| [
"C:\\Users\\nagirnyak\\AppData\\Roaming\\The Bat!"
] | C:\Users\nagirnyak\AppData\Roaming\The Bat! |
8552b0ab9b831402e6c6b8ae3f13a3556a8380f3 | dec284a2b40248c7cc4f919f52f82183fd9b8391 | /Libraries/Headers/utils/FixedUnorderedMap.hpp | 8008e242d7199f134ebe5d3d7275cf5166e8a80e | [] | no_license | XavierCL/ChessV2 | 4b6044bf573e796783898d53037f42bb8986a01b | 5f53835c448aadaf04a2842560b45c2b79c4891e | refs/heads/master | 2021-09-29T01:06:27.227305 | 2018-11-22T04:18:48 | 2018-11-22T04:18:48 | 120,318,540 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,494 | hpp | #pragma once
#include "Option.hpp"
#include "FastMath.hpp"
#include <utility>
template <typename _KeyType, typename _ValueType, typename _KeyHashType>
class FixedUnorderedMap
{
public:
FixedUnorderedMap(const size_t& minCapacity)
: _capacity(FastMath::nextOrSamePrime(minCapacity)),
_size(0),
_container(new Option<std::pair<_KeyType, _ValueType>>[_capacity]) // warning about use of other members in member initialization
{}
FixedUnorderedMap(const FixedUnorderedMap<_KeyType, _ValueType, _KeyHashType> &other)
: _capacity(other._capacity),
_size(other._size),
_container(new Option<std::pair<_KeyType, _ValueType>>[other._capacity])
{
size_t currentSize = 0;
size_t currentIndex = 0;
while (currentSize < _size)
{
if (other._container[currentIndex].isDefined())
{
_container[currentIndex] = other._container[currentIndex];
++currentSize;
}
++currentIndex;
}
}
~FixedUnorderedMap()
{
delete[] _container;
}
const Option<_ValueType> get(const _KeyType& key) const
{
return _container[_hasher(key) % _capacity].flatMap<_ValueType>([&key](const std::pair<_KeyType, _ValueType>& element) {
if (element.first == key)
{
return Option<_ValueType>(element.second);
}
else
{
return Option<_ValueType>();
}
});
}
void set(const _KeyType& key, const _ValueType& value)
{
const size_t keyIndex = _hasher(key) % _capacity;
if (_container[keyIndex].isEmpty())
{
++_size;
}
_container[keyIndex] = Option<std::pair<_KeyType, _ValueType>>(std::make_pair(key, value));
}
void remove(const _KeyType& key)
{
const size_t keyIndex = _hasher(key) % _capacity;
return _container[keyIndex].foreach([&key, this, &keyIndex](const std::pair<_KeyType, _ValueType>& element) {
if (element.first == key)
{
_container[keyIndex] = Option<std::pair<_KeyType, _ValueType>>();
--_size;
}
});
}
const size_t size() const
{
return _size;
}
void clear()
{
for (size_t i = 0; i < _capacity; ++i)
{
_container[i] = Option<std::pair<_KeyType, _ValueType>>();
}
}
static const FixedUnorderedMap<_KeyType, _ValueType, _KeyHashType> empty;
private:
const size_t _capacity;
size_t _size;
const _KeyHashType _hasher;
Option<std::pair<_KeyType, _ValueType>>* const _container;
};
template <typename _KeyType, typename _ValueType, typename _KeyHashType>
const FixedUnorderedMap<_KeyType, _ValueType, _KeyHashType> FixedUnorderedMap<_KeyType, _ValueType, _KeyHashType>::empty(1); | [
"xavierx-men@hotmail.com"
] | xavierx-men@hotmail.com |
d36c1e9115a1820be4ab6abdaf315b5cabb69e92 | 7bb793c39d512bc3490608ec028c06677fdd7b05 | /hrserver/src/push_server/push_app.cpp | f5115c543fbb11c550bd627bea592d871f5f5dc9 | [] | no_license | rineishou/highwayns_rin | 11564fc667633720db50f31ff9baf7654ceaac3f | dfade9705a95a41f44a7c921c94bd3b9e7a1e360 | refs/heads/master | 2021-06-17T23:06:29.082403 | 2018-12-17T12:13:09 | 2018-12-17T12:13:09 | 88,716,361 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,273 | cpp | //
// push_app.cpp
// my_push_server
//
// Created by luoning on 14-11-4.
// Copyright (c) 2014年 luoning. All rights reserved.
//
#include "push_app.h"
#include "push_define.h"
#include "ConfigFileReader.h"
#include "session_manager.h"
#include <openssl/ssl.h>
#include <openssl/err.h>
#include "slog_api.h"
CSLog g_pushlog = CSLog(LOG_MODULE_PUSH);
CPushApp::CPushApp()
{
m_bInit = FALSE;
}
CPushApp::~CPushApp()
{}
CPushApp* CPushApp::GetInstance()
{
static CPushApp app;
return &app;
}
BOOL CPushApp::Init()
{
if (!m_bInit) {
/* SSL 库初始化 */
SSL_library_init();
/* 载入所有 SSL 算法 */
//OpenSSL_add_all_algorithms();
/* 载入所有 SSL 错误消息 */
SSL_load_error_strings();
m_bInit = TRUE;
PUSH_SERVER_DEBUG("push app init successed.");
}
else
{
PUSH_SERVER_WARN("warning: push app has inited.");
}
return TRUE;
}
BOOL CPushApp::UnInit()
{
Stop();
if (m_bInit)
{
m_bInit = FALSE;
PUSH_SERVER_DEBUG("push app uninit successed.");
}
else
{
PUSH_SERVER_WARN("warning: push app has uninited.");
}
return TRUE;
}
BOOL CPushApp::Start()
{
if (m_bInit)
{
string file_name = "pushserver.conf";
CConfigFileReader config_file(file_name.c_str());
char* listen_ip = config_file.GetConfigName("ListenIP");
char* str_listen_port = config_file.GetConfigName("ListenPort");
char* cert_path = config_file.GetConfigName("CertPath");
char* key_path = config_file.GetConfigName("KeyPath");
char* key_password = config_file.GetConfigName("KeyPassword");
char* sand_box = config_file.GetConfigName("SandBox");
if (!listen_ip || !str_listen_port || !cert_path || !key_path || !sand_box || !key_password)
{
PUSH_SERVER_ERROR("push app config file: %s not exist or miss required parameter obtained.", file_name.c_str());
return FALSE;
}
uint32_t nsand_box = atoi(sand_box);
if (nsand_box != 1 && nsand_box != 0)
{
PUSH_SERVER_ERROR("push app config parameter: sand_box has invaid value: %u.", nsand_box)
return FALSE;
}
apns_client_ptr pAPNSClient(new CAPNSClient(m_io));
pAPNSClient->SetCertPath(cert_path);
pAPNSClient->SetKeyPath(key_path);
pAPNSClient->SetKeyPassword(key_password);
pAPNSClient->SetSandBox((BOOL)atoi(sand_box));
CSessionManager::GetInstance()->SetAPNSClient(pAPNSClient);
push_server_ptr pPushServer(new CPushServer(m_io));
pPushServer->SetListenIP(listen_ip);
pPushServer->SetPort(atoi(str_listen_port));
CSessionManager::GetInstance()->SetPushServer(pPushServer);
m_io.Start();
CSessionManager::GetInstance()->StartCheckPushSession();
if (pAPNSClient)
{
if (pAPNSClient->Start() == FALSE)
{
return FALSE;
}
}
if (pPushServer)
{
if (pPushServer->Start() == FALSE)
{
return FALSE;
}
}
PUSH_SERVER_DEBUG("push app start successed.");
}
else
{
PUSH_SERVER_WARN("push app not init before.");
}
return TRUE;
}
BOOL CPushApp::Stop()
{
if (m_bInit)
{
m_io.Stop();
CSessionManager::GetInstance()->StopCheckPushSession();
apns_client_ptr pAPNSClient = CSessionManager::GetInstance()->GetAPNSClient();
if (pAPNSClient)
{
pAPNSClient->Stop();
}
push_server_ptr pPushServer = CSessionManager::GetInstance()->GetPushServer();
if (pPushServer)
{
pPushServer->Stop();
}
CSessionManager::GetInstance()->StopAllPushSession();
CSessionManager::GetInstance()->RemoveAPNSClient();
CSessionManager::GetInstance()->RemovePushServer();
CSessionManager::GetInstance()->ClearPushSession();
PUSH_SERVER_DEBUG("push app stop successed.");
}
else
{
PUSH_SERVER_WARN("push app not init before.");
}
return TRUE;
}
| [
"tei952@hotmail.com"
] | tei952@hotmail.com |
c63d11020b0e2be1f608c5354092d8436ec11b73 | dd80a584130ef1a0333429ba76c1cee0eb40df73 | /external/chromium_org/chrome_frame/protocol_sink_wrap.cc | b94e7c020fb39c38139a04abc01f73e066e2b091 | [
"MIT",
"BSD-3-Clause"
] | permissive | karunmatharu/Android-4.4-Pay-by-Data | 466f4e169ede13c5835424c78e8c30ce58f885c1 | fcb778e92d4aad525ef7a995660580f948d40bc9 | refs/heads/master | 2021-03-24T13:33:01.721868 | 2017-02-18T17:48:49 | 2017-02-18T17:48:49 | 81,847,777 | 0 | 2 | MIT | 2020-03-09T00:02:12 | 2017-02-13T16:47:00 | null | UTF-8 | C++ | false | false | 36,195 | cc | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <htiframe.h>
#include <mshtml.h>
#include <algorithm>
#include "chrome_frame/protocol_sink_wrap.h"
#include "base/logging.h"
#include "base/memory/singleton.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/win/scoped_bstr.h"
#include "chrome_frame/bho.h"
#include "chrome_frame/bind_context_info.h"
#include "chrome_frame/exception_barrier.h"
#include "chrome_frame/function_stub.h"
#include "chrome_frame/policy_settings.h"
#include "chrome_frame/utils.h"
using std::min;
// BINDSTATUS_SERVER_MIMETYPEAVAILABLE == 54. Introduced in IE 8, so
// not in everyone's headers yet. See:
// http://msdn.microsoft.com/en-us/library/ms775133(VS.85,loband).aspx
#ifndef BINDSTATUS_SERVER_MIMETYPEAVAILABLE
#define BINDSTATUS_SERVER_MIMETYPEAVAILABLE 54
#endif
bool ProtocolSinkWrap::ignore_xua_ = false;
static const char kTextHtmlMimeType[] = "text/html";
const wchar_t kUrlMonDllName[] = L"urlmon.dll";
static const int kInternetProtocolStartIndex = 3;
static const int kInternetProtocolReadIndex = 9;
static const int kInternetProtocolStartExIndex = 13;
static const int kInternetProtocolLockRequestIndex = 11;
static const int kInternetProtocolUnlockRequestIndex = 12;
static const int kInternetProtocolAbortIndex = 5;
static const int kInternetProtocolTerminateIndex = 6;
// IInternetProtocol/Ex patches.
STDMETHODIMP Hook_Start(InternetProtocol_Start_Fn orig_start,
IInternetProtocol* protocol,
LPCWSTR url,
IInternetProtocolSink* prot_sink,
IInternetBindInfo* bind_info,
DWORD flags,
HANDLE_PTR reserved);
STDMETHODIMP Hook_StartEx(InternetProtocol_StartEx_Fn orig_start_ex,
IInternetProtocolEx* protocol,
IUri* uri,
IInternetProtocolSink* prot_sink,
IInternetBindInfo* bind_info,
DWORD flags,
HANDLE_PTR reserved);
STDMETHODIMP Hook_Read(InternetProtocol_Read_Fn orig_read,
IInternetProtocol* protocol,
void* buffer,
ULONG size,
ULONG* size_read);
STDMETHODIMP Hook_LockRequest(InternetProtocol_LockRequest_Fn orig_req,
IInternetProtocol* protocol,
DWORD options);
STDMETHODIMP Hook_UnlockRequest(InternetProtocol_UnlockRequest_Fn orig_req,
IInternetProtocol* protocol);
STDMETHODIMP Hook_Abort(InternetProtocol_Abort_Fn orig_req,
IInternetProtocol* protocol,
HRESULT hr,
DWORD options);
STDMETHODIMP Hook_Terminate(InternetProtocol_Terminate_Fn orig_req,
IInternetProtocol* protocol,
DWORD options);
/////////////////////////////////////////////////////////////////////////////
BEGIN_VTABLE_PATCHES(CTransaction)
VTABLE_PATCH_ENTRY(kInternetProtocolStartIndex, Hook_Start)
VTABLE_PATCH_ENTRY(kInternetProtocolReadIndex, Hook_Read)
VTABLE_PATCH_ENTRY(kInternetProtocolLockRequestIndex, Hook_LockRequest)
VTABLE_PATCH_ENTRY(kInternetProtocolUnlockRequestIndex, Hook_UnlockRequest)
VTABLE_PATCH_ENTRY(kInternetProtocolAbortIndex, Hook_Abort)
VTABLE_PATCH_ENTRY(kInternetProtocolTerminateIndex, Hook_Terminate)
END_VTABLE_PATCHES()
BEGIN_VTABLE_PATCHES(CTransaction2)
VTABLE_PATCH_ENTRY(kInternetProtocolStartExIndex, Hook_StartEx)
END_VTABLE_PATCHES()
//
// ProtocolSinkWrap implementation
// Static map initialization
ProtData::ProtocolDataMap ProtData::datamap_;
base::Lock ProtData::datamap_lock_;
ProtocolSinkWrap::ProtocolSinkWrap() {
DVLOG(1) << __FUNCTION__ << base::StringPrintf(" 0x%08X", this);
}
ProtocolSinkWrap::~ProtocolSinkWrap() {
DVLOG(1) << __FUNCTION__ << base::StringPrintf(" 0x%08X", this);
}
base::win::ScopedComPtr<IInternetProtocolSink> ProtocolSinkWrap::CreateNewSink(
IInternetProtocolSink* sink, ProtData* data) {
DCHECK(sink != NULL);
DCHECK(data != NULL);
CComObject<ProtocolSinkWrap>* new_sink = NULL;
CComObject<ProtocolSinkWrap>::CreateInstance(&new_sink);
new_sink->delegate_ = sink;
new_sink->prot_data_ = data;
return base::win::ScopedComPtr<IInternetProtocolSink>(new_sink);
}
// IInternetProtocolSink methods
STDMETHODIMP ProtocolSinkWrap::Switch(PROTOCOLDATA* protocol_data) {
HRESULT hr = E_FAIL;
if (delegate_)
hr = delegate_->Switch(protocol_data);
return hr;
}
STDMETHODIMP ProtocolSinkWrap::ReportProgress(ULONG status_code,
LPCWSTR status_text) {
DVLOG(1) << "ProtocolSinkWrap::ReportProgress: "
<< BindStatus2Str(status_code)
<< " Status: " << (status_text ? status_text : L"");
HRESULT hr = prot_data_->ReportProgress(delegate_, status_code, status_text);
return hr;
}
STDMETHODIMP ProtocolSinkWrap::ReportData(DWORD flags, ULONG progress,
ULONG max_progress) {
DCHECK(delegate_);
DVLOG(1) << "ProtocolSinkWrap::ReportData: " << Bscf2Str(flags)
<< " progress: " << progress << " progress_max: " << max_progress;
HRESULT hr = prot_data_->ReportData(delegate_, flags, progress, max_progress);
return hr;
}
STDMETHODIMP ProtocolSinkWrap::ReportResult(HRESULT result, DWORD error,
LPCWSTR result_text) {
DVLOG(1) << "ProtocolSinkWrap::ReportResult: result: " << result
<< " error: " << error
<< " Text: " << (result_text ? result_text : L"");
ExceptionBarrier barrier;
HRESULT hr = prot_data_->ReportResult(delegate_, result, error, result_text);
return hr;
}
// Helpers
base::win::ScopedComPtr<IBindCtx> BindCtxFromIBindInfo(
IInternetBindInfo* bind_info) {
LPOLESTR bind_ctx_string = NULL;
ULONG count;
base::win::ScopedComPtr<IBindCtx> bind_ctx;
bind_info->GetBindString(BINDSTRING_PTR_BIND_CONTEXT, &bind_ctx_string, 1,
&count);
if (bind_ctx_string) {
int bind_ctx_int;
base::StringToInt(bind_ctx_string, &bind_ctx_int);
IBindCtx* pbc = reinterpret_cast<IBindCtx*>(bind_ctx_int);
bind_ctx.Attach(pbc);
CoTaskMemFree(bind_ctx_string);
}
return bind_ctx;
}
bool ShouldWrapSink(IInternetProtocolSink* sink, const wchar_t* url) {
// Ignore everything that does not start with http:// or https://.
// |url| is already normalized (i.e. no leading spaces, capital letters in
// protocol etc) and non-null (we check in Hook_Start).
DCHECK(url != NULL);
if (ProtocolSinkWrap::ignore_xua())
return false; // No need to intercept, we're ignoring X-UA-Compatible tags
if ((url != StrStrW(url, L"http://")) && (url != StrStrW(url, L"https://")))
return false;
base::win::ScopedComPtr<IHttpNegotiate> http_negotiate;
HRESULT hr = DoQueryService(GUID_NULL, sink, http_negotiate.Receive());
if (http_negotiate && !IsSubFrameRequest(http_negotiate))
return true;
return false;
}
// High level helpers
bool IsCFRequest(IBindCtx* pbc) {
base::win::ScopedComPtr<BindContextInfo> info;
BindContextInfo::FromBindContext(pbc, info.Receive());
if (info && info->chrome_request())
return true;
return false;
}
bool HasProtData(IBindCtx* pbc) {
base::win::ScopedComPtr<BindContextInfo> info;
BindContextInfo::FromBindContext(pbc, info.Receive());
bool result = false;
if (info)
result = info->has_prot_data();
return result;
}
void PutProtData(IBindCtx* pbc, ProtData* data) {
// AddRef and Release to avoid a potential leak of a ProtData instance if
// FromBindContext fails.
data->AddRef();
base::win::ScopedComPtr<BindContextInfo> info;
BindContextInfo::FromBindContext(pbc, info.Receive());
if (info)
info->set_prot_data(data);
data->Release();
}
bool IsTextHtml(const wchar_t* status_text) {
const std::wstring str = status_text;
bool is_text_html = LowerCaseEqualsASCII(str, kTextHtmlMimeType);
return is_text_html;
}
bool IsAdditionallySupportedContentType(const wchar_t* status_text) {
static const char* kHeaderContentTypes[] = {
"application/xhtml+xml",
"application/xml",
"image/svg",
"image/svg+xml",
"text/xml",
"video/ogg",
"video/webm",
"video/mp4"
};
const std::wstring str = status_text;
for (int i = 0; i < arraysize(kHeaderContentTypes); ++i) {
if (LowerCaseEqualsASCII(str, kHeaderContentTypes[i]))
return true;
}
if (PolicySettings::GetInstance()->GetRendererForContentType(
status_text) == PolicySettings::RENDER_IN_CHROME_FRAME) {
return true;
}
return false;
}
// Returns:
// RENDERER_TYPE_OTHER: if suggested mime type is not text/html.
// RENDERER_TYPE_UNDETERMINED: if suggested mime type is text/html.
// RENDERER_TYPE_CHROME_RESPONSE_HEADER: X-UA-Compatible tag is in HTTP headers.
// RENDERER_TYPE_CHROME_DEFAULT_RENDERER: GCF is the default renderer and the
// Url is not listed in the
// RenderInHostUrls registry key.
// RENDERER_TYPE_CHROME_OPT_IN_URL: GCF is not the default renderer and the Url
// is listed in the RenderInGcfUrls registry
// key.
RendererType DetermineRendererTypeFromMetaData(
const wchar_t* suggested_mime_type,
const std::wstring& url,
IWinInetHttpInfo* info) {
bool is_text_html = IsTextHtml(suggested_mime_type);
bool is_supported_content_type = is_text_html ||
IsAdditionallySupportedContentType(suggested_mime_type);
if (!is_supported_content_type)
return RENDERER_TYPE_OTHER;
if (!url.empty()) {
RendererType renderer_type = RendererTypeForUrl(url);
if (IsChrome(renderer_type)) {
return renderer_type;
}
}
if (info) {
char buffer[512] = "x-ua-compatible";
DWORD len = sizeof(buffer);
DWORD flags = 0;
HRESULT hr = info->QueryInfo(HTTP_QUERY_CUSTOM, buffer, &len, &flags, NULL);
if (hr == S_OK && len > 0) {
if (CheckXUaCompatibleDirective(buffer, GetIEMajorVersion())) {
return RENDERER_TYPE_CHROME_RESPONSE_HEADER;
}
}
}
// We can (and want) to sniff the content.
if (is_text_html) {
return RENDERER_TYPE_UNDETERMINED;
}
// We cannot sniff the content.
return RENDERER_TYPE_OTHER;
}
RendererType DetermineRendererType(void* buffer, DWORD size, bool last_chance) {
RendererType renderer_type = RENDERER_TYPE_UNDETERMINED;
if (last_chance)
renderer_type = RENDERER_TYPE_OTHER;
std::wstring html_contents;
// TODO(joshia): detect and handle different content encodings
UTF8ToWide(reinterpret_cast<char*>(buffer), size, &html_contents);
// Note that document_contents_ may have NULL characters in it. While
// browsers may handle this properly, we don't and will stop scanning
// for the XUACompat content value if we encounter one.
std::wstring xua_compat_content;
if (SUCCEEDED(UtilGetXUACompatContentValue(html_contents,
&xua_compat_content))) {
if (CheckXUaCompatibleDirective(WideToASCII(xua_compat_content),
GetIEMajorVersion())) {
renderer_type = RENDERER_TYPE_CHROME_HTTP_EQUIV;
}
}
return renderer_type;
}
// ProtData
ProtData::ProtData(IInternetProtocol* protocol,
InternetProtocol_Read_Fn read_fun, const wchar_t* url)
: has_suggested_mime_type_(false), has_server_mime_type_(false),
buffer_size_(0), buffer_pos_(0),
renderer_type_(RENDERER_TYPE_UNDETERMINED), protocol_(protocol),
read_fun_(read_fun), url_(url) {
memset(buffer_, 0, arraysize(buffer_));
DVLOG(1) << __FUNCTION__ << " " << this;
// Add to map.
base::AutoLock lock(datamap_lock_);
DCHECK(datamap_.end() == datamap_.find(protocol_));
datamap_[protocol] = this;
}
ProtData::~ProtData() {
DVLOG(1) << __FUNCTION__ << " " << this;
Invalidate();
}
HRESULT ProtData::Read(void* buffer, ULONG size, ULONG* size_read) {
if (renderer_type_ == RENDERER_TYPE_UNDETERMINED) {
return E_PENDING;
}
const ULONG bytes_available = buffer_size_ - buffer_pos_;
const ULONG bytes_to_copy = std::min(bytes_available, size);
if (bytes_to_copy) {
// Copy from the local buffer.
memcpy(buffer, buffer_ + buffer_pos_, bytes_to_copy);
*size_read = bytes_to_copy;
buffer_pos_ += bytes_to_copy;
HRESULT hr = S_OK;
ULONG new_data = 0;
if (size > bytes_available) {
// User buffer is greater than what we have.
buffer = reinterpret_cast<uint8*>(buffer) + bytes_to_copy;
size -= bytes_to_copy;
hr = read_fun_(protocol_, buffer, size, &new_data);
}
if (size_read)
*size_read = bytes_to_copy + new_data;
return hr;
}
return read_fun_(protocol_, buffer, size, size_read);
}
// Attempt to detect ChromeFrame from HTTP headers when
// BINDSTATUS_MIMETYPEAVAILABLE is received.
// There are three possible outcomes: CHROME_*/OTHER/UNDETERMINED.
// If RENDERER_TYPE_UNDETERMINED we are going to sniff the content later in
// ReportData().
//
// With not-so-well-written software (mime filters/protocols/protocol patchers)
// BINDSTATUS_MIMETYPEAVAILABLE might be fired multiple times with different
// values for the same client.
// If the renderer_type_ member is:
// RENDERER_TYPE_CHROME_* - 2nd (and any subsequent)
// BINDSTATUS_MIMETYPEAVAILABLE is ignored.
// RENDERER_TYPE_OTHER - 2nd (and any subsequent) BINDSTATUS_MIMETYPEAVAILABLE
// is passed through.
// RENDERER_TYPE_UNDETERMINED - Try to detect ChromeFrame from HTTP headers
// (acts as if this is the first time
// BINDSTATUS_MIMETYPEAVAILABLE is received).
HRESULT ProtData::ReportProgress(IInternetProtocolSink* delegate,
ULONG status_code, LPCWSTR status_text) {
switch (status_code) {
case BINDSTATUS_DIRECTBIND:
renderer_type_ = RENDERER_TYPE_OTHER;
break;
case BINDSTATUS_REDIRECTING:
url_.clear();
if (status_text)
url_ = status_text;
break;
case BINDSTATUS_SERVER_MIMETYPEAVAILABLE:
has_server_mime_type_ = true;
SaveSuggestedMimeType(status_text);
return S_OK;
// TODO(stoyan): BINDSTATUS_RAWMIMETYPE
case BINDSTATUS_MIMETYPEAVAILABLE:
case BINDSTATUS_VERIFIEDMIMETYPEAVAILABLE:
SaveSuggestedMimeType(status_text);
// When Transaction is attached i.e. when existing BTS it terminated
// and "converted" to BTO, events will be re-fired for the new sink,
// but we may skip the renderer_type_ determination since it's already
// done.
if (renderer_type_ == RENDERER_TYPE_UNDETERMINED) {
// This may seem awkward. CBinding's implementation of IWinInetHttpInfo
// will forward to CTransaction that will forward to the real protocol.
// We may ask CTransaction (our protocol_ member) for IWinInetHttpInfo.
base::win::ScopedComPtr<IWinInetHttpInfo> info;
info.QueryFrom(delegate);
renderer_type_ = DetermineRendererTypeFromMetaData(suggested_mime_type_,
url_, info);
}
if (IsChrome(renderer_type_)) {
// Suggested mime type is "text/html" and we have DEFAULT_RENDERER,
// OPT_IN_URL, or RESPONSE_HEADER.
DVLOG(1) << "Forwarding BINDSTATUS_MIMETYPEAVAILABLE "
<< kChromeMimeType;
SaveReferrer(delegate);
delegate->ReportProgress(BINDSTATUS_MIMETYPEAVAILABLE, kChromeMimeType);
} else if (renderer_type_ == RENDERER_TYPE_OTHER) {
// Suggested mime type is not "text/html" - we are not interested in
// this request anymore.
FireSuggestedMimeType(delegate);
} else {
// Suggested mime type is "text/html"; We will try to sniff the
// HTML content in ReportData.
DCHECK_EQ(RENDERER_TYPE_UNDETERMINED, renderer_type_);
}
return S_OK;
}
// We are just pass through at this point, avoid false positive crash reports.
ExceptionBarrierReportOnlyModule barrier;
return delegate->ReportProgress(status_code, status_text);
}
HRESULT ProtData::ReportData(IInternetProtocolSink* delegate,
DWORD flags, ULONG progress, ULONG max_progress) {
if (renderer_type_ != RENDERER_TYPE_UNDETERMINED) {
// We are just pass through now, avoid false positive crash reports.
ExceptionBarrierReportOnlyModule barrier;
return delegate->ReportData(flags, progress, max_progress);
}
HRESULT hr = FillBuffer();
bool last_chance = false;
if (hr == S_OK || hr == S_FALSE) {
last_chance = true;
}
renderer_type_ = SkipMetadataCheck() ? RENDERER_TYPE_OTHER
: DetermineRendererType(buffer_, buffer_size_, last_chance);
if (renderer_type_ == RENDERER_TYPE_UNDETERMINED) {
// do not report anything, we need more data.
return S_OK;
}
if (IsChrome(renderer_type_)) {
DVLOG(1) << "Forwarding BINDSTATUS_MIMETYPEAVAILABLE " << kChromeMimeType;
SaveReferrer(delegate);
delegate->ReportProgress(BINDSTATUS_MIMETYPEAVAILABLE, kChromeMimeType);
}
if (renderer_type_ == RENDERER_TYPE_OTHER) {
FireSuggestedMimeType(delegate);
}
// This is the first data notification we forward, since up to now we hold
// the content received.
flags |= BSCF_FIRSTDATANOTIFICATION;
if (hr == S_FALSE) {
flags |= (BSCF_LASTDATANOTIFICATION | BSCF_DATAFULLYAVAILABLE);
}
return delegate->ReportData(flags, progress, max_progress);
}
HRESULT ProtData::ReportResult(IInternetProtocolSink* delegate, HRESULT result,
DWORD error, LPCWSTR result_text) {
// We may receive ReportResult without ReportData, if the connection fails
// for example.
if (renderer_type_ == RENDERER_TYPE_UNDETERMINED) {
DVLOG(1) << "ReportResult received but renderer type is yet unknown.";
renderer_type_ = RENDERER_TYPE_OTHER;
FireSuggestedMimeType(delegate);
}
HRESULT hr = S_OK;
if (delegate)
hr = delegate->ReportResult(result, error, result_text);
return hr;
}
void ProtData::UpdateUrl(const wchar_t* url) {
url_ = url;
}
// S_FALSE - EOF
// S_OK - buffer fully filled
// E_PENDING - some data added to buffer, but buffer is not yet full
// E_XXXX - some other error.
HRESULT ProtData::FillBuffer() {
HRESULT hr_read = S_OK;
while ((hr_read == S_OK) && (buffer_size_ < kMaxContentSniffLength)) {
ULONG size_read = 0;
hr_read = read_fun_(protocol_, buffer_ + buffer_size_,
kMaxContentSniffLength - buffer_size_, &size_read);
buffer_size_ += size_read;
}
return hr_read;
}
void ProtData::SaveSuggestedMimeType(LPCWSTR status_text) {
has_suggested_mime_type_ = true;
suggested_mime_type_.Allocate(status_text);
}
void ProtData::FireSuggestedMimeType(IInternetProtocolSink* delegate) {
if (has_server_mime_type_) {
DVLOG(1) << "Forwarding BINDSTATUS_SERVER_MIMETYPEAVAILABLE "
<< suggested_mime_type_;
delegate->ReportProgress(BINDSTATUS_SERVER_MIMETYPEAVAILABLE,
suggested_mime_type_);
}
if (has_suggested_mime_type_) {
DVLOG(1) << "Forwarding BINDSTATUS_MIMETYPEAVAILABLE "
<< suggested_mime_type_;
delegate->ReportProgress(BINDSTATUS_MIMETYPEAVAILABLE,
suggested_mime_type_);
}
}
void ProtData::SaveReferrer(IInternetProtocolSink* delegate) {
DCHECK(IsChrome(renderer_type_));
base::win::ScopedComPtr<IWinInetHttpInfo> info;
info.QueryFrom(delegate);
if (info) {
char buffer[4096] = {0};
DWORD len = sizeof(buffer);
DWORD flags = 0;
HRESULT hr = info->QueryInfo(
HTTP_QUERY_REFERER | HTTP_QUERY_FLAG_REQUEST_HEADERS,
buffer, &len, &flags, 0);
if (hr == S_OK && len > 0)
referrer_.assign(buffer);
} else {
DLOG(WARNING) << "Failed to QI for IWinInetHttpInfo";
}
}
scoped_refptr<ProtData> ProtData::DataFromProtocol(
IInternetProtocol* protocol) {
scoped_refptr<ProtData> instance;
base::AutoLock lock(datamap_lock_);
ProtocolDataMap::iterator it = datamap_.find(protocol);
if (datamap_.end() != it)
instance = it->second;
return instance;
}
void ProtData::Invalidate() {
if (protocol_) {
// Remove from map.
base::AutoLock lock(datamap_lock_);
DCHECK(datamap_.end() != datamap_.find(protocol_));
datamap_.erase(protocol_);
protocol_ = NULL;
}
}
// This function looks for the url pattern indicating that this request needs
// to be forced into chrome frame.
// This hack is required because window.open requests from Chrome don't have
// the URL up front. The URL comes in much later when the renderer initiates a
// top level navigation for the url passed into window.open.
// The new page must be rendered in ChromeFrame to preserve the opener
// relationship with its parent even if the new page does not have the chrome
// meta tag.
bool HandleAttachToExistingExternalTab(LPCWSTR url,
IInternetProtocol* protocol,
IInternetProtocolSink* prot_sink,
IBindCtx* bind_ctx) {
ChromeFrameUrl cf_url;
if (cf_url.Parse(url) && cf_url.attach_to_external_tab()) {
scoped_refptr<ProtData> prot_data = ProtData::DataFromProtocol(protocol);
if (!prot_data) {
// Pass NULL as the read function which indicates that always return EOF
// without calling the underlying protocol.
prot_data = new ProtData(protocol, NULL, url);
PutProtData(bind_ctx, prot_data);
}
prot_sink->ReportProgress(BINDSTATUS_MIMETYPEAVAILABLE, kChromeMimeType);
int data_flags = BSCF_FIRSTDATANOTIFICATION | BSCF_LASTDATANOTIFICATION;
prot_sink->ReportData(data_flags, 0, 0);
prot_sink->ReportResult(S_OK, 0, NULL);
return true;
}
return false;
}
HRESULT ForwardHookStart(InternetProtocol_Start_Fn orig_start,
IInternetProtocol* protocol, LPCWSTR url, IInternetProtocolSink* prot_sink,
IInternetBindInfo* bind_info, DWORD flags, HANDLE_PTR reserved) {
ExceptionBarrierReportOnlyModule barrier;
return orig_start(protocol, url, prot_sink, bind_info, flags, reserved);
}
HRESULT ForwardWrappedHookStart(InternetProtocol_Start_Fn orig_start,
IInternetProtocol* protocol, LPCWSTR url, IInternetProtocolSink* prot_sink,
IInternetBindInfo* bind_info, DWORD flags, HANDLE_PTR reserved) {
ExceptionBarrier barrier;
return orig_start(protocol, url, prot_sink, bind_info, flags, reserved);
}
// IInternetProtocol/Ex hooks.
STDMETHODIMP Hook_Start(InternetProtocol_Start_Fn orig_start,
IInternetProtocol* protocol, LPCWSTR url, IInternetProtocolSink* prot_sink,
IInternetBindInfo* bind_info, DWORD flags, HANDLE_PTR reserved) {
DCHECK(orig_start);
if (!url || !prot_sink || !bind_info)
return E_INVALIDARG;
DVLOG_IF(1, url != NULL) << "OnStart: " << url << PiFlags2Str(flags);
base::win::ScopedComPtr<IBindCtx> bind_ctx = BindCtxFromIBindInfo(bind_info);
if (!bind_ctx) {
// MSHTML sometimes takes a short path, skips the creation of
// moniker and binding, by directly grabbing protocol from InternetSession
DVLOG(1) << "DirectBind for " << url;
return ForwardHookStart(orig_start, protocol, url, prot_sink, bind_info,
flags, reserved);
}
scoped_refptr<ProtData> prot_data = ProtData::DataFromProtocol(protocol);
if (prot_data && !HasProtData(bind_ctx)) {
prot_data->Invalidate();
prot_data = NULL;
}
if (HandleAttachToExistingExternalTab(url, protocol, prot_sink, bind_ctx)) {
return S_OK;
}
if (IsCFRequest(bind_ctx)) {
base::win::ScopedComPtr<BindContextInfo> info;
BindContextInfo::FromBindContext(bind_ctx, info.Receive());
DCHECK(info);
if (info) {
info->set_protocol(protocol);
}
return ForwardHookStart(orig_start, protocol, url, prot_sink, bind_info,
flags, reserved);
}
if (prot_data) {
DVLOG(1) << "Found existing ProtData!";
prot_data->UpdateUrl(url);
base::win::ScopedComPtr<IInternetProtocolSink> new_sink =
ProtocolSinkWrap::CreateNewSink(prot_sink, prot_data);
return ForwardWrappedHookStart(orig_start, protocol, url, new_sink,
bind_info, flags, reserved);
}
if (!ShouldWrapSink(prot_sink, url)) {
return ForwardHookStart(orig_start, protocol, url, prot_sink, bind_info,
flags, reserved);
}
// Fresh request.
InternetProtocol_Read_Fn read_fun = reinterpret_cast<InternetProtocol_Read_Fn>
(CTransaction_PatchInfo[1].stub_->argument());
prot_data = new ProtData(protocol, read_fun, url);
PutProtData(bind_ctx, prot_data);
base::win::ScopedComPtr<IInternetProtocolSink> new_sink =
ProtocolSinkWrap::CreateNewSink(prot_sink, prot_data);
return ForwardWrappedHookStart(orig_start, protocol, url, new_sink, bind_info,
flags, reserved);
}
HRESULT ForwardHookStartEx(InternetProtocol_StartEx_Fn orig_start_ex,
IInternetProtocolEx* protocol, IUri* uri, IInternetProtocolSink* prot_sink,
IInternetBindInfo* bind_info, DWORD flags, HANDLE_PTR reserved) {
ExceptionBarrierReportOnlyModule barrier;
return orig_start_ex(protocol, uri, prot_sink, bind_info, flags, reserved);
}
HRESULT ForwardWrappedHookStartEx(InternetProtocol_StartEx_Fn orig_start_ex,
IInternetProtocolEx* protocol, IUri* uri, IInternetProtocolSink* prot_sink,
IInternetBindInfo* bind_info, DWORD flags, HANDLE_PTR reserved) {
ExceptionBarrier barrier;
return orig_start_ex(protocol, uri, prot_sink, bind_info, flags, reserved);
}
STDMETHODIMP Hook_StartEx(InternetProtocol_StartEx_Fn orig_start_ex,
IInternetProtocolEx* protocol, IUri* uri, IInternetProtocolSink* prot_sink,
IInternetBindInfo* bind_info, DWORD flags, HANDLE_PTR reserved) {
DCHECK(orig_start_ex);
if (!uri || !prot_sink || !bind_info)
return E_INVALIDARG;
base::win::ScopedBstr url;
uri->GetPropertyBSTR(Uri_PROPERTY_ABSOLUTE_URI, url.Receive(), 0);
DVLOG_IF(1, url != NULL) << "OnStartEx: " << url << PiFlags2Str(flags);
base::win::ScopedComPtr<IBindCtx> bind_ctx = BindCtxFromIBindInfo(bind_info);
if (!bind_ctx) {
// MSHTML sometimes takes a short path, skips the creation of
// moniker and binding, by directly grabbing protocol from InternetSession.
DVLOG(1) << "DirectBind for " << url;
return ForwardHookStartEx(orig_start_ex, protocol, uri, prot_sink,
bind_info, flags, reserved);
}
scoped_refptr<ProtData> prot_data = ProtData::DataFromProtocol(protocol);
if (prot_data && !HasProtData(bind_ctx)) {
prot_data->Invalidate();
prot_data = NULL;
}
if (HandleAttachToExistingExternalTab(url, protocol, prot_sink, bind_ctx)) {
return S_OK;
}
if (IsCFRequest(bind_ctx)) {
base::win::ScopedComPtr<BindContextInfo> info;
BindContextInfo::FromBindContext(bind_ctx, info.Receive());
DCHECK(info);
if (info) {
info->set_protocol(protocol);
}
return ForwardHookStartEx(orig_start_ex, protocol, uri, prot_sink,
bind_info, flags, reserved);
}
if (prot_data) {
DVLOG(1) << "Found existing ProtData!";
prot_data->UpdateUrl(url);
base::win::ScopedComPtr<IInternetProtocolSink> new_sink =
ProtocolSinkWrap::CreateNewSink(prot_sink, prot_data);
return ForwardWrappedHookStartEx(orig_start_ex, protocol, uri, new_sink,
bind_info, flags, reserved);
}
if (!ShouldWrapSink(prot_sink, url)) {
return ForwardHookStartEx(orig_start_ex, protocol, uri, prot_sink,
bind_info, flags, reserved);
}
// Fresh request.
InternetProtocol_Read_Fn read_fun = reinterpret_cast<InternetProtocol_Read_Fn>
(CTransaction_PatchInfo[1].stub_->argument());
prot_data = new ProtData(protocol, read_fun, url);
PutProtData(bind_ctx, prot_data);
base::win::ScopedComPtr<IInternetProtocolSink> new_sink =
ProtocolSinkWrap::CreateNewSink(prot_sink, prot_data);
return ForwardWrappedHookStartEx(orig_start_ex, protocol, uri, new_sink,
bind_info, flags, reserved);
}
STDMETHODIMP Hook_Read(InternetProtocol_Read_Fn orig_read,
IInternetProtocol* protocol, void* buffer, ULONG size, ULONG* size_read) {
DCHECK(orig_read);
HRESULT hr = E_FAIL;
scoped_refptr<ProtData> prot_data = ProtData::DataFromProtocol(protocol);
if (!prot_data) {
// We are not wrapping this request, avoid false positive crash reports.
ExceptionBarrierReportOnlyModule barrier;
hr = orig_read(protocol, buffer, size, size_read);
return hr;
}
if (prot_data->is_attach_external_tab_request()) {
// return EOF always.
if (size_read)
*size_read = 0;
return S_FALSE;
}
hr = prot_data->Read(buffer, size, size_read);
return hr;
}
STDMETHODIMP Hook_LockRequest(InternetProtocol_LockRequest_Fn orig_req,
IInternetProtocol* protocol,
DWORD options) {
DCHECK(orig_req);
scoped_refptr<ProtData> prot_data = ProtData::DataFromProtocol(protocol);
if (prot_data && prot_data->is_attach_external_tab_request()) {
prot_data->AddRef();
return S_OK;
}
// We are just pass through at this point, avoid false positive crash
// reports.
ExceptionBarrierReportOnlyModule barrier;
return orig_req(protocol, options);
}
STDMETHODIMP Hook_UnlockRequest(InternetProtocol_UnlockRequest_Fn orig_req,
IInternetProtocol* protocol) {
DCHECK(orig_req);
scoped_refptr<ProtData> prot_data = ProtData::DataFromProtocol(protocol);
if (prot_data && prot_data->is_attach_external_tab_request()) {
prot_data->Release();
return S_OK;
}
// We are just pass through at this point, avoid false positive crash
// reports.
ExceptionBarrierReportOnlyModule barrier;
return orig_req(protocol);
}
STDMETHODIMP Hook_Abort(InternetProtocol_Abort_Fn orig_req,
IInternetProtocol* protocol,
HRESULT hr,
DWORD options) {
scoped_refptr<ProtData> prot_data = ProtData::DataFromProtocol(protocol);
if (prot_data)
prot_data->Invalidate();
// We are just pass through at this point, avoid false positive crash
// reports.
ExceptionBarrierReportOnlyModule barrier;
return orig_req(protocol, hr, options);
}
STDMETHODIMP Hook_Terminate(InternetProtocol_Terminate_Fn orig_req,
IInternetProtocol* protocol,
DWORD options) {
scoped_refptr<ProtData> prot_data = ProtData::DataFromProtocol(protocol);
// We should not be invalidating the cached protocol data in the following
// cases:-
// 1. Pages which are switching into ChromeFrame.
// When IE switches into ChromeFrame, we report the Chrome mime type as
// the handler for the page. This results in urlmon terminating the
// protocol. When Chrome attempts to read the data we need to report the
// cached data back to Chrome.
// 2. For the attach external tab requests which are temporary navigations
// to ensure that a top level URL is opened in IE from ChromeFrame.
// We rely on the mapping to identify these requests as attach tab
// requests. This mapping is referred to in the
// IInternetProtocol::LockRequest/IInternetProtocol::UnlockRequest
// intercepts. Invalidating the mapping after LockRequest is called and
// before UnlockRequest causes IE to crash.
if (prot_data && !IsChrome(prot_data->renderer_type()) &&
!prot_data->is_attach_external_tab_request())
prot_data->Invalidate();
// We are just pass through at this point, avoid false positive crash
// reports.
ExceptionBarrierReportOnlyModule barrier;
return orig_req(protocol, options);
}
// Patching / Hooking code.
class FakeProtocol : public CComObjectRootEx<CComSingleThreadModel>,
public IInternetProtocol {
public:
BEGIN_COM_MAP(FakeProtocol)
COM_INTERFACE_ENTRY(IInternetProtocol)
COM_INTERFACE_ENTRY(IInternetProtocolRoot)
END_COM_MAP()
STDMETHOD(Start)(LPCWSTR url, IInternetProtocolSink *protocol_sink,
IInternetBindInfo* bind_info, DWORD flags, HANDLE_PTR reserved) {
transaction_.QueryFrom(protocol_sink);
// Return some unusual error code.
return INET_E_INVALID_CERTIFICATE;
}
STDMETHOD(Continue)(PROTOCOLDATA* protocol_data) { return S_OK; }
STDMETHOD(Abort)(HRESULT reason, DWORD options) { return S_OK; }
STDMETHOD(Terminate)(DWORD options) { return S_OK; }
STDMETHOD(Suspend)() { return S_OK; }
STDMETHOD(Resume)() { return S_OK; }
STDMETHOD(Read)(void *buffer, ULONG size, ULONG* size_read) { return S_OK; }
STDMETHOD(Seek)(LARGE_INTEGER move, DWORD origin, ULARGE_INTEGER* new_pos)
{ return S_OK; }
STDMETHOD(LockRequest)(DWORD options) { return S_OK; }
STDMETHOD(UnlockRequest)() { return S_OK; }
base::win::ScopedComPtr<IInternetProtocol> transaction_;
};
struct FakeFactory : public IClassFactory,
public CComObjectRootEx<CComSingleThreadModel> {
BEGIN_COM_MAP(FakeFactory)
COM_INTERFACE_ENTRY(IClassFactory)
END_COM_MAP()
STDMETHOD(CreateInstance)(IUnknown *pUnkOuter, REFIID riid, void **ppvObj) {
if (pUnkOuter)
return CLASS_E_NOAGGREGATION;
HRESULT hr = obj_->QueryInterface(riid, ppvObj);
return hr;
}
STDMETHOD(LockServer)(BOOL fLock) {
return S_OK;
}
IUnknown* obj_;
};
static void HookTransactionVtable(IInternetProtocol* p) {
base::win::ScopedComPtr<IInternetProtocolEx> ex;
ex.QueryFrom(p);
HRESULT hr = vtable_patch::PatchInterfaceMethods(p, CTransaction_PatchInfo);
if (hr == S_OK && ex) {
vtable_patch::PatchInterfaceMethods(ex.get(), CTransaction2_PatchInfo);
}
}
void TransactionHooks::InstallHooks() {
if (IS_PATCHED(CTransaction)) {
DLOG(WARNING) << __FUNCTION__ << " called more than once.";
return;
}
CComObjectStackEx<FakeProtocol> prot;
CComObjectStackEx<FakeFactory> factory;
factory.obj_ = &prot;
base::win::ScopedComPtr<IInternetSession> session;
HRESULT hr = ::CoInternetGetSession(0, session.Receive(), 0);
hr = session->RegisterNameSpace(&factory, CLSID_NULL, L"611", 0, 0, 0);
DLOG_IF(FATAL, FAILED(hr)) << "Failed to register namespace";
if (hr != S_OK)
return;
do {
base::win::ScopedComPtr<IMoniker> mk;
base::win::ScopedComPtr<IBindCtx> bc;
base::win::ScopedComPtr<IStream> stream;
hr = ::CreateAsyncBindCtxEx(0, 0, 0, 0, bc.Receive(), 0);
DLOG_IF(FATAL, FAILED(hr)) << "CreateAsyncBindCtxEx failed " << hr;
if (hr != S_OK)
break;
hr = ::CreateURLMoniker(NULL, L"611://512", mk.Receive());
DLOG_IF(FATAL, FAILED(hr)) << "CreateURLMoniker failed " << hr;
if (hr != S_OK)
break;
hr = mk->BindToStorage(bc, NULL, IID_IStream,
reinterpret_cast<void**>(stream.Receive()));
DLOG_IF(FATAL, hr != INET_E_INVALID_CERTIFICATE) <<
"BindToStorage failed " << hr;
} while (0);
hr = session->UnregisterNameSpace(&factory, L"611");
if (prot.transaction_) {
HookTransactionVtable(prot.transaction_);
// Explicit release, otherwise ~CComObjectStackEx will complain about
// outstanding reference to us, because it runs before ~FakeProtocol
prot.transaction_.Release();
}
}
void TransactionHooks::RevertHooks() {
vtable_patch::UnpatchInterfaceMethods(CTransaction_PatchInfo);
vtable_patch::UnpatchInterfaceMethods(CTransaction2_PatchInfo);
}
| [
"karun.matharu@gmail.com"
] | karun.matharu@gmail.com |
2247810dc5ddc1dc3aecd4e70240bbc72ccc7dd3 | 0347419bdc28fea923ab1a362ade269f7c60f2fd | /RandomQuestion/A_Linova_and_Kingdom.cpp | 454cecdf19957023069e9e6627fe0dbf1be88845 | [] | no_license | amit-haritwal/competitive | 198d0ac857eaba7b73ca6100ed1d5f85e0b23115 | 640d65b4abf96cfe00c03b06c2715fbf620e5391 | refs/heads/main | 2023-07-16T09:01:53.023933 | 2021-08-23T05:50:43 | 2021-08-23T05:50:43 | 323,053,897 | 0 | 1 | null | 2021-08-23T05:50:44 | 2020-12-20T11:16:52 | C++ | UTF-8 | C++ | false | false | 2,393 | cpp | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <queue>
#include <deque>
#include <bitset>
#include <iterator>
#include <list>
#include <stack>
#include <map>
#include <set>
#include <functional>
#include <numeric>
#include <utility>
#include <limits>
#include <time.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
using namespace std;
#define rep(i, a, b) for (ll i = a; i < b; i++)
#define res(i, a, b) for (ll i = a; i >= b; i--)
#define all(n) n.begin(), n.end()
#define mod 1000000007
typedef long long ll;
const long long INF = 1e18 + 42;
// vector<ll> primes(10005, 1);
template <typename T>
void pop_front(std::vector<T> &vec)
{
assert(!vec.empty());
vec.erase(vec.begin());
}
bool compPairF(pair<ll, ll> v1, pair<ll, ll> v2)
{
return v1.first < v2.first;
}
bool compPairS(pair<ll, ll> v1, pair<ll, ll> v2)
{
return v1.second < v2.second;
}
//void sieveWithCount(ll n)
//{
// vector<bool> v1(n, 1);
// for (ll i = 2; i * i < n; i++)
// {
// if (primes[i] != 0)
// {
// for (ll j = i * i; j < n; j = j + i)
// {
// primes[j] = 0;
// }
// }
// }
//}
ll gcd(ll a, ll b)
{
if (b == 0)
{
return a;
}
else
{
return gcd(b, a % b);
}
}
ll power(ll x, ll y)
{
ll temp;
if (y == 0)
return 1;
temp = power(x, y / 2);
if (y % 2 == 0)
return temp * temp;
else
return x * temp * temp;
}
vector<int> v1[200005];
int height[200005], nochilds[200005];
void findans(ll current, ll parent)
{
nochilds[current] = 1;
rep(i, 0, v1[current].size())
{
if (v1[current][i] == parent)
continue;
height[v1[current][i]] = height[current] + 1;
findans(v1[current][i], current);
nochilds[current] += nochilds[v1[current][i]];
}
}
void sol()
{
int n, k;
cin >> n >> k;
for (int i = 1; i < n; i++)
{
int a, b;
cin >> a >> b;
v1[a - 1].push_back(b - 1);
v1[b - 1].push_back(a - 1);
}
vector<ll> ans(n);
findans(0, -1);
rep(i, 0, n)
{
ans[i] = nochilds[i] - height[i] - 1;
}
sort(ans.begin(), ans.end());
reverse(ans.begin(), ans.end());
ll sum = 0;
rep(i, 0, n - k)
{
sum += ans[i];
}
cout << sum << endl;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int a = 1;
// cin >> a;
while (a--)
{
sol();
}
} | [
"65955451+competitivewithamit@users.noreply.github.com"
] | 65955451+competitivewithamit@users.noreply.github.com |
cd990ae741802025e2f7be7a066e8ce33ee805ec | 05efcf0b6b41768ff82bc03495f107361d64c87a | /practica2/2.7.cpp | a19948264f82706ae6cd48cbd50f43c00b4533aa | [] | no_license | Olesya11/practica-mera | 390d032a24d6315ee9ce2f83cdc4bc562c6cf9c5 | 948a8741a72cdfc221a91d44630274e75d331944 | refs/heads/master | 2020-07-07T21:42:20.526630 | 2016-11-30T19:03:37 | 2016-11-30T19:03:37 | 74,032,266 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 453 | cpp | // 2.7.cpp : Defines the entry point for the console application.
//
#include <stdio.h>
#define SIZE 250
int main()
{
char str[SIZE];
int specs=32;
printf("Enter the string:\n");
fgets(str, SIZE, stdin);
int ch[256]={0};
for(int i = 0; str[i] != '\0'; i++)
{
ch[str[i]]++;
}
for (;specs < 256; specs++)
{
char a=specs;
if (ch[specs] != 0)
{
printf("%c | %d\n", a, ch[specs]);
}
}
getchar();
getchar();
return( 0);
} | [
"olesyagolovanova1@yandex.ru"
] | olesyagolovanova1@yandex.ru |
409d934b6d78bb3624d050c94dbf71aa07c93f09 | 3d79227cc3f1e6157cf22c3338b13bb09ef60b42 | /ibrdtn/ibrdtn/ibrdtn/data/SDNV.h | f37f18e1c13da5a8407e385a535ba94da278e57d | [
"Apache-2.0"
] | permissive | aayushjr/ibrdtn | 6cc7e0a4131e70cf036b326b28a86a5e8d7137e0 | 538d3abc619faa0122867bfc5bdc6a9f9647d31a | refs/heads/master | 2020-12-24T09:53:07.419592 | 2013-07-16T14:25:08 | 2013-07-16T14:25:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,043 | h | /*
* SDNV.h
*
* Copyright (C) 2011 IBR, TU Braunschweig
*
* Written-by: Johannes Morgenroth <morgenroth@ibr.cs.tu-bs.de>
*
* 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.
*
* THIS FILE BASES ON DTN_2.4.0/SERVLIB/BUNDLING/SDNV.H
*/
#include <ibrcommon/Exceptions.h>
#include <ibrdtn/data/Exceptions.h>
#include <sstream>
#include <sys/types.h>
#include <iostream>
#include <stdio.h>
#include <stdint.h>
#include <limits>
#include <cstdlib>
#ifndef _SDNV_H_
#define _SDNV_H_
/**
* Class to handle parsing and formatting of self describing numeric
* values (SDNVs).
*
* The basic idea is to enable a compact byte representation of
* numeric values that may widely vary in size. This encoding is based
* on the ASN.1 specification for encoding Object Identifier Arcs.
*
* Conceptually, the integer value to be encoded is split into 7-bit
* segments. These are encoded into the output byte stream, such that
* the high order bit in each byte is set to one for all bytes except
* the last one.
*
* Note that this implementation only handles values up to 64-bits in
* length (since the conversion is between a uint64_t and the encoded
* byte sequence).
*/
namespace dtn
{
namespace data
{
class ValueOutOfRangeException : public dtn::InvalidDataException
{
public:
ValueOutOfRangeException(const std::string &what = "The value is out of range.") throw() : dtn::InvalidDataException(what)
{
};
};
template<class E>
class SDNV
{
public:
/**
* The maximum length for this SDNV implementation is 10 bytes,
* since the maximum value is 64 bits wide.
*/
static const size_t MAX_LENGTH = 10;
/**
* Constructor for a SDNV object
* @param value The new value of the SDNV
*/
SDNV(const E value) : _value(value) {
}
SDNV() : _value(0) {
}
/**
* Destructor
* @return
*/
~SDNV() {
}
/**
* Determine the encoded length of the value.
* @return The length of the encoded value.
*/
size_t getLength() const
{
size_t val_len = 0;
E tmp = _value;
do {
tmp = tmp >> 7;
val_len++;
} while (tmp != 0);
return val_len;
}
template<typename T>
T get() const {
return static_cast<T>(_value);
}
const E& get() const {
return _value;
}
const SDNV& operator=(const E value) {
_value = value;
return (*this);
}
bool operator==(const E value) const
{
return (value == _value);
}
bool operator==(const SDNV<E> &value) const
{
return (value._value == _value);
}
bool operator!=(const E value) const
{
return (value != _value);
}
bool operator!=(const SDNV<E> &value) const
{
return (value._value != _value);
}
SDNV<E> operator+(const E value)
{
E result = _value + value;
return SDNV<E>(result);
}
SDNV<E> operator+(const SDNV<E> &value)
{
E result = _value + value._value;
return SDNV<E>(result);
}
friend
SDNV<E> operator+(const SDNV<E> &left, const SDNV<E> &right)
{
SDNV<E> ret(left);
ret += right;
return ret;
}
friend
SDNV<E> operator+(const SDNV<E> &left, const E right)
{
SDNV<E> ret(left);
ret += right;
return ret;
}
SDNV<E>& operator+=(const E value)
{
_value += value;
return (*this);
}
SDNV<E>& operator+=(const SDNV<E> &value)
{
_value += value._value;
return (*this);
}
SDNV<E>& operator++() // prefix
{
++_value;
return (*this);
}
SDNV<E> operator++(int) // postfix
{
SDNV<E> prev(*this);
++_value;
return prev;
}
SDNV<E> operator-(const E value)
{
E result = _value - value;
return SDNV<E>(result);
}
SDNV<E> operator-(const SDNV<E> &value)
{
E result = _value - value._value;
return SDNV<E>(result);
}
friend
SDNV<E> operator-(const SDNV<E> &left, const SDNV<E> &right)
{
SDNV<E> ret(left);
ret -= right;
return ret;
}
friend
SDNV<E> operator-(const SDNV<E> &left, const E right)
{
SDNV<E> ret(left);
ret -= right;
return ret;
}
SDNV<E>& operator-=(const E value)
{
_value -= value;
return (*this);
}
SDNV<E>& operator-=(const SDNV<E> &value)
{
_value -= value._value;
return (*this);
}
SDNV<E>& operator--() // prefix
{
--_value;
return (*this);
}
SDNV<E> operator--(int) // postfix
{
SDNV<E> prev(*this);
--_value;
return prev;
}
SDNV<E> operator/(const E value)
{
E result = _value / value;
return SDNV<E>(result);
}
SDNV<E> operator/(const SDNV<E> &value)
{
E result = _value / value._value;
return SDNV<E>(result);
}
friend
SDNV<E> operator/(const SDNV<E> &left, const SDNV<E> &right)
{
SDNV<E> ret(left);
ret /= right;
return ret;
}
friend
SDNV<E> operator/(const SDNV<E> &left, const E right)
{
SDNV<E> ret(left);
ret /= right;
return ret;
}
SDNV<E>& operator/=(const E value)
{
_value /= value;
return (*this);
}
SDNV<E>& operator/=(const SDNV<E> &value)
{
_value /= value._value;
return (*this);
}
SDNV<E> operator*(const E value)
{
E result = _value * value;
return SDNV<E>(result);
}
SDNV<E> operator*(const SDNV<E> &value)
{
E result = _value * value._value;
return SDNV<E>(result);
}
friend
SDNV<E> operator*(const SDNV<E> &left, const SDNV<E> &right)
{
SDNV<E> ret(left);
ret *= right;
return ret;
}
friend
SDNV<E> operator*(const SDNV<E> &left, const E right)
{
SDNV<E> ret(left);
ret *= right;
return ret;
}
SDNV<E>& operator*=(const E value)
{
_value *= value;
return (*this);
}
SDNV<E>& operator*=(const SDNV<E> &value)
{
_value *= value._value;
return (*this);
}
bool operator&(const SDNV<E> &value) const
{
return (value._value & _value);
}
bool operator|(const SDNV<E> &value) const
{
return (value._value | _value);
}
SDNV<E>& operator&=(const SDNV<E> &value)
{
_value &= value._value;
return (*this);
}
SDNV<E>& operator|=(const SDNV<E> &value)
{
_value |= value._value;
return (*this);
}
bool operator<(const E value) const
{
return (_value < value);
}
bool operator<=(const E value) const
{
return (_value <= value);
}
bool operator>(const E value) const
{
return (_value > value);
}
bool operator>=(const E value) const
{
return (_value >= value);
}
bool operator<(const SDNV<E> &value) const
{
return (_value < value._value);
}
bool operator<=(const SDNV<E> &value) const
{
return (_value <= value._value);
}
bool operator>(const SDNV<E> &value) const
{
return (_value > value._value);
}
bool operator>=(const SDNV<E> &value) const
{
return (_value >= value._value);
}
static SDNV<E> max()
{
return std::numeric_limits<E>::max();
}
SDNV<E>& random()
{
// for compatibility use 32-bit here
uint32_t val = static_cast<uint32_t>(::random());
(*this) = static_cast<E>(val);
return (*this);
}
std::string toString() const {
std::stringstream ss;
ss << _value;
return ss.str();
}
void fromString(const std::string &data) {
std::stringstream ss; ss.str(data);
ss >> _value;
}
void read(std::istream &stream) {
stream >> _value;
}
void encode(std::ostream &stream) const
{
unsigned char buffer[10];
unsigned char *bp = &buffer[0];
uint64_t val = _value;
const size_t val_len = getLength();
if (!(val_len > 0)) throw ValueOutOfRangeException("ERROR(SDNV): !(val_len > 0)");
if (!(val_len <= SDNV::MAX_LENGTH)) throw ValueOutOfRangeException("ERROR(SDNV): !(val_len <= MAX_LENGTH)");
// Now advance bp to the last byte and fill it in backwards with the value bytes.
bp += val_len;
unsigned char high_bit = 0; // for the last octet
do {
--bp;
*bp = (unsigned char)(high_bit | (val & 0x7f));
high_bit = (1 << 7); // for all but the last octet
val = val >> 7;
} while (val != 0);
if (!(bp == &buffer[0])) throw ValueOutOfRangeException("ERROR(SDNV): !(bp == buffer)");
// write encoded value to the stream
stream.write((const char*)&buffer[0], val_len);
}
void decode(std::istream &stream)
{
size_t val_len = 0;
unsigned char bp = 0;
unsigned char start = 0;
int carry = 0;
_value = 0;
do {
stream.get((char&)bp);
_value = (_value << 7) | (bp & 0x7f);
++val_len;
if ((bp & (1 << 7)) == 0)
break; // all done;
// check if the value fits into sizeof(E)
if ((val_len % 8) == 0) ++carry;
if ((sizeof(E) + carry) < val_len)
throw ValueOutOfRangeException("ERROR(SDNV): overflow value in sdnv");
if (start == 0) start = bp;
} while (1);
if ((val_len > SDNV::MAX_LENGTH) || ((val_len == SDNV::MAX_LENGTH) && (start != 0x81)))
throw ValueOutOfRangeException("ERROR(SDNV): overflow value in sdnv");
}
private:
friend
std::ostream &operator<<(std::ostream &stream, const dtn::data::SDNV<E> &obj)
{
obj.encode(stream);
return stream;
}
friend
std::istream &operator>>(std::istream &stream, dtn::data::SDNV<E> &obj)
{
obj.decode(stream);
return stream;
}
E _value;
};
}
}
#endif /* _SDNV_H_ */
| [
"morgenroth@ibr.cs.tu-bs.de"
] | morgenroth@ibr.cs.tu-bs.de |
a621d36e269da0c185f9cdb9f2a262ae63e388d0 | 04034f7423b775259d3faaae2837f83e35c864dc | /OOP - ProperTrenchCoats/Tests.h | d2ce4bdae61e343cd9e346388ecc20cb6ac2e22a | [] | no_license | AdrianM20/OOP-ProperTrenchCoats__Lab5-6 | 5754a1d6926d59c4081ae68c43d1a183c2beb394 | efdf24cd91c14246043419a2f7961a7ec2912895 | refs/heads/master | 2021-01-20T01:50:17.432125 | 2017-05-27T17:08:04 | 2017-05-27T17:08:04 | 89,092,016 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 255 | h | #pragma once
#include <assert.h>
#include <stdexcept>
class Tests
{
public:
static void testCoat();
static void testRepository();
static void testValidators();
static void testShoppingCart();
static void testController();
static void testAll();
}; | [
"mihu.adrian97@gmail.com"
] | mihu.adrian97@gmail.com |
ad52caeeb3cc021db81d3593ad3aa8106b22f272 | 677de9d6219c779c1c14ef65370722b8a4543212 | /src/qt/receiverequestdialog.cpp | 046f784376086b3609b06d924643fe7140714f58 | [
"MIT"
] | permissive | LordSoylent/Vapex | 1bef9674f9580260212227e65e60d474305ea4e2 | 3ed2b7ef75b9557a06db7994053bb75a3f86deb6 | refs/heads/master | 2020-05-26T04:31:36.707397 | 2018-09-20T11:28:55 | 2018-09-20T11:28:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,625 | cpp | // Copyright (c) 2011-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "receiverequestdialog.h"
#include "ui_receiverequestdialog.h"
#include "bitcoinunits.h"
#include "guiconstants.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "walletmodel.h"
#include <QClipboard>
#include <QDrag>
#include <QMenu>
#include <QMimeData>
#include <QMouseEvent>
#include <QPixmap>
#if QT_VERSION < 0x050000
#include <QUrl>
#endif
#if defined(HAVE_CONFIG_H)
#include "config/vapexcoin-config.h" /* for USE_QRCODE */
#endif
#ifdef USE_QRCODE
#include <qrencode.h>
#endif
QRImageWidget::QRImageWidget(QWidget* parent) : QLabel(parent), contextMenu(0)
{
contextMenu = new QMenu();
QAction* saveImageAction = new QAction(tr("&Save Image..."), this);
connect(saveImageAction, SIGNAL(triggered()), this, SLOT(saveImage()));
contextMenu->addAction(saveImageAction);
QAction* copyImageAction = new QAction(tr("&Copy Image"), this);
connect(copyImageAction, SIGNAL(triggered()), this, SLOT(copyImage()));
contextMenu->addAction(copyImageAction);
}
QImage QRImageWidget::exportImage()
{
if (!pixmap())
return QImage();
return pixmap()->toImage().scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE);
}
void QRImageWidget::mousePressEvent(QMouseEvent* event)
{
if (event->button() == Qt::LeftButton && pixmap()) {
event->accept();
QMimeData* mimeData = new QMimeData;
mimeData->setImageData(exportImage());
QDrag* drag = new QDrag(this);
drag->setMimeData(mimeData);
drag->exec();
} else {
QLabel::mousePressEvent(event);
}
}
void QRImageWidget::saveImage()
{
if (!pixmap())
return;
QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Image (*.png)"), NULL);
if (!fn.isEmpty()) {
exportImage().save(fn);
}
}
void QRImageWidget::copyImage()
{
if (!pixmap())
return;
QApplication::clipboard()->setImage(exportImage());
}
void QRImageWidget::contextMenuEvent(QContextMenuEvent* event)
{
if (!pixmap())
return;
contextMenu->exec(event->globalPos());
}
ReceiveRequestDialog::ReceiveRequestDialog(QWidget* parent) : QDialog(parent),
ui(new Ui::ReceiveRequestDialog),
model(0)
{
ui->setupUi(this);
#ifndef USE_QRCODE
ui->btnSaveAs->setVisible(false);
ui->lblQRCode->setVisible(false);
#endif
connect(ui->btnSaveAs, SIGNAL(clicked()), ui->lblQRCode, SLOT(saveImage()));
}
ReceiveRequestDialog::~ReceiveRequestDialog()
{
delete ui;
}
void ReceiveRequestDialog::setModel(OptionsModel* model)
{
this->model = model;
if (model)
connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(update()));
// update the display unit if necessary
update();
}
void ReceiveRequestDialog::setInfo(const SendCoinsRecipient& info)
{
this->info = info;
update();
}
void ReceiveRequestDialog::update()
{
if (!model)
return;
QString target = info.label;
if (target.isEmpty())
target = info.address;
setWindowTitle(tr("Request payment to %1").arg(target));
QString uri = GUIUtil::formatBitcoinURI(info);
ui->btnSaveAs->setEnabled(false);
QString html;
html += "<html><font face='verdana, arial, helvetica, sans-serif'>";
html += "<b>" + tr("Payment information") + "</b><br>";
html += "<b>" + tr("URI") + "</b>: ";
html += "<a style=\"color:#00CD8D;\" href=\"" + uri + "\">" + GUIUtil::HtmlEscape(uri) + "</a><br>";
html += "<b>" + tr("Address") + "</b>: " + GUIUtil::HtmlEscape(info.address) + "<br>";
if (info.amount)
html += "<b>" + tr("Amount") + "</b>: " + BitcoinUnits::formatWithUnit(model->getDisplayUnit(), info.amount) + "<br>";
if (!info.label.isEmpty())
html += "<b>" + tr("Label") + "</b>: " + GUIUtil::HtmlEscape(info.label) + "<br>";
if (!info.message.isEmpty())
html += "<b>" + tr("Message") + "</b>: " + GUIUtil::HtmlEscape(info.message) + "<br>";
ui->outUri->setText(html);
#ifdef USE_QRCODE
ui->lblQRCode->setText("");
if (!uri.isEmpty()) {
// limit URI length
if (uri.length() > MAX_URI_LENGTH) {
ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message."));
} else {
QRcode* code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1);
if (!code) {
ui->lblQRCode->setText(tr("Error encoding URI into QR Code."));
return;
}
QImage myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32);
myImage.fill(0xffffff);
unsigned char* p = code->data;
for (int y = 0; y < code->width; y++) {
for (int x = 0; x < code->width; x++) {
myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff));
p++;
}
}
QRcode_free(code);
ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300));
ui->btnSaveAs->setEnabled(true);
}
}
#endif
}
void ReceiveRequestDialog::on_btnCopyURI_clicked()
{
GUIUtil::setClipboard(GUIUtil::formatBitcoinURI(info));
}
void ReceiveRequestDialog::on_btnCopyAddress_clicked()
{
GUIUtil::setClipboard(info.address);
}
| [
"41511792+VapeCoinDev@users.noreply.github.com"
] | 41511792+VapeCoinDev@users.noreply.github.com |
660756845f207728167ec3800bdb30088441a0bd | 0f0aabafee166e71e8d18eb06930f4daeb031abc | /typedefs.h | d79464dc8cf990f54892b65b159eb3f50de9fbb0 | [] | no_license | rubenguilherme/alphasteroids | 5f21117acc19d5f37020fc319f947b56ffbcc773 | 4082635cf81992bf29886b14a1837ff7772ac13c | refs/heads/master | 2023-02-15T14:12:23.234310 | 2021-01-14T23:59:47 | 2021-01-14T23:59:47 | 329,761,363 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 104 | h | #pragma once
#include <vector>
#include <game_object.hpp>
typedef std::vector<GameObject*> GAMEOBJECTS; | [
"ruben.henriques.guilherme@gmail.com"
] | ruben.henriques.guilherme@gmail.com |
2c52c1493da34a9705cf3a22ac29e8aaa5d8e8e7 | 560090526e32e009e2e9331e8a2b4f1e7861a5e8 | /Compiled/blaze-3.2/blazemark/blazemark/boost/DMatTrans.h | 36ba51b4a307aedd8aba4a9fb551a5ef9b74bb01 | [
"BSD-3-Clause"
] | permissive | jcd1994/MatlabTools | 9a4c1f8190b5ceda102201799cc6c483c0a7b6f7 | 2cc7eac920b8c066338b1a0ac495f0dbdb4c75c1 | refs/heads/master | 2021-01-18T03:05:19.351404 | 2018-02-14T02:17:07 | 2018-02-14T02:17:07 | 84,264,330 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,007 | h | //=================================================================================================
/*!
// \file blazemark/boost/DMatTrans.h
// \brief Header file for the Boost dense matrix transpose kernel
//
// Copyright (C) 2012-2017 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
#ifndef _BLAZEMARK_BOOST_DMATTRANS_H_
#define _BLAZEMARK_BOOST_DMATTRANS_H_
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <blazemark/system/Types.h>
namespace blazemark {
namespace boost {
//=================================================================================================
//
// KERNEL FUNCTIONS
//
//=================================================================================================
//*************************************************************************************************
/*!\name Boost uBLAS kernel functions */
//@{
double dmattrans( size_t N, size_t steps );
//@}
//*************************************************************************************************
} // namespace boost
} // namespace blazemark
#endif
| [
"jonathan.doucette@alumni.ubc.ca"
] | jonathan.doucette@alumni.ubc.ca |
1a6139d4a4e3baf681d1f9de2578fe1e0dbd305b | 786c32fee065fb428831a29c3416058b240e0bb7 | /include/Node.h | f8764f794f6348613059bd114e357e03e81393ea | [] | no_license | koraykural/Algorithms1-HWIII | 191ec80866608d59420999cd20039622f85ec471 | a070e80fc63f80ec79b760d857e6e7b5c6cf79d2 | refs/heads/main | 2023-02-10T00:17:57.935861 | 2021-01-07T21:37:36 | 2021-01-07T21:37:36 | 324,840,720 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,340 | h | /**
* Node Class for Red-Black Tree.
*/
#ifndef NODE_H
#define NODE_H
enum Color
{
RED,
BLACK,
};
template <class Data, class Key>
struct Node
{
Node *parent, *left, *right;
Color color;
Key key;
Data data;
/**
* Node constructor. Default color is red.
*
* @param node_data {Data} Data of the node.
* @param node_key {Key} Key of the node. Will be used to identify the node.
*/
Node(Data node_data, Key node_key, Color node_color = RED)
{
data = node_data;
key = node_key;
color = node_color;
parent = NULL;
left = NULL;
right = NULL;
}
/**
* Compares keys of two node.
*/
bool operator==(const Node &r)
{
return key == r.key;
}
/**
* Switches color of node between red and black.
*/
void toggle_color()
{
if (color == BLACK)
color = RED;
else
color = BLACK;
}
/**
* Returns whether node is black or not.
*
* @return {bool} True if node is black
*/
bool is_black()
{
return color == BLACK;
}
/**
* Returns whether node is red or not.
*
* @return {bool} True if node is red
*/
bool is_red()
{
return color == RED;
}
};
#endif
| [
"koraykural99@gmail.com"
] | koraykural99@gmail.com |
8bb11ef8e55e356c942f5cc41c57720bb54dc26c | fa9abaa16838c52af01affa4d5246a812f9cb232 | /quicksort.cpp | 27c2ee0cf17e1355c3fee7d9f4f2f7510f4e08e7 | [] | no_license | mcc12357/acm- | fcbfa1d6fc5011d9c8c22f2186d44bcd0f1ceb98 | 114d386353e6cb31f6ba0d121591005bf42e2bed | refs/heads/master | 2020-04-03T17:37:35.742867 | 2019-01-06T01:32:00 | 2019-01-06T01:32:00 | 155,452,881 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 451 | cpp | #include<iostream>
using namespace std;
void print (int a[],int n)
{
for(int j=0;j<n;j++)
{
cout<<a[j]<<" ";
}
cout<<endl;
}
void swap(int *a,int *b)
{
int tmp=*a;
*a = *b;
*b=tmp;
}
int partition(int a[],int low,int high)
{
int privotkey = a[low];
while(low<high)
{
while(low<high && a[high] >= privotkey) --high;
swap(&a[low],&a[high]);
while(low<high && a[low] <= privotkey) ++low;
swap(&a[low],&a[high]);
}
}
int main()
{
} | [
"machaochun1@gmail.com"
] | machaochun1@gmail.com |
23e08ab63e8358934861da46855f9d7108ccfb4c | 792d0f06dd3229190ab003ce2b541ff7973e2fbd | /TP6/contraste.h | c28735dca365fd35412ecc08e464c27d04d6e5e6 | [] | no_license | manleviet/TP-TI | 3433950d1bf52a012218b964eded4e514a5c3e8b | 6af34e43d091e805f0b653805d7c350db5eab509 | refs/heads/master | 2021-01-10T07:50:06.554087 | 2015-06-02T06:27:57 | 2015-06-02T06:27:57 | 36,712,331 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,888 | h | //
//
// contraste.h
//
// La classe permet d'modifier le contraste d'une image
// bang cach tinh gia tri mau co histogram lon nhat, roi dua vao do de tinh hai diem moc de thay doi contraste
// Les fonctionnalités :
// - Dessiner l'histogramme de l'image entrée et de l'image transformée
// - Dessiner la fonction de changement de contraste
// - Afficher les résultats dans les fenêtres
// - Modifier le contraste de l'image entrée
// - Enregistrer les résultats dans des fichiers sous forme ppm
//
// LE Viet Man
// 30/03/2010
// modifie : 29/05/2010
//
//
#ifndef CONTRASTE_H
#define CONTRASTE_H
#include <cv.h>
#include "point.h"
int const MAXNIVEAUDEGRIS = 256;
class Contraste
{
public:
//
// Le constructeur de la classe Contraste
//
Contraste();
//
// Le destructeur
//
~Contraste();
//
// Faire la modification du contraste de l'image entrée
// @param :
// IplImage *img : une image
// @result : une image modifiee
//
IplImage* modifierContraste(IplImage *img);
//
// Dessiner l'histogramme de l'image passée
// @param :
// IplImage *img : l'image passée
// IplImage *&img_his : l'image de l'histogramme de l'image passée
//
IplImage* dessinerHistogramme(IplImage *img);
private:
int LUT[MAXNIVEAUDEGRIS]; // le tableau LUT
//
// Calculer l'histogramme d'une image
// @param :
// IplImage *img : une image
// float &min_value : une variable qui contenira la plus moins valeur
// float &max_value : une variable qui contenire la plus haute valeur
// @result : CvHistogram
//
CvHistogram* calcHistogram(IplImage *img, float &min_value, float &max_value);
//
// Prendre la position de la plus haute valeur dans l'histogramme
// @param :
// CvHistogram *hist : un histogramme
// float max_value : la plus haute valeur
// @result : la position dans l'histogramme
//
int getPosMaxHist(CvHistogram *hist, float max_value);
//
// Calculer le tableau LUT
// @param :
// Point *points : un array des Points de la fonction de transformation
// int taillePoints : la longeur du array
//
void calculerLUT(Point *points, int taillePoints);
//
// Faire la modification du contraste de l'image passée
// @param:
// IplImage *img : une image
// @result : une image modifiee
//
IplImage* faireContraste(IplImage *img);
//
// Dessiner la fonction de changement de contraste
// @param :
// Point *points : un array des Point de la fonction de transfromation
// int taillePoints : la longeur du array
// @result : une image de la fonction de transformation
//
IplImage* dessinerFonction(Point *points, int taillePoints);
};
#endif // CONTRASTE_H
| [
"manleviet@gmail.com"
] | manleviet@gmail.com |
a515361821021bbc38feb8b73131df47301575e3 | bc89fa387526ca8ec5abe022c0ed3344be5fb4e0 | /src/motion/motion_model/src/constant_velocity.cpp | 111060d05bd7144a290a23c29181f73703f0fc3c | [
"Apache-2.0"
] | permissive | jimaldon/AutowareAuto | e6ba444d0e36c5660bab6a5d903e614c993605ec | 2b639aa06f67e41222c89f3885c0472483ac6b38 | refs/heads/master | 2020-08-17T07:27:01.356545 | 2019-10-14T15:10:26 | 2019-10-14T15:10:26 | 215,632,366 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,496 | cpp | // Copyright 2018 Apex.AI, Inc.
// Co-developed by Tier IV, Inc. and Apex.AI, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/// \copyright Copyright 2018 Apex.AI, Inc.
/// All rights reserved.
#include "motion_model/constant_velocity.hpp"
namespace autoware
{
namespace motion
{
namespace motion_model
{
///
ConstantVelocity & ConstantVelocity::operator=(const ConstantVelocity & rhs)
{
if (this != &rhs) {
m_state = rhs.m_state;
}
return *this;
}
///
void ConstantVelocity::predict(
Eigen::Matrix<float, 4U, 1U> & x,
const std::chrono::nanoseconds & dt) const
{
const float dt_s = static_cast<float>(dt.count()) / 1000000000LL;
x(States::POSE_X) = m_state(States::POSE_X) + (dt_s * m_state(States::VELOCITY_X));
x(States::POSE_Y) = m_state(States::POSE_Y) + (dt_s * m_state(States::VELOCITY_Y));
x(States::VELOCITY_X) = m_state(States::VELOCITY_X);
x(States::VELOCITY_Y) = m_state(States::VELOCITY_Y);
}
///
void ConstantVelocity::predict(const std::chrono::nanoseconds & dt)
{
predict(m_state, dt);
}
///
void ConstantVelocity::compute_jacobian(
Eigen::Matrix<float, 4U, 4U> & F,
const std::chrono::nanoseconds & dt)
{
const float dt_s = static_cast<float>(dt.count()) / 1000000000LL;
// identity matrix
F.setIdentity();
// only nonzero elements are ones along diagonal + constant terms for velocity
F(States::POSE_X, States::VELOCITY_X) = dt_s;
F(States::POSE_Y, States::VELOCITY_Y) = dt_s;
}
///
void ConstantVelocity::compute_jacobian_and_predict(
Eigen::Matrix<float, 4U, 4U> & F,
const std::chrono::nanoseconds & dt)
{
compute_jacobian(F, dt);
predict(dt);
}
///
float ConstantVelocity::operator[](const index_t idx) const {return m_state(idx);}
///
void ConstantVelocity::reset(const Eigen::Matrix<float, 4U, 1U> & x)
{
m_state = x;
}
///
const Eigen::Matrix<float, 4U, 1U> & ConstantVelocity::get_state() const
{
return m_state;
}
} // namespace motion_model
} // namespace motion
} // namespace autoware
| [
"christopher.ho@apex.ai"
] | christopher.ho@apex.ai |
2db6726f3afd5986beebefe6b16a67020dad8f89 | b0a82b2dcc289381ea0ab94271be7540282e509b | /src/kernel/core/protocol/ProtocolBase.hpp | e82609176b7bcb5e21442a0e7cf4b804bb40eaf6 | [] | no_license | ddkv587/Net | 6d2ecbcdbf1f1fef5bb338670bcb662e094f50be | 921a57f1f8ad6435491c419abd065404fbd41bf6 | refs/heads/master | 2021-06-06T14:13:55.587080 | 2019-03-25T11:06:48 | 2019-03-25T11:06:48 | 107,846,541 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,314 | hpp | #ifndef __PROTOCOLBASEHPP__
#define __PROTOCOLBASEHPP__
namespace NET
{
class CProtocolBase : public IProtocol
{
public:
enum EProcotol
{
EP_INVALID = 0,
EP_ECHO,
EP_PING,
EP_TIME,
EP_HEART,
EP_DISMISS,
EP_MAX
};
typedef struct tagSocketPing
{
int current;
int deadLimit;
} PING_MANAGER;
typedef struct tagSocketTime
{
int second;
int millsecond;
int offet;
int type;
} TIME_MANAGER;
typedef struct tagSocketHeart
{
int type;
int time;
} HEART_MANAGER;
const static int SIZE_PING_MANAGER = sizeof(PING_MANAGER);
const static int SIZE_TIME_MANAGER = sizeof(TIME_MANAGER);
const static int SIZE_HEART_MANAGER = sizeof(HEART_MANAGER);
public:
CProtocolBase();
virtual ~CProtocolBase();
virtual INT analyse(CHAR*, UINT) override;
virtual int package(int, const OBJECT*, char*&) override;
virtual int callSpecialFunc(int, int, const char*, OBJECT*&);
private:
bool checkProtocol(int);
int checkSize(int, int);
int innerPackageECHO(const OBJECT*, char*&);
int innerPackagePING(const OBJECT*, char*&);
void innerPackageTIME();
void innerPackageHEART();
CProtocolBase(CProtocolBase&) = delete;
CProtocolBase(const CProtocolBase&) = delete;
};
}
#endif
| [
"ddkv587@gmail.com"
] | ddkv587@gmail.com |
6483d9da165f817da8af5b6b0b6bc85324499c4b | 7d39da2aeb8f26327fc92923f4d8b1f08aa954ee | /src/STM32-MultiRF/RFProtocolMJXQ.cpp | 1aa60b0cf928391e73845079aa47a60b5bef2c05 | [] | no_license | PingguSoft/STM32F103 | 110e87b1241eaa54fa0370427dc65fd38757aaf1 | 88a21e7962d4c12ea02d31b9119c4ffa248292d0 | refs/heads/master | 2020-04-16T19:18:51.051852 | 2016-11-01T07:09:02 | 2016-11-01T07:09:02 | 54,895,606 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 11,820 | cpp | /*
This project 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 derived from deviationTx project for Arduino.
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.
see <http://www.gnu.org/licenses/>
*/
#include <SPI.h>
#include "RFProtocolMJXQ.h"
#include "utils.h"
#define BIND_COUNT 150
#define PACKET_PERIOD 4000 // Timeout for callback in uSec
#define INITIAL_WAIT 500
#define ADDRESS_LENGTH 5
enum {
FORMAT_WLH08 = 0,
FORMAT_X600,
FORMAT_X800,
FORMAT_H26D,
FORMAT_E010,
};
enum {
MJXq_INIT1 = 0,
MJXq_BIND1,
MJXq_DATA
};
#define CHANNEL_LED CH_AUX1
#define CHANNEL_FLIP CH_AUX2
#define CHANNEL_PICTURE CH_AUX3
#define CHANNEL_VIDEO CH_AUX4
#define CHANNEL_HEADLESS CH_AUX5
#define CHANNEL_RTH CH_AUX6
#define CHANNEL_AUTOFLIP CH_AUX7 // X800, X600
#define CHANNEL_PAN CH_AUX8 // H26D
#define CHANNEL_TILT CH_AUX9
// haven't figured out txid<-->rf channel mapping for MJX models
struct id_ch_map {
u8 txid[3];
u8 rfchan[4];
};
const struct id_ch_map TBL_TX_RF_MAP[] =
{
{{0xF8, 0x4F, 0x1C}, {0x0A, 0x46, 0x3A, 0x42}},
{{0xC8, 0x6E, 0x02}, {0x0A, 0x3C, 0x36, 0x3F}},
{{0x48, 0x6A, 0x40}, {0x0A, 0x43, 0x36, 0x3F}}
};
u8 RFProtocolMJXQ::calcCheckSum(void)
{
u8 sum = mPacketBuf[0];
for (u8 i = 1; i < MAX_PACKET_SIZE - 1; i++)
sum += mPacketBuf[i];
return sum;
}
#define BABS(X) (((X) < 0) ? -(u8)(X) : (X))
#define LIMIT_CHAN(X) (X < CHAN_MIN_VALUE ? CHAN_MIN_VALUE : (X > CHAN_MAX_VALUE ? CHAN_MAX_VALUE : X))
#define PAN_TILT_COUNT 16 // for H26D - match stock tx timing
#define PAN_DOWN 0x08
#define PAN_UP 0x04
#define TILT_DOWN 0x20
#define TILT_UP 0x10
u8 RFProtocolMJXQ::calcPanTilt(void)
{
static u8 count;
u8 pan = 0;
count++;
s32 ch = LIMIT_CHAN(RFProtocol::getControl(CHANNEL_PAN));
if ((ch < CHAN_MIN_VALUE / 2 || ch > CHAN_MAX_VALUE / 2) && (count & PAN_TILT_COUNT))
pan = ch < 0 ? PAN_DOWN : PAN_UP;
ch = LIMIT_CHAN(RFProtocol::getControl(CHANNEL_TILT));
if ((ch < CHAN_MIN_VALUE / 2 || ch > CHAN_MAX_VALUE / 2) && (count & PAN_TILT_COUNT))
return pan + (ch < 0 ? TILT_DOWN : TILT_UP);
return pan;
}
#define GET_FLAG(ch, mask) (RFProtocol::getControl(ch) > 0 ? mask : 0)
#define GET_FLAG_INV(ch, mask) (RFProtocol::getControl(ch) < 0 ? mask : 0)
//#define CHAN2TRIM(X) ((((X) & 0x80 ? 0xff - (X) : 0x80 + (X)) >> 1) + 0x00)
#define CHAN2TRIM(X) (((X) & 0x80 ? (X) : 0x7f - (X)) >> 1)
void RFProtocolMJXQ::sendPacket(u8 bind)
{
mPacketBuf[0] = getControl_8b(CH_THROTTLE); // throttle
mPacketBuf[1] = getControl_s8b(CH_RUDDER); // rudder
mPacketBuf[4] = 0x40; // rudder does not work well with dyntrim
mPacketBuf[2] = getControl_s8b(CH_ELEVATOR); // elevator
// driven trims cause issues when headless is enabled
mPacketBuf[5] = GET_FLAG(CHANNEL_HEADLESS, 1) ? 0x40 : CHAN2TRIM(mPacketBuf[2]); // trim elevator
mPacketBuf[3] = getControl_s8b(CH_AILERON); // aileron
mPacketBuf[6] = GET_FLAG(CHANNEL_HEADLESS, 1) ? 0x40 : CHAN2TRIM(mPacketBuf[3]); // trim aileron
mPacketBuf[7] = mTxID[0];
mPacketBuf[8] = mTxID[1];
mPacketBuf[9] = mTxID[2];
mPacketBuf[10] = 0; // overwritten below for feature bits
mPacketBuf[11] = 0; // overwritten below for X600
mPacketBuf[12] = 0;
mPacketBuf[13] = 0;
mPacketBuf[14] = 0xc0; // bind value
switch (getProtocolOpt()) {
case FORMAT_H26D:
mPacketBuf[10] = calcPanTilt();
// fall through on purpose - no break
case FORMAT_WLH08:
case FORMAT_E010:
mPacketBuf[10] = mPacketBuf[10] |
GET_FLAG(CHANNEL_RTH, 0x02) |
GET_FLAG(CHANNEL_HEADLESS, 0x01);
if (!bind) {
mPacketBuf[14] = GET_FLAG(CHANNEL_FLIP, 0x01);
if (getProtocolOpt() == FORMAT_WLH08) {
mPacketBuf[14] = mPacketBuf[14] |
GET_FLAG(CHANNEL_PICTURE, 0x08) |
GET_FLAG(CHANNEL_VIDEO, 0x10) |
GET_FLAG_INV(CHANNEL_LED, 0x20); // air/ground mode
} else {
mPacketBuf[14] = mPacketBuf[14] |
GET_FLAG(CH_AUX1, 0x04); // 0x04 : high rate
}
}
break;
case FORMAT_X600:
mPacketBuf[10] = GET_FLAG_INV(CHANNEL_LED, 0x02);
mPacketBuf[11] = GET_FLAG(CHANNEL_RTH, 0x01);
if (!bind) {
mPacketBuf[14] = 0x02 // always high rates by bit2 = 1
| GET_FLAG(CHANNEL_FLIP, 0x04)
| GET_FLAG(CHANNEL_AUTOFLIP, 0x10)
| GET_FLAG(CHANNEL_HEADLESS, 0x20);
}
break;
case FORMAT_X800:
default:
mPacketBuf[10] = 0x10
| GET_FLAG_INV(CHANNEL_LED, 0x02)
| GET_FLAG(CHANNEL_AUTOFLIP, 0x01);
if (!bind) {
mPacketBuf[14] = 0x02 // always high rates by bit2 = 1
| GET_FLAG(CHANNEL_FLIP, 0x04)
| GET_FLAG(CHANNEL_PICTURE, 0x08)
| GET_FLAG(CHANNEL_VIDEO, 0x10);
}
}
mPacketBuf[15] = calcCheckSum();
// Power on, TX mode, 2byte CRC
if (getProtocolOpt() == FORMAT_H26D) {
mDev.setRFMode(RF_TX);
} else {
mDev.XN297_configure(BV(NRF24L01_00_EN_CRC) | BV(NRF24L01_00_CRCO) | BV(NRF24L01_00_PWR_UP));
}
mDev.writeReg(NRF24L01_05_RF_CH, mRFChanBufs[mCurRFChan++ / 2]);
mCurRFChan %= 2 * MAX_RF_CHANNELS; // channels repeated
mDev.writeReg(NRF24L01_07_STATUS, 0x70);
mDev.flushTx();
if (getProtocolOpt() == FORMAT_H26D) {
mDev.writePayload(mPacketBuf, MAX_PACKET_SIZE);
} else {
mDev.XN297_writePayload(mPacketBuf, MAX_PACKET_SIZE);
}
// Check and adjust transmission power. We do this after
// transmission to not bother with timeout after power
// settings change - we have plenty of time until next
// mPacketBuf.
if (isRFPowerUpdated()) {
mDev.setRFPower(getRFPower());
clearRFPowerUpdated();
}
}
void RFProtocolMJXQ::init1()
{
u8 rx_tx_addr[ADDRESS_LENGTH];
memcpy(rx_tx_addr, "\x6d\x6a\x77\x77\x77", sizeof(rx_tx_addr));
if (getProtocolOpt() == FORMAT_WLH08) {
memcpy(mRFChanBufs, "\x12\x22\x32\x42", sizeof(mRFChanBufs));
} else if (getProtocolOpt() == FORMAT_H26D || getProtocolOpt() == FORMAT_E010) {
memcpy(mRFChanBufs, "\x36\x3e\x46\x2e", sizeof(mRFChanBufs));
} else {
memcpy(mRFChanBufs, "\x0a\x35\x42\x3d", sizeof(mRFChanBufs));
memcpy(rx_tx_addr, "\x6d\x6a\x73\x73\x73", sizeof(rx_tx_addr));
}
__PRINT_FUNC__;
mDev.initialize();
mDev.setRFMode(RF_TX);
// SPI trace of stock TX has these writes to registers that don't appear in
// nRF24L01 or Beken 2421 datasheets. Uncomment if you have an XN297 chip?
// NRF24L01_WriteRegisterMulti(0x3f, "\x4c\x84\x67,\x9c,\x20", 5);
// NRF24L01_WriteRegisterMulti(0x3e, "\xc9\x9a\xb0,\x61,\xbb,\xab,\x9c", 7);
// NRF24L01_WriteRegisterMulti(0x39, "\x0b\xdf\xc4,\xa7,\x03,\xab,\x9c", 7);
if (getProtocolOpt() == FORMAT_H26D) {
mDev.writeRegMulti(NRF24L01_10_TX_ADDR, rx_tx_addr, sizeof(rx_tx_addr));
} else {
mDev.XN297_setTxAddr(rx_tx_addr, sizeof(rx_tx_addr));
}
mDev.flushTx();
mDev.flushRx();
mDev.writeReg(NRF24L01_07_STATUS, 0x70); // Clear data ready, data sent, and retransmit
mDev.writeReg(NRF24L01_01_EN_AA, 0x00); // No Auto Acknowldgement on all data pipes
mDev.writeReg(NRF24L01_02_EN_RXADDR, 0x01);
mDev.writeReg(NRF24L01_04_SETUP_RETR, 0x00); // no retransmits
mDev.writeReg(NRF24L01_11_RX_PW_P0, MAX_PACKET_SIZE);
if (getProtocolOpt() == FORMAT_E010) {
mDev.setBitrate(NRF24L01_BR_250K);
} else {
mDev.setBitrate(NRF24L01_BR_1M);
}
mDev.setRFPower(getRFPower());
mDev.activate(0x73); // Activate feature register
mDev.writeReg(NRF24L01_1C_DYNPD, 0x00); // Disable dynamic payload length on all pipes
mDev.writeReg(NRF24L01_1D_FEATURE, 0x00);
mDev.activate(0x73);
}
void RFProtocolMJXQ::init2()
{
__PRINT_FUNC__;
if (getProtocolOpt() == FORMAT_H26D) {
memcpy(mRFChanBufs, "\x32\x3e\x42\x4e", sizeof(mRFChanBufs));
} else if (getProtocolOpt() != FORMAT_WLH08 && getProtocolOpt() != FORMAT_E010) {
memcpy(mRFChanBufs, TBL_TX_RF_MAP[getControllerID() % (sizeof(TBL_TX_RF_MAP) / sizeof(TBL_TX_RF_MAP[0]))].rfchan, MAX_RF_CHANNELS);
}
}
u16 RFProtocolMJXQ::callState(u32 now, u32 expected)
{
switch (mState) {
case MJXq_INIT1:
mState = MJXq_BIND1;
break;
case MJXq_BIND1:
if (mBindCtr == 0) {
init2();
mState = MJXq_DATA;
LOG(F("DATA STATE\n"));
} else {
sendPacket(1);
mBindCtr -= 1;
}
break;
case MJXq_DATA:
sendPacket(0);
break;
}
return PACKET_PERIOD;
}
void RFProtocolMJXQ::initTxID(void)
{
u32 id = getControllerID();
u32 lfsr = 0xb2c54a2ful;
for (int i = 0; i < 4; ++i) {
rand32_r(&lfsr, (id & 0xff));
id >>= 8;
}
__PRINT_FUNC__;
// Pump zero bytes for LFSR to diverge more
for (u8 i = 0; i < sizeof(lfsr); ++i)
rand32_r(&lfsr, 0);
if (getProtocolOpt() == FORMAT_E010) {
LOG("PROTOCOL E010\n");
// mTxID must be multiple of 8
mTxID[0] = (lfsr >> 16) & 0xf8;
mTxID[1] = ((lfsr >> 8 ) & 0xf0) | 0x0c;
mTxID[2] = lfsr & 0xf0;
}
else if (getProtocolOpt() == FORMAT_WLH08) {
// mTxID must be multiple of 8
mTxID[0] = (lfsr >> 16) & 0xf8;
mTxID[1] = (lfsr >> 8 ) & 0xff;
mTxID[2] = lfsr & 0xff;
} else {
memcpy(mTxID, TBL_TX_RF_MAP[id % (sizeof(TBL_TX_RF_MAP) / sizeof(TBL_TX_RF_MAP[0]))].txid, sizeof(mTxID));
}
}
int RFProtocolMJXQ::init(u8 bind)
{
__PRINT_FUNC__;
RFProtocol::registerCallback(this);
mPacketCtr = 0;
mCurRFChan = 0;
mBindCtr = BIND_COUNT;
initTxID();
init1();
mState = MJXq_INIT1;
startState(INITIAL_WAIT);
return 0;
}
int RFProtocolMJXQ::close(void)
{
mDev.initialize();
return (mDev.reset() ? 1L : -1L);
}
int RFProtocolMJXQ::reset(void)
{
return close();
}
int RFProtocolMJXQ::getInfo(s8 id, u8 *data)
{
u8 size;
size = RFProtocol::getInfo(id, data);
if (size == 0) {
switch (id) {
case INFO_STATE:
*data = mState;
size = 1;
break;
case INFO_CHANNEL:
*data = mRFChanBufs[mCurRFChan];
size = 1;
break;
case INFO_PACKET_CTR:
size = sizeof(mPacketCtr);
*((u32*)data) = mPacketCtr;
break;
}
}
return size;
}
| [
"pinggusoft@gmail.com"
] | pinggusoft@gmail.com |
8e1e9836bc703d9230b67378c2978b7e1f499e5b | 1e9244edc39d707b8831188f639033ec712282bc | /Hmwk/Homwork Review 1/Gaddis_8thED_Chap3_Prob13_Dollars/main.cpp | 755d42fad3fe2fef40ac20bb31b64cf7e9a58887 | [] | no_license | cmartinez169/MartinezChristian_2019_Summer_CIS17A_46096 | c5d9192afa2a8dbe1df113ff933aa7a24333626a | 99d2a490a0f7538a5c59c3419ee8eea5cb5de882 | refs/heads/master | 2020-06-06T21:04:39.868865 | 2019-06-24T03:01:39 | 2019-06-24T03:01:39 | 192,852,190 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,180 | cpp | /*
* File: main.cpp
* Author: Christian Martinez
* Created on June 21, 2019, 10:41 PM
* Purpose: A program that converts dollar amount to japanese yen and euros
*/
#include <iostream> //library for input output
#include <iomanip> //library to use setprecision for decimals
using namespace std;
//start of program
int main ()
{
const double YEN_PER_DOLLAR = 107.00; //constant varibale for conversion of dollar to Yen
const double EUROS_PER_DOLLAR = 0.88; //constant varibale for conversion of dollar to Euro
double dollars, yen, euros; //variables for inputs
//command to ask for input of dollar amount
cout << "Enter the amount in US Dollars to be converted to Yen and Euros: ";
cin >> dollars;
cout << "\n";
yen = dollars * YEN_PER_DOLLAR; //formula to convert dollars to yen.
euros = dollars * EUROS_PER_DOLLAR; //formula to convert dollars to euros.
cout << setprecision(2) << fixed; //set decimal places to 2
cout << dollars << " US Dollars is " << yen << " Japanese Yen\n\n"; //display to user the amount of yen
cout << dollars << " US Dollars is " << euros << " European Euros\n"; //display to user amount of euros
return 0;
}
| [
"cmartinez169@student.rccd.edu"
] | cmartinez169@student.rccd.edu |
c47417a1ecc49dff8acfcefb31208e339dec7eeb | c7cbc0572106bc378ccb81aaea59f0857ea7e338 | /DV1572/DV1572/trolls_inn/Events/EventHandler.h | b863fe29c06519df72e543b295d955d0b4446899 | [] | no_license | TheFlyingPandaa/ourEngine | def89a2ac6d9e248c9f02575a0e6b8f58825026d | ce69ee55705361a325f316578541d2e790b94582 | refs/heads/master | 2021-04-06T20:49:04.968200 | 2019-03-21T13:32:34 | 2019-03-21T13:32:34 | 125,350,660 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 678 | h | #pragma once
#include <stack>
#include "../AI_Base/Inn.h"
#include "Event.h"
class EventHandler
{
private:
//Events
std::stack<Event*> m_eventStack;
//Info to the events
Inn * m_inn;
RoomCtrl * m_roomCtrl;
//MailMan related
bool m_eventStart = false;
std::vector<std::shared_ptr<Node>> m_pathToInn;
std::vector<std::shared_ptr<Node>> m_pathOutInn;
public:
EventHandler(Inn * inn, RoomCtrl * roomCtrl, std::vector<std::shared_ptr<Node>> firstPath, std::vector<std::shared_ptr<Node>> secondPath);
~EventHandler();
void Update(double deltaTime);
void StartCollectEvent(); //Starts a collection event
void EndEvent(); //only for debug right now
void Draw();
};
| [
"joakim.trossvik@gmail.com"
] | joakim.trossvik@gmail.com |
70ec3adb9aa34420ef9ef6f6c0457a2e56a4062d | 0acb5d83cb8ee2f28f1b438a3da9f3c297d9615f | /src/HBsplines/TreeNode.cpp | c1e6fd4a97fd67b81925cd54669d8bc8bca2dbee | [
"MIT"
] | permissive | chennachaos/mpap | 444cc0ec54aa989dfac42e09762f57e75aa16ffa | bd1f270dd9cb8072eb3afc8dfb1adcc1a78c1495 | refs/heads/master | 2022-01-31T20:46:15.974004 | 2021-10-30T08:29:21 | 2021-10-30T08:29:21 | 221,304,094 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 24,945 | cpp |
#include "TreeNode.h"
#include "GeomDataHBSplines.h"
#include "SolutionData.h"
template <>
bool TreeNode<1>::isBoundary()
{
return (isLeftBoundary() || isRightBoundary() );
}
template <>
bool TreeNode<2>::isBoundary()
{
return (isLeftBoundary() || isRightBoundary() || isBottomBoundary() || isTopBoundary());
}
template <>
bool TreeNode<3>::isBoundary()
{
return (isLeftBoundary() || isRightBoundary() || isBottomBoundary() || isTopBoundary() || isFrontBoundary() || isBackBoundary() );
}
template<>
void TreeNode<1>::subDivide()
{
if( !isLeaf() )
return;
NUM_CHILDREN = 2;
child = new TreeNode_PTR[NUM_CHILDREN];
int ii=0, temp = level+1;
for(ii=0;ii<NUM_CHILDREN;ii++)
{
child[ii] = new TreeNode<1>(temp);
child[ii]->setLocalBFsSize(totnlbf);
child[ii]->setParent(this);
}
if(isGhost())
{
for(ii=0;ii<NUM_CHILDREN;ii++)
child[ii]->setGhostOn();
}
double mid = 0.5*(knotBegin[0] + knotEnd[0]);
TreeNode_PTR tmpnode;
child[LEFT]->orientation = LEFT;
child[RIGHT]->orientation = RIGHT;
//cout << " AAAAAAAAAAAAAA " << endl;
child[LEFT]->setKnots(Dir1, knotBegin[0], mid);
child[RIGHT]->setKnots(Dir1, mid, knotEnd[0]);
// link the children
child[LEFT]->setNeighbour(RIGHT, child[RIGHT]);
child[RIGHT]->setNeighbour(LEFT, child[LEFT]);
if(neighbours[LEFT] != NULL)
{
if(neighbours[LEFT]->isLeaf())
child[LEFT]->setNeighbour(LEFT, NULL);
else
{
tmpnode = neighbours[LEFT]->getChild(RIGHT);
child[LEFT]->setNeighbour(LEFT, tmpnode);
tmpnode->setNeighbour(RIGHT,child[LEFT]);
}
}
if(neighbours[RIGHT] != NULL)
{
if(neighbours[RIGHT]->isLeaf())
child[RIGHT]->setNeighbour(RIGHT, NULL);
else
{
tmpnode = neighbours[RIGHT]->getChild(LEFT);
child[RIGHT]->setNeighbour(RIGHT, tmpnode);
tmpnode->setNeighbour(LEFT,child[RIGHT]);
}
}
return;
}
template<>
void TreeNode<2>::subDivide()
{
if( !isLeaf() )
return;
int ii=0, jj=0, temp = level+1;
NUM_CHILDREN = 4;
child = new TreeNode_PTR[NUM_CHILDREN];
for(ii=0;ii<NUM_CHILDREN;ii++)
{
child[ii] = new TreeNode<2>(temp);
child[ii]->setLocalBFsSize(totnlbf);
child[ii]->setParent(this);
}
//
if(isGhost())
{
for(ii=0;ii<NUM_CHILDREN;ii++)
child[ii]->setGhostOn();
}
//
child[SW]->orientation = SW;
child[SE]->orientation = SE;
child[NW]->orientation = NW;
child[NE]->orientation = NE;
//cout << " child[SW]->orientation " << '\t' << SW << '\t' << child[SW]->orientation << endl;
//cout << " child[SE]->orientation " << '\t' << SE << '\t' << child[SE]->orientation << endl;
//cout << " child[NW]->orientation " << '\t' << NW << '\t' << child[NW]->orientation << endl;
//cout << " child[NE]->orientation " << '\t' << NE << '\t' << child[NE]->orientation << endl;
double midu = 0.5*(knotEnd[0] + knotBegin[0]);
double midv = 0.5*(knotEnd[1] + knotBegin[1]);
child[SW]->setKnots(Dir1, knotBegin[0], midu);
child[SW]->setKnots(Dir2, knotBegin[1], midv);
child[SE]->setKnots(Dir1, midu, knotEnd[0]);
child[SE]->setKnots(Dir2, knotBegin[1], midv);
child[NW]->setKnots(Dir1, knotBegin[0], midu);
child[NW]->setKnots(Dir2, midv, knotEnd[1]);
child[NE]->setKnots(Dir1, midu, knotEnd[0]);
child[NE]->setKnots(Dir2, midv, knotEnd[1]);
child[SW]->setNeighbour(EAST, child[SE]);
child[SW]->setNeighbour(NORTH, child[NW]);
child[SE]->setNeighbour(WEST, child[SW]);
child[SE]->setNeighbour(NORTH, child[NE]);
child[NW]->setNeighbour(EAST, child[NE]);
child[NW]->setNeighbour(SOUTH, child[SW]);
child[NE]->setNeighbour(WEST, child[NW]);
child[NE]->setNeighbour(SOUTH, child[SE]);
TreeNode_PTR tmpnode;
if(neighbours[WEST] != NULL)
{
if(neighbours[WEST]->isLeaf())
{
child[SW]->setNeighbour(WEST, NULL);
child[NW]->setNeighbour(WEST, NULL);
}
else
{
tmpnode = neighbours[WEST]->getChild(SE);
child[SW]->setNeighbour(WEST, tmpnode);
tmpnode->setNeighbour(EAST, child[SW]);
tmpnode = neighbours[WEST]->getChild(NE);
child[NW]->setNeighbour(WEST, tmpnode);
tmpnode->setNeighbour(EAST, child[NW]);
}
}
if(neighbours[EAST] != NULL)
{
if(neighbours[EAST]->isLeaf())
{
child[SE]->setNeighbour(EAST, NULL);
child[NE]->setNeighbour(EAST, NULL);
}
else
{
tmpnode = neighbours[EAST]->getChild(SW);
child[SE]->setNeighbour(EAST, tmpnode);
tmpnode->setNeighbour(WEST, child[SE]);
tmpnode = neighbours[EAST]->getChild(NW);
child[NE]->setNeighbour(EAST, tmpnode);
tmpnode->setNeighbour(WEST, child[NE]);
}
}
if(neighbours[NORTH] != NULL)
{
if(neighbours[NORTH]->isLeaf())
{
child[NW]->setNeighbour(NORTH, NULL);
child[NE]->setNeighbour(NORTH, NULL);
}
else
{
tmpnode = neighbours[NORTH]->getChild(SW);
child[NW]->setNeighbour(NORTH, tmpnode);
tmpnode->setNeighbour(SOUTH, child[NW]);
tmpnode = neighbours[NORTH]->getChild(SE);
child[NE]->setNeighbour(NORTH, tmpnode);
tmpnode->setNeighbour(SOUTH, child[NE]);
}
}
if(neighbours[SOUTH] != NULL)
{
if(neighbours[SOUTH]->isLeaf())
{
child[SW]->setNeighbour(SOUTH, NULL);
child[SE]->setNeighbour(SOUTH, NULL);
}
else
{
tmpnode = neighbours[SOUTH]->getChild(NW);
child[SW]->setNeighbour(SOUTH, tmpnode);
tmpnode->setNeighbour(NORTH, child[SW]);
tmpnode = neighbours[SOUTH]->getChild(NE);
child[SE]->setNeighbour(SOUTH, tmpnode);
tmpnode->setNeighbour(NORTH, child[SE]);
}
}
return;
}
template<>
void TreeNode<3>::subDivide()
{
if( !isLeaf() )
return;
int ii=0, jj=0, temp = level+1;
NUM_CHILDREN = 8;
child = new TreeNode_PTR[NUM_CHILDREN];
for(ii=0;ii<NUM_CHILDREN;ii++)
{
child[ii] = new TreeNode<3>(temp);
child[ii]->setLocalBFsSize(totnlbf);
child[ii]->setParent(this);
}
if(this->isGhost())
{
for(ii=0;ii<NUM_CHILDREN;ii++)
child[ii]->setGhostOn();
}
child[SW_FRONT]->orientation = SW_FRONT;
child[SE_FRONT]->orientation = SE_FRONT;
child[NW_FRONT]->orientation = NW_FRONT;
child[NE_FRONT]->orientation = NE_FRONT;
child[SW_BACK]->orientation = SW_BACK;
child[SE_BACK]->orientation = SE_BACK;
child[NW_BACK]->orientation = NW_BACK;
child[NE_BACK]->orientation = NE_BACK;
///////////////////////////////////////////////
//
// set the knot values
double midu = 0.5*(knotBegin[0] + knotEnd[0]);
double midv = 0.5*(knotBegin[1] + knotEnd[1]);
double midw = 0.5*(knotBegin[2] + knotEnd[2]);
child[SW_BACK ]->setKnots(Dir1, knotBegin[0], midu);
child[SW_FRONT]->setKnots(Dir1, knotBegin[0], midu);
child[NW_BACK ]->setKnots(Dir1, knotBegin[0], midu);
child[NW_FRONT]->setKnots(Dir1, knotBegin[0], midu);
child[SE_BACK ]->setKnots(Dir1, midu, knotEnd[0]);
child[SE_FRONT]->setKnots(Dir1, midu, knotEnd[0]);
child[NE_BACK ]->setKnots(Dir1, midu, knotEnd[0]);
child[NE_FRONT]->setKnots(Dir1, midu, knotEnd[0]);
child[SW_BACK ]->setKnots(Dir2, knotBegin[1], midv);
child[SW_FRONT]->setKnots(Dir2, knotBegin[1], midv);
child[SE_BACK ]->setKnots(Dir2, knotBegin[1], midv);
child[SE_FRONT]->setKnots(Dir2, knotBegin[1], midv);
child[NW_BACK ]->setKnots(Dir2, midv, knotEnd[1]);
child[NW_FRONT]->setKnots(Dir2, midv, knotEnd[1]);
child[NE_BACK ]->setKnots(Dir2, midv, knotEnd[1]);
child[NE_FRONT]->setKnots(Dir2, midv, knotEnd[1]);
child[SW_BACK ]->setKnots(Dir3, knotBegin[2], midw);
child[SE_BACK ]->setKnots(Dir3, knotBegin[2], midw);
child[NW_BACK ]->setKnots(Dir3, knotBegin[2], midw);
child[NE_BACK ]->setKnots(Dir3, knotBegin[2], midw);
child[SW_FRONT]->setKnots(Dir3, midw, knotEnd[2]);
child[SE_FRONT]->setKnots(Dir3, midw, knotEnd[2]);
child[NW_FRONT]->setKnots(Dir3, midw, knotEnd[2]);
child[NE_FRONT]->setKnots(Dir3, midw, knotEnd[2]);
///////////////////////////////////////////////
//
// set the neighbours among the children
child[SW_FRONT]->setNeighbour(EAST, child[SE_FRONT]);
child[SW_FRONT]->setNeighbour(NORTH, child[NW_FRONT]);
child[SW_FRONT]->setNeighbour(BACK, child[SW_BACK]);
child[SE_FRONT]->setNeighbour(WEST, child[SW_FRONT]);
child[SE_FRONT]->setNeighbour(NORTH, child[NE_FRONT]);
child[SE_FRONT]->setNeighbour(BACK, child[SE_BACK]);
child[NW_FRONT]->setNeighbour(EAST, child[NE_FRONT]);
child[NW_FRONT]->setNeighbour(SOUTH, child[SW_FRONT]);
child[NW_FRONT]->setNeighbour(BACK, child[NW_BACK]);
child[NE_FRONT]->setNeighbour(WEST, child[NW_FRONT]);
child[NE_FRONT]->setNeighbour(SOUTH, child[SE_FRONT]);
child[NE_FRONT]->setNeighbour(BACK, child[NE_BACK]);
child[SW_BACK]->setNeighbour(EAST, child[SE_BACK]);
child[SW_BACK]->setNeighbour(NORTH, child[NW_BACK]);
child[SW_BACK]->setNeighbour(FRONT, child[SW_FRONT]);
child[SE_BACK]->setNeighbour(WEST, child[SW_BACK]);
child[SE_BACK]->setNeighbour(NORTH, child[NE_BACK]);
child[SE_BACK]->setNeighbour(FRONT, child[SE_FRONT]);
child[NW_BACK]->setNeighbour(EAST, child[NE_BACK]);
child[NW_BACK]->setNeighbour(SOUTH, child[SW_BACK]);
child[NW_BACK]->setNeighbour(FRONT, child[NW_FRONT]);
child[NE_BACK]->setNeighbour(WEST, child[NW_BACK]);
child[NE_BACK]->setNeighbour(SOUTH, child[SE_BACK]);
child[NE_BACK]->setNeighbour(FRONT, child[NE_FRONT]);
///////////////////////////////////////////////
//
// set the neighbours with the children of neighbours
TreeNode_PTR tmpnode, nd;
nd = neighbours[WEST];
if(nd != NULL)
{
if(nd->isLeaf())
{
child[SW_FRONT]->setNeighbour(WEST, NULL);
child[NW_FRONT]->setNeighbour(WEST, NULL);
child[SW_BACK ]->setNeighbour(WEST, NULL);
child[NW_BACK ]->setNeighbour(WEST, NULL);
}
else
{
tmpnode = nd->getChild(SE_FRONT);
child[SW_FRONT]->setNeighbour(WEST, tmpnode);
tmpnode->setNeighbour(EAST, child[SW_FRONT]);
tmpnode = nd->getChild(NE_FRONT);
child[NW_FRONT]->setNeighbour(WEST, tmpnode);
tmpnode->setNeighbour(EAST, child[NW_FRONT]);
tmpnode = nd->getChild(SE_BACK);
child[SW_BACK]->setNeighbour(WEST, tmpnode);
tmpnode->setNeighbour(EAST, child[SW_BACK]);
tmpnode = nd->getChild(NE_BACK);
child[NW_BACK]->setNeighbour(WEST, tmpnode);
tmpnode->setNeighbour(EAST, child[NW_BACK]);
}
}
nd = neighbours[EAST];
if(nd != NULL)
{
if(nd->isLeaf())
{
child[SE_FRONT]->setNeighbour(EAST, NULL);
child[NE_FRONT]->setNeighbour(EAST, NULL);
child[SE_BACK ]->setNeighbour(EAST, NULL);
child[NE_BACK ]->setNeighbour(EAST, NULL);
}
else
{
tmpnode = nd->getChild(SW_FRONT);
child[SE_FRONT]->setNeighbour(EAST, tmpnode);
tmpnode->setNeighbour(WEST, child[SE_FRONT]);
tmpnode = nd->getChild(NW_FRONT);
child[NE_FRONT]->setNeighbour(EAST, tmpnode);
tmpnode->setNeighbour(WEST, child[NE_FRONT]);
tmpnode = nd->getChild(SW_BACK);
child[SE_BACK]->setNeighbour(EAST, tmpnode);
tmpnode->setNeighbour(WEST, child[SE_BACK]);
tmpnode = nd->getChild(NW_BACK);
child[NE_BACK]->setNeighbour(EAST, tmpnode);
tmpnode->setNeighbour(WEST, child[NE_BACK]);
}
}
nd = neighbours[SOUTH];
if(nd != NULL)
{
if(nd->isLeaf())
{
child[SW_FRONT]->setNeighbour(SOUTH, NULL);
child[SE_FRONT]->setNeighbour(SOUTH, NULL);
child[SW_BACK ]->setNeighbour(SOUTH, NULL);
child[SE_BACK ]->setNeighbour(SOUTH, NULL);
}
else
{
tmpnode = nd->getChild(NW_FRONT);
child[SW_FRONT]->setNeighbour(SOUTH, tmpnode);
tmpnode->setNeighbour(NORTH, child[SW_FRONT]);
tmpnode = nd->getChild(NE_FRONT);
child[SE_FRONT]->setNeighbour(SOUTH, tmpnode);
tmpnode->setNeighbour(NORTH, child[SE_FRONT]);
tmpnode = nd->getChild(NW_BACK);
child[SW_BACK]->setNeighbour(SOUTH, tmpnode);
tmpnode->setNeighbour(NORTH, child[SW_BACK]);
tmpnode = nd->getChild(NE_BACK);
child[SE_BACK]->setNeighbour(SOUTH, tmpnode);
tmpnode->setNeighbour(NORTH, child[SE_BACK]);
}
}
nd = neighbours[NORTH];
if(nd != NULL)
{
if(nd->isLeaf())
{
child[NW_FRONT]->setNeighbour(NORTH, NULL);
child[NE_FRONT]->setNeighbour(NORTH, NULL);
child[NW_BACK ]->setNeighbour(NORTH, NULL);
child[NE_BACK ]->setNeighbour(NORTH, NULL);
}
else
{
tmpnode = nd->getChild(SW_FRONT);
child[NW_FRONT]->setNeighbour(NORTH, tmpnode);
tmpnode->setNeighbour(SOUTH, child[NW_FRONT]);
tmpnode = nd->getChild(SE_FRONT);
child[NE_FRONT]->setNeighbour(NORTH, tmpnode);
tmpnode->setNeighbour(SOUTH, child[NE_FRONT]);
tmpnode = nd->getChild(SW_BACK);
child[NW_BACK]->setNeighbour(NORTH, tmpnode);
tmpnode->setNeighbour(SOUTH, child[NW_BACK]);
tmpnode = nd->getChild(SE_BACK);
child[NE_BACK]->setNeighbour(NORTH, tmpnode);
tmpnode->setNeighbour(SOUTH, child[NE_BACK]);
}
}
nd = neighbours[BACK];
if(nd != NULL)
{
if(nd->isLeaf())
{
child[SW_BACK]->setNeighbour(BACK, NULL);
child[SE_BACK]->setNeighbour(BACK, NULL);
child[NW_BACK]->setNeighbour(BACK, NULL);
child[NE_BACK]->setNeighbour(BACK, NULL);
}
else
{
tmpnode = nd->getChild(SW_FRONT);
child[SW_BACK]->setNeighbour(BACK, tmpnode);
tmpnode->setNeighbour(FRONT, child[SW_BACK]);
tmpnode = nd->getChild(SE_FRONT);
child[SE_BACK]->setNeighbour(BACK, tmpnode);
tmpnode->setNeighbour(FRONT, child[SE_BACK]);
tmpnode = nd->getChild(NW_FRONT);
child[NW_BACK]->setNeighbour(BACK, tmpnode);
tmpnode->setNeighbour(FRONT, child[NW_BACK]);
tmpnode = nd->getChild(NE_FRONT);
child[NE_BACK]->setNeighbour(BACK, tmpnode);
tmpnode->setNeighbour(FRONT, child[NE_BACK]);
}
}
nd = neighbours[FRONT];
if(nd != NULL)
{
if(nd->isLeaf())
{
child[SW_FRONT]->setNeighbour(FRONT, NULL);
child[SE_FRONT]->setNeighbour(FRONT, NULL);
child[NW_FRONT]->setNeighbour(FRONT, NULL);
child[NE_FRONT]->setNeighbour(FRONT, NULL);
}
else
{
tmpnode = nd->getChild(SW_BACK);
child[SW_FRONT]->setNeighbour(FRONT, tmpnode);
tmpnode->setNeighbour(BACK, child[SW_FRONT]);
tmpnode = nd->getChild(SE_BACK);
child[SE_FRONT]->setNeighbour(FRONT, tmpnode);
tmpnode->setNeighbour(BACK, child[SE_FRONT]);
tmpnode = nd->getChild(NW_BACK);
child[NW_FRONT]->setNeighbour(FRONT, tmpnode);
tmpnode->setNeighbour(BACK, child[NW_FRONT]);
tmpnode = nd->getChild(NE_BACK);
child[NE_FRONT]->setNeighbour(FRONT, tmpnode);
tmpnode->setNeighbour(BACK, child[NE_FRONT]);
}
}
return;
}
template<>
void TreeNode<1>::unRefine()
{
if(child == NULL)
{
cout << " This element has no children. So can't unrefine it ... " << endl;
return;
}
int ii=0, jj=0;
TreeNode_PTR tmpnode, nd;
// LEFT side children
tmpnode = child[LEFT]->getNeighbour(LEFT);
if(tmpnode != NULL)
tmpnode->setNeighbour(RIGHT, NULL);
child[LEFT]->setNeighbour(LEFT, NULL);
child[LEFT]->setNeighbour(RIGHT, NULL);
// RIGHT side children
tmpnode = child[RIGHT]->getNeighbour(RIGHT);
if(tmpnode != NULL)
tmpnode->setNeighbour(LEFT, NULL);
child[RIGHT]->setNeighbour(LEFT, NULL);
child[RIGHT]->setNeighbour(RIGHT, NULL);
child[LEFT]->deactivate();
child[RIGHT]->deactivate();
cout << " AAAAAAAAAA " << endl;
return;
}
/*
template<>
bool TreeNode<1>::isGhost()
{
if( (neighbours[RIGHT]) || (neighbours[LEFT] == NULL) )
return true;
TreeNode_PTR ndtmp1, ndtmp2;
ndtmp1 = neighbours[RIGHT];
ndtmp2 = neighbours[LEFT];
for(int ii=0;ii<degree[0]-1;ii++)
{
ndtmp1 = ndtmp1->getNeighbour(RIGHT);
ndtmp2 = ndtmp2->getNeighbour(LEFT);
if( (ndtmp1 == NULL) || (ndtmp2 == NULL) )
{
break;
return true;
}
}
return false;
}
*/
template<>
void TreeNode<1>::printSelf()
{
if(!isGhost())
{
printf("\t ID = %5d\n", id);
printf("\t Level = %5d\n", level);
//printf("\t Degree = %5d\n", degree[0]);
printf("\t Ghost = %5d\n", isGhost());
if(parent == NULL)
printf("\t Parent = %5d\n", -1);
else
printf("\t Parent = %5d\n", parent->getID());
printf("\t children = %5d\n", NUM_CHILDREN);
printf("\t Basis Functions ---> \n");
if( !LocalBasisFuncs.empty() )
{
printf("\t\t");
for(int jj=0;jj<LocalBasisFuncs.size();jj++)
printf("\t%5d\t", LocalBasisFuncs[jj]);
printf("\n");
}
else
printf(" NONE \n");
printf("\t Parameters ... \n");
printf("\t\t direction #%5d ---> \t%12.6f \t %12.6f\n", 1, knotBegin[0], knotEnd[0]);
printf("\n\t Neighbours ... \n");
if(neighbours != NULL)
{
if(neighbours[LEFT] != NULL)
printf("\t\t LEFT neighbour ID = %5d \n", neighbours[LEFT]->getID());
if(neighbours[RIGHT] != NULL)
printf("\t\t RIGHT neighbour ID = %5d \n", neighbours[RIGHT]->getID());
}
else
printf("\t\t No Neighbours \n");
printf("\n\t Children ... \n");
if(child != NULL)
{
if(child[LEFT] != NULL)
printf("\t\t LEFT neighbour ID = %5d \n", child[LEFT]->getID());
if(child[RIGHT] != NULL)
printf("\t\t RIGHT neighbour ID = %5d \n", child[RIGHT]->getID());
}
else
printf("\t\t No Children \n");
printf("\n\n");
}
}
template<>
void TreeNode<2>::printSelf()
{
printf("\t ID = %5d\n", id);
printf("\t Level = %5d\n", level);
//printf("\t Degree = ");
//for(int ii=0;ii<2;ii++)
//printf("%5d\t", degree[ii]);
//printf("\n");
if(parent == NULL)
printf("\t Parent = %5d\n", -1);
else
printf("\t Parent = %5d\n", parent->getID());
printf("\t Basis Functions ---> \n");
if( !LocalBasisFuncs.empty() )
{
printf("\t\t");
for(int jj=0;jj<LocalBasisFuncs.size();jj++)
printf("\t%5d\t", LocalBasisFuncs[jj]);
printf("\n");
}
else
printf(" NONE \n");
printf("\t Parameters ... \n");
for(int ii=0;ii<2;ii++)
{
printf("\t\t direction #%5d ---> \t%12.6f \t %12.6f\n", (ii+1), knotBegin[ii], knotEnd[ii]);
}
printf("\n\t Neighbours ... \n");
if(neighbours != NULL)
{
if(neighbours[EAST] != NULL)
printf("\t\t EAST neighbour ID = %5d \n", neighbours[EAST]->getID());
if(neighbours[WEST] != NULL)
printf("\t\t WEST neighbour ID = %5d \n", neighbours[WEST]->getID());
if(neighbours[NORTH] != NULL)
printf("\t\t NORTH neighbour ID = %5d \n", neighbours[NORTH]->getID());
if(neighbours[SOUTH] != NULL)
printf("\t\t SOUTH neighbour ID = %5d \n", neighbours[SOUTH]->getID());
}
else
printf("\t\t No Neighbours \n\n");
printf("\n\t children ... \n");
if(child != NULL)
{
//printf("\t # of children = %5d\n", NUM_CHILDREN);
if(child[SW] != NULL)
printf("\t\t SW child ID = %5d \n", child[SW]->getID());
if(child[SE] != NULL)
printf("\t\t SE child ID = %5d \n", child[SE]->getID());
if(child[NW] != NULL)
printf("\t\t NW child ID = %5d \n", child[NW]->getID());
if(child[NE] != NULL)
printf("\t\t NE child ID = %5d \n", child[NE]->getID());
}
else
printf("\t\t No children \n");
printf("\n\n");
return;
}
template<>
void TreeNode<3>::printSelf()
{
printf("\t ID = %5d\n", id);
printf("\t Level = %5d\n", level);
//printf("\t Degree = ");
//for(int ii=0;ii<3;ii++)
//printf("%5d\t", degree[ii]);
//printf("\n");
if(parent == NULL)
printf("\t Parent = %5d\n", -1);
else
printf("\t Parent = %5d\n", parent->getID());
printf("\t Basis Functions ---> \n");
if( !LocalBasisFuncs.empty() )
{
printf("\t\t");
for(int jj=0;jj<LocalBasisFuncs.size();jj++)
printf("\t%5d\t", LocalBasisFuncs[jj]);
printf("\n");
}
else
printf(" NONE \n");
printf("\t Parameters ... \n");
for(int ii=0;ii<3;ii++)
{
printf("\t\t direction #%5d ---> \t%12.6f \t %12.6f\n", (ii+1), knotBegin[ii], knotEnd[ii]);
}
printf("\n\t Neighbours ... \n");
if(neighbours != NULL)
{
if(neighbours[WEST] != NULL)
printf("\t\t WEST neighbour ID = %5d \n", neighbours[WEST]->getID());
else
printf("\t\t WEST neighbour ID = %5d \n", -1);
if(neighbours[EAST] != NULL)
printf("\t\t EAST neighbour ID = %5d \n", neighbours[EAST]->getID());
else
printf("\t\t EAST neighbour ID = %5d \n", -1);
if(neighbours[SOUTH] != NULL)
printf("\t\t SOUTH neighbour ID = %5d \n", neighbours[SOUTH]->getID());
else
printf("\t\t SOUTH neighbour ID = %5d \n", -1);
if(neighbours[NORTH] != NULL)
printf("\t\t NORTH neighbour ID = %5d \n", neighbours[NORTH]->getID());
else
printf("\t\t NORTH neighbour ID = %5d \n", -1);
if(neighbours[FRONT] != NULL)
printf("\t\t FRONT neighbour ID = %5d \n", neighbours[FRONT]->getID());
else
printf("\t\t FRONT neighbour ID = %5d \n", -1);
if(neighbours[BACK] != NULL)
printf("\t\t BACK neighbour ID = %5d \n", neighbours[BACK]->getID());
else
printf("\t\t BACK neighbour ID = %5d \n", -1);
}
else
printf("\t\t No Neighbours \n\n");
printf("\n\t children ... \n");
if(child != NULL)
{
//printf("\t # of children = %5d\n", NUM_CHILDREN);
if(child[SW] != NULL)
printf("\t\t SW child ID = %5d \n", child[SW]->getID());
if(child[SE] != NULL)
printf("\t\t SE child ID = %5d \n", child[SE]->getID());
if(child[NW] != NULL)
printf("\t\t NW child ID = %5d \n", child[NW]->getID());
if(child[NE] != NULL)
printf("\t\t NE child ID = %5d \n", child[NE]->getID());
}
else
printf("\t\t No children \n");
printf("\n\n");
return;
}
template<>
bool TreeNode<1>::pointLiesInside(const myPoint& pt)
{
if( (pt[0] >= knotBegin[0]) && (pt[0] <= knotEnd[0]) )
return true;
else
return false;
}
template<>
bool TreeNode<2>::pointLiesInside(const myPoint& pt)
{
if( (pt[0] >= knotBegin[0]) && (pt[0] <= knotEnd[0]) )
{
if( (pt[1] >= knotBegin[1]) && (pt[1] <= knotEnd[1]) )
return true;
else
return false;
}
else
return false;
}
template<>
bool TreeNode<3>::pointLiesInside(const myPoint& pt)
{
if( (pt[0] >= knotBegin[0]) && (pt[0] <= knotEnd[0]) )
{
if( (pt[1] >= knotBegin[1]) && (pt[1] <= knotEnd[1]) )
{
if( (pt[2] >= knotBegin[2]) && (pt[2] <= knotEnd[2]) )
return true;
else
return false;
}
else
return false;
}
else
return false;
}
| [
"thechenna123@gmail.com"
] | thechenna123@gmail.com |
34b29de8edce33e18c940f9357d1a8c90e23ebd1 | 62510fa67d0ca78082109a861b6948206252c885 | /bearpi-hm_nano-oh_flower/00_src/bearpi-hm_nano_oh_fun/test/xts/acts/kernel_lite/sched_posix/src/ProcessSchedApiTest.cpp | d9dd173a46efe6b0884850b961eb8675fc40c001 | [
"Apache-2.0"
] | permissive | dawmlight/vendor_oh_fun | a869e7efb761e54a62f509b25921e019e237219b | bc9fb50920f06cd4c27399f60076f5793043c77d | refs/heads/master | 2023-08-05T09:25:33.485332 | 2021-09-10T10:57:48 | 2021-09-10T10:57:48 | 406,236,565 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 35,568 | cpp | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <unistd.h>
#include <sys/resource.h>
#include <sys/shm.h>
#include <gtest/gtest.h>
#include "log.h"
#include "utils.h"
#include "KernelConstants.h"
#include "mt_utils.h"
using namespace testing::ext;
class ProcessSchedApiTest : public testing::Test {
};
/**
* @tc.number SUB_KERNEL_SCHED_API_GETPRIORITY_0100
* @tc.name getpriority api test.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testGetPriority, Function | MediumTest | Level1)
{
int priority = getpriority(PRIO_PROCESS, INIT_PROCESS_ID);
EXPECT_EQ(priority, DEFAULT_INIT_PROCESS_PRIORITY) << "check 'init' priority failed.";
priority = getpriority(PRIO_PROCESS, KERNEL_PROCESS_ID);
EXPECT_EQ(priority, DEFAULT_KERNEL_PROCESS_PRIORITY) << "check 'KProcess' priority failed.";
}
/**
* @tc.number SUB_KERNEL_SCHED_API_GETPRIORITY_0200
* @tc.name getpriority error test with unsupport parameter 1.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testGetPriorityError0200, Function | MediumTest | Level3)
{
LOG("invalid 'which' test:");
errno = 0;
int priority = getpriority(PRIO_PGRP, 0);
EXPECT_EQ(priority, -1);
EXPECT_EQ(errno, EINVAL);
errno = 0;
priority = getpriority(PRIO_USER, 0);
EXPECT_EQ(priority, -1);
EXPECT_EQ(errno, EINVAL);
}
/**
* @tc.number SUB_KERNEL_SCHED_API_GETPRIORITY_0300
* @tc.name getpriority error test with invalid parameter 1.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testGetPriorityError0300, Function | MediumTest | Level3)
{
int priority;
LOG("invalid 'which' test:");
errno = 0;
priority = getpriority(PRIO_USER + GetRandom(1000), 0);
EXPECT_EQ(priority, -1);
EXPECT_EQ(errno, EINVAL);
errno = 0;
priority = getpriority(-GetRandom(1000), 0);
EXPECT_EQ(priority, -1);
EXPECT_EQ(errno, EINVAL);
}
/**
* @tc.number SUB_KERNEL_SCHED_API_GETPRIORITY_0400
* @tc.name getpriority error test with invalid parameter 2.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testGetPriorityError0400, Function | MediumTest | Level3)
{
int priority;
LOG("invalid 'who' test:");
errno = 0;
priority = getpriority(PRIO_PROCESS, -1);
EXPECT_EQ(priority, -1);
EXPECT_EQ(errno, EINVAL);
errno = 0;
priority = getpriority(PRIO_PROCESS, MAX_PROCESS_NUMBER + 1);
EXPECT_EQ(priority, -1);
EXPECT_EQ(errno, EINVAL);
errno = 0;
priority = getpriority(PRIO_PROCESS, MAX_PROCESS_NUMBER + GetRandom(100000));
EXPECT_EQ(priority, -1);
EXPECT_EQ(errno, EINVAL);
}
/**
* @tc.number SUB_KERNEL_SCHED_API_GETPRIORITY_0500
* @tc.name getpriority error test with not exist parameter 2.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testGetPriorityError0500, Function | MediumTest | Level3)
{
int priority;
LOG("invalid 'who' test:");
LOG("not exist pid test:");
pid_t nonExitPid = GetNonExistPid(); // valid but not exist pid
if (nonExitPid != -1) {
priority = getpriority(PRIO_PROCESS, nonExitPid);
EXPECT_EQ(priority, -1);
EXPECT_EQ(errno, ESRCH);
}
}
void SetPriorityAllTest()
{
int rt, newPrio;
struct sched_param param;
LOG("test pid '0' and cover all supported priority:");
for (int prio = HIGHEST_USER_PROCESS_PRIORITY; prio <= LOWEST_USER_PROCESS_PRIORITY; prio++) {
rt = setpriority(PRIO_PROCESS, 0, prio);
EXPECT_EQ(rt, 0) << "setpriority failed for prio=" << prio << ", errno=" << errno;
newPrio = getpriority(PRIO_PROCESS, 0);
EXPECT_EQ(newPrio, prio);
rt = sched_getparam(getpid(), ¶m);
EXPECT_EQ(rt, 0);
newPrio = param.sched_priority;
EXPECT_EQ(newPrio, prio);
}
LOG("set back to default value:");
rt = setpriority(PRIO_PROCESS, getpid(), DEFAULT_SHELL_PROCESS_PRIORITY);
EXPECT_EQ(rt, 0);
newPrio = getpriority(PRIO_PROCESS, 0);
EXPECT_EQ(newPrio, DEFAULT_SHELL_PROCESS_PRIORITY);
}
/**
* @tc.number SUB_KERNEL_SCHED_API_SETPRIORITY_0100
* @tc.name test setpriority for all supported priority.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSetPriority, Function | MediumTest | Level1)
{
SetPriorityAllTest();
}
/**
* @tc.number SUB_KERNEL_SCHED_API_SETPRIORITY_0200
* @tc.name test setpriority for all supported priority, in RR mode
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSetPriorityFiFo, Function | MediumTest | Level3)
{
LOG("change sched policy");
struct sched_param param;
int rt = sched_getparam(0, ¶m);
ASSERT_EQ(rt, 0) << "get sched param failed, errno=" << errno;
SetPriorityAllTest();
LOG("set back to RR");
rt = sched_setscheduler(0, SCHED_RR, ¶m);
ASSERT_EQ(rt, 0) << "set SCHED_RR failed, errno=" << errno;
}
/**
* @tc.number SUB_KERNEL_SCHED_API_SETPRIORITY_0300
* @tc.name setpriority error test with unsupport parameter 1.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSetPriorityError0300, Function | MediumTest | Level3)
{
const int testPrio = 18;
LOG("invalid 'which' test:");
errno = 0;
int rt = setpriority(PRIO_PGRP, 0, testPrio);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
errno = 0;
rt = setpriority(PRIO_USER, 0, testPrio);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
}
/**
* @tc.number SUB_KERNEL_SCHED_API_SETPRIORITY_0400
* @tc.name setpriority error test with invlid parameter 1.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSetPriorityError0400, Function | MediumTest | Level3)
{
const int testPrio = 18;
int rt;
LOG("invalid 'which' test:");
errno = 0;
rt = setpriority(PRIO_USER + GetRandom(1000), 0, testPrio);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
errno = 0;
rt = setpriority(-GetRandom(1000), 0, testPrio);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
}
/**
* @tc.number SUB_KERNEL_SCHED_API_SETPRIORITY_0500
* @tc.name setpriority error test with invalid parameter 2.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSetPriorityError0500, Function | MediumTest | Level3)
{
int rt;
const int testPrio = 18;
LOG("invalid 'pid' test:");
errno = 0;
rt = setpriority(PRIO_PROCESS, -1, testPrio);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
errno = 0;
rt = setpriority(PRIO_PROCESS, MAX_PROCESS_NUMBER + 1, testPrio);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
errno = 0;
rt = setpriority(PRIO_PROCESS, MAX_PROCESS_NUMBER + GetRandom(1000), testPrio);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
}
/**
* @tc.number SUB_KERNEL_SCHED_API_SETPRIORITY_0600
* @tc.name setpriority error test with not exist parameter 2.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSetPriorityError0600, Function | MediumTest | Level3)
{
const int testPrio = 18;
int rt;
LOG("not exist pid test:");
pid_t nonExitPid = GetNonExistPid(); // valid but not exist pid
if (nonExitPid != -1) {
rt = setpriority(PRIO_PROCESS, nonExitPid, testPrio);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, ESRCH);
}
}
/**
* @tc.number SUB_KERNEL_SCHED_API_SETPRIORITY_0700
* @tc.name setpriority error test with invalid parameter 3.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSetPriorityError0700, Function | MediumTest | Level3)
{
int rt;
LOG("invalid 'priority' test:");
errno = 0;
rt = setpriority(PRIO_PROCESS, 0, -1);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
errno = 0;
rt = setpriority(PRIO_PROCESS, 0, -GetRandom(1000));
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
errno = 0;
rt = setpriority(PRIO_PROCESS, 0, 0);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
errno = 0;
rt = setpriority(PRIO_PROCESS, 0, HIGHEST_USER_PROCESS_PRIORITY - 1);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
LOG("check the default priority not changed:");
int newPrio = getpriority(PRIO_PROCESS, 0);
if (newPrio != DEFAULT_SHELL_PROCESS_PRIORITY) {
rt = setpriority(PRIO_PROCESS, 0, DEFAULT_SHELL_PROCESS_PRIORITY);
EXPECT_EQ(rt, 0);
FAIL() << "setpriority failed but priority has changed";
}
}
/**
* @tc.number SUB_KERNEL_SCHED_API_SETPRIORITY_0800
* @tc.name setpriority error test with no permission.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSetPriorityError0800, Function | MediumTest | Level3)
{
const int testPrio = 18;
int rt;
LOG("no permission test:");
errno = 0;
rt = setpriority(PRIO_PROCESS, INIT_PROCESS_ID, testPrio);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EPERM);
errno = 0;
rt = setpriority(PRIO_PROCESS, KERNEL_PROCESS_ID, testPrio);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EPERM);
}
/**
* @tc.number SUB_KERNEL_SCHED_API_SCHED_GETPARAM_0100
* @tc.name sched_getparam api test.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedGetParam, Function | MediumTest | Level1)
{
struct sched_param param;
int rt = sched_getparam(0, ¶m);
EXPECT_EQ(rt, 0) << "sched_getparam failed, errno=" << errno;
EXPECT_EQ(param.sched_priority, DEFAULT_SHELL_PROCESS_PRIORITY);
rt = sched_getparam(getpid(), ¶m);
EXPECT_EQ(rt, 0) << "sched_getparam failed, errno=" << errno;
EXPECT_EQ(param.sched_priority, DEFAULT_SHELL_PROCESS_PRIORITY);
rt = sched_getparam(INIT_PROCESS_ID, ¶m);
EXPECT_EQ(rt, 0) << "sched_getparam failed, errno=" << errno;
EXPECT_EQ(param.sched_priority, DEFAULT_INIT_PROCESS_PRIORITY);
rt = sched_getparam(KERNEL_PROCESS_ID, ¶m);
EXPECT_EQ(rt, 0) << "sched_getparam failed, errno=" << errno;
EXPECT_EQ(param.sched_priority, DEFAULT_KERNEL_PROCESS_PRIORITY);
}
/**
* @tc.number SUB_KERNEL_SCHED_API_SCHED_GETPARAM_0200
* @tc.name sched_getparam error test with invalid parameter 1.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedGetParamError0200, Function | MediumTest | Level3)
{
struct sched_param param;
LOG("invalid 'pid' test:");
errno = 0;
int rt = sched_getparam(-1, ¶m);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
errno = 0;
rt = sched_getparam(MAX_PROCESS_NUMBER + 1, ¶m);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
errno = 0;
rt = sched_getparam(MAX_PROCESS_NUMBER + GetRandom(100000), ¶m);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
}
/**
* @tc.number SUB_KERNEL_SCHED_API_SCHED_GETPARAM_0300
* @tc.name sched_getparam error test with not exist pid.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedGetParamError0300, Function | MediumTest | Level3)
{
struct sched_param param;
int rt;
LOG("not exist pid test:");
pid_t nonExitPid = GetNonExistPid(); // valid but not exist pid
if (nonExitPid != -1) {
rt = sched_getparam(nonExitPid, ¶m);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, ESRCH);
}
}
/**
* @tc.number SUB_KERNEL_SCHED_API_SCHED_GETPARAM_0400
* @tc.name sched_getparam error test with invalid parameter 2.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedGetParamError0400, Function | MediumTest | Level3)
{
int rt;
LOG("invalid 'param' test:");
rt = sched_getparam(0, NULL);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
}
void SchedSetParamAllTest()
{
int rt, newPrio;
struct sched_param param;
LOG("test all supported priority:");
for (int prio = HIGHEST_USER_PROCESS_PRIORITY; prio <= LOWEST_USER_PROCESS_PRIORITY; prio++) {
param.sched_priority = prio;
rt = sched_setparam(0, ¶m);
EXPECT_EQ(rt, 0) << "sched_setparam failed for prio=" << prio << ", errno=" << errno;
newPrio = getpriority(PRIO_PROCESS, getpid());
EXPECT_EQ(prio, newPrio);
rt = sched_getparam(0, ¶m);
EXPECT_EQ(rt, 0);
EXPECT_EQ(prio, param.sched_priority);
}
LOG("set back to default value:");
param.sched_priority = DEFAULT_SHELL_PROCESS_PRIORITY;
rt = sched_setparam(getpid(), ¶m);
EXPECT_EQ(rt, 0);
newPrio = getpriority(PRIO_PROCESS, 0);
EXPECT_EQ(newPrio, DEFAULT_SHELL_PROCESS_PRIORITY);
}
/**
* @tc.number SUB_KERNEL_SCHED_API_SCHED_SETPARAM_0100
* @tc.name test sched_setparam for all supported priority.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedSetParam, Function | MediumTest | Level1)
{
SchedSetParamAllTest();
}
/**
* @tc.number SUB_KERNEL_SCHED_API_SCHED_SETPARAM_0200
* @tc.name test sched_setparam for all supported priority, in FIFO mode
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedSetParamFiFo, Function | MediumTest | Level3)
{
struct sched_param param;
int rt = sched_getparam(0, ¶m);
ASSERT_EQ(rt, 0) << "get sched param failed, errno=" << errno;
SchedSetParamAllTest();
LOG("set to RR");
rt = sched_setscheduler(0, SCHED_RR, ¶m);
ASSERT_EQ(rt, 0) << "set SCHED_RR failed, errno=" << errno;
}
/**
* @tc.number SUB_KERNEL_SCHED_API_SCHED_SETPARAM_0300
* @tc.name sched_setparam error test with invalid pid.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedSetParamError0300, Function | MediumTest | Level3)
{
int rt;
struct sched_param param;
param.sched_priority = 18;
LOG("invalid 'pid' test:");
errno = 0;
rt = sched_setparam(-1, ¶m);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
errno = 0;
rt = sched_setparam(MAX_PROCESS_NUMBER + 1, ¶m);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
errno = 0;
rt = sched_setparam(MAX_PROCESS_NUMBER + GetRandom(100000), ¶m);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
}
/**
* @tc.number SUB_KERNEL_SCHED_API_SCHED_SETPARAM_0400
* @tc.name sched_setparam error test with not exist pid.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedSetParamError0400, Function | MediumTest | Level3)
{
int rt;
struct sched_param param;
param.sched_priority = 18;
LOG("not exist pid test:");
pid_t nonExitPid = GetNonExistPid(); // valid but not exist pid
if (nonExitPid != -1) {
rt = sched_setparam(nonExitPid, ¶m);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, ESRCH);
}
}
/**
* @tc.number SUB_KERNEL_SCHED_API_SCHED_SETPARAM_0500
* @tc.name sched_setparam error test with invalid parameter 2.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedSetParamError0500, Function | MediumTest | Level3)
{
int rt;
LOG("invalid 'param' test:");
rt = sched_setparam(0, NULL);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
}
/**
* @tc.number SUB_KERNEL_SCHED_API_SCHED_SETPARAM_0600
* @tc.name sched_setparam error test with invalid priority.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedSetParamError0600, Function | MediumTest | Level3)
{
int rt;
struct sched_param param;
param.sched_priority = 18;
LOG("invalid 'priority' test:");
errno = 0;
param.sched_priority = -1;
rt = sched_setparam(0, ¶m);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
errno = 0;
param.sched_priority = -GetRandom(1000);
rt = sched_setparam(0, ¶m);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
errno = 0;
param.sched_priority = 0;
rt = sched_setparam(0, ¶m);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
errno = 0;
param.sched_priority = HIGHEST_USER_PROCESS_PRIORITY - 1;
rt = sched_setparam(0, ¶m);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
LOG("check the default priority not changed:");
int newPrio = getpriority(PRIO_PROCESS, 0);
if (newPrio != DEFAULT_SHELL_PROCESS_PRIORITY) {
rt = setpriority(PRIO_PROCESS, 0, DEFAULT_SHELL_PROCESS_PRIORITY);
EXPECT_EQ(rt, 0);
FAIL() << "sched_setparam failed but priority has changed";
}
}
/**
* @tc.number SUB_KERNEL_SCHED_API_SCHED_SETPARAM_0700
* @tc.name sched_setparam error test with no permission.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedSetParamError0700, Function | MediumTest | Level3)
{
int rt;
struct sched_param param;
param.sched_priority = 18;
LOG("no permission test:");
errno = 0;
rt = sched_setparam(INIT_PROCESS_ID, ¶m);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EPERM);
errno = 0;
rt = sched_setparam(KERNEL_PROCESS_ID, ¶m);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EPERM);
LOG("check the default priority not changed:");
int newPrio = getpriority(PRIO_PROCESS, 0);
if (newPrio != DEFAULT_SHELL_PROCESS_PRIORITY) {
rt = setpriority(PRIO_PROCESS, 0, DEFAULT_SHELL_PROCESS_PRIORITY);
EXPECT_EQ(rt, 0);
FAIL() << "sched_setparam failed but priority has changed";
}
}
/**
* @tc.number SUB_KERNEL_SCHED_API_GET_PRIORITY_MAX_0100
* @tc.name sched_get_priority_max api test.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedGetPriorityMax, Function | MediumTest | Level3)
{
int prio = sched_get_priority_max(SCHED_RR);
EXPECT_EQ(prio, LOWEST_USER_PROCESS_PRIORITY);
}
/**
* @tc.number SUB_KERNEL_SCHED_API_GET_PRIORITY_MAX_0200
* @tc.name sched_get_priority_max api error test with unsupport policy.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedGetPriorityMaxError0200, Function | MediumTest | Level3)
{
// SCHED_RR is 2
int invalidPolicy[] = {SCHED_FIFO, SCHED_OTHER, SCHED_BATCH, SCHED_IDLE, SCHED_DEADLINE, SCHED_RESET_ON_FORK};
int testLoop = sizeof(invalidPolicy)/sizeof(int);
for (int i = 0; i < testLoop; i++) {
errno = 0;
int prio = sched_get_priority_max(invalidPolicy[i]);
EXPECT_EQ(prio, -1) << "sched_get_priority_max ok for policy=" << invalidPolicy[i];
EXPECT_EQ(errno, EINVAL) << "errno check fail for policy=" << invalidPolicy[i];
}
}
/**
* @tc.number SUB_KERNEL_SCHED_API_GET_PRIORITY_MAX_0300
* @tc.name sched_get_priority_max api error test with invalid policy.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedGetPriorityMaxError0300, Function | MediumTest | Level3)
{
// SCHED_RR is 2
int invalidPolicyVal;
int prio;
invalidPolicyVal = -GetRandom(10000);
errno = 0;
prio = sched_get_priority_max(invalidPolicyVal);
EXPECT_EQ(prio, -1) << "sched_get_priority_max ok for policy=" << invalidPolicyVal;
EXPECT_EQ(errno, EINVAL) << "errno check fail for policy=" << invalidPolicyVal;
invalidPolicyVal = GetRandom(10000) + SCHED_DEADLINE;
errno = 0;
prio = sched_get_priority_max(invalidPolicyVal);
EXPECT_EQ(prio, -1) << "sched_get_priority_max ok for policy=" << invalidPolicyVal;
EXPECT_EQ(errno, EINVAL) << "errno check fail for policy=" << invalidPolicyVal;
}
/**
* @tc.number SUB_KERNEL_SCHED_API_GET_PRIORITY_MIN_0100
* @tc.name sched_get_priority_min api test.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedGetPriorityMin, Function | MediumTest | Level3)
{
int prio = sched_get_priority_min(SCHED_RR);
EXPECT_EQ(prio, HIGHEST_USER_PROCESS_PRIORITY);
}
/**
* @tc.number SUB_KERNEL_SCHED_API_GET_PRIORITY_MIN_0200
* @tc.name sched_get_priority_min api error test with unsupport policy.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedGetPriorityMinError0200, Function | MediumTest | Level3)
{
// SCHED_RR is 2
int invalidPolicy[] = {SCHED_FIFO, SCHED_OTHER, SCHED_BATCH, SCHED_IDLE, SCHED_DEADLINE, SCHED_RESET_ON_FORK};
int testLoop = sizeof(invalidPolicy)/sizeof(int);
for (int i = 0; i < testLoop; i++) {
errno = 0;
int prio = sched_get_priority_min(invalidPolicy[i]);
EXPECT_EQ(prio, -1) << "sched_get_priority_min ok for policy=" << invalidPolicy[i];
EXPECT_EQ(errno, EINVAL) << "errno check fail for policy=" << invalidPolicy[i];
}
}
/**
* @tc.number SUB_KERNEL_SCHED_API_GET_PRIORITY_MIN_0300
* @tc.name sched_get_priority_min api error test with invalid policy.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedGetPriorityMinError0300, Function | MediumTest | Level3)
{
int invalidPolicyVal;
int prio;
invalidPolicyVal = -GetRandom(10000);
errno = 0;
prio = sched_get_priority_min(invalidPolicyVal);
EXPECT_EQ(prio, -1) << "sched_get_priority_min ok for policy=" << invalidPolicyVal;
EXPECT_EQ(errno, EINVAL) << "errno check fail for policy=" << invalidPolicyVal;
invalidPolicyVal = GetRandom(10000) + SCHED_DEADLINE;
errno = 0;
prio = sched_get_priority_min(invalidPolicyVal);
EXPECT_EQ(prio, -1) << "sched_get_priority_min ok for policy=" << invalidPolicyVal;
EXPECT_EQ(errno, EINVAL) << "errno check fail for policy=" << invalidPolicyVal;
}
/**
* @tc.number SUB_KERNEL_SCHED_API_GETSCHEDULER_0100
* @tc.name sched_getscheduler api test.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedGetScheduler, Function | MediumTest | Level1)
{
int policy = sched_getscheduler(0);
EXPECT_EQ(policy, SCHED_RR);
policy = sched_getscheduler(getpid());
EXPECT_EQ(policy, SCHED_RR) << "check 'shell' policy failed.";
policy = sched_getscheduler(INIT_PROCESS_ID);
EXPECT_EQ(policy, SCHED_RR) << "check 'init' policy failed.";
policy = sched_getscheduler(KERNEL_PROCESS_ID);
EXPECT_EQ(policy, SCHED_RR) << "check 'KProcess' policy failed.";
}
/**
* @tc.number SUB_KERNEL_SCHED_API_GETSCHEDULER_0200
* @tc.name sched_getscheduler api error test with invalid pid.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedGetSchedulerError0200, Function | MediumTest | Level1)
{
LOG("invalid pid test:");
errno = 0;
int rt = sched_getscheduler(-1);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
errno = 0;
rt = sched_getscheduler(MAX_PROCESS_NUMBER + 1);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
errno = 0;
rt = sched_getscheduler(MAX_PROCESS_NUMBER + GetRandom(1000));
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
}
/**
* @tc.number SUB_KERNEL_SCHED_API_GETSCHEDULER_0300
* @tc.name sched_getscheduler api error test with not exist pid.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedGetSchedulerError0300, Function | MediumTest | Level1)
{
int rt;
errno = 0;
LOG("not exist pid test:");
pid_t nonExitPid = GetNonExistPid(); // valid but not exist pid
if (nonExitPid != -1) {
rt = sched_getscheduler(nonExitPid);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, ESRCH);
}
}
/**
* @tc.number SUB_KERNEL_SCHED_API_SETSCHEDULER_0100
* @tc.name sched_setscheduler api test.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedSetScheduler, Function | MediumTest | Level1)
{
struct sched_param param;
int rt = sched_getparam(0, ¶m);
ASSERT_EQ(rt, 0) << "get sched param failed, errno=" << errno;
LOG("change policy and priority:");
rt = sched_setscheduler(0, SCHED_RR, ¶m);
ASSERT_EQ(rt, 0) << "set RR failed, errno=" << errno;
int policy = sched_getscheduler(0);
EXPECT_EQ(policy, SCHED_RR);
rt = sched_setscheduler(getpid(), SCHED_RR, ¶m);
EXPECT_EQ(rt, 0) << "set RR again failed, errno=" << errno;
policy = sched_getscheduler(0);
EXPECT_EQ(policy, SCHED_RR);
param.sched_priority = LOWEST_USER_PROCESS_PRIORITY;
rt = sched_setscheduler(getpid(), SCHED_RR, ¶m);
EXPECT_EQ(rt, 0) << "set RR again failed, errno=" << errno;
policy = sched_getscheduler(0);
EXPECT_EQ(policy, SCHED_RR);
int newPrio = getpriority(PRIO_PROCESS, 0);
EXPECT_EQ(newPrio, LOWEST_USER_PROCESS_PRIORITY);
LOG("set back to SCHED_RR and default priority:");
param.sched_priority = DEFAULT_SHELL_PROCESS_PRIORITY;
rt = sched_setscheduler(getpid(), SCHED_RR, ¶m);
EXPECT_EQ(rt, 0) << "set back to SCHED_RR failed, errno=" << errno;
policy = sched_getscheduler(0);
EXPECT_EQ(policy, SCHED_RR);
}
/**
* @tc.number SUB_KERNEL_SCHED_API_SETSCHEDULER_0200
* @tc.name sched_setscheduler api error test with invalid pid.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedSetSchedulerError0200, Function | MediumTest | Level1)
{
struct sched_param param;
int rt = sched_getparam(0, ¶m);
ASSERT_EQ(rt, 0) << "get sched param failed, errno=" << errno;
LOG("invalid pid test:");
errno = 0;
rt = sched_setscheduler(-1, SCHED_RR, ¶m);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
errno = 0;
rt = sched_setscheduler(MAX_PROCESS_NUMBER + 1, SCHED_RR, ¶m);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
errno = 0;
rt = sched_setscheduler(MAX_PROCESS_NUMBER + GetRandom(1000), SCHED_RR, ¶m);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
}
/**
* @tc.number SUB_KERNEL_SCHED_API_SETSCHEDULER_0300
* @tc.name sched_setscheduler api error test with not exist pid.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedSetSchedulerError0300, Function | MediumTest | Level1)
{
struct sched_param param;
int rt = sched_getparam(0, ¶m);
ASSERT_EQ(rt, 0) << "get sched param failed, errno=" << errno;
LOG("not exist pid test:");
pid_t nonExitPid = GetNonExistPid(); // valid but not exist pid
if (nonExitPid != -1) {
rt = sched_setscheduler(nonExitPid, SCHED_RR, ¶m);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, ESRCH);
}
}
/**
* @tc.number SUB_KERNEL_SCHED_API_SETSCHEDULER_0400
* @tc.name sched_setscheduler api error test with unsupport policy.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedSetSchedulerError0400, Function | MediumTest | Level1)
{
struct sched_param param;
int rt = sched_getparam(0, ¶m);
ASSERT_EQ(rt, 0) << "get sched param failed, errno=" << errno;
LOG("invalid policy test:");
//and SCHED_RR is 2
int invalidPolicy[] = {SCHED_FIFO, SCHED_OTHER, SCHED_BATCH, SCHED_IDLE, SCHED_DEADLINE, SCHED_RESET_ON_FORK};
int testLoop = sizeof(invalidPolicy)/sizeof(int);
for (int i = 0; i < testLoop; i++) {
errno = 0;
rt = sched_setscheduler(0, invalidPolicy[i], ¶m);
EXPECT_EQ(rt, -1) << "sched_get_priority_min ok for policy=" << invalidPolicy[i];
EXPECT_EQ(errno, EINVAL) << "errno check fail for policy=" << invalidPolicy[i];
}
LOG("check the default priority not changed:");
int policy = sched_getscheduler(0);
if (policy != SCHED_RR) {
rt = sched_setscheduler(0, SCHED_RR, ¶m);
EXPECT_EQ(rt, 0);
FAIL() << "sched_setscheduler failed but policy has changed";
}
}
/**
* @tc.number SUB_KERNEL_SCHED_API_SETSCHEDULER_0500
* @tc.name sched_setscheduler api error test with invalid policy.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedSetSchedulerError0500, Function | MediumTest | Level1)
{
struct sched_param param;
int rt = sched_getparam(0, ¶m);
ASSERT_EQ(rt, 0) << "get sched param failed, errno=" << errno;
LOG("invalid policy test:");
int invalidPolicy = -GetRandom(10000);
errno = 0;
rt = sched_setscheduler(0, invalidPolicy, ¶m);
EXPECT_EQ(rt, -1) << "sched_get_priority_min ok for policy=" << invalidPolicy;
EXPECT_EQ(errno, EINVAL) << "errno check fail for policy=" << invalidPolicy;
invalidPolicy = GetRandom(10000) + SCHED_DEADLINE;
errno = 0;
rt = sched_setscheduler(0, invalidPolicy, ¶m);
EXPECT_EQ(rt, -1) << "sched_get_priority_min ok for policy=" << invalidPolicy;
EXPECT_EQ(errno, EINVAL) << "errno check fail for policy=" << invalidPolicy;
LOG("check the default priority not changed:");
int policy = sched_getscheduler(0);
if (policy != SCHED_RR) {
rt = sched_setscheduler(0, SCHED_RR, ¶m);
EXPECT_EQ(rt, 0);
FAIL() << "sched_setscheduler failed but policy has changed";
}
}
/**
* @tc.number SUB_KERNEL_SCHED_API_SETSCHEDULER_0600
* @tc.name sched_setscheduler api error test with invalid parameter.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedSetSchedulerError0600, Function | MediumTest | Level1)
{
struct sched_param param;
int rt = sched_getparam(0, ¶m);
ASSERT_EQ(rt, 0) << "get sched param failed, errno=" << errno;
LOG("invalid param test:");
rt = sched_setscheduler(0, SCHED_RR, NULL);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
}
/**
* @tc.number SUB_KERNEL_SCHED_API_SETSCHEDULER_0700
* @tc.name sched_setscheduler api error test with no permission.
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedSetSchedulerError0700, Function | MediumTest | Level1)
{
struct sched_param param;
int rt = sched_getparam(0, ¶m);
ASSERT_EQ(rt, 0) << "get sched param failed, errno=" << errno;
LOG("no permission test:");
errno = 0;
rt = sched_setscheduler(INIT_PROCESS_ID, SCHED_RR, ¶m);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EPERM);
errno = 0;
rt = sched_setscheduler(KERNEL_PROCESS_ID, SCHED_RR, ¶m);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EPERM);
}
/**
* @tc.number SUB_KERNEL_SCHED_API_GETRRINTERVAL_0100
* @tc.name sched_rr_get_interval api test
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedRRGetInterval, Function | MediumTest | Level1)
{
struct timespec time1 = {1, 0};
int rt = sched_rr_get_interval(0, &time1);
printf("%llu, %u\n", time1.tv_sec, time1.tv_nsec);
EXPECT_EQ(rt, 0);
EXPECT_EQ(time1.tv_sec, 0);
EXPECT_GE (time1.tv_nsec, DEFAULT_RR_SCHED_INTERVAL);
time1.tv_sec = 1;
time1.tv_nsec = 0;
rt = sched_rr_get_interval(getpid(), &time1);
printf("%llu, %u\n", time1.tv_sec, time1.tv_nsec);
EXPECT_EQ(rt, 0);
EXPECT_EQ(time1.tv_sec, 0);
EXPECT_GE(time1.tv_nsec, DEFAULT_RR_SCHED_INTERVAL);
}
/**
* @tc.number SUB_KERNEL_SCHED_API_GETRRINTERVAL_0200
* @tc.name sched_rr_get_interval error test with invalid pid
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedRRGetIntervalError0200, Function | MediumTest | Level1)
{
struct timespec time1 = {0, 0};
LOG("invalid 'pid' test:");
errno = 0;
int rt = sched_rr_get_interval(-1, &time1);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
errno = 0;
rt = sched_rr_get_interval(MAX_PROCESS_NUMBER + 1, &time1);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
errno = 0;
rt = sched_rr_get_interval(MAX_PROCESS_NUMBER + GetRandom(1000), &time1);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
}
/**
* @tc.number SUB_KERNEL_SCHED_API_GETRRINTERVAL_0300
* @tc.name sched_rr_get_interval error test with not exist pid
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedRRGetIntervalError0300, Function | MediumTest | Level1)
{
struct timespec time1 = {0, 0};
int rt;
LOG("not exist pid test:");
pid_t nonExitPid = GetNonExistPid(); // valid but not exist pid
if (nonExitPid != -1) {
rt = sched_rr_get_interval(nonExitPid, &time1);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, ESRCH);
}
LOG("invalid 'timespec' test:");
rt = sched_rr_get_interval(0, NULL);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
}
/**
* @tc.number SUB_KERNEL_SCHED_API_GETRRINTERVAL_0400
* @tc.name sched_rr_get_interval error test with invalid timespec
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedRRGetIntervalError0400, Function | MediumTest | Level1)
{
int rt;
LOG("invalid 'timespec' test:");
rt = sched_rr_get_interval(0, NULL);
EXPECT_EQ(rt, -1);
EXPECT_EQ(errno, EINVAL);
}
/**
* @tc.number SUB_KERNEL_SCHED_API_YIELD_0100
* @tc.name test sched_yield with two process
* @tc.desc [C- SOFTWARE -0200]
*/
HWTEST_F(ProcessSchedApiTest, testSchedYieldBasic, Function | MediumTest | Level1)
{
int ret;
int cpuCnt = 0;
cpu_set_t oldMask;
CPU_ZERO(&oldMask);
cpuCnt = GetCpuCount();
LOG("GetCpuCount=%d", cpuCnt);
if (cpuCnt > 1) {
ret = FixCurProcessToOneCpu(0, &oldMask);
ASSERT_EQ(ret, 0);
}
ASSERT_EQ(InitPipe(), 0) << "> parent: pipe errno = " << errno;
EXPECT_NE(InitGlobalVariable(), -1);
pid_t pid = fork();
ASSERT_TRUE(pid >= 0) << "> parent: fork errno = " << errno;
if (pid == 0) {
if (cpuCnt > 1) {
ret = FixCurProcessToOneCpu(0, &oldMask);
EXPECT_EQ(ret, 0);
}
// control step 2
BlockOnPipe();
SetGlobalVariable(1);
LOG("222");
exit(0);
}
Msleep(50);
// control step 1
UnBlockPipe();
LOG("111");
EXPECT_EQ(sched_yield(), 0) << "> sched_yield error";
// control step 3
EXPECT_NE(SetGlobalVariable(2), -1);
LOG("333");
// control step 4
WaitProcExitedOK(pid);
EXPECT_EQ(GetGlobalVariable(), 2);
EXPECT_NE(DeleteGlobalVariable(), -1);
if (cpuCnt > 1) {
ret = sched_setaffinity(0, sizeof(oldMask), &oldMask);
ASSERT_EQ(ret, 0);
}
}
| [
"wangcheng@holdiot.com"
] | wangcheng@holdiot.com |
e32503cfbada56bcc43d61e471d2eb9094cb907c | 1e7869d7e1ab45fefb75b573d5ea5aa4b761a38a | /LISTA C/3c for.cpp | 43d81775d8eadd4f935782cc65d6ed225cbab8fb | [
"MIT"
] | permissive | cassiocamargos/C | 07d3814d85d0f71b88b279b24d2ca44a8981adfe | cfb03e6fb2b4788cb3d5fc0a738b0c90f07a47ee | refs/heads/main | 2023-06-15T19:41:19.014996 | 2021-07-13T16:38:18 | 2021-07-13T16:38:18 | 385,670,600 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 738 | cpp | /*
3- A tabuada de um determinado número é uma tabela de produtos deste número com os números de 1 a 9.
Escreva um programa que peça um número ao usuário e imprima a tabuada deste número na tela. Caso o
valor dado seja inválido o programa deve apenas exibir uma mensagem de aviso. Escreva um programa
usando cada estrutura de repetição estudada.
*/
#include<stdio.h>
#include<locale.h>
int main()
{
setlocale(LC_ALL,"");
int c, num, produto;
printf("Entre com o número que deseja calcular a tabuada: ");
scanf("%i", &num);
//c = 1;
//while(c<=10)
for(c=1;c<=10;c++)
{
produto = num * c;
printf("%i x %i = %i\n", num, c, produto);
//c = c + 1;
}
return 0;
}
| [
"70606359+cassiocamargos@users.noreply.github.com"
] | 70606359+cassiocamargos@users.noreply.github.com |
e978af78c3cb99b98544ac562ba5e82955824cb9 | f1ba22226a50fced530f438defeffda012e21cf7 | /Chapter15/IPC_SharedMem/ipc_mmap_2.cpp | aa47ce97e0a27b8261c80f7c7b40adc152afeba7 | [] | no_license | lidongmeng/APUE | 258d8b3b7c3d2491a16ac0f1bb237a22fa66d7f0 | 88a4d5b3466704c1d0a67f52235d8bcabbfc0bb7 | refs/heads/master | 2021-01-09T20:11:27.812547 | 2016-06-30T15:48:31 | 2016-06-30T15:48:31 | 59,926,408 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,458 | cpp | /*************************************************************************
> File Name: ipc_mmap_1.cpp
> Author: lidongmeng
> Mail: lidongmeng@ict.ac.cn
> Created Time: Wed 22 Jun 2016 09:32:58 AM EDT
************************************************************************/
#include <iostream>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <cstring>
using namespace std;
#define ERR_EXIT(m) \
do { \
perror(m); \
exit(EXIT_FAILURE); \
} while (0)
int main(int argc, char ** argv) {
int fd;
int i;
unsigned char * ptr;
if (argc != 4) {
printf("Usage: %s <filename> <filesize> <mmapsize>\n", argv[1]);
exit(0);
}
int filesize = atoi(argv[2]);
int mmapsize = atoi(argv[3]);
fd = open(argv[1], O_RDWR|O_TRUNC|O_CREAT, 0666);
if (fd < 0) ERR_EXIT("open");
lseek(fd, filesize-1, SEEK_SET);
write(fd, " ", 1);
ptr = (unsigned char*)mmap(NULL, mmapsize, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);
if (ptr == MAP_FAILED) ERR_EXIT("mmap");
close(fd);
int pagesize = sysconf(_SC_PAGESIZE);
printf("pagesize:[%d]\n", pagesize);
for (i = 0; i < max(filesize, mmapsize); i += pagesize) {
printf("ptr[%d] = %d\n", i, ptr[i]);
ptr[i] = 1;
printf("ptr[%d] = %d\n", i + pagesize-1, ptr[i+pagesize-1]);
ptr[i+pagesize-1] = 1;
}
printf("ptr[%d] = %d\n", i, ptr[i]);
return 0;
}
| [
"980201793@qq.com"
] | 980201793@qq.com |
af750f8de24d8ac157f78349ad7e3aa2f5f18ae7 | 2abe79a8fcad054e3a0fa427b0d81c068551ef96 | /RSA/RSA.cpp | 3f87e4921a0e148286a7861c3b7252512bd5d773 | [] | no_license | Cvske/cpp_alghs | 21bfb198b9268bec8bf48829de70226eb1c4e558 | 88f7d22b228e04a299ebddf5f343b914b71d8bc0 | refs/heads/master | 2023-06-27T00:54:03.695746 | 2021-07-20T19:50:08 | 2021-07-20T19:50:08 | 255,114,765 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,312 | cpp | #include <iostream>
using namespace std;
long long euklidean(long long e, long long phi)
{
long long x, y, add, restOfMod, restOfTotal;
long long tempPhi, tempE, phi2;
long long rememberIter;
x = 1, y = 0;
tempE = e, tempPhi = phi;
rememberIter = 1;
while (tempPhi != 0)
{
restOfMod = tempE % tempPhi;
restOfTotal = tempE / tempPhi;
add = x + restOfTotal * y;
x = y;
y = add;
tempE = tempPhi;
tempPhi = restOfMod;
rememberIter *= (-1);
}
if (rememberIter < 0) return phi - x;
else return x;
}
unsigned long long squares(unsigned long long index, unsigned long long mod, unsigned long long base)
{
unsigned long long result = 1;
if (index % 2 == 1)
{
index--;
result *= base;
result %= mod;
}
while (index > 0)
{
if (index % 2 == 1)
{
result *= base;
result %= mod;
}
base *= base;
base %= mod;
index /= 2;
}
return result;
}
int main()
{
ios_base::sync_with_stdio(false);
unsigned long long t, publicKey, c, e, x, y;
unsigned long long p, q, result = 1, phi;
unsigned long long n;
cin >> t;
for (int i = 0; i < t; i++)
{
cin >> p >> q >> e >> c;
n = p * q;
phi = (p - 1) * (q - 1);
unsigned long long d = euklidean(e, phi);
//cout << d;
result = squares(d, n, c);
cout << result << endl;
result = 0;
d = 0;
}
return 0;
} | [
"jakubbarr@gmail.com"
] | jakubbarr@gmail.com |
3c827d2b3b9e058dbc95712a507de73f58f892e8 | bbcda48854d6890ad029d5973e011d4784d248d2 | /trunk/win/Source/Includes/QtIncludes/src/gui/kernel/qformlayout.h | 370a90306ea1d1d2297b3a05101c98afa98c6041 | [
"MIT",
"curl",
"LGPL-2.1-or-later",
"BSD-3-Clause",
"BSL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"LGPL-2.1-only",
"Zlib",
"LicenseRef-scancode-unknown",
"LicenseRef-scancode-unknown-license-reference",
"MS-LPL"
] | permissive | dyzmapl/BumpTop | 9c396f876e6a9ace1099b3b32e45612a388943ff | 1329ea41411c7368516b942d19add694af3d602f | refs/heads/master | 2020-12-20T22:42:55.100473 | 2020-01-25T21:00:08 | 2020-01-25T21:00:08 | 236,229,087 | 0 | 0 | Apache-2.0 | 2020-01-25T20:58:59 | 2020-01-25T20:58:58 | null | UTF-8 | C++ | false | false | 5,712 | h | /****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#ifndef QFORMLAYOUT_H
#define QFORMLAYOUT_H
#include <QtGui/QLayout>
QT_BEGIN_HEADER
QT_BEGIN_NAMESPACE
QT_MODULE(Gui)
class QFormLayoutPrivate;
class Q_GUI_EXPORT QFormLayout : public QLayout
{
Q_OBJECT
Q_ENUMS(FormStyle FieldGrowthPolicy RowWrapPolicy ItemRole)
Q_DECLARE_PRIVATE(QFormLayout)
Q_PROPERTY(FieldGrowthPolicy fieldGrowthPolicy READ fieldGrowthPolicy WRITE setFieldGrowthPolicy RESET resetFieldGrowthPolicy)
Q_PROPERTY(RowWrapPolicy rowWrapPolicy READ rowWrapPolicy WRITE setRowWrapPolicy RESET resetRowWrapPolicy)
Q_PROPERTY(Qt::Alignment labelAlignment READ labelAlignment WRITE setLabelAlignment RESET resetLabelAlignment)
Q_PROPERTY(Qt::Alignment formAlignment READ formAlignment WRITE setFormAlignment RESET resetFormAlignment)
Q_PROPERTY(int horizontalSpacing READ horizontalSpacing WRITE setHorizontalSpacing)
Q_PROPERTY(int verticalSpacing READ verticalSpacing WRITE setVerticalSpacing)
public:
enum FieldGrowthPolicy {
FieldsStayAtSizeHint,
ExpandingFieldsGrow,
AllNonFixedFieldsGrow
};
enum RowWrapPolicy {
DontWrapRows,
WrapLongRows,
WrapAllRows
};
enum ItemRole {
LabelRole = 0,
FieldRole = 1,
SpanningRole = 2
};
explicit QFormLayout(QWidget *parent = 0);
~QFormLayout();
void setFieldGrowthPolicy(FieldGrowthPolicy policy);
FieldGrowthPolicy fieldGrowthPolicy() const;
void setRowWrapPolicy(RowWrapPolicy policy);
RowWrapPolicy rowWrapPolicy() const;
void setLabelAlignment(Qt::Alignment alignment);
Qt::Alignment labelAlignment() const;
void setFormAlignment(Qt::Alignment alignment);
Qt::Alignment formAlignment() const;
void setHorizontalSpacing(int spacing);
int horizontalSpacing() const;
void setVerticalSpacing(int spacing);
int verticalSpacing() const;
int spacing() const;
void setSpacing(int);
void addRow(QWidget *label, QWidget *field);
void addRow(QWidget *label, QLayout *field);
void addRow(const QString &labelText, QWidget *field);
void addRow(const QString &labelText, QLayout *field);
void addRow(QWidget *widget);
void addRow(QLayout *layout);
void insertRow(int row, QWidget *label, QWidget *field);
void insertRow(int row, QWidget *label, QLayout *field);
void insertRow(int row, const QString &labelText, QWidget *field);
void insertRow(int row, const QString &labelText, QLayout *field);
void insertRow(int row, QWidget *widget);
void insertRow(int row, QLayout *layout);
void setItem(int row, ItemRole role, QLayoutItem *item);
void setWidget(int row, ItemRole role, QWidget *widget);
void setLayout(int row, ItemRole role, QLayout *layout);
QLayoutItem *itemAt(int row, ItemRole role) const;
void getItemPosition(int index, int *rowPtr, ItemRole *rolePtr) const;
void getWidgetPosition(QWidget *widget, int *rowPtr, ItemRole *rolePtr) const;
void getLayoutPosition(QLayout *layout, int *rowPtr, ItemRole *rolePtr) const;
QWidget *labelForField(QWidget *field) const;
QWidget *labelForField(QLayout *field) const;
// reimplemented from QLayout
void addItem(QLayoutItem *item);
QLayoutItem *itemAt(int index) const;
QLayoutItem *takeAt(int index);
void setGeometry(const QRect &rect);
QSize minimumSize() const;
QSize sizeHint() const;
void invalidate();
bool hasHeightForWidth() const;
int heightForWidth(int width) const;
Qt::Orientations expandingDirections() const;
int count() const;
int rowCount() const;
#if 0
void dump() const;
#endif
private:
void resetFieldGrowthPolicy();
void resetRowWrapPolicy();
void resetLabelAlignment();
void resetFormAlignment();
};
QT_END_NAMESPACE
QT_END_HEADER
#endif
| [
"anandx@google.com"
] | anandx@google.com |
59b181b4d52de693e021f12cc2a7e7716776d8b6 | 83cf262905de55d3705e299dcc87ff94e554f566 | /reference/asr/cpu_asr_grpc.cc | cddd30f72f4146f4f807ac897e0f06db6556add1 | [
"Apache-2.0"
] | permissive | Aarsh2001/speechsquad | 9fed3e4ce980961d115a679e373e82d46a727019 | 2afe8706ea5092884ed900334081315032327e78 | refs/heads/master | 2022-12-27T10:02:14.780889 | 2020-10-06T02:53:48 | 2020-10-06T02:53:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,917 | cc |
/*
* Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "cpu_asr_grpc.h"
#include "wav_reader.h"
#include <chrono>
#include <glog/logging.h>
#include <random>
#include <thread>
#include "kaldi_asr.h"
using grpc::Status;
using grpc::StatusCode;
std::vector<std::string> ExtractWordsFromString(std::string &sentence) {
const std::string ws = " \t\r\n";
std::size_t pos = 0;
std::vector<std::string> words;
while (pos != sentence.size()) {
std::size_t from = sentence.find_first_not_of(ws, pos);
if (from == std::string::npos) {
break;
}
std::size_t to = sentence.find_first_of(ws, from + 1);
if (to == std::string::npos) {
to = sentence.size();
}
words.push_back(sentence.substr(from, to - from));
pos = to;
}
return words;
}
Status ValidateConfig(nj_asr::RecognitionConfig &config, int numchannels,
int bitspersample) {
if (numchannels > 1) {
return Status(StatusCode::INVALID_ARGUMENT,
std::string("Error: channel count must be 1"));
}
if (bitspersample != 8 && bitspersample != 16) {
return Status(StatusCode::INVALID_ARGUMENT,
std::string("Error: bits per sample must be 8 or 16"));
}
if (config.enable_separate_recognition_per_channel()) {
return Status(
StatusCode::INVALID_ARGUMENT,
std::string(
"Error: separate recognition per channel not yet supported"));
}
return Status::OK;
}
ASRServiceImpl::ASRServiceImpl() {
LOG(INFO) << "KALDI CPU ASR coming up...";
const char *kaldi_path = getenv("KALDI_MODEL_PATH");
if (!kaldi_path)
kaldi_path = "/data/models/LibriSpeech";
use_kaldi_cpu_asr_ = true;
kaldi_cpu_asr_ = new KaldiASRContext(kaldi_path);
if (kaldi_cpu_asr_->Initialize() != 0) {
std::cerr << "unable to create Kaldi object\n";
exit(1);
}
}
ASRServiceImpl::~ASRServiceImpl() {
if (use_kaldi_cpu_asr_)
delete kaldi_cpu_asr_;
}
Status ASRServiceImpl::Recognize(ServerContext *context,
const nj_asr::RecognizeRequest *request,
nj_asr::RecognizeResponse *response) {
LOG(INFO) << "ASRService.Recognize called.";
auto start = std::chrono::high_resolution_clock::now();
Status status = Status::OK;
LOG(ERROR) << "Not Implemented";
return Status(StatusCode::INVALID_ARGUMENT,
"Only StreamingRecognize is implemented for Kaldi");
}
void LatticeToString(fst::SymbolTable &word_syms,
const kaldi::CompactLattice &dlat, std::string *out_str) {
kaldi::CompactLattice best_path_clat;
kaldi::CompactLatticeShortestPath(dlat, &best_path_clat);
kaldi::Lattice best_path_lat;
fst::ConvertLattice(best_path_clat, &best_path_lat);
std::vector<int32> alignment;
std::vector<int32> words;
kaldi::LatticeWeight weight;
fst::GetLinearSymbolSequence(best_path_lat, &alignment, &words, &weight);
std::ostringstream oss;
for (size_t i = 0; i < words.size(); i++) {
std::string s = word_syms.Find(words[i]);
if (s == "")
std::cerr << "Word-id " << words[i] << " not in symbol table.";
oss << s << " ";
}
*out_str = std::move(oss.str());
}
Status ASRServiceImpl::StreamingRecognize(
ServerContext *context,
ServerReaderWriter<nj_asr::StreamingRecognizeResponse,
nj_asr::StreamingRecognizeRequest> *stream) {
LOG(INFO) << "ASRService.StreamingRecognize called.";
Status status = Status::OK;
nj_asr::StreamingRecognizeRequest streaming_request;
nj_asr::StreamingRecognitionConfig streaming_config;
nj_asr::RecognitionConfig config;
WavReader s_decoder;
std::string model_name;
std::unique_ptr<kaldi::OnlineNnet2FeaturePipeline> feature_pipeline_;
std::unique_ptr<kaldi::SingleUtteranceNnet3Decoder> decoder_;
if (stream->Read(&streaming_request) == false) {
return Status::OK;
}
// Check that first request has config
if (streaming_request.has_streaming_config() &&
streaming_request.streaming_config().has_config()) {
streaming_config = streaming_request.streaming_config();
config = streaming_config.config();
feature_pipeline_.reset(
new kaldi::OnlineNnet2FeaturePipeline(*kaldi_cpu_asr_->feature_info_));
decoder_.reset(new kaldi::SingleUtteranceNnet3Decoder(
kaldi_cpu_asr_->decoder_opts, kaldi_cpu_asr_->trans_model_,
*kaldi_cpu_asr_->decodable_info_, *kaldi_cpu_asr_->decode_fst_,
&*feature_pipeline_));
decoder_->InitDecoding(0);
} else {
LOG(ERROR) << "Early return" << std::endl;
return Status(StatusCode::INVALID_ARGUMENT,
"Error: First StreamingRecognize request must contain "
"RecognitionConfig");
}
// Handle audio_content requests
AudioFormat format;
bool first_buffer = true;
bool read_header = true;
int count = 0;
while (stream->Read(&streaming_request)) {
const std::string &raw_audio = streaming_request.audio_content();
if (first_buffer) {
// Detect format & populate stream format
status = s_decoder.DetectFormat(raw_audio);
if (!status.ok())
break;
// Check that config is valid
format = s_decoder.GetFormat();
status = ValidateConfig(config, format.numchannels, format.bitspersample);
if (!status.ok()) {
LOG(ERROR) << "Invalid config " << std::endl;
break;
}
first_buffer = false;
}
std::shared_ptr<std::vector<float>> request_buffer =
std::make_shared<std::vector<float>>();
status = s_decoder.GetAudioBuffer(raw_audio, request_buffer, read_header);
read_header = false;
int32 num_samp = request_buffer->size();
kaldi::SubVector<BaseFloat> wave_part(request_buffer->data(), num_samp);
wave_part.Scale(SHRT_MAX);
feature_pipeline_->AcceptWaveform(format.samplerate, wave_part);
count += num_samp;
if (!status.ok()) {
LOG(ERROR) << "Invalid buffer " << std::endl;
break;
}
}
// Decode once we're done
feature_pipeline_->InputFinished();
decoder_->AdvanceDecoding();
decoder_->FinalizeDecoding();
if (decoder_->NumFramesDecoded() > 0) {
kaldi::CompactLattice lat;
std::string final_transcript;
decoder_->GetLattice(true, &lat);
LatticeToString(*kaldi_cpu_asr_->word_syms_, lat, &final_transcript);
float sample_freq =
kaldi_cpu_asr_->feature_info_->mfcc_opts.frame_opts.samp_freq;
auto audio_processed = (float)count / sample_freq;
nj_asr::StreamingRecognizeResponse response;
auto result = response.add_results();
result->set_is_final(true);
result->set_channel_tag(1);
result->set_audio_processed(audio_processed);
auto alternative = result->add_alternatives();
alternative->set_transcript(final_transcript);
alternative->set_confidence(1.0);
float server_latency = 0;
{
std::unique_lock<std::mutex> lock(this->mu_);
context->AddTrailingMetadata(
"tracing.server_latency.streaming_recognition",
std::to_string(server_latency));
stream->Write(response);
}
}
if (!status.ok()) {
LOG(ERROR) << status.error_message();
LOG(ERROR) << "Early return" << std::endl;
return status;
}
LOG(INFO) << "ASRService.StreamingRecognize returning OK";
return Status::OK;
}
| [
"rleary@nvidia.com"
] | rleary@nvidia.com |
e32b5b6b7b397933e082f57c7cf3f3737e139efc | 7f79f35cfb3ef97cd8caeb6ba94bb8d92152ed75 | /Denas_Kinderis_IF160009_OOP_LD1/stdafx.cpp | 3690558c57443f3aa80c353bd83f70bfe2ad0924 | [] | no_license | SorrowMmussy/Denas_Kinderis_IF160009_OOP_LD1 | 6f0876c472fa4d1fa5fb88f9cfcaaa15b6ddd8ab | 34186561793f57fbc87773b3d1ad2b06d91cf842 | refs/heads/master | 2021-01-12T00:41:34.015955 | 2017-02-08T07:07:43 | 2017-02-08T07:07:43 | 81,299,149 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 310 | cpp | // stdafx.cpp : source file that includes just the standard includes
// Denas_Kinderis_IF160009_OOP_LD1.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"if160009@VDUIF-501-05"
] | if160009@VDUIF-501-05 |
602c5be08ca27b8b5fa9f67456fa396977faa5ff | 3350e3895efd37df101e607c6f381963db771e40 | /include/dll/layer_traits.hpp | 9992ea5a8a0b3b4df323ca6e4c53c3c5ad503f27 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | violettomsk/dll | 3eba4e14aebfb7bd674cb47d22a8b8a0523802fa | a648fed6a52f5cf866b7722c052dea5bfb71b8dd | refs/heads/master | 2020-06-16T22:06:06.338454 | 2016-11-24T07:09:24 | 2016-11-24T07:09:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,976 | hpp | //=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include "util/tmp.hpp"
#include "layer_fwd.hpp"
#include "base_conf.hpp"
namespace dll {
/*!
* \brief Type Traits to get information on layer type
*/
template <typename Layer>
struct layer_traits {
using layer_t = Layer; ///< The layer type being inspected
/*!
* \brief Indicates if the layer is neural (dense or conv)
*/
static constexpr bool is_neural_layer() {
return is_dense_layer() || is_convolutional_layer();
}
/*!
* \brief Indicates if the layer is dense
*/
static constexpr bool is_dense_layer() {
return is_standard_dense_layer() || is_dense_rbm_layer();
}
/*!
* \brief Indicates if the layer is convolutional
*/
static constexpr bool is_convolutional_layer() {
return is_standard_convolutional_layer() || is_convolutional_rbm_layer();
}
/*!
* \brief Indicates if the layer is a standard (non-rbm) layer.
*/
static constexpr bool is_standard_layer() {
return is_standard_dense_layer() || is_standard_convolutional_layer();
}
/*!
* \brief Indicates if the layer is a standard (non-rbm) dense layer.
*/
static constexpr bool is_standard_dense_layer() {
return cpp::is_specialization_of<dense_layer, layer_t>::value
|| cpp::is_specialization_of<dyn_dense_layer, layer_t>::value;
}
/*!
* \brief Indicates if the layer is a standard (non-rbm) convolutionl layer.
*/
static constexpr bool is_standard_convolutional_layer() {
return cpp::is_specialization_of<conv_layer, layer_t>::value
|| cpp::is_specialization_of<dyn_conv_layer, layer_t>::value;
}
/*!
* \brief Indicates if this layer is a RBM layer.
*/
static constexpr bool is_rbm_layer() {
return is_dense_rbm_layer() || is_convolutional_rbm_layer();
}
/*!
* \brief Indicates if this layer is a dense RBM layer.
*/
static constexpr bool is_dense_rbm_layer() {
return cpp::is_specialization_of<dyn_rbm, layer_t>::value
|| cpp::is_specialization_of<rbm, layer_t>::value;
}
/*!
* \brief Indicates if the layer is convolutional
*/
static constexpr bool is_convolutional_rbm_layer() {
return cpp::is_specialization_of<conv_rbm, layer_t>::value
|| cpp::is_specialization_of<conv_rbm_mp, layer_t>::value
|| cpp::is_specialization_of<dyn_conv_rbm, layer_t>::value
|| cpp::is_specialization_of<dyn_conv_rbm_mp, layer_t>::value;
}
/*!
* \brief Indicates if this layer is a pooling layer.
*/
static constexpr bool is_pooling_layer() {
return cpp::is_specialization_of<mp_layer_3d, layer_t>::value
|| cpp::is_specialization_of<dyn_mp_layer_3d, layer_t>::value
|| cpp::is_specialization_of<avgp_layer_3d, layer_t>::value
|| cpp::is_specialization_of<dyn_avgp_layer_3d, layer_t>::value;
}
/*!
* \brief Indicates if this layer is a max pooling layer.
*/
static constexpr bool is_max_pooling_layer() {
return cpp::is_specialization_of<mp_layer_3d, layer_t>::value
|| cpp::is_specialization_of<dyn_mp_layer_3d, layer_t>::value;
}
/*!
* \brief Indicates if this layer is a avg pooling layer.
*/
static constexpr bool is_avg_pooling_layer() {
return cpp::is_specialization_of<avgp_layer_3d, layer_t>::value
|| cpp::is_specialization_of<dyn_avgp_layer_3d, layer_t>::value;
}
/*!
* \brief Indicates if this layer is a transformation layer.
*/
static constexpr bool is_transform_layer() {
return cpp::is_specialization_of<binarize_layer, layer_t>::value
|| cpp::is_specialization_of<normalize_layer, layer_t>::value
|| cpp::is_specialization_of<scale_layer, layer_t>::value
|| cpp::is_specialization_of<rectifier_layer, layer_t>::value
|| cpp::is_specialization_of<random_layer, layer_t>::value
|| cpp::is_specialization_of<lcn_layer, layer_t>::value
|| cpp::is_specialization_of<dyn_lcn_layer, layer_t>::value
;
}
/*!
* \brief Indicates if this layer is a patches layer.
*/
static constexpr bool is_patches_layer() {
return cpp::is_specialization_of<patches_layer, layer_t>::value
|| cpp::is_specialization_of<dyn_patches_layer, layer_t>::value
|| cpp::is_specialization_of<patches_layer_padh, layer_t>::value
|| cpp::is_specialization_of<dyn_patches_layer_padh, layer_t>::value
;
}
/*!
* \brief Indicates if this layer is an augmentation layer.
*/
static constexpr bool is_augment_layer() {
return cpp::is_specialization_of<augment_layer, layer_t>::value;
}
/*!
* \brief Indicates if this layer is a multipley layer.
*/
static constexpr bool is_multiplex_layer() {
return is_augment_layer() || is_patches_layer();
}
/*!
* \brief Indicates if this layer keeps the same type
*/
static constexpr bool has_same_type() {
return is_transform_layer() || is_augment_layer();
}
/*!
* \brief Indicates if this layer is trained or not.
*/
static constexpr bool is_trained() {
return !is_transform_layer() && !is_multiplex_layer() && !is_augment_layer() && !is_pooling_layer();
}
/*!
* \brief Indicates if this layer is pretrained or not.
*/
static constexpr bool is_pretrained() {
return is_rbm_layer();
}
/*!
* \brief Indicates if the layer is dynamic
*/
static constexpr bool is_dynamic() {
return cpp::is_specialization_of<dyn_rbm, layer_t>::value
|| cpp::is_specialization_of<dyn_conv_rbm, layer_t>::value
|| cpp::is_specialization_of<dyn_conv_rbm_mp, layer_t>::value
|| cpp::is_specialization_of<dyn_dense_layer, layer_t>::value
|| cpp::is_specialization_of<dyn_conv_layer, layer_t>::value
|| cpp::is_specialization_of<dyn_mp_layer_3d, layer_t>::value
|| cpp::is_specialization_of<dyn_avgp_layer_3d, layer_t>::value
|| cpp::is_specialization_of<dyn_lcn_layer, layer_t>::value
|| cpp::is_specialization_of<dyn_patches_layer, layer_t>::value
|| cpp::is_specialization_of<dyn_patches_layer_padh, layer_t>::value
;
}
/*!
* \brief Indicates if the layer is convolutional and has probabilistic max
* pooling
*/
static constexpr bool has_probabilistic_max_pooling() {
return cpp::is_specialization_of<conv_rbm_mp, layer_t>::value;
}
/*!
* \brief Indicates if this layer should be trained if it is the last layer.
*/
template <cpp_enable_if_cst(layer_traits<layer_t>::is_rbm_layer())>
static constexpr bool pretrain_last() {
//Softmax unit should not be pretrained
return layer_t::hidden_unit != unit_type::SOFTMAX;
}
template <cpp_disable_if_cst(layer_traits<layer_t>::is_rbm_layer())>
static constexpr bool pretrain_last() {
//if the pooling layer is the last, we spare the time to activate the previous layer by not training it
//since training pooling layer is a nop, that doesn't change anything
return false;
}
static constexpr std::size_t input_size() {
return layer_t::input_size();
}
static constexpr std::size_t output_size() {
return layer_t::output_size();
}
static constexpr std::size_t batch_size() {
return detail::get_value_l<dll::batch_size<1>, typename layer_t::desc::parameters>::value;
}
static constexpr bool has_momentum() {
return layer_t::desc::parameters::template contains<momentum>();
}
static constexpr bool is_parallel_mode() {
return layer_t::desc::parameters::template contains<parallel_mode>();
}
static constexpr bool is_serial() {
return layer_t::desc::parameters::template contains<serial>();
}
static constexpr bool is_verbose() {
return layer_t::desc::parameters::template contains<verbose>();
}
static constexpr bool has_shuffle() {
return layer_t::desc::parameters::template contains<shuffle>();
}
static constexpr bool is_dbn_only() {
return layer_t::desc::parameters::template contains<dbn_only>();
}
static constexpr bool has_sparsity() {
return sparsity_method() != dll::sparsity_method::NONE;
}
static constexpr dll::sparsity_method sparsity_method() {
return detail::get_value_l<sparsity<dll::sparsity_method::NONE>, typename layer_t::desc::parameters>::value;
}
static constexpr enum dll::bias_mode bias_mode() {
return detail::get_value_l<bias<dll::bias_mode::SIMPLE>, typename layer_t::desc::parameters>::value;
}
static constexpr decay_type decay() {
return detail::get_value_l<weight_decay<decay_type::NONE>, typename layer_t::desc::parameters>::value;
}
static constexpr bool init_weights() {
return layer_t::desc::parameters::template contains<dll::init_weights>();
}
static constexpr bool free_energy() {
return layer_t::desc::parameters::template contains<dll::free_energy>();
}
};
template <typename T>
using decay_layer_traits = layer_traits<std::decay_t<T>>;
template <typename RBM, cpp_enable_if(layer_traits<RBM>::is_dynamic())>
std::size_t get_batch_size(const RBM& rbm) {
return rbm.batch_size;
}
template <typename RBM, cpp_disable_if(layer_traits<RBM>::is_dynamic())>
constexpr std::size_t get_batch_size(const RBM&) {
return layer_traits<RBM>::batch_size();
}
template <typename RBM, cpp_enable_if(layer_traits<RBM>::is_dynamic())>
std::size_t get_nc(const RBM& rbm) {
return rbm.nc;
}
template <typename RBM, cpp_disable_if(layer_traits<RBM>::is_dynamic())>
constexpr std::size_t get_nc(const RBM&) {
return RBM::NC;
}
template <typename RBM, cpp_enable_if(layer_traits<RBM>::is_dynamic())>
std::size_t get_k(const RBM& rbm) {
return rbm.k;
}
template <typename RBM, cpp_disable_if(layer_traits<RBM>::is_dynamic())>
constexpr std::size_t get_k(const RBM&) {
return RBM::K;
}
template <typename RBM, cpp_enable_if(layer_traits<RBM>::is_dynamic())>
std::size_t get_nv1(const RBM& rbm) {
return rbm.nv1;
}
template <typename RBM, cpp_disable_if(layer_traits<RBM>::is_dynamic())>
constexpr std::size_t get_nv1(const RBM&) {
return RBM::NV1;
}
template <typename RBM, cpp_enable_if(layer_traits<RBM>::is_dynamic())>
std::size_t get_nv2(const RBM& rbm) {
return rbm.nv2;
}
template <typename RBM, cpp_disable_if(layer_traits<RBM>::is_dynamic())>
constexpr std::size_t get_nv2(const RBM&) {
return RBM::NV2;
}
template <typename RBM, cpp_enable_if(layer_traits<RBM>::is_dynamic())>
std::size_t get_nw1(const RBM& rbm) {
return rbm.nw1;
}
template <typename RBM, cpp_disable_if(layer_traits<RBM>::is_dynamic())>
constexpr std::size_t get_nw1(const RBM&) {
return RBM::NW1;
}
template <typename RBM, cpp_enable_if(layer_traits<RBM>::is_dynamic())>
std::size_t get_nw2(const RBM& rbm) {
return rbm.nw2;
}
template <typename RBM, cpp_disable_if(layer_traits<RBM>::is_dynamic())>
constexpr std::size_t get_nw2(const RBM&) {
return RBM::NW2;
}
template <typename RBM, cpp_enable_if(layer_traits<RBM>::is_dynamic())>
std::size_t num_visible(const RBM& rbm) {
return rbm.num_visible;
}
template <typename RBM, cpp_disable_if(layer_traits<RBM>::is_dynamic())>
constexpr std::size_t num_visible(const RBM&) {
return RBM::desc::num_visible;
}
template <typename RBM, cpp_enable_if(layer_traits<RBM>::is_dynamic())>
std::size_t num_hidden(const RBM& rbm) {
return rbm.num_hidden;
}
template <typename RBM, cpp_disable_if(layer_traits<RBM>::is_dynamic())>
constexpr std::size_t num_hidden(const RBM&) {
return RBM::desc::num_hidden;
}
template <typename RBM, cpp_disable_if(layer_traits<RBM>::is_dynamic())>
constexpr std::size_t output_size(const RBM&) {
return layer_traits<RBM>::output_size();
}
template <typename RBM, cpp_enable_if(layer_traits<RBM>::is_dynamic())>
std::size_t output_size(const RBM& rbm) {
return rbm.output_size();
}
template <typename RBM, cpp_enable_if(layer_traits<RBM>::is_dynamic())>
std::size_t input_size(const RBM& rbm) {
return rbm.input_size();
}
template <typename RBM, cpp_disable_if(layer_traits<RBM>::is_dynamic())>
constexpr std::size_t input_size(const RBM&) {
return layer_traits<RBM>::input_size();
}
} //end of dll namespace
| [
"baptiste.wicht@gmail.com"
] | baptiste.wicht@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.