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
|
---|---|---|---|---|---|---|---|---|---|
e62bd5a72f209232f43a4b7ed47e677866496107
|
terminal/TerminalClient.cpp
|
terminal/TerminalClient.cpp
|
#include "ClientConnection.hpp"
#include "CryptoHandler.hpp"
#include "FlakyFakeSocketHandler.hpp"
#include "Headers.hpp"
#include "ProcessHelper.hpp"
#include "ServerConnection.hpp"
#include "SocketUtils.hpp"
#include "UnixSocketHandler.hpp"
#include <errno.h>
#include <pwd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <termios.h>
#include "ETerminal.pb.h"
using namespace et;
shared_ptr<ClientConnection> globalClient;
#define FAIL_FATAL(X) \
if ((X) == -1) { \
printf("Error: (%d), %s\n", errno, strerror(errno)); \
exit(errno); \
}
termios terminal_backup;
DEFINE_string(host, "localhost", "host to join");
DEFINE_int32(port, 10022, "port to connect on");
DEFINE_string(passkey, "", "Passkey to encrypt/decrypt packets");
DEFINE_string(passkeyfile, "", "Passkey file to encrypt/decrypt packets");
int main(int argc, char** argv) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
GOOGLE_PROTOBUF_VERIFY_VERSION;
FLAGS_logbufsecs = 0;
FLAGS_logbuflevel = google::GLOG_INFO;
srand(1);
std::shared_ptr<SocketHandler> clientSocket(new UnixSocketHandler());
string passkey = FLAGS_passkey;
if (passkey.length() == 0 && FLAGS_passkeyfile.length() > 0) {
// Check for passkey file
std::ifstream t(FLAGS_passkeyfile.c_str());
std::stringstream buffer;
buffer << t.rdbuf();
passkey = buffer.str();
// Trim whitespace
passkey.erase(passkey.find_last_not_of(" \n\r\t") + 1);
// Delete the file with the passkey
remove(FLAGS_passkeyfile.c_str());
}
if (passkey.length() != 32) {
LOG(FATAL) << "Invalid/missing passkey: " << passkey << " "
<< passkey.length();
}
shared_ptr<ClientConnection> client = shared_ptr<ClientConnection>(
new ClientConnection(clientSocket, FLAGS_host, FLAGS_port, passkey));
globalClient = client;
while (true) {
try {
client->connect();
} catch (const runtime_error& err) {
LOG(ERROR) << "Connecting to server failed: " << err.what() << endl;
sleep(1);
continue;
}
break;
}
cout << "Client created with id: " << client->getClientId() << endl;
termios terminal_local;
tcgetattr(0, &terminal_local);
memcpy(&terminal_backup, &terminal_local, sizeof(struct termios));
struct winsize win = {0, 0, 0, 0};
cfmakeraw(&terminal_local);
tcsetattr(0, TCSANOW, &terminal_local);
// Whether the TE should keep running.
bool run = true;
// TE sends/receives data to/from the shell one char at a time.
#define BUF_SIZE (1024)
char b[BUF_SIZE];
time_t keepaliveTime = time(NULL) + 5;
bool waitingOnKeepalive = false;
while (run) {
// Data structures needed for select() and
// non-blocking I/O.
fd_set rfd;
fd_set wfd;
fd_set efd;
timeval tv;
FD_ZERO(&rfd);
FD_ZERO(&wfd);
FD_ZERO(&efd);
FD_SET(STDIN_FILENO, &rfd);
tv.tv_sec = 0;
tv.tv_usec = 1000;
select(STDIN_FILENO + 1, &rfd, &wfd, &efd, &tv);
try {
// Check for data to send.
if (FD_ISSET(STDIN_FILENO, &rfd)) {
// Read from stdin and write to our client that will then send it to the
// server.
int rc = read(STDIN_FILENO, b, BUF_SIZE);
FAIL_FATAL(rc);
if (rc > 0) {
// VLOG(1) << "Sending byte: " << int(b) << " " << char(b) << " " <<
// globalClient->getWriter()->getSequenceNumber();
string s(b, rc);
et::TerminalBuffer tb;
tb.set_buffer(s);
char c = et::PacketType::TERMINAL_BUFFER;
globalClient->writeAll(&c, 1);
globalClient->writeProto(tb);
keepaliveTime = time(NULL) + 5;
} else {
LOG(FATAL) << "Got an error reading from stdin: " << rc;
}
}
while (globalClient->hasData()) {
char packetType;
globalClient->readAll(&packetType, 1);
switch (packetType) {
case et::PacketType::TERMINAL_BUFFER: {
// Read from the server and write to our fake terminal
et::TerminalBuffer tb =
globalClient->readProto<et::TerminalBuffer>();
const string& s = tb.buffer();
// VLOG(1) << "Got byte: " << int(b) << " " << char(b) << " " <<
// globalClient->getReader()->getSequenceNumber();
keepaliveTime = time(NULL) + 1;
FATAL_FAIL(writeAll(STDOUT_FILENO, &s[0], s.length()));
break;
}
case et::PacketType::KEEP_ALIVE:
waitingOnKeepalive = false;
break;
default:
LOG(FATAL) << "Unknown packet type: " << int(packetType) << endl;
}
}
if (keepaliveTime < time(NULL)) {
keepaliveTime = time(NULL) + 5;
if (waitingOnKeepalive) {
LOG(INFO) << "Missed a keepalive, killing connection.";
globalClient->closeSocket();
waitingOnKeepalive = false;
} else {
VLOG(1) << "Writing keepalive packet";
char c = et::PacketType::KEEP_ALIVE;
globalClient->writeAll(&c, 1);
waitingOnKeepalive = true;
}
}
winsize tmpwin;
ioctl(1, TIOCGWINSZ, &tmpwin);
if (win.ws_row != tmpwin.ws_row || win.ws_col != tmpwin.ws_col ||
win.ws_xpixel != tmpwin.ws_xpixel ||
win.ws_ypixel != tmpwin.ws_ypixel) {
win = tmpwin;
cout << "Window size changed: " << win.ws_row << " " << win.ws_col
<< " " << win.ws_xpixel << " " << win.ws_ypixel << endl;
TerminalInfo ti;
ti.set_rows(win.ws_row);
ti.set_columns(win.ws_col);
ti.set_width(win.ws_xpixel);
ti.set_height(win.ws_ypixel);
char c = et::PacketType::TERMINAL_INFO;
globalClient->writeAll(&c, 1);
globalClient->writeProto(ti);
}
} catch (const runtime_error& re) {
LOG(ERROR) << "Error: " << re.what() << endl;
run = false;
}
usleep(1000);
}
tcsetattr(0, TCSANOW, &terminal_backup);
globalClient.reset();
client.reset();
LOG(INFO) << "Client derefernced" << endl;
return 0;
}
|
#include "ClientConnection.hpp"
#include "CryptoHandler.hpp"
#include "FlakyFakeSocketHandler.hpp"
#include "Headers.hpp"
#include "ProcessHelper.hpp"
#include "ServerConnection.hpp"
#include "SocketUtils.hpp"
#include "UnixSocketHandler.hpp"
#include <errno.h>
#include <pwd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <termios.h>
#include "ETerminal.pb.h"
using namespace et;
shared_ptr<ClientConnection> globalClient;
#define FAIL_FATAL(X) \
if ((X) == -1) { \
printf("Error: (%d), %s\n", errno, strerror(errno)); \
exit(errno); \
}
termios terminal_backup;
DEFINE_string(host, "localhost", "host to join");
DEFINE_int32(port, 10022, "port to connect on");
DEFINE_string(passkey, "", "Passkey to encrypt/decrypt packets");
DEFINE_string(passkeyfile, "", "Passkey file to encrypt/decrypt packets");
int main(int argc, char** argv) {
gflags::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
GOOGLE_PROTOBUF_VERIFY_VERSION;
FLAGS_logbufsecs = 0;
FLAGS_logbuflevel = google::GLOG_INFO;
srand(1);
std::shared_ptr<SocketHandler> clientSocket(new UnixSocketHandler());
string passkey = FLAGS_passkey;
if (passkey.length() == 0 && FLAGS_passkeyfile.length() > 0) {
// Check for passkey file
std::ifstream t(FLAGS_passkeyfile.c_str());
std::stringstream buffer;
buffer << t.rdbuf();
passkey = buffer.str();
// Trim whitespace
passkey.erase(passkey.find_last_not_of(" \n\r\t") + 1);
// Delete the file with the passkey
remove(FLAGS_passkeyfile.c_str());
}
if (passkey.length() != 32) {
LOG(FATAL) << "Invalid/missing passkey: " << passkey << " "
<< passkey.length();
}
shared_ptr<ClientConnection> client = shared_ptr<ClientConnection>(
new ClientConnection(clientSocket, FLAGS_host, FLAGS_port, passkey));
globalClient = client;
while (true) {
try {
client->connect();
} catch (const runtime_error& err) {
LOG(ERROR) << "Connecting to server failed: " << err.what() << endl;
sleep(1);
continue;
}
break;
}
cout << "Client created with id: " << client->getClientId() << endl;
termios terminal_local;
tcgetattr(0, &terminal_local);
memcpy(&terminal_backup, &terminal_local, sizeof(struct termios));
struct winsize win = {0, 0, 0, 0};
cfmakeraw(&terminal_local);
tcsetattr(0, TCSANOW, &terminal_local);
char* term = getenv("TERM");
if (term) {
LOG(INFO) << "Sending command to set terminal to " << term;
// Set terminal
string s = std::string("export TERM=") + std::string(term) + std::string("\n");
et::TerminalBuffer tb;
tb.set_buffer(s);
char c = et::PacketType::TERMINAL_BUFFER;
globalClient->writeAll(&c, 1);
globalClient->writeProto(tb);
}
// Whether the TE should keep running.
bool run = true;
// TE sends/receives data to/from the shell one char at a time.
#define BUF_SIZE (1024)
char b[BUF_SIZE];
time_t keepaliveTime = time(NULL) + 5;
bool waitingOnKeepalive = false;
while (run) {
// Data structures needed for select() and
// non-blocking I/O.
fd_set rfd;
fd_set wfd;
fd_set efd;
timeval tv;
FD_ZERO(&rfd);
FD_ZERO(&wfd);
FD_ZERO(&efd);
FD_SET(STDIN_FILENO, &rfd);
tv.tv_sec = 0;
tv.tv_usec = 1000;
select(STDIN_FILENO + 1, &rfd, &wfd, &efd, &tv);
try {
// Check for data to send.
if (FD_ISSET(STDIN_FILENO, &rfd)) {
// Read from stdin and write to our client that will then send it to the
// server.
int rc = read(STDIN_FILENO, b, BUF_SIZE);
FAIL_FATAL(rc);
if (rc > 0) {
// VLOG(1) << "Sending byte: " << int(b) << " " << char(b) << " " <<
// globalClient->getWriter()->getSequenceNumber();
string s(b, rc);
et::TerminalBuffer tb;
tb.set_buffer(s);
char c = et::PacketType::TERMINAL_BUFFER;
globalClient->writeAll(&c, 1);
globalClient->writeProto(tb);
keepaliveTime = time(NULL) + 5;
} else {
LOG(FATAL) << "Got an error reading from stdin: " << rc;
}
}
while (globalClient->hasData()) {
char packetType;
globalClient->readAll(&packetType, 1);
switch (packetType) {
case et::PacketType::TERMINAL_BUFFER: {
// Read from the server and write to our fake terminal
et::TerminalBuffer tb =
globalClient->readProto<et::TerminalBuffer>();
const string& s = tb.buffer();
// VLOG(1) << "Got byte: " << int(b) << " " << char(b) << " " <<
// globalClient->getReader()->getSequenceNumber();
keepaliveTime = time(NULL) + 1;
FATAL_FAIL(writeAll(STDOUT_FILENO, &s[0], s.length()));
break;
}
case et::PacketType::KEEP_ALIVE:
waitingOnKeepalive = false;
break;
default:
LOG(FATAL) << "Unknown packet type: " << int(packetType) << endl;
}
}
if (keepaliveTime < time(NULL)) {
keepaliveTime = time(NULL) + 5;
if (waitingOnKeepalive) {
LOG(INFO) << "Missed a keepalive, killing connection.";
globalClient->closeSocket();
waitingOnKeepalive = false;
} else {
VLOG(1) << "Writing keepalive packet";
char c = et::PacketType::KEEP_ALIVE;
globalClient->writeAll(&c, 1);
waitingOnKeepalive = true;
}
}
winsize tmpwin;
ioctl(1, TIOCGWINSZ, &tmpwin);
if (win.ws_row != tmpwin.ws_row || win.ws_col != tmpwin.ws_col ||
win.ws_xpixel != tmpwin.ws_xpixel ||
win.ws_ypixel != tmpwin.ws_ypixel) {
win = tmpwin;
LOG(INFO) << "Window size changed: " << win.ws_row << " " << win.ws_col
<< " " << win.ws_xpixel << " " << win.ws_ypixel << endl;
TerminalInfo ti;
ti.set_rows(win.ws_row);
ti.set_columns(win.ws_col);
ti.set_width(win.ws_xpixel);
ti.set_height(win.ws_ypixel);
char c = et::PacketType::TERMINAL_INFO;
globalClient->writeAll(&c, 1);
globalClient->writeProto(ti);
}
} catch (const runtime_error& re) {
LOG(ERROR) << "Error: " << re.what() << endl;
run = false;
}
usleep(1000);
}
tcsetattr(0, TCSANOW, &terminal_backup);
globalClient.reset();
client.reset();
LOG(INFO) << "Client derefernced" << endl;
return 0;
}
|
Set TERM appropriately
|
Set TERM appropriately
|
C++
|
apache-2.0
|
MisterTea/EternalTCP,MisterTea/EternalTCP,MisterTea/EternalTCP
|
ffc87aff2dda923d36bc3227a1bf64fe0cc6aa0b
|
terminal/TerminalServer.cpp
|
terminal/TerminalServer.cpp
|
#include "ClientConnection.hpp"
#include "ConsoleUtils.hpp"
#include "CryptoHandler.hpp"
#include "FlakyFakeSocketHandler.hpp"
#include "Headers.hpp"
#include "ServerConnection.hpp"
#include "SocketUtils.hpp"
#include "UnixSocketHandler.hpp"
#include "IdPasskeyHandler.hpp"
#include "simpleini/SimpleIni.h"
#include <errno.h>
#include <pwd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <termios.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <grp.h>
#if __APPLE__
#include <util.h>
#elif __FreeBSD__
#include <sys/types.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <libutil.h>
#else
#include <pty.h>
#endif
#ifdef WITH_SELINUX
#include <selinux/selinux.h>
#include <selinux/get_context_list.h>
#endif
#include "ETerminal.pb.h"
using namespace et;
namespace google {}
namespace gflags {}
using namespace google;
using namespace gflags;
map<string, int64_t> idPidMap;
shared_ptr<ServerConnection> globalServer;
void halt();
#define FAIL_FATAL(X) \
if ((X) == -1) { \
LOG(FATAL) << "Error: (" << errno << "): " << strerror(errno); \
}
DEFINE_int32(port, 0, "Port to listen on");
DEFINE_string(idpasskey, "", "If set, uses IPC to send a client id/key to the server daemon");
DEFINE_string(idpasskeyfile, "", "If set, uses IPC to send a client id/key to the server daemon from a file");
DEFINE_bool(daemon, false, "Daemonize the server");
DEFINE_string(cfgfile, "", "Location of the config file");
thread* idPasskeyListenerThread = NULL;
thread* terminalThread = NULL;
void runTerminal(shared_ptr<ServerClientConnection> serverClientState,
int masterfd) {
string disconnectBuffer;
// Whether the TE should keep running.
bool run = true;
// TE sends/receives data to/from the shell one char at a time.
#define BUF_SIZE (1024)
char b[BUF_SIZE];
while (run) {
// Data structures needed for select() and
// non-blocking I/O.
fd_set rfd;
timeval tv;
FD_ZERO(&rfd);
FD_SET(masterfd, &rfd);
int maxfd = masterfd;
int serverClientFd = serverClientState->getSocketFd();
if (serverClientFd > 0) {
FD_SET(serverClientFd, &rfd);
maxfd = max(maxfd, serverClientFd);
}
tv.tv_sec = 0;
tv.tv_usec = 10000;
select(maxfd + 1, &rfd, NULL, NULL, &tv);
try {
// Check for data to receive; the received
// data includes also the data previously sent
// on the same master descriptor (line 90).
if (FD_ISSET(masterfd, &rfd)) {
// Read from fake terminal and write to server
memset(b, 0, BUF_SIZE);
int rc = read(masterfd, b, BUF_SIZE);
if (rc > 0) {
// VLOG(2) << "Sending bytes: " << int(b) << " " << char(b) << " "
// << serverClientState->getWriter()->getSequenceNumber();
char c = et::PacketType::TERMINAL_BUFFER;
serverClientState->writeMessage(string(1, c));
string s(b, rc);
et::TerminalBuffer tb;
tb.set_buffer(s);
serverClientState->writeProto(tb);
} else {
LOG(INFO) << "Terminal session ended";
run = false;
globalServer->removeClient(serverClientState->getId());
break;
}
}
if (serverClientFd > 0 && FD_ISSET(serverClientFd, &rfd)) {
while (serverClientState->hasData()) {
string packetTypeString;
if (!serverClientState->readMessage(&packetTypeString)) {
break;
}
char packetType = packetTypeString[0];
switch (packetType) {
case et::PacketType::TERMINAL_BUFFER: {
// Read from the server and write to our fake terminal
et::TerminalBuffer tb =
serverClientState->readProto<et::TerminalBuffer>();
const string& s = tb.buffer();
// VLOG(2) << "Got byte: " << int(b) << " " << char(b) << " " <<
// serverClientState->getReader()->getSequenceNumber();
FATAL_FAIL(writeAll(masterfd, &s[0], s.length()));
break;
}
case et::PacketType::KEEP_ALIVE: {
// Echo keepalive back to client
VLOG(1) << "Got keep alive";
char c = et::PacketType::KEEP_ALIVE;
serverClientState->writeMessage(string(1, c));
break;
}
case et::PacketType::TERMINAL_INFO: {
VLOG(1) << "Got terminal info";
et::TerminalInfo ti =
serverClientState->readProto<et::TerminalInfo>();
winsize tmpwin;
tmpwin.ws_row = ti.row();
tmpwin.ws_col = ti.column();
tmpwin.ws_xpixel = ti.width();
tmpwin.ws_ypixel = ti.height();
ioctl(masterfd, TIOCSWINSZ, &tmpwin);
break;
}
default:
LOG(FATAL) << "Unknown packet type: " << int(packetType) << endl;
}
}
}
} catch (const runtime_error& re) {
LOG(ERROR) << "Error: " << re.what();
cerr << "Error: " << re.what();
serverClientState->closeSocket();
// If the client disconnects the session, it shuoldn't end
// because the client may be starting a new one. TODO: Start a
// timer which eventually kills the server.
// run=false;
}
}
{
string id = serverClientState->getId();
serverClientState.reset();
globalServer->removeClient(id);
}
}
void startTerminal(shared_ptr<ServerClientConnection> serverClientState,
InitialPayload payload) {
const TerminalInfo& ti = payload.terminal();
winsize win;
win.ws_row = ti.row();
win.ws_col = ti.column();
win.ws_xpixel = ti.width();
win.ws_ypixel = ti.height();
for (const string& it : payload.environmentvar()) {
size_t equalsPos = it.find("=");
if (equalsPos == string::npos) {
LOG(FATAL) << "Invalid environment variable";
}
string name = it.substr(0, equalsPos);
string value = it.substr(equalsPos + 1);
setenv(name.c_str(), value.c_str(), 1);
}
int masterfd;
std::string terminal = getTerminal();
pid_t pid = forkpty(&masterfd, NULL, NULL, &win);
switch (pid) {
case -1:
FAIL_FATAL(pid);
case 0: {
// child
VLOG(1) << "Closing server in fork" << endl;
// Close server on client process
globalServer->close();
globalServer.reset();
string id = serverClientState->getId();
if (idPidMap.find(id) == idPidMap.end()) {
LOG(FATAL) << "Error: PID for ID not found";
}
passwd* pwd = getpwuid(idPidMap[id]);
gid_t groups[65536];
int ngroups = 65536;
#ifdef WITH_SELINUX
char* sename = NULL;
char* level = NULL;
FATAL_FAIL(getseuserbyname(pwd->pw_name, &sename, &level));
security_context_t user_ctx = NULL;
FATAL_FAIL(get_default_context_with_level(sename, level, NULL, &user_ctx));
setexeccon(user_ctx);
free(sename);
free(level);
#endif
#ifdef __APPLE__
if (getgrouplist(pwd->pw_name, pwd->pw_gid, (int*)groups, &ngroups) == -1) {
LOG(FATAL) << "User is part of more than 65536 groups!";
}
#else
if (getgrouplist(pwd->pw_name, pwd->pw_gid, groups, &ngroups) == -1) {
LOG(FATAL) << "User is part of more than 65536 groups!";
}
#endif
#ifdef setresgid
FATAL_FAIL(setresgid(pwd->pw_gid, pwd->pw_gid, pwd->pw_gid));
#else // OS/X
FATAL_FAIL(setregid(pwd->pw_gid, pwd->pw_gid));
#endif
#ifdef __APPLE__
/*
* OS X requires initgroups after setgid to opt back into
* memberd support for >16 supplemental groups.
*/
FATAL_FAIL(initgroups(pwd->pw_name, pwd->pw_gid));
#endif
FATAL_FAIL(::setgroups(ngroups, groups));
#ifdef setresuid
FATAL_FAIL(setresuid(pwd->pw_uid, pwd->pw_uid, pwd->pw_uid));
#else // OS/X
FATAL_FAIL(setreuid(pwd->pw_uid, pwd->pw_uid));
#endif
if (pwd->pw_shell) {
terminal = pwd->pw_shell;
}
setenv("SHELL", terminal.c_str(), 1);
const char *homedir = pwd->pw_dir;
setenv("HOME", homedir, 1);
setenv("USER", pwd->pw_name, 1);
setenv("LOGNAME", pwd->pw_name, 1);
setenv("PATH", "/usr/local/bin:/bin:/usr/bin", 1);
chdir(pwd->pw_dir);
VLOG(1) << "Child process " << terminal << endl;
execl(terminal.c_str(), terminal.c_str(), NULL);
exit(0);
break;
}
default:
// parent
cout << "pty opened " << masterfd << endl;
terminalThread = new thread(runTerminal, serverClientState, masterfd);
break;
}
}
class TerminalServerHandler : public ServerConnectionHandler {
virtual bool newClient(shared_ptr<ServerClientConnection> serverClientState) {
InitialPayload payload = serverClientState->readProto<InitialPayload>();
startTerminal(serverClientState, payload);
return true;
}
};
bool doneListening=false;
int main(int argc, char** argv) {
ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
GOOGLE_PROTOBUF_VERIFY_VERSION;
FLAGS_logbufsecs = 0;
FLAGS_logbuflevel = google::GLOG_INFO;
srand(1);
if (FLAGS_cfgfile.length()) {
// Load the config file
CSimpleIniA ini(true, true, true);
SI_Error rc = ini.LoadFile(FLAGS_cfgfile.c_str());
if (rc == 0) {
if (FLAGS_port == 0) {
const char* portString = ini.GetValue("Networking", "Port", NULL);
if (portString) {
FLAGS_port = stoi(portString);
}
}
} else {
LOG(FATAL) << "Invalid config file: " << FLAGS_cfgfile;
}
}
if (FLAGS_port == 0) {
FLAGS_port = 2022;
}
if (FLAGS_idpasskey.length() > 0 || FLAGS_idpasskeyfile.length() > 0) {
string idpasskey = FLAGS_idpasskey;
if (FLAGS_idpasskeyfile.length() > 0) {
// Check for passkey file
std::ifstream t(FLAGS_idpasskeyfile.c_str());
std::stringstream buffer;
buffer << t.rdbuf();
idpasskey = buffer.str();
// Trim whitespace
idpasskey.erase(idpasskey.find_last_not_of(" \n\r\t") + 1);
// Delete the file with the passkey
remove(FLAGS_idpasskeyfile.c_str());
}
idpasskey += '\0';
IdPasskeyHandler::send(idpasskey);
return 0;
}
if (FLAGS_daemon) {
if (::daemon(0,0) == -1) {
LOG(FATAL) << "Error creating daemon: " << strerror(errno);
}
stdout = fopen("/tmp/etserver_err", "w+");
setvbuf(stdout, NULL, _IOLBF, BUFSIZ); // set to line buffering
stderr = fopen("/tmp/etserver_err", "w+");
setvbuf(stderr, NULL, _IOLBF, BUFSIZ); // set to line buffering
}
std::shared_ptr<UnixSocketHandler> serverSocket(new UnixSocketHandler());
LOG(INFO) << "Creating server";
globalServer = shared_ptr<ServerConnection>(new ServerConnection(
serverSocket, FLAGS_port,
shared_ptr<TerminalServerHandler>(new TerminalServerHandler())));
idPasskeyListenerThread = new thread(IdPasskeyHandler::runServer, &doneListening);
globalServer->run();
}
void halt() {
LOG(INFO) << "Shutting down server" << endl;
doneListening = true;
globalServer->close();
LOG(INFO) << "Waiting for server to finish" << endl;
sleep(3);
exit(0);
}
|
#include "ClientConnection.hpp"
#include "ConsoleUtils.hpp"
#include "CryptoHandler.hpp"
#include "FlakyFakeSocketHandler.hpp"
#include "Headers.hpp"
#include "ServerConnection.hpp"
#include "SocketUtils.hpp"
#include "UnixSocketHandler.hpp"
#include "IdPasskeyHandler.hpp"
#include "simpleini/SimpleIni.h"
#include <errno.h>
#include <pwd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <termios.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <grp.h>
#if __APPLE__
#include <util.h>
#elif __FreeBSD__
#include <sys/types.h>
#include <sys/ioctl.h>
#include <termios.h>
#include <libutil.h>
#else
#include <pty.h>
#endif
#ifdef WITH_SELINUX
#include <selinux/selinux.h>
#include <selinux/get_context_list.h>
#endif
#include "ETerminal.pb.h"
using namespace et;
namespace google {}
namespace gflags {}
using namespace google;
using namespace gflags;
map<string, int64_t> idPidMap;
shared_ptr<ServerConnection> globalServer;
void halt();
#define FAIL_FATAL(X) \
if ((X) == -1) { \
LOG(FATAL) << "Error: (" << errno << "): " << strerror(errno); \
}
DEFINE_int32(port, 0, "Port to listen on");
DEFINE_string(idpasskey, "", "If set, uses IPC to send a client id/key to the server daemon");
DEFINE_string(idpasskeyfile, "", "If set, uses IPC to send a client id/key to the server daemon from a file");
DEFINE_bool(daemon, false, "Daemonize the server");
DEFINE_string(cfgfile, "", "Location of the config file");
thread* idPasskeyListenerThread = NULL;
thread* terminalThread = NULL;
void runTerminal(shared_ptr<ServerClientConnection> serverClientState,
int masterfd) {
string disconnectBuffer;
// Whether the TE should keep running.
bool run = true;
// TE sends/receives data to/from the shell one char at a time.
#define BUF_SIZE (1024)
char b[BUF_SIZE];
while (run) {
// Data structures needed for select() and
// non-blocking I/O.
fd_set rfd;
timeval tv;
FD_ZERO(&rfd);
FD_SET(masterfd, &rfd);
int maxfd = masterfd;
int serverClientFd = serverClientState->getSocketFd();
if (serverClientFd > 0) {
FD_SET(serverClientFd, &rfd);
maxfd = max(maxfd, serverClientFd);
}
tv.tv_sec = 0;
tv.tv_usec = 10000;
select(maxfd + 1, &rfd, NULL, NULL, &tv);
try {
// Check for data to receive; the received
// data includes also the data previously sent
// on the same master descriptor (line 90).
if (FD_ISSET(masterfd, &rfd)) {
// Read from fake terminal and write to server
memset(b, 0, BUF_SIZE);
int rc = read(masterfd, b, BUF_SIZE);
if (rc > 0) {
// VLOG(2) << "Sending bytes: " << int(b) << " " << char(b) << " "
// << serverClientState->getWriter()->getSequenceNumber();
char c = et::PacketType::TERMINAL_BUFFER;
serverClientState->writeMessage(string(1, c));
string s(b, rc);
et::TerminalBuffer tb;
tb.set_buffer(s);
serverClientState->writeProto(tb);
} else {
LOG(INFO) << "Terminal session ended";
run = false;
globalServer->removeClient(serverClientState->getId());
break;
}
}
if (serverClientFd > 0 && FD_ISSET(serverClientFd, &rfd)) {
while (serverClientState->hasData()) {
string packetTypeString;
if (!serverClientState->readMessage(&packetTypeString)) {
break;
}
char packetType = packetTypeString[0];
switch (packetType) {
case et::PacketType::TERMINAL_BUFFER: {
// Read from the server and write to our fake terminal
et::TerminalBuffer tb =
serverClientState->readProto<et::TerminalBuffer>();
const string& s = tb.buffer();
// VLOG(2) << "Got byte: " << int(b) << " " << char(b) << " " <<
// serverClientState->getReader()->getSequenceNumber();
FATAL_FAIL(writeAll(masterfd, &s[0], s.length()));
break;
}
case et::PacketType::KEEP_ALIVE: {
// Echo keepalive back to client
VLOG(1) << "Got keep alive";
char c = et::PacketType::KEEP_ALIVE;
serverClientState->writeMessage(string(1, c));
break;
}
case et::PacketType::TERMINAL_INFO: {
VLOG(1) << "Got terminal info";
et::TerminalInfo ti =
serverClientState->readProto<et::TerminalInfo>();
winsize tmpwin;
tmpwin.ws_row = ti.row();
tmpwin.ws_col = ti.column();
tmpwin.ws_xpixel = ti.width();
tmpwin.ws_ypixel = ti.height();
ioctl(masterfd, TIOCSWINSZ, &tmpwin);
break;
}
default:
LOG(FATAL) << "Unknown packet type: " << int(packetType) << endl;
}
}
}
} catch (const runtime_error& re) {
LOG(ERROR) << "Error: " << re.what();
cerr << "Error: " << re.what();
serverClientState->closeSocket();
// If the client disconnects the session, it shuoldn't end
// because the client may be starting a new one. TODO: Start a
// timer which eventually kills the server.
// run=false;
}
}
{
string id = serverClientState->getId();
serverClientState.reset();
globalServer->removeClient(id);
}
}
void startTerminal(shared_ptr<ServerClientConnection> serverClientState,
InitialPayload payload) {
const TerminalInfo& ti = payload.terminal();
winsize win;
win.ws_row = ti.row();
win.ws_col = ti.column();
win.ws_xpixel = ti.width();
win.ws_ypixel = ti.height();
for (const string& it : payload.environmentvar()) {
size_t equalsPos = it.find("=");
if (equalsPos == string::npos) {
LOG(FATAL) << "Invalid environment variable";
}
string name = it.substr(0, equalsPos);
string value = it.substr(equalsPos + 1);
setenv(name.c_str(), value.c_str(), 1);
}
int masterfd;
std::string terminal = getTerminal();
pid_t pid = forkpty(&masterfd, NULL, NULL, &win);
switch (pid) {
case -1:
FAIL_FATAL(pid);
case 0: {
// child
VLOG(1) << "Closing server in fork" << endl;
// Close server on client process
globalServer->close();
globalServer.reset();
string id = serverClientState->getId();
if (idPidMap.find(id) == idPidMap.end()) {
LOG(FATAL) << "Error: PID for ID not found";
}
passwd* pwd = getpwuid(idPidMap[id]);
gid_t groups[65536];
int ngroups = 65536;
#ifdef WITH_SELINUX
char* sename = NULL;
char* level = NULL;
FATAL_FAIL(getseuserbyname(pwd->pw_name, &sename, &level));
security_context_t user_ctx = NULL;
FATAL_FAIL(get_default_context_with_level(sename, level, NULL, &user_ctx));
setexeccon(user_ctx);
free(sename);
free(level);
#endif
#ifdef __APPLE__
if (getgrouplist(pwd->pw_name, pwd->pw_gid, (int*)groups, &ngroups) == -1) {
LOG(FATAL) << "User is part of more than 65536 groups!";
}
#else
if (getgrouplist(pwd->pw_name, pwd->pw_gid, groups, &ngroups) == -1) {
LOG(FATAL) << "User is part of more than 65536 groups!";
}
#endif
#ifdef setresgid
FATAL_FAIL(setresgid(pwd->pw_gid, pwd->pw_gid, pwd->pw_gid));
#else // OS/X
FATAL_FAIL(setregid(pwd->pw_gid, pwd->pw_gid));
#endif
#ifdef __APPLE__
FATAL_FAIL(initgroups(pwd->pw_name, pwd->pw_gid));
#else
FATAL_FAIL(::setgroups(ngroups, groups));
#endif
#ifdef setresuid
FATAL_FAIL(setresuid(pwd->pw_uid, pwd->pw_uid, pwd->pw_uid));
#else // OS/X
FATAL_FAIL(setreuid(pwd->pw_uid, pwd->pw_uid));
#endif
if (pwd->pw_shell) {
terminal = pwd->pw_shell;
}
setenv("SHELL", terminal.c_str(), 1);
const char *homedir = pwd->pw_dir;
setenv("HOME", homedir, 1);
setenv("USER", pwd->pw_name, 1);
setenv("LOGNAME", pwd->pw_name, 1);
setenv("PATH", "/usr/local/bin:/bin:/usr/bin", 1);
chdir(pwd->pw_dir);
VLOG(1) << "Child process " << terminal << endl;
execl(terminal.c_str(), terminal.c_str(), NULL);
exit(0);
break;
}
default:
// parent
cout << "pty opened " << masterfd << endl;
terminalThread = new thread(runTerminal, serverClientState, masterfd);
break;
}
}
class TerminalServerHandler : public ServerConnectionHandler {
virtual bool newClient(shared_ptr<ServerClientConnection> serverClientState) {
InitialPayload payload = serverClientState->readProto<InitialPayload>();
startTerminal(serverClientState, payload);
return true;
}
};
bool doneListening=false;
int main(int argc, char** argv) {
ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
GOOGLE_PROTOBUF_VERIFY_VERSION;
FLAGS_logbufsecs = 0;
FLAGS_logbuflevel = google::GLOG_INFO;
srand(1);
if (FLAGS_cfgfile.length()) {
// Load the config file
CSimpleIniA ini(true, true, true);
SI_Error rc = ini.LoadFile(FLAGS_cfgfile.c_str());
if (rc == 0) {
if (FLAGS_port == 0) {
const char* portString = ini.GetValue("Networking", "Port", NULL);
if (portString) {
FLAGS_port = stoi(portString);
}
}
} else {
LOG(FATAL) << "Invalid config file: " << FLAGS_cfgfile;
}
}
if (FLAGS_port == 0) {
FLAGS_port = 2022;
}
if (FLAGS_idpasskey.length() > 0 || FLAGS_idpasskeyfile.length() > 0) {
string idpasskey = FLAGS_idpasskey;
if (FLAGS_idpasskeyfile.length() > 0) {
// Check for passkey file
std::ifstream t(FLAGS_idpasskeyfile.c_str());
std::stringstream buffer;
buffer << t.rdbuf();
idpasskey = buffer.str();
// Trim whitespace
idpasskey.erase(idpasskey.find_last_not_of(" \n\r\t") + 1);
// Delete the file with the passkey
remove(FLAGS_idpasskeyfile.c_str());
}
idpasskey += '\0';
IdPasskeyHandler::send(idpasskey);
return 0;
}
if (FLAGS_daemon) {
if (::daemon(0,0) == -1) {
LOG(FATAL) << "Error creating daemon: " << strerror(errno);
}
stdout = fopen("/tmp/etserver_err", "w+");
setvbuf(stdout, NULL, _IOLBF, BUFSIZ); // set to line buffering
stderr = fopen("/tmp/etserver_err", "w+");
setvbuf(stderr, NULL, _IOLBF, BUFSIZ); // set to line buffering
}
std::shared_ptr<UnixSocketHandler> serverSocket(new UnixSocketHandler());
LOG(INFO) << "Creating server";
globalServer = shared_ptr<ServerConnection>(new ServerConnection(
serverSocket, FLAGS_port,
shared_ptr<TerminalServerHandler>(new TerminalServerHandler())));
idPasskeyListenerThread = new thread(IdPasskeyHandler::runServer, &doneListening);
globalServer->run();
}
void halt() {
LOG(INFO) << "Shutting down server" << endl;
doneListening = true;
globalServer->close();
LOG(INFO) << "Waiting for server to finish" << endl;
sleep(3);
exit(0);
}
|
Fix group setting in OS/X
|
Fix group setting in OS/X
|
C++
|
apache-2.0
|
MisterTea/EternalTCP,MisterTea/EternalTCP,MisterTea/EternalTCP
|
bb2bb66fbedc17509823588977fd52fa9c0b5ba0
|
src/drmap.cpp
|
src/drmap.cpp
|
/*
* Copyright (C) 2010 Telmo Menezes.
* [email protected]
*/
#include "drmap.h"
#include "utils.h"
#include "emd_hat_signatures_interface.hpp"
#include <stdlib.h>
#include <strings.h>
#include <stdio.h>
namespace syn
{
DRMap::DRMap(unsigned int bin_number, double min_val_hor, double max_val_hor,
double min_val_ver, double max_val_ver)
{
this->bin_number = bin_number;
this->min_val_hor = min_val_hor;
this->max_val_hor = max_val_hor;
this->min_val_ver = min_val_ver;
this->max_val_ver = max_val_ver;
data = (double*)malloc(bin_number * bin_number * sizeof(double));
clear();
}
DRMap::~DRMap()
{
free(data);
}
void DRMap::clear()
{
bzero(data, bin_number * bin_number * sizeof(double));
}
void DRMap::set_value(unsigned int x, unsigned int y, double val)
{
data[(y * bin_number) + x] = val;
}
void DRMap::inc_value(unsigned int x, unsigned int y)
{
data[(y * bin_number) + x] += 1;
}
double DRMap::get_value(unsigned int x, unsigned int y)
{
return data[(y * bin_number) + x];
}
void DRMap::log_scale()
{
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
if(data[(y * bin_number) + x] > 0) {
data[(y * bin_number) + x] = log(data[(y * bin_number) + x]);
}
}
}
}
void DRMap::normalize()
{
double m = max();
if (m <= 0) {
return;
}
// normalize by max
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
data[(y * bin_number) + x] = data[(y * bin_number) + x] / m;
}
}
}
void DRMap::binary()
{
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
if(data[(y * bin_number) + x] > 0) {
data[(y * bin_number) + x] = 1;
}
}
}
}
double DRMap::total()
{
double total = 0;
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
total += data[(y * bin_number) + x];
}
}
return total;
}
double DRMap::max()
{
double max = 0;
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
if (data[(y * bin_number) + x] > max) {
max = data[(y * bin_number) + x];
}
}
}
return max;
}
double DRMap::simple_dist(DRMap* map)
{
double dist = 0;
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
dist += fabs(data[(y * bin_number) + x] - map->data[(y * map->bin_number) + x]);
}
}
return dist;
}
double ground_dist(feature_tt* feature1, feature_tt* feature2)
{
double deltaX = feature1->x - feature2->x;
double deltaY = feature1->y - feature2->y;
double dist = sqrt((deltaX * deltaX) + (deltaY * deltaY));
//double dist = (deltaX * deltaX) + (deltaY * deltaY);
return dist;
}
signature_tt* get_emd_signature(DRMap* map)
{
unsigned int n = 0;
unsigned int bin_number = map->get_bin_number();
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
if (map->get_value(x, y) > 0) {
n++;
}
}
}
feature_tt* features = (feature_tt*)malloc(sizeof(feature_tt) * n);
double* weights = (double*)malloc(sizeof(double) * n);
unsigned int i = 0;
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
double val = map->get_value(x, y);
if (val > 0) {
features[i].x = x;
features[i].y = y;
weights[i] = val;
i++;
}
}
}
signature_tt* signature = (signature_tt*)malloc(sizeof(signature_tt));
signature->n = n;
signature->Features = features;
signature->Weights = weights;
return signature;
}
double DRMap::emd_dist(DRMap* map)
{
printf("totals-> %f; %f\n", total(), map->total());
double infinity = 9999999999.9;
if (total() <= 0) {
return infinity;
}
if (map->total() <= 0) {
return infinity;
}
signature_tt* sig1 = get_emd_signature(this);
signature_tt* sig2 = get_emd_signature(map);
double dist = emd_hat_signature_interface(sig1, sig2, ground_dist, -1);
free(sig1->Features);
free(sig1->Weights);
free(sig1);
free(sig2->Features);
free(sig2->Weights);
free(sig2);
return dist;
}
void DRMap::print()
{
for (unsigned int y = 0; y < bin_number; y++) {
for (unsigned int x = 0; x < bin_number; x++) {
printf("%f\t", get_value(x, y));
}
printf("\n");
}
}
}
|
/*
* Copyright (C) 2010 Telmo Menezes.
* [email protected]
*/
#include "drmap.h"
#include "utils.h"
#include "emd_hat_signatures_interface.hpp"
#include <stdlib.h>
#include <strings.h>
#include <stdio.h>
namespace syn
{
DRMap::DRMap(unsigned int bin_number, double min_val_hor, double max_val_hor,
double min_val_ver, double max_val_ver)
{
this->bin_number = bin_number;
this->min_val_hor = min_val_hor;
this->max_val_hor = max_val_hor;
this->min_val_ver = min_val_ver;
this->max_val_ver = max_val_ver;
data = (double*)malloc(bin_number * bin_number * sizeof(double));
clear();
}
DRMap::~DRMap()
{
free(data);
}
void DRMap::clear()
{
bzero(data, bin_number * bin_number * sizeof(double));
}
void DRMap::set_value(unsigned int x, unsigned int y, double val)
{
data[(y * bin_number) + x] = val;
}
void DRMap::inc_value(unsigned int x, unsigned int y)
{
data[(y * bin_number) + x] += 1;
}
double DRMap::get_value(unsigned int x, unsigned int y)
{
return data[(y * bin_number) + x];
}
void DRMap::log_scale()
{
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
if(data[(y * bin_number) + x] > 0) {
data[(y * bin_number) + x] = log(data[(y * bin_number) + x]);
}
}
}
}
void DRMap::normalize()
{
double m = total();
if (m <= 0) {
return;
}
// normalize by max
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
data[(y * bin_number) + x] = data[(y * bin_number) + x] / m;
}
}
}
void DRMap::binary()
{
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
if(data[(y * bin_number) + x] > 0) {
data[(y * bin_number) + x] = 1;
}
}
}
}
double DRMap::total()
{
double total = 0;
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
total += data[(y * bin_number) + x];
}
}
return total;
}
double DRMap::max()
{
double max = 0;
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
if (data[(y * bin_number) + x] > max) {
max = data[(y * bin_number) + x];
}
}
}
return max;
}
double DRMap::simple_dist(DRMap* map)
{
double dist = 0;
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
dist += fabs(data[(y * bin_number) + x] - map->data[(y * map->bin_number) + x]);
}
}
return dist;
}
double ground_dist(feature_tt* feature1, feature_tt* feature2)
{
double deltaX = feature1->x - feature2->x;
double deltaY = feature1->y - feature2->y;
double dist = sqrt((deltaX * deltaX) + (deltaY * deltaY));
//double dist = (deltaX * deltaX) + (deltaY * deltaY);
return dist;
}
signature_tt* get_emd_signature(DRMap* map)
{
unsigned int n = 0;
unsigned int bin_number = map->get_bin_number();
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
if (map->get_value(x, y) > 0) {
n++;
}
}
}
feature_tt* features = (feature_tt*)malloc(sizeof(feature_tt) * n);
double* weights = (double*)malloc(sizeof(double) * n);
unsigned int i = 0;
for (unsigned int x = 0; x < bin_number; x++) {
for (unsigned int y = 0; y < bin_number; y++) {
double val = map->get_value(x, y);
if (val > 0) {
features[i].x = x;
features[i].y = y;
weights[i] = val;
i++;
}
}
}
signature_tt* signature = (signature_tt*)malloc(sizeof(signature_tt));
signature->n = n;
signature->Features = features;
signature->Weights = weights;
return signature;
}
double DRMap::emd_dist(DRMap* map)
{
printf("totals-> %f; %f\n", total(), map->total());
double infinity = 9999999999.9;
if (total() <= 0) {
return infinity;
}
if (map->total() <= 0) {
return infinity;
}
signature_tt* sig1 = get_emd_signature(this);
signature_tt* sig2 = get_emd_signature(map);
double dist = emd_hat_signature_interface(sig1, sig2, ground_dist, -1);
free(sig1->Features);
free(sig1->Weights);
free(sig1);
free(sig2->Features);
free(sig2->Weights);
free(sig2);
return dist;
}
void DRMap::print()
{
for (unsigned int y = 0; y < bin_number; y++) {
for (unsigned int x = 0; x < bin_number; x++) {
printf("%f\t", get_value(x, y));
}
printf("\n");
}
}
}
|
normalize DRMap by total
|
normalize DRMap by total
|
C++
|
mit
|
telmomenezes/synthetic,telmomenezes/synthetic
|
381351d2121ddc4c0fb881b327e4bcd3ca871ff6
|
src/gurpy.cpp
|
src/gurpy.cpp
|
/******************************************************************************
* Copyright (C) 2015 Sahil Kang <[email protected]>
*
* This file is part of gurpy.
*
* gurpy 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.
*
* gurpy 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 gurpy. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include <Python.h>
#include <gur.hpp>
#include <gurmukhi.hpp>
static PyObject* gp_letters(PyObject *self, PyObject *args)
{
const char* str;
if (!PyArg_ParseTuple(args, "s", &str))
{
return NULL;
}
return PyUnicode_FromString(gur::letters(str));
}
static PyObject* gp_accents(PyObject *self, PyObject *args)
{
const char* str;
if (!PyArg_ParseTuple(args, "s", &str))
{
return NULL;
}
return PyUnicode_FromString(gur::accents(str));
}
static PyObject* gp_puncs(PyObject *self, PyObject *args)
{
const char* str;
if (!PyArg_ParseTuple(args, "s", &str))
{
return NULL;
}
return PyUnicode_FromString(gur::puncs(str));
}
static PyObject* gp_digits(PyObject *self, PyObject *args)
{
const char* str;
if (!PyArg_ParseTuple(args, "s", &str))
{
return NULL;
}
return PyUnicode_FromString(gur::digits(str));
}
static PyObject* gp_symbols(PyObject *self, PyObject *args)
{
const char* str;
if (!PyArg_ParseTuple(args, "s", &str))
{
return NULL;
}
return PyUnicode_FromString(gur::symbols(str));
}
static PyObject* gp_comp(PyObject *self, PyObject *args)
{
const char* str;
if (!PyArg_ParseTuple(args, "s", &str))
{
return NULL;
}
return PyUnicode_FromString(gur::comp(str));
}
static PyObject* gp_clobber(PyObject *self, PyObject *args)
{
const char* str;
if (!PyArg_ParseTuple(args, "s", &str))
{
return NULL;
}
return PyUnicode_FromString(gur::clobber(str));
}
static PyObject* gp_unclobber(PyObject *self, PyObject *args)
{
const char* str;
if (!PyArg_ParseTuple(args, "s", &str))
{
return NULL;
}
return PyUnicode_FromString(gur::unclobber(str));
}
static PyObject* gp_is_letter(PyObject *self, PyObject *args)
{
const char* str;
if (!PyArg_ParseTuple(args, "s", &str))
{
return NULL;
}
if (gur::is_letter(str))
{
Py_RETURN_TRUE;
}
else
{
Py_RETURN_FALSE;
}
}
static PyObject* gp_is_accent(PyObject *self, PyObject *args)
{
const char* str;
if (!PyArg_ParseTuple(args, "s", &str))
{
return NULL;
}
if (gur::is_accent(str))
{
Py_RETURN_TRUE;
}
else
{
Py_RETURN_FALSE;
}
}
static PyObject* gp_is_punc(PyObject *self, PyObject *args)
{
const char* str;
if (!PyArg_ParseTuple(args, "s", &str))
{
return NULL;
}
if (gur::is_punc(str))
{
Py_RETURN_TRUE;
}
else
{
Py_RETURN_FALSE;
}
}
static PyObject* gp_is_digit(PyObject *self, PyObject *args)
{
const char* str;
if (!PyArg_ParseTuple(args, "s", &str))
{
return NULL;
}
if (gur::is_digit(str))
{
Py_RETURN_TRUE;
}
else
{
Py_RETURN_FALSE;
}
}
static PyObject* gp_is_symbol(PyObject *self, PyObject *args)
{
const char* str;
if (!PyArg_ParseTuple(args, "s", &str))
{
return NULL;
}
if (gur::is_symbol(str))
{
Py_RETURN_TRUE;
}
else
{
Py_RETURN_FALSE;
}
}
static PyMethodDef gp_methods[] =
{
{"letters", gp_letters, METH_VARARGS, "Get the letters in a word."},
{"accents", gp_accents, METH_VARARGS, "Get the accents in a word."},
{"puncs", gp_puncs, METH_VARARGS, "Get the punctuations in a word."},
{"digits", gp_digits, METH_VARARGS, "Get the digits in a word."},
{"symbols", gp_symbols, METH_VARARGS, "Get the symbols in a word."},
{"comp", gp_comp, METH_VARARGS, "Get a word's composition."},
{"clobber", gp_clobber, METH_VARARGS, "Combine diacritics."},
{"unclobber", gp_unclobber, METH_VARARGS, "Separate diacritics."},
{"is_letter", gp_is_letter, METH_VARARGS, "Is string a letter?"},
{"is_accent", gp_is_accent, METH_VARARGS, "Is string a accent?"},
{"is_punc", gp_is_punc, METH_VARARGS, "Is string a punctuation?"},
{"is_digit", gp_is_digit, METH_VARARGS, "Is string a digit?"},
{"is_symbol", gp_is_symbol, METH_VARARGS, "Is string a symbol?"},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef gp_module =
{
PyModuleDef_HEAD_INIT,
"gurpy", //name of the module
"Python extension for libgur", //module doc
-1,
gp_methods
};
PyMODINIT_FUNC PyInit_gurpy(void)
{
PyObject *mod = PyModule_Create(&gp_module);
PyObject_SetAttrString(mod, "a1", PyUnicode_FromString(gur::A1));
PyObject_SetAttrString(mod, "a2", PyUnicode_FromString(gur::A2));
PyObject_SetAttrString(mod, "a3", PyUnicode_FromString(gur::A3));
PyObject_SetAttrString(mod, "a4", PyUnicode_FromString(gur::A4));
PyObject_SetAttrString(mod, "a5", PyUnicode_FromString(gur::A5));
PyObject_SetAttrString(mod, "b1", PyUnicode_FromString(gur::B1));
PyObject_SetAttrString(mod, "b2", PyUnicode_FromString(gur::B2));
PyObject_SetAttrString(mod, "b3", PyUnicode_FromString(gur::B3));
PyObject_SetAttrString(mod, "b4", PyUnicode_FromString(gur::B4));
PyObject_SetAttrString(mod, "b5", PyUnicode_FromString(gur::B5));
PyObject_SetAttrString(mod, "c1", PyUnicode_FromString(gur::C1));
PyObject_SetAttrString(mod, "c2", PyUnicode_FromString(gur::C2));
PyObject_SetAttrString(mod, "c3", PyUnicode_FromString(gur::C3));
PyObject_SetAttrString(mod, "c4", PyUnicode_FromString(gur::C4));
PyObject_SetAttrString(mod, "c5", PyUnicode_FromString(gur::C5));
PyObject_SetAttrString(mod, "d1", PyUnicode_FromString(gur::D1));
PyObject_SetAttrString(mod, "d2", PyUnicode_FromString(gur::D2));
PyObject_SetAttrString(mod, "d3", PyUnicode_FromString(gur::D3));
PyObject_SetAttrString(mod, "d4", PyUnicode_FromString(gur::D4));
PyObject_SetAttrString(mod, "d5", PyUnicode_FromString(gur::D5));
PyObject_SetAttrString(mod, "e1", PyUnicode_FromString(gur::E1));
PyObject_SetAttrString(mod, "e2", PyUnicode_FromString(gur::E2));
PyObject_SetAttrString(mod, "e3", PyUnicode_FromString(gur::E3));
PyObject_SetAttrString(mod, "e4", PyUnicode_FromString(gur::E4));
PyObject_SetAttrString(mod, "e5", PyUnicode_FromString(gur::E5));
PyObject_SetAttrString(mod, "f1", PyUnicode_FromString(gur::F1));
PyObject_SetAttrString(mod, "f2", PyUnicode_FromString(gur::F2));
PyObject_SetAttrString(mod, "f3", PyUnicode_FromString(gur::F3));
PyObject_SetAttrString(mod, "f4", PyUnicode_FromString(gur::F4));
PyObject_SetAttrString(mod, "f5", PyUnicode_FromString(gur::F5));
PyObject_SetAttrString(mod, "g1", PyUnicode_FromString(gur::G1));
PyObject_SetAttrString(mod, "g2", PyUnicode_FromString(gur::G2));
PyObject_SetAttrString(mod, "g3", PyUnicode_FromString(gur::G3));
PyObject_SetAttrString(mod, "g4", PyUnicode_FromString(gur::G4));
PyObject_SetAttrString(mod, "g5", PyUnicode_FromString(gur::G5));
PyObject_SetAttrString(mod, "h1", PyUnicode_FromString(gur::H1));
PyObject_SetAttrString(mod, "h2", PyUnicode_FromString(gur::H2));
PyObject_SetAttrString(mod, "h3", PyUnicode_FromString(gur::H3));
PyObject_SetAttrString(mod, "h4", PyUnicode_FromString(gur::H4));
PyObject_SetAttrString(mod, "h5", PyUnicode_FromString(gur::H5));
PyObject_SetAttrString(mod, "i1", PyUnicode_FromString(gur::I1));
PyObject_SetAttrString(mod, "i2", PyUnicode_FromString(gur::I2));
PyObject_SetAttrString(mod, "i3", PyUnicode_FromString(gur::I3));
PyObject_SetAttrString(mod, "i4", PyUnicode_FromString(gur::I4));
PyObject_SetAttrString(mod, "i5", PyUnicode_FromString(gur::I5));
PyObject_SetAttrString(mod, "j1", PyUnicode_FromString(gur::J1));
PyObject_SetAttrString(mod, "j2", PyUnicode_FromString(gur::J2));
PyObject_SetAttrString(mod, "j3", PyUnicode_FromString(gur::J3));
PyObject_SetAttrString(mod, "j4", PyUnicode_FromString(gur::J4));
PyObject_SetAttrString(mod, "j5", PyUnicode_FromString(gur::J5));
PyObject_SetAttrString(mod, "k1", PyUnicode_FromString(gur::K1));
PyObject_SetAttrString(mod, "k2", PyUnicode_FromString(gur::K2));
PyObject_SetAttrString(mod, "k3", PyUnicode_FromString(gur::K3));
PyObject_SetAttrString(mod, "k4", PyUnicode_FromString(gur::K4));
PyObject_SetAttrString(mod, "k5", PyUnicode_FromString(gur::K5));
PyObject_SetAttrString(mod, "l1", PyUnicode_FromString(gur::L1));
PyObject_SetAttrString(mod, "l2", PyUnicode_FromString(gur::L2));
PyObject_SetAttrString(mod, "l3", PyUnicode_FromString(gur::L3));
PyObject_SetAttrString(mod, "l4", PyUnicode_FromString(gur::L4));
PyObject_SetAttrString(mod, "l5", PyUnicode_FromString(gur::L5));
PyObject_SetAttrString(mod, "m1", PyUnicode_FromString(gur::M1));
PyObject_SetAttrString(mod, "m2", PyUnicode_FromString(gur::M2));
PyObject_SetAttrString(mod, "m3", PyUnicode_FromString(gur::M3));
PyObject_SetAttrString(mod, "m4", PyUnicode_FromString(gur::M4));
PyObject_SetAttrString(mod, "m5", PyUnicode_FromString(gur::M5));
PyObject_SetAttrString(mod, "n1", PyUnicode_FromString(gur::N1));
PyObject_SetAttrString(mod, "n2", PyUnicode_FromString(gur::N2));
PyObject_SetAttrString(mod, "n3", PyUnicode_FromString(gur::N3));
PyObject_SetAttrString(mod, "n4", PyUnicode_FromString(gur::N4));
PyObject_SetAttrString(mod, "n5", PyUnicode_FromString(gur::N5));
PyObject_SetAttrString(mod, "o1", PyUnicode_FromString(gur::O1));
PyObject_SetAttrString(mod, "o2", PyUnicode_FromString(gur::O2));
PyObject_SetAttrString(mod, "o3", PyUnicode_FromString(gur::O3));
PyObject_SetAttrString(mod, "o4", PyUnicode_FromString(gur::O4));
PyObject_SetAttrString(mod, "o5", PyUnicode_FromString(gur::O5));
PyObject_SetAttrString(mod, "p1", PyUnicode_FromString(gur::P1));
PyObject_SetAttrString(mod, "p2", PyUnicode_FromString(gur::P2));
PyObject_SetAttrString(mod, "p3", PyUnicode_FromString(gur::P3));
PyObject_SetAttrString(mod, "p4", PyUnicode_FromString(gur::P4));
PyObject_SetAttrString(mod, "p5", PyUnicode_FromString(gur::P5));
PyObject_SetAttrString(mod, "q1", PyUnicode_FromString(gur::Q1));
PyObject_SetAttrString(mod, "q2", PyUnicode_FromString(gur::Q2));
return mod;
}
|
/******************************************************************************
* Copyright (C) 2015 Sahil Kang <[email protected]>
*
* This file is part of gurpy.
*
* gurpy 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.
*
* gurpy 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 gurpy. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include <Python.h>
#include <gur.hpp>
#include <gurmukhi.hpp>
template<typename T>
static PyObject* get_func(PyObject *&args, const T &func)
{
const char *str;
if (!PyArg_ParseTuple(args, "s", &str))
{
return NULL;
}
return PyUnicode_FromString(func(str));
}
template<typename T>
static PyObject* is_type(PyObject *&args, const T &func)
{
const char* str;
if (!PyArg_ParseTuple(args, "s", &str))
{
return NULL;
}
if (func(str))
{
Py_RETURN_TRUE;
}
else
{
Py_RETURN_FALSE;
}
}
static PyObject* gp_letters(PyObject *self, PyObject *args)
{
return get_func(args,
(const char* (*)(const char* const&))&gur::letters);
}
static PyObject* gp_accents(PyObject *self, PyObject *args)
{
return get_func(args,
(const char* (*)(const char* const&))&gur::accents);
}
static PyObject* gp_puncs(PyObject *self, PyObject *args)
{
return get_func(args,
(const char* (*)(const char* const&))&gur::puncs);
}
static PyObject* gp_digits(PyObject *self, PyObject *args)
{
return get_func(args,
(const char* (*)(const char* const&))&gur::digits);
}
static PyObject* gp_symbols(PyObject *self, PyObject *args)
{
return get_func(args,
(const char* (*)(const char* const&))&gur::symbols);
}
static PyObject* gp_comp(PyObject *self, PyObject *args)
{
return get_func(args,
(const char* (*)(const char* const&))&gur::comp);
}
static PyObject* gp_clobber(PyObject *self, PyObject *args)
{
return get_func(args,
(const char* (*)(const char* const&))&gur::clobber);
}
static PyObject* gp_unclobber(PyObject *self, PyObject *args)
{
return get_func(args,
(const char* (*)(const char* const&))&gur::unclobber);
}
static PyObject* gp_is_letter(PyObject *self, PyObject *args)
{
return is_type(args, (bool (*)(const char* const&))&gur::is_letter);
}
static PyObject* gp_is_accent(PyObject *self, PyObject *args)
{
return is_type(args, (bool (*)(const char* const&))&gur::is_accent);
}
static PyObject* gp_is_punc(PyObject *self, PyObject *args)
{
return is_type(args, (bool (*)(const char* const&))&gur::is_punc);
}
static PyObject* gp_is_digit(PyObject *self, PyObject *args)
{
return is_type(args, (bool (*)(const char* const&))&gur::is_digit);
}
static PyObject* gp_is_symbol(PyObject *self, PyObject *args)
{
return is_type(args, (bool (*)(const char* const&))&gur::is_symbol);
}
static PyMethodDef gp_methods[] =
{
{"letters", gp_letters, METH_VARARGS, "Get the letters in a word."},
{"accents", gp_accents, METH_VARARGS, "Get the accents in a word."},
{"puncs", gp_puncs, METH_VARARGS, "Get the punctuations in a word."},
{"digits", gp_digits, METH_VARARGS, "Get the digits in a word."},
{"symbols", gp_symbols, METH_VARARGS, "Get the symbols in a word."},
{"comp", gp_comp, METH_VARARGS, "Get a word's composition."},
{"clobber", gp_clobber, METH_VARARGS, "Combine diacritics."},
{"unclobber", gp_unclobber, METH_VARARGS, "Separate diacritics."},
{"is_letter", gp_is_letter, METH_VARARGS, "Is string a letter?"},
{"is_accent", gp_is_accent, METH_VARARGS, "Is string a accent?"},
{"is_punc", gp_is_punc, METH_VARARGS, "Is string a punctuation?"},
{"is_digit", gp_is_digit, METH_VARARGS, "Is string a digit?"},
{"is_symbol", gp_is_symbol, METH_VARARGS, "Is string a symbol?"},
{NULL, NULL, 0, NULL}
};
static struct PyModuleDef gp_module =
{
PyModuleDef_HEAD_INIT,
"gurpy", //name of the module
"Python extension for libgur", //module doc
-1,
gp_methods
};
PyMODINIT_FUNC PyInit_gurpy(void)
{
PyObject *mod = PyModule_Create(&gp_module);
PyObject_SetAttrString(mod, "a1", PyUnicode_FromString(gur::A1));
PyObject_SetAttrString(mod, "a2", PyUnicode_FromString(gur::A2));
PyObject_SetAttrString(mod, "a3", PyUnicode_FromString(gur::A3));
PyObject_SetAttrString(mod, "a4", PyUnicode_FromString(gur::A4));
PyObject_SetAttrString(mod, "a5", PyUnicode_FromString(gur::A5));
PyObject_SetAttrString(mod, "b1", PyUnicode_FromString(gur::B1));
PyObject_SetAttrString(mod, "b2", PyUnicode_FromString(gur::B2));
PyObject_SetAttrString(mod, "b3", PyUnicode_FromString(gur::B3));
PyObject_SetAttrString(mod, "b4", PyUnicode_FromString(gur::B4));
PyObject_SetAttrString(mod, "b5", PyUnicode_FromString(gur::B5));
PyObject_SetAttrString(mod, "c1", PyUnicode_FromString(gur::C1));
PyObject_SetAttrString(mod, "c2", PyUnicode_FromString(gur::C2));
PyObject_SetAttrString(mod, "c3", PyUnicode_FromString(gur::C3));
PyObject_SetAttrString(mod, "c4", PyUnicode_FromString(gur::C4));
PyObject_SetAttrString(mod, "c5", PyUnicode_FromString(gur::C5));
PyObject_SetAttrString(mod, "d1", PyUnicode_FromString(gur::D1));
PyObject_SetAttrString(mod, "d2", PyUnicode_FromString(gur::D2));
PyObject_SetAttrString(mod, "d3", PyUnicode_FromString(gur::D3));
PyObject_SetAttrString(mod, "d4", PyUnicode_FromString(gur::D4));
PyObject_SetAttrString(mod, "d5", PyUnicode_FromString(gur::D5));
PyObject_SetAttrString(mod, "e1", PyUnicode_FromString(gur::E1));
PyObject_SetAttrString(mod, "e2", PyUnicode_FromString(gur::E2));
PyObject_SetAttrString(mod, "e3", PyUnicode_FromString(gur::E3));
PyObject_SetAttrString(mod, "e4", PyUnicode_FromString(gur::E4));
PyObject_SetAttrString(mod, "e5", PyUnicode_FromString(gur::E5));
PyObject_SetAttrString(mod, "f1", PyUnicode_FromString(gur::F1));
PyObject_SetAttrString(mod, "f2", PyUnicode_FromString(gur::F2));
PyObject_SetAttrString(mod, "f3", PyUnicode_FromString(gur::F3));
PyObject_SetAttrString(mod, "f4", PyUnicode_FromString(gur::F4));
PyObject_SetAttrString(mod, "f5", PyUnicode_FromString(gur::F5));
PyObject_SetAttrString(mod, "g1", PyUnicode_FromString(gur::G1));
PyObject_SetAttrString(mod, "g2", PyUnicode_FromString(gur::G2));
PyObject_SetAttrString(mod, "g3", PyUnicode_FromString(gur::G3));
PyObject_SetAttrString(mod, "g4", PyUnicode_FromString(gur::G4));
PyObject_SetAttrString(mod, "g5", PyUnicode_FromString(gur::G5));
PyObject_SetAttrString(mod, "h1", PyUnicode_FromString(gur::H1));
PyObject_SetAttrString(mod, "h2", PyUnicode_FromString(gur::H2));
PyObject_SetAttrString(mod, "h3", PyUnicode_FromString(gur::H3));
PyObject_SetAttrString(mod, "h4", PyUnicode_FromString(gur::H4));
PyObject_SetAttrString(mod, "h5", PyUnicode_FromString(gur::H5));
PyObject_SetAttrString(mod, "i1", PyUnicode_FromString(gur::I1));
PyObject_SetAttrString(mod, "i2", PyUnicode_FromString(gur::I2));
PyObject_SetAttrString(mod, "i3", PyUnicode_FromString(gur::I3));
PyObject_SetAttrString(mod, "i4", PyUnicode_FromString(gur::I4));
PyObject_SetAttrString(mod, "i5", PyUnicode_FromString(gur::I5));
PyObject_SetAttrString(mod, "j1", PyUnicode_FromString(gur::J1));
PyObject_SetAttrString(mod, "j2", PyUnicode_FromString(gur::J2));
PyObject_SetAttrString(mod, "j3", PyUnicode_FromString(gur::J3));
PyObject_SetAttrString(mod, "j4", PyUnicode_FromString(gur::J4));
PyObject_SetAttrString(mod, "j5", PyUnicode_FromString(gur::J5));
PyObject_SetAttrString(mod, "k1", PyUnicode_FromString(gur::K1));
PyObject_SetAttrString(mod, "k2", PyUnicode_FromString(gur::K2));
PyObject_SetAttrString(mod, "k3", PyUnicode_FromString(gur::K3));
PyObject_SetAttrString(mod, "k4", PyUnicode_FromString(gur::K4));
PyObject_SetAttrString(mod, "k5", PyUnicode_FromString(gur::K5));
PyObject_SetAttrString(mod, "l1", PyUnicode_FromString(gur::L1));
PyObject_SetAttrString(mod, "l2", PyUnicode_FromString(gur::L2));
PyObject_SetAttrString(mod, "l3", PyUnicode_FromString(gur::L3));
PyObject_SetAttrString(mod, "l4", PyUnicode_FromString(gur::L4));
PyObject_SetAttrString(mod, "l5", PyUnicode_FromString(gur::L5));
PyObject_SetAttrString(mod, "m1", PyUnicode_FromString(gur::M1));
PyObject_SetAttrString(mod, "m2", PyUnicode_FromString(gur::M2));
PyObject_SetAttrString(mod, "m3", PyUnicode_FromString(gur::M3));
PyObject_SetAttrString(mod, "m4", PyUnicode_FromString(gur::M4));
PyObject_SetAttrString(mod, "m5", PyUnicode_FromString(gur::M5));
PyObject_SetAttrString(mod, "n1", PyUnicode_FromString(gur::N1));
PyObject_SetAttrString(mod, "n2", PyUnicode_FromString(gur::N2));
PyObject_SetAttrString(mod, "n3", PyUnicode_FromString(gur::N3));
PyObject_SetAttrString(mod, "n4", PyUnicode_FromString(gur::N4));
PyObject_SetAttrString(mod, "n5", PyUnicode_FromString(gur::N5));
PyObject_SetAttrString(mod, "o1", PyUnicode_FromString(gur::O1));
PyObject_SetAttrString(mod, "o2", PyUnicode_FromString(gur::O2));
PyObject_SetAttrString(mod, "o3", PyUnicode_FromString(gur::O3));
PyObject_SetAttrString(mod, "o4", PyUnicode_FromString(gur::O4));
PyObject_SetAttrString(mod, "o5", PyUnicode_FromString(gur::O5));
PyObject_SetAttrString(mod, "p1", PyUnicode_FromString(gur::P1));
PyObject_SetAttrString(mod, "p2", PyUnicode_FromString(gur::P2));
PyObject_SetAttrString(mod, "p3", PyUnicode_FromString(gur::P3));
PyObject_SetAttrString(mod, "p4", PyUnicode_FromString(gur::P4));
PyObject_SetAttrString(mod, "p5", PyUnicode_FromString(gur::P5));
PyObject_SetAttrString(mod, "q1", PyUnicode_FromString(gur::Q1));
PyObject_SetAttrString(mod, "q2", PyUnicode_FromString(gur::Q2));
return mod;
}
|
Reduce code duplication
|
Reduce code duplication
|
C++
|
agpl-3.0
|
SahilKang/gurpy
|
5909a6e02465fdd3ef46bddd64e99193a2b61783
|
inc/libodfgen/OdtGenerator.hxx
|
inc/libodfgen/OdtGenerator.hxx
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* libodfgen
* Version: MPL 2.0 / LGPLv2.1+
*
* 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/.
*
* Major Contributor(s):
* Copyright (C) 2002-2004 William Lachance ([email protected])
* Copyright (C) 2004 Fridrich Strba ([email protected])
*
* For minor contributions see the git repository.
*
* Alternatively, the contents of this file may be used under the terms
* of the GNU Lesser General Public License Version 2.1 or later
* (LGPLv2.1+), in which case the provisions of the LGPLv2.1+ are
* applicable instead of those above.
*
* For further information visit http://libwpd.sourceforge.net
*/
/* "This product is not manufactured, approved, or supported by
* Corel Corporation or Corel Corporation Limited."
*/
#ifndef _ODTGENERATOR_HXX_
#define _ODTGENERATOR_HXX_
#include <librevenge/librevenge.h>
#include "OdfDocumentHandler.hxx"
class OdtGeneratorPrivate;
/** A generator for text documents.
*
* See @c librevenge library for documentation of the ::librevenge::RVNGDocumentInterface
* interface.
*/
class OdtGenerator : public librevenge::RVNGTextInterface
{
public:
OdtGenerator(OdfDocumentHandler *pHandler, const OdfStreamType streamType);
~OdtGenerator();
void setDocumentMetaData(const librevenge::RVNGPropertyList &propList);
void startDocument();
void endDocument();
void definePageStyle(const librevenge::RVNGPropertyList &);
void openPageSpan(const librevenge::RVNGPropertyList &propList);
void closePageSpan();
void defineSectionStyle(const librevenge::RVNGPropertyList &);
void openSection(const librevenge::RVNGPropertyList &propList);
void closeSection();
void openHeader(const librevenge::RVNGPropertyList &propList);
void closeHeader();
void openFooter(const librevenge::RVNGPropertyList &propList);
void closeFooter();
void defineParagraphStyle(const librevenge::RVNGPropertyList &);
void openParagraph(const librevenge::RVNGPropertyList &propList);
void closeParagraph();
void defineCharacterStyle(const librevenge::RVNGPropertyList &);
void openSpan(const librevenge::RVNGPropertyList &propList);
void closeSpan();
void insertTab();
void insertSpace();
void insertText(const librevenge::RVNGString &text);
void insertLineBreak();
void insertField(const librevenge::RVNGPropertyList &propList);
void defineOrderedListLevel(const librevenge::RVNGPropertyList &propList);
void defineUnorderedListLevel(const librevenge::RVNGPropertyList &propList);
void openOrderedListLevel(const librevenge::RVNGPropertyList &propList);
void openUnorderedListLevel(const librevenge::RVNGPropertyList &propList);
void closeOrderedListLevel();
void closeUnorderedListLevel();
void openListElement(const librevenge::RVNGPropertyList &propList);
void closeListElement();
void openFootnote(const librevenge::RVNGPropertyList &propList);
void closeFootnote();
void openEndnote(const librevenge::RVNGPropertyList &propList);
void closeEndnote();
void openComment(const librevenge::RVNGPropertyList &propList);
void closeComment();
void openTextBox(const librevenge::RVNGPropertyList &propList);
void closeTextBox();
void openTable(const librevenge::RVNGPropertyList &propList);
void openTableRow(const librevenge::RVNGPropertyList &propList);
void closeTableRow();
void openTableCell(const librevenge::RVNGPropertyList &propList);
void closeTableCell();
void insertCoveredTableCell(const librevenge::RVNGPropertyList &propList);
void closeTable();
void openFrame(const librevenge::RVNGPropertyList &propList);
void closeFrame();
void insertBinaryObject(const librevenge::RVNGPropertyList &propList);
void insertEquation(const librevenge::RVNGPropertyList &propList);
/** Registers a handler for embedded objects.
*
* @param[in] mimeType MIME type of the object
* @param[in] objectHandler a function that handles processing of
* the object's data and generating output
*/
void registerEmbeddedObjectHandler(const librevenge::RVNGString &mimeType, OdfEmbeddedObject objectHandler);
/** Registers a handler for embedded images.
*
* The handler converts the image to a format suitable for the used
* OdfDocumentHandler.
*
* @param[in] mimeType MIME type of the image
* @param[in] imageHandler a function that handles processing of
* the images's data and generating output
*/
void registerEmbeddedImageHandler(const librevenge::RVNGString &mimeType, OdfEmbeddedImage imageHandler);
private:
OdtGenerator(OdtGenerator const &);
OdtGenerator &operator=(OdtGenerator const &);
OdtGeneratorPrivate *mpImpl;
};
#endif
/* vim:set shiftwidth=4 softtabstop=4 noexpandtab: */
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- */
/* libodfgen
* Version: MPL 2.0 / LGPLv2.1+
*
* 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/.
*
* Major Contributor(s):
* Copyright (C) 2002-2004 William Lachance ([email protected])
* Copyright (C) 2004 Fridrich Strba ([email protected])
*
* For minor contributions see the git repository.
*
* Alternatively, the contents of this file may be used under the terms
* of the GNU Lesser General Public License Version 2.1 or later
* (LGPLv2.1+), in which case the provisions of the LGPLv2.1+ are
* applicable instead of those above.
*
* For further information visit http://libwpd.sourceforge.net
*/
/* "This product is not manufactured, approved, or supported by
* Corel Corporation or Corel Corporation Limited."
*/
#ifndef _ODTGENERATOR_HXX_
#define _ODTGENERATOR_HXX_
#include <librevenge/librevenge.h>
#include "OdfDocumentHandler.hxx"
class OdtGeneratorPrivate;
/** A generator for text documents.
*
* See @c librevenge library for documentation of the ::librevenge::RVNGTextInterface
* interface.
*/
class OdtGenerator : public librevenge::RVNGTextInterface
{
public:
OdtGenerator(OdfDocumentHandler *pHandler, const OdfStreamType streamType);
~OdtGenerator();
void setDocumentMetaData(const librevenge::RVNGPropertyList &propList);
void startDocument();
void endDocument();
void definePageStyle(const librevenge::RVNGPropertyList &);
void openPageSpan(const librevenge::RVNGPropertyList &propList);
void closePageSpan();
void defineSectionStyle(const librevenge::RVNGPropertyList &);
void openSection(const librevenge::RVNGPropertyList &propList);
void closeSection();
void openHeader(const librevenge::RVNGPropertyList &propList);
void closeHeader();
void openFooter(const librevenge::RVNGPropertyList &propList);
void closeFooter();
void defineParagraphStyle(const librevenge::RVNGPropertyList &);
void openParagraph(const librevenge::RVNGPropertyList &propList);
void closeParagraph();
void defineCharacterStyle(const librevenge::RVNGPropertyList &);
void openSpan(const librevenge::RVNGPropertyList &propList);
void closeSpan();
void insertTab();
void insertSpace();
void insertText(const librevenge::RVNGString &text);
void insertLineBreak();
void insertField(const librevenge::RVNGPropertyList &propList);
void defineOrderedListLevel(const librevenge::RVNGPropertyList &propList);
void defineUnorderedListLevel(const librevenge::RVNGPropertyList &propList);
void openOrderedListLevel(const librevenge::RVNGPropertyList &propList);
void openUnorderedListLevel(const librevenge::RVNGPropertyList &propList);
void closeOrderedListLevel();
void closeUnorderedListLevel();
void openListElement(const librevenge::RVNGPropertyList &propList);
void closeListElement();
void openFootnote(const librevenge::RVNGPropertyList &propList);
void closeFootnote();
void openEndnote(const librevenge::RVNGPropertyList &propList);
void closeEndnote();
void openComment(const librevenge::RVNGPropertyList &propList);
void closeComment();
void openTextBox(const librevenge::RVNGPropertyList &propList);
void closeTextBox();
void openTable(const librevenge::RVNGPropertyList &propList);
void openTableRow(const librevenge::RVNGPropertyList &propList);
void closeTableRow();
void openTableCell(const librevenge::RVNGPropertyList &propList);
void closeTableCell();
void insertCoveredTableCell(const librevenge::RVNGPropertyList &propList);
void closeTable();
void openFrame(const librevenge::RVNGPropertyList &propList);
void closeFrame();
void insertBinaryObject(const librevenge::RVNGPropertyList &propList);
void insertEquation(const librevenge::RVNGPropertyList &propList);
/** Registers a handler for embedded objects.
*
* @param[in] mimeType MIME type of the object
* @param[in] objectHandler a function that handles processing of
* the object's data and generating output
*/
void registerEmbeddedObjectHandler(const librevenge::RVNGString &mimeType, OdfEmbeddedObject objectHandler);
/** Registers a handler for embedded images.
*
* The handler converts the image to a format suitable for the used
* OdfDocumentHandler.
*
* @param[in] mimeType MIME type of the image
* @param[in] imageHandler a function that handles processing of
* the images's data and generating output
*/
void registerEmbeddedImageHandler(const librevenge::RVNGString &mimeType, OdfEmbeddedImage imageHandler);
private:
OdtGenerator(OdtGenerator const &);
OdtGenerator &operator=(OdtGenerator const &);
OdtGeneratorPrivate *mpImpl;
};
#endif
/* vim:set shiftwidth=4 softtabstop=4 noexpandtab: */
|
Correct a comment...
|
Correct a comment...
|
C++
|
mpl-2.0
|
Distrotech/libodfgen,Distrotech/libodfgen,Distrotech/libodfgen
|
5cb3dbd58a93f3c0c8d58e30821fe42db8fa5391
|
src/hello.cxx
|
src/hello.cxx
|
#include <hello/hello.h>
#include <iostream>
int main()
{
hello();
return 0;
}
|
#include <hello/hello.h>
#include <iostream>
int main()
{
hello();
return 0;
}
|
Indent hello.cxx
|
Indent hello.cxx
|
C++
|
bsd-2-clause
|
fujii/cmake-example,fujii/cmake-example
|
b1c9f494e61b3e43c94b182de0bbbf0dd5a66a87
|
include/construction/merge.hpp
|
include/construction/merge.hpp
|
/*******************************************************************************
* include/util/merge.hpp
*
* Copyright (C) 2017 Marvin Löbel <[email protected]>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#pragma once
#include <cassert>
#include <climits>
#include <omp.h>
#include "arrays/bit_vectors.hpp"
#include "util/common.hpp"
template<typename WordType>
void copy_bits(WordType* const dst, WordType const* const src,
uint64_t& dst_off_ref, uint64_t& src_off_ref, uint64_t const block_size) {
if (block_size == 0) return;
WordType constexpr BITS = (sizeof(WordType) * CHAR_BIT);
WordType constexpr MOD_MASK = BITS - 1;
WordType constexpr SHIFT = log2(MOD_MASK);
uint64_t dst_off = dst_off_ref;
uint64_t src_off = src_off_ref;
auto const dst_off_end = dst_off + block_size;
// NB: Check if source and target block are aligned the same way
// This is needed because the non-aligned code path would
// trigger undefined behavior in the aligned case.
if ((dst_off & MOD_MASK) == (src_off & MOD_MASK)) {
// Copy unaligned leading bits
{
auto& word = dst[dst_off >> SHIFT];
while ((dst_off & MOD_MASK) != 0 && dst_off != dst_off_end) {
bool const bit = bit_at<WordType>(src, src_off++);
word |= (WordType(bit) << (MOD_MASK - (dst_off++ & MOD_MASK)));
}
}
// Copy the the bulk in-between word-wise
{
auto const words = (dst_off_end - dst_off) >> SHIFT;
WordType* ds = dst + (dst_off >> SHIFT);
WordType const* sr = src + (src_off >> SHIFT);
WordType const* const ds_end = ds + words;
while (ds != ds_end) {
*ds++ = *sr++;
}
dst_off += words * BITS;
src_off += words * BITS;
}
// Copy unaligned trailing bits
{
auto& word = dst[dst_off >> SHIFT];
while (dst_off != dst_off_end) {
bool const bit = bit_at<WordType>(src, src_off++);
word |= (WordType(bit) << (MOD_MASK - (dst_off++ & MOD_MASK)));
}
}
} else {
// Copy unaligned leading bits
{
auto& word = dst[dst_off >> SHIFT];
while ((dst_off & MOD_MASK) != 0 && dst_off != dst_off_end) {
bool const bit = bit_at<WordType>(src, src_off++);
word |= (WordType(bit) << (MOD_MASK - (dst_off++ & MOD_MASK)));
}
}
// Copy the the bulk in-between word-wise
{
auto const words = (dst_off_end - dst_off) >> SHIFT;
WordType const src_shift_a = src_off & MOD_MASK;
WordType const src_shift_b = BITS - src_shift_a;
WordType* ds = dst + (dst_off >> SHIFT);
WordType const* sr = src + (src_off >> SHIFT);
WordType const* const ds_end = ds + words;
while (ds != ds_end) {
*ds++ = (*sr << src_shift_a) | (*(sr+1) >> src_shift_b);
sr++;
}
dst_off += words * BITS;
src_off += words * BITS;
}
// Copy unaligned trailing bits
{
auto& word = dst[dst_off >> SHIFT];
while (dst_off != dst_off_end) {
bool const bit = bit_at<WordType>(src, src_off++);
word |= (WordType(bit) << (MOD_MASK - (dst_off++ & MOD_MASK)));
}
}
}
dst_off_ref += block_size;
src_off_ref += block_size;
}
template<typename ContextType, typename Rho>
inline auto merge_bit_vectors(uint64_t size, uint64_t levels, uint64_t shards,
const std::vector<ContextType>& src_ctxs, const Rho& rho) {
assert(shards == src_ctxs.size());
// Allocate data structures centrally
struct MergeLevelCtx {
std::vector<uint64_t> read_offsets;
uint64_t offset_in_first_word;
uint64_t first_read_block;
};
struct MergeCtx {
uint64_t offset;
std::vector<MergeLevelCtx> levels;
};
auto ctxs = std::vector<MergeCtx>{shards, {
0,
std::vector<MergeLevelCtx> {
levels, {
std::vector<uint64_t>(shards),
0,
0,
}
},
}};
// Calculate bit offset per merge shard (thread)
for (size_t rank = 1; rank < shards; rank++) {
const size_t omp_rank = rank;
const size_t omp_size = shards;
const uint64_t offset = (omp_rank * (word_size(size) / omp_size)) +
std::min<uint64_t>(omp_rank, word_size(size) % omp_size);
ctxs[rank - 1].offset = offset * 64ull;
}
ctxs[shards - 1].offset = word_size(size) * 64ull;
//#pragma omp parallel for
for(size_t level = 0; level < levels; level++) {
const size_t br_size = 1ull << level;
size_t write_offset = 0; // bit offset in destination bv
size_t merge_shard = 0; // index of merge thread
for(size_t i = 0; i < br_size * shards; i++) {
const auto bit_i = i / shards;
const auto read_shard = i % shards;
auto read_offset =
[&level, &ctxs](auto merge_shard, auto read_shard) -> uint64_t& {
return ctxs[merge_shard].levels[level].read_offsets[read_shard];
};
auto block_size = src_ctxs[read_shard].hist(level, rho(level, bit_i));
write_offset += block_size;
read_offset(merge_shard + 1, read_shard) += block_size;
// If we passed the current right border, split up the block
if (write_offset > ctxs[merge_shard].offset) {
// Take back the last step
write_offset -= block_size;
read_offset(merge_shard + 1, read_shard) -= block_size;
uint64_t offset_in_first_word = 0;
do {
// Split up the block like this:
// [ left_block_size | right_block_size ]
// ^ ^ ^
// (write_offset) (ctxs[merge_shard].offset) (write_offset + block_size)
auto const left_block_size = ctxs[merge_shard].offset - write_offset;
write_offset += left_block_size;
read_offset(merge_shard + 1, read_shard) += left_block_size;
offset_in_first_word += left_block_size;
ctxs[merge_shard + 1].levels[level].offset_in_first_word =
offset_in_first_word;
ctxs[merge_shard + 1].levels[level].first_read_block = i;
if (merge_shard + 2 < shards) {
for(size_t s = 0; s < shards; s++) {
read_offset(merge_shard + 2, s) = read_offset(merge_shard + 1, s);
}
}
merge_shard++;
// Once we have calculated the offsets for all merge threads,
// break out of the whole nested loop
if (merge_shard + 1 == shards) {
goto triple_loop_exit;
}
// Iterate on remaining block, because one block might
// span multiple threads
block_size -= left_block_size;
} while ((write_offset + block_size) > ctxs[merge_shard].offset);
// Process remainder of block
write_offset += block_size;
read_offset(merge_shard + 1, read_shard) += block_size;
assert(write_offset <= ctxs[merge_shard].offset);
}
}
triple_loop_exit:; // we are done
}
auto r = bit_vectors(levels, size);
auto& _bv = r.raw_data();
#pragma omp parallel
//for(size_t omp_rank = 0; omp_rank < shards; omp_rank++)
{
assert(size_t(omp_get_num_threads()) == shards);
const size_t omp_rank = omp_get_thread_num();
const size_t merge_shard = omp_rank;
auto& ctx = ctxs[merge_shard];
const auto target_right = std::min(ctx.offset, size);
const auto target_left = std::min((merge_shard > 0 ?
ctxs[merge_shard - 1].offset : 0), target_right);
for (size_t level = 0; level < levels; level++) {
auto seq_i = ctx.levels[level].first_read_block;
uint64_t write_offset = target_left;
size_t init_offset = ctx.levels[level].offset_in_first_word;
while (write_offset < target_right) {
const auto i = seq_i / shards;
const auto read_shard = seq_i % shards;
seq_i++;
const auto& h = src_ctxs[read_shard];
const auto& local_bv = src_ctxs[read_shard].bv().raw_data()[level];
auto const block_size = std::min<uint64_t>(
target_right - write_offset,
h.hist(level, rho(level, i)) - init_offset
);
init_offset = 0; // TODO: remove this by doing a initial pass
auto& local_cursor = ctx.levels[level].read_offsets[read_shard];
copy_bits<uint64_t>(
_bv[level],
local_bv,
write_offset,
local_cursor,
block_size
);
}
}
}
return r;
}
/******************************************************************************/
|
/*******************************************************************************
* include/util/merge.hpp
*
* Copyright (C) 2017 Marvin Löbel <[email protected]>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#pragma once
#include <cassert>
#include <climits>
#include <omp.h>
#include "arrays/bit_vectors.hpp"
#include "util/common.hpp"
#include "util/macros.hpp"
template<typename WordType>
void copy_bits(WordType* const dst, WordType const* const src,
uint64_t& dst_off_ref, uint64_t& src_off_ref, uint64_t const block_size) {
if (block_size == 0) return;
WordType constexpr BITS = (sizeof(WordType) * CHAR_BIT);
WordType constexpr MOD_MASK = BITS - 1;
WordType constexpr SHIFT = log2(MOD_MASK);
uint64_t dst_off = dst_off_ref;
uint64_t src_off = src_off_ref;
auto const dst_off_end = dst_off + block_size;
// NB: Check if source and target block are aligned the same way
// This is needed because the non-aligned code path would
// trigger undefined behavior in the aligned case.
if ((dst_off & MOD_MASK) == (src_off & MOD_MASK)) {
// Copy unaligned leading bits
{
auto& word = dst[dst_off >> SHIFT];
while ((dst_off & MOD_MASK) != 0 && dst_off != dst_off_end) {
bool const bit = bit_at<WordType>(src, src_off++);
word |= (WordType(bit) << (MOD_MASK - (dst_off++ & MOD_MASK)));
}
}
// Copy the the bulk in-between word-wise
{
auto const words = (dst_off_end - dst_off) >> SHIFT;
WordType* ds = dst + (dst_off >> SHIFT);
WordType const* sr = src + (src_off >> SHIFT);
WordType const* const ds_end = ds + words;
while (ds != ds_end) {
*ds++ = *sr++;
}
dst_off += words * BITS;
src_off += words * BITS;
}
// Copy unaligned trailing bits
{
auto& word = dst[dst_off >> SHIFT];
while (dst_off != dst_off_end) {
bool const bit = bit_at<WordType>(src, src_off++);
word |= (WordType(bit) << (MOD_MASK - (dst_off++ & MOD_MASK)));
}
}
} else {
// Copy unaligned leading bits
{
auto& word = dst[dst_off >> SHIFT];
while ((dst_off & MOD_MASK) != 0 && dst_off != dst_off_end) {
bool const bit = bit_at<WordType>(src, src_off++);
word |= (WordType(bit) << (MOD_MASK - (dst_off++ & MOD_MASK)));
}
}
// Copy the the bulk in-between word-wise
{
auto const words = (dst_off_end - dst_off) >> SHIFT;
WordType const src_shift_a = src_off & MOD_MASK;
WordType const src_shift_b = BITS - src_shift_a;
WordType* ds = dst + (dst_off >> SHIFT);
WordType const* sr = src + (src_off >> SHIFT);
WordType const* const ds_end = ds + words;
while (ds != ds_end) {
*ds++ = (*sr << src_shift_a) | (*(sr+1) >> src_shift_b);
sr++;
}
dst_off += words * BITS;
src_off += words * BITS;
}
// Copy unaligned trailing bits
{
auto& word = dst[dst_off >> SHIFT];
while (dst_off != dst_off_end) {
bool const bit = bit_at<WordType>(src, src_off++);
word |= (WordType(bit) << (MOD_MASK - (dst_off++ & MOD_MASK)));
}
}
}
dst_off_ref += block_size;
src_off_ref += block_size;
}
template<typename ContextType, typename Rho>
inline auto merge_bit_vectors(uint64_t size,
uint64_t levels,
uint64_t shards,
const std::vector<ContextType>& src_ctxs,
const Rho& rho)
{
assert(shards == src_ctxs.size());
// Allocate data structures centrally
struct MergeLevelCtx {
std::vector<uint64_t> read_offsets;
uint64_t initial_offset;
uint64_t first_read_block;
};
struct MergeCtx {
uint64_t end_offset;
std::vector<MergeLevelCtx> levels;
};
auto ctxs = std::vector<MergeCtx>{shards, {
0,
std::vector<MergeLevelCtx> {
levels, {
std::vector<uint64_t>(shards),
0,
0,
}
},
}};
/*
Visualization of ctxs for levels = 2 and shards = 2:
┌──────────────┬───────────────────────┐
│ctxs: MergeCtx│ x shards │
│ ┌────────────┴───────────────────────┤
│ │end_offset: uint64_t │
│ ├─────────────────────┬──────────────┤
│ │levels: MergeLevelCtx│ x levels │
│ │ ┌───────────────────┴──────────────┤
│ │ │initial_offset: uint64_t │
│ │ ├──────────────────────────────────┤
│ │ │first_read_block: uint64_t │
│ │ ├──────────────────────┬───────────┤
│ │ │read_offsets: uint64_t│ x shards │
│ │ │ ┌────────────────────┴───────────┤
│ │ │ │ │
│ │ │ ╞════════════════════════════════╡
│ │ │ │ │
│ │ ╞═╧════════════════════════════════╡
│ │ │initial_offset: uint64_t │
│ │ ├──────────────────────────────────┤
│ │ │first_read_block: uint64_t │
│ │ ├──────────────────────┬───────────┤
│ │ │read_offsets: uint64_t│ x shards │
│ │ │ ┌────────────────────┴───────────┤
│ │ │ │ │
│ │ │ ╞════════════════════════════════╡
│ │ │ │ │
│ ╞═╧═╧════════════════════════════════╡
│ │end_offset: uint64_t │
│ ├─────────────────────┬──────────────┤
│ │levels: MergeLevelCtx│ x levels │
│ │ ┌───────────────────┴──────────────┤
│ │ │initial_offset: uint64_t │
│ │ ├──────────────────────────────────┤
│ │ │first_read_block: uint64_t │
│ │ ├──────────────────────┬───────────┤
│ │ │read_offsets: uint64_t│ x shards │
│ │ │ ┌────────────────────┴───────────┤
│ │ │ │ │
│ │ │ ╞════════════════════════════════╡
│ │ │ │ │
│ │ ╞═╧════════════════════════════════╡
│ │ │initial_offset: uint64_t │
│ │ ├──────────────────────────────────┤
│ │ │first_read_block: uint64_t │
│ │ ├──────────────────────┬───────────┤
│ │ │read_offsets: uint64_t│ x shards │
│ │ │ ┌────────────────────┴───────────┤
│ │ │ │ │
│ │ │ ╞════════════════════════════════╡
│ │ │ │ │
└─┴─┴─┴────────────────────────────────┘
*/
// Calculate end bit offset per merge shard (thread).
// It is an multiple of 64, to ensure no interference
// in writing bits to the left or right of it in parallel
for (size_t rank = 1; rank < shards; rank++) {
const size_t omp_rank = rank;
const size_t omp_size = shards;
const uint64_t offset = (omp_rank * (word_size(size) / omp_size)) +
std::min<uint64_t>(omp_rank, word_size(size) % omp_size);
ctxs[rank - 1].end_offset = offset * 64ull;
}
ctxs[shards - 1].end_offset = word_size(size) * 64ull;
//#pragma omp parallel for
for(size_t level = 0; level < levels; level++) {
// number of tree nodes on the current level
const size_t blocks = 1ull << level;
size_t write_offset = 0; // bit offset in destination bv
size_t merge_shard = 0; // index of merge thread
// iterate over all blocks of all shards on the current level
//
// this gradually assigns the bits of the
// blocks to each of the aviable merge shards of the current level:
//
// | read_shard | read_shard |
// +---------------+---------------+
// | block | block |
// | block | block | block | block | <- current level
// +----------+----------+---------+
// | m. shard | m. shard |m. shard |
//
for(size_t i = 0; i < blocks * shards; i++) {
// returns merge level context of merge_shard+1
auto nxt_lctx = [&level, &ctxs](auto merge_shard) -> MergeLevelCtx& {
return ctxs[merge_shard + 1].levels[level];
};
// which block (node on current level of tree)
const auto block = i / shards;
// which shard to read from
const auto read_shard = i % shards;
// map logical block index to
// actual block index (rho depends on WT vs WM)
const auto permuted_block = rho(level, block);
// block size == number of entries in the block on this level
auto block_size = src_ctxs[read_shard].hist(level, permuted_block);
// advance global write offset by the number of bits assigned for
// this block
write_offset += block_size;
// advance local read offset of next merge shard
// for the curent read shard
//
// this way, all merge shard start reading
// at different offsets from the read shards
nxt_lctx(merge_shard).read_offsets[read_shard] += block_size;
// If we passed the current right border, split up the block
if (write_offset > ctxs[merge_shard].end_offset) {
// Take back the last step
write_offset -= block_size;
nxt_lctx(merge_shard).read_offsets[read_shard] -= block_size;
uint64_t initial_offset = 0;
do {
// Split up the block like this:
// [ left_block_size | right_block_size ]
// ^ ^ ^
// (write_offset) | |
// (ctxs[merge_shard].end_offset) |
// (write_offset + block_size)
//
// this loop iterates multiple times, to ensure right_block_size
// did not also overlap the next end_offset
auto const left_block_size
= ctxs[merge_shard].end_offset - write_offset;
// advance global and local read offsets to end exactly at
// end_offset
write_offset += left_block_size;
nxt_lctx(merge_shard).read_offsets[read_shard] += left_block_size;
initial_offset += left_block_size;
// from which offset in which block to start reading
nxt_lctx(merge_shard).initial_offset = initial_offset;
nxt_lctx(merge_shard).first_read_block = i;
// if there is a merge_shard to the right
// of the next merge shard, intialize
// its local read offsets with those of the next shard
if (merge_shard + 2 < shards) {
for(size_t s = 0; s < shards; s++) {
nxt_lctx(merge_shard + 1).read_offsets[s]
= nxt_lctx(merge_shard).read_offsets[s];
}
}
merge_shard++;
// Once we have calculated the offsets for all merge threads,
// break out of the whole nested loop
if (merge_shard + 1 == shards) {
goto triple_loop_exit;
}
// Iterate on remaining block, because one block might
// span multiple threads
block_size -= left_block_size;
} while ((write_offset + block_size) > ctxs[merge_shard].end_offset);
// Process remainder of block
write_offset += block_size;
nxt_lctx(merge_shard).read_offsets[read_shard] += block_size;
assert(write_offset <= ctxs[merge_shard].end_offset);
}
}
triple_loop_exit:; // we are done
}
auto r = bit_vectors(levels, size);
auto& _bv = r;
#pragma omp parallel
//for(size_t omp_rank = 0; omp_rank < shards; omp_rank++)
{
assert(size_t(omp_get_num_threads()) == shards);
const size_t omp_rank = omp_get_thread_num();
const size_t merge_shard = omp_rank;
auto& ctx = ctxs[merge_shard];
const auto target_right = std::min(ctx.end_offset, size);
const auto target_left = std::min((merge_shard > 0 ?
ctxs[merge_shard - 1].end_offset : 0), target_right);
for (size_t level = 0; level < levels; level++) {
auto i = ctx.levels[level].first_read_block;
uint64_t write_offset = target_left;
auto copy_next_block = [&](size_t const initial_offset) {
const auto block = i / shards;
const auto read_shard = i % shards;
i++;
const auto& local_bv = src_ctxs[read_shard].bv()[level];
const auto& h = src_ctxs[read_shard];
uint64_t block_size = h.hist(level, rho(level, block)) - initial_offset;
uint64_t distance_to_end = target_right - write_offset;
uint64_t copy_size;
if (PWM_LIKELY(block_size <= distance_to_end)) {
copy_size = block_size;
} else {
copy_size = distance_to_end;
}
auto& local_cursor = ctx.levels[level].read_offsets[read_shard];
copy_bits<uint64_t>(
_bv[level].data(),
local_bv.data(),
write_offset,
local_cursor,
copy_size
);
};
if (write_offset < target_right) {
// the first block might start somewhere in the middle
copy_next_block(ctx.levels[level].initial_offset);
}
while (write_offset < target_right) {
// other blocks start at 0
copy_next_block(0);
}
}
}
return r;
}
/******************************************************************************/
|
Refactor & annotate merge.hpp
|
Refactor & annotate merge.hpp
|
C++
|
bsd-2-clause
|
kurpicz/pwm,kurpicz/pwm,kurpicz/pwm
|
d6b9fa1a193e6ebcb5ac78c9ba8881ab87e60eac
|
include/tudocomp/util/View.hpp
|
include/tudocomp/util/View.hpp
|
#pragma once
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <fstream>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
#include <iomanip>
#include <cstring>
#include <glog/logging.h>
#include <tudocomp/def.hpp>
namespace tdc {
/// A view into a slice of memory.
///
/// This is an abstraction around a `const uint8_t*` pointer and a `size_t` size,
/// and represents N bytes of memory starting at that pointer.
///
/// Creating/Copying/Modifying a View will not copy any of the data it points at.
class View {
const uliteral_t* m_data;
size_t m_size;
inline void bound_check(size_t pos) const {
if (pos >= m_size) {
std::stringstream ss;
ss << "accessing view with bounds [0, ";
ss << m_size;
ss << ") at out-of-bounds index ";
ss << pos;
throw std::out_of_range(ss.str());
}
}
inline void debug_bound_check(size_t pos) const {
#ifdef DEBUG
bound_check(pos);
#endif
}
public:
// Type members
using value_type = uliteral_t;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using const_reference = const value_type&;
using const_pointer = const value_type*;
using const_iterator = const_pointer;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
// static value members
static const size_type npos = -1;
// Constructors
/// Construct a empty View
inline View(): View("") {}
/// Construct a View pointing at `len` elements starting from `data`
inline View(const uint8_t* data, size_t len): m_data(data), m_size(len) {}
/// Construct a View as a copy of `other`
inline View(const View& other): View(other.m_data, other.m_size) {}
/// Construct a View pointing at the contents of a vector
inline View(const std::vector<uint8_t>& other):
View(other.data(), other.size()) {}
/// Construct a View pointing at the contents of a string
inline View(const std::string& other):
View((const uint8_t*) other.data(), other.size()) {}
/// Construct a View equal to the (offset)-th suffix of other
inline View(const View& other, size_t offset):
View((const uint8_t*) other.data()+offset, other.size()-offset) { DCHECK_LE(offset, other.size()); }
/// Construct a View pointing at a C-style null terminated string.
///
/// Can be used to construct from a string literal
inline View(const char* other):
View((const uint8_t*) other, strlen(other)) {}
/// Construct a View pointing at `len` elements starting from `data`
inline View(const char* data, size_t len):
View((const uint8_t*) data, len) {}
// Conversion
/// Construct a string with the contents of this View
inline operator std::string() const {
return std::string(cbegin(), cend());
}
/// Construct a vector with the contents of this View
inline operator std::vector<uint8_t>() const {
return std::vector<uint8_t>(cbegin(), cend());
}
// Element access
/// Access the element at `pos`
///
/// This method is always bounds checked
inline const_reference at(size_type pos) const {
bound_check(pos);
return m_data[pos];
}
/// Access the element at `pos`
///
/// This method is bounds checked in debug builds
inline const_reference operator[](size_type pos) const {
debug_bound_check(pos);
return m_data[pos];
}
/// Access the first element
inline const_reference front() const {
return (*this)[0];
}
/// Access the last element
inline const_reference back() const {
return (*this)[m_size - 1];
}
/// The backing memory location
inline const uint8_t* data() const {
return &front();
}
// Iterators
/// Begin of iterator
inline const_iterator begin() const {
return &(*this)[0];
}
/// Begin of const iterator
inline const_iterator cbegin() const {
return begin();
}
/// End of iterator
inline const_iterator end() const {
return m_data + m_size;
}
/// End of const iterator
inline const_iterator cend() const {
return end();
}
/// Begin of reverse iterator
inline const_reverse_iterator rbegin() const {
return std::reverse_iterator<const_iterator>(end());
}
/// Begin of const reverse iterator
inline const_reverse_iterator crbegin() const {
return rbegin();
}
/// End of reverse iterator
inline const_reverse_iterator rend() const {
return std::reverse_iterator<const_iterator>(begin());
}
/// End of const reverse iterator
inline const_reverse_iterator crend() const {
return rend();
}
// Capacity
/// Returns `true` if empty
inline bool empty() const {
return m_size == 0;
}
/// Returns size of the View
inline size_type size() const {
return m_size;
}
/// Returns max size of the View. Always the same as `size()`
inline size_type max_size() const {
return size();
}
// Slicing
/// Construct a new View that is a sub view into the current one.
///
/// The returned view will be a "from-to" slice,
/// and cover the bytes starting at `from` and ending at `to`.
///
/// Passing `npos` to `to` will create a slice until the end of the View
///
/// # Example
///
/// `View("abcd").slice(1, 3) == View("bc")`
inline View slice(size_type from, size_type to = npos) const {
if (to == npos) {
to = m_size;
}
DCHECK_LE(from, to);
DCHECK_LE(from, size());
DCHECK_LE(to, size());
return View(m_data + from, to - from);
}
/// Construct a new View that is a sub view into the current one.
///
/// The returned view will be a "position-length" slice,
/// and cover the bytes starting at `pos` and ending at `pos + len`.
///
/// Passing `npos` to `len` will create a slice until the end of the View
///
/// This method covers the same basic operation as `slice()`, but
/// mirrors the semantic of `std::string::substr`.
///
/// # Example
///
/// `View("abcd").substr(1, 2) == View("bc")`
inline View substr(size_type pos, size_type len = npos) const {
if (len == npos) {
len = m_size - pos;
}
return slice(pos, pos + len);
}
// Modifiers
/// Swap two Views
inline void swap(View& other) {
using std::swap;
swap(m_data, other.m_data);
swap(m_size, other.m_size);
}
/// Swap two Views
inline friend void swap(View& a, View& b) {
a.swap(b);
}
/// Sets the size to 0
inline void clear() {
m_size = 0;
}
/// Removes the first `n` elements from the View
inline void remove_prefix(size_type n) {
*this = slice(n);
}
/// Removes the last `n` elements from the View
inline void remove_suffix(size_type n) {
*this = slice(0, m_size - n);
}
// string predicates
/// Returns `true` if the View starts with `c`
inline bool starts_with(uint8_t c) const {
return !empty() && (front() == c);
}
/// Returns `true` if the View starts with `c`
inline bool starts_with(char c) const {
return starts_with(uint8_t(c));
}
/// Returns `true` if the View starts with `x`
inline bool starts_with(const View& x) const;
/// Returns `true` if the View ends with `c`
inline bool ends_with(uint8_t c) const {
return !empty() && (back() == c);
}
/// Returns `true` if the View ends with `c`
inline bool ends_with(char c) const {
return ends_with(uint8_t(c));
}
/// Returns `true` if the View ends with `x`
inline bool ends_with(const View& x) const;
};
inline bool operator==(const View& lhs, const View& rhs) {
// TODO: memcmp!
return (lhs.size() == rhs.size())
&& (std::memcmp(lhs.data(), rhs.data(), lhs.size()) == 0);
}
inline bool operator!=(const View& lhs, const View& rhs) {
return !(lhs == rhs);
}
inline bool operator<(const View& lhs, const View& rhs) {
return std::lexicographical_compare(lhs.cbegin(), lhs.cend(),
rhs.cbegin(), rhs.cend());
}
inline bool operator>(const View& lhs, const View& rhs) {
return std::lexicographical_compare(lhs.cbegin(), lhs.cend(),
rhs.cbegin(), rhs.cend(),
[](const uint8_t& l, const uint8_t& r){
return l > r;
});
}
inline bool operator<=(const View& lhs, const View& rhs) {
return !(lhs > rhs);
}
inline bool operator>=(const View& lhs, const View& rhs) {
return !(lhs < rhs);
}
inline std::ostream& operator<<(std::ostream& os, const View& v) {
os.write((const char*) v.data(), v.size());
return os;
}
inline bool View::starts_with(const View& x) const {
return (x.size() <= size())
&& (slice(0, x.size()) == x);
}
inline bool View::ends_with(const View& x) const {
return (x.size() <= size())
&& (slice(size() - x.size()) == x);
}
inline View operator "" _v(const char* str, size_t n)
{
return View(str, n);
}
using string_ref = View;
}
|
#pragma once
#include <algorithm>
#include <cmath>
#include <cstddef>
#include <fstream>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <type_traits>
#include <utility>
#include <iomanip>
#include <cstring>
#include <glog/logging.h>
#include <tudocomp/def.hpp>
namespace tdc {
/// A view into a slice of memory.
///
/// This is an abstraction around a `const uint8_t*` pointer and a `size_t` size,
/// and represents N bytes of memory starting at that pointer.
///
/// Creating/Copying/Modifying a View will not copy any of the data it points at.
class View {
const uliteral_t* m_data;
size_t m_size;
inline void bound_check(size_t pos) const {
if (pos >= m_size) {
std::stringstream ss;
ss << "accessing view with bounds [0, ";
ss << m_size;
ss << ") at out-of-bounds index ";
ss << pos;
throw std::out_of_range(ss.str());
}
}
inline void debug_bound_check(size_t pos) const {
#ifdef DEBUG
bound_check(pos);
#endif
}
public:
// Type members
using value_type = uliteral_t;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using const_reference = const value_type&;
using const_pointer = const value_type*;
using const_iterator = const_pointer;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
// static value members
static const size_type npos = -1;
// Constructors
/// Construct a empty View
inline View(): View("") {}
/// Construct a View pointing at `len` elements starting from `data`
inline View(const uint8_t* data, size_t len): m_data(data), m_size(len) {}
/// Construct a View as a copy of `other`
inline View(const View& other): View(other.m_data, other.m_size) {}
/// Construct a View pointing at the contents of a vector
inline View(const std::vector<uint8_t>& other):
View(other.data(), other.size()) {}
/// Construct a View pointing at the contents of a string
inline View(const std::string& other):
View((const uint8_t*) other.data(), other.size()) {}
/// Construct a View equal to the (offset)-th suffix of other
inline View(const View& other, size_t offset):
View((const uint8_t*) other.data()+offset, other.size()-offset) { DCHECK_LE(offset, other.size()); }
/// Construct a View pointing at a C-style null terminated string.
///
/// Can be used to construct from a string literal
inline View(const char* other):
View((const uint8_t*) other, strlen(other)) {}
/// Construct a View pointing at `len` elements starting from `data`
inline View(const char* data, size_t len):
View((const uint8_t*) data, len) {}
// Conversion
/// Construct a string with the contents of this View
inline operator std::string() const {
return std::string(cbegin(), cend());
}
/// Construct a vector with the contents of this View
inline operator std::vector<uint8_t>() const {
return std::vector<uint8_t>(cbegin(), cend());
}
// Element access
/// Access the element at `pos`
///
/// This method is always bounds checked
inline const_reference at(size_type pos) const {
bound_check(pos);
return m_data[pos];
}
/// Access the element at `pos`
///
/// This method is bounds checked in debug builds
inline const_reference operator[](size_type pos) const {
debug_bound_check(pos);
return m_data[pos];
}
/// Access the first element
inline const_reference front() const {
return (*this)[0];
}
/// Access the last element
inline const_reference back() const {
return (*this)[m_size - 1];
}
/// The backing memory location
inline const uint8_t* data() const {
return &front();
}
// Iterators
/// Begin of iterator
inline const_iterator begin() const {
return m_data;
}
/// Begin of const iterator
inline const_iterator cbegin() const {
return begin();
}
/// End of iterator
inline const_iterator end() const {
return m_data + m_size;
}
/// End of const iterator
inline const_iterator cend() const {
return end();
}
/// Begin of reverse iterator
inline const_reverse_iterator rbegin() const {
return std::reverse_iterator<const_iterator>(end());
}
/// Begin of const reverse iterator
inline const_reverse_iterator crbegin() const {
return rbegin();
}
/// End of reverse iterator
inline const_reverse_iterator rend() const {
return std::reverse_iterator<const_iterator>(begin());
}
/// End of const reverse iterator
inline const_reverse_iterator crend() const {
return rend();
}
// Capacity
/// Returns `true` if empty
inline bool empty() const {
return m_size == 0;
}
/// Returns size of the View
inline size_type size() const {
return m_size;
}
/// Returns max size of the View. Always the same as `size()`
inline size_type max_size() const {
return size();
}
// Slicing
/// Construct a new View that is a sub view into the current one.
///
/// The returned view will be a "from-to" slice,
/// and cover the bytes starting at `from` and ending at `to`.
///
/// Passing `npos` to `to` will create a slice until the end of the View
///
/// # Example
///
/// `View("abcd").slice(1, 3) == View("bc")`
inline View slice(size_type from, size_type to = npos) const {
if (to == npos) {
to = m_size;
}
DCHECK_LE(from, to);
DCHECK_LE(from, size());
DCHECK_LE(to, size());
return View(m_data + from, to - from);
}
/// Construct a new View that is a sub view into the current one.
///
/// The returned view will be a "position-length" slice,
/// and cover the bytes starting at `pos` and ending at `pos + len`.
///
/// Passing `npos` to `len` will create a slice until the end of the View
///
/// This method covers the same basic operation as `slice()`, but
/// mirrors the semantic of `std::string::substr`.
///
/// # Example
///
/// `View("abcd").substr(1, 2) == View("bc")`
inline View substr(size_type pos, size_type len = npos) const {
if (len == npos) {
len = m_size - pos;
}
return slice(pos, pos + len);
}
// Modifiers
/// Swap two Views
inline void swap(View& other) {
using std::swap;
swap(m_data, other.m_data);
swap(m_size, other.m_size);
}
/// Swap two Views
inline friend void swap(View& a, View& b) {
a.swap(b);
}
/// Sets the size to 0
inline void clear() {
m_size = 0;
}
/// Removes the first `n` elements from the View
inline void remove_prefix(size_type n) {
*this = slice(n);
}
/// Removes the last `n` elements from the View
inline void remove_suffix(size_type n) {
*this = slice(0, m_size - n);
}
// string predicates
/// Returns `true` if the View starts with `c`
inline bool starts_with(uint8_t c) const {
return !empty() && (front() == c);
}
/// Returns `true` if the View starts with `c`
inline bool starts_with(char c) const {
return starts_with(uint8_t(c));
}
/// Returns `true` if the View starts with `x`
inline bool starts_with(const View& x) const;
/// Returns `true` if the View ends with `c`
inline bool ends_with(uint8_t c) const {
return !empty() && (back() == c);
}
/// Returns `true` if the View ends with `c`
inline bool ends_with(char c) const {
return ends_with(uint8_t(c));
}
/// Returns `true` if the View ends with `x`
inline bool ends_with(const View& x) const;
};
inline bool operator==(const View& lhs, const View& rhs) {
// TODO: memcmp!
return (lhs.size() == rhs.size())
&& (std::memcmp(lhs.data(), rhs.data(), lhs.size()) == 0);
}
inline bool operator!=(const View& lhs, const View& rhs) {
return !(lhs == rhs);
}
inline bool operator<(const View& lhs, const View& rhs) {
return std::lexicographical_compare(lhs.cbegin(), lhs.cend(),
rhs.cbegin(), rhs.cend());
}
inline bool operator>(const View& lhs, const View& rhs) {
return std::lexicographical_compare(lhs.cbegin(), lhs.cend(),
rhs.cbegin(), rhs.cend(),
[](const uint8_t& l, const uint8_t& r){
return l > r;
});
}
inline bool operator<=(const View& lhs, const View& rhs) {
return !(lhs > rhs);
}
inline bool operator>=(const View& lhs, const View& rhs) {
return !(lhs < rhs);
}
inline std::ostream& operator<<(std::ostream& os, const View& v) {
os.write((const char*) v.data(), v.size());
return os;
}
inline bool View::starts_with(const View& x) const {
return (x.size() <= size())
&& (slice(0, x.size()) == x);
}
inline bool View::ends_with(const View& x) const {
return (x.size() <= size())
&& (slice(size() - x.size()) == x);
}
inline View operator "" _v(const char* str, size_t n)
{
return View(str, n);
}
using string_ref = View;
}
|
Add missing fix to View.hpp
|
Add missing fix to View.hpp
|
C++
|
apache-2.0
|
tudocomp/tudocomp,tudocomp/tudocomp,tudocomp/tudocomp,tudocomp/tudocomp,tudocomp/tudocomp
|
59e2f552ca2920defb76ba070a8abc8013d3c029
|
realm/wrappers/realm.cpp
|
realm/wrappers/realm.cpp
|
#include <iostream>
#include <realm.hpp>
#include <realm/table.hpp>
#include <realm/commit_log.hpp>
#include <realm/lang_bind_helper.hpp>
#include "object-store/shared_realm.hpp"
enum class RealmErrorType {
unknown = 0,
system = 1
};
struct RealmError {
RealmErrorType type;
std::string message;
};
static
void convert_exception_to_error(RealmError* error)
{
try {
throw;
}
catch (const std::exception& ex) {
error->type = RealmErrorType::system;
error->message = ex.what();
}
catch (...) {
error->type = RealmErrorType::unknown;
error->message = "Unknown exception thrown";
}
}
template <class T>
struct Default {
static T default_value() {
return T{};
}
};
template <>
struct Default<void> {
static void default_value() {}
};
template <class F>
auto handle_errors(RealmError** out_error, F&& func) -> decltype(func())
{
using RetVal = decltype(func());
try {
return func();
}
catch (...) {
*out_error = new RealmError;
convert_exception_to_error(*out_error);
return Default<RetVal>::default_value();
}
}
extern "C" {
using namespace realm;
void realm_error_destroy(RealmError* error)
{
delete error;
}
void realm_error_get_message(const RealmError* error, char const** out_message, size_t* out_message_size)
{
*out_message = error->message.c_str();
*out_message_size = error->message.size();
}
RealmErrorType realm_error_get_type(const RealmError* error)
{
return error->type;
}
Schema* realm_schema_new()
{
return new Schema;
}
ObjectSchema* realm_object_schema_new(const char* name)
{
auto p = new ObjectSchema;
p->name = name;
return p;
}
void realm_object_schema_add_property(ObjectSchema* cls, const char* name, DataType type, const char* object_type,
bool is_primary, bool is_indexed, bool is_nullable)
{
Property p;
p.name = name;
p.type = static_cast<PropertyType>(type);
p.object_type = object_type ? std::string(object_type) : std::string();
p.is_primary = is_primary;
p.is_indexed = is_indexed;
p.is_nullable = is_nullable;
cls->properties.push_back(std::move(p));
}
void realm_schema_add_class(Schema* schema, const char* name, ObjectSchema* cls)
{
(*schema)[name] = *cls;
}
SharedRealm* realm_open(RealmError** err, Schema* schema, const char* path, bool read_only, SharedGroup::DurabilityLevel durability,
const char* encryption_key)
{
Realm::Config config;
config.path = path;
config.read_only = read_only;
config.in_memory = durability != SharedGroup::durability_Full;
config.encryption_key = encryption_key;
config.schema.reset(schema);
return new SharedRealm{Realm::get_shared_realm(config)};
}
void realm_destroy(SharedRealm* realm)
{
delete realm;
}
bool realm_has_table(SharedRealm* realm, const char* name)
{
Group* g = (*realm)->read_group();
return g->has_table(name);
}
void realm_begin_transaction(RealmError** err, SharedRealm* realm)
{
handle_errors(err, [&]() {
(*realm)->begin_transaction();
});
}
void realm_commit_transaction(RealmError** err, SharedRealm* realm)
{
handle_errors(err, [&]() {
(*realm)->commit_transaction();
});
}
void realm_cancel_transaction(RealmError** err, SharedRealm* realm)
{
handle_errors(err, [&]() {
(*realm)->cancel_transaction();
});
}
bool realm_is_in_transaction(SharedRealm* realm)
{
return (*realm)->is_in_transaction();
}
bool realm_refresh(SharedRealm* realm)
{
return (*realm)->refresh();
}
void realm_shared_group_promote_to_write(RealmError** err, SharedGroup* sg, ClientHistory* hist)
{
handle_errors(err, [&]() {
LangBindHelper::promote_to_write(*sg, *hist);
});
}
SharedGroup::version_type realm_shared_group_commit(RealmError** err, SharedGroup* sg)
{
return handle_errors(err, [&]() {
return sg->commit();
});
}
void realm_shared_group_commit_and_continue_as_read(RealmError** err,
SharedGroup* sg)
{
LangBindHelper::commit_and_continue_as_read(*sg);
}
void realm_shared_group_rollback(SharedGroup* sg)
{
sg->rollback();
}
void realm_shared_group_rollback_and_continue_as_read(RealmError** err, SharedGroup* sg, ClientHistory* hist)
{
handle_errors(err, [&]() {
LangBindHelper::rollback_and_continue_as_read(*sg, *hist);
});
}
void realm_table_retain(const Table* table)
{
LangBindHelper::bind_table_ptr(table);
}
void realm_table_release(const Table* table)
{
LangBindHelper::unbind_table_ptr(table);
}
const Table* realm_get_table(RealmError** err, SharedGroup* sg, const char* name)
{
using sgf = _impl::SharedGroupFriend;
return handle_errors(err, [&]() {
auto& group = sgf::get_group(*sg);
return LangBindHelper::get_table(group, name);
});
}
Table* realm_get_table_mut(RealmError** err, SharedGroup* sg, const char* name)
{
using sgf = _impl::SharedGroupFriend;
return handle_errors(err, [&]() {
auto& group = sgf::get_group(*sg);
return LangBindHelper::get_table(group, name);
});
}
Table* realm_add_table(RealmError** err, SharedGroup* sg, const char* name)
{
using sgf = _impl::SharedGroupFriend;
return handle_errors(err, [&]() {
auto& group = sgf::get_group(*sg);
return LangBindHelper::add_table(group, name);
});
}
size_t realm_table_add_column(RealmError** err, Table* table, DataType type, const char* name, bool nullable)
{
return handle_errors(err, [&]() {
return table->add_column(type, name, nullable);
});
}
size_t realm_table_add_empty_row(RealmError** err, Table* table)
{
return handle_errors(err, [&]() {
return table->add_empty_row();
});
}
int64_t realm_table_get_int(const Table* table, size_t col_ndx, size_t row_ndx)
{
return table->get_int(col_ndx, row_ndx);
}
void realm_table_set_int(RealmError** err, Table* table, size_t col_ndx, size_t row_ndx, int64_t value)
{
return handle_errors(err, [&]() {
table->set_int(col_ndx, row_ndx, value);
});
}
void realm_row_destroy(Table::RowExpr* expr) {
delete expr;
}
int64_t realm_row_get_int(const Table::RowExpr* expr, size_t col_ndx) {
return expr->get_int(col_ndx);
}
}
|
#include <iostream>
#include <realm.hpp>
#include <realm/table.hpp>
#include <realm/commit_log.hpp>
#include <realm/lang_bind_helper.hpp>
#include "object-store/shared_realm.hpp"
#include "object-store/schema.hpp"
enum class RealmErrorType {
unknown = 0,
system = 1
};
struct RealmError {
RealmErrorType type;
std::string message;
};
static
void convert_exception_to_error(RealmError* error)
{
try {
throw;
}
catch (const std::exception& ex) {
error->type = RealmErrorType::system;
error->message = ex.what();
}
catch (...) {
error->type = RealmErrorType::unknown;
error->message = "Unknown exception thrown";
}
}
template <class T>
struct Default {
static T default_value() {
return T{};
}
};
template <>
struct Default<void> {
static void default_value() {}
};
template <class F>
auto handle_errors(RealmError** out_error, F&& func) -> decltype(func())
{
using RetVal = decltype(func());
try {
return func();
}
catch (...) {
*out_error = new RealmError;
convert_exception_to_error(*out_error);
return Default<RetVal>::default_value();
}
}
extern "C" {
using namespace realm;
void realm_error_destroy(RealmError* error)
{
delete error;
}
void realm_error_get_message(const RealmError* error, char const** out_message, size_t* out_message_size)
{
*out_message = error->message.c_str();
*out_message_size = error->message.size();
}
RealmErrorType realm_error_get_type(const RealmError* error)
{
return error->type;
}
std::vector<ObjectSchema>* realm_new_object_schemas()
{
return new std::vector<ObjectSchema>();
}
void realm_object_schemas_add_class(std::vector<ObjectSchema>* object_schemas, ObjectSchema* cls)
{
object_schemas->push_back(*cls);
}
Schema* realm_schema_new(std::vector<ObjectSchema>* object_schemas)
{
return new Schema(*object_schemas);
}
ObjectSchema* realm_object_schema_new(const char* name)
{
auto p = new ObjectSchema;
p->name = name;
return p;
}
void realm_object_schema_add_property(ObjectSchema* cls, const char* name, DataType type, const char* object_type,
bool is_primary, bool is_indexed, bool is_nullable)
{
Property p;
p.name = name;
p.type = static_cast<PropertyType>(type);
p.object_type = object_type ? std::string(object_type) : std::string();
p.is_primary = is_primary;
p.is_indexed = is_indexed;
p.is_nullable = is_nullable;
cls->properties.push_back(std::move(p));
}
SharedRealm* realm_open(RealmError** err, Schema* schema, const char* path, bool read_only, SharedGroup::DurabilityLevel durability,
const char* encryption_key)
{
Realm::Config config;
config.path = path;
config.read_only = read_only;
config.in_memory = durability != SharedGroup::durability_Full;
//config.encryption_key = encryption_key;
config.encryption_key = std::vector<char>(&encryption_key[0], &encryption_key[strlen(encryption_key)]);
config.schema.reset(schema);
return new SharedRealm{Realm::get_shared_realm(config)};
}
void realm_destroy(SharedRealm* realm)
{
delete realm;
}
bool realm_has_table(SharedRealm* realm, const char* name)
{
Group* g = (*realm)->read_group();
return g->has_table(name);
}
void realm_begin_transaction(RealmError** err, SharedRealm* realm)
{
handle_errors(err, [&]() {
(*realm)->begin_transaction();
});
}
void realm_commit_transaction(RealmError** err, SharedRealm* realm)
{
handle_errors(err, [&]() {
(*realm)->commit_transaction();
});
}
void realm_cancel_transaction(RealmError** err, SharedRealm* realm)
{
handle_errors(err, [&]() {
(*realm)->cancel_transaction();
});
}
bool realm_is_in_transaction(SharedRealm* realm)
{
return (*realm)->is_in_transaction();
}
bool realm_refresh(SharedRealm* realm)
{
return (*realm)->refresh();
}
void realm_shared_group_promote_to_write(RealmError** err, SharedGroup* sg, ClientHistory* hist)
{
handle_errors(err, [&]() {
LangBindHelper::promote_to_write(*sg, *hist);
});
}
SharedGroup::version_type realm_shared_group_commit(RealmError** err, SharedGroup* sg)
{
return handle_errors(err, [&]() {
return sg->commit();
});
}
void realm_shared_group_commit_and_continue_as_read(RealmError** err,
SharedGroup* sg)
{
LangBindHelper::commit_and_continue_as_read(*sg);
}
void realm_shared_group_rollback(SharedGroup* sg)
{
sg->rollback();
}
void realm_shared_group_rollback_and_continue_as_read(RealmError** err, SharedGroup* sg, ClientHistory* hist)
{
handle_errors(err, [&]() {
LangBindHelper::rollback_and_continue_as_read(*sg, *hist);
});
}
void realm_table_retain(const Table* table)
{
LangBindHelper::bind_table_ptr(table);
}
void realm_table_release(const Table* table)
{
LangBindHelper::unbind_table_ptr(table);
}
const Table* realm_get_table(RealmError** err, SharedGroup* sg, const char* name)
{
using sgf = _impl::SharedGroupFriend;
return handle_errors(err, [&]() {
auto& group = sgf::get_group(*sg);
return LangBindHelper::get_table(group, name);
});
}
Table* realm_get_table_mut(RealmError** err, SharedGroup* sg, const char* name)
{
using sgf = _impl::SharedGroupFriend;
return handle_errors(err, [&]() {
auto& group = sgf::get_group(*sg);
return LangBindHelper::get_table(group, name);
});
}
Table* realm_add_table(RealmError** err, SharedGroup* sg, const char* name)
{
using sgf = _impl::SharedGroupFriend;
return handle_errors(err, [&]() {
auto& group = sgf::get_group(*sg);
return LangBindHelper::add_table(group, name);
});
}
size_t realm_table_add_column(RealmError** err, Table* table, DataType type, const char* name, bool nullable)
{
return handle_errors(err, [&]() {
return table->add_column(type, name, nullable);
});
}
size_t realm_table_add_empty_row(RealmError** err, Table* table)
{
return handle_errors(err, [&]() {
return table->add_empty_row();
});
}
int64_t realm_table_get_int(const Table* table, size_t col_ndx, size_t row_ndx)
{
return table->get_int(col_ndx, row_ndx);
}
void realm_table_set_int(RealmError** err, Table* table, size_t col_ndx, size_t row_ndx, int64_t value)
{
return handle_errors(err, [&]() {
table->set_int(col_ndx, row_ndx, value);
});
}
void realm_row_destroy(Table::RowExpr* expr) {
delete expr;
}
int64_t realm_row_get_int(const Table::RowExpr* expr, size_t col_ndx) {
return expr->get_int(col_ndx);
}
}
|
Make schema initialization rely on a vector of ObjectSchema's
|
Make schema initialization rely on a vector of ObjectSchema's
|
C++
|
apache-2.0
|
Shaddix/realm-dotnet,Shaddix/realm-dotnet,realm/realm-dotnet,realm/realm-dotnet,Shaddix/realm-dotnet,realm/realm-dotnet,Shaddix/realm-dotnet
|
e22c7437f90e2f9c82ec6612533d9d0ae1b2a896
|
src/ansi_color.hh
|
src/ansi_color.hh
|
/*
* Copyright (C) 2017 deipi.com LLC and contributors. All rights reserved.
*
* 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 <string> // for string
#include <stdlib.h> // for getenv
#include "static_str.hh"
template <int N, int rem, char... a>
struct explode : explode<N + 1, rem / 10, ('0' + rem % 10), a...> { };
template <int N, char... a>
struct explode<N, 0, a...> {
constexpr static const char value[N + 1]{a..., 0};
};
template <unsigned num>
struct to_string : explode<0, num> { };
template <>
struct to_string<0> : explode<1, 0, '0'> { };
enum class Coloring : uint8_t {
TrueColor,
Palette,
Standard256,
Standard16,
None,
};
// Ansi colors:
template <uint8_t red, uint8_t green, uint8_t blue, bool bold = false>
class ansi_color {
static constexpr auto esc = static_str::literal("\033[");
static constexpr auto trueColor() {
return (
esc +
to_string<bold>::value +
";38;2;" +
to_string<red>::value + ";" +
to_string<green>::value + ";" +
to_string<blue>::value +
"m"
);
}
static constexpr auto standard256() {
constexpr uint8_t color = (red == green && green == blue) ? (
red < 8 ? 16 :
red > 248 ? 231 :
232 + static_cast<uint8_t>((((red - 8.0f) / 247.0f) * 24.0f) + 0.5f)
) : (
16 +
(static_cast<int>(red / 255.0f * 5.0f + 0.5f) * 36) +
(static_cast<int>(green / 255.0f * 5.0f + 0.5f) * 6) +
(static_cast<int>(blue / 255.0f * 5.0f + 0.5f))
);
return (
esc +
to_string<bold>::value +
";38;5;" +
to_string<color>::value +
"m"
);
}
static constexpr auto standard16() {
constexpr auto _min = red < green ? red : green;
constexpr auto min = _min < blue ? _min : blue;
constexpr auto _max = red > green ? red : green;
constexpr auto max = _max > blue ? _max : blue;
constexpr uint8_t color = (red == green && green == blue) ? (
red > 192 ? 15 :
red > 128 ? 7 :
red > 32 ? 8 :
0
) : (
(max <= 32) ? (
0
) : (
(
((static_cast<int>((blue - min) * 255.0f / (max - min) + 0.5f) > 128 ? 1 : 0) << 2) |
((static_cast<int>((green - min) * 255.0f / (max - min) + 0.5f) > 128 ? 1 : 0) << 1) |
((static_cast<int>((red - min) * 255.0f / (max - min) + 0.5f) > 128 ? 1 : 0))
) + (max > 192 ? 8 : 0)
)
);
return (
esc +
to_string<bold>::value +
";38;5;" +
to_string<color>::value +
"m"
);
}
static Coloring _detectColoring() {
std::string colorterm;
const char *env_colorterm = getenv("COLORTERM");
if (env_colorterm) {
colorterm = env_colorterm;
}
std::string term;
const char* env_term = getenv("TERM");
if (env_term) {
term = env_term;
}
if (colorterm.find("truecolor") != std::string::npos || term.find("24bit") != std::string::npos) {
return Coloring::TrueColor;
} else if (term.find("256color") != std::string::npos) {
return Coloring::Standard256;
} else if (term.find("ansi") != std::string::npos || term.find("16color") != std::string::npos) {
return Coloring::Standard16;
} else {
return Coloring::Standard16;
}
}
static const std::string _col() {
switch (ansi_color<0, 0, 0>::detectColoring()) {
case Coloring::TrueColor: {
constexpr const auto trueColor = ansi_color<red, green, blue, bold>::trueColor();
return std::string(trueColor);
}
case Coloring::Palette:
case Coloring::Standard256: {
constexpr const auto standard256 = ansi_color<red, green, blue, bold>::standard256();
return std::string(standard256);
}
case Coloring::Standard16: {
constexpr const auto standard16 = ansi_color<red, green, blue, bold>::standard16();
return std::string(standard16);
}
case Coloring::None: {
return "";
}
};
}
public:
static Coloring detectColoring() {
static Coloring coloring = _detectColoring();
return coloring;
}
static const std::string& col() {
static auto col = _col();
return col;
}
};
#define rgb(r, g, b) ansi_color<static_cast<uint8_t>(r), static_cast<uint8_t>(g), static_cast<uint8_t>(b), false>::col()
#define rgba(r, g, b, a) ansi_color<static_cast<uint8_t>(r * a + 0.5f), static_cast<uint8_t>(g * a + 0.5f), static_cast<uint8_t>(b * a + 0.5f), false>::col()
#define brgb(r, g, b) ansi_color<static_cast<uint8_t>(r), static_cast<uint8_t>(g), static_cast<uint8_t>(b), true>::col()
#define brgba(r, g, b, a) ansi_color<static_cast<uint8_t>(r * a + 0.5f), static_cast<uint8_t>(g * a + 0.5f), static_cast<uint8_t>(b * a + 0.5f), true>::col()
|
/*
* Copyright (C) 2017 deipi.com LLC and contributors. All rights reserved.
*
* 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 <string> // for string
#include <stdlib.h> // for getenv
#include "static_str.hh"
template <int N, int rem, char... a>
struct explode : explode<N + 1, rem / 10, ('0' + rem % 10), a...> { };
template <int N, char... a>
struct explode<N, 0, a...> {
constexpr static const char value[N + 1]{a..., 0};
};
template <unsigned num>
struct to_string : explode<0, num> { };
template <>
struct to_string<0> : explode<1, 0, '0'> { };
enum class Coloring : uint8_t {
TrueColor,
Palette,
Standard256,
Standard16,
None,
};
// Ansi colors:
template <uint8_t red, uint8_t green, uint8_t blue, bool bold = false>
class ansi_color {
static constexpr auto esc = static_str::literal("\033[");
static constexpr auto trueColor() {
return (
esc +
to_string<bold>::value +
";38;2;" +
to_string<red>::value + ";" +
to_string<green>::value + ";" +
to_string<blue>::value +
"m"
);
}
static constexpr auto standard256() {
constexpr uint8_t color = (red == green && green == blue) ? (
red < 8 ? 16 :
red > 248 ? 231 :
(232 + static_cast<int>((((red - 8.0f) / 247.0f) * 24.0f) + 0.5f))
) : (
16 +
(static_cast<int>(red / 255.0f * 5.0f + 0.5f) * 36) +
(static_cast<int>(green / 255.0f * 5.0f + 0.5f) * 6) +
(static_cast<int>(blue / 255.0f * 5.0f + 0.5f))
);
return (
esc +
to_string<bold>::value +
";38;5;" +
to_string<color>::value +
"m"
);
}
static constexpr auto standard16() {
constexpr auto _min = red < green ? red : green;
constexpr auto min = _min < blue ? _min : blue;
constexpr auto _max = red > green ? red : green;
constexpr auto max = _max > blue ? _max : blue;
constexpr uint8_t color = (red == green && green == blue) ? (
red > 192 ? 15 :
red > 128 ? 7 :
red > 32 ? 8 :
0
) : (
(max <= 32) ? (
0
) : (
(
((static_cast<int>((blue - min) * 255.0f / (max - min) + 0.5f) > 128 ? 1 : 0) << 2) |
((static_cast<int>((green - min) * 255.0f / (max - min) + 0.5f) > 128 ? 1 : 0) << 1) |
((static_cast<int>((red - min) * 255.0f / (max - min) + 0.5f) > 128 ? 1 : 0))
) + (max > 192 ? 8 : 0)
)
);
return (
esc +
to_string<bold>::value +
";38;5;" +
to_string<color>::value +
"m"
);
}
static Coloring _detectColoring() {
std::string colorterm;
const char *env_colorterm = getenv("COLORTERM");
if (env_colorterm) {
colorterm = env_colorterm;
}
std::string term;
const char* env_term = getenv("TERM");
if (env_term) {
term = env_term;
}
if (colorterm.find("truecolor") != std::string::npos || term.find("24bit") != std::string::npos) {
return Coloring::TrueColor;
} else if (term.find("256color") != std::string::npos) {
return Coloring::Standard256;
} else if (term.find("ansi") != std::string::npos || term.find("16color") != std::string::npos) {
return Coloring::Standard16;
} else {
return Coloring::Standard16;
}
}
static const std::string _col() {
switch (ansi_color<0, 0, 0>::detectColoring()) {
case Coloring::TrueColor: {
constexpr const auto trueColor = ansi_color<red, green, blue, bold>::trueColor();
return std::string(trueColor);
}
case Coloring::Palette:
case Coloring::Standard256: {
constexpr const auto standard256 = ansi_color<red, green, blue, bold>::standard256();
return std::string(standard256);
}
case Coloring::Standard16: {
constexpr const auto standard16 = ansi_color<red, green, blue, bold>::standard16();
return std::string(standard16);
}
case Coloring::None: {
return "";
}
};
}
public:
static Coloring detectColoring() {
static Coloring coloring = _detectColoring();
return coloring;
}
static const std::string& col() {
static auto col = _col();
return col;
}
};
#define rgb(r, g, b) ansi_color<static_cast<uint8_t>(r), static_cast<uint8_t>(g), static_cast<uint8_t>(b), false>::col()
#define rgba(r, g, b, a) ansi_color<static_cast<uint8_t>(r * a + 0.5f), static_cast<uint8_t>(g * a + 0.5f), static_cast<uint8_t>(b * a + 0.5f), false>::col()
#define brgb(r, g, b) ansi_color<static_cast<uint8_t>(r), static_cast<uint8_t>(g), static_cast<uint8_t>(b), true>::col()
#define brgba(r, g, b, a) ansi_color<static_cast<uint8_t>(r * a + 0.5f), static_cast<uint8_t>(g * a + 0.5f), static_cast<uint8_t>(b * a + 0.5f), true>::col()
|
Fix cast
|
ansi_color: Fix cast
|
C++
|
mit
|
Kronuz/Xapiand,Kronuz/Xapiand,Kronuz/Xapiand,Kronuz/Xapiand,Kronuz/Xapiand,Kronuz/Xapiand
|
bf47b58b8a57b105d82d4ed1600205f601081d3c
|
redis/command_factory.hh
|
redis/command_factory.hh
|
/*
* Copyright (C) 2019 pengjian.uestc @ gmail.com
*/
/*
* 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/>.
*/
#pragma once
#include "redis/abstract_command.hh"
#include "redis/options.hh"
namespace service {
class storage_proxy;
}
namespace redis {
using namespace seastar;
class request;
class command_factory {
public:
command_factory() {}
~command_factory() {}
static future<redis_message> create_execute(service::storage_proxy&, request&, redis::redis_options&, service_permit);
};
}
|
/*
* Copyright (C) 2019 pengjian.uestc @ gmail.com
*/
/*
* 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/>.
*/
#pragma once
#include "redis/abstract_command.hh"
#include "redis/options.hh"
namespace service {
class storage_proxy;
}
namespace redis {
class request;
class command_factory {
public:
command_factory() {}
~command_factory() {}
static seastar::future<redis_message> create_execute(service::storage_proxy&, request&, redis::redis_options&, service_permit);
};
}
|
Remove seastar namespace import from command_factory.hh
|
redis: Remove seastar namespace import from command_factory.hh
|
C++
|
agpl-3.0
|
scylladb/scylla,scylladb/scylla,scylladb/scylla,scylladb/scylla
|
2a79a0927c479b69316aa275c1f79c74d20e8040
|
lib/CodeGen/MachineInstr.cpp
|
lib/CodeGen/MachineInstr.cpp
|
//===-- MachineInstr.cpp --------------------------------------------------===//
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/Value.h"
#include "llvm/Target/MachineInstrInfo.h" // FIXME: shouldn't need this!
#include "llvm/Target/TargetMachine.h"
using std::cerr;
// Global variable holding an array of descriptors for machine instructions.
// The actual object needs to be created separately for each target machine.
// This variable is initialized and reset by class MachineInstrInfo.
//
// FIXME: This should be a property of the target so that more than one target
// at a time can be active...
//
extern const MachineInstrDescriptor *TargetInstrDescriptors;
// Constructor for instructions with fixed #operands (nearly all)
MachineInstr::MachineInstr(MachineOpCode _opCode)
: opCode(_opCode),
operands(TargetInstrDescriptors[_opCode].numOperands, MachineOperand()),
numImplicitRefs(0)
{
assert(TargetInstrDescriptors[_opCode].numOperands >= 0);
}
// Constructor for instructions with variable #operands
MachineInstr::MachineInstr(MachineOpCode OpCode, unsigned numOperands)
: opCode(OpCode),
operands(numOperands, MachineOperand()),
numImplicitRefs(0)
{
}
/// MachineInstr ctor - This constructor only does a _reserve_ of the operands,
/// not a resize for them. It is expected that if you use this that you call
/// add* methods below to fill up the operands, instead of the Set methods.
/// Eventually, the "resizing" ctors will be phased out.
///
MachineInstr::MachineInstr(MachineOpCode Opcode, unsigned numOperands,
bool XX, bool YY)
: opCode(Opcode),
numImplicitRefs(0)
{
operands.reserve(numOperands);
}
/// MachineInstr ctor - Work exactly the same as the ctor above, except that the
/// MachineInstr is created and added to the end of the specified basic block.
///
MachineInstr::MachineInstr(MachineBasicBlock *MBB, MachineOpCode Opcode,
unsigned numOperands)
: opCode(Opcode),
numImplicitRefs(0)
{
assert(MBB && "Cannot use inserting ctor with null basic block!");
operands.reserve(numOperands);
MBB->push_back(this); // Add instruction to end of basic block!
}
// OperandComplete - Return true if it's illegal to add a new operand
bool MachineInstr::OperandsComplete() const
{
int NumOperands = TargetInstrDescriptors[opCode].numOperands;
if (NumOperands >= 0 && getNumOperands() >= (unsigned)NumOperands)
return true; // Broken!
return false;
}
//
// Support for replacing opcode and operands of a MachineInstr in place.
// This only resets the size of the operand vector and initializes it.
// The new operands must be set explicitly later.
//
void MachineInstr::replace(MachineOpCode Opcode, unsigned numOperands)
{
assert(getNumImplicitRefs() == 0 &&
"This is probably broken because implicit refs are going to be lost.");
opCode = Opcode;
operands.clear();
operands.resize(numOperands, MachineOperand());
}
void
MachineInstr::SetMachineOperandVal(unsigned i,
MachineOperand::MachineOperandType opType,
Value* V,
bool isdef,
bool isDefAndUse)
{
assert(i < operands.size()); // may be explicit or implicit op
operands[i].opType = opType;
operands[i].value = V;
operands[i].regNum = -1;
operands[i].flags = 0;
if (isdef || TargetInstrDescriptors[opCode].resultPos == (int) i)
operands[i].markDef();
if (isDefAndUse)
operands[i].markDefAndUse();
}
void
MachineInstr::SetMachineOperandConst(unsigned i,
MachineOperand::MachineOperandType operandType,
int64_t intValue)
{
assert(i < getNumOperands()); // must be explicit op
assert(TargetInstrDescriptors[opCode].resultPos != (int) i &&
"immed. constant cannot be defined");
operands[i].opType = operandType;
operands[i].value = NULL;
operands[i].immedVal = intValue;
operands[i].regNum = -1;
operands[i].flags = 0;
}
void
MachineInstr::SetMachineOperandReg(unsigned i,
int regNum,
bool isdef) {
assert(i < getNumOperands()); // must be explicit op
operands[i].opType = MachineOperand::MO_MachineRegister;
operands[i].value = NULL;
operands[i].regNum = regNum;
operands[i].flags = 0;
if (isdef || TargetInstrDescriptors[opCode].resultPos == (int) i)
operands[i].markDef();
insertUsedReg(regNum);
}
void
MachineInstr::SetRegForOperand(unsigned i, int regNum)
{
assert(i < getNumOperands()); // must be explicit op
operands[i].setRegForValue(regNum);
insertUsedReg(regNum);
}
// Subsitute all occurrences of Value* oldVal with newVal in all operands
// and all implicit refs. If defsOnly == true, substitute defs only.
unsigned
MachineInstr::substituteValue(const Value* oldVal, Value* newVal, bool defsOnly)
{
unsigned numSubst = 0;
// Subsitute operands
for (MachineInstr::val_op_iterator O = begin(), E = end(); O != E; ++O)
if (*O == oldVal)
if (!defsOnly || O.isDef())
{
O.getMachineOperand().value = newVal;
++numSubst;
}
// Subsitute implicit refs
for (unsigned i=0, N=getNumImplicitRefs(); i < N; ++i)
if (getImplicitRef(i) == oldVal)
if (!defsOnly || implicitRefIsDefined(i))
{
getImplicitOp(i).value = newVal;
++numSubst;
}
return numSubst;
}
void
MachineInstr::dump() const
{
cerr << " " << *this;
}
static inline std::ostream&
OutputValue(std::ostream &os, const Value* val)
{
os << "(val ";
if (val && val->hasName())
return os << val->getName() << ")";
else
return os << (void*) val << ")"; // print address only
}
static inline std::ostream&
OutputReg(std::ostream &os, unsigned int regNum)
{
return os << "%mreg(" << regNum << ")";
}
static void print(const MachineOperand &MO, std::ostream &OS,
const TargetMachine &TM) {
bool CloseParen = true;
if (MO.opHiBits32())
OS << "%lm(";
else if (MO.opLoBits32())
OS << "%lo(";
else if (MO.opHiBits64())
OS << "%hh(";
else if (MO.opLoBits64())
OS << "%hm(";
else
CloseParen = false;
switch (MO.getType()) {
case MachineOperand::MO_VirtualRegister:
if (MO.getVRegValue()) {
OS << "%reg";
OutputValue(OS, MO.getVRegValue());
if (MO.hasAllocatedReg())
OS << "==";
}
if (MO.hasAllocatedReg())
OutputReg(OS, MO.getAllocatedRegNum());
break;
case MachineOperand::MO_CCRegister:
OS << "%ccreg";
OutputValue(OS, MO.getVRegValue());
if (MO.hasAllocatedReg()) {
OS << "==";
OutputReg(OS, MO.getAllocatedRegNum());
}
break;
case MachineOperand::MO_MachineRegister:
OutputReg(OS, MO.getMachineRegNum());
break;
case MachineOperand::MO_SignExtendedImmed:
OS << (long)MO.getImmedValue();
break;
case MachineOperand::MO_UnextendedImmed:
OS << (long)MO.getImmedValue();
break;
case MachineOperand::MO_PCRelativeDisp: {
const Value* opVal = MO.getVRegValue();
bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal);
OS << "%disp(" << (isLabel? "label " : "addr-of-val ");
if (opVal->hasName())
OS << opVal->getName();
else
OS << (const void*) opVal;
OS << ")";
break;
}
default:
assert(0 && "Unrecognized operand type");
}
if (CloseParen)
OS << ")";
}
void MachineInstr::print(std::ostream &OS, const TargetMachine &TM) {
OS << TM.getInstrInfo().getName(getOpcode());
for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
OS << "\t";
::print(getOperand(i), OS, TM);
if (operandIsDefinedAndUsed(i))
OS << "<def&use>";
else if (operandIsDefined(i))
OS << "<def>";
}
// code for printing implict references
if (getNumImplicitRefs()) {
OS << "\tImplicitRefs: ";
for(unsigned i = 0, e = getNumImplicitRefs(); i != e; ++i) {
OS << "\t";
OutputValue(OS, getImplicitRef(i));
if (implicitRefIsDefinedAndUsed(i))
OS << "<def&use>";
else if (implicitRefIsDefined(i))
OS << "<def>";
}
}
OS << "\n";
}
std::ostream &operator<<(std::ostream& os, const MachineInstr& minstr)
{
os << TargetInstrDescriptors[minstr.opCode].Name;
for (unsigned i=0, N=minstr.getNumOperands(); i < N; i++) {
os << "\t" << minstr.getOperand(i);
if( minstr.operandIsDefined(i) )
os << "*";
if( minstr.operandIsDefinedAndUsed(i) )
os << "*";
}
// code for printing implict references
unsigned NumOfImpRefs = minstr.getNumImplicitRefs();
if( NumOfImpRefs > 0 ) {
os << "\tImplicit: ";
for(unsigned z=0; z < NumOfImpRefs; z++) {
OutputValue(os, minstr.getImplicitRef(z));
if( minstr.implicitRefIsDefined(z)) os << "*";
if( minstr.implicitRefIsDefinedAndUsed(z)) os << "*";
os << "\t";
}
}
return os << "\n";
}
std::ostream &operator<<(std::ostream &os, const MachineOperand &mop)
{
if (mop.opHiBits32())
os << "%lm(";
else if (mop.opLoBits32())
os << "%lo(";
else if (mop.opHiBits64())
os << "%hh(";
else if (mop.opLoBits64())
os << "%hm(";
switch (mop.getType())
{
case MachineOperand::MO_VirtualRegister:
os << "%reg";
OutputValue(os, mop.getVRegValue());
if (mop.hasAllocatedReg()) {
os << "==";
OutputReg(os, mop.getAllocatedRegNum());
}
break;
case MachineOperand::MO_CCRegister:
os << "%ccreg";
OutputValue(os, mop.getVRegValue());
if (mop.hasAllocatedReg()) {
os << "==";
OutputReg(os, mop.getAllocatedRegNum());
}
break;
case MachineOperand::MO_MachineRegister:
OutputReg(os, mop.getMachineRegNum());
break;
case MachineOperand::MO_SignExtendedImmed:
os << (long)mop.getImmedValue();
break;
case MachineOperand::MO_UnextendedImmed:
os << (long)mop.getImmedValue();
break;
case MachineOperand::MO_PCRelativeDisp:
{
const Value* opVal = mop.getVRegValue();
bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal);
os << "%disp(" << (isLabel? "label " : "addr-of-val ");
if (opVal->hasName())
os << opVal->getName();
else
os << (const void*) opVal;
os << ")";
break;
}
default:
assert(0 && "Unrecognized operand type");
break;
}
if (mop.flags &
(MachineOperand::HIFLAG32 | MachineOperand::LOFLAG32 |
MachineOperand::HIFLAG64 | MachineOperand::LOFLAG64))
os << ")";
return os;
}
|
//===-- MachineInstr.cpp --------------------------------------------------===//
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/Value.h"
#include "llvm/Target/MachineInstrInfo.h" // FIXME: shouldn't need this!
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/MRegisterInfo.h"
using std::cerr;
// Global variable holding an array of descriptors for machine instructions.
// The actual object needs to be created separately for each target machine.
// This variable is initialized and reset by class MachineInstrInfo.
//
// FIXME: This should be a property of the target so that more than one target
// at a time can be active...
//
extern const MachineInstrDescriptor *TargetInstrDescriptors;
// Constructor for instructions with fixed #operands (nearly all)
MachineInstr::MachineInstr(MachineOpCode _opCode)
: opCode(_opCode),
operands(TargetInstrDescriptors[_opCode].numOperands, MachineOperand()),
numImplicitRefs(0)
{
assert(TargetInstrDescriptors[_opCode].numOperands >= 0);
}
// Constructor for instructions with variable #operands
MachineInstr::MachineInstr(MachineOpCode OpCode, unsigned numOperands)
: opCode(OpCode),
operands(numOperands, MachineOperand()),
numImplicitRefs(0)
{
}
/// MachineInstr ctor - This constructor only does a _reserve_ of the operands,
/// not a resize for them. It is expected that if you use this that you call
/// add* methods below to fill up the operands, instead of the Set methods.
/// Eventually, the "resizing" ctors will be phased out.
///
MachineInstr::MachineInstr(MachineOpCode Opcode, unsigned numOperands,
bool XX, bool YY)
: opCode(Opcode),
numImplicitRefs(0)
{
operands.reserve(numOperands);
}
/// MachineInstr ctor - Work exactly the same as the ctor above, except that the
/// MachineInstr is created and added to the end of the specified basic block.
///
MachineInstr::MachineInstr(MachineBasicBlock *MBB, MachineOpCode Opcode,
unsigned numOperands)
: opCode(Opcode),
numImplicitRefs(0)
{
assert(MBB && "Cannot use inserting ctor with null basic block!");
operands.reserve(numOperands);
MBB->push_back(this); // Add instruction to end of basic block!
}
// OperandComplete - Return true if it's illegal to add a new operand
bool MachineInstr::OperandsComplete() const
{
int NumOperands = TargetInstrDescriptors[opCode].numOperands;
if (NumOperands >= 0 && getNumOperands() >= (unsigned)NumOperands)
return true; // Broken!
return false;
}
//
// Support for replacing opcode and operands of a MachineInstr in place.
// This only resets the size of the operand vector and initializes it.
// The new operands must be set explicitly later.
//
void MachineInstr::replace(MachineOpCode Opcode, unsigned numOperands)
{
assert(getNumImplicitRefs() == 0 &&
"This is probably broken because implicit refs are going to be lost.");
opCode = Opcode;
operands.clear();
operands.resize(numOperands, MachineOperand());
}
void
MachineInstr::SetMachineOperandVal(unsigned i,
MachineOperand::MachineOperandType opType,
Value* V,
bool isdef,
bool isDefAndUse)
{
assert(i < operands.size()); // may be explicit or implicit op
operands[i].opType = opType;
operands[i].value = V;
operands[i].regNum = -1;
operands[i].flags = 0;
if (isdef || TargetInstrDescriptors[opCode].resultPos == (int) i)
operands[i].markDef();
if (isDefAndUse)
operands[i].markDefAndUse();
}
void
MachineInstr::SetMachineOperandConst(unsigned i,
MachineOperand::MachineOperandType operandType,
int64_t intValue)
{
assert(i < getNumOperands()); // must be explicit op
assert(TargetInstrDescriptors[opCode].resultPos != (int) i &&
"immed. constant cannot be defined");
operands[i].opType = operandType;
operands[i].value = NULL;
operands[i].immedVal = intValue;
operands[i].regNum = -1;
operands[i].flags = 0;
}
void
MachineInstr::SetMachineOperandReg(unsigned i,
int regNum,
bool isdef) {
assert(i < getNumOperands()); // must be explicit op
operands[i].opType = MachineOperand::MO_MachineRegister;
operands[i].value = NULL;
operands[i].regNum = regNum;
operands[i].flags = 0;
if (isdef || TargetInstrDescriptors[opCode].resultPos == (int) i)
operands[i].markDef();
insertUsedReg(regNum);
}
void
MachineInstr::SetRegForOperand(unsigned i, int regNum)
{
assert(i < getNumOperands()); // must be explicit op
operands[i].setRegForValue(regNum);
insertUsedReg(regNum);
}
// Subsitute all occurrences of Value* oldVal with newVal in all operands
// and all implicit refs. If defsOnly == true, substitute defs only.
unsigned
MachineInstr::substituteValue(const Value* oldVal, Value* newVal, bool defsOnly)
{
unsigned numSubst = 0;
// Subsitute operands
for (MachineInstr::val_op_iterator O = begin(), E = end(); O != E; ++O)
if (*O == oldVal)
if (!defsOnly || O.isDef())
{
O.getMachineOperand().value = newVal;
++numSubst;
}
// Subsitute implicit refs
for (unsigned i=0, N=getNumImplicitRefs(); i < N; ++i)
if (getImplicitRef(i) == oldVal)
if (!defsOnly || implicitRefIsDefined(i))
{
getImplicitOp(i).value = newVal;
++numSubst;
}
return numSubst;
}
void
MachineInstr::dump() const
{
cerr << " " << *this;
}
static inline std::ostream&
OutputValue(std::ostream &os, const Value* val)
{
os << "(val ";
if (val && val->hasName())
return os << val->getName() << ")";
else
return os << (void*) val << ")"; // print address only
}
static inline void OutputReg(std::ostream &os, unsigned RegNo,
const MRegisterInfo *MRI = 0) {
if (MRI) {
if (RegNo < MRegisterInfo::FirstVirtualRegister)
os << "%" << MRI->get(RegNo).Name;
else
os << "%reg" << RegNo;
} else
os << "%mreg(" << RegNo << ")";
}
static void print(const MachineOperand &MO, std::ostream &OS,
const TargetMachine &TM) {
const MRegisterInfo *MRI = TM.getRegisterInfo();
bool CloseParen = true;
if (MO.opHiBits32())
OS << "%lm(";
else if (MO.opLoBits32())
OS << "%lo(";
else if (MO.opHiBits64())
OS << "%hh(";
else if (MO.opLoBits64())
OS << "%hm(";
else
CloseParen = false;
switch (MO.getType()) {
case MachineOperand::MO_VirtualRegister:
if (MO.getVRegValue()) {
OS << "%reg";
OutputValue(OS, MO.getVRegValue());
if (MO.hasAllocatedReg())
OS << "==";
}
if (MO.hasAllocatedReg())
OutputReg(OS, MO.getAllocatedRegNum(), MRI);
break;
case MachineOperand::MO_CCRegister:
OS << "%ccreg";
OutputValue(OS, MO.getVRegValue());
if (MO.hasAllocatedReg()) {
OS << "==";
OutputReg(OS, MO.getAllocatedRegNum(), MRI);
}
break;
case MachineOperand::MO_MachineRegister:
OutputReg(OS, MO.getMachineRegNum(), MRI);
break;
case MachineOperand::MO_SignExtendedImmed:
OS << (long)MO.getImmedValue();
break;
case MachineOperand::MO_UnextendedImmed:
OS << (long)MO.getImmedValue();
break;
case MachineOperand::MO_PCRelativeDisp: {
const Value* opVal = MO.getVRegValue();
bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal);
OS << "%disp(" << (isLabel? "label " : "addr-of-val ");
if (opVal->hasName())
OS << opVal->getName();
else
OS << (const void*) opVal;
OS << ")";
break;
}
default:
assert(0 && "Unrecognized operand type");
}
if (CloseParen)
OS << ")";
}
void MachineInstr::print(std::ostream &OS, const TargetMachine &TM) {
OS << TM.getInstrInfo().getName(getOpcode());
for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
OS << "\t";
::print(getOperand(i), OS, TM);
if (operandIsDefinedAndUsed(i))
OS << "<def&use>";
else if (operandIsDefined(i))
OS << "<def>";
}
// code for printing implict references
if (getNumImplicitRefs()) {
OS << "\tImplicitRefs: ";
for(unsigned i = 0, e = getNumImplicitRefs(); i != e; ++i) {
OS << "\t";
OutputValue(OS, getImplicitRef(i));
if (implicitRefIsDefinedAndUsed(i))
OS << "<def&use>";
else if (implicitRefIsDefined(i))
OS << "<def>";
}
}
OS << "\n";
}
std::ostream &operator<<(std::ostream& os, const MachineInstr& minstr)
{
os << TargetInstrDescriptors[minstr.opCode].Name;
for (unsigned i=0, N=minstr.getNumOperands(); i < N; i++) {
os << "\t" << minstr.getOperand(i);
if( minstr.operandIsDefined(i) )
os << "*";
if( minstr.operandIsDefinedAndUsed(i) )
os << "*";
}
// code for printing implict references
unsigned NumOfImpRefs = minstr.getNumImplicitRefs();
if( NumOfImpRefs > 0 ) {
os << "\tImplicit: ";
for(unsigned z=0; z < NumOfImpRefs; z++) {
OutputValue(os, minstr.getImplicitRef(z));
if( minstr.implicitRefIsDefined(z)) os << "*";
if( minstr.implicitRefIsDefinedAndUsed(z)) os << "*";
os << "\t";
}
}
return os << "\n";
}
std::ostream &operator<<(std::ostream &os, const MachineOperand &mop)
{
if (mop.opHiBits32())
os << "%lm(";
else if (mop.opLoBits32())
os << "%lo(";
else if (mop.opHiBits64())
os << "%hh(";
else if (mop.opLoBits64())
os << "%hm(";
switch (mop.getType())
{
case MachineOperand::MO_VirtualRegister:
os << "%reg";
OutputValue(os, mop.getVRegValue());
if (mop.hasAllocatedReg()) {
os << "==";
OutputReg(os, mop.getAllocatedRegNum());
}
break;
case MachineOperand::MO_CCRegister:
os << "%ccreg";
OutputValue(os, mop.getVRegValue());
if (mop.hasAllocatedReg()) {
os << "==";
OutputReg(os, mop.getAllocatedRegNum());
}
break;
case MachineOperand::MO_MachineRegister:
OutputReg(os, mop.getMachineRegNum());
break;
case MachineOperand::MO_SignExtendedImmed:
os << (long)mop.getImmedValue();
break;
case MachineOperand::MO_UnextendedImmed:
os << (long)mop.getImmedValue();
break;
case MachineOperand::MO_PCRelativeDisp:
{
const Value* opVal = mop.getVRegValue();
bool isLabel = isa<Function>(opVal) || isa<BasicBlock>(opVal);
os << "%disp(" << (isLabel? "label " : "addr-of-val ");
if (opVal->hasName())
os << opVal->getName();
else
os << (const void*) opVal;
os << ")";
break;
}
default:
assert(0 && "Unrecognized operand type");
break;
}
if (mop.flags &
(MachineOperand::HIFLAG32 | MachineOperand::LOFLAG32 |
MachineOperand::HIFLAG64 | MachineOperand::LOFLAG64))
os << ")";
return os;
}
|
Use MRegisterInfo, if available, to print symbolic register names
|
Use MRegisterInfo, if available, to print symbolic register names
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@4438 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
apple/swift-llvm,dslab-epfl/asap,chubbymaggie/asap,llvm-mirror/llvm,llvm-mirror/llvm,chubbymaggie/asap,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,dslab-epfl/asap,apple/swift-llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,chubbymaggie/asap,chubbymaggie/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,chubbymaggie/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap
|
2e914a9dc50d5ea87af2a49780ee615cea723731
|
src/posix/net.cpp
|
src/posix/net.cpp
|
/**
* @file posix/net.cpp
* @brief POSIX network access layer (using cURL)
*
* (c) 2013 by Mega Limited, Wellsford, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK 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.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
#include "mega.h"
namespace mega {
CurlHttpIO::CurlHttpIO()
{
curl_global_init(CURL_GLOBAL_DEFAULT);
curlm = curl_multi_init();
curlsh = curl_share_init();
curl_share_setopt(curlsh, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS);
curl_share_setopt(curlsh, CURLSHOPT_SHARE, CURL_LOCK_DATA_SSL_SESSION);
contenttypejson = curl_slist_append(NULL, "Content-Type: application/json");
contenttypejson = curl_slist_append(contenttypejson, "Expect:");
contenttypebinary = curl_slist_append(NULL, "Content-Type: application/octet-stream");
contenttypebinary = curl_slist_append(contenttypebinary, "Expect:");
}
CurlHttpIO::~CurlHttpIO()
{
curl_global_cleanup();
}
void CurlHttpIO::setuseragent(string* u)
{
useragent = u;
}
// wake up from cURL I/O
void CurlHttpIO::addevents(Waiter* w, int flags)
{
int t;
PosixWaiter* pw = (PosixWaiter*)w;
curl_multi_fdset(curlm, &pw->rfds, &pw->wfds, &pw->efds, &t);
pw->bumpmaxfd(t);
}
// POST request to URL
void CurlHttpIO::post(HttpReq* req, const char* data, unsigned len)
{
if (debug)
{
cout << "POST target URL: " << req->posturl << endl;
if (req->binary)
{
cout << "[sending " << req->out->size() << " bytes of raw data]" << endl;
}
else
{
cout << "Sending: " << *req->out << endl;
}
}
CURL* curl;
req->in.clear();
if (( curl = curl_easy_init()))
{
curl_easy_setopt(curl, CURLOPT_URL, req->posturl.c_str());
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data ? data : req->out->data());
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, data ? len : req->out->size());
curl_easy_setopt(curl, CURLOPT_USERAGENT, useragent->c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, req->type == REQ_JSON ? contenttypejson : contenttypebinary);
curl_easy_setopt(curl, CURLOPT_SHARE, curlsh);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)req);
curl_easy_setopt(curl, CURLOPT_PRIVATE, (void*)req);
curl_multi_add_handle(curlm, curl);
req->status = REQ_INFLIGHT;
req->httpiohandle = (void*)curl;
}
else
{
req->status = REQ_FAILURE;
}
}
// cancel pending HTTP request
void CurlHttpIO::cancel(HttpReq* req)
{
if (req->httpiohandle)
{
curl_multi_remove_handle(curlm, (CURL*)req->httpiohandle);
curl_easy_cleanup((CURL*)req->httpiohandle);
req->httpstatus = 0;
req->status = REQ_FAILURE;
req->httpiohandle = NULL;
}
}
// real-time progress information on POST data
m_off_t CurlHttpIO::postpos(void* handle)
{
double bytes;
curl_easy_getinfo(handle, CURLINFO_SIZE_UPLOAD, &bytes);
return (m_off_t)bytes;
}
// process events
bool CurlHttpIO::doio()
{
bool done;
done = 0;
CURLMsg *msg;
int dummy;
curl_multi_perform(curlm, &dummy);
while (( msg = curl_multi_info_read(curlm, &dummy)))
{
HttpReq* req;
if (( curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, (char**)&req) == CURLE_OK ) && req)
{
req->httpio = NULL;
if (msg->msg == CURLMSG_DONE)
{
curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE, &req->httpstatus);
if (debug)
{
cout << "CURLMSG_DONE with HTTP status: " << req->httpstatus << endl;
if (req->binary)
{
cout << "[received " << req->in.size() << " bytes of raw data]" << endl;
}
else
{
cout << "Received: " << req->in.c_str() << endl;
}
}
req->status = req->httpstatus == 200 ? REQ_SUCCESS : REQ_FAILURE;
httpio->inetstatus(req->status);
done = true;
}
else
{
req->status = REQ_FAILURE;
}
}
curl_multi_remove_handle(curlm, msg->easy_handle);
curl_easy_cleanup(msg->easy_handle);
}
return done;
}
// callback for incoming HTTP payload
size_t CurlHttpIO::write_data(void *ptr, size_t size, size_t nmemb, void *target)
{
size *= nmemb;
((HttpReq*)target )->put(ptr, size);
return size;
}
} // namespace
|
/**
* @file posix/net.cpp
* @brief POSIX network access layer (using cURL)
*
* (c) 2013 by Mega Limited, Wellsford, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK 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.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
#include "mega.h"
namespace mega {
CurlHttpIO::CurlHttpIO()
{
curl_global_init(CURL_GLOBAL_DEFAULT);
curlm = curl_multi_init();
curlsh = curl_share_init();
curl_share_setopt(curlsh, CURLSHOPT_SHARE, CURL_LOCK_DATA_DNS);
curl_share_setopt(curlsh, CURLSHOPT_SHARE, CURL_LOCK_DATA_SSL_SESSION);
contenttypejson = curl_slist_append(NULL, "Content-Type: application/json");
contenttypejson = curl_slist_append(contenttypejson, "Expect:");
contenttypebinary = curl_slist_append(NULL, "Content-Type: application/octet-stream");
contenttypebinary = curl_slist_append(contenttypebinary, "Expect:");
}
CurlHttpIO::~CurlHttpIO()
{
curl_global_cleanup();
}
void CurlHttpIO::setuseragent(string* u)
{
useragent = u;
}
// wake up from cURL I/O
void CurlHttpIO::addevents(Waiter* w, int flags)
{
int t;
PosixWaiter* pw = (PosixWaiter*)w;
curl_multi_fdset(curlm, &pw->rfds, &pw->wfds, &pw->efds, &t);
pw->bumpmaxfd(t);
}
// POST request to URL
void CurlHttpIO::post(HttpReq* req, const char* data, unsigned len)
{
if (debug)
{
cout << "POST target URL: " << req->posturl << endl;
if (req->binary)
{
cout << "[sending " << req->out->size() << " bytes of raw data]" << endl;
}
else
{
cout << "Sending: " << *req->out << endl;
}
}
CURL* curl;
req->in.clear();
if (( curl = curl_easy_init()))
{
curl_easy_setopt(curl, CURLOPT_URL, req->posturl.c_str());
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, data ? data : req->out->data());
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, data ? len : req->out->size());
curl_easy_setopt(curl, CURLOPT_USERAGENT, useragent->c_str());
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, req->type == REQ_JSON ? contenttypejson : contenttypebinary);
curl_easy_setopt(curl, CURLOPT_SHARE, curlsh);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)req);
curl_easy_setopt(curl, CURLOPT_PRIVATE, (void*)req);
curl_multi_add_handle(curlm, curl);
req->status = REQ_INFLIGHT;
req->httpiohandle = (void*)curl;
}
else
{
req->status = REQ_FAILURE;
}
}
// cancel pending HTTP request
void CurlHttpIO::cancel(HttpReq* req)
{
if (req->httpiohandle)
{
curl_multi_remove_handle(curlm, (CURL*)req->httpiohandle);
curl_easy_cleanup((CURL*)req->httpiohandle);
req->httpstatus = 0;
req->status = REQ_FAILURE;
req->httpiohandle = NULL;
}
}
// real-time progress information on POST data
m_off_t CurlHttpIO::postpos(void* handle)
{
double bytes;
curl_easy_getinfo(handle, CURLINFO_SIZE_UPLOAD, &bytes);
return (m_off_t)bytes;
}
// process events
bool CurlHttpIO::doio()
{
bool done;
done = 0;
CURLMsg *msg;
int dummy;
curl_multi_perform(curlm, &dummy);
while (( msg = curl_multi_info_read(curlm, &dummy)))
{
HttpReq* req;
if (( curl_easy_getinfo(msg->easy_handle, CURLINFO_PRIVATE, (char**)&req) == CURLE_OK ) && req)
{
req->httpio = NULL;
if (msg->msg == CURLMSG_DONE)
{
curl_easy_getinfo(msg->easy_handle, CURLINFO_RESPONSE_CODE, &req->httpstatus);
if (debug)
{
cout << "CURLMSG_DONE with HTTP status: " << req->httpstatus << endl;
if (req->binary)
{
cout << "[received " << req->in.size() << " bytes of raw data]" << endl;
}
else
{
cout << "Received: " << req->in.c_str() << endl;
}
}
req->status = req->httpstatus == 200 ? REQ_SUCCESS : REQ_FAILURE;
inetstatus(req->status);
done = true;
}
else
{
req->status = REQ_FAILURE;
}
}
curl_multi_remove_handle(curlm, msg->easy_handle);
curl_easy_cleanup(msg->easy_handle);
}
return done;
}
// callback for incoming HTTP payload
size_t CurlHttpIO::write_data(void *ptr, size_t size, size_t nmemb, void *target)
{
size *= nmemb;
((HttpReq*)target )->put(ptr, size);
return size;
}
} // namespace
|
Fix POSIX
|
HttpIO: Fix POSIX
|
C++
|
bsd-2-clause
|
sergiohs84/sdk,Sisky/sdk,BlackFired/sdk,jedisct1/sdk,BiuroCo/mega,jedisct1/sdk,sergiohs84/sdk,javiserrano/sdk,wizzard/sdk,Acidburn0zzz/sdk,javiserrano/sdk,jedisct1/sdk,sergiohs84/sdk,javiserrano/sdk,BiuroCo/mega,Sisky/sdk,18671178307/sdk,18671178307/sdk,Acidburn0zzz/sdk,Sisky/sdk,jedisct1/sdk,PatrickJBaird/sdk,Acidburn0zzz/sdk,jedisct1/sdk,BlackFired/sdk,Acidburn0zzz/sdk,sergiohs84/sdk,18671178307/sdk,BlackFired/sdk,Alexx99/sdk,wizzard/sdk,Sisky/sdk,sergiohs84/sdk,BiuroCo/mega,Acidburn0zzz/sdk,meganz/sdk,sergiohs84/sdk,Sisky/sdk,BlackFired/sdk,18671178307/sdk,wizzard/sdk,Alexx99/sdk,meganz/sdk,thedebian/sdk,Acidburn0zzz/sdk,thedebian/sdk,meganz/sdk,jedisct1/sdk,Sisky/sdk,Alexx99/sdk,Novo1987/sdk,PatrickJBaird/sdk,sergiohs84/sdk,PatrickJBaird/sdk,Acidburn0zzz/sdk,SuperStarPL/sdk,PatrickJBaird/sdk,18671178307/sdk,thedebian/sdk,javiserrano/sdk,Novo1987/sdk,PatrickJBaird/sdk,18671178307/sdk,Novo1987/sdk,PatrickJBaird/sdk,Acidburn0zzz/sdk,javiserrano/sdk,Novo1987/sdk,SuperStarPL/sdk,thedebian/sdk,thedebian/sdk,Novo1987/sdk,Novo1987/sdk,SuperStarPL/sdk,BlackFired/sdk,SuperStarPL/sdk,BiuroCo/mega,Alexx99/sdk,meganz/sdk,Alexx99/sdk,SuperStarPL/sdk,meganz/sdk,BiuroCo/mega,jedisct1/sdk,BiuroCo/mega,javiserrano/sdk,meganz/sdk,Alexx99/sdk,Novo1987/sdk,thedebian/sdk,meganz/sdk,18671178307/sdk,SuperStarPL/sdk,jedisct1/sdk,sergiohs84/sdk,wizzard/sdk,BlackFired/sdk,18671178307/sdk,Novo1987/sdk
|
59db760c5327128b57f20316667fdcf830b99db2
|
Driver/Backend.cpp
|
Driver/Backend.cpp
|
//===--- Backend.cpp - Interface to LLVM backend technologies -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "ASTConsumers.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/TranslationUnit.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/CodeGen/ModuleBuilder.h"
#include "clang/Driver/CompileOptions.h"
#include "llvm/Module.h"
#include "llvm/ModuleProvider.h"
#include "llvm/PassManager.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/CodeGen/RegAllocRegistry.h"
#include "llvm/CodeGen/SchedulerRegistry.h"
#include "llvm/CodeGen/ScheduleDAGSDNodes.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Compiler.h"
#include "llvm/System/Path.h"
#include "llvm/System/Program.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetMachineRegistry.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/IPO.h"
using namespace clang;
using namespace llvm;
namespace {
class VISIBILITY_HIDDEN BackendConsumer : public ASTConsumer {
BackendAction Action;
CompileOptions CompileOpts;
const std::string &InputFile;
std::string OutputFile;
bool GenerateDebugInfo;
llvm::OwningPtr<CodeGenerator> Gen;
llvm::Module *TheModule;
llvm::TargetData *TheTargetData;
llvm::raw_ostream *AsmOutStream;
mutable llvm::ModuleProvider *ModuleProvider;
mutable FunctionPassManager *CodeGenPasses;
mutable PassManager *PerModulePasses;
mutable FunctionPassManager *PerFunctionPasses;
FunctionPassManager *getCodeGenPasses() const;
PassManager *getPerModulePasses() const;
FunctionPassManager *getPerFunctionPasses() const;
void CreatePasses();
/// AddEmitPasses - Add passes necessary to emit assembly or LLVM
/// IR.
///
/// \return True on success. On failure \arg Error will be set to
/// a user readable error message.
bool AddEmitPasses(std::string &Error);
void EmitAssembly();
public:
BackendConsumer(BackendAction action, Diagnostic &Diags,
const LangOptions &Features, const CompileOptions &compopts,
const std::string& infile, const std::string& outfile,
bool debug) :
Action(action),
CompileOpts(compopts),
InputFile(infile),
OutputFile(outfile),
GenerateDebugInfo(debug),
Gen(CreateLLVMCodeGen(Diags, Features, InputFile, GenerateDebugInfo)),
TheModule(0), TheTargetData(0), AsmOutStream(0), ModuleProvider(0),
CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}
~BackendConsumer() {
delete AsmOutStream;
delete TheTargetData;
delete ModuleProvider;
delete CodeGenPasses;
delete PerModulePasses;
delete PerFunctionPasses;
}
virtual void InitializeTU(TranslationUnit& TU) {
Gen->InitializeTU(TU);
TheModule = Gen->GetModule();
ModuleProvider = new ExistingModuleProvider(TheModule);
TheTargetData =
new llvm::TargetData(TU.getContext().Target.getTargetDescription());
}
virtual void HandleTopLevelDecl(Decl *D) {
Gen->HandleTopLevelDecl(D);
}
virtual void HandleTranslationUnit(TranslationUnit& TU) {
Gen->HandleTranslationUnit(TU);
EmitAssembly();
// Force a flush here in case we never get released.
if (AsmOutStream)
AsmOutStream->flush();
}
virtual void HandleTagDeclDefinition(TagDecl *D) {
Gen->HandleTagDeclDefinition(D);
}
};
}
FunctionPassManager *BackendConsumer::getCodeGenPasses() const {
if (!CodeGenPasses) {
CodeGenPasses = new FunctionPassManager(ModuleProvider);
CodeGenPasses->add(new TargetData(*TheTargetData));
}
return CodeGenPasses;
}
PassManager *BackendConsumer::getPerModulePasses() const {
if (!PerModulePasses) {
PerModulePasses = new PassManager();
PerModulePasses->add(new TargetData(*TheTargetData));
}
return PerModulePasses;
}
FunctionPassManager *BackendConsumer::getPerFunctionPasses() const {
if (!PerFunctionPasses) {
PerFunctionPasses = new FunctionPassManager(ModuleProvider);
PerFunctionPasses->add(new TargetData(*TheTargetData));
}
return PerFunctionPasses;
}
bool BackendConsumer::AddEmitPasses(std::string &Error) {
if (OutputFile == "-" || (InputFile == "-" && OutputFile.empty())) {
AsmOutStream = new raw_stdout_ostream();
sys::Program::ChangeStdoutToBinary();
} else {
if (OutputFile.empty()) {
llvm::sys::Path Path(InputFile);
Path.eraseSuffix();
if (Action == Backend_EmitBC) {
Path.appendSuffix("bc");
} else if (Action == Backend_EmitLL) {
Path.appendSuffix("ll");
} else {
Path.appendSuffix("s");
}
OutputFile = Path.toString();
}
AsmOutStream = new raw_fd_ostream(OutputFile.c_str(), true, Error);
if (!Error.empty())
return false;
}
if (Action == Backend_EmitBC) {
getPerModulePasses()->add(createBitcodeWriterPass(*AsmOutStream));
} else if (Action == Backend_EmitLL) {
getPerModulePasses()->add(createPrintModulePass(AsmOutStream));
} else {
bool Fast = CompileOpts.OptimizationLevel == 0;
// Create the TargetMachine for generating code.
const TargetMachineRegistry::entry *TME =
TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, Error);
if (!TME) {
Error = std::string("Unable to get target machine: ") + Error;
return false;
}
// FIXME: Support features?
std::string FeatureStr;
TargetMachine *TM = TME->CtorFn(*TheModule, FeatureStr);
// Set register scheduler & allocation policy.
RegisterScheduler::setDefault(createDefaultScheduler);
RegisterRegAlloc::setDefault(Fast ? createLocalRegisterAllocator :
createLinearScanRegisterAllocator);
// From llvm-gcc:
// If there are passes we have to run on the entire module, we do codegen
// as a separate "pass" after that happens.
// FIXME: This is disabled right now until bugs can be worked out. Reenable
// this for fast -O0 compiles!
FunctionPassManager *PM = getCodeGenPasses();
// Normal mode, emit a .s file by running the code generator.
// Note, this also adds codegenerator level optimization passes.
switch (TM->addPassesToEmitFile(*PM, *AsmOutStream,
TargetMachine::AssemblyFile, Fast)) {
default:
case FileModel::Error:
Error = "Unable to interface with target machine!\n";
return false;
case FileModel::AsmFile:
break;
}
if (TM->addPassesToEmitFileFinish(*CodeGenPasses, 0, Fast)) {
Error = "Unable to interface with target machine!\n";
return false;
}
}
return true;
}
void BackendConsumer::CreatePasses() {
// In -O0 if checking is disabled, we don't even have per-function passes.
if (CompileOpts.VerifyModule)
getPerFunctionPasses()->add(createVerifierPass());
if (CompileOpts.OptimizationLevel > 0) {
FunctionPassManager *PM = getPerFunctionPasses();
PM->add(createCFGSimplificationPass());
if (CompileOpts.OptimizationLevel == 1)
PM->add(createPromoteMemoryToRegisterPass());
else
PM->add(createScalarReplAggregatesPass());
PM->add(createInstructionCombiningPass());
}
// For now we always create per module passes.
PassManager *PM = getPerModulePasses();
if (CompileOpts.OptimizationLevel > 0) {
if (CompileOpts.UnitAtATime)
PM->add(createRaiseAllocationsPass()); // call %malloc -> malloc inst
PM->add(createCFGSimplificationPass()); // Clean up disgusting code
PM->add(createPromoteMemoryToRegisterPass()); // Kill useless allocas
if (CompileOpts.UnitAtATime) {
PM->add(createGlobalOptimizerPass()); // Optimize out global vars
PM->add(createGlobalDCEPass()); // Remove unused fns and globs
PM->add(createIPConstantPropagationPass()); // IP Constant Propagation
PM->add(createDeadArgEliminationPass()); // Dead argument elimination
}
PM->add(createInstructionCombiningPass()); // Clean up after IPCP & DAE
PM->add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
if (CompileOpts.UnitAtATime) {
PM->add(createPruneEHPass()); // Remove dead EH info
PM->add(createAddReadAttrsPass()); // Set readonly/readnone attrs
}
if (CompileOpts.InlineFunctions)
PM->add(createFunctionInliningPass()); // Inline small functions
else
PM->add(createAlwaysInlinerPass()); // Respect always_inline
if (CompileOpts.OptimizationLevel > 2)
PM->add(createArgumentPromotionPass()); // Scalarize uninlined fn args
if (CompileOpts.SimplifyLibCalls)
PM->add(createSimplifyLibCallsPass()); // Library Call Optimizations
PM->add(createInstructionCombiningPass()); // Cleanup for scalarrepl.
PM->add(createJumpThreadingPass()); // Thread jumps.
PM->add(createCFGSimplificationPass()); // Merge & remove BBs
PM->add(createScalarReplAggregatesPass()); // Break up aggregate allocas
PM->add(createInstructionCombiningPass()); // Combine silly seq's
PM->add(createCondPropagationPass()); // Propagate conditionals
PM->add(createTailCallEliminationPass()); // Eliminate tail calls
PM->add(createCFGSimplificationPass()); // Merge & remove BBs
PM->add(createReassociatePass()); // Reassociate expressions
PM->add(createLoopRotatePass()); // Rotate Loop
PM->add(createLICMPass()); // Hoist loop invariants
PM->add(createLoopUnswitchPass(CompileOpts.OptimizeSize ? true : false));
PM->add(createLoopIndexSplitPass()); // Split loop index
PM->add(createInstructionCombiningPass());
PM->add(createIndVarSimplifyPass()); // Canonicalize indvars
PM->add(createLoopDeletionPass()); // Delete dead loops
if (CompileOpts.UnrollLoops)
PM->add(createLoopUnrollPass()); // Unroll small loops
PM->add(createInstructionCombiningPass()); // Clean up after the unroller
PM->add(createGVNPass()); // Remove redundancies
PM->add(createMemCpyOptPass()); // Remove memcpy / form memset
PM->add(createSCCPPass()); // Constant prop with SCCP
// Run instcombine after redundancy elimination to exploit opportunities
// opened up by them.
PM->add(createInstructionCombiningPass());
PM->add(createCondPropagationPass()); // Propagate conditionals
PM->add(createDeadStoreEliminationPass()); // Delete dead stores
PM->add(createAggressiveDCEPass()); // Delete dead instructions
PM->add(createCFGSimplificationPass()); // Merge & remove BBs
if (CompileOpts.UnitAtATime) {
PM->add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
PM->add(createDeadTypeEliminationPass()); // Eliminate dead types
}
if (CompileOpts.OptimizationLevel > 1 && CompileOpts.UnitAtATime)
PM->add(createConstantMergePass()); // Merge dup global constants
} else {
PM->add(createAlwaysInlinerPass());
}
}
/// EmitAssembly - Handle interaction with LLVM backend to generate
/// actual machine code.
void BackendConsumer::EmitAssembly() {
// Silently ignore if we weren't initialized for some reason.
if (!TheModule || !TheTargetData)
return;
// Make sure IR generation is happy with the module. This is
// released by the module provider.
Module *M = Gen->ReleaseModule();
if (!M) {
// The module has been released by IR gen on failures, do not
// double free.
ModuleProvider->releaseModule();
TheModule = 0;
return;
}
assert(TheModule == M && "Unexpected module change during IR generation");
CreatePasses();
std::string Error;
if (!AddEmitPasses(Error)) {
// FIXME: Don't fail this way.
llvm::cerr << "ERROR: " << Error << "\n";
::exit(1);
}
// Run passes. For now we do all passes at once, but eventually we
// would like to have the option of streaming code generation.
if (PerFunctionPasses) {
PerFunctionPasses->doInitialization();
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
if (!I->isDeclaration())
PerFunctionPasses->run(*I);
PerFunctionPasses->doFinalization();
}
if (PerModulePasses)
PerModulePasses->run(*M);
if (CodeGenPasses) {
CodeGenPasses->doInitialization();
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
if (!I->isDeclaration())
CodeGenPasses->run(*I);
CodeGenPasses->doFinalization();
}
}
ASTConsumer *clang::CreateBackendConsumer(BackendAction Action,
Diagnostic &Diags,
const LangOptions &Features,
const CompileOptions &CompileOpts,
const std::string& InFile,
const std::string& OutFile,
bool GenerateDebugInfo) {
return new BackendConsumer(Action, Diags, Features, CompileOpts,
InFile, OutFile, GenerateDebugInfo);
}
|
//===--- Backend.cpp - Interface to LLVM backend technologies -------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "ASTConsumers.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/TranslationUnit.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/CodeGen/ModuleBuilder.h"
#include "clang/Driver/CompileOptions.h"
#include "llvm/Module.h"
#include "llvm/ModuleProvider.h"
#include "llvm/PassManager.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/Assembly/PrintModulePass.h"
#include "llvm/Analysis/CallGraph.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/CodeGen/RegAllocRegistry.h"
#include "llvm/CodeGen/SchedulerRegistry.h"
#include "llvm/CodeGen/ScheduleDAGSDNodes.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Compiler.h"
#include "llvm/System/Path.h"
#include "llvm/System/Program.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Target/TargetMachineRegistry.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/IPO.h"
using namespace clang;
using namespace llvm;
namespace {
class VISIBILITY_HIDDEN BackendConsumer : public ASTConsumer {
BackendAction Action;
CompileOptions CompileOpts;
const std::string &InputFile;
std::string OutputFile;
bool GenerateDebugInfo;
llvm::OwningPtr<CodeGenerator> Gen;
llvm::Module *TheModule;
llvm::TargetData *TheTargetData;
llvm::raw_ostream *AsmOutStream;
mutable llvm::ModuleProvider *ModuleProvider;
mutable FunctionPassManager *CodeGenPasses;
mutable PassManager *PerModulePasses;
mutable FunctionPassManager *PerFunctionPasses;
FunctionPassManager *getCodeGenPasses() const;
PassManager *getPerModulePasses() const;
FunctionPassManager *getPerFunctionPasses() const;
void CreatePasses();
/// AddEmitPasses - Add passes necessary to emit assembly or LLVM
/// IR.
///
/// \return True on success. On failure \arg Error will be set to
/// a user readable error message.
bool AddEmitPasses(std::string &Error);
void EmitAssembly();
public:
BackendConsumer(BackendAction action, Diagnostic &Diags,
const LangOptions &Features, const CompileOptions &compopts,
const std::string& infile, const std::string& outfile,
bool debug) :
Action(action),
CompileOpts(compopts),
InputFile(infile),
OutputFile(outfile),
GenerateDebugInfo(debug),
Gen(CreateLLVMCodeGen(Diags, Features, InputFile, GenerateDebugInfo)),
TheModule(0), TheTargetData(0), AsmOutStream(0), ModuleProvider(0),
CodeGenPasses(0), PerModulePasses(0), PerFunctionPasses(0) {}
~BackendConsumer() {
delete AsmOutStream;
delete TheTargetData;
delete ModuleProvider;
delete CodeGenPasses;
delete PerModulePasses;
delete PerFunctionPasses;
}
virtual void InitializeTU(TranslationUnit& TU) {
Gen->InitializeTU(TU);
TheModule = Gen->GetModule();
ModuleProvider = new ExistingModuleProvider(TheModule);
TheTargetData =
new llvm::TargetData(TU.getContext().Target.getTargetDescription());
}
virtual void HandleTopLevelDecl(Decl *D) {
Gen->HandleTopLevelDecl(D);
}
virtual void HandleTranslationUnit(TranslationUnit& TU) {
Gen->HandleTranslationUnit(TU);
EmitAssembly();
// Force a flush here in case we never get released.
if (AsmOutStream)
AsmOutStream->flush();
}
virtual void HandleTagDeclDefinition(TagDecl *D) {
Gen->HandleTagDeclDefinition(D);
}
};
}
FunctionPassManager *BackendConsumer::getCodeGenPasses() const {
if (!CodeGenPasses) {
CodeGenPasses = new FunctionPassManager(ModuleProvider);
CodeGenPasses->add(new TargetData(*TheTargetData));
}
return CodeGenPasses;
}
PassManager *BackendConsumer::getPerModulePasses() const {
if (!PerModulePasses) {
PerModulePasses = new PassManager();
PerModulePasses->add(new TargetData(*TheTargetData));
}
return PerModulePasses;
}
FunctionPassManager *BackendConsumer::getPerFunctionPasses() const {
if (!PerFunctionPasses) {
PerFunctionPasses = new FunctionPassManager(ModuleProvider);
PerFunctionPasses->add(new TargetData(*TheTargetData));
}
return PerFunctionPasses;
}
bool BackendConsumer::AddEmitPasses(std::string &Error) {
if (OutputFile == "-" || (InputFile == "-" && OutputFile.empty())) {
AsmOutStream = new raw_stdout_ostream();
sys::Program::ChangeStdoutToBinary();
} else {
if (OutputFile.empty()) {
llvm::sys::Path Path(InputFile);
Path.eraseSuffix();
if (Action == Backend_EmitBC) {
Path.appendSuffix("bc");
} else if (Action == Backend_EmitLL) {
Path.appendSuffix("ll");
} else {
Path.appendSuffix("s");
}
OutputFile = Path.toString();
}
AsmOutStream = new raw_fd_ostream(OutputFile.c_str(), true, Error);
if (!Error.empty())
return false;
}
if (Action == Backend_EmitBC) {
getPerModulePasses()->add(createBitcodeWriterPass(*AsmOutStream));
} else if (Action == Backend_EmitLL) {
getPerModulePasses()->add(createPrintModulePass(AsmOutStream));
} else {
bool Fast = CompileOpts.OptimizationLevel == 0;
// Create the TargetMachine for generating code.
const TargetMachineRegistry::entry *TME =
TargetMachineRegistry::getClosestStaticTargetForModule(*TheModule, Error);
if (!TME) {
Error = std::string("Unable to get target machine: ") + Error;
return false;
}
// FIXME: Support features?
std::string FeatureStr;
TargetMachine *TM = TME->CtorFn(*TheModule, FeatureStr);
// Set register scheduler & allocation policy.
RegisterScheduler::setDefault(createDefaultScheduler);
RegisterRegAlloc::setDefault(Fast ? createLocalRegisterAllocator :
createLinearScanRegisterAllocator);
// From llvm-gcc:
// If there are passes we have to run on the entire module, we do codegen
// as a separate "pass" after that happens.
// FIXME: This is disabled right now until bugs can be worked out. Reenable
// this for fast -O0 compiles!
FunctionPassManager *PM = getCodeGenPasses();
// Normal mode, emit a .s file by running the code generator.
// Note, this also adds codegenerator level optimization passes.
switch (TM->addPassesToEmitFile(*PM, *AsmOutStream,
TargetMachine::AssemblyFile, Fast)) {
default:
case FileModel::Error:
Error = "Unable to interface with target machine!\n";
return false;
case FileModel::AsmFile:
break;
}
if (TM->addPassesToEmitFileFinish(*CodeGenPasses, 0, Fast)) {
Error = "Unable to interface with target machine!\n";
return false;
}
}
return true;
}
void BackendConsumer::CreatePasses() {
// In -O0 if checking is disabled, we don't even have per-function passes.
if (CompileOpts.VerifyModule)
getPerFunctionPasses()->add(createVerifierPass());
if (CompileOpts.OptimizationLevel > 0) {
FunctionPassManager *PM = getPerFunctionPasses();
PM->add(createCFGSimplificationPass());
if (CompileOpts.OptimizationLevel == 1)
PM->add(createPromoteMemoryToRegisterPass());
else
PM->add(createScalarReplAggregatesPass());
PM->add(createInstructionCombiningPass());
}
// For now we always create per module passes.
PassManager *PM = getPerModulePasses();
if (CompileOpts.OptimizationLevel > 0) {
if (CompileOpts.UnitAtATime)
PM->add(createRaiseAllocationsPass()); // call %malloc -> malloc inst
PM->add(createCFGSimplificationPass()); // Clean up disgusting code
PM->add(createPromoteMemoryToRegisterPass()); // Kill useless allocas
if (CompileOpts.UnitAtATime) {
PM->add(createGlobalOptimizerPass()); // Optimize out global vars
PM->add(createGlobalDCEPass()); // Remove unused fns and globs
PM->add(createIPConstantPropagationPass()); // IP Constant Propagation
PM->add(createDeadArgEliminationPass()); // Dead argument elimination
}
PM->add(createInstructionCombiningPass()); // Clean up after IPCP & DAE
PM->add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
if (CompileOpts.UnitAtATime) {
PM->add(createPruneEHPass()); // Remove dead EH info
PM->add(createAddReadAttrsPass()); // Set readonly/readnone attrs
}
if (CompileOpts.InlineFunctions)
PM->add(createFunctionInliningPass()); // Inline small functions
else
PM->add(createAlwaysInlinerPass()); // Respect always_inline
if (CompileOpts.OptimizationLevel > 2)
PM->add(createArgumentPromotionPass()); // Scalarize uninlined fn args
if (CompileOpts.SimplifyLibCalls)
PM->add(createSimplifyLibCallsPass()); // Library Call Optimizations
PM->add(createInstructionCombiningPass()); // Cleanup for scalarrepl.
PM->add(createJumpThreadingPass()); // Thread jumps.
PM->add(createCFGSimplificationPass()); // Merge & remove BBs
PM->add(createScalarReplAggregatesPass()); // Break up aggregate allocas
PM->add(createInstructionCombiningPass()); // Combine silly seq's
PM->add(createCondPropagationPass()); // Propagate conditionals
PM->add(createTailCallEliminationPass()); // Eliminate tail calls
PM->add(createCFGSimplificationPass()); // Merge & remove BBs
PM->add(createReassociatePass()); // Reassociate expressions
PM->add(createLoopRotatePass()); // Rotate Loop
PM->add(createLICMPass()); // Hoist loop invariants
PM->add(createLoopUnswitchPass(CompileOpts.OptimizeSize ? true : false));
// PM->add(createLoopIndexSplitPass()); // Split loop index
PM->add(createInstructionCombiningPass());
PM->add(createIndVarSimplifyPass()); // Canonicalize indvars
PM->add(createLoopDeletionPass()); // Delete dead loops
if (CompileOpts.UnrollLoops)
PM->add(createLoopUnrollPass()); // Unroll small loops
PM->add(createInstructionCombiningPass()); // Clean up after the unroller
PM->add(createGVNPass()); // Remove redundancies
PM->add(createMemCpyOptPass()); // Remove memcpy / form memset
PM->add(createSCCPPass()); // Constant prop with SCCP
// Run instcombine after redundancy elimination to exploit opportunities
// opened up by them.
PM->add(createInstructionCombiningPass());
PM->add(createCondPropagationPass()); // Propagate conditionals
PM->add(createDeadStoreEliminationPass()); // Delete dead stores
PM->add(createAggressiveDCEPass()); // Delete dead instructions
PM->add(createCFGSimplificationPass()); // Merge & remove BBs
if (CompileOpts.UnitAtATime) {
PM->add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
PM->add(createDeadTypeEliminationPass()); // Eliminate dead types
}
if (CompileOpts.OptimizationLevel > 1 && CompileOpts.UnitAtATime)
PM->add(createConstantMergePass()); // Merge dup global constants
} else {
PM->add(createAlwaysInlinerPass());
}
}
/// EmitAssembly - Handle interaction with LLVM backend to generate
/// actual machine code.
void BackendConsumer::EmitAssembly() {
// Silently ignore if we weren't initialized for some reason.
if (!TheModule || !TheTargetData)
return;
// Make sure IR generation is happy with the module. This is
// released by the module provider.
Module *M = Gen->ReleaseModule();
if (!M) {
// The module has been released by IR gen on failures, do not
// double free.
ModuleProvider->releaseModule();
TheModule = 0;
return;
}
assert(TheModule == M && "Unexpected module change during IR generation");
CreatePasses();
std::string Error;
if (!AddEmitPasses(Error)) {
// FIXME: Don't fail this way.
llvm::cerr << "ERROR: " << Error << "\n";
::exit(1);
}
// Run passes. For now we do all passes at once, but eventually we
// would like to have the option of streaming code generation.
if (PerFunctionPasses) {
PerFunctionPasses->doInitialization();
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
if (!I->isDeclaration())
PerFunctionPasses->run(*I);
PerFunctionPasses->doFinalization();
}
if (PerModulePasses)
PerModulePasses->run(*M);
if (CodeGenPasses) {
CodeGenPasses->doInitialization();
for (Module::iterator I = M->begin(), E = M->end(); I != E; ++I)
if (!I->isDeclaration())
CodeGenPasses->run(*I);
CodeGenPasses->doFinalization();
}
}
ASTConsumer *clang::CreateBackendConsumer(BackendAction Action,
Diagnostic &Diags,
const LangOptions &Features,
const CompileOptions &CompileOpts,
const std::string& InFile,
const std::string& OutFile,
bool GenerateDebugInfo) {
return new BackendConsumer(Action, Diags, Features, CompileOpts,
InFile, OutFile, GenerateDebugInfo);
}
|
Disable -loop-index-split for now.
|
Disable -loop-index-split for now.
git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@60089 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang
|
9a6a3bd2c9f40ecbb34359db04722a5a6b8f6710
|
src/test/unit/lang/parser/pound_comment_deprecated_test.cpp
|
src/test/unit/lang/parser/pound_comment_deprecated_test.cpp
|
#include <gtest/gtest.h>
#include <test/unit/lang/utility.hpp>
TEST(langParser, poundCommentDeprecated) {
test_warning("pound-comment-deprecated",
"Comments beginning with # are deprecated."
" Please use //");
}
|
#include <gtest/gtest.h>
#include <test/unit/lang/utility.hpp>
TEST(langParser, poundCommentDeprecated) {
test_warning("pound-comment-deprecated",
"Comments beginning with # are deprecated."
" Please use //");
}
|
Update pound_comment_deprecated_test.cpp
|
Update pound_comment_deprecated_test.cpp
|
C++
|
bsd-3-clause
|
stan-dev/stan,stan-dev/stan,stan-dev/stan,stan-dev/stan,stan-dev/stan
|
bcd4a73874216dca3f5983a0b2d4b843ce71f34a
|
src/xercesc/util/MsgLoaders/MsgCatalog/MsgCatalogLoader.cpp
|
src/xercesc/util/MsgLoaders/MsgCatalog/MsgCatalogLoader.cpp
|
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.8 2002/12/02 21:58:43 peiyongz
* nls support
*
* Revision 1.7 2002/11/12 17:27:12 tng
* DOM Message: add new domain for DOM Messages.
*
* Revision 1.6 2002/11/05 16:54:46 peiyongz
* Using XERCESC_NLS_HOME
*
* Revision 1.5 2002/11/04 15:10:41 tng
* C++ Namespace Support.
*
* Revision 1.4 2002/09/24 19:58:33 tng
* Performance: use XMLString::equals instead of XMLString::compareString
*
* Revision 1.3 2002/09/23 21:05:40 peiyongz
* remove debugging code
*
* Revision 1.2 2002/09/23 21:03:06 peiyongz
* Build MsgCatalog on Solaris
*
* Revision 1.1.1.1 2002/02/01 22:22:21 peiyongz
* sane_include
*
* Revision 1.7 2001/10/09 12:19:44 tng
* Leak fix: can call transcode directly instead of using copyString.
*
* Revision 1.6 2000/07/25 22:28:40 aruna1
* Char definitions in XMLUni moved to XMLUniDefs
*
* Revision 1.5 2000/03/02 19:55:16 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.4 2000/02/06 07:48:22 rahulj
* Year 2K copyright swat.
*
* Revision 1.3 2000/01/05 22:00:22 aruna1
* Modified message 'set' attribute reading sequence. Removed dependencies on hard coded constants
*
* Revision 1.2 1999/12/23 01:43:37 aruna1
* MsgCatalog support added for solaris
*
* Revision 1.1.1.1 1999/11/09 01:07:16 twl
* Initial checkin
*
* Revision 1.2 1999/11/08 20:45:27 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLMsgLoader.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/XMLUni.hpp>
#include "MsgCatalogLoader.hpp"
#include "XMLMsgCat_Ids.hpp"
#include <locale.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Public Constructors and Destructor
// ---------------------------------------------------------------------------
MsgCatalogLoader::MsgCatalogLoader(const XMLCh* const msgDomain)
:fCatalogHandle(0)
,fMsgSet(0)
{
if (!XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain)
&& !XMLString::equals(msgDomain, XMLUni::fgExceptDomain)
&& !XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain)
&& !XMLString::equals(msgDomain, XMLUni::fgValidityDomain))
{
XMLPlatformUtils::panic(XMLPlatformUtils::Panic_UnknownMsgDomain);
}
// Prepare the path info
char catpath[1024];
memset(catpath, 0, sizeof catpath);
char *nlsHome = getenv("XERCESC_NLS_HOME");
if (nlsHome)
{
strcpy(catpath, nlsHome);
strcat(catpath, "/msg/");
}
// Prepare user-specified locale specific cat file
char catuser[1024];
memset(catuser, 0, sizeof catuser);
strcpy(catuser, catpath);
strcat(catuser, "XMLMessages_");
strcat(catuser, XMLMsgLoader::getLocale());
strcat(catuser, ".cat");
char catdefault[1024];
memset(catdefault, 0, sizeof catdefault);
strcpy(catdefault, catpath);
strcat(catdefault, "XMLMessages_en_US.cat");
/**
* To open user-specified locale specific cat file
* and default cat file if necessary
*/
if ( ((int)(fCatalogHandle=catopen(catuser, 0)) == -1) &&
((int)(fCatalogHandle=catopen(catdefault, 0)) == -1) )
{
// Probably have to call panic here
printf("Could not open catalog:\n %s\n or %s\n", catuser, catdefault);
exit(1);
}
if (XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain))
fMsgSet = CatId_XMLErrs;
else if (XMLString::equals(msgDomain, XMLUni::fgExceptDomain))
fMsgSet = CatId_XMLExcepts;
else if (XMLString::equals(msgDomain, XMLUni::fgValidityDomain))
fMsgSet = CatId_XMLValid;
else if (XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain))
fMsgSet = CatId_XMLDOMMsg;
}
MsgCatalogLoader::~MsgCatalogLoader()
{
catclose(fCatalogHandle);
}
// ---------------------------------------------------------------------------
// Implementation of the virtual message loader API
// ---------------------------------------------------------------------------
bool MsgCatalogLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars)
{
char msgString[100];
sprintf(msgString, "Could not find message ID %d from message set %d\n", msgToLoad, fMsgSet);
char* catMessage = catgets( fCatalogHandle, fMsgSet, (int)msgToLoad, msgString);
// catgets returns a pointer to msgString if it fails to locate the message
// from the message catalog
if (XMLString::equals(catMessage, msgString))
return false;
else
{
XMLString::transcode(catMessage, toFill, maxChars);
return true;
}
}
bool MsgCatalogLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars
, const XMLCh* const repText1
, const XMLCh* const repText2
, const XMLCh* const repText3
, const XMLCh* const repText4)
{
// Call the other version to load up the message
if (!loadMsg(msgToLoad, toFill, maxChars))
return false;
// And do the token replacement
XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4);
return true;
}
bool MsgCatalogLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars
, const char* const repText1
, const char* const repText2
, const char* const repText3
, const char* const repText4)
{
//
// Transcode the provided parameters and call the other version,
// which will do the replacement work.
//
XMLCh* tmp1 = 0;
XMLCh* tmp2 = 0;
XMLCh* tmp3 = 0;
XMLCh* tmp4 = 0;
bool bRet = false;
if (repText1)
tmp1 = XMLString::transcode(repText1);
if (repText2)
tmp2 = XMLString::transcode(repText2);
if (repText3)
tmp3 = XMLString::transcode(repText3);
if (repText4)
tmp4 = XMLString::transcode(repText4);
bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4);
if (tmp1)
delete [] tmp1;
if (tmp2)
delete [] tmp2;
if (tmp3)
delete [] tmp3;
if (tmp4)
delete [] tmp4;
return bRet;
}
XERCES_CPP_NAMESPACE_END
|
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.9 2002/12/04 18:03:13 peiyongz
* use $XERCESCROOT to search for msg catalog file if XERCESC_NLS_HOME
* undefined
*
* Revision 1.8 2002/12/02 21:58:43 peiyongz
* nls support
*
* Revision 1.7 2002/11/12 17:27:12 tng
* DOM Message: add new domain for DOM Messages.
*
* Revision 1.6 2002/11/05 16:54:46 peiyongz
* Using XERCESC_NLS_HOME
*
* Revision 1.5 2002/11/04 15:10:41 tng
* C++ Namespace Support.
*
* Revision 1.4 2002/09/24 19:58:33 tng
* Performance: use XMLString::equals instead of XMLString::compareString
*
* Revision 1.3 2002/09/23 21:05:40 peiyongz
* remove debugging code
*
* Revision 1.2 2002/09/23 21:03:06 peiyongz
* Build MsgCatalog on Solaris
*
* Revision 1.1.1.1 2002/02/01 22:22:21 peiyongz
* sane_include
*
* Revision 1.7 2001/10/09 12:19:44 tng
* Leak fix: can call transcode directly instead of using copyString.
*
* Revision 1.6 2000/07/25 22:28:40 aruna1
* Char definitions in XMLUni moved to XMLUniDefs
*
* Revision 1.5 2000/03/02 19:55:16 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.4 2000/02/06 07:48:22 rahulj
* Year 2K copyright swat.
*
* Revision 1.3 2000/01/05 22:00:22 aruna1
* Modified message 'set' attribute reading sequence. Removed dependencies on hard coded constants
*
* Revision 1.2 1999/12/23 01:43:37 aruna1
* MsgCatalog support added for solaris
*
* Revision 1.1.1.1 1999/11/09 01:07:16 twl
* Initial checkin
*
* Revision 1.2 1999/11/08 20:45:27 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLMsgLoader.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/XMLUni.hpp>
#include "MsgCatalogLoader.hpp"
#include "XMLMsgCat_Ids.hpp"
#include <locale.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Public Constructors and Destructor
// ---------------------------------------------------------------------------
MsgCatalogLoader::MsgCatalogLoader(const XMLCh* const msgDomain)
:fCatalogHandle(0)
,fMsgSet(0)
{
if (!XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain)
&& !XMLString::equals(msgDomain, XMLUni::fgExceptDomain)
&& !XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain)
&& !XMLString::equals(msgDomain, XMLUni::fgValidityDomain))
{
XMLPlatformUtils::panic(XMLPlatformUtils::Panic_UnknownMsgDomain);
}
// Prepare the path info
char catpath[1024];
memset(catpath, 0, sizeof catpath);
char *nlsHome = getenv("XERCESC_NLS_HOME");
if (nlsHome)
{
strcpy(catpath, nlsHome);
strcat(catpath, "/msg/");
}
else
{
char *altHome = getenv("XERCESCROOT");
if (altHome)
{
strcpy(catpath, altHome);
strcat(catpath, "/lib/msg/");
}
}
// Prepare user-specified locale specific cat file
char catuser[1024];
memset(catuser, 0, sizeof catuser);
strcpy(catuser, catpath);
strcat(catuser, "XMLMessages_");
strcat(catuser, XMLMsgLoader::getLocale());
strcat(catuser, ".cat");
char catdefault[1024];
memset(catdefault, 0, sizeof catdefault);
strcpy(catdefault, catpath);
strcat(catdefault, "XMLMessages_en_US.cat");
/**
* To open user-specified locale specific cat file
* and default cat file if necessary
*/
if ( ((int)(fCatalogHandle=catopen(catuser, 0)) == -1) &&
((int)(fCatalogHandle=catopen(catdefault, 0)) == -1) )
{
// Probably have to call panic here
printf("Could not open catalog:\n %s\n or %s\n", catuser, catdefault);
exit(1);
}
if (XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain))
fMsgSet = CatId_XMLErrs;
else if (XMLString::equals(msgDomain, XMLUni::fgExceptDomain))
fMsgSet = CatId_XMLExcepts;
else if (XMLString::equals(msgDomain, XMLUni::fgValidityDomain))
fMsgSet = CatId_XMLValid;
else if (XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain))
fMsgSet = CatId_XMLDOMMsg;
}
MsgCatalogLoader::~MsgCatalogLoader()
{
catclose(fCatalogHandle);
}
// ---------------------------------------------------------------------------
// Implementation of the virtual message loader API
// ---------------------------------------------------------------------------
bool MsgCatalogLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars)
{
char msgString[100];
sprintf(msgString, "Could not find message ID %d from message set %d\n", msgToLoad, fMsgSet);
char* catMessage = catgets( fCatalogHandle, fMsgSet, (int)msgToLoad, msgString);
// catgets returns a pointer to msgString if it fails to locate the message
// from the message catalog
if (XMLString::equals(catMessage, msgString))
return false;
else
{
XMLString::transcode(catMessage, toFill, maxChars);
return true;
}
}
bool MsgCatalogLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars
, const XMLCh* const repText1
, const XMLCh* const repText2
, const XMLCh* const repText3
, const XMLCh* const repText4)
{
// Call the other version to load up the message
if (!loadMsg(msgToLoad, toFill, maxChars))
return false;
// And do the token replacement
XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4);
return true;
}
bool MsgCatalogLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars
, const char* const repText1
, const char* const repText2
, const char* const repText3
, const char* const repText4)
{
//
// Transcode the provided parameters and call the other version,
// which will do the replacement work.
//
XMLCh* tmp1 = 0;
XMLCh* tmp2 = 0;
XMLCh* tmp3 = 0;
XMLCh* tmp4 = 0;
bool bRet = false;
if (repText1)
tmp1 = XMLString::transcode(repText1);
if (repText2)
tmp2 = XMLString::transcode(repText2);
if (repText3)
tmp3 = XMLString::transcode(repText3);
if (repText4)
tmp4 = XMLString::transcode(repText4);
bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4);
if (tmp1)
delete [] tmp1;
if (tmp2)
delete [] tmp2;
if (tmp3)
delete [] tmp3;
if (tmp4)
delete [] tmp4;
return bRet;
}
XERCES_CPP_NAMESPACE_END
|
use $XERCESCROOT to search for msg catalog file if XERCESC_NLS_HOME undefined
|
use $XERCESCROOT to search for msg catalog file if XERCESC_NLS_HOME
undefined
git-svn-id: 3ec853389310512053d525963cab269c063bb453@174458 13f79535-47bb-0310-9956-ffa450edef68
|
C++
|
apache-2.0
|
AaronNGray/xerces,AaronNGray/xerces,AaronNGray/xerces,AaronNGray/xerces
|
ca5336e974e2eeac15b39da2e3daf98485c50980
|
tests/auto/declarative_core/backend/routing/tst_routing.cpp
|
tests/auto/declarative_core/backend/routing/tst_routing.cpp
|
/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QtQuickTest/quicktest.h>
#include <QFile>
#define TESTNAME "routing backend tests"
QT_USE_NAMESPACE
// Empty tests so we can pick up the test results even if backend tests don't run
class tst_routing : public QObject
{
Q_OBJECT
};
int main(int argc, char **argv)
{
// We only want to run these tests in build configuration on Linux x86
#if (defined(Q_OS_LINUX) && defined(Q_PROCESSOR_X86_32)) || defined(QTLOCATION_BACKEND_TESTS)
const QString configurationFile = QStringLiteral("/var/lib/qt/qtlocation_tests_configuration.js");
if (QFile::exists(configurationFile))
return quick_test_main(argc, argv, TESTNAME, 0, QUICK_TEST_SOURCE_DIR);
qWarning("File '/var/lib/qt/qtlocation_tests_configuration.js' does not exist.");
qWarning("Not running tests.");
#else
qWarning("Not configured to run '" TESTNAME "'!");
#endif
tst_routing tc;
return QTest::qExec(&tc, argc, argv);
}
#include "tst_routing.moc"
|
/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <QtQuickTest/quicktest.h>
#include <QFile>
#define TESTNAME "routing backend tests"
QT_USE_NAMESPACE
// Empty tests so we can pick up the test results even if backend tests don't run
class tst_routing : public QObject
{
Q_OBJECT
};
int main(int argc, char **argv)
{
// We only want to run these tests in build configuration on Linux x86
#if (defined(Q_OS_LINUX) && defined(Q_PROCESSOR_X86_32)) || defined(QTLOCATION_BACKEND_TESTS)
const QString configurationFile = QStringLiteral("/var/lib/qt/qtlocation_tests_configuration.js");
if (QFile::exists(configurationFile))
return quick_test_main(argc, argv, TESTNAME, QUICK_TEST_SOURCE_DIR);
qWarning("File '/var/lib/qt/qtlocation_tests_configuration.js' does not exist.");
qWarning("Not running tests.");
#else
qWarning("Not configured to run '" TESTNAME "'!");
#endif
tst_routing tc;
return QTest::qExec(&tc, argc, argv);
}
#include "tst_routing.moc"
|
Adjust use of quick_test_main to match new API
|
Adjust use of quick_test_main to match new API
Fixes current build issue (hopefully).
Change-Id: Id4e8bf81353971fd725c55fbb03e29dce7e99afd
Reviewed-by: Aaron McCarthy <[email protected]>
|
C++
|
lgpl-2.1
|
kobolabs/qtlocation,amccarthy/qtlocation,amccarthy/qtlocation,amccarthy/qtlocation,kobolabs/qtlocation,kobolabs/qtlocation
|
c1970d9b8476f68dcaa6306f503544b260e1f331
|
parser_simple.hpp
|
parser_simple.hpp
|
//----------------------------------------------------------------------------
// copyright 2012, 2013, 2014 Keean Schupke
// compile with -std=gnu++11
// parser_simple.hpp
#include <istream>
#include <stdexcept>
using namespace std;
//----------------------------------------------------------------------------
// Character Predicates
struct char_pred {
string const name;
char_pred(string const n) : name(n) {}
virtual bool operator() (int const c) const = 0;
};
struct is_space : public char_pred {
is_space() : char_pred("space") {}
virtual bool operator() (int const c) const override {
return ::isspace(c) != 0;
}
} is_space;
struct is_digit : public char_pred {
is_digit() : char_pred("digit") {}
virtual bool operator() (int const c) const override {
return ::isdigit(c) != 0;
}
} is_digit;
struct is_upper : public char_pred {
is_upper() : char_pred("uppercase") {}
virtual bool operator() (int const c) const override {
return ::isupper(c) != 0;
}
} is_upper;
struct is_lower : public char_pred {
is_lower() : char_pred("lowercase") {}
virtual bool operator() (int const c) const override {
return ::islower(c) != 0;
}
} is_lower;
struct is_alpha : public char_pred {
is_alpha() : char_pred("alphabetic") {}
virtual bool operator() (int const c) const override {
return ::isalpha(c) != 0;
}
} is_alpha;
struct is_alnum : public char_pred {
is_alnum() : char_pred("alphanumeric") {}
virtual bool operator() (int const c) const override {
return ::isalnum(c) != 0;
}
} is_alnum;
struct is_print : public char_pred {
is_print() : char_pred("printable") {}
virtual bool operator() (int const c) const override {
return ::isprint(c) != 0;
}
} is_print;
class is_char : public char_pred {
int const k;
public:
explicit is_char(char const c)
: k(c), char_pred("'" + string(1, c) + "'") {}
virtual bool operator() (int const c) const override {
return k == c;
}
};
class is_either : public char_pred {
char_pred const &a;
char_pred const &b;
public:
is_either(char_pred const &a, char_pred const& b)
: a(a), b(b), char_pred("(" + a.name + " or " + b.name + ")") {}
bool operator() (int const c) const {
return a(c) || b(c);
}
};
class is_not : public char_pred {
char_pred const &a;
public:
explicit is_not(char_pred const &a)
: a(a), char_pred("~" + a.name) {}
bool operator() (int const c) const {
return !a(c);
}
};
is_char const is_minus('-');
//----------------------------------------------------------------------------
// Recursive Descent Parser
struct parse_error : public runtime_error {
int const row;
int const col;
int const sym;
string const exp;
parse_error(string const& what, int row, int col, string exp, int sym)
: runtime_error(what), row(row), col(col), exp(move(exp)), sym(sym) {}
};
class parser {
streambuf *in;
int count;
int row;
int col;
int sym;
void error(string const& err, string const exp) {
throw parse_error(err, row, col, exp, sym);
}
void next() {
sym = in->sgetc();
in->snextc();
++count;
if (sym == '\n') {
++row;
col = 1;
} else if (::isprint(sym)) {
++col;
}
}
public:
parser(istream &f) : in(f.rdbuf()), row(1), col(1), sym(in->sbumpc()) {}
protected:
int get_col() {
return col;
}
int get_row() {
return row;
}
int get_count() {
return count;
}
bool accept(char_pred const &t, string *s = nullptr) {
if (!t(sym)) {
return false;
}
if (s != nullptr) {
s->push_back(sym);
}
next();
return true;
}
bool expect(char_pred const &t, string *s = nullptr) {
if (!t(sym)) {
error("expected", t.name);
}
if (s != nullptr) {
s->push_back(sym);
}
next();
return true;
}
bool space(string *s = nullptr) {
if (accept(is_space)) {
if (s != nullptr) {
s->push_back(' ');
}
while (accept(is_space));
return true;
}
return false;
}
bool number(string *s = nullptr) {
if (accept(is_digit, s)) {
while (accept(is_digit, s));
return true;
}
return false;
}
bool signed_number(string *s = nullptr) {
return accept(is_minus, s), number(s);
}
bool name(string *s = nullptr) {
if (accept(is_alpha, s)) {
while (accept(is_alnum, s));
return true;
}
return false;
}
};
|
//----------------------------------------------------------------------------
// copyright 2012, 2013, 2014 Keean Schupke
// compile with -std=gnu++11
// parser_simple.hpp
#include <istream>
#include <stdexcept>
using namespace std;
//----------------------------------------------------------------------------
// Character Predicates
struct char_pred {
string const name;
char_pred(string const n) : name(n) {}
virtual bool operator() (int const c) const = 0;
};
struct is_space : public char_pred {
is_space() : char_pred("space") {}
virtual bool operator() (int const c) const override {
return ::isspace(c) != 0;
}
} is_space;
struct is_digit : public char_pred {
is_digit() : char_pred("digit") {}
virtual bool operator() (int const c) const override {
return ::isdigit(c) != 0;
}
} is_digit;
struct is_upper : public char_pred {
is_upper() : char_pred("uppercase") {}
virtual bool operator() (int const c) const override {
return ::isupper(c) != 0;
}
} is_upper;
struct is_lower : public char_pred {
is_lower() : char_pred("lowercase") {}
virtual bool operator() (int const c) const override {
return ::islower(c) != 0;
}
} is_lower;
struct is_alpha : public char_pred {
is_alpha() : char_pred("alphabetic") {}
virtual bool operator() (int const c) const override {
return ::isalpha(c) != 0;
}
} is_alpha;
struct is_alnum : public char_pred {
is_alnum() : char_pred("alphanumeric") {}
virtual bool operator() (int const c) const override {
return ::isalnum(c) != 0;
}
} is_alnum;
struct is_print : public char_pred {
is_print() : char_pred("printable") {}
virtual bool operator() (int const c) const override {
return ::isprint(c) != 0;
}
} is_print;
class is_char : public char_pred {
int const k;
public:
explicit is_char(char const c)
: k(c), char_pred("'" + string(1, c) + "'") {}
virtual bool operator() (int const c) const override {
return k == c;
}
};
class is_either : public char_pred {
char_pred const &a;
char_pred const &b;
public:
is_either(char_pred const &a, char_pred const& b)
: a(a), b(b), char_pred("(" + a.name + " or " + b.name + ")") {}
bool operator() (int const c) const {
return a(c) || b(c);
}
};
class is_not : public char_pred {
char_pred const &a;
public:
explicit is_not(char_pred const &a)
: a(a), char_pred("~" + a.name) {}
bool operator() (int const c) const {
return !a(c);
}
};
is_char const is_minus('-');
//----------------------------------------------------------------------------
// Recursive Descent Parser
struct parse_error : public runtime_error {
int const row;
int const col;
int const sym;
string const exp;
parse_error(string const& what, int row, int col, string exp, int sym)
: runtime_error(what), row(row), col(col), exp(move(exp)), sym(sym) {}
};
class parser {
streambuf *in;
int count;
int row;
int col;
int sym;
void error(string const& err, string const exp) {
throw parse_error(err, row, col, exp, sym);
}
void next() {
sym = in->sgetc();
in->snextc();
++count;
if (sym == '\n') {
++row;
col = 1;
} else if (::isprint(sym)) {
++col;
}
}
public:
parser(istream &f) : in(f.rdbuf()), count(0), row(1), col(1), sym(in->sbumpc()) {}
protected:
int get_col() {
return col;
}
int get_row() {
return row;
}
int get_count() {
return count;
}
bool accept(char_pred const &t, string *s = nullptr) {
if (!t(sym)) {
return false;
}
if (s != nullptr) {
s->push_back(sym);
}
next();
return true;
}
bool expect(char_pred const &t, string *s = nullptr) {
if (!t(sym)) {
error("expected", t.name);
}
if (s != nullptr) {
s->push_back(sym);
}
next();
return true;
}
bool space(string *s = nullptr) {
if (accept(is_space)) {
if (s != nullptr) {
s->push_back(' ');
}
while (accept(is_space));
return true;
}
return false;
}
bool number(string *s = nullptr) {
if (accept(is_digit, s)) {
while (accept(is_digit, s));
return true;
}
return false;
}
bool signed_number(string *s = nullptr) {
return accept(is_minus, s), number(s);
}
bool name(string *s = nullptr) {
if (accept(is_alpha, s)) {
while (accept(is_alnum, s));
return true;
}
return false;
}
};
|
add missing zero initialisaton of byte count
|
add missing zero initialisaton of byte count
|
C++
|
mit
|
keean/Parser-Combinators,seckcoder/Parser-Combinators
|
fab067cecef205ce246904cf122a5e545e348f99
|
passes/opt/opt.cc
|
passes/opt/opt.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/log.h"
#include <stdlib.h>
#include <stdio.h>
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct OptPass : public Pass {
OptPass() : Pass("opt", "perform simple optimizations") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" opt [options] [selection]\n");
log("\n");
log("This pass calls all the other opt_* passes in a useful order. This performs\n");
log("a series of trivial optimizations and cleanups. This pass executes the other\n");
log("passes in the following order:\n");
log("\n");
log(" opt_expr [-mux_undef] [-mux_bool] [-undriven] [-clkinv] [-fine] [-full] [-keepdc]\n");
log(" opt_merge [-share_all] -nomux\n");
log("\n");
log(" do\n");
log(" opt_muxtree\n");
log(" opt_reduce [-fine] [-full]\n");
log(" opt_merge [-share_all]\n");
log(" opt_rmdff [-keepdc] [-sat]\n");
log(" opt_clean [-purge]\n");
log(" opt_expr [-mux_undef] [-mux_bool] [-undriven] [-clkinv] [-fine] [-full] [-keepdc]\n");
log(" while <changed design>\n");
log("\n");
log("When called with -fast the following script is used instead:\n");
log("\n");
log(" do\n");
log(" opt_expr [-mux_undef] [-mux_bool] [-undriven] [-clkinv] [-fine] [-full] [-keepdc]\n");
log(" opt_merge [-share_all]\n");
log(" opt_rmdff [-keepdc] [-sat]\n");
log(" opt_clean [-purge]\n");
log(" while <changed design in opt_rmdff>\n");
log("\n");
log("Note: Options in square brackets (such as [-keepdc]) are passed through to\n");
log("the opt_* commands when given to 'opt'.\n");
log("\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
std::string opt_clean_args;
std::string opt_expr_args;
std::string opt_reduce_args;
std::string opt_merge_args;
std::string opt_rmdff_args;
bool fast_mode = false;
log_header(design, "Executing OPT pass (performing simple optimizations).\n");
log_push();
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-purge") {
opt_clean_args += " -purge";
continue;
}
if (args[argidx] == "-mux_undef") {
opt_expr_args += " -mux_undef";
continue;
}
if (args[argidx] == "-mux_bool") {
opt_expr_args += " -mux_bool";
continue;
}
if (args[argidx] == "-undriven") {
opt_expr_args += " -undriven";
continue;
}
if (args[argidx] == "-clkinv") {
opt_expr_args += " -clkinv";
continue;
}
if (args[argidx] == "-fine") {
opt_expr_args += " -fine";
opt_reduce_args += " -fine";
continue;
}
if (args[argidx] == "-full") {
opt_expr_args += " -full";
opt_reduce_args += " -full";
continue;
}
if (args[argidx] == "-keepdc") {
opt_expr_args += " -keepdc";
opt_rmdff_args += " -keepdc";
continue;
}
if (args[argidx] == "-sat") {
opt_rmdff_args += " -sat";
continue;
}
if (args[argidx] == "-share_all") {
opt_merge_args += " -share_all";
continue;
}
if (args[argidx] == "-fast") {
fast_mode = true;
continue;
}
break;
}
extra_args(args, argidx, design);
if (fast_mode)
{
while (1) {
Pass::call(design, "opt_expr" + opt_expr_args);
Pass::call(design, "opt_merge" + opt_merge_args);
design->scratchpad_unset("opt.did_something");
Pass::call(design, "opt_rmdff" + opt_rmdff_args);
if (design->scratchpad_get_bool("opt.did_something") == false)
break;
Pass::call(design, "opt_clean" + opt_clean_args);
log_header(design, "Rerunning OPT passes. (Removed registers in this run.)\n");
}
Pass::call(design, "opt_clean" + opt_clean_args);
}
else
{
Pass::call(design, "opt_expr" + opt_expr_args);
Pass::call(design, "opt_merge -nomux" + opt_merge_args);
while (1) {
design->scratchpad_unset("opt.did_something");
Pass::call(design, "opt_muxtree");
Pass::call(design, "opt_reduce" + opt_reduce_args);
Pass::call(design, "opt_merge" + opt_merge_args);
Pass::call(design, "opt_rmdff" + opt_rmdff_args);
Pass::call(design, "opt_clean" + opt_clean_args);
Pass::call(design, "opt_expr" + opt_expr_args);
if (design->scratchpad_get_bool("opt.did_something") == false)
break;
log_header(design, "Rerunning OPT passes. (Maybe there is more to do..)\n");
}
}
design->optimize();
design->sort();
design->check();
log_header(design, fast_mode ? "Finished fast OPT passes.\n" : "Finished OPT passes. (There is nothing left to do.)\n");
log_pop();
}
} OptPass;
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/log.h"
#include <stdlib.h>
#include <stdio.h>
USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN
struct OptPass : public Pass {
OptPass() : Pass("opt", "perform simple optimizations") { }
void help() YS_OVERRIDE
{
// |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
log("\n");
log(" opt [options] [selection]\n");
log("\n");
log("This pass calls all the other opt_* passes in a useful order. This performs\n");
log("a series of trivial optimizations and cleanups. This pass executes the other\n");
log("passes in the following order:\n");
log("\n");
log(" opt_expr [-mux_undef] [-mux_bool] [-undriven] [-clkinv] [-fine] [-full] [-keepdc]\n");
log(" opt_merge [-share_all] -nomux\n");
log("\n");
log(" do\n");
log(" opt_muxtree\n");
log(" opt_reduce [-fine] [-full]\n");
log(" opt_merge [-share_all]\n");
log(" opt_share (-full only)\n");
log(" opt_rmdff [-keepdc] [-sat]\n");
log(" opt_clean [-purge]\n");
log(" opt_expr [-mux_undef] [-mux_bool] [-undriven] [-clkinv] [-fine] [-full] [-keepdc]\n");
log(" while <changed design>\n");
log("\n");
log("When called with -fast the following script is used instead:\n");
log("\n");
log(" do\n");
log(" opt_expr [-mux_undef] [-mux_bool] [-undriven] [-clkinv] [-fine] [-full] [-keepdc]\n");
log(" opt_merge [-share_all]\n");
log(" opt_rmdff [-keepdc] [-sat]\n");
log(" opt_clean [-purge]\n");
log(" while <changed design in opt_rmdff>\n");
log("\n");
log("Note: Options in square brackets (such as [-keepdc]) are passed through to\n");
log("the opt_* commands when given to 'opt'.\n");
log("\n");
log("\n");
}
void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
{
std::string opt_clean_args;
std::string opt_expr_args;
std::string opt_reduce_args;
std::string opt_merge_args;
std::string opt_rmdff_args;
bool opt_share = false;
bool fast_mode = false;
log_header(design, "Executing OPT pass (performing simple optimizations).\n");
log_push();
size_t argidx;
for (argidx = 1; argidx < args.size(); argidx++) {
if (args[argidx] == "-purge") {
opt_clean_args += " -purge";
continue;
}
if (args[argidx] == "-mux_undef") {
opt_expr_args += " -mux_undef";
continue;
}
if (args[argidx] == "-mux_bool") {
opt_expr_args += " -mux_bool";
continue;
}
if (args[argidx] == "-undriven") {
opt_expr_args += " -undriven";
continue;
}
if (args[argidx] == "-clkinv") {
opt_expr_args += " -clkinv";
continue;
}
if (args[argidx] == "-fine") {
opt_expr_args += " -fine";
opt_reduce_args += " -fine";
continue;
}
if (args[argidx] == "-full") {
opt_expr_args += " -full";
opt_reduce_args += " -full";
opt_share = true;
continue;
}
if (args[argidx] == "-keepdc") {
opt_expr_args += " -keepdc";
opt_rmdff_args += " -keepdc";
continue;
}
if (args[argidx] == "-sat") {
opt_rmdff_args += " -sat";
continue;
}
if (args[argidx] == "-share_all") {
opt_merge_args += " -share_all";
continue;
}
if (args[argidx] == "-fast") {
fast_mode = true;
continue;
}
break;
}
extra_args(args, argidx, design);
if (fast_mode)
{
while (1) {
Pass::call(design, "opt_expr" + opt_expr_args);
Pass::call(design, "opt_merge" + opt_merge_args);
design->scratchpad_unset("opt.did_something");
Pass::call(design, "opt_rmdff" + opt_rmdff_args);
if (design->scratchpad_get_bool("opt.did_something") == false)
break;
Pass::call(design, "opt_clean" + opt_clean_args);
log_header(design, "Rerunning OPT passes. (Removed registers in this run.)\n");
}
Pass::call(design, "opt_clean" + opt_clean_args);
}
else
{
Pass::call(design, "opt_expr" + opt_expr_args);
Pass::call(design, "opt_merge -nomux" + opt_merge_args);
while (1) {
design->scratchpad_unset("opt.did_something");
Pass::call(design, "opt_muxtree");
Pass::call(design, "opt_reduce" + opt_reduce_args);
Pass::call(design, "opt_merge" + opt_merge_args);
if (opt_share)
Pass::call(design, "opt_share");
Pass::call(design, "opt_rmdff" + opt_rmdff_args);
Pass::call(design, "opt_clean" + opt_clean_args);
Pass::call(design, "opt_expr" + opt_expr_args);
if (design->scratchpad_get_bool("opt.did_something") == false)
break;
log_header(design, "Rerunning OPT passes. (Maybe there is more to do..)\n");
}
}
design->optimize();
design->sort();
design->check();
log_header(design, fast_mode ? "Finished fast OPT passes.\n" : "Finished OPT passes. (There is nothing left to do.)\n");
log_pop();
}
} OptPass;
PRIVATE_NAMESPACE_END
|
Add 'opt_share' to 'opt -full'
|
Add 'opt_share' to 'opt -full'
|
C++
|
isc
|
antmicro/yosys,YosysHQ/yosys,YosysHQ/yosys,cliffordwolf/yosys,SymbiFlow/yosys,SymbiFlow/yosys,YosysHQ/yosys,YosysHQ/yosys,SymbiFlow/yosys,antmicro/yosys,SymbiFlow/yosys,cliffordwolf/yosys,antmicro/yosys,YosysHQ/yosys,cliffordwolf/yosys,SymbiFlow/yosys,antmicro/yosys,antmicro/yosys,cliffordwolf/yosys,SymbiFlow/yosys,YosysHQ/yosys,cliffordwolf/yosys,cliffordwolf/yosys,cliffordwolf/yosys,cliffordwolf/yosys,YosysHQ/yosys,antmicro/yosys,YosysHQ/yosys,cliffordwolf/yosys,antmicro/yosys,SymbiFlow/yosys,antmicro/yosys,SymbiFlow/yosys
|
e65a17b30b731b276495049805444822bb3bd618
|
common/Geometry2d/Pose.hpp
|
common/Geometry2d/Pose.hpp
|
#pragma once
#include <ostream>
#include "Point.hpp"
#include "TransformMatrix.hpp"
namespace Geometry2d {
/**
* Represents a pose in 2d space: (x, y, theta). Uses double-precision floating
* point numbers for the coordinates, and can be used to represent the position
* and orientation of a robot in the plane.
*/
class Pose {
public:
/**
* Default constructor - zero-initialize
*/
Pose() : _position{}, _heading{0} {}
/**
* Point-heading constructor
*/
Pose(Point position, double heading)
: _position(position), _heading(heading) {}
/**
* Component-wise constructor
*/
Pose(double x, double y, double h) : _position(x, y), _heading(h) {}
/**
* Implicit conversion from Eigen::Vector3d
*/
Pose(const Eigen::Vector3d& other)
: _position(other(0), other(1)), _heading(other(2)) {}
/**
* Copy-constructor - default
*/
Pose(const Pose& other) = default;
/**
* Compute the pose specified using this pose as coordinates in a frame of
* reference specified by `other`, in the global space.
*
* i.e.
*
* x:
* | x
* | /
* |/
* ------|-------
* |
* |
* |
*
* y:
* |
* |
* ----|----
* |\
* | y
*
* y.withOrigin(x):
* | x
* | / \
* |/ y
* ------|------
* |
*/
Pose withOrigin(Pose other) const {
Point rotated = position().rotated(other.heading());
return other + Pose(rotated, heading());
}
/**
* Implicit conversion to Eigen::Vector3d
*/
operator Eigen::Vector3d() const {
return Eigen::Vector3d(position().x(), position().y(), heading());
}
/**
* Calculate a TransformMatrix corresponding to using this pose as the
* origin of the coordinate system.
*/
TransformMatrix transform() const {
return TransformMatrix(position(), heading());
}
/**
* Accessors
*/
Point& position() { return _position; }
Point const& position() const { return _position; }
double& heading() { return _heading; }
double const& heading() const { return _heading; }
/**
* Operators
*/
Pose operator+(const Pose& other) const {
return Pose(position() + other.position(), heading() + other.heading());
}
Pose operator-(const Pose& other) const {
return Pose(position() - other.position(), heading() - other.heading());
}
Pose operator*(double s) const {
return Pose(position() * s, heading() * s);
}
Pose operator/(double s) const {
return Pose(position() / s, heading() / s);
}
Pose& operator+=(const Pose& other) {
position() += other.position();
heading() += other.heading();
return *this;
}
Pose& operator-=(const Pose& other) {
position() += other.position();
heading() += other.heading();
return *this;
}
Pose& operator*=(double s) {
position() *= s;
heading() *= s;
return *this;
}
Pose& operator/=(double s) {
position() /= s;
heading() /= s;
return *this;
}
friend std::ostream& operator<<(std::ostream& stream, const Pose& pose) {
stream << "Pose(" << pose.position().x() << ", " << pose.position().y()
<< ", " << pose.heading() << ")";
return stream;
}
private:
Point _position;
double _heading;
};
/**
* Represents a differential (velocity, acceleration, etc.) in 2d space:
* (dx, dy, dh). Uses double-precision floating point numbers.
*/
class Twist {
public:
/**
* Default constructor - zero-initialize
*/
Twist() : _linear{}, _angular{0} {}
/**
* Linear+angular terms.
*/
Twist(const Point& linear, double angular)
: _linear(linear), _angular(angular) {}
/**
* Component-wise constructor
*/
Twist(double dx, double dy, double dh) : _linear(dx, dy), _angular(dh) {}
/**
* Implicit conversion from Eigen::Vector3d
*/
Twist(const Eigen::Vector3d& other)
: _linear(other(0), other(1)), _angular(other(2)) {}
/**
* Copy-constructor - default
*/
Twist(const Twist& other) = default;
/**
* Zero
*/
static Twist Zero() { return Twist(Eigen::Vector3d::Zero()); }
/**
* Implicit conversion to Eigen::Vector3d
*/
operator Eigen::Vector3d() const {
return Eigen::Vector3d(linear().x(), linear().y(), angular());
}
/**
* Accessors
*/
Point& linear() { return _linear; }
Point const& linear() const { return _linear; }
double& angular() { return _angular; }
double const& angular() const { return _angular; }
/**
* Find the resulting pose (delta) of an object starting at the origin and
* continuing with constant (world-space) velocity for the specified time
* (in seconds).
*
* Throughout the movement, linear velocity relative to the origin is
* constant (but velocity in the pose's reference frame is changing in
* direction as the pose rotates)
*
* Called deltaFixed because it operates fixed to the origin frame.
*/
Pose deltaFixed(double t) const {
return Pose(linear().x(), linear().y(), angular());
}
/**
* Find the resulting pose (delta) of an object starting at the origin and
* continuing with constant (local) velocity for the specified time
* (in seconds).
*
* Throughout the movement, linear velocity relative to the pose's frame of
* reference is constant (but linear velocity relative to the origin might
* change as the pose rotates)
*
* Called deltaRelative because it operates with velocities that remain
* constant relative to the pose.
*
* In mathematical terms, this is the exponential mapping that takes the Lie
* algebra se(2) (twists) to the Lie group SE(2) (poses).
*/
Pose deltaRelative(double t) const {
// twist = (x', y', h')
// dh(world) = h' * dt
// dx(world) = dx(local)cos(dh(world)) - dy(local)sin(dh(world))
// = integral(x'cos(h't) - y'sin(h't), dt)
// = x'/h' sin(h't) + y'/h' (cos(h't) - 1)
// dy(world) = dx(local)sin(dh(world)) + dy(local)cos(dh(world))
// = integral(x'sin(h't) + y'cos(h't), dt)
// = x'/h' (1 - cos(h't)) + y'/h' sin(h't)
double vx = linear().x();
double vy = linear().y();
double vh = angular();
// From above: sin(h't)/h' and (1 - cos(h't))/h' respectively
double sine_frac, cosine_frac;
if (std::abs(vh) < 1e-6) {
// Small-angle approximations
// sin(h't) ~ h't
// 1 - cos(h't) ~ 0
sine_frac = t;
cosine_frac = 0;
} else {
sine_frac = std::sin(vh * t) / vh;
cosine_frac = (1 - std::cos(vh * t)) / vh;
}
return Pose(vx * sine_frac - vy * cosine_frac,
vx * cosine_frac + vy * sine_frac, vh * t);
}
double curvature() const { return angular() / linear().mag(); }
/**
* Operators
*/
Twist operator+(const Twist& other) const {
return Twist(linear() + other.linear(), angular() + other.angular());
}
Twist operator-(const Twist& other) const {
return Twist(linear() - other.linear(), angular() - other.angular());
}
Twist operator*(double s) const {
return Twist(linear() * s, angular() * s);
}
Twist operator/(double s) const {
return Twist(linear() / s, angular() / s);
}
Twist& operator+=(const Twist& other) {
linear() += other.linear();
angular() += other.angular();
return *this;
}
Twist& operator-=(const Twist& other) {
linear() -= other.linear();
angular() -= other.angular();
return *this;
}
Twist& operator*=(double s) {
linear() *= s;
angular() *= s;
return *this;
}
Twist& operator/=(double s) {
linear() /= s;
angular() /= s;
return *this;
}
friend std::ostream& operator<<(std::ostream& stream, const Twist& twist) {
stream << "Twist(" << twist.linear().x() << ", " << twist.linear().y()
<< ", " << twist.angular() << ")";
return stream;
}
private:
Point _linear;
double _angular;
};
} // namespace Geometry2d
|
#pragma once
#include <ostream>
#include "Point.hpp"
#include "TransformMatrix.hpp"
namespace Geometry2d {
/**
* Represents a pose in 2d space: (x, y, theta). Uses double-precision floating
* point numbers for the coordinates, and can be used to represent the position
* and orientation of a robot in the plane.
*/
class Pose {
public:
/**
* Default constructor - zero-initialize
*/
Pose() : _position{}, _heading{0} {}
/**
* Point-heading constructor
*/
Pose(Point position, double heading)
: _position(position), _heading(heading) {}
/**
* Component-wise constructor
*/
Pose(double x, double y, double h) : _position(x, y), _heading(h) {}
/**
* Implicit conversion from Eigen::Vector3d
*/
Pose(const Eigen::Vector3d& other)
: _position(other(0), other(1)), _heading(other(2)) {}
/**
* Copy-constructor - default
*/
Pose(const Pose& other) = default;
/**
* Compute the pose specified using this pose as coordinates in a frame of
* reference specified by `other`, in the global space.
*
* i.e.
*
* x:
* | x
* | /
* |/
* ------|-------
* |
* |
* |
*
* y:
* |
* |
* ----|----
* |\
* | y
*
* y.withOrigin(x):
* | x
* | / \
* |/ y
* ------|------
* |
*/
Pose withOrigin(Pose other) const {
Point rotated = position().rotated(other.heading());
return other + Pose(rotated, heading());
}
/**
* Implicit conversion to Eigen::Vector3d
*/
operator Eigen::Vector3d() const {
return Eigen::Vector3d(position().x(), position().y(), heading());
}
/**
* Calculate a TransformMatrix corresponding to using this pose as the
* origin of the coordinate system.
*/
TransformMatrix transform() const {
return TransformMatrix(position(), heading());
}
/**
* Accessors
*/
Point& position() { return _position; }
Point const& position() const { return _position; }
double& heading() { return _heading; }
double const& heading() const { return _heading; }
/**
* Operators
*/
Pose operator+(const Pose& other) const {
return Pose(position() + other.position(), heading() + other.heading());
}
Pose operator-(const Pose& other) const {
return Pose(position() - other.position(), heading() - other.heading());
}
Pose operator*(double s) const {
return Pose(position() * s, heading() * s);
}
Pose operator/(double s) const {
return Pose(position() / s, heading() / s);
}
Pose& operator+=(const Pose& other) {
position() += other.position();
heading() += other.heading();
return *this;
}
Pose& operator-=(const Pose& other) {
position() += other.position();
heading() += other.heading();
return *this;
}
Pose& operator*=(double s) {
position() *= s;
heading() *= s;
return *this;
}
Pose& operator/=(double s) {
position() /= s;
heading() /= s;
return *this;
}
friend std::ostream& operator<<(std::ostream& stream, const Pose& pose) {
stream << "Pose(" << pose.position().x() << ", " << pose.position().y()
<< ", " << pose.heading() << ")";
return stream;
}
private:
Point _position;
double _heading;
};
/**
* Represents a differential (velocity, acceleration, etc.) in 2d space:
* (dx, dy, dh). Uses double-precision floating point numbers.
*/
class Twist {
public:
/**
* Default constructor - zero-initialize
*/
Twist() : _linear{}, _angular{0} {}
/**
* Linear+angular terms.
*/
Twist(const Point& linear, double angular)
: _linear(linear), _angular(angular) {}
/**
* Component-wise constructor
*/
Twist(double dx, double dy, double dh) : _linear(dx, dy), _angular(dh) {}
/**
* Implicit conversion from Eigen::Vector3d
*/
Twist(const Eigen::Vector3d& other)
: _linear(other(0), other(1)), _angular(other(2)) {}
/**
* Copy-constructor - default
*/
Twist(const Twist& other) = default;
/**
* Zero
*/
static Twist Zero() { return Twist(Eigen::Vector3d::Zero()); }
/**
* Implicit conversion to Eigen::Vector3d
*/
operator Eigen::Vector3d() const {
return Eigen::Vector3d(linear().x(), linear().y(), angular());
}
/**
* Accessors
*/
Point& linear() { return _linear; }
Point const& linear() const { return _linear; }
double& angular() { return _angular; }
double const& angular() const { return _angular; }
/**
* Find the resulting pose (delta) of an object starting at the origin and
* continuing with constant (world-space) velocity for the specified time
* (in seconds).
*
* Throughout the movement, linear velocity relative to the origin is
* constant (but velocity in the pose's reference frame is changing in
* direction as the pose rotates)
*
* Called deltaFixed because it operates fixed to the origin frame.
*/
Pose deltaFixed(double t) const {
return Pose(linear().x(), linear().y(), angular());
}
/**
* Find the resulting pose (delta) of an object starting at the origin and
* continuing with constant (local) velocity for the specified time
* (in seconds).
*
* Throughout the movement, linear velocity relative to the pose's frame of
* reference is constant (but linear velocity relative to the origin might
* change as the pose rotates)
*
* Called deltaRelative because it operates with velocities that remain
* constant relative to the pose.
*
* In mathematical terms, this is the exponential mapping that takes the Lie
* algebra se(2) (twists) to the Lie group SE(2) (poses).
*/
Pose deltaRelative(double t) const {
// twist = (x', y', h')
// dh(world) = h' * dt
// dx(world) = dx(local)cos(dh(world)) - dy(local)sin(dh(world))
// = integral(x'cos(h't) - y'sin(h't), dt)
// = x'/h' sin(h't) + y'/h' (cos(h't) - 1)
// dy(world) = dx(local)sin(dh(world)) + dy(local)cos(dh(world))
// = integral(x'sin(h't) + y'cos(h't), dt)
// = x'/h' (1 - cos(h't)) + y'/h' sin(h't)
double vx = linear().x();
double vy = linear().y();
double vh = angular();
// From above: sin(h't)/h' and (1 - cos(h't))/h' respectively
double sine_frac, cosine_frac;
if (std::abs(vh) < 1e-6) {
// Small-angle approximations
// sin(h't) ~ h't
// 1 - cos(h't) ~ 0
sine_frac = t;
cosine_frac = 0;
} else {
sine_frac = std::sin(vh * t) / vh;
cosine_frac = (1 - std::cos(vh * t)) / vh;
}
return Pose(vx * sine_frac - vy * cosine_frac,
vx * cosine_frac + vy * sine_frac, vh * t);
}
double curvature() const { return angular() / linear().mag(); }
/**
* Operators
*/
Twist operator+(const Twist& other) const {
return Twist(linear() + other.linear(), angular() + other.angular());
}
Twist operator-(const Twist& other) const {
return Twist(linear() - other.linear(), angular() - other.angular());
}
Twist operator*(double s) const {
return Twist(linear() * s, angular() * s);
}
Twist operator/(double s) const {
return Twist(linear() / s, angular() / s);
}
Twist& operator+=(const Twist& other) {
linear() += other.linear();
angular() += other.angular();
return *this;
}
Twist& operator-=(const Twist& other) {
linear() -= other.linear();
angular() -= other.angular();
return *this;
}
Twist& operator*=(double s) {
linear() *= s;
angular() *= s;
return *this;
}
Twist& operator/=(double s) {
linear() /= s;
angular() /= s;
return *this;
}
friend std::ostream& operator<<(std::ostream& stream, const Twist& twist) {
stream << "Twist(" << twist.linear().x() << ", " << twist.linear().y()
<< ", " << twist.angular() << ")";
return stream;
}
private:
Point _linear;
double _angular;
};
} // namespace Geometry2d
|
Make pretty
|
Make pretty
|
C++
|
apache-2.0
|
RoboJackets/robocup-software,RoboJackets/robocup-software,RoboJackets/robocup-software,RoboJackets/robocup-software
|
a5c4592bbc5086018dcfdf2ff3ad49931ae1183d
|
skia/ext/SkFontHost_fontconfig_direct.cpp
|
skia/ext/SkFontHost_fontconfig_direct.cpp
|
/* libs/graphics/ports/SkFontHost_fontconfig_direct.cpp
**
** Copyright 2009, Google 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 "SkFontHost_fontconfig_direct.h"
#include <unistd.h>
#include <fcntl.h>
#include <fontconfig/fontconfig.h>
#include "unicode/utf16.h"
namespace {
// Equivalence classes, used to match the Liberation and Ascender fonts
// with their metric-compatible replacements. See the discussion in
// GetFontEquivClass().
enum FontEquivClass
{
OTHER,
SANS,
SERIF,
MONO
};
// Match the font name against a whilelist of fonts, returning the equivalence
// class.
FontEquivClass GetFontEquivClass(const char* fontname)
{
// It would be nice for fontconfig to tell us whether a given suggested
// replacement is a "strong" match (that is, an equivalent font) or
// a "weak" match (that is, fontconfig's next-best attempt at finding a
// substitute). However, I played around with the fontconfig API for
// a good few hours and could not make it reveal this information.
//
// So instead, we hardcode. Initially this function emulated
// /etc/fonts/conf.d/30-metric-aliases.conf
// from my Ubuntu system, but we're better off being very conservative.
// "Ascender Sans", "Ascender Serif" and "Ascender Sans Mono" are the
// tentative names of another set of fonts metric-compatible with
// Arial, Times New Roman and Courier New with a character repertoire
// much larger than Liberation. Note that Ascender Sans Mono
// is metrically compatible with Courier New, but the former
// is sans-serif while ther latter is serif.
// Arimo, Tinos and Cousine are the names of new fonts derived from and
// expanded upon Ascender Sans, Ascender Serif and Ascender Sans Mono.
if (strcasecmp(fontname, "Arial") == 0 ||
strcasecmp(fontname, "Liberation Sans") == 0 ||
strcasecmp(fontname, "Arimo") == 0 ||
strcasecmp(fontname, "Ascender Sans") == 0) {
return SANS;
} else if (strcasecmp(fontname, "Times New Roman") == 0 ||
strcasecmp(fontname, "Liberation Serif") == 0 ||
strcasecmp(fontname, "Tinos") == 0 ||
strcasecmp(fontname, "Ascender Serif") == 0) {
return SERIF;
} else if (strcasecmp(fontname, "Courier New") == 0 ||
strcasecmp(fontname, "Cousine") == 0 ||
strcasecmp(fontname, "Ascender Sans Mono") == 0) {
return MONO;
}
return OTHER;
}
// Return true if |font_a| and |font_b| are visually and at the metrics
// level interchangeable.
bool IsMetricCompatibleReplacement(const char* font_a, const char* font_b)
{
FontEquivClass class_a = GetFontEquivClass(font_a);
FontEquivClass class_b = GetFontEquivClass(font_b);
return class_a != OTHER && class_a == class_b;
}
inline unsigned FileFaceIdToFileId(unsigned filefaceid)
{
return filefaceid >> 4;
}
inline unsigned FileIdAndFaceIndexToFileFaceId(unsigned fileid, int face_index)
{
SkASSERT((face_index & 0xfu) == face_index);
return (fileid << 4) | face_index;
}
} // anonymous namespace
FontConfigDirect::FontConfigDirect()
: next_file_id_(0) {
FcInit();
}
FontConfigDirect::~FontConfigDirect() {
}
// -----------------------------------------------------------------------------
// Normally we only return exactly the font asked for. In last-resort
// cases, the request either doesn't specify a font or is one of the
// basic font names like "Sans", "Serif" or "Monospace". This function
// tells you whether a given request is for such a fallback.
// -----------------------------------------------------------------------------
static bool IsFallbackFontAllowed(const std::string& family)
{
const char* family_cstr = family.c_str();
return family.empty() ||
strcasecmp(family_cstr, "sans") == 0 ||
strcasecmp(family_cstr, "serif") == 0 ||
strcasecmp(family_cstr, "monospace") == 0;
}
bool FontConfigDirect::Match(std::string* result_family,
unsigned* result_filefaceid,
bool filefaceid_valid, unsigned filefaceid,
const std::string& family,
const void* data, size_t characters_bytes,
bool* is_bold, bool* is_italic) {
if (family.length() > kMaxFontFamilyLength)
return false;
SkAutoMutexAcquire ac(mutex_);
FcPattern* pattern = FcPatternCreate();
if (filefaceid_valid) {
const std::map<unsigned, std::string>::const_iterator
i = fileid_to_filename_.find(FileFaceIdToFileId(filefaceid));
if (i == fileid_to_filename_.end()) {
FcPatternDestroy(pattern);
return false;
}
int face_index = filefaceid & 0xfu;
FcPatternAddString(pattern, FC_FILE,
reinterpret_cast<const FcChar8*>(i->second.c_str()));
// face_index is added only when family is empty because it is not
// necessary to uniquiely identify a font if both file and
// family are given.
if (family.empty())
FcPatternAddInteger(pattern, FC_INDEX, face_index);
}
if (!family.empty()) {
FcPatternAddString(pattern, FC_FAMILY, (FcChar8*) family.c_str());
}
FcCharSet* charset = NULL;
if (data) {
charset = FcCharSetCreate();
const uint16_t* chars = (const uint16_t*) data;
size_t num_chars = characters_bytes / 2;
for (size_t i = 0; i < num_chars; ++i) {
if (U16_IS_SURROGATE(chars[i])
&& U16_IS_SURROGATE_LEAD(chars[i])
&& i != num_chars - 1
&& U16_IS_TRAIL(chars[i + 1])) {
FcCharSetAddChar(charset, U16_GET_SUPPLEMENTARY(chars[i], chars[i+1]));
i++;
} else {
FcCharSetAddChar(charset, chars[i]);
}
}
FcPatternAddCharSet(pattern, FC_CHARSET, charset);
FcCharSetDestroy(charset); // pattern now owns it.
}
FcPatternAddInteger(pattern, FC_WEIGHT,
is_bold && *is_bold ? FC_WEIGHT_BOLD
: FC_WEIGHT_NORMAL);
FcPatternAddInteger(pattern, FC_SLANT,
is_italic && *is_italic ? FC_SLANT_ITALIC
: FC_SLANT_ROMAN);
FcPatternAddBool(pattern, FC_SCALABLE, FcTrue);
FcConfigSubstitute(NULL, pattern, FcMatchPattern);
FcDefaultSubstitute(pattern);
// Font matching:
// CSS often specifies a fallback list of families:
// font-family: a, b, c, serif;
// However, fontconfig will always do its best to find *a* font when asked
// for something so we need a way to tell if the match which it has found is
// "good enough" for us. Otherwise, we can return NULL which gets piped up
// and lets WebKit know to try the next CSS family name. However, fontconfig
// configs allow substitutions (mapping "Arial -> Helvetica" etc) and we
// wish to support that.
//
// Thus, if a specific family is requested we set @family_requested. Then we
// record two strings: the family name after config processing and the
// family name after resolving. If the two are equal, it's a good match.
//
// So consider the case where a user has mapped Arial to Helvetica in their
// config.
// requested family: "Arial"
// post_config_family: "Helvetica"
// post_match_family: "Helvetica"
// -> good match
//
// and for a missing font:
// requested family: "Monaco"
// post_config_family: "Monaco"
// post_match_family: "Times New Roman"
// -> BAD match
//
// However, we special-case fallback fonts; see IsFallbackFontAllowed().
FcChar8* post_config_family;
FcPatternGetString(pattern, FC_FAMILY, 0, &post_config_family);
FcResult result;
FcFontSet* font_set = FcFontSort(0, pattern, 0, 0, &result);
if (!font_set) {
FcPatternDestroy(pattern);
return false;
}
// Older versions of fontconfig have a bug where they cannot select
// only scalable fonts so we have to manually filter the results.
FcPattern* match = NULL;
for (int i = 0; i < font_set->nfont; ++i) {
FcPattern* current = font_set->fonts[i];
FcBool is_scalable;
if (FcPatternGetBool(current, FC_SCALABLE, 0,
&is_scalable) != FcResultMatch ||
!is_scalable) {
continue;
}
// fontconfig can also return fonts which are unreadable
FcChar8* c_filename;
if (FcPatternGetString(current, FC_FILE, 0, &c_filename) != FcResultMatch)
continue;
if (access(reinterpret_cast<char*>(c_filename), R_OK) != 0)
continue;
match = current;
break;
}
if (!match) {
FcPatternDestroy(pattern);
FcFontSetDestroy(font_set);
return false;
}
if (!IsFallbackFontAllowed(family)) {
bool acceptable_substitute = false;
for (int id = 0; id < 255; ++id) {
FcChar8* post_match_family;
if (FcPatternGetString(match, FC_FAMILY, id, &post_match_family) !=
FcResultMatch)
break;
acceptable_substitute =
(strcasecmp((char *)post_config_family,
(char *)post_match_family) == 0 ||
// Workaround for Issue 12530:
// requested family: "Bitstream Vera Sans"
// post_config_family: "Arial"
// post_match_family: "Bitstream Vera Sans"
// -> We should treat this case as a good match.
strcasecmp(family.c_str(),
(char *)post_match_family) == 0) ||
IsMetricCompatibleReplacement(family.c_str(),
(char*)post_match_family);
if (acceptable_substitute)
break;
}
if (!acceptable_substitute) {
FcPatternDestroy(pattern);
FcFontSetDestroy(font_set);
return false;
}
}
FcPatternDestroy(pattern);
FcChar8* c_filename;
if (FcPatternGetString(match, FC_FILE, 0, &c_filename) != FcResultMatch) {
FcFontSetDestroy(font_set);
return false;
}
int face_index;
if (FcPatternGetInteger(match, FC_INDEX, 0, &face_index) != FcResultMatch) {
FcFontSetDestroy(font_set);
return false;
}
const std::string filename(reinterpret_cast<char*>(c_filename));
unsigned out_filefaceid;
if (filefaceid_valid) {
out_filefaceid = filefaceid;
} else {
unsigned out_fileid;
const std::map<std::string, unsigned>::const_iterator
i = filename_to_fileid_.find(filename);
if (i == filename_to_fileid_.end()) {
out_fileid = next_file_id_++;
filename_to_fileid_[filename] = out_fileid;
fileid_to_filename_[out_fileid] = filename;
} else {
out_fileid = i->second;
}
// fileid stored in filename_to_fileid_ and fileid_to_filename_ is
// unique only up to the font file. We have to encode face_index for
// the out param.
out_filefaceid = FileIdAndFaceIndexToFileFaceId(out_fileid, face_index);
}
if (result_filefaceid)
*result_filefaceid = out_filefaceid;
FcChar8* c_family;
if (FcPatternGetString(match, FC_FAMILY, 0, &c_family)) {
FcFontSetDestroy(font_set);
return false;
}
int resulting_bold;
if (FcPatternGetInteger(match, FC_WEIGHT, 0, &resulting_bold))
resulting_bold = FC_WEIGHT_NORMAL;
int resulting_italic;
if (FcPatternGetInteger(match, FC_SLANT, 0, &resulting_italic))
resulting_italic = FC_SLANT_ROMAN;
// If we ask for an italic font, fontconfig might take a roman font and set
// the undocumented property FC_MATRIX to a skew matrix. It'll then say
// that the font is italic or oblique. So, if we see a matrix, we don't
// believe that it's italic.
FcValue matrix;
const bool have_matrix = FcPatternGet(match, FC_MATRIX, 0, &matrix) == 0;
// If we ask for an italic font, fontconfig might take a roman font and set
// FC_EMBOLDEN.
FcValue embolden;
const bool have_embolden =
FcPatternGet(match, FC_EMBOLDEN, 0, &embolden) == 0;
if (is_bold)
*is_bold = resulting_bold > FC_WEIGHT_MEDIUM && !have_embolden;
if (is_italic)
*is_italic = resulting_italic > FC_SLANT_ROMAN && !have_matrix;
if (result_family)
*result_family = (char *) c_family;
FcFontSetDestroy(font_set);
return true;
}
int FontConfigDirect::Open(unsigned filefaceid) {
SkAutoMutexAcquire ac(mutex_);
const std::map<unsigned, std::string>::const_iterator
i = fileid_to_filename_.find(FileFaceIdToFileId(filefaceid));
if (i == fileid_to_filename_.end())
return -1;
return open(i->second.c_str(), O_RDONLY);
}
|
/* libs/graphics/ports/SkFontHost_fontconfig_direct.cpp
**
** Copyright 2009, Google 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 "SkFontHost_fontconfig_direct.h"
#include <unistd.h>
#include <fcntl.h>
#include <fontconfig/fontconfig.h>
#include "unicode/utf16.h"
namespace {
// Equivalence classes, used to match the Liberation and other fonts
// with their metric-compatible replacements. See the discussion in
// GetFontEquivClass().
enum FontEquivClass
{
OTHER,
SANS,
SERIF,
MONO,
PMINCHO,
MINCHO,
PGOTHIC,
GOTHIC,
SIMSUN,
NSIMSUN,
};
// Match the font name against a whilelist of fonts, returning the equivalence
// class.
FontEquivClass GetFontEquivClass(const char* fontname)
{
// It would be nice for fontconfig to tell us whether a given suggested
// replacement is a "strong" match (that is, an equivalent font) or
// a "weak" match (that is, fontconfig's next-best attempt at finding a
// substitute). However, I played around with the fontconfig API for
// a good few hours and could not make it reveal this information.
//
// So instead, we hardcode. Initially this function emulated
// /etc/fonts/conf.d/30-metric-aliases.conf
// from my Ubuntu system, but we're better off being very conservative.
// Arimo, Tinos and Cousine are a set of fonts metric-compatible with
// Arial, Times New Roman and Courier New with a character repertoire
// much larger than Liberation. Note that Cousine is metrically
// compatible with Courier New, but the former is sans-serif while
// the latter is serif.
struct FontEquivMap {
FontEquivClass clazz;
const char name[40];
};
static const FontEquivMap kFontEquivMap[] = {
{ SANS, "Arial" },
{ SANS, "Arimo" },
{ SANS, "Liberation Sans" },
{ SERIF, "Times New Roman" },
{ SERIF, "Tinos" },
{ SERIF, "Liberation Serif" },
{ MONO, "Courier New" },
{ MONO, "Cousine" },
{ MONO, "Liberation Mono" },
// MS Pゴシック
{ PGOTHIC, "MS PGothic" },
{ PGOTHIC, "\xef\xbc\xad\xef\xbc\xb3 \xef\xbc\xb0"
"\xe3\x82\xb4\xe3\x82\xb7\xe3\x83\x83\xe3\x82\xaf" },
{ PGOTHIC, "IPAPGothic" },
// 宋体
{ SIMSUN, "Simsun" },
{ SIMSUN, "\xe5\xae\x8b\xe4\xbd\x93" },
{ SIMSUN, "Song ASC" },
// MS P明朝
{ PMINCHO, "MS PMincho" },
{ PMINCHO, "\xef\xbc\xad\xef\xbc\xb3 \xef\xbc\xb0"
"\xe6\x98\x8e\xe6\x9c\x9d"},
{ PMINCHO, "IPAPMincho" },
// MS ゴシック
{ GOTHIC, "MS Gothic" },
{ GOTHIC, "\xef\xbc\xad\xef\xbc\xb3 "
"\xe3\x82\xb4\xe3\x82\xb7\xe3\x83\x83\xe3\x82\xaf" },
{ GOTHIC, "IPAGothic" },
// MS 明朝
{ MINCHO, "MS Mincho" },
{ MINCHO, "\xef\xbc\xad\xef\xbc\xb3 \xe6\x98\x8e\xe6\x9c\x9d" },
{ MINCHO, "IPAMincho" },
// 新宋体
{ NSIMSUN, "NSimsun" },
{ NSIMSUN, "\xe6\x96\xb0\xe5\xae\x8b\xe4\xbd\x93" },
{ NSIMSUN, "N Song ASC" },
};
static const size_t kFontCount =
sizeof(kFontEquivMap)/sizeof(kFontEquivMap[0]);
// TODO(jungshik): If this loop turns out to be hot, turn
// the array to a static (hash)map to speed it up.
for (size_t i = 0; i < kFontCount; ++i) {
if (strcasecmp(kFontEquivMap[i].name, fontname) == 0)
return kFontEquivMap[i].clazz;
}
return OTHER;
}
// Return true if |font_a| and |font_b| are visually and at the metrics
// level interchangeable.
bool IsMetricCompatibleReplacement(const char* font_a, const char* font_b)
{
FontEquivClass class_a = GetFontEquivClass(font_a);
FontEquivClass class_b = GetFontEquivClass(font_b);
return class_a != OTHER && class_a == class_b;
}
inline unsigned FileFaceIdToFileId(unsigned filefaceid)
{
return filefaceid >> 4;
}
inline unsigned FileIdAndFaceIndexToFileFaceId(unsigned fileid, int face_index)
{
SkASSERT((face_index & 0xfu) == face_index);
return (fileid << 4) | face_index;
}
} // anonymous namespace
FontConfigDirect::FontConfigDirect()
: next_file_id_(0) {
FcInit();
}
FontConfigDirect::~FontConfigDirect() {
}
// -----------------------------------------------------------------------------
// Normally we only return exactly the font asked for. In last-resort
// cases, the request either doesn't specify a font or is one of the
// basic font names like "Sans", "Serif" or "Monospace". This function
// tells you whether a given request is for such a fallback.
// -----------------------------------------------------------------------------
static bool IsFallbackFontAllowed(const std::string& family)
{
const char* family_cstr = family.c_str();
return family.empty() ||
strcasecmp(family_cstr, "sans") == 0 ||
strcasecmp(family_cstr, "serif") == 0 ||
strcasecmp(family_cstr, "monospace") == 0;
}
bool FontConfigDirect::Match(std::string* result_family,
unsigned* result_filefaceid,
bool filefaceid_valid, unsigned filefaceid,
const std::string& family,
const void* data, size_t characters_bytes,
bool* is_bold, bool* is_italic) {
if (family.length() > kMaxFontFamilyLength)
return false;
SkAutoMutexAcquire ac(mutex_);
FcPattern* pattern = FcPatternCreate();
if (filefaceid_valid) {
const std::map<unsigned, std::string>::const_iterator
i = fileid_to_filename_.find(FileFaceIdToFileId(filefaceid));
if (i == fileid_to_filename_.end()) {
FcPatternDestroy(pattern);
return false;
}
int face_index = filefaceid & 0xfu;
FcPatternAddString(pattern, FC_FILE,
reinterpret_cast<const FcChar8*>(i->second.c_str()));
// face_index is added only when family is empty because it is not
// necessary to uniquiely identify a font if both file and
// family are given.
if (family.empty())
FcPatternAddInteger(pattern, FC_INDEX, face_index);
}
if (!family.empty()) {
FcPatternAddString(pattern, FC_FAMILY, (FcChar8*) family.c_str());
}
FcCharSet* charset = NULL;
if (data) {
charset = FcCharSetCreate();
const uint16_t* chars = (const uint16_t*) data;
size_t num_chars = characters_bytes / 2;
for (size_t i = 0; i < num_chars; ++i) {
if (U16_IS_SURROGATE(chars[i])
&& U16_IS_SURROGATE_LEAD(chars[i])
&& i != num_chars - 1
&& U16_IS_TRAIL(chars[i + 1])) {
FcCharSetAddChar(charset, U16_GET_SUPPLEMENTARY(chars[i], chars[i+1]));
i++;
} else {
FcCharSetAddChar(charset, chars[i]);
}
}
FcPatternAddCharSet(pattern, FC_CHARSET, charset);
FcCharSetDestroy(charset); // pattern now owns it.
}
FcPatternAddInteger(pattern, FC_WEIGHT,
is_bold && *is_bold ? FC_WEIGHT_BOLD
: FC_WEIGHT_NORMAL);
FcPatternAddInteger(pattern, FC_SLANT,
is_italic && *is_italic ? FC_SLANT_ITALIC
: FC_SLANT_ROMAN);
FcPatternAddBool(pattern, FC_SCALABLE, FcTrue);
FcConfigSubstitute(NULL, pattern, FcMatchPattern);
FcDefaultSubstitute(pattern);
// Font matching:
// CSS often specifies a fallback list of families:
// font-family: a, b, c, serif;
// However, fontconfig will always do its best to find *a* font when asked
// for something so we need a way to tell if the match which it has found is
// "good enough" for us. Otherwise, we can return NULL which gets piped up
// and lets WebKit know to try the next CSS family name. However, fontconfig
// configs allow substitutions (mapping "Arial -> Helvetica" etc) and we
// wish to support that.
//
// Thus, if a specific family is requested we set @family_requested. Then we
// record two strings: the family name after config processing and the
// family name after resolving. If the two are equal, it's a good match.
//
// So consider the case where a user has mapped Arial to Helvetica in their
// config.
// requested family: "Arial"
// post_config_family: "Helvetica"
// post_match_family: "Helvetica"
// -> good match
//
// and for a missing font:
// requested family: "Monaco"
// post_config_family: "Monaco"
// post_match_family: "Times New Roman"
// -> BAD match
//
// However, we special-case fallback fonts; see IsFallbackFontAllowed().
FcChar8* post_config_family;
FcPatternGetString(pattern, FC_FAMILY, 0, &post_config_family);
FcResult result;
FcFontSet* font_set = FcFontSort(0, pattern, 0, 0, &result);
if (!font_set) {
FcPatternDestroy(pattern);
return false;
}
// Older versions of fontconfig have a bug where they cannot select
// only scalable fonts so we have to manually filter the results.
FcPattern* match = NULL;
for (int i = 0; i < font_set->nfont; ++i) {
FcPattern* current = font_set->fonts[i];
FcBool is_scalable;
if (FcPatternGetBool(current, FC_SCALABLE, 0,
&is_scalable) != FcResultMatch ||
!is_scalable) {
continue;
}
// fontconfig can also return fonts which are unreadable
FcChar8* c_filename;
if (FcPatternGetString(current, FC_FILE, 0, &c_filename) != FcResultMatch)
continue;
if (access(reinterpret_cast<char*>(c_filename), R_OK) != 0)
continue;
match = current;
break;
}
if (!match) {
FcPatternDestroy(pattern);
FcFontSetDestroy(font_set);
return false;
}
if (!IsFallbackFontAllowed(family)) {
bool acceptable_substitute = false;
for (int id = 0; id < 255; ++id) {
FcChar8* post_match_family;
if (FcPatternGetString(match, FC_FAMILY, id, &post_match_family) !=
FcResultMatch)
break;
acceptable_substitute =
(strcasecmp((char *)post_config_family,
(char *)post_match_family) == 0 ||
// Workaround for Issue 12530:
// requested family: "Bitstream Vera Sans"
// post_config_family: "Arial"
// post_match_family: "Bitstream Vera Sans"
// -> We should treat this case as a good match.
strcasecmp(family.c_str(),
(char *)post_match_family) == 0) ||
IsMetricCompatibleReplacement(family.c_str(),
(char*)post_match_family);
if (acceptable_substitute)
break;
}
if (!acceptable_substitute) {
FcPatternDestroy(pattern);
FcFontSetDestroy(font_set);
return false;
}
}
FcPatternDestroy(pattern);
FcChar8* c_filename;
if (FcPatternGetString(match, FC_FILE, 0, &c_filename) != FcResultMatch) {
FcFontSetDestroy(font_set);
return false;
}
int face_index;
if (FcPatternGetInteger(match, FC_INDEX, 0, &face_index) != FcResultMatch) {
FcFontSetDestroy(font_set);
return false;
}
const std::string filename(reinterpret_cast<char*>(c_filename));
unsigned out_filefaceid;
if (filefaceid_valid) {
out_filefaceid = filefaceid;
} else {
unsigned out_fileid;
const std::map<std::string, unsigned>::const_iterator
i = filename_to_fileid_.find(filename);
if (i == filename_to_fileid_.end()) {
out_fileid = next_file_id_++;
filename_to_fileid_[filename] = out_fileid;
fileid_to_filename_[out_fileid] = filename;
} else {
out_fileid = i->second;
}
// fileid stored in filename_to_fileid_ and fileid_to_filename_ is
// unique only up to the font file. We have to encode face_index for
// the out param.
out_filefaceid = FileIdAndFaceIndexToFileFaceId(out_fileid, face_index);
}
if (result_filefaceid)
*result_filefaceid = out_filefaceid;
FcChar8* c_family;
if (FcPatternGetString(match, FC_FAMILY, 0, &c_family)) {
FcFontSetDestroy(font_set);
return false;
}
int resulting_bold;
if (FcPatternGetInteger(match, FC_WEIGHT, 0, &resulting_bold))
resulting_bold = FC_WEIGHT_NORMAL;
int resulting_italic;
if (FcPatternGetInteger(match, FC_SLANT, 0, &resulting_italic))
resulting_italic = FC_SLANT_ROMAN;
// If we ask for an italic font, fontconfig might take a roman font and set
// the undocumented property FC_MATRIX to a skew matrix. It'll then say
// that the font is italic or oblique. So, if we see a matrix, we don't
// believe that it's italic.
FcValue matrix;
const bool have_matrix = FcPatternGet(match, FC_MATRIX, 0, &matrix) == 0;
// If we ask for an italic font, fontconfig might take a roman font and set
// FC_EMBOLDEN.
FcValue embolden;
const bool have_embolden =
FcPatternGet(match, FC_EMBOLDEN, 0, &embolden) == 0;
if (is_bold)
*is_bold = resulting_bold > FC_WEIGHT_MEDIUM && !have_embolden;
if (is_italic)
*is_italic = resulting_italic > FC_SLANT_ROMAN && !have_matrix;
if (result_family)
*result_family = (char *) c_family;
FcFontSetDestroy(font_set);
return true;
}
int FontConfigDirect::Open(unsigned filefaceid) {
SkAutoMutexAcquire ac(mutex_);
const std::map<unsigned, std::string>::const_iterator
i = fileid_to_filename_.find(FileFaceIdToFileId(filefaceid));
if (i == fileid_to_filename_.end())
return -1;
return open(i->second.c_str(), O_RDONLY);
}
|
Add font-equivalent mapping for a few Chinese/Japanese fonts for CrOS.
|
Add font-equivalent mapping for a few Chinese/Japanese fonts for CrOS.
The following aliases are added to be recognized in addition to what we have.
The first four are applicable to Chrome on Linux and ChromeOS. The last
two are for Chrome OS.
IPAPMincho -> MS P Mincho
IPAMincho -> MS Mincho
IPAPGothic -> MS P Gothic
IPAGothic -> MS Gothic
Song ASC -> Simsun
N Song ASC -> NSimsun
BUG=65382,chromium-os:10182,chromium-os:8757
TEST=Install IPA fonts on Linux and make sure that Windows Japanese fonts are not installed on your machine. Also, add what's added in http://codereview.chromium.org/5695005/ to your copy of /etc/fonts/local.conf. And, load cjfontalias.html attached to http://crosbug.com/10182 to make sure that all three columns look identical (each rows should be different).
Review URL: http://codereview.chromium.org/5578008
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@71295 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
fujunwei/chromium-crosswalk,ltilve/chromium,anirudhSK/chromium,ltilve/chromium,M4sse/chromium.src,jaruba/chromium.src,nacl-webkit/chrome_deps,ondra-novak/chromium.src,patrickm/chromium.src,junmin-zhu/chromium-rivertrail,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,keishi/chromium,ltilve/chromium,Pluto-tv/chromium-crosswalk,robclark/chromium,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,rogerwang/chromium,zcbenz/cefode-chromium,robclark/chromium,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,timopulkkinen/BubbleFish,hujiajie/pa-chromium,dednal/chromium.src,patrickm/chromium.src,keishi/chromium,Jonekee/chromium.src,anirudhSK/chromium,patrickm/chromium.src,rogerwang/chromium,patrickm/chromium.src,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,anirudhSK/chromium,littlstar/chromium.src,hgl888/chromium-crosswalk,zcbenz/cefode-chromium,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,anirudhSK/chromium,fujunwei/chromium-crosswalk,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,zcbenz/cefode-chromium,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,anirudhSK/chromium,rogerwang/chromium,timopulkkinen/BubbleFish,keishi/chromium,ondra-novak/chromium.src,dushu1203/chromium.src,ondra-novak/chromium.src,timopulkkinen/BubbleFish,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,timopulkkinen/BubbleFish,dushu1203/chromium.src,M4sse/chromium.src,rogerwang/chromium,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,ltilve/chromium,hgl888/chromium-crosswalk-efl,hujiajie/pa-chromium,nacl-webkit/chrome_deps,patrickm/chromium.src,dushu1203/chromium.src,littlstar/chromium.src,hgl888/chromium-crosswalk,ltilve/chromium,junmin-zhu/chromium-rivertrail,anirudhSK/chromium,littlstar/chromium.src,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,Just-D/chromium-1,Jonekee/chromium.src,zcbenz/cefode-chromium,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,jaruba/chromium.src,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,Fireblend/chromium-crosswalk,keishi/chromium,ChromiumWebApps/chromium,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,M4sse/chromium.src,mogoweb/chromium-crosswalk,ondra-novak/chromium.src,ondra-novak/chromium.src,hujiajie/pa-chromium,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,ltilve/chromium,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,jaruba/chromium.src,zcbenz/cefode-chromium,chuan9/chromium-crosswalk,nacl-webkit/chrome_deps,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,anirudhSK/chromium,Just-D/chromium-1,Just-D/chromium-1,axinging/chromium-crosswalk,M4sse/chromium.src,hgl888/chromium-crosswalk,ondra-novak/chromium.src,dednal/chromium.src,littlstar/chromium.src,dushu1203/chromium.src,keishi/chromium,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,ondra-novak/chromium.src,M4sse/chromium.src,robclark/chromium,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,hgl888/chromium-crosswalk,junmin-zhu/chromium-rivertrail,dushu1203/chromium.src,jaruba/chromium.src,robclark/chromium,Pluto-tv/chromium-crosswalk,littlstar/chromium.src,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,pozdnyakov/chromium-crosswalk,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,robclark/chromium,krieger-od/nwjs_chromium.src,anirudhSK/chromium,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,Jonekee/chromium.src,rogerwang/chromium,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,anirudhSK/chromium,rogerwang/chromium,crosswalk-project/chromium-crosswalk-efl,keishi/chromium,ltilve/chromium,zcbenz/cefode-chromium,mogoweb/chromium-crosswalk,jaruba/chromium.src,hujiajie/pa-chromium,dushu1203/chromium.src,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,keishi/chromium,anirudhSK/chromium,markYoungH/chromium.src,Chilledheart/chromium,ChromiumWebApps/chromium,ChromiumWebApps/chromium,Chilledheart/chromium,anirudhSK/chromium,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,dednal/chromium.src,patrickm/chromium.src,junmin-zhu/chromium-rivertrail,Chilledheart/chromium,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,rogerwang/chromium,chuan9/chromium-crosswalk,markYoungH/chromium.src,timopulkkinen/BubbleFish,dednal/chromium.src,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,markYoungH/chromium.src,keishi/chromium,Chilledheart/chromium,M4sse/chromium.src,Jonekee/chromium.src,patrickm/chromium.src,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,timopulkkinen/BubbleFish,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,zcbenz/cefode-chromium,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,Jonekee/chromium.src,Chilledheart/chromium,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,dednal/chromium.src,zcbenz/cefode-chromium,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,robclark/chromium,nacl-webkit/chrome_deps,markYoungH/chromium.src,robclark/chromium,Just-D/chromium-1,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,jaruba/chromium.src,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,zcbenz/cefode-chromium,patrickm/chromium.src,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,hgl888/chromium-crosswalk,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,Jonekee/chromium.src,robclark/chromium,hgl888/chromium-crosswalk,hujiajie/pa-chromium,Chilledheart/chromium,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,dednal/chromium.src,krieger-od/nwjs_chromium.src,jaruba/chromium.src,zcbenz/cefode-chromium,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,jaruba/chromium.src,mogoweb/chromium-crosswalk,littlstar/chromium.src,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,krieger-od/nwjs_chromium.src,Chilledheart/chromium,krieger-od/nwjs_chromium.src,dednal/chromium.src,timopulkkinen/BubbleFish,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,keishi/chromium,dushu1203/chromium.src,axinging/chromium-crosswalk,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Pluto-tv/chromium-crosswalk,ltilve/chromium,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,markYoungH/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,littlstar/chromium.src,rogerwang/chromium,ChromiumWebApps/chromium,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,rogerwang/chromium,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,robclark/chromium,pozdnyakov/chromium-crosswalk,ondra-novak/chromium.src,nacl-webkit/chrome_deps,hgl888/chromium-crosswalk-efl,robclark/chromium,markYoungH/chromium.src,keishi/chromium,nacl-webkit/chrome_deps,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,bright-sparks/chromium-spacewalk,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,keishi/chromium,dushu1203/chromium.src,rogerwang/chromium
|
b31a5a636e420ee76bffe59fae5f72143881704c
|
test.cpp
|
test.cpp
|
#include<iostream>
#include<string>
#include<vector>
#include<sstream>
using namespace std;
int char2int(char c){
switch(c)
{
case 'I': return 1;
case 'V': return 5;
case 'X': return 10;
case 'L': return 50;
case 'C': return 100;
case 'D': return 500;
case 'M': return 1000;
default : return 0;
}
}
int romanToInt(string s) {
if(s.empty()){
return 0;
}
// from rear to front
int sum=char2int(s[s.size()-1]);
for(int i=s.size()-1; i>=1; i--){
if(char2int(s[i]) > char2int(s[i-1])){
sum-=char2int(s[i-1]);
}else{
sum+=char2int(s[i-1]);
}
}
return sum;
}
int main(){
cout<<romanToInt("XIV")<<endl;
}
|
#include<iostream>
#include<string>
#include<vector>
#include<sstream>
#include<algorithm>
#include<limits.h>
using namespace std;
int reverse(int x) {
int sign=1;
if(x<0){
sign=-1;
x=-x;
}
long long res=0;
while(x){
res=res*10+x%10;
if(res*sign> INT_MAX || res*sign < INT_MIN){
return 0;
}
x/=10;
}
return (int)res*sign;
}
int main(){
cout<<reverse(1534236469)<<endl;
}
|
add easy
|
add easy
|
C++
|
apache-2.0
|
WIZARD-CXY/pl,WIZARD-CXY/pl,WIZARD-CXY/pl,WIZARD-CXY/pl
|
3298df820d44217127b07caf0422ad3025c20549
|
test.cpp
|
test.cpp
|
#include <cstdlib>
#include <cstdio>
#include <chrono>
#include <algorithm>
#include <numeric>
#include <chrono>
#include <getopt.h>
#include "hll.h"
#include "kthread.h"
using namespace std::chrono;
using tp = std::chrono::system_clock::time_point;
static const size_t BITS = 25;
bool test_qty(size_t lim) {
hll::hll_t t(BITS);
for(size_t i(0); i < lim; t.addh(++i));
return std::abs(t.report() - lim) <= t.est_err();
}
struct kt_data {
hll::hll_t &hll_;
const std::uint64_t n_;
const int nt_;
};
void kt_helper(void *data, long index, int tid) {
hll::hll_t &hll(((kt_data *)data)->hll_);
const std::uint64_t todo((((kt_data *)data)->n_ + ((kt_data *)data)->nt_ - 1) / ((kt_data *)data)->nt_);
for(std::uint64_t i(index * todo), e(std::min(((kt_data *)data)->n_, (index + 1) * todo)); i < e; hll.addh(i++));
}
/*
* If no arguments are provided, runs test with 1 << 22 elements.
* Otherwise, it parses the first argument and tests that integer.
*/
int main(int argc, char *argv[]) {
using clock_t = std::chrono::system_clock;
unsigned nt(8), pb(1 << 18);
std::vector<std::uint64_t> vals;
int c;
while((c = getopt(argc, argv, "p:b:")) >= 0) {
switch(c) {
case 'p': nt = atoi(optarg); break;
case 'b': pb = atoi(optarg); break;
}
}
for(c = optind; c < argc; ++c) vals.push_back(strtoull(argv[c], 0, 10));
if(vals.empty()) vals.push_back(1ull<<(BITS+1));
for(const auto val: vals) {
hll::hll_t t(BITS);
#ifndef THREADSAFE
for(size_t i(0); i < val; t.addh(i++));
#else
kt_data data {t, val, (int)nt};
kt_for(nt, &kt_helper, &data, (val + nt - 1) / nt);
#endif
auto start(clock_t::now());
t.parsum(nt, pb);
auto end(clock_t::now());
std::chrono::duration<double> timediff(end - start);
fprintf(stderr, "Time diff: %lf\n", timediff.count());
fprintf(stderr, "Quantity: %lf\n", t.report());
auto startsum(clock_t::now());
t.sum();
auto endsum(clock_t::now());
std::chrono::duration<double> timediffsum(endsum - startsum);
fprintf(stderr, "Time diff not parallel: %lf\n", timediffsum.count());
fprintf(stderr, "Using %i threads is %4lf%% as fast as 1.\n", nt, timediffsum.count() / timediff.count() * 100.);
fprintf(stderr, "Quantity: %lf\n", t.report());
fprintf(stderr, "Quantity expected: %" PRIu64 ". Quantity estimated: %lf. Error bounds: %lf. Error: %lf. Within bounds? %s\n",
val, t.report(), t.est_err(), std::abs(val - t.report()), t.est_err() >= std::abs(val - t.report()) ? "true": "false");
}
return EXIT_SUCCESS;
}
|
#include <cstdlib>
#include <cstdio>
#include <chrono>
#include <algorithm>
#include <numeric>
#include <chrono>
#include <getopt.h>
#include "hll.h"
#include "kthread.h"
using namespace std::chrono;
using tp = std::chrono::system_clock::time_point;
static const size_t BITS = 25;
bool test_qty(size_t lim) {
hll::hll_t t(BITS);
for(size_t i(0); i < lim; t.addh(++i));
return std::abs(t.report() - lim) <= t.est_err();
}
struct kt_data {
hll::hll_t &hll_;
const std::uint64_t n_;
const int nt_;
};
void kt_helper(void *data, long index, int tid) {
hll::hll_t &hll(((kt_data *)data)->hll_);
const std::uint64_t todo((((kt_data *)data)->n_ + ((kt_data *)data)->nt_ - 1) / ((kt_data *)data)->nt_);
for(std::uint64_t i(index * todo), e(std::min(((kt_data *)data)->n_, (index + 1) * todo)); i < e; hll.addh(i++));
}
void usage() {
std::fprintf(stderr, "Usage: ./test <flags>\nFlags:\n-p\tSet number of threads. [8].\n-b\tSet size of sketch. [1 << 18]\n");
std::exit(EXIT_FAILURE);
}
/*
* If no arguments are provided, runs test with 1 << 22 elements.
* Otherwise, it parses the first argument and tests that integer.
*/
int main(int argc, char *argv[]) {
if(argc < 2) usage();
using clock_t = std::chrono::system_clock;
unsigned nt(8), pb(1 << 18);
std::vector<std::uint64_t> vals;
int c;
while((c = getopt(argc, argv, "p:b:h")) >= 0) {
switch(c) {
case 'p': nt = atoi(optarg); break;
case 'b': pb = atoi(optarg); break;
case 'h': case '?': usage();
}
}
for(c = optind; c < argc; ++c) vals.push_back(strtoull(argv[c], 0, 10));
if(vals.empty()) vals.push_back(1ull<<(BITS+1));
for(const auto val: vals) {
hll::hll_t t(BITS);
#ifndef THREADSAFE
for(size_t i(0); i < val; t.addh(i++));
#else
kt_data data {t, val, (int)nt};
kt_for(nt, &kt_helper, &data, (val + nt - 1) / nt);
#endif
auto start(clock_t::now());
t.parsum(nt, pb);
auto end(clock_t::now());
std::chrono::duration<double> timediff(end - start);
fprintf(stderr, "Time diff: %lf\n", timediff.count());
fprintf(stderr, "Quantity: %lf\n", t.report());
auto startsum(clock_t::now());
t.sum();
auto endsum(clock_t::now());
std::chrono::duration<double> timediffsum(endsum - startsum);
fprintf(stderr, "Time diff not parallel: %lf\n", timediffsum.count());
fprintf(stderr, "Using %i threads is %4lf%% as fast as 1.\n", nt, timediffsum.count() / timediff.count() * 100.);
fprintf(stderr, "Quantity: %lf\n", t.report());
fprintf(stderr, "Quantity expected: %" PRIu64 ". Quantity estimated: %lf. Error bounds: %lf. Error: %lf. Within bounds? %s\n",
val, t.report(), t.est_err(), std::abs(val - t.report()), t.est_err() >= std::abs(val - t.report()) ? "true": "false");
}
return EXIT_SUCCESS;
}
|
Add usage for test.
|
Add usage for test.
|
C++
|
mit
|
dnbh/hll,dnbh/hll
|
3d04dc8fed252980faf87e8e54bd53e25d333605
|
src/input.cpp
|
src/input.cpp
|
#include "input.h"
#include "engine.h"
P<WindowManager> InputHandler::windowManager;
bool InputHandler::touch_screen = false;
sf::Transform InputHandler::mouse_transform;
PVector<InputEventHandler> InputHandler::input_event_handlers;
sf::Vector2f InputHandler::mousePos;
float InputHandler::mouse_wheel_delta;
bool InputHandler::mouse_button_down[sf::Mouse::ButtonCount];
bool InputHandler::keyboard_button_down[sf::Keyboard::KeyCount];
bool InputHandler::mouseButtonDown[sf::Mouse::ButtonCount];
bool InputHandler::mouseButtonPressed[sf::Mouse::ButtonCount];
bool InputHandler::mouseButtonReleased[sf::Mouse::ButtonCount];
bool InputHandler::keyboardButtonDown[sf::Keyboard::KeyCount];
bool InputHandler::keyboardButtonPressed[sf::Keyboard::KeyCount];
bool InputHandler::keyboardButtonReleased[sf::Keyboard::KeyCount];
InputEventHandler::InputEventHandler()
{
InputHandler::input_event_handlers.push_back(this);
}
InputEventHandler::~InputEventHandler()
{
}
void InputEventHandler::handleKeyPress(sf::Keyboard::Key key, int unicode)
{
}
void InputHandler::initialize()
{
memset(mouse_button_down, 0, sizeof(mouse_button_down));
memset(keyboard_button_down, 0, sizeof(keyboard_button_down));
}
void InputHandler::update()
{
if (!windowManager)
windowManager = engine->getObject("windowManager");
for(unsigned int n=0; n<sf::Keyboard::KeyCount; n++)
{
bool down = keyboard_button_down[n];
keyboardButtonPressed[n] = (!keyboardButtonDown[n] && down);
keyboardButtonReleased[n] = (keyboardButtonDown[n] && !down);
keyboardButtonDown[n] = down;
}
#ifdef __ANDROID__
if (sf::Touch::isDown(0))
{
mousePos = realWindowPosToVirtual(sf::Touch::getPosition(0));
mouse_button_down[sf::Mouse::Left] = true;
}else{
if (mouse_button_down[sf::Mouse::Left])
{
mouse_button_down[sf::Mouse::Left] = false;
}
else
{
mousePos.x = -1;
mousePos.y = -1;
}
}
#else
mousePos = realWindowPosToVirtual(sf::Mouse::getPosition());
mousePos = mouse_transform.transformPoint(mousePos);
#endif
for(unsigned int n=0; n<sf::Mouse::ButtonCount; n++)
{
bool down = mouse_button_down[n];
mouseButtonPressed[n] = (!mouseButtonDown[n] && down);
mouseButtonReleased[n] = (mouseButtonDown[n] && !down);
mouseButtonDown[n] = down;
}
if (touch_screen)
{
bool any_button_down = false;
for(unsigned int n=0; n<sf::Mouse::ButtonCount; n++)
if (mouseButtonDown[n] || mouseButtonReleased[n])
any_button_down = true;
if (!any_button_down)
{
mousePos.x = -1;
mousePos.y = -1;
}
}
}
void InputHandler::fireKeyEvent(sf::Keyboard::Key key, int unicode)
{
foreach(InputEventHandler, e, input_event_handlers)
{
e->handleKeyPress(key, unicode);
}
}
sf::Vector2f InputHandler::realWindowPosToVirtual(sf::Vector2i position)
{
#ifndef __ANDROID__
sf::FloatRect viewport = windowManager->window.getView().getViewport();
sf::Vector2f pos = sf::Vector2f(position - windowManager->window.getPosition());
pos.x -= viewport.left * float(windowManager->window.getSize().x);
pos.y -= viewport.top * float(windowManager->window.getSize().y);
pos.x *= float(windowManager->virtualSize.x) / float(windowManager->window.getSize().x) / viewport.width;
pos.y *= float(windowManager->virtualSize.y) / float(windowManager->window.getSize().y) / viewport.height;
#else
sf::Vector2f pos = sf::Vector2f(position - windowManager->window.getPosition());
pos.x *= float(windowManager->virtualSize.x) / float(windowManager->window.getSize().x);
pos.y *= float(windowManager->virtualSize.y) / float(windowManager->window.getSize().y);
#endif
return pos;
}
|
#include "input.h"
#include "engine.h"
P<WindowManager> InputHandler::windowManager;
bool InputHandler::touch_screen = false;
sf::Transform InputHandler::mouse_transform;
PVector<InputEventHandler> InputHandler::input_event_handlers;
sf::Vector2f InputHandler::mousePos;
float InputHandler::mouse_wheel_delta;
bool InputHandler::mouse_button_down[sf::Mouse::ButtonCount];
bool InputHandler::keyboard_button_down[sf::Keyboard::KeyCount];
bool InputHandler::mouseButtonDown[sf::Mouse::ButtonCount];
bool InputHandler::mouseButtonPressed[sf::Mouse::ButtonCount];
bool InputHandler::mouseButtonReleased[sf::Mouse::ButtonCount];
bool InputHandler::keyboardButtonDown[sf::Keyboard::KeyCount];
bool InputHandler::keyboardButtonPressed[sf::Keyboard::KeyCount];
bool InputHandler::keyboardButtonReleased[sf::Keyboard::KeyCount];
InputEventHandler::InputEventHandler()
{
InputHandler::input_event_handlers.push_back(this);
}
InputEventHandler::~InputEventHandler()
{
}
void InputEventHandler::handleKeyPress(sf::Keyboard::Key key, int unicode)
{
}
void InputHandler::initialize()
{
memset(mouse_button_down, 0, sizeof(mouse_button_down));
memset(keyboard_button_down, 0, sizeof(keyboard_button_down));
}
void InputHandler::update()
{
if (!windowManager)
windowManager = engine->getObject("windowManager");
for(unsigned int n=0; n<sf::Keyboard::KeyCount; n++)
{
bool down = keyboard_button_down[n];
keyboardButtonPressed[n] = (!keyboardButtonDown[n] && down);
keyboardButtonReleased[n] = (keyboardButtonDown[n] && !down);
keyboardButtonDown[n] = down;
}
#ifdef __ANDROID__
if (sf::Touch::isDown(0))
{
mousePos = realWindowPosToVirtual(sf::Touch::getPosition(0));
mouse_button_down[sf::Mouse::Left] = true;
}else{
if (mouse_button_down[sf::Mouse::Left])
{
mouse_button_down[sf::Mouse::Left] = false;
}
else
{
mousePos.x = -1;
mousePos.y = -1;
}
}
#else
mousePos = realWindowPosToVirtual(sf::Mouse::getPosition());
mousePos = mouse_transform.transformPoint(mousePos);
#endif
for(unsigned int n=0; n<sf::Mouse::ButtonCount; n++)
{
bool down = mouse_button_down[n];
mouseButtonPressed[n] = (!mouseButtonDown[n] && down);
mouseButtonReleased[n] = (mouseButtonDown[n] && !down);
mouseButtonDown[n] = down;
}
if (touch_screen)
{
bool any_button_down = false;
for(unsigned int n=0; n<sf::Mouse::ButtonCount; n++)
if (mouseButtonDown[n] || mouseButtonReleased[n])
any_button_down = true;
if (!any_button_down)
{
mousePos.x = -1;
mousePos.y = -1;
}
}
}
void InputHandler::fireKeyEvent(sf::Keyboard::Key key, int unicode)
{
foreach(InputEventHandler, e, input_event_handlers)
{
e->handleKeyPress(key, unicode);
}
}
sf::Vector2f InputHandler::realWindowPosToVirtual(sf::Vector2i position)
{
#ifdef __ANDROID__
sf::FloatRect viewport = windowManager->window.getView().getViewport();
sf::Vector2f pos = sf::Vector2f(position - windowManager->window.getPosition());
pos.x -= viewport.left * float(windowManager->window.getSize().x);
pos.y -= viewport.top * float(windowManager->window.getSize().y);
pos.x *= float(windowManager->virtualSize.x) / float(windowManager->window.getSize().x) / viewport.width;
pos.y *= float(windowManager->virtualSize.y) / float(windowManager->window.getSize().y) / viewport.height;
#else
sf::Vector2f pos = sf::Vector2f(position - windowManager->window.getPosition());
pos.x *= float(windowManager->virtualSize.x) / float(windowManager->window.getSize().x);
pos.y *= float(windowManager->virtualSize.y) / float(windowManager->window.getSize().y);
#endif
return pos;
}
|
define was wrong way around.
|
define was wrong way around.
|
C++
|
mit
|
daid/SeriousProton,daid/SeriousProton,daid/SeriousProton,daid/SeriousProton,daid/SeriousProton,daid/SeriousProton
|
9925b45e6ff8975d71c49c3c70e4c139d89bb737
|
source/main.cpp
|
source/main.cpp
|
#include <ctrcommon/common.hpp>
#include <sstream>
#include <iomanip>
typedef enum {
INSTALL,
DELETE
} Mode;
bool ui_display_install_progress(int progress) {
std::stringstream stream;
stream << "Installing: [";
int progressBars = progress / 4;
for(int i = 0; i < 25; i++) {
if(i < progressBars) {
stream << '|';
} else {
stream << ' ';
}
}
std::ios state(NULL);
state.copyfmt(stream);
stream << "] " << std::setfill('0') << std::setw(3) << progress;
stream.copyfmt(state);
stream << "%" << "\n";
stream << "Press B to cancel." << "\n";
std::string str = stream.str();
screen_begin_draw(TOP_SCREEN);
screen_clear(0, 0, 0);
screen_draw_string(str, (screen_get_width() - screen_get_str_width(str)) / 2, (screen_get_height() - screen_get_str_height(str)) / 2, 255, 255, 255);
screen_end_draw();
screen_swap_buffers_quick();;
input_poll();
return !input_is_pressed(BUTTON_B);
}
void ui_display_deleting() {
std::string msg = "Deleting title...";
screen_begin_draw(TOP_SCREEN);
screen_clear(0, 0, 0);
screen_draw_string(msg, (screen_get_width() - screen_get_str_width(msg)) / 2, (screen_get_height() - screen_get_str_height(msg)) / 2, 255, 255, 255);
screen_end_draw();
screen_swap_buffers();
}
void ui_display_result(bool install, bool state) {
std::string msg = install ? (state ? "Install succeeded! Press start." : "Install failed! Press start.") : (state ? "Delete succeeded! Press start." : "Delete failed! Press start.");
while(platform_is_running()) {
input_poll();
if(input_is_pressed(BUTTON_START)) {
break;
}
screen_begin_draw(TOP_SCREEN);
screen_clear(0, 0, 0);
screen_draw_string(msg, (screen_get_width() - screen_get_str_width(msg)) / 2, (screen_get_height() - screen_get_str_height(msg)) / 2, 255, 255, 255);
screen_end_draw();
screen_swap_buffers();
}
}
bool ui_prompt_operation(Mode mode, std::string name) {
std::stringstream stream;
stream << (mode == INSTALL ? "Install" : "Delete") << " the selected title?" << "\n";
stream << name << "\n";
stream << "Press A to confirm, B to cancel." << "\n";
std::string str = stream.str();
while(platform_is_running()) {
input_poll();
if(input_is_pressed(BUTTON_A)) {
return true;
}
if(input_is_pressed(BUTTON_B)) {
return false;
}
screen_begin_draw(TOP_SCREEN);
screen_clear(0, 0, 0);
screen_draw_string(str, (screen_get_width() - screen_get_str_width(str)) / 2, (screen_get_height() - screen_get_str_height(str)) / 2, 255, 255, 255);
screen_end_draw();
screen_swap_buffers();
}
return false;
}
int main(int argc, char **argv) {
if(!platform_init()) {
return 0;
}
std::vector<std::string> extensions;
extensions.push_back("cia");
MediaType destination = SD;
Mode mode = INSTALL;
u64 freeSpace = fs_get_free_space(destination);
auto onLoop = [&]() {
bool breakLoop = false;
if(input_is_pressed(BUTTON_L)) {
if(destination == SD) {
destination = NAND;
} else {
destination = SD;
}
freeSpace = fs_get_free_space(destination);
if(mode == DELETE) {
breakLoop = true;
}
}
if(input_is_pressed(BUTTON_R)) {
if(mode == INSTALL) {
mode = DELETE;
} else {
mode = INSTALL;
}
breakLoop = true;
}
std::stringstream stream;
stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL ? "Install" : "Delete") << "\n";
stream << "L - Switch Destination, R - Switch Mode" << "\n";
std::string str = stream.str();
screen_draw_string(str, (screen_get_width() - screen_get_str_width(str)) / 2, screen_get_height() - 4 - screen_get_str_height(str), 255, 255, 255);
return breakLoop;
};
while(platform_is_running()) {
std::string targetInstall;
App targetDelete;
bool obtained = false;
if(mode == INSTALL) {
obtained = ui_select_file(&targetInstall, "sdmc:", extensions, onLoop);
} else if(mode == DELETE) {
obtained = ui_select_app(&targetDelete, destination, onLoop);
}
if(obtained) {
if(mode == INSTALL) {
if(ui_prompt_operation(mode, targetInstall)) {
ui_display_result(true, app_install(destination, targetInstall, &ui_display_install_progress));
}
} else if(mode == DELETE) {
if(ui_prompt_operation(mode, targetDelete.productCode)) {
ui_display_deleting();
ui_display_result(false, app_delete(targetDelete));
}
}
freeSpace = fs_get_free_space(destination);
}
}
platform_cleanup();
return 0;
}
|
#include <ctrcommon/common.hpp>
#include <sstream>
#include <iomanip>
typedef enum {
INSTALL,
DELETE
} Mode;
bool ui_display_install_progress(int progress) {
std::stringstream stream;
stream << "Installing: [";
int progressBars = progress / 4;
for(int i = 0; i < 25; i++) {
if(i < progressBars) {
stream << '|';
} else {
stream << ' ';
}
}
std::ios state(NULL);
state.copyfmt(stream);
stream << "] " << std::setfill('0') << std::setw(3) << progress;
stream.copyfmt(state);
stream << "%" << "\n";
stream << "Press B to cancel." << "\n";
std::string str = stream.str();
screen_begin_draw(TOP_SCREEN);
screen_clear(0, 0, 0);
screen_draw_string(str, (screen_get_width() - screen_get_str_width(str)) / 2, (screen_get_height() - screen_get_str_height(str)) / 2, 255, 255, 255);
screen_end_draw();
screen_swap_buffers_quick();;
input_poll();
return !input_is_pressed(BUTTON_B);
}
void ui_display_deleting() {
std::string msg = "Deleting title...";
screen_begin_draw(TOP_SCREEN);
screen_clear(0, 0, 0);
screen_draw_string(msg, (screen_get_width() - screen_get_str_width(msg)) / 2, (screen_get_height() - screen_get_str_height(msg)) / 2, 255, 255, 255);
screen_end_draw();
screen_swap_buffers();
}
void ui_display_result(bool install, bool state) {
std::string msg = install ? (state ? "Install succeeded! Press start." : "Install failed! Press start.") : (state ? "Delete succeeded! Press start." : "Delete failed! Press start.");
while(platform_is_running()) {
input_poll();
if(input_is_pressed(BUTTON_START)) {
break;
}
screen_begin_draw(TOP_SCREEN);
screen_clear(0, 0, 0);
screen_draw_string(msg, (screen_get_width() - screen_get_str_width(msg)) / 2, (screen_get_height() - screen_get_str_height(msg)) / 2, 255, 255, 255);
screen_end_draw();
screen_swap_buffers();
}
}
bool ui_prompt_operation(Mode mode, std::string name) {
std::stringstream stream;
stream << (mode == INSTALL ? "Install" : "Delete") << " the selected title?" << "\n";
stream << "Press A to confirm, B to cancel." << "\n";
std::string str = stream.str();
while(platform_is_running()) {
input_poll();
if(input_is_pressed(BUTTON_A)) {
return true;
}
if(input_is_pressed(BUTTON_B)) {
return false;
}
screen_begin_draw(TOP_SCREEN);
screen_clear(0, 0, 0);
screen_draw_string(str, (screen_get_width() - screen_get_str_width(str)) / 2, (screen_get_height() - screen_get_str_height(str)) / 2, 255, 255, 255);
screen_end_draw();
screen_swap_buffers();
}
return false;
}
int main(int argc, char **argv) {
if(!platform_init()) {
return 0;
}
std::vector<std::string> extensions;
extensions.push_back("cia");
MediaType destination = SD;
Mode mode = INSTALL;
u64 freeSpace = fs_get_free_space(destination);
auto onLoop = [&]() {
bool breakLoop = false;
if(input_is_pressed(BUTTON_L)) {
if(destination == SD) {
destination = NAND;
} else {
destination = SD;
}
freeSpace = fs_get_free_space(destination);
if(mode == DELETE) {
breakLoop = true;
}
}
if(input_is_pressed(BUTTON_R)) {
if(mode == INSTALL) {
mode = DELETE;
} else {
mode = INSTALL;
}
breakLoop = true;
}
std::stringstream stream;
stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL ? "Install" : "Delete") << "\n";
stream << "L - Switch Destination, R - Switch Mode" << "\n";
std::string str = stream.str();
screen_draw_string(str, (screen_get_width() - screen_get_str_width(str)) / 2, screen_get_height() - 4 - screen_get_str_height(str), 255, 255, 255);
return breakLoop;
};
while(platform_is_running()) {
std::string targetInstall;
App targetDelete;
bool obtained = false;
if(mode == INSTALL) {
obtained = ui_select_file(&targetInstall, "sdmc:", extensions, onLoop);
} else if(mode == DELETE) {
obtained = ui_select_app(&targetDelete, destination, onLoop);
}
if(obtained) {
if(mode == INSTALL) {
if(ui_prompt_operation(mode, targetInstall)) {
ui_display_result(true, app_install(destination, targetInstall, &ui_display_install_progress));
}
} else if(mode == DELETE) {
if(ui_prompt_operation(mode, targetDelete.productCode)) {
ui_display_deleting();
ui_display_result(false, app_delete(targetDelete));
}
}
freeSpace = fs_get_free_space(destination);
}
}
platform_cleanup();
return 0;
}
|
Remove name printing from testing.
|
Remove name printing from testing.
|
C++
|
mit
|
Steveice10/FBI,Steveice10/FBI,Steveice10/FBI
|
b56d0995203078ff2c49aa57cccb423449a99377
|
source/main.cpp
|
source/main.cpp
|
#include <ctrcommon/app.hpp>
#include <ctrcommon/fs.hpp>
#include <ctrcommon/gpu.hpp>
#include <ctrcommon/input.hpp>
#include <ctrcommon/nor.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>
#include "rop.h"
#include <sys/errno.h>
#include <stdio.h>
#include <string.h>
#include <sstream>
#include <iomanip>
typedef enum {
INSTALL_CIA,
DELETE_CIA,
DELETE_TITLE,
LAUNCH_TITLE
} Mode;
std::vector<std::string> extensions = {"cia"};
bool exit = false;
bool showNetworkPrompts = true;
u64 freeSpace = 0;
MediaType destination = SD;
Mode mode = INSTALL_CIA;
int prevProgress = -1;
std::string installInfo = "";
bool onProgress(u64 pos, u64 totalSize) {
u32 progress = (u32) ((pos * 100) / totalSize);
if(prevProgress != (int) progress) {
prevProgress = (int) progress;
std::stringstream details;
details << installInfo;
details << "Press B to cancel.";
uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress);
}
inputPoll();
return !inputIsPressed(BUTTON_B);
}
void networkInstall() {
while(platformIsRunning()) {
gpuClearScreens();
RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN, [&](std::stringstream& infoStream) {
if(inputIsPressed(BUTTON_A)) {
showNetworkPrompts = !showNetworkPrompts;
}
infoStream << "\n";
infoStream << "Prompts: " << (showNetworkPrompts ? "Enabled" : "Disabled") << "\n";
infoStream << "Press A to toggle prompts.";
});
if(file.fd == NULL) {
break;
}
std::stringstream confirmStream;
confirmStream << "Install the received application?" << "\n";
confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)";
if(!showNetworkPrompts || uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {
AppResult ret = appInstall(destination, file.fd, file.fileSize, &onProgress);
prevProgress = -1;
if(showNetworkPrompts || ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Install ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret);
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
}
fclose(file.fd);
}
}
void installROP() {
u32 selected = 0;
bool dirty = true;
while(platformIsRunning()) {
inputPoll();
if(inputIsPressed(BUTTON_B)) {
break;
}
if(inputIsPressed(BUTTON_A)) {
std::stringstream stream;
stream << "Install the selected ROP?" << "\n";
stream << ropNames[selected];
if(uiPrompt(TOP_SCREEN, stream.str(), true)) {
u16 userSettingsOffset = 0;
bool result = norRead(0x20, &userSettingsOffset, 2) && norWrite(userSettingsOffset << 3, rops[selected], ROP_SIZE);
std::stringstream resultMsg;
resultMsg << "ROP installation ";
if(result) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << platformGetErrorString(platformGetError());
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
}
dirty = true;
}
if(inputIsPressed(BUTTON_LEFT)) {
if(selected == 0) {
selected = ROP_COUNT - 1;
} else {
selected--;
}
dirty = true;
}
if(inputIsPressed(BUTTON_RIGHT)) {
if(selected >= ROP_COUNT - 1) {
selected = 0;
} else {
selected++;
}
dirty = true;
}
if(dirty) {
std::stringstream stream;
stream << "Select a ROP to install." << "\n";
stream << "< " << ropNames[selected] << " >" << "\n";
stream << "Press A to install, B to cancel.";
uiDisplayMessage(TOP_SCREEN, stream.str());
}
}
}
bool installCIA(MediaType destination, const std::string path, const std::string fileName) {
std::string name = fileName;
if(name.length() > 40) {
name.resize(40);
name += "...";
}
std::stringstream batchInstallStream;
batchInstallStream << name << "\n";
installInfo = batchInstallStream.str();
AppResult ret = appInstallFile(destination, path, &onProgress);
prevProgress = -1;
installInfo = "";
if(ret != APP_SUCCESS && platformHasError()) {
Error error = platformGetError();
if(error.module == MODULE_NN_AM && error.description == DESCRIPTION_ALREADY_EXISTS) {
std::stringstream overwriteMsg;
overwriteMsg << "Title already installed, overwrite?" << "\n";
overwriteMsg << name;
if(uiPrompt(TOP_SCREEN, overwriteMsg.str(), true)) {
uiDisplayMessage(TOP_SCREEN, "Deleting title...");
AppResult deleteRet = appDelete(appGetCiaInfo(path, destination));
if(deleteRet != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Delete failed!" << "\n";
resultMsg << name << "\n";
resultMsg << appGetResultString(deleteRet);
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
return false;
}
ret = appInstallFile(destination, path, &onProgress);
prevProgress = -1;
installInfo = "";
} else {
platformSetError(error);
}
} else {
platformSetError(error);
}
}
if(ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Install failed!" << "\n";
resultMsg << name << "\n";
resultMsg << appGetResultString(ret);
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
return false;
}
return true;
}
bool deleteCIA(const std::string path, const std::string fileName) {
std::string name = fileName;
if(name.length() > 40) {
name.resize(40);
name += "...";
}
std::stringstream deleteStream;
deleteStream << "Deleting CIA..." << "\n";
deleteStream << name;
uiDisplayMessage(TOP_SCREEN, deleteStream.str());
if(remove(path.c_str()) != 0) {
std::stringstream resultMsg;
resultMsg << "Delete failed!" << "\n";
resultMsg << name << "\n";
resultMsg << strerror(errno);
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
return false;
}
return true;
}
bool deleteTitle(App app) {
uiDisplayMessage(TOP_SCREEN, "Deleting title...");
AppResult ret = appDelete(app);
if(ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Delete failed!" << "\n";
resultMsg << appGetResultString(ret);
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
return false;
}
return true;
}
bool launchTitle(App app) {
uiDisplayMessage(TOP_SCREEN, "Launching title...");
AppResult ret = appLaunch(app);
if(ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Launch failed!" << "\n";
resultMsg << appGetResultString(ret);
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
return false;
}
return true;
}
bool onLoop() {
bool launcher = platformHasLauncher();
if(launcher && inputIsPressed(BUTTON_START)) {
exit = true;
return true;
}
bool breakLoop = false;
if(inputIsPressed(BUTTON_L)) {
if(destination == SD) {
destination = NAND;
} else {
destination = SD;
}
freeSpace = fsGetFreeSpace(destination);
if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
breakLoop = true;
}
}
if(inputIsPressed(BUTTON_R)) {
if(mode == INSTALL_CIA) {
mode = DELETE_CIA;
} else if(mode == DELETE_CIA) {
mode = DELETE_TITLE;
breakLoop = true;
} else if(mode == DELETE_TITLE) {
mode = LAUNCH_TITLE;
} else if(mode == LAUNCH_TITLE) {
mode = INSTALL_CIA;
breakLoop = true;
}
}
if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) {
networkInstall();
}
if(inputIsPressed(BUTTON_SELECT)) {
installROP();
}
std::stringstream stream;
stream << "Battery: ";
if(platformIsBatteryCharging()) {
stream << "Charging";
} else {
for(u32 i = 0; i < platformGetBatteryLevel(); i++) {
stream << "|";
}
}
stream << ", WiFi: ";
if(!platformIsWifiConnected()) {
stream << "Disconnected";
} else {
for(u32 i = 0; i < platformGetWifiLevel(); i++) {
stream << "|";
}
}
stream << "\n";
stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n";
stream << "L - Switch Destination, R - Switch Mode" << "\n";
if(mode == INSTALL_CIA) {
stream << "X - Install all CIAs in the current directory" << "\n";
stream << "Y - Receive an app over the network" << "\n";
} else if(mode == DELETE_CIA) {
stream << "X - Delete all CIAs in the current directory" << "\n";
}
stream << "SELECT - Install MSET ROP";
if(launcher) {
stream << "\n" << "START - Exit to launcher";
}
std::string str = stream.str();
const std::string title = "FBI v1.4.5";
gputDrawString(title, (gpuGetViewportWidth() - gputGetStringWidth(title, 16)) / 2, (gpuGetViewportHeight() - gputGetStringHeight(title, 16) + gputGetStringHeight(str, 8)) / 2, 16, 16);
gputDrawString(str, (gpuGetViewportWidth() - gputGetStringWidth(str, 8)) / 2, 4, 8, 8);
return breakLoop;
}
int main(int argc, char **argv) {
if(!platformInit(argc)) {
return 0;
}
freeSpace = fsGetFreeSpace(destination);
while(platformIsRunning()) {
if(mode == INSTALL_CIA || mode == DELETE_CIA) {
uiDisplayMessage(BOTTOM_SCREEN, "Loading file list...");
std::string fileTarget;
uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {
if(inputIsPressed(BUTTON_X)) {
std::stringstream confirmMsg;
if(mode == INSTALL_CIA) {
confirmMsg << "Install ";
} else {
confirmMsg << "Delete ";
}
confirmMsg << "all CIAs in the current directory?";
if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
bool failed = false;
std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory);
for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) {
std::string path = (*it).path;
std::string name = (*it).name;
if(!fsIsDirectory(name) && fsHasExtensions(name, extensions)) {
if(mode == INSTALL_CIA) {
if(!installCIA(destination, path, name)) {
failed = true;
break;
}
} else {
if(deleteCIA(path, name)) {
updateList = true;
} else {
failed = true;
break;
}
}
}
}
if(!failed) {
std::stringstream successMsg;
if(mode == INSTALL_CIA) {
successMsg << "Install ";
} else {
successMsg << "Delete ";
}
successMsg << "succeeded!";
uiPrompt(TOP_SCREEN, successMsg.str(), false);
}
freeSpace = fsGetFreeSpace(destination);
}
}
return onLoop();
}, [&](const std::string path, bool &updateList) {
std::stringstream confirmMsg;
if(mode == INSTALL_CIA) {
confirmMsg << "Install ";
} else {
confirmMsg << "Delete ";
}
confirmMsg << "the selected CIA?";
if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
bool success = false;
if(mode == INSTALL_CIA) {
success = installCIA(destination, path, fsGetFileName(path));
} else {
success = deleteCIA(path, fsGetFileName(path));
}
if(success) {
std::stringstream successMsg;
if(mode == INSTALL_CIA) {
successMsg << "Install ";
} else {
successMsg << "Delete ";
}
successMsg << "succeeded!";
uiPrompt(TOP_SCREEN, successMsg.str(), false);
}
freeSpace = fsGetFreeSpace(destination);
}
return false;
});
} else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
uiDisplayMessage(BOTTOM_SCREEN, "Loading title list...");
App appTarget;
uiSelectApp(&appTarget, destination, [&](bool &updateList) {
return onLoop();
}, [&](App app, bool &updateList) {
if(mode == DELETE_TITLE) {
if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true) && (destination != NAND || uiPrompt(TOP_SCREEN, "You are about to delete a title from the NAND.\nTHIS HAS THE POTENTIAL TO BRICK YOUR 3DS!\nAre you sure you wish to continue?", true))) {
if(deleteTitle(app)) {
uiPrompt(TOP_SCREEN, "Delete succeeded!", false);
}
updateList = true;
freeSpace = fsGetFreeSpace(destination);
}
} else if(mode == LAUNCH_TITLE) {
if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) {
if(launchTitle(app)) {
while(true) {
}
}
}
}
return false;
});
}
if(exit) {
break;
}
}
platformCleanup();
return 0;
}
|
#include <ctrcommon/app.hpp>
#include <ctrcommon/fs.hpp>
#include <ctrcommon/gpu.hpp>
#include <ctrcommon/input.hpp>
#include <ctrcommon/nor.hpp>
#include <ctrcommon/platform.hpp>
#include <ctrcommon/ui.hpp>
#include "rop.h"
#include <sys/errno.h>
#include <stdio.h>
#include <string.h>
#include <sstream>
#include <iomanip>
typedef enum {
INSTALL_CIA,
DELETE_CIA,
DELETE_TITLE,
LAUNCH_TITLE
} Mode;
std::vector<std::string> extensions = {"cia"};
bool exit = false;
bool showNetworkPrompts = true;
u64 freeSpace = 0;
MediaType destination = SD;
Mode mode = INSTALL_CIA;
int prevProgress = -1;
std::string installInfo = "";
bool onProgress(u64 pos, u64 totalSize) {
u32 progress = (u32) ((pos * 100) / totalSize);
if(prevProgress != (int) progress) {
prevProgress = (int) progress;
std::stringstream details;
details << installInfo;
details << "Press B to cancel.";
uiDisplayProgress(TOP_SCREEN, "Installing", details.str(), true, progress);
}
inputPoll();
return !inputIsPressed(BUTTON_B);
}
void networkInstall() {
while(platformIsRunning()) {
gpuClearScreens();
RemoteFile file = uiAcceptRemoteFile(TOP_SCREEN, [&](std::stringstream& infoStream) {
if(inputIsPressed(BUTTON_A)) {
showNetworkPrompts = !showNetworkPrompts;
}
infoStream << "\n";
infoStream << "Prompts: " << (showNetworkPrompts ? "Enabled" : "Disabled") << "\n";
infoStream << "Press A to toggle prompts.";
});
if(file.fd == NULL) {
break;
}
std::stringstream confirmStream;
confirmStream << "Install the received application?" << "\n";
confirmStream << "Size: " << file.fileSize << " bytes (" << std::fixed << std::setprecision(2) << file.fileSize / 1024.0f / 1024.0f << "MB)";
if(!showNetworkPrompts || uiPrompt(TOP_SCREEN, confirmStream.str(), true)) {
AppResult ret = appInstall(destination, file.fd, file.fileSize, &onProgress);
prevProgress = -1;
if(showNetworkPrompts || ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Install ";
if(ret == APP_SUCCESS) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << appGetResultString(ret);
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
freeSpace = fsGetFreeSpace(destination);
}
}
fclose(file.fd);
}
}
void installROP() {
u32 selected = 0;
bool dirty = true;
while(platformIsRunning()) {
inputPoll();
if(inputIsPressed(BUTTON_B)) {
break;
}
if(inputIsPressed(BUTTON_A)) {
std::stringstream stream;
stream << "Install the selected ROP?" << "\n";
stream << ropNames[selected];
if(uiPrompt(TOP_SCREEN, stream.str(), true)) {
u16 userSettingsOffset = 0;
bool result = norRead(0x20, &userSettingsOffset, 2) && norWrite(userSettingsOffset << 3, rops[selected], ROP_SIZE);
std::stringstream resultMsg;
resultMsg << "ROP installation ";
if(result) {
resultMsg << "succeeded!";
} else {
resultMsg << "failed!" << "\n";
resultMsg << platformGetErrorString(platformGetError());
}
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
}
dirty = true;
}
if(inputIsPressed(BUTTON_LEFT)) {
if(selected == 0) {
selected = ROP_COUNT - 1;
} else {
selected--;
}
dirty = true;
}
if(inputIsPressed(BUTTON_RIGHT)) {
if(selected >= ROP_COUNT - 1) {
selected = 0;
} else {
selected++;
}
dirty = true;
}
if(dirty) {
std::stringstream stream;
stream << "Select a ROP to install." << "\n";
stream << "< " << ropNames[selected] << " >" << "\n";
stream << "Press A to install, B to cancel.";
uiDisplayMessage(TOP_SCREEN, stream.str());
}
}
}
bool installCIA(MediaType destination, const std::string path, const std::string fileName) {
std::string name = fileName;
if(name.length() > 40) {
name.resize(40);
name += "...";
}
std::stringstream batchInstallStream;
batchInstallStream << name << "\n";
installInfo = batchInstallStream.str();
AppResult ret = appInstallFile(destination, path, &onProgress);
prevProgress = -1;
installInfo = "";
if(ret != APP_SUCCESS && platformHasError()) {
Error error = platformGetError();
if(error.module == MODULE_NN_AM && error.description == DESCRIPTION_ALREADY_EXISTS) {
std::stringstream overwriteMsg;
overwriteMsg << "Title already installed, overwrite?" << "\n";
overwriteMsg << name;
if(uiPrompt(TOP_SCREEN, overwriteMsg.str(), true)) {
uiDisplayMessage(TOP_SCREEN, "Deleting title...");
AppResult deleteRet = appDelete(appGetCiaInfo(path, destination));
if(deleteRet != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Delete failed!" << "\n";
resultMsg << name << "\n";
resultMsg << appGetResultString(deleteRet);
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
return false;
}
ret = appInstallFile(destination, path, &onProgress);
prevProgress = -1;
installInfo = "";
} else {
platformSetError(error);
}
} else {
platformSetError(error);
}
}
if(ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Install failed!" << "\n";
resultMsg << name << "\n";
resultMsg << appGetResultString(ret);
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
return false;
}
return true;
}
bool deleteCIA(const std::string path, const std::string fileName) {
std::string name = fileName;
if(name.length() > 40) {
name.resize(40);
name += "...";
}
std::stringstream deleteStream;
deleteStream << "Deleting CIA..." << "\n";
deleteStream << name;
uiDisplayMessage(TOP_SCREEN, deleteStream.str());
if(remove(path.c_str()) != 0) {
std::stringstream resultMsg;
resultMsg << "Delete failed!" << "\n";
resultMsg << name << "\n";
resultMsg << strerror(errno);
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
return false;
}
return true;
}
bool deleteTitle(App app) {
uiDisplayMessage(TOP_SCREEN, "Deleting title...");
AppResult ret = appDelete(app);
if(ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Delete failed!" << "\n";
resultMsg << appGetResultString(ret);
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
return false;
}
return true;
}
bool launchTitle(App app) {
uiDisplayMessage(TOP_SCREEN, "Launching title...");
AppResult ret = appLaunch(app);
if(ret != APP_SUCCESS) {
std::stringstream resultMsg;
resultMsg << "Launch failed!" << "\n";
resultMsg << appGetResultString(ret);
uiPrompt(TOP_SCREEN, resultMsg.str(), false);
return false;
}
return true;
}
bool onLoop() {
bool launcher = platformHasLauncher();
if(launcher && inputIsPressed(BUTTON_START)) {
exit = true;
return true;
}
bool breakLoop = false;
if(inputIsPressed(BUTTON_L)) {
if(destination == SD) {
destination = NAND;
} else {
destination = SD;
}
freeSpace = fsGetFreeSpace(destination);
if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
breakLoop = true;
}
}
if(inputIsPressed(BUTTON_R)) {
if(mode == INSTALL_CIA) {
mode = DELETE_CIA;
} else if(mode == DELETE_CIA) {
mode = DELETE_TITLE;
breakLoop = true;
} else if(mode == DELETE_TITLE) {
mode = LAUNCH_TITLE;
} else if(mode == LAUNCH_TITLE) {
mode = INSTALL_CIA;
breakLoop = true;
}
}
if(mode == INSTALL_CIA && inputIsPressed(BUTTON_Y)) {
networkInstall();
}
if(inputIsPressed(BUTTON_SELECT)) {
installROP();
}
std::stringstream stream;
stream << "Battery: ";
if(platformIsBatteryCharging()) {
stream << "Charging";
} else {
for(u32 i = 0; i < platformGetBatteryLevel(); i++) {
stream << "|";
}
}
stream << ", WiFi: ";
if(!platformIsWifiConnected()) {
stream << "Disconnected";
} else {
for(u32 i = 0; i < platformGetWifiLevel(); i++) {
stream << "|";
}
}
stream << "\n";
stream << "Free Space: " << freeSpace << " bytes (" << std::fixed << std::setprecision(2) << freeSpace / 1024.0f / 1024.0f << "MB)" << "\n";
stream << "Destination: " << (destination == NAND ? "NAND" : "SD") << ", Mode: " << (mode == INSTALL_CIA ? "Install CIA" : mode == DELETE_CIA ? "Delete CIA" : mode == DELETE_TITLE ? "Delete Title" : "Launch Title") << "\n";
stream << "L - Switch Destination, R - Switch Mode" << "\n";
if(mode == INSTALL_CIA) {
stream << "X - Install all CIAs in the current directory" << "\n";
stream << "Y - Receive an app over the network" << "\n";
} else if(mode == DELETE_CIA) {
stream << "X - Delete all CIAs in the current directory" << "\n";
}
stream << "SELECT - Install MSET ROP";
if(launcher) {
stream << "\n" << "START - Exit to launcher";
}
std::string str = stream.str();
const std::string title = "FBI v1.4.6";
gputDrawString(title, (gpuGetViewportWidth() - gputGetStringWidth(title, 16)) / 2, (gpuGetViewportHeight() - gputGetStringHeight(title, 16) + gputGetStringHeight(str, 8)) / 2, 16, 16);
gputDrawString(str, (gpuGetViewportWidth() - gputGetStringWidth(str, 8)) / 2, 4, 8, 8);
return breakLoop;
}
int main(int argc, char **argv) {
if(!platformInit(argc)) {
return 0;
}
freeSpace = fsGetFreeSpace(destination);
while(platformIsRunning()) {
if(mode == INSTALL_CIA || mode == DELETE_CIA) {
uiDisplayMessage(BOTTOM_SCREEN, "Loading file list...");
std::string fileTarget;
uiSelectFile(&fileTarget, "/", extensions, [&](const std::string currDirectory, bool inRoot, bool &updateList) {
if(inputIsPressed(BUTTON_X)) {
std::stringstream confirmMsg;
if(mode == INSTALL_CIA) {
confirmMsg << "Install ";
} else {
confirmMsg << "Delete ";
}
confirmMsg << "all CIAs in the current directory?";
if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
bool failed = false;
std::vector<FileInfo> contents = fsGetDirectoryContents(currDirectory);
for(std::vector<FileInfo>::iterator it = contents.begin(); it != contents.end(); it++) {
std::string path = (*it).path;
std::string name = (*it).name;
if(!fsIsDirectory(name) && fsHasExtensions(name, extensions)) {
if(mode == INSTALL_CIA) {
if(!installCIA(destination, path, name)) {
failed = true;
break;
}
} else {
if(deleteCIA(path, name)) {
updateList = true;
} else {
failed = true;
break;
}
}
}
}
if(!failed) {
std::stringstream successMsg;
if(mode == INSTALL_CIA) {
successMsg << "Install ";
} else {
successMsg << "Delete ";
}
successMsg << "succeeded!";
uiPrompt(TOP_SCREEN, successMsg.str(), false);
}
freeSpace = fsGetFreeSpace(destination);
}
}
return onLoop();
}, [&](const std::string path, bool &updateList) {
std::stringstream confirmMsg;
if(mode == INSTALL_CIA) {
confirmMsg << "Install ";
} else {
confirmMsg << "Delete ";
}
confirmMsg << "the selected CIA?";
if(uiPrompt(TOP_SCREEN, confirmMsg.str(), true)) {
bool success = false;
if(mode == INSTALL_CIA) {
success = installCIA(destination, path, fsGetFileName(path));
} else {
success = deleteCIA(path, fsGetFileName(path));
}
if(success) {
std::stringstream successMsg;
if(mode == INSTALL_CIA) {
successMsg << "Install ";
} else {
successMsg << "Delete ";
}
successMsg << "succeeded!";
uiPrompt(TOP_SCREEN, successMsg.str(), false);
}
freeSpace = fsGetFreeSpace(destination);
}
return false;
});
} else if(mode == DELETE_TITLE || mode == LAUNCH_TITLE) {
uiDisplayMessage(BOTTOM_SCREEN, "Loading title list...");
App appTarget;
uiSelectApp(&appTarget, destination, [&](bool &updateList) {
return onLoop();
}, [&](App app, bool &updateList) {
if(mode == DELETE_TITLE) {
if(uiPrompt(TOP_SCREEN, "Delete the selected title?", true) && (destination != NAND || uiPrompt(TOP_SCREEN, "You are about to delete a title from the NAND.\nTHIS HAS THE POTENTIAL TO BRICK YOUR 3DS!\nAre you sure you wish to continue?", true))) {
if(deleteTitle(app)) {
uiPrompt(TOP_SCREEN, "Delete succeeded!", false);
}
updateList = true;
freeSpace = fsGetFreeSpace(destination);
}
} else if(mode == LAUNCH_TITLE) {
if(uiPrompt(TOP_SCREEN, "Launch the selected title?", true)) {
if(launchTitle(app)) {
while(true) {
}
}
}
}
return false;
});
}
if(exit) {
break;
}
}
platformCleanup();
return 0;
}
|
Bump version for ctrcommon fixes.
|
Bump version for ctrcommon fixes.
|
C++
|
mit
|
Jerry-Shaw/FBI,leo60228/CTRM,masterhou/FBI,Traiver/FBI,Jerry-Shaw/FBI,soarqin/FBI,masterhou/FBI,leo60228/CTRM,hippydave/Newquay,hippydave/Newquay,kot2002/FBI,Possum/LumaLocaleSwitcher,Traiver/FBI,Possum/LumaLocaleSwitcher,leo60228/CTRM,Jerry-Shaw/FBI,soarqin/FBI,Traiver/FBI,kot2002/FBI,Jerry-Shaw/FBI
|
85c4208f0bdd57420f9f86b70a9a8768e39d3f15
|
src/lambda.cc
|
src/lambda.cc
|
#include "test_common.h"
#include <vector>
#include <iostream>
#include <algorithm>
#include <functional>
TEST_UNIT(lambda_test1)
{
std::vector<int> c{ 1, 2, 3, 4, 5, 6, 7 };
int x = 5;
c.erase(std::remove_if(c.begin(), c.end(), [x](int n) { return n < x; }), c.end());
std::cout << "c: ";
for (auto i : c) {
std::cout << i << ' ';
}
std::cout << '\n';
// the type of a closure cannot be named, but can be inferred with auto
auto func1 = [](int i) { return i + 4; };
std::cout << "func1: " << func1(6) << '\n';
// like all callable objects, closures can be captured in std::function
// (this may incur unnecessary overhead)
std::function<int(int)> func2 = [](int i) { return i + 4; };
std::cout << "func2: " << func2(6) << '\n';
}
using namespace std;
TEST_UNIT(lambda_test2)
{
// Create a vector object that contains 10 elements.
vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(i);
}
// Count the number of even numbers in the vector by
// using the for_each function and a lambda. ൱ڴһ캯IJΪ&evenCount
int evenCount = 0;
for_each(v.begin(), v.end(), [&evenCount](int n) { // [&](int n){...} ȼ
cout << n;
if (n % 2 == 0) {
cout << " is even " << endl;
++evenCount;
}
else {
cout << " is odd " << endl;
}
});
// Print the count of even numbers to the console.
cout << "There are " << evenCount
<< " even numbers in the vector." << endl;
H_TEST_ASSERT(evenCount == 5);
}
TEST_UNIT(lambda_test3)
{
int x = 10;
int y = 3;
int z = 0;
//Ϊֵݵķʽx,yx,yֵûзı
z = [=]()mutable throw() -> int { int n = x + y; x = y; y = n; return n; }();
cout << "z:" << z << "\tx:" << x << "\t" << "y:" << y << endl;
H_TEST_ASSERT(x == 10);
H_TEST_ASSERT(y == 3);
H_TEST_ASSERT(z == 13);
//Ϊôݵķʽx,yx,yֵѾı
z = [&]()mutable throw() -> int { int n = x + y; x = y; y = n; return n; }();
cout << "z:" << z << "\tx:" << x << "\t" << "y:" << y << endl;
H_TEST_ASSERT(y == 13);
H_TEST_ASSERT(x == 3);
H_TEST_ASSERT(z == 13);
}
TEST_UNIT(lambda_test4)
{
int n = [](int x, int y) { return x + y; }(5, 4);
H_TEST_ASSERT(n == 9);
auto f = [](int x, int y) { return x + y; };
H_TEST_ASSERT(f(5, 4) == 9);
}
TEST_UNIT(lambda_test5)
{
int a[10] = { 0 };
srand((unsigned int)time(NULL));
generate(a, a + 10, []()->int { return rand() % 100; });
cout << "before sort: " << endl;
for_each(a, a + 10, [&](int i){ cout << i << " "; });
cout << endl;
cout << "After sort" << endl;
sort(a, a + 10);
for_each(a, a + 10, [&](int i){ cout << i << " "; });
cout << endl;
}
|
#include "test_common.h"
#include <vector>
#include <iostream>
#include <algorithm>
#include <functional>
#include <memory>
TEST_UNIT(lambda_test1)
{
std::vector<int> c{ 1, 2, 3, 4, 5, 6, 7 };
int x = 5;
c.erase(std::remove_if(c.begin(), c.end(), [x](int n) { return n < x; }), c.end());
std::cout << "c: ";
for (auto i : c) {
std::cout << i << ' ';
}
std::cout << '\n';
// the type of a closure cannot be named, but can be inferred with auto
auto func1 = [](int i) { return i + 4; };
std::cout << "func1: " << func1(6) << '\n';
// like all callable objects, closures can be captured in std::function
// (this may incur unnecessary overhead)
std::function<int(int)> func2 = [](int i) { return i + 4; };
std::cout << "func2: " << func2(6) << '\n';
}
using namespace std;
TEST_UNIT(lambda_test2)
{
// Create a vector object that contains 10 elements.
vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(i);
}
// Count the number of even numbers in the vector by
// using the for_each function and a lambda. ൱ڴһ캯IJΪ&evenCount
int evenCount = 0;
for_each(v.begin(), v.end(), [&evenCount](int n) { // [&](int n){...} ȼ
cout << n;
if (n % 2 == 0) {
cout << " is even " << endl;
++evenCount;
}
else {
cout << " is odd " << endl;
}
});
// Print the count of even numbers to the console.
cout << "There are " << evenCount
<< " even numbers in the vector." << endl;
H_TEST_ASSERT(evenCount == 5);
}
TEST_UNIT(lambda_test3)
{
int x = 10;
int y = 3;
int z = 0;
//Ϊֵݵķʽx,yx,yֵûзı
z = [=]()mutable throw() -> int { int n = x + y; x = y; y = n; return n; }();
cout << "z:" << z << "\tx:" << x << "\t" << "y:" << y << endl;
H_TEST_ASSERT(x == 10);
H_TEST_ASSERT(y == 3);
H_TEST_ASSERT(z == 13);
//Ϊôݵķʽx,yx,yֵѾı
z = [&]()mutable throw() -> int { int n = x + y; x = y; y = n; return n; }();
cout << "z:" << z << "\tx:" << x << "\t" << "y:" << y << endl;
H_TEST_ASSERT(y == 13);
H_TEST_ASSERT(x == 3);
H_TEST_ASSERT(z == 13);
}
TEST_UNIT(lambda_test4)
{
int n = [](int x, int y) { return x + y; }(5, 4);
H_TEST_ASSERT(n == 9);
auto f = [](int x, int y) { return x + y; };
H_TEST_ASSERT(f(5, 4) == 9);
}
TEST_UNIT(lambda_test5)
{
int a[10] = { 0 };
srand((unsigned int)time(NULL));
generate(a, a + 10, []()->int { return rand() % 100; });
cout << "before sort: " << endl;
for_each(a, a + 10, [&](int i){ cout << i << " "; });
cout << endl;
cout << "After sort" << endl;
sort(a, a + 10);
for_each(a, a + 10, [&](int i){ cout << i << " "; });
cout << endl;
}
TEST_UNIT(lambda_test6) {
int* p1 = new int(1);
int* p2 = new int(2);
auto f = [p1, p2]() {
*p2 += 1;
delete p2;
*p1 += 1;
delete p1;
};
f();
}
|
Add lambda_test6
|
Add lambda_test6
|
C++
|
apache-2.0
|
zieckey/cxx11hello
|
2fc8701bc40bdcc0715780c407bf0d22a98ea530
|
tests/core/defaultfixture.cpp
|
tests/core/defaultfixture.cpp
|
/*
* libgamelib
*
* Copyright (C) 2013 Karol Herbst <[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.1 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.
*
* 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 "defaultfixture.h"
#include <gamelib/core/linuxinformation.h>
#include <Hypodermic/ContainerBuilder.h>
#include <Hypodermic/Helpers.h>
GAMELIB_NAMESPACE_START(test)
DefaultFicture::DefaultFicture()
{
Hypodermic::ContainerBuilder containerBuilder;
{
using namespace gamelib::core;
// set up IoC container
containerBuilder.registerType<LinuxInformation>()->
as<OSInformation>()->
singleInstance();
}
// left out not implemented stuff yet
this->container = containerBuilder.build();
}
GAMELIB_NAMESPACE_END(test)
|
/*
* libgamelib
*
* Copyright (C) 2013 Karol Herbst <[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.1 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.
*
* 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 "defaultfixture.h"
// some platform dependent stuff
#ifdef GAMELIB_OS_IS_WINDOWS
#include <gamelib/core/windowsinformation.h>
#define OSINFORMATIONCLASS WindowsInformation
#else
#include <gamelib/core/linuxinformation.h>
#define OSINFORMATIONCLASS LinuxInformation
#endif
#include <Hypodermic/ContainerBuilder.h>
#include <Hypodermic/Helpers.h>
GAMELIB_NAMESPACE_START(test)
DefaultFicture::DefaultFicture()
{
Hypodermic::ContainerBuilder containerBuilder;
{
using namespace gamelib::core;
// set up IoC container
containerBuilder.registerType<OSINFORMATIONCLASS>()->
as<OSInformation>()->
singleInstance();
}
// left out not implemented stuff yet
this->container = containerBuilder.build();
}
GAMELIB_NAMESPACE_END(test)
|
use plattform depentend osinformation implementation
|
test: use plattform depentend osinformation implementation
|
C++
|
lgpl-2.1
|
karolherbst/Gamekeeper-Framework,karolherbst/Gamekeeper-Framework,karolherbst/Gamekeeper-Framework,karolherbst/Gamekeeper-Framework
|
b7bc49ebdac6dbe966fe17f3557766c7ecc740e3
|
planning/jet/jetsim.cc
|
planning/jet/jetsim.cc
|
#include "viewer/primitives/simple_geometry.hh"
#include "viewer/window_3d.hh"
#include "geometry/visualization/put_stl.hh"
#include "planning/jet/jet_dynamics.hh"
#include "planning/jet/jet_planner.hh"
#include "planning/jet/jet_model.hh"
#include "eigen.hh"
#include "sophus.hh"
namespace planning {
namespace jet {
namespace {
void setup() {
const auto view = viewer::get_window3d("Mr. Jet, jets");
view->set_target_from_world(
SE3(SO3::exp(Eigen::Vector3d(-3.1415 * 0.5, 0.0, 0.0)), Eigen::Vector3d::Zero()));
view->set_continue_time_ms(10);
const auto background = view->add_primitive<viewer::SimpleGeometry>();
const geometry::shapes::Plane ground{jcc::Vec3::UnitZ(), 0.0};
background->add_plane({ground});
background->flip();
}
} // namespace
void go() {
setup();
const auto view = viewer::get_window3d("Mr. Jet, jets");
const std::string jet_path = "/home/jacob/repos/experiments/data/jetcat_p160.stl";
const auto put_jet = geometry::visualization::create_put_stl(jet_path);
const auto jet_geo = view->add_primitive<viewer::SimpleGeometry>();
const auto accum_geo = view->add_primitive<viewer::SimpleGeometry>();
const JetModel model;
Parameters params;
params.mass = 100.0;
params.unit_z = jcc::Vec3::UnitZ();
// params.external_force = jcc::Vec3::UnitZ() * -1.0;
State jet;
jet.x = jcc::Vec3(-3.0, -3.0, 3.0);
// jet.v = jcc::Vec3(0.3, 0.1, -0.6);
// jet.w = jcc::Vec3::UnitX() * 0.2;
// jet.R_world_from_body = SO3::exp(jcc::Vec3(0.1, 3.5, 0.2));
// jet.w = jcc::Vec3::UnitX() * 0.01;
// jet.v = jcc::Vec3(0.0, 0.1, 0.1);
jet.throttle_pct = 0.0;
std::vector<Controls> prev_controls;
for (int j = 0; j < 1000; ++j) {
const double dt = 0.01;
const jcc::Vec3 prev = jet.x;
const auto future_states = plan(jet, prev_controls);
{
prev_controls.clear();
for (std::size_t xu_ind = 1u; xu_ind < future_states.size(); ++xu_ind) {
const auto& xu = future_states.at(xu_ind);
// prev_controls.push_back(xu.control);
}
}
for (std::size_t k = 0; k < future_states.size(); ++k) {
const auto& state = future_states.at(k).state;
const SE3 world_from_state = SE3(state.R_world_from_body, state.x);
const double scale =
static_cast<double>(k) / static_cast<double>(future_states.size());
jet_geo->add_axes({world_from_state, 1.0 - scale});
if (k > 1) {
jet_geo->add_line({future_states.at(k).state.x, future_states.at(k - 1).state.x,
jcc::Vec4(0.8, 0.8, 0.1, 0.8), 5.0});
}
}
std::cout << "Done optimizing" << std::endl;
jet = future_states[1].state;
const auto ctrl = future_states[1].control;
std::cout << "\tq : " << ctrl.q.transpose() << std::endl;
std::cout << "\tx : " << jet.x.transpose() << std::endl;
std::cout << "\tw : " << jet.w.transpose() << std::endl;
std::cout << "\tv : " << jet.v.transpose() << std::endl;
std::cout << "\tthrust: " << jet.throttle_pct << std::endl;
// const State u = future_states.front();
// jet = rk4_integrate(jet, {}, params, dt);
accum_geo->add_line({prev, jet.x, jcc::Vec4(1.0, 0.7, 0.7, 0.7), 5.0});
const SE3 world_from_jet = SE3(jet.R_world_from_body, jet.x);
// put_jet(*jet_geo, world_from_jet);
model.put(*jet_geo, jet);
jet_geo->add_line(
{world_from_jet.translation(),
world_from_jet.translation() +
(world_from_jet.so3() * jcc::Vec3::UnitZ() * jet.throttle_pct * 0.1),
jcc::Vec4(0.1, 0.9, 0.1, 0.8), 9.0});
if (true) {
const SO3 world_from_target_rot = SO3::exp(jcc::Vec3::UnitX() * 3.1415 * 0.5);
const SE3 world_from_target(world_from_target_rot, world_from_jet.translation());
view->set_target_from_world(world_from_target.inverse());
} else {
view->set_target_from_world(world_from_jet.inverse());
}
jet_geo->flip();
accum_geo->flush();
view->spin_until_step();
}
}
} // namespace jet
} // namespace planning
int main() {
planning::jet::go();
}
|
#include "viewer/primitives/simple_geometry.hh"
#include "viewer/window_3d.hh"
#include "geometry/visualization/put_stl.hh"
#include "planning/jet/jet_dynamics.hh"
#include "planning/jet/jet_planner.hh"
#include "planning/jet/jet_model.hh"
#include "eigen.hh"
#include "sophus.hh"
namespace planning {
namespace jet {
namespace {
void setup() {
const auto view = viewer::get_window3d("Mr. Jet, jets");
view->set_target_from_world(
SE3(SO3::exp(Eigen::Vector3d(-3.1415 * 0.5, 0.0, 0.0)), Eigen::Vector3d::Zero()));
view->set_continue_time_ms(10);
const auto background = view->add_primitive<viewer::SimpleGeometry>();
const geometry::shapes::Plane ground{jcc::Vec3::UnitZ(), 0.0};
background->add_plane({ground});
background->flip();
}
} // namespace
void go() {
setup();
const auto view = viewer::get_window3d("Mr. Jet, jets");
const std::string jet_path = "/home/jacob/repos/experiments/data/jetcat_p160.stl";
const auto put_jet = geometry::visualization::create_put_stl(jet_path);
const auto jet_geo = view->add_primitive<viewer::SimpleGeometry>();
const auto accum_geo = view->add_primitive<viewer::SimpleGeometry>();
const JetModel model;
Parameters params;
params.mass = 100.0;
params.unit_z = jcc::Vec3::UnitZ();
// params.external_force = jcc::Vec3::UnitZ() * -1.0;
State jet;
jet.x = jcc::Vec3(-3.0, -3.0, 3.0);
// jet.v = jcc::Vec3(0.3, 0.1, -0.6);
// jet.w = jcc::Vec3::UnitX() * 0.2;
// jet.R_world_from_body = SO3::exp(jcc::Vec3(0.1, 3.5, 0.2));
// jet.w = jcc::Vec3::UnitX() * 0.01;
// jet.v = jcc::Vec3(0.0, 0.1, 0.1);
jet.throttle_pct = 0.0;
std::vector<Controls> prev_controls;
for (int j = 0; j < 1000 && !view->should_close(); ++j) {
const double dt = 0.01;
const jcc::Vec3 prev = jet.x;
const auto future_states = plan(jet, prev_controls);
{
prev_controls.clear();
for (std::size_t xu_ind = 1u; xu_ind < future_states.size(); ++xu_ind) {
const auto& xu = future_states.at(xu_ind);
// prev_controls.push_back(xu.control);
}
}
for (std::size_t k = 0; k < future_states.size(); ++k) {
const auto& state = future_states.at(k).state;
const SE3 world_from_state = SE3(state.R_world_from_body, state.x);
const double scale =
static_cast<double>(k) / static_cast<double>(future_states.size());
jet_geo->add_axes({world_from_state, 1.0 - scale});
if (k > 1) {
jet_geo->add_line({future_states.at(k).state.x, future_states.at(k - 1).state.x,
jcc::Vec4(0.8, 0.8, 0.1, 0.8), 5.0});
}
}
std::cout << "Done optimizing" << std::endl;
jet = future_states[1].state;
const auto ctrl = future_states[1].control;
std::cout << "\tq : " << ctrl.q.transpose() << std::endl;
std::cout << "\tx : " << jet.x.transpose() << std::endl;
std::cout << "\tw : " << jet.w.transpose() << std::endl;
std::cout << "\tv : " << jet.v.transpose() << std::endl;
std::cout << "\tthrust: " << jet.throttle_pct << std::endl;
// const State u = future_states.front();
// jet = rk4_integrate(jet, {}, params, dt);
accum_geo->add_line({prev, jet.x, jcc::Vec4(1.0, 0.7, 0.7, 0.7), 5.0});
const SE3 world_from_jet = SE3(jet.R_world_from_body, jet.x);
// put_jet(*jet_geo, world_from_jet);
model.put(*jet_geo, jet);
jet_geo->add_line(
{world_from_jet.translation(),
world_from_jet.translation() +
(world_from_jet.so3() * jcc::Vec3::UnitZ() * jet.throttle_pct * 0.1),
jcc::Vec4(0.1, 0.9, 0.1, 0.8), 9.0});
if (true) {
const SO3 world_from_target_rot = SO3::exp(jcc::Vec3::UnitX() * 3.1415 * 0.5);
const SE3 world_from_target(world_from_target_rot, world_from_jet.translation());
view->set_target_from_world(world_from_target.inverse());
} else {
view->set_target_from_world(world_from_jet.inverse());
}
jet_geo->flip();
accum_geo->flush();
view->spin_until_step();
}
}
} // namespace jet
} // namespace planning
int main() {
planning::jet::go();
}
|
Quit eagerly in jetsim
|
Quit eagerly in jetsim
|
C++
|
mit
|
jpanikulam/experiments,jpanikulam/experiments,jpanikulam/experiments,jpanikulam/experiments
|
82e37bd94cc50dfeeba8f8593e1487907afd473e
|
src/spiegel.cpp
|
src/spiegel.cpp
|
/*
* Copyright (C) 2009 Toni Gundogdu.
*
* This file is part of cclive.
*
* cclive 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.
*
* cclive is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <map>
#include "hosthandler.h"
#define HOST "spiegel"
SpiegelHandler::SpiegelHandler()
: HostHandler()
{
props.setHost (HOST);
props.setDomain ("spiegel.de");
props.setFormats("flv|vp6_576|vp_928|h264_1400");
}
void
SpiegelHandler::parseId() {
std::string id;
partialMatch("(?i)\\/video\\/video-(.*?)\\.", &id, props.getPageLink());
props.setId(id);
}
void
SpiegelHandler::parseTitle() {
// Done in parseLink.
}
void
SpiegelHandler::parseLink() {
const std::string playlist_url =
"http://www1.spiegel.de/active/playlist/fcgi/playlist.fcgi/"
"asset=flashvideo/mode=id/id=" + props.getId();
const std::string pl =
fetch(playlist_url, "playlist", true);
std::string headline;
partialMatch("(?i)<headline>(.*?)</", &headline, pl);
props.setTitle(headline);
const std::string config =
fetch("http://video.spiegel.de/flash/"
+ props.getId() + ".xml", "config", true);
pcrecpp::StringPiece tmp(config);
pcrecpp::RE re("(?i)<filename>(.*?)</");
const std::string _re("(?i)_(\\d+)\\.");
pcrecpp::RE re_rate(_re);
std::string format =
Util::parseFormatMap(HOST);
if (format == "flv")
format = "vp6_64";
std::map<std::string, std::string> m;
std::string path, rate, _path;
while (re.FindAndConsume(&tmp, &path)) {
if (re_rate.PartialMatch(path, &rate))
m[rate] = path;
if (pcrecpp::RE("(?i)"+format).PartialMatch(path))
_path = path; // Grab this while here.
}
if (format == "best")
_path = (m.begin())->second;
if (_path.empty())
throw HostHandler::ParseException("unable to construct video link");
std::string lnk = "http://video.spiegel.de/flash/" + _path;
curlmgr.escape(lnk);
props.setLink(lnk);
}
|
/*
* Copyright (C) 2009 Toni Gundogdu.
*
* This file is part of cclive.
*
* cclive 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.
*
* cclive is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <map>
#include "hosthandler.h"
#define HOST "spiegel"
SpiegelHandler::SpiegelHandler()
: HostHandler()
{
props.setHost (HOST);
props.setDomain ("spiegel.de");
props.setFormats("flv|vp6_576|vp6_928|h264_1400");
}
void
SpiegelHandler::parseId() {
std::string id;
partialMatch("(?i)\\/video\\/video-(.*?)\\.", &id, props.getPageLink());
props.setId(id);
}
void
SpiegelHandler::parseTitle() {
// Done in parseLink.
}
void
SpiegelHandler::parseLink() {
const std::string playlist_url =
"http://www1.spiegel.de/active/playlist/fcgi/playlist.fcgi/"
"asset=flashvideo/mode=id/id=" + props.getId();
const std::string pl =
fetch(playlist_url, "playlist", true);
std::string headline;
partialMatch("(?i)<headline>(.*?)</", &headline, pl);
props.setTitle(headline);
const std::string config =
fetch("http://video.spiegel.de/flash/"
+ props.getId() + ".xml", "config", true);
pcrecpp::StringPiece tmp(config);
pcrecpp::RE re("(?i)<filename>(.*?)</");
const std::string _re("(?i)_(\\d+)\\.");
pcrecpp::RE re_rate(_re);
std::string format =
Util::parseFormatMap(HOST);
if (format == "flv")
format = "vp6_64";
std::map<std::string, std::string> m;
std::string path, rate, _path;
while (re.FindAndConsume(&tmp, &path)) {
if (re_rate.PartialMatch(path, &rate))
m[rate] = path;
if (pcrecpp::RE("(?i)"+format).PartialMatch(path))
_path = path; // Grab this while here.
}
if (format == "best")
_path = (m.begin())->second;
if (_path.empty())
throw HostHandler::ParseException("unable to construct video link");
std::string lnk = "http://video.spiegel.de/flash/" + _path;
curlmgr.escape(lnk);
props.setLink(lnk);
}
|
fix a typo in supported formats.
|
spiegel: fix a typo in supported formats.
|
C++
|
agpl-3.0
|
legatvs/cclive,legatvs/cclive,legatvs/cclive
|
1e45f226ef35b649cb2889e23ad90ad39d0db947
|
src/pamix.cpp
|
src/pamix.cpp
|
#include <pamix.hpp>
#include <unistd.h>
#include <configuration.hpp>
#include <condition_variable>
#include <queue>
#include <csignal>
// GLOBAL VARIABLES
Configuration configuration;
bool running = true;
// sync main and callback threads
std::mutex updMutex;
std::condition_variable cv;
std::queue<UpdateData> updateDataQ;
void quit() {
running = false;
signal_update(false);
}
void __signal_update(bool all) {
{
std::lock_guard<std::mutex> lk(updMutex);
updateDataQ.push(UpdateData(all));
}
cv.notify_one();
}
void signal_update(bool all, bool threaded) {
if (threaded)
std::thread(__signal_update, all).detach();
else
__signal_update(all);
}
void set_volume(pamix_ui *ui, double pct) {
auto it = ui->getSelectedEntryIterator();
if (it != ui->m_Entries->end())
it->second->setVolume(it->second->m_Lock ? -1 : (int) ui->m_SelectedChannel, (pa_volume_t) (PA_VOLUME_NORM * pct));
}
void add_volume(pamix_ui *ui, double pct) {
auto it = ui->getSelectedEntryIterator();
if (it != ui->m_Entries->end())
it->second->addVolume(it->second->m_Lock ? -1 : (int) ui->m_SelectedChannel, pct);
}
void cycle_switch(pamix_ui *ui, bool increment) {
auto it = ui->getSelectedEntryIterator();
if (it != ui->m_Entries->end())
it->second->cycleSwitch(increment);
}
void set_mute(pamix_ui *ui, bool mute) {
auto it = ui->getSelectedEntryIterator();
if (it != ui->m_Entries->end())
it->second->setMute(mute);
}
void toggle_mute(pamix_ui *ui) {
auto it = ui->getSelectedEntryIterator();
if (it != ui->m_Entries->end())
it->second->setMute(!it->second->m_Mute);
}
void set_lock(pamix_ui *ui, bool lock) {
auto it = ui->getSelectedEntryIterator();
if (it != ui->m_Entries->end())
it->second->m_Lock = lock;
}
void toggle_lock(pamix_ui *ui) {
auto it = ui->getSelectedEntryIterator();
if (it != ui->m_Entries->end())
it->second->m_Lock = !it->second->m_Lock;
}
void inputThread(pamix_ui *ui) {
while (running) {
int ch = ui->getKeyInput();
bool isValidKey = ch != ERR && ch != KEY_RESIZE && ch != KEY_MOUSE;
//if (isValidKey && ui->m_paInterface->isConnected()) {
if (isValidKey) {
configuration.pressKey(ch);
}
usleep(2000);
}
}
void pai_subscription(PAInterface *, pai_subscription_type_t type) {
bool updAll = (type & PAI_SUBSCRIPTION_MASK_INFO) != 0
|| (type & PAI_SUBSCRIPTION_MASK_CONNECTION_STATUS) != 0;
signal_update(updAll);
}
void sig_handle_resize(int) {
endwin();
refresh();
signal_update(true, true);
}
void init_colors() {
start_color();
init_pair(1, COLOR_GREEN, 0);
init_pair(2, COLOR_YELLOW, 0);
init_pair(3, COLOR_RED, 0);
}
void sig_handle(int) {
endwin();
}
void loadConfiguration() {
char *home = getenv("HOME");
char *xdg_config_home = getenv("XDG_CONFIG_HOME");
std::string path;
path = xdg_config_home ? xdg_config_home : std::string(home) += "/.config";
path += "/pamix.conf";
if (Configuration::loadFile(&configuration, path))
return;
char *xdg_config_dirs = getenv("XDG_CONFIG_DIRS");
path = xdg_config_dirs ? xdg_config_dirs : "/etc/xdg";
path += "/pamix.conf";
size_t cpos = path.find(':');
while (cpos != std::string::npos) {
if (Configuration::loadFile(&configuration, path.substr(0, cpos)))
return;
path = path.substr(cpos + 1, path.length() - cpos - 1);
cpos = path.find(':');
}
if (Configuration::loadFile(&configuration, path))
return;
// if config file cant be loaded, use default bindings
configuration.bind("q", "quit");
configuration.bind("KEY_F(1)", "select-tab", "2");
configuration.bind("KEY_F(2)", "select-tab", "3");
configuration.bind("KEY_F(3)", "select-tab", "0");
configuration.bind("KEY_F(4)", "select-tab", "1");
configuration.bind("j", "select-next", "channel");
configuration.bind("KEY_DOWN", "select-next", "channel");
configuration.bind("J", "select-next");
configuration.bind("k", "select-prev", "channel");
configuration.bind("KEY_UP", "select-prev", "channel");
configuration.bind("K", "select-prev");
configuration.bind("h", "add-volume", "-0.05");
configuration.bind("KEY_LEFT", "add-volume", "-0.05");
configuration.bind("l", "add-volume", "0.05");
configuration.bind("KEY_RIGHT", "add-volume", "0.05");
configuration.bind("s", "cycle-next");
configuration.bind("S", "cycle-prev");
configuration.bind("c", "toggle-lock");
configuration.bind("m", "toggle-mute");
configuration.bind("1", "set-volume", "0.1");
configuration.bind("2", "set-volume", "0.2");
configuration.bind("3", "set-volume", "0.3");
configuration.bind("4", "set-volume", "0.4");
configuration.bind("5", "set-volume", "0.5");
configuration.bind("6", "set-volume", "0.6");
configuration.bind("7", "set-volume", "0.7");
configuration.bind("8", "set-volume", "0.8");
configuration.bind("9", "set-volume", "0.9");
configuration.bind("0", "set-volume", "1.0");
}
void interfaceReconnectThread(PAInterface *interface) {
while (running) {
if (!interface->isConnected()) {
interface->connect();
signal_update(true);
}
sleep(5);
}
}
void handleArguments(int argc, char **argv) {
for (int i = 1; i < argc; i++) {
std::string arg = argv[i];
if (arg == "--version") {
printf("PAmix v%s\n", GIT_VERSION);
exit(0);
}
}
}
int main(int argc, char **argv) {
handleArguments(argc, argv);
loadConfiguration();
setlocale(LC_ALL, "");
initscr();
init_colors();
nodelay(stdscr, true);
curs_set(0);
keypad(stdscr, true);
meta(stdscr, true);
noecho();
signal(SIGABRT, sig_handle);
signal(SIGSEGV, sig_handle);
signal(SIGWINCH, sig_handle_resize);
PAInterface pai("pamix");
pamix_ui pamixUi(&pai);
if (configuration.has(CONFIGURATION_AUTOSPAWN_PULSE))
pai.setAutospawn(configuration.getBool(CONFIGURATION_AUTOSPAWN_PULSE));
entry_type initialEntryType = ENTRY_SINKINPUT;
if (configuration.has(CONFIGURATION_DEFAULT_TAB)) {
int value = configuration.getInt(CONFIGURATION_DEFAULT_TAB);
if (value >= 0 && value < ENTRY_COUNT)
initialEntryType = (entry_type) value;
}
pamixUi.selectEntries(initialEntryType);
pai.subscribe(&pai_subscription);
pai.connect();
pamix_setup(&pamixUi);
pamixUi.redrawAll();
std::thread(&interfaceReconnectThread, &pai).detach();
std::thread inputT(inputThread, &pamixUi);
inputT.detach();
while (running) {
std::unique_lock<std::mutex> lk(updMutex);
cv.wait(lk, [] { return !updateDataQ.empty(); });
if (updateDataQ.front().redrawAll)
pamixUi.redrawAll();
else
pamixUi.redrawVolumeBars();
updateDataQ.pop();
}
endwin();
return 0;
}
|
#include <pamix.hpp>
#include <unistd.h>
#include <configuration.hpp>
#include <condition_variable>
#include <queue>
#include <csignal>
// GLOBAL VARIABLES
Configuration configuration;
bool running = true;
// sync main and callback threads
std::mutex updMutex;
std::condition_variable cv;
std::queue<UpdateData> updateDataQ;
void quit() {
running = false;
signal_update(false);
}
void __signal_update(bool all) {
{
std::lock_guard<std::mutex> lk(updMutex);
updateDataQ.push(UpdateData(all));
}
cv.notify_one();
}
void signal_update(bool all, bool threaded) {
if (threaded)
std::thread(__signal_update, all).detach();
else
__signal_update(all);
}
void set_volume(pamix_ui *ui, double pct) {
auto it = ui->getSelectedEntryIterator();
if (it != ui->m_Entries->end())
it->second->setVolume(it->second->m_Lock ? -1 : (int) ui->m_SelectedChannel, (pa_volume_t) (PA_VOLUME_NORM * pct));
}
void add_volume(pamix_ui *ui, double pct) {
auto it = ui->getSelectedEntryIterator();
if (it != ui->m_Entries->end())
it->second->addVolume(it->second->m_Lock ? -1 : (int) ui->m_SelectedChannel, pct);
}
void cycle_switch(pamix_ui *ui, bool increment) {
auto it = ui->getSelectedEntryIterator();
if (it != ui->m_Entries->end())
it->second->cycleSwitch(increment);
}
void set_mute(pamix_ui *ui, bool mute) {
auto it = ui->getSelectedEntryIterator();
if (it != ui->m_Entries->end())
it->second->setMute(mute);
}
void toggle_mute(pamix_ui *ui) {
auto it = ui->getSelectedEntryIterator();
if (it != ui->m_Entries->end())
it->second->setMute(!it->second->m_Mute);
}
void set_lock(pamix_ui *ui, bool lock) {
auto it = ui->getSelectedEntryIterator();
if (it != ui->m_Entries->end())
it->second->m_Lock = lock;
}
void toggle_lock(pamix_ui *ui) {
auto it = ui->getSelectedEntryIterator();
if (it != ui->m_Entries->end())
it->second->m_Lock = !it->second->m_Lock;
}
void inputThread(pamix_ui *ui) {
while (running) {
int ch = ui->getKeyInput();
bool isValidKey = ch != ERR && ch != KEY_RESIZE && ch != KEY_MOUSE;
//if (isValidKey && ui->m_paInterface->isConnected()) {
if (isValidKey) {
configuration.pressKey(ch);
}
usleep(2000);
}
}
void pai_subscription(PAInterface *, pai_subscription_type_t type) {
bool updAll = (type & PAI_SUBSCRIPTION_MASK_INFO) != 0
|| (type & PAI_SUBSCRIPTION_MASK_CONNECTION_STATUS) != 0;
signal_update(updAll);
}
void sig_handle_resize(int) {
endwin();
refresh();
signal_update(true, true);
}
void init_colors() {
start_color();
init_pair(1, COLOR_GREEN, 0);
init_pair(2, COLOR_YELLOW, 0);
init_pair(3, COLOR_RED, 0);
}
void sig_handle(int) {
endwin();
}
void loadConfiguration() {
char *home = getenv("HOME");
char *xdg_config_home = getenv("XDG_CONFIG_HOME");
std::string path;
path = xdg_config_home ? xdg_config_home : std::string(home) += "/.config";
path += "/pamix.conf";
if (Configuration::loadFile(&configuration, path))
return;
char *xdg_config_dirs = getenv("XDG_CONFIG_DIRS");
path = xdg_config_dirs ? xdg_config_dirs : "/etc/xdg";
path += "/pamix.conf";
size_t cpos = path.find(':');
while (cpos != std::string::npos) {
if (Configuration::loadFile(&configuration, path.substr(0, cpos)))
return;
path = path.substr(cpos + 1, path.length() - cpos - 1);
cpos = path.find(':');
}
if (Configuration::loadFile(&configuration, path))
return;
// if config file cant be loaded, use default bindings
configuration.bind("q", "quit");
configuration.bind("KEY_F(1)", "select-tab", "2");
configuration.bind("KEY_F(2)", "select-tab", "3");
configuration.bind("KEY_F(3)", "select-tab", "0");
configuration.bind("KEY_F(4)", "select-tab", "1");
configuration.bind("j", "select-next", "channel");
configuration.bind("KEY_DOWN", "select-next", "channel");
configuration.bind("J", "select-next");
configuration.bind("k", "select-prev", "channel");
configuration.bind("KEY_UP", "select-prev", "channel");
configuration.bind("K", "select-prev");
configuration.bind("h", "add-volume", "-0.05");
configuration.bind("KEY_LEFT", "add-volume", "-0.05");
configuration.bind("l", "add-volume", "0.05");
configuration.bind("KEY_RIGHT", "add-volume", "0.05");
configuration.bind("s", "cycle-next");
configuration.bind("S", "cycle-prev");
configuration.bind("c", "toggle-lock");
configuration.bind("m", "toggle-mute");
configuration.bind("1", "set-volume", "0.1");
configuration.bind("2", "set-volume", "0.2");
configuration.bind("3", "set-volume", "0.3");
configuration.bind("4", "set-volume", "0.4");
configuration.bind("5", "set-volume", "0.5");
configuration.bind("6", "set-volume", "0.6");
configuration.bind("7", "set-volume", "0.7");
configuration.bind("8", "set-volume", "0.8");
configuration.bind("9", "set-volume", "0.9");
configuration.bind("0", "set-volume", "1.0");
}
void interfaceReconnectThread(PAInterface *interface) {
while (running) {
if (!interface->isConnected()) {
interface->connect();
signal_update(true);
}
sleep(5);
}
}
void handleArguments(int argc, char **argv) {
for (int i = 1; i < argc; i++) {
std::string arg = argv[i];
if (arg == "--version") {
printf("PAmix v%s\n", GIT_VERSION);
exit(0);
}
}
}
int main(int argc, char **argv) {
handleArguments(argc, argv);
loadConfiguration();
setlocale(LC_ALL, "");
initscr();
init_colors();
nodelay(stdscr, true);
set_escdelay(25);
curs_set(0);
keypad(stdscr, true);
meta(stdscr, true);
noecho();
signal(SIGABRT, sig_handle);
signal(SIGSEGV, sig_handle);
signal(SIGWINCH, sig_handle_resize);
PAInterface pai("pamix");
pamix_ui pamixUi(&pai);
if (configuration.has(CONFIGURATION_AUTOSPAWN_PULSE))
pai.setAutospawn(configuration.getBool(CONFIGURATION_AUTOSPAWN_PULSE));
entry_type initialEntryType = ENTRY_SINKINPUT;
if (configuration.has(CONFIGURATION_DEFAULT_TAB)) {
int value = configuration.getInt(CONFIGURATION_DEFAULT_TAB);
if (value >= 0 && value < ENTRY_COUNT)
initialEntryType = (entry_type) value;
}
pamixUi.selectEntries(initialEntryType);
pai.subscribe(&pai_subscription);
pai.connect();
pamix_setup(&pamixUi);
pamixUi.redrawAll();
std::thread(&interfaceReconnectThread, &pai).detach();
std::thread inputT(inputThread, &pamixUi);
inputT.detach();
while (running) {
std::unique_lock<std::mutex> lk(updMutex);
cv.wait(lk, [] { return !updateDataQ.empty(); });
if (updateDataQ.front().redrawAll)
pamixUi.redrawAll();
else
pamixUi.redrawVolumeBars();
updateDataQ.pop();
}
endwin();
return 0;
}
|
Use 25ms as escdelay
|
Use 25ms as escdelay
By default ncurses will use 1000ms, which will cause freezing.
Fixes #44
|
C++
|
mit
|
patroclos/PAmix
|
b436d4937c27e4ad9535a1efa54c12e3ff4b66a5
|
src/tracing.hpp
|
src/tracing.hpp
|
// Copyright 2022 The clvk 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.
#pragma once
#ifdef CLVK_PERFETTO_ENABLE
#include "cl_headers.hpp"
#include "log.hpp"
#include "perfetto.h"
#define CLVK_PERFETTO_CATEGORY "clvk"
PERFETTO_DEFINE_CATEGORIES(
perfetto::Category(CLVK_PERFETTO_CATEGORY).SetDescription("CLVK Events"));
#define TRACE_STRING(str) perfetto::StaticString(str)
#define TRACE_FUNCTION(...) \
perfetto::StaticString __perfetto_fct_name = __func__; \
TRACE_EVENT(CLVK_PERFETTO_CATEGORY, __perfetto_fct_name, ##__VA_ARGS__)
#define TRACE_BEGIN_CMD(cmd_type, ...) \
TRACE_EVENT_BEGIN( \
CLVK_PERFETTO_CATEGORY, \
perfetto::StaticString(cl_command_type_to_string(cmd_type)), \
##__VA_ARGS__)
#define TRACE_BEGIN_EVENT(cmd_type, ...) \
TRACE_EVENT_BEGIN( \
CLVK_PERFETTO_CATEGORY, "event_wait", "cl_command_type", \
perfetto::StaticString(cl_command_type_to_string(cmd_type)), \
##__VA_ARGS__)
#define TRACE_BEGIN(name, ...) \
TRACE_EVENT_BEGIN(CLVK_PERFETTO_CATEGORY, name, ##__VA_ARGS__)
#define TRACE_END() TRACE_EVENT_END(CLVK_PERFETTO_CATEGORY)
#define TRACE_CNT(counter, value) \
TRACE_COUNTER(CLVK_PERFETTO_CATEGORY, *counter, value)
#define TRACE_CNT_VAR(name) \
std::string string_##name; \
std::unique_ptr<perfetto::CounterTrack> name
#define TRACE_CNT_VAR_INIT(name, value) \
string_##name = value; \
name = std::make_unique<perfetto::CounterTrack>(string_##name.c_str())
#else // CLVK_PERFETTO_ENABLE
#define TRACE_STRING()
#define TRACE_FUNCTION(...)
#define TRACE_BEGIN_CMD(cmd_type, ...)
#define TRACE_BEGIN_EVENT(cmd_type, ...)
#define TRACE_BEGIN(name, ...)
#define TRACE_END()
#define TRACE_CNT(str, value)
#define TRACE_CNT_VAR(name)
#define TRACE_CNT_VAR_INIT(name, value)
#endif // CLVK_PERFETTO_ENABLE
void init_tracing();
void term_tracing();
|
// Copyright 2022 The clvk 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.
#pragma once
#ifdef CLVK_PERFETTO_ENABLE
#include "cl_headers.hpp"
#include "log.hpp"
#include "perfetto.h"
#define CLVK_PERFETTO_CATEGORY "clvk"
PERFETTO_DEFINE_CATEGORIES(
perfetto::Category(CLVK_PERFETTO_CATEGORY).SetDescription("CLVK Events"));
#define TRACE_STRING(str) perfetto::StaticString(str)
#define TRACE_FUNCTION(...) \
perfetto::StaticString __perfetto_fct_name = __func__; \
TRACE_EVENT(CLVK_PERFETTO_CATEGORY, __perfetto_fct_name, ##__VA_ARGS__)
#define TRACE_BEGIN_CMD(cmd_type, ...) \
TRACE_EVENT_BEGIN( \
CLVK_PERFETTO_CATEGORY, \
perfetto::StaticString(cl_command_type_to_string(cmd_type)), \
##__VA_ARGS__)
#define TRACE_BEGIN_EVENT(cmd_type, ...) \
TRACE_EVENT_BEGIN( \
CLVK_PERFETTO_CATEGORY, "event_wait", "cl_command_type", \
perfetto::StaticString(cl_command_type_to_string(cmd_type)), \
##__VA_ARGS__)
#define TRACE_BEGIN(name, ...) \
TRACE_EVENT_BEGIN(CLVK_PERFETTO_CATEGORY, name, ##__VA_ARGS__)
#define TRACE_END() TRACE_EVENT_END(CLVK_PERFETTO_CATEGORY)
#define TRACE_CNT(counter, value) \
TRACE_COUNTER(CLVK_PERFETTO_CATEGORY, *counter, value)
#define TRACE_CNT_VAR(name) \
std::string string_##name; \
std::unique_ptr<perfetto::CounterTrack> name
#define TRACE_CNT_VAR_INIT(name, value) \
string_##name = value; \
name = std::make_unique<perfetto::CounterTrack>(string_##name.c_str())
#else // CLVK_PERFETTO_ENABLE
#define TRACE_STRING()
#define TRACE_FUNCTION(...)
#define TRACE_BEGIN_CMD(cmd_type, ...)
#define TRACE_BEGIN_EVENT(cmd_type, ...)
#define TRACE_BEGIN(name, ...)
#define TRACE_END()
#define TRACE_CNT(str, value) UNUSED(value)
#define TRACE_CNT_VAR(name)
#define TRACE_CNT_VAR_INIT(name, value)
#endif // CLVK_PERFETTO_ENABLE
void init_tracing();
void term_tracing();
|
fix warnings threaded as errors in google infra (#446)
|
fix warnings threaded as errors in google infra (#446)
|
C++
|
apache-2.0
|
kpet/clvk,kpet/clvk,kpet/clvk,kpet/clvk
|
f3c22197cb18dc25e7be2e42c4f6a03be7fc58ad
|
src/version.cpp
|
src/version.cpp
|
// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");
// Client version number
#define CLIENT_VERSION_SUFFIX "-ManicMiner"
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "$Format:%h$"
# define GIT_COMMIT_DATE "$Format:%cD$"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
|
// Copyright (c) 2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <string>
#include "version.h"
// Name of client reported in the 'version' message. Report the same name
// for both bitcoind and bitcoin-qt, to make it harder for attackers to
// target servers or GUI users specifically.
const std::string CLIENT_NAME("Satoshi");
// Client version number
#define CLIENT_VERSION_SUFFIX "-MM&KGW"
// The following part of the code determines the CLIENT_BUILD variable.
// Several mechanisms are used for this:
// * first, if HAVE_BUILD_INFO is defined, include build.h, a file that is
// generated by the build environment, possibly containing the output
// of git-describe in a macro called BUILD_DESC
// * secondly, if this is an exported version of the code, GIT_ARCHIVE will
// be defined (automatically using the export-subst git attribute), and
// GIT_COMMIT will contain the commit id.
// * then, three options exist for determining CLIENT_BUILD:
// * if BUILD_DESC is defined, use that literally (output of git-describe)
// * if not, but GIT_COMMIT is defined, use v[maj].[min].[rev].[build]-g[commit]
// * otherwise, use v[maj].[min].[rev].[build]-unk
// finally CLIENT_VERSION_SUFFIX is added
// First, include build.h if requested
#ifdef HAVE_BUILD_INFO
# include "build.h"
#endif
// git will put "#define GIT_ARCHIVE 1" on the next line inside archives. $Format:%n#define GIT_ARCHIVE 1$
#ifdef GIT_ARCHIVE
# define GIT_COMMIT_ID "$Format:%h$"
# define GIT_COMMIT_DATE "$Format:%cD$"
#endif
#define BUILD_DESC_FROM_COMMIT(maj,min,rev,build,commit) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-g" commit
#define BUILD_DESC_FROM_UNKNOWN(maj,min,rev,build) \
"v" DO_STRINGIZE(maj) "." DO_STRINGIZE(min) "." DO_STRINGIZE(rev) "." DO_STRINGIZE(build) "-unk"
#ifndef BUILD_DESC
# ifdef GIT_COMMIT_ID
# define BUILD_DESC BUILD_DESC_FROM_COMMIT(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD, GIT_COMMIT_ID)
# else
# define BUILD_DESC BUILD_DESC_FROM_UNKNOWN(CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD)
# endif
#endif
#ifndef BUILD_DATE
# ifdef GIT_COMMIT_DATE
# define BUILD_DATE GIT_COMMIT_DATE
# else
# define BUILD_DATE __DATE__ ", " __TIME__
# endif
#endif
const std::string CLIENT_BUILD(BUILD_DESC CLIENT_VERSION_SUFFIX);
const std::string CLIENT_DATE(BUILD_DATE);
|
Update version.cpp
|
Update version.cpp
New versión suffix: -MM&KWG
|
C++
|
mit
|
mp2apps/pesetacoin-master,mp2apps/pesetacoin-master,mp2apps/pesetacoin-master,mp2apps/pesetacoin-master,mp2apps/pesetacoin-master
|
973c6088d73f536e964623b8a04a11b36877e937
|
src/scene.cpp
|
src/scene.cpp
|
#include "./scene.h"
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <string>
#include <vector>
#include "./graphics/gl.h"
#include "./input/invoke_manager.h"
#include "./graphics/render_data.h"
#include "./graphics/managers.h"
#include "./graphics/volume_manager.h"
#include "./graphics/shader_program.h"
#include "./graphics/buffer_drawer.h"
#include "./camera_controllers.h"
#include "./nodes.h"
#include "./camera_node.h"
#include "./labelling/labeller_frame_data.h"
#include "./label_node.h"
#include "./eigen_qdebug.h"
#include "./utils/path_helper.h"
#include "./placement/to_gray.h"
#include "./placement/distance_transform.h"
#include "./placement/occupancy.h"
#include "./placement/apollonius.h"
#include "./texture_mapper_manager.h"
#include "./constraint_buffer_object.h"
#include "./placement/constraint_updater.h"
Scene::Scene(std::shared_ptr<InvokeManager> invokeManager,
std::shared_ptr<Nodes> nodes, std::shared_ptr<Labels> labels,
std::shared_ptr<Forces::Labeller> forcesLabeller,
std::shared_ptr<Placement::Labeller> placementLabeller,
std::shared_ptr<TextureMapperManager> textureMapperManager)
: nodes(nodes), labels(labels), forcesLabeller(forcesLabeller),
placementLabeller(placementLabeller), frustumOptimizer(nodes),
textureMapperManager(textureMapperManager)
{
cameraControllers =
std::make_shared<CameraControllers>(invokeManager, getCamera());
fbo = std::make_shared<Graphics::FrameBufferObject>();
constraintBufferObject = std::make_shared<ConstraintBufferObject>();
managers = std::make_shared<Graphics::Managers>();
}
Scene::~Scene()
{
nodes->clear();
qInfo() << "Destructor of Scene"
<< "Remaining managers instances" << managers.use_count();
}
void Scene::initialize()
{
glAssert(gl->glClearColor(0.9f, 0.9f, 0.8f, 1.0f));
quad = std::make_shared<Graphics::ScreenQuad>(
":shader/pass.vert", ":shader/textureForRenderBuffer.frag");
positionQuad = std::make_shared<Graphics::ScreenQuad>(
":shader/pass.vert", ":shader/positionRenderTarget.frag");
distanceTransformQuad = std::make_shared<Graphics::ScreenQuad>(
":shader/pass.vert", ":shader/distanceTransform.frag");
transparentQuad = std::make_shared<Graphics::ScreenQuad>(
":shader/pass.vert", ":shader/transparentOverlay.frag");
fbo->initialize(gl, width, height);
picker = std::make_unique<Picker>(fbo, gl, labels);
picker->resize(width, height);
constraintBufferObject->initialize(gl, textureMapperManager->getBufferSize(),
textureMapperManager->getBufferSize());
haBuffer =
std::make_shared<Graphics::HABuffer>(Eigen::Vector2i(width, height));
managers->getShaderManager()->initialize(gl, haBuffer);
managers->getObjectManager()->initialize(gl, 128, 10000000);
haBuffer->initialize(gl, managers);
quad->initialize(gl, managers);
positionQuad->initialize(gl, managers);
distanceTransformQuad->initialize(gl, managers);
transparentQuad->initialize(gl, managers);
managers->getTextureManager()->initialize(gl, true, 8);
textureMapperManager->resize(width, height);
textureMapperManager->initialize(gl, fbo, constraintBufferObject);
auto drawer = std::make_shared<Graphics::BufferDrawer>(
textureMapperManager->getBufferSize(),
textureMapperManager->getBufferSize(), gl, managers->getShaderManager());
auto constraintUpdater = std::make_shared<ConstraintUpdater>(
drawer, textureMapperManager->getBufferSize(),
textureMapperManager->getBufferSize());
placementLabeller->initialize(
textureMapperManager->getOccupancyTextureMapper(),
textureMapperManager->getDistanceTransformTextureMapper(),
textureMapperManager->getApolloniusTextureMapper(),
textureMapperManager->getConstraintTextureMapper(), constraintUpdater);
}
void Scene::cleanup()
{
placementLabeller->cleanup();
textureMapperManager->cleanup();
}
void Scene::update(double frameTime, QSet<Qt::Key> keysPressed)
{
auto camera = getCamera();
this->frameTime = frameTime;
cameraControllers->update(camera, frameTime);
frustumOptimizer.update(camera->getViewMatrix());
camera->updateNearAndFarPlanes(frustumOptimizer.getNear(),
frustumOptimizer.getFar());
haBuffer->updateNearAndFarPlanes(frustumOptimizer.getNear(),
frustumOptimizer.getFar());
/*
auto newPositions = forcesLabeller->update(LabellerFrameData(
frameTime, camera.getProjectionMatrix(), camera.getViewMatrix()));
*/
auto newPositions = placementLabeller->getLastPlacementResult();
for (auto &labelNode : nodes->getLabelNodes())
{
labelNode->labelPosition = newPositions[labelNode->label.id];
}
}
void Scene::render()
{
auto camera = getCamera();
if (shouldResize)
{
camera->resize(width, height);
fbo->resize(width, height);
shouldResize = false;
}
if (camera->needsResizing())
camera->resize(width, height);
glAssert(gl->glViewport(0, 0, width, height));
glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
RenderData renderData = createRenderData();
renderNodesWithHABufferIntoFBO(renderData);
glAssert(gl->glDisable(GL_DEPTH_TEST));
renderScreenQuad();
textureMapperManager->update();
constraintBufferObject->bind();
placementLabeller->update(LabellerFrameData(
frameTime, camera->getProjectionMatrix(), camera->getViewMatrix()));
constraintBufferObject->unbind();
glAssert(gl->glViewport(0, 0, width, height));
if (showConstraintOverlay)
{
constraintBufferObject->bindTexture(GL_TEXTURE0);
renderQuad(transparentQuad, Eigen::Matrix4f::Identity());
}
if (showBufferDebuggingViews)
renderDebuggingViews(renderData);
glAssert(gl->glEnable(GL_DEPTH_TEST));
nodes->renderLabels(gl, managers, renderData);
}
void Scene::renderNodesWithHABufferIntoFBO(const RenderData &renderData)
{
fbo->bind();
glAssert(gl->glViewport(0, 0, width, height));
glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
haBuffer->clearAndPrepare(managers);
nodes->render(gl, managers, renderData);
managers->getObjectManager()->render(renderData);
haBuffer->render(managers, renderData);
picker->doPick(renderData.projectionMatrix * renderData.viewMatrix);
fbo->unbind();
}
void Scene::renderDebuggingViews(const RenderData &renderData)
{
fbo->bindDepthTexture(GL_TEXTURE0);
auto transformation =
Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(-0.8, -0.8, 0)) *
Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));
renderQuad(quad, transformation.matrix());
textureMapperManager->bindOccupancyTexture();
transformation =
Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(-0.4, -0.8, 0)) *
Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));
renderQuad(quad, transformation.matrix());
textureMapperManager->bindDistanceTransform();
transformation =
Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.0, -0.8, 0)) *
Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));
renderQuad(distanceTransformQuad, transformation.matrix());
textureMapperManager->bindApollonius();
transformation =
Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.4, -0.8, 0)) *
Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));
renderQuad(quad, transformation.matrix());
constraintBufferObject->bindTexture(GL_TEXTURE0);
transformation =
Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.8, -0.8, 0)) *
Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));
renderQuad(quad, transformation.matrix());
}
void Scene::renderQuad(std::shared_ptr<Graphics::ScreenQuad> quad,
Eigen::Matrix4f modelMatrix)
{
RenderData renderData;
renderData.projectionMatrix = Eigen::Matrix4f::Identity();
renderData.viewMatrix = Eigen::Matrix4f::Identity();
renderData.modelMatrix = modelMatrix;
quad->getShaderProgram()->bind();
quad->getShaderProgram()->setUniform("textureSampler", 0);
quad->renderImmediately(gl, managers, renderData);
}
void Scene::renderScreenQuad()
{
fbo->bindColorTexture(GL_TEXTURE0);
renderQuad(quad, Eigen::Matrix4f::Identity());
}
void Scene::resize(int width, int height)
{
this->width = width;
this->height = height;
placementLabeller->resize(width, height);
shouldResize = true;
forcesLabeller->resize(width, height);
}
RenderData Scene::createRenderData()
{
RenderData renderData;
auto camera = getCamera();
renderData.projectionMatrix = camera->getProjectionMatrix();
renderData.viewMatrix = camera->getViewMatrix();
renderData.cameraPosition = camera->getPosition();
renderData.modelMatrix = Eigen::Matrix4f::Identity();
renderData.windowPixelSize = Eigen::Vector2f(width, height);
return renderData;
}
void Scene::pick(int id, Eigen::Vector2f position)
{
if (picker.get())
picker->pick(id, position);
}
void Scene::enableBufferDebuggingViews(bool enable)
{
showBufferDebuggingViews = enable;
}
void Scene::enableConstraingOverlay(bool enable)
{
showConstraintOverlay = enable;
}
std::shared_ptr<Camera> Scene::getCamera()
{
return nodes->getCameraNode()->getCamera();
}
|
#include "./scene.h"
#include <Eigen/Core>
#include <Eigen/Geometry>
#include <string>
#include <vector>
#include "./graphics/gl.h"
#include "./input/invoke_manager.h"
#include "./graphics/render_data.h"
#include "./graphics/managers.h"
#include "./graphics/volume_manager.h"
#include "./graphics/shader_program.h"
#include "./graphics/buffer_drawer.h"
#include "./camera_controllers.h"
#include "./nodes.h"
#include "./camera_node.h"
#include "./labelling/labeller_frame_data.h"
#include "./label_node.h"
#include "./eigen_qdebug.h"
#include "./utils/path_helper.h"
#include "./placement/to_gray.h"
#include "./placement/distance_transform.h"
#include "./placement/occupancy.h"
#include "./placement/apollonius.h"
#include "./texture_mapper_manager.h"
#include "./constraint_buffer_object.h"
#include "./placement/constraint_updater.h"
Scene::Scene(std::shared_ptr<InvokeManager> invokeManager,
std::shared_ptr<Nodes> nodes, std::shared_ptr<Labels> labels,
std::shared_ptr<Forces::Labeller> forcesLabeller,
std::shared_ptr<Placement::Labeller> placementLabeller,
std::shared_ptr<TextureMapperManager> textureMapperManager)
: nodes(nodes), labels(labels), forcesLabeller(forcesLabeller),
placementLabeller(placementLabeller), frustumOptimizer(nodes),
textureMapperManager(textureMapperManager)
{
cameraControllers =
std::make_shared<CameraControllers>(invokeManager, getCamera());
fbo = std::make_shared<Graphics::FrameBufferObject>();
constraintBufferObject = std::make_shared<ConstraintBufferObject>();
managers = std::make_shared<Graphics::Managers>();
}
Scene::~Scene()
{
nodes->clear();
qInfo() << "Destructor of Scene"
<< "Remaining managers instances" << managers.use_count();
}
void Scene::initialize()
{
glAssert(gl->glClearColor(0.9f, 0.9f, 0.8f, 1.0f));
quad = std::make_shared<Graphics::ScreenQuad>(
":shader/pass.vert", ":shader/textureForRenderBuffer.frag");
positionQuad = std::make_shared<Graphics::ScreenQuad>(
":shader/pass.vert", ":shader/positionRenderTarget.frag");
distanceTransformQuad = std::make_shared<Graphics::ScreenQuad>(
":shader/pass.vert", ":shader/distanceTransform.frag");
transparentQuad = std::make_shared<Graphics::ScreenQuad>(
":shader/pass.vert", ":shader/transparentOverlay.frag");
fbo->initialize(gl, width, height);
picker = std::make_unique<Picker>(fbo, gl, labels);
picker->resize(width, height);
constraintBufferObject->initialize(gl, textureMapperManager->getBufferSize(),
textureMapperManager->getBufferSize());
haBuffer =
std::make_shared<Graphics::HABuffer>(Eigen::Vector2i(width, height));
managers->getShaderManager()->initialize(gl, haBuffer);
managers->getObjectManager()->initialize(gl, 128, 10000000);
haBuffer->initialize(gl, managers);
quad->initialize(gl, managers);
positionQuad->initialize(gl, managers);
distanceTransformQuad->initialize(gl, managers);
transparentQuad->initialize(gl, managers);
managers->getTextureManager()->initialize(gl, true, 8);
textureMapperManager->resize(width, height);
textureMapperManager->initialize(gl, fbo, constraintBufferObject);
auto drawer = std::make_shared<Graphics::BufferDrawer>(
textureMapperManager->getBufferSize(),
textureMapperManager->getBufferSize(), gl, managers->getShaderManager());
auto constraintUpdater = std::make_shared<ConstraintUpdater>(
drawer, textureMapperManager->getBufferSize(),
textureMapperManager->getBufferSize());
placementLabeller->initialize(
textureMapperManager->getOccupancyTextureMapper(),
textureMapperManager->getDistanceTransformTextureMapper(),
textureMapperManager->getApolloniusTextureMapper(),
textureMapperManager->getConstraintTextureMapper(), constraintUpdater);
}
void Scene::cleanup()
{
placementLabeller->cleanup();
textureMapperManager->cleanup();
}
void Scene::update(double frameTime, QSet<Qt::Key> keysPressed)
{
auto camera = getCamera();
this->frameTime = frameTime;
cameraControllers->update(camera, frameTime);
// frustumOptimizer.update(camera->getViewMatrix());
// camera->updateNearAndFarPlanes(frustumOptimizer.getNear(),
// frustumOptimizer.getFar());
// haBuffer->updateNearAndFarPlanes(frustumOptimizer.getNear(),
// frustumOptimizer.getFar());
/*
auto newPositions = forcesLabeller->update(LabellerFrameData(
frameTime, camera.getProjectionMatrix(), camera.getViewMatrix()));
*/
auto newPositions = placementLabeller->getLastPlacementResult();
for (auto &labelNode : nodes->getLabelNodes())
{
labelNode->labelPosition = newPositions[labelNode->label.id];
}
}
void Scene::render()
{
auto camera = getCamera();
if (shouldResize)
{
camera->resize(width, height);
fbo->resize(width, height);
shouldResize = false;
}
if (camera->needsResizing())
camera->resize(width, height);
glAssert(gl->glViewport(0, 0, width, height));
glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
RenderData renderData = createRenderData();
renderNodesWithHABufferIntoFBO(renderData);
glAssert(gl->glDisable(GL_DEPTH_TEST));
renderScreenQuad();
textureMapperManager->update();
constraintBufferObject->bind();
placementLabeller->update(LabellerFrameData(
frameTime, camera->getProjectionMatrix(), camera->getViewMatrix()));
constraintBufferObject->unbind();
glAssert(gl->glViewport(0, 0, width, height));
if (showConstraintOverlay)
{
constraintBufferObject->bindTexture(GL_TEXTURE0);
renderQuad(transparentQuad, Eigen::Matrix4f::Identity());
}
if (showBufferDebuggingViews)
renderDebuggingViews(renderData);
glAssert(gl->glEnable(GL_DEPTH_TEST));
nodes->renderLabels(gl, managers, renderData);
}
void Scene::renderNodesWithHABufferIntoFBO(const RenderData &renderData)
{
fbo->bind();
glAssert(gl->glViewport(0, 0, width, height));
glAssert(gl->glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT));
haBuffer->clearAndPrepare(managers);
nodes->render(gl, managers, renderData);
managers->getObjectManager()->render(renderData);
haBuffer->render(managers, renderData);
picker->doPick(renderData.projectionMatrix * renderData.viewMatrix);
fbo->unbind();
}
void Scene::renderDebuggingViews(const RenderData &renderData)
{
fbo->bindDepthTexture(GL_TEXTURE0);
auto transformation =
Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(-0.8, -0.8, 0)) *
Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));
renderQuad(quad, transformation.matrix());
textureMapperManager->bindOccupancyTexture();
transformation =
Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(-0.4, -0.8, 0)) *
Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));
renderQuad(quad, transformation.matrix());
textureMapperManager->bindDistanceTransform();
transformation =
Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.0, -0.8, 0)) *
Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));
renderQuad(distanceTransformQuad, transformation.matrix());
textureMapperManager->bindApollonius();
transformation =
Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.4, -0.8, 0)) *
Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));
renderQuad(quad, transformation.matrix());
constraintBufferObject->bindTexture(GL_TEXTURE0);
transformation =
Eigen::Affine3f(Eigen::Translation3f(Eigen::Vector3f(0.8, -0.8, 0)) *
Eigen::Scaling(Eigen::Vector3f(0.2, 0.2, 1)));
renderQuad(quad, transformation.matrix());
}
void Scene::renderQuad(std::shared_ptr<Graphics::ScreenQuad> quad,
Eigen::Matrix4f modelMatrix)
{
RenderData renderData;
renderData.projectionMatrix = Eigen::Matrix4f::Identity();
renderData.viewMatrix = Eigen::Matrix4f::Identity();
renderData.modelMatrix = modelMatrix;
quad->getShaderProgram()->bind();
quad->getShaderProgram()->setUniform("textureSampler", 0);
quad->renderImmediately(gl, managers, renderData);
}
void Scene::renderScreenQuad()
{
fbo->bindColorTexture(GL_TEXTURE0);
renderQuad(quad, Eigen::Matrix4f::Identity());
}
void Scene::resize(int width, int height)
{
this->width = width;
this->height = height;
placementLabeller->resize(width, height);
shouldResize = true;
forcesLabeller->resize(width, height);
}
RenderData Scene::createRenderData()
{
RenderData renderData;
auto camera = getCamera();
renderData.projectionMatrix = camera->getProjectionMatrix();
renderData.viewMatrix = camera->getViewMatrix();
renderData.cameraPosition = camera->getPosition();
renderData.modelMatrix = Eigen::Matrix4f::Identity();
renderData.windowPixelSize = Eigen::Vector2f(width, height);
return renderData;
}
void Scene::pick(int id, Eigen::Vector2f position)
{
if (picker.get())
picker->pick(id, position);
}
void Scene::enableBufferDebuggingViews(bool enable)
{
showBufferDebuggingViews = enable;
}
void Scene::enableConstraingOverlay(bool enable)
{
showConstraintOverlay = enable;
}
std::shared_ptr<Camera> Scene::getCamera()
{
return nodes->getCameraNode()->getCamera();
}
|
Disable frustum optimizer for easier development of layering.
|
Disable frustum optimizer for easier development of layering.
|
C++
|
mit
|
Christof/voly-labeller,Christof/voly-labeller,Christof/voly-labeller,Christof/voly-labeller
|
65802068683f1f2b8ca4b6ca19399af815b5a962
|
src/timer.cpp
|
src/timer.cpp
|
#include "openmc/timer.h"
namespace openmc {
//==============================================================================
// Global variables
//==============================================================================
namespace simulation {
Timer time_active;
Timer time_bank;
Timer time_bank_sample;
Timer time_bank_sendrecv;
Timer time_finalize;
Timer time_inactive;
Timer time_initialize;
Timer time_read_xs;
Timer time_sample_source;
Timer time_tallies;
Timer time_total;
Timer time_transport;
Timer time_event_init;
Timer time_event_calculate_xs;
Timer time_event_advance_particle;
Timer time_event_surface_crossing;
Timer time_event_collision;
Timer time_event_death;
} // namespace simulation
//==============================================================================
// Timer implementation
//==============================================================================
void Timer::start ()
{
running_ = true;
start_ = clock::now();
}
void Timer::stop()
{
elapsed_ = elapsed();
running_ = false;
}
void Timer::reset()
{
running_ = false;
elapsed_ = 0.0;
}
double Timer::elapsed()
{
if (running_) {
std::chrono::duration<double> diff = clock::now() - start_;
return elapsed_ + diff.count();
} else {
return elapsed_;
}
}
//==============================================================================
// Non-member functions
//==============================================================================
void reset_timers()
{
simulation::time_active.reset();
simulation::time_bank.reset();
simulation::time_bank_sample.reset();
simulation::time_bank_sendrecv.reset();
simulation::time_finalize.reset();
simulation::time_inactive.reset();
simulation::time_initialize.reset();
simulation::time_read_xs.reset();
simulation::time_sample_source.reset();
simulation::time_tallies.reset();
simulation::time_total.reset();
simulation::time_transport.reset();
simulation::time_event_init.reset();
simulation::time_event_calculate_xs.reset();
simulation::time_event_advance_particle.reset();
simulation::time_event_surface_crossing.reset();
simulation::time_event_collision.reset();
simulation::time_event_death.reset();
}
void restart_timers()
{
simulation::time_active.restart();
simulation::time_bank.restart();
simulation::time_bank_sample.restart();
simulation::time_bank_sendrecv.restart();
simulation::time_finalize.restart();
simulation::time_inactive.restart();
simulation::time_initialize.restart();
simulation::time_read_xs.restart();
simulation::time_sample_source.restart();
simulation::time_tallies.restart();
simulation::time_total.restart();
simulation::time_transport.restart();
simulation::time_event_init.restart();
simulation::time_event_calculate_xs.restart();
simulation::time_event_advance_particle.restart();
simulation::time_event_surface_crossing.restart();
simulation::time_event_collision.restart();
simulation::time_event_death.restart();
}
} // namespace openmc
|
#include "openmc/timer.h"
namespace openmc {
//==============================================================================
// Global variables
//==============================================================================
namespace simulation {
Timer time_active;
Timer time_bank;
Timer time_bank_sample;
Timer time_bank_sendrecv;
Timer time_finalize;
Timer time_inactive;
Timer time_initialize;
Timer time_read_xs;
Timer time_sample_source;
Timer time_tallies;
Timer time_total;
Timer time_transport;
Timer time_event_init;
Timer time_event_calculate_xs;
Timer time_event_advance_particle;
Timer time_event_surface_crossing;
Timer time_event_collision;
Timer time_event_death;
} // namespace simulation
//==============================================================================
// Timer implementation
//==============================================================================
void Timer::start ()
{
running_ = true;
start_ = clock::now();
}
void Timer::stop()
{
elapsed_ = elapsed();
running_ = false;
}
void Timer::reset()
{
running_ = false;
elapsed_ = 0.0;
}
double Timer::elapsed()
{
if (running_) {
std::chrono::duration<double> diff = clock::now() - start_;
return elapsed_ + diff.count();
} else {
return elapsed_;
}
}
//==============================================================================
// Non-member functions
//==============================================================================
void reset_timers()
{
simulation::time_active.reset();
simulation::time_bank.reset();
simulation::time_bank_sample.reset();
simulation::time_bank_sendrecv.reset();
simulation::time_finalize.reset();
simulation::time_inactive.reset();
simulation::time_initialize.reset();
simulation::time_read_xs.reset();
simulation::time_sample_source.reset();
simulation::time_tallies.reset();
simulation::time_total.reset();
simulation::time_transport.reset();
simulation::time_event_init.reset();
simulation::time_event_calculate_xs.reset();
simulation::time_event_advance_particle.reset();
simulation::time_event_surface_crossing.reset();
simulation::time_event_collision.reset();
simulation::time_event_death.reset();
}
void restart_timers()
{
simulation::time_active.start();
simulation::time_bank.start();
simulation::time_bank_sample.start();
simulation::time_bank_sendrecv.start();
simulation::time_finalize.start();
simulation::time_inactive.start();
simulation::time_initialize.start();
simulation::time_read_xs.start();
simulation::time_sample_source.start();
simulation::time_tallies.start();
simulation::time_total.start();
simulation::time_transport.start();
simulation::time_event_init.start();
simulation::time_event_calculate_xs.start();
simulation::time_event_advance_particle.start();
simulation::time_event_surface_crossing.start();
simulation::time_event_collision.start();
simulation::time_event_death.start();
}
} // namespace openmc
|
fix a bug in timer.cpp
|
fix a bug in timer.cpp
|
C++
|
mit
|
walshjon/openmc,smharper/openmc,liangjg/openmc,paulromano/openmc,walshjon/openmc,mit-crpg/openmc,shikhar413/openmc,shikhar413/openmc,walshjon/openmc,mit-crpg/openmc,smharper/openmc,liangjg/openmc,shikhar413/openmc,smharper/openmc,mit-crpg/openmc,shikhar413/openmc,paulromano/openmc,liangjg/openmc,smharper/openmc,walshjon/openmc,liangjg/openmc,paulromano/openmc,amandalund/openmc,mit-crpg/openmc,paulromano/openmc,amandalund/openmc,amandalund/openmc,amandalund/openmc
|
ba7d0a5005ad861a766888915669a1404b753ca8
|
src/types.cpp
|
src/types.cpp
|
#include "clay.hpp"
#include "common.hpp"
llvm::Module *llvmModule;
llvm::ExecutionEngine *llvmEngine;
const llvm::TargetData *llvmTargetData;
void initLLVM() {
llvm::InitializeNativeTarget();
llvmModule = new llvm::Module("clay", llvm::getGlobalContext());
llvm::ModuleProvider *mp = new llvm::ExistingModuleProvider(llvmModule);
llvmEngine = llvm::EngineBuilder(mp).create();
assert(llvmEngine);
llvmTargetData = llvmEngine->getTargetData();
}
TypePtr boolType;
TypePtr int8Type;
TypePtr int16Type;
TypePtr int32Type;
TypePtr int64Type;
TypePtr uint8Type;
TypePtr uint16Type;
TypePtr uint32Type;
TypePtr uint64Type;
TypePtr float32Type;
TypePtr float64Type;
TypePtr compilerObjectType;
TypePtr voidType;
static vector<vector<ArrayTypePtr> > arrayTypes;
static vector<vector<TupleTypePtr> > tupleTypes;
static vector<vector<PointerTypePtr> > pointerTypes;
static vector<vector<RecordTypePtr> > recordTypes;
void initTypes() {
boolType = new BoolType();
int8Type = new IntegerType(8, true);
int16Type = new IntegerType(16, true);
int32Type = new IntegerType(32, true);
int64Type = new IntegerType(64, true);
uint8Type = new IntegerType(8, false);
uint16Type = new IntegerType(16, false);
uint32Type = new IntegerType(32, false);
uint64Type = new IntegerType(64, false);
float32Type = new FloatType(32);
float64Type = new FloatType(64);
compilerObjectType = new CompilerObjectType();
voidType = new VoidType();
int N = 1024;
arrayTypes.resize(N);
tupleTypes.resize(N);
pointerTypes.resize(N);
recordTypes.resize(N);
}
TypePtr integerType(int bits, bool isSigned) {
if (isSigned)
return intType(bits);
else
return uintType(bits);
}
TypePtr intType(int bits) {
switch (bits) {
case 8 : return int8Type;
case 16 : return int16Type;
case 32 : return int32Type;
case 64 : return int64Type;
default :
assert(false);
return NULL;
}
}
TypePtr uintType(int bits) {
switch (bits) {
case 8 : return uint8Type;
case 16 : return uint16Type;
case 32 : return uint32Type;
case 64 : return uint64Type;
default :
assert(false);
return NULL;
}
}
TypePtr floatType(int bits) {
switch (bits) {
case 32 : return float32Type;
case 64 : return float64Type;
default :
assert(false);
return NULL;
}
}
TypePtr arrayType(TypePtr elementType, int size) {
int h = pointerToInt(elementType.ptr()) + size;
h &= arrayTypes.size() - 1;
vector<ArrayTypePtr>::iterator i, end;
for (i = arrayTypes[h].begin(), end = arrayTypes[h].end();
i != end; ++i) {
ArrayType *t = i->ptr();
if ((t->elementType == elementType) && (t->size == size))
return t;
}
ArrayTypePtr t = new ArrayType(elementType, size);
arrayTypes[h].push_back(t);
return t.ptr();
}
TypePtr tupleType(const vector<TypePtr> &elementTypes) {
int h = 0;
vector<TypePtr>::const_iterator ei, eend;
for (ei = elementTypes.begin(), eend = elementTypes.end();
ei != eend; ++ei) {
h += pointerToInt(ei->ptr());
}
h &= tupleTypes.size() - 1;
vector<TupleTypePtr>::iterator i, end;
for (i = tupleTypes[h].begin(), end = tupleTypes[h].end();
i != end; ++i) {
TupleType *t = i->ptr();
if (t->elementTypes == elementTypes)
return t;
}
TupleTypePtr t = new TupleType(elementTypes);
tupleTypes[h].push_back(t);
return t.ptr();
}
TypePtr pointerType(TypePtr pointeeType) {
int h = pointerToInt(pointeeType.ptr());
h &= pointerTypes.size() - 1;
vector<PointerTypePtr>::iterator i, end;
for (i = pointerTypes[h].begin(), end = pointerTypes[h].end();
i != end; ++i) {
PointerType *t = i->ptr();
if (t->pointeeType == pointeeType)
return t;
}
PointerTypePtr t = new PointerType(pointeeType);
pointerTypes[h].push_back(t);
return t.ptr();
}
static bool valueVectorEquals(const vector<ValuePtr> &a,
const vector<ValuePtr> &b) {
if (a.size() != b.size()) return false;
vector<ValuePtr>::const_iterator ai, aend, bi;
for (ai = a.begin(), aend = a.end(), bi = b.begin();
ai != aend; ++ai, ++bi) {
if (!valueEquals(*ai, *bi))
return false;
}
return true;
}
TypePtr recordType(RecordPtr record, const vector<ValuePtr> ¶ms) {
int h = pointerToInt(record.ptr());
vector<ValuePtr>::const_iterator vi, vend;
for (vi = params.begin(), vend = params.end(); vi != vend; ++vi)
h += valueHash(*vi);
h &= recordTypes.size() - 1;
vector<RecordTypePtr>::iterator i, end;
for (i = recordTypes[h].begin(), end = recordTypes[h].end();
i != end; ++i) {
RecordType *t = i->ptr();
if ((t->record == record) && valueVectorEquals(t->params, params))
return t;
}
RecordTypePtr t = new RecordType(record);
for (vi = params.begin(), vend = params.end(); vi != vend; ++vi)
t->params.push_back(cloneValue(*vi));
recordTypes[h].push_back(t);
return t.ptr();
}
//
// recordFieldTypes
//
static void initializeRecordFields(RecordTypePtr t) {
t->fieldsInitialized = true;
RecordPtr r = t->record;
assert(t->params.size() == r->patternVars.size());
EnvPtr env = new Env(r->env);
for (unsigned i = 0; i < t->params.size(); ++i)
addLocal(env, r->patternVars[i], t->params[i].ptr());
for (unsigned i = 0; i < r->formalArgs.size(); ++i) {
FormalArg *x = r->formalArgs[i].ptr();
switch (x->objKind) {
case VALUE_ARG : {
ValueArg *y = (ValueArg *)x;
t->fieldIndexMap[y->name->str] = t->fieldTypes.size();
TypePtr ftype = evaluateNonVoidType(y->type, env);
t->fieldTypes.push_back(ftype);
break;
}
case STATIC_ARG :
break;
default :
assert(false);
}
}
}
const vector<TypePtr> &recordFieldTypes(RecordTypePtr t) {
if (!t->fieldsInitialized)
initializeRecordFields(t);
return t->fieldTypes;
}
const map<string, int> &recordFieldIndexMap(RecordTypePtr t) {
if (!t->fieldsInitialized)
initializeRecordFields(t);
return t->fieldIndexMap;
}
//
// llvmType
//
static const llvm::Type *makeLLVMType(TypePtr t);
const llvm::Type *llvmType(TypePtr t) {
if (t->llTypeHolder != NULL)
return t->llTypeHolder->get();
const llvm::Type *llt = makeLLVMType(t);
if (t->llTypeHolder == NULL)
t->llTypeHolder = new llvm::PATypeHolder(llt);
return llt;
}
static const llvm::Type *makeLLVMType(TypePtr t) {
switch (t->typeKind) {
case BOOL_TYPE :
return llvm::Type::getInt8Ty(llvm::getGlobalContext());
case INTEGER_TYPE : {
IntegerType *x = (IntegerType *)t.ptr();
return llvm::IntegerType::get(llvm::getGlobalContext(), x->bits);
}
case FLOAT_TYPE : {
FloatType *x = (FloatType *)t.ptr();
switch (x->bits) {
case 32 :
return llvm::Type::getFloatTy(llvm::getGlobalContext());
case 64 :
return llvm::Type::getDoubleTy(llvm::getGlobalContext());
default :
assert(false);
return NULL;
}
}
case ARRAY_TYPE : {
ArrayType *x = (ArrayType *)t.ptr();
return llvm::ArrayType::get(llvmType(x->elementType), x->size);
}
case TUPLE_TYPE : {
TupleType *x = (TupleType *)t.ptr();
vector<const llvm::Type *> llTypes;
vector<TypePtr>::iterator i, end;
for (i = x->elementTypes.begin(), end = x->elementTypes.end();
i != end; ++i)
llTypes.push_back(llvmType(*i));
return llvm::StructType::get(llvm::getGlobalContext(), llTypes);
}
case POINTER_TYPE : {
PointerType *x = (PointerType *)t.ptr();
return llvm::PointerType::getUnqual(llvmType(x->pointeeType));
}
case RECORD_TYPE : {
RecordType *x = (RecordType *)t.ptr();
llvm::OpaqueType *opaque =
llvm::OpaqueType::get(llvm::getGlobalContext());
x->llTypeHolder = new llvm::PATypeHolder(opaque);
const vector<TypePtr> &fieldTypes = recordFieldTypes(x);
vector<const llvm::Type *> llTypes;
vector<TypePtr>::const_iterator i, end;
for (i = fieldTypes.begin(), end = fieldTypes.end(); i != end; ++i)
llTypes.push_back(llvmType(*i));
llvm::StructType *st =
llvm::StructType::get(llvm::getGlobalContext(), llTypes);
opaque->refineAbstractTypeTo(st);
return x->llTypeHolder->get();
}
case COMPILER_OBJECT_TYPE :
return llvm::IntegerType::get(llvm::getGlobalContext(), 32);
case VOID_TYPE :
return llvm::Type::getVoidTy(llvm::getGlobalContext());
default :
assert(false);
return NULL;
}
}
int typeSize(TypePtr t) {
if (t->typeSize < 0)
t->typeSize = llvmTargetData->getTypeAllocSize(llvmType(t));
return t->typeSize;
}
//
// typePrint
//
void typePrint(TypePtr t, ostream &out) {
switch (t->typeKind) {
case BOOL_TYPE :
out << "Bool";
break;
case INTEGER_TYPE : {
IntegerType *x = (IntegerType *)t.ptr();
if (!x->isSigned)
out << "U";
out << "Int" << x->bits;
break;
}
case FLOAT_TYPE : {
FloatType *x = (FloatType *)t.ptr();
out << "Float" << x->bits;
break;
}
case ARRAY_TYPE : {
ArrayType *x = (ArrayType *)t.ptr();
out << "Array[" << x->elementType << ", " << x->size << "]";
break;
}
case TUPLE_TYPE : {
TupleType *x = (TupleType *)t.ptr();
out << "Tuple" << x->elementTypes;
break;
}
case POINTER_TYPE : {
PointerType *x = (PointerType *)t.ptr();
out << "Pointer[" << x->pointeeType << "]";
break;
}
case RECORD_TYPE : {
RecordType *x = (RecordType *)t.ptr();
out << x->record->name->str;
if (!x->params.empty())
out << x->params;
break;
}
case COMPILER_OBJECT_TYPE :
out << "CompilerObject";
break;
case VOID_TYPE :
out << "Void";
break;
default :
assert(false);
}
}
|
#include "clay.hpp"
#include "common.hpp"
llvm::Module *llvmModule;
llvm::ExecutionEngine *llvmEngine;
const llvm::TargetData *llvmTargetData;
void initLLVM() {
llvm::InitializeNativeTarget();
llvmModule = new llvm::Module("clay", llvm::getGlobalContext());
llvm::ModuleProvider *mp = new llvm::ExistingModuleProvider(llvmModule);
llvmEngine = llvm::EngineBuilder(mp).create();
assert(llvmEngine);
llvmTargetData = llvmEngine->getTargetData();
llvmModule->setDataLayout(llvmTargetData->getStringRepresentation());
}
TypePtr boolType;
TypePtr int8Type;
TypePtr int16Type;
TypePtr int32Type;
TypePtr int64Type;
TypePtr uint8Type;
TypePtr uint16Type;
TypePtr uint32Type;
TypePtr uint64Type;
TypePtr float32Type;
TypePtr float64Type;
TypePtr compilerObjectType;
TypePtr voidType;
static vector<vector<ArrayTypePtr> > arrayTypes;
static vector<vector<TupleTypePtr> > tupleTypes;
static vector<vector<PointerTypePtr> > pointerTypes;
static vector<vector<RecordTypePtr> > recordTypes;
void initTypes() {
boolType = new BoolType();
int8Type = new IntegerType(8, true);
int16Type = new IntegerType(16, true);
int32Type = new IntegerType(32, true);
int64Type = new IntegerType(64, true);
uint8Type = new IntegerType(8, false);
uint16Type = new IntegerType(16, false);
uint32Type = new IntegerType(32, false);
uint64Type = new IntegerType(64, false);
float32Type = new FloatType(32);
float64Type = new FloatType(64);
compilerObjectType = new CompilerObjectType();
voidType = new VoidType();
int N = 1024;
arrayTypes.resize(N);
tupleTypes.resize(N);
pointerTypes.resize(N);
recordTypes.resize(N);
}
TypePtr integerType(int bits, bool isSigned) {
if (isSigned)
return intType(bits);
else
return uintType(bits);
}
TypePtr intType(int bits) {
switch (bits) {
case 8 : return int8Type;
case 16 : return int16Type;
case 32 : return int32Type;
case 64 : return int64Type;
default :
assert(false);
return NULL;
}
}
TypePtr uintType(int bits) {
switch (bits) {
case 8 : return uint8Type;
case 16 : return uint16Type;
case 32 : return uint32Type;
case 64 : return uint64Type;
default :
assert(false);
return NULL;
}
}
TypePtr floatType(int bits) {
switch (bits) {
case 32 : return float32Type;
case 64 : return float64Type;
default :
assert(false);
return NULL;
}
}
TypePtr arrayType(TypePtr elementType, int size) {
int h = pointerToInt(elementType.ptr()) + size;
h &= arrayTypes.size() - 1;
vector<ArrayTypePtr>::iterator i, end;
for (i = arrayTypes[h].begin(), end = arrayTypes[h].end();
i != end; ++i) {
ArrayType *t = i->ptr();
if ((t->elementType == elementType) && (t->size == size))
return t;
}
ArrayTypePtr t = new ArrayType(elementType, size);
arrayTypes[h].push_back(t);
return t.ptr();
}
TypePtr tupleType(const vector<TypePtr> &elementTypes) {
int h = 0;
vector<TypePtr>::const_iterator ei, eend;
for (ei = elementTypes.begin(), eend = elementTypes.end();
ei != eend; ++ei) {
h += pointerToInt(ei->ptr());
}
h &= tupleTypes.size() - 1;
vector<TupleTypePtr>::iterator i, end;
for (i = tupleTypes[h].begin(), end = tupleTypes[h].end();
i != end; ++i) {
TupleType *t = i->ptr();
if (t->elementTypes == elementTypes)
return t;
}
TupleTypePtr t = new TupleType(elementTypes);
tupleTypes[h].push_back(t);
return t.ptr();
}
TypePtr pointerType(TypePtr pointeeType) {
int h = pointerToInt(pointeeType.ptr());
h &= pointerTypes.size() - 1;
vector<PointerTypePtr>::iterator i, end;
for (i = pointerTypes[h].begin(), end = pointerTypes[h].end();
i != end; ++i) {
PointerType *t = i->ptr();
if (t->pointeeType == pointeeType)
return t;
}
PointerTypePtr t = new PointerType(pointeeType);
pointerTypes[h].push_back(t);
return t.ptr();
}
static bool valueVectorEquals(const vector<ValuePtr> &a,
const vector<ValuePtr> &b) {
if (a.size() != b.size()) return false;
vector<ValuePtr>::const_iterator ai, aend, bi;
for (ai = a.begin(), aend = a.end(), bi = b.begin();
ai != aend; ++ai, ++bi) {
if (!valueEquals(*ai, *bi))
return false;
}
return true;
}
TypePtr recordType(RecordPtr record, const vector<ValuePtr> ¶ms) {
int h = pointerToInt(record.ptr());
vector<ValuePtr>::const_iterator vi, vend;
for (vi = params.begin(), vend = params.end(); vi != vend; ++vi)
h += valueHash(*vi);
h &= recordTypes.size() - 1;
vector<RecordTypePtr>::iterator i, end;
for (i = recordTypes[h].begin(), end = recordTypes[h].end();
i != end; ++i) {
RecordType *t = i->ptr();
if ((t->record == record) && valueVectorEquals(t->params, params))
return t;
}
RecordTypePtr t = new RecordType(record);
for (vi = params.begin(), vend = params.end(); vi != vend; ++vi)
t->params.push_back(cloneValue(*vi));
recordTypes[h].push_back(t);
return t.ptr();
}
//
// recordFieldTypes
//
static void initializeRecordFields(RecordTypePtr t) {
t->fieldsInitialized = true;
RecordPtr r = t->record;
assert(t->params.size() == r->patternVars.size());
EnvPtr env = new Env(r->env);
for (unsigned i = 0; i < t->params.size(); ++i)
addLocal(env, r->patternVars[i], t->params[i].ptr());
for (unsigned i = 0; i < r->formalArgs.size(); ++i) {
FormalArg *x = r->formalArgs[i].ptr();
switch (x->objKind) {
case VALUE_ARG : {
ValueArg *y = (ValueArg *)x;
t->fieldIndexMap[y->name->str] = t->fieldTypes.size();
TypePtr ftype = evaluateNonVoidType(y->type, env);
t->fieldTypes.push_back(ftype);
break;
}
case STATIC_ARG :
break;
default :
assert(false);
}
}
}
const vector<TypePtr> &recordFieldTypes(RecordTypePtr t) {
if (!t->fieldsInitialized)
initializeRecordFields(t);
return t->fieldTypes;
}
const map<string, int> &recordFieldIndexMap(RecordTypePtr t) {
if (!t->fieldsInitialized)
initializeRecordFields(t);
return t->fieldIndexMap;
}
//
// llvmType
//
static const llvm::Type *makeLLVMType(TypePtr t);
const llvm::Type *llvmType(TypePtr t) {
if (t->llTypeHolder != NULL)
return t->llTypeHolder->get();
const llvm::Type *llt = makeLLVMType(t);
if (t->llTypeHolder == NULL)
t->llTypeHolder = new llvm::PATypeHolder(llt);
return llt;
}
static const llvm::Type *makeLLVMType(TypePtr t) {
switch (t->typeKind) {
case BOOL_TYPE :
return llvm::Type::getInt8Ty(llvm::getGlobalContext());
case INTEGER_TYPE : {
IntegerType *x = (IntegerType *)t.ptr();
return llvm::IntegerType::get(llvm::getGlobalContext(), x->bits);
}
case FLOAT_TYPE : {
FloatType *x = (FloatType *)t.ptr();
switch (x->bits) {
case 32 :
return llvm::Type::getFloatTy(llvm::getGlobalContext());
case 64 :
return llvm::Type::getDoubleTy(llvm::getGlobalContext());
default :
assert(false);
return NULL;
}
}
case ARRAY_TYPE : {
ArrayType *x = (ArrayType *)t.ptr();
return llvm::ArrayType::get(llvmType(x->elementType), x->size);
}
case TUPLE_TYPE : {
TupleType *x = (TupleType *)t.ptr();
vector<const llvm::Type *> llTypes;
vector<TypePtr>::iterator i, end;
for (i = x->elementTypes.begin(), end = x->elementTypes.end();
i != end; ++i)
llTypes.push_back(llvmType(*i));
return llvm::StructType::get(llvm::getGlobalContext(), llTypes);
}
case POINTER_TYPE : {
PointerType *x = (PointerType *)t.ptr();
return llvm::PointerType::getUnqual(llvmType(x->pointeeType));
}
case RECORD_TYPE : {
RecordType *x = (RecordType *)t.ptr();
llvm::OpaqueType *opaque =
llvm::OpaqueType::get(llvm::getGlobalContext());
x->llTypeHolder = new llvm::PATypeHolder(opaque);
const vector<TypePtr> &fieldTypes = recordFieldTypes(x);
vector<const llvm::Type *> llTypes;
vector<TypePtr>::const_iterator i, end;
for (i = fieldTypes.begin(), end = fieldTypes.end(); i != end; ++i)
llTypes.push_back(llvmType(*i));
llvm::StructType *st =
llvm::StructType::get(llvm::getGlobalContext(), llTypes);
opaque->refineAbstractTypeTo(st);
return x->llTypeHolder->get();
}
case COMPILER_OBJECT_TYPE :
return llvm::IntegerType::get(llvm::getGlobalContext(), 32);
case VOID_TYPE :
return llvm::Type::getVoidTy(llvm::getGlobalContext());
default :
assert(false);
return NULL;
}
}
int typeSize(TypePtr t) {
if (t->typeSize < 0)
t->typeSize = llvmTargetData->getTypeAllocSize(llvmType(t));
return t->typeSize;
}
//
// typePrint
//
void typePrint(TypePtr t, ostream &out) {
switch (t->typeKind) {
case BOOL_TYPE :
out << "Bool";
break;
case INTEGER_TYPE : {
IntegerType *x = (IntegerType *)t.ptr();
if (!x->isSigned)
out << "U";
out << "Int" << x->bits;
break;
}
case FLOAT_TYPE : {
FloatType *x = (FloatType *)t.ptr();
out << "Float" << x->bits;
break;
}
case ARRAY_TYPE : {
ArrayType *x = (ArrayType *)t.ptr();
out << "Array[" << x->elementType << ", " << x->size << "]";
break;
}
case TUPLE_TYPE : {
TupleType *x = (TupleType *)t.ptr();
out << "Tuple" << x->elementTypes;
break;
}
case POINTER_TYPE : {
PointerType *x = (PointerType *)t.ptr();
out << "Pointer[" << x->pointeeType << "]";
break;
}
case RECORD_TYPE : {
RecordType *x = (RecordType *)t.ptr();
out << x->record->name->str;
if (!x->params.empty())
out << x->params;
break;
}
case COMPILER_OBJECT_TYPE :
out << "CompilerObject";
break;
case VOID_TYPE :
out << "Void";
break;
default :
assert(false);
}
}
|
set llvm module's target data from execution engine.
|
set llvm module's target data from execution engine.
|
C++
|
bsd-2-clause
|
jckarter/clay,aep/clay,iamrekcah/clay,aep/clay,iamrekcah/clay,aep/clay,jckarter/clay,jckarter/clay,mario-campos/clay,iamrekcah/clay,jckarter/clay,jckarter/clay,aep/clay,mario-campos/clay,mario-campos/clay,aep/clay,mario-campos/clay,iamrekcah/clay,mario-campos/clay,aep/clay,iamrekcah/clay,jckarter/clay
|
10c3ba2c1b8cb494175c3eae0f7c6fbecf1b3bd0
|
servers/audio/audio_rb_resampler.cpp
|
servers/audio/audio_rb_resampler.cpp
|
/*************************************************************************/
/* audio_rb_resampler.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "audio_rb_resampler.h"
#include "core/math/math_funcs.h"
#include "core/os/os.h"
#include "servers/audio_server.h"
int AudioRBResampler::get_channel_count() const {
if (!rb)
return 0;
return channels;
}
// Linear interpolation based sample rate conversion (low quality)
// Note that AudioStreamPlaybackResampled::mix has better algorithm,
// but it wasn't obvious to integrate that with VideoPlayer
template <int C>
uint32_t AudioRBResampler::_resample(AudioFrame *p_dest, int p_todo, int32_t p_increment) {
uint32_t read = offset & MIX_FRAC_MASK;
for (int i = 0; i < p_todo; i++) {
offset = (offset + p_increment) & (((1 << (rb_bits + MIX_FRAC_BITS)) - 1));
read += p_increment;
uint32_t pos = offset >> MIX_FRAC_BITS;
float frac = float(offset & MIX_FRAC_MASK) / float(MIX_FRAC_LEN);
ERR_FAIL_COND_V(pos >= rb_len, 0);
uint32_t pos_next = (pos + 1) & rb_mask;
// since this is a template with a known compile time value (C), conditionals go away when compiling.
if (C == 1) {
float v0 = rb[pos];
float v0n = rb[pos_next];
v0 += (v0n - v0) * frac;
p_dest[i] = AudioFrame(v0, v0);
}
if (C == 2) {
float v0 = rb[(pos << 1) + 0];
float v1 = rb[(pos << 1) + 1];
float v0n = rb[(pos_next << 1) + 0];
float v1n = rb[(pos_next << 1) + 1];
v0 += (v0n - v0) * frac;
v1 += (v1n - v1) * frac;
p_dest[i] = AudioFrame(v0, v1);
}
// For now, channels higher than stereo are almost ignored
if (C == 4) {
// FIXME: v2 and v3 are not being used (thus were commented out to prevent
// compilation warnings, but they should likely be uncommented *and* used).
// See also C == 6 with similar issues.
float v0 = rb[(pos << 2) + 0];
float v1 = rb[(pos << 2) + 1];
/*
float v2 = rb[(pos << 2) + 2];
float v3 = rb[(pos << 2) + 3];
*/
float v0n = rb[(pos_next << 2) + 0];
float v1n = rb[(pos_next << 2) + 1];
/*
float v2n = rb[(pos_next << 2) + 2];
float v3n = rb[(pos_next << 2) + 3];
*/
v0 += (v0n - v0) * frac;
v1 += (v1n - v1) * frac;
/*
v2 += (v2n - v2) * frac;
v3 += (v3n - v3) * frac;
*/
p_dest[i] = AudioFrame(v0, v1);
}
if (C == 6) {
// FIXME: Lot of unused assignments here, but it seems like intermediate calculations
// should be done as for C == 2 (C == 4 also has some unused assignments).
float v0 = rb[(pos * 6) + 0];
float v1 = rb[(pos * 6) + 1];
/*
float v2 = rb[(pos * 6) + 2];
float v3 = rb[(pos * 6) + 3];
float v4 = rb[(pos * 6) + 4];
float v5 = rb[(pos * 6) + 5];
float v0n = rb[(pos_next * 6) + 0];
float v1n = rb[(pos_next * 6) + 1];
float v2n = rb[(pos_next * 6) + 2];
float v3n = rb[(pos_next * 6) + 3];
float v4n = rb[(pos_next * 6) + 4];
float v5n = rb[(pos_next * 6) + 5];
*/
p_dest[i] = AudioFrame(v0, v1);
}
}
return read >> MIX_FRAC_BITS; //rb_read_pos = offset >> MIX_FRAC_BITS;
}
bool AudioRBResampler::mix(AudioFrame *p_dest, int p_frames) {
if (!rb)
return false;
int32_t increment = (src_mix_rate * MIX_FRAC_LEN) / target_mix_rate;
int read_space = get_reader_space();
int target_todo = MIN(get_num_of_ready_frames(), p_frames);
{
int src_read = 0;
switch (channels) {
case 1: src_read = _resample<1>(p_dest, target_todo, increment); break;
case 2: src_read = _resample<2>(p_dest, target_todo, increment); break;
case 4: src_read = _resample<4>(p_dest, target_todo, increment); break;
case 6: src_read = _resample<6>(p_dest, target_todo, increment); break;
}
if (src_read > read_space)
src_read = read_space;
rb_read_pos = (rb_read_pos + src_read) & rb_mask;
// Create fadeout effect for the end of stream (note that it can be because of slow writer)
if (p_frames - target_todo > 0) {
for (int i = 0; i < target_todo; i++) {
p_dest[i] = p_dest[i] * float(target_todo - i) / float(target_todo);
}
}
// Fill zeros (silence) for the rest of frames
for (int i = target_todo; i < p_frames; i++) {
p_dest[i] = AudioFrame(0, 0);
}
}
return true;
}
int AudioRBResampler::get_num_of_ready_frames() {
if (!is_ready())
return 0;
int32_t increment = (src_mix_rate * MIX_FRAC_LEN) / target_mix_rate;
int read_space = get_reader_space();
return (int64_t(read_space) << MIX_FRAC_BITS) / increment;
}
Error AudioRBResampler::setup(int p_channels, int p_src_mix_rate, int p_target_mix_rate, int p_buffer_msec, int p_minbuff_needed) {
ERR_FAIL_COND_V(p_channels != 1 && p_channels != 2 && p_channels != 4 && p_channels != 6, ERR_INVALID_PARAMETER);
int desired_rb_bits = nearest_shift(MAX((p_buffer_msec / 1000.0) * p_src_mix_rate, p_minbuff_needed));
bool recreate = !rb;
if (rb && (uint32_t(desired_rb_bits) != rb_bits || channels != uint32_t(p_channels))) {
memdelete_arr(rb);
memdelete_arr(read_buf);
recreate = true;
}
if (recreate) {
channels = p_channels;
rb_bits = desired_rb_bits;
rb_len = (1 << rb_bits);
rb_mask = rb_len - 1;
rb = memnew_arr(float, rb_len *p_channels);
read_buf = memnew_arr(float, rb_len *p_channels);
}
src_mix_rate = p_src_mix_rate;
target_mix_rate = p_target_mix_rate;
offset = 0;
rb_read_pos = 0;
rb_write_pos = 0;
//avoid maybe strange noises upon load
for (unsigned int i = 0; i < (rb_len * channels); i++) {
rb[i] = 0;
read_buf[i] = 0;
}
return OK;
}
void AudioRBResampler::clear() {
if (!rb)
return;
//should be stopped at this point but just in case
if (rb) {
memdelete_arr(rb);
memdelete_arr(read_buf);
}
rb = NULL;
offset = 0;
rb_read_pos = 0;
rb_write_pos = 0;
read_buf = NULL;
}
AudioRBResampler::AudioRBResampler() {
rb = NULL;
offset = 0;
read_buf = NULL;
rb_read_pos = 0;
rb_write_pos = 0;
rb_bits = 0;
rb_len = 0;
rb_mask = 0;
read_buff_len = 0;
channels = 0;
src_mix_rate = 0;
target_mix_rate = 0;
}
AudioRBResampler::~AudioRBResampler() {
if (rb) {
memdelete_arr(rb);
memdelete_arr(read_buf);
}
}
|
/*************************************************************************/
/* audio_rb_resampler.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2018 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2018 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* 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 "audio_rb_resampler.h"
#include "core/math/math_funcs.h"
#include "core/os/os.h"
#include "servers/audio_server.h"
int AudioRBResampler::get_channel_count() const {
if (!rb)
return 0;
return channels;
}
// Linear interpolation based sample rate conversion (low quality)
// Note that AudioStreamPlaybackResampled::mix has better algorithm,
// but it wasn't obvious to integrate that with VideoPlayer
template <int C>
uint32_t AudioRBResampler::_resample(AudioFrame *p_dest, int p_todo, int32_t p_increment) {
uint32_t read = offset & MIX_FRAC_MASK;
for (int i = 0; i < p_todo; i++) {
offset = (offset + p_increment) & (((1 << (rb_bits + MIX_FRAC_BITS)) - 1));
read += p_increment;
uint32_t pos = offset >> MIX_FRAC_BITS;
float frac = float(offset & MIX_FRAC_MASK) / float(MIX_FRAC_LEN);
ERR_FAIL_COND_V(pos >= rb_len, 0);
uint32_t pos_next = (pos + 1) & rb_mask;
// since this is a template with a known compile time value (C), conditionals go away when compiling.
if (C == 1) {
float v0 = rb[pos];
float v0n = rb[pos_next];
v0 += (v0n - v0) * frac;
p_dest[i] = AudioFrame(v0, v0);
}
if (C == 2) {
float v0 = rb[(pos << 1) + 0];
float v1 = rb[(pos << 1) + 1];
float v0n = rb[(pos_next << 1) + 0];
float v1n = rb[(pos_next << 1) + 1];
v0 += (v0n - v0) * frac;
v1 += (v1n - v1) * frac;
p_dest[i] = AudioFrame(v0, v1);
}
// This will probably never be used, but added anyway
if (C == 4) {
float v0 = rb[(pos << 2) + 0];
float v1 = rb[(pos << 2) + 1];
float v0n = rb[(pos_next << 2) + 0];
float v1n = rb[(pos_next << 2) + 1];
v0 += (v0n - v0) * frac;
v1 += (v1n - v1) * frac;
p_dest[i] = AudioFrame(v0, v1);
}
if (C == 6) {
float v0 = rb[(pos * 6) + 0];
float v1 = rb[(pos * 6) + 1];
float v0n = rb[(pos_next * 6) + 0];
float v1n = rb[(pos_next * 6) + 1];
v0 += (v0n - v0) * frac;
v1 += (v1n - v1) * frac;
p_dest[i] = AudioFrame(v0, v1);
}
}
return read >> MIX_FRAC_BITS; //rb_read_pos = offset >> MIX_FRAC_BITS;
}
bool AudioRBResampler::mix(AudioFrame *p_dest, int p_frames) {
if (!rb)
return false;
int32_t increment = (src_mix_rate * MIX_FRAC_LEN) / target_mix_rate;
int read_space = get_reader_space();
int target_todo = MIN(get_num_of_ready_frames(), p_frames);
{
int src_read = 0;
switch (channels) {
case 1: src_read = _resample<1>(p_dest, target_todo, increment); break;
case 2: src_read = _resample<2>(p_dest, target_todo, increment); break;
case 4: src_read = _resample<4>(p_dest, target_todo, increment); break;
case 6: src_read = _resample<6>(p_dest, target_todo, increment); break;
}
if (src_read > read_space)
src_read = read_space;
rb_read_pos = (rb_read_pos + src_read) & rb_mask;
// Create fadeout effect for the end of stream (note that it can be because of slow writer)
if (p_frames - target_todo > 0) {
for (int i = 0; i < target_todo; i++) {
p_dest[i] = p_dest[i] * float(target_todo - i) / float(target_todo);
}
}
// Fill zeros (silence) for the rest of frames
for (int i = target_todo; i < p_frames; i++) {
p_dest[i] = AudioFrame(0, 0);
}
}
return true;
}
int AudioRBResampler::get_num_of_ready_frames() {
if (!is_ready())
return 0;
int32_t increment = (src_mix_rate * MIX_FRAC_LEN) / target_mix_rate;
int read_space = get_reader_space();
return (int64_t(read_space) << MIX_FRAC_BITS) / increment;
}
Error AudioRBResampler::setup(int p_channels, int p_src_mix_rate, int p_target_mix_rate, int p_buffer_msec, int p_minbuff_needed) {
ERR_FAIL_COND_V(p_channels != 1 && p_channels != 2 && p_channels != 4 && p_channels != 6, ERR_INVALID_PARAMETER);
int desired_rb_bits = nearest_shift(MAX((p_buffer_msec / 1000.0) * p_src_mix_rate, p_minbuff_needed));
bool recreate = !rb;
if (rb && (uint32_t(desired_rb_bits) != rb_bits || channels != uint32_t(p_channels))) {
memdelete_arr(rb);
memdelete_arr(read_buf);
recreate = true;
}
if (recreate) {
channels = p_channels;
rb_bits = desired_rb_bits;
rb_len = (1 << rb_bits);
rb_mask = rb_len - 1;
rb = memnew_arr(float, rb_len *p_channels);
read_buf = memnew_arr(float, rb_len *p_channels);
}
src_mix_rate = p_src_mix_rate;
target_mix_rate = p_target_mix_rate;
offset = 0;
rb_read_pos = 0;
rb_write_pos = 0;
//avoid maybe strange noises upon load
for (unsigned int i = 0; i < (rb_len * channels); i++) {
rb[i] = 0;
read_buf[i] = 0;
}
return OK;
}
void AudioRBResampler::clear() {
if (!rb)
return;
//should be stopped at this point but just in case
if (rb) {
memdelete_arr(rb);
memdelete_arr(read_buf);
}
rb = NULL;
offset = 0;
rb_read_pos = 0;
rb_write_pos = 0;
read_buf = NULL;
}
AudioRBResampler::AudioRBResampler() {
rb = NULL;
offset = 0;
read_buf = NULL;
rb_read_pos = 0;
rb_write_pos = 0;
rb_bits = 0;
rb_len = 0;
rb_mask = 0;
read_buff_len = 0;
channels = 0;
src_mix_rate = 0;
target_mix_rate = 0;
}
AudioRBResampler::~AudioRBResampler() {
if (rb) {
memdelete_arr(rb);
memdelete_arr(read_buf);
}
}
|
Remove comments and corrected code, which exists for correctness but will likely never be used. Fixes #20362
|
Remove comments and corrected code, which exists for correctness but will likely never be used. Fixes #20362
|
C++
|
mit
|
akien-mga/godot,groud/godot,vkbsb/godot,ex/godot,vnen/godot,DmitriySalnikov/godot,Paulloz/godot,Paulloz/godot,vnen/godot,ZuBsPaCe/godot,firefly2442/godot,ex/godot,Valentactive/godot,okamstudio/godot,groud/godot,Shockblast/godot,akien-mga/godot,akien-mga/godot,sanikoyes/godot,Paulloz/godot,godotengine/godot,BastiaanOlij/godot,Paulloz/godot,Shockblast/godot,pkowal1982/godot,okamstudio/godot,MarianoGnu/godot,MarianoGnu/godot,groud/godot,okamstudio/godot,guilhermefelipecgs/godot,Faless/godot,akien-mga/godot,DmitriySalnikov/godot,godotengine/godot,DmitriySalnikov/godot,sanikoyes/godot,ex/godot,akien-mga/godot,MarianoGnu/godot,firefly2442/godot,Shockblast/godot,ex/godot,vnen/godot,godotengine/godot,BastiaanOlij/godot,josempans/godot,vkbsb/godot,sanikoyes/godot,guilhermefelipecgs/godot,vkbsb/godot,guilhermefelipecgs/godot,groud/godot,pkowal1982/godot,honix/godot,Valentactive/godot,MarianoGnu/godot,guilhermefelipecgs/godot,vkbsb/godot,Valentactive/godot,godotengine/godot,groud/godot,sanikoyes/godot,Zylann/godot,Paulloz/godot,guilhermefelipecgs/godot,honix/godot,guilhermefelipecgs/godot,okamstudio/godot,josempans/godot,pkowal1982/godot,BastiaanOlij/godot,MarianoGnu/godot,Valentactive/godot,ZuBsPaCe/godot,sanikoyes/godot,okamstudio/godot,honix/godot,ZuBsPaCe/godot,Valentactive/godot,Faless/godot,Faless/godot,Shockblast/godot,honix/godot,DmitriySalnikov/godot,firefly2442/godot,okamstudio/godot,vkbsb/godot,josempans/godot,BastiaanOlij/godot,firefly2442/godot,firefly2442/godot,MarianoGnu/godot,BastiaanOlij/godot,Zylann/godot,firefly2442/godot,BastiaanOlij/godot,Faless/godot,akien-mga/godot,Valentactive/godot,sanikoyes/godot,ZuBsPaCe/godot,ex/godot,ex/godot,ZuBsPaCe/godot,Faless/godot,godotengine/godot,BastiaanOlij/godot,vnen/godot,vnen/godot,Zylann/godot,ex/godot,honix/godot,MarianoGnu/godot,vnen/godot,Faless/godot,okamstudio/godot,MarianoGnu/godot,vkbsb/godot,pkowal1982/godot,Paulloz/godot,akien-mga/godot,vnen/godot,sanikoyes/godot,Faless/godot,ex/godot,groud/godot,akien-mga/godot,honix/godot,firefly2442/godot,josempans/godot,firefly2442/godot,Paulloz/godot,godotengine/godot,vkbsb/godot,pkowal1982/godot,Zylann/godot,DmitriySalnikov/godot,Shockblast/godot,Shockblast/godot,okamstudio/godot,Faless/godot,Shockblast/godot,DmitriySalnikov/godot,godotengine/godot,pkowal1982/godot,vkbsb/godot,Valentactive/godot,vnen/godot,guilhermefelipecgs/godot,ZuBsPaCe/godot,josempans/godot,Valentactive/godot,Shockblast/godot,BastiaanOlij/godot,Zylann/godot,josempans/godot,sanikoyes/godot,pkowal1982/godot,josempans/godot,ZuBsPaCe/godot,godotengine/godot,guilhermefelipecgs/godot,Zylann/godot,DmitriySalnikov/godot,Zylann/godot,okamstudio/godot,okamstudio/godot,Zylann/godot,ZuBsPaCe/godot,josempans/godot,pkowal1982/godot
|
73572b3c8c2064c082d43980e8f46562a9387a11
|
webkit/tools/test_shell/test_shell_platform_delegate_win.cc
|
webkit/tools/test_shell/test_shell_platform_delegate_win.cc
|
// Copyright (c) 2006-2009 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 <string>
#include <list>
#include <windows.h>
#include <commctrl.h>
#include "base/command_line.h"
#include "base/event_recorder.h"
#include "base/gfx/native_theme.h"
#include "base/resource_util.h"
#include "base/win_util.h"
#include "webkit/tools/test_shell/foreground_helper.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_platform_delegate.h"
TestShellPlatformDelegate::TestShellPlatformDelegate(
const CommandLine& command_line)
: command_line_(command_line) {
#ifdef _CRTDBG_MAP_ALLOC
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
#endif
}
TestShellPlatformDelegate::~TestShellPlatformDelegate() {
#ifdef _CRTDBG_MAP_ALLOC
_CrtDumpMemoryLeaks();
#endif
}
void TestShellPlatformDelegate::PreflightArgs(int *argc, char ***argv) {
}
// This test approximates whether you are running the default themes for
// your platform by inspecting a couple of metrics.
// It does not catch all cases, but it does pick up on classic vs xp,
// and normal vs large fonts. Something it misses is changes to the color
// scheme (which will infact cause pixel test failures).
bool TestShellPlatformDelegate::CheckLayoutTestSystemDependencies() {
std::list<std::string> errors;
OSVERSIONINFOEX osvi;
::ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
::GetVersionEx((OSVERSIONINFO *)&osvi);
// default to XP metrics, override if on Vista
int requiredVScrollSize = 17;
int requiredFontSize = -11; // 8 pt
const WCHAR *requiredFont = L"Tahoma";
bool isVista = false;
if (osvi.dwMajorVersion == 6
&& osvi.dwMinorVersion == 0
&& osvi.wProductType == VER_NT_WORKSTATION) {
requiredFont = L"Segoe UI";
requiredFontSize = -12; // 9 pt
isVista = true;
} else if (osvi.dwMajorVersion == 5
&& osvi.dwMinorVersion == 1
&& osvi.wProductType == VER_NT_WORKSTATION) {
// XP;
} else {
errors.push_back("Unsupported Operating System version "
"(must use XP or Vista)");
}
// on both XP and Vista, this metric will be 17 when font size is "Normal".
// The size of drop-down menus depends on it.
int vScrollSize = ::GetSystemMetrics(SM_CXVSCROLL);
if (vScrollSize != requiredVScrollSize) {
errors.push_back("Must use normal size fonts (96 dpi)");
}
// font smoothing (including ClearType) must be disabled
BOOL bFontSmoothing;
SystemParametersInfo(SPI_GETFONTSMOOTHING, (UINT)0,
(PVOID)&bFontSmoothing, (UINT)0);
if (bFontSmoothing) {
errors.push_back("Font smoothing (ClearType) must be disabled");
}
// Check that we're using the default system fonts
NONCLIENTMETRICS metrics;
win_util::GetNonClientMetrics(&metrics);
LOGFONTW* system_fonts[] =
{ &metrics.lfStatusFont, &metrics.lfMenuFont, &metrics.lfSmCaptionFont };
for (size_t i = 0; i < arraysize(system_fonts); ++i) {
if (system_fonts[i]->lfHeight != requiredFontSize ||
wcscmp(requiredFont, system_fonts[i]->lfFaceName)) {
if (isVista)
errors.push_back("Must use either the Aero or Basic theme");
else
errors.push_back("Must use the default XP theme (Luna)");
break;
}
}
if (!errors.empty()) {
fprintf(stderr, "%s",
"##################################################################\n"
"## Layout test system dependencies check failed.\n"
"##\n");
for (std::list<std::string>::iterator it = errors.begin();
it != errors.end();
++it) {
fprintf(stderr, "## %s\n", it->c_str());
}
fprintf(stderr, "%s",
"##\n"
"##################################################################\n");
}
return errors.empty();
}
void TestShellPlatformDelegate::SuppressErrorReporting() {
_set_abort_behavior(0, _WRITE_ABORT_MSG);
}
void TestShellPlatformDelegate::InitializeGUI() {
INITCOMMONCONTROLSEX InitCtrlEx;
InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX);
InitCtrlEx.dwICC = ICC_STANDARD_CLASSES;
InitCommonControlsEx(&InitCtrlEx);
TestShell::RegisterWindowClass();
}
void TestShellPlatformDelegate::SelectUnifiedTheme() {
gfx::NativeTheme::instance()->DisableTheming();
}
void TestShellPlatformDelegate::SetWindowPositionForRecording(
TestShell *shell) {
// Move the window to the upper left corner for consistent
// record/playback mode. For automation, we want this to work
// on build systems where the script invoking us is a background
// process. So for this case, make our window the topmost window
// as well.
ForegroundHelper::SetForeground(shell->mainWnd());
::SetWindowPos(shell->mainWnd(), HWND_TOP, 0, 0, 600, 800, 0);
}
|
// Copyright (c) 2006-2009 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 <string>
#include <list>
#include <windows.h>
#include <commctrl.h>
#include "base/command_line.h"
#include "base/event_recorder.h"
#include "base/gfx/native_theme.h"
#include "base/resource_util.h"
#include "base/win_util.h"
#include "webkit/tools/test_shell/foreground_helper.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_platform_delegate.h"
TestShellPlatformDelegate::TestShellPlatformDelegate(
const CommandLine& command_line)
: command_line_(command_line) {
#ifdef _CRTDBG_MAP_ALLOC
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
#endif
}
TestShellPlatformDelegate::~TestShellPlatformDelegate() {
#ifdef _CRTDBG_MAP_ALLOC
_CrtDumpMemoryLeaks();
#endif
}
void TestShellPlatformDelegate::PreflightArgs(int *argc, char ***argv) {
}
// This test approximates whether you are running the default themes for
// your platform by inspecting a couple of metrics.
// It does not catch all cases, but it does pick up on classic vs xp,
// and normal vs large fonts. Something it misses is changes to the color
// scheme (which will infact cause pixel test failures).
bool TestShellPlatformDelegate::CheckLayoutTestSystemDependencies() {
std::list<std::string> errors;
OSVERSIONINFOEX osvi;
::ZeroMemory(&osvi, sizeof(OSVERSIONINFOEX));
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX);
::GetVersionEx((OSVERSIONINFO *)&osvi);
// default to XP metrics, override if on Vista
int requiredVScrollSize = 17;
int requiredFontSize = -11; // 8 pt
const WCHAR *requiredFont = L"Tahoma";
bool isVista = false;
if (osvi.dwMajorVersion == 6
&& osvi.dwMinorVersion == 0
&& osvi.wProductType == VER_NT_WORKSTATION) {
requiredFont = L"Segoe UI";
requiredFontSize = -12; // 9 pt
isVista = true;
} else if (osvi.dwMajorVersion == 5
&& osvi.dwMinorVersion == 1
&& osvi.wProductType == VER_NT_WORKSTATION) {
// XP;
} else {
errors.push_back("Unsupported Operating System version "
"(must use XP or Vista).");
}
// on both XP and Vista, this metric will be 17 when font size is "Normal".
// The size of drop-down menus depends on it.
int vScrollSize = ::GetSystemMetrics(SM_CXVSCROLL);
if (vScrollSize != requiredVScrollSize) {
errors.push_back("Must use normal size fonts (96 dpi).");
}
// ClearType must be disabled, because the rendering is unpredictable.
BOOL bFontSmoothing;
SystemParametersInfo(SPI_GETFONTSMOOTHING, (UINT)0,
(PVOID)&bFontSmoothing, (UINT)0);
int fontSmoothingType;
SystemParametersInfo(SPI_GETFONTSMOOTHINGTYPE, (UINT)0,
(PVOID)&fontSmoothingType, (UINT)0);
if (bFontSmoothing && (fontSmoothingType == FE_FONTSMOOTHINGCLEARTYPE)) {
errors.push_back("ClearType must be disabled.");
}
// Check that we're using the default system fonts
NONCLIENTMETRICS metrics;
win_util::GetNonClientMetrics(&metrics);
LOGFONTW* system_fonts[] =
{ &metrics.lfStatusFont, &metrics.lfMenuFont, &metrics.lfSmCaptionFont };
for (size_t i = 0; i < arraysize(system_fonts); ++i) {
if (system_fonts[i]->lfHeight != requiredFontSize ||
wcscmp(requiredFont, system_fonts[i]->lfFaceName)) {
if (isVista)
errors.push_back("Must use either the Aero or Basic theme.");
else
errors.push_back("Must use the default XP theme (Luna).");
break;
}
}
if (!errors.empty()) {
fprintf(stderr, "%s",
"##################################################################\n"
"## Layout test system dependencies check failed.\n"
"##\n");
for (std::list<std::string>::iterator it = errors.begin();
it != errors.end();
++it) {
fprintf(stderr, "## %s\n", it->c_str());
}
fprintf(stderr, "%s",
"##\n"
"##################################################################\n");
}
return errors.empty();
}
void TestShellPlatformDelegate::SuppressErrorReporting() {
_set_abort_behavior(0, _WRITE_ABORT_MSG);
}
void TestShellPlatformDelegate::InitializeGUI() {
INITCOMMONCONTROLSEX InitCtrlEx;
InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX);
InitCtrlEx.dwICC = ICC_STANDARD_CLASSES;
InitCommonControlsEx(&InitCtrlEx);
TestShell::RegisterWindowClass();
}
void TestShellPlatformDelegate::SelectUnifiedTheme() {
gfx::NativeTheme::instance()->DisableTheming();
}
void TestShellPlatformDelegate::SetWindowPositionForRecording(
TestShell *shell) {
// Move the window to the upper left corner for consistent
// record/playback mode. For automation, we want this to work
// on build systems where the script invoking us is a background
// process. So for this case, make our window the topmost window
// as well.
ForegroundHelper::SetForeground(shell->mainWnd());
::SetWindowPos(shell->mainWnd(), HWND_TOP, 0, 0, 600, 800, 0);
}
|
Modify change in CL 21434 - allow standard font smoothing as well as none
|
Modify change in CL 21434 - allow standard font smoothing as well as none
Prior to CL 21434 test_shell did not actually check if ClearType was
disabled. I had thought that the requirement for the layout tests was
that *all* font smoothing was disabled (both ClearType and standard). Turns
out that standard is okay, so I am reenabling it here.
Note that CL 21434 was really just a re-reverting of 21368.
TEST=none
BUG=none
[email protected]
Review URL: http://codereview.chromium.org/160082
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@21568 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
Crystalnix/house-of-life-chromium,adobe/chromium,adobe/chromium,adobe/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,ropik/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,yitian134/chromium,adobe/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,ropik/chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium,yitian134/chromium,gavinp/chromium,adobe/chromium,gavinp/chromium,adobe/chromium,ropik/chromium,yitian134/chromium,ropik/chromium,yitian134/chromium,ropik/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,ropik/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,yitian134/chromium,yitian134/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,ropik/chromium,Crystalnix/house-of-life-chromium
|
0da73a3d52bb2a59e848246367aa92ab887b9c73
|
chrome/browser/ui/views/ash/tab_scrubber.cc
|
chrome/browser/ui/views/ash/tab_scrubber.cc
|
// Copyright (c) 2013 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/views/ash/tab_scrubber.h"
#include "ash/shell.h"
#include "ash/wm/window_util.h"
#include "base/metrics/histogram.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/immersive_mode_controller.h"
#include "chrome/browser/ui/views/tabs/tab.h"
#include "chrome/browser/ui/views/tabs/tab_strip.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_source.h"
#include "ui/aura/window.h"
#include "ui/base/events/event.h"
#include "ui/base/events/event_utils.h"
#include "ui/base/gestures/gesture_configuration.h"
#include "ui/views/controls/glow_hover_controller.h"
namespace {
const int64 kActivationDelayMS = 200;
const int64 kCancelImmersiveRevelDelayMS = 200;
}
// static
TabScrubber* TabScrubber::GetInstance() {
static TabScrubber* instance = NULL;
if (!instance)
instance = new TabScrubber();
return instance;
}
// static
gfx::Point TabScrubber::GetStartPoint(
TabStrip* tab_strip,
int index,
TabScrubber::Direction direction) {
int initial_tab_offset = Tab::GetMiniWidth() / 2;
gfx::Rect tab_bounds = tab_strip->tab_at(index)->bounds();
float x = direction == LEFT ?
tab_bounds.x() + initial_tab_offset :
tab_bounds.right() - initial_tab_offset;
return gfx::Point(x, tab_bounds.CenterPoint().y());
}
bool TabScrubber::IsActivationPending() {
return activate_timer_.IsRunning();
}
TabScrubber::TabScrubber()
: scrubbing_(false),
browser_(NULL),
swipe_x_(-1),
swipe_y_(-1),
swipe_direction_(LEFT),
highlighted_tab_(-1),
activate_timer_(true, false),
activation_delay_(kActivationDelayMS),
use_default_activation_delay_(true),
should_cancel_immersive_reveal_(false),
weak_ptr_factory_(this) {
ash::Shell::GetInstance()->AddPreTargetHandler(this);
registrar_.Add(
this,
chrome::NOTIFICATION_BROWSER_CLOSING,
content::NotificationService::AllSources());
}
TabScrubber::~TabScrubber() {
// Note: The weak_ptr_factory_ should invalidate its weak pointers before
// any other members are destroyed.
weak_ptr_factory_.InvalidateWeakPtrs();
}
void TabScrubber::OnScrollEvent(ui::ScrollEvent* event) {
if (event->type() == ui::ET_SCROLL_FLING_CANCEL ||
event->type() == ui::ET_SCROLL_FLING_START) {
FinishScrub(true);
CancelImmersiveReveal();
return;
}
if (event->finger_count() != 3)
return;
Browser* browser = GetActiveBrowser();
if (!browser || (scrubbing_ && browser_ && browser != browser_) ||
(highlighted_tab_ != -1 &&
highlighted_tab_ >= browser->tab_strip_model()->count())) {
FinishScrub(false);
return;
}
BrowserView* browser_view =
BrowserView::GetBrowserViewForNativeWindow(
browser->window()->GetNativeWindow());
TabStrip* tab_strip = browser_view->tabstrip();
if (tab_strip->IsAnimating()) {
FinishScrub(false);
return;
}
// We are handling the event.
event->StopPropagation();
float x_offset = event->x_offset();
if (!ui::IsNaturalScrollEnabled())
x_offset = -x_offset;
int last_tab_index = highlighted_tab_ == -1 ?
browser->tab_strip_model()->active_index() : highlighted_tab_;
if (!scrubbing_) {
swipe_direction_ = (x_offset < 0) ? LEFT : RIGHT;
const gfx::Point start_point =
GetStartPoint(tab_strip,
browser->tab_strip_model()->active_index(),
swipe_direction_);
browser_ = browser;
scrubbing_ = true;
swipe_x_ = start_point.x();
swipe_y_ = start_point.y();
ImmersiveModeController* immersive_controller =
browser_view->immersive_mode_controller();
if (immersive_controller->enabled() &&
!immersive_controller->IsRevealed()) {
immersive_controller->MaybeStartReveal();
should_cancel_immersive_reveal_ = true;
}
tab_strip->AddObserver(this);
} else if (highlighted_tab_ == -1) {
Direction direction = (x_offset < 0) ? LEFT : RIGHT;
if (direction != swipe_direction_) {
const gfx::Point start_point =
GetStartPoint(tab_strip,
browser->tab_strip_model()->active_index(),
direction);
swipe_x_ = start_point.x();
swipe_y_ = start_point.y();
swipe_direction_ = direction;
}
}
swipe_x_ += x_offset;
Tab* first_tab = tab_strip->tab_at(0);
int first_tab_center = first_tab->bounds().CenterPoint().x();
Tab* last_tab = tab_strip->tab_at(tab_strip->tab_count() - 1);
int last_tab_tab_center = last_tab->bounds().CenterPoint().x();
if (swipe_x_ < first_tab_center)
swipe_x_ = first_tab_center;
if (swipe_x_ > last_tab_tab_center)
swipe_x_ = last_tab_tab_center;
Tab* initial_tab = tab_strip->tab_at(last_tab_index);
gfx::Point tab_point(swipe_x_, swipe_y_);
views::View::ConvertPointToTarget(tab_strip, initial_tab, &tab_point);
Tab* new_tab = tab_strip->GetTabAt(initial_tab, tab_point);
if (!new_tab)
return;
int new_index = tab_strip->GetModelIndexOfTab(new_tab);
if (highlighted_tab_ == -1 &&
new_index == browser->tab_strip_model()->active_index())
return;
if (new_index != highlighted_tab_) {
if (activate_timer_.IsRunning()) {
activate_timer_.Reset();
} else {
int delay = use_default_activation_delay_ ?
ui::GestureConfiguration::tab_scrub_activation_delay_in_ms() :
activation_delay_;
if (delay >= 0) {
activate_timer_.Start(FROM_HERE,
base::TimeDelta::FromMilliseconds(delay),
base::Bind(&TabScrubber::FinishScrub,
weak_ptr_factory_.GetWeakPtr(),
true));
}
}
if (highlighted_tab_ != -1) {
Tab* tab = tab_strip->tab_at(highlighted_tab_);
tab->hover_controller()->HideImmediately();
}
if (new_index == browser->tab_strip_model()->active_index()) {
highlighted_tab_ = -1;
} else {
highlighted_tab_ = new_index;
new_tab->hover_controller()->Show(views::GlowHoverController::PRONOUNCED);
}
}
if (highlighted_tab_ != -1) {
gfx::Point hover_point(swipe_x_, swipe_y_);
views::View::ConvertPointToTarget(tab_strip, new_tab, &hover_point);
new_tab->hover_controller()->SetLocation(hover_point);
}
}
void TabScrubber::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
if (content::Source<Browser>(source).ptr() == browser_)
FinishScrub(false);
browser_ = NULL;
}
void TabScrubber::TabStripAddedTabAt(TabStrip* tab_strip, int index) {
if (highlighted_tab_ == -1)
return;
if (index < highlighted_tab_)
++highlighted_tab_;
}
void TabScrubber::TabStripMovedTab(TabStrip* tab_strip,
int from_index,
int to_index) {
if (highlighted_tab_ == -1)
return;
if (from_index == highlighted_tab_)
highlighted_tab_ = to_index;
else if (from_index < highlighted_tab_&& highlighted_tab_<= to_index)
--highlighted_tab_;
else if (from_index > highlighted_tab_ && highlighted_tab_ >= to_index)
++highlighted_tab_;
}
void TabScrubber::TabStripRemovedTabAt(TabStrip* tab_strip, int index) {
if (highlighted_tab_ == -1)
return;
if (index == highlighted_tab_) {
FinishScrub(false);
return;
}
if (index < highlighted_tab_)
--highlighted_tab_;
}
void TabScrubber::TabStripDeleted(TabStrip* tab_strip) {
if (highlighted_tab_ == -1)
return;
}
Browser* TabScrubber::GetActiveBrowser() {
aura::Window* active_window = ash::wm::GetActiveWindow();
if (!active_window)
return NULL;
Browser* browser = chrome::FindBrowserWithWindow(active_window);
if (!browser || browser->type() != Browser::TYPE_TABBED)
return NULL;
return browser;
}
void TabScrubber::FinishScrub(bool activate) {
activate_timer_.Stop();
if (browser_ && browser_->window()) {
BrowserView* browser_view =
BrowserView::GetBrowserViewForNativeWindow(
browser_->window()->GetNativeWindow());
TabStrip* tab_strip = browser_view->tabstrip();
if (activate && highlighted_tab_ != -1) {
Tab* tab = tab_strip->tab_at(highlighted_tab_);
tab->hover_controller()->HideImmediately();
int distance =
std::abs(
highlighted_tab_ - browser_->tab_strip_model()->active_index());
UMA_HISTOGRAM_CUSTOM_COUNTS("TabScrubber.Distance", distance, 0, 20, 20);
browser_->tab_strip_model()->ActivateTabAt(highlighted_tab_, true);
}
tab_strip->RemoveObserver(this);
}
swipe_x_ = -1;
swipe_y_ = -1;
scrubbing_ = false;
highlighted_tab_ = -1;
}
void TabScrubber::CancelImmersiveReveal() {
if (browser_ && should_cancel_immersive_reveal_) {
BrowserView* browser_view =
BrowserView::GetBrowserViewForNativeWindow(
browser_->window()->GetNativeWindow());
browser_view->immersive_mode_controller()->CancelReveal();
}
should_cancel_immersive_reveal_ = false;
}
|
// Copyright (c) 2013 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/views/ash/tab_scrubber.h"
#include "ash/shell.h"
#include "ash/wm/window_util.h"
#include "base/metrics/histogram.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/immersive_mode_controller.h"
#include "chrome/browser/ui/views/tabs/tab.h"
#include "chrome/browser/ui/views/tabs/tab_strip.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_source.h"
#include "ui/aura/window.h"
#include "ui/base/events/event.h"
#include "ui/base/events/event_utils.h"
#include "ui/base/gestures/gesture_configuration.h"
#include "ui/views/controls/glow_hover_controller.h"
namespace {
const int64 kActivationDelayMS = 200;
const int64 kCancelImmersiveRevelDelayMS = 200;
}
// static
TabScrubber* TabScrubber::GetInstance() {
static TabScrubber* instance = NULL;
if (!instance)
instance = new TabScrubber();
return instance;
}
// static
gfx::Point TabScrubber::GetStartPoint(
TabStrip* tab_strip,
int index,
TabScrubber::Direction direction) {
int initial_tab_offset = Tab::GetMiniWidth() / 2;
gfx::Rect tab_bounds = tab_strip->tab_at(index)->bounds();
float x = direction == LEFT ?
tab_bounds.x() + initial_tab_offset :
tab_bounds.right() - initial_tab_offset;
return gfx::Point(x, tab_bounds.CenterPoint().y());
}
bool TabScrubber::IsActivationPending() {
return activate_timer_.IsRunning();
}
TabScrubber::TabScrubber()
: scrubbing_(false),
browser_(NULL),
swipe_x_(-1),
swipe_y_(-1),
swipe_direction_(LEFT),
highlighted_tab_(-1),
activate_timer_(true, false),
activation_delay_(kActivationDelayMS),
use_default_activation_delay_(true),
should_cancel_immersive_reveal_(false),
weak_ptr_factory_(this) {
ash::Shell::GetInstance()->AddPreTargetHandler(this);
registrar_.Add(
this,
chrome::NOTIFICATION_BROWSER_CLOSING,
content::NotificationService::AllSources());
}
TabScrubber::~TabScrubber() {
// Note: The weak_ptr_factory_ should invalidate its weak pointers before
// any other members are destroyed.
weak_ptr_factory_.InvalidateWeakPtrs();
}
void TabScrubber::OnScrollEvent(ui::ScrollEvent* event) {
if (event->type() == ui::ET_SCROLL_FLING_CANCEL ||
event->type() == ui::ET_SCROLL_FLING_START) {
FinishScrub(true);
CancelImmersiveReveal();
return;
}
if (event->finger_count() != 3)
return;
Browser* browser = GetActiveBrowser();
if (!browser || (scrubbing_ && browser_ && browser != browser_) ||
(highlighted_tab_ != -1 &&
highlighted_tab_ >= browser->tab_strip_model()->count())) {
FinishScrub(false);
return;
}
BrowserView* browser_view =
BrowserView::GetBrowserViewForNativeWindow(
browser->window()->GetNativeWindow());
TabStrip* tab_strip = browser_view->tabstrip();
if (tab_strip->IsAnimating()) {
FinishScrub(false);
return;
}
// We are handling the event.
event->StopPropagation();
float x_offset = event->x_offset();
if (!ui::IsNaturalScrollEnabled())
x_offset = -x_offset;
int last_tab_index = highlighted_tab_ == -1 ?
browser->tab_strip_model()->active_index() : highlighted_tab_;
if (!scrubbing_) {
swipe_direction_ = (x_offset < 0) ? LEFT : RIGHT;
const gfx::Point start_point =
GetStartPoint(tab_strip,
browser->tab_strip_model()->active_index(),
swipe_direction_);
browser_ = browser;
scrubbing_ = true;
swipe_x_ = start_point.x();
swipe_y_ = start_point.y();
ImmersiveModeController* immersive_controller =
browser_view->immersive_mode_controller();
if (immersive_controller->enabled() &&
!immersive_controller->IsRevealed()) {
immersive_controller->MaybeStartReveal();
should_cancel_immersive_reveal_ = true;
}
tab_strip->AddObserver(this);
} else if (highlighted_tab_ == -1) {
Direction direction = (x_offset < 0) ? LEFT : RIGHT;
if (direction != swipe_direction_) {
const gfx::Point start_point =
GetStartPoint(tab_strip,
browser->tab_strip_model()->active_index(),
direction);
swipe_x_ = start_point.x();
swipe_y_ = start_point.y();
swipe_direction_ = direction;
}
}
swipe_x_ += x_offset;
Tab* first_tab = tab_strip->tab_at(0);
int first_tab_center = first_tab->bounds().CenterPoint().x();
Tab* last_tab = tab_strip->tab_at(tab_strip->tab_count() - 1);
int last_tab_tab_center = last_tab->bounds().CenterPoint().x();
if (swipe_x_ < first_tab_center)
swipe_x_ = first_tab_center;
if (swipe_x_ > last_tab_tab_center)
swipe_x_ = last_tab_tab_center;
Tab* initial_tab = tab_strip->tab_at(last_tab_index);
gfx::Point tab_point(swipe_x_, swipe_y_);
views::View::ConvertPointToTarget(tab_strip, initial_tab, &tab_point);
Tab* new_tab = tab_strip->GetTabAt(initial_tab, tab_point);
if (!new_tab)
return;
int new_index = tab_strip->GetModelIndexOfTab(new_tab);
if (highlighted_tab_ == -1 &&
new_index == browser->tab_strip_model()->active_index())
return;
if (new_index != highlighted_tab_) {
if (activate_timer_.IsRunning()) {
activate_timer_.Reset();
} else {
int delay = use_default_activation_delay_ ?
ui::GestureConfiguration::tab_scrub_activation_delay_in_ms() :
activation_delay_;
if (delay >= 0) {
activate_timer_.Start(FROM_HERE,
base::TimeDelta::FromMilliseconds(delay),
base::Bind(&TabScrubber::FinishScrub,
weak_ptr_factory_.GetWeakPtr(),
true));
}
}
if (highlighted_tab_ != -1) {
Tab* tab = tab_strip->tab_at(highlighted_tab_);
tab->hover_controller()->HideImmediately();
}
if (new_index == browser->tab_strip_model()->active_index()) {
highlighted_tab_ = -1;
} else {
highlighted_tab_ = new_index;
new_tab->hover_controller()->Show(views::GlowHoverController::PRONOUNCED);
}
}
if (highlighted_tab_ != -1) {
gfx::Point hover_point(swipe_x_, swipe_y_);
views::View::ConvertPointToTarget(tab_strip, new_tab, &hover_point);
new_tab->hover_controller()->SetLocation(hover_point);
}
}
void TabScrubber::Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
if (content::Source<Browser>(source).ptr() == browser_)
FinishScrub(false);
browser_ = NULL;
}
void TabScrubber::TabStripAddedTabAt(TabStrip* tab_strip, int index) {
if (highlighted_tab_ == -1)
return;
if (index < highlighted_tab_)
++highlighted_tab_;
}
void TabScrubber::TabStripMovedTab(TabStrip* tab_strip,
int from_index,
int to_index) {
if (highlighted_tab_ == -1)
return;
if (from_index == highlighted_tab_)
highlighted_tab_ = to_index;
else if (from_index < highlighted_tab_&& highlighted_tab_<= to_index)
--highlighted_tab_;
else if (from_index > highlighted_tab_ && highlighted_tab_ >= to_index)
++highlighted_tab_;
}
void TabScrubber::TabStripRemovedTabAt(TabStrip* tab_strip, int index) {
if (highlighted_tab_ == -1)
return;
if (index == highlighted_tab_) {
FinishScrub(false);
return;
}
if (index < highlighted_tab_)
--highlighted_tab_;
}
void TabScrubber::TabStripDeleted(TabStrip* tab_strip) {
if (highlighted_tab_ == -1)
return;
}
Browser* TabScrubber::GetActiveBrowser() {
aura::Window* active_window = ash::wm::GetActiveWindow();
if (!active_window)
return NULL;
Browser* browser = chrome::FindBrowserWithWindow(active_window);
if (!browser || browser->type() != Browser::TYPE_TABBED)
return NULL;
return browser;
}
void TabScrubber::FinishScrub(bool activate) {
activate_timer_.Stop();
if (browser_ && browser_->window()) {
BrowserView* browser_view =
BrowserView::GetBrowserViewForNativeWindow(
browser_->window()->GetNativeWindow());
TabStrip* tab_strip = browser_view->tabstrip();
if (activate && highlighted_tab_ != -1) {
Tab* tab = tab_strip->tab_at(highlighted_tab_);
tab->hover_controller()->HideImmediately();
int distance =
std::abs(
highlighted_tab_ - browser_->tab_strip_model()->active_index());
UMA_HISTOGRAM_CUSTOM_COUNTS("Tabs.ScrubDistance", distance, 0, 20, 20);
browser_->tab_strip_model()->ActivateTabAt(highlighted_tab_, true);
}
tab_strip->RemoveObserver(this);
}
swipe_x_ = -1;
swipe_y_ = -1;
scrubbing_ = false;
highlighted_tab_ = -1;
}
void TabScrubber::CancelImmersiveReveal() {
if (browser_ && should_cancel_immersive_reveal_) {
BrowserView* browser_view =
BrowserView::GetBrowserViewForNativeWindow(
browser_->window()->GetNativeWindow());
browser_view->immersive_mode_controller()->CancelReveal();
}
should_cancel_immersive_reveal_ = false;
}
|
Change UMA stat name for TabScrub.Distance so that it shares a group with other metrics
|
Change UMA stat name for TabScrub.Distance so that it shares a group with other metrics
BUG=None
TEST=None
TBR=sky
Review URL: https://codereview.chromium.org/12374058
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@185622 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,anirudhSK/chromium,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,hujiajie/pa-chromium,dushu1203/chromium.src,timopulkkinen/BubbleFish,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,dednal/chromium.src,pozdnyakov/chromium-crosswalk,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,Chilledheart/chromium,anirudhSK/chromium,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,dednal/chromium.src,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,anirudhSK/chromium,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,ltilve/chromium,Chilledheart/chromium,Jonekee/chromium.src,Fireblend/chromium-crosswalk,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,Chilledheart/chromium,jaruba/chromium.src,hujiajie/pa-chromium,Fireblend/chromium-crosswalk,ltilve/chromium,pozdnyakov/chromium-crosswalk,ondra-novak/chromium.src,pozdnyakov/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hujiajie/pa-chromium,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,TheTypoMaster/chromium-crosswalk,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,Fireblend/chromium-crosswalk,patrickm/chromium.src,jaruba/chromium.src,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,Jonekee/chromium.src,M4sse/chromium.src,ondra-novak/chromium.src,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,M4sse/chromium.src,anirudhSK/chromium,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,littlstar/chromium.src,littlstar/chromium.src,Just-D/chromium-1,ltilve/chromium,dednal/chromium.src,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,axinging/chromium-crosswalk,Just-D/chromium-1,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,littlstar/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,ChromiumWebApps/chromium,axinging/chromium-crosswalk,patrickm/chromium.src,hujiajie/pa-chromium,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,timopulkkinen/BubbleFish,littlstar/chromium.src,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk,littlstar/chromium.src,Chilledheart/chromium,littlstar/chromium.src,littlstar/chromium.src,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,jaruba/chromium.src,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,patrickm/chromium.src,Just-D/chromium-1,Jonekee/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,jaruba/chromium.src,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,timopulkkinen/BubbleFish,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,M4sse/chromium.src,mogoweb/chromium-crosswalk,ondra-novak/chromium.src,ltilve/chromium,TheTypoMaster/chromium-crosswalk,timopulkkinen/BubbleFish,dednal/chromium.src,M4sse/chromium.src,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,Just-D/chromium-1,patrickm/chromium.src,dednal/chromium.src,Jonekee/chromium.src,Chilledheart/chromium,dushu1203/chromium.src,mogoweb/chromium-crosswalk,hujiajie/pa-chromium,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,ltilve/chromium,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,Just-D/chromium-1,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,anirudhSK/chromium,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,krieger-od/nwjs_chromium.src,chuan9/chromium-crosswalk,patrickm/chromium.src,M4sse/chromium.src,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,dushu1203/chromium.src,ondra-novak/chromium.src,ChromiumWebApps/chromium,markYoungH/chromium.src,hgl888/chromium-crosswalk,M4sse/chromium.src,patrickm/chromium.src,bright-sparks/chromium-spacewalk,anirudhSK/chromium,ltilve/chromium,Just-D/chromium-1,M4sse/chromium.src,markYoungH/chromium.src,mogoweb/chromium-crosswalk,jaruba/chromium.src,ltilve/chromium,Fireblend/chromium-crosswalk,patrickm/chromium.src,timopulkkinen/BubbleFish,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,anirudhSK/chromium,ChromiumWebApps/chromium,Just-D/chromium-1,Fireblend/chromium-crosswalk,jaruba/chromium.src,Fireblend/chromium-crosswalk,markYoungH/chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,anirudhSK/chromium,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,dushu1203/chromium.src,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,chuan9/chromium-crosswalk,dednal/chromium.src,krieger-od/nwjs_chromium.src,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,hujiajie/pa-chromium,dednal/chromium.src,ondra-novak/chromium.src,jaruba/chromium.src,hujiajie/pa-chromium,hujiajie/pa-chromium,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,hujiajie/pa-chromium,hujiajie/pa-chromium,dednal/chromium.src,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,anirudhSK/chromium,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,timopulkkinen/BubbleFish,Jonekee/chromium.src,timopulkkinen/BubbleFish,dushu1203/chromium.src,mogoweb/chromium-crosswalk,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,Chilledheart/chromium,axinging/chromium-crosswalk,axinging/chromium-crosswalk,hujiajie/pa-chromium,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,markYoungH/chromium.src,M4sse/chromium.src,krieger-od/nwjs_chromium.src,bright-sparks/chromium-spacewalk,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ltilve/chromium,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk
|
ffd00f3d0f1b7536439f0b4afd71b338e94acafb
|
test-data.cpp
|
test-data.cpp
|
#include "data-general.hpp"
#include "data-course.hpp"
#include "data-major.hpp"
#include "data-student.hpp"
using namespace std;
vector<Course> all_courses;
void loadCourses() {
ifstream infile("data/2012-13-s2-csv.csv");
string str; // read in the header line
getline(infile, str);
while (infile.peek() != -1){
Course incourse(infile);
all_courses.push_back(incourse);
// cout << incourse << endl;
}
}
void whatDidICallThisWith(int argc, const char *argv[]) {
int count;
printf ("This program was called with \"%s\".\n",argv[0]);
if (argc > 1) {
for (count = 1; count < argc; count++) {
printf("argv[%d] = %s\n", count, argv[count]);
}
}
else {
printf("The command had no other arguments.\n");
}
}
void welcome() {
cout << "Welcome!" << endl;
cout << "What is your name?";
// cin
}
int main(int argc, const char *argv[]) {
loadCourses();
Course c = getCourse("CSCI 251");
cout << c << endl;
// if (argc == 2)
// Student person(argv[1]);
// else
// Student person("data/user.json");
return 0;
}
|
#include "data-general.hpp"
#include "data-course.hpp"
#include "data-major.hpp"
#include "data-student.hpp"
using namespace std;
vector<Course> all_courses;
Student user;
void loadCourses() {
ifstream infile("data/2012-13-s2-csv.csv");
string str; // read in the header line
getline(infile, str);
while (infile.peek() != -1){
Course incourse(infile);
all_courses.push_back(incourse);
// cout << incourse << endl;
}
}
void whatDidICallThisWith(int argc, const char *argv[]) {
int count;
printf ("This program was called with \"%s\".\n",argv[0]);
if (argc > 1) {
for (count = 1; count < argc; count++) {
printf("argv[%d] = %s\n", count, argv[count]);
}
}
else {
printf("The command had no other arguments.\n");
}
}
void welcome() {
string name, yearS, yearE, majors;
// cout << "Welcome!" << endl;
// cout << "What is your name? ";
// getline(cin, name);
name = "Xandra Best";
// cout << "What year do you graduate? ";
// cin >> yearE;
// cout << "What are your majors (ex. CSCI, ASIAN) ";
// getline(cin, majors);
majors = "CSCI, STAT, ASIAN";
user = Student(name, "", "", majors);
}
void getCourses() {
string courses;
// cout << "What are some courses that you have taken? (ex. CSCI125, STAT 110)" << endl;
// cout << "> ";
// getline(cin, courses);
courses = "CSCI 215, stat 110, THEAT398, writ211";
user.addCourses(courses);
}
int main(int argc, const char *argv[]) {
loadCourses();
// Course c("BIO 126");
// cout << c << endl;
welcome();
getCourses();
cout << user << endl;
// if (argc == 2)
// Student person(argv[1]);
// else
// Student person("data/user.json");
return 0;
}
|
Add more tests to test-data.cpp
|
Add more tests to test-data.cpp
|
C++
|
agpl-3.0
|
hawkrives/gobbldygook,hawkrives/gobbldygook,hawkrives/gobbldygook
|
8a4c06c8f8ca0e3c2a8e78af9cf70d59c2cf15a2
|
test-data.cpp
|
test-data.cpp
|
#include "data-general.hpp"
#include "data-course.hpp"
#include "data-student.hpp"
using namespace std;
vector<Course> all_courses;
Student user;
void loadCourses() {
ifstream infile("data/2012-13-s2-csv.csv");
string str; // read in the header line
getline(infile, str);
while (infile.peek() != -1){
Course incourse(infile);
all_courses.push_back(incourse);
// cout << incourse << endl;
}
// for (vector<Course>::iterator c = all_courses.begin(); c != all_courses.end(); ++c)
// if (c->getProfessor()[1] == ' ')
// if (c->getProfessor()[2] == '0' || c->getProfessor()[2] == '1')
// c->displayMany();
}
void welcome() {
string name, yearS = "", yearE = "", majors;
cout << "Welcome!" << endl;
cout << "What is your name? ";
getline(cin, name);
cout << "What year do you graduate? ";
getline(cin, yearE);
cout << "What are your majors (ex. CSCI, ASIAN) ";
getline(cin, majors);
user = Student(name, yearS, yearE, majors);
}
void getCourses() {
string courses;
cout << "What are some courses that you have taken? (ex. CSCI125, STAT 110)" << endl;
getline(cin, courses);
user.addCourses(courses);
}
int main(int argc, const char *argv[]) {
loadCourses();
// Method 1: Dynamic.
// welcome();
// getCourses();
// Method 2: Hard-coded file path.
Student user("data/user.txt");
// Method 3: File path as an argument.
// Student user(argv[1]);
user.display();
cout << "Question: Has the user taken CSCI 251? ";
cout << user.hasTakenCourse("CSCI251") << endl;
return 0;
}
// TODO: Add concentrations to Student
|
#include "data-general.hpp"
#include "data-course.hpp"
#include "data-student.hpp"
using namespace std;
vector<Course> all_courses;
Student user;
void loadCourses() {
ifstream infile("data/2012-13-s2-csv.csv");
string str; // read in the header line
getline(infile, str);
while (infile.peek() != -1){
Course incourse(infile);
all_courses.push_back(incourse);
// cout << incourse << endl;
}
// for (vector<Course>::iterator c = all_courses.begin(); c != all_courses.end(); ++c)
// if (c->getProfessor()[1] == ' ')
// if (c->getProfessor()[2] == '0' || c->getProfessor()[2] == '1')
// c->displayMany();
}
void welcome() {
string name, yearS = "", yearE = "", majors;
cout << "Welcome!" << endl;
cout << "What is your name? ";
getline(cin, name);
cout << "What year do you graduate? ";
getline(cin, yearE);
cout << "What are your majors (ex. CSCI, ASIAN) ";
getline(cin, majors);
user = Student(name, yearS, yearE, majors);
}
void requestCourses() {
string courses;
cout << "What are some courses that you have taken? (ex. CSCI125, STAT 110)" << endl;
getline(cin, courses);
user.addCourses(courses);
}
int main(int argc, const char *argv[]) {
loadCourses();
// Method 1: Dynamic.
// welcome();
// requestCourses();
// Method 2: Hard-coded file path.
Student user("data/user.txt");
// Method 3: File path as an argument.
// Student user(argv[1]);
user.display();
cout << "Question: Has the user taken CSCI 251? ";
cout << user.hasTakenCourse("CSCI251") << endl;
return 0;
}
// TODO: Add concentrations to Student
|
Rename getCourses to the less-confusing requestCourses
|
Rename getCourses to the less-confusing requestCourses
|
C++
|
agpl-3.0
|
hawkrives/gobbldygook,hawkrives/gobbldygook,hawkrives/gobbldygook
|
0079809bd29a39d6b8a161c94025e371a7210712
|
bp/loopy_belief_propagation.hpp
|
bp/loopy_belief_propagation.hpp
|
#pragma once
#include <vector>
#include <boost/graph/graph_traits.hpp>
#include <boost/property_map/vector_property_map.hpp>
#include "properties.hpp"
namespace bp {
template<typename Graph, typename Visitor,
typename MessagePropertyMap,
typename BeliefPropertyMap>
void loopy_sum_product(const Graph& graph, Visitor visitor,
MessagePropertyMap message_map,
BeliefPropertyMap belief_map,
std::size_t n_iteration) {
typedef boost::graph_traits<Graph> Traits;
typedef typename Traits::vertex_descriptor Vertex;
typedef typename Traits::edge_descriptor Edge;
// initialize messages
visitor.init_messages(message_map, graph);
visitor.init_beliefs(belief_map, graph);
// make messages
std::vector<Edge> in_vector;
for(std::size_t n=0; n<n_iteration; ++n) {
typename Traits::edge_iterator ei, ei_end;
boost::tie(ei, ei_end) = boost::edges(graph);
for(; ei != ei_end; ++ei) {
in_vector.clear();
const Vertex source = boost::source(*ei);
const Vertex target = boost::target(*ei);
typename Traits::in_edge_iterator ein, ein_end;
boost::tie(ein, ein_end) = boost::in_edges(source, graph);
for(; ein != ein_end; ++ein) {
if(boost::source(*ein, graph) == target)
in_vector.push_back(*ein)
}
visitor.make_message(
*ei,
in_vector.begin(),
in_vector.end(),
message_map,
graph);
}
}
// make beliefs
typename Traits::vertex_iterator vi, vi_end;
boost::tie(vi, vi_end) = boost::vertices(graph);
for(; vi != vi_end; ++vi) {
typename Traits::in_edge_iterator ein, ein_end;
boost::tie(ein, ein_end) = boost::in_edges(*vi, graph);
visitor.make_belief(
*vi, ein, ein_end,
message_map,
belief_map,
graph);
}
}
template<typename Graph, typename Visitor>
void loopy_sum_product(Graph& graph, Visitor visitor,
std::size_t n_iteration) {
loopy_sum_product(
graph, visitor,
boost::get(boost::edge_message, graph),
boost::get(boost::vertex_belief, graph),
n_iteration);
}
} // namespace bp
|
#pragma once
#include <vector>
#include <boost/graph/graph_traits.hpp>
#include <boost/property_map/vector_property_map.hpp>
#include "properties.hpp"
namespace bp {
template<typename Graph, typename Visitor,
typename MessagePropertyMap,
typename BeliefPropertyMap>
void apply_loopy_belief_propagation(const Graph& graph, Visitor visitor,
MessagePropertyMap message_map,
BeliefPropertyMap belief_map,
std::size_t n_iteration) {
typedef boost::graph_traits<Graph> Traits;
typedef typename Traits::vertex_descriptor Vertex;
typedef typename Traits::edge_descriptor Edge;
// initialize messages
visitor.init_messages(message_map, graph);
visitor.init_beliefs(belief_map, graph);
// make messages
std::vector<Edge> in_vector;
for(std::size_t n=0; n<n_iteration; ++n) {
typename Traits::edge_iterator ei, ei_end;
boost::tie(ei, ei_end) = boost::edges(graph);
for(; ei != ei_end; ++ei) {
in_vector.clear();
const Vertex source = boost::source(*ei);
const Vertex target = boost::target(*ei);
typename Traits::in_edge_iterator ein, ein_end;
boost::tie(ein, ein_end) = boost::in_edges(source, graph);
for(; ein != ein_end; ++ein) {
if(boost::source(*ein, graph) == target)
in_vector.push_back(*ein)
}
visitor.make_message(
*ei,
in_vector.begin(),
in_vector.end(),
message_map,
graph);
}
}
// make beliefs
typename Traits::vertex_iterator vi, vi_end;
boost::tie(vi, vi_end) = boost::vertices(graph);
for(; vi != vi_end; ++vi) {
typename Traits::in_edge_iterator ein, ein_end;
boost::tie(ein, ein_end) = boost::in_edges(*vi, graph);
visitor.make_belief(
*vi, ein, ein_end,
message_map,
belief_map,
graph);
}
}
template<typename Graph, typename Visitor>
void apply_loopy_belief_propagation(Graph& graph, Visitor visitor,
std::size_t n_iteration) {
apply_loopy_belief_propagation(
graph, visitor,
boost::get(boost::edge_message, graph),
boost::get(boost::vertex_belief, graph),
n_iteration);
}
} // namespace bp
|
rename to loopy belief propagation
|
rename to loopy belief propagation
|
C++
|
mit
|
rezoo/boost-BP
|
15dd8ed1bba4a51694191c248538ff2b333bfeaa
|
core/deleter.hh
|
core/deleter.hh
|
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef DELETER_HH_
#define DELETER_HH_
#include <memory>
#include <cstdlib>
#include <assert.h>
#include <type_traits>
class deleter {
public:
struct impl;
struct raw_object_tag {};
private:
// if bit 0 set, point to object to be freed directly.
impl* _impl = nullptr;
public:
deleter() = default;
deleter(const deleter&) = delete;
deleter(deleter&& x) : _impl(x._impl) { x._impl = nullptr; }
explicit deleter(impl* i) : _impl(i) {}
deleter(raw_object_tag tag, void* object)
: _impl(from_raw_object(object)) {}
~deleter();
deleter& operator=(deleter&& x);
deleter& operator=(deleter&) = delete;
impl& operator*() const { return *_impl; }
impl* operator->() const { return _impl; }
impl* get() const { return _impl; }
void unshare();
deleter share();
explicit operator bool() const { return bool(_impl); }
void reset(impl* i) {
this->~deleter();
new (this) deleter(i);
}
void append(deleter d);
private:
static bool is_raw_object(impl* i) {
auto x = reinterpret_cast<uintptr_t>(i);
return x & 1;
}
bool is_raw_object() const {
return is_raw_object(_impl);
}
static void* to_raw_object(impl* i) {
auto x = reinterpret_cast<uintptr_t>(i);
return reinterpret_cast<void*>(x & ~uintptr_t(1));
}
void* to_raw_object() const {
return to_raw_object(_impl);
}
impl* from_raw_object(void* object) {
auto x = reinterpret_cast<uintptr_t>(object);
return reinterpret_cast<impl*>(x | 1);
}
};
struct deleter::impl {
unsigned refs = 1;
deleter next;
impl(deleter next) : next(std::move(next)) {}
virtual ~impl() {}
};
inline
deleter::~deleter() {
if (is_raw_object()) {
std::free(to_raw_object());
return;
}
if (_impl && --_impl->refs == 0) {
delete _impl;
}
}
inline
deleter& deleter::operator=(deleter&& x) {
if (this != &x) {
this->~deleter();
new (this) deleter(std::move(x));
}
return *this;
}
template <typename Deleter>
struct lambda_deleter_impl final : deleter::impl {
Deleter del;
lambda_deleter_impl(deleter next, Deleter&& del)
: impl(std::move(next)), del(std::move(del)) {}
virtual ~lambda_deleter_impl() override { del(); }
};
template <typename Object>
struct object_deleter_impl final : deleter::impl {
Object obj;
object_deleter_impl(deleter next, Object&& obj)
: impl(std::move(next)), obj(std::move(obj)) {}
};
template <typename Object>
object_deleter_impl<Object>* make_object_deleter_impl(deleter next, Object obj) {
return new object_deleter_impl<Object>(std::move(next), std::move(obj));
}
template <typename Deleter>
deleter
make_deleter(deleter next, Deleter d) {
return deleter(new lambda_deleter_impl<Deleter>(std::move(next), std::move(d)));
}
template <typename Deleter>
deleter
make_deleter(Deleter d) {
return make_deleter(deleter(), std::move(d));
}
struct free_deleter_impl final : deleter::impl {
void* obj;
free_deleter_impl(void* obj) : impl(deleter()), obj(obj) {}
virtual ~free_deleter_impl() override { std::free(obj); }
};
inline
deleter
deleter::share() {
if (!_impl) {
return deleter();
}
if (is_raw_object()) {
_impl = new free_deleter_impl(to_raw_object());
}
++_impl->refs;
return deleter(_impl);
}
// Appends 'd' to the chain of deleters. Avoids allocation if possible. For
// performance reasons the current chain should be shorter and 'd' should be
// longer.
inline
void deleter::append(deleter d) {
if (!d._impl) {
return;
}
impl* next_impl = _impl;
deleter* next_d = this;
while (next_impl) {
assert(next_impl != d._impl);
if (is_raw_object(next_impl)) {
next_d->_impl = next_impl = new free_deleter_impl(to_raw_object(next_impl));
}
if (next_impl->refs != 1) {
next_d->_impl = next_impl = make_object_deleter_impl(std::move(next_impl->next), deleter(next_impl));
}
next_d = &next_impl->next;
next_impl = next_d->_impl;
}
next_d->_impl = d._impl;
d._impl = nullptr;
}
inline
deleter
make_free_deleter(void* obj) {
return deleter(deleter::raw_object_tag(), obj);
}
inline
deleter
make_free_deleter(deleter next, void* obj) {
return make_deleter(std::move(next), [obj] () mutable { std::free(obj); });
}
#endif /* DELETER_HH_ */
|
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef DELETER_HH_
#define DELETER_HH_
#include <memory>
#include <cstdlib>
#include <assert.h>
#include <type_traits>
class deleter final {
public:
struct impl;
struct raw_object_tag {};
private:
// if bit 0 set, point to object to be freed directly.
impl* _impl = nullptr;
public:
deleter() = default;
deleter(const deleter&) = delete;
deleter(deleter&& x) : _impl(x._impl) { x._impl = nullptr; }
explicit deleter(impl* i) : _impl(i) {}
deleter(raw_object_tag tag, void* object)
: _impl(from_raw_object(object)) {}
~deleter();
deleter& operator=(deleter&& x);
deleter& operator=(deleter&) = delete;
impl& operator*() const { return *_impl; }
impl* operator->() const { return _impl; }
impl* get() const { return _impl; }
void unshare();
deleter share();
explicit operator bool() const { return bool(_impl); }
void reset(impl* i) {
this->~deleter();
new (this) deleter(i);
}
void append(deleter d);
private:
static bool is_raw_object(impl* i) {
auto x = reinterpret_cast<uintptr_t>(i);
return x & 1;
}
bool is_raw_object() const {
return is_raw_object(_impl);
}
static void* to_raw_object(impl* i) {
auto x = reinterpret_cast<uintptr_t>(i);
return reinterpret_cast<void*>(x & ~uintptr_t(1));
}
void* to_raw_object() const {
return to_raw_object(_impl);
}
impl* from_raw_object(void* object) {
auto x = reinterpret_cast<uintptr_t>(object);
return reinterpret_cast<impl*>(x | 1);
}
};
struct deleter::impl {
unsigned refs = 1;
deleter next;
impl(deleter next) : next(std::move(next)) {}
virtual ~impl() {}
};
inline
deleter::~deleter() {
if (is_raw_object()) {
std::free(to_raw_object());
return;
}
if (_impl && --_impl->refs == 0) {
delete _impl;
}
}
inline
deleter& deleter::operator=(deleter&& x) {
if (this != &x) {
this->~deleter();
new (this) deleter(std::move(x));
}
return *this;
}
template <typename Deleter>
struct lambda_deleter_impl final : deleter::impl {
Deleter del;
lambda_deleter_impl(deleter next, Deleter&& del)
: impl(std::move(next)), del(std::move(del)) {}
virtual ~lambda_deleter_impl() override { del(); }
};
template <typename Object>
struct object_deleter_impl final : deleter::impl {
Object obj;
object_deleter_impl(deleter next, Object&& obj)
: impl(std::move(next)), obj(std::move(obj)) {}
};
template <typename Object>
object_deleter_impl<Object>* make_object_deleter_impl(deleter next, Object obj) {
return new object_deleter_impl<Object>(std::move(next), std::move(obj));
}
template <typename Deleter>
deleter
make_deleter(deleter next, Deleter d) {
return deleter(new lambda_deleter_impl<Deleter>(std::move(next), std::move(d)));
}
template <typename Deleter>
deleter
make_deleter(Deleter d) {
return make_deleter(deleter(), std::move(d));
}
struct free_deleter_impl final : deleter::impl {
void* obj;
free_deleter_impl(void* obj) : impl(deleter()), obj(obj) {}
virtual ~free_deleter_impl() override { std::free(obj); }
};
inline
deleter
deleter::share() {
if (!_impl) {
return deleter();
}
if (is_raw_object()) {
_impl = new free_deleter_impl(to_raw_object());
}
++_impl->refs;
return deleter(_impl);
}
// Appends 'd' to the chain of deleters. Avoids allocation if possible. For
// performance reasons the current chain should be shorter and 'd' should be
// longer.
inline
void deleter::append(deleter d) {
if (!d._impl) {
return;
}
impl* next_impl = _impl;
deleter* next_d = this;
while (next_impl) {
assert(next_impl != d._impl);
if (is_raw_object(next_impl)) {
next_d->_impl = next_impl = new free_deleter_impl(to_raw_object(next_impl));
}
if (next_impl->refs != 1) {
next_d->_impl = next_impl = make_object_deleter_impl(std::move(next_impl->next), deleter(next_impl));
}
next_d = &next_impl->next;
next_impl = next_d->_impl;
}
next_d->_impl = d._impl;
d._impl = nullptr;
}
inline
deleter
make_free_deleter(void* obj) {
return deleter(deleter::raw_object_tag(), obj);
}
inline
deleter
make_free_deleter(deleter next, void* obj) {
return make_deleter(std::move(next), [obj] () mutable { std::free(obj); });
}
#endif /* DELETER_HH_ */
|
mark as final class
|
deleter: mark as final class
Prevent accidental inheritance.
|
C++
|
agpl-3.0
|
scylladb/scylla,gwicke/scylla,avikivity/seastar,kangkot/scylla,printedheart/seastar,dwdm/seastar,raphaelsc/scylla,raphaelsc/scylla,eklitzke/scylla,linearregression/seastar,dwdm/seastar,bowlofstew/seastar,joerg84/seastar,avikivity/scylla,aruanruan/scylla,eklitzke/scylla,ducthangho/imdb,kangkot/scylla,koolhazz/seastar,wildinto/seastar,duarten/scylla,eklitzke/scylla,bowlofstew/scylla,xtao/seastar,justintung/scylla,scylladb/seastar,rluta/scylla,glommer/scylla,anzihenry/seastar,raphaelsc/seastar,raphaelsc/seastar,jonathanleang/seastar,tempbottle/scylla,kjniemi/scylla,linearregression/scylla,respu/scylla,printedheart/seastar,printedheart/seastar,syuu1228/seastar,rluta/scylla,leejir/seastar,guiquanz/scylla,sjperkins/seastar,norcimo5/seastar,gwicke/scylla,anzihenry/seastar,bzero/seastar,duarten/scylla,flashbuckets/seastar,linearregression/scylla,stamhe/seastar,raphaelsc/seastar,joerg84/seastar,stamhe/scylla,slivne/seastar,raphaelsc/scylla,gwicke/scylla,tempbottle/scylla,dwdm/seastar,acbellini/scylla,stamhe/scylla,acbellini/scylla,norcimo5/seastar,stamhe/scylla,acbellini/seastar,aruanruan/scylla,asias/scylla,shaunstanislaus/scylla,flashbuckets/seastar,dreamsxin/seastar,sjperkins/seastar,flashbuckets/seastar,scylladb/scylla-seastar,shaunstanislaus/scylla,cloudius-systems/seastar,leejir/seastar,mixja/seastar,scylladb/scylla-seastar,wildinto/scylla,linearregression/seastar,aruanruan/scylla,victorbriz/scylla,dreamsxin/seastar,capturePointer/scylla,avikivity/scylla,dwdm/scylla,leejir/seastar,stamhe/seastar,acbellini/seastar,wildinto/seastar,wildinto/scylla,senseb/scylla,sjperkins/seastar,shyamalschandra/seastar,scylladb/seastar,asias/scylla,phonkee/scylla,bowlofstew/seastar,joerg84/seastar,scylladb/scylla,koolhazz/seastar,tempbottle/scylla,scylladb/seastar,chunshengster/seastar,acbellini/scylla,justintung/scylla,bowlofstew/seastar,avikivity/scylla,tempbottle/seastar,dwdm/scylla,jonathanleang/seastar,phonkee/scylla,guiquanz/scylla,scylladb/scylla,justintung/scylla,tempbottle/seastar,dwdm/scylla,shyamalschandra/seastar,kjniemi/seastar,guiquanz/scylla,cloudius-systems/seastar,rentongzhang/scylla,bzero/seastar,jonathanleang/seastar,cloudius-systems/seastar,hongliangzhao/seastar,senseb/scylla,acbellini/seastar,phonkee/scylla,koolhazz/seastar,anzihenry/seastar,slivne/seastar,xtao/seastar,kjniemi/scylla,rentongzhang/scylla,scylladb/scylla,mixja/seastar,rentongzhang/scylla,linearregression/seastar,shyamalschandra/seastar,scylladb/scylla-seastar,linearregression/scylla,respu/scylla,syuu1228/seastar,chunshengster/seastar,victorbriz/scylla,wildinto/seastar,bzero/seastar,bowlofstew/scylla,glommer/scylla,duarten/scylla,senseb/scylla,xtao/seastar,chunshengster/seastar,kjniemi/seastar,hongliangzhao/seastar,avikivity/seastar,wildinto/scylla,kjniemi/seastar,kangkot/scylla,capturePointer/scylla,slivne/seastar,mixja/seastar,ducthangho/imdb,kjniemi/scylla,avikivity/seastar,ducthangho/imdb,syuu1228/seastar,dreamsxin/seastar,norcimo5/seastar,shaunstanislaus/scylla,bowlofstew/scylla,respu/scylla,glommer/scylla,victorbriz/scylla,hongliangzhao/seastar,capturePointer/scylla,rluta/scylla,stamhe/seastar,tempbottle/seastar,asias/scylla
|
1fc0df3b07e8425d7df0f6b6e538526bb51c7d3e
|
Applications/ctkExampleHostedApp/ctkExampleHostedAppMain.cpp
|
Applications/ctkExampleHostedApp/ctkExampleHostedAppMain.cpp
|
/*=============================================================================
Library: CTK
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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.
=============================================================================*/
// Qt includes
#include <QApplication>
#include <QString>
#include <QStringList>
#include <QDirIterator>
#include <QWidget>
#include <QFileInfo>
#include <QUrl>
#include <QDebug>
// CTK includes
#include <ctkCommandLineParser.h>
#include <ctkPluginFrameworkFactory.h>
#include <ctkPluginFramework.h>
#include <ctkPluginException.h>
#include <ctkPluginContext.h>
// For testing purposes use:
// --hostURL http://localhost:8081/host --applicationURL http://localhost:8082/app dicomapp
void print_usage()
{
qCritical() << "Usage:";
qCritical() << " " << QFileInfo(qApp->arguments().at(0)).fileName() << " --hostURL url1 --applicationURL url2 <plugin-name>";
}
int main(int argv, char** argc)
{
QApplication app(argv, argc);
qApp->setOrganizationName("CTK");
qApp->setOrganizationDomain("commontk.org");
qApp->setApplicationName("ctkExampleHostedApp");
ctkCommandLineParser parser;
parser.setArgumentPrefix("--", "-"); // Use Unix-style argument names
// Add command line argument names
parser.addArgument("hostURL", "", QVariant::String, "Hosting system URL");
parser.addArgument("applicationURL", "", QVariant::String, "Hosted Application URL");
parser.addArgument("help", "h", QVariant::Bool, "Show this help text");
bool ok = false;
QHash<QString, QVariant> parsedArgs = parser.parseArguments(QCoreApplication::arguments(), &ok);
if (!ok)
{
QTextStream(stderr, QIODevice::WriteOnly) << "Error parsing arguments: "
<< parser.errorString() << "\n";
return EXIT_FAILURE;
}
// Show a help message
if (parsedArgs.contains("help"))
{
print_usage();
QTextStream(stdout, QIODevice::WriteOnly) << parser.helpText();
return EXIT_SUCCESS;
}
if(parsedArgs.count() != 2)
{
qCritical() << "Wrong number of command line arguments.";
print_usage();
QTextStream(stdout, QIODevice::WriteOnly) << parser.helpText();
return EXIT_FAILURE;
}
QString hostURL = parsedArgs.value("hostURL").toString();
QString appURL = parsedArgs.value("applicationURL").toString();
qDebug() << "appURL is: " << appURL << " . Extracted port is: " << QUrl(appURL).port();
// setup the plugin framework
ctkProperties fwProps;
fwProps.insert("dah.hostURL", hostURL);
fwProps.insert("dah.appURL", appURL);
ctkPluginFrameworkFactory fwFactory(fwProps);
QSharedPointer<ctkPluginFramework> framework = fwFactory.getFramework();
try {
framework->init();
}
catch (const ctkPluginException& exc)
{
qCritical() << "Failed to initialize the plug-in framework:" << exc;
exit(2);
}
#ifdef CMAKE_INTDIR
QString pluginPath = qApp->applicationDirPath() + "/../plugins/" CMAKE_INTDIR "/";
#else
QString pluginPath = qApp->applicationDirPath() + "/plugins/";
#endif
qApp->addLibraryPath(pluginPath);
// Construct the name of the plugin with the business logic
// (thus the actual logic of the hosted app)
QString pluginName("org_commontk_dah_exampleapp");
if(parser.unparsedArguments().count() > 0)
{
pluginName = parser.unparsedArguments().at(0);
}
// try to find the plugin and install all plugins available in
// pluginPath containing the string "org_commontk_dah" (but do not start them)
QSharedPointer<ctkPlugin> appPlugin;
QStringList libFilter;
libFilter << "*.dll" << "*.so" << "*.dylib";
QDirIterator dirIter(pluginPath, libFilter, QDir::Files);
while(dirIter.hasNext())
{
try
{
QString fileLocation = dirIter.next();
if (fileLocation.contains("org_commontk_dah"))
{
QSharedPointer<ctkPlugin> plugin = framework->getPluginContext()->installPlugin(QUrl::fromLocalFile(fileLocation));
if (fileLocation.contains(pluginName))
{
appPlugin = plugin;
}
//plugin->start(ctkPlugin::START_TRANSIENT);
}
}
catch (const ctkPluginException& e)
{
qCritical() << e.what();
}
}
// if we did not find the business logic: abort
if(!appPlugin)
{
qCritical() << "Could not find plugin.";
qCritical() << " Plugin name: " << pluginName;
qCritical() << " Plugin path: " << pluginPath;
exit(3);
}
// start the plugin framework
framework->start();
// start the plugin with the business logic
try
{
appPlugin->start();
}
catch (const ctkPluginException& e)
{
qCritical() << e;
}
return app.exec();
}
|
/*=============================================================================
Library: CTK
Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics
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.
=============================================================================*/
// Qt includes
#include <QApplication>
#include <QString>
#include <QStringList>
#include <QDirIterator>
#include <QWidget>
#include <QFileInfo>
#include <QUrl>
#include <QDebug>
// CTK includes
#include <ctkCommandLineParser.h>
#include <ctkPluginFrameworkFactory.h>
#include <ctkPluginFramework.h>
#include <ctkPluginException.h>
#include <ctkPluginContext.h>
// For testing purposes use:
// --hostURL http://localhost:8081/host --applicationURL http://localhost:8082/app dicomapp
void print_usage()
{
qCritical() << "Usage:";
qCritical() << " " << QFileInfo(qApp->arguments().at(0)).fileName() << " --hostURL url1 --applicationURL url2 <plugin-name>";
}
int main(int argv, char** argc)
{
QApplication app(argv, argc);
qApp->setOrganizationName("CTK");
qApp->setOrganizationDomain("commontk.org");
qApp->setApplicationName("ctkExampleHostedApp");
ctkCommandLineParser parser;
parser.setArgumentPrefix("--", "-"); // Use Unix-style argument names
// Add command line argument names
parser.addArgument("hostURL", "", QVariant::String, "Hosting system URL");
parser.addArgument("applicationURL", "", QVariant::String, "Hosted Application URL");
parser.addArgument("help", "h", QVariant::Bool, "Show this help text");
bool ok = false;
QHash<QString, QVariant> parsedArgs = parser.parseArguments(QCoreApplication::arguments(), &ok);
if (!ok)
{
QTextStream(stderr, QIODevice::WriteOnly) << "Error parsing arguments: "
<< parser.errorString() << "\n";
return EXIT_FAILURE;
}
// Show a help message
if (parsedArgs.contains("help"))
{
print_usage();
QTextStream(stdout, QIODevice::WriteOnly) << parser.helpText();
return EXIT_SUCCESS;
}
if(parsedArgs.count() != 2)
{
qCritical() << "Wrong number of command line arguments.";
print_usage();
QTextStream(stdout, QIODevice::WriteOnly) << parser.helpText();
return EXIT_FAILURE;
}
QString hostURL = parsedArgs.value("hostURL").toString();
QString appURL = parsedArgs.value("applicationURL").toString();
qDebug() << "appURL is: " << appURL << " . Extracted port is: " << QUrl(appURL).port();
// setup the plugin framework
ctkProperties fwProps;
fwProps.insert("dah.hostURL", hostURL);
fwProps.insert("dah.appURL", appURL);
ctkPluginFrameworkFactory fwFactory(fwProps);
QSharedPointer<ctkPluginFramework> framework = fwFactory.getFramework();
try {
framework->init();
}
catch (const ctkPluginException& exc)
{
qCritical() << "Failed to initialize the plug-in framework:" << exc;
return EXIT_FAILURE;
}
#ifdef CMAKE_INTDIR
QString pluginPath = qApp->applicationDirPath() + "/../plugins/" CMAKE_INTDIR "/";
#else
QString pluginPath = qApp->applicationDirPath() + "/plugins/";
#endif
qApp->addLibraryPath(pluginPath);
// Construct the name of the plugin with the business logic
// (thus the actual logic of the hosted app)
QString pluginName("org_commontk_dah_exampleapp");
if(parser.unparsedArguments().count() > 0)
{
pluginName = parser.unparsedArguments().at(0);
}
// try to find the plugin and install all plugins available in
// pluginPath containing the string "org_commontk_dah" (but do not start them)
QSharedPointer<ctkPlugin> appPlugin;
QStringList libFilter;
libFilter << "*.dll" << "*.so" << "*.dylib";
QDirIterator dirIter(pluginPath, libFilter, QDir::Files);
while(dirIter.hasNext())
{
try
{
QString fileLocation = dirIter.next();
if (fileLocation.contains("org_commontk_dah"))
{
QSharedPointer<ctkPlugin> plugin = framework->getPluginContext()->installPlugin(QUrl::fromLocalFile(fileLocation));
if (fileLocation.contains(pluginName))
{
appPlugin = plugin;
}
//plugin->start(ctkPlugin::START_TRANSIENT);
}
}
catch (const ctkPluginException& e)
{
qCritical() << e.what();
}
}
// if we did not find the business logic: abort
if(!appPlugin)
{
qCritical() << "Could not find plugin.";
qCritical() << " Plugin name: " << pluginName;
qCritical() << " Plugin path: " << pluginPath;
return EXIT_FAILURE;
}
// start the plugin framework
framework->start();
// start the plugin with the business logic
try
{
appPlugin->start();
}
catch (const ctkPluginException& e)
{
qCritical() << e;
}
return app.exec();
}
|
Use EXIT_FAILURE define instead of hard-coded integers for exit code
|
Use EXIT_FAILURE define instead of hard-coded integers for exit code
|
C++
|
apache-2.0
|
mehrtash/CTK,vovythevov/CTK,naucoin/CTK,pieper/CTK,lassoan/CTK,msmolens/CTK,finetjul/CTK,msmolens/CTK,AndreasFetzer/CTK,AndreasFetzer/CTK,SINTEFMedtek/CTK,Sardge/CTK,laurennlam/CTK,danielknorr/CTK,ddao/CTK,ddao/CTK,rkhlebnikov/CTK,vovythevov/CTK,Heather/CTK,AndreasFetzer/CTK,fedorov/CTK,sankhesh/CTK,CJGoch/CTK,danielknorr/CTK,jcfr/CTK,sankhesh/CTK,espakm/CTK,laurennlam/CTK,151706061/CTK,CJGoch/CTK,vovythevov/CTK,jcfr/CTK,fedorov/CTK,SINTEFMedtek/CTK,lassoan/CTK,jcfr/CTK,espakm/CTK,SINTEFMedtek/CTK,CJGoch/CTK,danielknorr/CTK,Heather/CTK,msmolens/CTK,danielknorr/CTK,151706061/CTK,mehrtash/CTK,rkhlebnikov/CTK,Sardge/CTK,SINTEFMedtek/CTK,rkhlebnikov/CTK,rkhlebnikov/CTK,CJGoch/CTK,espakm/CTK,mehrtash/CTK,mehrtash/CTK,lassoan/CTK,sankhesh/CTK,fedorov/CTK,sankhesh/CTK,lassoan/CTK,jcfr/CTK,Sardge/CTK,commontk/CTK,ddao/CTK,vovythevov/CTK,pieper/CTK,naucoin/CTK,naucoin/CTK,naucoin/CTK,AndreasFetzer/CTK,Heather/CTK,jcfr/CTK,ddao/CTK,fedorov/CTK,151706061/CTK,commontk/CTK,laurennlam/CTK,laurennlam/CTK,CJGoch/CTK,commontk/CTK,msmolens/CTK,finetjul/CTK,151706061/CTK,finetjul/CTK,espakm/CTK,finetjul/CTK,Sardge/CTK,pieper/CTK,commontk/CTK,pieper/CTK,SINTEFMedtek/CTK,Heather/CTK,151706061/CTK
|
2a85a5f91d2deb56b00d189f435bc1d0cd998b8c
|
chrome/nacl/nacl_thread.cc
|
chrome/nacl/nacl_thread.cc
|
// Copyright (c) 2009 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/nacl/nacl_thread.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/nacl_messages.h"
// This is ugly. We need an interface header file for the exported
// sel_ldr interfaces.
// TODO(gregoryd,sehr): Add an interface header.
#if defined(OS_WIN)
typedef HANDLE NaClHandle;
#else
typedef int NaClHandle;
#endif // NaClHandle
// This is currently necessary because we have a conflict between
// NaCl's "struct NaClThread" and Chromium's "class NaClThread".
extern "C" int NaClMainForChromium(int handle_count, const NaClHandle* handles);
NaClThread::NaClThread() {
}
NaClThread::~NaClThread() {
}
NaClThread* NaClThread::current() {
return static_cast<NaClThread*>(ChildThread::current());
}
void NaClThread::OnControlMessageReceived(const IPC::Message& msg) {
IPC_BEGIN_MESSAGE_MAP(NaClThread, msg)
IPC_MESSAGE_HANDLER(NaClProcessMsg_Start, OnStartSelLdr)
IPC_END_MESSAGE_MAP()
}
void NaClThread::OnStartSelLdr(std::vector<nacl::FileDescriptor> handles) {
NaClHandle* array = new NaClHandle[handles.size()];
for (size_t i = 0; i < handles.size(); i++) {
array[i] = nacl::ToNativeHandle(handles[i]);
}
NaClMainForChromium(static_cast<int>(handles.size()), array);
delete array;
}
|
// Copyright (c) 2009 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/nacl/nacl_thread.h"
#include "base/scoped_ptr.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/nacl_messages.h"
// This is ugly. We need an interface header file for the exported
// sel_ldr interfaces.
// TODO(gregoryd,sehr): Add an interface header.
#if defined(OS_WIN)
typedef HANDLE NaClHandle;
#else
typedef int NaClHandle;
#endif // NaClHandle
// This is currently necessary because we have a conflict between
// NaCl's "struct NaClThread" and Chromium's "class NaClThread".
extern "C" int NaClMainForChromium(int handle_count, const NaClHandle* handles);
NaClThread::NaClThread() {
}
NaClThread::~NaClThread() {
}
NaClThread* NaClThread::current() {
return static_cast<NaClThread*>(ChildThread::current());
}
void NaClThread::OnControlMessageReceived(const IPC::Message& msg) {
IPC_BEGIN_MESSAGE_MAP(NaClThread, msg)
IPC_MESSAGE_HANDLER(NaClProcessMsg_Start, OnStartSelLdr)
IPC_END_MESSAGE_MAP()
}
void NaClThread::OnStartSelLdr(std::vector<nacl::FileDescriptor> handles) {
scoped_array<NaClHandle> array(new NaClHandle[handles.size()]);
for (size_t i = 0; i < handles.size(); i++) {
array[i] = nacl::ToNativeHandle(handles[i]);
}
NaClMainForChromium(static_cast<int>(handles.size()), array.get());
}
|
Use a scoped_array rather than a bare pointer.
|
nacl: Use a scoped_array rather than a bare pointer.
The bug was that we had a new[] without a matching delete[],
using a scoped_array fixes this and simplifies the code.
TEST=compiles
Review URL: http://codereview.chromium.org/3410009
git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@59856 0039d316-1c4b-4281-b951-d872f2087c98
|
C++
|
bsd-3-clause
|
hgl888/chromium-crosswalk,robclark/chromium,littlstar/chromium.src,ondra-novak/chromium.src,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,dednal/chromium.src,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,jaruba/chromium.src,jaruba/chromium.src,hgl888/chromium-crosswalk,anirudhSK/chromium,chuan9/chromium-crosswalk,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,ltilve/chromium,bright-sparks/chromium-spacewalk,axinging/chromium-crosswalk,junmin-zhu/chromium-rivertrail,patrickm/chromium.src,hgl888/chromium-crosswalk,rogerwang/chromium,rogerwang/chromium,Chilledheart/chromium,littlstar/chromium.src,dednal/chromium.src,Pluto-tv/chromium-crosswalk,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk-efl,keishi/chromium,ltilve/chromium,dushu1203/chromium.src,mogoweb/chromium-crosswalk,robclark/chromium,PeterWangIntel/chromium-crosswalk,nacl-webkit/chrome_deps,rogerwang/chromium,mogoweb/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,anirudhSK/chromium,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,ondra-novak/chromium.src,anirudhSK/chromium,hujiajie/pa-chromium,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,keishi/chromium,hujiajie/pa-chromium,anirudhSK/chromium,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,Fireblend/chromium-crosswalk,M4sse/chromium.src,Chilledheart/chromium,patrickm/chromium.src,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,junmin-zhu/chromium-rivertrail,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,robclark/chromium,crosswalk-project/chromium-crosswalk-efl,chuan9/chromium-crosswalk,jaruba/chromium.src,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,axinging/chromium-crosswalk,hujiajie/pa-chromium,dednal/chromium.src,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,anirudhSK/chromium,hujiajie/pa-chromium,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,Just-D/chromium-1,Jonekee/chromium.src,Just-D/chromium-1,keishi/chromium,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,Jonekee/chromium.src,axinging/chromium-crosswalk,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,nacl-webkit/chrome_deps,rogerwang/chromium,ondra-novak/chromium.src,timopulkkinen/BubbleFish,ltilve/chromium,rogerwang/chromium,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk,keishi/chromium,patrickm/chromium.src,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,chuan9/chromium-crosswalk,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,anirudhSK/chromium,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk,robclark/chromium,robclark/chromium,Jonekee/chromium.src,Jonekee/chromium.src,Chilledheart/chromium,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,robclark/chromium,pozdnyakov/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,axinging/chromium-crosswalk,ltilve/chromium,markYoungH/chromium.src,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,dednal/chromium.src,keishi/chromium,rogerwang/chromium,timopulkkinen/BubbleFish,littlstar/chromium.src,zcbenz/cefode-chromium,jaruba/chromium.src,dushu1203/chromium.src,littlstar/chromium.src,chuan9/chromium-crosswalk,Just-D/chromium-1,Fireblend/chromium-crosswalk,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,pozdnyakov/chromium-crosswalk,Chilledheart/chromium,jaruba/chromium.src,rogerwang/chromium,dushu1203/chromium.src,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,rogerwang/chromium,jaruba/chromium.src,robclark/chromium,keishi/chromium,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,bright-sparks/chromium-spacewalk,mogoweb/chromium-crosswalk,Jonekee/chromium.src,ondra-novak/chromium.src,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,krieger-od/nwjs_chromium.src,Chilledheart/chromium,Jonekee/chromium.src,hujiajie/pa-chromium,M4sse/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,Just-D/chromium-1,hujiajie/pa-chromium,M4sse/chromium.src,axinging/chromium-crosswalk,ChromiumWebApps/chromium,patrickm/chromium.src,nacl-webkit/chrome_deps,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,mohamed--abdel-maksoud/chromium.src,zcbenz/cefode-chromium,bright-sparks/chromium-spacewalk,zcbenz/cefode-chromium,Just-D/chromium-1,littlstar/chromium.src,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ltilve/chromium,dednal/chromium.src,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,junmin-zhu/chromium-rivertrail,pozdnyakov/chromium-crosswalk,dednal/chromium.src,M4sse/chromium.src,patrickm/chromium.src,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,TheTypoMaster/chromium-crosswalk,junmin-zhu/chromium-rivertrail,krieger-od/nwjs_chromium.src,littlstar/chromium.src,ltilve/chromium,M4sse/chromium.src,zcbenz/cefode-chromium,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,hujiajie/pa-chromium,ChromiumWebApps/chromium,robclark/chromium,keishi/chromium,fujunwei/chromium-crosswalk,keishi/chromium,chuan9/chromium-crosswalk,anirudhSK/chromium,ChromiumWebApps/chromium,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,dednal/chromium.src,ondra-novak/chromium.src,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,keishi/chromium,chuan9/chromium-crosswalk,anirudhSK/chromium,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,keishi/chromium,Pluto-tv/chromium-crosswalk,Fireblend/chromium-crosswalk,dednal/chromium.src,hgl888/chromium-crosswalk,anirudhSK/chromium,timopulkkinen/BubbleFish,Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,markYoungH/chromium.src,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,Chilledheart/chromium,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,nacl-webkit/chrome_deps,Fireblend/chromium-crosswalk,ondra-novak/chromium.src,robclark/chromium,TheTypoMaster/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ltilve/chromium,markYoungH/chromium.src,jaruba/chromium.src,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,M4sse/chromium.src,zcbenz/cefode-chromium,markYoungH/chromium.src,timopulkkinen/BubbleFish,patrickm/chromium.src,pozdnyakov/chromium-crosswalk,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,zcbenz/cefode-chromium,markYoungH/chromium.src,jaruba/chromium.src,keishi/chromium,Chilledheart/chromium,Fireblend/chromium-crosswalk,dushu1203/chromium.src,hgl888/chromium-crosswalk,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,nacl-webkit/chrome_deps,junmin-zhu/chromium-rivertrail,dednal/chromium.src,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,Chilledheart/chromium,patrickm/chromium.src,ChromiumWebApps/chromium,dednal/chromium.src,anirudhSK/chromium,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,rogerwang/chromium,rogerwang/chromium,dushu1203/chromium.src,timopulkkinen/BubbleFish,nacl-webkit/chrome_deps,krieger-od/nwjs_chromium.src,fujunwei/chromium-crosswalk,mogoweb/chromium-crosswalk,nacl-webkit/chrome_deps,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,junmin-zhu/chromium-rivertrail,littlstar/chromium.src,junmin-zhu/chromium-rivertrail,patrickm/chromium.src,jaruba/chromium.src,robclark/chromium,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,jaruba/chromium.src,hujiajie/pa-chromium,Jonekee/chromium.src,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1
|
c2383f6183165487e29b7f9900a64c419bec3791
|
test.cpp
|
test.cpp
|
#include <iostream>
#include <vector>
#include <ctime>
#include <stdint.h>
#include "libpopcnt.h"
int main(int argc, char** argv)
{
srand((unsigned int) time(0));
int max_size = 100000;
// Generate vectors with random data and compute the bit
// population count using 2 different algorithms and
// check that the results match
for (int size = 0; size < max_size; size++)
{
double percent = (100.0 * size) / max_size;
std::cout << "\rStatus: " << (int) percent << "%" << std::flush;
std::vector<uint8_t> data(size);
for (int i = 0; i < size; i++)
data[i] = (uint8_t) rand();
uint64_t bits = popcnt(&data[0], size);
uint64_t bits_verify = 0;
for (int i = 0; i < size; i++)
bits_verify += popcnt_u64(data[i]);
if (bits != bits_verify)
{
std::cerr << std::endl;
std::cerr << "libpopcnt test failed!" << std::endl;
return 1;
}
}
std::cout << "\rStatus: 100%" << std::flush;
std::cout << std::endl;
std::cout << "libpopcnt tested successfully!" << std::endl;
return 0;
}
|
#include <iostream>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <stdint.h>
#include "libpopcnt.h"
int main(int argc, char** argv)
{
srand((unsigned int) time(0));
int max_size = 100000;
// Generate vectors with random data and compute the bit
// population count using 2 different algorithms and
// check that the results match
for (int size = 0; size < max_size; size++)
{
double percent = (100.0 * size) / max_size;
std::cout << "\rStatus: " << (int) percent << "%" << std::flush;
std::vector<uint8_t> data(size);
for (int i = 0; i < size; i++)
data[i] = (uint8_t) rand();
uint64_t bits = popcnt(&data[0], size);
uint64_t bits_verify = 0;
for (int i = 0; i < size; i++)
bits_verify += popcnt_u64(data[i]);
if (bits != bits_verify)
{
std::cerr << std::endl;
std::cerr << "libpopcnt test failed!" << std::endl;
return 1;
}
}
std::cout << "\rStatus: 100%" << std::flush;
std::cout << std::endl;
std::cout << "libpopcnt tested successfully!" << std::endl;
return 0;
}
|
Add header <cstdlib>
|
Add header <cstdlib>
|
C++
|
bsd-2-clause
|
KOConchobhair/libpopcnt,KOConchobhair/libpopcnt,kimwalisch/libpopcnt,kimwalisch/libpopcnt
|
c6eae9030ab8e6217bd4766981d3597f61521652
|
test/test.cpp
|
test/test.cpp
|
/*
* Copyright 2015 Matthew Harvey
*
* 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.
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
|
/*
* Copyright 2015 Matthew Harvey
*
* 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.
*/
#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#include <boost/test/unit_test.hpp>
// TODO Write more tests.
|
Add TODO re. tests.
|
Add TODO re. tests.
|
C++
|
apache-2.0
|
matt-harvey/swx,skybaboon/swx
|
04b2183d48d341a491f3d6c7bf5ee2ab861f55a5
|
src/CPlayer.cpp
|
src/CPlayer.cpp
|
#include "CPlayer.h"
#include "CVehicle.h"
#include <sampgdk/a_players.h>
#include <sampgdk/core.h>
#include <boost/chrono/chrono.hpp>
namespace chrono = boost::chrono;
CPlayerHandler *CPlayerHandler::m_Instance = new CPlayerHandler;
CPlayerHandler::CPlayerHandler() :
m_Thread(new thread(boost::bind(&CPlayerHandler::ThreadFunc, this)))
{ }
CPlayerHandler::~CPlayerHandler()
{
m_ThreadRunning = false;
m_Thread->join();
delete m_Thread;
for(unordered_map<uint16_t, CPlayer *>::iterator i = m_Players.begin(), end = m_Players.end(); i != end; ++i)
(*i).second->Destroy();
}
CPlayer *CPlayerHandler::FindPlayer(uint16_t playerid)
{
CPlayer *player = nullptr;
unordered_map<uint16_t, CPlayer *>::iterator i;
if( (i = m_Players.find(playerid)) != m_Players.end())
player = i->second;
return player;
}
void CPlayerHandler::UpdateAll()
{
for(unordered_map<uint16_t, CPlayer *>::iterator i = m_Players.begin(), end = m_Players.end(); i != end; ++i)
i->second->Update();
}
void CPlayerHandler::ThreadFunc()
{
m_ThreadRunning = true;
while(m_ThreadRunning)
{
for(unordered_map<uint16_t, CPlayer *>::iterator i = m_Players.begin(), end = m_Players.end(); i != end; ++i) //very bad
{
CVehicleHandler::Get()->StreamAll(i->second);
}
this_thread::sleep_for(chrono::milliseconds(10));
}
}
void CPlayer::Update()
{
if(m_DataLock == true)
return ;
float tmp_pos[3];
GetPlayerCameraPos(m_Id, &m_CameraPos[0], &m_CameraPos[1], &m_CameraPos[2]);
GetPlayerCameraFrontVector(m_Id, &m_CameraDir[0], &m_CameraDir[1], &m_CameraDir[2]);
m_CameraMode = GetPlayerCameraMode(m_Id);
GetPlayerPos(m_Id, &tmp_pos[0], &tmp_pos[1], &tmp_pos[2]);
m_Pos = point(tmp_pos[0], tmp_pos[1], tmp_pos[2]);
GetPlayerVelocity(m_Id, &m_Velocity[0], &m_Velocity[1], &m_Velocity[2]);
}
bool CPlayer::IsInSight(float x, float y, float z)
{
bool ret_val = false;
m_DataLock = true;
float camera_angle = 0.0f;
switch (m_CameraMode)
{
case 4:
camera_angle = 41.5f;
break;
default:
break;
}
float
scal_prod,
vec_len[2];
x -= m_CameraPos[0];
y -= m_CameraPos[1];
z -= m_CameraPos[2];
scal_prod = (m_CameraDir[0] * x) + (m_CameraDir[1] * y) + (m_CameraDir[2] * z);
vec_len[0] = sqrtf(x*x + y*y + z*z);
vec_len[1] = sqrtf(m_CameraDir[0]*m_CameraDir[0] + m_CameraDir[1]*m_CameraDir[1] + m_CameraDir[2]*m_CameraDir[2]);
float cal_angle = acosf(scal_prod / (vec_len[0] * vec_len[1])) * 180.0f / 3.14159265f;
ret_val = cal_angle <= camera_angle;
m_DataLock = false;
return ret_val;
}
|
#include "CPlayer.h"
#include "CVehicle.h"
#include <sampgdk/a_players.h>
#include <sampgdk/core.h>
#include <boost/chrono/chrono.hpp>
namespace chrono = boost::chrono;
CPlayerHandler *CPlayerHandler::m_Instance = new CPlayerHandler;
CPlayerHandler::CPlayerHandler() :
m_Thread(new thread(boost::bind(&CPlayerHandler::ThreadFunc, this)))
{ }
CPlayerHandler::~CPlayerHandler()
{
m_ThreadRunning = false;
m_Thread->join();
delete m_Thread;
for(unordered_map<uint16_t, CPlayer *>::iterator i = m_Players.begin(), end = m_Players.end(); i != end; ++i)
(*i).second->Destroy();
}
CPlayer *CPlayerHandler::FindPlayer(uint16_t playerid)
{
CPlayer *player = nullptr;
unordered_map<uint16_t, CPlayer *>::iterator i;
if( (i = m_Players.find(playerid)) != m_Players.end())
player = i->second;
return player;
}
void CPlayerHandler::UpdateAll()
{
for(unordered_map<uint16_t, CPlayer *>::iterator i = m_Players.begin(), end = m_Players.end(); i != end; ++i)
i->second->Update();
}
void CPlayerHandler::ThreadFunc()
{
m_ThreadRunning = true;
while(m_ThreadRunning)
{
for(unordered_map<uint16_t, CPlayer *>::iterator i = m_Players.begin(), end = m_Players.end(); i != end; ++i) //very bad
{
CVehicleHandler::Get()->StreamAll(i->second);
}
this_thread::sleep_for(chrono::milliseconds(10));
}
}
void CPlayer::Update()
{
if(m_DataLock == true)
return ;
float tmp_pos[3];
GetPlayerCameraPos(m_Id, &m_CameraPos[0], &m_CameraPos[1], &m_CameraPos[2]);
GetPlayerCameraFrontVector(m_Id, &m_CameraDir[0], &m_CameraDir[1], &m_CameraDir[2]);
m_CameraMode = GetPlayerCameraMode(m_Id);
GetPlayerPos(m_Id, &tmp_pos[0], &tmp_pos[1], &tmp_pos[2]);
m_Pos = point(tmp_pos[0], tmp_pos[1], tmp_pos[2]);
GetPlayerVelocity(m_Id, &m_Velocity[0], &m_Velocity[1], &m_Velocity[2]);
}
bool CPlayer::IsInSight(float x, float y, float z)
{
bool ret_val = false;
m_DataLock = true;
float camera_angle = 0.0f;
switch (m_CameraMode)
{
case 4:
camera_angle = 41.5f;
break;
default:
break;
}
float
scal_prod,
vec_len;
x -= m_CameraPos[0];
y -= m_CameraPos[1];
z -= m_CameraPos[2];
scal_prod = (m_CameraDir[0] * x) + (m_CameraDir[1] * y) + (m_CameraDir[2] * z);
vec_len = sqrtf(x*x + y*y + z*z);
float cal_angle = acosf(scal_prod / vec_len) * (180.0f / 3.14159265f);
ret_val = cal_angle <= camera_angle;
m_DataLock = false;
return ret_val;
}
|
simplify sight-check calculation
|
simplify sight-check calculation
we don't need to calculate the length of the camera's facing vector, it's a normalized vector (length always '1')
|
C++
|
mit
|
maddinat0r/samp-streamer,maddinat0r/samp-streamer
|
6b4ab62f90850bb5c5ea9b4e9703401f001dc0ab
|
tests/unit/ceed/test_ceed.cpp
|
tests/unit/ceed/test_ceed.cpp
|
// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "catch.hpp"
#include "mfem.hpp"
#include <fstream>
#include <iostream>
#include "../../../fem/libceed/ceed.hpp"
using namespace mfem;
namespace ceed_test
{
double coeff_function(const Vector &x)
{
return 1.0 + x[0]*x[0];
}
// Velocity coefficient
void velocity_function(const Vector &x, Vector &v)
{
int dim = x.Size();
switch (dim)
{
case 1: v(0) = 1.0; break;
case 2: v(0) = 1.0; v(1) = 1.0; break;
case 3: v(0) = 1.0; v(1) = 1.0; v(2) = 1.0; break;
}
}
static std::string getString(AssemblyLevel assembly)
{
switch (assembly)
{
case AssemblyLevel::NONE:
return "NONE";
break;
case AssemblyLevel::PARTIAL:
return "PARTIAL";
break;
case AssemblyLevel::ELEMENT:
return "ELEMENT";
break;
case AssemblyLevel::FULL:
return "FULL";
break;
case AssemblyLevel::LEGACYFULL:
return "LEGACYFULL";
break;
}
mfem_error("Unknown AssemblyLevel.");
return "";
}
static std::string getString(CeedCoeff coeff_type)
{
switch (coeff_type)
{
case CeedCoeff::Const:
return "Const";
break;
case CeedCoeff::Grid:
return "Grid";
break;
case CeedCoeff::Quad:
return "Quad";
break;
case CeedCoeff::VecConst:
return "VecConst";
break;
case CeedCoeff::VecGrid:
return "VecGrid";
break;
case CeedCoeff::VecQuad:
return "VecQuad";
break;
}
mfem_error("Unknown CeedCoeff.");
return "";
}
enum class Problem {Mass, Convection, Diffusion, VectorMass, VectorDiffusion};
static std::string getString(Problem pb)
{
switch (pb)
{
case Problem::Mass:
return "Mass";
break;
case Problem::Convection:
return "Convection";
break;
case Problem::Diffusion:
return "Diffusion";
break;
case Problem::VectorMass:
return "VectorMass";
break;
case Problem::VectorDiffusion:
return "VectorDiffusion";
break;
}
mfem_error("Unknown Problem.");
return "";
}
enum class NLProblem {Convection};
static std::string getString(NLProblem pb)
{
switch (pb)
{
case NLProblem::Convection:
return "Convection";
break;
}
}
static void InitCoeff(Mesh &mesh, FiniteElementCollection &fec, const int dim,
const CeedCoeff coeff_type, GridFunction *&gf,
FiniteElementSpace *& coeff_fes,
Coefficient *&coeff, VectorCoefficient *&vcoeff)
{
switch (coeff_type)
{
case CeedCoeff::Const:
coeff = new ConstantCoefficient(1.0);
break;
case CeedCoeff::Grid:
{
FunctionCoefficient f_coeff(coeff_function);
coeff_fes = new FiniteElementSpace(&mesh, &fec);
gf = new GridFunction(coeff_fes);
gf->ProjectCoefficient(f_coeff);
coeff = new GridFunctionCoefficient(gf);
break;
}
case CeedCoeff::Quad:
coeff = new FunctionCoefficient(coeff_function);
break;
case CeedCoeff::VecConst:
{
Vector val(dim);
for (size_t i = 0; i < dim; i++)
{
val(i) = 1.0;
}
vcoeff = new VectorConstantCoefficient(val);
break;
}
case CeedCoeff::VecGrid:
{
VectorFunctionCoefficient f_vcoeff(dim, velocity_function);
coeff_fes = new FiniteElementSpace(&mesh, &fec, dim);
gf = new GridFunction(coeff_fes);
gf->ProjectCoefficient(f_vcoeff);
vcoeff = new VectorGridFunctionCoefficient(gf);
break;
}
case CeedCoeff::VecQuad:
vcoeff = new VectorFunctionCoefficient(dim, velocity_function);
break;
}
}
void test_ceed_operator(const char* input, int order, const CeedCoeff coeff_type,
const Problem pb, const AssemblyLevel assembly)
{
std::string section = "assembly: " + getString(assembly) + "\n" +
"coeff_type: " + getString(coeff_type) + "\n" +
"pb: " + getString(pb) + "\n" +
"order: " + std::to_string(order) + "\n" +
"mesh: " + input;
INFO(section);
Mesh mesh(input, 1, 1);
mesh.EnsureNodes();
int dim = mesh.Dimension();
H1_FECollection fec(order, dim);
// Coefficient Initialization
GridFunction *gf = nullptr;
FiniteElementSpace *coeff_fes = nullptr;
Coefficient *coeff = nullptr;
VectorCoefficient *vcoeff = nullptr;
InitCoeff(mesh, fec, dim, coeff_type, gf, coeff_fes, coeff, vcoeff);
// Build the BilinearForm
bool vecOp = pb == Problem::VectorMass || pb == Problem::VectorDiffusion;
const int vdim = vecOp ? dim : 1;
FiniteElementSpace fes(&mesh, &fec, vdim);
BilinearForm k_test(&fes);
BilinearForm k_ref(&fes);
switch (pb)
{
case Problem::Mass:
k_ref.AddDomainIntegrator(new MassIntegrator(*coeff));
k_test.AddDomainIntegrator(new MassIntegrator(*coeff));
break;
case Problem::Convection:
k_ref.AddDomainIntegrator(new ConvectionIntegrator(*vcoeff));
k_test.AddDomainIntegrator(new ConvectionIntegrator(*vcoeff));
break;
case Problem::Diffusion:
k_ref.AddDomainIntegrator(new DiffusionIntegrator(*coeff));
k_test.AddDomainIntegrator(new DiffusionIntegrator(*coeff));
break;
case Problem::VectorMass:
k_ref.AddDomainIntegrator(new VectorMassIntegrator(*coeff));
k_test.AddDomainIntegrator(new VectorMassIntegrator(*coeff));
break;
case Problem::VectorDiffusion:
k_ref.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff));
k_test.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff));
break;
}
k_ref.Assemble();
k_ref.Finalize();
k_test.SetAssemblyLevel(assembly);
k_test.Assemble();
// Compare ceed with mfem.
GridFunction x(&fes), y_ref(&fes), y_test(&fes);
x.Randomize(1);
k_ref.Mult(x,y_ref);
k_test.Mult(x,y_test);
y_test -= y_ref;
REQUIRE(y_test.Norml2() < 1.e-12);
delete gf;
delete coeff_fes;
delete coeff;
delete vcoeff;
}
void test_ceed_nloperator(const char* input, int order, const CeedCoeff coeff_type,
const NLProblem pb, const AssemblyLevel assembly)
{
std::string section = "assembly: " + getString(assembly) + "\n" +
"coeff_type: " + getString(coeff_type) + "\n" +
"pb: " + getString(pb) + "\n" +
"order: " + std::to_string(order) + "\n" +
"mesh: " + input;
INFO(section);
Mesh mesh(input, 1, 1);
mesh.EnsureNodes();
int dim = mesh.Dimension();
H1_FECollection fec(order, dim);
// Coefficient Initialization
GridFunction *gf = nullptr;
FiniteElementSpace *coeff_fes = nullptr;
Coefficient *coeff = nullptr;
VectorCoefficient *vcoeff = nullptr;
InitCoeff(mesh, fec, dim, coeff_type, gf, coeff_fes, coeff, vcoeff);
// Build the NonlinearForm
bool vecOp = pb == NLProblem::Convection;
const int vdim = vecOp ? dim : 1;
FiniteElementSpace fes(&mesh, &fec, vdim);
NonlinearForm k_test(&fes);
NonlinearForm k_ref(&fes);
switch (pb)
{
case NLProblem::Convection:
k_ref.AddDomainIntegrator(new VectorConvectionNLFIntegrator(*coeff));
k_test.AddDomainIntegrator(new VectorConvectionNLFIntegrator(*coeff));
break;
}
k_test.SetAssemblyLevel(assembly);
k_test.Setup();
k_ref.Setup();
// Compare ceed with mfem.
GridFunction x(&fes), y_ref(&fes), y_test(&fes);
x.Randomize(1);
k_ref.Mult(x,y_ref);
k_test.Mult(x,y_test);
y_test -= y_ref;
REQUIRE(y_test.Norml2() < 1.e-12);
delete gf;
delete coeff_fes;
delete coeff;
delete vcoeff;
}
TEST_CASE("CEED mass & diffusion", "[CEED mass & diffusion]")
{
auto assembly = GENERATE(AssemblyLevel::PARTIAL,AssemblyLevel::NONE);
auto coeff_type = GENERATE(CeedCoeff::Const,CeedCoeff::Grid,CeedCoeff::Quad);
auto pb = GENERATE(Problem::Mass,Problem::Diffusion,
Problem::VectorMass,Problem::VectorDiffusion);
auto order = GENERATE(1,2,3);
auto mesh = GENERATE("../../data/inline-quad.mesh","../../data/inline-hex.mesh",
"../../data/periodic-square.mesh",
"../../data/star-q2.mesh","../../data/fichera-q2.mesh",
"../../data/amr-quad.mesh","../../data/fichera-amr.mesh");
test_ceed_operator(mesh, order, coeff_type, pb, assembly);
} // test case
TEST_CASE("CEED convection", "[CEED convection]")
{
auto assembly = GENERATE(AssemblyLevel::PARTIAL,AssemblyLevel::NONE);
auto coeff_type = GENERATE(CeedCoeff::VecConst,CeedCoeff::VecGrid,
CeedCoeff::VecQuad);
auto pb = GENERATE(Problem::Convection);
auto order = GENERATE(1,2,3);
auto mesh = GENERATE("../../data/inline-quad.mesh","../../data/inline-hex.mesh",
"../../data/star-q2.mesh","../../data/fichera-q2.mesh",
"../../data/amr-quad.mesh","../../data/fichera-amr.mesh");
test_ceed_operator(mesh, order, coeff_type, pb, assembly);
} // test case
TEST_CASE("CEED non-linear convection", "[CEED nlconvection]")
{
auto assembly = GENERATE(AssemblyLevel::PARTIAL,AssemblyLevel::NONE);
auto coeff_type = GENERATE(CeedCoeff::Const,CeedCoeff::Grid,CeedCoeff::Quad);
auto pb = GENERATE(NLProblem::Convection);
auto order = GENERATE(1,2,3);
auto mesh = GENERATE("../../data/inline-quad.mesh",
"../../data/inline-hex.mesh",
"../../data/periodic-square.mesh",
"../../data/star-q2.mesh");
test_ceed_nloperator(mesh, order, coeff_type, pb, assembly);
} // test case
} // namespace ceed_test
|
// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced
// at the Lawrence Livermore National Laboratory. All Rights reserved. See files
// LICENSE and NOTICE for details. LLNL-CODE-806117.
//
// This file is part of the MFEM library. For more information and source code
// availability visit https://mfem.org.
//
// MFEM is free software; you can redistribute it and/or modify it under the
// terms of the BSD-3 license. We welcome feedback and contributions, see file
// CONTRIBUTING.md for details.
#include "catch.hpp"
#include "mfem.hpp"
#include <fstream>
#include <iostream>
#include "../../../fem/libceed/ceed.hpp"
using namespace mfem;
namespace ceed_test
{
double coeff_function(const Vector &x)
{
return 1.0 + x[0]*x[0];
}
// Velocity coefficient
void velocity_function(const Vector &x, Vector &v)
{
int dim = x.Size();
switch (dim)
{
case 1: v(0) = 1.0; break;
case 2: v(0) = 1.0; v(1) = 1.0; break;
case 3: v(0) = 1.0; v(1) = 1.0; v(2) = 1.0; break;
}
}
static std::string getString(AssemblyLevel assembly)
{
switch (assembly)
{
case AssemblyLevel::NONE:
return "NONE";
break;
case AssemblyLevel::PARTIAL:
return "PARTIAL";
break;
case AssemblyLevel::ELEMENT:
return "ELEMENT";
break;
case AssemblyLevel::FULL:
return "FULL";
break;
case AssemblyLevel::LEGACYFULL:
return "LEGACYFULL";
break;
}
mfem_error("Unknown AssemblyLevel.");
return "";
}
static std::string getString(CeedCoeff coeff_type)
{
switch (coeff_type)
{
case CeedCoeff::Const:
return "Const";
break;
case CeedCoeff::Grid:
return "Grid";
break;
case CeedCoeff::Quad:
return "Quad";
break;
case CeedCoeff::VecConst:
return "VecConst";
break;
case CeedCoeff::VecGrid:
return "VecGrid";
break;
case CeedCoeff::VecQuad:
return "VecQuad";
break;
}
mfem_error("Unknown CeedCoeff.");
return "";
}
enum class Problem {Mass, Convection, Diffusion, VectorMass, VectorDiffusion};
static std::string getString(Problem pb)
{
switch (pb)
{
case Problem::Mass:
return "Mass";
break;
case Problem::Convection:
return "Convection";
break;
case Problem::Diffusion:
return "Diffusion";
break;
case Problem::VectorMass:
return "VectorMass";
break;
case Problem::VectorDiffusion:
return "VectorDiffusion";
break;
}
mfem_error("Unknown Problem.");
return "";
}
enum class NLProblem {Convection};
static std::string getString(NLProblem pb)
{
switch (pb)
{
case NLProblem::Convection:
return "Convection";
break;
}
}
static void InitCoeff(Mesh &mesh, FiniteElementCollection &fec, const int dim,
const CeedCoeff coeff_type, GridFunction *&gf,
FiniteElementSpace *& coeff_fes,
Coefficient *&coeff, VectorCoefficient *&vcoeff)
{
switch (coeff_type)
{
case CeedCoeff::Const:
coeff = new ConstantCoefficient(1.0);
break;
case CeedCoeff::Grid:
{
FunctionCoefficient f_coeff(coeff_function);
coeff_fes = new FiniteElementSpace(&mesh, &fec);
gf = new GridFunction(coeff_fes);
gf->ProjectCoefficient(f_coeff);
coeff = new GridFunctionCoefficient(gf);
break;
}
case CeedCoeff::Quad:
coeff = new FunctionCoefficient(coeff_function);
break;
case CeedCoeff::VecConst:
{
Vector val(dim);
for (size_t i = 0; i < dim; i++)
{
val(i) = 1.0;
}
vcoeff = new VectorConstantCoefficient(val);
break;
}
case CeedCoeff::VecGrid:
{
VectorFunctionCoefficient f_vcoeff(dim, velocity_function);
coeff_fes = new FiniteElementSpace(&mesh, &fec, dim);
gf = new GridFunction(coeff_fes);
gf->ProjectCoefficient(f_vcoeff);
vcoeff = new VectorGridFunctionCoefficient(gf);
break;
}
case CeedCoeff::VecQuad:
vcoeff = new VectorFunctionCoefficient(dim, velocity_function);
break;
}
}
void test_ceed_operator(const char* input, int order, const CeedCoeff coeff_type,
const Problem pb, const AssemblyLevel assembly)
{
std::string section = "assembly: " + getString(assembly) + "\n" +
"coeff_type: " + getString(coeff_type) + "\n" +
"pb: " + getString(pb) + "\n" +
"order: " + std::to_string(order) + "\n" +
"mesh: " + input;
INFO(section);
Mesh mesh(input, 1, 1);
mesh.EnsureNodes();
int dim = mesh.Dimension();
H1_FECollection fec(order, dim);
// Coefficient Initialization
GridFunction *gf = nullptr;
FiniteElementSpace *coeff_fes = nullptr;
Coefficient *coeff = nullptr;
VectorCoefficient *vcoeff = nullptr;
InitCoeff(mesh, fec, dim, coeff_type, gf, coeff_fes, coeff, vcoeff);
// Build the BilinearForm
bool vecOp = pb == Problem::VectorMass || pb == Problem::VectorDiffusion;
const int vdim = vecOp ? dim : 1;
FiniteElementSpace fes(&mesh, &fec, vdim);
BilinearForm k_test(&fes);
BilinearForm k_ref(&fes);
switch (pb)
{
case Problem::Mass:
k_ref.AddDomainIntegrator(new MassIntegrator(*coeff));
k_test.AddDomainIntegrator(new MassIntegrator(*coeff));
break;
case Problem::Convection:
k_ref.AddDomainIntegrator(new ConvectionIntegrator(*vcoeff));
k_test.AddDomainIntegrator(new ConvectionIntegrator(*vcoeff));
break;
case Problem::Diffusion:
k_ref.AddDomainIntegrator(new DiffusionIntegrator(*coeff));
k_test.AddDomainIntegrator(new DiffusionIntegrator(*coeff));
break;
case Problem::VectorMass:
k_ref.AddDomainIntegrator(new VectorMassIntegrator(*coeff));
k_test.AddDomainIntegrator(new VectorMassIntegrator(*coeff));
break;
case Problem::VectorDiffusion:
k_ref.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff));
k_test.AddDomainIntegrator(new VectorDiffusionIntegrator(*coeff));
break;
}
k_ref.Assemble();
k_ref.Finalize();
k_test.SetAssemblyLevel(assembly);
k_test.Assemble();
// Compare ceed with mfem.
GridFunction x(&fes), y_ref(&fes), y_test(&fes);
x.Randomize(1);
k_ref.Mult(x,y_ref);
k_test.Mult(x,y_test);
y_test -= y_ref;
REQUIRE(y_test.Norml2() < 1.e-12);
delete gf;
delete coeff_fes;
delete coeff;
delete vcoeff;
}
void test_ceed_nloperator(const char* input, int order, const CeedCoeff coeff_type,
const NLProblem pb, const AssemblyLevel assembly)
{
std::string section = "assembly: " + getString(assembly) + "\n" +
"coeff_type: " + getString(coeff_type) + "\n" +
"pb: " + getString(pb) + "\n" +
"order: " + std::to_string(order) + "\n" +
"mesh: " + input;
INFO(section);
Mesh mesh(input, 1, 1);
mesh.EnsureNodes();
int dim = mesh.Dimension();
H1_FECollection fec(order, dim);
// Coefficient Initialization
GridFunction *gf = nullptr;
FiniteElementSpace *coeff_fes = nullptr;
Coefficient *coeff = nullptr;
VectorCoefficient *vcoeff = nullptr;
InitCoeff(mesh, fec, dim, coeff_type, gf, coeff_fes, coeff, vcoeff);
// Build the NonlinearForm
bool vecOp = pb == NLProblem::Convection;
const int vdim = vecOp ? dim : 1;
FiniteElementSpace fes(&mesh, &fec, vdim);
NonlinearForm k_test(&fes);
NonlinearForm k_ref(&fes);
switch (pb)
{
case NLProblem::Convection:
k_ref.AddDomainIntegrator(new VectorConvectionNLFIntegrator(*coeff));
k_test.AddDomainIntegrator(new VectorConvectionNLFIntegrator(*coeff));
break;
}
k_test.SetAssemblyLevel(assembly);
k_test.Setup();
k_ref.Setup();
// Compare ceed with mfem.
GridFunction x(&fes), y_ref(&fes), y_test(&fes);
x.Randomize(1);
k_ref.Mult(x,y_ref);
k_test.Mult(x,y_test);
y_test -= y_ref;
REQUIRE(y_test.Norml2() < 1.e-12);
delete gf;
delete coeff_fes;
delete coeff;
delete vcoeff;
}
TEST_CASE("CEED mass & diffusion", "[CEED mass & diffusion]")
{
auto assembly = GENERATE(AssemblyLevel::PARTIAL,AssemblyLevel::NONE);
auto coeff_type = GENERATE(CeedCoeff::Const,CeedCoeff::Grid,CeedCoeff::Quad);
auto pb = GENERATE(Problem::Mass,Problem::Diffusion,
Problem::VectorMass,Problem::VectorDiffusion);
auto order = GENERATE(1,2,3);
auto mesh = GENERATE("../../data/inline-quad.mesh","../../data/inline-hex.mesh",
"../../data/periodic-square.mesh",
"../../data/star-q2.mesh","../../data/fichera-q2.mesh",
"../../data/amr-quad.mesh","../../data/fichera-amr.mesh");
test_ceed_operator(mesh, order, coeff_type, pb, assembly);
} // test case
TEST_CASE("CEED convection", "[CEED convection]")
{
auto assembly = GENERATE(AssemblyLevel::PARTIAL,AssemblyLevel::NONE);
auto coeff_type = GENERATE(CeedCoeff::VecConst,CeedCoeff::VecGrid,
CeedCoeff::VecQuad);
auto pb = GENERATE(Problem::Convection);
auto order = GENERATE(1,2,3);
auto mesh = GENERATE("../../data/inline-quad.mesh","../../data/inline-hex.mesh",
"../../data/star-q2.mesh","../../data/fichera-q2.mesh",
"../../data/amr-quad.mesh","../../data/fichera-amr.mesh");
test_ceed_operator(mesh, order, coeff_type, pb, assembly);
} // test case
TEST_CASE("CEED non-linear convection", "[CEED nlconvection]")
{
auto assembly = GENERATE(AssemblyLevel::PARTIAL,AssemblyLevel::NONE);
auto coeff_type = GENERATE(CeedCoeff::Const,CeedCoeff::Grid,CeedCoeff::Quad);
auto pb = GENERATE(NLProblem::Convection);
auto order = GENERATE(1,2,3);
auto mesh = GENERATE("../../data/inline-quad.mesh",
"../../data/inline-hex.mesh",
"../../data/periodic-square.mesh",
"../../data/star-q2.mesh",
"../../data/fichera.mesh");
test_ceed_nloperator(mesh, order, coeff_type, pb, assembly);
} // test case
} // namespace ceed_test
|
Add fichera.mesh to the test for nlconvection.
|
Add fichera.mesh to the test for nlconvection.
|
C++
|
bsd-3-clause
|
mfem/mfem,mfem/mfem,mfem/mfem,mfem/mfem,mfem/mfem
|
775627473afaed32e7f90bc29fdad1e39848633b
|
Extractor/XMLParser.cpp
|
Extractor/XMLParser.cpp
|
/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
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.
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 "XMLParser.h"
#include "ExtractionWay.h"
#include "../DataStructures/HashTable.h"
#include "../DataStructures/ImportNode.h"
#include "../DataStructures/InputReaderFactory.h"
#include "../DataStructures/Restriction.h"
#include "../Util/SimpleLogger.h"
#include "../Util/StringUtil.h"
#include "../typedefs.h"
#include <osrm/Coordinate.h>
#include <boost/ref.hpp>
XMLParser::XMLParser(const char * filename, ExtractorCallbacks* ec, ScriptingEnvironment& se) : BaseParser(ec, se) {
SimpleLogger().Write(logWARNING) <<
"Parsing plain .osm/.osm.bz2 is deprecated. Switch to .pbf";
inputReader = inputReaderFactory(filename);
}
bool XMLParser::ReadHeader() {
return (xmlTextReaderRead( inputReader ) == 1);
}
bool XMLParser::Parse() {
while ( xmlTextReaderRead( inputReader ) == 1 ) {
const int type = xmlTextReaderNodeType( inputReader );
//1 is Element
if ( type != 1 ) {
continue;
}
xmlChar* currentName = xmlTextReaderName( inputReader );
if ( currentName == NULL ) {
continue;
}
if ( xmlStrEqual( currentName, ( const xmlChar* ) "node" ) == 1 ) {
ImportNode n = _ReadXMLNode();
ParseNodeInLua( n, lua_state );
extractor_callbacks->nodeFunction(n);
// if(!extractor_callbacks->nodeFunction(n))
// std::cerr << "[XMLParser] dense node not parsed" << std::endl;
}
if ( xmlStrEqual( currentName, ( const xmlChar* ) "way" ) == 1 ) {
ExtractionWay way = _ReadXMLWay( );
ParseWayInLua( way, lua_state );
extractor_callbacks->wayFunction(way);
// if(!extractor_callbacks->wayFunction(way))
// std::cerr << "[PBFParser] way not parsed" << std::endl;
}
if( use_turn_restrictions ) {
if ( xmlStrEqual( currentName, ( const xmlChar* ) "relation" ) == 1 ) {
InputRestrictionContainer r = _ReadXMLRestriction();
if(r.fromWay != UINT_MAX) {
if(!extractor_callbacks->restrictionFunction(r)) {
std::cerr << "[XMLParser] restriction not parsed" << std::endl;
}
}
}
}
xmlFree( currentName );
}
return true;
}
InputRestrictionContainer XMLParser::_ReadXMLRestriction() {
InputRestrictionContainer restriction;
std::string except_tag_string;
if ( xmlTextReaderIsEmptyElement( inputReader ) != 1 ) {
const int depth = xmlTextReaderDepth( inputReader );while ( xmlTextReaderRead( inputReader ) == 1 ) {
const int childType = xmlTextReaderNodeType( inputReader );
if ( childType != 1 && childType != 15 ) {
continue;
}
const int childDepth = xmlTextReaderDepth( inputReader );
xmlChar* childName = xmlTextReaderName( inputReader );
if ( childName == NULL ) {
continue;
}
if ( depth == childDepth && childType == 15 && xmlStrEqual( childName, ( const xmlChar* ) "relation" ) == 1 ) {
xmlFree( childName );
break;
}
if ( childType != 1 ) {
xmlFree( childName );
continue;
}
if ( xmlStrEqual( childName, ( const xmlChar* ) "tag" ) == 1 ) {
xmlChar* k = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "k" );
xmlChar* value = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "v" );
if ( k != NULL && value != NULL ) {
if(xmlStrEqual(k, ( const xmlChar* ) "restriction" )){
if(0 == std::string((const char *) value).find("only_")) {
restriction.restriction.flags.isOnly = true;
}
}
if ( xmlStrEqual(k, (const xmlChar *) "except") ) {
except_tag_string = (const char*) value;
}
}
if ( k != NULL ) {
xmlFree( k );
}
if ( value != NULL ) {
xmlFree( value );
}
} else if ( xmlStrEqual( childName, ( const xmlChar* ) "member" ) == 1 ) {
xmlChar* ref = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "ref" );
if ( ref != NULL ) {
xmlChar * role = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "role" );
xmlChar * type = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "type" );
if(xmlStrEqual(role, (const xmlChar *) "to") && xmlStrEqual(type, (const xmlChar *) "way")) {
restriction.toWay = stringToUint((const char*) ref);
}
if(xmlStrEqual(role, (const xmlChar *) "from") && xmlStrEqual(type, (const xmlChar *) "way")) {
restriction.fromWay = stringToUint((const char*) ref);
}
if(xmlStrEqual(role, (const xmlChar *) "via") && xmlStrEqual(type, (const xmlChar *) "node")) {
restriction.restriction.viaNode = stringToUint((const char*) ref);
}
if(NULL != type) {
xmlFree( type );
}
if(NULL != role) {
xmlFree( role );
}
if(NULL != ref) {
xmlFree( ref );
}
}
}
xmlFree( childName );
}
}
if( ShouldIgnoreRestriction(except_tag_string) ) {
restriction.fromWay = UINT_MAX; //workaround to ignore the restriction
}
return restriction;
}
ExtractionWay XMLParser::_ReadXMLWay() {
ExtractionWay way;
if ( xmlTextReaderIsEmptyElement( inputReader ) != 1 ) {
const int depth = xmlTextReaderDepth( inputReader );
while ( xmlTextReaderRead( inputReader ) == 1 ) {
const int childType = xmlTextReaderNodeType( inputReader );
if ( childType != 1 && childType != 15 ) {
continue;
}
const int childDepth = xmlTextReaderDepth( inputReader );
xmlChar* childName = xmlTextReaderName( inputReader );
if ( childName == NULL ) {
continue;
}
if ( depth == childDepth && childType == 15 && xmlStrEqual( childName, ( const xmlChar* ) "way" ) == 1 ) {
xmlChar* id = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "id" );
way.id = stringToUint((char*)id);
xmlFree(id);
xmlFree( childName );
break;
}
if ( childType != 1 ) {
xmlFree( childName );
continue;
}
if ( xmlStrEqual( childName, ( const xmlChar* ) "tag" ) == 1 ) {
xmlChar* k = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "k" );
xmlChar* value = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "v" );
// cout << "->k=" << k << ", v=" << value << endl;
if ( k != NULL && value != NULL ) {
way.keyVals.Add(std::string( (char *) k ), std::string( (char *) value));
}
if ( k != NULL ) {
xmlFree( k );
}
if ( value != NULL ) {
xmlFree( value );
}
} else if ( xmlStrEqual( childName, ( const xmlChar* ) "nd" ) == 1 ) {
xmlChar* ref = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "ref" );
if ( ref != NULL ) {
way.path.push_back( stringToUint(( const char* ) ref ) );
xmlFree( ref );
}
}
xmlFree( childName );
}
}
return way;
}
ImportNode XMLParser::_ReadXMLNode() {
ImportNode node;
xmlChar* attribute = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "lat" );
if ( attribute != NULL ) {
node.lat = static_cast<NodeID>(COORDINATE_PRECISION*atof(( const char* ) attribute ) );
xmlFree( attribute );
}
attribute = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "lon" );
if ( attribute != NULL ) {
node.lon = static_cast<NodeID>(COORDINATE_PRECISION*atof(( const char* ) attribute ));
xmlFree( attribute );
}
attribute = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "id" );
if ( attribute != NULL ) {
node.id = stringToUint(( const char* ) attribute );
xmlFree( attribute );
}
if ( xmlTextReaderIsEmptyElement( inputReader ) != 1 ) {
const int depth = xmlTextReaderDepth( inputReader );
while ( xmlTextReaderRead( inputReader ) == 1 ) {
const int childType = xmlTextReaderNodeType( inputReader );
// 1 = Element, 15 = EndElement
if ( childType != 1 && childType != 15 ) {
continue;
}
const int childDepth = xmlTextReaderDepth( inputReader );
xmlChar* childName = xmlTextReaderName( inputReader );
if ( childName == NULL ) {
continue;
}
if ( depth == childDepth && childType == 15 && xmlStrEqual( childName, ( const xmlChar* ) "node" ) == 1 ) {
xmlFree( childName );
break;
}
if ( childType != 1 ) {
xmlFree( childName );
continue;
}
if ( xmlStrEqual( childName, ( const xmlChar* ) "tag" ) == 1 ) {
xmlChar* k = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "k" );
xmlChar* value = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "v" );
if ( k != NULL && value != NULL ) {
node.keyVals.Add(std::string( reinterpret_cast<char*>(k) ), std::string( reinterpret_cast<char*>(value)));
}
if ( k != NULL ) {
xmlFree( k );
}
if ( value != NULL ) {
xmlFree( value );
}
}
xmlFree( childName );
}
}
return node;
}
|
/*
Copyright (c) 2013, Project OSRM, Dennis Luxen, others
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.
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 "XMLParser.h"
#include "ExtractionWay.h"
#include "../DataStructures/HashTable.h"
#include "../DataStructures/ImportNode.h"
#include "../DataStructures/InputReaderFactory.h"
#include "../DataStructures/Restriction.h"
#include "../Util/SimpleLogger.h"
#include "../Util/StringUtil.h"
#include "../typedefs.h"
#include <osrm/Coordinate.h>
#include <boost/ref.hpp>
XMLParser::XMLParser(const char * filename, ExtractorCallbacks* ec, ScriptingEnvironment& se) : BaseParser(ec, se) {
inputReader = inputReaderFactory(filename);
}
bool XMLParser::ReadHeader() {
return (xmlTextReaderRead( inputReader ) == 1);
}
bool XMLParser::Parse() {
while ( xmlTextReaderRead( inputReader ) == 1 ) {
const int type = xmlTextReaderNodeType( inputReader );
//1 is Element
if ( type != 1 ) {
continue;
}
xmlChar* currentName = xmlTextReaderName( inputReader );
if ( currentName == NULL ) {
continue;
}
if ( xmlStrEqual( currentName, ( const xmlChar* ) "node" ) == 1 ) {
ImportNode n = _ReadXMLNode();
ParseNodeInLua( n, lua_state );
extractor_callbacks->nodeFunction(n);
// if(!extractor_callbacks->nodeFunction(n))
// std::cerr << "[XMLParser] dense node not parsed" << std::endl;
}
if ( xmlStrEqual( currentName, ( const xmlChar* ) "way" ) == 1 ) {
ExtractionWay way = _ReadXMLWay( );
ParseWayInLua( way, lua_state );
extractor_callbacks->wayFunction(way);
// if(!extractor_callbacks->wayFunction(way))
// std::cerr << "[PBFParser] way not parsed" << std::endl;
}
if( use_turn_restrictions ) {
if ( xmlStrEqual( currentName, ( const xmlChar* ) "relation" ) == 1 ) {
InputRestrictionContainer r = _ReadXMLRestriction();
if(r.fromWay != UINT_MAX) {
if(!extractor_callbacks->restrictionFunction(r)) {
std::cerr << "[XMLParser] restriction not parsed" << std::endl;
}
}
}
}
xmlFree( currentName );
}
return true;
}
InputRestrictionContainer XMLParser::_ReadXMLRestriction() {
InputRestrictionContainer restriction;
std::string except_tag_string;
if ( xmlTextReaderIsEmptyElement( inputReader ) != 1 ) {
const int depth = xmlTextReaderDepth( inputReader );while ( xmlTextReaderRead( inputReader ) == 1 ) {
const int childType = xmlTextReaderNodeType( inputReader );
if ( childType != 1 && childType != 15 ) {
continue;
}
const int childDepth = xmlTextReaderDepth( inputReader );
xmlChar* childName = xmlTextReaderName( inputReader );
if ( childName == NULL ) {
continue;
}
if ( depth == childDepth && childType == 15 && xmlStrEqual( childName, ( const xmlChar* ) "relation" ) == 1 ) {
xmlFree( childName );
break;
}
if ( childType != 1 ) {
xmlFree( childName );
continue;
}
if ( xmlStrEqual( childName, ( const xmlChar* ) "tag" ) == 1 ) {
xmlChar* k = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "k" );
xmlChar* value = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "v" );
if ( k != NULL && value != NULL ) {
if(xmlStrEqual(k, ( const xmlChar* ) "restriction" )){
if(0 == std::string((const char *) value).find("only_")) {
restriction.restriction.flags.isOnly = true;
}
}
if ( xmlStrEqual(k, (const xmlChar *) "except") ) {
except_tag_string = (const char*) value;
}
}
if ( k != NULL ) {
xmlFree( k );
}
if ( value != NULL ) {
xmlFree( value );
}
} else if ( xmlStrEqual( childName, ( const xmlChar* ) "member" ) == 1 ) {
xmlChar* ref = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "ref" );
if ( ref != NULL ) {
xmlChar * role = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "role" );
xmlChar * type = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "type" );
if(xmlStrEqual(role, (const xmlChar *) "to") && xmlStrEqual(type, (const xmlChar *) "way")) {
restriction.toWay = stringToUint((const char*) ref);
}
if(xmlStrEqual(role, (const xmlChar *) "from") && xmlStrEqual(type, (const xmlChar *) "way")) {
restriction.fromWay = stringToUint((const char*) ref);
}
if(xmlStrEqual(role, (const xmlChar *) "via") && xmlStrEqual(type, (const xmlChar *) "node")) {
restriction.restriction.viaNode = stringToUint((const char*) ref);
}
if(NULL != type) {
xmlFree( type );
}
if(NULL != role) {
xmlFree( role );
}
if(NULL != ref) {
xmlFree( ref );
}
}
}
xmlFree( childName );
}
}
if( ShouldIgnoreRestriction(except_tag_string) ) {
restriction.fromWay = UINT_MAX; //workaround to ignore the restriction
}
return restriction;
}
ExtractionWay XMLParser::_ReadXMLWay() {
ExtractionWay way;
if ( xmlTextReaderIsEmptyElement( inputReader ) != 1 ) {
const int depth = xmlTextReaderDepth( inputReader );
while ( xmlTextReaderRead( inputReader ) == 1 ) {
const int childType = xmlTextReaderNodeType( inputReader );
if ( childType != 1 && childType != 15 ) {
continue;
}
const int childDepth = xmlTextReaderDepth( inputReader );
xmlChar* childName = xmlTextReaderName( inputReader );
if ( childName == NULL ) {
continue;
}
if ( depth == childDepth && childType == 15 && xmlStrEqual( childName, ( const xmlChar* ) "way" ) == 1 ) {
xmlChar* id = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "id" );
way.id = stringToUint((char*)id);
xmlFree(id);
xmlFree( childName );
break;
}
if ( childType != 1 ) {
xmlFree( childName );
continue;
}
if ( xmlStrEqual( childName, ( const xmlChar* ) "tag" ) == 1 ) {
xmlChar* k = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "k" );
xmlChar* value = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "v" );
// cout << "->k=" << k << ", v=" << value << endl;
if ( k != NULL && value != NULL ) {
way.keyVals.Add(std::string( (char *) k ), std::string( (char *) value));
}
if ( k != NULL ) {
xmlFree( k );
}
if ( value != NULL ) {
xmlFree( value );
}
} else if ( xmlStrEqual( childName, ( const xmlChar* ) "nd" ) == 1 ) {
xmlChar* ref = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "ref" );
if ( ref != NULL ) {
way.path.push_back( stringToUint(( const char* ) ref ) );
xmlFree( ref );
}
}
xmlFree( childName );
}
}
return way;
}
ImportNode XMLParser::_ReadXMLNode() {
ImportNode node;
xmlChar* attribute = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "lat" );
if ( attribute != NULL ) {
node.lat = static_cast<NodeID>(COORDINATE_PRECISION*atof(( const char* ) attribute ) );
xmlFree( attribute );
}
attribute = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "lon" );
if ( attribute != NULL ) {
node.lon = static_cast<NodeID>(COORDINATE_PRECISION*atof(( const char* ) attribute ));
xmlFree( attribute );
}
attribute = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "id" );
if ( attribute != NULL ) {
node.id = stringToUint(( const char* ) attribute );
xmlFree( attribute );
}
if ( xmlTextReaderIsEmptyElement( inputReader ) != 1 ) {
const int depth = xmlTextReaderDepth( inputReader );
while ( xmlTextReaderRead( inputReader ) == 1 ) {
const int childType = xmlTextReaderNodeType( inputReader );
// 1 = Element, 15 = EndElement
if ( childType != 1 && childType != 15 ) {
continue;
}
const int childDepth = xmlTextReaderDepth( inputReader );
xmlChar* childName = xmlTextReaderName( inputReader );
if ( childName == NULL ) {
continue;
}
if ( depth == childDepth && childType == 15 && xmlStrEqual( childName, ( const xmlChar* ) "node" ) == 1 ) {
xmlFree( childName );
break;
}
if ( childType != 1 ) {
xmlFree( childName );
continue;
}
if ( xmlStrEqual( childName, ( const xmlChar* ) "tag" ) == 1 ) {
xmlChar* k = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "k" );
xmlChar* value = xmlTextReaderGetAttribute( inputReader, ( const xmlChar* ) "v" );
if ( k != NULL && value != NULL ) {
node.keyVals.Add(std::string( reinterpret_cast<char*>(k) ), std::string( reinterpret_cast<char*>(value)));
}
if ( k != NULL ) {
xmlFree( k );
}
if ( value != NULL ) {
xmlFree( value );
}
}
xmlFree( childName );
}
}
return node;
}
|
remove .osm deprecation warning
|
remove .osm deprecation warning
|
C++
|
bsd-2-clause
|
nagyistoce/osrm-backend,felixguendling/osrm-backend,antoinegiret/osrm-backend,jpizarrom/osrm-backend,duizendnegen/osrm-backend,prembasumatary/osrm-backend,bjtaylor1/osrm-backend,felixguendling/osrm-backend,agruss/osrm-backend,neilbu/osrm-backend,Project-OSRM/osrm-backend,Conggge/osrm-backend,yuryleb/osrm-backend,deniskoronchik/osrm-backend,arnekaiser/osrm-backend,beemogmbh/osrm-backend,Carsten64/OSRM-aux-git,ammeurer/osrm-backend,bjtaylor1/osrm-backend,ramyaragupathy/osrm-backend,ramyaragupathy/osrm-backend,antoinegiret/osrm-geovelo,hydrays/osrm-backend,antoinegiret/osrm-geovelo,neilbu/osrm-backend,Carsten64/OSRM-aux-git,bjtaylor1/osrm-backend,KnockSoftware/osrm-backend,prembasumatary/osrm-backend,neilbu/osrm-backend,agruss/osrm-backend,chaupow/osrm-backend,yuryleb/osrm-backend,jpizarrom/osrm-backend,Conggge/osrm-backend,agruss/osrm-backend,beemogmbh/osrm-backend,hydrays/osrm-backend,KnockSoftware/osrm-backend,alex85k/Project-OSRM,ammeurer/osrm-backend,Carsten64/OSRM-aux-git,yuryleb/osrm-backend,Project-OSRM/osrm-backend,bjtaylor1/Project-OSRM-Old,nagyistoce/osrm-backend,ammeurer/osrm-backend,hydrays/osrm-backend,frodrigo/osrm-backend,chaupow/osrm-backend,Tristramg/osrm-backend,antoinegiret/osrm-geovelo,arnekaiser/osrm-backend,prembasumatary/osrm-backend,bjtaylor1/Project-OSRM-Old,bjtaylor1/Project-OSRM-Old,atsuyim/osrm-backend,tkhaxton/osrm-backend,ammeurer/osrm-backend,raymond0/osrm-backend,neilbu/osrm-backend,bitsteller/osrm-backend,Project-OSRM/osrm-backend,chaupow/osrm-backend,skyborla/osrm-backend,beemogmbh/osrm-backend,antoinegiret/osrm-backend,jpizarrom/osrm-backend,oxidase/osrm-backend,arnekaiser/osrm-backend,arnekaiser/osrm-backend,deniskoronchik/osrm-backend,alex85k/Project-OSRM,duizendnegen/osrm-backend,deniskoronchik/osrm-backend,bjtaylor1/Project-OSRM-Old,beemogmbh/osrm-backend,alex85k/Project-OSRM,felixguendling/osrm-backend,atsuyim/osrm-backend,tkhaxton/osrm-backend,Tristramg/osrm-backend,stevevance/Project-OSRM,skyborla/osrm-backend,yuryleb/osrm-backend,nagyistoce/osrm-backend,hydrays/osrm-backend,duizendnegen/osrm-backend,oxidase/osrm-backend,ammeurer/osrm-backend,Conggge/osrm-backend,oxidase/osrm-backend,Project-OSRM/osrm-backend,frodrigo/osrm-backend,frodrigo/osrm-backend,Tristramg/osrm-backend,KnockSoftware/osrm-backend,atsuyim/osrm-backend,stevevance/Project-OSRM,Conggge/osrm-backend,tkhaxton/osrm-backend,raymond0/osrm-backend,raymond0/osrm-backend,ramyaragupathy/osrm-backend,bjtaylor1/osrm-backend,deniskoronchik/osrm-backend,oxidase/osrm-backend,raymond0/osrm-backend,bitsteller/osrm-backend,skyborla/osrm-backend,Carsten64/OSRM-aux-git,bitsteller/osrm-backend,ammeurer/osrm-backend,stevevance/Project-OSRM,stevevance/Project-OSRM,duizendnegen/osrm-backend,KnockSoftware/osrm-backend,antoinegiret/osrm-backend,ammeurer/osrm-backend,frodrigo/osrm-backend
|
0095aaf822346ac3bcb16b4587cd0751555aab1c
|
test/kernel/unit/memmap.cpp
|
test/kernel/unit/memmap.cpp
|
// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <common.cxx>
#include <kernel/memmap.hpp>
CASE ("Using the kernel memory map") {
GIVEN ("An instance of the memory map")
{
Memory_map map;
EXPECT(map.size() == 0);
THEN("You can insert a named range")
{
map.assign_range({0x1, 0xff, "Range 1", "The first range"});
EXPECT(map.size() == 1);
AND_THEN("You can check the size again and it's fucked")
{
EXPECT(map.size() == 1);
}
};
}
}
// We can't link against the 32-bit version of IncludeOS (os.a)
#include <kernel/memmap.cpp>
|
// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// 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 <common.cxx>
#include <kernel/memmap.hpp>
CASE ("Using the kernel memory map") {
GIVEN ("An instance of the memory map")
{
Memory_map map;
EXPECT(map.size() == 0);
THEN("You can insert a named range")
{
map.assign_range({0x1, 0xff, "Range 1", "The first range"});
EXPECT(map.size() == 1);
AND_THEN("You can check the size again and it's fucked")
{
EXPECT(map.size() == 1);
}
};
auto improved_implementation = false;
EXPECT(improved_implementation);
}
}
// We can't link against the 32-bit version of IncludeOS (os.a)
#include <kernel/memmap.cpp>
|
Make the unfinished memmap test fail
|
test: Make the unfinished memmap test fail
|
C++
|
apache-2.0
|
hioa-cs/IncludeOS,alfred-bratterud/IncludeOS,AndreasAakesson/IncludeOS,mnordsletten/IncludeOS,AndreasAakesson/IncludeOS,mnordsletten/IncludeOS,ingve/IncludeOS,ingve/IncludeOS,ingve/IncludeOS,hioa-cs/IncludeOS,ingve/IncludeOS,mnordsletten/IncludeOS,AnnikaH/IncludeOS,hioa-cs/IncludeOS,AndreasAakesson/IncludeOS,mnordsletten/IncludeOS,AnnikaH/IncludeOS,AnnikaH/IncludeOS,hioa-cs/IncludeOS,mnordsletten/IncludeOS,alfred-bratterud/IncludeOS,AnnikaH/IncludeOS,hioa-cs/IncludeOS,AndreasAakesson/IncludeOS,ingve/IncludeOS,mnordsletten/IncludeOS,alfred-bratterud/IncludeOS,AnnikaH/IncludeOS,alfred-bratterud/IncludeOS,AndreasAakesson/IncludeOS,AndreasAakesson/IncludeOS,alfred-bratterud/IncludeOS
|
7c014431e9d0d176381da2e3d5ff5e9dbb905539
|
src/NTClient.cc
|
src/NTClient.cc
|
#include "NTClient.h"
using namespace std;
NTClient::NTClient(int _wpm, double _accuracy) {
typeIntervalMS = 12000 / _wpm;
wpm = _wpm;
accuracy = _accuracy;
hasError = false;
firstConnect = true;
connected = false;
lessonLen = 0;
lidx = 0;
log = new NTLogger("(Not logged in)");
wsh = nullptr;
}
NTClient::~NTClient() {
if (log != nullptr) {
delete log;
}
if (wsh != nullptr) {
delete wsh;
wsh = nullptr;
}
}
bool NTClient::login(string username, string password) {
log->type(LOG_HTTP);
log->wr("Logging into the NitroType account...\n");
log->setUsername(username);
uname = username;
pword = password;
bool ret = true;
string data = string("username=");
data += uname;
data += "&password=";
data += pword;
data += "&adb=1&tz=America%2FChicago"; // No need to have anything other than Chicago timezone
httplib::SSLClient loginReq(NITROTYPE_HOSTNAME, HTTPS_PORT);
shared_ptr<httplib::Response> res = loginReq.post(NT_LOGIN_ENDPOINT, data, "application/x-www-form-urlencoded; charset=UTF-8");
if (res) {
bool foundLoginCookie = false;
for (int i = 0; i < res->cookies.size(); ++i) {
string cookie = res->cookies.at(i);
addCookie(Utils::extractCKey(cookie), Utils::extractCValue(cookie));
if (cookie.find("ntuserrem=") == 0) {
foundLoginCookie = true;
token = Utils::extractCValue(cookie);
log->type(LOG_HTTP);
log->wr("Resolved ntuserrem login token.\n");
// addCookie("ntuserrem", token);
}
}
if (!foundLoginCookie) {
ret = false;
cout << "Unable to locate the login cookie. Maybe try a different account?\n";
}
} else {
ret = false;
cout << "Login request failed. This might be a network issue. Maybe try resetting your internet connection?\n";
}
if (ret == false) {
log->type(LOG_HTTP);
log->wr("Failed to log in. This account is most likely banned.\n");
} else {
bool success = getPrimusSID();
if (!success) return false;
}
return ret;
}
bool NTClient::connect() {
wsh = new Hub();
time_t tnow = time(0);
rawCookieStr = Utils::stringifyCookies(&cookies);
stringstream uristream;
uristream << "wss://realtime1.nitrotype.com:443/realtime/?_primuscb=" << tnow << "-0&EIO=3&transport=websocket&sid=" << primusSid << "&t=" << tnow << "&b64=1";
string wsURI = uristream.str();
log->type(LOG_CONN);
log->wr("Attempting to open a WebSocket on NitroType realtime server...\n");
if (firstConnect) {
addListeners();
}
// cout << "Cookies: " << rawCookieStr << endl << endl;
// Create override headers
customHeaders["Cookie"] = rawCookieStr;
customHeaders["Origin"] = "https://www.nitrotype.com";
customHeaders["User-Agent"] = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/55.0.2883.87 Chrome/55.0.2883.87 Safari/537.36";
// customHeaders["Host"] = "realtime1.nitrotype.com";
wsh->connect(wsURI, (void*)this, customHeaders, 7000);
// wsh->connect(wsURI);
if (firstConnect) {
wsh->run();
firstConnect = false;
}
return true;
}
void NTClient::addCookie(string key, string val) {
SPair sp = SPair(key, val);
cookies.push_back(sp);
}
bool NTClient::getPrimusSID() {
time_t tnow = time(0);
log->type(LOG_HTTP);
log->wr("Resolving Primus SID...\n");
rawCookieStr = Utils::stringifyCookies(&cookies);
stringstream squery;
squery << "?_primuscb=" << tnow << "-0&EIO=3&transport=polling&t=" << tnow << "-0&b64=1";
string queryStr = squery.str();
httplib::SSLClient loginReq(NT_REALTIME_HOST, HTTPS_PORT);
string path = NT_PRIMUS_ENDPOINT + queryStr;
shared_ptr<httplib::Response> res = loginReq.get(path.c_str(), rawCookieStr.c_str());
if (res) {
json jres = json::parse(res->body.substr(4, res->body.length()));
primusSid = jres["sid"];
log->type(LOG_HTTP);
log->wr("Resolved Primus SID successfully.\n");
// addCookie("io", primusSid);
} else {
cout << "Error retrieving primus handshake data.\n";
return false;
}
return true;
}
string NTClient::getJoinPacket(int avgSpeed) {
stringstream ss;
ss << "4{\"stream\":\"race\",\"msg\":\"join\",\"payload\":{\"debugging\":false,\"avgSpeed\":"
<< avgSpeed
<< ",\"forceEarlyPlace\":true,\"track\":\"desert\",\"music\":\"city_nights\"}}";
return ss.str();
}
void NTClient::addListeners() {
assert(wsh != nullptr);
wsh->onError([this](void* udata) {
cout << "Failed to connect to WebSocket server." << endl;
hasError = true;
});
wsh->onConnection([this](WebSocket<CLIENT>* wsocket, HttpRequest req) {
log->type(LOG_CONN);
log->wr("Established a WebSocket connection with the realtime server.\n");
onConnection(wsocket, req);
});
wsh->onDisconnection([this](WebSocket<CLIENT>* wsocket, int code, char* msg, size_t len) {
log->type(LOG_CONN);
log->wr("Disconnected from the realtime server.\n");
onDisconnection(wsocket, code, msg, len);
});
wsh->onMessage([this](WebSocket<CLIENT>* ws, char* msg, size_t len, OpCode opCode) {
onMessage(ws, msg, len, opCode);
});
}
void NTClient::onDisconnection(WebSocket<CLIENT>* wsocket, int code, char* msg, size_t len) {
/*
cout << "Disconn message: " << string(msg, len) << endl;
cout << "Disconn code: " << code << endl;
*/
log->type(LOG_CONN);
log->wr("Reconnecting to the realtime server...\n");
getPrimusSID();
rawCookieStr = Utils::stringifyCookies(&cookies);
stringstream uristream;
uristream << "wss://realtime1.nitrotype.com:443/realtime/?_primuscb=" << time(0) << "-0&EIO=3&transport=websocket&sid=" << primusSid << "&t=" << time(0) << "&b64=1";
string wsURI = uristream.str();
wsh->connect(wsURI, (void*)this, customHeaders, 7000);
}
void NTClient::handleData(WebSocket<CLIENT>* ws, json* j) {
// Uncomment to dump all raw JSON packets
// cout << "Recieved json data:" << endl << j->dump(4) << endl;
if (j->operator[]("msg") == "setup") {
log->type(LOG_RACE);
log->wr("I joined a new race.\n");
recievedEndPacket = false;
} else if (j->operator[]("msg") == "joined") {
string joinedName = j->operator[]("payload")["profile"]["username"];
string dispName;
try {
dispName = j->operator[]("payload")["profile"]["displayName"];
} catch (const exception& e) {
dispName = "[None]";
}
log->type(LOG_RACE);
if (joinedName == "bot") {
log->wr("Bot user '");
log->wrs(dispName);
log->wrs("' joined the race.\n");
} else {
log->wr("Human user '");
log->wrs(joinedName);
log->wrs("' joined the race.\n");
}
} else if (j->operator[]("msg") == "status" && j->operator[]("payload")["status"] == "countdown") {
lastRaceStart = time(0);
log->type(LOG_RACE);
log->wr("The race has started.\n");
lesson = j->operator[]("payload")["l"];
lessonLen = lesson.length();
lidx = 0;
log->type(LOG_INFO);
log->wr("Lesson length: ");
log->operator<<(lessonLen);
log->ln();
this_thread::sleep_for(chrono::milliseconds(50));
type(ws);
} else if (j->operator[]("msg") == "update" &&
j->operator[]("payload")["racers"][0] != nullptr &&
j->operator[]("payload")["racers"][0]["r"] != nullptr) {
// Race has finished for a client
if (recievedEndPacket == false) {
// Ensures its this client
recievedEndPacket = true;
handleRaceFinish(ws, j);
}
}
}
void NTClient::onMessage(WebSocket<CLIENT>* ws, char* msg, size_t len, OpCode opCode) {
if (opCode != OpCode::TEXT) {
cout << "The realtime server did not send a text packet for some reason, ignoring.\n";
return;
}
string smsg = string(msg, len);
if (smsg == "3probe") {
// Response to initial connection probe
ws->send("5", OpCode::TEXT);
// Join packet
this_thread::sleep_for(chrono::seconds(1));
string joinTo = getJoinPacket(20); // 20 WPM just to test
ws->send(joinTo.c_str(), OpCode::TEXT);
} else if (smsg.length() > 2 && smsg[0] == '4' && smsg[1] == '{') {
string rawJData = smsg.substr(1, smsg.length());
json jdata;
try {
jdata = json::parse(rawJData);
} catch (const exception& e) {
// Some error parsing real race data, something must be wrong
cout << "There was an issue parsing server data: " << e.what() << endl;
return;
}
handleData(ws, &jdata);
} else {
cout << "Recieved unknown WebSocket message: '" << smsg << "'\n";
}
}
void NTClient::onConnection(WebSocket<CLIENT>* wsocket, HttpRequest req) {
// Send a probe, which is required for connection
wsocket->send("2probe", OpCode::TEXT);
}
void NTClient::sendTypePacket(WebSocket<CLIENT>* ws, int idx, bool isRight) {
json p = {
{"stream", "race"},
{"msg", "update"},
{"payload", {}}
};
if (isRight) {
p["payload"]["t"] = idx;
} else {
p["payload"]["e"] = idx;
}
string packet = "4" + p.dump();
ws->send(packet.c_str(), OpCode::TEXT);
}
void NTClient::type(WebSocket<CLIENT>* ws) {
if (lidx > lessonLen) {
// All characters have been typed
return;
}
int low = typeIntervalMS - 10;
int high = typeIntervalMS + 10;
bool isRight = Utils::randBool(accuracy);
int sleepFor = Utils::randInt(low, high);
if (low < 10) {
low = 10;
}
if (lidx % 25 == 0) { // Display info every 25 characters
// Log race updated
log->type(LOG_INFO);
log->wr("I have finished ");
log->operator<<((((double)lidx) / ((double)lessonLen)) * 100.00);
log->wrs("% of the race (");
log->operator<<((int)lidx);
log->wrs(" / ");
log->operator<<((int)lessonLen);
log->wrs(" characters at ");
log->operator<<((int)wpm);
log->wrs(" WPM)");
log->ln();
}
// cout << "Typing with index: " << lidx << ", isRight: " << isRight << ", sleepFor: " << sleepFor << endl;
sendTypePacket(ws, lidx, isRight);
lidx++;
this_thread::sleep_for(chrono::milliseconds(sleepFor));
type(ws); // Call the function until the lesson has been "typed"
}
void NTClient::handleRaceFinish(WebSocket<CLIENT>* ws, json* j) {
int raceCompleteTime = time(0) - lastRaceStart;
log->type(LOG_RACE);
log->wr("The race has finished.\n");
log->type(LOG_INFO);
log->wr("The race took ");
log->operator<<(raceCompleteTime);
log->wrs(" seconds to complete.\n");
this_thread::sleep_for(chrono::seconds(10)); // Sleep 10 seconds
log->type(LOG_CONN);
log->wr("Closing WebSocket...\n");
ws->close();
}
|
#include "NTClient.h"
using namespace std;
NTClient::NTClient(int _wpm, double _accuracy) {
typeIntervalMS = 12000 / _wpm;
wpm = _wpm;
accuracy = _accuracy;
hasError = false;
firstConnect = true;
connected = false;
lessonLen = 0;
lidx = 0;
log = new NTLogger("(Not logged in)");
wsh = nullptr;
}
NTClient::~NTClient() {
if (log != nullptr) {
delete log;
}
if (wsh != nullptr) {
delete wsh;
wsh = nullptr;
}
}
bool NTClient::login(string username, string password) {
log->type(LOG_HTTP);
log->wr("Logging into the NitroType account...\n");
log->setUsername(username);
uname = username;
pword = password;
bool ret = true;
string data = string("username=");
data += uname;
data += "&password=";
data += pword;
data += "&adb=1&tz=America%2FChicago"; // No need to have anything other than Chicago timezone
httplib::SSLClient loginReq(NITROTYPE_HOSTNAME, HTTPS_PORT);
shared_ptr<httplib::Response> res = loginReq.post(NT_LOGIN_ENDPOINT, data, "application/x-www-form-urlencoded; charset=UTF-8");
if (res) {
bool foundLoginCookie = false;
for (int i = 0; i < res->cookies.size(); ++i) {
string cookie = res->cookies.at(i);
addCookie(Utils::extractCKey(cookie), Utils::extractCValue(cookie));
if (cookie.find("ntuserrem=") == 0) {
foundLoginCookie = true;
token = Utils::extractCValue(cookie);
log->type(LOG_HTTP);
log->wr("Resolved ntuserrem login token.\n");
// addCookie("ntuserrem", token);
}
}
if (!foundLoginCookie) {
ret = false;
log->type(LOG_HTTP);
log->wr("Unable to locate the login cookie. Maybe try a different account?\n");
}
} else {
ret = false;
log->type(LOG_HTTP);
log->wr("Login request failed. This might be a network issue. Maybe try resetting your internet connection?\n");
}
if (ret == false) {
log->type(LOG_HTTP);
log->wr("Failed to log in. This account is most likely banned.\n");
} else {
bool success = getPrimusSID();
if (!success) return false;
}
return ret;
}
bool NTClient::connect() {
wsh = new Hub();
time_t tnow = time(0);
rawCookieStr = Utils::stringifyCookies(&cookies);
stringstream uristream;
uristream << "wss://realtime1.nitrotype.com:443/realtime/?_primuscb=" << tnow << "-0&EIO=3&transport=websocket&sid=" << primusSid << "&t=" << tnow << "&b64=1";
string wsURI = uristream.str();
log->type(LOG_CONN);
log->wr("Attempting to open a WebSocket on NitroType realtime server...\n");
if (firstConnect) {
addListeners();
}
// cout << "Cookies: " << rawCookieStr << endl << endl;
// Create override headers
customHeaders["Cookie"] = rawCookieStr;
customHeaders["Origin"] = "https://www.nitrotype.com";
customHeaders["User-Agent"] = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/55.0.2883.87 Chrome/55.0.2883.87 Safari/537.36";
// customHeaders["Host"] = "realtime1.nitrotype.com";
wsh->connect(wsURI, (void*)this, customHeaders, 7000);
// wsh->connect(wsURI);
if (firstConnect) {
wsh->run();
firstConnect = false;
}
return true;
}
void NTClient::addCookie(string key, string val) {
SPair sp = SPair(key, val);
cookies.push_back(sp);
}
bool NTClient::getPrimusSID() {
time_t tnow = time(0);
log->type(LOG_HTTP);
log->wr("Resolving Primus SID...\n");
rawCookieStr = Utils::stringifyCookies(&cookies);
stringstream squery;
squery << "?_primuscb=" << tnow << "-0&EIO=3&transport=polling&t=" << tnow << "-0&b64=1";
string queryStr = squery.str();
httplib::SSLClient loginReq(NT_REALTIME_HOST, HTTPS_PORT);
string path = NT_PRIMUS_ENDPOINT + queryStr;
shared_ptr<httplib::Response> res = loginReq.get(path.c_str(), rawCookieStr.c_str());
if (res) {
json jres = json::parse(res->body.substr(4, res->body.length()));
primusSid = jres["sid"];
log->type(LOG_HTTP);
log->wr("Resolved Primus SID successfully.\n");
// addCookie("io", primusSid);
} else {
cout << "Error retrieving primus handshake data.\n";
return false;
}
return true;
}
string NTClient::getJoinPacket(int avgSpeed) {
stringstream ss;
ss << "4{\"stream\":\"race\",\"msg\":\"join\",\"payload\":{\"debugging\":false,\"avgSpeed\":"
<< avgSpeed
<< ",\"forceEarlyPlace\":true,\"track\":\"desert\",\"music\":\"city_nights\"}}";
return ss.str();
}
void NTClient::addListeners() {
assert(wsh != nullptr);
wsh->onError([this](void* udata) {
cout << "Failed to connect to WebSocket server." << endl;
hasError = true;
});
wsh->onConnection([this](WebSocket<CLIENT>* wsocket, HttpRequest req) {
log->type(LOG_CONN);
log->wr("Established a WebSocket connection with the realtime server.\n");
onConnection(wsocket, req);
});
wsh->onDisconnection([this](WebSocket<CLIENT>* wsocket, int code, char* msg, size_t len) {
log->type(LOG_CONN);
log->wr("Disconnected from the realtime server.\n");
onDisconnection(wsocket, code, msg, len);
});
wsh->onMessage([this](WebSocket<CLIENT>* ws, char* msg, size_t len, OpCode opCode) {
onMessage(ws, msg, len, opCode);
});
}
void NTClient::onDisconnection(WebSocket<CLIENT>* wsocket, int code, char* msg, size_t len) {
/*
cout << "Disconn message: " << string(msg, len) << endl;
cout << "Disconn code: " << code << endl;
*/
log->type(LOG_CONN);
log->wr("Reconnecting to the realtime server...\n");
getPrimusSID();
rawCookieStr = Utils::stringifyCookies(&cookies);
stringstream uristream;
uristream << "wss://realtime1.nitrotype.com:443/realtime/?_primuscb=" << time(0) << "-0&EIO=3&transport=websocket&sid=" << primusSid << "&t=" << time(0) << "&b64=1";
string wsURI = uristream.str();
wsh->connect(wsURI, (void*)this, customHeaders, 7000);
}
void NTClient::handleData(WebSocket<CLIENT>* ws, json* j) {
// Uncomment to dump all raw JSON packets
// cout << "Recieved json data:" << endl << j->dump(4) << endl;
if (j->operator[]("msg") == "setup") {
log->type(LOG_RACE);
log->wr("I joined a new race.\n");
recievedEndPacket = false;
} else if (j->operator[]("msg") == "joined") {
string joinedName = j->operator[]("payload")["profile"]["username"];
string dispName;
try {
dispName = j->operator[]("payload")["profile"]["displayName"];
} catch (const exception& e) {
dispName = "[None]";
}
log->type(LOG_RACE);
if (joinedName == "bot") {
log->wr("Bot user '");
log->wrs(dispName);
log->wrs("' joined the race.\n");
} else {
log->wr("Human user '");
log->wrs(joinedName);
log->wrs("' joined the race.\n");
}
} else if (j->operator[]("msg") == "status" && j->operator[]("payload")["status"] == "countdown") {
lastRaceStart = time(0);
log->type(LOG_RACE);
log->wr("The race has started.\n");
lesson = j->operator[]("payload")["l"];
lessonLen = lesson.length();
lidx = 0;
log->type(LOG_INFO);
log->wr("Lesson length: ");
log->operator<<(lessonLen);
log->ln();
this_thread::sleep_for(chrono::milliseconds(50));
type(ws);
} else if (j->operator[]("msg") == "update" &&
j->operator[]("payload")["racers"][0] != nullptr &&
j->operator[]("payload")["racers"][0]["r"] != nullptr) {
// Race has finished for a client
if (recievedEndPacket == false) {
// Ensures its this client
recievedEndPacket = true;
handleRaceFinish(ws, j);
}
}
}
void NTClient::onMessage(WebSocket<CLIENT>* ws, char* msg, size_t len, OpCode opCode) {
if (opCode != OpCode::TEXT) {
cout << "The realtime server did not send a text packet for some reason, ignoring.\n";
return;
}
string smsg = string(msg, len);
if (smsg == "3probe") {
// Response to initial connection probe
ws->send("5", OpCode::TEXT);
// Join packet
this_thread::sleep_for(chrono::seconds(1));
string joinTo = getJoinPacket(20); // 20 WPM just to test
ws->send(joinTo.c_str(), OpCode::TEXT);
} else if (smsg.length() > 2 && smsg[0] == '4' && smsg[1] == '{') {
string rawJData = smsg.substr(1, smsg.length());
json jdata;
try {
jdata = json::parse(rawJData);
} catch (const exception& e) {
// Some error parsing real race data, something must be wrong
cout << "There was an issue parsing server data: " << e.what() << endl;
return;
}
handleData(ws, &jdata);
} else {
cout << "Recieved unknown WebSocket message: '" << smsg << "'\n";
}
}
void NTClient::onConnection(WebSocket<CLIENT>* wsocket, HttpRequest req) {
// Send a probe, which is required for connection
wsocket->send("2probe", OpCode::TEXT);
}
void NTClient::sendTypePacket(WebSocket<CLIENT>* ws, int idx, bool isRight) {
json p = {
{"stream", "race"},
{"msg", "update"},
{"payload", {}}
};
if (isRight) {
p["payload"]["t"] = idx;
} else {
p["payload"]["e"] = idx;
}
string packet = "4" + p.dump();
ws->send(packet.c_str(), OpCode::TEXT);
}
void NTClient::type(WebSocket<CLIENT>* ws) {
if (lidx > lessonLen) {
// All characters have been typed
return;
}
int low = typeIntervalMS - 10;
int high = typeIntervalMS + 10;
bool isRight = Utils::randBool(accuracy);
int sleepFor = Utils::randInt(low, high);
if (low < 10) {
low = 10;
}
if (lidx % 25 == 0) { // Display info every 25 characters
// Log race updated
log->type(LOG_INFO);
log->wr("I have finished ");
log->operator<<((((double)lidx) / ((double)lessonLen)) * 100.00);
log->wrs("% of the race (");
log->operator<<((int)lidx);
log->wrs(" / ");
log->operator<<((int)lessonLen);
log->wrs(" characters at ");
log->operator<<((int)wpm);
log->wrs(" WPM)");
log->ln();
}
// cout << "Typing with index: " << lidx << ", isRight: " << isRight << ", sleepFor: " << sleepFor << endl;
sendTypePacket(ws, lidx, isRight);
lidx++;
this_thread::sleep_for(chrono::milliseconds(sleepFor));
type(ws); // Call the function until the lesson has been "typed"
}
void NTClient::handleRaceFinish(WebSocket<CLIENT>* ws, json* j) {
int raceCompleteTime = time(0) - lastRaceStart;
log->type(LOG_RACE);
log->wr("The race has finished.\n");
log->type(LOG_INFO);
log->wr("The race took ");
log->operator<<(raceCompleteTime);
log->wrs(" seconds to complete.\n");
this_thread::sleep_for(chrono::seconds(10)); // Sleep 10 seconds
log->type(LOG_CONN);
log->wr("Closing WebSocket...\n");
ws->close();
}
|
Use nice logging for failures
|
Use nice logging for failures
|
C++
|
mit
|
ultratype/UltraTypePP,ultratype/UltraTypePP
|
9bb2c29bc9adb15301ed50ae26c0336e39fd1f9b
|
src/appleseedmaya/shadingnodemetadata.cpp
|
src/appleseedmaya/shadingnodemetadata.cpp
|
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2016-2017 Esteban Tovagliari, The appleseedhq Organization
//
// 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.
//
// interface header.
#include "shadingnodemetadata.h"
// Standard library headers.
#include <cstdlib>
#include <map>
#include <vector>
// Maya headers.
#include <maya/MPlug.h>
// appleseed.foundation headers.
#include "foundation/utility/autoreleaseptr.h"
#include "foundation/utility/iostreamop.h"
// appleseed.renderer headers.
#include "renderer/api/shadergroup.h"
namespace asr = renderer;
namespace asf = foundation;
OSLMetadataExtractor::OSLMetadataExtractor(const foundation::Dictionary& metadata)
: m_metadata(metadata)
{
}
bool OSLMetadataExtractor::exists(const char *key) const
{
return m_metadata.dictionaries().exist(key);
}
bool OSLMetadataExtractor::getValue(const char *key, MString& value)
{
if (exists(key))
{
const foundation::Dictionary& dict = m_metadata.dictionary(key);
value = dict.get("value");
return true;
}
return false;
}
bool OSLMetadataExtractor::getValue(const char *key, bool& value)
{
int tmp;
if (getValue(key, tmp))
{
value = (tmp != 0);
return true;
}
return false;
}
namespace
{
void getFloat3Default(const asf::Dictionary& paramInfo, std::vector<double>& defaultValue)
{
const asf::Vector3f v = paramInfo.get<asf::Vector3f>("default");
defaultValue.push_back(v[0]);
defaultValue.push_back(v[1]);
defaultValue.push_back(v[2]);
}
}
OSLParamInfo::OSLParamInfo(const asf::Dictionary& paramInfo)
: arrayLen(-1)
, hasDefault(false)
, lockGeom(true)
, divider(false)
{
paramName = paramInfo.get("name");
mayaAttributeName = paramName;
mayaAttributeShortName = paramName;
paramType = paramInfo.get("type");
validDefault = paramInfo.get<bool>("validdefault");
// todo: lots of refactoring possibilities here...
if (validDefault && lockGeom)
{
if (paramInfo.strings().exist("default"))
{
if (paramType == "color")
{
getFloat3Default(paramInfo, defaultValue);
hasDefault = true;
}
else if (paramType == "float")
{
defaultValue.push_back(paramInfo.get<float>("default"));
hasDefault = true;
}
else if (paramType == "int")
{
defaultValue.push_back(paramInfo.get<int>("default"));
hasDefault = true;
}
if (paramType == "normal")
{
getFloat3Default(paramInfo, defaultValue);
hasDefault = true;
}
if (paramType == "point")
{
getFloat3Default(paramInfo, defaultValue);
hasDefault = true;
}
else if (paramType == "string")
{
defaultStringValue = paramInfo.get("default");
hasDefault = true;
}
else if (paramType == "vector")
{
getFloat3Default(paramInfo, defaultValue);
hasDefault = true;
}
}
}
isOutput = paramInfo.get<bool>("isoutput");
isClosure = paramInfo.get<bool>("isclosure");
isStruct = paramInfo.get<bool>("isstruct");
if (isStruct)
structName = paramInfo.get("structname");
isArray = paramInfo.get<bool>("isarray");
if (isArray)
arrayLen = paramInfo.get<int>("arraylen");
else
arrayLen = -1;
if (paramInfo.dictionaries().exist("metadata"))
{
OSLMetadataExtractor metadata(paramInfo.dictionary("metadata"));
metadata.getValue("lockgeom", lockGeom);
metadata.getValue("units", units);
metadata.getValue("page", page);
metadata.getValue("label", label);
metadata.getValue("widget", widget);
metadata.getValue("options", options);
metadata.getValue("help", help);
hasMin = metadata.getValue("min", minValue);
hasMax = metadata.getValue("max", maxValue);
metadata.getValue("divider", divider);
metadata.getValue("maya_attribute_name", mayaAttributeName);
metadata.getValue("maya_attribute_short_name", mayaAttributeShortName);
metadata.getValue("maya_attribute_type", mayaAttributeType);
}
}
std::ostream& operator<<(std::ostream& os, const OSLParamInfo& paramInfo)
{
os << "Param : " << paramInfo.paramName << "\n";
os << " maya name : " << paramInfo.mayaAttributeName << "\n";
os << " type : " << paramInfo.paramType << "\n";
os << " output : " << paramInfo.isOutput << "\n";
os << " valid default : " << paramInfo.validDefault << "\n";
os << " closure : " << paramInfo.isClosure << "\n";
if (paramInfo.isStruct)
os << " struct name : " << paramInfo.structName << "\n";
if (paramInfo.isArray)
os << " array len : " << paramInfo.arrayLen << "\n";
os << std::endl;
return os;
}
OSLShaderInfo::OSLShaderInfo()
: typeId(0)
{
}
OSLShaderInfo::OSLShaderInfo(const asr::ShaderQuery& q)
: typeId(0)
{
shaderName = q.get_shader_name();
shaderType = q.get_shader_type();
OSLMetadataExtractor metadata(q.get_metadata());
metadata.getValue("maya_node_name", mayaName);
metadata.getValue("maya_classification", mayaClassification);
metadata.getValue<unsigned int>("maya_type_id", typeId);
paramInfo.reserve(q.get_num_params());
for(size_t i = 0, e = q.get_num_params(); i < e; ++i)
paramInfo.push_back(OSLParamInfo(q.get_param_info(i)));
// Apply some defaults.
// If the shader is a custom node, we can default its name to the shader name.
if (typeId != 0 && mayaName.length() == 0)
mayaName = shaderName;
}
const OSLParamInfo *OSLShaderInfo::findParam(const MString& mayaAttrName) const
{
for(size_t i = 0, e = paramInfo.size(); i < e; ++i)
{
if (paramInfo[i].mayaAttributeName == mayaAttrName)
return ¶mInfo[i];
}
return 0;
}
const OSLParamInfo *OSLShaderInfo::findParam(const MPlug& plug) const
{
MStatus status;
const MString attrName =
plug.partialName(
false,
false,
false,
false,
false,
true, // use long names.
&status);
return findParam(attrName);
}
|
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2016-2017 Esteban Tovagliari, The appleseedhq Organization
//
// 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.
//
// interface header.
#include "shadingnodemetadata.h"
// Standard library headers.
#include <cstdlib>
#include <map>
#include <vector>
// Maya headers.
#include <maya/MPlug.h>
// appleseed.foundation headers.
#include "foundation/utility/autoreleaseptr.h"
#include "foundation/utility/iostreamop.h"
// appleseed.renderer headers.
#include "renderer/api/shadergroup.h"
namespace asr = renderer;
namespace asf = foundation;
OSLMetadataExtractor::OSLMetadataExtractor(const foundation::Dictionary& metadata)
: m_metadata(metadata)
{
}
bool OSLMetadataExtractor::exists(const char *key) const
{
return m_metadata.dictionaries().exist(key);
}
bool OSLMetadataExtractor::getValue(const char *key, MString& value)
{
if (exists(key))
{
const foundation::Dictionary& dict = m_metadata.dictionary(key);
value = dict.get("value");
return true;
}
return false;
}
bool OSLMetadataExtractor::getValue(const char *key, bool& value)
{
int tmp;
if (getValue(key, tmp))
{
value = (tmp != 0);
return true;
}
return false;
}
namespace
{
void getFloat3Default(const asf::Dictionary& paramInfo, std::vector<double>& defaultValue)
{
const asf::Vector3f v = paramInfo.get<asf::Vector3f>("default");
defaultValue.push_back(v[0]);
defaultValue.push_back(v[1]);
defaultValue.push_back(v[2]);
}
}
OSLParamInfo::OSLParamInfo(const asf::Dictionary& paramInfo)
: arrayLen(-1)
, hasDefault(false)
, lockGeom(true)
, divider(false)
{
paramName = paramInfo.get("name");
mayaAttributeName = paramName;
mayaAttributeShortName = paramName;
paramType = paramInfo.get("type");
validDefault = paramInfo.get<bool>("validdefault");
// todo: lots of refactoring possibilities here...
if (validDefault && lockGeom)
{
if (paramInfo.strings().exist("default"))
{
if (paramType == "color")
{
getFloat3Default(paramInfo, defaultValue);
hasDefault = true;
}
else if (paramType == "float")
{
defaultValue.push_back(paramInfo.get<float>("default"));
hasDefault = true;
}
else if (paramType == "int")
{
defaultValue.push_back(paramInfo.get<int>("default"));
hasDefault = true;
}
if (paramType == "normal")
{
getFloat3Default(paramInfo, defaultValue);
hasDefault = true;
}
if (paramType == "point")
{
getFloat3Default(paramInfo, defaultValue);
hasDefault = true;
}
else if (paramType == "string")
{
defaultStringValue = paramInfo.get("default");
hasDefault = true;
}
else if (paramType == "vector")
{
getFloat3Default(paramInfo, defaultValue);
hasDefault = true;
}
}
}
isOutput = paramInfo.get<bool>("isoutput");
isClosure = paramInfo.get<bool>("isclosure");
isStruct = paramInfo.get<bool>("isstruct");
if (isStruct)
structName = paramInfo.get("structname");
isArray = paramInfo.get<bool>("isarray");
if (isArray)
arrayLen = paramInfo.get<int>("arraylen");
else
arrayLen = -1;
if (paramInfo.dictionaries().exist("metadata"))
{
OSLMetadataExtractor metadata(paramInfo.dictionary("metadata"));
metadata.getValue("lockgeom", lockGeom);
metadata.getValue("units", units);
metadata.getValue("page", page);
metadata.getValue("label", label);
metadata.getValue("widget", widget);
metadata.getValue("options", options);
metadata.getValue("help", help);
hasMin = metadata.getValue("min", minValue);
hasMax = metadata.getValue("max", maxValue);
metadata.getValue("divider", divider);
metadata.getValue("maya_attribute_name", mayaAttributeName);
metadata.getValue("maya_attribute_short_name", mayaAttributeShortName);
metadata.getValue("maya_attribute_type", mayaAttributeType);
}
}
std::ostream& operator<<(std::ostream& os, const OSLParamInfo& paramInfo)
{
os << "Param : " << paramInfo.paramName << "\n";
os << " maya name : " << paramInfo.mayaAttributeName << "\n";
os << " type : " << paramInfo.paramType << "\n";
os << " output : " << paramInfo.isOutput << "\n";
os << " valid default : " << paramInfo.validDefault << "\n";
os << " closure : " << paramInfo.isClosure << "\n";
if (paramInfo.isStruct)
os << " struct name : " << paramInfo.structName << "\n";
if (paramInfo.isArray)
os << " array len : " << paramInfo.arrayLen << "\n";
os << std::endl;
return os;
}
OSLShaderInfo::OSLShaderInfo()
: typeId(0)
{
}
OSLShaderInfo::OSLShaderInfo(const asr::ShaderQuery& q)
: typeId(0)
{
shaderName = q.get_shader_name();
shaderType = q.get_shader_type();
OSLMetadataExtractor metadata(q.get_metadata());
metadata.getValue("maya_node_name", mayaName);
metadata.getValue("maya_classification", mayaClassification);
metadata.getValue<unsigned int>("maya_type_id", typeId);
paramInfo.reserve(q.get_param_count());
for(size_t i = 0, e = q.get_param_count(); i < e; ++i)
paramInfo.push_back(OSLParamInfo(q.get_param_info(i)));
// Apply some defaults.
// If the shader is a custom node, we can default its name to the shader name.
if (typeId != 0 && mayaName.length() == 0)
mayaName = shaderName;
}
const OSLParamInfo *OSLShaderInfo::findParam(const MString& mayaAttrName) const
{
for(size_t i = 0, e = paramInfo.size(); i < e; ++i)
{
if (paramInfo[i].mayaAttributeName == mayaAttrName)
return ¶mInfo[i];
}
return 0;
}
const OSLParamInfo *OSLShaderInfo::findParam(const MPlug& plug) const
{
MStatus status;
const MString attrName =
plug.partialName(
false,
false,
false,
false,
false,
true, // use long names.
&status);
return findParam(attrName);
}
|
Update for appleseed changes.
|
Update for appleseed changes.
|
C++
|
mit
|
luisbarrancos/appleseed-maya2,dictoon/appleseed-maya,appleseedhq/appleseed-maya2,dictoon/appleseed-maya,luisbarrancos/appleseed-maya2,dictoon/appleseed-maya,appleseedhq/appleseed-maya,appleseedhq/appleseed-maya2,luisbarrancos/appleseed-maya2,est77/appleseed-maya,est77/appleseed-maya,appleseedhq/appleseed-maya2,appleseedhq/appleseed-maya,appleseedhq/appleseed-maya,est77/appleseed-maya
|
18884a86ae337b6ce9636738c069a87004d43017
|
tools/llvm-prof/llvm-prof.cpp
|
tools/llvm-prof/llvm-prof.cpp
|
//===- llvm-prof.cpp - Read in and process llvmprof.out data files --------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tools is meant for use with the various LLVM profiling instrumentation
// passes. It reads in the data file produced by executing an instrumented
// program, and outputs a nice report.
//
//===----------------------------------------------------------------------===//
#include "ProfileInfo.h"
#include "llvm/Function.h"
#include "llvm/Bytecode/Reader.h"
#include "Support/CommandLine.h"
#include <iostream>
#include <cstdio>
#include <map>
namespace {
cl::opt<std::string>
BytecodeFile(cl::Positional, cl::desc("<program bytecode file>"),
cl::Required);
cl::opt<std::string>
ProfileDataFile(cl::Positional, cl::desc("<llvmprof.out file>"),
cl::Optional, cl::init("llvmprof.out"));
}
// PairSecondSort - A sorting predicate to sort by the second element of a pair.
template<class T>
struct PairSecondSort
: public std::binary_function<std::pair<T, unsigned>,
std::pair<T, unsigned>, bool> {
bool operator()(const std::pair<T, unsigned> &LHS,
const std::pair<T, unsigned> &RHS) const {
return LHS.second < RHS.second;
}
};
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv, " llvm profile dump decoder\n");
// Read in the bytecode file...
std::string ErrorMessage;
Module *M = ParseBytecodeFile(BytecodeFile, &ErrorMessage);
if (M == 0) {
std::cerr << argv[0] << ": " << BytecodeFile << ": " << ErrorMessage
<< "\n";
return 1;
}
// Read the profiling information
ProfileInfo PI(argv[0], ProfileDataFile, *M);
// Output a report. Eventually, there will be multiple reports selectable on
// the command line, for now, just keep things simple.
// Emit the most frequent function table...
std::vector<std::pair<Function*, unsigned> > FunctionCounts;
PI.getFunctionCounts(FunctionCounts);
// Sort by the frequency, backwards.
std::sort(FunctionCounts.begin(), FunctionCounts.end(),
std::not2(PairSecondSort<Function*>()));
unsigned TotalExecutions = 0;
for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i)
TotalExecutions += FunctionCounts[i].second;
std::cout << "===" << std::string(73, '-') << "===\n"
<< "LLVM profiling output for execution";
if (PI.getNumExecutions() != 1) std::cout << "s";
std::cout << ":\n";
for (unsigned i = 0, e = PI.getNumExecutions(); i != e; ++i) {
std::cout << " ";
if (e != 1) std::cout << i << ". ";
std::cout << PI.getExecution(i) << "\n";
}
std::cout << "\n===" << std::string(73, '-') << "===\n";
std::cout << "Function execution frequencies:\n\n";
// Print out the function frequencies...
printf(" ## Frequency\n");
for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i) {
if (FunctionCounts[i].second == 0) {
printf("\n NOTE: %d function%s never executed!\n",
e-i, e-i-1 ? "s were" : " was");
break;
}
printf("%3d. %5d/%d %s\n", i, FunctionCounts[i].second, TotalExecutions,
FunctionCounts[i].first->getName().c_str());
}
// If we have block count information, print out the LLVM module with
// frequency annotations.
if (PI.hasAccurateBlockCounts()) {
std::vector<std::pair<BasicBlock*, unsigned> > Counts;
PI.getBlockCounts(Counts);
std::map<BasicBlock*, unsigned> BlockFreqs(Counts.begin(), Counts.end());
}
return 0;
}
|
//===- llvm-prof.cpp - Read in and process llvmprof.out data files --------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This tools is meant for use with the various LLVM profiling instrumentation
// passes. It reads in the data file produced by executing an instrumented
// program, and outputs a nice report.
//
//===----------------------------------------------------------------------===//
#include "ProfileInfo.h"
#include "llvm/Function.h"
#include "llvm/Bytecode/Reader.h"
#include "Support/CommandLine.h"
#include <iostream>
#include <cstdio>
#include <map>
namespace {
cl::opt<std::string>
BytecodeFile(cl::Positional, cl::desc("<program bytecode file>"),
cl::Required);
cl::opt<std::string>
ProfileDataFile(cl::Positional, cl::desc("<llvmprof.out file>"),
cl::Optional, cl::init("llvmprof.out"));
}
// PairSecondSort - A sorting predicate to sort by the second element of a pair.
template<class T>
struct PairSecondSortReverse
: public std::binary_function<std::pair<T, unsigned>,
std::pair<T, unsigned>, bool> {
bool operator()(const std::pair<T, unsigned> &LHS,
const std::pair<T, unsigned> &RHS) const {
return LHS.second > RHS.second;
}
};
int main(int argc, char **argv) {
cl::ParseCommandLineOptions(argc, argv, " llvm profile dump decoder\n");
// Read in the bytecode file...
std::string ErrorMessage;
Module *M = ParseBytecodeFile(BytecodeFile, &ErrorMessage);
if (M == 0) {
std::cerr << argv[0] << ": " << BytecodeFile << ": " << ErrorMessage
<< "\n";
return 1;
}
// Read the profiling information
ProfileInfo PI(argv[0], ProfileDataFile, *M);
// Output a report. Eventually, there will be multiple reports selectable on
// the command line, for now, just keep things simple.
// Emit the most frequent function table...
std::vector<std::pair<Function*, unsigned> > FunctionCounts;
PI.getFunctionCounts(FunctionCounts);
// Sort by the frequency, backwards.
std::sort(FunctionCounts.begin(), FunctionCounts.end(),
PairSecondSortReverse<Function*>());
unsigned TotalExecutions = 0;
for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i)
TotalExecutions += FunctionCounts[i].second;
std::cout << "===" << std::string(73, '-') << "===\n"
<< "LLVM profiling output for execution";
if (PI.getNumExecutions() != 1) std::cout << "s";
std::cout << ":\n";
for (unsigned i = 0, e = PI.getNumExecutions(); i != e; ++i) {
std::cout << " ";
if (e != 1) std::cout << i+1 << ". ";
std::cout << PI.getExecution(i) << "\n";
}
std::cout << "\n===" << std::string(73, '-') << "===\n";
std::cout << "Function execution frequencies:\n\n";
// Print out the function frequencies...
printf(" ## Frequency\n");
for (unsigned i = 0, e = FunctionCounts.size(); i != e; ++i) {
if (FunctionCounts[i].second == 0) {
printf("\n NOTE: %d function%s never executed!\n",
e-i, e-i-1 ? "s were" : " was");
break;
}
printf("%3d. %5d/%d %s\n", i+1, FunctionCounts[i].second, TotalExecutions,
FunctionCounts[i].first->getName().c_str());
}
// If we have block count information, print out the LLVM module with
// frequency annotations.
if (PI.hasAccurateBlockCounts()) {
std::vector<std::pair<BasicBlock*, unsigned> > Counts;
PI.getBlockCounts(Counts);
TotalExecutions = 0;
for (unsigned i = 0, e = Counts.size(); i != e; ++i)
TotalExecutions += Counts[i].second;
// Sort by the frequency, backwards.
std::sort(Counts.begin(), Counts.end(),
PairSecondSortReverse<BasicBlock*>());
std::cout << "\n===" << std::string(73, '-') << "===\n";
std::cout << "Top 20 most frequently executed basic blocks:\n\n";
// Print out the function frequencies...
printf(" ## Frequency\n");
unsigned BlocksToPrint = Counts.size();
if (BlocksToPrint > 20) BlocksToPrint = 20;
for (unsigned i = 0; i != BlocksToPrint; ++i)
printf("%3d. %5d/%d %s - %s\n", i+1, Counts[i].second, TotalExecutions,
Counts[i].first->getParent()->getName().c_str(),
Counts[i].first->getName().c_str());
std::map<BasicBlock*, unsigned> BlockFreqs(Counts.begin(), Counts.end());
}
return 0;
}
|
Print the top 20 most frequently executed blocks. Fix sort predicate problem
|
Print the top 20 most frequently executed blocks. Fix sort predicate problem
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@9594 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
bsd-2-clause
|
chubbymaggie/asap,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,dslab-epfl/asap,apple/swift-llvm,apple/swift-llvm,dslab-epfl/asap,chubbymaggie/asap,dslab-epfl/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,chubbymaggie/asap,dslab-epfl/asap,chubbymaggie/asap,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm
|
3d7a48ccaaaa2e796d2f116c1a8645403185a8a2
|
src/irgen.cpp
|
src/irgen.cpp
|
#include "irgen.h"
#include <llvm/IR/Value.h>
#include <llvm/IR/Type.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <iostream>
#include "astnode.h"
#include "astnodetypes.h"
using namespace llvm;
LLVMContext context;
IRBuilder<> Builder(context);
Module* module;
#define ST SemanticType
Type* getIRType(ST t, std::string ident = "") {
Type* ret;
switch(t) {
case ST::Void:
ret = Type::getVoidTy(context);
break;
case ST::Int:
ret = Type::getInt32Ty(context);
break;
case ST::Float:
ret = Type::getFloatTy(context);
break;
case ST::Double:
ret = Type::getDoubleTy(context);
break;
case ST::Char:
ret = Type::getInt8Ty(context);
break;
case ST::Bool:
ret = Type::getInt1Ty(context);
break;
default:
std::cout << "Type not supported, defaulting to void\n";
ret = Type::getVoidTy(context);
break;
}
return ret;
}
#undef ST
Function* prototypeCodegen(AstNode* n) {
PrototypeNode* protonode = (PrototypeNode*) n;
std::vector<AstNode*>* vec = protonode->getParameters();
std::vector<Type*> parameterTypes;
parameterTypes.reserve(vec->size());
//TODO(marcus): handle user types for return/parameters
for(auto c : (*vec)) {
Type* t = getIRType(c->getType());
parameterTypes.push_back(t);
}
Type* retType = getIRType(protonode->getType());
FunctionType* FT = FunctionType::get(retType, parameterTypes, false);
Function* F = Function::Create(FT, Function::ExternalLinkage, protonode->mfuncname, module);
unsigned int idx = 0;
for(auto &Arg : F->args()) {
std::string name = ((ParamsNode*) (*vec)[idx])->mname;
Arg.setName(name);
++idx;
}
delete vec;
return F;
}
#define ANT AstNodeType
void generateIR_llvm(AstNode* ast) {
//check for null
if(!ast)
return;
//Handle IR gen for each node type
switch(ast->nodeType()) {
case ANT::Prototype:
{
Function* f = prototypeCodegen(ast);
//f->dump();
}
break;
default:
break;
}
//recurse
std::vector<AstNode*>* vec = ast->getChildren();
for(auto c : (*vec)) {
generateIR_llvm(c);
}
}
void dumpIR() {
module->dump();
return;
}
void generateIR(AstNode* ast) {
module = new Module("Neuro Program", context);
generateIR_llvm(ast);
}
|
#include "irgen.h"
#include <llvm/IR/Value.h>
#include <llvm/IR/Type.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/BasicBlock.h>
#include <iostream>
#include "astnode.h"
#include "astnodetypes.h"
using namespace llvm;
LLVMContext context;
IRBuilder<> Builder(context);
Module* module;
#define ST SemanticType
Type* getIRType(ST t, std::string ident = "") {
Type* ret;
switch(t) {
case ST::Void:
ret = Type::getVoidTy(context);
break;
case ST::Int:
ret = Type::getInt32Ty(context);
break;
case ST::Float:
ret = Type::getFloatTy(context);
break;
case ST::Double:
ret = Type::getDoubleTy(context);
break;
case ST::Char:
ret = Type::getInt8Ty(context);
break;
case ST::Bool:
ret = Type::getInt1Ty(context);
break;
default:
std::cout << "Type not supported, defaulting to void\n";
ret = Type::getVoidTy(context);
break;
}
return ret;
}
#undef ST
Function* prototypeCodegen(AstNode* n) {
PrototypeNode* protonode = (PrototypeNode*) n;
std::vector<AstNode*>* vec = protonode->getParameters();
std::vector<Type*> parameterTypes;
parameterTypes.reserve(vec->size());
//TODO(marcus): handle user types for return/parameters
for(auto c : (*vec)) {
Type* t = getIRType(c->getType());
parameterTypes.push_back(t);
}
Type* retType = getIRType(protonode->getType());
FunctionType* FT = FunctionType::get(retType, parameterTypes, false);
Function* F = Function::Create(FT, Function::ExternalLinkage, protonode->mfuncname, module);
unsigned int idx = 0;
for(auto &Arg : F->args()) {
std::string name = ((ParamsNode*) (*vec)[idx])->mname;
Arg.setName(name);
++idx;
}
delete vec;
return F;
}
Function* functionCodgen(AstNode* n) {
FuncDefNode* funcnode = (FuncDefNode*) n;
Function* F = module->getFunction(funcnode->mfuncname);
if(!F) {
std::vector<AstNode*>* vec = funcnode->getParameters();
std::vector<Type*> parameterTypes;
parameterTypes.reserve(vec->size());
//TODO(marcus): handle user types for return/parameters
for(auto c : (*vec)) {
Type* t = getIRType(c->getType());
parameterTypes.push_back(t);
}
Type* retType = getIRType(funcnode->getType());
FunctionType* FT = FunctionType::get(retType, parameterTypes, false);
F = Function::Create(FT, Function::ExternalLinkage, funcnode->mfuncname, module);
unsigned int idx = 0;
for(auto &Arg : F->args()) {
std::string name = ((ParamsNode*) (*vec)[idx])->mname;
Arg.setName(name);
++idx;
}
delete vec;
}
//TODO(marcus): what is entry, can it be used for every function?
BasicBlock* BB = BasicBlock::Create(context, "entry", F);
Builder.SetInsertPoint(BB);
//FIXME(marcus): remove void return once expression codegen works
Builder.CreateRetVoid();
return F;
}
#define ANT AstNodeType
void generateIR_llvm(AstNode* ast) {
//check for null
if(!ast)
return;
//Handle IR gen for each node type
switch(ast->nodeType()) {
case ANT::Prototype:
{
Function* f = prototypeCodegen(ast);
//f->dump();
return;
}
break;
case ANT::FuncDef:
{
Function* F = functionCodgen(ast);
//TODO(marcus): codegen function body
return;
}
break;
default:
break;
}
//recurse
std::vector<AstNode*>* vec = ast->getChildren();
for(auto c : (*vec)) {
generateIR_llvm(c);
}
}
void dumpIR() {
module->dump();
return;
}
void generateIR(AstNode* ast) {
module = new Module("Neuro Program", context);
generateIR_llvm(ast);
}
|
Add initial function definition codegen.
|
Add initial function definition codegen.
|
C++
|
mit
|
lotusronin/neuro,lotusronin/neuro,lotusronin/neuro,lotusronin/neuro
|
0bd525b8049b0202279f4c82da556e8d034ff8ae
|
tools/redexdump/RedexDump.cpp
|
tools/redexdump/RedexDump.cpp
|
/**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include "RedexDump.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <getopt.h>
#include "PrintUtil.h"
#include "Formatters.h"
static const char ddump_usage_string[] =
"ReDex, DEX Dump tool\n"
"\nredexdump pretty prints content of a dexfile. "
"By default only prints the header\n"
"\n"
"Usage:\n"
"\tredump [-h | --all | [[-string] [-type] [-proto] [-field] [-meth] "
"[-clsdef] [-clsdata] [-code] [-enarr] [-anno]] [-clean]"
" <classes.dex>...\n"
"\n<classes.dex>: path to a dex file (not an APK!)\n"
"\noptions:\n"
"--h: help summary\n"
"\nsections to print:\n"
"-a, --all: print all items in all sections\n"
"-s, --string: print items in the string id section\n"
"-S, --stringdata: print string section (pointee of string ids)\n"
"-t, --type: print items in the type id section\n"
"-p, --proto: print items in the proto id section\n"
"-f, --field: print items in the field id section\n"
"-m, --meth: print items in the method id section\n"
"-c, --clsdef: print items in the class def id section\n"
"-C, --clsdata: print items in the class data section\n"
"-x, --code: print items in the code data section\n"
"-e, --enarr: print items in the encoded array section\n"
"-A, --anno: print items in the annotation section\n"
"-d, --debug: print debug info items in the data section\n"
"-D, --ddebug=<addr>: disassemble debug info item at <addr>\n"
"\nprinting options:\n"
"--clean: does not print indexes or offsets making the output "
"--raw: print all bytes, even control characters "
"usable for a diff\n";
int main(int argc, char* argv[]) {
bool all = false;
bool string = false;
bool stringdata = false;
bool type = false;
bool proto = false;
bool field = false;
bool meth = false;
bool clsdef = false;
bool clsdata = false;
bool code = false;
bool enarr = false;
bool anno = false;
bool debug = false;
uint32_t ddebug_offset = 0;
int no_headers = 0;
char c;
static const struct option options[] = {
{ "all", no_argument, nullptr, 'a' },
{ "string", no_argument, nullptr, 's' },
{ "stringdata", no_argument, nullptr, 'S' },
{ "type", no_argument, nullptr, 't' },
{ "proto", no_argument, nullptr, 'p' },
{ "field", no_argument, nullptr, 'f' },
{ "meth", no_argument, nullptr, 'm' },
{ "clsdef", no_argument, nullptr, 'c' },
{ "clsdata", no_argument, nullptr, 'C' },
{ "code", no_argument, nullptr, 'x' },
{ "enarr", no_argument, nullptr, 'e' },
{ "anno", no_argument, nullptr, 'A' },
{ "debug", no_argument, nullptr, 'd' },
{ "ddebug", required_argument, nullptr, 'D' },
{ "clean", no_argument, (int*)&clean, 1 },
{ "raw", no_argument, (int*)&raw, 1 },
{ "no-headers", no_argument, &no_headers, 1 },
{ "help", no_argument, nullptr, 'h' },
{ nullptr, 0, nullptr, 0 },
};
while ((c = getopt_long(
argc,
argv,
"asStpfmcCxeAdDh",
&options[0],
nullptr)) != -1) {
switch (c) {
case 'a':
all = true;
break;
case 's':
string = true;
break;
case 'S':
stringdata = true;
break;
case 't':
type = true;
break;
case 'p':
proto = true;
break;
case 'f':
field = true;
break;
case 'm':
meth = true;
break;
case 'c':
clsdef = true;
break;
case 'C':
clsdata = true;
break;
case 'x':
code = true;
break;
case 'e':
enarr = true;
break;
case 'A':
anno = true;
break;
case 'd':
debug = true;
break;
case 'D':
sscanf(optarg, "%x", &ddebug_offset);
break;
case 'h':
puts(ddump_usage_string);
return 0;
case '?':
return 1; // getopt_long has printed an error
case 0:
// we're handling a long-only option
break;
default:
abort();
}
}
if (optind == argc) {
fprintf(stderr, "%s: no dex files given; use -h for help\n", argv[0]);
return 1;
}
while (optind < argc) {
const char* dexfile = argv[optind++];
ddump_data rd;
open_dex_file(dexfile, &rd);
if (!no_headers) {
redump(format_map(&rd).c_str());
}
if (string || all) {
dump_strings(&rd);
}
if (stringdata || all) {
dump_stringdata(&rd);
}
if (type || all) {
dump_types(&rd);
}
if (proto || all) {
dump_protos(&rd, !no_headers);
}
if (field || all) {
dump_fields(&rd, !no_headers);
}
if (meth || all) {
dump_methods(&rd, !no_headers);
}
if (clsdef || all) {
dump_clsdefs(&rd, !no_headers);
}
if (clsdata || all) {
dump_clsdata(&rd, !no_headers);
}
if (code || all) {
dump_code(&rd);
}
if (enarr || all) {
dump_enarr(&rd);
}
if (anno || all) {
dump_anno(&rd);
}
if (debug || all) {
dump_debug(&rd);
}
if (ddebug_offset != 0) {
disassemble_debug(&rd, ddebug_offset);
}
fprintf(stdout, "\n");
fflush(stdout);
}
return 0;
}
|
/**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include "RedexDump.h"
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <getopt.h>
#include "PrintUtil.h"
#include "Formatters.h"
static const char ddump_usage_string[] =
"ReDex, DEX Dump tool\n"
"\nredexdump pretty prints content of a dexfile. "
"By default only prints the header\n"
"\n"
"Usage:\n"
"\tredump [-h | --all | [[-string] [-type] [-proto] [-field] [-meth] "
"[-clsdef] [-clsdata] [-code] [-enarr] [-anno]] [-clean]"
" <classes.dex>...\n"
"\n<classes.dex>: path to a dex file (not an APK!)\n"
"\noptions:\n"
"--h: help summary\n"
"\nsections to print:\n"
"-a, --all: print all items in all sections\n"
"-s, --string: print items in the string id section\n"
"-S, --stringdata: print string section (pointee of string ids)\n"
"-t, --type: print items in the type id section\n"
"-p, --proto: print items in the proto id section\n"
"-f, --field: print items in the field id section\n"
"-m, --meth: print items in the method id section\n"
"-c, --clsdef: print items in the class def id section\n"
"-C, --clsdata: print items in the class data section\n"
"-x, --code: print items in the code data section\n"
"-e, --enarr: print items in the encoded array section\n"
"-A, --anno: print items in the annotation section\n"
"-d, --debug: print debug info items in the data section\n"
"-D, --ddebug=<addr>: disassemble debug info item at <addr>\n"
"\n"
"printing options:\n"
"--clean: suppress indices and offsets\n"
"--no-headers: suppress headers\n"
"--raw: print all bytes, even control characters\n"
;
int main(int argc, char* argv[]) {
bool all = false;
bool string = false;
bool stringdata = false;
bool type = false;
bool proto = false;
bool field = false;
bool meth = false;
bool clsdef = false;
bool clsdata = false;
bool code = false;
bool enarr = false;
bool anno = false;
bool debug = false;
uint32_t ddebug_offset = 0;
int no_headers = 0;
char c;
static const struct option options[] = {
{ "all", no_argument, nullptr, 'a' },
{ "string", no_argument, nullptr, 's' },
{ "stringdata", no_argument, nullptr, 'S' },
{ "type", no_argument, nullptr, 't' },
{ "proto", no_argument, nullptr, 'p' },
{ "field", no_argument, nullptr, 'f' },
{ "meth", no_argument, nullptr, 'm' },
{ "clsdef", no_argument, nullptr, 'c' },
{ "clsdata", no_argument, nullptr, 'C' },
{ "code", no_argument, nullptr, 'x' },
{ "enarr", no_argument, nullptr, 'e' },
{ "anno", no_argument, nullptr, 'A' },
{ "debug", no_argument, nullptr, 'd' },
{ "ddebug", required_argument, nullptr, 'D' },
{ "clean", no_argument, (int*)&clean, 1 },
{ "raw", no_argument, (int*)&raw, 1 },
{ "no-headers", no_argument, &no_headers, 1 },
{ "help", no_argument, nullptr, 'h' },
{ nullptr, 0, nullptr, 0 },
};
while ((c = getopt_long(
argc,
argv,
"asStpfmcCxeAdDh",
&options[0],
nullptr)) != -1) {
switch (c) {
case 'a':
all = true;
break;
case 's':
string = true;
break;
case 'S':
stringdata = true;
break;
case 't':
type = true;
break;
case 'p':
proto = true;
break;
case 'f':
field = true;
break;
case 'm':
meth = true;
break;
case 'c':
clsdef = true;
break;
case 'C':
clsdata = true;
break;
case 'x':
code = true;
break;
case 'e':
enarr = true;
break;
case 'A':
anno = true;
break;
case 'd':
debug = true;
break;
case 'D':
sscanf(optarg, "%x", &ddebug_offset);
break;
case 'h':
puts(ddump_usage_string);
return 0;
case '?':
return 1; // getopt_long has printed an error
case 0:
// we're handling a long-only option
break;
default:
abort();
}
}
if (optind == argc) {
fprintf(stderr, "%s: no dex files given; use -h for help\n", argv[0]);
return 1;
}
while (optind < argc) {
const char* dexfile = argv[optind++];
ddump_data rd;
open_dex_file(dexfile, &rd);
if (!no_headers) {
redump(format_map(&rd).c_str());
}
if (string || all) {
dump_strings(&rd);
}
if (stringdata || all) {
dump_stringdata(&rd);
}
if (type || all) {
dump_types(&rd);
}
if (proto || all) {
dump_protos(&rd, !no_headers);
}
if (field || all) {
dump_fields(&rd, !no_headers);
}
if (meth || all) {
dump_methods(&rd, !no_headers);
}
if (clsdef || all) {
dump_clsdefs(&rd, !no_headers);
}
if (clsdata || all) {
dump_clsdata(&rd, !no_headers);
}
if (code || all) {
dump_code(&rd);
}
if (enarr || all) {
dump_enarr(&rd);
}
if (anno || all) {
dump_anno(&rd);
}
if (debug || all) {
dump_debug(&rd);
}
if (ddebug_offset != 0) {
disassemble_debug(&rd, ddebug_offset);
}
fprintf(stdout, "\n");
fflush(stdout);
}
return 0;
}
|
Fix --help formatting
|
Fix --help formatting
Reviewed By: newobj
Differential Revision: D3936235
fbshipit-source-id: e0a30ce9b45e46355c27198fd4b087a9479e048f
|
C++
|
mit
|
facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex
|
c45ef6c6d9329ae69d1af5c94b3be755de1765e0
|
src/wizard.cc
|
src/wizard.cc
|
#include <vector>
using namespace std;
#include "error_handling.h"
#include "game.h"
#include "coordinate.h"
#include "potions.h"
#include "scrolls.h"
#include "command.h"
#include "options.h"
#include "io.h"
#include "armor.h"
#include "pack.h"
#include "rings.h"
#include "misc.h"
#include "level.h"
#include "weapons.h"
#include "player.h"
#include "wand.h"
#include "traps.h"
#include "things.h"
#include "os.h"
#include "rogue.h"
#include "wizard.h"
bool wizard = false;
static void
pr_spec(char type)
{
WINDOW* printscr = dupwin(stdscr);
Coordinate orig_pos;
getyx(stdscr, orig_pos.y, orig_pos.x);
vector<obj_info>* ptr;
size_t max;
switch (type)
{
case POTION: ptr = nullptr; max = Potion::Type::NPOTIONS; break;
case SCROLL: ptr = &scroll_info; max = NSCROLLS; break;
case RING: ptr = nullptr; max = Ring::Type::NRINGS; break;
case STICK: ptr = nullptr; max = Wand::Type::NWANDS; break;
case ARMOR: ptr = nullptr; max = Armor::Type::NARMORS; break;
case WEAPON: ptr = &weapon_info; max = MAXWEAPONS;break;
default: ptr = nullptr; max = 0; break;
}
char ch = '0';
for (size_t i = 0; i < max; ++i)
{
string name;
size_t prob;
wmove(printscr, static_cast<int>(i) + 1, 1);
switch (type) {
case ARMOR: {
name = Armor::name(static_cast<Armor::Type>(i));
prob = static_cast<size_t>(Armor::probability(static_cast<Armor::Type>(i)));
} break;
case POTION: {
name = Potion::name(static_cast<Potion::Type>(i));
prob = static_cast<size_t>(Potion::probability(static_cast<Potion::Type>(i)));
} break;
case STICK: {
name = Wand::name(static_cast<Wand::Type>(i));
prob = static_cast<size_t>(Wand::probability(static_cast<Wand::Type>(i)));
} break;
case RING: {
name = Ring::name(static_cast<Ring::Type>(i));
prob = static_cast<size_t>(Ring::probability(static_cast<Ring::Type>(i)));
} break;
default: {
name = ptr->at(i).oi_name;
prob = ptr->at(i).oi_prob;
} break;
}
wprintw(printscr, "%c: %s (%d%%)", ch, name.c_str(), prob);
ch = ch == '9' ? 'a' : (ch + 1);
}
wmove(stdscr, orig_pos.y, orig_pos.x);
wrefresh(printscr);
delwin(printscr);
}
static void
print_things(void)
{
char index_to_char[] = { POTION, SCROLL, FOOD, WEAPON, ARMOR, RING, STICK };
WINDOW* tmp = dupwin(stdscr);
Coordinate orig_pos;
getyx(stdscr, orig_pos.y, orig_pos.x);
for (size_t i = 0; i < things.size(); ++i)
{
wmove(tmp, static_cast<int>(i) + 1, 1);
wprintw(tmp, "%c %s", index_to_char[i], things.at(i).oi_name.c_str());
}
wmove(stdscr, orig_pos.y, orig_pos.x);
wrefresh(tmp);
delwin(tmp);
}
int
wizard_list_items(void)
{
io_msg("for what type of object do you want a list? ");
print_things();
int ch = io_readchar(true);
touchwin(stdscr);
refresh();
pr_spec(static_cast<char>(ch));
io_msg_clear();
io_msg("--Press any key to continue--");
io_readchar(false);
io_msg_clear();
touchwin(stdscr);
return 0;
}
void
wizard_create_item(void)
{
io_msg("type of item: ");
int type = io_readchar(true);
io_msg_clear();
if (!(type == WEAPON || type == ARMOR || type == RING || type == STICK
|| type == GOLD || type == POTION || type == SCROLL || type == TRAP))
{
io_msg("Bad pick");
return;
}
io_msg("which %c do you want? (0-f)", type);
char ch = io_readchar(true);
int which = isdigit(ch) ? ch - '0' : ch - 'a' + 10;
io_msg_clear();
Item* obj = nullptr;
switch (type)
{
case TRAP:
{
if (which < 0 || which >= NTRAPS)
io_msg("Bad trap id");
else
{
Game::level->set_not_real(player->get_position());
Game::level->set_trap_type(player->get_position(), static_cast<size_t>(which));
}
return;
}
case STICK: obj = new Wand(static_cast<Wand::Type>(which)); break;
case SCROLL: {
obj = scroll_create(which);
obj->o_count = 10;
} break;
case POTION: {
obj = new Potion(static_cast<Potion::Type>(which));
obj->o_count = 10;
} break;
case FOOD: obj = new_food(which); break;
case WEAPON:
{
obj = weapon_create(which, false);
io_msg("blessing? (+,-,n)");
char bless = io_readchar(true);
io_msg_clear();
if (bless == '-')
{
obj->o_flags |= ISCURSED;
obj->o_hplus -= os_rand_range(3) + 1;
}
else if (bless == '+')
obj->o_hplus += os_rand_range(3) + 1;
}
break;
case ARMOR:
{
obj = new Armor(false);
io_msg("blessing? (+,-,n)");
char bless = io_readchar(true);
io_msg_clear();
if (bless == '-')
{
obj->o_flags |= ISCURSED;
obj->o_arm += os_rand_range(3) + 1;
}
else if (bless == '+')
obj->o_arm -= os_rand_range(3) + 1;
}
break;
case RING:
{
obj = new Ring(static_cast<Ring::Type>(which), false);
switch (obj->o_which)
{
case Ring::Type::PROTECT: case Ring::Type::ADDSTR:
case Ring::Type::ADDHIT: case Ring::Type::ADDDAM:
io_msg("blessing? (+,-,n)");
char bless = io_readchar(true);
io_msg_clear();
if (bless == '-')
obj->o_flags |= ISCURSED;
obj->o_arm = (bless == '-' ? -1 : os_rand_range(2) + 1);
break;
}
}
break;
case GOLD:
{
char buf[MAXSTR] = { '\0' };
io_msg("how much?");
if (io_readstr(buf) == 0)
obj->o_goldval = static_cast<short>(atoi(buf));
}
break;
default:
error("Unimplemented item: " + to_string(which));
}
if (obj == nullptr) {
error("object was null");
}
pack_add(obj, false);
}
void
wizard_show_map(void)
{
wclear(hw);
for (int y = 1; y < NUMLINES - 1; y++)
for (int x = 0; x < NUMCOLS; x++)
{
if (!Game::level->is_real(x, y))
wstandout(hw);
wmove(hw, y, x);
waddcch(hw, static_cast<chtype>(Game::level->get_ch(x, y)));
if (!Game::level->is_real(x, y))
wstandend(hw);
}
show_win("---More (level map)---");
}
void
wizard_levels_and_gear(void)
{
player->raise_level(9);
/* Give him a sword (+1,+1) */
if (pack_equipped_item(EQUIPMENT_RHAND) == nullptr)
{
Item* obj = weapon_create(TWOSWORD, false);
obj->o_hplus = 1;
obj->o_dplus = 1;
pack_equip_item(obj);
}
/* And his suit of armor */
if (pack_equipped_item(EQUIPMENT_ARMOR) == nullptr)
{
Item* obj = new Armor(Armor::Type::PLATE_MAIL, false);
obj->o_arm = -5;
obj->o_flags |= ISKNOW;
obj->o_count = 1;
pack_equip_item(obj);
}
}
|
#include <vector>
using namespace std;
#include "error_handling.h"
#include "game.h"
#include "coordinate.h"
#include "potions.h"
#include "scrolls.h"
#include "command.h"
#include "options.h"
#include "io.h"
#include "armor.h"
#include "pack.h"
#include "rings.h"
#include "misc.h"
#include "level.h"
#include "weapons.h"
#include "player.h"
#include "wand.h"
#include "traps.h"
#include "things.h"
#include "os.h"
#include "rogue.h"
#include "wizard.h"
bool wizard = false;
static void
pr_spec(char type)
{
WINDOW* printscr = dupwin(stdscr);
Coordinate orig_pos;
getyx(stdscr, orig_pos.y, orig_pos.x);
vector<obj_info>* ptr;
size_t max;
switch (type)
{
case POTION: ptr = nullptr; max = Potion::Type::NPOTIONS; break;
case SCROLL: ptr = &scroll_info; max = NSCROLLS; break;
case RING: ptr = nullptr; max = Ring::Type::NRINGS; break;
case STICK: ptr = nullptr; max = Wand::Type::NWANDS; break;
case ARMOR: ptr = nullptr; max = Armor::Type::NARMORS; break;
case WEAPON: ptr = &weapon_info; max = MAXWEAPONS;break;
default: ptr = nullptr; max = 0; break;
}
char ch = '0';
for (size_t i = 0; i < max; ++i)
{
string name;
size_t prob;
wmove(printscr, static_cast<int>(i) + 1, 1);
switch (type) {
case ARMOR: {
name = Armor::name(static_cast<Armor::Type>(i));
prob = static_cast<size_t>(Armor::probability(static_cast<Armor::Type>(i)));
} break;
case POTION: {
name = Potion::name(static_cast<Potion::Type>(i));
prob = static_cast<size_t>(Potion::probability(static_cast<Potion::Type>(i)));
} break;
case STICK: {
name = Wand::name(static_cast<Wand::Type>(i));
prob = static_cast<size_t>(Wand::probability(static_cast<Wand::Type>(i)));
} break;
case RING: {
name = Ring::name(static_cast<Ring::Type>(i));
prob = static_cast<size_t>(Ring::probability(static_cast<Ring::Type>(i)));
} break;
default: {
name = ptr->at(i).oi_name;
prob = ptr->at(i).oi_prob;
} break;
}
wprintw(printscr, "%c: %s (%d%%)", ch, name.c_str(), prob);
ch = ch == '9' ? 'a' : (ch + 1);
}
wmove(stdscr, orig_pos.y, orig_pos.x);
wrefresh(printscr);
delwin(printscr);
}
static void
print_things(void)
{
char index_to_char[] = { POTION, SCROLL, FOOD, WEAPON, ARMOR, RING, STICK };
WINDOW* tmp = dupwin(stdscr);
Coordinate orig_pos;
getyx(stdscr, orig_pos.y, orig_pos.x);
for (size_t i = 0; i < things.size(); ++i)
{
wmove(tmp, static_cast<int>(i) + 1, 1);
wprintw(tmp, "%c %s", index_to_char[i], things.at(i).oi_name.c_str());
}
wmove(stdscr, orig_pos.y, orig_pos.x);
wrefresh(tmp);
delwin(tmp);
}
int
wizard_list_items(void)
{
io_msg("for what type of object do you want a list? ");
print_things();
int ch = io_readchar(true);
touchwin(stdscr);
refresh();
pr_spec(static_cast<char>(ch));
io_msg_clear();
io_msg("--Press any key to continue--");
io_readchar(false);
io_msg_clear();
touchwin(stdscr);
return 0;
}
void wizard_create_item(void) {
// Get itemtype
io_msg("type of item: ");
int type = io_readchar(true);
io_msg_clear();
switch (type) {
// Supported types:
case WEAPON: case ARMOR: case RING: case STICK: case GOLD:
case POTION: case SCROLL: case TRAP: {
break;
}
default: {
io_msg("Bad pick");
return;
}
}
// Get item subtype
io_msg("which %c do you want? (0-f)", type);
char ch = io_readchar(true);
int which = isdigit(ch) ? ch - '0' : ch - 'a' + 10;
io_msg_clear();
// Allocate item
Item* obj = nullptr;
switch (type) {
case TRAP: {
if (which < 0 || which >= NTRAPS) {
io_msg("Bad trap id");
} else {
Game::level->set_not_real(player->get_position());
Game::level->set_trap_type(player->get_position(), static_cast<size_t>(which));
}
} return;
case STICK: {
obj = new Wand(static_cast<Wand::Type>(which));
} break;
case SCROLL: {
obj = scroll_create(which);
obj->o_count = 10;
} break;
case POTION: {
obj = new Potion(static_cast<Potion::Type>(which));
obj->o_count = 10;
} break;
case FOOD: {
obj = new_food(which);
} break;
case WEAPON: {
obj = weapon_create(which, false);
io_msg("blessing? (+,-,n)");
char bless = io_readchar(true);
io_msg_clear();
if (bless == '-') {
obj->o_flags |= ISCURSED;
obj->o_hplus -= os_rand_range(3) + 1;
} else if (bless == '+')
obj->o_hplus += os_rand_range(3) + 1;
} break;
case ARMOR: {
obj = new Armor(false);
io_msg("blessing? (+,-,n)");
char bless = io_readchar(true);
io_msg_clear();
if (bless == '-') {
obj->o_flags |= ISCURSED;
obj->o_arm += os_rand_range(3) + 1;
} else if (bless == '+')
obj->o_arm -= os_rand_range(3) + 1;
} break;
case RING: {
obj = new Ring(static_cast<Ring::Type>(which), false);
switch (obj->o_which) {
case Ring::Type::PROTECT: case Ring::Type::ADDSTR:
case Ring::Type::ADDHIT: case Ring::Type::ADDDAM: {
io_msg("blessing? (+,-,n)");
char bless = io_readchar(true);
io_msg_clear();
if (bless == '-')
obj->o_flags |= ISCURSED;
obj->o_arm = (bless == '-' ? -1 : os_rand_range(2) + 1);
} break;
}
} break;
case GOLD: {
obj = new Item();
obj->o_flags = ISMANY;
obj->o_type = GOLD;
char buf[MAXSTR] = { '\0' };
io_msg("how much?");
if (io_readstr(buf) == 0) {
obj->o_goldval = static_cast<short>(atoi(buf));
}
} break;
default: {
error("Unimplemented item: " + to_string(which));
}
}
if (obj == nullptr) {
error("object was null");
}
pack_add(obj, false);
}
void
wizard_show_map(void)
{
wclear(hw);
for (int y = 1; y < NUMLINES - 1; y++)
for (int x = 0; x < NUMCOLS; x++)
{
if (!Game::level->is_real(x, y))
wstandout(hw);
wmove(hw, y, x);
waddcch(hw, static_cast<chtype>(Game::level->get_ch(x, y)));
if (!Game::level->is_real(x, y))
wstandend(hw);
}
show_win("---More (level map)---");
}
void
wizard_levels_and_gear(void)
{
player->raise_level(9);
/* Give him a sword (+1,+1) */
if (pack_equipped_item(EQUIPMENT_RHAND) == nullptr)
{
Item* obj = weapon_create(TWOSWORD, false);
obj->o_hplus = 1;
obj->o_dplus = 1;
pack_equip_item(obj);
}
/* And his suit of armor */
if (pack_equipped_item(EQUIPMENT_ARMOR) == nullptr)
{
Item* obj = new Armor(Armor::Type::PLATE_MAIL, false);
obj->o_arm = -5;
obj->o_flags |= ISKNOW;
obj->o_count = 1;
pack_equip_item(obj);
}
}
|
Fix crash when spawning gold as wizard
|
Fix crash when spawning gold as wizard
|
C++
|
bsd-3-clause
|
lollek/Rogue14,lollek/Rogue14,lollek/Misty-Mountains,lollek/Misty-Mountains,lollek/Misty-Mountains,lollek/Rogue14
|
5db9d4f4fac2f4f7ffb15edac51253d7296e3666
|
src/ae_conv.cpp
|
src/ae_conv.cpp
|
//=======================================================================
// Copyright Baptiste Wicht 2015-2017.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include "dll/neural/conv_layer.hpp"
#include "dll/neural/deconv_layer.hpp"
#include "dll/pooling/mp_layer.hpp"
#include "dll/pooling/upsample_layer.hpp"
#include "dll/dbn.hpp"
#include "dll/trainer/stochastic_gradient_descent.hpp"
#include "ae_config.hpp" // Must be first
#include "ae_conv.hpp"
#include "ae_evaluation.hpp"
namespace {
template<size_t K>
void conv_evaluate(const spot_dataset& dataset, const spot_dataset_set& set, config& conf, names train_word_names, names test_image_names, parameters params, const std::vector<image_t>& training_patches, float learning_rate, size_t epochs) {
static constexpr size_t K1 = 17;
static constexpr size_t NH1_1 = patch_height - K1 + 1;
static constexpr size_t NH1_2 = patch_width - K1 + 1;
using network_t = typename dll::dbn_desc<
dll::dbn_layers<
typename dll::conv_desc<1, patch_height, patch_width, K, NH1_1, NH1_2>::layer_t,
typename dll::deconv_desc<K, NH1_1, NH1_2, 1, K1, K1>::layer_t
>,
dll::momentum,
dll::weight_decay<dll::decay_type::L2>,
dll::trainer<dll::sgd_trainer>,
dll::batch_size<batch_size>,
dll::shuffle
>::dbn_t;
auto net = std::make_unique<network_t>();
net->display();
// Configure the network
net->learning_rate = learning_rate;
net->initial_momentum = 0.9;
net->momentum = 0.9;
// Train as autoencoder
net->fine_tune_ae(training_patches, epochs);
auto folder = spot::evaluate_patches_ae<0, image_t>(dataset, set, conf, *net, train_word_names, test_image_names, false, params);
std::cout << "AE-Result: Conv(" << K << "):" << folder << std::endl;
}
} // end of anonymous namespace
void conv_evaluate_all(const spot_dataset& dataset, const spot_dataset_set& set, config& conf, names train_word_names, names test_image_names, parameters params, const std::vector<image_t>& training_patches){
if (conf.conv) {
conv_evaluate<1>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-4, epochs);
conv_evaluate<2>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-4, epochs);
conv_evaluate<3>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-4, epochs);
conv_evaluate<4>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-4, epochs);
conv_evaluate<5>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-4, epochs);
conv_evaluate<6>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-4, epochs);
conv_evaluate<7>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-4, epochs);
conv_evaluate<8>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-4, epochs);
conv_evaluate<9>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-4, epochs);
conv_evaluate<10>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-4, epochs);
}
}
|
//=======================================================================
// Copyright Baptiste Wicht 2015-2017.
// Distributed under the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include "dll/neural/conv_layer.hpp"
#include "dll/neural/deconv_layer.hpp"
#include "dll/pooling/mp_layer.hpp"
#include "dll/pooling/upsample_layer.hpp"
#include "dll/dbn.hpp"
#include "dll/trainer/stochastic_gradient_descent.hpp"
#include "ae_config.hpp" // Must be first
#include "ae_conv.hpp"
#include "ae_evaluation.hpp"
namespace {
template<size_t K>
void conv_evaluate(const spot_dataset& dataset, const spot_dataset_set& set, config& conf, names train_word_names, names test_image_names, parameters params, const std::vector<image_t>& training_patches, float learning_rate, size_t epochs) {
static constexpr size_t K1 = 17;
static constexpr size_t NH1_1 = patch_height - K1 + 1;
static constexpr size_t NH1_2 = patch_width - K1 + 1;
using network_t = typename dll::dbn_desc<
dll::dbn_layers<
typename dll::conv_desc<1, patch_height, patch_width, K, NH1_1, NH1_2>::layer_t,
typename dll::deconv_desc<K, NH1_1, NH1_2, 1, K1, K1>::layer_t
>,
dll::momentum,
dll::weight_decay<dll::decay_type::L2>,
dll::trainer<dll::sgd_trainer>,
dll::batch_size<batch_size>,
dll::shuffle
>::dbn_t;
auto net = std::make_unique<network_t>();
net->display();
// Configure the network
net->learning_rate = learning_rate;
net->initial_momentum = 0.9;
net->momentum = 0.9;
// Train as autoencoder
net->fine_tune_ae(training_patches, epochs);
auto folder = spot::evaluate_patches_ae<0, image_t>(dataset, set, conf, *net, train_word_names, test_image_names, false, params);
std::cout << "AE-Result: Conv(" << K << "):" << folder << std::endl;
}
} // end of anonymous namespace
void conv_evaluate_all(const spot_dataset& dataset, const spot_dataset_set& set, config& conf, names train_word_names, names test_image_names, parameters params, const std::vector<image_t>& training_patches){
if (conf.conv) {
conv_evaluate<1>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-4, epochs);
conv_evaluate<2>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-5, epochs);
conv_evaluate<3>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-5, epochs);
conv_evaluate<4>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-5, epochs);
conv_evaluate<5>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-5, epochs);
conv_evaluate<6>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-5, epochs);
conv_evaluate<7>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-5, epochs);
conv_evaluate<8>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-5, epochs);
conv_evaluate<9>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-5, epochs);
conv_evaluate<10>(dataset, set, conf, train_word_names, test_image_names, params, training_patches, 1e-5, epochs);
}
}
|
Update learning rates
|
Update learning rates
|
C++
|
mit
|
wichtounet/word_spotting,wichtounet/word_spotting,wichtounet/word_spotting
|
571b7c978ec5fed594f7abdd451974e671e6b8bb
|
test/vp9_end_to_end_test.cc
|
test/vp9_end_to_end_test.cc
|
/*
* Copyright (c) 2014 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/util.h"
#include "test/y4m_video_source.h"
#include "test/yuv_video_source.h"
namespace {
const unsigned int kWidth = 160;
const unsigned int kHeight = 90;
const unsigned int kFramerate = 50;
const unsigned int kFrames = 10;
const int kBitrate = 500;
// List of psnr thresholds for speed settings 0-7 and 5 encoding modes
const double kPsnrThreshold[][5] = {
{ 36.0, 37.0, 37.0, 37.0, 37.0 },
{ 35.0, 36.0, 36.0, 36.0, 36.0 },
{ 34.0, 35.0, 35.0, 35.0, 35.0 },
{ 33.0, 34.0, 34.0, 34.0, 34.0 },
{ 32.0, 33.0, 33.0, 33.0, 33.0 },
{ 31.0, 32.0, 32.0, 32.0, 32.0 },
{ 30.0, 31.0, 31.0, 31.0, 31.0 },
{ 29.0, 30.0, 30.0, 30.0, 30.0 },
};
typedef struct {
const char *filename;
unsigned int input_bit_depth;
vpx_img_fmt fmt;
vpx_bit_depth_t bit_depth;
unsigned int profile;
} TestVideoParam;
const TestVideoParam kTestVectors[] = {
{"park_joy_90p_8_420.y4m", 8, VPX_IMG_FMT_I420, VPX_BITS_8, 0},
{"park_joy_90p_8_422.y4m", 8, VPX_IMG_FMT_I422, VPX_BITS_8, 1},
{"park_joy_90p_8_444.y4m", 8, VPX_IMG_FMT_I444, VPX_BITS_8, 1},
{"park_joy_90p_8_440.yuv", 8, VPX_IMG_FMT_I440, VPX_BITS_8, 1},
#if CONFIG_VP9_HIGHBITDEPTH
{"park_joy_90p_10_420.y4m", 10, VPX_IMG_FMT_I42016, VPX_BITS_10, 2},
{"park_joy_90p_10_422.y4m", 10, VPX_IMG_FMT_I42216, VPX_BITS_10, 3},
{"park_joy_90p_10_444.y4m", 10, VPX_IMG_FMT_I44416, VPX_BITS_10, 3},
{"park_joy_90p_10_440.yuv", 10, VPX_IMG_FMT_I44016, VPX_BITS_10, 3},
{"park_joy_90p_12_420.y4m", 12, VPX_IMG_FMT_I42016, VPX_BITS_12, 2},
{"park_joy_90p_12_422.y4m", 12, VPX_IMG_FMT_I42216, VPX_BITS_12, 3},
{"park_joy_90p_12_444.y4m", 12, VPX_IMG_FMT_I44416, VPX_BITS_12, 3},
{"park_joy_90p_12_440.yuv", 12, VPX_IMG_FMT_I44016, VPX_BITS_12, 3},
#endif // CONFIG_VP9_HIGHBITDEPTH
};
// Encoding modes tested
const libvpx_test::TestMode kEncodingModeVectors[] = {
::libvpx_test::kTwoPassGood,
::libvpx_test::kOnePassGood,
::libvpx_test::kRealTime,
};
// Speed settings tested
const int kCpuUsedVectors[] = {1, 2, 3, 5, 6};
int is_extension_y4m(const char *filename) {
const char *dot = strrchr(filename, '.');
if (!dot || dot == filename)
return 0;
else
return !strcmp(dot, ".y4m");
}
class EndToEndTestLarge
: public ::libvpx_test::EncoderTest,
public ::libvpx_test::CodecTestWith3Params<libvpx_test::TestMode, \
TestVideoParam, int> {
protected:
EndToEndTestLarge()
: EncoderTest(GET_PARAM(0)),
test_video_param_(GET_PARAM(2)),
cpu_used_(GET_PARAM(3)),
psnr_(0.0),
nframes_(0),
encoding_mode_(GET_PARAM(1)) {
}
virtual ~EndToEndTestLarge() {}
virtual void SetUp() {
InitializeConfig();
SetMode(encoding_mode_);
if (encoding_mode_ != ::libvpx_test::kRealTime) {
cfg_.g_lag_in_frames = 5;
cfg_.rc_end_usage = VPX_VBR;
} else {
cfg_.g_lag_in_frames = 0;
cfg_.rc_end_usage = VPX_CBR;
cfg_.rc_buf_sz = 1000;
cfg_.rc_buf_initial_sz = 500;
cfg_.rc_buf_optimal_sz = 600;
}
dec_cfg_.threads = 4;
}
virtual void BeginPassHook(unsigned int) {
psnr_ = 0.0;
nframes_ = 0;
}
virtual void PSNRPktHook(const vpx_codec_cx_pkt_t *pkt) {
psnr_ += pkt->data.psnr.psnr[0];
nframes_++;
}
virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video,
::libvpx_test::Encoder *encoder) {
if (video->frame() == 1) {
encoder->Control(VP9E_SET_FRAME_PARALLEL_DECODING, 1);
encoder->Control(VP9E_SET_TILE_COLUMNS, 4);
encoder->Control(VP8E_SET_CPUUSED, cpu_used_);
if (encoding_mode_ != ::libvpx_test::kRealTime) {
encoder->Control(VP8E_SET_ENABLEAUTOALTREF, 1);
encoder->Control(VP8E_SET_ARNR_MAXFRAMES, 7);
encoder->Control(VP8E_SET_ARNR_STRENGTH, 5);
encoder->Control(VP8E_SET_ARNR_TYPE, 3);
}
}
}
double GetAveragePsnr() const {
if (nframes_)
return psnr_ / nframes_;
return 0.0;
}
double GetPsnrThreshold() {
return kPsnrThreshold[cpu_used_][encoding_mode_];
}
TestVideoParam test_video_param_;
int cpu_used_;
private:
double psnr_;
unsigned int nframes_;
libvpx_test::TestMode encoding_mode_;
};
TEST_P(EndToEndTestLarge, EndtoEndPSNRTest) {
cfg_.rc_target_bitrate = kBitrate;
cfg_.g_error_resilient = 0;
cfg_.g_profile = test_video_param_.profile;
cfg_.g_input_bit_depth = test_video_param_.input_bit_depth;
cfg_.g_bit_depth = test_video_param_.bit_depth;
init_flags_ = VPX_CODEC_USE_PSNR;
if (cfg_.g_bit_depth > 8)
init_flags_ |= VPX_CODEC_USE_HIGHBITDEPTH;
libvpx_test::VideoSource *video;
if (is_extension_y4m(test_video_param_.filename)) {
video = new libvpx_test::Y4mVideoSource(test_video_param_.filename,
0, kFrames);
} else {
video = new libvpx_test::YUVVideoSource(test_video_param_.filename,
test_video_param_.fmt,
kWidth, kHeight,
kFramerate, 1, 0, kFrames);
}
ASSERT_NO_FATAL_FAILURE(RunLoop(video));
const double psnr = GetAveragePsnr();
EXPECT_GT(psnr, GetPsnrThreshold());
delete(video);
}
VP9_INSTANTIATE_TEST_CASE(
EndToEndTestLarge,
::testing::ValuesIn(kEncodingModeVectors),
::testing::ValuesIn(kTestVectors),
::testing::ValuesIn(kCpuUsedVectors));
VP10_INSTANTIATE_TEST_CASE(
EndToEndTestLarge,
::testing::ValuesIn(kEncodingModeVectors),
::testing::ValuesIn(kTestVectors),
::testing::ValuesIn(kCpuUsedVectors));
} // namespace
|
/*
* Copyright (c) 2014 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/util.h"
#include "test/y4m_video_source.h"
#include "test/yuv_video_source.h"
namespace {
const unsigned int kWidth = 160;
const unsigned int kHeight = 90;
const unsigned int kFramerate = 50;
const unsigned int kFrames = 10;
const int kBitrate = 500;
// List of psnr thresholds for speed settings 0-7 and 5 encoding modes
const double kPsnrThreshold[][5] = {
{ 36.0, 37.0, 37.0, 37.0, 37.0 },
{ 35.0, 36.0, 36.0, 36.0, 36.0 },
{ 34.0, 35.0, 35.0, 35.0, 35.0 },
{ 33.0, 34.0, 34.0, 34.0, 34.0 },
{ 32.0, 33.0, 33.0, 33.0, 33.0 },
{ 31.0, 32.0, 32.0, 32.0, 32.0 },
{ 30.0, 31.0, 31.0, 31.0, 31.0 },
{ 29.0, 30.0, 30.0, 30.0, 30.0 },
};
typedef struct {
const char *filename;
unsigned int input_bit_depth;
vpx_img_fmt fmt;
vpx_bit_depth_t bit_depth;
unsigned int profile;
} TestVideoParam;
const TestVideoParam kTestVectors[] = {
{"park_joy_90p_8_420.y4m", 8, VPX_IMG_FMT_I420, VPX_BITS_8, 0},
{"park_joy_90p_8_422.y4m", 8, VPX_IMG_FMT_I422, VPX_BITS_8, 1},
{"park_joy_90p_8_444.y4m", 8, VPX_IMG_FMT_I444, VPX_BITS_8, 1},
{"park_joy_90p_8_440.yuv", 8, VPX_IMG_FMT_I440, VPX_BITS_8, 1},
#if CONFIG_VP9_HIGHBITDEPTH
{"park_joy_90p_10_420.y4m", 10, VPX_IMG_FMT_I42016, VPX_BITS_10, 2},
{"park_joy_90p_10_422.y4m", 10, VPX_IMG_FMT_I42216, VPX_BITS_10, 3},
{"park_joy_90p_10_444.y4m", 10, VPX_IMG_FMT_I44416, VPX_BITS_10, 3},
{"park_joy_90p_10_440.yuv", 10, VPX_IMG_FMT_I44016, VPX_BITS_10, 3},
{"park_joy_90p_12_420.y4m", 12, VPX_IMG_FMT_I42016, VPX_BITS_12, 2},
{"park_joy_90p_12_422.y4m", 12, VPX_IMG_FMT_I42216, VPX_BITS_12, 3},
{"park_joy_90p_12_444.y4m", 12, VPX_IMG_FMT_I44416, VPX_BITS_12, 3},
{"park_joy_90p_12_440.yuv", 12, VPX_IMG_FMT_I44016, VPX_BITS_12, 3},
#endif // CONFIG_VP9_HIGHBITDEPTH
};
// Encoding modes tested
const libvpx_test::TestMode kEncodingModeVectors[] = {
::libvpx_test::kTwoPassGood,
::libvpx_test::kOnePassGood,
::libvpx_test::kRealTime,
};
// Speed settings tested
const int kCpuUsedVectors[] = {1, 2, 3, 5, 6};
int is_extension_y4m(const char *filename) {
const char *dot = strrchr(filename, '.');
if (!dot || dot == filename)
return 0;
else
return !strcmp(dot, ".y4m");
}
class EndToEndTestLarge
: public ::libvpx_test::EncoderTest,
public ::libvpx_test::CodecTestWith3Params<libvpx_test::TestMode, \
TestVideoParam, int> {
protected:
EndToEndTestLarge()
: EncoderTest(GET_PARAM(0)),
test_video_param_(GET_PARAM(2)),
cpu_used_(GET_PARAM(3)),
psnr_(0.0),
nframes_(0),
encoding_mode_(GET_PARAM(1)) {
}
virtual ~EndToEndTestLarge() {}
virtual void SetUp() {
InitializeConfig();
SetMode(encoding_mode_);
if (encoding_mode_ != ::libvpx_test::kRealTime) {
cfg_.g_lag_in_frames = 5;
cfg_.rc_end_usage = VPX_VBR;
} else {
cfg_.g_lag_in_frames = 0;
cfg_.rc_end_usage = VPX_CBR;
cfg_.rc_buf_sz = 1000;
cfg_.rc_buf_initial_sz = 500;
cfg_.rc_buf_optimal_sz = 600;
}
dec_cfg_.threads = 4;
}
virtual void BeginPassHook(unsigned int) {
psnr_ = 0.0;
nframes_ = 0;
}
virtual void PSNRPktHook(const vpx_codec_cx_pkt_t *pkt) {
psnr_ += pkt->data.psnr.psnr[0];
nframes_++;
}
virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video,
::libvpx_test::Encoder *encoder) {
if (video->frame() == 1) {
encoder->Control(VP9E_SET_FRAME_PARALLEL_DECODING, 1);
encoder->Control(VP9E_SET_TILE_COLUMNS, 4);
encoder->Control(VP8E_SET_CPUUSED, cpu_used_);
if (encoding_mode_ != ::libvpx_test::kRealTime) {
encoder->Control(VP8E_SET_ENABLEAUTOALTREF, 1);
encoder->Control(VP8E_SET_ARNR_MAXFRAMES, 7);
encoder->Control(VP8E_SET_ARNR_STRENGTH, 5);
encoder->Control(VP8E_SET_ARNR_TYPE, 3);
}
}
}
double GetAveragePsnr() const {
if (nframes_)
return psnr_ / nframes_;
return 0.0;
}
double GetPsnrThreshold() {
return kPsnrThreshold[cpu_used_][encoding_mode_];
}
TestVideoParam test_video_param_;
int cpu_used_;
private:
double psnr_;
unsigned int nframes_;
libvpx_test::TestMode encoding_mode_;
};
TEST_P(EndToEndTestLarge, EndtoEndPSNRTest) {
cfg_.rc_target_bitrate = kBitrate;
cfg_.g_error_resilient = 0;
cfg_.g_profile = test_video_param_.profile;
cfg_.g_input_bit_depth = test_video_param_.input_bit_depth;
cfg_.g_bit_depth = test_video_param_.bit_depth;
init_flags_ = VPX_CODEC_USE_PSNR;
if (cfg_.g_bit_depth > 8)
init_flags_ |= VPX_CODEC_USE_HIGHBITDEPTH;
libvpx_test::VideoSource *video;
if (is_extension_y4m(test_video_param_.filename)) {
video = new libvpx_test::Y4mVideoSource(test_video_param_.filename,
0, kFrames);
} else {
video = new libvpx_test::YUVVideoSource(test_video_param_.filename,
test_video_param_.fmt,
kWidth, kHeight,
kFramerate, 1, 0, kFrames);
}
ASSERT_NO_FATAL_FAILURE(RunLoop(video));
const double psnr = GetAveragePsnr();
EXPECT_GT(psnr, GetPsnrThreshold());
delete(video);
}
VP9_INSTANTIATE_TEST_CASE(
EndToEndTestLarge,
::testing::ValuesIn(kEncodingModeVectors),
::testing::ValuesIn(kTestVectors),
::testing::ValuesIn(kCpuUsedVectors));
#if CONFIG_VP9_HIGHBITDEPTH
# if CONFIG_VP10_ENCODER
// TODO(angiebird): many fail in high bitdepth mode.
INSTANTIATE_TEST_CASE_P(
DISABLED_VP10, EndToEndTestLarge,
::testing::Combine(
::testing::Values(static_cast<const libvpx_test::CodecFactory *>(
&libvpx_test::kVP10)),
::testing::ValuesIn(kEncodingModeVectors),
::testing::ValuesIn(kTestVectors),
::testing::ValuesIn(kCpuUsedVectors)));
# endif // CONFIG_VP10_ENCODER
#else
VP10_INSTANTIATE_TEST_CASE(
EndToEndTestLarge,
::testing::ValuesIn(kEncodingModeVectors),
::testing::ValuesIn(kTestVectors),
::testing::ValuesIn(kCpuUsedVectors));
#endif // CONFIG_VP9_HIGHBITDEPTH
} // namespace
|
disable vp10 w/high bitdepth
|
vp9_end_to_end_test: disable vp10 w/high bitdepth
the range check in dct.c (abs(input[i]) < (1 << bit)) will fail in many
cases. this was broken at the time this check was added
BUG=1076
Change-Id: I3df8c7a555e95567d73ac16acda997096ab8d6e2
|
C++
|
bsd-3-clause
|
mwgoldsmith/vpx,openpeer/libvpx_new,jmvalin/aom,mbebenita/aom,webmproject/libvpx,VTCSecureLLC/libvpx,mwgoldsmith/vpx,smarter/aom,smarter/aom,jmvalin/aom,thdav/aom,luctrudeau/aom,ittiamvpx/libvpx-1,mwgoldsmith/libvpx,openpeer/libvpx_new,ittiamvpx/libvpx-1,mwgoldsmith/libvpx,mbebenita/aom,smarter/aom,VTCSecureLLC/libvpx,ittiamvpx/libvpx-1,mwgoldsmith/vpx,ShiftMediaProject/libvpx,mwgoldsmith/libvpx,felipebetancur/libvpx,Topopiccione/libvpx,ShiftMediaProject/libvpx,felipebetancur/libvpx,mwgoldsmith/vpx,mbebenita/aom,VTCSecureLLC/libvpx,webmproject/libvpx,ittiamvpx/libvpx-1,thdav/aom,felipebetancur/libvpx,webmproject/libvpx,ittiamvpx/libvpx-1,thdav/aom,jmvalin/aom,jmvalin/aom,openpeer/libvpx_new,Topopiccione/libvpx,thdav/aom,shacklettbp/aom,openpeer/libvpx_new,Topopiccione/libvpx,thdav/aom,luctrudeau/aom,webmproject/libvpx,GrokImageCompression/aom,mwgoldsmith/vpx,VTCSecureLLC/libvpx,smarter/aom,luctrudeau/aom,mbebenita/aom,Topopiccione/libvpx,smarter/aom,mbebenita/aom,jmvalin/aom,felipebetancur/libvpx,felipebetancur/libvpx,mwgoldsmith/libvpx,mbebenita/aom,shacklettbp/aom,GrokImageCompression/aom,smarter/aom,webmproject/libvpx,webmproject/libvpx,felipebetancur/libvpx,mbebenita/aom,Topopiccione/libvpx,VTCSecureLLC/libvpx,VTCSecureLLC/libvpx,mwgoldsmith/libvpx,ittiamvpx/libvpx-1,thdav/aom,mwgoldsmith/libvpx,GrokImageCompression/aom,shacklettbp/aom,shacklettbp/aom,jmvalin/aom,openpeer/libvpx_new,mbebenita/aom,GrokImageCompression/aom,luctrudeau/aom,ShiftMediaProject/libvpx,shacklettbp/aom,shacklettbp/aom,GrokImageCompression/aom,openpeer/libvpx_new,luctrudeau/aom,luctrudeau/aom,GrokImageCompression/aom,ShiftMediaProject/libvpx,Topopiccione/libvpx,ShiftMediaProject/libvpx,mbebenita/aom,mwgoldsmith/vpx
|
9d924a0c4ae57643e0ac4be6845d72e890cf3a6e
|
test/vp9_end_to_end_test.cc
|
test/vp9_end_to_end_test.cc
|
/*
* Copyright (c) 2014 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/util.h"
#include "test/y4m_video_source.h"
#include "test/yuv_video_source.h"
namespace {
const unsigned int kWidth = 160;
const unsigned int kHeight = 90;
const unsigned int kFramerate = 50;
const unsigned int kFrames = 10;
const int kBitrate = 500;
// List of psnr thresholds for speed settings 0-7 and 5 encoding modes
const double kPsnrThreshold[][5] = {
// Note:
// VP10 HBD average PSNR is slightly lower than VP9.
// We make two cases here to enable the testing and
// guard picture quality.
#if CONFIG_VP10_ENCODER && CONFIG_VP9_HIGHBITDEPTH
{ 36.0, 37.0, 37.0, 37.0, 37.0 },
{ 31.0, 36.0, 36.0, 36.0, 36.0 },
{ 32.0, 35.0, 35.0, 35.0, 35.0 },
{ 32.0, 34.0, 34.0, 34.0, 34.0 },
{ 32.0, 33.0, 33.0, 33.0, 33.0 },
{ 31.0, 32.0, 32.0, 32.0, 32.0 },
{ 30.0, 31.0, 31.0, 31.0, 31.0 },
{ 29.0, 30.0, 30.0, 30.0, 30.0 },
#else
{ 36.0, 37.0, 37.0, 37.0, 37.0 },
{ 35.0, 36.0, 36.0, 36.0, 36.0 },
{ 34.0, 35.0, 35.0, 35.0, 35.0 },
{ 33.0, 34.0, 34.0, 34.0, 34.0 },
{ 32.0, 33.0, 33.0, 33.0, 33.0 },
{ 31.0, 32.0, 32.0, 32.0, 32.0 },
{ 30.0, 31.0, 31.0, 31.0, 31.0 },
{ 29.0, 30.0, 30.0, 30.0, 30.0 },
#endif // CONFIG_VP9_HIGHBITDEPTH && CONFIG_VP10_ENCODER
};
typedef struct {
const char *filename;
unsigned int input_bit_depth;
vpx_img_fmt fmt;
vpx_bit_depth_t bit_depth;
unsigned int profile;
} TestVideoParam;
const TestVideoParam kTestVectors[] = {
{"park_joy_90p_8_420.y4m", 8, VPX_IMG_FMT_I420, VPX_BITS_8, 0},
{"park_joy_90p_8_422.y4m", 8, VPX_IMG_FMT_I422, VPX_BITS_8, 1},
{"park_joy_90p_8_444.y4m", 8, VPX_IMG_FMT_I444, VPX_BITS_8, 1},
{"park_joy_90p_8_440.yuv", 8, VPX_IMG_FMT_I440, VPX_BITS_8, 1},
#if CONFIG_VP9_HIGHBITDEPTH
{"park_joy_90p_10_420.y4m", 10, VPX_IMG_FMT_I42016, VPX_BITS_10, 2},
{"park_joy_90p_10_422.y4m", 10, VPX_IMG_FMT_I42216, VPX_BITS_10, 3},
{"park_joy_90p_10_444.y4m", 10, VPX_IMG_FMT_I44416, VPX_BITS_10, 3},
{"park_joy_90p_10_440.yuv", 10, VPX_IMG_FMT_I44016, VPX_BITS_10, 3},
{"park_joy_90p_12_420.y4m", 12, VPX_IMG_FMT_I42016, VPX_BITS_12, 2},
{"park_joy_90p_12_422.y4m", 12, VPX_IMG_FMT_I42216, VPX_BITS_12, 3},
{"park_joy_90p_12_444.y4m", 12, VPX_IMG_FMT_I44416, VPX_BITS_12, 3},
{"park_joy_90p_12_440.yuv", 12, VPX_IMG_FMT_I44016, VPX_BITS_12, 3},
#endif // CONFIG_VP9_HIGHBITDEPTH
};
// Encoding modes tested
const libvpx_test::TestMode kEncodingModeVectors[] = {
::libvpx_test::kTwoPassGood,
::libvpx_test::kOnePassGood,
::libvpx_test::kRealTime,
};
// Speed settings tested
const int kCpuUsedVectors[] = {1, 2, 3, 5, 6};
int is_extension_y4m(const char *filename) {
const char *dot = strrchr(filename, '.');
if (!dot || dot == filename)
return 0;
else
return !strcmp(dot, ".y4m");
}
class EndToEndTestLarge
: public ::libvpx_test::EncoderTest,
public ::libvpx_test::CodecTestWith3Params<libvpx_test::TestMode, \
TestVideoParam, int> {
protected:
EndToEndTestLarge()
: EncoderTest(GET_PARAM(0)),
test_video_param_(GET_PARAM(2)),
cpu_used_(GET_PARAM(3)),
psnr_(0.0),
nframes_(0),
encoding_mode_(GET_PARAM(1)) {
}
virtual ~EndToEndTestLarge() {}
virtual void SetUp() {
InitializeConfig();
SetMode(encoding_mode_);
if (encoding_mode_ != ::libvpx_test::kRealTime) {
cfg_.g_lag_in_frames = 5;
cfg_.rc_end_usage = VPX_VBR;
} else {
cfg_.g_lag_in_frames = 0;
cfg_.rc_end_usage = VPX_CBR;
cfg_.rc_buf_sz = 1000;
cfg_.rc_buf_initial_sz = 500;
cfg_.rc_buf_optimal_sz = 600;
}
dec_cfg_.threads = 4;
}
virtual void BeginPassHook(unsigned int) {
psnr_ = 0.0;
nframes_ = 0;
}
virtual void PSNRPktHook(const vpx_codec_cx_pkt_t *pkt) {
psnr_ += pkt->data.psnr.psnr[0];
nframes_++;
}
virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video,
::libvpx_test::Encoder *encoder) {
if (video->frame() == 1) {
encoder->Control(VP9E_SET_FRAME_PARALLEL_DECODING, 1);
encoder->Control(VP9E_SET_TILE_COLUMNS, 4);
encoder->Control(VP8E_SET_CPUUSED, cpu_used_);
// Test screen coding tools at cpu_used = 1 && encoding mode is two-pass.
if (cpu_used_ == 1 && encoding_mode_ == ::libvpx_test::kTwoPassGood)
encoder->Control(VP9E_SET_TUNE_CONTENT, VP9E_CONTENT_SCREEN);
else
encoder->Control(VP9E_SET_TUNE_CONTENT, VP9E_CONTENT_DEFAULT);
if (encoding_mode_ != ::libvpx_test::kRealTime) {
encoder->Control(VP8E_SET_ENABLEAUTOALTREF, 1);
encoder->Control(VP8E_SET_ARNR_MAXFRAMES, 7);
encoder->Control(VP8E_SET_ARNR_STRENGTH, 5);
encoder->Control(VP8E_SET_ARNR_TYPE, 3);
}
}
}
double GetAveragePsnr() const {
if (nframes_)
return psnr_ / nframes_;
return 0.0;
}
double GetPsnrThreshold() {
return kPsnrThreshold[cpu_used_][encoding_mode_];
}
TestVideoParam test_video_param_;
int cpu_used_;
private:
double psnr_;
unsigned int nframes_;
libvpx_test::TestMode encoding_mode_;
};
TEST_P(EndToEndTestLarge, EndtoEndPSNRTest) {
cfg_.rc_target_bitrate = kBitrate;
cfg_.g_error_resilient = 0;
cfg_.g_profile = test_video_param_.profile;
cfg_.g_input_bit_depth = test_video_param_.input_bit_depth;
cfg_.g_bit_depth = test_video_param_.bit_depth;
init_flags_ = VPX_CODEC_USE_PSNR;
if (cfg_.g_bit_depth > 8)
init_flags_ |= VPX_CODEC_USE_HIGHBITDEPTH;
libvpx_test::VideoSource *video;
if (is_extension_y4m(test_video_param_.filename)) {
video = new libvpx_test::Y4mVideoSource(test_video_param_.filename,
0, kFrames);
} else {
video = new libvpx_test::YUVVideoSource(test_video_param_.filename,
test_video_param_.fmt,
kWidth, kHeight,
kFramerate, 1, 0, kFrames);
}
ASSERT_NO_FATAL_FAILURE(RunLoop(video));
const double psnr = GetAveragePsnr();
EXPECT_GT(psnr, GetPsnrThreshold());
delete(video);
}
VP9_INSTANTIATE_TEST_CASE(
EndToEndTestLarge,
::testing::ValuesIn(kEncodingModeVectors),
::testing::ValuesIn(kTestVectors),
::testing::ValuesIn(kCpuUsedVectors));
#if CONFIG_VP9_HIGHBITDEPTH
# if CONFIG_VP10_ENCODER
INSTANTIATE_TEST_CASE_P(
VP10, EndToEndTestLarge,
::testing::Combine(
::testing::Values(static_cast<const libvpx_test::CodecFactory *>(
&libvpx_test::kVP10)),
::testing::ValuesIn(kEncodingModeVectors),
::testing::ValuesIn(kTestVectors),
::testing::ValuesIn(kCpuUsedVectors)));
#endif // CONFIG_VP10_ENCODER
#endif // CONFIG_VP9_HIGHBITDEPTH
} // namespace
|
/*
* Copyright (c) 2014 The WebM project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "third_party/googletest/src/include/gtest/gtest.h"
#include "test/codec_factory.h"
#include "test/encode_test_driver.h"
#include "test/util.h"
#include "test/y4m_video_source.h"
#include "test/yuv_video_source.h"
namespace {
const unsigned int kWidth = 160;
const unsigned int kHeight = 90;
const unsigned int kFramerate = 50;
const unsigned int kFrames = 10;
const int kBitrate = 500;
// List of psnr thresholds for speed settings 0-7 and 5 encoding modes
const double kPsnrThreshold[][5] = {
// Note:
// VP10 HBD average PSNR is slightly lower than VP9.
// We make two cases here to enable the testing and
// guard picture quality.
#if CONFIG_VP10_ENCODER && CONFIG_VP9_HIGHBITDEPTH
{ 36.0, 37.0, 37.0, 37.0, 37.0 },
{ 31.0, 36.0, 36.0, 36.0, 36.0 },
{ 31.0, 35.0, 35.0, 35.0, 35.0 },
{ 31.0, 34.0, 34.0, 34.0, 34.0 },
{ 31.0, 33.0, 33.0, 33.0, 33.0 },
{ 31.0, 32.0, 32.0, 32.0, 32.0 },
{ 30.0, 31.0, 31.0, 31.0, 31.0 },
{ 29.0, 30.0, 30.0, 30.0, 30.0 },
#else
{ 36.0, 37.0, 37.0, 37.0, 37.0 },
{ 35.0, 36.0, 36.0, 36.0, 36.0 },
{ 34.0, 35.0, 35.0, 35.0, 35.0 },
{ 33.0, 34.0, 34.0, 34.0, 34.0 },
{ 32.0, 33.0, 33.0, 33.0, 33.0 },
{ 31.0, 32.0, 32.0, 32.0, 32.0 },
{ 30.0, 31.0, 31.0, 31.0, 31.0 },
{ 29.0, 30.0, 30.0, 30.0, 30.0 },
#endif // CONFIG_VP9_HIGHBITDEPTH && CONFIG_VP10_ENCODER
};
typedef struct {
const char *filename;
unsigned int input_bit_depth;
vpx_img_fmt fmt;
vpx_bit_depth_t bit_depth;
unsigned int profile;
} TestVideoParam;
const TestVideoParam kTestVectors[] = {
{"park_joy_90p_8_420.y4m", 8, VPX_IMG_FMT_I420, VPX_BITS_8, 0},
{"park_joy_90p_8_422.y4m", 8, VPX_IMG_FMT_I422, VPX_BITS_8, 1},
{"park_joy_90p_8_444.y4m", 8, VPX_IMG_FMT_I444, VPX_BITS_8, 1},
{"park_joy_90p_8_440.yuv", 8, VPX_IMG_FMT_I440, VPX_BITS_8, 1},
#if CONFIG_VP9_HIGHBITDEPTH
{"park_joy_90p_10_420.y4m", 10, VPX_IMG_FMT_I42016, VPX_BITS_10, 2},
{"park_joy_90p_10_422.y4m", 10, VPX_IMG_FMT_I42216, VPX_BITS_10, 3},
{"park_joy_90p_10_444.y4m", 10, VPX_IMG_FMT_I44416, VPX_BITS_10, 3},
{"park_joy_90p_10_440.yuv", 10, VPX_IMG_FMT_I44016, VPX_BITS_10, 3},
{"park_joy_90p_12_420.y4m", 12, VPX_IMG_FMT_I42016, VPX_BITS_12, 2},
{"park_joy_90p_12_422.y4m", 12, VPX_IMG_FMT_I42216, VPX_BITS_12, 3},
{"park_joy_90p_12_444.y4m", 12, VPX_IMG_FMT_I44416, VPX_BITS_12, 3},
{"park_joy_90p_12_440.yuv", 12, VPX_IMG_FMT_I44016, VPX_BITS_12, 3},
#endif // CONFIG_VP9_HIGHBITDEPTH
};
// Encoding modes tested
const libvpx_test::TestMode kEncodingModeVectors[] = {
::libvpx_test::kTwoPassGood,
::libvpx_test::kOnePassGood,
::libvpx_test::kRealTime,
};
// Speed settings tested
const int kCpuUsedVectors[] = {1, 2, 3, 5, 6};
int is_extension_y4m(const char *filename) {
const char *dot = strrchr(filename, '.');
if (!dot || dot == filename)
return 0;
else
return !strcmp(dot, ".y4m");
}
class EndToEndTestLarge
: public ::libvpx_test::EncoderTest,
public ::libvpx_test::CodecTestWith3Params<libvpx_test::TestMode, \
TestVideoParam, int> {
protected:
EndToEndTestLarge()
: EncoderTest(GET_PARAM(0)),
test_video_param_(GET_PARAM(2)),
cpu_used_(GET_PARAM(3)),
psnr_(0.0),
nframes_(0),
encoding_mode_(GET_PARAM(1)) {
}
virtual ~EndToEndTestLarge() {}
virtual void SetUp() {
InitializeConfig();
SetMode(encoding_mode_);
if (encoding_mode_ != ::libvpx_test::kRealTime) {
cfg_.g_lag_in_frames = 5;
cfg_.rc_end_usage = VPX_VBR;
} else {
cfg_.g_lag_in_frames = 0;
cfg_.rc_end_usage = VPX_CBR;
cfg_.rc_buf_sz = 1000;
cfg_.rc_buf_initial_sz = 500;
cfg_.rc_buf_optimal_sz = 600;
}
dec_cfg_.threads = 4;
}
virtual void BeginPassHook(unsigned int) {
psnr_ = 0.0;
nframes_ = 0;
}
virtual void PSNRPktHook(const vpx_codec_cx_pkt_t *pkt) {
psnr_ += pkt->data.psnr.psnr[0];
nframes_++;
}
virtual void PreEncodeFrameHook(::libvpx_test::VideoSource *video,
::libvpx_test::Encoder *encoder) {
if (video->frame() == 1) {
encoder->Control(VP9E_SET_FRAME_PARALLEL_DECODING, 1);
encoder->Control(VP9E_SET_TILE_COLUMNS, 4);
encoder->Control(VP8E_SET_CPUUSED, cpu_used_);
// Test screen coding tools at cpu_used = 1 && encoding mode is two-pass.
if (cpu_used_ == 1 && encoding_mode_ == ::libvpx_test::kTwoPassGood)
encoder->Control(VP9E_SET_TUNE_CONTENT, VP9E_CONTENT_SCREEN);
else
encoder->Control(VP9E_SET_TUNE_CONTENT, VP9E_CONTENT_DEFAULT);
if (encoding_mode_ != ::libvpx_test::kRealTime) {
encoder->Control(VP8E_SET_ENABLEAUTOALTREF, 1);
encoder->Control(VP8E_SET_ARNR_MAXFRAMES, 7);
encoder->Control(VP8E_SET_ARNR_STRENGTH, 5);
encoder->Control(VP8E_SET_ARNR_TYPE, 3);
}
}
}
double GetAveragePsnr() const {
if (nframes_)
return psnr_ / nframes_;
return 0.0;
}
double GetPsnrThreshold() {
return kPsnrThreshold[cpu_used_][encoding_mode_];
}
TestVideoParam test_video_param_;
int cpu_used_;
private:
double psnr_;
unsigned int nframes_;
libvpx_test::TestMode encoding_mode_;
};
TEST_P(EndToEndTestLarge, EndtoEndPSNRTest) {
cfg_.rc_target_bitrate = kBitrate;
cfg_.g_error_resilient = 0;
cfg_.g_profile = test_video_param_.profile;
cfg_.g_input_bit_depth = test_video_param_.input_bit_depth;
cfg_.g_bit_depth = test_video_param_.bit_depth;
init_flags_ = VPX_CODEC_USE_PSNR;
if (cfg_.g_bit_depth > 8)
init_flags_ |= VPX_CODEC_USE_HIGHBITDEPTH;
libvpx_test::VideoSource *video;
if (is_extension_y4m(test_video_param_.filename)) {
video = new libvpx_test::Y4mVideoSource(test_video_param_.filename,
0, kFrames);
} else {
video = new libvpx_test::YUVVideoSource(test_video_param_.filename,
test_video_param_.fmt,
kWidth, kHeight,
kFramerate, 1, 0, kFrames);
}
ASSERT_NO_FATAL_FAILURE(RunLoop(video));
const double psnr = GetAveragePsnr();
EXPECT_GT(psnr, GetPsnrThreshold());
delete(video);
}
VP9_INSTANTIATE_TEST_CASE(
EndToEndTestLarge,
::testing::ValuesIn(kEncodingModeVectors),
::testing::ValuesIn(kTestVectors),
::testing::ValuesIn(kCpuUsedVectors));
#if CONFIG_VP9_HIGHBITDEPTH
# if CONFIG_VP10_ENCODER
INSTANTIATE_TEST_CASE_P(
VP10, EndToEndTestLarge,
::testing::Combine(
::testing::Values(static_cast<const libvpx_test::CodecFactory *>(
&libvpx_test::kVP10)),
::testing::ValuesIn(kEncodingModeVectors),
::testing::ValuesIn(kTestVectors),
::testing::ValuesIn(kCpuUsedVectors)));
#endif // CONFIG_VP10_ENCODER
#endif // CONFIG_VP9_HIGHBITDEPTH
} // namespace
|
Fix vp9_end_to_end_test for vp10 HBD
|
Fix vp9_end_to_end_test for vp10 HBD
This test is failing when no experiments are turned on. PSNR is
31.96 when the threshold is 32.
broken since:
0d6980d Remove swap buffer speed feature
Change-Id: I3c29815b40d5282c37f52f4345b56992f8558b2e
|
C++
|
bsd-2-clause
|
GrokImageCompression/aom,GrokImageCompression/aom,mbebenita/aom,GrokImageCompression/aom,mbebenita/aom,luctrudeau/aom,mbebenita/aom,GrokImageCompression/aom,smarter/aom,luctrudeau/aom,mbebenita/aom,mbebenita/aom,mbebenita/aom,smarter/aom,mbebenita/aom,GrokImageCompression/aom,smarter/aom,luctrudeau/aom,smarter/aom,luctrudeau/aom,GrokImageCompression/aom,smarter/aom,mbebenita/aom,smarter/aom,luctrudeau/aom,luctrudeau/aom,mbebenita/aom
|
9982c5970c9c2e2049cbb4e7729ed421c1a58f28
|
src/xSW01.cpp
|
src/xSW01.cpp
|
/*
This is a library for the SW01
DIGITAL HUMIDITY, PRESSURE AND TEMPERATURE SENSOR
The board uses I2C for communication.
The board communicates with the following I2C device:
- BME280
Data Sheets:
BME280 - https://ae-bst.resource.bosch.com/media/_tech/media/datasheets/BST-BME280_DS001-11.pdf
*/
#include "xSW01.h"
#include <math.h>
/*--Public Class Function--*/
/********************************************************
Constructor
*********************************************************/
xSW01::xSW01(void)
{
tempcal = 0.0;
temperature = 0.0;
humidity = 0.0;
ressure = 0.0;
altitude = 0.0;
}
/********************************************************
Configure Sensor
*********************************************************/
bool xSW01::begin(void)
{
readSensorCoefficients();
xCore.write8(BME280_I2C_ADDRESS, BME280_REG_CONTROLHUMID, 0x01);
xCore.write8(BME280_I2C_ADDRESS, BME280_REG_CONTROLMEASURE, 0x3F);
return true;
}
/********************************************************
Read Data from BME280 Sensor
*********************************************************/
void xSW01::poll(void)
{
readTemperature();
readHumidity();
readPressure();
}
/********************************************************
Read Pressure from BME280 Sensor in Pa
*********************************************************/
float xSW01::getPressure(void)
{
return pressure;
}
/********************************************************
Read Altitude from BME280 Sensor
*********************************************************/
float xSW01::getAltitude(void)
{
float atmospheric = pressure / 100.0F;
altitude = 44330.0 * (1.0 - pow(atmospheric / 1013.25, 0.1903));
return altitude;
}
/********************************************************
Convert Temperature from BME280 Sensor to Celcuis
*********************************************************/
float xSW01::getTemperature_C(void)
{
temperature = temperature + tempcal;
return temperature;
}
/********************************************************
Convert Temperature from BME280 Sensor to Farenhied
*********************************************************/
float xSW01::getTemperature_F(void)
{
temperature = temperature + tempcal;
return temperature * 1.8 + 32;
}
/********************************************************
Read Humidity from BME280 Sensor
*********************************************************/
float xSW01::getHumidity(void)
{
return humidity;
}
/********************************************************
Set temperature calibration data
*********************************************************/
void xSW01::setTempCal(float offset)
{
tempcal = offset;
}
/*--Private Class Function--*/
/********************************************************
Read Temperature from BME280 Sensor
*********************************************************/
void xSW01::readTemperature(void)
{
int32_t var1, var2;
int32_t rawTemp = xCore.read24(BME280_I2C_ADDRESS, BME280_REG_TEMP);
rawTemp >>= 4;
var1 = ((((rawTemp >>3) - ((int32_t)cal_data.dig_T1 <<1))) *
((int32_t)cal_data.dig_T2)) >> 11;
var2 = (((((rawTemp >>4) - ((int32_t)cal_data.dig_T1)) *
((rawTemp >>4) - ((int32_t)cal_data.dig_T1))) >> 12) *
((int32_t)cal_data.dig_T3)) >> 14;
t_fine = var1 + var2;
temperature = (t_fine * 5 + 128) >> 8;
temperature = temperature / 100;
}
/********************************************************
Read Pressure from BME280 Sensor
*********************************************************/
void xSW01::readPressure(void)
{
int64_t var1, var2, p;
int32_t rawPressure = xCore.read24(BME280_I2C_ADDRESS, BME280_REG_PRESSURE);
rawPressure >>= 4;
var1 = ((int64_t)t_fine) - 128000;
var2 = var1 * var1 * (int64_t)cal_data.dig_P6;
var2 = var2 + ((var1*(int64_t)cal_data.dig_P5)<<17);
var2 = var2 + (((int64_t)cal_data.dig_P4)<<35);
var1 = ((var1 * var1 * (int64_t)cal_data.dig_P3)>>8) +
((var1 * (int64_t)cal_data.dig_P2)<<12);
var1 = (((((int64_t)1)<<47)+var1))*((int64_t)cal_data.dig_P1)>>33;
if (var1 == 0) {
pressure = 0.0;
}
p = 1048576 - rawPressure;
p = (((p<<31) - var2)*3125) / var1;
var1 = (((int64_t)cal_data.dig_P9) * (p>>13) * (p>>13)) >> 25;
var2 = (((int64_t)cal_data.dig_P8) * p) >> 19;
p = ((p + var1 + var2) >> 8) + (((int64_t)cal_data.dig_P7)<<4);
pressure = (float)p/256;
}
/********************************************************
Read Humidity from BME280 Sensor
*********************************************************/
void xSW01::readHumidity(void)
{
int32_t rawHumidity = xCore.read16(BME280_I2C_ADDRESS, BME280_REG_HUMID);
int32_t v_x1_u32r;
v_x1_u32r = (t_fine - ((int32_t)76800));
v_x1_u32r = (((((rawHumidity << 14) - (((int32_t)cal_data.dig_H4) << 20) -
(((int32_t)cal_data.dig_H5) * v_x1_u32r)) + ((int32_t)16384)) >> 15) *
(((((((v_x1_u32r * ((int32_t)cal_data.dig_H6)) >> 10) * (((v_x1_u32r *
((int32_t)cal_data.dig_H3)) >> 11) + ((int32_t)32768))) >> 10) +
((int32_t)2097152)) * ((int32_t)cal_data.dig_H2) + 8192) >> 14));
v_x1_u32r = (v_x1_u32r - (((((v_x1_u32r >> 15) * (v_x1_u32r >> 15)) >> 7) *
((int32_t)cal_data.dig_H1)) >> 4));
v_x1_u32r = (v_x1_u32r < 0) ? 0 : v_x1_u32r;
v_x1_u32r = (v_x1_u32r > 419430400) ? 419430400 : v_x1_u32r;
float h = (v_x1_u32r>>12);
humidity = h / 1024.0;
}
/********************************************************
Read Sensor Cailbration Data from BME280 Sensor
*********************************************************/
void xSW01::readSensorCoefficients(void)
{
cal_data.dig_T1 = xCore.read16_LE(BME280_I2C_ADDRESS, BME280_DIG_T1_REG);
cal_data.dig_T2 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_T2_REG);
cal_data.dig_T3 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_T3_REG);
cal_data.dig_P1 = xCore.read16_LE(BME280_I2C_ADDRESS, BME280_DIG_P1_REG);
cal_data.dig_P2 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P2_REG);
cal_data.dig_P3 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P3_REG);
cal_data.dig_P4 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P4_REG);
cal_data.dig_P5 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P5_REG);
cal_data.dig_P6 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P6_REG);
cal_data.dig_P7 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P7_REG);
cal_data.dig_P8 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P8_REG);
cal_data.dig_P9 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P9_REG);
cal_data.dig_H1 = xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H1_REG);
cal_data.dig_H2 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_H2_REG);
cal_data.dig_H3 = xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H3_REG);
cal_data.dig_H4 = (xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H4_REG) << 4) | (xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H4_REG+1) & 0xF);
cal_data.dig_H5 = (xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H5_REG+1) << 4) | (xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H5_REG) >> 4);
cal_data.dig_H6 = (int8_t)xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H6_REG);
}
xSW01 SW01 = xSW01();
|
/*
This is a library for the SW01
DIGITAL HUMIDITY, PRESSURE AND TEMPERATURE SENSOR
The board uses I2C for communication.
The board communicates with the following I2C device:
- BME280
Data Sheets:
BME280 - https://ae-bst.resource.bosch.com/media/_tech/media/datasheets/BST-BME280_DS001-11.pdf
*/
#include "xSW01.h"
#include <math.h>
/*--Public Class Function--*/
/********************************************************
Constructor
*********************************************************/
xSW01::xSW01(void)
{
tempcal = 0.0;
temperature = 0.0;
humidity = 0.0;
pressure = 0.0;
altitude = 0.0;
}
/********************************************************
Configure Sensor
*********************************************************/
bool xSW01::begin(void)
{
readSensorCoefficients();
xCore.write8(BME280_I2C_ADDRESS, BME280_REG_CONTROLHUMID, 0x01);
xCore.write8(BME280_I2C_ADDRESS, BME280_REG_CONTROLMEASURE, 0x3F);
return true;
}
/********************************************************
Read Data from BME280 Sensor
*********************************************************/
void xSW01::poll(void)
{
readTemperature();
readHumidity();
readPressure();
}
/********************************************************
Read Pressure from BME280 Sensor in Pa
*********************************************************/
float xSW01::getPressure(void)
{
return pressure;
}
/********************************************************
Read Altitude from BME280 Sensor
*********************************************************/
float xSW01::getAltitude(void)
{
float atmospheric = pressure / 100.0F;
altitude = 44330.0 * (1.0 - pow(atmospheric / 1013.25, 0.1903));
return altitude;
}
/********************************************************
Convert Temperature from BME280 Sensor to Celcuis
*********************************************************/
float xSW01::getTemperature_C(void)
{
temperature = temperature + tempcal;
return temperature;
}
/********************************************************
Convert Temperature from BME280 Sensor to Farenhied
*********************************************************/
float xSW01::getTemperature_F(void)
{
temperature = temperature + tempcal;
return temperature * 1.8 + 32;
}
/********************************************************
Read Humidity from BME280 Sensor
*********************************************************/
float xSW01::getHumidity(void)
{
return humidity;
}
/********************************************************
Set temperature calibration data
*********************************************************/
void xSW01::setTempCal(float offset)
{
tempcal = offset;
}
/*--Private Class Function--*/
/********************************************************
Read Temperature from BME280 Sensor
*********************************************************/
void xSW01::readTemperature(void)
{
int32_t var1, var2;
int32_t rawTemp = xCore.read24(BME280_I2C_ADDRESS, BME280_REG_TEMP);
rawTemp >>= 4;
var1 = ((((rawTemp >>3) - ((int32_t)cal_data.dig_T1 <<1))) *
((int32_t)cal_data.dig_T2)) >> 11;
var2 = (((((rawTemp >>4) - ((int32_t)cal_data.dig_T1)) *
((rawTemp >>4) - ((int32_t)cal_data.dig_T1))) >> 12) *
((int32_t)cal_data.dig_T3)) >> 14;
t_fine = var1 + var2;
temperature = (t_fine * 5 + 128) >> 8;
temperature = temperature / 100;
}
/********************************************************
Read Pressure from BME280 Sensor
*********************************************************/
void xSW01::readPressure(void)
{
int64_t var1, var2, p;
int32_t rawPressure = xCore.read24(BME280_I2C_ADDRESS, BME280_REG_PRESSURE);
rawPressure >>= 4;
var1 = ((int64_t)t_fine) - 128000;
var2 = var1 * var1 * (int64_t)cal_data.dig_P6;
var2 = var2 + ((var1*(int64_t)cal_data.dig_P5)<<17);
var2 = var2 + (((int64_t)cal_data.dig_P4)<<35);
var1 = ((var1 * var1 * (int64_t)cal_data.dig_P3)>>8) +
((var1 * (int64_t)cal_data.dig_P2)<<12);
var1 = (((((int64_t)1)<<47)+var1))*((int64_t)cal_data.dig_P1)>>33;
if (var1 == 0) {
pressure = 0.0;
}
p = 1048576 - rawPressure;
p = (((p<<31) - var2)*3125) / var1;
var1 = (((int64_t)cal_data.dig_P9) * (p>>13) * (p>>13)) >> 25;
var2 = (((int64_t)cal_data.dig_P8) * p) >> 19;
p = ((p + var1 + var2) >> 8) + (((int64_t)cal_data.dig_P7)<<4);
pressure = (float)p/256;
}
/********************************************************
Read Humidity from BME280 Sensor
*********************************************************/
void xSW01::readHumidity(void)
{
int32_t rawHumidity = xCore.read16(BME280_I2C_ADDRESS, BME280_REG_HUMID);
int32_t v_x1_u32r;
v_x1_u32r = (t_fine - ((int32_t)76800));
v_x1_u32r = (((((rawHumidity << 14) - (((int32_t)cal_data.dig_H4) << 20) -
(((int32_t)cal_data.dig_H5) * v_x1_u32r)) + ((int32_t)16384)) >> 15) *
(((((((v_x1_u32r * ((int32_t)cal_data.dig_H6)) >> 10) * (((v_x1_u32r *
((int32_t)cal_data.dig_H3)) >> 11) + ((int32_t)32768))) >> 10) +
((int32_t)2097152)) * ((int32_t)cal_data.dig_H2) + 8192) >> 14));
v_x1_u32r = (v_x1_u32r - (((((v_x1_u32r >> 15) * (v_x1_u32r >> 15)) >> 7) *
((int32_t)cal_data.dig_H1)) >> 4));
v_x1_u32r = (v_x1_u32r < 0) ? 0 : v_x1_u32r;
v_x1_u32r = (v_x1_u32r > 419430400) ? 419430400 : v_x1_u32r;
float h = (v_x1_u32r>>12);
humidity = h / 1024.0;
}
/********************************************************
Read Sensor Cailbration Data from BME280 Sensor
*********************************************************/
void xSW01::readSensorCoefficients(void)
{
cal_data.dig_T1 = xCore.read16_LE(BME280_I2C_ADDRESS, BME280_DIG_T1_REG);
cal_data.dig_T2 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_T2_REG);
cal_data.dig_T3 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_T3_REG);
cal_data.dig_P1 = xCore.read16_LE(BME280_I2C_ADDRESS, BME280_DIG_P1_REG);
cal_data.dig_P2 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P2_REG);
cal_data.dig_P3 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P3_REG);
cal_data.dig_P4 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P4_REG);
cal_data.dig_P5 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P5_REG);
cal_data.dig_P6 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P6_REG);
cal_data.dig_P7 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P7_REG);
cal_data.dig_P8 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P8_REG);
cal_data.dig_P9 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_P9_REG);
cal_data.dig_H1 = xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H1_REG);
cal_data.dig_H2 = xCore.readS16_LE(BME280_I2C_ADDRESS, BME280_DIG_H2_REG);
cal_data.dig_H3 = xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H3_REG);
cal_data.dig_H4 = (xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H4_REG) << 4) | (xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H4_REG+1) & 0xF);
cal_data.dig_H5 = (xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H5_REG+1) << 4) | (xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H5_REG) >> 4);
cal_data.dig_H6 = (int8_t)xCore.read8(BME280_I2C_ADDRESS, BME280_DIG_H6_REG);
}
xSW01 SW01 = xSW01();
|
Update xSW01.cpp
|
Update xSW01.cpp
|
C++
|
mit
|
xinabox/xSW01
|
bdae268164cfb1cb1a1d92c30c9e8ea134fc58bf
|
Source/bindings/core/v8/V8AbstractEventListener.cpp
|
Source/bindings/core/v8/V8AbstractEventListener.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"
#include "bindings/core/v8/V8AbstractEventListener.h"
#include "bindings/core/v8/V8Binding.h"
#include "bindings/core/v8/V8Event.h"
#include "bindings/core/v8/V8EventListenerList.h"
#include "bindings/core/v8/V8EventTarget.h"
#include "bindings/core/v8/V8HiddenValue.h"
#include "core/events/BeforeUnloadEvent.h"
#include "core/events/Event.h"
#include "core/inspector/InspectorCounters.h"
#include "core/workers/WorkerGlobalScope.h"
namespace blink {
V8AbstractEventListener::V8AbstractEventListener(bool isAttribute, ScriptState* scriptState)
: EventListener(JSEventListenerType)
, m_isAttribute(isAttribute)
, m_scriptState(scriptState)
, m_isolate(scriptState->isolate())
{
if (isMainThread())
InspectorCounters::incrementCounter(InspectorCounters::JSEventListenerCounter);
}
V8AbstractEventListener::V8AbstractEventListener(bool isAttribute, v8::Isolate* isolate)
: EventListener(JSEventListenerType)
, m_isAttribute(isAttribute)
, m_scriptState(nullptr)
, m_isolate(isolate)
{
if (isMainThread())
InspectorCounters::incrementCounter(InspectorCounters::JSEventListenerCounter);
}
V8AbstractEventListener::~V8AbstractEventListener()
{
if (!m_listener.isEmpty()) {
v8::HandleScope scope(m_isolate);
V8EventListenerList::clearWrapper(m_listener.newLocal(isolate()), m_isAttribute, isolate());
}
if (isMainThread())
InspectorCounters::decrementCounter(InspectorCounters::JSEventListenerCounter);
}
void V8AbstractEventListener::handleEvent(ExecutionContext*, Event* event)
{
// Don't reenter V8 if execution was terminated in this instance of V8.
if (scriptState()->executionContext()->isJSExecutionForbidden())
return;
ASSERT(event);
// The callback function on XMLHttpRequest can clear the event listener and destroys 'this' object. Keep a local reference to it.
// See issue 889829.
RefPtr<V8AbstractEventListener> protect(this);
if (scriptState()->contextIsEmpty())
return;
ScriptState::Scope scope(scriptState());
// Get the V8 wrapper for the event object.
v8::Handle<v8::Value> jsEvent = toV8(event, scriptState()->context()->Global(), isolate());
if (jsEvent.IsEmpty())
return;
invokeEventHandler(event, v8::Local<v8::Value>::New(isolate(), jsEvent));
}
void V8AbstractEventListener::setListenerObject(v8::Handle<v8::Object> listener)
{
m_listener.set(isolate(), listener);
m_listener.setWeak(this, &setWeakCallback);
}
void V8AbstractEventListener::invokeEventHandler(Event* event, v8::Local<v8::Value> jsEvent)
{
// If jsEvent is empty, attempt to set it as a hidden value would crash v8.
if (jsEvent.IsEmpty())
return;
ASSERT(!scriptState()->contextIsEmpty());
v8::Local<v8::Value> returnValue;
{
// Catch exceptions thrown in the event handler so they do not propagate to javascript code that caused the event to fire.
v8::TryCatch tryCatch;
tryCatch.SetVerbose(true);
// Save the old 'event' property so we can restore it later.
v8::Local<v8::Value> savedEvent = V8HiddenValue::getHiddenValue(isolate(), scriptState()->context()->Global(), V8HiddenValue::event(isolate()));
tryCatch.Reset();
// Make the event available in the global object, so LocalDOMWindow can expose it.
V8HiddenValue::setHiddenValue(isolate(), scriptState()->context()->Global(), V8HiddenValue::event(isolate()), jsEvent);
tryCatch.Reset();
returnValue = callListenerFunction(jsEvent, event);
if (tryCatch.HasCaught())
event->target()->uncaughtExceptionInEventHandler();
if (!tryCatch.CanContinue()) { // Result of TerminateExecution().
if (scriptState()->executionContext()->isWorkerGlobalScope())
toWorkerGlobalScope(scriptState()->executionContext())->script()->forbidExecution();
return;
}
tryCatch.Reset();
// Restore the old event. This must be done for all exit paths through this method.
if (savedEvent.IsEmpty())
V8HiddenValue::setHiddenValue(isolate(), scriptState()->context()->Global(), V8HiddenValue::event(isolate()), v8::Undefined(isolate()));
else
V8HiddenValue::setHiddenValue(isolate(), scriptState()->context()->Global(), V8HiddenValue::event(isolate()), savedEvent);
tryCatch.Reset();
}
if (returnValue.IsEmpty())
return;
if (m_isAttribute && !returnValue->IsNull() && !returnValue->IsUndefined() && event->isBeforeUnloadEvent()) {
TOSTRING_VOID(V8StringResource<>, stringReturnValue, returnValue);
toBeforeUnloadEvent(event)->setReturnValue(stringReturnValue);
}
if (m_isAttribute && shouldPreventDefault(returnValue))
event->preventDefault();
}
bool V8AbstractEventListener::shouldPreventDefault(v8::Local<v8::Value> returnValue)
{
// Prevent default action if the return value is false in accord with the spec
// http://www.w3.org/TR/html5/webappapis.html#event-handler-attributes
return returnValue->IsBoolean() && !returnValue->BooleanValue();
}
v8::Local<v8::Object> V8AbstractEventListener::getReceiverObject(Event* event)
{
v8::Local<v8::Object> listener = m_listener.newLocal(isolate());
if (!m_listener.isEmpty() && !listener->IsFunction())
return listener;
EventTarget* target = event->currentTarget();
v8::Handle<v8::Value> value = toV8(target, scriptState()->context()->Global(), isolate());
if (value.IsEmpty())
return v8::Local<v8::Object>();
return v8::Local<v8::Object>::New(isolate(), v8::Handle<v8::Object>::Cast(value));
}
bool V8AbstractEventListener::belongsToTheCurrentWorld() const
{
return isolate()->InContext() && &world() == &DOMWrapperWorld::current(isolate());
}
void V8AbstractEventListener::setWeakCallback(const v8::WeakCallbackData<v8::Object, V8AbstractEventListener> &data)
{
data.GetParameter()->m_listener.clear();
}
} // namespace blink
|
/*
* 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"
#include "bindings/core/v8/V8AbstractEventListener.h"
#include "bindings/core/v8/V8Binding.h"
#include "bindings/core/v8/V8Event.h"
#include "bindings/core/v8/V8EventListenerList.h"
#include "bindings/core/v8/V8EventTarget.h"
#include "bindings/core/v8/V8HiddenValue.h"
#include "core/events/BeforeUnloadEvent.h"
#include "core/events/Event.h"
#include "core/inspector/InspectorCounters.h"
#include "core/workers/WorkerGlobalScope.h"
namespace blink {
V8AbstractEventListener::V8AbstractEventListener(bool isAttribute, ScriptState* scriptState)
: EventListener(JSEventListenerType)
, m_isAttribute(isAttribute)
, m_scriptState(scriptState)
, m_isolate(scriptState->isolate())
{
if (isMainThread())
InspectorCounters::incrementCounter(InspectorCounters::JSEventListenerCounter);
}
V8AbstractEventListener::V8AbstractEventListener(bool isAttribute, v8::Isolate* isolate)
: EventListener(JSEventListenerType)
, m_isAttribute(isAttribute)
, m_scriptState(nullptr)
, m_isolate(isolate)
{
if (isMainThread())
InspectorCounters::incrementCounter(InspectorCounters::JSEventListenerCounter);
}
V8AbstractEventListener::~V8AbstractEventListener()
{
if (!m_listener.isEmpty()) {
v8::HandleScope scope(m_isolate);
V8EventListenerList::clearWrapper(m_listener.newLocal(isolate()), m_isAttribute, isolate());
}
if (isMainThread())
InspectorCounters::decrementCounter(InspectorCounters::JSEventListenerCounter);
}
void V8AbstractEventListener::handleEvent(ExecutionContext*, Event* event)
{
if (scriptState()->contextIsEmpty())
return;
if (!scriptState()->executionContext())
return;
// Don't reenter V8 if execution was terminated in this instance of V8.
if (scriptState()->executionContext()->isJSExecutionForbidden())
return;
ASSERT(event);
// The callback function on XMLHttpRequest can clear the event listener and destroys 'this' object. Keep a local reference to it.
// See issue 889829.
RefPtr<V8AbstractEventListener> protect(this);
ScriptState::Scope scope(scriptState());
// Get the V8 wrapper for the event object.
v8::Handle<v8::Value> jsEvent = toV8(event, scriptState()->context()->Global(), isolate());
if (jsEvent.IsEmpty())
return;
invokeEventHandler(event, v8::Local<v8::Value>::New(isolate(), jsEvent));
}
void V8AbstractEventListener::setListenerObject(v8::Handle<v8::Object> listener)
{
m_listener.set(isolate(), listener);
m_listener.setWeak(this, &setWeakCallback);
}
void V8AbstractEventListener::invokeEventHandler(Event* event, v8::Local<v8::Value> jsEvent)
{
// If jsEvent is empty, attempt to set it as a hidden value would crash v8.
if (jsEvent.IsEmpty())
return;
ASSERT(!scriptState()->contextIsEmpty());
v8::Local<v8::Value> returnValue;
{
// Catch exceptions thrown in the event handler so they do not propagate to javascript code that caused the event to fire.
v8::TryCatch tryCatch;
tryCatch.SetVerbose(true);
// Save the old 'event' property so we can restore it later.
v8::Local<v8::Value> savedEvent = V8HiddenValue::getHiddenValue(isolate(), scriptState()->context()->Global(), V8HiddenValue::event(isolate()));
tryCatch.Reset();
// Make the event available in the global object, so LocalDOMWindow can expose it.
V8HiddenValue::setHiddenValue(isolate(), scriptState()->context()->Global(), V8HiddenValue::event(isolate()), jsEvent);
tryCatch.Reset();
returnValue = callListenerFunction(jsEvent, event);
if (tryCatch.HasCaught())
event->target()->uncaughtExceptionInEventHandler();
if (!tryCatch.CanContinue()) { // Result of TerminateExecution().
if (scriptState()->executionContext()->isWorkerGlobalScope())
toWorkerGlobalScope(scriptState()->executionContext())->script()->forbidExecution();
return;
}
tryCatch.Reset();
// Restore the old event. This must be done for all exit paths through this method.
if (savedEvent.IsEmpty())
V8HiddenValue::setHiddenValue(isolate(), scriptState()->context()->Global(), V8HiddenValue::event(isolate()), v8::Undefined(isolate()));
else
V8HiddenValue::setHiddenValue(isolate(), scriptState()->context()->Global(), V8HiddenValue::event(isolate()), savedEvent);
tryCatch.Reset();
}
if (returnValue.IsEmpty())
return;
if (m_isAttribute && !returnValue->IsNull() && !returnValue->IsUndefined() && event->isBeforeUnloadEvent()) {
TOSTRING_VOID(V8StringResource<>, stringReturnValue, returnValue);
toBeforeUnloadEvent(event)->setReturnValue(stringReturnValue);
}
if (m_isAttribute && shouldPreventDefault(returnValue))
event->preventDefault();
}
bool V8AbstractEventListener::shouldPreventDefault(v8::Local<v8::Value> returnValue)
{
// Prevent default action if the return value is false in accord with the spec
// http://www.w3.org/TR/html5/webappapis.html#event-handler-attributes
return returnValue->IsBoolean() && !returnValue->BooleanValue();
}
v8::Local<v8::Object> V8AbstractEventListener::getReceiverObject(Event* event)
{
v8::Local<v8::Object> listener = m_listener.newLocal(isolate());
if (!m_listener.isEmpty() && !listener->IsFunction())
return listener;
EventTarget* target = event->currentTarget();
v8::Handle<v8::Value> value = toV8(target, scriptState()->context()->Global(), isolate());
if (value.IsEmpty())
return v8::Local<v8::Object>();
return v8::Local<v8::Object>::New(isolate(), v8::Handle<v8::Object>::Cast(value));
}
bool V8AbstractEventListener::belongsToTheCurrentWorld() const
{
return isolate()->InContext() && &world() == &DOMWrapperWorld::current(isolate());
}
void V8AbstractEventListener::setWeakCallback(const v8::WeakCallbackData<v8::Object, V8AbstractEventListener> &data)
{
data.GetParameter()->m_listener.clear();
}
} // namespace blink
|
Fix a crash in V8AbstractEventListener::handleEvent
|
Fix a crash in V8AbstractEventListener::handleEvent
handleEvent() should check scriptState->contextIsEmpty() before doing anything that uses scriptState. This CL also adds a check for scriptState->executionContext() just in case (I'm not sure if it's really needed).
BUG=396104
TEST=I cannot reproduce the crash.
Review URL: https://codereview.chromium.org/411463006
git-svn-id: bf5cd6ccde378db821296732a091cfbcf5285fbd@178772 bbb929c8-8fbe-4397-9dbb-9b2b20218538
|
C++
|
bsd-3-clause
|
Pluto-tv/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,jtg-gg/blink,hgl888/blink-crosswalk-efl,PeterWangIntel/blink-crosswalk,smishenk/blink-crosswalk,Pluto-tv/blink-crosswalk,XiaosongWei/blink-crosswalk,ondra-novak/blink,hgl888/blink-crosswalk-efl,kurli/blink-crosswalk,smishenk/blink-crosswalk,PeterWangIntel/blink-crosswalk,modulexcite/blink,modulexcite/blink,XiaosongWei/blink-crosswalk,Bysmyyr/blink-crosswalk,Bysmyyr/blink-crosswalk,smishenk/blink-crosswalk,XiaosongWei/blink-crosswalk,nwjs/blink,XiaosongWei/blink-crosswalk,modulexcite/blink,kurli/blink-crosswalk,modulexcite/blink,ondra-novak/blink,jtg-gg/blink,PeterWangIntel/blink-crosswalk,hgl888/blink-crosswalk-efl,Pluto-tv/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,kurli/blink-crosswalk,kurli/blink-crosswalk,PeterWangIntel/blink-crosswalk,nwjs/blink,XiaosongWei/blink-crosswalk,ondra-novak/blink,nwjs/blink,smishenk/blink-crosswalk,jtg-gg/blink,smishenk/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,kurli/blink-crosswalk,hgl888/blink-crosswalk-efl,Bysmyyr/blink-crosswalk,ondra-novak/blink,modulexcite/blink,smishenk/blink-crosswalk,modulexcite/blink,hgl888/blink-crosswalk-efl,jtg-gg/blink,PeterWangIntel/blink-crosswalk,kurli/blink-crosswalk,smishenk/blink-crosswalk,hgl888/blink-crosswalk-efl,crosswalk-project/blink-crosswalk-efl,kurli/blink-crosswalk,modulexcite/blink,crosswalk-project/blink-crosswalk-efl,kurli/blink-crosswalk,PeterWangIntel/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,crosswalk-project/blink-crosswalk-efl,XiaosongWei/blink-crosswalk,nwjs/blink,Pluto-tv/blink-crosswalk,hgl888/blink-crosswalk-efl,smishenk/blink-crosswalk,ondra-novak/blink,XiaosongWei/blink-crosswalk,crosswalk-project/blink-crosswalk-efl,Bysmyyr/blink-crosswalk,nwjs/blink,nwjs/blink,jtg-gg/blink,jtg-gg/blink,nwjs/blink,hgl888/blink-crosswalk-efl,nwjs/blink,XiaosongWei/blink-crosswalk,jtg-gg/blink,ondra-novak/blink,PeterWangIntel/blink-crosswalk,smishenk/blink-crosswalk,Bysmyyr/blink-crosswalk,XiaosongWei/blink-crosswalk,jtg-gg/blink,Bysmyyr/blink-crosswalk,jtg-gg/blink,crosswalk-project/blink-crosswalk-efl,ondra-novak/blink,Bysmyyr/blink-crosswalk,PeterWangIntel/blink-crosswalk,Pluto-tv/blink-crosswalk,hgl888/blink-crosswalk-efl,ondra-novak/blink,modulexcite/blink,ondra-novak/blink,XiaosongWei/blink-crosswalk,kurli/blink-crosswalk,jtg-gg/blink,PeterWangIntel/blink-crosswalk,Bysmyyr/blink-crosswalk,hgl888/blink-crosswalk-efl,Bysmyyr/blink-crosswalk,Pluto-tv/blink-crosswalk,kurli/blink-crosswalk,nwjs/blink,modulexcite/blink,Pluto-tv/blink-crosswalk,Pluto-tv/blink-crosswalk,modulexcite/blink,Pluto-tv/blink-crosswalk,nwjs/blink,PeterWangIntel/blink-crosswalk,smishenk/blink-crosswalk,Pluto-tv/blink-crosswalk,Bysmyyr/blink-crosswalk
|
13fbe110fcb59e4e27cce3354115f7c1730b3964
|
src/linux.cpp
|
src/linux.cpp
|
/*
* Copyright 2013-2016 Christian Lockley
*
* 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 "watchdogd.hpp"
#include "linux.hpp"
#include "sub.hpp"
#include "repair.hpp"
#ifdef __linux__
static int ConfigureKernelOutOfMemoryKiller(void)
{
int fd = 0;
int dfd = 0;
dfd = open("/proc/self", O_DIRECTORY | O_RDONLY);
if (dfd == -1) {
Logmsg(LOG_ERR, "open failed: %s", MyStrerror(errno));
return -1;
}
fd = openat(dfd, "oom_score_adj", O_WRONLY);
if (fd == -1) {
Logmsg(LOG_ERR, "open failed: %s", MyStrerror(errno));
close(dfd);
return -1;
}
if (write(fd, "-1000", strlen("-1000")) < 0) {
Logmsg(LOG_ERR, "write failed: %s", MyStrerror(errno));
close(fd);
close(dfd);
return -1;
}
close(fd);
close(dfd);
return 0;
}
bool PlatformInit(void)
{
sd_notifyf(0, "READY=1\n" "MAINPID=%lu", (unsigned long)getppid());
if (ConfigureKernelOutOfMemoryKiller() < 0) {
Logmsg(LOG_ERR, "unable to configure out of memory killer");
return false;
}
prctl(PR_SET_DUMPABLE, 0, 0, 0, 0); //prevent children from ptrace() ing main process and helpers
return true;
}
int NativeShutdown(int errorcode, int kexec)
{
//http://cgit.freedesktop.org/systemd/systemd/tree/src/core/manager.c?id=f49fd1d57a429d4a05ac86352c017a845f8185b3
extern sig_atomic_t stopPing;
stopPing = 1;
if (kexec == 1) {
kill(1, SIGRTMIN + 6);
} else if (errorcode == WECMDREBOOT) {
kill(1, SIGRTMIN+5);
} else if (errorcode == WETEMP) {
kill(1, SIGRTMIN + 4);
} else if (errorcode == WECMDRESET) {
kill(1, SIGRTMIN + 15);
} else {
kill(1, SIGRTMIN + 5);
}
return 0;
}
int GetConsoleColumns(void)
{
struct winsize w = { 0 };
if (ioctl(0, TIOCGWINSZ, &w) < 0) {
return 80;
}
return w.ws_col;
}
int SystemdWatchdogEnabled(const int unset, long long int *const interval)
{
const char *str = getenv("WATCHDOG_USEC");
if (str == NULL) {
return -1;
}
const char *watchdogPid = getenv("WATCHDOG_PID");
if (watchdogPid != NULL) {
if (getpid() != (pid_t) strtoll(watchdogPid, NULL, 10)) {
return -1;
}
} else {
Logmsg(LOG_WARNING,
"Your version of systemd is out of date. Upgrade for better integration with watchdogd");
}
if (interval != NULL) {
if (strtoll(str, NULL, 10) < 0) {
return -1;
}
if (strtoll(str, NULL, 10) == 0) {
return 0;
}
*interval = strtoll(str, NULL, 10);
}
if (unset != 0) {
if (unsetenv("WATCHDOG_PID") < 0) {
Logmsg(LOG_WARNING,
"Unable to delete WATCHDOG_PID environment variable:%s",
MyStrerror(errno));
} else if (unsetenv("WATCHDOG_USEC") < 0) {
return -1;
}
}
return 1;
}
bool OnParentDeathSend(uintptr_t sig)
{
if (prctl(PR_SET_PDEATHSIG, (uintptr_t *)sig) == -1) {
return false;
}
return true;
}
int NoNewProvileges(void)
{
if (prctl(PR_SET_NO_NEW_PRIVS, 0, 0, 0, 0) < 0) {
if (errno != 0) {
return -errno;
} else {
return 1;
}
}
return 0;
}
int GetCpuCount(void)
{
return std::thread::hardware_concurrency();
}
bool LoadKernelModule(void)
{
pid_t pid = fork();
if (pid == 0) {
if (execl("/sbin/modprobe", "modprobe", "softdog", NULL) == -1) {
_Exit(1);
}
}
if (pid == -1) {
abort();
}
int ret = 0;
waitpid(pid, &ret, 0);
if (WEXITSTATUS(ret) == 0) {
return true;
}
return false;
}
bool MakeDeviceFile(const char *file)
{
return true;
}
static bool GetDeviceMajorMinor(struct dev *m, char *name)
{
if (name == NULL || m == NULL) {
return false;
}
char *tmp = basename(name);
size_t len = 0;
char *buf = NULL;
struct dev tmpdev = {0};
DIR *dir = opendir("/sys/dev/char");
if (dir == NULL) {
return false;
}
for (struct dirent *node = readdir(dir); node != NULL; node = readdir(dir)) {
if (node->d_name[0] == '.') {
continue;
}
Wasnprintf(&len, &buf, "/sys/dev/char/%s/uevent", node->d_name);
if (buf == NULL) {
abort();
}
FILE *fp = fopen(buf, "r");
if (fp == NULL) {
abort();
}
int x = 1;
while (getline(&buf, &len, fp) != -1) {
char *const name = strtok(buf, "=");
char *const value = strtok(NULL, "=");
if (Validate(name, value) == false) {
continue;
}
if (x == 1) {
tmpdev.major = strtoul(value, NULL, 0);
x++;
} else if (x == 2) {
tmpdev.minor = strtoul(value, NULL, 0);
x++;
} else if (x == 3) {
strcpy(tmpdev.name, value);
x = 1;
}
}
if (strcmp(tmpdev.name, tmp) == 0) {
closedir(dir);
free(buf);
fclose(fp);
strcpy(m->name, tmpdev.name);
m->major = tmpdev.major;
m->minor = tmpdev.minor;
return true;
}
fclose(fp);
}
closedir(dir);
free(buf);
return false;
}
int ConfigWatchdogNowayoutIsSet(char *name)
{
bool found = false;
char *buf = NULL;
gzFile config = gzopen("/proc/config.gz", "r");
if (config == NULL) {
return -1;
}
gzbuffer(config, 8192);
while (true) {
char buf[72] = {'\0'};
size_t bytesRead = gzread(config, buf, sizeof(buf) - 1);
if (strstr(buf, "# CONFIG_WATCHDOG_NOWAYOUT is not set") != NULL) {
found = true;
break;
}
if (bytesRead < sizeof(buf) - 1) {
if (gzeof(config)) {
break;
} else {
break;
}
}
}
gzclose(config);
struct dev ad = {0};
GetDeviceMajorMinor(&ad, name);
char * devicePath = NULL;
Wasprintf(&devicePath, "/sys/dev/char/%lu:%lu/device/driver", ad.major, ad.minor);
buf = (char *)calloc(1, 4096);
if (devicePath == NULL) {
abort();
}
readlink(devicePath, buf, 4096 - 1);
Wasprintf(&buf, "/sys/module/%s/parameters/nowayout", basename(buf));
free(devicePath);
FILE *fp = fopen(buf, "r");
if (fp != NULL) {
if (fgetc(fp) == '1') {
found = false;
}
fclose(fp);
}
free(buf);
if (found) {
return 0;
}
return 1;
}
bool IsClientAdmin(int sock)
{
struct ucred peercred;
socklen_t len = sizeof(struct ucred);
if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &peercred, &len) != 0) {
return false;
}
if (peercred.uid == 0) {
return true;
}
return false;
}
#endif
|
/*
* Copyright 2013-2016 Christian Lockley
*
* 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 "watchdogd.hpp"
#include "linux.hpp"
#include "sub.hpp"
#include "repair.hpp"
#ifdef __linux__
static int ConfigureKernelOutOfMemoryKiller(void)
{
int fd = 0;
int dfd = 0;
dfd = open("/proc/self", O_DIRECTORY | O_RDONLY);
if (dfd == -1) {
Logmsg(LOG_ERR, "open failed: %s", MyStrerror(errno));
return -1;
}
fd = openat(dfd, "oom_score_adj", O_WRONLY);
if (fd == -1) {
Logmsg(LOG_ERR, "open failed: %s", MyStrerror(errno));
close(dfd);
return -1;
}
if (write(fd, "-1000", strlen("-1000")) < 0) {
Logmsg(LOG_ERR, "write failed: %s", MyStrerror(errno));
close(fd);
close(dfd);
return -1;
}
close(fd);
close(dfd);
return 0;
}
bool PlatformInit(void)
{
sd_notifyf(0, "READY=1\n" "MAINPID=%lu", (unsigned long)getppid());
if (ConfigureKernelOutOfMemoryKiller() < 0) {
Logmsg(LOG_ERR, "unable to configure out of memory killer");
return false;
}
prctl(PR_SET_DUMPABLE, 0, 0, 0, 0); //prevent children from ptrace() ing main process and helpers
return true;
}
int NativeShutdown(int errorcode, int kexec)
{
//http://cgit.freedesktop.org/systemd/systemd/tree/src/core/manager.c?id=f49fd1d57a429d4a05ac86352c017a845f8185b3
extern sig_atomic_t stopPing;
stopPing = 1;
if (kexec == 1) {
kill(1, SIGRTMIN + 6);
} else if (errorcode == WECMDREBOOT) {
kill(1, SIGRTMIN+5);
} else if (errorcode == WETEMP) {
kill(1, SIGRTMIN + 4);
} else if (errorcode == WECMDRESET) {
kill(1, SIGRTMIN + 15);
} else {
kill(1, SIGRTMIN + 5);
}
return 0;
}
int GetConsoleColumns(void)
{
struct winsize w = { 0 };
if (ioctl(0, TIOCGWINSZ, &w) < 0) {
return 80;
}
return w.ws_col;
}
int SystemdWatchdogEnabled(const int unset, long long int *const interval)
{
const char *str = getenv("WATCHDOG_USEC");
if (str == NULL) {
return -1;
}
const char *watchdogPid = getenv("WATCHDOG_PID");
if (watchdogPid != NULL) {
if (getpid() != (pid_t) strtoll(watchdogPid, NULL, 10)) {
return -1;
}
} else {
Logmsg(LOG_WARNING,
"Your version of systemd is out of date. Upgrade for better integration with watchdogd");
}
if (interval != NULL) {
if (strtoll(str, NULL, 10) < 0) {
return -1;
}
if (strtoll(str, NULL, 10) == 0) {
return 0;
}
*interval = strtoll(str, NULL, 10);
}
if (unset != 0) {
if (unsetenv("WATCHDOG_PID") < 0) {
Logmsg(LOG_WARNING,
"Unable to delete WATCHDOG_PID environment variable:%s",
MyStrerror(errno));
} else if (unsetenv("WATCHDOG_USEC") < 0) {
return -1;
}
}
return 1;
}
bool OnParentDeathSend(uintptr_t sig)
{
if (prctl(PR_SET_PDEATHSIG, (uintptr_t *)sig) == -1) {
return false;
}
return true;
}
int NoNewProvileges(void)
{
if (prctl(PR_SET_NO_NEW_PRIVS, 0, 0, 0, 0) < 0) {
if (errno != 0) {
return -errno;
} else {
return 1;
}
}
return 0;
}
int GetCpuCount(void)
{
return std::thread::hardware_concurrency();
}
bool LoadKernelModule(void)
{
pid_t pid = vfork();
if (pid == 0) {
if (execl("/sbin/modprobe", "modprobe", "softdog", NULL) == -1) {
_Exit(1);
}
}
if (pid == -1) {
abort();
}
int ret = 0;
waitpid(pid, &ret, 0);
if (WEXITSTATUS(ret) == 0) {
return true;
}
return false;
}
bool MakeDeviceFile(const char *file)
{
return true;
}
static bool GetDeviceMajorMinor(struct dev *m, char *name)
{
if (name == NULL || m == NULL) {
return false;
}
char *tmp = basename(name);
size_t len = 0;
char *buf = NULL;
struct dev tmpdev = {0};
DIR *dir = opendir("/sys/dev/char");
if (dir == NULL) {
return false;
}
for (struct dirent *node = readdir(dir); node != NULL; node = readdir(dir)) {
if (node->d_name[0] == '.') {
continue;
}
Wasnprintf(&len, &buf, "/sys/dev/char/%s/uevent", node->d_name);
if (buf == NULL) {
abort();
}
FILE *fp = fopen(buf, "r");
if (fp == NULL) {
abort();
}
int x = 1;
while (getline(&buf, &len, fp) != -1) {
char *const name = strtok(buf, "=");
char *const value = strtok(NULL, "=");
if (Validate(name, value) == false) {
continue;
}
if (x == 1) {
tmpdev.major = strtoul(value, NULL, 0);
x++;
} else if (x == 2) {
tmpdev.minor = strtoul(value, NULL, 0);
x++;
} else if (x == 3) {
strcpy(tmpdev.name, value);
x = 1;
}
}
if (strcmp(tmpdev.name, tmp) == 0) {
closedir(dir);
free(buf);
fclose(fp);
strcpy(m->name, tmpdev.name);
m->major = tmpdev.major;
m->minor = tmpdev.minor;
return true;
}
fclose(fp);
}
closedir(dir);
free(buf);
return false;
}
int ConfigWatchdogNowayoutIsSet(char *name)
{
bool found = false;
char *buf = NULL;
gzFile config = gzopen("/proc/config.gz", "r");
if (config == NULL) {
return -1;
}
gzbuffer(config, 8192);
while (true) {
char buf[72] = {'\0'};
size_t bytesRead = gzread(config, buf, sizeof(buf) - 1);
if (strstr(buf, "# CONFIG_WATCHDOG_NOWAYOUT is not set") != NULL) {
found = true;
break;
}
if (bytesRead < sizeof(buf) - 1) {
if (gzeof(config)) {
break;
} else {
break;
}
}
}
gzclose(config);
struct dev ad = {0};
GetDeviceMajorMinor(&ad, name);
char * devicePath = NULL;
Wasprintf(&devicePath, "/sys/dev/char/%lu:%lu/device/driver", ad.major, ad.minor);
buf = (char *)calloc(1, 4096);
if (devicePath == NULL) {
abort();
}
readlink(devicePath, buf, 4096 - 1);
Wasprintf(&buf, "/sys/module/%s/parameters/nowayout", basename(buf));
free(devicePath);
FILE *fp = fopen(buf, "r");
if (fp != NULL) {
if (fgetc(fp) == '1') {
found = false;
}
fclose(fp);
}
free(buf);
if (found) {
return 0;
}
return 1;
}
bool IsClientAdmin(int sock)
{
struct ucred peercred;
socklen_t len = sizeof(struct ucred);
if (getsockopt(sock, SOL_SOCKET, SO_PEERCRED, &peercred, &len) != 0) {
return false;
}
if (peercred.uid == 0) {
return true;
}
return false;
}
#endif
|
use vfork+exec to run modprobe
|
use vfork+exec to run modprobe
|
C++
|
apache-2.0
|
clockley/watchdogd,clockley/watchdogd
|
fdeab9c570b914bd137e81a6b3fef6ceff32f34d
|
lib/strings/aho_corasick.cpp
|
lib/strings/aho_corasick.cpp
|
#include <bits/stdc++.h>
using namespace std;
// maximum sum of the lengths of all patterns
#define N int(1e6+5)
// alphabet size
#define A 52
// ascii ---> [0, A)
int cvt(char c) {
return islower(c) ? c-'a' : c-'A'+26;
}
// aho corasick trie
// node 0 is the root (empty string, the ultimate failure node).
// failure paths are compressed, so nodes[q].adj[a] is always the correct state.
struct trie {
// node stuff
int adj[A], id, len, f, out;
// static stuff
static trie nodes[N];
static int nxt;
static void reset() { memset(nodes,0,sizeof nodes); nxt = 1; }
static void insert(const char* s, int id) {
int q = 0, len = 0;
for (; *s; s++) {
int a = cvt(*s);
if (!nodes[q].adj[a]) nodes[q].adj[a] = nxt++; // create node
q = nodes[q].adj[a]; // go through the edge
len++;
}
nodes[q].id = id; // pattern id
nodes[q].len = len; // pattern length
}
static void aho_corasick() {
queue<int> Q;
// failure, output and failure compression are always ready for root and
// its children.
for (int a = 0; a < A; a++) if (nodes[0].adj[a]) Q.push(nodes[0].adj[a]);
// bfs
while (!Q.empty()) {
int q = Q.front(); Q.pop();
for (int a = 0; a < A; a++) if (nodes[q].adj[a]) {
int u = nodes[q].adj[a];
Q.push(u);
// find failure link
int f = nodes[q].f; // start with parent failure
while (f && !nodes[f].adj[a]) f = nodes[f].f; // go through the links
f = nodes[f].adj[a]; // final failure goes through the edge
// set links
nodes[u].f = f; // failure link
nodes[u].out = (nodes[f].id ? f : nodes[f].out); // output link
} else nodes[q].adj[a] = nodes[nodes[q].f].adj[a]; // failure compression
}
}
static void match(const char* s, const function<void(int,int)>& outfunc) {
int q = 0, len = 0;
for (; *s; s++) {
q = nodes[q].adj[cvt(*s)]; // go through the edge
len++;
// output
if (nodes[q].id) outfunc(nodes[q].id,len-nodes[q].len); // current state
for (int u = nodes[q].out; u; u = nodes[u].out) { // output links
outfunc(nodes[u].id,len-nodes[u].len);
}
}
}
};
trie trie::nodes[N];
int trie::nxt;
// https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1620
int main() {
int k;
scanf("%d",&k);
while (k--) {
trie::reset();
// read text
static char t[int(1e5+5)];
scanf("%s",t);
// read patterns
int q;
scanf("%d",&q);
map<string,int> go; int nxt = 1; // this stuff handles...
static int id[int(1e3+5)]; // ...repeated patterns
for (int i = 1; i <= q; i++) {
static char p[int(1e3+5)];
scanf("%s",p);
if (!go.count(p)) { // new pattern
trie::insert(p,nxt);
go[p] = nxt++;
}
id[i] = go[p];
}
// match
trie::aho_corasick();
vector<bool> found(q+1,false);
trie::match(t,[&](int id, int pos) { found[id] = true; });
// output
for (int i = 1; i <= q; i++) printf(found[id[i]] ? "y\n" : "n\n");
}
return 0;
}
|
#include <bits/stdc++.h>
using namespace std;
// maximum sum of the lengths of all patterns
#define N int(1e6+5)
// alphabet size
#define A 52
// ascii ---> [0, A)
int cvt(char c) {
return islower(c) ? c-'a' : c-'A'+26;
}
// aho corasick trie
// node 0 is the root (empty string, the ultimate failure node).
// failure paths are compressed, so nodes[q].adj[a] is always the correct state.
struct trie {
// node stuff
int adj[A], id, len, f, out;
// static stuff
static trie nodes[N];
static int nxt;
static void reset() { memset(nodes,0,sizeof nodes); nxt = 1; }
static void insert(const char* s, int id) {
int q = 0, len = 0;
for (; *s; s++) {
int a = cvt(*s);
if (!nodes[q].adj[a]) nodes[q].adj[a] = nxt++; // create node
q = nodes[q].adj[a]; // go through the edge
len++;
}
nodes[q].id = id; // pattern id
nodes[q].len = len; // pattern length
}
static void aho_corasick() {
queue<int> Q;
// failure, output and failure compression are always ready for root and
// its children.
for (int a = 0; a < A; a++) if (nodes[0].adj[a]) Q.push(nodes[0].adj[a]);
// bfs
while (!Q.empty()) {
int q = Q.front(); Q.pop();
for (int a = 0; a < A; a++) if (nodes[q].adj[a]) {
int u = nodes[q].adj[a];
Q.push(u);
// find failure link
int f = nodes[q].f; // start with parent failure
f = nodes[f].adj[a]; // final failure goes through the edge
// set links
nodes[u].f = f; // failure link
nodes[u].out = (nodes[f].id ? f : nodes[f].out); // output link
} else nodes[q].adj[a] = nodes[nodes[q].f].adj[a]; // failure compression
}
}
static void match(const char* s, const function<void(int,int)>& outfunc) {
int q = 0, len = 0;
for (; *s; s++) {
q = nodes[q].adj[cvt(*s)]; // go through the edge
len++;
// output
if (nodes[q].id) outfunc(nodes[q].id,len-nodes[q].len); // current state
for (int u = nodes[q].out; u; u = nodes[u].out) { // output links
outfunc(nodes[u].id,len-nodes[u].len);
}
}
}
};
trie trie::nodes[N];
int trie::nxt;
// https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1620
int main() {
int k;
scanf("%d",&k);
while (k--) {
trie::reset();
// read text
static char t[int(1e5+5)];
scanf("%s",t);
// read patterns
int q;
scanf("%d",&q);
map<string,int> go; int nxt = 1; // this stuff handles...
static int id[int(1e3+5)]; // ...repeated patterns
for (int i = 1; i <= q; i++) {
static char p[int(1e3+5)];
scanf("%s",p);
if (!go.count(p)) { // new pattern
trie::insert(p,nxt);
go[p] = nxt++;
}
id[i] = go[p];
}
// match
trie::aho_corasick();
vector<bool> found(q+1,false);
trie::match(t,[&](int id, int pos) { found[id] = true; });
// output
for (int i = 1; i <= q; i++) printf(found[id[i]] ? "y\n" : "n\n");
}
return 0;
}
|
Remove unnecessary line in aho corasick
|
Remove unnecessary line in aho corasick
|
C++
|
mit
|
matheuscscp/problem-solving,matheuscscp/problem-solving,matheuscscp/problem-solving
|
07732decd920ceebebd13963a7bfc444c5d5eaa5
|
libdariadb/storage/chunk.cpp
|
libdariadb/storage/chunk.cpp
|
#include "chunk.h"
#include "bloom_filter.h"
#include <algorithm>
#include <cassert>
#include <cstring>
//TODO remove includes
#include "../compression.h"
#include "../compression/binarybuffer.h"
using namespace dariadb;
using namespace dariadb::utils;
using namespace dariadb::storage;
using namespace dariadb::compression;
std::unique_ptr<ChunkPool> ChunkPool::_instance=nullptr;
ChunkPool::ChunkPool(){
_max_size = ChunkPool_default_max_size;
}
ChunkPool::~ChunkPool(){
for(auto p:_ptrs){
:: operator delete(p);
}
}
void ChunkPool::start(size_t max_size){
if (max_size != 0) {
ChunkPool::instance()->_max_size = max_size;
}
}
void ChunkPool::stop(){
ChunkPool::_instance=nullptr;
}
ChunkPool*ChunkPool::instance(){
if(_instance==nullptr){
_instance=std::unique_ptr<ChunkPool>{new ChunkPool};
}
return _instance.get();
}
size_t ChunkPool::polled(){
return _ptrs.size();
}
void* ChunkPool::alloc(std::size_t sz){
std::lock_guard<std::mutex> lg(_mutex);
void*result=nullptr;
if(this->_ptrs.size()!=0){
result= this->_ptrs.back();
this->_ptrs.pop_back();
}else{
result=::operator new(sz);
}
memset(result,0,sz);
return result;
}
void ChunkPool::free(void* ptr, std::size_t){
std::lock_guard<std::mutex> lg(_mutex);
if (_ptrs.size() < _max_size) {
_ptrs.push_front(ptr);
}
else {
::operator delete(ptr);
}
}
void* Chunk::operator new(std::size_t sz){
return ChunkPool::instance()->alloc(sz);
}
void Chunk::operator delete(void* ptr, std::size_t sz){
ChunkPool::instance()->free(ptr,sz);
}
Chunk::Chunk(const ChunkIndexInfo&index, const uint8_t* buffer, const size_t buffer_length) :
_buffer_t(buffer_length),
_mutex{}
{
count = index.count;
first = index.first;
flag_bloom = index.flag_bloom;
last = index.last;
maxTime = index.maxTime;
minTime = index.minTime;
bw_pos = index.bw_pos;
bw_bit_num = index.bw_bit_num;
is_readonly = index.is_readonly;
is_dropped = index.is_dropped;
for (size_t i = 0; i < buffer_length; i++) {
_buffer_t[i] = buffer[i];
}
range = Range{ _buffer_t.data(),_buffer_t.data() + buffer_length };
assert(size_t(range.end - range.begin)==buffer_length);
bw = std::make_shared<BinaryBuffer>(range);
bw->set_bitnum(bw_bit_num);
bw->set_pos(bw_pos);
c_writer = compression::CopmressedWriter(bw);
c_writer.restore_position(index.writer_position);
}
Chunk::Chunk(size_t size, Meas first_m) :
_buffer_t(size),
_mutex()
{
is_readonly = false;
is_dropped=false;
count = 0;
first = first_m;
last = first_m;
minTime = std::numeric_limits<Time>::max();
maxTime = std::numeric_limits<Time>::min();
std::fill(_buffer_t.begin(), _buffer_t.end(), 0);
using compression::BinaryBuffer;
range = Range{ _buffer_t.data(),_buffer_t.data() + size };
bw = std::make_shared<BinaryBuffer>(range);
c_writer = compression::CopmressedWriter(bw);
c_writer.append(first);
minTime = first_m.time;
maxTime = first_m.time;
flag_bloom = dariadb::storage::bloom_empty<dariadb::Flag>();
}
Chunk::~Chunk() {
std::lock_guard<std::mutex> lg(_mutex);
}
bool Chunk::append(const Meas&m)
{
if (m.time == 59819) {
std::cout << "append to bug time\n";
}
if (minTime == 59817) {
std::cout << "append to bug\n";
auto bw_tmp = std::make_shared<dariadb::compression::BinaryBuffer>(this->bw->get_range());
bw_tmp->reset_pos();
dariadb::compression::CopmressedReader crr(bw_tmp, first);
for (size_t i = 0; i < count; i++) {
auto sub = crr.read();
std::cout << "sub: t" << sub.time
<< " v: " << sub.value
<< " f: " << sub.flag
<< " s: " << sub.src << std::endl;
}
}
assert(!is_readonly);
assert(!is_dropped);
std::lock_guard<std::mutex> lg(_mutex);
auto t_f = this->c_writer.append(m);
writer_position = c_writer.get_position();
if (!t_f) {
is_readonly = true;
assert(c_writer.is_full());
return false;
}
else {
bw_pos = uint32_t(bw->pos());
bw_bit_num = bw->bitnum();
count++;
minTime = std::min(minTime, m.time);
maxTime = std::max(maxTime, m.time);
flag_bloom = dariadb::storage::bloom_add(flag_bloom, m.flag);
last = m;
return true;
}
}
bool Chunk::check_flag(const Flag& f) {
if (f != 0) {
if (!dariadb::storage::bloom_check(flag_bloom, f)) {
return false;
}
}
return true;
}
|
#include "chunk.h"
#include "bloom_filter.h"
#include <algorithm>
#include <cassert>
#include <cstring>
//TODO remove includes
#include "../compression.h"
#include "../compression/binarybuffer.h"
using namespace dariadb;
using namespace dariadb::utils;
using namespace dariadb::storage;
using namespace dariadb::compression;
std::unique_ptr<ChunkPool> ChunkPool::_instance=nullptr;
ChunkPool::ChunkPool(){
_max_size = ChunkPool_default_max_size;
}
ChunkPool::~ChunkPool(){
for(auto p:_ptrs){
:: operator delete(p);
}
}
void ChunkPool::start(size_t max_size){
if (max_size != 0) {
ChunkPool::instance()->_max_size = max_size;
}
}
void ChunkPool::stop(){
ChunkPool::_instance=nullptr;
}
ChunkPool*ChunkPool::instance(){
if(_instance==nullptr){
_instance=std::unique_ptr<ChunkPool>{new ChunkPool};
}
return _instance.get();
}
size_t ChunkPool::polled(){
return _ptrs.size();
}
void* ChunkPool::alloc(std::size_t sz){
std::lock_guard<std::mutex> lg(_mutex);
void*result=nullptr;
if(this->_ptrs.size()!=0){
result= this->_ptrs.back();
this->_ptrs.pop_back();
}else{
result=::operator new(sz);
}
memset(result,0,sz);
return result;
}
void ChunkPool::free(void* ptr, std::size_t){
std::lock_guard<std::mutex> lg(_mutex);
if (_ptrs.size() < _max_size) {
_ptrs.push_front(ptr);
}
else {
::operator delete(ptr);
}
}
void* Chunk::operator new(std::size_t sz){
return ChunkPool::instance()->alloc(sz);
}
void Chunk::operator delete(void* ptr, std::size_t sz){
ChunkPool::instance()->free(ptr,sz);
}
Chunk::Chunk(const ChunkIndexInfo&index, const uint8_t* buffer, const size_t buffer_length) :
_buffer_t(buffer_length),
_mutex{}
{
count = index.count;
first = index.first;
flag_bloom = index.flag_bloom;
last = index.last;
maxTime = index.maxTime;
minTime = index.minTime;
bw_pos = index.bw_pos;
bw_bit_num = index.bw_bit_num;
is_readonly = index.is_readonly;
is_dropped = index.is_dropped;
for (size_t i = 0; i < buffer_length; i++) {
_buffer_t[i] = buffer[i];
}
range = Range{ _buffer_t.data(),_buffer_t.data() + buffer_length };
assert(size_t(range.end - range.begin)==buffer_length);
bw = std::make_shared<BinaryBuffer>(range);
bw->set_bitnum(bw_bit_num);
bw->set_pos(bw_pos);
c_writer = compression::CopmressedWriter(bw);
c_writer.restore_position(index.writer_position);
}
Chunk::Chunk(size_t size, Meas first_m) :
_buffer_t(size),
_mutex()
{
is_readonly = false;
is_dropped=false;
count = 0;
first = first_m;
last = first_m;
minTime = std::numeric_limits<Time>::max();
maxTime = std::numeric_limits<Time>::min();
std::fill(_buffer_t.begin(), _buffer_t.end(), 0);
using compression::BinaryBuffer;
range = Range{ _buffer_t.data(),_buffer_t.data() + size };
bw = std::make_shared<BinaryBuffer>(range);
c_writer = compression::CopmressedWriter(bw);
c_writer.append(first);
minTime = first_m.time;
maxTime = first_m.time;
flag_bloom = dariadb::storage::bloom_empty<dariadb::Flag>();
}
Chunk::~Chunk() {
std::lock_guard<std::mutex> lg(_mutex);
this->bw = nullptr;
_buffer_t.clear();
}
bool Chunk::append(const Meas&m)
{
if (m.time == 59819) {
std::cout << "append to bug time\n";
}
if (minTime == 26785)
{
std::cout << "****\n";
auto bw_tmp = std::make_shared<dariadb::compression::BinaryBuffer>(this->bw->get_range());
bw_tmp->reset_pos();
dariadb::compression::CopmressedReader crr(bw_tmp, first);
for (size_t i = 0; i < count; i++) {
auto sub = crr.read();
std::cout << "sub: t" << sub.time
<< " v: " << sub.value
<< " f: " << sub.flag
<< " s: " << sub.src << std::endl;
}
}
if (is_dropped || is_readonly) {
throw MAKE_EXCEPTION("(is_dropped || is_readonly)");
}
std::lock_guard<std::mutex> lg(_mutex);
auto t_f = this->c_writer.append(m);
writer_position = c_writer.get_position();
if (!t_f) {
is_readonly = true;
assert(c_writer.is_full());
return false;
}
else {
bw_pos = uint32_t(bw->pos());
bw_bit_num = bw->bitnum();
count++;
minTime = std::min(minTime, m.time);
maxTime = std::max(maxTime, m.time);
flag_bloom = dariadb::storage::bloom_add(flag_bloom, m.flag);
last = m;
return true;
}
}
bool Chunk::check_flag(const Flag& f) {
if (f != 0) {
if (!dariadb::storage::bloom_check(flag_bloom, f)) {
return false;
}
}
return true;
}
|
debug out.
|
debug out.
|
C++
|
apache-2.0
|
lysevi/dariadb,lysevi/dariadb,dariadb/dariadb,lysevi/dariadb,dariadb/dariadb
|
056c996f835526d631665ae251af99d792a790f1
|
libecasound/audioio-tone.cpp
|
libecasound/audioio-tone.cpp
|
// ------------------------------------------------------------------------
// audioio-tone.cpp: Tone generator
//
// Adaptation to Ecasound:
// Copyright (C) 2007-2009 Kai Vehmanen (adaptation to Ecasound)
//
// Sources for sine generation (cmt-src-1.15/src/sine.cpp):
//
// Computer Music Toolkit - a library of LADSPA plugins. Copyright (C)
// 2000-2002 Richard W.E. Furse. The author may be contacted at
// [email protected].
//
// Attributes:
// eca-style-version: 3 (see Ecasound Programmer's Guide)
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// ------------------------------------------------------------------------
#include <algorithm>
#include <string>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <math.h> /* C++'s standard <cmath> does not define M_PI */
#include <kvu_message_item.h>
#include <kvu_numtostr.h>
#include <kvu_dbc.h>
#include "eca-object-factory.h"
#include "samplebuffer.h"
#include "audioio-tone.h"
#include "eca-error.h"
#include "eca-logger.h"
/**
* FIXME notes (last update 2008-03-06)
*
* - define the syntax: is this 'tone', 'sinetone',
* 'tone=sine', ..., or?
* - add support for multichannel testing (different
* frequnecies for different channels?)
*/
using std::cout;
using std::endl;
using std::atof;
using std::string;
/* Sine table size is given by (1 << SINE_TABLE_BITS). */
#define SINE_TABLE_BITS 14
#define SINE_TABLE_SHIFT (8 * sizeof(unsigned long) - SINE_TABLE_BITS)
SAMPLE_SPECS::sample_t *g_pfSineTable = NULL;
SAMPLE_SPECS::sample_t g_fPhaseStepBase = 0;
static void initialise_sine_wavetable(void)
{
if (g_pfSineTable == NULL) {
unsigned long lTableSize = (1 << SINE_TABLE_BITS);
double dShift = (double(M_PI) * 2) / lTableSize;
g_pfSineTable = new SAMPLE_SPECS::sample_t[lTableSize];
if (g_pfSineTable != NULL)
for (unsigned long lIndex = 0; lIndex < lTableSize; lIndex++)
g_pfSineTable[lIndex] = SAMPLE_SPECS::sample_t(sin(dShift * lIndex));
}
if (g_fPhaseStepBase == 0) {
g_fPhaseStepBase = (SAMPLE_SPECS::sample_t)pow(2, sizeof(unsigned long) * 8);
}
}
AUDIO_IO_TONE::AUDIO_IO_TONE (const std::string& name)
: m_lPhaseStep(0),
m_fCachedFrequency(0),
m_fLimitFrequency(0),
m_fPhaseStepScalar(0)
{
set_label(name);
initialise_sine_wavetable();
}
AUDIO_IO_TONE::~AUDIO_IO_TONE(void)
{
}
AUDIO_IO_TONE* AUDIO_IO_TONE::clone(void) const
{
AUDIO_IO_TONE* target = new AUDIO_IO_TONE();
for(int n = 0; n < number_of_params(); n++) {
target->set_parameter(n + 1, get_parameter(n + 1));
}
target->set_position_in_samples(position_in_samples());
if (ECA_AUDIO_POSITION::length_set())
target->ECA_AUDIO_POSITION::set_length_in_samples(ECA_AUDIO_POSITION::length_in_samples());
target->buffersize_rep = buffersize_rep;
target->finished_rep = finished_rep;
target->m_lPhase = m_lPhase;
target->m_lPhaseStep = m_lPhaseStep;
DBC_CHECK(target->m_fCachedFrequency == m_fCachedFrequency);
target->m_fLimitFrequency = m_fLimitFrequency;
target->m_fPhaseStepScalar = m_fPhaseStepScalar;
return target;
}
void AUDIO_IO_TONE::open(void) throw(AUDIO_IO::SETUP_ERROR &)
{
DBC_CHECK(samples_per_second() != 0);
if (io_mode() != AUDIO_IO::io_read)
throw(SETUP_ERROR(SETUP_ERROR::io_mode, "AUDIO_IO_TONE: Writing to tone generator not allowed!"));
finished_rep = false;
m_fLimitFrequency
= SAMPLE_SPECS::sample_t(samples_per_second() * 0.5);
m_fPhaseStepScalar
= SAMPLE_SPECS::sample_t(g_fPhaseStepBase / samples_per_second());
/* recalculate m_fLimitFrequency and mfPhaseStepScalar */
if (m_fCachedFrequency)
setPhaseStepFromFrequency(m_fCachedFrequency, true);
AUDIO_IO::open();
}
void AUDIO_IO_TONE::close(void)
{
AUDIO_IO::close();
}
bool AUDIO_IO_TONE::finite_length_stream(void) const
{
return ECA_AUDIO_POSITION::length_set();
}
void AUDIO_IO_TONE::read_buffer(SAMPLE_BUFFER* sbuf)
{
/* write to sbuf->buffer[ch], similarly as the LADSPA
* chainops */
sbuf->number_of_channels(channels());
/* set the length according to our buffersize */
if ((ECA_AUDIO_POSITION::length_set() == true) &&
((position_in_samples() + buffersize())
>= ECA_AUDIO_POSITION::length_in_samples())) {
/* over requested duration, adjust buffersize */
SAMPLE_BUFFER::buf_size_t partialbuflen =
ECA_AUDIO_POSITION::length_in_samples()
- position_in_samples();
if (partialbuflen < 0)
partialbuflen = 0;
DBC_CHECK(partialbuflen <= buffersize());
sbuf->length_in_samples(partialbuflen);
finished_rep = true;
}
else
sbuf->length_in_samples(buffersize());
i.init(sbuf);
i.begin();
while(!i.end()) {
for(int n = 0; n < channels(); n++) {
if (i.end())
break;
*(i.current(n))
= g_pfSineTable[m_lPhase >> SINE_TABLE_SHIFT];
}
m_lPhase += m_lPhaseStep;
i.next();
}
change_position_in_samples(sbuf->length_in_samples());
DBC_ENSURE(sbuf->number_of_channels() == channels());
}
void AUDIO_IO_TONE::write_buffer(SAMPLE_BUFFER* sbuf)
{
/* NOP */
DBC_CHECK(false);
}
SAMPLE_SPECS::sample_pos_t AUDIO_IO_TONE::seek_position(SAMPLE_SPECS::sample_pos_t pos)
{
/* note: phase must be correct after arbitrary seeks */
m_lPhase = m_lPhaseStep * pos;
if (ECA_AUDIO_POSITION::length_set() == true &&
pos <
ECA_AUDIO_POSITION::length_in_samples())
finished_rep = false;
return pos;
}
void AUDIO_IO_TONE::setPhaseStepFromFrequency(const SAMPLE_SPECS::sample_t fFrequency, bool force)
{
if (fFrequency != m_fCachedFrequency || force == true) {
if (fFrequency >= 0 && fFrequency < m_fLimitFrequency)
m_lPhaseStep = (unsigned long)(m_fPhaseStepScalar * fFrequency);
else
m_lPhaseStep = 0;
m_fCachedFrequency = fFrequency;
}
}
void AUDIO_IO_TONE::set_parameter(int param,
string value)
{
ECA_LOG_MSG(ECA_LOGGER::user_objects,
AUDIO_IO::parameter_set_to_string(param, value));
switch (param)
{
case 1:
{
AUDIO_IO::set_parameter (param, value);
break;
}
case 2:
{
/* type; only "sine" supported */
break;
}
case 3:
{
setPhaseStepFromFrequency (atof(value.c_str()), false);
break;
}
case 4:
{
double duration = atof(value.c_str());
if (duration > 0.0f)
ECA_AUDIO_POSITION::set_length_in_seconds(duration);
break;
}
}
}
string AUDIO_IO_TONE::get_parameter(int param) const
{
switch (param)
{
case 1: return AUDIO_IO::get_parameter(param);
case 2: return "sine";
case 3: return kvu_numtostr(m_fCachedFrequency);
case 4:
{
if (ECA_AUDIO_POSITION::length_set() == true)
return kvu_numtostr(ECA_AUDIO_POSITION::length_in_seconds_exact());
else
return kvu_numtostr(-1.0f);
}
default: break;
}
return std::string();
}
|
// ------------------------------------------------------------------------
// audioio-tone.cpp: Tone generator
//
// Adaptation to Ecasound:
// Copyright (C) 2007-2009 Kai Vehmanen (adaptation to Ecasound)
//
// Sources for sine generation (cmt-src-1.15/src/sine.cpp):
//
// Computer Music Toolkit - a library of LADSPA plugins. Copyright (C)
// 2000-2002 Richard W.E. Furse. The author may be contacted at
// [email protected].
//
// Attributes:
// eca-style-version: 3 (see Ecasound Programmer's Guide)
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// ------------------------------------------------------------------------
#include <algorithm>
#include <string>
#include <iostream>
#include <fstream>
#include <cstdlib>
#include <math.h> /* C++'s standard <cmath> does not define M_PI */
#include <kvu_message_item.h>
#include <kvu_numtostr.h>
#include <kvu_dbc.h>
#include "eca-object-factory.h"
#include "samplebuffer.h"
#include "audioio-tone.h"
#include "eca-error.h"
#include "eca-logger.h"
/**
* FIXME notes (last update 2008-03-06)
*
* - define the syntax: is this 'tone', 'sinetone',
* 'tone=sine', ..., or?
* - add support for multichannel testing (different
* frequnecies for different channels?)
*/
using std::cout;
using std::endl;
using std::atof;
using std::string;
/* Sine table size is given by (1 << SINE_TABLE_BITS). */
#define SINE_TABLE_BITS 14
#define SINE_TABLE_SHIFT (8 * sizeof(unsigned long) - SINE_TABLE_BITS)
SAMPLE_SPECS::sample_t *g_pfSineTable = NULL;
SAMPLE_SPECS::sample_t g_fPhaseStepBase = 0;
static void initialise_sine_wavetable(void)
{
if (g_pfSineTable == NULL) {
unsigned long lTableSize = (1 << SINE_TABLE_BITS);
double dShift = (double(M_PI) * 2) / lTableSize;
g_pfSineTable = new SAMPLE_SPECS::sample_t[lTableSize];
if (g_pfSineTable != NULL)
for (unsigned long lIndex = 0; lIndex < lTableSize; lIndex++)
g_pfSineTable[lIndex] = SAMPLE_SPECS::sample_t(sin(dShift * lIndex));
}
if (g_fPhaseStepBase == 0) {
g_fPhaseStepBase = (SAMPLE_SPECS::sample_t)pow(2, sizeof(unsigned long) * 8);
}
}
AUDIO_IO_TONE::AUDIO_IO_TONE (const std::string& name)
: m_lPhaseStep(0),
m_fCachedFrequency(0),
m_fLimitFrequency(0),
m_fPhaseStepScalar(0)
{
set_label(name);
initialise_sine_wavetable();
}
AUDIO_IO_TONE::~AUDIO_IO_TONE(void)
{
}
AUDIO_IO_TONE* AUDIO_IO_TONE::clone(void) const
{
AUDIO_IO_TONE* target = new AUDIO_IO_TONE();
for(int n = 0; n < number_of_params(); n++) {
target->set_parameter(n + 1, get_parameter(n + 1));
}
target->set_position_in_samples(position_in_samples());
if (ECA_AUDIO_POSITION::length_set())
target->ECA_AUDIO_POSITION::set_length_in_samples(ECA_AUDIO_POSITION::length_in_samples());
target->buffersize_rep = buffersize_rep;
target->finished_rep = finished_rep;
target->m_lPhase = m_lPhase;
target->m_lPhaseStep = m_lPhaseStep;
DBC_CHECK(target->m_fCachedFrequency == m_fCachedFrequency);
target->m_fLimitFrequency = m_fLimitFrequency;
target->m_fPhaseStepScalar = m_fPhaseStepScalar;
return target;
}
void AUDIO_IO_TONE::open(void) throw(AUDIO_IO::SETUP_ERROR &)
{
DBC_CHECK(samples_per_second() != 0);
if (io_mode() != AUDIO_IO::io_read)
throw(SETUP_ERROR(SETUP_ERROR::io_mode, "AUDIO_IO_TONE: Writing to tone generator not allowed!"));
finished_rep = false;
m_fLimitFrequency
= SAMPLE_SPECS::sample_t(samples_per_second() * 0.5);
m_fPhaseStepScalar
= SAMPLE_SPECS::sample_t(g_fPhaseStepBase / samples_per_second());
/* recalculate m_fLimitFrequency and mfPhaseStepScalar */
if (m_fCachedFrequency)
setPhaseStepFromFrequency(m_fCachedFrequency, true);
AUDIO_IO::open();
}
void AUDIO_IO_TONE::close(void)
{
AUDIO_IO::close();
}
bool AUDIO_IO_TONE::finite_length_stream(void) const
{
return ECA_AUDIO_POSITION::length_set();
}
void AUDIO_IO_TONE::read_buffer(SAMPLE_BUFFER* sbuf)
{
/* write to sbuf->buffer[ch], similarly as the LADSPA
* chainops */
sbuf->number_of_channels(channels());
/* set the length according to our buffersize */
if ((ECA_AUDIO_POSITION::length_set() == true) &&
((position_in_samples() + buffersize())
>= ECA_AUDIO_POSITION::length_in_samples())) {
/* over requested duration, adjust buffersize */
SAMPLE_BUFFER::buf_size_t partialbuflen =
ECA_AUDIO_POSITION::length_in_samples()
- position_in_samples();
if (partialbuflen < 0)
partialbuflen = 0;
DBC_CHECK(partialbuflen <= buffersize());
sbuf->length_in_samples(partialbuflen);
sbuf->event_tag_set(SAMPLE_BUFFER::tag_end_of_stream);
finished_rep = true;
}
else
sbuf->length_in_samples(buffersize());
i.init(sbuf);
i.begin();
while(!i.end()) {
for(int n = 0; n < channels(); n++) {
if (i.end())
break;
*(i.current(n))
= g_pfSineTable[m_lPhase >> SINE_TABLE_SHIFT];
}
m_lPhase += m_lPhaseStep;
i.next();
}
change_position_in_samples(sbuf->length_in_samples());
DBC_ENSURE(sbuf->number_of_channels() == channels());
}
void AUDIO_IO_TONE::write_buffer(SAMPLE_BUFFER* sbuf)
{
/* NOP */
DBC_CHECK(false);
}
SAMPLE_SPECS::sample_pos_t AUDIO_IO_TONE::seek_position(SAMPLE_SPECS::sample_pos_t pos)
{
/* note: phase must be correct after arbitrary seeks */
m_lPhase = m_lPhaseStep * pos;
if (ECA_AUDIO_POSITION::length_set() == true &&
pos <
ECA_AUDIO_POSITION::length_in_samples())
finished_rep = false;
return pos;
}
void AUDIO_IO_TONE::setPhaseStepFromFrequency(const SAMPLE_SPECS::sample_t fFrequency, bool force)
{
if (fFrequency != m_fCachedFrequency || force == true) {
if (fFrequency >= 0 && fFrequency < m_fLimitFrequency)
m_lPhaseStep = (unsigned long)(m_fPhaseStepScalar * fFrequency);
else
m_lPhaseStep = 0;
m_fCachedFrequency = fFrequency;
}
}
void AUDIO_IO_TONE::set_parameter(int param,
string value)
{
ECA_LOG_MSG(ECA_LOGGER::user_objects,
AUDIO_IO::parameter_set_to_string(param, value));
switch (param)
{
case 1:
{
AUDIO_IO::set_parameter (param, value);
break;
}
case 2:
{
/* type; only "sine" supported */
break;
}
case 3:
{
setPhaseStepFromFrequency (atof(value.c_str()), false);
break;
}
case 4:
{
double duration = atof(value.c_str());
if (duration > 0.0f)
ECA_AUDIO_POSITION::set_length_in_seconds(duration);
break;
}
}
}
string AUDIO_IO_TONE::get_parameter(int param) const
{
switch (param)
{
case 1: return AUDIO_IO::get_parameter(param);
case 2: return "sine";
case 3: return kvu_numtostr(m_fCachedFrequency);
case 4:
{
if (ECA_AUDIO_POSITION::length_set() == true)
return kvu_numtostr(ECA_AUDIO_POSITION::length_in_seconds_exact());
else
return kvu_numtostr(-1.0f);
}
default: break;
}
return std::string();
}
|
Use end_of_stream tag for finite streams
|
audioio-tone: Use end_of_stream tag for finite streams
When a finite length stream is generated, mark the last
buffer with the end_of_stream tag.
|
C++
|
lgpl-2.1
|
jeremysalwen/Ecasound-LV2,jeremysalwen/Ecasound-LV2,jeremysalwen/Ecasound-LV2,jeremysalwen/Ecasound-LV2,jeremysalwen/Ecasound-LV2
|
9283ceb52d6f3c5b8fbbc7974efda5b1531475f7
|
src/ofApp.cpp
|
src/ofApp.cpp
|
#include "ofApp.h"
#include <boost/python.hpp>
namespace dsl{
namespace py = boost::python;
void background(double x){
ofBackground(x * 255);
}
BOOST_PYTHON_MODULE(core){
py::def("background", &background);
}
py::dict nameSpace;
py::object evalHyCode;
list<string> history;
void run_code(string code){
try{
evalHyCode(code, nameSpace);
}catch(py::error_already_set){
// TODO: better logging, ofLog() or show on window
PyErr_Print();
}
history.push_back(code);
}
void setup(int argc, char ** argv){
try{
Py_Initialize();
PySys_SetArgv(argc, argv);
PyImport_AppendInittab("core", &initcore);
py::import("hy");
evalHyCode = py::import("py.hy_utils").attr("eval_hy_code");
update("");
}catch(py::error_already_set){
PyErr_Print();
}
}
void update(string code){
ofLog() << code;
code = "(import [core [*]])(defn --draw-- [] " + code + ")";
run_code(code);
}
void draw(){
try{
evalHyCode("(--draw--)", nameSpace);
}catch(py::error_already_set){
// TODO: better logging, ofLog() or show on window
PyErr_Print();
history.pop_back(); // the broken one
// TODO: should not be necessary, but better to check history size
string code = history.back();
history.pop_back();
run_code(code);
}
}
}
void ofApp::setup(){
ofLog() << "Running setup()";
oscReceiver.setup(7172);
dsl::setup(argc, argv);
}
void ofApp::update(){
while(oscReceiver.hasWaitingMessages()){
// get the next message
ofxOscMessage m;
oscReceiver.getNextMessage(m);
if(m.getAddress() == "/code"){
string code = m.getArgAsString(0);
ofLog() << "ofApp" << "/code " << code;
dsl::update(code);
}
}
}
void ofApp::draw(){
dsl::draw();
}
void ofApp::keyPressed(int key){}
void ofApp::keyReleased(int key){}
void ofApp::mouseMoved(int x, int y){}
void ofApp::mouseDragged(int x, int y, int button){}
void ofApp::mousePressed(int x, int y, int button){}
void ofApp::mouseReleased(int x, int y, int button){}
void ofApp::mouseEntered(int x, int y){}
void ofApp::mouseExited(int x, int y){}
void ofApp::windowResized(int w, int h){}
void ofApp::gotMessage(ofMessage msg){}
void ofApp::dragEvent(ofDragInfo dragInfo){}
|
#include "ofApp.h"
#include <boost/python.hpp>
namespace dsl{
namespace py = boost::python;
void background(double x){
ofBackground(x * 255);
}
BOOST_PYTHON_MODULE(core){
py::def("background", &background);
}
py::dict nameSpace;
py::object evalHyCode;
list<string> history;
void safeEval(string code){
try{
evalHyCode(code, nameSpace);
}catch(py::error_already_set){
// TODO: better logging, ofLog() or show on window
PyErr_Print();
history.pop_back(); // the broken one
safeEval(history.back()); // assuming that the fist code is valid
}
}
void setup(int argc, char ** argv){
try{
Py_Initialize();
PySys_SetArgv(argc, argv);
PyImport_AppendInittab("core", &initcore);
py::import("hy");
evalHyCode = py::import("py.hy_utils").attr("eval_hy_code");
update("");
}catch(py::error_already_set){
PyErr_Print();
}
}
void update(string code){
ofLog() << code;
history.push_back("(import [core [*]])(defn --draw-- [] " + code + ")");
safeEval(history.back());
}
void draw(){
safeEval("(--draw--)");
}
}
void ofApp::setup(){
ofLog() << "Running setup()";
oscReceiver.setup(7172);
dsl::setup(argc, argv);
}
void ofApp::update(){
while(oscReceiver.hasWaitingMessages()){
// get the next message
ofxOscMessage m;
oscReceiver.getNextMessage(m);
if(m.getAddress() == "/code"){
string code = m.getArgAsString(0);
ofLog() << "ofApp" << "/code " << code;
dsl::update(code);
}
}
}
void ofApp::draw(){
dsl::draw();
}
void ofApp::keyPressed(int key){}
void ofApp::keyReleased(int key){}
void ofApp::mouseMoved(int x, int y){}
void ofApp::mouseDragged(int x, int y, int button){}
void ofApp::mousePressed(int x, int y, int button){}
void ofApp::mouseReleased(int x, int y, int button){}
void ofApp::mouseEntered(int x, int y){}
void ofApp::mouseExited(int x, int y){}
void ofApp::windowResized(int w, int h){}
void ofApp::gotMessage(ofMessage msg){}
void ofApp::dragEvent(ofDragInfo dragInfo){}
|
Move try-eval-catch in safeEval() function
|
Move try-eval-catch in safeEval() function
|
C++
|
agpl-3.0
|
edne/pineal
|
98184adf61ef7b984aa0283df5e471a8ea2f8a0e
|
src/parser.cc
|
src/parser.cc
|
#include <iostream>
#include <list>
#include <memory>
#include <string>
#include <tuple>
#include "lex-util.h"
#include "lexer.h"
#include "parse-problem.h"
#include "parser.h"
#include "ptr.h"
#include "token.h"
#include "type.h"
#include "value.h"
using namespace arua;
using namespace std;
typedef list<shared_ptr<const Token>>::const_iterator TokenListIterator;
struct Tokenizer {
TokenListIterator &itr;
list<tuple<Ptr<Type>, shared_ptr<vector<Token>>>> unresolvedTypes;
list<tuple<Ptr<Value>, shared_ptr<vector<Token>>>> unresolvedValues;
bool pub;
Tokenizer(TokenListIterator &itr)
: itr(itr)
, pub(false) {
}
shared_ptr<const Token> operator *() const throw() {
return *itr;
}
TokenListIterator operator ++() throw() {
return ++itr;
}
TokenListIterator operator ++(int) throw() {
return itr++;
}
TokenListIterator operator --() throw() {
return --itr;
}
TokenListIterator operator --(int) throw() {
return itr--;
}
const shared_ptr<const Token> * operator ->() const throw() {
return &*itr;
}
};
bool unexpected(Tokenizer &t) {
cerr << "aruab: error: " << (*t)->source << ":" << (*t)->line << ":" << (*t)->columnStart << ": unexpected token: " << arua::formatToken(*t, true) << endl;
return false;
}
bool burn(Tokenizer &t) {
for (;; ++t) {
switch ((*t)->type) {
case ABT_COMMENT:
case ABT_COMMENT_DOC:
case ABT_COMMENT_HEADER:
case ABT_NL:
break;
default:
return true;
}
}
}
bool parse_whitespace(Tokenizer &t) {
bool found = false;
while ((*t)->type == ABT_WS) {
found = true;
++t;
}
return found ? true : unexpected(t);
}
inline bool expect(Tokenizer &t, TokenType type) {
if ((*t)->type == type) {
++t;
return true;
} else {
return false;
}
}
bool parse_identifier(Tokenizer &t, string &id) {
if ((*t)->type != ABT_ID) return unexpected(t);
id = (*t)->value;
++t;
return true;
}
std::shared_ptr<Module> arua::parseFile(filesystem::path filename, unsigned int tabWidth) throw() {
auto tokens = arua::lexFile(filename, tabWidth);
shared_ptr<Module> module(new Module(filename.str()));
TokenListIterator vitr = tokens->cbegin();
Tokenizer t(vitr);
return nullptr;
}
|
#include <iostream>
#include <list>
#include <memory>
#include <stack>
#include <string>
#include "lex-util.h"
#include "lexer.h"
#include "parse-problem.h"
#include "parser.h"
#include "ptr.h"
#include "token.h"
#include "type.h"
#include "type-array.h"
#include "type-derived.h"
#include "type-function.h"
#include "type-scalar.h"
#include "type-reference.h"
#include "value.h"
using namespace arua;
using namespace std;
typedef list<shared_ptr<const Token>> TokenList;
typedef TokenList::const_iterator TokenListIterator;
template <typename A, typename B>
struct Tuple {
Tuple(const Tuple &other)
: a(other.a)
, b(other.b) {
}
Tuple(A a, B b)
: a(a)
, b(b) {
}
A a;
B b;
};
struct Tokenizer {
stack<TokenListIterator> stack;
list<Tuple<Ptr<Type>, shared_ptr<TokenList>>> unresolvedTypes;
list<Tuple<Ptr<Value>, shared_ptr<TokenList>>> unresolvedValues;
bool pub;
Tokenizer(TokenListIterator &itr)
: pub(false) {
this->stack.push(itr);
}
TokenListIterator & top() throw() {
return this->stack.top();
}
shared_ptr<const Token> operator *() throw() {
return *(this->top());
}
TokenListIterator operator ++() throw() {
return ++(this->top());
}
TokenListIterator operator ++(int) throw() {
return (this->top())++;
}
TokenListIterator operator --() throw() {
return --(this->top());
}
TokenListIterator operator --(int) throw() {
return (this->top())--;
}
const shared_ptr<const Token> * operator ->() throw() {
return &*(this->top());
}
void push() throw() {
this->stack.push(this->top());
}
void pop() throw() {
this->stack.pop();
}
void commit() throw() {
auto okItr = this->top();
this->stack.pop();
this->stack.top() = okItr;
}
};
ostream & problem(Tokenizer &t, string severity = "error") {
return cerr << "aruab: " << severity << ": " << (*t)->source << ":" << (*t)->line << ":" << (*t)->columnStart << ": ";
}
bool unexpected(Tokenizer &t) {
problem(t) << "unexpected token: " << arua::formatToken(*t, true) << endl;
return false;
}
bool burn(Tokenizer &t) {
for (;; ++t) {
switch ((*t)->type) {
case ABT_COMMENT:
case ABT_COMMENT_DOC:
case ABT_COMMENT_HEADER:
case ABT_NL:
break;
default:
return true;
}
}
}
bool parse_whitespace(Tokenizer &t) {
bool found = false;
while ((*t)->type == ABT_WS) {
found = true;
++t;
}
return found;
}
inline bool expect(Tokenizer &t, TokenType type) {
if ((*t)->type == type) {
++t;
return true;
} else {
return false;
}
}
bool parse_identifier(Tokenizer &t, string &id) {
if ((*t)->type != ABT_ID) return unexpected(t);
id = (*t)->value;
++t;
return true;
}
bool parse_pub(Tokenizer &t) {
if (!expect(t, ABT_PUB)) return unexpected(t);
if (!parse_whitespace(t)) return unexpected(t);
switch ((*t)->type) {
case ABT_TYPEDEF:
case ABT_TRAIT:
case ABT_STRUCT:
case ABT_USE:
case ABT_ALIAS:
case ABT_FN:
case ABT_ID:
break;
default:
return unexpected(t);
}
t.pub = true;
return true;
}
bool parse_type(Tokenizer &t, Ptr<Type> &type);
bool parse_array(Tokenizer &t, Ptr<Type> &type) {
if (!expect(t, ABT_OBRACKET)) return unexpected(t);
Ptr<Type> inner;
if (!parse_type(t, inner)) return false;
auto typeArray = Ptr<TypeArray>::make();
typeArray->setBaseType(inner);
if (!expect(t, ABT_CBRACKET)) return unexpected(t);
type = typeArray.as<Type>();
return true;
}
bool parse_fn(Tokenizer &t, Ptr<Type> &type) {
if (!expect(t, ABT_FN)) return unexpected(t);
if (!expect(t, ABT_OPAREN)) return unexpected(t);
parse_whitespace(t);
auto fnType = Ptr<TypeFunction>::make();
if (!expect(t, ABT_CPAREN)) {
// there might be args
Ptr<Type> firstArg;
if (!parse_type(t, firstArg)) return false;
fnType->addArgumentType(firstArg);
// any other args
while (!expect(t, ABT_CPAREN)) {
if (!expect(t, ABT_COMMA) || !parse_whitespace(t)) return unexpected(t);
Ptr<Type> nextArg;
if (!parse_type(t, nextArg)) return false;
fnType->addArgumentType(nextArg);
parse_whitespace(t);
}
}
// gotta be sneaky and check for whitespace + valid type as a return type.
t.push();
Ptr<Type> returnType;
if (parse_whitespace(t) && parse_type(t, returnType)) {
t.commit();
fnType->setReturnType(returnType);
} else {
t.pop();
}
type = fnType.as<Type>();
return true;
}
bool parse_reference(Tokenizer &t, Ptr<Type> &type) {
if (!expect(t, ABT_AMP)) return unexpected(t);
Ptr<Type> innerType;
if (!parse_type(t, innerType)) return false;
auto refType = Ptr<TypeReference>::make();
refType->setBaseType(innerType);
type = refType.as<Type>();
return true;
}
bool parse_scalar(Tokenizer &t, Ptr<Type> &type) {
if (!expect(t, ABT_SCALAR)) return unexpected(t);
ScalarType scalarFormat;
char clazz = (*t)->value[0];
switch (clazz) {
case 'u':
scalarFormat = ScalarType::UINTEGER;
break;
case 'i':
scalarFormat = ScalarType::INTEGER;
break;
case 'f':
scalarFormat = ScalarType::FLOAT;
break;
default:
problem(t) << "unknown scalar format (is the lexer feeling okay?): " << arua::formatToken(*t, true) << endl;
return false;
}
// I know there are pitfalls with this.
// This is the bootstrap compiler. I don't care.
int width = atoi((*t)->value.substr(1).c_str());
if (width == 0) {
problem(t) << "scalar type cannot have a width of 0: " << arua::formatToken(*t, true) << endl;
return false;
}
auto scalarType = Ptr<TypeScalar>::make();
scalarType->setScalarType(scalarFormat);
scalarType->setWidth(width);
type = scalarType.as<Type>();
return true;
}
bool parse_unresolved_type(Tokenizer &t, Ptr<Type> &type) {
if ((*t)->type == ABT_ID) return unexpected(t);
shared_ptr<TokenList> idents(new TokenList());
idents->push_back(*t);
++t;
while (expect(t, ABT_DOT)) {
if ((*t)->type != ABT_ID) return unexpected(t);
idents->push_back(*t);
++t;
}
t.unresolvedTypes.push_back(Tuple<Ptr<Type>, shared_ptr<TokenList>>(type, idents));
return true;
}
bool parse_type(Tokenizer &t, Ptr<Type> &type) {
// array?
if ((*t)->type == ABT_OBRACKET) {
return parse_array(t, type);
}
// function?
if ((*t)->type == ABT_FN) {
return parse_fn(t, type);
}
// reference?
if ((*t)->type == ABT_AMP) {
return parse_reference(t, type);
}
// scalar?
if ((*t)->type == ABT_SCALAR) {
return parse_scalar(t, type);
}
// make a deferred resolution type from an identifier if there is one
if ((*t)->type == ABT_ID) {
return parse_unresolved_type(t, type);
}
// otherwise, this is an invalid token
return unexpected(t);
}
bool parse_typedef(Tokenizer &t, shared_ptr<Module> module) {
if (!expect(t, ABT_TYPEDEF)) return unexpected(t);
if (!parse_whitespace(t)) return unexpected(t);
Ptr<Type> base;
if (!parse_type(t, base)) return false;
if (!parse_whitespace(t)) return unexpected(t);
if (!expect(t, ABT_AS)) return unexpected(t);
string name;
if (!parse_identifier(t, name)) return false;
parse_whitespace(t);
if (!expect(t, ABT_NL)) return unexpected(t);
auto derived = Ptr<TypeDerived>::make();
derived->setBaseType(base);
derived->setName(name);
module->addType(derived.as<Type>(), t.pub);
return true;
}
bool parse_module(Tokenizer &t, shared_ptr<Module> module) {
while ((*t)->type != ABT_EOF) {
if (!t.pub) {
burn(t);
}
switch ((*t)->type) {
case ABT_PUB:
if (!parse_pub(t)) {
return false;
}
continue;
case ABT_EOF:
break;
case ABT_TYPEDEF:
if (!parse_typedef(t, module)) {
return false;
}
break;
default:
return unexpected(t);
}
t.pub = false;
}
return true;
}
shared_ptr<Module> arua::parseFile(filesystem::path filename, unsigned int tabWidth) throw() {
auto tokens = arua::lexFile(filename, tabWidth);
shared_ptr<Module> module(new Module(filename.str()));
TokenListIterator vitr = tokens->cbegin();
Tokenizer t(vitr);
return parse_module(t, module) ? module : nullptr;
}
|
add untested typedef parsing
|
add untested typedef parsing
|
C++
|
mit
|
arua-lang/bootstrap,arua-lang/bootstrap
|
ab740c14d74a345c6f2453d2304dfbb04ea3c300
|
src/modules/RCEWriter/RCEWriterModule.cpp
|
src/modules/RCEWriter/RCEWriterModule.cpp
|
/**
* @file
* @brief Implementation of RCE Writer Module
* @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.
* This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
#include "RCEWriterModule.hpp"
#include <cassert>
#include <fstream>
#include <string>
#include <utility>
#include <TBranchElement.h>
#include <TClass.h>
#include <TDirectory.h>
#include "core/utils/file.h"
#include "core/utils/log.h"
#include "core/utils/type.h"
#include "objects/Object.hpp"
#include "objects/objects.h"
using namespace allpix;
RCEWriterModule::RCEWriterModule(Configuration& config, Messenger* messenger, GeometryManager* geo_mgr)
: Module(config), geo_mgr_(geo_mgr) {
// Bind to PixelHitMessage
messenger->bindMulti(this, &RCEWriterModule::pixel_hit_messages_);
config_.setDefault("file_name", "rce-data.root");
config_.setDefault("geometry_file", "rce-geo.toml");
}
static void print_geo_detector(std::ostream& os, int index, const Detector& detector) {
// Proteus uses the following local to global transformation
//
// r = r_0 + Q * q
//
// where the local origin (0, 0) is located on the lower-left
// pixel corner of the pixel closest to the the center of the
// active matrix
auto size = detector.getModel()->getNPixels();
auto pitch = detector.getModel()->getPixelSize();
// pixel index in allpix is pixel center, i.e. pixel goes from (-0.5, 0.5)
auto pos_u = pitch.x() * (std::round(size.x() / 2.0) - 0.5);
auto pos_v = pitch.y() * (std::round(size.y() / 2.0) - 0.5);
auto pos = detector.getGlobalPosition({pos_u, pos_v, 0});
// we need the column vectors of the local to global rotation
ROOT::Math::XYZVector uu, uv, uw;
auto rot = detector.getOrientation().Inverse();
rot.GetComponents(uu, uv, uw);
// we need to restore the ostream format state later on
auto flags = os.flags();
auto precision = os.precision();
os << std::showpoint;
os << std::setprecision(std::numeric_limits<double>::max_digits10);
os << "[[sensors]]\n";
os << "id = " << index << '\n';
os << "offset = [" << pos.x() << ", " << pos.y() << ", " << pos.z() << "]\n";
os << "unit_u = [" << uu.x() << ", " << uu.y() << ", " << uu.z() << "]\n";
os << "unit_v = [" << uv.x() << ", " << uv.y() << ", " << uv.z() << "]\n";
os << '\n';
os.flags(flags);
os.precision(precision);
}
static void print_geo(std::ostream& os, const std::vector<std::string>& names, GeometryManager* geo_mgr) {
assert(geo_mgr && "geo_mgr must be non-null");
int index = 0;
for(const auto& name : names) {
print_geo_detector(os, index++, *geo_mgr->getDetector(name));
}
}
void RCEWriterModule::init() {
// We need a sorted list of names to assign monotonic, numeric ids
std::vector<std::string> detector_names;
for(const auto& detector : geo_mgr_->getDetectors()) {
detector_names.push_back(detector->getName());
}
std::sort(detector_names.begin(), detector_names.end());
// Open output data file
std::string path_data = createOutputFile(add_file_extension(config_.get<std::string>("file_name"), "root"));
output_file_ = std::make_unique<TFile>(path_data.c_str(), "RECREATE");
output_file_->cd();
// Initialize the events tree
event_tree_ = new TTree("Event", "");
event_tree_->Branch("TimeStamp", ×tamp_);
event_tree_->Branch("FrameNumber", &frame_number_);
event_tree_->Branch("TriggerTime", &trigger_time_);
event_tree_->Branch("TriggerOffset", &trigger_offset_);
event_tree_->Branch("TriggerInfo", &trigger_info_);
event_tree_->Branch("Invalid", &invalid_);
// For each detector name, initialize an instance of SensorData
int det_index = 0;
for(const auto& detector_name : detector_names) {
auto& sensor = sensors_[detector_name];
LOG(TRACE) << "Sensor " << det_index << ", detector " << detector_name;
// Create sensor directory
std::string det_dir_name = "Plane" + std::to_string(det_index);
TDirectory* detector = output_file_->mkdir(det_dir_name.c_str());
detector->cd();
// Initialize the tree and its branches
sensor.tree = new TTree("Hits", "");
sensor.tree->Branch("NHits", &sensor.nhits_);
sensor.tree->Branch("PixX", &sensor.pix_x_, "PixX[NHits]/I");
sensor.tree->Branch("PixY", &sensor.pix_y_, "PixY[NHits]/I");
sensor.tree->Branch("Value", &sensor.value_, "Value[NHits]/I");
sensor.tree->Branch("Timing", &sensor.timing_, "Timing[NHits]/I");
sensor.tree->Branch("HitInCluster", &sensor.hit_in_cluster_, "HitInCluster[NHits]/I");
det_index += 1;
}
// Write proteus geometry file
std::string path_geo = createOutputFile(add_file_extension(config_.get<std::string>("geometry_file"), "toml"));
std::ofstream geo_file(path_geo);
print_geo(geo_file, detector_names, geo_mgr_);
}
void RCEWriterModule::run(unsigned int event_id) {
// fill per-event data
timestamp_ = 0;
frame_number_ = event_id;
trigger_time_ = 0;
trigger_offset_ = 0;
trigger_info_ = 0;
invalid_ = false;
event_tree_->Fill();
LOG(TRACE) << "Wrote global event data";
// reset all per-sensor trees
for(auto& item : sensors_) {
item.second.nhits_ = 0;
}
// Loop over the pixel hit messages
for(const auto& hit_msg : pixel_hit_messages_) {
std::string detector_name = hit_msg->getDetector()->getName();
auto& sensor = sensors_[detector_name];
// Loop over all the hits
for(const auto& hit : hit_msg->getData()) {
int i = sensor.nhits_;
if(sensor.kMaxHits <= sensor.nhits_) {
LOG(ERROR) << "More than " << sensor.kMaxHits << " in detector " << detector_name;
continue;
}
// Fill the tree with received messages
sensor.nhits_ += 1;
sensor.pix_x_[i] = static_cast<Int_t>(hit.getPixel().getIndex().x()); // NOLINT
sensor.pix_y_[i] = static_cast<Int_t>(hit.getPixel().getIndex().y()); // NOLINT
sensor.value_[i] = static_cast<Int_t>(hit.getSignal()); // NOLINT
// Set the Timing and HitInCluster for each sesnor_tree (= 0 for now)
sensor.timing_[i] = 0; // NOLINT
sensor.hit_in_cluster_[i] = 0; // NOLINT
LOG(TRACE) << detector_name << " x=" << hit.getPixel().getIndex().x() << " y=" << hit.getPixel().getIndex().y()
<< " signal=" << hit.getSignal();
}
}
// Loop over all the detectors to fill all corresponding sensor trees
for(auto& item : sensors_) {
item.second.tree->Fill();
LOG(TRACE) << "Wrote sensor event data for " << item.first;
}
}
void RCEWriterModule::finalize() {
output_file_->Write();
LOG(TRACE) << "Wrote data to file";
}
|
/**
* @file
* @brief Implementation of RCE Writer Module
* @copyright Copyright (c) 2017 CERN and the Allpix Squared authors.
* This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
#include "RCEWriterModule.hpp"
#include <cassert>
#include <fstream>
#include <utility>
#include <TBranchElement.h>
#include <TClass.h>
#include <TDecompSVD.h>
#include <TDirectory.h>
#include <TMatrixD.h>
#include "core/utils/file.h"
#include "core/utils/log.h"
#include "core/utils/type.h"
#include "objects/Object.hpp"
#include "objects/objects.h"
using namespace allpix;
/** Orthogonalize the coordinates definition using singular value decomposition.
*
* \param unit_u Unit vector along the first local axis
* \param unit_v Unit vector along the second local axis
*
* The third local axis is derived from the first two by assuming a right-handed
* coordinate system. The resulting rotation matrix is then orthogonalized
* by finding the closest orthogonal matrix.
*/
static void orthogonalize(ROOT::Math::XYZVector& unit_u, ROOT::Math::XYZVector& unit_v) {
// definition of a right-handed coordinate system
auto unit_w = unit_u.Cross(unit_v);
// resulting local-to-global rotation matrix
TMatrixD rot(3, 3);
rot(0, 0) = unit_u.x();
rot(1, 0) = unit_u.y();
rot(2, 0) = unit_u.z();
rot(0, 1) = unit_v.x();
rot(1, 1) = unit_v.y();
rot(2, 1) = unit_v.z();
rot(0, 2) = unit_w.x();
rot(1, 2) = unit_w.y();
rot(2, 2) = unit_w.z();
// decompose
TDecompSVD svd(rot);
svd.Decompose();
// nearest orthogonal matrix is defined by unit singular values
rot = svd.GetU() * TMatrixD(svd.GetV()).T();
unit_u.SetXYZ(rot(0, 0), rot(1, 0), rot(2, 0));
unit_v.SetXYZ(rot(0, 1), rot(1, 1), rot(2, 1));
}
static void print_geometry_sensor(std::ostream& os, int index, const Detector& detector) {
// Proteus uses the lower-left pixel edge closest to the geometric center
// of the active pixel matrix as the reference position.
// The position must be given in global coordinates
auto size = detector.getModel()->getNPixels();
auto pitch = detector.getModel()->getPixelSize();
// pixel index in allpix is pixel center, i.e. pixel goes from (-0.5, 0.5)
auto off_u = pitch.x() * (std::round(size.x() / 2.0) - 0.5);
auto off_v = pitch.y() * (std::round(size.y() / 2.0) - 0.5);
auto offset = detector.getGlobalPosition({off_u, off_v, 0});
// Proteus defines the orientation of the sensor using two unit vectors
// along the two local axes of the active matrix as seen in the global
// system.
// They are computed as difference vectors here to avoid a dependency
// on the transformation implementation (which has led to errors before).
auto zero = detector.getGlobalPosition({0, 0, 0});
auto unit_u = (detector.getGlobalPosition({1, 0, 0}) - zero).Unit();
auto unit_v = (detector.getGlobalPosition({0, 1, 0}) - zero).Unit();
// try to fix round-off issues
orthogonalize(unit_u, unit_v);
// we need to restore the ostream format state later on
auto flags = os.flags();
auto precision = os.precision();
os << std::showpoint;
os << std::setprecision(std::numeric_limits<double>::max_digits10);
os << "[[sensors]]\n";
os << "id = " << index << '\n';
os << "offset = [" << offset.x() << ", " << offset.y() << ", " << offset.z() << "]\n";
os << "unit_u = [" << unit_u.x() << ", " << unit_u.y() << ", " << unit_u.z() << "]\n";
os << "unit_v = [" << unit_v.x() << ", " << unit_v.y() << ", " << unit_v.z() << "]\n";
os << '\n';
os.flags(flags);
os.precision(precision);
}
static void print_geometry(std::ostream& os, const std::vector<std::string>& names, GeometryManager& geo_mgr) {
int index = 0;
for(const auto& name : names) {
print_geometry_sensor(os, index++, *geo_mgr.getDetector(name));
}
}
RCEWriterModule::RCEWriterModule(Configuration& config, Messenger* messenger, GeometryManager* geo_mgr)
: Module(config), geo_mgr_(geo_mgr) {
assert(geo_mgr_ and "GeometryManager must be non-null");
// Bind to PixelHitMessage
messenger->bindMulti(this, &RCEWriterModule::pixel_hit_messages_);
config_.setDefault("file_name", "rce-data.root");
config_.setDefault("geometry_file", "rce-geo.toml");
}
void RCEWriterModule::init() {
// We need a sorted list of names to assign monotonic, numeric ids
std::vector<std::string> detector_names;
for(const auto& detector : geo_mgr_->getDetectors()) {
detector_names.push_back(detector->getName());
}
std::sort(detector_names.begin(), detector_names.end());
// Open output data file
std::string path_data = createOutputFile(add_file_extension(config_.get<std::string>("file_name"), "root"));
output_file_ = std::make_unique<TFile>(path_data.c_str(), "RECREATE");
output_file_->cd();
// Initialize the events tree
event_tree_ = new TTree("Event", "");
event_tree_->Branch("TimeStamp", ×tamp_);
event_tree_->Branch("FrameNumber", &frame_number_);
event_tree_->Branch("TriggerTime", &trigger_time_);
event_tree_->Branch("TriggerOffset", &trigger_offset_);
event_tree_->Branch("TriggerInfo", &trigger_info_);
event_tree_->Branch("Invalid", &invalid_);
// For each detector name, initialize an instance of SensorData
int det_index = 0;
for(const auto& detector_name : detector_names) {
auto& sensor = sensors_[detector_name];
LOG(TRACE) << "Sensor " << det_index << ", detector " << detector_name;
// Create sensor directory
std::string det_dir_name = "Plane" + std::to_string(det_index);
TDirectory* detector = output_file_->mkdir(det_dir_name.c_str());
detector->cd();
// Initialize the tree and its branches
sensor.tree = new TTree("Hits", "");
sensor.tree->Branch("NHits", &sensor.nhits_);
sensor.tree->Branch("PixX", &sensor.pix_x_, "PixX[NHits]/I");
sensor.tree->Branch("PixY", &sensor.pix_y_, "PixY[NHits]/I");
sensor.tree->Branch("Value", &sensor.value_, "Value[NHits]/I");
sensor.tree->Branch("Timing", &sensor.timing_, "Timing[NHits]/I");
sensor.tree->Branch("HitInCluster", &sensor.hit_in_cluster_, "HitInCluster[NHits]/I");
det_index += 1;
}
// Write proteus geometry file
std::string path_geo = createOutputFile(add_file_extension(config_.get<std::string>("geometry_file"), "toml"));
std::ofstream geo_file(path_geo);
print_geometry(geo_file, detector_names, *geo_mgr_);
}
void RCEWriterModule::run(unsigned int event_id) {
// fill per-event data
timestamp_ = 0;
frame_number_ = event_id;
trigger_time_ = 0;
trigger_offset_ = 0;
trigger_info_ = 0;
invalid_ = false;
event_tree_->Fill();
LOG(TRACE) << "Wrote global event data";
// reset all per-sensor trees
for(auto& item : sensors_) {
item.second.nhits_ = 0;
}
// Loop over the pixel hit messages
for(const auto& hit_msg : pixel_hit_messages_) {
const auto& detector_name = hit_msg->getDetector()->getName();
auto& sensor = sensors_[detector_name];
// Loop over all the hits
for(const auto& hit : hit_msg->getData()) {
int i = sensor.nhits_;
if(sensor.kMaxHits <= sensor.nhits_) {
LOG(ERROR) << "More than " << sensor.kMaxHits << " in detector " << detector_name;
continue;
}
// Fill the tree with received messages
sensor.nhits_ += 1;
sensor.pix_x_[i] = static_cast<Int_t>(hit.getPixel().getIndex().x()); // NOLINT
sensor.pix_y_[i] = static_cast<Int_t>(hit.getPixel().getIndex().y()); // NOLINT
sensor.value_[i] = static_cast<Int_t>(hit.getSignal()); // NOLINT
// Set the Timing and HitInCluster for each sesnor_tree (= 0 for now)
sensor.timing_[i] = 0; // NOLINT
sensor.hit_in_cluster_[i] = 0; // NOLINT
LOG(TRACE) << detector_name << " x=" << hit.getPixel().getIndex().x() << " y=" << hit.getPixel().getIndex().y()
<< " signal=" << hit.getSignal();
}
}
// Loop over all the detectors to fill all corresponding sensor trees
for(auto& item : sensors_) {
item.second.tree->Fill();
LOG(TRACE) << "Wrote sensor event data for " << item.first;
}
}
void RCEWriterModule::finalize() {
output_file_->Write();
LOG(TRACE) << "Wrote data to file";
}
|
fix Proteus geometry output
|
RCEWriter: fix Proteus geometry output
|
C++
|
mit
|
Koensw/allpix-squared,Koensw/allpix-squared,Koensw/allpix-squared,Koensw/allpix-squared
|
456842b812bb1cbdf2464a1cb21369e5083b9c02
|
src/pmath.hpp
|
src/pmath.hpp
|
///
/// @file pmath.hpp
///
/// Copyright (C) 2014 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef PMATH_HPP
#define PMATH_HPP
#include <stdint.h>
#include <cmath>
#include <vector>
#include <limits>
inline int64_t isquare(int64_t x)
{
return x * x;
}
template <typename T1, typename T2, typename T3>
inline T2 in_between(T1 min, T2 x, T3 max)
{
if (x < min)
return static_cast<T2>(min);
if (x > max)
return static_cast<T2>(max);
return x;
}
template <typename T>
inline T number_of_bits(T)
{
return static_cast<T>(sizeof(T) * 8);
}
/// @brief Round up to the next power of 2.
/// @see Book "Hacker's Delight".
///
template <typename T>
inline T next_power_of_2(T x)
{
x--;
for (T i = 1; i < number_of_bits(x); i += i)
x |= (x >> i);
return ++x;
}
/// Raise to power
template <int N>
inline int64_t ipow(int64_t x)
{
int64_t r = 1;
for (int i = 0; i < N; i++)
r *= x;
return r;
}
/// Integer suare root
template <typename T>
inline T isqrt(T x)
{
T r = static_cast<T>(std::sqrt(static_cast<double>(x)));
// correct rounding error
while (ipow<2>(r) > x)
r--;
while (ipow<2>(r + 1) <= x)
r++;
return r;
}
/// Integer nth root
template <int N, typename T>
inline T iroot(T x)
{
T r = static_cast<T>(std::pow(static_cast<double>(x), 1.0 / N));
// correct rounding error
while (ipow<N>(r) > x)
r--;
while (ipow<N>(r + 1) <= x)
r++;
return r;
}
/// Generate a vector with Möbius function values.
/// This implementation is based on code by Rick Sladkey
/// posted here: http://mathoverflow.net/a/99545
///
inline std::vector<int32_t> make_moebius(int64_t max)
{
std::vector<int32_t> mu(max + 1, 1);
for (int32_t i = 2; i * i <= max; i++)
{
if (mu[i] == 1)
{
for (int32_t j = i; j <= max; j += i)
mu[j] *= -i;
for (int32_t j = i * i; j <= max; j += i * i)
mu[j] = 0;
}
}
for (int32_t i = 2; i <= max; i++)
{
if (mu[i] == i)
mu[i] = 1;
else if (mu[i] == -i)
mu[i] = -1;
else if (mu[i] < 0)
mu[i] = 1;
else if (mu[i] > 0)
mu[i] = -1;
}
return mu;
}
/// Generate a vector with the least prime
/// factors of the integers <= max.
///
inline std::vector<int32_t> make_least_prime_factor(int64_t max)
{
std::vector<int32_t> lpf(max + 1, 1);
// phi(x / 1, c) contributes to the sum, thus
// set lpf[1] = MAX in order to pass
// if (lpf[1] > primes[c])
if (lpf.size() > 1)
lpf[1] = std::numeric_limits<int32_t>::max();
for (int32_t i = 2; i * i <= max; i++)
if (lpf[i] == 1)
for (int32_t j = i * 2; j <= max; j += i)
if (lpf[j] == 1)
lpf[j] = i;
for (int32_t i = 2; i <= max; i++)
if (lpf[i] == 1)
lpf[i] = i;
return lpf;
}
/// Generate a vector with the prime counts below max
/// using the sieve of Eratosthenes.
///
inline std::vector<int32_t> make_pi(int64_t max)
{
std::vector<char> is_prime(max + 1, 1);
for (int64_t i = 2; i * i <= max; i++)
if (is_prime[i])
for (int64_t j = i * i; j <= max; j += i * 2)
is_prime[j] = 0;
std::vector<int32_t> pi(max + 1, 0);
int32_t pix = 0;
for (int64_t x = 2; x <= max; x++)
{
pix += is_prime[x];
pi[x] = pix;
}
return pi;
}
#endif
|
///
/// @file pmath.hpp
///
/// Copyright (C) 2014 Kim Walisch, <[email protected]>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#ifndef PMATH_HPP
#define PMATH_HPP
#include <stdint.h>
#include <cmath>
#include <vector>
#include <limits>
inline int64_t isquare(int64_t x)
{
return x * x;
}
template <typename T1, typename T2, typename T3>
inline T2 in_between(T1 min, T2 x, T3 max)
{
if (x < min)
return static_cast<T2>(min);
if (x > max)
return static_cast<T2>(max);
return x;
}
template <typename T>
inline T number_of_bits(T)
{
return static_cast<T>(sizeof(T) * 8);
}
/// @brief Round up to the next power of 2.
/// @see Book "Hacker's Delight".
///
template <typename T>
inline T next_power_of_2(T x)
{
x--;
for (T i = 1; i < number_of_bits(x); i += i)
x |= (x >> i);
return ++x;
}
/// Raise to power
template <int N>
inline int64_t ipow(int64_t x)
{
int64_t r = 1;
for (int i = 0; i < N; i++)
r *= x;
return r;
}
/// Integer suare root
template <typename T>
inline T isqrt(T x)
{
T r = static_cast<T>(std::sqrt(static_cast<double>(x)));
// correct rounding error
while (ipow<2>(r) > x)
r--;
while (ipow<2>(r + 1) <= x)
r++;
return r;
}
/// Integer nth root
template <int N, typename T>
inline T iroot(T x)
{
T r = static_cast<T>(std::pow(static_cast<double>(x), 1.0 / N));
// correct rounding error
while (ipow<N>(r) > x)
r--;
while (ipow<N>(r + 1) <= x)
r++;
return r;
}
/// Generate a vector with Möbius function values.
/// This implementation is based on code by Rick Sladkey
/// posted here: http://mathoverflow.net/a/99545
///
inline std::vector<int32_t> make_moebius(int64_t max)
{
std::vector<int32_t> mu(max + 1, 1);
for (int32_t i = 2; i * i <= max; i++)
{
if (mu[i] == 1)
{
for (int32_t j = i; j <= max; j += i)
mu[j] *= -i;
for (int32_t j = i * i; j <= max; j += i * i)
mu[j] = 0;
}
}
for (int32_t i = 2; i <= max; i++)
{
if (mu[i] == i)
mu[i] = 1;
else if (mu[i] == -i)
mu[i] = -1;
else if (mu[i] < 0)
mu[i] = 1;
else if (mu[i] > 0)
mu[i] = -1;
}
return mu;
}
/// Generate a vector with the least prime
/// factors of the integers <= max.
///
inline std::vector<int32_t> make_least_prime_factor(int64_t max)
{
std::vector<int32_t> lpf(max + 1, 1);
// phi(x / 1, c) contributes to the sum, thus
// set lpf[1] = MAX in order to pass
// if (lpf[1] > primes[c])
if (lpf.size() > 1)
lpf[1] = std::numeric_limits<int32_t>::max();
for (int32_t i = 2; i * i <= max; i++)
if (lpf[i] == 1)
for (int32_t j = i * 2; j <= max; j += i)
if (lpf[j] == 1)
lpf[j] = i;
for (int32_t i = 2; i <= max; i++)
if (lpf[i] == 1)
lpf[i] = i;
return lpf;
}
/// Generate a vector with the prime counts below max
/// using the sieve of Eratosthenes.
///
inline std::vector<int32_t> make_pi(int64_t max)
{
std::vector<char> is_prime(max + 1, 1);
for (int64_t i = 2; i * i <= max; i++)
if (is_prime[i])
for (int64_t j = i * i; j <= max; j += i)
is_prime[j] = 0;
std::vector<int32_t> pi(max + 1, 0);
int32_t pix = 0;
for (int64_t x = 2; x <= max; x++)
{
pix += is_prime[x];
pi[x] = pix;
}
return pi;
}
#endif
|
Fix bug in make_pi(x)
|
Fix bug in make_pi(x)
|
C++
|
bsd-2-clause
|
kimwalisch/primecount,kimwalisch/primecount,kimwalisch/primecount
|
ad971f4f2cb4484dc08575c8a5274a9dceaa8132
|
src/reader.cc
|
src/reader.cc
|
#include <v8.h>
#include <node.h>
#if _USE_CUSTOM_BUFFER_POOL
#include <node_buffer.h>
#endif
#include <string.h>
#include <assert.h>
#include "reader.h"
using namespace hiredis;
static void *tryParentize(const redisReadTask *task, const Local<Value> &v) {
Reader *r = reinterpret_cast<Reader*>(task->privdata);
size_t pidx, vidx;
if (task->parent != NULL) {
pidx = (size_t)task->parent->obj;
assert(pidx > 0 && pidx < 9);
/* When there is a parent, it should be an array. */
Local<Value> lvalue = NanNew(r->handle[pidx]);
assert(lvalue->IsArray());
Local<Array> larray = lvalue.As<Array>();
larray->Set(task->idx,v);
/* Store the handle when this is an inner array. Otherwise, hiredis
* doesn't care about the return value as long as the value is set in
* its parent array. */
vidx = pidx+1;
if (v->IsArray()) {
NanDisposePersistent(r->handle[vidx]);
NanAssignPersistent(r->handle[vidx], v);
return (void*)vidx;
} else {
/* Return value doesn't matter for inner value, as long as it is
* not NULL (which means OOM for hiredis). */
return (void*)0xcafef00d;
}
} else {
/* There is no parent, so this value is the root object. */
NanAssignPersistent(r->handle[1], v);
return (void*)1;
}
}
static void *createArray(const redisReadTask *task, int size) {
Local<Value> v(NanNew<Array>(size));
return tryParentize(task,v);
}
static void *createString(const redisReadTask *task, char *str, size_t len) {
Reader *r = reinterpret_cast<Reader*>(task->privdata);
Local<Value> v(r->createString(str,len));
if (task->type == REDIS_REPLY_ERROR)
v = Exception::Error(v->ToString());
return tryParentize(task,v);
}
static void *createInteger(const redisReadTask *task, long long value) {
Local<Value> v(NanNew<Number>(value));
return tryParentize(task,v);
}
static void *createNil(const redisReadTask *task) {
Local<Value> v(NanNull());
return tryParentize(task,v);
}
static redisReplyObjectFunctions v8ReplyFunctions = {
createString,
createArray,
createInteger,
createNil,
NULL /* No free function: cleanup is done in Reader::Get. */
};
Reader::Reader(bool return_buffers) :
return_buffers(return_buffers)
{
reader = redisReaderCreate();
reader->fn = &v8ReplyFunctions;
reader->privdata = this;
#if _USE_CUSTOM_BUFFER_POOL
if (return_buffers) {
Local<Object> global = Context::GetCurrent()->Global();
Local<Value> bv = global->Get(String::NewSymbol("Buffer"));
assert(bv->IsFunction());
Local<Function> bf = Local<Function>::Cast(bv);
buffer_fn = Persistent<Function>::New(bf);
buffer_pool_length = 8*1024; /* Same as node */
buffer_pool_offset = 0;
Buffer *b = Buffer::New(buffer_pool_length);
buffer_pool = Persistent<Object>::New(b->handle_);
}
#endif
}
Reader::~Reader() {
redisReaderFree(reader);
}
/* Don't declare an extra scope here, so the objects are created within the
* scope inherited from the caller (Reader::Get) and we don't have to the pay
* the overhead. */
inline Local<Value> Reader::createString(char *str, size_t len) {
if (return_buffers) {
#if _USE_CUSTOM_BUFFER_POOL
if (len > buffer_pool_length) {
Buffer *b = Buffer::New(str,len);
return Local<Value>::New(b->handle_);
} else {
return createBufferFromPool(str,len);
}
#else
return NanNewBufferHandle(str,len);
#endif
} else {
return NanNew<String>(str,len);
}
}
#if _USE_CUSTOM_BUFFER_POOL
Local<Value> Reader::createBufferFromPool(char *str, size_t len) {
HandleScope scope;
Local<Value> argv[3];
Local<Object> instance;
assert(len <= buffer_pool_length);
if (buffer_pool_length - buffer_pool_offset < len) {
Buffer *b = Buffer::New(buffer_pool_length);
buffer_pool.Dispose();
buffer_pool = Persistent<Object>::New(b->handle_);
buffer_pool_offset = 0;
}
memcpy(Buffer::Data(buffer_pool)+buffer_pool_offset,str,len);
argv[0] = Local<Value>::New(buffer_pool);
argv[1] = Integer::New(len);
argv[2] = Integer::New(buffer_pool_offset);
instance = buffer_fn->NewInstance(3,argv);
buffer_pool_offset += len;
return scope.Close(instance);
}
#endif
NAN_METHOD(Reader::New) {
NanScope();
bool return_buffers = false;
if (args.Length() > 0 && args[0]->IsObject()) {
Local<Value> bv = args[0].As<Object>()->Get(NanNew<String>("return_buffers"));
if (bv->IsBoolean())
return_buffers = bv->ToBoolean()->Value();
}
Reader *r = new Reader(return_buffers);
r->Wrap(args.This());
NanReturnValue(args.This());
}
void Reader::Initialize(Handle<Object> target) {
NanScope();
Local<FunctionTemplate> t = NanNew<FunctionTemplate>(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(t, "feed", Feed);
NODE_SET_PROTOTYPE_METHOD(t, "get", Get);
target->Set(NanSymbol("Reader"), t->GetFunction());
}
NAN_METHOD(Reader::Feed) {
NanScope();
Reader *r = ObjectWrap::Unwrap<Reader>(args.This());
if (args.Length() == 0) {
NanThrowTypeError("First argument must be a string or buffer");
} else {
if (Buffer::HasInstance(args[0])) {
Local<Object> buffer_object = args[0].As<Object>();
char *data;
size_t length;
data = Buffer::Data(buffer_object);
length = Buffer::Length(buffer_object);
/* Can't handle OOM for now. */
assert(redisReaderFeed(r->reader, data, length) == REDIS_OK);
} else if (args[0]->IsString()) {
String::Utf8Value str(args[0].As<String>());
redisReplyReaderFeed(r->reader, *str, str.length());
} else {
NanThrowError("Invalid argument");
}
}
NanReturnValue(args.This());
}
NAN_METHOD(Reader::Get) {
NanScope();
Reader *r = ObjectWrap::Unwrap<Reader>(args.This());
void *index = NULL;
Local<Value> reply;
int i;
if (redisReaderGetReply(r->reader,&index) == REDIS_OK) {
if (index == 0) {
NanReturnUndefined();
} else {
/* Complete replies should always have a root object at index 1. */
assert((size_t)index == 1);
reply = NanNew<Value>(r->handle[1]);
/* Dispose and clear used handles. */
for (i = 1; i < 3; i++) {
NanDisposePersistent(r->handle[i]);
}
}
} else {
NanThrowError(r->reader->errstr);
}
NanReturnValue(reply);
}
|
#include <v8.h>
#include <node.h>
#if _USE_CUSTOM_BUFFER_POOL
#include <node_buffer.h>
#endif
#include <string.h>
#include <assert.h>
#include "reader.h"
using namespace hiredis;
static void *tryParentize(const redisReadTask *task, const Local<Value> &v) {
Reader *r = reinterpret_cast<Reader*>(task->privdata);
size_t pidx, vidx;
if (task->parent != NULL) {
pidx = (size_t)task->parent->obj;
assert(pidx > 0 && pidx < 9);
/* When there is a parent, it should be an array. */
Local<Value> lvalue = NanNew(r->handle[pidx]);
assert(lvalue->IsArray());
Local<Array> larray = lvalue.As<Array>();
larray->Set(task->idx,v);
/* Store the handle when this is an inner array. Otherwise, hiredis
* doesn't care about the return value as long as the value is set in
* its parent array. */
vidx = pidx+1;
if (v->IsArray()) {
NanDisposePersistent(r->handle[vidx]);
NanAssignPersistent(r->handle[vidx], v);
return (void*)vidx;
} else {
/* Return value doesn't matter for inner value, as long as it is
* not NULL (which means OOM for hiredis). */
return (void*)0xcafef00d;
}
} else {
/* There is no parent, so this value is the root object. */
NanAssignPersistent(r->handle[1], v);
return (void*)1;
}
}
static void *createArray(const redisReadTask *task, int size) {
Local<Value> v(NanNew<Array>(size));
return tryParentize(task,v);
}
static void *createString(const redisReadTask *task, char *str, size_t len) {
Reader *r = reinterpret_cast<Reader*>(task->privdata);
Local<Value> v(r->createString(str,len));
if (task->type == REDIS_REPLY_ERROR)
v = Exception::Error(v->ToString());
return tryParentize(task,v);
}
static void *createInteger(const redisReadTask *task, long long value) {
Local<Value> v(NanNew<Number>(value));
return tryParentize(task,v);
}
static void *createNil(const redisReadTask *task) {
Local<Value> v(NanNew(NanNull()));
return tryParentize(task,v);
}
static redisReplyObjectFunctions v8ReplyFunctions = {
createString,
createArray,
createInteger,
createNil,
NULL /* No free function: cleanup is done in Reader::Get. */
};
Reader::Reader(bool return_buffers) :
return_buffers(return_buffers)
{
reader = redisReaderCreate();
reader->fn = &v8ReplyFunctions;
reader->privdata = this;
#if _USE_CUSTOM_BUFFER_POOL
if (return_buffers) {
Local<Object> global = Context::GetCurrent()->Global();
Local<Value> bv = global->Get(String::NewSymbol("Buffer"));
assert(bv->IsFunction());
Local<Function> bf = Local<Function>::Cast(bv);
buffer_fn = Persistent<Function>::New(bf);
buffer_pool_length = 8*1024; /* Same as node */
buffer_pool_offset = 0;
Buffer *b = Buffer::New(buffer_pool_length);
buffer_pool = Persistent<Object>::New(b->handle_);
}
#endif
}
Reader::~Reader() {
redisReaderFree(reader);
}
/* Don't declare an extra scope here, so the objects are created within the
* scope inherited from the caller (Reader::Get) and we don't have to the pay
* the overhead. */
inline Local<Value> Reader::createString(char *str, size_t len) {
if (return_buffers) {
#if _USE_CUSTOM_BUFFER_POOL
if (len > buffer_pool_length) {
Buffer *b = Buffer::New(str,len);
return Local<Value>::New(b->handle_);
} else {
return createBufferFromPool(str,len);
}
#else
return NanNewBufferHandle(str,len);
#endif
} else {
return NanNew<String>(str,len);
}
}
#if _USE_CUSTOM_BUFFER_POOL
Local<Value> Reader::createBufferFromPool(char *str, size_t len) {
HandleScope scope;
Local<Value> argv[3];
Local<Object> instance;
assert(len <= buffer_pool_length);
if (buffer_pool_length - buffer_pool_offset < len) {
Buffer *b = Buffer::New(buffer_pool_length);
buffer_pool.Dispose();
buffer_pool = Persistent<Object>::New(b->handle_);
buffer_pool_offset = 0;
}
memcpy(Buffer::Data(buffer_pool)+buffer_pool_offset,str,len);
argv[0] = Local<Value>::New(buffer_pool);
argv[1] = Integer::New(len);
argv[2] = Integer::New(buffer_pool_offset);
instance = buffer_fn->NewInstance(3,argv);
buffer_pool_offset += len;
return scope.Close(instance);
}
#endif
NAN_METHOD(Reader::New) {
NanScope();
bool return_buffers = false;
if (args.Length() > 0 && args[0]->IsObject()) {
Local<Value> bv = args[0].As<Object>()->Get(NanNew<String>("return_buffers"));
if (bv->IsBoolean())
return_buffers = bv->ToBoolean()->Value();
}
Reader *r = new Reader(return_buffers);
r->Wrap(args.This());
NanReturnValue(args.This());
}
void Reader::Initialize(Handle<Object> target) {
NanScope();
Local<FunctionTemplate> t = NanNew<FunctionTemplate>(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
NODE_SET_PROTOTYPE_METHOD(t, "feed", Feed);
NODE_SET_PROTOTYPE_METHOD(t, "get", Get);
target->Set(NanSymbol("Reader"), t->GetFunction());
}
NAN_METHOD(Reader::Feed) {
NanScope();
Reader *r = ObjectWrap::Unwrap<Reader>(args.This());
if (args.Length() == 0) {
NanThrowTypeError("First argument must be a string or buffer");
} else {
if (Buffer::HasInstance(args[0])) {
Local<Object> buffer_object = args[0].As<Object>();
char *data;
size_t length;
data = Buffer::Data(buffer_object);
length = Buffer::Length(buffer_object);
/* Can't handle OOM for now. */
assert(redisReaderFeed(r->reader, data, length) == REDIS_OK);
} else if (args[0]->IsString()) {
String::Utf8Value str(args[0].As<String>());
redisReplyReaderFeed(r->reader, *str, str.length());
} else {
NanThrowError("Invalid argument");
}
}
NanReturnValue(args.This());
}
NAN_METHOD(Reader::Get) {
NanScope();
Reader *r = ObjectWrap::Unwrap<Reader>(args.This());
void *index = NULL;
Local<Value> reply;
int i;
if (redisReaderGetReply(r->reader,&index) == REDIS_OK) {
if (index == 0) {
NanReturnUndefined();
} else {
/* Complete replies should always have a root object at index 1. */
assert((size_t)index == 1);
reply = NanNew<Value>(r->handle[1]);
/* Dispose and clear used handles. */
for (i = 1; i < 3; i++) {
NanDisposePersistent(r->handle[i]);
}
}
} else {
NanThrowError(r->reader->errstr);
}
NanReturnValue(reply);
}
|
Fix #59, small change for node <0.11
|
Fix #59, small change for node <0.11
|
C++
|
bsd-3-clause
|
BridgeAR/hiredis-node,kkoopa/hiredis-node,redis/hiredis-node,cmpis/hiredis-node,iddar/hiredis-node,erulabs/hiredis-node,redis/hiredis-node,iddar/hiredis-node,badboy/hiredis-node-win,iddar/hiredis-node,cmpis/hiredis-node,erulabs/hiredis-node,cmpis/hiredis-node,BridgeAR/hiredis-node,kkoopa/hiredis-node,BridgeAR/hiredis-node,badboy/hiredis-node-win,kkoopa/hiredis-node,redis/hiredis-node,erulabs/hiredis-node,badboy/hiredis-node-win
|
0e968f9de36351993eff7c79189f600382294b17
|
bbb/core/type/container/type_sequence_operation.hpp
|
bbb/core/type/container/type_sequence_operation.hpp
|
/* **** **** **** **** **** **** **** **** *
*
* _/ _/ _/
* _/_/_/ _/_/_/ _/_/_/
* _/ _/ _/ _/ _/ _/
* _/ _/ _/ _/ _/ _/
* _/_/_/ _/_/_/ _/_/_/
*
* bit by bit
* bbb/type_sequence_operation.hpp
*
* author: ISHII 2bit
* mail: [email protected]
*
* **** **** **** **** **** **** **** **** */
#pragma once
#include <bbb/core/type/utility.hpp>
#include <bbb/core/type/container/type_sequence.hpp>
namespace bbb {
namespace type_sequence_operations {
template <typename t, typename sequence>
struct push_front;
template <typename t, typename sequence>
using push_front_t = get_type<push_front<t, sequence>>;
template <typename t, typename ... types>
struct push_front<t, type_sequence<types ...>> {
using type = type_sequence<t, types ...>;
};
template <typename t, typename sequence>
struct push_back;
template <typename t, typename sequence>
using push_back_t = get_type<push_back<t, sequence>>;
template <typename t, typename ... types>
struct push_back<t, type_sequence<types ...>> {
using type = type_sequence<types ..., t>;
};
#if BBB_EXEC_UNIT_TEST
namespace push_test {
using test1 = unit_test::assert<
push_front_t<int, type_sequence<float, char>>,
type_sequence<int, float, char>
>;
using test2 = unit_test::assert<
push_back_t<char, type_sequence<int, float>>,
type_sequence<int, float, char>
>;
using test3 = unit_test::assert<
push_front_t<int, type_sequence<float, char>>,
push_back_t<char, type_sequence<int, float>>
>;
};
#endif
template <typename s, typename t>
struct concat_sequence;
template <typename s, typename t>
using concat_sequence_t = get_type<concat_sequence<s, t>>;
template <typename ... ss, typename ... ts>
struct concat_sequence<type_sequence<ss ...>, type_sequence<ts ...>> {
using type = type_sequence<ss ..., ts ...>;
};
namespace detail {
template <typename sequence, typename ... types>
struct slice;
template <std::size_t ... indices, typename ... types>
struct slice<index_sequence<indices ...>, types ...> {
using type = type_sequence<type_at<indices, types ...> ...>;
};
};
template <std::size_t from, std::size_t to, typename ... types>
using slice = detail::slice<index_range<from, to>, types ...>;
template <std::size_t from, std::size_t to, typename ... types>
using slice_t = get_type<slice<from, to, types ...>>;
#if BBB_EXEC_UNIT_TEST
namespace slice_test {
using test1 = unit_test::assert<
slice_t<0, 1, int, int, char>,
type_sequence<int, int>
>;
using test2 = unit_test::assert<
slice_t<1, 2, int, int, char>,
type_sequence<int, char>
>;
}
#endif
template <std::size_t from, std::size_t to, typename sequence>
struct slice_type_sequence;
template <std::size_t from, std::size_t to, typename ... types>
struct slice_type_sequence<from, to, type_sequence<types ...>> {
using type = slice_t<from, to, types ...>;
};
template <std::size_t from, std::size_t to, typename sequence>
using slice_type_sequence_t = get_type<slice_type_sequence<from, to, sequence>>;
#if BBB_EXEC_UNIT_TEST
namespace slice_type_sequence_test {
using test1 = unit_test::assert<
slice_type_sequence_t<0, 1, type_sequence<int, int, char>>,
type_sequence<int, int>
>;
using test2 = unit_test::assert<
slice_type_sequence_t<1, 2, type_sequence<int, int, char>>,
type_sequence<int, char>
>;
};
#endif
template <typename t, typename sequence>
struct remove;
template <typename t, typename sequence>
using remove_t = get_type<remove<t, sequence>>;
template <typename t, typename u, typename ... types>
struct remove<t, type_sequence<u, types ...>> {
using type = conditional_t<
is_same<t, u>(),
type_sequence<types ...>,
push_front_t<u, remove_t<t, type_sequence<types ...>>>
>;
};
template <typename t>
struct remove<t, type_sequence<>> {
using type = type_sequence<>;
};
#if BBB_EXEC_UNIT_TEST
namespace remove_test {
using test1 = unit_test::assert<
remove_t<int, type_sequence<int, int, char>>,
type_sequence<int, char>
>;
using test2 = unit_test::assert<
remove_t<char, type_sequence<int, int, char>>,
type_sequence<int, int>
>;
using test3 = unit_test::assert<
remove_t<char, type_sequence<float, int, char, double>>,
type_sequence<float, int, double>
>;
using test3 = unit_test::assert<
remove_t<char, type_sequence<float, int, double>>,
type_sequence<float, int, double>
>;
};
#endif
template <typename t, typename sequence>
struct remove_all;
template <typename t, typename sequence>
using remove_all_t = get_type<remove_all<t, sequence>>;
template <typename t, typename u, typename ... types>
struct remove_all<t, type_sequence<u, types ...>> {
using type = conditional_t<
is_same<t, u>(),
remove_all_t<t, type_sequence<types ...>>,
push_front_t<u, remove_all_t<t, type_sequence<types ...>>>
>;
};
template <typename t>
struct remove_all<t, type_sequence<>> {
using type = type_sequence<>;
};
#if BBB_EXEC_UNIT_TEST
namespace remove_all_test {
using test1 = unit_test::assert<
remove_all_t<int, type_sequence<int, int, char>>,
type_sequence<char>
>;
using test2 = unit_test::assert<
remove_all_t<char, type_sequence<int, int, char>>,
type_sequence<int, int>
>;
using test3 = unit_test::assert<
remove_all_t<char, type_sequence<float, int, char, double>>,
type_sequence<float, int, double>
>;
};
#endif
template <typename s, typename t>
struct difference_sequence;
template <typename s, typename t>
using difference_sequence_t = get_type<difference_sequence<s, t>>;
template <typename s, typename t, typename ... ts>
struct difference_sequence<s, type_sequence<t, ts ...>> {
using type = difference_sequence_t<remove_t<t, s>, type_sequence<ts ...>>;
};
template <typename s>
struct difference_sequence<s, type_sequence<>> {
using type = s;
};
#if BBB_EXEC_UNIT_TEST
namespace difference_sequence_test {
using test1 = unit_test::assert<
difference_sequence_t<type_sequence<int, int, char>, type_sequence<int>>,
type_sequence<int, char>
>;
};
#endif
namespace detail {
template <typename holder, typename ... types>
struct make_unique;
template <typename ... holded_types, typename first, typename ... types>
struct make_unique<type_sequence<holded_types ...>, first, types ...> {
template <typename rhs>
using eq = std::is_same<first, rhs>;
using type = get_type<conditional_t<
any_t<eq, holded_types ...>::value,
make_unique<type_sequence<holded_types ...>, types ...>,
make_unique<type_sequence<holded_types ..., first>, types ...>
>>;
};
template <typename ... holded_types>
struct make_unique<type_sequence<holded_types ...>> {
using type = type_sequence<holded_types ...>;
};
};
template <typename ... types>
using make_unique = detail::make_unique<type_sequence<>, types ...>;
template <typename ... types>
using make_unique_t = get_type<make_unique<types ...>>;
#if BBB_EXEC_UNIT_TEST
namespace make_unique_test {
using test1 = unit_test::assert<
make_unique_t<int, int>,
type_sequence<int>
>;
using test2 = unit_test::assert<
make_unique_t<int, char, int>,
type_sequence<int, char>
>;
}
#endif
template <typename sequence>
struct make_sequence_unique;
template <typename ... types>
struct make_sequence_unique<type_sequence<types ...>> {
using type = make_unique_t<types ...>;
};
template <typename sequence>
using make_sequence_unique_t = get_type<make_sequence_unique<sequence>>;
template <template <typename> class function, typename ... types>
struct map {
using type = type_sequence<function<types> ...>;
};
template <template <typename> class function, typename ... types>
using map_t = get_type<map<function, types ...>>;
template <template <typename> class function, typename sequence>
struct map_sequence;
template <template <typename> class function, typename sequence>
using map_sequence_t = get_type<map_sequence<function, sequence>>;
template <template <typename> class function, typename ... types>
struct map_sequence<function, type_sequence<types ...>> {
using type = map_t<function, types ...>;
};
template <template <typename, typename> class function, typename initial, typename ... types>
struct reduce;
template <template <typename, typename> class function, typename initial, typename ... types>
using reduce_t = get_type<reduce<function, initial, types ...>>;
template <template <typename, typename> class function, typename t, typename s, typename ... types>
struct reduce<function, t, s, types ...> {
using type = reduce_t<function, function<t, s>, types ...>;
};
template <template <typename, typename> class function, typename t>
struct reduce<function, t> {
using type = t;
};
template <template <typename, typename> class function, typename sequence>
struct reduce_sequence;
template <template <typename, typename> class function, typename sequence>
using reduce_sequence_t = get_type<reduce_sequence<function, sequence>>;
template <template <typename, typename> class function, typename t, typename ... types>
struct reduce_sequence<function, type_sequence<t, types ...>> {
using type = reduce_t<function, t, types ...>;
};
#if BBB_EXEC_UNIT_TEST
namespace reduce_test {
template <typename seq, typename type>
using f = push_back_t<type, seq>;
using test1 = unit_test::assert<
reduce_t<f, type_sequence<>, int, char, float>,
type_sequence<int, char, float>
>;
using test2 = unit_test::assert<
reduce_t<or_type, std::true_type, std::false_type, std::false_type>,
std::true_type
>;
using test3 = unit_test::assert<
reduce_t<or_type, std::false_type, std::false_type, std::false_type>,
std::false_type
>;
using test4 = unit_test::assert<
reduce_t<and_type, std::true_type, std::false_type, std::false_type>,
std::false_type
>;
using test5 = unit_test::assert<
reduce_t<and_type, std::true_type, std::true_type, std::true_type>,
std::true_type
>;
};
#endif
};
using namespace type_sequence_operations;
};
|
/* **** **** **** **** **** **** **** **** *
*
* _/ _/ _/
* _/_/_/ _/_/_/ _/_/_/
* _/ _/ _/ _/ _/ _/
* _/ _/ _/ _/ _/ _/
* _/_/_/ _/_/_/ _/_/_/
*
* bit by bit
* bbb/type_sequence_operation.hpp
*
* author: ISHII 2bit
* mail: [email protected]
*
* **** **** **** **** **** **** **** **** */
#pragma once
#include <bbb/core/type/utility.hpp>
#include <bbb/core/type/container/type_sequence.hpp>
namespace bbb {
namespace type_sequence_operations {
template <typename t, typename sequence>
struct push_front;
template <typename t, typename sequence>
using push_front_t = get_type<push_front<t, sequence>>;
template <typename t, typename ... types>
struct push_front<t, type_sequence<types ...>> {
using type = type_sequence<t, types ...>;
};
template <typename t, typename sequence>
struct push_back;
template <typename t, typename sequence>
using push_back_t = get_type<push_back<t, sequence>>;
template <typename t, typename ... types>
struct push_back<t, type_sequence<types ...>> {
using type = type_sequence<types ..., t>;
};
#if BBB_EXEC_UNIT_TEST
namespace push_test {
using test1 = unit_test::assert<
push_front_t<int, type_sequence<float, char>>,
type_sequence<int, float, char>
>;
using test2 = unit_test::assert<
push_back_t<char, type_sequence<int, float>>,
type_sequence<int, float, char>
>;
using test3 = unit_test::assert<
push_front_t<int, type_sequence<float, char>>,
push_back_t<char, type_sequence<int, float>>
>;
};
#endif
template <typename s, typename t>
struct concat_sequence;
template <typename s, typename t>
using concat_sequence_t = get_type<concat_sequence<s, t>>;
template <typename ... ss, typename ... ts>
struct concat_sequence<type_sequence<ss ...>, type_sequence<ts ...>> {
using type = type_sequence<ss ..., ts ...>;
};
namespace detail {
template <typename sequence, typename ... types>
struct slice;
template <std::size_t ... indices, typename ... types>
struct slice<index_sequence<indices ...>, types ...> {
using type = type_sequence<type_at<indices, types ...> ...>;
};
};
template <std::size_t from, std::size_t to, typename ... types>
using slice = detail::slice<index_range<from, to>, types ...>;
template <std::size_t from, std::size_t to, typename ... types>
using slice_t = get_type<slice<from, to, types ...>>;
#if BBB_EXEC_UNIT_TEST
namespace slice_test {
using test1 = unit_test::assert<
slice_t<0, 1, int, int, char>,
type_sequence<int, int>
>;
using test2 = unit_test::assert<
slice_t<1, 2, int, int, char>,
type_sequence<int, char>
>;
}
#endif
template <std::size_t from, std::size_t to, typename sequence>
struct slice_type_sequence;
template <std::size_t from, std::size_t to, typename ... types>
struct slice_type_sequence<from, to, type_sequence<types ...>> {
using type = slice_t<from, to, types ...>;
};
template <std::size_t from, std::size_t to, typename sequence>
using slice_type_sequence_t = get_type<slice_type_sequence<from, to, sequence>>;
#if BBB_EXEC_UNIT_TEST
namespace slice_type_sequence_test {
using test1 = unit_test::assert<
slice_type_sequence_t<0, 1, type_sequence<int, int, char>>,
type_sequence<int, int>
>;
using test2 = unit_test::assert<
slice_type_sequence_t<1, 2, type_sequence<int, int, char>>,
type_sequence<int, char>
>;
};
#endif
template <typename t, typename sequence>
struct remove;
template <typename t, typename sequence>
using remove_t = get_type<remove<t, sequence>>;
template <typename t, typename u, typename ... types>
struct remove<t, type_sequence<u, types ...>> {
using type = conditional_t<
is_same<t, u>(),
type_sequence<types ...>,
push_front_t<u, remove_t<t, type_sequence<types ...>>>
>;
};
template <typename t>
struct remove<t, type_sequence<>> {
using type = type_sequence<>;
};
#if BBB_EXEC_UNIT_TEST
namespace remove_test {
using test1 = unit_test::assert<
remove_t<int, type_sequence<int, int, char>>,
type_sequence<int, char>
>;
using test2 = unit_test::assert<
remove_t<char, type_sequence<int, int, char>>,
type_sequence<int, int>
>;
using test3 = unit_test::assert<
remove_t<char, type_sequence<float, int, char, double>>,
type_sequence<float, int, double>
>;
using test3 = unit_test::assert<
remove_t<char, type_sequence<float, int, double>>,
type_sequence<float, int, double>
>;
};
#endif
template <typename t, typename sequence>
struct remove_all;
template <typename t, typename sequence>
using remove_all_t = get_type<remove_all<t, sequence>>;
template <typename t, typename u, typename ... types>
struct remove_all<t, type_sequence<u, types ...>> {
using type = conditional_t<
is_same<t, u>(),
remove_all_t<t, type_sequence<types ...>>,
push_front_t<u, remove_all_t<t, type_sequence<types ...>>>
>;
};
template <typename t>
struct remove_all<t, type_sequence<>> {
using type = type_sequence<>;
};
#if BBB_EXEC_UNIT_TEST
namespace remove_all_test {
using test1 = unit_test::assert<
remove_all_t<int, type_sequence<int, int, char>>,
type_sequence<char>
>;
using test2 = unit_test::assert<
remove_all_t<char, type_sequence<int, int, char>>,
type_sequence<int, int>
>;
using test3 = unit_test::assert<
remove_all_t<char, type_sequence<float, int, char, double>>,
type_sequence<float, int, double>
>;
};
#endif
template <typename s, typename t>
struct difference_sequence;
template <typename s, typename t>
using difference_sequence_t = get_type<difference_sequence<s, t>>;
template <typename s, typename t, typename ... ts>
struct difference_sequence<s, type_sequence<t, ts ...>> {
using type = difference_sequence_t<remove_t<t, s>, type_sequence<ts ...>>;
};
template <typename s>
struct difference_sequence<s, type_sequence<>> {
using type = s;
};
#if BBB_EXEC_UNIT_TEST
namespace difference_sequence_test {
using test1 = unit_test::assert<
difference_sequence_t<type_sequence<int, int, char>, type_sequence<int>>,
type_sequence<int, char>
>;
};
#endif
namespace detail {
template <typename holder, typename ... types>
struct make_unique;
template <typename ... holded_types, typename first, typename ... types>
struct make_unique<type_sequence<holded_types ...>, first, types ...> {
template <typename rhs>
using eq = std::is_same<first, rhs>;
using type = get_type<conditional_t<
any_t<eq, holded_types ...>::value,
make_unique<type_sequence<holded_types ...>, types ...>,
make_unique<type_sequence<holded_types ..., first>, types ...>
>>;
};
template <typename ... holded_types>
struct make_unique<type_sequence<holded_types ...>> {
using type = type_sequence<holded_types ...>;
};
};
template <typename ... types>
using make_unique = detail::make_unique<type_sequence<>, types ...>;
template <typename ... types>
using make_unique_t = get_type<make_unique<types ...>>;
#if BBB_EXEC_UNIT_TEST
namespace make_unique_test {
using test1 = unit_test::assert<
make_unique_t<int, int>,
type_sequence<int>
>;
using test2 = unit_test::assert<
make_unique_t<int, char, int>,
type_sequence<int, char>
>;
}
#endif
template <typename sequence>
struct make_sequence_unique;
template <typename ... types>
struct make_sequence_unique<type_sequence<types ...>> {
using type = make_unique_t<types ...>;
};
template <typename sequence>
using make_sequence_unique_t = get_type<make_sequence_unique<sequence>>;
template <template <typename> class function, typename ... types>
struct map {
using type = type_sequence<function<types> ...>;
};
template <template <typename> class function, typename ... types>
using map_t = get_type<map<function, types ...>>;
template <template <typename> class function, typename sequence>
struct map_sequence;
template <template <typename> class function, typename sequence>
using map_sequence_t = get_type<map_sequence<function, sequence>>;
template <template <typename> class function, typename ... types>
struct map_sequence<function, type_sequence<types ...>> {
using type = map_t<function, types ...>;
};
#if BBB_EXEC_UNIT_TEST
namespace map_test {
template <typename type> using and_true = and_type<std::true_type, type>;
using test1 = unit_test::assert<
map_t<and_true, std::true_type, std::false_type>,
type_sequence<std::true_type, std::false_type>
>;
template <typename type> using and_false = and_type<std::false_type, type>;
using test2 = unit_test::assert<
map_t<and_false, std::true_type, std::false_type>,
type_sequence<std::false_type, std::false_type>
>;
template <typename type> using or_true = or_type<std::true_type, type>;
using test3 = unit_test::assert<
map_t<or_true, std::true_type, std::false_type>,
type_sequence<std::true_type, std::true_type>
>;
};
#endif
template <template <typename, typename> class function, typename initial, typename ... types>
struct reduce;
template <template <typename, typename> class function, typename initial, typename ... types>
using reduce_t = get_type<reduce<function, initial, types ...>>;
template <template <typename, typename> class function, typename t, typename s, typename ... types>
struct reduce<function, t, s, types ...> {
using type = reduce_t<function, function<t, s>, types ...>;
};
template <template <typename, typename> class function, typename t>
struct reduce<function, t> {
using type = t;
};
template <template <typename, typename> class function, typename sequence>
struct reduce_sequence;
template <template <typename, typename> class function, typename sequence>
using reduce_sequence_t = get_type<reduce_sequence<function, sequence>>;
template <template <typename, typename> class function, typename t, typename ... types>
struct reduce_sequence<function, type_sequence<t, types ...>> {
using type = reduce_t<function, t, types ...>;
};
#if BBB_EXEC_UNIT_TEST
namespace reduce_test {
template <typename seq, typename type>
using f = push_back_t<type, seq>;
using test1 = unit_test::assert<
reduce_t<f, type_sequence<>, int, char, float>,
type_sequence<int, char, float>
>;
using test2 = unit_test::assert<
reduce_t<or_type, std::true_type, std::false_type, std::false_type>,
std::true_type
>;
using test3 = unit_test::assert<
reduce_t<or_type, std::false_type, std::false_type, std::false_type>,
std::false_type
>;
using test4 = unit_test::assert<
reduce_t<and_type, std::true_type, std::false_type, std::false_type>,
std::false_type
>;
using test5 = unit_test::assert<
reduce_t<and_type, std::true_type, std::true_type, std::true_type>,
std::true_type
>;
};
#endif
};
using namespace type_sequence_operations;
};
|
add map_test
|
add map_test
|
C++
|
mit
|
2bbb/bit_by_bit
|
5f3ad13fcd1de4539495e1b74d242d3526ae4205
|
src/share.cpp
|
src/share.cpp
|
//=======================================================================
// Copyright (c) 2013-2018 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <tuple>
#include <utility>
#include <iostream>
#include "share.hpp"
#include "config.hpp"
#include "server.hpp"
#include "http.hpp"
#include "date.hpp"
namespace {
struct share_price_cache_key {
budget::date date;
std::string ticker;
share_price_cache_key(budget::date date, std::string ticker) : date(date), ticker(ticker) {}
friend bool operator<(const share_price_cache_key & lhs, const share_price_cache_key & rhs){
return std::tie(lhs.date, lhs.ticker) < std::tie(rhs.date, rhs.ticker);
}
friend bool operator==(const share_price_cache_key & lhs, const share_price_cache_key & rhs){
return std::tie(lhs.date, lhs.ticker) == std::tie(rhs.date, rhs.ticker);
}
};
std::map<share_price_cache_key, double> share_prices;
budget::date get_valid_date(budget::date d){
// We cannot get closing price in the future, so we use the day before date
if (d >= budget::local_day()) {
auto now = std::chrono::system_clock::now();
auto tt = std::chrono::system_clock::to_time_t(now);
auto tm = *std::localtime(&tt);
// We make sure that we are on a new U.S: day
// TODO This should be done by getting the current time in the U.S.
if (tm.tm_hour > 15) {
return get_valid_date(budget::local_day() - budget::days(1));
} else {
return get_valid_date(budget::local_day() - budget::days(2));
}
}
auto dow = d.day_of_the_week();
if (dow == 6 || dow == 7){
return get_valid_date(d - budget::days(dow - 5));
}
return d;
}
// V1 is using cloud.iexapis.com
double get_share_price_v1(const std::string& quote, const budget::date& date, int depth = 0) {
if (!budget::config_contains("iex_cloud_token")) {
std::cout << "ERROR: Price(v1): Need IEX cloud token configured to work" << std::endl;
return 1.0;
}
auto token = budget::config_value("iex_cloud_token");
httplib::SSLClient cli("cloud.iexapis.com", 443);
auto date_str = budget::date_to_string(date);
std::string api_complete = "/beta/stock/" + quote + "/chart/date/" + date_str + "?chartByDay=true&token=" + token;
auto res = cli.Get(api_complete.c_str());
if (!res) {
std::cout << "ERROR: Price(v1): No response" << std::endl;
std::cout << "ERROR: Price(v1): URL is " << api_complete << std::endl;
return 1.0;
} else if (res->status != 200) {
std::cout << "ERROR: Price(v1): Error response " << res->status << std::endl;
std::cout << "ERROR: Price(v1): URL is " << api_complete << std::endl;
std::cout << "ERROR: Price(v1): Response is " << res->body << std::endl;
return 1.0;
} else {
// Pseudo handling of holidays
if (res->body == "[]") {
if (depth <= 3) {
auto next_date = get_valid_date(date - budget::days(1));
std::cout << "INFO: Price(v1): Possible holiday, retrying on previous day" << std::endl;
std::cout << "INFO: Date was " << date << " retrying with " << next_date << std::endl;
// Opportunistically check the cache for previous day!
share_price_cache_key key(next_date, quote);
if (share_prices.count(key)) {
return share_prices[key];
} else {
return get_share_price_v1(quote, next_date, depth + 1);
}
}
}
// Example
// [{"date":"2019-03-01","open":174.28,"close":174.97,"high":175.15,"low":172.89,"volume":25886167,"uOpen":174.28,"uClose":174.97,"uHigh":175.15,"uLow":172.89,"uVolume":25886167,"change":1.82,"changePercent":1.0511,"label":"Mar
// 1, 19","changeOverTime":172.237624}]
auto& buffer = res->body;
std::string start = "\"close\":";
std::string stop = ",\"high\":";
if (buffer.find(start) == std::string::npos || buffer.find(stop) == std::string::npos) {
std::cout << "ERROR: Price(v1): Error parsing share prices" << std::endl;
std::cout << "ERROR: Price(v1): URL is " << api_complete << std::endl;
std::cout << "ERROR: Price(v1): Response is " << res->body << std::endl;
return 1.0;
} else {
std::string ratio_result(buffer.begin() + buffer.find(start) + start.size(), buffer.begin() + buffer.find(stop));
return atof(ratio_result.c_str());
}
}
}
} // end of anonymous namespace
void budget::load_share_price_cache(){
std::string file_path = budget::path_to_budget_file("share_price.cache");
std::ifstream file(file_path);
if (!file.is_open() || !file.good()){
std::cout << "INFO: Impossible to load Share Price Cache" << std::endl;
return;
}
std::string line;
while (file.good() && getline(file, line)) {
if (line.empty()) {
continue;
}
auto parts = split(line, ':');
share_price_cache_key key(budget::from_string(parts[0]), parts[1]);
share_prices[key] = budget::to_number<double>(parts[2]);
}
if (budget::is_server_running()) {
std::cout << "INFO: Share Price Cache has been loaded from " << file_path << std::endl;
std::cout << "INFO: Share Price Cache has " << share_prices.size() << " entries " << std::endl;
}
}
void budget::save_share_price_cache() {
std::string file_path = budget::path_to_budget_file("share_price.cache");
std::ofstream file(file_path);
if (!file.is_open() || !file.good()){
std::cout << "INFO: Impossible to save Share Price Cache" << std::endl;
return;
}
for (auto & pair : share_prices) {
if (pair.second != 1.0) {
auto& key = pair.first;
file << budget::date_to_string(key.date) << ':' << key.ticker << ':' << pair.second << std::endl;
}
}
if (budget::is_server_running()) {
std::cout << "INFO: Share Price Cache has been saved to " << file_path << std::endl;
std::cout << "INFO: Share Price Cache has " << share_prices.size() << " entries " << std::endl;
}
}
void budget::refresh_share_price_cache(){
// Refresh the prices for each value
for (auto& pair : share_prices) {
auto& key = pair.first;
share_prices[key] = get_share_price_v1(key.ticker, key.date);
}
// Prefetch the current prices
for (auto & pair : share_prices) {
auto& key = pair.first;
share_price(key.ticker);
}
if (budget::is_server_running()) {
std::cout << "INFO: Share Price Cache has been refreshed" << std::endl;
std::cout << "INFO: Share Price Cache has " << share_prices.size() << " entries " << std::endl;
}
}
double budget::share_price(const std::string& ticker){
return share_price(ticker, budget::local_day());
}
double budget::share_price(const std::string& ticker, budget::date d){
auto date = get_valid_date(d);
share_price_cache_key key(date, ticker);
if (!share_prices.count(key)) {
auto price = get_share_price_v1(ticker, date);
if (budget::is_server_running()) {
std::cout << "INFO: Share: Price (" << date << ")"
<< " ticker " << ticker << " = " << price << std::endl;
}
share_prices[key] = price;
}
return share_prices[key];
}
|
//=======================================================================
// Copyright (c) 2013-2018 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <tuple>
#include <utility>
#include <iostream>
#include <sstream>
#include "cpp_utils/string.hpp"
#include "share.hpp"
#include "config.hpp"
#include "server.hpp"
#include "http.hpp"
#include "date.hpp"
namespace {
struct share_price_cache_key {
budget::date date;
std::string ticker;
share_price_cache_key(budget::date date, std::string ticker) : date(date), ticker(ticker) {}
friend bool operator<(const share_price_cache_key & lhs, const share_price_cache_key & rhs){
return std::tie(lhs.date, lhs.ticker) < std::tie(rhs.date, rhs.ticker);
}
friend bool operator==(const share_price_cache_key & lhs, const share_price_cache_key & rhs){
return std::tie(lhs.date, lhs.ticker) == std::tie(rhs.date, rhs.ticker);
}
};
std::map<share_price_cache_key, double> share_prices;
budget::date get_valid_date(budget::date d){
// We cannot get closing price in the future, so we use the day before date
if (d >= budget::local_day()) {
auto now = std::chrono::system_clock::now();
auto tt = std::chrono::system_clock::to_time_t(now);
auto tm = *std::localtime(&tt);
// We make sure that we are on a new U.S: day
// TODO This should be done by getting the current time in the U.S.
if (tm.tm_hour > 15) {
return get_valid_date(budget::local_day() - budget::days(1));
} else {
return get_valid_date(budget::local_day() - budget::days(2));
}
}
auto dow = d.day_of_the_week();
if (dow == 6 || dow == 7){
return get_valid_date(d - budget::days(dow - 5));
}
return d;
}
// V2 is using alpha_vantage
double get_share_price_v2(const std::string& quote, const budget::date& date, int /*depth*/ = 0) {
if (!budget::config_contains("alpha_vantage_api_key")) {
std::cout << "ERROR: Price(v2): Need Alpha Vantage API KEY configured to work" << std::endl;
return 1.0;
}
auto api_key = budget::config_value("alpha_vantage_api_key");
//https://www.alphavantage.co/query\?function\=TIME_SERIES_DAILY\&symbol\=CHDVD.SWI\&interval\=5min\&apikey\=API_KEY
httplib::SSLClient cli("www.alphavantage.co", 443);
auto date_str = budget::date_to_string(date);
std::string api_complete = "/query?function=TIME_SERIES_DAILY&symbol=" + quote + "&outputsize=full&apikey=" + api_key;
auto res = cli.Get(api_complete.c_str());
if (!res) {
std::cout << "ERROR: Price(v2): No response" << std::endl;
std::cout << "ERROR: Price(v2): URL is " << api_complete << std::endl;
return 1.0;
} else if (res->status != 200) {
std::cout << "ERROR: Price(v2): Error response " << res->status << std::endl;
std::cout << "ERROR: Price(v2): URL is " << api_complete << std::endl;
std::cout << "ERROR: Price(v2): Response is " << res->body << std::endl;
return 1.0;
} else {
std::stringstream bodyreader(res->body);
std::vector<std::string> lines;
bool data = false;
std::string line;
while(std::getline(bodyreader, line)) {
cpp::trim(line);
if (line.size() <= 3) {
continue;
}
if (line.find("Time Series") != std::string::npos) {
data = true;
} else if(data) {
lines.emplace_back(line);
}
}
for (size_t i = 0; i < lines.size(); i += 6){
std::string date_str(lines[i].begin() + 1, lines[i].begin() + 11);
std::string value(lines[i+4].begin() + 13, lines[i+4].end() - 2);
share_price_cache_key key(budget::from_string(date_str), quote);
share_prices[key] = budget::to_number<float>(value);
}
share_price_cache_key key(date, quote);
if (share_prices.count(key) ){
return share_prices[key];
} else {
for (size_t i = 0; i < 4; ++i){
auto next_date = get_valid_date(date - budget::days(1));
std::cout << "INFO: Price(v2): Possible holiday, retrying on previous day" << std::endl;
std::cout << "INFO: Date was " << date << " retrying with " << next_date << std::endl;
// Opportunistically check the cache for previous day!
share_price_cache_key key(next_date, quote);
if (share_prices.count(key)) {
return share_prices[key];
}
}
}
return 1.0;
}
}
// V1 is using cloud.iexapis.com
double get_share_price_v1(const std::string& quote, const budget::date& date, int depth = 0) {
if (!budget::config_contains("iex_cloud_token")) {
std::cout << "ERROR: Price(v1): Need IEX cloud token configured to work" << std::endl;
return 1.0;
}
auto token = budget::config_value("iex_cloud_token");
httplib::SSLClient cli("cloud.iexapis.com", 443);
auto date_str = budget::date_to_string(date);
std::string api_complete = "/beta/stock/" + quote + "/chart/date/" + date_str + "?chartByDay=true&token=" + token;
auto res = cli.Get(api_complete.c_str());
if (!res) {
std::cout << "ERROR: Price(v1): No response" << std::endl;
std::cout << "ERROR: Price(v1): URL is " << api_complete << std::endl;
return 1.0;
} else if (res->status != 200) {
std::cout << "ERROR: Price(v1): Error response " << res->status << std::endl;
std::cout << "ERROR: Price(v1): URL is " << api_complete << std::endl;
std::cout << "ERROR: Price(v1): Response is " << res->body << std::endl;
return 1.0;
} else {
// Pseudo handling of holidays
if (res->body == "[]") {
if (depth <= 3) {
auto next_date = get_valid_date(date - budget::days(1));
std::cout << "INFO: Price(v1): Possible holiday, retrying on previous day" << std::endl;
std::cout << "INFO: Date was " << date << " retrying with " << next_date << std::endl;
// Opportunistically check the cache for previous day!
share_price_cache_key key(next_date, quote);
if (share_prices.count(key)) {
return share_prices[key];
} else {
return get_share_price_v1(quote, next_date, depth + 1);
}
}
}
// Example
// [{"date":"2019-03-01","open":174.28,"close":174.97,"high":175.15,"low":172.89,"volume":25886167,"uOpen":174.28,"uClose":174.97,"uHigh":175.15,"uLow":172.89,"uVolume":25886167,"change":1.82,"changePercent":1.0511,"label":"Mar
// 1, 19","changeOverTime":172.237624}]
auto& buffer = res->body;
std::string start = "\"close\":";
std::string stop = ",\"high\":";
if (buffer.find(start) == std::string::npos || buffer.find(stop) == std::string::npos) {
std::cout << "ERROR: Price(v1): Error parsing share prices" << std::endl;
std::cout << "ERROR: Price(v1): URL is " << api_complete << std::endl;
std::cout << "ERROR: Price(v1): Response is " << res->body << std::endl;
return 1.0;
} else {
std::string ratio_result(buffer.begin() + buffer.find(start) + start.size(), buffer.begin() + buffer.find(stop));
return atof(ratio_result.c_str());
}
}
}
} // end of anonymous namespace
void budget::load_share_price_cache(){
std::string file_path = budget::path_to_budget_file("share_price.cache");
std::ifstream file(file_path);
if (!file.is_open() || !file.good()){
std::cout << "INFO: Impossible to load Share Price Cache" << std::endl;
return;
}
std::string line;
while (file.good() && getline(file, line)) {
if (line.empty()) {
continue;
}
auto parts = split(line, ':');
share_price_cache_key key(budget::from_string(parts[0]), parts[1]);
share_prices[key] = budget::to_number<double>(parts[2]);
}
if (budget::is_server_running()) {
std::cout << "INFO: Share Price Cache has been loaded from " << file_path << std::endl;
std::cout << "INFO: Share Price Cache has " << share_prices.size() << " entries " << std::endl;
}
}
void budget::save_share_price_cache() {
std::string file_path = budget::path_to_budget_file("share_price.cache");
std::ofstream file(file_path);
if (!file.is_open() || !file.good()){
std::cout << "INFO: Impossible to save Share Price Cache" << std::endl;
return;
}
for (auto & pair : share_prices) {
if (pair.second != 1.0) {
auto& key = pair.first;
file << budget::date_to_string(key.date) << ':' << key.ticker << ':' << pair.second << std::endl;
}
}
if (budget::is_server_running()) {
std::cout << "INFO: Share Price Cache has been saved to " << file_path << std::endl;
std::cout << "INFO: Share Price Cache has " << share_prices.size() << " entries " << std::endl;
}
}
void budget::refresh_share_price_cache(){
// Refresh the prices for each value
for (auto& pair : share_prices) {
auto& key = pair.first;
share_prices[key] = get_share_price_v1(key.ticker, key.date);
}
// Prefetch the current prices
for (auto & pair : share_prices) {
auto& key = pair.first;
share_price(key.ticker);
}
if (budget::is_server_running()) {
std::cout << "INFO: Share Price Cache has been refreshed" << std::endl;
std::cout << "INFO: Share Price Cache has " << share_prices.size() << " entries " << std::endl;
}
}
double budget::share_price(const std::string& ticker){
return share_price(ticker, budget::local_day());
}
double budget::share_price(const std::string& ticker, budget::date d){
auto date = get_valid_date(d);
share_price_cache_key key(date, ticker);
if (!share_prices.count(key)) {
auto price = get_share_price_v1(ticker, date);
if (budget::is_server_running()) {
std::cout << "INFO: Share: Price (" << date << ")"
<< " ticker " << ticker << " = " << price << std::endl;
}
share_prices[key] = price;
}
return share_prices[key];
}
|
Add new V2 share price API (alpha_vantage)
|
Add new V2 share price API (alpha_vantage)
|
C++
|
mit
|
wichtounet/budgetwarrior,wichtounet/budgetwarrior,wichtounet/budgetwarrior
|
c4295b7e30d5fe9527fd7f3a20bc12ccfca8b94c
|
src/string.hh
|
src/string.hh
|
#ifndef string_hh_INCLUDED
#define string_hh_INCLUDED
#include "memoryview.hh"
#include "units.hh"
#include "utf8.hh"
#include <string>
#include <boost/regex.hpp>
namespace Kakoune
{
using Regex = boost::regex;
class String : public std::string
{
public:
String() {}
String(const char* content) : std::string(content) {}
String(std::string content) : std::string(std::move(content)) {}
explicit String(char content, CharCount count = 1) : std::string((size_t)(int)count, content) {}
explicit String(Codepoint cp, CharCount count = 1)
{
while (count-- > 0)
utf8::dump(back_inserter(*this), cp);
}
template<typename Iterator>
String(Iterator begin, Iterator end) : std::string(begin, end) {}
std::string& stdstr() { return *this; }
const std::string& stdstr() const { return *this; }
char operator[](ByteCount pos) const { return std::string::operator[]((int)pos); }
char& operator[](ByteCount pos) { return std::string::operator[]((int)pos); }
ByteCount length() const { return ByteCount{(int)std::string::length()}; }
CharCount char_length() const { return utf8::distance(begin(), end()); }
ByteCount byte_count_to(CharCount count) const { return utf8::advance(begin(), end(), (int)count) - begin(); }
CharCount char_count_to(ByteCount count) const { return utf8::distance(begin(), begin() + (int)count); }
String operator+(const String& other) const { return String{stdstr() + other.stdstr()}; }
String& operator+=(const String& other) { std::string::operator+=(other); return *this; }
String operator+(const char* other) const { return String{stdstr() + other}; }
String& operator+=(const char* other) { std::string::operator+=(other); return *this; }
String operator+(char other) const { return String{stdstr() + other}; }
String& operator+=(char other) { std::string::operator+=(other); return *this; }
String operator+(Codepoint cp) const { String res = *this; utf8::dump(back_inserter(res), cp); return res; }
String& operator+=(Codepoint cp) { utf8::dump(back_inserter(*this), cp); return *this; }
memoryview<char> data() const { return memoryview<char>(std::string::data(), size()); }
String substr(ByteCount pos, ByteCount length = -1) const
{
return String{std::string::substr((int)pos, (int)length)};
}
String substr(CharCount pos, CharCount length = INT_MAX) const
{
auto b = utf8::advance(begin(), end(), (int)pos);
auto e = utf8::advance(b, end(), (int)length);
return String(b,e);
}
};
class StringView
{
public:
constexpr StringView() : m_data{nullptr}, m_length{0} {}
constexpr StringView(const char* data, ByteCount length)
: m_data{data}, m_length{length} {}
constexpr StringView(const char* data) : m_data{data}, m_length{(int)strlen(data)} {}
constexpr StringView(const char* begin, const char* end) : m_data{begin}, m_length{(int)(end - begin)} {}
StringView(const String& str) : m_data{str.data().pointer()}, m_length{str.length()} {}
bool operator==(StringView other) const;
bool operator!=(StringView other) const;
const char* data() const { return m_data; }
using iterator = const char*;
using reverse_iterator = std::reverse_iterator<const char*>;
iterator begin() const { return m_data; }
iterator end() const { return m_data + (int)m_length; }
reverse_iterator rbegin() const { return reverse_iterator{m_data + (int)m_length}; }
reverse_iterator rend() const { return reverse_iterator{m_data}; }
char front() const { return *m_data; }
char back() const { return m_data[(int)m_length - 1]; }
char operator[](ByteCount pos) const { return m_data[(int)pos]; }
ByteCount length() const { return m_length; }
CharCount char_length() const { return utf8::distance(begin(), end()); }
bool empty() { return m_length == 0_byte; }
ByteCount byte_count_to(CharCount count) const;
CharCount char_count_to(ByteCount count) const;
StringView substr(ByteCount from, ByteCount length = INT_MAX) const;
StringView substr(CharCount from, CharCount length = INT_MAX) const;
String str() const { return String{begin(), end()}; }
operator String() const { return str(); } // to remove
private:
const char* m_data;
ByteCount m_length;
};
inline bool StringView::operator==(StringView other) const
{
return m_length == other.m_length and memcmp(m_data, other.m_data, (int)m_length) == 0;
}
inline bool StringView::operator!=(StringView other) const
{
return !this->operator==(other);
}
inline bool operator==(const char* lhs, StringView rhs)
{
return StringView{lhs} == rhs;
}
inline bool operator!=(const char* lhs, StringView rhs)
{
return StringView{lhs} != rhs;
}
inline bool operator==(const std::string& lhs, StringView rhs)
{
return StringView{lhs} == rhs;
}
inline bool operator!=(const std::string& lhs, StringView rhs)
{
return StringView{lhs} != rhs;
}
inline ByteCount StringView::byte_count_to(CharCount count) const
{
return utf8::advance(begin(), end(), (int)count) - begin();
}
inline CharCount StringView::char_count_to(ByteCount count) const
{
return utf8::distance(begin(), begin() + (int)count);
}
inline StringView StringView::substr(ByteCount from, ByteCount length) const
{
return StringView{ m_data + (int)from, std::min(m_length - from, length) };
}
inline StringView StringView::substr(CharCount from, CharCount length) const
{
auto beg = utf8::advance(begin(), end(), (int)from);
return StringView{ beg, utf8::advance(beg, end(), length) };
}
inline const char* begin(StringView str)
{
return str.begin();
}
inline const char* end(StringView str)
{
return str.end();
}
inline String operator+(const char* lhs, const String& rhs)
{
return String(lhs) + rhs;
}
inline String operator+(const std::string& lhs, const String& rhs)
{
return String(lhs) + rhs;
}
inline String operator+(const String& lhs, const std::string& rhs)
{
return lhs + String(rhs);
}
inline String& operator+=(String& lhs, StringView rhs)
{
lhs.append(rhs.data(), (size_t)(int)rhs.length());
return lhs;
}
inline String operator+(const char* lhs, StringView rhs)
{
String res = lhs;
res += rhs;
return res;
}
inline String operator+(const String& lhs, StringView rhs)
{
String res = lhs;
res += rhs;
return res;
}
inline String operator+(StringView lhs, const String& rhs)
{
String res{lhs.begin(), lhs.end()};
res.append(rhs);
return res;
}
inline String operator+(StringView lhs, const char* rhs)
{
String res{lhs.begin(), lhs.end()};
res.append(rhs);
return res;
}
inline String operator+(char lhs, const String& rhs)
{
return String(lhs) + rhs;
}
inline String operator+(Codepoint lhs, const String& rhs)
{
return String(lhs) + rhs;
}
std::vector<String> split(const String& str, char separator, char escape = 0);
String escape(const String& str, char character, char escape);
inline String operator"" _str(const char* str, size_t)
{
return String(str);
}
inline String codepoint_to_str(Codepoint cp)
{
std::string str;
utf8::dump(back_inserter(str), cp);
return String(str);
}
String option_to_string(const Regex& re);
void option_from_string(const String& str, Regex& re);
int str_to_int(const String& str);
String to_string(int val);
template<typename RealType, typename ValueType>
String to_string(const StronglyTypedNumber<RealType, ValueType>& val)
{
return to_string((ValueType)val);
}
bool prefix_match(StringView str, StringView prefix);
bool subsequence_match(StringView str, StringView subseq);
}
namespace std
{
template<>
struct hash<Kakoune::String> : hash<std::string>
{
size_t operator()(const Kakoune::String& str) const
{
return hash<std::string>::operator()(str);
}
};
}
#endif // string_hh_INCLUDED
|
#ifndef string_hh_INCLUDED
#define string_hh_INCLUDED
#include "memoryview.hh"
#include "units.hh"
#include "utf8.hh"
#include <string>
#include <boost/regex.hpp>
namespace Kakoune
{
using Regex = boost::regex;
class String : public std::string
{
public:
String() {}
String(const char* content) : std::string(content) {}
String(std::string content) : std::string(std::move(content)) {}
explicit String(char content, CharCount count = 1) : std::string((size_t)(int)count, content) {}
explicit String(Codepoint cp, CharCount count = 1)
{
while (count-- > 0)
utf8::dump(back_inserter(*this), cp);
}
template<typename Iterator>
String(Iterator begin, Iterator end) : std::string(begin, end) {}
std::string& stdstr() { return *this; }
const std::string& stdstr() const { return *this; }
char operator[](ByteCount pos) const { return std::string::operator[]((int)pos); }
char& operator[](ByteCount pos) { return std::string::operator[]((int)pos); }
ByteCount length() const { return ByteCount{(int)std::string::length()}; }
CharCount char_length() const { return utf8::distance(begin(), end()); }
ByteCount byte_count_to(CharCount count) const { return utf8::advance(begin(), end(), (int)count) - begin(); }
CharCount char_count_to(ByteCount count) const { return utf8::distance(begin(), begin() + (int)count); }
String operator+(const String& other) const { return String{stdstr() + other.stdstr()}; }
String& operator+=(const String& other) { std::string::operator+=(other); return *this; }
String operator+(const char* other) const { return String{stdstr() + other}; }
String& operator+=(const char* other) { std::string::operator+=(other); return *this; }
String operator+(char other) const { return String{stdstr() + other}; }
String& operator+=(char other) { std::string::operator+=(other); return *this; }
String operator+(Codepoint cp) const { String res = *this; utf8::dump(back_inserter(res), cp); return res; }
String& operator+=(Codepoint cp) { utf8::dump(back_inserter(*this), cp); return *this; }
memoryview<char> data() const { return memoryview<char>(std::string::data(), size()); }
String substr(ByteCount pos, ByteCount length = -1) const
{
return String{std::string::substr((int)pos, (int)length)};
}
String substr(CharCount pos, CharCount length = INT_MAX) const
{
auto b = utf8::advance(begin(), end(), (int)pos);
auto e = utf8::advance(b, end(), (int)length);
return String(b,e);
}
};
class StringView
{
public:
constexpr StringView() : m_data{nullptr}, m_length{0} {}
constexpr StringView(const char* data, ByteCount length)
: m_data{data}, m_length{length} {}
constexpr StringView(const char* data) : m_data{data}, m_length{(int)strlen(data)} {}
constexpr StringView(const char* begin, const char* end) : m_data{begin}, m_length{(int)(end - begin)} {}
StringView(const String& str) : m_data{str.data().pointer()}, m_length{str.length()} {}
bool operator==(StringView other) const;
bool operator!=(StringView other) const;
const char* data() const { return m_data; }
using iterator = const char*;
using reverse_iterator = std::reverse_iterator<const char*>;
iterator begin() const { return m_data; }
iterator end() const { return m_data + (int)m_length; }
reverse_iterator rbegin() const { return reverse_iterator{m_data + (int)m_length}; }
reverse_iterator rend() const { return reverse_iterator{m_data}; }
char front() const { return *m_data; }
char back() const { return m_data[(int)m_length - 1]; }
char operator[](ByteCount pos) const { return m_data[(int)pos]; }
ByteCount length() const { return m_length; }
CharCount char_length() const { return utf8::distance(begin(), end()); }
bool empty() { return m_length == 0_byte; }
ByteCount byte_count_to(CharCount count) const;
CharCount char_count_to(ByteCount count) const;
StringView substr(ByteCount from, ByteCount length = INT_MAX) const;
StringView substr(CharCount from, CharCount length = INT_MAX) const;
String str() const { return String{begin(), end()}; }
operator String() const { return str(); } // to remove
private:
const char* m_data;
ByteCount m_length;
};
inline bool StringView::operator==(StringView other) const
{
return m_length == other.m_length and memcmp(m_data, other.m_data, (int)m_length) == 0;
}
inline bool StringView::operator!=(StringView other) const
{
return !this->operator==(other);
}
inline bool operator==(const char* lhs, StringView rhs)
{
return StringView{lhs} == rhs;
}
inline bool operator!=(const char* lhs, StringView rhs)
{
return StringView{lhs} != rhs;
}
inline bool operator==(const std::string& lhs, StringView rhs)
{
return StringView{lhs} == rhs;
}
inline bool operator!=(const std::string& lhs, StringView rhs)
{
return StringView{lhs} != rhs;
}
inline ByteCount StringView::byte_count_to(CharCount count) const
{
return utf8::advance(begin(), end(), (int)count) - begin();
}
inline CharCount StringView::char_count_to(ByteCount count) const
{
return utf8::distance(begin(), begin() + (int)count);
}
inline StringView StringView::substr(ByteCount from, ByteCount length) const
{
if (length < 0)
length = INT_MAX;
return StringView{ m_data + (int)from, std::min(m_length - from, length) };
}
inline StringView StringView::substr(CharCount from, CharCount length) const
{
if (length < 0)
length = INT_MAX;
auto beg = utf8::advance(begin(), end(), (int)from);
return StringView{ beg, utf8::advance(beg, end(), length) };
}
inline const char* begin(StringView str)
{
return str.begin();
}
inline const char* end(StringView str)
{
return str.end();
}
inline String operator+(const char* lhs, const String& rhs)
{
return String(lhs) + rhs;
}
inline String operator+(const std::string& lhs, const String& rhs)
{
return String(lhs) + rhs;
}
inline String operator+(const String& lhs, const std::string& rhs)
{
return lhs + String(rhs);
}
inline String& operator+=(String& lhs, StringView rhs)
{
lhs.append(rhs.data(), (size_t)(int)rhs.length());
return lhs;
}
inline String operator+(const char* lhs, StringView rhs)
{
String res = lhs;
res += rhs;
return res;
}
inline String operator+(const String& lhs, StringView rhs)
{
String res = lhs;
res += rhs;
return res;
}
inline String operator+(StringView lhs, const String& rhs)
{
String res{lhs.begin(), lhs.end()};
res.append(rhs);
return res;
}
inline String operator+(StringView lhs, const char* rhs)
{
String res{lhs.begin(), lhs.end()};
res.append(rhs);
return res;
}
inline String operator+(char lhs, const String& rhs)
{
return String(lhs) + rhs;
}
inline String operator+(Codepoint lhs, const String& rhs)
{
return String(lhs) + rhs;
}
std::vector<String> split(const String& str, char separator, char escape = 0);
String escape(const String& str, char character, char escape);
inline String operator"" _str(const char* str, size_t)
{
return String(str);
}
inline String codepoint_to_str(Codepoint cp)
{
std::string str;
utf8::dump(back_inserter(str), cp);
return String(str);
}
String option_to_string(const Regex& re);
void option_from_string(const String& str, Regex& re);
int str_to_int(const String& str);
String to_string(int val);
template<typename RealType, typename ValueType>
String to_string(const StronglyTypedNumber<RealType, ValueType>& val)
{
return to_string((ValueType)val);
}
bool prefix_match(StringView str, StringView prefix);
bool subsequence_match(StringView str, StringView subseq);
}
namespace std
{
template<>
struct hash<Kakoune::String> : hash<std::string>
{
size_t operator()(const Kakoune::String& str) const
{
return hash<std::string>::operator()(str);
}
};
}
#endif // string_hh_INCLUDED
|
Fix StringView::substr when passed a negative length
|
Fix StringView::substr when passed a negative length
|
C++
|
unlicense
|
alpha123/kakoune,occivink/kakoune,jkonecny12/kakoune,zakgreant/kakoune,danr/kakoune,mawww/kakoune,casimir/kakoune,rstacruz/kakoune,danielma/kakoune,occivink/kakoune,alexherbo2/kakoune,xificurC/kakoune,rstacruz/kakoune,lenormf/kakoune,Somasis/kakoune,danielma/kakoune,zakgreant/kakoune,elegios/kakoune,ekie/kakoune,elegios/kakoune,danr/kakoune,casimir/kakoune,mawww/kakoune,alpha123/kakoune,flavius/kakoune,lenormf/kakoune,zakgreant/kakoune,jjthrash/kakoune,flavius/kakoune,Asenar/kakoune,lenormf/kakoune,jjthrash/kakoune,casimir/kakoune,Asenar/kakoune,ekie/kakoune,xificurC/kakoune,alexherbo2/kakoune,Somasis/kakoune,jjthrash/kakoune,danr/kakoune,occivink/kakoune,zakgreant/kakoune,xificurC/kakoune,jjthrash/kakoune,flavius/kakoune,casimir/kakoune,Somasis/kakoune,danielma/kakoune,elegios/kakoune,ekie/kakoune,jkonecny12/kakoune,alexherbo2/kakoune,jkonecny12/kakoune,jkonecny12/kakoune,elegios/kakoune,Somasis/kakoune,alpha123/kakoune,danr/kakoune,rstacruz/kakoune,occivink/kakoune,danielma/kakoune,Asenar/kakoune,alexherbo2/kakoune,mawww/kakoune,mawww/kakoune,ekie/kakoune,xificurC/kakoune,flavius/kakoune,rstacruz/kakoune,alpha123/kakoune,lenormf/kakoune,Asenar/kakoune
|
46e4b7fbd3c29ec9390979cae58d8c01ca2e2373
|
src/table.cpp
|
src/table.cpp
|
// Copyright (c) 2016 Kasper Kronborg Isager and Radoslaw Niemczyk.
#include "table.hpp"
namespace lsh {
/**
* Construct a new lookup table.
*
* @param dimensions The number of dimensions of vectors in the table.
* @param width The width of each vector hash.
* @param partitions The number of paritions to use.
*/
table::table(unsigned int dimensions, unsigned int width, unsigned int partitions) {
this->dimensions_ = dimensions;
for (unsigned int i = 0; i < partitions; i++) {
this->masks_.push_back(random_mask(dimensions, width));
this->partitions_.push_back(partition());
}
}
/**
* Construct a new lookup table.
*
* @param dimensions The number of dimensions of vectors in the table.
* @param radius The radius to cover in the table.
*/
table::table(unsigned int dimensions, unsigned int radius) {
unsigned int n = (1 << (radius + 1)) - 1;
covering_mask::mapping m;
for (unsigned int i = 0; i < dimensions; i++) {
m.push_back(vector::random(n));
}
for (unsigned int i = 0; i < n; i++) {
this->masks_.push_back(covering_mask(dimensions, i, m));
this->partitions_.push_back(partition());
}
}
/**
* Get the number of vectors in this lookup table.
*
* @return The number of vectors in this lookup table.
*/
unsigned int table::size() const {
return this->size_;
}
/**
* Add a vector to this lookup table.
*
* @param vector The vector to add to this lookup table.
*/
void table::add(vector vector) {
unsigned int n = this->partitions_.size();
for (unsigned int i = 0; i < n; i++) {
lsh::vector k = this->masks_[i].project(vector);
bucket* b = &this->partitions_[i][k];
b->push_back(vector);
}
this->size_++;
}
/**
* Query this lookup table for the nearest neighbour of a query vector.
*
* @param vector The query vector to look up the nearest neighbour of.
* @return The nearest neighbouring vector if found, otherwise a vector of size 0.
*/
vector table::query(const vector& vector) {
unsigned int n = this->partitions_.size();
// Keep track of the best candidate we've encountered.
lsh::vector* best_c = NULL;
// Keep track of the distance to the best candidate.
unsigned int best_d = 0;
for (unsigned int i = 0; i < n; i++) {
lsh::vector k = this->masks_[i].project(vector);
bucket* b = &this->partitions_[i][k];
for (lsh::vector& c: *b) {
unsigned int d = lsh::vector::distance(vector, c);
if (!best_c || d < best_d) {
best_c = &c;
best_d = d;
}
}
}
// In case we didn't find a vector then return the null vector.
if (!best_c) {
return lsh::vector(std::vector<bool> {});
}
return *best_c;
}
}
|
// Copyright (c) 2016 Kasper Kronborg Isager and Radoslaw Niemczyk.
#include "table.hpp"
namespace lsh {
/**
* Construct a new lookup table.
*
* @param dimensions The number of dimensions of vectors in the table.
* @param width The width of each vector hash.
* @param partitions The number of paritions to use.
*/
table::table(unsigned int dimensions, unsigned int width, unsigned int partitions) {
this->dimensions_ = dimensions;
for (unsigned int i = 0; i < partitions; i++) {
this->masks_.push_back(random_mask(dimensions, width));
this->partitions_.push_back(partition());
}
}
/**
* Construct a new lookup table.
*
* @param dimensions The number of dimensions of vectors in the table.
* @param radius The radius to cover in the table.
*/
table::table(unsigned int dimensions, unsigned int radius) {
unsigned int n = (1 << (radius + 1)) - 1;
covering_mask::mapping m;
for (unsigned int i = 0; i < dimensions; i++) {
m.push_back(vector::random(n + 1));
}
for (unsigned int i = 0; i < n; i++) {
this->masks_.push_back(covering_mask(dimensions, i, m));
this->partitions_.push_back(partition());
}
}
/**
* Get the number of vectors in this lookup table.
*
* @return The number of vectors in this lookup table.
*/
unsigned int table::size() const {
return this->size_;
}
/**
* Add a vector to this lookup table.
*
* @param vector The vector to add to this lookup table.
*/
void table::add(vector vector) {
unsigned int n = this->partitions_.size();
for (unsigned int i = 0; i < n; i++) {
lsh::vector k = this->masks_[i].project(vector);
bucket* b = &this->partitions_[i][k];
b->push_back(vector);
}
this->size_++;
}
/**
* Query this lookup table for the nearest neighbour of a query vector.
*
* @param vector The query vector to look up the nearest neighbour of.
* @return The nearest neighbouring vector if found, otherwise a vector of size 0.
*/
vector table::query(const vector& vector) {
unsigned int n = this->partitions_.size();
// Keep track of the best candidate we've encountered.
lsh::vector* best_c = NULL;
// Keep track of the distance to the best candidate.
unsigned int best_d = 0;
for (unsigned int i = 0; i < n; i++) {
lsh::vector k = this->masks_[i].project(vector);
bucket* b = &this->partitions_[i][k];
for (lsh::vector& c: *b) {
unsigned int d = lsh::vector::distance(vector, c);
if (!best_c || d < best_d) {
best_c = &c;
best_d = d;
}
}
}
// In case we didn't find a vector then return the null vector.
if (!best_c) {
return lsh::vector(std::vector<bool> {});
}
return *best_c;
}
}
|
Fix a +-1 issue
|
Fix a +-1 issue
|
C++
|
mit
|
kasperisager/hemingway
|
04dcf7084520c37e385a1f0560dbe7d98349acec
|
src/utils.cpp
|
src/utils.cpp
|
#include "utils.h"
//
#include <fstream> // fstream
#include <boost/tokenizer.hpp>
#include <boost/numeric/ublas/matrix.hpp>
using namespace std;
using namespace boost;
using namespace boost::numeric::ublas;
std::ostream& operator<<(std::ostream& os, const std::map<int, double>& int_double_map) {
std::map<int, double>::const_iterator it = int_double_map.begin();
os << "{";
if(it==int_double_map.end()) {
os << "}";
return os;
}
os << it->first << ":" << it->second;
it++;
for(; it!=int_double_map.end(); it++) {
os << ", " << it->first << ":" << it->second;
}
os << "}";
return os;
}
std::ostream& operator<<(std::ostream& os, const std::map<int, int>& int_int_map) {
std::map<int, int>::const_iterator it = int_int_map.begin();
os << "{";
if(it==int_int_map.end()) {
os << "}";
return os;
}
os << it->first << ":" << it->second;
it++;
for(; it!=int_int_map.end(); it++) {
os << ", " << it->first << ":" << it->second;
}
os << "}";
return os;
}
std::string int_to_str(int i) {
std::stringstream out;
out << i;
std::string s = out.str();
return s;
}
// FROM runModel_v2.cpp
/////////////////////////////////////////////////////////////////////
// expect a csv file of data
void LoadData(std::string file, boost::numeric::ublas::matrix<double>& M) {
ifstream in(file.c_str());
if (!in.is_open()) return;
typedef tokenizer< char_separator<char> > Tokenizer;
char_separator<char> sep(",");
string line;
int nrows = 0;
int ncols = 0;
std::vector<string> vec;
// get the size first
while (std::getline(in,line)) {
Tokenizer tok(line, sep);
vec.assign(tok.begin(), tok.end());
ncols = vec.end() - vec.begin();
nrows++;
}
cout << "num rows = "<< nrows << " num cols = " << ncols << endl;
// create a matrix to hold data
matrix<double> Data(nrows, ncols);
// make second pass
in.clear();
in.seekg(0);
int r = 0;
while (std::getline(in,line)) {
Tokenizer tok(line, sep);
vec.assign(tok.begin(), tok.end());
int i = 0;
for(i=0; i < vec.size() ; i++) {
Data(r, i) = ::strtod(vec[i].c_str(), 0);
}
r++;
}
M = Data;
}
bool is_almost(double val1, double val2, double precision) {
return abs(val1-val2) < precision;
}
|
#include "utils.h"
//
#include <fstream> // fstream
#include <boost/tokenizer.hpp>
#include <boost/numeric/ublas/matrix.hpp>
using namespace std;
using namespace boost;
using namespace boost::numeric::ublas;
std::ostream& operator<<(std::ostream& os, const map<int, double>& int_double_map) {
map<int, double>::const_iterator it = int_double_map.begin();
os << "{";
if(it==int_double_map.end()) {
os << "}";
return os;
}
os << it->first << ":" << it->second;
it++;
for(; it!=int_double_map.end(); it++) {
os << ", " << it->first << ":" << it->second;
}
os << "}";
return os;
}
std::ostream& operator<<(std::ostream& os, const map<int, int>& int_int_map) {
map<int, int>::const_iterator it = int_int_map.begin();
os << "{";
if(it==int_int_map.end()) {
os << "}";
return os;
}
os << it->first << ":" << it->second;
it++;
for(; it!=int_int_map.end(); it++) {
os << ", " << it->first << ":" << it->second;
}
os << "}";
return os;
}
string int_to_str(int i) {
std::stringstream out;
out << i;
string s = out.str();
return s;
}
// FROM runModel_v2.cpp
/////////////////////////////////////////////////////////////////////
// expect a csv file of data
void LoadData(string file, boost::numeric::ublas::matrix<double>& M) {
ifstream in(file.c_str());
if (!in.is_open()) return;
typedef tokenizer< char_separator<char> > Tokenizer;
char_separator<char> sep(",");
string line;
int nrows = 0;
int ncols = 0;
std::vector<string> vec;
// get the size first
while (std::getline(in,line)) {
Tokenizer tok(line, sep);
vec.assign(tok.begin(), tok.end());
ncols = vec.end() - vec.begin();
nrows++;
}
cout << "num rows = "<< nrows << " num cols = " << ncols << endl;
// create a matrix to hold data
matrix<double> Data(nrows, ncols);
// make second pass
in.clear();
in.seekg(0);
int r = 0;
while (std::getline(in,line)) {
Tokenizer tok(line, sep);
vec.assign(tok.begin(), tok.end());
int i = 0;
for(i=0; i < vec.size() ; i++) {
Data(r, i) = ::strtod(vec[i].c_str(), 0);
}
r++;
}
M = Data;
}
bool is_almost(double val1, double val2, double precision) {
return abs(val1-val2) < precision;
}
|
remove some std:: prefixes
|
remove some std:: prefixes
|
C++
|
apache-2.0
|
JDReutt/BayesDB,poppingtonic/BayesDB,probcomp/crosscat,probcomp/crosscat,poppingtonic/BayesDB,mit-probabilistic-computing-project/crosscat,probcomp/crosscat,probcomp/crosscat,mit-probabilistic-computing-project/crosscat,fivejjs/crosscat,JDReutt/BayesDB,poppingtonic/BayesDB,fivejjs/crosscat,probcomp/crosscat,mit-probabilistic-computing-project/crosscat,probcomp/crosscat,probcomp/crosscat,fivejjs/crosscat,mit-probabilistic-computing-project/crosscat,mit-probabilistic-computing-project/crosscat,JDReutt/BayesDB,poppingtonic/BayesDB,fivejjs/crosscat,JDReutt/BayesDB,fivejjs/crosscat,mit-probabilistic-computing-project/crosscat,mit-probabilistic-computing-project/crosscat,JDReutt/BayesDB,fivejjs/crosscat,probcomp/crosscat,poppingtonic/BayesDB,fivejjs/crosscat
|
3af5e765a2a197203feed676428b30c3d82e16b1
|
core/signal.h++
|
core/signal.h++
|
/**
* The MIT License (MIT)
*
* Copyright © 2017-2018 Ruben Van Boxem
*
* 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.
**/
/*
* Signal
* Registers observers.
* Notifies registered observers.
*/
#ifndef SKUI_CORE_SIGNAL_H
#define SKUI_CORE_SIGNAL_H
#include "core/slot.h++"
#include "core/trackable.h++"
#include "core/value_ptr.h++"
#include <algorithm>
#include <functional>
#include <iterator>
#include <list>
#include <memory>
#include <mutex>
#include <utility>
namespace skui
{
namespace core
{
namespace implementation
{
template<typename... ArgTypes>
class signal_base : public tracker
, public trackable
{
using mutex_type = std::mutex;
using mutex_lock = const std::lock_guard<mutex_type>;
public:
using function_type = void(*)(ArgTypes...);
using slot_type = slot<void, ArgTypes...>;
using object_slot_type = std::pair<const trackable*, value_ptr<slot_type>>;
using connection_type = typename std::list<object_slot_type>::const_iterator;
signal_base() = default;
~signal_base() override { disconnect_all(); }
signal_base(const signal_base& other)
: trackable(other)
, slots(other.slots.begin(), other.slots.end())
{}
signal_base(signal_base&& other) noexcept : slots(std::move(other.slots)) {}
signal_base& operator=(signal_base other) { swap(slots, other.slots); return *this; }
void trackable_deleted(const trackable* tracker) override
{
disconnect(tracker);
}
void trackable_moved(const trackable* old_object, const trackable* new_object) override
{
mutex_lock lock(slots_mutex);
for(auto& object_slot : slots)
{
if(object_slot.first == old_object)
object_slot.first = new_object;
}
}
void trackable_copied(const trackable* old_object, const trackable* new_object) override
{
mutex_lock lock(slots_mutex);
for(const auto& object_slot : slots)
{
if(object_slot.first == old_object)
slots.emplace_back(new_object, object_slot.second);
}
}
template<typename Callable, typename ReturnType = void>
connection_type connect(Callable&& callable)
{
mutex_lock lock(slots_mutex);
slots.emplace_back(nullptr, make_value<callable_slot<Callable, ReturnType, ArgTypes...>>(callable));
return --slots.end();
}
template<typename Class, class FunctionClass, typename ReturnType, typename... FunctionArgTypes>
connection_type connect(Class* object, ReturnType(FunctionClass::* slot)(FunctionArgTypes...))
{
static_assert(std::is_base_of<trackable, Class>::value,
"You can only connect to member functions of a trackable subclass.");
static_assert(std::is_base_of<FunctionClass, Class>::value,
"You can only connect to member functions of a related object.");
mutex_lock lock(slots_mutex);
slots.emplace_back(object, make_value<member_function_slot<Class, ReturnType(FunctionClass::*)(FunctionArgTypes...), ReturnType, ArgTypes...>>(slot));
object->track(this);
return --slots.end();
}
template<typename Class, typename FunctionClass, typename ReturnType, typename... FunctionArgTypes>
connection_type connect(const Class* object, ReturnType(FunctionClass::* slot)(FunctionArgTypes...) const)
{
static_assert(std::is_base_of<trackable, Class>::value,
"You can only connect to member functions of a trackable subclass");
static_assert(std::is_base_of<FunctionClass, Class>::value,
"You can only connect to member functions of a related object.");
mutex_lock lock(slots_mutex);
slots.emplace_back(object, make_value<const_member_function_slot<Class, ReturnType(FunctionClass::*)(FunctionArgTypes...) const, ReturnType, ArgTypes...>>(slot));
object->track(this);
return --slots.end();
}
template<typename Signal>
connection_type relay(const Signal& signal)
{
mutex_lock lock(slots_mutex);
slots.emplace_back(&signal, make_value<const_member_function_slot<Signal, void(Signal::*)(ArgTypes...) const, void, ArgTypes...>>(&Signal::template emit<ArgTypes...>));
signal.track(this);
return --slots.end();
}
// removes a previously made connection, handles lifetime tracking if it was the last connection to a specific object
void disconnect(connection_type connection)
{
mutex_lock lock(slots_mutex);
const trackable* object = connection->first;
slots.erase(connection);
if(object && std::any_of(slots.begin(), slots.end(),
[&object](const object_slot_type& object_slot)
{ return object_slot.first == object; }))
object->untrack(this);
}
// removes all connections to an object
void disconnect(const trackable* object)
{
mutex_lock lock(slots_mutex);
object->untrack(this);
slots.remove_if([object](const object_slot_type& object_slot)
{
return object == object_slot.first;
});
}
// removes all connections
void disconnect_all()
{
mutex_lock lock(slots_mutex);
for(object_slot_type& object_slot : slots)
{
auto trackable = object_slot.first;
if(trackable)
trackable->untrack(this);
}
slots.clear();
}
protected:
// mutable here allows to connect to a const object's signals
mutable std::list<object_slot_type> slots;
mutable mutex_type slots_mutex;
};
}
template<typename... ArgTypes>
class signal : public implementation::signal_base<ArgTypes...>
{
public:
signal() = default;
template<typename... EmitArgTypes>
void emit(EmitArgTypes&&... arguments) const
{
std::lock_guard<decltype(this->slots_mutex)> lock(this->slots_mutex);
for(auto&& object_slot : this->slots)
{
// This needs a dynamic_cast<const void*> e.g. when trackable is not the first parent class
object_slot.second->operator()(dynamic_cast<const void*>(object_slot.first),
std::forward<EmitArgTypes>(arguments)...);
}
}
};
}
}
#endif
|
/**
* The MIT License (MIT)
*
* Copyright © 2017-2018 Ruben Van Boxem
*
* 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.
**/
/*
* Signal
* Registers observers.
* Notifies registered observers.
*/
#ifndef SKUI_CORE_SIGNAL_H
#define SKUI_CORE_SIGNAL_H
#include "core/slot.h++"
#include "core/trackable.h++"
#include "core/value_ptr.h++"
#include <algorithm>
#include <functional>
#include <iterator>
#include <list>
#include <memory>
#include <mutex>
#include <utility>
namespace skui
{
namespace core
{
namespace implementation
{
template<typename... ArgTypes>
class signal_base : public tracker
, public trackable
{
using mutex_type = std::mutex;
using mutex_lock = const std::lock_guard<mutex_type>;
public:
using function_type = void(*)(ArgTypes...);
using slot_type = slot<void, ArgTypes...>;
using object_slot_type = std::pair<const trackable*, value_ptr<slot_type>>;
using connection_type = typename std::list<object_slot_type>::const_iterator;
signal_base() = default;
~signal_base() override { disconnect_all(); }
signal_base(const signal_base& other)
: trackable(other)
, slots(other.slots.begin(), other.slots.end())
{}
signal_base(signal_base&& other) noexcept : slots(std::move(other.slots)) {}
signal_base& operator=(signal_base other) { swap(slots, other.slots); return *this; }
void trackable_deleted(const trackable* tracker) override
{
disconnect(tracker);
}
void trackable_moved(const trackable* old_object, const trackable* new_object) override
{
mutex_lock lock(slots_mutex);
for(auto& object_slot : slots)
{
if(object_slot.first == old_object)
object_slot.first = new_object;
}
}
void trackable_copied(const trackable* old_object, const trackable* new_object) override
{
mutex_lock lock(slots_mutex);
for(const auto& object_slot : slots)
{
if(object_slot.first == old_object)
slots.emplace_back(new_object, object_slot.second);
}
}
template<typename Callable, typename ReturnType = void>
connection_type connect(Callable&& callable)
{
mutex_lock lock(slots_mutex);
slots.emplace_back(nullptr, make_value<callable_slot<Callable, ReturnType, ArgTypes...>>(callable));
return --slots.end();
}
template<typename Class, class FunctionClass, typename ReturnType, typename... FunctionArgTypes>
connection_type connect(Class* object, ReturnType(FunctionClass::* slot)(FunctionArgTypes...))
{
static_assert(std::is_base_of<trackable, Class>::value,
"You can only connect to member functions of a trackable subclass.");
static_assert(std::is_base_of<FunctionClass, Class>::value,
"You can only connect to member functions of a related object.");
mutex_lock lock(slots_mutex);
slots.emplace_back(object, make_value<member_function_slot<Class, ReturnType(FunctionClass::*)(FunctionArgTypes...), ReturnType, ArgTypes...>>(slot));
object->track(this);
return --slots.end();
}
template<typename Class, typename FunctionClass, typename ReturnType, typename... FunctionArgTypes>
connection_type connect(const Class* object, ReturnType(FunctionClass::* slot)(FunctionArgTypes...) const)
{
static_assert(std::is_base_of<trackable, Class>::value,
"You can only connect to member functions of a trackable subclass");
static_assert(std::is_base_of<FunctionClass, Class>::value,
"You can only connect to member functions of a related object.");
mutex_lock lock(slots_mutex);
slots.emplace_back(object, make_value<const_member_function_slot<Class, ReturnType(FunctionClass::*)(FunctionArgTypes...) const, ReturnType, ArgTypes...>>(slot));
object->track(this);
return --slots.end();
}
template<typename Signal>
connection_type relay(const Signal& signal)
{
mutex_lock lock(slots_mutex);
slots.emplace_back(&signal, make_value<const_member_function_slot<Signal, void(Signal::*)(ArgTypes...) const, void, ArgTypes...>>(&Signal::template emit<ArgTypes...>));
signal.track(this);
return --slots.end();
}
// removes a previously made connection, handles lifetime tracking if it was the last connection to a specific object
void disconnect(connection_type connection)
{
mutex_lock lock(slots_mutex);
const trackable* object = connection->first;
slots.erase(connection);
if(object && std::any_of(slots.begin(), slots.end(),
[&object](const object_slot_type& object_slot)
{ return object_slot.first == object; }))
object->untrack(this);
}
// removes all connections to an object
void disconnect(const trackable* object)
{
mutex_lock lock(slots_mutex);
object->untrack(this);
slots.remove_if([object](const object_slot_type& object_slot)
{
return object == object_slot.first;
});
}
// removes all connections
void disconnect_all()
{
mutex_lock lock(slots_mutex);
for(object_slot_type& object_slot : slots)
{
auto trackable = object_slot.first;
if(trackable)
trackable->untrack(this);
}
slots.clear();
}
protected:
// mutable here allows to connect to a const object's signals
mutable std::list<object_slot_type> slots;
mutable mutex_type slots_mutex;
};
}
template<typename... ArgTypes>
class signal : public implementation::signal_base<ArgTypes...>
{
public:
signal() = default;
template<typename... EmitArgTypes>
void emit(EmitArgTypes&&... arguments) const
{
std::lock_guard<decltype(this->slots_mutex)> lock(this->slots_mutex);
for(auto&& object_slot : this->slots)
{
// This needs a dynamic_cast<const void*> e.g. when trackable is not the first parent class
object_slot.second->operator()(dynamic_cast<const void*>(object_slot.first),
std::forward<EmitArgTypes>(arguments)...);
}
}
template<typename... EmitArgTypes>
void operator()(EmitArgTypes&&... arguments) const
{
emit(std::forward<EmitArgTypes>(arguments)...);
}
};
}
}
#endif
|
Add call operator to core::signal.
|
Add call operator to core::signal.
|
C++
|
mit
|
skui-org/skui,rubenvb/skui,skui-org/skui,rubenvb/skui
|
54f00be9114dfa8cc21f37169abcac8d93efb965
|
prog5_saxpy/main.cpp
|
prog5_saxpy/main.cpp
|
#include <stdio.h>
#include <algorithm>
#include "CycleTimer.h"
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
extern void saxpySerial(int N, float a, float* X, float* Y, float* result);
#ifdef USE_ISPC_OBJ
extern "C"
{
void saxpy_ispc(int N, float a, float* X, float* Y, float* result);
void saxpy_ispc_withtasks(int N, float a, float* X, float* Y, float* result);
}
#else
#include "saxpy_ispc.h"
using namespace ispc;
#endif
// return GB/s
static float
toBW(int bytes, float sec) {
return static_cast<float>(bytes) / (1024.f * 1024.f * 1024.f) / sec;
}
static float
toGFLOPS(int ops, float sec) {
return static_cast<float>(ops) / 1e9f / sec;
}
int main() {
const unsigned int N = 20 * 1000 * 1000; // 20 M element vectors (~80 MB)
const unsigned int TOTAL_BYTES = 4 * N * sizeof(float);
const unsigned int TOTAL_FLOPS = 2 * N;
float scale = 2.f;
float* arrayX = new float[N];
float* arrayY = new float[N];
float* result = new float[N];
// initialize array values
for (unsigned int i=0; i<N; i++)
{
arrayX[i] = (float)i;
arrayY[i] = (float)i;
result[i] = 0.f;
}
//
// Run the serial implementation. Repeat three times for robust
// timing.
//
double minSerial = 1e30;
for (int i = 0; i < 3; ++i) {
double startTime =CycleTimer::currentSeconds();
saxpySerial(N, scale, arrayX, arrayY, result);
double endTime = CycleTimer::currentSeconds();
minSerial = std::min(minSerial, endTime - startTime);
}
// printf("[saxpy serial]:\t\t[%.3f] ms\t[%.3f] GB/s\t[%.3f] GFLOPS\n",
// minSerial * 1000,
// toBW(TOTAL_BYTES, minSerial),
// toGFLOPS(TOTAL_FLOPS, minSerial));
// Clear out the buffer
for (unsigned int i = 0; i < N; ++i)
result[i] = 0.f;
//
// Run the ISPC (single core) implementation
//
double minISPC = 1e30;
for (int i = 0; i < 3; ++i) {
double startTime = CycleTimer::currentSeconds();
saxpy_ispc(N, scale, arrayX, arrayY, result);
double endTime = CycleTimer::currentSeconds();
minISPC = std::min(minISPC, endTime - startTime);
}
printf("[saxpy ispc]:\t\t[%.3f] ms\t[%.3f] GB/s\t[%.3f] GFLOPS\n",
minISPC * 1000,
toBW(TOTAL_BYTES, (float)minISPC),
toGFLOPS(TOTAL_FLOPS, (float)minISPC));
// Clear out the buffer
for (unsigned int i = 0; i < N; ++i)
result[i] = 0.f;
//
// Run the ISPC (multi-core) implementation
//
double minTaskISPC = 1e30;
for (int i = 0; i < 3; ++i) {
double startTime = CycleTimer::currentSeconds();
saxpy_ispc_withtasks(N, scale, arrayX, arrayY, result);
double endTime = CycleTimer::currentSeconds();
minTaskISPC = std::min(minTaskISPC, endTime - startTime);
}
printf("[saxpy task ispc]:\t[%.3f] ms\t[%.3f] GB/s\t[%.3f] GFLOPS\n",
minTaskISPC * 1000,
toBW(TOTAL_BYTES, (float)minTaskISPC),
toGFLOPS(TOTAL_FLOPS, (float)minTaskISPC));
printf("\t\t\t\t(%.2fx speedup from use of tasks)\n", minISPC/minTaskISPC);
//printf("\t\t\t\t(%.2fx speedup from ISPC)\n", minSerial/minISPC);
//printf("\t\t\t\t(%.2fx speedup from task ISPC)\n", minSerial/minTaskISPC);
delete[] arrayX;
delete[] arrayY;
delete[] result;
return 0;
}
|
#include <stdio.h>
#include <algorithm>
#include "CycleTimer.h"
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
extern void saxpySerial(int N, float a, float* X, float* Y, float* result);
#ifdef USE_ISPC_OBJ
extern "C"
{
void saxpy_ispc(int N, float a, float* X, float* Y, float* result);
void saxpy_ispc_withtasks(int N, float a, float* X, float* Y, float* result);
}
#else
#include "saxpy_ispc.h"
using namespace ispc;
#endif
// return GB/s
static float
toBW(int bytes, float sec) {
return static_cast<float>(bytes) / (1024.f * 1024.f * 1024.f) / sec;
}
static float
toGFLOPS(int ops, float sec) {
return static_cast<float>(ops) / 1e9f / sec;
}
int main() {
const unsigned int N = 24 * 1000 * 1000; // 20 M element vectors (~80 MB)
const unsigned int TOTAL_BYTES = 4 * N * sizeof(float);
const unsigned int TOTAL_FLOPS = 2 * N;
float scale = 2.f;
float* arrayX = new float[N];
float* arrayY = new float[N];
float* result = new float[N];
// initialize array values
for (unsigned int i=0; i<N; i++)
{
arrayX[i] = (float)i;
arrayY[i] = (float)i;
result[i] = 0.f;
}
//
// Run the serial implementation. Repeat three times for robust
// timing.
//
double minSerial = 1e30;
for (int i = 0; i < 3; ++i) {
double startTime =CycleTimer::currentSeconds();
saxpySerial(N, scale, arrayX, arrayY, result);
double endTime = CycleTimer::currentSeconds();
minSerial = std::min(minSerial, endTime - startTime);
}
// printf("[saxpy serial]:\t\t[%.3f] ms\t[%.3f] GB/s\t[%.3f] GFLOPS\n",
// minSerial * 1000,
// toBW(TOTAL_BYTES, minSerial),
// toGFLOPS(TOTAL_FLOPS, minSerial));
// Clear out the buffer
for (unsigned int i = 0; i < N; ++i)
result[i] = 0.f;
//
// Run the ISPC (single core) implementation
//
double minISPC = 1e30;
for (int i = 0; i < 3; ++i) {
double startTime = CycleTimer::currentSeconds();
saxpy_ispc(N, scale, arrayX, arrayY, result);
double endTime = CycleTimer::currentSeconds();
minISPC = std::min(minISPC, endTime - startTime);
}
printf("[saxpy ispc]:\t\t[%.3f] ms\t[%.3f] GB/s\t[%.3f] GFLOPS\n",
minISPC * 1000,
toBW(TOTAL_BYTES, (float)minISPC),
toGFLOPS(TOTAL_FLOPS, (float)minISPC));
// Clear out the buffer
for (unsigned int i = 0; i < N; ++i)
result[i] = 0.f;
//
// Run the ISPC (multi-core) implementation
//
double minTaskISPC = 1e30;
for (int i = 0; i < 3; ++i) {
double startTime = CycleTimer::currentSeconds();
saxpy_ispc_withtasks(N, scale, arrayX, arrayY, result);
double endTime = CycleTimer::currentSeconds();
minTaskISPC = std::min(minTaskISPC, endTime - startTime);
}
printf("[saxpy task ispc]:\t[%.3f] ms\t[%.3f] GB/s\t[%.3f] GFLOPS\n",
minTaskISPC * 1000,
toBW(TOTAL_BYTES, (float)minTaskISPC),
toGFLOPS(TOTAL_FLOPS, (float)minTaskISPC));
printf("\t\t\t\t(%.2fx speedup from use of tasks)\n", minISPC/minTaskISPC);
//printf("\t\t\t\t(%.2fx speedup from ISPC)\n", minSerial/minISPC);
//printf("\t\t\t\t(%.2fx speedup from task ISPC)\n", minSerial/minTaskISPC);
delete[] arrayX;
delete[] arrayY;
delete[] result;
return 0;
}
|
Update main.cpp
|
Update main.cpp
|
C++
|
mit
|
tsinghua-15418/assignment1
|
099eb24068ec41c0a294396d6daa5b5e654df0da
|
tests/Clock.cpp
|
tests/Clock.cpp
|
static const char rcsid[] = "$Id: Clock.cpp,v 1.4 2001-03-27 16:14:00 legoater Exp $";
/*
* See the COPYING file for the terms of usage and distribution.
*/
#include <stdlib.h>
#include <sys/time.h> // for struct timeval
#ifdef __osf__
# include <machine/builtins.h> // for __RPCC()
#elif __linux__
# include <asm/msr.h> // for rdtscl()
#endif
#include <iostream>
#include "Clock.hh"
namespace
{
const usec_t UsecPerSec = INT64_CONSTANT(1000000);
}
bool Clock::UsingCPU = ::getenv("CLOCK_USE_CPU") ? true : false;
// -----------------------------------------------------------------------------
usec_t Clock::time(void)
{
if (UsingCPU) {
static bool warn = true;
if (warn) {
std::cout << "Using CPU clock." << std::endl;
warn = false;
}
#ifdef __osf__
return (usec_t) __RPCC();
#elif __linux__
{
unsigned long tsc;
rdtscl(tsc);
return (usec_t) tsc;
}
#else
# error CPU clock not implemented for this architecture
#endif
} else {
struct timeval tv;
gettimeofday(&tv, NULL);
return (usec_t) (tv.tv_sec * UsecPerSec + tv.tv_usec);
}
}
// -----------------------------------------------------------------------------
Clock::Clock(void)
: _start(0),
_elapsed(0),
_active(false)
{
start();
}
// -----------------------------------------------------------------------------
Clock::~Clock(void)
{
;
}
// -----------------------------------------------------------------------------
usec_t Clock::elapsed(void) const
{
if (!active())
return _elapsed;
return time() - _start;
}
// -----------------------------------------------------------------------------
usec_t Clock::start(void)
{
_active = true;
return _start = time();
}
// -----------------------------------------------------------------------------
usec_t Clock::stop(void)
{
_elapsed = elapsed();
_active = false;
return _elapsed;
}
|
static const char rcsid[] = "$Id: Clock.cpp,v 1.5 2001-04-10 14:39:09 bastiaan Exp $";
/*
* See the COPYING file for the terms of usage and distribution.
*/
#include <stdlib.h>
#include <sys/time.h> // for struct timeval
#ifdef __osf__
# include <machine/builtins.h> // for __RPCC()
#elif __linux__
# include <asm/msr.h> // for rdtscl()
#endif
#include <iostream>
#include "Clock.hh"
namespace
{
const usec_t UsecPerSec = INT64_CONSTANT(1000000);
}
bool Clock::UsingCPU = ::getenv("CLOCK_USE_CPU") ? true : false;
// -----------------------------------------------------------------------------
usec_t Clock::time(void)
{
if (UsingCPU) {
static bool warn = true;
if (warn) {
std::cout << "Using CPU clock." << std::endl;
warn = false;
}
#ifdef __osf__
return (usec_t) __RPCC();
#elif __linux__
{
unsigned long tsc;
rdtscl(tsc);
return (usec_t) tsc;
}
#else
{
std::cerr << "CPU clock not implemented for this architecture" << endl;
UsingCPU = false;
return Clock::time();
}
#endif
} else {
struct timeval tv;
gettimeofday(&tv, NULL);
return (usec_t) (tv.tv_sec * UsecPerSec + tv.tv_usec);
}
}
// -----------------------------------------------------------------------------
Clock::Clock(void)
: _start(0),
_elapsed(0),
_active(false)
{
start();
}
// -----------------------------------------------------------------------------
Clock::~Clock(void)
{
;
}
// -----------------------------------------------------------------------------
usec_t Clock::elapsed(void) const
{
if (!active())
return _elapsed;
return time() - _start;
}
// -----------------------------------------------------------------------------
usec_t Clock::start(void)
{
_active = true;
return _start = time();
}
// -----------------------------------------------------------------------------
usec_t Clock::stop(void)
{
_elapsed = elapsed();
_active = false;
return _elapsed;
}
|
Make it compile on other platforms than Linux and Tru64.
|
Make it compile on other platforms than Linux and Tru64.
|
C++
|
lgpl-2.1
|
robotics-at-maryland/log4cpp,robotics-at-maryland/log4cpp,robotics-at-maryland/log4cpp
|
065c2c818f7d0c4f2ee6dc3e62db19ce517939de
|
stuff/math.hh
|
stuff/math.hh
|
#ifndef DUNE_STUFF_MATH_HH
#define DUNE_STUFF_MATH_HH
template <typename T>
bool isnan( T x ) { return !(x==x); }
namespace Stuff {
/** \todo DOCME **/
template <class SomeRangeType, class OtherRangeType >
static double colonProduct( const SomeRangeType& arg1,
const OtherRangeType& arg2 )
{
dune_static_assert( SomeRangeType::cols == SomeRangeType::rows
&& OtherRangeType::cols == OtherRangeType::rows
&& int(OtherRangeType::cols) == int(SomeRangeType::rows), "RangeTypes_dont_fit" );
double ret = 0.0;
// iterators
typedef typename SomeRangeType::ConstRowIterator
ConstRowIteratorType;
typedef typename SomeRangeType::row_type::ConstIterator
ConstIteratorType;
ConstRowIteratorType arg1RowItEnd = arg1.end();
ConstRowIteratorType arg2RowItEnd = arg2.end();
ConstRowIteratorType arg2RowIt = arg2.begin();
for ( ConstRowIteratorType arg1RowIt = arg1.begin();
arg1RowIt != arg1RowItEnd, arg2RowIt != arg2RowItEnd;
++arg1RowIt, ++arg2RowIt ) {
ConstIteratorType row1ItEnd = arg1RowIt->end();
ConstIteratorType row2ItEnd = arg2RowIt->end();
ConstIteratorType row2It = arg2RowIt->begin();
for ( ConstIteratorType row1It = arg1RowIt->begin();
row1It != row1ItEnd, row2It != row2ItEnd;
++row1It, ++row2It ) {
ret += *row1It * *row2It;
}
}
return ret;
}
/**
* \brief dyadic product
*
* Implements \f$\left(arg_{1} \otimes arg_{2}\right)_{i,j}:={arg_{1}}_{i} {arg_{2}}_{j}\f$
* RangeType1 should be fieldmatrix, RangeType2 fieldvector
**/
template <class RangeType1, class RangeType2 >
static RangeType1 dyadicProduct( const RangeType2& arg1,
const RangeType2& arg2 )
{
RangeType1 ret( 0.0 );
typedef typename RangeType1::RowIterator
MatrixRowIteratorType;
typedef typename RangeType2::ConstIterator
ConstVectorIteratorType;
typedef typename RangeType2::Iterator
VectorIteratorType;
MatrixRowIteratorType rItEnd = ret.end();
ConstVectorIteratorType arg1It = arg1.begin();
for ( MatrixRowIteratorType rIt = ret.begin(); rIt != rItEnd; ++rIt ) {
ConstVectorIteratorType arg2It = arg2.begin();
VectorIteratorType vItEnd = rIt->end();
for ( VectorIteratorType vIt = rIt->begin();
vIt != vItEnd;
++vIt ) {
*vIt = *arg1It * *arg2It;
++arg2It;
}
++arg1It;
}
return ret;
}
/** \brief a vector wrapper for continiously updating min,max,avg of some element type vector
\todo find use? it's only used in minimal as testcase for itself...
**/
template < class ElementType >
class MinMaxAvg {
protected:
typedef MinMaxAvg< ElementType >
ThisType;
typedef std::vector< ElementType >
ElementsVec;
typedef typename ElementsVec::const_iterator
ElementsVecConstIterator;
public:
MinMaxAvg()
: min_ ( std::numeric_limits< ElementType >::max() ),
max_ ( std::numeric_limits< ElementType >::min() ),
avg_ ( ( min_ + max_ ) / 2.0 )
{}
MinMaxAvg( const ElementsVec& elements )
{
for ( ElementsVecConstIterator it = elements.begin(); it != elements.end(); ++it ) {
push( *it );
}
}
ElementType min () const { return min_; }
ElementType max () const { return max_; }
ElementType average () const { return avg_; }
void push( const ElementType& el ) {
size_t num = elements_.size();
elements_.push_back( el );
max_ = std::max( el, max_ );
min_ = std::min( el, min_ );
if ( num > 0 ) {
avg_ *= ( num / double( num + 1 ) );
avg_ += ( el / double( num + 1 ) );
}
else {
avg_ = el;
}
}
template < class Stream >
void output( Stream& stream ) {
stream << "min: " << min_ << " max: " << max_ << " avg: " << avg_ << std::endl;
}
protected:
ElementsVec elements_;
ElementType min_,max_,avg_;
MinMaxAvg( const ThisType& other );
};
//! bound \param var in [\param min,\param max]
template <typename T> T clamp(const T var,const T min,const T max)
{
return ( (var < min) ? min : ( var > max ) ? max : var );
}
//! docme
class MovingAverage
{
double avg_;
size_t steps_;
public:
MovingAverage()
:avg_(0.0),steps_(0)
{}
MovingAverage& operator += (double val)
{
avg_ += ( val - avg_ ) / ++steps_;
return *this;
}
operator double () { return avg_; }
};
//! no-branch sign function
long sign(long x) { return long(x!=0) | (long(x>=0)-1); }
} //end namespace Stuff
#endif // DUNE_STUFF_MATH_HH
|
#ifndef DUNE_STUFF_MATH_HH
#define DUNE_STUFF_MATH_HH
namespace Stuff {
/** \todo DOCME **/
template <class SomeRangeType, class OtherRangeType >
static double colonProduct( const SomeRangeType& arg1,
const OtherRangeType& arg2 )
{
dune_static_assert( SomeRangeType::cols == SomeRangeType::rows
&& OtherRangeType::cols == OtherRangeType::rows
&& int(OtherRangeType::cols) == int(SomeRangeType::rows), "RangeTypes_dont_fit" );
double ret = 0.0;
// iterators
typedef typename SomeRangeType::ConstRowIterator
ConstRowIteratorType;
typedef typename SomeRangeType::row_type::ConstIterator
ConstIteratorType;
ConstRowIteratorType arg1RowItEnd = arg1.end();
ConstRowIteratorType arg2RowItEnd = arg2.end();
ConstRowIteratorType arg2RowIt = arg2.begin();
for ( ConstRowIteratorType arg1RowIt = arg1.begin();
arg1RowIt != arg1RowItEnd, arg2RowIt != arg2RowItEnd;
++arg1RowIt, ++arg2RowIt ) {
ConstIteratorType row1ItEnd = arg1RowIt->end();
ConstIteratorType row2ItEnd = arg2RowIt->end();
ConstIteratorType row2It = arg2RowIt->begin();
for ( ConstIteratorType row1It = arg1RowIt->begin();
row1It != row1ItEnd, row2It != row2ItEnd;
++row1It, ++row2It ) {
ret += *row1It * *row2It;
}
}
return ret;
}
/**
* \brief dyadic product
*
* Implements \f$\left(arg_{1} \otimes arg_{2}\right)_{i,j}:={arg_{1}}_{i} {arg_{2}}_{j}\f$
* RangeType1 should be fieldmatrix, RangeType2 fieldvector
**/
template <class RangeType1, class RangeType2 >
static RangeType1 dyadicProduct( const RangeType2& arg1,
const RangeType2& arg2 )
{
RangeType1 ret( 0.0 );
typedef typename RangeType1::RowIterator
MatrixRowIteratorType;
typedef typename RangeType2::ConstIterator
ConstVectorIteratorType;
typedef typename RangeType2::Iterator
VectorIteratorType;
MatrixRowIteratorType rItEnd = ret.end();
ConstVectorIteratorType arg1It = arg1.begin();
for ( MatrixRowIteratorType rIt = ret.begin(); rIt != rItEnd; ++rIt ) {
ConstVectorIteratorType arg2It = arg2.begin();
VectorIteratorType vItEnd = rIt->end();
for ( VectorIteratorType vIt = rIt->begin();
vIt != vItEnd;
++vIt ) {
*vIt = *arg1It * *arg2It;
++arg2It;
}
++arg1It;
}
return ret;
}
/** \brief a vector wrapper for continiously updating min,max,avg of some element type vector
\todo find use? it's only used in minimal as testcase for itself...
**/
template < class ElementType >
class MinMaxAvg {
protected:
typedef MinMaxAvg< ElementType >
ThisType;
typedef std::vector< ElementType >
ElementsVec;
typedef typename ElementsVec::const_iterator
ElementsVecConstIterator;
public:
MinMaxAvg()
: min_ ( std::numeric_limits< ElementType >::max() ),
max_ ( std::numeric_limits< ElementType >::min() ),
avg_ ( ( min_ + max_ ) / 2.0 )
{}
MinMaxAvg( const ElementsVec& elements )
{
for ( ElementsVecConstIterator it = elements.begin(); it != elements.end(); ++it ) {
push( *it );
}
}
ElementType min () const { return min_; }
ElementType max () const { return max_; }
ElementType average () const { return avg_; }
void push( const ElementType& el ) {
size_t num = elements_.size();
elements_.push_back( el );
max_ = std::max( el, max_ );
min_ = std::min( el, min_ );
if ( num > 0 ) {
avg_ *= ( num / double( num + 1 ) );
avg_ += ( el / double( num + 1 ) );
}
else {
avg_ = el;
}
}
template < class Stream >
void output( Stream& stream ) {
stream << "min: " << min_ << " max: " << max_ << " avg: " << avg_ << std::endl;
}
protected:
ElementsVec elements_;
ElementType min_,max_,avg_;
MinMaxAvg( const ThisType& other );
};
//! bound \param var in [\param min,\param max]
template <typename T> T clamp(const T var,const T min,const T max)
{
return ( (var < min) ? min : ( var > max ) ? max : var );
}
//! docme
class MovingAverage
{
double avg_;
size_t steps_;
public:
MovingAverage()
:avg_(0.0),steps_(0)
{}
MovingAverage& operator += (double val)
{
avg_ += ( val - avg_ ) / ++steps_;
return *this;
}
operator double () { return avg_; }
};
//! no-branch sign function
long sign(long x) { return long(x!=0) | (long(x>=0)-1); }
} //end namespace Stuff
#endif // DUNE_STUFF_MATH_HH
|
remove useles isnan function
|
remove useles isnan function
|
C++
|
bsd-2-clause
|
renemilk/DUNE-Stuff,renemilk/DUNE-Stuff,renemilk/DUNE-Stuff
|
09a4e870114644c57b3f3b7f0f50319a004feba0
|
src/ogvr/PluginKit/PluginRegistration.cpp
|
src/ogvr/PluginKit/PluginRegistration.cpp
|
/** @file
@brief Implementation
@date 2014
@author
Ryan Pavlik
<[email protected]>
<http://sensics.com>
*/
// Copyright 2014 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 <ogvr/PluginKit/PluginRegistration.h>
// Library/third-party includes
// - none
// Standard includes
// - none
namespace ogvr {
class PluginRegistrationContext_impl {};
PluginRegistrationContext::PluginRegistrationContext()
: m_impl(new PluginRegistrationContext_impl) {}
/// Implementation must be here to handle std::unique_ptr's requirements
/// for destruction of incomplete types.
PluginRegistrationContext::~PluginRegistrationContext() {}
} // end of namespace ogvr
|
/** @file
@brief Implementation
@date 2014
@author
Ryan Pavlik
<[email protected]>
<http://sensics.com>
*/
// Copyright 2014 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 <ogvr/PluginKit/PluginRegistration.h>
// Library/third-party includes
// - none
// Standard includes
// - none
namespace ogvr {} // end of namespace ogvr
|
Remove unused code.
|
Remove unused code.
|
C++
|
apache-2.0
|
Armada651/OSVR-Core,feilen/OSVR-Core,godbyk/OSVR-Core,d235j/OSVR-Core,d235j/OSVR-Core,OSVR/OSVR-Core,feilen/OSVR-Core,OSVR/OSVR-Core,leemichaelRazer/OSVR-Core,d235j/OSVR-Core,feilen/OSVR-Core,godbyk/OSVR-Core,feilen/OSVR-Core,godbyk/OSVR-Core,OSVR/OSVR-Core,godbyk/OSVR-Core,OSVR/OSVR-Core,OSVR/OSVR-Core,leemichaelRazer/OSVR-Core,Armada651/OSVR-Core,OSVR/OSVR-Core,godbyk/OSVR-Core,d235j/OSVR-Core,leemichaelRazer/OSVR-Core,leemichaelRazer/OSVR-Core,leemichaelRazer/OSVR-Core,d235j/OSVR-Core,godbyk/OSVR-Core,feilen/OSVR-Core,Armada651/OSVR-Core,Armada651/OSVR-Core,Armada651/OSVR-Core
|
5248049c2fe2267e605d7d2f1dae052fc133703c
|
src/osvr/Common/PathTreeSerialization.cpp
|
src/osvr/Common/PathTreeSerialization.cpp
|
/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 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 <osvr/Common/PathTreeSerialization.h>
#include <osvr/Common/PathTreeFull.h>
#include <osvr/Common/PathElementTools.h>
#include <osvr/Common/PathNode.h>
#include <osvr/Common/ApplyPathNodeVisitor.h>
#include <osvr/Util/Verbosity.h>
// Library/third-party includes
#include <json/value.h>
#include <json/reader.h>
#include <boost/variant.hpp>
#include <boost/mpl/for_each.hpp>
// Standard includes
// - none
namespace osvr {
namespace common {
namespace {
/// @brief Class template (for specialization) allowing serialization
/// and deserialization code to be generated from the same operations
/// (ensuring keys stay in sync, etc.)
template <typename T> class PathElementSerializationHandler {
public:
template <typename Functor, typename ValType>
static void handle(Functor &, ValType &) {}
};
/// @brief Specialization for DeviceElement
template <>
class PathElementSerializationHandler<elements::DeviceElement> {
public:
template <typename Functor, typename ValType>
static void handle(Functor &f, ValType &value) {
f("device_name", value.getDeviceName());
f("server", value.getServer());
f("descriptor", value.getDescriptor());
}
};
/// @brief Specialization for AliasElement
template <>
class PathElementSerializationHandler<elements::AliasElement> {
public:
template <typename Functor, typename ValType>
static void handle(Functor &f, ValType &value) {
f("source", value.getSource());
f("priority", value.priority(),
ALIASPRIORITY_MINIMUM /* default value */);
}
};
/// @brief Functor for use with PathElementSerializationHandler, for the
/// direction PathElement->JSON
class PathElementToJSONFunctor : boost::noncopyable {
public:
PathElementToJSONFunctor(Json::Value &val) : m_val(val) {}
template <typename T>
void operator()(const char name[], T const &data, ...) {
m_val[name] = data;
}
private:
Json::Value &m_val;
};
/// @brief A PathNodeVisitor that returns a JSON object corresponding to
/// a single PathNode.
class PathNodeToJsonVisitor
: public boost::static_visitor<Json::Value> {
public:
PathNodeToJsonVisitor() : boost::static_visitor<Json::Value>() {}
Json::Value setup(PathNode const &node) {
Json::Value val{Json::objectValue};
val["path"] = getFullPath(node);
val["type"] = getTypeName(node);
return val;
}
template <typename T>
Json::Value operator()(PathNode const &node, T const &elt) {
auto ret = setup(node);
PathElementToJSONFunctor f(ret);
PathElementSerializationHandler<T>::handle(f, elt);
return ret;
}
};
Json::Value pathNodeToJson(PathNode const &node) {
PathNodeToJsonVisitor visitor;
return applyPathNodeVisitor(visitor, node);
}
/// @brief A PathNode (tree) visitor to recursively convert nodes in a
/// PathTree to JSON
class PathTreeToJsonVisitor {
public:
PathTreeToJsonVisitor(bool keepNulls)
: m_ret(Json::arrayValue), m_keepNulls(keepNulls) {}
Json::Value getResult() { return m_ret; }
void operator()(PathNode const &node) {
if (m_keepNulls || !elements::isNull(node.value())) {
// If we're keeping nulls or this isn't a null...
m_ret.append(pathNodeToJson(node));
}
// Recurse on children
node.visitConstChildren(*this);
}
private:
Json::Value m_ret;
bool m_keepNulls;
};
/// @brief Functor for use with PathElementSerializationHandler, for the
/// direction JSON->PathElement
class PathElementFromJsonFunctor : boost::noncopyable {
public:
PathElementFromJsonFunctor(Json::Value const &val) : m_val(val) {}
void operator()(const char name[], std::string &dataRef) {
m_requireName(name);
dataRef = m_val[name].asString();
}
void operator()(const char name[], bool &dataRef) {
m_requireName(name);
dataRef = m_val[name].asBool();
}
void operator()(const char name[], Json::Value &dataRef) {
m_requireName(name);
if (m_val[name].isString()) {
Json::Reader reader;
Json::Value val;
if (reader.parse(m_val[name].asString(), val)) {
dataRef = val;
}
} else {
dataRef = m_val[name];
}
}
void operator()(const char name[], bool &dataRef, bool defaultVal) {
if (m_hasName(name)) {
dataRef = m_val[name].asBool();
} else {
dataRef = defaultVal;
}
}
void operator()(const char name[], uint8_t &dataRef,
uint8_t defaultVal) {
if (m_hasName(name)) {
dataRef = static_cast<uint8_t>(m_val[name].asInt());
} else {
dataRef = defaultVal;
}
}
/// @todo add more methods here if other data types are stored
private:
void m_requireName(const char name[]) {
if (!m_hasName(name)) {
throw std::runtime_error(
"Missing JSON object member named " +
std::string(name));
}
}
bool m_hasName(const char name[]) { return m_val.isMember(name); }
Json::Value const &m_val;
};
/// @brief Functor for use with the PathElement's type list and
/// mpl::for_each, to convert from type name string to actual type and
/// load the data.
class DeserializeElementFunctor {
public:
DeserializeElementFunctor(Json::Value const &val,
elements::PathElement &elt)
: m_val(val), m_typename(val["type"].asString()), m_elt(elt) {}
/// @brief Don't try to generate an assignment operator.
DeserializeElementFunctor &
operator=(const DeserializeElementFunctor &) = delete;
template <typename T> void operator()(T const &) {
if (elements::getTypeName<T>() == m_typename) {
T value;
PathElementFromJsonFunctor functor(m_val);
PathElementSerializationHandler<T>::handle(functor, value);
m_elt = value;
}
}
private:
Json::Value const &m_val;
std::string const m_typename;
elements::PathElement &m_elt;
};
} // namespace
Json::Value pathTreeToJson(PathTree &tree, bool keepNulls) {
auto visitor = PathTreeToJsonVisitor{keepNulls};
tree.visitConstTree(visitor);
return visitor.getResult();
}
void jsonToPathTree(PathTree &tree, Json::Value nodes) {
for (auto const &node : nodes) {
elements::PathElement elt;
DeserializeElementFunctor functor{node, elt};
boost::mpl::for_each<elements::PathElement::types>(functor);
tree.getNodeByPath(node["path"].asString()).value() = elt;
}
}
} // namespace common
} // namespace osvr
|
/** @file
@brief Implementation
@date 2015
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2015 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 <osvr/Common/PathTreeSerialization.h>
#include <osvr/Common/PathTreeFull.h>
#include <osvr/Common/PathElementTools.h>
#include <osvr/Common/PathNode.h>
#include <osvr/Common/ApplyPathNodeVisitor.h>
#include <osvr/Util/Verbosity.h>
// Library/third-party includes
#include <json/value.h>
#include <json/reader.h>
#include <boost/variant.hpp>
#include <boost/mpl/for_each.hpp>
// Standard includes
#include <type_traits>
namespace osvr {
namespace common {
namespace {
/// @brief "using" statement to combine/simplify the enable_if test for
/// an element type's serialization.
template <typename Input, typename Known>
using enable_if_element_type = std::enable_if_t<
std::is_same<std::remove_const_t<Input>, Known>::value>;
/// The serializationHandler function templates allow serialization
/// and deserialization code to be generated from the same operations
/// (ensuring keys stay in sync, etc.)
/// @brief Serialization handler for DeviceElement
template <typename Functor, typename ValType>
inline enable_if_element_type<ValType, elements::DeviceElement>
serializationHandler(Functor &f, ValType &value) {
f("device_name", value.getDeviceName());
f("server", value.getServer());
f("descriptor", value.getDescriptor());
}
/// @brief Serialization handler for AliasElement
template <typename Functor, typename ValType>
inline enable_if_element_type<ValType, elements::AliasElement>
serializationHandler(Functor &f, ValType &value) {
f("source", value.getSource());
f("priority", value.priority(),
ALIASPRIORITY_MINIMUM /* default value */);
}
/// @brief Serialization handler for StringElement
template <typename Functor, typename ValType>
inline enable_if_element_type<ValType, elements::StringElement>
serializationHandler(Functor &f, ValType &value) {
/// @todo implement
}
// Serialization handlers for elements without extra data
template <typename Functor, typename ValType>
inline enable_if_element_type<ValType, elements::NullElement>
serializationHandler(Functor &, ValType &) {}
template <typename Functor, typename ValType>
inline enable_if_element_type<ValType, elements::PluginElement>
serializationHandler(Functor &, ValType &) {}
template <typename Functor, typename ValType>
inline enable_if_element_type<ValType, elements::InterfaceElement>
serializationHandler(Functor &, ValType &) {}
template <typename Functor, typename ValType>
inline enable_if_element_type<ValType, elements::SensorElement>
serializationHandler(Functor &, ValType &) {}
/// @brief Functor for use with PathElementSerializationHandler, for the
/// direction PathElement->JSON
class PathElementToJSONFunctor : boost::noncopyable {
public:
PathElementToJSONFunctor(Json::Value &val) : m_val(val) {}
template <typename T>
void operator()(const char name[], T const &data, ...) {
m_val[name] = data;
}
private:
Json::Value &m_val;
};
/// @brief A PathNodeVisitor that returns a JSON object corresponding to
/// a single PathNode.
class PathNodeToJsonVisitor
: public boost::static_visitor<Json::Value> {
public:
PathNodeToJsonVisitor() : boost::static_visitor<Json::Value>() {}
Json::Value setup(PathNode const &node) {
Json::Value val{Json::objectValue};
val["path"] = getFullPath(node);
val["type"] = getTypeName(node);
return val;
}
template <typename T>
Json::Value operator()(PathNode const &node, T const &elt) {
auto ret = setup(node);
PathElementToJSONFunctor f(ret);
serializationHandler(f, elt);
return ret;
}
};
Json::Value pathNodeToJson(PathNode const &node) {
PathNodeToJsonVisitor visitor;
return applyPathNodeVisitor(visitor, node);
}
/// @brief A PathNode (tree) visitor to recursively convert nodes in a
/// PathTree to JSON
class PathTreeToJsonVisitor {
public:
PathTreeToJsonVisitor(bool keepNulls)
: m_ret(Json::arrayValue), m_keepNulls(keepNulls) {}
Json::Value getResult() { return m_ret; }
void operator()(PathNode const &node) {
if (m_keepNulls || !elements::isNull(node.value())) {
// If we're keeping nulls or this isn't a null...
m_ret.append(pathNodeToJson(node));
}
// Recurse on children
node.visitConstChildren(*this);
}
private:
Json::Value m_ret;
bool m_keepNulls;
};
/// @brief Functor for use with PathElementSerializationHandler, for the
/// direction JSON->PathElement
class PathElementFromJsonFunctor : boost::noncopyable {
public:
PathElementFromJsonFunctor(Json::Value const &val) : m_val(val) {}
void operator()(const char name[], std::string &dataRef) {
m_requireName(name);
dataRef = m_val[name].asString();
}
void operator()(const char name[], bool &dataRef) {
m_requireName(name);
dataRef = m_val[name].asBool();
}
void operator()(const char name[], Json::Value &dataRef) {
m_requireName(name);
if (m_val[name].isString()) {
Json::Reader reader;
Json::Value val;
if (reader.parse(m_val[name].asString(), val)) {
dataRef = val;
}
} else {
dataRef = m_val[name];
}
}
void operator()(const char name[], bool &dataRef, bool defaultVal) {
if (m_hasName(name)) {
dataRef = m_val[name].asBool();
} else {
dataRef = defaultVal;
}
}
void operator()(const char name[], uint8_t &dataRef,
uint8_t defaultVal) {
if (m_hasName(name)) {
dataRef = static_cast<uint8_t>(m_val[name].asInt());
} else {
dataRef = defaultVal;
}
}
/// @todo add more methods here if other data types are stored
private:
void m_requireName(const char name[]) {
if (!m_hasName(name)) {
throw std::runtime_error(
"Missing JSON object member named " +
std::string(name));
}
}
bool m_hasName(const char name[]) { return m_val.isMember(name); }
Json::Value const &m_val;
};
/// @brief Functor for use with the PathElement's type list and
/// mpl::for_each, to convert from type name string to actual type and
/// load the data.
class DeserializeElementFunctor {
public:
DeserializeElementFunctor(Json::Value const &val,
elements::PathElement &elt)
: m_val(val), m_typename(val["type"].asString()), m_elt(elt) {}
/// @brief Don't try to generate an assignment operator.
DeserializeElementFunctor &
operator=(const DeserializeElementFunctor &) = delete;
template <typename T> void operator()(T const &) {
if (elements::getTypeName<T>() == m_typename) {
T value;
PathElementFromJsonFunctor functor(m_val);
serializationHandler(functor, value);
m_elt = value;
}
}
private:
Json::Value const &m_val;
std::string const m_typename;
elements::PathElement &m_elt;
};
} // namespace
Json::Value pathTreeToJson(PathTree &tree, bool keepNulls) {
auto visitor = PathTreeToJsonVisitor{keepNulls};
tree.visitConstTree(visitor);
return visitor.getResult();
}
void jsonToPathTree(PathTree &tree, Json::Value nodes) {
for (auto const &node : nodes) {
elements::PathElement elt;
DeserializeElementFunctor functor{node, elt};
boost::mpl::for_each<elements::PathElement::types>(functor);
tree.getNodeByPath(node["path"].asString()).value() = elt;
}
}
} // namespace common
} // namespace osvr
|
Simplify path tree serialization.
|
Simplify path tree serialization.
|
C++
|
apache-2.0
|
leemichaelRazer/OSVR-Core,leemichaelRazer/OSVR-Core,godbyk/OSVR-Core,OSVR/OSVR-Core,feilen/OSVR-Core,Armada651/OSVR-Core,OSVR/OSVR-Core,Armada651/OSVR-Core,godbyk/OSVR-Core,d235j/OSVR-Core,d235j/OSVR-Core,OSVR/OSVR-Core,godbyk/OSVR-Core,feilen/OSVR-Core,feilen/OSVR-Core,godbyk/OSVR-Core,feilen/OSVR-Core,feilen/OSVR-Core,Armada651/OSVR-Core,d235j/OSVR-Core,Armada651/OSVR-Core,OSVR/OSVR-Core,d235j/OSVR-Core,d235j/OSVR-Core,leemichaelRazer/OSVR-Core,leemichaelRazer/OSVR-Core,OSVR/OSVR-Core,OSVR/OSVR-Core,leemichaelRazer/OSVR-Core,Armada651/OSVR-Core,godbyk/OSVR-Core,godbyk/OSVR-Core
|
2f6a5f1614f4c5c80a8bad3b8827aefcfbf3ef1f
|
mha/plugins/core/identity/identity.cpp
|
mha/plugins/core/identity/identity.cpp
|
// This file is part of the HörTech Open Master Hearing Aid (openMHA)
// Copyright © 2018 HörTech gGmbH
//
// openMHA 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, version 3 of the License.
//
// openMHA 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, version 3 for more details.
//
// You should have received a copy of the GNU Affero General Public License,
// version 3 along with openMHA. If not, see <http://www.gnu.org/licenses/>.
#include "mha_plugin.hh"
class identity_t : public MHAPlugin::plugin_t<int>
{
public:
identity_t(const algo_comm_t&,const std::string&,const std::string&);
mha_wave_t* process(mha_wave_t*);
mha_spec_t* process(mha_spec_t*);
void prepare(mhaconfig_t&);
void release();
};
identity_t::identity_t(const algo_comm_t& iac,
const std::string&,
const std::string&)
: MHAPlugin::plugin_t<int>("",ac)
{
}
void identity_t::prepare(mhaconfig_t& tf)
{
}
void identity_t::release()
{
}
mha_wave_t* identity_t::process(mha_wave_t* s)
{
return s;
}
mha_spec_t* identity_t::process(mha_spec_t* s)
{
return s;
}
MHAPLUGIN_CALLBACKS(identity,identity_t,wave,wave)
MHAPLUGIN_PROC_CALLBACK(identity,identity_t,spec,spec)
MHAPLUGIN_DOCUMENTATION(identity,
"core",
"The simplest \\mha{} plugin.\n\n"
"This plugin does nothing."
)
// Local variables:
// compile-command: "make"
// c-basic-offset: 4
// End:
|
// This file is part of the HörTech Open Master Hearing Aid (openMHA)
// Copyright © 2018 HörTech gGmbH
//
// openMHA 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, version 3 of the License.
//
// openMHA 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, version 3 for more details.
//
// You should have received a copy of the GNU Affero General Public License,
// version 3 along with openMHA. If not, see <http://www.gnu.org/licenses/>.
#include "mha_plugin.hh"
class identity_t : public MHAPlugin::plugin_t<int>
{
public:
identity_t(const algo_comm_t&,const std::string&,const std::string&);
mha_wave_t* process(mha_wave_t*);
mha_spec_t* process(mha_spec_t*);
void prepare(mhaconfig_t&);
void release();
};
identity_t::identity_t(const algo_comm_t& iac,
const std::string&,
const std::string&)
: MHAPlugin::plugin_t<int>("",iac)
{
}
void identity_t::prepare(mhaconfig_t& tf)
{
}
void identity_t::release()
{
}
mha_wave_t* identity_t::process(mha_wave_t* s)
{
return s;
}
mha_spec_t* identity_t::process(mha_spec_t* s)
{
return s;
}
MHAPLUGIN_CALLBACKS(identity,identity_t,wave,wave)
MHAPLUGIN_PROC_CALLBACK(identity,identity_t,spec,spec)
MHAPLUGIN_DOCUMENTATION(identity,
"core",
"The simplest \\mha{} plugin.\n\n"
"This plugin does nothing."
)
// Local variables:
// compile-command: "make"
// c-basic-offset: 4
// End:
|
Fix typo causing warning on macOS
|
Fix typo causing warning on macOS
|
C++
|
agpl-3.0
|
HoerTech-gGmbH/openMHA,HoerTech-gGmbH/openMHA,HoerTech-gGmbH/openMHA,HoerTech-gGmbH/openMHA,HoerTech-gGmbH/openMHA,HoerTech-gGmbH/openMHA,HoerTech-gGmbH/openMHA,HoerTech-gGmbH/openMHA
|
244b9289c6c7709a0b5a47918bfa057b668a21a2
|
api/messaging_service.cc
|
api/messaging_service.cc
|
/*
* Copyright 2015 Cloudius Systems
*/
#include "messaging_service.hh"
#include "message/messaging_service.hh"
#include "api/api-doc/messaging_service.json.hh"
#include <iostream>
#include <sstream>
using namespace httpd::messaging_service_json;
using namespace net;
namespace api {
using client = rpc::protocol<serializer, messaging_verb>::client;
static const int32_t num_verb = static_cast<int32_t>(messaging_verb::UNUSED_3) + 1;
std::vector<message_counter> map_to_message_counters(
const std::unordered_map<gms::inet_address, unsigned long>& map) {
std::vector<message_counter> res;
for (auto i : map) {
res.push_back(message_counter());
res.back().ip = boost::lexical_cast<sstring>(i.first);
res.back().count = i.second;
}
return res;
}
/**
* Return a function that performs a map_reduce on messaging_service
* For each instance it calls its foreach_client method set the value
* according to a function that it gets as a parameter.
*
*/
future_json_function get_client_getter(std::function<uint64_t(const client&)> f) {
return [f](std::unique_ptr<request> req) {
using map_type = std::unordered_map<gms::inet_address, uint64_t>;
auto get_shard_map = [f](messaging_service& ms) {
std::unordered_map<gms::inet_address, unsigned long> map;
ms.foreach_client([&map, f] (const messaging_service::shard_id& id,
const messaging_service::shard_info& info) {
map[id.addr] = f(*info.rpc_client.get());
});
return map;
};
return get_messaging_service().map_reduce0(get_shard_map, map_type(), map_sum<map_type>).
then([](map_type&& map) {
return make_ready_future<json::json_return_type>(map_to_message_counters(map));
});
};
}
void set_messaging_service(http_context& ctx, routes& r) {
get_sent_messages.set(r, get_client_getter([](const client& c) {
return c.get_stats().sent_messages;
}));
get_exception_messages.set(r, get_client_getter([](const client& c) {
return c.get_stats().exception_received;
}));
get_pending_messages.set(r, get_client_getter([](const client& c) {
return c.get_stats().pending;
}));
get_respond_pending_messages.set(r, get_client_getter([](const client& c) {
return c.get_stats().wait_reply;
}));
get_dropped_messages.set(r, [](std::unique_ptr<request> req) {
shared_ptr<std::vector<uint64_t>> map = make_shared<std::vector<uint64_t>>(num_verb, 0);
return net::get_messaging_service().map_reduce([map](const uint64_t* local_map) mutable {
for (auto i = 0; i < num_verb; i++) {
(*map)[i]+= local_map[i];
}
},[](messaging_service& ms) {
return make_ready_future<const uint64_t*>(ms.get_dropped_messages());
}).then([map]{
std::vector<verb_counter> res;
for (auto i : verb_counter::verb_wrapper::all_items()) {
verb_counter c;
messaging_verb v = i; // for type safety we use messaging_verb values
if ((*map)[static_cast<int32_t>(v)] > 0) {
c.count = (*map)[static_cast<int32_t>(v)];
c.verb = i;
res.push_back(c);
}
}
return make_ready_future<json::json_return_type>(res);
});
});
}
}
|
/*
* Copyright 2015 Cloudius Systems
*/
#include "messaging_service.hh"
#include "message/messaging_service.hh"
#include "rpc/rpc_types.hh"
#include "api/api-doc/messaging_service.json.hh"
#include <iostream>
#include <sstream>
using namespace httpd::messaging_service_json;
using namespace net;
namespace api {
using shard_info = messaging_service::shard_info;
using shard_id = messaging_service::shard_id;
static const int32_t num_verb = static_cast<int32_t>(messaging_verb::UNUSED_3) + 1;
std::vector<message_counter> map_to_message_counters(
const std::unordered_map<gms::inet_address, unsigned long>& map) {
std::vector<message_counter> res;
for (auto i : map) {
res.push_back(message_counter());
res.back().ip = boost::lexical_cast<sstring>(i.first);
res.back().count = i.second;
}
return res;
}
/**
* Return a function that performs a map_reduce on messaging_service
* For each instance it calls its foreach_client method set the value
* according to a function that it gets as a parameter.
*
*/
future_json_function get_client_getter(std::function<uint64_t(const shard_info&)> f) {
return [f](std::unique_ptr<request> req) {
using map_type = std::unordered_map<gms::inet_address, uint64_t>;
auto get_shard_map = [f](messaging_service& ms) {
std::unordered_map<gms::inet_address, unsigned long> map;
ms.foreach_client([&map, f] (const shard_id& id, const shard_info& info) {
map[id.addr] = f(info);
});
return map;
};
return get_messaging_service().map_reduce0(get_shard_map, map_type(), map_sum<map_type>).
then([](map_type&& map) {
return make_ready_future<json::json_return_type>(map_to_message_counters(map));
});
};
}
void set_messaging_service(http_context& ctx, routes& r) {
get_sent_messages.set(r, get_client_getter([](const shard_info& c) {
return c.get_stats().sent_messages;
}));
get_exception_messages.set(r, get_client_getter([](const shard_info& c) {
return c.get_stats().exception_received;
}));
get_pending_messages.set(r, get_client_getter([](const shard_info& c) {
return c.get_stats().pending;
}));
get_respond_pending_messages.set(r, get_client_getter([](const shard_info& c) {
return c.get_stats().wait_reply;
}));
get_dropped_messages.set(r, [](std::unique_ptr<request> req) {
shared_ptr<std::vector<uint64_t>> map = make_shared<std::vector<uint64_t>>(num_verb, 0);
return net::get_messaging_service().map_reduce([map](const uint64_t* local_map) mutable {
for (auto i = 0; i < num_verb; i++) {
(*map)[i]+= local_map[i];
}
},[](messaging_service& ms) {
return make_ready_future<const uint64_t*>(ms.get_dropped_messages());
}).then([map]{
std::vector<verb_counter> res;
for (auto i : verb_counter::verb_wrapper::all_items()) {
verb_counter c;
messaging_verb v = i; // for type safety we use messaging_verb values
if ((*map)[static_cast<int32_t>(v)] > 0) {
c.count = (*map)[static_cast<int32_t>(v)];
c.verb = i;
res.push_back(c);
}
}
return make_ready_future<json::json_return_type>(res);
});
});
}
}
|
Use get_stats
|
api/messaging_service: Use get_stats
Hide rpc::protocol<serializer, messaging_verb>::client from it.
|
C++
|
agpl-3.0
|
tempbottle/scylla,kangkot/scylla,avikivity/scylla,asias/scylla,capturePointer/scylla,senseb/scylla,victorbriz/scylla,linearregression/scylla,shaunstanislaus/scylla,justintung/scylla,capturePointer/scylla,bowlofstew/scylla,respu/scylla,senseb/scylla,wildinto/scylla,eklitzke/scylla,phonkee/scylla,avikivity/scylla,kangkot/scylla,asias/scylla,rentongzhang/scylla,victorbriz/scylla,tempbottle/scylla,eklitzke/scylla,respu/scylla,glommer/scylla,stamhe/scylla,phonkee/scylla,asias/scylla,dwdm/scylla,aruanruan/scylla,scylladb/scylla,duarten/scylla,dwdm/scylla,rluta/scylla,stamhe/scylla,shaunstanislaus/scylla,wildinto/scylla,kangkot/scylla,scylladb/scylla,respu/scylla,bowlofstew/scylla,tempbottle/scylla,acbellini/scylla,guiquanz/scylla,aruanruan/scylla,glommer/scylla,linearregression/scylla,gwicke/scylla,acbellini/scylla,gwicke/scylla,phonkee/scylla,dwdm/scylla,raphaelsc/scylla,rluta/scylla,acbellini/scylla,raphaelsc/scylla,senseb/scylla,kjniemi/scylla,capturePointer/scylla,gwicke/scylla,rentongzhang/scylla,kjniemi/scylla,duarten/scylla,justintung/scylla,avikivity/scylla,wildinto/scylla,justintung/scylla,rluta/scylla,glommer/scylla,guiquanz/scylla,raphaelsc/scylla,duarten/scylla,guiquanz/scylla,shaunstanislaus/scylla,eklitzke/scylla,victorbriz/scylla,scylladb/scylla,scylladb/scylla,aruanruan/scylla,linearregression/scylla,stamhe/scylla,kjniemi/scylla,bowlofstew/scylla,rentongzhang/scylla
|
1492cd0eec11ec3e3a1000cc2a60700b0f690dad
|
src/plugins/designer/formeditorplugin.cpp
|
src/plugins/designer/formeditorplugin.cpp
|
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
**
**************************************************************************/
#include "formeditorplugin.h"
#include "formeditorfactory.h"
#include "formeditorw.h"
#include "formwizard.h"
#ifdef CPP_ENABLED
# include "formclasswizard.h"
# include <cppeditor/cppeditorconstants.h>
#endif
#include "designerconstants.h"
#include <coreplugin/icore.h>
#include <coreplugin/mimedatabase.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/uniqueidmanager.h>
#include <QtCore/QtPlugin>
#include <QtCore/QDebug>
#ifdef CPP_ENABLED
# include <QtGui/QAction>
# include <QtGui/QWizard>
# include <QtGui/QMainWindow>
#endif
using namespace Designer::Internal;
using namespace Designer::Constants;
FormEditorPlugin::FormEditorPlugin() :
m_factory(0),
m_formWizard(0),
m_formClassWizard(0)
{
}
FormEditorPlugin::~FormEditorPlugin()
{
if (m_factory)
removeObject(m_factory);
if (m_formWizard)
removeObject(m_formWizard);
if (m_formClassWizard)
removeObject(m_formClassWizard);
delete m_factory;
delete m_formWizard;
delete m_formClassWizard;
FormEditorW::deleteInstance();
}
////////////////////////////////////////////////////
//
// INHERITED FROM ExtensionSystem::Plugin
//
////////////////////////////////////////////////////
bool FormEditorPlugin::initialize(const QStringList &arguments, QString *error)
{
Q_UNUSED(arguments);
Q_UNUSED(error);
Core::ICore *core = Core::ICore::instance();
if (!core->mimeDatabase()->addMimeTypes(QLatin1String(":/formeditor/Designer.mimetypes.xml"), error))
return false;
if (!initializeTemplates(error))
return false;
const int uid = core->uniqueIDManager()->uniqueIdentifier(QLatin1String(C_FORMEDITOR));
const QList<int> context = QList<int>() << uid;
m_factory = new FormEditorFactory;
addObject(m_factory);
FormEditorW::ensureInitStage(FormEditorW::RegisterPlugins);
error->clear();
return true;
}
void FormEditorPlugin::extensionsInitialized()
{
}
////////////////////////////////////////////////////
//
// PRIVATE methods
//
////////////////////////////////////////////////////
bool FormEditorPlugin::initializeTemplates(QString *error)
{
Q_UNUSED(error);
FormWizard::BaseFileWizardParameters wizardParameters(Core::IWizard::FileWizard);
wizardParameters.setCategory(QLatin1String("Qt"));
wizardParameters.setTrCategory(tr("Qt"));
const QString formFileType = QLatin1String(Constants::FORM_FILE_TYPE);
wizardParameters.setName(tr("Qt Designer Form"));
wizardParameters.setDescription(tr("This creates a new Qt Designer form file."));
m_formWizard = new FormWizard(wizardParameters, this);
addObject(m_formWizard);
#ifdef CPP_ENABLED
wizardParameters.setKind(Core::IWizard::ClassWizard);
wizardParameters.setName(tr("Qt Designer Form Class"));
wizardParameters.setDescription(tr("This creates a new Qt Designer form class."));
m_formClassWizard = new FormClassWizard(wizardParameters, this);
addObject(m_formClassWizard);
#endif
return true;
}
Q_EXPORT_PLUGIN(FormEditorPlugin)
|
/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Qt Software Information ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at [email protected].
**
**************************************************************************/
#include "formeditorplugin.h"
#include "formeditorfactory.h"
#include "formeditorw.h"
#include "formwizard.h"
#ifdef CPP_ENABLED
# include "formclasswizard.h"
# include <cppeditor/cppeditorconstants.h>
#endif
#include "designerconstants.h"
#include <coreplugin/icore.h>
#include <coreplugin/mimedatabase.h>
#include <coreplugin/coreconstants.h>
#include <coreplugin/uniqueidmanager.h>
#include <QtCore/QtPlugin>
#include <QtCore/QDebug>
#include <QtCore/QProcess>
#ifdef CPP_ENABLED
# include <QtGui/QAction>
# include <QtGui/QWizard>
# include <QtGui/QMainWindow>
#endif
using namespace Designer::Internal;
using namespace Designer::Constants;
FormEditorPlugin::FormEditorPlugin() :
m_factory(0),
m_formWizard(0),
m_formClassWizard(0)
{
}
FormEditorPlugin::~FormEditorPlugin()
{
if (m_factory)
removeObject(m_factory);
if (m_formWizard)
removeObject(m_formWizard);
if (m_formClassWizard)
removeObject(m_formClassWizard);
delete m_factory;
delete m_formWizard;
delete m_formClassWizard;
FormEditorW::deleteInstance();
}
////////////////////////////////////////////////////
//
// INHERITED FROM ExtensionSystem::Plugin
//
////////////////////////////////////////////////////
bool FormEditorPlugin::initialize(const QStringList &arguments, QString *error)
{
Q_UNUSED(arguments);
Q_UNUSED(error);
Core::ICore *core = Core::ICore::instance();
if (!core->mimeDatabase()->addMimeTypes(QLatin1String(":/formeditor/Designer.mimetypes.xml"), error))
return false;
if (!initializeTemplates(error))
return false;
const int uid = core->uniqueIDManager()->uniqueIdentifier(QLatin1String(C_FORMEDITOR));
const QList<int> context = QList<int>() << uid;
m_factory = new FormEditorFactory;
addObject(m_factory);
if (qgetenv("KDE_SESSION_VERSION") == QByteArray("4")) {
// KDE 4, possibly dangerous...
// KDE 4.2.0 had a nasty bug, which resulted in the File/Open Dialog crashing
// so check for that an fully load the plugins
QProcess proc;
proc.start("kde4-config", QStringList() << "--version");
proc.waitForFinished();
QString output = proc.readAll();
if (output.contains("KDE: 4.2.0"))
FormEditorW::ensureInitStage(FormEditorW::FullyInitialized);
} else {
FormEditorW::ensureInitStage(FormEditorW::RegisterPlugins);
}
error->clear();
return true;
}
void FormEditorPlugin::extensionsInitialized()
{
}
////////////////////////////////////////////////////
//
// PRIVATE methods
//
////////////////////////////////////////////////////
bool FormEditorPlugin::initializeTemplates(QString *error)
{
Q_UNUSED(error);
FormWizard::BaseFileWizardParameters wizardParameters(Core::IWizard::FileWizard);
wizardParameters.setCategory(QLatin1String("Qt"));
wizardParameters.setTrCategory(tr("Qt"));
const QString formFileType = QLatin1String(Constants::FORM_FILE_TYPE);
wizardParameters.setName(tr("Qt Designer Form"));
wizardParameters.setDescription(tr("This creates a new Qt Designer form file."));
m_formWizard = new FormWizard(wizardParameters, this);
addObject(m_formWizard);
#ifdef CPP_ENABLED
wizardParameters.setKind(Core::IWizard::ClassWizard);
wizardParameters.setName(tr("Qt Designer Form Class"));
wizardParameters.setDescription(tr("This creates a new Qt Designer form class."));
m_formClassWizard = new FormClassWizard(wizardParameters, this);
addObject(m_formClassWizard);
#endif
return true;
}
Q_EXPORT_PLUGIN(FormEditorPlugin)
|
Work around problems with kde 4.2.0 by checking for that exact version.
|
Work around problems with kde 4.2.0 by checking for that exact version.
Need to remove that at one point, but having someone report it one day
after we tried to remove this, means not now.
|
C++
|
lgpl-2.1
|
KDE/android-qt-creator,bakaiadam/collaborative_qt_creator,amyvmiwei/qt-creator,malikcjm/qtcreator,yinyunqiao/qtcreator,AltarBeastiful/qt-creator,yinyunqiao/qtcreator,darksylinc/qt-creator,hdweiss/qt-creator-visualizer,omniacreator/qtcreator,dmik/qt-creator-os2,syntheticpp/qt-creator,jonnor/qt-creator,KDAB/KDAB-Creator,maui-packages/qt-creator,dmik/qt-creator-os2,KDAB/KDAB-Creator,duythanhphan/qt-creator,enricoros/k-qt-creator-inspector,darksylinc/qt-creator,amyvmiwei/qt-creator,kuba1/qtcreator,ostash/qt-creator-i18n-uk,malikcjm/qtcreator,farseerri/git_code,hdweiss/qt-creator-visualizer,ostash/qt-creator-i18n-uk,bakaiadam/collaborative_qt_creator,dmik/qt-creator-os2,duythanhphan/qt-creator,martyone/sailfish-qtcreator,colede/qtcreator,KDE/android-qt-creator,ostash/qt-creator-i18n-uk,AltarBeastiful/qt-creator,enricoros/k-qt-creator-inspector,Distrotech/qtcreator,azat/qtcreator,kuba1/qtcreator,KDE/android-qt-creator,duythanhphan/qt-creator,martyone/sailfish-qtcreator,malikcjm/qtcreator,pcacjr/qt-creator,AltarBeastiful/qt-creator,hdweiss/qt-creator-visualizer,xianian/qt-creator,renatofilho/QtCreator,yinyunqiao/qtcreator,dmik/qt-creator-os2,Distrotech/qtcreator,darksylinc/qt-creator,farseerri/git_code,danimo/qt-creator,jonnor/qt-creator,martyone/sailfish-qtcreator,sandsmark/qtcreator-minimap,danimo/qt-creator,enricoros/k-qt-creator-inspector,richardmg/qtcreator,duythanhphan/qt-creator,maui-packages/qt-creator,ostash/qt-creator-i18n-uk,maui-packages/qt-creator,amyvmiwei/qt-creator,danimo/qt-creator,sandsmark/qtcreator-minimap,malikcjm/qtcreator,ostash/qt-creator-i18n-uk,colede/qtcreator,dmik/qt-creator-os2,richardmg/qtcreator,syntheticpp/qt-creator,renatofilho/QtCreator,pcacjr/qt-creator,duythanhphan/qt-creator,ostash/qt-creator-i18n-uk,yinyunqiao/qtcreator,martyone/sailfish-qtcreator,renatofilho/QtCreator,maui-packages/qt-creator,KDAB/KDAB-Creator,KDE/android-qt-creator,richardmg/qtcreator,colede/qtcreator,jonnor/qt-creator,kuba1/qtcreator,maui-packages/qt-creator,yinyunqiao/qtcreator,KDAB/KDAB-Creator,enricoros/k-qt-creator-inspector,bakaiadam/collaborative_qt_creator,amyvmiwei/qt-creator,sandsmark/qtcreator-minimap,amyvmiwei/qt-creator,duythanhphan/qt-creator,farseerri/git_code,xianian/qt-creator,AltarBeastiful/qt-creator,azat/qtcreator,bakaiadam/collaborative_qt_creator,danimo/qt-creator,azat/qtcreator,sandsmark/qtcreator-minimap,darksylinc/qt-creator,Distrotech/qtcreator,azat/qtcreator,amyvmiwei/qt-creator,omniacreator/qtcreator,KDE/android-qt-creator,AltarBeastiful/qt-creator,Distrotech/qtcreator,colede/qtcreator,darksylinc/qt-creator,pcacjr/qt-creator,kuba1/qtcreator,malikcjm/qtcreator,hdweiss/qt-creator-visualizer,maui-packages/qt-creator,danimo/qt-creator,kuba1/qtcreator,jonnor/qt-creator,hdweiss/qt-creator-visualizer,AltarBeastiful/qt-creator,omniacreator/qtcreator,farseerri/git_code,renatofilho/QtCreator,danimo/qt-creator,colede/qtcreator,jonnor/qt-creator,syntheticpp/qt-creator,Distrotech/qtcreator,syntheticpp/qt-creator,amyvmiwei/qt-creator,farseerri/git_code,dmik/qt-creator-os2,omniacreator/qtcreator,xianian/qt-creator,darksylinc/qt-creator,xianian/qt-creator,KDE/android-qt-creator,farseerri/git_code,danimo/qt-creator,syntheticpp/qt-creator,dmik/qt-creator-os2,AltarBeastiful/qt-creator,colede/qtcreator,colede/qtcreator,KDAB/KDAB-Creator,maui-packages/qt-creator,azat/qtcreator,kuba1/qtcreator,pcacjr/qt-creator,ostash/qt-creator-i18n-uk,KDE/android-qt-creator,richardmg/qtcreator,duythanhphan/qt-creator,richardmg/qtcreator,jonnor/qt-creator,renatofilho/QtCreator,Distrotech/qtcreator,xianian/qt-creator,syntheticpp/qt-creator,pcacjr/qt-creator,yinyunqiao/qtcreator,KDAB/KDAB-Creator,hdweiss/qt-creator-visualizer,yinyunqiao/qtcreator,martyone/sailfish-qtcreator,omniacreator/qtcreator,darksylinc/qt-creator,kuba1/qtcreator,richardmg/qtcreator,pcacjr/qt-creator,farseerri/git_code,Distrotech/qtcreator,xianian/qt-creator,xianian/qt-creator,amyvmiwei/qt-creator,xianian/qt-creator,enricoros/k-qt-creator-inspector,darksylinc/qt-creator,kuba1/qtcreator,kuba1/qtcreator,martyone/sailfish-qtcreator,syntheticpp/qt-creator,danimo/qt-creator,AltarBeastiful/qt-creator,enricoros/k-qt-creator-inspector,azat/qtcreator,pcacjr/qt-creator,martyone/sailfish-qtcreator,bakaiadam/collaborative_qt_creator,martyone/sailfish-qtcreator,danimo/qt-creator,xianian/qt-creator,bakaiadam/collaborative_qt_creator,malikcjm/qtcreator,malikcjm/qtcreator,omniacreator/qtcreator,sandsmark/qtcreator-minimap,bakaiadam/collaborative_qt_creator,sandsmark/qtcreator-minimap,richardmg/qtcreator,omniacreator/qtcreator,martyone/sailfish-qtcreator,renatofilho/QtCreator,farseerri/git_code,enricoros/k-qt-creator-inspector,KDE/android-qt-creator
|
b8121d9769d16edb3154f3d1f999f4ddea61d7a6
|
cpp/tests/systemintegration-tests/ProviderReregistrationControllerTest.cpp
|
cpp/tests/systemintegration-tests/ProviderReregistrationControllerTest.cpp
|
/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <chrono>
#include "joynr/JoynrClusterControllerRuntime.h"
#include "joynr/Settings.h"
#include "joynr/SystemServicesSettings.h"
#include "joynr/system/ProviderReregistrationControllerProxy.h"
#include "utils/TestLibJoynrWebSocketRuntime.h"
using namespace ::testing;
using namespace joynr;
TEST(ProviderReregistrationControllerTest, queryProviderReregistrationControllerSucceedsOnCCRuntime)
{
auto integrationSettings = std::make_unique<Settings>("test-resources/MqttSystemIntegrationTest1.settings");
joynr::SystemServicesSettings systemServiceSettings(*integrationSettings);
const std::string domain(systemServiceSettings.getDomain());
auto runtime = std::make_shared<JoynrClusterControllerRuntime>(std::move(integrationSettings));
runtime->init();
runtime->start();
auto providerReregistrationControllerProxyBuilder = runtime->createProxyBuilder<joynr::system::ProviderReregistrationControllerProxy>(domain);
auto providerReregistrationControllerProxy = providerReregistrationControllerProxyBuilder->build();
Semaphore finishedSemaphore;
providerReregistrationControllerProxy->triggerGlobalProviderReregistrationAsync([&finishedSemaphore]() { finishedSemaphore.notify(); }, nullptr);
finishedSemaphore.waitFor(std::chrono::seconds(2));
runtime->stop();
runtime = nullptr;
}
TEST(ProviderReregistrationControllerTest, queryProviderReregistrationControllerSucceedsOnWsRuntime)
{
auto integrationSettings = std::make_unique<Settings>("test-resources/MqttSystemIntegrationTest1.settings");
joynr::SystemServicesSettings systemServiceSettings(*integrationSettings);
const std::string domain(systemServiceSettings.getDomain());
auto ccRuntime = std::make_shared<JoynrClusterControllerRuntime>(std::move(integrationSettings));
ccRuntime->init();
ccRuntime->start();
auto wsRuntimeSettings = std::make_unique<Settings>("test-resources/libjoynrSystemIntegration1.settings");
auto wsRuntime = std::make_shared<TestLibJoynrWebSocketRuntime>(std::move(wsRuntimeSettings), nullptr);
wsRuntime->connect(std::chrono::seconds(2));
auto providerReregistrationControllerProxyBuilder = wsRuntime->createProxyBuilder<joynr::system::ProviderReregistrationControllerProxy>(domain);
auto providerReregistrationControllerProxy = providerReregistrationControllerProxyBuilder->build();
Semaphore finishedSemaphore;
providerReregistrationControllerProxy->triggerGlobalProviderReregistrationAsync([&finishedSemaphore]() { finishedSemaphore.notify(); }, [](const joynr::exceptions::JoynrRuntimeException&) { FAIL(); });
finishedSemaphore.waitFor(std::chrono::seconds(2));
wsRuntime = nullptr;
ccRuntime->stop();
ccRuntime = nullptr;
}
|
/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* 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.
* #L%
*/
#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <chrono>
#include "joynr/JoynrClusterControllerRuntime.h"
#include "joynr/Settings.h"
#include "joynr/SystemServicesSettings.h"
#include "joynr/system/ProviderReregistrationControllerProxy.h"
#include "utils/TestLibJoynrWebSocketRuntime.h"
using namespace ::testing;
using namespace joynr;
TEST(ProviderReregistrationControllerTest, queryProviderReregistrationControllerSucceedsOnCCRuntime)
{
auto integrationSettings = std::make_unique<Settings>("test-resources/MqttSystemIntegrationTest1.settings");
joynr::SystemServicesSettings systemServiceSettings(*integrationSettings);
const std::string domain(systemServiceSettings.getDomain());
auto runtime = std::make_shared<JoynrClusterControllerRuntime>(std::move(integrationSettings));
runtime->init();
runtime->start();
auto providerReregistrationControllerProxyBuilder = runtime->createProxyBuilder<joynr::system::ProviderReregistrationControllerProxy>(domain);
auto providerReregistrationControllerProxy = providerReregistrationControllerProxyBuilder->build();
Semaphore finishedSemaphore;
providerReregistrationControllerProxy->triggerGlobalProviderReregistrationAsync([&finishedSemaphore]() { finishedSemaphore.notify(); }, nullptr);
EXPECT_TRUE(finishedSemaphore.waitFor(std::chrono::seconds(10)));
runtime->stop();
runtime = nullptr;
}
TEST(ProviderReregistrationControllerTest, queryProviderReregistrationControllerSucceedsOnWsRuntime)
{
auto integrationSettings = std::make_unique<Settings>("test-resources/MqttSystemIntegrationTest1.settings");
joynr::SystemServicesSettings systemServiceSettings(*integrationSettings);
const std::string domain(systemServiceSettings.getDomain());
auto ccRuntime = std::make_shared<JoynrClusterControllerRuntime>(std::move(integrationSettings));
ccRuntime->init();
ccRuntime->start();
auto wsRuntimeSettings = std::make_unique<Settings>("test-resources/libjoynrSystemIntegration1.settings");
auto wsRuntime = std::make_shared<TestLibJoynrWebSocketRuntime>(std::move(wsRuntimeSettings), nullptr);
ASSERT_TRUE(wsRuntime->connect(std::chrono::seconds(2)));
auto providerReregistrationControllerProxyBuilder = wsRuntime->createProxyBuilder<joynr::system::ProviderReregistrationControllerProxy>(domain);
auto providerReregistrationControllerProxy = providerReregistrationControllerProxyBuilder->build();
Semaphore finishedSemaphore;
providerReregistrationControllerProxy->triggerGlobalProviderReregistrationAsync([&finishedSemaphore]() { finishedSemaphore.notify(); }, [](const joynr::exceptions::JoynrRuntimeException&) { FAIL(); });
EXPECT_TRUE(finishedSemaphore.waitFor(std::chrono::seconds(10)));
wsRuntime = nullptr;
ccRuntime->stop();
ccRuntime = nullptr;
}
|
fix sporadical failing test for ProviderReregistrationController Test
|
[C++] fix sporadical failing test for ProviderReregistrationController Test
- increase the timeout to be sure that registration is done before
notification
Change-Id: I6928125734642f6578bbe774bddaee4cbca41f51
|
C++
|
apache-2.0
|
bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr,bmwcarit/joynr
|
5869ad582a90b15276f0810a680ebd158bafa2c3
|
app/demo/src/lr_main.cpp
|
app/demo/src/lr_main.cpp
|
#include "lr_app.hpp"
#include <gflags/gflags.h>
#include <glog/logging.h>
DEFINE_int32(num_app_threads, 1, "Number of app threads in this client");
DEFINE_string(input_dir, "", "Data location");
DEFINE_double(learning_rate, 1.0, "Learning rate.");
DEFINE_double(lambda, 1000, "L2 regularization strength.");
DEFINE_int32(batch_size, 100, "mini batch size");
DEFINE_int32(w_staleness, 0, "staleness for w table");
int main(int argc, char *argv[]) {
google::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
LRAppConfig config;
config.input_dir = FLAGS_input_dir;
config.learning_rate = FLAGS_learning_rate;
config.lambda = FLAGS_lambda;
config.batch_size = FLAGS_batch_size;
config.w_staleness = FLAGS_w_staleness;
LRApp lrapp(config);
lrapp.Run(FLAGS_num_app_threads);
return 0;
}
|
#include "lr_app.hpp"
#include <gflags/gflags.h>
#include <glog/logging.h>
DEFINE_string(input_dir, "", "Data location");
DEFINE_double(learning_rate, 1.0, "Learning rate.");
DEFINE_double(lambda, 1000, "L2 regularization strength.");
DEFINE_int32(batch_size, 100, "mini batch size");
DEFINE_int32(w_staleness, 0, "staleness for w table");
int main(int argc, char *argv[]) {
google::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
LRAppConfig config;
config.input_dir = FLAGS_input_dir;
config.learning_rate = FLAGS_learning_rate;
config.lambda = FLAGS_lambda;
config.batch_size = FLAGS_batch_size;
config.w_staleness = FLAGS_w_staleness;
LRApp lrapp(config);
lrapp.Run(FLAGS_num_app_threads);
return 0;
}
|
Fix gflags bug.
|
Fix gflags bug.
|
C++
|
bsd-3-clause
|
petuum/public,petuum/public,petuum/public,petuum/public,petuum/public
|
4c6b9035dd349e613fe5ee66a16b82b6464a353a
|
m-keyboard/mkeyboardsettings.cpp
|
m-keyboard/mkeyboardsettings.cpp
|
/* * This file is part of m-keyboard *
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* Contact: Nokia Corporation ([email protected])
*
* If you have questions regarding the use of this file, please contact
* Nokia at [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 version 2.1 as published by the Free Software Foundation
* and appearing in the file LICENSE.LGPL included in the packaging
* of this file.
*/
#include "mkeyboardsettings.h"
#include "mkeyboardsettingswidget.h"
#include "keyboarddata.h"
#include <QObject>
#include <QGraphicsWidget>
#include <QDir>
#include <QFileInfo>
#include <QDebug>
namespace {
const QString SettingsImErrorCorrection("/meegotouch/inputmethods/virtualkeyboard/correctionenabled");
const QString SettingsImCorrectionSpace("/meegotouch/inputmethods/virtualkeyboard/correctwithspace");
const QString InputMethodLayouts("/meegotouch/inputmethods/virtualkeyboard/layouts");
const QString VKBConfigurationPath("/usr/share/meegotouch/virtual-keyboard/layouts/");
const QString VKBLayoutsFilterRule("*.xml");
const QString VKBLayoutsIgnoreRules("number|test|customer|default"); // use as regexp to ignore number, test, customer and default layouts
};
MKeyboardSettings::MKeyboardSettings()
: keyboardErrorCorrectionConf(SettingsImErrorCorrection),
keyboardCorrectionSpaceConf(SettingsImCorrectionSpace),
selectedKeyboardsConf(InputMethodLayouts)
{
readAvailableKeyboards();
connect(&keyboardErrorCorrectionConf, SIGNAL(valueChanged()),
this, SIGNAL(errorCorrectionChanged()));
connect(&keyboardCorrectionSpaceConf, SIGNAL(valueChanged()),
this, SIGNAL(correctionSpaceChanged()));
connect(&selectedKeyboardsConf, SIGNAL(valueChanged()),
this, SIGNAL(selectedKeyboardsChanged()));
}
MKeyboardSettings::~MKeyboardSettings()
{
}
QGraphicsWidget *MKeyboardSettings::createContentWidget(QGraphicsWidget *parent)
{
// the pointer of returned QGraphicsWidget is owned by the caller,
// so we just always create a new containerWidget.
return new MKeyboardSettingsWidget(this, parent);
}
QString MKeyboardSettings::title()
{
//% "Virtual keyboards"
return qtTrId("qtn_txts_virtual_keyboards");;
}
QString MKeyboardSettings::icon()
{
return "";
}
void MKeyboardSettings::readAvailableKeyboards()
{
availableKeyboardInfos.clear();
// available keyboard layouts are determined by xml layouts that can be found
const QDir layoutsDir(VKBConfigurationPath, VKBLayoutsFilterRule);
QRegExp ignoreExp(VKBLayoutsIgnoreRules, Qt::CaseInsensitive);
foreach (QFileInfo keyboardFileInfo, layoutsDir.entryInfoList()) {
if (keyboardFileInfo.fileName().contains(ignoreExp))
continue;
KeyboardData keyboard;
if (keyboard.loadNokiaKeyboard(keyboardFileInfo.fileName())) {
if (keyboard.layoutFile().isEmpty()
|| keyboard.language().isEmpty()
|| keyboard.title().isEmpty())
continue;
bool duplicated = false;
foreach (const KeyboardInfo &info, availableKeyboardInfos) {
if (info.layoutFile == keyboard.layoutFile()
|| info.title == keyboard.title()) {
// strip duplicated layout which has the same layout/title
duplicated = true;
break;
}
}
if (!duplicated) {
KeyboardInfo keyboardInfo;
keyboardInfo.layoutFile = keyboard.layoutFile();
keyboardInfo.title = keyboard.title();
availableKeyboardInfos.append(keyboardInfo);
}
}
}
}
QMap<QString, QString> MKeyboardSettings::availableKeyboards() const
{
QMap<QString, QString> keyboards;
foreach (const KeyboardInfo &keyboardInfo, availableKeyboardInfos) {
keyboards.insert(keyboardInfo.layoutFile, keyboardInfo.title);
}
return keyboards;
}
QMap<QString, QString> MKeyboardSettings::selectedKeyboards() const
{
QMap<QString, QString> keyboards;
foreach (const QString layoutFile, selectedKeyboardsConf.value().toStringList()) {
keyboards.insert(layoutFile, keyboardTitle(layoutFile));
}
return keyboards;
}
void MKeyboardSettings::setSelectedKeyboards(const QStringList &keyboardLayouts)
{
selectedKeyboardsConf.set(keyboardLayouts);
}
QString MKeyboardSettings::keyboardTitle(const QString &layoutFile) const
{
QString title;
foreach (const KeyboardInfo &keyboardInfo, availableKeyboardInfos) {
if (keyboardInfo.layoutFile == layoutFile) {
title = keyboardInfo.title;
break;
}
}
return title;
}
QString MKeyboardSettings::keyboardLayoutFile(const QString &title) const
{
QString layoutFile;
foreach (const KeyboardInfo &keyboardInfo, availableKeyboardInfos) {
if (keyboardInfo.title == title) {
layoutFile = keyboardInfo.layoutFile;
break;
}
}
return layoutFile;
}
bool MKeyboardSettings::errorCorrection() const
{
return keyboardErrorCorrectionConf.value().toBool();
}
void MKeyboardSettings::setErrorCorrection(bool enabled)
{
keyboardErrorCorrectionConf.set(enabled);
}
bool MKeyboardSettings::correctionSpace() const
{
return keyboardCorrectionSpaceConf.value().toBool();
}
void MKeyboardSettings::setCorrectionSpace(bool enabled)
{
keyboardCorrectionSpaceConf.set(enabled);
}
|
/* * This file is part of m-keyboard *
*
* Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* Contact: Nokia Corporation ([email protected])
*
* If you have questions regarding the use of this file, please contact
* Nokia at [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 version 2.1 as published by the Free Software Foundation
* and appearing in the file LICENSE.LGPL included in the packaging
* of this file.
*/
#include "mkeyboardsettings.h"
#include "mkeyboardsettingswidget.h"
#include "keyboarddata.h"
#include <QObject>
#include <QGraphicsWidget>
#include <QDir>
#include <QFileInfo>
#include <QDebug>
namespace {
const QString SettingsImErrorCorrection("/meegotouch/inputmethods/virtualkeyboard/correctionenabled");
const QString SettingsImCorrectionSpace("/meegotouch/inputmethods/virtualkeyboard/correctwithspace");
const QString InputMethodLayouts("/meegotouch/inputmethods/virtualkeyboard/layouts");
const QString VKBConfigurationPath("/usr/share/meegotouch/virtual-keyboard/layouts/");
const QString VKBLayoutsFilterRule("*.xml");
const QString VKBLayoutsIgnoreRules("number|test|customer|default"); // use as regexp to ignore number, test, customer and default layouts
const QString ChineseVKBConfigurationPath("/usr/share/meegotouch/virtual-keyboard/layouts/chinese");
};
MKeyboardSettings::MKeyboardSettings()
: keyboardErrorCorrectionConf(SettingsImErrorCorrection),
keyboardCorrectionSpaceConf(SettingsImCorrectionSpace),
selectedKeyboardsConf(InputMethodLayouts)
{
readAvailableKeyboards();
connect(&keyboardErrorCorrectionConf, SIGNAL(valueChanged()),
this, SIGNAL(errorCorrectionChanged()));
connect(&keyboardCorrectionSpaceConf, SIGNAL(valueChanged()),
this, SIGNAL(correctionSpaceChanged()));
connect(&selectedKeyboardsConf, SIGNAL(valueChanged()),
this, SIGNAL(selectedKeyboardsChanged()));
}
MKeyboardSettings::~MKeyboardSettings()
{
}
QGraphicsWidget *MKeyboardSettings::createContentWidget(QGraphicsWidget *parent)
{
// the pointer of returned QGraphicsWidget is owned by the caller,
// so we just always create a new containerWidget.
return new MKeyboardSettingsWidget(this, parent);
}
QString MKeyboardSettings::title()
{
//% "Virtual keyboards"
return qtTrId("qtn_txts_virtual_keyboards");;
}
QString MKeyboardSettings::icon()
{
return "";
}
void MKeyboardSettings::readAvailableKeyboards()
{
availableKeyboardInfos.clear();
QList<QDir> dirs;
dirs << QDir(VKBConfigurationPath, VKBLayoutsFilterRule);
// TO BE REMOVED
// Add Chinese input method layout directories here to allow our setting
// could manage Chinese IM layouts. This is a workaround, will be removed later.
dirs << QDir(ChineseVKBConfigurationPath, VKBLayoutsFilterRule);
QRegExp ignoreExp(VKBLayoutsIgnoreRules, Qt::CaseInsensitive);
foreach (const QDir &dir, dirs) {
// available keyboard layouts are determined by xml layouts that can be found
foreach (const QFileInfo &keyboardFileInfo, dir.entryInfoList()) {
if (keyboardFileInfo.fileName().contains(ignoreExp))
continue;
KeyboardData keyboard;
if (keyboard.loadNokiaKeyboard(keyboardFileInfo.filePath())) {
if (keyboard.layoutFile().isEmpty()
|| keyboard.language().isEmpty()
|| keyboard.title().isEmpty())
continue;
bool duplicated = false;
foreach (const KeyboardInfo &info, availableKeyboardInfos) {
if (info.layoutFile == keyboard.layoutFile()
|| info.title == keyboard.title()) {
// strip duplicated layout which has the same layout/title
duplicated = true;
break;
}
}
if (!duplicated) {
KeyboardInfo keyboardInfo;
// strip the path, only save the layout file name.
keyboardInfo.layoutFile = QFileInfo(keyboard.layoutFile()).fileName();
keyboardInfo.title = keyboard.title();
availableKeyboardInfos.append(keyboardInfo);
}
}
}
}
}
QMap<QString, QString> MKeyboardSettings::availableKeyboards() const
{
QMap<QString, QString> keyboards;
foreach (const KeyboardInfo &keyboardInfo, availableKeyboardInfos) {
keyboards.insert(keyboardInfo.layoutFile, keyboardInfo.title);
}
return keyboards;
}
QMap<QString, QString> MKeyboardSettings::selectedKeyboards() const
{
QMap<QString, QString> keyboards;
foreach (const QString layoutFile, selectedKeyboardsConf.value().toStringList()) {
keyboards.insert(layoutFile, keyboardTitle(layoutFile));
}
return keyboards;
}
void MKeyboardSettings::setSelectedKeyboards(const QStringList &keyboardLayouts)
{
selectedKeyboardsConf.set(keyboardLayouts);
}
QString MKeyboardSettings::keyboardTitle(const QString &layoutFile) const
{
QString title;
foreach (const KeyboardInfo &keyboardInfo, availableKeyboardInfos) {
if (keyboardInfo.layoutFile == layoutFile) {
title = keyboardInfo.title;
break;
}
}
return title;
}
QString MKeyboardSettings::keyboardLayoutFile(const QString &title) const
{
QString layoutFile;
foreach (const KeyboardInfo &keyboardInfo, availableKeyboardInfos) {
if (keyboardInfo.title == title) {
layoutFile = keyboardInfo.layoutFile;
break;
}
}
return layoutFile;
}
bool MKeyboardSettings::errorCorrection() const
{
return keyboardErrorCorrectionConf.value().toBool();
}
void MKeyboardSettings::setErrorCorrection(bool enabled)
{
keyboardErrorCorrectionConf.set(enabled);
}
bool MKeyboardSettings::correctionSpace() const
{
return keyboardCorrectionSpaceConf.value().toBool();
}
void MKeyboardSettings::setCorrectionSpace(bool enabled)
{
keyboardCorrectionSpaceConf.set(enabled);
}
|
support reading Chinese input method layout files for settings
|
Changes: support reading Chinese input method layout files for settings
RevBy: Pekka Vuorela
Details: Setting widget should read the Chinese input method layou files
and display them together with our latin layouts.
|
C++
|
bsd-3-clause
|
RHawkeyed/plugins,KDE/plasma-maliit-plugins,develersrl/maliit-demo-qml,RHawkeyed/plugins,RHawkeyed/plugins,KDE/plasma-maliit-plugins,KDE/plasma-maliit-plugins,RHawkeyed/plugins,maliit/plugins,maliit/plugins,develersrl/maliit-demo-qml,RHawkeyed/plugins,KDE/plasma-maliit-plugins,develersrl/maliit-demo-qml,maliit/plugins,maliit/plugins,develersrl/maliit-demo-qml
|
c301ce440f2a29eabcb1937f987f1b8d0d60c578
|
Modules/OpenIGTLink/Filters/mitkImageToIGTLMessageFilter.cpp
|
Modules/OpenIGTLink/Filters/mitkImageToIGTLMessageFilter.cpp
|
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "mitkImageToIGTLMessageFilter.h"
#include "mitkImageReadAccessor.h"
#include "itkByteSwapper.h"
#include "igtlImageMessage.h"
mitk::ImageToIGTLMessageFilter::ImageToIGTLMessageFilter()
{
mitk::IGTLMessage::Pointer output = mitk::IGTLMessage::New();
this->SetNumberOfRequiredOutputs(1);
this->SetNthOutput(0, output.GetPointer());
this->SetNumberOfRequiredInputs(1);
}
void mitk::ImageToIGTLMessageFilter::GenerateData()
{
// MITK_INFO << "ImageToIGTLMessageFilter.GenerateData()";
for (unsigned int i = 0; i < this->GetNumberOfIndexedOutputs(); ++i)
{
mitk::IGTLMessage* output = this->GetOutput(i);
assert(output);
const mitk::Image* img = this->GetInput(i);
int dims = img->GetDimension();
int chn = img->GetNumberOfChannels();
if (dims < 1)
{
MITK_ERROR << "Can not handle dimensionless images";
}
if (dims > 3)
{
MITK_ERROR << "Can not handle more than three dimensions";
continue;
}
if (chn != 1)
{
MITK_ERROR << "Can not handle anything but one channel. Image contained " << chn;
continue;
}
igtl::ImageMessage::Pointer imgMsg = igtl::ImageMessage::New();
// TODO: Which kind of coordinate system does MITK really use?
imgMsg->SetCoordinateSystem(igtl::ImageMessage::COORDINATE_RAS);
// We could do this based on the host endiannes, but that's weird.
// We instead use little endian, as most modern systems are little endian,
// so there will probably not be an endian swap involved.
imgMsg->SetEndian(igtl::ImageMessage::ENDIAN_LITTLE);
// Set number of components.
mitk::PixelType type = img->GetPixelType();
imgMsg->SetNumComponents(type.GetNumberOfComponents());
// Set scalar type.
switch (type.GetComponentType())
{
case itk::IOComponentEnum::CHAR:
imgMsg->SetScalarTypeToInt8();
break;
case itk::IOComponentEnum::UCHAR:
imgMsg->SetScalarTypeToUint8();
break;
case itk::IOComponentEnum::SHORT:
imgMsg->SetScalarTypeToInt16();
break;
case itk::IOComponentEnum::USHORT:
imgMsg->SetScalarTypeToUint16();
break;
case itk::IOComponentEnum::INT:
imgMsg->SetScalarTypeToInt32();
break;
case itk::IOComponentEnum::UINT:
imgMsg->SetScalarTypeToUint32();
break;
case itk::IOComponentEnum::LONG:
// OIGTL doesn't formally support 64bit int scalars, but if they are
// ever added,
// they will have the identifier 8 assigned.
imgMsg->SetScalarType(8);
break;
case itk::IOComponentEnum::ULONG:
// OIGTL doesn't formally support 64bit uint scalars, but if they are
// ever added,
// they will have the identifier 9 assigned.
imgMsg->SetScalarType(9);
break;
case itk::IOComponentEnum::FLOAT:
// The igtl library has no method for this. Correct type is 10.
imgMsg->SetScalarType(10);
break;
case itk::IOComponentEnum::DOUBLE:
// The igtl library has no method for this. Correct type is 11.
imgMsg->SetScalarType(11);
break;
default:
MITK_ERROR << "Can not handle pixel component type "
<< type.GetComponentType();
return;
}
// Set transformation matrix.
vtkMatrix4x4* matrix = img->GetGeometry()->GetVtkMatrix();
float matF[4][4];
for (size_t i = 0; i < 4; ++i)
{
for (size_t j = 0; j < 4; ++j)
{
matF[i][j] = matrix->GetElement(i, j);
}
}
imgMsg->SetMatrix(matF);
float spacing[3];
auto spacingImg = img->GetGeometry()->GetSpacing();
for (int i = 0; i < 3; ++i)
spacing[i] = spacingImg[i];
imgMsg->SetSpacing(spacing);
// Set dimensions.
int sizes[3];
for (size_t j = 0; j < 3; ++j)
{
sizes[j] = img->GetDimension(j);
}
imgMsg->SetDimensions(sizes);
// Allocate and copy data.
imgMsg->AllocatePack();
imgMsg->AllocateScalars();
size_t num_pixel = sizes[0] * sizes[1] * sizes[2];
void* out = imgMsg->GetScalarPointer();
{
// Scoped, so that readAccess will be released ASAP.
mitk::ImageReadAccessor readAccess(img, img->GetChannelData(0));
const void* in = readAccess.GetData();
memcpy(out, in, num_pixel * type.GetSize());
}
// We want to byte swap to little endian. We would like to just
// swap by number of bytes for each component, but itk::ByteSwapper
// is templated over element type, not over element size. So we need to
// switch on the size and use types of the same size.
size_t num_scalars = num_pixel * type.GetNumberOfComponents();
switch (type.GetComponentType())
{
case itk::IOComponentEnum::CHAR:
case itk::IOComponentEnum::UCHAR:
// No endian conversion necessary, because a char is exactly one byte!
break;
case itk::IOComponentEnum::SHORT:
case itk::IOComponentEnum::USHORT:
itk::ByteSwapper<short>::SwapRangeFromSystemToLittleEndian((short*)out,
num_scalars);
break;
case itk::IOComponentEnum::INT:
case itk::IOComponentEnum::UINT:
itk::ByteSwapper<int>::SwapRangeFromSystemToLittleEndian((int*)out,
num_scalars);
break;
case itk::IOComponentEnum::LONG:
case itk::IOComponentEnum::ULONG:
itk::ByteSwapper<long>::SwapRangeFromSystemToLittleEndian((long*)out,
num_scalars);
break;
case itk::IOComponentEnum::FLOAT:
itk::ByteSwapper<float>::SwapRangeFromSystemToLittleEndian((float*)out,
num_scalars);
break;
case itk::IOComponentEnum::DOUBLE:
itk::ByteSwapper<double>::SwapRangeFromSystemToLittleEndian(
(double*)out, num_scalars);
break;
}
//copy timestamp of mitk image
igtl::TimeStamp::Pointer timestamp = igtl::TimeStamp::New();
timestamp->SetTime(img->GetMTime() / 1000, (int)(img->GetMTime()) % 1000);
imgMsg->SetTimeStamp(timestamp);
imgMsg->Pack();
output->SetMessage(imgMsg.GetPointer());
}
}
void mitk::ImageToIGTLMessageFilter::SetInput(const mitk::Image* img)
{
this->ProcessObject::SetNthInput(0, const_cast<mitk::Image*>(img));
this->CreateOutputsForAllInputs();
}
void mitk::ImageToIGTLMessageFilter::SetInput(unsigned int idx,
const Image* img)
{
this->ProcessObject::SetNthInput(idx, const_cast<mitk::Image*>(img));
this->CreateOutputsForAllInputs();
}
const mitk::Image* mitk::ImageToIGTLMessageFilter::GetInput(void)
{
if (this->GetNumberOfInputs() < 1)
return nullptr;
return static_cast<const mitk::Image*>(this->ProcessObject::GetInput(0));
}
const mitk::Image* mitk::ImageToIGTLMessageFilter::GetInput(unsigned int idx)
{
if (this->GetNumberOfInputs() < idx + 1)
{
return nullptr;
}
return static_cast<const mitk::Image*>(this->ProcessObject::GetInput(idx));
}
void mitk::ImageToIGTLMessageFilter::ConnectTo(mitk::ImageSource* upstream)
{
MITK_INFO << "Image source for this (" << this << ") mitkImageToIGTLMessageFilter is " << upstream;
for (DataObjectPointerArraySizeType i = 0; i < upstream->GetNumberOfOutputs();
i++)
{
this->SetInput(i, upstream->GetOutput(i));
}
}
void mitk::ImageToIGTLMessageFilter::CreateOutputsForAllInputs()
{
// create one message output for all image inputs
this->SetNumberOfIndexedOutputs(this->GetNumberOfIndexedInputs());
for (size_t idx = 0; idx < this->GetNumberOfIndexedOutputs(); ++idx)
{
if (this->GetOutput(idx) == nullptr)
{
this->SetNthOutput(idx, this->MakeOutput(idx));
}
this->Modified();
}
}
|
/*============================================================================
The Medical Imaging Interaction Toolkit (MITK)
Copyright (c) German Cancer Research Center (DKFZ)
All rights reserved.
Use of this source code is governed by a 3-clause BSD license that can be
found in the LICENSE file.
============================================================================*/
#include "mitkImageToIGTLMessageFilter.h"
#include "mitkImageReadAccessor.h"
#include "itkByteSwapper.h"
#include "igtlImageMessage.h"
mitk::ImageToIGTLMessageFilter::ImageToIGTLMessageFilter()
{
mitk::IGTLMessage::Pointer output = mitk::IGTLMessage::New();
this->SetNumberOfRequiredOutputs(1);
this->SetNthOutput(0, output.GetPointer());
this->SetNumberOfRequiredInputs(1);
}
void mitk::ImageToIGTLMessageFilter::GenerateData()
{
// MITK_INFO << "ImageToIGTLMessageFilter.GenerateData()";
for (unsigned int i = 0; i < this->GetNumberOfIndexedOutputs(); ++i)
{
mitk::IGTLMessage* output = this->GetOutput(i);
assert(output);
const mitk::Image* img = this->GetInput(i);
int dims = img->GetDimension();
int chn = img->GetNumberOfChannels();
if (dims < 1)
{
MITK_ERROR << "Can not handle dimensionless images";
}
if (dims > 3)
{
MITK_ERROR << "Can not handle more than three dimensions";
continue;
}
if (chn != 1)
{
MITK_ERROR << "Can not handle anything but one channel. Image contained " << chn;
continue;
}
igtl::ImageMessage::Pointer imgMsg = igtl::ImageMessage::New();
// TODO: Which kind of coordinate system does MITK really use?
imgMsg->SetCoordinateSystem(igtl::ImageMessage::COORDINATE_RAS);
// We could do this based on the host endiannes, but that's weird.
// We instead use little endian, as most modern systems are little endian,
// so there will probably not be an endian swap involved.
imgMsg->SetEndian(igtl::ImageMessage::ENDIAN_LITTLE);
// Set number of components.
mitk::PixelType type = img->GetPixelType();
imgMsg->SetNumComponents(type.GetNumberOfComponents());
// Set scalar type.
switch (type.GetComponentType())
{
case itk::IOComponentEnum::CHAR:
imgMsg->SetScalarTypeToInt8();
break;
case itk::IOComponentEnum::UCHAR:
imgMsg->SetScalarTypeToUint8();
break;
case itk::IOComponentEnum::SHORT:
imgMsg->SetScalarTypeToInt16();
break;
case itk::IOComponentEnum::USHORT:
imgMsg->SetScalarTypeToUint16();
break;
case itk::IOComponentEnum::INT:
imgMsg->SetScalarTypeToInt32();
break;
case itk::IOComponentEnum::UINT:
imgMsg->SetScalarTypeToUint32();
break;
case itk::IOComponentEnum::LONG:
// OIGTL doesn't formally support 64bit int scalars, but if they are
// ever added,
// they will have the identifier 8 assigned.
imgMsg->SetScalarType(8);
break;
case itk::IOComponentEnum::ULONG:
// OIGTL doesn't formally support 64bit uint scalars, but if they are
// ever added,
// they will have the identifier 9 assigned.
imgMsg->SetScalarType(9);
break;
case itk::IOComponentEnum::FLOAT:
// The igtl library has no method for this. Correct type is 10.
imgMsg->SetScalarType(10);
break;
case itk::IOComponentEnum::DOUBLE:
// The igtl library has no method for this. Correct type is 11.
imgMsg->SetScalarType(11);
break;
default:
MITK_ERROR << "Can not handle pixel component type "
<< type.GetComponentType();
return;
}
// Set transformation matrix.
vtkMatrix4x4* matrix = img->GetGeometry()->GetVtkMatrix();
float matF[4][4];
for (size_t i = 0; i < 4; ++i)
{
for (size_t j = 0; j < 4; ++j)
{
matF[i][j] = matrix->GetElement(i, j);
}
}
imgMsg->SetMatrix(matF);
float spacing[3];
auto spacingImg = img->GetGeometry()->GetSpacing();
for (int i = 0; i < 3; ++i)
spacing[i] = spacingImg[i];
imgMsg->SetSpacing(spacing);
// Set dimensions.
int sizes[3];
for (size_t j = 0; j < 3; ++j)
{
sizes[j] = img->GetDimension(j);
}
imgMsg->SetDimensions(sizes);
// Allocate and copy data.
imgMsg->AllocatePack();
imgMsg->AllocateScalars();
size_t num_pixel = sizes[0] * sizes[1] * sizes[2];
void* out = imgMsg->GetScalarPointer();
{
// Scoped, so that readAccess will be released ASAP.
mitk::ImageReadAccessor readAccess(img, img->GetChannelData(0));
const void* in = readAccess.GetData();
memcpy(out, in, num_pixel * type.GetSize());
}
// We want to byte swap to little endian. We would like to just
// swap by number of bytes for each component, but itk::ByteSwapper
// is templated over element type, not over element size. So we need to
// switch on the size and use types of the same size.
size_t num_scalars = num_pixel * type.GetNumberOfComponents();
switch (type.GetComponentType())
{
case itk::IOComponentEnum::CHAR:
case itk::IOComponentEnum::UCHAR:
// No endian conversion necessary, because a char is exactly one byte!
break;
case itk::IOComponentEnum::SHORT:
case itk::IOComponentEnum::USHORT:
itk::ByteSwapper<short>::SwapRangeFromSystemToLittleEndian((short*)out,
num_scalars);
break;
case itk::IOComponentEnum::INT:
case itk::IOComponentEnum::UINT:
itk::ByteSwapper<int>::SwapRangeFromSystemToLittleEndian((int*)out,
num_scalars);
break;
case itk::IOComponentEnum::LONG:
case itk::IOComponentEnum::ULONG:
itk::ByteSwapper<long>::SwapRangeFromSystemToLittleEndian((long*)out,
num_scalars);
break;
case itk::IOComponentEnum::FLOAT:
itk::ByteSwapper<float>::SwapRangeFromSystemToLittleEndian((float*)out,
num_scalars);
break;
case itk::IOComponentEnum::DOUBLE:
itk::ByteSwapper<double>::SwapRangeFromSystemToLittleEndian(
(double*)out, num_scalars);
break;
default:
MITK_ERROR << "Can not handle pixel component type "
<< type.GetComponentType();
return;
}
//copy timestamp of mitk image
igtl::TimeStamp::Pointer timestamp = igtl::TimeStamp::New();
timestamp->SetTime(img->GetMTime() / 1000, (int)(img->GetMTime()) % 1000);
imgMsg->SetTimeStamp(timestamp);
imgMsg->Pack();
output->SetMessage(imgMsg.GetPointer());
}
}
void mitk::ImageToIGTLMessageFilter::SetInput(const mitk::Image* img)
{
this->ProcessObject::SetNthInput(0, const_cast<mitk::Image*>(img));
this->CreateOutputsForAllInputs();
}
void mitk::ImageToIGTLMessageFilter::SetInput(unsigned int idx,
const Image* img)
{
this->ProcessObject::SetNthInput(idx, const_cast<mitk::Image*>(img));
this->CreateOutputsForAllInputs();
}
const mitk::Image* mitk::ImageToIGTLMessageFilter::GetInput(void)
{
if (this->GetNumberOfInputs() < 1)
return nullptr;
return static_cast<const mitk::Image*>(this->ProcessObject::GetInput(0));
}
const mitk::Image* mitk::ImageToIGTLMessageFilter::GetInput(unsigned int idx)
{
if (this->GetNumberOfInputs() < idx + 1)
{
return nullptr;
}
return static_cast<const mitk::Image*>(this->ProcessObject::GetInput(idx));
}
void mitk::ImageToIGTLMessageFilter::ConnectTo(mitk::ImageSource* upstream)
{
MITK_INFO << "Image source for this (" << this << ") mitkImageToIGTLMessageFilter is " << upstream;
for (DataObjectPointerArraySizeType i = 0; i < upstream->GetNumberOfOutputs();
i++)
{
this->SetInput(i, upstream->GetOutput(i));
}
}
void mitk::ImageToIGTLMessageFilter::CreateOutputsForAllInputs()
{
// create one message output for all image inputs
this->SetNumberOfIndexedOutputs(this->GetNumberOfIndexedInputs());
for (size_t idx = 0; idx < this->GetNumberOfIndexedOutputs(); ++idx)
{
if (this->GetOutput(idx) == nullptr)
{
this->SetNthOutput(idx, this->MakeOutput(idx));
}
this->Modified();
}
}
|
Fix incomplete switch block
|
Fix incomplete switch block
|
C++
|
bsd-3-clause
|
MITK/MITK,MITK/MITK,MITK/MITK,MITK/MITK,MITK/MITK,MITK/MITK
|
848f7497a78834700921ffbd5db51548ae2b003e
|
src/stan/lang/ast/node/algebra_solver.hpp
|
src/stan/lang/ast/node/algebra_solver.hpp
|
#ifndef STAN_LANG_AST_NODE_ALGEBRA_SOLVER_HPP
#define STAN_LANG_AST_NODE_ALGEBRA_SOLVER_HPP
#include <stan/lang/ast/node/expression.hpp>
#include <string>
namespace stan {
namespace lang {
struct expression;
/**
* Structure for algebraic solver statement.
*/
struct algebra_solver {
/**
* Name of the algebra system.
*/
std::string system_function_name_;
/**
* Initial guess for solution.
*/
expression y_;
/**
* Parameters.
*/
expression theta_;
/**
* Real-valued data.
*/
expression x_r_;
/**
* Integer-valued data.
*/
expression x_i_;
/**
* Construct a default algebra solver node.
*/
algebra_solver();
/**
* Construct an algebraic solver.
*
* @param system_function_name name of ODE system
* @param x initial guess for solution
* @param y parameters
* @param dat real-valued data
* @param dat_int integer-valued data
*/
algebra_solver(const std::string& system_function_name,
const expression& y,
const expression& theta,
const expression& x_r,
const expression& x_i);
};
}
}
#endif
|
#ifndef STAN_LANG_AST_NODE_ALGEBRA_SOLVER_HPP
#define STAN_LANG_AST_NODE_ALGEBRA_SOLVER_HPP
#include <stan/lang/ast/node/expression.hpp>
#include <string>
namespace stan {
namespace lang {
struct expression;
/**
* Structure for algebraic solver statement.
*/
struct algebra_solver {
/**
* Name of the algebra system.
*/
std::string system_function_name_;
/**
* Initial guess for solution.
*/
expression y_;
/**
* Parameters.
*/
expression theta_;
/**
* Real-valued data.
*/
expression x_r_;
/**
* Integer-valued data.
*/
expression x_i_;
/**
* Construct a default algebra solver node.
*/
algebra_solver();
/**
* Construct an algebraic solver.
*
* @param system_function_name name of ODE system
* @param y initial guess for solution
* @param theta parameters
* @param x_r real-valued data
* @param x_i integer-valued data
*/
algebra_solver(const std::string& system_function_name,
const expression& y,
const expression& theta,
const expression& x_r,
const expression& x_i);
};
}
}
#endif
|
correct doxygen doc (jenkis).
|
correct doxygen doc (jenkis).
|
C++
|
bsd-3-clause
|
stan-dev/stan,stan-dev/stan,stan-dev/stan,stan-dev/stan,stan-dev/stan
|
04d0676f86b0de387c3eab7e418aeb75a61d6e58
|
core/semaphore.hh
|
core/semaphore.hh
|
/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef CORE_SEMAPHORE_HH_
#define CORE_SEMAPHORE_HH_
#include "future.hh"
#include "chunked_fifo.hh"
#include <stdexcept>
#include <exception>
#include "timer.hh"
/// \addtogroup fiber-module
/// @{
/// Exception thrown when a semaphore is broken by
/// \ref semaphore::broken().
class broken_semaphore : public std::exception {
public:
/// Reports the exception reason.
virtual const char* what() const noexcept {
return "Semaphore broken";
}
};
/// Exception thrown when a semaphore wait operation
/// times out.
///
/// \see semaphore::wait(typename timer<>::duration timeout, size_t nr)
class semaphore_timed_out : public std::exception {
public:
/// Reports the exception reason.
virtual const char* what() const noexcept {
return "Semaphore timedout";
}
};
/// Exception Factory for standard semaphore
///
/// constructs standard semaphore exceptions
/// \see semaphore_timed_out and broken_semaphore
struct semaphore_default_exception_factory {
static semaphore_timed_out timeout() {
return semaphore_timed_out();
}
static broken_semaphore broken() {
return broken_semaphore();
}
};
/// \brief Counted resource guard.
///
/// This is a standard computer science semaphore, adapted
/// for futures. You can deposit units into a counter,
/// or take them away. Taking units from the counter may wait
/// if not enough units are available.
///
/// To support exceptional conditions, a \ref broken() method
/// is provided, which causes all current waiters to stop waiting,
/// with an exceptional future returned. This allows causing all
/// fibers that are blocked on a semaphore to continue. This is
/// similar to POSIX's `pthread_cancel()`, with \ref wait() acting
/// as a cancellation point.
///
/// \tparam ExceptionFactory template parameter allows modifying a semaphore to throw
/// customized exceptions on timeout/broken(). It has to provide two static functions
/// ExceptionFactory::timeout() and ExceptionFactory::broken() which return corresponding
/// exception object.
template<typename ExceptionFactory>
class basic_semaphore {
private:
size_t _count;
std::exception_ptr _ex;
struct entry {
promise<> pr;
size_t nr;
timer<> tr;
// points at pointer back to this, to track the entry object as it moves
std::unique_ptr<entry*> tracker;
entry(promise<>&& pr_, size_t nr_) : pr(std::move(pr_)), nr(nr_) {}
entry(entry&& x) noexcept
: pr(std::move(x.pr)), nr(x.nr), tr(std::move(x.tr)), tracker(std::move(x.tracker)) {
if (tracker) {
*tracker = this;
}
}
entry** track() {
tracker = std::make_unique<entry*>(this);
return tracker.get();
}
entry& operator=(entry&&) noexcept = delete;
};
chunked_fifo<entry> _wait_list;
public:
using duration = timer<>::duration;
using clock = timer<>::clock;
using time_point = timer<>::time_point;
/// Constructs a semaphore object with a specific number of units
/// in its internal counter. The default is 1, suitable for use as
/// an unlocked mutex.
///
/// \param count number of initial units present in the counter (default 1).
basic_semaphore(size_t count = 1) : _count(count) {}
/// Waits until at least a specific number of units are available in the
/// counter, and reduces the counter by that amount of units.
///
/// \note Waits are serviced in FIFO order, though if several are awakened
/// at once, they may be reordered by the scheduler.
///
/// \param nr Amount of units to wait for (default 1).
/// \return a future that becomes ready when sufficient units are available
/// to satisfy the request. If the semaphore was \ref broken(), may
/// contain an exception.
future<> wait(size_t nr = 1) {
if (_count >= nr && _wait_list.empty()) {
_count -= nr;
return make_ready_future<>();
}
if (_ex) {
return make_exception_future(_ex);
}
promise<> pr;
auto fut = pr.get_future();
_wait_list.push_back(entry(std::move(pr), nr));
return fut;
}
/// Waits until at least a specific number of units are available in the
/// counter, and reduces the counter by that amount of units. If the request
/// cannot be satisfied in time, the request is aborted.
///
/// \note Waits are serviced in FIFO order, though if several are awakened
/// at once, they may be reordered by the scheduler.
///
/// \param timeout expiration time.
/// \param nr Amount of units to wait for (default 1).
/// \return a future that becomes ready when sufficient units are available
/// to satisfy the request. On timeout, the future contains a
/// \ref semaphore_timed_out exception. If the semaphore was
/// \ref broken(), may contain an exception.
future<> wait(time_point timeout, size_t nr = 1) {
auto fut = wait(nr);
if (!fut.available()) {
auto cancel = [this] (entry** e) {
(*e)->nr = 0;
(*e)->tracker = nullptr;
signal(0);
};
// Since circular_buffer<> can cause objects to move around,
// track them via entry::tracker
entry** e = _wait_list.back().track();
try {
(*e)->tr.set_callback([e, cancel] {
(*e)->pr.set_exception(ExceptionFactory::timeout());
cancel(e);
});
(*e)->tr.arm(timeout);
} catch (...) {
(*e)->pr.set_exception(std::current_exception());
cancel(e);
}
}
return std::move(fut);
}
/// Waits until at least a specific number of units are available in the
/// counter, and reduces the counter by that amount of units. If the request
/// cannot be satisfied in time, the request is aborted.
///
/// \note Waits are serviced in FIFO order, though if several are awakened
/// at once, they may be reordered by the scheduler.
///
/// \param timeout how long to wait.
/// \param nr Amount of units to wait for (default 1).
/// \return a future that becomes ready when sufficient units are available
/// to satisfy the request. On timeout, the future contains a
/// \ref semaphore_timed_out exception. If the semaphore was
/// \ref broken(), may contain an exception.
future<> wait(duration timeout, size_t nr = 1) {
return wait(clock::now() + timeout, nr);
}
/// Deposits a specified number of units into the counter.
///
/// The counter is incremented by the specified number of units.
/// If the new counter value is sufficient to satisfy the request
/// of one or more waiters, their futures (in FIFO order) become
/// ready, and the value of the counter is reduced according to
/// the amount requested.
///
/// \param nr Number of units to deposit (default 1).
void signal(size_t nr = 1) {
if (_ex) {
return;
}
_count += nr;
while (!_wait_list.empty() && _wait_list.front().nr <= _count) {
auto& x = _wait_list.front();
if (x.nr) {
_count -= x.nr;
x.pr.set_value();
x.tr.cancel();
}
_wait_list.pop_front();
}
}
/// Attempts to reduce the counter value by a specified number of units.
///
/// If sufficient units are available in the counter, and if no
/// other fiber is waiting, then the counter is reduced. Otherwise,
/// nothing happens. This is useful for "opportunistic" waits where
/// useful work can happen if the counter happens to be ready, but
/// when it is not worthwhile to wait.
///
/// \param nr number of units to reduce the counter by (default 1).
/// \return `true` if the counter had sufficient units, and was decremented.
bool try_wait(size_t nr = 1) {
if (_count >= nr && _wait_list.empty()) {
_count -= nr;
return true;
} else {
return false;
}
}
/// Returns the number of units available in the counter.
///
/// Does not take into account any waiters.
size_t current() const { return _count; }
/// Returns the current number of waiters
size_t waiters() const { return _wait_list.size(); }
/// Signal to waiters that an error occurred. \ref wait() will see
/// an exceptional future<> containing a \ref broken_semaphore exception.
/// The future is made available immediately.
void broken() { broken(std::make_exception_ptr(ExceptionFactory::broken())); }
/// Signal to waiters that an error occurred. \ref wait() will see
/// an exceptional future<> containing the provided exception parameter.
/// The future is made available immediately.
template <typename Exception>
void broken(const Exception& ex) {
broken(std::make_exception_ptr(ex));
}
/// Signal to waiters that an error occurred. \ref wait() will see
/// an exceptional future<> containing the provided exception parameter.
/// The future is made available immediately.
void broken(std::exception_ptr ex);
/// Reserve memory for waiters so that wait() will not throw.
void ensure_space_for_waiters(size_t n) {
_wait_list.reserve(n);
}
};
template<typename ExceptionFactory>
inline
void
basic_semaphore<ExceptionFactory>::broken(std::exception_ptr xp) {
_ex = xp;
_count = 0;
while (!_wait_list.empty()) {
auto& x = _wait_list.front();
x.pr.set_exception(xp);
x.tr.cancel();
_wait_list.pop_front();
}
}
/// \brief Runs a function protected by a semaphore
///
/// Acquires a \ref semaphore, runs a function, and releases
/// the semaphore, returning the the return value of the function,
/// as a \ref future.
///
/// \param sem The semaphore to be held while the \c func is
/// running.
/// \param units Number of units to acquire from \c sem (as
/// with semaphore::wait())
/// \param func The function to run; signature \c void() or
/// \c future<>().
/// \return a \ref future<> holding the function's return value
/// or exception thrown; or a \ref future<> containing
/// an exception from one of the semaphore::broken()
/// variants.
///
/// \note The caller must guarantee that \c sem is valid until
/// the future returned by with_semaphore() resolves.
///
/// \related semaphore
template <typename ExceptionFactory, typename Func>
inline
futurize_t<std::result_of_t<Func()>>
with_semaphore(basic_semaphore<ExceptionFactory>& sem, size_t units, Func&& func) {
return sem.wait(units)
.then(std::forward<Func>(func))
.then_wrapped([&sem, units] (auto&& fut) {
sem.signal(units);
return std::move(fut);
});
}
/// default basic_semaphore specialization that throws semaphore specific exceptions
/// on error conditions.
using semaphore = basic_semaphore<semaphore_default_exception_factory>;
/// @}
#endif /* CORE_SEMAPHORE_HH_ */
|
/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2014 Cloudius Systems, Ltd.
*/
#ifndef CORE_SEMAPHORE_HH_
#define CORE_SEMAPHORE_HH_
#include "future.hh"
#include "chunked_fifo.hh"
#include <stdexcept>
#include <exception>
#include "timer.hh"
/// \addtogroup fiber-module
/// @{
/// Exception thrown when a semaphore is broken by
/// \ref semaphore::broken().
class broken_semaphore : public std::exception {
public:
/// Reports the exception reason.
virtual const char* what() const noexcept {
return "Semaphore broken";
}
};
/// Exception thrown when a semaphore wait operation
/// times out.
///
/// \see semaphore::wait(typename timer<>::duration timeout, size_t nr)
class semaphore_timed_out : public std::exception {
public:
/// Reports the exception reason.
virtual const char* what() const noexcept {
return "Semaphore timedout";
}
};
/// Exception Factory for standard semaphore
///
/// constructs standard semaphore exceptions
/// \see semaphore_timed_out and broken_semaphore
struct semaphore_default_exception_factory {
static semaphore_timed_out timeout() {
return semaphore_timed_out();
}
static broken_semaphore broken() {
return broken_semaphore();
}
};
/// \brief Counted resource guard.
///
/// This is a standard computer science semaphore, adapted
/// for futures. You can deposit units into a counter,
/// or take them away. Taking units from the counter may wait
/// if not enough units are available.
///
/// To support exceptional conditions, a \ref broken() method
/// is provided, which causes all current waiters to stop waiting,
/// with an exceptional future returned. This allows causing all
/// fibers that are blocked on a semaphore to continue. This is
/// similar to POSIX's `pthread_cancel()`, with \ref wait() acting
/// as a cancellation point.
///
/// \tparam ExceptionFactory template parameter allows modifying a semaphore to throw
/// customized exceptions on timeout/broken(). It has to provide two static functions
/// ExceptionFactory::timeout() and ExceptionFactory::broken() which return corresponding
/// exception object.
template<typename ExceptionFactory>
class basic_semaphore {
private:
size_t _count;
std::exception_ptr _ex;
struct entry {
promise<> pr;
size_t nr;
timer<> tr;
// points at pointer back to this, to track the entry object as it moves
std::unique_ptr<entry*> tracker;
entry(promise<>&& pr_, size_t nr_) : pr(std::move(pr_)), nr(nr_) {}
entry(entry&& x) noexcept
: pr(std::move(x.pr)), nr(x.nr), tr(std::move(x.tr)), tracker(std::move(x.tracker)) {
if (tracker) {
*tracker = this;
}
}
entry** track() {
tracker = std::make_unique<entry*>(this);
return tracker.get();
}
entry& operator=(entry&&) noexcept = delete;
};
chunked_fifo<entry> _wait_list;
public:
using duration = timer<>::duration;
using clock = timer<>::clock;
using time_point = timer<>::time_point;
/// Constructs a semaphore object with a specific number of units
/// in its internal counter. The default is 1, suitable for use as
/// an unlocked mutex.
///
/// \param count number of initial units present in the counter (default 1).
basic_semaphore(size_t count = 1) : _count(count) {}
/// Waits until at least a specific number of units are available in the
/// counter, and reduces the counter by that amount of units.
///
/// \note Waits are serviced in FIFO order, though if several are awakened
/// at once, they may be reordered by the scheduler.
///
/// \param nr Amount of units to wait for (default 1).
/// \return a future that becomes ready when sufficient units are available
/// to satisfy the request. If the semaphore was \ref broken(), may
/// contain an exception.
future<> wait(size_t nr = 1) {
if (_count >= nr && _wait_list.empty()) {
_count -= nr;
return make_ready_future<>();
}
if (_ex) {
return make_exception_future(_ex);
}
promise<> pr;
auto fut = pr.get_future();
_wait_list.push_back(entry(std::move(pr), nr));
return fut;
}
/// Waits until at least a specific number of units are available in the
/// counter, and reduces the counter by that amount of units. If the request
/// cannot be satisfied in time, the request is aborted.
///
/// \note Waits are serviced in FIFO order, though if several are awakened
/// at once, they may be reordered by the scheduler.
///
/// \param timeout expiration time.
/// \param nr Amount of units to wait for (default 1).
/// \return a future that becomes ready when sufficient units are available
/// to satisfy the request. On timeout, the future contains a
/// \ref semaphore_timed_out exception. If the semaphore was
/// \ref broken(), may contain an exception.
future<> wait(time_point timeout, size_t nr = 1) {
auto fut = wait(nr);
if (!fut.available()) {
auto cancel = [this] (entry** e) {
(*e)->nr = 0;
(*e)->tracker = nullptr;
signal(0);
};
// Since circular_buffer<> can cause objects to move around,
// track them via entry::tracker
entry** e = _wait_list.back().track();
try {
(*e)->tr.set_callback([e, cancel] {
(*e)->pr.set_exception(ExceptionFactory::timeout());
cancel(e);
});
(*e)->tr.arm(timeout);
} catch (...) {
(*e)->pr.set_exception(std::current_exception());
cancel(e);
}
}
return std::move(fut);
}
/// Waits until at least a specific number of units are available in the
/// counter, and reduces the counter by that amount of units. If the request
/// cannot be satisfied in time, the request is aborted.
///
/// \note Waits are serviced in FIFO order, though if several are awakened
/// at once, they may be reordered by the scheduler.
///
/// \param timeout how long to wait.
/// \param nr Amount of units to wait for (default 1).
/// \return a future that becomes ready when sufficient units are available
/// to satisfy the request. On timeout, the future contains a
/// \ref semaphore_timed_out exception. If the semaphore was
/// \ref broken(), may contain an exception.
future<> wait(duration timeout, size_t nr = 1) {
return wait(clock::now() + timeout, nr);
}
/// Deposits a specified number of units into the counter.
///
/// The counter is incremented by the specified number of units.
/// If the new counter value is sufficient to satisfy the request
/// of one or more waiters, their futures (in FIFO order) become
/// ready, and the value of the counter is reduced according to
/// the amount requested.
///
/// \param nr Number of units to deposit (default 1).
void signal(size_t nr = 1) {
if (_ex) {
return;
}
_count += nr;
while (!_wait_list.empty() && _wait_list.front().nr <= _count) {
auto& x = _wait_list.front();
if (x.nr) {
_count -= x.nr;
x.pr.set_value();
x.tr.cancel();
}
_wait_list.pop_front();
}
}
/// Attempts to reduce the counter value by a specified number of units.
///
/// If sufficient units are available in the counter, and if no
/// other fiber is waiting, then the counter is reduced. Otherwise,
/// nothing happens. This is useful for "opportunistic" waits where
/// useful work can happen if the counter happens to be ready, but
/// when it is not worthwhile to wait.
///
/// \param nr number of units to reduce the counter by (default 1).
/// \return `true` if the counter had sufficient units, and was decremented.
bool try_wait(size_t nr = 1) {
if (_count >= nr && _wait_list.empty()) {
_count -= nr;
return true;
} else {
return false;
}
}
/// Returns the number of units available in the counter.
///
/// Does not take into account any waiters.
size_t current() const { return _count; }
/// Returns the current number of waiters
size_t waiters() const { return _wait_list.size(); }
/// Signal to waiters that an error occurred. \ref wait() will see
/// an exceptional future<> containing a \ref broken_semaphore exception.
/// The future is made available immediately.
void broken() { broken(std::make_exception_ptr(ExceptionFactory::broken())); }
/// Signal to waiters that an error occurred. \ref wait() will see
/// an exceptional future<> containing the provided exception parameter.
/// The future is made available immediately.
template <typename Exception>
void broken(const Exception& ex) {
broken(std::make_exception_ptr(ex));
}
/// Signal to waiters that an error occurred. \ref wait() will see
/// an exceptional future<> containing the provided exception parameter.
/// The future is made available immediately.
void broken(std::exception_ptr ex);
/// Reserve memory for waiters so that wait() will not throw.
void ensure_space_for_waiters(size_t n) {
_wait_list.reserve(n);
}
};
template<typename ExceptionFactory>
inline
void
basic_semaphore<ExceptionFactory>::broken(std::exception_ptr xp) {
_ex = xp;
_count = 0;
while (!_wait_list.empty()) {
auto& x = _wait_list.front();
x.pr.set_exception(xp);
x.tr.cancel();
_wait_list.pop_front();
}
}
template<typename ExceptionFactory = semaphore_default_exception_factory>
class semaphore_units {
basic_semaphore<ExceptionFactory>& _sem;
size_t _n;
public:
semaphore_units(basic_semaphore<ExceptionFactory>& sem, size_t n) noexcept : _sem(sem), _n(n) {}
semaphore_units(semaphore_units&& o) noexcept : _sem(o._sem), _n(o._n) {
o._n = 0;
}
semaphore_units& operator=(semaphore_units&& o) noexcept {
if (this != &o) {
this->~semaphore_units();
new (this) semaphore_units(std::move(o));
}
}
semaphore_units(const semaphore_units&) = delete;
~semaphore_units() noexcept {
if (_n) {
_sem.signal(_n);
}
}
};
/// \brief Take units from semaphore temporarily
///
/// Takes units from the semaphore and returns them when the \ref semaphore_units object goes out of scope.
/// This provides a safe way to temporarily take units from a semaphore and ensure
/// that they are eventually returned under all circumstances (exceptions, premature scope exits, etc).
///
/// Unlike with_semaphore(), the scope of unit holding is not limited to the scope of a single async lambda.
///
/// \param sem The semaphore to take units from
/// \param units Number of units to take
/// \return a \ref future<> holding \ref semaphore_units object. When the object goes out of scope
/// the units are returned to the semaphore.
///
/// \note The caller must guarantee that \c sem is valid as long as
/// \ref seaphore_units object is alive.
///
/// \related semaphore
template<typename ExceptionFactory>
future<semaphore_units<ExceptionFactory>>
get_units(basic_semaphore<ExceptionFactory>& sem, size_t units) {
return sem.wait(units).then([&sem, units] {
return semaphore_units<ExceptionFactory>{ sem, units };
});
}
/// \brief Runs a function protected by a semaphore
///
/// Acquires a \ref semaphore, runs a function, and releases
/// the semaphore, returning the the return value of the function,
/// as a \ref future.
///
/// \param sem The semaphore to be held while the \c func is
/// running.
/// \param units Number of units to acquire from \c sem (as
/// with semaphore::wait())
/// \param func The function to run; signature \c void() or
/// \c future<>().
/// \return a \ref future<> holding the function's return value
/// or exception thrown; or a \ref future<> containing
/// an exception from one of the semaphore::broken()
/// variants.
///
/// \note The caller must guarantee that \c sem is valid until
/// the future returned by with_semaphore() resolves.
///
/// \related semaphore
template <typename ExceptionFactory, typename Func>
inline
futurize_t<std::result_of_t<Func()>>
with_semaphore(basic_semaphore<ExceptionFactory>& sem, size_t units, Func&& func) {
return sem.wait(units)
.then(std::forward<Func>(func))
.then_wrapped([&sem, units] (auto&& fut) {
sem.signal(units);
return std::move(fut);
});
}
/// default basic_semaphore specialization that throws semaphore specific exceptions
/// on error conditions.
using semaphore = basic_semaphore<semaphore_default_exception_factory>;
/// @}
#endif /* CORE_SEMAPHORE_HH_ */
|
Introduce get_units()
|
semaphore: Introduce get_units()
Utility for safe temporary acquisition of semaphore units with
flexible scope. Unlike with_semaphore(), the scope of unit holding is
not limited to a single async lambda.
Example:
return get_units(sem, memory_footprint).then([] (auto mem_permit) {
return read_frame().then([mem_permit = std::move(mem_permit)] (auto frame) {
// process in parallel
process(frame).then([mem_permit = std::move(mem_permit)] {});
});
});
Message-Id: <[email protected]>
|
C++
|
apache-2.0
|
scylladb/seastar,cloudius-systems/seastar,dreamsxin/seastar,avikivity/seastar,cloudius-systems/seastar,dreamsxin/seastar,syuu1228/seastar,avikivity/seastar,syuu1228/seastar,scylladb/seastar,scylladb/seastar,dreamsxin/seastar,cloudius-systems/seastar,avikivity/seastar,syuu1228/seastar
|
987626d8ec49c3d844905f7f1d4318816336eeb9
|
CORRFW/test/AliCFTaskForUnfolding.cxx
|
CORRFW/test/AliCFTaskForUnfolding.cxx
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//-----------------------------------------------------------------------
// Task to prepare efficiency and response matrix for unfolding
//-----------------------------------------------------------------------
// Author : R. Vernet, INFN - Catania (it)
//-----------------------------------------------------------------------
#include "TStyle.h"
#include "AliCFTaskForUnfolding.h"
#include "TCanvas.h"
#include "AliStack.h"
#include "TParticle.h"
#include "TH1I.h"
#include "AliMCEvent.h"
#include "AliAnalysisManager.h"
#include "AliESDEvent.h"
#include "AliAODEvent.h"
#include "AliCFManager.h"
#include "AliCFCutBase.h"
#include "AliCFContainer.h"
#include "TChain.h"
#include "AliESDtrack.h"
#include "AliLog.h"
#include "THnSparse.h"
#include "TH2D.h"
ClassImp(AliCFTaskForUnfolding)
//__________________________________________________________________________
AliCFTaskForUnfolding::AliCFTaskForUnfolding() :
fCFManager(0x0),
fHistEventsProcessed(0x0),
fCorrelation(0x0)
{
//
//Default ctor
//
}
//___________________________________________________________________________
AliCFTaskForUnfolding::AliCFTaskForUnfolding(const Char_t* name) :
AliAnalysisTaskSE(name),
fCFManager(0x0),
fHistEventsProcessed(0x0),
fCorrelation(0x0)
{
//
// Constructor. Initialization of Inputs and Outputs
//
Info("AliCFTaskForUnfolding","Calling Constructor");
/*
DefineInput(0) and DefineOutput(0)
are taken care of by AliAnalysisTaskSE constructor
*/
DefineOutput(1,TH1I::Class());
DefineOutput(2,AliCFContainer::Class());
DefineOutput(3,THnSparseD::Class());
}
//___________________________________________________________________________
AliCFTaskForUnfolding::~AliCFTaskForUnfolding() {
//
//destructor
//
Info("~AliCFTaskForUnfolding","Calling Destructor");
if (fCFManager) delete fCFManager ;
if (fHistEventsProcessed) delete fHistEventsProcessed ;
if (fCorrelation) delete fCorrelation ;
}
//_________________________________________________
void AliCFTaskForUnfolding::UserExec(Option_t *)
{
//
// Main loop function
//
Info("UserExec","") ;
AliVEvent* fEvent = fInputEvent ;
AliVParticle* track ;
if (!fEvent) {
Error("UserExec","NO EVENT FOUND!");
return;
}
if (!fMCEvent) Error("UserExec","NO MC INFO FOUND");
//pass the MC evt handler to the cuts that need it
fCFManager->SetEventInfo(fMCEvent);
// MC-event selection
Double_t containerInput[2] ;
//loop on the MC event
for (Int_t ipart=0; ipart<fMCEvent->GetNumberOfTracks(); ipart++) {
AliMCParticle *mcPart = fMCEvent->GetTrack(ipart);
if (!fCFManager->CheckParticleCuts(0,mcPart)) continue;
containerInput[0] = (Float_t)mcPart->Pt();
containerInput[1] = (Float_t)mcPart->Eta();
fCFManager->GetParticleContainer()->Fill(containerInput,0);
}
//Now go to rec level
for (Int_t iTrack = 0; iTrack<fEvent->GetNumberOfTracks(); iTrack++) {
track = fEvent->GetTrack(iTrack);
if (!fCFManager->CheckParticleCuts(1,track)) continue;
Int_t label = track->GetLabel();
if (label<0) continue;
AliMCParticle* mcPart = fMCEvent->GetTrack(label);
// check if this track was part of the signal
if (!fCFManager->CheckParticleCuts(0,mcPart)) continue;
//fill the container
Double_t mom[3];
track->PxPyPz(mom);
Double_t pt=TMath::Sqrt(mom[0]*mom[0]+mom[1]*mom[1]);
containerInput[0] = pt;
containerInput[1] = track->Eta();
fCFManager->GetParticleContainer()->Fill(containerInput,1) ;
containerInput[0] = mcPart->Pt();
containerInput[1] = mcPart->Eta();
fCFManager->GetParticleContainer()->Fill(containerInput,2);
Double_t fill[4]; //fill response matrix
// dimensions 0&1 : pt,eta (Rec)
fill[0] = pt ;
fill[1] = track->Eta();
// dimensions 2&3 : pt,eta (MC)
fill[2] = mcPart->Pt();
fill[3] = mcPart->Eta();
fCorrelation->Fill(fill);
}
fHistEventsProcessed->Fill(0);
/* PostData(0) is taken care of by AliAnalysisTaskSE */
PostData(1,fHistEventsProcessed) ;
PostData(2,fCFManager->GetParticleContainer()) ;
PostData(3,fCorrelation) ;
}
//___________________________________________________________________________
void AliCFTaskForUnfolding::Terminate(Option_t*)
{
// The Terminate() function is the last function to be called during
// a query. It always runs on the client, it can be used to present
// the results graphically or save the results to file.
Info("Terminate","");
AliAnalysisTaskSE::Terminate();
gStyle->SetPalette(1);
//draw some example plots....
AliCFContainer *cont= dynamic_cast<AliCFContainer*> (GetOutputData(2));
TH2D* h00 = cont->ShowProjection(0,1,0) ;
TH2D* h01 = cont->ShowProjection(0,1,1) ;
THnSparseD* hcorr = dynamic_cast<THnSparseD*> (GetOutputData(3));
TCanvas * c =new TCanvas("c","",800,400);
c->Divide(2,1);
c->cd(1);
h00->Draw("text");
c->cd(2);
h01->Draw("text");
c->SaveAs("spectra.eps");
TCanvas * c2 =new TCanvas("c2","",800,400);
c2->Divide(2,1);
c2->cd(1);
hcorr->Projection(0,2)->Draw("text");
c2->cd(2);
hcorr->Projection(1,3)->Draw("text");
c2->SaveAs("correlation.eps");
}
//___________________________________________________________________________
void AliCFTaskForUnfolding::UserCreateOutputObjects() {
//HERE ONE CAN CREATE OUTPUT OBJECTS, IN PARTICULAR IF THE OBJECT PARAMETERS DON'T NEED
//TO BE SET BEFORE THE EXECUTION OF THE TASK
//
Info("CreateOutputObjects","CreateOutputObjects of task %s", GetName());
//slot #1
OpenFile(1);
fHistEventsProcessed = new TH1I("fHistEventsProcessed","",1,0,1) ;
// OpenFile(2);
// OpenFile(3);
}
|
/**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//-----------------------------------------------------------------------
// Task to prepare efficiency and response matrix for unfolding
//-----------------------------------------------------------------------
// Author : R. Vernet, INFN - Catania (it)
//-----------------------------------------------------------------------
#include "TStyle.h"
#include "AliCFTaskForUnfolding.h"
#include "TCanvas.h"
#include "AliStack.h"
#include "TParticle.h"
#include "TH1I.h"
#include "AliMCEvent.h"
#include "AliAnalysisManager.h"
#include "AliESDEvent.h"
#include "AliAODEvent.h"
#include "AliCFManager.h"
#include "AliCFCutBase.h"
#include "AliCFContainer.h"
#include "TChain.h"
#include "AliESDtrack.h"
#include "AliLog.h"
#include "THnSparse.h"
#include "TH2D.h"
ClassImp(AliCFTaskForUnfolding)
//__________________________________________________________________________
AliCFTaskForUnfolding::AliCFTaskForUnfolding() :
fCFManager(0x0),
fHistEventsProcessed(0x0),
fCorrelation(0x0)
{
//
//Default ctor
//
}
//___________________________________________________________________________
AliCFTaskForUnfolding::AliCFTaskForUnfolding(const Char_t* name) :
AliAnalysisTaskSE(name),
fCFManager(0x0),
fHistEventsProcessed(0x0),
fCorrelation(0x0)
{
//
// Constructor. Initialization of Inputs and Outputs
//
Info("AliCFTaskForUnfolding","Calling Constructor");
/*
DefineInput(0) and DefineOutput(0)
are taken care of by AliAnalysisTaskSE constructor
*/
DefineOutput(1,TH1I::Class());
DefineOutput(2,AliCFContainer::Class());
DefineOutput(3,THnSparseD::Class());
}
//___________________________________________________________________________
AliCFTaskForUnfolding::~AliCFTaskForUnfolding() {
//
//destructor
//
Info("~AliCFTaskForUnfolding","Calling Destructor");
if (fCFManager) delete fCFManager ;
if (fHistEventsProcessed) delete fHistEventsProcessed ;
if (fCorrelation) delete fCorrelation ;
}
//_________________________________________________
void AliCFTaskForUnfolding::UserExec(Option_t *)
{
//
// Main loop function
//
AliInfo("") ;
AliVEvent* fEvent = fInputEvent ;
AliVParticle* track ;
if (!fEvent) {
Error("UserExec","NO EVENT FOUND!");
return;
}
if (!fMCEvent) Error("UserExec","NO MC INFO FOUND");
//pass the MC evt handler to the cuts that need it
fCFManager->SetMCEventInfo(fMCEvent);
// MC-event selection
Double_t containerInput[2] ;
//loop on the MC event
for (Int_t ipart=0; ipart<fMCEvent->GetNumberOfTracks(); ipart++) {
AliMCParticle *mcPart = (AliMCParticle*)fMCEvent->GetTrack(ipart);
if (!fCFManager->CheckParticleCuts(0,mcPart)) continue;
containerInput[0] = (Float_t)mcPart->Pt();
containerInput[1] = (Float_t)mcPart->Eta();
fCFManager->GetParticleContainer()->Fill(containerInput,0);
}
//Now go to rec level
for (Int_t iTrack = 0; iTrack<fEvent->GetNumberOfTracks(); iTrack++) {
track = fEvent->GetTrack(iTrack);
if (!fCFManager->CheckParticleCuts(1,track)) continue;
Int_t label = track->GetLabel();
if (label<0) continue;
AliMCParticle* mcPart = (AliMCParticle*)fMCEvent->GetTrack(label);
// check if this track was part of the signal
if (!fCFManager->CheckParticleCuts(0,mcPart)) continue;
//fill the container
Double_t mom[3];
track->PxPyPz(mom);
Double_t pt=TMath::Sqrt(mom[0]*mom[0]+mom[1]*mom[1]);
containerInput[0] = pt;
containerInput[1] = track->Eta();
fCFManager->GetParticleContainer()->Fill(containerInput,1) ;
containerInput[0] = mcPart->Pt();
containerInput[1] = mcPart->Eta();
fCFManager->GetParticleContainer()->Fill(containerInput,2);
Double_t fill[4]; //fill response matrix
// dimensions 0&1 : pt,eta (Rec)
fill[0] = pt ;
fill[1] = track->Eta();
// dimensions 2&3 : pt,eta (MC)
fill[2] = mcPart->Pt();
fill[3] = mcPart->Eta();
fCorrelation->Fill(fill);
}
fHistEventsProcessed->Fill(0);
/* PostData(0) is taken care of by AliAnalysisTaskSE */
PostData(1,fHistEventsProcessed) ;
PostData(2,fCFManager->GetParticleContainer()) ;
PostData(3,fCorrelation) ;
}
//___________________________________________________________________________
void AliCFTaskForUnfolding::Terminate(Option_t*)
{
// The Terminate() function is the last function to be called during
// a query. It always runs on the client, it can be used to present
// the results graphically or save the results to file.
Info("Terminate","");
AliAnalysisTaskSE::Terminate();
gStyle->SetPalette(1);
//draw some example plots....
AliCFContainer *cont= dynamic_cast<AliCFContainer*> (GetOutputData(2));
TH2D* h00 = cont->ShowProjection(0,1,0) ;
TH2D* h01 = cont->ShowProjection(0,1,1) ;
THnSparseD* hcorr = dynamic_cast<THnSparseD*> (GetOutputData(3));
TCanvas * c =new TCanvas("c","",800,400);
c->Divide(2,1);
c->cd(1);
h00->Draw("text");
c->cd(2);
h01->Draw("text");
c->SaveAs("spectra.eps");
TCanvas * c2 =new TCanvas("c2","",800,400);
c2->Divide(2,1);
c2->cd(1);
hcorr->Projection(0,2)->Draw("text");
c2->cd(2);
hcorr->Projection(1,3)->Draw("text");
c2->SaveAs("correlation.eps");
}
//___________________________________________________________________________
void AliCFTaskForUnfolding::UserCreateOutputObjects() {
//HERE ONE CAN CREATE OUTPUT OBJECTS, IN PARTICULAR IF THE OBJECT PARAMETERS DON'T NEED
//TO BE SET BEFORE THE EXECUTION OF THE TASK
//
Info("CreateOutputObjects","CreateOutputObjects of task %s", GetName());
//slot #1
OpenFile(1);
fHistEventsProcessed = new TH1I("fHistEventsProcessed","",1,0,1) ;
// OpenFile(2);
// OpenFile(3);
}
|
update for compilation
|
update for compilation
|
C++
|
bsd-3-clause
|
SHornung1/AliPhysics,dlodato/AliPhysics,fbellini/AliPhysics,dstocco/AliPhysics,jgronefe/AliPhysics,AudreyFrancisco/AliPhysics,dlodato/AliPhysics,mpuccio/AliPhysics,pchrista/AliPhysics,pbuehler/AliPhysics,AMechler/AliPhysics,yowatana/AliPhysics,pchrista/AliPhysics,amaringarcia/AliPhysics,amatyja/AliPhysics,alisw/AliPhysics,mazimm/AliPhysics,aaniin/AliPhysics,carstooon/AliPhysics,aaniin/AliPhysics,adriansev/AliPhysics,lfeldkam/AliPhysics,rihanphys/AliPhysics,sebaleh/AliPhysics,mbjadhav/AliPhysics,rbailhac/AliPhysics,ALICEHLT/AliPhysics,mbjadhav/AliPhysics,carstooon/AliPhysics,ppribeli/AliPhysics,hzanoli/AliPhysics,alisw/AliPhysics,SHornung1/AliPhysics,rbailhac/AliPhysics,AudreyFrancisco/AliPhysics,akubera/AliPhysics,carstooon/AliPhysics,fcolamar/AliPhysics,mkrzewic/AliPhysics,fcolamar/AliPhysics,rderradi/AliPhysics,jgronefe/AliPhysics,preghenella/AliPhysics,jgronefe/AliPhysics,jgronefe/AliPhysics,mkrzewic/AliPhysics,lfeldkam/AliPhysics,AMechler/AliPhysics,amaringarcia/AliPhysics,hcab14/AliPhysics,ALICEHLT/AliPhysics,mazimm/AliPhysics,dstocco/AliPhysics,mpuccio/AliPhysics,alisw/AliPhysics,sebaleh/AliPhysics,carstooon/AliPhysics,ppribeli/AliPhysics,hzanoli/AliPhysics,pbatzing/AliPhysics,pbatzing/AliPhysics,pbatzing/AliPhysics,sebaleh/AliPhysics,sebaleh/AliPhysics,mkrzewic/AliPhysics,rihanphys/AliPhysics,hcab14/AliPhysics,aaniin/AliPhysics,AudreyFrancisco/AliPhysics,amatyja/AliPhysics,adriansev/AliPhysics,yowatana/AliPhysics,pbuehler/AliPhysics,mvala/AliPhysics,dlodato/AliPhysics,ALICEHLT/AliPhysics,lfeldkam/AliPhysics,preghenella/AliPhysics,lcunquei/AliPhysics,amatyja/AliPhysics,lfeldkam/AliPhysics,mazimm/AliPhysics,lcunquei/AliPhysics,victor-gonzalez/AliPhysics,ppribeli/AliPhysics,akubera/AliPhysics,dstocco/AliPhysics,btrzecia/AliPhysics,ALICEHLT/AliPhysics,victor-gonzalez/AliPhysics,adriansev/AliPhysics,jmargutt/AliPhysics,sebaleh/AliPhysics,pbuehler/AliPhysics,mbjadhav/AliPhysics,amaringarcia/AliPhysics,pchrista/AliPhysics,amaringarcia/AliPhysics,kreisl/AliPhysics,preghenella/AliPhysics,mvala/AliPhysics,preghenella/AliPhysics,SHornung1/AliPhysics,pbuehler/AliPhysics,mvala/AliPhysics,yowatana/AliPhysics,mkrzewic/AliPhysics,dstocco/AliPhysics,rbailhac/AliPhysics,ppribeli/AliPhysics,SHornung1/AliPhysics,mvala/AliPhysics,adriansev/AliPhysics,pbuehler/AliPhysics,preghenella/AliPhysics,fbellini/AliPhysics,pbatzing/AliPhysics,dstocco/AliPhysics,lfeldkam/AliPhysics,mazimm/AliPhysics,nschmidtALICE/AliPhysics,akubera/AliPhysics,ppribeli/AliPhysics,nschmidtALICE/AliPhysics,sebaleh/AliPhysics,lcunquei/AliPhysics,rihanphys/AliPhysics,mkrzewic/AliPhysics,amatyja/AliPhysics,kreisl/AliPhysics,amaringarcia/AliPhysics,lcunquei/AliPhysics,ALICEHLT/AliPhysics,carstooon/AliPhysics,amaringarcia/AliPhysics,dmuhlhei/AliPhysics,aaniin/AliPhysics,fcolamar/AliPhysics,ppribeli/AliPhysics,hzanoli/AliPhysics,mbjadhav/AliPhysics,carstooon/AliPhysics,SHornung1/AliPhysics,hcab14/AliPhysics,ppribeli/AliPhysics,fbellini/AliPhysics,AMechler/AliPhysics,rihanphys/AliPhysics,dmuhlhei/AliPhysics,lcunquei/AliPhysics,adriansev/AliPhysics,jmargutt/AliPhysics,aaniin/AliPhysics,mvala/AliPhysics,jmargutt/AliPhysics,rderradi/AliPhysics,pchrista/AliPhysics,pbatzing/AliPhysics,dstocco/AliPhysics,rbailhac/AliPhysics,akubera/AliPhysics,btrzecia/AliPhysics,hcab14/AliPhysics,hzanoli/AliPhysics,mvala/AliPhysics,rderradi/AliPhysics,rihanphys/AliPhysics,nschmidtALICE/AliPhysics,rderradi/AliPhysics,btrzecia/AliPhysics,victor-gonzalez/AliPhysics,dmuhlhei/AliPhysics,AudreyFrancisco/AliPhysics,preghenella/AliPhysics,fbellini/AliPhysics,mbjadhav/AliPhysics,rihanphys/AliPhysics,nschmidtALICE/AliPhysics,fcolamar/AliPhysics,kreisl/AliPhysics,pbuehler/AliPhysics,hcab14/AliPhysics,dmuhlhei/AliPhysics,mazimm/AliPhysics,btrzecia/AliPhysics,jgronefe/AliPhysics,yowatana/AliPhysics,pbuehler/AliPhysics,alisw/AliPhysics,fcolamar/AliPhysics,dmuhlhei/AliPhysics,nschmidtALICE/AliPhysics,lfeldkam/AliPhysics,dlodato/AliPhysics,alisw/AliPhysics,AMechler/AliPhysics,rderradi/AliPhysics,jmargutt/AliPhysics,hcab14/AliPhysics,hcab14/AliPhysics,mpuccio/AliPhysics,victor-gonzalez/AliPhysics,victor-gonzalez/AliPhysics,kreisl/AliPhysics,mpuccio/AliPhysics,SHornung1/AliPhysics,akubera/AliPhysics,aaniin/AliPhysics,sebaleh/AliPhysics,yowatana/AliPhysics,btrzecia/AliPhysics,pbatzing/AliPhysics,kreisl/AliPhysics,nschmidtALICE/AliPhysics,fcolamar/AliPhysics,mazimm/AliPhysics,mbjadhav/AliPhysics,hzanoli/AliPhysics,carstooon/AliPhysics,ALICEHLT/AliPhysics,AMechler/AliPhysics,amatyja/AliPhysics,adriansev/AliPhysics,mpuccio/AliPhysics,victor-gonzalez/AliPhysics,mazimm/AliPhysics,adriansev/AliPhysics,yowatana/AliPhysics,jgronefe/AliPhysics,rihanphys/AliPhysics,victor-gonzalez/AliPhysics,dstocco/AliPhysics,dmuhlhei/AliPhysics,pchrista/AliPhysics,jmargutt/AliPhysics,kreisl/AliPhysics,kreisl/AliPhysics,hzanoli/AliPhysics,lcunquei/AliPhysics,jmargutt/AliPhysics,jgronefe/AliPhysics,rderradi/AliPhysics,yowatana/AliPhysics,mkrzewic/AliPhysics,alisw/AliPhysics,AudreyFrancisco/AliPhysics,amatyja/AliPhysics,SHornung1/AliPhysics,btrzecia/AliPhysics,amaringarcia/AliPhysics,dmuhlhei/AliPhysics,AudreyFrancisco/AliPhysics,dlodato/AliPhysics,fbellini/AliPhysics,fbellini/AliPhysics,btrzecia/AliPhysics,rbailhac/AliPhysics,mbjadhav/AliPhysics,pbatzing/AliPhysics,rderradi/AliPhysics,mpuccio/AliPhysics,fbellini/AliPhysics,mvala/AliPhysics,rbailhac/AliPhysics,pchrista/AliPhysics,mpuccio/AliPhysics,lcunquei/AliPhysics,alisw/AliPhysics,AudreyFrancisco/AliPhysics,rbailhac/AliPhysics,fcolamar/AliPhysics,AMechler/AliPhysics,mkrzewic/AliPhysics,pchrista/AliPhysics,nschmidtALICE/AliPhysics,amatyja/AliPhysics,dlodato/AliPhysics,ALICEHLT/AliPhysics,dlodato/AliPhysics,akubera/AliPhysics,hzanoli/AliPhysics,lfeldkam/AliPhysics,jmargutt/AliPhysics,preghenella/AliPhysics,aaniin/AliPhysics,AMechler/AliPhysics,akubera/AliPhysics
|
fc4bc9715dae07a1e1c315122ef5794475814098
|
tests/dockey/dockey_test.cc
|
tests/dockey/dockey_test.cc
|
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2020 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/portability/GTest.h>
#include <memcached/dockey.h>
#include <array>
class DocKeyTest : public ::testing::Test {
protected:
void golden(cb::const_byte_buffer buffer,
size_t logicalKeyLen,
CollectionID encoded);
void golden(cb::const_byte_buffer buffer);
};
TEST_F(DocKeyTest, invalid) {
std::array<uint8_t, 4> data1 = {{0, 'k', 'e', 'y'}};
std::array<char, 4> data2 = {{0, 'k', 'e', 'y'}};
cb::const_char_buffer buf{data2.data(), 0};
EXPECT_THROW(std::make_unique<DocKey>(
data1.data(), 0, DocKeyEncodesCollectionId::Yes),
std::invalid_argument);
EXPECT_THROW(std::make_unique<DocKey>(
nullptr, 4, DocKeyEncodesCollectionId::Yes),
std::invalid_argument);
EXPECT_THROW(std::make_unique<DocKey>(buf, DocKeyEncodesCollectionId::Yes),
std::invalid_argument);
EXPECT_NO_THROW(std::make_unique<DocKey>(
data1.data(), data1.size(), DocKeyEncodesCollectionId::No));
EXPECT_NO_THROW(std::make_unique<DocKey>(
data1.data(), data1.size(), DocKeyEncodesCollectionId::Yes));
EXPECT_NO_THROW(std::make_unique<DocKey>(
nullptr, 0, DocKeyEncodesCollectionId::No));
}
// A DocKey can view nothing (len:0) if it does no encode a collection
TEST_F(DocKeyTest, zeroLength) {
std::array<uint8_t, 4> data1 = {{0, 'k', 'e', 'y'}};
// Safe to construct and we expect that it behaves ok
DocKey key(data1.data(), 0, DocKeyEncodesCollectionId::No);
EXPECT_EQ(0, key.size());
EXPECT_EQ(CollectionID::Default, key.getCollectionID());
EXPECT_FALSE(key.isPrivate());
EXPECT_EQ(DocKeyEncodesCollectionId::No, key.getEncoding());
auto pair = key.getIdAndKey();
EXPECT_EQ(CollectionID::Default, pair.first);
EXPECT_EQ(0, pair.second.size());
auto key2 = key.makeDocKeyWithoutCollectionID();
EXPECT_EQ(0, key2.size());
EXPECT_EQ(CollectionID::Default, key2.getCollectionID());
EXPECT_FALSE(key2.isPrivate());
EXPECT_EQ(DocKeyEncodesCollectionId::No, key2.getEncoding());
}
// A DocKey can view nothing (null,len:0) if it does not encode a collection
// There are some places in the code which construct with no data pointer
TEST_F(DocKeyTest, nullZeroLength) {
DocKey key(nullptr, 0, DocKeyEncodesCollectionId::No);
EXPECT_EQ(0, key.size());
EXPECT_EQ(CollectionID::Default, key.getCollectionID());
EXPECT_FALSE(key.isPrivate());
EXPECT_EQ(DocKeyEncodesCollectionId::No, key.getEncoding());
auto pair = key.getIdAndKey();
EXPECT_EQ(CollectionID::Default, pair.first);
EXPECT_EQ(0, pair.second.size());
auto key2 = key.makeDocKeyWithoutCollectionID();
EXPECT_EQ(0, key2.size());
EXPECT_EQ(CollectionID::Default, key2.getCollectionID());
EXPECT_FALSE(key2.isPrivate());
EXPECT_EQ(DocKeyEncodesCollectionId::No, key2.getEncoding());
}
void DocKeyTest::golden(cb::const_byte_buffer buffer,
size_t logicalKeyLen,
CollectionID encoded) {
DocKey key(buffer.data(), buffer.size(), DocKeyEncodesCollectionId::Yes);
EXPECT_EQ(buffer.size(), key.size());
EXPECT_EQ(encoded, key.getCollectionID());
EXPECT_FALSE(key.isPrivate());
EXPECT_EQ(DocKeyEncodesCollectionId::Yes, key.getEncoding());
auto pair = key.getIdAndKey();
EXPECT_EQ(encoded, pair.first);
EXPECT_EQ(logicalKeyLen, pair.second.size());
auto key2 = key.makeDocKeyWithoutCollectionID();
EXPECT_EQ(logicalKeyLen, key2.size());
EXPECT_EQ(CollectionID::Default, key2.getCollectionID());
EXPECT_FALSE(key2.isPrivate());
EXPECT_EQ(DocKeyEncodesCollectionId::No, key2.getEncoding());
}
TEST_F(DocKeyTest, golden) {
std::array<uint8_t, 4> data1 = {{8, 'k', 'e', 'y'}};
golden({data1.data(), data1.size()}, 3, CollectionID(8));
std::array<uint8_t, 5> data2 = {{0xf8, 0, 'k', 'e', 'y'}};
golden({data2.data(), data2.size()}, 3, CollectionID(120));
std::array<uint8_t, 4> data3 = {{0, 'k', 'e', 'y'}};
golden({data3.data(), data3.size()}, 3, CollectionID::Default);
}
void DocKeyTest::golden(cb::const_byte_buffer buffer) {
DocKey key(buffer.data(), buffer.size(), DocKeyEncodesCollectionId::No);
EXPECT_EQ(buffer.size(), key.size());
EXPECT_EQ(CollectionID::Default, key.getCollectionID());
EXPECT_FALSE(key.isPrivate());
EXPECT_EQ(DocKeyEncodesCollectionId::No, key.getEncoding());
auto pair = key.getIdAndKey();
EXPECT_EQ(CollectionID::Default, pair.first);
EXPECT_EQ(buffer.size(), pair.second.size());
auto key2 = key.makeDocKeyWithoutCollectionID();
EXPECT_EQ(buffer.size(), key2.size());
EXPECT_EQ(CollectionID::Default, key2.getCollectionID());
EXPECT_FALSE(key2.isPrivate());
EXPECT_EQ(DocKeyEncodesCollectionId::No, key2.getEncoding());
}
TEST_F(DocKeyTest, golden_nocollection_encoded) {
std::array<uint8_t, 4> data1 = {{8, 'k', 'e', 'y'}};
golden({data1.data(), data1.size()});
std::array<uint8_t, 5> data2 = {{0xf8, 0, 'k', 'e', 'y'}};
golden({data2.data(), data2.size()});
}
|
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
* Copyright 2020 Couchbase, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <folly/portability/GTest.h>
#include <memcached/dockey.h>
#include <array>
class DocKeyTest : public ::testing::Test {
protected:
void golden(cb::const_byte_buffer buffer,
size_t logicalKeyLen,
CollectionID encoded);
void golden(cb::const_byte_buffer buffer);
};
TEST_F(DocKeyTest, invalid) {
std::array<uint8_t, 4> data1 = {{0, 'k', 'e', 'y'}};
std::array<char, 4> data2 = {{0, 'k', 'e', 'y'}};
cb::const_char_buffer buf{data2.data(), 0};
std::unique_ptr<DocKey> ptr;
EXPECT_THROW(ptr = std::make_unique<DocKey>(
data1.data(), 0, DocKeyEncodesCollectionId::Yes),
std::invalid_argument);
EXPECT_THROW(ptr = std::make_unique<DocKey>(
nullptr, 4, DocKeyEncodesCollectionId::Yes),
std::invalid_argument);
EXPECT_THROW(
ptr = std::make_unique<DocKey>(buf, DocKeyEncodesCollectionId::Yes),
std::invalid_argument);
EXPECT_NO_THROW(
ptr = std::make_unique<DocKey>(
data1.data(), data1.size(), DocKeyEncodesCollectionId::No));
EXPECT_NO_THROW(
ptr = std::make_unique<DocKey>(data1.data(),
data1.size(),
DocKeyEncodesCollectionId::Yes));
EXPECT_NO_THROW(ptr = std::make_unique<DocKey>(
nullptr, 0, DocKeyEncodesCollectionId::No));
}
// A DocKey can view nothing (len:0) if it does no encode a collection
TEST_F(DocKeyTest, zeroLength) {
std::array<uint8_t, 4> data1 = {{0, 'k', 'e', 'y'}};
// Safe to construct and we expect that it behaves ok
DocKey key(data1.data(), 0, DocKeyEncodesCollectionId::No);
EXPECT_EQ(0, key.size());
EXPECT_EQ(CollectionID::Default, key.getCollectionID());
EXPECT_FALSE(key.isPrivate());
EXPECT_EQ(DocKeyEncodesCollectionId::No, key.getEncoding());
auto pair = key.getIdAndKey();
EXPECT_EQ(CollectionID::Default, pair.first);
EXPECT_EQ(0, pair.second.size());
auto key2 = key.makeDocKeyWithoutCollectionID();
EXPECT_EQ(0, key2.size());
EXPECT_EQ(CollectionID::Default, key2.getCollectionID());
EXPECT_FALSE(key2.isPrivate());
EXPECT_EQ(DocKeyEncodesCollectionId::No, key2.getEncoding());
}
// A DocKey can view nothing (null,len:0) if it does not encode a collection
// There are some places in the code which construct with no data pointer
TEST_F(DocKeyTest, nullZeroLength) {
DocKey key(nullptr, 0, DocKeyEncodesCollectionId::No);
EXPECT_EQ(0, key.size());
EXPECT_EQ(CollectionID::Default, key.getCollectionID());
EXPECT_FALSE(key.isPrivate());
EXPECT_EQ(DocKeyEncodesCollectionId::No, key.getEncoding());
auto pair = key.getIdAndKey();
EXPECT_EQ(CollectionID::Default, pair.first);
EXPECT_EQ(0, pair.second.size());
auto key2 = key.makeDocKeyWithoutCollectionID();
EXPECT_EQ(0, key2.size());
EXPECT_EQ(CollectionID::Default, key2.getCollectionID());
EXPECT_FALSE(key2.isPrivate());
EXPECT_EQ(DocKeyEncodesCollectionId::No, key2.getEncoding());
}
void DocKeyTest::golden(cb::const_byte_buffer buffer,
size_t logicalKeyLen,
CollectionID encoded) {
DocKey key(buffer.data(), buffer.size(), DocKeyEncodesCollectionId::Yes);
EXPECT_EQ(buffer.size(), key.size());
EXPECT_EQ(encoded, key.getCollectionID());
EXPECT_FALSE(key.isPrivate());
EXPECT_EQ(DocKeyEncodesCollectionId::Yes, key.getEncoding());
auto pair = key.getIdAndKey();
EXPECT_EQ(encoded, pair.first);
EXPECT_EQ(logicalKeyLen, pair.second.size());
auto key2 = key.makeDocKeyWithoutCollectionID();
EXPECT_EQ(logicalKeyLen, key2.size());
EXPECT_EQ(CollectionID::Default, key2.getCollectionID());
EXPECT_FALSE(key2.isPrivate());
EXPECT_EQ(DocKeyEncodesCollectionId::No, key2.getEncoding());
}
TEST_F(DocKeyTest, golden) {
std::array<uint8_t, 4> data1 = {{8, 'k', 'e', 'y'}};
golden({data1.data(), data1.size()}, 3, CollectionID(8));
std::array<uint8_t, 5> data2 = {{0xf8, 0, 'k', 'e', 'y'}};
golden({data2.data(), data2.size()}, 3, CollectionID(120));
std::array<uint8_t, 4> data3 = {{0, 'k', 'e', 'y'}};
golden({data3.data(), data3.size()}, 3, CollectionID::Default);
}
void DocKeyTest::golden(cb::const_byte_buffer buffer) {
DocKey key(buffer.data(), buffer.size(), DocKeyEncodesCollectionId::No);
EXPECT_EQ(buffer.size(), key.size());
EXPECT_EQ(CollectionID::Default, key.getCollectionID());
EXPECT_FALSE(key.isPrivate());
EXPECT_EQ(DocKeyEncodesCollectionId::No, key.getEncoding());
auto pair = key.getIdAndKey();
EXPECT_EQ(CollectionID::Default, pair.first);
EXPECT_EQ(buffer.size(), pair.second.size());
auto key2 = key.makeDocKeyWithoutCollectionID();
EXPECT_EQ(buffer.size(), key2.size());
EXPECT_EQ(CollectionID::Default, key2.getCollectionID());
EXPECT_FALSE(key2.isPrivate());
EXPECT_EQ(DocKeyEncodesCollectionId::No, key2.getEncoding());
}
TEST_F(DocKeyTest, golden_nocollection_encoded) {
std::array<uint8_t, 4> data1 = {{8, 'k', 'e', 'y'}};
golden({data1.data(), data1.size()});
std::array<uint8_t, 5> data2 = {{0xf8, 0, 'k', 'e', 'y'}};
golden({data2.data(), data2.size()});
}
|
Fix MSVC nodiscard warnings
|
dockey_test.cc: Fix MSVC nodiscard warnings
MSVC (with C++17) warns that the return value of make_unique<> is
ignored in this test:
dockey_test.cc(36): warning C4834: discarding return value of function with 'nodiscard' attribute
Change-Id: I783bea2dcb712742694f8ec6264d547eba17cda1
Reviewed-on: http://review.couchbase.org/123081
Reviewed-by: Ben Huddleston <[email protected]>
Tested-by: Build Bot <[email protected]>
|
C++
|
bsd-3-clause
|
daverigby/kv_engine,daverigby/kv_engine,daverigby/kv_engine,daverigby/kv_engine
|
88198b08d41a105d2d22292b605d72b668443766
|
src/node_usb.cc
|
src/node_usb.cc
|
#include "node_usb.h"
#include "uv_async_queue.h"
NAN_METHOD(SetDebugLevel);
NAN_METHOD(GetDeviceList);
NAN_METHOD(EnableHotplugEvents);
NAN_METHOD(DisableHotplugEvents);
void initConstants(Local<Object> target);
libusb_context* usb_context;
#ifdef USE_POLL
#include <poll.h>
#include <sys/time.h>
std::map<int, uv_poll_t*> pollByFD;
struct timeval zero_tv = {0, 0};
void onPollSuccess(uv_poll_t* handle, int status, int events){
libusb_handle_events_timeout(usb_context, &zero_tv);
}
void LIBUSB_CALL onPollFDAdded(int fd, short events, void *user_data){
uv_poll_t *poll_fd;
auto it = pollByFD.find(fd);
if (it != pollByFD.end()){
poll_fd = it->second;
}else{
poll_fd = (uv_poll_t*) malloc(sizeof(uv_poll_t));
uv_poll_init(uv_default_loop(), poll_fd, fd);
pollByFD.insert(std::make_pair(fd, poll_fd));
}
DEBUG_LOG("Added pollfd %i, %p", fd, poll_fd);
unsigned flags = ((events&POLLIN) ? UV_READABLE:0)
| ((events&POLLOUT)? UV_WRITABLE:0);
uv_poll_start(poll_fd, flags, onPollSuccess);
}
void LIBUSB_CALL onPollFDRemoved(int fd, void *user_data){
auto it = pollByFD.find(fd);
if (it != pollByFD.end()){
DEBUG_LOG("Removed pollfd %i, %p", fd, it->second);
uv_poll_stop(it->second);
uv_close((uv_handle_t*) it->second, (uv_close_cb) free);
pollByFD.erase(it);
}
}
#else
uv_thread_t usb_thread;
void USBThreadFn(void*){
while(1) libusb_handle_events(usb_context);
}
#endif
extern "C" void Initialize(Local<Object> target) {
Nan::HandleScope scope;
// Initialize libusb. On error, halt initialization.
int res = libusb_init(&usb_context);
target->Set(Nan::New<String>("INIT_ERROR").ToLocalChecked(), Nan::New<Number>(res));
if (res != 0) {
return;
}
#ifdef USE_POLL
assert(libusb_pollfds_handle_timeouts(usb_context));
libusb_set_pollfd_notifiers(usb_context, onPollFDAdded, onPollFDRemoved, NULL);
const struct libusb_pollfd** pollfds = libusb_get_pollfds(usb_context);
assert(pollfds);
for(const struct libusb_pollfd** i=pollfds; *i; i++){
onPollFDAdded((*i)->fd, (*i)->events, NULL);
}
free(pollfds);
#else
uv_thread_create(&usb_thread, USBThreadFn, NULL);
#endif
Device::Init(target);
Transfer::Init(target);
Nan::SetMethod(target, "setDebugLevel", SetDebugLevel);
Nan::SetMethod(target, "getDeviceList", GetDeviceList);
Nan::SetMethod(target, "_enableHotplugEvents", EnableHotplugEvents);
Nan::SetMethod(target, "_disableHotplugEvents", DisableHotplugEvents);
initConstants(target);
}
NODE_MODULE(usb_bindings, Initialize)
NAN_METHOD(SetDebugLevel) {
Nan::HandleScope scope;
if (info.Length() != 1 || !info[0]->IsUint32() || info[0]->Uint32Value() > 4) {
THROW_BAD_ARGS("Usb::SetDebugLevel argument is invalid. [uint:[0-4]]!")
}
libusb_set_debug(usb_context, info[0]->Uint32Value());
info.GetReturnValue().Set(Nan::Undefined());
}
NAN_METHOD(GetDeviceList) {
Nan::HandleScope scope;
libusb_device **devs;
int cnt = libusb_get_device_list(usb_context, &devs);
CHECK_USB(cnt);
Local<Array> arr = Nan::New<Array>(cnt);
for(int i = 0; i < cnt; i++) {
arr->Set(i, Device::get(devs[i]));
}
libusb_free_device_list(devs, true);
info.GetReturnValue().Set(arr);
}
Nan::Persistent<Object> hotplugThis;
void handleHotplug(std::pair<libusb_device*, libusb_hotplug_event> info){
Nan::HandleScope scope;
libusb_device* dev = info.first;
libusb_hotplug_event event = info.second;
DEBUG_LOG("HandleHotplug %p %i", dev, event);
Local<Value> v8dev = Device::get(dev);
libusb_unref_device(dev);
Local<String> eventName;
if (LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED == event) {
DEBUG_LOG("Device arrived");
eventName = Nan::New("attach").ToLocalChecked();
} else if (LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT == event) {
DEBUG_LOG("Device left");
eventName = Nan::New("detach").ToLocalChecked();
} else {
DEBUG_LOG("Unhandled hotplug event %d\n", event);
return;
}
Local<Value> argv[] = {eventName, v8dev};
Nan::MakeCallback(Nan::New(hotplugThis), "emit", 2, argv);
}
bool hotplugEnabled = 0;
libusb_hotplug_callback_handle hotplugHandle;
UVQueue<std::pair<libusb_device*, libusb_hotplug_event>> hotplugQueue(handleHotplug);
int LIBUSB_CALL hotplug_callback(libusb_context *ctx, libusb_device *dev,
libusb_hotplug_event event, void *user_data) {
libusb_ref_device(dev);
hotplugQueue.post(std::pair<libusb_device*, libusb_hotplug_event>(dev, event));
return 0;
}
NAN_METHOD(EnableHotplugEvents) {
Nan::HandleScope scope;
if (!hotplugEnabled) {
hotplugThis.Reset(info.This());
CHECK_USB(libusb_hotplug_register_callback(usb_context,
(libusb_hotplug_event)(LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED | LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT),
(libusb_hotplug_flag)0, LIBUSB_HOTPLUG_MATCH_ANY, LIBUSB_HOTPLUG_MATCH_ANY, LIBUSB_HOTPLUG_MATCH_ANY,
hotplug_callback, NULL, &hotplugHandle));
hotplugQueue.ref();
hotplugEnabled = true;
}
info.GetReturnValue().Set(Nan::Undefined());
}
NAN_METHOD(DisableHotplugEvents) {
Nan::HandleScope scope;
if (hotplugEnabled) {
libusb_hotplug_deregister_callback(usb_context, hotplugHandle);
hotplugQueue.unref();
hotplugEnabled = false;
}
info.GetReturnValue().Set(Nan::Undefined());
}
void initConstants(Local<Object> target){
NODE_DEFINE_CONSTANT(target, LIBUSB_CLASS_PER_INTERFACE);
NODE_DEFINE_CONSTANT(target, LIBUSB_CLASS_AUDIO);
NODE_DEFINE_CONSTANT(target, LIBUSB_CLASS_COMM);
NODE_DEFINE_CONSTANT(target, LIBUSB_CLASS_HID);
NODE_DEFINE_CONSTANT(target, LIBUSB_CLASS_PRINTER);
NODE_DEFINE_CONSTANT(target, LIBUSB_CLASS_PTP);
NODE_DEFINE_CONSTANT(target, LIBUSB_CLASS_MASS_STORAGE);
NODE_DEFINE_CONSTANT(target, LIBUSB_CLASS_HUB);
NODE_DEFINE_CONSTANT(target, LIBUSB_CLASS_DATA);
NODE_DEFINE_CONSTANT(target, LIBUSB_CLASS_WIRELESS);
NODE_DEFINE_CONSTANT(target, LIBUSB_CLASS_APPLICATION);
NODE_DEFINE_CONSTANT(target, LIBUSB_CLASS_VENDOR_SPEC);
// libusb_standard_request
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_GET_STATUS);
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_CLEAR_FEATURE);
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_SET_FEATURE);
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_SET_ADDRESS );
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_GET_DESCRIPTOR);
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_SET_DESCRIPTOR);
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_GET_CONFIGURATION);
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_SET_CONFIGURATION );
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_GET_INTERFACE);
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_SET_INTERFACE);
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_SYNCH_FRAME);
// libusb_descriptor_type
NODE_DEFINE_CONSTANT(target, LIBUSB_DT_DEVICE);
NODE_DEFINE_CONSTANT(target, LIBUSB_DT_CONFIG);
NODE_DEFINE_CONSTANT(target, LIBUSB_DT_STRING);
NODE_DEFINE_CONSTANT(target, LIBUSB_DT_INTERFACE);
NODE_DEFINE_CONSTANT(target, LIBUSB_DT_ENDPOINT);
NODE_DEFINE_CONSTANT(target, LIBUSB_DT_HID);
NODE_DEFINE_CONSTANT(target, LIBUSB_DT_REPORT);
NODE_DEFINE_CONSTANT(target, LIBUSB_DT_PHYSICAL);
NODE_DEFINE_CONSTANT(target, LIBUSB_DT_HUB);
// libusb_endpoint_direction
NODE_DEFINE_CONSTANT(target, LIBUSB_ENDPOINT_IN);
NODE_DEFINE_CONSTANT(target, LIBUSB_ENDPOINT_OUT);
// libusb_transfer_type
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_TYPE_CONTROL);
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_TYPE_ISOCHRONOUS);
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_TYPE_BULK);
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_TYPE_INTERRUPT);
// libusb_iso_sync_type
NODE_DEFINE_CONSTANT(target, LIBUSB_ISO_SYNC_TYPE_NONE);
NODE_DEFINE_CONSTANT(target, LIBUSB_ISO_SYNC_TYPE_ASYNC);
NODE_DEFINE_CONSTANT(target, LIBUSB_ISO_SYNC_TYPE_ADAPTIVE);
NODE_DEFINE_CONSTANT(target, LIBUSB_ISO_SYNC_TYPE_SYNC);
// libusb_iso_usage_type
NODE_DEFINE_CONSTANT(target, LIBUSB_ISO_USAGE_TYPE_DATA);
NODE_DEFINE_CONSTANT(target, LIBUSB_ISO_USAGE_TYPE_FEEDBACK);
NODE_DEFINE_CONSTANT(target, LIBUSB_ISO_USAGE_TYPE_IMPLICIT);
// libusb_transfer_status
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_COMPLETED);
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_ERROR);
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_TIMED_OUT);
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_CANCELLED);
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_STALL);
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_NO_DEVICE);
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_OVERFLOW);
// libusb_transfer_flags
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_SHORT_NOT_OK);
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_FREE_BUFFER);
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_FREE_TRANSFER);
// libusb_request_type
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_TYPE_STANDARD);
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_TYPE_CLASS);
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_TYPE_VENDOR);
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_TYPE_RESERVED);
// libusb_request_recipient
NODE_DEFINE_CONSTANT(target, LIBUSB_RECIPIENT_DEVICE);
NODE_DEFINE_CONSTANT(target, LIBUSB_RECIPIENT_INTERFACE);
NODE_DEFINE_CONSTANT(target, LIBUSB_RECIPIENT_ENDPOINT);
NODE_DEFINE_CONSTANT(target, LIBUSB_RECIPIENT_OTHER);
NODE_DEFINE_CONSTANT(target, LIBUSB_CONTROL_SETUP_SIZE);
}
Local<Value> libusbException(int errorno) {
const char* err = libusb_error_name(errorno);
Local<Value> e = Nan::Error(err);
e->ToObject()->Set(Nan::New<String>("errno").ToLocalChecked(), Nan::New<Integer>(errorno));
return e;
}
|
#include "node_usb.h"
#include "uv_async_queue.h"
NAN_METHOD(SetDebugLevel);
NAN_METHOD(GetDeviceList);
NAN_METHOD(EnableHotplugEvents);
NAN_METHOD(DisableHotplugEvents);
void initConstants(Local<Object> target);
libusb_context* usb_context;
#ifdef USE_POLL
#include <poll.h>
#include <sys/time.h>
std::map<int, uv_poll_t*> pollByFD;
struct timeval zero_tv = {0, 0};
void onPollSuccess(uv_poll_t* handle, int status, int events){
libusb_handle_events_timeout(usb_context, &zero_tv);
}
void LIBUSB_CALL onPollFDAdded(int fd, short events, void *user_data){
uv_poll_t *poll_fd;
auto it = pollByFD.find(fd);
if (it != pollByFD.end()){
poll_fd = it->second;
}else{
poll_fd = (uv_poll_t*) malloc(sizeof(uv_poll_t));
uv_poll_init(uv_default_loop(), poll_fd, fd);
pollByFD.insert(std::make_pair(fd, poll_fd));
}
DEBUG_LOG("Added pollfd %i, %p", fd, poll_fd);
unsigned flags = ((events&POLLIN) ? UV_READABLE:0)
| ((events&POLLOUT)? UV_WRITABLE:0);
uv_poll_start(poll_fd, flags, onPollSuccess);
}
void LIBUSB_CALL onPollFDRemoved(int fd, void *user_data){
auto it = pollByFD.find(fd);
if (it != pollByFD.end()){
DEBUG_LOG("Removed pollfd %i, %p", fd, it->second);
uv_poll_stop(it->second);
uv_close((uv_handle_t*) it->second, (uv_close_cb) free);
pollByFD.erase(it);
}
}
#else
uv_thread_t usb_thread;
void USBThreadFn(void*){
while(1) libusb_handle_events(usb_context);
}
#endif
extern "C" void Initialize(Local<Object> target) {
Nan::HandleScope scope;
// Initialize libusb. On error, halt initialization.
int res = libusb_init(&usb_context);
target->Set(Nan::New<String>("INIT_ERROR").ToLocalChecked(), Nan::New<Number>(res));
if (res != 0) {
return;
}
#ifdef USE_POLL
assert(libusb_pollfds_handle_timeouts(usb_context));
libusb_set_pollfd_notifiers(usb_context, onPollFDAdded, onPollFDRemoved, NULL);
const struct libusb_pollfd** pollfds = libusb_get_pollfds(usb_context);
assert(pollfds);
for(const struct libusb_pollfd** i=pollfds; *i; i++){
onPollFDAdded((*i)->fd, (*i)->events, NULL);
}
free(pollfds);
#else
uv_thread_create(&usb_thread, USBThreadFn, NULL);
#endif
Device::Init(target);
Transfer::Init(target);
Nan::SetMethod(target, "setDebugLevel", SetDebugLevel);
Nan::SetMethod(target, "getDeviceList", GetDeviceList);
Nan::SetMethod(target, "_enableHotplugEvents", EnableHotplugEvents);
Nan::SetMethod(target, "_disableHotplugEvents", DisableHotplugEvents);
initConstants(target);
}
NODE_MODULE(usb_bindings, Initialize)
NAN_METHOD(SetDebugLevel) {
Nan::HandleScope scope;
if (info.Length() != 1 || !info[0]->IsUint32() || info[0]->Uint32Value() > 4) {
THROW_BAD_ARGS("Usb::SetDebugLevel argument is invalid. [uint:[0-4]]!")
}
libusb_set_debug(usb_context, info[0]->Uint32Value());
info.GetReturnValue().Set(Nan::Undefined());
}
NAN_METHOD(GetDeviceList) {
Nan::HandleScope scope;
libusb_device **devs;
int cnt = libusb_get_device_list(usb_context, &devs);
CHECK_USB(cnt);
Local<Array> arr = Nan::New<Array>(cnt);
for(int i = 0; i < cnt; i++) {
arr->Set(i, Device::get(devs[i]));
}
libusb_free_device_list(devs, true);
info.GetReturnValue().Set(arr);
}
Nan::Persistent<Object> hotplugThis;
void handleHotplug(std::pair<libusb_device*, libusb_hotplug_event> info){
Nan::HandleScope scope;
libusb_device* dev = info.first;
libusb_hotplug_event event = info.second;
DEBUG_LOG("HandleHotplug %p %i", dev, event);
Local<Value> v8dev = Device::get(dev);
libusb_unref_device(dev);
Local<String> eventName;
if (LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED == event) {
DEBUG_LOG("Device arrived");
eventName = Nan::New("attach").ToLocalChecked();
} else if (LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT == event) {
DEBUG_LOG("Device left");
eventName = Nan::New("detach").ToLocalChecked();
} else {
DEBUG_LOG("Unhandled hotplug event %d\n", event);
return;
}
Local<Value> argv[] = {eventName, v8dev};
Nan::MakeCallback(Nan::New(hotplugThis), "emit", 2, argv);
}
bool hotplugEnabled = 0;
libusb_hotplug_callback_handle hotplugHandle;
UVQueue<std::pair<libusb_device*, libusb_hotplug_event>> hotplugQueue(handleHotplug);
int LIBUSB_CALL hotplug_callback(libusb_context *ctx, libusb_device *dev,
libusb_hotplug_event event, void *user_data) {
libusb_ref_device(dev);
hotplugQueue.post(std::pair<libusb_device*, libusb_hotplug_event>(dev, event));
return 0;
}
NAN_METHOD(EnableHotplugEvents) {
Nan::HandleScope scope;
if (!hotplugEnabled) {
hotplugThis.Reset(info.This());
CHECK_USB(libusb_hotplug_register_callback(usb_context,
(libusb_hotplug_event)(LIBUSB_HOTPLUG_EVENT_DEVICE_ARRIVED | LIBUSB_HOTPLUG_EVENT_DEVICE_LEFT),
(libusb_hotplug_flag)0, LIBUSB_HOTPLUG_MATCH_ANY, LIBUSB_HOTPLUG_MATCH_ANY, LIBUSB_HOTPLUG_MATCH_ANY,
hotplug_callback, NULL, &hotplugHandle));
hotplugQueue.ref();
hotplugEnabled = true;
}
info.GetReturnValue().Set(Nan::Undefined());
}
NAN_METHOD(DisableHotplugEvents) {
Nan::HandleScope scope;
if (hotplugEnabled) {
libusb_hotplug_deregister_callback(usb_context, hotplugHandle);
hotplugQueue.unref();
hotplugEnabled = false;
}
info.GetReturnValue().Set(Nan::Undefined());
}
void initConstants(Local<Object> target){
NODE_DEFINE_CONSTANT(target, LIBUSB_CLASS_PER_INTERFACE);
NODE_DEFINE_CONSTANT(target, LIBUSB_CLASS_AUDIO);
NODE_DEFINE_CONSTANT(target, LIBUSB_CLASS_COMM);
NODE_DEFINE_CONSTANT(target, LIBUSB_CLASS_HID);
NODE_DEFINE_CONSTANT(target, LIBUSB_CLASS_PRINTER);
NODE_DEFINE_CONSTANT(target, LIBUSB_CLASS_PTP);
NODE_DEFINE_CONSTANT(target, LIBUSB_CLASS_MASS_STORAGE);
NODE_DEFINE_CONSTANT(target, LIBUSB_CLASS_HUB);
NODE_DEFINE_CONSTANT(target, LIBUSB_CLASS_DATA);
NODE_DEFINE_CONSTANT(target, LIBUSB_CLASS_WIRELESS);
NODE_DEFINE_CONSTANT(target, LIBUSB_CLASS_APPLICATION);
NODE_DEFINE_CONSTANT(target, LIBUSB_CLASS_VENDOR_SPEC);
// libusb_standard_request
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_GET_STATUS);
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_CLEAR_FEATURE);
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_SET_FEATURE);
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_SET_ADDRESS );
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_GET_DESCRIPTOR);
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_SET_DESCRIPTOR);
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_GET_CONFIGURATION);
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_SET_CONFIGURATION );
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_GET_INTERFACE);
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_SET_INTERFACE);
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_SYNCH_FRAME);
// libusb_descriptor_type
NODE_DEFINE_CONSTANT(target, LIBUSB_DT_DEVICE);
NODE_DEFINE_CONSTANT(target, LIBUSB_DT_CONFIG);
NODE_DEFINE_CONSTANT(target, LIBUSB_DT_STRING);
NODE_DEFINE_CONSTANT(target, LIBUSB_DT_INTERFACE);
NODE_DEFINE_CONSTANT(target, LIBUSB_DT_ENDPOINT);
NODE_DEFINE_CONSTANT(target, LIBUSB_DT_HID);
NODE_DEFINE_CONSTANT(target, LIBUSB_DT_REPORT);
NODE_DEFINE_CONSTANT(target, LIBUSB_DT_PHYSICAL);
NODE_DEFINE_CONSTANT(target, LIBUSB_DT_HUB);
// libusb_endpoint_direction
NODE_DEFINE_CONSTANT(target, LIBUSB_ENDPOINT_IN);
NODE_DEFINE_CONSTANT(target, LIBUSB_ENDPOINT_OUT);
// libusb_transfer_type
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_TYPE_CONTROL);
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_TYPE_ISOCHRONOUS);
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_TYPE_BULK);
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_TYPE_INTERRUPT);
// libusb_iso_sync_type
NODE_DEFINE_CONSTANT(target, LIBUSB_ISO_SYNC_TYPE_NONE);
NODE_DEFINE_CONSTANT(target, LIBUSB_ISO_SYNC_TYPE_ASYNC);
NODE_DEFINE_CONSTANT(target, LIBUSB_ISO_SYNC_TYPE_ADAPTIVE);
NODE_DEFINE_CONSTANT(target, LIBUSB_ISO_SYNC_TYPE_SYNC);
// libusb_iso_usage_type
NODE_DEFINE_CONSTANT(target, LIBUSB_ISO_USAGE_TYPE_DATA);
NODE_DEFINE_CONSTANT(target, LIBUSB_ISO_USAGE_TYPE_FEEDBACK);
NODE_DEFINE_CONSTANT(target, LIBUSB_ISO_USAGE_TYPE_IMPLICIT);
// libusb_transfer_status
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_COMPLETED);
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_ERROR);
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_TIMED_OUT);
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_CANCELLED);
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_STALL);
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_NO_DEVICE);
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_OVERFLOW);
// libusb_transfer_flags
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_SHORT_NOT_OK);
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_FREE_BUFFER);
NODE_DEFINE_CONSTANT(target, LIBUSB_TRANSFER_FREE_TRANSFER);
// libusb_request_type
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_TYPE_STANDARD);
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_TYPE_CLASS);
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_TYPE_VENDOR);
NODE_DEFINE_CONSTANT(target, LIBUSB_REQUEST_TYPE_RESERVED);
// libusb_request_recipient
NODE_DEFINE_CONSTANT(target, LIBUSB_RECIPIENT_DEVICE);
NODE_DEFINE_CONSTANT(target, LIBUSB_RECIPIENT_INTERFACE);
NODE_DEFINE_CONSTANT(target, LIBUSB_RECIPIENT_ENDPOINT);
NODE_DEFINE_CONSTANT(target, LIBUSB_RECIPIENT_OTHER);
NODE_DEFINE_CONSTANT(target, LIBUSB_CONTROL_SETUP_SIZE);
// libusb_error
// Input/output error
NODE_DEFINE_CONSTANT(target, LIBUSB_ERROR_IO);
// Invalid parameter
NODE_DEFINE_CONSTANT(target, LIBUSB_ERROR_INVALID_PARAM);
// Access denied (insufficient permissions)
NODE_DEFINE_CONSTANT(target, LIBUSB_ERROR_ACCESS);
// No such device (it may have been disconnected)
NODE_DEFINE_CONSTANT(target, LIBUSB_ERROR_NO_DEVICE);
// Entity not found
NODE_DEFINE_CONSTANT(target, LIBUSB_ERROR_NOT_FOUND);
// Resource busy
NODE_DEFINE_CONSTANT(target, LIBUSB_ERROR_BUSY);
// Operation timed out
NODE_DEFINE_CONSTANT(target, LIBUSB_ERROR_TIMEOUT);
// Overflow
NODE_DEFINE_CONSTANT(target, LIBUSB_ERROR_OVERFLOW);
// Pipe error
NODE_DEFINE_CONSTANT(target, LIBUSB_ERROR_PIPE);
// System call interrupted (perhaps due to signal)
NODE_DEFINE_CONSTANT(target, LIBUSB_ERROR_INTERRUPTED);
// Insufficient memory
NODE_DEFINE_CONSTANT(target, LIBUSB_ERROR_NO_MEM);
// Operation not supported or unimplemented on this platform
NODE_DEFINE_CONSTANT(target, LIBUSB_ERROR_NOT_SUPPORTED);
// Other error
NODE_DEFINE_CONSTANT(target, LIBUSB_ERROR_OTHER);
}
Local<Value> libusbException(int errorno) {
const char* err = libusb_error_name(errorno);
Local<Value> e = Nan::Error(err);
e->ToObject()->Set(Nan::New<String>("errno").ToLocalChecked(), Nan::New<Integer>(errorno));
return e;
}
|
add error constants
|
add error constants
|
C++
|
mit
|
marcopiraccini/electron-usb,tessel/node-usb,marcopiraccini/electron-usb,marcopiraccini/electron-usb,stberger3040/node-usb,tessel/node-usb,stberger3040/node-usb,stberger3040/node-usb,stberger3040/node-usb,marcopiraccini/electron-usb,nonolith/node-usb,tessel/node-usb,SimplyComplexCo/node-usb,rhuehn/node-usb,rhuehn/node-usb,nonolith/node-usb,SimplyComplexCo/node-usb,stberger3040/node-usb,nonolith/node-usb,rhuehn/node-usb,rhuehn/node-usb,SimplyComplexCo/node-usb,tessel/node-usb,nonolith/node-usb,SimplyComplexCo/node-usb
|
264e09f890959f15125e4c0fb5b091b9e341faae
|
tests/tests.cpp
|
tests/tests.cpp
|
/*
* Copyright 2018 Markus Lindelöw
*
* 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.
*/
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "doctest.h"
#include <tinycsocket.h>
TEST_CASE("TCP test")
{
CHECK(tcs_lib_init() == TINYCSOCKET_SUCCESS);
CHECK(tcs_lib_free() == TINYCSOCKET_SUCCESS);
}
|
/*
* Copyright 2018 Markus Lindelöw
*
* 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.
*/
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "doctest.h"
#include <tinycsocket.h>
TEST_CASE("init test")
{
CHECK(tcs_lib_init() == TINYCSOCKET_SUCCESS);
CHECK(tcs_lib_free() == TINYCSOCKET_SUCCESS);
}
|
Rename init test
|
Rename init test
|
C++
|
mit
|
dosshell/tinycsockets,dosshell/tinycsockets,dosshell/tinycsockets
|
59bad57fe94b4b02422fad8d18826acf7bedfde6
|
Core/Stimuli/OpenGLContextManager.cpp
|
Core/Stimuli/OpenGLContextManager.cpp
|
/**
* OpenGLContextManager.cpp
*
* Created by David Cox on Thu Dec 05 2002.
* Copyright (c) 2002 MIT. All rights reserved.
*/
#include "OpenGLContextManager.h"
#include "StandardVariables.h"
#include "Experiment.h"
#include "Utilities.h"
#include "Event.h"
#include "ComponentRegistry.h"
using namespace mw;
//******************************************************************
//******************************************************************
// Using Cocoa OpenGL
//******************************************************************
// *****************************************************************
//#include "GLWindow.h"
#import <OpenGL/OpenGL.h>
#import <OpenGL/gl.h>
#import <OpenGL/glu.h>
#import <OpenGL/glext.h>
#import <IOKit/graphics/IOGraphicsTypes.h>
#import "StateSystem.h"
//#define kDefaultDisplay 1
// TODO: this may make more sense if it were in the stimDisplay class instead
// since multiple displays will have different VBLs etc. etc.
// This is currently just hacked in to show how it is done and to use
// in the meantime
#define M_BEAM_POSITION_CHECK_INTERVAL_US 2000
#define N_BEAM_POSITION_SUPPORT_CHECKS 50
struct beam_position_args {
CGDirectDisplayID id;
int display_height;
};
// TODO: it should be pretty easy to adapt this to spit out a genuine
// (pre-time-stamped) VBL event that occurs pretty damned close to the
// real VBL
void *announce_beam_position(void *arg){
struct beam_position_args *beam_args = (struct beam_position_args *)arg;
double beam_percent = ((double)CGDisplayBeamPosition(beam_args->id)) /
((double)beam_args->display_height);
if(GlobalCurrentExperiment != NULL){
shared_ptr <StateSystem> state_system = StateSystem::instance();
if(state_system->isRunning()){
beamPosition->setValue(Datum((double)beam_percent));
}
}
return NULL;
}
OpenGLContextManager::OpenGLContextManager() {
mirror_window_active = NO;
fullscreen_window_active = NO;
mirror_window = nil;
mirror_view = nil;
fullscreen_window = nil;
fullscreen_view = nil;
display_sleep_block = kIOPMNullAssertionID;
contexts = [[NSMutableArray alloc] init];
has_fence = false;
glew_initialized = false;
main_display_index = -1;
}
int OpenGLContextManager::getNMonitors() {
NSArray *screens = [NSScreen screens];
if(screens != nil){
return [screens count];
} else {
return 0;
}
}
NSScreen *OpenGLContextManager::_getScreen(const int index){
NSArray *screens = [NSScreen screens];
if(index < 0 || index > [screens count]){
// TODO: better exception
throw SimpleException("Attempt to query an invalid screen");
}
return [screens objectAtIndex: index];
}
NSRect OpenGLContextManager::getDisplayFrame(const int index){
NSScreen *screen = _getScreen(index);
NSRect frame = [screen frame];
return frame;
}
int OpenGLContextManager::getDisplayWidth(const int index) {
NSRect frame = getDisplayFrame(index);
return frame.size.width;
}
int OpenGLContextManager::getDisplayHeight(const int index) {
NSRect frame = getDisplayFrame(index);
return frame.size.height;
}
int OpenGLContextManager::getDisplayRefreshRate(const int index){
std::map<int, double>::iterator rate = display_refresh_rates.find(index);
if (rate == display_refresh_rates.end()) {
return 0;
}
double refresh_rate = (*rate).second;
return (int)refresh_rate;
}
CGDirectDisplayID OpenGLContextManager::_getDisplayID(int screen_number) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSDictionary *device_description = [_getScreen(screen_number) deviceDescription];
CGDirectDisplayID display_id = [[device_description objectForKey:@"NSScreenNumber"] intValue];
[pool drain];
return display_id;
}
void OpenGLContextManager::_measureDisplayRefreshRate(const int index)
{
CGDirectDisplayID display_id = _getDisplayID(index);
CGDisplayModeRef mode = CGDisplayCopyDisplayMode(display_id);
display_refresh_rates[index] = CGDisplayModeGetRefreshRate(mode);
}
CGDirectDisplayID OpenGLContextManager::getMainDisplayID() {
return _getDisplayID(main_display_index);
}
CVReturn OpenGLContextManager::prepareDisplayLinkForMainDisplay(CVDisplayLinkRef displayLink) {
NSOpenGLView *mainView;
if (fullscreen_view) {
mainView = fullscreen_view;
} else {
mainView = mirror_view;
}
CGLContextObj cglContext = (CGLContextObj)[[mainView openGLContext] CGLContextObj];
CGLPixelFormatObj cglPixelFormat = (CGLPixelFormatObj)[[mainView pixelFormat] CGLPixelFormatObj];
return CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext(displayLink, cglContext, cglPixelFormat);
}
int OpenGLContextManager::newMirrorContext(bool sync_to_vbl){
// Determine the width and height of the mirror window
double width = 100.0; // conspicuously wrong defaults
double height = 100.0;
shared_ptr<ComponentRegistry> reg = ComponentRegistry::getSharedRegistry();
shared_ptr<Variable> main_screen_info = reg->getVariable(MAIN_SCREEN_INFO_TAGNAME);
if(main_screen_info != NULL){
Datum info = *main_screen_info;
if(info.hasKey(M_DISPLAY_WIDTH_KEY)
&& info.hasKey(M_DISPLAY_HEIGHT_KEY)
&& info.hasKey(M_MIRROR_WINDOW_BASE_HEIGHT_KEY)){
double display_width, display_height, display_aspect;
display_width = info.getElement(M_DISPLAY_WIDTH_KEY);
display_height = info.getElement(M_DISPLAY_HEIGHT_KEY);
display_aspect = display_width / display_height;
height = (double)info.getElement(M_MIRROR_WINDOW_BASE_HEIGHT_KEY);
width = height * display_aspect;
}
}
NSRect mirror_rect = NSMakeRect(50.0, 50.0, width, height);
mirror_window = [[NSWindow alloc] initWithContentRect:mirror_rect
styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask)
backing:NSBackingStoreBuffered
defer:NO];
NSOpenGLPixelFormatAttribute attrs[] =
{
NSOpenGLPFADoubleBuffer,
0
};
NSOpenGLPixelFormat* pixel_format = [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs];
NSOpenGLContext *opengl_context = [[NSOpenGLContext alloc] initWithFormat:pixel_format shareContext:nil];
if(sync_to_vbl){
GLint swap_int = 1;
[opengl_context setValues: &swap_int forParameter: NSOpenGLCPSwapInterval];
}
NSRect view_rect = NSMakeRect(0.0, 0.0, mirror_rect.size.width, mirror_rect.size.height);
mirror_view = [[NSOpenGLView alloc] initWithFrame:view_rect pixelFormat:pixel_format];
[mirror_window setContentView:mirror_view];
[mirror_view setOpenGLContext:opengl_context];
[opengl_context setView:mirror_view];
[mirror_window makeKeyAndOrderFront:nil];
[contexts addObject:opengl_context];
int context_id = [contexts count] - 1;
[opengl_context release];
[pixel_format release];
_measureDisplayRefreshRate(0);
setCurrent(context_id);
_initGlew();
return context_id;
}
int OpenGLContextManager::newFullscreenContext(int screen_number){
NSScreen *screen = _getScreen(screen_number);
NSRect screen_rect = [screen frame];
// NSLog(@"screen_rect: %g w, %g h, %g x, %g y", screen_rect.size.width,
// screen_rect.size.height,
// screen_rect.origin.x,
// screen_rect.origin.y);
// for some reason, some displays have random values here...
screen_rect.origin.x = 0.0;
screen_rect.origin.y = 0.0;
fullscreen_window = [[NSWindow alloc] initWithContentRect:screen_rect
styleMask:NSBorderlessWindowMask
backing:NSBackingStoreBuffered
defer:NO
screen:screen];
[fullscreen_window setLevel:NSMainMenuWindowLevel+1];
[fullscreen_window setOpaque:YES];
[fullscreen_window setHidesOnDeactivate:NO];
NSOpenGLPixelFormatAttribute attrs[] =
{
NSOpenGLPFADoubleBuffer,
0
};
NSOpenGLPixelFormat* pixel_format = [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs];
NSOpenGLContext *opengl_context = [[NSOpenGLContext alloc] initWithFormat:pixel_format shareContext:nil];
GLint swap_int = 1;
[opengl_context setValues: &swap_int forParameter: NSOpenGLCPSwapInterval];
NSRect view_rect = NSMakeRect(0.0, 0.0, screen_rect.size.width, screen_rect.size.height);
fullscreen_view = [[NSOpenGLView alloc] initWithFrame:view_rect pixelFormat:pixel_format];
[fullscreen_window setContentView:fullscreen_view];
[fullscreen_view setOpenGLContext:opengl_context];
[opengl_context setView:fullscreen_view];
[fullscreen_window makeKeyAndOrderFront:nil];
[contexts addObject:opengl_context];
int context_id = [contexts count] - 1;
[opengl_context release];
[pixel_format release];
_measureDisplayRefreshRate(screen_number);
setCurrent(context_id);
_initGlew();
glGenFencesAPPLE(1, &synchronization_fence);
if(glIsFenceAPPLE(synchronization_fence)){
has_fence = true;
} else {
has_fence = false;
}
if (kIOPMNullAssertionID == display_sleep_block) {
if (kIOReturnSuccess != IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep,
kIOPMAssertionLevelOn,
(CFStringRef)@"MWorks Prevent Display Sleep",
&display_sleep_block)) {
mwarning(M_SERVER_MESSAGE_DOMAIN, "Cannot disable display sleep");
}
}
return context_id;
}
void OpenGLContextManager::setCurrent(int context_id) {
if(context_id < 0 || context_id >= [contexts count]) {
mwarning(M_SERVER_MESSAGE_DOMAIN, "OpenGL Context Manager: no context to set current.");
//NSLog(@"OpenGL Context Manager: no context to set current.");
return;
}
[[contexts objectAtIndex:context_id] makeCurrentContext];
}
void OpenGLContextManager::releaseDisplays() {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
[contexts makeObjectsPerformSelector:@selector(clearDrawable)];
mirror_window_active = NO;
if(mirror_window != nil){
[mirror_window orderOut:nil];
[mirror_window release];
[mirror_view clearGLContext];
[mirror_view release];
mirror_window = nil;
mirror_view = nil;
}
fullscreen_window_active = NO;
if(fullscreen_window != nil){
[fullscreen_window orderOut:nil];
[fullscreen_window release];
[fullscreen_view clearGLContext];
[fullscreen_view release];
fullscreen_window = nil;
fullscreen_view = nil;
}
if (kIOPMNullAssertionID != display_sleep_block) {
(void)IOPMAssertionRelease(display_sleep_block); // Ignore the return code
display_sleep_block = kIOPMNullAssertionID;
}
[contexts removeAllObjects];
[pool drain];
main_display_index = -1;
}
void OpenGLContextManager::flushCurrent() {
[[NSOpenGLContext currentContext] flushBuffer];
}
void OpenGLContextManager::flush(int context_id, bool update) {
if(context_id < 0 || context_id >= [contexts count]){
mwarning(M_SERVER_MESSAGE_DOMAIN, "OpenGL Context Manager: no context to flush");
//NSLog(@"OpenGL Context Manager: no context to flush");
return;
}
//glSetFenceAPPLE(synchronization_fence);
if(update){
[[contexts objectAtIndex:context_id] update];
}
[[contexts objectAtIndex:context_id] flushBuffer];
}
namespace mw {
SINGLETON_INSTANCE_STATIC_DECLARATION(OpenGLContextManager)
}
|
/**
* OpenGLContextManager.cpp
*
* Created by David Cox on Thu Dec 05 2002.
* Copyright (c) 2002 MIT. All rights reserved.
*/
#include "OpenGLContextManager.h"
#include "StandardVariables.h"
#include "Experiment.h"
#include "Utilities.h"
#include "Event.h"
#include "ComponentRegistry.h"
using namespace mw;
//******************************************************************
//******************************************************************
// Using Cocoa OpenGL
//******************************************************************
// *****************************************************************
//#include "GLWindow.h"
#import <OpenGL/OpenGL.h>
#import <OpenGL/gl.h>
#import <OpenGL/glu.h>
#import <OpenGL/glext.h>
#import <IOKit/graphics/IOGraphicsTypes.h>
#import "StateSystem.h"
//#define kDefaultDisplay 1
// TODO: this may make more sense if it were in the stimDisplay class instead
// since multiple displays will have different VBLs etc. etc.
// This is currently just hacked in to show how it is done and to use
// in the meantime
#define M_BEAM_POSITION_CHECK_INTERVAL_US 2000
#define N_BEAM_POSITION_SUPPORT_CHECKS 50
struct beam_position_args {
CGDirectDisplayID id;
int display_height;
};
// TODO: it should be pretty easy to adapt this to spit out a genuine
// (pre-time-stamped) VBL event that occurs pretty damned close to the
// real VBL
void *announce_beam_position(void *arg){
struct beam_position_args *beam_args = (struct beam_position_args *)arg;
double beam_percent = ((double)CGDisplayBeamPosition(beam_args->id)) /
((double)beam_args->display_height);
if(GlobalCurrentExperiment != NULL){
shared_ptr <StateSystem> state_system = StateSystem::instance();
if(state_system->isRunning()){
beamPosition->setValue(Datum((double)beam_percent));
}
}
return NULL;
}
OpenGLContextManager::OpenGLContextManager() {
mirror_window_active = NO;
fullscreen_window_active = NO;
mirror_window = nil;
mirror_view = nil;
fullscreen_window = nil;
fullscreen_view = nil;
display_sleep_block = kIOPMNullAssertionID;
contexts = [[NSMutableArray alloc] init];
has_fence = false;
glew_initialized = false;
main_display_index = -1;
}
int OpenGLContextManager::getNMonitors() {
NSArray *screens = [NSScreen screens];
if(screens != nil){
return [screens count];
} else {
return 0;
}
}
NSScreen *OpenGLContextManager::_getScreen(const int index){
NSArray *screens = [NSScreen screens];
if(index < 0 || index > [screens count]){
// TODO: better exception
throw SimpleException("Attempt to query an invalid screen");
}
return [screens objectAtIndex: index];
}
NSRect OpenGLContextManager::getDisplayFrame(const int index){
NSScreen *screen = _getScreen(index);
NSRect frame = [screen frame];
return frame;
}
int OpenGLContextManager::getDisplayWidth(const int index) {
NSRect frame = getDisplayFrame(index);
return frame.size.width;
}
int OpenGLContextManager::getDisplayHeight(const int index) {
NSRect frame = getDisplayFrame(index);
return frame.size.height;
}
int OpenGLContextManager::getDisplayRefreshRate(const int index){
std::map<int, double>::iterator rate = display_refresh_rates.find(index);
if (rate == display_refresh_rates.end()) {
return 0;
}
double refresh_rate = (*rate).second;
return (int)refresh_rate;
}
CGDirectDisplayID OpenGLContextManager::_getDisplayID(int screen_number) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSDictionary *device_description = [_getScreen(screen_number) deviceDescription];
CGDirectDisplayID display_id = [[device_description objectForKey:@"NSScreenNumber"] intValue];
[pool drain];
return display_id;
}
void OpenGLContextManager::_measureDisplayRefreshRate(const int index)
{
CGDirectDisplayID display_id = _getDisplayID(index);
CGDisplayModeRef mode = CGDisplayCopyDisplayMode(display_id);
display_refresh_rates[index] = CGDisplayModeGetRefreshRate(mode);
}
CGDirectDisplayID OpenGLContextManager::getMainDisplayID() {
return _getDisplayID(main_display_index);
}
CVReturn OpenGLContextManager::prepareDisplayLinkForMainDisplay(CVDisplayLinkRef displayLink) {
NSOpenGLView *mainView;
if (fullscreen_view) {
mainView = fullscreen_view;
} else {
mainView = mirror_view;
}
CGLContextObj cglContext = (CGLContextObj)[[mainView openGLContext] CGLContextObj];
CGLPixelFormatObj cglPixelFormat = (CGLPixelFormatObj)[[mainView pixelFormat] CGLPixelFormatObj];
return CVDisplayLinkSetCurrentCGDisplayFromOpenGLContext(displayLink, cglContext, cglPixelFormat);
}
int OpenGLContextManager::newMirrorContext(bool sync_to_vbl){
// Determine the width and height of the mirror window
double width = 100.0; // conspicuously wrong defaults
double height = 100.0;
shared_ptr<ComponentRegistry> reg = ComponentRegistry::getSharedRegistry();
shared_ptr<Variable> main_screen_info = reg->getVariable(MAIN_SCREEN_INFO_TAGNAME);
if(main_screen_info != NULL){
Datum info = *main_screen_info;
if(info.hasKey(M_DISPLAY_WIDTH_KEY)
&& info.hasKey(M_DISPLAY_HEIGHT_KEY)
&& info.hasKey(M_MIRROR_WINDOW_BASE_HEIGHT_KEY)){
double display_width, display_height, display_aspect;
display_width = info.getElement(M_DISPLAY_WIDTH_KEY);
display_height = info.getElement(M_DISPLAY_HEIGHT_KEY);
display_aspect = display_width / display_height;
height = (double)info.getElement(M_MIRROR_WINDOW_BASE_HEIGHT_KEY);
width = height * display_aspect;
}
}
NSRect mirror_rect = NSMakeRect(50.0, 50.0, width, height);
mirror_window = [[NSWindow alloc] initWithContentRect:mirror_rect
styleMask:(NSTitledWindowMask | NSMiniaturizableWindowMask)
backing:NSBackingStoreBuffered
defer:NO];
NSOpenGLPixelFormatAttribute attrs[] =
{
NSOpenGLPFADoubleBuffer,
0
};
NSOpenGLPixelFormat* pixel_format = [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs];
NSOpenGLContext *opengl_context = [[NSOpenGLContext alloc] initWithFormat:pixel_format shareContext:nil];
if(sync_to_vbl){
GLint swap_int = 1;
[opengl_context setValues: &swap_int forParameter: NSOpenGLCPSwapInterval];
}
NSRect view_rect = NSMakeRect(0.0, 0.0, mirror_rect.size.width, mirror_rect.size.height);
mirror_view = [[NSOpenGLView alloc] initWithFrame:view_rect pixelFormat:pixel_format];
[mirror_window setContentView:mirror_view];
[mirror_view setOpenGLContext:opengl_context];
[opengl_context setView:mirror_view];
[mirror_window makeKeyAndOrderFront:nil];
[contexts addObject:opengl_context];
int context_id = [contexts count] - 1;
[opengl_context release];
[pixel_format release];
_measureDisplayRefreshRate(0);
setCurrent(context_id);
_initGlew();
return context_id;
}
int OpenGLContextManager::newFullscreenContext(int screen_number){
NSScreen *screen = _getScreen(screen_number);
NSRect screen_rect = [screen frame];
// NSLog(@"screen_rect: %g w, %g h, %g x, %g y", screen_rect.size.width,
// screen_rect.size.height,
// screen_rect.origin.x,
// screen_rect.origin.y);
// for some reason, some displays have random values here...
screen_rect.origin.x = 0.0;
screen_rect.origin.y = 0.0;
fullscreen_window = [[NSWindow alloc] initWithContentRect:screen_rect
styleMask:NSBorderlessWindowMask
backing:NSBackingStoreBuffered
defer:NO
screen:screen];
[fullscreen_window setLevel:NSMainMenuWindowLevel+1];
[fullscreen_window setOpaque:YES];
[fullscreen_window setHidesOnDeactivate:NO];
//[fullscreen_window setAcceptsMouseMovedEvents:YES];
NSOpenGLPixelFormatAttribute attrs[] =
{
NSOpenGLPFADoubleBuffer,
0
};
NSOpenGLPixelFormat* pixel_format = [[NSOpenGLPixelFormat alloc] initWithAttributes:attrs];
NSOpenGLContext *opengl_context = [[NSOpenGLContext alloc] initWithFormat:pixel_format shareContext:nil];
GLint swap_int = 1;
[opengl_context setValues: &swap_int forParameter: NSOpenGLCPSwapInterval];
NSRect view_rect = NSMakeRect(0.0, 0.0, screen_rect.size.width, screen_rect.size.height);
fullscreen_view = [[NSOpenGLView alloc] initWithFrame:view_rect pixelFormat:pixel_format];
[fullscreen_window setContentView:fullscreen_view];
[fullscreen_view setOpenGLContext:opengl_context];
[opengl_context setView:fullscreen_view];
[fullscreen_window makeKeyAndOrderFront:nil];
[contexts addObject:opengl_context];
int context_id = [contexts count] - 1;
[opengl_context release];
[pixel_format release];
_measureDisplayRefreshRate(screen_number);
setCurrent(context_id);
_initGlew();
glGenFencesAPPLE(1, &synchronization_fence);
if(glIsFenceAPPLE(synchronization_fence)){
has_fence = true;
} else {
has_fence = false;
}
if (kIOPMNullAssertionID == display_sleep_block) {
if (kIOReturnSuccess != IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep,
kIOPMAssertionLevelOn,
(CFStringRef)@"MWorks Prevent Display Sleep",
&display_sleep_block)) {
mwarning(M_SERVER_MESSAGE_DOMAIN, "Cannot disable display sleep");
}
}
return context_id;
}
void OpenGLContextManager::setCurrent(int context_id) {
if(context_id < 0 || context_id >= [contexts count]) {
mwarning(M_SERVER_MESSAGE_DOMAIN, "OpenGL Context Manager: no context to set current.");
//NSLog(@"OpenGL Context Manager: no context to set current.");
return;
}
[[contexts objectAtIndex:context_id] makeCurrentContext];
}
void OpenGLContextManager::releaseDisplays() {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
[contexts makeObjectsPerformSelector:@selector(clearDrawable)];
mirror_window_active = NO;
if(mirror_window != nil){
[mirror_window orderOut:nil];
[mirror_window release];
[mirror_view clearGLContext];
[mirror_view release];
mirror_window = nil;
mirror_view = nil;
}
fullscreen_window_active = NO;
if(fullscreen_window != nil){
[fullscreen_window orderOut:nil];
[fullscreen_window release];
[fullscreen_view clearGLContext];
[fullscreen_view release];
fullscreen_window = nil;
fullscreen_view = nil;
}
if (kIOPMNullAssertionID != display_sleep_block) {
(void)IOPMAssertionRelease(display_sleep_block); // Ignore the return code
display_sleep_block = kIOPMNullAssertionID;
}
[contexts removeAllObjects];
[pool drain];
main_display_index = -1;
}
void OpenGLContextManager::flushCurrent() {
[[NSOpenGLContext currentContext] flushBuffer];
}
void OpenGLContextManager::flush(int context_id, bool update) {
if(context_id < 0 || context_id >= [contexts count]){
mwarning(M_SERVER_MESSAGE_DOMAIN, "OpenGL Context Manager: no context to flush");
//NSLog(@"OpenGL Context Manager: no context to flush");
return;
}
//glSetFenceAPPLE(synchronization_fence);
if(update){
[[contexts objectAtIndex:context_id] update];
}
[[contexts objectAtIndex:context_id] flushBuffer];
}
namespace mw {
SINGLETON_INSTANCE_STATIC_DECLARATION(OpenGLContextManager)
}
|
Allow the fullscreen opengl context to accept mouse events (useful for plugins that allow for manual exploratory receptive field mapping). Effectively no consequence unless a plugin registers to receive these events.
|
Allow the fullscreen opengl context to accept
mouse events (useful for plugins that allow for
manual exploratory receptive field mapping).
Effectively no consequence unless a plugin
registers to receive these events.
|
C++
|
mit
|
mworks/mworks,mworks/mworks,mworks/mworks,mworks/mworks,mworks/mworks,mworks/mworks,mworks/mworks,mworks/mworks,mworks/mworks
|
4d971021467dfad3f4e763dd19996cb6edcfd77a
|
src/pstring.cxx
|
src/pstring.cxx
|
/*
* String allocation.
*
* author: Max Kellermann <[email protected]>
*/
#include "pool.hxx"
#include "util/CharUtil.hxx"
#include <algorithm>
#include <assert.h>
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
static char *
Copy(char *dest, const char *src, size_t n)
{
return (char *)mempcpy(dest, src, n);
}
static char *
CopyLower(char *dest, const char *src, size_t n)
{
return std::transform(src, src + n, dest, ToLowerASCII);
}
void *
p_memdup_impl(struct pool *pool, const void *src, size_t length
TRACE_ARGS_DECL)
{
void *dest = p_malloc_fwd(pool, length);
memcpy(dest, src, length);
return dest;
}
char *
p_strdup_impl(struct pool *pool, const char *src
TRACE_ARGS_DECL)
{
return (char *)p_memdup_fwd(pool, src, strlen(src) + 1);
}
char *
p_strdup_lower_impl(struct pool *pool, const char *src
TRACE_ARGS_DECL)
{
return p_strndup_lower_fwd(pool, src, strlen(src));
}
char *
p_strndup_impl(struct pool *pool, const char *src, size_t length TRACE_ARGS_DECL)
{
char *dest = (char *)p_malloc_fwd(pool, length + 1);
*Copy(dest, src, length) = 0;
return dest;
}
char *
p_strndup_lower_impl(struct pool *pool, const char *src, size_t length
TRACE_ARGS_DECL)
{
char *dest = (char *)p_malloc_fwd(pool, length + 1);
*CopyLower(dest, src, length) = 0;
return dest;
}
char * gcc_malloc
p_sprintf(struct pool *pool, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
size_t length = (size_t)vsnprintf(nullptr, 0, fmt, ap) + 1;
va_end(ap);
char *p = (char *)p_malloc(pool, length);
va_start(ap, fmt);
gcc_unused int length2 = vsnprintf(p, length, fmt, ap);
va_end(ap);
assert((size_t)length2 + 1 == length);
return p;
}
char * gcc_malloc
p_strcat(struct pool *pool, const char *first, ...)
{
va_list ap;
size_t length = 1;
va_start(ap, first);
for (const char *s = first; s != nullptr; s = va_arg(ap, const char *))
length += strlen(s);
va_end(ap);
char *result = (char *)p_malloc(pool, length);
va_start(ap, first);
char *p = result;
for (const char *s = first; s != nullptr; s = va_arg(ap, const char *))
p = Copy(p, s, strlen(s));
va_end(ap);
*p = 0;
return result;
}
char * gcc_malloc
p_strncat(struct pool *pool, const char *first, size_t first_length, ...)
{
va_list ap;
size_t length = first_length + 1;
va_start(ap, first_length);
for (const char *s = va_arg(ap, const char *); s != nullptr;
s = va_arg(ap, const char *))
length += va_arg(ap, size_t);
va_end(ap);
char *result = (char *)p_malloc(pool, length);
char *p = result;
p = Copy(p, first, first_length);
va_start(ap, first_length);
for (const char *s = va_arg(ap, const char *); s != nullptr;
s = va_arg(ap, const char *))
p = Copy(p, s, va_arg(ap, size_t));
va_end(ap);
*p = 0;
return result;
}
|
/*
* String allocation.
*
* author: Max Kellermann <[email protected]>
*/
#include "pool.hxx"
#include "util/CharUtil.hxx"
#include <algorithm>
#include <assert.h>
#include <string.h>
#include <stdarg.h>
#include <stdio.h>
static char *
Copy(char *dest, const char *src, size_t n)
{
return std::copy_n(src, n, dest);
}
static char *
CopyLower(char *dest, const char *src, size_t n)
{
return std::transform(src, src + n, dest, ToLowerASCII);
}
void *
p_memdup_impl(struct pool *pool, const void *src, size_t length
TRACE_ARGS_DECL)
{
void *dest = p_malloc_fwd(pool, length);
memcpy(dest, src, length);
return dest;
}
char *
p_strdup_impl(struct pool *pool, const char *src
TRACE_ARGS_DECL)
{
return (char *)p_memdup_fwd(pool, src, strlen(src) + 1);
}
char *
p_strdup_lower_impl(struct pool *pool, const char *src
TRACE_ARGS_DECL)
{
return p_strndup_lower_fwd(pool, src, strlen(src));
}
char *
p_strndup_impl(struct pool *pool, const char *src, size_t length TRACE_ARGS_DECL)
{
char *dest = (char *)p_malloc_fwd(pool, length + 1);
*Copy(dest, src, length) = 0;
return dest;
}
char *
p_strndup_lower_impl(struct pool *pool, const char *src, size_t length
TRACE_ARGS_DECL)
{
char *dest = (char *)p_malloc_fwd(pool, length + 1);
*CopyLower(dest, src, length) = 0;
return dest;
}
char * gcc_malloc
p_sprintf(struct pool *pool, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
size_t length = (size_t)vsnprintf(nullptr, 0, fmt, ap) + 1;
va_end(ap);
char *p = (char *)p_malloc(pool, length);
va_start(ap, fmt);
gcc_unused int length2 = vsnprintf(p, length, fmt, ap);
va_end(ap);
assert((size_t)length2 + 1 == length);
return p;
}
char * gcc_malloc
p_strcat(struct pool *pool, const char *first, ...)
{
va_list ap;
size_t length = 1;
va_start(ap, first);
for (const char *s = first; s != nullptr; s = va_arg(ap, const char *))
length += strlen(s);
va_end(ap);
char *result = (char *)p_malloc(pool, length);
va_start(ap, first);
char *p = result;
for (const char *s = first; s != nullptr; s = va_arg(ap, const char *))
p = Copy(p, s, strlen(s));
va_end(ap);
*p = 0;
return result;
}
char * gcc_malloc
p_strncat(struct pool *pool, const char *first, size_t first_length, ...)
{
va_list ap;
size_t length = first_length + 1;
va_start(ap, first_length);
for (const char *s = va_arg(ap, const char *); s != nullptr;
s = va_arg(ap, const char *))
length += va_arg(ap, size_t);
va_end(ap);
char *result = (char *)p_malloc(pool, length);
char *p = result;
p = Copy(p, first, first_length);
va_start(ap, first_length);
for (const char *s = va_arg(ap, const char *); s != nullptr;
s = va_arg(ap, const char *))
p = Copy(p, s, va_arg(ap, size_t));
va_end(ap);
*p = 0;
return result;
}
|
use std::copy_n()
|
pstring: use std::copy_n()
|
C++
|
bsd-2-clause
|
CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy,CM4all/beng-proxy
|
b52e0241c03a257f96bd9c77788eff5b1a7fd437
|
lib/CodeGen/PHIElimination.cpp
|
lib/CodeGen/PHIElimination.cpp
|
//===-- PhiElimination.cpp - Eliminate PHI nodes by inserting copies ------===//
//
// This pass eliminates machine instruction PHI nodes by inserting copy
// instructions. This destroys SSA information, but is the desired input for
// some register allocators.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/SSARegMap.h"
#include "llvm/CodeGen/LiveVariables.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Support/CFG.h"
namespace {
struct PNE : public MachineFunctionPass {
bool runOnMachineFunction(MachineFunction &Fn) {
bool Changed = false;
// Eliminate PHI instructions by inserting copies into predecessor blocks.
//
for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Changed |= EliminatePHINodes(Fn, *I);
//std::cerr << "AFTER PHI NODE ELIM:\n";
//Fn.dump();
return Changed;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addPreserved<LiveVariables>();
MachineFunctionPass::getAnalysisUsage(AU);
}
private:
/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
/// in predecessor basic blocks.
///
bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
};
RegisterPass<PNE> X("phi-node-elimination",
"Eliminate PHI nodes for register allocation");
}
const PassInfo *PHIEliminationID = X.getPassInfo();
/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
/// predecessor basic blocks.
///
bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) {
if (MBB.empty() || MBB.front()->getOpcode() != TargetInstrInfo::PHI)
return false; // Quick exit for normal case...
LiveVariables *LV = getAnalysisToUpdate<LiveVariables>();
const TargetInstrInfo &MII = MF.getTarget().getInstrInfo();
const MRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
while (MBB.front()->getOpcode() == TargetInstrInfo::PHI) {
MachineInstr *MI = MBB.front();
// Unlink the PHI node from the basic block... but don't delete the PHI yet
MBB.erase(MBB.begin());
assert(MI->getOperand(0).isVirtualRegister() &&
"PHI node doesn't write virt reg?");
unsigned DestReg = MI->getOperand(0).getAllocatedRegNum();
// Create a new register for the incoming PHI arguments
const TargetRegisterClass *RC = MF.getSSARegMap()->getRegClass(DestReg);
unsigned IncomingReg = MF.getSSARegMap()->createVirtualRegister(RC);
// Insert a register to register copy in the top of the current block (but
// after any remaining phi nodes) which copies the new incoming register
// into the phi node destination.
//
MachineBasicBlock::iterator AfterPHIsIt = MBB.begin();
while (AfterPHIsIt != MBB.end() &&
(*AfterPHIsIt)->getOpcode() == TargetInstrInfo::PHI)
++AfterPHIsIt; // Skip over all of the PHI nodes...
RegInfo->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC);
// Update live variable information if there is any...
if (LV) {
MachineInstr *PHICopy = *(AfterPHIsIt-1);
// Add information to LiveVariables to know that the incoming value is
// dead. This says that the register is dead, not killed, because we
// cannot use the live variable information to indicate that the variable
// is defined in multiple entry blocks. Instead, we pretend that this
// instruction defined it and killed it at the same time.
//
LV->addVirtualRegisterDead(IncomingReg, &MBB, PHICopy);
// Since we are going to be deleting the PHI node, if it is the last use
// of any registers, or if the value itself is dead, we need to move this
// information over to the new copy we just inserted...
//
std::pair<LiveVariables::killed_iterator, LiveVariables::killed_iterator>
RKs = LV->killed_range(MI);
std::vector<std::pair<MachineInstr*, unsigned> > Range;
if (RKs.first != RKs.second) {
// Copy the range into a vector...
Range.assign(RKs.first, RKs.second);
// Delete the range...
LV->removeVirtualRegistersKilled(RKs.first, RKs.second);
// Add all of the kills back, which will update the appropriate info...
for (unsigned i = 0, e = Range.size(); i != e; ++i)
LV->addVirtualRegisterKilled(Range[i].second, &MBB, PHICopy);
}
RKs = LV->dead_range(MI);
if (RKs.first != RKs.second) {
// Works as above...
Range.assign(RKs.first, RKs.second);
LV->removeVirtualRegistersDead(RKs.first, RKs.second);
for (unsigned i = 0, e = Range.size(); i != e; ++i)
LV->addVirtualRegisterDead(Range[i].second, &MBB, PHICopy);
}
}
// Now loop over all of the incoming arguments, changing them to copy into
// the IncomingReg register in the corresponding predecessor basic block.
//
for (int i = MI->getNumOperands() - 1; i >= 2; i-=2) {
MachineOperand &opVal = MI->getOperand(i-1);
// Get the MachineBasicBlock equivalent of the BasicBlock that is the
// source path the PHI.
MachineBasicBlock &opBlock = *MI->getOperand(i).getMachineBasicBlock();
// Figure out where to insert the copy, which is at the end of the
// predecessor basic block, but before any terminator/branch
// instructions...
MachineBasicBlock::iterator I = opBlock.end();
if (I != opBlock.begin()) { // Handle empty blocks
--I;
// must backtrack over ALL the branches in the previous block
while (MII.isTerminatorInstr((*I)->getOpcode()) &&
I != opBlock.begin())
--I;
// move back to the first branch instruction so new instructions
// are inserted right in front of it and not in front of a non-branch
if (!MII.isTerminatorInstr((*I)->getOpcode()))
++I;
}
// Check to make sure we haven't already emitted the copy for this block.
// This can happen because PHI nodes may have multiple entries for the
// same basic block. It doesn't matter which entry we use though, because
// all incoming values are guaranteed to be the same for a particular bb.
//
// If we emitted a copy for this basic block already, it will be right
// where we want to insert one now. Just check for a definition of the
// register we are interested in!
//
bool HaveNotEmitted = true;
if (I != opBlock.begin()) {
MachineInstr *PrevInst = *(I-1);
for (unsigned i = 0, e = PrevInst->getNumOperands(); i != e; ++i) {
MachineOperand &MO = PrevInst->getOperand(i);
if (MO.isVirtualRegister() && MO.getReg() == IncomingReg)
if (MO.opIsDef() || MO.opIsDefAndUse()) {
HaveNotEmitted = false;
break;
}
}
}
if (HaveNotEmitted) { // If the copy has not already been emitted, do it.
assert(opVal.isVirtualRegister() &&
"Machine PHI Operands must all be virtual registers!");
unsigned SrcReg = opVal.getReg();
RegInfo->copyRegToReg(opBlock, I, IncomingReg, SrcReg, RC);
// Now update live variable information if we have it.
if (LV) {
// We want to be able to insert a kill of the register if this PHI
// (aka, the copy we just inserted) is the last use of the source
// value. Live variable analysis conservatively handles this by
// saying that the value is live until the end of the block the PHI
// entry lives in. If the value really is dead at the PHI copy, there
// will be no successor blocks which have the value live-in.
//
// Check to see if the copy is the last use, and if so, update the
// live variables information so that it knows the copy source
// instruction kills the incoming value.
//
LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg);
// Loop over all of the successors of the basic block, checking to
// see if the value is either live in the block, or if it is killed
// in the block.
//
bool ValueIsLive = false;
BasicBlock *BB = opBlock.getBasicBlock();
for (succ_iterator SI = succ_begin(BB), E = succ_end(BB);
SI != E; ++SI) {
const std::pair<MachineBasicBlock*, unsigned> &
SuccInfo = LV->getBasicBlockInfo(*SI);
// Is it alive in this successor?
unsigned SuccIdx = SuccInfo.second;
if (SuccIdx < InRegVI.AliveBlocks.size() &&
InRegVI.AliveBlocks[SuccIdx]) {
ValueIsLive = true;
break;
}
// Is it killed in this successor?
MachineBasicBlock *MBB = SuccInfo.first;
for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
if (InRegVI.Kills[i].first == MBB) {
ValueIsLive = true;
break;
}
}
// Okay, if we now know that the value is not live out of the block,
// we can add a kill marker to the copy we inserted saying that it
// kills the incoming value!
//
if (!ValueIsLive) {
// One more complication to worry about. There may actually be
// multiple PHI nodes using this value on this branch. If we aren't
// careful, the first PHI node will end up killing the value, not
// letting it get the to the copy for the final PHI node in the
// block. Therefore we have to check to see if there is already a
// kill in this block, and if so, extend the lifetime to our new
// copy.
//
for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
if (InRegVI.Kills[i].first == &opBlock) {
std::pair<LiveVariables::killed_iterator,
LiveVariables::killed_iterator> Range
= LV->killed_range(InRegVI.Kills[i].second);
LV->removeVirtualRegistersKilled(Range.first, Range.second);
break;
}
LV->addVirtualRegisterKilled(SrcReg, &opBlock, *(I-1));
}
}
}
}
// really delete the PHI instruction now!
delete MI;
}
return true;
}
|
//===-- PhiElimination.cpp - Eliminate PHI nodes by inserting copies ------===//
//
// This pass eliminates machine instruction PHI nodes by inserting copy
// instructions. This destroys SSA information, but is the desired input for
// some register allocators.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/SSARegMap.h"
#include "llvm/CodeGen/LiveVariables.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/Support/CFG.h"
namespace {
struct PNE : public MachineFunctionPass {
bool runOnMachineFunction(MachineFunction &Fn) {
bool Changed = false;
// Eliminate PHI instructions by inserting copies into predecessor blocks.
//
for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)
Changed |= EliminatePHINodes(Fn, *I);
//std::cerr << "AFTER PHI NODE ELIM:\n";
//Fn.dump();
return Changed;
}
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addPreserved<LiveVariables>();
MachineFunctionPass::getAnalysisUsage(AU);
}
private:
/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions
/// in predecessor basic blocks.
///
bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);
};
RegisterPass<PNE> X("phi-node-elimination",
"Eliminate PHI nodes for register allocation");
}
const PassInfo *PHIEliminationID = X.getPassInfo();
/// EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in
/// predecessor basic blocks.
///
bool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) {
if (MBB.empty() || MBB.front()->getOpcode() != TargetInstrInfo::PHI)
return false; // Quick exit for normal case...
LiveVariables *LV = getAnalysisToUpdate<LiveVariables>();
const TargetInstrInfo &MII = MF.getTarget().getInstrInfo();
const MRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();
while (MBB.front()->getOpcode() == TargetInstrInfo::PHI) {
MachineInstr *MI = MBB.front();
// Unlink the PHI node from the basic block... but don't delete the PHI yet
MBB.erase(MBB.begin());
assert(MI->getOperand(0).isVirtualRegister() &&
"PHI node doesn't write virt reg?");
unsigned DestReg = MI->getOperand(0).getAllocatedRegNum();
// Create a new register for the incoming PHI arguments
const TargetRegisterClass *RC = MF.getSSARegMap()->getRegClass(DestReg);
unsigned IncomingReg = MF.getSSARegMap()->createVirtualRegister(RC);
// Insert a register to register copy in the top of the current block (but
// after any remaining phi nodes) which copies the new incoming register
// into the phi node destination.
//
MachineBasicBlock::iterator AfterPHIsIt = MBB.begin();
while (AfterPHIsIt != MBB.end() &&
(*AfterPHIsIt)->getOpcode() == TargetInstrInfo::PHI)
++AfterPHIsIt; // Skip over all of the PHI nodes...
RegInfo->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC);
// Update live variable information if there is any...
if (LV) {
MachineInstr *PHICopy = *(AfterPHIsIt-1);
// Add information to LiveVariables to know that the incoming value is
// killed. Note that because the value is defined in several places (once
// each for each incoming block), the "def" block and instruction fields
// for the VarInfo is not filled in.
//
LV->addVirtualRegisterKilled(IncomingReg, &MBB, PHICopy);
// Since we are going to be deleting the PHI node, if it is the last use
// of any registers, or if the value itself is dead, we need to move this
// information over to the new copy we just inserted...
//
std::pair<LiveVariables::killed_iterator, LiveVariables::killed_iterator>
RKs = LV->killed_range(MI);
std::vector<std::pair<MachineInstr*, unsigned> > Range;
if (RKs.first != RKs.second) {
// Copy the range into a vector...
Range.assign(RKs.first, RKs.second);
// Delete the range...
LV->removeVirtualRegistersKilled(RKs.first, RKs.second);
// Add all of the kills back, which will update the appropriate info...
for (unsigned i = 0, e = Range.size(); i != e; ++i)
LV->addVirtualRegisterKilled(Range[i].second, &MBB, PHICopy);
}
RKs = LV->dead_range(MI);
if (RKs.first != RKs.second) {
// Works as above...
Range.assign(RKs.first, RKs.second);
LV->removeVirtualRegistersDead(RKs.first, RKs.second);
for (unsigned i = 0, e = Range.size(); i != e; ++i)
LV->addVirtualRegisterDead(Range[i].second, &MBB, PHICopy);
}
}
// Now loop over all of the incoming arguments, changing them to copy into
// the IncomingReg register in the corresponding predecessor basic block.
//
for (int i = MI->getNumOperands() - 1; i >= 2; i-=2) {
MachineOperand &opVal = MI->getOperand(i-1);
// Get the MachineBasicBlock equivalent of the BasicBlock that is the
// source path the PHI.
MachineBasicBlock &opBlock = *MI->getOperand(i).getMachineBasicBlock();
// Figure out where to insert the copy, which is at the end of the
// predecessor basic block, but before any terminator/branch
// instructions...
MachineBasicBlock::iterator I = opBlock.end();
if (I != opBlock.begin()) { // Handle empty blocks
--I;
// must backtrack over ALL the branches in the previous block
while (MII.isTerminatorInstr((*I)->getOpcode()) &&
I != opBlock.begin())
--I;
// move back to the first branch instruction so new instructions
// are inserted right in front of it and not in front of a non-branch
if (!MII.isTerminatorInstr((*I)->getOpcode()))
++I;
}
// Check to make sure we haven't already emitted the copy for this block.
// This can happen because PHI nodes may have multiple entries for the
// same basic block. It doesn't matter which entry we use though, because
// all incoming values are guaranteed to be the same for a particular bb.
//
// If we emitted a copy for this basic block already, it will be right
// where we want to insert one now. Just check for a definition of the
// register we are interested in!
//
bool HaveNotEmitted = true;
if (I != opBlock.begin()) {
MachineInstr *PrevInst = *(I-1);
for (unsigned i = 0, e = PrevInst->getNumOperands(); i != e; ++i) {
MachineOperand &MO = PrevInst->getOperand(i);
if (MO.isVirtualRegister() && MO.getReg() == IncomingReg)
if (MO.opIsDef() || MO.opIsDefAndUse()) {
HaveNotEmitted = false;
break;
}
}
}
if (HaveNotEmitted) { // If the copy has not already been emitted, do it.
assert(opVal.isVirtualRegister() &&
"Machine PHI Operands must all be virtual registers!");
unsigned SrcReg = opVal.getReg();
RegInfo->copyRegToReg(opBlock, I, IncomingReg, SrcReg, RC);
// Now update live variable information if we have it.
if (LV) {
// We want to be able to insert a kill of the register if this PHI
// (aka, the copy we just inserted) is the last use of the source
// value. Live variable analysis conservatively handles this by
// saying that the value is live until the end of the block the PHI
// entry lives in. If the value really is dead at the PHI copy, there
// will be no successor blocks which have the value live-in.
//
// Check to see if the copy is the last use, and if so, update the
// live variables information so that it knows the copy source
// instruction kills the incoming value.
//
LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg);
// Loop over all of the successors of the basic block, checking to
// see if the value is either live in the block, or if it is killed
// in the block.
//
bool ValueIsLive = false;
BasicBlock *BB = opBlock.getBasicBlock();
for (succ_iterator SI = succ_begin(BB), E = succ_end(BB);
SI != E; ++SI) {
const std::pair<MachineBasicBlock*, unsigned> &
SuccInfo = LV->getBasicBlockInfo(*SI);
// Is it alive in this successor?
unsigned SuccIdx = SuccInfo.second;
if (SuccIdx < InRegVI.AliveBlocks.size() &&
InRegVI.AliveBlocks[SuccIdx]) {
ValueIsLive = true;
break;
}
// Is it killed in this successor?
MachineBasicBlock *MBB = SuccInfo.first;
for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
if (InRegVI.Kills[i].first == MBB) {
ValueIsLive = true;
break;
}
}
// Okay, if we now know that the value is not live out of the block,
// we can add a kill marker to the copy we inserted saying that it
// kills the incoming value!
//
if (!ValueIsLive) {
// One more complication to worry about. There may actually be
// multiple PHI nodes using this value on this branch. If we aren't
// careful, the first PHI node will end up killing the value, not
// letting it get the to the copy for the final PHI node in the
// block. Therefore we have to check to see if there is already a
// kill in this block, and if so, extend the lifetime to our new
// copy.
//
for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)
if (InRegVI.Kills[i].first == &opBlock) {
std::pair<LiveVariables::killed_iterator,
LiveVariables::killed_iterator> Range
= LV->killed_range(InRegVI.Kills[i].second);
LV->removeVirtualRegistersKilled(Range.first, Range.second);
break;
}
LV->addVirtualRegisterKilled(SrcReg, &opBlock, *(I-1));
}
}
}
}
// really delete the PHI instruction now!
delete MI;
}
return true;
}
|
Use a kill, not a dead definition, update comment
|
Use a kill, not a dead definition, update comment
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@6131 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
apache-2.0
|
llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,chubbymaggie/asap,dslab-epfl/asap,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,chubbymaggie/asap,llvm-mirror/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,chubbymaggie/asap,apple/swift-llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,apple/swift-llvm,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,apple/swift-llvm
|
a61fab8c6d11bddeacec99c4b21278e1008fd08c
|
lib/Transforms/Scalar/ADCE.cpp
|
lib/Transforms/Scalar/ADCE.cpp
|
//===- ADCE.cpp - Code to perform aggressive dead code elimination --------===//
//
// This file implements "aggressive" dead code elimination. ADCE is DCe where
// values are assumed to be dead until proven otherwise. This is similar to
// SCCP, except applied to the liveness of values.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Type.h"
#include "llvm/Analysis/Dominators.h"
#include "llvm/iTerminators.h"
#include "llvm/iPHINode.h"
#include "llvm/Constant.h"
#include "llvm/Support/CFG.h"
#include "Support/STLExtras.h"
#include "Support/DepthFirstIterator.h"
#include "Support/StatisticReporter.h"
#include <algorithm>
#include <iostream>
using std::cerr;
using std::vector;
static Statistic<> NumBlockRemoved("adce\t\t- Number of basic blocks removed");
static Statistic<> NumInstRemoved ("adce\t\t- Number of instructions removed");
namespace {
//===----------------------------------------------------------------------===//
// ADCE Class
//
// This class does all of the work of Aggressive Dead Code Elimination.
// It's public interface consists of a constructor and a doADCE() method.
//
class ADCE : public FunctionPass {
Function *Func; // The function that we are working on
std::vector<Instruction*> WorkList; // Instructions that just became live
std::set<Instruction*> LiveSet; // The set of live instructions
//===--------------------------------------------------------------------===//
// The public interface for this class
//
public:
// Execute the Aggressive Dead Code Elimination Algorithm
//
virtual bool runOnFunction(Function &F) {
Func = &F;
bool Changed = doADCE();
assert(WorkList.empty());
LiveSet.clear();
return Changed;
}
// getAnalysisUsage - We require post dominance frontiers (aka Control
// Dependence Graph)
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired(PostDominatorTree::ID);
AU.addRequired(PostDominanceFrontier::ID);
}
//===--------------------------------------------------------------------===//
// The implementation of this class
//
private:
// doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
// true if the function was modified.
//
bool doADCE();
void markBlockAlive(BasicBlock *BB);
inline void markInstructionLive(Instruction *I) {
if (LiveSet.count(I)) return;
DEBUG(cerr << "Insn Live: " << I);
LiveSet.insert(I);
WorkList.push_back(I);
}
inline void markTerminatorLive(const BasicBlock *BB) {
DEBUG(cerr << "Terminat Live: " << BB->getTerminator());
markInstructionLive((Instruction*)BB->getTerminator());
}
};
RegisterOpt<ADCE> X("adce", "Aggressive Dead Code Elimination");
} // End of anonymous namespace
Pass *createAggressiveDCEPass() { return new ADCE(); }
void ADCE::markBlockAlive(BasicBlock *BB) {
// Mark the basic block as being newly ALIVE... and mark all branches that
// this block is control dependant on as being alive also...
//
PostDominanceFrontier &CDG = getAnalysis<PostDominanceFrontier>();
PostDominanceFrontier::const_iterator It = CDG.find(BB);
if (It != CDG.end()) {
// Get the blocks that this node is control dependant on...
const PostDominanceFrontier::DomSetType &CDB = It->second;
for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live
bind_obj(this, &ADCE::markTerminatorLive));
}
// If this basic block is live, then the terminator must be as well!
markTerminatorLive(BB);
}
// doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
// true if the function was modified.
//
bool ADCE::doADCE() {
bool MadeChanges = false;
// Iterate over all of the instructions in the function, eliminating trivially
// dead instructions, and marking instructions live that are known to be
// needed. Perform the walk in depth first order so that we avoid marking any
// instructions live in basic blocks that are unreachable. These blocks will
// be eliminated later, along with the instructions inside.
//
for (df_iterator<Function*> BBI = df_begin(Func), BBE = df_end(Func);
BBI != BBE; ++BBI) {
BasicBlock *BB = *BBI;
for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
if (II->hasSideEffects() || II->getOpcode() == Instruction::Ret) {
markInstructionLive(II);
++II; // Increment the inst iterator if the inst wasn't deleted
} else if (isInstructionTriviallyDead(II)) {
// Remove the instruction from it's basic block...
II = BB->getInstList().erase(II);
++NumInstRemoved;
MadeChanges = true;
} else {
++II; // Increment the inst iterator if the inst wasn't deleted
}
}
}
DEBUG(cerr << "Processing work list\n");
// AliveBlocks - Set of basic blocks that we know have instructions that are
// alive in them...
//
std::set<BasicBlock*> AliveBlocks;
// Process the work list of instructions that just became live... if they
// became live, then that means that all of their operands are neccesary as
// well... make them live as well.
//
while (!WorkList.empty()) {
Instruction *I = WorkList.back(); // Get an instruction that became live...
WorkList.pop_back();
BasicBlock *BB = I->getParent();
if (!AliveBlocks.count(BB)) { // Basic block not alive yet...
AliveBlocks.insert(BB); // Block is now ALIVE!
markBlockAlive(BB); // Make it so now!
}
// PHI nodes are a special case, because the incoming values are actually
// defined in the predecessor nodes of this block, meaning that the PHI
// makes the predecessors alive.
//
if (PHINode *PN = dyn_cast<PHINode>(I))
for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI)
if (!AliveBlocks.count(*PI)) {
AliveBlocks.insert(BB); // Block is now ALIVE!
markBlockAlive(*PI);
}
// Loop over all of the operands of the live instruction, making sure that
// they are known to be alive as well...
//
for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op)
if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op)))
markInstructionLive(Operand);
}
if (DebugFlag) {
cerr << "Current Function: X = Live\n";
for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE; ++BI){
if (LiveSet.count(BI)) cerr << "X ";
cerr << *BI;
}
}
// Find the first postdominator of the entry node that is alive. Make it the
// new entry node...
//
PostDominatorTree &DT = getAnalysis<PostDominatorTree>();
// If there are some blocks dead...
if (AliveBlocks.size() != Func->size()) {
// Insert a new entry node to eliminate the entry node as a special case.
BasicBlock *NewEntry = new BasicBlock();
NewEntry->getInstList().push_back(new BranchInst(&Func->front()));
Func->getBasicBlockList().push_front(NewEntry);
AliveBlocks.insert(NewEntry); // This block is always alive!
// Loop over all of the alive blocks in the function. If any successor
// blocks are not alive, we adjust the outgoing branches to branch to the
// first live postdominator of the live block, adjusting any PHI nodes in
// the block to reflect this.
//
for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
if (AliveBlocks.count(I)) {
BasicBlock *BB = I;
TerminatorInst *TI = BB->getTerminator();
// Loop over all of the successors, looking for ones that are not alive.
// We cannot save the number of successors in the terminator instruction
// here because we may remove them if we don't have a postdominator...
//
for (unsigned i = 0; i != TI->getNumSuccessors(); ++i)
if (!AliveBlocks.count(TI->getSuccessor(i))) {
// Scan up the postdominator tree, looking for the first
// postdominator that is alive, and the last postdominator that is
// dead...
//
PostDominatorTree::Node *LastNode = DT[TI->getSuccessor(i)];
// There is a special case here... if there IS no post-dominator for
// the block we have no owhere to point our branch to. Instead,
// convert it to a return. This can only happen if the code
// branched into an infinite loop. Note that this may not be
// desirable, because we _are_ altering the behavior of the code.
// This is a well known drawback of ADCE, so in the future if we
// choose to revisit the decision, this is where it should be.
//
if (LastNode == 0) { // No postdominator!
// Call RemoveSuccessor to transmogrify the terminator instruction
// to not contain the outgoing branch, or to create a new
// terminator if the form fundementally changes (ie unconditional
// branch to return). Note that this will change a branch into an
// infinite loop into a return instruction!
//
RemoveSuccessor(TI, i);
// RemoveSuccessor may replace TI... make sure we have a fresh
// pointer... and e variable.
//
TI = BB->getTerminator();
// Rescan this successor...
--i;
} else {
PostDominatorTree::Node *NextNode = LastNode->getIDom();
while (!AliveBlocks.count(NextNode->getNode())) {
LastNode = NextNode;
NextNode = NextNode->getIDom();
}
// Get the basic blocks that we need...
BasicBlock *LastDead = LastNode->getNode();
BasicBlock *NextAlive = NextNode->getNode();
// Make the conditional branch now go to the next alive block...
TI->getSuccessor(i)->removePredecessor(BB);
TI->setSuccessor(i, NextAlive);
// If there are PHI nodes in NextAlive, we need to add entries to
// the PHI nodes for the new incoming edge. The incoming values
// should be identical to the incoming values for LastDead.
//
for (BasicBlock::iterator II = NextAlive->begin();
PHINode *PN = dyn_cast<PHINode>(&*II); ++II) {
// Get the incoming value for LastDead...
int OldIdx = PN->getBasicBlockIndex(LastDead);
assert(OldIdx != -1 && "LastDead is not a pred of NextAlive!");
Value *InVal = PN->getIncomingValue(OldIdx);
// Add an incoming value for BB now...
PN->addIncoming(InVal, BB);
}
}
}
// Now loop over all of the instructions in the basic block, telling
// dead instructions to drop their references. This is so that the next
// sweep over the program can safely delete dead instructions without
// other dead instructions still refering to them.
//
for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; ++I)
if (!LiveSet.count(I)) // Is this instruction alive?
I->dropAllReferences(); // Nope, drop references...
}
}
// Loop over all of the basic blocks in the function, dropping references of
// the dead basic blocks
//
for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB) {
if (!AliveBlocks.count(BB)) {
// Remove all outgoing edges from this basic block and convert the
// terminator into a return instruction.
vector<BasicBlock*> Succs(succ_begin(BB), succ_end(BB));
if (!Succs.empty()) {
// Loop over all of the successors, removing this block from PHI node
// entries that might be in the block...
while (!Succs.empty()) {
Succs.back()->removePredecessor(BB);
Succs.pop_back();
}
// Delete the old terminator instruction...
BB->getInstList().pop_back();
const Type *RetTy = Func->getReturnType();
Instruction *New = new ReturnInst(RetTy != Type::VoidTy ?
Constant::getNullValue(RetTy) : 0);
BB->getInstList().push_back(New);
}
BB->dropAllReferences();
++NumBlockRemoved;
MadeChanges = true;
}
}
// Now loop through all of the blocks and delete the dead ones. We can safely
// do this now because we know that there are no references to dead blocks
// (because they have dropped all of their references... we also remove dead
// instructions from alive blocks.
//
for (Function::iterator BI = Func->begin(); BI != Func->end(); )
if (!AliveBlocks.count(BI))
BI = Func->getBasicBlockList().erase(BI);
else {
for (BasicBlock::iterator II = BI->begin(); II != --BI->end(); )
if (!LiveSet.count(II)) { // Is this instruction alive?
// Nope... remove the instruction from it's basic block...
II = BI->getInstList().erase(II);
++NumInstRemoved;
MadeChanges = true;
} else {
++II;
}
++BI; // Increment iterator...
}
return MadeChanges;
}
|
//===- ADCE.cpp - Code to perform aggressive dead code elimination --------===//
//
// This file implements "aggressive" dead code elimination. ADCE is DCe where
// values are assumed to be dead until proven otherwise. This is similar to
// SCCP, except applied to the liveness of values.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Type.h"
#include "llvm/Analysis/Dominators.h"
#include "llvm/iTerminators.h"
#include "llvm/iPHINode.h"
#include "llvm/Constant.h"
#include "llvm/Support/CFG.h"
#include "Support/STLExtras.h"
#include "Support/DepthFirstIterator.h"
#include "Support/StatisticReporter.h"
#include <algorithm>
#include <iostream>
using std::cerr;
using std::vector;
static Statistic<> NumBlockRemoved("adce\t\t- Number of basic blocks removed");
static Statistic<> NumInstRemoved ("adce\t\t- Number of instructions removed");
namespace {
//===----------------------------------------------------------------------===//
// ADCE Class
//
// This class does all of the work of Aggressive Dead Code Elimination.
// It's public interface consists of a constructor and a doADCE() method.
//
class ADCE : public FunctionPass {
Function *Func; // The function that we are working on
std::vector<Instruction*> WorkList; // Instructions that just became live
std::set<Instruction*> LiveSet; // The set of live instructions
//===--------------------------------------------------------------------===//
// The public interface for this class
//
public:
// Execute the Aggressive Dead Code Elimination Algorithm
//
virtual bool runOnFunction(Function &F) {
Func = &F;
bool Changed = doADCE();
assert(WorkList.empty());
LiveSet.clear();
return Changed;
}
// getAnalysisUsage - We require post dominance frontiers (aka Control
// Dependence Graph)
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired(PostDominatorTree::ID);
AU.addRequired(PostDominanceFrontier::ID);
}
//===--------------------------------------------------------------------===//
// The implementation of this class
//
private:
// doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
// true if the function was modified.
//
bool doADCE();
void markBlockAlive(BasicBlock *BB);
inline void markInstructionLive(Instruction *I) {
if (LiveSet.count(I)) return;
DEBUG(cerr << "Insn Live: " << I);
LiveSet.insert(I);
WorkList.push_back(I);
}
inline void markTerminatorLive(const BasicBlock *BB) {
DEBUG(cerr << "Terminat Live: " << BB->getTerminator());
markInstructionLive((Instruction*)BB->getTerminator());
}
};
RegisterOpt<ADCE> X("adce", "Aggressive Dead Code Elimination");
} // End of anonymous namespace
Pass *createAggressiveDCEPass() { return new ADCE(); }
void ADCE::markBlockAlive(BasicBlock *BB) {
// Mark the basic block as being newly ALIVE... and mark all branches that
// this block is control dependant on as being alive also...
//
PostDominanceFrontier &CDG = getAnalysis<PostDominanceFrontier>();
PostDominanceFrontier::const_iterator It = CDG.find(BB);
if (It != CDG.end()) {
// Get the blocks that this node is control dependant on...
const PostDominanceFrontier::DomSetType &CDB = It->second;
for_each(CDB.begin(), CDB.end(), // Mark all their terminators as live
bind_obj(this, &ADCE::markTerminatorLive));
}
// If this basic block is live, then the terminator must be as well!
markTerminatorLive(BB);
}
// doADCE() - Run the Aggressive Dead Code Elimination algorithm, returning
// true if the function was modified.
//
bool ADCE::doADCE() {
bool MadeChanges = false;
// Iterate over all of the instructions in the function, eliminating trivially
// dead instructions, and marking instructions live that are known to be
// needed. Perform the walk in depth first order so that we avoid marking any
// instructions live in basic blocks that are unreachable. These blocks will
// be eliminated later, along with the instructions inside.
//
for (df_iterator<Function*> BBI = df_begin(Func), BBE = df_end(Func);
BBI != BBE; ++BBI) {
BasicBlock *BB = *BBI;
for (BasicBlock::iterator II = BB->begin(), EI = BB->end(); II != EI; ) {
if (II->hasSideEffects() || II->getOpcode() == Instruction::Ret) {
markInstructionLive(II);
++II; // Increment the inst iterator if the inst wasn't deleted
} else if (isInstructionTriviallyDead(II)) {
// Remove the instruction from it's basic block...
II = BB->getInstList().erase(II);
++NumInstRemoved;
MadeChanges = true;
} else {
++II; // Increment the inst iterator if the inst wasn't deleted
}
}
}
DEBUG(cerr << "Processing work list\n");
// AliveBlocks - Set of basic blocks that we know have instructions that are
// alive in them...
//
std::set<BasicBlock*> AliveBlocks;
// Process the work list of instructions that just became live... if they
// became live, then that means that all of their operands are neccesary as
// well... make them live as well.
//
while (!WorkList.empty()) {
Instruction *I = WorkList.back(); // Get an instruction that became live...
WorkList.pop_back();
BasicBlock *BB = I->getParent();
if (!AliveBlocks.count(BB)) { // Basic block not alive yet...
AliveBlocks.insert(BB); // Block is now ALIVE!
markBlockAlive(BB); // Make it so now!
}
// PHI nodes are a special case, because the incoming values are actually
// defined in the predecessor nodes of this block, meaning that the PHI
// makes the predecessors alive.
//
if (PHINode *PN = dyn_cast<PHINode>(I))
for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI)
if (!AliveBlocks.count(*PI)) {
AliveBlocks.insert(BB); // Block is now ALIVE!
markBlockAlive(*PI);
}
// Loop over all of the operands of the live instruction, making sure that
// they are known to be alive as well...
//
for (unsigned op = 0, End = I->getNumOperands(); op != End; ++op)
if (Instruction *Operand = dyn_cast<Instruction>(I->getOperand(op)))
markInstructionLive(Operand);
}
if (DebugFlag) {
cerr << "Current Function: X = Live\n";
for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE; ++BI){
if (LiveSet.count(BI)) cerr << "X ";
cerr << *BI;
}
}
// Find the first postdominator of the entry node that is alive. Make it the
// new entry node...
//
PostDominatorTree &DT = getAnalysis<PostDominatorTree>();
// If there are some blocks dead...
if (AliveBlocks.size() != Func->size()) {
// Insert a new entry node to eliminate the entry node as a special case.
BasicBlock *NewEntry = new BasicBlock();
NewEntry->getInstList().push_back(new BranchInst(&Func->front()));
Func->getBasicBlockList().push_front(NewEntry);
AliveBlocks.insert(NewEntry); // This block is always alive!
// Loop over all of the alive blocks in the function. If any successor
// blocks are not alive, we adjust the outgoing branches to branch to the
// first live postdominator of the live block, adjusting any PHI nodes in
// the block to reflect this.
//
for (Function::iterator I = Func->begin(), E = Func->end(); I != E; ++I)
if (AliveBlocks.count(I)) {
BasicBlock *BB = I;
TerminatorInst *TI = BB->getTerminator();
// Loop over all of the successors, looking for ones that are not alive.
// We cannot save the number of successors in the terminator instruction
// here because we may remove them if we don't have a postdominator...
//
for (unsigned i = 0; i != TI->getNumSuccessors(); ++i)
if (!AliveBlocks.count(TI->getSuccessor(i))) {
// Scan up the postdominator tree, looking for the first
// postdominator that is alive, and the last postdominator that is
// dead...
//
PostDominatorTree::Node *LastNode = DT[TI->getSuccessor(i)];
// There is a special case here... if there IS no post-dominator for
// the block we have no owhere to point our branch to. Instead,
// convert it to a return. This can only happen if the code
// branched into an infinite loop. Note that this may not be
// desirable, because we _are_ altering the behavior of the code.
// This is a well known drawback of ADCE, so in the future if we
// choose to revisit the decision, this is where it should be.
//
if (LastNode == 0) { // No postdominator!
// Call RemoveSuccessor to transmogrify the terminator instruction
// to not contain the outgoing branch, or to create a new
// terminator if the form fundementally changes (ie unconditional
// branch to return). Note that this will change a branch into an
// infinite loop into a return instruction!
//
RemoveSuccessor(TI, i);
// RemoveSuccessor may replace TI... make sure we have a fresh
// pointer... and e variable.
//
TI = BB->getTerminator();
// Rescan this successor...
--i;
} else {
PostDominatorTree::Node *NextNode = LastNode->getIDom();
while (!AliveBlocks.count(NextNode->getNode())) {
LastNode = NextNode;
NextNode = NextNode->getIDom();
}
// Get the basic blocks that we need...
BasicBlock *LastDead = LastNode->getNode();
BasicBlock *NextAlive = NextNode->getNode();
// Make the conditional branch now go to the next alive block...
TI->getSuccessor(i)->removePredecessor(BB);
TI->setSuccessor(i, NextAlive);
// If there are PHI nodes in NextAlive, we need to add entries to
// the PHI nodes for the new incoming edge. The incoming values
// should be identical to the incoming values for LastDead.
//
for (BasicBlock::iterator II = NextAlive->begin();
PHINode *PN = dyn_cast<PHINode>(&*II); ++II) {
// Get the incoming value for LastDead...
int OldIdx = PN->getBasicBlockIndex(LastDead);
assert(OldIdx != -1 && "LastDead is not a pred of NextAlive!");
Value *InVal = PN->getIncomingValue(OldIdx);
// Add an incoming value for BB now...
PN->addIncoming(InVal, BB);
}
}
}
// Now loop over all of the instructions in the basic block, telling
// dead instructions to drop their references. This is so that the next
// sweep over the program can safely delete dead instructions without
// other dead instructions still refering to them.
//
for (BasicBlock::iterator I = BB->begin(), E = --BB->end(); I != E; )
if (!LiveSet.count(I)) { // Is this instruction alive?
I->dropAllReferences(); // Nope, drop references...
if (PHINode *PN = dyn_cast<PHINode>(&*I)) {
// We don't want to leave PHI nodes in the program that have
// #arguments != #predecessors, so we remove them now.
//
PN->replaceAllUsesWith(Constant::getNullValue(PN->getType()));
// Delete the instruction...
I = BB->getInstList().erase(I);
} else {
++I;
}
} else {
++I;
}
}
}
// Loop over all of the basic blocks in the function, dropping references of
// the dead basic blocks
//
for (Function::iterator BB = Func->begin(), E = Func->end(); BB != E; ++BB) {
if (!AliveBlocks.count(BB)) {
// Remove all outgoing edges from this basic block and convert the
// terminator into a return instruction.
vector<BasicBlock*> Succs(succ_begin(BB), succ_end(BB));
if (!Succs.empty()) {
// Loop over all of the successors, removing this block from PHI node
// entries that might be in the block...
while (!Succs.empty()) {
Succs.back()->removePredecessor(BB);
Succs.pop_back();
}
// Delete the old terminator instruction...
BB->getInstList().pop_back();
const Type *RetTy = Func->getReturnType();
Instruction *New = new ReturnInst(RetTy != Type::VoidTy ?
Constant::getNullValue(RetTy) : 0);
BB->getInstList().push_back(New);
}
BB->dropAllReferences();
++NumBlockRemoved;
MadeChanges = true;
}
}
// Now loop through all of the blocks and delete the dead ones. We can safely
// do this now because we know that there are no references to dead blocks
// (because they have dropped all of their references... we also remove dead
// instructions from alive blocks.
//
for (Function::iterator BI = Func->begin(); BI != Func->end(); )
if (!AliveBlocks.count(BI))
BI = Func->getBasicBlockList().erase(BI);
else {
for (BasicBlock::iterator II = BI->begin(); II != --BI->end(); )
if (!LiveSet.count(II)) { // Is this instruction alive?
// Nope... remove the instruction from it's basic block...
II = BI->getInstList().erase(II);
++NumInstRemoved;
MadeChanges = true;
} else {
++II;
}
++BI; // Increment iterator...
}
return MadeChanges;
}
|
Add code to ensure that no PHI nodes are left laying around with their arguments dropped. This fixes bug: test/Regression/Transforms/ADCE/2002-07-17-PHIAssertion.ll
|
Add code to ensure that no PHI nodes are left laying around with their
arguments dropped. This fixes bug:
test/Regression/Transforms/ADCE/2002-07-17-PHIAssertion.ll
git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@3134 91177308-0d34-0410-b5e6-96231b3b80d8
|
C++
|
bsd-2-clause
|
dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,apple/swift-llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,apple/swift-llvm,chubbymaggie/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,dslab-epfl/asap,llvm-mirror/llvm,llvm-mirror/llvm,apple/swift-llvm,llvm-mirror/llvm,chubbymaggie/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,dslab-epfl/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,llvm-mirror/llvm,chubbymaggie/asap,dslab-epfl/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm
|
1f64d5303e3cc3f105b72bc5a80cabc9a625fcc5
|
src/startup.cxx
|
src/startup.cxx
|
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <string>
#include <iostream>
#include <fstream>
#include <set>
#include <vector>
#include <list>
#include <unistd.h>
#include "startup.hxx"
#include "interp.hxx"
#include "cmd/list.hxx"
#include "options.hxx"
#include "common.hxx"
using namespace std;
namespace tglng {
static string dirname(const string& filename) {
size_t lastSlash = filename.find_last_of("/");
if (0 == lastSlash || string::npos == lastSlash)
return "";
return filename.substr(0, lastSlash);
}
static void chdirToFilename() {
string filenameDir = dirname(operationalFile);
if (!filenameDir.empty() && implicitChdir) {
if (!chdir(filenameDir.c_str())) {
cerr << "Failed to chdir() to " << filenameDir
<< ": " << strerror(errno);
exit(EXIT_PLATFORM_ERROR);
}
}
}
static string homeRel(const string& basename) {
const char* homeEnv = getenv("HOME");
if (!homeEnv) homeEnv = "";
return string(homeEnv) + "/" + basename;
}
static void slurpSet(set<string>& dst, const string& filename) {
ifstream in(filename.c_str());
if (!in) return;
string item;
while (getline(in, item, '\n'))
dst.insert(item);
}
static void spitSet(const string& filename, const set<string>& dst) {
ofstream out(filename.c_str());
if (!out) return;
for (set<string>::const_iterator it = dst.begin();
it != dst.end(); ++it)
out << *it << endl;
}
static void readConfig(Interpreter& interp, const string& filename) {
wifstream in(filename.c_str());
wstring discard;
if (!in) return;
if (!interp.exec(discard, in, Interpreter::ParseModeCommand))
exit(EXIT_PARSE_ERROR_IN_USER_LIBRARY);
}
static bool readAuxConfigs(Interpreter& interp,
set<string>& known, const set<string>& permitted,
string directory) {
const char* homeEnv = getenv("home");
const string root("/"), home(homeEnv? homeEnv : "/");
bool newKnown = false;
while (!directory.empty() && directory != root && directory != home) {
string path = directory + "/.tglng";
if (!access(path.c_str(), R_OK)) {
if (permitted.count(directory)) {
readConfig(interp, path);
} else if (!known.count(directory)) {
/* Warn the user about this once, then add it to known so we don't
* keep bothering them.
*/
cerr << "Note: Aux config " << path << " exists, but is not marked "
<< "as permitted." << endl
<< "Add \"" << directory << "\" to ~/.tglng_permitted if you "
<< "trust this script." << endl;
known.insert(directory);
newKnown = true;
}
}
directory = dirname(directory);
}
return newKnown;
}
static void readUserConfiguration(Interpreter& interp) {
if (!userConfigs.empty())
for (std::list<string>::const_iterator it = userConfigs.begin();
it != userConfigs.end(); ++it)
readConfig(interp, *it);
else
readConfig(interp, homeRel(".tglng"));
}
void startUp(Interpreter& interp) {
set<string> knownDirs, permittedDirs;
chdirToFilename();
if (enableSystemConfig) {
readConfig(interp, "/usr/local/etc/tglngrc");
readConfig(interp, "/usr/etc/tglngrc");
readConfig(interp, "/etc/tglngrc");
}
slurpSet(knownDirs, homeRel(".tglng_known"));
slurpSet(permittedDirs, homeRel(".tglng_permitted"));
const char* cwd = getcwd(NULL, ~0);
if (!cwd) {
cerr << "getcwd() failed: " << strerror(errno) << endl;
exit(EXIT_PLATFORM_ERROR);
}
if (readAuxConfigs(interp, knownDirs, permittedDirs, string(cwd)))
spitSet(homeRel(".tglng_known"), knownDirs);
free(const_cast<char*>(cwd));
readUserConfiguration(interp);
interp.registers = initialRegisters;
}
}
|
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <cstdlib>
#include <cstring>
#include <cerrno>
#include <string>
#include <iostream>
#include <fstream>
#include <set>
#include <vector>
#include <list>
#include <unistd.h>
#include "startup.hxx"
#include "interp.hxx"
#include "cmd/list.hxx"
#include "options.hxx"
#include "common.hxx"
using namespace std;
namespace tglng {
static string dirname(const string& filename) {
size_t lastSlash = filename.find_last_of("/");
if (0 == lastSlash || string::npos == lastSlash)
return "";
return filename.substr(0, lastSlash);
}
static void chdirToFilename() {
string filenameDir = dirname(operationalFile);
if (!filenameDir.empty() && implicitChdir) {
if (chdir(filenameDir.c_str())) {
cerr << "Failed to chdir() to " << filenameDir
<< ": " << strerror(errno);
exit(EXIT_PLATFORM_ERROR);
}
}
}
static string homeRel(const string& basename) {
const char* homeEnv = getenv("HOME");
if (!homeEnv) homeEnv = "";
return string(homeEnv) + "/" + basename;
}
static void slurpSet(set<string>& dst, const string& filename) {
ifstream in(filename.c_str());
if (!in) return;
string item;
while (getline(in, item, '\n'))
dst.insert(item);
}
static void spitSet(const string& filename, const set<string>& dst) {
ofstream out(filename.c_str());
if (!out) return;
for (set<string>::const_iterator it = dst.begin();
it != dst.end(); ++it)
out << *it << endl;
}
static void readConfig(Interpreter& interp, const string& filename) {
wifstream in(filename.c_str());
wstring discard;
if (!in) return;
if (!interp.exec(discard, in, Interpreter::ParseModeCommand))
exit(EXIT_PARSE_ERROR_IN_USER_LIBRARY);
}
static bool readAuxConfigs(Interpreter& interp,
set<string>& known, const set<string>& permitted,
string directory) {
const char* homeEnv = getenv("home");
const string root("/"), home(homeEnv? homeEnv : "/");
bool newKnown = false;
while (!directory.empty() && directory != root && directory != home) {
string path = directory + "/.tglng";
if (!access(path.c_str(), R_OK)) {
if (permitted.count(directory)) {
readConfig(interp, path);
} else if (!known.count(directory)) {
/* Warn the user about this once, then add it to known so we don't
* keep bothering them.
*/
cerr << "Note: Aux config " << path << " exists, but is not marked "
<< "as permitted." << endl
<< "Add \"" << directory << "\" to ~/.tglng_permitted if you "
<< "trust this script." << endl;
known.insert(directory);
newKnown = true;
}
}
directory = dirname(directory);
}
return newKnown;
}
static void readUserConfiguration(Interpreter& interp) {
if (!userConfigs.empty())
for (std::list<string>::const_iterator it = userConfigs.begin();
it != userConfigs.end(); ++it)
readConfig(interp, *it);
else
readConfig(interp, homeRel(".tglng"));
}
void startUp(Interpreter& interp) {
set<string> knownDirs, permittedDirs;
chdirToFilename();
if (enableSystemConfig) {
readConfig(interp, "/usr/local/etc/tglngrc");
readConfig(interp, "/usr/etc/tglngrc");
readConfig(interp, "/etc/tglngrc");
}
slurpSet(knownDirs, homeRel(".tglng_known"));
slurpSet(permittedDirs, homeRel(".tglng_permitted"));
const char* cwd = getcwd(NULL, ~0);
if (!cwd) {
cerr << "getcwd() failed: " << strerror(errno) << endl;
exit(EXIT_PLATFORM_ERROR);
}
if (readAuxConfigs(interp, knownDirs, permittedDirs, string(cwd)))
spitSet(homeRel(".tglng_known"), knownDirs);
free(const_cast<char*>(cwd));
readUserConfiguration(interp);
interp.registers = initialRegisters;
}
}
|
Fix inverted test for chdir().
|
Fix inverted test for chdir().
|
C++
|
bsd-3-clause
|
AltSysrq/tglng
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.