commit
stringlengths 40
40
| old_file
stringlengths 2
205
| new_file
stringlengths 2
205
| old_contents
stringlengths 0
32.9k
| new_contents
stringlengths 1
38.9k
| subject
stringlengths 3
9.4k
| message
stringlengths 6
9.84k
| lang
stringlengths 3
13
| license
stringclasses 13
values | repos
stringlengths 6
115k
|
|---|---|---|---|---|---|---|---|---|---|
688c59a56a242a7201630776f4b0103df06f95ef
|
firmware/ncd_gateway.cpp
|
firmware/ncd_gateway.cpp
|
#include "ncd_gateway.h"
#include "S3B.h"
#include "spark_wiring_eeprom.h"
S3B sModule;
String eventReturns[5];
unsigned long tOut = 3000;
//int s3b(JsonObject& root);
void init_gateway(){
Particle.function("deviceComm", gatewayCommand);
Particle.subscribe("ncd_deviceCom", commandHandler, MY_DEVICES);
Serial1.begin(115200);
Wire.begin();
}
int gatewayCommand(String arg){
int length = arg.length();
byte bytes[length+1];
arg.getBytes(bytes, length+1);
int newLen = (length/2)+1;
byte newBytes[newLen];
int ind = 0;
for(int i=0;i<length;i+=2){
if(i>0){
ind=i/2;
}
int b1=(bytes[i]-32) << 4;
int b2=bytes[i+1]-32;
newBytes[ind]=b1+b2;
}
//send int pointer for setting to allow me to test how to return results?
return ncdApi(newBytes);
}
void commandHandler(const char *event, const char *data){
Serial.println("Got Event "+String(event));
String newCommand = String(data);
gatewayCommand(newCommand);
}
int ncdApi(byte packetBytes[]){
int buffLen = 1;
Serial.println(String(packetBytes[0]));
switch(packetBytes[0]){
case 187:
{
//packet of packets
int i=2;
int max;
for(int pn = 0; pn<packetBytes[1]; pn++){
max=i+packetBytes[i];
Serial.println(max);
byte intPacket[packetBytes[i]];
i++;
int ni=0;
for(i;i<=max;i++){
intPacket[ni]=packetBytes[i];
ni++;
}
ncdApi(intPacket);
}
break;
}
case 188:
{
//plain i2c w/r command
if(packetBytes[3] > 0){
buffLen = packetBytes[3];
}
byte buff[buffLen];
i2c_command(packetBytes, buff);
break;
}
case 189:
{
//masking command
int addr = packetBytes[1];
int maskOp = packetBytes[2];
int maskedOffsets = packetBytes[3];
int readCommandLen = packetBytes[4];
int readLen = packetBytes[5];
int readCommand[readCommandLen];
array_slice(packetBytes, 6, readCommandLen, readCommand);
int writeCommandLen = packetBytes[6+readCommandLen];
int writeCommand[writeCommandLen];
array_slice(packetBytes, 7+readCommandLen, writeCommandLen, writeCommand);
int writeVals[writeCommandLen];
int wi=0;
for(wi; wi<maskedOffsets; wi++){
writeVals[wi]=writeCommand[wi];
Serial.println(writeVals[wi]);
}
writeCommandsI2C(addr, readCommand, readCommandLen);
Wire.requestFrom(addr, readLen);
for(int i=0;i<readLen;i++){
int current = Wire.read();
writeVals[wi] = mask(current, writeCommand[wi], maskOp);
Serial.println(current);
Serial.println(writeVals[wi]);
wi++;
}
writeCommandsI2C(addr, writeVals, writeCommandLen);
break;
}
}
return 1;
}
int mask(int val, int mask, int type){
switch(type){
case 0:
val |= mask;
break;
case 1:
val &= mask;
break;
case 2:
val ^= mask;
break;
case 3:
val = val << mask;
break;
case 4:
val = val >> mask;
}
return val;
}
void i2c_command(byte bytes[], byte *buff){
if(bytes[0] == 188){
int commands[bytes[2]];
array_slice(bytes, 4, bytes[2], commands);
int addr = bytes[1];
if(bytes[3] == 0){
//write command
buff[0]=writeCommandsI2C(addr, commands, bytes[2]);
}else{
//read command
writeCommandsI2C(addr, commands, bytes[2]);
Wire.requestFrom(addr, bytes[3]);
for(int i=0;i<bytes[3];i++){
buff[i] = Wire.read();
}
}
}
}
void array_slice(byte bytes[], int start, int len, byte *buff){
int ni = 0;
int end = start+len;
for(int i=start; i<=end; i++){
buff[ni] = bytes[i];
ni++;
}
}
void array_slice(byte bytes[], int start, int len, int *buff){
int ni=0;
int end = start+len;
for(int i=start; i<=end; i++){
buff[ni] = bytes[i];
ni++;
}
}
int sendEvent(String key){
int i = key.toInt();
String eventName = "";
eventName = "eventReturn_"+key;
Particle.publish(eventName, eventReturns[i], 60, PRIVATE);
eventReturns[i] = "";
return 1;
};
int setEventReturn(String value){
int index = 0;
while(eventReturns[index].length() > 1){
index++;
}
eventReturns[index] = value;
return index;
};
int writeCommandsI2C(int addr, int* commands, int commandsLen){
Serial.printf("Running I2C Command, address: %i data: ",addr);
Wire.beginTransmission(addr);
for(int i = 0; i < commandsLen; i++){
Wire.write(commands[i]);
Serial.printf("%i, ",commands[i]);
}
int status = Wire.endTransmission();
Serial.printf(" Status: %i \n", status);
return status;
};
|
#include "ncd_gateway.h"
#include "S3B.h"
#include "spark_wiring_eeprom.h"
S3B sModule;
String eventReturns[5];
unsigned long tOut = 3000;
//int s3b(JsonObject& root);
void init_gateway(){
Particle.function("deviceComm", gatewayCommand);
Particle.subscribe("ncd_deviceCom", commandHandler, MY_DEVICES);
Serial1.begin(115200);
Wire.begin();
}
int gatewayCommand(String arg){
int length = arg.length();
byte bytes[length+1];
arg.getBytes(bytes, length+1);
int newLen = (length/2)+1;
byte newBytes[newLen];
int ind = 0;
for(int i=0;i<length;i+=2){
if(i>0){
ind=i/2;
}
int b1=(bytes[i]-32) << 4;
int b2=bytes[i+1]-32;
newBytes[ind]=b1+b2;
}
//send int pointer for setting to allow me to test how to return results?
return ncdApi(newBytes);
}
void commandHandler(const char *event, const char *data){
Serial.println("Got Event "+String(event));
String newCommand = String(data);
gatewayCommand(newCommand);
}
int ncdApi(byte packetBytes[]){
int buffLen = 1;
Serial.println(String(packetBytes[0]));
switch(packetBytes[0]){
case 187:
{
//packet of packets
int i=2;
int max;
for(int pn = 0; pn<packetBytes[1]; pn++){
max=i+packetBytes[i];
Serial.println(max);
byte intPacket[packetBytes[i]];
i++;
int ni=0;
for(i;i<=max;i++){
intPacket[ni]=packetBytes[i];
ni++;
}
ncdApi(intPacket);
}
break;
}
case 188:
{
//plain i2c w/r command
if(packetBytes[3] > 0){
buffLen = packetBytes[3];
}
byte buff[buffLen];
i2c_command(packetBytes, buff);
break;
}
case 189:
{
//masking command
int addr = packetBytes[1];
int maskOp = packetBytes[2];
int maskedOffsets = packetBytes[3];
int readCommandLen = packetBytes[4];
int readLen = packetBytes[5];
int readCommand[readCommandLen];
array_slice(packetBytes, 6, readCommandLen, readCommand);
int writeCommandLen = packetBytes[6+readCommandLen];
int writeCommand[writeCommandLen];
array_slice(packetBytes, 7+readCommandLen, writeCommandLen, writeCommand);
int writeVals[writeCommandLen];
int wi=0;
for(wi; wi<maskedOffsets; wi++){
writeVals[wi]=writeCommand[wi];
Serial.println(writeVals[wi]);
}
writeCommandsI2C(addr, readCommand, readCommandLen);
Wire.requestFrom(addr, readLen);
for(int i=0;i<readLen;i++){
int current = Wire.read();
writeVals[wi] = mask(current, writeCommand[wi], maskOp);
Serial.println(current);
Serial.println(writeVals[wi]);
wi++;
}
writeCommandsI2C(addr, writeVals, writeCommandLen);
break;
}
}
return 1;
}
int mask(int val, int mask, int type){
switch(type){
case 0:
val |= mask;
break;
case 1:
val &= mask;
break;
case 2:
val ^= mask;
break;
case 3:
val &= ~mask;
case 4:
val = val << mask;
break;
case 5:
val = val >> mask;
}
return val;
}
void i2c_command(byte bytes[], byte *buff){
if(bytes[0] == 188){
int commands[bytes[2]];
array_slice(bytes, 4, bytes[2], commands);
int addr = bytes[1];
if(bytes[3] == 0){
//write command
buff[0]=writeCommandsI2C(addr, commands, bytes[2]);
}else{
//read command
writeCommandsI2C(addr, commands, bytes[2]);
Wire.requestFrom(addr, bytes[3]);
for(int i=0;i<bytes[3];i++){
buff[i] = Wire.read();
}
}
}
}
void array_slice(byte bytes[], int start, int len, byte *buff){
int ni = 0;
int end = start+len;
for(int i=start; i<=end; i++){
buff[ni] = bytes[i];
ni++;
}
}
void array_slice(byte bytes[], int start, int len, int *buff){
int ni=0;
int end = start+len;
for(int i=start; i<=end; i++){
buff[ni] = bytes[i];
ni++;
}
}
int sendEvent(String key){
int i = key.toInt();
String eventName = "";
eventName = "eventReturn_"+key;
Particle.publish(eventName, eventReturns[i], 60, PRIVATE);
eventReturns[i] = "";
return 1;
};
int setEventReturn(String value){
int index = 0;
while(eventReturns[index].length() > 1){
index++;
}
eventReturns[index] = value;
return index;
};
int writeCommandsI2C(int addr, int* commands, int commandsLen){
Serial.printf("Running I2C Command, address: %i data: ",addr);
Wire.beginTransmission(addr);
for(int i = 0; i < commandsLen; i++){
Wire.write(commands[i]);
Serial.printf("%i, ",commands[i]);
}
int status = Wire.endTransmission();
Serial.printf(" Status: %i \n", status);
return status;
};
|
Update ncd_gateway.cpp
|
Update ncd_gateway.cpp
|
C++
|
mit
|
ControlEverythingCom/ncd_gateway,ControlEverythingCom/ncd_gateway
|
78a3e36a3ac5711c2fe77d9f447863be41837f56
|
muduo/base/FileUtil.cc
|
muduo/base/FileUtil.cc
|
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.
//
// Author: Shuo Chen (chenshuo at chenshuo dot com)
#include "muduo/base/FileUtil.h"
#include "muduo/base/Logging.h"
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
using namespace muduo;
FileUtil::AppendFile::AppendFile(StringArg filename)
: fp_(::fopen(filename.c_str(), "ae")), // 'e' for O_CLOEXEC
writtenBytes_(0)
{
assert(fp_);
::setbuffer(fp_, buffer_, sizeof buffer_);
// posix_fadvise POSIX_FADV_DONTNEED ?
}
FileUtil::AppendFile::~AppendFile()
{
::fclose(fp_);
}
void FileUtil::AppendFile::append(const char* logline, const size_t len)
{
size_t n = write(logline, len);
size_t remain = len - n;
while (remain > 0)
{
size_t x = write(logline + n, remain);
if (x == 0)
{
int err = ferror(fp_);
if (err)
{
fprintf(stderr, "AppendFile::append() failed %s\n", strerror_tl(err));
}
break;
}
n += x;
remain = len - n; // remain -= x
}
writtenBytes_ += len;
}
void FileUtil::AppendFile::flush()
{
::fflush(fp_);
}
size_t FileUtil::AppendFile::write(const char* logline, size_t len)
{
// #undef fwrite_unlocked
return ::fwrite_unlocked(logline, 1, len, fp_);
}
FileUtil::ReadSmallFile::ReadSmallFile(StringArg filename)
: fd_(::open(filename.c_str(), O_RDONLY | O_CLOEXEC)),
err_(0)
{
buf_[0] = '\0';
if (fd_ < 0)
{
err_ = errno;
}
}
FileUtil::ReadSmallFile::~ReadSmallFile()
{
if (fd_ >= 0)
{
::close(fd_); // FIXME: check EINTR
}
}
// return errno
template<typename String>
int FileUtil::ReadSmallFile::readToString(int maxSize,
String* content,
int64_t* fileSize,
int64_t* modifyTime,
int64_t* createTime)
{
static_assert(sizeof(off_t) == 8, "_FILE_OFFSET_BITS = 64");
assert(content != NULL);
int err = err_;
if (fd_ >= 0)
{
content->clear();
if (fileSize)
{
struct stat statbuf;
if (::fstat(fd_, &statbuf) == 0)
{
if (S_ISREG(statbuf.st_mode))
{
*fileSize = statbuf.st_size;
content->reserve(static_cast<int>(std::min(implicit_cast<int64_t>(maxSize), *fileSize)));
}
else if (S_ISDIR(statbuf.st_mode))
{
err = EISDIR;
}
if (modifyTime)
{
*modifyTime = statbuf.st_mtime;
}
if (createTime)
{
*createTime = statbuf.st_ctime;
}
}
else
{
err = errno;
}
}
while (content->size() < implicit_cast<size_t>(maxSize))
{
size_t toRead = std::min(implicit_cast<size_t>(maxSize) - content->size(), sizeof(buf_));
ssize_t n = ::read(fd_, buf_, toRead);
if (n > 0)
{
content->append(buf_, n);
}
else
{
if (n < 0)
{
err = errno;
}
break;
}
}
}
return err;
}
int FileUtil::ReadSmallFile::readToBuffer(int* size)
{
int err = err_;
if (fd_ >= 0)
{
ssize_t n = ::pread(fd_, buf_, sizeof(buf_)-1, 0);
if (n >= 0)
{
if (size)
{
*size = static_cast<int>(n);
}
buf_[n] = '\0';
}
else
{
err = errno;
}
}
return err;
}
template int FileUtil::readFile(StringArg filename,
int maxSize,
string* content,
int64_t*, int64_t*, int64_t*);
template int FileUtil::ReadSmallFile::readToString(
int maxSize,
string* content,
int64_t*, int64_t*, int64_t*);
|
// Use of this source code is governed by a BSD-style license
// that can be found in the License file.
//
// Author: Shuo Chen (chenshuo at chenshuo dot com)
#include "muduo/base/FileUtil.h"
#include "muduo/base/Logging.h"
#include <assert.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
using namespace muduo;
FileUtil::AppendFile::AppendFile(StringArg filename)
: fp_(::fopen(filename.c_str(), "ae")), // 'e' for O_CLOEXEC
writtenBytes_(0)
{
assert(fp_);
::setbuffer(fp_, buffer_, sizeof buffer_);
// posix_fadvise POSIX_FADV_DONTNEED ?
}
FileUtil::AppendFile::~AppendFile()
{
::fclose(fp_);
}
void FileUtil::AppendFile::append(const char* logline, const size_t len)
{
size_t written = 0;
while (written != len)
{
size_t remain = len - written;
size_t n = write(logline + written, remain);
if (n != remain)
{
int err = ferror(fp_);
if (err)
{
fprintf(stderr, "AppendFile::append() failed %s\n", strerror_tl(err));
break;
}
}
written += n;
}
writtenBytes_ += written;
}
void FileUtil::AppendFile::flush()
{
::fflush(fp_);
}
size_t FileUtil::AppendFile::write(const char* logline, size_t len)
{
// #undef fwrite_unlocked
return ::fwrite_unlocked(logline, 1, len, fp_);
}
FileUtil::ReadSmallFile::ReadSmallFile(StringArg filename)
: fd_(::open(filename.c_str(), O_RDONLY | O_CLOEXEC)),
err_(0)
{
buf_[0] = '\0';
if (fd_ < 0)
{
err_ = errno;
}
}
FileUtil::ReadSmallFile::~ReadSmallFile()
{
if (fd_ >= 0)
{
::close(fd_); // FIXME: check EINTR
}
}
// return errno
template<typename String>
int FileUtil::ReadSmallFile::readToString(int maxSize,
String* content,
int64_t* fileSize,
int64_t* modifyTime,
int64_t* createTime)
{
static_assert(sizeof(off_t) == 8, "_FILE_OFFSET_BITS = 64");
assert(content != NULL);
int err = err_;
if (fd_ >= 0)
{
content->clear();
if (fileSize)
{
struct stat statbuf;
if (::fstat(fd_, &statbuf) == 0)
{
if (S_ISREG(statbuf.st_mode))
{
*fileSize = statbuf.st_size;
content->reserve(static_cast<int>(std::min(implicit_cast<int64_t>(maxSize), *fileSize)));
}
else if (S_ISDIR(statbuf.st_mode))
{
err = EISDIR;
}
if (modifyTime)
{
*modifyTime = statbuf.st_mtime;
}
if (createTime)
{
*createTime = statbuf.st_ctime;
}
}
else
{
err = errno;
}
}
while (content->size() < implicit_cast<size_t>(maxSize))
{
size_t toRead = std::min(implicit_cast<size_t>(maxSize) - content->size(), sizeof(buf_));
ssize_t n = ::read(fd_, buf_, toRead);
if (n > 0)
{
content->append(buf_, n);
}
else
{
if (n < 0)
{
err = errno;
}
break;
}
}
}
return err;
}
int FileUtil::ReadSmallFile::readToBuffer(int* size)
{
int err = err_;
if (fd_ >= 0)
{
ssize_t n = ::pread(fd_, buf_, sizeof(buf_)-1, 0);
if (n >= 0)
{
if (size)
{
*size = static_cast<int>(n);
}
buf_[n] = '\0';
}
else
{
err = errno;
}
}
return err;
}
template int FileUtil::readFile(StringArg filename,
int maxSize,
string* content,
int64_t*, int64_t*, int64_t*);
template int FileUtil::ReadSmallFile::readToString(
int maxSize,
string* content,
int64_t*, int64_t*, int64_t*);
|
write operation may fail, writtenBytes_ should be the actual number of bytes written
|
write operation may fail, writtenBytes_ should be the actual number of bytes written
|
C++
|
bsd-3-clause
|
westfly/muduo,westfly/muduo,westfly/muduo
|
bb39e8ca7609d0125e45498711c7023a4bb1baf9
|
common/detail/server_node_imp.cpp
|
common/detail/server_node_imp.cpp
|
/*
** Author(s):
** - Chris Kilner <[email protected]>
**
** Copyright (C) 2010 Aldebaran Robotics
*/
#include <alcommon-ng/common/detail/server_node_imp.hpp>
#include <string>
#include <alcommon-ng/common/detail/get_protocol.hpp>
#include <alcommon-ng/messaging/server.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <allog/allog.h>
namespace AL {
using namespace Messaging;
namespace Common {
ServerNodeImp::ServerNodeImp() : initOK(false) {}
ServerNodeImp::~ServerNodeImp() {}
ServerNodeImp::ServerNodeImp(
const std::string& serverName,
const std::string& serverAddress,
const std::string& masterAddress) : initOK(false)
{
fInfo.name = serverName;
fInfo.address = serverAddress;
bool initOK = fClient.connect(getProtocol(serverAddress, masterAddress) + masterAddress);
if (! initOK ) {
alserror << "\"" << serverName << "\" could not connect to master at address \"" << masterAddress << "\"";
return;
}
fServer.serve("tcp://" + serverAddress);
fServer.setMessageHandler(this);
boost::thread serverThread(boost::bind(&Server::run, fServer));
}
void ServerNodeImp::messageHandler(const CallDefinition &def, ResultDefinition& result) {
// handle message
std::string hash = def.methodName();
const ServiceInfo& si = xGetService(hash);
if (si.methodName.empty()) {
// method not found
alserror << " Error: Method not found " << hash;
}
si.functor->call(def.args(), result.value());
}
const NodeInfo& ServerNodeImp::getNodeInfo() const {
return fInfo;
}
void ServerNodeImp::addService(const std::string& name, Functor* functor) {
ServiceInfo service(name, functor);
std::string hash = service.methodName;
//std::cout << "Added Service" << hash << std::endl;
fLocalServiceList.insert(hash, service);
xRegisterServiceWithMaster(hash);
}
const ServiceInfo& ServerNodeImp::xGetService(
const std::string& methodHash) {
// functors ... should be found here
return fLocalServiceList.get(methodHash);
}
void ServerNodeImp::xRegisterServiceWithMaster(const std::string& methodHash) {
if (fInfo.name != "master") { // ehem
ResultDefinition r;
fClient.call(CallDefinition("master.registerService::v:ss", fInfo.address, methodHash),r);
}
}
}
}
|
/*
** Author(s):
** - Chris Kilner <[email protected]>
**
** Copyright (C) 2010 Aldebaran Robotics
*/
#include <alcommon-ng/common/detail/server_node_imp.hpp>
#include <string>
#include <alcommon-ng/common/detail/get_protocol.hpp>
#include <alcommon-ng/messaging/server.hpp>
#include <boost/thread.hpp>
#include <boost/bind.hpp>
#include <allog/allog.h>
namespace AL {
using namespace Messaging;
namespace Common {
ServerNodeImp::ServerNodeImp() : initOK(false) {}
ServerNodeImp::~ServerNodeImp() {}
ServerNodeImp::ServerNodeImp(
const std::string& serverName,
const std::string& serverAddress,
const std::string& masterAddress) : initOK(false)
{
fInfo.name = serverName;
fInfo.address = serverAddress;
bool initOK = fClient.connect(getProtocol(serverAddress, masterAddress) + masterAddress);
if (! initOK ) {
alserror << "\"" << serverName << "\" could not connect to master at address \"" << masterAddress << "\"";
return;
}
fServer.serve("tcp://" + serverAddress);
fServer.setMessageHandler(this);
boost::thread serverThread(boost::bind(&Server::run, fServer));
}
void ServerNodeImp::messageHandler(const CallDefinition &def, ResultDefinition& result) {
// handle message
std::string hash = def.methodName();
const ServiceInfo& si = xGetService(hash);
if (si.methodName.empty() || !si.functor) {
// method not found
alserror << " Error: Method not found " << hash;
}
si.functor->call(def.args(), result.value());
}
const NodeInfo& ServerNodeImp::getNodeInfo() const {
return fInfo;
}
void ServerNodeImp::addService(const std::string& name, Functor* functor) {
ServiceInfo service(name, functor);
std::string hash = service.methodName;
//std::cout << "Added Service" << hash << std::endl;
fLocalServiceList.insert(hash, service);
xRegisterServiceWithMaster(hash);
}
const ServiceInfo& ServerNodeImp::xGetService(
const std::string& methodHash) {
// functors ... should be found here
return fLocalServiceList.get(methodHash);
}
void ServerNodeImp::xRegisterServiceWithMaster(const std::string& methodHash) {
if (fInfo.name != "master") { // ehem
ResultDefinition r;
fClient.call(CallDefinition("master.registerService::v:ss", fInfo.address, methodHash),r);
}
}
}
}
|
check if methodname is empty and si.functor is not null (.length() might be a better check)
|
common: check if methodname is empty and si.functor is not null (.length() might be a better check)
|
C++
|
bsd-3-clause
|
bsautron/libqi,aldebaran/libqi,aldebaran/libqi-java,aldebaran/libqi-java,aldebaran/libqi-java,aldebaran/libqi,vbarbaresi/libqi,aldebaran/libqi
|
ae0fa609a962914e6104f5d0debd9a06f2b7f3db
|
features/mbedtls/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/src/default_random_seed.cpp
|
features/mbedtls/platform/TARGET_PSA/COMPONENT_PSA_SRV_IMPL/src/default_random_seed.cpp
|
#include "mbed.h"
#include "crypto.h"
#include "default_random_seed.h"
#include "psa_prot_internal_storage.h"
int mbed_default_seed_read(unsigned char *buf, size_t buf_len)
{
struct psa_its_info_t info = {0, 0};
size_t actual_size = buf_len;
psa_its_get_info(PSA_CRYPTO_ITS_RANDOM_SEED_UID, &info);
if (info.size < buf_len)
{
actual_size = info.size;
}
psa_its_status_t rc = psa_its_get(PSA_CRYPTO_ITS_RANDOM_SEED_UID, 0, actual_size, buf);
/* Make sure that in case of an error the value will be negative
* Mbed TLS errors are negative values */
rc = rc < 0 ? rc : (-1 * rc);
return (rc);
}
int mbed_default_seed_write(unsigned char *buf, size_t buf_len)
{
psa_its_status_t rc = psa_its_set(PSA_CRYPTO_ITS_RANDOM_SEED_UID, buf_len, buf, 0);
/* Make sure that in case of an error the value will be negative
* Mbed TLS errors are negative values */
rc = rc < 0 ? rc : (-1 * rc);
return (rc);
}
|
#include "mbed.h"
#include "crypto.h"
#include "default_random_seed.h"
#include "psa_prot_internal_storage.h"
int mbed_default_seed_read(unsigned char *buf, size_t buf_len)
{
psa_its_status_t rc = psa_its_get(PSA_CRYPTO_ITS_RANDOM_SEED_UID, 0, buf_len, buf);
return ( -1 * rc );
}
int mbed_default_seed_write(unsigned char *buf, size_t buf_len)
{
psa_its_status_t rc = psa_its_set(PSA_CRYPTO_ITS_RANDOM_SEED_UID, buf_len, buf, 0);
return ( -1 * rc );
}
|
remove psa_its_get_info from seed read function
|
remove psa_its_get_info from seed read function
|
C++
|
apache-2.0
|
mbedmicro/mbed,kjbracey-arm/mbed,andcor02/mbed-os,kjbracey-arm/mbed,kjbracey-arm/mbed,andcor02/mbed-os,mbedmicro/mbed,mbedmicro/mbed,mbedmicro/mbed,mbedmicro/mbed,kjbracey-arm/mbed,andcor02/mbed-os,andcor02/mbed-os,andcor02/mbed-os,andcor02/mbed-os
|
3af46639c887028ad05cef59e27dbf47f7c78219
|
include/stack.cpp
|
include/stack.cpp
|
#include <stdlib.h>
#include <iostream>
template <typename T>
class stack
{
private:
T *array_; // óêàçàòåëü íà ñòåê
size_t array_size_; // êîëè÷åñòâî ýëåìåíòîâ â ñòåêå
size_t count_; // íîìåð òåêóùåãî ýëåìåíòà ñòåêà
auto swap(stack & right) -> void; // ìåíÿåò ñîäåðæèìîå ñòåêîâ
public:
stack(); // êîíñòðóêòîð
~stack(); // äåñòðóêòîð
size_t count() const;
auto push(T const &) -> void; // ïîìåñòèòü ýëåìåíò â âåðøèíó ñòåêà
T pop(); // óäàëèòü ýëåìåíò èç âåðøèíû ñòåêà è âåðíóòü åãî
auto operator=(stack const & right)->stack &; // ïåðåîïðåäåëåíèå îïåðàòîðà, ïðèñâàèâàåò çíà÷åíèå êîíòåéíåðó"
};
int main()
{
stack<int> a;
a.push(1);
a.push(2);
a.push(3);
stack<int> b;
b.push(2);
system("pause");
}
template <typename T>
size_t stack<T>::count() const
{
std::cout << count_;
return count_;
}
template <typename T>
stack<T>::stack()
{
array_size_ = 0;
array_ = new T[array_size_];
count_ = 0;
}
template <typename T>
stack<T>::~stack()
{
delete[] array_;
}
template<typename T>
void stack<T>::push(T const &item)
{
if (count_ == array_size_)
{
count_++;
size_t size = array_size_ * 2 + (array_size_ == 0);
T *buff = new T[size];
for (int i = 0; i < count_; i++)
{
buff[i] = array_[i];
}
delete[] array_;
array_ = buff;
array_size_ = size;
array_[count_ - 1] = item;
}
}
template<typename T>
T stack<T>::pop()
{
if (count_ == 0)
{
throw std::logic_error("Stack is empty!");
}
return array_[--count_];
}
template<typename T>
auto stack<T>::swap(stack & right) -> void
{
array_size_ = right.array_size_;
count_ = right.count_;
T *buff = new T[array_size_];
std::swap(buff, array_);
std::swap(buff, right.array_);
std::swap(buff, array_);
}
template<typename T>
auto stack<T>::operator=(stack const & right) -> stack & {
if (this != &right) {
T* buff = newcopy(right.array_, right.array_size_, right.count_);
delete[] array_;
array_ = buff;
count_ = right.count_;
array_size_ = right.array_size_;
}
return *this;
}
|
#include <stdlib.h>
#include <iostream>
template <typename T>
class stack
{
private:
T *array_; // óêàçàòåëü íà ñòåê
size_t array_size_; // êîëè÷åñòâî ýëåìåíòîâ â ñòåêå
size_t count_; // íîìåð òåêóùåãî ýëåìåíòà ñòåêà
auto swap(stack & right) -> void; // ìåíÿåò ñîäåðæèìîå ñòåêîâ
public:
stack(); // êîíñòðóêòîð
~stack(); // äåñòðóêòîð
size_t count() const;
auto push(T const &) -> void; // ïîìåñòèòü ýëåìåíò â âåðøèíó ñòåêà
T pop(); // óäàëèòü ýëåìåíò èç âåðøèíû ñòåêà è âåðíóòü åãî
auto operator=(stack const & right)->stack &; // ïåðåîïðåäåëåíèå îïåðàòîðà, ïðèñâàèâàåò çíà÷åíèå êîíòåéíåðó"
};
int main()
{
stack<int> a;
a.push(1);
a.push(2);
a.push(3);
stack<int> b;
b.push(2);
system("pause");
}
template <typename T>
size_t stack<T>::count() const
{
std::cout << count_;
return count_;
}
template <typename T>
stack<T>::stack()
{
array_size_ = 0;
array_ = new T[array_size_];
count_ = 0;
}
template <typename T>
stack<T>::~stack()
{
delete[] array_;
}
template<typename T>
void stack<T>::push(T const &item)
{
if (count_ == array_size_)
{
count_++;
size_t size = array_size_ * 2 + (array_size_ == 0);
T *buff = new T[size];
for (int i = 0; i < count_; i++)
{
buff[i] = array_[i];
}
delete[] array_;
array_ = buff;
array_size_ = size;
array_[count_ - 1] = item;
}
}
template<typename T>
T stack<T>::pop()
{
if (count_ == 0)
{
throw std::logic_error("Stack is empty!");
}
return array_[--count_];
}
template<typename T>
auto stack<T>::swap(stack & right) -> void
{
array_size_ = right.array_size_;
count_ = right.count_;
T *buff = new T[array_size_];
std::swap(buff, array_);
std::swap(buff, right.array_);
std::swap(buff, array_);
}
template<typename T>
auto stack<T>::operator=(stack const & right) -> stack &
{
if (this != &right)
{
(stack(right)).swap(*this);
}
return *this;
}
|
Update stack.cpp
|
Update stack.cpp
|
C++
|
mit
|
tpabahatp/Stack
|
9192dc955760fc3a41d98466fd20fca4306e190e
|
cpp/xsimtop.cpp
|
cpp/xsimtop.cpp
|
#include <stdlib.h>
#include <string>
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <queue>
#include "xsi_loader.h"
#include <portal.h>
#include <sock_utils.h>
#include <GeneratedTypes.h>
#include <XsimMemSlaveRequest.h>
#include <XsimMemSlaveIndication.h>
XsimMemSlaveIndicationProxy *memSlaveIndicationProxy;
class XsimMemSlaveRequest;
XsimMemSlaveRequest *memSlaveRequest;
//deleteme
std::string getcurrentdir()
{
return get_current_dir_name();
}
class xsiport {
Xsi::Loader &xsiInstance;
int port;
//int direction;
const char *name;
int width;
s_xsi_vlog_logicval value;
public:
xsiport(Xsi::Loader &loader, const char *name, int bits = 1)
: xsiInstance(loader), port(-1), name(name), width(bits)
{
value = {1, 1};
port = xsiInstance.get_port_number(name);
//width = xsiInstance.get_int_port(port, xsiHDLValueSize);
std::cout << "Port name=" << name << " number=" << port << std::endl;
}
int read();
void write(int val);
int valid() { return port >= 0; }
};
int xsiport::read()
{
xsiInstance.get_value(port, &value);
int mask = (width == 32) ? -1 : ((1 << width) - 1);
if (value.bVal != 0) {
char charval[] = { '0', '1', 'Z', 'X' };
int encoding = (value.aVal & mask) | ((value.bVal & mask) << 1);
fprintf(stderr, "port %2d.%16s value=%08x.%08x mask=%08x width=%2d %c\n", port, name, value.aVal, value.bVal, mask, width, charval[encoding]);
}
return value.aVal & mask;
}
void xsiport::write(int aVal)
{
value.aVal = aVal;
value.bVal = 0;
xsiInstance.put_value(port, &value);
}
class XsimMemSlaveRequest : public XsimMemSlaveRequestWrapper {
struct idInfo {
int number;
int id;
int valid;
} ids[16];
int portal_count;
public:
struct readreq {
uint32_t addr;
};
struct writereq {
uint32_t addr;
uint32_t data;
};
std::queue<readreq> readreqs;
std::queue<uint32_t> readdata;
std::queue<writereq> writereqs;
std::queue<uint32_t> sinkbeats;
int connected;
XsimMemSlaveRequest(int id, PortalItemFunctions *item, void *param, PortalPoller *poller = 0) : XsimMemSlaveRequestWrapper(id, item, param, poller), connected(0) { }
~XsimMemSlaveRequest() {}
virtual void connect () {
connected = 1;
}
virtual void enableint( const uint32_t fpgaId, const uint32_t val);
virtual void read ( const uint32_t fpgaId, const uint32_t addr );
virtual void write ( const uint32_t fpgaId, const uint32_t addr, const uint32_t data );
virtual void msgSink ( const uint32_t data );
void directory( const uint32_t fpgaNumber, const uint32_t fpgaId, const uint32_t last );
int fpgaNumber(int fpgaId);
int fpgaId(int fpgaNumber);
};
void XsimMemSlaveRequest::enableint( const uint32_t fpgaId, const uint32_t val)
{
int number = fpgaNumber(fpgaId);
uint32_t hwaddr = number << 16 | 4;
writereq req = { hwaddr, val };
fprintf(stderr, "[%s:%d] id=%d number=%d addr=%08x\n", __FUNCTION__, __LINE__, fpgaId, number, hwaddr);
writereqs.push(req);
}
void XsimMemSlaveRequest::read ( const uint32_t fpgaId, const uint32_t addr )
{
int number = fpgaNumber(fpgaId);
fprintf(stderr, "[%s:%d] id=%d number=%d addr=%08x\n", __FUNCTION__, __LINE__, fpgaId, number, addr);
uint32_t hwaddr = number << 16 | addr;
readreq req = { hwaddr };
readreqs.push(req);
}
void XsimMemSlaveRequest::write ( const uint32_t fpgaId, const uint32_t addr, const uint32_t data )
{
int number = fpgaNumber(fpgaId);
uint32_t hwaddr = number << 16 | addr;
writereq req = { hwaddr, data };
fprintf(stderr, "[%s:%d] id=%d number=%d addr=%08x/%08x data=%08x\n", __FUNCTION__, __LINE__, fpgaId, fpgaNumber(fpgaId), addr, hwaddr, data);
writereqs.push(req);
}
void XsimMemSlaveRequest::msgSink ( const uint32_t data )
{
fprintf(stderr, "[%s:%d] data=%08x\n", __FUNCTION__, __LINE__, data);
sinkbeats.push(data);
}
void XsimMemSlaveRequest::directory ( const uint32_t fpgaNumber, const uint32_t fpgaId, const uint32_t last )
{
fprintf(stderr, "[%s:%d] fpga=%d id=%d last=%d\n", __FUNCTION__, __LINE__, fpgaNumber, fpgaId, last);
struct idInfo info = { fpgaNumber, fpgaId, 1 };
ids[fpgaNumber] = info;
if (last)
portal_count = fpgaNumber+1;
}
int XsimMemSlaveRequest::fpgaNumber(int fpgaId)
{
for (int i = 0; ids[i].valid; i++)
if (ids[i].id == fpgaId) {
return ids[i].number;
}
PORTAL_PRINTF( "Error: %s: did not find fpga_number %d\n", __FUNCTION__, fpgaId);
PORTAL_PRINTF( " Found fpga numbers:");
for (int i = 0; ids[i].valid; i++)
PORTAL_PRINTF( " %d", ids[i].id);
PORTAL_PRINTF( "\n");
return 0;
}
int XsimMemSlaveRequest::fpgaId(int fpgaNumber)
{
return ids[fpgaNumber].id;
}
enum xsimtop_state {
xt_reset, xt_read_directory, xt_active
};
int main(int argc, char **argv)
{
std::string cwd = getcurrentdir();
std::string simengine_libname = "librdi_simulator_kernel.so";
std::string design_libname = getcurrentdir() + "/xsim.dir/mkXsimTop/xsimk.so";
std::cout << "Design DLL : " << design_libname << std::endl;
std::cout << "Sim Engine DLL : " << simengine_libname << std::endl;
// See xsi.h header for more details on how Verilog values are stored as aVal/bVal pairs
Xsi::Loader xsiInstance(design_libname, simengine_libname);
s_xsi_setup_info info;
info.logFileName = (char *)"xsim.log";
xsiInstance.open(&info);
xsimtop_state state = xt_reset;
xsiport rst_n(xsiInstance, "RST_N");
xsiport clk(xsiInstance, "CLK");
xsiport en_interrupt(xsiInstance, "EN_interrupt");
xsiport rdy_interrupt(xsiInstance, "RDY_interrupt");
xsiport interrupt(xsiInstance, "interrupt", 4);
xsiport en_directoryEntry(xsiInstance, "EN_directoryEntry");
xsiport rdy_directoryEntry(xsiInstance, "RDY_directoryEntry");
xsiport directoryEntry(xsiInstance, "directoryEntry", 32);
xsiport read_addr(xsiInstance, "read_addr", 32);
xsiport en_read(xsiInstance, "EN_read");
xsiport rdy_read(xsiInstance, "RDY_read");
xsiport readData(xsiInstance, "readData", 32);
xsiport en_readData(xsiInstance, "EN_readData");
xsiport rdy_readData(xsiInstance, "RDY_readData");
xsiport write_addr(xsiInstance, "write_addr");
xsiport write_data(xsiInstance, "write_data");
xsiport en_write(xsiInstance, "EN_write");
xsiport rdy_write(xsiInstance, "RDY_write");
xsiport clk_singleClock(xsiInstance, "CLK_singleClock");
xsiport msgSource_src_rdy(xsiInstance, "msgSource_src_rdy");
xsiport msgSource_dst_rdy_b(xsiInstance, "msgSource_dst_rdy_b");
xsiport msgSource_beat(xsiInstance, "msgSource_beat");
xsiport msgSink_dst_rdy(xsiInstance, "msgSink_dst_rdy");
xsiport msgSink_src_rdy_b(xsiInstance, "msgSink_src_rdy_b");
xsiport msgSink_beat_v(xsiInstance, "msgSink_beat_v");
PortalSocketParam paramSocket = {};
PortalMuxParam param = {};
if (msgSource_beat.valid())
fprintf(stderr, "[%s:%d] using BluenocTop\n", __FILE__, __LINE__);
Portal *mcommon = new Portal(0, sizeof(uint32_t), portal_mux_handler, NULL, &socketfuncResp, ¶mSocket, 0);
param.pint = &mcommon->pint;
XsimMemSlaveIndicationProxy *memSlaveIndicationProxy = new XsimMemSlaveIndicationProxy(XsimIfcNames_XsimMemSlaveIndication, &muxfunc, ¶m);
XsimMemSlaveRequest *memSlaveRequest = new XsimMemSlaveRequest(XsimIfcNames_XsimMemSlaveRequest, &muxfunc, ¶m);
portalExec_init();
// start low clock
clk.write(0);
rst_n.write(0);
read_addr.write(0);
en_read.write(0);
en_readData.write(0);
en_write.write(0);
xsiInstance.run(10);
int portal_number = 0;
int waiting_for_read = 0;
int read_dir_val = 0;
int portal_ids[16];
int portal_count = 0;
int offset = 0x00;
for (int i = 0; 1; i++)
{
void *rc = portalExec_poll(1);
if ((long)rc >= 0) {
portalExec_event();
}
if (i > 2) {
rst_n.write(1);
}
// mkConnectalTop
if (!msgSource_beat.valid()) {
if (rdy_directoryEntry.read() && !portal_count) {
fprintf(stderr, "directoryEntry %08x\n", directoryEntry.read());
unsigned int val = directoryEntry.read();
bool last = (val & 0x80000000) != 0;
uint32_t id = val & 0x7fffffff;
memSlaveRequest->directory(portal_number, id, last);
portal_ids[portal_number++] = id;
if (last) {
portal_count = portal_number;
portal_number = 0;
fprintf(stderr, "portal_count=%d\n", portal_count);
state = xt_active;
}
en_directoryEntry.write(1);
} else {
en_directoryEntry.write(0);
}
if (memSlaveRequest->connected && (portal_number < portal_count)) {
memSlaveIndicationProxy->directory(portal_number, portal_ids[portal_number], portal_number == (portal_count-1));
portal_number++;
}
if (state == xt_active) {
if (memSlaveRequest->readreqs.size() && rdy_read.read()) {
XsimMemSlaveRequest::readreq readreq = memSlaveRequest->readreqs.front();
memSlaveRequest->readreqs.pop();
en_read.write(1);
fprintf(stderr, "Reading from addr %08x\n", readreq.addr);
read_addr.write(readreq.addr);
} else {
en_read.write(0);
}
if (rdy_readData.read()) {
en_readData.write(1);
uint32_t data = readData.read();
fprintf(stderr, "Read data %08x\n", data);
memSlaveIndicationProxy->readData(data);
} else {
en_readData.write(0);
}
if (memSlaveRequest->writereqs.size() && rdy_write.read()) {
XsimMemSlaveRequest::writereq writereq = memSlaveRequest->writereqs.front();
memSlaveRequest->writereqs.pop();
en_write.write(1);
fprintf(stderr, "Writing to addr %08x data %08x\n", writereq.addr, writereq.data);
write_addr.write(writereq.addr);
write_data.write(writereq.data);
} else {
en_write.write(0);
}
}
if (memSlaveRequest->connected && rdy_interrupt.read()) {
en_interrupt.write(1);
int intr = interrupt.read();
int id = memSlaveRequest->fpgaId(intr);
fprintf(stderr, "Got interrupt number %d id %d\n", intr, id);
memSlaveIndicationProxy->interrupt(id);
} else {
en_interrupt.write(0);
}
} else {
// mkBluenocTop
if (msgSource_src_rdy.read()) {
uint32_t beat = msgSource_beat.read();
msgSource_dst_rdy_b.write(1);
memSlaveIndicationProxy->msgSource(beat);
} else {
msgSource_dst_rdy_b.write(0);
}
if (msgSink_dst_rdy.read() && memSlaveRequest->sinkbeats.size()) {
uint32_t beat = memSlaveRequest->sinkbeats.front();
memSlaveRequest->sinkbeats.pop();
msgSink_beat_v.write(beat);
msgSink_src_rdy_b.write(1);
} else {
msgSink_src_rdy_b.write(0);
}
}
clk.write(1);
xsiInstance.run(10);
if (0) {
// clock is divided by two
clk.write(0);
xsiInstance.run(10);
clk.write(1);
xsiInstance.run(10);
}
clk.write(0);
xsiInstance.run(10);
}
sleep(10);
portalExec_end();
}
|
#include <stdlib.h>
#include <string>
#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <queue>
#include "xsi_loader.h"
#include <portal.h>
#include <sock_utils.h>
#include <GeneratedTypes.h>
#include <XsimMemSlaveRequest.h>
#include <XsimMemSlaveIndication.h>
XsimMemSlaveIndicationProxy *memSlaveIndicationProxy;
class XsimMemSlaveRequest;
XsimMemSlaveRequest *memSlaveRequest;
//deleteme
std::string getcurrentdir()
{
return get_current_dir_name();
}
class xsiport {
Xsi::Loader &xsiInstance;
int port;
//int direction;
const char *name;
int width;
s_xsi_vlog_logicval value;
public:
xsiport(Xsi::Loader &loader, const char *name, int bits = 1)
: xsiInstance(loader), port(-1), name(name), width(bits)
{
value = {1, 1};
port = xsiInstance.get_port_number(name);
//width = xsiInstance.get_int_port(port, xsiHDLValueSize);
std::cout << "Port name=" << name << " number=" << port << std::endl;
}
int read();
void write(int val);
int valid() { return port >= 0; }
};
int xsiport::read()
{
xsiInstance.get_value(port, &value);
int mask = (width == 32) ? -1 : ((1 << width) - 1);
if (value.bVal != 0) {
char charval[] = { '0', '1', 'Z', 'X' };
int encoding = (value.aVal & mask) | ((value.bVal & mask) << 1);
fprintf(stderr, "port %2d.%16s value=%08x.%08x mask=%08x width=%2d %c\n", port, name, value.aVal, value.bVal, mask, width, charval[encoding]);
}
return value.aVal & mask;
}
void xsiport::write(int aVal)
{
value.aVal = aVal;
value.bVal = 0;
xsiInstance.put_value(port, &value);
}
class XsimMemSlaveRequest : public XsimMemSlaveRequestWrapper {
struct idInfo {
int number;
int id;
int valid;
} ids[16];
int portal_count;
public:
struct readreq {
uint32_t addr;
};
struct writereq {
uint32_t addr;
uint32_t data;
};
std::queue<readreq> readreqs;
std::queue<uint32_t> readdata;
std::queue<writereq> writereqs;
std::queue<uint32_t> sinkbeats;
int connected;
XsimMemSlaveRequest(int id, PortalItemFunctions *item, void *param, PortalPoller *poller = 0) : XsimMemSlaveRequestWrapper(id, item, param, poller), connected(0) { }
~XsimMemSlaveRequest() {}
virtual void connect () {
connected = 1;
}
virtual void enableint( const uint32_t fpgaId, const uint32_t val);
virtual void read ( const uint32_t fpgaId, const uint32_t addr );
virtual void write ( const uint32_t fpgaId, const uint32_t addr, const uint32_t data );
virtual void msgSink ( const uint32_t data );
void directory( const uint32_t fpgaNumber, const uint32_t fpgaId, const uint32_t last );
int fpgaNumber(int fpgaId);
int fpgaId(int fpgaNumber);
};
void XsimMemSlaveRequest::enableint( const uint32_t fpgaId, const uint32_t val)
{
int number = fpgaNumber(fpgaId);
uint32_t hwaddr = number << 16 | 4;
writereq req = { hwaddr, val };
fprintf(stderr, "[%s:%d] id=%d number=%d addr=%08x\n", __FUNCTION__, __LINE__, fpgaId, number, hwaddr);
writereqs.push(req);
}
void XsimMemSlaveRequest::read ( const uint32_t fpgaId, const uint32_t addr )
{
int number = fpgaNumber(fpgaId);
fprintf(stderr, "[%s:%d] id=%d number=%d addr=%08x\n", __FUNCTION__, __LINE__, fpgaId, number, addr);
uint32_t hwaddr = number << 16 | addr;
readreq req = { hwaddr };
readreqs.push(req);
}
void XsimMemSlaveRequest::write ( const uint32_t fpgaId, const uint32_t addr, const uint32_t data )
{
int number = fpgaNumber(fpgaId);
uint32_t hwaddr = number << 16 | addr;
writereq req = { hwaddr, data };
fprintf(stderr, "[%s:%d] id=%d number=%d addr=%08x/%08x data=%08x\n", __FUNCTION__, __LINE__, fpgaId, fpgaNumber(fpgaId), addr, hwaddr, data);
writereqs.push(req);
}
void XsimMemSlaveRequest::msgSink ( const uint32_t data )
{
fprintf(stderr, "[%s:%d] data=%08x\n", __FUNCTION__, __LINE__, data);
sinkbeats.push(data);
}
void XsimMemSlaveRequest::directory ( const uint32_t fpgaNumber, const uint32_t fpgaId, const uint32_t last )
{
fprintf(stderr, "[%s:%d] fpga=%d id=%d last=%d\n", __FUNCTION__, __LINE__, fpgaNumber, fpgaId, last);
struct idInfo info = { fpgaNumber, fpgaId, 1 };
ids[fpgaNumber] = info;
if (last)
portal_count = fpgaNumber+1;
}
int XsimMemSlaveRequest::fpgaNumber(int fpgaId)
{
for (int i = 0; ids[i].valid; i++)
if (ids[i].id == fpgaId) {
return ids[i].number;
}
PORTAL_PRINTF( "Error: %s: did not find fpga_number %d\n", __FUNCTION__, fpgaId);
PORTAL_PRINTF( " Found fpga numbers:");
for (int i = 0; ids[i].valid; i++)
PORTAL_PRINTF( " %d", ids[i].id);
PORTAL_PRINTF( "\n");
return 0;
}
int XsimMemSlaveRequest::fpgaId(int fpgaNumber)
{
return ids[fpgaNumber].id;
}
enum xsimtop_state {
xt_reset, xt_read_directory, xt_active
};
int main(int argc, char **argv)
{
std::string cwd = getcurrentdir();
std::string simengine_libname = "librdi_simulator_kernel.so";
std::string design_libname = getcurrentdir() + "/xsim.dir/mkXsimTop/xsimk.so";
std::cout << "Design DLL : " << design_libname << std::endl;
std::cout << "Sim Engine DLL : " << simengine_libname << std::endl;
// See xsi.h header for more details on how Verilog values are stored as aVal/bVal pairs
Xsi::Loader xsiInstance(design_libname, simengine_libname);
s_xsi_setup_info info;
info.logFileName = (char *)"xsim.log";
xsiInstance.open(&info);
xsimtop_state state = xt_reset;
xsiport rst_n(xsiInstance, "RST_N");
xsiport clk(xsiInstance, "CLK");
xsiport en_interrupt(xsiInstance, "EN_interrupt");
xsiport rdy_interrupt(xsiInstance, "RDY_interrupt");
xsiport interrupt(xsiInstance, "interrupt", 4);
xsiport en_directoryEntry(xsiInstance, "EN_directoryEntry");
xsiport rdy_directoryEntry(xsiInstance, "RDY_directoryEntry");
xsiport directoryEntry(xsiInstance, "directoryEntry", 32);
xsiport read_addr(xsiInstance, "read_addr", 32);
xsiport en_read(xsiInstance, "EN_read");
xsiport rdy_read(xsiInstance, "RDY_read");
xsiport readData(xsiInstance, "readData", 32);
xsiport en_readData(xsiInstance, "EN_readData");
xsiport rdy_readData(xsiInstance, "RDY_readData");
xsiport write_addr(xsiInstance, "write_addr");
xsiport write_data(xsiInstance, "write_data");
xsiport en_write(xsiInstance, "EN_write");
xsiport rdy_write(xsiInstance, "RDY_write");
xsiport clk_singleClock(xsiInstance, "CLK_singleClock");
xsiport msgSource_src_rdy(xsiInstance, "msgSource_src_rdy");
xsiport msgSource_dst_rdy_b(xsiInstance, "msgSource_dst_rdy_b");
xsiport msgSource_beat(xsiInstance, "msgSource_beat");
xsiport msgSink_dst_rdy(xsiInstance, "msgSink_dst_rdy");
xsiport msgSink_src_rdy_b(xsiInstance, "msgSink_src_rdy_b");
xsiport msgSink_beat_v(xsiInstance, "msgSink_beat_v");
PortalSocketParam paramSocket = {};
PortalMuxParam param = {};
if (msgSource_beat.valid())
fprintf(stderr, "[%s:%d] using BluenocTop\n", __FILE__, __LINE__);
Portal *mcommon = new Portal(0, sizeof(uint32_t), portal_mux_handler, NULL, &socketfuncResp, ¶mSocket, 0);
param.pint = &mcommon->pint;
XsimMemSlaveIndicationProxy *memSlaveIndicationProxy = new XsimMemSlaveIndicationProxy(XsimIfcNames_XsimMemSlaveIndication, &muxfunc, ¶m);
XsimMemSlaveRequest *memSlaveRequest = new XsimMemSlaveRequest(XsimIfcNames_XsimMemSlaveRequest, &muxfunc, ¶m);
portalExec_init();
// start low clock
clk.write(0);
rst_n.write(0);
if (read_addr.valid()) {
read_addr.write(0);
en_read.write(0);
en_readData.write(0);
en_write.write(0);
}
xsiInstance.run(10);
int portal_number = 0;
int waiting_for_read = 0;
int read_dir_val = 0;
int portal_ids[16];
int portal_count = 0;
int offset = 0x00;
for (int i = 0; 1; i++)
{
void *rc = portalExec_poll(1);
if ((long)rc >= 0) {
portalExec_event();
}
if (i > 2) {
rst_n.write(1);
}
// mkConnectalTop
if (!msgSource_beat.valid()) {
if (rdy_directoryEntry.read() && !portal_count) {
fprintf(stderr, "directoryEntry %08x\n", directoryEntry.read());
unsigned int val = directoryEntry.read();
bool last = (val & 0x80000000) != 0;
uint32_t id = val & 0x7fffffff;
memSlaveRequest->directory(portal_number, id, last);
portal_ids[portal_number++] = id;
if (last) {
portal_count = portal_number;
portal_number = 0;
fprintf(stderr, "portal_count=%d\n", portal_count);
state = xt_active;
}
en_directoryEntry.write(1);
} else {
en_directoryEntry.write(0);
}
if (memSlaveRequest->connected && (portal_number < portal_count)) {
memSlaveIndicationProxy->directory(portal_number, portal_ids[portal_number], portal_number == (portal_count-1));
portal_number++;
}
if (state == xt_active) {
if (memSlaveRequest->readreqs.size() && rdy_read.read()) {
XsimMemSlaveRequest::readreq readreq = memSlaveRequest->readreqs.front();
memSlaveRequest->readreqs.pop();
en_read.write(1);
fprintf(stderr, "Reading from addr %08x\n", readreq.addr);
read_addr.write(readreq.addr);
} else {
en_read.write(0);
}
if (rdy_readData.read()) {
en_readData.write(1);
uint32_t data = readData.read();
fprintf(stderr, "Read data %08x\n", data);
memSlaveIndicationProxy->readData(data);
} else {
en_readData.write(0);
}
if (memSlaveRequest->writereqs.size() && rdy_write.read()) {
XsimMemSlaveRequest::writereq writereq = memSlaveRequest->writereqs.front();
memSlaveRequest->writereqs.pop();
en_write.write(1);
fprintf(stderr, "Writing to addr %08x data %08x\n", writereq.addr, writereq.data);
write_addr.write(writereq.addr);
write_data.write(writereq.data);
} else {
en_write.write(0);
}
}
if (memSlaveRequest->connected && rdy_interrupt.read()) {
en_interrupt.write(1);
int intr = interrupt.read();
int id = memSlaveRequest->fpgaId(intr);
fprintf(stderr, "Got interrupt number %d id %d\n", intr, id);
memSlaveIndicationProxy->interrupt(id);
} else {
en_interrupt.write(0);
}
} else {
// mkBluenocTop
if (msgSource_src_rdy.read()) {
uint32_t beat = msgSource_beat.read();
msgSource_dst_rdy_b.write(1);
memSlaveIndicationProxy->msgSource(beat);
} else {
msgSource_dst_rdy_b.write(0);
}
if (msgSink_dst_rdy.read() && memSlaveRequest->sinkbeats.size()) {
uint32_t beat = memSlaveRequest->sinkbeats.front();
memSlaveRequest->sinkbeats.pop();
msgSink_beat_v.write(beat);
msgSink_src_rdy_b.write(1);
} else {
msgSink_src_rdy_b.write(0);
}
}
clk.write(1);
xsiInstance.run(10);
if (0) {
// clock is divided by two
clk.write(0);
xsiInstance.run(10);
clk.write(1);
xsiInstance.run(10);
}
clk.write(0);
xsiInstance.run(10);
}
sleep(10);
portalExec_end();
}
|
check for validity of read_addr port
|
check for validity of read_addr port
|
C++
|
mit
|
chenm001/connectal,hanw/connectal,8l/connectal,hanw/connectal,cambridgehackers/connectal,8l/connectal,cambridgehackers/connectal,8l/connectal,hanw/connectal,chenm001/connectal,hanw/connectal,csail-csg/connectal,csail-csg/connectal,chenm001/connectal,chenm001/connectal,cambridgehackers/connectal,8l/connectal,csail-csg/connectal,8l/connectal,cambridgehackers/connectal,hanw/connectal,cambridgehackers/connectal,chenm001/connectal,csail-csg/connectal,csail-csg/connectal
|
9cb7f16f01c1009fdf847bd416b66d3fe66d0972
|
include/stack.cpp
|
include/stack.cpp
|
#ifndef stack_cpp
#define stack_cpp
#pragma once
#include <iostream>
template <typename T1, typename T2>
void construct(T1 * ptr, T2 const & value) {
new(ptr) T1 (value);
}
template <typename T>
void destroy(T * ptr) noexcept
{
ptr->~T();
}
template <typename FwdIter>
void destroy(FwdIter first, FwdIter last) noexcept
{
for (; first != last; ++first) {
destroy(&*first);
}
}
template <typename T>
class allocator
{
protected:
allocator(size_t size = 0);
~allocator();
auto swap(allocator & other) -> void;
allocator(allocator const &) = delete;
auto operator =(allocator const &) -> allocator & = delete;
T * ptr_;
size_t size_;
size_t count_;
};
template <typename T>
allocator<T>::allocator(size_t size) : ptr_((T*)(operator new(size*sizeof(T)))), size_(size), count_(0){};
template<typename T>
allocator<T>::~allocator()
{
operator delete(ptr_);
}
template<typename T>
auto allocator<T>::swap(allocator & other) -> void
{
std::swap(ptr_, other.ptr_);
std::swap(count_, other.count_);
std::swap(size_, other.size_);
}
template <typename T>
class stack : private allocator<T>
{
public:
stack(size_t size = 0); //noexcept
stack(stack const &); //strong
~stack(); //noexcept
size_t count() const; //noexcept
auto push(T const &) -> void; //strong
void pop(); //basic
const T& top(); //strong
auto operator=(stack const & right)->stack &; //strong
auto empty() const -> bool; //noexcept
};
template<typename T>
auto newcopy(const T * item, size_t size, size_t count) -> T* //strong
{
T * buff = new T[size];
try
{
std::copy(item, item + count, buff);
}
catch (...)
{
delete[] buff;
throw;
}
return buff;
}
template <typename T>
size_t stack<T>::count() const
{
return allocator<T>::count_;
}
template <typename T>
stack<T>::stack(size_t size):allocator<T>(size){}
template<typename T>
stack<T>::stack(stack const & other) : allocator<T>(other.size_)
{
for (size_t i = 0; i < other.count_; i++) construct(allocator<T>::ptr_ + i, other.ptr_[i]);
allocator<T>::count_ = other.count_;
};
template <typename T>
stack<T>::~stack(){}
template<typename T>
void stack<T>::push(T const &item)
{
if (allocator<T>::count_ == allocator<T>::size_)
{
size_t array_size = allocator<T>::size_ * 2 + (allocator<T>::size_ == 0);
stack<T> temp(array_size);
while (temp.count() < allocator<T>::count_) temp.push(allocator<T>::ptr_[temp.count()]);
this->swap(temp);
}
construct(allocator<T>::ptr_ + allocator<T>::count_, item);
++allocator<T>::count_;
}
template<typename T>
void stack<T>::pop()
{
if (allocator<T>::count_ == 0)
{
throw ("Stack is empty!");
}
else
{
allocator<T>::count_--;
}
}
template<typename T>
const T& stack<T>::top()
{
if (allocator<T>::count_ == 0)
{
throw ("Stack is empty!");
}
return allocator<T>::ptr_[allocator<T>::count_ - 1];
}
template<typename T>
auto stack<T>::operator=(stack const & right) -> stack &
{
if (this != &right)
{
stack<T> temp (right.size_);
while (temp.count_ < right.count_)
{
construct(temp.ptr_ + temp.count_, right.ptr_[temp.count_]);
++temp.count_;
}
this -> swap(temp);
}
return *this;
}
template<typename T>
auto stack<T>::empty() const -> bool
{
if (allocator<T>::count_ == 0)
{
return true;
}
else
{
return false;
}
}
#endif
|
#ifndef stack_cpp
#define stack_cpp
#pragma once
#include <iostream>
class bitset
{
public:
explicit
bitset(size_t size);
bitset(bitset const & other) = delete;
auto operator =(bitset const & other)->bitset & = delete;
bitset(bitset && other) = delete;
auto operator =(bitset && other)->bitset & = delete;
auto set(size_t index) -> void;
auto reset(size_t index) -> void;
auto test(size_t index) -> bool;
auto size() const -> size_t;
auto counter() const -> size_t;
private:
std::unique_ptr<bool[]> ptr_;
size_t size_;
size_t counter_;
};
bitset::bitset(size_t size) : ptr_(std::make_unique<bool[]>(size)), size_(size), counter_(0) {}
auto bitset::set(size_t index) -> void
{
if (index < size_)
{
ptr_[index] = true;
++counter_;
}
else throw("false_index");
}
auto bitset::reset(size_t index) -> void
{ if (index < size_)
{
ptr_[index] = false;
--counter_;
}
else throw("false_index");
}
auto bitset::test(size_t index) -> bool
{
if (index < size_)
{
return !ptr_[index];
}
else throw("false_index");
}
auto bitset::size() const -> size_t
{
return size_;
}
auto bitset::counter() const -> size_t
{
return counter_;
}
/*=====================================================================================*/
template <typename T1, typename T2>
void construct(T1 * ptr, T2 const & value) {
new(ptr) T1 (value);
}
template <typename T>
void destroy(T * ptr) noexcept
{
ptr->~T();
}
template <typename FwdIter>
void destroy(FwdIter first, FwdIter last) noexcept
{
for (; first != last; ++first) {
destroy(&*first);
}
}
template <typename T>
class allocator
{
public:
explicit
allocator( std::size_t size = 0 );
allocator( allocator const & other );
auto operator =( allocator const & other ) -> allocator & = delete;
~allocator();
auto resize() -> void;
auto construct(T * ptr, T const & value ) -> void;
auto destroy( T * ptr ) -> void;
auto get() -> T *;
auto get() const -> T const *;
auto count() const -> size_t;
auto full() const -> bool;
auto empty() const -> bool;
private:
auto destroy(T * first, T * last) -> void;
auto swap(allocator & other) -> void;
T * ptr_;
size_t size_;
std::unique_ptr<bitset> map_;
};
template <typename T>
allocator<T>::allocator(size_t size) : ptr_((T*)(operator new(size*sizeof(T)))), size_(size), map_(std::make_unique<bitset>(size)) {};
template<typename T>
allocator<T>::allocator(allocator const& other) :
allocator<T>(other.size_)
{
for (size_t i=0; i < size_; ++i)
if (other.map_->test(i))
construct(ptr_ + i, other.ptr_[i]);
}
template<typename T>
allocator<T>::~allocator()
{
destroy(ptr_, ptr_+size_);
operator delete(ptr_);
}
template<typename T>
auto allocator<T>::resize() -> void
{
allocator<T> buff(size_ * 2 + (size_ == 0));
for (size_t i = 0; i < size_; ++i) construct(buff.ptr_ + i, ptr_[i]);
this->swap(buff);
}
template<typename T>
auto allocator<T>::construct(T * ptr, T const & value)->void
{
if (ptr >= ptr_&&ptr < ptr_ + size_&&map_->test(ptr - ptr_))
{
new(ptr)T(value);
map_->set(ptr - ptr_);
}
else throw("error");
}
template<typename T>
auto allocator<T>::destroy(T * ptr) -> void
{
if(ptr>=ptr_&&ptr<=ptr_+this->count())
{
if (!map_->test(ptr-ptr_))
{
ptr->~T();
map_->reset(ptr-ptr_);
}
}
else throw("error");
}
template<typename T>
auto allocator<T>::destroy(T * first, T * last) -> void
{
if(first>=ptr_&&last<=ptr_+this->count())
for (; first != last; ++first)
{
destroy(&*first);
}
}
template<typename T>
auto allocator<T>::get()-> T*
{
return ptr_;
}
template<typename T>
auto allocator<T>::get() const -> T const *
{
return ptr_;
}
template<typename T>
auto allocator<T>::count() const -> size_t
{
return map_->counter();
}
template<typename T>
auto allocator<T>::full() const -> bool
{
return map_->counter()==size_;
}
template<typename T>
auto allocator<T>::empty() const -> bool
{
return map_->counter()==0;
}
template<typename T>
auto allocator<T>::swap(allocator & other) -> void
{
std::swap(ptr_, other.ptr_);
std::swap(count_, other.count_);
std::swap(size_, other.size_);
}
/*=====================================================================================*/
template <typename T>
class stack : private allocator<T>
{
public:
explicit
stack(size_t size = 0); //noexcept
auto pop() -> void;
auto top() -> T &;
auto top() const -> T const &;
auto push(T const &vaule) -> void; //strong
auto operator=(stack const & right)->stack &; //strong
auto empty() const -> bool; //noexcept
auto count() const -> size_t;
private:
allocator<T> allocator_;
auto throw_is_empty() const -> void;
};
template <typename T>
size_t stack<T>::count() const
{
return allocator_.count();
}
template <typename T>
stack<T>::stack(size_t size):allocator_(size){}
template <typename T>
void stack<T>::push(T const &item)
{
if (allocator_.full()) allocator_.resize();
allocator_.construct(allocator_.get() + this->count(), item);
}
template<typename T>
void stack<T>::pop()
{
if (this->count() > 0)
allocator_.destroy(allocator_.get() + (this->count()-1));
else
throw_is_empty();
}
template<typename T>
auto stack<T>::top() -> T &
{
if (allocator_.count() == 0) {
throw_is_empty();
}
return (*(allocator_.get() + allocator_.count() - 1));
}
template<typename T>
auto stack<T>::top() const -> T const &
{
if (allocator_.count() == 0)
{
throw_is_empty();
}
return (*(allocator_.get() + allocator_.count() - 1));
}
template<typename T>
auto stack<T>::operator=(stack const & right)-> stack &
{
if (this != &right)
{
(allocator<T>(right.allocator_)).swap(allocator_);
}
return *this;
}
template<typename T>
auto stack<T>::empty() const -> bool
{
return allocator_.empty();
}
template<typename T>
auto stack<T>::throw_is_empty() const -> void
{
throw("Stack is empty!");
}
#endif
|
Update stack.cpp
|
Update stack.cpp
|
C++
|
mit
|
tpabahatp/Stack
|
a6aceb179d316311758780dba0014a5ec639a1a3
|
range_tombstone.cc
|
range_tombstone.cc
|
/*
* Copyright (C) 2016 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "range_tombstone.hh"
std::ostream& operator<<(std::ostream& out, const bound_kind k) {
switch(k) {
case bound_kind::excl_end:
return out << "excl end";
case bound_kind::incl_start:
return out << "incl start";
case bound_kind::incl_end:
return out << "incl end";
case bound_kind::excl_start:
return out << "excl start";
}
abort();
}
bound_kind invert_kind(bound_kind k) {
switch(k) {
case bound_kind::excl_start: return bound_kind::incl_end;
case bound_kind::incl_start: return bound_kind::excl_end;
case bound_kind::excl_end: return bound_kind::incl_start;
case bound_kind::incl_end: return bound_kind::excl_start;
}
abort();
}
int32_t weight(bound_kind k) {
switch(k) {
case bound_kind::excl_end:
case bound_kind::incl_start:
return -1;
case bound_kind::incl_end:
case bound_kind::excl_start:
return 1;
}
abort();
}
const thread_local clustering_key_prefix bound_view::empty_prefix = clustering_key::make_empty();
std::ostream& operator<<(std::ostream& out, const range_tombstone& rt) {
if (rt) {
return out << "{range_tombstone: start=" << rt.start_bound() << ", end=" << rt.end_bound() << ", " << rt.tomb << "}";
} else {
return out << "{range_tombstone: none}";
}
}
|
/*
* Copyright (C) 2016 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#include "range_tombstone.hh"
std::ostream& operator<<(std::ostream& out, const bound_kind k) {
switch(k) {
case bound_kind::excl_end:
return out << "excl end";
case bound_kind::incl_start:
return out << "incl start";
case bound_kind::incl_end:
return out << "incl end";
case bound_kind::excl_start:
return out << "excl start";
}
abort();
}
bound_kind invert_kind(bound_kind k) {
switch(k) {
case bound_kind::excl_start: return bound_kind::incl_end;
case bound_kind::incl_start: return bound_kind::excl_end;
case bound_kind::excl_end: return bound_kind::incl_start;
case bound_kind::incl_end: return bound_kind::excl_start;
}
abort();
}
int32_t weight(bound_kind k) {
switch(k) {
case bound_kind::excl_end:
return -2;
case bound_kind::incl_start:
return -1;
case bound_kind::incl_end:
return 1;
case bound_kind::excl_start:
return 2;
}
abort();
}
const thread_local clustering_key_prefix bound_view::empty_prefix = clustering_key::make_empty();
std::ostream& operator<<(std::ostream& out, const range_tombstone& rt) {
if (rt) {
return out << "{range_tombstone: start=" << rt.start_bound() << ", end=" << rt.end_bound() << ", " << rt.tomb << "}";
} else {
return out << "{range_tombstone: none}";
}
}
|
fix bound ordering
|
range_tombstone: fix bound ordering
Assuming the clustering keys are equal:
excl_end < incl_start < incl_end < excl_start.
Signed-off-by: Paweł Dziepak <[email protected]>
|
C++
|
agpl-3.0
|
scylladb/scylla,scylladb/scylla,scylladb/scylla,duarten/scylla,raphaelsc/scylla,kjniemi/scylla,avikivity/scylla,duarten/scylla,avikivity/scylla,kjniemi/scylla,duarten/scylla,raphaelsc/scylla,avikivity/scylla,scylladb/scylla,raphaelsc/scylla,kjniemi/scylla
|
c8125f357e5c551b15e81570281f73579760383b
|
include/BEdge.hpp
|
include/BEdge.hpp
|
#ifndef BEDGE
#define BEDGE
#include <utility>
#include "BVect.hpp"
#include "DominanceStatus.hpp"
class BEdge {
private:
BVect _a;
BVect _b;
bool _aClosed;
bool _bClosed;
bool _point;
public:
BEdge() {}
BEdge (BVect a, BVect b, bool aC = true, bool bC = true) : _a(a), _b(b), _aClosed(aC), _bClosed(bC), _point(a==b) {}
BEdge (BVect a) : _a(a), _b(a), _aClosed(true), _bClosed(true), _point(true) {}
BVect leftPoint() const {return _a;}
BVect rightPoint() const {return _b;}
bool isAPoint() const {return _point;}
bool isInA1AreaOf(const BEdge& be) const {
return (this->rightPoint().isInA1AreaOf(be.leftPoint()));
}
bool isInA2AreaOf(const BEdge& be) const {
return be.isInA1AreaOf(*this);
}
std::pair<double, double> computeLambdasWithPoint(const BVect& bv) const {
std::pair<double, double> lambdas;
if (this->leftPoint().z1() <= bv.z1() && bv.z1() <= this->rightPoint().z1())
lambdas.first = ((this->rightPoint().z1() - bv.z1()) / ( this->rightPoint().z1() - this->leftPoint().z1()));
else lambdas.first = 1;
if (this->rightPoint().z2() <= bv.z2() && bv.z2() <= this->leftPoint().z2())
lambdas.second = ((bv.z2() - this->rightPoint().z2()) / ( this->leftPoint().z2() - this->rightPoint().z2()));
else lambdas.second = 0;
return lambdas;
}
std::pair<BVect, BVect> computeProjWithPoint(const BVect& bv) const {
std::pair<BVect, BVect> projections;
if (this->leftPoint().z1() <= bv.z1() && bv.z1() <= this->rightPoint().z1()) {
double lambda = ((this->rightPoint().z1() - bv.z1()) / ( this->rightPoint().z1() - this->leftPoint().z1()));
BVect p(this->leftPoint(), this->rightPoint(), lambda);
projections.first = BVect(bv.z1(), p.z2(), p.x());
} else {
projections.first = this->leftPoint();
}
if (this->rightPoint().z2() <= bv.z2() && bv.z2() <= this->leftPoint().z2()) {
double lambda = ((bv.z2() - this->rightPoint().z2()) / ( this->leftPoint().z2() - this->rightPoint().z2()));
BVect p(this->leftPoint(), this->rightPoint(), lambda);
projections.second = BVect(p.z1(), bv.z2(), p.x());
} else {
projections.second = this->rightPoint();
}
return projections;
}
DominanceStatus compareWithPoint(const BEdge& be, BEdge& tleft, BEdge& tright) const {
if (this->isInA1AreaOf(be) || this->isInA2AreaOf(be))
return DominanceStatus::NO_DOM;
BVect bv = be.leftPoint();
if (this->leftPoint().weaklyDominates(bv) && this->rightPoint().weaklyDominates(bv))
return DominanceStatus::A_DOM_B;
if (bv.weaklyDominates(this->leftPoint()) && bv.weaklyDominates(this->rightPoint()))
return DominanceStatus::B_DOM_A;
std::pair<BVect, BVect> projs = computeProjWithPoint(bv);
BVect proj1 = projs.first;
BVect proj2 = projs.second;
if (proj1.weaklyDominates(bv))
return DominanceStatus::A_DOM_B;
else {
if (proj1 != this->leftPoint())
tleft = BEdge(this->leftPoint(), proj1);
if (proj2 != this->rightPoint())
tright = BEdge(proj2, this->rightPoint());
return DominanceStatus::B_PART_DOM_A;
}
}
bool intersect(const BEdge& be, BVect& i1, BVect& i2) const {
double Az1 = this->leftPoint().z1();
double Az2 = this->leftPoint().z2();
double Cz1 = be.leftPoint().z1();
double Cz2 = be.leftPoint().z2();
double Iz1 = this->rightPoint().z1() - Az1;
double Iz2 = this->rightPoint().z2() - Az2;
double Jz1 = be.rightPoint().z1() - Cz1;
double Jz2 = be.rightPoint().z2() - Cz2;
double lambda = (Iz1*Cz1 - Iz1*Az1 - Iz2*Cz2 + Iz2*Az2) / (Iz1*Jz2 - Iz2*Jz1);
double mu = (Iz2*Cz1 - Iz2*Az1 - Iz1*Cz2 + Iz1*Az2) / (Iz1*Jz2 - Iz2*Jz1);
if (0 < lambda && lambda < 1 && 0 < mu && mu < 1) {
i1 = BVect(this->leftPoint(), this->rightPoint(), lambda);
i2 = BVect(be.leftPoint(), be.rightPoint(), mu);
return true;
} else {
return false;
}
}
DominanceStatus compareLeftEdges(BEdge& t, BEdge& b) const {
if (t.leftPoint().weaklyDominates(b.leftPoint()))
return DominanceStatus::A_DOM_B;
else if (t.leftPoint().isInA1AreaOf(b.leftPoint())) {
std::pair<BVect, BVect> projs = t.computeProjWithPoint(b.leftPoint());
BVect proj1 = projs.first;
BVect proj2 = projs.second;
if (b.leftPoint().dominates(proj1)) {
t = BEdge(t.leftPoint(), proj1);
return DominanceStatus::B_PART_DOM_A;
} else {
return DominanceStatus::A_DOM_B;
}
} else {
return invert(compareLeftEdges(b, t));
}
}
DominanceStatus compareRightEdges(BEdge& t, BEdge& b) const {
if (t.rightPoint().weaklyDominates(b.rightPoint()))
return DominanceStatus::A_DOM_B;
else if (t.rightPoint().isInA2AreaOf(b.rightPoint())) {
std::pair<BVect, BVect> projs = t.computeProjWithPoint(b.rightPoint());
BVect proj1 = projs.first;
BVect proj2 = projs.second;
if (b.rightPoint().dominates(proj2)) {
t = BEdge(proj2, t.rightPoint());
return DominanceStatus::B_PART_DOM_A;
} else {
return DominanceStatus::A_DOM_B;
}
} else {
return invert(compareRightEdges(b, t));
}
}
DominanceStatus compareWith(const BEdge& be, BEdge& tleft, BEdge& tright, BEdge& beleft, BEdge& beright) const {
if (this->isAPoint() && be.isAPoint()) {
if (this->leftPoint().dominates(be.leftPoint()))
return DominanceStatus::A_DOM_B;
else if (be.leftPoint().dominates(this->leftPoint()))
return DominanceStatus::B_DOM_A;
else return DominanceStatus::NO_DOM;
} else if (this->isAPoint()) {
return invert(be.compareWithPoint(*this, tleft, tright));
} else if (be.isAPoint()) {
return this->compareWithPoint(be, beleft, beright);
} else {
BVect intThis;
BVect intBe;
if (this->intersect(be, intThis, intBe)) {
tleft = BEdge(this->leftPoint(), intThis);
tright = BEdge(intThis, this->rightPoint());
beleft = BEdge(be.leftPoint(), intBe);
beright = BEdge(intBe, be.rightPoint());
DominanceStatus left = compareLeftEdges(tleft, beleft);
DominanceStatus right = compareRightEdges(tright, beright);
return DominanceStatus::MUTUAL_DOM;
} else {
if (this->isInA1AreaOf(be) || this->isInA2AreaOf(be))
return DominanceStatus::NO_DOM;
std::pair<BVect, BVect> projb1 = this->computeProjWithPoint(be.leftPoint());
BVect proj1bleft = projb1.first;
BVect proj2bleft = projb1.second;
std::pair<BVect, BVect> projb2 = this->computeProjWithPoint(be.rightPoint());
BVect proj1bright = projb2.first;
BVect proj2bright = projb2.second;
std::pair<BVect, BVect> projt1 = be.computeProjWithPoint(this->leftPoint());
BVect proj1tleft = projt1.first;
BVect proj2tleft = projt1.second;
std::pair<BVect, BVect> projt2 = be.computeProjWithPoint(this->rightPoint());
BVect proj1tright = projt2.first;
BVect proj2tright = projt2.second;
bool adomb = false;
bool bdoma = false;
bool apartdomb = false;
bool bpartdoma = false;
if (be.leftPoint().weaklyDominates(proj1bleft)) {
bdoma = true;
if (proj1bleft != this->leftPoint()) {
tleft = BEdge(this->leftPoint(), proj1bleft);
bpartdoma = true;
}
}
if (be.rightPoint().weaklyDominates(proj2bright)) {
bdoma = true;
if (proj2bright != this->rightPoint()) {
tright = BEdge(proj2bright, this->rightPoint());
bpartdoma = true;
}
}
if (proj2bleft.weaklyDominates(be.leftPoint())) {
adomb = true;
}
if (proj1bright.weaklyDominates(be.rightPoint())) {
adomb = true;
}
if (this->leftPoint().weaklyDominates(proj1tleft)) {
adomb = true;
if (proj1tleft != be.leftPoint()) {
beleft = BEdge(be.leftPoint(), proj1tleft);
apartdomb = true;
}
}
if (this->rightPoint().weaklyDominates(proj2tright)) {
adomb = true;
if (proj2tright != be.rightPoint()) {
beright = BEdge(proj2tright, be.rightPoint());
apartdomb = true;
}
}
if (proj2tleft.weaklyDominates(this->leftPoint())) {
bdoma = true;
}
if (proj1tright.weaklyDominates(this->rightPoint())) {
bdoma = true;
}
if (adomb && bdoma)
return DominanceStatus::MUTUAL_DOM;
if (apartdomb)
return DominanceStatus::A_PART_DOM_B;
if (adomb)
return DominanceStatus::A_DOM_B;
if (bpartdoma)
return DominanceStatus::B_PART_DOM_A;
if (bdoma)
return DominanceStatus::B_DOM_A;
return DominanceStatus::NO_DOM;
}
}
}
};
#endif
|
#ifndef BEDGE
#define BEDGE
#include <utility>
#include "BVect.hpp"
#include "DominanceStatus.hpp"
class BEdge {
private:
BVect _a;
BVect _b;
bool _aClosed;
bool _bClosed;
bool _point;
public:
BEdge() {}
BEdge (BVect a, BVect b, bool aC = true, bool bC = true) : _a(a), _b(b), _aClosed(aC), _bClosed(bC), _point(a==b) {}
BEdge (BVect a) : _a(a), _b(a), _aClosed(true), _bClosed(true), _point(true) {}
BVect leftPoint() const {return _a;}
BVect rightPoint() const {return _b;}
bool isAPoint() const {return _point;}
bool isInA1AreaOf(const BEdge& be) const {
return (this->rightPoint().isInA1AreaOf(be.leftPoint()));
}
bool isInA2AreaOf(const BEdge& be) const {
return be.isInA1AreaOf(*this);
}
std::pair<double, double> computeLambdasWithPoint(const BVect& bv) const {
std::pair<double, double> lambdas;
if (this->leftPoint().z1() <= bv.z1() && bv.z1() <= this->rightPoint().z1())
lambdas.first = ((this->rightPoint().z1() - bv.z1()) / ( this->rightPoint().z1() - this->leftPoint().z1()));
else lambdas.first = 1;
if (this->rightPoint().z2() <= bv.z2() && bv.z2() <= this->leftPoint().z2())
lambdas.second = ((bv.z2() - this->rightPoint().z2()) / ( this->leftPoint().z2() - this->rightPoint().z2()));
else lambdas.second = 0;
return lambdas;
}
std::pair<BVect, BVect> computeProjWithPoint(const BVect& bv) const {
std::pair<BVect, BVect> projections;
if (this->leftPoint().z1() <= bv.z1() && bv.z1() <= this->rightPoint().z1()) {
double lambda = ((this->rightPoint().z1() - bv.z1()) / ( this->rightPoint().z1() - this->leftPoint().z1()));
BVect p(this->leftPoint(), this->rightPoint(), lambda);
projections.first = BVect(bv.z1(), p.z2(), p.x());
} else {
projections.first = this->leftPoint();
}
if (this->rightPoint().z2() <= bv.z2() && bv.z2() <= this->leftPoint().z2()) {
double lambda = ((bv.z2() - this->rightPoint().z2()) / ( this->leftPoint().z2() - this->rightPoint().z2()));
BVect p(this->leftPoint(), this->rightPoint(), lambda);
projections.second = BVect(p.z1(), bv.z2(), p.x());
} else {
projections.second = this->rightPoint();
}
return projections;
}
DominanceStatus compareWithPoint(const BEdge& be, BEdge& tleft, BEdge& tright) const {
if (this->isInA1AreaOf(be) || this->isInA2AreaOf(be))
return DominanceStatus::NO_DOM;
BVect bv = be.leftPoint();
if (this->leftPoint().weaklyDominates(bv) && this->rightPoint().weaklyDominates(bv))
return DominanceStatus::A_DOM_B;
if (bv.weaklyDominates(this->leftPoint()) && bv.weaklyDominates(this->rightPoint()))
return DominanceStatus::B_DOM_A;
std::pair<BVect, BVect> projs = computeProjWithPoint(bv);
BVect proj1 = projs.first;
BVect proj2 = projs.second;
if (proj1.weaklyDominates(bv))
return DominanceStatus::A_DOM_B;
else {
if (proj1 != this->leftPoint())
tleft = BEdge(this->leftPoint(), proj1);
if (proj2 != this->rightPoint())
tright = BEdge(proj2, this->rightPoint());
return DominanceStatus::B_PART_DOM_A;
}
}
bool intersect(const BEdge& be, BVect& i1, BVect& i2) const {
double Az1 = this->rightPoint().z1();
double Az2 = this->rightPoint().z2();
double Cz1 = be.rightPoint().z1();
double Cz2 = be.rightPoint().z2();
double Iz1 = this->leftPoint().z1() - Az1;
double Iz2 = this->leftPoint().z2() - Az2;
double Jz1 = be.leftPoint().z1() - Cz1;
double Jz2 = be.leftPoint().z2() - Cz2;
double lambda = (Iz2*Cz1 - Iz2*Az1 - Iz1*Cz2 + Iz1*Az2) / (Iz1*Jz2 - Iz2*Jz1);
double mu = (Jz2*Cz1 - Jz2*Az1 - Jz1*Cz2 + Jz1*Az2) / (Iz1*Jz2 - Iz2*Jz1);
if (0 < lambda && lambda < 1 && 0 < mu && mu < 1) {
i1 = BVect(this->leftPoint(), this->rightPoint(), mu);
i2 = BVect(be.leftPoint(), be.rightPoint(), lambda);
return true;
} else {
return false;
}
}
DominanceStatus compareLeftEdges(BEdge& t, BEdge& b) const {
if (t.leftPoint().weaklyDominates(b.leftPoint()))
return DominanceStatus::A_DOM_B;
else if (t.leftPoint().isInA1AreaOf(b.leftPoint())) {
std::pair<BVect, BVect> projs = t.computeProjWithPoint(b.leftPoint());
BVect proj1 = projs.first;
BVect proj2 = projs.second;
if (b.leftPoint().dominates(proj1)) {
t = BEdge(t.leftPoint(), proj1);
return DominanceStatus::B_PART_DOM_A;
} else {
return DominanceStatus::A_DOM_B;
}
} else {
return invert(compareLeftEdges(b, t));
}
}
DominanceStatus compareRightEdges(BEdge& t, BEdge& b) const {
if (t.rightPoint().weaklyDominates(b.rightPoint()))
return DominanceStatus::A_DOM_B;
else if (t.rightPoint().isInA2AreaOf(b.rightPoint())) {
std::pair<BVect, BVect> projs = t.computeProjWithPoint(b.rightPoint());
BVect proj1 = projs.first;
BVect proj2 = projs.second;
if (b.rightPoint().dominates(proj2)) {
t = BEdge(proj2, t.rightPoint());
return DominanceStatus::B_PART_DOM_A;
} else {
return DominanceStatus::A_DOM_B;
}
} else {
return invert(compareRightEdges(b, t));
}
}
DominanceStatus compareWith(const BEdge& be, BEdge& tleft, BEdge& tright, BEdge& beleft, BEdge& beright) const {
if (this->isAPoint() && be.isAPoint()) {
if (this->leftPoint().dominates(be.leftPoint()))
return DominanceStatus::A_DOM_B;
else if (be.leftPoint().dominates(this->leftPoint()))
return DominanceStatus::B_DOM_A;
else return DominanceStatus::NO_DOM;
} else if (this->isAPoint()) {
return invert(be.compareWithPoint(*this, tleft, tright));
} else if (be.isAPoint()) {
return this->compareWithPoint(be, beleft, beright);
} else {
BVect intThis;
BVect intBe;
if (this->intersect(be, intThis, intBe)) {
tleft = BEdge(this->leftPoint(), intThis);
tright = BEdge(intThis, this->rightPoint());
beleft = BEdge(be.leftPoint(), intBe);
beright = BEdge(intBe, be.rightPoint());
DominanceStatus left = compareLeftEdges(tleft, beleft);
DominanceStatus right = compareRightEdges(tright, beright);
return DominanceStatus::MUTUAL_DOM;
} else {
if (this->isInA1AreaOf(be) || this->isInA2AreaOf(be))
return DominanceStatus::NO_DOM;
std::pair<BVect, BVect> projb1 = this->computeProjWithPoint(be.leftPoint());
BVect proj1bleft = projb1.first;
BVect proj2bleft = projb1.second;
std::pair<BVect, BVect> projb2 = this->computeProjWithPoint(be.rightPoint());
BVect proj1bright = projb2.first;
BVect proj2bright = projb2.second;
std::pair<BVect, BVect> projt1 = be.computeProjWithPoint(this->leftPoint());
BVect proj1tleft = projt1.first;
BVect proj2tleft = projt1.second;
std::pair<BVect, BVect> projt2 = be.computeProjWithPoint(this->rightPoint());
BVect proj1tright = projt2.first;
BVect proj2tright = projt2.second;
bool adomb = false;
bool bdoma = false;
bool apartdomb = false;
bool bpartdoma = false;
if (be.leftPoint().weaklyDominates(proj1bleft)) {
bdoma = true;
if (proj1bleft != this->leftPoint()) {
tleft = BEdge(this->leftPoint(), proj1bleft);
bpartdoma = true;
}
}
if (be.rightPoint().weaklyDominates(proj2bright)) {
bdoma = true;
if (proj2bright != this->rightPoint()) {
tright = BEdge(proj2bright, this->rightPoint());
bpartdoma = true;
}
}
if (proj2bleft.weaklyDominates(be.leftPoint())) {
adomb = true;
}
if (proj1bright.weaklyDominates(be.rightPoint())) {
adomb = true;
}
if (this->leftPoint().weaklyDominates(proj1tleft)) {
adomb = true;
if (proj1tleft != be.leftPoint()) {
beleft = BEdge(be.leftPoint(), proj1tleft);
apartdomb = true;
}
}
if (this->rightPoint().weaklyDominates(proj2tright)) {
adomb = true;
if (proj2tright != be.rightPoint()) {
beright = BEdge(proj2tright, be.rightPoint());
apartdomb = true;
}
}
if (proj2tleft.weaklyDominates(this->leftPoint())) {
bdoma = true;
}
if (proj1tright.weaklyDominates(this->rightPoint())) {
bdoma = true;
}
if (adomb && bdoma)
return DominanceStatus::MUTUAL_DOM;
if (apartdomb)
return DominanceStatus::A_PART_DOM_B;
if (adomb)
return DominanceStatus::A_DOM_B;
if (bpartdoma)
return DominanceStatus::B_PART_DOM_A;
if (bdoma)
return DominanceStatus::B_DOM_A;
return DominanceStatus::NO_DOM;
}
}
}
};
#endif
|
Fix intersection computation
|
BEdge: Fix intersection computation
|
C++
|
lgpl-2.1
|
tvincent2/mo-utils
|
9d39163a6f723cd555f26286e34c44f6fb01db6c
|
include/Utils.hpp
|
include/Utils.hpp
|
//=======================================================================
// Copyright Baptiste Wicht 2011.
// 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)
//=======================================================================
#ifndef UTILS_H
#define UTILS_H
#include <sstream>
namespace eddic {
template <typename T>
T toNumber (std::string text) {
std::stringstream ss(text);
T result;
ss >> result;
return result;
}
template <typename T>
std::string toString(T number) {
std::stringstream out;
out << number;
return out.str();
}
class deleter {
public:
template <typename T>
void operator()(const T& x) const {
delete x;
}
};
} //end of eddic
#endif
|
//=======================================================================
// Copyright Baptiste Wicht 2011.
// 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)
//=======================================================================
#ifndef UTILS_H
#define UTILS_H
#include <sstream>
namespace eddic {
template <typename T>
T toNumber (std::string text) {
std::stringstream ss(text);
T result;
ss >> result;
return result;
}
template <typename T>
std::string toString(T number) {
std::stringstream out;
out << number;
return out.str();
}
} //end of eddic
#endif
|
Remove useless deleter functor
|
Remove useless deleter functor
|
C++
|
mit
|
wichtounet/eddic,vogelsgesang/eddic,wichtounet/eddic,vogelsgesang/eddic,vogelsgesang/eddic,wichtounet/eddic
|
e283fdf4ae25f0ec10cee32217b026b530b2cc0a
|
src/engine/entity/src/world.cpp
|
src/engine/entity/src/world.cpp
|
#include <iostream>
#include <chrono>
#include <halley/support/exception.h>
#include <halley/data_structures/memory_pool.h>
#include <halley/utils/utils.h>
#include "world.h"
#include "system.h"
#include "family.h"
#include "halley/text/string_converter.h"
#include "halley/support/debug.h"
#include "halley/file_formats/config_file.h"
using namespace Halley;
World::World(const HalleyAPI* api, bool collectMetrics, CreateComponentFunction createComponent)
: api(api)
, createComponent(std::move(createComponent))
, collectMetrics(collectMetrics)
{
}
World::~World()
{
for (auto& f: families) {
//f.second->clearEntities();
f->clearEntities();
}
for (auto& tl: systems) {
tl.clear();
}
for (auto e: entitiesPendingCreation) {
deleteEntity(e);
}
for (auto e: entities) {
deleteEntity(e);
}
families.clear();
services.clear();
}
System& World::addSystem(std::unique_ptr<System> system, TimeLine timelineType)
{
system->api = api;
system->setCollectSamples(collectMetrics);
auto& ref = *system.get();
auto& timeline = getSystems(timelineType);
timeline.emplace_back(std::move(system));
ref.onAddedToWorld(*this, int(timeline.size()));
return ref;
}
void World::removeSystem(System& system)
{
for (auto& sys : systems) {
for (size_t i = 0; i < sys.size(); i++) {
if (sys[i].get() == &system) {
sys.erase(sys.begin() + i);
return;
}
}
}
}
Vector<std::unique_ptr<System>>& World::getSystems(TimeLine timeline)
{
return systems[static_cast<int>(timeline)];
}
const Vector<std::unique_ptr<System>>& World::getSystems(TimeLine timeline) const
{
return systems[static_cast<int>(timeline)];
}
Vector<System*> World::getSystems()
{
size_t n = 0;
for (auto& tl : systems) {
n += tl.size();
}
Vector<System*> result(n);
int i = 0;
for (auto& tl : systems) {
for (auto& s : tl) {
result[i++] = s.get();
}
}
return result;
}
System& World::getSystem(const String& name)
{
for (auto& tl : systems) {
for (auto& s : tl) {
if (s->name == name) {
return *s.get();
}
}
}
throw Exception("System not found: " + name, HalleyExceptions::Entity);
}
Service& World::addService(std::shared_ptr<Service> service)
{
auto& ref = *service;
services[service->getName()] = std::move(service);
return ref;
}
void World::loadSystems(const ConfigNode& root, std::function<std::unique_ptr<System>(String)> createFunction)
{
auto timelines = root["timelines"].asMap();
for (auto iter = timelines.begin(); iter != timelines.end(); ++iter) {
String timelineName = iter->first;
TimeLine timeline;
if (timelineName == "fixedUpdate") {
timeline = TimeLine::FixedUpdate;
} else if (timelineName == "variableUpdate") {
timeline = TimeLine::VariableUpdate;
} else if (timelineName == "render") {
timeline = TimeLine::Render;
} else {
throw Exception("Unknown timeline: " + timelineName, HalleyExceptions::Entity);
}
for (auto& sysName: iter->second) {
String name = sysName.asString();
addSystem(createFunction(name + "System"), timeline).setName(name);
}
}
}
Service& World::getService(const String& name) const
{
auto iter = services.find(name);
if (iter == services.end()) {
throw Exception("Service not found: " + name, HalleyExceptions::Entity);
}
return *iter->second;
}
EntityRef World::createEntity(String name)
{
Entity* entity = new(PoolAllocator<Entity>::alloc()) Entity();
if (entity == nullptr) {
throw Exception("Error creating entity - out of memory?", HalleyExceptions::Entity);
}
entitiesPendingCreation.push_back(entity);
allocateEntity(entity);
auto e = EntityRef(*entity, *this);
e.setName(std::move(name));
return e;
}
void World::destroyEntity(EntityId id)
{
auto e = tryGetEntity(id);
if (e) {
e->destroy();
entityDirty = true;
}
}
EntityRef World::getEntity(EntityId id)
{
Entity* entity = tryGetEntity(id);
if (entity == nullptr) {
throw Exception("Entity does not exist: " + toString(id), HalleyExceptions::Entity);
}
return EntityRef(*entity, *this);
}
Entity* World::tryGetEntity(EntityId id)
{
auto v = entityMap.get(id.value);
if (v == nullptr) {
return nullptr;
}
return *v;
}
size_t World::numEntities() const
{
return entities.size();
}
std::vector<EntityRef> World::getEntities()
{
std::vector<EntityRef> result;
result.reserve(entities.size());
for (auto& e: entities) {
result.push_back(EntityRef(*e, *this));
}
return result;
}
void World::onEntityDirty()
{
entityDirty = true;
}
const World::CreateComponentFunction& World::getCreateComponentFunction() const
{
return createComponent;
}
void World::deleteEntity(Entity* entity)
{
Expects (entity);
entity->~Entity();
PoolAllocator<Entity>::free(entity);
}
bool World::hasSystemsOnTimeLine(TimeLine timeline) const
{
return getSystems(timeline).size() > 0;
}
int64_t World::getAverageTime(TimeLine timeline) const
{
return timer[int(timeline)].averageElapsedNanoSeconds();
}
void World::step(TimeLine timeline, Time elapsed)
{
auto& t = timer[int(timeline)];
if (collectMetrics) {
t.beginSample();
}
spawnPending();
initSystems();
updateSystems(timeline, elapsed);
if (collectMetrics) {
t.endSample();
}
}
void World::render(RenderContext& rc) const
{
auto& t = timer[int(TimeLine::Render)];
if (collectMetrics) {
t.beginSample();
}
renderSystems(rc);
if (collectMetrics) {
t.endSample();
}
}
void World::allocateEntity(Entity* entity) {
auto res = entityMap.alloc();
*res.first = entity;
entity->uid.value = res.second;
}
void World::spawnPending()
{
if (!entitiesPendingCreation.empty()) {
HALLEY_DEBUG_TRACE();
for (auto& e : entitiesPendingCreation) {
e->onReady();
}
std::move(entitiesPendingCreation.begin(), entitiesPendingCreation.end(), std::insert_iterator<decltype(entities)>(entities, entities.end()));
entitiesPendingCreation.clear();
entityDirty = true;
HALLEY_DEBUG_TRACE();
}
updateEntities();
}
void World::updateEntities()
{
if (!entityDirty) {
return;
}
HALLEY_DEBUG_TRACE();
size_t nEntities = entities.size();
std::vector<size_t> entitiesRemoved;
struct FamilyTodo {
std::vector<Entity*> toAdd;
std::vector<Entity*> toRemove;
};
std::map<FamilyMaskType, FamilyTodo> pending;
// Update all entities
// This loop should be as fast as reasonably possible
for (size_t i = 0; i < nEntities; i++) {
auto& entity = *entities[i];
if (i + 20 < nEntities) { // Watch out for sign! Don't subtract!
prefetchL2(entities[i + 20]);
}
// Check if it needs any sort of updating
if (entity.needsRefresh()) {
// First of all, let's check if it's dead
if (!entity.isAlive()) {
// Remove from systems
pending[entity.getMask()].toRemove.push_back(&entity);
entitiesRemoved.push_back(i);
} else {
// It's alive, so check old and new system inclusions
FamilyMaskType oldMask = entity.getMask();
entity.refresh();
FamilyMaskType newMask = entity.getMask();
// Did it change?
if (oldMask != newMask) {
pending[oldMask].toRemove.push_back(&entity);
pending[newMask].toAdd.push_back(&entity);
}
}
}
}
HALLEY_DEBUG_TRACE();
for (auto& todo: pending) {
for (auto& fam: getFamiliesFor(todo.first)) {
for (auto& e: todo.second.toRemove) {
fam->removeEntity(*e);
}
for (auto& e: todo.second.toAdd) {
fam->addEntity(*e);
}
}
}
HALLEY_DEBUG_TRACE();
// Update families
for (auto& iter : families) {
iter->updateEntities();
}
HALLEY_DEBUG_TRACE();
// Actually remove dead entities
if (!entitiesRemoved.empty()) {
size_t livingEntityCount = entities.size();
for (int i = int(entitiesRemoved.size()); --i >= 0; ) {
size_t idx = entitiesRemoved[i];
auto& entity = *entities[idx];
// Remove
entityMap.freeId(entity.getEntityId().value);
deleteEntity(&entity);
// Put it at the back of the array, so it's removed when the array gets resized
std::swap(entities[idx], entities[--livingEntityCount]);
}
entities.resize(livingEntityCount);
}
entityDirty = false;
HALLEY_DEBUG_TRACE();
}
void World::initSystems()
{
for (auto& tl: systems) {
for (auto& system : tl) {
// If the system is initialised, also check for any entities that need spawning
if (system->tryInit()) {
spawnPending();
}
}
}
}
void World::updateSystems(TimeLine timeline, Time time)
{
for (auto& system : getSystems(timeline)) {
system->doUpdate(time);
spawnPending();
}
}
void World::renderSystems(RenderContext& rc) const
{
for (auto& system : getSystems(TimeLine::Render)) {
system->doRender(rc);
}
}
void World::onAddFamily(Family& family)
{
// Add any existing entities to this new family
size_t nEntities = entities.size();
for (size_t i = 0; i < nEntities; i++) {
auto& entity = *entities[i];
auto eMask = entity.getMask();
auto fMask = family.inclusionMask;
if ((eMask & fMask) == fMask) {
family.addEntity(entity);
}
}
familyCache.clear();
}
const std::vector<Family*>& World::getFamiliesFor(const FamilyMaskType& mask)
{
auto i = familyCache.find(mask);
if (i != familyCache.end()) {
return i->second;
} else {
std::vector<Family*> result;
for (auto& iter : families) {
auto& family = *iter;
FamilyMaskType famMask = family.inclusionMask;
if (mask.contains(famMask)) {
result.push_back(&family);
}
}
familyCache[mask] = std::move(result);
return familyCache[mask];
}
}
|
#include <iostream>
#include <chrono>
#include <halley/support/exception.h>
#include <halley/data_structures/memory_pool.h>
#include <halley/utils/utils.h>
#include "world.h"
#include "system.h"
#include "family.h"
#include "halley/text/string_converter.h"
#include "halley/support/debug.h"
#include "halley/file_formats/config_file.h"
using namespace Halley;
World::World(const HalleyAPI* api, bool collectMetrics, CreateComponentFunction createComponent)
: api(api)
, createComponent(std::move(createComponent))
, collectMetrics(collectMetrics)
{
}
World::~World()
{
for (auto& f: families) {
//f.second->clearEntities();
f->clearEntities();
}
for (auto& tl: systems) {
tl.clear();
}
for (auto e: entitiesPendingCreation) {
deleteEntity(e);
}
for (auto e: entities) {
deleteEntity(e);
}
families.clear();
services.clear();
}
System& World::addSystem(std::unique_ptr<System> system, TimeLine timelineType)
{
system->api = api;
system->setCollectSamples(collectMetrics);
auto& ref = *system.get();
auto& timeline = getSystems(timelineType);
timeline.emplace_back(std::move(system));
ref.onAddedToWorld(*this, int(timeline.size()));
return ref;
}
void World::removeSystem(System& system)
{
for (auto& sys : systems) {
for (size_t i = 0; i < sys.size(); i++) {
if (sys[i].get() == &system) {
sys.erase(sys.begin() + i);
return;
}
}
}
}
Vector<std::unique_ptr<System>>& World::getSystems(TimeLine timeline)
{
return systems[static_cast<int>(timeline)];
}
const Vector<std::unique_ptr<System>>& World::getSystems(TimeLine timeline) const
{
return systems[static_cast<int>(timeline)];
}
Vector<System*> World::getSystems()
{
size_t n = 0;
for (auto& tl : systems) {
n += tl.size();
}
Vector<System*> result(n);
int i = 0;
for (auto& tl : systems) {
for (auto& s : tl) {
result[i++] = s.get();
}
}
return result;
}
System& World::getSystem(const String& name)
{
for (auto& tl : systems) {
for (auto& s : tl) {
if (s->name == name) {
return *s.get();
}
}
}
throw Exception("System not found: " + name, HalleyExceptions::Entity);
}
Service& World::addService(std::shared_ptr<Service> service)
{
auto& ref = *service;
services[service->getName()] = std::move(service);
return ref;
}
void World::loadSystems(const ConfigNode& root, std::function<std::unique_ptr<System>(String)> createFunction)
{
auto timelines = root["timelines"].asMap();
for (auto iter = timelines.begin(); iter != timelines.end(); ++iter) {
String timelineName = iter->first;
TimeLine timeline;
if (timelineName == "fixedUpdate") {
timeline = TimeLine::FixedUpdate;
} else if (timelineName == "variableUpdate") {
timeline = TimeLine::VariableUpdate;
} else if (timelineName == "render") {
timeline = TimeLine::Render;
} else {
throw Exception("Unknown timeline: " + timelineName, HalleyExceptions::Entity);
}
for (auto& sysName: iter->second) {
String name = sysName.asString();
addSystem(createFunction(name + "System"), timeline).setName(name);
}
}
}
Service& World::getService(const String& name) const
{
auto iter = services.find(name);
if (iter == services.end()) {
throw Exception("Service not found: " + name, HalleyExceptions::Entity);
}
return *iter->second;
}
EntityRef World::createEntity(String name)
{
Entity* entity = new(PoolAllocator<Entity>::alloc()) Entity();
if (entity == nullptr) {
throw Exception("Error creating entity - out of memory?", HalleyExceptions::Entity);
}
entitiesPendingCreation.push_back(entity);
allocateEntity(entity);
auto e = EntityRef(*entity, *this);
e.setName(std::move(name));
return e;
}
void World::destroyEntity(EntityId id)
{
auto e = tryGetEntity(id);
if (e) {
e->destroy();
entityDirty = true;
}
}
EntityRef World::getEntity(EntityId id)
{
Entity* entity = tryGetEntity(id);
if (entity == nullptr) {
throw Exception("Entity does not exist: " + toString(id), HalleyExceptions::Entity);
}
return EntityRef(*entity, *this);
}
Entity* World::tryGetEntity(EntityId id)
{
auto v = entityMap.get(id.value);
if (v == nullptr) {
return nullptr;
}
return *v;
}
size_t World::numEntities() const
{
return entities.size();
}
std::vector<EntityRef> World::getEntities()
{
std::vector<EntityRef> result;
result.reserve(entities.size());
for (auto& e: entities) {
result.push_back(EntityRef(*e, *this));
}
return result;
}
void World::onEntityDirty()
{
entityDirty = true;
}
const World::CreateComponentFunction& World::getCreateComponentFunction() const
{
return createComponent;
}
void World::deleteEntity(Entity* entity)
{
Expects (entity);
entity->~Entity();
PoolAllocator<Entity>::free(entity);
}
bool World::hasSystemsOnTimeLine(TimeLine timeline) const
{
return getSystems(timeline).size() > 0;
}
int64_t World::getAverageTime(TimeLine timeline) const
{
return timer[int(timeline)].averageElapsedNanoSeconds();
}
void World::step(TimeLine timeline, Time elapsed)
{
auto& t = timer[int(timeline)];
if (collectMetrics) {
t.beginSample();
}
spawnPending();
initSystems();
updateSystems(timeline, elapsed);
if (collectMetrics) {
t.endSample();
}
}
void World::render(RenderContext& rc) const
{
auto& t = timer[int(TimeLine::Render)];
if (collectMetrics) {
t.beginSample();
}
renderSystems(rc);
if (collectMetrics) {
t.endSample();
}
}
void World::allocateEntity(Entity* entity) {
auto res = entityMap.alloc();
*res.first = entity;
entity->uid.value = res.second;
}
void World::spawnPending()
{
if (!entitiesPendingCreation.empty()) {
HALLEY_DEBUG_TRACE();
for (auto& e : entitiesPendingCreation) {
e->onReady();
}
std::move(entitiesPendingCreation.begin(), entitiesPendingCreation.end(), std::insert_iterator<decltype(entities)>(entities, entities.end()));
entitiesPendingCreation.clear();
entityDirty = true;
HALLEY_DEBUG_TRACE();
}
updateEntities();
}
void World::updateEntities()
{
if (!entityDirty) {
return;
}
HALLEY_DEBUG_TRACE();
size_t nEntities = entities.size();
std::vector<size_t> entitiesRemoved;
struct FamilyTodo {
std::vector<std::pair<FamilyMaskType, Entity*>> toAdd;
std::vector<std::pair<FamilyMaskType, Entity*>> toRemove;
};
std::map<FamilyMaskType, FamilyTodo> pending;
// Update all entities
// This loop should be as fast as reasonably possible
for (size_t i = 0; i < nEntities; i++) {
auto& entity = *entities[i];
if (i + 20 < nEntities) { // Watch out for sign! Don't subtract!
prefetchL2(entities[i + 20]);
}
// Check if it needs any sort of updating
if (entity.needsRefresh()) {
// First of all, let's check if it's dead
if (!entity.isAlive()) {
// Remove from systems
pending[entity.getMask()].toRemove.emplace_back(FamilyMaskType(), &entity);
entitiesRemoved.push_back(i);
} else {
// It's alive, so check old and new system inclusions
FamilyMaskType oldMask = entity.getMask();
entity.refresh();
FamilyMaskType newMask = entity.getMask();
// Did it change?
if (oldMask != newMask) {
pending[oldMask].toRemove.emplace_back(newMask, &entity);
pending[newMask].toAdd.emplace_back(oldMask, &entity);
}
}
}
}
HALLEY_DEBUG_TRACE();
// Go through every family adding/removing entities as needed
for (auto& todo: pending) {
for (auto& fam: getFamiliesFor(todo.first)) {
const auto& famMask = fam->inclusionMask;
for (auto& e: todo.second.toRemove) {
// Only remove if the entity is not about to be re-added
const auto& newMask = e.first;
if (!newMask.contains(famMask)) {
fam->removeEntity(*e.second);
}
}
for (auto& e: todo.second.toAdd) {
// Only add if the entity was not already in this
const auto& oldMask = e.first;
if (!oldMask.contains(famMask)) {
fam->addEntity(*e.second);
}
}
}
}
HALLEY_DEBUG_TRACE();
// Update families
for (auto& iter : families) {
iter->updateEntities();
}
HALLEY_DEBUG_TRACE();
// Actually remove dead entities
if (!entitiesRemoved.empty()) {
size_t livingEntityCount = entities.size();
for (int i = int(entitiesRemoved.size()); --i >= 0; ) {
size_t idx = entitiesRemoved[i];
auto& entity = *entities[idx];
// Remove
entityMap.freeId(entity.getEntityId().value);
deleteEntity(&entity);
// Put it at the back of the array, so it's removed when the array gets resized
std::swap(entities[idx], entities[--livingEntityCount]);
}
entities.resize(livingEntityCount);
}
entityDirty = false;
HALLEY_DEBUG_TRACE();
}
void World::initSystems()
{
for (auto& tl: systems) {
for (auto& system : tl) {
// If the system is initialised, also check for any entities that need spawning
if (system->tryInit()) {
spawnPending();
}
}
}
}
void World::updateSystems(TimeLine timeline, Time time)
{
for (auto& system : getSystems(timeline)) {
system->doUpdate(time);
spawnPending();
}
}
void World::renderSystems(RenderContext& rc) const
{
for (auto& system : getSystems(TimeLine::Render)) {
system->doRender(rc);
}
}
void World::onAddFamily(Family& family)
{
// Add any existing entities to this new family
size_t nEntities = entities.size();
for (size_t i = 0; i < nEntities; i++) {
auto& entity = *entities[i];
auto eMask = entity.getMask();
auto fMask = family.inclusionMask;
if ((eMask & fMask) == fMask) {
family.addEntity(entity);
}
}
familyCache.clear();
}
const std::vector<Family*>& World::getFamiliesFor(const FamilyMaskType& mask)
{
auto i = familyCache.find(mask);
if (i != familyCache.end()) {
return i->second;
} else {
std::vector<Family*> result;
for (auto& iter : families) {
auto& family = *iter;
FamilyMaskType famMask = family.inclusionMask;
if (mask.contains(famMask)) {
result.push_back(&family);
}
}
familyCache[mask] = std::move(result);
return familyCache[mask];
}
}
|
Fix entity families getting confused with a component is dynamically added to an entity.
|
Fix entity families getting confused with a component is dynamically added to an entity.
|
C++
|
apache-2.0
|
amzeratul/halley,amzeratul/halley,amzeratul/halley
|
36177493c43ed78d74732123c0ce9ca42a41f259
|
src/eventql/db/partition_map.cc
|
src/eventql/db/partition_map.cc
|
/**
* Copyright (c) 2016 zScale Technology GmbH <[email protected]>
* Authors:
* - Paul Asmuth <[email protected]>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* 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 license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include <thread>
#include <eventql/util/util/Base64.h>
#include <eventql/util/fnv.h>
#include <eventql/util/protobuf/msg.h>
#include <eventql/util/io/fileutil.h>
#include <eventql/io/sstable/sstablereader.h>
#include <eventql/db/partition_map.h>
#include <eventql/db/PartitionState.pb.h>
#include <eventql/db/PartitionReplication.h>
#include <eventql/db/metadata_coordinator.h>
#include "eventql/eventql.h"
#include "eventql/db/file_tracker.h"
namespace eventql {
static mdb::MDBOptions tsdb_mdb_opts() {
mdb::MDBOptions opts;
opts.data_filename = "index.db";
opts.lock_filename = "index.db.lck";
return opts;
};
PartitionMap::PartitionMap(
ServerCfg* cfg) :
cfg_(cfg),
db_(mdb::MDB::open(cfg_->db_path, tsdb_mdb_opts())),
cdir_(cfg->config_directory) {}
Option<RefPtr<Table>> PartitionMap::findTable(
const String& stream_ns,
const String& table_name) const {
std::unique_lock<std::mutex> lk(mutex_);
return findTableWithLock(stream_ns, table_name);
}
Option<RefPtr<Table>> PartitionMap::findTableWithLock(
const String& stream_ns,
const String& table_name) const {
auto stream_ns_key = stream_ns + "~" + table_name;
const auto& iter = tables_.find(stream_ns_key);
if (iter == tables_.end()) {
return None<RefPtr<Table>>();
} else {
return Some(iter->second);
}
}
void PartitionMap::configureTable(
const TableDefinition& table,
Set<SHA1Hash>* affected_partitions /* = nullptr */) {
std::unique_lock<std::mutex> lk(mutex_);
auto tbl_key = table.customer() + "~" + table.table_name();
bool metadata_changed = false;
{
auto iter = tables_.find(tbl_key);
if (iter == tables_.end()) {
tables_.emplace(tbl_key, new Table(table));
} else {
if (table.config().partitioner() != TBL_PARTITION_FIXED) {
auto last_metadata_txn = iter->second->getLastMetadataTransaction();
if (table.metadata_txnseq() > last_metadata_txn.getSequenceNumber()) {
metadata_changed = true;
}
}
iter->second->updateConfig(table);
}
}
if (metadata_changed && affected_partitions != nullptr) {
auto key_prefix = tbl_key + "~";
auto iter = partitions_.lower_bound(key_prefix);
for (; iter != partitions_.end(); ++iter) {
if (!StringUtil::beginsWith(iter->first, key_prefix)) {
break;
}
auto partition_id_str = iter->first.substr(key_prefix.size());
affected_partitions->emplace(
SHA1Hash(partition_id_str.data(), partition_id_str.size()));
}
}
}
void PartitionMap::open() {
auto txn = db_->startTransaction(false);
auto cursor = txn->getCursor();
Vector<PartitionKey> partitions;
for (int i = 0; ; ++i) {
Buffer key;
Buffer value;
if (i == 0) {
if (!cursor->getFirst(&key, &value)) {
break;
}
} else {
if (!cursor->getNext(&key, &value)) {
break;
}
}
auto db_key = key.toString();
if (db_key.size() == 0) {
continue;
}
if (db_key[0] == 0x1b) {
continue;
}
auto tsdb_namespace_off = StringUtil::find(db_key, '~');
if (tsdb_namespace_off == String::npos) {
RAISEF(kRuntimeError, "invalid partition key: $0", db_key);
}
auto tsdb_namespace = db_key.substr(0, tsdb_namespace_off);
SHA1Hash partition_key(
db_key.data() + tsdb_namespace_off + 1,
db_key.size() - tsdb_namespace_off - 1);
auto table_key = value.toString();
auto table = findTableWithLock(tsdb_namespace, table_key);
auto mem_key = tsdb_namespace + "~" + table_key + "~";
mem_key.append((char*) partition_key.data(), partition_key.size());
partitions_.emplace(mem_key, mkScoped(new LazyPartition()));
if (table.isEmpty()) {
logWarning(
"tsdb",
"Orphaned partition: $0/$1",
table_key,
partition_key.toString());
continue;
}
partitions.emplace_back(
std::make_tuple(tsdb_namespace, table_key, partition_key));
}
cursor->close();
txn->abort();
auto background_load_thread = std::thread(
std::bind(&PartitionMap::loadPartitions, this, partitions));
background_load_thread.detach();
}
void PartitionMap::loadPartitions(const Vector<PartitionKey>& partitions) {
for (const auto& p : partitions) {
try {
findPartition(std::get<0>(p), std::get<1>(p), std::get<2>(p));
} catch (const StandardException& e) {
logError(
"tsdb",
e,
"error while loading partition $0/$1/$2",
std::get<0>(p),
std::get<1>(p),
std::get<2>(p).toString());
}
}
}
RefPtr<Partition> PartitionMap::findOrCreatePartition(
const String& tsdb_namespace,
const String& table_name,
const SHA1Hash& partition_key) {
auto db_key = tsdb_namespace + "~";
db_key.append((char*) partition_key.data(), partition_key.size());
auto mem_key = tsdb_namespace + "~" + table_name + "~";
mem_key.append((char*) partition_key.data(), partition_key.size());
std::unique_lock<std::mutex> lk(mutex_);
Option<RefPtr<Table>> table;
{
auto iter = partitions_.find(mem_key);
if (iter != partitions_.end()) {
if (iter->second->isLoaded()) {
return iter->second->getPartition();
}
}
table = findTableWithLock(tsdb_namespace, table_name);
if (table.isEmpty()) {
RAISEF(kNotFoundError, "table not found: $0", table_name);
}
if (iter != partitions_.end()) {
auto partition = iter->second.get();
lk.unlock();
return partition->getPartition(
tsdb_namespace,
table.get(),
partition_key,
cfg_,
this);
}
}
lk.unlock();
PartitionDiscoveryResponse discovery_info;
if (table.get()->partitionerType() != TBL_PARTITION_FIXED) {
PartitionDiscoveryRequest discovery_request;
discovery_request.set_db_namespace(tsdb_namespace);
discovery_request.set_table_id(table_name);
discovery_request.set_min_txnseq(0);
discovery_request.set_partition_id(
partition_key.data(),
partition_key.size());
discovery_request.set_lookup_by_id(true);
MetadataCoordinator coordinator(cdir_);
PartitionDiscoveryResponse discovery_response;
auto rc = coordinator.discoverPartition(
discovery_request,
&discovery_info);
if (!rc.isSuccess()) {
RAISE(kRuntimeError, rc.message());
}
switch (discovery_info.code()) {
case PDISCOVERY_LOAD:
case PDISCOVERY_SERVE:
break;
default:
RAISE(kRuntimeError, "trying to load unassigned partition");
}
}
lk.lock();
{
auto iter = partitions_.find(mem_key);
if (iter != partitions_.end()) {
return iter->second->getPartition(
tsdb_namespace,
table.get(),
partition_key,
cfg_,
this);
}
}
auto partition = Partition::create(
tsdb_namespace,
table.get(),
partition_key,
discovery_info,
cfg_);
partitions_.emplace(mem_key, mkScoped(new LazyPartition(partition)));
auto txn = db_->startTransaction(false);
txn->update(
db_key.data(),
db_key.size(),
table_name.data(),
table_name.size());
txn->commit();
lk.unlock();
auto change = mkRef(new PartitionChangeNotification());
change->partition = partition;
publishPartitionChange(change);
return partition;
}
Option<RefPtr<Partition>> PartitionMap::findPartition(
const String& tsdb_namespace,
const String& table_name,
const SHA1Hash& partition_key) {
auto db_key = tsdb_namespace + "~";
db_key.append((char*) partition_key.data(), partition_key.size());
auto mem_key = tsdb_namespace + "~" + table_name + "~";
mem_key.append((char*) partition_key.data(), partition_key.size());
std::unique_lock<std::mutex> lk(mutex_);
auto iter = partitions_.find(mem_key);
if (iter == partitions_.end()) {
return None<RefPtr<Partition>>();
} else {
if (iter->second->isLoaded()) {
return Some(iter->second->getPartition());
}
auto table = findTableWithLock(tsdb_namespace, table_name);
if (table.isEmpty()) {
RAISEF(kNotFoundError, "table not found: $0", table_name);
}
auto partition = iter->second.get();
lk.unlock();
return Some(
partition->getPartition(
tsdb_namespace,
table.get(),
partition_key,
cfg_,
this));
}
}
void PartitionMap::listTables(
const String& tsdb_namespace,
Function<void (const TSDBTableInfo& table)> fn) const {
for (const auto& tbl : tables_) {
if (tbl.second->tsdbNamespace() != tsdb_namespace) {
continue;
}
TSDBTableInfo ti;
ti.table_name = tbl.second->name();
ti.config = tbl.second->config();
ti.schema = tbl.second->schema();
fn(ti);
}
}
void PartitionMap::listTablesReverse(
const String& tsdb_namespace,
Function<void (const TSDBTableInfo& table)> fn) const {
for (auto cur = tables_.rbegin(); cur != tables_.rend(); ++cur) {
if (cur->second->tsdbNamespace() != tsdb_namespace) {
continue;
}
TSDBTableInfo ti;
ti.table_name = cur->second->name();
ti.config = cur->second->config();
ti.schema = cur->second->schema();
fn(ti);
}
}
bool PartitionMap::dropLocalPartition(
const String& tsdb_namespace,
const String& table_name,
const SHA1Hash& partition_key) {
auto partition_opt = findPartition(tsdb_namespace, table_name, partition_key);
if (partition_opt.isEmpty()) {
RAISE(kNotFoundError, "partition not found");
}
auto partition = partition_opt.get();
auto partition_writer = partition->getWriter();
/* lock partition */
partition_writer->lock();
/* check preconditions */
try {
auto repl = partition->getReplicationStrategy(cfg_->repl_scheme, nullptr);
if (!repl->shouldDropPartition()) {
RAISE(kIllegalStateError, "can't delete partition");
}
} catch (const StandardException& e) {
/* unlock partition and bail */
partition_writer->unlock();
return false;
}
/* start deletion */
logInfo(
"z1.core",
"Partition $0/$1/$2 is not owned by this node and is fully replicated," \
" trying to unload and drop",
tsdb_namespace,
table_name,
partition_key.toString());
/* freeze partition and unlock waiting writers (they will fail) */
partition_writer->freeze();
partition_writer->unlock();
auto db_key = tsdb_namespace + "~";
db_key.append((char*) partition_key.data(), partition_key.size());
auto mem_key = tsdb_namespace + "~" + table_name + "~";
mem_key.append((char*) partition_key.data(), partition_key.size());
/* grab the main lock */
std::unique_lock<std::mutex> lk(mutex_);
/* delete from in memory partition map */
auto iter = partitions_.find(mem_key);
if (iter == partitions_.end()) {
/* somebody else already deleted this partition */
return true;
} else {
partitions_.erase(iter);
}
/* delete from on disk partition map */
auto txn = db_->startTransaction(false);
txn->del(db_key);
txn->commit();
/* move partition data to trash */
cfg_->file_tracker->deleteFile(
StringUtil::format(
"$0/$1/$2",
tsdb_namespace,
SHA1::compute(table_name).toString(),
partition_key.toString()));
return true;
}
Option<TSDBTableInfo> PartitionMap::tableInfo(
const String& tsdb_namespace,
const String& table_key) const {
auto table = findTable(tsdb_namespace, table_key);
if (table.isEmpty()) {
return None<TSDBTableInfo>();
}
TSDBTableInfo ti;
ti.table_name = table.get()->name();
ti.config = table.get()->config();
ti.schema = table.get()->schema();
return Some(ti);
}
void PartitionMap::subscribeToPartitionChanges(PartitionChangeCallbackFn fn) {
callbacks_.emplace_back(fn);
}
void PartitionMap::publishPartitionChange(
RefPtr<PartitionChangeNotification> change) {
for (const auto& cb : callbacks_) {
cb(change);
}
}
} // namespace tdsb
|
/**
* Copyright (c) 2016 zScale Technology GmbH <[email protected]>
* Authors:
* - Paul Asmuth <[email protected]>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* 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 license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include <thread>
#include <eventql/util/util/Base64.h>
#include <eventql/util/fnv.h>
#include <eventql/util/protobuf/msg.h>
#include <eventql/util/io/fileutil.h>
#include <eventql/io/sstable/sstablereader.h>
#include <eventql/db/partition_map.h>
#include <eventql/db/PartitionState.pb.h>
#include <eventql/db/PartitionReplication.h>
#include <eventql/db/metadata_coordinator.h>
#include "eventql/eventql.h"
#include "eventql/db/file_tracker.h"
namespace eventql {
static mdb::MDBOptions tsdb_mdb_opts() {
mdb::MDBOptions opts;
opts.data_filename = "index.db";
opts.lock_filename = "index.db.lck";
return opts;
};
PartitionMap::PartitionMap(
ServerCfg* cfg) :
cfg_(cfg),
db_(mdb::MDB::open(cfg_->db_path, tsdb_mdb_opts())),
cdir_(cfg->config_directory) {}
Option<RefPtr<Table>> PartitionMap::findTable(
const String& stream_ns,
const String& table_name) const {
std::unique_lock<std::mutex> lk(mutex_);
return findTableWithLock(stream_ns, table_name);
}
Option<RefPtr<Table>> PartitionMap::findTableWithLock(
const String& stream_ns,
const String& table_name) const {
auto stream_ns_key = stream_ns + "~" + table_name;
const auto& iter = tables_.find(stream_ns_key);
if (iter == tables_.end()) {
return None<RefPtr<Table>>();
} else {
return Some(iter->second);
}
}
void PartitionMap::configureTable(
const TableDefinition& table,
Set<SHA1Hash>* affected_partitions /* = nullptr */) {
if (table.config().partitioner() == TBL_PARTITION_FIXED) {
return;
}
if (table.config().storage() != TBL_STORAGE_COLSM) {
return;
}
std::unique_lock<std::mutex> lk(mutex_);
auto tbl_key = table.customer() + "~" + table.table_name();
bool metadata_changed = false;
{
auto iter = tables_.find(tbl_key);
if (iter == tables_.end()) {
tables_.emplace(tbl_key, new Table(table));
} else {
if (table.config().partitioner() != TBL_PARTITION_FIXED) {
auto last_metadata_txn = iter->second->getLastMetadataTransaction();
if (table.metadata_txnseq() > last_metadata_txn.getSequenceNumber()) {
metadata_changed = true;
}
}
iter->second->updateConfig(table);
}
}
if (metadata_changed && affected_partitions != nullptr) {
auto key_prefix = tbl_key + "~";
auto iter = partitions_.lower_bound(key_prefix);
for (; iter != partitions_.end(); ++iter) {
if (!StringUtil::beginsWith(iter->first, key_prefix)) {
break;
}
auto partition_id_str = iter->first.substr(key_prefix.size());
affected_partitions->emplace(
SHA1Hash(partition_id_str.data(), partition_id_str.size()));
}
}
}
void PartitionMap::open() {
auto txn = db_->startTransaction(false);
auto cursor = txn->getCursor();
Vector<PartitionKey> partitions;
for (int i = 0; ; ++i) {
Buffer key;
Buffer value;
if (i == 0) {
if (!cursor->getFirst(&key, &value)) {
break;
}
} else {
if (!cursor->getNext(&key, &value)) {
break;
}
}
auto db_key = key.toString();
if (db_key.size() == 0) {
continue;
}
if (db_key[0] == 0x1b) {
continue;
}
auto tsdb_namespace_off = StringUtil::find(db_key, '~');
if (tsdb_namespace_off == String::npos) {
RAISEF(kRuntimeError, "invalid partition key: $0", db_key);
}
auto tsdb_namespace = db_key.substr(0, tsdb_namespace_off);
SHA1Hash partition_key(
db_key.data() + tsdb_namespace_off + 1,
db_key.size() - tsdb_namespace_off - 1);
auto table_key = value.toString();
auto table = findTableWithLock(tsdb_namespace, table_key);
auto mem_key = tsdb_namespace + "~" + table_key + "~";
mem_key.append((char*) partition_key.data(), partition_key.size());
partitions_.emplace(mem_key, mkScoped(new LazyPartition()));
if (table.isEmpty()) {
logWarning(
"tsdb",
"Orphaned partition: $0/$1",
table_key,
partition_key.toString());
continue;
}
partitions.emplace_back(
std::make_tuple(tsdb_namespace, table_key, partition_key));
}
cursor->close();
txn->abort();
auto background_load_thread = std::thread(
std::bind(&PartitionMap::loadPartitions, this, partitions));
background_load_thread.detach();
}
void PartitionMap::loadPartitions(const Vector<PartitionKey>& partitions) {
for (const auto& p : partitions) {
try {
findPartition(std::get<0>(p), std::get<1>(p), std::get<2>(p));
} catch (const StandardException& e) {
logError(
"tsdb",
e,
"error while loading partition $0/$1/$2",
std::get<0>(p),
std::get<1>(p),
std::get<2>(p).toString());
}
}
}
RefPtr<Partition> PartitionMap::findOrCreatePartition(
const String& tsdb_namespace,
const String& table_name,
const SHA1Hash& partition_key) {
auto db_key = tsdb_namespace + "~";
db_key.append((char*) partition_key.data(), partition_key.size());
auto mem_key = tsdb_namespace + "~" + table_name + "~";
mem_key.append((char*) partition_key.data(), partition_key.size());
std::unique_lock<std::mutex> lk(mutex_);
Option<RefPtr<Table>> table;
{
auto iter = partitions_.find(mem_key);
if (iter != partitions_.end()) {
if (iter->second->isLoaded()) {
return iter->second->getPartition();
}
}
table = findTableWithLock(tsdb_namespace, table_name);
if (table.isEmpty()) {
RAISEF(kNotFoundError, "table not found: $0", table_name);
}
if (iter != partitions_.end()) {
auto partition = iter->second.get();
lk.unlock();
return partition->getPartition(
tsdb_namespace,
table.get(),
partition_key,
cfg_,
this);
}
}
lk.unlock();
PartitionDiscoveryResponse discovery_info;
if (table.get()->partitionerType() != TBL_PARTITION_FIXED) {
PartitionDiscoveryRequest discovery_request;
discovery_request.set_db_namespace(tsdb_namespace);
discovery_request.set_table_id(table_name);
discovery_request.set_min_txnseq(0);
discovery_request.set_partition_id(
partition_key.data(),
partition_key.size());
discovery_request.set_lookup_by_id(true);
MetadataCoordinator coordinator(cdir_);
PartitionDiscoveryResponse discovery_response;
auto rc = coordinator.discoverPartition(
discovery_request,
&discovery_info);
if (!rc.isSuccess()) {
RAISE(kRuntimeError, rc.message());
}
switch (discovery_info.code()) {
case PDISCOVERY_LOAD:
case PDISCOVERY_SERVE:
break;
default:
RAISE(kRuntimeError, "trying to load unassigned partition");
}
}
lk.lock();
{
auto iter = partitions_.find(mem_key);
if (iter != partitions_.end()) {
return iter->second->getPartition(
tsdb_namespace,
table.get(),
partition_key,
cfg_,
this);
}
}
auto partition = Partition::create(
tsdb_namespace,
table.get(),
partition_key,
discovery_info,
cfg_);
partitions_.emplace(mem_key, mkScoped(new LazyPartition(partition)));
auto txn = db_->startTransaction(false);
txn->update(
db_key.data(),
db_key.size(),
table_name.data(),
table_name.size());
txn->commit();
lk.unlock();
auto change = mkRef(new PartitionChangeNotification());
change->partition = partition;
publishPartitionChange(change);
return partition;
}
Option<RefPtr<Partition>> PartitionMap::findPartition(
const String& tsdb_namespace,
const String& table_name,
const SHA1Hash& partition_key) {
auto db_key = tsdb_namespace + "~";
db_key.append((char*) partition_key.data(), partition_key.size());
auto mem_key = tsdb_namespace + "~" + table_name + "~";
mem_key.append((char*) partition_key.data(), partition_key.size());
std::unique_lock<std::mutex> lk(mutex_);
auto iter = partitions_.find(mem_key);
if (iter == partitions_.end()) {
return None<RefPtr<Partition>>();
} else {
if (iter->second->isLoaded()) {
return Some(iter->second->getPartition());
}
auto table = findTableWithLock(tsdb_namespace, table_name);
if (table.isEmpty()) {
RAISEF(kNotFoundError, "table not found: $0", table_name);
}
auto partition = iter->second.get();
lk.unlock();
return Some(
partition->getPartition(
tsdb_namespace,
table.get(),
partition_key,
cfg_,
this));
}
}
void PartitionMap::listTables(
const String& tsdb_namespace,
Function<void (const TSDBTableInfo& table)> fn) const {
for (const auto& tbl : tables_) {
if (tbl.second->tsdbNamespace() != tsdb_namespace) {
continue;
}
TSDBTableInfo ti;
ti.table_name = tbl.second->name();
ti.config = tbl.second->config();
ti.schema = tbl.second->schema();
fn(ti);
}
}
void PartitionMap::listTablesReverse(
const String& tsdb_namespace,
Function<void (const TSDBTableInfo& table)> fn) const {
for (auto cur = tables_.rbegin(); cur != tables_.rend(); ++cur) {
if (cur->second->tsdbNamespace() != tsdb_namespace) {
continue;
}
TSDBTableInfo ti;
ti.table_name = cur->second->name();
ti.config = cur->second->config();
ti.schema = cur->second->schema();
fn(ti);
}
}
bool PartitionMap::dropLocalPartition(
const String& tsdb_namespace,
const String& table_name,
const SHA1Hash& partition_key) {
auto partition_opt = findPartition(tsdb_namespace, table_name, partition_key);
if (partition_opt.isEmpty()) {
RAISE(kNotFoundError, "partition not found");
}
auto partition = partition_opt.get();
auto partition_writer = partition->getWriter();
/* lock partition */
partition_writer->lock();
/* check preconditions */
try {
auto repl = partition->getReplicationStrategy(cfg_->repl_scheme, nullptr);
if (!repl->shouldDropPartition()) {
RAISE(kIllegalStateError, "can't delete partition");
}
} catch (const StandardException& e) {
/* unlock partition and bail */
partition_writer->unlock();
return false;
}
/* start deletion */
logInfo(
"z1.core",
"Partition $0/$1/$2 is not owned by this node and is fully replicated," \
" trying to unload and drop",
tsdb_namespace,
table_name,
partition_key.toString());
/* freeze partition and unlock waiting writers (they will fail) */
partition_writer->freeze();
partition_writer->unlock();
auto db_key = tsdb_namespace + "~";
db_key.append((char*) partition_key.data(), partition_key.size());
auto mem_key = tsdb_namespace + "~" + table_name + "~";
mem_key.append((char*) partition_key.data(), partition_key.size());
/* grab the main lock */
std::unique_lock<std::mutex> lk(mutex_);
/* delete from in memory partition map */
auto iter = partitions_.find(mem_key);
if (iter == partitions_.end()) {
/* somebody else already deleted this partition */
return true;
} else {
partitions_.erase(iter);
}
/* delete from on disk partition map */
auto txn = db_->startTransaction(false);
txn->del(db_key);
txn->commit();
/* move partition data to trash */
cfg_->file_tracker->deleteFile(
StringUtil::format(
"$0/$1/$2",
tsdb_namespace,
SHA1::compute(table_name).toString(),
partition_key.toString()));
return true;
}
Option<TSDBTableInfo> PartitionMap::tableInfo(
const String& tsdb_namespace,
const String& table_key) const {
auto table = findTable(tsdb_namespace, table_key);
if (table.isEmpty()) {
return None<TSDBTableInfo>();
}
TSDBTableInfo ti;
ti.table_name = table.get()->name();
ti.config = table.get()->config();
ti.schema = table.get()->schema();
return Some(ti);
}
void PartitionMap::subscribeToPartitionChanges(PartitionChangeCallbackFn fn) {
callbacks_.emplace_back(fn);
}
void PartitionMap::publishPartitionChange(
RefPtr<PartitionChangeNotification> change) {
for (const auto& cb : callbacks_) {
cb(change);
}
}
} // namespace tdsb
|
disable legacy tables
|
disable legacy tables
|
C++
|
agpl-3.0
|
eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql,eventql/eventql
|
76943f82c9345cc6c565b6358671d746ea81b29f
|
unreal/trunk/qrgui/mainwindow/gesturesShow/gestureswidget.cpp
|
unreal/trunk/qrgui/mainwindow/gesturesShow/gestureswidget.cpp
|
#include "gestureswidget.h"
#include "ui_gestureswidget.h"
GesturesWidget::GesturesWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::GesturesWidget)
{
ui->setupUi(this);
mGestureScene = new QGraphicsScene(ui->graphicsView);
ui->graphicsView->setScene(mGestureScene);
connect(ui->listWidget, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)),
this, SIGNAL(currentElementChanged()));
mTimer = new QTimer(this);
QObject::connect(mTimer, SIGNAL(timeout()), this, SLOT(drawGesture()));
mTimer->start(50);
}
GesturesWidget::~GesturesWidget()
{
delete mTimer;
delete ui;
}
void GesturesWidget::draw(QList<QPoint> const & path)
{
mCurrentPointNumber = 0;
mGestureScene->clear();
mPath = path;
}
void GesturesWidget::drawGesture()
{
if (mPath.isEmpty())
return;
int verticeIndex = (mCurrentPointNumber / pointsAtSegment) % mPath.size();
int segmentNumber = mCurrentPointNumber % pointsAtSegment + 1;
if (verticeIndex == mPath.size() - 1)
{
mGestureScene->clear();
mCurrentPointNumber = 0;
return;
}
QPoint lastPaintedPoint = mPath.at(verticeIndex);
QPoint nextPoint = mPath.at(verticeIndex + 1);
QPoint currentPoint(coord(lastPaintedPoint.x(), nextPoint.x(), segmentNumber),
coord(lastPaintedPoint.y(), nextPoint.y(), segmentNumber));
mGestureScene->addLine(QLine(lastPaintedPoint, currentPoint), QPen(Qt::black));
mCurrentPointNumber++;
}
int GesturesWidget::coord(int previous, int next, int part)
{
return previous + (next - previous) * part / pointsAtSegment;
}
QString GesturesWidget::currentElement()
{
return ui->listWidget->currentItem()->text();
}
void GesturesWidget::setElements(const QList<QString> &elements)
{
foreach(QString element, elements)
{
ui->listWidget->addItem(element);
}
}
|
#include "gestureswidget.h"
#include "ui_gestureswidget.h"
GesturesWidget::GesturesWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::GesturesWidget)
{
ui->setupUi(this);
mGestureScene = new QGraphicsScene(ui->graphicsView);
ui->graphicsView->setScene(mGestureScene);
connect(ui->listWidget, SIGNAL(currentItemChanged(QListWidgetItem*,QListWidgetItem*)),
this, SIGNAL(currentElementChanged()));
mTimer = new QTimer(this);
QObject::connect(mTimer, SIGNAL(timeout()), this, SLOT(drawGesture()));
mTimer->start(50);
}
GesturesWidget::~GesturesWidget()
{
delete mTimer;
delete ui;
}
void GesturesWidget::draw(QList<QPoint> const & path)
{
mCurrentPointNumber = 0;
mGestureScene->clear();
mPath = path;
}
void GesturesWidget::drawGesture()
{
if (mPath.isEmpty())
return;
int verticeIndex = (mCurrentPointNumber / pointsAtSegment) % mPath.size();
int segmentNumber = mCurrentPointNumber % pointsAtSegment + 1;
if (verticeIndex == mPath.size() - 1)
{
mGestureScene->clear();
mCurrentPointNumber = 0;
return;
}
QPoint lastPaintedPoint = mPath.at(verticeIndex);
QPoint nextPoint = mPath.at(verticeIndex + 1);
QPoint currentPoint(coord(lastPaintedPoint.x(), nextPoint.x(), segmentNumber),
coord(lastPaintedPoint.y(), nextPoint.y(), segmentNumber));
mGestureScene->addLine(QLine(lastPaintedPoint, currentPoint), QPen(Qt::black));
mCurrentPointNumber++;
}
int GesturesWidget::coord(int previous, int next, int part)
{
return previous + (next - previous) * part / pointsAtSegment;
}
QString GesturesWidget::currentElement()
{
return ui->listWidget->currentItem()->text();
}
void GesturesWidget::setElements(const QList<QString> &elements)
{
ui->listWidget->clear();
ui->listWidget->addItems(elements);
}
|
fix ideal gestures printing
|
fix ideal gestures printing
|
C++
|
apache-2.0
|
Julia-Khramyshkina/qreal,qreal/qreal,Ashatta/qreal,anastasia143/qreal,dvvrd/qreal,Julia-Khramyshkina/qreal,ZiminGrigory/qreal,tara-sova/qreal,dvvrd/qreal,Ashatta/qreal,ZiminGrigory/qreal,iakov/qreal,tara-sova/qreal,Ashatta/qreal,qreal/qreal,tara-sova/qreal,tara-sova/qreal,Julia-Khramyshkina/qreal,DenisKogutich/qreal,danilaml/qreal,dvvrd/qreal,danilaml/qreal,DenisKogutich/qreal,danilaml/qreal,tara-sova/qreal,tara-sova/qreal,dvvrd/qreal,danilaml/qreal,qreal/qreal,iakov/qreal,danilaml/qreal,qreal/qreal,Julia-Khramyshkina/qreal,tara-sova/qreal,RomanBelkov/qreal,Victor-Y-Fadeev/qreal,RomanBelkov/qreal,RomanBelkov/qreal,Julia-Khramyshkina/qreal,iakov/qreal,ZiminGrigory/qreal,anastasia143/qreal,Ashatta/qreal,RomanBelkov/qreal,qreal/qreal,anastasia143/qreal,tara-sova/qreal,ZiminGrigory/qreal,iakov/qreal,Victor-Y-Fadeev/qreal,iakov/qreal,anastasia143/qreal,Julia-Khramyshkina/qreal,danilaml/qreal,iakov/qreal,ZiminGrigory/qreal,Ashatta/qreal,iakov/qreal,RomanBelkov/qreal,dvvrd/qreal,dvvrd/qreal,Julia-Khramyshkina/qreal,RomanBelkov/qreal,qreal/qreal,anastasia143/qreal,Ashatta/qreal,RomanBelkov/qreal,Julia-Khramyshkina/qreal,Ashatta/qreal,DenisKogutich/qreal,iakov/qreal,RomanBelkov/qreal,Victor-Y-Fadeev/qreal,dvvrd/qreal,iakov/qreal,ZiminGrigory/qreal,qreal/qreal,dvvrd/qreal,Victor-Y-Fadeev/qreal,danilaml/qreal,Victor-Y-Fadeev/qreal,Ashatta/qreal,Ashatta/qreal,anastasia143/qreal,dvvrd/qreal,DenisKogutich/qreal,Victor-Y-Fadeev/qreal,Julia-Khramyshkina/qreal,tara-sova/qreal,DenisKogutich/qreal,Victor-Y-Fadeev/qreal,qreal/qreal,ZiminGrigory/qreal,danilaml/qreal,ZiminGrigory/qreal,DenisKogutich/qreal,danilaml/qreal,anastasia143/qreal,ZiminGrigory/qreal,DenisKogutich/qreal,RomanBelkov/qreal,qreal/qreal,DenisKogutich/qreal,anastasia143/qreal,anastasia143/qreal,Victor-Y-Fadeev/qreal,DenisKogutich/qreal
|
3deccf99ab0a84726628f6d23c4e8e27ba810986
|
src/global_timestamp_reader.cpp
|
src/global_timestamp_reader.cpp
|
// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2015 Intel Corporation. All Rights Reserved.
#include "global_timestamp_reader.h"
#include <chrono>
namespace librealsense
{
CSample& CSample::operator-=(const CSample& other)
{
_x -= other._x;
_y -= other._y;
return *this;
}
CSample& CSample::operator+=(const CSample& other)
{
_x += other._x;
_y += other._y;
return *this;
}
CLinearCoefficients::CLinearCoefficients(unsigned int buffer_size) :
_base_sample(0, 0),
_buffer_size(buffer_size),
_time_span_ms(1000) // Spread the linear equation modifications over a whole second.
{
}
void CLinearCoefficients::reset()
{
_last_values.clear();
}
bool CLinearCoefficients::is_full() const
{
return _last_values.size() >= _buffer_size;
}
void CLinearCoefficients::add_value(CSample val)
{
while (_last_values.size() > _buffer_size)
{
_last_values.pop_back();
}
_last_values.push_front(val);
calc_linear_coefs();
}
void CLinearCoefficients::add_const_y_coefs(double dy)
{
for (auto &&sample : _last_values)
{
sample._y += dy;
}
}
void CLinearCoefficients::calc_linear_coefs()
{
// Calculate linear coefficients, based on calculus described in: https://www.statisticshowto.datasciencecentral.com/probability-and-statistics/regression-analysis/find-a-linear-regression-equation/
// Calculate Std
double n(static_cast<double>(_last_values.size()));
double a(1);
double b(0);
double crnt_time(_last_values.front()._x);
double dt(1);
if (n == 1)
{
_base_sample = _last_values.back();
_dest_a = 1;
_dest_b = 0;
_prev_a = 0;
_prev_b = 0;
}
else
{
double sum_x(0);
double sum_y(0);
double sum_xy(0);
double sum_x2(0);
for (auto sample = _last_values.begin(); sample != _last_values.end(); sample++)
{
CSample crnt_sample(*sample);
crnt_sample -= _base_sample;
sum_x += crnt_sample._x;
sum_y += crnt_sample._y;
sum_xy += (crnt_sample._x * crnt_sample._y);
sum_x2 += (crnt_sample._x * crnt_sample._x);
}
b = (sum_y*sum_x2 - sum_x * sum_xy) / (n*sum_x2 - sum_x * sum_x);
a = (n*sum_xy - sum_x * sum_y) / (n*sum_x2 - sum_x * sum_x);
if (crnt_time - _prev_time < _time_span_ms)
{
dt = (crnt_time - _prev_time) / _time_span_ms;
}
}
_prev_a = _dest_a * dt + _prev_a * (1 - dt);
_prev_b = _dest_b * dt + _prev_b * (1 - dt);
_dest_a = a;
_dest_b = b;
_prev_time = crnt_time;
}
void CLinearCoefficients::get_a_b(double x, double& a, double& b) const
{
a = _dest_a;
b = _dest_b;
if (x - _prev_time < _time_span_ms)
{
double dt((x - _prev_time) / _time_span_ms);
a = _dest_a * dt + _prev_a * (1 - dt);
b = _dest_b * dt + _prev_b * (1 - dt);
}
}
double CLinearCoefficients::calc_value(double x) const
{
double a, b;
get_a_b(x, a, b);
double y(a * (x - _base_sample._x) + b + _base_sample._y);
LOG_DEBUG(__FUNCTION__ << ": " << x << " -> " << y << " with coefs:" << a << ", " << b << ", " << _base_sample._x << ", " << _base_sample._y);
return y;
}
bool CLinearCoefficients::update_samples_base(double x, double& last_sample_x)
{
static const double max_device_time(pow(2, 32) * TIMESTAMP_USEC_TO_MSEC);
double base_x;
if ((_last_values.front()._x - x) > max_device_time / 2)
base_x = max_device_time;
else if ((x - _last_values.front()._x) > max_device_time / 2)
base_x = -max_device_time;
else
return false;
LOG_DEBUG(__FUNCTION__ << "(" << base_x << ")");
double a, b;
get_a_b(x+base_x, a, b);
for (auto &&sample : _last_values)
{
sample._x -= base_x;
}
_prev_time -= base_x;
_base_sample._y += a * base_x;
last_sample_x = _last_values.front()._x;
return true;
}
time_diff_keeper::time_diff_keeper(global_time_interface* dev, const unsigned int sampling_interval_ms) :
_device(dev),
_poll_intervals_ms(sampling_interval_ms),
_last_sample_hw_time(1e+200),
_coefs(15),
_users_count(0),
_is_ready(false),
_min_command_delay(1000),
_active_object([this](dispatcher::cancellable_timer cancellable_timer)
{
polling(cancellable_timer);
})
{
//LOG_DEBUG("start new time_diff_keeper ");
}
void time_diff_keeper::start()
{
std::lock_guard<std::recursive_mutex> lock(_enable_mtx);
_users_count++;
LOG_DEBUG("time_diff_keeper::start: _users_count = " << _users_count);
_active_object.start();
}
void time_diff_keeper::stop()
{
std::lock_guard<std::recursive_mutex> lock(_enable_mtx);
if (_users_count <= 0)
LOG_ERROR("time_diff_keeper users_count <= 0.");
_users_count--;
LOG_DEBUG("time_diff_keeper::stop: _users_count = " << _users_count);
if (_users_count == 0)
{
LOG_DEBUG("time_diff_keeper::stop: stop object.");
_active_object.stop();
_coefs.reset();
}
}
time_diff_keeper::~time_diff_keeper()
{
_active_object.stop();
}
bool time_diff_keeper::update_diff_time()
{
using namespace std::chrono;
try
{
if (!_users_count)
throw wrong_api_call_sequence_exception("time_diff_keeper::update_diff_time called before object started.");
double system_time_start = duration<double, std::milli>(system_clock::now().time_since_epoch()).count();
double sample_hw_time = _device->get_device_time_ms();
double system_time_finish = duration<double, std::milli>(system_clock::now().time_since_epoch()).count();
double command_delay = (system_time_finish-system_time_start)/2;
if (command_delay < _min_command_delay)
{
_coefs.add_const_y_coefs(command_delay - _min_command_delay);
_min_command_delay = command_delay;
}
double system_time(system_time_finish - _min_command_delay);
std::lock_guard<std::recursive_mutex> lock(_read_mtx);
if (_is_ready)
{
double un_used;
_coefs.update_samples_base(sample_hw_time, un_used);
}
CSample crnt_sample(sample_hw_time, system_time);
_coefs.add_value(crnt_sample);
_last_sample_hw_time = sample_hw_time;
_is_ready = true;
return true;
}
catch (const io_exception& ex)
{
LOG_DEBUG("Temporary skip during time_diff_keeper polling: " << ex.what());
}
catch (const wrong_api_call_sequence_exception& ex)
{
LOG_DEBUG("Temporary skip during time_diff_keeper polling: " << ex.what());
}
catch (const std::exception& ex)
{
LOG_ERROR("Error during time_diff_keeper polling: " << ex.what());
}
catch (...)
{
LOG_ERROR("Unknown error during time_diff_keeper polling!");
}
return false;
}
void time_diff_keeper::polling(dispatcher::cancellable_timer cancellable_timer)
{
unsigned int time_to_sleep = _poll_intervals_ms + _coefs.is_full() * (9 * _poll_intervals_ms);
if (cancellable_timer.try_sleep(time_to_sleep))
{
update_diff_time();
}
else
{
LOG_DEBUG("Notification: time_diff_keeper polling loop is being shut-down");
}
}
double time_diff_keeper::get_system_hw_time(double crnt_hw_time, bool& is_ready)
{
is_ready = _is_ready;
if (_is_ready)
{
std::lock_guard<std::recursive_mutex> lock(_read_mtx);
double last_sample_hw_time;
if (_coefs.update_samples_base(crnt_hw_time, last_sample_hw_time))
{
// A time loop happened:
_last_sample_hw_time = last_sample_hw_time;
}
return _coefs.calc_value(crnt_hw_time);
}
else
return crnt_hw_time;
}
global_timestamp_reader::global_timestamp_reader(std::unique_ptr<frame_timestamp_reader> device_timestamp_reader,
std::shared_ptr<time_diff_keeper> timediff,
std::shared_ptr<global_time_option> enable_option) :
_device_timestamp_reader(std::move(device_timestamp_reader)),
_time_diff_keeper(timediff),
_option_is_enabled(enable_option),
_ts_is_ready(false)
{
}
double global_timestamp_reader::get_frame_timestamp(const std::shared_ptr<frame_interface>& frame)
{
double frame_time = _device_timestamp_reader->get_frame_timestamp(frame);
rs2_timestamp_domain ts_domain = _device_timestamp_reader->get_frame_timestamp_domain(frame);
if (_option_is_enabled->is_true() && ts_domain == RS2_TIMESTAMP_DOMAIN_HARDWARE_CLOCK)
{
auto sp = _time_diff_keeper.lock();
if (sp)
frame_time = sp->get_system_hw_time(frame_time, _ts_is_ready);
else
LOG_DEBUG("Notification: global_timestamp_reader - time_diff_keeper is being shut-down");
}
return frame_time;
}
unsigned long long global_timestamp_reader::get_frame_counter(const std::shared_ptr<frame_interface>& frame) const
{
return _device_timestamp_reader->get_frame_counter(frame);
}
rs2_timestamp_domain global_timestamp_reader::get_frame_timestamp_domain(const std::shared_ptr<frame_interface>& frame) const
{
rs2_timestamp_domain ts_domain = _device_timestamp_reader->get_frame_timestamp_domain(frame);
return (_option_is_enabled->is_true() && _ts_is_ready && ts_domain == RS2_TIMESTAMP_DOMAIN_HARDWARE_CLOCK) ? RS2_TIMESTAMP_DOMAIN_GLOBAL_TIME : ts_domain;
}
void global_timestamp_reader::reset()
{
_device_timestamp_reader->reset();
}
global_time_interface::global_time_interface() :
_tf_keeper(std::make_shared<time_diff_keeper>(this, 100))
{}
void global_time_interface::enable_time_diff_keeper(bool is_enable)
{
if (is_enable)
_tf_keeper->start();
else
_tf_keeper->stop();
}
}
|
// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2015 Intel Corporation. All Rights Reserved.
#include "global_timestamp_reader.h"
#include <chrono>
namespace librealsense
{
CSample& CSample::operator-=(const CSample& other)
{
_x -= other._x;
_y -= other._y;
return *this;
}
CSample& CSample::operator+=(const CSample& other)
{
_x += other._x;
_y += other._y;
return *this;
}
CLinearCoefficients::CLinearCoefficients(unsigned int buffer_size) :
_base_sample(0, 0),
_buffer_size(buffer_size),
_time_span_ms(1000) // Spread the linear equation modifications over a whole second.
{
}
void CLinearCoefficients::reset()
{
_last_values.clear();
}
bool CLinearCoefficients::is_full() const
{
return _last_values.size() >= _buffer_size;
}
void CLinearCoefficients::add_value(CSample val)
{
while (_last_values.size() > _buffer_size)
{
_last_values.pop_back();
}
_last_values.push_front(val);
calc_linear_coefs();
}
void CLinearCoefficients::add_const_y_coefs(double dy)
{
for (auto &&sample : _last_values)
{
sample._y += dy;
}
}
void CLinearCoefficients::calc_linear_coefs()
{
// Calculate linear coefficients, based on calculus described in: https://www.statisticshowto.datasciencecentral.com/probability-and-statistics/regression-analysis/find-a-linear-regression-equation/
// Calculate Std
double n(static_cast<double>(_last_values.size()));
double a(1);
double b(0);
double crnt_time(_last_values.front()._x);
double dt(1);
if (n == 1)
{
_base_sample = _last_values.back();
_dest_a = 1;
_dest_b = 0;
_prev_a = 0;
_prev_b = 0;
}
else
{
double sum_x(0);
double sum_y(0);
double sum_xy(0);
double sum_x2(0);
for (auto sample = _last_values.begin(); sample != _last_values.end(); sample++)
{
CSample crnt_sample(*sample);
crnt_sample -= _base_sample;
sum_x += crnt_sample._x;
sum_y += crnt_sample._y;
sum_xy += (crnt_sample._x * crnt_sample._y);
sum_x2 += (crnt_sample._x * crnt_sample._x);
}
b = (sum_y*sum_x2 - sum_x * sum_xy) / (n*sum_x2 - sum_x * sum_x);
a = (n*sum_xy - sum_x * sum_y) / (n*sum_x2 - sum_x * sum_x);
if (crnt_time - _prev_time < _time_span_ms)
{
dt = (crnt_time - _prev_time) / _time_span_ms;
}
}
_prev_a = _dest_a * dt + _prev_a * (1 - dt);
_prev_b = _dest_b * dt + _prev_b * (1 - dt);
_dest_a = a;
_dest_b = b;
_prev_time = crnt_time;
}
void CLinearCoefficients::get_a_b(double x, double& a, double& b) const
{
a = _dest_a;
b = _dest_b;
if (x - _prev_time < _time_span_ms)
{
double dt((x - _prev_time) / _time_span_ms);
a = _dest_a * dt + _prev_a * (1 - dt);
b = _dest_b * dt + _prev_b * (1 - dt);
}
}
double CLinearCoefficients::calc_value(double x) const
{
double a, b;
get_a_b(x, a, b);
double y(a * (x - _base_sample._x) + b + _base_sample._y);
LOG_DEBUG(__FUNCTION__ << ": " << x << " -> " << y << " with coefs:" << a << ", " << b << ", " << _base_sample._x << ", " << _base_sample._y);
return y;
}
bool CLinearCoefficients::update_samples_base(double x, double& last_sample_x)
{
static const double max_device_time(pow(2, 32) * TIMESTAMP_USEC_TO_MSEC);
double base_x;
if ((_last_values.front()._x - x) > max_device_time / 2)
base_x = max_device_time;
else if ((x - _last_values.front()._x) > max_device_time / 2)
base_x = -max_device_time;
else
return false;
LOG_DEBUG(__FUNCTION__ << "(" << base_x << ")");
double a, b;
get_a_b(x+base_x, a, b);
for (auto &&sample : _last_values)
{
sample._x -= base_x;
}
_prev_time -= base_x;
_base_sample._y += a * base_x;
last_sample_x = _last_values.front()._x;
return true;
}
time_diff_keeper::time_diff_keeper(global_time_interface* dev, const unsigned int sampling_interval_ms) :
_device(dev),
_poll_intervals_ms(sampling_interval_ms),
_last_sample_hw_time(1e+200),
_coefs(15),
_users_count(0),
_is_ready(false),
_min_command_delay(1000),
_active_object([this](dispatcher::cancellable_timer cancellable_timer)
{
polling(cancellable_timer);
})
{
//LOG_DEBUG("start new time_diff_keeper ");
}
void time_diff_keeper::start()
{
std::lock_guard<std::recursive_mutex> lock(_enable_mtx);
_users_count++;
LOG_DEBUG("time_diff_keeper::start: _users_count = " << _users_count);
_active_object.start();
}
void time_diff_keeper::stop()
{
std::lock_guard<std::recursive_mutex> lock(_enable_mtx);
if (_users_count <= 0)
LOG_ERROR("time_diff_keeper users_count <= 0.");
_users_count--;
LOG_DEBUG("time_diff_keeper::stop: _users_count = " << _users_count);
if (_users_count == 0)
{
LOG_DEBUG("time_diff_keeper::stop: stop object.");
_active_object.stop();
_coefs.reset();
}
}
time_diff_keeper::~time_diff_keeper()
{
_active_object.stop();
}
bool time_diff_keeper::update_diff_time()
{
using namespace std::chrono;
try
{
if (!_users_count)
throw wrong_api_call_sequence_exception("time_diff_keeper::update_diff_time called before object started.");
double system_time_start = duration<double, std::milli>(system_clock::now().time_since_epoch()).count();
double sample_hw_time = _device->get_device_time_ms();
double system_time_finish = duration<double, std::milli>(system_clock::now().time_since_epoch()).count();
double command_delay = (system_time_finish-system_time_start)/2;
if (command_delay < _min_command_delay)
{
_coefs.add_const_y_coefs(command_delay - _min_command_delay);
_min_command_delay = command_delay;
}
double system_time(system_time_finish - _min_command_delay);
std::lock_guard<std::recursive_mutex> lock(_read_mtx);
if (_is_ready)
{
double un_used;
_coefs.update_samples_base(sample_hw_time, un_used);
}
CSample crnt_sample(sample_hw_time, system_time);
_coefs.add_value(crnt_sample);
_last_sample_hw_time = sample_hw_time;
_is_ready = true;
return true;
}
catch (const io_exception& ex)
{
LOG_DEBUG("Temporary skip during time_diff_keeper polling: " << ex.what());
}
catch (const wrong_api_call_sequence_exception& ex)
{
LOG_DEBUG("Temporary skip during time_diff_keeper polling: " << ex.what());
}
catch (const std::exception& ex)
{
LOG_ERROR("Error during time_diff_keeper polling: " << ex.what());
}
catch (...)
{
LOG_ERROR("Unknown error during time_diff_keeper polling!");
}
return false;
}
void time_diff_keeper::polling(dispatcher::cancellable_timer cancellable_timer)
{
update_diff_time();
unsigned int time_to_sleep = _poll_intervals_ms + _coefs.is_full() * (9 * _poll_intervals_ms);
if (!cancellable_timer.try_sleep(time_to_sleep))
{
LOG_DEBUG("Notification: time_diff_keeper polling loop is being shut-down");
}
}
double time_diff_keeper::get_system_hw_time(double crnt_hw_time, bool& is_ready)
{
is_ready = _is_ready;
if (_is_ready)
{
std::lock_guard<std::recursive_mutex> lock(_read_mtx);
double last_sample_hw_time;
if (_coefs.update_samples_base(crnt_hw_time, last_sample_hw_time))
{
// A time loop happened:
_last_sample_hw_time = last_sample_hw_time;
}
return _coefs.calc_value(crnt_hw_time);
}
else
return crnt_hw_time;
}
global_timestamp_reader::global_timestamp_reader(std::unique_ptr<frame_timestamp_reader> device_timestamp_reader,
std::shared_ptr<time_diff_keeper> timediff,
std::shared_ptr<global_time_option> enable_option) :
_device_timestamp_reader(std::move(device_timestamp_reader)),
_time_diff_keeper(timediff),
_option_is_enabled(enable_option),
_ts_is_ready(false)
{
}
double global_timestamp_reader::get_frame_timestamp(const std::shared_ptr<frame_interface>& frame)
{
double frame_time = _device_timestamp_reader->get_frame_timestamp(frame);
rs2_timestamp_domain ts_domain = _device_timestamp_reader->get_frame_timestamp_domain(frame);
if (_option_is_enabled->is_true() && ts_domain == RS2_TIMESTAMP_DOMAIN_HARDWARE_CLOCK)
{
auto sp = _time_diff_keeper.lock();
if (sp)
frame_time = sp->get_system_hw_time(frame_time, _ts_is_ready);
else
LOG_DEBUG("Notification: global_timestamp_reader - time_diff_keeper is being shut-down");
}
return frame_time;
}
unsigned long long global_timestamp_reader::get_frame_counter(const std::shared_ptr<frame_interface>& frame) const
{
return _device_timestamp_reader->get_frame_counter(frame);
}
rs2_timestamp_domain global_timestamp_reader::get_frame_timestamp_domain(const std::shared_ptr<frame_interface>& frame) const
{
rs2_timestamp_domain ts_domain = _device_timestamp_reader->get_frame_timestamp_domain(frame);
return (_option_is_enabled->is_true() && _ts_is_ready && ts_domain == RS2_TIMESTAMP_DOMAIN_HARDWARE_CLOCK) ? RS2_TIMESTAMP_DOMAIN_GLOBAL_TIME : ts_domain;
}
void global_timestamp_reader::reset()
{
_device_timestamp_reader->reset();
}
global_time_interface::global_time_interface() :
_tf_keeper(std::make_shared<time_diff_keeper>(this, 100))
{}
void global_time_interface::enable_time_diff_keeper(bool is_enable)
{
if (is_enable)
_tf_keeper->start();
else
_tf_keeper->stop();
}
}
|
fix global_timestamp_reader to make first time request from device sooner. Reduces number of frame requests receiving Hardware timestamp instead of global timestamp.
|
fix global_timestamp_reader to make first time request from device sooner. Reduces number of frame requests receiving Hardware timestamp instead of global timestamp.
|
C++
|
apache-2.0
|
IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense,IntelRealSense/librealsense
|
85b489739fbc2d1ab430aea311ab381b4ee55848
|
Driver/RewriteTest.cpp
|
Driver/RewriteTest.cpp
|
//===--- RewriteTest.cpp - Rewriter playground ----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is a testbed.
//
//===----------------------------------------------------------------------===//
#include "clang.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Rewrite/TokenRewriter.h"
#include <iostream>
void clang::DoRewriteTest(Preprocessor &PP, const std::string &InFileName,
const std::string &OutFileName) {
SourceManager &SM = PP.getSourceManager();
const LangOptions &LangOpts = PP.getLangOptions();
TokenRewriter Rewriter(SM.getMainFileID(), SM, LangOpts);
// Throw <i> </i> tags around comments.
for (TokenRewriter::token_iterator I = Rewriter.token_begin(),
E = Rewriter.token_end(); I != E; ++I) {
if (I->isNot(tok::comment)) continue;
Rewriter.AddTokenBefore(I, "<i>");
Rewriter.AddTokenAfter(I, "</i>");
}
// Print out the output.
for (TokenRewriter::token_iterator I = Rewriter.token_begin(),
E = Rewriter.token_end(); I != E; ++I)
std::cout << PP.getSpelling(*I);
}
|
//===--- RewriteTest.cpp - Rewriter playground ----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is a testbed.
//
//===----------------------------------------------------------------------===//
#include "clang.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Rewrite/TokenRewriter.h"
#include <iostream>
void clang::DoRewriteTest(Preprocessor &PP, const std::string &InFileName,
const std::string &OutFileName) {
SourceManager &SM = PP.getSourceManager();
const LangOptions &LangOpts = PP.getLangOptions();
TokenRewriter Rewriter(SM.getMainFileID(), SM, LangOpts);
// Throw <i> </i> tags around comments.
for (TokenRewriter::token_iterator I = Rewriter.token_begin(),
E = Rewriter.token_end(); I != E; ++I) {
if (I->isNot(tok::comment)) continue;
Rewriter.AddTokenBefore(I, "<i>");
Rewriter.AddTokenAfter(I, "</i>");
}
// Print out the output.
for (TokenRewriter::token_iterator I = Rewriter.token_begin(),
E = Rewriter.token_end(); I != E; ++I)
std::cout << PP.getSpelling(*I);
}
|
Add newline at the end of file, to silence compiler warning.
|
Add newline at the end of file, to silence compiler warning.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@57818 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang
|
4f2becd2d1fb613afa9e6a73b7f02b478be6f884
|
Source/platform/fonts/skia/FontCacheSkia.cpp
|
Source/platform/fonts/skia/FontCacheSkia.cpp
|
/*
* Copyright (c) 2006, 2007, 2008, 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if !OS(WIN) && !OS(ANDROID)
#include "SkFontConfigInterface.h"
#endif
#include "SkFontMgr.h"
#include "SkStream.h"
#include "SkTypeface.h"
#include "platform/NotImplemented.h"
#include "platform/fonts/AlternateFontFamily.h"
#include "platform/fonts/FontCache.h"
#include "platform/fonts/FontDescription.h"
#include "platform/fonts/FontFaceCreationParams.h"
#include "platform/fonts/SimpleFontData.h"
#include "public/platform/Platform.h"
#include "public/platform/linux/WebSandboxSupport.h"
#include "wtf/Assertions.h"
#include "wtf/text/AtomicString.h"
#include "wtf/text/CString.h"
#include <unicode/locid.h>
#if !OS(WIN) && !OS(ANDROID)
static SkStream* streamForFontconfigInterfaceId(int fontconfigInterfaceId)
{
SkAutoTUnref<SkFontConfigInterface> fci(SkFontConfigInterface::RefGlobal());
SkFontConfigInterface::FontIdentity fontIdentity;
fontIdentity.fID = fontconfigInterfaceId;
return fci->openStream(fontIdentity);
}
#endif
namespace WebCore {
void FontCache::platformInit()
{
}
PassRefPtr<SimpleFontData> FontCache::fallbackOnStandardFontStyle(
const FontDescription& fontDescription, UChar32 character)
{
FontDescription substituteDescription(fontDescription);
substituteDescription.setStyle(FontStyleNormal);
substituteDescription.setWeight(FontWeightNormal);
FontFaceCreationParams creationParams(substituteDescription.family().family());
FontPlatformData* substitutePlatformData = getFontPlatformData(substituteDescription, creationParams);
if (substitutePlatformData && substitutePlatformData->fontContainsCharacter(character)) {
FontPlatformData platformData = FontPlatformData(*substitutePlatformData);
platformData.setSyntheticBold(fontDescription.weight() >= FontWeight600);
platformData.setSyntheticItalic(fontDescription.style() == FontStyleItalic);
return fontDataFromFontPlatformData(&platformData, DoNotRetain);
}
return nullptr;
}
#if !OS(WIN) && !OS(ANDROID)
PassRefPtr<SimpleFontData> FontCache::fallbackFontForCharacter(const FontDescription& fontDescription, UChar32 c, const SimpleFontData*)
{
// First try the specified font with standard style & weight.
if (fontDescription.style() == FontStyleItalic
|| fontDescription.weight() >= FontWeight600) {
RefPtr<SimpleFontData> fontData = fallbackOnStandardFontStyle(
fontDescription, c);
if (fontData)
return fontData;
}
FontCache::PlatformFallbackFont fallbackFont;
FontCache::getFontForCharacter(c, "", &fallbackFont);
if (fallbackFont.name.isEmpty())
return nullptr;
FontFaceCreationParams creationParams;
creationParams = FontFaceCreationParams(fallbackFont.filename, fallbackFont.fontconfigInterfaceId, fallbackFont.ttcIndex);
// Changes weight and/or italic of given FontDescription depends on
// the result of fontconfig so that keeping the correct font mapping
// of the given character. See http://crbug.com/32109 for details.
bool shouldSetSyntheticBold = false;
bool shouldSetSyntheticItalic = false;
FontDescription description(fontDescription);
if (fallbackFont.isBold && description.weight() < FontWeightBold)
description.setWeight(FontWeightBold);
if (!fallbackFont.isBold && description.weight() >= FontWeightBold) {
shouldSetSyntheticBold = true;
description.setWeight(FontWeightNormal);
}
if (fallbackFont.isItalic && description.style() == FontStyleNormal)
description.setStyle(FontStyleItalic);
if (!fallbackFont.isItalic && description.style() == FontStyleItalic) {
shouldSetSyntheticItalic = true;
description.setStyle(FontStyleNormal);
}
FontPlatformData* substitutePlatformData = getFontPlatformData(description, creationParams);
if (!substitutePlatformData)
return nullptr;
FontPlatformData platformData = FontPlatformData(*substitutePlatformData);
platformData.setSyntheticBold(shouldSetSyntheticBold);
platformData.setSyntheticItalic(shouldSetSyntheticItalic);
return fontDataFromFontPlatformData(&platformData, DoNotRetain);
}
#endif // !OS(WIN) && !OS(ANDROID)
PassRefPtr<SimpleFontData> FontCache::getLastResortFallbackFont(const FontDescription& description, ShouldRetain shouldRetain)
{
const FontFaceCreationParams fallbackCreationParams(getFallbackFontFamily(description));
const FontPlatformData* fontPlatformData = getFontPlatformData(description, fallbackCreationParams);
// We should at least have Sans or Arial which is the last resort fallback of SkFontHost ports.
if (!fontPlatformData) {
DEFINE_STATIC_LOCAL(const FontFaceCreationParams, sansCreationParams, (AtomicString("Sans", AtomicString::ConstructFromLiteral)));
fontPlatformData = getFontPlatformData(description, sansCreationParams);
}
if (!fontPlatformData) {
DEFINE_STATIC_LOCAL(const FontFaceCreationParams, arialCreationParams, (AtomicString("Arial", AtomicString::ConstructFromLiteral)));
fontPlatformData = getFontPlatformData(description, arialCreationParams);
}
ASSERT(fontPlatformData);
return fontDataFromFontPlatformData(fontPlatformData, shouldRetain);
}
PassRefPtr<SkTypeface> FontCache::createTypeface(const FontDescription& fontDescription, const FontFaceCreationParams& creationParams, CString& name)
{
#if !OS(WIN) && !OS(ANDROID)
if (creationParams.creationType() == CreateFontByFciIdAndTtcIndex) {
// TODO(dro): crbug.com/381620 Use creationParams.ttcIndex() after
// https://code.google.com/p/skia/issues/detail?id=1186 gets fixed.
SkTypeface* typeface = nullptr;
if (blink::Platform::current()->sandboxSupport())
typeface = SkTypeface::CreateFromStream(streamForFontconfigInterfaceId(creationParams.fontconfigInterfaceId()));
else
typeface = SkTypeface::CreateFromFile(creationParams.filename().data());
if (typeface)
return adoptRef(typeface);
}
#endif
AtomicString family = creationParams.family();
// If we're creating a fallback font (e.g. "-webkit-monospace"), convert the name into
// the fallback name (like "monospace") that fontconfig understands.
if (!family.length() || family.startsWith("-webkit-")) {
name = getFallbackFontFamily(fontDescription).string().utf8();
} else {
// convert the name to utf8
name = family.utf8();
}
int style = SkTypeface::kNormal;
if (fontDescription.weight() >= FontWeight600)
style |= SkTypeface::kBold;
if (fontDescription.style())
style |= SkTypeface::kItalic;
#if OS(WIN)
if (s_sideloadedFonts) {
HashMap<String, SkTypeface*>::iterator sideloadedFont = s_sideloadedFonts->find(name.data());
if (sideloadedFont != s_sideloadedFonts->end()) {
return adoptRef(sideloadedFont->value);
}
}
// FIXME: Use SkFontStyle and matchFamilyStyle instead of legacyCreateTypeface.
if (m_fontManager)
return adoptRef(m_fontManager->legacyCreateTypeface(name.data(), style));
#endif
return adoptRef(SkTypeface::CreateFromName(name.data(), static_cast<SkTypeface::Style>(style)));
}
#if !OS(WIN)
FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const FontFaceCreationParams& creationParams, float fontSize)
{
CString name;
RefPtr<SkTypeface> tf(createTypeface(fontDescription, creationParams, name));
if (!tf)
return 0;
FontPlatformData* result = new FontPlatformData(tf,
name.data(),
fontSize,
(fontDescription.weight() >= FontWeight600 && !tf->isBold()) || fontDescription.isSyntheticBold(),
(fontDescription.style() && !tf->isItalic()) || fontDescription.isSyntheticItalic(),
fontDescription.orientation(),
fontDescription.useSubpixelPositioning());
return result;
}
#endif // !OS(WIN)
} // namespace WebCore
|
/*
* Copyright (c) 2006, 2007, 2008, 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#if !OS(WIN) && !OS(ANDROID)
#include "SkFontConfigInterface.h"
#endif
#include "SkFontMgr.h"
#include "SkStream.h"
#include "SkTypeface.h"
#include "platform/NotImplemented.h"
#include "platform/fonts/AlternateFontFamily.h"
#include "platform/fonts/FontCache.h"
#include "platform/fonts/FontDescription.h"
#include "platform/fonts/FontFaceCreationParams.h"
#include "platform/fonts/SimpleFontData.h"
#include "public/platform/Platform.h"
#include "public/platform/linux/WebSandboxSupport.h"
#include "wtf/Assertions.h"
#include "wtf/text/AtomicString.h"
#include "wtf/text/CString.h"
#include <unicode/locid.h>
#if !OS(WIN) && !OS(ANDROID)
static SkStream* streamForFontconfigInterfaceId(int fontconfigInterfaceId)
{
SkAutoTUnref<SkFontConfigInterface> fci(SkFontConfigInterface::RefGlobal());
SkFontConfigInterface::FontIdentity fontIdentity;
fontIdentity.fID = fontconfigInterfaceId;
return fci->openStream(fontIdentity);
}
#endif
namespace WebCore {
void FontCache::platformInit()
{
}
PassRefPtr<SimpleFontData> FontCache::fallbackOnStandardFontStyle(
const FontDescription& fontDescription, UChar32 character)
{
FontDescription substituteDescription(fontDescription);
substituteDescription.setStyle(FontStyleNormal);
substituteDescription.setWeight(FontWeightNormal);
FontFaceCreationParams creationParams(substituteDescription.family().family());
FontPlatformData* substitutePlatformData = getFontPlatformData(substituteDescription, creationParams);
if (substitutePlatformData && substitutePlatformData->fontContainsCharacter(character)) {
FontPlatformData platformData = FontPlatformData(*substitutePlatformData);
platformData.setSyntheticBold(fontDescription.weight() >= FontWeight600);
platformData.setSyntheticItalic(fontDescription.style() == FontStyleItalic);
return fontDataFromFontPlatformData(&platformData, DoNotRetain);
}
return nullptr;
}
#if !OS(WIN) && !OS(ANDROID)
PassRefPtr<SimpleFontData> FontCache::fallbackFontForCharacter(const FontDescription& fontDescription, UChar32 c, const SimpleFontData*)
{
// First try the specified font with standard style & weight.
if (fontDescription.style() == FontStyleItalic
|| fontDescription.weight() >= FontWeight600) {
RefPtr<SimpleFontData> fontData = fallbackOnStandardFontStyle(
fontDescription, c);
if (fontData)
return fontData;
}
FontCache::PlatformFallbackFont fallbackFont;
FontCache::getFontForCharacter(c, "", &fallbackFont);
if (fallbackFont.name.isEmpty())
return nullptr;
FontFaceCreationParams creationParams;
creationParams = FontFaceCreationParams(fallbackFont.filename, fallbackFont.fontconfigInterfaceId, fallbackFont.ttcIndex);
// Changes weight and/or italic of given FontDescription depends on
// the result of fontconfig so that keeping the correct font mapping
// of the given character. See http://crbug.com/32109 for details.
bool shouldSetSyntheticBold = false;
bool shouldSetSyntheticItalic = false;
FontDescription description(fontDescription);
if (fallbackFont.isBold && description.weight() < FontWeightBold)
description.setWeight(FontWeightBold);
if (!fallbackFont.isBold && description.weight() >= FontWeightBold) {
shouldSetSyntheticBold = true;
description.setWeight(FontWeightNormal);
}
if (fallbackFont.isItalic && description.style() == FontStyleNormal)
description.setStyle(FontStyleItalic);
if (!fallbackFont.isItalic && description.style() == FontStyleItalic) {
shouldSetSyntheticItalic = true;
description.setStyle(FontStyleNormal);
}
FontPlatformData* substitutePlatformData = getFontPlatformData(description, creationParams);
if (!substitutePlatformData)
return nullptr;
FontPlatformData platformData = FontPlatformData(*substitutePlatformData);
platformData.setSyntheticBold(shouldSetSyntheticBold);
platformData.setSyntheticItalic(shouldSetSyntheticItalic);
return fontDataFromFontPlatformData(&platformData, DoNotRetain);
}
#endif // !OS(WIN) && !OS(ANDROID)
PassRefPtr<SimpleFontData> FontCache::getLastResortFallbackFont(const FontDescription& description, ShouldRetain shouldRetain)
{
const FontFaceCreationParams fallbackCreationParams(getFallbackFontFamily(description));
const FontPlatformData* fontPlatformData = getFontPlatformData(description, fallbackCreationParams);
// We should at least have Sans or Arial which is the last resort fallback of SkFontHost ports.
if (!fontPlatformData) {
DEFINE_STATIC_LOCAL(const FontFaceCreationParams, sansCreationParams, (AtomicString("Sans", AtomicString::ConstructFromLiteral)));
fontPlatformData = getFontPlatformData(description, sansCreationParams);
}
if (!fontPlatformData) {
DEFINE_STATIC_LOCAL(const FontFaceCreationParams, arialCreationParams, (AtomicString("Arial", AtomicString::ConstructFromLiteral)));
fontPlatformData = getFontPlatformData(description, arialCreationParams);
}
#if OS(WIN)
// Try some more Windows-specific fallbacks.
if (!fontPlatformData) {
DEFINE_STATIC_LOCAL(const FontFaceCreationParams, msuigothicCreationParams, (AtomicString("MS UI Gothic", AtomicString::ConstructFromLiteral)));
fontPlatformData = getFontPlatformData(description, msuigothicCreationParams);
}
if (!fontPlatformData) {
DEFINE_STATIC_LOCAL(const FontFaceCreationParams, mssansserifCreationParams, (AtomicString("Microsoft Sans Serif", AtomicString::ConstructFromLiteral)));
fontPlatformData = getFontPlatformData(description, mssansserifCreationParams);
}
#endif
ASSERT(fontPlatformData);
return fontDataFromFontPlatformData(fontPlatformData, shouldRetain);
}
PassRefPtr<SkTypeface> FontCache::createTypeface(const FontDescription& fontDescription, const FontFaceCreationParams& creationParams, CString& name)
{
#if !OS(WIN) && !OS(ANDROID)
if (creationParams.creationType() == CreateFontByFciIdAndTtcIndex) {
// TODO(dro): crbug.com/381620 Use creationParams.ttcIndex() after
// https://code.google.com/p/skia/issues/detail?id=1186 gets fixed.
SkTypeface* typeface = nullptr;
if (blink::Platform::current()->sandboxSupport())
typeface = SkTypeface::CreateFromStream(streamForFontconfigInterfaceId(creationParams.fontconfigInterfaceId()));
else
typeface = SkTypeface::CreateFromFile(creationParams.filename().data());
if (typeface)
return adoptRef(typeface);
}
#endif
AtomicString family = creationParams.family();
// If we're creating a fallback font (e.g. "-webkit-monospace"), convert the name into
// the fallback name (like "monospace") that fontconfig understands.
if (!family.length() || family.startsWith("-webkit-")) {
name = getFallbackFontFamily(fontDescription).string().utf8();
} else {
// convert the name to utf8
name = family.utf8();
}
int style = SkTypeface::kNormal;
if (fontDescription.weight() >= FontWeight600)
style |= SkTypeface::kBold;
if (fontDescription.style())
style |= SkTypeface::kItalic;
#if OS(WIN)
if (s_sideloadedFonts) {
HashMap<String, SkTypeface*>::iterator sideloadedFont = s_sideloadedFonts->find(name.data());
if (sideloadedFont != s_sideloadedFonts->end()) {
return adoptRef(sideloadedFont->value);
}
}
// FIXME: Use SkFontStyle and matchFamilyStyle instead of legacyCreateTypeface.
if (m_fontManager)
return adoptRef(m_fontManager->legacyCreateTypeface(name.data(), style));
#endif
return adoptRef(SkTypeface::CreateFromName(name.data(), static_cast<SkTypeface::Style>(style)));
}
#if !OS(WIN)
FontPlatformData* FontCache::createFontPlatformData(const FontDescription& fontDescription, const FontFaceCreationParams& creationParams, float fontSize)
{
CString name;
RefPtr<SkTypeface> tf(createTypeface(fontDescription, creationParams, name));
if (!tf)
return 0;
FontPlatformData* result = new FontPlatformData(tf,
name.data(),
fontSize,
(fontDescription.weight() >= FontWeight600 && !tf->isBold()) || fontDescription.isSyntheticBold(),
(fontDescription.style() && !tf->isItalic()) || fontDescription.isSyntheticItalic(),
fontDescription.orientation(),
fontDescription.useSubpixelPositioning());
return result;
}
#endif // !OS(WIN)
} // namespace WebCore
|
Add more Windows-specific fonts to fallback path
|
Add more Windows-specific fonts to fallback path
MS Shell Dlg is the aliased font name that means "the one font that
shall always be available" per http://msdn.microsoft.com/en-us/library/windows/desktop/dd374112(v=vs.85).aspx
DirectWrite doesn't like that name, but we add the two fonts that it
can map to so that we can be very certain to succeed on retreiving a
font, even if Arial has gone missing.
[email protected]
BUG=383542
Review URL: https://codereview.chromium.org/402503003
git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@178380 bbb929c8-8fbe-4397-9dbb-9b2b20218538
|
C++
|
bsd-3-clause
|
smishenk/blink-crosswalk,modulexcite/blink,crosswalk-project/blink-crosswalk-efl,XiaosongWei/blink-crosswalk,smishenk/blink-crosswalk,hgl888/blink-crosswalk-efl,crosswalk-project/blink-crosswalk-efl,jtg-gg/blink,kurli/blink-crosswalk,PeterWangIntel/blink-crosswalk,XiaosongWei/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,jtg-gg/blink,modulexcite/blink,ondra-novak/blink,XiaosongWei/blink-crosswalk,hgl888/blink-crosswalk-efl,ondra-novak/blink,smishenk/blink-crosswalk,kurli/blink-crosswalk,PeterWangIntel/blink-crosswalk,ondra-novak/blink,nwjs/blink,modulexcite/blink,hgl888/blink-crosswalk-efl,kurli/blink-crosswalk,nwjs/blink,crosswalk-project/blink-crosswalk-efl,jtg-gg/blink,Pluto-tv/blink-crosswalk,smishenk/blink-crosswalk,Bysmyyr/blink-crosswalk,Pluto-tv/blink-crosswalk,Bysmyyr/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,nwjs/blink,modulexcite/blink,crosswalk-project/blink-crosswalk-efl,PeterWangIntel/blink-crosswalk,Pluto-tv/blink-crosswalk,Bysmyyr/blink-crosswalk,hgl888/blink-crosswalk-efl,smishenk/blink-crosswalk,Bysmyyr/blink-crosswalk,nwjs/blink,ondra-novak/blink,crosswalk-project/blink-crosswalk-efl,hgl888/blink-crosswalk-efl,modulexcite/blink,jtg-gg/blink,modulexcite/blink,modulexcite/blink,PeterWangIntel/blink-crosswalk,XiaosongWei/blink-crosswalk,Bysmyyr/blink-crosswalk,XiaosongWei/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,Pluto-tv/blink-crosswalk,Pluto-tv/blink-crosswalk,modulexcite/blink,Bysmyyr/blink-crosswalk,XiaosongWei/blink-crosswalk,kurli/blink-crosswalk,Bysmyyr/blink-crosswalk,Pluto-tv/blink-crosswalk,jtg-gg/blink,PeterWangIntel/blink-crosswalk,hgl888/blink-crosswalk-efl,hgl888/blink-crosswalk-efl,modulexcite/blink,kurli/blink-crosswalk,Bysmyyr/blink-crosswalk,hgl888/blink-crosswalk-efl,ondra-novak/blink,ondra-novak/blink,XiaosongWei/blink-crosswalk,PeterWangIntel/blink-crosswalk,nwjs/blink,kurli/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,Bysmyyr/blink-crosswalk,Pluto-tv/blink-crosswalk,kurli/blink-crosswalk,nwjs/blink,nwjs/blink,Pluto-tv/blink-crosswalk,nwjs/blink,ondra-novak/blink,hgl888/blink-crosswalk-efl,nwjs/blink,hgl888/blink-crosswalk-efl,Pluto-tv/blink-crosswalk,kurli/blink-crosswalk,modulexcite/blink,XiaosongWei/blink-crosswalk,kurli/blink-crosswalk,jtg-gg/blink,jtg-gg/blink,smishenk/blink-crosswalk,kurli/blink-crosswalk,jtg-gg/blink,ondra-novak/blink,smishenk/blink-crosswalk,nwjs/blink,PeterWangIntel/blink-crosswalk,PeterWangIntel/blink-crosswalk,smishenk/blink-crosswalk,XiaosongWei/blink-crosswalk,jtg-gg/blink,smishenk/blink-crosswalk,XiaosongWei/blink-crosswalk,Bysmyyr/blink-crosswalk,PeterWangIntel/blink-crosswalk,PeterWangIntel/blink-crosswalk,Pluto-tv/blink-crosswalk,ondra-novak/blink,smishenk/blink-crosswalk,jtg-gg/blink
|
b3021447d1da2817e133acab3e55d23da7e10eed
|
include/stack.hpp
|
include/stack.hpp
|
#ifndef STACK_HPP
#define STACK_HPP
#include <cstdlib>
#include <iostream>
#include <memory>
template <typename T>
class allocator {
protected:
allocator(size_t size = 0);
~allocator();
auto swap(allocator & other) -> void;
allocator(allocator const &) = delete;
auto operator=(allocator const &)->allocator & = delete;
T * ptr_;
size_t size_;
size_t count_;
};
template <typename T>
class stack : private allocator<T>
{
public:
stack();
size_t count() const;
void push(T const &elem);
void pop();
const T& top();
~stack();
stack(const stack &b);
stack & operator=(const stack &b);
bool operator==(stack const & _s);
bool empty() const noexcept;
void swap(stack &v);
private:
size_t array_size_;
size_t count_;
T * array_;
};
template<typename T>
T*copy_new(const T*arr,size_t count,size_t array_size)
{
T*l= new T[array_size];
try
{
std::copy(arr,arr+count,l);
}
catch(...)
{
delete[] l;
throw;
}
return l;
}
#include "stack.cpp"
#endif
|
#ifndef STACK_HPP
#define STACK_HPP
#include <cstdlib>
#include <iostream>
#include <memory>
template <typename T>
class allocator {
protected:
allocator(size_t size = 0);
~allocator();
auto swap(allocator & other) -> void;
allocator(allocator const &) = delete;
auto operator=(allocator const &)->allocator & = delete;
T * ptr_;
size_t size_;
size_t count_;
};
template <typename T>
class stack : private allocator<T>
{
public:
stack();
size_t count() const;
void push(T const &elem);
void pop();
const T& top();
~stack();
stack(const stack &b);
stack & operator=(const stack &b);
bool operator==(stack const & _s);
bool empty() const noexcept;
void swap(stack &v);
private:
size_t array_size_;
size_t count_;
T * array_;
};
template<typename T>
T*copy_new(const T*arr,size_t count,size_t array_size)
{
T*l= new T[array_size];
try
{
std::copy(arr,arr+count,l);
}
catch(...)
{
delete[] l;
throw;
}
return l;
}
#include "stack.cpp"
#endif
|
Update stack.hpp
|
Update stack.hpp
|
C++
|
mit
|
anastasiya0304/stack
|
eadbaf90d6c7b3ac4bccdaa1f8e7a0746a140321
|
src/html/HTMLLinkElementImp.cpp
|
src/html/HTMLLinkElementImp.cpp
|
/*
* Copyright 2010-2013 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "HTMLLinkElementImp.h"
#include <boost/bind.hpp>
#include <boost/version.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include "one_at_a_time.hpp"
constexpr auto Intern = &one_at_a_time::hash<char16_t>;
#include "DocumentImp.h"
#include "DOMTokenListImp.h"
#include "WindowImp.h"
#include "HTMLUtil.h"
#include "css/BoxImage.h"
#include "css/CSSInputStream.h"
#include "css/CSSParser.h"
#include "css/CSSStyleSheetImp.h"
#include "css/Ico.h"
#include "Test.util.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
HTMLLinkElementImp::HTMLLinkElementImp(DocumentImp* ownerDocument) :
ObjectMixin(ownerDocument, u"link"),
request(0),
styleSheet(0)
{
tabIndex = -1;
}
HTMLLinkElementImp::HTMLLinkElementImp(HTMLLinkElementImp* org, bool deep) :
ObjectMixin(org, deep),
request(0), // TODO: XXX
styleSheet(org->styleSheet) // TODO: make a clone sheet, too?
{
}
HTMLLinkElementImp::~HTMLLinkElementImp()
{
delete request;
}
void HTMLLinkElementImp::handleMutation(events::MutationEvent mutation)
{
switch (Intern(mutation.getAttrName().c_str())) {
case Intern(u"href"):
handleMutationHref(mutation);
break;
case Intern(u"tabindex"):
if (hasAttribute(u"href") && !toInteger(mutation.getNewValue(), tabIndex))
tabIndex = 0;
break;
default:
HTMLElementImp::handleMutation(mutation);
break;
}
}
void HTMLLinkElementImp::eval()
{
std::u16string href = getHref();
if (href.empty())
return;
std::u16string rel = getRel();
toLower(rel);
if (::contains(rel, u"stylesheet")) {
// TODO: check "type"
if (!::contains(rel, u"alternate")) {
// Check "media"
std::u16string mediaText = getMedia();
Retained<MediaListImp> mediaList;
mediaList.setMediaText(mediaText);
if (mediaText.empty() || mediaList.hasMedium(MediaListImp::Screen)) { // TODO: support other mediums, too.
DocumentImp* document = getOwnerDocumentImp();
request = new(std::nothrow) HttpRequest(document->getDocumentURI());
if (request) {
request->open(u"GET", href);
request->setHandler(boost::bind(&HTMLLinkElementImp::linkStyleSheet, this));
document->incrementLoadEventDelayCount();
request->send();
}
}
}
}
else if (::contains(rel, u"icon")) {
DocumentImp* document = getOwnerDocumentImp();
request = new(std::nothrow) HttpRequest(document->getDocumentURI());
if (request) {
request->open(u"GET", href);
request->setHandler(boost::bind(&HTMLLinkElementImp::linkIcon, this));
document->incrementLoadEventDelayCount();
request->send();
}
}
}
void HTMLLinkElementImp::linkStyleSheet()
{
DocumentImp* document = getOwnerDocumentImp();
if (request->getStatus() == 200) {
boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(request->getContentDescriptor(), boost::iostreams::close_handle);
CSSParser parser;
CSSInputStream cssStream(stream, request->getResponseMessage().getContentCharset(), utfconv(document->getCharacterSet()));
styleSheet = parser.parse(document, cssStream);
if (auto imp = dynamic_cast<CSSStyleSheetImp*>(styleSheet.self())) {
imp->setHref(request->getRequestMessage().getURL());
imp->setOwnerNode(this);
}
if (4 <= getLogLevel())
dumpStyleSheet(std::cerr, styleSheet.self());
document->resetStyleSheets();
if (WindowImp* view = document->getDefaultWindow())
view->setFlags(Box::NEED_SELECTOR_REMATCHING);
}
document->decrementLoadEventDelayCount();
}
void HTMLLinkElementImp::linkIcon()
{
DocumentImp* document = getOwnerDocumentImp();
setFavicon(document);
document->decrementLoadEventDelayCount();
}
bool HTMLLinkElementImp::setFavicon(DocumentImp* document)
{
std::u16string rel = getRel();
toLower(rel);
if (!::contains(rel, u"icon"))
return false;
if (!request || request->getStatus() != 200)
return false;
bool result = false;
if (FILE* file = request->openFile()) {
std::u16string type = getType();
if (type == u"image/vnd.microsoft.icon" || type.empty()) {
IcoImage ico;
if (ico.open(file)) {
if (WindowImp* view = document->getDefaultWindow()) {
view->setFavicon(&ico, file);
result = true;
}
}
} else {
BoxImage image;
image.open(file);
if (image.getState() == BoxImage::CompletelyAvailable) {
if (WindowImp* view = document->getDefaultWindow()) {
view->setFavicon(&image);
result = true;
}
}
}
fclose(file);
}
return result;
}
// Node
Node HTMLLinkElementImp::cloneNode(bool deep)
{
return new(std::nothrow) HTMLLinkElementImp(this, deep);
}
// HTMLLinkElement
bool HTMLLinkElementImp::getDisabled()
{
if (!styleSheet)
return false;
return styleSheet.getDisabled();
}
void HTMLLinkElementImp::setDisabled(bool disabled)
{
if (styleSheet)
styleSheet.setDisabled(disabled);
}
std::u16string HTMLLinkElementImp::getHref()
{
return getAttribute(u"href");
}
void HTMLLinkElementImp::setHref(const std::u16string& href)
{
setAttribute(u"href", href);
}
std::u16string HTMLLinkElementImp::getRel()
{
return getAttribute(u"rel");
}
void HTMLLinkElementImp::setRel(const std::u16string& rel)
{
setAttribute(u"rel", rel);
}
DOMTokenList HTMLLinkElementImp::getRelList()
{
return new(std::nothrow) DOMTokenListImp(this, u"rel");
}
std::u16string HTMLLinkElementImp::getMedia()
{
return getAttribute(u"media");
}
void HTMLLinkElementImp::setMedia(const std::u16string& media)
{
setAttribute(u"media", media);
}
std::u16string HTMLLinkElementImp::getHreflang()
{
return getAttribute(u"hreflang");
}
void HTMLLinkElementImp::setHreflang(const std::u16string& hreflang)
{
setAttribute(u"hreflang", hreflang);
}
std::u16string HTMLLinkElementImp::getType()
{
return getAttribute(u"type");
}
void HTMLLinkElementImp::setType(const std::u16string& type)
{
setAttribute(u"type", type);
}
DOMSettableTokenList HTMLLinkElementImp::getSizes()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLLinkElementImp::setSizes(const std::u16string& sizes)
{
// TODO: implement me!
}
stylesheets::StyleSheet HTMLLinkElementImp::getSheet()
{
return styleSheet;
}
std::u16string HTMLLinkElementImp::getCharset()
{
// TODO: implement me!
return u"";
}
void HTMLLinkElementImp::setCharset(const std::u16string& charset)
{
// TODO: implement me!
}
std::u16string HTMLLinkElementImp::getRev()
{
// TODO: implement me!
return u"";
}
void HTMLLinkElementImp::setRev(const std::u16string& rev)
{
// TODO: implement me!
}
std::u16string HTMLLinkElementImp::getTarget()
{
// TODO: implement me!
return u"";
}
void HTMLLinkElementImp::setTarget(const std::u16string& target)
{
// TODO: implement me!
}
}}}} // org::w3c::dom::bootstrap
|
/*
* Copyright 2010-2013 Esrille Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "HTMLLinkElementImp.h"
#include <boost/bind.hpp>
#include <boost/version.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
#include "one_at_a_time.hpp"
constexpr auto Intern = &one_at_a_time::hash<char16_t>;
#include "DocumentImp.h"
#include "DOMTokenListImp.h"
#include "WindowImp.h"
#include "HTMLUtil.h"
#include "css/BoxImage.h"
#include "css/CSSInputStream.h"
#include "css/CSSParser.h"
#include "css/CSSStyleSheetImp.h"
#include "css/Ico.h"
#include "Test.util.h"
namespace org { namespace w3c { namespace dom { namespace bootstrap {
HTMLLinkElementImp::HTMLLinkElementImp(DocumentImp* ownerDocument) :
ObjectMixin(ownerDocument, u"link"),
request(0),
styleSheet(0)
{
tabIndex = -1;
}
HTMLLinkElementImp::HTMLLinkElementImp(HTMLLinkElementImp* org, bool deep) :
ObjectMixin(org, deep),
request(0), // TODO: XXX
styleSheet(org->styleSheet) // TODO: make a clone sheet, too?
{
}
HTMLLinkElementImp::~HTMLLinkElementImp()
{
delete request;
}
void HTMLLinkElementImp::handleMutation(events::MutationEvent mutation)
{
switch (Intern(mutation.getAttrName().c_str())) {
case Intern(u"href"):
handleMutationHref(mutation);
break;
case Intern(u"tabindex"):
if (hasAttribute(u"href") && !toInteger(mutation.getNewValue(), tabIndex))
tabIndex = 0;
break;
default:
HTMLElementImp::handleMutation(mutation);
break;
}
}
void HTMLLinkElementImp::eval()
{
std::u16string href = getHref();
if (href.empty())
return;
std::u16string rel = getRel();
toLower(rel);
if (::contains(rel, u"stylesheet")) {
// TODO: check "type"
if (!::contains(rel, u"alternate")) {
// Check "media"
std::u16string mediaText = getMedia();
Retained<MediaListImp> mediaList;
mediaList.setMediaText(mediaText);
if (mediaText.empty() || mediaList.hasMedium(MediaListImp::Screen)) { // TODO: support other mediums, too.
DocumentImp* document = getOwnerDocumentImp();
request = new(std::nothrow) HttpRequest(document->getDocumentURI());
if (request) {
request->open(u"GET", href);
request->setHandler(boost::bind(&HTMLLinkElementImp::linkStyleSheet, this));
document->incrementLoadEventDelayCount();
request->send();
}
}
}
}
else if (::contains(rel, u"icon")) {
DocumentImp* document = getOwnerDocumentImp();
request = new(std::nothrow) HttpRequest(document->getDocumentURI());
if (request) {
request->open(u"GET", href);
request->setHandler(boost::bind(&HTMLLinkElementImp::linkIcon, this));
document->incrementLoadEventDelayCount();
request->send();
}
}
}
void HTMLLinkElementImp::linkStyleSheet()
{
DocumentImp* document = getOwnerDocumentImp();
if (request->getStatus() == 200) {
boost::iostreams::stream<boost::iostreams::file_descriptor_source> stream(request->getContentDescriptor(), boost::iostreams::close_handle);
CSSParser parser;
CSSInputStream cssStream(stream, request->getResponseMessage().getContentCharset(), utfconv(document->getCharacterSet()));
styleSheet = parser.parse(document, cssStream);
if (auto imp = dynamic_cast<CSSStyleSheetImp*>(styleSheet.self())) {
imp->setHref(request->getRequestMessage().getURL());
imp->setOwnerNode(this);
}
if (4 <= getLogLevel())
dumpStyleSheet(std::cerr, styleSheet.self());
document->resetStyleSheets();
if (WindowImp* view = document->getDefaultWindow())
view->setFlags(Box::NEED_SELECTOR_REMATCHING);
}
document->decrementLoadEventDelayCount();
}
void HTMLLinkElementImp::linkIcon()
{
DocumentImp* document = getOwnerDocumentImp();
setFavicon(document);
document->decrementLoadEventDelayCount();
}
bool HTMLLinkElementImp::setFavicon(DocumentImp* document)
{
std::u16string rel = getRel();
toLower(rel);
if (!::contains(rel, u"icon"))
return false;
if (!request || request->getStatus() != 200)
return false;
bool result = false;
if (FILE* file = request->openFile()) {
std::u16string type = getType();
if (type == u"image/vnd.microsoft.icon" || type.empty()) {
IcoImage ico;
if (ico.open(file)) {
if (WindowImp* view = document->getDefaultWindow()) {
view->setFavicon(&ico, file);
result = true;
}
}
} else {
BoxImage image;
image.open(file);
if (image.getState() == BoxImage::CompletelyAvailable) {
if (WindowImp* view = document->getDefaultWindow()) {
view->setFavicon(&image);
result = true;
}
}
}
fclose(file);
}
return result;
}
// Node
Node HTMLLinkElementImp::cloneNode(bool deep)
{
return new(std::nothrow) HTMLLinkElementImp(this, deep);
}
// HTMLLinkElement
bool HTMLLinkElementImp::getDisabled()
{
if (!styleSheet)
return false;
return styleSheet.getDisabled();
}
void HTMLLinkElementImp::setDisabled(bool disabled)
{
if (styleSheet)
styleSheet.setDisabled(disabled);
}
std::u16string HTMLLinkElementImp::getHref()
{
return getAttributeAsURL(u"href");
}
void HTMLLinkElementImp::setHref(const std::u16string& href)
{
setAttribute(u"href", href);
}
std::u16string HTMLLinkElementImp::getRel()
{
return getAttribute(u"rel");
}
void HTMLLinkElementImp::setRel(const std::u16string& rel)
{
setAttribute(u"rel", rel);
}
DOMTokenList HTMLLinkElementImp::getRelList()
{
return new(std::nothrow) DOMTokenListImp(this, u"rel");
}
std::u16string HTMLLinkElementImp::getMedia()
{
return getAttribute(u"media");
}
void HTMLLinkElementImp::setMedia(const std::u16string& media)
{
setAttribute(u"media", media);
}
std::u16string HTMLLinkElementImp::getHreflang()
{
return getAttribute(u"hreflang");
}
void HTMLLinkElementImp::setHreflang(const std::u16string& hreflang)
{
setAttribute(u"hreflang", hreflang);
}
std::u16string HTMLLinkElementImp::getType()
{
return getAttribute(u"type");
}
void HTMLLinkElementImp::setType(const std::u16string& type)
{
setAttribute(u"type", type);
}
DOMSettableTokenList HTMLLinkElementImp::getSizes()
{
// TODO: implement me!
return static_cast<Object*>(0);
}
void HTMLLinkElementImp::setSizes(const std::u16string& sizes)
{
// TODO: implement me!
}
stylesheets::StyleSheet HTMLLinkElementImp::getSheet()
{
return styleSheet;
}
std::u16string HTMLLinkElementImp::getCharset()
{
// TODO: implement me!
return u"";
}
void HTMLLinkElementImp::setCharset(const std::u16string& charset)
{
// TODO: implement me!
}
std::u16string HTMLLinkElementImp::getRev()
{
// TODO: implement me!
return u"";
}
void HTMLLinkElementImp::setRev(const std::u16string& rev)
{
// TODO: implement me!
}
std::u16string HTMLLinkElementImp::getTarget()
{
// TODO: implement me!
return u"";
}
void HTMLLinkElementImp::setTarget(const std::u16string& target)
{
// TODO: implement me!
}
}}}} // org::w3c::dom::bootstrap
|
Fix a bug
|
(HTMLLinkElementImp::getHref): Fix a bug
|
C++
|
apache-2.0
|
esrille/escudo,esrille/escudo,esrille/escudo,esrille/escudo,esrille/escudo
|
66609a03a0457f5271e2556ffca35f496e29efc2
|
src/hyperion-x11/X11Wrapper.cpp
|
src/hyperion-x11/X11Wrapper.cpp
|
// Hyperion-X11 includes
#include "X11Wrapper.h"
X11Wrapper::X11Wrapper(int grabInterval, int cropLeft, int cropRight, int cropTop, int cropBottom, int horizontalPixelDecimation, int verticalPixelDecimation) :
_timer(this),
_grabber(cropLeft, cropRight, cropTop, cropBottom, horizontalPixelDecimation, verticalPixelDecimation)
{
_timer.setSingleShot(false);
_timer.setInterval(grabInterval);
// Connect capturing to the timeout signal of the timer
connect(&_timer, SIGNAL(timeout()), this, SLOT(capture()));
}
const Image<ColorRgb> & X11Wrapper::getScreenshot()
{
const Image<ColorRgb> & screenshot = _grabber.grab();
return screenshot;
}
void X11Wrapper::start()
{
_timer.start();
}
void X11Wrapper::stop()
{
_timer.stop();
}
void X11Wrapper::capture()
{
const Image<ColorRgb> & screenshot = _grabber.grab();
emit sig_screenshot(screenshot);
}
|
// Hyperion-X11 includes
#include "X11Wrapper.h"
X11Wrapper::X11Wrapper(int grabInterval, int cropLeft, int cropRight, int cropTop, int cropBottom, int horizontalPixelDecimation, int verticalPixelDecimation) :
_timer(this),
_grabber(cropLeft, cropRight, cropTop, cropBottom, horizontalPixelDecimation, verticalPixelDecimation)
{
_timer.setSingleShot(false);
_timer.setInterval(grabInterval);
// Connect capturing to the timeout signal of the timer
connect(&_timer, SIGNAL(timeout()), this, SLOT(capture()));
}
const Image<ColorRgb> & X11Wrapper::getScreenshot()
{
const Image<ColorRgb> & screenshot = _grabber.grab();
return screenshot;
}
void X11Wrapper::start()
{
_timer.start();
}
void X11Wrapper::stop()
{
_timer.stop();
}
bool X11Wrapper::displayInit()
{
return _grabber.Setup();
}
void X11Wrapper::capture()
{
const Image<ColorRgb> & screenshot = _grabber.grab();
emit sig_screenshot(screenshot);
}
|
Update X11Wrapper.cpp
|
Update X11Wrapper.cpp
Former-commit-id: f644a24c77db18feb34526aa937f12700865f5be
|
C++
|
mit
|
hyperion-project/hyperion,hyperion-project/hyperion.ng,redPanther/hyperion.ng,ntim/hyperion,hyperion-project/hyperion.ng,hyperion-project/hyperion,Funatiq/hyperion.ng,hyperion-project/hyperion,penfold42/hyperion.ng,hyperion-project/hyperion.ng,hyperion-project/hyperion,ntim/hyperion,hyperion-project/hyperion,redPanther/hyperion.ng,Funatiq/hyperion.ng,penfold42/hyperion.ng,Funatiq/hyperion.ng,penfold42/hyperion.ng,ntim/hyperion,redPanther/hyperion.ng,hyperion-project/hyperion,ntim/hyperion,redPanther/hyperion.ng,hyperion-project/hyperion.ng,redPanther/hyperion.ng,Funatiq/hyperion.ng,hyperion-project/hyperion.ng,penfold42/hyperion.ng,penfold42/hyperion.ng,Funatiq/hyperion.ng,penfold42/hyperion.ng,Funatiq/hyperion.ng,ntim/hyperion,hyperion-project/hyperion.ng,ntim/hyperion,redPanther/hyperion.ng
|
a964deda7360b3bdb3358812cb69451c7760a344
|
rk78/rk78_init.cpp
|
rk78/rk78_init.cpp
|
/**
* \file
* \brief Implementation of the necessary initialization for Boost's RK78-Felhberg solver
*
* \author Nicholas Curtis
* \date 04/15/2016
*
*/
//wrapper code
#include "rk78_typedefs.hpp"
#ifdef GENERATE_DOCS
namespace rk78 {
#endif
//! State vector containers for boost
std::vector<state_type*> state_vectors;
//! RHS wrappers for boost
std::vector<rhs_eval*> evaluators;
//! Addaptive timesteppers
std::vector<stepper*> steppers;
//! ODE controllers
std::vector<controller*> controllers;
#ifdef STIFFNESS_MEASURE
std::vector<double> max_stepsize;
#include <stdio.h>
FILE* stepsizes;
#endif
extern "C" void initialize_solver(int);
extern "C" void cleanup_solver(int);
extern "C" const char* solver_name();
extern "C" void init_solver_log();
extern "C" void solver_log();
/*! \fn void initialize_solver(int num_threads)
\brief Initializes the solver
\param num_threads The number of OpenMP threads to use
*/
void initialize_solver(int num_threads) {
//create the necessary state vectors and evaluators
for (int i = 0; i < num_threads; ++i)
{
state_vectors.push_back(new state_type(NSP, 0.0));
evaluators.push_back(new rhs_eval());
steppers.push_back(new stepper());
controllers.push_back(new controller(ATOL, RTOL, *steppers[i]));
}
}
/*!
\brief Cleans up the created solvers
\param num_threads The number of OpenMP threads used
Frees and cleans up allocated RK78 memory.
*/
void cleanup_solver(int num_threads) {
for (int i = 0; i < state_vectors.size(); ++i)
{
delete state_vectors[i];
delete evaluators[i];
delete steppers[i];
delete controllers[i];
}
#ifdef STIFFNESS_MEASURE
fclose(stepsizes);
#endif
}
/*!
\fn char* solver_name()
\brief Returns a descriptive solver name
*/
const char* solver_name() {
const char* name = "rk78-int";
return name;
}
/*!
\fn init_solver_log()
\brief Initializes solver specific items for logging
Initializes stepsize logging for stiffness measurement
*/
void init_solver_log() {
#ifdef STIFFNESS_MEASURE
stepsizes = fopen("stepsize_log.txt", "w");
#endif
}
/*!
\fn solver_log()
\brief Executes solver specific logging tasks
*/
void solver_log() {
#ifdef STIFFNESS_MEASURE
for (int i = 0; i < max_stepsize.size(); ++i){
fprintf(stepsizes, "%d\t%.16e\n", i, max_stepsize[i]);
}
#endif
}
#ifdef GENERATE_DOCS
}
#endif
|
/**
* \file
* \brief Implementation of the necessary initialization for Boost's RK78-Felhberg solver
*
* \author Nicholas Curtis
* \date 04/15/2016
*
*/
//wrapper code
#include "rk78_typedefs.hpp"
#ifdef GENERATE_DOCS
namespace rk78 {
#endif
//! State vector containers for boost
std::vector<state_type*> state_vectors;
//! RHS wrappers for boost
std::vector<rhs_eval*> evaluators;
//! Addaptive timesteppers
std::vector<stepper*> steppers;
//! ODE controllers
std::vector<controller> controllers;
#ifdef STIFFNESS_MEASURE
std::vector<double> max_stepsize;
#include <stdio.h>
FILE* stepsizes;
#endif
extern "C" void initialize_solver(int);
extern "C" void cleanup_solver(int);
extern "C" const char* solver_name();
extern "C" void init_solver_log();
extern "C" void solver_log();
/*! \fn void initialize_solver(int num_threads)
\brief Initializes the solver
\param num_threads The number of OpenMP threads to use
*/
void initialize_solver(int num_threads) {
//create the necessary state vectors and evaluators
for (int i = 0; i < num_threads; ++i)
{
state_vectors.push_back(new state_type(NSP, 0.0));
evaluators.push_back(new rhs_eval());
steppers.push_back(new stepper());
controllers.push_back(make_controlled<stepper>(ATOL, RTOL, *steppers[i]));
}
}
/*!
\brief Cleans up the created solvers
\param num_threads The number of OpenMP threads used
Frees and cleans up allocated RK78 memory.
*/
void cleanup_solver(int num_threads) {
for (int i = 0; i < state_vectors.size(); ++i)
{
delete state_vectors[i];
delete evaluators[i];
delete steppers[i];
controllers.pop_back();
}
#ifdef STIFFNESS_MEASURE
fclose(stepsizes);
#endif
}
/*!
\fn char* solver_name()
\brief Returns a descriptive solver name
*/
const char* solver_name() {
const char* name = "rk78-int";
return name;
}
/*!
\fn init_solver_log()
\brief Initializes solver specific items for logging
Initializes stepsize logging for stiffness measurement
*/
void init_solver_log() {
#ifdef STIFFNESS_MEASURE
stepsizes = fopen("stepsize_log.txt", "w");
#endif
}
/*!
\fn solver_log()
\brief Executes solver specific logging tasks
*/
void solver_log() {
#ifdef STIFFNESS_MEASURE
for (int i = 0; i < max_stepsize.size(); ++i){
fprintf(stepsizes, "%d\t%.16e\n", i, max_stepsize[i]);
}
#endif
}
#ifdef GENERATE_DOCS
}
#endif
|
use make_controller to support older versions of boost
|
use make_controller to support older versions of boost
|
C++
|
mit
|
SLACKHA/accelerInt,SLACKHA/accelerInt,SLACKHA/accelerInt,SLACKHA/accelerInt
|
769cf00442061157dd6838e4d3ee1dbd0310f08c
|
config.tests/db/main.cpp
|
config.tests/db/main.cpp
|
#include <db.h>
#if DB_VERSION_MAJOR < 4
#error db>=4.4 required
#endif
#if DB_VERSION_MINOR < 4
#error db>=4.4 required
#endif
#if DB_VERSION_MINOR < 6
#warning db < 4.6, some features will be disabled
#endif
int main (int,char**)
{
DB * db;
db_create(&db, NULL, 0);
return 0;
}
|
#include <db.h>
#if DB_VERSION_MAJOR < 4
#error db>=4.4 required
#endif
#if DB_VERSION_MAJOR < 5
#if DB_VERSION_MINOR < 4
#error db>=4.4 required
#endif
#if DB_VERSION_MINOR < 6
#warning db < 4.6, some features will be disabled
#endif
#endif
int main (int,char**)
{
DB * db;
db_create(&db, NULL, 0);
return 0;
}
|
fix db version check to respect MAJOR>4
|
fix db version check to respect MAJOR>4
|
C++
|
bsd-3-clause
|
mmitkevich/libqxt,hrobeers/qxtweb-qt5,mmitkevich/libqxt,mmitkevich/libqxt,mmitkevich/libqxt,hrobeers/qxtweb-qt5,hrobeers/qxtweb-qt5,hrobeers/qxtweb-qt5,hrobeers/qxtweb-qt5
|
1df129aab79b00a662559d7d7744d1e32fe1dbd6
|
io/pipe_simple.cc
|
io/pipe_simple.cc
|
#include <common/buffer.h>
#include <event/action.h>
#include <event/callback.h>
#include <event/event_system.h>
#include <io/pipe.h>
#include <io/pipe_simple.h>
/*
* PipeSimple is a pipe which passes data through a processing function and
* which provides no discipline -- it will always immediately signal that it is
* ready to process more data.
*
* TODO: Asynchronous processing function.
*
* XXX Should flag error and ensure all subsequent input() and output() fail.
*/
PipeSimple::PipeSimple(const LogHandle& log)
: log_(log),
input_buffer_(),
input_eos_(false),
output_action_(NULL),
output_callback_(NULL)
{
}
PipeSimple::~PipeSimple()
{
ASSERT(output_action_ == NULL);
ASSERT(output_callback_ == NULL);
}
Action *
PipeSimple::input(Buffer *buf, EventCallback *cb)
{
if (buf->empty()) {
input_eos_ = true;
}
if (output_callback_ != NULL) {
ASSERT(input_buffer_.empty());
ASSERT(output_action_ == NULL);
Buffer tmp;
if (!process(&tmp, buf)) {
output_callback_->event(Event(Event::Error, 0));
output_action_ = EventSystem::instance()->schedule(output_callback_);
output_callback_ = NULL;
cb->event(Event(Event::Error, 0));
return (EventSystem::instance()->schedule(cb));
}
ASSERT(buf->empty());
if (!tmp.empty() || input_eos_) {
if (input_eos_ && tmp.empty()) {
output_callback_->event(Event(Event::EOS, 0));
} else {
output_callback_->event(Event(Event::Done, 0, tmp));
}
output_action_ = EventSystem::instance()->schedule(output_callback_);
output_callback_ = NULL;
}
} else {
if (!buf->empty()) {
input_buffer_.append(buf);
buf->clear();
}
}
cb->event(Event(Event::Done, 0));
return (EventSystem::instance()->schedule(cb));
}
Action *
PipeSimple::output(EventCallback *cb)
{
ASSERT(output_action_ == NULL);
ASSERT(output_callback_ == NULL);
if (!input_buffer_.empty() || input_eos_) {
Buffer tmp;
if (!process(&tmp, &input_buffer_)) {
cb->event(Event(Event::Error, 0));
return (EventSystem::instance()->schedule(cb));
}
ASSERT(input_buffer_.empty());
if (!tmp.empty() || input_eos_) {
if (input_eos_ && tmp.empty()) {
cb->event(Event(Event::EOS, 0));
} else {
ASSERT(!tmp.empty());
cb->event(Event(Event::Done, 0, tmp));
}
return (EventSystem::instance()->schedule(cb));
}
}
output_callback_ = cb;
return (cancellation(this, &PipeSimple::output_cancel));
}
void
PipeSimple::output_cancel(void)
{
if (output_action_ != NULL) {
ASSERT(output_callback_ == NULL);
output_action_->cancel();
output_action_ = NULL;
}
if (output_callback_ != NULL) {
delete output_callback_;
output_callback_ = NULL;
}
}
void
PipeSimple::output_spontaneous(void)
{
if (output_callback_ == NULL)
return;
Buffer tmp;
if (!process(&tmp, &input_buffer_)) {
output_callback_->event(Event(Event::Error, 0));
output_action_ = EventSystem::instance()->schedule(output_callback_);
output_callback_ = NULL;
return;
}
ASSERT(input_buffer_.empty());
/*
* XXX
* Would prefer for this to never happen!
*/
if (tmp.empty() && !input_eos_) {
DEBUG(log_) << "Spontaneous output generated no output despite EOS being unset.";
return;
}
if (tmp.empty()) {
output_callback_->event(Event(Event::EOS, 0));
} else {
output_callback_->event(Event(Event::Done, 0, tmp));
}
output_action_ = EventSystem::instance()->schedule(output_callback_);
output_callback_ = NULL;
}
|
#include <common/buffer.h>
#include <event/action.h>
#include <event/callback.h>
#include <event/event_system.h>
#include <io/pipe.h>
#include <io/pipe_simple.h>
/*
* PipeSimple is a pipe which passes data through a processing function and
* which provides no discipline -- it will always immediately signal that it is
* ready to process more data.
*
* TODO: Asynchronous processing function.
*
* XXX Should flag error and ensure all subsequent input() and output() fail.
*/
PipeSimple::PipeSimple(const LogHandle& log)
: log_(log),
input_buffer_(),
input_eos_(false),
output_action_(NULL),
output_callback_(NULL)
{
}
PipeSimple::~PipeSimple()
{
ASSERT(output_action_ == NULL);
ASSERT(output_callback_ == NULL);
}
Action *
PipeSimple::input(Buffer *buf, EventCallback *cb)
{
if (buf->empty()) {
input_eos_ = true;
}
if (output_callback_ != NULL) {
ASSERT(output_action_ == NULL);
Buffer tmp;
if (!process(&tmp, buf)) {
output_callback_->event(Event(Event::Error, 0));
output_action_ = EventSystem::instance()->schedule(output_callback_);
output_callback_ = NULL;
cb->event(Event(Event::Error, 0));
return (EventSystem::instance()->schedule(cb));
}
if (!tmp.empty() || input_eos_) {
if (input_eos_ && tmp.empty()) {
output_callback_->event(Event(Event::EOS, 0));
} else {
output_callback_->event(Event(Event::Done, 0, tmp));
}
output_action_ = EventSystem::instance()->schedule(output_callback_);
output_callback_ = NULL;
}
}
if (!buf->empty()) {
input_buffer_.append(buf);
buf->clear();
}
cb->event(Event(Event::Done, 0));
return (EventSystem::instance()->schedule(cb));
}
Action *
PipeSimple::output(EventCallback *cb)
{
ASSERT(output_action_ == NULL);
ASSERT(output_callback_ == NULL);
if (!input_buffer_.empty() || input_eos_) {
Buffer tmp;
if (!process(&tmp, &input_buffer_)) {
cb->event(Event(Event::Error, 0));
return (EventSystem::instance()->schedule(cb));
}
if (!tmp.empty() || input_eos_) {
if (input_eos_ && tmp.empty()) {
ASSERT(input_buffer_.empty());
cb->event(Event(Event::EOS, 0));
} else {
ASSERT(!tmp.empty());
cb->event(Event(Event::Done, 0, tmp));
}
return (EventSystem::instance()->schedule(cb));
}
}
output_callback_ = cb;
return (cancellation(this, &PipeSimple::output_cancel));
}
void
PipeSimple::output_cancel(void)
{
if (output_action_ != NULL) {
ASSERT(output_callback_ == NULL);
output_action_->cancel();
output_action_ = NULL;
}
if (output_callback_ != NULL) {
delete output_callback_;
output_callback_ = NULL;
}
}
void
PipeSimple::output_spontaneous(void)
{
if (output_callback_ == NULL)
return;
Buffer tmp;
if (!process(&tmp, &input_buffer_)) {
output_callback_->event(Event(Event::Error, 0));
output_action_ = EventSystem::instance()->schedule(output_callback_);
output_callback_ = NULL;
return;
}
ASSERT(input_buffer_.empty());
/*
* XXX
* Would prefer for this to never happen!
*/
if (tmp.empty() && !input_eos_) {
DEBUG(log_) << "Spontaneous output generated no output despite EOS being unset.";
return;
}
if (tmp.empty()) {
output_callback_->event(Event(Event::EOS, 0));
} else {
output_callback_->event(Event(Event::Done, 0, tmp));
}
output_action_ = EventSystem::instance()->schedule(output_callback_);
output_callback_ = NULL;
}
|
Fix some assertions and queueing needs.
|
Fix some assertions and queueing needs.
git-svn-id: 9e2532540f1574e817ce42f20b9d0fb64899e451@394 4068ffdb-0463-0410-8185-8cc71e3bd399
|
C++
|
bsd-2-clause
|
splbio/wanproxy,splbio/wanproxy,diegows/wanproxy,diegows/wanproxy,diegows/wanproxy,splbio/wanproxy
|
ec2d399e9a32b91767e2104b07661ce25a929d57
|
tests/src/NanoWinMsPrintfTests.cpp
|
tests/src/NanoWinMsPrintfTests.cpp
|
#include "NWUnitTest.h"
#ifdef __linux
#include "NanoWinMsPrintf.h"
#include <unistd.h>
#else
#include <windows.h>
#endif
#define NanoWinMsSWPrintf swprintf
#define NanoWinMsVSWPrintf vswprintf
#define NanoWinMsWPrintf wprintf
#define NanoWinMsVWPrintf vwprintf
#define NanoWinMsFWPrintf fwprintf
#define NanoWinMsVFWPrintf vfwprintf
#define FILE_NAME ("testFile.txt")
#define FILE_NAME_W (L"testFile.txt")
static FILE *GetFile()
{
#ifndef __GNUC__
FILE *stream = _wfopen(FILE_NAME_W, L"w+t");
#else
FILE *stream = fopen(FILE_NAME, "w+t");
#endif
if (stream != NULL)
{
return stream;
}
else return NULL;
}
static void CloseFile(FILE *stream)
{
if (stream != NULL)
{
fclose(stream);
}
#ifndef __GNUC__
_wunlink(FILE_NAME_W);
#else
unlink(FILE_NAME);
#endif
}
static void ReadFile(FILE *stream, wchar_t *buff)
{
fseek(stream, 0, SEEK_SET);
if (stream != NULL)
{
fgetws(buff, 256, stream);
}
}
NW_BEGIN_TEST_GROUP_SIMPLE(PrintfWFormatMs2UnixTestGroup)
NW_TEST(PrintfWFormatMs2UnixTestGroup, PrintfWFormatMs2UnixSimpleTest)
{
const wchar_t *srcS = L"%s";
wchar_t destS[256];
NanoWinMsWFormatProcMs2Unix(destS, srcS);
NW_CHECK_EQUAL_MEMCMP(L"%S", destS, 3 * sizeof(wchar_t));
const wchar_t *srcC = L"%c";
wchar_t destC[256];
NanoWinMsWFormatProcMs2Unix(destC, srcC);
NW_CHECK_EQUAL_MEMCMP(L"%C", destC, 3 * sizeof(wchar_t));
const wchar_t *srcSs = L"%S";
wchar_t destSs[256];
NanoWinMsWFormatProcMs2Unix(destSs, srcSs);
NW_CHECK_EQUAL_MEMCMP(L"%s", destSs, 3 * sizeof(wchar_t));
const wchar_t *srcCs = L"%C";
wchar_t destCs[256];
NanoWinMsWFormatProcMs2Unix(destCs, srcCs);
NW_CHECK_EQUAL_MEMCMP(L"%c", destCs, 3 * sizeof(wchar_t));
const wchar_t *srcLS = L"%ls";
wchar_t destLS[256];
NanoWinMsWFormatProcMs2Unix(destLS, srcLS);
NW_CHECK_EQUAL_MEMCMP(L"%ls", destLS, 4 * sizeof(wchar_t));
const wchar_t *srcLC = L"%lc";
wchar_t destLC[256];
NanoWinMsWFormatProcMs2Unix(destLC, srcLC);
NW_CHECK_EQUAL_MEMCMP(L"%lc", destLC, 4 * sizeof(wchar_t));
const wchar_t *srcWS = L"%ws";
wchar_t destWS[256];
NanoWinMsWFormatProcMs2Unix(destWS, srcWS);
NW_CHECK_EQUAL_MEMCMP(L"%ls", destWS, 4 * sizeof(wchar_t));
const wchar_t *srcWC = L"%wc";
wchar_t destWC[256];
NanoWinMsWFormatProcMs2Unix(destWC, srcWC);
NW_CHECK_EQUAL_MEMCMP(L"%lc", destWC, 4 * sizeof(wchar_t));
}
NW_TEST(PrintfWFormatMs2UnixTestGroup, PrintfWFormatMs2UnixTest)
{
const wchar_t *srcS = L"%5s %#20S";
wchar_t destS[256];
NanoWinMsWFormatProcMs2Unix(destS, srcS);
NW_CHECK_EQUAL_MEMCMP(L"%5S %#20s", destS, 10 * sizeof(wchar_t));
const wchar_t *srcF = L"%+0*f %4.2f";
wchar_t destF[256];
NanoWinMsWFormatProcMs2Unix(destF, srcF);
NW_CHECK_EQUAL_MEMCMP(L"%+0*f %4.2f", destF, 13 * sizeof(wchar_t));
const wchar_t *srcD = L"%+05lld %-I64i %02I32u %#x%#X %#3o";
wchar_t destD[256];
NanoWinMsWFormatProcMs2Unix(destD, srcD);
NW_CHECK_EQUAL_MEMCMP(L"%+05lld %-I64i %02I32u %#x%#X %#3o", destD, 37 * sizeof(wchar_t));
const wchar_t *srcC = L"%-c %5C %wc";
wchar_t destC[256];
NanoWinMsWFormatProcMs2Unix(destC, srcC);
NW_CHECK_EQUAL_MEMCMP(L"%-C %5c %lc", destC, 12 * sizeof(wchar_t));
const wchar_t *srcG = L"%-3lg %+5LG";
wchar_t destG[256];
NanoWinMsWFormatProcMs2Unix(destG, srcG);
NW_CHECK_EQUAL_MEMCMP(L"%-3lg %+5LG", destG, 12 * sizeof(wchar_t));
const wchar_t *srcA = L"%-*3.a %+5#A";
wchar_t destA[256];
NanoWinMsWFormatProcMs2Unix(destA, srcA);
NW_CHECK_EQUAL_MEMCMP(L"%-*3.a %+5#A", destA, 15 * sizeof(wchar_t));
}
NW_END_TEST_GROUP()
NW_BEGIN_TEST_GROUP_SIMPLE(NanoWinMsSWPrintfTestGroup)
NW_TEST(NanoWinMsSWPrintfTestGroup, NanoWinMsSWPrintfSimpleTest)
{
wchar_t str[256];
int count0 = NanoWinMsSWPrintf(str, 5, L"test");
NW_CHECK_EQUAL(4, count0);
NW_CHECK_EQUAL_MEMCMP(L"test", str, 5 * sizeof(wchar_t));
int count1 = NanoWinMsSWPrintf(str, 4, L"%s", L"abc");
NW_CHECK_EQUAL(3, count1);
NW_CHECK_EQUAL_MEMCMP(L"abc", str, 4 * sizeof(wchar_t));
int count2 = NanoWinMsSWPrintf(str, 4, L"%ws", L"def");
NW_CHECK_EQUAL(3, count2);
NW_CHECK_EQUAL_MEMCMP(L"def", str, 4 * sizeof(wchar_t));
int count3 = NanoWinMsSWPrintf(str, 4, L"%wc", L'g');
NW_CHECK_EQUAL(1, count3);
NW_CHECK_EQUAL_MEMCMP(L"g", str, 2 * sizeof(wchar_t));
int count4 = NanoWinMsSWPrintf(str, 4, L"%hd", (short int)-12);
NW_CHECK_EQUAL(3, count4);
NW_CHECK_EQUAL_MEMCMP(L"-12", str, 4 * sizeof(wchar_t));
int count5 = NanoWinMsSWPrintf(str, 4, L"%lu", (unsigned long int)34);
NW_CHECK_EQUAL(2, count5);
NW_CHECK_EQUAL_MEMCMP(L"34", str, 3 * sizeof(wchar_t));
int count6 = NanoWinMsSWPrintf(str, 4, L"%c", L'd');
NW_CHECK_EQUAL(1, count6);
NW_CHECK_EQUAL_MEMCMP(L"d", str, 2 * sizeof(wchar_t));
int count7 = NanoWinMsSWPrintf(str, 5, L"%#x", 0xFF);
NW_CHECK_EQUAL(4, count7);
NW_CHECK_EQUAL_MEMCMP(L"0xff", str, 5 * sizeof(wchar_t));
int count8 = NanoWinMsSWPrintf(str, 5, L"%#X", 0xff);
NW_CHECK_EQUAL(4, count8);
NW_CHECK_EQUAL_MEMCMP(L"0XFF", str, 5 * sizeof(wchar_t));
int count9 = NanoWinMsSWPrintf(str, 5, L"%o", 056);
NW_CHECK_EQUAL(2, count9);
NW_CHECK_EQUAL_MEMCMP(L"56", str, 3 * sizeof(wchar_t));
int count10 = NanoWinMsSWPrintf(str, 10, L"%f", 5.678f);
NW_CHECK_EQUAL(8, count10);
NW_CHECK_EQUAL_MEMCMP(L"5.678000", str, 9 * sizeof(wchar_t));
}
NW_TEST(NanoWinMsSWPrintfTestGroup, NanoWinMsSWPrintfTest)
{
wchar_t str[256];
int count1 = NanoWinMsSWPrintf(str, sizeof(str) / sizeof(wchar_t), L"%ls ww %#2s%ws", L"abc", L"f", L"zz");
NW_CHECK_EQUAL(11, count1);
NW_CHECK_EQUAL_MEMCMP(L"abc ww fzz", str, 12 * sizeof(wchar_t));
int count2 = NanoWinMsSWPrintf(str, sizeof(str) / sizeof(wchar_t), L"%c %wc %lc", L'd', L'e', L'f');
NW_CHECK_EQUAL(5, count2);
NW_CHECK_EQUAL_MEMCMP(L"d e f", str, 6 * sizeof(wchar_t));
int count3 = NanoWinMsSWPrintf(str, sizeof(str) / sizeof(wchar_t), L"%hd %+i bb %#llu", (short int)-56, 123, (long long unsigned int)10);
NW_CHECK_EQUAL(15, count3);
NW_CHECK_EQUAL_MEMCMP(L"-56 +123 bb 10", str, 16 * sizeof(wchar_t));
int count4 = NanoWinMsSWPrintf(str, sizeof(str) / sizeof(wchar_t), L"%#x %#X %x", 11, 22, 33);
NW_CHECK_EQUAL(12, count4);
NW_CHECK_EQUAL_MEMCMP(L"0xb 0X16 21", str, 13 * sizeof(wchar_t));
int count5 = NanoWinMsSWPrintf(str, sizeof(str) / sizeof(wchar_t), L"%o %#o", 056, 24);
NW_CHECK_EQUAL(7, count5);
NW_CHECK_EQUAL_MEMCMP(L"56 030", str, 8 * sizeof(wchar_t));
int count6 = NanoWinMsSWPrintf(str, sizeof(str) / sizeof(wchar_t), L"%.*f %.3f", 3, 0.1312f, 1.22222f);
NW_CHECK_EQUAL(11, count6);
NW_CHECK_EQUAL_MEMCMP(L"0.131 1.222", str, 12 * sizeof(wchar_t));
}
NW_END_TEST_GROUP()
NW_BEGIN_TEST_GROUP_SIMPLE(NanoWinMsFWPrintfTestGroup)
#ifndef __GNUC__
NW_TEST(NanoWinMsFWPrintfTestGroup, NanoWinMsFWPrintfSTest)
{
wchar_t str[256];
FILE *file = GetFile();
if (file != NULL)
{
int count = NanoWinMsFWPrintf(file, L"%ls ww %#2s%ws", L"abc", L"f", L"zz");
NW_CHECK_EQUAL(11, count);
ReadFile(file, str);
NW_CHECK_EQUAL_MEMCMP(L"abc ww fzz", str, 12 * sizeof(wchar_t));
CloseFile(file);
}
}
NW_TEST(NanoWinMsFWPrintfTestGroup, NanoWinMsFWPrintfCTest)
{
wchar_t str[256];
FILE *file = GetFile();
if (file != NULL)
{
int count = NanoWinMsFWPrintf(file, L"%c %wc %lc", L'd', L'e', L'f');
NW_CHECK_EQUAL(5, count);
ReadFile(file, str);
NW_CHECK_EQUAL_MEMCMP(L"d e f", str, 6 * sizeof(wchar_t));
CloseFile(file);
}
}
#endif
NW_TEST(NanoWinMsFWPrintfTestGroup, NanoWinMsFWPrintfDTest)
{
wchar_t str[256];
FILE *file = GetFile();
if (file != NULL)
{
int count = NanoWinMsFWPrintf(file, L"%hd %+i bb %#llu", (short int)-56, 123, (long long unsigned int)10);
NW_CHECK_EQUAL(15, count);
ReadFile(file, str);
NW_CHECK_EQUAL_MEMCMP(L"-56 +123 bb 10", str, 16 * sizeof(wchar_t));
CloseFile(file);
}
}
NW_TEST(NanoWinMsFWPrintfTestGroup, NanoWinMsFWPrintfXTest)
{
wchar_t str[256];
FILE *file = GetFile();
if (file != NULL)
{
int count = NanoWinMsFWPrintf(file, L"%#x %#X %x", 11, 22, 33);
NW_CHECK_EQUAL(12, count);
ReadFile(file, str);
NW_CHECK_EQUAL_MEMCMP(L"0xb 0X16 21", str, 13 * sizeof(wchar_t));
CloseFile(file);
}
}
NW_TEST(NanoWinMsFWPrintfTestGroup, NanoWinMsFWPrintfOTest)
{
wchar_t str[256];
FILE *file = GetFile();
if (file != NULL)
{
int count = NanoWinMsFWPrintf(file, L"%o %#o", 056, 24);
NW_CHECK_EQUAL(7, count);
ReadFile(file, str);
NW_CHECK_EQUAL_MEMCMP(L"56 030", str, 8 * sizeof(wchar_t));
CloseFile(file);
}
}
NW_TEST(NanoWinMsFWPrintfTestGroup, NanoWinMsFWPrintfFTest)
{
wchar_t str[256];
FILE *file = GetFile();
if (file != NULL)
{
int count = NanoWinMsFWPrintf(file, L"%.*f %.3f", 3, 0.1312f, 1.22222f);
NW_CHECK_EQUAL(11, count);
ReadFile(file, str);
NW_CHECK_EQUAL_MEMCMP(L"0.131 1.222", str, 12 * sizeof(wchar_t));
CloseFile(file);
}
}
NW_END_TEST_GROUP()
|
#include "NWUnitTest.h"
#ifdef __linux
#include "NanoWinMsPrintf.h"
#include <unistd.h>
#else
#include <windows.h>
#endif
#define NanoWinMsSWPrintf swprintf
#define NanoWinMsVSWPrintf vswprintf
#define NanoWinMsWPrintf wprintf
#define NanoWinMsVWPrintf vwprintf
#define NanoWinMsFWPrintf fwprintf
#define NanoWinMsVFWPrintf vfwprintf
#define FILE_NAME ("testFile.txt")
#define FILE_NAME_W (L"testFile.txt")
static FILE *GetFile()
{
#ifndef __GNUC__
FILE *stream = _wfopen(FILE_NAME_W, L"w+t");
#else
FILE *stream = fopen(FILE_NAME, "w+t");
#endif
if (stream != NULL)
{
return stream;
}
else return NULL;
}
static void CloseFile(FILE *stream)
{
if (stream != NULL)
{
fclose(stream);
}
#ifndef __GNUC__
_wunlink(FILE_NAME_W);
#else
unlink(FILE_NAME);
#endif
}
static void ReadFile(FILE *stream, wchar_t *buff)
{
fseek(stream, 0, SEEK_SET);
if (stream != NULL)
{
fgetws(buff, 256, stream);
}
}
NW_BEGIN_TEST_GROUP_SIMPLE(PrintfWFormatMs2UnixTestGroup)
NW_TEST(PrintfWFormatMs2UnixTestGroup, PrintfWFormatMs2UnixSimpleTest)
{
const wchar_t *srcS = L"%s";
wchar_t destS[256];
NanoWinMsWFormatProcMs2Unix(destS, srcS);
NW_CHECK_EQUAL_MEMCMP(L"%S", destS, 3 * sizeof(wchar_t));
const wchar_t *srcC = L"%c";
wchar_t destC[256];
NanoWinMsWFormatProcMs2Unix(destC, srcC);
NW_CHECK_EQUAL_MEMCMP(L"%C", destC, 3 * sizeof(wchar_t));
const wchar_t *srcSs = L"%S";
wchar_t destSs[256];
NanoWinMsWFormatProcMs2Unix(destSs, srcSs);
NW_CHECK_EQUAL_MEMCMP(L"%s", destSs, 3 * sizeof(wchar_t));
const wchar_t *srcCs = L"%C";
wchar_t destCs[256];
NanoWinMsWFormatProcMs2Unix(destCs, srcCs);
NW_CHECK_EQUAL_MEMCMP(L"%c", destCs, 3 * sizeof(wchar_t));
const wchar_t *srcLS = L"%ls";
wchar_t destLS[256];
NanoWinMsWFormatProcMs2Unix(destLS, srcLS);
NW_CHECK_EQUAL_MEMCMP(L"%ls", destLS, 4 * sizeof(wchar_t));
const wchar_t *srcLC = L"%lc";
wchar_t destLC[256];
NanoWinMsWFormatProcMs2Unix(destLC, srcLC);
NW_CHECK_EQUAL_MEMCMP(L"%lc", destLC, 4 * sizeof(wchar_t));
const wchar_t *srcWS = L"%ws";
wchar_t destWS[256];
NanoWinMsWFormatProcMs2Unix(destWS, srcWS);
NW_CHECK_EQUAL_MEMCMP(L"%ls", destWS, 4 * sizeof(wchar_t));
const wchar_t *srcWC = L"%wc";
wchar_t destWC[256];
NanoWinMsWFormatProcMs2Unix(destWC, srcWC);
NW_CHECK_EQUAL_MEMCMP(L"%lc", destWC, 4 * sizeof(wchar_t));
}
NW_TEST(PrintfWFormatMs2UnixTestGroup, PrintfWFormatMs2UnixTest)
{
const wchar_t *srcS = L"%5s %#20S";
wchar_t destS[256];
NanoWinMsWFormatProcMs2Unix(destS, srcS);
NW_CHECK_EQUAL_MEMCMP(L"%5S %#20s", destS, 10 * sizeof(wchar_t));
const wchar_t *srcF = L"%+0*f %4.2f";
wchar_t destF[256];
NanoWinMsWFormatProcMs2Unix(destF, srcF);
NW_CHECK_EQUAL_MEMCMP(L"%+0*f %4.2f", destF, 13 * sizeof(wchar_t));
const wchar_t *srcD = L"%+05lld %-I64i %02I32u %#x%#X %#3o";
wchar_t destD[256];
NanoWinMsWFormatProcMs2Unix(destD, srcD);
NW_CHECK_EQUAL_MEMCMP(L"%+05lld %-I64i %02I32u %#x%#X %#3o", destD, 37 * sizeof(wchar_t));
const wchar_t *srcC = L"%-c %5C %wc";
wchar_t destC[256];
NanoWinMsWFormatProcMs2Unix(destC, srcC);
NW_CHECK_EQUAL_MEMCMP(L"%-C %5c %lc", destC, 12 * sizeof(wchar_t));
const wchar_t *srcG = L"%-3lg %+5LG";
wchar_t destG[256];
NanoWinMsWFormatProcMs2Unix(destG, srcG);
NW_CHECK_EQUAL_MEMCMP(L"%-3lg %+5LG", destG, 12 * sizeof(wchar_t));
const wchar_t *srcA = L"%-*3.a %+5#A";
wchar_t destA[256];
NanoWinMsWFormatProcMs2Unix(destA, srcA);
NW_CHECK_EQUAL_MEMCMP(L"%-*3.a %+5#A", destA, 15 * sizeof(wchar_t));
}
NW_END_TEST_GROUP()
NW_BEGIN_TEST_GROUP_SIMPLE(NanoWinMsSWPrintfTestGroup)
NW_TEST(NanoWinMsSWPrintfTestGroup, NanoWinMsSWPrintfSimpleTest)
{
wchar_t str[256];
int count0 = NanoWinMsSWPrintf(str, 5, L"test");
NW_CHECK_EQUAL(4, count0);
NW_CHECK_EQUAL_MEMCMP(L"test", str, 5 * sizeof(wchar_t));
int count1 = NanoWinMsSWPrintf(str, 4, L"%s", L"abc");
NW_CHECK_EQUAL(3, count1);
NW_CHECK_EQUAL_MEMCMP(L"abc", str, 4 * sizeof(wchar_t));
int count2 = NanoWinMsSWPrintf(str, 4, L"%ws", L"def");
NW_CHECK_EQUAL(3, count2);
NW_CHECK_EQUAL_MEMCMP(L"def", str, 4 * sizeof(wchar_t));
int count3 = NanoWinMsSWPrintf(str, 4, L"%wc", L'g');
NW_CHECK_EQUAL(1, count3);
NW_CHECK_EQUAL_MEMCMP(L"g", str, 2 * sizeof(wchar_t));
int count4 = NanoWinMsSWPrintf(str, 4, L"%hd", (short int)-12);
NW_CHECK_EQUAL(3, count4);
NW_CHECK_EQUAL_MEMCMP(L"-12", str, 4 * sizeof(wchar_t));
int count5 = NanoWinMsSWPrintf(str, 4, L"%lu", (unsigned long int)34);
NW_CHECK_EQUAL(2, count5);
NW_CHECK_EQUAL_MEMCMP(L"34", str, 3 * sizeof(wchar_t));
int count6 = NanoWinMsSWPrintf(str, 4, L"%c", L'd');
NW_CHECK_EQUAL(1, count6);
NW_CHECK_EQUAL_MEMCMP(L"d", str, 2 * sizeof(wchar_t));
int count7 = NanoWinMsSWPrintf(str, 5, L"%#x", 0xFF);
NW_CHECK_EQUAL(4, count7);
NW_CHECK_EQUAL_MEMCMP(L"0xff", str, 5 * sizeof(wchar_t));
int count8 = NanoWinMsSWPrintf(str, 5, L"%#X", 0xff);
NW_CHECK_EQUAL(4, count8);
NW_CHECK_EQUAL_MEMCMP(L"0XFF", str, 5 * sizeof(wchar_t));
int count9 = NanoWinMsSWPrintf(str, 5, L"%o", 056);
NW_CHECK_EQUAL(2, count9);
NW_CHECK_EQUAL_MEMCMP(L"56", str, 3 * sizeof(wchar_t));
int count10 = NanoWinMsSWPrintf(str, 10, L"%f", 5.678f);
NW_CHECK_EQUAL(8, count10);
NW_CHECK_EQUAL_MEMCMP(L"5.678000", str, 9 * sizeof(wchar_t));
// 'h'-prefix in char and string fields checks
int count = NanoWinMsSWPrintf(str, sizeof(str) / sizeof(wchar_t), L"%hc",'A');
NW_CHECK_EQUAL(1,count);
NW_CHECK_EQUAL_STRCMP(L"A",str);
count = NanoWinMsSWPrintf(str, sizeof(str) / sizeof(wchar_t), L"%hs","multibyte string");
NW_CHECK_EQUAL(16,count);
NW_CHECK_EQUAL_STRCMP(L"multibyte string",str);
}
NW_TEST(NanoWinMsSWPrintfTestGroup, NanoWinMsSWPrintfTest)
{
wchar_t str[256];
int count1 = NanoWinMsSWPrintf(str, sizeof(str) / sizeof(wchar_t), L"%ls ww %#2s%ws", L"abc", L"f", L"zz");
NW_CHECK_EQUAL(11, count1);
NW_CHECK_EQUAL_MEMCMP(L"abc ww fzz", str, 12 * sizeof(wchar_t));
int count2 = NanoWinMsSWPrintf(str, sizeof(str) / sizeof(wchar_t), L"%c %wc %lc", L'd', L'e', L'f');
NW_CHECK_EQUAL(5, count2);
NW_CHECK_EQUAL_MEMCMP(L"d e f", str, 6 * sizeof(wchar_t));
int count3 = NanoWinMsSWPrintf(str, sizeof(str) / sizeof(wchar_t), L"%hd %+i bb %#llu", (short int)-56, 123, (long long unsigned int)10);
NW_CHECK_EQUAL(15, count3);
NW_CHECK_EQUAL_MEMCMP(L"-56 +123 bb 10", str, 16 * sizeof(wchar_t));
int count4 = NanoWinMsSWPrintf(str, sizeof(str) / sizeof(wchar_t), L"%#x %#X %x", 11, 22, 33);
NW_CHECK_EQUAL(12, count4);
NW_CHECK_EQUAL_MEMCMP(L"0xb 0X16 21", str, 13 * sizeof(wchar_t));
int count5 = NanoWinMsSWPrintf(str, sizeof(str) / sizeof(wchar_t), L"%o %#o", 056, 24);
NW_CHECK_EQUAL(7, count5);
NW_CHECK_EQUAL_MEMCMP(L"56 030", str, 8 * sizeof(wchar_t));
int count6 = NanoWinMsSWPrintf(str, sizeof(str) / sizeof(wchar_t), L"%.*f %.3f", 3, 0.1312f, 1.22222f);
NW_CHECK_EQUAL(11, count6);
NW_CHECK_EQUAL_MEMCMP(L"0.131 1.222", str, 12 * sizeof(wchar_t));
}
NW_END_TEST_GROUP()
NW_BEGIN_TEST_GROUP_SIMPLE(NanoWinMsFWPrintfTestGroup)
#ifndef __GNUC__
NW_TEST(NanoWinMsFWPrintfTestGroup, NanoWinMsFWPrintfSTest)
{
wchar_t str[256];
FILE *file = GetFile();
if (file != NULL)
{
int count = NanoWinMsFWPrintf(file, L"%ls ww %#2s%ws", L"abc", L"f", L"zz");
NW_CHECK_EQUAL(11, count);
ReadFile(file, str);
NW_CHECK_EQUAL_MEMCMP(L"abc ww fzz", str, 12 * sizeof(wchar_t));
CloseFile(file);
}
}
NW_TEST(NanoWinMsFWPrintfTestGroup, NanoWinMsFWPrintfCTest)
{
wchar_t str[256];
FILE *file = GetFile();
if (file != NULL)
{
int count = NanoWinMsFWPrintf(file, L"%c %wc %lc", L'd', L'e', L'f');
NW_CHECK_EQUAL(5, count);
ReadFile(file, str);
NW_CHECK_EQUAL_MEMCMP(L"d e f", str, 6 * sizeof(wchar_t));
CloseFile(file);
}
}
#endif
NW_TEST(NanoWinMsFWPrintfTestGroup, NanoWinMsFWPrintfDTest)
{
wchar_t str[256];
FILE *file = GetFile();
if (file != NULL)
{
int count = NanoWinMsFWPrintf(file, L"%hd %+i bb %#llu", (short int)-56, 123, (long long unsigned int)10);
NW_CHECK_EQUAL(15, count);
ReadFile(file, str);
NW_CHECK_EQUAL_MEMCMP(L"-56 +123 bb 10", str, 16 * sizeof(wchar_t));
CloseFile(file);
}
}
NW_TEST(NanoWinMsFWPrintfTestGroup, NanoWinMsFWPrintfXTest)
{
wchar_t str[256];
FILE *file = GetFile();
if (file != NULL)
{
int count = NanoWinMsFWPrintf(file, L"%#x %#X %x", 11, 22, 33);
NW_CHECK_EQUAL(12, count);
ReadFile(file, str);
NW_CHECK_EQUAL_MEMCMP(L"0xb 0X16 21", str, 13 * sizeof(wchar_t));
CloseFile(file);
}
}
NW_TEST(NanoWinMsFWPrintfTestGroup, NanoWinMsFWPrintfOTest)
{
wchar_t str[256];
FILE *file = GetFile();
if (file != NULL)
{
int count = NanoWinMsFWPrintf(file, L"%o %#o", 056, 24);
NW_CHECK_EQUAL(7, count);
ReadFile(file, str);
NW_CHECK_EQUAL_MEMCMP(L"56 030", str, 8 * sizeof(wchar_t));
CloseFile(file);
}
}
NW_TEST(NanoWinMsFWPrintfTestGroup, NanoWinMsFWPrintfFTest)
{
wchar_t str[256];
FILE *file = GetFile();
if (file != NULL)
{
int count = NanoWinMsFWPrintf(file, L"%.*f %.3f", 3, 0.1312f, 1.22222f);
NW_CHECK_EQUAL(11, count);
ReadFile(file, str);
NW_CHECK_EQUAL_MEMCMP(L"0.131 1.222", str, 12 * sizeof(wchar_t));
CloseFile(file);
}
}
NW_END_TEST_GROUP()
|
test for compatibility with Ms-specific "%hc" and "%hs" printf format specifiers added
|
test for compatibility with Ms-specific "%hc" and "%hs" printf format specifiers added
|
C++
|
mit
|
openlab-vn-ua/NanoWin32,openlab-vn-ua/NanoWin32
|
8487b33c356576bcd1b9f9ddcd5d7faf7858b750
|
megingjord/simd/pack.hpp
|
megingjord/simd/pack.hpp
|
#ifndef MEGINGJORD_SIMD_PACK
#define MEGINGJORD_SIMD_PACK
#include <megingjord/util/aligned_array.hpp>
#include <cmath>
namespace megingjord
{
namespace simd
{
template<typename, std::size_t> struct pack;
template<typename, std::size_t, typename> struct packed_array;
template<typename> struct is_simd : public std::false_type{};
template<typename> struct single_type_of;
template<typename T, std::size_t N>
struct single_type_of<pack<T, N>>
{
typedef T type;
};
template<typename T, std::size_t N, std::size_t align>
struct single_type_of<aligned_array<T, N, align>>
{
typedef T type;
};
template<typename T, std::size_t N, typename trait>
struct single_type_of<packed_array<T, N, trait>>
{
typedef T type;
};
template<typename> struct set_impl;
template<typename> struct load_impl;
template<typename> struct broadcast_impl;
template<typename> struct store_impl;
template<typename T> struct add_impl
{
constexpr static inline
T invoke(T lhs, T rhs) {return lhs + rhs;}
};
template<typename T> struct sub_impl
{
constexpr static inline
T invoke(T lhs, T rhs) {return lhs - rhs;}
};
template<typename T> struct mul_impl
{
constexpr static inline
T invoke(T lhs, T rhs) {return lhs * rhs;}
};
template<typename T> struct div_impl
{
constexpr static inline
T invoke(T lhs, T rhs) {return lhs / rhs;}
};
template<typename T> struct rcp_impl
{
constexpr static inline
T invoke(T a) {return 1 / a;}
};
template<typename T> struct rsqrt_impl
{
static inline
T invoke(T a) {return 1 / std::sqrt(a);}
};
template<typename T> struct sqrt_impl
{
static inline
T invoke(T a) {return std::sqrt(a);}
};
template<typename T> struct floor_impl
{
static inline
T invoke(T a) {return std::floor(a);}
};
template<typename T> struct ceil_impl
{
static inline
T invoke(T a) {return std::ceil(a);}
};
template<typename T> struct fmadd_impl
{
constexpr static inline
T invoke(T a, T b, T c) {return a * b + c;}
};
template<typename T> struct fnmadd_impl
{
constexpr static inline
T invoke(T a, T b, T c) {return -a * b + c;}
};
template<typename T> struct fmsub_impl
{
constexpr static inline
T invoke(T a, T b, T c) {return a * b - c;}
};
template<typename T> struct fnmsub_impl
{
constexpr static inline
T invoke(T a, T b, T c) {return -a * b - c;}
};
} // simd
} // megingjord
#ifdef MJOLNIR_HAVE_AVX
#include <immintrin.h>
#include "avx/pack_avx.hpp"
#include "avx/functor_avx.hpp"
#define MEGINGJORD_DEFAULT_SIMD avx_traits
#endif
#include "operation_pack.hpp"
#include "packed_array.hpp"
#include "operation_array.hpp"
#endif /* MEGINGJORD_SIMD_PACK */
|
#ifndef MEGINGJORD_SIMD_PACK
#define MEGINGJORD_SIMD_PACK
#include <megingjord/util/aligned_array.hpp>
#include <cmath>
namespace megingjord
{
namespace simd
{
template<typename, std::size_t> struct pack;
template<typename, std::size_t, typename> struct packed_array;
template<typename> struct is_simd : public std::false_type{};
template<typename> struct single_type_of;
template<typename T, std::size_t N>
struct single_type_of<pack<T, N>>
{
typedef T type;
};
template<typename T, std::size_t N, std::size_t align>
struct single_type_of<aligned_array<T, N, align>>
{
typedef T type;
};
template<typename T, std::size_t N, typename trait>
struct single_type_of<packed_array<T, N, trait>>
{
typedef T type;
};
template<typename> struct set_impl;
template<typename> struct load_impl;
template<typename> struct broadcast_impl;
template<typename> struct store_impl;
template<typename T> struct add_impl
{
constexpr static inline
T invoke(T lhs, T rhs) {return lhs + rhs;}
};
template<typename T> struct sub_impl
{
constexpr static inline
T invoke(T lhs, T rhs) {return lhs - rhs;}
};
template<typename T> struct mul_impl
{
constexpr static inline
T invoke(T lhs, T rhs) {return lhs * rhs;}
};
template<typename T> struct div_impl
{
constexpr static inline
T invoke(T lhs, T rhs) {return lhs / rhs;}
};
template<typename T> struct rcp_impl
{
constexpr static inline
T invoke(T a) {return 1 / a;}
};
template<typename T> struct rsqrt_impl
{
static inline
T invoke(T a) {return 1 / std::sqrt(a);}
};
template<typename T> struct sqrt_impl
{
static inline
T invoke(T a) {return std::sqrt(a);}
};
template<typename T> struct floor_impl
{
static inline
T invoke(T a) {return std::floor(a);}
};
template<typename T> struct ceil_impl
{
static inline
T invoke(T a) {return std::ceil(a);}
};
template<typename T> struct fmadd_impl
{
constexpr static inline
T invoke(T a, T b, T c) {return a * b + c;}
};
template<typename T> struct fnmadd_impl
{
constexpr static inline
T invoke(T a, T b, T c) {return -a * b + c;}
};
template<typename T> struct fmsub_impl
{
constexpr static inline
T invoke(T a, T b, T c) {return a * b - c;}
};
template<typename T> struct fnmsub_impl
{
constexpr static inline
T invoke(T a, T b, T c) {return -a * b - c;}
};
} // simd
} // megingjord
#ifdef MJOLNIR_HAVE_AVX
#include <immintrin.h>
#include "avx/pack_avx.hpp"
#include "avx/functor_avx.hpp"
#define MEGINGJORD_DEFAULT_SIMD avx_traits
#endif
#include "packable_array.hpp"
#include "operation_pack.hpp"
#include "operation_array.hpp"
#endif /* MEGINGJORD_SIMD_PACK */
|
rename include file
|
rename include file
|
C++
|
mit
|
ToruNiina/Mjolnir,ToruNiina/Mjolnir,ToruNiina/Mjolnir
|
5a663d67bd32a3207f5d47e079c5a66f328f5dd0
|
src/Utils/FileUtils_test.cpp
|
src/Utils/FileUtils_test.cpp
|
/*
Copyright 2021 The Surelog Team.
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 "Utils/FileUtils.h"
#include "SourceCompile/SymbolTable.h"
#include <string>
#include <vector>
#include <fstream>
#include "gtest/gtest.h"
#if (__cplusplus >= 201703L) && __has_include(<filesystem>)
#include <filesystem>
namespace fs = std::filesystem;
#else
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#endif
namespace SURELOG {
namespace {
TEST(FileUtilsTest, BasicFileOperations) {
const std::string dirtest = testing::TempDir() + "/file-exist-dir";
const std::string basename = "file-exists-test.txt";
const std::string filename = dirtest + "/" + basename;
const std::string dummy_data = "This file contains some bytes";
EXPECT_TRUE(FileUtils::rmDirRecursively(dirtest));
EXPECT_TRUE(FileUtils::rmDirRecursively(dirtest)); // not there: no error
EXPECT_FALSE(FileUtils::fileIsDirectory(dirtest));
EXPECT_TRUE(FileUtils::mkDir(dirtest));
EXPECT_TRUE(FileUtils::fileIsDirectory(dirtest));
EXPECT_FALSE(FileUtils::fileIsRegular(dirtest));
EXPECT_FALSE(FileUtils::fileExists(filename));
{
std::ofstream testfile(filename);
testfile.write(dummy_data.data(), dummy_data.size());
testfile.close();
}
EXPECT_TRUE(FileUtils::fileExists(filename));
EXPECT_FALSE(FileUtils::fileIsDirectory(filename));
EXPECT_TRUE(FileUtils::fileIsRegular(filename));
EXPECT_EQ(FileUtils::fileSize(filename), dummy_data.size());
const std::string content = FileUtils::getFileContent(filename);
EXPECT_EQ(content, dummy_data);
FileUtils::rmDirRecursively(dirtest);
EXPECT_EQ(FileUtils::basename(filename), basename);
}
TEST(FileUtilsTest, LocateFile) {
SymbolTable sym;
const std::string search_file = "search-file.txt";
const std::string basedir = testing::TempDir() + "/locate-file-test";
const std::string path1 = basedir + "/dir1-no-slash";
const std::string path2 = basedir + "/dir2-with-slash/";
const std::string actual_dir = basedir + "/actual-dir";
FileUtils::mkDir(path1);
FileUtils::mkDir(actual_dir);
std::vector<SymbolId> paths = {
sym.registerSymbol(path1),
sym.registerSymbol(path2),
sym.registerSymbol(actual_dir),
};
SymbolId search_file_id = sym.registerSymbol(search_file);
// At this point, the file does not exist yet.
SymbolId non_exist = FileUtils::locateFile(search_file_id, &sym, paths);
EXPECT_EQ(non_exist, SymbolTable::getBadId());
const std::string actual_loc = actual_dir + "/" + search_file;
std::ofstream(actual_loc).close();
SymbolId now_exists = FileUtils::locateFile(search_file_id, &sym, paths);
EXPECT_NE(now_exists, SymbolTable::getBadId());
EXPECT_EQ(sym.getSymbol(now_exists), actual_loc);
SymbolId already_found = FileUtils::locateFile(now_exists, &sym, paths);
EXPECT_EQ(already_found, now_exists);
FileUtils::rmDirRecursively(basedir);
}
TEST(FileUtilsTest, GetPathName) {
EXPECT_EQ(FileUtils::getPathName(""), "");
EXPECT_EQ(FileUtils::getPathName("/r/dir/file.txt"),
(fs::path("/r/dir") += fs::path::preferred_separator).string());
}
// Still missing
// FileUtils::getFullPath
// FileUtils::collectFiles() <- important, a lot of untested logic there.
// FileUtils::hashPath()
// FileUtils::getPrefferedPath()
} // namespace
} // namespace SURELOG
|
/*
Copyright 2021 The Surelog Team.
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 "Utils/FileUtils.h"
#include <fstream>
#include <string>
#include <vector>
#include "SourceCompile/SymbolTable.h"
#include "gtest/gtest.h"
#if (__cplusplus >= 201703L) && __has_include(<filesystem>)
#include <filesystem>
namespace fs = std::filesystem;
#else
#include <experimental/filesystem>
namespace fs = std::experimental::filesystem;
#endif
namespace SURELOG {
namespace {
TEST(FileUtilsTest, BasicFileOperations) {
const std::string dirtest = testing::TempDir() + "/file-exist-dir";
const std::string basename = "file-exists-test.txt";
const std::string filename = dirtest + "/" + basename;
const std::string dummy_data = "This file contains some bytes";
EXPECT_TRUE(FileUtils::rmDirRecursively(dirtest));
EXPECT_TRUE(FileUtils::rmDirRecursively(dirtest)); // not there: no error
EXPECT_FALSE(FileUtils::fileIsDirectory(dirtest));
EXPECT_TRUE(FileUtils::mkDir(dirtest));
EXPECT_TRUE(FileUtils::fileIsDirectory(dirtest));
EXPECT_FALSE(FileUtils::fileIsRegular(dirtest));
EXPECT_FALSE(FileUtils::fileExists(filename));
{
std::ofstream testfile(filename);
testfile.write(dummy_data.data(), dummy_data.size());
testfile.close();
}
EXPECT_TRUE(FileUtils::fileExists(filename));
EXPECT_FALSE(FileUtils::fileIsDirectory(filename));
EXPECT_TRUE(FileUtils::fileIsRegular(filename));
EXPECT_EQ(FileUtils::fileSize(filename), dummy_data.size());
const std::string content = FileUtils::getFileContent(filename);
EXPECT_EQ(content, dummy_data);
FileUtils::rmDirRecursively(dirtest);
EXPECT_EQ(FileUtils::basename(filename), basename);
}
TEST(FileUtilsTest, LocateFile) {
SymbolTable sym;
const std::string search_file = "search-file.txt";
const std::string basedir = testing::TempDir() + "/locate-file-test";
const std::string path1 = basedir + "/dir1-no-slash";
const std::string path2 = basedir + "/dir2-with-slash/";
const std::string actual_dir = basedir + "/actual-dir";
FileUtils::mkDir(path1);
FileUtils::mkDir(actual_dir);
std::vector<SymbolId> paths = {
sym.registerSymbol(path1),
sym.registerSymbol(path2),
sym.registerSymbol(actual_dir),
};
SymbolId search_file_id = sym.registerSymbol(search_file);
// At this point, the file does not exist yet.
SymbolId non_exist = FileUtils::locateFile(search_file_id, &sym, paths);
EXPECT_EQ(non_exist, SymbolTable::getBadId());
const std::string actual_loc = actual_dir + "/" + search_file;
std::ofstream(actual_loc).close();
SymbolId now_exists = FileUtils::locateFile(search_file_id, &sym, paths);
EXPECT_NE(now_exists, SymbolTable::getBadId());
EXPECT_EQ(sym.getSymbol(now_exists), actual_loc);
SymbolId already_found = FileUtils::locateFile(now_exists, &sym, paths);
EXPECT_EQ(already_found, now_exists);
FileUtils::rmDirRecursively(basedir);
}
TEST(FileUtilsTest, GetPathName) {
EXPECT_EQ(FileUtils::getPathName(""), "");
EXPECT_EQ(FileUtils::getPathName("/r/dir/file.txt"),
(fs::path("/r/dir") += fs::path::preferred_separator).string());
}
// Still missing
// FileUtils::getFullPath
// FileUtils::collectFiles() <- important, a lot of untested logic there.
// FileUtils::hashPath()
// FileUtils::getPrefferedPath()
} // namespace
} // namespace SURELOG
|
Add review comments.
|
Add review comments.
Signed-off-by: Henner Zeller <[email protected]>
|
C++
|
apache-2.0
|
chipsalliance/Surelog,alainmarcel/Surelog,alainmarcel/Surelog,chipsalliance/Surelog,alainmarcel/Surelog,alainmarcel/Surelog,chipsalliance/Surelog,chipsalliance/Surelog
|
1b4435aefdcae60d2a22561fc26381f5101f8f50
|
rst/Defer/Test.cpp
|
rst/Defer/Test.cpp
|
// Copyright (c) 2017, Sergey Abbakumov
// All rights reserved.
//
// 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.
//
// 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.
#include <string>
#include <gtest/gtest.h>
#include "Defer.h"
using std::string;
auto g_int = 0;
TEST(Defer, Lambda) {
auto i = 0;
{
DEFER([&i]() { i = 1; });
}
EXPECT_EQ(1, i);
}
void Foo() {
g_int = 1;
}
TEST(Defer, Function) {
{
DEFER(Foo);
}
EXPECT_EQ(1, g_int);
}
TEST(Defer, MultipleTimesDeclaration) {
string result;
{
DEFER([&result]() { result += '1'; });
DEFER([&result]() { result += '2'; });
}
EXPECT_EQ("21", result);
}
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
// Copyright (c) 2017, Sergey Abbakumov
// All rights reserved.
//
// 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.
//
// 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.
#include <string>
#include <gtest/gtest.h>
#include "Defer.h"
using std::string;
auto g_int = 0;
TEST(Defer, Lambda) {
auto i = 0;
{
DEFER([&i]() { i = 1; });
}
EXPECT_EQ(1, i);
}
void Foo() {
g_int = 1;
}
TEST(Defer, Function) {
{
DEFER(Foo);
}
EXPECT_EQ(1, g_int);
}
TEST(Defer, MultipleTimesDeclaration) {
string result;
{
DEFER([&result]() { result += '1'; });
DEFER([&result]() { result += '2'; });
}
EXPECT_EQ("21", result);
}
TEST(Defer, NoExceptionPropagation) {
auto i = 0;
{
DEFER([]() { throw 0; });
}
EXPECT_EQ(0, i);
}
int main(int argc, char** argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
Modify test for Defer
|
Modify test for Defer
|
C++
|
bsd-2-clause
|
sabbakumov/rst,sabbakumov/rst
|
fa887378edec01fbd24ae6824e0aa1b5f5134c28
|
tests/valgrind/network/network.cpp
|
tests/valgrind/network/network.cpp
|
#include "../warnings-disable.h"
WARNINGS_DISABLE
#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QThread>
WARNINGS_ENABLE
#include "../macros-valgrind.h"
static void pl_nothing()
{
}
static void pl_networkaccessmanager()
{
T_APP_BEGIN_CONSOLE;
QNetworkAccessManager *nam = new QNetworkAccessManager();
QThread::msleep(200);
delete nam;
T_APP_END;
}
static void pl_networkaccessmanager_status()
{
T_APP_BEGIN_CONSOLE;
QNetworkAccessManager *nam = new QNetworkAccessManager();
QThread::msleep(200);
nam->networkAccessible();
QThread::msleep(200);
delete nam;
T_APP_END;
}
static void pl_networkaccessmanager_repeated()
{
T_APP_BEGIN_CONSOLE;
// QNetworkAccessManger has an unpredictable interactions with dbus,
// causing variable memory leaks. This is my attempt at catching them.
for(int i = 0; i < 10; i++)
{
pl_networkaccessmanager_status();
QThread::msleep(200);
}
T_APP_END;
}
// clang-format off
T_TEST_BEGIN
MEMLEAKTEST(pl_nothing),
MEMLEAKTEST(pl_networkaccessmanager),
MEMLEAKTEST(pl_networkaccessmanager_status),
MEMLEAKTEST(pl_networkaccessmanager_repeated)
T_TEST_END
|
#include "../warnings-disable.h"
WARNINGS_DISABLE
#include <QCoreApplication>
#include <QNetworkAccessManager>
#include <QThread>
WARNINGS_ENABLE
#include "../macros-valgrind.h"
static void pl_nothing()
{
}
static void pl_networkaccessmanager()
{
T_APP_BEGIN_CONSOLE;
QNetworkAccessManager *nam = new QNetworkAccessManager();
QThread::msleep(200);
delete nam;
T_APP_END;
}
static void pl_networkaccessmanager_status_not_solo()
{
QNetworkAccessManager *nam = new QNetworkAccessManager();
QThread::msleep(200);
nam->networkAccessible();
QThread::msleep(200);
delete nam;
}
static void pl_networkaccessmanager_status()
{
T_APP_BEGIN_CONSOLE;
pl_networkaccessmanager_status_not_solo();
T_APP_END;
}
static void pl_networkaccessmanager_repeated()
{
T_APP_BEGIN_CONSOLE;
// QNetworkAccessManger has an unpredictable interactions with dbus,
// causing variable memory leaks. This is my attempt at catching them.
for(int i = 0; i < 10; i++)
{
pl_networkaccessmanager_status_not_solo();
QThread::msleep(200);
}
T_APP_END;
}
// clang-format off
T_TEST_BEGIN
MEMLEAKTEST(pl_nothing),
MEMLEAKTEST(pl_networkaccessmanager),
MEMLEAKTEST(pl_networkaccessmanager_status),
MEMLEAKTEST(pl_networkaccessmanager_repeated)
T_TEST_END
|
fix accidental multiple apps
|
tests/valgrind/network: fix accidental multiple apps
|
C++
|
bsd-2-clause
|
Tarsnap/tarsnap-gui,Tarsnap/tarsnap-gui,Tarsnap/tarsnap-gui,Tarsnap/tarsnap-gui,Tarsnap/tarsnap-gui
|
9016282573ff00e2fa971b5ad1303994ec0e471d
|
src/lepp2/SplitApproximator.hpp
|
src/lepp2/SplitApproximator.hpp
|
#ifndef LEPP2_SPLIT_APPROXIMATOR_H__
#define LEPP2_SPLIT_APPROXIMATOR_H__
#include "lepp2/ObjectApproximator.hpp"
#include "lepp2/models/ObjectModel.h"
#include <deque>
#include <map>
#include <pcl/common/pca.h>
#include <pcl/common/common.h>
namespace lepp {
/**
* An ABC that represents the strategy for splitting a point cloud used by the
* `SplitObjectApproximator`.
*
* Varying the `SplitStrategy` implementation allows us to change how point
* clouds are split (or if they are split at all) without changing the logic of
* the `SplitObjectApproximator` approximator itself.
*/
template<class PointT>
class SplitStrategy {
public:
/**
* A pure virtual method that concrete implementations need to define.
*
* :param split_depth: The current split depth, i.e. the number of times the
* original cloud has already been split
* :param point_cloud: The current point cloud that should be split by the
* `SplitStrategy` implementation.
* :returns: The method should return a vector of point clouds obtained by
* splitting the given cloud into any number of parts. If the given
* point cloud should not be split, an empty vector should be returned.
* Once the empty vector is returned, the `SplitObjectApproximator` will
* stop the splitting process for that branch of the split tree.
*/
virtual std::vector<typename pcl::PointCloud<PointT>::Ptr> split(
int split_depth,
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud) = 0;
};
/**
* An approximator implementation that will generate an approximation by
* splitting the given object into multiple parts. Each part approximation is
* generated by delegating to a wrapped `ObjectApproximator` instance, allowing
* clients to vary the algorithm used for approximations, while keeping the
* logic of incrementally splitting up the object.
*/
template<class PointT>
class SplitObjectApproximator : public ObjectApproximator<PointT> {
public:
/**
* Create a new `SplitObjectApproximator` that will approximate each part by
* using the given approximator instance.
*/
SplitObjectApproximator(boost::shared_ptr<ObjectApproximator<PointT> > approx)
: approximator_(approx) {}
/**
* `ObjectApproximator` interface method.
*/
boost::shared_ptr<CompositeModel> approximate(
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud);
private:
/**
* Splits the given point_cloud into two parts and places them in the
* ``first`` and ``second`` PointCloud references.
*/
void splitCloud(
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud,
pcl::PointCloud<PointT>& first,
pcl::PointCloud<PointT>& second);
/**
* An `ObjectApproximator` used to generate approximations for object parts.
*/
boost::shared_ptr<ObjectApproximator<PointT> > approximator_;
};
template<class PointT>
boost::shared_ptr<CompositeModel> SplitObjectApproximator<PointT>::approximate(
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud) {
boost::shared_ptr<CompositeModel> approx(new CompositeModel);
typedef typename pcl::PointCloud<PointT>::ConstPtr PointCloudConstPtr;
typedef typename pcl::PointCloud<PointT>::Ptr PointCloudPtr;
std::deque<std::pair<int, PointCloudConstPtr> > queue;
queue.push_back(std::make_pair(0, point_cloud));
while (!queue.empty()) {
int const depth = queue[0].first;
PointCloudConstPtr const current_cloud = queue[0].second;
queue.pop_front();
// Delegates to the wrapped approximator for each part's approximation.
ObjectModelPtr model = approximator_->approximate(current_cloud);
// TODO Decide whether the model fits well enough for the current cloud.
// For now we fix the number of split iterations.
if (depth == 0) {
// The approximation should be improved. Try doing it for the split clouds
PointCloudPtr first(new pcl::PointCloud<PointT>());
PointCloudPtr second(new pcl::PointCloud<PointT>());
splitCloud(current_cloud, *first, *second);
queue.push_back(std::make_pair(depth + 1, first));
queue.push_back(std::make_pair(depth + 1, second));
} else {
// Keep the approximation
approx->addModel(model);
}
}
return approx;
}
template<class PointT>
void SplitObjectApproximator<PointT>::splitCloud(
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud,
pcl::PointCloud<PointT>& first,
pcl::PointCloud<PointT>& second) {
// Compute PCA for the input cloud
pcl::PCA<PointT> pca;
pca.setInputCloud(point_cloud);
Eigen::Vector3f eigenvalues = pca.getEigenValues();
Eigen::Matrix3f eigenvectors = pca.getEigenVectors();
Eigen::Vector3d main_pca_axis = eigenvectors.col(0).cast<double>();
// Compute the centroid
Eigen::Vector4d centroid;
pcl::compute3DCentroid(*point_cloud, centroid);
/// The plane equation
double d = (-1) * (
centroid[0] * main_pca_axis[0] +
centroid[1] * main_pca_axis[1] +
centroid[2] * main_pca_axis[2]
);
// Now divide the input cloud into two clusters based on the splitting plane
size_t const sz = point_cloud->size();
for (size_t i = 0; i < sz; ++i) {
// Boost the precision of the points we are dealing with to make the
// calculation more precise.
PointT const& original_point = (*point_cloud)[i];
Eigen::Vector3f const vector_point = original_point.getVector3fMap();
Eigen::Vector3d const point = vector_point.cast<double>();
// Decide on which side of the plane the current point is and add it to the
// appropriate partition.
if (point.dot(main_pca_axis) + d < 0.) {
first.push_back(original_point);
} else {
second.push_back(original_point);
}
}
}
} // namespace lepp
#endif
|
#ifndef LEPP2_SPLIT_APPROXIMATOR_H__
#define LEPP2_SPLIT_APPROXIMATOR_H__
#include "lepp2/ObjectApproximator.hpp"
#include "lepp2/models/ObjectModel.h"
#include <deque>
#include <map>
#include <pcl/common/pca.h>
#include <pcl/common/common.h>
namespace lepp {
/**
* An ABC that represents the strategy for splitting a point cloud used by the
* `SplitObjectApproximator`.
*
* Varying the `SplitStrategy` implementation allows us to change how point
* clouds are split (or if they are split at all) without changing the logic of
* the `SplitObjectApproximator` approximator itself.
*/
template<class PointT>
class SplitStrategy {
public:
/**
* A pure virtual method that concrete implementations need to define.
*
* :param split_depth: The current split depth, i.e. the number of times the
* original cloud has already been split
* :param point_cloud: The current point cloud that should be split by the
* `SplitStrategy` implementation.
* :returns: The method should return a vector of point clouds obtained by
* splitting the given cloud into any number of parts. If the given
* point cloud should not be split, an empty vector should be returned.
* Once the empty vector is returned, the `SplitObjectApproximator` will
* stop the splitting process for that branch of the split tree.
*/
virtual std::vector<typename pcl::PointCloud<PointT>::Ptr> split(
int split_depth,
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud) = 0;
};
template<class PointT>
class DepthLimitSplitStrategy : public SplitStrategy<PointT> {
public:
DepthLimitSplitStrategy(int depth_limit) : limit_(depth_limit) {}
std::vector<typename pcl::PointCloud<PointT>::Ptr> split(
int split_depth,
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud);
private:
/**
* A helper method that does the actual split, when needed.
*/
std::vector<typename pcl::PointCloud<PointT>::Ptr> doSplit(
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud);
int const limit_;
};
template<class PointT>
std::vector<typename pcl::PointCloud<PointT>::Ptr>
DepthLimitSplitStrategy<PointT>::split(
int split_depth,
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud) {
if (split_depth < limit_) {
return this->doSplit(point_cloud);
} else {
return std::vector<typename pcl::PointCloud<PointT>::Ptr>();
}
}
template<class PointT>
std::vector<typename pcl::PointCloud<PointT>::Ptr>
DepthLimitSplitStrategy<PointT>::doSplit(
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud) {
typedef pcl::PointCloud<PointT> PointCloud;
typedef typename pcl::PointCloud<PointT>::Ptr PointCloudPtr;
// Compute PCA for the input cloud
pcl::PCA<PointT> pca;
pca.setInputCloud(point_cloud);
Eigen::Vector3f eigenvalues = pca.getEigenValues();
Eigen::Matrix3f eigenvectors = pca.getEigenVectors();
Eigen::Vector3d main_pca_axis = eigenvectors.col(0).cast<double>();
// Compute the centroid
Eigen::Vector4d centroid;
pcl::compute3DCentroid(*point_cloud, centroid);
/// The plane equation
double d = (-1) * (
centroid[0] * main_pca_axis[0] +
centroid[1] * main_pca_axis[1] +
centroid[2] * main_pca_axis[2]
);
// Prepare the two parts.
std::vector<PointCloudPtr> ret;
ret.push_back(PointCloudPtr(new pcl::PointCloud<PointT>()));
ret.push_back(PointCloudPtr(new pcl::PointCloud<PointT>()));
PointCloud& first = *ret[0];
PointCloud& second = *ret[1];
// Now divide the input cloud into two clusters based on the splitting plane
size_t const sz = point_cloud->size();
for (size_t i = 0; i < sz; ++i) {
// Boost the precision of the points we are dealing with to make the
// calculation more precise.
PointT const& original_point = (*point_cloud)[i];
Eigen::Vector3f const vector_point = original_point.getVector3fMap();
Eigen::Vector3d const point = vector_point.cast<double>();
// Decide on which side of the plane the current point is and add it to the
// appropriate partition.
if (point.dot(main_pca_axis) + d < 0.) {
first.push_back(original_point);
} else {
second.push_back(original_point);
}
}
// Return the parts in a vector, as expected by the interface...
return ret;
}
/**
* An approximator implementation that will generate an approximation by
* splitting the given object into multiple parts. Each part approximation is
* generated by delegating to a wrapped `ObjectApproximator` instance, allowing
* clients to vary the algorithm used for approximations, while keeping the
* logic of incrementally splitting up the object.
*/
template<class PointT>
class SplitObjectApproximator : public ObjectApproximator<PointT> {
public:
/**
* Create a new `SplitObjectApproximator` that will approximate each part by
* using the given approximator instance.
*/
SplitObjectApproximator(boost::shared_ptr<ObjectApproximator<PointT> > approx)
: approximator_(approx) {}
/**
* `ObjectApproximator` interface method.
*/
boost::shared_ptr<CompositeModel> approximate(
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud);
private:
/**
* Splits the given point_cloud into two parts and places them in the
* ``first`` and ``second`` PointCloud references.
*/
void splitCloud(
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud,
pcl::PointCloud<PointT>& first,
pcl::PointCloud<PointT>& second);
/**
* An `ObjectApproximator` used to generate approximations for object parts.
*/
boost::shared_ptr<ObjectApproximator<PointT> > approximator_;
};
template<class PointT>
boost::shared_ptr<CompositeModel> SplitObjectApproximator<PointT>::approximate(
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud) {
boost::shared_ptr<CompositeModel> approx(new CompositeModel);
typedef typename pcl::PointCloud<PointT>::ConstPtr PointCloudConstPtr;
typedef typename pcl::PointCloud<PointT>::Ptr PointCloudPtr;
std::deque<std::pair<int, PointCloudConstPtr> > queue;
queue.push_back(std::make_pair(0, point_cloud));
while (!queue.empty()) {
int const depth = queue[0].first;
PointCloudConstPtr const current_cloud = queue[0].second;
queue.pop_front();
// Delegates to the wrapped approximator for each part's approximation.
ObjectModelPtr model = approximator_->approximate(current_cloud);
// TODO Decide whether the model fits well enough for the current cloud.
// For now we fix the number of split iterations.
if (depth == 0) {
// The approximation should be improved. Try doing it for the split clouds
PointCloudPtr first(new pcl::PointCloud<PointT>());
PointCloudPtr second(new pcl::PointCloud<PointT>());
splitCloud(current_cloud, *first, *second);
queue.push_back(std::make_pair(depth + 1, first));
queue.push_back(std::make_pair(depth + 1, second));
} else {
// Keep the approximation
approx->addModel(model);
}
}
return approx;
}
template<class PointT>
void SplitObjectApproximator<PointT>::splitCloud(
const typename pcl::PointCloud<PointT>::ConstPtr& point_cloud,
pcl::PointCloud<PointT>& first,
pcl::PointCloud<PointT>& second) {
// Compute PCA for the input cloud
pcl::PCA<PointT> pca;
pca.setInputCloud(point_cloud);
Eigen::Vector3f eigenvalues = pca.getEigenValues();
Eigen::Matrix3f eigenvectors = pca.getEigenVectors();
Eigen::Vector3d main_pca_axis = eigenvectors.col(0).cast<double>();
// Compute the centroid
Eigen::Vector4d centroid;
pcl::compute3DCentroid(*point_cloud, centroid);
/// The plane equation
double d = (-1) * (
centroid[0] * main_pca_axis[0] +
centroid[1] * main_pca_axis[1] +
centroid[2] * main_pca_axis[2]
);
// Now divide the input cloud into two clusters based on the splitting plane
size_t const sz = point_cloud->size();
for (size_t i = 0; i < sz; ++i) {
// Boost the precision of the points we are dealing with to make the
// calculation more precise.
PointT const& original_point = (*point_cloud)[i];
Eigen::Vector3f const vector_point = original_point.getVector3fMap();
Eigen::Vector3d const point = vector_point.cast<double>();
// Decide on which side of the plane the current point is and add it to the
// appropriate partition.
if (point.dot(main_pca_axis) + d < 0.) {
first.push_back(original_point);
} else {
second.push_back(original_point);
}
}
}
} // namespace lepp
#endif
|
Implement a DepthLimit SplitStrategy
|
Implement a DepthLimit SplitStrategy
This implementation of the `SplitStrategy` interface stops the splitting
process once a certain depth of the BFS tree is reached.
|
C++
|
mit
|
sahandy/lepp2,mlalic/lepp2,mlalic/lepp2,sahandy/lepp2
|
7d21ab59fdf3939128fac67b0fb7e4e119397ce3
|
src/libaten/geometry/vertex.cpp
|
src/libaten/geometry/vertex.cpp
|
#include "geometry/vertex.h"
namespace aten
{
std::vector<int> VertexManager::s_indices;
std::vector<vertex> VertexManager::s_vertices;
GeomVertexBuffer VertexManager::s_vb;
void VertexManager::build()
{
s_vb.init(
sizeof(vertex),
s_vertices.size(),
0,
&s_vertices[0]);
}
}
|
#include "geometry/vertex.h"
namespace aten
{
std::vector<int> VertexManager::s_indices;
std::vector<vertex> VertexManager::s_vertices;
GeomVertexBuffer VertexManager::s_vb;
void VertexManager::build()
{
if (!s_vertices.empty()
&& !s_vb.isInitialized())
{
s_vb.init(
sizeof(vertex),
s_vertices.size(),
0,
&s_vertices[0]);
}
}
}
|
Modify to initialize one time.
|
Modify to initialize one time.
|
C++
|
mit
|
nakdai/aten,nakdai/aten
|
80735c4cc987d9db89bdc248010c8f47fd748c1b
|
src/libexpr/primops/fetchGit.cc
|
src/libexpr/primops/fetchGit.cc
|
#include "primops.hh"
#include "eval-inline.hh"
#include "download.hh"
#include "store-api.hh"
#include "pathlocks.hh"
#include <sys/time.h>
#include <regex>
#include <nlohmann/json.hpp>
using namespace std::string_literals;
namespace nix {
struct GitInfo
{
Path storePath;
std::string rev;
std::string shortRev;
uint64_t revCount = 0;
};
std::regex revRegex("^[0-9a-fA-F]{40}$");
GitInfo exportGit(ref<Store> store, const std::string & uri,
std::experimental::optional<std::string> ref, std::string rev,
const std::string & name)
{
if (settings.pureEval && rev == "")
throw Error("in pure evaluation mode, 'fetchGit' requires a Git revision");
if (!ref && rev == "" && hasPrefix(uri, "/") && pathExists(uri + "/.git")) {
bool clean = true;
try {
runProgram("git", true, { "-C", uri, "diff-index", "--quiet", "HEAD", "--" });
} catch (ExecError e) {
if (!WIFEXITED(e.status) || WEXITSTATUS(e.status) != 1) throw;
clean = false;
}
if (!clean) {
/* This is an unclean working tree. So copy all tracked
files. */
GitInfo gitInfo;
gitInfo.rev = "0000000000000000000000000000000000000000";
gitInfo.shortRev = std::string(gitInfo.rev, 0, 7);
auto files = tokenizeString<std::set<std::string>>(
runProgram("git", true, { "-C", uri, "ls-files", "-z" }), "\0"s);
PathFilter filter = [&](const Path & p) -> bool {
assert(hasPrefix(p, uri));
std::string file(p, uri.size() + 1);
auto st = lstat(p);
if (S_ISDIR(st.st_mode)) {
auto prefix = file + "/";
auto i = files.lower_bound(prefix);
return i != files.end() && hasPrefix(*i, prefix);
}
return files.count(file);
};
gitInfo.storePath = store->addToStore("source", uri, true, htSHA256, filter);
return gitInfo;
}
// clean working tree, but no ref or rev specified. Use 'HEAD'.
rev = chomp(runProgram("git", true, { "-C", uri, "rev-parse", "HEAD" }));
ref = "HEAD"s;
}
if (!ref) ref = "HEAD"s;
if (rev != "" && !std::regex_match(rev, revRegex))
throw Error("invalid Git revision '%s'", rev);
Path cacheDir = getCacheDir() + "/nix/git";
if (!pathExists(cacheDir)) {
runProgram("git", true, { "init", "--bare", cacheDir });
}
std::string localRef = hashString(htSHA256, fmt("%s-%s", uri, *ref)).to_string(Base32, false);
Path localRefFile = cacheDir + "/refs/heads/" + localRef;
bool doFetch;
time_t now = time(0);
/* If a rev was specified, we need to fetch if it's not in the
repo. */
if (rev != "") {
try {
runProgram("git", true, { "-C", cacheDir, "cat-file", "-e", rev });
doFetch = false;
} catch (ExecError & e) {
if (WIFEXITED(e.status)) {
doFetch = true;
} else {
throw;
}
}
} else {
/* If the local ref is older than ‘tarball-ttl’ seconds, do a
git fetch to update the local ref to the remote ref. */
struct stat st;
doFetch = stat(localRefFile.c_str(), &st) != 0 ||
st.st_mtime <= now - settings.tarballTtl;
}
if (doFetch)
{
Activity act(*logger, lvlTalkative, actUnknown, fmt("fetching Git repository '%s'", uri));
// FIXME: git stderr messes up our progress indicator, so
// we're using --quiet for now. Should process its stderr.
runProgram("git", true, { "-C", cacheDir, "fetch", "--quiet", "--force", "--", uri, *ref + ":" + localRef });
struct timeval times[2];
times[0].tv_sec = now;
times[0].tv_usec = 0;
times[1].tv_sec = now;
times[1].tv_usec = 0;
utimes(localRefFile.c_str(), times);
}
// FIXME: check whether rev is an ancestor of ref.
GitInfo gitInfo;
gitInfo.rev = rev != "" ? rev : chomp(readFile(localRefFile));
gitInfo.shortRev = std::string(gitInfo.rev, 0, 7);
printTalkative("using revision %s of repo '%s'", uri, gitInfo.rev);
std::string storeLinkName = hashString(htSHA512, name + std::string("\0"s) + gitInfo.rev).to_string(Base32, false);
Path storeLink = cacheDir + "/" + storeLinkName + ".link";
PathLocks storeLinkLock({storeLink}, fmt("waiting for lock on '%1%'...", storeLink)); // FIXME: broken
try {
auto json = nlohmann::json::parse(readFile(storeLink));
assert(json["name"] == name && json["rev"] == gitInfo.rev);
gitInfo.storePath = json["storePath"];
if (store->isValidPath(gitInfo.storePath)) {
gitInfo.revCount = json["revCount"];
return gitInfo;
}
} catch (SysError & e) {
if (e.errNo != ENOENT) throw;
}
// FIXME: should pipe this, or find some better way to extract a
// revision.
auto tar = runProgram("git", true, { "-C", cacheDir, "archive", gitInfo.rev });
Path tmpDir = createTempDir();
AutoDelete delTmpDir(tmpDir, true);
runProgram("tar", true, { "x", "-C", tmpDir }, tar);
gitInfo.storePath = store->addToStore(name, tmpDir);
gitInfo.revCount = std::stoull(runProgram("git", true, { "-C", cacheDir, "rev-list", "--count", gitInfo.rev }));
nlohmann::json json;
json["storePath"] = gitInfo.storePath;
json["uri"] = uri;
json["name"] = name;
json["rev"] = gitInfo.rev;
json["revCount"] = gitInfo.revCount;
writeFile(storeLink, json.dump());
return gitInfo;
}
static void prim_fetchGit(EvalState & state, const Pos & pos, Value * * args, Value & v)
{
std::string url;
std::experimental::optional<std::string> ref;
std::string rev;
std::string name = "source";
PathSet context;
state.forceValue(*args[0]);
if (args[0]->type == tAttrs) {
state.forceAttrs(*args[0], pos);
for (auto & attr : *args[0]->attrs) {
string n(attr.name);
if (n == "url")
url = state.coerceToString(*attr.pos, *attr.value, context, false, false);
else if (n == "ref")
ref = state.forceStringNoCtx(*attr.value, *attr.pos);
else if (n == "rev")
rev = state.forceStringNoCtx(*attr.value, *attr.pos);
else if (n == "name")
name = state.forceStringNoCtx(*attr.value, *attr.pos);
else
throw EvalError("unsupported argument '%s' to 'fetchGit', at %s", attr.name, *attr.pos);
}
if (url.empty())
throw EvalError(format("'url' argument required, at %1%") % pos);
} else
url = state.coerceToString(pos, *args[0], context, false, false);
if (!isUri(url)) url = absPath(url);
// FIXME: git externals probably can be used to bypass the URI
// whitelist. Ah well.
state.checkURI(url);
auto gitInfo = exportGit(state.store, url, ref, rev, name);
state.mkAttrs(v, 8);
mkString(*state.allocAttr(v, state.sOutPath), gitInfo.storePath, PathSet({gitInfo.storePath}));
mkString(*state.allocAttr(v, state.symbols.create("rev")), gitInfo.rev);
mkString(*state.allocAttr(v, state.symbols.create("shortRev")), gitInfo.shortRev);
mkInt(*state.allocAttr(v, state.symbols.create("revCount")), gitInfo.revCount);
v.attrs->sort();
if (state.allowedPaths)
state.allowedPaths->insert(gitInfo.storePath);
}
static RegisterPrimOp r("fetchGit", 1, prim_fetchGit);
}
|
#include "primops.hh"
#include "eval-inline.hh"
#include "download.hh"
#include "store-api.hh"
#include "pathlocks.hh"
#include <sys/time.h>
#include <regex>
#include <nlohmann/json.hpp>
using namespace std::string_literals;
namespace nix {
struct GitInfo
{
Path storePath;
std::string rev;
std::string shortRev;
uint64_t revCount = 0;
};
std::regex revRegex("^[0-9a-fA-F]{40}$");
GitInfo exportGit(ref<Store> store, const std::string & uri,
std::experimental::optional<std::string> ref, std::string rev,
const std::string & name)
{
if (settings.pureEval && rev == "")
throw Error("in pure evaluation mode, 'fetchGit' requires a Git revision");
if (!ref && rev == "" && hasPrefix(uri, "/") && pathExists(uri + "/.git")) {
bool clean = true;
try {
runProgram("git", true, { "-C", uri, "diff-index", "--quiet", "HEAD", "--" });
} catch (ExecError e) {
if (!WIFEXITED(e.status) || WEXITSTATUS(e.status) != 1) throw;
clean = false;
}
if (!clean) {
/* This is an unclean working tree. So copy all tracked
files. */
GitInfo gitInfo;
gitInfo.rev = "0000000000000000000000000000000000000000";
gitInfo.shortRev = std::string(gitInfo.rev, 0, 7);
auto files = tokenizeString<std::set<std::string>>(
runProgram("git", true, { "-C", uri, "ls-files", "-z" }), "\0"s);
PathFilter filter = [&](const Path & p) -> bool {
assert(hasPrefix(p, uri));
std::string file(p, uri.size() + 1);
auto st = lstat(p);
if (S_ISDIR(st.st_mode)) {
auto prefix = file + "/";
auto i = files.lower_bound(prefix);
return i != files.end() && hasPrefix(*i, prefix);
}
return files.count(file);
};
gitInfo.storePath = store->addToStore("source", uri, true, htSHA256, filter);
return gitInfo;
}
// clean working tree, but no ref or rev specified. Use 'HEAD'.
rev = chomp(runProgram("git", true, { "-C", uri, "rev-parse", "HEAD" }));
ref = "HEAD"s;
}
if (!ref) ref = "HEAD"s;
if (rev != "" && !std::regex_match(rev, revRegex))
throw Error("invalid Git revision '%s'", rev);
Path cacheDir = getCacheDir() + "/nix/git";
if (!pathExists(cacheDir)) {
runProgram("git", true, { "init", "--bare", cacheDir });
}
std::string localRef = hashString(htSHA256, fmt("%s-%s", uri, *ref)).to_string(Base32, false);
Path localRefFile = cacheDir + "/refs/heads/" + localRef;
bool doFetch;
time_t now = time(0);
/* If a rev was specified, we need to fetch if it's not in the
repo. */
if (rev != "") {
try {
runProgram("git", true, { "-C", cacheDir, "cat-file", "-e", rev });
doFetch = false;
} catch (ExecError & e) {
if (WIFEXITED(e.status)) {
doFetch = true;
} else {
throw;
}
}
} else {
/* If the local ref is older than ‘tarball-ttl’ seconds, do a
git fetch to update the local ref to the remote ref. */
struct stat st;
doFetch = stat(localRefFile.c_str(), &st) != 0 ||
st.st_mtime <= now - settings.tarballTtl;
}
if (doFetch)
{
Activity act(*logger, lvlTalkative, actUnknown, fmt("fetching Git repository '%s'", uri));
// FIXME: git stderr messes up our progress indicator, so
// we're using --quiet for now. Should process its stderr.
runProgram("git", true, { "-C", cacheDir, "fetch", "--quiet", "--force", "--", uri, *ref + ":" + localRef });
struct timeval times[2];
times[0].tv_sec = now;
times[0].tv_usec = 0;
times[1].tv_sec = now;
times[1].tv_usec = 0;
utimes(localRefFile.c_str(), times);
}
// FIXME: check whether rev is an ancestor of ref.
GitInfo gitInfo;
gitInfo.rev = rev != "" ? rev : chomp(readFile(localRefFile));
gitInfo.shortRev = std::string(gitInfo.rev, 0, 7);
printTalkative("using revision %s of repo '%s'", gitInfo.rev, uri);
std::string storeLinkName = hashString(htSHA512, name + std::string("\0"s) + gitInfo.rev).to_string(Base32, false);
Path storeLink = cacheDir + "/" + storeLinkName + ".link";
PathLocks storeLinkLock({storeLink}, fmt("waiting for lock on '%1%'...", storeLink)); // FIXME: broken
try {
auto json = nlohmann::json::parse(readFile(storeLink));
assert(json["name"] == name && json["rev"] == gitInfo.rev);
gitInfo.storePath = json["storePath"];
if (store->isValidPath(gitInfo.storePath)) {
gitInfo.revCount = json["revCount"];
return gitInfo;
}
} catch (SysError & e) {
if (e.errNo != ENOENT) throw;
}
// FIXME: should pipe this, or find some better way to extract a
// revision.
auto tar = runProgram("git", true, { "-C", cacheDir, "archive", gitInfo.rev });
Path tmpDir = createTempDir();
AutoDelete delTmpDir(tmpDir, true);
runProgram("tar", true, { "x", "-C", tmpDir }, tar);
gitInfo.storePath = store->addToStore(name, tmpDir);
gitInfo.revCount = std::stoull(runProgram("git", true, { "-C", cacheDir, "rev-list", "--count", gitInfo.rev }));
nlohmann::json json;
json["storePath"] = gitInfo.storePath;
json["uri"] = uri;
json["name"] = name;
json["rev"] = gitInfo.rev;
json["revCount"] = gitInfo.revCount;
writeFile(storeLink, json.dump());
return gitInfo;
}
static void prim_fetchGit(EvalState & state, const Pos & pos, Value * * args, Value & v)
{
std::string url;
std::experimental::optional<std::string> ref;
std::string rev;
std::string name = "source";
PathSet context;
state.forceValue(*args[0]);
if (args[0]->type == tAttrs) {
state.forceAttrs(*args[0], pos);
for (auto & attr : *args[0]->attrs) {
string n(attr.name);
if (n == "url")
url = state.coerceToString(*attr.pos, *attr.value, context, false, false);
else if (n == "ref")
ref = state.forceStringNoCtx(*attr.value, *attr.pos);
else if (n == "rev")
rev = state.forceStringNoCtx(*attr.value, *attr.pos);
else if (n == "name")
name = state.forceStringNoCtx(*attr.value, *attr.pos);
else
throw EvalError("unsupported argument '%s' to 'fetchGit', at %s", attr.name, *attr.pos);
}
if (url.empty())
throw EvalError(format("'url' argument required, at %1%") % pos);
} else
url = state.coerceToString(pos, *args[0], context, false, false);
if (!isUri(url)) url = absPath(url);
// FIXME: git externals probably can be used to bypass the URI
// whitelist. Ah well.
state.checkURI(url);
auto gitInfo = exportGit(state.store, url, ref, rev, name);
state.mkAttrs(v, 8);
mkString(*state.allocAttr(v, state.sOutPath), gitInfo.storePath, PathSet({gitInfo.storePath}));
mkString(*state.allocAttr(v, state.symbols.create("rev")), gitInfo.rev);
mkString(*state.allocAttr(v, state.symbols.create("shortRev")), gitInfo.shortRev);
mkInt(*state.allocAttr(v, state.symbols.create("revCount")), gitInfo.revCount);
v.attrs->sort();
if (state.allowedPaths)
state.allowedPaths->insert(gitInfo.storePath);
}
static RegisterPrimOp r("fetchGit", 1, prim_fetchGit);
}
|
Fix debug message
|
fetchGit: Fix debug message
|
C++
|
lgpl-2.1
|
NixOS/nix,peti/nix,dezgeg/nix,rycee/nix,dezgeg/nix,layus/nix,layus/nix,NixOS/nix,peti/nix,layus/nix,ehmry/nix,NixOS/nix,rycee/nix,dezgeg/nix,dtzWill/nix,ehmry/nix,ehmry/nix,layus/nix,zimbatm/nix,rycee/nix,zimbatm/nix,vcunat/nix,vcunat/nix,peti/nix,NixOS/nix,shlevy/nix,layus/nix,NixOS/nix,peti/nix,dtzWill/nix,shlevy/nix,rycee/nix,vcunat/nix,zimbatm/nix,dtzWill/nix,dezgeg/nix,pikajude/nix,zimbatm/nix,shlevy/nix,dezgeg/nix,dtzWill/nix,rycee/nix,pikajude/nix,ehmry/nix,ehmry/nix,peti/nix,ehmry/nix,pikajude/nix,dtzWill/nix,vcunat/nix,shlevy/nix,shlevy/nix
|
96c22c9cdff5abb50d3653d352acfbbf345b96d2
|
src/libs/engine/AudioBuffer.cpp
|
src/libs/engine/AudioBuffer.cpp
|
/* This file is part of Ingen.
* Copyright (C) 2007 Dave Robillard <http://drobilla.net>
*
* Ingen is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* Ingen 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 details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <iostream>
#include <cassert>
#include <stdlib.h>
#include "AudioBuffer.hpp"
using namespace std;
/* TODO: Be sure these functions are vectorized by GCC when it's vectorizer
* stops sucking. Probably a good idea to inline them as well */
namespace Ingen {
AudioBuffer::AudioBuffer(size_t size)
: Buffer((size == 1) ? DataType::CONTROL : DataType::AUDIO, size)
, _data(NULL)
, _local_data(NULL)
, _size(size)
, _filled_size(0)
, _state(OK)
, _set_value(0)
, _set_time(0)
{
assert(_size > 0);
allocate();
assert(data());
}
void
AudioBuffer::resize(size_t size)
{
_size = size;
Sample* const old_data = _data;
const bool using_local_data = (_data == _local_data);
deallocate();
const int ret = posix_memalign((void**)&_local_data, 16, _size * sizeof(Sample));
if (ret != 0) {
cerr << "[Buffer] Failed to allocate buffer. Aborting." << endl;
exit(EXIT_FAILURE);
}
assert(ret == 0);
assert(_local_data);
if (using_local_data)
_data = _local_data;
else
_data = old_data;
set_block(0, 0, _size-1);
}
/** Allocate and use a locally managed buffer (data).
*/
void
AudioBuffer::allocate()
{
assert(!_joined_buf);
assert(_local_data == NULL);
assert(_size > 0);
const int ret = posix_memalign((void**)&_local_data, 16, _size * sizeof(Sample));
if (ret != 0) {
cerr << "[Buffer] Failed to allocate buffer. Aborting." << endl;
exit(EXIT_FAILURE);
}
assert(ret == 0);
assert(_local_data);
_data = _local_data;
set_block(0, 0, _size-1);
}
/** Free locally allocated buffer.
*/
void
AudioBuffer::deallocate()
{
assert(!_joined_buf);
free(_local_data);
_local_data = NULL;
_data = NULL;
}
/** Empty (ie zero) the buffer.
*/
void
AudioBuffer::clear()
{
set_block(0, 0, _size-1);
_state = OK;
_filled_size = 0;
}
/** Set value of buffer to @a val after @a start_sample.
*
* The Buffer will handle setting the intial portion of the buffer to the
* value on the next cycle automatically (if @a start_sample is > 0), as
* long as pre_process() is called every cycle.
*/
void
AudioBuffer::set_value(Sample val, FrameTime cycle_start, FrameTime time)
{
if (_size == 1)
time = cycle_start;
FrameTime offset = time - cycle_start;
assert(offset <= _size);
set_block(val, offset, _size - 1);
if (offset > 0)
_state = HALF_SET_CYCLE_1;
_set_time = time;
_set_value = val;
}
/** Set a block of buffer to @a val.
*
* @a start_sample and @a end_sample define the inclusive range to be set.
*/
void
AudioBuffer::set_block(Sample val, size_t start_offset, size_t end_offset)
{
assert(end_offset >= start_offset);
assert(end_offset < _size);
Sample* const buf = data();
assert(buf);
for (size_t i = start_offset; i <= end_offset; ++i)
buf[i] = val;
}
/** Scale a block of buffer by @a val.
*
* @a start_sample and @a end_sample define the inclusive range to be set.
*/
void
AudioBuffer::scale(Sample val, size_t start_sample, size_t end_sample)
{
assert(end_sample >= start_sample);
assert(end_sample < _size);
Sample* const buf = data();
assert(buf);
for (size_t i=start_sample; i <= end_sample; ++i)
buf[i] *= val;
}
/** Copy a block of @a src into buffer.
*
* @a start_sample and @a end_sample define the inclusive range to be set.
* This function only copies the same range in one buffer to another.
*/
void
AudioBuffer::copy(const Buffer* src, size_t start_sample, size_t end_sample)
{
assert(end_sample >= start_sample);
assert(end_sample < _size);
assert(src);
assert(src->type() == DataType::CONTROL || DataType::AUDIO);
Sample* const buf = data();
assert(buf);
const Sample* const src_buf = ((AudioBuffer*)src)->data();
assert(src_buf);
for (size_t i=start_sample; i <= end_sample; ++i)
buf[i] = src_buf[i];
}
/** Accumulate a block of @a src into @a dst.
*
* @a start_sample and @a end_sample define the inclusive range to be accumulated.
* This function only adds the same range in one buffer to another.
*/
void
AudioBuffer::accumulate(const AudioBuffer* const src, size_t start_sample, size_t end_sample)
{
assert(end_sample >= start_sample);
assert(end_sample < _size);
assert(src);
Sample* const buf = data();
assert(buf);
const Sample* const src_buf = src->data();
assert(src_buf);
for (size_t i=start_sample; i <= end_sample; ++i)
buf[i] += src_buf[i];
}
/** Use another buffer's data instead of the local one.
*
* This buffer will essentially be identical to @a buf after this call.
*/
bool
AudioBuffer::join(Buffer* buf)
{
AudioBuffer* abuf = dynamic_cast<AudioBuffer*>(buf);
if (!abuf)
return false;
assert(abuf->size() >= _size);
_joined_buf = abuf;
_filled_size = abuf->filled_size();
assert(_filled_size <= _size);
return true;
}
void
AudioBuffer::unjoin()
{
_joined_buf = NULL;
_data = _local_data;
}
void
AudioBuffer::prepare_read(FrameTime start, SampleCount nframes)
{
// FIXME: nframes parameter doesn't actually work,
// writing starts from 0 every time
assert(_size == 1 || nframes == _size);
switch (_state) {
case HALF_SET_CYCLE_1:
if (start > _set_time)
_state = HALF_SET_CYCLE_2;
break;
case HALF_SET_CYCLE_2:
set_block(_set_value, 0, _size-1);
_state = OK;
break;
default:
break;
}
}
/** Set the buffer (data) used.
*
* This is only to be used by Drivers (to provide zero-copy processing).
*/
void
AudioBuffer::set_data(Sample* buf)
{
assert(buf);
assert(!_joined_buf);
_data = buf;
}
} // namespace Ingen
|
/* This file is part of Ingen.
* Copyright (C) 2007 Dave Robillard <http://drobilla.net>
*
* Ingen is free software; you can redistribute it and/or modify it under the
* terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* Ingen 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 details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <iostream>
#include <cassert>
#include <stdlib.h>
#include "AudioBuffer.hpp"
using namespace std;
/* TODO: Be sure these functions are vectorized by GCC when it's vectorizer
* stops sucking. Probably a good idea to inline them as well */
namespace Ingen {
AudioBuffer::AudioBuffer(size_t size)
: Buffer((size == 1) ? DataType::CONTROL : DataType::AUDIO, size)
, _data(NULL)
, _local_data(NULL)
, _size(size)
, _filled_size(0)
, _state(OK)
, _set_value(0)
, _set_time(0)
{
assert(_size > 0);
allocate();
assert(data());
}
void
AudioBuffer::resize(size_t size)
{
_size = size;
Sample* const old_data = _data;
const bool using_local_data = (_data == _local_data);
deallocate();
const int ret = posix_memalign((void**)&_local_data, 16, _size * sizeof(Sample));
if (ret != 0) {
cerr << "[Buffer] Failed to allocate buffer. Aborting." << endl;
exit(EXIT_FAILURE);
}
assert(ret == 0);
assert(_local_data);
if (using_local_data)
_data = _local_data;
else
_data = old_data;
set_block(0, 0, _size-1);
}
/** Allocate and use a locally managed buffer (data).
*/
void
AudioBuffer::allocate()
{
assert(!_joined_buf);
assert(_local_data == NULL);
assert(_size > 0);
const int ret = posix_memalign((void**)&_local_data, 16, _size * sizeof(Sample));
if (ret != 0) {
cerr << "[Buffer] Failed to allocate buffer. Aborting." << endl;
exit(EXIT_FAILURE);
}
assert(ret == 0);
assert(_local_data);
_data = _local_data;
set_block(0, 0, _size-1);
}
/** Free locally allocated buffer.
*/
void
AudioBuffer::deallocate()
{
assert(!_joined_buf);
free(_local_data);
_local_data = NULL;
_data = NULL;
}
/** Empty (ie zero) the buffer.
*/
void
AudioBuffer::clear()
{
set_block(0, 0, _size-1);
_state = OK;
_filled_size = 0;
}
/** Set value of buffer to @a val after @a start_sample.
*
* The Buffer will handle setting the intial portion of the buffer to the
* value on the next cycle automatically (if @a start_sample is > 0), as
* long as pre_process() is called every cycle.
*/
void
AudioBuffer::set_value(Sample val, FrameTime cycle_start, FrameTime time)
{
if (_size == 1)
time = cycle_start;
FrameTime offset = time - cycle_start;
assert(offset <= _size);
if (offset < _size) {
set_block(val, offset, _size - 1);
if (offset > 0)
_state = HALF_SET_CYCLE_1;
} // else trigger at very end of block
_set_time = time;
_set_value = val;
}
/** Set a block of buffer to @a val.
*
* @a start_sample and @a end_sample define the inclusive range to be set.
*/
void
AudioBuffer::set_block(Sample val, size_t start_offset, size_t end_offset)
{
assert(end_offset >= start_offset);
assert(end_offset < _size);
Sample* const buf = data();
assert(buf);
for (size_t i = start_offset; i <= end_offset; ++i)
buf[i] = val;
}
/** Scale a block of buffer by @a val.
*
* @a start_sample and @a end_sample define the inclusive range to be set.
*/
void
AudioBuffer::scale(Sample val, size_t start_sample, size_t end_sample)
{
assert(end_sample >= start_sample);
assert(end_sample < _size);
Sample* const buf = data();
assert(buf);
for (size_t i=start_sample; i <= end_sample; ++i)
buf[i] *= val;
}
/** Copy a block of @a src into buffer.
*
* @a start_sample and @a end_sample define the inclusive range to be set.
* This function only copies the same range in one buffer to another.
*/
void
AudioBuffer::copy(const Buffer* src, size_t start_sample, size_t end_sample)
{
assert(end_sample >= start_sample);
assert(end_sample < _size);
assert(src);
assert(src->type() == DataType::CONTROL || DataType::AUDIO);
Sample* const buf = data();
assert(buf);
const Sample* const src_buf = ((AudioBuffer*)src)->data();
assert(src_buf);
for (size_t i=start_sample; i <= end_sample; ++i)
buf[i] = src_buf[i];
}
/** Accumulate a block of @a src into @a dst.
*
* @a start_sample and @a end_sample define the inclusive range to be accumulated.
* This function only adds the same range in one buffer to another.
*/
void
AudioBuffer::accumulate(const AudioBuffer* const src, size_t start_sample, size_t end_sample)
{
assert(end_sample >= start_sample);
assert(end_sample < _size);
assert(src);
Sample* const buf = data();
assert(buf);
const Sample* const src_buf = src->data();
assert(src_buf);
for (size_t i=start_sample; i <= end_sample; ++i)
buf[i] += src_buf[i];
}
/** Use another buffer's data instead of the local one.
*
* This buffer will essentially be identical to @a buf after this call.
*/
bool
AudioBuffer::join(Buffer* buf)
{
AudioBuffer* abuf = dynamic_cast<AudioBuffer*>(buf);
if (!abuf)
return false;
assert(abuf->size() >= _size);
_joined_buf = abuf;
_filled_size = abuf->filled_size();
assert(_filled_size <= _size);
return true;
}
void
AudioBuffer::unjoin()
{
_joined_buf = NULL;
_data = _local_data;
}
void
AudioBuffer::prepare_read(FrameTime start, SampleCount nframes)
{
// FIXME: nframes parameter doesn't actually work,
// writing starts from 0 every time
assert(_size == 1 || nframes == _size);
switch (_state) {
case HALF_SET_CYCLE_1:
if (start > _set_time)
_state = HALF_SET_CYCLE_2;
break;
case HALF_SET_CYCLE_2:
set_block(_set_value, 0, _size-1);
_state = OK;
break;
default:
break;
}
}
/** Set the buffer (data) used.
*
* This is only to be used by Drivers (to provide zero-copy processing).
*/
void
AudioBuffer::set_data(Sample* buf)
{
assert(buf);
assert(!_joined_buf);
_data = buf;
}
} // namespace Ingen
|
Fix crash on triggers on the last sample of the cycle.
|
Fix crash on triggers on the last sample of the cycle.
git-svn-id: 0c12d7dd8c1ea2d70f3066f15e3a34dd5ccac610@1356 a436a847-0d15-0410-975c-d299462d15a1
|
C++
|
agpl-3.0
|
drobilla/ingen,ventosus/ingen,ventosus/ingen,drobilla/ingen,ventosus/ingen,drobilla/ingen,ventosus/ingen,drobilla/ingen
|
d45084d7f2d358ee8f441df0fd3514d8a18f71af
|
src/Dataflow/Serialization/Network/Tests/NetworkSerializationTests.cc
|
src/Dataflow/Serialization/Network/Tests/NetworkSerializationTests.cc
|
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 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 <Dataflow/Serialization/Network/ModuleDescriptionSerialization.h>
#include <Dataflow/Serialization/Network/NetworkDescriptionSerialization.h>
#include <Dataflow/Serialization/Network/NetworkXMLSerializer.h>
#include <Modules/Factory/HardCodedModuleFactory.h>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <Dataflow/Network/Network.h>
#include <Dataflow/Network/ModuleInterface.h>
#include <Dataflow/Network/ModuleStateInterface.h>
#include <Dataflow/Network/ConnectionId.h>
#include <Dataflow/Network/Tests/MockNetwork.h>
#include <Core/Datatypes/DenseMatrix.h>
#include <Core/Datatypes/MatrixComparison.h>
#include <Core/Datatypes/MatrixIO.h>
#include <Modules/Basic/SendTestMatrix.h>
#include <Modules/Basic/ReceiveTestMatrix.h>
#include <Modules/Math/EvaluateLinearAlgebraUnary.h>
#include <Modules/Factory/HardCodedModuleFactory.h>
#include <Core/Algorithms/Math/EvaluateLinearAlgebraUnaryAlgo.h>
#include <Core/Algorithms/Math/EvaluateLinearAlgebraBinaryAlgo.h>
#include <Core/Algorithms/Math/ReportMatrixInfo.h>
#include <Dataflow/Network/Tests/MockModuleState.h>
#include <Dataflow/State/SimpleMapModuleState.h>
#include <Dataflow/Engine/Controller/NetworkEditorController.h>
#include <Dataflow/Serialization/Network/XMLSerializer.h>
#include <Dataflow/Engine/Scheduler/DesktopExecutionStrategyFactory.h>
#include <Core/Algorithms/Base/AlgorithmVariableNames.h>
using namespace SCIRun;
using namespace SCIRun::Dataflow::Engine;
using namespace SCIRun::Modules::Basic;
using namespace SCIRun::Modules::Math;
using namespace SCIRun::Modules::Factory;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Dataflow::Networks::Mocks;
using namespace SCIRun::Core::Algorithms::Math;
using namespace SCIRun::Dataflow::State;
using namespace SCIRun::Core::Algorithms;
#include <stdexcept>
#include <fstream>
#include <boost/assign.hpp>
using namespace SCIRun::Dataflow::Networks;
using namespace boost::assign;
namespace
{
DenseMatrixHandle matrix1()
{
DenseMatrixHandle m(new DenseMatrix(3, 3));
for (int i = 0; i < m->rows(); ++i)
for (int j = 0; j < m->cols(); ++j)
(*m)(i, j) = 3.0 * i + j;
return m;
}
DenseMatrixHandle matrix2()
{
DenseMatrixHandle m(new DenseMatrix(3, 3));
for (int i = 0; i < m->rows(); ++i)
for (int j = 0; j < m->cols(); ++j)
(*m)(i, j) = -2.0 * i + j;
return m;
}
NetworkXML exampleNet()
{
ModuleLookupInfoXML info1;
info1.module_name_ = "EvaluateLinearAlgebraUnary";
info1.category_name_ = "Math";
info1.package_name_ = "SCIRun";
ModuleLookupInfoXML info2;
info2.module_name_ = "ReadMatrix";
info2.category_name_ = "DataIO";
info2.package_name_ = "SCIRun";
ModuleLookupInfoXML info3;
info3.module_name_ = "WriteMatrix";
info3.category_name_ = "DataIO";
info3.package_name_ = "SCIRun";
ConnectionDescriptionXML conn;
conn.out_.moduleId_ = ModuleId("ReadMatrix", 2);
conn.in_.moduleId_ = ModuleId("EvaluateLinearAlgebraUnary", 1);
conn.out_.portId_ = PortId(0, "MatrixLoaded");
conn.in_.portId_ = PortId(0, "InputMatrix");
ConnectionDescriptionXML conn2;
conn2.out_.moduleId_ = ModuleId("EvaluateLinearAlgebraUnary", 1);
conn2.in_.moduleId_ = ModuleId("WriteMatrix", 3);
conn2.out_.portId_ = PortId(0, "Result");
conn2.in_.portId_ = PortId(0, "MatrixToWrite");
ConnectionsXML connections;
connections += conn2, conn;
ModuleMapXML mods;
mods["EvaluateLinearAlgebraUnary:1"] = info1;
mods["ReadMatrix:2"] = info2;
mods["WriteMatrix:3"] = info3;
NetworkXML network;
network.connections = connections;
network.modules = mods;
return network;
}
}
TEST(SerializeNetworkTest, RoundTripData)
{
NetworkXML networkXML = exampleNet();
NetworkXMLSerializer serializer;
std::ostringstream ostr1;
serializer.save_xml(networkXML, ostr1);
const std::string xml1 = ostr1.str();
std::istringstream istr(xml1);
NetworkXMLHandle readIn = serializer.load_xml(istr);
ASSERT_TRUE(readIn.get() != nullptr);
std::ostringstream ostr2;
serializer.save_xml(*readIn, ostr2);
const std::string xml2 = ostr2.str();
EXPECT_EQ(xml1, xml2);
}
TEST(SerializeNetworkTest, RoundTripObject)
{
NetworkXML networkXML = exampleNet();
NetworkXMLSerializer serializer;
std::ostringstream ostr1;
serializer.save_xml(networkXML, ostr1);
ModuleFactoryHandle mf(new HardCodedModuleFactory);
NetworkEditorController controller(mf, ModuleStateFactoryHandle(), ExecutionStrategyFactoryHandle(), AlgorithmFactoryHandle());
NetworkXMLConverter converter(mf, ModuleStateFactoryHandle(), AlgorithmFactoryHandle(), 0);
NetworkHandle network = converter.from_xml_data(networkXML);
ASSERT_TRUE(network.get() != nullptr);
auto xml2 = converter.to_xml_data(network);
ASSERT_TRUE(xml2.get() != nullptr);
std::ostringstream ostr2;
serializer.save_xml(xml2->network, ostr2);
EXPECT_EQ(ostr1.str(), ostr2.str());
}
TEST(SerializeNetworkTest, FullTestWithModuleState)
{
ModuleFactoryHandle mf(new HardCodedModuleFactory);
ModuleStateFactoryHandle sf(new SimpleMapModuleStateFactory);
ExecutionStrategyFactoryHandle exe(new DesktopExecutionStrategyFactory);
NetworkEditorController controller(mf, sf, exe, AlgorithmFactoryHandle());
ModuleHandle matrix1Send = controller.addModule("SendTestMatrix");
ModuleHandle matrix2Send = controller.addModule("SendTestMatrix");
ModuleHandle transpose = controller.addModule("EvaluateLinearAlgebraUnary");
ModuleHandle negate = controller.addModule("EvaluateLinearAlgebraUnary");
ModuleHandle scalar = controller.addModule("EvaluateLinearAlgebraUnary");
ModuleHandle multiply = controller.addModule("EvaluateLinearAlgebraBinary");
ModuleHandle add = controller.addModule("EvaluateLinearAlgebraBinary");
ModuleHandle report = controller.addModule("ReportMatrixInfo");
ModuleHandle receive = controller.addModule("ReceiveTestMatrix");
NetworkHandle matrixMathNetwork = controller.getNetwork();
EXPECT_EQ(9, matrixMathNetwork->nmodules());
EXPECT_EQ(0, matrixMathNetwork->nconnections());
matrixMathNetwork->connect(ConnectionOutputPort(matrix1Send, 0), ConnectionInputPort(transpose, 0));
matrixMathNetwork->connect(ConnectionOutputPort(matrix1Send, 0), ConnectionInputPort(negate, 0));
matrixMathNetwork->connect(ConnectionOutputPort(matrix2Send, 0), ConnectionInputPort(scalar, 0));
matrixMathNetwork->connect(ConnectionOutputPort(negate, 0), ConnectionInputPort(multiply, 0));
matrixMathNetwork->connect(ConnectionOutputPort(scalar, 0), ConnectionInputPort(multiply, 1));
matrixMathNetwork->connect(ConnectionOutputPort(transpose, 0), ConnectionInputPort(add, 0));
matrixMathNetwork->connect(ConnectionOutputPort(multiply, 0), ConnectionInputPort(add, 1));
matrixMathNetwork->connect(ConnectionOutputPort(add, 0), ConnectionInputPort(report, 0));
matrixMathNetwork->connect(ConnectionOutputPort(add, 0), ConnectionInputPort(receive, 0));
EXPECT_EQ(9, matrixMathNetwork->nconnections());
//Set module parameters.
matrix1Send->get_state()->setTransientValue("MatrixToSend", matrix1());
matrix2Send->get_state()->setTransientValue("MatrixToSend", matrix2());
transpose->get_state()->setValue(Variables::Operator, EvaluateLinearAlgebraUnaryAlgorithm::TRANSPOSE);
negate->get_state()->setValue(Variables::Operator, EvaluateLinearAlgebraUnaryAlgorithm::NEGATE);
scalar->get_state()->setValue(Variables::Operator, EvaluateLinearAlgebraUnaryAlgorithm::SCALAR_MULTIPLY);
scalar->get_state()->setValue(Variables::ScalarValue, 4.0);
multiply->get_state()->setValue(Variables::Operator, EvaluateLinearAlgebraBinaryAlgorithm::MULTIPLY);
add->get_state()->setValue(Variables::Operator, EvaluateLinearAlgebraBinaryAlgorithm::ADD);
auto xml = controller.saveNetwork();
std::ostringstream ostr;
XMLSerializer::save_xml(*xml, ostr, "network");
std::cout << ostr.str() << std::endl;
NetworkEditorController controller2(mf, sf, exe, AlgorithmFactoryHandle());
controller2.loadNetwork(xml);
NetworkHandle deserialized = controller2.getNetwork();
ASSERT_TRUE(deserialized.get() != nullptr);
EXPECT_EQ(9, deserialized->nconnections());
EXPECT_EQ(9, deserialized->nmodules());
EXPECT_NE(matrixMathNetwork.get(), deserialized.get());
ModuleHandle trans2 = deserialized->lookupModule(ModuleId("EvaluateLinearAlgebraUnary", 2));
ASSERT_TRUE(trans2.get() != nullptr);
EXPECT_EQ("EvaluateLinearAlgebraUnary", trans2->get_module_name());
EXPECT_EQ(EvaluateLinearAlgebraUnaryAlgorithm::TRANSPOSE, trans2->get_state()->getValue(Variables::Operator).getInt());
}
TEST(SerializeNetworkTest, FullTestWithDynamicPorts)
{
ModuleFactoryHandle mf(new HardCodedModuleFactory);
ModuleStateFactoryHandle sf(new SimpleMapModuleStateFactory);
NetworkEditorController controller(mf, sf, ExecutionStrategyFactoryHandle(), AlgorithmFactoryHandle());
std::vector<ModuleHandle> showFields;
showFields.push_back(controller.addModule("ShowField"));
showFields.push_back(controller.addModule("ShowField"));
showFields.push_back(controller.addModule("ShowField"));
showFields.push_back(controller.addModule("ShowField"));
showFields.push_back(controller.addModule("ShowField"));
ModuleHandle view = controller.addModule("ViewScene");
NetworkHandle net = controller.getNetwork();
EXPECT_EQ(showFields.size() + 1, net->nmodules());
EXPECT_EQ(0, net->nconnections());
size_t port = 0;
BOOST_FOREACH(ModuleHandle show, showFields)
{
std::cout << "Attempting to connect to view scene on " << port << std::endl;
controller.requestConnection(show->outputPorts()[0].get(), view->inputPorts()[port++].get());
}
EXPECT_EQ(showFields.size(), net->nconnections());
auto xml = controller.saveNetwork();
std::cout << "NOW TESTING SERIALIZED COPY" << std::endl;
std::ostringstream ostr;
XMLSerializer::save_xml(*xml, ostr, "network");
//std::cout << ostr.str() << std::endl;
NetworkEditorController controller2(mf, sf, ExecutionStrategyFactoryHandle(), AlgorithmFactoryHandle());
controller2.loadNetwork(xml);
NetworkHandle deserialized = controller2.getNetwork();
ASSERT_TRUE(deserialized != nullptr);
EXPECT_EQ(showFields.size(), deserialized->nconnections());
EXPECT_EQ(showFields.size() + 1, deserialized->nmodules());
EXPECT_NE(net.get(), deserialized.get());
}
|
/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2012 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 <Dataflow/Serialization/Network/ModuleDescriptionSerialization.h>
#include <Dataflow/Serialization/Network/NetworkDescriptionSerialization.h>
#include <Dataflow/Serialization/Network/NetworkXMLSerializer.h>
#include <Modules/Factory/HardCodedModuleFactory.h>
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <Dataflow/Network/Network.h>
#include <Dataflow/Network/ModuleInterface.h>
#include <Dataflow/Network/ModuleStateInterface.h>
#include <Dataflow/Network/ConnectionId.h>
#include <Dataflow/Network/Tests/MockNetwork.h>
#include <Core/Datatypes/DenseMatrix.h>
#include <Core/Datatypes/MatrixComparison.h>
#include <Core/Datatypes/MatrixIO.h>
#include <Modules/Basic/SendTestMatrix.h>
#include <Modules/Basic/ReceiveTestMatrix.h>
#include <Modules/Math/EvaluateLinearAlgebraUnary.h>
#include <Modules/Factory/HardCodedModuleFactory.h>
#include <Core/Algorithms/Math/EvaluateLinearAlgebraUnaryAlgo.h>
#include <Core/Algorithms/Math/EvaluateLinearAlgebraBinaryAlgo.h>
#include <Core/Algorithms/Math/ReportMatrixInfo.h>
#include <Dataflow/Network/Tests/MockModuleState.h>
#include <Dataflow/State/SimpleMapModuleState.h>
#include <Dataflow/Engine/Controller/NetworkEditorController.h>
#include <Dataflow/Serialization/Network/XMLSerializer.h>
#include <Dataflow/Engine/Scheduler/DesktopExecutionStrategyFactory.h>
#include <Core/Algorithms/Base/AlgorithmVariableNames.h>
using namespace SCIRun;
using namespace SCIRun::Dataflow::Engine;
using namespace SCIRun::Modules::Basic;
using namespace SCIRun::Modules::Math;
using namespace SCIRun::Modules::Factory;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Dataflow::Networks;
using namespace SCIRun::Dataflow::Networks::Mocks;
using namespace SCIRun::Core::Algorithms::Math;
using namespace SCIRun::Dataflow::State;
using namespace SCIRun::Core::Algorithms;
#include <stdexcept>
#include <fstream>
#include <boost/assign.hpp>
using namespace SCIRun::Dataflow::Networks;
using namespace boost::assign;
namespace
{
DenseMatrixHandle matrix1()
{
DenseMatrixHandle m(new DenseMatrix(3, 3));
for (int i = 0; i < m->rows(); ++i)
for (int j = 0; j < m->cols(); ++j)
(*m)(i, j) = 3.0 * i + j;
return m;
}
DenseMatrixHandle matrix2()
{
DenseMatrixHandle m(new DenseMatrix(3, 3));
for (int i = 0; i < m->rows(); ++i)
for (int j = 0; j < m->cols(); ++j)
(*m)(i, j) = -2.0 * i + j;
return m;
}
NetworkXML exampleNet()
{
ModuleLookupInfoXML info1;
info1.module_name_ = "EvaluateLinearAlgebraUnary";
info1.category_name_ = "Math";
info1.package_name_ = "SCIRun";
ModuleLookupInfoXML info2;
info2.module_name_ = "ReadMatrix";
info2.category_name_ = "DataIO";
info2.package_name_ = "SCIRun";
ModuleLookupInfoXML info3;
info3.module_name_ = "WriteMatrix";
info3.category_name_ = "DataIO";
info3.package_name_ = "SCIRun";
ConnectionDescriptionXML conn;
conn.out_.moduleId_ = ModuleId("ReadMatrix", 2);
conn.in_.moduleId_ = ModuleId("EvaluateLinearAlgebraUnary", 1);
conn.out_.portId_ = PortId(0, "MatrixLoaded");
conn.in_.portId_ = PortId(0, "InputMatrix");
ConnectionDescriptionXML conn2;
conn2.out_.moduleId_ = ModuleId("EvaluateLinearAlgebraUnary", 1);
conn2.in_.moduleId_ = ModuleId("WriteMatrix", 3);
conn2.out_.portId_ = PortId(0, "Result");
conn2.in_.portId_ = PortId(0, "MatrixToWrite");
ConnectionsXML connections;
connections += conn2, conn;
ModuleMapXML mods;
mods["EvaluateLinearAlgebraUnary:1"] = info1;
mods["ReadMatrix:2"] = info2;
mods["WriteMatrix:3"] = info3;
NetworkXML network;
network.connections = connections;
network.modules = mods;
return network;
}
}
TEST(SerializeNetworkTest, RoundTripData)
{
NetworkXML networkXML = exampleNet();
NetworkXMLSerializer serializer;
std::ostringstream ostr1;
serializer.save_xml(networkXML, ostr1);
const std::string xml1 = ostr1.str();
std::istringstream istr(xml1);
NetworkXMLHandle readIn = serializer.load_xml(istr);
ASSERT_TRUE(readIn.get() != nullptr);
std::ostringstream ostr2;
serializer.save_xml(*readIn, ostr2);
const std::string xml2 = ostr2.str();
EXPECT_EQ(xml1, xml2);
}
TEST(SerializeNetworkTest, RoundTripObject)
{
NetworkXML networkXML = exampleNet();
NetworkXMLSerializer serializer;
std::ostringstream ostr1;
serializer.save_xml(networkXML, ostr1);
ModuleFactoryHandle mf(new HardCodedModuleFactory);
NetworkEditorController controller(mf, ModuleStateFactoryHandle(), ExecutionStrategyFactoryHandle(), AlgorithmFactoryHandle());
NetworkXMLConverter converter(mf, ModuleStateFactoryHandle(), AlgorithmFactoryHandle(), &controller);
NetworkHandle network = converter.from_xml_data(networkXML);
ASSERT_TRUE(network.get() != nullptr);
auto xml2 = converter.to_xml_data(network);
ASSERT_TRUE(xml2.get() != nullptr);
std::ostringstream ostr2;
serializer.save_xml(xml2->network, ostr2);
EXPECT_EQ(ostr1.str(), ostr2.str());
}
TEST(SerializeNetworkTest, FullTestWithModuleState)
{
Module::resetInstanceCount();
ModuleFactoryHandle mf(new HardCodedModuleFactory);
ModuleStateFactoryHandle sf(new SimpleMapModuleStateFactory);
ExecutionStrategyFactoryHandle exe(new DesktopExecutionStrategyFactory);
NetworkEditorController controller(mf, sf, exe, AlgorithmFactoryHandle());
ModuleHandle matrix1Send = controller.addModule("SendTestMatrix");
ModuleHandle matrix2Send = controller.addModule("SendTestMatrix");
ModuleHandle transpose = controller.addModule("EvaluateLinearAlgebraUnary");
ModuleHandle negate = controller.addModule("EvaluateLinearAlgebraUnary");
ModuleHandle scalar = controller.addModule("EvaluateLinearAlgebraUnary");
ModuleHandle multiply = controller.addModule("EvaluateLinearAlgebraBinary");
ModuleHandle add = controller.addModule("EvaluateLinearAlgebraBinary");
ModuleHandle report = controller.addModule("ReportMatrixInfo");
ModuleHandle receive = controller.addModule("ReceiveTestMatrix");
NetworkHandle matrixMathNetwork = controller.getNetwork();
EXPECT_EQ(9, matrixMathNetwork->nmodules());
EXPECT_EQ(0, matrixMathNetwork->nconnections());
matrixMathNetwork->connect(ConnectionOutputPort(matrix1Send, 0), ConnectionInputPort(transpose, 0));
matrixMathNetwork->connect(ConnectionOutputPort(matrix1Send, 0), ConnectionInputPort(negate, 0));
matrixMathNetwork->connect(ConnectionOutputPort(matrix2Send, 0), ConnectionInputPort(scalar, 0));
matrixMathNetwork->connect(ConnectionOutputPort(negate, 0), ConnectionInputPort(multiply, 0));
matrixMathNetwork->connect(ConnectionOutputPort(scalar, 0), ConnectionInputPort(multiply, 1));
matrixMathNetwork->connect(ConnectionOutputPort(transpose, 0), ConnectionInputPort(add, 0));
matrixMathNetwork->connect(ConnectionOutputPort(multiply, 0), ConnectionInputPort(add, 1));
matrixMathNetwork->connect(ConnectionOutputPort(add, 0), ConnectionInputPort(report, 0));
matrixMathNetwork->connect(ConnectionOutputPort(add, 0), ConnectionInputPort(receive, 0));
EXPECT_EQ(9, matrixMathNetwork->nconnections());
//Set module parameters.
matrix1Send->get_state()->setTransientValue("MatrixToSend", matrix1());
matrix2Send->get_state()->setTransientValue("MatrixToSend", matrix2());
transpose->get_state()->setValue(Variables::Operator, EvaluateLinearAlgebraUnaryAlgorithm::TRANSPOSE);
negate->get_state()->setValue(Variables::Operator, EvaluateLinearAlgebraUnaryAlgorithm::NEGATE);
scalar->get_state()->setValue(Variables::Operator, EvaluateLinearAlgebraUnaryAlgorithm::SCALAR_MULTIPLY);
scalar->get_state()->setValue(Variables::ScalarValue, 4.0);
multiply->get_state()->setValue(Variables::Operator, EvaluateLinearAlgebraBinaryAlgorithm::MULTIPLY);
add->get_state()->setValue(Variables::Operator, EvaluateLinearAlgebraBinaryAlgorithm::ADD);
auto xml = controller.saveNetwork();
std::ostringstream ostr;
XMLSerializer::save_xml(*xml, ostr, "network");
std::cout << ostr.str() << std::endl;
NetworkEditorController controller2(mf, sf, exe, AlgorithmFactoryHandle());
controller2.loadNetwork(xml);
NetworkHandle deserialized = controller2.getNetwork();
ASSERT_TRUE(deserialized.get() != nullptr);
EXPECT_EQ(9, deserialized->nconnections());
EXPECT_EQ(9, deserialized->nmodules());
EXPECT_NE(matrixMathNetwork.get(), deserialized.get());
ModuleHandle trans2 = deserialized->lookupModule(ModuleId("EvaluateLinearAlgebraUnary", 2));
ASSERT_TRUE(trans2.get() != nullptr);
EXPECT_EQ("EvaluateLinearAlgebraUnary", trans2->get_module_name());
EXPECT_EQ(EvaluateLinearAlgebraUnaryAlgorithm::TRANSPOSE, trans2->get_state()->getValue(Variables::Operator).getInt());
}
TEST(SerializeNetworkTest, FullTestWithDynamicPorts)
{
ModuleFactoryHandle mf(new HardCodedModuleFactory);
ModuleStateFactoryHandle sf(new SimpleMapModuleStateFactory);
NetworkEditorController controller(mf, sf, ExecutionStrategyFactoryHandle(), AlgorithmFactoryHandle());
std::vector<ModuleHandle> showFields;
showFields.push_back(controller.addModule("ShowField"));
showFields.push_back(controller.addModule("ShowField"));
showFields.push_back(controller.addModule("ShowField"));
showFields.push_back(controller.addModule("ShowField"));
showFields.push_back(controller.addModule("ShowField"));
ModuleHandle view = controller.addModule("ViewScene");
NetworkHandle net = controller.getNetwork();
EXPECT_EQ(showFields.size() + 1, net->nmodules());
EXPECT_EQ(0, net->nconnections());
size_t port = 0;
BOOST_FOREACH(ModuleHandle show, showFields)
{
std::cout << "Attempting to connect to view scene on " << port << std::endl;
controller.requestConnection(show->outputPorts()[0].get(), view->inputPorts()[port++].get());
}
EXPECT_EQ(showFields.size(), net->nconnections());
auto xml = controller.saveNetwork();
std::cout << "NOW TESTING SERIALIZED COPY" << std::endl;
std::ostringstream ostr;
XMLSerializer::save_xml(*xml, ostr, "network");
//std::cout << ostr.str() << std::endl;
NetworkEditorController controller2(mf, sf, ExecutionStrategyFactoryHandle(), AlgorithmFactoryHandle());
controller2.loadNetwork(xml);
NetworkHandle deserialized = controller2.getNetwork();
ASSERT_TRUE(deserialized != nullptr);
EXPECT_EQ(showFields.size(), deserialized->nconnections());
EXPECT_EQ(showFields.size() + 1, deserialized->nmodules());
EXPECT_NE(net.get(), deserialized.get());
}
|
Fix serialization tests
|
Fix serialization tests
|
C++
|
mit
|
collint8/SCIRun,jcollfont/SCIRun,jessdtate/SCIRun,moritzdannhauer/SCIRunGUIPrototype,ajanson/SCIRun,jessdtate/SCIRun,jessdtate/SCIRun,moritzdannhauer/SCIRunGUIPrototype,jcollfont/SCIRun,jessdtate/SCIRun,jcollfont/SCIRun,jcollfont/SCIRun,moritzdannhauer/SCIRunGUIPrototype,collint8/SCIRun,collint8/SCIRun,jessdtate/SCIRun,jessdtate/SCIRun,collint8/SCIRun,ajanson/SCIRun,ajanson/SCIRun,moritzdannhauer/SCIRunGUIPrototype,ajanson/SCIRun,ajanson/SCIRun,collint8/SCIRun,moritzdannhauer/SCIRunGUIPrototype,jcollfont/SCIRun,collint8/SCIRun,collint8/SCIRun,moritzdannhauer/SCIRunGUIPrototype,jessdtate/SCIRun,ajanson/SCIRun,collint8/SCIRun,jcollfont/SCIRun,ajanson/SCIRun,jessdtate/SCIRun,jcollfont/SCIRun,moritzdannhauer/SCIRunGUIPrototype
|
6902d9220c7ba8b26230031c13612c567bbe22fc
|
tools/driver/swift_format_main.cpp
|
tools/driver/swift_format_main.cpp
|
//===--- swift_format_main.cpp - Swift code formatting tool ---------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Formats Swift files or file ranges according to a set of parameters.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/DiagnosticsFrontend.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Frontend/Frontend.h"
#include "swift/Frontend/PrintingDiagnosticConsumer.h"
#include "swift/IDE/Formatting.h"
#include "swift/Option/Options.h"
#include "swift/Subsystems.h"
#include "clang/Format/Format.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include <string>
#include <vector>
using namespace swift;
using namespace swift::ide;
using namespace llvm::opt;
class FormatterDocument {
private:
SourceManager SM;
unsigned BufferID;
CompilerInvocation CompInv;
std::unique_ptr<ParserUnit> Parser;
class FormatterDiagConsumer : public swift::DiagnosticConsumer {
void handleDiagnostic(SourceManager &SM, SourceLoc Loc, DiagnosticKind Kind,
StringRef Text,
const swift::DiagnosticInfo &Info) override {
llvm::errs() << "Parse error: " << Text << "\n";
}
} DiagConsumer;
public:
FormatterDocument(std::unique_ptr<llvm::MemoryBuffer> Buffer) {
updateCode(std::move(Buffer));
}
void updateCode(std::unique_ptr<llvm::MemoryBuffer> Buffer) {
BufferID = SM.addNewSourceBuffer(std::move(Buffer));
Parser.reset(new ParserUnit(SM, BufferID, CompInv.getLangOptions(),
CompInv.getModuleName()));
Parser->getDiagnosticEngine().addConsumer(DiagConsumer);
auto &P = Parser->getParser();
for (bool Done = false; !Done; Done = P.Tok.is(tok::eof)) {
P.parseTopLevel();
}
}
std::pair<LineRange, std::string> reformat(LineRange Range,
CodeFormatOptions Options) {
return ::reformat(Range, Options, SM, Parser->getSourceFile());
}
const llvm::MemoryBuffer &memBuffer() const {
return *SM.getLLVMSourceMgr().getMemoryBuffer(BufferID);
}
};
class SwiftFormatInvocation {
private:
std::string MainExecutablePath;
std::string OutputFilename = "-";
std::vector<std::string> InputFilenames;
bool UseTabs = false;
bool InPlace = false;
unsigned TabWidth = 4;
unsigned IndentWidth = 4;
std::vector<std::string> LineRanges;
bool parseLineRange(StringRef Input, unsigned &FromLine, unsigned &ToLine) {
std::pair<StringRef, StringRef> LineRange = Input.split(":");
return LineRange.first.getAsInteger(0, FromLine) ||
LineRange.second.getAsInteger(0, ToLine);
}
public:
void setMainExecutablePath(const std::string &Path) {
MainExecutablePath = Path;
}
const std::string &getOutputFilename() { return OutputFilename; }
const std::vector<std::string> &getInputFilenames() { return InputFilenames; }
const std::vector<std::string> &getLineRanges() { return LineRanges; }
int parseArgs(ArrayRef<const char *> Args, DiagnosticEngine &Diags) {
using namespace options;
std::unique_ptr<llvm::opt::OptTable> Table = createSwiftOptTable();
unsigned MissingIndex;
unsigned MissingCount;
llvm::opt::InputArgList ParsedArgs =
Table->ParseArgs(Args, MissingIndex, MissingCount, SwiftFormatOption);
if (MissingCount) {
Diags.diagnose(SourceLoc(), diag::error_missing_arg_value,
ParsedArgs.getArgString(MissingIndex), MissingCount);
return 1;
}
if (ParsedArgs.getLastArg(OPT_use_tabs))
UseTabs = true;
if (ParsedArgs.getLastArg(OPT_inplace))
InPlace = true;
if (const Arg *A = ParsedArgs.getLastArg(OPT_tab_width))
if (StringRef(A->getValue()).getAsInteger(10, TabWidth))
Diags.diagnose(SourceLoc(), diag::error_invalid_arg_value,
A->getAsString(ParsedArgs), A->getValue());
if (const Arg *A = ParsedArgs.getLastArg(OPT_indent_width))
if (StringRef(A->getValue()).getAsInteger(10, IndentWidth))
Diags.diagnose(SourceLoc(), diag::error_invalid_arg_value,
A->getAsString(ParsedArgs), A->getValue());
for (const Arg *A : make_range(ParsedArgs.filtered_begin(OPT_line_ranges),
ParsedArgs.filtered_end()))
LineRanges.push_back(A->getValue());
if (ParsedArgs.hasArg(OPT_UNKNOWN)) {
for (const Arg *A : make_range(ParsedArgs.filtered_begin(OPT_UNKNOWN),
ParsedArgs.filtered_end())) {
Diags.diagnose(SourceLoc(), diag::error_unknown_arg,
A->getAsString(ParsedArgs));
}
return true;
}
if (ParsedArgs.getLastArg(OPT_help)) {
std::string ExecutableName = llvm::sys::path::stem(MainExecutablePath);
Table->PrintHelp(llvm::outs(), ExecutableName.c_str(),
"Swift Format Tool", options::SwiftFormatOption, 0);
return 1;
}
for (const Arg *A : make_range(ParsedArgs.filtered_begin(OPT_INPUT),
ParsedArgs.filtered_end())) {
InputFilenames.push_back(A->getValue());
}
if (InputFilenames.empty()) {
Diags.diagnose(SourceLoc(), diag::error_mode_requires_an_input_file);
return 1;
}
if (const Arg *A = ParsedArgs.getLastArg(OPT_o)) {
OutputFilename = A->getValue();
}
return 0;
}
/// Formats a filename and returns false if successful, true otherwise.
bool format(StringRef Filename, DiagnosticEngine &Diags) {
auto ErrOrBuf = llvm::MemoryBuffer::getFileOrSTDIN(Filename);
if (!ErrOrBuf) {
Diags.diagnose(SourceLoc(), diag::error_no_such_file_or_directory,
Filename);
return true;
}
std::unique_ptr<llvm::MemoryBuffer> Code = std::move(ErrOrBuf.get());
if (Code->getBufferSize() == 0) {
// Assume empty files are formatted successfully.
return false;
}
FormatterDocument Doc(std::move(Code));
if (LineRanges.empty()) {
LineRanges.push_back("1:9999999");
}
std::string Output = Doc.memBuffer().getBuffer();
clang::tooling::Replacements Replacements;
for (unsigned Range = 0; Range < LineRanges.size(); ++Range) {
unsigned FromLine;
unsigned ToLine;
if (parseLineRange(LineRanges[Range], FromLine, ToLine)) {
Diags.diagnose(SourceLoc(), diag::error_formatting_invalid_range);
return true;
}
if (FromLine > ToLine) {
Diags.diagnose(SourceLoc(), diag::error_formatting_invalid_range);
return true;
}
for (unsigned Line = FromLine; Line <= ToLine; ++Line) {
size_t Offset = getOffsetOfLine(Line, Output);
ssize_t Length = getOffsetOfLine(Line + 1, Output) - 1 - Offset;
if (Length < 0)
break;
CodeFormatOptions FormatOptions;
FormatOptions.UseTabs = UseTabs;
FormatOptions.IndentWidth = IndentWidth;
FormatOptions.TabWidth = TabWidth;
std::string Formatted =
Doc.reformat(LineRange(Line, 1), FormatOptions).second;
if (Formatted.find_first_not_of(" \t\v\f", 0) == StringRef::npos)
Formatted = "";
if (Formatted == Output.substr(Offset, Length))
continue;
Output.replace(Offset, Length, Formatted);
Doc.updateCode(llvm::MemoryBuffer::getMemBuffer(Output));
Replacements.insert(
clang::tooling::Replacement(Filename, Offset, Length, Formatted));
}
if (Filename == "-" || (!InPlace && OutputFilename == "-")) {
llvm::outs() << Output;
return false;
}
std::error_code EC;
StringRef Destination;
if (InPlace)
Destination = Filename;
else
Destination = OutputFilename;
llvm::raw_fd_ostream out(Destination, EC, llvm::sys::fs::F_None);
if (out.has_error() || EC) {
Diags.diagnose(SourceLoc(), diag::error_opening_output, Filename,
EC.message());
out.clear_error();
return true;
}
out << Output;
}
return false;
}
};
int swift_format_main(ArrayRef<const char *> Args, const char *Argv0,
void *MainAddr) {
CompilerInstance Instance;
PrintingDiagnosticConsumer PDC;
Instance.addDiagnosticConsumer(&PDC);
SwiftFormatInvocation Invocation;
std::string MainExecutablePath =
llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
Invocation.setMainExecutablePath(MainExecutablePath);
DiagnosticEngine &Diags = Instance.getDiags();
if (Invocation.parseArgs(Args, Diags) != 0)
return 1;
std::vector<std::string> InputFiles = Invocation.getInputFilenames();
unsigned NumInputFiles = InputFiles.size();
if (NumInputFiles == 0) {
// Read source code from standard input.
Invocation.format("-", Diags);
} else if (NumInputFiles == 1) {
Invocation.format(InputFiles[0], Diags);
} else {
if (!Invocation.getLineRanges().empty()) {
// We don't support formatting file ranges for multiple files.
Instance.getDiags().diagnose(SourceLoc(),
diag::error_formatting_multiple_file_ranges);
return 1;
}
for (unsigned i = 0; i < NumInputFiles; ++i)
Invocation.format(InputFiles[i], Diags);
}
return 0;
}
|
//===--- swift_format_main.cpp - Swift code formatting tool ---------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Formats Swift files or file ranges according to a set of parameters.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/DiagnosticsFrontend.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Frontend/Frontend.h"
#include "swift/Frontend/PrintingDiagnosticConsumer.h"
#include "swift/IDE/Formatting.h"
#include "swift/Option/Options.h"
#include "swift/Subsystems.h"
#include "clang/Format/Format.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/Option.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include <string>
#include <vector>
using namespace swift;
using namespace swift::ide;
using namespace llvm::opt;
class FormatterDocument {
private:
SourceManager SM;
unsigned BufferID;
CompilerInvocation CompInv;
std::unique_ptr<ParserUnit> Parser;
class FormatterDiagConsumer : public swift::DiagnosticConsumer {
void handleDiagnostic(SourceManager &SM, SourceLoc Loc, DiagnosticKind Kind,
StringRef Text,
const swift::DiagnosticInfo &Info) override {
llvm::errs() << "Parse error: " << Text << "\n";
}
} DiagConsumer;
public:
FormatterDocument(std::unique_ptr<llvm::MemoryBuffer> Buffer) {
updateCode(std::move(Buffer));
}
void updateCode(std::unique_ptr<llvm::MemoryBuffer> Buffer) {
BufferID = SM.addNewSourceBuffer(std::move(Buffer));
Parser.reset(new ParserUnit(SM, BufferID, CompInv.getLangOptions(),
CompInv.getModuleName()));
Parser->getDiagnosticEngine().addConsumer(DiagConsumer);
auto &P = Parser->getParser();
for (bool Done = false; !Done; Done = P.Tok.is(tok::eof)) {
P.parseTopLevel();
}
}
std::pair<LineRange, std::string> reformat(LineRange Range,
CodeFormatOptions Options) {
return ::reformat(Range, Options, SM, Parser->getSourceFile());
}
const llvm::MemoryBuffer &memBuffer() const {
return *SM.getLLVMSourceMgr().getMemoryBuffer(BufferID);
}
};
class SwiftFormatInvocation {
private:
std::string MainExecutablePath;
std::string OutputFilename = "-";
std::vector<std::string> InputFilenames;
bool UseTabs = false;
bool InPlace = false;
unsigned TabWidth = 4;
unsigned IndentWidth = 4;
std::vector<std::string> LineRanges;
bool parseLineRange(StringRef Input, unsigned &FromLine, unsigned &ToLine) {
std::pair<StringRef, StringRef> LineRange = Input.split(":");
return LineRange.first.getAsInteger(0, FromLine) ||
LineRange.second.getAsInteger(0, ToLine);
}
public:
void setMainExecutablePath(const std::string &Path) {
MainExecutablePath = Path;
}
const std::string &getOutputFilename() { return OutputFilename; }
const std::vector<std::string> &getInputFilenames() { return InputFilenames; }
const std::vector<std::string> &getLineRanges() { return LineRanges; }
int parseArgs(ArrayRef<const char *> Args, DiagnosticEngine &Diags) {
using namespace options;
std::unique_ptr<llvm::opt::OptTable> Table = createSwiftOptTable();
unsigned MissingIndex;
unsigned MissingCount;
llvm::opt::InputArgList ParsedArgs =
Table->ParseArgs(Args, MissingIndex, MissingCount, SwiftFormatOption);
if (MissingCount) {
Diags.diagnose(SourceLoc(), diag::error_missing_arg_value,
ParsedArgs.getArgString(MissingIndex), MissingCount);
return 1;
}
if (ParsedArgs.getLastArg(OPT_use_tabs))
UseTabs = true;
if (ParsedArgs.getLastArg(OPT_inplace))
InPlace = true;
if (const Arg *A = ParsedArgs.getLastArg(OPT_tab_width))
if (StringRef(A->getValue()).getAsInteger(10, TabWidth))
Diags.diagnose(SourceLoc(), diag::error_invalid_arg_value,
A->getAsString(ParsedArgs), A->getValue());
if (const Arg *A = ParsedArgs.getLastArg(OPT_indent_width))
if (StringRef(A->getValue()).getAsInteger(10, IndentWidth))
Diags.diagnose(SourceLoc(), diag::error_invalid_arg_value,
A->getAsString(ParsedArgs), A->getValue());
for (const Arg *A : make_range(ParsedArgs.filtered_begin(OPT_line_ranges),
ParsedArgs.filtered_end()))
LineRanges.push_back(A->getValue());
if (ParsedArgs.hasArg(OPT_UNKNOWN)) {
for (const Arg *A : make_range(ParsedArgs.filtered_begin(OPT_UNKNOWN),
ParsedArgs.filtered_end())) {
Diags.diagnose(SourceLoc(), diag::error_unknown_arg,
A->getAsString(ParsedArgs));
}
return true;
}
if (ParsedArgs.getLastArg(OPT_help)) {
std::string ExecutableName = llvm::sys::path::stem(MainExecutablePath);
Table->PrintHelp(llvm::outs(), ExecutableName.c_str(),
"Swift Format Tool", options::SwiftFormatOption, 0);
return 1;
}
for (const Arg *A : make_range(ParsedArgs.filtered_begin(OPT_INPUT),
ParsedArgs.filtered_end())) {
InputFilenames.push_back(A->getValue());
}
if (InputFilenames.empty()) {
Diags.diagnose(SourceLoc(), diag::error_mode_requires_an_input_file);
return 1;
}
if (const Arg *A = ParsedArgs.getLastArg(OPT_o)) {
OutputFilename = A->getValue();
}
return 0;
}
/// Formats a filename and returns false if successful, true otherwise.
bool format(StringRef Filename, DiagnosticEngine &Diags) {
auto ErrOrBuf = llvm::MemoryBuffer::getFileOrSTDIN(Filename);
if (!ErrOrBuf) {
Diags.diagnose(SourceLoc(), diag::error_no_such_file_or_directory,
Filename);
return true;
}
std::unique_ptr<llvm::MemoryBuffer> Code = std::move(ErrOrBuf.get());
if (Code->getBufferSize() == 0) {
// Assume empty files are formatted successfully.
return false;
}
FormatterDocument Doc(std::move(Code));
if (LineRanges.empty()) {
LineRanges.push_back("1:" + std::to_string(UINT_MAX));
}
std::string Output = Doc.memBuffer().getBuffer();
clang::tooling::Replacements Replacements;
for (unsigned Range = 0; Range < LineRanges.size(); ++Range) {
unsigned FromLine;
unsigned ToLine;
if (parseLineRange(LineRanges[Range], FromLine, ToLine)) {
Diags.diagnose(SourceLoc(), diag::error_formatting_invalid_range);
return true;
}
if (FromLine > ToLine) {
Diags.diagnose(SourceLoc(), diag::error_formatting_invalid_range);
return true;
}
for (unsigned Line = FromLine; Line <= ToLine; ++Line) {
size_t Offset = getOffsetOfLine(Line, Output);
ssize_t Length = getOffsetOfLine(Line + 1, Output) - 1 - Offset;
if (Length < 0)
break;
CodeFormatOptions FormatOptions;
FormatOptions.UseTabs = UseTabs;
FormatOptions.IndentWidth = IndentWidth;
FormatOptions.TabWidth = TabWidth;
std::string Formatted =
Doc.reformat(LineRange(Line, 1), FormatOptions).second;
if (Formatted.find_first_not_of(" \t\v\f", 0) == StringRef::npos)
Formatted = "";
if (Formatted == Output.substr(Offset, Length))
continue;
Output.replace(Offset, Length, Formatted);
Doc.updateCode(llvm::MemoryBuffer::getMemBuffer(Output));
Replacements.insert(
clang::tooling::Replacement(Filename, Offset, Length, Formatted));
}
if (Filename == "-" || (!InPlace && OutputFilename == "-")) {
llvm::outs() << Output;
return false;
}
std::error_code EC;
StringRef Destination;
if (InPlace)
Destination = Filename;
else
Destination = OutputFilename;
llvm::raw_fd_ostream out(Destination, EC, llvm::sys::fs::F_None);
if (out.has_error() || EC) {
Diags.diagnose(SourceLoc(), diag::error_opening_output, Filename,
EC.message());
out.clear_error();
return true;
}
out << Output;
}
return false;
}
};
int swift_format_main(ArrayRef<const char *> Args, const char *Argv0,
void *MainAddr) {
CompilerInstance Instance;
PrintingDiagnosticConsumer PDC;
Instance.addDiagnosticConsumer(&PDC);
SwiftFormatInvocation Invocation;
std::string MainExecutablePath =
llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
Invocation.setMainExecutablePath(MainExecutablePath);
DiagnosticEngine &Diags = Instance.getDiags();
if (Invocation.parseArgs(Args, Diags) != 0)
return 1;
std::vector<std::string> InputFiles = Invocation.getInputFilenames();
unsigned NumInputFiles = InputFiles.size();
if (NumInputFiles == 0) {
// Read source code from standard input.
Invocation.format("-", Diags);
} else if (NumInputFiles == 1) {
Invocation.format(InputFiles[0], Diags);
} else {
if (!Invocation.getLineRanges().empty()) {
// We don't support formatting file ranges for multiple files.
Instance.getDiags().diagnose(SourceLoc(),
diag::error_formatting_multiple_file_ranges);
return 1;
}
for (unsigned i = 0; i < NumInputFiles; ++i)
Invocation.format(InputFiles[i], Diags);
}
return 0;
}
|
Use UINT_MAX instead of a "magic" upper bound
|
Use UINT_MAX instead of a "magic" upper bound
If a line range is not set, create a line range over the unsigned type,
instead of setting an arbitrary limit. We're not probably going to ever
deal with such big files, though.
|
C++
|
apache-2.0
|
frootloops/swift,huonw/swift,IngmarStein/swift,bitjammer/swift,jmgc/swift,jopamer/swift,roambotics/swift,gregomni/swift,uasys/swift,apple/swift,xwu/swift,stephentyrone/swift,shahmishal/swift,tardieu/swift,karwa/swift,stephentyrone/swift,harlanhaskins/swift,aschwaighofer/swift,jtbandes/swift,austinzheng/swift,karwa/swift,deyton/swift,nathawes/swift,tjw/swift,huonw/swift,lorentey/swift,bitjammer/swift,IngmarStein/swift,xedin/swift,practicalswift/swift,IngmarStein/swift,jtbandes/swift,JGiola/swift,aschwaighofer/swift,amraboelela/swift,parkera/swift,tjw/swift,nathawes/swift,gribozavr/swift,modocache/swift,codestergit/swift,amraboelela/swift,karwa/swift,gregomni/swift,uasys/swift,sschiau/swift,Jnosh/swift,codestergit/swift,brentdax/swift,codestergit/swift,glessard/swift,kstaring/swift,felix91gr/swift,swiftix/swift,ben-ng/swift,danielmartin/swift,gottesmm/swift,atrick/swift,return/swift,tardieu/swift,arvedviehweger/swift,djwbrown/swift,tkremenek/swift,gribozavr/swift,return/swift,gribozavr/swift,alblue/swift,djwbrown/swift,frootloops/swift,deyton/swift,natecook1000/swift,roambotics/swift,codestergit/swift,nathawes/swift,Jnosh/swift,CodaFi/swift,therealbnut/swift,natecook1000/swift,deyton/swift,frootloops/swift,tardieu/swift,brentdax/swift,gribozavr/swift,kstaring/swift,calebd/swift,aschwaighofer/swift,uasys/swift,natecook1000/swift,frootloops/swift,practicalswift/swift,apple/swift,apple/swift,hooman/swift,allevato/swift,JaSpa/swift,milseman/swift,nathawes/swift,deyton/swift,tjw/swift,JaSpa/swift,shahmishal/swift,airspeedswift/swift,rudkx/swift,alblue/swift,karwa/swift,CodaFi/swift,tjw/swift,swiftix/swift,return/swift,jtbandes/swift,JGiola/swift,danielmartin/swift,gmilos/swift,swiftix/swift,gottesmm/swift,djwbrown/swift,xedin/swift,gottesmm/swift,return/swift,arvedviehweger/swift,bitjammer/swift,sschiau/swift,uasys/swift,gribozavr/swift,kstaring/swift,JGiola/swift,zisko/swift,tinysun212/swift-windows,brentdax/swift,modocache/swift,ben-ng/swift,alblue/swift,nathawes/swift,xwu/swift,airspeedswift/swift,xedin/swift,frootloops/swift,aschwaighofer/swift,tinysun212/swift-windows,deyton/swift,shahmishal/swift,allevato/swift,shahmishal/swift,rudkx/swift,bitjammer/swift,benlangmuir/swift,xedin/swift,benlangmuir/swift,deyton/swift,gottesmm/swift,harlanhaskins/swift,IngmarStein/swift,shahmishal/swift,glessard/swift,practicalswift/swift,milseman/swift,manavgabhawala/swift,brentdax/swift,tkremenek/swift,tinysun212/swift-windows,CodaFi/swift,djwbrown/swift,hughbe/swift,airspeedswift/swift,kstaring/swift,JGiola/swift,xwu/swift,milseman/swift,modocache/swift,kstaring/swift,lorentey/swift,JaSpa/swift,kstaring/swift,hooman/swift,OscarSwanros/swift,swiftix/swift,devincoughlin/swift,calebd/swift,sschiau/swift,therealbnut/swift,arvedviehweger/swift,tardieu/swift,ben-ng/swift,hughbe/swift,CodaFi/swift,JaSpa/swift,tardieu/swift,shahmishal/swift,jckarter/swift,allevato/swift,shajrawi/swift,arvedviehweger/swift,devincoughlin/swift,parkera/swift,jopamer/swift,felix91gr/swift,tkremenek/swift,xwu/swift,manavgabhawala/swift,milseman/swift,codestergit/swift,atrick/swift,danielmartin/swift,karwa/swift,deyton/swift,frootloops/swift,gmilos/swift,ben-ng/swift,stephentyrone/swift,uasys/swift,harlanhaskins/swift,jmgc/swift,austinzheng/swift,roambotics/swift,zisko/swift,JaSpa/swift,calebd/swift,practicalswift/swift,roambotics/swift,ahoppen/swift,milseman/swift,hughbe/swift,xedin/swift,tkremenek/swift,arvedviehweger/swift,atrick/swift,xwu/swift,ahoppen/swift,airspeedswift/swift,Jnosh/swift,parkera/swift,arvedviehweger/swift,felix91gr/swift,hughbe/swift,jopamer/swift,jmgc/swift,calebd/swift,gribozavr/swift,jmgc/swift,huonw/swift,kstaring/swift,IngmarStein/swift,amraboelela/swift,gregomni/swift,jckarter/swift,therealbnut/swift,hooman/swift,jckarter/swift,jmgc/swift,devincoughlin/swift,OscarSwanros/swift,JGiola/swift,Jnosh/swift,huonw/swift,tjw/swift,apple/swift,huonw/swift,gottesmm/swift,stephentyrone/swift,modocache/swift,roambotics/swift,rudkx/swift,gribozavr/swift,modocache/swift,gribozavr/swift,tjw/swift,amraboelela/swift,hooman/swift,austinzheng/swift,ahoppen/swift,OscarSwanros/swift,jtbandes/swift,atrick/swift,JGiola/swift,hughbe/swift,therealbnut/swift,harlanhaskins/swift,aschwaighofer/swift,lorentey/swift,devincoughlin/swift,felix91gr/swift,nathawes/swift,parkera/swift,modocache/swift,jckarter/swift,IngmarStein/swift,rudkx/swift,alblue/swift,OscarSwanros/swift,manavgabhawala/swift,jopamer/swift,gmilos/swift,harlanhaskins/swift,huonw/swift,calebd/swift,xwu/swift,therealbnut/swift,jmgc/swift,milseman/swift,tardieu/swift,apple/swift,codestergit/swift,gregomni/swift,CodaFi/swift,glessard/swift,practicalswift/swift,roambotics/swift,gmilos/swift,zisko/swift,austinzheng/swift,sschiau/swift,shahmishal/swift,apple/swift,jtbandes/swift,glessard/swift,OscarSwanros/swift,xedin/swift,CodaFi/swift,karwa/swift,parkera/swift,shajrawi/swift,practicalswift/swift,jtbandes/swift,gottesmm/swift,gregomni/swift,jopamer/swift,natecook1000/swift,benlangmuir/swift,tkremenek/swift,alblue/swift,zisko/swift,tinysun212/swift-windows,airspeedswift/swift,tinysun212/swift-windows,austinzheng/swift,nathawes/swift,jtbandes/swift,JaSpa/swift,karwa/swift,shajrawi/swift,parkera/swift,Jnosh/swift,frootloops/swift,sschiau/swift,stephentyrone/swift,atrick/swift,danielmartin/swift,shahmishal/swift,calebd/swift,amraboelela/swift,shajrawi/swift,calebd/swift,milseman/swift,IngmarStein/swift,ahoppen/swift,benlangmuir/swift,huonw/swift,return/swift,shajrawi/swift,aschwaighofer/swift,danielmartin/swift,hughbe/swift,arvedviehweger/swift,swiftix/swift,swiftix/swift,zisko/swift,lorentey/swift,hooman/swift,danielmartin/swift,kperryua/swift,swiftix/swift,devincoughlin/swift,bitjammer/swift,lorentey/swift,return/swift,xwu/swift,felix91gr/swift,gmilos/swift,tinysun212/swift-windows,ahoppen/swift,ben-ng/swift,airspeedswift/swift,hughbe/swift,djwbrown/swift,tkremenek/swift,tjw/swift,kperryua/swift,harlanhaskins/swift,parkera/swift,allevato/swift,natecook1000/swift,stephentyrone/swift,kperryua/swift,brentdax/swift,OscarSwanros/swift,brentdax/swift,uasys/swift,shajrawi/swift,ben-ng/swift,jckarter/swift,xedin/swift,CodaFi/swift,glessard/swift,devincoughlin/swift,bitjammer/swift,practicalswift/swift,aschwaighofer/swift,therealbnut/swift,jopamer/swift,sschiau/swift,atrick/swift,manavgabhawala/swift,manavgabhawala/swift,amraboelela/swift,alblue/swift,ahoppen/swift,shajrawi/swift,sschiau/swift,jopamer/swift,kperryua/swift,allevato/swift,shajrawi/swift,tardieu/swift,stephentyrone/swift,lorentey/swift,alblue/swift,devincoughlin/swift,hooman/swift,return/swift,jckarter/swift,sschiau/swift,therealbnut/swift,gmilos/swift,allevato/swift,rudkx/swift,Jnosh/swift,parkera/swift,lorentey/swift,kperryua/swift,gregomni/swift,tinysun212/swift-windows,zisko/swift,lorentey/swift,devincoughlin/swift,bitjammer/swift,djwbrown/swift,kperryua/swift,gottesmm/swift,benlangmuir/swift,natecook1000/swift,natecook1000/swift,airspeedswift/swift,benlangmuir/swift,allevato/swift,rudkx/swift,danielmartin/swift,austinzheng/swift,austinzheng/swift,felix91gr/swift,jckarter/swift,felix91gr/swift,manavgabhawala/swift,Jnosh/swift,amraboelela/swift,kperryua/swift,hooman/swift,OscarSwanros/swift,xedin/swift,practicalswift/swift,zisko/swift,manavgabhawala/swift,codestergit/swift,gmilos/swift,karwa/swift,glessard/swift,djwbrown/swift,harlanhaskins/swift,uasys/swift,tkremenek/swift,ben-ng/swift,jmgc/swift,brentdax/swift,modocache/swift,JaSpa/swift
|
3f4963bae6821005c0d355587e43ca17512e5a3b
|
src/import/chips/p9/procedures/hwp/io/p9_io_erepairAccessorHwpFuncs.H
|
src/import/chips/p9/procedures/hwp/io/p9_io_erepairAccessorHwpFuncs.H
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_erepairAccessorHwpFuncs.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2017 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_io_erepairAccessorHwpFuncs.H
/// @brief FW Team utility functions that access fabric and memory eRepair data.
///
//----------------------------------------------------------------------------
#ifndef P9_IO_EREPAIRACCESSORHWPFUNCS_H_
#define P9_IO_EREPAIRACCESSORHWPFUNCS_H_
#include <fapi2.H>
#include <algorithm>
const uint8_t EREPAIR_MAX_CENTAUR_PER_MCS = 1;
typedef fapi2::ReturnCode (*getLanes_t)(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS |
fapi2::TARGET_TYPE_OBUS |
fapi2::TARGET_TYPE_MEMBUF_CHIP |
fapi2::TARGET_TYPE_MCS_CHIPLET |
fapi2::TARGET_TYPE_MCS > &i_tgtHandle,
const uint8_t i_clkGroup,
std::vector<uint8_t>& o_txFailLanes,
std::vector<uint8_t>& o_rxFailLanes);
typedef fapi2::ReturnCode (*setLanes_t)(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS |
fapi2::TARGET_TYPE_OBUS |
fapi2::TARGET_TYPE_MEMBUF_CHIP |
fapi2::TARGET_TYPE_MCS_CHIPLET |
fapi2::TARGET_TYPE_MCS > &i_tgtHandle,
const uint8_t i_clkGroup,
const std::vector<uint8_t>& i_txFailLanes,
const std::vector<uint8_t>& i_rxFailLanes);
/**
* @brief FW Team Utility function that gets eRepair data from the VPD
* This function gets the eRepair data from both the Field VPD
* and the Manufacturing VPD.
*
* @param[in] i_endp_target Reference to X-Bus or O-Bus or MCS or memBuf Target
* @param[in] i_clkGroup Specifies clock group 0:[XOA, X1A,..] 1:[X0B, X1B,..]
* @param[out] o_txFailLanes Reference to a Vector that will contain the fail
* lanes read from the VPD for Drive side
* @param[out] o_rxFailLanes Reference to a Vector that will contain the fail
* lanes read from the VPD for Receive side
* @return ReturnCode
*
*/
fapi2::ReturnCode erepairGetFailedLanes(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS |
fapi2::TARGET_TYPE_OBUS |
fapi2::TARGET_TYPE_MEMBUF_CHIP |
fapi2::TARGET_TYPE_MCS_CHIPLET |
fapi2::TARGET_TYPE_MCS > &i_endp_target,
const uint8_t i_clkGroup,
std::vector<uint8_t>& o_txFailLanes,
std::vector<uint8_t>& o_rxFailLanes);
/**
* @brief FW Team Utility function that gets eRepair data
*
* This is a wrapper function for the Accessor HWP which reads failed lane
* numbers from the Field VPD
*
* @param[in] i_endp_target Reference to X-Bus or O-Bus or MCS or memBuf Target
* @param[in] i_clkGroup Specifies clock group 0:[XOA, X1A,..] 1:[X0B, X1B,..]
* @param[out] o_txFailLanes Reference to a Vector that will contain the fail
* lanes read from the Field VPD for Drive side
* @param[out] o_rxFailLanes Reference to a Vector that will contain the fail
* lanes read from the Field VPD for Receive side
* @return ReturnCode
*
*/
fapi2::ReturnCode erepairGetFieldFailedLanes(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS |
fapi2::TARGET_TYPE_OBUS |
fapi2::TARGET_TYPE_MEMBUF_CHIP |
fapi2::TARGET_TYPE_MCS_CHIPLET |
fapi2::TARGET_TYPE_MCS > &i_endp_target,
const uint8_t i_clkGroup,
std::vector<uint8_t>& o_txFailLanes,
std::vector<uint8_t>& o_rxFailLanes);
/**
* @brief FW Team Utility function that gets eRepair data
*
* This is a wrapper function for the Accessor HWP which reads failed lane
* numbers from the Manufacturing VPD
*
* @param[in] i_endp_target Reference to X-Bus or O-Bus or MCS or memBuf Target
* @param[in] i_clkGroup Specifies clock group 0:[XOA, X1A,..] 1:[X0B, X1B,..]
* @param[out] o_txFailLanes Reference to a Vector that will contain the fail
* lanes read from the Mnfg VPD for Drive side
* @param[out] o_rxFailLanes Reference to a Vector that will contain the fail
* lanes read from the Mnfg VPD for Receive side
* @return ReturnCode
*
*/
fapi2::ReturnCode erepairGetMnfgFailedLanes(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS |
fapi2::TARGET_TYPE_OBUS |
fapi2::TARGET_TYPE_MEMBUF_CHIP |
fapi2::TARGET_TYPE_MCS_CHIPLET |
fapi2::TARGET_TYPE_MCS > &i_endp_target,
const uint8_t i_clkGroup,
std::vector<uint8_t>& o_txFailLanes,
std::vector<uint8_t>& o_rxFailLanes);
/**
* @brief FW Team Utility function that sets eRepair data in the VPD.
* This functions sets the eRepair data to either the Field VPD
* or the Manufacturing VPD depending on whether the IPL was done
* in normal mode or Manufacturing mode.
* It writes eRepair data to the VPD of both the endpoint targets
* passed as arguments.
*
* @param[in] i_txEndp_target Reference to X-Bus or O-Bus or MCS or memBuf
* Target. This is the peer target of
* i_rxEndp_target
* @param[in] i_rxEndp_target Reference to X-Bus or O-Bus or MCS or memBuf
* Target. This is the target on which the
* badlanes were found
* @param[in] i_rxFailLanes Vector that will contain the fail lanes
* to be written to VPD for Receive side
* @param[in] i_clkGroup Specifies clock group 0:[XOA, X1A,..] 1:[X0B, X1B,..]
* @param[out] o_thresholdExceed If TRUE, indicates that the eRepair threshold
* has exceeded, FALSE otherwise.
*
* @return ReturnCode
*/
fapi2::ReturnCode erepairSetFailedLanes(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS |
fapi2::TARGET_TYPE_OBUS |
fapi2::TARGET_TYPE_MEMBUF_CHIP |
fapi2::TARGET_TYPE_MCS_CHIPLET |
fapi2::TARGET_TYPE_MCS > &i_txEndp_target,
const fapi2::Target < fapi2::TARGET_TYPE_XBUS |
fapi2::TARGET_TYPE_OBUS |
fapi2::TARGET_TYPE_MEMBUF_CHIP |
fapi2::TARGET_TYPE_MCS_CHIPLET |
fapi2::TARGET_TYPE_MCS > &i_rxEndp_target,
const std::vector<uint8_t>& i_rxFailLanes,
const uint8_t i_clkGroup,
bool& o_thresholdExceed);
/**
* @brief FW Team Utility function that sets eRepair data in Field VPD
*
* This is a wrapper function for the Accessor HWP which writes failed lane
* numbers to the Field VPD
*
* @param[in] i_endp_target Reference to X-Bus or O-Bus or MCS or memBuf Target
* @param[in] i_clkGroup Specifies clock group 0:[XOA, X1A,..] 1:[X0B, X1B,..]
* @param[in] i_txFailLanes Vector that will contain the fail lane
* to be written to Field VPD for Drive side
* @param[in] i_rxFailLanes Vector that will contain the fail lanes
* to be written to Field VPD for Receive side
*
* @return ReturnCode
*/
fapi2::ReturnCode erepairSetFieldFailedLanes(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS |
fapi2::TARGET_TYPE_OBUS |
fapi2::TARGET_TYPE_MEMBUF_CHIP |
fapi2::TARGET_TYPE_MCS_CHIPLET |
fapi2::TARGET_TYPE_MCS > &i_endp_target,
const uint8_t i_clkGroup,
const std::vector<uint8_t>& i_txFailLanes,
const std::vector<uint8_t>& i_rxFailLanes);
/**
* @brief FW Team Utility function that sets eRepair data in Manufacturing VPD
*
* This is a wrapper function for the Accessor HWP which writes failed lane
* numbers to the Manufacturing VPD
*
* @param[in] i_endp_target Reference to X-Bus or O-Bus or MCS or memBuf Target
* @param[in] i_clkGroup Specifies clock group 0:[XOA, X1A,..] 1:[X0B, X1B,..]
* @param[in] i_txFailLanes Vector that will contain the fail lane
* to be written to Mnfg VPD for Drive side
* @param[in] i_rxFailLanes Vector that will contain the fail lanes
* to be written to Mnfg VPD for Receive side
*
* @return ReturnCode
*/
fapi2::ReturnCode erepairSetMnfgFailedLanes(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS |
fapi2::TARGET_TYPE_OBUS |
fapi2::TARGET_TYPE_MEMBUF_CHIP |
fapi2::TARGET_TYPE_MCS_CHIPLET |
fapi2::TARGET_TYPE_MCS > &i_endp_target,
const uint8_t i_clkGroup,
const std::vector<uint8_t>& i_txFailLanes,
const std::vector<uint8_t>& i_rxFailLanes);
/**
* @brief Function which retrieves the lanes that need to be restored for the
* given end point targets
*
* This function is called by the iStep dispatcher during the Restore Repair
* iStep for Fabric buses and DMI buses. The caller need to make sure that the
* first and fourth arguments are the endpoint targets of a Fabric bus or
* DMI bus.
* It calls the wrapper functions of Accessor HWP to read the fail lane data
* recorded in the VPD on both the ends and verifies that there are matching
* records on both the ends. If matching fail lanes are not found, the
* corresponding fail lane data is invalidated using the wrapper Accessor HWP
* that writes data to the VPD.
*
* @param [in] i_endp1_target Reference to X-Bus or O-Bus or MCS Target
* @param [in] i_endp2_target Reference to X-Bus or O-Bus or MCS Target
* @param[in] i_clkGroup Specifies clock group 0:[XOA, X1A,..] 1:[X0B, X1B,..]
* @param [out] o_endp1_txFaillanes Reference to vector that will have the
* fail lane numbers that need to be restored
* for the Tx side of the target passed
* as first param
* @param [out] o_endp1_rxFaillanes Reference to vector that will have the
* fail lane numbers that need to be restored
* for the Rx side of the target passed
* as first param
* @param [out] o_endp2_txFaillanes Reference to vector that will have the
* fail lane numbers that need to be restored
* for the Tx side of the target passed
* as fourth param
* @param [out] o_endp2_rxFaillanes Reference to vector that will have the
* fail lane numbers that need to be restored
* for the Rx side of the target passed
* as fourth param
*
* @return ReturnCode
*
*/
fapi2::ReturnCode erepairGetRestoreLanes(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS |
fapi2::TARGET_TYPE_OBUS |
fapi2::TARGET_TYPE_MEMBUF_CHIP |
fapi2::TARGET_TYPE_MCS_CHIPLET |
fapi2::TARGET_TYPE_MCS > &i_endp1_target,
const fapi2::Target < fapi2::TARGET_TYPE_XBUS |
fapi2::TARGET_TYPE_OBUS |
fapi2::TARGET_TYPE_MEMBUF_CHIP |
fapi2::TARGET_TYPE_MCS_CHIPLET |
fapi2::TARGET_TYPE_MCS > &i_endp2_target,
const uint8_t i_clkGroup,
std::vector<uint8_t>& o_endp1_txFaillanes,
std::vector<uint8_t>& o_endp1_rxFaillanes,
std::vector<uint8_t>& o_endp2_txFaillanes,
std::vector<uint8_t>& o_endp2_rxFaillanes);
#endif
|
/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/io/p9_io_erepairAccessorHwpFuncs.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2017 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* 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. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_io_erepairAccessorHwpFuncs.H
/// @brief FW Team utility functions that access fabric and memory eRepair data.
///
//----------------------------------------------------------------------------
#ifndef P9_IO_EREPAIRACCESSORHWPFUNCS_H_
#define P9_IO_EREPAIRACCESSORHWPFUNCS_H_
#include <fapi2.H>
#include <algorithm>
const uint8_t EREPAIR_MAX_CENTAUR_PER_MCS = 1;
typedef fapi2::ReturnCode (*getLanes_t)(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS |
fapi2::TARGET_TYPE_OBUS |
fapi2::TARGET_TYPE_MEMBUF_CHIP |
fapi2::TARGET_TYPE_MCS_CHIPLET |
fapi2::TARGET_TYPE_MCS > &i_tgtHandle,
const uint8_t i_clkGroup,
std::vector<uint8_t>& o_txFailLanes,
std::vector<uint8_t>& o_rxFailLanes);
typedef fapi2::ReturnCode (*setLanes_t)(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS |
fapi2::TARGET_TYPE_OBUS |
fapi2::TARGET_TYPE_MEMBUF_CHIP |
fapi2::TARGET_TYPE_MCS_CHIPLET |
fapi2::TARGET_TYPE_MCS > &i_tgtHandle,
const uint8_t i_clkGroup,
const std::vector<uint8_t>& i_txFailLanes,
const std::vector<uint8_t>& i_rxFailLanes);
/**
* @brief FW Team Utility function that gets eRepair data from the VPD
* This function gets the eRepair data from both the Field VPD
* and the Manufacturing VPD.
*
* @param[in] i_endp_target Reference to X-Bus or O-Bus or MCS or memBuf Target
* @param[in] i_clkGroup Specifies clock group 0:[XOA, X1A,..] 1:[X0B, X1B,..]
* @param[out] o_txFailLanes Reference to a Vector that will contain the fail
* lanes read from the VPD for Drive side
* @param[out] o_rxFailLanes Reference to a Vector that will contain the fail
* lanes read from the VPD for Receive side
* @return ReturnCode
*
*/
fapi2::ReturnCode erepairGetFailedLanes(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS |
fapi2::TARGET_TYPE_OBUS |
fapi2::TARGET_TYPE_MEMBUF_CHIP |
fapi2::TARGET_TYPE_MCS_CHIPLET |
fapi2::TARGET_TYPE_MCS > &i_endp_target,
const uint8_t i_clkGroup,
std::vector<uint8_t>& o_txFailLanes,
std::vector<uint8_t>& o_rxFailLanes);
/**
* @brief FW Team Utility function that gets eRepair data
*
* This is a wrapper function for the Accessor HWP which reads failed lane
* numbers from the Field VPD
*
* @param[in] i_endp_target Reference to X-Bus or O-Bus or MCS or memBuf Target
* @param[in] i_clkGroup Specifies clock group 0:[XOA, X1A,..] 1:[X0B, X1B,..]
* @param[out] o_txFailLanes Reference to a Vector that will contain the fail
* lanes read from the Field VPD for Drive side
* @param[out] o_rxFailLanes Reference to a Vector that will contain the fail
* lanes read from the Field VPD for Receive side
* @return ReturnCode
*
*/
fapi2::ReturnCode erepairGetFieldFailedLanes(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS |
fapi2::TARGET_TYPE_OBUS |
fapi2::TARGET_TYPE_MEMBUF_CHIP |
fapi2::TARGET_TYPE_MCS_CHIPLET |
fapi2::TARGET_TYPE_MCS > &i_endp_target,
const uint8_t i_clkGroup,
std::vector<uint8_t>& o_txFailLanes,
std::vector<uint8_t>& o_rxFailLanes);
/**
* @brief FW Team Utility function that gets eRepair data
*
* This is a wrapper function for the Accessor HWP which reads failed lane
* numbers from the Manufacturing VPD
*
* @param[in] i_endp_target Reference to X-Bus or O-Bus or MCS or memBuf Target
* @param[in] i_clkGroup Specifies clock group 0:[XOA, X1A,..] 1:[X0B, X1B,..]
* @param[out] o_txFailLanes Reference to a Vector that will contain the fail
* lanes read from the Mnfg VPD for Drive side
* @param[out] o_rxFailLanes Reference to a Vector that will contain the fail
* lanes read from the Mnfg VPD for Receive side
* @return ReturnCode
*
*/
fapi2::ReturnCode erepairGetMnfgFailedLanes(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS |
fapi2::TARGET_TYPE_OBUS |
fapi2::TARGET_TYPE_MEMBUF_CHIP |
fapi2::TARGET_TYPE_MCS_CHIPLET |
fapi2::TARGET_TYPE_MCS > &i_endp_target,
const uint8_t i_clkGroup,
std::vector<uint8_t>& o_txFailLanes,
std::vector<uint8_t>& o_rxFailLanes);
/**
* @brief FW Team Utility function that sets eRepair data in the VPD.
* This functions sets the eRepair data to either the Field VPD
* or the Manufacturing VPD depending on whether the IPL was done
* in normal mode or Manufacturing mode.
* It writes eRepair data to the VPD of both the endpoint targets
* passed as arguments.
*
* @param[in] i_txEndp_target Reference to X-Bus or O-Bus or MCS or memBuf
* Target. This is the peer target of
* i_rxEndp_target
* @param[in] i_rxEndp_target Reference to X-Bus or O-Bus or MCS or memBuf
* Target. This is the target on which the
* badlanes were found
* @param[in] i_rxFailLanes Vector that will contain the fail lanes
* to be written to VPD for Receive side
* @param[in] i_clkGroup Specifies clock group 0:[XOA, X1A,..] 1:[X0B, X1B,..]
* @param[out] o_thresholdExceed If TRUE, indicates that the eRepair threshold
* has exceeded, FALSE otherwise.
*
* @return ReturnCode
*/
fapi2::ReturnCode erepairSetFailedLanes(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS |
fapi2::TARGET_TYPE_OBUS |
fapi2::TARGET_TYPE_MEMBUF_CHIP |
fapi2::TARGET_TYPE_MCS_CHIPLET |
fapi2::TARGET_TYPE_MCS > &i_txEndp_target,
const fapi2::Target < fapi2::TARGET_TYPE_XBUS |
fapi2::TARGET_TYPE_OBUS |
fapi2::TARGET_TYPE_MEMBUF_CHIP |
fapi2::TARGET_TYPE_MCS_CHIPLET |
fapi2::TARGET_TYPE_MCS > &i_rxEndp_target,
const uint8_t i_clkGroup,
const std::vector<uint8_t>& i_rxFailLanes,
bool& o_thresholdExceed);
/**
* @brief FW Team Utility function that sets eRepair data in Field VPD
*
* This is a wrapper function for the Accessor HWP which writes failed lane
* numbers to the Field VPD
*
* @param[in] i_endp_target Reference to X-Bus or O-Bus or MCS or memBuf Target
* @param[in] i_clkGroup Specifies clock group 0:[XOA, X1A,..] 1:[X0B, X1B,..]
* @param[in] i_txFailLanes Vector that will contain the fail lane
* to be written to Field VPD for Drive side
* @param[in] i_rxFailLanes Vector that will contain the fail lanes
* to be written to Field VPD for Receive side
*
* @return ReturnCode
*/
fapi2::ReturnCode erepairSetFieldFailedLanes(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS |
fapi2::TARGET_TYPE_OBUS |
fapi2::TARGET_TYPE_MEMBUF_CHIP |
fapi2::TARGET_TYPE_MCS_CHIPLET |
fapi2::TARGET_TYPE_MCS > &i_endp_target,
const uint8_t i_clkGroup,
const std::vector<uint8_t>& i_txFailLanes,
const std::vector<uint8_t>& i_rxFailLanes);
/**
* @brief FW Team Utility function that sets eRepair data in Manufacturing VPD
*
* This is a wrapper function for the Accessor HWP which writes failed lane
* numbers to the Manufacturing VPD
*
* @param[in] i_endp_target Reference to X-Bus or O-Bus or MCS or memBuf Target
* @param[in] i_clkGroup Specifies clock group 0:[XOA, X1A,..] 1:[X0B, X1B,..]
* @param[in] i_txFailLanes Vector that will contain the fail lane
* to be written to Mnfg VPD for Drive side
* @param[in] i_rxFailLanes Vector that will contain the fail lanes
* to be written to Mnfg VPD for Receive side
*
* @return ReturnCode
*/
fapi2::ReturnCode erepairSetMnfgFailedLanes(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS |
fapi2::TARGET_TYPE_OBUS |
fapi2::TARGET_TYPE_MEMBUF_CHIP |
fapi2::TARGET_TYPE_MCS_CHIPLET |
fapi2::TARGET_TYPE_MCS > &i_endp_target,
const uint8_t i_clkGroup,
const std::vector<uint8_t>& i_txFailLanes,
const std::vector<uint8_t>& i_rxFailLanes);
/**
* @brief Function which retrieves the lanes that need to be restored for the
* given end point targets
*
* This function is called by the iStep dispatcher during the Restore Repair
* iStep for Fabric buses and DMI buses. The caller need to make sure that the
* first and fourth arguments are the endpoint targets of a Fabric bus or
* DMI bus.
* It calls the wrapper functions of Accessor HWP to read the fail lane data
* recorded in the VPD on both the ends and verifies that there are matching
* records on both the ends. If matching fail lanes are not found, the
* corresponding fail lane data is invalidated using the wrapper Accessor HWP
* that writes data to the VPD.
*
* @param [in] i_endp1_target Reference to X-Bus or O-Bus or MCS Target
* @param [in] i_endp2_target Reference to X-Bus or O-Bus or MCS Target
* @param[in] i_clkGroup Specifies clock group 0:[XOA, X1A,..] 1:[X0B, X1B,..]
* @param [out] o_endp1_txFaillanes Reference to vector that will have the
* fail lane numbers that need to be restored
* for the Tx side of the target passed
* as first param
* @param [out] o_endp1_rxFaillanes Reference to vector that will have the
* fail lane numbers that need to be restored
* for the Rx side of the target passed
* as first param
* @param [out] o_endp2_txFaillanes Reference to vector that will have the
* fail lane numbers that need to be restored
* for the Tx side of the target passed
* as fourth param
* @param [out] o_endp2_rxFaillanes Reference to vector that will have the
* fail lane numbers that need to be restored
* for the Rx side of the target passed
* as fourth param
*
* @return ReturnCode
*
*/
fapi2::ReturnCode erepairGetRestoreLanes(
const fapi2::Target < fapi2::TARGET_TYPE_XBUS |
fapi2::TARGET_TYPE_OBUS |
fapi2::TARGET_TYPE_MEMBUF_CHIP |
fapi2::TARGET_TYPE_MCS_CHIPLET |
fapi2::TARGET_TYPE_MCS > &i_endp1_target,
const fapi2::Target < fapi2::TARGET_TYPE_XBUS |
fapi2::TARGET_TYPE_OBUS |
fapi2::TARGET_TYPE_MEMBUF_CHIP |
fapi2::TARGET_TYPE_MCS_CHIPLET |
fapi2::TARGET_TYPE_MCS > &i_endp2_target,
const uint8_t i_clkGroup,
std::vector<uint8_t>& o_endp1_txFaillanes,
std::vector<uint8_t>& o_endp1_rxFaillanes,
std::vector<uint8_t>& o_endp2_txFaillanes,
std::vector<uint8_t>& o_endp2_rxFaillanes);
#endif
|
Fix parameter order mismatch for erepairSetFailedLanes
|
Fix parameter order mismatch for erepairSetFailedLanes
Change-Id: I204e26740cf192ac161a4dfb6a1b8c45c0d1b25e
CQ:SW405469
Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/48558
Reviewed-by: Caleb N. Palmer <[email protected]>
Tested-by: FSP CI Jenkins <[email protected]>
Tested-by: Jenkins Server <[email protected]>
Tested-by: Hostboot CI <[email protected]>
Reviewed-by: Brian J. Stegmiller <[email protected]>
Reviewed-by: Zane C. Shelley <[email protected]>
Reviewed-by: Jennifer A. Stofer <[email protected]>
Reviewed-on: http://ralgit01.raleigh.ibm.com/gerrit1/48567
Reviewed-by: Hostboot Team <[email protected]>
Tested-by: Jenkins OP Build CI <[email protected]>
Tested-by: Jenkins OP HW <op-hw-jenkins+6963c9c00f6fe376c46a8e103faee5c9a2f9eaf2@us.ibm.com>
|
C++
|
apache-2.0
|
Over-enthusiastic/hostboot,Over-enthusiastic/hostboot,Over-enthusiastic/hostboot,Over-enthusiastic/hostboot,Over-enthusiastic/hostboot
|
c47b24138b77747556641b9b526c534abeda9434
|
protocols/oscar/liboscar/tasks/profiletask.cpp
|
protocols/oscar/liboscar/tasks/profiletask.cpp
|
/*
Kopete Oscar Protocol
profiletask.h - Update the user's profile on the server
Copyright (c) 2004 Matt Rogers <[email protected]>
Kopete (c) 2002-2004 by the Kopete developers <[email protected]>
*************************************************************************
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#include "profiletask.h"
#include <qstring.h>
#include <kdebug.h>
#include "transfer.h"
#include "connection.h"
#include "oscartypes.h"
#include "oscarutils.h"
using namespace Oscar;
ProfileTask::ProfileTask( Task* parent )
: Task( parent )
{
m_sendCaps = false;
m_xtrazStatus = -1;
}
ProfileTask::~ProfileTask()
{
}
bool ProfileTask::forMe( const Transfer* transfer ) const
{
Q_UNUSED( transfer );
return false;
}
bool ProfileTask::take( Transfer* transfer )
{
Q_UNUSED( transfer );
return false;
}
void ProfileTask::onGo()
{
sendProfileUpdate();
}
void ProfileTask::setProfileText( const QString& text )
{
m_profileText = text;
}
void ProfileTask::setAwayMessage( const QString& text )
{
m_awayMessage = text;
}
void ProfileTask::setXtrazStatus( int xtrazStatus )
{
if ( xtrazStatus < Oscar::XSTAT_LAST )
{
m_xtrazStatus = xtrazStatus;
m_sendCaps = true;
}
}
void ProfileTask::setCapabilities( bool value )
{
m_sendCaps = value;
}
void ProfileTask::sendProfileUpdate()
{
kDebug(OSCAR_RAW_DEBUG) << k_funcinfo << "SEND (CLI_SETUSERINFO/CLI_SET_LOCATION_INFO)";
FLAP f = { 0x02, 0, 0 };
SNAC s = { 0x0002, 0x0004, 0x0000, client()->snacSequence() };
Buffer *buffer = new Buffer();
if ( !m_profileText.isNull() )
{
static const QString defencoding = "text/aolrtf; charset=\"us-ascii\"";
buffer->addTLV(0x0001, defencoding.toLatin1());
buffer->addTLV(0x0002, m_profileText.toLocal8Bit());
kDebug(OSCAR_RAW_DEBUG) << k_funcinfo << "setting profile = " << m_profileText;
}
if ( !m_awayMessage.isNull() )
{
static const QString defencoding = "text/aolrtf; charset=\"us-ascii\"";
buffer->addTLV(0x0003, defencoding.toLatin1());
buffer->addTLV(0x0004, m_awayMessage.toLocal8Bit());
kDebug(OSCAR_RAW_DEBUG) << k_funcinfo << "setting away message = " << m_awayMessage;
}
if ( m_sendCaps )
{
Buffer capBuf;
if ( client()->isIcq() )
{
capBuf.addGuid( oscar_caps[CAP_ICQSERVERRELAY] ); // we support type-2 messages
capBuf.addGuid( oscar_caps[CAP_DIRECT_ICQ_COMMUNICATION] ); // we support direct communication
//capBuf.addGuid( oscar_caps[CAP_RTFMSGS] ); // we do incoming RTF messages
capBuf.addGuid( oscar_caps[CAP_NEWCAPS] ); // we understand the new format of caps (xtra status)
capBuf.addGuid( oscar_caps[CAP_XTRAZ] ); // we support xtraz
if ( m_xtrazStatus > -1 )
capBuf.addGuid( oscar_xStatus[m_xtrazStatus] ); // set xtraz status
}
capBuf.addGuid( oscar_caps[CAP_SENDFILE] ); // we can do filetransfers! :)
capBuf.addGuid( oscar_caps[CAP_UTF8] ); // we can send/receive UTF encoded messages
capBuf.addGuid( oscar_caps[CAP_KOPETE] ); // we are the borg, resistance is futile
capBuf.addGuid( oscar_caps[CAP_TYPING] ); // we know you're typing something to us!
capBuf.addGuid( oscar_caps[CAP_BUDDYICON] ); //can you take my picture?
capBuf.addGuid( oscar_caps[CAP_INTEROPERATE] ); //AIM can communicate with ICQ users and ICQ with AIM users.
kDebug(OSCAR_RAW_DEBUG) << k_funcinfo << "adding capabilities, size=" << capBuf.length();
buffer->addTLV(0x0005, capBuf.buffer());
}
Transfer* st = createTransfer( f, s , buffer );
send( st );
setSuccess( 0, QString() );
kDebug(OSCAR_RAW_DEBUG) << k_funcinfo << "done.";
}
//kate: tab-width 4; indent-mode csands;
|
/*
Kopete Oscar Protocol
profiletask.h - Update the user's profile on the server
Copyright (c) 2004 Matt Rogers <[email protected]>
Kopete (c) 2002-2004 by the Kopete developers <[email protected]>
*************************************************************************
* *
* This library is free software; you can redistribute it and/or *
* modify it under the terms of the GNU Lesser General Public *
* License as published by the Free Software Foundation; either *
* version 2 of the License, or (at your option) any later version. *
* *
*************************************************************************
*/
#include "profiletask.h"
#include <qstring.h>
#include <kdebug.h>
#include "kopeteversion.h"
#include "transfer.h"
#include "connection.h"
#include "oscartypes.h"
#include "oscarutils.h"
using namespace Oscar;
ProfileTask::ProfileTask( Task* parent )
: Task( parent )
{
m_sendCaps = false;
m_xtrazStatus = -1;
}
ProfileTask::~ProfileTask()
{
}
bool ProfileTask::forMe( const Transfer* transfer ) const
{
Q_UNUSED( transfer );
return false;
}
bool ProfileTask::take( Transfer* transfer )
{
Q_UNUSED( transfer );
return false;
}
void ProfileTask::onGo()
{
sendProfileUpdate();
}
void ProfileTask::setProfileText( const QString& text )
{
m_profileText = text;
}
void ProfileTask::setAwayMessage( const QString& text )
{
m_awayMessage = text;
}
void ProfileTask::setXtrazStatus( int xtrazStatus )
{
if ( xtrazStatus < Oscar::XSTAT_LAST )
{
m_xtrazStatus = xtrazStatus;
m_sendCaps = true;
}
}
void ProfileTask::setCapabilities( bool value )
{
m_sendCaps = value;
}
void ProfileTask::sendProfileUpdate()
{
kDebug(OSCAR_RAW_DEBUG) << k_funcinfo << "SEND (CLI_SETUSERINFO/CLI_SET_LOCATION_INFO)";
FLAP f = { 0x02, 0, 0 };
SNAC s = { 0x0002, 0x0004, 0x0000, client()->snacSequence() };
Buffer *buffer = new Buffer();
if ( !m_profileText.isNull() )
{
static const QString defencoding = "text/aolrtf; charset=\"us-ascii\"";
buffer->addTLV(0x0001, defencoding.toLatin1());
buffer->addTLV(0x0002, m_profileText.toLocal8Bit());
kDebug(OSCAR_RAW_DEBUG) << k_funcinfo << "setting profile = " << m_profileText;
}
if ( !m_awayMessage.isNull() )
{
static const QString defencoding = "text/aolrtf; charset=\"us-ascii\"";
buffer->addTLV(0x0003, defencoding.toLatin1());
buffer->addTLV(0x0004, m_awayMessage.toLocal8Bit());
kDebug(OSCAR_RAW_DEBUG) << k_funcinfo << "setting away message = " << m_awayMessage;
}
if ( m_sendCaps )
{
Buffer capBuf;
if ( client()->isIcq() )
{
capBuf.addGuid( oscar_caps[CAP_ICQSERVERRELAY] ); // we support type-2 messages
capBuf.addGuid( oscar_caps[CAP_DIRECT_ICQ_COMMUNICATION] ); // we support direct communication
//capBuf.addGuid( oscar_caps[CAP_RTFMSGS] ); // we do incoming RTF messages
capBuf.addGuid( oscar_caps[CAP_NEWCAPS] ); // we understand the new format of caps (xtra status)
capBuf.addGuid( oscar_caps[CAP_XTRAZ] ); // we support xtraz
if ( m_xtrazStatus > -1 )
capBuf.addGuid( oscar_xStatus[m_xtrazStatus] ); // set xtraz status
}
capBuf.addGuid( oscar_caps[CAP_SENDFILE] ); // we can do filetransfers! :)
capBuf.addGuid( oscar_caps[CAP_UTF8] ); // we can send/receive UTF encoded messages
// send version
QByteArray kg = oscar_caps[CAP_KOPETE].data();
kg[12] = KOPETE_VERSION_MAJOR;
kg[13] = KOPETE_VERSION_MINOR;
kg[14] = KOPETE_VERSION_RELEASE / 100;
kg[15] = KOPETE_VERSION_RELEASE % 100;
capBuf.addGuid( Guid(kg) );
capBuf.addGuid( oscar_caps[CAP_TYPING] ); // we know you're typing something to us!
capBuf.addGuid( oscar_caps[CAP_BUDDYICON] ); //can you take my picture?
capBuf.addGuid( oscar_caps[CAP_INTEROPERATE] ); //AIM can communicate with ICQ users and ICQ with AIM users.
kDebug(OSCAR_RAW_DEBUG) << k_funcinfo << "adding capabilities, size=" << capBuf.length();
buffer->addTLV(0x0005, capBuf.buffer());
}
Transfer* st = createTransfer( f, s , buffer );
send( st );
setSuccess( 0, QString() );
kDebug(OSCAR_RAW_DEBUG) << k_funcinfo << "done.";
}
//kate: tab-width 4; indent-mode csands;
|
Send real kopete version to others. We had 0.12.1 long time
|
Send real kopete version to others. We had 0.12.1 long time
svn path=/trunk/KDE/kdenetwork/kopete/; revision=698407
|
C++
|
lgpl-2.1
|
josh-wambua/kopete,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,josh-wambua/kopete,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,josh-wambua/kopete,josh-wambua/kopete,josh-wambua/kopete,josh-wambua/kopete,Jtalk/kopete-fork-xep0136,josh-wambua/kopete
|
1705545222f11367f1fa02758bcc153caff1065b
|
scan_file_task.cpp
|
scan_file_task.cpp
|
#include <QDebug>
#include <jansson.h>
#include "VtFile.h"
#include "VtResponse.h"
#include "qvtfile.h"
#include "vt-log.h"
#include "scan_file_task.h"
ScanFileTask::ScanFileTask(QVtFile *vt_file)
{
file = vt_file;
}
#define RESP_BUF_SIZE 255
static void progress_update(struct VtFile *vtfile, void *qfile)
{
QVtFile::ProgessUpdateCallback(vtfile, (QVtFile *) qfile);
}
//Scan for a file
void ScanFileTask::ScanSmallFile(void)
{
int ret;
struct VtFile *api = VtFile_new();
struct VtResponse *response;
char *str = NULL;
char buf[RESP_BUF_SIZE+1] = { 0, };
int response_code;
VtFile_setApiKey(api, file->GetApiKey().toStdString().c_str());
// VtFile_setProgressCallback(api, QVtFile::ProgessUpdateCallback, (void *)file);
VtFile_setProgressCallback(api, progress_update, (void *)file);
ret = VtFile_scan(api, file->fileName().toStdString().c_str());
if (ret) {
qDebug() << "Error opening fetching report " << QString(file->GetSha256().toHex()) << " " << ret;
file->SetState(kWaitForReport);
emit LogMsg(VT_LOG_ERR, ret, "Error fetching report");
} else {
response = VtFile_getResponse(api);
str = VtResponse_toJSONstr(response, VT_JSON_FLAG_INDENT);
if (str) {
qDebug() << "Scan Response: " << str;
free(str);
}
VtResponse_getVerboseMsg(response, buf, RESP_BUF_SIZE);
qDebug() << "Buff: " << buf;
file->SetVerboseMsg(buf);
ret = VtResponse_getResponseCode(response, &response_code);
if (!ret) {
qDebug() << "scan response code: " << response_code;
} else {
emit LogMsg(VT_LOG_ERR, ret, "Error fetching scan response code");
goto free_response;
}
if (response_code == 1) {
file->SetScanDate(QDateTime::currentDateTime());
file->SetState(kWaitForReport);
file->SetUploaded(true);
} else {
// FIXME what other codes?
goto free_response;
}
str = VtResponse_getString(response, "scan_id");
if (str) {
file->SetScanId(str);
free(str);
}
str = VtResponse_getString(response, "permalink");
if (str) {
file->SetPermalink(str);
free(str);
}
file->SetState(kReportFeteched);
free_response:
VtResponse_put(&response);
}
VtFile_put(&api);
}
void ScanFileTask::run(void)
{
qint64 fsize= file->size();
qDebug() << "Scanning: " << file->fileName() << " size " << fsize;
if (fsize < 64*1024*1024) {
ScanSmallFile();
return;
}
file->SetState(kErrorTooBig);
qDebug() << "FixMe large file";
}
|
#include <QDebug>
#include <jansson.h>
#include "VtFile.h"
#include "VtResponse.h"
#include "qvtfile.h"
#include "vt-log.h"
#include "scan_file_task.h"
ScanFileTask::ScanFileTask(QVtFile *vt_file)
{
file = vt_file;
}
#define RESP_BUF_SIZE 255
static void progress_update(struct VtFile *vtfile, void *qfile)
{
QVtFile::ProgessUpdateCallback(vtfile, (QVtFile *) qfile);
}
//Scan for a file
void ScanFileTask::ScanSmallFile(void)
{
int ret;
struct VtFile *api = VtFile_new();
struct VtResponse *response;
char *str = NULL;
char buf[RESP_BUF_SIZE+1] = { 0, };
int response_code;
VtFile_setApiKey(api, file->GetApiKey().toStdString().c_str());
// VtFile_setProgressCallback(api, QVtFile::ProgessUpdateCallback, (void *)file);
VtFile_setProgressCallback(api, progress_update, (void *)file);
ret = VtFile_scan(api, file->fileName().toStdString().c_str(), NULL);
if (ret) {
qDebug() << "Error opening fetching report " << QString(file->GetSha256().toHex()) << " " << ret;
file->SetState(kWaitForReport);
emit LogMsg(VT_LOG_ERR, ret, "Error fetching report");
} else {
response = VtFile_getResponse(api);
str = VtResponse_toJSONstr(response, VT_JSON_FLAG_INDENT);
if (str) {
qDebug() << "Scan Response: " << str;
free(str);
}
VtResponse_getVerboseMsg(response, buf, RESP_BUF_SIZE);
qDebug() << "Buff: " << buf;
file->SetVerboseMsg(buf);
ret = VtResponse_getResponseCode(response, &response_code);
if (!ret) {
qDebug() << "scan response code: " << response_code;
} else {
emit LogMsg(VT_LOG_ERR, ret, "Error fetching scan response code");
goto free_response;
}
if (response_code == 1) {
file->SetScanDate(QDateTime::currentDateTime());
file->SetState(kWaitForReport);
file->SetUploaded(true);
} else {
// FIXME what other codes?
goto free_response;
}
str = VtResponse_getString(response, "scan_id");
if (str) {
file->SetScanId(str);
free(str);
}
str = VtResponse_getString(response, "permalink");
if (str) {
file->SetPermalink(str);
free(str);
}
file->SetState(kReportFeteched);
free_response:
VtResponse_put(&response);
}
VtFile_put(&api);
}
void ScanFileTask::run(void)
{
qint64 fsize= file->size();
qDebug() << "Scanning: " << file->fileName() << " size " << fsize;
if (fsize < 64*1024*1024) {
ScanSmallFile();
return;
}
file->SetState(kErrorTooBig);
qDebug() << "FixMe large file";
}
|
fix for API change
|
fix for API change
|
C++
|
apache-2.0
|
VirusTotal/qt-virustotal-uploader,VirusTotal/qt-virustotal-uploader,VirusTotal/qt-virustotal-uploader
|
329daf5b51c2bcc30e9a0257670cd8193100801d
|
query_server/cpp_client_server/QueryClient.cpp
|
query_server/cpp_client_server/QueryClient.cpp
|
/**
* Non-metric Space Library
*
* Main developers: Bilegsaikhan Naidan, Leonid Boytsov, Yury Malkov, Ben Frederickson, David Novak
*
* For the complete list of contributors and further details see:
* https://github.com/searchivarius/NonMetricSpaceLib
*
* Copyright (c) 2013-2018
*
* This code is released under the
* Apache License Version 2.0 http://www.apache.org/licenses/.
*
*/
#include <memory>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TTransportUtils.h>
#include "QueryService.h"
#include "ztimer.h"
#include "params_def.h"
#include <boost/program_options.hpp>
using std::string;
using std::exception;
using std::stringstream;
using std::cerr;
using std::cout;
using std::cin;
using std::endl;
using std::unique_ptr;
using namespace ::similarity;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
namespace po = boost::program_options;
enum SearchType {
kNoSearch, kKNNSearch, kRangeSearch
};
static void Usage(const char *prog,
const po::options_description& desc) {
std::cout << prog << std::endl
<< desc << std::endl;
}
void ParseCommandLineForClient(int argc, char*argv[],
string& host,
int& port,
SearchType& searchType,
int& k,
double& r,
bool& retExternId,
bool& retObj,
string& queryTimeParams
) {
po::options_description ProgOptDesc("Allowed options");
ProgOptDesc.add_options()
(HELP_PARAM_OPT.c_str(), HELP_PARAM_MSG.c_str())
(PORT_PARAM_OPT.c_str(), po::value<int>(&port)->required(), PORT_PARAM_MSG.c_str())
(ADDR_PARAM_OPT.c_str(), po::value<string>(&host)->required(), ADDR_PARAM_MSG.c_str())
(KNN_PARAM_OPT.c_str(), po::value<int>(&k), KNN_PARAM_MSG.c_str())
(RANGE_PARAM_OPT.c_str(), po::value<double>(&r), RANGE_PARAM_MSG.c_str())
(QUERY_TIME_PARAMS_PARAM_OPT.c_str(), po::value<string>(&queryTimeParams)->default_value(""), QUERY_TIME_PARAMS_PARAM_MSG.c_str())
(RET_EXT_ID_PARAM_OPT.c_str(), RET_EXT_ID_PARAM_MSG.c_str())
(RET_OBJ_PARAM_OPT.c_str(), RET_EXT_ID_PARAM_MSG.c_str())
;
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, argv, ProgOptDesc), vm);
po::notify(vm);
} catch (const exception& e) {
Usage(argv[0], ProgOptDesc);
cerr << e.what() << endl;
exit(1);
}
if (vm.count("knn") == 1) {
if (vm.count("range") != 0) {
cerr << "Range search is not allowed if the KNN search is specified!";
Usage(argv[0], ProgOptDesc);
exit(1);
}
searchType = kKNNSearch;
} else if (vm.count("range") == 1) {
if (vm.count("knn") != 0) {
cerr << "KNN search is not allowed if the range search is specified";
Usage(argv[0], ProgOptDesc);
exit(1);
}
searchType = kRangeSearch;
} else {
searchType = kNoSearch;
}
retExternId = vm.count("retExternId") != 0;
retObj = vm.count("retObj") != 0;
if (vm.count("help") ) {
Usage(argv[0], ProgOptDesc);
exit(0);
}
}
int main(int argc, char *argv[]) {
string host;
int port = 0;
int k;
double r;
bool retExternId;
bool retObj;
SearchType searchType;
string queryTimeParams;
ParseCommandLineForClient(argc, argv,
host,
port,
searchType,
k, r,
retExternId,
retObj,
queryTimeParams);
// Let's read the query from the input stream
string s;
stringstream ss;
if (kNoSearch != searchType) {
while (getline(cin, s)) {
ss << s << endl;
}
}
string queryObjStr = ss.str();
::apache::thrift::stdcxx::shared_ptr<TTransport> socket(new TSocket(host, port));
::apache::thrift::stdcxx::shared_ptr<TTransport> transport(new TBufferedTransport(socket));
::apache::thrift::stdcxx::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
QueryServiceClient client(protocol);
try {
transport->open();
try {
if (!queryTimeParams.empty()) {
client.setQueryTimeParams(queryTimeParams);
}
WallClockTimer wtm;
wtm.reset();
ReplyEntryList res;
if (kKNNSearch == searchType) {
cout << "Running a " << k << "-NN query" << endl;;
client.knnQuery(res, k, queryObjStr, retExternId, retObj);
}
if (kRangeSearch == searchType) {
cout << "Running a range query with radius = " << r << endl;
client.rangeQuery(res, r, queryObjStr, retExternId, retObj);
}
wtm.split();
cout << "Finished in: " << wtm.elapsed() / 1e3f << " ms" << endl;
for (auto e: res) {
cout << "id=" << e.id << " dist=" << e.dist << ( retExternId ? " externId=" + e.externId : string("")) << endl;
if (retObj) cout << e.obj << endl;
}
} catch (const QueryException& e) {
cerr << "Query execution error: " << e.message << endl;
exit(1);
}
transport->close(); // Close transport !!!
} catch (const TException& tx) {
cerr << "Connection error: " << tx.what() << endl;
exit(1);
}
return 0;
}
|
/**
* Non-metric Space Library
*
* Main developers: Bilegsaikhan Naidan, Leonid Boytsov, Yury Malkov, Ben Frederickson, David Novak
*
* For the complete list of contributors and further details see:
* https://github.com/searchivarius/NonMetricSpaceLib
*
* Copyright (c) 2013-2018
*
* This code is released under the
* Apache License Version 2.0 http://www.apache.org/licenses/.
*
*/
#include <memory>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <vector>
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TSocket.h>
#include <thrift/transport/TTransportUtils.h>
#include "QueryService.h"
#include "ztimer.h"
#include "params_def.h"
#include <boost/program_options.hpp>
using std::string;
using std::exception;
using std::stringstream;
using std::cerr;
using std::cout;
using std::cin;
using std::endl;
using std::unique_ptr;
using namespace ::similarity;
using namespace apache::thrift;
using namespace apache::thrift::protocol;
using namespace apache::thrift::transport;
namespace po = boost::program_options;
enum SearchType {
kNoSearch, kKNNSearch, kRangeSearch, kKNNSearchBatch
};
static void Usage(const char *prog,
const po::options_description& desc) {
std::cout << prog << std::endl
<< desc << std::endl;
}
void ParseCommandLineForClient(int argc, char*argv[],
string& host,
int& port,
SearchType& searchType,
int& k,
double& r,
bool& retExternId,
bool& retObj,
string& queryTimeParams,
bool& batch
) {
po::options_description ProgOptDesc("Allowed options");
ProgOptDesc.add_options()
(HELP_PARAM_OPT.c_str(), HELP_PARAM_MSG.c_str())
(PORT_PARAM_OPT.c_str(), po::value<int>(&port)->required(), PORT_PARAM_MSG.c_str())
(ADDR_PARAM_OPT.c_str(), po::value<string>(&host)->required(), ADDR_PARAM_MSG.c_str())
(KNN_PARAM_OPT.c_str(), po::value<int>(&k), KNN_PARAM_MSG.c_str())
(RANGE_PARAM_OPT.c_str(), po::value<double>(&r), RANGE_PARAM_MSG.c_str())
(QUERY_TIME_PARAMS_PARAM_OPT.c_str(), po::value<string>(&queryTimeParams)->default_value(""), QUERY_TIME_PARAMS_PARAM_MSG.c_str())
(RET_EXT_ID_PARAM_OPT.c_str(), RET_EXT_ID_PARAM_MSG.c_str())
(RET_OBJ_PARAM_OPT.c_str(), RET_EXT_ID_PARAM_MSG.c_str())
("batch,b", po::value<bool>(&batch), "batch mode (only for knn). client can process multiple input lines)")
;
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, argv, ProgOptDesc), vm);
po::notify(vm);
} catch (const exception& e) {
Usage(argv[0], ProgOptDesc);
cerr << e.what() << endl;
exit(1);
}
if (vm.count("knn") == 1) {
if (vm.count("range") != 0) {
cerr << "Range search is not allowed if the KNN search is specified!";
Usage(argv[0], ProgOptDesc);
exit(1);
}
if (batch) {
searchType = kKNNSearchBatch;
} else {
searchType = kKNNSearch;
}
} else if (vm.count("range") == 1) {
if (vm.count("knn") != 0) {
cerr << "KNN search is not allowed if the range search is specified";
Usage(argv[0], ProgOptDesc);
exit(1);
}
searchType = kRangeSearch;
} else {
searchType = kNoSearch;
}
retExternId = vm.count("retExternId") != 0;
retObj = vm.count("retObj") != 0;
if (vm.count("help") ) {
Usage(argv[0], ProgOptDesc);
exit(0);
}
}
int main(int argc, char *argv[]) {
string host;
int port = 0;
int k;
double r;
bool retExternId;
bool retObj;
SearchType searchType;
string queryTimeParams;
bool batch = false;
ParseCommandLineForClient(argc, argv,
host,
port,
searchType,
k, r,
retExternId,
retObj,
queryTimeParams,
batch);
// Let's read the query from the input stream
string s;
stringstream ss;
std::vector<std::string> lines;
if (kNoSearch != searchType) {
while (getline(cin, s)) {
lines.push_back(s);
}
}
::apache::thrift::stdcxx::shared_ptr<TTransport> socket(new TSocket(host, port));
::apache::thrift::stdcxx::shared_ptr<TTransport> transport(new TBufferedTransport(socket));
::apache::thrift::stdcxx::shared_ptr<TProtocol> protocol(new TBinaryProtocol(transport));
QueryServiceClient client(protocol);
try {
transport->open();
try {
if (!queryTimeParams.empty()) {
client.setQueryTimeParams(queryTimeParams);
}
WallClockTimer wtm;
wtm.reset();
std::vector<ReplyEntryList> results;
if (kKNNSearch == searchType) {
cout << "Running a " << k << "-NN query" << endl;
for (auto queryObjStr: lines) {
ReplyEntryList res;
client.knnQuery(res, k, queryObjStr, retExternId, retObj);
results.push_back(res);
}
}
if (kRangeSearch == searchType) {
string queryObjStr = lines[0];
cout << "Running a range query with radius = " << r << endl;
ReplyEntryList res;
client.rangeQuery(res, r, queryObjStr, retExternId, retObj);
results.push_back(res);
}
if (kKNNSearchBatch == searchType) {
cout << "Running a batch " << k << "-NN query" << endl;;
ReplyEntryListBatch resBatch;
client.knnQueryBatch(resBatch, k, lines, retExternId, retObj, 4);
results = resBatch;
}
wtm.split();
cout << "Finished in: " << wtm.elapsed() / 1e3f << " ms" << endl;
for (auto res: results) {
cout << "----------------------------------" << endl;
for (auto e: res) {
cout << "id=" << e.id << " dist=" << e.dist << ( retExternId ? " externId=" + e.externId : string("")) << endl;
if (retObj) cout << e.obj << endl;
}
}
} catch (const QueryException& e) {
cerr << "Query execution error: " << e.message << endl;
exit(1);
}
transport->close(); // Close transport !!!
} catch (const TException& tx) {
cerr << "Connection error: " << tx.what() << endl;
exit(1);
}
return 0;
}
|
Update cpp client to experiment with batch knn query
|
Update cpp client to experiment with batch knn query
|
C++
|
apache-2.0
|
nmslib/nmslib,nmslib/nmslib,nmslib/nmslib,nmslib/nmslib,nmslib/nmslib,nmslib/nmslib,nmslib/nmslib
|
8208a85a1b6268c7adf77837db5fc75540ceda77
|
plugins/unifiedvideoinertialtracker/TrackingSystem.cpp
|
plugins/unifiedvideoinertialtracker/TrackingSystem.cpp
|
/** @file
@brief Implementation
@date 2016
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2016 Sensics, 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.
// Internal Includes
#include "TrackingSystem.h"
#include "TrackedBody.h"
#include "TrackedBodyTarget.h"
#include "UndistortMeasurements.h"
#include "ForEachTracked.h"
#include "TrackingSystem_Impl.h"
#include "SBDBlobExtractor.h"
// Library/third-party includes
#include <boost/assert.hpp>
// Standard includes
#include <algorithm>
#include <iterator>
#include <iostream>
#include <string>
#include <stdexcept>
namespace osvr {
namespace vbtracker {
TrackingSystem::TrackingSystem(ConfigParams const ¶ms)
: m_params(params), m_impl(new Impl(params)) {}
TrackingSystem::~TrackingSystem() {}
TrackedBody *TrackingSystem::createTrackedBody() {
auto newId = BodyId(m_bodies.size());
BodyPtr newBody(new TrackedBody(*this, newId));
m_bodies.emplace_back(std::move(newBody));
return m_bodies.back().get();
}
TrackedBodyTarget *TrackingSystem::getTarget(BodyTargetId target) {
return getBody(target.first).getTarget(target.second);
}
ImageOutputDataPtr TrackingSystem::performInitialImageProcessing(
util::time::TimeValue const &tv, cv::Mat const &frame,
cv::Mat const &frameGray, CameraParameters const &camParams) {
ImageOutputDataPtr ret(new ImageProcessingOutput);
ret->tv = tv;
ret->frame = frame;
ret->frameGray = frameGray;
ret->camParams = camParams.createUndistortedVariant();
auto rawMeasurements =
m_impl->blobExtractor->extractBlobs(ret->frameGray);
ret->ledMeasurements = undistortLeds(rawMeasurements, camParams);
return ret;
}
LedUpdateCount const &
TrackingSystem::updateLedsFromVideoData(ImageOutputDataPtr &&imageData) {
/// Clear internal data, we're invalidating things here.
m_updated.clear();
auto &updateCount = m_impl->updateCount;
updateCount.clear();
/// Update our frame cache, since we're taking ownership of the image
/// data now.
m_impl->frame = imageData->frame;
m_impl->frameGray = imageData->frameGray;
m_impl->camParams = imageData->camParams;
/// Go through each target and try to process the measurements.
forEachTarget(*this, [&](TrackedBodyTarget &target) {
auto usedMeasurements =
target.processLedMeasurements(imageData->ledMeasurements);
if (usedMeasurements != 0) {
updateCount[target.getQualifiedId()] = usedMeasurements;
}
});
return updateCount;
}
BodyIndices const &
TrackingSystem::updateBodiesFromVideoData(ImageOutputDataPtr &&imageData) {
/// Do the second phase of stuff
updateLedsFromVideoData(std::move(imageData));
/// Do the third phase of tracking.
updatePoseEstimates();
/// Trigger debug display, if activated.
m_impl->triggerDebugDisplay(*this);
return m_updated;
}
void TrackingSystem::updatePoseEstimates() {
auto const &updateCount = m_impl->updateCount;
for (auto &bodyTargetWithMeasurements : updateCount) {
auto targetPtr = getTarget(bodyTargetWithMeasurements.first);
BOOST_ASSERT_MSG(targetPtr != nullptr, "We should never be "
"retrieving a nullptr for a "
"target with measurements!");
if (!targetPtr) {
throw std::logic_error("Logical impossibility: Couldn't "
"retrieve a valid pointer for a target "
"that we were just told updated its "
"LEDs from data this frame.");
}
auto &target = *targetPtr;
/// @todo right now assumes one target per body here!
auto &body = target.getBody();
util::time::TimeValue stateTime;
BodyState state;
auto newTime = m_impl->lastFrame;
auto validState =
body.getStateAtOrBefore(newTime, stateTime, state);
auto gotPose = target.updatePoseEstimateFromLeds(
m_impl->camParams, newTime, state, stateTime, validState);
if (gotPose) {
body.replaceStateSnapshot(stateTime, newTime, state);
/// @todo deduplicate in making this list.
m_updated.push_back(body.getId());
}
}
}
bool TrackedBody::hasPoseEstimate() const {
/// @todo handle IMU here.
auto ret = false;
forEachTarget([&ret](TrackedBodyTarget &target) {
ret = ret || target.hasPoseEstimate();
});
return ret;
}
} // namespace vbtracker
} // namespace osvr
|
/** @file
@brief Implementation
@date 2016
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2016 Sensics, 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.
// Internal Includes
#include "TrackingSystem.h"
#include "TrackedBody.h"
#include "TrackedBodyTarget.h"
#include "UndistortMeasurements.h"
#include "ForEachTracked.h"
#include "TrackingSystem_Impl.h"
#include "SBDBlobExtractor.h"
// Library/third-party includes
#include <boost/assert.hpp>
// Standard includes
#include <algorithm>
#include <iterator>
#include <iostream>
#include <string>
#include <stdexcept>
namespace osvr {
namespace vbtracker {
TrackingSystem::TrackingSystem(ConfigParams const ¶ms)
: m_params(params), m_impl(new Impl(params)) {}
TrackingSystem::~TrackingSystem() {}
TrackedBody *TrackingSystem::createTrackedBody() {
auto newId = BodyId(m_bodies.size());
BodyPtr newBody(new TrackedBody(*this, newId));
m_bodies.emplace_back(std::move(newBody));
return m_bodies.back().get();
}
TrackedBodyTarget *TrackingSystem::getTarget(BodyTargetId target) {
return getBody(target.first).getTarget(target.second);
}
ImageOutputDataPtr TrackingSystem::performInitialImageProcessing(
util::time::TimeValue const &tv, cv::Mat const &frame,
cv::Mat const &frameGray, CameraParameters const &camParams) {
ImageOutputDataPtr ret(new ImageProcessingOutput);
ret->tv = tv;
ret->frame = frame;
ret->frameGray = frameGray;
ret->camParams = camParams.createUndistortedVariant();
auto rawMeasurements =
m_impl->blobExtractor->extractBlobs(ret->frameGray);
ret->ledMeasurements = undistortLeds(rawMeasurements, camParams);
return ret;
}
LedUpdateCount const &
TrackingSystem::updateLedsFromVideoData(ImageOutputDataPtr &&imageData) {
/// Clear internal data, we're invalidating things here.
m_updated.clear();
auto &updateCount = m_impl->updateCount;
updateCount.clear();
/// Update our frame cache, since we're taking ownership of the image
/// data now.
m_impl->frame = imageData->frame;
m_impl->frameGray = imageData->frameGray;
m_impl->camParams = imageData->camParams;
m_impl->lastFrame = imageData->tv;
/// Go through each target and try to process the measurements.
forEachTarget(*this, [&](TrackedBodyTarget &target) {
auto usedMeasurements =
target.processLedMeasurements(imageData->ledMeasurements);
if (usedMeasurements != 0) {
updateCount[target.getQualifiedId()] = usedMeasurements;
}
});
return updateCount;
}
BodyIndices const &
TrackingSystem::updateBodiesFromVideoData(ImageOutputDataPtr &&imageData) {
/// Do the second phase of stuff
updateLedsFromVideoData(std::move(imageData));
/// Do the third phase of tracking.
updatePoseEstimates();
/// Trigger debug display, if activated.
m_impl->triggerDebugDisplay(*this);
return m_updated;
}
void TrackingSystem::updatePoseEstimates() {
auto const &updateCount = m_impl->updateCount;
for (auto &bodyTargetWithMeasurements : updateCount) {
auto targetPtr = getTarget(bodyTargetWithMeasurements.first);
BOOST_ASSERT_MSG(targetPtr != nullptr, "We should never be "
"retrieving a nullptr for a "
"target with measurements!");
if (!targetPtr) {
throw std::logic_error("Logical impossibility: Couldn't "
"retrieve a valid pointer for a target "
"that we were just told updated its "
"LEDs from data this frame.");
}
auto &target = *targetPtr;
/// @todo right now assumes one target per body here!
auto &body = target.getBody();
util::time::TimeValue stateTime;
BodyState state;
auto newTime = m_impl->lastFrame;
auto validState =
body.getStateAtOrBefore(newTime, stateTime, state);
auto gotPose = target.updatePoseEstimateFromLeds(
m_impl->camParams, newTime, state, stateTime, validState);
if (gotPose) {
body.replaceStateSnapshot(stateTime, newTime, state);
/// @todo deduplicate in making this list.
m_updated.push_back(body.getId());
}
}
}
bool TrackedBody::hasPoseEstimate() const {
/// @todo handle IMU here.
auto ret = false;
forEachTarget([&ret](TrackedBodyTarget &target) {
ret = ret || target.hasPoseEstimate();
});
return ret;
}
} // namespace vbtracker
} // namespace osvr
|
Fix where we were failing to update a timestamp.
|
Fix where we were failing to update a timestamp.
|
C++
|
apache-2.0
|
godbyk/OSVR-Core,leemichaelRazer/OSVR-Core,OSVR/OSVR-Core,godbyk/OSVR-Core,leemichaelRazer/OSVR-Core,OSVR/OSVR-Core,OSVR/OSVR-Core,leemichaelRazer/OSVR-Core,godbyk/OSVR-Core,leemichaelRazer/OSVR-Core,OSVR/OSVR-Core,OSVR/OSVR-Core,godbyk/OSVR-Core,OSVR/OSVR-Core,godbyk/OSVR-Core,godbyk/OSVR-Core,leemichaelRazer/OSVR-Core
|
0f1ad2260e7b3cb03178fef1d4f9fb30c7a15958
|
contracts/eosiolib/dispatcher.hpp
|
contracts/eosiolib/dispatcher.hpp
|
#pragma once
#include <eosiolib/print.hpp>
#include <eosiolib/action.hpp>
#include <boost/fusion/adapted/std_tuple.hpp>
#include <boost/fusion/include/std_tuple.hpp>
#include <boost/mp11/tuple.hpp>
#define N(X) ::eosio::string_to_name(#X)
namespace eosio {
template<typename Contract, typename FirstAction>
bool dispatch( uint64_t code, uint64_t act ) {
if( code == FirstAction::get_account() && FirstAction::get_name() == act ) {
Contract().on( unpack_action_data<FirstAction>() );
return true;
}
return false;
}
/**
* This method will dynamically dispatch an incoming set of actions to
*
* ```
* static Contract::on( ActionType )
* ```
*
* For this to work the Actions must be dervied from the
*
*/
template<typename Contract, typename FirstAction, typename SecondAction, typename... Actions>
bool dispatch( uint64_t code, uint64_t act ) {
if( code == FirstAction::get_account() && FirstAction::get_name() == act ) {
Contract().on( unpack_action_data<FirstAction>() );
return true;
}
return eosio::dispatch<Contract,SecondAction,Actions...>( code, act );
}
template<typename T, typename... Args>
bool execute_action( T* obj, void (T::*func)(Args...) ) {
char buffer[action_data_size()];
read_action_data( buffer, sizeof(buffer) );
auto args = unpack<std::tuple<Args...>>( buffer, sizeof(buffer) );
auto f2 = [&]( auto... a ){
(obj->*func)( a... );
};
// apply( obj, func, args );
boost::mp11::tuple_apply( f2, args );
return true;
}
#define EOSIO_API_CALL( r, OP, elem ) \
case ::eosio::string_to_name( BOOST_PP_STRINGIZE(elem) ): eosio::execute_action( &thiscontract, &OP::elem ); return;
#define EOSIO_API( TYPE, MEMBERS ) \
BOOST_PP_SEQ_FOR_EACH( EOSIO_API_CALL, TYPE, MEMBERS )
#define EOSIO_ABI( TYPE, MEMBERS ) \
extern "C" { \
void apply( uint64_t code, uint64_t action ) { \
if( code == current_receiver() ) { \
TYPE thiscontract( current_receiver() ); \
switch( action ) { \
EOSIO_API( TYPE, (transfer)(issue) ) \
} \
eosio_exit(0); \
} \
} \
} \
/*
template<typename T>
struct dispatcher {
dispatcher( account_name code ):_contract(code){}
template<typename FuncPtr>
void dispatch( account_name action, FuncPtr ) {
}
T contract;
};
void dispatch( account_name code, account_name action,
*/
}
|
#pragma once
#include <eosiolib/print.hpp>
#include <eosiolib/action.hpp>
#include <boost/fusion/adapted/std_tuple.hpp>
#include <boost/fusion/include/std_tuple.hpp>
#include <boost/mp11/tuple.hpp>
#define N(X) ::eosio::string_to_name(#X)
namespace eosio {
template<typename Contract, typename FirstAction>
bool dispatch( uint64_t code, uint64_t act ) {
if( code == FirstAction::get_account() && FirstAction::get_name() == act ) {
Contract().on( unpack_action_data<FirstAction>() );
return true;
}
return false;
}
/**
* This method will dynamically dispatch an incoming set of actions to
*
* ```
* static Contract::on( ActionType )
* ```
*
* For this to work the Actions must be dervied from the
*
*/
template<typename Contract, typename FirstAction, typename SecondAction, typename... Actions>
bool dispatch( uint64_t code, uint64_t act ) {
if( code == FirstAction::get_account() && FirstAction::get_name() == act ) {
Contract().on( unpack_action_data<FirstAction>() );
return true;
}
return eosio::dispatch<Contract,SecondAction,Actions...>( code, act );
}
template<typename T, typename... Args>
bool execute_action( T* obj, void (T::*func)(Args...) ) {
char buffer[action_data_size()];
read_action_data( buffer, sizeof(buffer) );
auto args = unpack<std::tuple<Args...>>( buffer, sizeof(buffer) );
auto f2 = [&]( auto... a ){
(obj->*func)( a... );
};
// apply( obj, func, args );
boost::mp11::tuple_apply( f2, args );
return true;
}
#define EOSIO_API_CALL( r, OP, elem ) \
case ::eosio::string_to_name( BOOST_PP_STRINGIZE(elem) ): eosio::execute_action( &thiscontract, &OP::elem ); return;
#define EOSIO_API( TYPE, MEMBERS ) \
BOOST_PP_SEQ_FOR_EACH( EOSIO_API_CALL, TYPE, MEMBERS )
#define EOSIO_ABI( TYPE, MEMBERS ) \
extern "C" { \
void apply( uint64_t code, uint64_t action ) { \
if( code == current_receiver() ) { \
TYPE thiscontract( current_receiver() ); \
switch( action ) { \
EOSIO_API( TYPE, MEMBERS ) \
} \
eosio_exit(0); \
} \
} \
} \
/*
template<typename T>
struct dispatcher {
dispatcher( account_name code ):_contract(code){}
template<typename FuncPtr>
void dispatch( account_name action, FuncPtr ) {
}
T contract;
};
void dispatch( account_name code, account_name action,
*/
}
|
Update dispatcher.hpp
|
Update dispatcher.hpp
|
C++
|
mit
|
EOSIO/eos,EOSIO/eos,EOSIO/eos,EOSIO/eos,EOSIO/eos
|
3e966a918a9df7e65d381ddcaca35271cb305000
|
src/avancedb/rest_server.cpp
|
src/avancedb/rest_server.cpp
|
#include "rest_server.h"
#include <sstream>
#include <cstring>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/random_generator.hpp>
#include <boost/uuid/uuid_io.hpp>
#include "json_stream.h"
#include "rest_exceptions.h"
#include "database.h"
#define REGEX_DBNAME R"(_?[a-z][a-z0-9_\$\+\-\(\)]+)"
#define REGEX_DBNAME_GROUP "/(?<db>" REGEX_DBNAME ")"
RestServer::RestServer() {
router_.Add("HEAD", REGEX_DBNAME_GROUP "/?", boost::bind(&RestServer::HeadDatabase, this, _1, _2, _3));
router_.Add("DELETE", REGEX_DBNAME_GROUP "/?/?", boost::bind(&RestServer::DeleteDatabase, this, _1, _2, _3));
router_.Add("PUT", REGEX_DBNAME_GROUP "/?", boost::bind(&RestServer::PutDatabase, this, _1, _2, _3));
router_.Add("GET", "/_active_tasks", boost::bind(&RestServer::GetActiveTasks, this, _1, _2, _3));
router_.Add("GET", "/_uuids", boost::bind(&RestServer::GetUuids, this, _1, _2, _3));
router_.Add("GET", "/_session", boost::bind(&RestServer::GetSession, this, _1, _2, _3));
router_.Add("GET", "/_all_dbs", boost::bind(&RestServer::GetAllDbs, this, _1, _2, _3));
router_.Add("GET", REGEX_DBNAME_GROUP "/_all_docs", boost::bind(&RestServer::GetDatabaseAllDocs, this, _1, _2, _3));
router_.Add("GET", REGEX_DBNAME_GROUP "/?", boost::bind(&RestServer::GetDatabase, this, _1, _2, _3));
router_.Add("GET", "/_config/query_servers/?", boost::bind(&RestServer::GetConfigQueryServers, this, _1, _2, _3));
router_.Add("GET", "/_config/native_query_servers/?", boost::bind(&RestServer::GetConfigNativeQueryServers, this, _1, _2, _3));
router_.Add("GET", "/", boost::bind(&RestServer::GetSignature, this, _1, _2, _3));
databases_.AddDatabase("_replicator");
databases_.AddDatabase("_users");
}
void RestServer::RouteRequest(rs::httpserver::socket_ptr, rs::httpserver::request_ptr request, rs::httpserver::response_ptr response) {
router_.Match(request, response);
}
bool RestServer::GetActiveTasks(rs::httpserver::request_ptr request, const rs::httpserver::RequestRouter::CallbackArgs&, rs::httpserver::response_ptr response) {
response->setContentType("application/javascript").Send("[]");
return true;
}
bool RestServer::GetSession(rs::httpserver::request_ptr request, const rs::httpserver::RequestRouter::CallbackArgs&, rs::httpserver::response_ptr response) {
response->setContentType("application/javascript").Send(R"({"ok":true,"userCtx":{"name":null,"roles":["_admin"]},"info":{"authentication_db":"_users","authentication_handlers":["oauth","cookie","default"],"authenticated":"default"}})");
return true;
}
bool RestServer::GetAllDbs(rs::httpserver::request_ptr request, const rs::httpserver::RequestRouter::CallbackArgs&, rs::httpserver::response_ptr response) {
auto dbs = databases_.GetDatabases();
std::stringstream stream;
stream << "[";
for (int i = 0; i < dbs.size(); ++i) {
stream << (i > 0 ? "," : "") << "\"" << dbs[i] << "\"";
}
stream << "]";
response->setContentType("application/javascript").Send(stream.str());
return true;
}
bool RestServer::GetSignature(rs::httpserver::request_ptr request, const rs::httpserver::RequestRouter::CallbackArgs&, rs::httpserver::response_ptr response) {
response->setContentType("application/javascript").Send(R"({"couchdb":"Welcome","avancedb":"Welcome","uuid":"a2db86472466bcd02e84ac05a6c86185","version":"1.6.1","vendor":{"version":"0.0.1","name":"Ripcord Software"}})");
return true;
}
bool RestServer::GetUuids(rs::httpserver::request_ptr request, const rs::httpserver::RequestRouter::CallbackArgs&, rs::httpserver::response_ptr response) {
int count = 1;
if (request->getQueryString().IsKey("count")) {
auto countParam = request->getQueryString().getValue("count");
if (countParam.length() > 0) {
count = boost::lexical_cast<int>(countParam);
}
}
std::stringstream stream;
stream << std::hex << "{\"uuids\":[";
boost::uuids::basic_random_generator<boost::mt19937> gen;
for (int i = 0; i < count; ++i) {
stream << (i > 0 ? "," : "") << "\"";
stream.width(2);
auto uuid = gen();
for (auto iter = uuid.begin(); iter != uuid.end(); iter++) {
stream << static_cast<int>(*iter);
}
stream.width(0);
stream << "\"";
}
stream << "]}";
response->setContentType("application/javascript").Send(stream.str());
return true;
}
bool RestServer::HeadDatabase(rs::httpserver::request_ptr request, const rs::httpserver::RequestRouter::CallbackArgs& args, rs::httpserver::response_ptr response) {
auto iter = args.find("db");
bool found = iter != args.cend() && databases_.IsDatabase(iter->second);
if (found) {
response->setContentType("application/javascript").Send();
}
return found;
}
bool RestServer::GetDatabase(rs::httpserver::request_ptr request, const rs::httpserver::RequestRouter::CallbackArgs& args, rs::httpserver::response_ptr response) {
auto argsIter = args.find("db");
bool found = argsIter != args.cend();
if (found) {
auto db = databases_.GetDatabase(argsIter->second);
found = !!db;
if (found) {
JsonStream stream;
stream.Append("committed_update_seq", db->CommitedUpdateSequence());
stream.Append("compact_running", false);
stream.Append("data_size", db->DataSize());
stream.Append("db_name", argsIter->second);
stream.Append("disk_format_version", 6);
stream.Append("disk_size", db->DiskSize());
stream.Append("doc_count", db->DocCount());
stream.Append("doc_del_count", db->DocDelCount());
stream.Append("instance_start_time", db->InstanceStartTime());
stream.Append("purge_seq", db->PurgeSequence());
stream.Append("update_seq", db->UpdateSequence());
response->setContentType("application/javascript").Send(stream.Flush());
} else {
throw MissingDatabase();
}
}
return found;
}
bool RestServer::PutDatabase(rs::httpserver::request_ptr request, const rs::httpserver::RequestRouter::CallbackArgs& args, rs::httpserver::response_ptr response) {
bool created = false;
auto argsIter = args.find("db");
if (argsIter != args.cend()) {
auto name = argsIter->second;
if (std::strlen(name) <= 0 || name[0] == '_') {
throw InvalidDatabaseName();
}
if (databases_.IsDatabase(name)) {
throw DatabaseAlreadyExists();
}
created = databases_.AddDatabase(name);
if (created) {
response->setStatusCode(201).setContentType("application/javascript").Send(R"({"ok":true})");
}
}
return created;
}
bool RestServer::DeleteDatabase(rs::httpserver::request_ptr request, const rs::httpserver::RequestRouter::CallbackArgs& args, rs::httpserver::response_ptr response) {
bool deleted = false;
auto argsIter = args.find("db");
if (argsIter != args.cend()) {
auto name = argsIter->second;
if (std::strlen(name) <= 0 || name[0] == '_') {
throw InvalidDatabaseName();
}
deleted = databases_.RemoveDatabase(argsIter->second);
if (deleted) {
response->setContentType("application/javascript").Send(R"({"ok":true})");
} else {
throw MissingDatabase();
}
}
return deleted;
}
bool RestServer::GetDatabaseAllDocs(rs::httpserver::request_ptr request, const rs::httpserver::RequestRouter::CallbackArgs& args, rs::httpserver::response_ptr response) {
response->setContentType("application/javascript").Send(R"({"offset":0,"rows":[],"total_rows":0})");
}
bool RestServer::GetConfigQueryServers(rs::httpserver::request_ptr request, const rs::httpserver::RequestRouter::CallbackArgs&, rs::httpserver::response_ptr response) {
response->setContentType("application/javascript").Send(R"({"javascript":"libjsapi"})");
}
bool RestServer::GetConfigNativeQueryServers(rs::httpserver::request_ptr request, const rs::httpserver::RequestRouter::CallbackArgs&, rs::httpserver::response_ptr response) {
response->setContentType("application/javascript").Send("{}");
}
|
#include "rest_server.h"
#include <sstream>
#include <cstring>
#include <iomanip>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/random_generator.hpp>
#include <boost/uuid/uuid_io.hpp>
#include "json_stream.h"
#include "rest_exceptions.h"
#include "database.h"
#define REGEX_DBNAME R"(_?[a-z][a-z0-9_\$\+\-\(\)]+)"
#define REGEX_DBNAME_GROUP "/(?<db>" REGEX_DBNAME ")"
RestServer::RestServer() {
router_.Add("HEAD", REGEX_DBNAME_GROUP "/?", boost::bind(&RestServer::HeadDatabase, this, _1, _2, _3));
router_.Add("DELETE", REGEX_DBNAME_GROUP "/?/?", boost::bind(&RestServer::DeleteDatabase, this, _1, _2, _3));
router_.Add("PUT", REGEX_DBNAME_GROUP "/?", boost::bind(&RestServer::PutDatabase, this, _1, _2, _3));
router_.Add("GET", "/_active_tasks", boost::bind(&RestServer::GetActiveTasks, this, _1, _2, _3));
router_.Add("GET", "/_uuids", boost::bind(&RestServer::GetUuids, this, _1, _2, _3));
router_.Add("GET", "/_session", boost::bind(&RestServer::GetSession, this, _1, _2, _3));
router_.Add("GET", "/_all_dbs", boost::bind(&RestServer::GetAllDbs, this, _1, _2, _3));
router_.Add("GET", REGEX_DBNAME_GROUP "/_all_docs", boost::bind(&RestServer::GetDatabaseAllDocs, this, _1, _2, _3));
router_.Add("GET", REGEX_DBNAME_GROUP "/?", boost::bind(&RestServer::GetDatabase, this, _1, _2, _3));
router_.Add("GET", "/_config/query_servers/?", boost::bind(&RestServer::GetConfigQueryServers, this, _1, _2, _3));
router_.Add("GET", "/_config/native_query_servers/?", boost::bind(&RestServer::GetConfigNativeQueryServers, this, _1, _2, _3));
router_.Add("GET", "/", boost::bind(&RestServer::GetSignature, this, _1, _2, _3));
databases_.AddDatabase("_replicator");
databases_.AddDatabase("_users");
}
void RestServer::RouteRequest(rs::httpserver::socket_ptr, rs::httpserver::request_ptr request, rs::httpserver::response_ptr response) {
router_.Match(request, response);
}
bool RestServer::GetActiveTasks(rs::httpserver::request_ptr request, const rs::httpserver::RequestRouter::CallbackArgs&, rs::httpserver::response_ptr response) {
response->setContentType("application/javascript").Send("[]");
return true;
}
bool RestServer::GetSession(rs::httpserver::request_ptr request, const rs::httpserver::RequestRouter::CallbackArgs&, rs::httpserver::response_ptr response) {
response->setContentType("application/javascript").Send(R"({"ok":true,"userCtx":{"name":null,"roles":["_admin"]},"info":{"authentication_db":"_users","authentication_handlers":["oauth","cookie","default"],"authenticated":"default"}})");
return true;
}
bool RestServer::GetAllDbs(rs::httpserver::request_ptr request, const rs::httpserver::RequestRouter::CallbackArgs&, rs::httpserver::response_ptr response) {
auto dbs = databases_.GetDatabases();
std::stringstream stream;
stream << "[";
for (int i = 0; i < dbs.size(); ++i) {
stream << (i > 0 ? "," : "") << "\"" << dbs[i] << "\"";
}
stream << "]";
response->setContentType("application/javascript").Send(stream.str());
return true;
}
bool RestServer::GetSignature(rs::httpserver::request_ptr request, const rs::httpserver::RequestRouter::CallbackArgs&, rs::httpserver::response_ptr response) {
response->setContentType("application/javascript").Send(R"({"couchdb":"Welcome","avancedb":"Welcome","uuid":"a2db86472466bcd02e84ac05a6c86185","version":"1.6.1","vendor":{"version":"0.0.1","name":"Ripcord Software"}})");
return true;
}
bool RestServer::GetUuids(rs::httpserver::request_ptr request, const rs::httpserver::RequestRouter::CallbackArgs&, rs::httpserver::response_ptr response) {
int count = 1;
if (request->getQueryString().IsKey("count")) {
auto countParam = request->getQueryString().getValue("count");
if (countParam.length() > 0) {
count = boost::lexical_cast<int>(countParam);
}
}
std::stringstream stream;
stream << std::hex << std::setfill('0') << "{\"uuids\":[";
boost::uuids::random_generator gen;
for (int i = 0; i < count; ++i) {
stream << (i > 0 ? "," : "") << "\"";
auto uuid = gen();
for (auto iter = uuid.begin(); iter != uuid.end(); ++iter) {
stream << std::setw(2) << static_cast<unsigned>(*iter);
}
stream << "\"";
}
stream << "]}";
response->setContentType("application/javascript").Send(stream.str());
return true;
}
bool RestServer::HeadDatabase(rs::httpserver::request_ptr request, const rs::httpserver::RequestRouter::CallbackArgs& args, rs::httpserver::response_ptr response) {
auto iter = args.find("db");
bool found = iter != args.cend() && databases_.IsDatabase(iter->second);
if (found) {
response->setContentType("application/javascript").Send();
}
return found;
}
bool RestServer::GetDatabase(rs::httpserver::request_ptr request, const rs::httpserver::RequestRouter::CallbackArgs& args, rs::httpserver::response_ptr response) {
auto argsIter = args.find("db");
bool found = argsIter != args.cend();
if (found) {
auto db = databases_.GetDatabase(argsIter->second);
found = !!db;
if (found) {
JsonStream stream;
stream.Append("committed_update_seq", db->CommitedUpdateSequence());
stream.Append("compact_running", false);
stream.Append("data_size", db->DataSize());
stream.Append("db_name", argsIter->second);
stream.Append("disk_format_version", 6);
stream.Append("disk_size", db->DiskSize());
stream.Append("doc_count", db->DocCount());
stream.Append("doc_del_count", db->DocDelCount());
stream.Append("instance_start_time", db->InstanceStartTime());
stream.Append("purge_seq", db->PurgeSequence());
stream.Append("update_seq", db->UpdateSequence());
response->setContentType("application/javascript").Send(stream.Flush());
} else {
throw MissingDatabase();
}
}
return found;
}
bool RestServer::PutDatabase(rs::httpserver::request_ptr request, const rs::httpserver::RequestRouter::CallbackArgs& args, rs::httpserver::response_ptr response) {
bool created = false;
auto argsIter = args.find("db");
if (argsIter != args.cend()) {
auto name = argsIter->second;
if (std::strlen(name) <= 0 || name[0] == '_') {
throw InvalidDatabaseName();
}
if (databases_.IsDatabase(name)) {
throw DatabaseAlreadyExists();
}
created = databases_.AddDatabase(name);
if (created) {
response->setStatusCode(201).setContentType("application/javascript").Send(R"({"ok":true})");
}
}
return created;
}
bool RestServer::DeleteDatabase(rs::httpserver::request_ptr request, const rs::httpserver::RequestRouter::CallbackArgs& args, rs::httpserver::response_ptr response) {
bool deleted = false;
auto argsIter = args.find("db");
if (argsIter != args.cend()) {
auto name = argsIter->second;
if (std::strlen(name) <= 0 || name[0] == '_') {
throw InvalidDatabaseName();
}
deleted = databases_.RemoveDatabase(argsIter->second);
if (deleted) {
response->setContentType("application/javascript").Send(R"({"ok":true})");
} else {
throw MissingDatabase();
}
}
return deleted;
}
bool RestServer::GetDatabaseAllDocs(rs::httpserver::request_ptr request, const rs::httpserver::RequestRouter::CallbackArgs& args, rs::httpserver::response_ptr response) {
response->setContentType("application/javascript").Send(R"({"offset":0,"rows":[],"total_rows":0})");
}
bool RestServer::GetConfigQueryServers(rs::httpserver::request_ptr request, const rs::httpserver::RequestRouter::CallbackArgs&, rs::httpserver::response_ptr response) {
response->setContentType("application/javascript").Send(R"({"javascript":"libjsapi"})");
}
bool RestServer::GetConfigNativeQueryServers(rs::httpserver::request_ptr request, const rs::httpserver::RequestRouter::CallbackArgs&, rs::httpserver::response_ptr response) {
response->setContentType("application/javascript").Send("{}");
}
|
Correct /_uuids formatting behaviour
|
Correct /_uuids formatting behaviour
|
C++
|
agpl-3.0
|
AppleWatchHipster/AvanceDB,AppleWatchHipster/AvanceDB,RipcordSoftware/AvanceDB,AppleWatchHipster/AvanceDB,AppleWatchHipster/AvanceDB,RipcordSoftware/AvanceDB,AppleWatchHipster/AvanceDB,RipcordSoftware/AvanceDB,RipcordSoftware/AvanceDB,RipcordSoftware/AvanceDB,AppleWatchHipster/AvanceDB,RipcordSoftware/AvanceDB,RipcordSoftware/AvanceDB
|
e67c9f46379880120eeb8c61123330cea4150ca9
|
LxRunOffline/error.cpp
|
LxRunOffline/error.cpp
|
#include "stdafx.h"
#include "error.h"
#include "utils.h"
const wstr msg_table[] = {
L"Could't open the file \"%1%\".",
L"Couldn't open the directory \"%1%\".",
L"Couldn't create the file \"%1%\".",
L"Couldn't create the directory \"%1%\".",
L"Couldn't delete the file \"%1%\".",
L"Couldn't delete the directory \"%1%\".",
L"Couldn't get contents of the directory \"%1%\".",
L"Couldn't get information of the file \"%1%\".",
L"Couldn't get extended attributes of the file or directory \"%1%\".",
L"Couldn't set extended attributes of the file or directory \"%1%\".",
L"Couldn't set the case sensitive attribute of the directory \"%1%\".",
L"Couldn't create the hard link from \"%1%\" to \"%2%\".",
L"Couldn't read from the file \"%1%\".",
L"Couldn't write to the file \"%1%\".",
L"Couldn't recognize the path \"%1%\".",
L"Couldn't convert a string from UTF-8 encoding to wide chars.",
L"Error occurred while processing the archive.",
L"Couldn't get Windows version information. \"%1%\"",
L"Windows 10 v%1% (v10.0.%2%) or later is required. Please upgrade your system.",
L"Couldn't open or create the registry key \"%1%\".",
L"Couldn't delete the registry key \"%1%\".",
L"Couldn't get subkeys of the registry key \"%1%\".",
L"Couldn't copy the registry key \"%1%\" to \"%2%\".",
L"Couldn't get the value \"%2%\" of the registry key \"%1%\".",
L"Couldn't set the value \"%2%\" of the registry key \"%1%\".",
L"Couldn't create a GUID.",
L"Couldn't convert a GUID to a string.",
L"Couldn't find the distro named \"%1%\".",
L"A distro named \"%1%\" already exists.",
L"No action is speicified.",
L"The action \"%1%\" is not recognized.",
L"Couldn't load wslapi.dll. Please make sure that WSL has been installed.",
L"Error occurred when trying to launch the distro \"%1%\".",
L"Error occurred when creating a shortcut."
};
err error_hresult(err_msg msg_code, const std::vector<wstr> &msg_args, HRESULT err_code) {
return err{ msg_code,msg_args,err_code };
}
err error_win32(err_msg msg_code, const std::vector<wstr> &msg_args, uint32_t err_code) {
return error_hresult(msg_code, msg_args, HRESULT_FROM_WIN32(err_code));
}
err error_win32_last(err_msg msg_code, const std::vector<wstr> &msg_args) {
return error_win32(msg_code, msg_args, GetLastError());
}
err error_nt(err_msg msg_code, const std::vector<wstr> &msg_args, NTSTATUS err_code) {
return error_hresult(msg_code, msg_args, HRESULT_FROM_NT(err_code));
}
err error_other(err_msg msg_code, const std::vector<wstr> &msg_args) {
return error_hresult(msg_code, msg_args, S_OK);
}
wstr err::format() const {
std::wstringstream ss;
auto fmt = boost::wformat(msg_table[msg_code]);
for (const auto &s : msg_args) fmt = fmt % s;
ss << fmt << std::endl;
if (err_code) {
ss << L"Reason: ";
if (err_code & FACILITY_NT_BIT) {
auto stat = err_code & ~FACILITY_NT_BIT;
wchar_t *buf = nullptr;
auto f = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_IGNORE_INSERTS;
auto hm = LoadLibrary(L"ntdll.dll");
auto ok = hm && FormatMessage(f, hm, stat, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), (wchar_t *)&buf, 0, nullptr);
if (hm) FreeLibrary(hm);
if (ok) {
ss << buf;
LocalFree(buf);
} else {
ss << L"Unknown NTSTATUS: " << L"0x" << std::setfill(L'0') << std::setw(8) << std::hex << stat;
}
} else {
_com_error ce(err_code);
ss << ce.ErrorMessage();
}
}
return ss.str();
}
void err::push_if_empty(crwstr arg) {
if (msg_args.empty()) msg_args.push_back(arg);
}
|
#include "stdafx.h"
#include "error.h"
#include "utils.h"
const wstr msg_table[] = {
L"Could't open the file \"%1%\".",
L"Couldn't open the directory \"%1%\".",
L"Couldn't create the file \"%1%\".",
L"Couldn't create the directory \"%1%\".",
L"Couldn't delete the file \"%1%\".",
L"Couldn't delete the directory \"%1%\".",
L"Couldn't get contents of the directory \"%1%\".",
L"Couldn't get information of the file \"%1%\".",
L"Couldn't get extended attributes of the file or directory \"%1%\".",
L"Couldn't set extended attributes of the file or directory \"%1%\".",
L"Couldn't set the case sensitive attribute of the directory \"%1%\".",
L"Couldn't create the hard link from \"%1%\" to \"%2%\".",
L"Couldn't read from the file \"%1%\".",
L"Couldn't write to the file \"%1%\".",
L"Couldn't recognize the path \"%1%\".",
L"Couldn't convert a string from UTF-8 encoding to wide chars.",
L"Error occurred while processing the archive.",
L"Couldn't get Windows version information. \"%1%\"",
L"Windows 10 v%1% (v10.0.%2%) or later is required. Please upgrade your system.",
L"Couldn't open or create the registry key \"%1%\".",
L"Couldn't delete the registry key \"%1%\".",
L"Couldn't get subkeys of the registry key \"%1%\".",
L"Couldn't copy the registry key \"%1%\" to \"%2%\".",
L"Couldn't get the value \"%2%\" of the registry key \"%1%\".",
L"Couldn't set the value \"%2%\" of the registry key \"%1%\".",
L"Couldn't create a GUID.",
L"Couldn't convert a GUID to a string.",
L"Couldn't find the distro named \"%1%\".",
L"A distro named \"%1%\" already exists.",
L"No action is specified.",
L"The action \"%1%\" is not recognized.",
L"Couldn't load wslapi.dll. Please make sure that WSL has been installed.",
L"Error occurred when trying to launch the distro \"%1%\".",
L"Error occurred when creating a shortcut."
};
err error_hresult(err_msg msg_code, const std::vector<wstr> &msg_args, HRESULT err_code) {
return err{ msg_code,msg_args,err_code };
}
err error_win32(err_msg msg_code, const std::vector<wstr> &msg_args, uint32_t err_code) {
return error_hresult(msg_code, msg_args, HRESULT_FROM_WIN32(err_code));
}
err error_win32_last(err_msg msg_code, const std::vector<wstr> &msg_args) {
return error_win32(msg_code, msg_args, GetLastError());
}
err error_nt(err_msg msg_code, const std::vector<wstr> &msg_args, NTSTATUS err_code) {
return error_hresult(msg_code, msg_args, HRESULT_FROM_NT(err_code));
}
err error_other(err_msg msg_code, const std::vector<wstr> &msg_args) {
return error_hresult(msg_code, msg_args, S_OK);
}
wstr err::format() const {
std::wstringstream ss;
auto fmt = boost::wformat(msg_table[msg_code]);
for (const auto &s : msg_args) fmt = fmt % s;
ss << fmt << std::endl;
if (err_code) {
ss << L"Reason: ";
if (err_code & FACILITY_NT_BIT) {
auto stat = err_code & ~FACILITY_NT_BIT;
wchar_t *buf = nullptr;
auto f = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_FROM_HMODULE | FORMAT_MESSAGE_IGNORE_INSERTS;
auto hm = LoadLibrary(L"ntdll.dll");
auto ok = hm && FormatMessage(f, hm, stat, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), (wchar_t *)&buf, 0, nullptr);
if (hm) FreeLibrary(hm);
if (ok) {
ss << buf;
LocalFree(buf);
} else {
ss << L"Unknown NTSTATUS: " << L"0x" << std::setfill(L'0') << std::setw(8) << std::hex << stat;
}
} else {
_com_error ce(err_code);
ss << ce.ErrorMessage();
}
}
return ss.str();
}
void err::push_if_empty(crwstr arg) {
if (msg_args.empty()) msg_args.push_back(arg);
}
|
fix typo speicified -> specified
|
fix typo speicified -> specified
|
C++
|
mit
|
sqc1999/LxRunOffline
|
c4768ff6c3acf85fd296572a6d492e14982577a3
|
MMgc/GCHeapGeneric.cpp
|
MMgc/GCHeapGeneric.cpp
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is [Open Source Virtual Machine.].
*
* The Initial Developer of the Original Code is
* Adobe System Incorporated.
* Portions created by the Initial Developer are Copyright (C) 2004-2007
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adobe AS3 Team
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "MMgc.h"
#include "GCDebug.h"
#include "GC.h"
namespace MMgc
{
void *aligned_malloc(size_t size, size_t align_size, GCMallocFuncPtr m_malloc)
{
char *ptr, *ptr2, *aligned_ptr;
int align_mask = align_size - 1;
int alloc_size = size + align_size + sizeof(int);
ptr=(char *)m_malloc(alloc_size);
if(ptr==NULL) return(NULL);
ptr2 = ptr + sizeof(int);
aligned_ptr = ptr2 + (align_size - ((size_t)ptr2 & align_mask));
ptr2 = aligned_ptr - sizeof(int);
*((int *)ptr2)=(int)(aligned_ptr - ptr);
return(aligned_ptr);
}
void aligned_free(void *ptr, GCFreeFuncPtr m_free)
{
int *ptr2=(int *)ptr - 1;
char *unaligned_ptr = (char*) ptr - *ptr2;
m_free(unaligned_ptr);
}
int GCHeap::vmPageSize()
{
return MMGC_PortAPI_GetPageSize();
}
#ifdef MEASURE_MEMORY_HIGHWATER
ChunkTracker* ChunkTracker::s_pHead = NULL;
unsigned int ChunkTracker::s_highwater = 0;
unsigned int ChunkTracker::s_total_mem = 0;
unsigned int ChunkTracker::s_blocks = 0;
unsigned int ChunkTracker::s_maxblocks = 0;
#endif
char* GCHeap::AllocateAlignedMemory(size_t size)
{
#ifdef MEASURE_MEMORY_HIGHWATER
ChunkTracker::s_total_mem += size;
if (ChunkTracker::s_total_mem > ChunkTracker::s_highwater)
{
ChunkTracker::s_highwater = ChunkTracker::s_total_mem;
}
ChunkTracker::s_blocks++;
if (ChunkTracker::s_blocks > ChunkTracker::s_maxblocks)
{
ChunkTracker::s_maxblocks = ChunkTracker::s_blocks;
}
void* block = aligned_malloc(size, vmPageSize(), m_malloc);
ChunkTracker* chunk = new ChunkTracker(block, size);
chunk->m_pNext = ChunkTracker::s_pHead;
ChunkTracker::s_pHead = chunk;
return (char*)block;
#else
return (char *) aligned_malloc(size, vmPageSize(), m_malloc);
#endif
}
void GCHeap::ReleaseMemory(char *address, size_t)
{
#ifdef MEASURE_MEMORY_HIGHWATER
ChunkTracker::s_blocks--;
ChunkTracker* chunk = ChunkTracker::s_pHead;
ChunkTracker* prev = NULL;
while(chunk)
{
if (chunk->m_block == address)
{
ChunkTracker::s_total_mem -= chunk->m_size;
if (prev)
{
prev->m_pNext = chunk->m_pNext;
}
else
{
ChunkTracker::s_pHead = chunk->m_pNext;
}
delete chunk;
break;
}
prev = chunk;
chunk = chunk->m_pNext;
}
#endif
aligned_free(address, m_free);
}
void GetStackTrace(int* /* trace */, int /* len */, int /* skip */)
{
}
void GetInfoFromPC(int /* pc */, char *buff, int buffSize)
{
if (buffSize > 0)
{
buff[0] = '\0';
}
}
/*static*/
size_t GCHeap::GetPrivateBytes() { return 0; } // TODO
}
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is [Open Source Virtual Machine.].
*
* The Initial Developer of the Original Code is
* Adobe System Incorporated.
* Portions created by the Initial Developer are Copyright (C) 2004-2007
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Adobe AS3 Team
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "MMgc.h"
#include "GCDebug.h"
#include "GC.h"
namespace MMgc
{
void *aligned_malloc(size_t size, size_t align_size, GCMallocFuncPtr m_malloc)
{
char *ptr, *ptr2, *aligned_ptr;
int align_mask = align_size - 1;
int alloc_size = size + align_size + sizeof(int);
ptr=(char *)m_malloc(alloc_size);
if(ptr==NULL) return(NULL);
ptr2 = ptr + sizeof(int);
aligned_ptr = ptr2 + (align_size - ((size_t)ptr2 & align_mask));
ptr2 = aligned_ptr - sizeof(int);
*((int *)ptr2)=(int)(aligned_ptr - ptr);
return(aligned_ptr);
}
void aligned_free(void *ptr, GCFreeFuncPtr m_free)
{
int *ptr2=(int *)ptr - 1;
char *unaligned_ptr = (char*) ptr - *ptr2;
m_free(unaligned_ptr);
}
uint32_t GCHeap::vmPageSize()
{
#ifdef MMGC_PORTING_API
return MMGC_PortAPI_GetPageSize();
#else
return 4096;
#endif
}
#ifdef MEASURE_MEMORY_HIGHWATER
ChunkTracker* ChunkTracker::s_pHead = NULL;
unsigned int ChunkTracker::s_highwater = 0;
unsigned int ChunkTracker::s_total_mem = 0;
unsigned int ChunkTracker::s_blocks = 0;
unsigned int ChunkTracker::s_maxblocks = 0;
#endif
char* GCHeap::AllocateAlignedMemory(size_t size)
{
GCMallocFuncPtr m;
#ifdef MMGC_PORTING_API
m = MMGC_PortAPI_Alloc;
#else
m = malloc;
#endif
#ifdef MEASURE_MEMORY_HIGHWATER
ChunkTracker::s_total_mem += size;
if (ChunkTracker::s_total_mem > ChunkTracker::s_highwater)
{
ChunkTracker::s_highwater = ChunkTracker::s_total_mem;
}
ChunkTracker::s_blocks++;
if (ChunkTracker::s_blocks > ChunkTracker::s_maxblocks)
{
ChunkTracker::s_maxblocks = ChunkTracker::s_blocks;
}
void* block = aligned_malloc(size, vmPageSize(), m);
ChunkTracker* chunk = new ChunkTracker(block, size);
chunk->m_pNext = ChunkTracker::s_pHead;
ChunkTracker::s_pHead = chunk;
return (char*)block;
#else
return (char *) aligned_malloc(size, vmPageSize(), m);
#endif
}
void GCHeap::ReleaseAlignedMemory(char *address, size_t)
{
GCFreeFuncPtr f;
#ifdef MMGC_PORTING_API
f = MMGC_PortAPI_Free;
#else
f = free;
#endif
#ifdef MEASURE_MEMORY_HIGHWATER
ChunkTracker::s_blocks--;
ChunkTracker* chunk = ChunkTracker::s_pHead;
ChunkTracker* prev = NULL;
while(chunk)
{
if (chunk->m_block == address)
{
ChunkTracker::s_total_mem -= chunk->m_size;
if (prev)
{
prev->m_pNext = chunk->m_pNext;
}
else
{
ChunkTracker::s_pHead = chunk->m_pNext;
}
delete chunk;
break;
}
prev = chunk;
chunk = chunk->m_pNext;
}
#endif
aligned_free(address, f);
}
void GetStackTrace(int* /* trace */, int /* len */, int /* skip */)
{
}
void GetInfoFromPC(int /* pc */, char *buff, int buffSize)
{
if (buffSize > 0)
{
buff[0] = '\0';
}
}
/*static*/
size_t GCHeap::GetPrivateBytes() { return 0; } // TODO
bool GCHeap::osSupportsRegionMerging()
{
return false;
}
bool GCHeap::osSupportsVirtualMemory()
{
return false;
}
char *GCHeap::ReserveMemory(char *, size_t) { GCAssert(false); return NULL; }
bool GCHeap::CommitMemory(char *, size_t) { GCAssert(false); return false; }
bool GCHeap::DecommitMemory(char *, size_t) { GCAssert(false); return false; }
void GCHeap::ReleaseMemory(char *, size_t ) { GCAssert(false); }
bool GCHeap::CommitMemoryThatMaySpanRegions(char *, size_t) { GCAssert(false); return false; }
bool GCHeap::DecommitMemoryThatMaySpanRegions(char *, size_t) { GCAssert(false); return false; }
}
|
Fix the unused/untested GCHeapGeneric.cpp, need to address this somehow
|
Fix the unused/untested GCHeapGeneric.cpp, need to address this somehow
|
C++
|
mpl-2.0
|
pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux,pnkfelix/tamarin-redux,pnkfelix/tamarin-redux,pfgenyun/tamarin-redux,pfgenyun/tamarin-redux
|
7a6437e51f708eda7eba98a7ad2250ada4b0f198
|
src/mlpack/core/math/random.hpp
|
src/mlpack/core/math/random.hpp
|
/**
* @file random.hpp
*
* Miscellaneous math random-related routines.
*/
#ifndef __MLPACK_CORE_MATH_RANDOM_HPP
#define __MLPACK_CORE_MATH_RANDOM_HPP
#include <stdlib.h>
#include <math.h>
#include <float.h>
#include <stdint.h>
#include <boost/random.hpp>
namespace mlpack {
namespace math /** Miscellaneous math routines. */ {
// Annoying Boost versioning issues.
#include <boost/version.hpp>
#if BOOST_VERSION >= 104700
// Global random object.
extern boost::random::mt19937 randGen;
// Global uniform distribution.
extern boost::random::uniform_01<> randUniformDist;
// Global normal distribution.
extern boost::random::normal_distribution<> randNormalDist;
#else
// Global random object.
extern boost::mt19937 randGen;
#if BOOST_VERSION >= 103900
// Global uniform distribution.
extern boost::uniform_01<> randUniformDist;
#else
// Pre-1.39 Boost.Random did not give default template parameter values.
extern boost::uniform_01<boost::mt19937, double> randUniformDist;
#endif
// Global normal distribution.
extern boost::normal_distribution<> randNormalDist;
#endif
/**
* Set the random seed used by the random functions (Random() and RandInt()).
* The seed is casted to a 32-bit integer before being given to the random
* number generator, but a size_t is taken as a parameter for API consistency.
*
* @param seed Seed for the random number generator.
*/
inline void RandomSeed(const size_t seed)
{
randGen.seed((uint32_t) seed);
srand((unsigned int) seed);
}
/**
* Generates a uniform random number between 0 and 1.
*/
inline double Random()
{
#if BOOST_VERSION >= 103900
return randUniformDist(randGen);
#else
// Before Boost 1.39, we did not give the random object when we wanted a
// random number; that gets given at construction time.
return randUniformDist();
#endif
}
/**
* Generates a uniform random number in the specified range.
*/
inline double Random(const double lo, const double hi)
{
#if BOOST_VERSION >= 103900
return lo + (hi - lo) * randUniformDist(randGen);
#else
// Before Boost 1.39, we did not give the random object when we wanted a
// random number; that gets given at construction time.
return lo + (hi - lo) * randUniformDist();
#endif
}
/**
* Generates a uniform random integer.
*/
inline int RandInt(const int hiExclusive)
{
#if BOOST_VERSION >= 103900
return (int) std::floor((double) hiExclusive * randUniformDist(randGen));
#else
// Before Boost 1.39, we did not give the random object when we wanted a
// random number; that gets given at construction time.
return (int) std::floor((double) hiExclusive * randUniformDist());
#endif
}
/**
* Generates a uniform random integer.
*/
inline int RandInt(const int lo, const int hiExclusive)
{
#if BOOST_VERSION >= 103900
return lo + (int) std::floor((double) (hiExclusive - lo)
* randUniformDist(randGen));
#else
// Before Boost 1.39, we did not give the random object when we wanted a
// random number; that gets given at construction time.
return lo + (int) std::floor((double) (hiExclusive - lo)
* randUniformDist());
#endif
}
/**
* Generates a normally distributed random number with mean 0 and variance 1.
*/
inline double RandNormal()
{
return randNormalDist(randGen);
}
/**
* Generates a normally distributed random number with specified mean and
* variance.
*
* @param mean Mean of distribution.
* @param variance Variance of distribution.
*/
inline double RandNormal(const double mean, const double variance)
{
return variance * randNormalDist(randGen) + mean;
}
}; // namespace math
}; // namespace mlpack
#endif // __MLPACK_CORE_MATH_MATH_LIB_HPP
|
/**
* @file random.hpp
*
* Miscellaneous math random-related routines.
*/
#ifndef __MLPACK_CORE_MATH_RANDOM_HPP
#define __MLPACK_CORE_MATH_RANDOM_HPP
#include <mlpack/prereqs.hpp>
#include <boost/random.hpp>
namespace mlpack {
namespace math /** Miscellaneous math routines. */ {
// Annoying Boost versioning issues.
#include <boost/version.hpp>
#if BOOST_VERSION >= 104700
// Global random object.
extern boost::random::mt19937 randGen;
// Global uniform distribution.
extern boost::random::uniform_01<> randUniformDist;
// Global normal distribution.
extern boost::random::normal_distribution<> randNormalDist;
#else
// Global random object.
extern boost::mt19937 randGen;
#if BOOST_VERSION >= 103900
// Global uniform distribution.
extern boost::uniform_01<> randUniformDist;
#else
// Pre-1.39 Boost.Random did not give default template parameter values.
extern boost::uniform_01<boost::mt19937, double> randUniformDist;
#endif
// Global normal distribution.
extern boost::normal_distribution<> randNormalDist;
#endif
/**
* Set the random seed used by the random functions (Random() and RandInt()).
* The seed is casted to a 32-bit integer before being given to the random
* number generator, but a size_t is taken as a parameter for API consistency.
*
* @param seed Seed for the random number generator.
*/
inline void RandomSeed(const size_t seed)
{
randGen.seed((uint32_t) seed);
srand((unsigned int) seed);
}
/**
* Generates a uniform random number between 0 and 1.
*/
inline double Random()
{
#if BOOST_VERSION >= 103900
return randUniformDist(randGen);
#else
// Before Boost 1.39, we did not give the random object when we wanted a
// random number; that gets given at construction time.
return randUniformDist();
#endif
}
/**
* Generates a uniform random number in the specified range.
*/
inline double Random(const double lo, const double hi)
{
#if BOOST_VERSION >= 103900
return lo + (hi - lo) * randUniformDist(randGen);
#else
// Before Boost 1.39, we did not give the random object when we wanted a
// random number; that gets given at construction time.
return lo + (hi - lo) * randUniformDist();
#endif
}
/**
* Generates a uniform random integer.
*/
inline int RandInt(const int hiExclusive)
{
#if BOOST_VERSION >= 103900
return (int) std::floor((double) hiExclusive * randUniformDist(randGen));
#else
// Before Boost 1.39, we did not give the random object when we wanted a
// random number; that gets given at construction time.
return (int) std::floor((double) hiExclusive * randUniformDist());
#endif
}
/**
* Generates a uniform random integer.
*/
inline int RandInt(const int lo, const int hiExclusive)
{
#if BOOST_VERSION >= 103900
return lo + (int) std::floor((double) (hiExclusive - lo)
* randUniformDist(randGen));
#else
// Before Boost 1.39, we did not give the random object when we wanted a
// random number; that gets given at construction time.
return lo + (int) std::floor((double) (hiExclusive - lo)
* randUniformDist());
#endif
}
/**
* Generates a normally distributed random number with mean 0 and variance 1.
*/
inline double RandNormal()
{
return randNormalDist(randGen);
}
/**
* Generates a normally distributed random number with specified mean and
* variance.
*
* @param mean Mean of distribution.
* @param variance Variance of distribution.
*/
inline double RandNormal(const double mean, const double variance)
{
return variance * randNormalDist(randGen) + mean;
}
}; // namespace math
}; // namespace mlpack
#endif // __MLPACK_CORE_MATH_MATH_LIB_HPP
|
Remove unnecessary includes.
|
Remove unnecessary includes.
|
C++
|
bsd-3-clause
|
thirdwing/mlpack,thirdwing/mlpack,trungda/mlpack,minhpqn/mlpack,minhpqn/mlpack,trungda/mlpack,bmswgnp/mlpack,Azizou/mlpack,stereomatchingkiss/mlpack,darcyliu/mlpack,stereomatchingkiss/mlpack,BookChan/mlpack,erubboli/mlpack,datachand/mlpack,Azizou/mlpack,chenmoshushi/mlpack,palashahuja/mlpack,chenmoshushi/mlpack,stereomatchingkiss/mlpack,ersanliqiao/mlpack,datachand/mlpack,ersanliqiao/mlpack,lezorich/mlpack,ajjl/mlpack,ranjan1990/mlpack,trungda/mlpack,thirdwing/mlpack,theranger/mlpack,ranjan1990/mlpack,palashahuja/mlpack,minhpqn/mlpack,BookChan/mlpack,theranger/mlpack,lezorich/mlpack,bmswgnp/mlpack,ajjl/mlpack,erubboli/mlpack,Azizou/mlpack,palashahuja/mlpack,ersanliqiao/mlpack,lezorich/mlpack,ajjl/mlpack,bmswgnp/mlpack,chenmoshushi/mlpack,ranjan1990/mlpack,BookChan/mlpack,darcyliu/mlpack,erubboli/mlpack,darcyliu/mlpack,theranger/mlpack,datachand/mlpack
|
3c9e520f007b227b78ac542ae63226bd0586a963
|
app/TimerMessage.cpp
|
app/TimerMessage.cpp
|
#include <TimerMessage.h>
#include <QDebug>
TimerMessage::TimerMessage(QObject *parent) :
QObject(parent),
m_pTimer(new QTimer(this)),
m_counter(0)
{
connect(m_pTimer, SIGNAL(timeout()), this, SLOT(printCounter()) );
m_pTimer->setInterval(1000);
m_pTimer->start();
}
void TimerMessage::printCounter()
{
print(QString("Message counter # %1").arg(m_counter++));
if(m_counter >= 1024)
m_counter = 0;
}
void TimerMessage::print(const QString &msg)
{
qDebug() << qPrintable(msg);
}
|
#include <TimerMessage.h>
#include <QDebug>
TimerMessage::TimerMessage(QObject *parent) :
QObject(parent),
m_pTimer(new QTimer(this)),
m_counter(0)
{
connect(m_pTimer, SIGNAL(timeout()), this, SLOT(printCounter()) );
m_pTimer->setInterval(750);
m_pTimer->start();
}
void TimerMessage::printCounter()
{
print(QString("Message counter # %1").arg(m_counter++));
if(m_counter >= 1024)
m_counter = 0;
}
void TimerMessage::print(const QString &msg)
{
qDebug() << qPrintable(msg);
}
|
Test them all. Fix interval
|
Test them all. Fix interval
|
C++
|
mit
|
lomedil/betterlogger
|
09e0d3ffdffd87e9efecbf5b4c6d24224153fdea
|
src/codegen/expression/null_check_translator.cpp
|
src/codegen/expression/null_check_translator.cpp
|
//===----------------------------------------------------------------------===//
//
// Peloton
//
// null_check_translator.cpp
//
// Identification: src/codegen/expression/null_check_translator.cpp
//
// Copyright (c) 2015-2017, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "codegen/expression/null_checker_translator.h"
#include "codegen/type/boolean_type.h"
#include "codegen/type/type_system.h"
#include "expression/operator_expression.h"
namespace peloton {
namespace codegen {
// Constructor
NullCheckTranslator::NullCheckTranslator(
const expression::OperatorExpression &null_check, CompilationContext &ctx)
: ExpressionTranslator(null_check, ctx) {
PL_ASSERT(null_check.GetChildrenSize() == 1);
}
Value NullCheckTranslator::DeriveValue(CodeGen &codegen,
RowBatch::Row &row) const {
const auto &null_check = GetExpressionAs<expression::OperatorExpression>();
Value val = row.DeriveValue(codegen, *null_check.GetChild(0));
switch (null_check.GetExpressionType()) {
case ExpressionType::OPERATOR_IS_NULL:
return Value{type::Boolean::Instance(), val.IsNull(codegen)};
case ExpressionType::OPERATOR_IS_NOT_NULL:
return Value{type::Boolean::Instance(), val.IsNotNull(codegen)};
default: {
throw Exception(
"Null_check expression has invalid type for translation: " +
ExpressionTypeToString(null_check.GetExpressionType()));
}
}
}
} // namespace codegen
} // namespace peloton
|
//===----------------------------------------------------------------------===//
//
// Peloton
//
// null_check_translator.cpp
//
// Identification: src/codegen/expression/null_check_translator.cpp
//
// Copyright (c) 2015-2017, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "codegen/expression/null_check_translator.h"
#include "codegen/type/boolean_type.h"
#include "codegen/type/type_system.h"
#include "expression/operator_expression.h"
namespace peloton {
namespace codegen {
// Constructor
NullCheckTranslator::NullCheckTranslator(
const expression::OperatorExpression &null_check, CompilationContext &ctx)
: ExpressionTranslator(null_check, ctx) {
PL_ASSERT(null_check.GetChildrenSize() == 1);
}
Value NullCheckTranslator::DeriveValue(CodeGen &codegen,
RowBatch::Row &row) const {
const auto &null_check = GetExpressionAs<expression::OperatorExpression>();
Value val = row.DeriveValue(codegen, *null_check.GetChild(0));
switch (null_check.GetExpressionType()) {
case ExpressionType::OPERATOR_IS_NULL:
return Value{type::Boolean::Instance(), val.IsNull(codegen)};
case ExpressionType::OPERATOR_IS_NOT_NULL:
return Value{type::Boolean::Instance(), val.IsNotNull(codegen)};
default: {
throw Exception(
"Null_check expression has invalid type for translation: " +
ExpressionTypeToString(null_check.GetExpressionType()));
}
}
}
} // namespace codegen
} // namespace peloton
|
Correct name of included header file.
|
Correct name of included header file.
|
C++
|
apache-2.0
|
PauloAmora/peloton,yingjunwu/peloton,malin1993ml/peloton,malin1993ml/peloton,yingjunwu/peloton,PauloAmora/peloton,cmu-db/peloton,haojin2/peloton,seojungmin/peloton,seojungmin/peloton,seojungmin/peloton,yingjunwu/peloton,apavlo/peloton,cmu-db/peloton,cmu-db/peloton,cmu-db/peloton,seojungmin/peloton,cmu-db/peloton,haojin2/peloton,malin1993ml/peloton,malin1993ml/peloton,apavlo/peloton,apavlo/peloton,malin1993ml/peloton,haojin2/peloton,vittvolt/peloton,PauloAmora/peloton,apavlo/peloton,yingjunwu/peloton,PauloAmora/peloton,vittvolt/peloton,PauloAmora/peloton,haojin2/peloton,vittvolt/peloton,apavlo/peloton,haojin2/peloton,apavlo/peloton,haojin2/peloton,yingjunwu/peloton,cmu-db/peloton,seojungmin/peloton,PauloAmora/peloton,vittvolt/peloton,yingjunwu/peloton,vittvolt/peloton,vittvolt/peloton,seojungmin/peloton,malin1993ml/peloton
|
da4a555bc63a0725068ef8ad2fc4d18bde5e115a
|
core/test/async/callback_test.cpp
|
core/test/async/callback_test.cpp
|
/*
*
* callback_test
* ledger-core
*
* Created by Pierre Pollastri on 28/09/2016.
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ledger
*
* 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 <gtest/gtest.h>
#include <ledger/core/async/Callback.hpp>
#include <future>
class TestExecutionContext : public ledger::core::ExecutionContext {
public:
virtual void execute(const std::function<void()> &closure) override {
std::async([closure]() {
closure();
});
}
virtual void reportError(std::exception exception) override {
}
};
auto context = new TestExecutionContext();
void call(ledger::core::Callback<int> cb, int result) {
//cb(result);
}
TEST(Callback, PThreadTest) {
std::promise<int> p;
// auto cb = ledger::core::callback(context, [] () {
// std::cout << "Hello from thread" << std::endl;
// return;
// });
p.get_future().wait();
}
|
/*
*
* callback_test
* ledger-core
*
* Created by Pierre Pollastri on 28/09/2016.
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Ledger
*
* 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 <gtest/gtest.h>
#include <ledger/core/async/Callback.hpp>
#include <future>
class TestExecutionContext : public ledger::core::ExecutionContext {
public:
virtual void execute(const std::function<void()> &closure) override {
}
virtual void reportError(std::exception exception) override {
}
};
auto context = new TestExecutionContext();
void call(ledger::core::Callback<int> cb, int result) {
//cb(result);
}
TEST(Callback, PThreadTest) {
}
|
Update travis
|
Update travis
|
C++
|
mit
|
LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core,LedgerHQ/lib-ledger-core
|
ae2679b1bf2367be471e528b870c4311cb9ea131
|
234-Palindrome_Linked_List-e.cpp
|
234-Palindrome_Linked_List-e.cpp
|
// Given a singly linked list, determine if it is a palindrome.
// Follow up:
// Could you do it in O(n) time and O(1) space?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool isPalindrome(ListNode *head) {
}
};
|
// Given a singly linked list, determine if it is a palindrome.
// Follow up:
// Could you do it in O(n) time and O(1) space?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
// just follow regular reverse list method
// ref 206
class Solution {
ListNode *reverseList(ListNode *head) {
ListNode *temp = NULL;
while (head) {
std::swap(temp, head->next);
std::swap(head, temp);
}
return temp;
}
public:
bool isPalindrome(ListNode *head) {
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
fast = fast->next->next;
slow = slow->next;
}
slow = reverseList(slow);
while (slow) {
if (slow->val != head->val)
return 0;
slow = slow->next;
head = head->next;
}
return 1;
}
};
|
update 234
|
update 234
|
C++
|
bsd-3-clause
|
ysmiles/leetcode-cpp,ysmiles/leetcode-cpp
|
950f62c1ccff7cf59c220e9016ead0845767e546
|
os/win/color_space.cpp
|
os/win/color_space.cpp
|
// LAF OS Library
// Copyright (C) 2018 Igara Studio S.A.
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "os/osx/color_space.h"
#include "base/file_content.h"
#include "base/fs.h"
#include "base/string.h"
#include "os/system.h"
#include <windows.h>
namespace os {
std::string get_hmonitor_icc_filename(HMONITOR monitor)
{
std::string iccFilename;
MONITORINFOEX mi;
ZeroMemory(&mi, sizeof(MONITORINFOEX));
mi.cbSize = sizeof(MONITORINFOEX);
GetMonitorInfo(monitor, &mi);
HDC hdc = CreateDC(mi.szDevice, nullptr, nullptr, nullptr);
if (hdc) {
DWORD length = MAX_PATH;
std::vector<TCHAR> str(length+1);
if (GetICMProfile(hdc, &length, &str[0]))
iccFilename = base::to_utf8(&str[0]);
DeleteDC(hdc);
}
return iccFilename;
}
os::ColorSpacePtr get_colorspace_from_icc_file(const std::string& iccFilename)
{
auto buf = base::read_file_content(iccFilename);
auto osCS = os::instance()->createColorSpace(gfx::ColorSpace::MakeICC(std::move(buf)));
if (osCS) {
osCS->gfxColorSpace()
->setName("Display Profile: " +
base::get_file_title(iccFilename));
}
return osCS;
}
os::ColorSpacePtr get_hmonitor_colorspace(HMONITOR monitor)
{
os::ColorSpacePtr osCS;
std::string filename = get_hmonitor_icc_filename(monitor);
if (!filename.empty())
osCS = get_colorspace_from_icc_file(filename);
return osCS;
}
static BOOL list_display_colorspaces_enumproc(HMONITOR monitor,
HDC hdc, LPRECT rc,
LPARAM data)
{
auto list = (std::vector<os::ColorSpacePtr>*)data;
auto osCS = get_hmonitor_colorspace(monitor);
if (osCS)
list->push_back(osCS);
return TRUE;
}
void list_display_colorspaces(std::vector<os::ColorSpacePtr>& list)
{
EnumDisplayMonitors(
nullptr, nullptr,
list_display_colorspaces_enumproc,
(LPARAM)&list);
}
} // namespace os
|
// LAF OS Library
// Copyright (C) 2018 Igara Studio S.A.
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "os/osx/color_space.h"
#include "base/file_content.h"
#include "base/fs.h"
#include "base/string.h"
#include "os/system.h"
#include <windows.h>
namespace os {
std::string get_hmonitor_icc_filename(HMONITOR monitor)
{
std::string iccFilename;
MONITORINFOEX mi;
ZeroMemory(&mi, sizeof(MONITORINFOEX));
mi.cbSize = sizeof(MONITORINFOEX);
GetMonitorInfo(monitor, &mi);
HDC hdc = CreateDC(mi.szDevice, nullptr, nullptr, nullptr);
if (hdc) {
DWORD length = MAX_PATH;
std::vector<TCHAR> str(length+1);
if (GetICMProfile(hdc, &length, &str[0]))
iccFilename = base::to_utf8(&str[0]);
DeleteDC(hdc);
}
return iccFilename;
}
os::ColorSpacePtr get_colorspace_from_icc_file(const std::string& iccFilename)
{
auto buf = base::read_file_content(iccFilename);
auto osCS = os::instance()->createColorSpace(gfx::ColorSpace::MakeICC(std::move(buf)));
if (osCS) {
osCS->gfxColorSpace()
->setName("Display Profile: " +
base::get_file_title(iccFilename));
}
return osCS;
}
os::ColorSpacePtr get_hmonitor_colorspace(HMONITOR monitor)
{
os::ColorSpacePtr osCS;
std::string filename = get_hmonitor_icc_filename(monitor);
if (!filename.empty())
osCS = get_colorspace_from_icc_file(filename);
return osCS;
}
static BOOL CALLBACK list_display_colorspaces_enumproc(HMONITOR monitor,
HDC hdc, LPRECT rc,
LPARAM data)
{
auto list = (std::vector<os::ColorSpacePtr>*)data;
auto osCS = get_hmonitor_colorspace(monitor);
if (osCS)
list->push_back(osCS);
return TRUE;
}
void list_display_colorspaces(std::vector<os::ColorSpacePtr>& list)
{
EnumDisplayMonitors(
nullptr, nullptr,
list_display_colorspaces_enumproc,
(LPARAM)&list);
}
} // namespace os
|
Fix compilation on Windows/MSVC for 32-bit CPUs
|
Fix compilation on Windows/MSVC for 32-bit CPUs
|
C++
|
mit
|
aseprite/laf,aseprite/laf
|
7108cc5f2b1408299e711d76d7a555b09518b8de
|
atom/browser/api/atom_api_protocol.cc
|
atom/browser/api/atom_api_protocol.cc
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/api/atom_api_protocol.h"
#include "atom/browser/atom_browser_client.h"
#include "atom/browser/atom_browser_context.h"
#include "atom/browser/atom_browser_main_parts.h"
#include "atom/browser/net/url_request_async_asar_job.h"
#include "atom/browser/net/url_request_buffer_job.h"
#include "atom/browser/net/url_request_fetch_job.h"
#include "atom/browser/net/url_request_string_job.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/net_converter.h"
#include "atom/common/node_includes.h"
#include "atom/common/options_switches.h"
#include "base/command_line.h"
#include "base/strings/string_util.h"
#include "native_mate/dictionary.h"
#include "url/url_util.h"
using content::BrowserThread;
namespace atom {
namespace api {
Protocol::Protocol(v8::Isolate* isolate, AtomBrowserContext* browser_context)
: request_context_getter_(browser_context->GetRequestContext()),
job_factory_(browser_context->job_factory()) {
CHECK(job_factory_);
Init(isolate);
}
void Protocol::RegisterServiceWorkerSchemes(
const std::vector<std::string>& schemes) {
atom::AtomBrowserClient::SetCustomServiceWorkerSchemes(schemes);
}
void Protocol::UnregisterProtocol(
const std::string& scheme, mate::Arguments* args) {
CompletionCallback callback;
args->GetNext(&callback);
content::BrowserThread::PostTaskAndReplyWithResult(
content::BrowserThread::IO, FROM_HERE,
base::Bind(&Protocol::UnregisterProtocolInIO,
base::Unretained(this), scheme),
base::Bind(&Protocol::OnIOCompleted,
base::Unretained(this), callback));
}
Protocol::ProtocolError Protocol::UnregisterProtocolInIO(
const std::string& scheme) {
if (!job_factory_->HasProtocolHandler(scheme))
return PROTOCOL_NOT_REGISTERED;
job_factory_->SetProtocolHandler(scheme, nullptr);
return PROTOCOL_OK;
}
void Protocol::IsProtocolHandled(const std::string& scheme,
const BooleanCallback& callback) {
content::BrowserThread::PostTaskAndReplyWithResult(
content::BrowserThread::IO, FROM_HERE,
base::Bind(&Protocol::IsProtocolHandledInIO,
base::Unretained(this), scheme),
callback);
}
bool Protocol::IsProtocolHandledInIO(const std::string& scheme) {
return job_factory_->IsHandledProtocol(scheme);
}
void Protocol::UninterceptProtocol(
const std::string& scheme, mate::Arguments* args) {
CompletionCallback callback;
args->GetNext(&callback);
content::BrowserThread::PostTaskAndReplyWithResult(
content::BrowserThread::IO, FROM_HERE,
base::Bind(&Protocol::UninterceptProtocolInIO,
base::Unretained(this), scheme),
base::Bind(&Protocol::OnIOCompleted,
base::Unretained(this), callback));
}
Protocol::ProtocolError Protocol::UninterceptProtocolInIO(
const std::string& scheme) {
if (!original_protocols_.contains(scheme))
return PROTOCOL_NOT_INTERCEPTED;
job_factory_->ReplaceProtocol(scheme,
original_protocols_.take_and_erase(scheme));
return PROTOCOL_OK;
}
void Protocol::OnIOCompleted(
const CompletionCallback& callback, ProtocolError error) {
// The completion callback is optional.
if (callback.is_null())
return;
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
if (error == PROTOCOL_OK) {
callback.Run(v8::Null(isolate()));
} else {
std::string str = ErrorCodeToString(error);
callback.Run(v8::Exception::Error(mate::StringToV8(isolate(), str)));
}
}
std::string Protocol::ErrorCodeToString(ProtocolError error) {
switch (error) {
case PROTOCOL_FAIL: return "Failed to manipulate protocol factory";
case PROTOCOL_REGISTERED: return "The scheme has been registred";
case PROTOCOL_NOT_REGISTERED: return "The scheme has not been registred";
case PROTOCOL_INTERCEPTED: return "The scheme has been intercepted";
case PROTOCOL_NOT_INTERCEPTED: return "The scheme has not been intercepted";
default: return "Unexpected error";
}
}
// static
mate::Handle<Protocol> Protocol::Create(
v8::Isolate* isolate, AtomBrowserContext* browser_context) {
return mate::CreateHandle(isolate, new Protocol(isolate, browser_context));
}
// static
void Protocol::BuildPrototype(
v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> prototype) {
mate::ObjectTemplateBuilder(isolate, prototype)
.SetMethod("registerServiceWorkerSchemes",
&Protocol::RegisterServiceWorkerSchemes)
.SetMethod("registerStringProtocol",
&Protocol::RegisterProtocol<URLRequestStringJob>)
.SetMethod("registerBufferProtocol",
&Protocol::RegisterProtocol<URLRequestBufferJob>)
.SetMethod("registerFileProtocol",
&Protocol::RegisterProtocol<URLRequestAsyncAsarJob>)
.SetMethod("registerHttpProtocol",
&Protocol::RegisterProtocol<URLRequestFetchJob>)
.SetMethod("unregisterProtocol", &Protocol::UnregisterProtocol)
.SetMethod("isProtocolHandled", &Protocol::IsProtocolHandled)
.SetMethod("interceptStringProtocol",
&Protocol::InterceptProtocol<URLRequestStringJob>)
.SetMethod("interceptBufferProtocol",
&Protocol::InterceptProtocol<URLRequestBufferJob>)
.SetMethod("interceptFileProtocol",
&Protocol::InterceptProtocol<URLRequestAsyncAsarJob>)
.SetMethod("interceptHttpProtocol",
&Protocol::InterceptProtocol<URLRequestFetchJob>)
.SetMethod("uninterceptProtocol", &Protocol::UninterceptProtocol);
}
} // namespace api
} // namespace atom
namespace {
void RegisterStandardSchemes(
const std::vector<std::string>& schemes) {
for (const auto& scheme : schemes)
url::AddStandardScheme(scheme.c_str(), url::SCHEME_WITHOUT_PORT);
auto command_line = base::CommandLine::ForCurrentProcess();
command_line->AppendSwitchASCII(atom::switches::kStandardSchemes,
base::JoinString(schemes, ","));
}
mate::Handle<atom::api::Protocol> CreateProtocol(v8::Isolate* isolate) {
auto browser_context = static_cast<atom::AtomBrowserContext*>(
atom::AtomBrowserMainParts::Get()->browser_context());
return atom::api::Protocol::Create(isolate, browser_context);
}
void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
v8::Local<v8::Context> context, void* priv) {
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.SetMethod("createProtocolObject", base::Bind(&CreateProtocol, isolate));
dict.SetMethod("registerStandardSchemes", &RegisterStandardSchemes);
}
} // namespace
NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_protocol, Initialize)
|
// Copyright (c) 2013 GitHub, Inc.
// Use of this source code is governed by the MIT license that can be
// found in the LICENSE file.
#include "atom/browser/api/atom_api_protocol.h"
#include "atom/browser/atom_browser_client.h"
#include "atom/browser/atom_browser_context.h"
#include "atom/browser/atom_browser_main_parts.h"
#include "atom/browser/net/url_request_async_asar_job.h"
#include "atom/browser/net/url_request_buffer_job.h"
#include "atom/browser/net/url_request_fetch_job.h"
#include "atom/browser/net/url_request_string_job.h"
#include "atom/common/native_mate_converters/callback.h"
#include "atom/common/native_mate_converters/net_converter.h"
#include "atom/common/node_includes.h"
#include "atom/common/options_switches.h"
#include "base/command_line.h"
#include "base/strings/string_util.h"
#include "content/public/browser/child_process_security_policy.h"
#include "native_mate/dictionary.h"
#include "url/url_util.h"
using content::BrowserThread;
namespace atom {
namespace api {
Protocol::Protocol(v8::Isolate* isolate, AtomBrowserContext* browser_context)
: request_context_getter_(browser_context->GetRequestContext()),
job_factory_(browser_context->job_factory()) {
CHECK(job_factory_);
Init(isolate);
}
void Protocol::RegisterServiceWorkerSchemes(
const std::vector<std::string>& schemes) {
atom::AtomBrowserClient::SetCustomServiceWorkerSchemes(schemes);
}
void Protocol::UnregisterProtocol(
const std::string& scheme, mate::Arguments* args) {
CompletionCallback callback;
args->GetNext(&callback);
content::BrowserThread::PostTaskAndReplyWithResult(
content::BrowserThread::IO, FROM_HERE,
base::Bind(&Protocol::UnregisterProtocolInIO,
base::Unretained(this), scheme),
base::Bind(&Protocol::OnIOCompleted,
base::Unretained(this), callback));
}
Protocol::ProtocolError Protocol::UnregisterProtocolInIO(
const std::string& scheme) {
if (!job_factory_->HasProtocolHandler(scheme))
return PROTOCOL_NOT_REGISTERED;
job_factory_->SetProtocolHandler(scheme, nullptr);
return PROTOCOL_OK;
}
void Protocol::IsProtocolHandled(const std::string& scheme,
const BooleanCallback& callback) {
content::BrowserThread::PostTaskAndReplyWithResult(
content::BrowserThread::IO, FROM_HERE,
base::Bind(&Protocol::IsProtocolHandledInIO,
base::Unretained(this), scheme),
callback);
}
bool Protocol::IsProtocolHandledInIO(const std::string& scheme) {
return job_factory_->IsHandledProtocol(scheme);
}
void Protocol::UninterceptProtocol(
const std::string& scheme, mate::Arguments* args) {
CompletionCallback callback;
args->GetNext(&callback);
content::BrowserThread::PostTaskAndReplyWithResult(
content::BrowserThread::IO, FROM_HERE,
base::Bind(&Protocol::UninterceptProtocolInIO,
base::Unretained(this), scheme),
base::Bind(&Protocol::OnIOCompleted,
base::Unretained(this), callback));
}
Protocol::ProtocolError Protocol::UninterceptProtocolInIO(
const std::string& scheme) {
if (!original_protocols_.contains(scheme))
return PROTOCOL_NOT_INTERCEPTED;
job_factory_->ReplaceProtocol(scheme,
original_protocols_.take_and_erase(scheme));
return PROTOCOL_OK;
}
void Protocol::OnIOCompleted(
const CompletionCallback& callback, ProtocolError error) {
// The completion callback is optional.
if (callback.is_null())
return;
v8::Locker locker(isolate());
v8::HandleScope handle_scope(isolate());
if (error == PROTOCOL_OK) {
callback.Run(v8::Null(isolate()));
} else {
std::string str = ErrorCodeToString(error);
callback.Run(v8::Exception::Error(mate::StringToV8(isolate(), str)));
}
}
std::string Protocol::ErrorCodeToString(ProtocolError error) {
switch (error) {
case PROTOCOL_FAIL: return "Failed to manipulate protocol factory";
case PROTOCOL_REGISTERED: return "The scheme has been registred";
case PROTOCOL_NOT_REGISTERED: return "The scheme has not been registred";
case PROTOCOL_INTERCEPTED: return "The scheme has been intercepted";
case PROTOCOL_NOT_INTERCEPTED: return "The scheme has not been intercepted";
default: return "Unexpected error";
}
}
// static
mate::Handle<Protocol> Protocol::Create(
v8::Isolate* isolate, AtomBrowserContext* browser_context) {
return mate::CreateHandle(isolate, new Protocol(isolate, browser_context));
}
// static
void Protocol::BuildPrototype(
v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> prototype) {
mate::ObjectTemplateBuilder(isolate, prototype)
.SetMethod("registerServiceWorkerSchemes",
&Protocol::RegisterServiceWorkerSchemes)
.SetMethod("registerStringProtocol",
&Protocol::RegisterProtocol<URLRequestStringJob>)
.SetMethod("registerBufferProtocol",
&Protocol::RegisterProtocol<URLRequestBufferJob>)
.SetMethod("registerFileProtocol",
&Protocol::RegisterProtocol<URLRequestAsyncAsarJob>)
.SetMethod("registerHttpProtocol",
&Protocol::RegisterProtocol<URLRequestFetchJob>)
.SetMethod("unregisterProtocol", &Protocol::UnregisterProtocol)
.SetMethod("isProtocolHandled", &Protocol::IsProtocolHandled)
.SetMethod("interceptStringProtocol",
&Protocol::InterceptProtocol<URLRequestStringJob>)
.SetMethod("interceptBufferProtocol",
&Protocol::InterceptProtocol<URLRequestBufferJob>)
.SetMethod("interceptFileProtocol",
&Protocol::InterceptProtocol<URLRequestAsyncAsarJob>)
.SetMethod("interceptHttpProtocol",
&Protocol::InterceptProtocol<URLRequestFetchJob>)
.SetMethod("uninterceptProtocol", &Protocol::UninterceptProtocol);
}
} // namespace api
} // namespace atom
namespace {
void RegisterStandardSchemes(
const std::vector<std::string>& schemes) {
auto policy = content::ChildProcessSecurityPolicy::GetInstance();
for (const auto& scheme : schemes) {
url::AddStandardScheme(scheme.c_str(), url::SCHEME_WITHOUT_PORT);
policy->RegisterWebSafeScheme(scheme);
}
auto command_line = base::CommandLine::ForCurrentProcess();
command_line->AppendSwitchASCII(atom::switches::kStandardSchemes,
base::JoinString(schemes, ","));
}
mate::Handle<atom::api::Protocol> CreateProtocol(v8::Isolate* isolate) {
auto browser_context = static_cast<atom::AtomBrowserContext*>(
atom::AtomBrowserMainParts::Get()->browser_context());
return atom::api::Protocol::Create(isolate, browser_context);
}
void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused,
v8::Local<v8::Context> context, void* priv) {
v8::Isolate* isolate = context->GetIsolate();
mate::Dictionary dict(isolate, exports);
dict.SetMethod("createProtocolObject", base::Bind(&CreateProtocol, isolate));
dict.SetMethod("registerStandardSchemes", &RegisterStandardSchemes);
}
} // namespace
NODE_MODULE_CONTEXT_AWARE_BUILTIN(atom_browser_protocol, Initialize)
|
Mark standard scheme as safe scheme
|
Mark standard scheme as safe scheme
|
C++
|
mit
|
thomsonreuters/electron,jhen0409/electron,twolfson/electron,miniak/electron,rajatsingla28/electron,aliib/electron,gabriel/electron,thompsonemerson/electron,biblerule/UMCTelnetHub,gabriel/electron,biblerule/UMCTelnetHub,electron/electron,jhen0409/electron,seanchas116/electron,tonyganch/electron,gerhardberger/electron,voidbridge/electron,gerhardberger/electron,aliib/electron,Gerhut/electron,tinydew4/electron,aichingm/electron,thomsonreuters/electron,thomsonreuters/electron,MaxWhere/electron,aichingm/electron,shiftkey/electron,MaxWhere/electron,tonyganch/electron,gabriel/electron,the-ress/electron,renaesop/electron,jhen0409/electron,bpasero/electron,renaesop/electron,twolfson/electron,noikiy/electron,rreimann/electron,dongjoon-hyun/electron,bpasero/electron,brave/muon,wan-qy/electron,tonyganch/electron,seanchas116/electron,noikiy/electron,gerhardberger/electron,bbondy/electron,the-ress/electron,kokdemo/electron,dongjoon-hyun/electron,bpasero/electron,jhen0409/electron,tonyganch/electron,noikiy/electron,leethomas/electron,brenca/electron,noikiy/electron,brave/electron,rreimann/electron,bpasero/electron,seanchas116/electron,leethomas/electron,voidbridge/electron,miniak/electron,brave/electron,joaomoreno/atom-shell,minggo/electron,bpasero/electron,twolfson/electron,twolfson/electron,leethomas/electron,electron/electron,bbondy/electron,the-ress/electron,bbondy/electron,electron/electron,rajatsingla28/electron,Floato/electron,shiftkey/electron,tinydew4/electron,Gerhut/electron,rreimann/electron,gerhardberger/electron,kokdemo/electron,jhen0409/electron,rreimann/electron,tinydew4/electron,brenca/electron,brenca/electron,gerhardberger/electron,MaxWhere/electron,shiftkey/electron,kokdemo/electron,rajatsingla28/electron,bbondy/electron,noikiy/electron,the-ress/electron,thompsonemerson/electron,dongjoon-hyun/electron,aichingm/electron,seanchas116/electron,kokdemo/electron,renaesop/electron,leethomas/electron,leethomas/electron,Floato/electron,Floato/electron,deed02392/electron,twolfson/electron,seanchas116/electron,biblerule/UMCTelnetHub,gabriel/electron,aliib/electron,tinydew4/electron,posix4e/electron,posix4e/electron,voidbridge/electron,rreimann/electron,wan-qy/electron,deed02392/electron,gabriel/electron,deed02392/electron,posix4e/electron,wan-qy/electron,miniak/electron,joaomoreno/atom-shell,electron/electron,joaomoreno/atom-shell,MaxWhere/electron,biblerule/UMCTelnetHub,minggo/electron,posix4e/electron,Floato/electron,jhen0409/electron,aliib/electron,electron/electron,brave/muon,dongjoon-hyun/electron,brave/electron,tinydew4/electron,leethomas/electron,deed02392/electron,voidbridge/electron,shiftkey/electron,Gerhut/electron,thomsonreuters/electron,deed02392/electron,thomsonreuters/electron,aichingm/electron,tinydew4/electron,brenca/electron,bbondy/electron,MaxWhere/electron,miniak/electron,brave/electron,wan-qy/electron,shiftkey/electron,minggo/electron,aichingm/electron,brenca/electron,brave/muon,miniak/electron,twolfson/electron,voidbridge/electron,brave/electron,Gerhut/electron,minggo/electron,shiftkey/electron,electron/electron,thompsonemerson/electron,Floato/electron,posix4e/electron,thomsonreuters/electron,bbondy/electron,thompsonemerson/electron,thompsonemerson/electron,brave/muon,gabriel/electron,biblerule/UMCTelnetHub,the-ress/electron,rajatsingla28/electron,wan-qy/electron,kokdemo/electron,bpasero/electron,electron/electron,biblerule/UMCTelnetHub,aichingm/electron,minggo/electron,the-ress/electron,noikiy/electron,aliib/electron,gerhardberger/electron,brave/electron,tonyganch/electron,MaxWhere/electron,brenca/electron,minggo/electron,wan-qy/electron,thompsonemerson/electron,Floato/electron,brave/muon,voidbridge/electron,dongjoon-hyun/electron,rajatsingla28/electron,gerhardberger/electron,the-ress/electron,dongjoon-hyun/electron,rreimann/electron,miniak/electron,Gerhut/electron,posix4e/electron,rajatsingla28/electron,tonyganch/electron,deed02392/electron,renaesop/electron,renaesop/electron,seanchas116/electron,renaesop/electron,joaomoreno/atom-shell,brave/muon,joaomoreno/atom-shell,bpasero/electron,Gerhut/electron,joaomoreno/atom-shell,kokdemo/electron,aliib/electron
|
fe1fb1336b44bb073125aa4b42f12baa316e9fea
|
techlibs/xilinx/synth_xilinx.cc
|
techlibs/xilinx/synth_xilinx.cc
|
/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
bool check_label(bool &active, std::string run_from, std::string run_to, std::string label)
{
if (label == run_from)
active = true;
if (label == run_to)
active = false;
return active;
}
struct SynthXilinxPass : public Pass
{
SynthXilinxPass() : Pass("synth_xilinx", "synthesis for Xilinx FPGAs") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" synth_xilinx [options]\n");
log("\n");
log("This command runs synthesis for Xilinx FPGAs. This command does not operate on\n");
log("partly selected designs. At the moment this command creates netlists that are\n");
log("compatible with 7-Series Xilinx devices.\n");
log("\n");
log(" -top <module>\n");
log(" use the specified module as top module\n");
log("\n");
log(" -edif <file>\n");
log(" write the design to the specified edif file. writing of an output file\n");
log(" is omitted if this parameter is not specified.\n");
log("\n");
log(" -blif <file>\n");
log(" write the design to the specified BLIF file. writing of an output file\n");
log(" is omitted if this parameter is not specified.\n");
log("\n");
log(" -vpr\n");
log(" generate an output netlist (and BLIF file) suitable for VPR\n");
log(" (this feature is experimental and incomplete)\n");
log("\n");
log(" -nobram\n");
log(" disable infering of block rams\n");
log("\n");
log(" -nodram\n");
log(" disable infering of distributed rams\n");
log("\n");
log(" -run <from_label>:<to_label>\n");
log(" only run the commands between the labels (see below). an empty\n");
log(" from label is synonymous to 'begin', and empty to label is\n");
log(" synonymous to the end of the command list.\n");
log("\n");
log(" -flatten\n");
log(" flatten design before synthesis\n");
log("\n");
log(" -retime\n");
log(" run 'abc' with -dff option\n");
log("\n");
log("\n");
log("The following commands are executed by this synthesis command:\n");
log("\n");
log(" begin:\n");
log(" read_verilog -lib +/xilinx/cells_sim.v\n");
log(" read_verilog -lib +/xilinx/cells_xtra.v\n");
log(" read_verilog -lib +/xilinx/brams_bb.v\n");
log(" hierarchy -check -top <top>\n");
log("\n");
log(" flatten: (only if -flatten)\n");
log(" proc\n");
log(" flatten\n");
log("\n");
log(" coarse:\n");
log(" synth -run coarse\n");
log("\n");
log(" bram: (only executed when '-nobram' is not given)\n");
log(" memory_bram -rules +/xilinx/brams.txt\n");
log(" techmap -map +/xilinx/brams_map.v\n");
log("\n");
log(" dram: (only executed when '-nodram' is not given)\n");
log(" memory_bram -rules +/xilinx/drams.txt\n");
log(" techmap -map +/xilinx/drams_map.v\n");
log("\n");
log(" fine:\n");
log(" opt -fast -full\n");
log(" memory_map\n");
log(" dffsr2dff\n");
log(" dff2dffe\n");
log(" opt -full\n");
log(" techmap -map +/techmap.v -map +/xilinx/arith_map.v -map +/xilinx/ff_map.v\n");
log(" opt -fast\n");
log("\n");
log(" map_luts:\n");
log(" abc -luts 2:2,3,6:5,10,20 [-dff] (without '-vpr' only!)\n");
log(" abc -lut 5 [-dff] (with '-vpr' only!)\n");
log(" clean\n");
log("\n");
log(" map_cells:\n");
log(" techmap -map +/xilinx/cells_map.v\n");
log(" dffinit -ff FDRE Q INIT -ff FDCE Q INIT -ff FDPE Q INIT -ff FDSE Q INIT\n");
log(" clean\n");
log("\n");
log(" check:\n");
log(" hierarchy -check\n");
log(" stat\n");
log(" check -noinit\n");
log("\n");
log(" edif: (only if -edif)\n");
log(" write_edif <file-name>\n");
log("\n");
log(" blif: (only if -blif)\n");
log(" write_blif <file-name>\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
std::string top_opt = "-auto-top";
std::string edif_file;
std::string blif_file;
std::string run_from, run_to;
bool flatten = false;
bool retime = false;
bool vpr = false;
bool nobram = false;
bool nodram = false;
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
if (args[argidx] == "-top" && argidx+1 < args.size()) {
top_opt = "-top " + args[++argidx];
continue;
}
if (args[argidx] == "-edif" && argidx+1 < args.size()) {
edif_file = args[++argidx];
continue;
}
if (args[argidx] == "-blif" && argidx+1 < args.size()) {
blif_file = args[++argidx];
continue;
}
if (args[argidx] == "-run" && argidx+1 < args.size()) {
size_t pos = args[argidx+1].find(':');
if (pos == std::string::npos)
break;
run_from = args[++argidx].substr(0, pos);
run_to = args[argidx].substr(pos+1);
continue;
}
if (args[argidx] == "-flatten") {
flatten = true;
continue;
}
if (args[argidx] == "-retime") {
retime = true;
continue;
}
if (args[argidx] == "-vpr") {
vpr = true;
continue;
}
if (args[argidx] == "-nobram") {
nobram = true;
continue;
}
if (args[argidx] == "-nodram") {
nodram = true;
continue;
}
break;
}
extra_args(args, argidx, design);
if (!design->full_selection())
log_cmd_error("This command only operates on fully selected designs!\n");
bool active = run_from.empty();
log_header(design, "Executing SYNTH_XILINX pass.\n");
log_push();
if (check_label(active, run_from, run_to, "begin"))
{
if (vpr) {
Pass::call(design, "read_verilog -lib -D_EXPLICIT_CARRY +/xilinx/cells_sim.v");
} else {
Pass::call(design, "read_verilog -lib +/xilinx/cells_sim.v");
}
Pass::call(design, "read_verilog -lib +/xilinx/cells_xtra.v");
if (!nobram) {
Pass::call(design, "read_verilog -lib +/xilinx/brams_bb.v");
}
Pass::call(design, stringf("hierarchy -check %s", top_opt.c_str()));
}
if (flatten && check_label(active, run_from, run_to, "flatten"))
{
Pass::call(design, "proc");
Pass::call(design, "flatten");
}
if (check_label(active, run_from, run_to, "coarse"))
{
Pass::call(design, "synth -run coarse");
}
if (check_label(active, run_from, run_to, "bram"))
{
if (!nobram) {
Pass::call(design, "memory_bram -rules +/xilinx/brams.txt");
Pass::call(design, "techmap -map +/xilinx/brams_map.v");
}
}
if (check_label(active, run_from, run_to, "dram"))
{
if (!nodram) {
Pass::call(design, "memory_bram -rules +/xilinx/drams.txt");
Pass::call(design, "techmap -map +/xilinx/drams_map.v");
}
}
if (check_label(active, run_from, run_to, "fine"))
{
Pass::call(design, "opt -fast -full");
Pass::call(design, "memory_map");
Pass::call(design, "dffsr2dff");
Pass::call(design, "dff2dffe");
Pass::call(design, "opt -full");
if (vpr) {
Pass::call(design, "techmap -map +/techmap.v -map +/xilinx/arith_map.v -map +/xilinx/ff_map.v -D _EXPLICIT_CARRY");
} else {
Pass::call(design, "techmap -map +/techmap.v -map +/xilinx/arith_map.v -map +/xilinx/ff_map.v");
}
Pass::call(design, "hierarchy -check");
Pass::call(design, "opt -fast");
}
if (check_label(active, run_from, run_to, "map_luts"))
{
Pass::call(design, "abc -luts 2:2,3,6:5,10,20" + string(retime ? " -dff" : ""));
Pass::call(design, "clean");
Pass::call(design, "techmap -map +/xilinx/lut_map.v");
}
if (check_label(active, run_from, run_to, "map_cells"))
{
Pass::call(design, "techmap -map +/xilinx/cells_map.v");
Pass::call(design, "dffinit -ff FDRE Q INIT -ff FDCE Q INIT -ff FDPE Q INIT -ff FDSE Q INIT");
Pass::call(design, "clean");
}
if (check_label(active, run_from, run_to, "check"))
{
Pass::call(design, "hierarchy -check");
Pass::call(design, "stat");
Pass::call(design, "check -noinit");
}
if (check_label(active, run_from, run_to, "edif"))
{
if (!edif_file.empty())
Pass::call(design, stringf("write_edif -pvector bra %s", edif_file.c_str()));
}
if (check_label(active, run_from, run_to, "blif"))
{
if (!blif_file.empty())
Pass::call(design, stringf("write_blif %s", edif_file.c_str()));
}
log_pop();
}
} SynthXilinxPass;
PRIVATE_NAMESPACE_END
|
/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2012 Clifford Wolf <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
bool check_label(bool &active, std::string run_from, std::string run_to, std::string label)
{
if (label == run_from)
active = true;
if (label == run_to)
active = false;
return active;
}
struct SynthXilinxPass : public Pass
{
SynthXilinxPass() : Pass("synth_xilinx", "synthesis for Xilinx FPGAs") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" synth_xilinx [options]\n");
log("\n");
log("This command runs synthesis for Xilinx FPGAs. This command does not operate on\n");
log("partly selected designs. At the moment this command creates netlists that are\n");
log("compatible with 7-Series Xilinx devices.\n");
log("\n");
log(" -top <module>\n");
log(" use the specified module as top module\n");
log("\n");
log(" -edif <file>\n");
log(" write the design to the specified edif file. writing of an output file\n");
log(" is omitted if this parameter is not specified.\n");
log("\n");
log(" -blif <file>\n");
log(" write the design to the specified BLIF file. writing of an output file\n");
log(" is omitted if this parameter is not specified.\n");
log("\n");
log(" -vpr\n");
log(" generate an output netlist (and BLIF file) suitable for VPR\n");
log(" (this feature is experimental and incomplete)\n");
log("\n");
log(" -nobram\n");
log(" disable infering of block rams\n");
log("\n");
log(" -nodram\n");
log(" disable infering of distributed rams\n");
log("\n");
log(" -run <from_label>:<to_label>\n");
log(" only run the commands between the labels (see below). an empty\n");
log(" from label is synonymous to 'begin', and empty to label is\n");
log(" synonymous to the end of the command list.\n");
log("\n");
log(" -flatten\n");
log(" flatten design before synthesis\n");
log("\n");
log(" -retime\n");
log(" run 'abc' with -dff option\n");
log("\n");
log("\n");
log("The following commands are executed by this synthesis command:\n");
log("\n");
log(" begin:\n");
log(" read_verilog -lib +/xilinx/cells_sim.v\n");
log(" read_verilog -lib +/xilinx/cells_xtra.v\n");
log(" read_verilog -lib +/xilinx/brams_bb.v\n");
log(" hierarchy -check -top <top>\n");
log("\n");
log(" flatten: (only if -flatten)\n");
log(" proc\n");
log(" flatten\n");
log("\n");
log(" coarse:\n");
log(" synth -run coarse\n");
log("\n");
log(" bram: (only executed when '-nobram' is not given)\n");
log(" memory_bram -rules +/xilinx/brams.txt\n");
log(" techmap -map +/xilinx/brams_map.v\n");
log("\n");
log(" dram: (only executed when '-nodram' is not given)\n");
log(" memory_bram -rules +/xilinx/drams.txt\n");
log(" techmap -map +/xilinx/drams_map.v\n");
log("\n");
log(" fine:\n");
log(" opt -fast -full\n");
log(" memory_map\n");
log(" dffsr2dff\n");
log(" dff2dffe\n");
log(" opt -full\n");
log(" techmap -map +/techmap.v -map +/xilinx/arith_map.v -map +/xilinx/ff_map.v\n");
log(" opt -fast\n");
log("\n");
log(" map_luts:\n");
log(" abc -luts 2:2,3,6:5,10,20 [-dff] (without '-vpr' only!)\n");
log(" abc -lut 5 [-dff] (with '-vpr' only!)\n");
log(" clean\n");
log("\n");
log(" map_cells:\n");
log(" techmap -map +/xilinx/cells_map.v\n");
log(" dffinit -ff FDRE Q INIT -ff FDCE Q INIT -ff FDPE Q INIT -ff FDSE Q INIT \\\n");
log(" -ff FDRE_1 Q INIT -ff FDCE_1 Q INIT -ff FDPE_1 Q INIT -ff FDSE_1 Q INIT\n");
log(" clean\n");
log("\n");
log(" check:\n");
log(" hierarchy -check\n");
log(" stat\n");
log(" check -noinit\n");
log("\n");
log(" edif: (only if -edif)\n");
log(" write_edif <file-name>\n");
log("\n");
log(" blif: (only if -blif)\n");
log(" write_blif <file-name>\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
std::string top_opt = "-auto-top";
std::string edif_file;
std::string blif_file;
std::string run_from, run_to;
bool flatten = false;
bool retime = false;
bool vpr = false;
bool nobram = false;
bool nodram = false;
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++)
{
if (args[argidx] == "-top" && argidx+1 < args.size()) {
top_opt = "-top " + args[++argidx];
continue;
}
if (args[argidx] == "-edif" && argidx+1 < args.size()) {
edif_file = args[++argidx];
continue;
}
if (args[argidx] == "-blif" && argidx+1 < args.size()) {
blif_file = args[++argidx];
continue;
}
if (args[argidx] == "-run" && argidx+1 < args.size()) {
size_t pos = args[argidx+1].find(':');
if (pos == std::string::npos)
break;
run_from = args[++argidx].substr(0, pos);
run_to = args[argidx].substr(pos+1);
continue;
}
if (args[argidx] == "-flatten") {
flatten = true;
continue;
}
if (args[argidx] == "-retime") {
retime = true;
continue;
}
if (args[argidx] == "-vpr") {
vpr = true;
continue;
}
if (args[argidx] == "-nobram") {
nobram = true;
continue;
}
if (args[argidx] == "-nodram") {
nodram = true;
continue;
}
break;
}
extra_args(args, argidx, design);
if (!design->full_selection())
log_cmd_error("This command only operates on fully selected designs!\n");
bool active = run_from.empty();
log_header(design, "Executing SYNTH_XILINX pass.\n");
log_push();
if (check_label(active, run_from, run_to, "begin"))
{
if (vpr) {
Pass::call(design, "read_verilog -lib -D_EXPLICIT_CARRY +/xilinx/cells_sim.v");
} else {
Pass::call(design, "read_verilog -lib +/xilinx/cells_sim.v");
}
Pass::call(design, "read_verilog -lib +/xilinx/cells_xtra.v");
if (!nobram) {
Pass::call(design, "read_verilog -lib +/xilinx/brams_bb.v");
}
Pass::call(design, stringf("hierarchy -check %s", top_opt.c_str()));
}
if (flatten && check_label(active, run_from, run_to, "flatten"))
{
Pass::call(design, "proc");
Pass::call(design, "flatten");
}
if (check_label(active, run_from, run_to, "coarse"))
{
Pass::call(design, "synth -run coarse");
}
if (check_label(active, run_from, run_to, "bram"))
{
if (!nobram) {
Pass::call(design, "memory_bram -rules +/xilinx/brams.txt");
Pass::call(design, "techmap -map +/xilinx/brams_map.v");
}
}
if (check_label(active, run_from, run_to, "dram"))
{
if (!nodram) {
Pass::call(design, "memory_bram -rules +/xilinx/drams.txt");
Pass::call(design, "techmap -map +/xilinx/drams_map.v");
}
}
if (check_label(active, run_from, run_to, "fine"))
{
Pass::call(design, "opt -fast -full");
Pass::call(design, "memory_map");
Pass::call(design, "dffsr2dff");
Pass::call(design, "dff2dffe");
Pass::call(design, "opt -full");
if (vpr) {
Pass::call(design, "techmap -map +/techmap.v -map +/xilinx/arith_map.v -map +/xilinx/ff_map.v -D _EXPLICIT_CARRY");
} else {
Pass::call(design, "techmap -map +/techmap.v -map +/xilinx/arith_map.v -map +/xilinx/ff_map.v");
}
Pass::call(design, "hierarchy -check");
Pass::call(design, "opt -fast");
}
if (check_label(active, run_from, run_to, "map_luts"))
{
Pass::call(design, "abc -luts 2:2,3,6:5,10,20" + string(retime ? " -dff" : ""));
Pass::call(design, "clean");
Pass::call(design, "techmap -map +/xilinx/lut_map.v");
}
if (check_label(active, run_from, run_to, "map_cells"))
{
Pass::call(design, "techmap -map +/xilinx/cells_map.v");
Pass::call(design, "dffinit -ff FDRE Q INIT -ff FDCE Q INIT -ff FDPE Q INIT -ff FDSE Q INIT "
"-ff FDRE_1 Q INIT -ff FDCE_1 Q INIT -ff FDPE_1 Q INIT -ff FDSE_1 Q INIT");
Pass::call(design, "clean");
}
if (check_label(active, run_from, run_to, "check"))
{
Pass::call(design, "hierarchy -check");
Pass::call(design, "stat");
Pass::call(design, "check -noinit");
}
if (check_label(active, run_from, run_to, "edif"))
{
if (!edif_file.empty())
Pass::call(design, stringf("write_edif -pvector bra %s", edif_file.c_str()));
}
if (check_label(active, run_from, run_to, "blif"))
{
if (!blif_file.empty())
Pass::call(design, stringf("write_blif %s", edif_file.c_str()));
}
log_pop();
}
} SynthXilinxPass;
PRIVATE_NAMESPACE_END
|
Add Xilinx negedge FFs to synth_xilinx dffinit call, fixes #873
|
Add Xilinx negedge FFs to synth_xilinx dffinit call, fixes #873
Signed-off-by: Clifford Wolf <[email protected]>
|
C++
|
isc
|
cliffordwolf/yosys,cliffordwolf/yosys,SymbiFlow/yosys,YosysHQ/yosys,SymbiFlow/yosys,SymbiFlow/yosys,SymbiFlow/yosys,cliffordwolf/yosys,cliffordwolf/yosys,cliffordwolf/yosys,antmicro/yosys,YosysHQ/yosys,antmicro/yosys,YosysHQ/yosys,cliffordwolf/yosys,antmicro/yosys,cliffordwolf/yosys,YosysHQ/yosys,antmicro/yosys,YosysHQ/yosys,SymbiFlow/yosys,antmicro/yosys,antmicro/yosys,YosysHQ/yosys,antmicro/yosys,YosysHQ/yosys,SymbiFlow/yosys,YosysHQ/yosys,antmicro/yosys,cliffordwolf/yosys,SymbiFlow/yosys,SymbiFlow/yosys,cliffordwolf/yosys
|
f903e13d9e8f39afbb53beb2823342a0fa902ab7
|
cpp/GraphColoring/source/main.cpp
|
cpp/GraphColoring/source/main.cpp
|
#include "../include/AdjacencyList.h"
#include "../include/FileReader.h"
#include <iostream>
int main() {
std::string base = "../../../../OneDrive/Documents/TU Delft/Research/Graphs/";
std::string path = base + "tiny/out.tiny";
AdjacencyList adjacencyList = FileReader::read(path);
auto sorted = adjacencyList.getSorted(true);
for (auto it = sorted.rbegin(); it != sorted.rend(); ++it)
{
std::cout << it->id << " (" << it->degree << ")" << std::endl;
}
while (1) {}
}
|
#include "../include/AdjacencyList.h"
#include "../include/FileReader.h"
#include <iostream>
#include <string>
#include <chrono>
int main() {
typedef std::chrono::high_resolution_clock Clock;
typedef std::chrono::milliseconds ms;
Clock::time_point start, finish;
std::string base = "../../../../OneDrive/Documents/TU Delft/Research/Graphs/";
std::string path = base + "Testing/arenas-jazz/out.arenas-jazz";
// Read file
std::cout << "Reading file ... ";
start = Clock::now();
AdjacencyList adjacencyList = FileReader::read(path);
finish = Clock::now();
std::cout << std::chrono::duration_cast<ms>(finish - start).count() / 1000.0 << " sec" << std::endl;
// Sort vertices
std::cout << "Sorting vertices ... ";
start = Clock::now();
auto sorted = adjacencyList.getSorted(true);
finish = Clock::now();
std::cout << std::chrono::duration_cast<ms>(finish - start).count() / 1000.0 << " sec" << std::endl;
std::cout << "Number of vertices: " << sorted.size() << std::endl;
while (1) {}
}
|
Add std::chrono timing to main
|
Add std::chrono timing to main
|
C++
|
mit
|
leonoverweel/graph-coloring,leonoverweel/graph-coloring
|
9b92949189633416e723c308e59be89d0b9c806e
|
multivec/monolingual.hpp
|
multivec/monolingual.hpp
|
#pragma once
#include "utils.hpp"
class MonolingualModel
{
friend class BilingualModel;
friend void save(ofstream& outfile, const MonolingualModel& model);
friend void load(ifstream& infile, MonolingualModel& model);
private:
Config* const config;
mat input_weights;
mat output_weights; // output weights for negative sampling
mat output_weights_hs; // output weights for hierarchical softmax
mat sent_weights;
long long vocab_word_count; // property of vocabulary (sum of all word counts)
// training file stats (properties of this training instance)
long long training_words; // total number of words in training file (used for progress estimation)
long long training_lines;
// training state
long long words_processed;
float alpha;
unordered_map<string, HuffmanNode> vocabulary;
vector<HuffmanNode*> unigram_table;
void addWordToVocab(const string& word);
void reduceVocab();
void createBinaryTree();
void assignCodes(HuffmanNode* node, vector<int> code, vector<int> parents) const;
void initUnigramTable();
HuffmanNode* getRandomHuffmanNode(); // uses the unigram frequency table to sample a random node
vector<HuffmanNode> getNodes(const string& sentence) const;
void subsample(vector<HuffmanNode>& node) const;
void readVocab(const string& training_file);
void initNet();
void initSentWeights();
void trainChunk(const string& training_file, const vector<long long>& chunks, int chunk_id);
int trainSentence(const string& sent, int sent_id);
void trainWord(const vector<HuffmanNode>& nodes, int word_pos, int sent_id);
void trainWordCBOW(const vector<HuffmanNode>& nodes, int word_pos, int sent_id);
void trainWordSkipGram(const vector<HuffmanNode>& nodes, int word_pos, int sent_id);
vec hierarchicalUpdate(const HuffmanNode& node, const vec& hidden, float alpha, bool update = true);
vec negSamplingUpdate(const HuffmanNode& node, const vec& hidden, float alpha, bool update = true);
vector<long long> chunkify(const string& filename, int n_chunks);
vec wordVec(int index, int policy) const;
public:
MonolingualModel(Config* config) : config(config) {} // prefer this constructor
vec wordVec(const string& word, int policy = 0) const; // word embedding
vec sentVec(const string& sentence); // paragraph vector (Le & Mikolov), TODO: custom alpha and iterations
void sentVec(istream& infile); // compute paragraph vector for all lines in a stream
void train(const string& training_file, bool initialize = true); // training from scratch (resets vocabulary and weights)
void saveVectorsBin(const string &filename, int policy = 0) const; // saves word embeddings in the word2vec binary format
void saveVectors(const string &filename, int policy = 0) const; // saves word embeddings in the word2vec text format
void saveSentVectors(const string &filename) const;
void load(const string& filename); // loads the entire model
void save(const string& filename) const; // saves the entire model
void normalizeWeights(); // normalize all weights between 0 and 1
float similarity(const string& word1, const string& word2, int policy = 0) const; // cosine similarity
float distance(const string& word1, const string& word2, int policy = 0) const; // 1 - cosine similarity
float similarityNgrams(const string& seq1, const string& seq2, int policy = 0) const; // similarity between two sequences of same size
float similaritySentence(const string& seq1, const string& seq2, int policy = 0) const; // similarity between two variable-size sequences
float softWER(const string& hyp, const string& ref, int policy = 0) const; // soft Word Error Rate
// syntax-aware similarity between two sequences
float similaritySentenceSyntax(const string& seq1, const string& seq2, const string& tags1, const string& tags2, int policy = 0) const;
int getDimension() const { return config->dimension; };
vector<pair<string, float>> closest(const string& word, int n = 10, int policy = 0) const; // n closest words to given word
vector<pair<string, float>> closest(const string& word, const vector<string>& words, int policy = 0) const;
vector<pair<string, float>> closest(const vec& v, int n = 10, int policy = 0) const;
vector<pair<string, int>> getWords() const; // get words with their counts
void analogicalReasoning(const string& filename, int max_voc = 0, int policy = 0) const;
};
|
#pragma once
#include "utils.hpp"
class MonolingualModel
{
friend class BilingualModel;
friend void save(ofstream& outfile, const MonolingualModel& model);
friend void load(ifstream& infile, MonolingualModel& model);
private:
Config* const config;
mat input_weights;
mat output_weights; // output weights for negative sampling
mat output_weights_hs; // output weights for hierarchical softmax
mat sent_weights;
long long vocab_word_count; // property of vocabulary (sum of all word counts)
// training file stats (properties of this training instance)
long long training_words; // total number of words in training file (used for progress estimation)
long long training_lines;
// training state
long long words_processed;
float alpha;
unordered_map<string, HuffmanNode> vocabulary;
vector<HuffmanNode*> unigram_table;
void addWordToVocab(const string& word);
void reduceVocab();
void createBinaryTree();
void assignCodes(HuffmanNode* node, vector<int> code, vector<int> parents) const;
void initUnigramTable();
HuffmanNode* getRandomHuffmanNode(); // uses the unigram frequency table to sample a random node
vector<HuffmanNode> getNodes(const string& sentence) const;
void subsample(vector<HuffmanNode>& node) const;
void readVocab(const string& training_file);
void initNet();
void initSentWeights();
void trainChunk(const string& training_file, const vector<long long>& chunks, int chunk_id);
int trainSentence(const string& sent, int sent_id);
void trainWord(const vector<HuffmanNode>& nodes, int word_pos, int sent_id);
void trainWordCBOW(const vector<HuffmanNode>& nodes, int word_pos, int sent_id);
void trainWordSkipGram(const vector<HuffmanNode>& nodes, int word_pos, int sent_id);
vec hierarchicalUpdate(const HuffmanNode& node, const vec& hidden, float alpha, bool update = true);
vec negSamplingUpdate(const HuffmanNode& node, const vec& hidden, float alpha, bool update = true);
vector<long long> chunkify(const string& filename, int n_chunks);
vec wordVec(int index, int policy) const;
public:
MonolingualModel(Config* config) : config(config) {} // prefer this constructor
vec wordVec(const string& word, int policy = 0) const; // word embedding
vec sentVec(const string& sentence); // paragraph vector (Le & Mikolov), TODO: custom alpha and iterations
void sentVec(istream& infile); // compute paragraph vector for all lines in a stream
void train(const string& training_file, bool initialize = true); // training from scratch (resets vocabulary and weights)
void saveVectorsBin(const string &filename, int policy = 0) const; // saves word embeddings in the word2vec binary format
void saveVectors(const string &filename, int policy = 0) const; // saves word embeddings in the word2vec text format
void saveSentVectors(const string &filename) const;
void load(const string& filename); // loads the entire model
void save(const string& filename) const; // saves the entire model
void normalizeWeights(); // normalize all weights between 0 and 1
float similarity(const string& word1, const string& word2, int policy = 0) const; // cosine similarity
float distance(const string& word1, const string& word2, int policy = 0) const; // 1 - cosine similarity
float similarityNgrams(const string& seq1, const string& seq2, int policy = 0) const; // similarity between two sequences of same size
float similaritySentence(const string& seq1, const string& seq2, int policy = 0) const; // similarity between two variable-size sequences
float similaritySentenceSyntax(const string& seq1, const string& seq2, const string& tags1, const string& tags2, const string& idf1, const string& idf2, float alpha, int policy = 0) const; // similarity between two variable-size sequences according of part-of-speech and inverse document frequencies of terms in the sequences
float softWER(const string& hyp, const string& ref, int policy = 0) const; // soft Word Error Rate
vector<pair<string, float>> trg_closest(const string& src_word, int n = 10, int policy = 0) const; // n closest words to given word
vector<pair<string, float>> src_closest(const string& trg_word, int n = 10, int policy = 0) const;
};
int getDimension() const { return config->dimension; };
vector<pair<string, float>> closest(const string& word, int n = 10, int policy = 0) const; // n closest words to given word
vector<pair<string, float>> closest(const string& word, const vector<string>& words, int policy = 0) const;
vector<pair<string, float>> closest(const vec& v, int n = 10, int policy = 0) const;
vector<pair<string, int>> getWords() const; // get words with their counts
void analogicalReasoning(const string& filename, int max_voc = 0, int policy = 0) const;
};
|
Add IDF consideration in similaritySentenceSyntax
|
Add IDF consideration in similaritySentenceSyntax
Add IDF consideration in similaritySentenceSyntax
|
C++
|
apache-2.0
|
eske/word2vecpp-legacy,eske/multivec,eske/multivec,eske/word2vecpp-legacy,eske/multivec,eske/multivec,eske/word2vecpp-legacy,eske/word2vecpp-legacy,eske/word2vecpp-legacy,eske/multivec,eske/multivec
|
e8572158a66861efae8b3dcbc1cc28dcbd34a6d9
|
grab_display/zcacalc.cpp
|
grab_display/zcacalc.cpp
|
#include <string>
#include "zca.hpp"
#include "utilities_common.h"
using namespace std;
using namespace cv;
int main(void)
{
vector<string> filePaths;
GetFilePaths("/media/kjaget/84CA3305CA32F2D2/cygwin64/home/ubuntu/2015VisionCode/cascade_training/negative_images/framegrabber", ".png", filePaths);
GetFilePaths("/media/kjaget/84CA3305CA32F2D2/cygwin64/home/ubuntu/2015VisionCode/cascade_training/negative_images/Framegrabber2", ".png", filePaths, true);
GetFilePaths("/media/kjaget/84CA3305CA32F2D2/cygwin64/home/ubuntu/2015VisionCode/cascade_training/negative_images/generic", ".png", filePaths, true);
cout << filePaths.size() << " images!" << endl;
const int seed = 12345;
RNG rng(seed);
vector<Mat> images;
const int nImgs = 100000;
Mat img; // full image data
Mat patch; // randomly selected image patch from full image
for (int nDone = 0; nDone < nImgs; )
{
// Grab a random image from the list
size_t idx = rng.uniform(0, filePaths.size());
img = imread(filePaths[idx]);
// Pick a random row and column from the image
int r = rng.uniform(0, img.rows);
int c = rng.uniform(0, img.cols);
// Pick a random size as well. Make sure it
// doesn't extend past the edge of the input
int s = rng.uniform(0, 2*MIN(MIN(r, img.rows-r), MIN(c, img.cols-c)) + 1 );
if (s < 28)
continue;
Rect rect = Rect(c-s/2, r-s/2, s, s);
//cout << "Using " << filePaths[idx] << rect << endl;
// Resize patches to 24x24 to save memory
resize(img(rect), patch, Size(24,24));
images.push_back(patch.clone());
nDone++;
if (!(nDone % 1000))
cout << nDone << " image patches extracted" << endl;
}
ZCA zca12(images, Size(12,12), .05);
ZCA zca24(images, Size(24,24), .05);
stringstream name;
name << "zcaWeightsE05_12_" << seed << "_" << nImgs << ".xml";
zca12.Write(name.str().c_str());
name.str(string());
name << "zcaWeightsE05_24_" << seed << "_" << nImgs << ".xml";
zca24.Write(name.str().c_str());
}
|
#include <string>
#include "zca.hpp"
#include "random_subimage.hpp"
#include "utilities_common.h"
using namespace std;
using namespace cv;
static void doZCA(const vector<Mat> &images, const Size &size, const float epsilon, const bool gcn, const string &id, int seed)
{
ZCA zca(images, size, epsilon, gcn);
stringstream name;
name << "zcaWeights" <<(gcn ? "GCN" : "") << id << "_" << size.width << "_" << seed << "_" << images.size() << ".xml";
zca.Write(name.str().c_str());
}
// returns true if the given 3 channel image is B = G = R
bool isGrayImage(const Mat &img)
{
Mat dst;
Mat bgr[3];
split( img, bgr );
absdiff( bgr[0], bgr[1], dst );
if(countNonZero( dst ))
return false;
absdiff( bgr[0], bgr[2], dst );
return !countNonZero( dst );
}
int main(void)
{
vector<string> filePaths;
GetFilePaths("/media/kjaget/AC8612CF86129A42/cygwin64/home/ubuntu/2015VisionCode/cascade_training/negative_images/framegrabber", ".png", filePaths);
GetFilePaths("/media/kjaget/AC8612CF86129A42/cygwin64/home/ubuntu/2015VisionCode/cascade_training/negative_images/Framegrabber2", ".png", filePaths, true);
GetFilePaths("/media/kjaget/AC8612CF86129A42/cygwin64/home/ubuntu/2015VisionCode/cascade_training/negative_images/generic", ".png", filePaths, true);
GetFilePaths("/media/kjaget/AC8612CF86129A42/cygwin64/home/ubuntu/2015VisionCode/cascade_training/negative_images/20160210", ".png", filePaths, true);
GetFilePaths("/media/kjaget/AC8612CF86129A42/cygwin64/home/ubuntu/2015VisionCode/cascade_training/negative_images/white_bg", ".png", filePaths, true);
cout << filePaths.size() << " images!" << endl;
const int seed = 12345;
RandomSubImage rsi(RNG(seed), filePaths);
Mat img; // full image data
Mat patch; // randomly selected image patch from full image
vector<Mat> images;
const int nImgs = 200000;
for (int nDone = 0; nDone < nImgs; )
{
img = rsi.get(1.0, 0.05);
resize(img, patch, Size(24,24));
// There are grayscale images in the
// negatives, but we'll never see one
// in real life. Exclude those for now
if (isGrayImage(img))
continue;
images.push_back(patch.clone());
nDone++;
if (!(nDone % 1000))
cout << nDone << " image patches extracted" << endl;
}
doZCA(images, Size(12,12), 0.1, true, "nograyE1", seed);
doZCA(images, Size(24,24), 0.1, true, "nograyE1", seed);
doZCA(images, Size(12,12), 0.01, true, "nograyE01", seed);
doZCA(images, Size(24,24), 0.01, true, "nograyE01", seed);
doZCA(images, Size(12,12), 0.001, true, "nograyE001", seed);
doZCA(images, Size(24,24), 0.001, true, "nograyE001", seed);
doZCA(images, Size(12,12), 0.0001, true, "nograyE0001", seed);
doZCA(images, Size(24,24), 0.0001, true, "nograyE0001", seed);
doZCA(images, Size(12,12), 0.00001, true, "nograyE00001", seed);
doZCA(images, Size(24,24), 0.00001, true, "nograyE00001", seed);
doZCA(images, Size(12,12), 0.1, false, "nograyE1", seed);
doZCA(images, Size(24,24), 0.1, false, "nograyE1", seed);
doZCA(images, Size(12,12), 0.01, false, "nograyE01", seed);
doZCA(images, Size(24,24), 0.01, false, "nograyE01", seed);
doZCA(images, Size(12,12), 0.001, false, "nograyE001", seed);
doZCA(images, Size(24,24), 0.001, false, "nograyE001", seed);
doZCA(images, Size(12,12), 0.0001, false, "nograyE0001", seed);
doZCA(images, Size(24,24), 0.0001, false, "nograyE0001", seed);
doZCA(images, Size(12,12), 0.00001, false, "nograyE00001", seed);
doZCA(images, Size(24,24), 0.00001, false, "nograyE00001", seed);
}
|
Make more modular
|
Make more modular
|
C++
|
mit
|
FRC900/2016VisionCode,FRC900/2016VisionCode,FRC900/2016VisionCode,FRC900/2016VisionCode,FRC900/2016VisionCode,FRC900/2016VisionCode,FRC900/2016VisionCode
|
ea4f412d5da23212ab59c352e9b361d23ea38e40
|
Source/DebugCamera.cpp
|
Source/DebugCamera.cpp
|
//Alex Newman
#include "DebugCamera.h"
#include "EventManager.h"
#include "World.h"
#include <GLM/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/vector_angle.hpp>
#include <GLFW/glfw3.h>
#include <algorithm>
#include <iostream>
using namespace glm;
float DebugCamera::zoomLevel = 45.0f;
DebugCamera::DebugCamera(vec3 position) : Camera(), mHorizontalAngle(0.0f), mVerticalAngle(0.0f),
mMouseSpeed(0.005f), mMovementSpeed(5.0f), mPosition(position)
{
CalculateCameraBasis();
glfwSetScrollCallback(EventManager::GetWindow(), scroll_callback);
}
DebugCamera::~DebugCamera()
{}
void DebugCamera::CalculateCameraBasis()
{
mLookAt = glm::vec3(cos(mVerticalAngle) * sin(mHorizontalAngle),
sin(mVerticalAngle),
cos(mVerticalAngle) * cos(mHorizontalAngle));
mRight = glm::cross(mLookAt, vec3(0, 1.0f, 0));
mUp = glm::cross(mRight, mLookAt);
}
void DebugCamera::Update(float dt)
{
EventManager::DisableMouseCursor();
mHorizontalAngle -= mMouseSpeed * EventManager::GetMouseMotionX();
mVerticalAngle -= mMouseSpeed * EventManager::GetMouseMotionY();
//horizonal wrapping and vertical clamping
if (mHorizontalAngle < -3.14)
mHorizontalAngle = 3.14;
else if (mHorizontalAngle > 3.14)
mHorizontalAngle = -3.14;
if (mVerticalAngle < -1.48)
mVerticalAngle = -1.48;
if (mVerticalAngle > 1.48)
mVerticalAngle = 1.48;
//movement
vec3 forward = normalize(mLookAt);
vec3 normRight = normalize(mRight);
if (glfwGetKey(EventManager::GetWindow(), GLFW_KEY_W) == GLFW_PRESS)
mPosition += dt * mMovementSpeed * forward;
if (glfwGetKey(EventManager::GetWindow(), GLFW_KEY_S) == GLFW_PRESS)
mPosition -= dt * mMovementSpeed * forward;
if (glfwGetKey(EventManager::GetWindow(), GLFW_KEY_A) == GLFW_PRESS)
mPosition -= dt * mMovementSpeed * normRight;
if (glfwGetKey(EventManager::GetWindow(), GLFW_KEY_D) == GLFW_PRESS)
mPosition += dt * mMovementSpeed * normRight;
if (glfwGetKey(EventManager::GetWindow(), GLFW_KEY_SPACE) == GLFW_PRESS)
mPosition += dt * mMovementSpeed * vec3(0.0f, 1.0f, 0.0f);
if (glfwGetKey(EventManager::GetWindow(), GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS)
mPosition -= dt * mMovementSpeed * vec3(0.0f, 1.0f, 0.0f);
//reset camera zoom
if (glfwGetMouseButton(EventManager::GetWindow(), GLFW_MOUSE_BUTTON_MIDDLE) == GLFW_PRESS)
zoomLevel = 45.0f;
CalculateCameraBasis();
}
glm::mat4 DebugCamera::GetViewMatrix() const
{
return glm::lookAt(mPosition , mPosition + mLookAt, mUp);
}
glm::mat4 DebugCamera::GetProjectionMatrix() const
{
return glm::perspective(zoomLevel, 4.0f / 3.0f, 0.1f, 1000.0f);
}
void DebugCamera::scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
zoomLevel -= yoffset;
std::cout << "Zoom level: " << zoomLevel << "\n";
}
|
//Alex Newman
#include "DebugCamera.h"
#include "EventManager.h"
#include "World.h"
#include <GLM/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/vector_angle.hpp>
#include <GLFW/glfw3.h>
#include <algorithm>
#include <iostream>
using namespace glm;
float DebugCamera::zoomLevel = 45.0f;
DebugCamera::DebugCamera(vec3 position) : Camera(), mHorizontalAngle(0.0f), mVerticalAngle(0.0f),
mMouseSpeed(0.005f), mMovementSpeed(15.0f), mPosition(position)
{
CalculateCameraBasis();
glfwSetScrollCallback(EventManager::GetWindow(), scroll_callback);
}
DebugCamera::~DebugCamera()
{}
void DebugCamera::CalculateCameraBasis()
{
mLookAt = glm::vec3(cos(mVerticalAngle) * sin(mHorizontalAngle),
sin(mVerticalAngle),
cos(mVerticalAngle) * cos(mHorizontalAngle));
mRight = glm::cross(mLookAt, vec3(0, 1.0f, 0));
mUp = glm::cross(mRight, mLookAt);
}
void DebugCamera::Update(float dt)
{
EventManager::DisableMouseCursor();
mHorizontalAngle -= mMouseSpeed * EventManager::GetMouseMotionX();
mVerticalAngle -= mMouseSpeed * EventManager::GetMouseMotionY();
//horizonal wrapping and vertical clamping
if (mHorizontalAngle < -3.14)
mHorizontalAngle = 3.14;
else if (mHorizontalAngle > 3.14)
mHorizontalAngle = -3.14;
if (mVerticalAngle < -1.48)
mVerticalAngle = -1.48;
if (mVerticalAngle > 1.48)
mVerticalAngle = 1.48;
//movement
vec3 forward = normalize(mLookAt);
vec3 normRight = normalize(mRight);
if (glfwGetKey(EventManager::GetWindow(), GLFW_KEY_W) == GLFW_PRESS)
mPosition += dt * mMovementSpeed * forward;
if (glfwGetKey(EventManager::GetWindow(), GLFW_KEY_S) == GLFW_PRESS)
mPosition -= dt * mMovementSpeed * forward;
if (glfwGetKey(EventManager::GetWindow(), GLFW_KEY_A) == GLFW_PRESS)
mPosition -= dt * mMovementSpeed * normRight;
if (glfwGetKey(EventManager::GetWindow(), GLFW_KEY_D) == GLFW_PRESS)
mPosition += dt * mMovementSpeed * normRight;
if (glfwGetKey(EventManager::GetWindow(), GLFW_KEY_SPACE) == GLFW_PRESS)
mPosition += dt * mMovementSpeed * vec3(0.0f, 1.0f, 0.0f);
if (glfwGetKey(EventManager::GetWindow(), GLFW_KEY_LEFT_SHIFT) == GLFW_PRESS)
mPosition -= dt * mMovementSpeed * vec3(0.0f, 1.0f, 0.0f);
//reset camera zoom
if (glfwGetMouseButton(EventManager::GetWindow(), GLFW_MOUSE_BUTTON_MIDDLE) == GLFW_PRESS)
zoomLevel = 45.0f;
CalculateCameraBasis();
}
glm::mat4 DebugCamera::GetViewMatrix() const
{
return glm::lookAt(mPosition , mPosition + mLookAt, mUp);
}
glm::mat4 DebugCamera::GetProjectionMatrix() const
{
return glm::perspective(zoomLevel, 4.0f / 3.0f, 0.1f, 1000.0f);
}
void DebugCamera::scroll_callback(GLFWwindow* window, double xoffset, double yoffset)
{
zoomLevel -= yoffset;
std::cout << "Zoom level: " << zoomLevel << "\n";
}
|
Debug cam speed
|
Debug cam speed
|
C++
|
mit
|
MadReza/IslandAdventures,MadReza/IslandAdventures,MadReza/IslandAdventures,MadReza/IslandAdventures,MadReza/IslandAdventures,MadReza/IslandAdventures
|
55a23b2c6b38506f6f3f68e00aacd78afaab214c
|
test/extensions/filters/listener/common/fuzz/listener_filter_fakes.cc
|
test/extensions/filters/listener/common/fuzz/listener_filter_fakes.cc
|
#include "test/extensions/filters/listener/common/fuzz/listener_filter_fakes.h"
namespace Envoy {
namespace Extensions {
namespace ListenerFilters {
Network::IoHandle& FakeConnectionSocket::ioHandle() { return *io_handle_; }
const Network::IoHandle& FakeConnectionSocket::ioHandle() const { return *io_handle_; }
Network::Address::Type FakeConnectionSocket::addressType() const {
return address_provider_->localAddress()->type();
}
absl::optional<Network::Address::IpVersion> FakeConnectionSocket::ipVersion() const {
if (address_provider_->localAddress() == nullptr || addressType() != Network::Address::Type::Ip) {
return absl::nullopt;
}
return address_provider_->localAddress()->ip()->version();
}
void FakeConnectionSocket::setDetectedTransportProtocol(absl::string_view protocol) {
transport_protocol_ = std::string(protocol);
}
absl::string_view FakeConnectionSocket::detectedTransportProtocol() const {
return transport_protocol_;
}
void FakeConnectionSocket::setRequestedApplicationProtocols(
const std::vector<absl::string_view>& protocols) {
application_protocols_.clear();
for (const auto& protocol : protocols) {
application_protocols_.emplace_back(protocol);
}
}
const std::vector<std::string>& FakeConnectionSocket::requestedApplicationProtocols() const {
return application_protocols_;
}
void FakeConnectionSocket::setRequestedServerName(absl::string_view server_name) {
server_name_ = std::string(server_name);
}
absl::string_view FakeConnectionSocket::requestedServerName() const { return server_name_; }
Api::SysCallIntResult FakeConnectionSocket::getSocketOption(int level, int, void* optval,
socklen_t*) const {
#ifdef SOL_IP
switch (level) {
case SOL_IPV6:
static_cast<sockaddr_storage*>(optval)->ss_family = AF_INET6;
break;
case SOL_IP:
static_cast<sockaddr_storage*>(optval)->ss_family = AF_INET;
break;
default:
NOT_REACHED_GCOVR_EXCL_LINE;
}
return Api::SysCallIntResult{0, 0};
#else
// TODO: Waiting to determine if connection redirection possible, see
// Network::Utility::getOriginalDst()
return Api::SysCallIntResult{-1, 0};
#endif
}
absl::optional<std::chrono::milliseconds> FakeConnectionSocket::lastRoundTripTime() { return {}; }
} // namespace ListenerFilters
} // namespace Extensions
} // namespace Envoy
|
#include "test/extensions/filters/listener/common/fuzz/listener_filter_fakes.h"
namespace Envoy {
namespace Extensions {
namespace ListenerFilters {
Network::IoHandle& FakeConnectionSocket::ioHandle() { return *io_handle_; }
const Network::IoHandle& FakeConnectionSocket::ioHandle() const { return *io_handle_; }
Network::Address::Type FakeConnectionSocket::addressType() const {
return address_provider_->localAddress()->type();
}
absl::optional<Network::Address::IpVersion> FakeConnectionSocket::ipVersion() const {
if (address_provider_->localAddress() == nullptr || addressType() != Network::Address::Type::Ip) {
return absl::nullopt;
}
return address_provider_->localAddress()->ip()->version();
}
void FakeConnectionSocket::setDetectedTransportProtocol(absl::string_view protocol) {
transport_protocol_ = std::string(protocol);
}
absl::string_view FakeConnectionSocket::detectedTransportProtocol() const {
return transport_protocol_;
}
void FakeConnectionSocket::setRequestedApplicationProtocols(
const std::vector<absl::string_view>& protocols) {
application_protocols_.clear();
for (const auto& protocol : protocols) {
application_protocols_.emplace_back(protocol);
}
}
const std::vector<std::string>& FakeConnectionSocket::requestedApplicationProtocols() const {
return application_protocols_;
}
void FakeConnectionSocket::setRequestedServerName(absl::string_view server_name) {
server_name_ = std::string(server_name);
}
absl::string_view FakeConnectionSocket::requestedServerName() const { return server_name_; }
Api::SysCallIntResult FakeConnectionSocket::getSocketOption([[maybe_unused]] int level, int,
[[maybe_unused]] void* optval,
socklen_t*) const {
#ifdef SOL_IP
switch (level) {
case SOL_IPV6:
static_cast<sockaddr_storage*>(optval)->ss_family = AF_INET6;
break;
case SOL_IP:
static_cast<sockaddr_storage*>(optval)->ss_family = AF_INET;
break;
default:
NOT_REACHED_GCOVR_EXCL_LINE;
}
return Api::SysCallIntResult{0, 0};
#else
// TODO: Waiting to determine if connection redirection possible, see
// Network::Utility::getOriginalDst()
return Api::SysCallIntResult{-1, 0};
#endif
}
absl::optional<std::chrono::milliseconds> FakeConnectionSocket::lastRoundTripTime() { return {}; }
} // namespace ListenerFilters
} // namespace Extensions
} // namespace Envoy
|
test fails to build on MacOS due to unused parameters (#16454)
|
bugfix: test fails to build on MacOS due to unused parameters (#16454)
Signed-off-by: Mike Schore <[email protected]>
|
C++
|
apache-2.0
|
envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,envoyproxy/envoy,lyft/envoy,lyft/envoy,envoyproxy/envoy,envoyproxy/envoy,lyft/envoy,envoyproxy/envoy,lyft/envoy,envoyproxy/envoy,envoyproxy/envoy,lyft/envoy,envoyproxy/envoy,lyft/envoy
|
b410db844dd44c14204a43c93f104f6816ba6474
|
src/singletons/emotemanager.cpp
|
src/singletons/emotemanager.cpp
|
#include "singletons/emotemanager.hpp"
#include "application.hpp"
#include "controllers/accounts/accountcontroller.hpp"
using namespace chatterino::providers::twitch;
using namespace chatterino::messages;
namespace chatterino {
namespace singletons {
void EmoteManager::initialize()
{
getApp()->accounts->twitch.currentUserChanged.connect([this] {
auto currentUser = getApp()->accounts->twitch.getCurrent();
assert(currentUser);
this->twitch.refresh(currentUser);
});
this->emojis.load();
this->bttv.loadGlobalEmotes();
this->ffz.loadGlobalEmotes();
this->gifTimer.initialize();
}
} // namespace singletons
} // namespace chatterino
#if 0
namespace chatterino {
void EmojiTest()
{
auto &emoteManager = singletons::EmoteManager::getInstance();
emoteManager.loadEmojis();
{
std::vector<std::tuple<util::EmoteData, QString>> dummy;
// couple_mm 1f468-2764-1f468
// "\154075\156150❤\154075\156150"
// [0] 55357 0xd83d QChar
// [1] 56424 0xdc68 QChar
// [2] '❤' 10084 0x2764 QChar
// [3] 55357 0xd83d QChar
// [4] 56424 0xdc68 QChar
QString text = "👨❤👨";
emoteManager.parseEmojis(dummy, text);
assert(dummy.size() == 1);
}
{
std::vector<std::tuple<util::EmoteData, QString>> dummy;
// "✍\154074\157777"
// [0] '✍' 9997 0x270d QChar
// [1] 55356 0xd83c QChar
// [2] 57343 0xdfff QChar
QString text = "✍🏿";
emoteManager.parseEmojis(dummy, text);
assert(dummy.size() == 1);
assert(std::get<0>(dummy[0]).isValid());
}
{
std::vector<std::tuple<util::EmoteData, QString>> dummy;
QString text = "✍";
emoteManager.parseEmojis(dummy, text);
assert(dummy.size() == 1);
assert(std::get<0>(dummy[0]).isValid());
}
}
} // namespace chatterino
#endif
|
#include "singletons/emotemanager.hpp"
#include "application.hpp"
#include "controllers/accounts/accountcontroller.hpp"
namespace chatterino {
namespace singletons {
void EmoteManager::initialize()
{
getApp()->accounts->twitch.currentUserChanged.connect([this] {
auto currentUser = getApp()->accounts->twitch.getCurrent();
assert(currentUser);
this->twitch.refresh(currentUser);
});
this->emojis.load();
this->bttv.loadGlobalEmotes();
this->ffz.loadGlobalEmotes();
this->gifTimer.initialize();
}
} // namespace singletons
} // namespace chatterino
|
Remove old emoji parsing test code
|
Remove old emoji parsing test code
it can be recovered from the repo if we decide to make a test suite eShrug
|
C++
|
mit
|
hemirt/chatterino2,hemirt/chatterino2,fourtf/chatterino2,fourtf/chatterino2,Cranken/chatterino2,Cranken/chatterino2,fourtf/chatterino2,Cranken/chatterino2,hemirt/chatterino2,hemirt/chatterino2,Cranken/chatterino2
|
65594cfb2121b7cff76e5be79f9f901266c4f5b8
|
ngxpp/NgxLoadBalance.hpp
|
ngxpp/NgxLoadBalance.hpp
|
// Copyright (c) 2015-2017
// Author: Chrono Law
#ifndef _NGX_LOAD_BALANCE_HPP
#define _NGX_LOAD_BALANCE_HPP
#include "NgxPool.hpp"
template<typename T,
ngx_event_get_peer_pt get_peer,
ngx_event_free_peer_pt free_peer = nullptr,
ngx_http_upstream_rr_peer_data_t T::* ptr = &T::rrp>
class NgxLoadBalance final
{
typedef ngx_http_upstream_rr_peer_data_t peer_data_t;
typedef ngx_http_upstream_srv_conf_t srv_conf_t;
public:
static void init(ngx_conf_t *cf, srv_conf_t* us,
ngx_http_upstream_init_peer_pt init_peer)
{
auto rc = ngx_http_upstream_init_round_robin(cf, us);
NgxException::require(rc);
us->peer.init = init_peer;
}
public:
static T& init(ngx_http_request_t* r, srv_conf_t* us)
{
auto& peer_data = *NgxPool(r).alloc<T>();
r->upstream->peer.data = &(peer_data.*ptr);
auto rc = ngx_http_upstream_init_round_robin_peer(r, us);
NgxException::require(rc);
r->upstream->peer.get = get_peer;
r->upstream->peer.free = free_peer?free_peer:
r->upstream->peer.free;
return peer_data;
}
public:
static ngx_int_t round_robin(ngx_peer_connection_t* pc, void* data)
{
return ngx_http_upstream_get_round_robin_peer(pc, data);
}
};
#endif //_NGX_LOAD_BALANCE_HPP
|
// Copyright (c) 2015-2017
// Author: Chrono Law
#ifndef _NGX_LOAD_BALANCE_HPP
#define _NGX_LOAD_BALANCE_HPP
#include "NgxPool.hpp"
template<typename T,
ngx_event_get_peer_pt get_peer,
ngx_event_free_peer_pt free_peer = nullptr,
ngx_http_upstream_rr_peer_data_t T::* ptr = &T::rrp>
class NgxLoadBalance final
{
typedef ngx_http_upstream_rr_peer_data_t peer_data_t;
typedef ngx_http_upstream_srv_conf_t srv_conf_t;
public:
static void init(ngx_conf_t *cf, srv_conf_t* us,
ngx_http_upstream_init_peer_pt init_peer)
{
auto rc = ngx_http_upstream_init_round_robin(cf, us);
NgxException::require(rc);
us->peer.init = init_peer;
}
public:
static T& init(ngx_http_request_t* r, srv_conf_t* us)
{
auto& peer_data = *NgxPool(r).alloc<T>();
r->upstream->peer.data = &(peer_data.*ptr);
auto rc = ngx_http_upstream_init_round_robin_peer(r, us);
NgxException::require(rc);
r->upstream->peer.get = get_peer;
r->upstream->peer.free = (free_peer != nullptr)?free_peer:
r->upstream->peer.free;
return peer_data;
}
public:
static ngx_int_t round_robin(ngx_peer_connection_t* pc, void* data)
{
return ngx_http_upstream_get_round_robin_peer(pc, data);
}
};
#endif //_NGX_LOAD_BALANCE_HPP
|
fix nullptr warning in clang
|
fix nullptr warning in clang
|
C++
|
bsd-2-clause
|
chronolaw/ngx_cpp_dev,chronolaw/ngx_cpp_dev,chronolaw/ngx_cpp_dev
|
23e235bb3d2dc5ecbcd55956933b24baf33d0b76
|
test/acknowledgements_to_sql.cc
|
test/acknowledgements_to_sql.cc
|
/*
** Copyright 2012-2013 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <QSqlError>
#include <QSqlQuery>
#include <QVariant>
#include <sstream>
#include "com/centreon/broker/exceptions/msg.hh"
#include "test/config.hh"
#include "test/engine.hh"
#include "test/external_command.hh"
#include "test/generate.hh"
#include "test/misc.hh"
#include "test/vars.hh"
using namespace com::centreon::broker;
#define DB_NAME "broker_acknowledgements_to_sql"
#define FALSE_COMMAND_LINE "/bin/false"
#define FALSE_COMMAND "1"
/**
* Check that acknowledgements are properly inserted in SQL database.
*
* @return EXIT_SUCCESS on success.
*/
int main() {
// Return value.
int retval(EXIT_FAILURE);
// Variables that need cleaning.
std::list<host> hosts;
std::list<service> services;
std::list<command> commands;
std::string engine_config_path(tmpnam(NULL));
external_command commander;
engine daemon;
try {
// Prepare database.
QSqlDatabase db(config_db_open(DB_NAME));
// Prepare monitoring engine configuration parameters.
generate_commands(commands, 1);
for (std::list<command>::iterator
it(commands.begin()),
end(commands.end());
it != end;
++it) {
it->command_line = new char[sizeof(FALSE_COMMAND_LINE)];
strcpy(it->command_line, FALSE_COMMAND_LINE);
}
generate_hosts(hosts, 2);
for (std::list<host>::iterator it(hosts.begin()), end(hosts.end());
it != end;
++it) {
it->host_check_command = new char[sizeof(FALSE_COMMAND)];
strcpy(it->host_check_command, FALSE_COMMAND);
}
generate_services(services, hosts, 1);
for (std::list<service>::iterator
it(services.begin()),
end(services.end());
it != end;
++it) {
it->service_check_command = new char[sizeof(FALSE_COMMAND)];
strcpy(it->service_check_command, FALSE_COMMAND);
}
commander.set_file(tmpnam(NULL));
std::string additional_config;
{
std::ostringstream oss;
oss << "use_aggressive_host_checking=1\n"
<< commander.get_engine_config()
<< "broker_module=" << CBMOD_PATH << " "
<< PROJECT_SOURCE_DIR << "/test/cfg/acknowledgements_to_sql.xml\n";
additional_config = oss.str();
}
// Generate monitoring engine configuration files.
config_write(
engine_config_path.c_str(),
additional_config.c_str(),
&hosts,
&services,
&commands);
// Start monitoring engine.
std::string engine_config_file(engine_config_path);
engine_config_file.append("/nagios.cfg");
daemon.set_config_file(engine_config_file);
daemon.start();
// Let the daemon initialize and set checkpoints as non-OK.
sleep_for(15 * MONITORING_ENGINE_INTERVAL_LENGTH);
// Base time.
time_t now(time(NULL));
// Acknowledge the hosts.
{
std::ostringstream oss;
oss << "ACKNOWLEDGE_HOST_PROBLEM;1;1;0;0;Merethis;Random comment";
commander.execute(oss.str().c_str());
}
{
std::ostringstream oss;
oss << "ACKNOWLEDGE_HOST_PROBLEM;2;1;0;0;Centreon;Comment text.";
commander.execute(oss.str().c_str());
}
// Acknowledge the services.
{
std::ostringstream oss;
oss << "ACKNOWLEDGE_SVC_PROBLEM;1;1;1;0;0;Broker;Monitoring";
commander.execute(oss.str().c_str());
}
{
std::ostringstream oss;
oss << "ACKNOWLEDGE_SVC_PROBLEM;2;2;1;0;0;Author;Just a comment!";
commander.execute(oss.str().c_str());
}
// Let the monitoring engine process commands.
sleep_for(10 * MONITORING_ENGINE_INTERVAL_LENGTH);
// New time.
time_t t1(now);
now = time(NULL);
// Check acknowledgements.
{
std::ostringstream query;
query << "SELECT host_id, service_id, entry_time, author,"
<< " comment_data, deletion_time, notify_contacts,"
<< " persistent_comment, sticky, type"
<< " FROM acknowledgements"
<< " ORDER BY service_id ASC, host_id ASC";
QSqlQuery q(db);
if (!q.exec(query.str().c_str()))
throw (exceptions::msg()
<< "cannot get acknowledgements from DB: "
<< q.lastError().text().toStdString().c_str());
if (// Host acknowledgement #1.
!q.next()
|| (q.value(0).toUInt() != 1)
|| !q.value(1).isNull()
|| (static_cast<time_t>(q.value(2).toLongLong()) < t1)
|| (static_cast<time_t>(q.value(2).toLongLong()) > now)
|| (q.value(3).toString() != "Merethis")
|| (q.value(4).toString() != "Random comment")
|| !(q.value(5).isNull() || !q.value(5).toUInt())
|| q.value(6).toUInt()
|| q.value(7).toUInt()
// XXX: sticky not set || !q.value(8).toUInt()
|| q.value(9).toUInt()
// Host acknowledgement #2.
|| !q.next()
|| (q.value(0).toUInt() != 2)
|| !q.value(1).isNull()
|| (static_cast<time_t>(q.value(2).toLongLong()) < t1)
|| (static_cast<time_t>(q.value(2).toLongLong()) > now)
|| (q.value(3).toString() != "Centreon")
|| (q.value(4).toString() != "Comment text.")
|| !(q.value(5).isNull() || !q.value(5).toUInt())
|| q.value(6).toUInt()
|| q.value(7).toUInt()
// XXX: sticky not set || !q.value(8).toUInt()
|| q.value(9).toUInt()
// Service acknowledgement #1.
|| !q.next()
|| (q.value(0).toUInt() != 1)
|| (q.value(1).toUInt() != 1)
|| (static_cast<time_t>(q.value(2).toLongLong()) < t1)
|| (static_cast<time_t>(q.value(2).toLongLong()) > now)
|| (q.value(3).toString() != "Broker")
|| (q.value(4).toString() != "Monitoring")
|| !(q.value(5).isNull() || !q.value(5).toUInt())
|| q.value(6).toUInt()
|| q.value(7).toUInt()
// XXX: sticky not set || !q.value(8).toUInt()
|| (q.value(9).toUInt() != 1)
// Service acknowledgement #2.
|| !q.next()
|| (q.value(0).toUInt() != 2)
|| (q.value(1).toUInt() != 2)
|| (static_cast<time_t>(q.value(2).toLongLong()) < t1)
|| (static_cast<time_t>(q.value(2).toLongLong()) > now)
|| (q.value(3).toString() != "Author")
|| (q.value(4).toString() != "Just a comment!")
|| !(q.value(5).isNull() || !q.value(5).toUInt())
|| q.value(6).toUInt()
|| q.value(7).toUInt()
// XXX: sticky not set || !q.value(8).toUInt()
|| (q.value(9).toUInt() != 1)
// EOF.
|| q.next())
throw (exceptions::msg()
<< "invalid acknowledgement entry in DB");
}
// Disable acknowledgements on host #1 and service #1.
commander.execute("REMOVE_HOST_ACKNOWLEDGEMENT;1");
commander.execute("REMOVE_SVC_ACKNOWLEDGEMENT;1;1");
// Disable active checks on host #2.
commander.execute("DISABLE_HOST_CHECK;2");
commander.execute(
"PROCESS_HOST_CHECK_RESULT;2;0;Submitted by unit test");
commander.execute(
"PROCESS_HOST_CHECK_RESULT;2;0;Submitted by unit test");
commander.execute(
"PROCESS_HOST_CHECK_RESULT;2;0;Submitted by unit test");
// Disable active check on service #2.
commander.execute("DISABLE_SVC_CHECK;2;2");
commander.execute(
"PROCESS_SERVICE_CHECK_RESULT;2;2;0;Submitted by unit test");
commander.execute(
"PROCESS_SERVICE_CHECK_RESULT;2;2;0;Submitted by unit test");
commander.execute(
"PROCESS_SERVICE_CHECK_RESULT;2;2;0;Submitted by unit test");
// Run a while.
sleep_for(12 * MONITORING_ENGINE_INTERVAL_LENGTH);
// Update time.
time_t t2(now);
now = time(NULL);
// Check hosts.
{
std::ostringstream query;
query << "SELECT host_id, acknowledged"
<< " FROM hosts"
<< " ORDER BY host_id";
QSqlQuery q(db);
if (!q.exec(query.str().c_str()))
throw (exceptions::msg() << "cannot get host list from DB: "
<< q.lastError().text().toStdString().c_str());
if (!q.next()
|| (q.value(0).toUInt() != 1)
|| q.value(1).toUInt()
|| !q.next()
|| (q.value(0).toUInt() != 2)
|| q.value(1).toUInt()
|| q.next())
throw (exceptions::msg()
<< "invalid host entry after deletion");
}
// Check services.
{
std::ostringstream query;
query << "SELECT host_id, service_id, acknowledged"
<< " FROM services"
<< " ORDER BY host_id ASC, service_id ASC";
QSqlQuery q(db);
if (!q.exec(query.str().c_str()))
throw (exceptions::msg() << "cannot get service list from DB: "
<< q.lastError().text().toStdString().c_str());
if (!q.next()
|| (q.value(0).toUInt() != 1)
|| (q.value(1).toUInt() != 1)
|| q.value(2).toUInt()
|| !q.next()
|| (q.value(0).toUInt() != 2)
|| (q.value(1).toUInt() != 2)
|| q.value(2).toUInt()
|| q.next())
throw (exceptions::msg()
<< "invalid service entry after deletion");
}
// Check acknowledgements.
{
std::ostringstream query;
query << "SELECT host_id, service_id, deletion_time"
<< " FROM acknowledgements"
<< " ORDER BY service_id ASC, host_id ASC";
QSqlQuery q(db);
if (!q.exec(query.str().c_str()))
throw (exceptions::msg()
<< "cannot get acknowledgement list from DB: "
<< q.lastError().text().toStdString().c_str());
if (// Host acknowledgement #1.
!q.next()
|| (q.value(0).toUInt() != 1)
|| !q.value(1).isNull()
|| (static_cast<time_t>(q.value(2).toLongLong()) < t2)
|| (static_cast<time_t>(q.value(2).toLongLong()) > now)
// Host acknowledgement #2.
|| !q.next()
|| (q.value(0).toUInt() != 2)
|| !q.value(1).isNull()
|| !(q.value(2).isNull() || !q.value(2).toUInt())
// Service acknowledgement #1.
|| !q.next()
|| (q.value(0).toUInt() != 1)
|| (q.value(1).toUInt() != 1)
|| (static_cast<time_t>(q.value(2).toLongLong()) < t2)
|| (static_cast<time_t>(q.value(2).toLongLong()) > now)
// Service acknowledgement #2.
|| !q.next()
|| (q.value(0).toUInt() != 2)
|| (q.value(1).toUInt() != 2)
|| !(q.value(2).isNull() || !q.value(2).toUInt())
// EOF
|| q.next())
throw (exceptions::msg()
<< "invalid acknowledgement entry after deletion");
}
// Success.
retval = EXIT_SUCCESS;
}
catch (std::exception const& e) {
std::cerr << e.what() << std::endl;
}
catch (...) {
std::cerr << "unknown exception" << std::endl;
}
// Cleanup.
daemon.stop();
config_remove(engine_config_path.c_str());
config_db_close(DB_NAME);
free_hosts(hosts);
free_services(services);
return (retval);
}
|
/*
** Copyright 2012-2013 Merethis
**
** This file is part of Centreon Broker.
**
** Centreon Broker is free software: you can redistribute it and/or
** modify it under the terms of the GNU General Public License version 2
** as published by the Free Software Foundation.
**
** Centreon Broker is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
** General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with Centreon Broker. If not, see
** <http://www.gnu.org/licenses/>.
*/
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iostream>
#include <QSqlError>
#include <QSqlQuery>
#include <QVariant>
#include <sstream>
#include "com/centreon/broker/exceptions/msg.hh"
#include "test/config.hh"
#include "test/engine.hh"
#include "test/external_command.hh"
#include "test/generate.hh"
#include "test/misc.hh"
#include "test/vars.hh"
using namespace com::centreon::broker;
#define DB_NAME "broker_acknowledgements_to_sql"
/**
* Check that acknowledgements are properly inserted in SQL database.
*
* @return EXIT_SUCCESS on success.
*/
int main() {
// Return value.
int retval(EXIT_FAILURE);
// Variables that need cleaning.
std::list<host> hosts;
std::list<service> services;
std::list<command> commands;
std::string engine_config_path(tmpnam(NULL));
external_command commander;
engine daemon;
try {
// Prepare database.
QSqlDatabase db(config_db_open(DB_NAME));
// Prepare monitoring engine configuration parameters.
generate_commands(commands, 1);
for (std::list<command>::iterator
it(commands.begin()),
end(commands.end());
it != end;
++it) {
char const* cmdline(MY_PLUGIN_PATH " 2");
it->command_line = new char[strlen(cmdline) + 1];
strcpy(it->command_line, cmdline);
}
generate_hosts(hosts, 2);
for (std::list<host>::iterator it(hosts.begin()), end(hosts.end());
it != end;
++it) {
it->accept_passive_host_checks = 1;
it->host_check_command = new char[2];
strcpy(it->host_check_command, "1");
}
generate_services(services, hosts, 1);
for (std::list<service>::iterator
it(services.begin()),
end(services.end());
it != end;
++it) {
it->accept_passive_service_checks = 1;
it->service_check_command = new char[2];
strcpy(it->service_check_command, "1");
}
commander.set_file(tmpnam(NULL));
std::string additional_config;
{
std::ostringstream oss;
oss << "use_aggressive_host_checking=1\n"
<< commander.get_engine_config()
<< "broker_module=" << CBMOD_PATH << " "
<< PROJECT_SOURCE_DIR << "/test/cfg/acknowledgements_to_sql.xml\n";
additional_config = oss.str();
}
// Generate monitoring engine configuration files.
config_write(
engine_config_path.c_str(),
additional_config.c_str(),
&hosts,
&services,
&commands);
// Start monitoring engine.
std::string engine_config_file(engine_config_path);
engine_config_file.append("/nagios.cfg");
daemon.set_config_file(engine_config_file);
daemon.start();
// Let the daemon initialize and set checkpoints as non-OK.
sleep_for(15 * MONITORING_ENGINE_INTERVAL_LENGTH);
// Base time.
time_t now(time(NULL));
// Acknowledge the hosts.
{
std::ostringstream oss;
oss << "ACKNOWLEDGE_HOST_PROBLEM;1;1;0;0;Merethis;Random comment";
commander.execute(oss.str().c_str());
}
{
std::ostringstream oss;
oss << "ACKNOWLEDGE_HOST_PROBLEM;2;1;0;0;Centreon;Comment text.";
commander.execute(oss.str().c_str());
}
// Acknowledge the services.
{
std::ostringstream oss;
oss << "ACKNOWLEDGE_SVC_PROBLEM;1;1;1;0;0;Broker;Monitoring";
commander.execute(oss.str().c_str());
}
{
std::ostringstream oss;
oss << "ACKNOWLEDGE_SVC_PROBLEM;2;2;1;0;0;Author;Just a comment!";
commander.execute(oss.str().c_str());
}
// Let the monitoring engine process commands.
sleep_for(10 * MONITORING_ENGINE_INTERVAL_LENGTH);
// New time.
time_t t1(now);
now = time(NULL);
// Check acknowledgements.
{
std::ostringstream query;
query << "SELECT host_id, service_id, entry_time, author,"
<< " comment_data, deletion_time, notify_contacts,"
<< " persistent_comment, sticky, type"
<< " FROM acknowledgements"
<< " ORDER BY service_id ASC, host_id ASC";
QSqlQuery q(db);
if (!q.exec(query.str().c_str()))
throw (exceptions::msg()
<< "cannot get acknowledgements from DB: "
<< q.lastError().text().toStdString().c_str());
if (// Host acknowledgement #1.
!q.next()
|| (q.value(0).toUInt() != 1)
|| !q.value(1).isNull()
|| (static_cast<time_t>(q.value(2).toLongLong()) < t1)
|| (static_cast<time_t>(q.value(2).toLongLong()) > now)
|| (q.value(3).toString() != "Merethis")
|| (q.value(4).toString() != "Random comment")
|| !(q.value(5).isNull() || !q.value(5).toUInt())
|| q.value(6).toUInt()
|| q.value(7).toUInt()
// XXX: sticky not set || !q.value(8).toUInt()
|| q.value(9).toUInt()
// Host acknowledgement #2.
|| !q.next()
|| (q.value(0).toUInt() != 2)
|| !q.value(1).isNull()
|| (static_cast<time_t>(q.value(2).toLongLong()) < t1)
|| (static_cast<time_t>(q.value(2).toLongLong()) > now)
|| (q.value(3).toString() != "Centreon")
|| (q.value(4).toString() != "Comment text.")
|| !(q.value(5).isNull() || !q.value(5).toUInt())
|| q.value(6).toUInt()
|| q.value(7).toUInt()
// XXX: sticky not set || !q.value(8).toUInt()
|| q.value(9).toUInt()
// Service acknowledgement #1.
|| !q.next()
|| (q.value(0).toUInt() != 1)
|| (q.value(1).toUInt() != 1)
|| (static_cast<time_t>(q.value(2).toLongLong()) < t1)
|| (static_cast<time_t>(q.value(2).toLongLong()) > now)
|| (q.value(3).toString() != "Broker")
|| (q.value(4).toString() != "Monitoring")
|| !(q.value(5).isNull() || !q.value(5).toUInt())
|| q.value(6).toUInt()
|| q.value(7).toUInt()
// XXX: sticky not set || !q.value(8).toUInt()
|| (q.value(9).toUInt() != 1)
// Service acknowledgement #2.
|| !q.next()
|| (q.value(0).toUInt() != 2)
|| (q.value(1).toUInt() != 2)
|| (static_cast<time_t>(q.value(2).toLongLong()) < t1)
|| (static_cast<time_t>(q.value(2).toLongLong()) > now)
|| (q.value(3).toString() != "Author")
|| (q.value(4).toString() != "Just a comment!")
|| !(q.value(5).isNull() || !q.value(5).toUInt())
|| q.value(6).toUInt()
|| q.value(7).toUInt()
// XXX: sticky not set || !q.value(8).toUInt()
|| (q.value(9).toUInt() != 1)
// EOF.
|| q.next())
throw (exceptions::msg()
<< "invalid acknowledgement entry in DB");
}
// Disable acknowledgements on host #1 and service #1.
commander.execute("REMOVE_HOST_ACKNOWLEDGEMENT;1");
commander.execute("REMOVE_SVC_ACKNOWLEDGEMENT;1;1");
// Disable active checks on host #2.
commander.execute("DISABLE_HOST_CHECK;2");
commander.execute(
"PROCESS_HOST_CHECK_RESULT;2;0;Submitted by unit test");
commander.execute(
"PROCESS_HOST_CHECK_RESULT;2;0;Submitted by unit test");
commander.execute(
"PROCESS_HOST_CHECK_RESULT;2;0;Submitted by unit test");
// Disable active check on service #2.
commander.execute("DISABLE_SVC_CHECK;2;2");
commander.execute(
"PROCESS_SERVICE_CHECK_RESULT;2;2;0;Submitted by unit test");
commander.execute(
"PROCESS_SERVICE_CHECK_RESULT;2;2;0;Submitted by unit test");
commander.execute(
"PROCESS_SERVICE_CHECK_RESULT;2;2;0;Submitted by unit test");
// Run a while.
sleep_for(12 * MONITORING_ENGINE_INTERVAL_LENGTH);
// Update time.
time_t t2(now);
now = time(NULL);
// Check hosts.
{
std::ostringstream query;
query << "SELECT host_id, acknowledged"
<< " FROM hosts"
<< " ORDER BY host_id";
QSqlQuery q(db);
if (!q.exec(query.str().c_str()))
throw (exceptions::msg() << "cannot get host list from DB: "
<< q.lastError().text().toStdString().c_str());
if (!q.next()
|| (q.value(0).toUInt() != 1)
|| q.value(1).toUInt()
|| !q.next()
|| (q.value(0).toUInt() != 2)
|| q.value(1).toUInt()
|| q.next())
throw (exceptions::msg()
<< "invalid host entry after deletion");
}
// Check services.
{
std::ostringstream query;
query << "SELECT host_id, service_id, acknowledged"
<< " FROM services"
<< " ORDER BY host_id ASC, service_id ASC";
QSqlQuery q(db);
if (!q.exec(query.str().c_str()))
throw (exceptions::msg() << "cannot get service list from DB: "
<< q.lastError().text().toStdString().c_str());
if (!q.next()
|| (q.value(0).toUInt() != 1)
|| (q.value(1).toUInt() != 1)
|| q.value(2).toUInt()
|| !q.next()
|| (q.value(0).toUInt() != 2)
|| (q.value(1).toUInt() != 2)
|| q.value(2).toUInt()
|| q.next())
throw (exceptions::msg()
<< "invalid service entry after deletion");
}
// Check acknowledgements.
{
std::ostringstream query;
query << "SELECT host_id, service_id, deletion_time"
<< " FROM acknowledgements"
<< " ORDER BY service_id ASC, host_id ASC";
QSqlQuery q(db);
if (!q.exec(query.str().c_str()))
throw (exceptions::msg()
<< "cannot get acknowledgement list from DB: "
<< q.lastError().text().toStdString().c_str());
if (// Host acknowledgement #1.
!q.next()
|| (q.value(0).toUInt() != 1)
|| !q.value(1).isNull()
|| (static_cast<time_t>(q.value(2).toLongLong()) < t2)
|| (static_cast<time_t>(q.value(2).toLongLong()) > now)
// Host acknowledgement #2.
|| !q.next()
|| (q.value(0).toUInt() != 2)
|| !q.value(1).isNull()
|| !(q.value(2).isNull() || !q.value(2).toUInt())
// Service acknowledgement #1.
|| !q.next()
|| (q.value(0).toUInt() != 1)
|| (q.value(1).toUInt() != 1)
|| (static_cast<time_t>(q.value(2).toLongLong()) < t2)
|| (static_cast<time_t>(q.value(2).toLongLong()) > now)
// Service acknowledgement #2.
|| !q.next()
|| (q.value(0).toUInt() != 2)
|| (q.value(1).toUInt() != 2)
|| !(q.value(2).isNull() || !q.value(2).toUInt())
// EOF
|| q.next())
throw (exceptions::msg()
<< "invalid acknowledgement entry after deletion");
}
// Success.
retval = EXIT_SUCCESS;
}
catch (std::exception const& e) {
std::cerr << e.what() << std::endl;
}
catch (...) {
std::cerr << "unknown exception" << std::endl;
}
// Cleanup.
daemon.stop();
config_remove(engine_config_path.c_str());
//config_db_close(DB_NAME);
free_hosts(hosts);
free_services(services);
return (retval);
}
|
Fix the 'live' acknowledgement test.
|
Fix the 'live' acknowledgement test.
|
C++
|
apache-2.0
|
centreon/centreon-broker,centreon/centreon-broker,centreon/centreon-broker,centreon/centreon-broker,centreon/centreon-broker
|
b2910300d2e8474d3342ef478ada10fdd0b3c5cd
|
sw.cpp
|
sw.cpp
|
#ifdef SW_PRAGMA_HEADER
#pragma sw header on
void gen_stamp(NativeExecutedTarget &t)
{
auto tools_stamp_gen = THIS_PREFIX "." "primitives.tools.stamp_gen" "-" THIS_VERSION_DEPENDENCY;
{
auto d = t + tools_stamp_gen;
d->Dummy = true;
}
auto out = t.BinaryPrivateDir / "stamp.h.in";
SW_MAKE_COMMAND_AND_ADD(c, t);
c->always = true;
c->setProgram(tools_stamp_gen);
c->redirectStdout(out);
c->addOutput(out);
t += out;
}
void gen_sqlite2cpp(NativeExecutedTarget &t, const path &sql_file, const path &out_file, const String &ns)
{
auto tools_sqlite2cpp = THIS_PREFIX "." "primitives.tools.sqlpp11.sqlite2cpp" "-" THIS_VERSION_DEPENDENCY;
{
auto d = t + tools_sqlite2cpp;
d->Dummy = true;
}
auto out = t.BinaryDir / out_file;
SW_MAKE_COMMAND_AND_ADD(c, t);
c->setProgram(tools_sqlite2cpp);
c->args.push_back(sql_file.u8string());
c->args.push_back(out.u8string());
c->args.push_back(ns);
c->addInput(sql_file);
c->addOutput(out);
t += out;
}
void embed(NativeExecutedTarget &t, const path &in)
{
if (in.is_absolute())
throw std::runtime_error("embed: in must be relative to SourceDir");
auto embedder = THIS_PREFIX "." "primitives.tools.embedder" "-" THIS_VERSION_DEPENDENCY;
{
auto d = t + embedder;
d->Dummy = true;
}
auto f = t.SourceDir / in;
auto wdir = f.parent_path();
auto out = t.BinaryDir / in.parent_path() / in.filename().stem();
SW_MAKE_COMMAND_AND_ADD(c, t);
c->setProgram(embedder);
c->working_directory = wdir;
c->args.push_back(f.u8string());
c->args.push_back(out.u8string());
c->addInput(f);
c->addOutput(out);
t += in, out;
t += IncludeDirectory(out.parent_path()); // but remove this later
}
void syncqt(NativeExecutedTarget &t, const Strings &modules)
{
auto sqt = THIS_PREFIX "." "primitives.tools.syncqt" "-" THIS_VERSION_DEPENDENCY;
{
auto d = t + sqt;
d->Dummy = true;
}
auto v = t.pkg.version.toString();
for (auto &m : modules)
{
fs::create_directories(t.BinaryDir / "include" / m / v / m);
auto c = t.addCommand();
c << cmd::prog(sqt)
<< "-s" << t.SourceDir
<< "-b" << t.BinaryDir
<< "-m" << m
<< "-v" << v
<< cmd::end()
<< cmd::out(t.BinaryDir / "include" / m / m)
;
t.Public += IncludeDirectory(t.BinaryDir / "include");
t.Public += IncludeDirectory(t.BinaryDir / "include" / m);
t.Public += IncludeDirectory(t.BinaryDir / "include" / m / v);
t.Public += IncludeDirectory(t.BinaryDir / "include" / m / v / m);
}
}
#pragma sw header off
#endif
#pragma sw require header org.sw.demo.ragel-6
#pragma sw require header org.sw.demo.lexxmark.winflexbison.bison-master
#define ADD_LIBRARY_WITH_NAME(var, name) \
auto &var = p.addTarget<LibraryTarget>(name); \
setup_primitives(var)
#define ADD_LIBRARY(x) ADD_LIBRARY_WITH_NAME(x, #x)
void configure(Solution &s)
{
//s.Settings.Native.LibrariesType = LibraryType::Static;
s.Settings.Native.ConfigurationType = ConfigurationType::Debug;
}
void build(Solution &s)
{
auto &p = s.addProject("primitives", "master");
p += Git("https://github.com/egorpugin/primitives", "", "master");
auto setup_primitives_no_all_sources = [](auto &t)
{
path p = "src";
auto n = t.getPackage().ppath.slice(t.getPackage().ppath.isAbsolute() ? 3 : 1);
auto n2 = n;
while (!n.empty())
{
p /= n.front();
n = n.slice(1);
}
t.ApiName = "PRIMITIVES_" + boost::to_upper_copy(n2.toString("_")) + "_API";
t.CPPVersion = CPPLanguageStandard::CPP17;
t.PackageDefinitions = true;
return p;
};
auto setup_primitives = [&setup_primitives_no_all_sources](auto &t)
{
auto p = setup_primitives_no_all_sources(t);
t.setRootDirectory(p);
// explicit!
t += "include/.*"_rr;
t += "src/.*"_rr;
};
ADD_LIBRARY(error_handling);
auto &templates = p.addTarget<StaticLibraryTarget>("templates");
setup_primitives(templates);
ADD_LIBRARY(string);
string.Public += "org.sw.demo.boost.algorithm-1"_dep;
ADD_LIBRARY(filesystem);
filesystem.Public += string, templates,
"org.sw.demo.boost.filesystem-1"_dep,
"org.sw.demo.boost.thread-1"_dep,
"org.sw.demo.grisumbras.enum_flags-master"_dep;
ADD_LIBRARY(file_monitor);
file_monitor.Public += filesystem,
"org.sw.demo.libuv-1"_dep;
ADD_LIBRARY(context);
context.Public += filesystem;
ADD_LIBRARY(executor);
executor.Public += templates,
"org.sw.demo.boost.asio-1"_dep,
"org.sw.demo.boost.system-1"_dep;
ADD_LIBRARY(command);
command.Public += file_monitor,
"org.sw.demo.boost.process-1"_dep;
if (s.Settings.TargetOS.Type == OSType::Windows)
command.Public += "Shell32.lib"_l;
ADD_LIBRARY(date_time);
date_time.Public += string,
"org.sw.demo.boost.date_time-1"_dep;
ADD_LIBRARY(lock);
lock.Public += filesystem,
"org.sw.demo.boost.interprocess-1"_dep;
ADD_LIBRARY(log);
log.Public += "org.sw.demo.boost.log-1"_dep;
ADD_LIBRARY(cron);
cron.Public += executor, log;
ADD_LIBRARY(yaml);
yaml.Public += string,
"org.sw.demo.jbeder.yaml_cpp-master"_dep;
ADD_LIBRARY(pack);
pack.Public += filesystem, templates,
"org.sw.demo.libarchive.libarchive-3"_dep;
ADD_LIBRARY(http);
http.Public += filesystem, templates,
"org.sw.demo.badger.curl.libcurl-7"_dep;
if (s.Settings.TargetOS.Type == OSType::Windows)
http.Public += "Winhttp.lib"_l;
ADD_LIBRARY(hash);
hash.Public += filesystem,
"org.sw.demo.aleksey14.rhash-1"_dep,
"org.sw.demo.openssl.crypto-1.*.*.*"_dep;
ADD_LIBRARY(win32helpers);
win32helpers.Public += filesystem,
"org.sw.demo.boost.dll-1"_dep,
"org.sw.demo.boost.algorithm-1"_dep;
if (s.Settings.TargetOS.Type == OSType::Windows)
{
win32helpers.Public += "UNICODE"_d;
win32helpers += "Shell32.lib"_lib, "Ole32.lib"_lib, "Advapi32.lib"_lib, "user32.lib"_lib;
}
ADD_LIBRARY_WITH_NAME(db_common, "db.common");
db_common.Public += filesystem, templates,
"org.sw.demo.imageworks.pystring-1"_dep;
ADD_LIBRARY_WITH_NAME(db_sqlite3, "db.sqlite3");
db_sqlite3.Public += db_common, "org.sw.demo.sqlite3"_dep;
ADD_LIBRARY_WITH_NAME(db_postgresql, "db.postgresql");
db_postgresql.Public += db_common, "org.sw.demo.jtv.pqxx-*"_dep;
auto &main = p.addTarget<StaticLibraryTarget>("main");
setup_primitives(main);
main.Public += error_handling;
ADD_LIBRARY(settings);
settings.Public += yaml, filesystem, templates,
"pub.egorpugin.llvm_project.llvm.support_lite-master"_dep;
gen_flex_bison_pair(settings, "LALR1_CPP_VARIANT_PARSER", "src/settings");
gen_flex_bison_pair(settings, "LALR1_CPP_VARIANT_PARSER", "src/path");
ADD_LIBRARY(symbol);
symbol.Public += filesystem, "org.sw.demo.boost.dll-1"_dep;
ADD_LIBRARY_WITH_NAME(sw_settings, "sw.settings");
sw_settings.Public += settings;
sw_settings -= "src/sw.settings.program_name.cpp";
//sw_settings.Interface += "src/sw.settings.program_name.cpp";
ADD_LIBRARY(version);
version.Public += string, templates,
"org.sw.demo.fmt-*"_dep,
"org.sw.demo.boost.container_hash-1"_dep,
"org.sw.demo.imageworks.pystring-1"_dep;
gen_ragel(version, "src/version.rl");
gen_flex_bison_pair(version, "GLR_CPP_PARSER", "src/range");
auto &sw_main = p.addTarget<StaticLibraryTarget>("sw.main");
setup_primitives(sw_main);
sw_main.Public += main, sw_settings,
"org.sw.demo.boost.dll-1"_dep;
sw_main.Interface.LinkLibraries.push_back(main.getImportLibrary()); // main itself
sw_main.Interface.LinkLibraries.push_back(sw_main.getImportLibrary()); // then me (self, sw.main)
sw_main.Interface.LinkLibraries.push_back(sw_settings.getImportLibrary()); // then sw.settings
if (s.Settings.TargetOS.Type == OSType::Windows)
{
sw_main.Public +=
"org.sw.demo.google.breakpad.client.windows.handler-master"_dep,
"org.sw.demo.google.breakpad.client.windows.crash_generation.client-master"_dep,
"org.sw.demo.google.breakpad.client.windows.crash_generation.server-master"_dep
;
}
auto &tools_embedder = p.addTarget<ExecutableTarget>("tools.embedder");
setup_primitives_no_all_sources(tools_embedder);
tools_embedder += "src/tools/embedder.cpp";
tools_embedder += filesystem, sw_main;
auto &tools_sqlite2cpp = p.addTarget<ExecutableTarget>("tools.sqlpp11.sqlite2cpp");
setup_primitives_no_all_sources(tools_sqlite2cpp);
tools_sqlite2cpp += "src/tools/sqlpp11.sqlite2cpp.cpp";
tools_sqlite2cpp += filesystem, context, sw_main, "org.sw.demo.sqlite3"_dep;
auto &tools_syncqt = p.addTarget<ExecutableTarget>("tools.syncqt");
setup_primitives_no_all_sources(tools_syncqt);
tools_syncqt += "src/tools/syncqt.cpp";
tools_syncqt += filesystem, sw_main;
auto &stamp_gen = p.addTarget<ExecutableTarget>("tools.stamp_gen");
setup_primitives_no_all_sources(stamp_gen);
stamp_gen += "src/tools/stamp_gen.cpp";
auto &test = p.addDirectory("test");
test.Scope = TargetScope::Test;
auto add_test = [&test, &s](const String &name) -> decltype(auto)
{
auto &t = test.addTarget<ExecutableTarget>(name);
t.CPPVersion = CPPLanguageStandard::CPP17;
t += path("src/" + name + ".cpp");
t += "org.sw.demo.catchorg.catch2-*"_dep;
if (s.Settings.Native.CompilerType == CompilerType::MSVC)
t.CompileOptions.push_back("-bigobj");
//else if (s.Settings.Native.CompilerType == CompilerType::GNU)
//t.CompileOptions.push_back("-Wa,-mbig-obj");
return t;
};
auto &test_main = add_test("main");
test_main += sw_main, command, date_time,
executor, hash, yaml, context, http,
"org.sw.demo.nlohmann.json-*"_dep;
auto &test_db = add_test("db");
test_db += sw_main, command, db_sqlite3, db_postgresql, date_time,
executor, hash, yaml;
auto &test_settings = add_test("settings");
test_settings.PackageDefinitions = true;
test_settings += sw_main, settings;
auto &test_version = add_test("version");
test_version += sw_main, version;
s.addTest(test_main);
s.addTest(test_db);
s.addTest(test_settings);
s.addTest(test_version);
}
|
#ifdef SW_PRAGMA_HEADER
#pragma sw header on
void gen_stamp(NativeExecutedTarget &t)
{
auto tools_stamp_gen = THIS_PREFIX "." "primitives.tools.stamp_gen" "-" THIS_VERSION_DEPENDENCY;
{
auto d = t + tools_stamp_gen;
d->Dummy = true;
}
auto out = t.BinaryPrivateDir / "stamp.h.in";
SW_MAKE_COMMAND_AND_ADD(c, t);
c->always = true;
c->setProgram(tools_stamp_gen);
c->redirectStdout(out);
c->addOutput(out);
t += out;
}
void gen_sqlite2cpp(NativeExecutedTarget &t, const path &sql_file, const path &out_file, const String &ns)
{
auto tools_sqlite2cpp = THIS_PREFIX "." "primitives.tools.sqlpp11.sqlite2cpp" "-" THIS_VERSION_DEPENDENCY;
{
auto d = t + tools_sqlite2cpp;
d->Dummy = true;
}
auto out = t.BinaryDir / out_file;
SW_MAKE_COMMAND_AND_ADD(c, t);
c->setProgram(tools_sqlite2cpp);
c->args.push_back(sql_file.u8string());
c->args.push_back(out.u8string());
c->args.push_back(ns);
c->addInput(sql_file);
c->addOutput(out);
t += out;
}
void embed(NativeExecutedTarget &t, const path &in)
{
if (in.is_absolute())
throw std::runtime_error("embed: in must be relative to SourceDir");
auto embedder = THIS_PREFIX "." "primitives.tools.embedder" "-" THIS_VERSION_DEPENDENCY;
{
auto d = t + embedder;
d->Dummy = true;
}
auto f = t.SourceDir / in;
auto wdir = f.parent_path();
auto out = t.BinaryDir / in.parent_path() / in.filename().stem();
SW_MAKE_COMMAND_AND_ADD(c, t);
c->setProgram(embedder);
c->working_directory = wdir;
c->args.push_back(f.u8string());
c->args.push_back(out.u8string());
c->addInput(f);
c->addOutput(out);
t += in, out;
t += IncludeDirectory(out.parent_path()); // but remove this later
}
void syncqt(NativeExecutedTarget &t, const Strings &modules)
{
auto sqt = THIS_PREFIX "." "primitives.tools.syncqt" "-" THIS_VERSION_DEPENDENCY;
{
auto d = t + sqt;
d->Dummy = true;
}
auto v = t.pkg.version.toString();
for (auto &m : modules)
{
fs::create_directories(t.BinaryDir / "include" / m / v / m);
auto c = t.addCommand();
c << cmd::prog(sqt)
<< "-s" << t.SourceDir
<< "-b" << t.BinaryDir
<< "-m" << m
<< "-v" << v
<< cmd::end()
<< cmd::out(t.BinaryDir / "include" / m / m)
;
t.Public += IncludeDirectory(t.BinaryDir / "include");
t.Public += IncludeDirectory(t.BinaryDir / "include" / m);
t.Public += IncludeDirectory(t.BinaryDir / "include" / m / v);
t.Public += IncludeDirectory(t.BinaryDir / "include" / m / v / m);
}
}
#pragma sw header off
#endif
#pragma sw require header org.sw.demo.ragel-6
#pragma sw require header org.sw.demo.lexxmark.winflexbison.bison-master
#define ADD_LIBRARY_WITH_NAME(var, name) \
auto &var = p.addTarget<LibraryTarget>(name); \
setup_primitives(var)
#define ADD_LIBRARY(x) ADD_LIBRARY_WITH_NAME(x, #x)
void configure(Solution &s)
{
//s.Settings.Native.LibrariesType = LibraryType::Static;
s.Settings.Native.ConfigurationType = ConfigurationType::Debug;
}
void build(Solution &s)
{
auto &p = s.addProject("primitives", "master");
p += Git("https://github.com/egorpugin/primitives", "", "master");
auto setup_primitives_no_all_sources = [](auto &t)
{
path p = "src";
auto n = t.getPackage().ppath.slice(t.getPackage().ppath.isAbsolute() ? 3 : 1);
auto n2 = n;
while (!n.empty())
{
p /= n.front();
n = n.slice(1);
}
t.ApiName = "PRIMITIVES_" + boost::to_upper_copy(n2.toString("_")) + "_API";
t.CPPVersion = CPPLanguageStandard::CPP17;
t.PackageDefinitions = true;
return p;
};
auto setup_primitives = [&setup_primitives_no_all_sources](auto &t)
{
auto p = setup_primitives_no_all_sources(t);
t.setRootDirectory(p);
// explicit!
t += "include/.*"_rr;
t += "src/.*"_rr;
};
ADD_LIBRARY(error_handling);
auto &templates = p.addTarget<StaticLibraryTarget>("templates");
setup_primitives(templates);
ADD_LIBRARY(string);
string.Public += "org.sw.demo.boost.algorithm-1"_dep;
ADD_LIBRARY(filesystem);
filesystem.Public += string, templates,
"org.sw.demo.boost.filesystem-1"_dep,
"org.sw.demo.boost.thread-1"_dep,
"org.sw.demo.grisumbras.enum_flags-master"_dep;
ADD_LIBRARY(file_monitor);
file_monitor.Public += filesystem,
"org.sw.demo.libuv-1"_dep;
ADD_LIBRARY(context);
context.Public += filesystem;
ADD_LIBRARY(executor);
executor.Public += templates,
"org.sw.demo.boost.asio-1"_dep,
"org.sw.demo.boost.system-1"_dep;
ADD_LIBRARY(command);
command.Public += file_monitor,
"org.sw.demo.boost.process-1"_dep;
if (s.Settings.TargetOS.Type == OSType::Windows)
command.Public += "Shell32.lib"_l;
ADD_LIBRARY(date_time);
date_time.Public += string,
"org.sw.demo.boost.date_time-1"_dep;
ADD_LIBRARY(lock);
lock.Public += filesystem,
"org.sw.demo.boost.interprocess-1"_dep;
ADD_LIBRARY(log);
log.Public += "org.sw.demo.boost.log-1"_dep;
ADD_LIBRARY(cron);
cron.Public += executor, log;
ADD_LIBRARY(yaml);
yaml.Public += string,
"org.sw.demo.jbeder.yaml_cpp-master"_dep;
ADD_LIBRARY(pack);
pack.Public += filesystem, templates,
"org.sw.demo.libarchive.libarchive-3"_dep;
ADD_LIBRARY(http);
http.Public += filesystem, templates,
"org.sw.demo.badger.curl.libcurl-7"_dep;
if (s.Settings.TargetOS.Type == OSType::Windows)
http.Public += "Winhttp.lib"_l;
ADD_LIBRARY(hash);
hash.Public += filesystem,
"org.sw.demo.aleksey14.rhash-1"_dep,
"org.sw.demo.openssl.crypto-1.*.*.*"_dep;
ADD_LIBRARY(win32helpers);
win32helpers.Public += filesystem,
"org.sw.demo.boost.dll-1"_dep,
"org.sw.demo.boost.algorithm-1"_dep;
if (s.Settings.TargetOS.Type == OSType::Windows)
{
win32helpers.Public += "UNICODE"_d;
win32helpers += "Shell32.lib"_lib, "Ole32.lib"_lib, "Advapi32.lib"_lib, "user32.lib"_lib;
}
ADD_LIBRARY_WITH_NAME(db_common, "db.common");
db_common.Public += filesystem, templates,
"org.sw.demo.imageworks.pystring-1"_dep;
ADD_LIBRARY_WITH_NAME(db_sqlite3, "db.sqlite3");
db_sqlite3.Public += db_common, "org.sw.demo.sqlite3"_dep;
ADD_LIBRARY_WITH_NAME(db_postgresql, "db.postgresql");
db_postgresql.Public += db_common, "org.sw.demo.jtv.pqxx-*"_dep;
auto &main = p.addTarget<StaticLibraryTarget>("main");
setup_primitives(main);
main.Public += error_handling;
ADD_LIBRARY(settings);
settings.Public += yaml, filesystem, templates,
"pub.egorpugin.llvm_project.llvm.support_lite-master"_dep;
gen_flex_bison_pair(settings, "LALR1_CPP_VARIANT_PARSER", "src/settings");
gen_flex_bison_pair(settings, "LALR1_CPP_VARIANT_PARSER", "src/path");
ADD_LIBRARY(symbol);
symbol.Public += filesystem, "org.sw.demo.boost.dll-1"_dep;
ADD_LIBRARY_WITH_NAME(sw_settings, "sw.settings");
sw_settings.Public += settings;
sw_settings -= "src/sw.settings.program_name.cpp";
//sw_settings.Interface += "src/sw.settings.program_name.cpp";
ADD_LIBRARY(version);
version.Public += string, templates,
"org.sw.demo.fmt-*"_dep,
"org.sw.demo.boost.container_hash-1"_dep,
"org.sw.demo.imageworks.pystring-1"_dep;
gen_ragel(version, "src/version.rl");
gen_flex_bison_pair(version, "GLR_CPP_PARSER", "src/range");
auto &sw_main = p.addTarget<StaticLibraryTarget>("sw.main");
setup_primitives(sw_main);
sw_main.Public += main, sw_settings,
"org.sw.demo.boost.dll-1"_dep;
sw_main.Interface.LinkLibraries.push_back(main.getImportLibrary()); // main itself
sw_main.Interface.LinkLibraries.push_back(sw_main.getImportLibrary()); // then me (self, sw.main)
sw_main.Interface.LinkLibraries.push_back(sw_settings.getImportLibrary()); // then sw.settings
if (s.Settings.TargetOS.Type == OSType::Windows)
{
sw_main.Public +=
"org.sw.demo.google.breakpad.client.windows.handler-master"_dep,
"org.sw.demo.google.breakpad.client.windows.crash_generation.client-master"_dep,
"org.sw.demo.google.breakpad.client.windows.crash_generation.server-master"_dep
;
}
auto &tools_embedder = p.addTarget<ExecutableTarget>("tools.embedder");
setup_primitives_no_all_sources(tools_embedder);
tools_embedder += "src/tools/embedder.cpp";
tools_embedder += filesystem, sw_main;
auto &tools_sqlite2cpp = p.addTarget<ExecutableTarget>("tools.sqlpp11.sqlite2cpp");
setup_primitives_no_all_sources(tools_sqlite2cpp);
tools_sqlite2cpp += "src/tools/sqlpp11.sqlite2cpp.cpp";
tools_sqlite2cpp += filesystem, context, sw_main, "org.sw.demo.sqlite3"_dep;
auto &tools_syncqt = p.addTarget<ExecutableTarget>("tools.syncqt");
setup_primitives_no_all_sources(tools_syncqt);
tools_syncqt += "src/tools/syncqt.cpp";
tools_syncqt += filesystem, sw_main;
auto &stamp_gen = p.addTarget<ExecutableTarget>("tools.stamp_gen");
setup_primitives_no_all_sources(stamp_gen);
stamp_gen += "src/tools/stamp_gen.cpp";
/*auto &test = p.addDirectory("test");
test.Scope = TargetScope::Test;
auto add_test = [&test, &s](const String &name) -> decltype(auto)
{
auto &t = test.addTarget<ExecutableTarget>(name);
t.CPPVersion = CPPLanguageStandard::CPP17;
t += path("src/" + name + ".cpp");
t += "org.sw.demo.catchorg.catch2-*"_dep;
if (s.Settings.Native.CompilerType == CompilerType::MSVC)
t.CompileOptions.push_back("-bigobj");
//else if (s.Settings.Native.CompilerType == CompilerType::GNU)
//t.CompileOptions.push_back("-Wa,-mbig-obj");
return t;
};
auto &test_main = add_test("main");
test_main += sw_main, command, date_time,
executor, hash, yaml, context, http,
"org.sw.demo.nlohmann.json-*"_dep;
auto &test_db = add_test("db");
test_db += sw_main, command, db_sqlite3, db_postgresql, date_time,
executor, hash, yaml;
auto &test_settings = add_test("settings");
test_settings.PackageDefinitions = true;
test_settings += sw_main, settings;
auto &test_version = add_test("version");
test_version += sw_main, version;
s.addTest(test_main);
s.addTest(test_db);
s.addTest(test_settings);
s.addTest(test_version);*/
}
|
Comment out tests.
|
Comment out tests.
|
C++
|
mpl-2.0
|
egorpugin/primitives,egorpugin/primitives
|
c570772bce8dff8c997077ea375f31ebce6c73f8
|
sw.cpp
|
sw.cpp
|
void build(Solution &s)
{
auto &tess = s.addProject("google.tesseract", "master");
tess += Git("https://github.com/tesseract-ocr/tesseract", "", "{v}");
auto &libtesseract = tess.addTarget<LibraryTarget>("libtesseract");
{
libtesseract.setChecks("libtesseract");
libtesseract.ExportAllSymbols = true;
libtesseract.PackageDefinitions = true;
libtesseract +=
"src/api/.*\\.cpp"_rr,
"src/api/.*\\.h"_rr,
"src/api/tess_version.h.in",
"src/arch/.*\\.cpp"_rr,
"src/arch/.*\\.h"_rr,
"src/ccmain/.*\\.cpp"_rr,
"src/ccmain/.*\\.h"_rr,
"src/ccstruct/.*\\.cpp"_rr,
"src/ccstruct/.*\\.h"_rr,
"src/ccutil/.*\\.cpp"_rr,
"src/ccutil/.*\\.h"_rr,
"src/classify/.*\\.cpp"_rr,
"src/classify/.*\\.h"_rr,
"src/cutil/.*\\.cpp"_rr,
"src/cutil/.*\\.h"_rr,
"src/dict/.*\\.cpp"_rr,
"src/dict/.*\\.h"_rr,
"src/lstm/.*\\.cpp"_rr,
"src/lstm/.*\\.h"_rr,
"src/opencl/.*\\.cpp"_rr,
"src/opencl/.*\\.h"_rr,
"src/textord/.*\\.cpp"_rr,
"src/textord/.*\\.h"_rr,
"src/viewer/.*\\.cpp"_rr,
"src/viewer/.*\\.h"_rr,
"src/wordrec/.*\\.cpp"_rr,
"src/wordrec/.*\\.h"_rr;
libtesseract -=
"src/api/tesseractmain.cpp",
"src/viewer/svpaint.cpp";
libtesseract.Public +=
"src/vs2010/port"_id,
"src/opencl"_id,
"src/ccmain"_id,
"src/api"_id,
"src/dict"_id,
"src/viewer"_id,
"src/wordrec"_id,
"src/ccstruct"_id,
"src/cutil"_id,
"src/textord"_id,
"src/ccutil"_id,
"src/lstm"_id,
"src/classify"_id,
"src/arch"_id;
if (libtesseract.getCompilerType() == CompilerType::MSVC ||
libtesseract.getCompilerType() == CompilerType::ClangCl)
{
libtesseract += "__SSE4_1__"_def;
libtesseract.CompileOptions.push_back("-arch:AVX2");
}
libtesseract.Public += "HAVE_CONFIG_H"_d;
libtesseract.Public += "_SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS=1"_d;
libtesseract.Public += "HAVE_LIBARCHIVE"_d;
libtesseract.Interface += sw::Shared, "TESS_IMPORTS"_d;
libtesseract.Private += sw::Shared, "TESS_EXPORTS"_d;
libtesseract.Public += "org.sw.demo.danbloomberg.leptonica-master"_dep;
libtesseract.Public += "org.sw.demo.libarchive.libarchive"_dep;
if (libtesseract.getSettings().TargetOS.Type == OSType::Windows)
{
libtesseract.Public += "ws2_32.lib"_l;
libtesseract.Protected += "NOMINMAX"_def;
}
libtesseract.Variables["TESSERACT_MAJOR_VERSION"] = libtesseract.Variables["PACKAGE_MAJOR_VERSION"];
libtesseract.Variables["TESSERACT_MINOR_VERSION"] = libtesseract.Variables["PACKAGE_MINOR_VERSION"];
libtesseract.Variables["TESSERACT_MICRO_VERSION"] = libtesseract.Variables["PACKAGE_PATCH_VERSION"];
libtesseract.Variables["TESSERACT_VERSION_STR"] = "master";
libtesseract.configureFile("src/api/tess_version.h.in", "tess_version.h");
}
//
auto &tesseract = tess.addExecutable("tesseract");
tesseract += "src/api/tesseractmain.cpp";
tesseract += libtesseract;
//
auto &tessopt = tess.addStaticLibrary("tessopt");
tessopt += "src/training/tessopt.*"_rr;
tessopt.Public += "training"_id;
tessopt.Public += libtesseract;
//
auto &common_training = tess.addStaticLibrary("common_training");
common_training +=
"src/training/commandlineflags.cpp",
"src/training/commandlineflags.h",
"src/training/commontraining.cpp",
"src/training/commontraining.h";
common_training.Public += "training"_id;
common_training.Public += tessopt;
//
auto &unicharset_training = tess.addStaticLibrary("unicharset_training");
unicharset_training +=
"src/training/icuerrorcode.*"_rr,
"src/training/icuerrorcode.h",
"src/training/lang_model_helpers.*"_rr,
"src/training/lstmtester.*"_rr,
"src/training/normstrngs.*"_rr,
"src/training/unicharset_training_utils.*"_rr,
"src/training/validat.*"_rr;
unicharset_training.Public += "training"_id;
unicharset_training.Public += common_training;
unicharset_training.Public += "org.sw.demo.unicode.icu.i18n"_dep;
//
#define ADD_EXE(n, ...) \
auto &n = tess.addExecutable(#n); \
n += "src/training/" #n ".*"_rr; \
n.Public += __VA_ARGS__; \
n
ADD_EXE(ambiguous_words, libtesseract);
ADD_EXE(classifier_tester, common_training);
ADD_EXE(combine_lang_model, unicharset_training);
ADD_EXE(combine_tessdata, libtesseract);
ADD_EXE(cntraining, common_training);
ADD_EXE(dawg2wordlist, libtesseract);
ADD_EXE(mftraining, common_training) += "src/training/mergenf.*"_rr;
ADD_EXE(shapeclustering, common_training);
ADD_EXE(unicharset_extractor, unicharset_training);
ADD_EXE(wordlist2dawg, libtesseract);
ADD_EXE(lstmeval, unicharset_training);
ADD_EXE(lstmtraining, unicharset_training);
ADD_EXE(set_unicharset_properties, unicharset_training);
ADD_EXE(text2image, unicharset_training);
text2image +=
"src/training/boxchar.cpp",
"src/training/boxchar.h",
"src/training/degradeimage.cpp",
"src/training/degradeimage.h",
"src/training/icuerrorcode.h",
"src/training/ligature_table.cpp",
"src/training/ligature_table.h",
"src/training/normstrngs.cpp",
"src/training/normstrngs.h",
"src/training/pango_font_info.cpp",
"src/training/pango_font_info.h",
"src/training/stringrenderer.cpp",
"src/training/stringrenderer.h",
"src/training/text2image.cpp",
"src/training/tlog.cpp",
"src/training/tlog.h",
"src/training/util.h";
text2image.Public += "org.sw.demo.gnome.pango.pangocairo-1"_dep;
}
void check(Checker &c)
{
auto &s = c.addSet("libtesseract");
s.checkFunctionExists("getline");
s.checkIncludeExists("dlfcn.h");
s.checkIncludeExists("inttypes.h");
s.checkIncludeExists("limits.h");
s.checkIncludeExists("malloc.h");
s.checkIncludeExists("memory.h");
s.checkIncludeExists("stdbool.h");
s.checkIncludeExists("stdint.h");
s.checkIncludeExists("stdlib.h");
s.checkIncludeExists("string.h");
s.checkIncludeExists("sys/ipc.h");
s.checkIncludeExists("sys/shm.h");
s.checkIncludeExists("sys/stat.h");
s.checkIncludeExists("sys/types.h");
s.checkIncludeExists("sys/wait.h");
s.checkIncludeExists("tiffio.h");
s.checkIncludeExists("unistd.h");
s.checkTypeSize("long long int");
s.checkTypeSize("mbstate_t");
s.checkTypeSize("off_t");
s.checkTypeSize("size_t");
s.checkTypeSize("void *");
s.checkTypeSize("wchar_t");
s.checkTypeSize("_Bool");
{
auto &c = s.checkSymbolExists("snprintf");
c.Parameters.Includes.push_back("stdio.h");
}
}
|
void build(Solution &s)
{
auto &tess = s.addProject("google.tesseract", "master");
tess += Git("https://github.com/tesseract-ocr/tesseract", "", "{v}");
auto &libtesseract = tess.addTarget<LibraryTarget>("libtesseract");
{
libtesseract.setChecks("libtesseract");
libtesseract.ExportAllSymbols = true;
libtesseract.PackageDefinitions = true;
libtesseract +=
"src/api/.*\\.cpp"_rr,
"src/api/.*\\.h"_rr,
"src/api/tess_version.h.in",
"src/arch/.*\\.cpp"_rr,
"src/arch/.*\\.h"_rr,
"src/ccmain/.*\\.cpp"_rr,
"src/ccmain/.*\\.h"_rr,
"src/ccstruct/.*\\.cpp"_rr,
"src/ccstruct/.*\\.h"_rr,
"src/ccutil/.*\\.cpp"_rr,
"src/ccutil/.*\\.h"_rr,
"src/classify/.*\\.cpp"_rr,
"src/classify/.*\\.h"_rr,
"src/cutil/.*\\.cpp"_rr,
"src/cutil/.*\\.h"_rr,
"src/dict/.*\\.cpp"_rr,
"src/dict/.*\\.h"_rr,
"src/lstm/.*\\.cpp"_rr,
"src/lstm/.*\\.h"_rr,
"src/opencl/.*\\.cpp"_rr,
"src/opencl/.*\\.h"_rr,
"src/textord/.*\\.cpp"_rr,
"src/textord/.*\\.h"_rr,
"src/viewer/.*\\.cpp"_rr,
"src/viewer/.*\\.h"_rr,
"src/wordrec/.*\\.cpp"_rr,
"src/wordrec/.*\\.h"_rr;
libtesseract -=
"src/api/tesseractmain.cpp",
"src/viewer/svpaint.cpp";
libtesseract.Public +=
"src/opencl"_id,
"src/ccmain"_id,
"src/api"_id,
"src/dict"_id,
"src/viewer"_id,
"src/wordrec"_id,
"src/ccstruct"_id,
"src/cutil"_id,
"src/textord"_id,
"src/ccutil"_id,
"src/lstm"_id,
"src/classify"_id,
"src/arch"_id;
if (libtesseract.getCompilerType() == CompilerType::MSVC ||
libtesseract.getCompilerType() == CompilerType::ClangCl)
{
libtesseract += "__SSE4_1__"_def;
libtesseract.CompileOptions.push_back("-arch:AVX2");
}
libtesseract.Public += "HAVE_CONFIG_H"_d;
libtesseract.Public += "_SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS=1"_d;
libtesseract.Public += "HAVE_LIBARCHIVE"_d;
libtesseract.Interface += sw::Shared, "TESS_IMPORTS"_d;
libtesseract.Private += sw::Shared, "TESS_EXPORTS"_d;
libtesseract.Public += "org.sw.demo.danbloomberg.leptonica-master"_dep;
libtesseract.Public += "org.sw.demo.libarchive.libarchive"_dep;
if (libtesseract.getSettings().TargetOS.Type == OSType::Windows)
{
libtesseract.Public += "ws2_32.lib"_l;
libtesseract.Protected += "NOMINMAX"_def;
}
libtesseract.Variables["TESSERACT_MAJOR_VERSION"] = libtesseract.Variables["PACKAGE_MAJOR_VERSION"];
libtesseract.Variables["TESSERACT_MINOR_VERSION"] = libtesseract.Variables["PACKAGE_MINOR_VERSION"];
libtesseract.Variables["TESSERACT_MICRO_VERSION"] = libtesseract.Variables["PACKAGE_PATCH_VERSION"];
libtesseract.Variables["TESSERACT_VERSION_STR"] = "master";
libtesseract.configureFile("src/api/tess_version.h.in", "tess_version.h");
}
//
auto &tesseract = tess.addExecutable("tesseract");
tesseract += "src/api/tesseractmain.cpp";
tesseract += libtesseract;
//
auto &tessopt = tess.addStaticLibrary("tessopt");
tessopt += "src/training/tessopt.*"_rr;
tessopt.Public += "training"_id;
tessopt.Public += libtesseract;
//
auto &common_training = tess.addStaticLibrary("common_training");
common_training +=
"src/training/commandlineflags.cpp",
"src/training/commandlineflags.h",
"src/training/commontraining.cpp",
"src/training/commontraining.h";
common_training.Public += "training"_id;
common_training.Public += tessopt;
//
auto &unicharset_training = tess.addStaticLibrary("unicharset_training");
unicharset_training +=
"src/training/icuerrorcode.*"_rr,
"src/training/icuerrorcode.h",
"src/training/lang_model_helpers.*"_rr,
"src/training/lstmtester.*"_rr,
"src/training/normstrngs.*"_rr,
"src/training/unicharset_training_utils.*"_rr,
"src/training/validat.*"_rr;
unicharset_training.Public += "training"_id;
unicharset_training.Public += common_training;
unicharset_training.Public += "org.sw.demo.unicode.icu.i18n"_dep;
//
#define ADD_EXE(n, ...) \
auto &n = tess.addExecutable(#n); \
n += "src/training/" #n ".*"_rr; \
n.Public += __VA_ARGS__; \
n
ADD_EXE(ambiguous_words, libtesseract);
ADD_EXE(classifier_tester, common_training);
ADD_EXE(combine_lang_model, unicharset_training);
ADD_EXE(combine_tessdata, libtesseract);
ADD_EXE(cntraining, common_training);
ADD_EXE(dawg2wordlist, libtesseract);
ADD_EXE(mftraining, common_training) += "src/training/mergenf.*"_rr;
ADD_EXE(shapeclustering, common_training);
ADD_EXE(unicharset_extractor, unicharset_training);
ADD_EXE(wordlist2dawg, libtesseract);
ADD_EXE(lstmeval, unicharset_training);
ADD_EXE(lstmtraining, unicharset_training);
ADD_EXE(set_unicharset_properties, unicharset_training);
ADD_EXE(text2image, unicharset_training);
text2image +=
"src/training/boxchar.cpp",
"src/training/boxchar.h",
"src/training/degradeimage.cpp",
"src/training/degradeimage.h",
"src/training/icuerrorcode.h",
"src/training/ligature_table.cpp",
"src/training/ligature_table.h",
"src/training/normstrngs.cpp",
"src/training/normstrngs.h",
"src/training/pango_font_info.cpp",
"src/training/pango_font_info.h",
"src/training/stringrenderer.cpp",
"src/training/stringrenderer.h",
"src/training/text2image.cpp",
"src/training/tlog.cpp",
"src/training/tlog.h",
"src/training/util.h";
text2image.Public += "org.sw.demo.gnome.pango.pangocairo-1"_dep;
}
void check(Checker &c)
{
auto &s = c.addSet("libtesseract");
s.checkFunctionExists("getline");
s.checkIncludeExists("dlfcn.h");
s.checkIncludeExists("inttypes.h");
s.checkIncludeExists("limits.h");
s.checkIncludeExists("malloc.h");
s.checkIncludeExists("memory.h");
s.checkIncludeExists("stdbool.h");
s.checkIncludeExists("stdint.h");
s.checkIncludeExists("stdlib.h");
s.checkIncludeExists("string.h");
s.checkIncludeExists("sys/ipc.h");
s.checkIncludeExists("sys/shm.h");
s.checkIncludeExists("sys/stat.h");
s.checkIncludeExists("sys/types.h");
s.checkIncludeExists("sys/wait.h");
s.checkIncludeExists("tiffio.h");
s.checkIncludeExists("unistd.h");
s.checkTypeSize("long long int");
s.checkTypeSize("mbstate_t");
s.checkTypeSize("off_t");
s.checkTypeSize("size_t");
s.checkTypeSize("void *");
s.checkTypeSize("wchar_t");
s.checkTypeSize("_Bool");
{
auto &c = s.checkSymbolExists("snprintf");
c.Parameters.Includes.push_back("stdio.h");
}
}
|
Exclude missing include dir.
|
[sw] Exclude missing include dir.
|
C++
|
apache-2.0
|
tesseract-ocr/tesseract,UB-Mannheim/tesseract,stweil/tesseract,UB-Mannheim/tesseract,UB-Mannheim/tesseract,amitdo/tesseract,tesseract-ocr/tesseract,stweil/tesseract,amitdo/tesseract,UB-Mannheim/tesseract,tesseract-ocr/tesseract,stweil/tesseract,tesseract-ocr/tesseract,amitdo/tesseract,stweil/tesseract,stweil/tesseract,amitdo/tesseract,UB-Mannheim/tesseract,amitdo/tesseract,tesseract-ocr/tesseract
|
b9b10751dcb34e755a2088931206d51c235cdb99
|
o3d/plugin/cross/main.cc
|
o3d/plugin/cross/main.cc
|
/*
* Copyright 2009, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "plugin/cross/main.h"
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "plugin/cross/config.h"
#include "plugin/cross/out_of_memory.h"
#include "plugin/cross/whitelist.h"
#ifdef OS_WIN
#include "breakpad/win/bluescreen_detector.h"
#endif
using glue::_o3d::PluginObject;
using glue::StreamManager;
#if !defined(O3D_INTERNAL_PLUGIN)
#ifdef OS_WIN
#define O3D_DEBUG_LOG_FILENAME L"debug.log"
#else
#define O3D_DEBUG_LOG_FILENAME "debug.log"
#endif
#if defined(OS_WIN) || defined(OS_MACOSX)
o3d::PluginLogging *g_logger = NULL;
static bool g_logging_initialized = false;
#ifdef OS_WIN
static o3d::BluescreenDetector *g_bluescreen_detector = NULL;
#endif // OS_WIN
#endif // OS_WIN || OS_MACOSX
// We would normally make this a stack variable in main(), but in a
// plugin, that's not possible, so we make it a global. When the DLL is loaded
// this it gets constructed and when it is unlooaded it is destructed. Note
// that this cannot be done in NP_Initialize and NP_Shutdown because those
// calls do not necessarily signify the DLL being loaded and unloaded. If the
// DLL is not unloaded then the values of global variables are preserved.
static base::AtExitManager g_at_exit_manager;
int BreakpadEnabler::scope_count_ = 0;
#endif // O3D_INTERNAL_PLUGIN
namespace o3d {
NPError NP_GetValue(NPPVariable variable, void *value) {
switch (variable) {
case NPPVpluginNameString:
*static_cast<char **>(value) = const_cast<char*>(O3D_PLUGIN_NAME);
break;
case NPPVpluginDescriptionString:
*static_cast<char **>(value) = const_cast<char*>(O3D_PLUGIN_DESCRIPTION);
break;
default:
return NPERR_INVALID_PARAM;
break;
}
return NPERR_NO_ERROR;
}
int16 NPP_HandleEvent(NPP instance, void *event) {
HANDLE_CRASHES;
PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
if (!obj) {
return 0;
}
return PlatformNPPHandleEvent(instance, obj, event);
}
NPError NPP_NewStream(NPP instance,
NPMIMEType type,
NPStream *stream,
NPBool seekable,
uint16 *stype) {
HANDLE_CRASHES;
PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
if (!obj) {
return NPERR_INVALID_PARAM;
}
StreamManager *stream_manager = obj->stream_manager();
if (stream_manager->NewStream(stream, stype)) {
return NPERR_NO_ERROR;
} else {
// TODO: find out which error we should return
return NPERR_INVALID_PARAM;
}
}
NPError NPP_DestroyStream(NPP instance, NPStream *stream, NPReason reason) {
HANDLE_CRASHES;
PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
if (!obj) {
return NPERR_NO_ERROR;
}
StreamManager *stream_manager = obj->stream_manager();
if (stream_manager->DestroyStream(stream, reason)) {
return NPERR_NO_ERROR;
} else {
// TODO: find out which error we should return
return NPERR_INVALID_PARAM;
}
}
int32 NPP_WriteReady(NPP instance, NPStream *stream) {
HANDLE_CRASHES;
PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
if (!obj) {
return 0;
}
StreamManager *stream_manager = obj->stream_manager();
return stream_manager->WriteReady(stream);
}
int32 NPP_Write(NPP instance, NPStream *stream, int32 offset, int32 len,
void *buffer) {
HANDLE_CRASHES;
PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
if (!obj) {
return 0;
}
StreamManager *stream_manager = obj->stream_manager();
return stream_manager->Write(stream, offset, len, buffer);
}
void NPP_Print(NPP instance, NPPrint *platformPrint) {
HANDLE_CRASHES;
}
void NPP_URLNotify(NPP instance, const char *url, NPReason reason,
void *notifyData) {
HANDLE_CRASHES;
PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
if (!obj) {
return;
}
StreamManager *stream_manager = obj->stream_manager();
stream_manager->URLNotify(url, reason, notifyData);
}
NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) {
HANDLE_CRASHES;
PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
if (!obj) {
return NPERR_INVALID_PARAM;
}
switch (variable) {
case NPPVpluginScriptableNPObject: {
void **v = static_cast<void **>(value);
// Return value is expected to be retained
GLUE_PROFILE_START(instance, "retainobject");
NPN_RetainObject(obj);
GLUE_PROFILE_STOP(instance, "retainobject");
*v = obj;
break;
}
default: {
NPError ret = PlatformNPPGetValue(obj, variable, value);
if (ret == NPERR_INVALID_PARAM)
ret = o3d::NP_GetValue(variable, value);
return ret;
}
}
return NPERR_NO_ERROR;
}
NPError NPP_New(NPMIMEType pluginType,
NPP instance,
uint16 mode,
int16 argc,
char *argn[],
char *argv[],
NPSavedData *saved) {
HANDLE_CRASHES;
#if !defined(O3D_INTERNAL_PLUGIN) && (defined(OS_WIN) || defined(OS_MACOSX))
// TODO(tschmelcher): Support this on Linux?
if (!g_logging_initialized) {
// Get user config metrics. These won't be stored though unless the user
// opts-in for usagestats logging
GetUserAgentMetrics(instance);
GetUserConfigMetrics();
// Create usage stats logs object
g_logger = o3d::PluginLogging::InitializeUsageStatsLogging();
#ifdef OS_WIN
if (g_logger) {
// Setup blue-screen detection
g_bluescreen_detector = new o3d::BluescreenDetector();
g_bluescreen_detector->Start();
}
#endif
g_logging_initialized = true;
}
#endif
if (!IsDomainAuthorized(instance)) {
return NPERR_INVALID_URL;
}
PluginObject *obj = glue::_o3d::PluginObject::Create(instance);
instance->pdata = obj;
glue::_o3d::InitializeGlue(instance);
obj->Init(argc, argn, argv);
return PlatformNPPNew(instance, obj);
}
NPError NPP_Destroy(NPP instance, NPSavedData **save) {
HANDLE_CRASHES;
PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
if (!obj) {
return NPERR_NO_ERROR;
}
NPError err = PlatformNPPDestroy(instance, obj);
NPN_ReleaseObject(obj);
instance->pdata = NULL;
return err;
}
NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value) {
HANDLE_CRASHES;
return NPERR_GENERIC_ERROR;
}
NPError NPP_SetWindow(NPP instance, NPWindow* window) {
HANDLE_CRASHES;
PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
if (!obj) {
return NPERR_NO_ERROR;
}
return PlatformNPPSetWindow(instance, obj, window);
}
// Called when the browser has finished attempting to stream data to
// a file as requested. If fname == NULL the attempt was not successful.
void NPP_StreamAsFile(NPP instance, NPStream *stream, const char *fname) {
HANDLE_CRASHES;
PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
if (!obj) {
return;
}
StreamManager *stream_manager = obj->stream_manager();
PlatformNPPStreamAsFile(stream_manager, stream, fname);
}
} // namespace o3d
#if defined(O3D_INTERNAL_PLUGIN)
namespace o3d {
#else
extern "C" {
#endif
NPError EXPORT_SYMBOL OSCALL NP_Initialize(NPNetscapeFuncs *browserFuncs
#ifdef OS_LINUX
,
NPPluginFuncs *pluginFuncs
#endif
) {
HANDLE_CRASHES;
NPError err = InitializeNPNApi(browserFuncs);
if (err != NPERR_NO_ERROR) {
return err;
}
#ifdef OS_LINUX
NP_GetEntryPoints(pluginFuncs);
#endif // OS_LINUX
#if !defined(O3D_INTERNAL_PLUGIN)
if (!o3d::SetupOutOfMemoryHandler())
return NPERR_MODULE_LOAD_FAILED_ERROR;
#endif // O3D_INTERNAL_PLUGIN
err = o3d::PlatformPreNPInitialize();
if (err != NPERR_NO_ERROR) {
return err;
}
#if !defined(O3D_INTERNAL_PLUGIN)
// Turn on the logging.
CommandLine::Init(0, NULL);
FilePath log;
file_util::GetTempDir(&log);
log.Append(O3D_DEBUG_LOG_FILENAME);
InitLogging(log.value().c_str(),
logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG,
logging::DONT_LOCK_LOG_FILE,
logging::APPEND_TO_OLD_LOG_FILE);
#endif // O3D_INTERNAL_PLUGIN
DLOG(INFO) << "NP_Initialize";
return o3d::PlatformPostNPInitialize();
}
NPError EXPORT_SYMBOL OSCALL NP_Shutdown(void) {
HANDLE_CRASHES;
DLOG(INFO) << "NP_Shutdown";
NPError err = o3d::PlatformPreNPShutdown();
if (err != NPERR_NO_ERROR) {
return err;
}
#if !defined(O3D_INTERNAL_PLUGIN)
#if defined(OS_WIN) || defined(OS_MACOSX)
if (g_logger) {
// Do a last sweep to aggregate metrics before we shut down
g_logger->ProcessMetrics(true, false, false);
delete g_logger;
g_logger = NULL;
g_logging_initialized = false;
stats_report::g_global_metrics.Uninitialize();
}
#endif // OS_WIN || OS_MACOSX
CommandLine::Reset();
#ifdef OS_WIN
// Strictly speaking, on windows, it's not really necessary to call
// Stop(), but we do so for completeness
if (g_bluescreen_detector) {
g_bluescreen_detector->Stop();
delete g_bluescreen_detector;
g_bluescreen_detector = NULL;
}
#endif // OS_WIN
#endif // O3D_INTERNAL_PLUGIN
return o3d::PlatformPostNPShutdown();
}
NPError EXPORT_SYMBOL OSCALL NP_GetEntryPoints(NPPluginFuncs *pluginFuncs) {
HANDLE_CRASHES;
pluginFuncs->version = 11;
pluginFuncs->size = sizeof(*pluginFuncs);
pluginFuncs->newp = o3d::NPP_New;
pluginFuncs->destroy = o3d::NPP_Destroy;
pluginFuncs->setwindow = o3d::NPP_SetWindow;
pluginFuncs->newstream = o3d::NPP_NewStream;
pluginFuncs->destroystream = o3d::NPP_DestroyStream;
pluginFuncs->asfile = o3d::NPP_StreamAsFile;
pluginFuncs->writeready = o3d::NPP_WriteReady;
pluginFuncs->write = o3d::NPP_Write;
pluginFuncs->print = o3d::NPP_Print;
pluginFuncs->event = o3d::NPP_HandleEvent;
pluginFuncs->urlnotify = o3d::NPP_URLNotify;
pluginFuncs->getvalue = o3d::NPP_GetValue;
pluginFuncs->setvalue = o3d::NPP_SetValue;
return NPERR_NO_ERROR;
}
char* NP_GetMIMEDescription(void) {
return const_cast<char*>(O3D_PLUGIN_NPAPI_MIMETYPE "::O3D MIME");
}
} // namespace o3d / extern "C"
#if !defined(O3D_INTERNAL_PLUGIN)
extern "C" {
NPError EXPORT_SYMBOL NP_GetValue(void *instance, NPPVariable variable,
void *value) {
return o3d::NP_GetValue(variable, value);
}
}
#endif
|
/*
* Copyright 2009, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "plugin/cross/main.h"
#include "base/at_exit.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "plugin/cross/config.h"
#include "plugin/cross/out_of_memory.h"
#include "plugin/cross/whitelist.h"
#ifdef OS_WIN
#include "breakpad/win/bluescreen_detector.h"
#endif
using glue::_o3d::PluginObject;
using glue::StreamManager;
#if !defined(O3D_INTERNAL_PLUGIN)
#ifdef OS_WIN
#define O3D_DEBUG_LOG_FILENAME L"debug.log"
#else
#define O3D_DEBUG_LOG_FILENAME "debug.log"
#endif
#if defined(OS_WIN) || defined(OS_MACOSX)
o3d::PluginLogging *g_logger = NULL;
static bool g_logging_initialized = false;
#ifdef OS_WIN
static o3d::BluescreenDetector *g_bluescreen_detector = NULL;
#endif // OS_WIN
#endif // OS_WIN || OS_MACOSX
// We would normally make this a stack variable in main(), but in a
// plugin, that's not possible, so we make it a global. When the DLL is loaded
// this it gets constructed and when it is unlooaded it is destructed. Note
// that this cannot be done in NP_Initialize and NP_Shutdown because those
// calls do not necessarily signify the DLL being loaded and unloaded. If the
// DLL is not unloaded then the values of global variables are preserved.
static base::AtExitManager g_at_exit_manager;
int BreakpadEnabler::scope_count_ = 0;
#endif // O3D_INTERNAL_PLUGIN
namespace o3d {
NPError NP_GetValue(NPPVariable variable, void *value) {
switch (variable) {
case NPPVpluginNameString:
*static_cast<char **>(value) = const_cast<char*>(O3D_PLUGIN_NAME);
break;
case NPPVpluginDescriptionString:
*static_cast<char **>(value) = const_cast<char*>(O3D_PLUGIN_DESCRIPTION);
break;
default:
return NPERR_INVALID_PARAM;
break;
}
return NPERR_NO_ERROR;
}
int16 NPP_HandleEvent(NPP instance, void *event) {
HANDLE_CRASHES;
PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
if (!obj) {
return 0;
}
return PlatformNPPHandleEvent(instance, obj, event);
}
NPError NPP_NewStream(NPP instance,
NPMIMEType type,
NPStream *stream,
NPBool seekable,
uint16 *stype) {
HANDLE_CRASHES;
PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
if (!obj) {
return NPERR_INVALID_PARAM;
}
StreamManager *stream_manager = obj->stream_manager();
if (stream_manager->NewStream(stream, stype)) {
return NPERR_NO_ERROR;
} else {
// TODO: find out which error we should return
return NPERR_INVALID_PARAM;
}
}
NPError NPP_DestroyStream(NPP instance, NPStream *stream, NPReason reason) {
HANDLE_CRASHES;
PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
if (!obj) {
return NPERR_NO_ERROR;
}
StreamManager *stream_manager = obj->stream_manager();
if (stream_manager->DestroyStream(stream, reason)) {
return NPERR_NO_ERROR;
} else {
// TODO: find out which error we should return
return NPERR_INVALID_PARAM;
}
}
int32 NPP_WriteReady(NPP instance, NPStream *stream) {
HANDLE_CRASHES;
PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
if (!obj) {
return 0;
}
StreamManager *stream_manager = obj->stream_manager();
return stream_manager->WriteReady(stream);
}
int32 NPP_Write(NPP instance, NPStream *stream, int32 offset, int32 len,
void *buffer) {
HANDLE_CRASHES;
PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
if (!obj) {
return 0;
}
StreamManager *stream_manager = obj->stream_manager();
return stream_manager->Write(stream, offset, len, buffer);
}
void NPP_Print(NPP instance, NPPrint *platformPrint) {
HANDLE_CRASHES;
}
void NPP_URLNotify(NPP instance, const char *url, NPReason reason,
void *notifyData) {
HANDLE_CRASHES;
PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
if (!obj) {
return;
}
StreamManager *stream_manager = obj->stream_manager();
stream_manager->URLNotify(url, reason, notifyData);
}
NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) {
HANDLE_CRASHES;
if (!instance) {
// Our ActiveX wrapper calls us like this as a way of saying that what it
// really wants to call is NP_GetValue(). :/
return o3d::NP_GetValue(variable, value);
}
PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
if (!obj) {
return NPERR_INVALID_PARAM;
}
switch (variable) {
case NPPVpluginScriptableNPObject: {
void **v = static_cast<void **>(value);
// Return value is expected to be retained
GLUE_PROFILE_START(instance, "retainobject");
NPN_RetainObject(obj);
GLUE_PROFILE_STOP(instance, "retainobject");
*v = obj;
break;
}
default: {
NPError ret = PlatformNPPGetValue(obj, variable, value);
if (ret == NPERR_INVALID_PARAM)
// TODO(tschmelcher): Do we still need to fall back to this now that we
// have the ActiveX special case above?
ret = o3d::NP_GetValue(variable, value);
return ret;
}
}
return NPERR_NO_ERROR;
}
NPError NPP_New(NPMIMEType pluginType,
NPP instance,
uint16 mode,
int16 argc,
char *argn[],
char *argv[],
NPSavedData *saved) {
HANDLE_CRASHES;
#if !defined(O3D_INTERNAL_PLUGIN) && (defined(OS_WIN) || defined(OS_MACOSX))
// TODO(tschmelcher): Support this on Linux?
if (!g_logging_initialized) {
// Get user config metrics. These won't be stored though unless the user
// opts-in for usagestats logging
GetUserAgentMetrics(instance);
GetUserConfigMetrics();
// Create usage stats logs object
g_logger = o3d::PluginLogging::InitializeUsageStatsLogging();
#ifdef OS_WIN
if (g_logger) {
// Setup blue-screen detection
g_bluescreen_detector = new o3d::BluescreenDetector();
g_bluescreen_detector->Start();
}
#endif
g_logging_initialized = true;
}
#endif
if (!IsDomainAuthorized(instance)) {
return NPERR_INVALID_URL;
}
PluginObject *obj = glue::_o3d::PluginObject::Create(instance);
instance->pdata = obj;
glue::_o3d::InitializeGlue(instance);
obj->Init(argc, argn, argv);
return PlatformNPPNew(instance, obj);
}
NPError NPP_Destroy(NPP instance, NPSavedData **save) {
HANDLE_CRASHES;
PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
if (!obj) {
return NPERR_NO_ERROR;
}
NPError err = PlatformNPPDestroy(instance, obj);
NPN_ReleaseObject(obj);
instance->pdata = NULL;
return err;
}
NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value) {
HANDLE_CRASHES;
return NPERR_GENERIC_ERROR;
}
NPError NPP_SetWindow(NPP instance, NPWindow* window) {
HANDLE_CRASHES;
PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
if (!obj) {
return NPERR_NO_ERROR;
}
return PlatformNPPSetWindow(instance, obj, window);
}
// Called when the browser has finished attempting to stream data to
// a file as requested. If fname == NULL the attempt was not successful.
void NPP_StreamAsFile(NPP instance, NPStream *stream, const char *fname) {
HANDLE_CRASHES;
PluginObject *obj = static_cast<PluginObject *>(instance->pdata);
if (!obj) {
return;
}
StreamManager *stream_manager = obj->stream_manager();
PlatformNPPStreamAsFile(stream_manager, stream, fname);
}
} // namespace o3d
#if defined(O3D_INTERNAL_PLUGIN)
namespace o3d {
#else
extern "C" {
#endif
NPError EXPORT_SYMBOL OSCALL NP_Initialize(NPNetscapeFuncs *browserFuncs
#ifdef OS_LINUX
,
NPPluginFuncs *pluginFuncs
#endif
) {
HANDLE_CRASHES;
NPError err = InitializeNPNApi(browserFuncs);
if (err != NPERR_NO_ERROR) {
return err;
}
#ifdef OS_LINUX
NP_GetEntryPoints(pluginFuncs);
#endif // OS_LINUX
#if !defined(O3D_INTERNAL_PLUGIN)
if (!o3d::SetupOutOfMemoryHandler())
return NPERR_MODULE_LOAD_FAILED_ERROR;
#endif // O3D_INTERNAL_PLUGIN
err = o3d::PlatformPreNPInitialize();
if (err != NPERR_NO_ERROR) {
return err;
}
#if !defined(O3D_INTERNAL_PLUGIN)
// Turn on the logging.
CommandLine::Init(0, NULL);
FilePath log;
file_util::GetTempDir(&log);
log.Append(O3D_DEBUG_LOG_FILENAME);
InitLogging(log.value().c_str(),
logging::LOG_TO_BOTH_FILE_AND_SYSTEM_DEBUG_LOG,
logging::DONT_LOCK_LOG_FILE,
logging::APPEND_TO_OLD_LOG_FILE);
#endif // O3D_INTERNAL_PLUGIN
DLOG(INFO) << "NP_Initialize";
return o3d::PlatformPostNPInitialize();
}
NPError EXPORT_SYMBOL OSCALL NP_Shutdown(void) {
HANDLE_CRASHES;
DLOG(INFO) << "NP_Shutdown";
NPError err = o3d::PlatformPreNPShutdown();
if (err != NPERR_NO_ERROR) {
return err;
}
#if !defined(O3D_INTERNAL_PLUGIN)
#if defined(OS_WIN) || defined(OS_MACOSX)
if (g_logger) {
// Do a last sweep to aggregate metrics before we shut down
g_logger->ProcessMetrics(true, false, false);
delete g_logger;
g_logger = NULL;
g_logging_initialized = false;
stats_report::g_global_metrics.Uninitialize();
}
#endif // OS_WIN || OS_MACOSX
CommandLine::Reset();
#ifdef OS_WIN
// Strictly speaking, on windows, it's not really necessary to call
// Stop(), but we do so for completeness
if (g_bluescreen_detector) {
g_bluescreen_detector->Stop();
delete g_bluescreen_detector;
g_bluescreen_detector = NULL;
}
#endif // OS_WIN
#endif // O3D_INTERNAL_PLUGIN
return o3d::PlatformPostNPShutdown();
}
NPError EXPORT_SYMBOL OSCALL NP_GetEntryPoints(NPPluginFuncs *pluginFuncs) {
HANDLE_CRASHES;
pluginFuncs->version = 11;
pluginFuncs->size = sizeof(*pluginFuncs);
pluginFuncs->newp = o3d::NPP_New;
pluginFuncs->destroy = o3d::NPP_Destroy;
pluginFuncs->setwindow = o3d::NPP_SetWindow;
pluginFuncs->newstream = o3d::NPP_NewStream;
pluginFuncs->destroystream = o3d::NPP_DestroyStream;
pluginFuncs->asfile = o3d::NPP_StreamAsFile;
pluginFuncs->writeready = o3d::NPP_WriteReady;
pluginFuncs->write = o3d::NPP_Write;
pluginFuncs->print = o3d::NPP_Print;
pluginFuncs->event = o3d::NPP_HandleEvent;
pluginFuncs->urlnotify = o3d::NPP_URLNotify;
pluginFuncs->getvalue = o3d::NPP_GetValue;
pluginFuncs->setvalue = o3d::NPP_SetValue;
return NPERR_NO_ERROR;
}
char* NP_GetMIMEDescription(void) {
return const_cast<char*>(O3D_PLUGIN_NPAPI_MIMETYPE "::O3D MIME");
}
} // namespace o3d / extern "C"
#if !defined(O3D_INTERNAL_PLUGIN)
extern "C" {
NPError EXPORT_SYMBOL NP_GetValue(void *instance, NPPVariable variable,
void *value) {
return o3d::NP_GetValue(variable, value);
}
}
#endif
|
Fix IE crash regression from r66344.
|
Fix IE crash regression from r66344.
TEST=pending: build and load in IE
BUG=none
Review URL: http://codereview.chromium.org/5325002
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@67296 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
yitian134/chromium,yitian134/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,adobe/chromium,yitian134/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,ropik/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,adobe/chromium,ropik/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,yitian134/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,adobe/chromium,ropik/chromium,gavinp/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,gavinp/chromium
|
3e60056c44dc7f7c7dd62302825720e10c9b942c
|
gui/src/TGFSComboBox.cxx
|
gui/src/TGFSComboBox.cxx
|
// @(#)root/gui:$Name: $:$Id: TGFSComboBox.cxx,v 1.3 2000/09/29 08:57:05 rdm Exp $
// Author: Fons Rademakers 19/01/98
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/**************************************************************************
This source is based on Xclass95, a Win95-looking GUI toolkit.
Copyright (C) 1996, 1997 David Barth, Ricky Ralston, Hector Peraza.
Xclass95 is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
**************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TGFSComboBox, TGTreeLBEntry //
// //
// This is a combo box that is used in the File Selection dialog box. //
// It will allow the file path selection. //
// //
//////////////////////////////////////////////////////////////////////////
#ifdef HAVE_CONFIG
#include "config.h"
#endif
#include "TGFSComboBox.h"
#include "TGPicture.h"
#include "TMath.h"
#include "TSystem.h"
//--- this is temp here...
struct lbc_t {
char *name;
char *path;
char *pixmap;
Int_t id, indent, flags;
};
static struct lbc_t gLbc[] = {
{ "Root", "/", "hdisk_t.xpm", 1000, 0, 0 },
{ "Floppy", "/floppy", "fdisk_t.xpm", 2000, 1, 0 },
{ "CD-ROM", "/cdrom", "cdrom_t.xpm", 3000, 1, 0 },
{ "Home", "$HOME", "home_t.xpm", 4000, 1, 0 },
#ifndef ROOTPREFIX
{ "RootSys", "$ROOTSYS", "root_t.xpm", 5000, 1, 0 },
#else
{ ROOTPREFIX, ROOTPREFIX, "root_t.xpm", 5000, 1, 0 },
#endif
{ 0, 0, 0, 6000, 0, 0 }
};
ClassImp(TGTreeLBEntry)
ClassImp(TGFSComboBox)
//______________________________________________________________________________
TGTreeLBEntry::TGTreeLBEntry(const TGWindow *p, TGString *text,
const TGPicture *pic, Int_t id, TGString *path,
GContext_t norm, FontStruct_t font, UInt_t options,
ULong_t back) :
TGLBEntry(p, id, options, back)
{
// Create a tree (i.e. entry can be indented) listbox entry.
// The strings text and path are adopted by the entry.
if (!pic)
Error("TGTreeLBEntry", "icon not found for entry %s", text->GetString());
fPic = pic;
fSelPic = 0;
fText = text;
fPath = path;
fNormGC = norm;
fFontStruct = font;
fActive = kFALSE;
int max_ascent, max_descent;
fTWidth = gVirtualX->TextWidth(fFontStruct, fText->GetString(), fText->GetLength());
gVirtualX->GetFontProperties(fFontStruct, max_ascent, max_descent);
fTHeight = max_ascent + max_descent;
}
//______________________________________________________________________________
TGTreeLBEntry::~TGTreeLBEntry()
{
// Delete tree listbox entry.
delete fText;
delete fPath;
}
//______________________________________________________________________________
void TGTreeLBEntry::Activate(Bool_t a)
{
// Make entry active (highlight picture).
if (fActive == a) return;
fActive = a;
if (fActive) {
fSelPic = new TGSelectedPicture(fClient, fPic);
} else {
if (fSelPic) delete fSelPic;
fSelPic = 0;
}
DoRedraw();
}
//______________________________________________________________________________
void TGTreeLBEntry::DoRedraw()
{
// Redraw the tree listbox entry.
int ix, iy, lx, ly;
ix = 0;
iy = (fHeight - fPic->GetHeight()) >> 1;
lx = (int)(fPic->GetWidth() + 4);
ly = (int)((fHeight - (fTHeight+1)) >> 1);
if (fActive) {
if (fSelPic) fSelPic->Draw(fId, fNormGC, ix, iy);
gVirtualX->SetForeground(fNormGC, fgDefaultSelectedBackground);
gVirtualX->FillRectangle(fId, fNormGC, lx, ly, fTWidth, fTHeight+1);
gVirtualX->SetForeground(fNormGC, fgSelPixel);
} else {
fPic->Draw(fId, fNormGC, ix, iy);
gVirtualX->SetForeground(fNormGC, fgWhitePixel);
gVirtualX->FillRectangle(fId, fNormGC, lx, ly, fTWidth, fTHeight+1);
gVirtualX->SetForeground(fNormGC, fgBlackPixel);
}
int max_ascent, max_descent;
gVirtualX->GetFontProperties(fFontStruct, max_ascent, max_descent);
fText->Draw(fId, fNormGC, lx, ly + max_ascent);
}
//______________________________________________________________________________
TGDimension TGTreeLBEntry::GetDefaultSize() const
{
// Return default size of tree listbox entry.
TGDimension isize(fPic->GetWidth(), fPic->GetHeight());
TGDimension lsize(fTWidth, fTHeight+1);
return TGDimension(isize.fWidth + lsize.fWidth + 4,
TMath::Max(isize.fHeight, lsize.fHeight) + 2);
}
//______________________________________________________________________________
void TGTreeLBEntry::Update(TGLBEntry *e)
{
// Update text and picture of a listbox entry.
TGTreeLBEntry *te = (TGTreeLBEntry *) e;
if (fText) delete fText;
fText = new TGString(te->GetText());
fPic = te->GetPicture();
fTWidth = gVirtualX->TextWidth(fFontStruct, fText->GetString(), fText->GetLength());
gVirtualX->ClearWindow(fId);
fClient->NeedRedraw(this);
}
//______________________________________________________________________________
FontStruct_t TGTreeLBEntry::GetDefaultFontStruct()
{ return fgDefaultFontStruct; }
//______________________________________________________________________________
const TGGC &TGTreeLBEntry::GetDefaultGC()
{ return fgDefaultGC; }
//______________________________________________________________________________
TGFSComboBox::TGFSComboBox(const TGWindow *parent, Int_t id, UInt_t options,
ULong_t back) :
TGComboBox(parent, id, options | kOwnBackground, back)
{
// Create a file system combobox showing system directories.
int i, indent;
const TGPicture *pic;
char *p;
SetTopEntry(new TGTreeLBEntry(this, new TGString("Current dir"),
fClient->GetPicture("folder_t.xpm"), 0),
new TGLayoutHints(kLHintsLeft | kLHintsExpandX |
kLHintsExpandY, 4, 0, 0, 0));
fListBox->GetContainer()->AddInput(kButtonPressMask | kButtonReleaseMask |
kPointerMotionMask);
//--- first check for the existence of some directories...
const char *homeDir = gSystem->Getenv("HOME");
#ifndef ROOTPREFIX
const char *rootSys = gSystem->Getenv("ROOTSYS");
#else
const char *rootSys = ROOTPREFIX;
#endif
for (i = 0; gLbc[i].path != 0; ++i) {
if (strstr(gLbc[i].path, "$HOME") != 0) {
if (homeDir) {
int hlen = strlen(homeDir);
p = new char[hlen + strlen(gLbc[i].path) - 3];
strcpy(p, homeDir);
strcat(p, &gLbc[i].path[5]);
gLbc[i].path = p;
} else {
gLbc[i].flags = 0;
}
}
#ifndef ROOTPREFIX
if (strstr(gLbc[i].path, "$ROOTSYS") != 0) {
#else
if (strstr(gLbc[i].path, ROOTPREFIX) != 0) {
#endif
if (rootSys) {
int hlen = strlen(rootSys);
p = new char[hlen + strlen(gLbc[i].path) - 3];
strcpy(p, rootSys);
strcat(p, &gLbc[i].path[8]);
gLbc[i].path = p;
} else {
gLbc[i].flags = 0;
}
}
if (gSystem->AccessPathName(gLbc[i].path, kFileExists) == 0)
gLbc[i].flags = 1;
}
//--- then init the contents...
for (i = 0; gLbc[i].name != 0; ++i) {
if (gLbc[i].flags) {
indent = 4 + (gLbc[i].indent * 10);
pic = fClient->GetPicture(gLbc[i].pixmap);
if (!pic) Error("TGFSComboBox", "pixmap not found: %s", gLbc[i].pixmap);
AddEntry(new TGTreeLBEntry(fListBox->GetContainer(),
new TGString(gLbc[i].name), pic, gLbc[i].id,
new TGString(gLbc[i].path)),
new TGLayoutHints(kLHintsLeft | kLHintsTop, indent, 0, 0, 0));
}
}
}
//______________________________________________________________________________
void TGFSComboBox::Update(const char *path)
{
// Update file system combo box.
char dirname[1024], mpath[1024];
const char *tailpath = 0;
int i, indent_lvl = 0, afterID = -1, sel = -1;
if (!path) return;
for (i = 0; gLbc[i].path != 0; ++i)
RemoveEntries(gLbc[i].id+1, gLbc[i+1].id-1);
int len = 0;
for (i = 0; gLbc[i].name != 0; ++i) {
if (gLbc[i].flags) {
int slen = strlen(gLbc[i].path);
if (strncmp(path, gLbc[i].path, slen) == 0) {
if (slen > len) {
sel = afterID = gLbc[i].id;
indent_lvl = gLbc[i].indent + 1;
tailpath = path + slen;
strcpy(mpath, gLbc[i].path);
len = slen;
}
}
}
}
if (tailpath && *tailpath) {
if (*tailpath == '/') ++tailpath;
if (*tailpath)
while (1) {
char *picname;
const char *semi = strchr(tailpath, '/');
if (semi == 0) {
strcpy(dirname, tailpath);
picname = "ofolder_t.xpm";
} else {
strncpy(dirname, tailpath, semi-tailpath);
dirname[semi-tailpath] = 0;
picname = "folder_t.xpm";
}
if (mpath[strlen(mpath)-1] != '/') strcat(mpath, "/");
strcat(mpath, dirname);
int indent = 4 + (indent_lvl * 10);
const TGPicture *pic = fClient->GetPicture(picname);
if (!pic) Error("Update", "pixmap not found: %s", picname);
InsertEntry(new TGTreeLBEntry(fListBox->GetContainer(),
new TGString(dirname), pic, afterID+1,
new TGString(mpath)),
new TGLayoutHints(kLHintsLeft | kLHintsTop,
indent, 0, 0, 0),
afterID);
sel = ++afterID;
++indent_lvl;
if (semi == 0) break;
tailpath = ++semi;
}
}
if (sel > 0) Select(sel);
}
|
// @(#)root/gui:$Name: $:$Id: TGFSComboBox.cxx,v 1.4 2000/10/04 23:40:07 rdm Exp $
// Author: Fons Rademakers 19/01/98
/*************************************************************************
* Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
/**************************************************************************
This source is based on Xclass95, a Win95-looking GUI toolkit.
Copyright (C) 1996, 1997 David Barth, Ricky Ralston, Hector Peraza.
Xclass95 is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
**************************************************************************/
//////////////////////////////////////////////////////////////////////////
// //
// TGFSComboBox, TGTreeLBEntry //
// //
// This is a combo box that is used in the File Selection dialog box. //
// It will allow the file path selection. //
// //
//////////////////////////////////////////////////////////////////////////
#ifdef HAVE_CONFIG
#include "config.h"
#endif
#include "TGFSComboBox.h"
#include "TGPicture.h"
#include "TMath.h"
#include "TSystem.h"
//--- this is temp here...
struct lbc_t {
char *name;
char *path;
char *pixmap;
Int_t id, indent, flags;
};
static struct lbc_t gLbc[] = {
{ "Root", "/", "hdisk_t.xpm", 1000, 0, 0 },
{ "Floppy", "/floppy", "fdisk_t.xpm", 2000, 1, 0 },
{ "CD-ROM", "/cdrom", "cdrom_t.xpm", 3000, 1, 0 },
{ "Home", "$HOME", "home_t.xpm", 4000, 1, 0 },
#ifndef ROOTPREFIX
{ "RootSys", "$ROOTSYS", "root_t.xpm", 5000, 1, 0 },
#else
{ ROOTPREFIX, ROOTPREFIX, "root_t.xpm", 5000, 1, 0 },
#endif
{ 0, 0, 0, 6000, 0, 0 }
};
ClassImp(TGTreeLBEntry)
ClassImp(TGFSComboBox)
//______________________________________________________________________________
TGTreeLBEntry::TGTreeLBEntry(const TGWindow *p, TGString *text,
const TGPicture *pic, Int_t id, TGString *path,
GContext_t norm, FontStruct_t font, UInt_t options,
ULong_t back) :
TGLBEntry(p, id, options, back)
{
// Create a tree (i.e. entry can be indented) listbox entry.
// The strings text and path are adopted by the entry.
if (!pic)
Error("TGTreeLBEntry", "icon not found for entry %s", text->GetString());
fPic = pic;
fSelPic = 0;
fText = text;
fPath = path;
fNormGC = norm;
fFontStruct = font;
fActive = kFALSE;
int max_ascent, max_descent;
fTWidth = gVirtualX->TextWidth(fFontStruct, fText->GetString(), fText->GetLength());
gVirtualX->GetFontProperties(fFontStruct, max_ascent, max_descent);
fTHeight = max_ascent + max_descent;
}
//______________________________________________________________________________
TGTreeLBEntry::~TGTreeLBEntry()
{
// Delete tree listbox entry.
delete fText;
delete fPath;
delete fSelPic;
}
//______________________________________________________________________________
void TGTreeLBEntry::Activate(Bool_t a)
{
// Make entry active (highlight picture).
if (fActive == a) return;
fActive = a;
if (fActive) {
fSelPic = new TGSelectedPicture(fClient, fPic);
} else {
if (fSelPic) delete fSelPic;
fSelPic = 0;
}
DoRedraw();
}
//______________________________________________________________________________
void TGTreeLBEntry::DoRedraw()
{
// Redraw the tree listbox entry.
int ix, iy, lx, ly;
ix = 0;
iy = (fHeight - fPic->GetHeight()) >> 1;
lx = (int)(fPic->GetWidth() + 4);
ly = (int)((fHeight - (fTHeight+1)) >> 1);
if (fActive) {
if (fSelPic) fSelPic->Draw(fId, fNormGC, ix, iy);
gVirtualX->SetForeground(fNormGC, fgDefaultSelectedBackground);
gVirtualX->FillRectangle(fId, fNormGC, lx, ly, fTWidth, fTHeight+1);
gVirtualX->SetForeground(fNormGC, fgSelPixel);
} else {
fPic->Draw(fId, fNormGC, ix, iy);
gVirtualX->SetForeground(fNormGC, fgWhitePixel);
gVirtualX->FillRectangle(fId, fNormGC, lx, ly, fTWidth, fTHeight+1);
gVirtualX->SetForeground(fNormGC, fgBlackPixel);
}
int max_ascent, max_descent;
gVirtualX->GetFontProperties(fFontStruct, max_ascent, max_descent);
fText->Draw(fId, fNormGC, lx, ly + max_ascent);
}
//______________________________________________________________________________
TGDimension TGTreeLBEntry::GetDefaultSize() const
{
// Return default size of tree listbox entry.
TGDimension isize(fPic->GetWidth(), fPic->GetHeight());
TGDimension lsize(fTWidth, fTHeight+1);
return TGDimension(isize.fWidth + lsize.fWidth + 4,
TMath::Max(isize.fHeight, lsize.fHeight) + 2);
}
//______________________________________________________________________________
void TGTreeLBEntry::Update(TGLBEntry *e)
{
// Update text and picture of a listbox entry.
TGTreeLBEntry *te = (TGTreeLBEntry *) e;
if (fText) delete fText;
fText = new TGString(te->GetText());
fPic = te->GetPicture();
fTWidth = gVirtualX->TextWidth(fFontStruct, fText->GetString(), fText->GetLength());
gVirtualX->ClearWindow(fId);
fClient->NeedRedraw(this);
}
//______________________________________________________________________________
FontStruct_t TGTreeLBEntry::GetDefaultFontStruct()
{ return fgDefaultFontStruct; }
//______________________________________________________________________________
const TGGC &TGTreeLBEntry::GetDefaultGC()
{ return fgDefaultGC; }
//______________________________________________________________________________
TGFSComboBox::TGFSComboBox(const TGWindow *parent, Int_t id, UInt_t options,
ULong_t back) :
TGComboBox(parent, id, options | kOwnBackground, back)
{
// Create a file system combobox showing system directories.
int i, indent;
const TGPicture *pic;
char *p;
SetTopEntry(new TGTreeLBEntry(this, new TGString("Current dir"),
fClient->GetPicture("folder_t.xpm"), 0),
new TGLayoutHints(kLHintsLeft | kLHintsExpandX |
kLHintsExpandY, 4, 0, 0, 0));
fListBox->GetContainer()->AddInput(kButtonPressMask | kButtonReleaseMask |
kPointerMotionMask);
//--- first check for the existence of some directories...
const char *homeDir = gSystem->Getenv("HOME");
#ifndef ROOTPREFIX
const char *rootSys = gSystem->Getenv("ROOTSYS");
#else
const char *rootSys = ROOTPREFIX;
#endif
for (i = 0; gLbc[i].path != 0; ++i) {
if (strstr(gLbc[i].path, "$HOME") != 0) {
if (homeDir) {
int hlen = strlen(homeDir);
p = new char[hlen + strlen(gLbc[i].path) - 3];
strcpy(p, homeDir);
strcat(p, &gLbc[i].path[5]);
gLbc[i].path = p;
} else {
gLbc[i].flags = 0;
}
}
#ifndef ROOTPREFIX
if (strstr(gLbc[i].path, "$ROOTSYS") != 0) {
#else
if (strstr(gLbc[i].path, ROOTPREFIX) != 0) {
#endif
if (rootSys) {
int hlen = strlen(rootSys);
p = new char[hlen + strlen(gLbc[i].path) - 3];
strcpy(p, rootSys);
strcat(p, &gLbc[i].path[8]);
gLbc[i].path = p;
} else {
gLbc[i].flags = 0;
}
}
if (gSystem->AccessPathName(gLbc[i].path, kFileExists) == 0)
gLbc[i].flags = 1;
}
//--- then init the contents...
for (i = 0; gLbc[i].name != 0; ++i) {
if (gLbc[i].flags) {
indent = 4 + (gLbc[i].indent * 10);
pic = fClient->GetPicture(gLbc[i].pixmap);
if (!pic) Error("TGFSComboBox", "pixmap not found: %s", gLbc[i].pixmap);
AddEntry(new TGTreeLBEntry(fListBox->GetContainer(),
new TGString(gLbc[i].name), pic, gLbc[i].id,
new TGString(gLbc[i].path)),
new TGLayoutHints(kLHintsLeft | kLHintsTop, indent, 0, 0, 0));
}
}
}
//______________________________________________________________________________
void TGFSComboBox::Update(const char *path)
{
// Update file system combo box.
char dirname[1024], mpath[1024];
const char *tailpath = 0;
int i, indent_lvl = 0, afterID = -1, sel = -1;
if (!path) return;
for (i = 0; gLbc[i].path != 0; ++i)
RemoveEntries(gLbc[i].id+1, gLbc[i+1].id-1);
int len = 0;
for (i = 0; gLbc[i].name != 0; ++i) {
if (gLbc[i].flags) {
int slen = strlen(gLbc[i].path);
if (strncmp(path, gLbc[i].path, slen) == 0) {
if (slen > len) {
sel = afterID = gLbc[i].id;
indent_lvl = gLbc[i].indent + 1;
tailpath = path + slen;
strcpy(mpath, gLbc[i].path);
len = slen;
}
}
}
}
if (tailpath && *tailpath) {
if (*tailpath == '/') ++tailpath;
if (*tailpath)
while (1) {
char *picname;
const char *semi = strchr(tailpath, '/');
if (semi == 0) {
strcpy(dirname, tailpath);
picname = "ofolder_t.xpm";
} else {
strncpy(dirname, tailpath, semi-tailpath);
dirname[semi-tailpath] = 0;
picname = "folder_t.xpm";
}
if (mpath[strlen(mpath)-1] != '/') strcat(mpath, "/");
strcat(mpath, dirname);
int indent = 4 + (indent_lvl * 10);
const TGPicture *pic = fClient->GetPicture(picname);
if (!pic) Error("Update", "pixmap not found: %s", picname);
InsertEntry(new TGTreeLBEntry(fListBox->GetContainer(),
new TGString(dirname), pic, afterID+1,
new TGString(mpath)),
new TGLayoutHints(kLHintsLeft | kLHintsTop,
indent, 0, 0, 0),
afterID);
sel = ++afterID;
++indent_lvl;
if (semi == 0) break;
tailpath = ++semi;
}
}
if (sel > 0) Select(sel);
}
|
fix small memory leak.
|
fix small memory leak.
git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@2089 27541ba8-7e3a-0410-8455-c3a389f83636
|
C++
|
lgpl-2.1
|
zzxuanyuan/root-compressor-dummy,root-mirror/root,zzxuanyuan/root-compressor-dummy,omazapa/root-old,perovic/root,Duraznos/root,pspe/root,buuck/root,agarciamontoro/root,sbinet/cxx-root,mattkretz/root,simonpf/root,jrtomps/root,omazapa/root,arch1tect0r/root,lgiommi/root,bbockelm/root,tc3t/qoot,CristinaCristescu/root,evgeny-boger/root,Y--/root,omazapa/root-old,gbitzes/root,veprbl/root,tc3t/qoot,esakellari/root,tc3t/qoot,evgeny-boger/root,gbitzes/root,perovic/root,satyarth934/root,krafczyk/root,gganis/root,zzxuanyuan/root-compressor-dummy,zzxuanyuan/root,strykejern/TTreeReader,0x0all/ROOT,sawenzel/root,beniz/root,vukasinmilosevic/root,nilqed/root,mkret2/root,davidlt/root,sawenzel/root,lgiommi/root,BerserkerTroll/root,agarciamontoro/root,bbockelm/root,smarinac/root,veprbl/root,bbockelm/root,sawenzel/root,satyarth934/root,0x0all/ROOT,davidlt/root,gganis/root,beniz/root,esakellari/root,zzxuanyuan/root-compressor-dummy,strykejern/TTreeReader,veprbl/root,cxx-hep/root-cern,zzxuanyuan/root,thomaskeck/root,sirinath/root,veprbl/root,zzxuanyuan/root,zzxuanyuan/root-compressor-dummy,agarciamontoro/root,simonpf/root,mkret2/root,0x0all/ROOT,arch1tect0r/root,georgtroska/root,ffurano/root5,abhinavmoudgil95/root,perovic/root,CristinaCristescu/root,nilqed/root,lgiommi/root,0x0all/ROOT,nilqed/root,gbitzes/root,dfunke/root,olifre/root,veprbl/root,CristinaCristescu/root,sirinath/root,omazapa/root-old,beniz/root,georgtroska/root,abhinavmoudgil95/root,gbitzes/root,Duraznos/root,evgeny-boger/root,kirbyherm/root-r-tools,BerserkerTroll/root,arch1tect0r/root,omazapa/root-old,dfunke/root,karies/root,sawenzel/root,omazapa/root,tc3t/qoot,agarciamontoro/root,0x0all/ROOT,sirinath/root,zzxuanyuan/root,evgeny-boger/root,zzxuanyuan/root-compressor-dummy,satyarth934/root,zzxuanyuan/root-compressor-dummy,strykejern/TTreeReader,zzxuanyuan/root-compressor-dummy,jrtomps/root,nilqed/root,gganis/root,esakellari/root,omazapa/root,mhuwiler/rootauto,zzxuanyuan/root-compressor-dummy,sirinath/root,alexschlueter/cern-root,omazapa/root,esakellari/root,sbinet/cxx-root,georgtroska/root,mattkretz/root,strykejern/TTreeReader,agarciamontoro/root,bbockelm/root,vukasinmilosevic/root,omazapa/root-old,vukasinmilosevic/root,mkret2/root,lgiommi/root,omazapa/root,omazapa/root,krafczyk/root,simonpf/root,simonpf/root,perovic/root,dfunke/root,beniz/root,davidlt/root,pspe/root,ffurano/root5,BerserkerTroll/root,beniz/root,gbitzes/root,olifre/root,esakellari/root,Y--/root,alexschlueter/cern-root,mattkretz/root,kirbyherm/root-r-tools,Y--/root,Duraznos/root,mhuwiler/rootauto,smarinac/root,agarciamontoro/root,CristinaCristescu/root,evgeny-boger/root,thomaskeck/root,tc3t/qoot,sirinath/root,BerserkerTroll/root,abhinavmoudgil95/root,esakellari/my_root_for_test,satyarth934/root,thomaskeck/root,vukasinmilosevic/root,olifre/root,dfunke/root,esakellari/my_root_for_test,georgtroska/root,mkret2/root,pspe/root,sirinath/root,satyarth934/root,root-mirror/root,esakellari/root,nilqed/root,krafczyk/root,omazapa/root,georgtroska/root,nilqed/root,root-mirror/root,cxx-hep/root-cern,bbockelm/root,thomaskeck/root,gganis/root,esakellari/my_root_for_test,abhinavmoudgil95/root,vukasinmilosevic/root,gbitzes/root,Duraznos/root,abhinavmoudgil95/root,zzxuanyuan/root,veprbl/root,alexschlueter/cern-root,mattkretz/root,buuck/root,ffurano/root5,BerserkerTroll/root,mkret2/root,omazapa/root-old,ffurano/root5,esakellari/root,buuck/root,strykejern/TTreeReader,omazapa/root,karies/root,simonpf/root,vukasinmilosevic/root,dfunke/root,evgeny-boger/root,veprbl/root,georgtroska/root,perovic/root,smarinac/root,CristinaCristescu/root,karies/root,bbockelm/root,simonpf/root,perovic/root,agarciamontoro/root,root-mirror/root,cxx-hep/root-cern,mkret2/root,pspe/root,zzxuanyuan/root,CristinaCristescu/root,root-mirror/root,BerserkerTroll/root,gganis/root,BerserkerTroll/root,abhinavmoudgil95/root,lgiommi/root,nilqed/root,gganis/root,tc3t/qoot,BerserkerTroll/root,esakellari/root,gganis/root,agarciamontoro/root,cxx-hep/root-cern,cxx-hep/root-cern,kirbyherm/root-r-tools,sawenzel/root,satyarth934/root,karies/root,cxx-hep/root-cern,Duraznos/root,davidlt/root,kirbyherm/root-r-tools,ffurano/root5,perovic/root,CristinaCristescu/root,olifre/root,tc3t/qoot,mhuwiler/rootauto,agarciamontoro/root,veprbl/root,CristinaCristescu/root,gganis/root,zzxuanyuan/root-compressor-dummy,CristinaCristescu/root,veprbl/root,Duraznos/root,esakellari/root,sbinet/cxx-root,Y--/root,Dr15Jones/root,zzxuanyuan/root,georgtroska/root,abhinavmoudgil95/root,alexschlueter/cern-root,kirbyherm/root-r-tools,krafczyk/root,mhuwiler/rootauto,sbinet/cxx-root,root-mirror/root,omazapa/root-old,veprbl/root,thomaskeck/root,davidlt/root,vukasinmilosevic/root,bbockelm/root,Duraznos/root,veprbl/root,satyarth934/root,olifre/root,mhuwiler/rootauto,nilqed/root,Y--/root,root-mirror/root,evgeny-boger/root,sawenzel/root,krafczyk/root,Dr15Jones/root,beniz/root,mhuwiler/rootauto,gganis/root,root-mirror/root,krafczyk/root,sbinet/cxx-root,0x0all/ROOT,esakellari/my_root_for_test,omazapa/root,buuck/root,thomaskeck/root,davidlt/root,perovic/root,smarinac/root,jrtomps/root,buuck/root,kirbyherm/root-r-tools,tc3t/qoot,omazapa/root,georgtroska/root,mkret2/root,olifre/root,arch1tect0r/root,karies/root,thomaskeck/root,mhuwiler/rootauto,karies/root,root-mirror/root,sirinath/root,kirbyherm/root-r-tools,root-mirror/root,gbitzes/root,mhuwiler/rootauto,mhuwiler/rootauto,krafczyk/root,Dr15Jones/root,beniz/root,karies/root,buuck/root,nilqed/root,dfunke/root,mhuwiler/rootauto,mattkretz/root,olifre/root,satyarth934/root,buuck/root,dfunke/root,esakellari/my_root_for_test,Y--/root,cxx-hep/root-cern,lgiommi/root,sawenzel/root,alexschlueter/cern-root,sirinath/root,BerserkerTroll/root,buuck/root,beniz/root,satyarth934/root,root-mirror/root,smarinac/root,vukasinmilosevic/root,thomaskeck/root,satyarth934/root,zzxuanyuan/root,lgiommi/root,agarciamontoro/root,arch1tect0r/root,esakellari/my_root_for_test,alexschlueter/cern-root,perovic/root,evgeny-boger/root,smarinac/root,gbitzes/root,tc3t/qoot,thomaskeck/root,agarciamontoro/root,arch1tect0r/root,Y--/root,vukasinmilosevic/root,Y--/root,jrtomps/root,perovic/root,olifre/root,smarinac/root,arch1tect0r/root,georgtroska/root,dfunke/root,Duraznos/root,zzxuanyuan/root-compressor-dummy,pspe/root,arch1tect0r/root,sawenzel/root,simonpf/root,sbinet/cxx-root,jrtomps/root,dfunke/root,smarinac/root,sirinath/root,lgiommi/root,mkret2/root,CristinaCristescu/root,bbockelm/root,karies/root,mattkretz/root,perovic/root,abhinavmoudgil95/root,karies/root,mkret2/root,smarinac/root,Duraznos/root,evgeny-boger/root,dfunke/root,lgiommi/root,beniz/root,vukasinmilosevic/root,mkret2/root,krafczyk/root,krafczyk/root,Duraznos/root,CristinaCristescu/root,esakellari/my_root_for_test,buuck/root,sbinet/cxx-root,omazapa/root-old,Y--/root,Dr15Jones/root,esakellari/my_root_for_test,mhuwiler/rootauto,buuck/root,karies/root,davidlt/root,vukasinmilosevic/root,krafczyk/root,davidlt/root,gganis/root,Duraznos/root,sbinet/cxx-root,satyarth934/root,pspe/root,sawenzel/root,gbitzes/root,strykejern/TTreeReader,0x0all/ROOT,bbockelm/root,davidlt/root,bbockelm/root,davidlt/root,georgtroska/root,pspe/root,smarinac/root,abhinavmoudgil95/root,omazapa/root-old,esakellari/my_root_for_test,arch1tect0r/root,zzxuanyuan/root,0x0all/ROOT,abhinavmoudgil95/root,thomaskeck/root,cxx-hep/root-cern,bbockelm/root,Dr15Jones/root,nilqed/root,sbinet/cxx-root,tc3t/qoot,strykejern/TTreeReader,sbinet/cxx-root,davidlt/root,zzxuanyuan/root,ffurano/root5,olifre/root,pspe/root,sirinath/root,alexschlueter/cern-root,jrtomps/root,zzxuanyuan/root,beniz/root,simonpf/root,mattkretz/root,jrtomps/root,esakellari/root,jrtomps/root,arch1tect0r/root,mattkretz/root,pspe/root,olifre/root,Dr15Jones/root,mattkretz/root,gbitzes/root,evgeny-boger/root,evgeny-boger/root,omazapa/root-old,Y--/root,esakellari/my_root_for_test,lgiommi/root,krafczyk/root,Y--/root,abhinavmoudgil95/root,gganis/root,jrtomps/root,sbinet/cxx-root,simonpf/root,omazapa/root,lgiommi/root,zzxuanyuan/root,ffurano/root5,0x0all/ROOT,sawenzel/root,arch1tect0r/root,georgtroska/root,dfunke/root,simonpf/root,BerserkerTroll/root,buuck/root,simonpf/root,nilqed/root,pspe/root,jrtomps/root,mattkretz/root,beniz/root,karies/root,gbitzes/root,omazapa/root-old,pspe/root,olifre/root,BerserkerTroll/root,esakellari/root,sawenzel/root,Dr15Jones/root,mkret2/root,jrtomps/root,sirinath/root,mattkretz/root
|
b669c6091e1b512674afc92d173c8a21bb6bfb44
|
src/coordinate_transform.hpp
|
src/coordinate_transform.hpp
|
//
// coordinate_transform.hpp
// OpenTsiolkovsky
//
// Created by Takahiro Inagawa on 2015/11/28.
// Copyright © 2015 Takahiro Inagawa. All rights reserved.
//
#ifndef coordinate_transform_hpp
#define coordinate_transform_hpp
#include <stdio.h>
#include <iostream>
#include "../lib/Eigen/Core"
const double pi = 3.14159265358979323846;
using namespace Eigen;
using namespace std;
Matrix3d dcmECI2ECEF(double second);
Vector3d posECEF(Matrix3d dcmECI2ECEF_, Vector3d posECI_);
Vector3d posLLH(Vector3d posECEF_);
double n_posECEF2LLH(double phi_n, double a, double e2);
inline double deg2rad(double deg);
Matrix3d dcmECEF2NED(Vector3d posLLH_);
Matrix3d dcmECI2NED(Matrix3d dcmECEF2NED_, Matrix3d dcmECI2ECEF_);
Vector3d vel_ECEF_NEDframe(Matrix3d dcmECI2NED_, Vector3d vel_ECI_ECIframe_, Vector3d pos_ECI_);
Vector3d vel_wind_NEDframe(double wind_speed, double wind_direction);
Vector3d vel_AIR_BODYframe(Matrix3d dcmNED2ECEF_, Vector3d vel_ECEF_NEDframe_, Vector3d vel_wind_NEDframe_);
Vector3d angle_of_attack(Vector3d vel_AIR_BODYframe_);
Matrix3d dcmNED2BODY(double azimuth_rad, double elevation_rad);
Matrix3d dcmNED2BODY(double azimuth_rad, double elevation_rad, double roll_rad);
Vector2d azimuth_elevation(Vector3d vel_BODY_NEDframe);
Vector3d azimuth_elevation_roll(Matrix3d dcmNED2BODY_);
Matrix3d dcmECI2BODY(Matrix3d dcmNED2BODY_, Matrix3d dcmECI2NED_);
Vector3d posECEF(Vector3d posLLH_);
Vector3d posECI(Matrix3d posECEF_, double second);
Vector3d vel_ECI_ECIframe(Matrix3d dcmNED2ECI_, Vector3d vel_ECEF_NEDframe_, Vector3d posECI_);
// ==== Initialize ====
Vector3d posECI_init(Vector3d posLLH_);
Vector3d velECI_init(Vector3d vel_ECEF_NEDframe_, Vector3d posLLH_);
double distance_surface(Vector3d pos0_LLH, Vector3d pos1_LLH);
Vector3d posLLH_IIP(Vector3d posECEF_, Vector3d vel_ECEF_ECEFframe_);
inline double deg2rad(double deg){
return deg / 180.0 * pi;
}
inline double rad2deg(double rad){
return rad * 180.0 / pi;
}
#endif /* coordinate_transform_hpp */
|
//
// coordinate_transform.hpp
// OpenTsiolkovsky
//
// Created by Takahiro Inagawa on 2015/11/28.
// Copyright © 2015 Takahiro Inagawa. All rights reserved.
//
#ifndef coordinate_transform_hpp
#define coordinate_transform_hpp
#include <stdio.h>
#include <iostream>
#include "../lib/Eigen/Core"
#include "../lib/Eigen/Geometry"
const double pi = 3.14159265358979323846;
using namespace Eigen;
using namespace std;
Matrix3d dcmECI2ECEF(double second);
Vector3d posECEF(Matrix3d dcmECI2ECEF_, Vector3d posECI_);
Vector3d posLLH(Vector3d posECEF_);
double n_posECEF2LLH(double phi_n, double a, double e2);
inline double deg2rad(double deg);
Matrix3d dcmECEF2NED(Vector3d posLLH_);
Matrix3d dcmECI2NED(Matrix3d dcmECEF2NED_, Matrix3d dcmECI2ECEF_);
Vector3d vel_ECEF_NEDframe(Matrix3d dcmECI2NED_, Vector3d vel_ECI_ECIframe_, Vector3d pos_ECI_);
Vector3d vel_wind_NEDframe(double wind_speed, double wind_direction);
Vector3d vel_AIR_BODYframe(Matrix3d dcmNED2ECEF_, Vector3d vel_ECEF_NEDframe_, Vector3d vel_wind_NEDframe_);
Vector3d angle_of_attack(Vector3d vel_AIR_BODYframe_);
Matrix3d dcmNED2BODY(double azimuth_rad, double elevation_rad);
Matrix3d dcmNED2BODY(double azimuth_rad, double elevation_rad, double roll_rad);
Vector2d azimuth_elevation(Vector3d vel_BODY_NEDframe);
Vector3d azimuth_elevation_roll(Matrix3d dcmNED2BODY_);
Matrix3d dcmECI2BODY(Matrix3d dcmNED2BODY_, Matrix3d dcmECI2NED_);
Vector3d posECEF(Vector3d posLLH_);
Vector3d posECI(Matrix3d posECEF_, double second);
Vector3d vel_ECI_ECIframe(Matrix3d dcmNED2ECI_, Vector3d vel_ECEF_NEDframe_, Vector3d posECI_);
// ==== Initialize ====
Vector3d posECI_init(Vector3d posLLH_);
Vector3d velECI_init(Vector3d vel_ECEF_NEDframe_, Vector3d posLLH_);
double distance_surface(Vector3d pos0_LLH, Vector3d pos1_LLH);
Vector3d posLLH_IIP(Vector3d posECEF_, Vector3d vel_ECEF_ECEFframe_);
inline double deg2rad(double deg){
return deg / 180.0 * pi;
}
inline double rad2deg(double rad){
return rad * 180.0 / pi;
}
#endif /* coordinate_transform_hpp */
|
fix include
|
fix include
|
C++
|
mit
|
istellartech/OpenTsiolkovsky,istellartech/OpenTsiolkovsky,istellartech/OpenTsiolkovsky,istellartech/OpenTsiolkovsky,istellartech/OpenTsiolkovsky,istellartech/OpenTsiolkovsky
|
c239e0416d54c0a19b55a056fa1c92bbd400cac7
|
src/core/lib/surface/init.cc
|
src/core/lib/surface/init.cc
|
/*
*
* Copyright 2015 gRPC authors.
*
* 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 <grpc/support/port_platform.h>
#include <limits.h>
#include <memory.h>
#include <grpc/fork.h>
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/time.h>
#include "src/core/lib/channel/channel_stack.h"
#include "src/core/lib/channel/channelz_registry.h"
#include "src/core/lib/channel/connected_channel.h"
#include "src/core/lib/channel/handshaker_registry.h"
#include "src/core/lib/debug/stats.h"
#include "src/core/lib/debug/trace.h"
#include "src/core/lib/gprpp/fork.h"
#include "src/core/lib/gprpp/mutex_lock.h"
#include "src/core/lib/http/parser.h"
#include "src/core/lib/iomgr/call_combiner.h"
#include "src/core/lib/iomgr/combiner.h"
#include "src/core/lib/iomgr/executor.h"
#include "src/core/lib/iomgr/iomgr.h"
#include "src/core/lib/iomgr/resource_quota.h"
#include "src/core/lib/iomgr/timer_manager.h"
#include "src/core/lib/profiling/timers.h"
#include "src/core/lib/slice/slice_internal.h"
#include "src/core/lib/surface/api_trace.h"
#include "src/core/lib/surface/call.h"
#include "src/core/lib/surface/channel_init.h"
#include "src/core/lib/surface/completion_queue.h"
#include "src/core/lib/surface/init.h"
#include "src/core/lib/surface/lame_client.h"
#include "src/core/lib/surface/server.h"
#include "src/core/lib/transport/bdp_estimator.h"
#include "src/core/lib/transport/connectivity_state.h"
#include "src/core/lib/transport/transport_impl.h"
/* (generated) built in registry of plugins */
extern void grpc_register_built_in_plugins(void);
#define MAX_PLUGINS 128
static gpr_once g_basic_init = GPR_ONCE_INIT;
static gpr_mu g_init_mu;
static int g_initializations;
static gpr_cv* g_shutting_down_cv;
static bool g_shutting_down;
static void do_basic_init(void) {
gpr_log_verbosity_init();
gpr_mu_init(&g_init_mu);
g_shutting_down_cv = static_cast<gpr_cv*>(malloc(sizeof(gpr_cv)));
gpr_cv_init(g_shutting_down_cv);
g_shutting_down = false;
grpc_register_built_in_plugins();
grpc_cq_global_init();
g_initializations = 0;
}
static bool append_filter(grpc_channel_stack_builder* builder, void* arg) {
return grpc_channel_stack_builder_append_filter(
builder, static_cast<const grpc_channel_filter*>(arg), nullptr, nullptr);
}
static bool prepend_filter(grpc_channel_stack_builder* builder, void* arg) {
return grpc_channel_stack_builder_prepend_filter(
builder, static_cast<const grpc_channel_filter*>(arg), nullptr, nullptr);
}
static void register_builtin_channel_init() {
grpc_channel_init_register_stage(GRPC_CLIENT_SUBCHANNEL,
GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
grpc_add_connected_filter, nullptr);
grpc_channel_init_register_stage(GRPC_CLIENT_DIRECT_CHANNEL,
GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
grpc_add_connected_filter, nullptr);
grpc_channel_init_register_stage(GRPC_SERVER_CHANNEL,
GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
grpc_add_connected_filter, nullptr);
grpc_channel_init_register_stage(GRPC_CLIENT_LAME_CHANNEL,
GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
append_filter, (void*)&grpc_lame_filter);
grpc_channel_init_register_stage(GRPC_SERVER_CHANNEL, INT_MAX, prepend_filter,
(void*)&grpc_server_top_filter);
}
typedef struct grpc_plugin {
void (*init)();
void (*destroy)();
} grpc_plugin;
static grpc_plugin g_all_of_the_plugins[MAX_PLUGINS];
static int g_number_of_plugins = 0;
void grpc_register_plugin(void (*init)(void), void (*destroy)(void)) {
GRPC_API_TRACE("grpc_register_plugin(init=%p, destroy=%p)", 2,
((void*)(intptr_t)init, (void*)(intptr_t)destroy));
GPR_ASSERT(g_number_of_plugins != MAX_PLUGINS);
g_all_of_the_plugins[g_number_of_plugins].init = init;
g_all_of_the_plugins[g_number_of_plugins].destroy = destroy;
g_number_of_plugins++;
}
void grpc_init(void) {
int i;
gpr_once_init(&g_basic_init, do_basic_init);
grpc_core::MutexLock lock(&g_init_mu);
if (++g_initializations == 1) {
if (g_shutting_down) {
g_shutting_down = false;
gpr_cv_broadcast(g_shutting_down_cv);
}
grpc_core::Fork::GlobalInit();
grpc_fork_handlers_auto_register();
gpr_time_init();
gpr_arena_init();
grpc_stats_init();
grpc_slice_intern_init();
grpc_mdctx_global_init();
grpc_channel_init_init();
grpc_core::channelz::ChannelzRegistry::Init();
grpc_security_pre_init();
grpc_core::ApplicationCallbackExecCtx::GlobalInit();
grpc_core::ExecCtx::GlobalInit();
grpc_iomgr_init();
gpr_timers_global_init();
grpc_core::HandshakerRegistry::Init();
grpc_security_init();
for (i = 0; i < g_number_of_plugins; i++) {
if (g_all_of_the_plugins[i].init != nullptr) {
g_all_of_the_plugins[i].init();
}
}
/* register channel finalization AFTER all plugins, to ensure that it's run
* at the appropriate time */
grpc_register_security_filters();
register_builtin_channel_init();
grpc_tracer_init("GRPC_TRACE");
/* no more changes to channel init pipelines */
grpc_channel_init_finalize();
grpc_iomgr_start();
}
GRPC_API_TRACE("grpc_init(void)", 0, ());
}
void grpc_shutdown_internal_locked(void) {
int i;
{
grpc_core::ExecCtx exec_ctx(0);
grpc_iomgr_shutdown_background_closure();
{
grpc_timer_manager_set_threading(false); // shutdown timer_manager thread
grpc_core::Executor::ShutdownAll();
for (i = g_number_of_plugins; i >= 0; i--) {
if (g_all_of_the_plugins[i].destroy != nullptr) {
g_all_of_the_plugins[i].destroy();
}
}
}
grpc_iomgr_shutdown();
gpr_timers_global_destroy();
grpc_tracer_shutdown();
grpc_mdctx_global_shutdown();
grpc_core::HandshakerRegistry::Shutdown();
grpc_slice_intern_shutdown();
grpc_core::channelz::ChannelzRegistry::Shutdown();
grpc_stats_shutdown();
grpc_core::Fork::GlobalShutdown();
}
grpc_core::ExecCtx::GlobalShutdown();
grpc_core::ApplicationCallbackExecCtx::GlobalShutdown();
g_shutting_down = false;
gpr_cv_broadcast(g_shutting_down_cv);
}
void grpc_shutdown_internal(void* ignored) {
GRPC_API_TRACE("grpc_shutdown_internal", 0, ());
grpc_core::MutexLock lock(&g_init_mu);
// We have released lock from the shutdown thread and it is possible that
// another grpc_init has been called, and do nothing if that is the case.
if (--g_initializations != 0) {
return;
}
grpc_shutdown_internal_locked();
}
void grpc_shutdown(void) {
GRPC_API_TRACE("grpc_shutdown(void)", 0, ());
grpc_core::MutexLock lock(&g_init_mu);
if (--g_initializations == 0) {
g_initializations++;
g_shutting_down = true;
// spawn a detached thread to do the actual clean up in case we are
// currently in an executor thread.
grpc_core::Thread cleanup_thread(
"grpc_shutdown", grpc_shutdown_internal, nullptr, nullptr,
grpc_core::Thread::Options().set_joinable(false).set_tracked(false));
cleanup_thread.Start();
}
}
void grpc_shutdown_blocking(void) {
GRPC_API_TRACE("grpc_shutdown_blocking(void)", 0, ());
grpc_core::MutexLock lock(&g_init_mu);
if (--g_initializations == 0) {
g_shutting_down = true;
grpc_shutdown_internal_locked();
}
}
int grpc_is_initialized(void) {
int r;
gpr_once_init(&g_basic_init, do_basic_init);
grpc_core::MutexLock lock(&g_init_mu);
r = g_initializations > 0;
return r;
}
void grpc_maybe_wait_for_async_shutdown(void) {
gpr_once_init(&g_basic_init, do_basic_init);
grpc_core::MutexLock lock(&g_init_mu);
while (g_shutting_down) {
gpr_cv_wait(g_shutting_down_cv, &g_init_mu,
gpr_inf_future(GPR_CLOCK_REALTIME));
}
}
|
/*
*
* Copyright 2015 gRPC authors.
*
* 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 <grpc/support/port_platform.h>
#include <limits.h>
#include <memory.h>
#include <grpc/fork.h>
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/time.h>
#include "src/core/lib/channel/channel_stack.h"
#include "src/core/lib/channel/channelz_registry.h"
#include "src/core/lib/channel/connected_channel.h"
#include "src/core/lib/channel/handshaker_registry.h"
#include "src/core/lib/debug/stats.h"
#include "src/core/lib/debug/trace.h"
#include "src/core/lib/gprpp/fork.h"
#include "src/core/lib/gprpp/mutex_lock.h"
#include "src/core/lib/http/parser.h"
#include "src/core/lib/iomgr/call_combiner.h"
#include "src/core/lib/iomgr/combiner.h"
#include "src/core/lib/iomgr/executor.h"
#include "src/core/lib/iomgr/iomgr.h"
#include "src/core/lib/iomgr/resource_quota.h"
#include "src/core/lib/iomgr/timer_manager.h"
#include "src/core/lib/profiling/timers.h"
#include "src/core/lib/slice/slice_internal.h"
#include "src/core/lib/surface/api_trace.h"
#include "src/core/lib/surface/call.h"
#include "src/core/lib/surface/channel_init.h"
#include "src/core/lib/surface/completion_queue.h"
#include "src/core/lib/surface/init.h"
#include "src/core/lib/surface/lame_client.h"
#include "src/core/lib/surface/server.h"
#include "src/core/lib/transport/bdp_estimator.h"
#include "src/core/lib/transport/connectivity_state.h"
#include "src/core/lib/transport/transport_impl.h"
/* (generated) built in registry of plugins */
extern void grpc_register_built_in_plugins(void);
#define MAX_PLUGINS 128
static gpr_once g_basic_init = GPR_ONCE_INIT;
static gpr_mu g_init_mu;
static int g_initializations;
static gpr_cv* g_shutting_down_cv;
static bool g_shutting_down;
static void do_basic_init(void) {
gpr_log_verbosity_init();
gpr_mu_init(&g_init_mu);
g_shutting_down_cv = static_cast<gpr_cv*>(malloc(sizeof(gpr_cv)));
gpr_cv_init(g_shutting_down_cv);
g_shutting_down = false;
grpc_register_built_in_plugins();
grpc_cq_global_init();
gpr_time_init();
g_initializations = 0;
}
static bool append_filter(grpc_channel_stack_builder* builder, void* arg) {
return grpc_channel_stack_builder_append_filter(
builder, static_cast<const grpc_channel_filter*>(arg), nullptr, nullptr);
}
static bool prepend_filter(grpc_channel_stack_builder* builder, void* arg) {
return grpc_channel_stack_builder_prepend_filter(
builder, static_cast<const grpc_channel_filter*>(arg), nullptr, nullptr);
}
static void register_builtin_channel_init() {
grpc_channel_init_register_stage(GRPC_CLIENT_SUBCHANNEL,
GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
grpc_add_connected_filter, nullptr);
grpc_channel_init_register_stage(GRPC_CLIENT_DIRECT_CHANNEL,
GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
grpc_add_connected_filter, nullptr);
grpc_channel_init_register_stage(GRPC_SERVER_CHANNEL,
GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
grpc_add_connected_filter, nullptr);
grpc_channel_init_register_stage(GRPC_CLIENT_LAME_CHANNEL,
GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
append_filter, (void*)&grpc_lame_filter);
grpc_channel_init_register_stage(GRPC_SERVER_CHANNEL, INT_MAX, prepend_filter,
(void*)&grpc_server_top_filter);
}
typedef struct grpc_plugin {
void (*init)();
void (*destroy)();
} grpc_plugin;
static grpc_plugin g_all_of_the_plugins[MAX_PLUGINS];
static int g_number_of_plugins = 0;
void grpc_register_plugin(void (*init)(void), void (*destroy)(void)) {
GRPC_API_TRACE("grpc_register_plugin(init=%p, destroy=%p)", 2,
((void*)(intptr_t)init, (void*)(intptr_t)destroy));
GPR_ASSERT(g_number_of_plugins != MAX_PLUGINS);
g_all_of_the_plugins[g_number_of_plugins].init = init;
g_all_of_the_plugins[g_number_of_plugins].destroy = destroy;
g_number_of_plugins++;
}
void grpc_init(void) {
int i;
gpr_once_init(&g_basic_init, do_basic_init);
grpc_core::MutexLock lock(&g_init_mu);
if (++g_initializations == 1) {
if (g_shutting_down) {
g_shutting_down = false;
gpr_cv_broadcast(g_shutting_down_cv);
}
grpc_core::Fork::GlobalInit();
grpc_fork_handlers_auto_register();
gpr_arena_init();
grpc_stats_init();
grpc_slice_intern_init();
grpc_mdctx_global_init();
grpc_channel_init_init();
grpc_core::channelz::ChannelzRegistry::Init();
grpc_security_pre_init();
grpc_core::ApplicationCallbackExecCtx::GlobalInit();
grpc_core::ExecCtx::GlobalInit();
grpc_iomgr_init();
gpr_timers_global_init();
grpc_core::HandshakerRegistry::Init();
grpc_security_init();
for (i = 0; i < g_number_of_plugins; i++) {
if (g_all_of_the_plugins[i].init != nullptr) {
g_all_of_the_plugins[i].init();
}
}
/* register channel finalization AFTER all plugins, to ensure that it's run
* at the appropriate time */
grpc_register_security_filters();
register_builtin_channel_init();
grpc_tracer_init("GRPC_TRACE");
/* no more changes to channel init pipelines */
grpc_channel_init_finalize();
grpc_iomgr_start();
}
GRPC_API_TRACE("grpc_init(void)", 0, ());
}
void grpc_shutdown_internal_locked(void) {
int i;
{
grpc_core::ExecCtx exec_ctx(0);
grpc_iomgr_shutdown_background_closure();
{
grpc_timer_manager_set_threading(false); // shutdown timer_manager thread
grpc_core::Executor::ShutdownAll();
for (i = g_number_of_plugins; i >= 0; i--) {
if (g_all_of_the_plugins[i].destroy != nullptr) {
g_all_of_the_plugins[i].destroy();
}
}
}
grpc_iomgr_shutdown();
gpr_timers_global_destroy();
grpc_tracer_shutdown();
grpc_mdctx_global_shutdown();
grpc_core::HandshakerRegistry::Shutdown();
grpc_slice_intern_shutdown();
grpc_core::channelz::ChannelzRegistry::Shutdown();
grpc_stats_shutdown();
grpc_core::Fork::GlobalShutdown();
}
grpc_core::ExecCtx::GlobalShutdown();
grpc_core::ApplicationCallbackExecCtx::GlobalShutdown();
g_shutting_down = false;
gpr_cv_broadcast(g_shutting_down_cv);
}
void grpc_shutdown_internal(void* ignored) {
GRPC_API_TRACE("grpc_shutdown_internal", 0, ());
grpc_core::MutexLock lock(&g_init_mu);
// We have released lock from the shutdown thread and it is possible that
// another grpc_init has been called, and do nothing if that is the case.
if (--g_initializations != 0) {
return;
}
grpc_shutdown_internal_locked();
}
void grpc_shutdown(void) {
GRPC_API_TRACE("grpc_shutdown(void)", 0, ());
grpc_core::MutexLock lock(&g_init_mu);
if (--g_initializations == 0) {
g_initializations++;
g_shutting_down = true;
// spawn a detached thread to do the actual clean up in case we are
// currently in an executor thread.
grpc_core::Thread cleanup_thread(
"grpc_shutdown", grpc_shutdown_internal, nullptr, nullptr,
grpc_core::Thread::Options().set_joinable(false).set_tracked(false));
cleanup_thread.Start();
}
}
void grpc_shutdown_blocking(void) {
GRPC_API_TRACE("grpc_shutdown_blocking(void)", 0, ());
grpc_core::MutexLock lock(&g_init_mu);
if (--g_initializations == 0) {
g_shutting_down = true;
grpc_shutdown_internal_locked();
}
}
int grpc_is_initialized(void) {
int r;
gpr_once_init(&g_basic_init, do_basic_init);
grpc_core::MutexLock lock(&g_init_mu);
r = g_initializations > 0;
return r;
}
void grpc_maybe_wait_for_async_shutdown(void) {
gpr_once_init(&g_basic_init, do_basic_init);
grpc_core::MutexLock lock(&g_init_mu);
while (g_shutting_down) {
gpr_cv_wait(g_shutting_down_cv, &g_init_mu,
gpr_inf_future(GPR_CLOCK_REALTIME));
}
}
|
Initialize time as part of basic initialization.
|
Initialize time as part of basic initialization.
`gpr_time_init` must happen in `do_basic_init`, because
for normal initialization we may need the precise clock
(e.g., if profilers are enabled).
Otherwise, we will have an stack overflow.
Fixes #18589
|
C++
|
apache-2.0
|
sreecha/grpc,jtattermusch/grpc,pszemus/grpc,vjpai/grpc,muxi/grpc,muxi/grpc,stanley-cheung/grpc,grpc/grpc,grpc/grpc,pszemus/grpc,grpc/grpc,pszemus/grpc,firebase/grpc,sreecha/grpc,jtattermusch/grpc,grpc/grpc,ctiller/grpc,ejona86/grpc,ctiller/grpc,donnadionne/grpc,nicolasnoble/grpc,firebase/grpc,stanley-cheung/grpc,nicolasnoble/grpc,jtattermusch/grpc,ctiller/grpc,firebase/grpc,jboeuf/grpc,muxi/grpc,donnadionne/grpc,sreecha/grpc,sreecha/grpc,vjpai/grpc,sreecha/grpc,sreecha/grpc,ejona86/grpc,jboeuf/grpc,muxi/grpc,vjpai/grpc,firebase/grpc,vjpai/grpc,jboeuf/grpc,jtattermusch/grpc,nicolasnoble/grpc,vjpai/grpc,ctiller/grpc,ctiller/grpc,donnadionne/grpc,ejona86/grpc,nicolasnoble/grpc,muxi/grpc,muxi/grpc,ejona86/grpc,ejona86/grpc,vjpai/grpc,jtattermusch/grpc,donnadionne/grpc,firebase/grpc,sreecha/grpc,pszemus/grpc,stanley-cheung/grpc,grpc/grpc,nicolasnoble/grpc,vjpai/grpc,pszemus/grpc,vjpai/grpc,vjpai/grpc,firebase/grpc,muxi/grpc,sreecha/grpc,donnadionne/grpc,stanley-cheung/grpc,ejona86/grpc,firebase/grpc,muxi/grpc,pszemus/grpc,muxi/grpc,sreecha/grpc,jboeuf/grpc,jtattermusch/grpc,vjpai/grpc,ejona86/grpc,ejona86/grpc,donnadionne/grpc,stanley-cheung/grpc,stanley-cheung/grpc,firebase/grpc,firebase/grpc,pszemus/grpc,jboeuf/grpc,jtattermusch/grpc,firebase/grpc,nicolasnoble/grpc,firebase/grpc,pszemus/grpc,jboeuf/grpc,ctiller/grpc,jboeuf/grpc,stanley-cheung/grpc,ctiller/grpc,ctiller/grpc,nicolasnoble/grpc,pszemus/grpc,pszemus/grpc,jboeuf/grpc,vjpai/grpc,jtattermusch/grpc,sreecha/grpc,grpc/grpc,nicolasnoble/grpc,ejona86/grpc,stanley-cheung/grpc,ejona86/grpc,jtattermusch/grpc,stanley-cheung/grpc,sreecha/grpc,grpc/grpc,ctiller/grpc,nicolasnoble/grpc,nicolasnoble/grpc,donnadionne/grpc,ctiller/grpc,stanley-cheung/grpc,stanley-cheung/grpc,donnadionne/grpc,stanley-cheung/grpc,jboeuf/grpc,ejona86/grpc,grpc/grpc,pszemus/grpc,ejona86/grpc,jtattermusch/grpc,grpc/grpc,jtattermusch/grpc,donnadionne/grpc,ctiller/grpc,muxi/grpc,muxi/grpc,jboeuf/grpc,nicolasnoble/grpc,muxi/grpc,ctiller/grpc,grpc/grpc,pszemus/grpc,firebase/grpc,grpc/grpc,donnadionne/grpc,nicolasnoble/grpc,vjpai/grpc,sreecha/grpc,donnadionne/grpc,jboeuf/grpc,jtattermusch/grpc,grpc/grpc,jboeuf/grpc,donnadionne/grpc
|
3a9db750bb48434321c2f5e43d9e6bc26dc29def
|
data_structures/patricia_trie.cpp
|
data_structures/patricia_trie.cpp
|
/*
Copyright Eli Dupree and Isaac Dupree, 2011, 2012, 2013
This file is part of Lasercake.
Lasercake is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Lasercake is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Lasercake. If not, see <http://www.gnu.org/licenses/>.
*/
#include "patricia_trie.hpp"
template<num_coordinates_type Dims, typename Coord, typename T, typename Traits>
pow2_radix_patricia_trie_node<Dims, Coord, T, Traits>&
pow2_radix_patricia_trie_node<Dims, Coord, T, Traits>::insert(loc_type leaf_loc, T&& new_leaf, monoid_type leaf_monoid) {
// invariant: this 'node' variable changes but is never nullptr.
node_type* node_to_initialize;
node_type*const node = &this->find_node(leaf_loc);
caller_error_if(node->points_to_leaf() && node->min() == leaf_loc, "Inserting a leaf in a location that's already in the tree");
if (node->is_empty()) {
node_to_initialize = node;
node_to_initialize->initialize_monoid_(std::move(leaf_monoid));
//LOG << "Type 1 " << std::hex << size_t(node_to_initialize) << std::dec << "\n";
}
else {
// That child's location was too specific (wrong) for us.
sub_nodes_type* intermediate_nodes = node_allocator().allocate(1);
if (!intermediate_nodes) {
throw std::bad_alloc();
}
try {
// nothrow except monoids
new (intermediate_nodes) sub_nodes_type();
for (node_type& intermediate_node : *intermediate_nodes) {
intermediate_node.set_parent(node);
assert(intermediate_node.size_exponent_in_each_dimension() == 0);
}
}
catch(...) {
node_allocator().deallocate(intermediate_nodes, 1);
throw;
}
num_bits_type shared_size_exponent;
node_type* new_location_for_node_original_contents;
node_type* new_leaf_ptr_node;
try {
// loop is nothrow
shared_size_exponent = 0;
for (num_coordinates_type dim = 0; dim != dimensions; ++dim) {
const num_bits_type dim_shared_size_exponent =
num_bits_in_integer_that_are_not_leading_zeroes(
to_unsigned_type(node->min()[dim] ^ leaf_loc[dim]));
if(shared_size_exponent < dim_shared_size_exponent) {
shared_size_exponent = dim_shared_size_exponent;
}
}
// assert is typically nothrow, and it's also okay
// if it throws here.
assert(shared_size_exponent > 0);
//LOG << "~~" << shared_size_exponent << std::endl;
// move node's contents to its new location
new_location_for_node_original_contents = // nothrow
&child_matching(*intermediate_nodes, shared_size_exponent, node->min());
new_leaf_ptr_node = // nothrow
&child_matching(*intermediate_nodes, shared_size_exponent, leaf_loc);
assert(new_location_for_node_original_contents != new_leaf_ptr_node);
// Monoid ops may throw. Do the copy before anything else so that if
// it throws, we won't be in a partial state and have destructors
// mess things up.
new_location_for_node_original_contents->set_monoid(node->monoid());
new_location_for_node_original_contents->set_min(node->min());
new_location_for_node_original_contents->set_size_exponent_in_each_dimension(node->size_exponent_in_each_dimension());
new_location_for_node_original_contents->set_stable_node_reference_keeper(node->stable_node_reference_keeper());
// Update monoids. If they throw, insert() will still
// be a no-op except for monoid inconsistency
//
// is this impl a time waste? if starting at the root,
// and if not worrying about exceptions,
// we could have updated them on the way down,
// though the short-circuit wouldn't take effect then.
assert(new_leaf_ptr_node->parent());
assert(new_leaf_ptr_node->parent() == node);
new_leaf_ptr_node->initialize_monoid_(std::move(leaf_monoid));
// Compute shared coords here in case some Coord ops can throw.
loc_type shared_loc_min;
const Coord mask = safe_left_shift(~Coord(0), shared_size_exponent);
for (num_coordinates_type dim = 0; dim != dimensions; ++dim) {
shared_loc_min[dim] = node->min()[dim] & mask;
}
// If Coord move throws, we're in trouble, because we're moving
// an array of them so some of node's coords could be overwritten
// already and we have no reliable way to restore them without
// nothrow move. This is why we require nothrow Coord move.
//
// Nevertheless do this inside the try/catch so we at least
// don't leak memory if it throws.
node->set_min(std::move(shared_loc_min));
}
catch(...) {
intermediate_nodes->~sub_nodes_type();
node_allocator().deallocate(intermediate_nodes, 1);
throw;
}
// continue moving node's contents to its new location
// nothrow
new_location_for_node_original_contents->set_sub_nodes(node->sub_nodes());
new_location_for_node_original_contents->set_leaf(node->move_leaf());
if(sub_nodes_type* original_sub_nodes = new_location_for_node_original_contents->sub_nodes()) {
for (node_type& sub_node : *original_sub_nodes) {
sub_node.set_parent(new_location_for_node_original_contents);
}
}
node->set_size_exponent_in_each_dimension(shared_size_exponent);
node->set_leaf();
node->set_sub_nodes(intermediate_nodes);
node->set_stable_node_reference_keeper();
//node->parent remains the same
//node->monoid remains the same (it will be updated later as one of the parents)
// nothrow
node_to_initialize = new_leaf_ptr_node;
//LOG << "Type 2 " << std::hex << size_t(node_to_initialize) << std::dec << "\n";
}
assert(!node_to_initialize->sub_nodes());
node_to_initialize->set_min(std::move(leaf_loc));
// hopefully nothrow
node_to_initialize->set_leaf(std::move(new_leaf));
return *node_to_initialize;
}
template<num_coordinates_type Dims, typename Coord, typename T, typename Traits>
bool pow2_radix_patricia_trie_node<Dims, Coord, T, Traits>::erase(loc_type leaf_loc) {
node_type& node = find_node(leaf_loc);
if (node.points_to_leaf()) {
node.update_monoid(monoid_type());
node.set_leaf();
// TODO shorten tree where appropriate
// (Could keep immediate-children-counts explicitly in nodes
// to make that a little faster; probably fine either way.)
delete_empty_leaves_(node);
// Now node (which might be *this) might no longer exist.
return true;
}
else { return false; }
}
template<num_coordinates_type Dims, typename Coord, typename T, typename Traits>
bool pow2_radix_patricia_trie_node<Dims, Coord, T, Traits>::erase_if_empty() {
node_type& node_that_exists = delete_empty_leaves_(*this);
return (&node_that_exists != this);
}
template<num_coordinates_type Dims, typename Coord, typename T, typename Traits>
pow2_radix_patricia_trie_node<Dims, Coord, T, Traits>&
pow2_radix_patricia_trie_node<Dims, Coord, T, Traits>::delete_empty_leaves_(node_type& node1) {
node_type* node = &node1;
while(true) {
sub_nodes_type* siblings = node->siblings();
if(!siblings) { break; }
bool siblings_all_empty = true;
for(node_type& sibling : *siblings) {
if(!sibling.is_empty()) { siblings_all_empty = false; }
}
if(siblings_all_empty) {
node_type* parent = node->parent();
for(node_type& sibling : *siblings) {
if(auto sibling_keeper = sibling.stable_node_reference_keeper()) {
if(auto parent_keeper = parent->stable_node_reference_keeper()) {
sibling_keeper->look_at_this_one_instead_ = parent_keeper;
sibling_keeper->here_ = nullptr;
}
else {
sibling_keeper->here_ = parent;
parent->set_stable_node_reference_keeper(sibling_keeper);
}
}
}
parent->delete_sub_nodes_();
node = parent;
}
else {
break;
}
}
return *node;
}
#include "../world.hpp"
template class pow2_radix_patricia_trie_node<3,
tile_coordinate,
the_decomposition_of_the_world_into_blocks_impl::region_specification,
the_decomposition_of_the_world_into_blocks_impl::worldblock_trie_traits>;
#include "../tests/patricia_trie_tests.hpp"
template class pow2_radix_patricia_trie_node<3,
patricia_trie_testing::coord,
std::unique_ptr<patricia_trie_testing::block>,
patricia_trie_testing::trie_traits>;
|
/*
Copyright Eli Dupree and Isaac Dupree, 2011, 2012, 2013
This file is part of Lasercake.
Lasercake is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Lasercake is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Lasercake. If not, see <http://www.gnu.org/licenses/>.
*/
#include "patricia_trie.hpp"
template<num_coordinates_type Dims, typename Coord, typename T, typename Traits>
pow2_radix_patricia_trie_node<Dims, Coord, T, Traits>&
pow2_radix_patricia_trie_node<Dims, Coord, T, Traits>::insert(loc_type leaf_loc, T&& new_leaf, monoid_type leaf_monoid) {
// invariant: this 'node' variable changes but is never nullptr.
node_type* node_to_initialize;
node_type*const node = &this->find_node(leaf_loc);
caller_error_if(node->points_to_leaf() && node->min() == leaf_loc, "Inserting a leaf in a location that's already in the tree");
if (node->is_empty()) {
node_to_initialize = node;
//LOG << "Type 1 " << std::hex << size_t(node_to_initialize) << std::dec << "\n";
}
else {
// That child's location was too specific (wrong) for us.
sub_nodes_type* intermediate_nodes = node_allocator().allocate(1);
if (!intermediate_nodes) {
throw std::bad_alloc();
}
try {
// nothrow except monoids
new (intermediate_nodes) sub_nodes_type();
for (node_type& intermediate_node : *intermediate_nodes) {
intermediate_node.set_parent(node);
assert(intermediate_node.size_exponent_in_each_dimension() == 0);
}
}
catch(...) {
node_allocator().deallocate(intermediate_nodes, 1);
throw;
}
num_bits_type shared_size_exponent;
node_type* new_location_for_node_original_contents;
node_type* new_leaf_ptr_node;
try {
// loop is nothrow
shared_size_exponent = 0;
for (num_coordinates_type dim = 0; dim != dimensions; ++dim) {
const num_bits_type dim_shared_size_exponent =
num_bits_in_integer_that_are_not_leading_zeroes(
to_unsigned_type(node->min()[dim] ^ leaf_loc[dim]));
if(shared_size_exponent < dim_shared_size_exponent) {
shared_size_exponent = dim_shared_size_exponent;
}
}
// assert is typically nothrow, and it's also okay
// if it throws here.
assert(shared_size_exponent > 0);
//LOG << "~~" << shared_size_exponent << std::endl;
// move node's contents to its new location
new_location_for_node_original_contents = // nothrow
&child_matching(*intermediate_nodes, shared_size_exponent, node->min());
new_leaf_ptr_node = // nothrow
&child_matching(*intermediate_nodes, shared_size_exponent, leaf_loc);
assert(new_location_for_node_original_contents != new_leaf_ptr_node);
// Monoid ops may throw. Do the copy before anything else so that if
// it throws, we won't be in a partial state and have destructors
// mess things up.
new_location_for_node_original_contents->set_monoid(node->monoid());
new_location_for_node_original_contents->set_min(node->min());
new_location_for_node_original_contents->set_size_exponent_in_each_dimension(node->size_exponent_in_each_dimension());
new_location_for_node_original_contents->set_stable_node_reference_keeper(node->stable_node_reference_keeper());
// Compute shared coords here in case some Coord ops can throw.
loc_type shared_loc_min;
const Coord mask = safe_left_shift(~Coord(0), shared_size_exponent);
for (num_coordinates_type dim = 0; dim != dimensions; ++dim) {
shared_loc_min[dim] = node->min()[dim] & mask;
}
// If Coord move throws, we're in trouble, because we're moving
// an array of them so some of node's coords could be overwritten
// already and we have no reliable way to restore them without
// nothrow move. This is why we require nothrow Coord move.
//
// Nevertheless do this inside the try/catch so we at least
// don't leak memory if it throws.
node->set_min(std::move(shared_loc_min));
}
catch(...) {
intermediate_nodes->~sub_nodes_type();
node_allocator().deallocate(intermediate_nodes, 1);
throw;
}
// continue moving node's contents to its new location
// nothrow
new_location_for_node_original_contents->set_sub_nodes(node->sub_nodes());
new_location_for_node_original_contents->set_leaf(node->move_leaf());
if(sub_nodes_type* original_sub_nodes = new_location_for_node_original_contents->sub_nodes()) {
for (node_type& sub_node : *original_sub_nodes) {
sub_node.set_parent(new_location_for_node_original_contents);
}
}
node->set_size_exponent_in_each_dimension(shared_size_exponent);
node->set_leaf();
node->set_sub_nodes(intermediate_nodes);
node->set_stable_node_reference_keeper();
//node->parent remains the same
//node->monoid remains the same (it will be updated later as one of the parents)
// nothrow
node_to_initialize = new_leaf_ptr_node;
//LOG << "Type 2 " << std::hex << size_t(node_to_initialize) << std::dec << "\n";
}
assert(!node_to_initialize->sub_nodes());
node_to_initialize->set_min(std::move(leaf_loc));
// hopefully nothrow
node_to_initialize->set_leaf(std::move(new_leaf));
// hopefully nothrow
node_to_initialize->initialize_monoid_(std::move(leaf_monoid));
return *node_to_initialize;
}
template<num_coordinates_type Dims, typename Coord, typename T, typename Traits>
bool pow2_radix_patricia_trie_node<Dims, Coord, T, Traits>::erase(loc_type leaf_loc) {
node_type& node = find_node(leaf_loc);
if (node.points_to_leaf()) {
node.update_monoid(monoid_type());
node.set_leaf();
// TODO shorten tree where appropriate
// (Could keep immediate-children-counts explicitly in nodes
// to make that a little faster; probably fine either way.)
delete_empty_leaves_(node);
// Now node (which might be *this) might no longer exist.
return true;
}
else { return false; }
}
template<num_coordinates_type Dims, typename Coord, typename T, typename Traits>
bool pow2_radix_patricia_trie_node<Dims, Coord, T, Traits>::erase_if_empty() {
node_type& node_that_exists = delete_empty_leaves_(*this);
return (&node_that_exists != this);
}
template<num_coordinates_type Dims, typename Coord, typename T, typename Traits>
pow2_radix_patricia_trie_node<Dims, Coord, T, Traits>&
pow2_radix_patricia_trie_node<Dims, Coord, T, Traits>::delete_empty_leaves_(node_type& node1) {
node_type* node = &node1;
while(true) {
sub_nodes_type* siblings = node->siblings();
if(!siblings) { break; }
bool siblings_all_empty = true;
for(node_type& sibling : *siblings) {
if(!sibling.is_empty()) { siblings_all_empty = false; }
}
if(siblings_all_empty) {
node_type* parent = node->parent();
for(node_type& sibling : *siblings) {
if(auto sibling_keeper = sibling.stable_node_reference_keeper()) {
if(auto parent_keeper = parent->stable_node_reference_keeper()) {
sibling_keeper->look_at_this_one_instead_ = parent_keeper;
sibling_keeper->here_ = nullptr;
}
else {
sibling_keeper->here_ = parent;
parent->set_stable_node_reference_keeper(sibling_keeper);
}
}
}
parent->delete_sub_nodes_();
node = parent;
}
else {
break;
}
}
return *node;
}
#include "../world.hpp"
template class pow2_radix_patricia_trie_node<3,
tile_coordinate,
the_decomposition_of_the_world_into_blocks_impl::region_specification,
the_decomposition_of_the_world_into_blocks_impl::worldblock_trie_traits>;
#include "../tests/patricia_trie_tests.hpp"
template class pow2_radix_patricia_trie_node<3,
patricia_trie_testing::coord,
std::unique_ptr<patricia_trie_testing::block>,
patricia_trie_testing::trie_traits>;
|
simplify insert()
|
patricia_trie: simplify insert()
|
C++
|
agpl-3.0
|
idupree/Lasercake,Lasercake/Lasercake,elidupree/Lasercake,elidupree/Lasercake,elidupree/Lasercake,elidupree/Lasercake,Lasercake/Lasercake,idupree/Lasercake,elidupree/Lasercake,idupree/Lasercake,idupree/Lasercake,idupree/Lasercake,elidupree/Lasercake,elidupree/Lasercake,Lasercake/Lasercake,idupree/Lasercake,idupree/Lasercake,Lasercake/Lasercake,Lasercake/Lasercake
|
94067584aba85c85c27e0fdd95b6070c1ae570d5
|
tests/GenericConversionTest.cpp
|
tests/GenericConversionTest.cpp
|
/*
This file is part of the Util library.
Copyright (C) 2013 Benjamin Eikel <[email protected]>
This library is subject to the terms of the Mozilla Public License, v. 2.0.
You should have received a copy of the MPL along with this library; see the
file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "GenericConversionTest.h"
#include <cppunit/TestAssert.h>
#include <Util/Generic.h>
#include <Util/GenericConversion.h>
#include <Util/StringIdentifier.h>
#include <Util/StringUtils.h>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
CPPUNIT_TEST_SUITE_REGISTRATION(GenericConversionTest);
typedef std::vector<Util::Generic> GenericArray;
typedef std::unordered_map<Util::StringIdentifier, Util::Generic> GenericMap;
static bool checkGenericArraysEqual(const GenericArray & expected, const GenericArray & actual);
static bool checkGenericMapsEqual(const GenericMap & expected, const GenericMap & actual);
static bool checkGenericsEqual(const Util::Generic & expected, const Util::Generic & actual) {
CPPUNIT_ASSERT(expected.valid());
CPPUNIT_ASSERT(actual.valid());
if(expected.contains<bool>()) {
CPPUNIT_ASSERT(actual.contains<bool>());
CPPUNIT_ASSERT_EQUAL(expected.ref<bool>(), actual.ref<bool>());
return true;
} else if(expected.contains<float>()) {
CPPUNIT_ASSERT(actual.contains<float>());
CPPUNIT_ASSERT_EQUAL(expected.ref<float>(), actual.ref<float>());
return true;
} else if(expected.contains<std::string>()) {
CPPUNIT_ASSERT(actual.contains<std::string>());
CPPUNIT_ASSERT_EQUAL(expected.ref<std::string>(), actual.ref<std::string>());
return true;
} else if(expected.contains<GenericArray>()) {
CPPUNIT_ASSERT(actual.contains<GenericArray>());
return checkGenericArraysEqual(expected.ref<GenericArray>(), actual.ref<GenericArray>());
} else if(expected.contains<GenericMap>()) {
CPPUNIT_ASSERT(actual.contains<GenericMap>());
return checkGenericMapsEqual(expected.ref<GenericMap>(), actual.ref<GenericMap>());
}
return false;
}
static bool checkGenericArraysEqual(const GenericArray & expected, const GenericArray & actual) {
CPPUNIT_ASSERT_EQUAL(expected.size(), actual.size());
auto actualIt = actual.begin();
return std::equal(expected.cbegin(), expected.cend(), actual.cbegin(), &checkGenericsEqual);
}
static bool checkGenericMapsEqual(const GenericMap & expected, const GenericMap & actual) {
CPPUNIT_ASSERT_EQUAL(expected.size(), actual.size());
for(auto expectedElement : expected) {
CPPUNIT_ASSERT(actual.count(expectedElement.first) != 0);
if(!checkGenericsEqual(expectedElement.second, actual.at(expectedElement.first))) {
return false;
}
}
return true;
}
template<typename WriteValueType, typename ReadValueType>
static void testGenericSerialization(const WriteValueType writeValue,
const std::string & expectedSerialization,
const ReadValueType readValue) {
const Util::Generic genericExport(writeValue);
std::stringstream tempStream;
Util::GenericConversion::toJSON(genericExport, tempStream);
const std::string actualSerialization = tempStream.str();
CPPUNIT_ASSERT_EQUAL(expectedSerialization, actualSerialization);
const Util::Generic genericImport = Util::GenericConversion::fromJSON(tempStream);
CPPUNIT_ASSERT_EQUAL(readValue, genericImport.ref<ReadValueType>());
}
static void testGenericStringSerialization(const std::string & str) {
testGenericSerialization<std::string, std::string>(str,
std::string("\"") + Util::StringUtils::escape(str) + std::string("\""),
str);
}
void GenericConversionTest::testBasicSerialization() {
testGenericSerialization<bool, bool>(true, "true", true);
testGenericSerialization<bool, bool>(false, "false", false);
testGenericSerialization<double, float>(25.6789, "25.6789", 25.6789f);
testGenericSerialization<float, float>(12.345f, "12.345", 12.345f);
testGenericSerialization<long, float>(-234978l, "-234978", -234978.0f);
testGenericSerialization<unsigned long, float>(413214ul, "413214", 413214.0f);
testGenericSerialization<int, float>(-234978, "-234978", -234978.0f);
testGenericSerialization<unsigned int, float>(413214u, "413214", 413214.0f);
testGenericSerialization<short, float>(-1200, "-1200", -1200.0f);
testGenericSerialization<unsigned short, float>(837u, "837", 837.0f);
testGenericSerialization<char, float>(-128, "-128", -128.0f);
testGenericSerialization<char, float>(0, "0", 0.0f);
testGenericSerialization<char, float>(127, "127", 127.0f);
testGenericSerialization<unsigned char, float>(0u, "0", 0.0f);
testGenericSerialization<unsigned char, float>(127u, "127", 127.0f);
testGenericSerialization<unsigned char, float>(255u, "255", 255.0f);
testGenericStringSerialization("Hello, world!");
testGenericStringSerialization("abc");
testGenericStringSerialization("ABC");
testGenericStringSerialization("123");
testGenericStringSerialization("x");
testGenericStringSerialization("");
testGenericStringSerialization("\"\"");
testGenericStringSerialization("''");
testGenericStringSerialization("'\"");
testGenericStringSerialization("[1, 2, 3]");
testGenericStringSerialization("a\nb\nc");
}
void GenericConversionTest::testArraySerialization() {
GenericArray array;
array.emplace_back(true);
array.emplace_back(std::string("[1, 2, \"xyz\"]"));
array.emplace_back(12345.6f);
array.emplace_back(false);
GenericArray innerArray;
innerArray.emplace_back(std::string("one"));
innerArray.emplace_back(std::string("two"));
innerArray.emplace_back(std::string("three"));
array.emplace_back(innerArray);
const Util::Generic genericArray(array);
std::stringstream tempStream;
Util::GenericConversion::toJSON(genericArray, tempStream);
const std::string serialization = tempStream.str();
const Util::Generic importedGenericArray = Util::GenericConversion::fromJSON(tempStream);
CPPUNIT_ASSERT(checkGenericsEqual(genericArray, importedGenericArray));
}
void GenericConversionTest::testMapSerialization() {
GenericMap map;
map.emplace(Util::StringIdentifier("firstBool"), Util::Generic(true));
map.emplace(Util::StringIdentifier("secondBool"), Util::Generic(false));
map.emplace(Util::StringIdentifier("first string"), Util::Generic(std::string("[1, 2, \"xyz\"]")));
map.emplace(Util::StringIdentifier("second string"), Util::Generic(std::string("hello")));
map.emplace(Util::StringIdentifier("first number"), Util::Generic(12345.6f));
map.emplace(Util::StringIdentifier("second number"), Util::Generic(-4321.1f));
GenericMap innerMap;
innerMap.emplace(Util::StringIdentifier("a"), Util::Generic(std::string("one")));
innerMap.emplace(Util::StringIdentifier("b"), Util::Generic(std::string("two")));
innerMap.emplace(Util::StringIdentifier("c"), Util::Generic(std::string("three")));
map.emplace(Util::StringIdentifier("innerMap"), Util::Generic(innerMap));
const Util::Generic genericMap(map);
std::stringstream tempStream;
Util::GenericConversion::toJSON(genericMap, tempStream);
const std::string serialization = tempStream.str();
const Util::Generic importedGenericArray = Util::GenericConversion::fromJSON(tempStream);
CPPUNIT_ASSERT(checkGenericsEqual(genericMap, importedGenericArray));
}
|
/*
This file is part of the Util library.
Copyright (C) 2013 Benjamin Eikel <[email protected]>
This library is subject to the terms of the Mozilla Public License, v. 2.0.
You should have received a copy of the MPL along with this library; see the
file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/.
*/
#include "GenericConversionTest.h"
#include <cppunit/TestAssert.h>
#include <Util/Generic.h>
#include <Util/GenericConversion.h>
#include <Util/StringIdentifier.h>
#include <Util/StringUtils.h>
#include <sstream>
#include <string>
#include <unordered_map>
#include <vector>
CPPUNIT_TEST_SUITE_REGISTRATION(GenericConversionTest);
typedef std::vector<Util::Generic> GenericArray;
typedef std::unordered_map<Util::StringIdentifier, Util::Generic> GenericMap;
static bool checkGenericArraysEqual(const GenericArray & expected, const GenericArray & actual);
static bool checkGenericMapsEqual(const GenericMap & expected, const GenericMap & actual);
static bool checkGenericsEqual(const Util::Generic & expected, const Util::Generic & actual) {
CPPUNIT_ASSERT(expected.valid());
CPPUNIT_ASSERT(actual.valid());
if(expected.contains<bool>()) {
CPPUNIT_ASSERT(actual.contains<bool>());
CPPUNIT_ASSERT_EQUAL(expected.ref<bool>(), actual.ref<bool>());
return true;
} else if(expected.contains<float>()) {
CPPUNIT_ASSERT(actual.contains<float>());
CPPUNIT_ASSERT_EQUAL(expected.ref<float>(), actual.ref<float>());
return true;
} else if(expected.contains<std::string>()) {
CPPUNIT_ASSERT(actual.contains<std::string>());
CPPUNIT_ASSERT_EQUAL(expected.ref<std::string>(), actual.ref<std::string>());
return true;
} else if(expected.contains<GenericArray>()) {
CPPUNIT_ASSERT(actual.contains<GenericArray>());
return checkGenericArraysEqual(expected.ref<GenericArray>(), actual.ref<GenericArray>());
} else if(expected.contains<GenericMap>()) {
CPPUNIT_ASSERT(actual.contains<GenericMap>());
return checkGenericMapsEqual(expected.ref<GenericMap>(), actual.ref<GenericMap>());
}
return false;
}
static bool checkGenericArraysEqual(const GenericArray & expected, const GenericArray & actual) {
CPPUNIT_ASSERT_EQUAL(expected.size(), actual.size());
return std::equal(expected.cbegin(), expected.cend(), actual.cbegin(), &checkGenericsEqual);
}
static bool checkGenericMapsEqual(const GenericMap & expected, const GenericMap & actual) {
CPPUNIT_ASSERT_EQUAL(expected.size(), actual.size());
for(auto expectedElement : expected) {
CPPUNIT_ASSERT(actual.count(expectedElement.first) != 0);
if(!checkGenericsEqual(expectedElement.second, actual.at(expectedElement.first))) {
return false;
}
}
return true;
}
template<typename WriteValueType, typename ReadValueType>
static void testGenericSerialization(const WriteValueType writeValue,
const std::string & expectedSerialization,
const ReadValueType readValue) {
const Util::Generic genericExport(writeValue);
std::stringstream tempStream;
Util::GenericConversion::toJSON(genericExport, tempStream);
const std::string actualSerialization = tempStream.str();
CPPUNIT_ASSERT_EQUAL(expectedSerialization, actualSerialization);
const Util::Generic genericImport = Util::GenericConversion::fromJSON(tempStream);
CPPUNIT_ASSERT_EQUAL(readValue, genericImport.ref<ReadValueType>());
}
static void testGenericStringSerialization(const std::string & str) {
testGenericSerialization<std::string, std::string>(str,
std::string("\"") + Util::StringUtils::escape(str) + std::string("\""),
str);
}
void GenericConversionTest::testBasicSerialization() {
testGenericSerialization<bool, bool>(true, "true", true);
testGenericSerialization<bool, bool>(false, "false", false);
testGenericSerialization<double, float>(25.6789, "25.6789", 25.6789f);
testGenericSerialization<float, float>(12.345f, "12.345", 12.345f);
testGenericSerialization<long, float>(-234978l, "-234978", -234978.0f);
testGenericSerialization<unsigned long, float>(413214ul, "413214", 413214.0f);
testGenericSerialization<int, float>(-234978, "-234978", -234978.0f);
testGenericSerialization<unsigned int, float>(413214u, "413214", 413214.0f);
testGenericSerialization<short, float>(-1200, "-1200", -1200.0f);
testGenericSerialization<unsigned short, float>(837u, "837", 837.0f);
testGenericSerialization<char, float>(-128, "-128", -128.0f);
testGenericSerialization<char, float>(0, "0", 0.0f);
testGenericSerialization<char, float>(127, "127", 127.0f);
testGenericSerialization<unsigned char, float>(0u, "0", 0.0f);
testGenericSerialization<unsigned char, float>(127u, "127", 127.0f);
testGenericSerialization<unsigned char, float>(255u, "255", 255.0f);
testGenericStringSerialization("Hello, world!");
testGenericStringSerialization("abc");
testGenericStringSerialization("ABC");
testGenericStringSerialization("123");
testGenericStringSerialization("x");
testGenericStringSerialization("");
testGenericStringSerialization("\"\"");
testGenericStringSerialization("''");
testGenericStringSerialization("'\"");
testGenericStringSerialization("[1, 2, 3]");
testGenericStringSerialization("a\nb\nc");
}
void GenericConversionTest::testArraySerialization() {
GenericArray array;
array.emplace_back(true);
array.emplace_back(std::string("[1, 2, \"xyz\"]"));
array.emplace_back(12345.6f);
array.emplace_back(false);
GenericArray innerArray;
innerArray.emplace_back(std::string("one"));
innerArray.emplace_back(std::string("two"));
innerArray.emplace_back(std::string("three"));
array.emplace_back(innerArray);
const Util::Generic genericArray(array);
std::stringstream tempStream;
Util::GenericConversion::toJSON(genericArray, tempStream);
const std::string serialization = tempStream.str();
const Util::Generic importedGenericArray = Util::GenericConversion::fromJSON(tempStream);
CPPUNIT_ASSERT(checkGenericsEqual(genericArray, importedGenericArray));
}
void GenericConversionTest::testMapSerialization() {
GenericMap map;
map.emplace(Util::StringIdentifier("firstBool"), Util::Generic(true));
map.emplace(Util::StringIdentifier("secondBool"), Util::Generic(false));
map.emplace(Util::StringIdentifier("first string"), Util::Generic(std::string("[1, 2, \"xyz\"]")));
map.emplace(Util::StringIdentifier("second string"), Util::Generic(std::string("hello")));
map.emplace(Util::StringIdentifier("first number"), Util::Generic(12345.6f));
map.emplace(Util::StringIdentifier("second number"), Util::Generic(-4321.1f));
GenericMap innerMap;
innerMap.emplace(Util::StringIdentifier("a"), Util::Generic(std::string("one")));
innerMap.emplace(Util::StringIdentifier("b"), Util::Generic(std::string("two")));
innerMap.emplace(Util::StringIdentifier("c"), Util::Generic(std::string("three")));
map.emplace(Util::StringIdentifier("innerMap"), Util::Generic(innerMap));
const Util::Generic genericMap(map);
std::stringstream tempStream;
Util::GenericConversion::toJSON(genericMap, tempStream);
const std::string serialization = tempStream.str();
const Util::Generic importedGenericArray = Util::GenericConversion::fromJSON(tempStream);
CPPUNIT_ASSERT(checkGenericsEqual(genericMap, importedGenericArray));
}
|
Remove unused iterator
|
Remove unused iterator
|
C++
|
mpl-2.0
|
PADrend/Util
|
97c490d3698a08e3e7ba1cf001033ea263dbdd13
|
093.cpp
|
093.cpp
|
/*
This solution draws ideas from how genetic algorithms can be used to
determine combinations of operators and values to give some selected number.
We consider arithmetic operations in Polish notation. We have a set of
operators, A = {'.', '+', '-', '*', '/'} where '.' refers to a unary
operator that maps a number to itself.
First we start with a tuple ('+') corresponding to the outer most operator.
We expand this tuple by selecting the possible pairs of second outer most
operators, i.e. we expand (+) to one of
(+(.)(+)) (+(.)(-)) (+(.)(*)) (+(.)(/)) (+(.)(.))
(+(+)(+)) (+(+)(-)) (+(+)(*)) (+(+)(/)) (+(+)(.))
(+(-)(+)) (+(-)(-)) (+(-)(*)) (+(-)(/)) (+(-)(.))
(+(*)(+)) (+(*)(-)) (+(*)(*)) (+(*)(/)) (+(*)(.))
(+(/)(+)) (+(/)(-)) (+(/)(*)) (+(/)(/)) (+(/)(.))
Next, we move on to expand the sub operators, in this case the last two
operators. For (+(-)(*)), we expand (-) and (*), giving results such as
(+(-(.)(.)) (*(.)(.)))
A tuple is said to be fully expanded when it cannot be expanded anymore,
i.e. when the innermost operators at each depth is '.'. Examples are
(+(.)(.))
(+(+(.)(.)))
Note we need expansion with "length" 4. These are full expansions with 4 '.',
for which we can slot a, b, c, d into.
With our expressions table, we try out all combinations of a < b < c < d.
For each combination, we evaluate the expressions in the expressions table
with values that are permutations of (a, b, c, d) and collect the integer
results (of course catching divide by zero errors and discarding such
cases).
Finally, we pick the combination that gives the most consecutive first
positive integers.
*/
#include <utility>
#include <vector>
#include <string>
#include <iostream>
#include <set>
#include <algorithm>
#include <cmath>
#include "iter_util.h"
std::vector<std::string> ops = { ".", "+", "-", "/", "*" };
std::vector<std::string> get_exprs(std::string op, int length)
{
std::vector<std::string> exprs;
if (op == ".")
{
if (length == 1)
exprs.emplace_back("(.)");
else
return exprs;
}
if (length < 2)
return exprs;
for (int length_left = 1; length_left < length; length_left++)
{
int length_right = length - length_left;
std::vector<std::string> exprs_left, exprs_right;
for (std::string &_op : ops)
{
for (std::string &expr : get_exprs(_op, length_left))
exprs_left.emplace_back(expr);
for (std::string &expr : get_exprs(_op, length_right))
exprs_right.emplace_back(expr);
}
for (std::string &expr_left : exprs_left)
for (std::string &expr_right : exprs_right)
exprs.emplace_back("(" + op + expr_left + expr_right + ")");
}
}
std::string substitute(std::string expr, std::vector<int> &digits)
{
std::string _expr = expr;
for (int &d : digits)
_expr.replace(_expr.find('.'), 1, 1, (char)(d + '0'));
return _expr;
}
double evaluate(std::string expr)
{
if (expr[1] - '0' >= 0 && expr[1] - '0' <= 9)
return expr[1] - '0';
std::string op(1, expr[1]);
std::string expr_left;
std::string expr_right;
int count = 1;
int start = 2;
int end = start + 1;
while (count > 0)
{
if (expr[end] == '(') count++;
else if (expr[end] == ')') count--;
end++;
}
expr_left = expr.substr(start, end - start);
count = 1;
start = end++;;
while (count > 0)
{
if (expr[end] == '(') count++;
else if (expr[end] == ')') count--;
end++;
}
expr_right = expr.substr(start, end - start);
double val_left = evaluate(expr_left);
double val_right = evaluate(expr_right);
if (op == "+") return val_left + val_right;
if (op == "-") return val_left - val_right;
if (op == "*") return val_left * val_right;
if (op == "/") return val_left / val_right;
return 0;
}
int main()
{
std::vector<std::string> exprs;
std::vector<std::string> _ops = { "+", "-", "/", "*" };
for (std::string &op : _ops)
{
std::vector<std::string> _exprs = get_exprs(op, 4);
exprs.insert(exprs.end(), _exprs.begin(), _exprs.end());
}
std::string digits_best;
int length_best = -1;
std::vector<int> valid_digits = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (std::vector<int> &digits : util::get_combinations(valid_digits.begin(), valid_digits.end(), 4))
{
std::set<int> values;
do
{
for (std::string &expr : exprs)
{
std::string expr_sub = substitute(expr, digits);
double value = evaluate(expr_sub);
if (!std::isinf(value) && std::fmod(value, 1) == 0)
values.emplace(value);
}
} while (std::next_permutation(digits.begin(), digits.end()));
int length = 0;
for (; values.find(length + 1) != values.end(); length++);
if (length > length_best)
{
digits_best = "";
for (int &d : digits)
digits_best += d + '0';
length_best = length;
}
}
std::cout << digits_best;
}
|
/*
This solution draws ideas from how genetic algorithms can be used to
determine combinations of operators and values to give some selected number.
We consider arithmetic operations in Polish notation. We have a set of
operators, A = {'.', '+', '-', '*', '/'} where '.' refers to a unary
operator that maps a number to itself.
First we start with a tuple ('+') corresponding to the outer most operator.
We expand this tuple by selecting the possible pairs of second outer most
operators, i.e. we expand (+) to one of
(+(.)(+)) (+(.)(-)) (+(.)(*)) (+(.)(/)) (+(.)(.))
(+(+)(+)) (+(+)(-)) (+(+)(*)) (+(+)(/)) (+(+)(.))
(+(-)(+)) (+(-)(-)) (+(-)(*)) (+(-)(/)) (+(-)(.))
(+(*)(+)) (+(*)(-)) (+(*)(*)) (+(*)(/)) (+(*)(.))
(+(/)(+)) (+(/)(-)) (+(/)(*)) (+(/)(/)) (+(/)(.))
Next, we move on to expand the sub operators, in this case the last two
operators. For (+(-)(*)), we expand (-) and (*), giving results such as
(+(-(.)(.)) (*(.)(.)))
A tuple is said to be fully expanded when it cannot be expanded anymore,
i.e. when the innermost operators at each depth is '.'. Examples are
(+(.)(.))
(+(+(.)(.)))
Note we need expansion with "length" 4. These are full expansions with 4 '.',
for which we can slot a, b, c, d into.
With our expressions table, we try out all combinations of a < b < c < d.
For each combination, we evaluate the expressions in the expressions table
with values that are permutations of (a, b, c, d) and collect the integer
results (of course catching divide by zero errors and discarding such
cases).
Finally, we pick the combination that gives the most consecutive first
positive integers.
*/
#include <utility>
#include <vector>
#include <string>
#include <iostream>
#include <set>
#include <algorithm>
#include <cmath>
#include "iter_util.h"
std::vector<std::string> ops = { ".", "+", "-", "/", "*" };
std::vector<std::string> get_exprs(std::string op, int length)
{
std::vector<std::string> exprs;
if (op == ".")
{
if (length == 1)
exprs.emplace_back("(.)");
else
return exprs;
}
if (length < 2)
return exprs;
for (int length_left = 1; length_left < length; length_left++)
{
int length_right = length - length_left;
std::vector<std::string> exprs_left, exprs_right;
for (std::string &_op : ops)
{
for (std::string &expr : get_exprs(_op, length_left))
exprs_left.emplace_back(expr);
for (std::string &expr : get_exprs(_op, length_right))
exprs_right.emplace_back(expr);
}
for (std::string &expr_left : exprs_left)
for (std::string &expr_right : exprs_right)
exprs.emplace_back("(" + op + expr_left + expr_right + ")");
}
}
std::string substitute(std::string expr, std::vector<int> const &digits)
{
std::string _expr = expr;
for (int const &d : digits)
_expr.replace(_expr.find('.'), 1, 1, (char)(d + '0'));
return _expr;
}
double evaluate(std::string expr)
{
if (expr[1] - '0' >= 0 && expr[1] - '0' <= 9)
return expr[1] - '0';
std::string op(1, expr[1]);
std::string expr_left;
std::string expr_right;
int count = 1;
int start = 2;
int end = start + 1;
while (count > 0)
{
if (expr[end] == '(') count++;
else if (expr[end] == ')') count--;
end++;
}
expr_left = expr.substr(start, end - start);
count = 1;
start = end++;;
while (count > 0)
{
if (expr[end] == '(') count++;
else if (expr[end] == ')') count--;
end++;
}
expr_right = expr.substr(start, end - start);
double val_left = evaluate(expr_left);
double val_right = evaluate(expr_right);
if (op == "+") return val_left + val_right;
if (op == "-") return val_left - val_right;
if (op == "*") return val_left * val_right;
if (op == "/") return val_left / val_right;
return 0;
}
int main()
{
std::vector<std::string> exprs;
std::vector<std::string> _ops = { "+", "-", "/", "*" };
for (std::string &op : _ops)
{
std::vector<std::string> _exprs = get_exprs(op, 4);
exprs.insert(exprs.end(), _exprs.begin(), _exprs.end());
}
std::string digits_best;
int length_best = -1;
std::vector<int> valid_digits = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
for (std::vector<int> &digits : util::get_combinations(valid_digits.begin(), valid_digits.end(), 4))
{
std::set<int> values;
do
{
for (std::string &expr : exprs)
{
std::string expr_sub = substitute(expr, digits);
double value = evaluate(expr_sub);
if (!std::isinf(value) && std::fmod(value, 1) == 0)
values.emplace(value);
}
} while (std::next_permutation(digits.begin(), digits.end()));
int length = 0;
for (; values.find(length + 1) != values.end(); length++);
if (length > length_best)
{
digits_best = "";
for (int &d : digits)
digits_best += d + '0';
length_best = length;
}
}
std::cout << digits_best;
}
|
Enforce const correctness.
|
Enforce const correctness.
|
C++
|
mit
|
LeeYiyuan/projecteuler,LeeYiyuan/projecteuler
|
da684a6202ee2fea94fe243c50a5f67ae2d532f5
|
163.cpp
|
163.cpp
|
class Solution {
public:
/**
* @paramn n: An integer
* @return: An integer
*/
int numTrees(int n) {
// write your code here
int f[n+5],i,j;
for (i=0;i<n+1;++i) f[i]=0;
f[0]=1;
f[1]=1;
for (i=2;i<=n;++i){
for (j=0;j<i;++j)
f[i]+= (f[j]*f[i-1-j]);
// cout<<f[i]<<endl;
}
return f[n];
}
};
|
Solve 163 in c++
|
Solve 163 in c++
|
C++
|
mit
|
jonathanxqs/lintcode,jonathanxqs/lintcode
|
|
f77e6a113576e7457bf1559bb74c7aedfa51aaa5
|
chrome/browser/extensions/extension_disabled_ui_browsertest.cc
|
chrome/browser/extensions/extension_disabled_ui_browsertest.cc
|
// Copyright (c) 2012 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 "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_prefs.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/updater/extension_updater.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/global_error/global_error.h"
#include "chrome/browser/ui/global_error/global_error_service.h"
#include "chrome/browser/ui/global_error/global_error_service_factory.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension.h"
#include "content/test/net/url_request_prepackaged_interceptor.h"
#include "net/url_request/url_fetcher.h"
using extensions::Extension;
class ExtensionDisabledGlobalErrorTest : public ExtensionBrowserTest {
protected:
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
ExtensionBrowserTest::SetUpCommandLine(command_line);
command_line->AppendSwitchASCII(switches::kAppsGalleryUpdateURL,
"http://localhost/autoupdate/updates.xml");
}
virtual void SetUpOnMainThread() OVERRIDE {
EXPECT_TRUE(scoped_temp_dir_.CreateUniqueTempDir());
service_ = browser()->profile()->GetExtensionService();
base::FilePath pem_path = test_data_dir_.
AppendASCII("permissions_increase").AppendASCII("permissions.pem");
path_v1_ = PackExtensionWithOptions(
test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v1"),
scoped_temp_dir_.path().AppendASCII("permissions1.crx"),
pem_path,
base::FilePath());
path_v2_ = PackExtensionWithOptions(
test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v2"),
scoped_temp_dir_.path().AppendASCII("permissions2.crx"),
pem_path,
base::FilePath());
path_v3_ = PackExtensionWithOptions(
test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v3"),
scoped_temp_dir_.path().AppendASCII("permissions3.crx"),
pem_path,
base::FilePath());
}
// Returns the ExtensionDisabledGlobalError, if present.
// Caution: currently only supports one error at a time.
GlobalError* GetExtensionDisabledGlobalError() {
return GlobalErrorServiceFactory::GetForProfile(browser()->profile())->
GetGlobalErrorByMenuItemCommandID(IDC_EXTENSION_DISABLED_FIRST);
}
// Install the initial version, which should happen just fine.
const Extension* InstallIncreasingPermissionExtensionV1() {
size_t size_before = service_->extensions()->size();
const Extension* extension = InstallExtension(path_v1_, 1);
if (!extension)
return NULL;
if (service_->extensions()->size() != size_before + 1)
return NULL;
return extension;
}
// Upgrade to a version that wants more permissions. We should disable the
// extension and prompt the user to reenable.
const Extension* UpdateIncreasingPermissionExtension(
const Extension* extension,
const base::FilePath& crx_path,
int expected_change) {
size_t size_before = service_->extensions()->size();
if (UpdateExtension(extension->id(), crx_path, expected_change))
return NULL;
EXPECT_EQ(size_before + expected_change, service_->extensions()->size());
if (service_->disabled_extensions()->size() != 1u)
return NULL;
return *service_->disabled_extensions()->begin();
}
// Helper function to install an extension and upgrade it to a version
// requiring additional permissions. Returns the new disabled Extension.
const Extension* InstallAndUpdateIncreasingPermissionsExtension() {
const Extension* extension = InstallIncreasingPermissionExtensionV1();
extension = UpdateIncreasingPermissionExtension(extension, path_v2_, -1);
return extension;
}
ExtensionService* service_;
base::ScopedTempDir scoped_temp_dir_;
base::FilePath path_v1_;
base::FilePath path_v2_;
base::FilePath path_v3_;
};
// Tests the process of updating an extension to one that requires higher
// permissions, and accepting the permissions.
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, AcceptPermissions) {
const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();
ASSERT_TRUE(extension);
ASSERT_TRUE(GetExtensionDisabledGlobalError());
const size_t size_before = service_->extensions()->size();
service_->GrantPermissionsAndEnableExtension(extension);
EXPECT_EQ(size_before + 1, service_->extensions()->size());
EXPECT_EQ(0u, service_->disabled_extensions()->size());
ASSERT_FALSE(GetExtensionDisabledGlobalError());
}
// Tests uninstalling an extension that was disabled due to higher permissions.
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, Uninstall) {
const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();
ASSERT_TRUE(extension);
ASSERT_TRUE(GetExtensionDisabledGlobalError());
const size_t size_before = service_->extensions()->size();
UninstallExtension(extension->id());
EXPECT_EQ(size_before, service_->extensions()->size());
EXPECT_EQ(0u, service_->disabled_extensions()->size());
ASSERT_FALSE(GetExtensionDisabledGlobalError());
}
// Tests that no error appears if the user disabled the extension.
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, UserDisabled) {
const Extension* extension = InstallIncreasingPermissionExtensionV1();
DisableExtension(extension->id());
extension = UpdateIncreasingPermissionExtension(extension, path_v2_, 0);
ASSERT_FALSE(GetExtensionDisabledGlobalError());
}
// Test that no error appears if the disable reason is unknown
// (but probably was by the user).
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,
UnknownReasonSamePermissions) {
const Extension* extension = InstallIncreasingPermissionExtensionV1();
DisableExtension(extension->id());
// Clear disable reason to simulate legacy disables.
service_->extension_prefs()->ClearDisableReasons(extension->id());
// Upgrade to version 2. Infer from version 1 having the same permissions
// granted by the user that it was disabled by the user.
extension = UpdateIncreasingPermissionExtension(extension, path_v2_, 0);
ASSERT_TRUE(extension);
ASSERT_FALSE(GetExtensionDisabledGlobalError());
}
// Test that an error appears if the disable reason is unknown
// (but probably was for increased permissions).
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,
UnknownReasonHigherPermissions) {
const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();
// Clear disable reason to simulate legacy disables.
service_->extension_prefs()->ClearDisableReasons(extension->id());
// We now have version 2 but only accepted permissions for version 1.
GlobalError* error = GetExtensionDisabledGlobalError();
ASSERT_TRUE(error);
// Also, remove the upgrade error for version 2.
GlobalErrorServiceFactory::GetForProfile(browser()->profile())->
RemoveGlobalError(error);
delete error;
// Upgrade to version 3, with even higher permissions. Infer from
// version 2 having higher-than-granted permissions that it was disabled
// for permissions increase.
extension = UpdateIncreasingPermissionExtension(extension, path_v3_, 0);
ASSERT_TRUE(extension);
ASSERT_TRUE(GetExtensionDisabledGlobalError());
}
// Test that an error appears if the extension gets disabled because a
// version with higher permissions was installed by sync.
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,
HigherPermissionsFromSync) {
// Get data for extension v2 (disabled) into sync.
const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();
std::string extension_id = extension->id();
// service_->GrantPermissionsAndEnableExtension(extension, false);
extensions::ExtensionSyncData sync_data =
service_->GetExtensionSyncData(*extension);
UninstallExtension(extension_id);
extension = NULL;
// Install extension v1.
InstallIncreasingPermissionExtensionV1();
// Note: This interceptor gets requests on the IO thread.
content::URLLocalHostRequestPrepackagedInterceptor interceptor;
net::URLFetcher::SetEnableInterceptionForTests(true);
interceptor.SetResponseIgnoreQuery(
GURL("http://localhost/autoupdate/updates.xml"),
test_data_dir_.AppendASCII("permissions_increase")
.AppendASCII("updates.xml"));
interceptor.SetResponseIgnoreQuery(
GURL("http://localhost/autoupdate/v2.crx"),
scoped_temp_dir_.path().AppendASCII("permissions2.crx"));
extensions::ExtensionUpdater::CheckParams params;
params.check_blacklist = false;
service_->updater()->set_default_check_params(params);
// Sync is replacing an older version, so it pends.
EXPECT_FALSE(service_->ProcessExtensionSyncData(sync_data));
WaitForExtensionInstall();
extension = service_->GetExtensionById(extension_id, true);
ASSERT_TRUE(extension);
EXPECT_EQ("2", extension->VersionString());
EXPECT_EQ(1u, service_->disabled_extensions()->size());
EXPECT_EQ(Extension::DISABLE_PERMISSIONS_INCREASE,
service_->extension_prefs()->GetDisableReasons(extension_id));
EXPECT_TRUE(GetExtensionDisabledGlobalError());
}
|
// Copyright (c) 2012 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 "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "chrome/app/chrome_command_ids.h"
#include "chrome/browser/extensions/extension_browsertest.h"
#include "chrome/browser/extensions/extension_prefs.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/updater/extension_updater.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/global_error/global_error.h"
#include "chrome/browser/ui/global_error/global_error_service.h"
#include "chrome/browser/ui/global_error/global_error_service_factory.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension.h"
#include "content/test/net/url_request_prepackaged_interceptor.h"
#include "net/url_request/url_fetcher.h"
using extensions::Extension;
class ExtensionDisabledGlobalErrorTest : public ExtensionBrowserTest {
protected:
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
ExtensionBrowserTest::SetUpCommandLine(command_line);
command_line->AppendSwitchASCII(switches::kAppsGalleryUpdateURL,
"http://localhost/autoupdate/updates.xml");
}
virtual void SetUpOnMainThread() OVERRIDE {
EXPECT_TRUE(scoped_temp_dir_.CreateUniqueTempDir());
service_ = browser()->profile()->GetExtensionService();
base::FilePath pem_path = test_data_dir_.
AppendASCII("permissions_increase").AppendASCII("permissions.pem");
path_v1_ = PackExtensionWithOptions(
test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v1"),
scoped_temp_dir_.path().AppendASCII("permissions1.crx"),
pem_path,
base::FilePath());
path_v2_ = PackExtensionWithOptions(
test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v2"),
scoped_temp_dir_.path().AppendASCII("permissions2.crx"),
pem_path,
base::FilePath());
path_v3_ = PackExtensionWithOptions(
test_data_dir_.AppendASCII("permissions_increase").AppendASCII("v3"),
scoped_temp_dir_.path().AppendASCII("permissions3.crx"),
pem_path,
base::FilePath());
}
// Returns the ExtensionDisabledGlobalError, if present.
// Caution: currently only supports one error at a time.
GlobalError* GetExtensionDisabledGlobalError() {
return GlobalErrorServiceFactory::GetForProfile(browser()->profile())->
GetGlobalErrorByMenuItemCommandID(IDC_EXTENSION_DISABLED_FIRST);
}
// Install the initial version, which should happen just fine.
const Extension* InstallIncreasingPermissionExtensionV1() {
size_t size_before = service_->extensions()->size();
const Extension* extension = InstallExtension(path_v1_, 1);
if (!extension)
return NULL;
if (service_->extensions()->size() != size_before + 1)
return NULL;
return extension;
}
// Upgrade to a version that wants more permissions. We should disable the
// extension and prompt the user to reenable.
const Extension* UpdateIncreasingPermissionExtension(
const Extension* extension,
const base::FilePath& crx_path,
int expected_change) {
size_t size_before = service_->extensions()->size();
if (UpdateExtension(extension->id(), crx_path, expected_change))
return NULL;
EXPECT_EQ(size_before + expected_change, service_->extensions()->size());
if (service_->disabled_extensions()->size() != 1u)
return NULL;
return *service_->disabled_extensions()->begin();
}
// Helper function to install an extension and upgrade it to a version
// requiring additional permissions. Returns the new disabled Extension.
const Extension* InstallAndUpdateIncreasingPermissionsExtension() {
const Extension* extension = InstallIncreasingPermissionExtensionV1();
extension = UpdateIncreasingPermissionExtension(extension, path_v2_, -1);
return extension;
}
ExtensionService* service_;
base::ScopedTempDir scoped_temp_dir_;
base::FilePath path_v1_;
base::FilePath path_v2_;
base::FilePath path_v3_;
};
// Tests the process of updating an extension to one that requires higher
// permissions, and accepting the permissions.
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, AcceptPermissions) {
const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();
ASSERT_TRUE(extension);
ASSERT_TRUE(GetExtensionDisabledGlobalError());
const size_t size_before = service_->extensions()->size();
service_->GrantPermissionsAndEnableExtension(extension);
EXPECT_EQ(size_before + 1, service_->extensions()->size());
EXPECT_EQ(0u, service_->disabled_extensions()->size());
ASSERT_FALSE(GetExtensionDisabledGlobalError());
}
// Tests uninstalling an extension that was disabled due to higher permissions.
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, Uninstall) {
const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();
ASSERT_TRUE(extension);
ASSERT_TRUE(GetExtensionDisabledGlobalError());
const size_t size_before = service_->extensions()->size();
UninstallExtension(extension->id());
EXPECT_EQ(size_before, service_->extensions()->size());
EXPECT_EQ(0u, service_->disabled_extensions()->size());
ASSERT_FALSE(GetExtensionDisabledGlobalError());
}
// Tests that no error appears if the user disabled the extension.
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest, UserDisabled) {
const Extension* extension = InstallIncreasingPermissionExtensionV1();
DisableExtension(extension->id());
extension = UpdateIncreasingPermissionExtension(extension, path_v2_, 0);
ASSERT_FALSE(GetExtensionDisabledGlobalError());
}
// Test that no error appears if the disable reason is unknown
// (but probably was by the user).
// Disabled due to http://crbug.com/246431
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,
DISABLED_UnknownReasonSamePermissions) {
const Extension* extension = InstallIncreasingPermissionExtensionV1();
DisableExtension(extension->id());
// Clear disable reason to simulate legacy disables.
service_->extension_prefs()->ClearDisableReasons(extension->id());
// Upgrade to version 2. Infer from version 1 having the same permissions
// granted by the user that it was disabled by the user.
extension = UpdateIncreasingPermissionExtension(extension, path_v2_, 0);
ASSERT_TRUE(extension);
ASSERT_FALSE(GetExtensionDisabledGlobalError());
}
// Test that an error appears if the disable reason is unknown
// (but probably was for increased permissions).
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,
UnknownReasonHigherPermissions) {
const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();
// Clear disable reason to simulate legacy disables.
service_->extension_prefs()->ClearDisableReasons(extension->id());
// We now have version 2 but only accepted permissions for version 1.
GlobalError* error = GetExtensionDisabledGlobalError();
ASSERT_TRUE(error);
// Also, remove the upgrade error for version 2.
GlobalErrorServiceFactory::GetForProfile(browser()->profile())->
RemoveGlobalError(error);
delete error;
// Upgrade to version 3, with even higher permissions. Infer from
// version 2 having higher-than-granted permissions that it was disabled
// for permissions increase.
extension = UpdateIncreasingPermissionExtension(extension, path_v3_, 0);
ASSERT_TRUE(extension);
ASSERT_TRUE(GetExtensionDisabledGlobalError());
}
// Test that an error appears if the extension gets disabled because a
// version with higher permissions was installed by sync.
IN_PROC_BROWSER_TEST_F(ExtensionDisabledGlobalErrorTest,
HigherPermissionsFromSync) {
// Get data for extension v2 (disabled) into sync.
const Extension* extension = InstallAndUpdateIncreasingPermissionsExtension();
std::string extension_id = extension->id();
// service_->GrantPermissionsAndEnableExtension(extension, false);
extensions::ExtensionSyncData sync_data =
service_->GetExtensionSyncData(*extension);
UninstallExtension(extension_id);
extension = NULL;
// Install extension v1.
InstallIncreasingPermissionExtensionV1();
// Note: This interceptor gets requests on the IO thread.
content::URLLocalHostRequestPrepackagedInterceptor interceptor;
net::URLFetcher::SetEnableInterceptionForTests(true);
interceptor.SetResponseIgnoreQuery(
GURL("http://localhost/autoupdate/updates.xml"),
test_data_dir_.AppendASCII("permissions_increase")
.AppendASCII("updates.xml"));
interceptor.SetResponseIgnoreQuery(
GURL("http://localhost/autoupdate/v2.crx"),
scoped_temp_dir_.path().AppendASCII("permissions2.crx"));
extensions::ExtensionUpdater::CheckParams params;
params.check_blacklist = false;
service_->updater()->set_default_check_params(params);
// Sync is replacing an older version, so it pends.
EXPECT_FALSE(service_->ProcessExtensionSyncData(sync_data));
WaitForExtensionInstall();
extension = service_->GetExtensionById(extension_id, true);
ASSERT_TRUE(extension);
EXPECT_EQ("2", extension->VersionString());
EXPECT_EQ(1u, service_->disabled_extensions()->size());
EXPECT_EQ(Extension::DISABLE_PERMISSIONS_INCREASE,
service_->extension_prefs()->GetDisableReasons(extension_id));
EXPECT_TRUE(GetExtensionDisabledGlobalError());
}
|
Disable flaky ExtensionDisabledGlobalErrorTest.UnknownReasonHigherPermissions test.
|
Disable flaky ExtensionDisabledGlobalErrorTest.UnknownReasonHigherPermissions test.
BUG=246431
NOTRY=true
TBR=yoz
Review URL: https://chromiumcodereview.appspot.com/16338002
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@203802 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,ondra-novak/chromium.src,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,anirudhSK/chromium,Just-D/chromium-1,fujunwei/chromium-crosswalk,hujiajie/pa-chromium,Chilledheart/chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,dednal/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,M4sse/chromium.src,anirudhSK/chromium,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,Chilledheart/chromium,anirudhSK/chromium,Jonekee/chromium.src,markYoungH/chromium.src,axinging/chromium-crosswalk,pozdnyakov/chromium-crosswalk,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,hujiajie/pa-chromium,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,Jonekee/chromium.src,jaruba/chromium.src,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,anirudhSK/chromium,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,patrickm/chromium.src,ltilve/chromium,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,patrickm/chromium.src,M4sse/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,ltilve/chromium,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,Jonekee/chromium.src,ltilve/chromium,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,hujiajie/pa-chromium,dushu1203/chromium.src,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,dednal/chromium.src,Fireblend/chromium-crosswalk,M4sse/chromium.src,anirudhSK/chromium,Just-D/chromium-1,jaruba/chromium.src,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,littlstar/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,dushu1203/chromium.src,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,ChromiumWebApps/chromium,dednal/chromium.src,Chilledheart/chromium,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,markYoungH/chromium.src,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,patrickm/chromium.src,Jonekee/chromium.src,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,ChromiumWebApps/chromium,ltilve/chromium,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,Chilledheart/chromium,ltilve/chromium,ltilve/chromium,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,jaruba/chromium.src,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,Just-D/chromium-1,ondra-novak/chromium.src,patrickm/chromium.src,Just-D/chromium-1,Fireblend/chromium-crosswalk,jaruba/chromium.src,littlstar/chromium.src,M4sse/chromium.src,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,dednal/chromium.src,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk,mogoweb/chromium-crosswalk,littlstar/chromium.src,M4sse/chromium.src,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,M4sse/chromium.src,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,hujiajie/pa-chromium,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,dushu1203/chromium.src,ltilve/chromium,Chilledheart/chromium,littlstar/chromium.src,fujunwei/chromium-crosswalk,Just-D/chromium-1,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,littlstar/chromium.src,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,dednal/chromium.src,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,ltilve/chromium,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,anirudhSK/chromium,dednal/chromium.src,chuan9/chromium-crosswalk,patrickm/chromium.src,dushu1203/chromium.src,patrickm/chromium.src,markYoungH/chromium.src,chuan9/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,chuan9/chromium-crosswalk,hujiajie/pa-chromium,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,ondra-novak/chromium.src,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,dednal/chromium.src,fujunwei/chromium-crosswalk,ChromiumWebApps/chromium,krieger-od/nwjs_chromium.src,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,dednal/chromium.src,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,dednal/chromium.src,mogoweb/chromium-crosswalk,Chilledheart/chromium,jaruba/chromium.src,dushu1203/chromium.src,axinging/chromium-crosswalk,ChromiumWebApps/chromium,anirudhSK/chromium,fujunwei/chromium-crosswalk,dushu1203/chromium.src,dushu1203/chromium.src,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,dushu1203/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,patrickm/chromium.src,markYoungH/chromium.src,mogoweb/chromium-crosswalk,jaruba/chromium.src,anirudhSK/chromium,mogoweb/chromium-crosswalk
|
b961d642fd72e80821bf4ef3ca855953c83a5326
|
bench/ClearBench.cpp
|
bench/ClearBench.cpp
|
/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// This benchmark attempts to measure the time to do a fullscreen clear, an axis-aligned partial
// clear, and a clear restricted to an axis-aligned rounded rect. The fullscreen and axis-aligned
// partial clears on the GPU should follow a fast path that maps to backend-specialized clear
// operations, whereas the rounded-rect clear cannot be.
#include "Benchmark.h"
#include "SkCanvas.h"
#include "SkPaint.h"
#include "SkRect.h"
#include "SkRRect.h"
class ClearBench : public Benchmark {
public:
enum ClearType {
kFull_ClearType,
kPartial_ClearType,
kComplex_ClearType
};
ClearBench(ClearType type) : fType(type) {}
protected:
const char* onGetName() override {
switch(fType) {
case kFull_ClearType:
return "Clear-Full";
case kPartial_ClearType:
return "Clear-Partial";
case kComplex_ClearType:
return "Clear-Complex";
}
SkASSERT(false);
return "Unreachable";
}
void onDraw(int loops, SkCanvas* canvas) override {
const SkColor color = SK_ColorBLUE;
const SkRect partialClip = SkRect::MakeLTRB(50, 50, 400, 400);
const SkRRect complexClip = SkRRect::MakeRectXY(partialClip, 15, 15);
// TODO (michaelludwig): Any benefit to changing the clip geometry?
for (int i = 0; i < loops; i++) {
canvas->save();
switch(fType) {
case kPartial_ClearType:
canvas->clipRect(partialClip);
break;
case kComplex_ClearType:
canvas->clipRRect(complexClip);
break;
case kFull_ClearType:
// Don't add any extra clipping, since it defaults to the entire "device"
break;
}
canvas->clear(color);
canvas->restore();
// Loop to prevent batching between ops (which matters for fullscreen clears that just
// overwrite each other and only one thing is executed regardless of the loop count)
canvas->flush();
}
}
private:
ClearType fType;
};
DEF_BENCH( return new ClearBench(ClearBench::kFull_ClearType); )
DEF_BENCH( return new ClearBench(ClearBench::kPartial_ClearType); )
DEF_BENCH( return new ClearBench(ClearBench::kComplex_ClearType); )
|
/*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
// This benchmark attempts to measure the time to do a fullscreen clear, an axis-aligned partial
// clear, and a clear restricted to an axis-aligned rounded rect. The fullscreen and axis-aligned
// partial clears on the GPU should follow a fast path that maps to backend-specialized clear
// operations, whereas the rounded-rect clear cannot be.
#include "Benchmark.h"
#include "SkCanvas.h"
#include "SkPaint.h"
#include "SkRect.h"
#include "SkRRect.h"
class ClearBench : public Benchmark {
public:
enum ClearType {
kFull_ClearType,
kPartial_ClearType,
kComplex_ClearType
};
ClearBench(ClearType type) : fType(type) {}
protected:
const char* onGetName() override {
switch(fType) {
case kFull_ClearType:
return "Clear-Full";
case kPartial_ClearType:
return "Clear-Partial";
case kComplex_ClearType:
return "Clear-Complex";
}
SkASSERT(false);
return "Unreachable";
}
void onDraw(int loops, SkCanvas* canvas) override {
const SkColor color = SK_ColorBLUE;
const SkRect partialClip = SkRect::MakeLTRB(50, 50, 400, 400);
const SkRRect complexClip = SkRRect::MakeRectXY(partialClip, 15, 15);
// TODO (michaelludwig): Any benefit to changing the clip geometry?
for (int i = 0; i < loops; i++) {
canvas->save();
switch(fType) {
case kPartial_ClearType:
canvas->clipRect(partialClip);
break;
case kComplex_ClearType:
canvas->clipRRect(complexClip);
break;
case kFull_ClearType:
// Don't add any extra clipping, since it defaults to the entire "device"
break;
}
canvas->clear(color);
canvas->restore();
}
}
private:
ClearType fType;
};
DEF_BENCH( return new ClearBench(ClearBench::kFull_ClearType); )
DEF_BENCH( return new ClearBench(ClearBench::kPartial_ClearType); )
DEF_BENCH( return new ClearBench(ClearBench::kComplex_ClearType); )
|
Revert "Force flush in clear benchmarks"
|
Revert "Force flush in clear benchmarks"
This reverts commit 75294fe3e8b43505cddcc0bee584f96daa099d99.
Reason for revert: nanobench hangs on Perf-Win10-Clang-NUC6i5SYK-GPU-IntelIris540-x86_64-Release-All
Original change's description:
> Force flush in clear benchmarks
>
> Bug: skia:
> Change-Id: I9d373dbcf78c6fe52f74deb37d8e08595d3a7c28
> Reviewed-on: https://skia-review.googlesource.com/c/184064
> Reviewed-by: Brian Salomon <[email protected]>
> Commit-Queue: Michael Ludwig <[email protected]>
[email protected],[email protected]
Change-Id: I6eba0057bff7399023f6324a79b80b93ff087eb0
No-Presubmit: true
No-Tree-Checks: true
No-Try: true
Bug: skia:
Reviewed-on: https://skia-review.googlesource.com/c/184193
Reviewed-by: Michael Ludwig <[email protected]>
Commit-Queue: Michael Ludwig <[email protected]>
|
C++
|
bsd-3-clause
|
HalCanary/skia-hc,aosp-mirror/platform_external_skia,rubenvb/skia,HalCanary/skia-hc,HalCanary/skia-hc,rubenvb/skia,aosp-mirror/platform_external_skia,rubenvb/skia,HalCanary/skia-hc,HalCanary/skia-hc,aosp-mirror/platform_external_skia,Hikari-no-Tenshi/android_external_skia,Hikari-no-Tenshi/android_external_skia,aosp-mirror/platform_external_skia,google/skia,rubenvb/skia,google/skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,Hikari-no-Tenshi/android_external_skia,aosp-mirror/platform_external_skia,HalCanary/skia-hc,rubenvb/skia,google/skia,rubenvb/skia,aosp-mirror/platform_external_skia,google/skia,HalCanary/skia-hc,aosp-mirror/platform_external_skia,HalCanary/skia-hc,HalCanary/skia-hc,rubenvb/skia,google/skia,google/skia,google/skia,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,rubenvb/skia,aosp-mirror/platform_external_skia,aosp-mirror/platform_external_skia,Hikari-no-Tenshi/android_external_skia,Hikari-no-Tenshi/android_external_skia,rubenvb/skia,Hikari-no-Tenshi/android_external_skia,google/skia,google/skia,google/skia,Hikari-no-Tenshi/android_external_skia
|
0f98c5a0ad3ddfada0b800a38edfa7bf9da710a7
|
chrome/browser/renderer_host/safe_browsing_resource_handler.cc
|
chrome/browser/renderer_host/safe_browsing_resource_handler.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 "chrome/browser/renderer_host/safe_browsing_resource_handler.h"
#include "base/logging.h"
#include "chrome/browser/renderer_host/global_request_id.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
#include "chrome/browser/renderer_host/resource_message_filter.h"
#include "chrome/common/resource_response.h"
#include "net/base/net_errors.h"
#include "net/base/io_buffer.h"
// Maximum time in milliseconds to wait for the safe browsing service to
// verify a URL. After this amount of time the outstanding check will be
// aborted, and the URL will be treated as if it were safe.
static const int kCheckUrlTimeoutMs = 5000;
// TODO(eroman): Downgrade these CHECK()s to DCHECKs once there is more
// unit test coverage.
SafeBrowsingResourceHandler::SafeBrowsingResourceHandler(
ResourceHandler* handler,
int render_process_host_id,
int render_view_id,
ResourceType::Type resource_type,
SafeBrowsingService* safe_browsing,
ResourceDispatcherHost* resource_dispatcher_host)
: state_(STATE_NONE),
defer_state_(DEFERRED_NONE),
deferred_request_id_(-1),
next_handler_(handler),
render_process_host_id_(render_process_host_id),
render_view_id_(render_view_id),
safe_browsing_(safe_browsing),
rdh_(resource_dispatcher_host),
resource_type_(resource_type) {
}
SafeBrowsingResourceHandler::~SafeBrowsingResourceHandler() {
}
bool SafeBrowsingResourceHandler::OnUploadProgress(int request_id,
uint64 position,
uint64 size) {
return next_handler_->OnUploadProgress(request_id, position, size);
}
bool SafeBrowsingResourceHandler::OnRequestRedirected(
int request_id,
const GURL& new_url,
ResourceResponse* response,
bool* defer) {
CHECK(state_ == STATE_NONE);
CHECK(defer_state_ == DEFERRED_NONE);
// Save the redirect urls for possible malware detail reporting later.
redirect_urls_.push_back(new_url);
// We need to check the new URL before following the redirect.
if (CheckUrl(new_url)) {
return next_handler_->OnRequestRedirected(
request_id, new_url, response, defer);
}
// If the URL couldn't be verified synchronously, defer following the
// redirect until the SafeBrowsing check is complete. Store the redirect
// context so we can pass it on to other handlers once we have completed
// our check.
defer_state_ = DEFERRED_REDIRECT;
deferred_request_id_ = request_id;
deferred_url_ = new_url;
deferred_redirect_response_ = response;
*defer = true;
return true;
}
bool SafeBrowsingResourceHandler::OnResponseStarted(
int request_id, ResourceResponse* response) {
CHECK(state_ == STATE_NONE);
CHECK(defer_state_ == DEFERRED_NONE);
return next_handler_->OnResponseStarted(request_id, response);
}
void SafeBrowsingResourceHandler::OnCheckUrlTimeout() {
CHECK(state_ == STATE_CHECKING_URL);
CHECK(defer_state_ != DEFERRED_NONE);
safe_browsing_->CancelCheck(this);
OnBrowseUrlCheckResult(deferred_url_, SafeBrowsingService::URL_SAFE);
}
bool SafeBrowsingResourceHandler::OnWillStart(int request_id,
const GURL& url,
bool* defer) {
// We need to check the new URL before starting the request.
if (CheckUrl(url))
return next_handler_->OnWillStart(request_id, url, defer);
// If the URL couldn't be verified synchronously, defer starting the
// request until the check has completed.
defer_state_ = DEFERRED_START;
deferred_request_id_ = request_id;
deferred_url_ = url;
*defer = true;
return true;
}
bool SafeBrowsingResourceHandler::OnWillRead(int request_id,
net::IOBuffer** buf, int* buf_size,
int min_size) {
CHECK(state_ == STATE_NONE);
CHECK(defer_state_ == DEFERRED_NONE);
return next_handler_->OnWillRead(request_id, buf, buf_size, min_size);
}
bool SafeBrowsingResourceHandler::OnReadCompleted(int request_id,
int* bytes_read) {
CHECK(state_ == STATE_NONE);
CHECK(defer_state_ == DEFERRED_NONE);
return next_handler_->OnReadCompleted(request_id, bytes_read);
}
bool SafeBrowsingResourceHandler::OnResponseCompleted(
int request_id, const net::URLRequestStatus& status,
const std::string& security_info) {
Shutdown();
return next_handler_->OnResponseCompleted(request_id, status, security_info);
}
void SafeBrowsingResourceHandler::OnRequestClosed() {
Shutdown();
next_handler_->OnRequestClosed();
}
// SafeBrowsingService::Client implementation, called on the IO thread once
// the URL has been classified.
void SafeBrowsingResourceHandler::OnBrowseUrlCheckResult(
const GURL& url, SafeBrowsingService::UrlCheckResult result) {
CHECK(state_ == STATE_CHECKING_URL);
CHECK(defer_state_ != DEFERRED_NONE);
CHECK(url == deferred_url_) << "Was expecting: " << deferred_url_
<< " but got: " << url;
timer_.Stop(); // Cancel the timeout timer.
safe_browsing_result_ = result;
state_ = STATE_NONE;
if (result == SafeBrowsingService::URL_SAFE) {
// Log how much time the safe browsing check cost us.
base::TimeDelta pause_delta;
pause_delta = base::TimeTicks::Now() - url_check_start_time_;
safe_browsing_->LogPauseDelay(pause_delta);
// Continue the request.
ResumeRequest();
} else {
StartDisplayingBlockingPage(url, result);
}
Release(); // Balances the AddRef() in CheckingUrl().
}
void SafeBrowsingResourceHandler::StartDisplayingBlockingPage(
const GURL& url,
SafeBrowsingService::UrlCheckResult result) {
CHECK(state_ == STATE_NONE);
CHECK(defer_state_ != DEFERRED_NONE);
CHECK(deferred_request_id_ != -1);
state_ = STATE_DISPLAYING_BLOCKING_PAGE;
AddRef(); // Balanced in OnBlockingPageComplete().
// Grab the original url of this request as well.
GURL original_url;
net::URLRequest* request = rdh_->GetURLRequest(
GlobalRequestID(render_process_host_id_, deferred_request_id_));
if (request)
original_url = request->original_url();
else
original_url = url;
safe_browsing_->DisplayBlockingPage(
url, original_url, redirect_urls_, resource_type_,
result, this, render_process_host_id_, render_view_id_);
}
// SafeBrowsingService::Client implementation, called on the IO thread when
// the user has decided to proceed with the current request, or go back.
void SafeBrowsingResourceHandler::OnBlockingPageComplete(bool proceed) {
CHECK(state_ == STATE_DISPLAYING_BLOCKING_PAGE);
state_ = STATE_NONE;
if (proceed) {
safe_browsing_result_ = SafeBrowsingService::URL_SAFE;
ResumeRequest();
} else {
rdh_->CancelRequest(render_process_host_id_, deferred_request_id_, false);
}
Release(); // Balances the AddRef() in StartDisplayingBlockingPage().
}
void SafeBrowsingResourceHandler::Shutdown() {
if (state_ == STATE_CHECKING_URL) {
timer_.Stop();
safe_browsing_->CancelCheck(this);
state_ = STATE_NONE;
// Balance the AddRef() from CheckUrl() which would ordinarily be
// balanced by OnUrlCheckResult().
Release();
}
}
bool SafeBrowsingResourceHandler::CheckUrl(const GURL& url) {
CHECK(state_ == STATE_NONE);
bool succeeded_synchronously = safe_browsing_->CheckBrowseUrl(url, this);
if (succeeded_synchronously) {
safe_browsing_result_ = SafeBrowsingService::URL_SAFE;
safe_browsing_->LogPauseDelay(base::TimeDelta()); // No delay.
return true;
}
AddRef(); // Balanced in OnUrlCheckResult().
state_ = STATE_CHECKING_URL;
// Record the start time of the check.
url_check_start_time_ = base::TimeTicks::Now();
// Start a timer to abort the check if it takes too long.
timer_.Start(base::TimeDelta::FromMilliseconds(kCheckUrlTimeoutMs),
this, &SafeBrowsingResourceHandler::OnCheckUrlTimeout);
return false;
}
void SafeBrowsingResourceHandler::ResumeRequest() {
CHECK(state_ == STATE_NONE);
CHECK(defer_state_ != DEFERRED_NONE);
// Resume whatever stage got paused by the safe browsing check.
switch (defer_state_) {
case DEFERRED_START:
ResumeStart();
break;
case DEFERRED_REDIRECT:
ResumeRedirect();
break;
case DEFERRED_NONE:
NOTREACHED();
break;
}
}
void SafeBrowsingResourceHandler::ResumeStart() {
CHECK(defer_state_ == DEFERRED_START);
CHECK(deferred_request_id_ != -1);
defer_state_ = DEFERRED_NONE;
// Retrieve the details for the paused OnWillStart().
int request_id = deferred_request_id_;
GURL url = deferred_url_;
ClearDeferredRequestInfo();
// Give the other resource handlers a chance to defer starting.
bool defer = false;
// TODO(eroman): the return value is being lost here. Should
// use it to cancel the request.
next_handler_->OnWillStart(request_id, url, &defer);
if (!defer)
rdh_->StartDeferredRequest(render_process_host_id_, request_id);
}
void SafeBrowsingResourceHandler::ResumeRedirect() {
CHECK(defer_state_ == DEFERRED_REDIRECT);
defer_state_ = DEFERRED_NONE;
// Retrieve the details for the paused OnReceivedRedirect().
int request_id = deferred_request_id_;
GURL redirect_url = deferred_url_;
scoped_refptr<ResourceResponse> redirect_response =
deferred_redirect_response_;
ClearDeferredRequestInfo();
// Give the other resource handlers a chance to handle the redirect.
bool defer = false;
// TODO(eroman): the return value is being lost here. Should
// use it to cancel the request.
next_handler_->OnRequestRedirected(request_id, redirect_url,
redirect_response, &defer);
if (!defer) {
rdh_->FollowDeferredRedirect(render_process_host_id_, request_id,
false, GURL());
}
}
void SafeBrowsingResourceHandler::ClearDeferredRequestInfo() {
deferred_request_id_ = -1;
deferred_url_ = GURL();
deferred_redirect_response_ = NULL;
}
|
// 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 "chrome/browser/renderer_host/safe_browsing_resource_handler.h"
#include "base/logging.h"
#include "chrome/browser/renderer_host/global_request_id.h"
#include "chrome/browser/renderer_host/resource_dispatcher_host.h"
#include "chrome/browser/renderer_host/resource_message_filter.h"
#include "chrome/common/resource_response.h"
#include "net/base/net_errors.h"
#include "net/base/io_buffer.h"
// Maximum time in milliseconds to wait for the safe browsing service to
// verify a URL. After this amount of time the outstanding check will be
// aborted, and the URL will be treated as if it were safe.
static const int kCheckUrlTimeoutMs = 5000;
// TODO(eroman): Downgrade these CHECK()s to DCHECKs once there is more
// unit test coverage.
SafeBrowsingResourceHandler::SafeBrowsingResourceHandler(
ResourceHandler* handler,
int render_process_host_id,
int render_view_id,
ResourceType::Type resource_type,
SafeBrowsingService* safe_browsing,
ResourceDispatcherHost* resource_dispatcher_host)
: state_(STATE_NONE),
defer_state_(DEFERRED_NONE),
safe_browsing_result_(SafeBrowsingService::URL_SAFE),
deferred_request_id_(-1),
next_handler_(handler),
render_process_host_id_(render_process_host_id),
render_view_id_(render_view_id),
safe_browsing_(safe_browsing),
rdh_(resource_dispatcher_host),
resource_type_(resource_type) {
}
SafeBrowsingResourceHandler::~SafeBrowsingResourceHandler() {
}
bool SafeBrowsingResourceHandler::OnUploadProgress(int request_id,
uint64 position,
uint64 size) {
return next_handler_->OnUploadProgress(request_id, position, size);
}
bool SafeBrowsingResourceHandler::OnRequestRedirected(
int request_id,
const GURL& new_url,
ResourceResponse* response,
bool* defer) {
CHECK(state_ == STATE_NONE);
CHECK(defer_state_ == DEFERRED_NONE);
// Save the redirect urls for possible malware detail reporting later.
redirect_urls_.push_back(new_url);
// We need to check the new URL before following the redirect.
if (CheckUrl(new_url)) {
return next_handler_->OnRequestRedirected(
request_id, new_url, response, defer);
}
// If the URL couldn't be verified synchronously, defer following the
// redirect until the SafeBrowsing check is complete. Store the redirect
// context so we can pass it on to other handlers once we have completed
// our check.
defer_state_ = DEFERRED_REDIRECT;
deferred_request_id_ = request_id;
deferred_url_ = new_url;
deferred_redirect_response_ = response;
*defer = true;
return true;
}
bool SafeBrowsingResourceHandler::OnResponseStarted(
int request_id, ResourceResponse* response) {
CHECK(state_ == STATE_NONE);
CHECK(defer_state_ == DEFERRED_NONE);
return next_handler_->OnResponseStarted(request_id, response);
}
void SafeBrowsingResourceHandler::OnCheckUrlTimeout() {
CHECK(state_ == STATE_CHECKING_URL);
CHECK(defer_state_ != DEFERRED_NONE);
safe_browsing_->CancelCheck(this);
OnBrowseUrlCheckResult(deferred_url_, SafeBrowsingService::URL_SAFE);
}
bool SafeBrowsingResourceHandler::OnWillStart(int request_id,
const GURL& url,
bool* defer) {
// We need to check the new URL before starting the request.
if (CheckUrl(url))
return next_handler_->OnWillStart(request_id, url, defer);
// If the URL couldn't be verified synchronously, defer starting the
// request until the check has completed.
defer_state_ = DEFERRED_START;
deferred_request_id_ = request_id;
deferred_url_ = url;
*defer = true;
return true;
}
bool SafeBrowsingResourceHandler::OnWillRead(int request_id,
net::IOBuffer** buf, int* buf_size,
int min_size) {
CHECK(state_ == STATE_NONE);
CHECK(defer_state_ == DEFERRED_NONE);
return next_handler_->OnWillRead(request_id, buf, buf_size, min_size);
}
bool SafeBrowsingResourceHandler::OnReadCompleted(int request_id,
int* bytes_read) {
CHECK(state_ == STATE_NONE);
CHECK(defer_state_ == DEFERRED_NONE);
return next_handler_->OnReadCompleted(request_id, bytes_read);
}
bool SafeBrowsingResourceHandler::OnResponseCompleted(
int request_id, const net::URLRequestStatus& status,
const std::string& security_info) {
Shutdown();
return next_handler_->OnResponseCompleted(request_id, status, security_info);
}
void SafeBrowsingResourceHandler::OnRequestClosed() {
Shutdown();
next_handler_->OnRequestClosed();
}
// SafeBrowsingService::Client implementation, called on the IO thread once
// the URL has been classified.
void SafeBrowsingResourceHandler::OnBrowseUrlCheckResult(
const GURL& url, SafeBrowsingService::UrlCheckResult result) {
CHECK(state_ == STATE_CHECKING_URL);
CHECK(defer_state_ != DEFERRED_NONE);
CHECK(url == deferred_url_) << "Was expecting: " << deferred_url_
<< " but got: " << url;
timer_.Stop(); // Cancel the timeout timer.
safe_browsing_result_ = result;
state_ = STATE_NONE;
if (result == SafeBrowsingService::URL_SAFE) {
// Log how much time the safe browsing check cost us.
base::TimeDelta pause_delta;
pause_delta = base::TimeTicks::Now() - url_check_start_time_;
safe_browsing_->LogPauseDelay(pause_delta);
// Continue the request.
ResumeRequest();
} else {
StartDisplayingBlockingPage(url, result);
}
Release(); // Balances the AddRef() in CheckingUrl().
}
void SafeBrowsingResourceHandler::StartDisplayingBlockingPage(
const GURL& url,
SafeBrowsingService::UrlCheckResult result) {
CHECK(state_ == STATE_NONE);
CHECK(defer_state_ != DEFERRED_NONE);
CHECK(deferred_request_id_ != -1);
state_ = STATE_DISPLAYING_BLOCKING_PAGE;
AddRef(); // Balanced in OnBlockingPageComplete().
// Grab the original url of this request as well.
GURL original_url;
net::URLRequest* request = rdh_->GetURLRequest(
GlobalRequestID(render_process_host_id_, deferred_request_id_));
if (request)
original_url = request->original_url();
else
original_url = url;
safe_browsing_->DisplayBlockingPage(
url, original_url, redirect_urls_, resource_type_,
result, this, render_process_host_id_, render_view_id_);
}
// SafeBrowsingService::Client implementation, called on the IO thread when
// the user has decided to proceed with the current request, or go back.
void SafeBrowsingResourceHandler::OnBlockingPageComplete(bool proceed) {
CHECK(state_ == STATE_DISPLAYING_BLOCKING_PAGE);
state_ = STATE_NONE;
if (proceed) {
safe_browsing_result_ = SafeBrowsingService::URL_SAFE;
ResumeRequest();
} else {
rdh_->CancelRequest(render_process_host_id_, deferred_request_id_, false);
}
Release(); // Balances the AddRef() in StartDisplayingBlockingPage().
}
void SafeBrowsingResourceHandler::Shutdown() {
if (state_ == STATE_CHECKING_URL) {
timer_.Stop();
safe_browsing_->CancelCheck(this);
state_ = STATE_NONE;
// Balance the AddRef() from CheckUrl() which would ordinarily be
// balanced by OnUrlCheckResult().
Release();
}
}
bool SafeBrowsingResourceHandler::CheckUrl(const GURL& url) {
CHECK(state_ == STATE_NONE);
bool succeeded_synchronously = safe_browsing_->CheckBrowseUrl(url, this);
if (succeeded_synchronously) {
safe_browsing_result_ = SafeBrowsingService::URL_SAFE;
safe_browsing_->LogPauseDelay(base::TimeDelta()); // No delay.
return true;
}
AddRef(); // Balanced in OnUrlCheckResult().
state_ = STATE_CHECKING_URL;
// Record the start time of the check.
url_check_start_time_ = base::TimeTicks::Now();
// Start a timer to abort the check if it takes too long.
timer_.Start(base::TimeDelta::FromMilliseconds(kCheckUrlTimeoutMs),
this, &SafeBrowsingResourceHandler::OnCheckUrlTimeout);
return false;
}
void SafeBrowsingResourceHandler::ResumeRequest() {
CHECK(state_ == STATE_NONE);
CHECK(defer_state_ != DEFERRED_NONE);
// Resume whatever stage got paused by the safe browsing check.
switch (defer_state_) {
case DEFERRED_START:
ResumeStart();
break;
case DEFERRED_REDIRECT:
ResumeRedirect();
break;
case DEFERRED_NONE:
NOTREACHED();
break;
}
}
void SafeBrowsingResourceHandler::ResumeStart() {
CHECK(defer_state_ == DEFERRED_START);
CHECK(deferred_request_id_ != -1);
defer_state_ = DEFERRED_NONE;
// Retrieve the details for the paused OnWillStart().
int request_id = deferred_request_id_;
GURL url = deferred_url_;
ClearDeferredRequestInfo();
// Give the other resource handlers a chance to defer starting.
bool defer = false;
// TODO(eroman): the return value is being lost here. Should
// use it to cancel the request.
next_handler_->OnWillStart(request_id, url, &defer);
if (!defer)
rdh_->StartDeferredRequest(render_process_host_id_, request_id);
}
void SafeBrowsingResourceHandler::ResumeRedirect() {
CHECK(defer_state_ == DEFERRED_REDIRECT);
defer_state_ = DEFERRED_NONE;
// Retrieve the details for the paused OnReceivedRedirect().
int request_id = deferred_request_id_;
GURL redirect_url = deferred_url_;
scoped_refptr<ResourceResponse> redirect_response =
deferred_redirect_response_;
ClearDeferredRequestInfo();
// Give the other resource handlers a chance to handle the redirect.
bool defer = false;
// TODO(eroman): the return value is being lost here. Should
// use it to cancel the request.
next_handler_->OnRequestRedirected(request_id, redirect_url,
redirect_response, &defer);
if (!defer) {
rdh_->FollowDeferredRedirect(render_process_host_id_, request_id,
false, GURL());
}
}
void SafeBrowsingResourceHandler::ClearDeferredRequestInfo() {
deferred_request_id_ = -1;
deferred_url_ = GURL();
deferred_redirect_response_ = NULL;
}
|
Initialize SafeBrowsingResourceHandler member.
|
Initialize SafeBrowsingResourceHandler member.
BUG=None
TEST=None
CID=14296
Review URL: http://codereview.chromium.org/6469031
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@74808 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
adobe/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,ropik/chromium,gavinp/chromium,adobe/chromium,gavinp/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,yitian134/chromium,ropik/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,ropik/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,adobe/chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,Crystalnix/house-of-life-chromium,yitian134/chromium,gavinp/chromium,yitian134/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,ropik/chromium
|
3f1ca23ca4e463784a187f265a1115172b63b8ba
|
bench/re2/common.hpp
|
bench/re2/common.hpp
|
// common re2 things
#include <stdio.h>
#include <re2/re2.h>
#include <iostream>
#include <string>
#include <sys/time.h>
#include <algorithm>
#include <inttypes.h>
using namespace std;
#ifndef USE_UTF8
#define ENCODING_OPTION RE2::Options::EncodingLatin1
#else
#define ENCODING_OPTION RE2::Options::EncodingUTF8
#endif
#define MATCH_ERROR \
fprintf(stderr, "match error on line %d\n", line); \
return 1;
#define PRE_COMPILE \
uint64_t preCompile = getTimeMs(); \
RE2 pattern(regex, options);
#define START_TIMING uint64_t start = getTimeMs();
#define PRINT_TIMES \
uint64_t stop = getTimeMs(); \
fprintf(stderr, "\ncompilation (ms): %" PRIu64 "\n", start - preCompile); \
fprintf(stderr, "matching (ms): %" PRIu64 "\n", stop - start);
// Initialize capture arguments
#define INIT_RE2_CAPTURE_ARGS(N) \
RE2::Arg *args[N]; \
string target[N]; \
for (int i = 0; i < N; i++) { \
args[i] = new RE2::Arg(&target[i]); \
}
// C-style fgets() is much much faster than C++-style getline(), so always use that.
#define BUFFER_SIZE (200*1024*1024)
char buffer[BUFFER_SIZE] = {0};
#define SETOPTS \
RE2::Options options; \
options.set_dot_nl(true); \
options.set_encoding(ENCODING_OPTION);
#define FOR_EACH_LINE(BODY) \
int line = 0; \
while(fgets(buffer, LINE_LEN, stdin)) { \
line++; \
BODY \
}
// Size of the chunks we read in at a time
#define INPUT_BLOCK_SIZE (1024*1024)
// Maximum line length
#define LINE_LEN 100000000
// Number of capturing parentheses
#ifndef NO_CAPTURE
#define CAPTURE true
#else
#define CAPTURE false
#endif
/** Gets the current timestamp in millisecond resolution */
uint64_t getTimeMs() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_usec / 1000 + tv.tv_sec * 1000;
}
|
// common re2 things
#include <stdio.h>
#include <re2/re2.h>
#include <iostream>
#include <string>
#include <sys/time.h>
#include <algorithm>
#include <inttypes.h>
using namespace std;
#ifndef USE_UTF8
#define ENCODING_OPTION RE2::Options::EncodingLatin1
#else
#define ENCODING_OPTION RE2::Options::EncodingUTF8
#endif
#define MATCH_ERROR \
fprintf(stderr, "match error on line %d\n", line); \
return 1;
#define PRE_COMPILE \
uint64_t preCompile = getTimeMs(); \
RE2 pattern(regex, options);
#define START_TIMING uint64_t start = getTimeMs();
#define PRINT_TIMES \
uint64_t stop = getTimeMs(); \
fprintf(stderr, "\ncompilation (ms): %" PRIu64 "\n", start - preCompile); \
fprintf(stderr, "matching (ms): %" PRIu64 "\n", stop - start);
// Initialize capture arguments
#define INIT_RE2_CAPTURE_ARGS(N) \
RE2::Arg *args[N]; \
string target[N]; \
for (int i = 0; i < N; i++) { \
args[i] = new RE2::Arg(&target[i]); \
}
// C-style fgets() is much much faster than C++-style getline(), so always use that.
#define BUFFER_SIZE (200*1024*1024)
char buffer[BUFFER_SIZE] = {0};
#define SETOPTS \
RE2::Options options; \
options.set_dot_nl(true); \
options.set_encoding(ENCODING_OPTION);
#define FOR_EACH_LINE(BODY) \
int line = 0; \
while(fgets(buffer, sizeof(buffer), stdin)) { \
line++; \
BODY \
}
// Size of the chunks we read in at a time
#define INPUT_BLOCK_SIZE (1024*1024)
// Number of capturing parentheses
#ifndef NO_CAPTURE
#define CAPTURE true
#else
#define CAPTURE false
#endif
/** Gets the current timestamp in millisecond resolution */
uint64_t getTimeMs() {
struct timeval tv;
gettimeofday(&tv, NULL);
return tv.tv_usec / 1000 + tv.tv_sec * 1000;
}
|
read long lines
|
re2: read long lines
|
C++
|
mit
|
diku-kmc/kleenexlang,diku-kmc/kleenexlang,diku-kmc/kleenexlang,diku-kmc/repg,diku-kmc/repg,diku-kmc/repg,diku-kmc/repg,diku-kmc/repg,diku-kmc/repg,diku-kmc/kleenexlang,diku-kmc/kleenexlang,diku-kmc/kleenexlang
|
ff509545edb6a4daf7b940ab229aa65bbee6befa
|
chrome/browser/ui/webui/chromeos/login/reset_screen_handler.cc
|
chrome/browser/ui/webui/chromeos/login/reset_screen_handler.cc
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/chromeos/login/reset_screen_handler.h"
#include <string>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/memory/scoped_ptr.h"
#include "base/metrics/histogram.h"
#include "base/prefs/pref_service.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/login/help_app_launcher.h"
#include "chrome/browser/chromeos/reset/metrics.h"
#include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h"
#include "chrome/common/pref_names.h"
#include "chromeos/chromeos_switches.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/power_manager_client.h"
#include "chromeos/dbus/session_manager_client.h"
#include "chromeos/dbus/update_engine_client.h"
#include "content/public/browser/browser_thread.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
namespace {
const char kJsScreenPath[] = "login.ResetScreen";
// Reset screen id.
const char kResetScreen[] = "reset";
const int kErrorUIStateRollback = 7;
static const char kRollbackFlagFile[] = "/tmp/.enable_rollback_ui";
void CheckRollbackFlagFileExists(bool *file_exists) {
DCHECK(content::BrowserThread::GetBlockingPool()->RunsTasksOnCurrentThread());
*file_exists = base::PathExists(base::FilePath(kRollbackFlagFile));
}
} // namespace
namespace chromeos {
ResetScreenHandler::ResetScreenHandler()
: BaseScreenHandler(kJsScreenPath),
delegate_(NULL),
show_on_init_(false),
restart_required_(true),
reboot_was_requested_(false),
rollback_available_(false),
weak_ptr_factory_(this) {
}
ResetScreenHandler::~ResetScreenHandler() {
if (delegate_)
delegate_->OnActorDestroyed(this);
DBusThreadManager::Get()->GetUpdateEngineClient()->RemoveObserver(this);
}
void ResetScreenHandler::PrepareToShow() {
}
void ResetScreenHandler::ShowWithParams() {
int dialog_type;
if (reboot_was_requested_) {
dialog_type = rollback_available_ ?
reset::DIALOG_SHORTCUT_CONFIRMING_POWERWASH_AND_ROLLBACK :
reset::DIALOG_SHORTCUT_CONFIRMING_POWERWASH_ONLY;
} else {
dialog_type = rollback_available_ ?
reset::DIALOG_SHORTCUT_OFFERING_ROLLBACK_AVAILABLE :
reset::DIALOG_SHORTCUT_OFFERING_ROLLBACK_UNAVAILABLE;
}
UMA_HISTOGRAM_ENUMERATION("Reset.ChromeOS.PowerwashDialogShown",
dialog_type,
reset::DIALOG_VIEW_TYPE_SIZE);
base::DictionaryValue reset_screen_params;
reset_screen_params.SetBoolean("showRestartMsg", restart_required_);
reset_screen_params.SetBoolean(
"showRollbackOption", rollback_available_ && !reboot_was_requested_);
reset_screen_params.SetBoolean(
"simpleConfirm", reboot_was_requested_ && !rollback_available_);
reset_screen_params.SetBoolean(
"rollbackConfirm", reboot_was_requested_ && rollback_available_);
PrefService* prefs = g_browser_process->local_state();
prefs->SetBoolean(prefs::kFactoryResetRequested, false);
prefs->SetBoolean(prefs::kRollbackRequested, false);
prefs->CommitPendingWrite();
ShowScreen(kResetScreen, &reset_screen_params);
}
void ResetScreenHandler::Show() {
if (!page_is_ready()) {
show_on_init_ = true;
return;
}
ChooseAndApplyShowScenario();
}
void ResetScreenHandler::ChooseAndApplyShowScenario() {
PrefService* prefs = g_browser_process->local_state();
restart_required_ = !CommandLine::ForCurrentProcess()->HasSwitch(
switches::kFirstExecAfterBoot);
reboot_was_requested_ = false;
rollback_available_ = false;
if (!restart_required_) // First exec after boot.
reboot_was_requested_ = prefs->GetBoolean(prefs::kFactoryResetRequested);
// Check Rollback flag-file.
scoped_ptr<bool> file_exists(new bool(false));
base::Closure checkfile_closure = base::Bind(
&CheckRollbackFlagFileExists,
base::Unretained(file_exists.get()));
base::Closure on_check_done = base::Bind(
&ResetScreenHandler::OnRollbackFlagFileCheckDone,
weak_ptr_factory_.GetWeakPtr(),
base::Passed(file_exists.Pass()));
if (!content::BrowserThread::PostBlockingPoolTaskAndReply(
FROM_HERE,
checkfile_closure,
on_check_done)) {
LOG(WARNING) << "Failed to check flag file for Rollback reset option";
on_check_done.Run();
}
}
void ResetScreenHandler::OnRollbackFlagFileCheckDone(
scoped_ptr<bool> file_exists) {
if (!file_exists && !CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableRollbackOption)) {
rollback_available_ = false;
ShowWithParams();
} else if (!restart_required_ && reboot_was_requested_) {
// First exec after boot.
PrefService* prefs = g_browser_process->local_state();
rollback_available_ = prefs->GetBoolean(prefs::kRollbackRequested);
ShowWithParams();
} else {
chromeos::DBusThreadManager::Get()->GetUpdateEngineClient()->
CanRollbackCheck(base::Bind(&ResetScreenHandler::OnRollbackCheck,
weak_ptr_factory_.GetWeakPtr()));
}
}
void ResetScreenHandler::Hide() {
DBusThreadManager::Get()->GetUpdateEngineClient()->RemoveObserver(this);
}
void ResetScreenHandler::SetDelegate(Delegate* delegate) {
delegate_ = delegate;
if (page_is_ready())
Initialize();
}
void ResetScreenHandler::DeclareLocalizedValues(
LocalizedValuesBuilder* builder) {
builder->Add("resetScreenTitle", IDS_RESET_SCREEN_TITLE);
builder->Add("resetScreenAccessibleTitle", IDS_RESET_SCREEN_TITLE);
builder->Add("resetScreenIconTitle",IDS_RESET_SCREEN_ICON_TITLE);
builder->Add("cancelButton", IDS_CANCEL);
builder->Add("resetWarningDataDetails",
IDS_RESET_SCREEN_WARNING_DETAILS_DATA);
builder->Add("resetRestartMessage", IDS_RESET_SCREEN_RESTART_MSG);
builder->AddF("resetRollbackOption",
IDS_RESET_SCREEN_ROLLBACK_OPTION,
IDS_SHORT_PRODUCT_NAME);
builder->AddF("resetRevertPromise",
IDS_RESET_SCREEN_PREPARING_REVERT_PROMISE,
IDS_SHORT_PRODUCT_NAME);
builder->AddF("resetRevertSpinnerMessage",
IDS_RESET_SCREEN_PREPARING_REVERT_SPINNER_MESSAGE,
IDS_SHORT_PRODUCT_NAME);
// Different variants of the same UI elements for all dialog cases.
builder->Add("resetButtonReset", IDS_RESET_SCREEN_RESET);
builder->Add("resetButtonRelaunch", IDS_RELAUNCH_BUTTON);
builder->Add("resetButtonPowerwash", IDS_RESET_SCREEN_POWERWASH);
builder->AddF(
"resetAndRollbackWarningTextConfirmational",
IDS_RESET_SCREEN_CONFIRMATION_WARNING_POWERWASH_AND_ROLLBACK_MSG,
IDS_SHORT_PRODUCT_NAME);
builder->AddF("resetWarningTextConfirmational",
IDS_RESET_SCREEN_CONFIRMATION_WARNING_POWERWASH_MSG,
IDS_SHORT_PRODUCT_NAME);
builder->AddF("resetWarningTextInitial",
IDS_RESET_SCREEN_WARNING_MSG,
IDS_SHORT_PRODUCT_NAME);
builder->AddF(
"resetAndRollbackWarningDetailsConfirmational",
IDS_RESET_SCREEN_CONFIRMATION_WARNING_ROLLBACK_DETAILS,
IDS_SHORT_PRODUCT_NAME);
builder->AddF("resetWarningDetailsConfirmational",
IDS_RESET_SCREEN_CONFIRMATION_WARNING_DETAILS,
IDS_SHORT_PRODUCT_NAME);
builder->AddF("resetWarningDetailsInitial",
IDS_RESET_SCREEN_WARNING_DETAILS,
IDS_SHORT_PRODUCT_NAME);
}
// Invoked from call to CanRollbackCheck upon completion of the DBus call.
void ResetScreenHandler::OnRollbackCheck(bool can_rollback) {
VLOG(1) << "Callback from CanRollbackCheck, result " << can_rollback;
rollback_available_ = can_rollback;
ShowWithParams();
}
void ResetScreenHandler::Initialize() {
if (!page_is_ready() || !delegate_)
return;
if (show_on_init_) {
Show();
show_on_init_ = false;
}
}
void ResetScreenHandler::RegisterMessages() {
AddCallback("cancelOnReset", &ResetScreenHandler::HandleOnCancel);
AddCallback("restartOnReset", &ResetScreenHandler::HandleOnRestart);
AddCallback("powerwashOnReset", &ResetScreenHandler::HandleOnPowerwash);
AddCallback("resetOnLearnMore", &ResetScreenHandler::HandleOnLearnMore);
}
void ResetScreenHandler::HandleOnCancel() {
if (delegate_)
delegate_->OnExit();
DBusThreadManager::Get()->GetUpdateEngineClient()->RemoveObserver(this);
}
void ResetScreenHandler::HandleOnRestart(bool should_rollback) {
PrefService* prefs = g_browser_process->local_state();
prefs->SetBoolean(prefs::kFactoryResetRequested, true);
prefs->SetBoolean(prefs::kRollbackRequested, should_rollback);
prefs->CommitPendingWrite();
chromeos::DBusThreadManager::Get()->GetPowerManagerClient()->RequestRestart();
}
void ResetScreenHandler::HandleOnPowerwash(bool rollback_checked) {
if (rollback_available_ && (rollback_checked || reboot_was_requested_)) {
CallJS("updateViewOnRollbackCall");
DBusThreadManager::Get()->GetUpdateEngineClient()->AddObserver(this);
chromeos::DBusThreadManager::Get()->GetUpdateEngineClient()->Rollback();
} else {
if (rollback_checked && !rollback_available_) {
NOTREACHED() <<
"Rollback was checked but not available. Starting powerwash.";
}
chromeos::DBusThreadManager::Get()->GetSessionManagerClient()->
StartDeviceWipe();
}
}
void ResetScreenHandler::HandleOnLearnMore() {
if (!help_app_.get())
help_app_ = new HelpAppLauncher(GetNativeWindow());
help_app_->ShowHelpTopic(HelpAppLauncher::HELP_POWERWASH);
}
void ResetScreenHandler::UpdateStatusChanged(
const UpdateEngineClient::Status& status) {
VLOG(1) << "Update status change to " << status.status;
if (status.status == UpdateEngineClient::UPDATE_STATUS_ERROR) {
// Show error screen.
base::DictionaryValue params;
params.SetInteger("uiState", kErrorUIStateRollback);
ShowScreen(OobeUI::kScreenErrorMessage, ¶ms);
} else if (status.status ==
UpdateEngineClient::UPDATE_STATUS_UPDATED_NEED_REBOOT) {
DBusThreadManager::Get()->GetPowerManagerClient()->RequestRestart();
}
}
} // namespace chromeos
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/chromeos/login/reset_screen_handler.h"
#include <string>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/file_util.h"
#include "base/files/file_path.h"
#include "base/memory/scoped_ptr.h"
#include "base/metrics/histogram.h"
#include "base/prefs/pref_service.h"
#include "base/values.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/chromeos/login/help_app_launcher.h"
#include "chrome/browser/chromeos/reset/metrics.h"
#include "chrome/browser/ui/webui/chromeos/login/oobe_ui.h"
#include "chrome/common/pref_names.h"
#include "chromeos/chromeos_switches.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "chromeos/dbus/power_manager_client.h"
#include "chromeos/dbus/session_manager_client.h"
#include "chromeos/dbus/update_engine_client.h"
#include "content/public/browser/browser_thread.h"
#include "grit/browser_resources.h"
#include "grit/chromium_strings.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
namespace {
const char kJsScreenPath[] = "login.ResetScreen";
// Reset screen id.
const char kResetScreen[] = "reset";
const int kErrorUIStateRollback = 7;
static const char kRollbackFlagFile[] = "/tmp/.enable_rollback_ui";
void CheckRollbackFlagFileExists(bool *file_exists) {
DCHECK(content::BrowserThread::GetBlockingPool()->RunsTasksOnCurrentThread());
*file_exists = base::PathExists(base::FilePath(kRollbackFlagFile));
}
} // namespace
namespace chromeos {
ResetScreenHandler::ResetScreenHandler()
: BaseScreenHandler(kJsScreenPath),
delegate_(NULL),
show_on_init_(false),
restart_required_(true),
reboot_was_requested_(false),
rollback_available_(false),
weak_ptr_factory_(this) {
}
ResetScreenHandler::~ResetScreenHandler() {
if (delegate_)
delegate_->OnActorDestroyed(this);
DBusThreadManager::Get()->GetUpdateEngineClient()->RemoveObserver(this);
}
void ResetScreenHandler::PrepareToShow() {
}
void ResetScreenHandler::ShowWithParams() {
int dialog_type;
if (reboot_was_requested_) {
dialog_type = rollback_available_ ?
reset::DIALOG_SHORTCUT_CONFIRMING_POWERWASH_AND_ROLLBACK :
reset::DIALOG_SHORTCUT_CONFIRMING_POWERWASH_ONLY;
} else {
dialog_type = rollback_available_ ?
reset::DIALOG_SHORTCUT_OFFERING_ROLLBACK_AVAILABLE :
reset::DIALOG_SHORTCUT_OFFERING_ROLLBACK_UNAVAILABLE;
}
UMA_HISTOGRAM_ENUMERATION("Reset.ChromeOS.PowerwashDialogShown",
dialog_type,
reset::DIALOG_VIEW_TYPE_SIZE);
base::DictionaryValue reset_screen_params;
reset_screen_params.SetBoolean("showRestartMsg", restart_required_);
reset_screen_params.SetBoolean(
"showRollbackOption", rollback_available_ && !reboot_was_requested_);
reset_screen_params.SetBoolean(
"simpleConfirm", reboot_was_requested_ && !rollback_available_);
reset_screen_params.SetBoolean(
"rollbackConfirm", reboot_was_requested_ && rollback_available_);
PrefService* prefs = g_browser_process->local_state();
prefs->SetBoolean(prefs::kFactoryResetRequested, false);
prefs->SetBoolean(prefs::kRollbackRequested, false);
prefs->CommitPendingWrite();
ShowScreen(kResetScreen, &reset_screen_params);
}
void ResetScreenHandler::Show() {
if (!page_is_ready()) {
show_on_init_ = true;
return;
}
ChooseAndApplyShowScenario();
}
void ResetScreenHandler::ChooseAndApplyShowScenario() {
PrefService* prefs = g_browser_process->local_state();
restart_required_ = !CommandLine::ForCurrentProcess()->HasSwitch(
switches::kFirstExecAfterBoot);
reboot_was_requested_ = false;
rollback_available_ = false;
if (!restart_required_) // First exec after boot.
reboot_was_requested_ = prefs->GetBoolean(prefs::kFactoryResetRequested);
// Check Rollback flag-file.
scoped_ptr<bool> file_exists(new bool(false));
base::Closure checkfile_closure = base::Bind(
&CheckRollbackFlagFileExists,
base::Unretained(file_exists.get()));
base::Closure on_check_done = base::Bind(
&ResetScreenHandler::OnRollbackFlagFileCheckDone,
weak_ptr_factory_.GetWeakPtr(),
base::Passed(file_exists.Pass()));
if (!content::BrowserThread::PostBlockingPoolTaskAndReply(
FROM_HERE,
checkfile_closure,
on_check_done)) {
LOG(WARNING) << "Failed to check flag file for Rollback reset option";
on_check_done.Run();
}
}
void ResetScreenHandler::OnRollbackFlagFileCheckDone(
scoped_ptr<bool> file_exists) {
if (!(*file_exists) && !CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableRollbackOption)) {
rollback_available_ = false;
ShowWithParams();
} else if (!restart_required_ && reboot_was_requested_) {
// First exec after boot.
PrefService* prefs = g_browser_process->local_state();
rollback_available_ = prefs->GetBoolean(prefs::kRollbackRequested);
ShowWithParams();
} else {
chromeos::DBusThreadManager::Get()->GetUpdateEngineClient()->
CanRollbackCheck(base::Bind(&ResetScreenHandler::OnRollbackCheck,
weak_ptr_factory_.GetWeakPtr()));
}
}
void ResetScreenHandler::Hide() {
DBusThreadManager::Get()->GetUpdateEngineClient()->RemoveObserver(this);
}
void ResetScreenHandler::SetDelegate(Delegate* delegate) {
delegate_ = delegate;
if (page_is_ready())
Initialize();
}
void ResetScreenHandler::DeclareLocalizedValues(
LocalizedValuesBuilder* builder) {
builder->Add("resetScreenTitle", IDS_RESET_SCREEN_TITLE);
builder->Add("resetScreenAccessibleTitle", IDS_RESET_SCREEN_TITLE);
builder->Add("resetScreenIconTitle",IDS_RESET_SCREEN_ICON_TITLE);
builder->Add("cancelButton", IDS_CANCEL);
builder->Add("resetWarningDataDetails",
IDS_RESET_SCREEN_WARNING_DETAILS_DATA);
builder->Add("resetRestartMessage", IDS_RESET_SCREEN_RESTART_MSG);
builder->AddF("resetRollbackOption",
IDS_RESET_SCREEN_ROLLBACK_OPTION,
IDS_SHORT_PRODUCT_NAME);
builder->AddF("resetRevertPromise",
IDS_RESET_SCREEN_PREPARING_REVERT_PROMISE,
IDS_SHORT_PRODUCT_NAME);
builder->AddF("resetRevertSpinnerMessage",
IDS_RESET_SCREEN_PREPARING_REVERT_SPINNER_MESSAGE,
IDS_SHORT_PRODUCT_NAME);
// Different variants of the same UI elements for all dialog cases.
builder->Add("resetButtonReset", IDS_RESET_SCREEN_RESET);
builder->Add("resetButtonRelaunch", IDS_RELAUNCH_BUTTON);
builder->Add("resetButtonPowerwash", IDS_RESET_SCREEN_POWERWASH);
builder->AddF(
"resetAndRollbackWarningTextConfirmational",
IDS_RESET_SCREEN_CONFIRMATION_WARNING_POWERWASH_AND_ROLLBACK_MSG,
IDS_SHORT_PRODUCT_NAME);
builder->AddF("resetWarningTextConfirmational",
IDS_RESET_SCREEN_CONFIRMATION_WARNING_POWERWASH_MSG,
IDS_SHORT_PRODUCT_NAME);
builder->AddF("resetWarningTextInitial",
IDS_RESET_SCREEN_WARNING_MSG,
IDS_SHORT_PRODUCT_NAME);
builder->AddF(
"resetAndRollbackWarningDetailsConfirmational",
IDS_RESET_SCREEN_CONFIRMATION_WARNING_ROLLBACK_DETAILS,
IDS_SHORT_PRODUCT_NAME);
builder->AddF("resetWarningDetailsConfirmational",
IDS_RESET_SCREEN_CONFIRMATION_WARNING_DETAILS,
IDS_SHORT_PRODUCT_NAME);
builder->AddF("resetWarningDetailsInitial",
IDS_RESET_SCREEN_WARNING_DETAILS,
IDS_SHORT_PRODUCT_NAME);
}
// Invoked from call to CanRollbackCheck upon completion of the DBus call.
void ResetScreenHandler::OnRollbackCheck(bool can_rollback) {
VLOG(1) << "Callback from CanRollbackCheck, result " << can_rollback;
rollback_available_ = can_rollback;
ShowWithParams();
}
void ResetScreenHandler::Initialize() {
if (!page_is_ready() || !delegate_)
return;
if (show_on_init_) {
Show();
show_on_init_ = false;
}
}
void ResetScreenHandler::RegisterMessages() {
AddCallback("cancelOnReset", &ResetScreenHandler::HandleOnCancel);
AddCallback("restartOnReset", &ResetScreenHandler::HandleOnRestart);
AddCallback("powerwashOnReset", &ResetScreenHandler::HandleOnPowerwash);
AddCallback("resetOnLearnMore", &ResetScreenHandler::HandleOnLearnMore);
}
void ResetScreenHandler::HandleOnCancel() {
if (delegate_)
delegate_->OnExit();
DBusThreadManager::Get()->GetUpdateEngineClient()->RemoveObserver(this);
}
void ResetScreenHandler::HandleOnRestart(bool should_rollback) {
PrefService* prefs = g_browser_process->local_state();
prefs->SetBoolean(prefs::kFactoryResetRequested, true);
prefs->SetBoolean(prefs::kRollbackRequested, should_rollback);
prefs->CommitPendingWrite();
chromeos::DBusThreadManager::Get()->GetPowerManagerClient()->RequestRestart();
}
void ResetScreenHandler::HandleOnPowerwash(bool rollback_checked) {
if (rollback_available_ && (rollback_checked || reboot_was_requested_)) {
CallJS("updateViewOnRollbackCall");
DBusThreadManager::Get()->GetUpdateEngineClient()->AddObserver(this);
chromeos::DBusThreadManager::Get()->GetUpdateEngineClient()->Rollback();
} else {
if (rollback_checked && !rollback_available_) {
NOTREACHED() <<
"Rollback was checked but not available. Starting powerwash.";
}
chromeos::DBusThreadManager::Get()->GetSessionManagerClient()->
StartDeviceWipe();
}
}
void ResetScreenHandler::HandleOnLearnMore() {
if (!help_app_.get())
help_app_ = new HelpAppLauncher(GetNativeWindow());
help_app_->ShowHelpTopic(HelpAppLauncher::HELP_POWERWASH);
}
void ResetScreenHandler::UpdateStatusChanged(
const UpdateEngineClient::Status& status) {
VLOG(1) << "Update status change to " << status.status;
if (status.status == UpdateEngineClient::UPDATE_STATUS_ERROR) {
// Show error screen.
base::DictionaryValue params;
params.SetInteger("uiState", kErrorUIStateRollback);
ShowScreen(OobeUI::kScreenErrorMessage, ¶ms);
} else if (status.status ==
UpdateEngineClient::UPDATE_STATUS_UPDATED_NEED_REBOOT) {
DBusThreadManager::Get()->GetPowerManagerClient()->RequestRestart();
}
}
} // namespace chromeos
|
Fix for flag-file covering Rollback reset option.
|
Fix for flag-file covering Rollback reset option.
BUG=368844
Review URL: https://codereview.chromium.org/305153002
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@273884 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
Pluto-tv/chromium-crosswalk,M4sse/chromium.src,axinging/chromium-crosswalk,Chilledheart/chromium,dednal/chromium.src,dushu1203/chromium.src,markYoungH/chromium.src,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,ondra-novak/chromium.src,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,Chilledheart/chromium,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,dushu1203/chromium.src,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,ltilve/chromium,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,markYoungH/chromium.src,jaruba/chromium.src,ltilve/chromium,krieger-od/nwjs_chromium.src,jaruba/chromium.src,jaruba/chromium.src,Just-D/chromium-1,Jonekee/chromium.src,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,littlstar/chromium.src,Just-D/chromium-1,fujunwei/chromium-crosswalk,ltilve/chromium,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,dednal/chromium.src,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ltilve/chromium,hgl888/chromium-crosswalk-efl,ltilve/chromium,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,Just-D/chromium-1,dednal/chromium.src,dushu1203/chromium.src,dushu1203/chromium.src,littlstar/chromium.src,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,Just-D/chromium-1,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,axinging/chromium-crosswalk,ltilve/chromium,littlstar/chromium.src,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,Jonekee/chromium.src,M4sse/chromium.src,ltilve/chromium,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,ltilve/chromium,jaruba/chromium.src,markYoungH/chromium.src,Jonekee/chromium.src,ondra-novak/chromium.src,littlstar/chromium.src,hgl888/chromium-crosswalk,M4sse/chromium.src,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,dednal/chromium.src,littlstar/chromium.src,krieger-od/nwjs_chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk,dednal/chromium.src,dushu1203/chromium.src,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,Just-D/chromium-1,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,Chilledheart/chromium,jaruba/chromium.src,littlstar/chromium.src,axinging/chromium-crosswalk,M4sse/chromium.src,jaruba/chromium.src,Jonekee/chromium.src,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,jaruba/chromium.src,dushu1203/chromium.src,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,jaruba/chromium.src,Jonekee/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,dednal/chromium.src,dushu1203/chromium.src,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,axinging/chromium-crosswalk,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,Fireblend/chromium-crosswalk,Chilledheart/chromium,dednal/chromium.src,markYoungH/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk,littlstar/chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,M4sse/chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,jaruba/chromium.src,markYoungH/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,Jonekee/chromium.src,Jonekee/chromium.src,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src
|
b4caf2bb13b467a7f7b81134556e70d4f1b2717d
|
include/cybozu/zlib.hpp
|
include/cybozu/zlib.hpp
|
#pragma once
/**
@file
@brief zlib compressor and decompressor class
Copyright (C) 2009 Cybozu Labs, Inc., all rights reserved.
*/
#include <cybozu/exception.hpp>
#include <cybozu/endian.hpp>
#include <cybozu/stream_fwd.hpp>
#include <assert.h>
#include <zlib.h>
#ifdef _MSC_VER
#pragma comment(lib, "zlib.lib")
#endif
namespace cybozu {
namespace zlib_local {
const int DEF_MEM_LEVEL = 8;
} // zlib_local
/**
zlib compressor class
OutputStream must have size_t write(const char *buf, size_t size);
*/
template<class OutputStream, size_t maxBufSize = 2048>
class ZlibCompressorT {
OutputStream& os_;
unsigned int crc_;
unsigned int totalSize_; /* mod 2^32 */
z_stream z_;
char buf_[maxBufSize];
bool isFlushCalled_;
const bool useGzip_;
ZlibCompressorT(const ZlibCompressorT&);
void operator=(const ZlibCompressorT&);
public:
/**
@param os [in] output stream
@param useGzip [in] useGzip if true, use deflate if false
@note useGzip option is not fully tested, so default off
*/
ZlibCompressorT(OutputStream& os, bool useGzip = false, int compressionLevel = Z_DEFAULT_COMPRESSION)
: os_(os)
, crc_(crc32(0L, Z_NULL, 0))
, totalSize_(0)
, isFlushCalled_(false)
, useGzip_(useGzip)
{
z_.zalloc = Z_NULL;
z_.zfree = Z_NULL;
z_.opaque = Z_NULL;
if (useGzip_) {
if (deflateInit2(&z_, compressionLevel, Z_DEFLATED, -MAX_WBITS, zlib_local::DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY) != Z_OK) {
throw cybozu::Exception("zlib:ZlibCompressorT:deflateInit2") << std::string(z_.msg);
}
char header[] = "\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03"; /* OS_CODE = 0x03(Unix) */
write_os(header, 10);
} else {
if (deflateInit(&z_, compressionLevel) != Z_OK) {
throw cybozu::Exception("zlib:ZlibCompressorT:deflateInit") << std::string(z_.msg);
}
}
}
~ZlibCompressorT()
{
if (!isFlushCalled_) {
try {
flush();
} catch (std::exception& e) {
fprintf(stderr, "ZlibCompressor:flush:exception:%s\n", e.what());
} catch (...) {
fprintf(stderr, "ZlibCompressor:flush:unknown exception\n");
}
}
deflateEnd(&z_);
}
/*
compress buf
@param buf [in] input data
@param size [in] input data size
*/
bool write(const char *buf, size_t _size)
{
assert(_size < (1U << 31));
uint32_t size = (uint32_t)_size;
if (useGzip_) {
crc_ = crc32(crc_, (const Bytef *)buf, size);
totalSize_ += (unsigned int)size;
}
z_.next_in = (Bytef*)const_cast<char*>(buf);
z_.avail_in = size;
while (z_.avail_in > 0) {
z_.next_out = (Bytef*)buf_;
z_.avail_out = maxBufSize;
int ret = deflate(&z_, Z_NO_FLUSH);
if (ret != Z_STREAM_END && ret != Z_OK) {
throw cybozu::Exception("zlib:exec:compress") << std::string(z_.msg);
}
write_os(buf_, maxBufSize - z_.avail_out);
if (ret == Z_STREAM_END) break;
}
return true;
}
void flush()
{
isFlushCalled_ = true;
z_.next_in = 0;
z_.avail_in = 0;
for (;;) {
z_.next_out = (Bytef*)buf_;
z_.avail_out = maxBufSize;
int ret = deflate(&z_, Z_FINISH);
if (ret != Z_STREAM_END && ret != Z_OK) {
throw cybozu::Exception("zlib:flush") << std::string(z_.msg);
}
write_os(buf_, sizeof(buf_) - z_.avail_out);
if (ret == Z_STREAM_END) break;
}
if (useGzip_) {
char tail[8];
cybozu::Set32bitAsLE(&tail[0], crc_);
cybozu::Set32bitAsLE(&tail[4], totalSize_);
write_os(tail, sizeof(tail));
}
}
private:
void write_os(const char *buf, size_t size)
{
cybozu::OutputStreamTag<OutputStream>::write(os_, buf, size);
}
};
/**
zlib decompressor class
InputStream must have size_t read(char *str, size_t size);
*/
template<class InputStream, size_t maxBufSize = 2048>
class ZlibDecompressorT {
InputStream& is_;
unsigned int crc_;
unsigned int totalSize_; /* mod 2^32 */
z_stream z_;
int ret_;
char buf_[maxBufSize];
const bool useGzip_;
bool readGzipHeader_;
void readAll(char *buf, size_t size)
{
ssize_t readSize = cybozu::InputStreamTag<InputStream>::read(is_, buf, size);
if ((size_t)readSize != size) {
throw cybozu::Exception("zlib:ZlibDecompressorT:readAll") << readSize << size;
}
}
void skipToZero()
{
for (;;) {
char buf[1];
readAll(buf, 1);
if (buf[0] == '\0') break;
}
}
void skip(int size)
{
for (int i = 0 ; i < size; i++) {
char buf[1];
readAll(buf, 1);
}
}
void readGzipHeader()
{
char header[10];
readAll(header, sizeof(header));
enum {
FHCRC = 1 << 1,
FEXTRA = 1 << 2,
FNAME = 1 << 3,
FCOMMENT = 1 << 4,
RESERVED = 7 << 5,
};
char flg = header[3];
if (header[0] == '\x1f'
&& header[1] == '\x8b'
&& header[2] == Z_DEFLATED
&& !(flg & RESERVED)) {
if (flg & FEXTRA) {
char xlen[2];
readAll(xlen, sizeof(xlen));
int size = cybozu::Get16bitAsLE(xlen);
skip(size);
}
if (flg & FNAME) {
skipToZero();
}
if (flg & FCOMMENT) {
skipToZero();
}
if (flg & FHCRC) {
skip(2);
}
return;
}
throw cybozu::Exception("zlib:ZlibDecompressorT:readGzipHeader:bad gzip header") << std::string(header, 10);
}
ZlibDecompressorT(const ZlibDecompressorT&);
void operator=(const ZlibDecompressorT&);
public:
/**
@param os [in] input stream
@param useGzip [in] useGzip if true, use deflate if false
@note useGzip option is not fully tested, so default off
*/
ZlibDecompressorT(InputStream& is, bool useGzip = false)
: is_(is)
, crc_(crc32(0L, Z_NULL, 0))
, totalSize_(0)
, ret_(Z_OK)
, useGzip_(useGzip)
, readGzipHeader_(false)
{
z_.zalloc = Z_NULL;
z_.zfree = Z_NULL;
z_.opaque = Z_NULL;
z_.next_in = 0;
z_.avail_in = 0;
if (useGzip_) {
if (inflateInit2(&z_, -MAX_WBITS) != Z_OK) {
throw cybozu::Exception("zlib:ZlibDecompressorT:inflateInit2") << std::string(z_.msg);
}
} else {
if (inflateInit(&z_) != Z_OK) {
throw cybozu::Exception("zlib:ZlibDecompressorT:inflateInit") << std::string(z_.msg);
}
}
}
~ZlibDecompressorT()
{
inflateEnd(&z_);
}
/*
decompress is
@param str [out] decompressed data
@param str [out] max buf size
@return written size
*/
ssize_t read(char *buf, size_t _size)
{
assert(_size < (1U << 31));
uint32_t size = (uint32_t)_size;
if (size == 0) return 0;
if (useGzip_ && !readGzipHeader_) {
readGzipHeader();
readGzipHeader_ = true;
}
z_.next_out = (Bytef*)buf;
z_.avail_out = size;
do {
if (z_.avail_in == 0) {
z_.avail_in = (uint32_t)cybozu::InputStreamTag<InputStream>::read(is_, buf_, maxBufSize);
if (ret_ == Z_STREAM_END && z_.avail_in == 0) return 0;
z_.next_in = (Bytef*)buf_;
}
ret_ = inflate(&z_, Z_NO_FLUSH);
if (ret_ == Z_STREAM_END) break;
if (ret_ != Z_OK) {
throw cybozu::Exception("zlib:read:decompress") << std::string(z_.msg);
}
} while (size == z_.avail_out);
return size - z_.avail_out;
}
};
} // cybozu
|
#pragma once
/**
@file
@brief zlib compressor and decompressor class
Copyright (C) 2009 Cybozu Labs, Inc., all rights reserved.
*/
#include <cybozu/exception.hpp>
#include <cybozu/endian.hpp>
#include <cybozu/stream_fwd.hpp>
#include <assert.h>
#include <zlib.h>
#ifdef _MSC_VER
#ifdef _DLL_CPPLIB
#pragma comment(lib, "zlib_md.lib")
#else
#pragma comment(lib, "zlib_mt.lib")
#endif
#endif
namespace cybozu {
namespace zlib_local {
const int DEF_MEM_LEVEL = 8;
} // zlib_local
/**
zlib compressor class
OutputStream must have size_t write(const char *buf, size_t size);
*/
template<class OutputStream, size_t maxBufSize = 2048>
class ZlibCompressorT {
OutputStream& os_;
unsigned int crc_;
unsigned int totalSize_; /* mod 2^32 */
z_stream z_;
char buf_[maxBufSize];
bool isFlushCalled_;
const bool useGzip_;
ZlibCompressorT(const ZlibCompressorT&);
void operator=(const ZlibCompressorT&);
public:
/**
@param os [in] output stream
@param useGzip [in] useGzip if true, use deflate if false
@note useGzip option is not fully tested, so default off
*/
ZlibCompressorT(OutputStream& os, bool useGzip = false, int compressionLevel = Z_DEFAULT_COMPRESSION)
: os_(os)
, crc_(crc32(0L, Z_NULL, 0))
, totalSize_(0)
, isFlushCalled_(false)
, useGzip_(useGzip)
{
z_.zalloc = Z_NULL;
z_.zfree = Z_NULL;
z_.opaque = Z_NULL;
if (useGzip_) {
if (deflateInit2(&z_, compressionLevel, Z_DEFLATED, -MAX_WBITS, zlib_local::DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY) != Z_OK) {
throw cybozu::Exception("zlib:ZlibCompressorT:deflateInit2") << std::string(z_.msg);
}
char header[] = "\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03"; /* OS_CODE = 0x03(Unix) */
write_os(header, 10);
} else {
if (deflateInit(&z_, compressionLevel) != Z_OK) {
throw cybozu::Exception("zlib:ZlibCompressorT:deflateInit") << std::string(z_.msg);
}
}
}
~ZlibCompressorT()
{
if (!isFlushCalled_) {
try {
flush();
} catch (std::exception& e) {
fprintf(stderr, "ZlibCompressor:flush:exception:%s\n", e.what());
} catch (...) {
fprintf(stderr, "ZlibCompressor:flush:unknown exception\n");
}
}
deflateEnd(&z_);
}
/*
compress buf
@param buf [in] input data
@param size [in] input data size
*/
bool write(const char *buf, size_t _size)
{
assert(_size < (1U << 31));
uint32_t size = (uint32_t)_size;
if (useGzip_) {
crc_ = crc32(crc_, (const Bytef *)buf, size);
totalSize_ += (unsigned int)size;
}
z_.next_in = (Bytef*)const_cast<char*>(buf);
z_.avail_in = size;
while (z_.avail_in > 0) {
z_.next_out = (Bytef*)buf_;
z_.avail_out = maxBufSize;
int ret = deflate(&z_, Z_NO_FLUSH);
if (ret != Z_STREAM_END && ret != Z_OK) {
throw cybozu::Exception("zlib:exec:compress") << std::string(z_.msg);
}
write_os(buf_, maxBufSize - z_.avail_out);
if (ret == Z_STREAM_END) break;
}
return true;
}
void flush()
{
isFlushCalled_ = true;
z_.next_in = 0;
z_.avail_in = 0;
for (;;) {
z_.next_out = (Bytef*)buf_;
z_.avail_out = maxBufSize;
int ret = deflate(&z_, Z_FINISH);
if (ret != Z_STREAM_END && ret != Z_OK) {
throw cybozu::Exception("zlib:flush") << std::string(z_.msg);
}
write_os(buf_, sizeof(buf_) - z_.avail_out);
if (ret == Z_STREAM_END) break;
}
if (useGzip_) {
char tail[8];
cybozu::Set32bitAsLE(&tail[0], crc_);
cybozu::Set32bitAsLE(&tail[4], totalSize_);
write_os(tail, sizeof(tail));
}
}
private:
void write_os(const char *buf, size_t size)
{
cybozu::OutputStreamTag<OutputStream>::write(os_, buf, size);
}
};
/**
zlib decompressor class
InputStream must have size_t read(char *str, size_t size);
*/
template<class InputStream, size_t maxBufSize = 2048>
class ZlibDecompressorT {
InputStream& is_;
unsigned int crc_;
unsigned int totalSize_; /* mod 2^32 */
z_stream z_;
int ret_;
char buf_[maxBufSize];
const bool useGzip_;
bool readGzipHeader_;
void readAll(char *buf, size_t size)
{
ssize_t readSize = cybozu::InputStreamTag<InputStream>::read(is_, buf, size);
if ((size_t)readSize != size) {
throw cybozu::Exception("zlib:ZlibDecompressorT:readAll") << readSize << size;
}
}
void skipToZero()
{
for (;;) {
char buf[1];
readAll(buf, 1);
if (buf[0] == '\0') break;
}
}
void skip(int size)
{
for (int i = 0 ; i < size; i++) {
char buf[1];
readAll(buf, 1);
}
}
void readGzipHeader()
{
char header[10];
readAll(header, sizeof(header));
enum {
FHCRC = 1 << 1,
FEXTRA = 1 << 2,
FNAME = 1 << 3,
FCOMMENT = 1 << 4,
RESERVED = 7 << 5,
};
char flg = header[3];
if (header[0] == '\x1f'
&& header[1] == '\x8b'
&& header[2] == Z_DEFLATED
&& !(flg & RESERVED)) {
if (flg & FEXTRA) {
char xlen[2];
readAll(xlen, sizeof(xlen));
int size = cybozu::Get16bitAsLE(xlen);
skip(size);
}
if (flg & FNAME) {
skipToZero();
}
if (flg & FCOMMENT) {
skipToZero();
}
if (flg & FHCRC) {
skip(2);
}
return;
}
throw cybozu::Exception("zlib:ZlibDecompressorT:readGzipHeader:bad gzip header") << std::string(header, 10);
}
ZlibDecompressorT(const ZlibDecompressorT&);
void operator=(const ZlibDecompressorT&);
public:
/**
@param os [in] input stream
@param useGzip [in] useGzip if true, use deflate if false
@note useGzip option is not fully tested, so default off
*/
ZlibDecompressorT(InputStream& is, bool useGzip = false)
: is_(is)
, crc_(crc32(0L, Z_NULL, 0))
, totalSize_(0)
, ret_(Z_OK)
, useGzip_(useGzip)
, readGzipHeader_(false)
{
z_.zalloc = Z_NULL;
z_.zfree = Z_NULL;
z_.opaque = Z_NULL;
z_.next_in = 0;
z_.avail_in = 0;
if (useGzip_) {
if (inflateInit2(&z_, -MAX_WBITS) != Z_OK) {
throw cybozu::Exception("zlib:ZlibDecompressorT:inflateInit2") << std::string(z_.msg);
}
} else {
if (inflateInit(&z_) != Z_OK) {
throw cybozu::Exception("zlib:ZlibDecompressorT:inflateInit") << std::string(z_.msg);
}
}
}
~ZlibDecompressorT()
{
inflateEnd(&z_);
}
/*
decompress is
@param str [out] decompressed data
@param str [out] max buf size
@return written size
*/
ssize_t read(char *buf, size_t _size)
{
assert(_size < (1U << 31));
uint32_t size = (uint32_t)_size;
if (size == 0) return 0;
if (useGzip_ && !readGzipHeader_) {
readGzipHeader();
readGzipHeader_ = true;
}
z_.next_out = (Bytef*)buf;
z_.avail_out = size;
do {
if (z_.avail_in == 0) {
z_.avail_in = (uint32_t)cybozu::InputStreamTag<InputStream>::read(is_, buf_, maxBufSize);
if (ret_ == Z_STREAM_END && z_.avail_in == 0) return 0;
z_.next_in = (Bytef*)buf_;
}
ret_ = inflate(&z_, Z_NO_FLUSH);
if (ret_ == Z_STREAM_END) break;
if (ret_ != Z_OK) {
throw cybozu::Exception("zlib:read:decompress") << std::string(z_.msg);
}
} while (size == z_.avail_out);
return size - z_.avail_out;
}
};
} // cybozu
|
select zlib_md.lib if _DLL_CPPLIB is defined
|
select zlib_md.lib if _DLL_CPPLIB is defined
|
C++
|
bsd-3-clause
|
herumi/cybozulib,herumi/cybozulib
|
812560d3349d555722f248a37a2503d0c8b4e1e8
|
include/dll/dyn_rbm.inl
|
include/dll/dyn_rbm.inl
|
//=======================================================================
// 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 "etl/etl.hpp"
#include "standard_rbm.hpp"
namespace dll {
/*!
* \brief Standard version of Restricted Boltzmann Machine
*
* This follows the definition of a RBM by Geoffrey Hinton.
*/
template <typename Desc>
struct dyn_rbm final : public standard_rbm<dyn_rbm<Desc>, Desc> {
using desc = Desc;
using weight = typename desc::weight;
using this_type = dyn_rbm<Desc>;
using base_type = standard_rbm<this_type, Desc>;
static constexpr const unit_type visible_unit = desc::visible_unit;
static constexpr const unit_type hidden_unit = desc::hidden_unit;
using w_type = etl::dyn_matrix<weight>;
using b_type = etl::dyn_vector<weight>;
using c_type = etl::dyn_vector<weight>;
//Weights and biases
w_type w; //!< Weights
b_type b; //!< Hidden biases
c_type c; //!< Visible biases
//Backup weights and biases
std::unique_ptr<w_type> bak_w; //!< Backup Weights
std::unique_ptr<b_type> bak_b; //!< Backup Hidden biases
std::unique_ptr<c_type> bak_c; //!< Backup Visible biases
//Reconstruction data
etl::dyn_vector<weight> v1; //!< State of the visible units
etl::dyn_vector<weight> h1_a; //!< Activation probabilities of hidden units after first CD-step
etl::dyn_vector<weight> h1_s; //!< Sampled value of hidden units after first CD-step
etl::dyn_vector<weight> v2_a; //!< Activation probabilities of visible units after first CD-step
etl::dyn_vector<weight> v2_s; //!< Sampled value of visible units after first CD-step
etl::dyn_vector<weight> h2_a; //!< Activation probabilities of hidden units after last CD-step
etl::dyn_vector<weight> h2_s; //!< Sampled value of hidden units after last CD-step
template <std::size_t B>
using input_batch_t = etl::fast_dyn_matrix<weight, B, 1>; //TODO Check how to handle this
size_t num_visible;
size_t num_hidden;
size_t batch_size = 25;
//No copying
dyn_rbm(const dyn_rbm& rbm) = delete;
dyn_rbm& operator=(const dyn_rbm& rbm) = delete;
//No moving
dyn_rbm(dyn_rbm&& rbm) = delete;
dyn_rbm& operator=(dyn_rbm&& rbm) = delete;
dyn_rbm()
: base_type() {}
/*!
* \brief Initialize a RBM with basic weights.
*
* The weights are initialized from a normal distribution of
* zero-mean and 0.1 variance.
*/
dyn_rbm(size_t num_visible, size_t num_hidden)
: base_type(),
w(num_visible, num_hidden),
b(num_hidden, static_cast<weight>(0.0)),
c(num_visible, static_cast<weight>(0.0)),
v1(num_visible),
h1_a(num_hidden),
h1_s(num_hidden),
v2_a(num_visible),
v2_s(num_visible),
h2_a(num_hidden),
h2_s(num_hidden),
num_visible(num_visible),
num_hidden(num_hidden) {
//Initialize the weights with a zero-mean and unit variance Gaussian distribution
w = etl::normal_generator<weight>() * 0.1;
}
void init_layer(size_t nv, size_t nh) {
num_visible = nv;
num_hidden = nh;
w = etl::dyn_matrix<weight>(num_visible, num_hidden);
b = etl::dyn_vector<weight>(num_hidden, static_cast<weight>(0.0));
c = etl::dyn_vector<weight>(num_visible, static_cast<weight>(0.0));
v1 = etl::dyn_vector<weight>(num_visible);
h1_a = etl::dyn_vector<weight>(num_hidden);
h1_s = etl::dyn_vector<weight>(num_hidden);
v2_a = etl::dyn_vector<weight>(num_visible);
v2_s = etl::dyn_vector<weight>(num_visible);
h2_a = etl::dyn_vector<weight>(num_hidden);
h2_s = etl::dyn_vector<weight>(num_hidden);
//Initialize the weights with a zero-mean and unit variance Gaussian distribution
w = etl::normal_generator<weight>() * 0.1;
}
void backup_weights() {
unique_safe_get(bak_w) = w;
unique_safe_get(bak_b) = b;
unique_safe_get(bak_c) = c;
}
void restore_weights() {
w = *bak_w;
b = *bak_b;
c = *bak_c;
}
std::size_t input_size() const noexcept {
return num_visible;
}
std::size_t output_size() const noexcept {
return num_hidden;
}
std::size_t parameters() const noexcept {
return num_visible * num_hidden;
}
std::string to_short_string() const {
char buffer[1024];
snprintf(
buffer, 1024, "RBM(dyn)(%s): %lu -> %lu",
to_string(hidden_unit).c_str(), num_visible, num_hidden);
return {buffer};
}
void display() const {
std::cout << to_short_string() << std::endl;
}
// Make base class them participate in overload resolution
using base_type::activate_hidden;
template <bool P = true, bool S = true, typename H1, typename H2, typename V>
void activate_hidden(H1&& h_a, H2&& h_s, const V& v_a, const V& v_s) const {
etl::dyn_vector<weight> t(num_hidden);
activate_hidden(std::forward<H1>(h_a), std::forward<H2>(h_s), v_a, v_s, b, w, t);
}
template <bool P = true, bool S = true, typename H1, typename H2, typename V, typename T>
void activate_hidden(H1&& h_a, H2&& h_s, const V& v_a, const V& v_s, T&& t) const {
activate_hidden(std::forward<H1>(h_a), std::forward<H2>(h_s), v_a, v_s, b, w, std::forward<T>(t));
}
template <bool P = true, bool S = true, typename H1, typename H2, typename V, typename B, typename W>
void activate_hidden(H1&& h_a, H2&& h_s, const V& v_a, const V& v_s, const B& b, const W& w) const {
etl::dyn_vector<weight> t(num_hidden);
activate_hidden(std::forward<H1>(h_a), std::forward<H2>(h_s), v_a, v_s, b, w, t);
}
template <bool P = true, bool S = true, typename H1, typename H2, typename V, typename B, typename W, typename T>
void activate_hidden(H1&& h_a, H2&& h_s, const V& v_a, const V& v_s, const B& b, const W& w, T&& t) const {
cpp_assert(etl::size(h_a) == num_hidden, "Invalid h_a size");
cpp_assert(etl::size(h_s) == num_hidden, "Invalid h_s size");
cpp_assert(etl::size(v_a) == num_visible, "Invalid v_a size");
cpp_assert(etl::size(v_s) == num_visible, "Invalid v_s size");
cpp_assert(etl::size(t) == num_hidden, "Invalid t size");
base_type::template std_activate_hidden(std::forward<H1>(h_a), std::forward<H2>(h_s), v_a, v_s, b, w, std::forward<T>(t));
}
template <bool P = true, bool S = true, typename H, typename V>
void activate_visible(const H& h_a, const H& h_s, V&& v_a, V&& v_s) const {
etl::dyn_vector<weight> t(num_visible);
activate_visible(h_a, h_s, std::forward<V>(v_a), std::forward<V>(v_s), t);
}
template <bool P = true, bool S = true, typename H, typename V, typename T>
void activate_visible(const H& h_a, const H& h_s, V&& v_a, V&& v_s, T&& t) const {
cpp_assert(etl::size(h_a) == num_hidden, "Invalid h_a size");
cpp_assert(etl::size(h_s) == num_hidden, "Invalid h_s size");
cpp_assert(etl::size(v_a) == num_visible, "Invalid v_a size");
cpp_assert(etl::size(v_s) == num_visible, "Invalid v_s size");
cpp_assert(etl::size(t) == num_visible, "Invalid t size");
base_type::template std_activate_visible(h_a, h_s, std::forward<V>(v_a), std::forward<V>(v_s), c, w, std::forward<T>(t));
}
template <bool P = true, bool S = true, typename H1, typename H2, typename V>
void batch_activate_hidden(H1&& h_a, H2&& h_s, const V& v_a, const V& v_s) const {
base_type::template batch_std_activate_hidden<P, S>(std::forward<H1>(h_a), std::forward<H2>(h_s), v_a, v_s, b, w);
}
template <bool P = true, bool S = true, typename H, typename V>
void batch_activate_visible(const H& h_a, const H& h_s, V&& v_a, V&& v_s) const {
base_type::template batch_std_activate_visible<P, S>(h_a, h_s, std::forward<V>(v_a), std::forward<V>(v_s), c, w);
}
template <typename H, typename V>
void activate_hidden(H&& h_a, const V& v_a) const {
etl::dyn_matrix<weight, 1> t(num_hidden);
base_type::template std_activate_hidden<true, false>(std::forward<H>(h_a), std::forward<H>(h_a), v_a, v_a, b, w, t);
}
template <typename H, typename V>
void batch_activate_hidden(H&& h_a, const V& v_a) const {
base_type::template batch_std_activate_hidden<true, false>(std::forward<H>(h_a), std::forward<H>(h_a), v_a, v_a, b, w);
}
template <typename DBN>
void init_sgd_context() {
this->sgd_context_ptr = std::make_shared<sgd_context<DBN, this_type>>(num_visible, num_hidden);
}
void init_cg_context() {
if (!this->cg_context_ptr) {
this->cg_context_ptr = std::make_shared<cg_context<this_type>>(num_visible, num_hidden);
}
}
template <std::size_t B>
auto prepare_input_batch() const {
return etl::dyn_matrix<weight, 2>(B, num_visible);
}
template <std::size_t B>
auto prepare_output_batch() const {
return etl::dyn_matrix<weight, 2>(B, num_hidden);
}
};
/*!
* \brief Simple traits to pass information around from the real
* class to the CRTP class.
*/
template <typename Desc>
struct rbm_base_traits<dyn_rbm<Desc>> {
using desc = Desc;
using weight = typename desc::weight;
using input_one_t = etl::dyn_vector<weight>;
using output_one_t = etl::dyn_vector<weight>;
using input_t = std::vector<input_one_t>;
using output_t = std::vector<output_one_t>;
};
} //end of dll namespace
|
//=======================================================================
// 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 "etl/etl.hpp"
#include "standard_rbm.hpp"
namespace dll {
/*!
* \brief Standard version of Restricted Boltzmann Machine
*
* This follows the definition of a RBM by Geoffrey Hinton.
*/
template <typename Desc>
struct dyn_rbm final : public standard_rbm<dyn_rbm<Desc>, Desc> {
using desc = Desc;
using weight = typename desc::weight;
using this_type = dyn_rbm<Desc>;
using base_type = standard_rbm<this_type, Desc>;
static constexpr const unit_type visible_unit = desc::visible_unit;
static constexpr const unit_type hidden_unit = desc::hidden_unit;
using w_type = etl::dyn_matrix<weight>;
using b_type = etl::dyn_vector<weight>;
using c_type = etl::dyn_vector<weight>;
//Weights and biases
w_type w; //!< Weights
b_type b; //!< Hidden biases
c_type c; //!< Visible biases
//Backup weights and biases
std::unique_ptr<w_type> bak_w; //!< Backup Weights
std::unique_ptr<b_type> bak_b; //!< Backup Hidden biases
std::unique_ptr<c_type> bak_c; //!< Backup Visible biases
//Reconstruction data
etl::dyn_vector<weight> v1; //!< State of the visible units
etl::dyn_vector<weight> h1_a; //!< Activation probabilities of hidden units after first CD-step
etl::dyn_vector<weight> h1_s; //!< Sampled value of hidden units after first CD-step
etl::dyn_vector<weight> v2_a; //!< Activation probabilities of visible units after first CD-step
etl::dyn_vector<weight> v2_s; //!< Sampled value of visible units after first CD-step
etl::dyn_vector<weight> h2_a; //!< Activation probabilities of hidden units after last CD-step
etl::dyn_vector<weight> h2_s; //!< Sampled value of hidden units after last CD-step
template <std::size_t B>
using input_batch_t = etl::fast_dyn_matrix<weight, B, 1>; //TODO Check how to handle this
size_t num_visible;
size_t num_hidden;
size_t batch_size = 25;
//No copying
dyn_rbm(const dyn_rbm& rbm) = delete;
dyn_rbm& operator=(const dyn_rbm& rbm) = delete;
//No moving
dyn_rbm(dyn_rbm&& rbm) = delete;
dyn_rbm& operator=(dyn_rbm&& rbm) = delete;
dyn_rbm()
: base_type() {}
/*!
* \brief Initialize a RBM with basic weights.
*
* The weights are initialized from a normal distribution of
* zero-mean and 0.1 variance.
*/
dyn_rbm(size_t num_visible, size_t num_hidden)
: base_type(),
w(num_visible, num_hidden),
b(num_hidden, static_cast<weight>(0.0)),
c(num_visible, static_cast<weight>(0.0)),
v1(num_visible),
h1_a(num_hidden),
h1_s(num_hidden),
v2_a(num_visible),
v2_s(num_visible),
h2_a(num_hidden),
h2_s(num_hidden),
num_visible(num_visible),
num_hidden(num_hidden) {
//Initialize the weights with a zero-mean and unit variance Gaussian distribution
w = etl::normal_generator<weight>() * 0.1;
}
void init_layer(size_t nv, size_t nh) {
num_visible = nv;
num_hidden = nh;
w = etl::dyn_matrix<weight>(num_visible, num_hidden);
b = etl::dyn_vector<weight>(num_hidden, static_cast<weight>(0.0));
c = etl::dyn_vector<weight>(num_visible, static_cast<weight>(0.0));
v1 = etl::dyn_vector<weight>(num_visible);
h1_a = etl::dyn_vector<weight>(num_hidden);
h1_s = etl::dyn_vector<weight>(num_hidden);
v2_a = etl::dyn_vector<weight>(num_visible);
v2_s = etl::dyn_vector<weight>(num_visible);
h2_a = etl::dyn_vector<weight>(num_hidden);
h2_s = etl::dyn_vector<weight>(num_hidden);
//Initialize the weights with a zero-mean and unit variance Gaussian distribution
w = etl::normal_generator<weight>() * 0.1;
}
void backup_weights() {
unique_safe_get(bak_w) = w;
unique_safe_get(bak_b) = b;
unique_safe_get(bak_c) = c;
}
void restore_weights() {
w = *bak_w;
b = *bak_b;
c = *bak_c;
}
std::size_t input_size() const noexcept {
return num_visible;
}
std::size_t output_size() const noexcept {
return num_hidden;
}
std::size_t parameters() const noexcept {
return num_visible * num_hidden;
}
std::string to_short_string() const {
char buffer[1024];
snprintf(
buffer, 1024, "RBM(dyn)(%s): %lu -> %lu",
to_string(hidden_unit).c_str(), num_visible, num_hidden);
return {buffer};
}
void display() const {
std::cout << to_short_string() << std::endl;
}
// Make base class them participate in overload resolution
using base_type::activate_hidden;
template <bool P = true, bool S = true, typename H1, typename H2, typename V>
void activate_hidden(H1&& h_a, H2&& h_s, const V& v_a, const V& v_s) const {
etl::dyn_vector<weight> t(num_hidden);
activate_hidden(std::forward<H1>(h_a), std::forward<H2>(h_s), v_a, v_s, b, w, t);
}
template <bool P = true, bool S = true, typename H1, typename H2, typename V, typename T>
void activate_hidden(H1&& h_a, H2&& h_s, const V& v_a, const V& v_s, T&& t) const {
activate_hidden(std::forward<H1>(h_a), std::forward<H2>(h_s), v_a, v_s, b, w, std::forward<T>(t));
}
template <bool P = true, bool S = true, typename H1, typename H2, typename V, typename B, typename W>
void activate_hidden(H1&& h_a, H2&& h_s, const V& v_a, const V& v_s, const B& b, const W& w) const {
etl::dyn_vector<weight> t(num_hidden);
activate_hidden(std::forward<H1>(h_a), std::forward<H2>(h_s), v_a, v_s, b, w, t);
}
template <bool P = true, bool S = true, typename H1, typename H2, typename V, typename B, typename W, typename T>
void activate_hidden(H1&& h_a, H2&& h_s, const V& v_a, const V& v_s, const B& b, const W& w, T&& t) const {
cpp_assert(etl::size(h_a) == num_hidden, "Invalid h_a size");
cpp_assert(etl::size(h_s) == num_hidden, "Invalid h_s size");
cpp_assert(etl::size(v_a) == num_visible, "Invalid v_a size");
cpp_assert(etl::size(v_s) == num_visible, "Invalid v_s size");
cpp_assert(etl::size(t) == num_hidden, "Invalid t size");
base_type::template std_activate_hidden(std::forward<H1>(h_a), std::forward<H2>(h_s), v_a, v_s, b, w, std::forward<T>(t));
}
template <bool P = true, bool S = true, typename H, typename V>
void activate_visible(const H& h_a, const H& h_s, V&& v_a, V&& v_s) const {
etl::dyn_vector<weight> t(num_visible);
activate_visible(h_a, h_s, std::forward<V>(v_a), std::forward<V>(v_s), t);
}
template <bool P = true, bool S = true, typename H, typename V, typename T>
void activate_visible(const H& h_a, const H& h_s, V&& v_a, V&& v_s, T&& t) const {
cpp_assert(etl::size(h_a) == num_hidden, "Invalid h_a size");
cpp_assert(etl::size(h_s) == num_hidden, "Invalid h_s size");
cpp_assert(etl::size(v_a) == num_visible, "Invalid v_a size");
cpp_assert(etl::size(v_s) == num_visible, "Invalid v_s size");
cpp_assert(etl::size(t) == num_visible, "Invalid t size");
base_type::template std_activate_visible(h_a, h_s, std::forward<V>(v_a), std::forward<V>(v_s), c, w, std::forward<T>(t));
}
template <bool P = true, bool S = true, typename H1, typename H2, typename V>
void batch_activate_hidden(H1&& h_a, H2&& h_s, const V& v_a, const V& v_s) const {
base_type::template batch_std_activate_hidden<P, S>(std::forward<H1>(h_a), std::forward<H2>(h_s), v_a, v_s, b, w);
}
template <bool P = true, bool S = true, typename H, typename V>
void batch_activate_visible(const H& h_a, const H& h_s, V&& v_a, V&& v_s) const {
base_type::template batch_std_activate_visible<P, S>(h_a, h_s, std::forward<V>(v_a), std::forward<V>(v_s), c, w);
}
template <typename H, typename V, cpp_enable_if(etl::decay_traits<V>::dimensions() == 1)>
void activate_hidden(H&& h_a, const V& v_a) const {
etl::dyn_matrix<weight, 1> t(num_hidden);
base_type::template std_activate_hidden<true, false>(std::forward<H>(h_a), std::forward<H>(h_a), v_a, v_a, b, w, t);
}
template <typename H, typename V, cpp_enable_if(etl::decay_traits<V>::dimensions() != 1)>
void activate_hidden(H&& h_a, const V& v_a) const {
activate_hidden(h_a, etl::reshape(v_a, num_visible));
}
template <typename H, typename V, cpp_enable_if(etl::decay_traits<V>::dimensions() == 2)>
void batch_activate_hidden(H&& h_a, const V& v_a) const {
base_type::template batch_std_activate_hidden<true, false>(std::forward<H>(h_a), std::forward<H>(h_a), v_a, v_a, b, w);
}
template <typename H, typename V, cpp_enable_if(etl::decay_traits<V>::dimensions() != 2)>
void batch_activate_hidden(H&& h_a, const V& v_a) const {
batch_activate_hidden(h_a, etl::reshape(v_a, etl::dim<0>(h_a), num_visible));
}
template <typename DBN>
void init_sgd_context() {
this->sgd_context_ptr = std::make_shared<sgd_context<DBN, this_type>>(num_visible, num_hidden);
}
void init_cg_context() {
if (!this->cg_context_ptr) {
this->cg_context_ptr = std::make_shared<cg_context<this_type>>(num_visible, num_hidden);
}
}
template <std::size_t B>
auto prepare_input_batch() const {
return etl::dyn_matrix<weight, 2>(B, num_visible);
}
template <std::size_t B>
auto prepare_output_batch() const {
return etl::dyn_matrix<weight, 2>(B, num_hidden);
}
};
/*!
* \brief Simple traits to pass information around from the real
* class to the CRTP class.
*/
template <typename Desc>
struct rbm_base_traits<dyn_rbm<Desc>> {
using desc = Desc;
using weight = typename desc::weight;
using input_one_t = etl::dyn_vector<weight>;
using output_one_t = etl::dyn_vector<weight>;
using input_t = std::vector<input_one_t>;
using output_t = std::vector<output_one_t>;
};
} //end of dll namespace
|
Support input flattening
|
Support input flattening
|
C++
|
mit
|
wichtounet/dll,wichtounet/dll,wichtounet/dll
|
2859755bd3911bdd69ff75a99733f7d0a7f58989
|
excercise04/sort/quick/type_b.cpp
|
excercise04/sort/quick/type_b.cpp
|
#include "../quick.hpp"
#include "../swap.hpp"
void quick(int *data, const int size_of_data)
{
return quick(data, 0, size_of_data - 1);
}
void quick(int *data, const int start, const int end)
{
int size = end - start + 1;
if(start >= end) return; /* Base case */
/* Conquer */
int pivot = partition(data, start, end);
/* Divide */
quick(data, start, pe - 1);
quick(data, pe + 1, end);
}
int partition(int *data, const int start, const int end)
{
int pivot = end; /* Set pivot */
int ps = start, pe = end - 1;
while(ps < pe)
{
while(ps < pe && data[ps] < data[pivot]) ++ps;
while(ps < pe && data[pe] >= data[pivot]) --pe;
if(ps < pe) swap(data[ps], data[pe]);
}
if(data[pe] > data[pivot])
swap(data[pe], data[pivot]);
else if(pe == end - 1)
++pe;
return pe;
}
|
#include "../quick.hpp"
#include "../swap.hpp"
void quick(int *data, const int size_of_data)
{
return quick(data, 0, size_of_data - 1);
}
void quick(int *data, const int start, const int end)
{
int size = end - start + 1;
if(start >= end) return; /* Base case */
/* Conquer */
int pivot = partition(data, start, end);
/* Divide */
quick(data, start, pivot - 1);
quick(data, pivot + 1, end);
}
int partition(int *data, const int start, const int end)
{
int pivot = end; /* Set pivot */
int ps = start, pe = end - 1;
while(ps < pe)
{
while(ps < pe && data[ps] < data[pivot]) ++ps;
while(ps < pe && data[pe] >= data[pivot]) --pe;
if(ps < pe) swap(data[ps], data[pe]);
}
if(data[pe] > data[pivot])
swap(data[pe], data[pivot]);
else if(pe == end - 1)
++pe;
return pe;
}
|
Fix bug which variable name is not match
|
Fix bug which variable name is not match
|
C++
|
mit
|
kdzlvaids/algorithm_and_practice-pknu-2016,kdzlvaids/algorithm_and_practice-pknu-2016
|
e12689aca372ab4b2d317c84f6fba4a27ef490d3
|
tests/src/read_circuit_test.cpp
|
tests/src/read_circuit_test.cpp
|
#include "read_circuit.h"
#include "circuit.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace qflex {
namespace {
using ::testing::Eq;
using ::testing::Pointwise;
// This circuit is missing the number of active qubits as its first line.
constexpr char kMissingNumQubitsCircuit[] = R"(
0 h 0
0 h 1)";
constexpr char kWrongNumQubitsCircuit[] = R"(3
0 h 0
0 h 1)";
TEST(ReadCircuitDeathTest, InvalidNumberOfQubits) {
std::vector<std::vector<std::vector<Tensor>>> grid_of_tensors;
s_type scratch[256];
QflexCircuit circuit;
circuit.load(std::stringstream(kMissingNumQubitsCircuit));
EXPECT_DEATH(
circuit_data_to_tensor_network(circuit, 2, 1, "00", "01", {},
{}, grid_of_tensors, scratch),
"");
circuit.load(std::stringstream(kWrongNumQubitsCircuit));
EXPECT_DEATH(
circuit_data_to_tensor_network(circuit, 2, 1, "00", "01", {},
{}, grid_of_tensors, scratch),
"");
}
// This circuit has an invalid one-qubit gate.
constexpr char kBadCircuit[] = R"(2
0 h 0
0 h 1
1 badgate 0)";
TEST(ReadCircuitDeathTest, BadOneQubitGate) {
std::vector<std::vector<std::vector<Tensor>>> grid_of_tensors;
s_type scratch[256];
QflexCircuit circuit;
circuit.load(std::stringstream(kBadCircuit));
EXPECT_DEATH(
circuit_data_to_tensor_network(circuit, 2, 1, "00", "01", {},
{}, grid_of_tensors, scratch),
"");
}
// This circuit has an invalid fsim-type gate.
constexpr char kBadFsimCircuit[] = R"(2
0 h 0
0 h 1
1 fsimbadgate 0 1)";
TEST(ReadCircuitDeathTest, BadFsimGate) {
std::vector<std::vector<std::vector<Tensor>>> grid_of_tensors;
s_type scratch[256];
QflexCircuit circuit;
circuit.load(std::stringstream(kBadFsimCircuit));
EXPECT_DEATH(
circuit_data_to_tensor_network(circuit, 2, 1, "00", "01", {},
{}, grid_of_tensors, scratch),
"");
}
// These circuits reference inactive qubits.
constexpr char kBadTGate[] = R"(2
1 t 0)";
constexpr char kBadCzGate[] = R"(2
1 cz 0 1)";
constexpr char kBadCxGate[] = R"(2
1 cx 0 1)";
TEST(ReadCircuitTest, CircuitReferencingInactiveQubits) {
std::vector<std::vector<std::vector<Tensor>>> grid_of_tensors;
std::vector<std::vector<int>> off_qubits = {{0, 0}};
s_type scratch[256];
// One qubit gate must be on active qubit.
QflexCircuit circuit;
circuit.load(std::stringstream(kBadTGate));
EXPECT_DEATH(
circuit_data_to_tensor_network(circuit, 2, 1, "0", "1", {},
off_qubits, grid_of_tensors, scratch),
"");
// Two qubit gate must have active qubit as first qubit input.
circuit.load(std::stringstream(kBadCzGate));
EXPECT_DEATH(
circuit_data_to_tensor_network(circuit, 2, 1, "0", "1", {},
off_qubits, grid_of_tensors, scratch),
"");
// Two qubit gate must have active qubit as first qubit input.
circuit.load(std::stringstream(kBadCxGate));
EXPECT_DEATH(
circuit_data_to_tensor_network(circuit, 2, 1, "0", "1", {},
off_qubits, grid_of_tensors, scratch),
"");
// Two qubit gate must have active qubit as second qubit input.
off_qubits = {{1, 0}};
EXPECT_DEATH(
circuit_data_to_tensor_network(circuit, 2, 1, "0", "1", {},
off_qubits, grid_of_tensors, scratch),
"");
}
constexpr char kBadCycle1[] = R"(4
1 t 1
1 t 1)";
constexpr char kBadCycle2[] = R"(4
1 t 1
1 cz 1 2)";
constexpr char kBadCycle3[] = R"(4
1 t 2
1 cz 1 2)";
constexpr char kBadCycle4[] = R"(4
1 cz 1 2
1 cz 1 3)";
constexpr char kBadCycle5[] = R"(4
1 cz 1 3
1 cz 2 3)";
TEST(ReadCircuitDeathTest, MultipleGatesPerQubitPerCycle) {
std::vector<std::vector<std::vector<Tensor>>> grid_of_tensors;
std::vector<std::vector<int>> off_qubits = {{0, 0}};
s_type scratch[256];
QflexCircuit circuit;
EXPECT_ANY_THROW(circuit.load(std::stringstream(kBadCycle1)));
EXPECT_ANY_THROW(circuit.load(std::stringstream(kBadCycle2)));
EXPECT_ANY_THROW(circuit.load(std::stringstream(kBadCycle3)));
EXPECT_ANY_THROW(circuit.load(std::stringstream(kBadCycle4)));
EXPECT_ANY_THROW(circuit.load(std::stringstream(kBadCycle5)));
}
// This circuit returns the input string with amplitude 1.
constexpr char kNullCircuit[] = R"(2
0 h 0
0 h 1
9 h 0
9 h 1)";
// Verifies that circuits can be read from file and the resulting gates match
// the expected circuit.
TEST(ReadCircuitTest, NullCircuit) {
std::vector<std::vector<std::vector<Tensor>>> grid_of_tensors;
s_type scratch[256];
QflexCircuit circuit;
circuit.load(std::stringstream(kNullCircuit));
circuit_data_to_tensor_network(circuit, 2, 1, "00", "01", {}, {},
grid_of_tensors, scratch);
// Qubit-0 path has amplitude 1 (0 --> 0)
// Qubit-1 path has amplitude 0 (0 --> 1)
std::vector<s_type> expected_data = {std::complex<float>(1, 0),
std::complex<float>(0, 0)};
// Resulting tensor grid should be 2x1x1 (IxJxK).
ASSERT_EQ(grid_of_tensors.size(), 2);
for (int i = 0; i < 2; i++) {
ASSERT_EQ(grid_of_tensors[i].size(), 1);
// TODO: tensors are not homogeneous anymore.
//ASSERT_EQ(grid_of_tensors[i][0].size(), 1);
//ASSERT_EQ(grid_of_tensors[i][0][0].size(), 1);
// TODO: tensors are not homogeneous anymore.
//const std::vector<s_type> data(grid_of_tensors[i][0][0].data(),
// grid_of_tensors[i][0][0].data() + 1);
// Testing exact equality of floating-point types will fail.
// Instead, we use EXPECT_FLOAT_EQ on each component of the data.
//EXPECT_FLOAT_EQ(data[0].real(), expected_data[i].real());
//EXPECT_FLOAT_EQ(data[0].imag(), expected_data[i].imag());
}
}
// Simple grid with one "off" qubit and one cut:
// 0 - 1
// | x --> cut between (0,1) and (1,1)
// 2 - 3
// |
// 4 5 --> qubit at (2,0) is off; (2,1) is in final region.
// This circuit should return the input string with amplitude ~= 1 when summing
// over the cut values, but only when the output of (2,1) is a zero.
constexpr char kSimpleCircuit[] = R"(5
0 h 0
0 h 1
0 h 2
0 h 3
0 h 5
1 cz 0 1
2 cx 0 2
3 cx 1 3
4 cz 2 3
5 cz 3 5
11 cz 0 1
12 cx 0 2
13 cx 1 3
14 cz 2 3
15 cx 3 5
17 h 0
17 h 1
17 h 2
17 h 3
17 h 5)";
// Verifies that collapsing the 3D tensor network to a 2D grid behaves as
// expected.
TEST(ReadCircuitTest, CondenseToGrid) {
std::vector<std::vector<std::vector<Tensor>>> tensor_grid_3D;
std::vector<std::vector<int>> qubits_A = {{2, 1}};
std::vector<std::vector<int>> qubits_off = {{2, 0}};
s_type* scratch = new s_type[256];
QflexCircuit circuit;
circuit.load(std::stringstream(kSimpleCircuit));
circuit_data_to_tensor_network(circuit, 3, 2, "00000", "0000x",
qubits_A, qubits_off, tensor_grid_3D,
scratch);
ASSERT_EQ(tensor_grid_3D.size(), 3);
for(const auto &g: tensor_grid_3D) ASSERT_EQ(g.size(), 2);
// TODO: tensors are not homogeneous anymore.
//ASSERT_EQ(tensor_grid_3D[0][0].size(), 2);
std::vector<std::vector<Tensor>> tensor_grid_2D;
for (int i = 0; i < 3; ++i) {
tensor_grid_2D.push_back(std::vector<Tensor>(2));
}
// Working from either end, create two patches and meet in the middle.
std::list<ContractionOperation> ordering;
ordering.emplace_back(CutIndex({{0, 1}, {1, 1}}));
ordering.emplace_back(ExpandPatch("a", {0, 1}));
ordering.emplace_back(ExpandPatch("a", {0, 0}));
ordering.emplace_back(ExpandPatch("a", {1, 0}));
ordering.emplace_back(CutIndex({{2, 1}}));
ordering.emplace_back(ExpandPatch("b", {2, 1}));
ordering.emplace_back(ExpandPatch("b", {1, 1}));
ordering.emplace_back(MergePatches("a", "b"));
flatten_grid_of_tensors(tensor_grid_3D, tensor_grid_2D, qubits_A, qubits_off,
ordering, scratch);
// Verify that index ordering follows this pattern:
// 1) Final-region indices ("<index>,(o)")
// 2) Cut indices
// 3) Same-patch indices in order by index
// 4) Cross-patch indices in order by patch
std::vector<std::vector<std::vector<std::string>>> expected_indices = {
{
// qubit (0,0) - normal
{"(0,0),(0,1)", "(0,0),(1,0)"},
// qubit (0,1) - cut index
{"(0,1),(1,1)", "(0,0),(0,1)"},
},
{
// qubit (1,0) - cross-patch index
{"(0,0),(1,0)", "(1,0),(1,1)"},
// qubit (1,1) - cut index and cross-patch index
{"(0,1),(1,1)", "(1,1),(2,1)", "(1,0),(1,1)"},
},
{
// qubit (2,0) - off
{},
// qubit (2,1) - final-region index
{"(2,1),(o)", "(1,1),(2,1)"},
},
};
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 2; ++j) {
ASSERT_EQ(tensor_grid_2D[i][j].get_indices(), expected_indices[i][j]);
}
}
}
TEST(ReadCircuitDeathTest, CircuitDataToGridOfTensorsInvalidInput) {
std::vector<std::vector<std::vector<Tensor>>> grid_of_tensors;
s_type scratch[256];
QflexCircuit circuit;
circuit.load(std::stringstream(kNullCircuit));
// Scratch cannot be null pointer.
EXPECT_DEATH(
circuit_data_to_tensor_network(circuit, 2, 1, "01", "01", {},
{}, grid_of_tensors, nullptr),
"");
// Input configuration length must be equal to the number of qubits.
EXPECT_DEATH(
circuit_data_to_tensor_network(circuit, 2, 1, "001", "01", {},
{}, grid_of_tensors, scratch),
"");
// Output configuration length must be equal to the number of qubits.
EXPECT_DEATH(
circuit_data_to_tensor_network(circuit, 2, 1, "00", "011", {},
{}, grid_of_tensors, scratch),
"");
}
TEST(ReadCircuitDeathTest, GridOfTensors3DTo2DInvalidInput) {
std::vector<std::vector<std::vector<Tensor>>> grid_of_tensors_3D;
std::vector<std::vector<Tensor>> grid_of_tensors_2D;
std::optional<std::vector<std::vector<int>>> A;
std::optional<std::vector<std::vector<int>>> off;
std::list<ContractionOperation> ordering;
// Scratch cannot be null pointer.
EXPECT_DEATH(flatten_grid_of_tensors(grid_of_tensors_3D, grid_of_tensors_2D,
A, off, ordering, nullptr),
"");
}
} // namespace
} // namespace qflex
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
#include "read_circuit.h"
#include "circuit.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace qflex {
namespace {
using ::testing::Eq;
using ::testing::Pointwise;
// This circuit is missing the number of active qubits as its first line.
constexpr char kMissingNumQubitsCircuit[] = R"(
0 h 0
0 h 1)";
constexpr char kWrongNumQubitsCircuit[] = R"(3
0 h 0
0 h 1)";
TEST(ReadCircuitDeathTest, InvalidNumberOfQubits) {
std::vector<std::vector<std::vector<Tensor>>> grid_of_tensors;
s_type scratch[256];
QflexCircuit circuit;
circuit.load(std::stringstream(kMissingNumQubitsCircuit));
EXPECT_DEATH(
circuit_data_to_tensor_network(circuit, 2, 1, "00", "01", {},
{}, grid_of_tensors, scratch),
"");
circuit.load(std::stringstream(kWrongNumQubitsCircuit));
EXPECT_DEATH(
circuit_data_to_tensor_network(circuit, 2, 1, "00", "01", {},
{}, grid_of_tensors, scratch),
"");
}
// This circuit has an invalid one-qubit gate.
constexpr char kBadCircuit[] = R"(2
0 h 0
0 h 1
1 badgate 0)";
TEST(ReadCircuitDeathTest, BadOneQubitGate) {
std::vector<std::vector<std::vector<Tensor>>> grid_of_tensors;
s_type scratch[256];
QflexCircuit circuit;
circuit.load(std::stringstream(kBadCircuit));
EXPECT_DEATH(
circuit_data_to_tensor_network(circuit, 2, 1, "00", "01", {},
{}, grid_of_tensors, scratch),
"");
}
// This circuit has an invalid fsim-type gate.
constexpr char kBadFsimCircuit[] = R"(2
0 h 0
0 h 1
1 fsimbadgate 0 1)";
TEST(ReadCircuitDeathTest, BadFsimGate) {
std::vector<std::vector<std::vector<Tensor>>> grid_of_tensors;
s_type scratch[256];
QflexCircuit circuit;
circuit.load(std::stringstream(kBadFsimCircuit));
EXPECT_DEATH(
circuit_data_to_tensor_network(circuit, 2, 1, "00", "01", {},
{}, grid_of_tensors, scratch),
"");
}
// These circuits reference inactive qubits.
constexpr char kBadTGate[] = R"(2
1 t 0)";
constexpr char kBadCzGate[] = R"(2
1 cz 0 1)";
constexpr char kBadCxGate[] = R"(2
1 cx 0 1)";
TEST(ReadCircuitTest, CircuitReferencingInactiveQubits) {
std::vector<std::vector<std::vector<Tensor>>> grid_of_tensors;
std::vector<std::vector<int>> off_qubits = {{0, 0}};
s_type scratch[256];
// One qubit gate must be on active qubit.
QflexCircuit circuit;
circuit.load(std::stringstream(kBadTGate));
EXPECT_DEATH(
circuit_data_to_tensor_network(circuit, 2, 1, "0", "1", {},
off_qubits, grid_of_tensors, scratch),
"");
// Two qubit gate must have active qubit as first qubit input.
circuit.load(std::stringstream(kBadCzGate));
EXPECT_DEATH(
circuit_data_to_tensor_network(circuit, 2, 1, "0", "1", {},
off_qubits, grid_of_tensors, scratch),
"");
// Two qubit gate must have active qubit as first qubit input.
circuit.load(std::stringstream(kBadCxGate));
EXPECT_DEATH(
circuit_data_to_tensor_network(circuit, 2, 1, "0", "1", {},
off_qubits, grid_of_tensors, scratch),
"");
// Two qubit gate must have active qubit as second qubit input.
off_qubits = {{1, 0}};
EXPECT_DEATH(
circuit_data_to_tensor_network(circuit, 2, 1, "0", "1", {},
off_qubits, grid_of_tensors, scratch),
"");
}
constexpr char kBadCycle1[] = R"(4
1 t 1
1 t 1)";
constexpr char kBadCycle2[] = R"(4
1 t 1
1 cz 1 2)";
constexpr char kBadCycle3[] = R"(4
1 t 2
1 cz 1 2)";
constexpr char kBadCycle4[] = R"(4
1 cz 1 2
1 cz 1 3)";
constexpr char kBadCycle5[] = R"(4
1 cz 1 3
1 cz 2 3)";
TEST(ReadCircuitDeathTest, MultipleGatesPerQubitPerCycle) {
std::vector<std::vector<std::vector<Tensor>>> grid_of_tensors;
std::vector<std::vector<int>> off_qubits = {{0, 0}};
s_type scratch[256];
QflexCircuit circuit;
EXPECT_ANY_THROW(circuit.load(std::stringstream(kBadCycle1)));
EXPECT_ANY_THROW(circuit.load(std::stringstream(kBadCycle2)));
EXPECT_ANY_THROW(circuit.load(std::stringstream(kBadCycle3)));
EXPECT_ANY_THROW(circuit.load(std::stringstream(kBadCycle4)));
EXPECT_ANY_THROW(circuit.load(std::stringstream(kBadCycle5)));
}
// This circuit returns the input string with amplitude 1.
constexpr char kNullCircuit[] = R"(2
0 h 0
0 h 1
9 h 0
9 h 1)";
// Verifies that circuits can be read from file and the resulting gates match
// the expected circuit.
TEST(ReadCircuitTest, NullCircuit) {
std::vector<std::vector<std::vector<Tensor>>> grid_of_tensors;
s_type scratch[256];
QflexCircuit circuit;
circuit.load(std::stringstream(kNullCircuit));
circuit_data_to_tensor_network(circuit, 2, 1, "00", "10", {}, {},
grid_of_tensors, scratch);
// Qubit-0 path has amplitude 1 (0 --> 0)
// Qubit-1 path has amplitude 0 (0 --> 1)
std::vector<s_type> expected_data = {std::complex<float>(1, 0),
std::complex<float>(0, 0)};
// Resulting tensor grid should be 2x1 (IxJ) ..
ASSERT_EQ(std::size(grid_of_tensors), 2);
for(std::size_t i = 0; i < 2; ++i) {
const auto &tensor = grid_of_tensors[i];
ASSERT_EQ(std::size(tensor), 1);
// .. and each qubit tensor should have 4 tensors ..
for(const auto &t: tensor) {
ASSERT_EQ(std::size(t), 4);
// .. of size 1, 2, 2, 1 (x2, because of complex numbers) respectively
ASSERT_EQ(std::size(t[0]), 1 * 2);
ASSERT_EQ(std::size(t[1]), 2 * 2);
ASSERT_EQ(std::size(t[2]), 2 * 2);
ASSERT_EQ(std::size(t[3]), 1 * 2);
// Each qubit tensor should have 4 elements (delta_0, h, h, delta_0)
// and (delta_0, h, h, delta_1) respectively
ASSERT_EQ(t[0].data()[0], std::complex<float>(1,0));
ASSERT_EQ(t[1].data()[0], std::complex<float>(1./M_SQRT2,0));
ASSERT_EQ(t[1].data()[1], std::complex<float>(1./M_SQRT2,0));
ASSERT_EQ(t[2].data()[0], std::complex<float>(1./M_SQRT2,0));
ASSERT_EQ(t[2].data()[1], std::complex<float>(1./M_SQRT2,0));
ASSERT_EQ(t[3].data()[0], std::complex<float>(i,0));
}
}
}
// Simple grid with one "off" qubit and one cut:
// 0 - 1
// | x --> cut between (0,1) and (1,1)
// 2 - 3
// |
// 4 5 --> qubit at (2,0) is off; (2,1) is in final region.
// This circuit should return the input string with amplitude ~= 1 when summing
// over the cut values, but only when the output of (2,1) is a zero.
constexpr char kSimpleCircuit[] = R"(5
0 h 0
0 h 1
0 h 2
0 h 3
0 h 5
1 cz 0 1
2 cx 0 2
3 cx 1 3
4 cz 2 3
5 cz 3 5
11 cz 0 1
12 cx 0 2
13 cx 1 3
14 cz 2 3
15 cx 3 5
17 h 0
17 h 1
17 h 2
17 h 3
17 h 5)";
// Verifies that collapsing the 3D tensor network to a 2D grid behaves as
// expected.
TEST(ReadCircuitTest, CondenseToGrid) {
std::vector<std::vector<std::vector<Tensor>>> tensor_grid_3D;
std::vector<std::vector<int>> qubits_A = {{2, 1}};
std::vector<std::vector<int>> qubits_off = {{2, 0}};
s_type* scratch = new s_type[256];
QflexCircuit circuit;
circuit.load(std::stringstream(kSimpleCircuit));
circuit_data_to_tensor_network(circuit, 3, 2, "00000", "0000x",
qubits_A, qubits_off, tensor_grid_3D,
scratch);
ASSERT_EQ(tensor_grid_3D.size(), 3);
for(const auto &g: tensor_grid_3D) ASSERT_EQ(g.size(), 2);
// TODO: qFlex does not rely anymore on super-cycle blocks.
//ASSERT_EQ(tensor_grid_3D[0][0].size(), 2);
std::vector<std::vector<Tensor>> tensor_grid_2D;
for (int i = 0; i < 3; ++i) {
tensor_grid_2D.push_back(std::vector<Tensor>(2));
}
// Working from either end, create two patches and meet in the middle.
std::list<ContractionOperation> ordering;
ordering.emplace_back(CutIndex({{0, 1}, {1, 1}}));
ordering.emplace_back(ExpandPatch("a", {0, 1}));
ordering.emplace_back(ExpandPatch("a", {0, 0}));
ordering.emplace_back(ExpandPatch("a", {1, 0}));
ordering.emplace_back(CutIndex({{2, 1}}));
ordering.emplace_back(ExpandPatch("b", {2, 1}));
ordering.emplace_back(ExpandPatch("b", {1, 1}));
ordering.emplace_back(MergePatches("a", "b"));
flatten_grid_of_tensors(tensor_grid_3D, tensor_grid_2D, qubits_A, qubits_off,
ordering, scratch);
// Verify that index ordering follows this pattern:
// 1) Final-region indices ("<index>,(o)")
// 2) Cut indices
// 3) Same-patch indices in order by index
// 4) Cross-patch indices in order by patch
std::vector<std::vector<std::vector<std::string>>> expected_indices = {
{
// qubit (0,0) - normal
{"(0,0),(0,1)", "(0,0),(1,0)"},
// qubit (0,1) - cut index
{"(0,1),(1,1)", "(0,0),(0,1)"},
},
{
// qubit (1,0) - cross-patch index
{"(0,0),(1,0)", "(1,0),(1,1)"},
// qubit (1,1) - cut index and cross-patch index
{"(0,1),(1,1)", "(1,1),(2,1)", "(1,0),(1,1)"},
},
{
// qubit (2,0) - off
{},
// qubit (2,1) - final-region index
{"(2,1),(o)", "(1,1),(2,1)"},
},
};
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 2; ++j) {
ASSERT_EQ(tensor_grid_2D[i][j].get_indices(), expected_indices[i][j]);
}
}
}
TEST(ReadCircuitDeathTest, CircuitDataToGridOfTensorsInvalidInput) {
std::vector<std::vector<std::vector<Tensor>>> grid_of_tensors;
s_type scratch[256];
QflexCircuit circuit;
circuit.load(std::stringstream(kNullCircuit));
// Scratch cannot be null pointer.
EXPECT_DEATH(
circuit_data_to_tensor_network(circuit, 2, 1, "01", "01", {},
{}, grid_of_tensors, nullptr),
"");
// Input configuration length must be equal to the number of qubits.
EXPECT_DEATH(
circuit_data_to_tensor_network(circuit, 2, 1, "001", "01", {},
{}, grid_of_tensors, scratch),
"");
// Output configuration length must be equal to the number of qubits.
EXPECT_DEATH(
circuit_data_to_tensor_network(circuit, 2, 1, "00", "011", {},
{}, grid_of_tensors, scratch),
"");
}
TEST(ReadCircuitDeathTest, GridOfTensors3DTo2DInvalidInput) {
std::vector<std::vector<std::vector<Tensor>>> grid_of_tensors_3D;
std::vector<std::vector<Tensor>> grid_of_tensors_2D;
std::optional<std::vector<std::vector<int>>> A;
std::optional<std::vector<std::vector<int>>> off;
std::list<ContractionOperation> ordering;
// Scratch cannot be null pointer.
EXPECT_DEATH(flatten_grid_of_tensors(grid_of_tensors_3D, grid_of_tensors_2D,
A, off, ordering, nullptr),
"");
}
} // namespace
} // namespace qflex
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
|
Fix test.
|
Fix test.
|
C++
|
apache-2.0
|
ngnrsaa/qflex,ngnrsaa/qflex,ngnrsaa/qflex,ngnrsaa/qflex
|
e645ef2d47b66a6bb7be48b770a7ebaa296714cb
|
tests/test_member_iterator2.cpp
|
tests/test_member_iterator2.cpp
|
#include "catch.hpp"
#include <utility>
#include <type_traits>
#include <iterator>
#include <algorithm>
#include <member_iterator.hpp>
#include <forward_list>
TEST_CASE("member_iterator based on ForwardIterator", "[member_iterator]")
{
struct mock
{
char c;
int i;
};
std::forward_list<mock> mocklist{{'a', 1}, {'b', 2}, {'c', 3}};
typedef helene::
member_iterator<int, mock, std::forward_list<mock>::iterator, &mock::i>
mocklist_iterator_type;
mocklist_iterator_type beg_it = mocklist.begin();
mocklist_iterator_type end_it = mocklist.end();
////////////////////////////////////////////////////////////////////////////
// Iterator concept
SECTION("construction")
{
auto elem = *beg_it;
mocklist_iterator_type cop_it = beg_it;
mocklist_iterator_type mov_it = std::move(beg_it);
REQUIRE(*mov_it == elem);
REQUIRE(cop_it == mov_it);
}
SECTION("assignment")
{
mocklist_iterator_type cop_it = beg_it;
cop_it = end_it;
REQUIRE(cop_it == end_it);
}
SECTION("move assignment")
{
mocklist_iterator_type an_it = beg_it;
mocklist_iterator_type another_it = end_it;
another_it = std::move(an_it);
REQUIRE(another_it == beg_it);
REQUIRE(*another_it == *beg_it);
}
SECTION("swappable")
{
using std::swap;
mocklist_iterator_type beg_it2 = beg_it;
mocklist_iterator_type end_it2 = end_it;
swap(beg_it2, end_it2);
REQUIRE(beg_it2 == end_it);
REQUIRE(end_it2 == beg_it);
}
SECTION("traits")
{
std::iterator_traits<mocklist_iterator_type>::value_type i = 20;
std::iterator_traits<mocklist_iterator_type>::difference_type j = -2;
std::iterator_traits<mocklist_iterator_type>::reference k = i;
std::iterator_traits<mocklist_iterator_type>::pointer l = &i;
bool is_forward_iterator = std::is_same<
std::iterator_traits<mocklist_iterator_type>::iterator_category,
std::forward_iterator_tag>::value;
REQUIRE(is_forward_iterator == true);
}
SECTION("dereference")
{
auto is_reference = std::is_same<decltype(*beg_it), int&>::value;
REQUIRE(is_reference == true);
REQUIRE(*beg_it == 1);
}
SECTION("preincrement")
{
auto ref_it = ++beg_it;
bool is_iterator_reference =
std::is_same<decltype(++beg_it), mocklist_iterator_type&>::value;
REQUIRE(ref_it == beg_it);
REQUIRE(*beg_it == 2);
REQUIRE(is_iterator_reference == true);
}
SECTION("EqualityComparable")
{
bool equal = beg_it == end_it;
REQUIRE(equal == false);
REQUIRE(beg_it == mocklist.begin());
}
////////////////////////////////////////////////////////////////////////////
// InputIterator
SECTION("!=")
{
bool not_equal = beg_it != mocklist.begin();
REQUIRE(beg_it != end_it);
REQUIRE(not_equal == false);
}
SECTION("postincrement")
{
bool is_conv_to_const_ref =
std::is_convertible<decltype(beg_it++),
const mocklist_iterator_type&>::value;
(void)beg_it++;
REQUIRE(is_conv_to_const_ref == true);
REQUIRE(*beg_it == 2);
}
SECTION("postincrement and dereference")
{
bool is_conv_to_value_type =
std::is_convertible<decltype(*beg_it++), int>::value;
auto val = *beg_it++;
REQUIRE(is_conv_to_value_type == true);
REQUIRE(val == 1);
REQUIRE(*beg_it == 2);
}
////////////////////////////////////////////////////////////////////////////
// OutputIterator
SECTION("assignment through iterator")
{
*beg_it = 10;
REQUIRE(*beg_it == 10);
REQUIRE(mocklist.front().i == 10);
REQUIRE(mocklist.front().c == 'a');
}
////////////////////////////////////////////////////////////////////////////
// ForwardIterator
SECTION("DefaultConstructible")
{
mocklist_iterator_type it;
mocklist_iterator_type it2{};
mocklist_iterator_type();
mocklist_iterator_type{};
}
SECTION("multipass guarantee")
{
auto beg_it_copy = beg_it;
++beg_it;
++beg_it;
auto val0 = *beg_it_copy++;
auto val1 = *beg_it_copy++;
auto val2 = *beg_it_copy;
REQUIRE(val0 == 1);
REQUIRE(val1 == 2);
REQUIRE(val2 == 3);
}
////////////////////////////////////////////////////////////////////////////
// Test std algorithms
SECTION("std::equal")
{
std::forward_list<mock> mocklist_copy = mocklist;
mocklist_iterator_type beg_it_copy(mocklist_copy.begin());
REQUIRE(std::equal(beg_it, end_it, beg_it_copy) == true);
}
SECTION("std::find")
{
auto found = std::find(beg_it, end_it, 2);
REQUIRE(found != end_it);
}
SECTION("std::for_each")
{
int sum = 0;
std::for_each(beg_it, end_it, [&sum](int i) { sum += i; });
REQUIRE(sum == 6);
}
SECTION("std::search") // requires ForwardIterator
{
std::vector<int> subsequence;
subsequence.push_back(2);
subsequence.push_back(3);
auto found =
std::search(beg_it, end_it, subsequence.begin(), subsequence.end());
REQUIRE(found != end_it);
}
SECTION("std::remove") // requires ForwardIterator
{
auto past_end = std::remove(beg_it, end_it, 2);
auto native_iter = mocklist.begin();
REQUIRE(*beg_it == 1);
REQUIRE(native_iter->i == 1);
REQUIRE(native_iter->c == 'a');
SECTION("increment to second element")
{
++beg_it;
++native_iter;
REQUIRE(*beg_it == 3);
REQUIRE(native_iter->i == 3);
REQUIRE(native_iter->c == 'b');
}
}
}
TEST_CASE("member_iterator based on std::vector::iterator", "[member_iterator]")
{
struct payload
{
int i;
int
get_i() const
{
return i;
}
bool
operator==(const payload& other) const
{
return i == other.i;
}
};
struct mock
{
double weight;
payload value;
};
typedef helene::member_iterator<payload,
mock,
std::vector<mock>::iterator,
&mock::value>
mockveck_iterator_type;
std::vector<mock> mockvec{{0.3, {1}}, {0.4, {2}}, {0.3, {3}}};
mockveck_iterator_type beg_it(mockvec.begin());
mockveck_iterator_type end_it(mockvec.end());
SECTION("category should be random_access_iterator_tag")
{
bool is_rai = std::is_same<
std::iterator_traits<mockveck_iterator_type>::iterator_category,
std::random_access_iterator_tag>::value;
REQUIRE(is_rai == true);
}
////////////////////////////////////////////////////////////////////////////
// BidirectionalIterator
SECTION("predecrement")
{
--end_it;
REQUIRE(end_it->i == 3);
REQUIRE(end_it->get_i() == 3);
}
SECTION("postdecrement")
{
end_it--;
REQUIRE(end_it->i == 3);
REQUIRE(end_it->get_i() == 3);
}
SECTION("postdecrement and dereference statement")
{
++beg_it;
auto old = *beg_it--;
REQUIRE(old.i == 2);
REQUIRE(beg_it->i == 1);
}
////////////////////////////////////////////////////////////////////////////
// RandomAccesIterator
SECTION("+=")
{
bool is_iter_ref =
std::is_same<decltype(beg_it += 2), mockveck_iterator_type&>::value;
beg_it += 2;
REQUIRE(is_iter_ref == true);
REQUIRE(beg_it->i == 3);
}
SECTION("adding number")
{
bool is_iter_type =
std::is_same<decltype(beg_it + 2), mockveck_iterator_type>::value;
bool is_iter_type2 =
std::is_same<decltype(2 + beg_it), mockveck_iterator_type>::value;
auto res1 = beg_it + 2;
auto res2 = 2 + beg_it;
REQUIRE(is_iter_type == true);
REQUIRE(is_iter_type2 == true);
REQUIRE(res1 == res2);
REQUIRE(res1->i == 3);
REQUIRE(res2->i == 3);
}
SECTION("-=")
{
bool is_iter_ref =
std::is_same<decltype(end_it -= 2), mockveck_iterator_type&>::value;
end_it -= 2;
REQUIRE(is_iter_ref == true);
REQUIRE(end_it->i == 2);
}
SECTION("subtracting number")
{
bool is_iter_type =
std::is_same<decltype(end_it - 2), mockveck_iterator_type>::value;
auto res1 = end_it - 3;
REQUIRE(is_iter_type == true);
REQUIRE(res1->i == 1);
}
SECTION("subtracting two iterators")
{
bool is_difference_type =
std::is_same<decltype(end_it - beg_it),
std::iterator_traits<
mockveck_iterator_type>::difference_type>::value;
REQUIRE(end_it - beg_it == mockvec.size());
}
}
|
#include "catch.hpp"
#include <utility>
#include <type_traits>
#include <iterator>
#include <algorithm>
#include <member_iterator.hpp>
#include <forward_list>
TEST_CASE("member_iterator based on ForwardIterator", "[member_iterator]")
{
struct mock
{
char c;
int i;
};
std::forward_list<mock> mocklist{{'a', 1}, {'b', 2}, {'c', 3}};
typedef helene::
member_iterator<int, mock, std::forward_list<mock>::iterator, &mock::i>
mocklist_iterator_type;
mocklist_iterator_type beg_it = mocklist.begin();
mocklist_iterator_type end_it = mocklist.end();
////////////////////////////////////////////////////////////////////////////
// Iterator concept
SECTION("construction")
{
auto elem = *beg_it;
mocklist_iterator_type cop_it = beg_it;
mocklist_iterator_type mov_it = std::move(beg_it);
REQUIRE(*mov_it == elem);
REQUIRE(cop_it == mov_it);
}
SECTION("assignment")
{
mocklist_iterator_type cop_it = beg_it;
cop_it = end_it;
REQUIRE(cop_it == end_it);
}
SECTION("move assignment")
{
mocklist_iterator_type an_it = beg_it;
mocklist_iterator_type another_it = end_it;
another_it = std::move(an_it);
REQUIRE(another_it == beg_it);
REQUIRE(*another_it == *beg_it);
}
SECTION("swappable")
{
using std::swap;
mocklist_iterator_type beg_it2 = beg_it;
mocklist_iterator_type end_it2 = end_it;
swap(beg_it2, end_it2);
REQUIRE(beg_it2 == end_it);
REQUIRE(end_it2 == beg_it);
}
SECTION("traits")
{
std::iterator_traits<mocklist_iterator_type>::value_type i = 20;
std::iterator_traits<mocklist_iterator_type>::difference_type j = -2;
std::iterator_traits<mocklist_iterator_type>::reference k = i;
std::iterator_traits<mocklist_iterator_type>::pointer l = &i;
bool is_forward_iterator = std::is_same<
std::iterator_traits<mocklist_iterator_type>::iterator_category,
std::forward_iterator_tag>::value;
REQUIRE(is_forward_iterator == true);
}
SECTION("dereference")
{
auto is_reference = std::is_same<decltype(*beg_it), int&>::value;
REQUIRE(is_reference == true);
REQUIRE(*beg_it == 1);
}
SECTION("preincrement")
{
auto ref_it = ++beg_it;
bool is_iterator_reference =
std::is_same<decltype(++beg_it), mocklist_iterator_type&>::value;
REQUIRE(ref_it == beg_it);
REQUIRE(*beg_it == 2);
REQUIRE(is_iterator_reference == true);
}
SECTION("EqualityComparable")
{
bool equal = beg_it == end_it;
REQUIRE(equal == false);
REQUIRE(beg_it == mocklist.begin());
}
////////////////////////////////////////////////////////////////////////////
// InputIterator
SECTION("!=")
{
bool not_equal = beg_it != mocklist.begin();
REQUIRE(beg_it != end_it);
REQUIRE(not_equal == false);
}
SECTION("postincrement")
{
bool is_conv_to_const_ref =
std::is_convertible<decltype(beg_it++),
const mocklist_iterator_type&>::value;
(void)beg_it++;
REQUIRE(is_conv_to_const_ref == true);
REQUIRE(*beg_it == 2);
}
SECTION("postincrement and dereference")
{
bool is_conv_to_value_type =
std::is_convertible<decltype(*beg_it++), int>::value;
auto val = *beg_it++;
REQUIRE(is_conv_to_value_type == true);
REQUIRE(val == 1);
REQUIRE(*beg_it == 2);
}
////////////////////////////////////////////////////////////////////////////
// OutputIterator
SECTION("assignment through iterator")
{
*beg_it = 10;
REQUIRE(*beg_it == 10);
REQUIRE(mocklist.front().i == 10);
REQUIRE(mocklist.front().c == 'a');
}
////////////////////////////////////////////////////////////////////////////
// ForwardIterator
SECTION("DefaultConstructible")
{
mocklist_iterator_type it;
mocklist_iterator_type it2{};
mocklist_iterator_type();
mocklist_iterator_type{};
}
SECTION("multipass guarantee")
{
auto beg_it_copy = beg_it;
++beg_it;
++beg_it;
auto val0 = *beg_it_copy++;
auto val1 = *beg_it_copy++;
auto val2 = *beg_it_copy;
REQUIRE(val0 == 1);
REQUIRE(val1 == 2);
REQUIRE(val2 == 3);
}
////////////////////////////////////////////////////////////////////////////
// Test std algorithms
SECTION("std::equal")
{
std::forward_list<mock> mocklist_copy = mocklist;
mocklist_iterator_type beg_it_copy(mocklist_copy.begin());
REQUIRE(std::equal(beg_it, end_it, beg_it_copy) == true);
}
SECTION("std::find")
{
auto found = std::find(beg_it, end_it, 2);
REQUIRE(found != end_it);
}
SECTION("std::for_each")
{
int sum = 0;
std::for_each(beg_it, end_it, [&sum](int i) { sum += i; });
REQUIRE(sum == 6);
}
SECTION("std::search") // requires ForwardIterator
{
std::vector<int> subsequence;
subsequence.push_back(2);
subsequence.push_back(3);
auto found =
std::search(beg_it, end_it, subsequence.begin(), subsequence.end());
REQUIRE(found != end_it);
}
SECTION("std::remove") // requires ForwardIterator
{
auto past_end = std::remove(beg_it, end_it, 2);
auto native_iter = mocklist.begin();
REQUIRE(*beg_it == 1);
REQUIRE(native_iter->i == 1);
REQUIRE(native_iter->c == 'a');
SECTION("increment to second element")
{
++beg_it;
++native_iter;
REQUIRE(*beg_it == 3);
REQUIRE(native_iter->i == 3);
REQUIRE(native_iter->c == 'b');
}
}
}
TEST_CASE("member_iterator based on std::vector::iterator", "[member_iterator]")
{
struct payload
{
int i;
int
get_i() const
{
return i;
}
bool
operator==(const payload& other) const
{
return i == other.i;
}
};
struct mock
{
double weight;
payload value;
};
typedef helene::member_iterator<payload,
mock,
std::vector<mock>::iterator,
&mock::value>
mockveck_iterator_type;
std::vector<mock> mockvec{{0.3, {1}}, {0.4, {2}}, {0.3, {3}}};
mockveck_iterator_type beg_it(mockvec.begin());
mockveck_iterator_type end_it(mockvec.end());
SECTION("category should be random_access_iterator_tag")
{
bool is_rai = std::is_same<
std::iterator_traits<mockveck_iterator_type>::iterator_category,
std::random_access_iterator_tag>::value;
REQUIRE(is_rai == true);
}
////////////////////////////////////////////////////////////////////////////
// BidirectionalIterator
SECTION("predecrement")
{
--end_it;
REQUIRE(end_it->i == 3);
REQUIRE(end_it->get_i() == 3);
}
SECTION("postdecrement")
{
end_it--;
REQUIRE(end_it->i == 3);
REQUIRE(end_it->get_i() == 3);
}
SECTION("postdecrement and dereference statement")
{
++beg_it;
auto old = *beg_it--;
REQUIRE(old.i == 2);
REQUIRE(beg_it->i == 1);
}
////////////////////////////////////////////////////////////////////////////
// RandomAccesIterator
SECTION("+=")
{
bool is_iter_ref =
std::is_same<decltype(beg_it += 2), mockveck_iterator_type&>::value;
beg_it += 2;
REQUIRE(is_iter_ref == true);
REQUIRE(beg_it->i == 3);
}
SECTION("adding number")
{
bool is_iter_type =
std::is_same<decltype(beg_it + 2), mockveck_iterator_type>::value;
bool is_iter_type2 =
std::is_same<decltype(2 + beg_it), mockveck_iterator_type>::value;
auto res1 = beg_it + 2;
auto res2 = 2 + beg_it;
REQUIRE(is_iter_type == true);
REQUIRE(is_iter_type2 == true);
REQUIRE(res1 == res2);
REQUIRE(res1->i == 3);
REQUIRE(res2->i == 3);
}
SECTION("-=")
{
bool is_iter_ref =
std::is_same<decltype(end_it -= 2), mockveck_iterator_type&>::value;
end_it -= 2;
REQUIRE(is_iter_ref == true);
REQUIRE(end_it->i == 2);
}
SECTION("subtracting number")
{
bool is_iter_type =
std::is_same<decltype(end_it - 2), mockveck_iterator_type>::value;
auto res1 = end_it - 3;
REQUIRE(is_iter_type == true);
REQUIRE(res1->i == 1);
}
SECTION("subtracting two iterators")
{
bool is_difference_type =
std::is_same<decltype(end_it - beg_it),
std::iterator_traits<
mockveck_iterator_type>::difference_type>::value;
REQUIRE(end_it - beg_it == mockvec.size());
}
SECTION("array_access")
{
REQUIRE(beg_it[0].i == 1);
REQUIRE(beg_it[2].i == 3);
REQUIRE(end_it[-1].i == 3);
}
SECTION("less than")
{
REQUIRE(beg_it < end_it);
REQUIRE(beg_it <= end_it);
REQUIRE(beg_it <= beg_it);
}
SECTION("greater than")
{
REQUIRE(end_it > beg_it);
REQUIRE(end_it >= beg_it);
REQUIRE(end_it >= end_it);
}
}
|
Test less than and greater than. modified: tests/test_member_iterator2.cpp
|
Test less than and greater than.
modified: tests/test_member_iterator2.cpp
|
C++
|
mit
|
bergesenha/helene
|
2a904565e528a8a97d3e3886a59f17fd07ec1699
|
idl/source/prj/svidl.cxx
|
idl/source/prj/svidl.cxx
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_idl.hxx"
#include <stdlib.h>
#include <stdio.h>
#include <database.hxx>
#include <globals.hxx>
#include <command.hxx>
#include <tools/fsys.hxx>
#include <tools/string.hxx>
#define BR 0x8000
BOOL FileMove_Impl( const String & rFile1, const String & rFile2, BOOL bImmerVerschieben )
{
//printf( "Move from %s to %s\n", rFile2.GetStr(), rFile1.GetStr() );
ULONG nC1 = 0;
ULONG nC2 = 1;
if( !bImmerVerschieben )
{
SvFileStream aOutStm1( rFile1, STREAM_STD_READ );
SvFileStream aOutStm2( rFile2, STREAM_STD_READ );
if( aOutStm1.GetError() == SVSTREAM_OK )
{
BYTE * pBuf1 = new BYTE[ BR ];
BYTE * pBuf2 = new BYTE[ BR ];
nC1 = aOutStm1.Read( pBuf1, BR );
nC2 = aOutStm2.Read( pBuf2, BR );
while( nC1 == nC2 )
{
if( memcmp( pBuf1, pBuf2, nC1 ) )
{
nC1++;
break;
}
else
{
if( 0x8000 != nC1 )
break;
nC1 = aOutStm1.Read( pBuf1, BR );
nC2 = aOutStm2.Read( pBuf2, BR );
}
}
delete[] pBuf1;
delete[] pBuf2;
}
}
DirEntry aF2( rFile2 );
if( nC1 != nC2 )
{// something has changed
DirEntry aF1( rFile1 );
aF1.Kill();
// move file
if( aF2.MoveTo( aF1 ) )
{
// delete both files
aF1.Kill();
aF2.Kill();
return FALSE;
}
return TRUE;
}
return 0 == aF2.Kill();
}
#if defined( UNX ) || (defined( PM2 ) && defined( CSET )) || defined (MTW) || defined (__MINGW32__) || defined( OS2 )
int main ( int argc, char ** argv)
{
#else
int cdecl main ( int argc, char ** argv)
{
#endif
String aTmpListFile;
String aTmpSlotMapFile;
String aTmpSfxItemFile;
String aTmpDataBaseFile;
String aTmpCallingFile;
String aTmpSrcFile;
String aTmpCxxFile;
String aTmpHxxFile;
String aTmpHelpIdFile;
String aTmpCSVFile;
String aTmpDocuFile;
SvCommand aCommand( argc, argv );
if( aCommand.nVerbosity != 0 )
printf( "StarView Interface Definition Language (IDL) Compiler 3.0\n" );
Init();
SvIdlWorkingBase * pDataBase = new SvIdlWorkingBase(aCommand);
int nExit = 0;
if( aCommand.aExportFile.Len() )
{
DirEntry aDE( aCommand.aExportFile );
pDataBase->SetExportFile( aDE.GetName() );
}
if( ReadIdl( pDataBase, aCommand ) )
{
if( nExit == 0 && aCommand.aDocuFile.Len() )
{
DirEntry aDE( aCommand.aDocuFile );
aDE.ToAbs();
aTmpDocuFile = aDE.GetPath().TempName().GetFull();
SvFileStream aOutStm( aTmpDocuFile, STREAM_READWRITE | STREAM_TRUNC );
if( !pDataBase->WriteDocumentation( aOutStm ) )
{
nExit = -1;
ByteString aStr = "cannot write documentation file: ";
aStr += ByteString( aCommand.aDocuFile, RTL_TEXTENCODING_UTF8 );
fprintf( stderr, "%s\n", aStr.GetBuffer() );
}
}
if( nExit == 0 && aCommand.aListFile.Len() )
{
DirEntry aDE( aCommand.aListFile );
aDE.ToAbs();
aTmpListFile = aDE.GetPath().TempName().GetFull();
SvFileStream aOutStm( aTmpListFile, STREAM_READWRITE | STREAM_TRUNC );
if( !pDataBase->WriteSvIdl( aOutStm ) )
{
nExit = -1;
ByteString aStr = "cannot write list file: ";
aStr += ByteString( aCommand.aListFile, RTL_TEXTENCODING_UTF8 );
fprintf( stderr, "%s\n", aStr.GetBuffer() );
}
}
if( nExit == 0 && aCommand.aSlotMapFile.Len() )
{
DirEntry aDE( aCommand.aSlotMapFile );
aDE.ToAbs();
aTmpSlotMapFile = aDE.GetPath().TempName().GetFull();
SvFileStream aOutStm( aTmpSlotMapFile, STREAM_READWRITE | STREAM_TRUNC );
if( !pDataBase->WriteSfx( aOutStm ) )
{
nExit = -1;
ByteString aStr = "cannot write slotmap file: ";
aStr += ByteString( aCommand.aSlotMapFile, RTL_TEXTENCODING_UTF8 );
fprintf( stderr, "%s\n", aStr.GetBuffer() );
}
}
if( nExit == 0 && aCommand.aHelpIdFile.Len() )
{
DirEntry aDE( aCommand.aHelpIdFile );
aDE.ToAbs();
aTmpHelpIdFile = aDE.GetPath().TempName().GetFull();
SvFileStream aStm( aTmpHelpIdFile, STREAM_READWRITE | STREAM_TRUNC );
if (!pDataBase->WriteHelpIds( aStm ) )
{
nExit = -1;
ByteString aStr = "cannot write help ID file: ";
aStr += ByteString( aCommand.aHelpIdFile, RTL_TEXTENCODING_UTF8 );
fprintf( stderr, "%s\n", aStr.GetBuffer() );
}
}
if( nExit == 0 && aCommand.aCSVFile.Len() )
{
DirEntry aDE( aCommand.aCSVFile );
aDE.ToAbs();
aTmpCSVFile = aDE.GetPath().TempName().GetFull();
SvFileStream aStm( aTmpCSVFile, STREAM_READWRITE | STREAM_TRUNC );
if (!pDataBase->WriteCSV( aStm ) )
{
nExit = -1;
ByteString aStr = "cannot write CSV file: ";
aStr += ByteString( aCommand.aCSVFile, RTL_TEXTENCODING_UTF8 );
fprintf( stderr, "%s\n", aStr.GetBuffer() );
}
}
if( nExit == 0 && aCommand.aSfxItemFile.Len() )
{
DirEntry aDE( aCommand.aSfxItemFile );
aDE.ToAbs();
aTmpSfxItemFile = aDE.GetPath().TempName().GetFull();
SvFileStream aOutStm( aTmpSfxItemFile, STREAM_READWRITE | STREAM_TRUNC );
if( !pDataBase->WriteSfxItem( aOutStm ) )
{
nExit = -1;
ByteString aStr = "cannot write item file: ";
aStr += ByteString( aCommand.aSfxItemFile, RTL_TEXTENCODING_UTF8 );
fprintf( stderr, "%s\n", aStr.GetBuffer() );
}
}
if( nExit == 0 && aCommand.aDataBaseFile.Len() )
{
DirEntry aDE( aCommand.aDataBaseFile );
aDE.ToAbs();
aTmpDataBaseFile = aDE.GetPath().TempName().GetFull();
SvFileStream aOutStm( aTmpDataBaseFile, STREAM_READWRITE | STREAM_TRUNC );
pDataBase->Save( aOutStm, aCommand.nFlags );
if( aOutStm.GetError() != SVSTREAM_OK )
{
nExit = -1;
ByteString aStr = "cannot write database file: ";
aStr += ByteString( aCommand.aDataBaseFile, RTL_TEXTENCODING_UTF8 );
fprintf( stderr, "%s\n", aStr.GetBuffer() );
}
}
}
else
nExit = -1;
if( nExit == 0 )
{
BOOL bErr = FALSE;
BOOL bDoMove = aCommand.aTargetFile.Len() == 0;
String aErrFile, aErrFile2;
if( !bErr && aCommand.aListFile.Len() )
{
bErr |= !FileMove_Impl( aCommand.aListFile, aTmpListFile, bDoMove );
if( bErr ) {
aErrFile = aCommand.aListFile;
aErrFile2 = aTmpListFile;
}
}
if( !bErr && aCommand.aSlotMapFile.Len() )
{
bErr |= !FileMove_Impl( aCommand.aSlotMapFile, aTmpSlotMapFile, bDoMove );
if( bErr ) {
aErrFile = aCommand.aSlotMapFile;
aErrFile2 = aTmpSlotMapFile;
}
}
if( !bErr && aCommand.aSfxItemFile.Len() )
{
bErr |= !FileMove_Impl( aCommand.aSfxItemFile, aTmpSfxItemFile, bDoMove );
if( bErr ) {
aErrFile = aCommand.aSfxItemFile;
aErrFile2 = aTmpSfxItemFile;
}
}
if( !bErr && aCommand.aDataBaseFile.Len() )
{
bErr |= !FileMove_Impl( aCommand.aDataBaseFile, aTmpDataBaseFile, bDoMove );
if( bErr ) {
aErrFile = aCommand.aDataBaseFile;
aErrFile2 = aTmpDataBaseFile;
}
}
if( !bErr && aCommand.aCallingFile.Len() )
{
bErr |= !FileMove_Impl( aCommand.aCallingFile, aTmpCallingFile, bDoMove );
if( bErr ) {
aErrFile = aCommand.aCallingFile;
aErrFile2 = aTmpCallingFile;
}
}
if( !bErr && aCommand.aCxxFile.Len() )
{
bErr |= !FileMove_Impl( aCommand.aCxxFile, aTmpCxxFile, bDoMove );
if( bErr ) {
aErrFile = aCommand.aCxxFile;
aErrFile2 = aTmpCxxFile;
}
}
if( !bErr && aCommand.aHxxFile.Len() )
{
bErr |= !FileMove_Impl( aCommand.aHxxFile, aTmpHxxFile, bDoMove );
if( bErr ) {
aErrFile = aCommand.aHxxFile;
aErrFile2 = aTmpHxxFile;
}
}
if( !bErr && aCommand.aHelpIdFile.Len() )
{
bErr |= !FileMove_Impl( aCommand.aHelpIdFile, aTmpHelpIdFile, bDoMove );
if( bErr ) {
aErrFile = aCommand.aHelpIdFile;
aErrFile2 = aTmpHelpIdFile;
}
}
if( !bErr && aCommand.aCSVFile.Len() )
{
bErr |= !FileMove_Impl( aCommand.aCSVFile, aTmpCSVFile, bDoMove );
if( bErr ) {
aErrFile = aCommand.aCSVFile;
aErrFile2 = aTmpCSVFile;
}
}
if( !bErr && aCommand.aDocuFile.Len() )
{
bErr |= !FileMove_Impl( aCommand.aDocuFile, aTmpDocuFile, bDoMove );
if( bErr ) {
aErrFile = aCommand.aDocuFile;
aErrFile2 = aTmpDocuFile;
}
}
if( bErr )
{
nExit = -1;
ByteString aStr = "cannot move file from: ";
aStr += ByteString( aErrFile2, RTL_TEXTENCODING_UTF8 );
aStr += "\n to file: ";
aStr += ByteString( aErrFile, RTL_TEXTENCODING_UTF8 );
fprintf( stderr, "%s\n", aStr.GetBuffer() );
}
else
{
if( aCommand.aTargetFile.Len() )
{
#ifdef ICC
DirEntry aT(aCommand.aTargetFile);
aT.Kill();
#endif
// stamp file, because idl passed through correctly
SvFileStream aOutStm( aCommand.aTargetFile,
STREAM_READWRITE | STREAM_TRUNC );
}
}
}
if( nExit != 0 )
{
if( aCommand.aListFile.Len() )
DirEntry( aTmpListFile ).Kill();
if( aCommand.aSlotMapFile.Len() )
DirEntry( aTmpSlotMapFile ).Kill();
if( aCommand.aSfxItemFile.Len() )
DirEntry( aTmpSfxItemFile ).Kill();
if( aCommand.aDataBaseFile.Len() )
DirEntry( aTmpDataBaseFile ).Kill();
if( aCommand.aCallingFile.Len() )
DirEntry( aTmpCallingFile ).Kill();
if( aCommand.aCxxFile.Len() )
DirEntry( aTmpCxxFile ).Kill();
if( aCommand.aHxxFile.Len() )
DirEntry( aTmpHxxFile ).Kill();
}
delete pDataBase;
DeInit();
if( nExit != 0 )
fprintf( stderr, "svidl terminated with errors\n" );
return nExit;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_idl.hxx"
#include <stdlib.h>
#include <stdio.h>
#include <database.hxx>
#include <globals.hxx>
#include <command.hxx>
#include <tools/fsys.hxx>
#include <tools/string.hxx>
#define BR 0x8000
BOOL FileMove_Impl( const String & rFile1, const String & rFile2, BOOL bImmerVerschieben )
{
//printf( "Move from %s to %s\n", rFile2.GetStr(), rFile1.GetStr() );
ULONG nC1 = 0;
ULONG nC2 = 1;
if( !bImmerVerschieben )
{
SvFileStream aOutStm1( rFile1, STREAM_STD_READ );
SvFileStream aOutStm2( rFile2, STREAM_STD_READ );
if( aOutStm1.GetError() == SVSTREAM_OK )
{
BYTE * pBuf1 = new BYTE[ BR ];
BYTE * pBuf2 = new BYTE[ BR ];
nC1 = aOutStm1.Read( pBuf1, BR );
nC2 = aOutStm2.Read( pBuf2, BR );
while( nC1 == nC2 )
{
if( memcmp( pBuf1, pBuf2, nC1 ) )
{
nC1++;
break;
}
else
{
if( 0x8000 != nC1 )
break;
nC1 = aOutStm1.Read( pBuf1, BR );
nC2 = aOutStm2.Read( pBuf2, BR );
}
}
delete[] pBuf1;
delete[] pBuf2;
}
}
DirEntry aF2( rFile2 );
if( nC1 != nC2 )
{// something has changed
DirEntry aF1( rFile1 );
aF1.Kill();
// move file
if( aF2.MoveTo( aF1 ) )
{
// delete both files
aF1.Kill();
aF2.Kill();
return FALSE;
}
return TRUE;
}
return 0 == aF2.Kill();
}
#if defined( UNX ) || (defined( PM2 ) && defined( CSET )) || defined (__MINGW32__) || defined( OS2 )
int main ( int argc, char ** argv)
{
#else
int cdecl main ( int argc, char ** argv)
{
#endif
String aTmpListFile;
String aTmpSlotMapFile;
String aTmpSfxItemFile;
String aTmpDataBaseFile;
String aTmpCallingFile;
String aTmpSrcFile;
String aTmpCxxFile;
String aTmpHxxFile;
String aTmpHelpIdFile;
String aTmpCSVFile;
String aTmpDocuFile;
SvCommand aCommand( argc, argv );
if( aCommand.nVerbosity != 0 )
printf( "StarView Interface Definition Language (IDL) Compiler 3.0\n" );
Init();
SvIdlWorkingBase * pDataBase = new SvIdlWorkingBase(aCommand);
int nExit = 0;
if( aCommand.aExportFile.Len() )
{
DirEntry aDE( aCommand.aExportFile );
pDataBase->SetExportFile( aDE.GetName() );
}
if( ReadIdl( pDataBase, aCommand ) )
{
if( nExit == 0 && aCommand.aDocuFile.Len() )
{
DirEntry aDE( aCommand.aDocuFile );
aDE.ToAbs();
aTmpDocuFile = aDE.GetPath().TempName().GetFull();
SvFileStream aOutStm( aTmpDocuFile, STREAM_READWRITE | STREAM_TRUNC );
if( !pDataBase->WriteDocumentation( aOutStm ) )
{
nExit = -1;
ByteString aStr = "cannot write documentation file: ";
aStr += ByteString( aCommand.aDocuFile, RTL_TEXTENCODING_UTF8 );
fprintf( stderr, "%s\n", aStr.GetBuffer() );
}
}
if( nExit == 0 && aCommand.aListFile.Len() )
{
DirEntry aDE( aCommand.aListFile );
aDE.ToAbs();
aTmpListFile = aDE.GetPath().TempName().GetFull();
SvFileStream aOutStm( aTmpListFile, STREAM_READWRITE | STREAM_TRUNC );
if( !pDataBase->WriteSvIdl( aOutStm ) )
{
nExit = -1;
ByteString aStr = "cannot write list file: ";
aStr += ByteString( aCommand.aListFile, RTL_TEXTENCODING_UTF8 );
fprintf( stderr, "%s\n", aStr.GetBuffer() );
}
}
if( nExit == 0 && aCommand.aSlotMapFile.Len() )
{
DirEntry aDE( aCommand.aSlotMapFile );
aDE.ToAbs();
aTmpSlotMapFile = aDE.GetPath().TempName().GetFull();
SvFileStream aOutStm( aTmpSlotMapFile, STREAM_READWRITE | STREAM_TRUNC );
if( !pDataBase->WriteSfx( aOutStm ) )
{
nExit = -1;
ByteString aStr = "cannot write slotmap file: ";
aStr += ByteString( aCommand.aSlotMapFile, RTL_TEXTENCODING_UTF8 );
fprintf( stderr, "%s\n", aStr.GetBuffer() );
}
}
if( nExit == 0 && aCommand.aHelpIdFile.Len() )
{
DirEntry aDE( aCommand.aHelpIdFile );
aDE.ToAbs();
aTmpHelpIdFile = aDE.GetPath().TempName().GetFull();
SvFileStream aStm( aTmpHelpIdFile, STREAM_READWRITE | STREAM_TRUNC );
if (!pDataBase->WriteHelpIds( aStm ) )
{
nExit = -1;
ByteString aStr = "cannot write help ID file: ";
aStr += ByteString( aCommand.aHelpIdFile, RTL_TEXTENCODING_UTF8 );
fprintf( stderr, "%s\n", aStr.GetBuffer() );
}
}
if( nExit == 0 && aCommand.aCSVFile.Len() )
{
DirEntry aDE( aCommand.aCSVFile );
aDE.ToAbs();
aTmpCSVFile = aDE.GetPath().TempName().GetFull();
SvFileStream aStm( aTmpCSVFile, STREAM_READWRITE | STREAM_TRUNC );
if (!pDataBase->WriteCSV( aStm ) )
{
nExit = -1;
ByteString aStr = "cannot write CSV file: ";
aStr += ByteString( aCommand.aCSVFile, RTL_TEXTENCODING_UTF8 );
fprintf( stderr, "%s\n", aStr.GetBuffer() );
}
}
if( nExit == 0 && aCommand.aSfxItemFile.Len() )
{
DirEntry aDE( aCommand.aSfxItemFile );
aDE.ToAbs();
aTmpSfxItemFile = aDE.GetPath().TempName().GetFull();
SvFileStream aOutStm( aTmpSfxItemFile, STREAM_READWRITE | STREAM_TRUNC );
if( !pDataBase->WriteSfxItem( aOutStm ) )
{
nExit = -1;
ByteString aStr = "cannot write item file: ";
aStr += ByteString( aCommand.aSfxItemFile, RTL_TEXTENCODING_UTF8 );
fprintf( stderr, "%s\n", aStr.GetBuffer() );
}
}
if( nExit == 0 && aCommand.aDataBaseFile.Len() )
{
DirEntry aDE( aCommand.aDataBaseFile );
aDE.ToAbs();
aTmpDataBaseFile = aDE.GetPath().TempName().GetFull();
SvFileStream aOutStm( aTmpDataBaseFile, STREAM_READWRITE | STREAM_TRUNC );
pDataBase->Save( aOutStm, aCommand.nFlags );
if( aOutStm.GetError() != SVSTREAM_OK )
{
nExit = -1;
ByteString aStr = "cannot write database file: ";
aStr += ByteString( aCommand.aDataBaseFile, RTL_TEXTENCODING_UTF8 );
fprintf( stderr, "%s\n", aStr.GetBuffer() );
}
}
}
else
nExit = -1;
if( nExit == 0 )
{
BOOL bErr = FALSE;
BOOL bDoMove = aCommand.aTargetFile.Len() == 0;
String aErrFile, aErrFile2;
if( !bErr && aCommand.aListFile.Len() )
{
bErr |= !FileMove_Impl( aCommand.aListFile, aTmpListFile, bDoMove );
if( bErr ) {
aErrFile = aCommand.aListFile;
aErrFile2 = aTmpListFile;
}
}
if( !bErr && aCommand.aSlotMapFile.Len() )
{
bErr |= !FileMove_Impl( aCommand.aSlotMapFile, aTmpSlotMapFile, bDoMove );
if( bErr ) {
aErrFile = aCommand.aSlotMapFile;
aErrFile2 = aTmpSlotMapFile;
}
}
if( !bErr && aCommand.aSfxItemFile.Len() )
{
bErr |= !FileMove_Impl( aCommand.aSfxItemFile, aTmpSfxItemFile, bDoMove );
if( bErr ) {
aErrFile = aCommand.aSfxItemFile;
aErrFile2 = aTmpSfxItemFile;
}
}
if( !bErr && aCommand.aDataBaseFile.Len() )
{
bErr |= !FileMove_Impl( aCommand.aDataBaseFile, aTmpDataBaseFile, bDoMove );
if( bErr ) {
aErrFile = aCommand.aDataBaseFile;
aErrFile2 = aTmpDataBaseFile;
}
}
if( !bErr && aCommand.aCallingFile.Len() )
{
bErr |= !FileMove_Impl( aCommand.aCallingFile, aTmpCallingFile, bDoMove );
if( bErr ) {
aErrFile = aCommand.aCallingFile;
aErrFile2 = aTmpCallingFile;
}
}
if( !bErr && aCommand.aCxxFile.Len() )
{
bErr |= !FileMove_Impl( aCommand.aCxxFile, aTmpCxxFile, bDoMove );
if( bErr ) {
aErrFile = aCommand.aCxxFile;
aErrFile2 = aTmpCxxFile;
}
}
if( !bErr && aCommand.aHxxFile.Len() )
{
bErr |= !FileMove_Impl( aCommand.aHxxFile, aTmpHxxFile, bDoMove );
if( bErr ) {
aErrFile = aCommand.aHxxFile;
aErrFile2 = aTmpHxxFile;
}
}
if( !bErr && aCommand.aHelpIdFile.Len() )
{
bErr |= !FileMove_Impl( aCommand.aHelpIdFile, aTmpHelpIdFile, bDoMove );
if( bErr ) {
aErrFile = aCommand.aHelpIdFile;
aErrFile2 = aTmpHelpIdFile;
}
}
if( !bErr && aCommand.aCSVFile.Len() )
{
bErr |= !FileMove_Impl( aCommand.aCSVFile, aTmpCSVFile, bDoMove );
if( bErr ) {
aErrFile = aCommand.aCSVFile;
aErrFile2 = aTmpCSVFile;
}
}
if( !bErr && aCommand.aDocuFile.Len() )
{
bErr |= !FileMove_Impl( aCommand.aDocuFile, aTmpDocuFile, bDoMove );
if( bErr ) {
aErrFile = aCommand.aDocuFile;
aErrFile2 = aTmpDocuFile;
}
}
if( bErr )
{
nExit = -1;
ByteString aStr = "cannot move file from: ";
aStr += ByteString( aErrFile2, RTL_TEXTENCODING_UTF8 );
aStr += "\n to file: ";
aStr += ByteString( aErrFile, RTL_TEXTENCODING_UTF8 );
fprintf( stderr, "%s\n", aStr.GetBuffer() );
}
else
{
if( aCommand.aTargetFile.Len() )
{
#ifdef ICC
DirEntry aT(aCommand.aTargetFile);
aT.Kill();
#endif
// stamp file, because idl passed through correctly
SvFileStream aOutStm( aCommand.aTargetFile,
STREAM_READWRITE | STREAM_TRUNC );
}
}
}
if( nExit != 0 )
{
if( aCommand.aListFile.Len() )
DirEntry( aTmpListFile ).Kill();
if( aCommand.aSlotMapFile.Len() )
DirEntry( aTmpSlotMapFile ).Kill();
if( aCommand.aSfxItemFile.Len() )
DirEntry( aTmpSfxItemFile ).Kill();
if( aCommand.aDataBaseFile.Len() )
DirEntry( aTmpDataBaseFile ).Kill();
if( aCommand.aCallingFile.Len() )
DirEntry( aTmpCallingFile ).Kill();
if( aCommand.aCxxFile.Len() )
DirEntry( aTmpCxxFile ).Kill();
if( aCommand.aHxxFile.Len() )
DirEntry( aTmpHxxFile ).Kill();
}
delete pDataBase;
DeInit();
if( nExit != 0 )
fprintf( stderr, "svidl terminated with errors\n" );
return nExit;
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
Remove MTW leftover
|
Remove MTW leftover
|
C++
|
mpl-2.0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
38b7c4f1b78044a4b127499743d24a2369fb445a
|
include/vcl/sysdata.hxx
|
include/vcl/sysdata.hxx
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef INCLUDED_VCL_SYSDATA_HXX
#define INCLUDED_VCL_SYSDATA_HXX
#include <vector>
#include <cstddef>
#ifdef MACOSX
// predeclare the native classes to avoid header/include problems
typedef struct CGContext *CGContextRef;
typedef struct CGLayer *CGLayerRef;
typedef const struct __CTFont * CTFontRef;
#ifdef __OBJC__
@class NSView;
#else
class NSView;
#endif
#endif
#ifdef IOS
typedef const struct __CTFont * CTFontRef;
typedef struct CGContext *CGContextRef;
#endif
#if defined( WNT )
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4201)
#endif
#include <windef.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif
struct SystemEnvData
{
unsigned long nSize; // size in bytes of this structure
#if defined( WNT )
HWND hWnd; // the window hwnd
#elif defined( MACOSX )
NSView* mpNSView; // the cocoa (NSView *) implementing this object
#elif defined( ANDROID )
// Nothing
#elif defined( IOS )
// Nothing
#elif defined( UNX )
void* pDisplay; // the relevant display connection
long aWindow; // the window of the object
void* pSalFrame; // contains a salframe, if object has one
void* pWidget; // the corresponding widget
void* pVisual; // the visual in use
int nScreen; // the current screen of the window
int nDepth; // depth of said visual
long aColormap; // the colormap being used
void* pAppContext; // the application context in use
long aShellWindow; // the window of the frame's shell
void* pShellWidget; // the frame's shell widget
#endif
};
struct SystemParentData
{
unsigned long nSize; // size in bytes of this structure
#if defined( WNT )
HWND hWnd; // the window hwnd
#elif defined( MACOSX )
NSView* pView; // the cocoa (NSView *) implementing this object
#elif defined( ANDROID )
// Nothing
#elif defined( IOS )
// Nothing
#elif defined( UNX )
long aWindow; // the window of the object
bool bXEmbedSupport:1; // decides whether the object in question
// should support the XEmbed protocol
#endif
};
struct SystemMenuData
{
unsigned long nSize; // size in bytes of this structure
#if defined( WNT )
HMENU hMenu; // the menu handle of the menu bar
#elif defined( MACOSX )
// Nothing
#elif defined( ANDROID )
// Nothing
#elif defined( IOS )
// Nothing
#elif defined( UNX )
long aMenu; // ???
#endif
};
struct SystemGraphicsData
{
unsigned long nSize; // size in bytes of this structure
#if defined( WNT )
HDC hDC; // handle to a device context
#elif defined( MACOSX )
CGContextRef rCGContext; // CoreGraphics graphic context
#elif defined( ANDROID )
// Nothing
#elif defined( IOS )
// Nothing
#elif defined( UNX )
void* pDisplay; // the relevant display connection
long hDrawable; // a drawable
void* pVisual; // the visual in use
int nScreen; // the current screen of the drawable
int nDepth; // depth of said visual
long aColormap; // the colormap being used
void* pXRenderFormat; // render format for drawable
#endif
SystemGraphicsData()
: nSize( sizeof( SystemGraphicsData ) )
#if defined( WNT )
, hDC( 0 )
#elif defined( MACOSX )
// Nothing
#elif defined( ANDROID )
// Nothing
#elif defined( IOS )
// Nothing
#elif defined( UNX )
, pDisplay( NULL )
, hDrawable( 0 )
, pVisual( NULL )
, nScreen( 0 )
, nDepth( 0 )
, aColormap( 0 )
, pXRenderFormat( NULL )
#endif
{ }
};
struct SystemWindowData
{
unsigned long nSize; // size in bytes of this structure
#if defined( WNT ) // meaningless on Windows
#elif defined( MACOSX ) // meaningless on Mac OS X
// Nothing
#elif defined( ANDROID )
// Nothing
#elif defined( IOS )
// Nothing
#elif defined( UNX )
void* pVisual; // the visual to be used
#endif
};
struct SystemGlyphData
{
unsigned long index;
double x;
double y;
int fallbacklevel;
};
struct SystemFontData
{
unsigned long nSize; // size in bytes of this structure
#if defined( WNT )
HFONT hFont; // native font object
#elif defined( MACOSX )
#elif defined( UNX )
void* nFontId; // native font id
int nFontFlags; // native font flags
#endif
bool bFakeBold; // Does this font need faking the bold style
bool bFakeItalic; // Does this font need faking the italic style
bool bAntialias; // Should this font be antialiased
bool bVerticalCharacterType; // Is the font using vertical character type
SystemFontData()
: nSize( sizeof( SystemFontData ) )
#if defined( WNT )
, hFont( 0 )
#elif defined( MACOSX )
#elif defined( UNX )
, nFontId( NULL )
, nFontFlags( 0 )
#endif
, bFakeBold( false )
, bFakeItalic( false )
, bAntialias( true )
, bVerticalCharacterType( false )
{
}
};
typedef std::vector<SystemGlyphData> SystemGlyphDataVector;
struct SystemTextLayoutData
{
unsigned long nSize; // size in bytes of this structure
SystemGlyphDataVector rGlyphData; // glyph data
int orientation; // Text orientation
};
#endif // INCLUDED_VCL_SYSDATA_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef INCLUDED_VCL_SYSDATA_HXX
#define INCLUDED_VCL_SYSDATA_HXX
#include <vector>
#include <cstddef>
#ifdef MACOSX
// predeclare the native classes to avoid header/include problems
typedef struct CGContext *CGContextRef;
typedef struct CGLayer *CGLayerRef;
typedef const struct __CTFont * CTFontRef;
#ifdef __OBJC__
@class NSView;
#else
class NSView;
#endif
#endif
#ifdef IOS
typedef const struct __CTFont * CTFontRef;
typedef struct CGContext *CGContextRef;
#endif
#if defined( WNT )
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable:4201)
#endif
#include <windef.h>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif
struct SystemEnvData
{
unsigned long nSize; // size in bytes of this structure
#if defined( WNT )
HWND hWnd; // the window hwnd
#elif defined( MACOSX )
NSView* mpNSView; // the cocoa (NSView *) implementing this object
#elif defined( ANDROID )
// Nothing
#elif defined( IOS )
// Nothing
#elif defined( UNX )
void* pDisplay; // the relevant display connection
long aWindow; // the window of the object
void* pSalFrame; // contains a salframe, if object has one
void* pWidget; // the corresponding widget
void* pVisual; // the visual in use
int nScreen; // the current screen of the window
int nDepth; // depth of said visual
long aColormap; // the colormap being used
void* pAppContext; // the application context in use
long aShellWindow; // the window of the frame's shell
void* pShellWidget; // the frame's shell widget
#endif
};
struct SystemParentData
{
unsigned long nSize; // size in bytes of this structure
#if defined( WNT )
HWND hWnd; // the window hwnd
#elif defined( MACOSX )
NSView* pView; // the cocoa (NSView *) implementing this object
#elif defined( ANDROID )
// Nothing
#elif defined( IOS )
// Nothing
#elif defined( UNX )
long aWindow; // the window of the object
bool bXEmbedSupport:1; // decides whether the object in question
// should support the XEmbed protocol
#endif
};
struct SystemMenuData
{
unsigned long nSize; // size in bytes of this structure
#if defined( WNT )
HMENU hMenu; // the menu handle of the menu bar
#elif defined( MACOSX )
// Nothing
#elif defined( ANDROID )
// Nothing
#elif defined( IOS )
// Nothing
#elif defined( UNX )
long aMenu; // ???
#endif
};
struct SystemGraphicsData
{
unsigned long nSize; // size in bytes of this structure
#if defined( WNT )
HDC hDC; // handle to a device context
#elif defined( MACOSX )
CGContextRef rCGContext; // CoreGraphics graphic context
#elif defined( ANDROID )
// Nothing
#elif defined( IOS )
CGContextRef rCGContext; // CoreGraphics graphic context
#elif defined( UNX )
void* pDisplay; // the relevant display connection
long hDrawable; // a drawable
void* pVisual; // the visual in use
int nScreen; // the current screen of the drawable
int nDepth; // depth of said visual
long aColormap; // the colormap being used
void* pXRenderFormat; // render format for drawable
#endif
SystemGraphicsData()
: nSize( sizeof( SystemGraphicsData ) )
#if defined( WNT )
, hDC( 0 )
#elif defined( MACOSX )
, rCGContext( NULL )
#elif defined( ANDROID )
// Nothing
#elif defined( IOS )
, rCGContext( NULL )
#elif defined( UNX )
, pDisplay( NULL )
, hDrawable( 0 )
, pVisual( NULL )
, nScreen( 0 )
, nDepth( 0 )
, aColormap( 0 )
, pXRenderFormat( NULL )
#endif
{ }
};
struct SystemWindowData
{
unsigned long nSize; // size in bytes of this structure
#if defined( WNT ) // meaningless on Windows
#elif defined( MACOSX ) // meaningless on Mac OS X
// Nothing
#elif defined( ANDROID )
// Nothing
#elif defined( IOS )
// Nothing
#elif defined( UNX )
void* pVisual; // the visual to be used
#endif
};
struct SystemGlyphData
{
unsigned long index;
double x;
double y;
int fallbacklevel;
};
struct SystemFontData
{
unsigned long nSize; // size in bytes of this structure
#if defined( WNT )
HFONT hFont; // native font object
#elif defined( MACOSX )
#elif defined( UNX )
void* nFontId; // native font id
int nFontFlags; // native font flags
#endif
bool bFakeBold; // Does this font need faking the bold style
bool bFakeItalic; // Does this font need faking the italic style
bool bAntialias; // Should this font be antialiased
bool bVerticalCharacterType; // Is the font using vertical character type
SystemFontData()
: nSize( sizeof( SystemFontData ) )
#if defined( WNT )
, hFont( 0 )
#elif defined( MACOSX )
#elif defined( UNX )
, nFontId( NULL )
, nFontFlags( 0 )
#endif
, bFakeBold( false )
, bFakeItalic( false )
, bAntialias( true )
, bVerticalCharacterType( false )
{
}
};
typedef std::vector<SystemGlyphData> SystemGlyphDataVector;
struct SystemTextLayoutData
{
unsigned long nSize; // size in bytes of this structure
SystemGlyphDataVector rGlyphData; // glyph data
int orientation; // Text orientation
};
#endif // INCLUDED_VCL_SYSDATA_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|
Add CGContext field to SystemGraphicsData for iOS, too
|
Add CGContext field to SystemGraphicsData for iOS, too
|
C++
|
mpl-2.0
|
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
|
116d9f1e002fc5b79a8402f34018b4991a85fd80
|
include/VisitorUtils.hpp
|
include/VisitorUtils.hpp
|
//=======================================================================
// Copyright Baptiste Wicht 2011.
// 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)
//=======================================================================
#ifndef VISITOR_UTILS_H
#define VISITOR_UTILS_H
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/variant.hpp>
#include <boost/optional/optional.hpp>
#define ASSIGN(Type, Value)\
result_type operator()(Type & ){\
return Value;\
}
#define ASSIGN_INSIDE(Visitor, Type, Value)\
result_type Visitor::operator()(Type & ){\
return Value;\
}
namespace eddic {
template<typename Visitor, typename Visitable>
inline void visit(Visitor& visitor, const Visitable& visitable){
boost::apply_visitor(visitor, visitable);
}
template<typename Visitor, typename Visitable>
inline void visit(Visitor& visitor, Visitable& visitable){
boost::apply_visitor(visitor, visitable);
}
template<typename Visitor, typename Visitable>
inline void visit_each(Visitor& visitor, std::vector<Visitable>& elements){
for_each(elements.begin(), elements.end(), [&](Visitable& visitable){ visit(visitor, visitable); });
}
template<typename Visitor, typename Visitable>
inline void visit_non_variant(Visitor& visitor, Visitable& visitable){
visitor(visitable);
}
template<typename Visitor, typename Visitable>
inline void visit_each_non_variant(Visitor& visitor, std::vector<Visitable>& elements){
for_each(elements.begin(), elements.end(), [&](Visitable& visitable){ visit_non_variant(visitor, visitable); });
}
template<typename Visitor, typename Visitable>
inline void visit_optional(Visitor& visitor, boost::optional<Visitable>& optional){
if(optional){
boost::apply_visitor(visitor, *optional);
}
}
template<typename Visitor, typename Visitable>
inline void visit_optional_non_variant(Visitor& visitor, boost::optional<Visitable>& optional){
if(optional){
visit_non_variant(visitor, *optional);
}
}
} //end of eddic
#endif
|
//=======================================================================
// Copyright Baptiste Wicht 2011.
// 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)
//=======================================================================
#ifndef VISITOR_UTILS_H
#define VISITOR_UTILS_H
#include <boost/variant/apply_visitor.hpp>
#include <boost/variant/variant.hpp>
#include <boost/optional/optional.hpp>
#include <boost/utility/enable_if.hpp>
#define ASSIGN(Type, Value)\
result_type operator()(Type & ){\
return Value;\
}
#define ASSIGN_INSIDE(Visitor, Type, Value)\
result_type Visitor::operator()(Type & ){\
return Value;\
}
namespace eddic {
/* non-const-non-const version */
template<typename Visitor, typename Visitable>
inline typename boost::disable_if_c<boost::is_void<typename Visitor::result_type>::value, typename Visitor::result_type>::type
visit(Visitor& visitor, Visitable& visitable){
return boost::apply_visitor(visitor, visitable);
}
template<typename Visitor, typename Visitable>
inline void visit(Visitor& visitor, Visitable& visitable){
boost::apply_visitor(visitor, visitable);
}
/* const-const version */
template<typename Visitor, typename Visitable>
inline typename boost::disable_if_c<boost::is_void<typename Visitor::result_type>::value, typename Visitor::result_type>::type
visit(const Visitor& visitor, const Visitable& visitable){
return boost::apply_visitor(visitor, visitable);
}
template<typename Visitor, typename Visitable>
inline void visit(const Visitor& visitor, const Visitable& visitable){
boost::apply_visitor(visitor, visitable);
}
/* non const non variant version */
template<typename Visitor, typename Visitable>
inline typename boost::disable_if_c<boost::is_void<typename Visitor::result_type>::value, typename Visitor::result_type>::type
visit_non_variant(Visitor& visitor, Visitable& visitable){
return visitor(visitable);
}
template<typename Visitor, typename Visitable>
inline void visit_non_variant(Visitor& visitor, Visitable& visitable){
visitor(visitable);
}
/* const non variant version */
template<typename Visitor, typename Visitable>
inline typename boost::disable_if_c<boost::is_void<typename Visitor::result_type>::value, typename Visitor::result_type>::type
visit_non_variant(const Visitor& visitor, const Visitable& visitable){
return visitor(visitable);
}
template<typename Visitor, typename Visitable>
inline void visit_non_variant(const Visitor& visitor, const Visitable& visitable){
visitor(visitable);
}
/* optional versions : no return */
template<typename Visitor, typename Visitable>
inline void visit_optional(Visitor& visitor, boost::optional<Visitable>& optional){
if(optional){
boost::apply_visitor(visitor, *optional);
}
}
template<typename Visitor, typename Visitable>
inline void visit_optional_non_variant(Visitor& visitor, boost::optional<Visitable>& optional){
if(optional){
visit_non_variant(visitor, *optional);
}
}
/* Visit a set : only void version */
template<typename Visitor, typename Visitable>
inline void visit_each(Visitor& visitor, std::vector<Visitable>& elements){
for_each(elements.begin(), elements.end(), [&](Visitable& visitable){ visit(visitor, visitable); });
}
template<typename Visitor, typename Visitable>
inline void visit_each_non_variant(Visitor& visitor, std::vector<Visitable>& elements){
for_each(elements.begin(), elements.end(), [&](Visitable& visitable){ visit_non_variant(visitor, visitable); });
}
} //end of eddic
#endif
|
Improve VisitorUtils to handle both void and non_void visitors
|
Improve VisitorUtils to handle both void and non_void visitors
|
C++
|
mit
|
wichtounet/eddic,wichtounet/eddic,vogelsgesang/eddic,vogelsgesang/eddic,vogelsgesang/eddic,wichtounet/eddic
|
07fdf6adca585a2bbedbe082d5b947364f81a4b6
|
C++/intervalcover/intervalcover.cpp
|
C++/intervalcover/intervalcover.cpp
|
#include <stdio.h>
#include <stdlib.h>
#include <utility>
#include <queue>
#define pdd pair<double, double>
#define pdi pair<double, int>
using namespace std;
// Should work, but there are still some bugs
struct comp {
bool operator() (const pdi &a, const pdi &b) {
return a.first > b.first;
}
};
vector<int> indexes;
pdd intervals[10001];
int n;
int main(int argc, char const *argv[]) {
double A, B, x, y, u, v, last, max;
int index, maxIndex;
freopen("intervalcover.in", "r", stdin);
while(!feof(stdin)) {
priority_queue< pdi, vector< pdi >, comp > Q;
scanf("%lf %lf", &A, &B);
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%lf %lf", &x, &y);
if (y < A || x > B) continue;
if (x < A) x = A;
if (y > B) y = B;
intervals[i] = make_pair(x, y);
Q.push(make_pair(x, i));
}
last = A;
while (!Q.empty()) {
max = last;
maxIndex = -1;
while (!Q.empty() && Q.top().first <= last) {
index = (int) Q.top().second;
y = intervals[index].second;
if (y > max) {
max = y;
maxIndex = index;
}
Q.pop();
}
if (maxIndex == -1) {
break;
}
last = max;
indexes.push_back(index);
}
if (maxIndex != -1) {
printf("%lu\n", indexes.size());
for (int i = 0; i < indexes.size(); i++) {
printf("%d ", indexes[i]);
}
printf("\n");
} else {
printf("impossible\n");
}
indexes.clear();
}
return 0;
}
|
#include <stdio.h>
#include <stdlib.h>
#include <utility>
#include <queue>
#define pdd pair<double, double>
#define pdi pair<double, int>
using namespace std;
// Should work, but there are still some bugs
struct comp {
bool operator() (const pdi &a, const pdi &b) {
return a.first > b.first;
}
};
vector<int> indexes;
pdd intervals[10001];
int n;
int main(int argc, char const *argv[]) {
double A, B, x, y, u, v, last, max;
int index, maxIndex;
freopen("intervalcover.in", "r", stdin);
while(!feof(stdin)) {
priority_queue< pdi, vector< pdi >, comp > Q;
scanf("%lf %lf", &A, &B);
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%lf %lf", &x, &y);
if (y < A || x > B) continue;
if (x < A) x = A;
if (y > B) y = B;
intervals[i] = make_pair(x, y);
Q.push(make_pair(x, i));
}
last = A;
while (!Q.empty()) {
max = last;
maxIndex = -1;
while (!Q.empty() && Q.top().first <= last) {
index = (int) Q.top().second;
y = intervals[index].second;
if (y > max) {
max = y;
maxIndex = index;
}
Q.pop();
}
if (maxIndex == -1) {
break;
}
last = max;
indexes.push_back(index);
}
if (maxIndex != -1) {
printf("%lu\n", indexes.size());
for (int i = 0; i < indexes.size(); i++) {
printf("%d ", indexes[i]);
}
printf("\n");
} else {
printf("impossible\n");
}
indexes.clear();
}
return 0;
}
|
fix typo
|
fix typo
|
C++
|
mit
|
rvrheenen/OpenKattis,rvrheenen/OpenKattis,rvrheenen/OpenKattis,rvrheenen/OpenKattis,rvrheenen/OpenKattis,rvrheenen/OpenKattis,rvrheenen/OpenKattis
|
0d3ab07ad1863ad89785c3e66d4e1969eac98a29
|
CompilerStack.cpp
|
CompilerStack.cpp
|
/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <[email protected]>
* @date 2014
* Full-stack compiler that converts a source code string to bytecode.
*/
#include <libsolidity/AST.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/GlobalContext.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Compiler.h>
#include <libsolidity/CompilerStack.h>
#include <jsonrpc/json/json.h>
using namespace std;
namespace dev
{
namespace solidity
{
void CompilerStack::setSource(string const& _sourceCode)
{
reset();
m_scanner = make_shared<Scanner>(CharStream(_sourceCode));
}
void CompilerStack::parse()
{
if (!m_scanner)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Source not available."));
m_contractASTNode = Parser().parse(m_scanner);
m_globalContext = make_shared<GlobalContext>();
m_globalContext->setCurrentContract(*m_contractASTNode);
NameAndTypeResolver(m_globalContext->getDeclarations()).resolveNamesAndTypes(*m_contractASTNode);
m_parseSuccessful = true;
}
void CompilerStack::parse(string const& _sourceCode)
{
setSource(_sourceCode);
parse();
}
bytes const& CompilerStack::compile(bool _optimize)
{
if (!m_parseSuccessful)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
m_bytecode.clear();
m_compiler = make_shared<Compiler>();
m_compiler->compileContract(*m_contractASTNode, m_globalContext->getMagicVariables());
return m_bytecode = m_compiler->getAssembledBytecode(_optimize);
}
bytes const& CompilerStack::compile(string const& _sourceCode, bool _optimize)
{
parse(_sourceCode);
return compile(_optimize);
}
void CompilerStack::streamAssembly(ostream& _outStream)
{
if (!m_compiler || m_bytecode.empty())
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Compilation was not successful."));
m_compiler->streamAssembly(_outStream);
}
string const& CompilerStack::getInterface()
{
Json::StyledWriter writer;
if (!m_parseSuccessful)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
if (m_interface.empty())
{
Json::Value methods(Json::arrayValue);
vector<FunctionDefinition const*> exportedFunctions = m_contractASTNode->getInterfaceFunctions();
for (FunctionDefinition const* f: exportedFunctions)
{
Json::Value method;
Json::Value inputs(Json::arrayValue);
Json::Value outputs(Json::arrayValue);
auto streamVariables = [&](vector<ASTPointer<VariableDeclaration>> const& _vars,
Json::Value &json)
{
for (ASTPointer<VariableDeclaration> const& var: _vars)
{
Json::Value input;
input["name"] = var->getName();
input["type"] = var->getType()->toString();
json.append(input);
}
};
method["name"] = f->getName();
streamVariables(f->getParameters(), inputs);
method["inputs"] = inputs;
streamVariables(f->getReturnParameters(), outputs);
method["outputs"] = outputs;
methods.append(method);
}
m_interface = writer.write(methods);
}
return m_interface;
}
string const& CompilerStack::getDocumentation()
{
Json::StyledWriter writer;
if (!m_parseSuccessful)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
if (m_documentation.empty())
{
Json::Value doc;
Json::Value methods(Json::objectValue);
vector<FunctionDefinition const*> exportedFunctions = m_contractASTNode->getInterfaceFunctions();
for (FunctionDefinition const* f: exportedFunctions)
{
Json::Value user;
user["user"] = Json::Value(*f->getDocumentation());
methods[f->getName()] = user;
}
doc["methods"] = methods;
m_documentation = writer.write(doc);
}
return m_documentation;
}
bytes CompilerStack::staticCompile(std::string const& _sourceCode, bool _optimize)
{
CompilerStack stack;
return stack.compile(_sourceCode, _optimize);
}
}
}
|
/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <[email protected]>
* @date 2014
* Full-stack compiler that converts a source code string to bytecode.
*/
#include <libsolidity/AST.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/GlobalContext.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Compiler.h>
#include <libsolidity/CompilerStack.h>
#include <jsonrpc/json/json.h>
using namespace std;
namespace dev
{
namespace solidity
{
void CompilerStack::setSource(string const& _sourceCode)
{
reset();
m_scanner = make_shared<Scanner>(CharStream(_sourceCode));
}
void CompilerStack::parse()
{
if (!m_scanner)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Source not available."));
m_contractASTNode = Parser().parse(m_scanner);
m_globalContext = make_shared<GlobalContext>();
m_globalContext->setCurrentContract(*m_contractASTNode);
NameAndTypeResolver(m_globalContext->getDeclarations()).resolveNamesAndTypes(*m_contractASTNode);
m_parseSuccessful = true;
}
void CompilerStack::parse(string const& _sourceCode)
{
setSource(_sourceCode);
parse();
}
bytes const& CompilerStack::compile(bool _optimize)
{
if (!m_parseSuccessful)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
m_bytecode.clear();
m_compiler = make_shared<Compiler>();
m_compiler->compileContract(*m_contractASTNode, m_globalContext->getMagicVariables());
return m_bytecode = m_compiler->getAssembledBytecode(_optimize);
}
bytes const& CompilerStack::compile(string const& _sourceCode, bool _optimize)
{
parse(_sourceCode);
return compile(_optimize);
}
void CompilerStack::streamAssembly(ostream& _outStream)
{
if (!m_compiler || m_bytecode.empty())
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Compilation was not successful."));
m_compiler->streamAssembly(_outStream);
}
string const& CompilerStack::getInterface()
{
Json::StyledWriter writer;
if (!m_parseSuccessful)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
if (m_interface.empty())
{
Json::Value methods(Json::arrayValue);
vector<FunctionDefinition const*> exportedFunctions = m_contractASTNode->getInterfaceFunctions();
for (FunctionDefinition const* f: exportedFunctions)
{
Json::Value method;
Json::Value inputs(Json::arrayValue);
Json::Value outputs(Json::arrayValue);
auto streamVariables = [&](vector<ASTPointer<VariableDeclaration>> const& _vars,
Json::Value &json)
{
for (ASTPointer<VariableDeclaration> const& var: _vars)
{
Json::Value input;
input["name"] = var->getName();
input["type"] = var->getType()->toString();
json.append(input);
}
};
method["name"] = f->getName();
streamVariables(f->getParameters(), inputs);
method["inputs"] = inputs;
streamVariables(f->getReturnParameters(), outputs);
method["outputs"] = outputs;
methods.append(method);
}
m_interface = writer.write(methods);
}
return m_interface;
}
string const& CompilerStack::getDocumentation()
{
Json::StyledWriter writer;
if (!m_parseSuccessful)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
if (m_documentation.empty())
{
Json::Value doc;
Json::Value methods(Json::objectValue);
vector<FunctionDefinition const*> exportedFunctions = m_contractASTNode->getInterfaceFunctions();
for (FunctionDefinition const* f: exportedFunctions)
{
Json::Value user;
auto strPtr = f->getDocumentation();
if (strPtr)
{
user["user"] = Json::Value(*strPtr);
methods[f->getName()] = user;
}
}
doc["methods"] = methods;
m_documentation = writer.write(doc);
}
return m_documentation;
}
bytes CompilerStack::staticCompile(std::string const& _sourceCode, bool _optimize)
{
CompilerStack stack;
return stack.compile(_sourceCode, _optimize);
}
}
}
|
Handle absence of Natspec doc and add option to solc
|
Handle absence of Natspec doc and add option to solc
|
C++
|
mit
|
ruchevits/solidity,shahankhatch/solidity,ethers/solidity,ruchevits/solidity,chriseth/solidity,LianaHus/solidity,arkpar/solidity,LefterisJP/solidity,ruchevits/solidity,vaporry/solidity,ruchevits/solidity,douglas-larocca/solidity,chriseth/solidity-doc-test,gluk256/solidity,debris/solidity
|
446be95b98fe3366b52df6adeacb6e2e16f0b90c
|
tntdb/src/oracle/connection.cpp
|
tntdb/src/oracle/connection.cpp
|
/*
* Copyright (C) 2007 Tommi Maekitalo
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <tntdb/oracle/connection.h>
#include <tntdb/oracle/statement.h>
#include <tntdb/oracle/error.h>
#include <tntdb/result.h>
#include <tntdb/statement.h>
#include <cxxtools/log.h>
log_define("tntdb.oracle.connection")
namespace tntdb
{
namespace oracle
{
namespace error
{
log_define("tntdb.oracle.error")
inline void checkError(OCIError* errhp, sword ret, const char* function)
{
switch (ret)
{
case OCI_SUCCESS:
break;
case OCI_SUCCESS_WITH_INFO:
log_warn(function << ": OCI_SUCCESS_WITH_INFO");
break;
case OCI_NEED_DATA:
log_warn(function << ": OCI_NEED_DATA");
throw Error(errhp, function);
case OCI_NO_DATA:
log_warn(function << ": OCI_NO_DATA");
throw NotFound();
case OCI_ERROR:
throw Error(errhp, function);
case OCI_INVALID_HANDLE:
log_error("OCI_INVALID_HANDLE");
throw InvalidHandle(function);
case OCI_STILL_EXECUTING:
log_error("OCI_STILL_EXECUTING");
throw StillExecuting(function);
case OCI_CONTINUE:
log_error("OCI_CONTINUE");
throw ErrorContinue(function);
}
}
}
void Connection::checkError(sword ret, const char* function) const
{
error::checkError(getErrorHandle(), ret, function);
}
void Connection::logon(const std::string& dblink, const std::string& user, const std::string& password)
{
log_debug("logon \"" << dblink << "\" user=\"" << user << '"');
sword ret;
log_debug("create oracle environment");
ret = OCIEnvCreate(&envhp, OCI_OBJECT, 0, 0, 0, 0, 0, 0);
if (ret != OCI_SUCCESS)
throw Error("cannot create environment handle");
log_debug("environment handle => " << envhp);
log_debug("allocate error handle");
ret = OCIHandleAlloc(envhp, (void**)&errhp, OCI_HTYPE_ERROR, 0, 0);
if (ret != OCI_SUCCESS)
throw Error("cannot create error handle");
log_debug("error handle => " << errhp);
log_debug("allocate server handle");
ret = OCIHandleAlloc(envhp, (void**)&srvhp, OCI_HTYPE_SERVER, 0, 0);
checkError(ret, "OCIHandleAlloc(OCI_HTYPE_SERVER)");
log_debug("server handle => " << srvhp);
log_debug("allocate service handle");
ret = OCIHandleAlloc(envhp, (void**)&svchp, OCI_HTYPE_SVCCTX, 0, 0);
checkError(ret, "OCIHandleAlloc(OCI_HTYPE_SVCCTX)");
log_debug("service handle => " << svchp);
log_debug("attach to server");
ret = OCIServerAttach(srvhp, errhp, reinterpret_cast<const text*>(dblink.data()), dblink.size(), 0);
checkError(ret, "OCIServerAttach");
/* set attribute server context in the service context */
ret = OCIAttrSet(svchp, OCI_HTYPE_SVCCTX, srvhp, 0, OCI_ATTR_SERVER, errhp);
checkError(ret, "OCIAttrSet(OCI_ATTR_SERVER)");
log_debug("allocate session handle");
ret = OCIHandleAlloc((dvoid*)envhp, (dvoid**)&usrhp, OCI_HTYPE_SESSION, 0, (dvoid**)0);
checkError(ret, "OCIHandleAlloc(OCI_HTYPE_SESSION)");
/* set username attribute in user session handle */
log_debug("set username attribute in session handle");
ret = OCIAttrSet(usrhp, OCI_HTYPE_SESSION,
reinterpret_cast<void*>(const_cast<char*>(user.data())),
user.size(), OCI_ATTR_USERNAME, errhp);
checkError(ret, "OCIAttrSet(OCI_ATTR_USERNAME)");
/* set password attribute in user session handle */
ret = OCIAttrSet(usrhp, OCI_HTYPE_SESSION,
reinterpret_cast<void*>(const_cast<char*>(password.data())),
password.size(), OCI_ATTR_PASSWORD, errhp);
checkError(ret, "OCIAttrSet(OCI_ATTR_PASSWORD)");
/* start session */
log_debug("start session");
ret = OCISessionBegin(svchp, errhp, usrhp, OCI_CRED_RDBMS, OCI_DEFAULT);
checkError(ret, "OCISessionBegin");
/* set user session attrubte in the service context handle */
ret = OCIAttrSet(svchp, OCI_HTYPE_SVCCTX, usrhp, 0, OCI_ATTR_SESSION, errhp);
checkError(ret, "OCIAttrSet(OCI_ATTR_SESSION)");
}
namespace
{
std::string extractAttribute(std::string& value, const std::string& key)
{
std::string::size_type p0 = value.find(key);
if (p0 == std::string::npos)
return std::string();
if (p0 > 0 && value.at(p0 - 1) != ';')
return std::string();
std::string::size_type p1 = value.find(';', p0);
if (p1 == std::string::npos)
p1 = value.size();
std::string::size_type n = p1 - p0;
std::string ret(value, p0 + key.size(), n - key.size());
if (p0 > 0)
value.erase(p0 - 1, n + 1);
else
value.erase(p0, n);
return ret;
}
}
Connection::Connection(const char* conninfo_)
: envhp(0),
srvhp(0),
errhp(0),
usrhp(0),
svchp(0),
transactionActive(0)
{
std::string conninfo(conninfo_);
std::string user = extractAttribute(conninfo, "user=");
std::string passwd = extractAttribute(conninfo, "passwd=");
logon(conninfo, user, passwd);
}
Connection::~Connection()
{
if (envhp)
{
clearStatementCache();
log_debug("OCIHandleFree(" << envhp << ')');
sword ret = OCIHandleFree(envhp, OCI_HTYPE_ENV);
if (ret == OCI_SUCCESS)
log_debug("handle released");
else
log_error("OCIHandleFree failed");
}
}
void Connection::beginTransaction()
{
//log_debug("OCITransStart(" << svchp << ", " << errhp << ')');
//checkError(OCITransStart(svchp, errhp, 10, OCI_TRANS_NEW), "OCITransStart");
++transactionActive;
}
void Connection::commitTransaction()
{
if (transactionActive == 0 || --transactionActive == 0)
{
log_debug("OCITransCommit(" << srvhp << ", " << errhp << ')');
checkError(OCITransCommit(svchp, errhp, OCI_DEFAULT), "OCITransCommit");
}
}
void Connection::rollbackTransaction()
{
if (transactionActive == 0 || --transactionActive == 0)
{
log_debug("OCITransRollback(" << srvhp << ", " << errhp << ')');
checkError(OCITransRollback(svchp, errhp, OCI_DEFAULT), "OCITransRollback");
}
}
Connection::size_type Connection::execute(const std::string& query)
{
return prepare(query).execute();
}
tntdb::Result Connection::select(const std::string& query)
{
return prepare(query).select();
}
Row Connection::selectRow(const std::string& query)
{
return prepare(query).selectRow();
}
Value Connection::selectValue(const std::string& query)
{
return prepare(query).selectValue();
}
tntdb::Statement Connection::prepare(const std::string& query)
{
return tntdb::Statement(new Statement(this, query));
}
bool Connection::ping()
{
try
{
if (!pingStmt)
pingStmt = prepare("select 1 from dual");
pingStmt.selectValue();
return true;
}
catch (const Error&)
{
return false;
}
}
}
}
|
/*
* Copyright (C) 2007 Tommi Maekitalo
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* As a special exception, you may use this file as part of a free
* software library without restriction. Specifically, if other files
* instantiate templates or use macros or inline functions from this
* file, or you compile this file and link it with other files to
* produce an executable, this file does not by itself cause the
* resulting executable to be covered by the GNU General Public
* License. This exception does not however invalidate any other
* reasons why the executable file might be covered by the GNU Library
* General Public License.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <tntdb/oracle/connection.h>
#include <tntdb/oracle/statement.h>
#include <tntdb/oracle/error.h>
#include <tntdb/result.h>
#include <tntdb/statement.h>
#include <cxxtools/log.h>
log_define("tntdb.oracle.connection")
namespace tntdb
{
namespace oracle
{
namespace error
{
log_define("tntdb.oracle.error")
inline void checkError(OCIError* errhp, sword ret, const char* function)
{
switch (ret)
{
case OCI_SUCCESS:
break;
case OCI_SUCCESS_WITH_INFO:
log_warn(function << ": OCI_SUCCESS_WITH_INFO");
break;
case OCI_NEED_DATA:
log_warn(function << ": OCI_NEED_DATA");
throw Error(errhp, function);
case OCI_NO_DATA:
log_warn(function << ": OCI_NO_DATA");
throw NotFound();
case OCI_ERROR:
throw Error(errhp, function);
case OCI_INVALID_HANDLE:
log_error("OCI_INVALID_HANDLE");
throw InvalidHandle(function);
case OCI_STILL_EXECUTING:
log_error("OCI_STILL_EXECUTING");
throw StillExecuting(function);
case OCI_CONTINUE:
log_error("OCI_CONTINUE");
throw ErrorContinue(function);
}
}
}
void Connection::checkError(sword ret, const char* function) const
{
error::checkError(getErrorHandle(), ret, function);
}
void Connection::logon(const std::string& dblink, const std::string& user, const std::string& password)
{
log_debug("logon \"" << dblink << "\" user=\"" << user << '"');
sword ret;
log_debug("create oracle environment");
ret = OCIEnvCreate(&envhp, OCI_OBJECT, 0, 0, 0, 0, 0, 0);
if (ret != OCI_SUCCESS)
throw Error("cannot create environment handle");
log_debug("environment handle => " << envhp);
log_debug("allocate error handle");
ret = OCIHandleAlloc(envhp, (void**)&errhp, OCI_HTYPE_ERROR, 0, 0);
if (ret != OCI_SUCCESS)
throw Error("cannot create error handle");
log_debug("error handle => " << errhp);
log_debug("allocate server handle");
ret = OCIHandleAlloc(envhp, (void**)&srvhp, OCI_HTYPE_SERVER, 0, 0);
checkError(ret, "OCIHandleAlloc(OCI_HTYPE_SERVER)");
log_debug("server handle => " << srvhp);
log_debug("allocate service handle");
ret = OCIHandleAlloc(envhp, (void**)&svchp, OCI_HTYPE_SVCCTX, 0, 0);
checkError(ret, "OCIHandleAlloc(OCI_HTYPE_SVCCTX)");
log_debug("service handle => " << svchp);
log_debug("attach to server");
ret = OCIServerAttach(srvhp, errhp, reinterpret_cast<const text*>(dblink.data()), dblink.size(), 0);
checkError(ret, "OCIServerAttach");
/* set attribute server context in the service context */
ret = OCIAttrSet(svchp, OCI_HTYPE_SVCCTX, srvhp, 0, OCI_ATTR_SERVER, errhp);
checkError(ret, "OCIAttrSet(OCI_ATTR_SERVER)");
log_debug("allocate session handle");
ret = OCIHandleAlloc((dvoid*)envhp, (dvoid**)&usrhp, OCI_HTYPE_SESSION, 0, (dvoid**)0);
checkError(ret, "OCIHandleAlloc(OCI_HTYPE_SESSION)");
/* set username attribute in user session handle */
log_debug("set username attribute in session handle");
ret = OCIAttrSet(usrhp, OCI_HTYPE_SESSION,
reinterpret_cast<void*>(const_cast<char*>(user.data())),
user.size(), OCI_ATTR_USERNAME, errhp);
checkError(ret, "OCIAttrSet(OCI_ATTR_USERNAME)");
/* set password attribute in user session handle */
ret = OCIAttrSet(usrhp, OCI_HTYPE_SESSION,
reinterpret_cast<void*>(const_cast<char*>(password.data())),
password.size(), OCI_ATTR_PASSWORD, errhp);
checkError(ret, "OCIAttrSet(OCI_ATTR_PASSWORD)");
/* start session */
log_debug("start session");
ret = OCISessionBegin(svchp, errhp, usrhp, OCI_CRED_RDBMS, OCI_DEFAULT);
checkError(ret, "OCISessionBegin");
/* set user session attrubte in the service context handle */
ret = OCIAttrSet(svchp, OCI_HTYPE_SVCCTX, usrhp, 0, OCI_ATTR_SESSION, errhp);
checkError(ret, "OCIAttrSet(OCI_ATTR_SESSION)");
}
namespace
{
std::string extractAttribute(std::string& value, const std::string& key)
{
std::string::size_type p0 = value.find(key);
if (p0 == std::string::npos)
return std::string();
if (p0 > 0 && value.at(p0 - 1) != ';')
return std::string();
std::string::size_type p1 = value.find(';', p0);
if (p1 == std::string::npos)
p1 = value.size();
std::string::size_type n = p1 - p0;
std::string ret(value, p0 + key.size(), n - key.size());
if (p0 > 0)
value.erase(p0 - 1, n + 1);
else
value.erase(p0, n);
return ret;
}
}
Connection::Connection(const char* conninfo_)
: envhp(0),
srvhp(0),
errhp(0),
usrhp(0),
svchp(0),
transactionActive(0)
{
std::string conninfo(conninfo_);
std::string user = extractAttribute(conninfo, "user=");
std::string passwd = extractAttribute(conninfo, "passwd=");
logon(conninfo, user, passwd);
}
Connection::~Connection()
{
if (envhp)
{
clearStatementCache();
pingStmt = tntdb::Statement();
log_debug("OCIHandleFree(" << envhp << ')');
sword ret = OCIHandleFree(envhp, OCI_HTYPE_ENV);
if (ret == OCI_SUCCESS)
log_debug("handle released");
else
log_error("OCIHandleFree failed");
}
}
void Connection::beginTransaction()
{
//log_debug("OCITransStart(" << svchp << ", " << errhp << ')');
//checkError(OCITransStart(svchp, errhp, 10, OCI_TRANS_NEW), "OCITransStart");
++transactionActive;
}
void Connection::commitTransaction()
{
if (transactionActive == 0 || --transactionActive == 0)
{
log_debug("OCITransCommit(" << srvhp << ", " << errhp << ')');
checkError(OCITransCommit(svchp, errhp, OCI_DEFAULT), "OCITransCommit");
}
}
void Connection::rollbackTransaction()
{
if (transactionActive == 0 || --transactionActive == 0)
{
log_debug("OCITransRollback(" << srvhp << ", " << errhp << ')');
checkError(OCITransRollback(svchp, errhp, OCI_DEFAULT), "OCITransRollback");
}
}
Connection::size_type Connection::execute(const std::string& query)
{
return prepare(query).execute();
}
tntdb::Result Connection::select(const std::string& query)
{
return prepare(query).select();
}
Row Connection::selectRow(const std::string& query)
{
return prepare(query).selectRow();
}
Value Connection::selectValue(const std::string& query)
{
return prepare(query).selectValue();
}
tntdb::Statement Connection::prepare(const std::string& query)
{
return tntdb::Statement(new Statement(this, query));
}
bool Connection::ping()
{
try
{
if (!pingStmt)
pingStmt = prepare("select 1 from dual");
pingStmt.selectValue();
return true;
}
catch (const Error&)
{
return false;
}
}
}
}
|
fix error in oracle driver when shutting down the connection after ping
|
fix error in oracle driver when shutting down the connection after ping
git-svn-id: 668645f5c615c5338f34c47d21d9e584f02cf8c0@153 8aebba32-5d12-0410-a889-bbfed4e15866
|
C++
|
lgpl-2.1
|
maekitalo/tntdb,OlafRadicke/tntdb,maekitalo/tntdb,OlafRadicke/tntdb
|
b026be19942d23c2607924c3d571ac6c921da434
|
CompoundAgent.cpp
|
CompoundAgent.cpp
|
/*
* CompoundAgent.cpp
* openc2e
*
* Created by Alyssa Milburn on Tue May 25 2004.
* Copyright (c) 2004 Alyssa Milburn. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include "CompoundAgent.h"
#include "openc2e.h"
#include "c16Image.h"
#include <algorithm> // sort
void CompoundAgent::render(SDLBackend *renderer, int xoffset, int yoffset) {
for (std::vector<CompoundPart *>::iterator i = parts.begin(); i != parts.end(); i++) {
(*i)->render(renderer, xoffset + (int)x, yoffset + (int)y);
}
// draw core
int xoff = xoffset + x;
int yoff = yoffset + y;
renderer->renderLine(xoff + (getWidth() / 2), yoff, xoff + getWidth(), yoff + (getHeight() / 2), 0xFF0000CC);
renderer->renderLine(xoff + getWidth(), yoff + (getHeight() / 2), xoff + (getWidth() / 2), yoff + getHeight(), 0xFF0000CC);
renderer->renderLine(xoff + (getWidth() / 2), yoff + getHeight(), xoff, yoff + (getHeight() / 2), 0xFF0000CC);
renderer->renderLine(xoff, yoff + (getHeight() / 2), xoff + (getWidth() / 2), yoff, 0xFF0000CC);
}
void CompoundAgent::addPart(CompoundPart *p) {
assert(!part(p->id)); // todo: handle better
// todo: we should prbly insert at the right place, not call sort
parts.push_back(p);
std::sort(parts.begin(), parts.end());
if (width < p->getWidth()) width = p->getWidth();
if (height < p->getHeight()) height = p->getHeight();
}
void CompoundAgent::delPart(unsigned int id) {
for (std::vector<CompoundPart *>::iterator x = parts.begin(); x != parts.end(); x++) {
if ((*x)->id == id) { parts.erase(x); delete *x; return; }
}
throw "oops"; // TODO: handle this exception properly
}
CompoundPart *CompoundAgent::part(unsigned int id) {
for (std::vector<CompoundPart *>::iterator x = parts.begin(); x != parts.end(); x++) {
if ((*x)->id == id) return *x;
}
return 0;
}
void CompoundPart::render(SDLBackend *renderer, int xoffset, int yoffset) {
renderer->render(getSprite(), getCurrentSprite(), xoffset + x, yoffset + y);
}
CompoundAgent::CompoundAgent(unsigned char _family, unsigned char _genus, unsigned short _species, unsigned int plane,
std::string spritefile, unsigned int firstimage, unsigned int imagecount) :
Agent(_family, _genus, _species, plane), width(0), height(0) {
// CAOS docs seem to imply initial part is part 1 in NEW: COMP, but rest of docs call it part 0
// TODO: we ignore image count acos it sucks
CompoundPart *p = new DullPart(0, spritefile, firstimage, 0, 0, 0);
addPart(p);
}
CompoundAgent::~CompoundAgent() {
for (std::vector<CompoundPart *>::iterator x = parts.begin(); x != parts.end(); x++) {
delete *x;
}
}
CompoundPart::CompoundPart(unsigned int _id, std::string spritefile, unsigned int fimg,
unsigned int _x, unsigned int _y, unsigned int _z) {
id = _id;
firstimg = fimg;
x = _x;
y = _y;
zorder = _z;
sprite = gallery.getImage(spritefile);
assert(sprite);
pose = 0;
}
DullPart::DullPart(unsigned int _id, std::string spritefile, unsigned int fimg, unsigned int _x, unsigned int _y,
unsigned int _z) : CompoundPart(_id, spritefile, fimg, _x, _y, _z) {
}
ButtonPart::ButtonPart(unsigned int _id, std::string spritefile, unsigned int fimg, unsigned int _x, unsigned int _y,
unsigned int _z, std::string animhover, int msgid, int option) : CompoundPart(_id, spritefile, fimg, _x, _y, _z) {
}
// TODO: combine identical code from SimpleAgent/CompoundAgent
// TODO: implement set/getAttributes for Vehicle/Creature(?)
void CompoundAgent::setAttributes(unsigned int attr) {
carryable = (attr & 1);
mouseable = (attr & 2);
activateable = (attr & 4);
invisible = (attr & 16);
floatable = (attr & 32);
suffercollisions = (attr & 64);
sufferphysics = (attr & 128);
camerashy = (attr & 256);
rotatable = (attr & 1024);
presence = (attr & 2048);
}
unsigned int CompoundAgent::getAttributes() {
unsigned int a = (carryable ? 1 : 0);
a += (mouseable ? 2: 0);
a += (activateable ? 4: 0);
a += (invisible ? 16: 0);
a += (floatable ? 32: 0);
a += (suffercollisions ? 64: 0);
a += (sufferphysics ? 128: 0);
a += (camerashy ? 256: 0);
a += (rotatable ? 1024: 0);
return a + (presence ? 2048: 0);
}
void CompoundAgent::tick() {
Agent::tick();
for (std::vector<CompoundPart *>::iterator x = parts.begin(); x != parts.end(); x++) {
(*x)->tick();
}
}
void CompoundPart::tick() {
if (!animation.empty()) {
unsigned int f = frameno + 1;
if (f == animation.size()) return;
if (animation[f] == 255) {
if (f == (animation.size() - 1)) f = 0;
else f = animation[f + 1];
}
setFrameNo(f);
}
}
|
/*
* CompoundAgent.cpp
* openc2e
*
* Created by Alyssa Milburn on Tue May 25 2004.
* Copyright (c) 2004 Alyssa Milburn. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include "CompoundAgent.h"
#include "openc2e.h"
#include "c16Image.h"
#include <algorithm> // sort
void CompoundAgent::render(SDLBackend *renderer, int xoffset, int yoffset) {
// todo: we're ignoring zorder here..
for (std::vector<CompoundPart *>::iterator i = parts.begin(); i != parts.end(); i++) {
(*i)->render(renderer, xoffset + (int)x, yoffset + (int)y);
}
// draw core
int xoff = xoffset + x;
int yoff = yoffset + y;
renderer->renderLine(xoff + (getWidth() / 2), yoff, xoff + getWidth(), yoff + (getHeight() / 2), 0xFF0000CC);
renderer->renderLine(xoff + getWidth(), yoff + (getHeight() / 2), xoff + (getWidth() / 2), yoff + getHeight(), 0xFF0000CC);
renderer->renderLine(xoff + (getWidth() / 2), yoff + getHeight(), xoff, yoff + (getHeight() / 2), 0xFF0000CC);
renderer->renderLine(xoff, yoff + (getHeight() / 2), xoff + (getWidth() / 2), yoff, 0xFF0000CC);
}
void CompoundAgent::addPart(CompoundPart *p) {
assert(!part(p->id)); // todo: handle better
// todo: we should prbly insert at the right place, not call sort
parts.push_back(p);
std::sort(parts.begin(), parts.end());
if (width < p->getWidth()) width = p->getWidth();
if (height < p->getHeight()) height = p->getHeight();
}
void CompoundAgent::delPart(unsigned int id) {
for (std::vector<CompoundPart *>::iterator x = parts.begin(); x != parts.end(); x++) {
if ((*x)->id == id) { delete *x; parts.erase(x); return; }
}
throw "oops"; // TODO: handle this exception properly
}
CompoundPart *CompoundAgent::part(unsigned int id) {
for (std::vector<CompoundPart *>::iterator x = parts.begin(); x != parts.end(); x++) {
if ((*x)->id == id) return *x;
}
return 0;
}
void CompoundPart::render(SDLBackend *renderer, int xoffset, int yoffset) {
renderer->render(getSprite(), getCurrentSprite(), xoffset + x, yoffset + y);
}
CompoundAgent::CompoundAgent(unsigned char _family, unsigned char _genus, unsigned short _species, unsigned int plane,
std::string spritefile, unsigned int firstimage, unsigned int imagecount) :
Agent(_family, _genus, _species, plane), width(0), height(0) {
// CAOS docs seem to imply initial part is part 1 in NEW: COMP, but rest of docs call it part 0
// TODO: we ignore image count acos it sucks
CompoundPart *p = new DullPart(0, spritefile, firstimage, 0, 0, 0);
addPart(p);
}
CompoundAgent::~CompoundAgent() {
for (std::vector<CompoundPart *>::iterator x = parts.begin(); x != parts.end(); x++) {
delete *x;
}
}
CompoundPart::CompoundPart(unsigned int _id, std::string spritefile, unsigned int fimg,
unsigned int _x, unsigned int _y, unsigned int _z) {
id = _id;
firstimg = fimg;
x = _x;
y = _y;
zorder = _z;
sprite = gallery.getImage(spritefile);
assert(sprite);
pose = 0;
}
DullPart::DullPart(unsigned int _id, std::string spritefile, unsigned int fimg, unsigned int _x, unsigned int _y,
unsigned int _z) : CompoundPart(_id, spritefile, fimg, _x, _y, _z) {
}
ButtonPart::ButtonPart(unsigned int _id, std::string spritefile, unsigned int fimg, unsigned int _x, unsigned int _y,
unsigned int _z, std::string animhover, int msgid, int option) : CompoundPart(_id, spritefile, fimg, _x, _y, _z) {
}
// TODO: combine identical code from SimpleAgent/CompoundAgent
// TODO: implement set/getAttributes for Vehicle/Creature(?)
void CompoundAgent::setAttributes(unsigned int attr) {
carryable = (attr & 1);
mouseable = (attr & 2);
activateable = (attr & 4);
invisible = (attr & 16);
floatable = (attr & 32);
suffercollisions = (attr & 64);
sufferphysics = (attr & 128);
camerashy = (attr & 256);
rotatable = (attr & 1024);
presence = (attr & 2048);
}
unsigned int CompoundAgent::getAttributes() {
unsigned int a = (carryable ? 1 : 0);
a += (mouseable ? 2: 0);
a += (activateable ? 4: 0);
a += (invisible ? 16: 0);
a += (floatable ? 32: 0);
a += (suffercollisions ? 64: 0);
a += (sufferphysics ? 128: 0);
a += (camerashy ? 256: 0);
a += (rotatable ? 1024: 0);
return a + (presence ? 2048: 0);
}
void CompoundAgent::tick() {
Agent::tick();
for (std::vector<CompoundPart *>::iterator x = parts.begin(); x != parts.end(); x++) {
(*x)->tick();
}
}
void CompoundPart::tick() {
if (!animation.empty()) {
unsigned int f = frameno + 1;
if (f == animation.size()) return;
if (animation[f] == 255) {
if (f == (animation.size() - 1)) f = 0;
else f = animation[f + 1];
}
setFrameNo(f);
}
}
|
fix crash
|
fix crash
|
C++
|
lgpl-2.1
|
crystalline/openc2e,crystalline/openc2e,bdonlan/openc2e,bdonlan/openc2e,crystalline/openc2e,ccdevnet/openc2e,bdonlan/openc2e,bdonlan/openc2e,crystalline/openc2e,crystalline/openc2e,ccdevnet/openc2e,ccdevnet/openc2e,ccdevnet/openc2e,ccdevnet/openc2e,ccdevnet/openc2e
|
658df475c35b473b3d0edb0b64de268903b703b1
|
src/input/ExtAtomFactory.cpp
|
src/input/ExtAtomFactory.cpp
|
/*******************************************************************************
* Copyright 2016 Francesco Calimeri, Davide Fusca', Simona Perri and Jessica Zangari
*
* 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.
*******************************************************************************/
/*
* ExtAtomFactory.cpp
*
* Created on: 22 lug 2016
* Author: giovanni
*/
#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#define FILENAME_MAX MAX_PATH
#else
#include <unistd.h>
#include <limits.h>
#define GetCurrentDir getcwd
#define FILENAME_MAX PATH_MAX
#endif
#include "ExtAtomFactory.h"
#include "../grounder/atom/PythonExtAtom.h"
#include "../grounder/exception/ExtAtomException.h"
#include "../grounder/table/PredicateTable.h"
#include <regex>
#include <fstream>
using namespace std;
namespace DLV2 {
namespace grounder {
ExtAtomFactory* ExtAtomFactory::factory = nullptr;
#ifdef PYTHON
constexpr char ExtAtomFactory::SPARQL_FUNC[];
constexpr char ExtAtomFactory::SPARQLENDPOINT_FUNC[];
constexpr char ExtAtomFactory::SPARQLENDPOINT_PYTHON_FUNC[];
constexpr char ExtAtomFactory::SPARQLENDPOINT_TEMP[];
ExtAtomFactory::ExtAtomFactory():
pyRunning(false),
sparqlModuling (false),
sparqlLoadFunc (false),
sparqlLoadEndFunc (false),
sparqlModule(nullptr),
sparqlEndpointFunc(nullptr),
sparqlFunc(nullptr),
SPARQL_SCRIPT("py_sparql_import"),
SPARQL_SCRIPT_PATH("scripts/python")
{}
ExtAtom* ExtAtomFactory::makeExtAtom(Predicate* predicate, vector<Term*>& terms, unsigned separator, bool naf) {
if(!pyRunning)
pyInitialize();
//Check if exist other predicate with different arity
ExtAtom* extAtom = nullptr;
PyObject* pFunc = nullptr;
//Load module for sparql query
if(!sparqlModuling && predicate->getName() == SPARQLENDPOINT_FUNC){
sparqlModuling = true;
sparqlModule =importPyFunctionFromString(SPARQLENDPOINT_TEMP,SPARQLENDPOINT_PYTHON_FUNC);
}
if(predicate->getName() == SPARQLENDPOINT_FUNC){
//load sparqlEndpoint function for query an Endpoint sparql
if(!sparqlLoadEndFunc) {
sparqlLoadEndFunc = true;
sparqlEndpointFunc = importFunc(predicate->getName(), sparqlModule);
if(sparqlEndpointFunc==nullptr){
throw ExtAtomException(" cannot load sparqlEndpoint function. Check the file script/python/py_sparql_import.py.");
}
}
pFunc = sparqlEndpointFunc;
}else{
//Load a function in a script specified by the user
// if --python-file is not specified
if(scriptPath.size() == 0){
pyFinalize();
throw ExtAtomException(" cannot load python scripts. You have not specified --python-file option.");
}
if(scriptNameFunction.count(predicate->getName())){
pFunc=scriptNameFunction[predicate->getName()];
}else{
//Find the function in scripts
for (auto it:scriptName){
auto script=it.first;
auto& module=it.second;
if(module==nullptr)
module = importModule(script);
pFunc = importFunc(predicate->getName(), module);
if(pFunc!=nullptr){
scriptNameFunction[predicate->getName()]=pFunc;
break;
}
}
}
if(pFunc==nullptr){
pyFinalize();
string files="";
for(auto p:scriptName)files+=p.first+" ";
throw ExtAtomException(" cannot load function. There is no function named \""+predicate->getName()+"\" in the python scripts \""+files+"\".");
}
}
string name=predicate->getName();
for(unsigned i=separator;i<terms.size();i++){
if(terms[i]->getType()==FUNCTION || terms[i]->getType()==ARITH){
throw ExtAtomException(" Invalid type term of &"+name+": output terms only accept variable, numeric, string or symbolic constant.");
}
}
extAtom = new PythonExtAtom(predicate, pFunc, terms, separator, naf);
if(extTypeConv.count(name)){
extAtom->setTypeConvs(extTypeConv[name]);
}
if(scriptInput.count(name)){
if(scriptInput[name]!=separator)
cerr<<"WARNING: "+name+", first used with input terms arity "+to_string(scriptInput[name])+", now seen with input terms "+to_string(separator)+"."<<endl;
}else
scriptInput[name]=separator;
return extAtom;
}
PyObject* ExtAtomFactory::importFunc(const string& name, PyObject* module) {
if(!PyObject_HasAttrString(module,name.c_str()))
return nullptr;
PyObject* pFunc = PyObject_GetAttrString(module, name.c_str());
if (!pFunc || !PyCallable_Check(pFunc))
return nullptr;
return pFunc;
}
PyObject* ExtAtomFactory::importModule(const string& script) {
PyObject* pName = PyUnicode_FromString(script.c_str());
PyObject* module;
module = PyImport_Import(pName);
Py_DECREF(pName);
if (module == nullptr) {
if (PyErr_Occurred()) {
PyErr_Print();
}
pyFinalize();
throw ExtAtomException(" during import of module "+script+". Cannot load script.");
}
return module;
}
void ExtAtomFactory::pyInitialize() {
setenv("PYTHONDONTWRITEBYTECODE", " ", 1);
pyRunning = true;
Py_Initialize();
unordered_set<string> paths;
for(auto p:scriptPath)
paths.insert(p.second);
appendSysDirectory(paths);
}
void ExtAtomFactory::pyFinalize() {
if(pyRunning) {
Py_XDECREF(sparqlFunc);
Py_XDECREF(sparqlModule);
for(auto p:scriptName)
Py_XDECREF(p.second);
for(auto p:scriptNameFunction)
Py_XDECREF(p.second);
Py_Finalize();
pyRunning=false;
}
}
void ExtAtomFactory::splitPythonPath(const string& path) {
size_t i = path.find_last_of("/\\");
// if path is not an absolute path, scriptPath = CURR_DIR
string paths,script;
if(i == path.npos)
paths=getCurrentDirectory();
else
paths = path.substr(0, i);
script = path.substr(i+1);
// erase the extension ".py" in scriptName if it exists
regex e("(.*?).py");
if(regex_match(script, e))
script.erase(script.find(".py"));
scriptName[script]=nullptr;
scriptPath[script]=paths;
}
string ExtAtomFactory::getCurrentDirectory() {
char cCurrentPath[FILENAME_MAX];
GetCurrentDir(cCurrentPath, sizeof(cCurrentPath));
return cCurrentPath;
}
void ExtAtomFactory::appendSysDirectory(unordered_set<string> path) {
PyObject *sysPath = PySys_GetObject((char*)"path");
for(auto p:path)
PyList_Append(sysPath, PyUnicode_FromString(p.c_str()));
}
#endif
} /* namespace grounder */
} /* namespace DLV2 */
|
/*******************************************************************************
* Copyright 2016 Francesco Calimeri, Davide Fusca', Simona Perri and Jessica Zangari
*
* 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.
*******************************************************************************/
/*
* ExtAtomFactory.cpp
*
* Created on: 22 lug 2016
* Author: giovanni
*/
#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#define FILENAME_MAX MAX_PATH
#else
#include <unistd.h>
#include <limits.h>
#define GetCurrentDir getcwd
#define FILENAME_MAX PATH_MAX
#endif
#include "ExtAtomFactory.h"
#include "../grounder/atom/PythonExtAtom.h"
#include "../grounder/exception/ExtAtomException.h"
#include "../grounder/table/PredicateTable.h"
#include <regex>
#include <fstream>
using namespace std;
namespace DLV2 {
namespace grounder {
ExtAtomFactory* ExtAtomFactory::factory = nullptr;
#ifdef PYTHON
constexpr char ExtAtomFactory::SPARQL_FUNC[];
constexpr char ExtAtomFactory::SPARQLENDPOINT_FUNC[];
constexpr char ExtAtomFactory::SPARQLENDPOINT_PYTHON_FUNC[];
constexpr char ExtAtomFactory::SPARQLENDPOINT_TEMP[];
ExtAtomFactory::ExtAtomFactory():
pyRunning(false),
sparqlModuling (false),
sparqlLoadFunc (false),
sparqlLoadEndFunc (false),
sparqlModule(nullptr),
sparqlEndpointFunc(nullptr),
sparqlFunc(nullptr),
SPARQL_SCRIPT("py_sparql_import"),
SPARQL_SCRIPT_PATH("scripts/python")
{}
ExtAtom* ExtAtomFactory::makeExtAtom(Predicate* predicate, vector<Term*>& terms, unsigned separator, bool naf) {
if(!pyRunning)
pyInitialize();
//Check if exist other predicate with different arity
ExtAtom* extAtom = nullptr;
PyObject* pFunc = nullptr;
//Load module for sparql query
if(!sparqlModuling && predicate->getName() == SPARQLENDPOINT_FUNC){
sparqlModuling = true;
sparqlModule =importPyFunctionFromString(SPARQLENDPOINT_TEMP,SPARQLENDPOINT_PYTHON_FUNC);
}
if(predicate->getName() == SPARQLENDPOINT_FUNC){
//load sparqlEndpoint function for query an Endpoint sparql
if(!sparqlLoadEndFunc) {
sparqlLoadEndFunc = true;
sparqlEndpointFunc = importFunc(predicate->getName(), sparqlModule);
if(sparqlEndpointFunc==nullptr){
throw ExtAtomException(" cannot load sparqlEndpoint function.");
}
}
pFunc = sparqlEndpointFunc;
}else{
//Load a function in a script specified by the user
// if --python-file is not specified
if(scriptPath.size() == 0){
pyFinalize();
throw ExtAtomException(" cannot load python scripts. You have not specified any python file.");
}
if(scriptNameFunction.count(predicate->getName())){
pFunc=scriptNameFunction[predicate->getName()];
}else{
//Find the function in scripts
for (auto it:scriptName){
auto script=it.first;
auto& module=it.second;
if(module==nullptr)
module = importModule(script);
pFunc = importFunc(predicate->getName(), module);
if(pFunc!=nullptr){
scriptNameFunction[predicate->getName()]=pFunc;
break;
}
}
}
if(pFunc==nullptr){
pyFinalize();
string files="";
for(auto p:scriptName)files+=p.first+" ";
throw ExtAtomException(" cannot load function. There is no function named \""+predicate->getName()+"\" in the python scripts \""+files+"\".");
}
}
string name=predicate->getName();
for(unsigned i=separator;i<terms.size();i++){
if(terms[i]->getType()==FUNCTION || terms[i]->getType()==ARITH){
throw ExtAtomException(" Invalid type term of &"+name+": output terms only accept variable, numeric, string or symbolic constant.");
}
}
extAtom = new PythonExtAtom(predicate, pFunc, terms, separator, naf);
if(extTypeConv.count(name)){
extAtom->setTypeConvs(extTypeConv[name]);
}
if(scriptInput.count(name)){
if(scriptInput[name]!=separator)
cerr<<"WARNING: "+name+", first used with input terms arity "+to_string(scriptInput[name])+", now seen with input terms "+to_string(separator)+"."<<endl;
}else
scriptInput[name]=separator;
return extAtom;
}
PyObject* ExtAtomFactory::importFunc(const string& name, PyObject* module) {
if(!PyObject_HasAttrString(module,name.c_str()))
return nullptr;
PyObject* pFunc = PyObject_GetAttrString(module, name.c_str());
if (!pFunc || !PyCallable_Check(pFunc))
return nullptr;
return pFunc;
}
PyObject* ExtAtomFactory::importModule(const string& script) {
PyObject* pName = PyUnicode_FromString(script.c_str());
PyObject* module;
module = PyImport_Import(pName);
Py_DECREF(pName);
if (module == nullptr) {
if (PyErr_Occurred()) {
PyErr_Print();
}
pyFinalize();
throw ExtAtomException(" during import of module "+script+". Cannot load script.");
}
return module;
}
void ExtAtomFactory::pyInitialize() {
setenv("PYTHONDONTWRITEBYTECODE", " ", 1);
pyRunning = true;
Py_Initialize();
unordered_set<string> paths;
for(auto p:scriptPath)
paths.insert(p.second);
appendSysDirectory(paths);
}
void ExtAtomFactory::pyFinalize() {
if(pyRunning) {
Py_XDECREF(sparqlFunc);
Py_XDECREF(sparqlModule);
for(auto p:scriptName)
Py_XDECREF(p.second);
for(auto p:scriptNameFunction)
Py_XDECREF(p.second);
Py_Finalize();
pyRunning=false;
}
}
void ExtAtomFactory::splitPythonPath(const string& path) {
size_t i = path.find_last_of("/\\");
// if path is not an absolute path, scriptPath = CURR_DIR
string paths,script;
if(i == path.npos)
paths=getCurrentDirectory();
else
paths = path.substr(0, i);
script = path.substr(i+1);
// erase the extension ".py" in scriptName if it exists
regex e("(.*?).py");
if(regex_match(script, e))
script.erase(script.find(".py"));
scriptName[script]=nullptr;
scriptPath[script]=paths;
}
string ExtAtomFactory::getCurrentDirectory() {
char cCurrentPath[FILENAME_MAX];
GetCurrentDir(cCurrentPath, sizeof(cCurrentPath));
return cCurrentPath;
}
void ExtAtomFactory::appendSysDirectory(unordered_set<string> path) {
PyObject *sysPath = PySys_GetObject((char*)"path");
for(auto p:path)
PyList_Append(sysPath, PyUnicode_FromString(p.c_str()));
}
#endif
} /* namespace grounder */
} /* namespace DLV2 */
|
Fix minor error message
|
Fix minor error message
|
C++
|
apache-2.0
|
DeMaCS-UNICAL/I-DLV,DeMaCS-UNICAL/I-DLV
|
551d2b7f510545c6e9548e8da0a982e0e648d7a3
|
E_Libs/StdLib.cpp
|
E_Libs/StdLib.cpp
|
// StdLib.cpp
// This file is part of the EScript programming language (https://github.com/EScript)
//
// Copyright (C) 2011-2013 Claudius Jähn <[email protected]>
// Copyright (C) 2012 Benjamin Eikel <[email protected]>
//
// Licensed under the MIT License. See LICENSE file for details.
// ---------------------------------------------------------------------------------
#include "StdLib.h"
#include "../EScript/Basics.h"
#include "../EScript/StdObjects.h"
#include "../EScript/Objects/Callables/UserFunction.h"
#include "../EScript/Compiler/Compiler.h"
#include "../EScript/Utils/IO/IO.h"
#include "../EScript/Utils/StringUtils.h"
#include "../EScript/Consts.h"
#include "ext/JSON.h"
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <sstream>
#if !defined(_MSC_VER)
#include <unistd.h>
#endif
#if defined(_WIN32)
#include <windows.h>
#endif
namespace EScript{
std::string StdLib::getOS(){
#if defined(_WIN32) || defined(_WIN64)
return std::string("WINDOWS");
#elif defined(__APPLE__)
return std::string("MAC OS");
#elif defined(__linux__)
return std::string("LINUX");
#elif defined(__unix__)
return std::string("UNIX");
#else
return std::string("UNKNOWN");
#endif
}
//! (static)
void StdLib::print_r(Object * o,int maxLevel,int level) {
if(!o) return;
if(level>maxLevel) {
std::cout << " ... " << std::endl;
return;
}
if(Array * a = dynamic_cast<Array *>(o)) {
std::cout << "[\n";
ERef<Iterator> itRef = a->getIterator();
int nr = 0;
while(!itRef->end()) {
ObjRef valueRef = itRef->value();
ObjRef keyRef = itRef->key();
if(nr++>0)std::cout << ",\n";
if(!valueRef.isNull()) {
for(int i = 0;i<level;++i)
std::cout << "\t";
std::cout << "["<<keyRef.toString() <<"] : ";
print_r(valueRef.get(),maxLevel,level+1);
}
itRef->next();
}
std::cout << "\n";
for(int i = 0;i<level-1;++i)
std::cout << "\t";
std::cout << "]";
} else if(Map * m = dynamic_cast<Map *>(o)) {
std::cout << "{\n";
ERef<Iterator> itRef = m->getIterator();
int nr = 0;
while(!itRef->end()) {
ObjRef valueRef = itRef->value();
ObjRef keyRef = itRef->key();
if(nr++>0)
std::cout << ",\n";
if(!valueRef.isNull()) {
for(int i = 0;i<level;++i)
std::cout << "\t";
std::cout << "["<<keyRef.toString() <<"] : ";
print_r(valueRef.get(),maxLevel,level+1);
}
itRef->next();
}
std::cout << "\n";
for(int i = 0;i<level-1;++i)
std::cout << "\t";
std::cout << "}";
} else {
if(dynamic_cast<String *>(o))
std::cout << "\""<<o->toString()<<"\"";
else std::cout << o->toString();
}
std::cout.flush();
}
/*! Tries to locate the given __filename__ with the current searchPath set in the runtime.
@return the path to the file or the original __filename__ if the file could not be found. */
static std::string findFile(Runtime & runtime, const std::string & filename){
static const StringId seachPathsId("__searchPaths");
std::string file(IO::condensePath(filename));
if( IO::getEntryType(file)!=IO::TYPE_FILE ){
if(Array * searchPaths = dynamic_cast<Array*>(runtime.getAttribute(seachPathsId).getValue())){
for(ERef<Iterator> itRef = searchPaths->getIterator();!itRef->end();itRef->next()){
ObjRef valueRef = itRef->value();
std::string s(IO::condensePath(valueRef.toString()+'/'+filename));
if( IO::getEntryType(s)==IO::TYPE_FILE ){
file = s;
break;
}
}
}
}
return file;
}
//! (static)
ObjRef StdLib::loadOnce(Runtime & runtime,const std::string & filename){
static const StringId mapId("__loadOnce_loadedFiles");
std::string condensedFilename( IO::condensePath(findFile(runtime,filename)) );
Map * m = dynamic_cast<Map*>(runtime.getAttribute(mapId).getValue());
if(m==nullptr){
m = Map::create();
runtime.setAttribute(mapId, Attribute(m));
}
ObjRef obj = m->getValue(condensedFilename);
if(obj.toBool()){ // already loaded?
return nullptr;
}
m->setValue(create(condensedFilename), create(true));
std::unordered_map<StringId,ObjRef> staticVars;
return _loadAndExecute(runtime,condensedFilename,staticVars);
}
#if defined(_WIN32)
static LARGE_INTEGER _getPerformanceCounter();
// execute this as soon as possible (when the global static variables are initialized)
static LARGE_INTEGER _clockStart = _getPerformanceCounter();
// wrapper for the windows high performance timer.
LARGE_INTEGER _getPerformanceCounter(){
LARGE_INTEGER c;
QueryPerformanceCounter(&c);
return c;
}
#endif
// -------------------------------------------------------------
//! init (globals)
void StdLib::init(EScript::Namespace * globals) {
/*! [ESF] void addSearchPath(path)
Adds a search path which is used for load(...) and loadOnce(...) */
ES_FUNCTION(globals,"addSearchPath",1,1,{
static const StringId seachPathsId("__searchPaths");
Array * searchPaths = dynamic_cast<Array*>(rt.getAttribute(seachPathsId).getValue());
if(searchPaths == nullptr){
searchPaths = Array::create();
rt.setAttribute(seachPathsId, Attribute(searchPaths));
}
searchPaths->pushBack(String::create(parameter[0].toString()));
return nullptr;
})
//! [ESF] void assert( expression[,text])
ES_FUNCTION(globals,"assert",1,2, {
if(!parameter[0].toBool()){
rt.setException(parameter.count()>1?parameter[1].toString():"Assert failed.");
}
return nullptr;
})
//! [ESF] string chr(number)
ES_FUN(globals,"chr",1,1, StringUtils::utf32_to_utf8(parameter[0].to<uint32_t>(rt)))
// clock
{
#if defined(_WIN32)
typedef LARGE_INTEGER timer_t;
static timer_t frequency;
if(!QueryPerformanceFrequency(&frequency)) {
std::cout <<("QueryPerformanceFrequency failed, timer will not work properly!");
}
//! [ESF] number clock()
ES_FUNCTION(globals,"clock",0,0,{
LARGE_INTEGER time = _getPerformanceCounter();
return static_cast<double>(time.QuadPart-_clockStart.QuadPart) / static_cast<double>(frequency.QuadPart);
})
#else
//! [ESF] number clock()
ES_FUN(globals,"clock",0,0,static_cast<double>(clock())/CLOCKS_PER_SEC)
#endif
}
typedef std::unordered_map<StringId,ObjRef> staticVarMap_t;
//! [ESF] Object eval(string, Map _staticVariables)
ES_FUNCTION(globals,"eval",1,2,{
staticVarMap_t staticVars;
if(parameter.count() > 1){
for( auto& entry : *parameter[1].to<const Map*>(rt)){
if(entry.second.value){
staticVars[ entry.first ] = entry.second.value;
}
}
}
return _eval(rt,
CodeFragment(Consts::FILENAME_INLINE, StringData(parameter[0].toString())),
staticVars);
})
/*! [ESF] Map getDate([time])
like http://de3.php.net/manual/de/function.getdate.php */
ES_FUNCTION(globals,"getDate",0,1,{
time_t t=(parameter.count()==0)?time(nullptr):static_cast<time_t>(parameter[0].to<int>(rt));
tm *d = localtime (& t );
Map * m = Map::create();
m->setValue(create("seconds"), create(d->tm_sec));
m->setValue(create("minutes"), create(d->tm_min));
m->setValue(create("hours"), create(d->tm_hour));
m->setValue(create("mday"), create(d->tm_mday));
m->setValue(create("mon"), create(d->tm_mon+1));
m->setValue(create("year"), create(d->tm_year+1900));
m->setValue(create("wday"), create(d->tm_wday));
m->setValue(create("yday"), create(d->tm_yday));
m->setValue(create("isdst"), create(d->tm_isdst));
return m;
})
//! [ESF] string|void getEnv(String)
ES_FUNCTION(globals,"getEnv",1,1,{
const char * value = std::getenv(parameter[0].toString().c_str());
if(value==nullptr)
return nullptr;
return std::string(value);
})
//! [ESF] string getOS()
ES_FUN(globals,"getOS",0,0,StdLib::getOS())
//! [ESF] Runtime getRuntime( )
ES_FUN(globals,"getRuntime",0,0, &rt)
//! [ESF] mixed load(string filename, Map _staticVars)
ES_FUNCTION(globals,"load",1,2,{
staticVarMap_t staticVars;
if(parameter.count() > 1){
for( auto& entry : *parameter[1].to<const Map*>(rt)){
if(entry.second.value){
staticVars[ entry.first ] = entry.second.value;
}
}
}
return _loadAndExecute(rt,findFile(rt,parameter[0].toString()),staticVars);
})
//! [ESF] mixed loadOnce(string filename)
ES_FUN(globals,"loadOnce",1,1,StdLib::loadOnce(rt,parameter[0].toString()))
//! [ESF] Number ord(String [,pos] )
ES_FUNCTION(globals,"ord",1,2, {
const uint32_t codePoint = parameter[0].to<const String*>(rt)->_getStringData().getCodePoint(parameter[1].toInt(0));
if(codePoint == static_cast<uint32_t>(~0))
return false;
else
return codePoint;
})
//! [ESF] void out(...)
ES_FUNCTION(globals,"out",0,-1, {
for(const auto & param : parameter) {
std::cout << param.toString();
}
std::cout.flush();
return nullptr;
})
//! [ESF] void outln(...)
ES_FUNCTION(globals,"outln",0,-1, {
for(const auto & param : parameter) {
std::cout << param.toString();
}
std::cout << std::endl;
return nullptr;
})
//! [ESF] BlockStatement parse(string) @deprecated
ES_FUNCTION(globals,"parse",1,1, {
std::vector<StringId> injectedStaticVars;
Compiler compiler(rt.getLogger());
auto compileUnit = compiler.compile(CodeFragment(Consts::FILENAME_INLINE, StringData(parameter[0].toString())),injectedStaticVars);
return compileUnit.first.detachAndDecrease();
})
//! [ESF] obj parseJSON(string)
ES_FUN(globals,"parseJSON",1,1,JSON::parseJSON(parameter[0].toString()))
//! [ESF] void print_r(...)
ES_FUNCTION(globals,"print_r",0,-1, {
std::cout << "\n";
for(const auto & param : parameter) {
if(!param.isNull()) {
print_r(param.get());
}
}
return nullptr;
})
//! [ESF] number system(command)
ES_FUN(globals,"system",1,1,system(parameter[0].toString().c_str()))
//! [ESF] Number exec(String path, Array argv)
ES_FUNCTION(globals, "exec", 2, 2, {
Array * array = assertType<Array>(rt, parameter[1]);
uint32_t argc = array->size();
char ** argv = new char *[argc + 1];
for(uint_fast32_t i = 0; i < argc; ++i) {
std::string arg = array->get(i)->toString();
argv[i] = new char[arg.length() + 1];
std::copy(arg.begin(), arg.end(), argv[i]);
argv[i][arg.length()] = '\0';
}
argv[argc] = nullptr;
Number * result = create(execv(parameter[0].toString().c_str(), argv));
for(uint_fast32_t i = 0; i < argc; ++i) {
delete [] argv[i];
}
delete [] argv;
return result;
})
//! [ESF] number time()
ES_FUN(globals,"time",0,0,static_cast<double>(time(nullptr)))
//! [ESF] string toJSON(obj[,formatted = true])
ES_FUN(globals,"toJSON",1,2,JSON::toJSON(parameter[0].get(),parameter[1].toBool(true)))
}
}
|
// StdLib.cpp
// This file is part of the EScript programming language (https://github.com/EScript)
//
// Copyright (C) 2011-2013 Claudius Jähn <[email protected]>
// Copyright (C) 2012 Benjamin Eikel <[email protected]>
//
// Licensed under the MIT License. See LICENSE file for details.
// ---------------------------------------------------------------------------------
#include "StdLib.h"
#include "../EScript/Basics.h"
#include "../EScript/StdObjects.h"
#include "../EScript/Objects/Callables/UserFunction.h"
#include "../EScript/Compiler/Compiler.h"
#include "../EScript/Utils/IO/IO.h"
#include "../EScript/Utils/StringUtils.h"
#include "../EScript/Consts.h"
#include "ext/JSON.h"
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <sstream>
#if defined(_MSC_VER)
#include <process.h>
#else
#include <unistd.h>
#endif
#if defined(_WIN32)
#include <windows.h>
#endif
namespace EScript{
std::string StdLib::getOS(){
#if defined(_WIN32) || defined(_WIN64)
return std::string("WINDOWS");
#elif defined(__APPLE__)
return std::string("MAC OS");
#elif defined(__linux__)
return std::string("LINUX");
#elif defined(__unix__)
return std::string("UNIX");
#else
return std::string("UNKNOWN");
#endif
}
//! (static)
void StdLib::print_r(Object * o,int maxLevel,int level) {
if(!o) return;
if(level>maxLevel) {
std::cout << " ... " << std::endl;
return;
}
if(Array * a = dynamic_cast<Array *>(o)) {
std::cout << "[\n";
ERef<Iterator> itRef = a->getIterator();
int nr = 0;
while(!itRef->end()) {
ObjRef valueRef = itRef->value();
ObjRef keyRef = itRef->key();
if(nr++>0)std::cout << ",\n";
if(!valueRef.isNull()) {
for(int i = 0;i<level;++i)
std::cout << "\t";
std::cout << "["<<keyRef.toString() <<"] : ";
print_r(valueRef.get(),maxLevel,level+1);
}
itRef->next();
}
std::cout << "\n";
for(int i = 0;i<level-1;++i)
std::cout << "\t";
std::cout << "]";
} else if(Map * m = dynamic_cast<Map *>(o)) {
std::cout << "{\n";
ERef<Iterator> itRef = m->getIterator();
int nr = 0;
while(!itRef->end()) {
ObjRef valueRef = itRef->value();
ObjRef keyRef = itRef->key();
if(nr++>0)
std::cout << ",\n";
if(!valueRef.isNull()) {
for(int i = 0;i<level;++i)
std::cout << "\t";
std::cout << "["<<keyRef.toString() <<"] : ";
print_r(valueRef.get(),maxLevel,level+1);
}
itRef->next();
}
std::cout << "\n";
for(int i = 0;i<level-1;++i)
std::cout << "\t";
std::cout << "}";
} else {
if(dynamic_cast<String *>(o))
std::cout << "\""<<o->toString()<<"\"";
else std::cout << o->toString();
}
std::cout.flush();
}
/*! Tries to locate the given __filename__ with the current searchPath set in the runtime.
@return the path to the file or the original __filename__ if the file could not be found. */
static std::string findFile(Runtime & runtime, const std::string & filename){
static const StringId seachPathsId("__searchPaths");
std::string file(IO::condensePath(filename));
if( IO::getEntryType(file)!=IO::TYPE_FILE ){
if(Array * searchPaths = dynamic_cast<Array*>(runtime.getAttribute(seachPathsId).getValue())){
for(ERef<Iterator> itRef = searchPaths->getIterator();!itRef->end();itRef->next()){
ObjRef valueRef = itRef->value();
std::string s(IO::condensePath(valueRef.toString()+'/'+filename));
if( IO::getEntryType(s)==IO::TYPE_FILE ){
file = s;
break;
}
}
}
}
return file;
}
//! (static)
ObjRef StdLib::loadOnce(Runtime & runtime,const std::string & filename){
static const StringId mapId("__loadOnce_loadedFiles");
std::string condensedFilename( IO::condensePath(findFile(runtime,filename)) );
Map * m = dynamic_cast<Map*>(runtime.getAttribute(mapId).getValue());
if(m==nullptr){
m = Map::create();
runtime.setAttribute(mapId, Attribute(m));
}
ObjRef obj = m->getValue(condensedFilename);
if(obj.toBool()){ // already loaded?
return nullptr;
}
m->setValue(create(condensedFilename), create(true));
std::unordered_map<StringId,ObjRef> staticVars;
return _loadAndExecute(runtime,condensedFilename,staticVars);
}
#if defined(_WIN32)
static LARGE_INTEGER _getPerformanceCounter();
// execute this as soon as possible (when the global static variables are initialized)
static LARGE_INTEGER _clockStart = _getPerformanceCounter();
// wrapper for the windows high performance timer.
LARGE_INTEGER _getPerformanceCounter(){
LARGE_INTEGER c;
QueryPerformanceCounter(&c);
return c;
}
#endif
// -------------------------------------------------------------
//! init (globals)
void StdLib::init(EScript::Namespace * globals) {
/*! [ESF] void addSearchPath(path)
Adds a search path which is used for load(...) and loadOnce(...) */
ES_FUNCTION(globals,"addSearchPath",1,1,{
static const StringId seachPathsId("__searchPaths");
Array * searchPaths = dynamic_cast<Array*>(rt.getAttribute(seachPathsId).getValue());
if(searchPaths == nullptr){
searchPaths = Array::create();
rt.setAttribute(seachPathsId, Attribute(searchPaths));
}
searchPaths->pushBack(String::create(parameter[0].toString()));
return nullptr;
})
//! [ESF] void assert( expression[,text])
ES_FUNCTION(globals,"assert",1,2, {
if(!parameter[0].toBool()){
rt.setException(parameter.count()>1?parameter[1].toString():"Assert failed.");
}
return nullptr;
})
//! [ESF] string chr(number)
ES_FUN(globals,"chr",1,1, StringUtils::utf32_to_utf8(parameter[0].to<uint32_t>(rt)))
// clock
{
#if defined(_WIN32)
typedef LARGE_INTEGER timer_t;
static timer_t frequency;
if(!QueryPerformanceFrequency(&frequency)) {
std::cout <<("QueryPerformanceFrequency failed, timer will not work properly!");
}
//! [ESF] number clock()
ES_FUNCTION(globals,"clock",0,0,{
LARGE_INTEGER time = _getPerformanceCounter();
return static_cast<double>(time.QuadPart-_clockStart.QuadPart) / static_cast<double>(frequency.QuadPart);
})
#else
//! [ESF] number clock()
ES_FUN(globals,"clock",0,0,static_cast<double>(clock())/CLOCKS_PER_SEC)
#endif
}
typedef std::unordered_map<StringId,ObjRef> staticVarMap_t;
//! [ESF] Object eval(string, Map _staticVariables)
ES_FUNCTION(globals,"eval",1,2,{
staticVarMap_t staticVars;
if(parameter.count() > 1){
for( auto& entry : *parameter[1].to<const Map*>(rt)){
if(entry.second.value){
staticVars[ entry.first ] = entry.second.value;
}
}
}
return _eval(rt,
CodeFragment(Consts::FILENAME_INLINE, StringData(parameter[0].toString())),
staticVars);
})
/*! [ESF] Map getDate([time])
like http://de3.php.net/manual/de/function.getdate.php */
ES_FUNCTION(globals,"getDate",0,1,{
time_t t=(parameter.count()==0)?time(nullptr):static_cast<time_t>(parameter[0].to<int>(rt));
tm *d = localtime (& t );
Map * m = Map::create();
m->setValue(create("seconds"), create(d->tm_sec));
m->setValue(create("minutes"), create(d->tm_min));
m->setValue(create("hours"), create(d->tm_hour));
m->setValue(create("mday"), create(d->tm_mday));
m->setValue(create("mon"), create(d->tm_mon+1));
m->setValue(create("year"), create(d->tm_year+1900));
m->setValue(create("wday"), create(d->tm_wday));
m->setValue(create("yday"), create(d->tm_yday));
m->setValue(create("isdst"), create(d->tm_isdst));
return m;
})
//! [ESF] string|void getEnv(String)
ES_FUNCTION(globals,"getEnv",1,1,{
const char * value = std::getenv(parameter[0].toString().c_str());
if(value==nullptr)
return nullptr;
return std::string(value);
})
//! [ESF] string getOS()
ES_FUN(globals,"getOS",0,0,StdLib::getOS())
//! [ESF] Runtime getRuntime( )
ES_FUN(globals,"getRuntime",0,0, &rt)
//! [ESF] mixed load(string filename, Map _staticVars)
ES_FUNCTION(globals,"load",1,2,{
staticVarMap_t staticVars;
if(parameter.count() > 1){
for( auto& entry : *parameter[1].to<const Map*>(rt)){
if(entry.second.value){
staticVars[ entry.first ] = entry.second.value;
}
}
}
return _loadAndExecute(rt,findFile(rt,parameter[0].toString()),staticVars);
})
//! [ESF] mixed loadOnce(string filename)
ES_FUN(globals,"loadOnce",1,1,StdLib::loadOnce(rt,parameter[0].toString()))
//! [ESF] Number ord(String [,pos] )
ES_FUNCTION(globals,"ord",1,2, {
const uint32_t codePoint = parameter[0].to<const String*>(rt)->_getStringData().getCodePoint(parameter[1].toInt(0));
if(codePoint == static_cast<uint32_t>(~0))
return false;
else
return codePoint;
})
//! [ESF] void out(...)
ES_FUNCTION(globals,"out",0,-1, {
for(const auto & param : parameter) {
std::cout << param.toString();
}
std::cout.flush();
return nullptr;
})
//! [ESF] void outln(...)
ES_FUNCTION(globals,"outln",0,-1, {
for(const auto & param : parameter) {
std::cout << param.toString();
}
std::cout << std::endl;
return nullptr;
})
//! [ESF] BlockStatement parse(string) @deprecated
ES_FUNCTION(globals,"parse",1,1, {
std::vector<StringId> injectedStaticVars;
Compiler compiler(rt.getLogger());
auto compileUnit = compiler.compile(CodeFragment(Consts::FILENAME_INLINE, StringData(parameter[0].toString())),injectedStaticVars);
return compileUnit.first.detachAndDecrease();
})
//! [ESF] obj parseJSON(string)
ES_FUN(globals,"parseJSON",1,1,JSON::parseJSON(parameter[0].toString()))
//! [ESF] void print_r(...)
ES_FUNCTION(globals,"print_r",0,-1, {
std::cout << "\n";
for(const auto & param : parameter) {
if(!param.isNull()) {
print_r(param.get());
}
}
return nullptr;
})
//! [ESF] number system(command)
ES_FUN(globals,"system",1,1,system(parameter[0].toString().c_str()))
#if defined(_MSC_VER)
//! [ESF] Number exec(String path, Array argv)
ES_FUNCTION(globals, "exec", 2, 2, {
Array * array = assertType<Array>(rt, parameter[1]);
uint32_t argc = array->size();
char ** argv = new char *[argc + 1];
for(uint_fast32_t i = 0; i < argc; ++i) {
std::string arg = array->get(i)->toString();
argv[i] = new char[arg.length() + 1];
std::copy(arg.begin(), arg.end(), argv[i]);
argv[i][arg.length()] = '\0';
}
argv[argc] = nullptr;
Number * result = create(*_execv(parameter[0].toString().c_str(), argv));
for(uint_fast32_t i = 0; i < argc; ++i) {
delete [] argv[i];
}
delete [] argv;
return result;
})
#else
//! [ESF] Number exec(String path, Array argv)
ES_FUNCTION(globals, "exec", 2, 2, {
Array * array = assertType<Array>(rt, parameter[1]);
uint32_t argc = array->size();
char ** argv = new char *[argc + 1];
for(uint_fast32_t i = 0; i < argc; ++i) {
std::string arg = array->get(i)->toString();
argv[i] = new char[arg.length() + 1];
std::copy(arg.begin(), arg.end(), argv[i]);
argv[i][arg.length()] = '\0';
}
argv[argc] = nullptr;
Number * result = create(execv(parameter[0].toString().c_str(), argv));
for(uint_fast32_t i = 0; i < argc; ++i) {
delete [] argv[i];
}
delete [] argv;
return result;
})
#endif
//! [ESF] number time()
ES_FUN(globals,"time",0,0,static_cast<double>(time(nullptr)))
//! [ESF] string toJSON(obj[,formatted = true])
ES_FUN(globals,"toJSON",1,2,JSON::toJSON(parameter[0].get(),parameter[1].toBool(true)))
}
}
|
Use _execv from process.h
|
VS: Use _execv from process.h
See https://msdn.microsoft.com/en-us/library/886kc0as.aspx
|
C++
|
mit
|
EScript/EScript,EScript/EScript
|
7137277a3d9a612b2555e67f988a6b0aca9505c4
|
src/istream/sink_gstring.cxx
|
src/istream/sink_gstring.cxx
|
/*
* author: Max Kellermann <[email protected]>
*/
#include "sink_gstring.hxx"
#include "async.hxx"
#include "istream.hxx"
#include "pool.hxx"
#include "util/Cast.hxx"
#include <glib.h>
struct sink_gstring {
struct pool *pool;
struct istream *input;
GString *value;
void (*callback)(GString *value, GError *error, void *ctx);
void *callback_ctx;
struct async_operation async_operation;
};
/*
* istream handler
*
*/
static size_t
sink_gstring_input_data(const void *data, size_t length, void *ctx)
{
struct sink_gstring *sg = (struct sink_gstring *)ctx;
g_string_append_len(sg->value, (const char *)data, length);
return length;
}
static void
sink_gstring_input_eof(void *ctx)
{
struct sink_gstring *sg = (struct sink_gstring *)ctx;
sg->async_operation.Finished();
sg->callback(sg->value, nullptr, sg->callback_ctx);
}
static void
sink_gstring_input_abort(GError *error, void *ctx)
{
struct sink_gstring *sg = (struct sink_gstring *)ctx;
sg->async_operation.Finished();
g_string_free(sg->value, true);
sg->callback(nullptr, error, sg->callback_ctx);
}
static const struct istream_handler sink_gstring_input_handler = {
.data = sink_gstring_input_data,
.eof = sink_gstring_input_eof,
.abort = sink_gstring_input_abort,
};
/*
* async operation
*
*/
static struct sink_gstring *
async_to_sink_gstring(struct async_operation *ao)
{
return &ContainerCast2(*ao, &sink_gstring::async_operation);
}
static void
sink_gstring_async_abort(struct async_operation *ao)
{
struct sink_gstring *sg = async_to_sink_gstring(ao);
g_string_free(sg->value, true);
const ScopePoolRef ref(*sg->pool TRACE_ARGS);
istream_close_handler(sg->input);
}
static const struct async_operation_class sink_gstring_operation = {
.abort = sink_gstring_async_abort,
};
/*
* constructor
*
*/
void
sink_gstring_new(struct pool *pool, struct istream *input,
void (*callback)(GString *value, GError *error, void *ctx),
void *ctx, struct async_operation_ref *async_ref)
{
auto sg = NewFromPool<struct sink_gstring>(*pool);
sg->pool = pool;
istream_assign_handler(&sg->input, input,
&sink_gstring_input_handler, sg,
FD_ANY);
sg->value = g_string_sized_new(256);
sg->callback = callback;
sg->callback_ctx = ctx;
sg->async_operation.Init(sink_gstring_operation);
async_ref->Set(sg->async_operation);
}
|
/*
* author: Max Kellermann <[email protected]>
*/
#include "sink_gstring.hxx"
#include "async.hxx"
#include "istream_oo.hxx"
#include "pool.hxx"
#include "util/Cast.hxx"
#include <glib.h>
struct sink_gstring {
struct pool *pool;
struct istream *input;
GString *value;
void (*callback)(GString *value, GError *error, void *ctx);
void *callback_ctx;
struct async_operation async_operation;
/* istream handler */
size_t OnData(const void *data, size_t length) {
g_string_append_len(value, (const char *)data, length);
return length;
}
ssize_t OnDirect(gcc_unused FdType type, gcc_unused int fd,
gcc_unused size_t max_length) {
gcc_unreachable();
}
void OnEof() {
async_operation.Finished();
callback(value, nullptr, callback_ctx);
}
void OnError(GError *error) {
async_operation.Finished();
g_string_free(value, true);
callback(nullptr, error, callback_ctx);
}
};
/*
* async operation
*
*/
static struct sink_gstring *
async_to_sink_gstring(struct async_operation *ao)
{
return &ContainerCast2(*ao, &sink_gstring::async_operation);
}
static void
sink_gstring_async_abort(struct async_operation *ao)
{
struct sink_gstring *sg = async_to_sink_gstring(ao);
g_string_free(sg->value, true);
const ScopePoolRef ref(*sg->pool TRACE_ARGS);
istream_close_handler(sg->input);
}
static const struct async_operation_class sink_gstring_operation = {
.abort = sink_gstring_async_abort,
};
/*
* constructor
*
*/
void
sink_gstring_new(struct pool *pool, struct istream *input,
void (*callback)(GString *value, GError *error, void *ctx),
void *ctx, struct async_operation_ref *async_ref)
{
auto sg = NewFromPool<struct sink_gstring>(*pool);
sg->pool = pool;
istream_assign_handler(&sg->input, input,
&MakeIstreamHandler<struct sink_gstring>::handler, sg,
FD_ANY);
sg->value = g_string_sized_new(256);
sg->callback = callback;
sg->callback_ctx = ctx;
sg->async_operation.Init(sink_gstring_operation);
async_ref->Set(sg->async_operation);
}
|
use MakeIstreamHandler
|
istream/sink_gstring: use MakeIstreamHandler
|
C++
|
bsd-2-clause
|
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
|
441331f158a5b5530286226161cca576a4d715a8
|
core/temporary_buffer.hh
|
core/temporary_buffer.hh
|
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef TEMPORARY_BUFFER_HH_
#define TEMPORARY_BUFFER_HH_
#include "deleter.hh"
#include "util/eclipse.hh"
// A temporary_buffer either points inside a larger buffer, or, if the requested size
// is too large, or if the larger buffer is scattered, contains its own storage.
template <typename CharType>
class temporary_buffer {
static_assert(sizeof(CharType) == 1, "must buffer stream of bytes");
CharType* _buffer;
size_t _size;
deleter _deleter;
public:
explicit temporary_buffer(size_t size)
: _buffer(static_cast<CharType*>(malloc(size * sizeof(CharType)))), _size(size)
, _deleter(make_free_deleter(_buffer)) {}
//explicit temporary_buffer(CharType* borrow, size_t size) : _buffer(borrow), _size(size) {}
temporary_buffer()
: _buffer(nullptr)
, _size(0) {}
temporary_buffer(const temporary_buffer&) = delete;
temporary_buffer(temporary_buffer&& x) : _buffer(x._buffer), _size(x._size), _deleter(std::move(x._deleter)) {
x._buffer = nullptr;
x._size = 0;
}
temporary_buffer(CharType* buf, size_t size, deleter d)
: _buffer(buf), _size(size), _deleter(std::move(d)) {}
void operator=(const temporary_buffer&) = delete;
temporary_buffer& operator=(temporary_buffer&& x) {
if (this != &x) {
_buffer = x._buffer;
_size = x._size;
_deleter = std::move(x._deleter);
x._buffer = nullptr;
x._size = 0;
}
return *this;
}
const CharType* get() const { return _buffer; }
CharType* get_write() { return _buffer; }
size_t size() const { return _size; }
const CharType* begin() { return _buffer; }
const CharType* end() { return _buffer + _size; }
temporary_buffer prefix(size_t size) && {
auto ret = std::move(*this);
ret._size = size;
return ret;
}
CharType operator[](size_t pos) const {
return _buffer[pos];
}
bool empty() const { return !size(); }
operator bool() { return size(); }
temporary_buffer share() {
return temporary_buffer(_buffer, _size, _deleter.share());
}
temporary_buffer share(size_t pos, size_t len) {
auto ret = share();
ret._buffer += pos;
ret._size = len;
return ret;
}
void trim_front(size_t pos) {
_buffer += pos;
_size -= pos;
}
void trim(size_t pos) {
_size = pos;
}
deleter release() {
return std::move(_deleter);
}
};
#endif /* TEMPORARY_BUFFER_HH_ */
|
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef TEMPORARY_BUFFER_HH_
#define TEMPORARY_BUFFER_HH_
#include "deleter.hh"
#include "util/eclipse.hh"
// A temporary_buffer either points inside a larger buffer, or, if the requested size
// is too large, or if the larger buffer is scattered, contains its own storage.
template <typename CharType>
class temporary_buffer {
static_assert(sizeof(CharType) == 1, "must buffer stream of bytes");
CharType* _buffer;
size_t _size;
deleter _deleter;
public:
explicit temporary_buffer(size_t size)
: _buffer(static_cast<CharType*>(malloc(size * sizeof(CharType)))), _size(size)
, _deleter(make_free_deleter(_buffer)) {
if (!_buffer) {
throw std::bad_alloc();
}
}
//explicit temporary_buffer(CharType* borrow, size_t size) : _buffer(borrow), _size(size) {}
temporary_buffer()
: _buffer(nullptr)
, _size(0) {}
temporary_buffer(const temporary_buffer&) = delete;
temporary_buffer(temporary_buffer&& x) : _buffer(x._buffer), _size(x._size), _deleter(std::move(x._deleter)) {
x._buffer = nullptr;
x._size = 0;
}
temporary_buffer(CharType* buf, size_t size, deleter d)
: _buffer(buf), _size(size), _deleter(std::move(d)) {}
void operator=(const temporary_buffer&) = delete;
temporary_buffer& operator=(temporary_buffer&& x) {
if (this != &x) {
_buffer = x._buffer;
_size = x._size;
_deleter = std::move(x._deleter);
x._buffer = nullptr;
x._size = 0;
}
return *this;
}
const CharType* get() const { return _buffer; }
CharType* get_write() { return _buffer; }
size_t size() const { return _size; }
const CharType* begin() { return _buffer; }
const CharType* end() { return _buffer + _size; }
temporary_buffer prefix(size_t size) && {
auto ret = std::move(*this);
ret._size = size;
return ret;
}
CharType operator[](size_t pos) const {
return _buffer[pos];
}
bool empty() const { return !size(); }
operator bool() { return size(); }
temporary_buffer share() {
return temporary_buffer(_buffer, _size, _deleter.share());
}
temporary_buffer share(size_t pos, size_t len) {
auto ret = share();
ret._buffer += pos;
ret._size = len;
return ret;
}
void trim_front(size_t pos) {
_buffer += pos;
_size -= pos;
}
void trim(size_t pos) {
_size = pos;
}
deleter release() {
return std::move(_deleter);
}
};
#endif /* TEMPORARY_BUFFER_HH_ */
|
fix missing exception
|
temporary_buffer: fix missing exception
Since we switched temporary_buffer to malloc(), it now longer throws
an exception after running out of memory, which leads to a segfault
when referencing a null buffer.
|
C++
|
apache-2.0
|
slivne/seastar,joerg84/seastar,avikivity/scylla,stamhe/seastar,rentongzhang/scylla,justintung/scylla,respu/scylla,mixja/seastar,raphaelsc/seastar,kjniemi/seastar,jonathanleang/seastar,eklitzke/scylla,scylladb/scylla-seastar,phonkee/scylla,printedheart/seastar,raphaelsc/seastar,leejir/seastar,scylladb/scylla,raphaelsc/scylla,dwdm/scylla,chunshengster/seastar,scylladb/scylla,avikivity/scylla,bzero/seastar,xtao/seastar,glommer/scylla,acbellini/scylla,dwdm/seastar,wildinto/scylla,tempbottle/scylla,duarten/scylla,guiquanz/scylla,kjniemi/scylla,tempbottle/seastar,duarten/scylla,koolhazz/seastar,kjniemi/scylla,tempbottle/seastar,capturePointer/scylla,stamhe/scylla,anzihenry/seastar,victorbriz/scylla,raphaelsc/scylla,kjniemi/seastar,cloudius-systems/seastar,hongliangzhao/seastar,acbellini/scylla,cloudius-systems/seastar,bowlofstew/seastar,kjniemi/scylla,dreamsxin/seastar,koolhazz/seastar,guiquanz/scylla,tempbottle/seastar,ducthangho/imdb,scylladb/scylla-seastar,glommer/scylla,slivne/seastar,acbellini/seastar,dwdm/seastar,acbellini/scylla,bowlofstew/scylla,koolhazz/seastar,stamhe/seastar,raphaelsc/seastar,shaunstanislaus/scylla,bowlofstew/seastar,kjniemi/seastar,mixja/seastar,rentongzhang/scylla,rluta/scylla,anzihenry/seastar,aruanruan/scylla,scylladb/seastar,respu/scylla,dwdm/scylla,asias/scylla,chunshengster/seastar,phonkee/scylla,printedheart/seastar,kangkot/scylla,scylladb/scylla,anzihenry/seastar,xtao/seastar,rluta/scylla,victorbriz/scylla,stamhe/scylla,linearregression/scylla,jonathanleang/seastar,wildinto/seastar,shyamalschandra/seastar,eklitzke/scylla,avikivity/scylla,senseb/scylla,justintung/scylla,stamhe/seastar,wildinto/scylla,wildinto/seastar,respu/scylla,aruanruan/scylla,printedheart/seastar,asias/scylla,scylladb/seastar,bzero/seastar,raphaelsc/scylla,flashbuckets/seastar,leejir/seastar,linearregression/seastar,hongliangzhao/seastar,bowlofstew/seastar,syuu1228/seastar,eklitzke/scylla,rentongzhang/scylla,avikivity/seastar,leejir/seastar,dwdm/seastar,senseb/scylla,slivne/seastar,norcimo5/seastar,bzero/seastar,capturePointer/scylla,dwdm/scylla,acbellini/seastar,gwicke/scylla,avikivity/seastar,flashbuckets/seastar,joerg84/seastar,wildinto/scylla,ducthangho/imdb,linearregression/scylla,linearregression/seastar,aruanruan/scylla,dreamsxin/seastar,jonathanleang/seastar,norcimo5/seastar,linearregression/scylla,sjperkins/seastar,senseb/scylla,dreamsxin/seastar,chunshengster/seastar,tempbottle/scylla,hongliangzhao/seastar,bowlofstew/scylla,wildinto/seastar,scylladb/scylla,sjperkins/seastar,mixja/seastar,shyamalschandra/seastar,guiquanz/scylla,stamhe/scylla,syuu1228/seastar,norcimo5/seastar,victorbriz/scylla,linearregression/seastar,sjperkins/seastar,asias/scylla,shyamalschandra/seastar,gwicke/scylla,gwicke/scylla,shaunstanislaus/scylla,syuu1228/seastar,flashbuckets/seastar,scylladb/seastar,tempbottle/scylla,justintung/scylla,joerg84/seastar,ducthangho/imdb,capturePointer/scylla,acbellini/seastar,bowlofstew/scylla,rluta/scylla,duarten/scylla,kangkot/scylla,scylladb/scylla-seastar,kangkot/scylla,phonkee/scylla,shaunstanislaus/scylla,avikivity/seastar,glommer/scylla,xtao/seastar,cloudius-systems/seastar
|
e7285e80ca03432cab9f3a34078d72586fe2cfca
|
include/nomlib/types.hpp
|
include/nomlib/types.hpp
|
/******************************************************************************
nomlib - C++11 cross-platform game engine
Copyright (c) 2013, Jeffrey Carpenter <[email protected]>
All rights reserved.
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#ifndef NOMLIB_TYPES_HEADERS
#define NOMLIB_TYPES_HEADERS
#include <cstdint>
// Portable fixed-size data types derive from stdint.h
namespace nom {
// 1-bit integer types
typedef bool bit;
// 8-bit integer types
typedef int8_t int8;
typedef uint8_t uint8;
// 16-bit integer types
typedef int16_t int16;
typedef uint16_t uint16;
// 32-bit integer types
typedef int32_t int32;
typedef uint32_t uint32;
// 64-bit integer types
typedef signed long long int int64;
typedef unsigned long long int uint64;
// Additional integer type definitions
typedef unsigned long ulong;
} // namespace nom
// Ensure our data types have the right sizes
static_assert ( sizeof ( nom::bit ) == 1, "nom::bit" );
static_assert ( sizeof ( nom::uint8 ) == 1, "nom::uint8" );
static_assert ( sizeof ( nom::int8 ) == 1, "nom::int8" );
static_assert ( sizeof ( nom::uint16 ) == 2, "nom::uint16" );
static_assert ( sizeof ( nom::int16 ) == 2, "nom::int16" );
static_assert ( sizeof ( nom::uint32 ) == 4, "nom::uint32" );
static_assert ( sizeof ( nom::int32 ) == 4, "nom::int32" );
static_assert ( sizeof ( nom::uint64 ) == 8, "nom::uint64" );
static_assert ( sizeof ( nom::int64 ) == 8, "nom::int64" );
#endif // NOMLIB_TYPES_HEADERS defined
|
/******************************************************************************
nomlib - C++11 cross-platform game engine
Copyright (c) 2013, Jeffrey Carpenter <[email protected]>
All rights reserved.
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.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#ifndef NOMLIB_TYPES_HEADERS
#define NOMLIB_TYPES_HEADERS
#include <cstdint>
// Portable fixed-size data types derive from stdint.h
namespace nom {
// 8-bit integer types
typedef int8_t int8;
typedef uint8_t uint8;
// 16-bit integer types
typedef int16_t int16;
typedef uint16_t uint16;
// 32-bit integer types
typedef int32_t int32;
typedef uint32_t uint32;
// 64-bit integer types
typedef signed long long int int64;
typedef unsigned long long int uint64;
// Additional integer type definitions
typedef unsigned long ulong;
} // namespace nom
// Ensure our data types have the right sizes
static_assert ( sizeof ( nom::uint8 ) == 1, "nom::uint8" );
static_assert ( sizeof ( nom::int8 ) == 1, "nom::int8" );
static_assert ( sizeof ( nom::uint16 ) == 2, "nom::uint16" );
static_assert ( sizeof ( nom::int16 ) == 2, "nom::int16" );
static_assert ( sizeof ( nom::uint32 ) == 4, "nom::uint32" );
static_assert ( sizeof ( nom::int32 ) == 4, "nom::int32" );
static_assert ( sizeof ( nom::uint64 ) == 8, "nom::uint64" );
static_assert ( sizeof ( nom::int64 ) == 8, "nom::int64" );
#endif // NOMLIB_TYPES_HEADERS defined
|
Remove useless data typedef 'bit'
|
Remove useless data typedef 'bit'
|
C++
|
bsd-2-clause
|
i8degrees/nomlib,i8degrees/nomlib,i8degrees/nomlib,i8degrees/nomlib
|
a8b279b1986efe8bd4a96ab3bc46674b391a0d9c
|
cpp/aizu/stable_sort.cpp
|
cpp/aizu/stable_sort.cpp
|
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int length, count = 0;
cin >> length;
vector<string> vector(length);
for (int i = 0; i < length; i++)
{
cin >> vector[i];
}
//sort logic
cout << vector[0];
for (int i = 1; i < length; i++)
{
cout << ' '<< vector[i];
}
cout << endl << count << endl;
}
|
#include <iostream>
#include <vector>
using namespace std;
class Card
{
private:
string name_;
int value_;
public:
Card(string card)
{
name_ = card;
value_ = stoi(card.substr(1, 1));
};
string name(){return name_;};
int value(){return value_;};
};
void bubbleSort(vector<Card *> &cards);
void shellSort(vector<Card *> &cards);
int main()
{
int length, count = 0;
cin >> length;
vector<Card*> cards(length);
for (int i = 0; i < length; i++)
{
string card;
cin >> card;
cards[i] = new Card(card);
}
bubbleSort(cards);
shellSort(cards);
}
void bubbleSort(vector<Card *> &cards)
{
for(int i = 0; i < cards.size(); i++)
{
for(int j = cards.size() - 1; j > i; j--)
{
if(cards[j-1]->value() > cards[j]->value())
{
Card* temp = cards[j-1];
cards[j-1] = cards[j];
cards[j] = temp;
}
}
}
cout << cards[0]->name();
for(int i = 1; i < cards.size(); i++)
{
cout << ' ' << cards[i]->name();
}
cout << endl << "Stable" << endl;
}
void shellSort(vector<Card *> &cards)
{
}
|
Add bubbleSort() to stable sort.
|
Add bubbleSort() to stable sort.
|
C++
|
mit
|
itohiro73/playground,itohiro73/playground,itohiro73/playground,itohiro73/playground,itohiro73/playground,itohiro73/playground
|
7b9c845c883b2d378587f83c9de9b5a3eb673554
|
include/signum/fixed.hpp
|
include/signum/fixed.hpp
|
/*
* Copyright 2015 C. Brett Witherspoon
*/
#include <cmath>
#include <limits>
#include <type_traits>
namespace signum
{
//! Convert a fixed-point type to a floating-point type
template<typename Float, typename Fixed>
Float fixed_to_floating(Fixed fixed)
{
static_assert(
std::is_floating_point<Float>::value && std::is_integral<Fixed>::value,
"Template arguments must be floating-point and integral types");
const auto scale = 1.0 / (std::numeric_limits<Fixed>::max() + 1.0);
return static_cast<Float>(scale * fixed);
}
//! Convert a floating-point type to a fixed-point type
template<typename Fixed, typename Float>
Fixed floating_to_fixed(Float floating)
{
static_assert(
std::is_floating_point<Float>::value && std::is_integral<Fixed>::value,
"Template arguments must be floating-point and integral types");
static_assert(
sizeof(Fixed) < sizeof(Float),
"An integral type larger then the floating-point type is not supported");
const auto min = std::numeric_limits<Fixed>::min();
const auto max = std::numeric_limits<Fixed>::max();
switch (std::fpclassify(floating))
{
case FP_NAN:
case FP_ZERO:
case FP_SUBNORMAL:
return static_cast<Fixed>(0);
case FP_INFINITE:
return (std::signbit(floating)) ? min : max;
default:
auto ret = floating * (std::numeric_limits<Fixed>::max() + 1.0);
ret = std::fmin(ret, max);
ret = std::fmax(ret, min);
return static_cast<Fixed>(std::lround(ret));
}
}
} /* namespace signum */
|
/*
* Copyright 2015 C. Brett Witherspoon
*/
#ifndef SIGNUM_FIXED_HPP_
#define SIGNUM_FIXED_HPP_
#include <cmath>
#include <limits>
#include <type_traits>
namespace signum
{
//! Convert a fixed-point type to a floating-point type
template<typename Float, typename Fixed>
Float fixed_to_floating(Fixed fixed)
{
static_assert(
std::is_floating_point<Float>::value && std::is_integral<Fixed>::value,
"Template arguments must be floating-point and integral types");
const auto scale = 1.0 / (std::numeric_limits<Fixed>::max() + 1.0);
return static_cast<Float>(scale * fixed);
}
//! Convert a floating-point type to a fixed-point type
template<typename Fixed, typename Float>
Fixed floating_to_fixed(Float floating)
{
static_assert(
std::is_floating_point<Float>::value && std::is_integral<Fixed>::value,
"Template arguments must be floating-point and integral types");
static_assert(
sizeof(Fixed) < sizeof(Float),
"An integral type larger then the floating-point type is not supported");
const auto min = std::numeric_limits<Fixed>::min();
const auto max = std::numeric_limits<Fixed>::max();
switch (std::fpclassify(floating))
{
case FP_NAN:
case FP_ZERO:
case FP_SUBNORMAL:
return static_cast<Fixed>(0);
case FP_INFINITE:
return (std::signbit(floating)) ? min : max;
default:
auto ret = floating * (std::numeric_limits<Fixed>::max() + 1.0);
ret = std::fmin(ret, max);
ret = std::fmax(ret, min);
return static_cast<Fixed>(std::lround(ret));
}
}
} /* namespace signum */
#endif /* SIGNUM_FIXED_HPP_ */
|
add include gaurds
|
fixed: add include gaurds
|
C++
|
isc
|
bwitherspoon/signum
|
a6dc94870ec87dd02ab3d9fce3711c9549f6a15b
|
gninasrc/gninagrid/molgridder.cpp
|
gninasrc/gninagrid/molgridder.cpp
|
/*
* molgridder.cpp
*
* Created on: Apr 23, 2019
* Author: dkoes
*/
#include "molgridder.h"
#include <libmolgrid/cartesian_grid.h>
#include <boost/timer/timer.hpp>
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace libmolgrid;
MolGridder::MolGridder(const gridoptions& opt) :
dimension(opt.dim), resolution(opt.res),
random_rotate(opt.randrotate), random_translate(opt.randtranslate),
gmaker(opt.res, opt.dim), gpu(opt.gpu) {
//setup typers
rectyper = std::make_shared<FileMappedGninaTyper>(defaultGninaReceptorTyper);
ligtyper = std::make_shared<FileMappedGninaTyper>(defaultGninaLigandTyper);
if (opt.recmap.size() > 0) {
rectyper = std::make_shared<FileMappedGninaTyper>(opt.recmap);
}
if (opt.ligmap.size() > 0) {
ligtyper = std::make_shared<FileMappedGninaTyper>(opt.ligmap);
}
float3 dims = gmaker.get_grid_dims();
grid = MGrid4f(rectyper->num_types()+ligtyper->num_types(), dims[0], dims[1], dims[2]);
tee log(true);
FlexInfo finfo(log); //dummy
mols.create_init_model(opt.receptorfile, "", finfo, log);
mols.setInputFile(opt.ligandfile);
N = 1 + round(dimension / resolution);
if (opt.examplegrid.size() > 0) set_from_example(opt.examplegrid);
if (opt.usergrids.size()) set_usergrids(opt.usergrids);
setReceptor(mols.getInitModel());
if(opt.separate) setGrid(gpu);
ex.sets.resize(2);
}
//set receptor coordinate set from model
void MolGridder::setReceptor(const model& m) {
const atomv& atoms = m.get_fixed_atoms();
vector<libmolgrid::cuda_float3> coords; coords.reserve(atoms.size());
vector<unsigned> t; t.reserve(atoms.size());
vector<float> r; t.reserve(atoms.size());
for (unsigned i = 0, n = atoms.size(); i < n; i++) {
const atom& a = atoms[i];
auto t_r = rectyper->get_int_type(a.sm);
if (t_r.first >= 0) {
coords.push_back(gfloat3(a.coords));
t.push_back(t_r.first);
r.push_back(t_r.second);
}
}
ex.sets[0] = CoordinateSet(coords, t, r, rectyper->num_types());
}
void MolGridder::setLigand(const model& m) {
const atomv& atoms = m.get_movable_atoms();
assert(atoms.size() == m.coordinates().size());
vector<libmolgrid::cuda_float3> coords; coords.reserve(atoms.size());
vector<unsigned> t; t.reserve(atoms.size());
vector<float> r; t.reserve(atoms.size());
for (unsigned i = 0, n = atoms.size(); i < n; i++) {
const atom& a = atoms[i];
auto t_r = ligtyper->get_int_type(a.sm);
if (t_r.first >= 0) {
coords.push_back(gfloat3(a.coords));
t.push_back(t_r.first);
r.push_back(t_r.second);
}
}
ex.sets[1] = CoordinateSet(coords, t, r, ligtyper->num_types());
}
//convert ex to a grid
void MolGridder::setGrid(bool use_gpu) {
if(!center_set) {
//get center from lig
center = ex.sets[1].center();
}
if(random_translate > 0 || random_rotate) {
//update transform
current_transform = Transform(center, random_translate, random_rotate);
} else {
current_transform.set_rotation_center(center);
}
if(usergrids.size() > 0) { //not particularly optimized
//copy into first so many channels
unsigned n = usergrids.size();
for(unsigned i = 0; i < n; i++) {
grid[i].copyFrom(usergrids[i].cpu());
}
size_t offset = grid[0].size()*n;
unsigned channels = rectyper->num_types()+ligtyper->num_types();
if(use_gpu) {
Grid4fCUDA g(grid.data()+offset, channels, N, N, N);
gmaker.forward(ex, current_transform, g);
} else {
Grid4f g(grid.data()+offset, channels, N, N, N);
gmaker.forward(ex, current_transform, g);
}
}
else { //no user grids
if(use_gpu) {
gmaker.forward(ex, current_transform, grid.gpu());
} else {
gmaker.forward(ex, current_transform, grid.cpu());
}
}
}
void MolGridder::cpuSetGridCheck() {
//assume current grid is right
MGrid4f saved = grid.clone();
//for recompute, apply same transformation
bool saverot = random_rotate;
float savetrans = random_translate;
setGrid(false);
random_rotate = saverot;
random_translate = savetrans;
//now compare
if(saved.size() != grid.size()) {
cerr << "Different sized grids in compare\n";
exit(-1);
}
float* a = saved.data();
float* b = grid.data();
for(unsigned i = 0, n = grid.size(); i < n; i++) {
float diff = a[i]-b[i];
if(fabs(diff) > 0.0001) {
cerr << "Values differ " << a[i] << " != " << b[i] << " at index " << i << "\n";
exit(1);
}
}
}
void MolGridder::set_center(float3 c) {
center_set = true;
center = c;
}
//set grid parameters from an example dx
void MolGridder::set_from_example(const string& examplefile) {
CartesianMGrid cgrid = read_dx<float>(examplefile);
center = cgrid.center();
resolution = cgrid.resolution();
dimension = resolution * (cgrid.grid().dimension(0) - 1);
center_set = true;
N = 1 + round(dimension / resolution);
}
//read in specified grid files and set usergrids and grid parameters appropriately
void MolGridder::set_usergrids(const vector<string>& userfiles) {
if (userfiles.size() > 0) {
//use grid specified by user
if (random_rotate || random_translate) {
cerr << "Random rotation/translation is not supported with user grids.\n";
exit(1);
}
}
usergrids.resize(0);
usergrids.reserve(userfiles.size());
center_set = true; //defiend by user grids
for (unsigned i = 0, ng = userfiles.size(); i < ng; i++) {
//load dx file
CartesianMGrid cgrid = read_dx<float>(userfiles[i]);
unsigned npts = cgrid.grid().dimension(0);
usergrids.push_back(cgrid.grid());
//check resolution/dimensions
if (i == 0) {
resolution = cgrid.resolution();
center = cgrid.center();
dimension = resolution * (npts - 1); //fencepost
} else {
if (cgrid.resolution() != resolution) {
cerr << "Inconsistent resolutions in grids: " << cgrid.resolution()
<< " vs "
<< resolution << "\n";
exit(1);
}
double dim = resolution * (npts - 1);
if (dim != dimension) {
cerr << "Inconsistent dimensions in grids: " << dim << " vs "
<< dimension << "\n";
exit(1);
}
if (center != cgrid.center()) {
cerr << "Inconsistent centers in grids\n";
exit(1);
}
}
}
N = 1 + round(dimension / resolution);
}
bool MolGridder::readMolecule(bool timeit) {
model m;
if (!mols.readMoleculeIntoModel(m)) return false;
setLigand(m);
boost::timer::cpu_timer t;
setGrid(gpu);
if (timeit) {
cout << "Grid Time: " << t.elapsed().wall << "\n";
cpuSetGridCheck();
}
return true;
}
//return true if grid only contains zeroes
static bool gridIsEmpty(const Grid3f& grid) {
for (const float *ptr = grid.data(), *end = grid.data() + grid.size();
ptr != end; ptr++) {
if (*ptr != 0.0) return false;
}
return true;
}
//output map for each grid
void MolGridder::outputMAP(const std::string& base) {
std::vector<std::string> recnames = rectyper->get_type_names();
for (unsigned a = 0, na = recnames.size(); a < na; a++) {
//this is for debugging, so avoid outputting empty grids
if (!gridIsEmpty(grid[a])) {
string name = recnames[a];
string fname = base + "_rec_" + name + ".map";
ofstream out(fname.c_str());
libmolgrid::write_map<float>(out, grid[a], center, resolution);
}
}
std::vector<std::string> lignames = ligtyper->get_type_names();
unsigned roff = recnames.size();
for (unsigned a = 0, na = lignames.size(); a < na; a++) {
if (!gridIsEmpty(grid[roff+a])) {
string name = lignames[a];
string fname = base + "_lig_" + name + ".map";
ofstream out(fname.c_str());
libmolgrid::write_map<float>(out,grid[roff+a], center, resolution);
}
}
}
//output an dx map for each grid
void MolGridder::outputDX(const std::string& base) {
std::vector<std::string> recnames = rectyper->get_type_names();
for (unsigned a = 0, na = recnames.size(); a < na; a++) {
//this is for debugging, so avoid outputting empty grids
if (!gridIsEmpty(grid[a])) {
string name = recnames[a];
string fname = base + "_rec_" + name + ".map";
ofstream out(fname.c_str());
libmolgrid::write_dx<float>(out, grid[a], center, resolution);
}
}
std::vector<std::string> lignames = ligtyper->get_type_names();
unsigned roff = recnames.size();
for (unsigned a = 0, na = lignames.size(); a < na; a++) {
if (!gridIsEmpty(grid[roff+a])) {
string name = lignames[a];
string fname = base + "_lig_" + name + ".map";
ofstream out(fname.c_str());
libmolgrid::write_dx<float>(out,grid[roff+a], center, resolution);
}
}
}
//output binary form of raw data in 3D multi-channel form
void MolGridder::outputBIN(const std::string& base, bool outputrec, bool outputlig) {
unsigned chan = 0;
if (outputrec) chan += rectyper->num_types() + usergrids.size();
if (outputlig) chan += ligtyper->num_types();
string outname = base + "." + boost::lexical_cast<string>(N) + "." + boost::lexical_cast<string>(chan);
ofstream binout(outname.c_str());
if(!binout) {
throw file_error(outname, false);
}
if(outputrec) {
for(unsigned i = 0, n = usergrids.size(); i < n; i++) {
write_bin(binout, usergrids[i]);
}
for (unsigned a = 0, na = rectyper->num_types(); a < na; a++) {
write_bin(binout, grid[a]);
}
}
unsigned roff = rectyper->num_types();
if(outputlig) {
for (unsigned a = 0, na = ligtyper->num_types(); a < na; a++) {
write_bin(binout, grid[roff+a]);
}
}
}
|
/*
* molgridder.cpp
*
* Created on: Apr 23, 2019
* Author: dkoes
*/
#include "molgridder.h"
#include <libmolgrid/cartesian_grid.h>
#include <boost/timer/timer.hpp>
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace libmolgrid;
MolGridder::MolGridder(const gridoptions& opt) :
dimension(opt.dim), resolution(opt.res),
random_rotate(opt.randrotate), random_translate(opt.randtranslate),
gmaker(opt.res, opt.dim), gpu(opt.gpu) {
ex.sets.resize(2); //ligand and receptor
//setup typers
rectyper = std::make_shared<FileMappedGninaTyper>(defaultGninaReceptorTyper);
ligtyper = std::make_shared<FileMappedGninaTyper>(defaultGninaLigandTyper);
if (opt.recmap.size() > 0) {
rectyper = std::make_shared<FileMappedGninaTyper>(opt.recmap);
}
if (opt.ligmap.size() > 0) {
ligtyper = std::make_shared<FileMappedGninaTyper>(opt.ligmap);
}
float3 dims = gmaker.get_grid_dims();
grid = MGrid4f(rectyper->num_types()+ligtyper->num_types(), dims[0], dims[1], dims[2]);
tee log(true);
FlexInfo finfo(log); //dummy
mols.create_init_model(opt.receptorfile, "", finfo, log);
mols.setInputFile(opt.ligandfile);
N = 1 + round(dimension / resolution);
if (opt.examplegrid.size() > 0) set_from_example(opt.examplegrid);
if (opt.usergrids.size()) set_usergrids(opt.usergrids);
setReceptor(mols.getInitModel());
if(opt.separate) setGrid(gpu);
}
//set receptor coordinate set from model
void MolGridder::setReceptor(const model& m) {
const atomv& atoms = m.get_fixed_atoms();
vector<libmolgrid::cuda_float3> coords; coords.reserve(atoms.size());
vector<unsigned> t; t.reserve(atoms.size());
vector<float> r; t.reserve(atoms.size());
for (unsigned i = 0, n = atoms.size(); i < n; i++) {
const atom& a = atoms[i];
auto t_r = rectyper->get_int_type(a.sm);
if (t_r.first >= 0) {
coords.push_back(gfloat3(a.coords));
t.push_back(t_r.first);
r.push_back(t_r.second);
}
}
ex.sets[0] = CoordinateSet(coords, t, r, rectyper->num_types());
}
void MolGridder::setLigand(const model& m) {
const atomv& atoms = m.get_movable_atoms();
assert(atoms.size() == m.coordinates().size());
vector<libmolgrid::cuda_float3> coords; coords.reserve(atoms.size());
vector<unsigned> t; t.reserve(atoms.size());
vector<float> r; t.reserve(atoms.size());
for (unsigned i = 0, n = atoms.size(); i < n; i++) {
const atom& a = atoms[i];
auto t_r = ligtyper->get_int_type(a.sm);
if (t_r.first >= 0) {
coords.push_back(gfloat3(a.coords));
t.push_back(t_r.first);
r.push_back(t_r.second);
}
}
ex.sets[1] = CoordinateSet(coords, t, r, ligtyper->num_types());
}
//convert ex to a grid
void MolGridder::setGrid(bool use_gpu) {
if(!center_set) {
//get center from lig
center = ex.sets[1].center();
}
if(random_translate > 0 || random_rotate) {
//update transform
current_transform = Transform(center, random_translate, random_rotate);
} else {
current_transform.set_rotation_center(center);
}
if(usergrids.size() > 0) { //not particularly optimized
//copy into first so many channels
unsigned n = usergrids.size();
for(unsigned i = 0; i < n; i++) {
grid[i].copyFrom(usergrids[i].cpu());
}
size_t offset = grid[0].size()*n;
unsigned channels = rectyper->num_types()+ligtyper->num_types();
if(use_gpu) {
Grid4fCUDA g(grid.data()+offset, channels, N, N, N);
gmaker.forward(ex, current_transform, g);
} else {
Grid4f g(grid.data()+offset, channels, N, N, N);
gmaker.forward(ex, current_transform, g);
}
}
else { //no user grids
if(use_gpu) {
gmaker.forward(ex, current_transform, grid.gpu());
} else {
gmaker.forward(ex, current_transform, grid.cpu());
}
}
}
void MolGridder::cpuSetGridCheck() {
//assume current grid is right
MGrid4f saved = grid.clone();
//for recompute, apply same transformation
bool saverot = random_rotate;
float savetrans = random_translate;
setGrid(false);
random_rotate = saverot;
random_translate = savetrans;
//now compare
if(saved.size() != grid.size()) {
cerr << "Different sized grids in compare\n";
exit(-1);
}
float* a = saved.data();
float* b = grid.data();
for(unsigned i = 0, n = grid.size(); i < n; i++) {
float diff = a[i]-b[i];
if(fabs(diff) > 0.0001) {
cerr << "Values differ " << a[i] << " != " << b[i] << " at index " << i << "\n";
exit(1);
}
}
}
void MolGridder::set_center(float3 c) {
center_set = true;
center = c;
}
//set grid parameters from an example dx
void MolGridder::set_from_example(const string& examplefile) {
CartesianMGrid cgrid = read_dx<float>(examplefile);
center = cgrid.center();
resolution = cgrid.resolution();
dimension = resolution * (cgrid.grid().dimension(0) - 1);
center_set = true;
N = 1 + round(dimension / resolution);
}
//read in specified grid files and set usergrids and grid parameters appropriately
void MolGridder::set_usergrids(const vector<string>& userfiles) {
if (userfiles.size() > 0) {
//use grid specified by user
if (random_rotate || random_translate) {
cerr << "Random rotation/translation is not supported with user grids.\n";
exit(1);
}
}
usergrids.resize(0);
usergrids.reserve(userfiles.size());
center_set = true; //defiend by user grids
for (unsigned i = 0, ng = userfiles.size(); i < ng; i++) {
//load dx file
CartesianMGrid cgrid = read_dx<float>(userfiles[i]);
unsigned npts = cgrid.grid().dimension(0);
usergrids.push_back(cgrid.grid());
//check resolution/dimensions
if (i == 0) {
resolution = cgrid.resolution();
center = cgrid.center();
dimension = resolution * (npts - 1); //fencepost
} else {
if (cgrid.resolution() != resolution) {
cerr << "Inconsistent resolutions in grids: " << cgrid.resolution()
<< " vs "
<< resolution << "\n";
exit(1);
}
double dim = resolution * (npts - 1);
if (dim != dimension) {
cerr << "Inconsistent dimensions in grids: " << dim << " vs "
<< dimension << "\n";
exit(1);
}
if (center != cgrid.center()) {
cerr << "Inconsistent centers in grids\n";
exit(1);
}
}
}
N = 1 + round(dimension / resolution);
}
bool MolGridder::readMolecule(bool timeit) {
model m;
if (!mols.readMoleculeIntoModel(m)) return false;
setLigand(m);
boost::timer::cpu_timer t;
setGrid(gpu);
if (timeit) {
cout << "Grid Time: " << t.elapsed().wall << "\n";
cpuSetGridCheck();
}
return true;
}
//return true if grid only contains zeroes
static bool gridIsEmpty(const Grid3f& grid) {
for (const float *ptr = grid.data(), *end = grid.data() + grid.size();
ptr != end; ptr++) {
if (*ptr != 0.0) return false;
}
return true;
}
//output map for each grid
void MolGridder::outputMAP(const std::string& base) {
std::vector<std::string> recnames = rectyper->get_type_names();
for (unsigned a = 0, na = recnames.size(); a < na; a++) {
//this is for debugging, so avoid outputting empty grids
if (!gridIsEmpty(grid[a])) {
string name = recnames[a];
string fname = base + "_rec_" + name + ".map";
ofstream out(fname.c_str());
libmolgrid::write_map<float>(out, grid[a], center, resolution);
}
}
std::vector<std::string> lignames = ligtyper->get_type_names();
unsigned roff = recnames.size();
for (unsigned a = 0, na = lignames.size(); a < na; a++) {
if (!gridIsEmpty(grid[roff+a])) {
string name = lignames[a];
string fname = base + "_lig_" + name + ".map";
ofstream out(fname.c_str());
libmolgrid::write_map<float>(out,grid[roff+a], center, resolution);
}
}
}
//output an dx map for each grid
void MolGridder::outputDX(const std::string& base) {
std::vector<std::string> recnames = rectyper->get_type_names();
for (unsigned a = 0, na = recnames.size(); a < na; a++) {
//this is for debugging, so avoid outputting empty grids
if (!gridIsEmpty(grid[a])) {
string name = recnames[a];
string fname = base + "_rec_" + name + ".map";
ofstream out(fname.c_str());
libmolgrid::write_dx<float>(out, grid[a], center, resolution);
}
}
std::vector<std::string> lignames = ligtyper->get_type_names();
unsigned roff = recnames.size();
for (unsigned a = 0, na = lignames.size(); a < na; a++) {
if (!gridIsEmpty(grid[roff+a])) {
string name = lignames[a];
string fname = base + "_lig_" + name + ".map";
ofstream out(fname.c_str());
libmolgrid::write_dx<float>(out,grid[roff+a], center, resolution);
}
}
}
//output binary form of raw data in 3D multi-channel form
void MolGridder::outputBIN(const std::string& base, bool outputrec, bool outputlig) {
unsigned chan = 0;
if (outputrec) chan += rectyper->num_types() + usergrids.size();
if (outputlig) chan += ligtyper->num_types();
string outname = base + "." + boost::lexical_cast<string>(N) + "." + boost::lexical_cast<string>(chan);
ofstream binout(outname.c_str());
if(!binout) {
throw file_error(outname, false);
}
if(outputrec) {
for(unsigned i = 0, n = usergrids.size(); i < n; i++) {
write_bin(binout, usergrids[i]);
}
for (unsigned a = 0, na = rectyper->num_types(); a < na; a++) {
write_bin(binout, grid[a]);
}
}
unsigned roff = rectyper->num_types();
if(outputlig) {
for (unsigned a = 0, na = ligtyper->num_types(); a < na; a++) {
write_bin(binout, grid[roff+a]);
}
}
}
|
fix segfault
|
fix segfault
|
C++
|
apache-2.0
|
gnina/gnina,gnina/gnina,gnina/gnina,gnina/gnina,gnina/gnina,gnina/gnina
|
1e701b2fdaa10672393c7196ee6a08caf5d89b20
|
mordor/streams/timeout.cpp
|
mordor/streams/timeout.cpp
|
// Copyright (c) 2010 - Mozy, Inc.
#include "mordor/pch.h"
#include "timeout.h"
#include "mordor/exception.h"
#include "mordor/socket.h"
#include "mordor/timer.h"
namespace Mordor {
static void cancelReadLocal(Stream::ptr stream, bool &flag)
{
stream->cancelRead();
flag = true;
}
static void cancelWriteLocal(Stream::ptr stream, bool &flag)
{
stream->cancelWrite();
flag = true;
}
void
TimeoutStream::readTimeout(unsigned long long readTimeout)
{
FiberMutex::ScopedLock lock(m_mutex);
m_readTimeout = readTimeout;
if (m_readTimer) {
if (readTimeout == ~0ull)
m_readTimer->cancel();
else
m_readTimer->reset(readTimeout, true);
} else if (m_readTimeout != ~0ull && !m_readTimedOut) {
m_readTimer = m_timerManager.registerTimer(m_readTimeout,
boost::bind(&cancelReadLocal, parent(),
boost::ref(m_readTimedOut)));
}
}
void
TimeoutStream::writeTimeout(unsigned long long writeTimeout)
{
FiberMutex::ScopedLock lock(m_mutex);
m_writeTimeout = writeTimeout;
if (m_writeTimer) {
if (writeTimeout == ~0ull)
m_writeTimer->cancel();
else
m_writeTimer->reset(writeTimeout, true);
} else if (m_writeTimeout != ~0ull && !m_writeTimedOut) {
m_writeTimer = m_timerManager.registerTimer(m_writeTimeout,
boost::bind(&cancelWriteLocal, parent(),
boost::ref(m_writeTimedOut)));
}
}
size_t
TimeoutStream::read(Buffer &buffer, size_t length)
{
FiberMutex::ScopedLock lock(m_mutex);
m_readTimedOut = false;
if (m_readTimeout != ~0ull)
m_readTimer = m_timerManager.registerTimer(m_readTimeout,
boost::bind(&cancelReadLocal, parent(),
boost::ref(m_readTimedOut)));
lock.unlock();
size_t result;
try {
result = parent()->read(buffer, length);
} catch (OperationAbortedException &) {
lock.lock();
if (m_readTimedOut)
MORDOR_THROW_EXCEPTION(TimedOutException());
m_readTimedOut = true;
throw;
}
lock.lock();
if (m_readTimer)
m_readTimer->cancel();
m_readTimedOut = true;
return result;
}
size_t
TimeoutStream::write(const Buffer &buffer, size_t length)
{
FiberMutex::ScopedLock lock(m_mutex);
m_writeTimedOut = false;
if (m_writeTimeout != ~0ull)
m_writeTimer = m_timerManager.registerTimer(m_writeTimeout,
boost::bind(&cancelWriteLocal, parent(),
boost::ref(m_writeTimedOut)));
lock.unlock();
size_t result;
try {
result = parent()->write(buffer, length);
} catch (OperationAbortedException &) {
lock.lock();
if (m_writeTimedOut)
MORDOR_THROW_EXCEPTION(TimedOutException());
m_writeTimedOut = true;
throw;
}
lock.lock();
if (m_writeTimer)
m_writeTimer->cancel();
m_writeTimedOut = true;
return result;
}
}
|
// Copyright (c) 2010 - Mozy, Inc.
#include "mordor/pch.h"
#include "timeout.h"
#include "mordor/exception.h"
#include "mordor/log.h"
#include "mordor/socket.h"
#include "mordor/timer.h"
namespace Mordor {
static Logger::ptr g_log = Log::lookup("mordor:streams:timeout");
static void cancelReadLocal(Stream::ptr stream, bool &flag)
{
MORDOR_LOG_INFO(g_log) << "read timeout";
stream->cancelRead();
flag = true;
}
static void cancelWriteLocal(Stream::ptr stream, bool &flag)
{
MORDOR_LOG_INFO(g_log) << "write timeout";
stream->cancelWrite();
flag = true;
}
void
TimeoutStream::readTimeout(unsigned long long readTimeout)
{
FiberMutex::ScopedLock lock(m_mutex);
m_readTimeout = readTimeout;
if (m_readTimer) {
if (readTimeout == ~0ull)
m_readTimer->cancel();
else
m_readTimer->reset(readTimeout, true);
} else if (m_readTimeout != ~0ull && !m_readTimedOut) {
m_readTimer = m_timerManager.registerTimer(m_readTimeout,
boost::bind(&cancelReadLocal, parent(),
boost::ref(m_readTimedOut)));
}
}
void
TimeoutStream::writeTimeout(unsigned long long writeTimeout)
{
FiberMutex::ScopedLock lock(m_mutex);
m_writeTimeout = writeTimeout;
if (m_writeTimer) {
if (writeTimeout == ~0ull)
m_writeTimer->cancel();
else
m_writeTimer->reset(writeTimeout, true);
} else if (m_writeTimeout != ~0ull && !m_writeTimedOut) {
m_writeTimer = m_timerManager.registerTimer(m_writeTimeout,
boost::bind(&cancelWriteLocal, parent(),
boost::ref(m_writeTimedOut)));
}
}
size_t
TimeoutStream::read(Buffer &buffer, size_t length)
{
FiberMutex::ScopedLock lock(m_mutex);
m_readTimedOut = false;
if (m_readTimeout != ~0ull)
m_readTimer = m_timerManager.registerTimer(m_readTimeout,
boost::bind(&cancelReadLocal, parent(),
boost::ref(m_readTimedOut)));
lock.unlock();
size_t result;
try {
result = parent()->read(buffer, length);
} catch (OperationAbortedException &) {
lock.lock();
if (m_readTimer)
m_readTimer->cancel();
if (m_readTimedOut)
MORDOR_THROW_EXCEPTION(TimedOutException());
m_readTimedOut = true;
throw;
}
lock.lock();
if (m_readTimer)
m_readTimer->cancel();
m_readTimedOut = true;
return result;
}
size_t
TimeoutStream::write(const Buffer &buffer, size_t length)
{
FiberMutex::ScopedLock lock(m_mutex);
m_writeTimedOut = false;
if (m_writeTimeout != ~0ull)
m_writeTimer = m_timerManager.registerTimer(m_writeTimeout,
boost::bind(&cancelWriteLocal, parent(),
boost::ref(m_writeTimedOut)));
lock.unlock();
size_t result;
try {
result = parent()->write(buffer, length);
} catch (OperationAbortedException &) {
lock.lock();
if (m_writeTimer)
m_writeTimer->cancel();
if (m_writeTimedOut)
MORDOR_THROW_EXCEPTION(TimedOutException());
m_writeTimedOut = true;
throw;
}
lock.lock();
if (m_writeTimer)
m_writeTimer->cancel();
m_writeTimedOut = true;
return result;
}
}
|
Make sure to cancel the timeout if a read/write fails.
|
Make sure to cancel the timeout if a read/write fails.
Change-Id: I883a6af37b9dfcc4e6e6973f7a07102ee70d218b
Reviewed-on: https://gerrit.dechocorp.com/4745
Reviewed-by: Jeremy Stanley <[email protected]>
Reviewed-by: Russ Simons <[email protected]>
|
C++
|
bsd-3-clause
|
mtanski/mordor,cgaebel/mordor,mtanski/mordor,adfin/mordor,mtanski/mordor,mozy/mordor,mozy/mordor,adfin/mordor,ccutrer/mordor,ccutrer/mordor,ccutrer/mordor,mozy/mordor,cgaebel/mordor,adfin/mordor
|
d887d0ba518b4181259b7dda8a501b23d4ba542a
|
hoomd/md/MolecularForceCompute.cc
|
hoomd/md/MolecularForceCompute.cc
|
// Copyright (c) 2009-2017 The Regents of the University of Michigan
// This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.
// Maintainer: jglaser
#include "MolecularForceCompute.h"
#include "hoomd/CachedAllocator.h"
#include "hoomd/Autotuner.h"
#ifdef ENABLE_CUDA
#include "MolecularForceCompute.cuh"
#endif
#include <string.h>
#include <map>
namespace py = pybind11;
/*! \file MolecularForceCompute.cc
\brief Contains code for the MolecularForceCompute class
*/
/*! \param sysdef SystemDefinition containing the ParticleData to compute forces on
*/
MolecularForceCompute::MolecularForceCompute(std::shared_ptr<SystemDefinition> sysdef)
: ForceConstraint(sysdef), m_molecule_tag(m_exec_conf), m_n_molecules_global(0),
m_molecule_list(m_exec_conf), m_molecule_length(m_exec_conf), m_molecule_order(m_exec_conf),
m_molecule_idx(m_exec_conf), m_dirty(true)
{
// connect to the ParticleData to recieve notifications when particles change order in memory
m_pdata->getParticleSortSignal().connect<MolecularForceCompute, &MolecularForceCompute::setDirty>(this);
#ifdef ENABLE_CUDA
if (m_exec_conf->isCUDAEnabled())
{
// initialize autotuner
std::vector<unsigned int> valid_params;
for (unsigned int block_size = 32; block_size <= 1024; block_size += 32)
valid_params.push_back(block_size);
m_tuner_fill.reset(new Autotuner(valid_params, 5, 100000, "fill_molecule_table", this->m_exec_conf));
}
#endif
}
//! Destructor
MolecularForceCompute::~MolecularForceCompute()
{
m_pdata->getParticleSortSignal().disconnect<MolecularForceCompute, &MolecularForceCompute::setDirty>(this);
}
#ifdef ENABLE_CUDA
void MolecularForceCompute::initMoleculesGPU()
{
if (m_prof) m_prof->push(m_exec_conf,"init molecules");
unsigned int nptl_local = m_pdata->getN() + m_pdata->getNGhosts();
unsigned int n_local_molecules = 0;
// maximum molecule length
unsigned int nmax = 0;
// number of local particles that are part of molecules
unsigned int n_local_ptls_in_molecules = 0;
// resize to maximum possible number of local molecules
m_molecule_length.resize(nptl_local);
m_molecule_idx.resize(nptl_local);
ScopedAllocation<unsigned int> d_idx_sorted_by_tag(m_exec_conf->getCachedAllocator(), nptl_local);
ScopedAllocation<unsigned int> d_local_molecule_tags(m_exec_conf->getCachedAllocator(), nptl_local);
{
ArrayHandle<unsigned int> d_molecule_tag(m_molecule_tag, access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_tag(m_pdata->getTags(), access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_molecule_length(m_molecule_length, access_location::device, access_mode::overwrite);
ArrayHandle<unsigned int> d_molecule_idx(m_molecule_idx, access_location::device, access_mode::overwrite);
// temporary buffers
ScopedAllocation<unsigned int> d_local_unique_molecule_tags(m_exec_conf->getCachedAllocator(), m_n_molecules_global);
ScopedAllocation<unsigned int> d_sorted_by_tag(m_exec_conf->getCachedAllocator(), nptl_local);
gpu_sort_by_molecule(nptl_local,
d_tag.data,
d_molecule_tag.data,
d_local_molecule_tags.data,
d_local_unique_molecule_tags.data,
d_molecule_idx.data,
d_sorted_by_tag.data,
d_idx_sorted_by_tag.data,
d_molecule_length.data,
n_local_molecules,
nmax,
n_local_ptls_in_molecules,
m_exec_conf->getCachedAllocator());
if (m_exec_conf->isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
}
// set up indexer
m_molecule_indexer = Index2D(n_local_molecules, nmax);
// resize molecule list
m_molecule_list.resize(m_molecule_indexer.getNumElements());
// resize molecule lookup to size of local particle data
m_molecule_order.resize(m_pdata->getMaxN());
{
// write out molecule list and order
ArrayHandle<unsigned int> d_molecule_list(m_molecule_list, access_location::device, access_mode::overwrite);
ArrayHandle<unsigned int> d_molecule_order(m_molecule_order, access_location::device, access_mode::overwrite);
ArrayHandle<unsigned int> d_molecule_idx(m_molecule_idx, access_location::device, access_mode::read);
m_tuner_fill->begin();
unsigned int block_size = m_tuner_fill->getParam();
gpu_fill_molecule_table(nptl_local,
n_local_ptls_in_molecules,
m_molecule_indexer,
d_molecule_idx.data,
d_local_molecule_tags.data,
d_idx_sorted_by_tag.data,
d_molecule_list.data,
d_molecule_order.data,
block_size,
m_exec_conf->getCachedAllocator());
if (m_exec_conf->isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
m_tuner_fill->end();
}
if (m_prof) m_prof->pop(m_exec_conf);
}
#endif
void MolecularForceCompute::initMolecules()
{
// return early if no molecules are defined
if (!m_n_molecules_global) return;
m_exec_conf->msg->notice(7) << "MolecularForceCompute initializing molecule table" << std::endl;
#ifdef ENABLE_CUDA
if (m_exec_conf->isCUDAEnabled())
{
initMoleculesGPU();
return;
}
#endif
if (m_prof) m_prof->push("init molecules");
// construct local molecule table
unsigned int nptl_local = m_pdata->getN() + m_pdata->getNGhosts();
ArrayHandle<unsigned int> h_molecule_tag(m_molecule_tag, access_location::host, access_mode::read);
ArrayHandle<unsigned int> h_tag(m_pdata->getTags(), access_location::host, access_mode::read);
std::set<unsigned int> local_molecule_tags;
unsigned int n_local_molecules = 0;
std::vector<unsigned int> local_molecule_idx(nptl_local, NO_MOLECULE);
// resize molecule lookup to size of local particle data
m_molecule_order.resize(m_pdata->getMaxN());
// sort local molecules lexicographically by molecule and by ptl tag
std::map<unsigned int, std::set<unsigned int> > local_molecules_sorted;
for (unsigned int iptl = 0; iptl < nptl_local; ++iptl)
{
unsigned int tag = h_tag.data[iptl];
assert(tag < m_molecule_tag.getNumElements());
unsigned int mol_tag = h_molecule_tag.data[tag];
if (mol_tag == NO_MOLECULE) continue;
auto it = local_molecules_sorted.find(mol_tag);
if (it == local_molecules_sorted.end())
{
auto res = local_molecules_sorted.insert(std::make_pair(mol_tag,std::set<unsigned int>()));
assert(res.second);
it = res.first;
}
it->second.insert(tag);
}
n_local_molecules = local_molecules_sorted.size();
m_molecule_length.resize(n_local_molecules);
ArrayHandle<unsigned int> h_molecule_length(m_molecule_length, access_location::host, access_mode::overwrite);
// reset lengths
for (unsigned int imol = 0; imol < n_local_molecules; ++imol)
{
h_molecule_length.data[imol] = 0;
}
// count molecule lengths
unsigned int i = 0;
for (auto it = local_molecules_sorted.begin(); it != local_molecules_sorted.end(); ++it)
{
h_molecule_length.data[i++] = it->second.size();
}
// find maximum length
unsigned nmax = 0;
for (unsigned int imol = 0; imol < n_local_molecules; ++imol)
{
if (h_molecule_length.data[imol] > nmax)
{
nmax = h_molecule_length.data[imol];
}
}
// set up indexer
m_molecule_indexer = Index2D(n_local_molecules, nmax);
// resize molecule list
m_molecule_list.resize(m_molecule_indexer.getNumElements());
// reset lengths again
for (unsigned int imol = 0; imol < n_local_molecules; ++imol)
{
h_molecule_length.data[imol] = 0;
}
// reset molecule order
ArrayHandle<unsigned int> h_molecule_order(m_molecule_order, access_location::host, access_mode::overwrite);
memset(h_molecule_order.data, 0, sizeof(unsigned int)*(m_pdata->getN() + m_pdata->getNGhosts()));
// resize reverse-lookup
m_molecule_idx.resize(nptl_local);
// fill molecule list
ArrayHandle<unsigned int> h_molecule_list(m_molecule_list, access_location::host, access_mode::overwrite);
ArrayHandle<unsigned int> h_molecule_idx(m_molecule_idx, access_location::host, access_mode::overwrite);
ArrayHandle<unsigned int> h_rtag(m_pdata->getRTags(), access_location::host, access_mode::read);
// reset reverse lookup
memset(h_molecule_idx.data, 0, sizeof(unsigned int)*nptl_local);
unsigned int i_mol = 0;
for (auto it_mol = local_molecules_sorted.begin(); it_mol != local_molecules_sorted.end(); ++it_mol)
{
for (std::set<unsigned int>::iterator it_tag = it_mol->second.begin(); it_tag != it_mol->second.end(); ++it_tag)
{
unsigned int n = h_molecule_length.data[i_mol]++;
unsigned int ptl_idx = h_rtag.data[*it_tag];
assert(ptl_idx < m_pdata->getN() + m_pdata->getNGhosts());
h_molecule_list.data[m_molecule_indexer(i_mol, n)] = ptl_idx;
h_molecule_idx.data[ptl_idx] = i_mol;
h_molecule_order.data[ptl_idx] = n;
}
i_mol ++;
}
if (m_prof) m_prof->pop(m_exec_conf);
}
void export_MolecularForceCompute(py::module& m)
{
py::class_< MolecularForceCompute, std::shared_ptr<MolecularForceCompute> >(m, "MolecularForceCompute", py::base<ForceConstraint>())
.def(py::init< std::shared_ptr<SystemDefinition> >())
;
}
|
// Copyright (c) 2009-2017 The Regents of the University of Michigan
// This file is part of the HOOMD-blue project, released under the BSD 3-Clause License.
// Maintainer: jglaser
#include "MolecularForceCompute.h"
#include "hoomd/CachedAllocator.h"
#include "hoomd/Autotuner.h"
#ifdef ENABLE_CUDA
#include "MolecularForceCompute.cuh"
#endif
#include <string.h>
#include <map>
namespace py = pybind11;
/*! \file MolecularForceCompute.cc
\brief Contains code for the MolecularForceCompute class
*/
/*! \param sysdef SystemDefinition containing the ParticleData to compute forces on
*/
MolecularForceCompute::MolecularForceCompute(std::shared_ptr<SystemDefinition> sysdef)
: ForceConstraint(sysdef), m_molecule_tag(m_exec_conf), m_n_molecules_global(0),
m_molecule_list(m_exec_conf), m_molecule_length(m_exec_conf), m_molecule_order(m_exec_conf),
m_molecule_idx(m_exec_conf), m_dirty(true)
{
// connect to the ParticleData to recieve notifications when particles change order in memory
m_pdata->getParticleSortSignal().connect<MolecularForceCompute, &MolecularForceCompute::setDirty>(this);
#ifdef ENABLE_CUDA
if (m_exec_conf->isCUDAEnabled())
{
// initialize autotuner
std::vector<unsigned int> valid_params;
for (unsigned int block_size = 32; block_size <= 1024; block_size += 32)
valid_params.push_back(block_size);
m_tuner_fill.reset(new Autotuner(valid_params, 5, 100000, "fill_molecule_table", this->m_exec_conf));
}
#endif
}
//! Destructor
MolecularForceCompute::~MolecularForceCompute()
{
m_pdata->getParticleSortSignal().disconnect<MolecularForceCompute, &MolecularForceCompute::setDirty>(this);
}
#ifdef ENABLE_CUDA
void MolecularForceCompute::initMoleculesGPU()
{
if (m_prof) m_prof->push(m_exec_conf,"init molecules");
unsigned int nptl_local = m_pdata->getN() + m_pdata->getNGhosts();
unsigned int n_local_molecules = 0;
// maximum molecule length
unsigned int nmax = 0;
// number of local particles that are part of molecules
unsigned int n_local_ptls_in_molecules = 0;
// resize to maximum possible number of local molecules
m_molecule_length.resize(nptl_local);
m_molecule_idx.resize(nptl_local);
ScopedAllocation<unsigned int> d_idx_sorted_by_tag(m_exec_conf->getCachedAllocator(), nptl_local);
ScopedAllocation<unsigned int> d_local_molecule_tags(m_exec_conf->getCachedAllocator(), nptl_local);
{
ArrayHandle<unsigned int> d_molecule_tag(m_molecule_tag, access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_tag(m_pdata->getTags(), access_location::device, access_mode::read);
ArrayHandle<unsigned int> d_molecule_length(m_molecule_length, access_location::device, access_mode::overwrite);
ArrayHandle<unsigned int> d_molecule_idx(m_molecule_idx, access_location::device, access_mode::overwrite);
// temporary buffers
ScopedAllocation<unsigned int> d_local_unique_molecule_tags(m_exec_conf->getCachedAllocator(), m_n_molecules_global);
ScopedAllocation<unsigned int> d_sorted_by_tag(m_exec_conf->getCachedAllocator(), nptl_local);
gpu_sort_by_molecule(nptl_local,
d_tag.data,
d_molecule_tag.data,
d_local_molecule_tags.data,
d_local_unique_molecule_tags.data,
d_molecule_idx.data,
d_sorted_by_tag.data,
d_idx_sorted_by_tag.data,
d_molecule_length.data,
n_local_molecules,
nmax,
n_local_ptls_in_molecules,
m_exec_conf->getCachedAllocator());
if (m_exec_conf->isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
}
// set up indexer
m_molecule_indexer = Index2D(n_local_molecules, nmax);
m_exec_conf->msg->notice(7) << "MolecularForceCompute: " << n_local_molecules << " molecules, "
<< n_local_ptls_in_molecules << " particles in molceules " << std::endl;
// resize molecule list
m_molecule_list.resize(m_molecule_indexer.getNumElements());
// resize molecule lookup to size of local particle data
m_molecule_order.resize(m_pdata->getMaxN());
{
// write out molecule list and order
ArrayHandle<unsigned int> d_molecule_list(m_molecule_list, access_location::device, access_mode::overwrite);
ArrayHandle<unsigned int> d_molecule_order(m_molecule_order, access_location::device, access_mode::overwrite);
ArrayHandle<unsigned int> d_molecule_idx(m_molecule_idx, access_location::device, access_mode::read);
m_tuner_fill->begin();
unsigned int block_size = m_tuner_fill->getParam();
gpu_fill_molecule_table(nptl_local,
n_local_ptls_in_molecules,
m_molecule_indexer,
d_molecule_idx.data,
d_local_molecule_tags.data,
d_idx_sorted_by_tag.data,
d_molecule_list.data,
d_molecule_order.data,
block_size,
m_exec_conf->getCachedAllocator());
if (m_exec_conf->isCUDAErrorCheckingEnabled())
CHECK_CUDA_ERROR();
m_tuner_fill->end();
}
if (m_prof) m_prof->pop(m_exec_conf);
}
#endif
void MolecularForceCompute::initMolecules()
{
// return early if no molecules are defined
if (!m_n_molecules_global) return;
m_exec_conf->msg->notice(7) << "MolecularForceCompute initializing molecule table" << std::endl;
#ifdef ENABLE_CUDA
if (m_exec_conf->isCUDAEnabled())
{
initMoleculesGPU();
return;
}
#endif
if (m_prof) m_prof->push("init molecules");
// construct local molecule table
unsigned int nptl_local = m_pdata->getN() + m_pdata->getNGhosts();
ArrayHandle<unsigned int> h_molecule_tag(m_molecule_tag, access_location::host, access_mode::read);
ArrayHandle<unsigned int> h_tag(m_pdata->getTags(), access_location::host, access_mode::read);
std::set<unsigned int> local_molecule_tags;
unsigned int n_local_molecules = 0;
std::vector<unsigned int> local_molecule_idx(nptl_local, NO_MOLECULE);
// resize molecule lookup to size of local particle data
m_molecule_order.resize(m_pdata->getMaxN());
// sort local molecules lexicographically by molecule and by ptl tag
std::map<unsigned int, std::set<unsigned int> > local_molecules_sorted;
for (unsigned int iptl = 0; iptl < nptl_local; ++iptl)
{
unsigned int tag = h_tag.data[iptl];
assert(tag < m_molecule_tag.getNumElements());
unsigned int mol_tag = h_molecule_tag.data[tag];
if (mol_tag == NO_MOLECULE) continue;
auto it = local_molecules_sorted.find(mol_tag);
if (it == local_molecules_sorted.end())
{
auto res = local_molecules_sorted.insert(std::make_pair(mol_tag,std::set<unsigned int>()));
assert(res.second);
it = res.first;
}
it->second.insert(tag);
}
n_local_molecules = local_molecules_sorted.size();
m_exec_conf->msg->notice(7) << "MolecularForceCompute: " << n_local_molecules << " molecules" << std::endl;
m_molecule_length.resize(n_local_molecules);
ArrayHandle<unsigned int> h_molecule_length(m_molecule_length, access_location::host, access_mode::overwrite);
// reset lengths
for (unsigned int imol = 0; imol < n_local_molecules; ++imol)
{
h_molecule_length.data[imol] = 0;
}
// count molecule lengths
unsigned int i = 0;
for (auto it = local_molecules_sorted.begin(); it != local_molecules_sorted.end(); ++it)
{
h_molecule_length.data[i++] = it->second.size();
}
// find maximum length
unsigned nmax = 0;
for (unsigned int imol = 0; imol < n_local_molecules; ++imol)
{
if (h_molecule_length.data[imol] > nmax)
{
nmax = h_molecule_length.data[imol];
}
}
// set up indexer
m_molecule_indexer = Index2D(n_local_molecules, nmax);
// resize molecule list
m_molecule_list.resize(m_molecule_indexer.getNumElements());
// reset lengths again
for (unsigned int imol = 0; imol < n_local_molecules; ++imol)
{
h_molecule_length.data[imol] = 0;
}
// reset molecule order
ArrayHandle<unsigned int> h_molecule_order(m_molecule_order, access_location::host, access_mode::overwrite);
memset(h_molecule_order.data, 0, sizeof(unsigned int)*(m_pdata->getN() + m_pdata->getNGhosts()));
// resize reverse-lookup
m_molecule_idx.resize(nptl_local);
// fill molecule list
ArrayHandle<unsigned int> h_molecule_list(m_molecule_list, access_location::host, access_mode::overwrite);
ArrayHandle<unsigned int> h_molecule_idx(m_molecule_idx, access_location::host, access_mode::overwrite);
ArrayHandle<unsigned int> h_rtag(m_pdata->getRTags(), access_location::host, access_mode::read);
// reset reverse lookup
memset(h_molecule_idx.data, 0, sizeof(unsigned int)*nptl_local);
unsigned int i_mol = 0;
for (auto it_mol = local_molecules_sorted.begin(); it_mol != local_molecules_sorted.end(); ++it_mol)
{
for (std::set<unsigned int>::iterator it_tag = it_mol->second.begin(); it_tag != it_mol->second.end(); ++it_tag)
{
unsigned int n = h_molecule_length.data[i_mol]++;
unsigned int ptl_idx = h_rtag.data[*it_tag];
assert(ptl_idx < m_pdata->getN() + m_pdata->getNGhosts());
h_molecule_list.data[m_molecule_indexer(i_mol, n)] = ptl_idx;
h_molecule_idx.data[ptl_idx] = i_mol;
h_molecule_order.data[ptl_idx] = n;
}
i_mol ++;
}
if (m_prof) m_prof->pop(m_exec_conf);
}
void export_MolecularForceCompute(py::module& m)
{
py::class_< MolecularForceCompute, std::shared_ptr<MolecularForceCompute> >(m, "MolecularForceCompute", py::base<ForceConstraint>())
.def(py::init< std::shared_ptr<SystemDefinition> >())
;
}
|
add debug output
|
add debug output
|
C++
|
bsd-3-clause
|
joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue,joaander/hoomd-blue
|
6a9d3b5be3d171203791a355183d64c6b23093e0
|
COFF/PDB.cpp
|
COFF/PDB.cpp
|
//===- PDB.cpp ------------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "PDB.h"
#include "Chunks.h"
#include "Config.h"
#include "Error.h"
#include "SymbolTable.h"
#include "Symbols.h"
#include "llvm/DebugInfo/CodeView/CVDebugRecord.h"
#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
#include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
#include "llvm/DebugInfo/CodeView/SymbolDumper.h"
#include "llvm/DebugInfo/CodeView/TypeDatabase.h"
#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
#include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
#include "llvm/DebugInfo/CodeView/TypeTableBuilder.h"
#include "llvm/DebugInfo/MSF/MSFBuilder.h"
#include "llvm/DebugInfo/MSF/MSFCommon.h"
#include "llvm/DebugInfo/PDB/Native/DbiStream.h"
#include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
#include "llvm/DebugInfo/PDB/Native/InfoStream.h"
#include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
#include "llvm/DebugInfo/PDB/Native/PDBFile.h"
#include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
#include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
#include "llvm/DebugInfo/PDB/Native/PDBTypeServerHandler.h"
#include "llvm/DebugInfo/PDB/Native/TpiStream.h"
#include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
#include "llvm/Object/COFF.h"
#include "llvm/Support/BinaryByteStream.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/FileOutputBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/ScopedPrinter.h"
#include <memory>
using namespace lld;
using namespace lld::coff;
using namespace llvm;
using namespace llvm::codeview;
using namespace llvm::support;
using namespace llvm::support::endian;
using llvm::object::coff_section;
static ExitOnError ExitOnErr;
// Returns a list of all SectionChunks.
static std::vector<coff_section> getInputSections(SymbolTable *Symtab) {
std::vector<coff_section> V;
for (Chunk *C : Symtab->getChunks())
if (auto *SC = dyn_cast<SectionChunk>(C))
V.push_back(*SC->Header);
return V;
}
static SectionChunk *findByName(std::vector<SectionChunk *> &Sections,
StringRef Name) {
for (SectionChunk *C : Sections)
if (C->getSectionName() == Name)
return C;
return nullptr;
}
static ArrayRef<uint8_t> getDebugSection(ObjectFile *File, StringRef SecName) {
SectionChunk *Sec = findByName(File->getDebugChunks(), SecName);
if (!Sec)
return {};
// First 4 bytes are section magic.
ArrayRef<uint8_t> Data = Sec->getContents();
if (Data.size() < 4)
fatal(SecName + " too short");
if (read32le(Data.data()) != COFF::DEBUG_SECTION_MAGIC)
fatal(SecName + " has an invalid magic");
return Data.slice(4);
}
static void addTypeInfo(pdb::TpiStreamBuilder &TpiBuilder,
codeview::TypeTableBuilder &TypeTable) {
// Start the TPI or IPI stream header.
TpiBuilder.setVersionHeader(pdb::PdbTpiV80);
// Flatten the in memory type table.
TypeTable.ForEachRecord([&](TypeIndex TI, ArrayRef<uint8_t> Rec) {
// FIXME: Hash types.
TpiBuilder.addTypeRecord(Rec, None);
});
}
// Merge .debug$T sections into IpiData and TpiData.
static void mergeDebugT(SymbolTable *Symtab, pdb::PDBFileBuilder &Builder,
codeview::TypeTableBuilder &TypeTable,
codeview::TypeTableBuilder &IDTable) {
// Visit all .debug$T sections to add them to Builder.
for (ObjectFile *File : Symtab->ObjectFiles) {
ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
if (Data.empty())
continue;
BinaryByteStream Stream(Data, support::little);
codeview::CVTypeArray Types;
BinaryStreamReader Reader(Stream);
SmallVector<TypeIndex, 128> SourceToDest;
// Follow type servers. If the same type server is encountered more than
// once for this instance of `PDBTypeServerHandler` (for example if many
// object files reference the same TypeServer), the types from the
// TypeServer will only be visited once.
pdb::PDBTypeServerHandler Handler;
Handler.addSearchPath(llvm::sys::path::parent_path(File->getName()));
if (auto EC = Reader.readArray(Types, Reader.getLength()))
fatal(EC, "Reader::readArray failed");
if (auto Err = codeview::mergeTypeAndIdRecords(
IDTable, TypeTable, SourceToDest, &Handler, Types))
fatal(Err, "codeview::mergeTypeStreams failed");
}
// Construct TPI stream contents.
addTypeInfo(Builder.getTpiBuilder(), TypeTable);
// Construct IPI stream contents.
addTypeInfo(Builder.getIpiBuilder(), IDTable);
}
static void dumpDebugT(ScopedPrinter &W, ObjectFile *File) {
ListScope LS(W, "DebugT");
ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
if (Data.empty())
return;
LazyRandomTypeCollection Types(Data, 100);
TypeDumpVisitor TDV(Types, &W, false);
// Use a default implementation that does not follow type servers and instead
// just dumps the contents of the TypeServer2 record.
if (auto EC = codeview::visitTypeStream(Types, TDV))
fatal(EC, "CVTypeDumper::dump failed");
}
static void dumpDebugS(ScopedPrinter &W, ObjectFile *File) {
ListScope LS(W, "DebugS");
ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$S");
if (Data.empty())
return;
BinaryByteStream Stream(Data, llvm::support::little);
CVSymbolArray Symbols;
BinaryStreamReader Reader(Stream);
if (auto EC = Reader.readArray(Symbols, Reader.getLength()))
fatal(EC, "StreamReader.readArray<CVSymbolArray> failed");
TypeDatabase TDB(0);
CVSymbolDumper SymbolDumper(W, TDB, nullptr, false);
if (auto EC = SymbolDumper.dump(Symbols))
fatal(EC, "CVSymbolDumper::dump failed");
}
// Dump CodeView debug info. This is for debugging.
static void dumpCodeView(SymbolTable *Symtab) {
ScopedPrinter W(outs());
for (ObjectFile *File : Symtab->ObjectFiles) {
dumpDebugT(W, File);
dumpDebugS(W, File);
}
}
// Creates a PDB file.
void coff::createPDB(StringRef Path, SymbolTable *Symtab,
ArrayRef<uint8_t> SectionTable,
const llvm::codeview::DebugInfo *DI) {
if (Config->DumpPdb)
dumpCodeView(Symtab);
BumpPtrAllocator Alloc;
pdb::PDBFileBuilder Builder(Alloc);
ExitOnErr(Builder.initialize(4096)); // 4096 is blocksize
// Create streams in MSF for predefined streams, namely
// PDB, TPI, DBI and IPI.
for (int I = 0; I < (int)pdb::kSpecialStreamCount; ++I)
ExitOnErr(Builder.getMsfBuilder().addStream(0));
// Add an Info stream.
auto &InfoBuilder = Builder.getInfoBuilder();
InfoBuilder.setAge(DI ? DI->PDB70.Age : 0);
pdb::PDB_UniqueId uuid{};
if (DI)
memcpy(&uuid, &DI->PDB70.Signature, sizeof(uuid));
InfoBuilder.setGuid(uuid);
// Should be the current time, but set 0 for reproducibilty.
InfoBuilder.setSignature(0);
InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
// Add an empty DPI stream.
auto &DbiBuilder = Builder.getDbiBuilder();
DbiBuilder.setVersionHeader(pdb::PdbDbiV110);
codeview::TypeTableBuilder TypeTable(BAlloc);
codeview::TypeTableBuilder IDTable(BAlloc);
mergeDebugT(Symtab, Builder, TypeTable, IDTable);
// Add Section Contributions.
std::vector<pdb::SectionContrib> Contribs =
pdb::DbiStreamBuilder::createSectionContribs(getInputSections(Symtab));
DbiBuilder.setSectionContribs(Contribs);
// Add Section Map stream.
ArrayRef<object::coff_section> Sections = {
(const object::coff_section *)SectionTable.data(),
SectionTable.size() / sizeof(object::coff_section)};
std::vector<pdb::SecMapEntry> SectionMap =
pdb::DbiStreamBuilder::createSectionMap(Sections);
DbiBuilder.setSectionMap(SectionMap);
ExitOnErr(DbiBuilder.addModuleInfo("* Linker *"));
// Add COFF section header stream.
ExitOnErr(
DbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, SectionTable));
// Write to a file.
ExitOnErr(Builder.commit(Path));
}
|
//===- PDB.cpp ------------------------------------------------------------===//
//
// The LLVM Linker
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "PDB.h"
#include "Chunks.h"
#include "Config.h"
#include "Error.h"
#include "SymbolTable.h"
#include "Symbols.h"
#include "llvm/DebugInfo/CodeView/CVDebugRecord.h"
#include "llvm/DebugInfo/CodeView/CVTypeVisitor.h"
#include "llvm/DebugInfo/CodeView/LazyRandomTypeCollection.h"
#include "llvm/DebugInfo/CodeView/SymbolDumper.h"
#include "llvm/DebugInfo/CodeView/TypeDatabase.h"
#include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h"
#include "llvm/DebugInfo/CodeView/TypeStreamMerger.h"
#include "llvm/DebugInfo/CodeView/TypeTableBuilder.h"
#include "llvm/DebugInfo/MSF/MSFBuilder.h"
#include "llvm/DebugInfo/MSF/MSFCommon.h"
#include "llvm/DebugInfo/PDB/Native/DbiStream.h"
#include "llvm/DebugInfo/PDB/Native/DbiStreamBuilder.h"
#include "llvm/DebugInfo/PDB/Native/InfoStream.h"
#include "llvm/DebugInfo/PDB/Native/InfoStreamBuilder.h"
#include "llvm/DebugInfo/PDB/Native/PDBFile.h"
#include "llvm/DebugInfo/PDB/Native/PDBFileBuilder.h"
#include "llvm/DebugInfo/PDB/Native/PDBStringTableBuilder.h"
#include "llvm/DebugInfo/PDB/Native/PDBTypeServerHandler.h"
#include "llvm/DebugInfo/PDB/Native/TpiStream.h"
#include "llvm/DebugInfo/PDB/Native/TpiStreamBuilder.h"
#include "llvm/Object/COFF.h"
#include "llvm/Support/BinaryByteStream.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/FileOutputBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/ScopedPrinter.h"
#include <memory>
using namespace lld;
using namespace lld::coff;
using namespace llvm;
using namespace llvm::codeview;
using namespace llvm::support;
using namespace llvm::support::endian;
using llvm::object::coff_section;
static ExitOnError ExitOnErr;
// Returns a list of all SectionChunks.
static std::vector<coff_section> getInputSections(SymbolTable *Symtab) {
std::vector<coff_section> V;
for (Chunk *C : Symtab->getChunks())
if (auto *SC = dyn_cast<SectionChunk>(C))
V.push_back(*SC->Header);
return V;
}
static SectionChunk *findByName(std::vector<SectionChunk *> &Sections,
StringRef Name) {
for (SectionChunk *C : Sections)
if (C->getSectionName() == Name)
return C;
return nullptr;
}
static ArrayRef<uint8_t> getDebugSection(ObjectFile *File, StringRef SecName) {
SectionChunk *Sec = findByName(File->getDebugChunks(), SecName);
if (!Sec)
return {};
// First 4 bytes are section magic.
ArrayRef<uint8_t> Data = Sec->getContents();
if (Data.size() < 4)
fatal(SecName + " too short");
if (read32le(Data.data()) != COFF::DEBUG_SECTION_MAGIC)
fatal(SecName + " has an invalid magic");
return Data.slice(4);
}
static void addTypeInfo(pdb::TpiStreamBuilder &TpiBuilder,
codeview::TypeTableBuilder &TypeTable) {
// Start the TPI or IPI stream header.
TpiBuilder.setVersionHeader(pdb::PdbTpiV80);
// Flatten the in memory type table.
TypeTable.ForEachRecord([&](TypeIndex TI, ArrayRef<uint8_t> Rec) {
// FIXME: Hash types.
TpiBuilder.addTypeRecord(Rec, None);
});
}
// Merge .debug$T sections into IpiData and TpiData.
static void mergeDebugT(SymbolTable *Symtab, pdb::PDBFileBuilder &Builder,
codeview::TypeTableBuilder &TypeTable,
codeview::TypeTableBuilder &IDTable) {
// Follow type servers. If the same type server is encountered more than
// once for this instance of `PDBTypeServerHandler` (for example if many
// object files reference the same TypeServer), the types from the
// TypeServer will only be visited once.
pdb::PDBTypeServerHandler Handler;
// Visit all .debug$T sections to add them to Builder.
for (ObjectFile *File : Symtab->ObjectFiles) {
ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
if (Data.empty())
continue;
BinaryByteStream Stream(Data, support::little);
codeview::CVTypeArray Types;
BinaryStreamReader Reader(Stream);
SmallVector<TypeIndex, 128> SourceToDest;
Handler.addSearchPath(llvm::sys::path::parent_path(File->getName()));
if (auto EC = Reader.readArray(Types, Reader.getLength()))
fatal(EC, "Reader::readArray failed");
if (auto Err = codeview::mergeTypeAndIdRecords(
IDTable, TypeTable, SourceToDest, &Handler, Types))
fatal(Err, "codeview::mergeTypeStreams failed");
}
// Construct TPI stream contents.
addTypeInfo(Builder.getTpiBuilder(), TypeTable);
// Construct IPI stream contents.
addTypeInfo(Builder.getIpiBuilder(), IDTable);
}
static void dumpDebugT(ScopedPrinter &W, ObjectFile *File) {
ListScope LS(W, "DebugT");
ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$T");
if (Data.empty())
return;
LazyRandomTypeCollection Types(Data, 100);
TypeDumpVisitor TDV(Types, &W, false);
// Use a default implementation that does not follow type servers and instead
// just dumps the contents of the TypeServer2 record.
if (auto EC = codeview::visitTypeStream(Types, TDV))
fatal(EC, "CVTypeDumper::dump failed");
}
static void dumpDebugS(ScopedPrinter &W, ObjectFile *File) {
ListScope LS(W, "DebugS");
ArrayRef<uint8_t> Data = getDebugSection(File, ".debug$S");
if (Data.empty())
return;
BinaryByteStream Stream(Data, llvm::support::little);
CVSymbolArray Symbols;
BinaryStreamReader Reader(Stream);
if (auto EC = Reader.readArray(Symbols, Reader.getLength()))
fatal(EC, "StreamReader.readArray<CVSymbolArray> failed");
TypeDatabase TDB(0);
CVSymbolDumper SymbolDumper(W, TDB, nullptr, false);
if (auto EC = SymbolDumper.dump(Symbols))
fatal(EC, "CVSymbolDumper::dump failed");
}
// Dump CodeView debug info. This is for debugging.
static void dumpCodeView(SymbolTable *Symtab) {
ScopedPrinter W(outs());
for (ObjectFile *File : Symtab->ObjectFiles) {
dumpDebugT(W, File);
dumpDebugS(W, File);
}
}
// Creates a PDB file.
void coff::createPDB(StringRef Path, SymbolTable *Symtab,
ArrayRef<uint8_t> SectionTable,
const llvm::codeview::DebugInfo *DI) {
if (Config->DumpPdb)
dumpCodeView(Symtab);
BumpPtrAllocator Alloc;
pdb::PDBFileBuilder Builder(Alloc);
ExitOnErr(Builder.initialize(4096)); // 4096 is blocksize
// Create streams in MSF for predefined streams, namely
// PDB, TPI, DBI and IPI.
for (int I = 0; I < (int)pdb::kSpecialStreamCount; ++I)
ExitOnErr(Builder.getMsfBuilder().addStream(0));
// Add an Info stream.
auto &InfoBuilder = Builder.getInfoBuilder();
InfoBuilder.setAge(DI ? DI->PDB70.Age : 0);
pdb::PDB_UniqueId uuid{};
if (DI)
memcpy(&uuid, &DI->PDB70.Signature, sizeof(uuid));
InfoBuilder.setGuid(uuid);
// Should be the current time, but set 0 for reproducibilty.
InfoBuilder.setSignature(0);
InfoBuilder.setVersion(pdb::PdbRaw_ImplVer::PdbImplVC70);
// Add an empty DPI stream.
auto &DbiBuilder = Builder.getDbiBuilder();
DbiBuilder.setVersionHeader(pdb::PdbDbiV110);
codeview::TypeTableBuilder TypeTable(BAlloc);
codeview::TypeTableBuilder IDTable(BAlloc);
mergeDebugT(Symtab, Builder, TypeTable, IDTable);
// Add Section Contributions.
std::vector<pdb::SectionContrib> Contribs =
pdb::DbiStreamBuilder::createSectionContribs(getInputSections(Symtab));
DbiBuilder.setSectionContribs(Contribs);
// Add Section Map stream.
ArrayRef<object::coff_section> Sections = {
(const object::coff_section *)SectionTable.data(),
SectionTable.size() / sizeof(object::coff_section)};
std::vector<pdb::SecMapEntry> SectionMap =
pdb::DbiStreamBuilder::createSectionMap(Sections);
DbiBuilder.setSectionMap(SectionMap);
ExitOnErr(DbiBuilder.addModuleInfo("* Linker *"));
// Add COFF section header stream.
ExitOnErr(
DbiBuilder.addDbgStream(pdb::DbgHeaderType::SectionHdr, SectionTable));
// Write to a file.
ExitOnErr(Builder.commit(Path));
}
|
Fix a bug where we continually re-follow type servers.
|
[lld] Fix a bug where we continually re-follow type servers.
Originally this was intended to be set up so that when linking
a PDB which refers to a type server, it would only visit the
PDB once, and on subsequent visitations it would just skip it
since all the records had already been added.
Due to some C++ scoping issues, this was not occurring and it
was revisiting the type server every time, which caused every
record to end up being thrown away on all subsequent visitations.
This doesn't affect the performance of linking clang-cl generated
object files because we don't use type servers, but when linking
object files and libraries generated with /Zi via MSVC, this means
only 1 object file has to be linked instead of N object files, so
the speedup is quite large.
git-svn-id: f6089bf0e6284f307027cef4f64114ee9ebb0424@303920 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/lld,llvm-mirror/lld
|
d8adbff72f6648589d7699857ee8c65a80315033
|
kernel/fstdata.cc
|
kernel/fstdata.cc
|
/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2022 Miodrag Milanovic <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/fstdata.h"
USING_YOSYS_NAMESPACE
static std::string file_base_name(std::string const & path)
{
return path.substr(path.find_last_of("/\\") + 1);
}
FstData::FstData(std::string filename) : ctx(nullptr)
{
#if !defined(YOSYS_DISABLE_SPAWN)
std::string filename_trim = file_base_name(filename);
if (filename_trim.size() > 4 && filename_trim.compare(filename_trim.size()-4, std::string::npos, ".vcd") == 0) {
filename_trim.erase(filename_trim.size()-4);
tmp_file = stringf("/tmp/converted_%s.fst", filename_trim.c_str());
std::string cmd = stringf("vcd2fst %s %s", filename.c_str(), tmp_file.c_str());
log("Exec: %s\n", cmd.c_str());
if (run_command(cmd) != 0)
log_cmd_error("Shell command failed!\n");
filename = tmp_file;
}
#endif
const std::vector<std::string> g_units = { "s", "ms", "us", "ns", "ps", "fs", "as", "zs" };
ctx = (fstReaderContext *)fstReaderOpen(filename.c_str());
if (!ctx)
log_error("Error opening '%s' as FST file\n", filename.c_str());
int scale = (int)fstReaderGetTimescale(ctx);
timescale = pow(10.0, scale);
timescale_str = "";
int unit = 0;
int zeros = 0;
if (scale > 0) {
zeros = scale;
} else {
if ((scale % 3) == 0) {
zeros = (-scale % 3);
unit = (-scale / 3);
} else {
zeros = 3 - (-scale % 3);
unit = (-scale / 3) + 1;
}
}
for (int i=0;i<zeros; i++) timescale_str += "0";
timescale_str += g_units[unit];
extractVarNames();
}
FstData::~FstData()
{
if (ctx)
fstReaderClose(ctx);
if (!tmp_file.empty())
remove(tmp_file.c_str());
}
uint64_t FstData::getStartTime() { return fstReaderGetStartTime(ctx); }
uint64_t FstData::getEndTime() { return fstReaderGetEndTime(ctx); }
fstHandle FstData::getHandle(std::string name) {
if (name_to_handle.find(name) != name_to_handle.end())
return name_to_handle[name];
else
return 0;
};
dict<int,fstHandle> FstData::getMemoryHandles(std::string name) {
if (memory_to_handle.find(name) != memory_to_handle.end())
return memory_to_handle[name];
else
return dict<int,fstHandle>();
};
static std::string remove_spaces(std::string str)
{
str.erase(std::remove(str.begin(), str.end(), ' '), str.end());
return str;
}
void FstData::extractVarNames()
{
struct fstHier *h;
std::string fst_scope_name;
while ((h = fstReaderIterateHier(ctx))) {
switch (h->htyp) {
case FST_HT_SCOPE: {
fst_scope_name = fstReaderPushScope(ctx, h->u.scope.name, NULL);
break;
}
case FST_HT_UPSCOPE: {
fst_scope_name = fstReaderPopScope(ctx);
break;
}
case FST_HT_VAR: {
FstVar var;
var.id = h->u.var.handle;
var.is_alias = h->u.var.is_alias;
var.is_reg = (fstVarType)h->u.var.typ == FST_VT_VCD_REG;
var.name = remove_spaces(h->u.var.name);
var.scope = fst_scope_name;
var.width = h->u.var.length;
vars.push_back(var);
if (!var.is_alias)
handle_to_var[h->u.var.handle] = var;
std::string clean_name;
for(size_t i=0;i<strlen(h->u.var.name);i++)
{
char c = h->u.var.name[i];
if(c==' ') break;
clean_name += c;
}
if (clean_name[0]=='\\')
clean_name = clean_name.substr(1);
size_t pos = clean_name.find_last_of("<");
if (pos != std::string::npos) {
std::string mem_cell = clean_name.substr(0, pos);
std::string addr = clean_name.substr(pos+1);
addr.pop_back(); // remove closing bracket
char *endptr;
int mem_addr = strtol(addr.c_str(), &endptr, 16);
if (*endptr) {
log_error("Error parsing memory address in : %s\n", clean_name.c_str());
}
memory_to_handle[var.scope+"."+mem_cell][mem_addr] = var.id;
name_to_handle[stringf("%s.%s[%d]",var.scope.c_str(),mem_cell.c_str(),mem_addr)] = h->u.var.handle;
continue;
}
pos = clean_name.find_last_of("[");
if (pos != std::string::npos) {
std::string mem_cell = clean_name.substr(0, pos);
std::string addr = clean_name.substr(pos+1);
addr.pop_back(); // remove closing bracket
char *endptr;
int mem_addr = strtol(addr.c_str(), &endptr, 10);
if (*endptr) {
log_error("Error parsing memory address in : %s\n", clean_name.c_str());
}
memory_to_handle[var.scope+"."+mem_cell][mem_addr] = var.id;
name_to_handle[stringf("%s.%s[%d]",var.scope.c_str(),mem_cell.c_str(),mem_addr)] = h->u.var.handle;
continue;
}
name_to_handle[var.scope+"."+clean_name] = h->u.var.handle;
break;
}
}
}
}
static void reconstruct_clb_varlen_attimes(void *user_data, uint64_t pnt_time, fstHandle pnt_facidx, const unsigned char *pnt_value, uint32_t plen)
{
FstData *ptr = (FstData*)user_data;
ptr->reconstruct_callback_attimes(pnt_time, pnt_facidx, pnt_value, plen);
}
static void reconstruct_clb_attimes(void *user_data, uint64_t pnt_time, fstHandle pnt_facidx, const unsigned char *pnt_value)
{
FstData *ptr = (FstData*)user_data;
uint32_t plen = (pnt_value) ? strlen((const char *)pnt_value) : 0;
ptr->reconstruct_callback_attimes(pnt_time, pnt_facidx, pnt_value, plen);
}
void FstData::reconstruct_callback_attimes(uint64_t pnt_time, fstHandle pnt_facidx, const unsigned char *pnt_value, uint32_t /* plen */)
{
if (pnt_time > end_time) return;
// if we are past the timestamp
bool is_clock = false;
if (!all_samples) {
for(auto &s : clk_signals) {
if (s==pnt_facidx) {
is_clock=true;
break;
}
}
}
if (pnt_time > past_time) {
past_data = last_data;
past_time = pnt_time;
}
if (pnt_time > last_time) {
if (all_samples) {
callback(last_time);
last_time = pnt_time;
} else {
if (is_clock) {
std::string val = std::string((const char *)pnt_value);
std::string prev = past_data[pnt_facidx];
if ((prev!="1" && val=="1") || (prev!="0" && val=="0")) {
callback(last_time);
last_time = pnt_time;
}
}
}
}
// always update last_data
last_data[pnt_facidx] = std::string((const char *)pnt_value);
}
void FstData::reconstructAllAtTimes(std::vector<fstHandle> &signal, uint64_t start, uint64_t end, CallbackFunction cb)
{
clk_signals = signal;
callback = cb;
start_time = start;
end_time = end;
last_data.clear();
last_time = start_time;
past_data.clear();
past_time = start_time;
all_samples = clk_signals.empty();
fstReaderSetUnlimitedTimeRange(ctx);
fstReaderSetFacProcessMaskAll(ctx);
fstReaderIterBlocks2(ctx, reconstruct_clb_attimes, reconstruct_clb_varlen_attimes, this, nullptr);
if (last_time!=end_time) {
past_data = last_data;
callback(last_time);
}
callback(end_time);
}
std::string FstData::valueOf(fstHandle signal)
{
if (past_data.find(signal) == past_data.end())
log_error("Signal id %d not found\n", (int)signal);
return past_data[signal];
}
|
/*
* yosys -- Yosys Open SYnthesis Suite
*
* Copyright (C) 2022 Miodrag Milanovic <[email protected]>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
#include "kernel/fstdata.h"
USING_YOSYS_NAMESPACE
static std::string file_base_name(std::string const & path)
{
return path.substr(path.find_last_of("/\\") + 1);
}
FstData::FstData(std::string filename) : ctx(nullptr)
{
#if !defined(YOSYS_DISABLE_SPAWN)
std::string filename_trim = file_base_name(filename);
if (filename_trim.size() > 4 && filename_trim.compare(filename_trim.size()-4, std::string::npos, ".vcd") == 0) {
filename_trim.erase(filename_trim.size()-4);
tmp_file = stringf("/tmp/converted_%s.fst", filename_trim.c_str());
std::string cmd = stringf("vcd2fst %s %s", filename.c_str(), tmp_file.c_str());
log("Exec: %s\n", cmd.c_str());
if (run_command(cmd) != 0)
log_cmd_error("Shell command failed!\n");
filename = tmp_file;
}
#endif
const std::vector<std::string> g_units = { "s", "ms", "us", "ns", "ps", "fs", "as", "zs" };
ctx = (fstReaderContext *)fstReaderOpen(filename.c_str());
if (!ctx)
log_error("Error opening '%s' as FST file\n", filename.c_str());
int scale = (int)fstReaderGetTimescale(ctx);
timescale = pow(10.0, scale);
timescale_str = "";
int unit = 0;
int zeros = 0;
if (scale > 0) {
zeros = scale;
} else {
if ((scale % 3) == 0) {
zeros = (-scale % 3);
unit = (-scale / 3);
} else {
zeros = 3 - (-scale % 3);
unit = (-scale / 3) + 1;
}
}
for (int i=0;i<zeros; i++) timescale_str += "0";
timescale_str += g_units[unit];
extractVarNames();
}
FstData::~FstData()
{
if (ctx)
fstReaderClose(ctx);
if (!tmp_file.empty())
remove(tmp_file.c_str());
}
uint64_t FstData::getStartTime() { return fstReaderGetStartTime(ctx); }
uint64_t FstData::getEndTime() { return fstReaderGetEndTime(ctx); }
fstHandle FstData::getHandle(std::string name) {
if (name_to_handle.find(name) != name_to_handle.end())
return name_to_handle[name];
else
return 0;
};
dict<int,fstHandle> FstData::getMemoryHandles(std::string name) {
if (memory_to_handle.find(name) != memory_to_handle.end())
return memory_to_handle[name];
else
return dict<int,fstHandle>();
};
static std::string remove_spaces(std::string str)
{
str.erase(std::remove(str.begin(), str.end(), ' '), str.end());
return str;
}
void FstData::extractVarNames()
{
struct fstHier *h;
std::string fst_scope_name;
while ((h = fstReaderIterateHier(ctx))) {
switch (h->htyp) {
case FST_HT_SCOPE: {
fst_scope_name = fstReaderPushScope(ctx, h->u.scope.name, NULL);
break;
}
case FST_HT_UPSCOPE: {
fst_scope_name = fstReaderPopScope(ctx);
break;
}
case FST_HT_VAR: {
FstVar var;
var.id = h->u.var.handle;
var.is_alias = h->u.var.is_alias;
var.is_reg = (fstVarType)h->u.var.typ == FST_VT_VCD_REG;
var.name = remove_spaces(h->u.var.name);
var.scope = fst_scope_name;
var.width = h->u.var.length;
vars.push_back(var);
if (!var.is_alias)
handle_to_var[h->u.var.handle] = var;
std::string clean_name;
for(size_t i=0;i<strlen(h->u.var.name);i++)
{
char c = h->u.var.name[i];
if(c==' ') break;
clean_name += c;
}
if (clean_name[0]=='\\')
clean_name = clean_name.substr(1);
size_t pos = clean_name.find_last_of("<");
if (pos != std::string::npos) {
std::string mem_cell = clean_name.substr(0, pos);
std::string addr = clean_name.substr(pos+1);
addr.pop_back(); // remove closing bracket
char *endptr;
int mem_addr = strtol(addr.c_str(), &endptr, 16);
if (*endptr) {
log_warning("Error parsing memory address in : %s\n", clean_name.c_str());
} else {
memory_to_handle[var.scope+"."+mem_cell][mem_addr] = var.id;
name_to_handle[stringf("%s.%s[%d]",var.scope.c_str(),mem_cell.c_str(),mem_addr)] = h->u.var.handle;
continue;
}
}
pos = clean_name.find_last_of("[");
if (pos != std::string::npos) {
std::string mem_cell = clean_name.substr(0, pos);
std::string addr = clean_name.substr(pos+1);
addr.pop_back(); // remove closing bracket
char *endptr;
int mem_addr = strtol(addr.c_str(), &endptr, 10);
if (*endptr) {
log_warning("Error parsing memory address in : %s\n", clean_name.c_str());
} else {
memory_to_handle[var.scope+"."+mem_cell][mem_addr] = var.id;
name_to_handle[stringf("%s.%s[%d]",var.scope.c_str(),mem_cell.c_str(),mem_addr)] = h->u.var.handle;
continue;
}
}
name_to_handle[var.scope+"."+clean_name] = h->u.var.handle;
break;
}
}
}
}
static void reconstruct_clb_varlen_attimes(void *user_data, uint64_t pnt_time, fstHandle pnt_facidx, const unsigned char *pnt_value, uint32_t plen)
{
FstData *ptr = (FstData*)user_data;
ptr->reconstruct_callback_attimes(pnt_time, pnt_facidx, pnt_value, plen);
}
static void reconstruct_clb_attimes(void *user_data, uint64_t pnt_time, fstHandle pnt_facidx, const unsigned char *pnt_value)
{
FstData *ptr = (FstData*)user_data;
uint32_t plen = (pnt_value) ? strlen((const char *)pnt_value) : 0;
ptr->reconstruct_callback_attimes(pnt_time, pnt_facidx, pnt_value, plen);
}
void FstData::reconstruct_callback_attimes(uint64_t pnt_time, fstHandle pnt_facidx, const unsigned char *pnt_value, uint32_t /* plen */)
{
if (pnt_time > end_time) return;
// if we are past the timestamp
bool is_clock = false;
if (!all_samples) {
for(auto &s : clk_signals) {
if (s==pnt_facidx) {
is_clock=true;
break;
}
}
}
if (pnt_time > past_time) {
past_data = last_data;
past_time = pnt_time;
}
if (pnt_time > last_time) {
if (all_samples) {
callback(last_time);
last_time = pnt_time;
} else {
if (is_clock) {
std::string val = std::string((const char *)pnt_value);
std::string prev = past_data[pnt_facidx];
if ((prev!="1" && val=="1") || (prev!="0" && val=="0")) {
callback(last_time);
last_time = pnt_time;
}
}
}
}
// always update last_data
last_data[pnt_facidx] = std::string((const char *)pnt_value);
}
void FstData::reconstructAllAtTimes(std::vector<fstHandle> &signal, uint64_t start, uint64_t end, CallbackFunction cb)
{
clk_signals = signal;
callback = cb;
start_time = start;
end_time = end;
last_data.clear();
last_time = start_time;
past_data.clear();
past_time = start_time;
all_samples = clk_signals.empty();
fstReaderSetUnlimitedTimeRange(ctx);
fstReaderSetFacProcessMaskAll(ctx);
fstReaderIterBlocks2(ctx, reconstruct_clb_attimes, reconstruct_clb_varlen_attimes, this, nullptr);
if (last_time!=end_time) {
past_data = last_data;
callback(last_time);
}
callback(end_time);
}
std::string FstData::valueOf(fstHandle signal)
{
if (past_data.find(signal) == past_data.end())
log_error("Signal id %d not found\n", (int)signal);
return past_data[signal];
}
|
Handle possible non-memory indexed data
|
Handle possible non-memory indexed data
|
C++
|
isc
|
YosysHQ/yosys,YosysHQ/yosys,YosysHQ/yosys,YosysHQ/yosys,YosysHQ/yosys,YosysHQ/yosys,YosysHQ/yosys,YosysHQ/yosys
|
2e9238157dd8ab55ba7a0e48cec986a35a3bc882
|
shims/graphics.cpp
|
shims/graphics.cpp
|
#include "graphics.h"
#include <SDL.h>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
#define error(fmt, ...) _error(__LINE__, fmt, __VA_ARGS__)
#define sdl_error(name, ...) _sdl_error(__LINE__, name)
static void _error(long line, const char *fmt, ...);
static void _sdl_error(long line, const char *name);
static int const SURFACE_WIDTH = 640;
static int const SURFACE_HEIGHT = 480;
static int const SURFACE_BPP = 32;
static SDL_Surface *surface = NULL;
void initgraph(int *gdriver, int *gmode, const char *something) {
if (surface) {
error("initgraph() can only be called once", NULL);
}
if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
sdl_error("SDL_Init");
}
if (SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL)) {
sdl_error("SDL_EnableKeyRepeat");
}
if ((surface = SDL_SetVideoMode(
SURFACE_WIDTH,
SURFACE_HEIGHT,
SURFACE_BPP,
SDL_HWSURFACE | SDL_DOUBLEBUF
)) == NULL) {
sdl_error("SDL_SetVideoMode");
}
}
void closegraph(void) {
// TODO: Implement
}
int getpixel(int x, int y) {
// TODO: Implement
return 0;
}
void putpixel(int x, int y, int color) {
// TODO: Implement
}
int getcolor(void) {
// TODO: Implement
return 0;
}
void setcolor(int color) {
// TODO: Implement
}
void getimage(int left, int top, int right, int bottom, void *pic) {
// TODO: Implement
}
void putimage(int left, int top, void *pic, int mode) {
// TODO: Implement
}
size_t imagesize(int left, int top, int right, int bottom) {
// TODO: Implement
return 0;
}
void line(int a_x, int a_y, int b_x, int b_y) {
// TODO: Implement
}
void rectangle(int left, int top, int right, int bottom) {
// TODO: Implement
}
void setfillstyle(int mode, int color) {
// TODO: Implement
}
void floodfill(int x, int y, int color) {
// TODO: Implement
}
void outtextxy(int x, int y, const char *text) {
// TODO: Implement
}
int GetKeyState(int key) {
// TODO: Implement
return 0;
}
void SetNormalKeysMode(void) {
// no implementation necessary
}
void SetButtonKeysMode(void) {
// no implementation necessary
}
void delay(int milliseconds) {
// TODO: Implement
}
void cleardevice(void) {
// TODO: Implement
}
void itoa(int num, char *str, int base) {
// Only writing impl for base 10 conversion
if (base != 10) {
fprintf(stderr, "iota() only supports base 10 conversion\n");
exit(1);
}
// Stupid unsafe itoa has no buffer size parameter, so we have
// to use sprintf instead of snprintf
sprintf(str, "%d", num);
}
static void _error(long line, const char *fmt, ...) {
va_list args;
va_start(args, fmt);
fprintf(stderr, "graphics.cpp error on line %ld: ", line);
vfprintf(stderr, fmt, args);
fprintf(stderr, "\n");
va_end(args);
if (surface) {
SDL_Quit();
surface = NULL;
}
exit(1);
}
static void _sdl_error(long line, const char *name) {
_error(line, "SDL function %s failed. Reason: %s", name, SDL_GetError());
}
|
#include "graphics.h"
#include <SDL.h>
#ifdef __EMSCRIPTEN__
#include <emscripten.h>
#endif
#define error(fmt, ...) _error(__LINE__, fmt, __VA_ARGS__)
#define sdl_error(name, ...) _sdl_error(__LINE__, name)
static void _error(long line, const char *fmt, ...);
static void _sdl_error(long line, const char *name);
static int const SURFACE_WIDTH = 640;
static int const SURFACE_HEIGHT = 480;
static int const SURFACE_BPP = 32;
static SDL_Surface *surface = NULL;
void initgraph(int *gdriver, int *gmode, const char *something) {
if (surface) {
error("initgraph() can only be called once", NULL);
}
if (SDL_Init(SDL_INIT_EVERYTHING) < 0) {
sdl_error("SDL_Init");
}
if (SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL)) {
sdl_error("SDL_EnableKeyRepeat");
}
if ((surface = SDL_SetVideoMode(
SURFACE_WIDTH,
SURFACE_HEIGHT,
SURFACE_BPP,
SDL_HWSURFACE | SDL_DOUBLEBUF
)) == NULL) {
sdl_error("SDL_SetVideoMode");
}
}
void closegraph(void) {
if (surface) {
SDL_Quit();
surface = NULL;
}
}
int getpixel(int x, int y) {
// TODO: Implement
return 0;
}
void putpixel(int x, int y, int color) {
// TODO: Implement
}
int getcolor(void) {
// TODO: Implement
return 0;
}
void setcolor(int color) {
// TODO: Implement
}
void getimage(int left, int top, int right, int bottom, void *pic) {
// TODO: Implement
}
void putimage(int left, int top, void *pic, int mode) {
// TODO: Implement
}
size_t imagesize(int left, int top, int right, int bottom) {
// TODO: Implement
return 0;
}
void line(int a_x, int a_y, int b_x, int b_y) {
// TODO: Implement
}
void rectangle(int left, int top, int right, int bottom) {
// TODO: Implement
}
void setfillstyle(int mode, int color) {
// TODO: Implement
}
void floodfill(int x, int y, int color) {
// TODO: Implement
}
void outtextxy(int x, int y, const char *text) {
// TODO: Implement
}
int GetKeyState(int key) {
// TODO: Implement
return 0;
}
void SetNormalKeysMode(void) {
// no implementation necessary
}
void SetButtonKeysMode(void) {
// no implementation necessary
}
void delay(int milliseconds) {
// TODO: Implement
}
void cleardevice(void) {
// TODO: Implement
}
void itoa(int num, char *str, int base) {
// Only writing impl for base 10 conversion
if (base != 10) {
fprintf(stderr, "iota() only supports base 10 conversion\n");
exit(1);
}
// Stupid unsafe itoa has no buffer size parameter, so we have
// to use sprintf instead of snprintf
sprintf(str, "%d", num);
}
static void _error(long line, const char *fmt, ...) {
va_list args;
va_start(args, fmt);
fprintf(stderr, "graphics.cpp error on line %ld: ", line);
vfprintf(stderr, fmt, args);
fprintf(stderr, "\n");
va_end(args);
closegraph();
exit(1);
}
static void _sdl_error(long line, const char *name) {
_error(line, "SDL function %s failed. Reason: %s", name, SDL_GetError());
}
|
Add implementation for closegraph
|
Add implementation for closegraph
|
C++
|
mit
|
sortelli/tankbeta,sortelli/tankbeta,sortelli/tankbeta,sortelli/tankbeta
|
62771e0f36e2417c7c46c6cdaf78375186ba76fe
|
deal.II/examples/step-53/step-53.cc
|
deal.II/examples/step-53/step-53.cc
|
/* ---------------------------------------------------------------------
* $Id$
*
* Copyright (C) 2014 by the deal.II authors
*
* This file is part of the deal.II library.
*
* The deal.II library is free software; you can use it, redistribute
* it, and/or modify it under the terms of the GNU Lesser General
* Public License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* The full text of the license can be found in the file LICENSE at
* the top level of the deal.II distribution.
*
* ---------------------------------------------------------------------
*
* Author: Wolfgang Bangerth, Texas A&M University, 2014
*/
#include <deal.II/grid/tria.h>
#include <deal.II/grid/tria_boundary.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/grid_out.h>
#include <fstream>
using namespace dealii;
class SineBoundary : public Boundary<3>
{
public:
virtual
Point<3>
get_new_point_on_line (const typename Triangulation<3>::line_iterator &line) const;
virtual
Point<3>
get_new_point_on_quad (const typename Triangulation<3>::quad_iterator &quad) const;
};
Point<3>
SineBoundary::
get_new_point_on_line (const typename Triangulation<3>::line_iterator &line) const
{
const double new_x = (line->vertex(0)[0] + line->vertex(1)[0]) / 2;
const double new_y = (line->vertex(0)[1] + line->vertex(1)[1]) / 2;
const double new_z = 1 +
0.05 * std::sin (2 * numbers::PI * new_x) +
0.05 * std::sin (2 * numbers::PI * new_y);
return Point<3> (new_x, new_y, new_z);
}
Point<3>
SineBoundary::
get_new_point_on_quad (const typename Triangulation<3>::quad_iterator &quad) const
{
const double new_x = (quad->vertex(0)[0] + quad->vertex(1)[0] +
quad->vertex(2)[0] + quad->vertex(3)[0]) / 4;
const double new_y = (quad->vertex(0)[1] + quad->vertex(1)[1] +
quad->vertex(2)[1] + quad->vertex(3)[1]) / 4;
const double new_z = 1 +
0.05 * std::sin (2 * numbers::PI * new_x) +
0.05 * std::sin (2 * numbers::PI * new_y);
return Point<3> (new_x, new_y, new_z);
}
void make_grid ()
{
SineBoundary sine_boundary;
Triangulation<3> triangulation;
GridGenerator::hyper_cube (triangulation);
triangulation.begin_active()->face(5)->set_manifold_id(1);
triangulation.set_boundary (1, sine_boundary);
triangulation.refine_global (2);
std::ofstream out ("mesh.mgl");
GridOut grid_out;
grid_out.write_mathgl (triangulation, out);
}
// @sect3{The main function}
// Finally, the main function. There isn't much to do here, only to call the
// subfunctions.
int main ()
{
make_grid ();
}
|
/* ---------------------------------------------------------------------
* $Id$
*
* Copyright (C) 2014 by the deal.II authors
*
* This file is part of the deal.II library.
*
* The deal.II library is free software; you can use it, redistribute
* it, and/or modify it under the terms of the GNU Lesser General
* Public License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* The full text of the license can be found in the file LICENSE at
* the top level of the deal.II distribution.
*
* ---------------------------------------------------------------------
*
* Author: Wolfgang Bangerth, Texas A&M University, 2014
*/
#include <deal.II/grid/tria.h>
#include <deal.II/grid/tria_boundary.h>
#include <deal.II/grid/tria_boundary_lib.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/grid_out.h>
#include <fstream>
using namespace dealii;
template <int dim>
void make_grid ()
{
Point<dim> center;
for (unsigned int i=0; i<dim; ++i)
center[i] = .25;
double radius=center.norm();
HyperBallBoundary<dim,dim> boundary(center, .25*std::sqrt((double)dim));
Triangulation<dim,dim> triangulation;
GridGenerator::hyper_cube (triangulation);
triangulation.refine_global(1);
for (typename Triangulation<dim>::active_cell_iterator cell=triangulation.begin_active();
cell!=triangulation.end(); ++cell)
for (unsigned int f=0; f<GeometryInfo<dim>::faces_per_cell; ++f)
if (cell->face(f)->center().distance(center)< radius)
cell->face(f)->set_all_manifold_ids(1);
triangulation.set_manifold(1,boundary);
triangulation.refine_global(3);
const std::string filename = "mesh-" + Utilities::int_to_string(dim) + "d.vtk";
std::ofstream out (filename.c_str());
GridOut grid_out;
grid_out.write_vtk (triangulation, out);
}
// @sect3{The main function}
// Finally, the main function. There isn't much to do here, only to call the
// subfunctions.
int main ()
{
make_grid<2> ();
make_grid<3> ();
}
|
Copy Luca's example from tests/manifold/manifold_06.cc.
|
Copy Luca's example from tests/manifold/manifold_06.cc.
git-svn-id: 31d9d2f6432a47c86a3640814024c107794ea77c@33178 0785d39b-7218-0410-832d-ea1e28bc413d
|
C++
|
lgpl-2.1
|
andreamola/dealii,natashasharma/dealii,lpolster/dealii,JaeryunYim/dealii,adamkosik/dealii,natashasharma/dealii,mtezzele/dealii,johntfoster/dealii,maieneuro/dealii,sairajat/dealii,kalj/dealii,gpitton/dealii,sairajat/dealii,shakirbsm/dealii,lue/dealii,lpolster/dealii,shakirbsm/dealii,spco/dealii,angelrca/dealii,nicolacavallini/dealii,ibkim11/dealii,jperryhouts/dealii,danshapero/dealii,adamkosik/dealii,Arezou-gh/dealii,lpolster/dealii,YongYang86/dealii,msteigemann/dealii,spco/dealii,JaeryunYim/dealii,kalj/dealii,andreamola/dealii,JaeryunYim/dealii,maieneuro/dealii,pesser/dealii,spco/dealii,jperryhouts/dealii,flow123d/dealii,flow123d/dealii,kalj/dealii,kalj/dealii,johntfoster/dealii,flow123d/dealii,gpitton/dealii,shakirbsm/dealii,sriharisundar/dealii,andreamola/dealii,spco/dealii,lue/dealii,lue/dealii,msteigemann/dealii,ESeNonFossiIo/dealii,andreamola/dealii,msteigemann/dealii,naliboff/dealii,lue/dealii,adamkosik/dealii,msteigemann/dealii,adamkosik/dealii,Arezou-gh/dealii,pesser/dealii,mac-a/dealii,ESeNonFossiIo/dealii,lue/dealii,pesser/dealii,rrgrove6/dealii,sairajat/dealii,jperryhouts/dealii,angelrca/dealii,Arezou-gh/dealii,EGP-CIG-REU/dealii,YongYang86/dealii,mtezzele/dealii,jperryhouts/dealii,lpolster/dealii,andreamola/dealii,JaeryunYim/dealii,kalj/dealii,naliboff/dealii,gpitton/dealii,shakirbsm/dealii,flow123d/dealii,jperryhouts/dealii,sairajat/dealii,danshapero/dealii,nicolacavallini/dealii,ibkim11/dealii,kalj/dealii,naliboff/dealii,rrgrove6/dealii,YongYang86/dealii,YongYang86/dealii,sriharisundar/dealii,angelrca/dealii,naliboff/dealii,johntfoster/dealii,spco/dealii,rrgrove6/dealii,adamkosik/dealii,mtezzele/dealii,pesser/dealii,flow123d/dealii,Arezou-gh/dealii,sriharisundar/dealii,ESeNonFossiIo/dealii,maieneuro/dealii,gpitton/dealii,EGP-CIG-REU/dealii,pesser/dealii,angelrca/dealii,JaeryunYim/dealii,mac-a/dealii,spco/dealii,danshapero/dealii,ESeNonFossiIo/dealii,angelrca/dealii,mac-a/dealii,EGP-CIG-REU/dealii,rrgrove6/dealii,Arezou-gh/dealii,danshapero/dealii,adamkosik/dealii,gpitton/dealii,natashasharma/dealii,flow123d/dealii,sriharisundar/dealii,danshapero/dealii,ibkim11/dealii,msteigemann/dealii,ESeNonFossiIo/dealii,kalj/dealii,mac-a/dealii,flow123d/dealii,Arezou-gh/dealii,rrgrove6/dealii,sriharisundar/dealii,andreamola/dealii,ESeNonFossiIo/dealii,pesser/dealii,gpitton/dealii,angelrca/dealii,maieneuro/dealii,mtezzele/dealii,mac-a/dealii,EGP-CIG-REU/dealii,andreamola/dealii,adamkosik/dealii,nicolacavallini/dealii,YongYang86/dealii,YongYang86/dealii,jperryhouts/dealii,mtezzele/dealii,natashasharma/dealii,mac-a/dealii,EGP-CIG-REU/dealii,lpolster/dealii,Arezou-gh/dealii,nicolacavallini/dealii,ibkim11/dealii,nicolacavallini/dealii,nicolacavallini/dealii,YongYang86/dealii,danshapero/dealii,lpolster/dealii,natashasharma/dealii,sairajat/dealii,rrgrove6/dealii,gpitton/dealii,rrgrove6/dealii,natashasharma/dealii,maieneuro/dealii,EGP-CIG-REU/dealii,danshapero/dealii,johntfoster/dealii,shakirbsm/dealii,msteigemann/dealii,mtezzele/dealii,spco/dealii,maieneuro/dealii,johntfoster/dealii,ibkim11/dealii,johntfoster/dealii,pesser/dealii,shakirbsm/dealii,maieneuro/dealii,mtezzele/dealii,lue/dealii,lpolster/dealii,shakirbsm/dealii,sairajat/dealii,sriharisundar/dealii,lue/dealii,naliboff/dealii,natashasharma/dealii,mac-a/dealii,nicolacavallini/dealii,jperryhouts/dealii,ibkim11/dealii,EGP-CIG-REU/dealii,JaeryunYim/dealii,johntfoster/dealii,sairajat/dealii,sriharisundar/dealii,ibkim11/dealii,naliboff/dealii,ESeNonFossiIo/dealii,angelrca/dealii,JaeryunYim/dealii,msteigemann/dealii,naliboff/dealii
|
cefefc985f7f340c68eca91a34cfd22a60860c50
|
kmail/kmmimeparttree.cpp
|
kmail/kmmimeparttree.cpp
|
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "kmmimeparttree.h"
#include "kmreaderwin.h"
#include "partNode.h"
#include "kmkernel.h"
#include "objecttreeparser.h"
using KMail::ObjectTreeParser;
#include <kdebug.h>
#include <klocale.h>
#include <kfiledialog.h>
#include <kmessagebox.h>
#include <kiconloader.h>
#include <qheader.h>
#include <qpopupmenu.h>
KMMimePartTree::KMMimePartTree( KMReaderWin* readerWin,
QWidget* parent,
const char* name )
: KListView( parent, name ),
mReaderWin( readerWin )
{
addColumn( i18n("Description") );
addColumn( i18n("Type") );
addColumn( i18n("Encoding") );
addColumn( i18n("Size") );
setColumnAlignment( 3, Qt::AlignRight );
restoreLayoutIfPresent();
connect( this, SIGNAL( clicked( QListViewItem* ) ),
this, SLOT( itemClicked( QListViewItem* ) ) );
connect( this, SIGNAL( contextMenuRequested( QListViewItem*,
const QPoint&, int ) ),
this, SLOT( itemRightClicked( QListViewItem*, const QPoint& ) ) );
setSelectionMode( QListView::Extended );
setRootIsDecorated( false );
setAllColumnsShowFocus( true );
setShowToolTips( true );
setSorting(-1);
}
static const char configGroup[] = "MimePartTree";
KMMimePartTree::~KMMimePartTree() {
saveLayout( KMKernel::config(), configGroup );
}
void KMMimePartTree::restoreLayoutIfPresent() {
// first column: soaks up the rest of the space:
setColumnWidthMode( 0, Manual );
header()->setStretchEnabled( true, 0 );
// rest of the columns:
if ( KMKernel::config()->hasGroup( configGroup ) ) {
// there is a saved layout. use it...
restoreLayout( KMKernel::config(), configGroup );
// and disable Maximum mode:
for ( int i = 1 ; i < 4 ; ++i )
setColumnWidthMode( i, Manual );
} else {
// columns grow with their contents:
for ( int i = 1 ; i < 4 ; ++i )
setColumnWidthMode( i, Maximum );
}
}
void KMMimePartTree::itemClicked( QListViewItem* item )
{
KMMimePartTreeItem* i = dynamic_cast<KMMimePartTreeItem*>( item );
if ( 0 == i ) {
kdDebug(5006) << "Item was not a KMMimePartTreeItem!" << endl;
}
else {
kdDebug(5006) << "\n**\n** KMMimePartTree::itemClicked() **\n**" << endl;
if( mReaderWin->mRootNode == i->node() )
mReaderWin->update( true ); // Force update
else {
ObjectTreeParser otp( mReaderWin, 0, true );
otp.parseObjectTree( i->node() );
}
}
}
void KMMimePartTree::itemRightClicked( QListViewItem* item,
const QPoint& point )
{
mCurrentContextMenuItem = dynamic_cast<KMMimePartTreeItem*>( item );
if ( 0 == mCurrentContextMenuItem ) {
kdDebug(5006) << "Item was not a KMMimePartTreeItem!" << endl;
}
else {
kdDebug(5006) << "\n**\n** KMMimePartTree::itemRightClicked() **\n**" << endl;
/*
if( mReaderWin->mRootNode == i->node() )
mReaderWin->setMsg(mReaderWin->mMsg, true); // Force update
else
mReaderWin->parseObjectTree( i->node(), true );
// mReaderWin->parseObjectTree( mCurrentContextMenuItem->node(), true );
*/
QPopupMenu* popup = new QPopupMenu;
popup->insertItem( i18n( "Save &As..." ), this, SLOT( slotSaveAs() ) );
popup->insertItem( i18n( "Save as &Encoded..." ), this,
SLOT( slotSaveAsEncoded() ) );
popup->insertItem( i18n( "Save Selected Items..." ), this,
SLOT( slotSaveSelected() ) );
popup->insertItem( i18n( "Save All..." ), this,
SLOT( slotSaveAll() ) );
popup->exec( point );
delete popup;
//mReaderWin->parseObjectTree( mCurrentContextMenuItem->node(), true );
mCurrentContextMenuItem = 0;
}
}
void KMMimePartTree::slotSaveAs()
{
if( mCurrentContextMenuItem ) { // this should always be true
QString s = mCurrentContextMenuItem->text(0);
if( s.startsWith( "file: " ) )
s = s.mid(6).stripWhiteSpace();
else
s = s.stripWhiteSpace();
QString filename = KFileDialog::getSaveFileName( s,
QString::null,
this, QString::null );
if( !filename.isEmpty() ) {
if( QFile::exists( filename ) ) {
if( KMessageBox::warningYesNo( this,
i18n( "A file with this name already exists. Do you want to overwrite it?" ),
i18n( "KMail Warning" ) ) ==
KMessageBox::No )
return;
}
slotSaveItem( mCurrentContextMenuItem, filename );
}
}
}
void KMMimePartTree::slotSaveAsEncoded()
{
if( mCurrentContextMenuItem ) { // this should always be true
QString s = mCurrentContextMenuItem->text(0);
if( s.startsWith( "file: " ) )
s = s.mid(6).stripWhiteSpace();
else
s = s.stripWhiteSpace();
QString filename = KFileDialog::getSaveFileName( s,
QString::null,
this, QString::null );
if( !filename.isEmpty() ) {
if( QFile::exists( filename ) ) {
if( KMessageBox::warningYesNo( this,
i18n( "A file with this name already exists. Do you want to overwrite it?" ),
i18n( "KMail Warning" ) ) ==
KMessageBox::No )
return;
}
// Note: SaveAsEncoded *always* stores the ENCRYPTED content with SIGNATURES.
// reason: SaveAsEncoded does not decode the Message Content-Transfer-Encoding
// but saves the _original_ content of the message (or the message part, resp.)
QFile file( filename );
if( file.open( IO_WriteOnly ) ) {
QDataStream ds( &file );
QCString cstr( mCurrentContextMenuItem->node()->msgPart().body() );
ds.writeRawBytes( cstr, cstr.length() );
file.close();
} else
KMessageBox::error( this, i18n( "Could not write the file" ),
i18n( "KMail Error" ) );
}
}
}
void KMMimePartTree::slotSaveItem( KMMimePartTreeItem* item, const QString& filename )
{
if ( item && !filename.isEmpty() ) {
bool bSaveEncrypted = false;
bool bEncryptedParts = item->node()->encryptionState() != KMMsgNotEncrypted;
if( bEncryptedParts )
if( KMessageBox::questionYesNo( this,
i18n( "This part of the message is encrypted. Do you want to keep the encryption when saving?" ),
i18n( "KMail Question" ) ) ==
KMessageBox::Yes )
bSaveEncrypted = true;
bool bSaveWithSig = true;
if( item->node()->signatureState() != KMMsgNotSigned )
if( KMessageBox::questionYesNo( this,
i18n( "This part of the message is signed. Do you want to keep the signature when saving?" ),
i18n( "KMail Question" ) ) !=
KMessageBox::Yes )
bSaveWithSig = false;
QFile file( filename );
if( file.open( IO_WriteOnly ) ) {
QDataStream ds( &file );
if( (bSaveEncrypted || !bEncryptedParts) && bSaveWithSig ) {
QByteArray cstr = item->node()->msgPart().bodyDecodedBinary();
ds.writeRawBytes( cstr, cstr.size() );
} else {
ObjectTreeParser otp( mReaderWin, 0, true,
bSaveEncrypted, bSaveWithSig );
otp.parseObjectTree( item->node() );
}
file.close();
} else
KMessageBox::error( this, i18n( "Could not write the file" ),
i18n( "KMail Error" ) );
}
}
void KMMimePartTree::slotSaveAll()
{
if( childCount() == 0)
return;
KFileDialog fdlg( QString::null, QString::null, this, 0, TRUE );
fdlg.setMode( KFile::Directory );
if (!fdlg.exec())
return;
QString dir = fdlg.selectedURL().path();
QListViewItemIterator lit( firstChild() );
for ( ; lit.current(); ) {
KMMimePartTreeItem *item = static_cast<KMMimePartTreeItem*>( lit.current() );
QString s = item->text(0);
if( s.startsWith( "file: " ) )
s = s.mid(6).stripWhiteSpace();
else
s = s.stripWhiteSpace();
QString filename = dir + "/" + s;
if( !filename.isEmpty() ) {
if( QFile::exists( filename ) ) {
// Unlike slotSaveAs, we're saving multiple files, so show which one creates trouble
if( KMessageBox::warningYesNo( this,
i18n( "A file named %1 already exists. Do you want to overwrite it?" ).arg( s ),
i18n( "KMail Warning" ) ) ==
KMessageBox::No ) {
++lit;
continue;
}
}
slotSaveItem( item, filename );
}
++lit;
}
}
void KMMimePartTree::slotSaveSelected()
{
QPtrList<QListViewItem> selected = selectedItems();
Q_ASSERT( selected.count() > 0 );
QPtrListIterator<QListViewItem> it( selected );
KFileDialog fdlg( QString::null, QString::null, this, 0, TRUE );
fdlg.setMode( KFile::Directory );
if (!fdlg.exec()) return;
QString dir = fdlg.selectedURL().path();
while ( it.current() ) {
KMMimePartTreeItem *item = static_cast<KMMimePartTreeItem*>( it.current() );
QString s = item->text(0);
if( s.startsWith( "file: " ) )
s = s.mid(6).stripWhiteSpace();
else
s = s.stripWhiteSpace();
QString filename = dir + "/" + s;
if( !filename.isEmpty() ) {
if( QFile::exists( filename ) ) {
// Unlike slotSaveAs, we're saving multiple files, so show which one creates trouble
if( KMessageBox::warningYesNo( this,
i18n( "A file named %1 already exists. Do you want to overwrite it?" ).arg( s ),
i18n( "KMail Warning" ) ) ==
KMessageBox::No ) {
++it;
continue;
}
}
slotSaveItem( item, filename );
}
++it;
}
}
KMMimePartTreeItem::KMMimePartTreeItem( KMMimePartTree * parent,
partNode* node,
const QString & description,
const QString & mimetype,
const QString & encoding,
KIO::filesize_t size )
: QListViewItem( parent, description,
QString::null, // set by setIconAndTextForType()
encoding,
KIO::convertSize( size ) ),
mPartNode( node )
{
if( node )
node->setMimePartTreeItem( this );
setIconAndTextForType( mimetype );
}
KMMimePartTreeItem::KMMimePartTreeItem( KMMimePartTreeItem * parent,
partNode* node,
const QString & description,
const QString & mimetype,
const QString & encoding,
KIO::filesize_t size,
bool revertOrder )
: QListViewItem( parent, description,
QString::null, // set by setIconAndTextForType()
encoding,
KIO::convertSize( size ) ),
mPartNode( node )
{
if( revertOrder && nextSibling() ){
QListViewItem* sib = nextSibling();
while( sib->nextSibling() )
sib = sib->nextSibling();
moveItem( sib );
}
if( node )
node->setMimePartTreeItem( this );
setIconAndTextForType( mimetype );
}
void KMMimePartTreeItem::setIconAndTextForType( const QString & mime )
{
QString mimetype = mime.lower();
if ( mimetype.startsWith( "multipart/" ) ) {
setText( 1, mimetype );
setPixmap( 0, SmallIcon("folder") );
} else if ( mimetype == "application/octet-stream" ) {
setText( 1, i18n("Unspecified Binary Data") ); // don't show "Unknown"...
setPixmap( 0, SmallIcon("unknown") );
} else {
KMimeType::Ptr mtp = KMimeType::mimeType( mimetype );
setText( 1, mtp ? mtp->comment() : mimetype );
setPixmap( 0, mtp ? mtp->pixmap( KIcon::Small) : SmallIcon("unknown") );
}
}
#include "kmmimeparttree.moc"
|
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "kmmimeparttree.h"
#include "kmreaderwin.h"
#include "partNode.h"
#include "kmmsgpart.h"
#include "kmkernel.h"
#include "objecttreeparser.h"
using KMail::ObjectTreeParser;
#include <kdebug.h>
#include <klocale.h>
#include <kfiledialog.h>
#include <kmessagebox.h>
#include <kiconloader.h>
#include <qheader.h>
#include <qpopupmenu.h>
KMMimePartTree::KMMimePartTree( KMReaderWin* readerWin,
QWidget* parent,
const char* name )
: KListView( parent, name ),
mReaderWin( readerWin )
{
addColumn( i18n("Description") );
addColumn( i18n("Type") );
addColumn( i18n("Encoding") );
addColumn( i18n("Size") );
setColumnAlignment( 3, Qt::AlignRight );
restoreLayoutIfPresent();
connect( this, SIGNAL( clicked( QListViewItem* ) ),
this, SLOT( itemClicked( QListViewItem* ) ) );
connect( this, SIGNAL( contextMenuRequested( QListViewItem*,
const QPoint&, int ) ),
this, SLOT( itemRightClicked( QListViewItem*, const QPoint& ) ) );
setSelectionMode( QListView::Extended );
setRootIsDecorated( false );
setAllColumnsShowFocus( true );
setShowToolTips( true );
setSorting(-1);
}
static const char configGroup[] = "MimePartTree";
KMMimePartTree::~KMMimePartTree() {
saveLayout( KMKernel::config(), configGroup );
}
void KMMimePartTree::restoreLayoutIfPresent() {
// first column: soaks up the rest of the space:
setColumnWidthMode( 0, Manual );
header()->setStretchEnabled( true, 0 );
// rest of the columns:
if ( KMKernel::config()->hasGroup( configGroup ) ) {
// there is a saved layout. use it...
restoreLayout( KMKernel::config(), configGroup );
// and disable Maximum mode:
for ( int i = 1 ; i < 4 ; ++i )
setColumnWidthMode( i, Manual );
} else {
// columns grow with their contents:
for ( int i = 1 ; i < 4 ; ++i )
setColumnWidthMode( i, Maximum );
}
}
void KMMimePartTree::itemClicked( QListViewItem* item )
{
KMMimePartTreeItem* i = dynamic_cast<KMMimePartTreeItem*>( item );
if ( 0 == i ) {
kdDebug(5006) << "Item was not a KMMimePartTreeItem!" << endl;
}
else {
kdDebug(5006) << "\n**\n** KMMimePartTree::itemClicked() **\n**" << endl;
if( mReaderWin->mRootNode == i->node() )
mReaderWin->update( true ); // Force update
else {
ObjectTreeParser otp( mReaderWin, 0, true );
otp.parseObjectTree( i->node() );
}
}
}
void KMMimePartTree::itemRightClicked( QListViewItem* item,
const QPoint& point )
{
mCurrentContextMenuItem = dynamic_cast<KMMimePartTreeItem*>( item );
if ( 0 == mCurrentContextMenuItem ) {
kdDebug(5006) << "Item was not a KMMimePartTreeItem!" << endl;
}
else {
kdDebug(5006) << "\n**\n** KMMimePartTree::itemRightClicked() **\n**" << endl;
/*
if( mReaderWin->mRootNode == i->node() )
mReaderWin->setMsg(mReaderWin->mMsg, true); // Force update
else
mReaderWin->parseObjectTree( i->node(), true );
// mReaderWin->parseObjectTree( mCurrentContextMenuItem->node(), true );
*/
QPopupMenu* popup = new QPopupMenu;
popup->insertItem( i18n( "Save &As..." ), this, SLOT( slotSaveAs() ) );
popup->insertItem( i18n( "Save as &Encoded..." ), this,
SLOT( slotSaveAsEncoded() ) );
popup->insertItem( i18n( "Save Selected Items..." ), this,
SLOT( slotSaveSelected() ) );
popup->insertItem( i18n( "Save All Attachments..." ), this,
SLOT( slotSaveAll() ) );
popup->exec( point );
delete popup;
//mReaderWin->parseObjectTree( mCurrentContextMenuItem->node(), true );
mCurrentContextMenuItem = 0;
}
}
void KMMimePartTree::slotSaveAs()
{
if( mCurrentContextMenuItem ) { // this should always be true
QString s = mCurrentContextMenuItem->text(0);
if( s.startsWith( "file: " ) )
s = s.mid(6).stripWhiteSpace();
else
s = s.stripWhiteSpace();
QString filename = KFileDialog::getSaveFileName( s,
QString::null,
this, QString::null );
if( !filename.isEmpty() ) {
if( QFile::exists( filename ) ) {
if( KMessageBox::warningYesNo( this,
i18n( "A file with this name already exists. Do you want to overwrite it?" ),
i18n( "KMail Warning" ) ) ==
KMessageBox::No )
return;
}
slotSaveItem( mCurrentContextMenuItem, filename );
}
}
}
void KMMimePartTree::slotSaveAsEncoded()
{
if( mCurrentContextMenuItem ) { // this should always be true
QString s = mCurrentContextMenuItem->text(0);
if( s.startsWith( "file: " ) )
s = s.mid(6).stripWhiteSpace();
else
s = s.stripWhiteSpace();
QString filename = KFileDialog::getSaveFileName( s,
QString::null,
this, QString::null );
if( !filename.isEmpty() ) {
if( QFile::exists( filename ) ) {
if( KMessageBox::warningYesNo( this,
i18n( "A file with this name already exists. Do you want to overwrite it?" ),
i18n( "KMail Warning" ) ) ==
KMessageBox::No )
return;
}
// Note: SaveAsEncoded *always* stores the ENCRYPTED content with SIGNATURES.
// reason: SaveAsEncoded does not decode the Message Content-Transfer-Encoding
// but saves the _original_ content of the message (or the message part, resp.)
QFile file( filename );
if( file.open( IO_WriteOnly ) ) {
QDataStream ds( &file );
QCString cstr( mCurrentContextMenuItem->node()->msgPart().body() );
ds.writeRawBytes( cstr, cstr.length() );
file.close();
} else
KMessageBox::error( this, i18n( "Could not write the file" ),
i18n( "KMail Error" ) );
}
}
}
void KMMimePartTree::slotSaveItem( KMMimePartTreeItem* item, const QString& filename )
{
if ( item && !filename.isEmpty() ) {
bool bSaveEncrypted = false;
bool bEncryptedParts = item->node()->encryptionState() != KMMsgNotEncrypted;
if( bEncryptedParts )
if( KMessageBox::questionYesNo( this,
i18n( "This part of the message is encrypted. Do you want to keep the encryption when saving?" ),
i18n( "KMail Question" ) ) ==
KMessageBox::Yes )
bSaveEncrypted = true;
bool bSaveWithSig = true;
if( item->node()->signatureState() != KMMsgNotSigned )
if( KMessageBox::questionYesNo( this,
i18n( "This part of the message is signed. Do you want to keep the signature when saving?" ),
i18n( "KMail Question" ) ) !=
KMessageBox::Yes )
bSaveWithSig = false;
QFile file( filename );
if( file.open( IO_WriteOnly ) ) {
QDataStream ds( &file );
if( (bSaveEncrypted || !bEncryptedParts) && bSaveWithSig ) {
QByteArray cstr = item->node()->msgPart().bodyDecodedBinary();
ds.writeRawBytes( cstr, cstr.size() );
} else {
ObjectTreeParser otp( mReaderWin, 0, true,
bSaveEncrypted, bSaveWithSig );
otp.parseObjectTree( item->node() );
}
file.close();
} else
KMessageBox::error( this, i18n( "Could not write the file" ),
i18n( "KMail Error" ) );
}
}
void KMMimePartTree::slotSaveAll()
{
if( childCount() == 0)
return;
KFileDialog fdlg( QString::null, QString::null, this, 0, TRUE );
fdlg.setMode( KFile::Directory );
if (!fdlg.exec())
return;
QString dir = fdlg.selectedURL().path();
for ( QListViewItemIterator lit( firstChild() ); lit.current(); ++lit ) {
KMMimePartTreeItem *item = static_cast<KMMimePartTreeItem*>( lit.current() );
//Check if it has the Content-Disposition... filename: header
//to make sure it's an actuall attachment
if( item->node()->msgPart().fileName().isNull() )
continue;
QString s = item->text(0);
if( s.startsWith( "file: " ) )
s = s.mid(6).stripWhiteSpace();
else
s = s.stripWhiteSpace();
QString filename = dir + "/" + s;
if( !filename.isEmpty() ) {
if( QFile::exists( filename ) ) {
// Unlike slotSaveAs, we're saving multiple files, so show which one creates trouble
if( KMessageBox::warningYesNo( this,
i18n( "A file named %1 already exists. Do you want to overwrite it?" ).arg( s ),
i18n( "KMail Warning" ) ) ==
KMessageBox::No ) {
++lit;
continue;
}
}
slotSaveItem( item, filename );
}
}
}
void KMMimePartTree::slotSaveSelected()
{
QPtrList<QListViewItem> selected = selectedItems();
Q_ASSERT( selected.count() > 0 );
QPtrListIterator<QListViewItem> it( selected );
KFileDialog fdlg( QString::null, QString::null, this, 0, TRUE );
fdlg.setMode( KFile::Directory );
if (!fdlg.exec()) return;
QString dir = fdlg.selectedURL().path();
while ( it.current() ) {
KMMimePartTreeItem *item = static_cast<KMMimePartTreeItem*>( it.current() );
QString s = item->text(0);
if( s.startsWith( "file: " ) )
s = s.mid(6).stripWhiteSpace();
else
s = s.stripWhiteSpace();
QString filename = dir + "/" + s;
if( !filename.isEmpty() ) {
if( QFile::exists( filename ) ) {
// Unlike slotSaveAs, we're saving multiple files, so show which one creates trouble
if( KMessageBox::warningYesNo( this,
i18n( "A file named %1 already exists. Do you want to overwrite it?" ).arg( s ),
i18n( "KMail Warning" ) ) ==
KMessageBox::No ) {
++it;
continue;
}
}
slotSaveItem( item, filename );
}
++it;
}
}
KMMimePartTreeItem::KMMimePartTreeItem( KMMimePartTree * parent,
partNode* node,
const QString & description,
const QString & mimetype,
const QString & encoding,
KIO::filesize_t size )
: QListViewItem( parent, description,
QString::null, // set by setIconAndTextForType()
encoding,
KIO::convertSize( size ) ),
mPartNode( node )
{
if( node )
node->setMimePartTreeItem( this );
setIconAndTextForType( mimetype );
}
KMMimePartTreeItem::KMMimePartTreeItem( KMMimePartTreeItem * parent,
partNode* node,
const QString & description,
const QString & mimetype,
const QString & encoding,
KIO::filesize_t size,
bool revertOrder )
: QListViewItem( parent, description,
QString::null, // set by setIconAndTextForType()
encoding,
KIO::convertSize( size ) ),
mPartNode( node )
{
if( revertOrder && nextSibling() ){
QListViewItem* sib = nextSibling();
while( sib->nextSibling() )
sib = sib->nextSibling();
moveItem( sib );
}
if( node )
node->setMimePartTreeItem( this );
setIconAndTextForType( mimetype );
}
void KMMimePartTreeItem::setIconAndTextForType( const QString & mime )
{
QString mimetype = mime.lower();
if ( mimetype.startsWith( "multipart/" ) ) {
setText( 1, mimetype );
setPixmap( 0, SmallIcon("folder") );
} else if ( mimetype == "application/octet-stream" ) {
setText( 1, i18n("Unspecified Binary Data") ); // don't show "Unknown"...
setPixmap( 0, SmallIcon("unknown") );
} else {
KMimeType::Ptr mtp = KMimeType::mimeType( mimetype );
setText( 1, mtp ? mtp->comment() : mimetype );
setPixmap( 0, mtp ? mtp->pixmap( KIcon::Small) : SmallIcon("unknown") );
}
}
#include "kmmimeparttree.moc"
|
Save all _actual_ attachments. But Ingo is right this whole code should be moved to KMCommand, which I'm gonna do but for the time being, save the attachments and not all body parts.
|
Save all _actual_ attachments. But Ingo is right this whole code should be moved
to KMCommand, which I'm gonna do but for the time being, save the attachments
and not all body parts.
svn path=/trunk/kdepim/; revision=236042
|
C++
|
lgpl-2.1
|
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.