text stringlengths 54 60.6k |
|---|
<commit_before>#include "TF1.h"
#include "Math/Functor.h"
#include "TStopwatch.h"
#include "RConfigure.h"
#include "Math/RootFinder.h"
#include "Math/DistFunc.h"
#include <iostream>
#include <iomanip>
#include <cmath>
/**
Test of ROOT finder for various function
case = 0 simple function (polynomial)
case = 1 function which fails for a bug in BrentMethod::MinimBrent fixed with r = 32544 (5.27.01)
*/
const double ERRORLIMIT = 1E-8;
const int iterTest = 10000;
int myfuncCalls = 0;
const double Y0_P2 = 5.0; // Y0 for test 1 (parabola)
// these are value which gave problems in 5.26 for gamma_cdf
const double Y0_GAMMA = 0.32; // Y0 for test 2 (gamma cdf)
const double ALPHA_GAMMA = 16.; // alpha of gamma cdf
const double THETA_GAMMA = 0.4; // theta of gamma cdf
int gTestCase = 0;
double myfunc ( double x ) {
myfuncCalls ++;
if (gTestCase == 0) // polynomial
return x*x - Y0_P2;
if (gTestCase == 1) // function showing bug in BrentMethod::
return ROOT::Math::gamma_cdf(x,ALPHA_GAMMA,THETA_GAMMA)-Y0_GAMMA;
return 0;
}
double ExactResult() {
if (gTestCase == 0) {
return std::sqrt(Y0_P2);
}
if (gTestCase == 1)
#ifdef R__HAS_MATHMORE
return ROOT::Math::gamma_quantile(Y0_GAMMA,ALPHA_GAMMA,THETA_GAMMA);
#else
return 5.55680381022934800; //result as before if quantile of gamma is not available
#endif
return 0;
}
double myfunc_p (double *x, double *) { return myfunc(x[0]); }
int printStats(TStopwatch& timer, double root) {
//std::cout << "Return code: " << status << std::endl;
double difference = root - ExactResult();
int pr = std::cout.precision(16);
std::cout << "Result: " << root << std::endl;
std::cout << "Exact result: " << ExactResult();
std::cout.precision(pr);
std::cout << " difference: " << difference << std::endl;
std::cout << "Time: " << timer.RealTime()/(double) iterTest << std::endl;
std::cout << "Number of calls to function: " << myfuncCalls/iterTest << std::endl;
return difference > ERRORLIMIT;
}
int runTest(int testcase = 0) {
double xmin = 0;
double xmax = 10;
std::cout << "*************************************************************\n";
gTestCase = testcase;
if (gTestCase == 0)
std::cout << "Test for simple function f(x) = x^2 - 5 \n" << std::endl;
if (gTestCase == 1) {
std::cout << "\nTest for f(x) = gamma_cdf \n" << std::endl;
xmin = 3.955687382047723;
xmax = 9.3423159494328623;
}
TStopwatch timer;
double root;
int status = 0;
double tol = 1.E-14;
int maxiter = 100;
ROOT::Math::Functor1D *func = new ROOT::Math::Functor1D (&myfunc);
TF1* f1 = new TF1("f1", myfunc_p, xmin, xmax);
timer.Reset(); timer.Start(); myfuncCalls = 0;
for (int i = 0; i < iterTest; ++i)
{
//brf.SetFunction( *func, 0, 10 ); // Just to make a fair comparision!
root = f1->GetX(0, xmin, xmax,tol,maxiter);
}
timer.Stop();
std::cout << "\nTF1 Stats:" << std::endl;
status += printStats(timer, root);
ROOT::Math::RootFinder brf(ROOT::Math::RootFinder::kBRENT);
timer.Reset(); timer.Start(); myfuncCalls = 0;
for (int i = 0; i < iterTest; ++i)
{
brf.SetFunction( *func, xmin, xmax );
bool ret = brf.Solve(maxiter,tol,tol);
if (!ret && i == 0) std::cout << "Error returned from RootFinder::Solve BRENT " << std::endl;
root = brf.Root();
}
timer.Stop();
std::cout << "Brent RootFinder Stats:" << std::endl;
status += printStats(timer, root);
#ifdef R__HAS_MATHMORE
ROOT::Math::RootFinder grf(ROOT::Math::RootFinder::kGSL_BRENT);
timer.Reset(); timer.Start(); myfuncCalls = 0;
for (int i = 0; i < iterTest; ++i)
{
grf.SetFunction( *func, xmin, xmax );
bool ret = grf.Solve(maxiter,tol,tol);
root = grf.Root();
if (!ret && i == 0) std::cout << "Error returned from RootFinder::Solve GSL_BRENT" << std::endl;
}
timer.Stop();
std::cout << "GSL Brent RootFinder Stats:" << std::endl;
status += printStats(timer, root);
#endif
if (status) std::cout << "Test-case " << testcase << " FAILED" << std::endl;
return status;
}
int testRootFinder() {
int status = 0;
status |= runTest(0); // test pol function
if (status) std::cerr << "Test pol function FAILED" << std::endl;
status |= runTest(1); // test gamma_cdf
if (status) std::cerr << "Test gamma function FAILED" << std::endl;
std::cerr << "*************************************************************\n";
std::cerr << "\nTest RootFinder :\t";
if (status == 0)
std::cerr << "OK " << std::endl;
else
std::cerr << "Failed !" << std::endl;
return status;
}
int main() {
return testRootFinder();
}
<commit_msg>remore a direct dependecy on MathMore<commit_after>#include "TF1.h"
#include "Math/Functor.h"
#include "TStopwatch.h"
#include "RConfigure.h"
#include "Math/RootFinder.h"
#include "Math/DistFunc.h"
#include <iostream>
#include <iomanip>
#include <cmath>
/**
Test of ROOT finder for various function
case = 0 simple function (polynomial)
case = 1 function which fails for a bug in BrentMethod::MinimBrent fixed with r = 32544 (5.27.01)
*/
const double ERRORLIMIT = 1E-8;
const int iterTest = 10000;
int myfuncCalls = 0;
const double Y0_P2 = 5.0; // Y0 for test 1 (parabola)
// these are value which gave problems in 5.26 for gamma_cdf
const double Y0_GAMMA = 0.32; // Y0 for test 2 (gamma cdf)
const double ALPHA_GAMMA = 16.; // alpha of gamma cdf
const double THETA_GAMMA = 0.4; // theta of gamma cdf
int gTestCase = 0;
double myfunc ( double x ) {
myfuncCalls ++;
if (gTestCase == 0) // polynomial
return x*x - Y0_P2;
if (gTestCase == 1) // function showing bug in BrentMethod::
return ROOT::Math::gamma_cdf(x,ALPHA_GAMMA,THETA_GAMMA)-Y0_GAMMA;
return 0;
}
double ExactResult() {
if (gTestCase == 0) {
return std::sqrt(Y0_P2);
}
if (gTestCase == 1)
//return ROOT::Math::gamma_quantile(Y0_GAMMA,ALPHA_GAMMA,THETA_GAMMA);
// put the value to avoid direct MathMore dependency
return 5.55680381022934800;
return 0;
}
double myfunc_p (double *x, double *) { return myfunc(x[0]); }
int printStats(TStopwatch& timer, double root) {
//std::cout << "Return code: " << status << std::endl;
double difference = root - ExactResult();
int pr = std::cout.precision(16);
std::cout << "Result: " << root << std::endl;
std::cout << "Exact result: " << ExactResult();
std::cout.precision(pr);
std::cout << " difference: " << difference << std::endl;
std::cout << "Time: " << timer.RealTime()/(double) iterTest << std::endl;
std::cout << "Number of calls to function: " << myfuncCalls/iterTest << std::endl;
return difference > ERRORLIMIT;
}
int runTest(int testcase = 0) {
double xmin = 0;
double xmax = 10;
std::cout << "*************************************************************\n";
gTestCase = testcase;
if (gTestCase == 0)
std::cout << "Test for simple function f(x) = x^2 - 5 \n" << std::endl;
if (gTestCase == 1) {
std::cout << "\nTest for f(x) = gamma_cdf \n" << std::endl;
xmin = 3.955687382047723;
xmax = 9.3423159494328623;
}
TStopwatch timer;
double root;
int status = 0;
double tol = 1.E-14;
int maxiter = 100;
ROOT::Math::Functor1D *func = new ROOT::Math::Functor1D (&myfunc);
TF1* f1 = new TF1("f1", myfunc_p, xmin, xmax);
timer.Reset(); timer.Start(); myfuncCalls = 0;
for (int i = 0; i < iterTest; ++i)
{
//brf.SetFunction( *func, 0, 10 ); // Just to make a fair comparision!
root = f1->GetX(0, xmin, xmax,tol,maxiter);
}
timer.Stop();
std::cout << "\nTF1 Stats:" << std::endl;
status += printStats(timer, root);
ROOT::Math::RootFinder brf(ROOT::Math::RootFinder::kBRENT);
timer.Reset(); timer.Start(); myfuncCalls = 0;
for (int i = 0; i < iterTest; ++i)
{
brf.SetFunction( *func, xmin, xmax );
bool ret = brf.Solve(maxiter,tol,tol);
if (!ret && i == 0) std::cout << "Error returned from RootFinder::Solve BRENT " << std::endl;
root = brf.Root();
}
timer.Stop();
std::cout << "Brent RootFinder Stats:" << std::endl;
status += printStats(timer, root);
#ifdef R__HAS_MATHMORE
ROOT::Math::RootFinder grf(ROOT::Math::RootFinder::kGSL_BRENT);
timer.Reset(); timer.Start(); myfuncCalls = 0;
for (int i = 0; i < iterTest; ++i)
{
grf.SetFunction( *func, xmin, xmax );
bool ret = grf.Solve(maxiter,tol,tol);
root = grf.Root();
if (!ret && i == 0) std::cout << "Error returned from RootFinder::Solve GSL_BRENT" << std::endl;
}
timer.Stop();
std::cout << "GSL Brent RootFinder Stats:" << std::endl;
status += printStats(timer, root);
#endif
if (status) std::cout << "Test-case " << testcase << " FAILED" << std::endl;
return status;
}
int testRootFinder() {
int status = 0;
status |= runTest(0); // test pol function
if (status) std::cerr << "Test pol function FAILED" << std::endl;
status |= runTest(1); // test gamma_cdf
if (status) std::cerr << "Test gamma function FAILED" << std::endl;
std::cerr << "*************************************************************\n";
std::cerr << "\nTest RootFinder :\t";
if (status == 0)
std::cerr << "OK " << std::endl;
else
std::cerr << "Failed !" << std::endl;
return status;
}
int main() {
return testRootFinder();
}
<|endoftext|> |
<commit_before>#pragma once
#include <Simple-Web-Server/client_https.hpp>
#include <boost/regex.hpp>
using namespace std;
// ------------------------------------------------------------------------------
// This header contains utilities that depend on HttpsClient.
// They are maintained outside of utilities.hpp to avoid bundling http code where it is not needed.
// ------------------------------------------------------------------------------
// Results extraction helpers
static string get_body(std::shared_ptr<Client<HTTP>::Response> response) { if (response) return response->content.string(); return ""; }
static int32_t get_status_code(std::shared_ptr<Client<HTTP>::Response> response) { if (response) return boost::lexical_cast<int32_t>(response->status_code.substr(0,3));; return 500; }
static string get_body(std::shared_ptr<Client<HTTPS>::Response> response) { if (response) return response->content.string(); return ""; }
static int32_t get_status_code(std::shared_ptr<Client<HTTPS>::Response> response) { if (response) return boost::lexical_cast<int32_t>(response->status_code.substr(0,3));; return 500; }
// scrape_website
// --------------
// Scraping websites in general is an ugly brittle job.
// No website publisher thinks of their site as a stable API.
// With that in mind, whenever we scrape, we do it in as fault-tolerant a way as possible.
// That means searching for a snippet of regex, in every case.
//
// EXAMPLE:
//
// Client<HTTPS> client("google.com");
// if (
// scrape_website(
// client,
// "",
// "(Feeling Lucky)"
// result
// )
// cout << result; // "Feeling Lucky" punk? :-)
//
// INPUT:
// regex provide a regex search string that includes a group; if a match is found, the group will be returned
// eg, for the rows in a particular table: "<table[^>]+class[^>]+width=\"100[^>]+>([\\s\\S]+?)<[/]table>"
//
// REQUIREMENTS
// The common case is to search not just for your target text, but for surrounding text as well.
// This function is designed for such use case.
// With that in mind, you MUST use a GROUP to identify your target text, as that is OFTEN
// but not always needed. Examples:
//
// If you want to find target text that MUST be surrounded by a <div> tag:
//
// regex: "<div>(My Target Text)</div>"
//
// If you just want a search string, you MUST use a group, eg:
//
// regex: "(My Target Text)"
//
// NOTE It's become pretty annoying that SWS separates out http from https so severely
// via hard templates with no non-templated base class.
// Results in a shittone of dupe code, the bane of my existence.
// And should be yours too. Rewrite SWS some day.
// ALWAYS USE A NON-TEMPLATED BASE CLASS for all your templates!
static bool scrape_website(
Client<HTTP>& client, // Use: Client<HTTP> client("mydomain");
const string& path,
const string& regex,
string& result
) {
assert(regex.find('(') != std::string::npos); // Remember to always provide a "(group)" in your regex!
auto http_response = client.request_without_exception("GET",path);
return
get_status_code(http_response) == 200
&& find_substring(http_response->content.string(),regex,result);
}
static bool scrape_website(
Client<HTTPS>& client, // Use: Client<HTTPS> client("mysecuredomain");
const string& path,
const string& regex,
string& result
) {
assert(regex.find('(') != std::string::npos); // Remember to always provide a "(group)" in your regex!
auto http_response = client.request_without_exception("GET",path);
return
get_status_code(http_response) == 200
&& find_substring(http_response->content.string(),regex,result);
}
<commit_msg>Adding libraries to mh First one is rapidjson Hopefully many more to come Well a few good ones anyway<commit_after>#pragma once
#include <Simple-Web-Server/client_https.hpp>
#include <boost/regex.hpp>
using namespace std;
// ------------------------------------------------------------------------------
// This header contains utilities that depend on HttpsClient.
// They are maintained outside of utilities.hpp to avoid bundling http code where it is not needed.
// ------------------------------------------------------------------------------
// Results extraction helpers
static string get_body(std::shared_ptr<Client<HTTP>::Response> response) { if (response) return response->content.string(); return ""; }
static int32_t get_status_code(std::shared_ptr<Client<HTTP>::Response> response) { if (response) return boost::lexical_cast<int32_t>(response->status_code.substr(0,3));; return 500; }
static string get_body(std::shared_ptr<Client<HTTPS>::Response> response) { if (response) return response->content.string(); return ""; }
static int32_t get_status_code(std::shared_ptr<Client<HTTPS>::Response> response) { if (response) return boost::lexical_cast<int32_t>(response->status_code.substr(0,3));; return 500; }
// scrape_website
// --------------
// Scraping websites in general is an ugly brittle job.
// No website publisher thinks of their site as a stable API.
// With that in mind, whenever we scrape, we do it in as fault-tolerant a way as possible.
// That means searching for a snippet of regex, in every case.
//
// EXAMPLE:
//
// Client<HTTPS> client("google.com");
// if (
// scrape_website(
// client,
// "",
// "(Feeling Lucky)"
// result
// )
// cout << result; // "Feeling Lucky" punk? :-)
//
// INPUT:
// regex provide a regex search string that includes a group; if a match is found, the group will be returned
// eg, for the rows in a particular table: "<table[^>]+class[^>]+width=\"100[^>]+>([\\s\\S]+?)<[/]table>"
//
// REQUIREMENTS
// The common case is to search not just for your target text, but for surrounding text as well.
// This function is designed for such use case.
// With that in mind, you MUST use a GROUP to identify your target text, as that is OFTEN
// but not always needed. Examples:
//
// If you want to find target text that MUST be surrounded by a <div> tag:
//
// regex: "<div>(My Target Text)</div>"
//
// If you just want a search string, you MUST use a group, eg:
//
// regex: "(My Target Text)"
//
// NOTE It's become pretty annoying that SWS separates out http from https so severely
// via hard templates with no non-templated base class.
// Results in a shittone of dupe code, the bane of my existence.
// And should be yours too. Rewrite SWS some day.
// ALWAYS USE A NON-TEMPLATED BASE CLASS for all your templates!
static bool scrape_website_body(
const string& body,
const string& regex,
string& result
) {
assert(regex.find('(') != std::string::npos); // Remember to always provide a "(group)" in your regex!
return find_substring(body,regex,result);
}
static bool scrape_website(
Client<HTTP>& client, // Use: Client<HTTP> client("mydomain");
const string& path,
const string& regex,
string& result
) {
auto http_response = client.request_without_exception("GET",path);
return
get_status_code(http_response) == 200
&& scrape_website_body(http_response->content.string(),regex,result);
}
static bool scrape_website(
Client<HTTPS>& client, // Use: Client<HTTPS> client("mysecuredomain");
const string& path,
const string& regex,
string& result
) {
auto http_response = client.request_without_exception("GET",path);
return
get_status_code(http_response) == 200
&& scrape_website_body(http_response->content.string(),regex,result);
}
<|endoftext|> |
<commit_before>/**
* @file llavatarlist.h
* @brief Generic avatar list
*
* $LicenseInfo:firstyear=2009&license=viewergpl$
*
* Copyright (c) 2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llavatarlist.h"
// newview
#include "llcallingcard.h" // for LLAvatarTracker
#include "llcachename.h"
#include "llvoiceclient.h"
#include "llviewercontrol.h" // for gSavedSettings
static LLDefaultChildRegistry::Register<LLAvatarList> r("avatar_list");
// Maximum number of avatars that can be added to a list in one pass.
// Used to limit time spent for avatar list update per frame.
static const unsigned ADD_LIMIT = 50;
void LLAvatarList::toggleIcons()
{
// Save the new value for new items to use.
mShowIcons = !mShowIcons;
gSavedSettings.setBOOL(mIconParamName, mShowIcons);
// Show/hide icons for all existing items.
std::vector<LLPanel*> items;
getItems(items);
for( std::vector<LLPanel*>::const_iterator it = items.begin(); it != items.end(); it++)
{
static_cast<LLAvatarListItem*>(*it)->setAvatarIconVisible(mShowIcons);
}
}
static bool findInsensitive(std::string haystack, const std::string& needle_upper)
{
LLStringUtil::toUpper(haystack);
return haystack.find(needle_upper) != std::string::npos;
}
//comparators
static const LLAvatarItemNameComparator NAME_COMPARATOR;
static const LLFlatListView::ItemReverseComparator REVERSE_NAME_COMPARATOR(NAME_COMPARATOR);
LLAvatarList::Params::Params()
: ignore_online_status("ignore_online_status", false)
{
}
LLAvatarList::LLAvatarList(const Params& p)
: LLFlatListView(p)
, mIgnoreOnlineStatus(p.ignore_online_status)
, mContextMenu(NULL)
, mDirty(true) // to force initial update
{
setCommitOnSelectionChange(true);
// Set default sort order.
setComparator(&NAME_COMPARATOR);
}
void LLAvatarList::setShowIcons(std::string param_name)
{
mIconParamName= param_name;
mShowIcons = gSavedSettings.getBOOL(mIconParamName);
}
// virtual
void LLAvatarList::draw()
{
if (mDirty)
refresh();
LLFlatListView::draw();
}
void LLAvatarList::setNameFilter(const std::string& filter)
{
if (mNameFilter != filter)
{
mNameFilter = filter;
setDirty();
}
}
void LLAvatarList::sortByName()
{
setComparator(&NAME_COMPARATOR);
sort();
}
//////////////////////////////////////////////////////////////////////////
// PROTECTED SECTION
//////////////////////////////////////////////////////////////////////////
void LLAvatarList::refresh()
{
bool have_names = TRUE;
bool add_limit_exceeded = false;
bool modified = false;
bool have_filter = !mNameFilter.empty();
// Save selection.
std::vector<LLUUID> selected_ids;
getSelectedUUIDs(selected_ids);
LLUUID current_id = getSelectedUUID();
// Determine what to add and what to remove.
std::vector<LLUUID> added, removed;
LLAvatarList::computeDifference(getIDs(), added, removed);
// Handle added items.
unsigned nadded = 0;
for (std::vector<LLUUID>::const_iterator it=added.begin(); it != added.end(); it++)
{
std::string name;
const LLUUID& buddy_id = *it;
have_names &= (bool)gCacheName->getFullName(buddy_id, name);
if (!have_filter || findInsensitive(name, mNameFilter))
{
if (nadded >= ADD_LIMIT)
{
add_limit_exceeded = true;
break;
}
else
{
addNewItem(buddy_id, name, LLAvatarTracker::instance().isBuddyOnline(buddy_id));
modified = true;
nadded++;
}
}
}
// Handle removed items.
for (std::vector<LLUUID>::const_iterator it=removed.begin(); it != removed.end(); it++)
{
removeItemByUUID(*it);
modified = true;
}
// Handle filter.
if (have_filter)
{
std::vector<LLSD> cur_values;
getValues(cur_values);
for (std::vector<LLSD>::const_iterator it=cur_values.begin(); it != cur_values.end(); it++)
{
std::string name;
const LLUUID& buddy_id = it->asUUID();
have_names &= (bool)gCacheName->getFullName(buddy_id, name);
if (!findInsensitive(name, mNameFilter))
{
removeItemByUUID(buddy_id);
modified = true;
}
}
}
// Changed item in place, need to request sort and update columns
// because we might have changed data in a column on which the user
// has already sorted. JC
sort();
// re-select items
// selectMultiple(selected_ids); // TODO: implement in LLFlatListView if need
selectItemByUUID(current_id);
// If the name filter is specified and the names are incomplete,
// we need to re-update when the names are complete so that
// the filter can be applied correctly.
//
// Otherwise, if we have no filter then no need to update again
// because the items will update their names.
bool dirty = add_limit_exceeded || (have_filter && !have_names);
setDirty(dirty);
// Commit if we've added/removed items.
if (modified)
onCommit();
}
void LLAvatarList::addNewItem(const LLUUID& id, const std::string& name, BOOL is_online, EAddPosition pos)
{
LLAvatarListItem* item = new LLAvatarListItem();
item->showStatus(false);
item->showInfoBtn(true);
item->showSpeakingIndicator(true);
item->setName(name);
item->setAvatarId(id, mIgnoreOnlineStatus);
item->setOnline(mIgnoreOnlineStatus ? true : is_online);
item->setContextMenu(mContextMenu);
item->childSetVisible("info_btn", false);
item->setAvatarIconVisible(mShowIcons);
addItem(item, id, pos);
}
// virtual
BOOL LLAvatarList::handleRightMouseDown(S32 x, S32 y, MASK mask)
{
BOOL handled = LLUICtrl::handleRightMouseDown(x, y, mask);
if ( mContextMenu )
{
std::vector<LLUUID> selected_uuids;
getSelectedUUIDs(selected_uuids);
mContextMenu->show(this, selected_uuids, x, y);
}
return handled;
}
void LLAvatarList::computeDifference(
const std::vector<LLUUID>& vnew_unsorted,
std::vector<LLUUID>& vadded,
std::vector<LLUUID>& vremoved)
{
std::vector<LLUUID> vcur;
std::vector<LLUUID> vnew = vnew_unsorted;
// Convert LLSDs to LLUUIDs.
{
std::vector<LLSD> vcur_values;
getValues(vcur_values);
for (size_t i=0; i<vcur_values.size(); i++)
vcur.push_back(vcur_values[i].asUUID());
}
std::sort(vcur.begin(), vcur.end());
std::sort(vnew.begin(), vnew.end());
std::vector<LLUUID>::iterator it;
size_t maxsize = llmax(vcur.size(), vnew.size());
vadded.resize(maxsize);
vremoved.resize(maxsize);
// what to remove
it = set_difference(vcur.begin(), vcur.end(), vnew.begin(), vnew.end(), vremoved.begin());
vremoved.erase(it, vremoved.end());
// what to add
it = set_difference(vnew.begin(), vnew.end(), vcur.begin(), vcur.end(), vadded.begin());
vadded.erase(it, vadded.end());
}
bool LLAvatarItemComparator::compare(const LLPanel* item1, const LLPanel* item2) const
{
const LLAvatarListItem* avatar_item1 = dynamic_cast<const LLAvatarListItem*>(item1);
const LLAvatarListItem* avatar_item2 = dynamic_cast<const LLAvatarListItem*>(item2);
if (!avatar_item1 || !avatar_item2)
{
llerror("item1 and item2 cannot be null", 0);
return true;
}
return doCompare(avatar_item1, avatar_item2);
}
bool LLAvatarItemNameComparator::doCompare(const LLAvatarListItem* avatar_item1, const LLAvatarListItem* avatar_item2) const
{
std::string name1 = avatar_item1->getAvatarName();
std::string name2 = avatar_item2->getAvatarName();
LLStringUtil::toUpper(name1);
LLStringUtil::toUpper(name2);
return name1 < name2;
}
<commit_msg>Fixed normal bug EXT-1164 - FlatList isn't reshaped on filtering when accordion panels are collpased.<commit_after>/**
* @file llavatarlist.h
* @brief Generic avatar list
*
* $LicenseInfo:firstyear=2009&license=viewergpl$
*
* Copyright (c) 2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden Lab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llavatarlist.h"
// newview
#include "llcallingcard.h" // for LLAvatarTracker
#include "llcachename.h"
#include "llvoiceclient.h"
#include "llviewercontrol.h" // for gSavedSettings
static LLDefaultChildRegistry::Register<LLAvatarList> r("avatar_list");
// Maximum number of avatars that can be added to a list in one pass.
// Used to limit time spent for avatar list update per frame.
static const unsigned ADD_LIMIT = 50;
void LLAvatarList::toggleIcons()
{
// Save the new value for new items to use.
mShowIcons = !mShowIcons;
gSavedSettings.setBOOL(mIconParamName, mShowIcons);
// Show/hide icons for all existing items.
std::vector<LLPanel*> items;
getItems(items);
for( std::vector<LLPanel*>::const_iterator it = items.begin(); it != items.end(); it++)
{
static_cast<LLAvatarListItem*>(*it)->setAvatarIconVisible(mShowIcons);
}
}
static bool findInsensitive(std::string haystack, const std::string& needle_upper)
{
LLStringUtil::toUpper(haystack);
return haystack.find(needle_upper) != std::string::npos;
}
//comparators
static const LLAvatarItemNameComparator NAME_COMPARATOR;
static const LLFlatListView::ItemReverseComparator REVERSE_NAME_COMPARATOR(NAME_COMPARATOR);
LLAvatarList::Params::Params()
: ignore_online_status("ignore_online_status", false)
{
}
LLAvatarList::LLAvatarList(const Params& p)
: LLFlatListView(p)
, mIgnoreOnlineStatus(p.ignore_online_status)
, mContextMenu(NULL)
, mDirty(true) // to force initial update
{
setCommitOnSelectionChange(true);
// Set default sort order.
setComparator(&NAME_COMPARATOR);
}
void LLAvatarList::setShowIcons(std::string param_name)
{
mIconParamName= param_name;
mShowIcons = gSavedSettings.getBOOL(mIconParamName);
}
// virtual
void LLAvatarList::draw()
{
LLFlatListView::draw();
if (mDirty)
refresh();
}
void LLAvatarList::setNameFilter(const std::string& filter)
{
if (mNameFilter != filter)
{
mNameFilter = filter;
setDirty();
}
}
void LLAvatarList::sortByName()
{
setComparator(&NAME_COMPARATOR);
sort();
}
//////////////////////////////////////////////////////////////////////////
// PROTECTED SECTION
//////////////////////////////////////////////////////////////////////////
void LLAvatarList::refresh()
{
bool have_names = TRUE;
bool add_limit_exceeded = false;
bool modified = false;
bool have_filter = !mNameFilter.empty();
// Save selection.
std::vector<LLUUID> selected_ids;
getSelectedUUIDs(selected_ids);
LLUUID current_id = getSelectedUUID();
// Determine what to add and what to remove.
std::vector<LLUUID> added, removed;
LLAvatarList::computeDifference(getIDs(), added, removed);
// Handle added items.
unsigned nadded = 0;
for (std::vector<LLUUID>::const_iterator it=added.begin(); it != added.end(); it++)
{
std::string name;
const LLUUID& buddy_id = *it;
have_names &= (bool)gCacheName->getFullName(buddy_id, name);
if (!have_filter || findInsensitive(name, mNameFilter))
{
if (nadded >= ADD_LIMIT)
{
add_limit_exceeded = true;
break;
}
else
{
addNewItem(buddy_id, name, LLAvatarTracker::instance().isBuddyOnline(buddy_id));
modified = true;
nadded++;
}
}
}
// Handle removed items.
for (std::vector<LLUUID>::const_iterator it=removed.begin(); it != removed.end(); it++)
{
removeItemByUUID(*it);
modified = true;
}
// Handle filter.
if (have_filter)
{
std::vector<LLSD> cur_values;
getValues(cur_values);
for (std::vector<LLSD>::const_iterator it=cur_values.begin(); it != cur_values.end(); it++)
{
std::string name;
const LLUUID& buddy_id = it->asUUID();
have_names &= (bool)gCacheName->getFullName(buddy_id, name);
if (!findInsensitive(name, mNameFilter))
{
removeItemByUUID(buddy_id);
modified = true;
}
}
}
// Changed item in place, need to request sort and update columns
// because we might have changed data in a column on which the user
// has already sorted. JC
sort();
// re-select items
// selectMultiple(selected_ids); // TODO: implement in LLFlatListView if need
selectItemByUUID(current_id);
// If the name filter is specified and the names are incomplete,
// we need to re-update when the names are complete so that
// the filter can be applied correctly.
//
// Otherwise, if we have no filter then no need to update again
// because the items will update their names.
bool dirty = add_limit_exceeded || (have_filter && !have_names);
setDirty(dirty);
// Commit if we've added/removed items.
if (modified)
onCommit();
}
void LLAvatarList::addNewItem(const LLUUID& id, const std::string& name, BOOL is_online, EAddPosition pos)
{
LLAvatarListItem* item = new LLAvatarListItem();
item->showStatus(false);
item->showInfoBtn(true);
item->showSpeakingIndicator(true);
item->setName(name);
item->setAvatarId(id, mIgnoreOnlineStatus);
item->setOnline(mIgnoreOnlineStatus ? true : is_online);
item->setContextMenu(mContextMenu);
item->childSetVisible("info_btn", false);
item->setAvatarIconVisible(mShowIcons);
addItem(item, id, pos);
}
// virtual
BOOL LLAvatarList::handleRightMouseDown(S32 x, S32 y, MASK mask)
{
BOOL handled = LLUICtrl::handleRightMouseDown(x, y, mask);
if ( mContextMenu )
{
std::vector<LLUUID> selected_uuids;
getSelectedUUIDs(selected_uuids);
mContextMenu->show(this, selected_uuids, x, y);
}
return handled;
}
void LLAvatarList::computeDifference(
const std::vector<LLUUID>& vnew_unsorted,
std::vector<LLUUID>& vadded,
std::vector<LLUUID>& vremoved)
{
std::vector<LLUUID> vcur;
std::vector<LLUUID> vnew = vnew_unsorted;
// Convert LLSDs to LLUUIDs.
{
std::vector<LLSD> vcur_values;
getValues(vcur_values);
for (size_t i=0; i<vcur_values.size(); i++)
vcur.push_back(vcur_values[i].asUUID());
}
std::sort(vcur.begin(), vcur.end());
std::sort(vnew.begin(), vnew.end());
std::vector<LLUUID>::iterator it;
size_t maxsize = llmax(vcur.size(), vnew.size());
vadded.resize(maxsize);
vremoved.resize(maxsize);
// what to remove
it = set_difference(vcur.begin(), vcur.end(), vnew.begin(), vnew.end(), vremoved.begin());
vremoved.erase(it, vremoved.end());
// what to add
it = set_difference(vnew.begin(), vnew.end(), vcur.begin(), vcur.end(), vadded.begin());
vadded.erase(it, vadded.end());
}
bool LLAvatarItemComparator::compare(const LLPanel* item1, const LLPanel* item2) const
{
const LLAvatarListItem* avatar_item1 = dynamic_cast<const LLAvatarListItem*>(item1);
const LLAvatarListItem* avatar_item2 = dynamic_cast<const LLAvatarListItem*>(item2);
if (!avatar_item1 || !avatar_item2)
{
llerror("item1 and item2 cannot be null", 0);
return true;
}
return doCompare(avatar_item1, avatar_item2);
}
bool LLAvatarItemNameComparator::doCompare(const LLAvatarListItem* avatar_item1, const LLAvatarListItem* avatar_item2) const
{
std::string name1 = avatar_item1->getAvatarName();
std::string name2 = avatar_item2->getAvatarName();
LLStringUtil::toUpper(name1);
LLStringUtil::toUpper(name2);
return name1 < name2;
}
<|endoftext|> |
<commit_before>#include"../header/IThreadPoolItemBase.hpp"
#include<utility> //forward, move
#include"../../lib/header/thread/CSemaphore.hpp"
#include"../../lib/header/thread/CSmartThread.hpp"
using namespace std;
namespace nThread
{
struct IThreadPoolItemBase::Impl
{
bool destructor;
CSemaphore wait; //to wake up thr
CSmartThread thr; //must destroying before destructor and wait
function<void()> func;
Impl();
template<class FuncFwdRef>
void exec(FuncFwdRef &&val)
{
func=forward<FuncFwdRef>(val);
wake();
}
inline void wake()
{
wait.signal();
}
~Impl();
};
IThreadPoolItemBase::Impl::Impl()
:destructor{false},wait{0},thr{[this]{
while(wait.wait(),!destructor)
func();
}}{}
IThreadPoolItemBase::Impl::~Impl()
{
destructor=true;
wake();
}
IThreadPoolItemBase::IThreadPoolItemBase()
:impl_{}{}
IThreadPoolItemBase::IThreadPoolItemBase(IThreadPoolItemBase &&xval) noexcept
:impl_{move(xval.impl_)}{}
thread::id IThreadPoolItemBase::get_id() const noexcept
{
return impl_.get().thr.get_id();
}
IThreadPoolItemBase& IThreadPoolItemBase::operator=(IThreadPoolItemBase &&xval) noexcept
{
impl_=move(xval.impl_);
return *this;
}
IThreadPoolItemBase::~IThreadPoolItemBase(){}
void IThreadPoolItemBase::exec_(const function<void()> &val)
{
impl_.get().exec(val);
}
void IThreadPoolItemBase::exec_(function<void()> &&xval)
{
impl_.get().exec(move(xval));
}
}<commit_msg>replace destructor to alive<commit_after>#include"../header/IThreadPoolItemBase.hpp"
#include<utility> //forward, move
#include"../../lib/header/thread/CSemaphore.hpp"
#include"../../lib/header/thread/CSmartThread.hpp"
using namespace std;
namespace nThread
{
struct IThreadPoolItemBase::Impl
{
bool alive;
CSemaphore wait; //to wake up thr
CSmartThread thr; //must destroying before alive and wait
function<void()> func;
Impl();
template<class FuncFwdRef>
void exec(FuncFwdRef &&val)
{
func=forward<FuncFwdRef>(val);
wake();
}
inline void wake()
{
wait.signal();
}
~Impl();
};
IThreadPoolItemBase::Impl::Impl()
:alive{true},wait{0},thr{[this]{
while(wait.wait(),alive)
func();
}}{}
IThreadPoolItemBase::Impl::~Impl()
{
alive=false;
wake();
}
IThreadPoolItemBase::IThreadPoolItemBase()
:impl_{}{}
IThreadPoolItemBase::IThreadPoolItemBase(IThreadPoolItemBase &&xval) noexcept
:impl_{move(xval.impl_)}{}
thread::id IThreadPoolItemBase::get_id() const noexcept
{
return impl_.get().thr.get_id();
}
IThreadPoolItemBase& IThreadPoolItemBase::operator=(IThreadPoolItemBase &&xval) noexcept
{
impl_=move(xval.impl_);
return *this;
}
IThreadPoolItemBase::~IThreadPoolItemBase(){}
void IThreadPoolItemBase::exec_(const function<void()> &val)
{
impl_.get().exec(val);
}
void IThreadPoolItemBase::exec_(function<void()> &&xval)
{
impl_.get().exec(move(xval));
}
}<|endoftext|> |
<commit_before>// Copyright (c) 2013, Kenton Varda <temporal@gmail.com>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "arena.h"
#include "message.h"
#include <vector>
#include <string.h>
#include <iostream>
namespace capnproto {
namespace internal {
Arena::~Arena() {}
// =======================================================================================
ReaderArena::ReaderArena(MessageReader* message)
: message(message),
readLimiter(message->getOptions().traversalLimitInWords * WORDS),
ignoreErrors(false),
segment0(this, SegmentId(0), message->getSegment(0), &readLimiter) {}
ReaderArena::~ReaderArena() {}
SegmentReader* ReaderArena::tryGetSegment(SegmentId id) {
if (id == SegmentId(0)) {
if (segment0.getArray() == nullptr) {
return nullptr;
} else {
return &segment0;
}
}
// TODO: Lock a mutex so that reading is thread-safe. Take a reader lock during the first
// lookup, unlock it before calling getSegment(), then take a writer lock to update the map.
// Bleh, lazy initialization is sad.
if (moreSegments != nullptr) {
auto iter = moreSegments->find(id.value);
if (iter != moreSegments->end()) {
return iter->second.get();
}
}
ArrayPtr<const word> newSegment = message->getSegment(id.value);
if (newSegment == nullptr) {
return nullptr;
}
if (moreSegments == nullptr) {
// OK, the segment exists, so allocate the map.
moreSegments = std::unique_ptr<SegmentMap>(new SegmentMap);
}
std::unique_ptr<SegmentReader>* slot = &(*moreSegments)[id.value];
*slot = std::unique_ptr<SegmentReader>(new SegmentReader(this, id, newSegment, &readLimiter));
return slot->get();
}
void ReaderArena::reportInvalidData(const char* description) {
if (!ignoreErrors) {
message->getOptions().errorReporter->reportError(description);
}
}
void ReaderArena::reportReadLimitReached() {
if (!ignoreErrors) {
message->getOptions().errorReporter->reportError(
"Exceeded message traversal limit. See capnproto::ReaderOptions.");
// Ignore further errors since they are likely repeats or caused by the read limit being
// reached.
ignoreErrors = true;
}
}
// =======================================================================================
BuilderArena::BuilderArena(MessageBuilder* message)
: message(message), segment0(nullptr, SegmentId(0), nullptr, nullptr) {}
BuilderArena::~BuilderArena() {}
SegmentBuilder* BuilderArena::getSegment(SegmentId id) {
// This method is allowed to crash if the segment ID is not valid.
if (id == SegmentId(0)) {
return &segment0;
} else {
return moreSegments->builders[id.value - 1].get();
}
}
SegmentBuilder* BuilderArena::getSegmentWithAvailable(WordCount minimumAvailable) {
// TODO: Mutex-locking? Do we want to allow people to build different parts of the same message
// in different threads?
if (segment0.getArena() == nullptr) {
// We're allocating the first segment.
ArrayPtr<word> ptr = message->allocateSegment(minimumAvailable / WORDS);
// Re-allocate segment0 in-place. This is a bit of a hack, but we have not returned any
// pointers to this segment yet, so it should be fine.
segment0.~SegmentBuilder();
return new (&segment0) SegmentBuilder(this, SegmentId(0), ptr, &this->dummyLimiter);
} else {
if (segment0.available() >= minimumAvailable) {
return &segment0;
}
if (moreSegments == nullptr) {
moreSegments = std::unique_ptr<MultiSegmentState>(new MultiSegmentState());
} else {
// TODO: Check for available space in more than just the last segment. We don't want this
// to be O(n), though, so we'll need to maintain some sort of table. Complicating matters,
// we want SegmentBuilders::allocate() to be fast, so we can't update any such table when
// allocation actually happens. Instead, we could have a priority queue based on the
// last-known available size, and then re-check the size when we pop segments off it and
// shove them to the back of the queue if they have become too small.
if (moreSegments->builders.back()->available() >= minimumAvailable) {
return moreSegments->builders.back().get();
}
}
std::unique_ptr<SegmentBuilder> newBuilder = std::unique_ptr<SegmentBuilder>(
new SegmentBuilder(this, SegmentId(moreSegments->builders.size() + 1),
message->allocateSegment(minimumAvailable / WORDS), &this->dummyLimiter));
SegmentBuilder* result = newBuilder.get();
moreSegments->builders.push_back(std::move(newBuilder));
// Keep forOutput the right size so that we don't have to re-allocate during
// getSegmentsForOutput(), which callers might reasonably expect is a thread-safe method.
moreSegments->forOutput.resize(moreSegments->builders.size() + 1);
return result;
}
}
ArrayPtr<const ArrayPtr<const word>> BuilderArena::getSegmentsForOutput() {
// We shouldn't need to lock a mutex here because if this is called multiple times simultaneously,
// we should only be overwriting the array with the exact same data. If the number or size of
// segments is actually changing due to an activity in another thread, then the caller has a
// problem regardless of locking here.
if (moreSegments == nullptr) {
if (segment0.getArena() == nullptr) {
// We haven't actually allocated any segments yet.
return nullptr;
} else {
// We have only one segment so far.
segment0ForOutput = segment0.currentlyAllocated();
return arrayPtr(&segment0ForOutput, 1);
}
} else {
CAPNPROTO_DEBUG_ASSERT(moreSegments->forOutput.size() == moreSegments->builders.size() + 1,
"Bug in capnproto::internal::BuilderArena: moreSegments->forOutput wasn't resized "
"correctly when the last builder was added.");
ArrayPtr<ArrayPtr<const word>> result(
&moreSegments->forOutput[0], moreSegments->forOutput.size());
uint i = 0;
result[i++] = segment0.currentlyAllocated();
for (auto& builder: moreSegments->builders) {
result[i++] = builder->currentlyAllocated();
}
return result;
}
}
SegmentReader* BuilderArena::tryGetSegment(SegmentId id) {
if (id == SegmentId(0)) {
if (segment0.getArena() == nullptr) {
// We haven't allocated any segments yet.
return nullptr;
} else {
return &segment0;
}
} else {
if (moreSegments == nullptr || id.value > moreSegments->builders.size()) {
return nullptr;
} else {
return moreSegments->builders[id.value - 1].get();
}
}
}
void BuilderArena::reportInvalidData(const char* description) {
// TODO: Better error reporting.
std::cerr << "BuilderArena: Parse error: " << description << std::endl;
}
void BuilderArena::reportReadLimitReached() {
// TODO: Better error reporting.
std::cerr << "BuilderArena: Exceeded read limit." << std::endl;
}
} // namespace internal
} // namespace capnproto
<commit_msg>Remove iostream from prod sources.<commit_after>// Copyright (c) 2013, Kenton Varda <temporal@gmail.com>
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "arena.h"
#include "message.h"
#include <vector>
#include <string.h>
#include <stdio.h>
namespace capnproto {
namespace internal {
Arena::~Arena() {}
// =======================================================================================
ReaderArena::ReaderArena(MessageReader* message)
: message(message),
readLimiter(message->getOptions().traversalLimitInWords * WORDS),
ignoreErrors(false),
segment0(this, SegmentId(0), message->getSegment(0), &readLimiter) {}
ReaderArena::~ReaderArena() {}
SegmentReader* ReaderArena::tryGetSegment(SegmentId id) {
if (id == SegmentId(0)) {
if (segment0.getArray() == nullptr) {
return nullptr;
} else {
return &segment0;
}
}
// TODO: Lock a mutex so that reading is thread-safe. Take a reader lock during the first
// lookup, unlock it before calling getSegment(), then take a writer lock to update the map.
// Bleh, lazy initialization is sad.
if (moreSegments != nullptr) {
auto iter = moreSegments->find(id.value);
if (iter != moreSegments->end()) {
return iter->second.get();
}
}
ArrayPtr<const word> newSegment = message->getSegment(id.value);
if (newSegment == nullptr) {
return nullptr;
}
if (moreSegments == nullptr) {
// OK, the segment exists, so allocate the map.
moreSegments = std::unique_ptr<SegmentMap>(new SegmentMap);
}
std::unique_ptr<SegmentReader>* slot = &(*moreSegments)[id.value];
*slot = std::unique_ptr<SegmentReader>(new SegmentReader(this, id, newSegment, &readLimiter));
return slot->get();
}
void ReaderArena::reportInvalidData(const char* description) {
if (!ignoreErrors) {
message->getOptions().errorReporter->reportError(description);
}
}
void ReaderArena::reportReadLimitReached() {
if (!ignoreErrors) {
message->getOptions().errorReporter->reportError(
"Exceeded message traversal limit. See capnproto::ReaderOptions.");
// Ignore further errors since they are likely repeats or caused by the read limit being
// reached.
ignoreErrors = true;
}
}
// =======================================================================================
BuilderArena::BuilderArena(MessageBuilder* message)
: message(message), segment0(nullptr, SegmentId(0), nullptr, nullptr) {}
BuilderArena::~BuilderArena() {}
SegmentBuilder* BuilderArena::getSegment(SegmentId id) {
// This method is allowed to crash if the segment ID is not valid.
if (id == SegmentId(0)) {
return &segment0;
} else {
return moreSegments->builders[id.value - 1].get();
}
}
SegmentBuilder* BuilderArena::getSegmentWithAvailable(WordCount minimumAvailable) {
// TODO: Mutex-locking? Do we want to allow people to build different parts of the same message
// in different threads?
if (segment0.getArena() == nullptr) {
// We're allocating the first segment.
ArrayPtr<word> ptr = message->allocateSegment(minimumAvailable / WORDS);
// Re-allocate segment0 in-place. This is a bit of a hack, but we have not returned any
// pointers to this segment yet, so it should be fine.
segment0.~SegmentBuilder();
return new (&segment0) SegmentBuilder(this, SegmentId(0), ptr, &this->dummyLimiter);
} else {
if (segment0.available() >= minimumAvailable) {
return &segment0;
}
if (moreSegments == nullptr) {
moreSegments = std::unique_ptr<MultiSegmentState>(new MultiSegmentState());
} else {
// TODO: Check for available space in more than just the last segment. We don't want this
// to be O(n), though, so we'll need to maintain some sort of table. Complicating matters,
// we want SegmentBuilders::allocate() to be fast, so we can't update any such table when
// allocation actually happens. Instead, we could have a priority queue based on the
// last-known available size, and then re-check the size when we pop segments off it and
// shove them to the back of the queue if they have become too small.
if (moreSegments->builders.back()->available() >= minimumAvailable) {
return moreSegments->builders.back().get();
}
}
std::unique_ptr<SegmentBuilder> newBuilder = std::unique_ptr<SegmentBuilder>(
new SegmentBuilder(this, SegmentId(moreSegments->builders.size() + 1),
message->allocateSegment(minimumAvailable / WORDS), &this->dummyLimiter));
SegmentBuilder* result = newBuilder.get();
moreSegments->builders.push_back(std::move(newBuilder));
// Keep forOutput the right size so that we don't have to re-allocate during
// getSegmentsForOutput(), which callers might reasonably expect is a thread-safe method.
moreSegments->forOutput.resize(moreSegments->builders.size() + 1);
return result;
}
}
ArrayPtr<const ArrayPtr<const word>> BuilderArena::getSegmentsForOutput() {
// We shouldn't need to lock a mutex here because if this is called multiple times simultaneously,
// we should only be overwriting the array with the exact same data. If the number or size of
// segments is actually changing due to an activity in another thread, then the caller has a
// problem regardless of locking here.
if (moreSegments == nullptr) {
if (segment0.getArena() == nullptr) {
// We haven't actually allocated any segments yet.
return nullptr;
} else {
// We have only one segment so far.
segment0ForOutput = segment0.currentlyAllocated();
return arrayPtr(&segment0ForOutput, 1);
}
} else {
CAPNPROTO_DEBUG_ASSERT(moreSegments->forOutput.size() == moreSegments->builders.size() + 1,
"Bug in capnproto::internal::BuilderArena: moreSegments->forOutput wasn't resized "
"correctly when the last builder was added.");
ArrayPtr<ArrayPtr<const word>> result(
&moreSegments->forOutput[0], moreSegments->forOutput.size());
uint i = 0;
result[i++] = segment0.currentlyAllocated();
for (auto& builder: moreSegments->builders) {
result[i++] = builder->currentlyAllocated();
}
return result;
}
}
SegmentReader* BuilderArena::tryGetSegment(SegmentId id) {
if (id == SegmentId(0)) {
if (segment0.getArena() == nullptr) {
// We haven't allocated any segments yet.
return nullptr;
} else {
return &segment0;
}
} else {
if (moreSegments == nullptr || id.value > moreSegments->builders.size()) {
return nullptr;
} else {
return moreSegments->builders[id.value - 1].get();
}
}
}
void BuilderArena::reportInvalidData(const char* description) {
// TODO: Better error reporting.
fprintf(stderr, "BuilderArena: Parse error: %s\n", description);
}
void BuilderArena::reportReadLimitReached() {
// TODO: Better error reporting.
fputs("BuilderArena: Exceeded read limit.\n", stderr);
}
} // namespace internal
} // namespace capnproto
<|endoftext|> |
<commit_before>/**
* @file LLNearbyChat.cpp
* @brief Nearby chat history scrolling panel implementation
*
* $LicenseInfo:firstyear=2009&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llnearbychat.h"
#include "llviewercontrol.h"
#include "llviewerwindow.h"
#include "llrootview.h"
//#include "llchatitemscontainerctrl.h"
#include "lliconctrl.h"
#include "llfloatersidepanelcontainer.h"
#include "llfocusmgr.h"
#include "lllogchat.h"
#include "llresizebar.h"
#include "llresizehandle.h"
#include "llmenugl.h"
#include "llviewermenu.h"//for gMenuHolder
#include "llnearbychathandler.h"
#include "llchannelmanager.h"
#include "llagent.h" // gAgent
#include "llchathistory.h"
#include "llstylemap.h"
#include "llavatarnamecache.h"
#include "lldraghandle.h"
#include "llnearbychatbar.h"
#include "llfloaterreg.h"
#include "lltrans.h"
static const S32 RESIZE_BAR_THICKNESS = 3;
static LLRegisterPanelClassWrapper<LLNearbyChat> t_panel_nearby_chat("panel_nearby_chat");
LLNearbyChat::LLNearbyChat()
: LLPanel()
,mChatHistory(NULL)
{
}
LLNearbyChat::~LLNearbyChat()
{
}
BOOL LLNearbyChat::postBuild()
{
//menu
LLUICtrl::CommitCallbackRegistry::ScopedRegistrar registrar;
LLUICtrl::EnableCallbackRegistry::ScopedRegistrar enable_registrar;
enable_registrar.add("NearbyChat.Check", boost::bind(&LLNearbyChat::onNearbyChatCheckContextMenuItem, this, _2));
registrar.add("NearbyChat.Action", boost::bind(&LLNearbyChat::onNearbyChatContextMenuItemClicked, this, _2));
LLMenuGL* menu = LLUICtrlFactory::getInstance()->createFromFile<LLMenuGL>("menu_nearby_chat.xml", gMenuHolder, LLViewerMenuHolderGL::child_registry_t::instance());
if(menu)
mPopupMenuHandle = menu->getHandle();
gSavedSettings.declareS32("nearbychat_showicons_and_names",2,"NearByChat header settings",true);
mChatHistory = getChild<LLChatHistory>("chat_history");
if(!LLPanel::postBuild())
return false;
return true;
}
std::string appendTime()
{
time_t utc_time;
utc_time = time_corrected();
std::string timeStr ="["+ LLTrans::getString("TimeHour")+"]:["
+LLTrans::getString("TimeMin")+"]";
LLSD substitution;
substitution["datetime"] = (S32) utc_time;
LLStringUtil::format (timeStr, substitution);
return timeStr;
}
void LLNearbyChat::addMessage(const LLChat& chat,bool archive,const LLSD &args)
{
LLChat& tmp_chat = const_cast<LLChat&>(chat);
if(tmp_chat.mTimeStr.empty())
tmp_chat.mTimeStr = appendTime();
bool use_plain_text_chat_history = gSavedSettings.getBOOL("PlainTextChatHistory");
if (!chat.mMuted)
{
tmp_chat.mFromName = chat.mFromName;
LLSD chat_args = args;
chat_args["use_plain_text_chat_history"] = use_plain_text_chat_history;
mChatHistory->appendMessage(chat, chat_args);
}
if(archive)
{
mMessageArchive.push_back(chat);
if(mMessageArchive.size()>200)
mMessageArchive.erase(mMessageArchive.begin());
}
if (args["do_not_log"].asBoolean())
{
return;
}
if (gSavedPerAccountSettings.getBOOL("LogNearbyChat"))
{
std::string from_name = chat.mFromName;
if (chat.mSourceType == CHAT_SOURCE_AGENT)
{
// if the chat is coming from an agent, log the complete name
LLAvatarName av_name;
LLAvatarNameCache::get(chat.mFromID, &av_name);
if (!av_name.mIsDisplayNameDefault)
{
from_name = av_name.getCompleteName();
}
}
LLLogChat::saveHistory("chat", from_name, chat.mFromID, chat.mText);
}
}
void LLNearbyChat::onNearbySpeakers()
{
LLSD param;
param["people_panel_tab_name"] = "nearby_panel";
LLFloaterSidePanelContainer::showPanel("people", "panel_people", param);
}
void LLNearbyChat::onNearbyChatContextMenuItemClicked(const LLSD& userdata)
{
}
bool LLNearbyChat::onNearbyChatCheckContextMenuItem(const LLSD& userdata)
{
std::string str = userdata.asString();
if(str == "nearby_people")
onNearbySpeakers();
return false;
}
void LLNearbyChat::setVisible(BOOL visible)
{
if(visible)
{
LLNotificationsUI::LLScreenChannelBase* chat_channel = LLNotificationsUI::LLChannelManager::getInstance()->findChannelByID(LLUUID(gSavedSettings.getString("NearByChatChannelUUID")));
if(chat_channel)
{
chat_channel->removeToastsFromChannel();
}
}
LLPanel::setVisible(visible);
}
void LLNearbyChat::getAllowedRect(LLRect& rect)
{
rect = gViewerWindow->getWorldViewRectScaled();
}
void LLNearbyChat::updateChatHistoryStyle()
{
mChatHistory->clear();
LLSD do_not_log;
do_not_log["do_not_log"] = true;
for(std::vector<LLChat>::iterator it = mMessageArchive.begin();it!=mMessageArchive.end();++it)
{
// Update the messages without re-writing them to a log file.
addMessage(*it,false, do_not_log);
}
}
//static
void LLNearbyChat::processChatHistoryStyleUpdate(const LLSD& newvalue)
{
//LLNearbyChat* nearby_chat = LLFloaterReg::getTypedInstance<LLNearbyChat>("nearby_chat", LLSD());
//if(nearby_chat)
// nearby_chat->updateChatHistoryStyle();
}
bool isWordsName(const std::string& name)
{
// checking to see if it's display name plus username in parentheses
S32 open_paren = name.find(" (", 0);
S32 close_paren = name.find(')', 0);
if (open_paren != std::string::npos &&
close_paren == name.length()-1)
{
return true;
}
else
{
//checking for a single space
S32 pos = name.find(' ', 0);
return std::string::npos != pos && name.rfind(' ', name.length()) == pos && 0 != pos && name.length()-1 != pos;
}
}
void LLNearbyChat::loadHistory()
{
LLSD do_not_log;
do_not_log["do_not_log"] = true;
std::list<LLSD> history;
LLLogChat::loadAllHistory("chat", history);
std::list<LLSD>::const_iterator it = history.begin();
while (it != history.end())
{
const LLSD& msg = *it;
std::string from = msg[IM_FROM];
LLUUID from_id;
if (msg[IM_FROM_ID].isDefined())
{
from_id = msg[IM_FROM_ID].asUUID();
}
else
{
std::string legacy_name = gCacheName->buildLegacyName(from);
gCacheName->getUUID(legacy_name, from_id);
}
LLChat chat;
chat.mFromName = from;
chat.mFromID = from_id;
chat.mText = msg[IM_TEXT].asString();
chat.mTimeStr = msg[IM_TIME].asString();
chat.mChatStyle = CHAT_STYLE_HISTORY;
chat.mSourceType = CHAT_SOURCE_AGENT;
if (from_id.isNull() && SYSTEM_FROM == from)
{
chat.mSourceType = CHAT_SOURCE_SYSTEM;
}
else if (from_id.isNull())
{
chat.mSourceType = isWordsName(from) ? CHAT_SOURCE_UNKNOWN : CHAT_SOURCE_OBJECT;
}
addMessage(chat, true, do_not_log);
it++;
}
}
//static
LLNearbyChat* LLNearbyChat::getInstance()
{
LLFloater* chat_bar = LLFloaterReg::getInstance("chat_bar");
return chat_bar->findChild<LLNearbyChat>("nearby_chat");
}
////////////////////////////////////////////////////////////////////////////////
//
void LLNearbyChat::onFocusReceived()
{
setBackgroundOpaque(true);
LLPanel::onFocusReceived();
}
////////////////////////////////////////////////////////////////////////////////
//
void LLNearbyChat::onFocusLost()
{
setBackgroundOpaque(false);
LLPanel::onFocusLost();
}
BOOL LLNearbyChat::handleMouseDown(S32 x, S32 y, MASK mask)
{
//fix for EXT-6625
//highlight NearbyChat history whenever mouseclick happen in NearbyChat
//setting focus to eidtor will force onFocusLost() call that in its turn will change
//background opaque. This all happenn since NearByChat is "chrome" and didn't process focus change.
if(mChatHistory)
mChatHistory->setFocus(TRUE);
return LLPanel::handleMouseDown(x, y, mask);
}
void LLNearbyChat::draw()
{
// *HACK: Update transparency type depending on whether our children have focus.
// This is needed because this floater is chrome and thus cannot accept focus, so
// the transparency type setting code from LLFloater::setFocus() isn't reached.
if (getTransparencyType() != TT_DEFAULT)
{
setTransparencyType(hasFocus() ? TT_ACTIVE : TT_INACTIVE);
}
LLPanel::draw();
}
<commit_msg>EXP-1435 Nearby chat log does not change to "Plain style"/"Widget style" without restarting viewer<commit_after>/**
* @file LLNearbyChat.cpp
* @brief Nearby chat history scrolling panel implementation
*
* $LicenseInfo:firstyear=2009&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llnearbychat.h"
#include "llviewercontrol.h"
#include "llviewerwindow.h"
#include "llrootview.h"
//#include "llchatitemscontainerctrl.h"
#include "lliconctrl.h"
#include "llfloatersidepanelcontainer.h"
#include "llfocusmgr.h"
#include "lllogchat.h"
#include "llresizebar.h"
#include "llresizehandle.h"
#include "llmenugl.h"
#include "llviewermenu.h"//for gMenuHolder
#include "llnearbychathandler.h"
#include "llchannelmanager.h"
#include "llagent.h" // gAgent
#include "llchathistory.h"
#include "llstylemap.h"
#include "llavatarnamecache.h"
#include "lldraghandle.h"
#include "llnearbychatbar.h"
#include "llfloaterreg.h"
#include "lltrans.h"
static const S32 RESIZE_BAR_THICKNESS = 3;
static LLRegisterPanelClassWrapper<LLNearbyChat> t_panel_nearby_chat("panel_nearby_chat");
LLNearbyChat::LLNearbyChat()
: LLPanel()
,mChatHistory(NULL)
{
}
LLNearbyChat::~LLNearbyChat()
{
}
BOOL LLNearbyChat::postBuild()
{
//menu
LLUICtrl::CommitCallbackRegistry::ScopedRegistrar registrar;
LLUICtrl::EnableCallbackRegistry::ScopedRegistrar enable_registrar;
enable_registrar.add("NearbyChat.Check", boost::bind(&LLNearbyChat::onNearbyChatCheckContextMenuItem, this, _2));
registrar.add("NearbyChat.Action", boost::bind(&LLNearbyChat::onNearbyChatContextMenuItemClicked, this, _2));
LLMenuGL* menu = LLUICtrlFactory::getInstance()->createFromFile<LLMenuGL>("menu_nearby_chat.xml", gMenuHolder, LLViewerMenuHolderGL::child_registry_t::instance());
if(menu)
mPopupMenuHandle = menu->getHandle();
gSavedSettings.declareS32("nearbychat_showicons_and_names",2,"NearByChat header settings",true);
mChatHistory = getChild<LLChatHistory>("chat_history");
if(!LLPanel::postBuild())
return false;
return true;
}
std::string appendTime()
{
time_t utc_time;
utc_time = time_corrected();
std::string timeStr ="["+ LLTrans::getString("TimeHour")+"]:["
+LLTrans::getString("TimeMin")+"]";
LLSD substitution;
substitution["datetime"] = (S32) utc_time;
LLStringUtil::format (timeStr, substitution);
return timeStr;
}
void LLNearbyChat::addMessage(const LLChat& chat,bool archive,const LLSD &args)
{
LLChat& tmp_chat = const_cast<LLChat&>(chat);
if(tmp_chat.mTimeStr.empty())
tmp_chat.mTimeStr = appendTime();
bool use_plain_text_chat_history = gSavedSettings.getBOOL("PlainTextChatHistory");
if (!chat.mMuted)
{
tmp_chat.mFromName = chat.mFromName;
LLSD chat_args = args;
chat_args["use_plain_text_chat_history"] = use_plain_text_chat_history;
mChatHistory->appendMessage(chat, chat_args);
}
if(archive)
{
mMessageArchive.push_back(chat);
if(mMessageArchive.size()>200)
mMessageArchive.erase(mMessageArchive.begin());
}
if (args["do_not_log"].asBoolean())
{
return;
}
if (gSavedPerAccountSettings.getBOOL("LogNearbyChat"))
{
std::string from_name = chat.mFromName;
if (chat.mSourceType == CHAT_SOURCE_AGENT)
{
// if the chat is coming from an agent, log the complete name
LLAvatarName av_name;
LLAvatarNameCache::get(chat.mFromID, &av_name);
if (!av_name.mIsDisplayNameDefault)
{
from_name = av_name.getCompleteName();
}
}
LLLogChat::saveHistory("chat", from_name, chat.mFromID, chat.mText);
}
}
void LLNearbyChat::onNearbySpeakers()
{
LLSD param;
param["people_panel_tab_name"] = "nearby_panel";
LLFloaterSidePanelContainer::showPanel("people", "panel_people", param);
}
void LLNearbyChat::onNearbyChatContextMenuItemClicked(const LLSD& userdata)
{
}
bool LLNearbyChat::onNearbyChatCheckContextMenuItem(const LLSD& userdata)
{
std::string str = userdata.asString();
if(str == "nearby_people")
onNearbySpeakers();
return false;
}
void LLNearbyChat::setVisible(BOOL visible)
{
if(visible)
{
LLNotificationsUI::LLScreenChannelBase* chat_channel = LLNotificationsUI::LLChannelManager::getInstance()->findChannelByID(LLUUID(gSavedSettings.getString("NearByChatChannelUUID")));
if(chat_channel)
{
chat_channel->removeToastsFromChannel();
}
}
LLPanel::setVisible(visible);
}
void LLNearbyChat::getAllowedRect(LLRect& rect)
{
rect = gViewerWindow->getWorldViewRectScaled();
}
void LLNearbyChat::updateChatHistoryStyle()
{
mChatHistory->clear();
LLSD do_not_log;
do_not_log["do_not_log"] = true;
for(std::vector<LLChat>::iterator it = mMessageArchive.begin();it!=mMessageArchive.end();++it)
{
// Update the messages without re-writing them to a log file.
addMessage(*it,false, do_not_log);
}
}
//static
void LLNearbyChat::processChatHistoryStyleUpdate(const LLSD& newvalue)
{
LLFloater* chat_bar = LLFloaterReg::getInstance("chat_bar");
LLNearbyChat* nearby_chat = chat_bar->findChild<LLNearbyChat>("nearby_chat");
if(nearby_chat)
nearby_chat->updateChatHistoryStyle();
}
bool isWordsName(const std::string& name)
{
// checking to see if it's display name plus username in parentheses
S32 open_paren = name.find(" (", 0);
S32 close_paren = name.find(')', 0);
if (open_paren != std::string::npos &&
close_paren == name.length()-1)
{
return true;
}
else
{
//checking for a single space
S32 pos = name.find(' ', 0);
return std::string::npos != pos && name.rfind(' ', name.length()) == pos && 0 != pos && name.length()-1 != pos;
}
}
void LLNearbyChat::loadHistory()
{
LLSD do_not_log;
do_not_log["do_not_log"] = true;
std::list<LLSD> history;
LLLogChat::loadAllHistory("chat", history);
std::list<LLSD>::const_iterator it = history.begin();
while (it != history.end())
{
const LLSD& msg = *it;
std::string from = msg[IM_FROM];
LLUUID from_id;
if (msg[IM_FROM_ID].isDefined())
{
from_id = msg[IM_FROM_ID].asUUID();
}
else
{
std::string legacy_name = gCacheName->buildLegacyName(from);
gCacheName->getUUID(legacy_name, from_id);
}
LLChat chat;
chat.mFromName = from;
chat.mFromID = from_id;
chat.mText = msg[IM_TEXT].asString();
chat.mTimeStr = msg[IM_TIME].asString();
chat.mChatStyle = CHAT_STYLE_HISTORY;
chat.mSourceType = CHAT_SOURCE_AGENT;
if (from_id.isNull() && SYSTEM_FROM == from)
{
chat.mSourceType = CHAT_SOURCE_SYSTEM;
}
else if (from_id.isNull())
{
chat.mSourceType = isWordsName(from) ? CHAT_SOURCE_UNKNOWN : CHAT_SOURCE_OBJECT;
}
addMessage(chat, true, do_not_log);
it++;
}
}
//static
LLNearbyChat* LLNearbyChat::getInstance()
{
LLFloater* chat_bar = LLFloaterReg::getInstance("chat_bar");
return chat_bar->findChild<LLNearbyChat>("nearby_chat");
}
////////////////////////////////////////////////////////////////////////////////
//
void LLNearbyChat::onFocusReceived()
{
setBackgroundOpaque(true);
LLPanel::onFocusReceived();
}
////////////////////////////////////////////////////////////////////////////////
//
void LLNearbyChat::onFocusLost()
{
setBackgroundOpaque(false);
LLPanel::onFocusLost();
}
BOOL LLNearbyChat::handleMouseDown(S32 x, S32 y, MASK mask)
{
//fix for EXT-6625
//highlight NearbyChat history whenever mouseclick happen in NearbyChat
//setting focus to eidtor will force onFocusLost() call that in its turn will change
//background opaque. This all happenn since NearByChat is "chrome" and didn't process focus change.
if(mChatHistory)
mChatHistory->setFocus(TRUE);
return LLPanel::handleMouseDown(x, y, mask);
}
void LLNearbyChat::draw()
{
// *HACK: Update transparency type depending on whether our children have focus.
// This is needed because this floater is chrome and thus cannot accept focus, so
// the transparency type setting code from LLFloater::setFocus() isn't reached.
if (getTransparencyType() != TT_DEFAULT)
{
setTransparencyType(hasFocus() ? TT_ACTIVE : TT_INACTIVE);
}
LLPanel::draw();
}
<|endoftext|> |
<commit_before>#include "UpdaterWindow.h"
#include "../3RVX/3RVX.h"
#include "../3RVX/Logger.h"
#include "../3RVX/CommCtl.h"
#include "../3RVX/NotifyIcon.h"
#include "resource.h"
UpdaterWindow::UpdaterWindow() :
Window(L"3RVX-UpdateWindow") {
HRESULT hr = LoadIconMetric(
Window::InstanceHandle(),
MAKEINTRESOURCE(IDI_MAINICON),
LIM_SMALL,
&_icon);
}
LRESULT UpdaterWindow::WndProc(
HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
if (message == _3RVX::WM_3RVX_SETTINGSCTRL) {
switch (wParam) {
case _3RVX::MSG_UPDATEICON:
CLOG(L"Creating update icon");
new NotifyIcon(Window::Handle(), L"Update Available", _icon);
break;
}
}
return Window::WndProc(hWnd, message, wParam, lParam);
}
<commit_msg>Test update icon ballooon<commit_after>#include "UpdaterWindow.h"
#include "../3RVX/3RVX.h"
#include "../3RVX/Logger.h"
#include "../3RVX/CommCtl.h"
#include "../3RVX/NotifyIcon.h"
#include "resource.h"
UpdaterWindow::UpdaterWindow() :
Window(L"3RVX-UpdateWindow") {
HRESULT hr = LoadIconMetric(
Window::InstanceHandle(),
MAKEINTRESOURCE(IDI_MAINICON),
LIM_SMALL,
&_icon);
}
LRESULT UpdaterWindow::WndProc(
HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
if (message == _3RVX::WM_3RVX_SETTINGSCTRL) {
switch (wParam) {
case _3RVX::MSG_UPDATEICON:
CLOG(L"Creating update icon");
NotifyIcon *x = new NotifyIcon(Window::Handle(), L"Update Available", _icon);
HICON ic;
LoadIconMetric(Window::InstanceHandle(), MAKEINTRESOURCE(IDI_MAINICON), LIM_LARGE, &ic);
x->Balloon(L"Update Available", L"3RVX 3.2", ic);
break;
}
}
return Window::WndProc(hWnd, message, wParam, lParam);
}
<|endoftext|> |
<commit_before>#if !defined(_TSXX_TS7300_DEVICES_HPP_)
#define _TSXX_TS7300_DEVICES_HPP_
#include <vector>
#include <tsxx/ports.hpp>
namespace tsxx
{
namespace ts7300
{
namespace devices
{
/**
* DIO1 port class.
*/
class
dio1
{
private:
enum { BASE_ADDR = 0x80840000 };
public:
dio1(tsxx::system::memory &memory)
: dio17_mask(0xfb),
dio17(memory.get_region(BASE_ADDR + 0x04), memory.get_region(BASE_ADDR + 0x14)),
dio8_mask(0x04),
dio8(memory.get_region(BASE_ADDR + 0x30), memory.get_region(BASE_ADDR + 0x34))
{
}
public:
typedef tsxx::ports::dioport<tsxx::ports::port8> port_type;
// WordPort
public:
typedef port_type::word_type word_type;
inline void
write(word_type word)
{
dio17.write(word & dio17_mask);
dio8.write((word & dio8_mask) >> 1);
}
inline word_type
read()
{
return (dio17.read() & dio17_mask) | ((dio8.read() & dio8_mask) << 1);
}
public:
inline void
set_dir(word_type word)
{
dio17.set_dir(word & dio17_mask);
dio8.set_dir((word & dio8_mask) >> 1);
}
inline word_type
get_dir()
{
return (dio17.get_dir() & dio17_mask) | ((dio8.get_dir() & dio8_mask) << 1);
}
private:
const port_type::word_type dio17_mask;
port_type dio17;
const port_type::word_type dio8_mask;
port_type dio8;
};
/**
* LCD port class.
*/
class
lcd
{
private:
enum { BASE_ADDR = 0x80840000 };
enum {
LCD_CMD_CLEAR = 0x01,
LCD_CMD_HOME = 0x02,
LCD_CMD_ENTRY = 0x04,
LCD_BIT_ENTRY_DIR_RIGHT = 0x02,
LCD_BIT_ENTRY_DIR_LEFT = 0x00,
LCD_CMD_CTRL = 0x08,
LCD_BIT_CTRL_BLNK_OFF = 0x00,
LCD_BIT_CTRL_BLNK_ON = 0x01,
LCD_BIT_CTRL_CUR_OFF = 0x00,
LCD_BIT_CTRL_CUR_ON = 0x02,
LCD_BIT_CTRL_DSP_OFF = 0x00,
LCD_BIT_CTRL_DSP_ON = 0x04,
LCD_CMD_FNSET = 0x20,
LCD_BIT_FNSET_FONT_5x8 = 0x00,
LCD_BIT_FNSET_FONT_5x11 = 0x04,
LCD_BIT_FNSET_NLINES_1LIN = 0x00,
LCD_BIT_FNSET_NLINES_2LIN = 0x08,
LCD_BIT_FNSET_DATLEN_4BIT = 0x00,
LCD_BIT_FNSET_DATLEN_8BIT = 0x10,
LCD_CMD_CGRAM = 0x40,
LCD_CMD_DDRAM = 0x80,
LCD_VAL_DDRAM_ROW0 = 0x00,
LCD_VAL_DDRAM_ROW1 = 0x40,
LCD_VAL_DDRAM_ROW2 = 0x14,
LCD_VAL_DDRAM_ROW3 = 0x54,
};
public:
lcd(tsxx::system::memory &memory);
void init();
void print(std::string str);
void print(const void *p, std::size_t len);
void command(uint8_t cmd);
bool wait();
public:
void
clear()
{
command(LCD_CMD_CLEAR);
usleep(1530);
}
void
home()
{
command(LCD_CMD_HOME);
usleep(1530);
}
void
entry_mode(bool right)
{
command(LCD_CMD_ENTRY | (right ? LCD_BIT_ENTRY_DIR_RIGHT : LCD_BIT_ENTRY_DIR_LEFT));
usleep(39);
}
void
control(bool display_on, bool cursor_on, bool blink_on)
{
command(LCD_CMD_CTRL |
(display_on ? LCD_BIT_CTRL_DSP_ON : LCD_BIT_CTRL_DSP_OFF) |
(cursor_on ? LCD_BIT_CTRL_CUR_ON : LCD_BIT_CTRL_CUR_OFF) |
(blink_on ? LCD_BIT_CTRL_BLNK_ON : LCD_BIT_CTRL_BLNK_OFF));
usleep(39);
}
void
function(bool font_5x8, bool n2lines, bool dat8bit)
{
command(LCD_CMD_FNSET |
(font_5x8 ? LCD_BIT_FNSET_FONT_5x8 : LCD_BIT_FNSET_FONT_5x11) |
(n2lines ? LCD_BIT_FNSET_NLINES_2LIN : LCD_BIT_FNSET_NLINES_1LIN) |
(dat8bit ? LCD_BIT_FNSET_DATLEN_8BIT : LCD_BIT_FNSET_DATLEN_4BIT));
usleep(39);
}
void
ddram(unsigned int x, unsigned int y)
{
command(LCD_CMD_DDRAM |
(y == 0 ? LCD_VAL_DDRAM_ROW0 :
y == 1 ? LCD_VAL_DDRAM_ROW1 :
y == 2 ? LCD_VAL_DDRAM_ROW2 :
LCD_VAL_DDRAM_ROW3) |
x);
}
private:
// Referenced in the manual as Port A (data) and C (data7).
tsxx::ports::dioport<tsxx::ports::port8> data, data7;
const tsxx::ports::port8::word_type data_mask, data7_mask;
const tsxx::ports::port8::word_type data_bit_busy;
// Referenced in the manual as Port H.
tsxx::ports::dioport<tsxx::ports::port8> ctrl;
const tsxx::ports::port8::word_type ctrl_bit_en, ctrl_bit_rs, ctrl_bit_wr;
};
/**
* XDIO port class.
*
* The only implemented mode (yet) is DIO (GPIO) mode (set_mode_dio()).
*/
class
xdio
{
private:
enum { BASE_ADDR = 0x72000040 };
public:
/**
* @param n The number of the XDIO port. Can be 0 (XDIO1) or 1 (XDIO2).
*/
xdio(tsxx::system::memory &memory, unsigned int n);
void init();
private:
enum mode_cfg {
MODE_DIO = 0x00,
MODE_EDGEQUADCNTR = 0x01,
MODE_INPULSTIMER = 0x02,
MODE_PWM = 0x03,
UNINITIALIZED,
} mode;
void read_conf();
void write_conf();
// Operation mode setting methods.
public:
void set_mode_dio();
// DIO methods and variables.
public:
/**
* Returns the DIO port.
*/
inline tsxx::ports::dioport<tsxx::ports::port8> &
get_dio()
{
return dio_port;
}
// WordPort
public:
typedef tsxx::ports::port8::word_type word_type;
void
write(word_type word)
{
get_dio().write(word);
}
word_type
read()
{
return get_dio().read();
}
private:
tsxx::ports::port8 conf, reg1, reg2, reg3;
tsxx::ports::dioport<tsxx::ports::port8> dio_port;
};
class
spi
{
private:
enum { BASE_ADDR = 0x808a0000 };
public:
spi(tsxx::system::memory &memory);
public:
void init();
public:
void write_read(tsxx::interfaces::binport &cs, const void *wrp, std::size_t wrsiz, void *rdp, std::size_t rdsiz);
inline void
write_read(tsxx::interfaces::binport &cs, void *rdwrp, std::size_t rdwrsiz)
{
write_read(cs, rdwrp, rdwrsiz, rdwrp, rdwrsiz);
}
inline void
write_read(tsxx::interfaces::binport &cs, std::vector<uint8_t> &rw_data)
{
write_read(cs, rw_data, rw_data);
}
inline void
write_read(tsxx::interfaces::binport &cs, const std::vector<uint8_t> &wr_data, std::vector<uint8_t> &read_data)
{
if (read_data.size() != wr_data.size())
read_data.resize(wr_data.size());
write_read(cs, &wr_data[0], wr_data.size(), &read_data[0], read_data.size());
}
private:
/// SPI registers.
tsxx::ports::port16 ctrl, status, data;
tsxx::ports::bport16 tx_bit, busy_bit, inp_bit;
};
class
spi_chip
{
public:
spi_chip(spi &_port, tsxx::interfaces::binport &_cs)
: port(&_port), cs(_cs)
{
}
inline void
write_read(void *p, std::size_t siz)
{
port->write_read(cs, p, siz);
}
inline void
write_read(std::vector<uint8_t> &rw_data)
{
port->write_read(cs, rw_data);
}
inline void
write_read(const std::vector<uint8_t> &wr_data, std::vector<uint8_t> &rd_data)
{
port->write_read(cs, wr_data, rd_data);
}
private:
spi *port;
tsxx::interfaces::binport &cs;
};
}
}
}
#endif // !defined(_TSXX_TS7300_DEVICES_HPP_)
<commit_msg>Bug fix in dio1 class.<commit_after>#if !defined(_TSXX_TS7300_DEVICES_HPP_)
#define _TSXX_TS7300_DEVICES_HPP_
#include <vector>
#include <tsxx/ports.hpp>
namespace tsxx
{
namespace ts7300
{
namespace devices
{
/**
* DIO1 port class.
*/
class
dio1
{
private:
enum { BASE_ADDR = 0x80840000 };
public:
dio1(tsxx::system::memory &memory)
: dio17_mask(0xfb),
dio17(memory.get_region(BASE_ADDR + 0x04), memory.get_region(BASE_ADDR + 0x14)),
dio8_mask(0x04),
dio8(memory.get_region(BASE_ADDR + 0x30), memory.get_region(BASE_ADDR + 0x34))
{
}
public:
typedef tsxx::ports::dioport<tsxx::ports::port8> port_type;
// WordPort
public:
typedef port_type::word_type word_type;
inline void
write(word_type word)
{
dio17.write(word & dio17_mask);
dio8.write((word & dio8_mask) >> 1);
}
inline word_type
read()
{
return (dio17.read() & dio17_mask) | ((dio8.read() << 1) & dio8_mask);
}
public:
inline void
set_dir(word_type word)
{
dio17.set_dir(word & dio17_mask);
dio8.set_dir((word & dio8_mask) >> 1);
}
inline word_type
get_dir()
{
return (dio17.get_dir() & dio17_mask) | ((dio8.get_dir() & dio8_mask) << 1);
}
private:
const port_type::word_type dio17_mask;
port_type dio17;
const port_type::word_type dio8_mask;
port_type dio8;
};
/**
* LCD port class.
*/
class
lcd
{
private:
enum { BASE_ADDR = 0x80840000 };
enum {
LCD_CMD_CLEAR = 0x01,
LCD_CMD_HOME = 0x02,
LCD_CMD_ENTRY = 0x04,
LCD_BIT_ENTRY_DIR_RIGHT = 0x02,
LCD_BIT_ENTRY_DIR_LEFT = 0x00,
LCD_CMD_CTRL = 0x08,
LCD_BIT_CTRL_BLNK_OFF = 0x00,
LCD_BIT_CTRL_BLNK_ON = 0x01,
LCD_BIT_CTRL_CUR_OFF = 0x00,
LCD_BIT_CTRL_CUR_ON = 0x02,
LCD_BIT_CTRL_DSP_OFF = 0x00,
LCD_BIT_CTRL_DSP_ON = 0x04,
LCD_CMD_FNSET = 0x20,
LCD_BIT_FNSET_FONT_5x8 = 0x00,
LCD_BIT_FNSET_FONT_5x11 = 0x04,
LCD_BIT_FNSET_NLINES_1LIN = 0x00,
LCD_BIT_FNSET_NLINES_2LIN = 0x08,
LCD_BIT_FNSET_DATLEN_4BIT = 0x00,
LCD_BIT_FNSET_DATLEN_8BIT = 0x10,
LCD_CMD_CGRAM = 0x40,
LCD_CMD_DDRAM = 0x80,
LCD_VAL_DDRAM_ROW0 = 0x00,
LCD_VAL_DDRAM_ROW1 = 0x40,
LCD_VAL_DDRAM_ROW2 = 0x14,
LCD_VAL_DDRAM_ROW3 = 0x54,
};
public:
lcd(tsxx::system::memory &memory);
void init();
void print(std::string str);
void print(const void *p, std::size_t len);
void command(uint8_t cmd);
bool wait();
public:
void
clear()
{
command(LCD_CMD_CLEAR);
usleep(1530);
}
void
home()
{
command(LCD_CMD_HOME);
usleep(1530);
}
void
entry_mode(bool right)
{
command(LCD_CMD_ENTRY | (right ? LCD_BIT_ENTRY_DIR_RIGHT : LCD_BIT_ENTRY_DIR_LEFT));
usleep(39);
}
void
control(bool display_on, bool cursor_on, bool blink_on)
{
command(LCD_CMD_CTRL |
(display_on ? LCD_BIT_CTRL_DSP_ON : LCD_BIT_CTRL_DSP_OFF) |
(cursor_on ? LCD_BIT_CTRL_CUR_ON : LCD_BIT_CTRL_CUR_OFF) |
(blink_on ? LCD_BIT_CTRL_BLNK_ON : LCD_BIT_CTRL_BLNK_OFF));
usleep(39);
}
void
function(bool font_5x8, bool n2lines, bool dat8bit)
{
command(LCD_CMD_FNSET |
(font_5x8 ? LCD_BIT_FNSET_FONT_5x8 : LCD_BIT_FNSET_FONT_5x11) |
(n2lines ? LCD_BIT_FNSET_NLINES_2LIN : LCD_BIT_FNSET_NLINES_1LIN) |
(dat8bit ? LCD_BIT_FNSET_DATLEN_8BIT : LCD_BIT_FNSET_DATLEN_4BIT));
usleep(39);
}
void
ddram(unsigned int x, unsigned int y)
{
command(LCD_CMD_DDRAM |
(y == 0 ? LCD_VAL_DDRAM_ROW0 :
y == 1 ? LCD_VAL_DDRAM_ROW1 :
y == 2 ? LCD_VAL_DDRAM_ROW2 :
LCD_VAL_DDRAM_ROW3) |
x);
}
private:
// Referenced in the manual as Port A (data) and C (data7).
tsxx::ports::dioport<tsxx::ports::port8> data, data7;
const tsxx::ports::port8::word_type data_mask, data7_mask;
const tsxx::ports::port8::word_type data_bit_busy;
// Referenced in the manual as Port H.
tsxx::ports::dioport<tsxx::ports::port8> ctrl;
const tsxx::ports::port8::word_type ctrl_bit_en, ctrl_bit_rs, ctrl_bit_wr;
};
/**
* XDIO port class.
*
* The only implemented mode (yet) is DIO (GPIO) mode (set_mode_dio()).
*/
class
xdio
{
private:
enum { BASE_ADDR = 0x72000040 };
public:
/**
* @param n The number of the XDIO port. Can be 0 (XDIO1) or 1 (XDIO2).
*/
xdio(tsxx::system::memory &memory, unsigned int n);
void init();
private:
enum mode_cfg {
MODE_DIO = 0x00,
MODE_EDGEQUADCNTR = 0x01,
MODE_INPULSTIMER = 0x02,
MODE_PWM = 0x03,
UNINITIALIZED,
} mode;
void read_conf();
void write_conf();
// Operation mode setting methods.
public:
void set_mode_dio();
// DIO methods and variables.
public:
/**
* Returns the DIO port.
*/
inline tsxx::ports::dioport<tsxx::ports::port8> &
get_dio()
{
return dio_port;
}
// WordPort
public:
typedef tsxx::ports::port8::word_type word_type;
void
write(word_type word)
{
get_dio().write(word);
}
word_type
read()
{
return get_dio().read();
}
private:
tsxx::ports::port8 conf, reg1, reg2, reg3;
tsxx::ports::dioport<tsxx::ports::port8> dio_port;
};
class
spi
{
private:
enum { BASE_ADDR = 0x808a0000 };
public:
spi(tsxx::system::memory &memory);
public:
void init();
public:
void write_read(tsxx::interfaces::binport &cs, const void *wrp, std::size_t wrsiz, void *rdp, std::size_t rdsiz);
inline void
write_read(tsxx::interfaces::binport &cs, void *rdwrp, std::size_t rdwrsiz)
{
write_read(cs, rdwrp, rdwrsiz, rdwrp, rdwrsiz);
}
inline void
write_read(tsxx::interfaces::binport &cs, std::vector<uint8_t> &rw_data)
{
write_read(cs, rw_data, rw_data);
}
inline void
write_read(tsxx::interfaces::binport &cs, const std::vector<uint8_t> &wr_data, std::vector<uint8_t> &read_data)
{
if (read_data.size() != wr_data.size())
read_data.resize(wr_data.size());
write_read(cs, &wr_data[0], wr_data.size(), &read_data[0], read_data.size());
}
private:
/// SPI registers.
tsxx::ports::port16 ctrl, status, data;
tsxx::ports::bport16 tx_bit, busy_bit, inp_bit;
};
class
spi_chip
{
public:
spi_chip(spi &_port, tsxx::interfaces::binport &_cs)
: port(&_port), cs(_cs)
{
}
inline void
write_read(void *p, std::size_t siz)
{
port->write_read(cs, p, siz);
}
inline void
write_read(std::vector<uint8_t> &rw_data)
{
port->write_read(cs, rw_data);
}
inline void
write_read(const std::vector<uint8_t> &wr_data, std::vector<uint8_t> &rd_data)
{
port->write_read(cs, wr_data, rd_data);
}
private:
spi *port;
tsxx::interfaces::binport &cs;
};
}
}
}
#endif // !defined(_TSXX_TS7300_DEVICES_HPP_)
<|endoftext|> |
<commit_before>/**
* @file llversioninfo.cpp
* @brief Routines to access the viewer version and build information
* @author Martin Reddy
*
* $LicenseInfo:firstyear=2009&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llversioninfo.h"
#include "llversionviewer.h"
//
// Set the version numbers in indra/llcommon/llversionviewer.h
//
//static
S32 LLVersionInfo::getMajor()
{
return LL_VERSION_MAJOR;
}
//static
S32 LLVersionInfo::getMinor()
{
return LL_VERSION_MINOR;
}
//static
S32 LLVersionInfo::getPatch()
{
return LL_VERSION_PATCH;
}
//static
S32 LLVersionInfo::getBuild()
{
return LL_VERSION_BUILD;
}
//static
const std::string &LLVersionInfo::getVersion()
{
static std::string version("");
if (version.empty())
{
// cache the version string
std::ostringstream stream;
stream << LL_VERSION_MAJOR << "."
<< LL_VERSION_MINOR << "."
<< LL_VERSION_PATCH << "."
<< LL_VERSION_BUILD;
version = stream.str();
}
return version;
}
//static
const std::string &LLVersionInfo::getShortVersion()
{
static std::string version("");
if (version.empty())
{
// cache the version string
std::ostringstream stream;
stream << LL_VERSION_MAJOR << "."
<< LL_VERSION_MINOR << "."
<< LL_VERSION_PATCH;
version = stream.str();
}
return version;
}
namespace
{
/// Storage of the channel name the viewer is using.
// The channel name is set by hardcoded constant,
// or by calling LLVersionInfo::resetChannel()
std::string sWorkingChannelName(LL_CHANNEL);
// Storage for the "version and channel" string.
// This will get reset too.
std::string sVersionChannel("");
}
//static
const std::string &LLVersionInfo::getChannelAndVersion()
{
if (sVersionChannel.empty())
{
// cache the version string
std::ostringstream stream;
stream << LLVersionInfo::getChannel()
<< " "
<< LLVersionInfo::getVersion();
sVersionChannel = stream.str();
}
return sVersionChannel;
}
//static
const std::string &LLVersionInfo::getChannel()
{
return sWorkingChannelName;
}
void LLVersionInfo::resetChannel(const std::string& channel)
{
sWorkingChannelName = channel;
sVersionChannel.clear(); // Reset version and channel string til next use.
}
// [SL:KB] - Patch: Viewer-CrashReporting | Checked: 2011-05-08 (Catznip-2.6.0a) | Added: Catznip-2.6.0a
const char* getBuildPlatformString()
{
#if LL_WINDOWS
#ifndef _WIN64
return "Win32";
#else
return "Win64";
#endif // _WIN64
#elif LL_SDL
#if LL_GNUC
#if ( defined(__amd64__) || defined(__x86_64__) )
return "Linux64";
#else
return "Linux32";
#endif
#endif
#elif LL_DARWIN
return "Darwin";
#else
return "Unknown";
#endif
return "Unknown";
}
const std::string& LLVersionInfo::getBuildPlatform()
{
static std::string strPlatform = getBuildPlatformString();
return strPlatform;
}
// [/SL:KB]
<commit_msg>slightly improved build fix<commit_after>/**
* @file llversioninfo.cpp
* @brief Routines to access the viewer version and build information
* @author Martin Reddy
*
* $LicenseInfo:firstyear=2009&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2010, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "llviewerprecompiledheaders.h"
#include "llversioninfo.h"
#include "llversionviewer.h"
//
// Set the version numbers in indra/llcommon/llversionviewer.h
//
//static
S32 LLVersionInfo::getMajor()
{
return LL_VERSION_MAJOR;
}
//static
S32 LLVersionInfo::getMinor()
{
return LL_VERSION_MINOR;
}
//static
S32 LLVersionInfo::getPatch()
{
return LL_VERSION_PATCH;
}
//static
S32 LLVersionInfo::getBuild()
{
return LL_VERSION_BUILD;
}
//static
const std::string &LLVersionInfo::getVersion()
{
static std::string version("");
if (version.empty())
{
// cache the version string
std::ostringstream stream;
stream << LL_VERSION_MAJOR << "."
<< LL_VERSION_MINOR << "."
<< LL_VERSION_PATCH << "."
<< LL_VERSION_BUILD;
version = stream.str();
}
return version;
}
//static
const std::string &LLVersionInfo::getShortVersion()
{
static std::string version("");
if (version.empty())
{
// cache the version string
std::ostringstream stream;
stream << LL_VERSION_MAJOR << "."
<< LL_VERSION_MINOR << "."
<< LL_VERSION_PATCH;
version = stream.str();
}
return version;
}
namespace
{
/// Storage of the channel name the viewer is using.
// The channel name is set by hardcoded constant,
// or by calling LLVersionInfo::resetChannel()
std::string sWorkingChannelName(LL_CHANNEL);
// Storage for the "version and channel" string.
// This will get reset too.
std::string sVersionChannel("");
}
//static
const std::string &LLVersionInfo::getChannelAndVersion()
{
if (sVersionChannel.empty())
{
// cache the version string
std::ostringstream stream;
stream << LLVersionInfo::getChannel()
<< " "
<< LLVersionInfo::getVersion();
sVersionChannel = stream.str();
}
return sVersionChannel;
}
//static
const std::string &LLVersionInfo::getChannel()
{
return sWorkingChannelName;
}
void LLVersionInfo::resetChannel(const std::string& channel)
{
sWorkingChannelName = channel;
sVersionChannel.clear(); // Reset version and channel string til next use.
}
// [SL:KB] - Patch: Viewer-CrashReporting | Checked: 2011-05-08 (Catznip-2.6.0a) | Added: Catznip-2.6.0a
const char* getBuildPlatformString()
{
#if LL_WINDOWS
#ifndef _WIN64
return "Win32";
#else
return "Win64";
#endif // _WIN64
#elif LL_SDL
#if LL_GNUC
#if ( defined(__amd64__) || defined(__x86_64__) )
return "Linux64";
#else
return "Linux32";
#endif
#endif
#elif LL_DARWIN
return "Darwin";
#endif
return "Unknown";
}
const std::string& LLVersionInfo::getBuildPlatform()
{
static std::string strPlatform = getBuildPlatformString();
return strPlatform;
}
// [/SL:KB]
<|endoftext|> |
<commit_before>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (C) 2010 Kim Jung Nissen <jungnissen@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "qrealpropertywidgetitem.h"
#include <cfloat>
#include <core/gluonobject.h>
#include <core/metainfo.h>
#include <knuminput.h>
#include <QtGui/QDoubleSpinBox>
REGISTER_PROPERTYWIDGETITEM( GluonCreator, QRealPropertyWidgetItem )
using namespace GluonCreator;
QRealPropertyWidgetItem::QRealPropertyWidgetItem( QWidget* parent, Qt::WindowFlags f )
: PropertyWidgetItem( parent, f )
{
}
QRealPropertyWidgetItem::~QRealPropertyWidgetItem()
{
}
QStringList
QRealPropertyWidgetItem::supportedDataTypes() const
{
QList<QString> supportedTypes;
supportedTypes.append( "qreal" );
supportedTypes.append( "float" );
supportedTypes.append( "double" );
return supportedTypes;
}
PropertyWidgetItem *
QRealPropertyWidgetItem::instantiate()
{
return new QRealPropertyWidgetItem();
}
void
QRealPropertyWidgetItem::setEditProperty( const QString& value )
{
// Clean up any possible leftovers
delete editWidget();
GluonCore::GluonObject* theObject = qobject_cast<GluonCore::GluonObject*>( editObject() );
bool noPropertyRange = true;;
if( theObject )
{
if( theObject->hasMetaInfo() )
{
if( theObject->metaInfo()->hasPropertyRange( value ) )
{
noPropertyRange = false;
KDoubleNumInput* editor = new KDoubleNumInput( this );
editor->setRange( theObject->metaInfo()->propertyRangeMin( value ), theObject->metaInfo()->propertyRangeMax( value ) );
setEditWidget( editor );
}
}
}
if( noPropertyRange )
{
QDoubleSpinBox* spinBox = new QDoubleSpinBox( this );
setEditWidget( spinBox );
}
connect( editWidget(), SIGNAL( valueChanged( double ) ), SLOT( qrealValueChanged( double ) ) );
GluonCreator::PropertyWidgetItem::setEditProperty( value );
}
void
QRealPropertyWidgetItem::setEditValue( const QVariant& value )
{
editWidget()->setProperty( "value", value );
}
void
QRealPropertyWidgetItem::qrealValueChanged( double value )
{
PropertyWidgetItem::valueChanged( QVariant( value ) );
}
// #include "qrealpropertywidgetitem.moc"
<commit_msg>Properly increase the range of the float PWI.<commit_after>/******************************************************************************
* This file is part of the Gluon Development Platform
* Copyright (C) 2010 Kim Jung Nissen <jungnissen@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "qrealpropertywidgetitem.h"
#include <cfloat>
#include <core/gluonobject.h>
#include <core/metainfo.h>
#include <knuminput.h>
#include <QtGui/QDoubleSpinBox>
REGISTER_PROPERTYWIDGETITEM( GluonCreator, QRealPropertyWidgetItem )
using namespace GluonCreator;
QRealPropertyWidgetItem::QRealPropertyWidgetItem( QWidget* parent, Qt::WindowFlags f )
: PropertyWidgetItem( parent, f )
{
}
QRealPropertyWidgetItem::~QRealPropertyWidgetItem()
{
}
QStringList
QRealPropertyWidgetItem::supportedDataTypes() const
{
QList<QString> supportedTypes;
supportedTypes.append( "qreal" );
supportedTypes.append( "float" );
supportedTypes.append( "double" );
return supportedTypes;
}
PropertyWidgetItem *
QRealPropertyWidgetItem::instantiate()
{
return new QRealPropertyWidgetItem();
}
void
QRealPropertyWidgetItem::setEditProperty( const QString& value )
{
// Clean up any possible leftovers
delete editWidget();
GluonCore::GluonObject* theObject = qobject_cast<GluonCore::GluonObject*>( editObject() );
bool noPropertyRange = true;;
if( theObject )
{
if( theObject->hasMetaInfo() )
{
if( theObject->metaInfo()->hasPropertyRange( value ) )
{
noPropertyRange = false;
KDoubleNumInput* editor = new KDoubleNumInput( this );
editor->setRange( theObject->metaInfo()->propertyRangeMin( value ), theObject->metaInfo()->propertyRangeMax( value ) );
setEditWidget( editor );
}
}
}
if( noPropertyRange )
{
QDoubleSpinBox* spinBox = new QDoubleSpinBox( this );
spinBox->setMinimum( -FLT_MAX );
spinBox->setMaximum( FLT_MAX );
spinBox->setSingleStep(0.01f);
setEditWidget( spinBox );
}
connect( editWidget(), SIGNAL( valueChanged( double ) ), SLOT( qrealValueChanged( double ) ) );
GluonCreator::PropertyWidgetItem::setEditProperty( value );
}
void
QRealPropertyWidgetItem::setEditValue( const QVariant& value )
{
editWidget()->setProperty( "value", value );
}
void
QRealPropertyWidgetItem::qrealValueChanged( double value )
{
PropertyWidgetItem::valueChanged( QVariant( value ) );
}
// #include "qrealpropertywidgetitem.moc"
<|endoftext|> |
<commit_before>#include "../include/oasis.h"
#ifdef HAVE_PARQUET
#include "../include/oasisparquet.h"
#endif
#include <cstring>
#include <map>
#include <vector>
namespace katparquet {
struct period_event {
int period;
int eventID;
};
bool operator<(const period_event &lhs, const period_event &rhs) {
if (lhs.period != rhs.period) {
return lhs.period < rhs.period;
} else {
return lhs.eventID < rhs.eventID;
}
}
bool operator==(const period_event &lhs, const period_event &rhs) {
return lhs.period == rhs.period && lhs.eventID == rhs.eventID;
}
template<typename tableNameT>
void GetRow(std::map<int, int> &event_to_file, const tableNameT &row,
const int i) {
event_to_file[row.eventID] = i;
}
template<typename tableNameT>
void GetRow(std::map<period_event, int> &period_to_file,
const tableNameT &row, const int i) {
period_event periodEventID;
periodEventID.period = row.period;
periodEventID.eventID = row.eventID;
period_to_file[periodEventID] = i;
}
template<typename tableNameT, typename rowMapT>
void ReadFirstRows(const std::vector<std::string> &inFiles,
std::vector<parquet::StreamReader> &isIn,
std::vector<tableNameT> &rows, rowMapT &rowMap_to_file) {
// Read first row from each file
for (int i = 0; i < (int)inFiles.size(); i++) {
isIn[i] = OasisParquet::SetupParquetInputStream(inFiles[i]);
tableNameT row;
if (isIn[i].eof()) continue; // Ignore empty files
isIn[i] >> row;
rows[i] = row;
GetRow(rowMap_to_file, rows[i], i);
}
}
template<typename tableNameT>
void WriteOutput(std::vector<tableNameT> &rows,
std::map<int, int> &event_to_file,
parquet::StreamWriter &osOut,
std::vector<parquet::StreamReader> &isIn) {
// First entry should always have lowest event ID
while(event_to_file.size() != 0) {
auto iter = event_to_file.begin();
int currentEventID = iter->first;
while (rows[iter->second].eventID == currentEventID) {
osOut << rows[iter->second];
if (isIn[iter->second].eof()) break;
isIn[iter->second] >> rows[iter->second];
}
if (!isIn[iter->second].eof()) {
GetRow(event_to_file, rows[iter->second], iter->second);
}
event_to_file.erase(iter);
}
}
template<typename tableNameT>
void WriteOutput(std::vector<tableNameT> &rows,
std::map<period_event, int> &period_to_file,
parquet::StreamWriter &osOut,
std::vector<parquet::StreamReader> &isIn) {
// First entry should always have lowest period number followed by event ID
while (period_to_file.size() != 0) {
auto iter = period_to_file.begin();
period_event currentPeriodEvent = iter->first;
period_event periodEventID;
periodEventID.period = rows[iter->second].period;
periodEventID.eventID = rows[iter->second].eventID;
while (periodEventID == currentPeriodEvent) {
osOut << rows[iter->second];
if (isIn[iter->second].eof()) break;
isIn[iter->second] >> rows[iter->second];
periodEventID.period = rows[iter->second].period;
periodEventID.eventID = rows[iter->second].eventID;
}
if (!isIn[iter->second].eof()) {
GetRow(period_to_file, rows[iter->second], iter->second);
}
period_to_file.erase(iter);
}
}
template<typename tableNameT, typename rowMapT>
void DoKat(const std::vector<std::string> &inFiles,
parquet::StreamWriter &osOut, std::vector<tableNameT> &rows,
rowMapT &rowMap_to_file) {
rows.resize(inFiles.size());
std::vector<parquet::StreamReader> isIn;
isIn.resize(inFiles.size());
ReadFirstRows(inFiles, isIn, rows, rowMap_to_file);
if (rowMap_to_file.size() == 0) {
fprintf(stderr, "ERROR: All input files are empty\n");
exit(EXIT_FAILURE);
}
WriteOutput(rows, rowMap_to_file, osOut, isIn);
}
void doit(const std::vector<std::string> &inFiles,
const std::string outFile, const int tableName) {
parquet::StreamWriter osOut = OasisParquet::GetParquetStreamWriter(tableName, outFile);
std::map<int, int> event_to_file; // Exceedance Loss Table
std::map<period_event, int> period_to_file; // Period Loss Table
if (tableName == OasisParquet::MPLT) {
std::vector<OasisParquet::MomentPLTEntry> rows;
DoKat(inFiles, osOut, rows, period_to_file);
} else if (tableName == OasisParquet::QPLT) {
std::vector<OasisParquet::QuantilePLTEntry> rows;
DoKat(inFiles, osOut, rows, period_to_file);
} else if (tableName == OasisParquet::SPLT) {
std::vector<OasisParquet::SamplePLTEntry> rows;
DoKat(inFiles, osOut, rows, period_to_file);
} else if (tableName == OasisParquet::MELT) {
std::vector<OasisParquet::MomentELTEntry> rows;
DoKat(inFiles, osOut, rows, event_to_file);
} else if (tableName == OasisParquet::QELT) {
std::vector<OasisParquet::QuantileELTEntry> rows;
DoKat(inFiles, osOut, rows, event_to_file);
} else if (tableName == OasisParquet::SELT) {
std::vector<OasisParquet::SampleELTEntry> rows;
DoKat(inFiles, osOut, rows, event_to_file);
} else if (tableName == OasisParquet::NONE) {
fprintf(stderr, "FATAL: No table type selected - please select table "
"type for files to be concatenated.\n");
exit(EXIT_FAILURE);
} else { // Should never get here
fprintf(stderr, "FATAL: Unknown table selected.\n");
exit(EXIT_FAILURE);
}
}
}
<commit_msg>Remove second check for end of file (#309)<commit_after>#include "../include/oasis.h"
#ifdef HAVE_PARQUET
#include "../include/oasisparquet.h"
#endif
#include <cstring>
#include <map>
#include <vector>
namespace katparquet {
struct period_event {
int period;
int eventID;
};
bool operator<(const period_event &lhs, const period_event &rhs) {
if (lhs.period != rhs.period) {
return lhs.period < rhs.period;
} else {
return lhs.eventID < rhs.eventID;
}
}
bool operator==(const period_event &lhs, const period_event &rhs) {
return lhs.period == rhs.period && lhs.eventID == rhs.eventID;
}
template<typename tableNameT>
void GetRow(std::map<int, int> &event_to_file, const tableNameT &row,
const int i) {
event_to_file[row.eventID] = i;
}
template<typename tableNameT>
void GetRow(std::map<period_event, int> &period_to_file,
const tableNameT &row, const int i) {
period_event periodEventID;
periodEventID.period = row.period;
periodEventID.eventID = row.eventID;
period_to_file[periodEventID] = i;
}
template<typename tableNameT, typename rowMapT>
void ReadFirstRows(const std::vector<std::string> &inFiles,
std::vector<parquet::StreamReader> &isIn,
std::vector<tableNameT> &rows, rowMapT &rowMap_to_file) {
// Read first row from each file
for (int i = 0; i < (int)inFiles.size(); i++) {
isIn[i] = OasisParquet::SetupParquetInputStream(inFiles[i]);
tableNameT row;
if (isIn[i].eof()) continue; // Ignore empty files
isIn[i] >> row;
rows[i] = row;
GetRow(rowMap_to_file, rows[i], i);
}
}
template<typename tableNameT>
void WriteOutput(std::vector<tableNameT> &rows,
std::map<int, int> &event_to_file,
parquet::StreamWriter &osOut,
std::vector<parquet::StreamReader> &isIn) {
// First entry should always have lowest event ID
while(event_to_file.size() != 0) {
auto iter = event_to_file.begin();
int currentEventID = iter->first;
while (rows[iter->second].eventID == currentEventID) {
osOut << rows[iter->second];
if (isIn[iter->second].eof()) break;
isIn[iter->second] >> rows[iter->second];
}
GetRow(event_to_file, rows[iter->second], iter->second);
event_to_file.erase(iter);
}
}
template<typename tableNameT>
void WriteOutput(std::vector<tableNameT> &rows,
std::map<period_event, int> &period_to_file,
parquet::StreamWriter &osOut,
std::vector<parquet::StreamReader> &isIn) {
// First entry should always have lowest period number followed by event ID
while (period_to_file.size() != 0) {
auto iter = period_to_file.begin();
period_event currentPeriodEvent = iter->first;
period_event periodEventID;
periodEventID.period = rows[iter->second].period;
periodEventID.eventID = rows[iter->second].eventID;
while (periodEventID == currentPeriodEvent) {
osOut << rows[iter->second];
if (isIn[iter->second].eof()) break;
isIn[iter->second] >> rows[iter->second];
periodEventID.period = rows[iter->second].period;
periodEventID.eventID = rows[iter->second].eventID;
}
GetRow(period_to_file, rows[iter->second], iter->second);
period_to_file.erase(iter);
}
}
template<typename tableNameT, typename rowMapT>
void DoKat(const std::vector<std::string> &inFiles,
parquet::StreamWriter &osOut, std::vector<tableNameT> &rows,
rowMapT &rowMap_to_file) {
rows.resize(inFiles.size());
std::vector<parquet::StreamReader> isIn;
isIn.resize(inFiles.size());
ReadFirstRows(inFiles, isIn, rows, rowMap_to_file);
if (rowMap_to_file.size() == 0) {
fprintf(stderr, "ERROR: All input files are empty\n");
exit(EXIT_FAILURE);
}
WriteOutput(rows, rowMap_to_file, osOut, isIn);
}
void doit(const std::vector<std::string> &inFiles,
const std::string outFile, const int tableName) {
parquet::StreamWriter osOut = OasisParquet::GetParquetStreamWriter(tableName, outFile);
std::map<int, int> event_to_file; // Exceedance Loss Table
std::map<period_event, int> period_to_file; // Period Loss Table
if (tableName == OasisParquet::MPLT) {
std::vector<OasisParquet::MomentPLTEntry> rows;
DoKat(inFiles, osOut, rows, period_to_file);
} else if (tableName == OasisParquet::QPLT) {
std::vector<OasisParquet::QuantilePLTEntry> rows;
DoKat(inFiles, osOut, rows, period_to_file);
} else if (tableName == OasisParquet::SPLT) {
std::vector<OasisParquet::SamplePLTEntry> rows;
DoKat(inFiles, osOut, rows, period_to_file);
} else if (tableName == OasisParquet::MELT) {
std::vector<OasisParquet::MomentELTEntry> rows;
DoKat(inFiles, osOut, rows, event_to_file);
} else if (tableName == OasisParquet::QELT) {
std::vector<OasisParquet::QuantileELTEntry> rows;
DoKat(inFiles, osOut, rows, event_to_file);
} else if (tableName == OasisParquet::SELT) {
std::vector<OasisParquet::SampleELTEntry> rows;
DoKat(inFiles, osOut, rows, event_to_file);
} else if (tableName == OasisParquet::NONE) {
fprintf(stderr, "FATAL: No table type selected - please select table "
"type for files to be concatenated.\n");
exit(EXIT_FAILURE);
} else { // Should never get here
fprintf(stderr, "FATAL: Unknown table selected.\n");
exit(EXIT_FAILURE);
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// 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 <errno.h>
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <algorithm>
#include <set>
#include <iostream>
#include <sstream>
#include "leveldb/env.h"
#include "leveldb/status.h"
#include "leveldb/env_dfs.h"
#include "leveldb/table_utils.h"
#include "util/hash.h"
#include "util/mutexlock.h"
#include "helpers/memenv/memenv.h"
#include "../utils/counter.h"
#include "leveldb/env_flash.h"
namespace leveldb {
tera::Counter ssd_read_counter;
tera::Counter ssd_read_size_counter;
tera::Counter ssd_write_counter;
tera::Counter ssd_write_size_counter;
// Log error message
static Status IOError(const std::string& context, int err_number) {
return Status::IOError(context, strerror(err_number));
}
/// copy file from env to local
Status CopyToLocal(const std::string& local_fname, Env* env,
const std::string& fname, uint64_t fsize, bool vanish_allowed) {
uint64_t time_s = env->NowMicros();
uint64_t local_size = 0;
Status s = Env::Default()->GetFileSize(local_fname, &local_size);
if (s.ok() && fsize == local_size) {
return s;
}
Log("[env_flash] local file mismatch, expect %lu, actual %lu, delete %s\n",
fsize, local_size, local_fname.c_str());
Env::Default()->DeleteFile(local_fname);
// Log("[env_flash] open dfs_file %s\n", fname.c_str());
SequentialFile* dfs_file = NULL;
s = env->NewSequentialFile(fname, &dfs_file);
if (!s.ok()) {
return s;
}
for (size_t i = 1; i < local_fname.size(); i++) {
if (local_fname.at(i) == '/') {
Env::Default()->CreateDir(local_fname.substr(0,i));
}
}
// Log("[env_flash] open local %s\n", local_fname.c_str());
WritableFile* local_file = NULL;
s = Env::Default()->NewWritableFile(local_fname, &local_file);
if (!s.ok()) {
if (!vanish_allowed) {
Log("[env_flash] local env error, exit: %s\n",
local_fname.c_str());
exit(-1);
}
delete dfs_file;
return s;
}
char buf[1048576];
Slice result;
local_size = 0;
while (dfs_file->Read(1048576, &result, buf).ok() && result.size() > 0
&& local_file->Append(result).ok()) {
local_size += result.size();
}
delete dfs_file;
delete local_file;
if (local_size == fsize) {
uint64_t time_used = env->NowMicros() - time_s;
//if (time_used > 200000) {
if (true) {
Log("[env_flash] copy %s to local used %llu ms\n",
fname.c_str(), static_cast<unsigned long long>(time_used) / 1000);
}
return s;
}
uint64_t file_size = 0;
s = env->GetFileSize(fname, &file_size);
if (!s.ok()) {
return Status::IOError("dfs GetFileSize fail", s.ToString());
}
if (fsize == file_size) {
// dfs fsize match but local doesn't match
s = IOError("local fsize mismatch", file_size);
} else {
s = IOError("dfs fsize mismatch", file_size);
}
Env::Default()->DeleteFile(local_fname);
return s;
}
class FlashSequentialFile: public SequentialFile {
private:
SequentialFile* dfs_file_;
SequentialFile* flash_file_;
public:
FlashSequentialFile(Env* posix_env, Env* dfs_env, const std::string& fname)
:dfs_file_(NULL), flash_file_(NULL) {
dfs_env->NewSequentialFile(fname, &dfs_file_);
}
virtual ~FlashSequentialFile() {
delete dfs_file_;
delete flash_file_;
}
virtual Status Read(size_t n, Slice* result, char* scratch) {
if (flash_file_) {
return flash_file_->Read(n, result, scratch);
}
return dfs_file_->Read(n, result, scratch);
}
virtual Status Skip(uint64_t n) {
if (flash_file_) {
return flash_file_->Skip(n);
}
return dfs_file_->Skip(n);
}
bool isValid() {
return (dfs_file_ || flash_file_);
}
};
// A file abstraction for randomly reading the contents of a file.
class FlashRandomAccessFile :public RandomAccessFile{
private:
RandomAccessFile* dfs_file_;
RandomAccessFile* flash_file_;
public:
FlashRandomAccessFile(Env* posix_env, Env* dfs_env, const std::string& fname,
uint64_t fsize, bool vanish_allowed)
:dfs_file_(NULL), flash_file_(NULL) {
std::string local_fname = FlashEnv::FlashPath(fname) + fname;
// copy from dfs with seq read
Status copy_status = CopyToLocal(local_fname, dfs_env, fname, fsize,
vanish_allowed);
if (!copy_status.ok()) {
Log("[env_flash] copy to local fail [%s]: %s\n",
copy_status.ToString().c_str(), local_fname.c_str());
// no flash file, use dfs file
dfs_env->NewRandomAccessFile(fname, &dfs_file_);
return;
}
Status s = posix_env->NewRandomAccessFile(local_fname, &flash_file_);
if (s.ok()) {
return;
}
Log("[env_flash] local file exists, but open for RandomAccess fail: %s\n",
local_fname.c_str());
Env::Default()->DeleteFile(local_fname);
dfs_env->NewRandomAccessFile(fname, &dfs_file_);
}
~FlashRandomAccessFile() {
delete dfs_file_;
delete flash_file_;
}
Status Read(uint64_t offset, size_t n, Slice* result,
char* scratch) const {
if (flash_file_) {
Status read_status = flash_file_->Read(offset, n, result, scratch);
if (read_status.ok()) {
ssd_read_counter.Inc();
ssd_read_size_counter.Add(result->size());
}
return read_status;
}
return dfs_file_->Read(offset, n, result, scratch);
}
bool isValid() {
return (dfs_file_ || flash_file_);
}
};
// WritableFile
class FlashWritableFile: public WritableFile {
private:
WritableFile* dfs_file_;
WritableFile* flash_file_;
std::string local_fname_;
public:
FlashWritableFile(Env* posix_env, Env* dfs_env, const std::string& fname)
:dfs_file_(NULL), flash_file_(NULL) {
Status s = dfs_env->NewWritableFile(fname, &dfs_file_);
if (!s.ok()) {
return;
}
if (fname.rfind(".sst") != fname.size()-4) {
// Log(logger, "[env_flash] Don't cache %s\n", fname.c_str());
return;
}
local_fname_ = FlashEnv::FlashPath(fname) + fname;
for(size_t i = 1; i < local_fname_.size(); i++) {
if (local_fname_.at(i) == '/') {
posix_env->CreateDir(local_fname_.substr(0,i));
}
}
s = posix_env->NewWritableFile(local_fname_, &flash_file_);
if (!s.ok()) {
Log("[env_flash] Open local flash file for write fail: %s\n",
local_fname_.c_str());
}
}
virtual ~FlashWritableFile() {
delete dfs_file_;
delete flash_file_;
}
void DeleteLocal() {
delete flash_file_;
flash_file_ = NULL;
Env::Default()->DeleteFile(local_fname_);
}
virtual Status Append(const Slice& data) {
Status s = dfs_file_->Append(data);
if (!s.ok()) {
return s;
}
if (flash_file_) {
Status local_s = flash_file_->Append(data);
if (!local_s.ok()) {
DeleteLocal();
}else{
ssd_write_counter.Inc();
ssd_write_size_counter.Add(data.size());
}
}
return s;
}
bool isValid() {
return (dfs_file_ || flash_file_);
}
virtual Status Flush() {
Status s = dfs_file_->Flush();
if (!s.ok()) {
return s;
}
// Don't flush cache file
/*
if (flash_file_) {
Status local_s = flash_file_->Flush();
if (!local_s.ok()) {
DeleteLocal();
}
}*/
return s;
}
virtual Status Sync() {
Status s = dfs_file_->Sync();
if (!s.ok()) {
return s;
}
/* Don't sync cache file
if (flash_file_) {
Status local_s = flash_file_->Sync();
if (!local_s.ok()) {
DeleteLocal();
}
}*/
return s;
}
virtual Status Close() {
if (flash_file_) {
Status local_s = flash_file_->Close();
if (!local_s.ok()) {
DeleteLocal();
}
}
return dfs_file_->Close();
}
};
std::vector<std::string> FlashEnv::flash_paths_(1, "./flash");
FlashEnv::FlashEnv(Env* base_env) : EnvWrapper(Env::Default())
{
dfs_env_ = base_env;
posix_env_ = Env::Default();
}
FlashEnv::~FlashEnv()
{
}
// SequentialFile
Status FlashEnv::NewSequentialFile(const std::string& fname, SequentialFile** result)
{
FlashSequentialFile* f = new FlashSequentialFile(posix_env_, dfs_env_, fname);
if (!f->isValid()) {
delete f;
*result = NULL;
return IOError(fname, errno);
}
*result = f;
return Status::OK();
}
// random read file
Status FlashEnv::NewRandomAccessFile(const std::string& fname,
uint64_t fsize, RandomAccessFile** result)
{
FlashRandomAccessFile* f =
new FlashRandomAccessFile(posix_env_, dfs_env_, fname,
fsize, vanish_allowed_);
if (f == NULL || !f->isValid()) {
*result = NULL;
delete f;
return IOError(fname, errno);
}
*result = f;
return Status::OK();
}
Status FlashEnv::NewRandomAccessFile(const std::string& fname,
RandomAccessFile** result) {
// not implement
abort();
}
// writable
Status FlashEnv::NewWritableFile(const std::string& fname,
WritableFile** result)
{
Status s;
FlashWritableFile* f = new FlashWritableFile(posix_env_, dfs_env_, fname);
if (f == NULL || !f->isValid()) {
*result = NULL;
delete f;
return IOError(fname, errno);
}
*result = f;
return Status::OK();
}
// FileExists
bool FlashEnv::FileExists(const std::string& fname)
{
return dfs_env_->FileExists(fname);
}
//
Status FlashEnv::GetChildren(const std::string& path,
std::vector<std::string>* result)
{
return dfs_env_->GetChildren(path, result);
}
Status FlashEnv::DeleteFile(const std::string& fname)
{
posix_env_->DeleteFile(FlashEnv::FlashPath(fname) + fname);
return dfs_env_->DeleteFile(fname);
}
Status FlashEnv::CreateDir(const std::string& name)
{
std::string local_name = FlashEnv::FlashPath(name) + name;
for(size_t i=1 ;i<local_name.size(); i++) {
if (local_name.at(i) == '/') {
posix_env_->CreateDir(local_name.substr(0,i));
}
}
posix_env_->CreateDir(local_name);
return dfs_env_->CreateDir(name);
};
Status FlashEnv::DeleteDir(const std::string& name)
{
posix_env_->DeleteDir(FlashEnv::FlashPath(name) + name);
return dfs_env_->DeleteDir(name);
};
Status FlashEnv::GetFileSize(const std::string& fname, uint64_t* size)
{
return dfs_env_->GetFileSize(fname, size);
}
///
Status FlashEnv::RenameFile(const std::string& src, const std::string& target)
{
posix_env_->RenameFile(FlashEnv::FlashPath(src) + src, FlashEnv::FlashPath(target) + target);
return dfs_env_->RenameFile(src, target);
}
Status FlashEnv::LockFile(const std::string& fname, FileLock** lock)
{
*lock = NULL;
return Status::OK();
}
Status FlashEnv::UnlockFile(FileLock* lock)
{
return Status::OK();
}
void FlashEnv::SetFlashPath(const std::string& path, bool vanish_allowed) {
std::vector<std::string> backup;
flash_paths_.swap(backup);
vanish_allowed_ = vanish_allowed;
size_t beg = 0;
const char *str = path.c_str();
for (size_t i = 0; i <= path.size(); ++i) {
if ((str[i] == '\0' || str[i] == ';') && i - beg > 0) {
flash_paths_.push_back(std::string(str + beg, i - beg));
beg = i +1;
if (!vanish_allowed
&& !Env::Default()->FileExists(flash_paths_.back())
&& !Env::Default()->CreateDir(flash_paths_.back()).ok()) {
Log("[env_flash] cannot access cache dir: %s\n",
flash_paths_.back().c_str());
exit(-1);
}
}
}
if (!flash_paths_.size()) {
flash_paths_.swap(backup);
}
}
const std::string& FlashEnv::FlashPath(const std::string& fname) {
if (flash_paths_.size() == 1) {
return flash_paths_[0];
}
uint32_t hash = Hash(fname.c_str(), fname.size(), 13);
return flash_paths_[hash % flash_paths_.size()];
}
bool FlashEnv::vanish_allowed_ = false;
Env* NewFlashEnv(Env* base_env)
{
return new FlashEnv(base_env);
}
} // namespace leveldb
<commit_msg>#556: large block size in copy to local<commit_after>// Copyright (c) 2015, Baidu.com, Inc. All Rights Reserved
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// 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 <errno.h>
#include <stdio.h>
#include <sys/time.h>
#include <time.h>
#include <algorithm>
#include <set>
#include <iostream>
#include <sstream>
#include "leveldb/env.h"
#include "leveldb/status.h"
#include "leveldb/env_dfs.h"
#include "leveldb/table_utils.h"
#include "util/hash.h"
#include "util/mutexlock.h"
#include "helpers/memenv/memenv.h"
#include "../utils/counter.h"
#include "leveldb/env_flash.h"
namespace leveldb {
tera::Counter ssd_read_counter;
tera::Counter ssd_read_size_counter;
tera::Counter ssd_write_counter;
tera::Counter ssd_write_size_counter;
// Log error message
static Status IOError(const std::string& context, int err_number) {
return Status::IOError(context, strerror(err_number));
}
/// copy file from env to local
Status CopyToLocal(const std::string& local_fname, Env* env,
const std::string& fname, uint64_t fsize, bool vanish_allowed) {
uint64_t time_s = env->NowMicros();
uint64_t local_size = 0;
Status s = Env::Default()->GetFileSize(local_fname, &local_size);
if (s.ok() && fsize == local_size) {
return s;
}
Log("[env_flash] local file mismatch, expect %lu, actual %lu, delete %s\n",
fsize, local_size, local_fname.c_str());
Env::Default()->DeleteFile(local_fname);
// Log("[env_flash] open dfs_file %s\n", fname.c_str());
SequentialFile* dfs_file = NULL;
s = env->NewSequentialFile(fname, &dfs_file);
if (!s.ok()) {
return s;
}
for (size_t i = 1; i < local_fname.size(); i++) {
if (local_fname.at(i) == '/') {
Env::Default()->CreateDir(local_fname.substr(0,i));
}
}
// Log("[env_flash] open local %s\n", local_fname.c_str());
WritableFile* local_file = NULL;
s = Env::Default()->NewWritableFile(local_fname, &local_file);
if (!s.ok()) {
if (!vanish_allowed) {
Log("[env_flash] local env error, exit: %s\n",
local_fname.c_str());
exit(-1);
}
delete dfs_file;
return s;
}
char* buf = new char[1048576];
Slice result;
local_size = 0;
while (dfs_file->Read(1048576, &result, buf).ok() && result.size() > 0
&& local_file->Append(result).ok()) {
local_size += result.size();
}
delete buf;
delete dfs_file;
delete local_file;
if (local_size == fsize) {
uint64_t time_used = env->NowMicros() - time_s;
//if (time_used > 200000) {
if (true) {
Log("[env_flash] copy %s to local used %llu ms\n",
fname.c_str(), static_cast<unsigned long long>(time_used) / 1000);
}
return s;
}
uint64_t file_size = 0;
s = env->GetFileSize(fname, &file_size);
if (!s.ok()) {
return Status::IOError("dfs GetFileSize fail", s.ToString());
}
if (fsize == file_size) {
// dfs fsize match but local doesn't match
s = IOError("local fsize mismatch", file_size);
} else {
s = IOError("dfs fsize mismatch", file_size);
}
Env::Default()->DeleteFile(local_fname);
return s;
}
class FlashSequentialFile: public SequentialFile {
private:
SequentialFile* dfs_file_;
SequentialFile* flash_file_;
public:
FlashSequentialFile(Env* posix_env, Env* dfs_env, const std::string& fname)
:dfs_file_(NULL), flash_file_(NULL) {
dfs_env->NewSequentialFile(fname, &dfs_file_);
}
virtual ~FlashSequentialFile() {
delete dfs_file_;
delete flash_file_;
}
virtual Status Read(size_t n, Slice* result, char* scratch) {
if (flash_file_) {
return flash_file_->Read(n, result, scratch);
}
return dfs_file_->Read(n, result, scratch);
}
virtual Status Skip(uint64_t n) {
if (flash_file_) {
return flash_file_->Skip(n);
}
return dfs_file_->Skip(n);
}
bool isValid() {
return (dfs_file_ || flash_file_);
}
};
// A file abstraction for randomly reading the contents of a file.
class FlashRandomAccessFile :public RandomAccessFile{
private:
RandomAccessFile* dfs_file_;
RandomAccessFile* flash_file_;
public:
FlashRandomAccessFile(Env* posix_env, Env* dfs_env, const std::string& fname,
uint64_t fsize, bool vanish_allowed)
:dfs_file_(NULL), flash_file_(NULL) {
std::string local_fname = FlashEnv::FlashPath(fname) + fname;
// copy from dfs with seq read
Status copy_status = CopyToLocal(local_fname, dfs_env, fname, fsize,
vanish_allowed);
if (!copy_status.ok()) {
Log("[env_flash] copy to local fail [%s]: %s\n",
copy_status.ToString().c_str(), local_fname.c_str());
// no flash file, use dfs file
dfs_env->NewRandomAccessFile(fname, &dfs_file_);
return;
}
Status s = posix_env->NewRandomAccessFile(local_fname, &flash_file_);
if (s.ok()) {
return;
}
Log("[env_flash] local file exists, but open for RandomAccess fail: %s\n",
local_fname.c_str());
Env::Default()->DeleteFile(local_fname);
dfs_env->NewRandomAccessFile(fname, &dfs_file_);
}
~FlashRandomAccessFile() {
delete dfs_file_;
delete flash_file_;
}
Status Read(uint64_t offset, size_t n, Slice* result,
char* scratch) const {
if (flash_file_) {
Status read_status = flash_file_->Read(offset, n, result, scratch);
if (read_status.ok()) {
ssd_read_counter.Inc();
ssd_read_size_counter.Add(result->size());
}
return read_status;
}
return dfs_file_->Read(offset, n, result, scratch);
}
bool isValid() {
return (dfs_file_ || flash_file_);
}
};
// WritableFile
class FlashWritableFile: public WritableFile {
private:
WritableFile* dfs_file_;
WritableFile* flash_file_;
std::string local_fname_;
public:
FlashWritableFile(Env* posix_env, Env* dfs_env, const std::string& fname)
:dfs_file_(NULL), flash_file_(NULL) {
Status s = dfs_env->NewWritableFile(fname, &dfs_file_);
if (!s.ok()) {
return;
}
if (fname.rfind(".sst") != fname.size()-4) {
// Log(logger, "[env_flash] Don't cache %s\n", fname.c_str());
return;
}
local_fname_ = FlashEnv::FlashPath(fname) + fname;
for(size_t i = 1; i < local_fname_.size(); i++) {
if (local_fname_.at(i) == '/') {
posix_env->CreateDir(local_fname_.substr(0,i));
}
}
s = posix_env->NewWritableFile(local_fname_, &flash_file_);
if (!s.ok()) {
Log("[env_flash] Open local flash file for write fail: %s\n",
local_fname_.c_str());
}
}
virtual ~FlashWritableFile() {
delete dfs_file_;
delete flash_file_;
}
void DeleteLocal() {
delete flash_file_;
flash_file_ = NULL;
Env::Default()->DeleteFile(local_fname_);
}
virtual Status Append(const Slice& data) {
Status s = dfs_file_->Append(data);
if (!s.ok()) {
return s;
}
if (flash_file_) {
Status local_s = flash_file_->Append(data);
if (!local_s.ok()) {
DeleteLocal();
}else{
ssd_write_counter.Inc();
ssd_write_size_counter.Add(data.size());
}
}
return s;
}
bool isValid() {
return (dfs_file_ || flash_file_);
}
virtual Status Flush() {
Status s = dfs_file_->Flush();
if (!s.ok()) {
return s;
}
// Don't flush cache file
/*
if (flash_file_) {
Status local_s = flash_file_->Flush();
if (!local_s.ok()) {
DeleteLocal();
}
}*/
return s;
}
virtual Status Sync() {
Status s = dfs_file_->Sync();
if (!s.ok()) {
return s;
}
/* Don't sync cache file
if (flash_file_) {
Status local_s = flash_file_->Sync();
if (!local_s.ok()) {
DeleteLocal();
}
}*/
return s;
}
virtual Status Close() {
if (flash_file_) {
Status local_s = flash_file_->Close();
if (!local_s.ok()) {
DeleteLocal();
}
}
return dfs_file_->Close();
}
};
std::vector<std::string> FlashEnv::flash_paths_(1, "./flash");
FlashEnv::FlashEnv(Env* base_env) : EnvWrapper(Env::Default())
{
dfs_env_ = base_env;
posix_env_ = Env::Default();
}
FlashEnv::~FlashEnv()
{
}
// SequentialFile
Status FlashEnv::NewSequentialFile(const std::string& fname, SequentialFile** result)
{
FlashSequentialFile* f = new FlashSequentialFile(posix_env_, dfs_env_, fname);
if (!f->isValid()) {
delete f;
*result = NULL;
return IOError(fname, errno);
}
*result = f;
return Status::OK();
}
// random read file
Status FlashEnv::NewRandomAccessFile(const std::string& fname,
uint64_t fsize, RandomAccessFile** result)
{
FlashRandomAccessFile* f =
new FlashRandomAccessFile(posix_env_, dfs_env_, fname,
fsize, vanish_allowed_);
if (f == NULL || !f->isValid()) {
*result = NULL;
delete f;
return IOError(fname, errno);
}
*result = f;
return Status::OK();
}
Status FlashEnv::NewRandomAccessFile(const std::string& fname,
RandomAccessFile** result) {
// not implement
abort();
}
// writable
Status FlashEnv::NewWritableFile(const std::string& fname,
WritableFile** result)
{
Status s;
FlashWritableFile* f = new FlashWritableFile(posix_env_, dfs_env_, fname);
if (f == NULL || !f->isValid()) {
*result = NULL;
delete f;
return IOError(fname, errno);
}
*result = f;
return Status::OK();
}
// FileExists
bool FlashEnv::FileExists(const std::string& fname)
{
return dfs_env_->FileExists(fname);
}
//
Status FlashEnv::GetChildren(const std::string& path,
std::vector<std::string>* result)
{
return dfs_env_->GetChildren(path, result);
}
Status FlashEnv::DeleteFile(const std::string& fname)
{
posix_env_->DeleteFile(FlashEnv::FlashPath(fname) + fname);
return dfs_env_->DeleteFile(fname);
}
Status FlashEnv::CreateDir(const std::string& name)
{
std::string local_name = FlashEnv::FlashPath(name) + name;
for(size_t i=1 ;i<local_name.size(); i++) {
if (local_name.at(i) == '/') {
posix_env_->CreateDir(local_name.substr(0,i));
}
}
posix_env_->CreateDir(local_name);
return dfs_env_->CreateDir(name);
};
Status FlashEnv::DeleteDir(const std::string& name)
{
posix_env_->DeleteDir(FlashEnv::FlashPath(name) + name);
return dfs_env_->DeleteDir(name);
};
Status FlashEnv::GetFileSize(const std::string& fname, uint64_t* size)
{
return dfs_env_->GetFileSize(fname, size);
}
///
Status FlashEnv::RenameFile(const std::string& src, const std::string& target)
{
posix_env_->RenameFile(FlashEnv::FlashPath(src) + src, FlashEnv::FlashPath(target) + target);
return dfs_env_->RenameFile(src, target);
}
Status FlashEnv::LockFile(const std::string& fname, FileLock** lock)
{
*lock = NULL;
return Status::OK();
}
Status FlashEnv::UnlockFile(FileLock* lock)
{
return Status::OK();
}
void FlashEnv::SetFlashPath(const std::string& path, bool vanish_allowed) {
std::vector<std::string> backup;
flash_paths_.swap(backup);
vanish_allowed_ = vanish_allowed;
size_t beg = 0;
const char *str = path.c_str();
for (size_t i = 0; i <= path.size(); ++i) {
if ((str[i] == '\0' || str[i] == ';') && i - beg > 0) {
flash_paths_.push_back(std::string(str + beg, i - beg));
beg = i +1;
if (!vanish_allowed
&& !Env::Default()->FileExists(flash_paths_.back())
&& !Env::Default()->CreateDir(flash_paths_.back()).ok()) {
Log("[env_flash] cannot access cache dir: %s\n",
flash_paths_.back().c_str());
exit(-1);
}
}
}
if (!flash_paths_.size()) {
flash_paths_.swap(backup);
}
}
const std::string& FlashEnv::FlashPath(const std::string& fname) {
if (flash_paths_.size() == 1) {
return flash_paths_[0];
}
uint32_t hash = Hash(fname.c_str(), fname.size(), 13);
return flash_paths_[hash % flash_paths_.size()];
}
bool FlashEnv::vanish_allowed_ = false;
Env* NewFlashEnv(Env* base_env)
{
return new FlashEnv(base_env);
}
} // namespace leveldb
<|endoftext|> |
<commit_before><commit_msg>fix Generator_makefile<commit_after><|endoftext|> |
<commit_before><commit_msg>PrimitiveVariable : Fix typo<commit_after><|endoftext|> |
<commit_before>#include <fcntl.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/text_format.h>
#include <opencv2/core/core.hpp>
#ifdef USE_OPENCV
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/highgui/highgui_c.h>
#include <opencv2/imgproc/imgproc.hpp>
#endif // USE_OPENCV
#include <stdint.h>
#include <algorithm>
#include <fstream> // NOLINT(readability/streams)
#include <string>
#include <vector>
#include "caffe/common.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/io.hpp"
const int kProtoReadBytesLimit = INT_MAX; // Max size of 2 GB minus 1 byte.
namespace caffe {
using google::protobuf::io::FileInputStream;
using google::protobuf::io::FileOutputStream;
using google::protobuf::io::ZeroCopyInputStream;
using google::protobuf::io::CodedInputStream;
using google::protobuf::io::ZeroCopyOutputStream;
using google::protobuf::io::CodedOutputStream;
using google::protobuf::Message;
bool ReadProtoFromTextFile(const char* filename, Message* proto) {
int fd = open(filename, O_RDONLY);
CHECK_NE(fd, -1) << "File not found: " << filename;
FileInputStream* input = new FileInputStream(fd);
bool success = google::protobuf::TextFormat::Parse(input, proto);
delete input;
close(fd);
return success;
}
void WriteProtoToTextFile(const Message& proto, const char* filename) {
int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
FileOutputStream* output = new FileOutputStream(fd);
CHECK(google::protobuf::TextFormat::Print(proto, output));
delete output;
close(fd);
}
bool ReadProtoFromBinaryFile(const char* filename, Message* proto) {
int fd = open(filename, O_RDONLY);
CHECK_NE(fd, -1) << "File not found: " << filename;
ZeroCopyInputStream* raw_input = new FileInputStream(fd);
CodedInputStream* coded_input = new CodedInputStream(raw_input);
coded_input->SetTotalBytesLimit(kProtoReadBytesLimit, 536870912);
bool success = proto->ParseFromCodedStream(coded_input);
delete coded_input;
delete raw_input;
close(fd);
return success;
}
void WriteProtoToBinaryFile(const Message& proto, const char* filename) {
fstream output(filename, ios::out | ios::trunc | ios::binary);
CHECK(proto.SerializeToOstream(&output));
}
#ifdef USE_OPENCV
cv::Mat ReadImageToCVMat(const string& filename,
const int height, const int width, const bool is_color) {
cv::Mat cv_img;
int cv_read_flag = (is_color ? CV_LOAD_IMAGE_COLOR :
CV_LOAD_IMAGE_GRAYSCALE);
cv::Mat cv_img_origin = cv::imread(filename, cv_read_flag);
if (!cv_img_origin.data) {
LOG(ERROR) << "Could not open or find file " << filename;
return cv_img_origin;
}
if (height > 0 && width > 0) {
cv::resize(cv_img_origin, cv_img, cv::Size(width, height));
} else {
cv_img = cv_img_origin;
}
return cv_img;
}
cv::Mat ReadImageToCVMat(const string& filename,
const int height, const int width) {
return ReadImageToCVMat(filename, height, width, true);
}
cv::Mat ReadImageToCVMat(const string& filename,
const bool is_color) {
return ReadImageToCVMat(filename, 0, 0, is_color);
}
cv::Mat ReadImageToCVMat(const string& filename) {
return ReadImageToCVMat(filename, 0, 0, true);
}
// Do the file extension and encoding match?
static bool matchExt(const std::string & fn,
std::string en) {
size_t p = fn.rfind('.');
std::string ext = p != fn.npos ? fn.substr(p) : fn;
std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
std::transform(en.begin(), en.end(), en.begin(), ::tolower);
if ( ext == en )
return true;
if ( en == "jpg" && ext == "jpeg" )
return true;
return false;
}
bool ReadImageToDatum(const string& filename, const int label,
const int height, const int width, const bool is_color,
const std::string & encoding, Datum* datum) {
cv::Mat cv_img = ReadImageToCVMat(filename, height, width, is_color);
if (cv_img.data) {
if (encoding.size()) {
if ( (cv_img.channels() == 3) == is_color && !height && !width &&
matchExt(filename, encoding) )
return ReadFileToDatum(filename, label, datum);
std::vector<uchar> buf;
cv::imencode("."+encoding, cv_img, buf);
datum->set_data(std::string(reinterpret_cast<char*>(&buf[0]),
buf.size()));
datum->set_label(label);
datum->set_encoded(true);
return true;
}
CVMatToDatum(cv_img, datum);
datum->set_label(label);
return true;
} else {
return false;
}
}
#endif // USE_OPENCV
bool ReadFileToDatum(const string& filename, const int label,
Datum* datum) {
std::streampos size;
fstream file(filename.c_str(), ios::in|ios::binary|ios::ate);
if (file.is_open()) {
size = file.tellg();
std::string buffer(size, ' ');
file.seekg(0, ios::beg);
file.read(&buffer[0], size);
file.close();
datum->set_data(buffer);
datum->set_label(label);
datum->set_encoded(true);
return true;
} else {
return false;
}
}
#ifdef USE_OPENCV
cv::Mat DecodeDatumToCVMatNative(const Datum& datum) {
cv::Mat cv_img;
CHECK(datum.encoded()) << "Datum not encoded";
const string& data = datum.data();
std::vector<char> vec_data(data.c_str(), data.c_str() + data.size());
cv_img = cv::imdecode(vec_data, -1);
if (!cv_img.data) {
LOG(ERROR) << "Could not decode datum ";
}
return cv_img;
}
cv::Mat DecodeDatumToCVMat(const Datum& datum, bool is_color) {
cv::Mat cv_img;
CHECK(datum.encoded()) << "Datum not encoded";
const string& data = datum.data();
std::vector<char> vec_data(data.c_str(), data.c_str() + data.size());
int cv_read_flag = (is_color ? CV_LOAD_IMAGE_COLOR :
CV_LOAD_IMAGE_GRAYSCALE);
cv_img = cv::imdecode(vec_data, cv_read_flag);
if (!cv_img.data) {
LOG(ERROR) << "Could not decode datum ";
}
return cv_img;
}
// If Datum is encoded will decoded using DecodeDatumToCVMat and CVMatToDatum
// If Datum is not encoded will do nothing
bool DecodeDatumNative(Datum* datum) {
if (datum->encoded()) {
cv::Mat cv_img = DecodeDatumToCVMatNative((*datum));
CVMatToDatum(cv_img, datum);
return true;
} else {
return false;
}
}
bool DecodeDatum(Datum* datum, bool is_color) {
if (datum->encoded()) {
cv::Mat cv_img = DecodeDatumToCVMat((*datum), is_color);
CVMatToDatum(cv_img, datum);
return true;
} else {
return false;
}
}
void CVMatToDatum(const cv::Mat& cv_img, Datum* datum) {
CHECK(cv_img.depth() == CV_8U) << "Image data type must be unsigned byte";
datum->set_channels(cv_img.channels());
datum->set_height(cv_img.rows);
datum->set_width(cv_img.cols);
datum->clear_data();
datum->clear_float_data();
datum->set_encoded(false);
int datum_channels = datum->channels();
int datum_height = datum->height();
int datum_width = datum->width();
int datum_size = datum_channels * datum_height * datum_width;
std::string buffer(datum_size, ' ');
for (int h = 0; h < datum_height; ++h) {
const uchar* ptr = cv_img.ptr<uchar>(h);
int img_index = 0;
for (int w = 0; w < datum_width; ++w) {
for (int c = 0; c < datum_channels; ++c) {
int datum_index = (c * datum_height + h) * datum_width + w;
buffer[datum_index] = static_cast<char>(ptr[img_index++]);
}
}
}
datum->set_data(buffer);
}
#endif // USE_OPENCV
} // namespace caffe
<commit_msg>allow compilation without opencv<commit_after>#include <fcntl.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/io/zero_copy_stream_impl.h>
#include <google/protobuf/text_format.h>
#ifdef USE_OPENCV
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/highgui/highgui_c.h>
#include <opencv2/imgproc/imgproc.hpp>
#endif // USE_OPENCV
#include <stdint.h>
#include <algorithm>
#include <fstream> // NOLINT(readability/streams)
#include <string>
#include <vector>
#include "caffe/common.hpp"
#include "caffe/proto/caffe.pb.h"
#include "caffe/util/io.hpp"
const int kProtoReadBytesLimit = INT_MAX; // Max size of 2 GB minus 1 byte.
namespace caffe {
using google::protobuf::io::FileInputStream;
using google::protobuf::io::FileOutputStream;
using google::protobuf::io::ZeroCopyInputStream;
using google::protobuf::io::CodedInputStream;
using google::protobuf::io::ZeroCopyOutputStream;
using google::protobuf::io::CodedOutputStream;
using google::protobuf::Message;
bool ReadProtoFromTextFile(const char* filename, Message* proto) {
int fd = open(filename, O_RDONLY);
CHECK_NE(fd, -1) << "File not found: " << filename;
FileInputStream* input = new FileInputStream(fd);
bool success = google::protobuf::TextFormat::Parse(input, proto);
delete input;
close(fd);
return success;
}
void WriteProtoToTextFile(const Message& proto, const char* filename) {
int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
FileOutputStream* output = new FileOutputStream(fd);
CHECK(google::protobuf::TextFormat::Print(proto, output));
delete output;
close(fd);
}
bool ReadProtoFromBinaryFile(const char* filename, Message* proto) {
int fd = open(filename, O_RDONLY);
CHECK_NE(fd, -1) << "File not found: " << filename;
ZeroCopyInputStream* raw_input = new FileInputStream(fd);
CodedInputStream* coded_input = new CodedInputStream(raw_input);
coded_input->SetTotalBytesLimit(kProtoReadBytesLimit, 536870912);
bool success = proto->ParseFromCodedStream(coded_input);
delete coded_input;
delete raw_input;
close(fd);
return success;
}
void WriteProtoToBinaryFile(const Message& proto, const char* filename) {
fstream output(filename, ios::out | ios::trunc | ios::binary);
CHECK(proto.SerializeToOstream(&output));
}
#ifdef USE_OPENCV
cv::Mat ReadImageToCVMat(const string& filename,
const int height, const int width, const bool is_color) {
cv::Mat cv_img;
int cv_read_flag = (is_color ? CV_LOAD_IMAGE_COLOR :
CV_LOAD_IMAGE_GRAYSCALE);
cv::Mat cv_img_origin = cv::imread(filename, cv_read_flag);
if (!cv_img_origin.data) {
LOG(ERROR) << "Could not open or find file " << filename;
return cv_img_origin;
}
if (height > 0 && width > 0) {
cv::resize(cv_img_origin, cv_img, cv::Size(width, height));
} else {
cv_img = cv_img_origin;
}
return cv_img;
}
cv::Mat ReadImageToCVMat(const string& filename,
const int height, const int width) {
return ReadImageToCVMat(filename, height, width, true);
}
cv::Mat ReadImageToCVMat(const string& filename,
const bool is_color) {
return ReadImageToCVMat(filename, 0, 0, is_color);
}
cv::Mat ReadImageToCVMat(const string& filename) {
return ReadImageToCVMat(filename, 0, 0, true);
}
// Do the file extension and encoding match?
static bool matchExt(const std::string & fn,
std::string en) {
size_t p = fn.rfind('.');
std::string ext = p != fn.npos ? fn.substr(p) : fn;
std::transform(ext.begin(), ext.end(), ext.begin(), ::tolower);
std::transform(en.begin(), en.end(), en.begin(), ::tolower);
if ( ext == en )
return true;
if ( en == "jpg" && ext == "jpeg" )
return true;
return false;
}
bool ReadImageToDatum(const string& filename, const int label,
const int height, const int width, const bool is_color,
const std::string & encoding, Datum* datum) {
cv::Mat cv_img = ReadImageToCVMat(filename, height, width, is_color);
if (cv_img.data) {
if (encoding.size()) {
if ( (cv_img.channels() == 3) == is_color && !height && !width &&
matchExt(filename, encoding) )
return ReadFileToDatum(filename, label, datum);
std::vector<uchar> buf;
cv::imencode("."+encoding, cv_img, buf);
datum->set_data(std::string(reinterpret_cast<char*>(&buf[0]),
buf.size()));
datum->set_label(label);
datum->set_encoded(true);
return true;
}
CVMatToDatum(cv_img, datum);
datum->set_label(label);
return true;
} else {
return false;
}
}
#endif // USE_OPENCV
bool ReadFileToDatum(const string& filename, const int label,
Datum* datum) {
std::streampos size;
fstream file(filename.c_str(), ios::in|ios::binary|ios::ate);
if (file.is_open()) {
size = file.tellg();
std::string buffer(size, ' ');
file.seekg(0, ios::beg);
file.read(&buffer[0], size);
file.close();
datum->set_data(buffer);
datum->set_label(label);
datum->set_encoded(true);
return true;
} else {
return false;
}
}
#ifdef USE_OPENCV
cv::Mat DecodeDatumToCVMatNative(const Datum& datum) {
cv::Mat cv_img;
CHECK(datum.encoded()) << "Datum not encoded";
const string& data = datum.data();
std::vector<char> vec_data(data.c_str(), data.c_str() + data.size());
cv_img = cv::imdecode(vec_data, -1);
if (!cv_img.data) {
LOG(ERROR) << "Could not decode datum ";
}
return cv_img;
}
cv::Mat DecodeDatumToCVMat(const Datum& datum, bool is_color) {
cv::Mat cv_img;
CHECK(datum.encoded()) << "Datum not encoded";
const string& data = datum.data();
std::vector<char> vec_data(data.c_str(), data.c_str() + data.size());
int cv_read_flag = (is_color ? CV_LOAD_IMAGE_COLOR :
CV_LOAD_IMAGE_GRAYSCALE);
cv_img = cv::imdecode(vec_data, cv_read_flag);
if (!cv_img.data) {
LOG(ERROR) << "Could not decode datum ";
}
return cv_img;
}
// If Datum is encoded will decoded using DecodeDatumToCVMat and CVMatToDatum
// If Datum is not encoded will do nothing
bool DecodeDatumNative(Datum* datum) {
if (datum->encoded()) {
cv::Mat cv_img = DecodeDatumToCVMatNative((*datum));
CVMatToDatum(cv_img, datum);
return true;
} else {
return false;
}
}
bool DecodeDatum(Datum* datum, bool is_color) {
if (datum->encoded()) {
cv::Mat cv_img = DecodeDatumToCVMat((*datum), is_color);
CVMatToDatum(cv_img, datum);
return true;
} else {
return false;
}
}
void CVMatToDatum(const cv::Mat& cv_img, Datum* datum) {
CHECK(cv_img.depth() == CV_8U) << "Image data type must be unsigned byte";
datum->set_channels(cv_img.channels());
datum->set_height(cv_img.rows);
datum->set_width(cv_img.cols);
datum->clear_data();
datum->clear_float_data();
datum->set_encoded(false);
int datum_channels = datum->channels();
int datum_height = datum->height();
int datum_width = datum->width();
int datum_size = datum_channels * datum_height * datum_width;
std::string buffer(datum_size, ' ');
for (int h = 0; h < datum_height; ++h) {
const uchar* ptr = cv_img.ptr<uchar>(h);
int img_index = 0;
for (int w = 0; w < datum_width; ++w) {
for (int c = 0; c < datum_channels; ++c) {
int datum_index = (c * datum_height + h) * datum_width + w;
buffer[datum_index] = static_cast<char>(ptr[img_index++]);
}
}
}
datum->set_data(buffer);
}
#endif // USE_OPENCV
} // namespace caffe
<|endoftext|> |
<commit_before>#include "theme-loader.h"
#include <QApplication>
#include <QDir>
#include <QFile>
ThemeLoader::ThemeLoader(QString path, QObject *parent)
: QObject(parent), m_path(std::move(path))
{
connect(&m_watcher, &QFileSystemWatcher::fileChanged, this, &ThemeLoader::themeFileChanged);
}
QStringList ThemeLoader::getAllThemes() const
{
return QDir(m_path).entryList(QDir::Dirs | QDir::NoDotAndDotDot);
}
bool ThemeLoader::setTheme(const QString &name)
{
const QString dir = QString(m_path).replace('\\', '/') + name + "/";
const QString cssFile = dir + "style.css";
QFile f(cssFile);
if (!f.open(QFile::ReadOnly | QFile::Text)) {
return false;
}
QString css = f.readAll();
f.close();
// Replace urls relative paths by absolute ones
css.replace("url(", "url(" + dir);
// Update watcher if necessary
if (m_currentTheme != name) {
m_currentTheme = name;
m_watcher.removePaths(m_watcher.files());
m_watcher.addPath(cssFile);
}
qApp->setStyleSheet(css);
return true;
}
void ThemeLoader::themeFileChanged()
{
setTheme(m_currentTheme);
}
<commit_msg>Fix warning on startup from theme watcher<commit_after>#include "theme-loader.h"
#include <QApplication>
#include <QDir>
#include <QFile>
ThemeLoader::ThemeLoader(QString path, QObject *parent)
: QObject(parent), m_path(std::move(path))
{
connect(&m_watcher, &QFileSystemWatcher::fileChanged, this, &ThemeLoader::themeFileChanged);
}
QStringList ThemeLoader::getAllThemes() const
{
return QDir(m_path).entryList(QDir::Dirs | QDir::NoDotAndDotDot);
}
bool ThemeLoader::setTheme(const QString &name)
{
const QString dir = QString(m_path).replace('\\', '/') + name + "/";
const QString cssFile = dir + "style.css";
QFile f(cssFile);
if (!f.open(QFile::ReadOnly | QFile::Text)) {
return false;
}
QString css = f.readAll();
f.close();
// Replace urls relative paths by absolute ones
css.replace("url(", "url(" + dir);
// Update watcher if necessary
if (m_currentTheme != name) {
m_currentTheme = name;
if (!m_watcher.files().isEmpty()) {
m_watcher.removePaths(m_watcher.files());
}
m_watcher.addPath(cssFile);
}
qApp->setStyleSheet(css);
return true;
}
void ThemeLoader::themeFileChanged()
{
setTheme(m_currentTheme);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <nix/hdf5/Group.hpp>
#include <boost/multi_array.hpp>
namespace nix {
namespace hdf5 {
Group::Group()
: h5group()
{}
Group::Group(H5::Group h5group)
: h5group(h5group)
{}
Group::Group(const Group &group)
: h5group(group.h5group)
{}
Group& Group::operator=(const Group &group)
{
h5group = group.h5group;
return *this;
}
bool Group::hasAttr(const std::string &name) const {
return H5Aexists(h5group.getId(), name.c_str());
}
void Group::removeAttr(const std::string &name) const {
h5group.removeAttr(name);
}
bool Group::hasObject(const std::string &name) const {
// empty string should return false, not exception (which H5Lexists would)
if (name.empty()) {
return false;
}
htri_t res = H5Lexists(h5group.getLocId(), name.c_str(), H5P_DEFAULT);
return res;
}
size_t Group::objectCount() const {
return h5group.getNumObjs();
}
std::string Group::objectName(size_t index) const {
std::string str_name;
// check whether name is found by index
ssize_t name_len = H5Lget_name_by_idx(h5group.getLocId(),
".",
H5_INDEX_NAME,
H5_ITER_NATIVE,
(hsize_t) index,
NULL,
0,
H5P_DEFAULT);
if (name_len > 0) {
char* name = new char[name_len+1];
name_len = H5Lget_name_by_idx(h5group.getLocId(),
".",
H5_INDEX_NAME,
H5_ITER_NATIVE,
(hsize_t) index,
name,
name_len+1,
H5P_DEFAULT);
str_name = name;
delete [] name;
} else {
str_name = "";
}
return str_name;
}
bool Group::hasData(const std::string &name) const {
if (hasObject(name)) {
H5G_stat_t info;
h5group.getObjinfo(name, info);
if (info.type == H5G_DATASET) {
return true;
}
}
return false;
}
void Group::removeData(const std::string &name) {
if (hasData(name))
h5group.unlink(name);
}
DataSet Group::openData(const std::string &name) const {
H5::DataSet ds5 = h5group.openDataSet(name);
return DataSet(ds5);
}
bool Group::hasGroup(const std::string &name) const {
if (hasObject(name)) {
H5G_stat_t info;
h5group.getObjinfo(name, info);
if (info.type == H5G_GROUP) {
return true;
}
}
return false;
}
Group Group::openGroup(const std::string &name, bool create) const {
Group g;
if (hasGroup(name)) {
g = Group(h5group.openGroup(name));
} else if (create) {
g = Group(h5group.createGroup(name));
} else {
throw std::runtime_error("Unable to open group with name '" + name + "'!");
}
return g;
}
void Group::removeGroup(const std::string &name) {
if (hasGroup(name))
h5group.unlink(name);
}
void Group::renameGroup(const std::string &old_name, const std::string &new_name) {
if (hasGroup(old_name)) {
h5group.move(old_name, new_name);
}
}
bool Group::operator==(const Group &group) const {
return h5group.getLocId() == group.h5group.getLocId();
}
bool Group::operator!=(const Group &group) const {
return h5group.getLocId() != group.h5group.getLocId();
}
H5::Group Group::h5Group() const {
return h5group;
}
Group Group::createLink(const Group &target, const std::string &link_name) {
herr_t error = H5Lcreate_hard(target.h5group.getLocId(), ".", h5group.getLocId(), link_name.c_str(),
H5L_SAME_LOC, H5L_SAME_LOC);
if (error)
throw std::runtime_error("Unable to create link " + link_name);
return openGroup(link_name, false);
}
// TODO implement some kind of roll-back in order to avoid half renamed links.
bool Group::renameAllLinks(const std::string &old_name, const std::string &new_name) {
bool renamed = false;
if (hasGroup(old_name)) {
std::vector<std::string> links;
Group group = openGroup(old_name, false);
size_t size = 128;
char *name_read = new char[size];
size_t size_read = H5Iget_name(group.h5group.getId(), name_read, size);
while (size_read > 0) {
if (size_read < size) {
H5Ldelete(h5group.getId(), name_read, H5L_SAME_LOC);
links.push_back(name_read);
} else {
delete[] name_read;
size = size * 2;
name_read = new char[size];
}
size_read = H5Iget_name(group.h5group.getId(), name_read, size);
}
renamed = links.size() > 0;
for (std::string curr_name: links) {
size_t pos = curr_name.find_last_of('/') + 1;
if (curr_name.substr(pos) == old_name) {
curr_name.replace(curr_name.begin() + pos, curr_name.end(), new_name.begin(), new_name.end());
}
herr_t error = H5Lcreate_hard(group.h5group.getLocId(), ".", h5group.getLocId(), curr_name.c_str(),
H5L_SAME_LOC, H5L_SAME_LOC);
renamed = renamed && (error >= 0);
}
}
return renamed;
}
// TODO implement some kind of roll-back in order to avoid half removed links.
bool Group::removeAllLinks(const std::string &name) {
bool removed = false;
if (hasGroup(name)) {
Group group = openGroup(name, false);
size_t size = 128;
char *name_read = new char[size];
size_t size_read = H5Iget_name(group.h5group.getId(), name_read, size);
while (size_read > 0) {
if (size_read < size) {
H5Ldelete(h5group.getId(), name_read, H5L_SAME_LOC);
} else {
delete[] name_read;
size = size * 2;
name_read = new char[size];
}
size_read = H5Iget_name(group.h5group.getId(), name_read, size);
}
delete[] name_read;
removed = true;
}
return removed;
}
void Group::readAttr(const H5::Attribute &attr, H5::DataType mem_type, const NDSize &size, void *data) {
attr.read(mem_type, data);
}
void Group::readAttr(const H5::Attribute &attr, H5::DataType mem_type, const NDSize &size, std::string *data) {
StringWriter writer(size, data);
attr.read(mem_type, *writer);
writer.finish();
H5::DataSet::vlenReclaim(*writer, mem_type, attr.getSpace()); //recycle space?
}
void Group::writeAttr(const H5::Attribute &attr, H5::DataType mem_type, const NDSize &size, const void *data) {
attr.write(mem_type, data);
}
void Group::writeAttr(const H5::Attribute &attr, H5::DataType mem_type, const NDSize &size, const std::string *data) {
StringReader reader(size, data);
attr.write(mem_type, *reader);
}
Group::~Group() {
h5group.close();
}
} // namespace hdf5
} // namespace nix
<commit_msg>Modified Group.cpp to check index before calling H5Lget_name_by_idx<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <nix/hdf5/Group.hpp>
#include <boost/multi_array.hpp>
namespace nix {
namespace hdf5 {
Group::Group()
: h5group()
{}
Group::Group(H5::Group h5group)
: h5group(h5group)
{}
Group::Group(const Group &group)
: h5group(group.h5group)
{}
Group& Group::operator=(const Group &group)
{
h5group = group.h5group;
return *this;
}
bool Group::hasAttr(const std::string &name) const {
return H5Aexists(h5group.getId(), name.c_str());
}
void Group::removeAttr(const std::string &name) const {
h5group.removeAttr(name);
}
bool Group::hasObject(const std::string &name) const {
// empty string should return false, not exception (which H5Lexists would)
if (name.empty()) {
return false;
}
htri_t res = H5Lexists(h5group.getLocId(), name.c_str(), H5P_DEFAULT);
return res;
}
size_t Group::objectCount() const {
return h5group.getNumObjs();
}
std::string Group::objectName(size_t index) const {
// check if index valid
if(index > objectCount()) {
throw OutOfBounds("No data array at given index", index);
}
std::string str_name;
// check whether name is found by index
ssize_t name_len = H5Lget_name_by_idx(h5group.getLocId(),
".",
H5_INDEX_NAME,
H5_ITER_NATIVE,
(hsize_t) index,
NULL,
0,
H5P_DEFAULT);
if (name_len > 0) {
char* name = new char[name_len+1];
name_len = H5Lget_name_by_idx(h5group.getLocId(),
".",
H5_INDEX_NAME,
H5_ITER_NATIVE,
(hsize_t) index,
name,
name_len+1,
H5P_DEFAULT);
str_name = name;
delete [] name;
} else {
str_name = "";
}
return str_name;
}
bool Group::hasData(const std::string &name) const {
if (hasObject(name)) {
H5G_stat_t info;
h5group.getObjinfo(name, info);
if (info.type == H5G_DATASET) {
return true;
}
}
return false;
}
void Group::removeData(const std::string &name) {
if (hasData(name))
h5group.unlink(name);
}
DataSet Group::openData(const std::string &name) const {
H5::DataSet ds5 = h5group.openDataSet(name);
return DataSet(ds5);
}
bool Group::hasGroup(const std::string &name) const {
if (hasObject(name)) {
H5G_stat_t info;
h5group.getObjinfo(name, info);
if (info.type == H5G_GROUP) {
return true;
}
}
return false;
}
Group Group::openGroup(const std::string &name, bool create) const {
Group g;
if (hasGroup(name)) {
g = Group(h5group.openGroup(name));
} else if (create) {
g = Group(h5group.createGroup(name));
} else {
throw std::runtime_error("Unable to open group with name '" + name + "'!");
}
return g;
}
void Group::removeGroup(const std::string &name) {
if (hasGroup(name))
h5group.unlink(name);
}
void Group::renameGroup(const std::string &old_name, const std::string &new_name) {
if (hasGroup(old_name)) {
h5group.move(old_name, new_name);
}
}
bool Group::operator==(const Group &group) const {
return h5group.getLocId() == group.h5group.getLocId();
}
bool Group::operator!=(const Group &group) const {
return h5group.getLocId() != group.h5group.getLocId();
}
H5::Group Group::h5Group() const {
return h5group;
}
Group Group::createLink(const Group &target, const std::string &link_name) {
herr_t error = H5Lcreate_hard(target.h5group.getLocId(), ".", h5group.getLocId(), link_name.c_str(),
H5L_SAME_LOC, H5L_SAME_LOC);
if (error)
throw std::runtime_error("Unable to create link " + link_name);
return openGroup(link_name, false);
}
// TODO implement some kind of roll-back in order to avoid half renamed links.
bool Group::renameAllLinks(const std::string &old_name, const std::string &new_name) {
bool renamed = false;
if (hasGroup(old_name)) {
std::vector<std::string> links;
Group group = openGroup(old_name, false);
size_t size = 128;
char *name_read = new char[size];
size_t size_read = H5Iget_name(group.h5group.getId(), name_read, size);
while (size_read > 0) {
if (size_read < size) {
H5Ldelete(h5group.getId(), name_read, H5L_SAME_LOC);
links.push_back(name_read);
} else {
delete[] name_read;
size = size * 2;
name_read = new char[size];
}
size_read = H5Iget_name(group.h5group.getId(), name_read, size);
}
renamed = links.size() > 0;
for (std::string curr_name: links) {
size_t pos = curr_name.find_last_of('/') + 1;
if (curr_name.substr(pos) == old_name) {
curr_name.replace(curr_name.begin() + pos, curr_name.end(), new_name.begin(), new_name.end());
}
herr_t error = H5Lcreate_hard(group.h5group.getLocId(), ".", h5group.getLocId(), curr_name.c_str(),
H5L_SAME_LOC, H5L_SAME_LOC);
renamed = renamed && (error >= 0);
}
}
return renamed;
}
// TODO implement some kind of roll-back in order to avoid half removed links.
bool Group::removeAllLinks(const std::string &name) {
bool removed = false;
if (hasGroup(name)) {
Group group = openGroup(name, false);
size_t size = 128;
char *name_read = new char[size];
size_t size_read = H5Iget_name(group.h5group.getId(), name_read, size);
while (size_read > 0) {
if (size_read < size) {
H5Ldelete(h5group.getId(), name_read, H5L_SAME_LOC);
} else {
delete[] name_read;
size = size * 2;
name_read = new char[size];
}
size_read = H5Iget_name(group.h5group.getId(), name_read, size);
}
delete[] name_read;
removed = true;
}
return removed;
}
void Group::readAttr(const H5::Attribute &attr, H5::DataType mem_type, const NDSize &size, void *data) {
attr.read(mem_type, data);
}
void Group::readAttr(const H5::Attribute &attr, H5::DataType mem_type, const NDSize &size, std::string *data) {
StringWriter writer(size, data);
attr.read(mem_type, *writer);
writer.finish();
H5::DataSet::vlenReclaim(*writer, mem_type, attr.getSpace()); //recycle space?
}
void Group::writeAttr(const H5::Attribute &attr, H5::DataType mem_type, const NDSize &size, const void *data) {
attr.write(mem_type, data);
}
void Group::writeAttr(const H5::Attribute &attr, H5::DataType mem_type, const NDSize &size, const std::string *data) {
StringReader reader(size, data);
attr.write(mem_type, *reader);
}
Group::~Group() {
h5group.close();
}
} // namespace hdf5
} // namespace nix
<|endoftext|> |
<commit_before><commit_msg>GlobalLanguageObject: Improvements.<commit_after><|endoftext|> |
<commit_before>#include <stdio.h>
#include "Q7Mem.h"
#include "Q7MemAPI.h"
#include "easySocket.h"
int check(Q7Mem *tx,uint64_t rxtime)
{
if( tx->head->packet.header.offset<rxtime )
{
printf("send data is out of date\n");
tx->head->packet.header.offset = (rxtime+1024L)&(-1024L);
}
tx->head->safe = rxtime+tx->head->overSend;
tx->head->packet.header.time = rxtime;
return 0;
}
int main(int argc, char*argv[] )
{
Q7Mem *tx_mem = attachQ7Mem( "tx_udp.d" );
tx_mem->head->maxSend = 16;
tx_mem->head->overSend = 1920*2*4; //2ms
dumpQ7Mem( tx_mem );
Q7Mem *rx_mem = attachQ7Mem( "rx_udp.d" );
dumpQ7Mem( rx_mem );
int port;
sscanf( argv[2],"%d",&port );
printf("port %d,sizeof int %ld\n",port, sizeof(int));
udpClient udp( argv[1], port );
udp.send( (char *)(&tx_mem->head->packet), sizeof(udp_package_t) );
int len = 0;
while( (len=udp.recv( (char*)(&rx_mem->head->packet), sizeof(udp_package_t) )) == sizeof(udp_package_t) )
{
uint64_t from = rx_mem->head->packet.header.offset;
uint64_t offset = rx_mem->getOff();
if( from != offset )
{
printf("recv discontinued _off:%lx, off:%lx",offset,from);
rx_mem->setOff(from);
}
void *p = (void *)rx_mem->_getBuf( from, sizeof(rx_mem->head->packet.data) );
memcpy( p, &(rx_mem->head->packet.data), sizeof(rx_mem->head->packet.data) );
int ck = check(tx_mem,rx_mem->head->packet.header.time);
for( int i=0;i<tx_mem->head->maxSend;i++ )
{
if(tx_mem->head->packet.header.offset<tx_mem->head->safe)
{
p = (void *)tx_mem->_getBuf( tx_mem->head->packet.header.offset, sizeof(tx_mem->head->packet.data) );
memcpy(&(tx_mem->head->packet.data),p,sizeof(tx_mem->head->packet.data));
tx_mem->head->packet.header.offset += sizeof(tx_mem->head->packet.data);
len = udp.send( (char *)(&tx_mem->head->packet), sizeof(udp_package_t) );
if( len!=sizeof(udp_package_t) )
{
printf("udp send failure,%d\n",len);
}
}
else
break;
}
}
printf("recv length error %d, exit\n",len);
}
<commit_msg>over 4ms<commit_after>#include <stdio.h>
#include "Q7Mem.h"
#include "Q7MemAPI.h"
#include "easySocket.h"
int check(Q7Mem *tx,uint64_t rxtime)
{
if( tx->head->packet.header.offset<rxtime )
{
printf("send data is out of date\n");
tx->head->packet.header.offset = (rxtime+1024L)&(-1024L);
}
tx->head->safe = rxtime+tx->head->overSend;
tx->head->packet.header.time = rxtime;
return 0;
}
int main(int argc, char*argv[] )
{
Q7Mem *tx_mem = attachQ7Mem( "tx_udp.d" );
tx_mem->head->maxSend = 16;
tx_mem->head->overSend = 1920*4*4; //4ms
dumpQ7Mem( tx_mem );
Q7Mem *rx_mem = attachQ7Mem( "rx_udp.d" );
dumpQ7Mem( rx_mem );
int port;
sscanf( argv[2],"%d",&port );
printf("port %d,sizeof int %ld\n",port, sizeof(int));
udpClient udp( argv[1], port );
udp.send( (char *)(&tx_mem->head->packet), sizeof(udp_package_t) );
int len = 0;
while( (len=udp.recv( (char*)(&rx_mem->head->packet), sizeof(udp_package_t) )) == sizeof(udp_package_t) )
{
uint64_t from = rx_mem->head->packet.header.offset;
uint64_t offset = rx_mem->getOff();
if( from != offset )
{
printf("recv discontinued _off:%lx, off:%lx",offset,from);
rx_mem->setOff(from);
}
void *p = (void *)rx_mem->_getBuf( from, sizeof(rx_mem->head->packet.data) );
memcpy( p, &(rx_mem->head->packet.data), sizeof(rx_mem->head->packet.data) );
int ck = check(tx_mem,rx_mem->head->packet.header.time);
for( int i=0;i<tx_mem->head->maxSend;i++ )
{
if(tx_mem->head->packet.header.offset<tx_mem->head->safe)
{
p = (void *)tx_mem->_getBuf( tx_mem->head->packet.header.offset, sizeof(tx_mem->head->packet.data) );
memcpy(&(tx_mem->head->packet.data),p,sizeof(tx_mem->head->packet.data));
tx_mem->head->packet.header.offset += sizeof(tx_mem->head->packet.data);
len = udp.send( (char *)(&tx_mem->head->packet), sizeof(udp_package_t) );
if( len!=sizeof(udp_package_t) )
{
printf("udp send failure,%d\n",len);
}
}
else
break;
}
}
printf("recv length error %d, exit\n",len);
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2008-2010 The QXmpp developers
*
* Author:
* Manjeet Dahiya
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include "vCardCache.h"
#include "QXmppClient.h"
#include "QXmppUtils.h"
#include "utils.h"
#include "QXmppVCardManager.h"
#include <QFile>
#include <QDir>
#include <QDomDocument>
#include <QTextStream>
#include <QCoreApplication>
#include <QDomDocument>
vCardCache::vCardCache(QXmppClient* client) : QObject(client),
m_client(client)
{
}
void vCardCache::vCardReceived(const QXmppVCardIq& vcard)
{
QString from = vcard.from();
if(from.isEmpty() && m_client)
{
from = m_client->configuration().jidBare();
m_selfFullName = vcard.fullName();
}
m_mapBareJidVcard[from] = vcard;
saveToCache(from);
emit vCardReadyToUse(from);
}
bool vCardCache::isVCardAvailable(const QString& bareJid)
{
return m_mapBareJidVcard.contains(bareJid);
}
void vCardCache::requestVCard(const QString& bareJid)
{
if(m_client)
m_client->vCardManager().requestVCard(bareJid);
}
//TODO not a good way to handle
QXmppVCardIq& vCardCache::getVCard(const QString& bareJid)
{
return m_mapBareJidVcard[bareJid];
}
void vCardCache::saveToCache(const QString& bareJid)
{
QDir dir;
if(!dir.exists(getSettingsDir(m_client->configuration().jidBare())))
dir.mkpath(getSettingsDir(m_client->configuration().jidBare()));
QDir dir2;
if(!dir2.exists(getSettingsDir(m_client->configuration().jidBare())+ "vCards/"))
dir2.mkpath(getSettingsDir(m_client->configuration().jidBare())+ "vCards/");
foreach(QString bareJid, m_mapBareJidVcard.keys())
{
QString fileVCard = getSettingsDir(m_client->configuration().jidBare()) + "vCards/" + bareJid + ".xml";
QFile file(fileVCard);
if(file.open(QIODevice::ReadWrite))
{
QXmlStreamWriter stream(&file);
stream.setAutoFormatting(true);
stream.setAutoFormattingIndent(2);
m_mapBareJidVcard[bareJid].toXml(&stream);
file.close();
}
}
}
void vCardCache::loadAllFromCache()
{
m_mapBareJidVcard.clear();
QDir dirVCards(getSettingsDir(m_client->configuration().jidBare())+ "vCards/");
if(dirVCards.exists())
{
QStringList list = dirVCards.entryList(QStringList("*.xml"));
foreach(QString fileName, list)
{
QFile file(getSettingsDir(m_client->configuration().jidBare())+ "vCards/" + fileName);
QString bareJid = fileName;
bareJid.chop(4);
if(file.open(QIODevice::ReadOnly))
{
QDomDocument doc;
if(doc.setContent(&file, true))
{
QXmppVCardIq vCardIq;
vCardIq.parse(doc.documentElement());
m_mapBareJidVcard[bareJid] = vCardIq;
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
}
}
}
}
}
QString vCardCache::getSelfFullName()
{
return m_selfFullName;
}
// this should return scaled image
QImage vCardCache::getAvatar(const QString& bareJid) const
{
if(m_mapBareJidVcard.contains(bareJid))
return getImageFromByteArray(m_mapBareJidVcard[bareJid].photo());
else
return QImage();
}
<commit_msg>bugfix: save only the given bareJid's vCard<commit_after>/*
* Copyright (C) 2008-2010 The QXmpp developers
*
* Author:
* Manjeet Dahiya
*
* Source:
* http://code.google.com/p/qxmpp
*
* This file is a part of QXmpp library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
#include "vCardCache.h"
#include "QXmppClient.h"
#include "QXmppUtils.h"
#include "utils.h"
#include "QXmppVCardManager.h"
#include <QFile>
#include <QDir>
#include <QDomDocument>
#include <QTextStream>
#include <QCoreApplication>
#include <QDomDocument>
vCardCache::vCardCache(QXmppClient* client) : QObject(client),
m_client(client)
{
}
void vCardCache::vCardReceived(const QXmppVCardIq& vcard)
{
QString from = vcard.from();
if(from.isEmpty() && m_client)
{
from = m_client->configuration().jidBare();
m_selfFullName = vcard.fullName();
}
m_mapBareJidVcard[from] = vcard;
saveToCache(from);
emit vCardReadyToUse(from);
}
bool vCardCache::isVCardAvailable(const QString& bareJid)
{
return m_mapBareJidVcard.contains(bareJid);
}
void vCardCache::requestVCard(const QString& bareJid)
{
if(m_client)
m_client->vCardManager().requestVCard(bareJid);
}
//TODO not a good way to handle
QXmppVCardIq& vCardCache::getVCard(const QString& bareJid)
{
return m_mapBareJidVcard[bareJid];
}
void vCardCache::saveToCache(const QString& bareJid)
{
QDir dir;
if(!dir.exists(getSettingsDir(m_client->configuration().jidBare())))
dir.mkpath(getSettingsDir(m_client->configuration().jidBare()));
QDir dir2;
if(!dir2.exists(getSettingsDir(m_client->configuration().jidBare())+ "vCards/"))
dir2.mkpath(getSettingsDir(m_client->configuration().jidBare())+ "vCards/");
if(m_mapBareJidVcard.contains(bareJid))
{
QString fileVCard = getSettingsDir(m_client->configuration().jidBare()) + "vCards/" + bareJid + ".xml";
QFile file(fileVCard);
if(file.open(QIODevice::ReadWrite))
{
QXmlStreamWriter stream(&file);
stream.setAutoFormatting(true);
stream.setAutoFormattingIndent(2);
m_mapBareJidVcard[bareJid].toXml(&stream);
file.close();
}
}
}
void vCardCache::loadAllFromCache()
{
m_mapBareJidVcard.clear();
QDir dirVCards(getSettingsDir(m_client->configuration().jidBare())+ "vCards/");
if(dirVCards.exists())
{
QStringList list = dirVCards.entryList(QStringList("*.xml"));
foreach(QString fileName, list)
{
QFile file(getSettingsDir(m_client->configuration().jidBare())+ "vCards/" + fileName);
QString bareJid = fileName;
bareJid.chop(4);
if(file.open(QIODevice::ReadOnly))
{
QDomDocument doc;
if(doc.setContent(&file, true))
{
QXmppVCardIq vCardIq;
vCardIq.parse(doc.documentElement());
m_mapBareJidVcard[bareJid] = vCardIq;
QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
}
}
}
}
}
QString vCardCache::getSelfFullName()
{
return m_selfFullName;
}
// this should return scaled image
QImage vCardCache::getAvatar(const QString& bareJid) const
{
if(m_mapBareJidVcard.contains(bareJid))
return getImageFromByteArray(m_mapBareJidVcard[bareJid].photo());
else
return QImage();
}
<|endoftext|> |
<commit_before>// Copyright © 2016 George Georgiev. All rights reserved.
//
#include "task/manager.h"
#include "task/sys/execute_command_task.h"
#include "tpool/task_callback.h"
#include "doim/manager.h"
#include "db/database.h"
#include "err/err_assert.h"
#include "err/err_cppformat.h"
#include "log/log.h"
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <stddef.h>
#include <stdio.h>
namespace task
{
tpool::TaskSPtr ExecuteCommandTask::createLogOnError(const doim::SysCommandSPtr& command,
const std::string& description)
{
auto task =
std::make_shared<task::ExecuteCommandTask>(command,
task::EExitExpectation::kNonZero,
description);
task = task::gManager->valid(task);
tpool::TaskCallback::Function onError = [](const tpool::TaskSPtr& task) -> ECode {
const auto& executeTask = std::static_pointer_cast<ExecuteCommandTask>(task);
std::string stdout;
EHTest(executeTask->stdout(stdout));
ELOG("{}", stdout);
EHEnd;
};
return std::make_shared<tpool::TaskCallback>(0, task, nullptr, onError);
}
ExecuteCommandTask::ExecuteCommandTask(const doim::SysCommandSPtr& command,
EExitExpectation exitExpectation,
const std::string& description)
: Base(command,
static_cast<typename std::underlying_type<EExitExpectation>::type>(
exitExpectation))
, mDescription(description)
{
ASSERT(doim::gManager->isUnique(command));
}
ECode ExecuteCommandTask::operator()()
{
const auto& cmd = command()->string() + " 2>&1";
auto pipe = popen(cmd.c_str(), "r");
if (!pipe)
EHBan(kUnable, cmd);
char buffer[1024];
std::string stdout;
while (!feof(pipe))
{
if (fgets(buffer, sizeof(buffer), pipe) != NULL)
stdout += buffer;
}
auto exit = pclose(pipe);
EHTest(db::gDatabase->put(stdoutDbKey(), stdout));
if (exitExpectation() == EExitExpectation::kNonZero && exit != 0)
EHBan(kUnable, cmd);
EHEnd;
}
ECode ExecuteCommandTask::stdout(std::string& stdout) const
{
ASSERT(finished());
EHTest(db::gDatabase->put(stdoutDbKey(), stdout));
EHEnd;
}
std::string ExecuteCommandTask::stdoutDbKey() const
{
return "stdout: " + command()->string();
}
std::string ExecuteCommandTask::description() const
{
if (!mDescription.empty())
return mDescription;
return "Execute command " + command()->string();
}
} // namespace task
<commit_msg>fix bug in reading the output<commit_after>// Copyright © 2016 George Georgiev. All rights reserved.
//
#include "task/manager.h"
#include "task/sys/execute_command_task.h"
#include "tpool/task_callback.h"
#include "doim/manager.h"
#include "db/database.h"
#include "err/err_assert.h"
#include "err/err_cppformat.h"
#include "log/log.h"
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <stddef.h>
#include <stdio.h>
namespace task
{
tpool::TaskSPtr ExecuteCommandTask::createLogOnError(const doim::SysCommandSPtr& command,
const std::string& description)
{
auto task =
std::make_shared<task::ExecuteCommandTask>(command,
task::EExitExpectation::kNonZero,
description);
task = task::gManager->valid(task);
tpool::TaskCallback::Function onError = [](const tpool::TaskSPtr& task) -> ECode {
const auto& executeTask = std::static_pointer_cast<ExecuteCommandTask>(task);
std::string stdout;
EHTest(executeTask->stdout(stdout));
ELOG("{}", stdout);
EHEnd;
};
return std::make_shared<tpool::TaskCallback>(0, task, nullptr, onError);
}
ExecuteCommandTask::ExecuteCommandTask(const doim::SysCommandSPtr& command,
EExitExpectation exitExpectation,
const std::string& description)
: Base(command,
static_cast<typename std::underlying_type<EExitExpectation>::type>(
exitExpectation))
, mDescription(description)
{
ASSERT(doim::gManager->isUnique(command));
}
ECode ExecuteCommandTask::operator()()
{
const auto& cmd = command()->string() + " 2>&1";
auto pipe = popen(cmd.c_str(), "r");
if (!pipe)
EHBan(kUnable, cmd);
char buffer[1024];
std::string stdout;
while (!feof(pipe))
{
if (fgets(buffer, sizeof(buffer), pipe) != NULL)
stdout += buffer;
}
auto exit = pclose(pipe);
EHTest(db::gDatabase->put(stdoutDbKey(), stdout));
if (exitExpectation() == EExitExpectation::kNonZero && exit != 0)
EHBan(kUnable, cmd);
EHEnd;
}
ECode ExecuteCommandTask::stdout(std::string& stdout) const
{
ASSERT(finished());
EHTest(db::gDatabase->get(stdoutDbKey(), stdout));
EHEnd;
}
std::string ExecuteCommandTask::stdoutDbKey() const
{
return "stdout: " + command()->string();
}
std::string ExecuteCommandTask::description() const
{
if (!mDescription.empty())
return mDescription;
return "Execute command " + command()->string();
}
} // namespace task
<|endoftext|> |
<commit_before>/**\file
* \brief "Hello World" HTTP Server
*
* \copyright
* Copyright (c) 2015, ef.gy Project Members
* \copyright
* 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:
* \copyright
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* \copyright
* 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.
*
* \see Project Documentation: http://ef.gy/documentation/libefgy
* \see Project Source Code: https://github.com/ef-gy/libefgy
*/
#define ASIO_DISABLE_THREADS
#include <ef.gy/http.h>
#include <iostream>
using namespace efgy;
using namespace asio;
using namespace std;
using asio::ip::tcp;
static bool hello (net::http::session<tcp, net::http::processor::base<tcp> > &session, std::smatch &) {
session.reply(200, "Hello World!");
return true;
}
int main(int argc, char *argv[]) {
try {
if (argc != 3) {
std::cerr << "Usage: http-hello <host> <port>\n";
return 1;
}
asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(argv[1], argv[2]);
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::resolver::iterator end;
if (endpoint_iterator != end) {
tcp::endpoint endpoint = *endpoint_iterator;
net::http::server<tcp> s(io_service, endpoint, cout);
s.processor.add("^/$", hello);
io_service.run();
}
}
catch (std::exception & e) {
std::cerr << "Exception: " << e.what() << "\n";
}
catch (std::system_error & e) {
std::cerr << "System Error: " << e.what() << "\n";
}
return 0;
}
<commit_msg>add docs for the processor; fix weirdness in the comparison operator<commit_after>/**\file
* \brief "Hello World" HTTP Server
*
* \copyright
* Copyright (c) 2015, ef.gy Project Members
* \copyright
* 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:
* \copyright
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* \copyright
* 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.
*
* \see Project Documentation: http://ef.gy/documentation/libefgy
* \see Project Source Code: https://github.com/ef-gy/libefgy
*/
#define ASIO_DISABLE_THREADS
#include <ef.gy/http.h>
#include <iostream>
using namespace efgy;
using namespace asio;
using namespace std;
using asio::ip::tcp;
static bool hello(typename net::http::server<tcp>::session &session,
std::smatch &) {
session.reply(200, "Hello World!");
return true;
}
int main(int argc, char *argv[]) {
try {
if (argc != 3) {
std::cerr << "Usage: http-hello <host> <port>\n";
return 1;
}
asio::io_service io_service;
tcp::resolver resolver(io_service);
tcp::resolver::query query(argv[1], argv[2]);
tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);
tcp::resolver::iterator end;
if (endpoint_iterator != end) {
tcp::endpoint endpoint = *endpoint_iterator;
net::http::server<tcp> s(io_service, endpoint, cout);
s.processor.add("^/$", hello);
io_service.run();
}
}
catch (std::exception & e) {
std::cerr << "Exception: " << e.what() << "\n";
}
catch (std::system_error & e) {
std::cerr << "System Error: " << e.what() << "\n";
}
return 0;
}
<|endoftext|> |
<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2004-2007 Torsten Rahn <tackat@kde.org>
// Copyright 2007 Inge Wallin <ingwa@kde.org>
//
#include "MarbleDirs.h"
#include "MarbleDebug.h"
#include <QDir>
#include <QFile>
#include <QString>
#include <QStringList>
#include <QApplication>
#include <stdlib.h>
#if QT_VERSION >= 0x050000
#include <QStandardPaths>
#else
#include <QDesktopServices>
#endif
#ifdef Q_OS_WIN
//for getting appdata path
//mingw-w64 Internet Explorer 5.01
#define _WIN32_IE 0x0501
#include <shlobj.h>
#endif
#ifdef Q_OS_MACX
//for getting app bundle path
#include <ApplicationServices/ApplicationServices.h>
#endif
#include <config-marble.h>
using namespace Marble;
namespace
{
QString runTimeMarbleDataPath = "";
QString runTimeMarblePluginPath = "";
}
MarbleDirs::MarbleDirs()
: d( 0 )
{
}
QString MarbleDirs::path( const QString& relativePath )
{
QString localpath = localPath() + '/' + relativePath; // local path
QString systempath = systemPath() + '/' + relativePath; // system path
QString fullpath = systempath;
if ( QFile::exists( localpath ) ) {
fullpath = localpath;
}
return QDir( fullpath ).canonicalPath();
}
QString MarbleDirs::pluginPath( const QString& relativePath )
{
QString localpath = pluginLocalPath() + QDir::separator() + relativePath; // local path
QString systempath = pluginSystemPath() + QDir::separator() + relativePath; // system path
QString fullpath = systempath;
if ( QFile::exists( localpath ) ) {
fullpath = localpath;
}
return QDir( fullpath ).canonicalPath();
}
QStringList MarbleDirs::entryList( const QString& relativePath, QDir::Filters filters )
{
QStringList filesLocal = QDir( MarbleDirs::localPath() + '/' + relativePath ).entryList(filters);
QStringList filesSystem = QDir( MarbleDirs::systemPath() + '/' + relativePath ).entryList(filters);
QStringList allFiles( filesLocal );
allFiles << filesSystem;
// remove duplicate entries
allFiles.sort();
for ( int i = 1; i < allFiles.size(); ++i ) {
if ( allFiles.at(i) == allFiles.at( i - 1 ) ) {
allFiles.removeAt(i);
--i;
}
}
return allFiles;
}
QStringList MarbleDirs::pluginEntryList( const QString& relativePath, QDir::Filters filters )
{
QStringList filesLocal = QDir( MarbleDirs::pluginLocalPath() + '/' + relativePath ).entryList(filters);
QStringList filesSystem = QDir( MarbleDirs::pluginSystemPath() + '/' + relativePath ).entryList(filters);
QStringList allFiles( filesLocal );
allFiles << filesSystem;
// remove duplicate entries
allFiles.sort();
for ( int i = 1; i < allFiles.size(); ++i ) {
if ( allFiles.at(i) == allFiles.at( i - 1 ) ) {
allFiles.removeAt(i);
--i;
}
}
return allFiles;
}
QString MarbleDirs::systemPath()
{
QString systempath;
#ifdef Q_OS_MACX
//
// On OSX lets try to find any file first in the bundle
// before branching out to home and sys dirs
//
CFURLRef myBundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
CFStringRef myMacPath = CFURLCopyFileSystemPath(myBundleRef, kCFURLPOSIXPathStyle);
const char *mypPathPtr = CFStringGetCStringPtr(myMacPath,CFStringGetSystemEncoding());
CFRelease(myBundleRef);
QString myPath(mypPathPtr);
CFRelease(myMacPath);
//do some magick so that we can still find data dir if
//marble was not built as a bundle
if (myPath.contains(".app")) //its a bundle!
{
systempath = myPath + "/Contents/Resources/data";
}
if ( QFile::exists( systempath ) ){
return systempath;
}
#endif // mac bundle
// Should this happen before the Mac bundle already?
if ( !runTimeMarbleDataPath.isEmpty() )
return runTimeMarbleDataPath;
#ifdef MARBLE_DATA_PATH
//MARBLE_DATA_PATH is a compiler define set by cmake
QString compileTimeMarbleDataPath(MARBLE_DATA_PATH);
if(QDir(compileTimeMarbleDataPath).exists())
return compileTimeMarbleDataPath;
#endif // MARBLE_DATA_PATH
return QDir( QCoreApplication::applicationDirPath()
#if defined(QTONLY)
+ QLatin1String( "/data" )
#else
+ QLatin1String( "/../share/apps/marble/data" )
#endif
).canonicalPath();
}
QString MarbleDirs::pluginSystemPath()
{
QString systempath;
#ifdef Q_OS_MACX
//
// On OSX lets try to find any file first in the bundle
// before branching out to home and sys dirs
//
CFURLRef myBundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
CFStringRef myMacPath = CFURLCopyFileSystemPath(myBundleRef, kCFURLPOSIXPathStyle);
const char *mypPathPtr = CFStringGetCStringPtr(myMacPath,CFStringGetSystemEncoding());
CFRelease(myBundleRef);
CFRelease(myMacPath);
QString myPath(mypPathPtr);
//do some magick so that we can still find data dir if
//marble was not built as a bundle
if (myPath.contains(".app")) //its a bundle!
{
systempath = myPath + "/Contents/Resources/plugins";
}
if ( QFile::exists( systempath ) ){
return systempath;
}
#endif // mac bundle
// Should this happen before the Mac bundle already?
if ( !runTimeMarblePluginPath.isEmpty() )
return runTimeMarblePluginPath;
#ifdef MARBLE_PLUGIN_PATH
//MARBLE_PLUGIN_PATH is a compiler define set by cmake
QString compileTimeMarblePluginPath(MARBLE_PLUGIN_PATH);
if(QDir(compileTimeMarblePluginPath).exists())
return compileTimeMarblePluginPath;
#endif // MARBLE_PLUGIN_PATH
return QDir( QCoreApplication::applicationDirPath()
#if defined(QTONLY)
+ QLatin1String( "/plugins" )
#else
+ QLatin1String( "/../lib/kde4/plugins/marble" )
#endif
).canonicalPath();
}
QString MarbleDirs::localPath()
{
#ifndef Q_OS_WIN
QString dataHome = getenv( "XDG_DATA_HOME" );
if( dataHome.isEmpty() )
dataHome = QDir::homePath() + "/.local/share";
return dataHome + "/marble"; // local path
#else
#if QT_VERSION >= 0x050000
return QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/.marble/data";
#else
return QDesktopServices::storageLocation(QDesktopServices::DataLocation) + "/.marble/data";
#endif
#endif
}
QStringList MarbleDirs::oldLocalPaths()
{
QStringList possibleOldPaths;
#ifndef Q_OS_WIN
QString oldDefault = QDir::homePath() + "/.marble/data";
possibleOldPaths.append( oldDefault );
QString xdgDefault = QDir::homePath() + "/.local/share/marble";
possibleOldPaths.append( xdgDefault );
QString xdg = getenv( "XDG_DATA_HOME" );
xdg += "/marble/";
possibleOldPaths.append( xdg );
#endif
#ifdef Q_OS_WIN
HWND hwnd = 0;
WCHAR *appdata_path = new WCHAR[MAX_PATH + 1];
SHGetSpecialFolderPathW(hwnd, appdata_path, CSIDL_APPDATA, 0);
QString appdata = QString::fromUtf16(reinterpret_cast<ushort*>(appdata_path));
delete[] appdata_path;
possibleOldPaths << QString(QDir::fromNativeSeparators(appdata) + "/.marble/data"); // local path
#endif
QString currentLocalPath = QDir( MarbleDirs::localPath() ).canonicalPath();
QStringList oldPaths;
foreach( const QString& possibleOldPath, possibleOldPaths ) {
if( !QDir().exists( possibleOldPath ) ) {
continue;
}
QString canonicalPossibleOldPath = QDir( possibleOldPath ).canonicalPath();
if( canonicalPossibleOldPath == currentLocalPath ) {
continue;
}
oldPaths.append( canonicalPossibleOldPath );
}
return oldPaths;
}
QString MarbleDirs::pluginLocalPath()
{
#ifndef Q_OS_WIN
return QString( QDir::homePath() + "/.marble/plugins" ); // local path
#else
#if QT_VERSION >= 0x050000
return QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/.marble/plugins";
#else
return QDesktopServices::storageLocation(QDesktopServices::DataLocation) + "/.marble/plugins";
#endif
#endif
}
QString MarbleDirs::marbleDataPath()
{
return runTimeMarbleDataPath;
}
QString MarbleDirs::marblePluginPath()
{
return runTimeMarblePluginPath;
}
void MarbleDirs::setMarbleDataPath( const QString& adaptedPath )
{
if ( !QDir::root().exists( adaptedPath ) )
{
qWarning() << QString( "Invalid MarbleDataPath \"%1\". Using \"%2\" instead." ).arg( adaptedPath ).arg( systemPath() );
return;
}
runTimeMarbleDataPath = adaptedPath;
}
void MarbleDirs::setMarblePluginPath( const QString& adaptedPath )
{
if ( !QDir::root().exists( adaptedPath ) )
{
qWarning() << QString( "Invalid MarblePluginPath \"%1\". Using \"%2\" instead." ).arg( adaptedPath ).arg( pluginSystemPath() );
return;
}
runTimeMarblePluginPath = adaptedPath;
}
void MarbleDirs::debug()
{
mDebug() << "=== MarbleDirs: ===";
mDebug() << "Local Path:" << localPath();
mDebug() << "Plugin Local Path:" << pluginLocalPath();
mDebug() << "";
mDebug() << "Marble Data Path (Run Time) :" << runTimeMarbleDataPath;
mDebug() << "Marble Data Path (Compile Time):" << QString(MARBLE_DATA_PATH);
mDebug() << "";
mDebug() << "Marble Plugin Path (Run Time) :" << runTimeMarblePluginPath;
mDebug() << "Marble Plugin Path (Compile Time):" << QString(MARBLE_PLUGIN_PATH);
mDebug() << "";
mDebug() << "System Path:" << systemPath();
mDebug() << "Plugin System Path:" << pluginSystemPath();
mDebug() << "===================";
}
<commit_msg>REVIEW: 124195 Setting the systempath for Android<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2004-2007 Torsten Rahn <tackat@kde.org>
// Copyright 2007 Inge Wallin <ingwa@kde.org>
//
#include "MarbleDirs.h"
#include "MarbleDebug.h"
#include <QDir>
#include <QFile>
#include <QString>
#include <QStringList>
#include <QApplication>
#include <stdlib.h>
#if QT_VERSION >= 0x050000
#include <QStandardPaths>
#else
#include <QDesktopServices>
#endif
#ifdef Q_OS_WIN
//for getting appdata path
//mingw-w64 Internet Explorer 5.01
#define _WIN32_IE 0x0501
#include <shlobj.h>
#endif
#ifdef Q_OS_MACX
//for getting app bundle path
#include <ApplicationServices/ApplicationServices.h>
#endif
#include <config-marble.h>
using namespace Marble;
namespace
{
QString runTimeMarbleDataPath = "";
QString runTimeMarblePluginPath = "";
}
MarbleDirs::MarbleDirs()
: d( 0 )
{
}
QString MarbleDirs::path( const QString& relativePath )
{
QString localpath = localPath() + '/' + relativePath; // local path
QString systempath = systemPath() + '/' + relativePath; // system path
QString fullpath = systempath;
if ( QFile::exists( localpath ) ) {
fullpath = localpath;
}
return QDir( fullpath ).canonicalPath();
}
QString MarbleDirs::pluginPath( const QString& relativePath )
{
QString localpath = pluginLocalPath() + QDir::separator() + relativePath; // local path
QString systempath = pluginSystemPath() + QDir::separator() + relativePath; // system path
QString fullpath = systempath;
if ( QFile::exists( localpath ) ) {
fullpath = localpath;
}
return QDir( fullpath ).canonicalPath();
}
QStringList MarbleDirs::entryList( const QString& relativePath, QDir::Filters filters )
{
QStringList filesLocal = QDir( MarbleDirs::localPath() + '/' + relativePath ).entryList(filters);
QStringList filesSystem = QDir( MarbleDirs::systemPath() + '/' + relativePath ).entryList(filters);
QStringList allFiles( filesLocal );
allFiles << filesSystem;
// remove duplicate entries
allFiles.sort();
for ( int i = 1; i < allFiles.size(); ++i ) {
if ( allFiles.at(i) == allFiles.at( i - 1 ) ) {
allFiles.removeAt(i);
--i;
}
}
return allFiles;
}
QStringList MarbleDirs::pluginEntryList( const QString& relativePath, QDir::Filters filters )
{
QStringList filesLocal = QDir( MarbleDirs::pluginLocalPath() + '/' + relativePath ).entryList(filters);
QStringList filesSystem = QDir( MarbleDirs::pluginSystemPath() + '/' + relativePath ).entryList(filters);
QStringList allFiles( filesLocal );
allFiles << filesSystem;
// remove duplicate entries
allFiles.sort();
for ( int i = 1; i < allFiles.size(); ++i ) {
if ( allFiles.at(i) == allFiles.at( i - 1 ) ) {
allFiles.removeAt(i);
--i;
}
}
return allFiles;
}
QString MarbleDirs::systemPath()
{
QString systempath;
#ifdef Q_OS_MACX
//
// On OSX lets try to find any file first in the bundle
// before branching out to home and sys dirs
//
CFURLRef myBundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
CFStringRef myMacPath = CFURLCopyFileSystemPath(myBundleRef, kCFURLPOSIXPathStyle);
const char *mypPathPtr = CFStringGetCStringPtr(myMacPath,CFStringGetSystemEncoding());
CFRelease(myBundleRef);
QString myPath(mypPathPtr);
CFRelease(myMacPath);
//do some magick so that we can still find data dir if
//marble was not built as a bundle
if (myPath.contains(".app")) //its a bundle!
{
systempath = myPath + "/Contents/Resources/data";
}
if ( QFile::exists( systempath ) ){
return systempath;
}
#endif // mac bundle
#ifdef ANDROID
systempath = "assets:/data";
return systempath;
#endif
// Should this happen before the Mac bundle already?
if ( !runTimeMarbleDataPath.isEmpty() )
return runTimeMarbleDataPath;
#ifdef MARBLE_DATA_PATH
//MARBLE_DATA_PATH is a compiler define set by cmake
QString compileTimeMarbleDataPath(MARBLE_DATA_PATH);
if(QDir(compileTimeMarbleDataPath).exists())
return compileTimeMarbleDataPath;
#endif // MARBLE_DATA_PATH
return QDir( QCoreApplication::applicationDirPath()
#if defined(QTONLY)
+ QLatin1String( "/data" )
#else
+ QLatin1String( "/../share/apps/marble/data" )
#endif
).canonicalPath();
}
QString MarbleDirs::pluginSystemPath()
{
QString systempath;
#ifdef Q_OS_MACX
//
// On OSX lets try to find any file first in the bundle
// before branching out to home and sys dirs
//
CFURLRef myBundleRef = CFBundleCopyBundleURL(CFBundleGetMainBundle());
CFStringRef myMacPath = CFURLCopyFileSystemPath(myBundleRef, kCFURLPOSIXPathStyle);
const char *mypPathPtr = CFStringGetCStringPtr(myMacPath,CFStringGetSystemEncoding());
CFRelease(myBundleRef);
CFRelease(myMacPath);
QString myPath(mypPathPtr);
//do some magick so that we can still find data dir if
//marble was not built as a bundle
if (myPath.contains(".app")) //its a bundle!
{
systempath = myPath + "/Contents/Resources/plugins";
}
if ( QFile::exists( systempath ) ){
return systempath;
}
#endif // mac bundle
// Should this happen before the Mac bundle already?
if ( !runTimeMarblePluginPath.isEmpty() )
return runTimeMarblePluginPath;
#ifdef MARBLE_PLUGIN_PATH
//MARBLE_PLUGIN_PATH is a compiler define set by cmake
QString compileTimeMarblePluginPath(MARBLE_PLUGIN_PATH);
if(QDir(compileTimeMarblePluginPath).exists())
return compileTimeMarblePluginPath;
#endif // MARBLE_PLUGIN_PATH
return QDir( QCoreApplication::applicationDirPath()
#if defined(QTONLY)
+ QLatin1String( "/plugins" )
#else
+ QLatin1String( "/../lib/kde4/plugins/marble" )
#endif
).canonicalPath();
}
QString MarbleDirs::localPath()
{
#ifndef Q_OS_WIN
QString dataHome = getenv( "XDG_DATA_HOME" );
if( dataHome.isEmpty() )
dataHome = QDir::homePath() + "/.local/share";
return dataHome + "/marble"; // local path
#else
#if QT_VERSION >= 0x050000
return QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/.marble/data";
#else
return QDesktopServices::storageLocation(QDesktopServices::DataLocation) + "/.marble/data";
#endif
#endif
}
QStringList MarbleDirs::oldLocalPaths()
{
QStringList possibleOldPaths;
#ifndef Q_OS_WIN
QString oldDefault = QDir::homePath() + "/.marble/data";
possibleOldPaths.append( oldDefault );
QString xdgDefault = QDir::homePath() + "/.local/share/marble";
possibleOldPaths.append( xdgDefault );
QString xdg = getenv( "XDG_DATA_HOME" );
xdg += "/marble/";
possibleOldPaths.append( xdg );
#endif
#ifdef Q_OS_WIN
HWND hwnd = 0;
WCHAR *appdata_path = new WCHAR[MAX_PATH + 1];
SHGetSpecialFolderPathW(hwnd, appdata_path, CSIDL_APPDATA, 0);
QString appdata = QString::fromUtf16(reinterpret_cast<ushort*>(appdata_path));
delete[] appdata_path;
possibleOldPaths << QString(QDir::fromNativeSeparators(appdata) + "/.marble/data"); // local path
#endif
QString currentLocalPath = QDir( MarbleDirs::localPath() ).canonicalPath();
QStringList oldPaths;
foreach( const QString& possibleOldPath, possibleOldPaths ) {
if( !QDir().exists( possibleOldPath ) ) {
continue;
}
QString canonicalPossibleOldPath = QDir( possibleOldPath ).canonicalPath();
if( canonicalPossibleOldPath == currentLocalPath ) {
continue;
}
oldPaths.append( canonicalPossibleOldPath );
}
return oldPaths;
}
QString MarbleDirs::pluginLocalPath()
{
#ifndef Q_OS_WIN
return QString( QDir::homePath() + "/.marble/plugins" ); // local path
#else
#if QT_VERSION >= 0x050000
return QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/.marble/plugins";
#else
return QDesktopServices::storageLocation(QDesktopServices::DataLocation) + "/.marble/plugins";
#endif
#endif
}
QString MarbleDirs::marbleDataPath()
{
return runTimeMarbleDataPath;
}
QString MarbleDirs::marblePluginPath()
{
return runTimeMarblePluginPath;
}
void MarbleDirs::setMarbleDataPath( const QString& adaptedPath )
{
if ( !QDir::root().exists( adaptedPath ) )
{
qWarning() << QString( "Invalid MarbleDataPath \"%1\". Using \"%2\" instead." ).arg( adaptedPath ).arg( systemPath() );
return;
}
runTimeMarbleDataPath = adaptedPath;
}
void MarbleDirs::setMarblePluginPath( const QString& adaptedPath )
{
if ( !QDir::root().exists( adaptedPath ) )
{
qWarning() << QString( "Invalid MarblePluginPath \"%1\". Using \"%2\" instead." ).arg( adaptedPath ).arg( pluginSystemPath() );
return;
}
runTimeMarblePluginPath = adaptedPath;
}
void MarbleDirs::debug()
{
mDebug() << "=== MarbleDirs: ===";
mDebug() << "Local Path:" << localPath();
mDebug() << "Plugin Local Path:" << pluginLocalPath();
mDebug() << "";
mDebug() << "Marble Data Path (Run Time) :" << runTimeMarbleDataPath;
mDebug() << "Marble Data Path (Compile Time):" << QString(MARBLE_DATA_PATH);
mDebug() << "";
mDebug() << "Marble Plugin Path (Run Time) :" << runTimeMarblePluginPath;
mDebug() << "Marble Plugin Path (Compile Time):" << QString(MARBLE_PLUGIN_PATH);
mDebug() << "";
mDebug() << "System Path:" << systemPath();
mDebug() << "Plugin System Path:" << pluginSystemPath();
mDebug() << "===================";
}
<|endoftext|> |
<commit_before>/**********************************************************************************
Infomap software package for multi-level network clustering
Copyright (c) 2013, 2014 Daniel Edler, Martin Rosvall
For more information, see <http://www.mapequation.org>
This file is part of Infomap software package.
Infomap software package 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.
Infomap software package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Infomap software package. If not, see <http://www.gnu.org/licenses/>.
**********************************************************************************/
#include "version.h"
#ifdef NS_INFOMAP
namespace infomap
{
#endif
const char* INFOMAP_VERSION = "0.18.2";
#ifdef NS_INFOMAP
}
#endif
<commit_msg>Bumped version<commit_after>/**********************************************************************************
Infomap software package for multi-level network clustering
Copyright (c) 2013, 2014 Daniel Edler, Martin Rosvall
For more information, see <http://www.mapequation.org>
This file is part of Infomap software package.
Infomap software package 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.
Infomap software package is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Infomap software package. If not, see <http://www.gnu.org/licenses/>.
**********************************************************************************/
#include "version.h"
#ifdef NS_INFOMAP
namespace infomap
{
#endif
const char* INFOMAP_VERSION = "0.18.3";
#ifdef NS_INFOMAP
}
#endif
<|endoftext|> |
<commit_before>#include "Exception.hpp"
#include "MeshBoolean.hpp"
#include "libslic3r/TriangleMesh.hpp"
#include "boost/log/trivial.hpp"
#undef PI
// Include igl first. It defines "L" macro which then clashes with our localization
#include <igl/copyleft/cgal/mesh_boolean.h>
#undef L
// CGAL headers
#include <CGAL/Polygon_mesh_processing/corefinement.h>
#include <CGAL/Exact_integer.h>
#include <CGAL/Surface_mesh.h>
#include <CGAL/Polygon_mesh_processing/orient_polygon_soup.h>
#include <CGAL/Polygon_mesh_processing/repair.h>
#include <CGAL/Polygon_mesh_processing/remesh.h>
#include <CGAL/Polygon_mesh_processing/polygon_soup_to_polygon_mesh.h>
#include <CGAL/Polygon_mesh_processing/orientation.h>
#include <CGAL/Cartesian_converter.h>
namespace Slic3r {
namespace MeshBoolean {
using MapMatrixXfUnaligned = Eigen::Map<const Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor | Eigen::DontAlign>>;
using MapMatrixXiUnaligned = Eigen::Map<const Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor | Eigen::DontAlign>>;
TriangleMesh eigen_to_triangle_mesh(const EigenMesh &emesh)
{
auto &VC = emesh.first; auto &FC = emesh.second;
Pointf3s points(size_t(VC.rows()));
std::vector<Vec3i> facets(size_t(FC.rows()));
for (Eigen::Index i = 0; i < VC.rows(); ++i)
points[size_t(i)] = VC.row(i);
for (Eigen::Index i = 0; i < FC.rows(); ++i)
facets[size_t(i)] = FC.row(i);
TriangleMesh out{points, facets};
out.require_shared_vertices();
return out;
}
EigenMesh triangle_mesh_to_eigen(const TriangleMesh &mesh)
{
EigenMesh emesh;
emesh.first = MapMatrixXfUnaligned(mesh.its.vertices.front().data(),
Eigen::Index(mesh.its.vertices.size()),
3).cast<double>();
emesh.second = MapMatrixXiUnaligned(mesh.its.indices.front().data(),
Eigen::Index(mesh.its.indices.size()),
3);
return emesh;
}
void minus(EigenMesh &A, const EigenMesh &B)
{
auto &[VA, FA] = A;
auto &[VB, FB] = B;
Eigen::MatrixXd VC;
Eigen::MatrixXi FC;
igl::MeshBooleanType boolean_type(igl::MESH_BOOLEAN_TYPE_MINUS);
igl::copyleft::cgal::mesh_boolean(VA, FA, VB, FB, boolean_type, VC, FC);
VA = std::move(VC); FA = std::move(FC);
}
void minus(TriangleMesh& A, const TriangleMesh& B)
{
EigenMesh eA = triangle_mesh_to_eigen(A);
minus(eA, triangle_mesh_to_eigen(B));
A = eigen_to_triangle_mesh(eA);
}
void self_union(EigenMesh &A)
{
EigenMesh result;
auto &[V, F] = A;
auto &[VC, FC] = result;
igl::MeshBooleanType boolean_type(igl::MESH_BOOLEAN_TYPE_UNION);
igl::copyleft::cgal::mesh_boolean(V, F, Eigen::MatrixXd(), Eigen::MatrixXi(), boolean_type, VC, FC);
A = std::move(result);
}
void self_union(TriangleMesh& mesh)
{
auto eM = triangle_mesh_to_eigen(mesh);
self_union(eM);
mesh = eigen_to_triangle_mesh(eM);
}
namespace cgal {
namespace CGALProc = CGAL::Polygon_mesh_processing;
namespace CGALParams = CGAL::Polygon_mesh_processing::parameters;
using EpecKernel = CGAL::Exact_predicates_exact_constructions_kernel;
using EpicKernel = CGAL::Exact_predicates_inexact_constructions_kernel;
using _EpicMesh = CGAL::Surface_mesh<EpicKernel::Point_3>;
using _EpecMesh = CGAL::Surface_mesh<EpecKernel::Point_3>;
struct CGALMesh { _EpicMesh m; };
// /////////////////////////////////////////////////////////////////////////////
// Converions from and to CGAL mesh
// /////////////////////////////////////////////////////////////////////////////
template<class _Mesh>
void triangle_mesh_to_cgal(const std::vector<stl_vertex> & V,
const std::vector<stl_triangle_vertex_indices> &F,
_Mesh &out)
{
if (F.empty()) return;
for (auto &v : V)
out.add_vertex(typename _Mesh::Point{v.x(), v.y(), v.z()});
using VI = typename _Mesh::Vertex_index;
for (auto &f : F)
out.add_face(VI(f(0)), VI(f(1)), VI(f(2)));
}
inline Vec3d to_vec3d(const _EpicMesh::Point &v)
{
return {v.x(), v.y(), v.z()};
}
inline Vec3d to_vec3d(const _EpecMesh::Point &v)
{
CGAL::Cartesian_converter<EpecKernel, EpicKernel> cvt;
auto iv = cvt(v);
return {iv.x(), iv.y(), iv.z()};
}
template<class _Mesh> TriangleMesh cgal_to_triangle_mesh(const _Mesh &cgalmesh)
{
Pointf3s points;
std::vector<Vec3i> facets;
points.reserve(cgalmesh.num_vertices());
facets.reserve(cgalmesh.num_faces());
for (auto &vi : cgalmesh.vertices()) {
auto &v = cgalmesh.point(vi); // Don't ask...
points.emplace_back(to_vec3d(v));
}
for (auto &face : cgalmesh.faces()) {
auto vtc = cgalmesh.vertices_around_face(cgalmesh.halfedge(face));
int i = 0;
Vec3i facet;
for (const auto &v : vtc) {
if (i > 2) { i = 0; break; }
facet(i++) = v;
}
if (i == 3) {
facets.emplace_back(facet);
} else {
BOOST_LOG_TRIVIAL(error) << "CGAL face is not a triangle.";
}
}
TriangleMesh out{points, facets};
out.repair();
return out;
}
std::unique_ptr<CGALMesh, CGALMeshDeleter>
triangle_mesh_to_cgal(const std::vector<stl_vertex> &V,
const std::vector<stl_triangle_vertex_indices> &F)
{
std::unique_ptr<CGALMesh, CGALMeshDeleter> out(new CGALMesh{});
triangle_mesh_to_cgal(V, F, out->m);
return out;
}
TriangleMesh cgal_to_triangle_mesh(const CGALMesh &cgalmesh)
{
return cgal_to_triangle_mesh(cgalmesh.m);
}
// /////////////////////////////////////////////////////////////////////////////
// Boolean operations for CGAL meshes
// /////////////////////////////////////////////////////////////////////////////
static bool _cgal_diff(CGALMesh &A, CGALMesh &B, CGALMesh &R)
{
const auto &p = CGALParams::throw_on_self_intersection(true);
return CGALProc::corefine_and_compute_difference(A.m, B.m, R.m, p, p);
}
static bool _cgal_union(CGALMesh &A, CGALMesh &B, CGALMesh &R)
{
const auto &p = CGALParams::throw_on_self_intersection(true);
return CGALProc::corefine_and_compute_union(A.m, B.m, R.m, p, p);
}
static bool _cgal_intersection(CGALMesh &A, CGALMesh &B, CGALMesh &R)
{
const auto &p = CGALParams::throw_on_self_intersection(true);
return CGALProc::corefine_and_compute_intersection(A.m, B.m, R.m, p, p);
}
template<class Op> void _cgal_do(Op &&op, CGALMesh &A, CGALMesh &B)
{
bool success = false;
try {
CGALMesh result;
success = op(A, B, result);
A = std::move(result); // In-place operation does not work
} catch (...) {
success = false;
}
if (! success)
throw Slic3r::RuntimeError("CGAL mesh boolean operation failed.");
}
void minus(CGALMesh &A, CGALMesh &B) { _cgal_do(_cgal_diff, A, B); }
void plus(CGALMesh &A, CGALMesh &B) { _cgal_do(_cgal_union, A, B); }
void intersect(CGALMesh &A, CGALMesh &B) { _cgal_do(_cgal_intersection, A, B); }
bool does_self_intersect(const CGALMesh &mesh) { return CGALProc::does_self_intersect(mesh.m); }
// /////////////////////////////////////////////////////////////////////////////
// Now the public functions for TriangleMesh input:
// /////////////////////////////////////////////////////////////////////////////
template<class Op> void _mesh_boolean_do(Op &&op, TriangleMesh &A, const TriangleMesh &B)
{
CGALMesh meshA;
CGALMesh meshB;
triangle_mesh_to_cgal(A.its.vertices, A.its.indices, meshA.m);
triangle_mesh_to_cgal(B.its.vertices, B.its.indices, meshB.m);
_cgal_do(op, meshA, meshB);
A = cgal_to_triangle_mesh(meshA.m);
}
void minus(TriangleMesh &A, const TriangleMesh &B)
{
_mesh_boolean_do(_cgal_diff, A, B);
}
void plus(TriangleMesh &A, const TriangleMesh &B)
{
_mesh_boolean_do(_cgal_union, A, B);
}
void intersect(TriangleMesh &A, const TriangleMesh &B)
{
_mesh_boolean_do(_cgal_intersection, A, B);
}
bool does_self_intersect(const TriangleMesh &mesh)
{
CGALMesh cgalm;
triangle_mesh_to_cgal(mesh.its.vertices, mesh.its.indices, cgalm.m);
return CGALProc::does_self_intersect(cgalm.m);
}
void CGALMeshDeleter::operator()(CGALMesh *ptr) { delete ptr; }
} // namespace cgal
} // namespace MeshBoolean
} // namespace Slic3r
<commit_msg>Fix mac warnings<commit_after>#include "Exception.hpp"
#include "MeshBoolean.hpp"
#include "libslic3r/TriangleMesh.hpp"
#include "boost/log/trivial.hpp"
#undef PI
// Include igl first. It defines "L" macro which then clashes with our localization
#include <igl/copyleft/cgal/mesh_boolean.h>
#undef L
// CGAL headers
#include <CGAL/Polygon_mesh_processing/corefinement.h>
#include <CGAL/Exact_integer.h>
#include <CGAL/Surface_mesh.h>
#include <CGAL/Polygon_mesh_processing/orient_polygon_soup.h>
#include <CGAL/Polygon_mesh_processing/repair.h>
#include <CGAL/Polygon_mesh_processing/remesh.h>
#include <CGAL/Polygon_mesh_processing/polygon_soup_to_polygon_mesh.h>
#include <CGAL/Polygon_mesh_processing/orientation.h>
#include <CGAL/Cartesian_converter.h>
namespace Slic3r {
namespace MeshBoolean {
using MapMatrixXfUnaligned = Eigen::Map<const Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor | Eigen::DontAlign>>;
using MapMatrixXiUnaligned = Eigen::Map<const Eigen::Matrix<int, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor | Eigen::DontAlign>>;
TriangleMesh eigen_to_triangle_mesh(const EigenMesh &emesh)
{
auto &VC = emesh.first; auto &FC = emesh.second;
Pointf3s points(size_t(VC.rows()));
std::vector<Vec3i> facets(size_t(FC.rows()));
for (Eigen::Index i = 0; i < VC.rows(); ++i)
points[size_t(i)] = VC.row(i);
for (Eigen::Index i = 0; i < FC.rows(); ++i)
facets[size_t(i)] = FC.row(i);
TriangleMesh out{points, facets};
out.require_shared_vertices();
return out;
}
EigenMesh triangle_mesh_to_eigen(const TriangleMesh &mesh)
{
EigenMesh emesh;
emesh.first = MapMatrixXfUnaligned(mesh.its.vertices.front().data(),
Eigen::Index(mesh.its.vertices.size()),
3).cast<double>();
emesh.second = MapMatrixXiUnaligned(mesh.its.indices.front().data(),
Eigen::Index(mesh.its.indices.size()),
3);
return emesh;
}
void minus(EigenMesh &A, const EigenMesh &B)
{
auto &[VA, FA] = A;
auto &[VB, FB] = B;
Eigen::MatrixXd VC;
Eigen::MatrixXi FC;
igl::MeshBooleanType boolean_type(igl::MESH_BOOLEAN_TYPE_MINUS);
igl::copyleft::cgal::mesh_boolean(VA, FA, VB, FB, boolean_type, VC, FC);
VA = std::move(VC); FA = std::move(FC);
}
void minus(TriangleMesh& A, const TriangleMesh& B)
{
EigenMesh eA = triangle_mesh_to_eigen(A);
minus(eA, triangle_mesh_to_eigen(B));
A = eigen_to_triangle_mesh(eA);
}
void self_union(EigenMesh &A)
{
EigenMesh result;
auto &[V, F] = A;
auto &[VC, FC] = result;
igl::MeshBooleanType boolean_type(igl::MESH_BOOLEAN_TYPE_UNION);
igl::copyleft::cgal::mesh_boolean(V, F, Eigen::MatrixXd(), Eigen::MatrixXi(), boolean_type, VC, FC);
A = std::move(result);
}
void self_union(TriangleMesh& mesh)
{
auto eM = triangle_mesh_to_eigen(mesh);
self_union(eM);
mesh = eigen_to_triangle_mesh(eM);
}
namespace cgal {
namespace CGALProc = CGAL::Polygon_mesh_processing;
namespace CGALParams = CGAL::Polygon_mesh_processing::parameters;
using EpecKernel = CGAL::Exact_predicates_exact_constructions_kernel;
using EpicKernel = CGAL::Exact_predicates_inexact_constructions_kernel;
using _EpicMesh = CGAL::Surface_mesh<EpicKernel::Point_3>;
using _EpecMesh = CGAL::Surface_mesh<EpecKernel::Point_3>;
struct CGALMesh { _EpicMesh m; };
// /////////////////////////////////////////////////////////////////////////////
// Converions from and to CGAL mesh
// /////////////////////////////////////////////////////////////////////////////
template<class _Mesh>
void triangle_mesh_to_cgal(const std::vector<stl_vertex> & V,
const std::vector<stl_triangle_vertex_indices> &F,
_Mesh &out)
{
if (F.empty()) return;
for (auto &v : V)
out.add_vertex(typename _Mesh::Point{v.x(), v.y(), v.z()});
using VI = typename _Mesh::Vertex_index;
for (auto &f : F)
out.add_face(VI(f(0)), VI(f(1)), VI(f(2)));
}
inline Vec3d to_vec3d(const _EpicMesh::Point &v)
{
return {v.x(), v.y(), v.z()};
}
inline Vec3d to_vec3d(const _EpecMesh::Point &v)
{
CGAL::Cartesian_converter<EpecKernel, EpicKernel> cvt;
auto iv = cvt(v);
return {iv.x(), iv.y(), iv.z()};
}
template<class _Mesh> TriangleMesh cgal_to_triangle_mesh(const _Mesh &cgalmesh)
{
Pointf3s points;
std::vector<Vec3i> facets;
points.reserve(cgalmesh.num_vertices());
facets.reserve(cgalmesh.num_faces());
for (auto &vi : cgalmesh.vertices()) {
auto &v = cgalmesh.point(vi); // Don't ask...
points.emplace_back(to_vec3d(v));
}
for (auto &face : cgalmesh.faces()) {
auto vtc = cgalmesh.vertices_around_face(cgalmesh.halfedge(face));
int i = 0;
Vec3i facet;
for (auto v : vtc) {
if (i > 2) { i = 0; break; }
facet(i++) = v;
}
if (i == 3) {
facets.emplace_back(facet);
} else {
BOOST_LOG_TRIVIAL(error) << "CGAL face is not a triangle.";
}
}
TriangleMesh out{points, facets};
out.repair();
return out;
}
std::unique_ptr<CGALMesh, CGALMeshDeleter>
triangle_mesh_to_cgal(const std::vector<stl_vertex> &V,
const std::vector<stl_triangle_vertex_indices> &F)
{
std::unique_ptr<CGALMesh, CGALMeshDeleter> out(new CGALMesh{});
triangle_mesh_to_cgal(V, F, out->m);
return out;
}
TriangleMesh cgal_to_triangle_mesh(const CGALMesh &cgalmesh)
{
return cgal_to_triangle_mesh(cgalmesh.m);
}
// /////////////////////////////////////////////////////////////////////////////
// Boolean operations for CGAL meshes
// /////////////////////////////////////////////////////////////////////////////
static bool _cgal_diff(CGALMesh &A, CGALMesh &B, CGALMesh &R)
{
const auto &p = CGALParams::throw_on_self_intersection(true);
return CGALProc::corefine_and_compute_difference(A.m, B.m, R.m, p, p);
}
static bool _cgal_union(CGALMesh &A, CGALMesh &B, CGALMesh &R)
{
const auto &p = CGALParams::throw_on_self_intersection(true);
return CGALProc::corefine_and_compute_union(A.m, B.m, R.m, p, p);
}
static bool _cgal_intersection(CGALMesh &A, CGALMesh &B, CGALMesh &R)
{
const auto &p = CGALParams::throw_on_self_intersection(true);
return CGALProc::corefine_and_compute_intersection(A.m, B.m, R.m, p, p);
}
template<class Op> void _cgal_do(Op &&op, CGALMesh &A, CGALMesh &B)
{
bool success = false;
try {
CGALMesh result;
success = op(A, B, result);
A = std::move(result); // In-place operation does not work
} catch (...) {
success = false;
}
if (! success)
throw Slic3r::RuntimeError("CGAL mesh boolean operation failed.");
}
void minus(CGALMesh &A, CGALMesh &B) { _cgal_do(_cgal_diff, A, B); }
void plus(CGALMesh &A, CGALMesh &B) { _cgal_do(_cgal_union, A, B); }
void intersect(CGALMesh &A, CGALMesh &B) { _cgal_do(_cgal_intersection, A, B); }
bool does_self_intersect(const CGALMesh &mesh) { return CGALProc::does_self_intersect(mesh.m); }
// /////////////////////////////////////////////////////////////////////////////
// Now the public functions for TriangleMesh input:
// /////////////////////////////////////////////////////////////////////////////
template<class Op> void _mesh_boolean_do(Op &&op, TriangleMesh &A, const TriangleMesh &B)
{
CGALMesh meshA;
CGALMesh meshB;
triangle_mesh_to_cgal(A.its.vertices, A.its.indices, meshA.m);
triangle_mesh_to_cgal(B.its.vertices, B.its.indices, meshB.m);
_cgal_do(op, meshA, meshB);
A = cgal_to_triangle_mesh(meshA.m);
}
void minus(TriangleMesh &A, const TriangleMesh &B)
{
_mesh_boolean_do(_cgal_diff, A, B);
}
void plus(TriangleMesh &A, const TriangleMesh &B)
{
_mesh_boolean_do(_cgal_union, A, B);
}
void intersect(TriangleMesh &A, const TriangleMesh &B)
{
_mesh_boolean_do(_cgal_intersection, A, B);
}
bool does_self_intersect(const TriangleMesh &mesh)
{
CGALMesh cgalm;
triangle_mesh_to_cgal(mesh.its.vertices, mesh.its.indices, cgalm.m);
return CGALProc::does_self_intersect(cgalm.m);
}
void CGALMeshDeleter::operator()(CGALMesh *ptr) { delete ptr; }
} // namespace cgal
} // namespace MeshBoolean
} // namespace Slic3r
<|endoftext|> |
<commit_before>/*
*
* Copyright (c) 2020 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <core/CHIPEncoding.h>
#include <core/CHIPSafeCasts.h>
#include <platform/internal/DeviceNetworkInfo.h>
#include <protocols/CHIPProtocols.h>
#include <support/CodeUtils.h>
#include <support/ErrorStr.h>
#include <support/SafeInt.h>
#include <transport/NetworkProvisioning.h>
#if CONFIG_DEVICE_LAYER
#include <platform/CHIPDeviceLayer.h>
#endif
namespace chip {
void NetworkProvisioning::Init(NetworkProvisioningDelegate * delegate, DeviceNetworkProvisioningDelegate * deviceDelegate)
{
if (deviceDelegate != nullptr)
{
mDeviceDelegate = deviceDelegate;
}
}
NetworkProvisioning::~NetworkProvisioning()
{
if (mDeviceDelegate != nullptr)
{
#if CONFIG_DEVICE_LAYER
DeviceLayer::PlatformMgr().RemoveEventHandler(ConnectivityHandler, reinterpret_cast<intptr_t>(this));
#endif
}
}
CHIP_ERROR NetworkProvisioning::HandleNetworkProvisioningMessage(uint8_t msgType, System::PacketBuffer * msgBuf)
{
CHIP_ERROR err = CHIP_NO_ERROR;
switch (msgType)
{
case NetworkProvisioning::MsgTypes::kWiFiAssociationRequest: {
char SSID[chip::DeviceLayer::Internal::kMaxWiFiSSIDLength];
char passwd[chip::DeviceLayer::Internal::kMaxWiFiKeyLength];
BufBound bbufSSID(Uint8::from_char(SSID), chip::DeviceLayer::Internal::kMaxWiFiSSIDLength);
BufBound bbufPW(Uint8::from_char(passwd), chip::DeviceLayer::Internal::kMaxWiFiKeyLength);
const uint8_t * buffer = msgBuf->Start();
size_t len = msgBuf->DataLength();
size_t offset = 0;
ChipLogProgress(NetworkProvisioning, "Received kWiFiAssociationRequest. DeviceDelegate %p", mDeviceDelegate);
VerifyOrExit(mDeviceDelegate != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = DecodeString(&buffer[offset], len - offset, bbufSSID, offset);
// TODO: Check for the error once network provisioning is moved to delegate calls
err = DecodeString(&buffer[offset], len - offset, bbufPW, offset);
// TODO: Check for the error once network provisioning is moved to delegate calls
#if CONFIG_DEVICE_LAYER
// Start listening for Internet connectivity changes to be able to respond with assigned IP Address
DeviceLayer::PlatformMgr().AddEventHandler(ConnectivityHandler, reinterpret_cast<intptr_t>(this));
#endif
mDeviceDelegate->ProvisionWiFi(SSID, passwd);
err = CHIP_NO_ERROR;
}
break;
case NetworkProvisioning::MsgTypes::kThreadAssociationRequest:
ChipLogProgress(NetworkProvisioning, "Received kThreadAssociationRequest");
err = DecodeThreadAssociationRequest(msgBuf);
break;
case NetworkProvisioning::MsgTypes::kIPAddressAssigned: {
ChipLogProgress(NetworkProvisioning, "Received kIPAddressAssigned");
if (!Inet::IPAddress::FromString(Uint8::to_const_char(msgBuf->Start()), msgBuf->DataLength(), mDeviceAddress))
{
ExitNow(err = CHIP_ERROR_INVALID_ADDRESS);
}
}
break;
default:
ExitNow(err = CHIP_ERROR_INVALID_MESSAGE_TYPE);
break;
};
exit:
if (mDelegate != nullptr)
{
if (err != CHIP_NO_ERROR)
{
ChipLogError(NetworkProvisioning, "Failed in HandleNetworkProvisioningMessage. error %s\n", ErrorStr(err));
mDelegate->OnNetworkProvisioningError(err);
}
else
{
// Network provisioning handshake requires only one message exchange in either direction.
// If the current message handling did not result in an error, network provisioning is
// complete.
mDelegate->OnNetworkProvisioningComplete();
}
}
return err;
}
CHIP_ERROR NetworkProvisioning::EncodeString(const char * str, BufBound & bbuf)
{
CHIP_ERROR err = CHIP_NO_ERROR;
size_t length = strlen(str);
uint16_t u16len = static_cast<uint16_t>(length);
VerifyOrExit(CanCastTo<uint16_t>(length), err = CHIP_ERROR_INVALID_ARGUMENT);
bbuf.PutLE16(u16len);
bbuf.Put(str);
exit:
return err;
}
CHIP_ERROR NetworkProvisioning::DecodeString(const uint8_t * input, size_t input_len, BufBound & bbuf, size_t & consumed)
{
CHIP_ERROR err = CHIP_NO_ERROR;
uint16_t length = 0;
VerifyOrExit(input_len >= sizeof(uint16_t), err = CHIP_ERROR_BUFFER_TOO_SMALL);
length = chip::Encoding::LittleEndian::Get16(input);
consumed = sizeof(uint16_t);
VerifyOrExit(input_len - consumed >= length, err = CHIP_ERROR_BUFFER_TOO_SMALL);
bbuf.Put(&input[consumed], length);
consumed += bbuf.Written();
bbuf.Put('\0');
VerifyOrExit(bbuf.Fit(), err = CHIP_ERROR_BUFFER_TOO_SMALL);
exit:
return err;
}
CHIP_ERROR NetworkProvisioning::SendIPAddress(const Inet::IPAddress & addr)
{
CHIP_ERROR err = CHIP_NO_ERROR;
System::PacketBuffer * buffer = System::PacketBuffer::New();
char * addrStr = addr.ToString(Uint8::to_char(buffer->Start()), buffer->AvailableDataLength());
size_t addrLen = 0;
ChipLogProgress(NetworkProvisioning, "Sending IP Address. Delegate %p\n", mDelegate);
VerifyOrExit(mDelegate != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
VerifyOrExit(addrStr != nullptr, err = CHIP_ERROR_INVALID_ADDRESS);
addrLen = strlen(addrStr) + 1;
VerifyOrExit(CanCastTo<uint16_t>(addrLen), err = CHIP_ERROR_INVALID_ARGUMENT);
buffer->SetDataLength(static_cast<uint16_t>(addrLen));
err = mDelegate->SendSecureMessage(Protocols::kChipProtocol_NetworkProvisioning,
NetworkProvisioning::MsgTypes::kIPAddressAssigned, buffer);
buffer = nullptr;
SuccessOrExit(err);
exit:
if (buffer)
System::PacketBuffer::Free(buffer);
if (CHIP_NO_ERROR != err)
ChipLogError(NetworkProvisioning, "Failed in sending IP address. error %s\n", ErrorStr(err));
return err;
}
CHIP_ERROR NetworkProvisioning::SendNetworkCredentials(const char * ssid, const char * passwd)
{
CHIP_ERROR err = CHIP_NO_ERROR;
System::PacketBuffer * buffer = System::PacketBuffer::New();
BufBound bbuf(buffer->Start(), buffer->AvailableDataLength());
ChipLogProgress(NetworkProvisioning, "Sending Network Creds. Delegate %p\n", mDelegate);
VerifyOrExit(mDelegate != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
SuccessOrExit(EncodeString(ssid, bbuf));
SuccessOrExit(EncodeString(passwd, bbuf));
VerifyOrExit(bbuf.Fit(), err = CHIP_ERROR_BUFFER_TOO_SMALL);
VerifyOrExit(CanCastTo<uint16_t>(bbuf.Written()), err = CHIP_ERROR_INVALID_ARGUMENT);
buffer->SetDataLength(static_cast<uint16_t>(bbuf.Written()));
err = mDelegate->SendSecureMessage(Protocols::kChipProtocol_NetworkProvisioning,
NetworkProvisioning::MsgTypes::kWiFiAssociationRequest, buffer);
buffer = nullptr;
SuccessOrExit(err);
exit:
if (buffer)
System::PacketBuffer::Free(buffer);
if (CHIP_NO_ERROR != err)
ChipLogError(NetworkProvisioning, "Failed in sending Network Creds. error %s\n", ErrorStr(err));
return err;
}
#ifdef CHIP_ENABLE_OPENTHREAD
CHIP_ERROR NetworkProvisioning::DecodeThreadAssociationRequest(System::PacketBuffer * msgBuf)
{
CHIP_ERROR err = CHIP_NO_ERROR;
DeviceLayer::Internal::DeviceNetworkInfo networkInfo = {};
uint8_t * data = msgBuf->Start();
size_t dataLen = msgBuf->DataLength();
VerifyOrExit(mDeviceDelegate != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
VerifyOrExit(dataLen >= sizeof(networkInfo.ThreadNetworkName),
ChipLogProgress(NetworkProvisioning, "Invalid network provision message"));
memcpy(networkInfo.ThreadNetworkName, data, sizeof(networkInfo.ThreadNetworkName));
data += sizeof(networkInfo.ThreadNetworkName);
dataLen -= sizeof(networkInfo.ThreadNetworkName);
VerifyOrExit(dataLen >= sizeof(networkInfo.ThreadExtendedPANId),
ChipLogProgress(NetworkProvisioning, "Invalid network provision message"));
memcpy(networkInfo.ThreadExtendedPANId, data, sizeof(networkInfo.ThreadExtendedPANId));
data += sizeof(networkInfo.ThreadExtendedPANId);
dataLen -= sizeof(networkInfo.ThreadExtendedPANId);
VerifyOrExit(dataLen >= sizeof(networkInfo.ThreadMeshPrefix),
ChipLogProgress(NetworkProvisioning, "Invalid network provision message"));
memcpy(networkInfo.ThreadMeshPrefix, data, sizeof(networkInfo.ThreadMeshPrefix));
data += sizeof(networkInfo.ThreadMeshPrefix);
dataLen -= sizeof(networkInfo.ThreadMeshPrefix);
VerifyOrExit(dataLen >= sizeof(networkInfo.ThreadMasterKey),
ChipLogProgress(NetworkProvisioning, "Invalid network provision message"));
memcpy(networkInfo.ThreadMasterKey, data, sizeof(networkInfo.ThreadMasterKey));
data += sizeof(networkInfo.ThreadMasterKey);
dataLen -= sizeof(networkInfo.ThreadMasterKey);
VerifyOrExit(dataLen >= sizeof(networkInfo.ThreadPSKc),
ChipLogProgress(NetworkProvisioning, "Invalid network provision message"));
memcpy(networkInfo.ThreadPSKc, data, sizeof(networkInfo.ThreadPSKc));
data += sizeof(networkInfo.ThreadPSKc);
dataLen -= sizeof(networkInfo.ThreadPSKc);
VerifyOrExit(dataLen >= sizeof(networkInfo.ThreadPANId),
ChipLogProgress(NetworkProvisioning, "Invalid network provision message"));
networkInfo.ThreadPANId = Encoding::LittleEndian::Get16(data);
data += sizeof(networkInfo.ThreadPANId);
dataLen -= sizeof(networkInfo.ThreadPANId);
VerifyOrExit(dataLen >= sizeof(networkInfo.ThreadChannel),
ChipLogProgress(NetworkProvisioning, "Invalid network provision message"));
networkInfo.ThreadChannel = data[0];
data += sizeof(networkInfo.ThreadChannel);
dataLen -= sizeof(networkInfo.ThreadChannel);
VerifyOrExit(dataLen >= 3, ChipLogProgress(NetworkProvisioning, "Invalid network provision message"));
networkInfo.FieldPresent.ThreadExtendedPANId = *data;
data++;
networkInfo.FieldPresent.ThreadMeshPrefix = *data;
data++;
networkInfo.FieldPresent.ThreadPSKc = *data;
data++;
networkInfo.NetworkId = 0;
networkInfo.FieldPresent.NetworkId = true;
#if CONFIG_DEVICE_LAYER
// Start listening for OpenThread changes to be able to respond with SLAAC/On-Mesh IP Address
DeviceLayer::PlatformMgr().AddEventHandler(ConnectivityHandler, reinterpret_cast<intptr_t>(this));
#endif
mDeviceDelegate->ProvisionThread(networkInfo);
exit:
return err;
}
#else // CHIP_ENABLE_OPENTHREAD
CHIP_ERROR NetworkProvisioning::DecodeThreadAssociationRequest(System::PacketBuffer *)
{
return CHIP_ERROR_INVALID_MESSAGE_TYPE;
}
#endif // CHIP_ENABLE_OPENTHREAD
#if CONFIG_DEVICE_LAYER
void NetworkProvisioning::ConnectivityHandler(const DeviceLayer::ChipDeviceEvent * event, intptr_t arg)
{
NetworkProvisioning * session = reinterpret_cast<NetworkProvisioning *>(arg);
VerifyOrExit(session != nullptr, /**/);
if (event->Type == DeviceLayer::DeviceEventType::kInternetConnectivityChange &&
event->InternetConnectivityChange.IPv4 == DeviceLayer::kConnectivity_Established)
{
Inet::IPAddress addr;
Inet::IPAddress::FromString(event->InternetConnectivityChange.address, addr);
(void) session->SendIPAddress(addr);
}
#if CHIP_DEVICE_CONFIG_ENABLE_THREAD
if (event->Type == DeviceLayer::DeviceEventType::kThreadStateChange && event->ThreadStateChange.AddressChanged)
{
Inet::IPAddress addr;
SuccessOrExit(DeviceLayer::ThreadStackMgr().GetSlaacIPv6Address(addr));
(void) session->SendIPAddress(addr);
}
#endif
exit:
return;
}
#endif
} // namespace chip
<commit_msg>Fix initialization of NetworkProvisioning delegate (#3450)<commit_after>/*
*
* Copyright (c) 2020 Project CHIP Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <core/CHIPEncoding.h>
#include <core/CHIPSafeCasts.h>
#include <platform/internal/DeviceNetworkInfo.h>
#include <protocols/CHIPProtocols.h>
#include <support/CodeUtils.h>
#include <support/ErrorStr.h>
#include <support/SafeInt.h>
#include <transport/NetworkProvisioning.h>
#if CONFIG_DEVICE_LAYER
#include <platform/CHIPDeviceLayer.h>
#endif
namespace chip {
void NetworkProvisioning::Init(NetworkProvisioningDelegate * delegate, DeviceNetworkProvisioningDelegate * deviceDelegate)
{
mDelegate = delegate;
mDeviceDelegate = deviceDelegate;
}
NetworkProvisioning::~NetworkProvisioning()
{
if (mDeviceDelegate != nullptr)
{
#if CONFIG_DEVICE_LAYER
DeviceLayer::PlatformMgr().RemoveEventHandler(ConnectivityHandler, reinterpret_cast<intptr_t>(this));
#endif
}
}
CHIP_ERROR NetworkProvisioning::HandleNetworkProvisioningMessage(uint8_t msgType, System::PacketBuffer * msgBuf)
{
CHIP_ERROR err = CHIP_NO_ERROR;
switch (msgType)
{
case NetworkProvisioning::MsgTypes::kWiFiAssociationRequest: {
char SSID[chip::DeviceLayer::Internal::kMaxWiFiSSIDLength];
char passwd[chip::DeviceLayer::Internal::kMaxWiFiKeyLength];
BufBound bbufSSID(Uint8::from_char(SSID), chip::DeviceLayer::Internal::kMaxWiFiSSIDLength);
BufBound bbufPW(Uint8::from_char(passwd), chip::DeviceLayer::Internal::kMaxWiFiKeyLength);
const uint8_t * buffer = msgBuf->Start();
size_t len = msgBuf->DataLength();
size_t offset = 0;
ChipLogProgress(NetworkProvisioning, "Received kWiFiAssociationRequest. DeviceDelegate %p", mDeviceDelegate);
VerifyOrExit(mDeviceDelegate != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
err = DecodeString(&buffer[offset], len - offset, bbufSSID, offset);
// TODO: Check for the error once network provisioning is moved to delegate calls
err = DecodeString(&buffer[offset], len - offset, bbufPW, offset);
// TODO: Check for the error once network provisioning is moved to delegate calls
#if CONFIG_DEVICE_LAYER
// Start listening for Internet connectivity changes to be able to respond with assigned IP Address
DeviceLayer::PlatformMgr().AddEventHandler(ConnectivityHandler, reinterpret_cast<intptr_t>(this));
#endif
mDeviceDelegate->ProvisionWiFi(SSID, passwd);
err = CHIP_NO_ERROR;
}
break;
case NetworkProvisioning::MsgTypes::kThreadAssociationRequest:
ChipLogProgress(NetworkProvisioning, "Received kThreadAssociationRequest");
err = DecodeThreadAssociationRequest(msgBuf);
break;
case NetworkProvisioning::MsgTypes::kIPAddressAssigned: {
ChipLogProgress(NetworkProvisioning, "Received kIPAddressAssigned");
if (!Inet::IPAddress::FromString(Uint8::to_const_char(msgBuf->Start()), msgBuf->DataLength(), mDeviceAddress))
{
ExitNow(err = CHIP_ERROR_INVALID_ADDRESS);
}
}
break;
default:
ExitNow(err = CHIP_ERROR_INVALID_MESSAGE_TYPE);
break;
};
exit:
if (mDelegate != nullptr)
{
if (err != CHIP_NO_ERROR)
{
ChipLogError(NetworkProvisioning, "Failed in HandleNetworkProvisioningMessage. error %s\n", ErrorStr(err));
mDelegate->OnNetworkProvisioningError(err);
}
else
{
// Network provisioning handshake requires only one message exchange in either direction.
// If the current message handling did not result in an error, network provisioning is
// complete.
mDelegate->OnNetworkProvisioningComplete();
}
}
return err;
}
CHIP_ERROR NetworkProvisioning::EncodeString(const char * str, BufBound & bbuf)
{
CHIP_ERROR err = CHIP_NO_ERROR;
size_t length = strlen(str);
uint16_t u16len = static_cast<uint16_t>(length);
VerifyOrExit(CanCastTo<uint16_t>(length), err = CHIP_ERROR_INVALID_ARGUMENT);
bbuf.PutLE16(u16len);
bbuf.Put(str);
exit:
return err;
}
CHIP_ERROR NetworkProvisioning::DecodeString(const uint8_t * input, size_t input_len, BufBound & bbuf, size_t & consumed)
{
CHIP_ERROR err = CHIP_NO_ERROR;
uint16_t length = 0;
VerifyOrExit(input_len >= sizeof(uint16_t), err = CHIP_ERROR_BUFFER_TOO_SMALL);
length = chip::Encoding::LittleEndian::Get16(input);
consumed = sizeof(uint16_t);
VerifyOrExit(input_len - consumed >= length, err = CHIP_ERROR_BUFFER_TOO_SMALL);
bbuf.Put(&input[consumed], length);
consumed += bbuf.Written();
bbuf.Put('\0');
VerifyOrExit(bbuf.Fit(), err = CHIP_ERROR_BUFFER_TOO_SMALL);
exit:
return err;
}
CHIP_ERROR NetworkProvisioning::SendIPAddress(const Inet::IPAddress & addr)
{
CHIP_ERROR err = CHIP_NO_ERROR;
System::PacketBuffer * buffer = System::PacketBuffer::New();
char * addrStr = addr.ToString(Uint8::to_char(buffer->Start()), buffer->AvailableDataLength());
size_t addrLen = 0;
ChipLogProgress(NetworkProvisioning, "Sending IP Address. Delegate %p\n", mDelegate);
VerifyOrExit(mDelegate != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
VerifyOrExit(addrStr != nullptr, err = CHIP_ERROR_INVALID_ADDRESS);
addrLen = strlen(addrStr) + 1;
VerifyOrExit(CanCastTo<uint16_t>(addrLen), err = CHIP_ERROR_INVALID_ARGUMENT);
buffer->SetDataLength(static_cast<uint16_t>(addrLen));
err = mDelegate->SendSecureMessage(Protocols::kChipProtocol_NetworkProvisioning,
NetworkProvisioning::MsgTypes::kIPAddressAssigned, buffer);
buffer = nullptr;
SuccessOrExit(err);
exit:
if (buffer)
System::PacketBuffer::Free(buffer);
if (CHIP_NO_ERROR != err)
ChipLogError(NetworkProvisioning, "Failed in sending IP address. error %s\n", ErrorStr(err));
return err;
}
CHIP_ERROR NetworkProvisioning::SendNetworkCredentials(const char * ssid, const char * passwd)
{
CHIP_ERROR err = CHIP_NO_ERROR;
System::PacketBuffer * buffer = System::PacketBuffer::New();
BufBound bbuf(buffer->Start(), buffer->AvailableDataLength());
ChipLogProgress(NetworkProvisioning, "Sending Network Creds. Delegate %p\n", mDelegate);
VerifyOrExit(mDelegate != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
SuccessOrExit(EncodeString(ssid, bbuf));
SuccessOrExit(EncodeString(passwd, bbuf));
VerifyOrExit(bbuf.Fit(), err = CHIP_ERROR_BUFFER_TOO_SMALL);
VerifyOrExit(CanCastTo<uint16_t>(bbuf.Written()), err = CHIP_ERROR_INVALID_ARGUMENT);
buffer->SetDataLength(static_cast<uint16_t>(bbuf.Written()));
err = mDelegate->SendSecureMessage(Protocols::kChipProtocol_NetworkProvisioning,
NetworkProvisioning::MsgTypes::kWiFiAssociationRequest, buffer);
buffer = nullptr;
SuccessOrExit(err);
exit:
if (buffer)
System::PacketBuffer::Free(buffer);
if (CHIP_NO_ERROR != err)
ChipLogError(NetworkProvisioning, "Failed in sending Network Creds. error %s\n", ErrorStr(err));
return err;
}
#ifdef CHIP_ENABLE_OPENTHREAD
CHIP_ERROR NetworkProvisioning::DecodeThreadAssociationRequest(System::PacketBuffer * msgBuf)
{
CHIP_ERROR err = CHIP_NO_ERROR;
DeviceLayer::Internal::DeviceNetworkInfo networkInfo = {};
uint8_t * data = msgBuf->Start();
size_t dataLen = msgBuf->DataLength();
VerifyOrExit(mDeviceDelegate != nullptr, err = CHIP_ERROR_INCORRECT_STATE);
VerifyOrExit(dataLen >= sizeof(networkInfo.ThreadNetworkName),
ChipLogProgress(NetworkProvisioning, "Invalid network provision message"));
memcpy(networkInfo.ThreadNetworkName, data, sizeof(networkInfo.ThreadNetworkName));
data += sizeof(networkInfo.ThreadNetworkName);
dataLen -= sizeof(networkInfo.ThreadNetworkName);
VerifyOrExit(dataLen >= sizeof(networkInfo.ThreadExtendedPANId),
ChipLogProgress(NetworkProvisioning, "Invalid network provision message"));
memcpy(networkInfo.ThreadExtendedPANId, data, sizeof(networkInfo.ThreadExtendedPANId));
data += sizeof(networkInfo.ThreadExtendedPANId);
dataLen -= sizeof(networkInfo.ThreadExtendedPANId);
VerifyOrExit(dataLen >= sizeof(networkInfo.ThreadMeshPrefix),
ChipLogProgress(NetworkProvisioning, "Invalid network provision message"));
memcpy(networkInfo.ThreadMeshPrefix, data, sizeof(networkInfo.ThreadMeshPrefix));
data += sizeof(networkInfo.ThreadMeshPrefix);
dataLen -= sizeof(networkInfo.ThreadMeshPrefix);
VerifyOrExit(dataLen >= sizeof(networkInfo.ThreadMasterKey),
ChipLogProgress(NetworkProvisioning, "Invalid network provision message"));
memcpy(networkInfo.ThreadMasterKey, data, sizeof(networkInfo.ThreadMasterKey));
data += sizeof(networkInfo.ThreadMasterKey);
dataLen -= sizeof(networkInfo.ThreadMasterKey);
VerifyOrExit(dataLen >= sizeof(networkInfo.ThreadPSKc),
ChipLogProgress(NetworkProvisioning, "Invalid network provision message"));
memcpy(networkInfo.ThreadPSKc, data, sizeof(networkInfo.ThreadPSKc));
data += sizeof(networkInfo.ThreadPSKc);
dataLen -= sizeof(networkInfo.ThreadPSKc);
VerifyOrExit(dataLen >= sizeof(networkInfo.ThreadPANId),
ChipLogProgress(NetworkProvisioning, "Invalid network provision message"));
networkInfo.ThreadPANId = Encoding::LittleEndian::Get16(data);
data += sizeof(networkInfo.ThreadPANId);
dataLen -= sizeof(networkInfo.ThreadPANId);
VerifyOrExit(dataLen >= sizeof(networkInfo.ThreadChannel),
ChipLogProgress(NetworkProvisioning, "Invalid network provision message"));
networkInfo.ThreadChannel = data[0];
data += sizeof(networkInfo.ThreadChannel);
dataLen -= sizeof(networkInfo.ThreadChannel);
VerifyOrExit(dataLen >= 3, ChipLogProgress(NetworkProvisioning, "Invalid network provision message"));
networkInfo.FieldPresent.ThreadExtendedPANId = *data;
data++;
networkInfo.FieldPresent.ThreadMeshPrefix = *data;
data++;
networkInfo.FieldPresent.ThreadPSKc = *data;
data++;
networkInfo.NetworkId = 0;
networkInfo.FieldPresent.NetworkId = true;
#if CONFIG_DEVICE_LAYER
// Start listening for OpenThread changes to be able to respond with SLAAC/On-Mesh IP Address
DeviceLayer::PlatformMgr().AddEventHandler(ConnectivityHandler, reinterpret_cast<intptr_t>(this));
#endif
mDeviceDelegate->ProvisionThread(networkInfo);
exit:
return err;
}
#else // CHIP_ENABLE_OPENTHREAD
CHIP_ERROR NetworkProvisioning::DecodeThreadAssociationRequest(System::PacketBuffer *)
{
return CHIP_ERROR_INVALID_MESSAGE_TYPE;
}
#endif // CHIP_ENABLE_OPENTHREAD
#if CONFIG_DEVICE_LAYER
void NetworkProvisioning::ConnectivityHandler(const DeviceLayer::ChipDeviceEvent * event, intptr_t arg)
{
NetworkProvisioning * session = reinterpret_cast<NetworkProvisioning *>(arg);
VerifyOrExit(session != nullptr, /**/);
if (event->Type == DeviceLayer::DeviceEventType::kInternetConnectivityChange &&
event->InternetConnectivityChange.IPv4 == DeviceLayer::kConnectivity_Established)
{
Inet::IPAddress addr;
Inet::IPAddress::FromString(event->InternetConnectivityChange.address, addr);
(void) session->SendIPAddress(addr);
}
#if CHIP_DEVICE_CONFIG_ENABLE_THREAD
if (event->Type == DeviceLayer::DeviceEventType::kThreadStateChange && event->ThreadStateChange.AddressChanged)
{
Inet::IPAddress addr;
SuccessOrExit(DeviceLayer::ThreadStackMgr().GetSlaacIPv6Address(addr));
(void) session->SendIPAddress(addr);
}
#endif
exit:
return;
}
#endif
} // namespace chip
<|endoftext|> |
<commit_before>#include "watcherSerialize.h"
#include "gpsMessage.h"
using namespace std;
namespace watcher {
namespace event {
INIT_LOGGER(GPSMessage, "Message.GPSMessage");
GPSMessage::GPSMessage(const float &x_, const float &y_, const float &z_) :
Message(GPS_MESSAGE_TYPE, GPS_MESSAGE_VERSION),
x(x_),
y(y_),
z(z_),
dataFormat(LAT_LONG_ALT_WGS84)
{
TRACE_ENTER();
TRACE_EXIT();
}
GPSMessage::GPSMessage(const GPSMessage &other) :
Message(other.type, other.version),
x(other.x),
y(other.y),
z(other.z),
dataFormat(other.dataFormat)
{
TRACE_ENTER();
TRACE_EXIT();
}
bool GPSMessage::operator==(const GPSMessage &other) const
{
TRACE_ENTER();
bool retVal =
Message::operator==(other) &&
x == other.x &&
y == other.y &&
z == other.z &&
dataFormat == other.dataFormat;
TRACE_EXIT_RET(retVal);
return retVal;
}
GPSMessage &GPSMessage::operator=(const GPSMessage &other)
{
TRACE_ENTER();
Message::operator=(other);
x = other.x;
y = other.y;
z = other.z;
TRACE_EXIT();
return *this;
}
// virtual
std::ostream &GPSMessage::toStream(std::ostream &out) const
{
TRACE_ENTER();
Message::toStream(out);
out << " x: " << x;
out << " y: " << y;
out << " z: " << z;
out << " format: " << dataFormat;
TRACE_EXIT();
return out;
}
ostream &operator<<(ostream &out, const GPSMessage &mess)
{
TRACE_ENTER();
mess.operator<<(out);
TRACE_EXIT();
return out;
}
template <typename Archive> void GPSMessage::serialize(Archive & ar, const unsigned int /* file_version */)
{
TRACE_ENTER();
ar & boost::serialization::base_object<Message>(*this);
ar & x;
ar & y;
ar & z;
ar & dataFormat;
TRACE_EXIT();
}
}
}
BOOST_CLASS_EXPORT(watcher::event::GPSMessage);
<commit_msg>gpsMessage: use base class copy ctor when doing a copy.<commit_after>#include "watcherSerialize.h"
#include "gpsMessage.h"
using namespace std;
namespace watcher {
namespace event {
INIT_LOGGER(GPSMessage, "Message.GPSMessage");
GPSMessage::GPSMessage(const float &x_, const float &y_, const float &z_) :
Message(GPS_MESSAGE_TYPE, GPS_MESSAGE_VERSION),
x(x_),
y(y_),
z(z_),
dataFormat(LAT_LONG_ALT_WGS84)
{
TRACE_ENTER();
TRACE_EXIT();
}
GPSMessage::GPSMessage(const GPSMessage &other) :
Message(other),
x(other.x),
y(other.y),
z(other.z),
dataFormat(other.dataFormat)
{
TRACE_ENTER();
TRACE_EXIT();
}
bool GPSMessage::operator==(const GPSMessage &other) const
{
TRACE_ENTER();
bool retVal =
Message::operator==(other) &&
x == other.x &&
y == other.y &&
z == other.z &&
dataFormat == other.dataFormat;
TRACE_EXIT_RET(retVal);
return retVal;
}
GPSMessage &GPSMessage::operator=(const GPSMessage &other)
{
TRACE_ENTER();
Message::operator=(other);
x = other.x;
y = other.y;
z = other.z;
TRACE_EXIT();
return *this;
}
// virtual
std::ostream &GPSMessage::toStream(std::ostream &out) const
{
TRACE_ENTER();
Message::toStream(out);
out << " x: " << x;
out << " y: " << y;
out << " z: " << z;
out << " format: " << dataFormat;
TRACE_EXIT();
return out;
}
ostream &operator<<(ostream &out, const GPSMessage &mess)
{
TRACE_ENTER();
mess.operator<<(out);
TRACE_EXIT();
return out;
}
template <typename Archive> void GPSMessage::serialize(Archive & ar, const unsigned int /* file_version */)
{
TRACE_ENTER();
ar & boost::serialization::base_object<Message>(*this);
ar & x;
ar & y;
ar & z;
ar & dataFormat;
TRACE_EXIT();
}
}
}
BOOST_CLASS_EXPORT(watcher::event::GPSMessage);
<|endoftext|> |
<commit_before>//===- llvm-profdata.cpp - LLVM profile data tool -------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// llvm-profdata merges .profdata files.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/LineIterator.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
static void exitWithError(const std::string &Message,
const std::string &Filename, int64_t Line = -1) {
errs() << "error: " << Filename;
if (Line >= 0)
errs() << ":" << Line;
errs() << ": " << Message << "\n";
::exit(1);
}
//===----------------------------------------------------------------------===//
int merge_main(int argc, const char *argv[]) {
cl::opt<std::string> Filename1(cl::Positional, cl::Required,
cl::desc("file1"));
cl::opt<std::string> Filename2(cl::Positional, cl::Required,
cl::desc("file2"));
cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
cl::init("-"),
cl::desc("Output file"));
cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
cl::aliasopt(OutputFilename));
cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
std::unique_ptr<MemoryBuffer> File1;
std::unique_ptr<MemoryBuffer> File2;
if (error_code ec = MemoryBuffer::getFile(Filename1, File1))
exitWithError(ec.message(), Filename1);
if (error_code ec = MemoryBuffer::getFile(Filename2, File2))
exitWithError(ec.message(), Filename2);
if (OutputFilename.empty())
OutputFilename = "-";
std::string ErrorInfo;
raw_fd_ostream Output(OutputFilename.data(), ErrorInfo, sys::fs::F_Text);
if (!ErrorInfo.empty())
exitWithError(ErrorInfo, OutputFilename);
enum {ReadName, ReadHash, ReadCount, ReadCounters} State = ReadName;
uint64_t N1, N2, NumCounters;
line_iterator I1(*File1, '#'), I2(*File2, '#');
for (; !I1.is_at_end() && !I2.is_at_end(); ++I1, ++I2) {
if (I1->empty()) {
if (!I2->empty())
exitWithError("data mismatch", Filename2, I2.line_number());
Output << "\n";
continue;
}
switch (State) {
case ReadName:
if (*I1 != *I2)
exitWithError("function name mismatch", Filename2, I2.line_number());
Output << *I1 << "\n";
State = ReadHash;
break;
case ReadHash:
if (I1->getAsInteger(10, N1))
exitWithError("bad function hash", Filename1, I1.line_number());
if (I2->getAsInteger(10, N2))
exitWithError("bad function hash", Filename2, I2.line_number());
if (N1 != N2)
exitWithError("function hash mismatch", Filename2, I2.line_number());
Output << N1 << "\n";
State = ReadCount;
break;
case ReadCount:
if (I1->getAsInteger(10, N1))
exitWithError("bad function count", Filename1, I1.line_number());
if (I2->getAsInteger(10, N2))
exitWithError("bad function count", Filename2, I2.line_number());
if (N1 != N2)
exitWithError("function count mismatch", Filename2, I2.line_number());
Output << N1 << "\n";
NumCounters = N1;
State = ReadCounters;
break;
case ReadCounters:
if (I1->getAsInteger(10, N1))
exitWithError("invalid counter", Filename1, I1.line_number());
if (I2->getAsInteger(10, N2))
exitWithError("invalid counter", Filename2, I2.line_number());
uint64_t Sum = N1 + N2;
if (Sum < N1)
exitWithError("counter overflow", Filename2, I2.line_number());
Output << N1 + N2 << "\n";
if (--NumCounters == 0)
State = ReadName;
break;
}
}
if (!I1.is_at_end())
exitWithError("truncated file", Filename1, I1.line_number());
if (!I2.is_at_end())
exitWithError("truncated file", Filename2, I2.line_number());
if (State != ReadName)
exitWithError("truncated file", Filename1, I1.line_number());
return 0;
}
int main(int argc, const char *argv[]) {
// Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
StringRef ProgName(sys::path::filename(argv[0]));
if (argc > 1) {
int (*func)(int, const char *[]) = 0;
if (strcmp(argv[1], "merge") == 0)
func = merge_main;
if (func) {
std::string Invocation(ProgName.str() + " " + argv[1]);
argv[1] = Invocation.c_str();
return func(argc - 1, argv + 1);
}
if (strcmp(argv[1], "-h") == 0 ||
strcmp(argv[1], "-help") == 0 ||
strcmp(argv[1], "--help") == 0) {
errs() << "OVERVIEW: LLVM profile data tools\n\n"
<< "USAGE: " << ProgName << " <command> [args...]\n"
<< "USAGE: " << ProgName << " <command> -help\n\n"
<< "Available commands: merge\n";
return 0;
}
}
if (argc < 2)
errs() << ProgName << ": No command specified!\n";
else
errs() << ProgName << ": Unknown command!\n";
errs() << "USAGE: " << ProgName << " <merge|show|generate> [args...]\n";
return 1;
}
<commit_msg>llvm-profdata: Remove an empty comment<commit_after>//===- llvm-profdata.cpp - LLVM profile data tool -------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// llvm-profdata merges .profdata files.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/LineIterator.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Signals.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
static void exitWithError(const std::string &Message,
const std::string &Filename, int64_t Line = -1) {
errs() << "error: " << Filename;
if (Line >= 0)
errs() << ":" << Line;
errs() << ": " << Message << "\n";
::exit(1);
}
int merge_main(int argc, const char *argv[]) {
cl::opt<std::string> Filename1(cl::Positional, cl::Required,
cl::desc("file1"));
cl::opt<std::string> Filename2(cl::Positional, cl::Required,
cl::desc("file2"));
cl::opt<std::string> OutputFilename("output", cl::value_desc("output"),
cl::init("-"),
cl::desc("Output file"));
cl::alias OutputFilenameA("o", cl::desc("Alias for --output"),
cl::aliasopt(OutputFilename));
cl::ParseCommandLineOptions(argc, argv, "LLVM profile data merger\n");
std::unique_ptr<MemoryBuffer> File1;
std::unique_ptr<MemoryBuffer> File2;
if (error_code ec = MemoryBuffer::getFile(Filename1, File1))
exitWithError(ec.message(), Filename1);
if (error_code ec = MemoryBuffer::getFile(Filename2, File2))
exitWithError(ec.message(), Filename2);
if (OutputFilename.empty())
OutputFilename = "-";
std::string ErrorInfo;
raw_fd_ostream Output(OutputFilename.data(), ErrorInfo, sys::fs::F_Text);
if (!ErrorInfo.empty())
exitWithError(ErrorInfo, OutputFilename);
enum {ReadName, ReadHash, ReadCount, ReadCounters} State = ReadName;
uint64_t N1, N2, NumCounters;
line_iterator I1(*File1, '#'), I2(*File2, '#');
for (; !I1.is_at_end() && !I2.is_at_end(); ++I1, ++I2) {
if (I1->empty()) {
if (!I2->empty())
exitWithError("data mismatch", Filename2, I2.line_number());
Output << "\n";
continue;
}
switch (State) {
case ReadName:
if (*I1 != *I2)
exitWithError("function name mismatch", Filename2, I2.line_number());
Output << *I1 << "\n";
State = ReadHash;
break;
case ReadHash:
if (I1->getAsInteger(10, N1))
exitWithError("bad function hash", Filename1, I1.line_number());
if (I2->getAsInteger(10, N2))
exitWithError("bad function hash", Filename2, I2.line_number());
if (N1 != N2)
exitWithError("function hash mismatch", Filename2, I2.line_number());
Output << N1 << "\n";
State = ReadCount;
break;
case ReadCount:
if (I1->getAsInteger(10, N1))
exitWithError("bad function count", Filename1, I1.line_number());
if (I2->getAsInteger(10, N2))
exitWithError("bad function count", Filename2, I2.line_number());
if (N1 != N2)
exitWithError("function count mismatch", Filename2, I2.line_number());
Output << N1 << "\n";
NumCounters = N1;
State = ReadCounters;
break;
case ReadCounters:
if (I1->getAsInteger(10, N1))
exitWithError("invalid counter", Filename1, I1.line_number());
if (I2->getAsInteger(10, N2))
exitWithError("invalid counter", Filename2, I2.line_number());
uint64_t Sum = N1 + N2;
if (Sum < N1)
exitWithError("counter overflow", Filename2, I2.line_number());
Output << N1 + N2 << "\n";
if (--NumCounters == 0)
State = ReadName;
break;
}
}
if (!I1.is_at_end())
exitWithError("truncated file", Filename1, I1.line_number());
if (!I2.is_at_end())
exitWithError("truncated file", Filename2, I2.line_number());
if (State != ReadName)
exitWithError("truncated file", Filename1, I1.line_number());
return 0;
}
int main(int argc, const char *argv[]) {
// Print a stack trace if we signal out.
sys::PrintStackTraceOnErrorSignal();
PrettyStackTraceProgram X(argc, argv);
llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
StringRef ProgName(sys::path::filename(argv[0]));
if (argc > 1) {
int (*func)(int, const char *[]) = 0;
if (strcmp(argv[1], "merge") == 0)
func = merge_main;
if (func) {
std::string Invocation(ProgName.str() + " " + argv[1]);
argv[1] = Invocation.c_str();
return func(argc - 1, argv + 1);
}
if (strcmp(argv[1], "-h") == 0 ||
strcmp(argv[1], "-help") == 0 ||
strcmp(argv[1], "--help") == 0) {
errs() << "OVERVIEW: LLVM profile data tools\n\n"
<< "USAGE: " << ProgName << " <command> [args...]\n"
<< "USAGE: " << ProgName << " <command> -help\n\n"
<< "Available commands: merge\n";
return 0;
}
}
if (argc < 2)
errs() << ProgName << ": No command specified!\n";
else
errs() << ProgName << ": Unknown command!\n";
errs() << "USAGE: " << ProgName << " <merge|show|generate> [args...]\n";
return 1;
}
<|endoftext|> |
<commit_before><commit_msg>INTEGRATION: CWS oj14 (1.15.38); FILE MERGED 2006/12/19 14:04:58 oj 1.15.38.1: use of XIndexAccess instead of XNameAccess<commit_after><|endoftext|> |
<commit_before>#include <rai/cli/daemon.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <iostream>
#include <fstream>
#include <thread>
rai_daemon::daemon_config::daemon_config () :
peering_port (24000),
rpc_port (25000)
{
}
void rai_daemon::daemon_config::serialize (std::ostream & output_a)
{
boost::property_tree::ptree tree;
tree.put ("peering_port", std::to_string (peering_port));
tree.put ("rpc_port", std::to_string (rpc_port));
boost::property_tree::write_json (output_a, tree);
}
bool rai_daemon::daemon_config::deserialize (std::istream & input_a)
{
auto result (false);
boost::property_tree::ptree tree;
try
{
boost::property_tree::read_json (input_a, tree);
auto peering_port_l (tree.get <std::string> ("peering_port"));
auto rpc_port_l (tree.get <std::string> ("rpc_port"));
try
{
peering_port = std::stoul (peering_port_l);
rpc_port = std::stoul (rpc_port_l);
result = peering_port > std::numeric_limits <uint16_t>::max () || rpc_port > std::numeric_limits <uint16_t>::max ();
}
catch (std::logic_error const &)
{
result = true;
}
}
catch (std::runtime_error const &)
{
std::cout << "Error parsing config file" << std::endl;
result = true;
}
return result;
}
rai_daemon::daemon::daemon ()
{
}
void rai_daemon::daemon::run ()
{
auto working (boost::filesystem::current_path ());
auto config_error (false);
rai_daemon::daemon_config config;
auto config_path ((working / "config.json").string ());
std::ifstream config_file;
config_file.open (config_path);
if (!config_file.fail ())
{
config_error = config.deserialize (config_file);
}
else
{
std::ofstream config_file;
config_file.open (config_path);
if (!config_file.fail ())
{
config.serialize (config_file);
}
}
if (!config_error)
{
auto service (boost::make_shared <boost::asio::io_service> ());
auto pool (boost::make_shared <boost::network::utils::thread_pool> ());
rai::processor_service processor;
auto client (std::make_shared <rai::client> (service, config.peering_port, working / "data", processor, rai::genesis_address));
client->start ();
rai::rpc rpc (service, pool, config.rpc_port, *client, std::unordered_set <rai::uint256_union> ());
rpc.start ();
std::thread network_thread ([&service] ()
{
try
{
service->run ();
}
catch (...)
{
assert (false);
}
});
std::thread processor_thread ([&processor] ()
{
try
{
processor.run ();
}
catch (...)
{
assert (false);
}
});
network_thread.join ();
processor_thread.join ();
}
}
<commit_msg>Fixing compile issue with daemon.<commit_after>#include <rai/cli/daemon.hpp>
#include <boost/property_tree/json_parser.hpp>
#include <iostream>
#include <fstream>
#include <thread>
rai_daemon::daemon_config::daemon_config () :
peering_port (24000),
rpc_port (25000)
{
}
void rai_daemon::daemon_config::serialize (std::ostream & output_a)
{
boost::property_tree::ptree tree;
tree.put ("peering_port", std::to_string (peering_port));
tree.put ("rpc_port", std::to_string (rpc_port));
boost::property_tree::write_json (output_a, tree);
}
bool rai_daemon::daemon_config::deserialize (std::istream & input_a)
{
auto result (false);
boost::property_tree::ptree tree;
try
{
boost::property_tree::read_json (input_a, tree);
auto peering_port_l (tree.get <std::string> ("peering_port"));
auto rpc_port_l (tree.get <std::string> ("rpc_port"));
try
{
peering_port = std::stoul (peering_port_l);
rpc_port = std::stoul (rpc_port_l);
result = peering_port > std::numeric_limits <uint16_t>::max () || rpc_port > std::numeric_limits <uint16_t>::max ();
}
catch (std::logic_error const &)
{
result = true;
}
}
catch (std::runtime_error const &)
{
std::cout << "Error parsing config file" << std::endl;
result = true;
}
return result;
}
rai_daemon::daemon::daemon ()
{
}
void rai_daemon::daemon::run ()
{
auto working (boost::filesystem::current_path ());
auto config_error (false);
rai_daemon::daemon_config config;
auto config_path ((working / "config.json").string ());
std::ifstream config_file;
config_file.open (config_path);
if (!config_file.fail ())
{
config_error = config.deserialize (config_file);
}
else
{
std::ofstream config_file;
config_file.open (config_path);
if (!config_file.fail ())
{
config.serialize (config_file);
}
}
if (!config_error)
{
auto service (boost::make_shared <boost::asio::io_service> ());
auto pool (boost::make_shared <boost::network::utils::thread_pool> ());
rai::processor_service processor;
auto client (std::make_shared <rai::client> (service, config.peering_port, working / "data", processor, rai::genesis_address));
client->start ();
rai::rpc rpc (service, pool, config.rpc_port, *client);
rpc.start ();
std::thread network_thread ([&service] ()
{
try
{
service->run ();
}
catch (...)
{
assert (false);
}
});
std::thread processor_thread ([&processor] ()
{
try
{
processor.run ();
}
catch (...)
{
assert (false);
}
});
network_thread.join ();
processor_thread.join ();
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: debug.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: kz $ $Date: 2005-11-02 12:40:17 $
*
* 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
*
************************************************************************/
#if ! defined(INCLUDED_CANVAS_DEBUG_HXX)
#define INCLUDED_CANVAS_DEBUG_HXX
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _RTL_USTRING_HXX_
#include <rtl/ustring.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_RUNTIMEEXCEPTION_HPP_
#include <com/sun/star/uno/RuntimeException.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_ILLEGALARGUMENTEXCEPTION_HPP_
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#endif
#include <boost/current_function.hpp>
// Class invariants
// ----------------
#if OSL_DEBUG_LEVEL > 0
/** This macro asserts the given condition, and throws an
IllegalArgumentException afterwards.
In production code, no assertion appears, but the
IllegalArgumentException is thrown nevertheless (although without
the given error string, to conserve space).
*/
#define CHECK_AND_THROW(c, m) if( !(c) ) { \
OSL_ENSURE(false, m); \
throw ::com::sun::star::lang::IllegalArgumentException( \
::rtl::OUString::createFromAscii(BOOST_CURRENT_FUNCTION) + \
::rtl::OUString::createFromAscii(",\n"m), \
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >(), \
0 ); }
/** This macro asserts the given condition, and throws an
RuntimeException afterwards.
In production code, no assertion appears, but the
RuntimeException is thrown nevertheless (although without
the given error string, to conserve space).
*/
#define ENSURE_AND_THROW(c, m) if( !(c) ) { \
OSL_ENSURE(false, m); \
throw ::com::sun::star::uno::RuntimeException( \
::rtl::OUString::createFromAscii(BOOST_CURRENT_FUNCTION) + \
::rtl::OUString::createFromAscii(",\n"m), \
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >() ); }
/** This macro asserts the given condition, and returns false
afterwards.
In production code, no assertion appears, but the return is issued
nevertheless.
*/
#define ENSURE_AND_RETURN(c, m) if( !(c) ) { \
OSL_ENSURE(false, m); \
return false; }
#else // ! (OSL_DEBUG_LEVEL > 0)
#define CHECK_AND_THROW(c, m) if( !(c) ) \
throw ::com::sun::star::lang::IllegalArgumentException( \
::rtl::OUString::createFromAscii(BOOST_CURRENT_FUNCTION) + \
::rtl::OUString::createFromAscii(",\n"m), \
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >(), \
0 )
#define ENSURE_AND_THROW(c, m) if( !(c) ) \
throw ::com::sun::star::uno::RuntimeException( \
::rtl::OUString::createFromAscii(BOOST_CURRENT_FUNCTION) + \
::rtl::OUString::createFromAscii(",\n"m), \
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >() )
#define ENSURE_AND_RETURN(c, m) if( !(c) ) \
return false
#endif
// shared_ptr debugging
// --------------------
#ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
#include <boost/shared_ptr.hpp>
::std::size_t find_unreachable_objects( bool );
#ifdef VERBOSE
#define SHARED_PTR_LEFTOVERS(a) OSL_TRACE( "%s\n%s: Unreachable objects still use %d bytes\n", \
BOOST_CURRENT_FUNCTION, a, \
find_unreachable_objects(true) )
#else
/** This macro shows how much memory is still used by shared_ptrs
Use this macro at places in the code where normally all shared_ptr
objects should have been deleted. You'll get the number of bytes
still contained in those objects, which quite possibly are prevented
from deletion by circular references.
*/
#define SHARED_PTR_LEFTOVERS(a) OSL_TRACE( "%s\n%s: Unreachable objects still use %d bytes\n", \
BOOST_CURRENT_FUNCTION, a, \
find_unreachable_objects(false) )
#endif
#else
#define SHARED_PTR_LEFTOVERS(a) ((void)0)
#endif
#endif // ! defined(INCLUDED_CANVAS_DEBUG_HXX)
<commit_msg>INTEGRATION: CWS changefileheader (1.6.136); FILE MERGED 2008/04/01 15:03:01 thb 1.6.136.3: #i85898# Stripping all external header guards 2008/04/01 10:49:24 thb 1.6.136.2: #i85898# Stripping all external header guards 2008/03/28 16:34:51 rt 1.6.136.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: debug.hxx,v $
* $Revision: 1.7 $
*
* 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.
*
************************************************************************/
#if ! defined(INCLUDED_CANVAS_DEBUG_HXX)
#define INCLUDED_CANVAS_DEBUG_HXX
#include <osl/diagnose.h>
#include <rtl/ustring.hxx>
#include <com/sun/star/uno/RuntimeException.hpp>
#include <com/sun/star/lang/IllegalArgumentException.hpp>
#include <boost/current_function.hpp>
// Class invariants
// ----------------
#if OSL_DEBUG_LEVEL > 0
/** This macro asserts the given condition, and throws an
IllegalArgumentException afterwards.
In production code, no assertion appears, but the
IllegalArgumentException is thrown nevertheless (although without
the given error string, to conserve space).
*/
#define CHECK_AND_THROW(c, m) if( !(c) ) { \
OSL_ENSURE(false, m); \
throw ::com::sun::star::lang::IllegalArgumentException( \
::rtl::OUString::createFromAscii(BOOST_CURRENT_FUNCTION) + \
::rtl::OUString::createFromAscii(",\n"m), \
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >(), \
0 ); }
/** This macro asserts the given condition, and throws an
RuntimeException afterwards.
In production code, no assertion appears, but the
RuntimeException is thrown nevertheless (although without
the given error string, to conserve space).
*/
#define ENSURE_AND_THROW(c, m) if( !(c) ) { \
OSL_ENSURE(false, m); \
throw ::com::sun::star::uno::RuntimeException( \
::rtl::OUString::createFromAscii(BOOST_CURRENT_FUNCTION) + \
::rtl::OUString::createFromAscii(",\n"m), \
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >() ); }
/** This macro asserts the given condition, and returns false
afterwards.
In production code, no assertion appears, but the return is issued
nevertheless.
*/
#define ENSURE_AND_RETURN(c, m) if( !(c) ) { \
OSL_ENSURE(false, m); \
return false; }
#else // ! (OSL_DEBUG_LEVEL > 0)
#define CHECK_AND_THROW(c, m) if( !(c) ) \
throw ::com::sun::star::lang::IllegalArgumentException( \
::rtl::OUString::createFromAscii(BOOST_CURRENT_FUNCTION) + \
::rtl::OUString::createFromAscii(",\n"m), \
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >(), \
0 )
#define ENSURE_AND_THROW(c, m) if( !(c) ) \
throw ::com::sun::star::uno::RuntimeException( \
::rtl::OUString::createFromAscii(BOOST_CURRENT_FUNCTION) + \
::rtl::OUString::createFromAscii(",\n"m), \
::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >() )
#define ENSURE_AND_RETURN(c, m) if( !(c) ) \
return false
#endif
// shared_ptr debugging
// --------------------
#ifdef BOOST_SP_ENABLE_DEBUG_HOOKS
#include <boost/shared_ptr.hpp>
::std::size_t find_unreachable_objects( bool );
#ifdef VERBOSE
#define SHARED_PTR_LEFTOVERS(a) OSL_TRACE( "%s\n%s: Unreachable objects still use %d bytes\n", \
BOOST_CURRENT_FUNCTION, a, \
find_unreachable_objects(true) )
#else
/** This macro shows how much memory is still used by shared_ptrs
Use this macro at places in the code where normally all shared_ptr
objects should have been deleted. You'll get the number of bytes
still contained in those objects, which quite possibly are prevented
from deletion by circular references.
*/
#define SHARED_PTR_LEFTOVERS(a) OSL_TRACE( "%s\n%s: Unreachable objects still use %d bytes\n", \
BOOST_CURRENT_FUNCTION, a, \
find_unreachable_objects(false) )
#endif
#else
#define SHARED_PTR_LEFTOVERS(a) ((void)0)
#endif
#endif // ! defined(INCLUDED_CANVAS_DEBUG_HXX)
<|endoftext|> |
<commit_before>/*******************************************************************/
/* XDMF */
/* eXtensible Data Model and Format */
/* */
/* Id : Id */
/* Date : $Date$ */
/* Version : $Revision$ */
/* */
/* Author: */
/* Jerry A. Clarke */
/* clarke@arl.army.mil */
/* US Army Research Laboratory */
/* Aberdeen Proving Ground, MD */
/* */
/* Copyright @ 2002 US Army Research Laboratory */
/* All Rights Reserved */
/* See Copyright.txt or http://www.arl.hpc.mil/ice for details */
/* */
/* This software is distributed WITHOUT ANY WARRANTY; without */
/* even the implied warranty of MERCHANTABILITY or FITNESS */
/* FOR A PARTICULAR PURPOSE. See the above copyright notice */
/* for more information. */
/* */
/*******************************************************************/
#include "XdmfDOM.h"
#include <libxml/parser.h>
#include <libxml/tree.h>
#define xmlNodePtrCAST (xmlNode *)
XdmfDOM *HandleToXdmfDOM( XdmfConstString Source ){
XdmfObject *TempObj;
XdmfDOM *DOM;
TempObj = HandleToXdmfObject( Source );
DOM = (XdmfDOM *)TempObj;
return( DOM );
}
static xmlNode *
XdmfGetNextElement(xmlNode *Node){
xmlNode *NextElement = Node->next;
while(NextElement && (NextElement->type != XML_ELEMENT_NODE)){
NextElement = NextElement->next;
}
return(NextElement);
}
XdmfDOM::XdmfDOM(){
this->WorkingDirectory = 0;
this->NdgmHost = 0;
this->LastDOMGet = new char[256];
this->tree = NULL;
this->xml = NULL;
this->Output = &cout;
this->Input = &cin;
this->Doc = NULL;
this->OutputFileName = 0;
this->InputFileName = 0;
XDMF_STRING_DUPLICATE(this->OutputFileName, "stdout");
XDMF_STRING_DUPLICATE(this->InputFileName, "stdin");
this->SetNdgmHost( "" );
this->SetWorkingDirectory( "" );
}
XdmfDOM::~XdmfDOM(){
if (this->xml != NULL) free(this->xml);
if( ( this->Output != &cout ) && ( this->Output != &cerr ) ) {
ofstream *OldOutput = ( ofstream *)this->Output;
OldOutput->close();
}
if( this->Input != &cin ) {
ifstream *OldInput = ( ifstream *)this->Input;
OldInput->close();
delete this->Input;
this->Input = &cin;
}
if ( this->LastDOMGet )
{
delete [] this->LastDOMGet;
}
this->SetWorkingDirectory(0);
this->SetNdgmHost(0);
if ( this->InputFileName )
{
delete [] this->InputFileName;
}
if ( this->OutputFileName )
{
delete [] this->OutputFileName;
}
}
XdmfInt32
XdmfDOM::GetNumberOfAttributes( XdmfXmlNode Node ){
XdmfInt32 NumberOfAttributes = 0;
xmlAttr *Attr;
Attr = (xmlNodePtrCAST Node)->properties;
while(Attr){
Attr = Attr->next;
NumberOfAttributes++;
}
return( NumberOfAttributes );
}
XdmfConstString
XdmfDOM::GetAttribute( XdmfXmlNode Node, XdmfInt32 Index ){
xmlAttr *Attr;
XdmfConstString AttributeValue = NULL;
XdmfInt32 EIndex = 0;
Attr = (xmlNodePtrCAST Node)->properties;
while( Attr && (EIndex < Index)){
Attr = Attr->next;
EIndex++;
}
if (Attr) {
AttributeValue = (XdmfConstString)xmlGetProp(xmlNodePtrCAST Node, Attr->name);
}
return(AttributeValue);
}
XdmfInt32
XdmfDOM::IsChild( XdmfXmlNode ChildToCheck, XdmfXmlNode Start ) {
XdmfXmlNode Node;
Node = (xmlNodePtrCAST Start)->xmlChildrenNode;
// Check All Children
for(Node=(xmlNodePtrCAST Start)->xmlChildrenNode ; Node ; Node=(xmlNodePtrCAST Node)->next){
if((xmlNodePtrCAST Node)->type = XML_ELEMENT_NODE) {
// Is this it?
if(Node == ChildToCheck) {
return(XDMF_SUCCESS);
}
// Check Its children
if(this->IsChild(ChildToCheck, Node) == XDMF_SUCCESS){
return(XDMF_SUCCESS);
}
}
}
return(XDMF_FAIL);
}
XdmfInt32
XdmfDOM::SetOutputFileName( XdmfConstString Filename ){
if( ( this->Output != &cout ) && ( this->Output != &cerr ) ) {
ofstream *OldOutput = ( ofstream *)this->Output;
OldOutput->close();
}
if( XDMF_WORD_CMP( Filename, "stdin" ) ) {
this->Output = &cout;
} else if( XDMF_WORD_CMP( Filename, "stderr" ) ) {
this->Output = &cerr;
} else {
ofstream *NewOutput = new ofstream( Filename );
if( !NewOutput ) {
XdmfErrorMessage("Can't Open Output File " << Filename );
return( XDMF_FAIL );
}
this->Output = NewOutput;
}
if ( this->OutputFileName )
{
delete [] this->OutputFileName;
}
XDMF_STRING_DUPLICATE(this->InputFileName, Filename);
return( XDMF_SUCCESS );
}
XdmfInt32
XdmfDOM::SetInputFileName( XdmfConstString Filename ){
if( this->Input != &cin ) {
ifstream *OldInput = ( ifstream *)this->Input;
OldInput->close();
delete this->Input;
this->Input = &cin;
}
if( XDMF_WORD_CMP( Filename, "stdin" ) ) {
this->Input = &cin;
} else {
ifstream *NewInput = new ifstream( Filename );
if( !NewInput ) {
XdmfErrorMessage("Can't Open Input File " << Filename );
return( XDMF_FAIL );
}
this->Input = NewInput;
}
if ( this->InputFileName )
{
delete [] this->InputFileName;
}
XDMF_STRING_DUPLICATE(this->InputFileName, Filename);
return( XDMF_SUCCESS );
}
XdmfInt32
XdmfDOM::GenerateHead() {
*this->Output << "<?xml version=\"1.0\" ?>" << endl
<< "<!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\">" << endl
<< "<Xdmf>" << endl;
this->Output->flush();
return( XDMF_SUCCESS );
}
XdmfInt32
XdmfDOM::Puts( XdmfConstString String ){
*this->Output << String;
this->Output->flush();
return( XDMF_SUCCESS );
}
XdmfConstString
XdmfDOM::Gets( void ) {
}
XdmfInt32
XdmfDOM::GenerateTail() {
*this->Output << "</Xdmf>";
this->Output->flush();
return( XDMF_SUCCESS );
}
XdmfConstString
XdmfDOM::Serialize(XdmfXmlNode node) {
XdmfConstString XML = NULL;
xmlBufferPtr BufPtr;
return(XML);
}
XdmfXmlNode
XdmfDOM::__Parse( XdmfConstString inxml) {
xmlNode *Root = NULL;
if(inxml) {
this->Doc = xmlReadMemory(inxml, strlen(inxml), NULL, NULL, 0);
}else{
this->Doc = xmlReadFile(this->GetInputFileName(), NULL, 0);
}
if(this->Doc){
Root = xmlDocGetRootElement((xmlDoc *)this->Doc);
}
return(Root);
}
XdmfInt32
XdmfDOM::Parse(XdmfConstString inxml) {
XdmfXmlNode Root;
XdmfXmlNode Node;
XdmfConstString Attribute;
// Remove Previous Data
// if (this->tree != NULL) XdmfTree_remove(this->tree,C__XdmfXmlNodeDelete);
this->tree = NULL;
// if (this->xml != NULL) free(this->xml);
// this->xml = NULL;
Root = this->__Parse(inxml);
if (Root) {
this->tree = Root;
} else {
return(XDMF_FAIL);
}
Node = this->FindElement( "Xdmf", 0, NULL );
if( Node != NULL ){
Attribute = this->Get( Node, "NdgmHost" );
if( Attribute != NULL ){
XdmfDebug("NdgmHost = " << Attribute );
this->SetNdgmHost( Attribute );
}
Attribute = this->Get( Node, "WorkingDirectory" );
if( Attribute != NULL ){
XdmfDebug("WorkingDirectory = " << Attribute );
this->SetWorkingDirectory( Attribute );
}
}
return( XDMF_SUCCESS );
}
XdmfInt32
XdmfDOM::DeleteNode( XdmfXmlNode Node ) {
return(XDMF_SUCCESS);
}
XdmfInt32
XdmfDOM::InsertFromString(XdmfXmlNode Parent, XdmfConstString inxml) {
XdmfXmlNode NewNode;
NewNode = (XdmfXmlNode)xmlNewDocText((xmlDoc *)this->Doc, (const xmlChar *)inxml);
if(NewNode){
return(this->Insert(Parent, NewNode));
}
return(XDMF_FAIL);
}
XdmfInt32
XdmfDOM::Insert(XdmfXmlNode Parent, XdmfXmlNode Child) {
if(xmlAddChild(xmlNodePtrCAST Parent, xmlNodePtrCAST Child)){
return(XDMF_SUCCESS);
}
return(XDMF_FAIL);
}
XdmfXmlNode
XdmfDOM::GetChild( XdmfInt64 Index, XdmfXmlNode Node ){
xmlNode *Child = (xmlNodePtrCAST Node)->children;
while(Child && Index){
Child = XdmfGetNextElement(Child);
Index--;
}
return(Child);
}
XdmfInt64
XdmfDOM::GetNumberOfChildren( XdmfXmlNode Node ){
XdmfInt64 Index = 0;
xmlNode *Child;
if(!Node){
Node = this->tree;
}
if(!Node) return(NULL);
Child = (xmlNodePtrCAST Node)->children;
while(Child){
Child = XdmfGetNextElement(Child);
Index++;
}
return(Index);
}
XdmfXmlNode
XdmfDOM::GetRoot( void ) {
return(this->tree);
}
XdmfXmlNode
XdmfDOM::FindElement(XdmfConstString TagName, XdmfInt32 Index, XdmfXmlNode Node ) {
XdmfString type = (XdmfString )TagName;
XdmfXmlNode Start;
xmlNode *Child;
// XdmfDebug( " IN FindElement , type = " << type << " Node = " << Node << " # " << occurance);
Start = Node;
if(!Start) {
Start = this->tree;
Child = (xmlNode *)this->tree;
if( !Start ) return( NULL );
}else{
Child = (xmlNodePtrCAST Start)->children;
}
if ( type ) {
if( STRNCASECMP( type, "NULL", 4 ) == 0 ) type = NULL;
}
if ( !type ) {
return(this->GetChild(Index, Start));
} else {
while(Child){
cout << "Checking " << type << " against " << (xmlNodePtrCAST Child)->name << endl;
if(XDMF_WORD_CMP((const char *)type, (const char *)(xmlNodePtrCAST Child)->name)){
if(Index <= 0){
return(Child);
}
Index--;
}
Child = XdmfGetNextElement(Child);
}
}
return(NULL);
}
XdmfXmlNode
XdmfDOM::FindElementByAttribute(XdmfConstString Attribute,
XdmfConstString Value, XdmfInt32 Index, XdmfXmlNode Node ) {
XdmfXmlNode Start;
xmlNode *Child = (xmlNodePtrCAST Node)->children;
Start = Node;
if( !Start) {
Start = this->tree;
}
if( !Start ) return( NULL );
while(Child){
if(XDMF_WORD_CMP((const char *)xmlGetProp(Child, (xmlChar *)Attribute), (const char *)Value)){
if(Index <= 0){
return(Child);
}
Index--;
}
Child = XdmfGetNextElement(Child);
}
return(NULL);
}
XdmfInt32
XdmfDOM::FindNumberOfElements(XdmfConstString TagName, XdmfXmlNode Node ) {
xmlNode *node, *child;
XdmfInt32 Index = 0;
if( !Node ) {
if(!this->tree) return(NULL);
Node = this->tree;
}
node = (xmlNode *)Node;
child = node->children;
if(!child) return(NULL);
while(child){
if(XDMF_WORD_CMP(TagName, (const char *)child->name)){
Index++;
}
Child = XdmfGetNextElement(Child);
}
return(Index);
}
XdmfInt32
XdmfDOM::FindNumberOfElementsByAttribute(XdmfConstString Attribute,
XdmfConstString Value, XdmfXmlNode Node ) {
}
XdmfConstString
XdmfDOM::Get( XdmfXmlNode Node, XdmfConstString Attribute ) {
xmlNode *node;
if( !Node ) {
if(!this->tree) return(NULL);
Node = this->tree;
}
node = (xmlNode *)Node;
if( STRNCASECMP( Attribute, "CDATA", 5 ) == 0 ){
char *txt;
delete [] this->LastDOMGet;
txt = (char *)xmlNodeListGetString((xmlDoc *)this->Doc, node->xmlChildrenNode, 1);
this->LastDOMGet = new char[ strlen(txt) + 2];
strcpy(this->LastDOMGet, txt);
xmlFree(txt);
return((XdmfConstString)this->LastDOMGet);
}
return((XdmfConstString)xmlGetProp(node, (xmlChar *)Attribute));
}
void
XdmfDOM::Set( XdmfXmlNode Node, XdmfConstString Attribute, XdmfConstString Value ){
// What About CDATA ??
xmlSetProp(xmlNodePtrCAST Node, (xmlChar *)Attribute, (xmlChar *)Value);
}
<commit_msg>added serialization<commit_after>/*******************************************************************/
/* XDMF */
/* eXtensible Data Model and Format */
/* */
/* Id : Id */
/* Date : $Date$ */
/* Version : $Revision$ */
/* */
/* Author: */
/* Jerry A. Clarke */
/* clarke@arl.army.mil */
/* US Army Research Laboratory */
/* Aberdeen Proving Ground, MD */
/* */
/* Copyright @ 2002 US Army Research Laboratory */
/* All Rights Reserved */
/* See Copyright.txt or http://www.arl.hpc.mil/ice for details */
/* */
/* This software is distributed WITHOUT ANY WARRANTY; without */
/* even the implied warranty of MERCHANTABILITY or FITNESS */
/* FOR A PARTICULAR PURPOSE. See the above copyright notice */
/* for more information. */
/* */
/*******************************************************************/
#include "XdmfDOM.h"
#include <libxml/parser.h>
#include <libxml/tree.h>
#define xmlNodePtrCAST (xmlNode *)
XdmfDOM *HandleToXdmfDOM( XdmfConstString Source ){
XdmfObject *TempObj;
XdmfDOM *DOM;
TempObj = HandleToXdmfObject( Source );
DOM = (XdmfDOM *)TempObj;
return( DOM );
}
static xmlNode *
XdmfGetNextElement(xmlNode *Node){
xmlNode *NextElement = Node->next;
while(NextElement && (NextElement->type != XML_ELEMENT_NODE)){
NextElement = NextElement->next;
}
return(NextElement);
}
XdmfDOM::XdmfDOM(){
this->WorkingDirectory = 0;
this->NdgmHost = 0;
this->LastDOMGet = new char[256];
this->tree = NULL;
this->xml = NULL;
this->Output = &cout;
this->Input = &cin;
this->Doc = NULL;
this->OutputFileName = 0;
this->InputFileName = 0;
XDMF_STRING_DUPLICATE(this->OutputFileName, "stdout");
XDMF_STRING_DUPLICATE(this->InputFileName, "stdin");
this->SetNdgmHost( "" );
this->SetWorkingDirectory( "" );
}
XdmfDOM::~XdmfDOM(){
if (this->xml != NULL) free(this->xml);
if( ( this->Output != &cout ) && ( this->Output != &cerr ) ) {
ofstream *OldOutput = ( ofstream *)this->Output;
OldOutput->close();
}
if( this->Input != &cin ) {
ifstream *OldInput = ( ifstream *)this->Input;
OldInput->close();
delete this->Input;
this->Input = &cin;
}
if ( this->LastDOMGet )
{
delete [] this->LastDOMGet;
}
this->SetWorkingDirectory(0);
this->SetNdgmHost(0);
if ( this->InputFileName )
{
delete [] this->InputFileName;
}
if ( this->OutputFileName )
{
delete [] this->OutputFileName;
}
}
XdmfInt32
XdmfDOM::GetNumberOfAttributes( XdmfXmlNode Node ){
XdmfInt32 NumberOfAttributes = 0;
xmlAttr *Attr;
Attr = (xmlNodePtrCAST Node)->properties;
while(Attr){
Attr = Attr->next;
NumberOfAttributes++;
}
return( NumberOfAttributes );
}
XdmfConstString
XdmfDOM::GetAttribute( XdmfXmlNode Node, XdmfInt32 Index ){
xmlAttr *Attr;
XdmfConstString AttributeValue = NULL;
XdmfInt32 EIndex = 0;
Attr = (xmlNodePtrCAST Node)->properties;
while( Attr && (EIndex < Index)){
Attr = Attr->next;
EIndex++;
}
if (Attr) {
AttributeValue = (XdmfConstString)xmlGetProp(xmlNodePtrCAST Node, Attr->name);
}
return(AttributeValue);
}
XdmfInt32
XdmfDOM::IsChild( XdmfXmlNode ChildToCheck, XdmfXmlNode Start ) {
XdmfXmlNode Node;
Node = (xmlNodePtrCAST Start)->xmlChildrenNode;
// Check All Children
for(Node=(xmlNodePtrCAST Start)->xmlChildrenNode ; Node ; Node=(xmlNodePtrCAST Node)->next){
if((xmlNodePtrCAST Node)->type = XML_ELEMENT_NODE) {
// Is this it?
if(Node == ChildToCheck) {
return(XDMF_SUCCESS);
}
// Check Its children
if(this->IsChild(ChildToCheck, Node) == XDMF_SUCCESS){
return(XDMF_SUCCESS);
}
}
}
return(XDMF_FAIL);
}
XdmfInt32
XdmfDOM::SetOutputFileName( XdmfConstString Filename ){
if( ( this->Output != &cout ) && ( this->Output != &cerr ) ) {
ofstream *OldOutput = ( ofstream *)this->Output;
OldOutput->close();
}
if( XDMF_WORD_CMP( Filename, "stdin" ) ) {
this->Output = &cout;
} else if( XDMF_WORD_CMP( Filename, "stderr" ) ) {
this->Output = &cerr;
} else {
ofstream *NewOutput = new ofstream( Filename );
if( !NewOutput ) {
XdmfErrorMessage("Can't Open Output File " << Filename );
return( XDMF_FAIL );
}
this->Output = NewOutput;
}
if ( this->OutputFileName )
{
delete [] this->OutputFileName;
}
XDMF_STRING_DUPLICATE(this->InputFileName, Filename);
return( XDMF_SUCCESS );
}
XdmfInt32
XdmfDOM::SetInputFileName( XdmfConstString Filename ){
if( this->Input != &cin ) {
ifstream *OldInput = ( ifstream *)this->Input;
OldInput->close();
delete this->Input;
this->Input = &cin;
}
if( XDMF_WORD_CMP( Filename, "stdin" ) ) {
this->Input = &cin;
} else {
ifstream *NewInput = new ifstream( Filename );
if( !NewInput ) {
XdmfErrorMessage("Can't Open Input File " << Filename );
return( XDMF_FAIL );
}
this->Input = NewInput;
}
if ( this->InputFileName )
{
delete [] this->InputFileName;
}
XDMF_STRING_DUPLICATE(this->InputFileName, Filename);
return( XDMF_SUCCESS );
}
XdmfInt32
XdmfDOM::GenerateHead() {
*this->Output << "<?xml version=\"1.0\" ?>" << endl
<< "<!DOCTYPE Xdmf SYSTEM \"Xdmf.dtd\">" << endl
<< "<Xdmf>" << endl;
this->Output->flush();
return( XDMF_SUCCESS );
}
XdmfInt32
XdmfDOM::Puts( XdmfConstString String ){
*this->Output << String;
this->Output->flush();
return( XDMF_SUCCESS );
}
XdmfConstString
XdmfDOM::Gets( void ) {
}
XdmfInt32
XdmfDOM::GenerateTail() {
*this->Output << "</Xdmf>";
this->Output->flush();
return( XDMF_SUCCESS );
}
XdmfConstString
XdmfDOM::Serialize(XdmfXmlNode Node) {
XdmfConstString XML = NULL;
xmlBufferPtr bufp;
xmlNode *node;
node = (xmlNode *)Node;
if(!node) node = (xmlNode *)this->tree;
if(!node) return(NULL);
bufp = xmlBufferCreate();
if( xmlNodeDump(bufp, (xmlDoc *)this->Doc, node, 0, 0) > 0 ){
XML = (XdmfConstString)bufp->content;
}
return(XML);
}
XdmfXmlNode
XdmfDOM::__Parse( XdmfConstString inxml) {
xmlNode *Root = NULL;
if(inxml) {
this->Doc = xmlReadMemory(inxml, strlen(inxml), NULL, NULL, 0);
}else{
this->Doc = xmlReadFile(this->GetInputFileName(), NULL, 0);
}
if(this->Doc){
Root = xmlDocGetRootElement((xmlDoc *)this->Doc);
}
return(Root);
}
XdmfInt32
XdmfDOM::Parse(XdmfConstString inxml) {
XdmfXmlNode Root;
XdmfXmlNode Node;
XdmfConstString Attribute;
// Remove Previous Data
// if (this->tree != NULL) XdmfTree_remove(this->tree,C__XdmfXmlNodeDelete);
this->tree = NULL;
// if (this->xml != NULL) free(this->xml);
// this->xml = NULL;
Root = this->__Parse(inxml);
if (Root) {
this->tree = Root;
} else {
return(XDMF_FAIL);
}
Node = this->FindElement( "Xdmf", 0, NULL );
if( Node != NULL ){
Attribute = this->Get( Node, "NdgmHost" );
if( Attribute != NULL ){
XdmfDebug("NdgmHost = " << Attribute );
this->SetNdgmHost( Attribute );
}
Attribute = this->Get( Node, "WorkingDirectory" );
if( Attribute != NULL ){
XdmfDebug("WorkingDirectory = " << Attribute );
this->SetWorkingDirectory( Attribute );
}
}
return( XDMF_SUCCESS );
}
XdmfInt32
XdmfDOM::DeleteNode( XdmfXmlNode Node ) {
return(XDMF_SUCCESS);
}
XdmfInt32
XdmfDOM::InsertFromString(XdmfXmlNode Parent, XdmfConstString inxml) {
XdmfXmlNode NewNode;
NewNode = (XdmfXmlNode)xmlNewDocText((xmlDoc *)this->Doc, (const xmlChar *)inxml);
if(NewNode){
return(this->Insert(Parent, NewNode));
}
return(XDMF_FAIL);
}
XdmfInt32
XdmfDOM::Insert(XdmfXmlNode Parent, XdmfXmlNode Child) {
if(xmlAddChild(xmlNodePtrCAST Parent, xmlNodePtrCAST Child)){
return(XDMF_SUCCESS);
}
return(XDMF_FAIL);
}
XdmfXmlNode
XdmfDOM::GetChild( XdmfInt64 Index, XdmfXmlNode Node ){
xmlNode *Child = (xmlNodePtrCAST Node)->children;
while(Child && Index){
Child = XdmfGetNextElement(Child);
Index--;
}
return(Child);
}
XdmfInt64
XdmfDOM::GetNumberOfChildren( XdmfXmlNode Node ){
XdmfInt64 Index = 0;
xmlNode *Child;
if(!Node){
Node = this->tree;
}
if(!Node) return(0);
Child = (xmlNodePtrCAST Node)->children;
while(Child){
Child = XdmfGetNextElement(Child);
Index++;
}
return(Index);
}
XdmfXmlNode
XdmfDOM::GetRoot( void ) {
return(this->tree);
}
XdmfXmlNode
XdmfDOM::FindElement(XdmfConstString TagName, XdmfInt32 Index, XdmfXmlNode Node ) {
XdmfString type = (XdmfString )TagName;
XdmfXmlNode Start;
xmlNode *Child;
// XdmfDebug( " IN FindElement , type = " << type << " Node = " << Node << " # " << occurance);
Start = Node;
if(!Start) {
Start = this->tree;
Child = (xmlNode *)this->tree;
if( !Start ) return( NULL );
}else{
Child = (xmlNodePtrCAST Start)->children;
}
if ( type ) {
if( STRNCASECMP( type, "NULL", 4 ) == 0 ) type = NULL;
}
if ( !type ) {
return(this->GetChild(Index, Start));
} else {
while(Child){
cout << "Checking " << type << " against " << (xmlNodePtrCAST Child)->name << endl;
if(XDMF_WORD_CMP((const char *)type, (const char *)(xmlNodePtrCAST Child)->name)){
if(Index <= 0){
return(Child);
}
Index--;
}
Child = XdmfGetNextElement(Child);
}
}
return(NULL);
}
XdmfXmlNode
XdmfDOM::FindElementByAttribute(XdmfConstString Attribute,
XdmfConstString Value, XdmfInt32 Index, XdmfXmlNode Node ) {
XdmfXmlNode Start;
xmlNode *Child = (xmlNodePtrCAST Node)->children;
Start = Node;
if( !Start) {
Start = this->tree;
}
if( !Start ) return( NULL );
while(Child){
if(XDMF_WORD_CMP((const char *)xmlGetProp(Child, (xmlChar *)Attribute), (const char *)Value)){
if(Index <= 0){
return(Child);
}
Index--;
}
Child = XdmfGetNextElement(Child);
}
return(NULL);
}
XdmfInt32
XdmfDOM::FindNumberOfElements(XdmfConstString TagName, XdmfXmlNode Node ) {
xmlNode *node, *child;
XdmfInt32 Index = 0;
if( !Node ) {
if(!this->tree) return(XDMF_FAIL);
Node = this->tree;
}
node = (xmlNode *)Node;
child = node->children;
if(!child) return(0);
while(child){
if(XDMF_WORD_CMP(TagName, (const char *)child->name)){
Index++;
}
child = XdmfGetNextElement(child);
}
return(Index);
}
XdmfInt32
XdmfDOM::FindNumberOfElementsByAttribute(XdmfConstString Attribute,
XdmfConstString Value, XdmfXmlNode Node ) {
}
XdmfConstString
XdmfDOM::Get( XdmfXmlNode Node, XdmfConstString Attribute ) {
xmlNode *node;
if( !Node ) {
if(!this->tree) return(NULL);
Node = this->tree;
}
node = (xmlNode *)Node;
if( STRNCASECMP( Attribute, "CDATA", 5 ) == 0 ){
char *txt;
delete [] this->LastDOMGet;
txt = (char *)xmlNodeListGetString((xmlDoc *)this->Doc, node->xmlChildrenNode, 1);
this->LastDOMGet = new char[ strlen(txt) + 2];
strcpy(this->LastDOMGet, txt);
xmlFree(txt);
return((XdmfConstString)this->LastDOMGet);
}
return((XdmfConstString)xmlGetProp(node, (xmlChar *)Attribute));
}
void
XdmfDOM::Set( XdmfXmlNode Node, XdmfConstString Attribute, XdmfConstString Value ){
// What About CDATA ??
xmlSetProp(xmlNodePtrCAST Node, (xmlChar *)Attribute, (xmlChar *)Value);
}
<|endoftext|> |
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Data Differential YATL (i.e. libtest) library
*
* Copyright (C) 2012 Data Differential, http://datadifferential.com/
*
* 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.
*
* * The names of its contributors may not 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.
*
*/
#pragma once
#include <pthread.h>
namespace libtest
{
namespace thread
{
class Mutex
{
public:
Mutex() :
_err(0)
{
_err= pthread_mutex_init(&_mutex, NULL);
}
~Mutex()
{
if ((_err= pthread_mutex_destroy(&_mutex)))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_cond_destroy: %s", strerror(_err));
}
}
pthread_mutex_t* handle()
{
if (_err != 0)
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_mutex_init: %s", strerror(_err));
}
return &_mutex;
}
private:
int _err;
pthread_mutex_t _mutex;
};
class ScopedLock
{
public:
ScopedLock(Mutex& mutex_) :
_mutex(mutex_)
{
init();
}
~ScopedLock()
{
int err;
if ((err= pthread_mutex_unlock(_mutex.handle())))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_mutex_unlock: %s", strerror(err));
}
}
Mutex* handle()
{
return &_mutex;
}
private:
void init()
{
int err;
if ((err= pthread_mutex_lock(_mutex.handle())))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_mutex_lock: %s", strerror(err));
}
}
private:
Mutex& _mutex;
};
class Condition
{
public:
Condition()
{
int err;
if ((err= pthread_cond_init(&_cond, NULL)))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_mutex_init: %s", strerror(err));
}
}
~Condition()
{
int err;
if ((err= pthread_cond_destroy(&_cond)))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_cond_destroy: %s", strerror(err));
}
}
void broadcast()
{
int err;
if ((err= pthread_cond_broadcast(&_cond)))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_cond_broadcast: %s", strerror(err));
}
}
void signal()
{
int err;
if ((err= pthread_cond_signal(&_cond)))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_cond_broadcast: %s", strerror(err));
}
}
void wait(ScopedLock& lock_)
{
int err;
if ((err= pthread_cond_wait(&_cond, lock_.handle()->handle())))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_cond_wait: %s", strerror(err));
}
}
private:
pthread_cond_t _cond;
};
class Barrier
{
public:
explicit Barrier(uint32_t count):
_threshold(count),
_count(count),
_generation(0)
{
if (_count == 0)
{
fatal_assert("Zero is an invalid value");
}
}
~Barrier()
{
}
bool wait()
{
ScopedLock l(_mutex);
uint32_t gen = _generation;
if (--_count == 0)
{
_generation++;
_count = _threshold;
_cond.broadcast();
return true;
}
while (gen == _generation)
{
_cond.wait(l);
}
return false;
}
private:
Mutex _mutex;
Condition _cond;
uint32_t _threshold;
uint32_t _count;
uint32_t _generation;
};
class Thread
{
private:
typedef void *(*start_routine_fn) (void *);
public:
template <class Function,class Arg1>
Thread(Function func, Arg1 arg):
_joined(false),
_func((start_routine_fn)func),
_context(arg)
{
int err;
if ((err= pthread_create(&_thread, NULL, entry_func, (void*)this)))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_create: %s", strerror(err));
}
_owner= pthread_self();
}
bool running() const
{
return (pthread_kill(_thread, 0) == 0);
}
bool detached()
{
if (EDEADLK == pthread_join(_thread, NULL))
{
return true;
}
/* Result of pthread_join was EINVAL == detached thread */
return false;
}
bool join()
{
if (_thread == pthread_self())
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "Thread cannot join on itself");
}
if (_owner != pthread_self())
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "Attempt made by a non-owner thead to join on thread");
}
bool ret= false;
{
ScopedLock l(_join_mutex);
if (_joined == false)
{
int err;
if ((err= pthread_join(_thread, NULL)))
{
switch(err)
{
case EINVAL:
break;
case ESRCH:
ret= true;
break;
case EDEADLK:
default:
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_join: %s", strerror(err));
}
}
else
{
ret= true;
}
_joined= true;
}
}
return ret;
}
~Thread()
{
join();
}
protected:
void run()
{
_func(_context);
}
private:
static void * entry_func(void* This)
{
((Thread *)This)->run();
return NULL;
}
private:
bool _joined;
pthread_t _thread;
pthread_t _owner;
start_routine_fn _func;
void* _context;
Mutex _join_mutex;
};
} // namespace thread
} // namespace libtest
<commit_msg>replace throw inside desctructor by abort it's a part of the issue #72<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Data Differential YATL (i.e. libtest) library
*
* Copyright (C) 2012 Data Differential, http://datadifferential.com/
*
* 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.
*
* * The names of its contributors may not 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.
*
*/
#pragma once
#include <pthread.h>
namespace libtest
{
namespace thread
{
class Mutex
{
public:
Mutex() :
_err(0)
{
_err= pthread_mutex_init(&_mutex, NULL);
}
~Mutex()
{
if ((_err= pthread_mutex_destroy(&_mutex)))
{
libtest::stream::make_cerr(LIBYATL_DEFAULT_PARAM) << "pthread_cond_destroy: " << strerror(_err);
abort();
}
}
pthread_mutex_t* handle()
{
if (_err != 0)
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_mutex_init: %s", strerror(_err));
}
return &_mutex;
}
private:
int _err;
pthread_mutex_t _mutex;
};
class ScopedLock
{
public:
ScopedLock(Mutex& mutex_) :
_mutex(mutex_)
{
init();
}
~ScopedLock()
{
int err;
if ((err= pthread_mutex_unlock(_mutex.handle())))
{
libtest::stream::make_cerr(LIBYATL_DEFAULT_PARAM) << "pthread_mutex_unlock: " << strerror(err);
abort();
}
}
Mutex* handle()
{
return &_mutex;
}
private:
void init()
{
int err;
if ((err= pthread_mutex_lock(_mutex.handle())))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_mutex_lock: %s", strerror(err));
}
}
private:
Mutex& _mutex;
};
class Condition
{
public:
Condition()
{
int err;
if ((err= pthread_cond_init(&_cond, NULL)))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_mutex_init: %s", strerror(err));
}
}
~Condition()
{
int err;
if ((err= pthread_cond_destroy(&_cond)))
{
libtest::stream::make_cerr(LIBYATL_DEFAULT_PARAM) << "pthread_cond_destroy: " << strerror(err);
abort();
}
}
void broadcast()
{
int err;
if ((err= pthread_cond_broadcast(&_cond)))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_cond_broadcast: %s", strerror(err));
}
}
void signal()
{
int err;
if ((err= pthread_cond_signal(&_cond)))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_cond_broadcast: %s", strerror(err));
}
}
void wait(ScopedLock& lock_)
{
int err;
if ((err= pthread_cond_wait(&_cond, lock_.handle()->handle())))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_cond_wait: %s", strerror(err));
}
}
private:
pthread_cond_t _cond;
};
class Barrier
{
public:
explicit Barrier(uint32_t count):
_threshold(count),
_count(count),
_generation(0)
{
if (_count == 0)
{
fatal_assert("Zero is an invalid value");
}
}
~Barrier()
{
}
bool wait()
{
ScopedLock l(_mutex);
uint32_t gen = _generation;
if (--_count == 0)
{
_generation++;
_count = _threshold;
_cond.broadcast();
return true;
}
while (gen == _generation)
{
_cond.wait(l);
}
return false;
}
private:
Mutex _mutex;
Condition _cond;
uint32_t _threshold;
uint32_t _count;
uint32_t _generation;
};
class Thread
{
private:
typedef void *(*start_routine_fn) (void *);
public:
template <class Function,class Arg1>
Thread(Function func, Arg1 arg):
_joined(false),
_func((start_routine_fn)func),
_context(arg)
{
int err;
if ((err= pthread_create(&_thread, NULL, entry_func, (void*)this)))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_create: %s", strerror(err));
}
_owner= pthread_self();
}
bool running() const
{
return (pthread_kill(_thread, 0) == 0);
}
bool detached()
{
if (EDEADLK == pthread_join(_thread, NULL))
{
return true;
}
/* Result of pthread_join was EINVAL == detached thread */
return false;
}
bool join()
{
if (_thread == pthread_self())
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "Thread cannot join on itself");
}
if (_owner != pthread_self())
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "Attempt made by a non-owner thead to join on thread");
}
bool ret= false;
{
ScopedLock l(_join_mutex);
if (_joined == false)
{
int err;
if ((err= pthread_join(_thread, NULL)))
{
switch(err)
{
case EINVAL:
break;
case ESRCH:
ret= true;
break;
case EDEADLK:
default:
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_join: %s", strerror(err));
}
}
else
{
ret= true;
}
_joined= true;
}
}
return ret;
}
~Thread()
{
join();
}
protected:
void run()
{
_func(_context);
}
private:
static void * entry_func(void* This)
{
((Thread *)This)->run();
return NULL;
}
private:
bool _joined;
pthread_t _thread;
pthread_t _owner;
start_routine_fn _func;
void* _context;
Mutex _join_mutex;
};
} // namespace thread
} // namespace libtest
<|endoftext|> |
<commit_before>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Data Differential YATL (i.e. libtest) library
*
* Copyright (C) 2012 Data Differential, http://datadifferential.com/
*
* 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.
*
* * The names of its contributors may not 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.
*
*/
#pragma once
#include <pthread.h>
namespace libtest
{
namespace thread
{
class Mutex
{
public:
Mutex() :
_err(0)
{
_err= pthread_mutex_init(&_mutex, NULL);
}
~Mutex()
{
if ((_err= pthread_mutex_destroy(&_mutex)))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_cond_destroy: %s", strerror(_err));
}
}
pthread_mutex_t* handle()
{
if (_err != 0)
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_mutex_init: %s", strerror(_err));
}
return &_mutex;
}
private:
int _err;
pthread_mutex_t _mutex;
};
class ScopedLock
{
public:
ScopedLock(Mutex& mutex_) :
_mutex(mutex_)
{
init();
}
~ScopedLock()
{
int err;
if ((err= pthread_mutex_unlock(_mutex.handle())))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_mutex_unlock: %s", strerror(err));
}
}
Mutex* handle()
{
return &_mutex;
}
private:
void init()
{
int err;
if ((err= pthread_mutex_lock(_mutex.handle())))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_mutex_lock: %s", strerror(err));
}
}
private:
Mutex& _mutex;
};
class Condition
{
public:
Condition()
{
int err;
if ((err= pthread_cond_init(&_cond, NULL)))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_mutex_init: %s", strerror(err));
}
}
~Condition()
{
int err;
if ((err= pthread_cond_destroy(&_cond)))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_cond_destroy: %s", strerror(err));
}
}
void broadcast()
{
int err;
if ((err= pthread_cond_broadcast(&_cond)))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_cond_broadcast: %s", strerror(err));
}
}
void signal()
{
int err;
if ((err= pthread_cond_signal(&_cond)))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_cond_broadcast: %s", strerror(err));
}
}
void wait(ScopedLock& lock_)
{
int err;
if ((err= pthread_cond_wait(&_cond, lock_.handle()->handle())))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_cond_wait: %s", strerror(err));
}
}
private:
pthread_cond_t _cond;
};
class Barrier
{
public:
explicit Barrier(uint32_t count):
_threshold(count),
_count(count),
_generation(0)
{
if (_count == 0)
{
fatal_assert("Zero is an invalid value");
}
}
~Barrier()
{
}
bool wait()
{
ScopedLock l(_mutex);
uint32_t gen = _generation;
if (--_count == 0)
{
_generation++;
_count = _threshold;
_cond.broadcast();
return true;
}
while (gen == _generation)
{
_cond.wait(l);
}
return false;
}
private:
Mutex _mutex;
Condition _cond;
uint32_t _threshold;
uint32_t _count;
uint32_t _generation;
};
class Thread
{
private:
typedef void *(*start_routine_fn) (void *);
public:
template <class Function,class Arg1>
Thread(Function func, Arg1 arg):
_joined(false),
_func((start_routine_fn)func),
_context(arg)
{
int err;
if ((err= pthread_create(&_thread, NULL, entry_func, (void*)this)))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_create: %s", strerror(err));
}
_owner= pthread_self();
}
bool running() const
{
return (pthread_kill(_thread, 0) == 0);
}
bool detached()
{
if (EDEADLK == pthread_join(_thread, NULL))
{
return true;
}
/* Result of pthread_join was EINVAL == detached thread */
return false;
}
bool join()
{
if (_thread == pthread_self())
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "Thread cannot join on itself");
}
if (_owner != pthread_self())
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "Attempt made by a non-owner thead to join on thread");
}
bool ret= false;
{
ScopedLock l(_join_mutex);
if (_joined == false)
{
int err;
if ((err= pthread_join(_thread, NULL)))
{
switch(err)
{
case EINVAL:
break;
case ESRCH:
ret= true;
break;
case EDEADLK:
default:
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_join: %s", strerror(err));
}
}
else
{
ret= true;
}
_joined= true;
}
}
return ret;
}
~Thread()
{
join();
}
protected:
void run()
{
_func(_context);
}
private:
static void * entry_func(void* This)
{
((Thread *)This)->run();
return NULL;
}
private:
bool _joined;
pthread_t _thread;
pthread_t _owner;
start_routine_fn _func;
void* _context;
Mutex _join_mutex;
};
} // namespace thread
} // namespace libtest
<commit_msg>replace throw inside desctructor by abort<commit_after>/* vim:expandtab:shiftwidth=2:tabstop=2:smarttab:
*
* Data Differential YATL (i.e. libtest) library
*
* Copyright (C) 2012 Data Differential, http://datadifferential.com/
*
* 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.
*
* * The names of its contributors may not 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.
*
*/
#pragma once
#include <pthread.h>
namespace libtest
{
namespace thread
{
class Mutex
{
public:
Mutex() :
_err(0)
{
_err= pthread_mutex_init(&_mutex, NULL);
}
~Mutex()
{
if ((_err= pthread_mutex_destroy(&_mutex)))
{
libtest::stream::make_cerr(LIBYATL_DEFAULT_PARAM) << "pthread_cond_destroy: " << strerror(_err);
abort();
}
}
pthread_mutex_t* handle()
{
if (_err != 0)
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_mutex_init: %s", strerror(_err));
}
return &_mutex;
}
private:
int _err;
pthread_mutex_t _mutex;
};
class ScopedLock
{
public:
ScopedLock(Mutex& mutex_) :
_mutex(mutex_)
{
init();
}
~ScopedLock()
{
int err;
if ((err= pthread_mutex_unlock(_mutex.handle())))
{
libtest::stream::make_cerr(LIBYATL_DEFAULT_PARAM) << "pthread_mutex_unlock: " << strerror(err);
abort();
}
}
Mutex* handle()
{
return &_mutex;
}
private:
void init()
{
int err;
if ((err= pthread_mutex_lock(_mutex.handle())))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_mutex_lock: %s", strerror(err));
}
}
private:
Mutex& _mutex;
};
class Condition
{
public:
Condition()
{
int err;
if ((err= pthread_cond_init(&_cond, NULL)))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_mutex_init: %s", strerror(err));
}
}
~Condition()
{
int err;
if ((err= pthread_cond_destroy(&_cond)))
{
libtest::stream::make_cerr(LIBYATL_DEFAULT_PARAM) << "pthread_cond_destroy: " << strerror(err);
abort();
}
}
void broadcast()
{
int err;
if ((err= pthread_cond_broadcast(&_cond)))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_cond_broadcast: %s", strerror(err));
}
}
void signal()
{
int err;
if ((err= pthread_cond_signal(&_cond)))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_cond_broadcast: %s", strerror(err));
}
}
void wait(ScopedLock& lock_)
{
int err;
if ((err= pthread_cond_wait(&_cond, lock_.handle()->handle())))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_cond_wait: %s", strerror(err));
}
}
private:
pthread_cond_t _cond;
};
class Barrier
{
public:
explicit Barrier(uint32_t count):
_threshold(count),
_count(count),
_generation(0)
{
if (_count == 0)
{
fatal_assert("Zero is an invalid value");
}
}
~Barrier()
{
}
bool wait()
{
ScopedLock l(_mutex);
uint32_t gen = _generation;
if (--_count == 0)
{
_generation++;
_count = _threshold;
_cond.broadcast();
return true;
}
while (gen == _generation)
{
_cond.wait(l);
}
return false;
}
private:
Mutex _mutex;
Condition _cond;
uint32_t _threshold;
uint32_t _count;
uint32_t _generation;
};
class Thread
{
private:
typedef void *(*start_routine_fn) (void *);
public:
template <class Function,class Arg1>
Thread(Function func, Arg1 arg):
_joined(false),
_func((start_routine_fn)func),
_context(arg)
{
int err;
if ((err= pthread_create(&_thread, NULL, entry_func, (void*)this)))
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_create: %s", strerror(err));
}
_owner= pthread_self();
}
bool running() const
{
return (pthread_kill(_thread, 0) == 0);
}
bool detached()
{
if (EDEADLK == pthread_join(_thread, NULL))
{
return true;
}
/* Result of pthread_join was EINVAL == detached thread */
return false;
}
bool join()
{
if (_thread == pthread_self())
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "Thread cannot join on itself");
}
if (_owner != pthread_self())
{
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "Attempt made by a non-owner thead to join on thread");
}
bool ret= false;
{
ScopedLock l(_join_mutex);
if (_joined == false)
{
int err;
if ((err= pthread_join(_thread, NULL)))
{
switch(err)
{
case EINVAL:
break;
case ESRCH:
ret= true;
break;
case EDEADLK:
default:
throw libtest::fatal(LIBYATL_DEFAULT_PARAM, "pthread_join: %s", strerror(err));
}
}
else
{
ret= true;
}
_joined= true;
}
}
return ret;
}
~Thread()
{
join();
}
protected:
void run()
{
_func(_context);
}
private:
static void * entry_func(void* This)
{
((Thread *)This)->run();
return NULL;
}
private:
bool _joined;
pthread_t _thread;
pthread_t _owner;
start_routine_fn _func;
void* _context;
Mutex _join_mutex;
};
} // namespace thread
} // namespace libtest
<|endoftext|> |
<commit_before>#ifndef JSPROC_JOB_HPP_
#define JSPROC_JOB_HPP_
#include "containers/archive/archive.hpp"
namespace jsproc {
// Declared out here so that its branches are visible at top-level. Only
// actually used in job_result_t.
enum job_result_type_t {
JOB_SUCCESS = 0,
JOB_UNKNOWN_ERROR,
// If we couldn't deserialize the initial job function or instance.
// `data.archive_result` contains more info.
JOB_INITIAL_READ_FAILURE,
// If we couldn't deserialize something during the job's execution itself.
// `data.archive_result` contains more info.
JOB_READ_FAILURE,
// If writing failed at some point during the job's execution. No additional
// data.
JOB_WRITE_FAILURE,
// Indicates that the worker process executing this job should shut down.
JOB_SHUTDOWN,
};
struct job_result_t {
job_result_type_t type;
// Extra data regarding the failure mode.
union {
archive_result_t archive_result;
} data;
};
typedef void (*job_func_t)(job_result_t *result, read_stream_t *read, write_stream_t *write);
// Abstract base class for jobs.
class job_t {
public:
virtual ~job_t() {}
// Called on main process side.
virtual void send(write_stream_t *stream) = 0;
virtual void rdb_serialize(write_message_t &msg) = 0;
// Called on worker process side.
virtual archive_result_t rdb_deserialize(read_stream_t *s) = 0;
virtual void run_job(job_result_t *result, read_stream_t *input, write_stream_t *output) = 0;
};
template <typename instance_t>
class magic_job_t : public job_t {
public:
// The job_func_t that runs this kind of job.
static void job_runner(job_result_t *result, read_stream_t *input, write_stream_t *output) {
// Get the job instance.
instance_t job;
archive_result_t res = deserialize(input, &job);
if (res != ARCHIVE_SUCCESS) {
result->type = JOB_INITIAL_READ_FAILURE;
result->data.archive_result = res;
return;
}
// Run it.
job.run_job(result, input, output);
}
void send(write_stream_t *stream) {
write_message_t msg;
// This is kind of a hack.
//
// We send the address of the function that runs the job we want (namely
// job_runner). This works only because the address of job_runner is
// statically known and the worker processes we are sending to are
// fork()s of ourselves, and so have the same address space layout.
const job_func_t funcptr = &job_runner;
msg.append(&funcptr, sizeof funcptr);
// We send ourselves over as well; run_job will deserialize us.
rdb_serialize(msg);
send_write_message(stream, &msg);
}
};
} // namespace jsproc
#endif // JSPROC_JOB_HPP_
<commit_msg>replace magic_job_t with send_job, which works<commit_after>#ifndef JSPROC_JOB_HPP_
#define JSPROC_JOB_HPP_
#include "containers/archive/archive.hpp"
namespace jsproc {
// Declared out here so that its branches are visible at top-level. Only
// actually used in job_result_t.
enum job_result_type_t {
JOB_SUCCESS = 0,
JOB_UNKNOWN_ERROR,
// If we couldn't deserialize the initial job function or instance.
// `data.archive_result` contains more info.
JOB_INITIAL_READ_FAILURE,
// If we couldn't deserialize something during the job's execution itself.
// `data.archive_result` contains more info.
JOB_READ_FAILURE,
// If writing failed at some point during the job's execution. No additional
// data.
JOB_WRITE_FAILURE,
// Indicates that the worker process executing this job should shut down.
JOB_SHUTDOWN,
};
struct job_result_t {
job_result_type_t type;
// Extra data regarding the failure mode.
union {
archive_result_t archive_result;
} data;
};
typedef void (*job_func_t)(job_result_t *result, read_stream_t *read, write_stream_t *write);
// Abstract base class for jobs.
class job_t {
public:
virtual ~job_t() {}
// Called on worker process side.
virtual void run_job(job_result_t *result, read_stream_t *input, write_stream_t *output) = 0;
};
// Returns 0 on success, -1 on failure.
template <typename instance_t>
int send_job(write_stream_t *stream, const instance_t &job) {
struct garbage {
static void job_runner(job_result_t *result, read_stream_t *input, write_stream_t *output) {
// Get the job instance.
instance_t job;
archive_result_t res = deserialize(input, &job);
if (res != ARCHIVE_SUCCESS) {
result->type = JOB_INITIAL_READ_FAILURE;
result->data.archive_result = res;
return;
}
// Run it.
job.run_job(result, input, output);
}
};
write_message_t msg;
// This is kind of a hack.
//
// We send the address of the function that runs the job we want (namely
// job_runner). This works only because the address of job_runner is
// statically known and the worker processes we are sending to are
// fork()s of ourselves, and so have the same address space layout.
const job_func_t funcptr = &garbage::job_runner;
msg.append(&funcptr, sizeof funcptr);
// We send the job over as well; job_runner will deserialize us.
msg << job;
return send_write_message(stream, &msg);
}
} // namespace jsproc
#endif // JSPROC_JOB_HPP_
<|endoftext|> |
<commit_before>/**
* @file cf_test.cpp
* @author Mudit Raj Gupta
*
* Test file for CF class.
*/
#include <mlpack/core.hpp>
#include <mlpack/methods/cf/cf.hpp>
#include <iostream>
#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"
BOOST_AUTO_TEST_SUITE(CFTest);
using namespace mlpack;
using namespace mlpack::cf;
using namespace std;
/**
* Make sure that the rated item is not recommended
*/
BOOST_AUTO_TEST_CASE(CFConstructorTest)
{
//Matrix to save data
arma::mat dataset, retDataset;
//Loading GroupLens data
data::Load("GroupLens100k.csv", dataset);
//Number of Recommendations
size_t numRecs = 10;
//Number of users for similarity
size_t numUsersForSimilarity = 5;
//Creating a CF object
CF c(numRecs, numUsersForSimilarity, dataset);
//Getter
retDataset = c.Data();
//Checking for parameters
BOOST_REQUIRE_EQUAL(c.NumRecs(), numRecs);
BOOST_REQUIRE_EQUAL(c.NumUsersForSimilarity(), numUsersForSimilarity);
//Checking Data
BOOST_REQUIRE_EQUAL(retDataset.n_rows, dataset.n_rows);
BOOST_REQUIRE_EQUAL(retDataset.n_cols, dataset.n_cols);
//Checking Values
for (size_t i=0;i<dataset.n_rows;i++)
for (size_t j=0;j<dataset.n_cols;j++)
BOOST_REQUIRE_EQUAL(retDataset(i,j),dataset(i,j));
}
/*
* Make sure that correct number of recommendations
* are generated when query set. Default Case.
*/
BOOST_AUTO_TEST_CASE(CFGetRecommendationsAllUsersTest)
{
//Dummy number of recommendations
size_t numRecs = 3;
//GroupLens100k.csv dataset has 943 users
size_t numUsers = 943;
//Matrix to save recommednations
arma::Mat<size_t> recommendations;
//Matrix to save data
arma::mat dataset;
//Loading GroupLens data
data::Load("GroupLens100k.csv", dataset);
//Creating a CF object
CF c(dataset);
//Setting Number of Recommendations
c.NumRecs(numRecs);
//Generating Recommendations when query set is not specified
c.GetRecommendations(recommendations);
//Checking if correct number of Recommendations are generated
BOOST_REQUIRE_EQUAL(recommendations.n_rows, numRecs);
//Checking if recommendations are generated for all users
BOOST_REQUIRE_EQUAL(recommendations.n_cols, numUsers);
}
/*
* Make sure that the recommendations are genrated
* for queried users only
*/
BOOST_AUTO_TEST_CASE(CFGetRecommendationsQueriedUserTest)
{
//Number of users for which recommendations are seeked
size_t numUsers = 10;
//Default number of recommendations
size_t numRecsDefault = 5;
//Creaating dummy query set
arma::Col<size_t> users = arma::zeros<arma::Col<size_t> >(numUsers,1);
for (size_t i=0;i<numUsers;i++)
users(i) = i+1;
//Matrix to save recommednations
arma::Mat<size_t> recommendations;
//Matrix to save data
arma::mat dataset;
//Loading GroupLens data
data::Load("GroupLens100k.csv", dataset);
//Creating a CF object
CF c(dataset);
//Generating Recommendations when query set is not specified
c.GetRecommendations(recommendations, users);
//Checking if correct number of Recommendations are generated
BOOST_REQUIRE_EQUAL(recommendations.n_rows, numRecsDefault);
//Checking if recommendations are generated for all users
BOOST_REQUIRE_EQUAL(recommendations.n_cols, numUsers);
}
BOOST_AUTO_TEST_SUITE_END();
<commit_msg>Clean up CFTest, and fix some comments that were wrong.<commit_after>/**
* @file cf_test.cpp
* @author Mudit Raj Gupta
*
* Test file for CF class.
*/
#include <mlpack/core.hpp>
#include <mlpack/methods/cf/cf.hpp>
#include <iostream>
#include <boost/test/unit_test.hpp>
#include "old_boost_test_definitions.hpp"
BOOST_AUTO_TEST_SUITE(CFTest);
using namespace mlpack;
using namespace mlpack::cf;
using namespace std;
/**
* Make sure that the constructor works okay.
*/
BOOST_AUTO_TEST_CASE(CFConstructorTest)
{
// Load GroupLens data.
arma::mat dataset;
data::Load("GroupLens100k.csv", dataset);
// Number of recommendations (not the default).
const size_t numRecs = 15;
// Number of users for similarity (not the default).
const size_t numUsersForSimilarity = 8;
CF c(numRecs, numUsersForSimilarity, dataset);
// Check parameters.
BOOST_REQUIRE_EQUAL(c.NumRecs(), numRecs);
BOOST_REQUIRE_EQUAL(c.NumUsersForSimilarity(), numUsersForSimilarity);
// Check data.
BOOST_REQUIRE_EQUAL(c.Data().n_rows, dataset.n_rows);
BOOST_REQUIRE_EQUAL(c.Data().n_cols, dataset.n_cols);
// Check values (this should be superfluous...).
for (size_t i = 0; i < dataset.n_rows; i++)
for (size_t j = 0; j < dataset.n_cols; j++)
BOOST_REQUIRE_EQUAL(c.Data()(i, j), dataset(i, j));
}
/**
* Make sure that correct number of recommendations are generated when query
* set. Default case.
*/
BOOST_AUTO_TEST_CASE(CFGetRecommendationsAllUsersTest)
{
// Dummy number of recommendations.
size_t numRecs = 3;
// GroupLens100k.csv dataset has 943 users.
size_t numUsers = 943;
// Matrix to save recommendations into.
arma::Mat<size_t> recommendations;
// Load GroupLens data.
arma::mat dataset;
data::Load("GroupLens100k.csv", dataset);
// Creat a CF object
CF c(dataset);
// Set number of recommendations.
c.NumRecs(numRecs);
// Generate recommendations when query set is not specified.
c.GetRecommendations(recommendations);
// Check if correct number of recommendations are generated.
BOOST_REQUIRE_EQUAL(recommendations.n_rows, numRecs);
// Check if recommendations are generated for all users.
BOOST_REQUIRE_EQUAL(recommendations.n_cols, numUsers);
}
/**
* Make sure that the recommendations are generated for queried users only.
*/
BOOST_AUTO_TEST_CASE(CFGetRecommendationsQueriedUserTest)
{
// Number of users that we will search for recommendations for.
size_t numUsers = 10;
// Default number of recommendations.
size_t numRecsDefault = 5;
// Creaate dummy query set.
arma::Col<size_t> users = arma::zeros<arma::Col<size_t> >(numUsers, 1);
for (size_t i = 0; i < numUsers; i++)
users(i) = i + 1;
// Matrix to save recommendations into.
arma::Mat<size_t> recommendations;
// Load GroupLens data.
arma::mat dataset;
data::Load("GroupLens100k.csv", dataset);
CF c(dataset);
// Generate recommendations when query set is specified.
c.GetRecommendations(recommendations, users);
// Check if correct number of recommendations are generated.
BOOST_REQUIRE_EQUAL(recommendations.n_rows, numRecsDefault);
// Check if recommendations are generated for the right number of users.
BOOST_REQUIRE_EQUAL(recommendations.n_cols, numUsers);
}
BOOST_AUTO_TEST_SUITE_END();
<|endoftext|> |
<commit_before>#include <ros/ros.h>
//ROS libraries
#include <tf/transform_datatypes.h>
//ROS messages
#include <std_msgs/Float32.h>
#include <std_msgs/String.h>
#include <geometry_msgs/Quaternion.h>
#include <geometry_msgs/QuaternionStamped.h>
#include <geometry_msgs/Twist.h>
#include <nav_msgs/Odometry.h>
#include <sensor_msgs/Imu.h>
#include <sensor_msgs/Range.h>
#include <std_msgs/UInt8.h>
//Package include
#include <usbSerial.h>
using namespace std;
//aBridge functions
void driveCommandHandler(const geometry_msgs::Twist::ConstPtr& message);
void fingerAngleHandler(const std_msgs::Float32::ConstPtr& angle);
void wristAngleHandler(const std_msgs::Float32::ConstPtr& angle);
void serialActivityTimer(const ros::TimerEvent& e);
void publishRosTopics();
void parseData(string data);
std::string getHumanFriendlyTime();
//Globals
geometry_msgs::QuaternionStamped fingerAngle;
geometry_msgs::QuaternionStamped wristAngle;
sensor_msgs::Imu imu;
nav_msgs::Odometry odom;
sensor_msgs::Range sonarLeft;
sensor_msgs::Range sonarCenter;
sensor_msgs::Range sonarRight;
USBSerial usb;
const int baud = 115200;
char dataCmd[] = "d\n";
char moveCmd[16];
char host[128];
const float deltaTime = 0.1; //abridge's update interval
int currentMode = 0;
string publishedName;
float heartbeat_publish_interval = 2;
//PID constants and arrays
const int histArrayLength = 1000;
float velFF = 0; //velocity feed forward
int stepV = 0; //keeps track of the point in the evArray for adding new error each update cycle.
float evArray[histArrayLength]; //history array of previous error for (arraySize/hz) seconds (error Velocity Array)
float velError[4] = {0,0,0,0}; //contains current velocity error and error 3 steps in the past.
int stepY = 0; //keeps track of the point in the eyArray for adding new error each update cycle.
float eyArray[histArrayLength]; //history array of previous error for (arraySize/hz) seconds (error Yaw Array)
float yawError[4] = {0,0,0,0}; //contains current yaw error and error 3 steps in the past.
float prevLin = 0;
float prevYaw = 0;
ros::Time prevDriveCommandUpdateTime;
//Publishers
ros::Publisher fingerAnglePublish;
ros::Publisher wristAnglePublish;
ros::Publisher imuPublish;
ros::Publisher odomPublish;
ros::Publisher sonarLeftPublish;
ros::Publisher sonarCenterPublish;
ros::Publisher sonarRightPublish;
ros::Publisher infoLogPublisher;
ros::Publisher heartbeatPublisher;
//Subscribers
ros::Subscriber driveControlSubscriber;
ros::Subscriber fingerAngleSubscriber;
ros::Subscriber wristAngleSubscriber;
ros::Subscriber modeSubscriber;
//Timers
ros::Timer publishTimer;
ros::Timer publish_heartbeat_timer;
//Callback handlers
void publishHeartBeatTimerEventHandler(const ros::TimerEvent& event);
void modeHandler(const std_msgs::UInt8::ConstPtr& message);
int main(int argc, char **argv) {
gethostname(host, sizeof (host));
string hostname(host);
ros::init(argc, argv, (hostname + "_ABRIDGE"));
ros::NodeHandle param("~");
string devicePath;
param.param("device", devicePath, string("/dev/ttyUSB0"));
usb.openUSBPort(devicePath, baud);
sleep(5);
ros::NodeHandle aNH;
if (argc >= 2) {
publishedName = argv[1];
cout << "Welcome to the world of tomorrow " << publishedName << "! ABridge module started." << endl;
} else {
publishedName = hostname;
cout << "No Name Selected. Default is: " << publishedName << endl;
}
fingerAnglePublish = aNH.advertise<geometry_msgs::QuaternionStamped>((publishedName + "/fingerAngle/prev_cmd"), 10);
wristAnglePublish = aNH.advertise<geometry_msgs::QuaternionStamped>((publishedName + "/wristAngle/prev_cmd"), 10);
imuPublish = aNH.advertise<sensor_msgs::Imu>((publishedName + "/imu"), 10);
odomPublish = aNH.advertise<nav_msgs::Odometry>((publishedName + "/odom"), 10);
sonarLeftPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarLeft"), 10);
sonarCenterPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarCenter"), 10);
sonarRightPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarRight"), 10);
infoLogPublisher = aNH.advertise<std_msgs::String>("/infoLog", 1, true);
heartbeatPublisher = aNH.advertise<std_msgs::String>((publishedName + "/abridge/heartbeat"), 1, true);
driveControlSubscriber = aNH.subscribe((publishedName + "/driveControl"), 10, driveCommandHandler);
fingerAngleSubscriber = aNH.subscribe((publishedName + "/fingerAngle/cmd"), 1, fingerAngleHandler);
wristAngleSubscriber = aNH.subscribe((publishedName + "/wristAngle/cmd"), 1, wristAngleHandler);
modeSubscriber = aNH.subscribe((publishedName + "/mode"), 1, modeHandler);
publishTimer = aNH.createTimer(ros::Duration(deltaTime), serialActivityTimer);
publish_heartbeat_timer = aNH.createTimer(ros::Duration(heartbeat_publish_interval), publishHeartBeatTimerEventHandler);
imu.header.frame_id = publishedName+"/base_link";
odom.header.frame_id = publishedName+"/odom";
odom.child_frame_id = publishedName+"/base_link";
for (int i = 0; i < histArrayLength; i++)
{
evArray[i] = 0;
eyArray[i] = 0;
}
prevDriveCommandUpdateTime = ros::Time::now();
ros::spin();
return EXIT_SUCCESS;
}
//This command handler recives a linear velocity setpoint and a angular yaw error
//and produces a command output for the left and right motors of the robot.
//See the following paper for description of PID controllers.
//Bennett, Stuart (November 1984). "Nicholas Minorsky and the automatic steering of ships". IEEE Control Systems Magazine. 4 (4): 10–15. doi:10.1109/MCS.1984.1104827. ISSN 0272-1708.
void driveCommandHandler(const geometry_msgs::Twist::ConstPtr& message) {
float left = (message->linear.x); //target linear velocity in meters per second
float right = (message->angular.z); //angular error in radians
if (currentMode == 1) //manual control
{
float linear = left * 255;
float angular = right * 255; //scale values between -255 and 255;
left = linear - angular;
right = linear + angular;
if (left >255)
{
left = 255;
}
else if (left < -255)
{
left = -255;
}
if (right >255)
{
right = 255;
}
else if (right < -255)
{
right = -255;
}
}
int leftInt = left;
int rightInt = right;
sprintf(moveCmd, "v,%d,%d\n", leftInt, rightInt); //format data for arduino into c string
usb.sendData(moveCmd); //send movement command to arduino over usb
memset(&moveCmd, '\0', sizeof (moveCmd)); //clear the movement command string
}
// The finger and wrist handlers receive gripper angle commands in floating point
// radians, write them to a string and send that to the arduino
// for processing.
void fingerAngleHandler(const std_msgs::Float32::ConstPtr& angle) {
char cmd[16]={'\0'};
// Avoid dealing with negative exponents which confuse the conversion to string by checking if the angle is small
if (angle->data < 0.01) {
// 'f' indicates this is a finger command to the arduino
sprintf(cmd, "f,0\n");
} else {
sprintf(cmd, "f,%.4g\n", angle->data);
}
usb.sendData(cmd);
memset(&cmd, '\0', sizeof (cmd));
}
void wristAngleHandler(const std_msgs::Float32::ConstPtr& angle) {
char cmd[16]={'\0'};
// Avoid dealing with negative exponents which confuse the conversion to string by checking if the angle is small
if (angle->data < 0.01) {
// 'w' indicates this is a wrist command to the arduino
sprintf(cmd, "w,0\n");
} else {
sprintf(cmd, "w,%.4g\n", angle->data);
}
usb.sendData(cmd);
memset(&cmd, '\0', sizeof (cmd));
}
void serialActivityTimer(const ros::TimerEvent& e) {
usb.sendData(dataCmd);
parseData(usb.readData());
publishRosTopics();
}
void publishRosTopics() {
fingerAnglePublish.publish(fingerAngle);
wristAnglePublish.publish(wristAngle);
imuPublish.publish(imu);
odomPublish.publish(odom);
sonarLeftPublish.publish(sonarLeft);
sonarCenterPublish.publish(sonarCenter);
sonarRightPublish.publish(sonarRight);
}
void parseData(string str) {
istringstream oss(str);
string sentence;
while (getline(oss, sentence, '\n')) {
istringstream wss(sentence);
string word;
vector<string> dataSet;
while (getline(wss, word, ',')) {
dataSet.push_back(word);
}
if (dataSet.size() >= 3 && dataSet.at(1) == "1") {
if (dataSet.at(0) == "GRF") {
fingerAngle.header.stamp = ros::Time::now();
fingerAngle.quaternion = tf::createQuaternionMsgFromRollPitchYaw(atof(dataSet.at(2).c_str()), 0.0, 0.0);
}
else if (dataSet.at(0) == "GRW") {
wristAngle.header.stamp = ros::Time::now();
wristAngle.quaternion = tf::createQuaternionMsgFromRollPitchYaw(atof(dataSet.at(2).c_str()), 0.0, 0.0);
}
else if (dataSet.at(0) == "IMU") {
imu.header.stamp = ros::Time::now();
imu.linear_acceleration.x = atof(dataSet.at(2).c_str());
imu.linear_acceleration.y = 0; //atof(dataSet.at(3).c_str());
imu.linear_acceleration.z = atof(dataSet.at(4).c_str());
imu.angular_velocity.x = atof(dataSet.at(5).c_str());
imu.angular_velocity.y = atof(dataSet.at(6).c_str());
imu.angular_velocity.z = atof(dataSet.at(7).c_str());
imu.orientation = tf::createQuaternionMsgFromRollPitchYaw(atof(dataSet.at(8).c_str()), atof(dataSet.at(9).c_str()), atof(dataSet.at(10).c_str()));
}
else if (dataSet.at(0) == "ODOM") {
odom.header.stamp = ros::Time::now();
odom.pose.pose.position.x += atof(dataSet.at(2).c_str()) / 100.0;
odom.pose.pose.position.y += atof(dataSet.at(3).c_str()) / 100.0;
odom.pose.pose.position.z = 0.0;
odom.pose.pose.orientation = tf::createQuaternionMsgFromYaw(atof(dataSet.at(4).c_str()));
odom.twist.twist.linear.x = atof(dataSet.at(5).c_str()) / 100.0;
odom.twist.twist.linear.y = atof(dataSet.at(6).c_str()) / 100.0;
odom.twist.twist.angular.z = atof(dataSet.at(7).c_str());
}
else if (dataSet.at(0) == "USL") {
sonarLeft.header.stamp = ros::Time::now();
sonarLeft.range = atof(dataSet.at(2).c_str()) / 100.0;
}
else if (dataSet.at(0) == "USC") {
sonarCenter.header.stamp = ros::Time::now();
sonarCenter.range = atof(dataSet.at(2).c_str()) / 100.0;
}
else if (dataSet.at(0) == "USR") {
sonarRight.header.stamp = ros::Time::now();
sonarRight.range = atof(dataSet.at(2).c_str()) / 100.0;
}
}
}
}
void modeHandler(const std_msgs::UInt8::ConstPtr& message) {
currentMode = message->data;
}
void publishHeartBeatTimerEventHandler(const ros::TimerEvent&) {
std_msgs::String msg;
msg.data = "";
heartbeatPublisher.publish(msg);
}
<commit_msg>Bug fix: Limited the max motor command values<commit_after>#include <ros/ros.h>
//ROS libraries
#include <tf/transform_datatypes.h>
//ROS messages
#include <std_msgs/Float32.h>
#include <std_msgs/String.h>
#include <geometry_msgs/Quaternion.h>
#include <geometry_msgs/QuaternionStamped.h>
#include <geometry_msgs/Twist.h>
#include <nav_msgs/Odometry.h>
#include <sensor_msgs/Imu.h>
#include <sensor_msgs/Range.h>
#include <std_msgs/UInt8.h>
//Package include
#include <usbSerial.h>
using namespace std;
//aBridge functions
void driveCommandHandler(const geometry_msgs::Twist::ConstPtr& message);
void fingerAngleHandler(const std_msgs::Float32::ConstPtr& angle);
void wristAngleHandler(const std_msgs::Float32::ConstPtr& angle);
void serialActivityTimer(const ros::TimerEvent& e);
void publishRosTopics();
void parseData(string data);
std::string getHumanFriendlyTime();
//Globals
geometry_msgs::QuaternionStamped fingerAngle;
geometry_msgs::QuaternionStamped wristAngle;
sensor_msgs::Imu imu;
nav_msgs::Odometry odom;
sensor_msgs::Range sonarLeft;
sensor_msgs::Range sonarCenter;
sensor_msgs::Range sonarRight;
USBSerial usb;
const int baud = 115200;
char dataCmd[] = "d\n";
char moveCmd[16];
char host[128];
const float deltaTime = 0.1; //abridge's update interval
int currentMode = 0;
string publishedName;
float heartbeat_publish_interval = 2;
//PID constants and arrays
const int histArrayLength = 1000;
float velFF = 0; //velocity feed forward
int stepV = 0; //keeps track of the point in the evArray for adding new error each update cycle.
float evArray[histArrayLength]; //history array of previous error for (arraySize/hz) seconds (error Velocity Array)
float velError[4] = {0,0,0,0}; //contains current velocity error and error 3 steps in the past.
int stepY = 0; //keeps track of the point in the eyArray for adding new error each update cycle.
float eyArray[histArrayLength]; //history array of previous error for (arraySize/hz) seconds (error Yaw Array)
float yawError[4] = {0,0,0,0}; //contains current yaw error and error 3 steps in the past.
float prevLin = 0;
float prevYaw = 0;
ros::Time prevDriveCommandUpdateTime;
//Publishers
ros::Publisher fingerAnglePublish;
ros::Publisher wristAnglePublish;
ros::Publisher imuPublish;
ros::Publisher odomPublish;
ros::Publisher sonarLeftPublish;
ros::Publisher sonarCenterPublish;
ros::Publisher sonarRightPublish;
ros::Publisher infoLogPublisher;
ros::Publisher heartbeatPublisher;
//Subscribers
ros::Subscriber driveControlSubscriber;
ros::Subscriber fingerAngleSubscriber;
ros::Subscriber wristAngleSubscriber;
ros::Subscriber modeSubscriber;
//Timers
ros::Timer publishTimer;
ros::Timer publish_heartbeat_timer;
//Callback handlers
void publishHeartBeatTimerEventHandler(const ros::TimerEvent& event);
void modeHandler(const std_msgs::UInt8::ConstPtr& message);
int main(int argc, char **argv) {
gethostname(host, sizeof (host));
string hostname(host);
ros::init(argc, argv, (hostname + "_ABRIDGE"));
ros::NodeHandle param("~");
string devicePath;
param.param("device", devicePath, string("/dev/ttyUSB0"));
usb.openUSBPort(devicePath, baud);
sleep(5);
ros::NodeHandle aNH;
if (argc >= 2) {
publishedName = argv[1];
cout << "Welcome to the world of tomorrow " << publishedName << "! ABridge module started." << endl;
} else {
publishedName = hostname;
cout << "No Name Selected. Default is: " << publishedName << endl;
}
fingerAnglePublish = aNH.advertise<geometry_msgs::QuaternionStamped>((publishedName + "/fingerAngle/prev_cmd"), 10);
wristAnglePublish = aNH.advertise<geometry_msgs::QuaternionStamped>((publishedName + "/wristAngle/prev_cmd"), 10);
imuPublish = aNH.advertise<sensor_msgs::Imu>((publishedName + "/imu"), 10);
odomPublish = aNH.advertise<nav_msgs::Odometry>((publishedName + "/odom"), 10);
sonarLeftPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarLeft"), 10);
sonarCenterPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarCenter"), 10);
sonarRightPublish = aNH.advertise<sensor_msgs::Range>((publishedName + "/sonarRight"), 10);
infoLogPublisher = aNH.advertise<std_msgs::String>("/infoLog", 1, true);
heartbeatPublisher = aNH.advertise<std_msgs::String>((publishedName + "/abridge/heartbeat"), 1, true);
driveControlSubscriber = aNH.subscribe((publishedName + "/driveControl"), 10, driveCommandHandler);
fingerAngleSubscriber = aNH.subscribe((publishedName + "/fingerAngle/cmd"), 1, fingerAngleHandler);
wristAngleSubscriber = aNH.subscribe((publishedName + "/wristAngle/cmd"), 1, wristAngleHandler);
modeSubscriber = aNH.subscribe((publishedName + "/mode"), 1, modeHandler);
publishTimer = aNH.createTimer(ros::Duration(deltaTime), serialActivityTimer);
publish_heartbeat_timer = aNH.createTimer(ros::Duration(heartbeat_publish_interval), publishHeartBeatTimerEventHandler);
imu.header.frame_id = publishedName+"/base_link";
odom.header.frame_id = publishedName+"/odom";
odom.child_frame_id = publishedName+"/base_link";
for (int i = 0; i < histArrayLength; i++)
{
evArray[i] = 0;
eyArray[i] = 0;
}
prevDriveCommandUpdateTime = ros::Time::now();
ros::spin();
return EXIT_SUCCESS;
}
//This command handler recives a linear velocity setpoint and a angular yaw error
//and produces a command output for the left and right motors of the robot.
//See the following paper for description of PID controllers.
//Bennett, Stuart (November 1984). "Nicholas Minorsky and the automatic steering of ships". IEEE Control Systems Magazine. 4 (4): 10–15. doi:10.1109/MCS.1984.1104827. ISSN 0272-1708.
void driveCommandHandler(const geometry_msgs::Twist::ConstPtr& message) {
float left = (message->linear.x); //target linear velocity in meters per second
float right = (message->angular.z); //angular error in radians
// Cap motor commands at 120. Experimentally determined that high values (tested 180 and 255) can cause
// the hardware to fail when the robot moves itself too violently.
int max_motor_cmd = 120;
// Assumes left and right are always between -1 and 1
float linear = left * max_motor_cmd;
float angular = right * max_motor_cmd;
left = linear - angular;
right = linear + angular;
if (left > max_motor_cmd)
{
left = max_motor_cmd;
}
else if (left < -max_motor_cmd)
{
left = - max_motor_cmd;
}
if (right > max_motor_cmd)
{
right = max_motor_cmd;
}
else if (right < -max_motor_cmd)
{
right = -max_motor_cmd;
}
int leftInt = left;
int rightInt = right;
sprintf(moveCmd, "v,%d,%d\n", leftInt, rightInt); //format data for arduino into c string
usb.sendData(moveCmd); //send movement command to arduino over usb
memset(&moveCmd, '\0', sizeof (moveCmd)); //clear the movement command string
}
// The finger and wrist handlers receive gripper angle commands in floating point
// radians, write them to a string and send that to the arduino
// for processing.
void fingerAngleHandler(const std_msgs::Float32::ConstPtr& angle) {
char cmd[16]={'\0'};
// Avoid dealing with negative exponents which confuse the conversion to string by checking if the angle is small
if (angle->data < 0.01) {
// 'f' indicates this is a finger command to the arduino
sprintf(cmd, "f,0\n");
} else {
sprintf(cmd, "f,%.4g\n", angle->data);
}
usb.sendData(cmd);
memset(&cmd, '\0', sizeof (cmd));
}
void wristAngleHandler(const std_msgs::Float32::ConstPtr& angle) {
char cmd[16]={'\0'};
// Avoid dealing with negative exponents which confuse the conversion to string by checking if the angle is small
if (angle->data < 0.01) {
// 'w' indicates this is a wrist command to the arduino
sprintf(cmd, "w,0\n");
} else {
sprintf(cmd, "w,%.4g\n", angle->data);
}
usb.sendData(cmd);
memset(&cmd, '\0', sizeof (cmd));
}
void serialActivityTimer(const ros::TimerEvent& e) {
usb.sendData(dataCmd);
parseData(usb.readData());
publishRosTopics();
}
void publishRosTopics() {
fingerAnglePublish.publish(fingerAngle);
wristAnglePublish.publish(wristAngle);
imuPublish.publish(imu);
odomPublish.publish(odom);
sonarLeftPublish.publish(sonarLeft);
sonarCenterPublish.publish(sonarCenter);
sonarRightPublish.publish(sonarRight);
}
void parseData(string str) {
istringstream oss(str);
string sentence;
while (getline(oss, sentence, '\n')) {
istringstream wss(sentence);
string word;
vector<string> dataSet;
while (getline(wss, word, ',')) {
dataSet.push_back(word);
}
if (dataSet.size() >= 3 && dataSet.at(1) == "1") {
if (dataSet.at(0) == "GRF") {
fingerAngle.header.stamp = ros::Time::now();
fingerAngle.quaternion = tf::createQuaternionMsgFromRollPitchYaw(atof(dataSet.at(2).c_str()), 0.0, 0.0);
}
else if (dataSet.at(0) == "GRW") {
wristAngle.header.stamp = ros::Time::now();
wristAngle.quaternion = tf::createQuaternionMsgFromRollPitchYaw(atof(dataSet.at(2).c_str()), 0.0, 0.0);
}
else if (dataSet.at(0) == "IMU") {
imu.header.stamp = ros::Time::now();
imu.linear_acceleration.x = atof(dataSet.at(2).c_str());
imu.linear_acceleration.y = 0; //atof(dataSet.at(3).c_str());
imu.linear_acceleration.z = atof(dataSet.at(4).c_str());
imu.angular_velocity.x = atof(dataSet.at(5).c_str());
imu.angular_velocity.y = atof(dataSet.at(6).c_str());
imu.angular_velocity.z = atof(dataSet.at(7).c_str());
imu.orientation = tf::createQuaternionMsgFromRollPitchYaw(atof(dataSet.at(8).c_str()), atof(dataSet.at(9).c_str()), atof(dataSet.at(10).c_str()));
}
else if (dataSet.at(0) == "ODOM") {
odom.header.stamp = ros::Time::now();
odom.pose.pose.position.x += atof(dataSet.at(2).c_str()) / 100.0;
odom.pose.pose.position.y += atof(dataSet.at(3).c_str()) / 100.0;
odom.pose.pose.position.z = 0.0;
odom.pose.pose.orientation = tf::createQuaternionMsgFromYaw(atof(dataSet.at(4).c_str()));
odom.twist.twist.linear.x = atof(dataSet.at(5).c_str()) / 100.0;
odom.twist.twist.linear.y = atof(dataSet.at(6).c_str()) / 100.0;
odom.twist.twist.angular.z = atof(dataSet.at(7).c_str());
}
else if (dataSet.at(0) == "USL") {
sonarLeft.header.stamp = ros::Time::now();
sonarLeft.range = atof(dataSet.at(2).c_str()) / 100.0;
}
else if (dataSet.at(0) == "USC") {
sonarCenter.header.stamp = ros::Time::now();
sonarCenter.range = atof(dataSet.at(2).c_str()) / 100.0;
}
else if (dataSet.at(0) == "USR") {
sonarRight.header.stamp = ros::Time::now();
sonarRight.range = atof(dataSet.at(2).c_str()) / 100.0;
}
}
}
}
void modeHandler(const std_msgs::UInt8::ConstPtr& message) {
currentMode = message->data;
}
void publishHeartBeatTimerEventHandler(const ros::TimerEvent&) {
std_msgs::String msg;
msg.data = "";
heartbeatPublisher.publish(msg);
}
<|endoftext|> |
<commit_before>//
// (c) Copyright 2017 DESY,ESS
//
// This file is part of h5cpp.
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor
// Boston, MA 02110-1301 USA
// ===========================================================================
//
// Authors:
// Jan Kotanski <jan.kotanski@desy.de>
// Created on: Jul 06, 2018
//
#include <catch2/catch.hpp>
#include <h5cpp/core/filesystem.hpp>
#include <h5cpp/file/functions.hpp>
#include <h5cpp/hdf5.hpp>
#include <h5cpp/node/group.hpp>
#include <string>
using namespace hdf5;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wexit-time-destructor"
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
namespace {
static const std::string filename = "file_close_test.h5";
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
SCENARIO("Closing file") {
{
hdf5::property::FileAccessList fapl;
hdf5::property::FileCreationList fcpl;
auto f =
file::create(filename, file::AccessFlags::TRUNCATE, fcpl, fapl);
f.root()
.attributes
.create("HDF5_version", datatype::create<std::string>(),
dataspace::Scalar())
.write(std::string("1.0.0"));
}
GIVEN("A strong closing policy") {
hdf5::property::FileAccessList fapl;
fapl.close_degree(hdf5::property::CloseDegree::STRONG);
REQUIRE(fapl.close_degree() == hdf5::property::CloseDegree::STRONG);
THEN("the all remaining objects will be close along with the file") {
auto file = hdf5::file::open(filename,
hdf5::file::AccessFlags::READONLY, fapl);
auto root_group = file.root();
auto attr = root_group.attributes[0];
REQUIRE(file.count_open_objects(file::SearchFlags::ALL) == 3u);
// with CloseDegree::STRONG it closes also root_group and attr
REQUIRE_NOTHROW(file.close());
REQUIRE_FALSE(root_group.is_valid());
REQUIRE_FALSE(attr.is_valid());
REQUIRE_FALSE(file.is_valid());
// everything is close so file can be reopen in a different mode, i.e.
// READWRITE
REQUIRE_NOTHROW(
hdf5::file::open(filename, hdf5::file::AccessFlags::READWRITE));
}
}
GIVEN("the default closing policy") {
hdf5::property::FileAccessList fapl;
REQUIRE(fapl.close_degree() == hdf5::property::CloseDegree::DEFAULT);
auto file = hdf5::file::open(filename,
hdf5::file::AccessFlags::READONLY, fapl);
auto root_group = file.root();
auto attr = root_group.attributes[0];
REQUIRE(file.count_open_objects(file::SearchFlags::ALL) == 3ul);
// without CloseDegree::STRONG root_group and attr are still open
REQUIRE_NOTHROW(file.close());
REQUIRE(root_group.is_valid());
REQUIRE(attr.is_valid());
// file cannot be reopen in a different mode, i.e. READWRITE
REQUIRE_THROWS_AS(
hdf5::file::open(filename, hdf5::file::AccessFlags::READWRITE),
std::runtime_error);
}
}
<commit_msg>Fixed warning pragma<commit_after>//
// (c) Copyright 2017 DESY,ESS
//
// This file is part of h5cpp.
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor
// Boston, MA 02110-1301 USA
// ===========================================================================
//
// Authors:
// Jan Kotanski <jan.kotanski@desy.de>
// Created on: Jul 06, 2018
//
#include <catch2/catch.hpp>
#include <h5cpp/core/filesystem.hpp>
#include <h5cpp/file/functions.hpp>
#include <h5cpp/hdf5.hpp>
#include <h5cpp/node/group.hpp>
#include <string>
using namespace hdf5;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wexit-time-destructors"
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
namespace {
static const std::string filename = "file_close_test.h5";
}
#ifdef __clang__
#pragma clang diagnostic pop
#endif
SCENARIO("Closing file") {
{
hdf5::property::FileAccessList fapl;
hdf5::property::FileCreationList fcpl;
auto f =
file::create(filename, file::AccessFlags::TRUNCATE, fcpl, fapl);
f.root()
.attributes
.create("HDF5_version", datatype::create<std::string>(),
dataspace::Scalar())
.write(std::string("1.0.0"));
}
GIVEN("A strong closing policy") {
hdf5::property::FileAccessList fapl;
fapl.close_degree(hdf5::property::CloseDegree::STRONG);
REQUIRE(fapl.close_degree() == hdf5::property::CloseDegree::STRONG);
THEN("the all remaining objects will be close along with the file") {
auto file = hdf5::file::open(filename,
hdf5::file::AccessFlags::READONLY, fapl);
auto root_group = file.root();
auto attr = root_group.attributes[0];
REQUIRE(file.count_open_objects(file::SearchFlags::ALL) == 3u);
// with CloseDegree::STRONG it closes also root_group and attr
REQUIRE_NOTHROW(file.close());
REQUIRE_FALSE(root_group.is_valid());
REQUIRE_FALSE(attr.is_valid());
REQUIRE_FALSE(file.is_valid());
// everything is close so file can be reopen in a different mode, i.e.
// READWRITE
REQUIRE_NOTHROW(
hdf5::file::open(filename, hdf5::file::AccessFlags::READWRITE));
}
}
GIVEN("the default closing policy") {
hdf5::property::FileAccessList fapl;
REQUIRE(fapl.close_degree() == hdf5::property::CloseDegree::DEFAULT);
auto file = hdf5::file::open(filename,
hdf5::file::AccessFlags::READONLY, fapl);
auto root_group = file.root();
auto attr = root_group.attributes[0];
REQUIRE(file.count_open_objects(file::SearchFlags::ALL) == 3ul);
// without CloseDegree::STRONG root_group and attr are still open
REQUIRE_NOTHROW(file.close());
REQUIRE(root_group.is_valid());
REQUIRE(attr.is_valid());
// file cannot be reopen in a different mode, i.e. READWRITE
REQUIRE_THROWS_AS(
hdf5::file::open(filename, hdf5::file::AccessFlags::READWRITE),
std::runtime_error);
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2006 The Regents of The University of Michigan
* 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 copyright holders 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.
*
* Authors: Gabe Black
*/
/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* The software must be used only for Non-Commercial Use which means any
* use which is NOT directed to receiving any direct monetary
* compensation for, or commercial advantage from such use. Illustrative
* examples of non-commercial use are academic research, personal study,
* teaching, education and corporate research & development.
* Illustrative examples of commercial use are distributing products for
* commercial advantage and providing services using the software for
* commercial advantage.
*
* If you wish to use this software or functionality therein that may be
* covered by patents for commercial use, please contact:
* Director of Intellectual Property Licensing
* Office of Strategy and Technology
* Hewlett-Packard Company
* 1501 Page Mill Road
* Palo Alto, California 94304
*
* 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 COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission. No right of
* sublicense is granted herewith. Derivatives of the software and
* output created using the software may be prepared, but only for
* Non-Commercial Uses. Derivatives of the software may be shared with
* others provided: (i) the others agree to abide by the list of
* conditions herein which includes the Non-Commercial Use restrictions;
* and (ii) such Derivatives of the software include the above copyright
* notice to acknowledge the contribution from this software where
* applicable, this list of conditions and the disclaimer below.
*
* 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.
*
* Authors: Gabe Black
*/
#ifndef __ARCH_X86_MISCREGFILE_HH__
#define __ARCH_X86_MISCREGFILE_HH__
#include "arch/x86/faults.hh"
#include "arch/x86/types.hh"
#include <string>
class Checkpoint;
namespace X86ISA
{
std::string getMiscRegName(RegIndex);
//These will have to be updated in the future.
const int NumMiscArchRegs = 0;
const int NumMiscRegs = 0;
class MiscRegFile
{
void clear();
MiscRegFile()
{
clear();
}
MiscReg readReg(int miscReg);
MiscReg readRegWithEffect(int miscReg, ThreadContext *tc);
void setReg(int miscReg, const MiscReg &val);
void setRegWithEffect(int miscReg,
const MiscReg &val, ThreadContext *tc);
void serialize(std::ostream & os);
void unserialize(Checkpoint * cp, const std::string §ion);
void copyMiscRegs(ThreadContext * tc);
};
}
#endif //__ARCH_X86_MISCREGFILE_HH__
<commit_msg>Make the constructor (and all the other functions) public<commit_after>/*
* Copyright (c) 2003-2006 The Regents of The University of Michigan
* 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 copyright holders 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.
*
* Authors: Gabe Black
*/
/*
* Copyright (c) 2007 The Hewlett-Packard Development Company
* All rights reserved.
*
* Redistribution and use of this software in source and binary forms,
* with or without modification, are permitted provided that the
* following conditions are met:
*
* The software must be used only for Non-Commercial Use which means any
* use which is NOT directed to receiving any direct monetary
* compensation for, or commercial advantage from such use. Illustrative
* examples of non-commercial use are academic research, personal study,
* teaching, education and corporate research & development.
* Illustrative examples of commercial use are distributing products for
* commercial advantage and providing services using the software for
* commercial advantage.
*
* If you wish to use this software or functionality therein that may be
* covered by patents for commercial use, please contact:
* Director of Intellectual Property Licensing
* Office of Strategy and Technology
* Hewlett-Packard Company
* 1501 Page Mill Road
* Palo Alto, California 94304
*
* 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 COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission. No right of
* sublicense is granted herewith. Derivatives of the software and
* output created using the software may be prepared, but only for
* Non-Commercial Uses. Derivatives of the software may be shared with
* others provided: (i) the others agree to abide by the list of
* conditions herein which includes the Non-Commercial Use restrictions;
* and (ii) such Derivatives of the software include the above copyright
* notice to acknowledge the contribution from this software where
* applicable, this list of conditions and the disclaimer below.
*
* 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.
*
* Authors: Gabe Black
*/
#ifndef __ARCH_X86_MISCREGFILE_HH__
#define __ARCH_X86_MISCREGFILE_HH__
#include "arch/x86/faults.hh"
#include "arch/x86/types.hh"
#include <string>
class Checkpoint;
namespace X86ISA
{
std::string getMiscRegName(RegIndex);
//These will have to be updated in the future.
const int NumMiscArchRegs = 0;
const int NumMiscRegs = 0;
class MiscRegFile
{
public:
void clear();
MiscRegFile()
{
clear();
}
MiscReg readReg(int miscReg);
MiscReg readRegWithEffect(int miscReg, ThreadContext *tc);
void setReg(int miscReg, const MiscReg &val);
void setRegWithEffect(int miscReg,
const MiscReg &val, ThreadContext *tc);
void serialize(std::ostream & os);
void unserialize(Checkpoint * cp, const std::string §ion);
void copyMiscRegs(ThreadContext * tc);
};
}
#endif //__ARCH_X86_MISCREGFILE_HH__
<|endoftext|> |
<commit_before>/*
* Copyright 2011 The LibYuv Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "libyuv/cpu_id.h"
#if defined(_MSC_VER)
#include <intrin.h> // For __cpuidex()
#endif
#if !defined(__pnacl__) && !defined(__CLR_VER) && \
!defined(__native_client__) && (defined(_M_IX86) || defined(_M_X64)) && \
defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 160040219)
#include <immintrin.h> // For _xgetbv()
#endif
// For ArmCpuCaps() but unittested on all platforms
#include <stdio.h>
#include <string.h>
#ifdef __cplusplus
namespace libyuv {
extern "C" {
#endif
// For functions that use the stack and have runtime checks for overflow,
// use SAFEBUFFERS to avoid additional check.
#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 160040219) && \
!defined(__clang__)
#define SAFEBUFFERS __declspec(safebuffers)
#else
#define SAFEBUFFERS
#endif
// cpu_info_ variable for SIMD instruction sets detected.
LIBYUV_API int cpu_info_ = 0;
// TODO(fbarchard): Consider using int for cpuid so casting is not needed.
// Low level cpuid for X86.
#if (defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \
defined(__x86_64__)) && \
!defined(__pnacl__) && !defined(__CLR_VER)
LIBYUV_API
void CpuId(int info_eax, int info_ecx, int* cpu_info) {
#if defined(_MSC_VER)
// Visual C version uses intrinsic or inline x86 assembly.
#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 160040219)
__cpuidex(cpu_info, info_eax, info_ecx);
#elif defined(_M_IX86)
__asm {
mov eax, info_eax
mov ecx, info_ecx
mov edi, cpu_info
cpuid
mov [edi], eax
mov [edi + 4], ebx
mov [edi + 8], ecx
mov [edi + 12], edx
}
#else // Visual C but not x86
if (info_ecx == 0) {
__cpuid(cpu_info, info_eax);
} else {
cpu_info[3] = cpu_info[2] = cpu_info[1] = cpu_info[0] = 0u;
}
#endif
// GCC version uses inline x86 assembly.
#else // defined(_MSC_VER)
int info_ebx, info_edx;
asm volatile(
#if defined(__i386__) && defined(__PIC__)
// Preserve ebx for fpic 32 bit.
"mov %%ebx, %%edi \n"
"cpuid \n"
"xchg %%edi, %%ebx \n"
: "=D"(info_ebx),
#else
"cpuid \n"
: "=b"(info_ebx),
#endif // defined( __i386__) && defined(__PIC__)
"+a"(info_eax), "+c"(info_ecx), "=d"(info_edx));
cpu_info[0] = info_eax;
cpu_info[1] = info_ebx;
cpu_info[2] = info_ecx;
cpu_info[3] = info_edx;
#endif // defined(_MSC_VER)
}
#else // (defined(_M_IX86) || defined(_M_X64) ...
LIBYUV_API
void CpuId(int eax, int ecx, int* cpu_info) {
(void)eax;
(void)ecx;
cpu_info[0] = cpu_info[1] = cpu_info[2] = cpu_info[3] = 0;
}
#endif
// For VS2010 and earlier emit can be used:
// _asm _emit 0x0f _asm _emit 0x01 _asm _emit 0xd0 // For VS2010 and earlier.
// __asm {
// xor ecx, ecx // xcr 0
// xgetbv
// mov xcr0, eax
// }
// For VS2013 and earlier 32 bit, the _xgetbv(0) optimizer produces bad code.
// https://code.google.com/p/libyuv/issues/detail?id=529
#if defined(_M_IX86) && (_MSC_VER < 1900)
#pragma optimize("g", off)
#endif
#if (defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \
defined(__x86_64__)) && \
!defined(__pnacl__) && !defined(__CLR_VER) && !defined(__native_client__)
// X86 CPUs have xgetbv to detect OS saves high parts of ymm registers.
int GetXCR0() {
int xcr0 = 0;
#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 160040219)
xcr0 = (int)_xgetbv(0); // VS2010 SP1 required. NOLINT
#elif defined(__i386__) || defined(__x86_64__)
asm(".byte 0x0f, 0x01, 0xd0" : "=a"(xcr0) : "c"(0) : "%edx");
#endif // defined(__i386__) || defined(__x86_64__)
return xcr0;
}
#else
// xgetbv unavailable to query for OSSave support. Return 0.
#define GetXCR0() 0
#endif // defined(_M_IX86) || defined(_M_X64) ..
// Return optimization to previous setting.
#if defined(_M_IX86) && (_MSC_VER < 1900)
#pragma optimize("g", on)
#endif
// based on libvpx arm_cpudetect.c
// For Arm, but public to allow testing on any CPU
LIBYUV_API SAFEBUFFERS int ArmCpuCaps(const char* cpuinfo_name) {
char cpuinfo_line[512];
FILE* f = fopen(cpuinfo_name, "r");
if (!f) {
// Assume Neon if /proc/cpuinfo is unavailable.
// This will occur for Chrome sandbox for Pepper or Render process.
return kCpuHasNEON;
}
while (fgets(cpuinfo_line, sizeof(cpuinfo_line) - 1, f)) {
if (memcmp(cpuinfo_line, "Features", 8) == 0) {
char* p = strstr(cpuinfo_line, " neon");
if (p && (p[5] == ' ' || p[5] == '\n')) {
fclose(f);
return kCpuHasNEON;
}
// aarch64 uses asimd for Neon.
p = strstr(cpuinfo_line, " asimd");
if (p) {
fclose(f);
return kCpuHasNEON;
}
}
}
fclose(f);
return 0;
}
// TODO(fbarchard): Consider read_msa_ir().
// TODO(fbarchard): Add unittest.
LIBYUV_API SAFEBUFFERS int MipsCpuCaps(const char* cpuinfo_name,
const char ase[]) {
char cpuinfo_line[512];
FILE* f = fopen(cpuinfo_name, "r");
if (!f) {
// ase enabled if /proc/cpuinfo is unavailable.
if (strcmp(ase, " msa") == 0) {
return kCpuHasMSA;
}
if (strcmp(ase, " mmi") == 0) {
return kCpuHasMMI;
}
return 0;
}
while (fgets(cpuinfo_line, sizeof(cpuinfo_line) - 1, f)) {
if (memcmp(cpuinfo_line, "ASEs implemented", 16) == 0) {
char* p = strstr(cpuinfo_line, ase);
if (p) {
fclose(f);
if (strcmp(ase, " msa") == 0) {
return kCpuHasMSA;
}
return 0;
}
} else if (memcmp(cpuinfo_line, "cpu model", 9) == 0) {
char* p = strstr(cpuinfo_line, "Loongson-3");
if (p) {
fclose(f);
if (strcmp(ase, " mmi") == 0) {
return kCpuHasMMI;
}
return 0;
}
}
}
fclose(f);
return 0;
}
static SAFEBUFFERS int GetCpuFlags(void) {
int cpu_info = 0;
#if !defined(__pnacl__) && !defined(__CLR_VER) && \
(defined(__x86_64__) || defined(_M_X64) || defined(__i386__) || \
defined(_M_IX86))
int cpu_info0[4] = {0, 0, 0, 0};
int cpu_info1[4] = {0, 0, 0, 0};
int cpu_info7[4] = {0, 0, 0, 0};
CpuId(0, 0, cpu_info0);
CpuId(1, 0, cpu_info1);
if (cpu_info0[0] >= 7) {
CpuId(7, 0, cpu_info7);
}
cpu_info = kCpuHasX86 | ((cpu_info1[3] & 0x04000000) ? kCpuHasSSE2 : 0) |
((cpu_info1[2] & 0x00000200) ? kCpuHasSSSE3 : 0) |
((cpu_info1[2] & 0x00080000) ? kCpuHasSSE41 : 0) |
((cpu_info1[2] & 0x00100000) ? kCpuHasSSE42 : 0) |
((cpu_info7[1] & 0x00000200) ? kCpuHasERMS : 0);
// AVX requires OS saves YMM registers.
if (((cpu_info1[2] & 0x1c000000) == 0x1c000000) && // AVX and OSXSave
((GetXCR0() & 6) == 6)) { // Test OS saves YMM registers
cpu_info |= kCpuHasAVX | ((cpu_info7[1] & 0x00000020) ? kCpuHasAVX2 : 0) |
((cpu_info1[2] & 0x00001000) ? kCpuHasFMA3 : 0) |
((cpu_info1[2] & 0x20000000) ? kCpuHasF16C : 0);
// Detect AVX512bw
if ((GetXCR0() & 0xe0) == 0xe0) {
cpu_info |= (cpu_info7[1] & 0x40000000) ? kCpuHasAVX512BW : 0;
cpu_info |= (cpu_info7[1] & 0x80000000) ? kCpuHasAVX512VL : 0;
cpu_info |= (cpu_info7[2] & 0x00000002) ? kCpuHasAVX512VBMI : 0;
cpu_info |= (cpu_info7[2] & 0x00000040) ? kCpuHasAVX512VBMI2 : 0;
cpu_info |= (cpu_info7[2] & 0x00001000) ? kCpuHasAVX512VBITALG : 0;
cpu_info |= (cpu_info7[2] & 0x00004000) ? kCpuHasAVX512VPOPCNTDQ : 0;
cpu_info |= (cpu_info7[2] & 0x00000100) ? kCpuHasGFNI : 0;
}
}
#endif
#if defined(__mips__) && defined(__linux__)
#if defined(__mips_msa)
cpu_info = MipsCpuCaps("/proc/cpuinfo", " msa");
#elif defined(_MIPS_ARCH_LOONGSON3A)
cpu_info = MipsCpuCaps("/proc/cpuinfo", " mmi");
#endif
cpu_info |= kCpuHasMIPS;
#endif
#if defined(__arm__) || defined(__aarch64__)
// gcc -mfpu=neon defines __ARM_NEON__
// __ARM_NEON__ generates code that requires Neon. NaCL also requires Neon.
// For Linux, /proc/cpuinfo can be tested but without that assume Neon.
#if defined(__ARM_NEON__) || defined(__native_client__) || !defined(__linux__)
cpu_info = kCpuHasNEON;
// For aarch64(arm64), /proc/cpuinfo's feature is not complete, e.g. no neon
// flag in it.
// So for aarch64, neon enabling is hard coded here.
#endif
#if defined(__aarch64__)
cpu_info = kCpuHasNEON;
#else
// Linux arm parse text file for neon detect.
cpu_info = ArmCpuCaps("/proc/cpuinfo");
#endif
cpu_info |= kCpuHasARM;
#endif // __arm__
cpu_info |= kCpuInitialized;
return cpu_info;
}
// Note that use of this function is not thread safe.
LIBYUV_API
int MaskCpuFlags(int enable_flags) {
int cpu_info = GetCpuFlags() & enable_flags;
SetCpuFlags(cpu_info);
return cpu_info;
}
LIBYUV_API
int InitCpuFlags(void) {
return MaskCpuFlags(-1);
}
#ifdef __cplusplus
} // extern "C"
} // namespace libyuv
#endif
<commit_msg>Refine function MipsCpuCaps.<commit_after>/*
* Copyright 2011 The LibYuv Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "libyuv/cpu_id.h"
#if defined(_MSC_VER)
#include <intrin.h> // For __cpuidex()
#endif
#if !defined(__pnacl__) && !defined(__CLR_VER) && \
!defined(__native_client__) && (defined(_M_IX86) || defined(_M_X64)) && \
defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 160040219)
#include <immintrin.h> // For _xgetbv()
#endif
// For ArmCpuCaps() but unittested on all platforms
#include <stdio.h>
#include <string.h>
#ifdef __cplusplus
namespace libyuv {
extern "C" {
#endif
// For functions that use the stack and have runtime checks for overflow,
// use SAFEBUFFERS to avoid additional check.
#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 160040219) && \
!defined(__clang__)
#define SAFEBUFFERS __declspec(safebuffers)
#else
#define SAFEBUFFERS
#endif
// cpu_info_ variable for SIMD instruction sets detected.
LIBYUV_API int cpu_info_ = 0;
// TODO(fbarchard): Consider using int for cpuid so casting is not needed.
// Low level cpuid for X86.
#if (defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \
defined(__x86_64__)) && \
!defined(__pnacl__) && !defined(__CLR_VER)
LIBYUV_API
void CpuId(int info_eax, int info_ecx, int* cpu_info) {
#if defined(_MSC_VER)
// Visual C version uses intrinsic or inline x86 assembly.
#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 160040219)
__cpuidex(cpu_info, info_eax, info_ecx);
#elif defined(_M_IX86)
__asm {
mov eax, info_eax
mov ecx, info_ecx
mov edi, cpu_info
cpuid
mov [edi], eax
mov [edi + 4], ebx
mov [edi + 8], ecx
mov [edi + 12], edx
}
#else // Visual C but not x86
if (info_ecx == 0) {
__cpuid(cpu_info, info_eax);
} else {
cpu_info[3] = cpu_info[2] = cpu_info[1] = cpu_info[0] = 0u;
}
#endif
// GCC version uses inline x86 assembly.
#else // defined(_MSC_VER)
int info_ebx, info_edx;
asm volatile(
#if defined(__i386__) && defined(__PIC__)
// Preserve ebx for fpic 32 bit.
"mov %%ebx, %%edi \n"
"cpuid \n"
"xchg %%edi, %%ebx \n"
: "=D"(info_ebx),
#else
"cpuid \n"
: "=b"(info_ebx),
#endif // defined( __i386__) && defined(__PIC__)
"+a"(info_eax), "+c"(info_ecx), "=d"(info_edx));
cpu_info[0] = info_eax;
cpu_info[1] = info_ebx;
cpu_info[2] = info_ecx;
cpu_info[3] = info_edx;
#endif // defined(_MSC_VER)
}
#else // (defined(_M_IX86) || defined(_M_X64) ...
LIBYUV_API
void CpuId(int eax, int ecx, int* cpu_info) {
(void)eax;
(void)ecx;
cpu_info[0] = cpu_info[1] = cpu_info[2] = cpu_info[3] = 0;
}
#endif
// For VS2010 and earlier emit can be used:
// _asm _emit 0x0f _asm _emit 0x01 _asm _emit 0xd0 // For VS2010 and earlier.
// __asm {
// xor ecx, ecx // xcr 0
// xgetbv
// mov xcr0, eax
// }
// For VS2013 and earlier 32 bit, the _xgetbv(0) optimizer produces bad code.
// https://code.google.com/p/libyuv/issues/detail?id=529
#if defined(_M_IX86) && (_MSC_VER < 1900)
#pragma optimize("g", off)
#endif
#if (defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \
defined(__x86_64__)) && \
!defined(__pnacl__) && !defined(__CLR_VER) && !defined(__native_client__)
// X86 CPUs have xgetbv to detect OS saves high parts of ymm registers.
int GetXCR0() {
int xcr0 = 0;
#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 160040219)
xcr0 = (int)_xgetbv(0); // VS2010 SP1 required. NOLINT
#elif defined(__i386__) || defined(__x86_64__)
asm(".byte 0x0f, 0x01, 0xd0" : "=a"(xcr0) : "c"(0) : "%edx");
#endif // defined(__i386__) || defined(__x86_64__)
return xcr0;
}
#else
// xgetbv unavailable to query for OSSave support. Return 0.
#define GetXCR0() 0
#endif // defined(_M_IX86) || defined(_M_X64) ..
// Return optimization to previous setting.
#if defined(_M_IX86) && (_MSC_VER < 1900)
#pragma optimize("g", on)
#endif
// based on libvpx arm_cpudetect.c
// For Arm, but public to allow testing on any CPU
LIBYUV_API SAFEBUFFERS int ArmCpuCaps(const char* cpuinfo_name) {
char cpuinfo_line[512];
FILE* f = fopen(cpuinfo_name, "r");
if (!f) {
// Assume Neon if /proc/cpuinfo is unavailable.
// This will occur for Chrome sandbox for Pepper or Render process.
return kCpuHasNEON;
}
while (fgets(cpuinfo_line, sizeof(cpuinfo_line) - 1, f)) {
if (memcmp(cpuinfo_line, "Features", 8) == 0) {
char* p = strstr(cpuinfo_line, " neon");
if (p && (p[5] == ' ' || p[5] == '\n')) {
fclose(f);
return kCpuHasNEON;
}
// aarch64 uses asimd for Neon.
p = strstr(cpuinfo_line, " asimd");
if (p) {
fclose(f);
return kCpuHasNEON;
}
}
}
fclose(f);
return 0;
}
// TODO(fbarchard): Consider read_msa_ir().
// TODO(fbarchard): Add unittest.
LIBYUV_API SAFEBUFFERS int MipsCpuCaps(const char* cpuinfo_name) {
char cpuinfo_line[512];
int flag = 0x0;
FILE* f = fopen(cpuinfo_name, "r");
if (!f) {
// Assume nothing if /proc/cpuinfo is unavailable.
// This will occur for Chrome sandbox for Pepper or Render process.
return 0;
}
while (fgets(cpuinfo_line, sizeof(cpuinfo_line) - 1, f)) {
if (memcmp(cpuinfo_line, "cpu model", 9) == 0) {
// Workaround early kernel without mmi in ASEs line.
if (strstr(cpuinfo_line, "Loongson-3")) {
flag |= kCpuHasMMI;
} else if (strstr(cpuinfo_line, "Loongson-2K")) {
flag |= kCpuHasMMI | kCpuHasMSA;
}
}
if (memcmp(cpuinfo_line, "ASEs implemented", 16) == 0) {
if (strstr(cpuinfo_line, "loongson-mmi") &&
strstr(cpuinfo_line, "loongson-ext")) {
flag |= kCpuHasMMI;
}
if (strstr(cpuinfo_line, "msa")) {
flag |= kCpuHasMSA;
}
// ASEs is the last line, so we can break here.
break;
}
}
fclose(f);
return flag;
}
static SAFEBUFFERS int GetCpuFlags(void) {
int cpu_info = 0;
#if !defined(__pnacl__) && !defined(__CLR_VER) && \
(defined(__x86_64__) || defined(_M_X64) || defined(__i386__) || \
defined(_M_IX86))
int cpu_info0[4] = {0, 0, 0, 0};
int cpu_info1[4] = {0, 0, 0, 0};
int cpu_info7[4] = {0, 0, 0, 0};
CpuId(0, 0, cpu_info0);
CpuId(1, 0, cpu_info1);
if (cpu_info0[0] >= 7) {
CpuId(7, 0, cpu_info7);
}
cpu_info = kCpuHasX86 | ((cpu_info1[3] & 0x04000000) ? kCpuHasSSE2 : 0) |
((cpu_info1[2] & 0x00000200) ? kCpuHasSSSE3 : 0) |
((cpu_info1[2] & 0x00080000) ? kCpuHasSSE41 : 0) |
((cpu_info1[2] & 0x00100000) ? kCpuHasSSE42 : 0) |
((cpu_info7[1] & 0x00000200) ? kCpuHasERMS : 0);
// AVX requires OS saves YMM registers.
if (((cpu_info1[2] & 0x1c000000) == 0x1c000000) && // AVX and OSXSave
((GetXCR0() & 6) == 6)) { // Test OS saves YMM registers
cpu_info |= kCpuHasAVX | ((cpu_info7[1] & 0x00000020) ? kCpuHasAVX2 : 0) |
((cpu_info1[2] & 0x00001000) ? kCpuHasFMA3 : 0) |
((cpu_info1[2] & 0x20000000) ? kCpuHasF16C : 0);
// Detect AVX512bw
if ((GetXCR0() & 0xe0) == 0xe0) {
cpu_info |= (cpu_info7[1] & 0x40000000) ? kCpuHasAVX512BW : 0;
cpu_info |= (cpu_info7[1] & 0x80000000) ? kCpuHasAVX512VL : 0;
cpu_info |= (cpu_info7[2] & 0x00000002) ? kCpuHasAVX512VBMI : 0;
cpu_info |= (cpu_info7[2] & 0x00000040) ? kCpuHasAVX512VBMI2 : 0;
cpu_info |= (cpu_info7[2] & 0x00001000) ? kCpuHasAVX512VBITALG : 0;
cpu_info |= (cpu_info7[2] & 0x00004000) ? kCpuHasAVX512VPOPCNTDQ : 0;
cpu_info |= (cpu_info7[2] & 0x00000100) ? kCpuHasGFNI : 0;
}
}
#endif
#if defined(__mips__) && defined(__linux__)
cpu_info = MipsCpuCaps("/proc/cpuinfo");
cpu_info |= kCpuHasMIPS;
#endif
#if defined(__arm__) || defined(__aarch64__)
// gcc -mfpu=neon defines __ARM_NEON__
// __ARM_NEON__ generates code that requires Neon. NaCL also requires Neon.
// For Linux, /proc/cpuinfo can be tested but without that assume Neon.
#if defined(__ARM_NEON__) || defined(__native_client__) || !defined(__linux__)
cpu_info = kCpuHasNEON;
// For aarch64(arm64), /proc/cpuinfo's feature is not complete, e.g. no neon
// flag in it.
// So for aarch64, neon enabling is hard coded here.
#endif
#if defined(__aarch64__)
cpu_info = kCpuHasNEON;
#else
// Linux arm parse text file for neon detect.
cpu_info = ArmCpuCaps("/proc/cpuinfo");
#endif
cpu_info |= kCpuHasARM;
#endif // __arm__
cpu_info |= kCpuInitialized;
return cpu_info;
}
// Note that use of this function is not thread safe.
LIBYUV_API
int MaskCpuFlags(int enable_flags) {
int cpu_info = GetCpuFlags() & enable_flags;
SetCpuFlags(cpu_info);
return cpu_info;
}
LIBYUV_API
int InitCpuFlags(void) {
return MaskCpuFlags(-1);
}
#ifdef __cplusplus
} // extern "C"
} // namespace libyuv
#endif
<|endoftext|> |
<commit_before>#include "drape_frontend/visual_params.hpp"
#include "base/macros.hpp"
#include "base/math.hpp"
#include "base/assert.hpp"
#include "geometry/mercator.hpp"
#include "indexer/scales.hpp"
#include "std/target_os.hpp"
#include <algorithm>
#include <cmath>
#include <limits>
#include <utility>
namespace df
{
using VisualScale = std::pair<std::string, double>;
#ifdef DEBUG
static bool g_isInited = false;
#define RISE_INITED g_isInited = true
#define ASSERT_INITED ASSERT(g_isInited, ())
#else
#define RISE_INITED
#define ASSERT_INITED
#endif
double const VisualParams::kMdpiScale = 1.0;
double const VisualParams::kHdpiScale = 1.5;
double const VisualParams::kXhdpiScale = 2.0;
double const VisualParams::k6plusScale = 2.4;
double const VisualParams::kXxhdpiScale = 3.0;
double const VisualParams::kXxxhdpiScale = 3.5;
VisualParams::VisualParams()
: m_tileSize(0)
, m_visualScale(0.0)
, m_fontScale(1.0)
{}
VisualParams & VisualParams::Instance()
{
static VisualParams vizParams;
return vizParams;
}
void VisualParams::Init(double vs, uint32_t tileSize)
{
VisualParams & vizParams = Instance();
vizParams.m_tileSize = tileSize;
vizParams.m_visualScale = vs;
// Here we set up glyphs rendering parameters separately for high-res and low-res screens.
if (vs <= 1.0)
vizParams.m_glyphVisualParams = { 0.48f, 0.08f, 0.2f, 0.01f, 0.49f, 0.04f };
else
vizParams.m_glyphVisualParams = { 0.5f, 0.06f, 0.2f, 0.01f, 0.49f, 0.04f };
RISE_INITED;
}
uint32_t VisualParams::GetGlyphSdfScale() const
{
ASSERT_INITED;
return (m_visualScale <= 1.0) ? 3 : 4;
}
bool VisualParams::IsSdfPrefered() const
{
ASSERT_INITED;
return m_visualScale >= kHdpiScale;
}
uint32_t VisualParams::GetGlyphBaseSize() const
{
ASSERT_INITED;
return 22;
}
double VisualParams::GetFontScale() const
{
ASSERT_INITED;
return m_fontScale;
}
void VisualParams::SetFontScale(double fontScale)
{
ASSERT_INITED;
m_fontScale = fontScale;
}
void VisualParams::SetVisualScale(double visualScale)
{
ASSERT_INITED;
m_visualScale = visualScale;
}
std::string const & VisualParams::GetResourcePostfix(double visualScale)
{
ASSERT_INITED;
static VisualScale postfixes[] =
{
std::make_pair("mdpi", kMdpiScale),
std::make_pair("hdpi", kHdpiScale),
std::make_pair("xhdpi", kXhdpiScale),
std::make_pair("6plus", k6plusScale),
std::make_pair("xxhdpi", kXxhdpiScale),
std::make_pair("xxxhdpi", kXxxhdpiScale),
};
// Looking for the nearest available scale.
int postfixIndex = -1;
double minValue = std::numeric_limits<double>::max();
for (int i = 0; i < static_cast<int>(ARRAY_SIZE(postfixes)); i++)
{
double val = fabs(postfixes[i].second - visualScale);
if (val < minValue)
{
minValue = val;
postfixIndex = i;
}
}
ASSERT_GREATER_OR_EQUAL(postfixIndex, 0, ());
return postfixes[postfixIndex].first;
}
std::string const & VisualParams::GetResourcePostfix() const
{
ASSERT_INITED;
return VisualParams::GetResourcePostfix(m_visualScale);
}
double VisualParams::GetVisualScale() const
{
ASSERT_INITED;
return m_visualScale;
}
uint32_t VisualParams::GetTileSize() const
{
ASSERT_INITED;
return m_tileSize;
}
uint32_t VisualParams::GetTouchRectRadius() const
{
ASSERT_INITED;
float const kRadiusInPixels = 20.0f;
return static_cast<uint32_t>(kRadiusInPixels * GetVisualScale());
}
double VisualParams::GetDragThreshold() const
{
ASSERT_INITED;
double const kDragThresholdInPixels = 10.0;
return kDragThresholdInPixels * GetVisualScale();
}
double VisualParams::GetScaleThreshold() const
{
ASSERT_INITED;
double const kScaleThresholdInPixels = 2.0;
return kScaleThresholdInPixels * GetVisualScale();
}
VisualParams::GlyphVisualParams const & VisualParams::GetGlyphVisualParams() const
{
ASSERT_INITED;
return m_glyphVisualParams;
}
m2::RectD const & GetWorldRect()
{
static m2::RectD const worldRect = mercator::Bounds::FullRect();
return worldRect;
}
int GetTileScaleBase(ScreenBase const & s, uint32_t tileSize)
{
ScreenBase tmpS = s;
tmpS.Rotate(-tmpS.GetAngle());
auto const halfSize = tileSize / 2;
m2::RectD glbRect;
m2::PointD const pxCenter = tmpS.PixelRect().Center();
tmpS.PtoG(m2::RectD(pxCenter - m2::PointD(halfSize, halfSize),
pxCenter + m2::PointD(halfSize, halfSize)),
glbRect);
return GetTileScaleBase(glbRect);
}
int GetTileScaleBase(ScreenBase const & s)
{
return GetTileScaleBase(s, VisualParams::Instance().GetTileSize());
}
int GetTileScaleBase(m2::RectD const & r)
{
double const sz = std::max(r.SizeX(), r.SizeY());
return std::max(1, base::SignedRound(log(mercator::Bounds::kRangeX / sz) / log(2.0)));
}
double GetTileScaleBase(double drawScale)
{
return std::max(1.0, drawScale - GetTileScaleIncrement());
}
int GetTileScaleIncrement(uint32_t tileSize, double visualScale)
{
return static_cast<int>(log(tileSize / 256.0 / visualScale) / log(2.0));
}
int GetTileScaleIncrement()
{
VisualParams const & p = VisualParams::Instance();
return GetTileScaleIncrement(p.GetTileSize(), p.GetVisualScale());
}
m2::RectD GetRectForDrawScale(int drawScale, m2::PointD const & center, uint32_t tileSize, double visualScale)
{
// +1 - we will calculate half length for each side
double const factor = 1 << (std::max(1, drawScale - GetTileScaleIncrement(tileSize, visualScale)) + 1);
double const len = mercator::Bounds::kRangeX / factor;
return m2::RectD(mercator::ClampX(center.x - len), mercator::ClampY(center.y - len),
mercator::ClampX(center.x + len), mercator::ClampY(center.y + len));
}
m2::RectD GetRectForDrawScale(int drawScale, m2::PointD const & center)
{
VisualParams const & p = VisualParams::Instance();
return GetRectForDrawScale(drawScale, center, p.GetTileSize(), p.GetVisualScale());
}
m2::RectD GetRectForDrawScale(double drawScale, m2::PointD const & center, uint32_t tileSize, double visualScale)
{
return GetRectForDrawScale(base::SignedRound(drawScale), center, tileSize, visualScale);
}
m2::RectD GetRectForDrawScale(double drawScale, m2::PointD const & center)
{
return GetRectForDrawScale(base::SignedRound(drawScale), center);
}
uint32_t CalculateTileSize(uint32_t screenWidth, uint32_t screenHeight)
{
uint32_t const maxSz = std::max(screenWidth, screenHeight);
// we're calculating the tileSize based on (maxSz > 1024 ? rounded : ceiled)
// to the nearest power of two value of the maxSz
int const ceiledSz = 1 << static_cast<int>(ceil(log(double(maxSz + 1)) / log(2.0)));
int res = 0;
if (maxSz < 1024)
{
res = ceiledSz;
}
else
{
int const flooredSz = ceiledSz / 2;
// rounding to the nearest power of two.
if (ceiledSz - maxSz < maxSz - flooredSz)
res = ceiledSz;
else
res = flooredSz;
}
#ifndef OMIM_OS_DESKTOP
return static_cast<uint32_t>(base::Clamp(res / 2, 256, 1024));
#else
return static_cast<uint32_t>(base::Clamp(res / 2, 512, 1024));
#endif
}
int GetDrawTileScale(int baseScale, uint32_t tileSize, double visualScale)
{
return std::clamp(baseScale + GetTileScaleIncrement(tileSize, visualScale), 1, scales::GetUpperStyleScale());
}
int GetDrawTileScale(ScreenBase const & s, uint32_t tileSize, double visualScale)
{
return GetDrawTileScale(GetTileScaleBase(s, tileSize), tileSize, visualScale);
}
int GetDrawTileScale(m2::RectD const & r, uint32_t tileSize, double visualScale)
{
return GetDrawTileScale(GetTileScaleBase(r), tileSize, visualScale);
}
int GetDrawTileScale(int baseScale)
{
VisualParams const & p = VisualParams::Instance();
return GetDrawTileScale(baseScale, p.GetTileSize(), p.GetVisualScale());
}
double GetDrawTileScale(double baseScale)
{
return std::max(1.0, baseScale + GetTileScaleIncrement());
}
int GetDrawTileScale(ScreenBase const & s)
{
VisualParams const & p = VisualParams::Instance();
return GetDrawTileScale(s, p.GetTileSize(), p.GetVisualScale());
}
int GetDrawTileScale(m2::RectD const & r)
{
VisualParams const & p = VisualParams::Instance();
return GetDrawTileScale(r, p.GetTileSize(), p.GetVisualScale());
}
void ExtractZoomFactors(ScreenBase const & s, double & zoom, int & index, float & lerpCoef)
{
double const zoomLevel = GetZoomLevel(s.GetScale());
zoom = trunc(zoomLevel);
index = static_cast<int>(zoom - 1.0);
lerpCoef = static_cast<float>(zoomLevel - zoom);
}
float InterpolateByZoomLevels(int index, float lerpCoef, std::vector<float> const & values)
{
ASSERT_GREATER_OR_EQUAL(index, 0, ());
ASSERT_GREATER(values.size(), scales::UPPER_STYLE_SCALE, ());
if (index < scales::UPPER_STYLE_SCALE)
return values[index] + lerpCoef * (values[index + 1] - values[index]);
return values[scales::UPPER_STYLE_SCALE];
}
m2::PointF InterpolateByZoomLevels(int index, float lerpCoef, std::vector<m2::PointF> const & values)
{
ASSERT_GREATER_OR_EQUAL(index, 0, ());
ASSERT_GREATER(values.size(), scales::UPPER_STYLE_SCALE, ());
if (index < scales::UPPER_STYLE_SCALE)
return values[index] + (values[index + 1] - values[index]) * lerpCoef;
return values[scales::UPPER_STYLE_SCALE];
}
double GetNormalizedZoomLevel(double screenScale, int minZoom)
{
double const kMaxZoom = scales::GetUpperStyleScale() + 1.0;
return base::Clamp((GetZoomLevel(screenScale) - minZoom) / (kMaxZoom - minZoom), 0.0, 1.0);
}
double GetScreenScale(double zoomLevel)
{
VisualParams const & p = VisualParams::Instance();
auto const factor = pow(2.0, GetTileScaleBase(zoomLevel));
auto const len = mercator::Bounds::kRangeX / factor;
auto const pxLen = static_cast<double>(p.GetTileSize());
return len / pxLen;
}
double GetZoomLevel(double screenScale)
{
VisualParams const & p = VisualParams::Instance();
auto const pxLen = static_cast<double>(p.GetTileSize());
auto const len = pxLen * screenScale;
auto const factor = mercator::Bounds::kRangeX / len;
static double const kLog2 = log(2.0);
return base::Clamp(GetDrawTileScale(fabs(log(factor) / kLog2)), 1.0, scales::GetUpperStyleScale() + 1.0);
}
} // namespace df
<commit_msg>[drape] Fix infinite zoom in MAPSME-14796<commit_after>#include "drape_frontend/visual_params.hpp"
#include "base/macros.hpp"
#include "base/math.hpp"
#include "base/assert.hpp"
#include "geometry/mercator.hpp"
#include "indexer/scales.hpp"
#include "std/target_os.hpp"
#include <algorithm>
#include <cmath>
#include <limits>
#include <utility>
namespace df
{
using VisualScale = std::pair<std::string, double>;
#ifdef DEBUG
static bool g_isInited = false;
#define RISE_INITED g_isInited = true
#define ASSERT_INITED ASSERT(g_isInited, ())
#else
#define RISE_INITED
#define ASSERT_INITED
#endif
double const VisualParams::kMdpiScale = 1.0;
double const VisualParams::kHdpiScale = 1.5;
double const VisualParams::kXhdpiScale = 2.0;
double const VisualParams::k6plusScale = 2.4;
double const VisualParams::kXxhdpiScale = 3.0;
double const VisualParams::kXxxhdpiScale = 3.5;
VisualParams::VisualParams()
: m_tileSize(0)
, m_visualScale(0.0)
, m_fontScale(1.0)
{}
VisualParams & VisualParams::Instance()
{
static VisualParams vizParams;
return vizParams;
}
void VisualParams::Init(double vs, uint32_t tileSize)
{
VisualParams & vizParams = Instance();
vizParams.m_tileSize = tileSize;
vizParams.m_visualScale = vs;
// Here we set up glyphs rendering parameters separately for high-res and low-res screens.
if (vs <= 1.0)
vizParams.m_glyphVisualParams = { 0.48f, 0.08f, 0.2f, 0.01f, 0.49f, 0.04f };
else
vizParams.m_glyphVisualParams = { 0.5f, 0.06f, 0.2f, 0.01f, 0.49f, 0.04f };
RISE_INITED;
}
uint32_t VisualParams::GetGlyphSdfScale() const
{
ASSERT_INITED;
return (m_visualScale <= 1.0) ? 3 : 4;
}
bool VisualParams::IsSdfPrefered() const
{
ASSERT_INITED;
return m_visualScale >= kHdpiScale;
}
uint32_t VisualParams::GetGlyphBaseSize() const
{
ASSERT_INITED;
return 22;
}
double VisualParams::GetFontScale() const
{
ASSERT_INITED;
return m_fontScale;
}
void VisualParams::SetFontScale(double fontScale)
{
ASSERT_INITED;
m_fontScale = fontScale;
}
void VisualParams::SetVisualScale(double visualScale)
{
ASSERT_INITED;
m_visualScale = visualScale;
}
std::string const & VisualParams::GetResourcePostfix(double visualScale)
{
ASSERT_INITED;
static VisualScale postfixes[] =
{
std::make_pair("mdpi", kMdpiScale),
std::make_pair("hdpi", kHdpiScale),
std::make_pair("xhdpi", kXhdpiScale),
std::make_pair("6plus", k6plusScale),
std::make_pair("xxhdpi", kXxhdpiScale),
std::make_pair("xxxhdpi", kXxxhdpiScale),
};
// Looking for the nearest available scale.
int postfixIndex = -1;
double minValue = std::numeric_limits<double>::max();
for (int i = 0; i < static_cast<int>(ARRAY_SIZE(postfixes)); i++)
{
double val = fabs(postfixes[i].second - visualScale);
if (val < minValue)
{
minValue = val;
postfixIndex = i;
}
}
ASSERT_GREATER_OR_EQUAL(postfixIndex, 0, ());
return postfixes[postfixIndex].first;
}
std::string const & VisualParams::GetResourcePostfix() const
{
ASSERT_INITED;
return VisualParams::GetResourcePostfix(m_visualScale);
}
double VisualParams::GetVisualScale() const
{
ASSERT_INITED;
return m_visualScale;
}
uint32_t VisualParams::GetTileSize() const
{
ASSERT_INITED;
return m_tileSize;
}
uint32_t VisualParams::GetTouchRectRadius() const
{
ASSERT_INITED;
float const kRadiusInPixels = 20.0f;
return static_cast<uint32_t>(kRadiusInPixels * GetVisualScale());
}
double VisualParams::GetDragThreshold() const
{
ASSERT_INITED;
double const kDragThresholdInPixels = 10.0;
return kDragThresholdInPixels * GetVisualScale();
}
double VisualParams::GetScaleThreshold() const
{
ASSERT_INITED;
double const kScaleThresholdInPixels = 2.0;
return kScaleThresholdInPixels * GetVisualScale();
}
VisualParams::GlyphVisualParams const & VisualParams::GetGlyphVisualParams() const
{
ASSERT_INITED;
return m_glyphVisualParams;
}
m2::RectD const & GetWorldRect()
{
static m2::RectD const worldRect = mercator::Bounds::FullRect();
return worldRect;
}
int GetTileScaleBase(ScreenBase const & s, uint32_t tileSize)
{
ScreenBase tmpS = s;
tmpS.Rotate(-tmpS.GetAngle());
auto const halfSize = tileSize / 2;
m2::RectD glbRect;
m2::PointD const pxCenter = tmpS.PixelRect().Center();
tmpS.PtoG(m2::RectD(pxCenter - m2::PointD(halfSize, halfSize),
pxCenter + m2::PointD(halfSize, halfSize)),
glbRect);
return GetTileScaleBase(glbRect);
}
int GetTileScaleBase(ScreenBase const & s)
{
return GetTileScaleBase(s, VisualParams::Instance().GetTileSize());
}
int GetTileScaleBase(m2::RectD const & r)
{
double const sz = std::max(r.SizeX(), r.SizeY());
return std::max(1, base::SignedRound(log(mercator::Bounds::kRangeX / sz) / log(2.0)));
}
double GetTileScaleBase(double drawScale)
{
return std::max(1.0, drawScale - GetTileScaleIncrement());
}
int GetTileScaleIncrement(uint32_t tileSize, double visualScale)
{
return static_cast<int>(log(tileSize / 256.0 / visualScale) / log(2.0));
}
int GetTileScaleIncrement()
{
VisualParams const & p = VisualParams::Instance();
return GetTileScaleIncrement(p.GetTileSize(), p.GetVisualScale());
}
m2::RectD GetRectForDrawScale(int drawScale, m2::PointD const & center, uint32_t tileSize, double visualScale)
{
// +1 - we will calculate half length for each side
double const factor = 1 << (std::max(1, drawScale - GetTileScaleIncrement(tileSize, visualScale)) + 1);
double const len = mercator::Bounds::kRangeX / factor;
return m2::RectD(mercator::ClampX(center.x - len), mercator::ClampY(center.y - len),
mercator::ClampX(center.x + len), mercator::ClampY(center.y + len));
}
m2::RectD GetRectForDrawScale(int drawScale, m2::PointD const & center)
{
VisualParams const & p = VisualParams::Instance();
return GetRectForDrawScale(drawScale, center, p.GetTileSize(), p.GetVisualScale());
}
m2::RectD GetRectForDrawScale(double drawScale, m2::PointD const & center, uint32_t tileSize, double visualScale)
{
return GetRectForDrawScale(base::SignedRound(drawScale), center, tileSize, visualScale);
}
m2::RectD GetRectForDrawScale(double drawScale, m2::PointD const & center)
{
return GetRectForDrawScale(base::SignedRound(drawScale), center);
}
uint32_t CalculateTileSize(uint32_t screenWidth, uint32_t screenHeight)
{
uint32_t const maxSz = std::max(screenWidth, screenHeight);
// we're calculating the tileSize based on (maxSz > 1024 ? rounded : ceiled)
// to the nearest power of two value of the maxSz
int const ceiledSz = 1 << static_cast<int>(ceil(log(double(maxSz + 1)) / log(2.0)));
int res = 0;
if (maxSz < 1024)
{
res = ceiledSz;
}
else
{
int const flooredSz = ceiledSz / 2;
// rounding to the nearest power of two.
if (ceiledSz - maxSz < maxSz - flooredSz)
res = ceiledSz;
else
res = flooredSz;
}
#ifndef OMIM_OS_DESKTOP
return static_cast<uint32_t>(base::Clamp(res / 2, 256, 1024));
#else
return static_cast<uint32_t>(base::Clamp(res / 2, 512, 1024));
#endif
}
int GetDrawTileScale(int baseScale, uint32_t tileSize, double visualScale)
{
return std::max(1, baseScale + GetTileScaleIncrement(tileSize, visualScale));
}
int GetDrawTileScale(ScreenBase const & s, uint32_t tileSize, double visualScale)
{
return GetDrawTileScale(GetTileScaleBase(s, tileSize), tileSize, visualScale);
}
int GetDrawTileScale(m2::RectD const & r, uint32_t tileSize, double visualScale)
{
return GetDrawTileScale(GetTileScaleBase(r), tileSize, visualScale);
}
int GetDrawTileScale(int baseScale)
{
VisualParams const & p = VisualParams::Instance();
return GetDrawTileScale(baseScale, p.GetTileSize(), p.GetVisualScale());
}
double GetDrawTileScale(double baseScale)
{
return std::max(1.0, baseScale + GetTileScaleIncrement());
}
int GetDrawTileScale(ScreenBase const & s)
{
VisualParams const & p = VisualParams::Instance();
return GetDrawTileScale(s, p.GetTileSize(), p.GetVisualScale());
}
int GetDrawTileScale(m2::RectD const & r)
{
VisualParams const & p = VisualParams::Instance();
return GetDrawTileScale(r, p.GetTileSize(), p.GetVisualScale());
}
void ExtractZoomFactors(ScreenBase const & s, double & zoom, int & index, float & lerpCoef)
{
double const zoomLevel = GetZoomLevel(s.GetScale());
zoom = trunc(zoomLevel);
index = static_cast<int>(zoom - 1.0);
lerpCoef = static_cast<float>(zoomLevel - zoom);
}
float InterpolateByZoomLevels(int index, float lerpCoef, std::vector<float> const & values)
{
ASSERT_GREATER_OR_EQUAL(index, 0, ());
ASSERT_GREATER(values.size(), scales::UPPER_STYLE_SCALE, ());
if (index < scales::UPPER_STYLE_SCALE)
return values[index] + lerpCoef * (values[index + 1] - values[index]);
return values[scales::UPPER_STYLE_SCALE];
}
m2::PointF InterpolateByZoomLevels(int index, float lerpCoef, std::vector<m2::PointF> const & values)
{
ASSERT_GREATER_OR_EQUAL(index, 0, ());
ASSERT_GREATER(values.size(), scales::UPPER_STYLE_SCALE, ());
if (index < scales::UPPER_STYLE_SCALE)
return values[index] + (values[index + 1] - values[index]) * lerpCoef;
return values[scales::UPPER_STYLE_SCALE];
}
double GetNormalizedZoomLevel(double screenScale, int minZoom)
{
double const kMaxZoom = scales::GetUpperStyleScale() + 1.0;
return base::Clamp((GetZoomLevel(screenScale) - minZoom) / (kMaxZoom - minZoom), 0.0, 1.0);
}
double GetScreenScale(double zoomLevel)
{
VisualParams const & p = VisualParams::Instance();
auto const factor = pow(2.0, GetTileScaleBase(zoomLevel));
auto const len = mercator::Bounds::kRangeX / factor;
auto const pxLen = static_cast<double>(p.GetTileSize());
return len / pxLen;
}
double GetZoomLevel(double screenScale)
{
VisualParams const & p = VisualParams::Instance();
auto const pxLen = static_cast<double>(p.GetTileSize());
auto const len = pxLen * screenScale;
auto const factor = mercator::Bounds::kRangeX / len;
static double const kLog2 = log(2.0);
return base::Clamp(GetDrawTileScale(fabs(log(factor) / kLog2)), 1.0, scales::GetUpperStyleScale() + 1.0);
}
} // namespace df
<|endoftext|> |
<commit_before># define CATCH_CONFIG_RUNNER
# include "catch.hpp"
# include <cmath>
# include <string>
int gcd(int a, int b)
{
if (b == 0)
{
return a
}
else if(a==0)
{
return b;
}
else
{
return gcd(b, a%b);
}
}
double mileToKilometer(double mile)
{
double kilometer;
kilometer = mile*1.60934;
return kilometer;
}
float ZylinderOberfl(float r, float h)
{
float oberfl = (2*M_PI*r^2)+(2*M_PI*r*h);
return oberfl;
}
float ZylinderVol(float r, float h)
{
float vol = M_PI*(r^2)*h
return vol;
}
float frac(float x)
{
int y = (int)x;
int z = y-x;
return z;
}
int checksum(int Zahl)
{
int sum = 0;
while(Zahl>0)
{
sum += Zahl%10;
Zahl /= 10;
}
return sum;
}
int sumMultiples()
{
int sum = 0;
for (int i = 0; i < 1000; i++)
{
if (i % 3 == 0)
{
sum += i;
}
else if (i % 5 == 0)
{
sum += i;
}
}
return sum;
}
TEST_CASE("describe_gcd ", "[gcd]")
{
REQUIRE(gcd(2, 4) == 2);
REQUIRE(gcd(6, 9) == 3);
REQUIRE(gcd(3, 7) == 1);
}
TEST_CASE("describe_sumMultiples ", "[sumMultiples]")
{
REQUIRE(sumMultiples() ==234168);
}
TEST_CASE("describe_checksum ", "[checksum]")
{
REQUIRE(chekcsum(15) == 6);
REQUIRE(checksum(25) == 7);
REQUIRE(checksum(35) == 8);
}
TEST_CASE("describe_ZylinderVol","[ZylinderVol]")
{
REQUIRE(ZylinderVol(1,2) == Approx(6.283));
}
TEST_CASE("describe_ZylinderOberfl","[ZylinderOberfl]")
{
REQUIRE(ZylinderOberfl(1,2) == Approx(18.85));
}
TEST_CASE("describe_mileToKilometer","[mileToKilometer]")
{
REQUIRE(mileToKilometer(1) == Approx(1.60934));
REQUIRE(mileToKilometer(2) == Approx(3,21869));
REQUIRE(mileToKilometer(5) == Approx(8,04672));
}
TEST_CASE("describe_frac","[frac]")
{
REQUIRE(frac(1.11) == Approx(0.11));
REQUIRE(frac(45.1234) == Approx(0.1234));
}
int main(int argc, char* argv[])
{
return Catch::Session().run(argc, argv);
}
<commit_msg>Update tests.cpp<commit_after># define CATCH_CONFIG_RUNNER
# include "catch.hpp"
# include <cmath>
# include <string>
int gcd(int a, int b)
{
if (b == 0)
{
return a;
}
else if(a==0)
{
return b;
}
else
{
return gcd(b, a%b);
}
}
double mileToKilometer(double mile)
{
double kilometer;
kilometer = mile*1.60934;
return kilometer;
}
float ZylinderOberfl(float r, float h)
{
float oberfl = (2*M_PI*r*r)+(2*M_PI*r*h);
return oberfl;
}
float ZylinderVol(float r, float h)
{
float vol = M_PI*(r*r)*h
return vol;
}
float frac(float x)
{
int y = (int)x;
int z = y-x;
return z;
}
int checksum(int Zahl)
{
int sum = 0;
while(Zahl>0)
{
sum += Zahl%10;
Zahl /= 10;
}
return sum;
}
int sumMultiples()
{
int sum = 0;
for (int i = 0; i <= 1000; i++)
{
if (i % 3 == 0)
{
sum += i;
}
else if (i % 5 == 0)
{
sum += i;
}
}
return sum;
}
TEST_CASE("describe_gcd ", "[gcd]")
{
REQUIRE(gcd(2, 4) == 2);
REQUIRE(gcd(6, 9) == 3);
REQUIRE(gcd(3, 7) == 1);
}
TEST_CASE("describe_sumMultiples ", "[sumMultiples]")
{
REQUIRE(sumMultiples() ==234168);
}
TEST_CASE("describe_checksum ", "[checksum]")
{
REQUIRE(checksum(15) == 6);
REQUIRE(checksum(25) == 7);
REQUIRE(checksum(35) == 8);
}
TEST_CASE("describe_ZylinderVol","[ZylinderVol]")
{
REQUIRE(ZylinderVol(1,2) == Approx(6.283));
}
TEST_CASE("describe_ZylinderOberfl","[ZylinderOberfl]")
{
REQUIRE(ZylinderOberfl(1,2) == Approx(18.85));
}
TEST_CASE("describe_mileToKilometer","[mileToKilometer]")
{
REQUIRE(mileToKilometer(1) == Approx(1.60934));
REQUIRE(mileToKilometer(2) == Approx(3,21869));
REQUIRE(mileToKilometer(5) == Approx(8,04672));
}
TEST_CASE("describe_frac","[frac]")
{
REQUIRE(frac(1.11) == Approx(0.11));
REQUIRE(frac(45.1234) == Approx(0.1234));
}
int main(int argc, char* argv[])
{
return Catch::Session().run(argc, argv);
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014, Nick Potts
* All rights reserved.
*
* This Source Code Form is subject to the terms of the
* Mozilla Public License, v. 2.0. If a copy of the MPL
* was not distributed with this file, You can obtain
* one at http://mozilla.org/MPL/2.0/.
*/
#include "SHData.h"
#include "SweepInspector.h"
int main(int c, char **v) {
QHoundData data;
qDebug() << "Opened SQL database: " << (data.openSQL("test.db") ? "Ok": "Fail");
qDebug() << "Available Tables" << data.SQLTables();
qDebug() << "Setting Table to fast_20141130L205728: " << (data.setSQLTable("fast_20141130L205728") ? "Ok": "Fail");
//std::cout << "openCSV: " << (data.openCSV("test.csv") ? "Ok": "Fail") << std::endl;
QApplication *app = new QApplication( c, v);
SweepInspector *si = new SweepInspector();
si->setpData(&data);
si->show();
return app->exec();
/*
// CSV tests
std::cout << "openCSV: " << (data.openCSV("test.csv") ? "Ok": "Fail") << std::endl;
std::cout << "1417406248.8, 399999783.0 " << data.value(1417406248.8, 399999783.0) << " s/b -83.5439" << std::endl; //top left point
std::cout << "1417406248.8, 406000216.0 " << data.value(1417406248.8, 406000216.0) << " s/b -92.3722" << std::endl;//top right
std::cout << "1417406252.3, 399999783.0 " << data.value(1417406252.3, 399999783.0) << " s/b -86.8954" << std::endl;//bottom left
std::cout << "1417406252.3, 406000216.0 " << data.value(1417406252.3, 406000216.0) << " s/b -84.871" << std::endl;//bottom right
//SQL tests
qDebug() << "Opened SQL database: " << (data.openSQL("test.db") ? "Ok": "Fail");
qDebug() << "Available Tables" << data.tables();
qDebug() << "Setting Table to fast_20141130L205728: " << (data.setSQLTable("fast_20141130L205728") ? "Ok": "Fail");
std::cout << "1417406248.8, 399999783.0 " << data.value(1417406248.8, 399999783.0) << " s/b -83.5439" << std::endl; //top left point
std::cout << "1417406248.8, 406000216.0 " << data.value(1417406248.8, 406000216.0) << " s/b -92.3722" << std::endl;//top right
std::cout << "1417406252.3, 399999783.0 " << data.value(1417406252.3, 399999783.0) << " s/b -86.8954" << std::endl;//bottom left
std::cout << "1417406252.3, 406000216.0 " << data.value(1417406252.3, 406000216.0) << " s/b -84.871" << std::endl;//bottom right
*/
}<commit_msg>More edits for testing a much larger sweep data range<commit_after>/*
* Copyright (c) 2014, Nick Potts
* All rights reserved.
*
* This Source Code Form is subject to the terms of the
* Mozilla Public License, v. 2.0. If a copy of the MPL
* was not distributed with this file, You can obtain
* one at http://mozilla.org/MPL/2.0/.
*/
#include "SHData.h"
#include "SweepInspector.h"
int main(int c, char **v) {
QHoundData data;
qDebug() << "Opened SQL database: " << (data.openSQL("test.db") ? "Ok": "Fail");
QStringList tables = data.SQLTables();
qDebug() << "Available Tables" << tables;
tables.removeOne(tables.last());
//qDebug() << "Setting Table to fast_20141130L205728: " << (data.setSQLTable("fast_20141130L205728") ? "Ok": "Fail");
qDebug() << "Setting Table to FAST_20141204L112314: " << (data.setSQLTable(tables.last()) ? "Ok": "Fail");
//std::cout << "openCSV: " << (data.openCSV("test.csv") ? "Ok": "Fail") << std::endl;
QApplication *app = new QApplication( c, v);
SweepInspector *si = new SweepInspector();
si->setpData(&data);
si->show();
return app->exec();
/*
// CSV tests
std::cout << "openCSV: " << (data.openCSV("test.csv") ? "Ok": "Fail") << std::endl;
std::cout << "1417406248.8, 399999783.0 " << data.value(1417406248.8, 399999783.0) << " s/b -83.5439" << std::endl; //top left point
std::cout << "1417406248.8, 406000216.0 " << data.value(1417406248.8, 406000216.0) << " s/b -92.3722" << std::endl;//top right
std::cout << "1417406252.3, 399999783.0 " << data.value(1417406252.3, 399999783.0) << " s/b -86.8954" << std::endl;//bottom left
std::cout << "1417406252.3, 406000216.0 " << data.value(1417406252.3, 406000216.0) << " s/b -84.871" << std::endl;//bottom right
//SQL tests
qDebug() << "Opened SQL database: " << (data.openSQL("test.db") ? "Ok": "Fail");
qDebug() << "Available Tables" << data.tables();
qDebug() << "Setting Table to fast_20141130L205728: " << (data.setSQLTable("fast_20141130L205728") ? "Ok": "Fail");
std::cout << "1417406248.8, 399999783.0 " << data.value(1417406248.8, 399999783.0) << " s/b -83.5439" << std::endl; //top left point
std::cout << "1417406248.8, 406000216.0 " << data.value(1417406248.8, 406000216.0) << " s/b -92.3722" << std::endl;//top right
std::cout << "1417406252.3, 399999783.0 " << data.value(1417406252.3, 399999783.0) << " s/b -86.8954" << std::endl;//bottom left
std::cout << "1417406252.3, 406000216.0 " << data.value(1417406252.3, 406000216.0) << " s/b -84.871" << std::endl;//bottom right
*/
}<|endoftext|> |
<commit_before>#include <Halide.h>
#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <iostream>
using namespace Halide;
Var x, y, c;
double square(double x) {
return x * x;
}
template <typename T>
void test_function(Expr e, Image<T> &cpu_result, Image<T> &gpu_result) {
Func cpu, gpu;
Target cpu_target = get_host_target();
Target gpu_target = get_host_target();
gpu_target.set_feature(Target::OpenGL);
cpu(x, y, c) = e;
gpu(x, y, c) = e;
cpu.compile_jit(cpu_target);
gpu.compile_jit(gpu_target);
cpu.realize(cpu_result);
gpu.bound(c, 0, 3).glsl(x, y, c);
gpu.realize(gpu_result);
gpu_result.copy_to_host();
}
template <typename T>
bool test_exact(Expr r, Expr g, Expr b) {
Expr e = cast<T>(select(c == 0, r, c == 1, g, b));
const int W = 256, H = 256;
Image<T> cpu_result(W, H, 3);
Image<T> gpu_result(W, H, 3);
test_function(e, cpu_result, gpu_result);
double err = 0.0;
for (int y=0; y<gpu_result.height(); y++) {
for (int x=0; x<gpu_result.width(); x++) {
if (!(gpu_result(x, y, 0) == cpu_result(x, y, 0) &&
gpu_result(x, y, 1) == cpu_result(x, y, 1) &&
gpu_result(x, y, 2) == cpu_result(x, y, 2))) {
std::cerr << "Incorrect pixel for " << e << " at (" << x << ", " << y << ")\n"
<< " ("
<< (int)gpu_result(x, y, 0) << ", "
<< (int)gpu_result(x, y, 1) << ", "
<< (int)gpu_result(x, y, 2) << ") != ("
<< (int)cpu_result(x, y, 0) << ", "
<< (int)cpu_result(x, y, 1) << ", "
<< (int)cpu_result(x, y, 2)
<< ")\n";
return false;
}
}
}
return true;
}
template <typename T>
bool test_approx(Expr r, Expr g, Expr b, double rms_error) {
Expr e = cast<T>(select(c == 0, r, c == 1, g, b));
const int W = 256, H = 256;
Image<T> cpu_result(W, H, 3);
Image<T> gpu_result(W, H, 3);
test_function(e, cpu_result, gpu_result);
double err = 0.0;
for (int y=0; y<gpu_result.height(); y++) {
for (int x=0; x<gpu_result.width(); x++) {
err += square(gpu_result(x, y, 0) - cpu_result(x, y, 0));
err += square(gpu_result(x, y, 1) - cpu_result(x, y, 1));
err += square(gpu_result(x, y, 2) - cpu_result(x, y, 2));
}
}
err = sqrt(err / (W * H));
if (err > rms_error) {
std::cerr << "RMS error too large for " << e << ": "
<< err << " > " << rms_error << "\n";
return false;
} else {
return true;
}
}
int main() {
bool ok = true;
double rms;
ok = ok && test_exact<uint8_t>(0, 0, 0);
ok = ok && test_exact<uint8_t>(clamp(x + y, 0, 255), 0, 0);
ok = ok && test_exact<uint8_t>(
max(x, y),
cast<int>(min(cast<float>(x), cast<float>(y))),
clamp(x, 0, 10));
// Trigonometric functions in GLSL are fast but not very accurate,
// especially outside of 0..2pi.
Expr r = (256 * x + y) / ceilf(65536.f / (2 * 3.1415926536f));
ok = test_approx<float>(sin(r), cos(r), 0, 5e-7);
ok = ok && test_exact<uint8_t>(
(x - 127) / 3 + 127,
(x - 127) % 3 + 127,
0);
ok = ok && test_exact<uint8_t>(
lerp(cast<uint8_t>(x), cast<uint8_t>(y), cast<uint8_t>(128)),
lerp(cast<uint8_t>(x), cast<uint8_t>(y), 0.5f),
cast<uint8_t>(lerp(cast<float>(x), cast<float>(y), 0.2f)));
if (ok) {
printf("Success!\n");
return 0;
} else {
return 1;
}
}
<commit_msg>Fixed warnings in test for -Werror builds<commit_after>#include <Halide.h>
#include <stdio.h>
#include <algorithm>
#include <stdlib.h>
#include <iostream>
using namespace Halide;
Var x, y, c;
double square(double x) {
return x * x;
}
template <typename T>
void test_function(Expr e, Image<T> &cpu_result, Image<T> &gpu_result) {
Func cpu, gpu;
Target cpu_target = get_host_target();
Target gpu_target = get_host_target();
gpu_target.set_feature(Target::OpenGL);
cpu(x, y, c) = e;
gpu(x, y, c) = e;
cpu.compile_jit(cpu_target);
gpu.compile_jit(gpu_target);
cpu.realize(cpu_result);
gpu.bound(c, 0, 3).glsl(x, y, c);
gpu.realize(gpu_result);
gpu_result.copy_to_host();
}
template <typename T>
bool test_exact(Expr r, Expr g, Expr b) {
Expr e = cast<T>(select(c == 0, r, c == 1, g, b));
const int W = 256, H = 256;
Image<T> cpu_result(W, H, 3);
Image<T> gpu_result(W, H, 3);
test_function(e, cpu_result, gpu_result);
for (int y=0; y<gpu_result.height(); y++) {
for (int x=0; x<gpu_result.width(); x++) {
if (!(gpu_result(x, y, 0) == cpu_result(x, y, 0) &&
gpu_result(x, y, 1) == cpu_result(x, y, 1) &&
gpu_result(x, y, 2) == cpu_result(x, y, 2))) {
std::cerr << "Incorrect pixel for " << e << " at (" << x << ", " << y << ")\n"
<< " ("
<< (int)gpu_result(x, y, 0) << ", "
<< (int)gpu_result(x, y, 1) << ", "
<< (int)gpu_result(x, y, 2) << ") != ("
<< (int)cpu_result(x, y, 0) << ", "
<< (int)cpu_result(x, y, 1) << ", "
<< (int)cpu_result(x, y, 2)
<< ")\n";
return false;
}
}
}
return true;
}
template <typename T>
bool test_approx(Expr r, Expr g, Expr b, double rms_error) {
Expr e = cast<T>(select(c == 0, r, c == 1, g, b));
const int W = 256, H = 256;
Image<T> cpu_result(W, H, 3);
Image<T> gpu_result(W, H, 3);
test_function(e, cpu_result, gpu_result);
double err = 0.0;
for (int y=0; y<gpu_result.height(); y++) {
for (int x=0; x<gpu_result.width(); x++) {
err += square(gpu_result(x, y, 0) - cpu_result(x, y, 0));
err += square(gpu_result(x, y, 1) - cpu_result(x, y, 1));
err += square(gpu_result(x, y, 2) - cpu_result(x, y, 2));
}
}
err = sqrt(err / (W * H));
if (err > rms_error) {
std::cerr << "RMS error too large for " << e << ": "
<< err << " > " << rms_error << "\n";
return false;
} else {
return true;
}
}
int main() {
bool ok = true;
ok = ok && test_exact<uint8_t>(0, 0, 0);
ok = ok && test_exact<uint8_t>(clamp(x + y, 0, 255), 0, 0);
ok = ok && test_exact<uint8_t>(
max(x, y),
cast<int>(min(cast<float>(x), cast<float>(y))),
clamp(x, 0, 10));
// Trigonometric functions in GLSL are fast but not very accurate,
// especially outside of 0..2pi.
Expr r = (256 * x + y) / ceilf(65536.f / (2 * 3.1415926536f));
ok = test_approx<float>(sin(r), cos(r), 0, 5e-7);
ok = ok && test_exact<uint8_t>(
(x - 127) / 3 + 127,
(x - 127) % 3 + 127,
0);
ok = ok && test_exact<uint8_t>(
lerp(cast<uint8_t>(x), cast<uint8_t>(y), cast<uint8_t>(128)),
lerp(cast<uint8_t>(x), cast<uint8_t>(y), 0.5f),
cast<uint8_t>(lerp(cast<float>(x), cast<float>(y), 0.2f)));
if (ok) {
printf("Success!\n");
return 0;
} else {
return 1;
}
}
<|endoftext|> |
<commit_before>#include "extensions/openpower-pels/data_interface.hpp"
#include "extensions/openpower-pels/host_interface.hpp"
#include <fcntl.h>
#include <filesystem>
#include <sdeventplus/source/io.hpp>
#include <gmock/gmock.h>
namespace openpower
{
namespace pels
{
class MockDataInterface : public DataInterfaceBase
{
public:
MockDataInterface()
{
}
MOCK_METHOD(std::string, getMachineTypeModel, (), (const override));
MOCK_METHOD(std::string, getMachineSerialNumber, (), (const override));
MOCK_METHOD(std::string, getServerFWVersion, (), (const override));
MOCK_METHOD(std::string, getBMCFWVersion, (), (const override));
void changeHostState(bool newState)
{
setHostState(newState);
}
void setHMCManaged(bool managed)
{
_hmcManaged = managed;
}
};
/**
* @brief The mock HostInterface class
*/
class MockHostInterface : public HostInterface
{
public:
MockHostInterface(sd_event* event, DataInterfaceBase& dataIface) :
HostInterface(event, dataIface)
{
}
virtual ~MockHostInterface()
{
}
virtual void cancelCmd() override
{
}
MOCK_METHOD(CmdStatus, sendNewLogCmd, (uint32_t, uint32_t), (override));
protected:
void receive(sdeventplus::source::IO& source, int fd,
uint32_t events) override
{
// Keep account of the number of commands responses for testing.
_cmdsProcessed++;
}
private:
size_t _cmdsProcessed = 0;
};
} // namespace pels
} // namespace openpower
<commit_msg>PEL: Mock the new PEL available cmd<commit_after>#include "extensions/openpower-pels/data_interface.hpp"
#include "extensions/openpower-pels/host_interface.hpp"
#include <fcntl.h>
#include <filesystem>
#include <sdeventplus/source/io.hpp>
#include <gmock/gmock.h>
namespace openpower
{
namespace pels
{
class MockDataInterface : public DataInterfaceBase
{
public:
MockDataInterface()
{
}
MOCK_METHOD(std::string, getMachineTypeModel, (), (const override));
MOCK_METHOD(std::string, getMachineSerialNumber, (), (const override));
MOCK_METHOD(std::string, getServerFWVersion, (), (const override));
MOCK_METHOD(std::string, getBMCFWVersion, (), (const override));
void changeHostState(bool newState)
{
setHostState(newState);
}
void setHMCManaged(bool managed)
{
_hmcManaged = managed;
}
};
/**
* @brief The mock HostInterface class
*
* This replaces the PLDM calls with a FIFO for the asynchronous
* responses.
*/
class MockHostInterface : public HostInterface
{
public:
/**
* @brief Constructor
*
* @param[in] event - The sd_event object
* @param[in] dataIface - The DataInterface class
*/
MockHostInterface(sd_event* event, DataInterfaceBase& dataIface) :
HostInterface(event, dataIface)
{
char templ[] = "/tmp/cmdfifoXXXXXX";
std::filesystem::path dir = mkdtemp(templ);
_fifo = dir / "fifo";
}
/**
* @brief Destructor
*/
virtual ~MockHostInterface()
{
std::filesystem::remove_all(_fifo.parent_path());
}
MOCK_METHOD(CmdStatus, sendNewLogCmd, (uint32_t, uint32_t), (override));
/**
* @brief Cancels waiting for a command response
*/
virtual void cancelCmd() override
{
_inProgress = false;
_source = nullptr;
}
/**
* @brief Returns the amount of time to wait before retrying after
* a failed send command.
*
* @return milliseconds - The amount of time to wait
*/
virtual std::chrono::milliseconds getSendRetryDelay() const override
{
return std::chrono::milliseconds(2);
}
/**
* @brief Returns the amount of time to wait before retrying after
* a command receive.
*
* @return milliseconds - The amount of time to wait
*/
virtual std::chrono::milliseconds getReceiveRetryDelay() const override
{
return std::chrono::milliseconds(2);
}
/**
* @brief Returns the number of commands processed
*/
size_t numCmdsProcessed() const
{
return _cmdsProcessed;
}
/**
* @brief Writes the data passed in to the FIFO
*
* @param[in] hostResponse - use a 0 to indicate success
*
* @return CmdStatus - success or failure
*/
CmdStatus send(uint8_t hostResponse)
{
// Create a FIFO once.
if (!std::filesystem::exists(_fifo))
{
if (mkfifo(_fifo.c_str(), 0622))
{
ADD_FAILURE() << "Failed mkfifo " << _fifo << strerror(errno);
exit(-1);
}
}
// Open it and register the reponse callback to
// be used on FD activity.
int fd = open(_fifo.c_str(), O_NONBLOCK | O_RDWR);
EXPECT_TRUE(fd >= 0) << "Unable to open FIFO";
auto callback = [this](sdeventplus::source::IO& source, int fd,
uint32_t events) {
this->receive(source, fd, events);
};
try
{
_source = std::make_unique<sdeventplus::source::IO>(
_event, fd, EPOLLIN,
std::bind(callback, std::placeholders::_1,
std::placeholders::_2, std::placeholders::_3));
}
catch (std::exception& e)
{
ADD_FAILURE() << "Event exception: " << e.what();
close(fd);
return CmdStatus::failure;
}
// Write the fake host reponse to the FIFO
auto bytesWritten = write(fd, &hostResponse, sizeof(hostResponse));
EXPECT_EQ(bytesWritten, sizeof(hostResponse));
_inProgress = true;
return CmdStatus::success;
}
protected:
/**
* @brief Reads the data written to the fifo and then calls
* the subscriber's callback.
*
* Nonzero data indicates a command failure (for testing bad path).
*
* @param[in] source - The event source object
* @param[in] fd - The file descriptor used
* @param[in] events - The event bits
*/
void receive(sdeventplus::source::IO& source, int fd,
uint32_t events) override
{
if (!(events & EPOLLIN))
{
return;
}
_inProgress = false;
int newFD = open(_fifo.c_str(), O_NONBLOCK | O_RDONLY);
ASSERT_TRUE(newFD >= 0) << "Failed to open FIFO";
// Read the host success/failure response from the FIFO.
uint8_t data;
auto bytesRead = read(newFD, &data, sizeof(data));
EXPECT_EQ(bytesRead, sizeof(data));
close(newFD);
ResponseStatus status = ResponseStatus::success;
if (data != 0)
{
status = ResponseStatus::failure;
}
if (_responseFunc)
{
(*_responseFunc)(status);
}
// Keep account of the number of commands responses for testing.
_cmdsProcessed++;
}
private:
/**
* @brief The event source for the fifo
*/
std::unique_ptr<sdeventplus::source::IO> _source;
/**
* @brief the path to the fifo
*/
std::filesystem::path _fifo;
/**
* @brief The number of commands processed
*/
size_t _cmdsProcessed = 0;
};
} // namespace pels
} // namespace openpower
<|endoftext|> |
<commit_before>#include "catch.hpp"
#include <iostream>
#include <exception> // std::bad_function_call, std::runtime_error
#include <thread> // std::thread, std::this_thread::yield
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
#include <functional> // std::function
class EventThreader {
public:
std::condition_variable event_waiter;
std::condition_variable calling_waiter;
std::unique_lock<std::mutex>* event_lock = nullptr;
std::unique_lock<std::mutex>* calling_lock = nullptr;
std::mutex mtx;
std::mutex allocation_mtx;
std::thread event_thread;
void switchToCallingThread();
bool require_switch_from_event = false;
std::function<void(void)> event_cleanup;
std::runtime_error* exception_from_the_event_thread = nullptr;
std::function<void (std::function<void (void)>)> event_function;
void deallocate();
public:
EventThreader(std::function<void (std::function<void (void)>)> func);
~EventThreader();
void switchToEventThread();
void join();
void setEventCleanup(std::function<void(void)>);
};
EventThreader::EventThreader(std::function<void (std::function<void (void)>)> func) {
allocation_mtx.lock();
calling_lock = new std::unique_lock<std::mutex>(mtx);
allocation_mtx.unlock();
event_cleanup = [](){}; // empty function
event_function = func;
auto event = [&](){
/* mtx force switch to calling - blocked by the mutex */
this->allocation_mtx.lock();
this->event_lock = new std::unique_lock<std::mutex>(this->mtx);
this->allocation_mtx.unlock();
this->calling_waiter.notify_one();
this->event_waiter.wait(*(this->event_lock));
std::this_thread::yield();
try {
this->event_function([&](){this->switchToCallingThread();});
if (this->require_switch_from_event) { // the event has ended, but not ready to join
// rejoin the calling thread after dealing with this exception
throw std::runtime_error("switch to event not matched with a switch to calling");
}
} catch (const std::runtime_error &e) {
/* report the exception to the calling thread */
this->allocation_mtx.lock();
this->exception_from_the_event_thread = new std::runtime_error(e);
this->allocation_mtx.unlock();
this->calling_waiter.notify_one();
std::this_thread::yield();
}
this->allocation_mtx.lock();
delete this->event_lock;
this->event_lock = nullptr;
this->allocation_mtx.unlock();
this->event_cleanup();
};
event_thread = std::thread(event);
}
EventThreader::~EventThreader() {
deallocate();
}
void EventThreader::deallocate() {
allocation_mtx.lock();
if (exception_from_the_event_thread != nullptr) {
delete exception_from_the_event_thread;
exception_from_the_event_thread = nullptr;
}
if (calling_lock != nullptr) {
delete calling_lock;
calling_lock = nullptr;
}
if (event_lock != nullptr) {
delete event_lock;
event_lock = nullptr;
}
allocation_mtx.unlock();
}
void EventThreader::switchToCallingThread() {
if (!require_switch_from_event) {
throw std::runtime_error("switch to calling not matched with a switch to event");
}
require_switch_from_event = false;
/* switch to calling */
calling_waiter.notify_one();
std::this_thread::yield();
event_waiter.wait(*(event_lock));
std::this_thread::yield();
/* back from calling */
}
void EventThreader::switchToEventThread() {
}
void EventThreader::join() {
allocation_mtx.lock();
delete calling_lock; // remove lock on this thread, allow event to run
calling_lock = nullptr;
allocation_mtx.unlock();
if (event_lock != nullptr) {
event_waiter.notify_one();
std::this_thread::yield();
}
event_thread.join();
if (exception_from_the_event_thread != nullptr) {
/* an exception occured */
std::runtime_error e_copy(exception_from_the_event_thread->what());
allocation_mtx.lock();
delete exception_from_the_event_thread;
exception_from_the_event_thread = nullptr;
allocation_mtx.unlock();
throw e_copy;
}
deallocate();
}
void EventThreader::setEventCleanup(std::function<void(void)> cleanup) {
event_cleanup = cleanup;
}
TEST_CASE( "EventThreader", "[EventThreader]" ) {
std::stringstream ss;
SECTION("Finding the error") {
/* Example of most basic use */
auto f = [&ss](std::function<void(void)> switchToMainThread){
for(int i = 0; i < 100; i++) { ss << "*"; }
switchToMainThread();
for(int i = 0; i < 50; i++) { ss << "*"; }
switchToMainThread();
};
EventThreader et(f);
// class functions
auto switchToEventThread= [&]() {
if (et.require_switch_from_event) {
throw std::runtime_error("switch to event not matched with a switch to calling");
}
et.require_switch_from_event = true;
/* switch to event */
et.event_waiter.notify_one();
std::this_thread::yield();
et.calling_waiter.wait(*et.calling_lock);
std::this_thread::yield();
/* back from event */
if (et.require_switch_from_event) {
/* this exception is thrown if switchToCallingThread() was not used, which means the thread ended */
et.join();
}
};
// Start construction
std::this_thread::yield();
et.calling_waiter.wait(*(et.calling_lock));
std::this_thread::yield();
// End constuction
//EventThreader et(f);
switchToEventThread();
for(int i = 0; i < 75; i++) { ss << "$"; }
switchToEventThread();
for(int i = 0; i < 25; i++) { ss << "$"; }
et.join();
/* Generate what the result should look like */
std::string requirement;
for(int i = 0; i < 100; i++) { requirement += "*"; }
for(int i = 0; i < 75; i++) { requirement += "$"; }
for(int i = 0; i < 50; i++) { requirement += "*"; }
for(int i = 0; i < 25; i++) { requirement += "$"; }
REQUIRE( requirement == ss.str());
}
/* SECTION("Abitrary use") {
// Example of most basic use
auto f = [&ss](std::function<void(void)> switchToMainThread){
for(int i = 0; i < 100; i++) { ss << "*"; }
switchToMainThread();
for(int i = 0; i < 50; i++) { ss << "*"; }
switchToMainThread();
};
EventThreader et(f);
switchToEventThread();
for(int i = 0; i < 75; i++) { ss << "$"; }
switchToEventThread();
for(int i = 0; i < 25; i++) { ss << "$"; }
join();
// Generate what the result should look like
std::string requirement;
for(int i = 0; i < 100; i++) { requirement += "*"; }
for(int i = 0; i < 75; i++) { requirement += "$"; }
for(int i = 0; i < 50; i++) { requirement += "*"; }
for(int i = 0; i < 25; i++) { requirement += "$"; }
REQUIRE( requirement == ss.str());
} */
}
<commit_msg>moved class code<commit_after>#include "catch.hpp"
#include <iostream>
#include <exception> // std::bad_function_call, std::runtime_error
#include <thread> // std::thread, std::this_thread::yield
#include <mutex> // std::mutex, std::unique_lock
#include <condition_variable> // std::condition_variable
#include <functional> // std::function
class EventThreader {
public:
std::condition_variable event_waiter;
std::condition_variable calling_waiter;
std::unique_lock<std::mutex>* event_lock = nullptr;
std::unique_lock<std::mutex>* calling_lock = nullptr;
std::mutex mtx;
std::mutex allocation_mtx;
std::thread event_thread;
void switchToCallingThread();
bool require_switch_from_event = false;
std::function<void(void)> event_cleanup;
std::runtime_error* exception_from_the_event_thread = nullptr;
std::function<void (std::function<void (void)>)> event_function;
void deallocate();
public:
EventThreader(std::function<void (std::function<void (void)>)> func);
~EventThreader();
void switchToEventThread();
void join();
void setEventCleanup(std::function<void(void)>);
};
EventThreader::EventThreader(std::function<void (std::function<void (void)>)> func) {
allocation_mtx.lock();
calling_lock = new std::unique_lock<std::mutex>(mtx);
allocation_mtx.unlock();
event_cleanup = [](){}; // empty function
event_function = func;
auto event = [&](){
/* mtx force switch to calling - blocked by the mutex */
this->allocation_mtx.lock();
this->event_lock = new std::unique_lock<std::mutex>(this->mtx);
this->allocation_mtx.unlock();
this->calling_waiter.notify_one();
this->event_waiter.wait(*(this->event_lock));
std::this_thread::yield();
try {
this->event_function([&](){this->switchToCallingThread();});
if (this->require_switch_from_event) { // the event has ended, but not ready to join
// rejoin the calling thread after dealing with this exception
throw std::runtime_error("switch to event not matched with a switch to calling");
}
} catch (const std::runtime_error &e) {
/* report the exception to the calling thread */
this->allocation_mtx.lock();
this->exception_from_the_event_thread = new std::runtime_error(e);
this->allocation_mtx.unlock();
this->calling_waiter.notify_one();
std::this_thread::yield();
}
this->allocation_mtx.lock();
delete this->event_lock;
this->event_lock = nullptr;
this->allocation_mtx.unlock();
this->event_cleanup();
};
event_thread = std::thread(event);
std::this_thread::yield();
calling_waiter.wait(*calling_lock);
std::this_thread::yield();
}
EventThreader::~EventThreader() {
deallocate();
}
void EventThreader::deallocate() {
allocation_mtx.lock();
if (exception_from_the_event_thread != nullptr) {
delete exception_from_the_event_thread;
exception_from_the_event_thread = nullptr;
}
if (calling_lock != nullptr) {
delete calling_lock;
calling_lock = nullptr;
}
if (event_lock != nullptr) {
delete event_lock;
event_lock = nullptr;
}
allocation_mtx.unlock();
}
void EventThreader::switchToCallingThread() {
if (!require_switch_from_event) {
throw std::runtime_error("switch to calling not matched with a switch to event");
}
require_switch_from_event = false;
/* switch to calling */
calling_waiter.notify_one();
std::this_thread::yield();
event_waiter.wait(*(event_lock));
std::this_thread::yield();
/* back from calling */
}
void EventThreader::switchToEventThread() {
}
void EventThreader::join() {
allocation_mtx.lock();
delete calling_lock; // remove lock on this thread, allow event to run
calling_lock = nullptr;
allocation_mtx.unlock();
if (event_lock != nullptr) {
event_waiter.notify_one();
std::this_thread::yield();
}
event_thread.join();
if (exception_from_the_event_thread != nullptr) {
/* an exception occured */
std::runtime_error e_copy(exception_from_the_event_thread->what());
allocation_mtx.lock();
delete exception_from_the_event_thread;
exception_from_the_event_thread = nullptr;
allocation_mtx.unlock();
throw e_copy;
}
deallocate();
}
void EventThreader::setEventCleanup(std::function<void(void)> cleanup) {
event_cleanup = cleanup;
}
TEST_CASE( "EventThreader", "[EventThreader]" ) {
std::stringstream ss;
SECTION("Finding the error") {
/* Example of most basic use */
auto f = [&ss](std::function<void(void)> switchToMainThread){
for(int i = 0; i < 100; i++) { ss << "*"; }
switchToMainThread();
for(int i = 0; i < 50; i++) { ss << "*"; }
switchToMainThread();
};
EventThreader et(f);
// class functions
auto switchToEventThread= [&]() {
if (et.require_switch_from_event) {
throw std::runtime_error("switch to event not matched with a switch to calling");
}
et.require_switch_from_event = true;
/* switch to event */
et.event_waiter.notify_one();
std::this_thread::yield();
et.calling_waiter.wait(*et.calling_lock);
std::this_thread::yield();
/* back from event */
if (et.require_switch_from_event) {
/* this exception is thrown if switchToCallingThread() was not used, which means the thread ended */
et.join();
}
};
// Start construction
// End constuction
//EventThreader et(f);
switchToEventThread();
for(int i = 0; i < 75; i++) { ss << "$"; }
switchToEventThread();
for(int i = 0; i < 25; i++) { ss << "$"; }
et.join();
/* Generate what the result should look like */
std::string requirement;
for(int i = 0; i < 100; i++) { requirement += "*"; }
for(int i = 0; i < 75; i++) { requirement += "$"; }
for(int i = 0; i < 50; i++) { requirement += "*"; }
for(int i = 0; i < 25; i++) { requirement += "$"; }
REQUIRE( requirement == ss.str());
}
/* SECTION("Abitrary use") {
// Example of most basic use
auto f = [&ss](std::function<void(void)> switchToMainThread){
for(int i = 0; i < 100; i++) { ss << "*"; }
switchToMainThread();
for(int i = 0; i < 50; i++) { ss << "*"; }
switchToMainThread();
};
EventThreader et(f);
switchToEventThread();
for(int i = 0; i < 75; i++) { ss << "$"; }
switchToEventThread();
for(int i = 0; i < 25; i++) { ss << "$"; }
join();
// Generate what the result should look like
std::string requirement;
for(int i = 0; i < 100; i++) { requirement += "*"; }
for(int i = 0; i < 75; i++) { requirement += "$"; }
for(int i = 0; i < 50; i++) { requirement += "*"; }
for(int i = 0; i < 25; i++) { requirement += "$"; }
REQUIRE( requirement == ss.str());
} */
}
<|endoftext|> |
<commit_before>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <visionaray/math/math.h>
#include <visionaray/bvh.h>
#include <visionaray/get_normal.h>
#include <gtest/gtest.h>
using namespace visionaray;
//-------------------------------------------------------------------------------------------------
// Test get_normal() for BVHs
//
TEST(GetNormal, BVH)
{
using triangle_type = basic_triangle<3, float>;
triangle_type triangles[2];
triangles[0].v1 = vec3(-1.0f, -1.0f, 1.0f);
triangles[0].e1 = vec3( 1.0f, -1.0f, 1.0f) - triangles[0].v1;
triangles[0].e2 = vec3( 1.0f, 1.0f, 1.0f) - triangles[0].v1;
triangles[0].prim_id = 0;
triangles[0].geom_id = 0;
triangles[1].v1 = vec3( 1.0f, -1.0f, -1.0f);
triangles[1].e1 = vec3(-1.0f, -1.0f, -1.0f) - triangles[1].v1;
triangles[1].e2 = vec3(-1.0f, 1.0f, -1.0f) - triangles[1].v1;
triangles[1].prim_id = 1;
triangles[1].geom_id = 1;
binned_sah_builder builder;
auto bvh = builder.build(index_bvh<triangle_type>{}, triangles, 2);
ray r;
r.ori = vec3(0.5f, -0.5f, 2.0f);
r.dir = normalize( vec3(0.0f, 0.0f, -1.0f) );
auto hr = intersect(r, bvh);
// Make some basic assumptions about the hit record
EXPECT_TRUE(hr.hit);
EXPECT_FLOAT_EQ(hr.t, 1.0f);
EXPECT_EQ(hr.prim_id, 0);
// Now test get_normal()
auto n1 = get_normal(hr, bvh);
auto n2 = normalize( cross(triangles[hr.prim_id].e1, triangles[hr.prim_id].e2) );
EXPECT_FLOAT_EQ(n1.x, n2.x);
EXPECT_FLOAT_EQ(n1.y, n2.y);
EXPECT_FLOAT_EQ(n1.z, n2.z);
// Test with SIMD ray
simd::ray4 r4;
r4.ori = vector<3, simd::float4>(r.ori);
r4.dir = vector<3, simd::float4>(r.dir);
auto hr4 = intersect(r4, bvh);
// Again make some basic assumptions about the hit record
EXPECT_TRUE( all(hr4.hit) );
EXPECT_TRUE( all(hr4.t == 1.0f) );
EXPECT_TRUE( all(hr4.prim_id == 0) );
// Test get_normal()
auto n1_4 = get_normal(hr4, bvh);
auto n2_4 = vector<3, simd::float4>(n2);
EXPECT_FLOAT_EQ(simd::get<0>(n1_4.x), simd::get<0>(n2_4.x));
EXPECT_FLOAT_EQ(simd::get<0>(n1_4.y), simd::get<0>(n2_4.y));
EXPECT_FLOAT_EQ(simd::get<0>(n1_4.z), simd::get<0>(n2_4.z));
}
<commit_msg>Fix unit tests<commit_after>// This file is distributed under the MIT license.
// See the LICENSE file for details.
#include <visionaray/math/math.h>
#include <visionaray/bvh.h>
#include <visionaray/get_normal.h>
#include <gtest/gtest.h>
using namespace visionaray;
//-------------------------------------------------------------------------------------------------
// Test get_normal() for BVHs
//
TEST(GetNormal, BVH)
{
using triangle_type = basic_triangle<3, float>;
triangle_type triangles[2];
triangles[0].v1 = vec3(-1.0f, -1.0f, 1.0f);
triangles[0].e1 = vec3( 1.0f, -1.0f, 1.0f) - triangles[0].v1;
triangles[0].e2 = vec3( 1.0f, 1.0f, 1.0f) - triangles[0].v1;
triangles[0].prim_id = 0;
triangles[0].geom_id = 0;
triangles[1].v1 = vec3( 1.0f, -1.0f, -1.0f);
triangles[1].e1 = vec3(-1.0f, -1.0f, -1.0f) - triangles[1].v1;
triangles[1].e2 = vec3(-1.0f, 1.0f, -1.0f) - triangles[1].v1;
triangles[1].prim_id = 1;
triangles[1].geom_id = 1;
binned_sah_builder builder;
auto bvh = builder.build(index_bvh<triangle_type>{}, triangles, 2);
ray r;
r.ori = vec3(0.5f, -0.5f, 2.0f);
r.dir = normalize( vec3(0.0f, 0.0f, -1.0f) );
r.tmin = 0.0f;
r.tmax = numeric_limits<float>::max();
auto hr = intersect(r, bvh);
// Make some basic assumptions about the hit record
EXPECT_TRUE(hr.hit);
EXPECT_FLOAT_EQ(hr.t, 1.0f);
EXPECT_EQ(hr.prim_id, 0);
// Now test get_normal()
auto n1 = get_normal(hr, bvh);
auto n2 = normalize( cross(triangles[hr.prim_id].e1, triangles[hr.prim_id].e2) );
EXPECT_FLOAT_EQ(n1.x, n2.x);
EXPECT_FLOAT_EQ(n1.y, n2.y);
EXPECT_FLOAT_EQ(n1.z, n2.z);
// Test with SIMD ray
simd::ray4 r4;
r4.ori = vector<3, simd::float4>(r.ori);
r4.dir = vector<3, simd::float4>(r.dir);
r4.tmin = simd::float4(0.0f);
r4.tmax = numeric_limits<simd::float4>::max();
auto hr4 = intersect(r4, bvh);
// Again make some basic assumptions about the hit record
EXPECT_TRUE( all(hr4.hit) );
EXPECT_TRUE( all(hr4.t == 1.0f) );
EXPECT_TRUE( all(hr4.prim_id == 0) );
// Test get_normal()
auto n1_4 = get_normal(hr4, bvh);
auto n2_4 = vector<3, simd::float4>(n2);
EXPECT_FLOAT_EQ(simd::get<0>(n1_4.x), simd::get<0>(n2_4.x));
EXPECT_FLOAT_EQ(simd::get<0>(n1_4.y), simd::get<0>(n2_4.y));
EXPECT_FLOAT_EQ(simd::get<0>(n1_4.z), simd::get<0>(n2_4.z));
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: stg.hxx,v $
*
* $Revision: 1.9 $
*
* last change: $Author: mba $ $Date: 2001-02-12 17:16:55 $
*
* 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 _STG_HXX
#define _STG_HXX
#ifndef _RTTI_HXX //autogen
#include <tools/rtti.hxx>
#endif
#ifndef _TOOLS_STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#ifndef _TOOLS_GLOBNAME_HXX //autogen
#include <tools/globname.hxx>
#endif
class Storage;
class StorageStream;
class StgIo;
class StgDirEntry;
class StgStrm;
class SvGlobalName;
struct ClsId
{
INT32 n1;
INT16 n2, n3;
UINT8 n4, n5, n6, n7, n8, n9, n10, n11;
};
class StorageBase : public SvRefBase
{
protected:
ULONG nError; // error code
StreamMode nMode; // open mode
BOOL bAutoCommit;
StorageBase();
virtual ~StorageBase();
public:
TYPEINFO();
virtual const SvStream* GetSvStream() const = 0;
virtual BOOL Validate( BOOL=FALSE ) const = 0;
virtual BOOL ValidateMode( StreamMode ) const = 0;
void ResetError() const;
void SetError( ULONG ) const;
ULONG GetError() const;
BOOL Good() const { return BOOL( nError == SVSTREAM_OK ); }
StreamMode GetMode() const { return nMode; }
void SetAutoCommit( BOOL bSet )
{ bAutoCommit = bSet; }
};
class BaseStorageStream : public StorageBase
{
public:
TYPEINFO();
virtual ULONG Read( void * pData, ULONG nSize ) = 0;
virtual ULONG Write( const void* pData, ULONG nSize ) = 0;
virtual ULONG Seek( ULONG nPos ) = 0;
virtual ULONG Tell() = 0;
virtual void Flush() = 0;
virtual BOOL SetSize( ULONG nNewSize ) = 0;
virtual BOOL CopyTo( BaseStorageStream * pDestStm ) = 0;
virtual BOOL Commit() = 0;
virtual BOOL Revert() = 0;
virtual BOOL Equals( const BaseStorageStream& rStream ) const = 0;
};
class SvStorageInfoList;
class BaseStorage : public StorageBase
{
public:
TYPEINFO();
virtual const String& GetName() const = 0;
virtual BOOL IsRoot() const = 0;
virtual void SetClassId( const ClsId& ) = 0;
virtual const ClsId& GetClassId() const = 0;
virtual void SetDirty() = 0;
virtual void SetClass( const SvGlobalName & rClass,
ULONG nOriginalClipFormat,
const String & rUserTypeName ) = 0;
virtual void SetConvertClass( const SvGlobalName & rConvertClass,
ULONG nOriginalClipFormat,
const String & rUserTypeName ) = 0;
virtual SvGlobalName GetClassName() = 0;
virtual ULONG GetFormat() = 0;
virtual String GetUserName() = 0;
virtual BOOL ShouldConvert() = 0;
virtual void FillInfoList( SvStorageInfoList* ) const = 0;
virtual BOOL CopyTo( BaseStorage* pDestStg ) const = 0;
virtual BOOL Commit() = 0;
virtual BOOL Revert() = 0;
virtual BaseStorageStream* OpenStream( const String & rEleName,
StreamMode = STREAM_STD_READWRITE,
BOOL bDirect = TRUE ) = 0;
virtual BaseStorage* OpenStorage( const String & rEleName,
StreamMode = STREAM_STD_READWRITE,
BOOL bDirect = FALSE ) = 0;
virtual BaseStorage* OpenUCBStorage( const String & rEleName,
StreamMode = STREAM_STD_READWRITE,
BOOL bDirect = FALSE ) = 0;
virtual BaseStorage* OpenOLEStorage( const String & rEleName,
StreamMode = STREAM_STD_READWRITE,
BOOL bDirect = FALSE ) = 0;
virtual BOOL IsStream( const String& rEleName ) const = 0;
virtual BOOL IsStorage( const String& rEleName ) const = 0;
virtual BOOL IsContained( const String& rEleName ) const = 0;
virtual BOOL Remove( const String & rEleName ) = 0;
virtual BOOL Rename( const String & rEleName, const String & rNewName ) = 0;
virtual BOOL CopyTo( const String & rEleName, BaseStorage * pDest, const String & rNewName ) = 0;
virtual BOOL MoveTo( const String & rEleName, BaseStorage * pDest, const String & rNewName ) = 0;
virtual BOOL ValidateFAT() = 0;
virtual BOOL Equals( const BaseStorage& rStream ) const = 0;
};
class OLEStorageBase
{
protected:
StreamMode& nStreamMode; // open mode
StgIo* pIo; // I/O subsystem
StgDirEntry* pEntry; // the dir entry
OLEStorageBase( StgIo*, StgDirEntry*, StreamMode& );
~OLEStorageBase();
BOOL Validate_Impl( BOOL=FALSE ) const;
BOOL ValidateMode_Impl( StreamMode, StgDirEntry* p = NULL ) const ;
const SvStream* GetSvStream_Impl() const;
public:
};
class StorageStream : public BaseStorageStream, public OLEStorageBase
{
//friend class Storage;
ULONG nPos; // current position
protected:
~StorageStream();
public:
TYPEINFO();
StorageStream( StgIo*, StgDirEntry*, StreamMode );
virtual ULONG Read( void * pData, ULONG nSize );
virtual ULONG Write( const void* pData, ULONG nSize );
virtual ULONG Seek( ULONG nPos );
virtual ULONG Tell() { return nPos; }
virtual void Flush();
virtual BOOL SetSize( ULONG nNewSize );
virtual BOOL CopyTo( BaseStorageStream * pDestStm );
virtual BOOL Commit();
virtual BOOL Revert();
virtual BOOL Validate( BOOL=FALSE ) const;
virtual BOOL ValidateMode( StreamMode ) const;
BOOL ValidateMode( StreamMode, StgDirEntry* p ) const;
const SvStream* GetSvStream() const;
virtual BOOL Equals( const BaseStorageStream& rStream ) const;
};
class Storage : public BaseStorage, public OLEStorageBase
{
String aName;
BOOL bIsRoot;
void Init( BOOL bCreate );
Storage( StgIo*, StgDirEntry*, StreamMode );
protected:
~Storage();
public:
TYPEINFO();
Storage( const String &, StreamMode = STREAM_STD_READWRITE, BOOL bDirect = TRUE );
Storage( SvStream& rStrm, BOOL bDirect = TRUE );
static BOOL IsStorageFile( const String & rFileName );
static BOOL IsStorageFile( SvStream* );
virtual const String& GetName() const;
virtual BOOL IsRoot() const { return bIsRoot; }
virtual void SetClassId( const ClsId& );
virtual const ClsId& GetClassId() const;
virtual void SetDirty();
virtual void SetClass( const SvGlobalName & rClass,
ULONG nOriginalClipFormat,
const String & rUserTypeName );
virtual void SetConvertClass( const SvGlobalName & rConvertClass,
ULONG nOriginalClipFormat,
const String & rUserTypeName );
virtual SvGlobalName GetClassName();
virtual ULONG GetFormat();
virtual String GetUserName();
virtual BOOL ShouldConvert();
virtual void FillInfoList( SvStorageInfoList* ) const;
virtual BOOL CopyTo( BaseStorage* pDestStg ) const;
virtual BOOL Commit();
virtual BOOL Revert();
virtual BaseStorageStream* OpenStream( const String & rEleName,
StreamMode = STREAM_STD_READWRITE,
BOOL bDirect = TRUE );
virtual BaseStorage* OpenStorage( const String & rEleName,
StreamMode = STREAM_STD_READWRITE,
BOOL bDirect = FALSE );
virtual BaseStorage* OpenUCBStorage( const String & rEleName,
StreamMode = STREAM_STD_READWRITE,
BOOL bDirect = FALSE );
virtual BaseStorage* OpenOLEStorage( const String & rEleName,
StreamMode = STREAM_STD_READWRITE,
BOOL bDirect = FALSE );
virtual BOOL IsStream( const String& rEleName ) const;
virtual BOOL IsStorage( const String& rEleName ) const;
virtual BOOL IsContained( const String& rEleName ) const;
virtual BOOL Remove( const String & rEleName );
virtual BOOL Rename( const String & rEleName, const String & rNewName );
virtual BOOL CopyTo( const String & rEleName, BaseStorage * pDest, const String & rNewName );
virtual BOOL MoveTo( const String & rEleName, BaseStorage * pDest, const String & rNewName );
virtual BOOL ValidateFAT();
virtual BOOL Validate( BOOL=FALSE ) const;
virtual BOOL ValidateMode( StreamMode ) const;
BOOL ValidateMode( StreamMode, StgDirEntry* p ) const;
virtual const SvStream* GetSvStream() const;
virtual BOOL Equals( const BaseStorage& rStream ) const;
};
class UCBStorageStream_Impl;
class UCBStorageStream : public BaseStorageStream
{
friend class UCBStorage;
UCBStorageStream_Impl*
pImp;
protected:
~UCBStorageStream();
public:
TYPEINFO();
UCBStorageStream( const String& rName, StreamMode nMode, BOOL bDirect );
UCBStorageStream( UCBStorageStream_Impl* );
virtual ULONG Read( void * pData, ULONG nSize );
virtual ULONG Write( const void* pData, ULONG nSize );
virtual ULONG Seek( ULONG nPos );
virtual ULONG Tell();
virtual void Flush();
virtual BOOL SetSize( ULONG nNewSize );
virtual BOOL CopyTo( BaseStorageStream * pDestStm );
virtual BOOL Commit();
virtual BOOL Revert();
virtual BOOL Validate( BOOL=FALSE ) const;
virtual BOOL ValidateMode( StreamMode ) const;
const SvStream* GetSvStream() const;
virtual BOOL Equals( const BaseStorageStream& rStream ) const;
};
class UCBStorage_Impl;
struct UCBStorageElement_Impl;
class UCBStorage : public BaseStorage
{
UCBStorage_Impl* pImp;
protected:
~UCBStorage();
public:
static BOOL IsStorageFile( SvStream* );
UCBStorage( const String& rName, StreamMode nMode, BOOL bDirect = TRUE, BOOL bIsRoot = TRUE );
UCBStorage( UCBStorage_Impl* );
UCBStorage( SvStream& rStrm, BOOL bDirect = TRUE );
TYPEINFO();
virtual const String& GetName() const;
virtual BOOL IsRoot() const;
virtual void SetClassId( const ClsId& );
virtual const ClsId& GetClassId() const;
virtual void SetDirty();
virtual void SetClass( const SvGlobalName & rClass,
ULONG nOriginalClipFormat,
const String & rUserTypeName );
virtual void SetConvertClass( const SvGlobalName & rConvertClass,
ULONG nOriginalClipFormat,
const String & rUserTypeName );
virtual SvGlobalName GetClassName();
virtual ULONG GetFormat();
virtual String GetUserName();
virtual BOOL ShouldConvert();
virtual void FillInfoList( SvStorageInfoList* ) const;
virtual BOOL CopyTo( BaseStorage* pDestStg ) const;
virtual BOOL Commit();
virtual BOOL Revert();
virtual BaseStorageStream* OpenStream( const String & rEleName,
StreamMode = STREAM_STD_READWRITE,
BOOL bDirect = TRUE );
virtual BaseStorage* OpenStorage( const String & rEleName,
StreamMode = STREAM_STD_READWRITE,
BOOL bDirect = FALSE );
virtual BaseStorage* OpenUCBStorage( const String & rEleName,
StreamMode = STREAM_STD_READWRITE,
BOOL bDirect = FALSE );
virtual BaseStorage* OpenOLEStorage( const String & rEleName,
StreamMode = STREAM_STD_READWRITE,
BOOL bDirect = FALSE );
virtual BOOL IsStream( const String& rEleName ) const;
virtual BOOL IsStorage( const String& rEleName ) const;
virtual BOOL IsContained( const String& rEleName ) const;
virtual BOOL Remove( const String & rEleName );
virtual BOOL Rename( const String & rEleName, const String & rNewName );
virtual BOOL CopyTo( const String & rEleName, BaseStorage * pDest, const String & rNewName );
virtual BOOL MoveTo( const String & rEleName, BaseStorage * pDest, const String & rNewName );
virtual BOOL ValidateFAT();
virtual BOOL Validate( BOOL=FALSE ) const;
virtual BOOL ValidateMode( StreamMode ) const;
virtual const SvStream* GetSvStream() const;
virtual BOOL Equals( const BaseStorage& rStream ) const;
#if _SOLAR__PRIVATE
UCBStorageElement_Impl* FindElement_Impl( const String& rName ) const;
BOOL CopyStorageElement_Impl( UCBStorageElement_Impl& rElement,
BaseStorage* pDest, const String& rNew ) const;
BaseStorage* OpenStorage_Impl( const String & rEleName,
StreamMode, BOOL bDirect, BOOL bForceUCBStorage );
#endif
};
#endif
<commit_msg>allow setting properties on UCBStorage elements<commit_after>/*************************************************************************
*
* $RCSfile: stg.hxx,v $
*
* $Revision: 1.10 $
*
* last change: $Author: mba $ $Date: 2001-02-19 13:04:33 $
*
* 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 _STG_HXX
#define _STG_HXX
#ifndef _COM_SUN_STAR_UNO_ANY_H_
#include <com/sun/star/uno/Any.h>
#endif
#ifndef _RTTI_HXX //autogen
#include <tools/rtti.hxx>
#endif
#ifndef _TOOLS_STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#ifndef _TOOLS_GLOBNAME_HXX //autogen
#include <tools/globname.hxx>
#endif
class Storage;
class StorageStream;
class StgIo;
class StgDirEntry;
class StgStrm;
class SvGlobalName;
struct ClsId
{
INT32 n1;
INT16 n2, n3;
UINT8 n4, n5, n6, n7, n8, n9, n10, n11;
};
class StorageBase : public SvRefBase
{
protected:
ULONG nError; // error code
StreamMode nMode; // open mode
BOOL bAutoCommit;
StorageBase();
virtual ~StorageBase();
public:
TYPEINFO();
virtual const SvStream* GetSvStream() const = 0;
virtual BOOL Validate( BOOL=FALSE ) const = 0;
virtual BOOL ValidateMode( StreamMode ) const = 0;
void ResetError() const;
void SetError( ULONG ) const;
ULONG GetError() const;
BOOL Good() const { return BOOL( nError == SVSTREAM_OK ); }
StreamMode GetMode() const { return nMode; }
void SetAutoCommit( BOOL bSet )
{ bAutoCommit = bSet; }
};
class BaseStorageStream : public StorageBase
{
public:
TYPEINFO();
virtual ULONG Read( void * pData, ULONG nSize ) = 0;
virtual ULONG Write( const void* pData, ULONG nSize ) = 0;
virtual ULONG Seek( ULONG nPos ) = 0;
virtual ULONG Tell() = 0;
virtual void Flush() = 0;
virtual BOOL SetSize( ULONG nNewSize ) = 0;
virtual BOOL CopyTo( BaseStorageStream * pDestStm ) = 0;
virtual BOOL Commit() = 0;
virtual BOOL Revert() = 0;
virtual BOOL Equals( const BaseStorageStream& rStream ) const = 0;
};
class SvStorageInfoList;
class BaseStorage : public StorageBase
{
public:
TYPEINFO();
virtual const String& GetName() const = 0;
virtual BOOL IsRoot() const = 0;
virtual void SetClassId( const ClsId& ) = 0;
virtual const ClsId& GetClassId() const = 0;
virtual void SetDirty() = 0;
virtual void SetClass( const SvGlobalName & rClass,
ULONG nOriginalClipFormat,
const String & rUserTypeName ) = 0;
virtual void SetConvertClass( const SvGlobalName & rConvertClass,
ULONG nOriginalClipFormat,
const String & rUserTypeName ) = 0;
virtual SvGlobalName GetClassName() = 0;
virtual ULONG GetFormat() = 0;
virtual String GetUserName() = 0;
virtual BOOL ShouldConvert() = 0;
virtual void FillInfoList( SvStorageInfoList* ) const = 0;
virtual BOOL CopyTo( BaseStorage* pDestStg ) const = 0;
virtual BOOL Commit() = 0;
virtual BOOL Revert() = 0;
virtual BaseStorageStream* OpenStream( const String & rEleName,
StreamMode = STREAM_STD_READWRITE,
BOOL bDirect = TRUE ) = 0;
virtual BaseStorage* OpenStorage( const String & rEleName,
StreamMode = STREAM_STD_READWRITE,
BOOL bDirect = FALSE ) = 0;
virtual BaseStorage* OpenUCBStorage( const String & rEleName,
StreamMode = STREAM_STD_READWRITE,
BOOL bDirect = FALSE ) = 0;
virtual BaseStorage* OpenOLEStorage( const String & rEleName,
StreamMode = STREAM_STD_READWRITE,
BOOL bDirect = FALSE ) = 0;
virtual BOOL IsStream( const String& rEleName ) const = 0;
virtual BOOL IsStorage( const String& rEleName ) const = 0;
virtual BOOL IsContained( const String& rEleName ) const = 0;
virtual BOOL Remove( const String & rEleName ) = 0;
virtual BOOL Rename( const String & rEleName, const String & rNewName ) = 0;
virtual BOOL CopyTo( const String & rEleName, BaseStorage * pDest, const String & rNewName ) = 0;
virtual BOOL MoveTo( const String & rEleName, BaseStorage * pDest, const String & rNewName ) = 0;
virtual BOOL ValidateFAT() = 0;
virtual BOOL Equals( const BaseStorage& rStream ) const = 0;
};
class OLEStorageBase
{
protected:
StreamMode& nStreamMode; // open mode
StgIo* pIo; // I/O subsystem
StgDirEntry* pEntry; // the dir entry
OLEStorageBase( StgIo*, StgDirEntry*, StreamMode& );
~OLEStorageBase();
BOOL Validate_Impl( BOOL=FALSE ) const;
BOOL ValidateMode_Impl( StreamMode, StgDirEntry* p = NULL ) const ;
const SvStream* GetSvStream_Impl() const;
public:
};
class StorageStream : public BaseStorageStream, public OLEStorageBase
{
//friend class Storage;
ULONG nPos; // current position
protected:
~StorageStream();
public:
TYPEINFO();
StorageStream( StgIo*, StgDirEntry*, StreamMode );
virtual ULONG Read( void * pData, ULONG nSize );
virtual ULONG Write( const void* pData, ULONG nSize );
virtual ULONG Seek( ULONG nPos );
virtual ULONG Tell() { return nPos; }
virtual void Flush();
virtual BOOL SetSize( ULONG nNewSize );
virtual BOOL CopyTo( BaseStorageStream * pDestStm );
virtual BOOL Commit();
virtual BOOL Revert();
virtual BOOL Validate( BOOL=FALSE ) const;
virtual BOOL ValidateMode( StreamMode ) const;
BOOL ValidateMode( StreamMode, StgDirEntry* p ) const;
const SvStream* GetSvStream() const;
virtual BOOL Equals( const BaseStorageStream& rStream ) const;
};
class Storage : public BaseStorage, public OLEStorageBase
{
String aName;
BOOL bIsRoot;
void Init( BOOL bCreate );
Storage( StgIo*, StgDirEntry*, StreamMode );
protected:
~Storage();
public:
TYPEINFO();
Storage( const String &, StreamMode = STREAM_STD_READWRITE, BOOL bDirect = TRUE );
Storage( SvStream& rStrm, BOOL bDirect = TRUE );
static BOOL IsStorageFile( const String & rFileName );
static BOOL IsStorageFile( SvStream* );
virtual const String& GetName() const;
virtual BOOL IsRoot() const { return bIsRoot; }
virtual void SetClassId( const ClsId& );
virtual const ClsId& GetClassId() const;
virtual void SetDirty();
virtual void SetClass( const SvGlobalName & rClass,
ULONG nOriginalClipFormat,
const String & rUserTypeName );
virtual void SetConvertClass( const SvGlobalName & rConvertClass,
ULONG nOriginalClipFormat,
const String & rUserTypeName );
virtual SvGlobalName GetClassName();
virtual ULONG GetFormat();
virtual String GetUserName();
virtual BOOL ShouldConvert();
virtual void FillInfoList( SvStorageInfoList* ) const;
virtual BOOL CopyTo( BaseStorage* pDestStg ) const;
virtual BOOL Commit();
virtual BOOL Revert();
virtual BaseStorageStream* OpenStream( const String & rEleName,
StreamMode = STREAM_STD_READWRITE,
BOOL bDirect = TRUE );
virtual BaseStorage* OpenStorage( const String & rEleName,
StreamMode = STREAM_STD_READWRITE,
BOOL bDirect = FALSE );
virtual BaseStorage* OpenUCBStorage( const String & rEleName,
StreamMode = STREAM_STD_READWRITE,
BOOL bDirect = FALSE );
virtual BaseStorage* OpenOLEStorage( const String & rEleName,
StreamMode = STREAM_STD_READWRITE,
BOOL bDirect = FALSE );
virtual BOOL IsStream( const String& rEleName ) const;
virtual BOOL IsStorage( const String& rEleName ) const;
virtual BOOL IsContained( const String& rEleName ) const;
virtual BOOL Remove( const String & rEleName );
virtual BOOL Rename( const String & rEleName, const String & rNewName );
virtual BOOL CopyTo( const String & rEleName, BaseStorage * pDest, const String & rNewName );
virtual BOOL MoveTo( const String & rEleName, BaseStorage * pDest, const String & rNewName );
virtual BOOL ValidateFAT();
virtual BOOL Validate( BOOL=FALSE ) const;
virtual BOOL ValidateMode( StreamMode ) const;
BOOL ValidateMode( StreamMode, StgDirEntry* p ) const;
virtual const SvStream* GetSvStream() const;
virtual BOOL Equals( const BaseStorage& rStream ) const;
};
class UCBStorageStream_Impl;
class UCBStorageStream : public BaseStorageStream
{
friend class UCBStorage;
UCBStorageStream_Impl*
pImp;
protected:
~UCBStorageStream();
public:
TYPEINFO();
UCBStorageStream( const String& rName, StreamMode nMode, BOOL bDirect );
UCBStorageStream( UCBStorageStream_Impl* );
virtual ULONG Read( void * pData, ULONG nSize );
virtual ULONG Write( const void* pData, ULONG nSize );
virtual ULONG Seek( ULONG nPos );
virtual ULONG Tell();
virtual void Flush();
virtual BOOL SetSize( ULONG nNewSize );
virtual BOOL CopyTo( BaseStorageStream * pDestStm );
virtual BOOL Commit();
virtual BOOL Revert();
virtual BOOL Validate( BOOL=FALSE ) const;
virtual BOOL ValidateMode( StreamMode ) const;
const SvStream* GetSvStream() const;
virtual BOOL Equals( const BaseStorageStream& rStream ) const;
BOOL SetProperty( const String& rName, const ::com::sun::star::uno::Any& rValue );
BOOL GetProperty( const String& rName, ::com::sun::star::uno::Any& rValue );
};
class UCBStorage_Impl;
struct UCBStorageElement_Impl;
class UCBStorage : public BaseStorage
{
UCBStorage_Impl* pImp;
protected:
~UCBStorage();
public:
static BOOL IsStorageFile( SvStream* );
UCBStorage( const String& rName, StreamMode nMode, BOOL bDirect = TRUE, BOOL bIsRoot = TRUE );
UCBStorage( UCBStorage_Impl* );
UCBStorage( SvStream& rStrm, BOOL bDirect = TRUE );
TYPEINFO();
virtual const String& GetName() const;
virtual BOOL IsRoot() const;
virtual void SetClassId( const ClsId& );
virtual const ClsId& GetClassId() const;
virtual void SetDirty();
virtual void SetClass( const SvGlobalName & rClass,
ULONG nOriginalClipFormat,
const String & rUserTypeName );
virtual void SetConvertClass( const SvGlobalName & rConvertClass,
ULONG nOriginalClipFormat,
const String & rUserTypeName );
virtual SvGlobalName GetClassName();
virtual ULONG GetFormat();
virtual String GetUserName();
virtual BOOL ShouldConvert();
virtual void FillInfoList( SvStorageInfoList* ) const;
virtual BOOL CopyTo( BaseStorage* pDestStg ) const;
virtual BOOL Commit();
virtual BOOL Revert();
virtual BaseStorageStream* OpenStream( const String & rEleName,
StreamMode = STREAM_STD_READWRITE,
BOOL bDirect = TRUE );
virtual BaseStorage* OpenStorage( const String & rEleName,
StreamMode = STREAM_STD_READWRITE,
BOOL bDirect = FALSE );
virtual BaseStorage* OpenUCBStorage( const String & rEleName,
StreamMode = STREAM_STD_READWRITE,
BOOL bDirect = FALSE );
virtual BaseStorage* OpenOLEStorage( const String & rEleName,
StreamMode = STREAM_STD_READWRITE,
BOOL bDirect = FALSE );
virtual BOOL IsStream( const String& rEleName ) const;
virtual BOOL IsStorage( const String& rEleName ) const;
virtual BOOL IsContained( const String& rEleName ) const;
virtual BOOL Remove( const String & rEleName );
virtual BOOL Rename( const String & rEleName, const String & rNewName );
virtual BOOL CopyTo( const String & rEleName, BaseStorage * pDest, const String & rNewName );
virtual BOOL MoveTo( const String & rEleName, BaseStorage * pDest, const String & rNewName );
virtual BOOL ValidateFAT();
virtual BOOL Validate( BOOL=FALSE ) const;
virtual BOOL ValidateMode( StreamMode ) const;
virtual const SvStream* GetSvStream() const;
virtual BOOL Equals( const BaseStorage& rStream ) const;
BOOL SetProperty( const String& rName, const ::com::sun::star::uno::Any& rValue );
BOOL GetProperty( const String& rName, ::com::sun::star::uno::Any& rValue );
#if _SOLAR__PRIVATE
UCBStorageElement_Impl* FindElement_Impl( const String& rName ) const;
BOOL CopyStorageElement_Impl( UCBStorageElement_Impl& rElement,
BaseStorage* pDest, const String& rNew ) const;
BaseStorage* OpenStorage_Impl( const String & rEleName,
StreamMode, BOOL bDirect, BOOL bForceUCBStorage );
#endif
};
#endif
<|endoftext|> |
<commit_before>//===--- ProtocolHandlers.cpp - LSP callbacks -----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "ProtocolHandlers.h"
#include "DocumentStore.h"
#include "clang/Format/Format.h"
using namespace clang;
using namespace clangd;
void TextDocumentDidOpenHandler::handleNotification(
llvm::yaml::MappingNode *Params) {
auto DOTDP = DidOpenTextDocumentParams::parse(Params);
if (!DOTDP) {
Output.logs() << "Failed to decode DidOpenTextDocumentParams!\n";
return;
}
Store.addDocument(DOTDP->textDocument.uri, DOTDP->textDocument.text);
}
void TextDocumentDidChangeHandler::handleNotification(
llvm::yaml::MappingNode *Params) {
auto DCTDP = DidChangeTextDocumentParams::parse(Params);
if (!DCTDP || DCTDP->contentChanges.size() != 1) {
Output.logs() << "Failed to decode DidChangeTextDocumentParams!\n";
return;
}
// We only support full syncing right now.
Store.addDocument(DCTDP->textDocument.uri, DCTDP->contentChanges[0].text);
}
/// Turn a [line, column] pair into an offset in Code.
static size_t positionToOffset(StringRef Code, Position P) {
size_t Offset = 0;
for (int I = 0; I != P.line; ++I) {
// FIXME: \r\n
// FIXME: UTF-8
size_t F = Code.find('\n', Offset);
if (F == StringRef::npos)
return 0; // FIXME: Is this reasonable?
Offset = F + 1;
}
return (Offset == 0 ? 0 : (Offset - 1)) + P.character;
}
/// Turn an offset in Code into a [line, column] pair.
static Position offsetToPosition(StringRef Code, size_t Offset) {
StringRef JustBefore = Code.substr(0, Offset);
// FIXME: \r\n
// FIXME: UTF-8
int Lines = JustBefore.count('\n');
int Cols = JustBefore.size() - JustBefore.rfind('\n') - 1;
return {Lines, Cols};
}
static std::string formatCode(StringRef Code, StringRef Filename,
ArrayRef<tooling::Range> Ranges, StringRef ID) {
// Call clang-format.
// FIXME: Don't ignore style.
format::FormatStyle Style = format::getLLVMStyle();
// On windows FileManager doesn't like file://. Just strip it, clang-format
// doesn't need it.
Filename.consume_front("file://");
tooling::Replacements Replacements =
format::reformat(Style, Code, Ranges, Filename);
// Now turn the replacements into the format specified by the Language Server
// Protocol. Fuse them into one big JSON array.
std::string Edits;
for (auto &R : Replacements) {
Range ReplacementRange = {
offsetToPosition(Code, R.getOffset()),
offsetToPosition(Code, R.getOffset() + R.getLength())};
TextEdit TE = {ReplacementRange, R.getReplacementText()};
Edits += TextEdit::unparse(TE);
Edits += ',';
}
if (!Edits.empty())
Edits.pop_back();
return R"({"jsonrpc":"2.0","id":)" + ID.str() +
R"(,"result":[)" + Edits + R"(]})";
}
void TextDocumentRangeFormattingHandler::handleMethod(
llvm::yaml::MappingNode *Params, StringRef ID) {
auto DRFP = DocumentRangeFormattingParams::parse(Params);
if (!DRFP) {
Output.logs() << "Failed to decode DocumentRangeFormattingParams!\n";
return;
}
StringRef Code = Store.getDocument(DRFP->textDocument.uri);
size_t Begin = positionToOffset(Code, DRFP->range.start);
size_t Len = positionToOffset(Code, DRFP->range.end) - Begin;
writeMessage(formatCode(Code, DRFP->textDocument.uri,
{clang::tooling::Range(Begin, Len)}, ID));
}
void TextDocumentFormattingHandler::handleMethod(
llvm::yaml::MappingNode *Params, StringRef ID) {
auto DFP = DocumentFormattingParams::parse(Params);
if (!DFP) {
Output.logs() << "Failed to decode DocumentFormattingParams!\n";
return;
}
// Format everything.
StringRef Code = Store.getDocument(DFP->textDocument.uri);
writeMessage(formatCode(Code, DFP->textDocument.uri,
{clang::tooling::Range(0, Code.size())}, ID));
}
<commit_msg>[clangd] Fix use after free.<commit_after>//===--- ProtocolHandlers.cpp - LSP callbacks -----------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "ProtocolHandlers.h"
#include "DocumentStore.h"
#include "clang/Format/Format.h"
using namespace clang;
using namespace clangd;
void TextDocumentDidOpenHandler::handleNotification(
llvm::yaml::MappingNode *Params) {
auto DOTDP = DidOpenTextDocumentParams::parse(Params);
if (!DOTDP) {
Output.logs() << "Failed to decode DidOpenTextDocumentParams!\n";
return;
}
Store.addDocument(DOTDP->textDocument.uri, DOTDP->textDocument.text);
}
void TextDocumentDidChangeHandler::handleNotification(
llvm::yaml::MappingNode *Params) {
auto DCTDP = DidChangeTextDocumentParams::parse(Params);
if (!DCTDP || DCTDP->contentChanges.size() != 1) {
Output.logs() << "Failed to decode DidChangeTextDocumentParams!\n";
return;
}
// We only support full syncing right now.
Store.addDocument(DCTDP->textDocument.uri, DCTDP->contentChanges[0].text);
}
/// Turn a [line, column] pair into an offset in Code.
static size_t positionToOffset(StringRef Code, Position P) {
size_t Offset = 0;
for (int I = 0; I != P.line; ++I) {
// FIXME: \r\n
// FIXME: UTF-8
size_t F = Code.find('\n', Offset);
if (F == StringRef::npos)
return 0; // FIXME: Is this reasonable?
Offset = F + 1;
}
return (Offset == 0 ? 0 : (Offset - 1)) + P.character;
}
/// Turn an offset in Code into a [line, column] pair.
static Position offsetToPosition(StringRef Code, size_t Offset) {
StringRef JustBefore = Code.substr(0, Offset);
// FIXME: \r\n
// FIXME: UTF-8
int Lines = JustBefore.count('\n');
int Cols = JustBefore.size() - JustBefore.rfind('\n') - 1;
return {Lines, Cols};
}
static std::string formatCode(StringRef Code, StringRef Filename,
ArrayRef<tooling::Range> Ranges, StringRef ID) {
// Call clang-format.
// FIXME: Don't ignore style.
format::FormatStyle Style = format::getLLVMStyle();
// On windows FileManager doesn't like file://. Just strip it, clang-format
// doesn't need it.
Filename.consume_front("file://");
tooling::Replacements Replacements =
format::reformat(Style, Code, Ranges, Filename);
// Now turn the replacements into the format specified by the Language Server
// Protocol. Fuse them into one big JSON array.
std::string Edits;
for (auto &R : Replacements) {
Range ReplacementRange = {
offsetToPosition(Code, R.getOffset()),
offsetToPosition(Code, R.getOffset() + R.getLength())};
TextEdit TE = {ReplacementRange, R.getReplacementText()};
Edits += TextEdit::unparse(TE);
Edits += ',';
}
if (!Edits.empty())
Edits.pop_back();
return R"({"jsonrpc":"2.0","id":)" + ID.str() +
R"(,"result":[)" + Edits + R"(]})";
}
void TextDocumentRangeFormattingHandler::handleMethod(
llvm::yaml::MappingNode *Params, StringRef ID) {
auto DRFP = DocumentRangeFormattingParams::parse(Params);
if (!DRFP) {
Output.logs() << "Failed to decode DocumentRangeFormattingParams!\n";
return;
}
std::string Code = Store.getDocument(DRFP->textDocument.uri);
size_t Begin = positionToOffset(Code, DRFP->range.start);
size_t Len = positionToOffset(Code, DRFP->range.end) - Begin;
writeMessage(formatCode(Code, DRFP->textDocument.uri,
{clang::tooling::Range(Begin, Len)}, ID));
}
void TextDocumentFormattingHandler::handleMethod(
llvm::yaml::MappingNode *Params, StringRef ID) {
auto DFP = DocumentFormattingParams::parse(Params);
if (!DFP) {
Output.logs() << "Failed to decode DocumentFormattingParams!\n";
return;
}
// Format everything.
StringRef Code = Store.getDocument(DFP->textDocument.uri);
writeMessage(formatCode(Code, DFP->textDocument.uri,
{clang::tooling::Range(0, Code.size())}, ID));
}
<|endoftext|> |
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <stdlib.h>
#include <string.h>
#include <osg/CullSettings>
#include <osg/ArgumentParser>
#include <osg/ApplicationUsage>
#include <osg/Notify>
using namespace osg;
CullSettings::CullSettings(const CullSettings& cs)
{
setCullSettings(cs);
}
void CullSettings::setDefaults()
{
_inheritanceMask = ALL_VARIABLES;
_inheritanceMaskActionOnAttributeSetting = DISABLE_ASSOCIATED_INHERITANCE_MASK_BIT;
_cullingMode = DEFAULT_CULLING;
_LODScale = 1.0f;
_smallFeatureCullingPixelSize = 2.0f;
_computeNearFar = COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES;
_nearFarRatio = 0.0005f;
_impostorActive = true;
_depthSortImpostorSprites = false;
_impostorPixelErrorThreshold = 4.0f;
_numFramesToKeepImpostorSprites = 10;
_cullMask = 0xffffffff;
_cullMaskLeft = 0xffffffff;
_cullMaskRight = 0xffffffff;
// override during testing
//_computeNearFar = COMPUTE_NEAR_FAR_USING_PRIMITIVES;
//_nearFarRatio = 0.00005f;
}
void CullSettings::setCullSettings(const CullSettings& rhs)
{
_inheritanceMask = rhs._inheritanceMask;
_inheritanceMaskActionOnAttributeSetting = rhs._inheritanceMaskActionOnAttributeSetting;
_computeNearFar = rhs._computeNearFar;
_cullingMode = rhs._cullingMode;
_LODScale = rhs._LODScale;
_smallFeatureCullingPixelSize = rhs._smallFeatureCullingPixelSize;
_clampProjectionMatrixCallback = rhs._clampProjectionMatrixCallback;
_nearFarRatio = rhs._nearFarRatio;
_impostorActive = rhs._impostorActive;
_depthSortImpostorSprites = rhs._depthSortImpostorSprites;
_impostorPixelErrorThreshold = rhs._impostorPixelErrorThreshold;
_numFramesToKeepImpostorSprites = rhs._numFramesToKeepImpostorSprites;
_cullMask = rhs._cullMask;
_cullMaskLeft = rhs._cullMaskLeft;
_cullMaskRight = rhs._cullMaskRight;
}
void CullSettings::inheritCullSettings(const CullSettings& settings, unsigned int inheritanceMask)
{
if (inheritanceMask & COMPUTE_NEAR_FAR_MODE) _computeNearFar = settings._computeNearFar;
if (inheritanceMask & NEAR_FAR_RATIO) _nearFarRatio = settings._nearFarRatio;
if (inheritanceMask & IMPOSTOR_ACTIVE) _impostorActive = settings._impostorActive;
if (inheritanceMask & DEPTH_SORT_IMPOSTOR_SPRITES) _depthSortImpostorSprites = settings._depthSortImpostorSprites;
if (inheritanceMask & IMPOSTOR_PIXEL_ERROR_THRESHOLD) _impostorPixelErrorThreshold = settings._impostorPixelErrorThreshold;
if (inheritanceMask & NUM_FRAMES_TO_KEEP_IMPOSTORS_SPRITES) _numFramesToKeepImpostorSprites = settings._numFramesToKeepImpostorSprites;
if (inheritanceMask & CULL_MASK) _cullMask = settings._cullMask;
if (inheritanceMask & CULL_MASK_LEFT) _cullMaskLeft = settings._cullMaskLeft;
if (inheritanceMask & CULL_MASK_RIGHT) _cullMaskRight = settings._cullMaskRight;
if (inheritanceMask & CULLING_MODE) _cullingMode = settings._cullingMode;
if (inheritanceMask & LOD_SCALE) _LODScale = settings._LODScale;
if (inheritanceMask & SMALL_FEATURE_CULLING_PIXEL_SIZE) _smallFeatureCullingPixelSize = settings._smallFeatureCullingPixelSize;
if (inheritanceMask & CLAMP_PROJECTION_MATRIX_CALLBACK) _clampProjectionMatrixCallback = settings._clampProjectionMatrixCallback;
}
static ApplicationUsageProxy ApplicationUsageProxyCullSettings_e0(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_COMPUTE_NEAR_FAR_MODE <mode>","DO_NOT_COMPUTE_NEAR_FAR | COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES | COMPUTE_NEAR_FAR_USING_PRIMITIVES");
static ApplicationUsageProxy ApplicationUsageProxyCullSettings_e1(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_NEAR_FAR_RATIO <float>","Set the ratio between near and far planes - must greater than 0.0 but less than 1.0.");
void CullSettings::readEnvironmentalVariables()
{
OSG_INFO<<"CullSettings::readEnvironmentalVariables()"<<std::endl;
char *ptr;
if ((ptr = getenv("OSG_COMPUTE_NEAR_FAR_MODE")) != 0)
{
if (strcmp(ptr,"DO_NOT_COMPUTE_NEAR_FAR")==0) _computeNearFar = DO_NOT_COMPUTE_NEAR_FAR;
else if (strcmp(ptr,"COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES")==0) _computeNearFar = COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES;
else if (strcmp(ptr,"COMPUTE_NEAR_FAR_USING_PRIMITIVES")==0) _computeNearFar = COMPUTE_NEAR_FAR_USING_PRIMITIVES;
OSG_INFO<<"Set compute near far mode to "<<_computeNearFar<<std::endl;
}
if ((ptr = getenv("OSG_NEAR_FAR_RATIO")) != 0)
{
_nearFarRatio = osg::asciiToDouble(ptr);
OSG_INFO<<"Set near/far ratio to "<<_nearFarRatio<<std::endl;
}
}
void CullSettings::readCommandLine(ArgumentParser& arguments)
{
// report the usage options.
if (arguments.getApplicationUsage())
{
arguments.getApplicationUsage()->addCommandLineOption("--COMPUTE_NEAR_FAR_MODE <mode>","DO_NOT_COMPUTE_NEAR_FAR | COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES | COMPUTE_NEAR_FAR_USING_PRIMITIVES");
arguments.getApplicationUsage()->addCommandLineOption("--NEAR_FAR_RATIO <float>","Set the ratio between near and far planes - must greater than 0.0 but less than 1.0.");
}
std::string str;
while(arguments.read("--COMPUTE_NEAR_FAR_MODE",str))
{
if (str=="DO_NOT_COMPUTE_NEAR_FAR") _computeNearFar = DO_NOT_COMPUTE_NEAR_FAR;
else if (str=="COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES") _computeNearFar = COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES;
else if (str=="COMPUTE_NEAR_FAR_USING_PRIMITIVES") _computeNearFar = COMPUTE_NEAR_FAR_USING_PRIMITIVES;
OSG_INFO<<"Set compute near far mode to "<<_computeNearFar<<std::endl;
}
double value;
while(arguments.read("--NEAR_FAR_RATIO",value))
{
_nearFarRatio = value;
OSG_INFO<<"Set near/far ratio to "<<_nearFarRatio<<std::endl;
}
}
void CullSettings::write(std::ostream& out)
{
out<<"CullSettings: "<<this<<" {"<<std::endl;
out<<" _inheritanceMask = "<<_inheritanceMask<<std::endl;
out<<" _inheritanceMaskActionOnAttributeSetting = "<<_inheritanceMaskActionOnAttributeSetting<<std::endl;
out<<" _computeNearFar = "<<_computeNearFar<<std::endl;
out<<" _cullingMode = "<<_cullingMode<<std::endl;
out<<" _LODScale = "<<_LODScale<<std::endl;
out<<" _smallFeatureCullingPixelSize = "<<_smallFeatureCullingPixelSize<<std::endl;
out<<" _clampProjectionMatrixCallback = "<<_clampProjectionMatrixCallback.get()<<std::endl;
out<<" _nearFarRatio = "<<_nearFarRatio<<std::endl;
out<<" _impostorActive = "<<_impostorActive<<std::endl;
out<<" _depthSortImpostorSprites = "<<_depthSortImpostorSprites<<std::endl;
out<<" _impostorPixelErrorThreshold = "<<_impostorPixelErrorThreshold<<std::endl;
out<<" _numFramesToKeepImpostorSprites = "<<_numFramesToKeepImpostorSprites<<std::endl;
out<<" _cullMask = "<<_cullMask<<std::endl;
out<<" _cullMaskLeft = "<<_cullMaskLeft<<std::endl;
out<<" _cullMaskRight = "<<_cullMaskRight<<std::endl;
out<<"{"<<std::endl;
}
<commit_msg>Fixed type of numberical constant<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <stdlib.h>
#include <string.h>
#include <osg/CullSettings>
#include <osg/ArgumentParser>
#include <osg/ApplicationUsage>
#include <osg/Notify>
using namespace osg;
CullSettings::CullSettings(const CullSettings& cs)
{
setCullSettings(cs);
}
void CullSettings::setDefaults()
{
_inheritanceMask = ALL_VARIABLES;
_inheritanceMaskActionOnAttributeSetting = DISABLE_ASSOCIATED_INHERITANCE_MASK_BIT;
_cullingMode = DEFAULT_CULLING;
_LODScale = 1.0f;
_smallFeatureCullingPixelSize = 2.0f;
_computeNearFar = COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES;
_nearFarRatio = 0.0005;
_impostorActive = true;
_depthSortImpostorSprites = false;
_impostorPixelErrorThreshold = 4.0f;
_numFramesToKeepImpostorSprites = 10;
_cullMask = 0xffffffff;
_cullMaskLeft = 0xffffffff;
_cullMaskRight = 0xffffffff;
// override during testing
//_computeNearFar = COMPUTE_NEAR_FAR_USING_PRIMITIVES;
//_nearFarRatio = 0.00005f;
}
void CullSettings::setCullSettings(const CullSettings& rhs)
{
_inheritanceMask = rhs._inheritanceMask;
_inheritanceMaskActionOnAttributeSetting = rhs._inheritanceMaskActionOnAttributeSetting;
_computeNearFar = rhs._computeNearFar;
_cullingMode = rhs._cullingMode;
_LODScale = rhs._LODScale;
_smallFeatureCullingPixelSize = rhs._smallFeatureCullingPixelSize;
_clampProjectionMatrixCallback = rhs._clampProjectionMatrixCallback;
_nearFarRatio = rhs._nearFarRatio;
_impostorActive = rhs._impostorActive;
_depthSortImpostorSprites = rhs._depthSortImpostorSprites;
_impostorPixelErrorThreshold = rhs._impostorPixelErrorThreshold;
_numFramesToKeepImpostorSprites = rhs._numFramesToKeepImpostorSprites;
_cullMask = rhs._cullMask;
_cullMaskLeft = rhs._cullMaskLeft;
_cullMaskRight = rhs._cullMaskRight;
}
void CullSettings::inheritCullSettings(const CullSettings& settings, unsigned int inheritanceMask)
{
if (inheritanceMask & COMPUTE_NEAR_FAR_MODE) _computeNearFar = settings._computeNearFar;
if (inheritanceMask & NEAR_FAR_RATIO) _nearFarRatio = settings._nearFarRatio;
if (inheritanceMask & IMPOSTOR_ACTIVE) _impostorActive = settings._impostorActive;
if (inheritanceMask & DEPTH_SORT_IMPOSTOR_SPRITES) _depthSortImpostorSprites = settings._depthSortImpostorSprites;
if (inheritanceMask & IMPOSTOR_PIXEL_ERROR_THRESHOLD) _impostorPixelErrorThreshold = settings._impostorPixelErrorThreshold;
if (inheritanceMask & NUM_FRAMES_TO_KEEP_IMPOSTORS_SPRITES) _numFramesToKeepImpostorSprites = settings._numFramesToKeepImpostorSprites;
if (inheritanceMask & CULL_MASK) _cullMask = settings._cullMask;
if (inheritanceMask & CULL_MASK_LEFT) _cullMaskLeft = settings._cullMaskLeft;
if (inheritanceMask & CULL_MASK_RIGHT) _cullMaskRight = settings._cullMaskRight;
if (inheritanceMask & CULLING_MODE) _cullingMode = settings._cullingMode;
if (inheritanceMask & LOD_SCALE) _LODScale = settings._LODScale;
if (inheritanceMask & SMALL_FEATURE_CULLING_PIXEL_SIZE) _smallFeatureCullingPixelSize = settings._smallFeatureCullingPixelSize;
if (inheritanceMask & CLAMP_PROJECTION_MATRIX_CALLBACK) _clampProjectionMatrixCallback = settings._clampProjectionMatrixCallback;
}
static ApplicationUsageProxy ApplicationUsageProxyCullSettings_e0(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_COMPUTE_NEAR_FAR_MODE <mode>","DO_NOT_COMPUTE_NEAR_FAR | COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES | COMPUTE_NEAR_FAR_USING_PRIMITIVES");
static ApplicationUsageProxy ApplicationUsageProxyCullSettings_e1(ApplicationUsage::ENVIRONMENTAL_VARIABLE,"OSG_NEAR_FAR_RATIO <float>","Set the ratio between near and far planes - must greater than 0.0 but less than 1.0.");
void CullSettings::readEnvironmentalVariables()
{
OSG_INFO<<"CullSettings::readEnvironmentalVariables()"<<std::endl;
char *ptr;
if ((ptr = getenv("OSG_COMPUTE_NEAR_FAR_MODE")) != 0)
{
if (strcmp(ptr,"DO_NOT_COMPUTE_NEAR_FAR")==0) _computeNearFar = DO_NOT_COMPUTE_NEAR_FAR;
else if (strcmp(ptr,"COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES")==0) _computeNearFar = COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES;
else if (strcmp(ptr,"COMPUTE_NEAR_FAR_USING_PRIMITIVES")==0) _computeNearFar = COMPUTE_NEAR_FAR_USING_PRIMITIVES;
OSG_INFO<<"Set compute near far mode to "<<_computeNearFar<<std::endl;
}
if ((ptr = getenv("OSG_NEAR_FAR_RATIO")) != 0)
{
_nearFarRatio = osg::asciiToDouble(ptr);
OSG_INFO<<"Set near/far ratio to "<<_nearFarRatio<<std::endl;
}
}
void CullSettings::readCommandLine(ArgumentParser& arguments)
{
// report the usage options.
if (arguments.getApplicationUsage())
{
arguments.getApplicationUsage()->addCommandLineOption("--COMPUTE_NEAR_FAR_MODE <mode>","DO_NOT_COMPUTE_NEAR_FAR | COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES | COMPUTE_NEAR_FAR_USING_PRIMITIVES");
arguments.getApplicationUsage()->addCommandLineOption("--NEAR_FAR_RATIO <float>","Set the ratio between near and far planes - must greater than 0.0 but less than 1.0.");
}
std::string str;
while(arguments.read("--COMPUTE_NEAR_FAR_MODE",str))
{
if (str=="DO_NOT_COMPUTE_NEAR_FAR") _computeNearFar = DO_NOT_COMPUTE_NEAR_FAR;
else if (str=="COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES") _computeNearFar = COMPUTE_NEAR_FAR_USING_BOUNDING_VOLUMES;
else if (str=="COMPUTE_NEAR_FAR_USING_PRIMITIVES") _computeNearFar = COMPUTE_NEAR_FAR_USING_PRIMITIVES;
OSG_INFO<<"Set compute near far mode to "<<_computeNearFar<<std::endl;
}
double value;
while(arguments.read("--NEAR_FAR_RATIO",value))
{
_nearFarRatio = value;
OSG_INFO<<"Set near/far ratio to "<<_nearFarRatio<<std::endl;
}
}
void CullSettings::write(std::ostream& out)
{
out<<"CullSettings: "<<this<<" {"<<std::endl;
out<<" _inheritanceMask = "<<_inheritanceMask<<std::endl;
out<<" _inheritanceMaskActionOnAttributeSetting = "<<_inheritanceMaskActionOnAttributeSetting<<std::endl;
out<<" _computeNearFar = "<<_computeNearFar<<std::endl;
out<<" _cullingMode = "<<_cullingMode<<std::endl;
out<<" _LODScale = "<<_LODScale<<std::endl;
out<<" _smallFeatureCullingPixelSize = "<<_smallFeatureCullingPixelSize<<std::endl;
out<<" _clampProjectionMatrixCallback = "<<_clampProjectionMatrixCallback.get()<<std::endl;
out<<" _nearFarRatio = "<<_nearFarRatio<<std::endl;
out<<" _impostorActive = "<<_impostorActive<<std::endl;
out<<" _depthSortImpostorSprites = "<<_depthSortImpostorSprites<<std::endl;
out<<" _impostorPixelErrorThreshold = "<<_impostorPixelErrorThreshold<<std::endl;
out<<" _numFramesToKeepImpostorSprites = "<<_numFramesToKeepImpostorSprites<<std::endl;
out<<" _cullMask = "<<_cullMask<<std::endl;
out<<" _cullMaskLeft = "<<_cullMaskLeft<<std::endl;
out<<" _cullMaskRight = "<<_cullMaskRight<<std::endl;
out<<"{"<<std::endl;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2014 Quanta Research Cambridge, Inc.
// 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 <stdio.h>
//#include <stdlib.h>
//#include <errno.h>
//#include <string.h>
//#include <unistd.h>
//#include <sys/types.h>
//#include <sys/un.h>
//#include <pthread.h>
//#include <assert.h>
//#include <portal.h>
extern "C" {
void bdpi_hdmi_vsync(unsigned int v)
{
printf("v %x; ", v);
}
void bdpi_hdmi_hsync(unsigned int v)
{
printf("h %x; ", v);
}
void bdpi_hdmi_de(unsigned int v)
{
printf("e %x; ", v);
}
void bdpi_hdmi_data(unsigned int v)
{
printf("= %4x\n", v);
}
}
<commit_msg>cleanup<commit_after>// Copyright (c) 2014 Quanta Research Cambridge, Inc.
// 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 <stdio.h>
static unsigned int vsync, hsync, de;
extern "C" void bdpi_hdmi_vsync(unsigned int v)
{
vsync = v;
}
extern "C" void bdpi_hdmi_hsync(unsigned int v)
{
hsync = v;
}
extern "C" void bdpi_hdmi_de(unsigned int v)
{
de = v;
}
extern "C" void bdpi_hdmi_data(unsigned int v)
{
#if 0
extern void show_data(unsigned int vsync, unsigned int hsync, unsigned int de, unsigned int data);
show_data(vsync, hsync, de, v);
#else
printf("v %x; h %x; e %x = %4x\n", vsync, hsync, de, v);
#endif
}
<|endoftext|> |
<commit_before>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <memory.hpp>
#include <cuda.h>
#include <cuda_runtime_api.h>
#include <cuda_runtime.h>
#include <err_cuda.hpp>
#include <types.hpp>
#include <map>
#include <dispatch.hpp>
namespace cuda
{
typedef struct
{
bool is_free;
size_t bytes;
} mem_info;
static size_t used_bytes = 0;
typedef std::map<void *, mem_info> mem_t;
typedef mem_t::iterator mem_iter;
mem_t memory_map;
template<typename T>
void cudaFreeWrapper(T *ptr)
{
cudaError_t err = cudaFree(ptr);
if (err != cudaErrorCudartUnloading) // see issue #167
CUDA_CHECK(err);
}
void garbageCollect()
{
for(mem_iter iter = memory_map.begin(); iter != memory_map.end(); iter++) {
if ((iter->second).is_free) cudaFreeWrapper(iter->first);
}
mem_iter memory_curr = memory_map.begin();
mem_iter memory_end = memory_map.end();
while(memory_curr != memory_end) {
if (memory_curr->second.is_free) {
memory_map.erase(memory_curr++);
} else {
++memory_curr;
}
}
}
template<typename T>
T* memAlloc(const size_t &elements)
{
T* ptr = NULL;
size_t alloc_bytes = divup(sizeof(T) * elements, 1024) * 1024;
if (elements > 0) {
// FIXME: Add better checks for garbage collection
// Perhaps look at total memory available as a metric
if (memory_map.size() > 100 || used_bytes >= (1 << 30)) {
garbageCollect();
}
for(mem_iter iter = memory_map.begin(); iter != memory_map.end(); iter++) {
mem_info info = iter->second;
if (info.is_free && info.bytes == alloc_bytes) {
iter->second.is_free = false;
used_bytes += alloc_bytes;
return (T *)iter->first;
}
}
// Perform garbage collection if memory can not be allocated
if (cudaMalloc((void **)&ptr, alloc_bytes) != cudaSuccess) {
garbageCollect();
CUDA_CHECK(cudaMalloc((void **)(&ptr), alloc_bytes));
}
mem_info info = {false, alloc_bytes};
memory_map[ptr] = info;
used_bytes += alloc_bytes;
}
return ptr;
}
template<typename T>
void memFree(T *ptr)
{
mem_iter iter = memory_map.find((void *)ptr);
if (iter != memory_map.end()) {
iter->second.is_free = true;
used_bytes -= iter->second.bytes;
} else {
cudaFreeWrapper(ptr); // Free it because we are not sure what the size is
}
}
#define INSTANTIATE(T) \
template T* memAlloc(const size_t &elements); \
template void memFree(T* ptr); \
INSTANTIATE(float)
INSTANTIATE(cfloat)
INSTANTIATE(double)
INSTANTIATE(cdouble)
INSTANTIATE(int)
INSTANTIATE(uint)
INSTANTIATE(char)
INSTANTIATE(uchar)
}
<commit_msg>BUG: Fix in memory manager for CUDA backend with multiple devices<commit_after>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <memory.hpp>
#include <cuda.h>
#include <cuda_runtime_api.h>
#include <cuda_runtime.h>
#include <err_cuda.hpp>
#include <types.hpp>
#include <map>
#include <dispatch.hpp>
#include <platform.hpp>
namespace cuda
{
template<typename T>
void cudaFreeWrapper(T *ptr)
{
cudaError_t err = cudaFree(ptr);
if (err != cudaErrorCudartUnloading) // see issue #167
CUDA_CHECK(err);
}
#ifdef CUDA_MEM_DEBUG
template<typename T>
T* memAlloc(const size_t &elements)
{
T* ptr = NULL;
CUDA_CHECK(cudaMalloc(&ptr, elements * sizeof(T)));
return ptr;
}
template<typename T>
void memFree(T *ptr)
{
cudaFreeWrapper(ptr); // Free it because we are not sure what the size is
}
#else
const int MAX_BUFFERS = 100;
typedef struct
{
bool is_free;
size_t bytes;
} mem_info;
static size_t used_bytes = 0;
typedef std::map<void *, mem_info> mem_t;
typedef mem_t::iterator mem_iter;
mem_t memory_maps[DeviceManager::MAX_DEVICES];
void garbageCollect()
{
int n = getActiveDeviceId();
for(mem_iter iter = memory_maps[n].begin(); iter != memory_maps[n].end(); iter++) {
if ((iter->second).is_free) cudaFreeWrapper(iter->first);
}
mem_iter memory_curr = memory_maps[n].begin();
mem_iter memory_end = memory_maps[n].end();
while(memory_curr != memory_end) {
if (memory_curr->second.is_free) {
memory_maps[n].erase(memory_curr++);
} else {
++memory_curr;
}
}
}
template<typename T>
T* memAlloc(const size_t &elements)
{
int n = getActiveDeviceId();
T* ptr = NULL;
size_t alloc_bytes = divup(sizeof(T) * elements, 1024) * 1024;
if (elements > 0) {
// FIXME: Add better checks for garbage collection
// Perhaps look at total memory available as a metric
if (memory_maps[n].size() >= MAX_BUFFERS || used_bytes >= (1 << 30)) {
garbageCollect();
}
for(mem_iter iter = memory_maps[n].begin(); iter != memory_maps[n].end(); iter++) {
mem_info info = iter->second;
if (info.is_free && info.bytes == alloc_bytes) {
iter->second.is_free = false;
used_bytes += alloc_bytes;
return (T *)iter->first;
}
}
// Perform garbage collection if memory can not be allocated
if (cudaMalloc((void **)&ptr, alloc_bytes) != cudaSuccess) {
garbageCollect();
CUDA_CHECK(cudaMalloc((void **)(&ptr), alloc_bytes));
}
mem_info info = {false, alloc_bytes};
memory_maps[n][ptr] = info;
used_bytes += alloc_bytes;
}
return ptr;
}
template<typename T>
void memFree(T *ptr)
{
int n = getActiveDeviceId();
mem_iter iter = memory_maps[n].find((void *)ptr);
if (iter != memory_maps[n].end()) {
iter->second.is_free = true;
used_bytes -= iter->second.bytes;
} else {
cudaFreeWrapper(ptr); // Free it because we are not sure what the size is
}
}
#endif
#define INSTANTIATE(T) \
template T* memAlloc(const size_t &elements); \
template void memFree(T* ptr); \
INSTANTIATE(float)
INSTANTIATE(cfloat)
INSTANTIATE(double)
INSTANTIATE(cdouble)
INSTANTIATE(int)
INSTANTIATE(uint)
INSTANTIATE(char)
INSTANTIATE(uchar)
}
<|endoftext|> |
<commit_before>// $Id: equation_systems.C,v 1.17 2003-02-17 01:23:01 benkirk Exp $
// The Next Great Finite Element Library.
// Copyright (C) 2002 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// System includes
#include <sstream>
// Local Includes
//#include "enum_solver_package.h"
#include "libmesh.h"
#include "fe_interface.h"
//#include "petsc_vector.h"
//#include "petsc_matrix.h"
//#include "petsc_interface.h"
#include "linear_solver_interface.h"
#include "equation_systems.h"
#include "general_system.h"
// Forward Declarations
// ------------------------------------------------------------
// EquationSystem class implementation
EquationSystems::EquationSystems (Mesh& m,
const SolverPackage sp) :
_mesh(m),
_solver_package(sp)
{
// Default parameters
set_parameter("linear solver tolerance") = 1.e-12;
set_parameter("linear solver maximum iterations") = 5000;
}
EquationSystems::~EquationSystems ()
{
clear();
assert (!libMesh::closed());
}
void EquationSystems::clear ()
{
for (std::map<std::string, GeneralSystem*>::iterator
pos = _systems.begin(); pos != _systems.end();
++pos)
delete pos->second;
_systems.clear ();
_flags.clear ();
_parameters.clear ();
}
void EquationSystems::init ()
{
const unsigned int n_sys = n_systems();
assert (n_sys != 0);
// /**
// * Tell all the \p DofObject entities how many systems
// * there are.
// */
// {
// // All the nodes
// node_iterator node_it (_mesh.nodes_begin());
// const node_iterator node_end (_mesh.nodes_end());
// for ( ; node_it != node_end; ++node_it)
// (*node_it)->set_n_systems(n_sys);
// // All the elements
// elem_iterator elem_it (_mesh.elements_begin());
// const elem_iterator elem_end(_mesh.elements_end());
// for ( ; elem_it != elem_end; ++elem_it)
// (*elem_it)->set_n_systems(n_sys);
// }
for (std::map<std::string, GeneralSystem*>::iterator
sys = _systems.begin(); sys != _systems.end();
++sys)
{
/**
* Initialize the system.
*/
sys->second->init();
}
}
void EquationSystems::add_system (const std::string& name)
{
if (!_systems.count(name))
{
const unsigned int num = n_systems();
_systems.insert (std::pair<std::string,
GeneralSystem*>(name,
new GeneralSystem(*this,
name,
num,
_solver_package)
)
);
}
else
{
std::cerr << "ERROR: There was already a system"
<< " named " << name
<< std::endl;
error();
}
/**
* Tell all the \p DofObject entities to add a system.
*/
{
// All the nodes
node_iterator node_it (_mesh.nodes_begin());
const node_iterator node_end (_mesh.nodes_end());
for ( ; node_it != node_end; ++node_it)
(*node_it)->add_system();
// All the elements
elem_iterator elem_it (_mesh.elements_begin());
const elem_iterator elem_end(_mesh.elements_end());
for ( ; elem_it != elem_end; ++elem_it)
(*elem_it)->add_system();
}
}
void EquationSystems::delete_system (const std::string& name)
{
if (!_systems.count(name))
{
std::cerr << "ERROR: no system named "
<< name << std::endl;
error();
}
delete _systems[name];
_systems.erase (name);
}
unsigned int EquationSystems::n_vars () const
{
if (_systems.empty())
return 0;
unsigned int tot=0;
for (std::map<std::string, GeneralSystem*>::const_iterator
pos = _systems.begin(); pos != _systems.end(); ++pos)
tot += pos->second->n_vars();
return tot;
}
unsigned int EquationSystems::n_dofs () const
{
if (_systems.empty())
return 0;
unsigned int tot=0;
for (std::map<std::string, GeneralSystem*>::const_iterator
pos = _systems.begin(); pos != _systems.end(); ++pos)
tot += pos->second->n_dofs();
return tot;
}
GeneralSystem & EquationSystems::operator () (const std::string& name)
{
std::map<std::string, GeneralSystem*>::iterator
pos = _systems.find(name);
if (pos == _systems.end())
{
std::cerr << "ERROR: system "
<< name
<< " not found!"
<< std::endl;
error();
}
return *pos->second;
}
const GeneralSystem & EquationSystems::operator () (const std::string& name) const
{
std::map<std::string, GeneralSystem*>::const_iterator
pos = _systems.find(name);
if (pos == _systems.end())
{
std::cerr << "ERROR: system "
<< name
<< " not found!"
<< std::endl;
error();
}
return *pos->second;
}
const std::string & EquationSystems::name (const unsigned int num) const
{
assert (num < n_systems());
std::map<std::string, GeneralSystem*>::const_iterator
pos = _systems.begin();
// New code
#if (__GNUC__ == 2)
std::advance (pos, static_cast<int>(num));
#else
std::advance (pos, num);
#endif
// Old code
// for (unsigned int i=0; i<num; i++)
// ++pos;
return pos->first;
}
GeneralSystem & EquationSystems::operator () (const unsigned int num)
{
assert (num < n_systems());
std::map<std::string, GeneralSystem*>::iterator
pos = _systems.begin();
// New code
#if (__GNUC__ == 2)
std::advance (pos, static_cast<int>(num));
#else
std::advance (pos, num);
#endif
// Old code
// for (unsigned int i=0; i<num; i++)
// ++pos;
return *pos->second;
}
const GeneralSystem & EquationSystems::operator () (const unsigned int num) const
{
assert (num < n_systems());
std::map<std::string, GeneralSystem*>::const_iterator
pos = _systems.begin();
// New code
#if (__GNUC__ == 2)
std::advance (pos, static_cast<int>(num));
#else
std::advance (pos, num);
#endif
// Old code
// for (unsigned int i=0; i<num; i++)
// ++pos;
return *pos->second;
}
bool EquationSystems::flag (const std::string& fl) const
{
return (_flags.count(fl) != 0);
}
void EquationSystems::set_flag (const std::string& fl)
{
#ifdef DEBUG
/*
// Make sure the parameter isn't already set
if (flags.count(fl))
std::cerr << "WARNING: flag "
<< "\""
<< fl
<< "\""
<< " is already set!"
<< std::endl;
*/
#endif
_flags.insert (fl);
}
void EquationSystems::unset_flag (const std::string& fl)
{
// Look for the flag in the database
if (!_flags.count(fl))
{
std::cerr << "ERROR: flag " << fl
<< " was not set!"
<< std::endl;
error();
}
// Remove the flag
_flags.erase (fl);
}
Real EquationSystems::parameter (const std::string& id) const
{
// Look for the id in the database
std::map<std::string, Real>::const_iterator
pos = _parameters.find(id);
if (pos == _parameters.end())
{
std::cerr << "ERROR: parameter " << id
<< " was not set!"
<< std::endl;
error();
}
// Return the parameter value if found
return pos->second;
}
Real & EquationSystems::set_parameter (const std::string& id)
{
#ifdef DEBUG
/*
// Make sure the parameter isn't already set
if (parameters.count(id))
std::cerr << "WARNING: parameter "
<< "\""
<< id
<< "\""
<< " is already set!"
<< std::endl;
*/
#endif
// Insert the parameter/value pair into the database
return _parameters[id];
}
void EquationSystems::unset_parameter (const std::string& id)
{
// Look for the id in the database
std::map<std::string, Real>::iterator
pos = _parameters.find(id);
// Make sure the parameter was found
if (pos == _parameters.end())
{
std::cerr << "ERROR: parameter " << id
<< " was not set!"
<< std::endl;
error();
}
// Erase the entry
_parameters.erase(pos);
}
void EquationSystems::build_variable_names (std::vector<std::string>& var_names)
{
assert (n_systems());
var_names.resize (n_vars());
unsigned int var_num=0;
for (unsigned int sys=0; sys<n_systems(); sys++)
for (unsigned int vn=0; vn < (*this)(sys).n_vars(); vn++)
var_names[var_num++] = (*this)(sys).variable_name(vn);
}
void EquationSystems::build_solution_vector (std::vector<Complex>& soln)
{
assert (n_systems());
const unsigned int dim = _mesh.mesh_dimension();
const unsigned int nn = _mesh.n_nodes();
const unsigned int nv = n_vars();
if (_mesh.processor_id() == 0)
soln.resize(nn*nv);
std::vector<Complex> sys_soln;
unsigned int var_num=0;
for (unsigned int sys=0; sys<n_systems(); sys++)
{
const GeneralSystem& system = (*this)(sys);
const unsigned int nv_sys = system.n_vars();
system.update_global_solution (sys_soln);
if (_mesh.processor_id() == 0)
{
std::vector<Complex> elem_soln; // The finite element solution
std::vector<Complex> nodal_soln; // The finite elemnt solution interpolated to the nodes
std::vector<unsigned int> dof_indices; // The DOF indices for the finite element
for (unsigned int var=0; var<nv_sys; var++)
{
const FEType& fe_type = system.variable_type(var);
for (unsigned int e=0; e<_mesh.n_elem(); e++)
if (_mesh.elem(e)->active())
{
const Elem* elem = _mesh.elem(e);
system.get_dof_map().dof_indices (elem, dof_indices, var);
elem_soln.resize(dof_indices.size());
for (unsigned int i=0; i<dof_indices.size(); i++)
elem_soln[i] = sys_soln[dof_indices[i]];
FEInterface::nodal_soln (dim, fe_type, elem,
elem_soln, nodal_soln);
assert (nodal_soln.size() == elem->n_nodes());
for (unsigned int n=0; n<elem->n_nodes(); n++)
soln[nv*(elem->node(n)) + (var + var_num)] =
nodal_soln[n];
}
}
}
var_num += nv_sys;
}
}
std::string EquationSystems::get_info () const
{
std::ostringstream out;
out << " EquationSystems:" << std::endl
<< " n_systems()=" << n_systems() << std::endl;
for (std::map<std::string, GeneralSystem*>::const_iterator it=_systems.begin();
it != _systems.end(); ++it)
{
const std::string& sys_name = it->first;
const GeneralSystem& system = *it->second;
out << " System \"" << sys_name << "\"" << std::endl
<< " Variables=";
for (unsigned int vn=0; vn<system.n_vars(); vn++)
out << "\"" << system.variable_name(vn) << "\" ";
out << std::endl;
#ifndef ENABLE_INFINITE_ELEMENTS
out << " Finite Element Types=";
for (unsigned int vn=0; vn<system.n_vars(); vn++)
{
out << "\"" << system.get_dof_map().component_type(vn).family << "\" ";
}
#else
out << " Finite Element Types=";
for (unsigned int vn=0; vn<system.n_vars(); vn++)
{
out << "\"" << system.get_dof_map().variable_type(vn).family << "\", ";
out << "\"" << system.get_dof_map().variable_type(vn).radial_family << "\" ";
}
out << std::endl << " Infinite Element Mapping=";
for (unsigned int vn=0; vn<system.n_vars(); vn++)
{
out << "\"" << system.get_dof_map().variable_type(vn).inf_map << "\" ";
}
#endif
out << std::endl;
out << " Approximation Orders=";
for (unsigned int vn=0; vn<system.n_vars(); vn++)
{
#ifndef ENABLE_INFINITE_ELEMENTS
out << "\"" << system.get_dof_map().variable_type(vn).order << "\" ";
#else
out << "\"" << system.get_dof_map().variable_type(vn).order << "\", ";
out << "\"" << system.get_dof_map().variable_type(vn).radial_order << "\" ";
#endif
}
out << std::endl;
out << " n_dofs()=" << system.n_dofs() << std::endl;
out << " n_local_dofs()=" << system.n_local_dofs() << std::endl;
#ifdef ENABLE_AMR
out << " n_constrained_dofs()=" << system.n_constrained_dofs() << std::endl;
#endif
}
if (!_flags.empty())
{
out << " Flags:" << std::endl;
for (std::set<std::string>::const_iterator flag = _flags.begin();
flag != _flags.end(); ++flag)
out << " "
<< "\""
<< *flag
<< "\""
<< std::endl;
}
if (!_parameters.empty())
{
out << " Parameters:" << std::endl;
for (std::map<std::string, Real>::const_iterator
param = _parameters.begin(); param != _parameters.end();
++param)
out << " "
<< "\""
<< param->first
<< "\""
<< "="
<< param->second
<< std::endl;
}
return out.str();
}
<commit_msg>one final DofMap::component changed to variable<commit_after>// $Id: equation_systems.C,v 1.18 2003-02-17 05:33:09 jwpeterson Exp $
// The Next Great Finite Element Library.
// Copyright (C) 2002 Benjamin S. Kirk, John W. Peterson
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// System includes
#include <sstream>
// Local Includes
//#include "enum_solver_package.h"
#include "libmesh.h"
#include "fe_interface.h"
//#include "petsc_vector.h"
//#include "petsc_matrix.h"
//#include "petsc_interface.h"
#include "linear_solver_interface.h"
#include "equation_systems.h"
#include "general_system.h"
// Forward Declarations
// ------------------------------------------------------------
// EquationSystem class implementation
EquationSystems::EquationSystems (Mesh& m,
const SolverPackage sp) :
_mesh(m),
_solver_package(sp)
{
// Default parameters
set_parameter("linear solver tolerance") = 1.e-12;
set_parameter("linear solver maximum iterations") = 5000;
}
EquationSystems::~EquationSystems ()
{
clear();
assert (!libMesh::closed());
}
void EquationSystems::clear ()
{
for (std::map<std::string, GeneralSystem*>::iterator
pos = _systems.begin(); pos != _systems.end();
++pos)
delete pos->second;
_systems.clear ();
_flags.clear ();
_parameters.clear ();
}
void EquationSystems::init ()
{
const unsigned int n_sys = n_systems();
assert (n_sys != 0);
// /**
// * Tell all the \p DofObject entities how many systems
// * there are.
// */
// {
// // All the nodes
// node_iterator node_it (_mesh.nodes_begin());
// const node_iterator node_end (_mesh.nodes_end());
// for ( ; node_it != node_end; ++node_it)
// (*node_it)->set_n_systems(n_sys);
// // All the elements
// elem_iterator elem_it (_mesh.elements_begin());
// const elem_iterator elem_end(_mesh.elements_end());
// for ( ; elem_it != elem_end; ++elem_it)
// (*elem_it)->set_n_systems(n_sys);
// }
for (std::map<std::string, GeneralSystem*>::iterator
sys = _systems.begin(); sys != _systems.end();
++sys)
{
/**
* Initialize the system.
*/
sys->second->init();
}
}
void EquationSystems::add_system (const std::string& name)
{
if (!_systems.count(name))
{
const unsigned int num = n_systems();
_systems.insert (std::pair<std::string,
GeneralSystem*>(name,
new GeneralSystem(*this,
name,
num,
_solver_package)
)
);
}
else
{
std::cerr << "ERROR: There was already a system"
<< " named " << name
<< std::endl;
error();
}
/**
* Tell all the \p DofObject entities to add a system.
*/
{
// All the nodes
node_iterator node_it (_mesh.nodes_begin());
const node_iterator node_end (_mesh.nodes_end());
for ( ; node_it != node_end; ++node_it)
(*node_it)->add_system();
// All the elements
elem_iterator elem_it (_mesh.elements_begin());
const elem_iterator elem_end(_mesh.elements_end());
for ( ; elem_it != elem_end; ++elem_it)
(*elem_it)->add_system();
}
}
void EquationSystems::delete_system (const std::string& name)
{
if (!_systems.count(name))
{
std::cerr << "ERROR: no system named "
<< name << std::endl;
error();
}
delete _systems[name];
_systems.erase (name);
}
unsigned int EquationSystems::n_vars () const
{
if (_systems.empty())
return 0;
unsigned int tot=0;
for (std::map<std::string, GeneralSystem*>::const_iterator
pos = _systems.begin(); pos != _systems.end(); ++pos)
tot += pos->second->n_vars();
return tot;
}
unsigned int EquationSystems::n_dofs () const
{
if (_systems.empty())
return 0;
unsigned int tot=0;
for (std::map<std::string, GeneralSystem*>::const_iterator
pos = _systems.begin(); pos != _systems.end(); ++pos)
tot += pos->second->n_dofs();
return tot;
}
GeneralSystem & EquationSystems::operator () (const std::string& name)
{
std::map<std::string, GeneralSystem*>::iterator
pos = _systems.find(name);
if (pos == _systems.end())
{
std::cerr << "ERROR: system "
<< name
<< " not found!"
<< std::endl;
error();
}
return *pos->second;
}
const GeneralSystem & EquationSystems::operator () (const std::string& name) const
{
std::map<std::string, GeneralSystem*>::const_iterator
pos = _systems.find(name);
if (pos == _systems.end())
{
std::cerr << "ERROR: system "
<< name
<< " not found!"
<< std::endl;
error();
}
return *pos->second;
}
const std::string & EquationSystems::name (const unsigned int num) const
{
assert (num < n_systems());
std::map<std::string, GeneralSystem*>::const_iterator
pos = _systems.begin();
// New code
#if (__GNUC__ == 2)
std::advance (pos, static_cast<int>(num));
#else
std::advance (pos, num);
#endif
// Old code
// for (unsigned int i=0; i<num; i++)
// ++pos;
return pos->first;
}
GeneralSystem & EquationSystems::operator () (const unsigned int num)
{
assert (num < n_systems());
std::map<std::string, GeneralSystem*>::iterator
pos = _systems.begin();
// New code
#if (__GNUC__ == 2)
std::advance (pos, static_cast<int>(num));
#else
std::advance (pos, num);
#endif
// Old code
// for (unsigned int i=0; i<num; i++)
// ++pos;
return *pos->second;
}
const GeneralSystem & EquationSystems::operator () (const unsigned int num) const
{
assert (num < n_systems());
std::map<std::string, GeneralSystem*>::const_iterator
pos = _systems.begin();
// New code
#if (__GNUC__ == 2)
std::advance (pos, static_cast<int>(num));
#else
std::advance (pos, num);
#endif
// Old code
// for (unsigned int i=0; i<num; i++)
// ++pos;
return *pos->second;
}
bool EquationSystems::flag (const std::string& fl) const
{
return (_flags.count(fl) != 0);
}
void EquationSystems::set_flag (const std::string& fl)
{
#ifdef DEBUG
/*
// Make sure the parameter isn't already set
if (flags.count(fl))
std::cerr << "WARNING: flag "
<< "\""
<< fl
<< "\""
<< " is already set!"
<< std::endl;
*/
#endif
_flags.insert (fl);
}
void EquationSystems::unset_flag (const std::string& fl)
{
// Look for the flag in the database
if (!_flags.count(fl))
{
std::cerr << "ERROR: flag " << fl
<< " was not set!"
<< std::endl;
error();
}
// Remove the flag
_flags.erase (fl);
}
Real EquationSystems::parameter (const std::string& id) const
{
// Look for the id in the database
std::map<std::string, Real>::const_iterator
pos = _parameters.find(id);
if (pos == _parameters.end())
{
std::cerr << "ERROR: parameter " << id
<< " was not set!"
<< std::endl;
error();
}
// Return the parameter value if found
return pos->second;
}
Real & EquationSystems::set_parameter (const std::string& id)
{
#ifdef DEBUG
/*
// Make sure the parameter isn't already set
if (parameters.count(id))
std::cerr << "WARNING: parameter "
<< "\""
<< id
<< "\""
<< " is already set!"
<< std::endl;
*/
#endif
// Insert the parameter/value pair into the database
return _parameters[id];
}
void EquationSystems::unset_parameter (const std::string& id)
{
// Look for the id in the database
std::map<std::string, Real>::iterator
pos = _parameters.find(id);
// Make sure the parameter was found
if (pos == _parameters.end())
{
std::cerr << "ERROR: parameter " << id
<< " was not set!"
<< std::endl;
error();
}
// Erase the entry
_parameters.erase(pos);
}
void EquationSystems::build_variable_names (std::vector<std::string>& var_names)
{
assert (n_systems());
var_names.resize (n_vars());
unsigned int var_num=0;
for (unsigned int sys=0; sys<n_systems(); sys++)
for (unsigned int vn=0; vn < (*this)(sys).n_vars(); vn++)
var_names[var_num++] = (*this)(sys).variable_name(vn);
}
void EquationSystems::build_solution_vector (std::vector<Complex>& soln)
{
assert (n_systems());
const unsigned int dim = _mesh.mesh_dimension();
const unsigned int nn = _mesh.n_nodes();
const unsigned int nv = n_vars();
if (_mesh.processor_id() == 0)
soln.resize(nn*nv);
std::vector<Complex> sys_soln;
unsigned int var_num=0;
for (unsigned int sys=0; sys<n_systems(); sys++)
{
const GeneralSystem& system = (*this)(sys);
const unsigned int nv_sys = system.n_vars();
system.update_global_solution (sys_soln);
if (_mesh.processor_id() == 0)
{
std::vector<Complex> elem_soln; // The finite element solution
std::vector<Complex> nodal_soln; // The finite elemnt solution interpolated to the nodes
std::vector<unsigned int> dof_indices; // The DOF indices for the finite element
for (unsigned int var=0; var<nv_sys; var++)
{
const FEType& fe_type = system.variable_type(var);
for (unsigned int e=0; e<_mesh.n_elem(); e++)
if (_mesh.elem(e)->active())
{
const Elem* elem = _mesh.elem(e);
system.get_dof_map().dof_indices (elem, dof_indices, var);
elem_soln.resize(dof_indices.size());
for (unsigned int i=0; i<dof_indices.size(); i++)
elem_soln[i] = sys_soln[dof_indices[i]];
FEInterface::nodal_soln (dim, fe_type, elem,
elem_soln, nodal_soln);
assert (nodal_soln.size() == elem->n_nodes());
for (unsigned int n=0; n<elem->n_nodes(); n++)
soln[nv*(elem->node(n)) + (var + var_num)] =
nodal_soln[n];
}
}
}
var_num += nv_sys;
}
}
std::string EquationSystems::get_info () const
{
std::ostringstream out;
out << " EquationSystems:" << std::endl
<< " n_systems()=" << n_systems() << std::endl;
for (std::map<std::string, GeneralSystem*>::const_iterator it=_systems.begin();
it != _systems.end(); ++it)
{
const std::string& sys_name = it->first;
const GeneralSystem& system = *it->second;
out << " System \"" << sys_name << "\"" << std::endl
<< " Variables=";
for (unsigned int vn=0; vn<system.n_vars(); vn++)
out << "\"" << system.variable_name(vn) << "\" ";
out << std::endl;
#ifndef ENABLE_INFINITE_ELEMENTS
out << " Finite Element Types=";
for (unsigned int vn=0; vn<system.n_vars(); vn++)
{
out << "\"" << system.get_dof_map().variable_type(vn).family << "\" ";
}
#else
out << " Finite Element Types=";
for (unsigned int vn=0; vn<system.n_vars(); vn++)
{
out << "\"" << system.get_dof_map().variable_type(vn).family << "\", ";
out << "\"" << system.get_dof_map().variable_type(vn).radial_family << "\" ";
}
out << std::endl << " Infinite Element Mapping=";
for (unsigned int vn=0; vn<system.n_vars(); vn++)
{
out << "\"" << system.get_dof_map().variable_type(vn).inf_map << "\" ";
}
#endif
out << std::endl;
out << " Approximation Orders=";
for (unsigned int vn=0; vn<system.n_vars(); vn++)
{
#ifndef ENABLE_INFINITE_ELEMENTS
out << "\"" << system.get_dof_map().variable_type(vn).order << "\" ";
#else
out << "\"" << system.get_dof_map().variable_type(vn).order << "\", ";
out << "\"" << system.get_dof_map().variable_type(vn).radial_order << "\" ";
#endif
}
out << std::endl;
out << " n_dofs()=" << system.n_dofs() << std::endl;
out << " n_local_dofs()=" << system.n_local_dofs() << std::endl;
#ifdef ENABLE_AMR
out << " n_constrained_dofs()=" << system.n_constrained_dofs() << std::endl;
#endif
}
if (!_flags.empty())
{
out << " Flags:" << std::endl;
for (std::set<std::string>::const_iterator flag = _flags.begin();
flag != _flags.end(); ++flag)
out << " "
<< "\""
<< *flag
<< "\""
<< std::endl;
}
if (!_parameters.empty())
{
out << " Parameters:" << std::endl;
for (std::map<std::string, Real>::const_iterator
param = _parameters.begin(); param != _parameters.end();
++param)
out << " "
<< "\""
<< param->first
<< "\""
<< "="
<< param->second
<< std::endl;
}
return out.str();
}
<|endoftext|> |
<commit_before>/*
* reflection.cc
*
* Copyright (C) 2013 Diamond Light Source
*
* Author: James Parkhurst
*
* This code is distributed under the BSD license, a copy of which is
* included in the root directory of this package.
*/
#include <boost/python.hpp>
#include <boost/python/def.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <sstream>
#include <string>
#include <scitbx/array_family/flex_types.h>
#include <scitbx/array_family/boost_python/flex_wrapper.h>
#include <scitbx/array_family/ref_reductions.h>
#include <dials/model/data/reflection.h>
#include <dials/error.h>
#include <dials/model/data/boost_python/pickle.h>
#include <dials/model/data/observation.h>
#include <dials/model/data/shoebox.h>
#include <scitbx/array_family/boost_python/flex_pickle_double_buffered.h>
namespace dials { namespace model { namespace boost_python {
using namespace boost::python;
using scitbx::af::flex_double;
using scitbx::af::flex_int;
using scitbx::af::flex;
typedef cctbx::miller::index<> miller_index;
std::string reflection_to_string(const Reflection &reflection) {
std::stringstream ss;
ss << reflection;
return ss.str();
}
af::flex<Reflection>::type* init_from_observation_and_shoebox(
const af::const_ref<Observation> &o,
const af::const_ref< Shoebox<Reflection::float_type> > &s) {
DIALS_ASSERT(o.size() == s.size());
af::shared<Reflection> result(o.size());
for (std::size_t i = 0; i < result.size(); ++i) {
// Check panel numbers
DIALS_ASSERT(o[i].panel == s[i].panel);
result[i].panel_number_ = o[i].panel;
// Copy observation info
result[i].centroid_position_ = o[i].centroid.px.position;
result[i].centroid_variance_ = o[i].centroid.px.std_err_sq;
result[i].centroid_sq_width_ = o[i].centroid.px.variance;
result[i].intensity_ = o[i].intensity.observed.value;
result[i].intensity_variance_ = o[i].intensity.observed.variance;
result[i].corrected_intensity_ = o[i].intensity.corrected.value;
result[i].corrected_intensity_variance_ = o[i].intensity.corrected.variance;
// Copy shoebox info
result[i].bounding_box_ = s[i].bbox;
result[i].shoebox_ = s[i].data;
result[i].shoebox_mask_ = s[i].mask;
result[i].shoebox_background_ = s[i].background;
}
return new af::flex<Reflection>::type(
result, af::flex_grid<>(result.size()));
}
void set_shoebox(Reflection &obj,
flex<Reflection::float_type>::type &data) {
DIALS_ASSERT(data.accessor().all().size() == 3);
obj.set_shoebox(af::versa<Reflection::float_type, af::c_grid<3> >(
data.handle(), af::c_grid<3>(data.accessor())));
}
// static
// flex_double get_shoebox(Reflection &obj) {
// return flex_double(obj.get_shoebox().handle(),
// obj.get_shoebox().accessor().as_flex_grid());
// }
void set_shoebox_mask(Reflection &obj, flex_int &data) {
DIALS_ASSERT(data.accessor().all().size() == 3);
obj.set_shoebox_mask(af::versa<int, af::c_grid<3> >(
data.handle(), af::c_grid<3>(data.accessor())));
}
// static
// flex_int get_shoebox_mask(Reflection &obj) {
// return flex_int(obj.get_shoebox_mask().handle(),
// obj.get_shoebox_mask().accessor().as_flex_grid());
// }
void set_shoebox_background(Reflection &obj,
flex<Reflection::float_type>::type &data) {
DIALS_ASSERT(data.accessor().all().size() == 3);
obj.set_shoebox_background(af::versa<Reflection::float_type, af::c_grid<3> >(
data.handle(), af::c_grid<3>(data.accessor())));
}
// static
// flex_double get_shoebox_background(Reflection &obj) {
// return flex_double(obj.get_shoebox_background().handle(),
// obj.get_shoebox_background().accessor().as_flex_grid());
// }
void set_transformed_shoebox(Reflection &obj,
flex<Reflection::float_type>::type &data) {
DIALS_ASSERT(data.accessor().all().size() == 3);
obj.set_transformed_shoebox(af::versa<Reflection::float_type, af::c_grid<3> >(
data.handle(), af::c_grid<3>(data.accessor())));
}
// static
// flex_double get_transformed_shoebox(Reflection &obj) {
// return flex_double(obj.get_transformed_shoebox().handle(),
// obj.get_transformed_shoebox().accessor().as_flex_grid());
// }
void set_transformed_shoebox_background(Reflection &obj,
flex<Reflection::float_type>::type &data) {
DIALS_ASSERT(data.accessor().all().size() == 3);
obj.set_transformed_shoebox_background(af::versa<Reflection::float_type, af::c_grid<3> >(
data.handle(), af::c_grid<3>(data.accessor())));
}
static
af::shared< cctbx::miller::index<> > get_miller_index(const af::const_ref<Reflection> &r) {
af::shared< cctbx::miller::index<> > result(r.size());
for (std::size_t i = 0; i < result.size(); ++i) {
result[i] = r[i].get_miller_index();
}
return result;
}
static
af::shared< double > get_rotation_angle(const af::const_ref<Reflection> &r) {
af::shared< double > result(r.size());
for (std::size_t i = 0; i < result.size(); ++i) {
result[i] = r[i].get_rotation_angle();
}
return result;
}
static
af::shared< vec3<double> > get_beam_vector(const af::const_ref<Reflection> &r) {
af::shared< vec3<double> > result(r.size());
for (std::size_t i = 0; i < result.size(); ++i) {
result[i] = r[i].get_beam_vector();
}
return result;
}
static
void set_beam_vector(
af::ref<Reflection> const& r,
af::const_ref<vec3 <double> > const& beam_vector) {
af::shared< vec3<double> > result(r.size());
for (std::size_t i = 0; i < result.size(); ++i) {
r[i].set_beam_vector(beam_vector[i]);
}
}
static
af::shared< vec3<double> > get_centroid_position(const af::const_ref<Reflection> &r) {
af::shared< vec3<double> > result(r.size());
for (std::size_t i = 0; i < result.size(); ++i) {
result[i] = r[i].get_centroid_position();
}
return result;
}
static
af::shared< vec2<double> > get_image_coord_px(const af::const_ref<Reflection> &r) {
af::shared< vec2<double> > result(r.size());
for (std::size_t i = 0; i < result.size(); ++i) {
result[i] = r[i].get_image_coord_px();
}
return result;
}
static
af::shared< vec2<double> > get_image_coord_mm(const af::const_ref<Reflection> &r) {
af::shared< vec2<double> > result(r.size());
for (std::size_t i = 0; i < result.size(); ++i) {
result[i] = r[i].get_image_coord_mm();
}
return result;
}
static
af::shared< double > get_frame_number(const af::const_ref<Reflection> &r) {
af::shared< double > result(r.size());
for (std::size_t i = 0; i < result.size(); ++i) {
result[i] = r[i].get_frame_number();
}
return result;
}
static
af::shared< bool > get_is_valid(const af::const_ref<Reflection> &r) {
af::shared< bool > result(r.size());
for (std::size_t i = 0; i < result.size(); ++i) {
result[i] = r[i].is_valid();
}
return result;
}
// static
// flex_double get_transformed_shoebox_background(Reflection &obj) {
// return flex_double(obj.get_transformed_shoebox_background().handle(),
// obj.get_transformed_shoebox_background().accessor().as_flex_grid());
// }
void reflection_wrapper()
{
class_<ReflectionBase>("ReflectionBase")
.def(init <miller_index_type> ((
arg("miller_index"))))
.add_property("miller_index",
&ReflectionBase::get_miller_index,
&ReflectionBase::set_miller_index)
.add_property("entering",
&ReflectionBase::get_entering,
&ReflectionBase::set_entering)
.add_property("status",
&ReflectionBase::get_status,
&ReflectionBase::set_status)
.def("is_valid", &ReflectionBase::is_valid)
.def("is_active", &ReflectionBase::is_active)
.def("is_strong", &ReflectionBase::is_strong)
.def("set_valid", &ReflectionBase::set_valid)
.def("set_active", &ReflectionBase::set_active)
.def("set_strong", &ReflectionBase::set_strong)
.def("is_zero", &ReflectionBase::is_zero);
class_<Reflection, bases<ReflectionBase> > ("Reflection")
.def(init <const Reflection &>())
.def(init <miller_index_type> ((
arg("miller_index"))))
.add_property("rotation_angle",
&Reflection::get_rotation_angle,
&Reflection::set_rotation_angle)
.add_property("beam_vector",
&Reflection::get_beam_vector,
&Reflection::set_beam_vector)
.add_property("image_coord_mm",
&Reflection::get_image_coord_mm,
&Reflection::set_image_coord_mm)
.add_property("image_coord_px",
&Reflection::get_image_coord_px,
&Reflection::set_image_coord_px)
.add_property("frame_number",
&Reflection::get_frame_number,
&Reflection::set_frame_number)
.add_property("panel_number",
&Reflection::get_panel_number,
&Reflection::set_panel_number)
.add_property("bounding_box",
&Reflection::get_bounding_box,
&Reflection::set_bounding_box)
// .def("shoebox", &get_shoebox)
// .def("shoebox", &set_shoebox)
// .def("shoebox_mask", &get_shoebox_mask)
// .def("shoebox_mask", &set_shoebox_mask)
// .def("shoebox_background", &get_shoebox_background)
// .def("shoebox_background", &set_shoebox_background)
// .def("transformed_shoebox", &get_transformed_shoebox)
// .def("transformed_shoebox", &set_transformed_shoebox)
// .def("transformed_shoebox_background", &get_transformed_shoebox_background)
// .def("transformed_shoebox_background", &set_transformed_shoebox_background)
.add_property("shoebox",
&Reflection::get_shoebox,
&set_shoebox)
.add_property("shoebox_mask",
&Reflection::get_shoebox_mask,
&set_shoebox_mask)
.add_property("shoebox_background",
&Reflection::get_shoebox_background,
&set_shoebox_background)
.add_property("transformed_shoebox",
&Reflection::get_transformed_shoebox,
&set_transformed_shoebox)
.add_property("transformed_shoebox_background",
&Reflection::get_transformed_shoebox_background,
&set_transformed_shoebox_background)
.add_property("centroid_position",
&Reflection::get_centroid_position,
&Reflection::set_centroid_position)
.add_property("centroid_variance",
&Reflection::get_centroid_variance,
&Reflection::set_centroid_variance)
.add_property("centroid_sq_width",
&Reflection::get_centroid_sq_width,
&Reflection::set_centroid_sq_width)
.add_property("intensity",
&Reflection::get_intensity,
&Reflection::set_intensity)
.add_property("intensity_variance",
&Reflection::get_intensity_variance,
&Reflection::set_intensity_variance)
.add_property("corrected_intensity",
&Reflection::get_corrected_intensity,
&Reflection::set_corrected_intensity)
.add_property("corrected_intensity_variance",
&Reflection::get_corrected_intensity_variance,
&Reflection::set_corrected_intensity_variance)
.add_property("crystal",
&Reflection::get_crystal,
&Reflection::set_crystal)
.def("__str__", &reflection_to_string)
.def_pickle(reflection::ReflectionPickleSuite());
scitbx::af::boost_python::flex_wrapper
<Reflection, return_internal_reference<> >::plain("ReflectionList")
.def("__init__", make_constructor(
&init_from_observation_and_shoebox))
.def_pickle(scitbx::af::boost_python::flex_pickle_double_buffered<
Reflection,
reflection::to_string,
reflection::from_string>())
.def("miller_index", &get_miller_index)
.def("rotation_angle", &get_rotation_angle)
.def("centroid_position", &get_centroid_position)
.def("beam_vector", &get_beam_vector)
.def("set_beam_vector", &set_beam_vector)
.def("image_coord_px", &get_image_coord_px)
.def("image_coord_mm", &get_image_coord_mm)
.def("frame_number", &get_frame_number)
.def("is_valid", &get_is_valid);
}
void export_reflection() {
reflection_wrapper();
}
}}} // namespace dials::model::boost_python
<commit_msg>add DIALS_ASSERT and remove creation of unused array<commit_after>/*
* reflection.cc
*
* Copyright (C) 2013 Diamond Light Source
*
* Author: James Parkhurst
*
* This code is distributed under the BSD license, a copy of which is
* included in the root directory of this package.
*/
#include <boost/python.hpp>
#include <boost/python/def.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <sstream>
#include <string>
#include <scitbx/array_family/flex_types.h>
#include <scitbx/array_family/boost_python/flex_wrapper.h>
#include <scitbx/array_family/ref_reductions.h>
#include <dials/model/data/reflection.h>
#include <dials/error.h>
#include <dials/model/data/boost_python/pickle.h>
#include <dials/model/data/observation.h>
#include <dials/model/data/shoebox.h>
#include <scitbx/array_family/boost_python/flex_pickle_double_buffered.h>
namespace dials { namespace model { namespace boost_python {
using namespace boost::python;
using scitbx::af::flex_double;
using scitbx::af::flex_int;
using scitbx::af::flex;
typedef cctbx::miller::index<> miller_index;
std::string reflection_to_string(const Reflection &reflection) {
std::stringstream ss;
ss << reflection;
return ss.str();
}
af::flex<Reflection>::type* init_from_observation_and_shoebox(
const af::const_ref<Observation> &o,
const af::const_ref< Shoebox<Reflection::float_type> > &s) {
DIALS_ASSERT(o.size() == s.size());
af::shared<Reflection> result(o.size());
for (std::size_t i = 0; i < result.size(); ++i) {
// Check panel numbers
DIALS_ASSERT(o[i].panel == s[i].panel);
result[i].panel_number_ = o[i].panel;
// Copy observation info
result[i].centroid_position_ = o[i].centroid.px.position;
result[i].centroid_variance_ = o[i].centroid.px.std_err_sq;
result[i].centroid_sq_width_ = o[i].centroid.px.variance;
result[i].intensity_ = o[i].intensity.observed.value;
result[i].intensity_variance_ = o[i].intensity.observed.variance;
result[i].corrected_intensity_ = o[i].intensity.corrected.value;
result[i].corrected_intensity_variance_ = o[i].intensity.corrected.variance;
// Copy shoebox info
result[i].bounding_box_ = s[i].bbox;
result[i].shoebox_ = s[i].data;
result[i].shoebox_mask_ = s[i].mask;
result[i].shoebox_background_ = s[i].background;
}
return new af::flex<Reflection>::type(
result, af::flex_grid<>(result.size()));
}
void set_shoebox(Reflection &obj,
flex<Reflection::float_type>::type &data) {
DIALS_ASSERT(data.accessor().all().size() == 3);
obj.set_shoebox(af::versa<Reflection::float_type, af::c_grid<3> >(
data.handle(), af::c_grid<3>(data.accessor())));
}
// static
// flex_double get_shoebox(Reflection &obj) {
// return flex_double(obj.get_shoebox().handle(),
// obj.get_shoebox().accessor().as_flex_grid());
// }
void set_shoebox_mask(Reflection &obj, flex_int &data) {
DIALS_ASSERT(data.accessor().all().size() == 3);
obj.set_shoebox_mask(af::versa<int, af::c_grid<3> >(
data.handle(), af::c_grid<3>(data.accessor())));
}
// static
// flex_int get_shoebox_mask(Reflection &obj) {
// return flex_int(obj.get_shoebox_mask().handle(),
// obj.get_shoebox_mask().accessor().as_flex_grid());
// }
void set_shoebox_background(Reflection &obj,
flex<Reflection::float_type>::type &data) {
DIALS_ASSERT(data.accessor().all().size() == 3);
obj.set_shoebox_background(af::versa<Reflection::float_type, af::c_grid<3> >(
data.handle(), af::c_grid<3>(data.accessor())));
}
// static
// flex_double get_shoebox_background(Reflection &obj) {
// return flex_double(obj.get_shoebox_background().handle(),
// obj.get_shoebox_background().accessor().as_flex_grid());
// }
void set_transformed_shoebox(Reflection &obj,
flex<Reflection::float_type>::type &data) {
DIALS_ASSERT(data.accessor().all().size() == 3);
obj.set_transformed_shoebox(af::versa<Reflection::float_type, af::c_grid<3> >(
data.handle(), af::c_grid<3>(data.accessor())));
}
// static
// flex_double get_transformed_shoebox(Reflection &obj) {
// return flex_double(obj.get_transformed_shoebox().handle(),
// obj.get_transformed_shoebox().accessor().as_flex_grid());
// }
void set_transformed_shoebox_background(Reflection &obj,
flex<Reflection::float_type>::type &data) {
DIALS_ASSERT(data.accessor().all().size() == 3);
obj.set_transformed_shoebox_background(af::versa<Reflection::float_type, af::c_grid<3> >(
data.handle(), af::c_grid<3>(data.accessor())));
}
static
af::shared< cctbx::miller::index<> > get_miller_index(const af::const_ref<Reflection> &r) {
af::shared< cctbx::miller::index<> > result(r.size());
for (std::size_t i = 0; i < result.size(); ++i) {
result[i] = r[i].get_miller_index();
}
return result;
}
static
af::shared< double > get_rotation_angle(const af::const_ref<Reflection> &r) {
af::shared< double > result(r.size());
for (std::size_t i = 0; i < result.size(); ++i) {
result[i] = r[i].get_rotation_angle();
}
return result;
}
static
af::shared< vec3<double> > get_beam_vector(const af::const_ref<Reflection> &r) {
af::shared< vec3<double> > result(r.size());
for (std::size_t i = 0; i < result.size(); ++i) {
result[i] = r[i].get_beam_vector();
}
return result;
}
static
void set_beam_vector(
af::ref<Reflection> const& r,
af::const_ref<vec3 <double> > const& beam_vector) {
DIALS_ASSERT(r.size() == beam_vector.size());
for (std::size_t i = 0; i < r.size(); ++i) {
r[i].set_beam_vector(beam_vector[i]);
}
}
static
af::shared< vec3<double> > get_centroid_position(const af::const_ref<Reflection> &r) {
af::shared< vec3<double> > result(r.size());
for (std::size_t i = 0; i < result.size(); ++i) {
result[i] = r[i].get_centroid_position();
}
return result;
}
static
af::shared< vec2<double> > get_image_coord_px(const af::const_ref<Reflection> &r) {
af::shared< vec2<double> > result(r.size());
for (std::size_t i = 0; i < result.size(); ++i) {
result[i] = r[i].get_image_coord_px();
}
return result;
}
static
af::shared< vec2<double> > get_image_coord_mm(const af::const_ref<Reflection> &r) {
af::shared< vec2<double> > result(r.size());
for (std::size_t i = 0; i < result.size(); ++i) {
result[i] = r[i].get_image_coord_mm();
}
return result;
}
static
af::shared< double > get_frame_number(const af::const_ref<Reflection> &r) {
af::shared< double > result(r.size());
for (std::size_t i = 0; i < result.size(); ++i) {
result[i] = r[i].get_frame_number();
}
return result;
}
static
af::shared< bool > get_is_valid(const af::const_ref<Reflection> &r) {
af::shared< bool > result(r.size());
for (std::size_t i = 0; i < result.size(); ++i) {
result[i] = r[i].is_valid();
}
return result;
}
// static
// flex_double get_transformed_shoebox_background(Reflection &obj) {
// return flex_double(obj.get_transformed_shoebox_background().handle(),
// obj.get_transformed_shoebox_background().accessor().as_flex_grid());
// }
void reflection_wrapper()
{
class_<ReflectionBase>("ReflectionBase")
.def(init <miller_index_type> ((
arg("miller_index"))))
.add_property("miller_index",
&ReflectionBase::get_miller_index,
&ReflectionBase::set_miller_index)
.add_property("entering",
&ReflectionBase::get_entering,
&ReflectionBase::set_entering)
.add_property("status",
&ReflectionBase::get_status,
&ReflectionBase::set_status)
.def("is_valid", &ReflectionBase::is_valid)
.def("is_active", &ReflectionBase::is_active)
.def("is_strong", &ReflectionBase::is_strong)
.def("set_valid", &ReflectionBase::set_valid)
.def("set_active", &ReflectionBase::set_active)
.def("set_strong", &ReflectionBase::set_strong)
.def("is_zero", &ReflectionBase::is_zero);
class_<Reflection, bases<ReflectionBase> > ("Reflection")
.def(init <const Reflection &>())
.def(init <miller_index_type> ((
arg("miller_index"))))
.add_property("rotation_angle",
&Reflection::get_rotation_angle,
&Reflection::set_rotation_angle)
.add_property("beam_vector",
&Reflection::get_beam_vector,
&Reflection::set_beam_vector)
.add_property("image_coord_mm",
&Reflection::get_image_coord_mm,
&Reflection::set_image_coord_mm)
.add_property("image_coord_px",
&Reflection::get_image_coord_px,
&Reflection::set_image_coord_px)
.add_property("frame_number",
&Reflection::get_frame_number,
&Reflection::set_frame_number)
.add_property("panel_number",
&Reflection::get_panel_number,
&Reflection::set_panel_number)
.add_property("bounding_box",
&Reflection::get_bounding_box,
&Reflection::set_bounding_box)
// .def("shoebox", &get_shoebox)
// .def("shoebox", &set_shoebox)
// .def("shoebox_mask", &get_shoebox_mask)
// .def("shoebox_mask", &set_shoebox_mask)
// .def("shoebox_background", &get_shoebox_background)
// .def("shoebox_background", &set_shoebox_background)
// .def("transformed_shoebox", &get_transformed_shoebox)
// .def("transformed_shoebox", &set_transformed_shoebox)
// .def("transformed_shoebox_background", &get_transformed_shoebox_background)
// .def("transformed_shoebox_background", &set_transformed_shoebox_background)
.add_property("shoebox",
&Reflection::get_shoebox,
&set_shoebox)
.add_property("shoebox_mask",
&Reflection::get_shoebox_mask,
&set_shoebox_mask)
.add_property("shoebox_background",
&Reflection::get_shoebox_background,
&set_shoebox_background)
.add_property("transformed_shoebox",
&Reflection::get_transformed_shoebox,
&set_transformed_shoebox)
.add_property("transformed_shoebox_background",
&Reflection::get_transformed_shoebox_background,
&set_transformed_shoebox_background)
.add_property("centroid_position",
&Reflection::get_centroid_position,
&Reflection::set_centroid_position)
.add_property("centroid_variance",
&Reflection::get_centroid_variance,
&Reflection::set_centroid_variance)
.add_property("centroid_sq_width",
&Reflection::get_centroid_sq_width,
&Reflection::set_centroid_sq_width)
.add_property("intensity",
&Reflection::get_intensity,
&Reflection::set_intensity)
.add_property("intensity_variance",
&Reflection::get_intensity_variance,
&Reflection::set_intensity_variance)
.add_property("corrected_intensity",
&Reflection::get_corrected_intensity,
&Reflection::set_corrected_intensity)
.add_property("corrected_intensity_variance",
&Reflection::get_corrected_intensity_variance,
&Reflection::set_corrected_intensity_variance)
.add_property("crystal",
&Reflection::get_crystal,
&Reflection::set_crystal)
.def("__str__", &reflection_to_string)
.def_pickle(reflection::ReflectionPickleSuite());
scitbx::af::boost_python::flex_wrapper
<Reflection, return_internal_reference<> >::plain("ReflectionList")
.def("__init__", make_constructor(
&init_from_observation_and_shoebox))
.def_pickle(scitbx::af::boost_python::flex_pickle_double_buffered<
Reflection,
reflection::to_string,
reflection::from_string>())
.def("miller_index", &get_miller_index)
.def("rotation_angle", &get_rotation_angle)
.def("centroid_position", &get_centroid_position)
.def("beam_vector", &get_beam_vector)
.def("set_beam_vector", &set_beam_vector)
.def("image_coord_px", &get_image_coord_px)
.def("image_coord_mm", &get_image_coord_mm)
.def("frame_number", &get_frame_number)
.def("is_valid", &get_is_valid);
}
void export_reflection() {
reflection_wrapper();
}
}}} // namespace dials::model::boost_python
<|endoftext|> |
<commit_before>/*
* Clutter-Bullet
* Copyright (C) 2010 William Hua
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include <clutter/clutter.h>
#include "clutter-bullet-actor.h"
#include <BulletCollision/CollisionShapes/btBox2dShape.h>
#include <btBulletDynamicsCommon.h>
#include "clutter-bullet-private.h"
typedef struct _ClutterBulletActorBinder ClutterBulletActorBinder;
struct _ClutterBulletActorBinder
{
gulong signal;
ClutterActor *actor;
ClutterBulletGroup *group;
};
static GHashTable *actor_binder;
static GHashTable *actor_body;
static void clutter_bullet_actor_real_bind (GObject *obj,
GParamSpec *spec,
gpointer data);
G_DEFINE_INTERFACE (
ClutterBulletActor,
clutter_bullet_actor,
G_TYPE_INVALID
);
static void
clutter_bullet_actor_default_init (ClutterBulletActorInterface *klass)
{
static GParamSpec *spec = NULL;
if (spec == NULL)
{
spec = g_param_spec_object ("actor",
"Target actor",
"Target actor to add to group",
CLUTTER_TYPE_ACTOR,
(GParamFlags) (G_PARAM_READWRITE |
G_PARAM_CONSTRUCT_ONLY));
g_object_interface_install_property (klass, spec);
spec = g_param_spec_pointer ("body",
"Rigid body",
"Physical representation of actor",
G_PARAM_READABLE);
g_object_interface_install_property (klass, spec);
}
}
ClutterActor *
clutter_bullet_actor_get_actor (ClutterActor *self)
{
ClutterActor *actor = self;
if (CLUTTER_BULLET_IS_ACTOR (self))
{
g_object_get (self, "actor", &actor, NULL);
if (actor != NULL)
g_object_unref (actor);
else
actor = self;
}
return actor;
}
btRigidBody *
clutter_bullet_actor_get_body (ClutterActor *self)
{
btRigidBody *body;
if (CLUTTER_BULLET_IS_ACTOR (self))
g_object_get (self, "body", &body, NULL);
else
body = (btRigidBody *) g_hash_table_lookup (actor_body, self);
return body;
}
void
clutter_bullet_actor_bind (ClutterActor *self,
ClutterBulletGroup *group)
{
ClutterBulletActorBinder *binder;
if (actor_binder == NULL)
actor_binder = g_hash_table_new (NULL, NULL);
binder = (ClutterBulletActorBinder *) g_hash_table_lookup (actor_binder, self);
if (binder == NULL)
{
binder = new ClutterBulletActorBinder;
binder->actor = self;
binder->group = group;
binder->signal = g_signal_connect (
clutter_bullet_actor_get_actor (self),
"notify::allocation",
G_CALLBACK (clutter_bullet_actor_real_bind),
binder
);
g_hash_table_replace (actor_binder, self, binder);
}
else
binder->group = group;
}
static void
clutter_bullet_actor_real_bind (GObject *obj,
GParamSpec *spec,
gpointer data)
{
if (!clutter_actor_has_allocation (CLUTTER_ACTOR (obj)))
return;
ClutterBulletActorBinder *binder = (ClutterBulletActorBinder *) data;
ClutterActor *self = binder->actor;
ClutterBulletGroup *group = binder->group;
if (actor_binder == NULL)
actor_binder = g_hash_table_new (NULL, NULL);
g_signal_handler_disconnect (obj, binder->signal);
g_hash_table_remove (actor_binder, self);
delete binder;
if (CLUTTER_BULLET_IS_ACTOR (self))
{
ClutterBulletActor *actor = CLUTTER_BULLET_ACTOR (self);
CLUTTER_BULLET_ACTOR_GET_INTERFACE (actor)->bind (actor, group);
}
else
{
if (actor_body == NULL)
actor_body = g_hash_table_new (NULL, NULL);
if (g_hash_table_lookup (actor_body, self) == NULL)
{
btCollisionShape *shape;
btVector3 tensor;
gdouble scale;
gfloat w, h;
scale = clutter_bullet_group_get_scale (group);
clutter_actor_get_size (self, &w, &h);
w /= scale;
h /= scale;
shape = new btBox2dShape (btVector3 (w / 2, h / 2, 0));
shape->setMargin (0);
shape->calculateLocalInertia (0, tensor);
btRigidBody *body = new btRigidBody (
btRigidBody::btRigidBodyConstructionInfo (
0,
new ClutterBulletMotionState (self, scale),
shape,
tensor
)
);
clutter_bullet_group_get_world (group)->addRigidBody (body);
g_hash_table_replace (actor_body, self, body);
}
}
}
void
clutter_bullet_actor_unbind (ClutterActor *self,
ClutterBulletGroup *group)
{
ClutterBulletActorBinder *binder;
if (actor_binder == NULL)
actor_binder = g_hash_table_new (NULL, NULL);
if ((binder = (ClutterBulletActorBinder *) g_hash_table_lookup (actor_binder, self)) != NULL)
{
g_signal_handler_disconnect (clutter_bullet_actor_get_actor (self), binder->signal);
g_hash_table_remove (actor_binder, self);
delete binder;
}
if (CLUTTER_BULLET_IS_ACTOR (self))
{
ClutterBulletActor *actor = CLUTTER_BULLET_ACTOR (self);
CLUTTER_BULLET_ACTOR_GET_INTERFACE (actor)->unbind (actor, group);
}
else
{
btRigidBody *body;
if (actor_body == NULL)
actor_body = g_hash_table_new (NULL, NULL);
if ((body = (btRigidBody *) g_hash_table_lookup (actor_body, self)) != NULL)
{
g_hash_table_remove (actor_body, self);
clutter_bullet_group_get_world (group)->removeRigidBody (body);
delete body->getCollisionShape ();
delete body->getMotionState ();
delete body;
}
}
}
<commit_msg>require ClutterBulletActors to be ClutterActors<commit_after>/*
* Clutter-Bullet
* Copyright (C) 2010 William Hua
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include <clutter/clutter.h>
#include "clutter-bullet-actor.h"
#include <BulletCollision/CollisionShapes/btBox2dShape.h>
#include <btBulletDynamicsCommon.h>
#include "clutter-bullet-private.h"
typedef struct _ClutterBulletActorBinder ClutterBulletActorBinder;
struct _ClutterBulletActorBinder
{
gulong signal;
ClutterActor *actor;
ClutterBulletGroup *group;
};
static GHashTable *actor_binder;
static GHashTable *actor_body;
static void clutter_bullet_actor_real_bind (GObject *obj,
GParamSpec *spec,
gpointer data);
G_DEFINE_INTERFACE (
ClutterBulletActor,
clutter_bullet_actor,
CLUTTER_TYPE_ACTOR
);
static void
clutter_bullet_actor_default_init (ClutterBulletActorInterface *klass)
{
static GParamSpec *spec = NULL;
if (spec == NULL)
{
spec = g_param_spec_object ("actor",
"Target actor",
"Target actor to add to group",
CLUTTER_TYPE_ACTOR,
(GParamFlags) (G_PARAM_READWRITE |
G_PARAM_CONSTRUCT_ONLY));
g_object_interface_install_property (klass, spec);
spec = g_param_spec_pointer ("body",
"Rigid body",
"Physical representation of actor",
G_PARAM_READABLE);
g_object_interface_install_property (klass, spec);
}
}
ClutterActor *
clutter_bullet_actor_get_actor (ClutterActor *self)
{
ClutterActor *actor = self;
if (CLUTTER_BULLET_IS_ACTOR (self))
{
g_object_get (self, "actor", &actor, NULL);
if (actor != NULL)
g_object_unref (actor);
else
actor = self;
}
return actor;
}
btRigidBody *
clutter_bullet_actor_get_body (ClutterActor *self)
{
btRigidBody *body;
if (CLUTTER_BULLET_IS_ACTOR (self))
g_object_get (self, "body", &body, NULL);
else
body = (btRigidBody *) g_hash_table_lookup (actor_body, self);
return body;
}
void
clutter_bullet_actor_bind (ClutterActor *self,
ClutterBulletGroup *group)
{
ClutterBulletActorBinder *binder;
if (actor_binder == NULL)
actor_binder = g_hash_table_new (NULL, NULL);
binder = (ClutterBulletActorBinder *) g_hash_table_lookup (actor_binder, self);
if (binder == NULL)
{
binder = new ClutterBulletActorBinder;
binder->actor = self;
binder->group = group;
binder->signal = g_signal_connect (
clutter_bullet_actor_get_actor (self),
"notify::allocation",
G_CALLBACK (clutter_bullet_actor_real_bind),
binder
);
g_hash_table_replace (actor_binder, self, binder);
}
else
binder->group = group;
}
static void
clutter_bullet_actor_real_bind (GObject *obj,
GParamSpec *spec,
gpointer data)
{
if (!clutter_actor_has_allocation (CLUTTER_ACTOR (obj)))
return;
ClutterBulletActorBinder *binder = (ClutterBulletActorBinder *) data;
ClutterActor *self = binder->actor;
ClutterBulletGroup *group = binder->group;
if (actor_binder == NULL)
actor_binder = g_hash_table_new (NULL, NULL);
g_signal_handler_disconnect (obj, binder->signal);
g_hash_table_remove (actor_binder, self);
delete binder;
if (CLUTTER_BULLET_IS_ACTOR (self))
{
ClutterBulletActor *actor = CLUTTER_BULLET_ACTOR (self);
CLUTTER_BULLET_ACTOR_GET_INTERFACE (actor)->bind (actor, group);
}
else
{
if (actor_body == NULL)
actor_body = g_hash_table_new (NULL, NULL);
if (g_hash_table_lookup (actor_body, self) == NULL)
{
btCollisionShape *shape;
btVector3 tensor;
gdouble scale;
gfloat w, h;
scale = clutter_bullet_group_get_scale (group);
clutter_actor_get_size (self, &w, &h);
w /= scale;
h /= scale;
shape = new btBox2dShape (btVector3 (w / 2, h / 2, 0));
shape->setMargin (0);
shape->calculateLocalInertia (0, tensor);
btRigidBody *body = new btRigidBody (
btRigidBody::btRigidBodyConstructionInfo (
0,
new ClutterBulletMotionState (self, scale),
shape,
tensor
)
);
clutter_bullet_group_get_world (group)->addRigidBody (body);
g_hash_table_replace (actor_body, self, body);
}
}
}
void
clutter_bullet_actor_unbind (ClutterActor *self,
ClutterBulletGroup *group)
{
ClutterBulletActorBinder *binder;
if (actor_binder == NULL)
actor_binder = g_hash_table_new (NULL, NULL);
if ((binder = (ClutterBulletActorBinder *) g_hash_table_lookup (actor_binder, self)) != NULL)
{
g_signal_handler_disconnect (clutter_bullet_actor_get_actor (self), binder->signal);
g_hash_table_remove (actor_binder, self);
delete binder;
}
if (CLUTTER_BULLET_IS_ACTOR (self))
{
ClutterBulletActor *actor = CLUTTER_BULLET_ACTOR (self);
CLUTTER_BULLET_ACTOR_GET_INTERFACE (actor)->unbind (actor, group);
}
else
{
btRigidBody *body;
if (actor_body == NULL)
actor_body = g_hash_table_new (NULL, NULL);
if ((body = (btRigidBody *) g_hash_table_lookup (actor_body, self)) != NULL)
{
g_hash_table_remove (actor_body, self);
clutter_bullet_group_get_world (group)->removeRigidBody (body);
delete body->getCollisionShape ();
delete body->getMotionState ();
delete body;
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 ScyllaDB
*
* Modified by ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "schema.hh"
#include "query-request.hh"
#include "mutation_fragment.hh"
// Utility for in-order checking of overlap with position ranges.
class clustering_ranges_walker {
const schema& _schema;
const query::clustering_row_ranges& _ranges;
query::clustering_row_ranges::const_iterator _current;
query::clustering_row_ranges::const_iterator _end;
bool _in_current; // next position is known to be >= _current_start
bool _with_static_row;
position_in_partition_view _current_start;
position_in_partition_view _current_end;
stdx::optional<position_in_partition> _trim;
size_t _change_counter = 1;
private:
bool advance_to_next_range() {
_in_current = false;
if (!_current_start.is_static_row()) {
if (_current == _end) {
return false;
}
++_current;
}
++_change_counter;
if (_current == _end) {
_current_end = _current_start = position_in_partition_view::after_all_clustered_rows();
return false;
}
_current_start = position_in_partition_view::for_range_start(*_current);
_current_end = position_in_partition_view::for_range_end(*_current);
return true;
}
public:
clustering_ranges_walker(const schema& s, const query::clustering_row_ranges& ranges, bool with_static_row = true)
: _schema(s)
, _ranges(ranges)
, _current(ranges.begin())
, _end(ranges.end())
, _in_current(with_static_row)
, _with_static_row(with_static_row)
, _current_start(position_in_partition_view::for_static_row())
, _current_end(position_in_partition_view::before_all_clustered_rows())
{
if (!with_static_row) {
if (_current == _end) {
_current_start = _current_end = position_in_partition_view::after_all_clustered_rows();
} else {
_current_start = position_in_partition_view::for_range_start(*_current);
_current_end = position_in_partition_view::for_range_end(*_current);
}
}
}
clustering_ranges_walker(clustering_ranges_walker&& o) noexcept
: _schema(o._schema)
, _ranges(o._ranges)
, _current(o._current)
, _end(o._end)
, _in_current(o._in_current)
, _with_static_row(o._with_static_row)
, _current_start(o._current_start)
, _current_end(o._current_end)
, _trim(std::move(o._trim))
, _change_counter(o._change_counter)
{ }
clustering_ranges_walker& operator=(clustering_ranges_walker&& o) {
if (this != &o) {
this->~clustering_ranges_walker();
new (this) clustering_ranges_walker(std::move(o));
}
return *this;
}
// Excludes positions smaller than pos from the ranges.
// pos should be monotonic.
// No constraints between pos and positions passed to advance_to().
//
// After the invocation, when !out_of_range(), lower_bound() returns the smallest position still contained.
void trim_front(position_in_partition pos) {
position_in_partition::less_compare less(_schema);
do {
if (!less(_current_start, pos)) {
break;
}
if (less(pos, _current_end)) {
_trim = std::move(pos);
_current_start = *_trim;
_in_current = false;
++_change_counter;
break;
}
} while (advance_to_next_range());
}
// Returns true if given position is contained.
// Must be called with monotonic positions.
// Idempotent.
bool advance_to(position_in_partition_view pos) {
position_in_partition::less_compare less(_schema);
do {
if (!_in_current && less(pos, _current_start)) {
break;
}
// All subsequent clustering keys are larger than the start of this
// range so there is no need to check that again.
_in_current = true;
if (less(pos, _current_end)) {
return true;
}
} while (advance_to_next_range());
return false;
}
// Returns true if the range expressed by start and end (as in position_range) overlaps
// with clustering ranges.
// Must be called with monotonic start position. That position must also be greater than
// the last position passed to the other advance_to() overload.
// Idempotent.
bool advance_to(position_in_partition_view start, position_in_partition_view end) {
position_in_partition::less_compare less(_schema);
do {
if (!less(_current_start, end)) {
break;
}
if (less(start, _current_end)) {
return true;
}
} while (advance_to_next_range());
return false;
}
// Returns true if the range tombstone expressed by start and end (as in position_range) overlaps
// with clustering ranges.
// No monotonicity restrictions on argument values across calls.
// Does not affect lower_bound().
// Idempotent.
bool contains_tombstone(position_in_partition_view start, position_in_partition_view end) const {
position_in_partition::less_compare less(_schema);
if (_trim && !less(*_trim, end)) {
return false;
}
auto i = _current;
while (i != _end) {
auto range_start = position_in_partition_view::for_range_start(*i);
if (!less(range_start, end)) {
return false;
}
auto range_end = position_in_partition_view::for_range_end(*i);
if (less(start, range_end)) {
return true;
}
++i;
}
return false;
}
// Returns true if advanced past all contained positions. Any later advance_to() until reset() will return false.
bool out_of_range() const {
return !_in_current && _current == _end;
}
// Resets the state of the walker so that advance_to() can be now called for new sequence of positions.
// Any range trimmings still hold after this.
void reset() {
auto trim = std::move(_trim);
auto ctr = _change_counter;
*this = clustering_ranges_walker(_schema, _ranges, _with_static_row);
_change_counter = ctr + 1;
if (trim) {
trim_front(std::move(*trim));
}
}
// Can be called only when !out_of_range()
position_in_partition_view lower_bound() const {
return _current_start;
}
// When lower_bound() changes, this also does
// Always > 0.
size_t lower_bound_change_counter() const {
return _change_counter;
}
};
<commit_msg>clustering_ranges_walker: Stop after static row in case no clustering ranges<commit_after>/*
* Copyright (C) 2017 ScyllaDB
*
* Modified by ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include "schema.hh"
#include "query-request.hh"
#include "mutation_fragment.hh"
// Utility for in-order checking of overlap with position ranges.
class clustering_ranges_walker {
const schema& _schema;
const query::clustering_row_ranges& _ranges;
query::clustering_row_ranges::const_iterator _current;
query::clustering_row_ranges::const_iterator _end;
bool _in_current; // next position is known to be >= _current_start
bool _with_static_row;
position_in_partition_view _current_start;
position_in_partition_view _current_end;
stdx::optional<position_in_partition> _trim;
size_t _change_counter = 1;
private:
bool advance_to_next_range() {
_in_current = false;
if (!_current_start.is_static_row()) {
if (_current == _end) {
return false;
}
++_current;
}
++_change_counter;
if (_current == _end) {
_current_end = _current_start = position_in_partition_view::after_all_clustered_rows();
return false;
}
_current_start = position_in_partition_view::for_range_start(*_current);
_current_end = position_in_partition_view::for_range_end(*_current);
return true;
}
public:
clustering_ranges_walker(const schema& s, const query::clustering_row_ranges& ranges, bool with_static_row = true)
: _schema(s)
, _ranges(ranges)
, _current(ranges.begin())
, _end(ranges.end())
, _in_current(with_static_row)
, _with_static_row(with_static_row)
, _current_start(position_in_partition_view::for_static_row())
, _current_end(position_in_partition_view::before_all_clustered_rows())
{
if (!with_static_row) {
if (_current == _end) {
_current_start = position_in_partition_view::before_all_clustered_rows();
} else {
_current_start = position_in_partition_view::for_range_start(*_current);
_current_end = position_in_partition_view::for_range_end(*_current);
}
}
}
clustering_ranges_walker(clustering_ranges_walker&& o) noexcept
: _schema(o._schema)
, _ranges(o._ranges)
, _current(o._current)
, _end(o._end)
, _in_current(o._in_current)
, _with_static_row(o._with_static_row)
, _current_start(o._current_start)
, _current_end(o._current_end)
, _trim(std::move(o._trim))
, _change_counter(o._change_counter)
{ }
clustering_ranges_walker& operator=(clustering_ranges_walker&& o) {
if (this != &o) {
this->~clustering_ranges_walker();
new (this) clustering_ranges_walker(std::move(o));
}
return *this;
}
// Excludes positions smaller than pos from the ranges.
// pos should be monotonic.
// No constraints between pos and positions passed to advance_to().
//
// After the invocation, when !out_of_range(), lower_bound() returns the smallest position still contained.
void trim_front(position_in_partition pos) {
position_in_partition::less_compare less(_schema);
do {
if (!less(_current_start, pos)) {
break;
}
if (less(pos, _current_end)) {
_trim = std::move(pos);
_current_start = *_trim;
_in_current = false;
++_change_counter;
break;
}
} while (advance_to_next_range());
}
// Returns true if given position is contained.
// Must be called with monotonic positions.
// Idempotent.
bool advance_to(position_in_partition_view pos) {
position_in_partition::less_compare less(_schema);
do {
if (!_in_current && less(pos, _current_start)) {
break;
}
// All subsequent clustering keys are larger than the start of this
// range so there is no need to check that again.
_in_current = true;
if (less(pos, _current_end)) {
return true;
}
} while (advance_to_next_range());
return false;
}
// Returns true if the range expressed by start and end (as in position_range) overlaps
// with clustering ranges.
// Must be called with monotonic start position. That position must also be greater than
// the last position passed to the other advance_to() overload.
// Idempotent.
bool advance_to(position_in_partition_view start, position_in_partition_view end) {
position_in_partition::less_compare less(_schema);
do {
if (!less(_current_start, end)) {
break;
}
if (less(start, _current_end)) {
return true;
}
} while (advance_to_next_range());
return false;
}
// Returns true if the range tombstone expressed by start and end (as in position_range) overlaps
// with clustering ranges.
// No monotonicity restrictions on argument values across calls.
// Does not affect lower_bound().
// Idempotent.
bool contains_tombstone(position_in_partition_view start, position_in_partition_view end) const {
position_in_partition::less_compare less(_schema);
if (_trim && !less(*_trim, end)) {
return false;
}
auto i = _current;
while (i != _end) {
auto range_start = position_in_partition_view::for_range_start(*i);
if (!less(range_start, end)) {
return false;
}
auto range_end = position_in_partition_view::for_range_end(*i);
if (less(start, range_end)) {
return true;
}
++i;
}
return false;
}
// Returns true if advanced past all contained positions. Any later advance_to() until reset() will return false.
bool out_of_range() const {
return !_in_current && _current == _end;
}
// Resets the state of the walker so that advance_to() can be now called for new sequence of positions.
// Any range trimmings still hold after this.
void reset() {
auto trim = std::move(_trim);
auto ctr = _change_counter;
*this = clustering_ranges_walker(_schema, _ranges, _with_static_row);
_change_counter = ctr + 1;
if (trim) {
trim_front(std::move(*trim));
}
}
// Can be called only when !out_of_range()
position_in_partition_view lower_bound() const {
return _current_start;
}
// When lower_bound() changes, this also does
// Always > 0.
size_t lower_bound_change_counter() const {
return _change_counter;
}
};
<|endoftext|> |
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "test_precomp.hpp"
#include "opencv2/highgui.hpp"
#include <vector>
#include <string>
using namespace std;
using namespace cv;
#undef RENDER_MSERS
#define RENDER_MSERS 0
#if defined RENDER_MSERS && RENDER_MSERS
static void renderMSERs(const Mat& gray, Mat& img, const vector<vector<Point> >& msers)
{
cvtColor(gray, img, COLOR_GRAY2BGR);
RNG rng((uint64)1749583);
for( int i = 0; i < (int)msers.size(); i++ )
{
uchar b = rng.uniform(0, 256);
uchar g = rng.uniform(0, 256);
uchar r = rng.uniform(0, 256);
Vec3b color(b, g, r);
const Point* pt = &msers[i][0];
size_t j, n = msers[i].size();
for( j = 0; j < n; j++ )
img.at<Vec3b>(pt[j]) = color;
}
}
#endif
TEST(Features2d_MSER, cases)
{
uchar buf[] =
{
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255,
255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255,
255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255,
255, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255
};
Mat big_image = imread(cvtest::TS::ptr()->get_data_path() + "mser/puzzle.png", 0);
Mat small_image(14, 26, CV_8U, buf);
static const int thresharr[] = { 0, 70, 120, 180, 255 };
const int kDelta = 5;
Ptr<MSER> mserExtractor = MSER::create( kDelta );
vector<vector<Point> > msers;
vector<Rect> boxes;
RNG& rng = theRNG();
for( int i = 0; i < 30; i++ )
{
bool use_big_image = rng.uniform(0, 7) != 0;
bool invert = rng.uniform(0, 2) != 0;
bool binarize = use_big_image ? rng.uniform(0, 5) != 0 : false;
bool blur = rng.uniform(0, 2) != 0;
int thresh = thresharr[rng.uniform(0, 5)];
/*if( i == 0 )
{
use_big_image = true;
invert = binarize = blur = false;
}*/
const Mat& src0 = use_big_image ? big_image : small_image;
Mat src = src0.clone();
int kMinArea = use_big_image ? 256 : 10;
int kMaxArea = (int)src.total()/4;
mserExtractor->setMinArea(kMinArea);
mserExtractor->setMaxArea(kMaxArea);
if( invert )
bitwise_not(src, src);
if( binarize )
threshold(src, src, thresh, 255, THRESH_BINARY);
if( blur )
GaussianBlur(src, src, Size(5, 5), 1.5, 1.5);
int minRegs = use_big_image ? 10 : 2;
int maxRegs = use_big_image ? 1000 : 15;
if( binarize && (thresh == 0 || thresh == 255) )
minRegs = maxRegs = 0;
mserExtractor->detectRegions( src, msers, boxes );
int nmsers = (int)msers.size();
ASSERT_EQ(nmsers, (int)boxes.size());
if( maxRegs < nmsers || minRegs > nmsers )
{
printf("%d. minArea=%d, maxArea=%d, nmsers=%d, minRegs=%d, maxRegs=%d, "
"image=%s, invert=%d, binarize=%d, thresh=%d, blur=%d\n",
i, kMinArea, kMaxArea, nmsers, minRegs, maxRegs, use_big_image ? "big" : "small",
(int)invert, (int)binarize, thresh, (int)blur);
#if defined RENDER_MSERS && RENDER_MSERS
Mat image;
imshow("source", src);
renderMSERs(src, image, msers);
imshow("result", image);
waitKey();
#endif
}
ASSERT_LE(minRegs, nmsers);
ASSERT_GE(maxRegs, nmsers);
}
}
<commit_msg>another attempt to make the MSER test pass. removed possible randomization in parameters from run to run<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "test_precomp.hpp"
#include "opencv2/highgui.hpp"
#include <vector>
#include <string>
using namespace std;
using namespace cv;
#undef RENDER_MSERS
#define RENDER_MSERS 0
#if defined RENDER_MSERS && RENDER_MSERS
static void renderMSERs(const Mat& gray, Mat& img, const vector<vector<Point> >& msers)
{
cvtColor(gray, img, COLOR_GRAY2BGR);
RNG rng((uint64)1749583);
for( int i = 0; i < (int)msers.size(); i++ )
{
uchar b = rng.uniform(0, 256);
uchar g = rng.uniform(0, 256);
uchar r = rng.uniform(0, 256);
Vec3b color(b, g, r);
const Point* pt = &msers[i][0];
size_t j, n = msers[i].size();
for( j = 0; j < n; j++ )
img.at<Vec3b>(pt[j]) = color;
}
}
#endif
TEST(Features2d_MSER, cases)
{
uchar buf[] =
{
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255,
255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255,
255, 255, 255, 255, 255, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255,
255, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255
};
Mat big_image = imread(cvtest::TS::ptr()->get_data_path() + "mser/puzzle.png", 0);
Mat small_image(14, 26, CV_8U, buf);
static const int thresharr[] = { 0, 70, 120, 180, 255 };
const int kDelta = 5;
Ptr<MSER> mserExtractor = MSER::create( kDelta );
vector<vector<Point> > msers;
vector<Rect> boxes;
RNG rng((uint64)123456);
for( int i = 0; i < 100; i++ )
{
bool use_big_image = rng.uniform(0, 7) != 0;
bool invert = rng.uniform(0, 2) != 0;
bool binarize = use_big_image ? rng.uniform(0, 5) != 0 : false;
bool blur = rng.uniform(0, 2) != 0;
int thresh = thresharr[rng.uniform(0, 5)];
/*if( i == 0 )
{
use_big_image = true;
invert = binarize = blur = false;
}*/
const Mat& src0 = use_big_image ? big_image : small_image;
Mat src = src0.clone();
int kMinArea = use_big_image ? 256 : 10;
int kMaxArea = (int)src.total()/4;
mserExtractor->setMinArea(kMinArea);
mserExtractor->setMaxArea(kMaxArea);
if( invert )
bitwise_not(src, src);
if( binarize )
threshold(src, src, thresh, 255, THRESH_BINARY);
if( blur )
GaussianBlur(src, src, Size(5, 5), 1.5, 1.5);
int minRegs = use_big_image ? 7 : 2;
int maxRegs = use_big_image ? 1000 : 15;
if( binarize && (thresh == 0 || thresh == 255) )
minRegs = maxRegs = 0;
mserExtractor->detectRegions( src, msers, boxes );
int nmsers = (int)msers.size();
ASSERT_EQ(nmsers, (int)boxes.size());
if( maxRegs < nmsers || minRegs > nmsers )
{
printf("%d. minArea=%d, maxArea=%d, nmsers=%d, minRegs=%d, maxRegs=%d, "
"image=%s, invert=%d, binarize=%d, thresh=%d, blur=%d\n",
i, kMinArea, kMaxArea, nmsers, minRegs, maxRegs, use_big_image ? "big" : "small",
(int)invert, (int)binarize, thresh, (int)blur);
#if defined RENDER_MSERS && RENDER_MSERS
Mat image;
imshow("source", src);
renderMSERs(src, image, msers);
imshow("result", image);
waitKey();
#endif
}
ASSERT_LE(minRegs, nmsers);
ASSERT_GE(maxRegs, nmsers);
}
}
<|endoftext|> |
<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
using namespace cv;
using namespace cv::gpu;
cv::gpu::CudaMem::CudaMem()
: flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(0)
{
}
cv::gpu::CudaMem::CudaMem(int _rows, int _cols, int _type, int _alloc_type)
: flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(0)
{
if( _rows > 0 && _cols > 0 )
create( _rows, _cols, _type, _alloc_type);
}
cv::gpu::CudaMem::CudaMem(Size _size, int _type, int _alloc_type)
: flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(0)
{
if( _size.height > 0 && _size.width > 0 )
create( _size.height, _size.width, _type, _alloc_type);
}
cv::gpu::CudaMem::CudaMem(const CudaMem& m)
: flags(m.flags), rows(m.rows), cols(m.cols), step(m.step), data(m.data), refcount(m.refcount), datastart(m.datastart), dataend(m.dataend), alloc_type(m.alloc_type)
{
if( refcount )
CV_XADD(refcount, 1);
}
cv::gpu::CudaMem::CudaMem(const Mat& m, int _alloc_type)
: flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(0)
{
if( m.rows > 0 && m.cols > 0 )
create( m.size(), m.type(), _alloc_type);
Mat tmp = createMatHeader();
m.copyTo(tmp);
}
cv::gpu::CudaMem::~CudaMem()
{
release();
}
CudaMem& cv::gpu::CudaMem::operator = (const CudaMem& m)
{
if( this != &m )
{
if( m.refcount )
CV_XADD(m.refcount, 1);
release();
flags = m.flags;
rows = m.rows; cols = m.cols;
step = m.step; data = m.data;
datastart = m.datastart;
dataend = m.dataend;
refcount = m.refcount;
alloc_type = m.alloc_type;
}
return *this;
}
CudaMem cv::gpu::CudaMem::clone() const
{
CudaMem m(size(), type(), alloc_type);
Mat to = m;
Mat from = *this;
from.copyTo(to);
return m;
}
void cv::gpu::CudaMem::create(Size _size, int _type, int _alloc_type)
{
create(_size.height, _size.width, _type, _alloc_type);
}
Mat cv::gpu::CudaMem::createMatHeader() const
{
return Mat(size(), type(), data, step);
}
cv::gpu::CudaMem::operator Mat() const
{
return createMatHeader();
}
cv::gpu::CudaMem::operator GpuMat() const
{
return createGpuMatHeader();
}
bool cv::gpu::CudaMem::isContinuous() const
{
return (flags & Mat::CONTINUOUS_FLAG) != 0;
}
size_t cv::gpu::CudaMem::elemSize() const
{
return CV_ELEM_SIZE(flags);
}
size_t cv::gpu::CudaMem::elemSize1() const
{
return CV_ELEM_SIZE1(flags);
}
int cv::gpu::CudaMem::type() const
{
return CV_MAT_TYPE(flags);
}
int cv::gpu::CudaMem::depth() const
{
return CV_MAT_DEPTH(flags);
}
int cv::gpu::CudaMem::channels() const
{
return CV_MAT_CN(flags);
}
size_t cv::gpu::CudaMem::step1() const
{
return step/elemSize1();
}
Size cv::gpu::CudaMem::size() const
{
return Size(cols, rows);
}
bool cv::gpu::CudaMem::empty() const
{
return data == 0;
}
#if !defined (HAVE_CUDA)
void cv::gpu::registerPageLocked(Mat&) { throw_nogpu(); }
void cv::gpu::unregisterPageLocked(Mat&) { throw_nogpu(); }
void cv::gpu::CudaMem::create(int /*_rows*/, int /*_cols*/, int /*_type*/, int /*type_alloc*/) { throw_nogpu(); }
bool cv::gpu::CudaMem::canMapHostMemory() { throw_nogpu(); return false; }
void cv::gpu::CudaMem::release() { throw_nogpu(); }
GpuMat cv::gpu::CudaMem::createGpuMatHeader () const { throw_nogpu(); return GpuMat(); }
#else /* !defined (HAVE_CUDA) */
void registerPageLocked(Mat& m)
{
cudaSafeCall( cudaHostRegister(m.ptr(), m.step * m.rows, cudaHostRegisterPortable) );
}
void unregisterPageLocked(Mat& m)
{
cudaSafeCall( cudaHostUnregister(m.ptr()) );
}
bool cv::gpu::CudaMem::canMapHostMemory()
{
cudaDeviceProp prop;
cudaSafeCall( cudaGetDeviceProperties(&prop, getDevice()) );
return (prop.canMapHostMemory != 0) ? true : false;
}
namespace
{
size_t alignUpStep(size_t what, size_t alignment)
{
size_t alignMask = alignment-1;
size_t inverseAlignMask = ~alignMask;
size_t res = (what + alignMask) & inverseAlignMask;
return res;
}
}
void cv::gpu::CudaMem::create(int _rows, int _cols, int _type, int _alloc_type)
{
if (_alloc_type == ALLOC_ZEROCOPY && !canMapHostMemory())
cv::gpu::error("ZeroCopy is not supported by current device", __FILE__, __LINE__);
_type &= TYPE_MASK;
if( rows == _rows && cols == _cols && type() == _type && data )
return;
if( data )
release();
CV_DbgAssert( _rows >= 0 && _cols >= 0 );
if( _rows > 0 && _cols > 0 )
{
flags = Mat::MAGIC_VAL + Mat::CONTINUOUS_FLAG + _type;
rows = _rows;
cols = _cols;
step = elemSize()*cols;
if (_alloc_type == ALLOC_ZEROCOPY)
{
cudaDeviceProp prop;
cudaSafeCall( cudaGetDeviceProperties(&prop, getDevice()) );
step = alignUpStep(step, prop.textureAlignment);
}
int64 _nettosize = (int64)step*rows;
size_t nettosize = (size_t)_nettosize;
if( _nettosize != (int64)nettosize )
CV_Error(CV_StsNoMem, "Too big buffer is allocated");
size_t datasize = alignSize(nettosize, (int)sizeof(*refcount));
//datastart = data = (uchar*)fastMalloc(datasize + sizeof(*refcount));
alloc_type = _alloc_type;
void *ptr;
switch (alloc_type)
{
case ALLOC_PAGE_LOCKED: cudaSafeCall( cudaHostAlloc( &ptr, datasize, cudaHostAllocDefault) ); break;
case ALLOC_ZEROCOPY: cudaSafeCall( cudaHostAlloc( &ptr, datasize, cudaHostAllocMapped) ); break;
case ALLOC_WRITE_COMBINED: cudaSafeCall( cudaHostAlloc( &ptr, datasize, cudaHostAllocWriteCombined) ); break;
default: cv::gpu::error("Invalid alloc type", __FILE__, __LINE__);
}
datastart = data = (uchar*)ptr;
dataend = data + nettosize;
refcount = (int*)cv::fastMalloc(sizeof(*refcount));
*refcount = 1;
}
}
GpuMat cv::gpu::CudaMem::createGpuMatHeader () const
{
GpuMat res;
if (alloc_type == ALLOC_ZEROCOPY)
{
void *pdev;
cudaSafeCall( cudaHostGetDevicePointer( &pdev, data, 0 ) );
res = GpuMat(rows, cols, type(), pdev, step);
}
else
cv::gpu::error("Zero-copy is not supported or memory was allocated without zero-copy flag", __FILE__, __LINE__);
return res;
}
void cv::gpu::CudaMem::release()
{
if( refcount && CV_XADD(refcount, -1) == 1 )
{
cudaSafeCall( cudaFreeHost(datastart ) );
fastFree(refcount);
}
data = datastart = dataend = 0;
step = rows = cols = 0;
refcount = 0;
}
#endif /* !defined (HAVE_CUDA) */
<commit_msg>fixed #2113<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
using namespace cv;
using namespace cv::gpu;
cv::gpu::CudaMem::CudaMem()
: flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(0)
{
}
cv::gpu::CudaMem::CudaMem(int _rows, int _cols, int _type, int _alloc_type)
: flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(0)
{
if( _rows > 0 && _cols > 0 )
create( _rows, _cols, _type, _alloc_type);
}
cv::gpu::CudaMem::CudaMem(Size _size, int _type, int _alloc_type)
: flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(0)
{
if( _size.height > 0 && _size.width > 0 )
create( _size.height, _size.width, _type, _alloc_type);
}
cv::gpu::CudaMem::CudaMem(const CudaMem& m)
: flags(m.flags), rows(m.rows), cols(m.cols), step(m.step), data(m.data), refcount(m.refcount), datastart(m.datastart), dataend(m.dataend), alloc_type(m.alloc_type)
{
if( refcount )
CV_XADD(refcount, 1);
}
cv::gpu::CudaMem::CudaMem(const Mat& m, int _alloc_type)
: flags(0), rows(0), cols(0), step(0), data(0), refcount(0), datastart(0), dataend(0), alloc_type(0)
{
if( m.rows > 0 && m.cols > 0 )
create( m.size(), m.type(), _alloc_type);
Mat tmp = createMatHeader();
m.copyTo(tmp);
}
cv::gpu::CudaMem::~CudaMem()
{
release();
}
CudaMem& cv::gpu::CudaMem::operator = (const CudaMem& m)
{
if( this != &m )
{
if( m.refcount )
CV_XADD(m.refcount, 1);
release();
flags = m.flags;
rows = m.rows; cols = m.cols;
step = m.step; data = m.data;
datastart = m.datastart;
dataend = m.dataend;
refcount = m.refcount;
alloc_type = m.alloc_type;
}
return *this;
}
CudaMem cv::gpu::CudaMem::clone() const
{
CudaMem m(size(), type(), alloc_type);
Mat to = m;
Mat from = *this;
from.copyTo(to);
return m;
}
void cv::gpu::CudaMem::create(Size _size, int _type, int _alloc_type)
{
create(_size.height, _size.width, _type, _alloc_type);
}
Mat cv::gpu::CudaMem::createMatHeader() const
{
return Mat(size(), type(), data, step);
}
cv::gpu::CudaMem::operator Mat() const
{
return createMatHeader();
}
cv::gpu::CudaMem::operator GpuMat() const
{
return createGpuMatHeader();
}
bool cv::gpu::CudaMem::isContinuous() const
{
return (flags & Mat::CONTINUOUS_FLAG) != 0;
}
size_t cv::gpu::CudaMem::elemSize() const
{
return CV_ELEM_SIZE(flags);
}
size_t cv::gpu::CudaMem::elemSize1() const
{
return CV_ELEM_SIZE1(flags);
}
int cv::gpu::CudaMem::type() const
{
return CV_MAT_TYPE(flags);
}
int cv::gpu::CudaMem::depth() const
{
return CV_MAT_DEPTH(flags);
}
int cv::gpu::CudaMem::channels() const
{
return CV_MAT_CN(flags);
}
size_t cv::gpu::CudaMem::step1() const
{
return step/elemSize1();
}
Size cv::gpu::CudaMem::size() const
{
return Size(cols, rows);
}
bool cv::gpu::CudaMem::empty() const
{
return data == 0;
}
#if !defined (HAVE_CUDA)
void cv::gpu::registerPageLocked(Mat&) { throw_nogpu(); }
void cv::gpu::unregisterPageLocked(Mat&) { throw_nogpu(); }
void cv::gpu::CudaMem::create(int /*_rows*/, int /*_cols*/, int /*_type*/, int /*type_alloc*/) { throw_nogpu(); }
bool cv::gpu::CudaMem::canMapHostMemory() { throw_nogpu(); return false; }
void cv::gpu::CudaMem::release() { throw_nogpu(); }
GpuMat cv::gpu::CudaMem::createGpuMatHeader () const { throw_nogpu(); return GpuMat(); }
#else /* !defined (HAVE_CUDA) */
void cv::gpu::registerPageLocked(Mat& m)
{
cudaSafeCall( cudaHostRegister(m.ptr(), m.step * m.rows, cudaHostRegisterPortable) );
}
void cv::gpu::unregisterPageLocked(Mat& m)
{
cudaSafeCall( cudaHostUnregister(m.ptr()) );
}
bool cv::gpu::CudaMem::canMapHostMemory()
{
cudaDeviceProp prop;
cudaSafeCall( cudaGetDeviceProperties(&prop, getDevice()) );
return (prop.canMapHostMemory != 0) ? true : false;
}
namespace
{
size_t alignUpStep(size_t what, size_t alignment)
{
size_t alignMask = alignment-1;
size_t inverseAlignMask = ~alignMask;
size_t res = (what + alignMask) & inverseAlignMask;
return res;
}
}
void cv::gpu::CudaMem::create(int _rows, int _cols, int _type, int _alloc_type)
{
if (_alloc_type == ALLOC_ZEROCOPY && !canMapHostMemory())
cv::gpu::error("ZeroCopy is not supported by current device", __FILE__, __LINE__);
_type &= TYPE_MASK;
if( rows == _rows && cols == _cols && type() == _type && data )
return;
if( data )
release();
CV_DbgAssert( _rows >= 0 && _cols >= 0 );
if( _rows > 0 && _cols > 0 )
{
flags = Mat::MAGIC_VAL + Mat::CONTINUOUS_FLAG + _type;
rows = _rows;
cols = _cols;
step = elemSize()*cols;
if (_alloc_type == ALLOC_ZEROCOPY)
{
cudaDeviceProp prop;
cudaSafeCall( cudaGetDeviceProperties(&prop, getDevice()) );
step = alignUpStep(step, prop.textureAlignment);
}
int64 _nettosize = (int64)step*rows;
size_t nettosize = (size_t)_nettosize;
if( _nettosize != (int64)nettosize )
CV_Error(CV_StsNoMem, "Too big buffer is allocated");
size_t datasize = alignSize(nettosize, (int)sizeof(*refcount));
//datastart = data = (uchar*)fastMalloc(datasize + sizeof(*refcount));
alloc_type = _alloc_type;
void *ptr;
switch (alloc_type)
{
case ALLOC_PAGE_LOCKED: cudaSafeCall( cudaHostAlloc( &ptr, datasize, cudaHostAllocDefault) ); break;
case ALLOC_ZEROCOPY: cudaSafeCall( cudaHostAlloc( &ptr, datasize, cudaHostAllocMapped) ); break;
case ALLOC_WRITE_COMBINED: cudaSafeCall( cudaHostAlloc( &ptr, datasize, cudaHostAllocWriteCombined) ); break;
default: cv::gpu::error("Invalid alloc type", __FILE__, __LINE__);
}
datastart = data = (uchar*)ptr;
dataend = data + nettosize;
refcount = (int*)cv::fastMalloc(sizeof(*refcount));
*refcount = 1;
}
}
GpuMat cv::gpu::CudaMem::createGpuMatHeader () const
{
GpuMat res;
if (alloc_type == ALLOC_ZEROCOPY)
{
void *pdev;
cudaSafeCall( cudaHostGetDevicePointer( &pdev, data, 0 ) );
res = GpuMat(rows, cols, type(), pdev, step);
}
else
cv::gpu::error("Zero-copy is not supported or memory was allocated without zero-copy flag", __FILE__, __LINE__);
return res;
}
void cv::gpu::CudaMem::release()
{
if( refcount && CV_XADD(refcount, -1) == 1 )
{
cudaSafeCall( cudaFreeHost(datastart ) );
fastFree(refcount);
}
data = datastart = dataend = 0;
step = rows = cols = 0;
refcount = 0;
}
#endif /* !defined (HAVE_CUDA) */
<|endoftext|> |
<commit_before>#include "lm/model.hh"
#include "util/file_piece.hh"
#include <cstdlib>
#include <exception>
#include <iostream>
#include <iomanip>
#include <math.h>
#include <stdlib.h>
#ifdef WIN32
#include "util/getopt.hh"
#endif
namespace lm {
namespace ngram {
namespace {
void Usage(const char *name) {
std::cerr << "Usage: " << name << " [-u log10_unknown_probability] [-s] [-i] [-p probing_multiplier] [-t trie_temporary] [-m trie_building_megabytes] [-q bits] [-b bits] [-a bits] [type] input.arpa [output.mmap]\n\n"
"-u sets the log10 probability for <unk> if the ARPA file does not have one.\n"
" Default is -100. The ARPA file will always take precedence.\n"
"-s allows models to be built even if they do not have <s> and </s>.\n"
"-i allows buggy models from IRSTLM by mapping positive log probability to 0.\n\n"
"type is either probing or trie. Default is probing.\n\n"
"probing uses a probing hash table. It is the fastest but uses the most memory.\n"
"-p sets the space multiplier and must be >1.0. The default is 1.5.\n\n"
"trie is a straightforward trie with bit-level packing. It uses the least\n"
"memory and is still faster than SRI or IRST. Building the trie format uses an\n"
"on-disk sort to save memory.\n"
"-t is the temporary directory prefix. Default is the output file name.\n"
"-m limits memory use for sorting. Measured in MB. Default is 1024MB.\n"
"-q turns quantization on and sets the number of bits (e.g. -q 8).\n"
"-b sets backoff quantization bits. Requires -q and defaults to that value.\n"
"-a compresses pointers using an array of offsets. The parameter is the\n"
" maximum number of bits encoded by the array. Memory is minimized subject\n"
" to the maximum, so pick 255 to minimize memory.\n\n"
"Get a memory estimate by passing an ARPA file without an output file name.\n";
exit(1);
}
// I could really use boost::lexical_cast right about now.
float ParseFloat(const char *from) {
char *end;
float ret = strtod(from, &end);
if (*end) throw util::ParseNumberException(from);
return ret;
}
unsigned long int ParseUInt(const char *from) {
char *end;
unsigned long int ret = strtoul(from, &end, 10);
if (*end) throw util::ParseNumberException(from);
return ret;
}
uint8_t ParseBitCount(const char *from) {
unsigned long val = ParseUInt(from);
if (val > 25) {
util::ParseNumberException e(from);
e << " bit counts are limited to 256.";
}
return val;
}
void ShowSizes(const char *file, const lm::ngram::Config &config) {
std::vector<uint64_t> counts;
util::FilePiece f(file);
lm::ReadARPACounts(f, counts);
std::size_t sizes[5];
sizes[0] = ProbingModel::Size(counts, config);
sizes[1] = TrieModel::Size(counts, config);
sizes[2] = QuantTrieModel::Size(counts, config);
sizes[3] = ArrayTrieModel::Size(counts, config);
sizes[4] = QuantArrayTrieModel::Size(counts, config);
std::size_t max_length = *std::max_element(sizes, sizes + sizeof(sizes) / sizeof(size_t));
std::size_t min_length = *std::min_element(sizes, sizes + sizeof(sizes) / sizeof(size_t));
std::size_t divide;
char prefix;
if (min_length < (1 << 10) * 10) {
prefix = ' ';
divide = 1;
} else if (min_length < (1 << 20) * 10) {
prefix = 'k';
divide = 1 << 10;
} else if (min_length < (1ULL << 30) * 10) {
prefix = 'M';
divide = 1 << 20;
} else {
prefix = 'G';
divide = 1 << 30;
}
long int length = std::max<long int>(2, static_cast<long int>(ceil(log10((double) max_length / divide))));
std::cout << "Memory estimate:\ntype ";
// right align bytes.
for (long int i = 0; i < length - 2; ++i) std::cout << ' ';
std::cout << prefix << "B\n"
"probing " << std::setw(length) << (sizes[0] / divide) << " assuming -p " << config.probing_multiplier << "\n"
"trie " << std::setw(length) << (sizes[1] / divide) << " without quantization\n"
"trie " << std::setw(length) << (sizes[2] / divide) << " assuming -q " << (unsigned)config.prob_bits << " -b " << (unsigned)config.backoff_bits << " quantization \n"
"trie " << std::setw(length) << (sizes[3] / divide) << " assuming -a " << (unsigned)config.pointer_bhiksha_bits << " array pointer compression\n"
"trie " << std::setw(length) << (sizes[4] / divide) << " assuming -a " << (unsigned)config.pointer_bhiksha_bits << " -q " << (unsigned)config.prob_bits << " -b " << (unsigned)config.backoff_bits<< " array pointer compression and quantization\n";
}
void ProbingQuantizationUnsupported() {
std::cerr << "Quantization is only implemented in the trie data structure." << std::endl;
exit(1);
}
} // namespace ngram
} // namespace lm
} // namespace
int main(int argc, char *argv[]) {
using namespace lm::ngram;
try {
bool quantize = false, set_backoff_bits = false, bhiksha = false;
lm::ngram::Config config;
int opt;
while ((opt = getopt(argc, argv, "siu:p:t:m:q:b:a:")) != -1) {
switch(opt) {
case 'q':
config.prob_bits = ParseBitCount(optarg);
if (!set_backoff_bits) config.backoff_bits = config.prob_bits;
quantize = true;
break;
case 'b':
config.backoff_bits = ParseBitCount(optarg);
set_backoff_bits = true;
break;
case 'a':
config.pointer_bhiksha_bits = ParseBitCount(optarg);
bhiksha = true;
case 'u':
config.unknown_missing_logprob = ParseFloat(optarg);
break;
case 'p':
config.probing_multiplier = ParseFloat(optarg);
break;
case 't':
config.temporary_directory_prefix = optarg;
break;
case 'm':
config.building_memory = ParseUInt(optarg) * 1048576;
break;
case 's':
config.sentence_marker_missing = lm::SILENT;
break;
case 'i':
config.positive_log_probability = lm::SILENT;
break;
default:
Usage(argv[0]);
}
}
if (!quantize && set_backoff_bits) {
std::cerr << "You specified backoff quantization (-b) but not probability quantization (-q)" << std::endl;
abort();
}
if (optind + 1 == argc) {
ShowSizes(argv[optind], config);
} else if (optind + 2 == argc) {
config.write_mmap = argv[optind + 1];
if (quantize || set_backoff_bits) ProbingQuantizationUnsupported();
ProbingModel(argv[optind], config);
} else if (optind + 3 == argc) {
const char *model_type = argv[optind];
const char *from_file = argv[optind + 1];
config.write_mmap = argv[optind + 2];
if (!strcmp(model_type, "probing")) {
if (quantize || set_backoff_bits) ProbingQuantizationUnsupported();
ProbingModel(from_file, config);
} else if (!strcmp(model_type, "trie")) {
if (quantize) {
if (bhiksha) {
QuantArrayTrieModel(from_file, config);
} else {
QuantTrieModel(from_file, config);
}
} else {
if (bhiksha) {
ArrayTrieModel(from_file, config);
} else {
TrieModel(from_file, config);
}
}
} else {
Usage(argv[0]);
}
} else {
Usage(argv[0]);
}
}
catch (const std::exception &e) {
std::cerr << e.what() << std::endl;
return 1;
}
return 0;
}
<commit_msg>kenlm build binary stderr message on exit<commit_after>#include "lm/model.hh"
#include "util/file_piece.hh"
#include <cstdlib>
#include <exception>
#include <iostream>
#include <iomanip>
#include <math.h>
#include <stdlib.h>
#ifdef WIN32
#include "util/getopt.hh"
#endif
namespace lm {
namespace ngram {
namespace {
void Usage(const char *name) {
std::cerr << "Usage: " << name << " [-u log10_unknown_probability] [-s] [-i] [-p probing_multiplier] [-t trie_temporary] [-m trie_building_megabytes] [-q bits] [-b bits] [-a bits] [type] input.arpa [output.mmap]\n\n"
"-u sets the log10 probability for <unk> if the ARPA file does not have one.\n"
" Default is -100. The ARPA file will always take precedence.\n"
"-s allows models to be built even if they do not have <s> and </s>.\n"
"-i allows buggy models from IRSTLM by mapping positive log probability to 0.\n\n"
"type is either probing or trie. Default is probing.\n\n"
"probing uses a probing hash table. It is the fastest but uses the most memory.\n"
"-p sets the space multiplier and must be >1.0. The default is 1.5.\n\n"
"trie is a straightforward trie with bit-level packing. It uses the least\n"
"memory and is still faster than SRI or IRST. Building the trie format uses an\n"
"on-disk sort to save memory.\n"
"-t is the temporary directory prefix. Default is the output file name.\n"
"-m limits memory use for sorting. Measured in MB. Default is 1024MB.\n"
"-q turns quantization on and sets the number of bits (e.g. -q 8).\n"
"-b sets backoff quantization bits. Requires -q and defaults to that value.\n"
"-a compresses pointers using an array of offsets. The parameter is the\n"
" maximum number of bits encoded by the array. Memory is minimized subject\n"
" to the maximum, so pick 255 to minimize memory.\n\n"
"Get a memory estimate by passing an ARPA file without an output file name.\n";
exit(1);
}
// I could really use boost::lexical_cast right about now.
float ParseFloat(const char *from) {
char *end;
float ret = strtod(from, &end);
if (*end) throw util::ParseNumberException(from);
return ret;
}
unsigned long int ParseUInt(const char *from) {
char *end;
unsigned long int ret = strtoul(from, &end, 10);
if (*end) throw util::ParseNumberException(from);
return ret;
}
uint8_t ParseBitCount(const char *from) {
unsigned long val = ParseUInt(from);
if (val > 25) {
util::ParseNumberException e(from);
e << " bit counts are limited to 256.";
}
return val;
}
void ShowSizes(const char *file, const lm::ngram::Config &config) {
std::vector<uint64_t> counts;
util::FilePiece f(file);
lm::ReadARPACounts(f, counts);
std::size_t sizes[5];
sizes[0] = ProbingModel::Size(counts, config);
sizes[1] = TrieModel::Size(counts, config);
sizes[2] = QuantTrieModel::Size(counts, config);
sizes[3] = ArrayTrieModel::Size(counts, config);
sizes[4] = QuantArrayTrieModel::Size(counts, config);
std::size_t max_length = *std::max_element(sizes, sizes + sizeof(sizes) / sizeof(size_t));
std::size_t min_length = *std::min_element(sizes, sizes + sizeof(sizes) / sizeof(size_t));
std::size_t divide;
char prefix;
if (min_length < (1 << 10) * 10) {
prefix = ' ';
divide = 1;
} else if (min_length < (1 << 20) * 10) {
prefix = 'k';
divide = 1 << 10;
} else if (min_length < (1ULL << 30) * 10) {
prefix = 'M';
divide = 1 << 20;
} else {
prefix = 'G';
divide = 1 << 30;
}
long int length = std::max<long int>(2, static_cast<long int>(ceil(log10((double) max_length / divide))));
std::cout << "Memory estimate:\ntype ";
// right align bytes.
for (long int i = 0; i < length - 2; ++i) std::cout << ' ';
std::cout << prefix << "B\n"
"probing " << std::setw(length) << (sizes[0] / divide) << " assuming -p " << config.probing_multiplier << "\n"
"trie " << std::setw(length) << (sizes[1] / divide) << " without quantization\n"
"trie " << std::setw(length) << (sizes[2] / divide) << " assuming -q " << (unsigned)config.prob_bits << " -b " << (unsigned)config.backoff_bits << " quantization \n"
"trie " << std::setw(length) << (sizes[3] / divide) << " assuming -a " << (unsigned)config.pointer_bhiksha_bits << " array pointer compression\n"
"trie " << std::setw(length) << (sizes[4] / divide) << " assuming -a " << (unsigned)config.pointer_bhiksha_bits << " -q " << (unsigned)config.prob_bits << " -b " << (unsigned)config.backoff_bits<< " array pointer compression and quantization\n";
}
void ProbingQuantizationUnsupported() {
std::cerr << "Quantization is only implemented in the trie data structure." << std::endl;
exit(1);
}
} // namespace ngram
} // namespace lm
} // namespace
int main(int argc, char *argv[]) {
using namespace lm::ngram;
try {
bool quantize = false, set_backoff_bits = false, bhiksha = false;
lm::ngram::Config config;
int opt;
while ((opt = getopt(argc, argv, "siu:p:t:m:q:b:a:")) != -1) {
switch(opt) {
case 'q':
config.prob_bits = ParseBitCount(optarg);
if (!set_backoff_bits) config.backoff_bits = config.prob_bits;
quantize = true;
break;
case 'b':
config.backoff_bits = ParseBitCount(optarg);
set_backoff_bits = true;
break;
case 'a':
config.pointer_bhiksha_bits = ParseBitCount(optarg);
bhiksha = true;
case 'u':
config.unknown_missing_logprob = ParseFloat(optarg);
break;
case 'p':
config.probing_multiplier = ParseFloat(optarg);
break;
case 't':
config.temporary_directory_prefix = optarg;
break;
case 'm':
config.building_memory = ParseUInt(optarg) * 1048576;
break;
case 's':
config.sentence_marker_missing = lm::SILENT;
break;
case 'i':
config.positive_log_probability = lm::SILENT;
break;
default:
Usage(argv[0]);
}
}
if (!quantize && set_backoff_bits) {
std::cerr << "You specified backoff quantization (-b) but not probability quantization (-q)" << std::endl;
abort();
}
if (optind + 1 == argc) {
ShowSizes(argv[optind], config);
} else if (optind + 2 == argc) {
config.write_mmap = argv[optind + 1];
if (quantize || set_backoff_bits) ProbingQuantizationUnsupported();
ProbingModel(argv[optind], config);
} else if (optind + 3 == argc) {
const char *model_type = argv[optind];
const char *from_file = argv[optind + 1];
config.write_mmap = argv[optind + 2];
if (!strcmp(model_type, "probing")) {
if (quantize || set_backoff_bits) ProbingQuantizationUnsupported();
ProbingModel(from_file, config);
} else if (!strcmp(model_type, "trie")) {
if (quantize) {
if (bhiksha) {
QuantArrayTrieModel(from_file, config);
} else {
QuantTrieModel(from_file, config);
}
} else {
if (bhiksha) {
ArrayTrieModel(from_file, config);
} else {
TrieModel(from_file, config);
}
}
} else {
Usage(argv[0]);
}
} else {
Usage(argv[0]);
}
}
catch (const std::exception &e) {
std::cerr << e.what() << std::endl;
std::cerr << "ERROR" << std::endl;
return 1;
}
std::cerr << "SUCCESS" << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>#include "../kontsevich_graph_series.hpp"
#include <ginac/ginac.h>
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
using namespace GiNaC;
int main(int argc, char* argv[])
{
if (argc != 3)
{
cout << "Usage: " << argv[0] << " <graph-series-filename> <expression>\n";
return 1;
}
// Reading in graph series:
string graph_series_filename(argv[1]);
ifstream graph_series_file(graph_series_filename);
parser coefficient_reader;
KontsevichGraphSeries<ex> graph_series = KontsevichGraphSeries<ex>::from_istream(graph_series_file, [&coefficient_reader](std::string s) -> ex { return coefficient_reader(s); });
ex expression = coefficient_reader(string(argv[2]));
for (size_t n = 0; n <= graph_series.precision(); ++n)
{
if (graph_series[n] != 0 || n == graph_series.precision())
cout << "h^" << n << ":\n";
for (auto& term : graph_series[n])
{
term.first = term.first.coeff(expression);
if (term.first != 0)
cout << term.second.encoding() << " " << term.first << "\n";
}
}
}
<commit_msg>Now `extract_coefficient <graph-series-filename> 1` extracts the constant part<commit_after>#include "../kontsevich_graph_series.hpp"
#include <ginac/ginac.h>
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
using namespace GiNaC;
int main(int argc, char* argv[])
{
if (argc != 3)
{
cout << "Usage: " << argv[0] << " <graph-series-filename> <expression>\n\n"
<< "If <expression>=1, the constant part is taken.\n";
return 1;
}
// Reading in graph series:
string graph_series_filename(argv[1]);
ifstream graph_series_file(graph_series_filename);
parser coefficient_reader;
KontsevichGraphSeries<ex> graph_series = KontsevichGraphSeries<ex>::from_istream(graph_series_file, [&coefficient_reader](std::string s) -> ex { return coefficient_reader(s); });
ex expression = coefficient_reader(string(argv[2]));
lst allzero_substitution;
if (expression == 1)
for (auto named_symbol : coefficient_reader.get_syms())
allzero_substitution.append(named_symbol.second==0);
for (size_t n = 0; n <= graph_series.precision(); ++n)
{
if (graph_series[n] != 0 || n == graph_series.precision())
cout << "h^" << n << ":\n";
for (auto& term : graph_series[n])
{
if (expression == 1)
term.first = term.first.subs(allzero_substitution);
else
term.first = term.first.coeff(expression);
if (term.first != 0)
cout << term.second.encoding() << " " << term.first << "\n";
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: xdictionary.hxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: rt $ $Date: 2007-07-26 09:07:48 $
*
* 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 _XDICTIONARY_H_
#define _XDICTIONARY_H_
#include <sal/types.h>
#include <osl/module.h>
#include <com/sun/star/i18n/Boundary.hpp>
namespace com { namespace sun { namespace star { namespace i18n {
#define CACHE_MAX 32 // max cache structure number
#define DEFAULT_SIZE 256 // for boundary size, to avoid alloc and release memory
// cache structure.
typedef struct _WrodBreakCache {
sal_Bool SAL_CALL equals(const sal_Unicode *str, Boundary& boundary); // checking cached string
sal_Int32 length; // contents length saved here.
sal_Unicode *contents; // seperated segment contents.
sal_Int32* wordboundary; // word boundaries in segments.
sal_Int32 size; // size of wordboundary
} WordBreakCache;
class xdictionary
{
private:
const sal_uInt8 * existMark;
const sal_Int16 * index1;
const sal_Int32 * index2;
const sal_Int32 * lenArray;
const sal_Unicode* dataArea;
oslModule hModule;
Boundary boundary;
sal_Bool useCellBoundary;
sal_Int32* cellBoundary;
sal_Bool japaneseWordBreak;
public:
xdictionary(const sal_Char *lang);
~xdictionary();
Boundary SAL_CALL nextWord( const rtl::OUString& rText, sal_Int32 nPos, sal_Int16 wordType);
Boundary SAL_CALL previousWord( const rtl::OUString& rText, sal_Int32 nPos, sal_Int16 wordType);
Boundary SAL_CALL getWordBoundary( const rtl::OUString& rText, sal_Int32 nPos, sal_Int16 wordType, sal_Bool bDirection );
void SAL_CALL setCellBoundary(sal_Int32* cellBondary);
void SAL_CALL setJapaneseWordBreak();
private:
WordBreakCache cache[CACHE_MAX];
sal_Bool SAL_CALL seekSegment(const sal_Unicode *text, sal_Int32 pos, sal_Int32 len, Boundary& boundary);
WordBreakCache& SAL_CALL getCache(const sal_Unicode *text, Boundary& boundary);
sal_Bool SAL_CALL exists(const sal_Unicode u);
sal_Int32 SAL_CALL getLongestMatch(const sal_Unicode *text, sal_Int32 len);
};
} } } }
#endif
<commit_msg>INTEGRATION: CWS changefileheader (1.6.68); FILE MERGED 2008/03/31 16:01:18 rt 1.6.68.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: xdictionary.hxx,v $
* $Revision: 1.7 $
*
* 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 _XDICTIONARY_H_
#define _XDICTIONARY_H_
#include <sal/types.h>
#include <osl/module.h>
#include <com/sun/star/i18n/Boundary.hpp>
namespace com { namespace sun { namespace star { namespace i18n {
#define CACHE_MAX 32 // max cache structure number
#define DEFAULT_SIZE 256 // for boundary size, to avoid alloc and release memory
// cache structure.
typedef struct _WrodBreakCache {
sal_Bool SAL_CALL equals(const sal_Unicode *str, Boundary& boundary); // checking cached string
sal_Int32 length; // contents length saved here.
sal_Unicode *contents; // seperated segment contents.
sal_Int32* wordboundary; // word boundaries in segments.
sal_Int32 size; // size of wordboundary
} WordBreakCache;
class xdictionary
{
private:
const sal_uInt8 * existMark;
const sal_Int16 * index1;
const sal_Int32 * index2;
const sal_Int32 * lenArray;
const sal_Unicode* dataArea;
oslModule hModule;
Boundary boundary;
sal_Bool useCellBoundary;
sal_Int32* cellBoundary;
sal_Bool japaneseWordBreak;
public:
xdictionary(const sal_Char *lang);
~xdictionary();
Boundary SAL_CALL nextWord( const rtl::OUString& rText, sal_Int32 nPos, sal_Int16 wordType);
Boundary SAL_CALL previousWord( const rtl::OUString& rText, sal_Int32 nPos, sal_Int16 wordType);
Boundary SAL_CALL getWordBoundary( const rtl::OUString& rText, sal_Int32 nPos, sal_Int16 wordType, sal_Bool bDirection );
void SAL_CALL setCellBoundary(sal_Int32* cellBondary);
void SAL_CALL setJapaneseWordBreak();
private:
WordBreakCache cache[CACHE_MAX];
sal_Bool SAL_CALL seekSegment(const sal_Unicode *text, sal_Int32 pos, sal_Int32 len, Boundary& boundary);
WordBreakCache& SAL_CALL getCache(const sal_Unicode *text, Boundary& boundary);
sal_Bool SAL_CALL exists(const sal_Unicode u);
sal_Int32 SAL_CALL getLongestMatch(const sal_Unicode *text, sal_Int32 len);
};
} } } }
#endif
<|endoftext|> |
<commit_before>//
// refract/ExpandVisitor.cc
// librefract
//
// Created by Jiri Kratochvil on 21/05/15.
// Copyright (c) 2015 Apiary Inc. All rights reserved.
//
#include "Element.h"
#include "Visitors.h"
#include "Registry.h"
#include <stack>
namespace refract
{
namespace
{
bool Expandable(const IElement& e)
{
IsExpandableVisitor v;
e.content(v);
return v.get();
}
IElement* ExpandOrClone(const IElement* e, const Registry& registry)
{
IElement* result = NULL;
if (!e) {
return result;
}
ExpandVisitor expander(registry);
e->content(expander);
result = expander.get();
if (!result) {
result = e->clone();
}
return result;
}
void CopyMetaId(IElement& dst, const IElement& src)
{
IElement::MemberElementCollection::const_iterator name = src.meta.find("id");
if (name != src.meta.end() && (*name)->value.second && !(*name)->value.second->empty()) {
dst.meta["id"] = (*name)->value.second->clone();
}
}
IElement* FindMemberByKey(const ObjectElement& e, const std::string& name)
{
for (ObjectElement::ValueType::const_iterator it = e.value.begin()
; it != e.value.end()
; ++it ) {
ComparableVisitor cmp(name, ComparableVisitor::key);
(*it)->content(cmp);
if (cmp.get()) { // key was recognized - it is save to cast to MemberElement
MemberElement* m = static_cast<MemberElement*>(*it);
return m->value.second;
}
}
return NULL;
}
typedef enum {
Inherited,
Referenced,
} NamedTypeExpansion;
template<typename T>
T* ExpandNamedType(const Registry& registry, const std::string& name, NamedTypeExpansion expansion)
{
std::string en = name;
T* e = NULL;
if (expansion == Inherited) {
e = new T;
}
// FIXME: add check against recursive inheritance
std::stack<IElement*> inheritance;
// walk recursive in registry and expand inheritance tree
for (const IElement* parent = registry.find(en)
; parent && !isReserved(en)
; en = parent->element(), parent = registry.find(en) ) {
inheritance.push(parent->clone((IElement::cAll ^ IElement::cElement) | IElement::cNoMetaId));
inheritance.top()->meta["ref"] = IElement::Create(en);
if (parent->element() == "enum") {
inheritance.top()->element("enum");
}
}
while (!inheritance.empty()) {
IElement* clone = inheritance.top();
if (e) {
e->push_back(clone);
}
else {
e = static_cast<T*>(clone);
}
inheritance.pop();
}
// FIXME: posible solution while referenced type is not found in regisry
// \see test/fixtures/mson-resource-unresolved-reference.apib
//
//if (e->value.empty()) {
// e->meta["ref"] = IElement::Create(name);
//}
if (T* expanded = TypeQueryVisitor::as<T>(ExpandOrClone(e, registry))) {
delete e;
return expanded;
}
return e;
}
template<typename T>
T* ExpandMembers(const T& e, const Registry& registry)
{
std::vector<IElement*> members;
for (typename T::ValueType::const_iterator it = e.value.begin() ; it != e.value.end() ; ++it) {
members.push_back(ExpandOrClone(*it, registry));
}
T* o = new T;
o->attributes.clone(e.attributes);
o->meta.clone(e.meta);
if (!members.empty()) {
o->set(members);
}
return o;
}
template<typename T>
T* CreateExtend(const IElement& e, const Registry& registry) {
typedef T ElementType;
ElementType* extend = ExpandNamedType<T>(registry, e.element(), Inherited);
extend->element("extend");
CopyMetaId(*extend, e);
ElementType* origin = ExpandMembers(static_cast<const ElementType&>(e), registry);
origin->meta.erase("id");
extend->push_back(origin);
return extend;
}
IElement* FindRootAncestor(const std::string& name, const Registry& registry)
{
IElement* parent = registry.find(name);
while (parent && !isReserved(parent->element())) {
IElement* next = registry.find(parent->element());
if (!next || (next == parent)) {
return parent;
}
parent = next;
}
return parent;
}
IElement* ExpandInheritance(const ObjectElement& e, const Registry& registry)
{
IElement* base = FindRootAncestor(e.element(), registry);
TypeQueryVisitor t;
if (base) {
base->content(t);
}
if (t.get() == TypeQueryVisitor::Array) {
return CreateExtend<ArrayElement>(e, registry);
}
else {
return CreateExtend<ObjectElement>(e, registry);
}
}
IElement* ExpandReference(const ObjectElement& e, const Registry& registry)
{
ObjectElement* ref = ExpandMembers(e, registry);
ref->element("ref");
ref->renderType(e.renderType());
StringElement* href = TypeQueryVisitor::as<StringElement>(FindMemberByKey(e, "href"));
if (!href || href->value.empty()) {
return ref;
}
IElement* referenced = registry.find(href->value);
if (!referenced) {
return ref;
}
TypeQueryVisitor t;
referenced->content(t);
IElement* resolved = NULL;
if (t.get() == TypeQueryVisitor::Array) {
resolved = ExpandNamedType<ArrayElement>(registry, href->value, Referenced);
}
else {
resolved = ExpandNamedType<ObjectElement>(registry, href->value, Referenced);
}
if (!resolved) {
return ref;
}
resolved->renderType(IElement::rFull);
ref->attributes["resolved"] = resolved;
return ref;
}
} // end of anonymous namespace
ExpandVisitor::ExpandVisitor(const Registry& registry) : result(NULL), registry(registry) {};
void ExpandVisitor::visit(const IElement& e) {
if (!Expandable(e)) {
return;
}
e.content(*this);
}
void ExpandVisitor::visit(const MemberElement& e) {
if (!Expandable(e)) {
return;
}
MemberElement* expanded = static_cast<MemberElement*>(e.clone(IElement::cAll ^ IElement::cValue));
expanded->set(ExpandOrClone(e.value.first, registry), ExpandOrClone(e.value.second, registry));
result = expanded;
}
void ExpandVisitor::visit(const ObjectElement& e) {
if (!Expandable(e)) { // do we have some expandable members?
return;
}
std::string en = e.element();
if (!isReserved(en)) { // expand named type
result = ExpandInheritance(e, registry);
}
else if (en == "ref") { // expand reference
result = ExpandReference(e, registry);
}
else { // walk throught members and expand them
result = ExpandMembers(e, registry);
}
}
// do nothing, primitive elements are not expandable
void ExpandVisitor::visit(const NullElement& e) {}
void ExpandVisitor::visit(const StringElement& e) {}
void ExpandVisitor::visit(const NumberElement& e) {}
void ExpandVisitor::visit(const BooleanElement& e) {}
void ExpandVisitor::visit(const ArrayElement& e) {
if (!Expandable(e)) { // do we have some expandable members?
return;
}
result = ExpandMembers(e, registry);
}
IElement* ExpandVisitor::get() const {
return result;
}
}; // namespace refract
<commit_msg>type - fixup<commit_after>//
// refract/ExpandVisitor.cc
// librefract
//
// Created by Jiri Kratochvil on 21/05/15.
// Copyright (c) 2015 Apiary Inc. All rights reserved.
//
#include "Element.h"
#include "Visitors.h"
#include "Registry.h"
#include <stack>
namespace refract
{
namespace
{
bool Expandable(const IElement& e)
{
IsExpandableVisitor v;
e.content(v);
return v.get();
}
IElement* ExpandOrClone(const IElement* e, const Registry& registry)
{
IElement* result = NULL;
if (!e) {
return result;
}
ExpandVisitor expander(registry);
e->content(expander);
result = expander.get();
if (!result) {
result = e->clone();
}
return result;
}
void CopyMetaId(IElement& dst, const IElement& src)
{
IElement::MemberElementCollection::const_iterator name = src.meta.find("id");
if (name != src.meta.end() && (*name)->value.second && !(*name)->value.second->empty()) {
dst.meta["id"] = (*name)->value.second->clone();
}
}
IElement* FindMemberByKey(const ObjectElement& e, const std::string& name)
{
for (ObjectElement::ValueType::const_iterator it = e.value.begin()
; it != e.value.end()
; ++it ) {
ComparableVisitor cmp(name, ComparableVisitor::key);
(*it)->content(cmp);
if (cmp.get()) { // key was recognized - it is save to cast to MemberElement
MemberElement* m = static_cast<MemberElement*>(*it);
return m->value.second;
}
}
return NULL;
}
typedef enum {
Inherited,
Referenced,
} NamedTypeExpansion;
template<typename T>
T* ExpandNamedType(const Registry& registry, const std::string& name, NamedTypeExpansion expansion)
{
std::string en = name;
T* e = NULL;
if (expansion == Inherited) {
e = new T;
}
// FIXME: add check against recursive inheritance
std::stack<IElement*> inheritance;
// walk recursive in registry and expand inheritance tree
for (const IElement* parent = registry.find(en)
; parent && !isReserved(en)
; en = parent->element(), parent = registry.find(en)) {
inheritance.push(parent->clone((IElement::cAll ^ IElement::cElement) | IElement::cNoMetaId));
inheritance.top()->meta["ref"] = IElement::Create(en);
if (parent->element() == "enum") {
inheritance.top()->element("enum");
}
}
while (!inheritance.empty()) {
IElement* clone = inheritance.top();
if (e) {
e->push_back(clone);
}
else {
e = static_cast<T*>(clone);
}
inheritance.pop();
}
// FIXME: posible solution while referenced type is not found in regisry
// \see test/fixtures/mson-resource-unresolved-reference.apib
//
//if (e->value.empty()) {
// e->meta["ref"] = IElement::Create(name);
//}
if (T* expanded = TypeQueryVisitor::as<T>(ExpandOrClone(e, registry))) {
delete e;
return expanded;
}
return e;
}
template<typename T>
T* ExpandMembers(const T& e, const Registry& registry)
{
std::vector<IElement*> members;
for (typename T::ValueType::const_iterator it = e.value.begin() ; it != e.value.end() ; ++it) {
members.push_back(ExpandOrClone(*it, registry));
}
T* o = new T;
o->attributes.clone(e.attributes);
o->meta.clone(e.meta);
if (!members.empty()) {
o->set(members);
}
return o;
}
template<typename T>
T* CreateExtend(const IElement& e, const Registry& registry) {
typedef T ElementType;
ElementType* extend = ExpandNamedType<T>(registry, e.element(), Inherited);
extend->element("extend");
CopyMetaId(*extend, e);
ElementType* origin = ExpandMembers(static_cast<const ElementType&>(e), registry);
origin->meta.erase("id");
extend->push_back(origin);
return extend;
}
IElement* FindRootAncestor(const std::string& name, const Registry& registry)
{
IElement* parent = registry.find(name);
while (parent && !isReserved(parent->element())) {
IElement* next = registry.find(parent->element());
if (!next || (next == parent)) {
return parent;
}
parent = next;
}
return parent;
}
IElement* ExpandInheritance(const ObjectElement& e, const Registry& registry)
{
IElement* base = FindRootAncestor(e.element(), registry);
TypeQueryVisitor t;
if (base) {
base->content(t);
}
if (t.get() == TypeQueryVisitor::Array) {
return CreateExtend<ArrayElement>(e, registry);
}
else {
return CreateExtend<ObjectElement>(e, registry);
}
}
IElement* ExpandReference(const ObjectElement& e, const Registry& registry)
{
ObjectElement* ref = ExpandMembers(e, registry);
ref->element("ref");
ref->renderType(e.renderType());
StringElement* href = TypeQueryVisitor::as<StringElement>(FindMemberByKey(e, "href"));
if (!href || href->value.empty()) {
return ref;
}
IElement* referenced = registry.find(href->value);
if (!referenced) {
return ref;
}
TypeQueryVisitor t;
referenced->content(t);
IElement* resolved = NULL;
if (t.get() == TypeQueryVisitor::Array) {
resolved = ExpandNamedType<ArrayElement>(registry, href->value, Referenced);
}
else {
resolved = ExpandNamedType<ObjectElement>(registry, href->value, Referenced);
}
if (!resolved) {
return ref;
}
resolved->renderType(IElement::rFull);
ref->attributes["resolved"] = resolved;
return ref;
}
} // end of anonymous namespace
ExpandVisitor::ExpandVisitor(const Registry& registry) : result(NULL), registry(registry) {};
void ExpandVisitor::visit(const IElement& e) {
if (!Expandable(e)) {
return;
}
e.content(*this);
}
void ExpandVisitor::visit(const MemberElement& e) {
if (!Expandable(e)) {
return;
}
MemberElement* expanded = static_cast<MemberElement*>(e.clone(IElement::cAll ^ IElement::cValue));
expanded->set(ExpandOrClone(e.value.first, registry), ExpandOrClone(e.value.second, registry));
result = expanded;
}
void ExpandVisitor::visit(const ObjectElement& e) {
if (!Expandable(e)) { // do we have some expandable members?
return;
}
std::string en = e.element();
if (!isReserved(en)) { // expand named type
result = ExpandInheritance(e, registry);
}
else if (en == "ref") { // expand reference
result = ExpandReference(e, registry);
}
else { // walk throught members and expand them
result = ExpandMembers(e, registry);
}
}
// do nothing, primitive elements are not expandable
void ExpandVisitor::visit(const NullElement& e) {}
void ExpandVisitor::visit(const StringElement& e) {}
void ExpandVisitor::visit(const NumberElement& e) {}
void ExpandVisitor::visit(const BooleanElement& e) {}
void ExpandVisitor::visit(const ArrayElement& e) {
if (!Expandable(e)) { // do we have some expandable members?
return;
}
result = ExpandMembers(e, registry);
}
IElement* ExpandVisitor::get() const {
return result;
}
}; // namespace refract
<|endoftext|> |
<commit_before>/*
* Copyright, Gambling Holdings Limited, All Rights Reserved.
*/
//System Includes
#include <regex>
#include <cstdio>
#include <vector>
#include <string>
#include <ciso646>
#include <cstdlib>
#include <iostream>
//Project Includes
#include "bet.hpp"
#include "race.hpp"
#include "product.hpp"
#include "settings.hpp"
#include "totalisator.hpp"
//External Includes
//System Namespaces
using std::cin;
using std::regex;
using std::vector;
using std::string;
using std::smatch;
using std::getline;
using std::regex_match;
using std::regex_constants::icase;
//Project Namespaces
using gambling::Bet;
using gambling::Race;
using gambling::WIN;
using gambling::PLACE;
using gambling::Product;
using gambling::Settings;
using gambling::Totalisator;
//External Namespaces
void display_results( const Race& race )
{
fprintf( stdout, "Win:%u:$%.2f\n", race.results.front( ), race.win_dividend );
for ( unsigned int index = 0; index < race.place_dividends.size( ); index++ )
{
fprintf( stdout, "Place:%u:$%.2f\n", race.results[ index ], race.place_dividends[ index ] );
}
}
Bet make_bet( const smatch& match )
{
Bet bet = { };
const auto product = match[ 1 ].str( );
bet.product = ( product == "w" or product == "W" ) ? WIN : PLACE;
bet.selection = stoi( match[ 2 ].str( ) );
bet.stake = stoi( match[ 3 ].str( ) );
return bet;
}
Race make_race( const smatch& match )
{
Race race = { };
race.results.push_back( 2 );
race.results.push_back( 3 );
race.results.push_back( 1 );
race.results.push_back( 4 );
return race;
}
int main( const int, const char** )
{
Race race = { };
vector< Bet > bets = { };
smatch match;
string line = "";
vector< string > tokens = { };
const auto bet_input_pattern = regex( "^Bet\\:(w|W|p|P)\\:(\\d+)\\:(\\d+)$", icase );
const auto result_input_pattern = regex( "^Result\\:(\\d+)\\:(\\d+)\\:(\\d+)$", icase );
while ( getline( cin, line ) )
{
const bool is_bet_input_line = regex_match( line, match, bet_input_pattern );
if ( is_bet_input_line )
{
bets.emplace_back( make_bet( match ) );
continue;
}
const bool is_result_input_line = regex_match( line, match, result_input_pattern );
if ( is_result_input_line )
{
race = make_race( match );
break;
}
fprintf( stderr, "The following input was malformed: %s\n", line.data( ) );
return EXIT_FAILURE;
}
auto totalisator = Totalisator::create( );
totalisator->run( race, bets );
display_results( race );
return EXIT_SUCCESS;
}
<commit_msg>Removed fixed race results.<commit_after>/*
* Copyright, Gambling Holdings Limited, All Rights Reserved.
*/
//System Includes
#include <regex>
#include <cstdio>
#include <vector>
#include <string>
#include <ciso646>
#include <cstdlib>
#include <iostream>
//Project Includes
#include "bet.hpp"
#include "race.hpp"
#include "product.hpp"
#include "settings.hpp"
#include "totalisator.hpp"
//External Includes
//System Namespaces
using std::cin;
using std::stoi;
using std::regex;
using std::vector;
using std::string;
using std::smatch;
using std::getline;
using std::regex_match;
using std::regex_constants::icase;
//Project Namespaces
using gambling::Bet;
using gambling::Race;
using gambling::WIN;
using gambling::PLACE;
using gambling::Product;
using gambling::Settings;
using gambling::Totalisator;
//External Namespaces
void display_results( const Race& race )
{
fprintf( stdout, "Win:%u:$%.2f\n", race.results.front( ), race.win_dividend );
for ( unsigned int index = 0; index < race.place_dividends.size( ); index++ )
{
fprintf( stdout, "Place:%u:$%.2f\n", race.results[ index ], race.place_dividends[ index ] );
}
}
Bet make_bet( const smatch& match )
{
Bet bet = { };
const auto product = match[ 1 ].str( );
bet.product = ( product == "w" or product == "W" ) ? WIN : PLACE;
bet.selection = stoi( match[ 2 ].str( ) );
bet.stake = stoi( match[ 3 ].str( ) );
return bet;
}
Race make_race( const smatch& match )
{
Race race = { };
race.results.push_back( stoi( match[ 1 ].str( ) ) );
race.results.push_back( stoi( match[ 2 ].str( ) ) );
race.results.push_back( stoi( match[ 3 ].str( ) ) );
return race;
}
int main( const int, const char** )
{
Race race = { };
vector< Bet > bets = { };
smatch match;
string line = "";
vector< string > tokens = { };
const auto bet_input_pattern = regex( "^Bet\\:(w|W|p|P)\\:(\\d+)\\:(\\d+)$", icase );
const auto result_input_pattern = regex( "^Result\\:(\\d+)\\:(\\d+)\\:(\\d+)$", icase );
while ( getline( cin, line ) )
{
const bool is_bet_input_line = regex_match( line, match, bet_input_pattern );
if ( is_bet_input_line )
{
bets.emplace_back( make_bet( match ) );
continue;
}
const bool is_result_input_line = regex_match( line, match, result_input_pattern );
if ( is_result_input_line )
{
race = make_race( match );
break;
}
fprintf( stderr, "The following input was malformed: %s\n", line.data( ) );
return EXIT_FAILURE;
}
auto totalisator = Totalisator::create( );
totalisator->run( race, bets );
display_results( race );
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <windows.h>
#include "types.h"
#include "renderer.cpp"
u8 CompressColorComponent(float component)
{
return u8(component * 255.0f);
}
LRESULT CALLBACK WindowProc(
HWND window,
UINT message,
WPARAM wParam,
LPARAM lParam)
{
switch (message)
{
case WM_CLOSE:
{
PostQuitMessage(0);
return 0;
} break;
}
return DefWindowProc(window, message, wParam, lParam);
}
int CALLBACK WinMain(
HINSTANCE instance,
HINSTANCE /* prevInstance */,
LPSTR /* cmdLine */,
int /* cmdShow */)
{
const int windowWidth = 640;
const int windowHeight = 480;
WNDCLASSEX wndClass {};
wndClass.cbSize = sizeof(wndClass);
wndClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wndClass.lpfnWndProc = WindowProc;
wndClass.hInstance = instance;
wndClass.lpszClassName = "Software Renderer Window Class Name";
RegisterClassEx(&wndClass);
HWND window = CreateWindowEx(
0,
wndClass.lpszClassName,
"Software Renderer",
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
CW_USEDEFAULT,
CW_USEDEFAULT,
windowWidth,
windowHeight,
0,
0,
instance,
nullptr
);
Bitmap renderBuffer(windowWidth, windowHeight);
HDC windowDC = GetDC(window);
HDC backBufferDC = CreateCompatibleDC(windowDC);
HBITMAP backBufferMemory = CreateCompatibleBitmap(backBufferDC, windowWidth, windowHeight);
SelectObject (backBufferDC, backBufferMemory);
MSG message {};
do
{
while (PeekMessage(&message, window, 0, 0, PM_REMOVE))
{
TranslateMessage(&message);
DispatchMessage(&message);
}
Render(renderBuffer);
for (int y = 0; y < renderBuffer.Height(); ++y)
{
for (int x = 0; x < renderBuffer.Width(); ++x)
{
Color& bufferColor = renderBuffer(x, y);
COLORREF windowColor = RGB(
CompressColorComponent(bufferColor.r),
CompressColorComponent(bufferColor.g),
CompressColorComponent(bufferColor.b));
SetPixelV(backBufferDC, x, y, windowColor);
}
}
BitBlt(windowDC, 0, 0, windowWidth, windowHeight, backBufferDC, 0, 0, SRCCOPY);
} while (message.message != WM_QUIT);
return 0;
}
<commit_msg>working blitting to window (quite fast also)<commit_after>#include <windows.h>
#include "types.h"
#include "renderer.cpp"
u8 CompressColorComponent(float component)
{
return u8(component * 255.0f);
}
LRESULT CALLBACK WindowProc(
HWND window,
UINT message,
WPARAM wParam,
LPARAM lParam)
{
switch (message)
{
case WM_CLOSE:
{
PostQuitMessage(0);
return 0;
} break;
}
return DefWindowProc(window, message, wParam, lParam);
}
int CALLBACK WinMain(
HINSTANCE instance,
HINSTANCE /* prevInstance */,
LPSTR /* cmdLine */,
int /* cmdShow */)
{
const int windowWidth = 640;
const int windowHeight = 480;
WNDCLASSEX wndClass {};
wndClass.cbSize = sizeof(wndClass);
wndClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;
wndClass.lpfnWndProc = WindowProc;
wndClass.hInstance = instance;
wndClass.lpszClassName = "Software Renderer Window Class Name";
RegisterClassEx(&wndClass);
HWND window = CreateWindowEx(
0,
wndClass.lpszClassName,
"Software Renderer",
WS_OVERLAPPEDWINDOW | WS_VISIBLE,
CW_USEDEFAULT,
CW_USEDEFAULT,
windowWidth,
windowHeight,
0,
0,
instance,
nullptr
);
BITMAPINFO backBufferInfo {};
backBufferInfo.bmiHeader.biSize = sizeof(backBufferInfo.bmiHeader);
backBufferInfo.bmiHeader.biWidth = windowWidth;
backBufferInfo.bmiHeader.biHeight = windowHeight;
backBufferInfo.bmiHeader.biPlanes = 1;
backBufferInfo.bmiHeader.biBitCount = 32;
backBufferInfo.bmiHeader.biCompression = BI_RGB;
u32* backBufferMemory = new u32[windowWidth * windowHeight];
Bitmap renderBuffer(windowWidth, windowHeight);
HDC windowDC = GetDC(window);
MSG message {};
do
{
while (PeekMessage(&message, window, 0, 0, PM_REMOVE))
{
TranslateMessage(&message);
DispatchMessage(&message);
}
Render(renderBuffer);
for (int y = 0; y < renderBuffer.Height(); ++y)
{
for (int x = 0; x < renderBuffer.Width(); ++x)
{
Color& bufferColor = renderBuffer(x, y);
backBufferMemory[y * windowWidth + x] =
CompressColorComponent(bufferColor.b) |
(CompressColorComponent(bufferColor.g) << 8) |
(CompressColorComponent(bufferColor.r) << 16);
}
}
StretchDIBits(
windowDC,
0,
0,
windowWidth,
windowHeight,
0,
0,
windowWidth,
windowHeight,
backBufferMemory,
&backBufferInfo,
DIB_RGB_COLORS,
SRCCOPY);
} while (message.message != WM_QUIT);
return 0;
}
<|endoftext|> |
<commit_before>#include <nds.h>
#include <stdio.h>
#include <fat.h>
#include <vector>
#include <string>
#include "patches.h"
#include "drunkenlogo.h"
unsigned int rawDataOffset=0;
u8 workbuffer[1024] ALIGN(32);
#define SCREEN_COLS 32
#define ITEMS_PER_SCREEN 10
#define ITEMS_START_ROW 12
#define MAX_DATNAME_LEN 26
using namespace std;
struct patchEntry {
string description;
u32 fileoffset;
};
//---------------------------------------------------------------------------------
void halt() {
//---------------------------------------------------------------------------------
int pressed;
iprintf(" Press A to exit\n");
while(1) {
swiWaitForVBlank();
scanKeys();
pressed = keysDown();
if (pressed & KEY_A) break;
}
exit(0);
}
//---------------------------------------------------------------------------------
void userSettingsCRC(void *buffer) {
//---------------------------------------------------------------------------------
u16 *slot = (u16*)buffer;
u16 CRC1 = swiCRC16(0xFFFF, slot, 0x70);
u16 CRC2 = swiCRC16(0xFFFF, &slot[0x3a], 0x8A);
slot[0x39] = CRC1; slot[0x7f] = CRC2;
}
/*
//---------------------------------------------------------------------------------
void saveFile(char *name, void *buffer, int size) {
//---------------------------------------------------------------------------------
FILE *out = fopen(name,"wb");
if (out) {
fwrite(buffer, 1, 1024, out);
fclose(out);
} else {
printf("couldn't open %s for writing\n",name);
}
}
*/
//---------------------------------------------------------------------------------
void showPatchList (const vector<patchEntry>& patchList, const char* datName, int offset) {
//---------------------------------------------------------------------------------
for (unsigned int i = 0; i < patchList.size() && i < ITEMS_PER_SCREEN; i++) {
const patchEntry* patch = &patchList.at(i);
// Set row
iprintf ("\x1b[%d;5H", i + ITEMS_START_ROW + offset);
iprintf ("%s", patch->description.c_str());
iprintf (datName);
}
}
void aread( void * ptr, size_t size, size_t count, int stream ){ // 'array read' drop in substitute for fread
size=0;
stream=0;
memcpy(ptr,&rawData[rawDataOffset],count);
rawDataOffset+=count;
}
int aseek( int stream, int offset, int origin ){ // 'array seek' drop in substitute for fseek
origin=0;
stream=0;
rawDataOffset=offset;
return 0;
}
int aeof(int stream){
stream=0;
int result=0;
if(rawDataOffset >= fSIZE)result=1;
return result;
}
int atell(int stream){
return rawDataOffset;
}
char * agets( char * str, int num, int stream ){
stream=0;
memcpy(str,&rawData[rawDataOffset],num);
return str;
}
//---------------------------------------------------------------------------------
int main(int argc, char **argv) {
//---------------------------------------------------------------------------------
videoSetMode(MODE_5_2D); //shamlessly ripped from the libnds examples :p
videoSetModeSub(MODE_0_2D);
vramSetBankA(VRAM_A_MAIN_BG);
bgInit(3, BgType_Bmp16, BgSize_B16_256x256, 0,0);
decompress(drunkenlogoBitmap, BG_GFX, LZ77Vram);
consoleDemoInit();
iprintf("\n\n\n\n\n\n");
iprintf(" >> Cakes ROP Installer << \n");
iprintf("\n\n");
int patchfile = 0;
int header;
rawDataOffset=0;
char datName[MAX_DATNAME_LEN]="YS:/" DATNAME;
char custom[6][35];
aread(&header,1,4,patchfile);
if ( header != 'ROPP') {
iprintf(" Invalid patch file!\n");
halt();
}
int index_offset;
aread(&index_offset,1,4,patchfile);
aseek(patchfile,index_offset,SEEK_SET);
vector<patchEntry> patches;
patchEntry patch;
while(1) {
patch.description.clear();
int string_offset;
aread(&string_offset,1,4,patchfile);
if (aeof(patchfile)) break;
aread(&patch.fileoffset,1,4,patchfile);
// save file pointer
int file_ptr = atell(patchfile);
aseek(patchfile,string_offset,SEEK_SET);
char description[21];
char *desc = agets(description, 20, patchfile);
if (desc == NULL ) {
iprintf(" Failed reading description\n");
halt();
}
// terminate string
description[20] = 0;
patch.description = description;
patches.push_back(patch);
// restore file pointer for next offset
aseek(patchfile,file_ptr,SEEK_SET);
}
int pressed,fwSelected=0,screenOffset=0;
// Default Cakes.dat + custom
int patch_count = patches.size() * 2;
showPatchList(patches, DISPNAME, 0);
showPatchList(patches, "ropCustom.txt", patches.size());
while(1) {
// Show cursor
iprintf ("\x1b[%d;3H[>\x1b[21C<]", fwSelected - screenOffset + ITEMS_START_ROW);
// Power saving loop. Only poll the keys once per frame and sleep the CPU if there is nothing else to do
do {
scanKeys();
pressed = keysDownRepeat();
swiWaitForVBlank();
} while (!pressed);
// Hide cursor
iprintf ("\x1b[%d;3H \x1b[21C ", fwSelected - screenOffset + ITEMS_START_ROW);
if (pressed & KEY_UP) fwSelected -= 1;
if (pressed & KEY_DOWN) fwSelected += 1;
if (pressed & KEY_A) break;
if (fwSelected < 0) fwSelected = patch_count - 1; // Wrap around to bottom of list
if (fwSelected > (patch_count - 1)) fwSelected = 0; // Wrap around to top of list
}
iprintf ("\x1b[5;0H\x1b[J");
const patchEntry *selectedPatch;
if (fwSelected < (int)patches.size()) {
selectedPatch = &patches.at(fwSelected);
} else {
selectedPatch = &patches.at(fwSelected - (patch_count - patches.size()));
}
iprintf("Patching for %s\n\n",selectedPatch->description.c_str());
// read header
readFirmware(0,workbuffer,42);
u32 userSettingsOffset = (workbuffer[32] + (workbuffer[33] << 8))<<3;
// read User Settings
readFirmware(userSettingsOffset,workbuffer,512);
aseek(patchfile,selectedPatch->fileoffset,SEEK_SET);
aread(&header,1,4,patchfile);
if (header != 'PTCH' ) {
printf(" Patch set invalid\n");
halt();
} else {
int32_t numPatches;
uint32_t patchSize,patchOffset;
aread(&numPatches,1,4,patchfile);
uint32_t patchOffsetList[numPatches];
aread(patchOffsetList,1,sizeof(patchOffsetList),patchfile);
for (int i=0; i<numPatches; i++) {
aseek(patchfile,patchOffsetList[i],SEEK_SET);
aread(&patchSize,1,4,patchfile);
aread(&patchOffset,1,4,patchfile);
aread(&workbuffer[patchOffset],1,patchSize,patchfile);
}
}
if (fwSelected < (int)patches.size()) {
for(int i = 0;i < MAX_DATNAME_LEN * 2;i += 2){
char c = datName[i / 2];
*(workbuffer + 0x11C + i) = c;
*(workbuffer + 0x11C + i + 1) = 0;
}
} else {
// Load filename from ropCustom.txt
int csSelected=0; //custom selected
int customLinesTotal=6;
int i=0;
char pathBegin[]="YS:/";
if(!fatInitDefault()){
iprintf(" fat init error\n");
halt();
}
FILE *text=fopen("ropCustom.txt","r");
if(!text){
iprintf(" ropCustom.txt load error\n Does it exist?\n\n");
halt();
}
for(i=0;i<customLinesTotal;i++){
fgets(custom[i],30,text);
if(!custom[i] || (custom[i][0] < 0x21) )break;
for(int j=0; j < 30 ;j++){ //strip newline junk
if(custom[i][j]==0x0D || custom[i][j]==0x0A)
custom[i][j]=0;
}
custom[i][25]=0; //make damn sure it terminates
}
if(i==0){
iprintf(" ropCustom.txt read error\n");
iprintf(" invalid first line path\n");
halt();
}
customLinesTotal=i;
fclose(text);
iprintf("\x1b[2J"); //clear console
iprintf("Custom filename list:");
for(i=0;i<customLinesTotal;i++){
iprintf ("\x1b[%d;3H", i + ITEMS_START_ROW -8);
iprintf ("%s", custom[i]);
}
while(1) {
// Show cursor
iprintf ("\x1b[%d;0H[>", csSelected - screenOffset + ITEMS_START_ROW -8);
// Power saving loop. Only poll the keys once per frame and sleep the CPU if there is nothing else to do
do {
scanKeys();
pressed = keysDownRepeat();
swiWaitForVBlank();
} while (!pressed);
// Hide cursor
iprintf ("\x1b[%d;0H ", csSelected - screenOffset + ITEMS_START_ROW -8);
if (pressed & KEY_UP) csSelected -= 1;
if (pressed & KEY_DOWN) csSelected += 1;
if (pressed & KEY_A) break;
if (csSelected < 0) csSelected = customLinesTotal - 1; // Wrap around to bottom of list
if (csSelected > (customLinesTotal - 1)) csSelected = 0; // Wrap around to top of list
}
for(int i = 0; i < 4 * 2 ;i += 2){
*(workbuffer + 0x11C + i) = pathBegin[i / 2];
*(workbuffer + 0x11C + i + 1) = 0;
}
for(int i = 0; i < (MAX_DATNAME_LEN - 4) * 2;i += 2){
*(workbuffer + 0x124 + i) = custom[csSelected][i / 2];
*(workbuffer + 0x124 + i + 1)=0;
}
*(workbuffer + 0x142)=0; //ensure terminated string (again)
*(workbuffer + 0x143)=0;
}
userSettingsCRC(workbuffer);
userSettingsCRC(workbuffer+256);
iprintf("\n\n\n\n\n Writing ... ");
int ret = writeFirmware(userSettingsOffset,workbuffer,512);
if (ret) {
iprintf("failed\n");
} else {
iprintf("success\n");
}
iprintf(" Verifying ... ");
readFirmware(userSettingsOffset,workbuffer+512,512);
if (memcmp(workbuffer,workbuffer+512,512)){
iprintf("failed\n");
} else {
iprintf("success\n");
}
halt();
return 0;
}
<commit_msg>Reverted codes<commit_after>#include <nds.h>
#include <stdio.h>
#include <fat.h>
#include <vector>
#include <string>
#include "patches.h"
#include "drunkenlogo.h"
unsigned int rawDataOffset=0;
u8 workbuffer[1024] ALIGN(32);
#define SCREEN_COLS 32
#define ITEMS_PER_SCREEN 10
#define ITEMS_START_ROW 12
#define MAX_DATNAME_LEN 26
using namespace std;
struct patchEntry {
string description;
u32 fileoffset;
};
//---------------------------------------------------------------------------------
void halt() {
//---------------------------------------------------------------------------------
int pressed;
iprintf(" Press A to exit\n");
while(1) {
swiWaitForVBlank();
scanKeys();
pressed = keysDown();
if (pressed & KEY_A) break;
}
exit(0);
}
//---------------------------------------------------------------------------------
void userSettingsCRC(void *buffer) {
//---------------------------------------------------------------------------------
u16 *slot = (u16*)buffer;
u16 CRC1 = swiCRC16(0xFFFF, slot, 0x70);
u16 CRC2 = swiCRC16(0xFFFF, &slot[0x3a], 0x8A);
slot[0x39] = CRC1; slot[0x7f] = CRC2;
}
/*
//---------------------------------------------------------------------------------
void saveFile(char *name, void *buffer, int size) {
//---------------------------------------------------------------------------------
FILE *out = fopen(name,"wb");
if (out) {
fwrite(buffer, 1, 1024, out);
fclose(out);
} else {
printf("couldn't open %s for writing\n",name);
}
}
*/
//---------------------------------------------------------------------------------
void showPatchList (const vector<patchEntry>& patchList, const char* datName, int offset) {
//---------------------------------------------------------------------------------
for (unsigned int i = 0; i < patchList.size() && i < ITEMS_PER_SCREEN; i++) {
const patchEntry* patch = &patchList.at(i);
// Set row
iprintf ("\x1b[%d;5H", i + ITEMS_START_ROW + offset);
iprintf ("%s", patch->description.c_str());
iprintf (datName);
}
}
void aread( void * ptr, size_t size, size_t count, int stream ){ // 'array read' drop in substitute for fread
size=0;
stream=0;
memcpy(ptr,&rawData[rawDataOffset],count);
rawDataOffset+=count;
}
int aseek( int stream, int offset, int origin ){ // 'array seek' drop in substitute for fseek
origin=0;
stream=0;
rawDataOffset=offset;
return 0;
}
int aeof(int stream){
stream=0;
int result=0;
if(rawDataOffset >= fSIZE)result=1;
return result;
}
int atell(int stream){
return rawDataOffset;
}
char * agets( char * str, int num, int stream ){
stream=0;
memcpy(str,&rawData[rawDataOffset],num);
return str;
}
//---------------------------------------------------------------------------------
int main(int argc, char **argv) {
//---------------------------------------------------------------------------------
videoSetMode(MODE_5_2D); //shamlessly ripped from the libnds examples :p
videoSetModeSub(MODE_0_2D);
vramSetBankA(VRAM_A_MAIN_BG);
bgInit(3, BgType_Bmp16, BgSize_B16_256x256, 0,0);
decompress(drunkenlogoBitmap, BG_GFX, LZ77Vram);
consoleDemoInit();
iprintf("\n\n\n\n\n\n");
iprintf(" >> Cakes ROP Installer << \n");
iprintf("\n\n");
int patchfile = 0;
int header;
rawDataOffset=0;
char datName[MAX_DATNAME_LEN]="YS:/" DATNAME;
char custom[6][35];
aread(&header,1,4,patchfile);
if ( header != 'ROPP') {
iprintf(" Invalid patch file!\n");
halt();
}
int index_offset;
aread(&index_offset,1,4,patchfile);
aseek(patchfile,index_offset,SEEK_SET);
vector<patchEntry> patches;
patchEntry patch;
while(1) {
patch.description.clear();
int string_offset;
aread(&string_offset,1,4,patchfile);
if (aeof(patchfile)) break;
aread(&patch.fileoffset,1,4,patchfile);
// save file pointer
int file_ptr = atell(patchfile);
aseek(patchfile,string_offset,SEEK_SET);
char description[21];
char *desc = agets(description, 20, patchfile);
if (desc == NULL ) {
iprintf(" Failed reading description\n");
halt();
}
// terminate string
description[20] = 0;
patch.description = description;
patches.push_back(patch);
// restore file pointer for next offset
aseek(patchfile,file_ptr,SEEK_SET);
}
int pressed,fwSelected=0,screenOffset=0;
// Default Cakes.dat + custom
int patch_count = patches.size() * 2;
showPatchList(patches, DISPNAME, 0);
showPatchList(patches, "ropCustom.txt", patches.size());
while(1) {
// Show cursor
iprintf ("\x1b[%d;3H[>\x1b[21C<]", fwSelected - screenOffset + ITEMS_START_ROW);
// Power saving loop. Only poll the keys once per frame and sleep the CPU if there is nothing else to do
do {
scanKeys();
pressed = keysDownRepeat();
swiWaitForVBlank();
} while (!pressed);
// Hide cursor
iprintf ("\x1b[%d;3H \x1b[21C ", fwSelected - screenOffset + ITEMS_START_ROW);
if (pressed & KEY_UP) fwSelected -= 1;
if (pressed & KEY_DOWN) fwSelected += 1;
if (pressed & KEY_A) break;
if (fwSelected < 0) fwSelected = patch_count - 1; // Wrap around to bottom of list
if (fwSelected > (patch_count - 1)) fwSelected = 0; // Wrap around to top of list
}
iprintf ("\x1b[5;0H\x1b[J");
const patchEntry *selectedPatch;
if (fwSelected < (int)patches.size()) {
selectedPatch = &patches.at(fwSelected);
} else {
selectedPatch = &patches.at(fwSelected - (patch_count - patches.size()));
}
iprintf("Patching for %s\n\n",selectedPatch->description.c_str());
// read header
readFirmware(0,workbuffer,42);
u32 userSettingsOffset = (workbuffer[32] + (workbuffer[33] << 8))<<3;
// read User Settings
readFirmware(userSettingsOffset,workbuffer,512);
aseek(patchfile,selectedPatch->fileoffset,SEEK_SET);
aread(&header,1,4,patchfile);
if (header != 'PTCH' ) {
printf(" Patch set invalid\n");
halt();
} else {
int32_t numPatches;
uint32_t patchSize,patchOffset;
aread(&numPatches,1,4,patchfile);
uint32_t patchOffsetList[numPatches];
aread(patchOffsetList,1,sizeof(patchOffsetList),patchfile);
for (int i=0; i<numPatches; i++) {
aseek(patchfile,patchOffsetList[i],SEEK_SET);
aread(&patchSize,1,4,patchfile);
aread(&patchOffset,1,4,patchfile);
aread(&workbuffer[patchOffset],1,patchSize,patchfile);
}
}
if (fwSelected < (int)patches.size()) {
for(int i = 0;i < MAX_DATNAME_LEN * 2;i += 2){
*(workbuffer + 0x11C + i) = datName[i / 2];
*(workbuffer + 0x11C + i + 1) = 0;
}
} else {
// Load filename from ropCustom.txt
int csSelected=0; //custom selected
int customLinesTotal=6;
int i=0;
char pathBegin[]="YS:/";
if(!fatInitDefault()){
iprintf(" fat init error\n");
halt();
}
FILE *text=fopen("ropCustom.txt","r");
if(!text){
iprintf(" ropCustom.txt load error\n Does it exist?\n\n");
halt();
}
for(i=0;i<customLinesTotal;i++){
fgets(custom[i],30,text);
if(!custom[i] || (custom[i][0] < 0x21) )break;
for(int j=0; j < 30 ;j++){ //strip newline junk
if(custom[i][j]==0x0D || custom[i][j]==0x0A)
custom[i][j]=0;
}
custom[i][25]=0; //make damn sure it terminates
}
if(i==0){
iprintf(" ropCustom.txt read error\n");
iprintf(" invalid first line path\n");
halt();
}
customLinesTotal=i;
fclose(text);
iprintf("\x1b[2J"); //clear console
iprintf("Custom filename list:");
for(i=0;i<customLinesTotal;i++){
iprintf ("\x1b[%d;3H", i + ITEMS_START_ROW -8);
iprintf ("%s", custom[i]);
}
while(1) {
// Show cursor
iprintf ("\x1b[%d;0H[>", csSelected - screenOffset + ITEMS_START_ROW -8);
// Power saving loop. Only poll the keys once per frame and sleep the CPU if there is nothing else to do
do {
scanKeys();
pressed = keysDownRepeat();
swiWaitForVBlank();
} while (!pressed);
// Hide cursor
iprintf ("\x1b[%d;0H ", csSelected - screenOffset + ITEMS_START_ROW -8);
if (pressed & KEY_UP) csSelected -= 1;
if (pressed & KEY_DOWN) csSelected += 1;
if (pressed & KEY_A) break;
if (csSelected < 0) csSelected = customLinesTotal - 1; // Wrap around to bottom of list
if (csSelected > (customLinesTotal - 1)) csSelected = 0; // Wrap around to top of list
}
for(int i = 0; i < 4 * 2 ;i += 2){
*(workbuffer + 0x11C + i) = pathBegin[i / 2];
*(workbuffer + 0x11C + i + 1) = 0;
}
for(int i = 0; i < (MAX_DATNAME_LEN - 4) * 2;i += 2){
*(workbuffer + 0x124 + i) = custom[csSelected][i / 2];
*(workbuffer + 0x124 + i + 1)=0;
}
*(workbuffer + 0x142)=0; //ensure terminated string (again)
*(workbuffer + 0x143)=0;
}
userSettingsCRC(workbuffer);
userSettingsCRC(workbuffer+256);
iprintf("\n\n\n\n\n Writing ... ");
int ret = writeFirmware(userSettingsOffset,workbuffer,512);
if (ret) {
iprintf("failed\n");
} else {
iprintf("success\n");
}
iprintf(" Verifying ... ");
readFirmware(userSettingsOffset,workbuffer+512,512);
if (memcmp(workbuffer,workbuffer+512,512)){
iprintf("failed\n");
} else {
iprintf("success\n");
}
halt();
return 0;
}
<|endoftext|> |
<commit_before>#include <CMDParser.hpp>
#include <FileBuffer.hpp>
#include <timevalue.hpp>
#include <clock.hpp>
#include <zmq.hpp>
#include <iostream>
#include <sstream>
namespace{
template <class T>
inline std::string
toString(T value){
std::ostringstream stream;
stream << value;
return stream.str();
}
}
int main(int argc, char* argv[]){
int start_loop = 0;
int end_loop = 0;
bool perform_loop = false;
bool swing = false;
unsigned num_kinect_cameras = 1;
bool rgb_is_compressed = false;
float max_fps = 20.0;
std::string socket_ip = "127.0.0.01";
unsigned base_socket_port = 7000;
CMDParser p("play_this_filename ...");
p.addOpt("k",1,"num_kinect_cameras", "specify how many kinect cameras are in stream, default: 1");
p.addOpt("f",1,"max_fps", "specify how fast in fps the stream should be played, default: 20.0");
p.addOpt("c",-1,"rgb_is_compressed", "enable compressed recording for rgb stream, default: false");
p.addOpt("s",1,"socket_ip", "specify ip address of socket for sending, default: " + socket_ip);
p.addOpt("p",1,"socket_port", "specify port of socket for sending, default: " + toString(base_socket_port));
p.addOpt("l",2,"loop", "specify a start and end frame for looping, default: " + toString(start_loop) + " " + toString(end_loop));
p.addOpt("w",-1,"swing", "enable swing looping mode, default: false");
p.init(argc,argv);
if(p.isOptSet("k")){
num_kinect_cameras = p.getOptsInt("k")[0];
}
if(p.isOptSet("f")){
max_fps = p.getOptsFloat("f")[0];
}
if(p.isOptSet("c")){
rgb_is_compressed = true;
}
if(p.isOptSet("s")){
socket_ip = p.getOptsString("s")[0];
}
if(p.isOptSet("p")){
base_socket_port = p.getOptsInt("p")[0];
}
if(p.isOptSet("l")){
start_loop = p.getOptsInt("l")[0];
end_loop = p.getOptsInt("l")[1];
if(start_loop > end_loop || start_loop < 0 || end_loop < 0){
std::cerr << "ERROR: -l option must be both positive and second parameter must be greater than first!" << std::endl;
p.showHelp();
}
perform_loop = true;
}
if(p.isOptSet("w")){
swing = true;
}
unsigned min_frame_time_ns = 1000000000/max_fps;
const unsigned colorsize = rgb_is_compressed ? 691200 : 1280 * 1080 * 3;
const unsigned depthsize = 512 * 424 * sizeof(float);
const size_t frame_size_bytes((colorsize + depthsize) * num_kinect_cameras);
zmq::context_t ctx(1); // means single threaded
const unsigned num_streams = p.getArgs().size();
std::cout << "going to stream " << num_streams << " to socket ip " << socket_ip << " starting at port number " << base_socket_port << std::endl;
std::vector<FileBuffer*> fbs;
std::vector<zmq::socket_t* > sockets;
std::vector<int> frame_numbers;
for(unsigned s_num = 0; s_num < num_streams; ++s_num){
FileBuffer* fb = new FileBuffer(p.getArgs()[s_num].c_str());
if(!fb->open("r")){
std::cerr << "error opening " << p.getArgs()[s_num] << " exiting..." << std::endl;
return 1;
}
else{
const unsigned n_fs = fb->getFileSizeBytes()/frame_size_bytes;
std::cout << p.getArgs()[s_num] << " contains " << n_fs << " frames..." << std::endl;
if(perform_loop && end_loop > 0 && end_loop > n_fs){
end_loop = n_fs;
start_loop = std::min(end_loop, start_loop);
std::cout << "INFO: setting start loop to " << start_loop << " and end loop to " << end_loop << std::endl;
}
}
fb->setLooping(true);
fbs.push_back(fb);
frame_numbers.push_back(0);
zmq::socket_t* socket = new zmq::socket_t(ctx, ZMQ_PUB); // means a publisher
uint32_t hwm = 1;
socket->setsockopt(ZMQ_SNDHWM,&hwm, sizeof(hwm));
std::string endpoint("tcp://" + socket_ip + ":" + toString(base_socket_port + s_num));
socket->bind(endpoint.c_str());
std::cout << "binding socket to " << endpoint << std::endl;
sockets.push_back(socket);
}
bool fwd = true;
sensor::timevalue ts(sensor::clock::time());
while(true){
for(unsigned s_num = 0; s_num < num_streams; ++s_num){
if(perform_loop){
frame_numbers[s_num] = fwd ? frame_numbers[s_num] + 1 : frame_numbers[s_num] - 1;
if(frame_numbers[s_num] < start_loop){
frame_numbers[s_num] = start_loop + 1;
if(swing){
fwd = true;
}
}
else if(frame_numbers[s_num] > end_loop){
if(swing){
fwd = false;
frame_numbers[s_num] = end_loop - 1;
}
else{
frame_numbers[s_num] = start_loop;
}
}
std::cout << "s_num: " << s_num << " -> frame_number: " << frame_numbers[s_num] << std::endl;
fbs[s_num]->gotoByte(frame_size_bytes * frame_numbers[s_num]);
}
zmq::message_t zmqm(frame_size_bytes);
fbs[s_num]->read((unsigned char*) zmqm.data(), frame_size_bytes);
// send frames
sockets[s_num]->send(zmqm);
}
// check if fps is correct
sensor::timevalue ts_now = sensor::clock::time();
long long time_spent_ns = (ts_now - ts).nsec();
long long rest_sleep_ns = min_frame_time_ns - time_spent_ns;
ts = ts_now;
if(0 < rest_sleep_ns){
sensor::timevalue rest_sleep(0,rest_sleep_ns);
nanosleep(rest_sleep);
}
}
// cleanup
for(unsigned s_num = 0; s_num < num_streams; ++s_num){
delete fbs[s_num];
delete sockets[s_num];
}
return 0;
}
<commit_msg>added num loops<commit_after>#include <CMDParser.hpp>
#include <FileBuffer.hpp>
#include <timevalue.hpp>
#include <clock.hpp>
#include <zmq.hpp>
#include <iostream>
#include <sstream>
namespace{
template <class T>
inline std::string
toString(T value){
std::ostringstream stream;
stream << value;
return stream.str();
}
}
int main(int argc, char* argv[]){
int start_loop = 0;
int end_loop = 0;
int num_loops = 0;
bool perform_loop = false;
bool swing = false;
unsigned num_kinect_cameras = 1;
bool rgb_is_compressed = false;
float max_fps = 20.0;
std::string socket_ip = "127.0.0.01";
unsigned base_socket_port = 7000;
CMDParser p("play_this_filename ...");
p.addOpt("k",1,"num_kinect_cameras", "specify how many kinect cameras are in stream, default: 1");
p.addOpt("f",1,"max_fps", "specify how fast in fps the stream should be played, default: 20.0");
p.addOpt("c",-1,"rgb_is_compressed", "enable compressed recording for rgb stream, default: false");
p.addOpt("s",1,"socket_ip", "specify ip address of socket for sending, default: " + socket_ip);
p.addOpt("p",1,"socket_port", "specify port of socket for sending, default: " + toString(base_socket_port));
p.addOpt("l",2,"loop", "specify a start and end frame for looping, default: " + toString(start_loop) + " " + toString(end_loop));
p.addOpt("w",-1,"swing", "enable swing looping mode, default: false");
p.addOpt("n",1,"num_loops", "loop n time, default: loop forever");
p.init(argc,argv);
if(p.isOptSet("k")){
num_kinect_cameras = p.getOptsInt("k")[0];
}
if(p.isOptSet("f")){
max_fps = p.getOptsFloat("f")[0];
}
if(p.isOptSet("c")){
rgb_is_compressed = true;
}
if(p.isOptSet("s")){
socket_ip = p.getOptsString("s")[0];
}
if(p.isOptSet("p")){
base_socket_port = p.getOptsInt("p")[0];
}
if(p.isOptSet("l")){
start_loop = p.getOptsInt("l")[0];
end_loop = p.getOptsInt("l")[1];
if(start_loop > end_loop || start_loop < 0 || end_loop < 0){
std::cerr << "ERROR: -l option must be both positive and second parameter must be greater than first!" << std::endl;
p.showHelp();
}
perform_loop = true;
}
if(p.isOptSet("w")){
swing = true;
}
if(p.isOptSet("n")){
num_loops = p.getOptsInt("n")[0];
}
unsigned min_frame_time_ns = 1000000000/max_fps;
const unsigned colorsize = rgb_is_compressed ? 691200 : 1280 * 1080 * 3;
const unsigned depthsize = 512 * 424 * sizeof(float);
const size_t frame_size_bytes((colorsize + depthsize) * num_kinect_cameras);
zmq::context_t ctx(1); // means single threaded
const unsigned num_streams = p.getArgs().size();
std::cout << "going to stream " << num_streams << " to socket ip " << socket_ip << " starting at port number " << base_socket_port << std::endl;
std::vector<FileBuffer*> fbs;
std::vector<zmq::socket_t* > sockets;
std::vector<int> frame_numbers;
for(unsigned s_num = 0; s_num < num_streams; ++s_num){
FileBuffer* fb = new FileBuffer(p.getArgs()[s_num].c_str());
if(!fb->open("r")){
std::cerr << "error opening " << p.getArgs()[s_num] << " exiting..." << std::endl;
return 1;
}
else{
const unsigned n_fs = fb->getFileSizeBytes()/frame_size_bytes;
std::cout << p.getArgs()[s_num] << " contains " << n_fs << " frames..." << std::endl;
if(perform_loop && end_loop > 0 && end_loop > n_fs){
end_loop = n_fs;
start_loop = std::min(end_loop, start_loop);
std::cout << "INFO: setting start loop to " << start_loop << " and end loop to " << end_loop << std::endl;
}
}
fb->setLooping(true);
fbs.push_back(fb);
frame_numbers.push_back(0);
zmq::socket_t* socket = new zmq::socket_t(ctx, ZMQ_PUB); // means a publisher
uint32_t hwm = 1;
socket->setsockopt(ZMQ_SNDHWM,&hwm, sizeof(hwm));
std::string endpoint("tcp://" + socket_ip + ":" + toString(base_socket_port + s_num));
socket->bind(endpoint.c_str());
std::cout << "binding socket to " << endpoint << std::endl;
sockets.push_back(socket);
}
bool fwd = true;
int loop_num = 1;
sensor::timevalue ts(sensor::clock::time());
while(true){
if(loop_num > num_loops && num_loops > 0){
break;
}
for(unsigned s_num = 0; s_num < num_streams; ++s_num){
if(perform_loop){
frame_numbers[s_num] = fwd ? frame_numbers[s_num] + 1 : frame_numbers[s_num] - 1;
if(frame_numbers[s_num] < start_loop){
frame_numbers[s_num] = start_loop + 1;
if(swing){
fwd = true;
}
if(s_num == 0){
++loop_num;
}
}
else if(frame_numbers[s_num] > end_loop){
if(swing){
fwd = false;
frame_numbers[s_num] = end_loop - 1;
}
else{
frame_numbers[s_num] = start_loop;
}
}
std::cout << "s_num: " << s_num << " -> frame_number: " << frame_numbers[s_num] << std::endl;
fbs[s_num]->gotoByte(frame_size_bytes * frame_numbers[s_num]);
}
zmq::message_t zmqm(frame_size_bytes);
fbs[s_num]->read((unsigned char*) zmqm.data(), frame_size_bytes);
// send frames
sockets[s_num]->send(zmqm);
}
// check if fps is correct
sensor::timevalue ts_now = sensor::clock::time();
long long time_spent_ns = (ts_now - ts).nsec();
long long rest_sleep_ns = min_frame_time_ns - time_spent_ns;
ts = ts_now;
if(0 < rest_sleep_ns){
sensor::timevalue rest_sleep(0,rest_sleep_ns);
nanosleep(rest_sleep);
}
}
// cleanup
for(unsigned s_num = 0; s_num < num_streams; ++s_num){
delete fbs[s_num];
delete sockets[s_num];
}
return 0;
}
<|endoftext|> |
<commit_before>#include "../inc/mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
userdata(UserData::GetInstance())
{
ui->setupUi(this);
createUi();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::createUi() {
// icon resources
const QPixmap *plus_pixmap = new QPixmap(":/res/plus-48.png");
QIcon *plus_icon = new QIcon(*plus_pixmap);
const QPixmap *minus_pixmap = new QPixmap(":/res/minus-48.png");
QIcon *minus_icon = new QIcon(*minus_pixmap);
// create toolbar
QToolBar *fileToolBar = addToolBar("File");
// create actions
const QPixmap *new_pixmap = new QPixmap(":/res/create_new-48.png");
QIcon *new_icon = new QIcon(*new_pixmap);
QAction *newDocument = new QAction(*new_icon, "New document", this);
connect(newDocument, &QAction::triggered, this, &MainWindow::createNewUser);
const QPixmap *open_pixmap = new QPixmap(":/res/opened_folder-48.png");
QIcon *open_icon = new QIcon(*open_pixmap);
QAction *openDocument = new QAction(*open_icon, "Open document", this);
connect(openDocument, &QAction::triggered, this, &MainWindow::open);
const QPixmap *save_pixmap = new QPixmap(":/res/save-48.png");
QIcon *save_icon = new QIcon(*save_pixmap);
QAction *saveDocument = new QAction(*save_icon, "Save document", this);
const QPixmap *save_as_pixmap = new QPixmap(":/res/save_as-48.png");
QIcon *save_as_icon = new QIcon(*save_as_pixmap);
QAction *saveAsDocument = new QAction(*save_as_icon, "Save document as", this);
connect(saveAsDocument, &QAction::triggered, this, &MainWindow::saveAs);
QList<QAction*> *actions = new QList<QAction*>();
actions->append(newDocument);
actions->append(openDocument);
actions->append(saveDocument);
actions->append(saveAsDocument);
fileToolBar->addActions(*actions);
// create mainwindow layout
mainLayout = new QGridLayout;
// create column with list of users
QPushButton *addUser = new QPushButton(*plus_icon, "Add user", this);
connect(addUser, &QPushButton::clicked, this, &MainWindow::createNewUser);
removeUser = new QPushButton(*minus_icon, "Remove user", this);
connect(removeUser, &QPushButton::clicked, this, &MainWindow::removeSelectedUserEntry);
removeUser->setEnabled(false);
userColumn = new QListView;
userColumnModel = new QStringListModel;
QFont* columnFont = new QFont;
columnFont->setPointSize(14);
userColumn->setEditTriggers(QAbstractItemView::NoEditTriggers);
userColumn->setModel(userColumnModel);
userColumn->setFont(*columnFont);
connect(userdata, &UserData::userAdded, this, &MainWindow::addUserEntry);
connect(userColumn->selectionModel(), &QItemSelectionModel::selectionChanged, this, &MainWindow::userSelected);
// create password entry column
QPushButton *addPassword = new QPushButton(*plus_icon, "Add password entry", this);
connect(addPassword, &QPushButton::clicked, this, &MainWindow::createNewPassword);
removePassword = new QPushButton(*minus_icon, "Remove password entry", this);
connect(removePassword, &QPushButton::clicked, this, &MainWindow::removeSelectedPasswordEntry);
removePassword->setEnabled(false);
passwordColumn = new QListView;
passwordColumnModel= new QStringListModel;
passwordColumn->setEditTriggers(QAbstractItemView::NoEditTriggers);
passwordColumn->setModel(passwordColumnModel);
passwordColumn->setFont(*columnFont);
connect(userdata, &UserData::passwordEntryAdded, this, &MainWindow::addPasswordEntry);
// create details panel
serviceName = new QLabel;
username = new QLabel;
password = new QLabel;
notes = new QLabel;
connect(passwordColumn->selectionModel(), &QItemSelectionModel::selectionChanged, this, &MainWindow::passwordEntrySelected);
QGridLayout* userColumnLayout = new QGridLayout;
userColumnLayout->addWidget(addUser, 0, 0);
userColumnLayout->addWidget(removeUser, 0, 1);
userColumnLayout->addWidget(userColumn, 1, 0, 1, 0);
QGridLayout* passwordColumnLayout = new QGridLayout;
passwordColumnLayout->addWidget(addPassword, 0, 0);
passwordColumnLayout->addWidget(removePassword, 0, 1);
passwordColumnLayout->addWidget(passwordColumn, 1, 0, 1, 0);
QFormLayout* detailsLayout = new QFormLayout;
detailsLayout->addRow(tr("Service name:"), serviceName);
detailsLayout->addRow(tr("Username:"), username);
detailsLayout->addRow(tr("Password:"), password);
detailsLayout->addRow(tr("Notes:"), notes);
QWidget* userSection = new QWidget;
userSection->setLayout(userColumnLayout);
QWidget* passwordSection = new QWidget;
passwordSection->setLayout(passwordColumnLayout);
QWidget* detailsSection = new QWidget;
detailsSection->setLayout(detailsLayout);
int buttonHeight = addUser->height();
detailsSection->setContentsMargins(0, buttonHeight + 4, 0, 0);
QSplitter* mainSplitter = new QSplitter;
mainSplitter->addWidget(userSection);
mainSplitter->addWidget(passwordSection);
mainSplitter->addWidget(detailsSection);
mainLayout->addWidget(mainSplitter);
ui->centralWidget->setLayout(mainLayout);
}
void MainWindow::open() {
int rval;
QString filePath = QFileDialog::getOpenFileName(this);
if (!filePath.isEmpty()) {
rval = userdata->ParseUserFile(filePath);
if (rval != 0) {
QMessageBox *invalidFileMsgBox = new QMessageBox(this);
invalidFileMsgBox->setText("Unable to open file \"" + filePath + "\".");
invalidFileMsgBox->setIcon(QMessageBox::Critical);
invalidFileMsgBox->exec();
}
}
}
void MainWindow::saveAs() {
QString filePath = QFileDialog::getSaveFileName(this, tr("Save File As"),
Q_NULLPTR,
tr("Karabiner Account File (*.kbr)"));
if (!filePath.isEmpty()) {
userdata->SaveUserFile(filePath);
}
}
void MainWindow::createNewUser() {
NewUserDialog *dialog = new NewUserDialog(this);
dialog->exec();
}
void MainWindow::createNewPassword() {
NewPasswordDialog *dialog = new NewPasswordDialog(this);
dialog->exec();
}
void MainWindow::addUserEntry(QString usernameToAdd) {
int lastRow = userColumnModel->rowCount();
userColumnModel->insertRow(lastRow);
QModelIndex lastRowModelIndex = userColumnModel->index(lastRow);
userColumnModel->setData(lastRowModelIndex, usernameToAdd, Qt::DisplayRole);
userColumn->selectionModel()->select(lastRowModelIndex, QItemSelectionModel::ClearAndSelect);
}
void MainWindow::removeSelectedUserEntry() {
QList<QModelIndex> selectedRowIndexes = userColumn->selectionModel()->selectedRows();
QModelIndex selectedRowModelIndex = selectedRowIndexes.first();
QString usernameString = selectedRowModelIndex.data().toString();
userdata->DeleteUser(usernameString);
int selectedRow = selectedRowModelIndex.row();
userColumnModel->removeRow(selectedRow);
userColumn->selectionModel()->clear();
}
void MainWindow::userSelected(const QItemSelection &selectedUserItem, const QItemSelection &deselectedUserItem) {
QList<QModelIndex> selectedUserIndexes = selectedUserItem.indexes();
QList<QModelIndex> deselectedUserIndexes = deselectedUserItem.indexes();
if (selectedUserIndexes.size() == 0) {
removeUser->setEnabled(false);
return;
}
removeUser->setEnabled(true);
int selectedRow = selectedUserIndexes[0].row();
QString selectedUsername = userColumnModel->stringList()[selectedRow];
User* selectedUser = userdata->GetUser(selectedUsername);
// authenticate user if encrypted
if (!selectedUser->isDecrypted()) {
bool authenticated = 0;
while (!authenticated) {
bool accepted;
QString password = QInputDialog::getText(this, "Authentication", "Password:",
QLineEdit::Password, "", &accepted);
// if user presses cancel on the dialog
if (!accepted) {
if (deselectedUserIndexes.size() == 0) {
// clear selection if nothing was previously selected
userColumn->selectionModel()->clearSelection();
} else {
// select previously selected row
userColumn->selectionModel()->select(deselectedUserIndexes[0], QItemSelectionModel::ClearAndSelect);
}
return;
}
authenticated = selectedUser->Authenticate(password, User::Decrypt);
}
}
refreshPasswordEntries();
}
void MainWindow::addPasswordEntry(QString newServiceName) {
int lastRow = passwordColumnModel->rowCount();
passwordColumnModel->insertRow(lastRow);
QModelIndex lastRowModelIndex = passwordColumnModel->index(lastRow);
passwordColumnModel->setData(lastRowModelIndex, newServiceName, Qt::DisplayRole);
passwordColumn->selectionModel()->select(lastRowModelIndex, QItemSelectionModel::ClearAndSelect);
}
void MainWindow::removeSelectedPasswordEntry() {
QList<QModelIndex> selectedRowIndexes = passwordColumn->selectionModel()->selectedRows();
QModelIndex selectedRowModelIndex = selectedRowIndexes.first();
QString serviceName = selectedRowModelIndex.data().toString();
userdata->DeleteUser(serviceName);
int selectedRow = selectedRowModelIndex.row();
passwordColumnModel->removeRow(selectedRow);
passwordColumn->selectionModel()->clear();
}
void MainWindow::passwordEntrySelected(const QItemSelection &selectedPasswordItem, const QItemSelection &deselectedPasswordItem) {
QList<QModelIndex> selectedPasswordIndexes = selectedPasswordItem.indexes();
QList<QModelIndex> deselectedPasswordIndexes = deselectedPasswordItem.indexes();
if (selectedPasswordIndexes.length() != 0) {
removePassword->setEnabled(true);
} else {
removePassword->setEnabled(false);
}
refreshDetailsPane();
}
void MainWindow::refreshPasswordEntries() {
int numRows = passwordColumnModel->rowCount();
passwordColumnModel->removeRows(0, numRows);
// find the selected row
QList<QModelIndex> selectedRowIndexes = userColumn->selectionModel()->selectedRows();
if (selectedRowIndexes.size() == 0) {
return;
}
int selectedRow = selectedRowIndexes.first().row();
QString selectedUsername = userColumnModel->stringList()[selectedRow];
User* selectedUser = userdata->GetUser(selectedUsername);
int numPasswordEntries = selectedUser->password_entries.length();
passwordColumnModel->insertRows(0, numPasswordEntries);
int i;
QModelIndex curRowModelIndex;
for (i = 0; i < numPasswordEntries; i++) {
curRowModelIndex = passwordColumnModel->index(i);
passwordColumnModel->setData(curRowModelIndex, selectedUser->password_entries[i].service_name, Qt::DisplayRole);
}
}
void MainWindow::refreshDetailsPane() {
// find the selected user
QList<QModelIndex> selectedRowIndexes = userColumn->selectionModel()->selectedRows();
if (selectedRowIndexes.size() == 0) {
clearDetailsPane();
return;
}
int selectedRow = selectedRowIndexes[0].row();
QString selectedUsername = userColumnModel->stringList()[selectedRow];
User* selectedUser = userdata->GetUser(selectedUsername);
// find the selected password entry
selectedRowIndexes = passwordColumn->selectionModel()->selectedRows();
if (selectedRowIndexes.size() == 0) {
clearDetailsPane();
return;
}
selectedRow = selectedRowIndexes[0].row();
PwEntry selectedPwEntry = selectedUser->password_entries[selectedRow];
serviceName->setText(selectedPwEntry.service_name);
username->setText(selectedPwEntry.username);
password->setText(selectedPwEntry.password);
notes->setText(selectedPwEntry.notes);
}
void MainWindow::clearDetailsPane() {
serviceName->setText("");
username->setText("");
password->setText("");
notes->setText("");
}
<commit_msg>Removes previous user entries from the view when opening a new user file<commit_after>#include "../inc/mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
userdata(UserData::GetInstance())
{
ui->setupUi(this);
createUi();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::createUi() {
// icon resources
const QPixmap *plus_pixmap = new QPixmap(":/res/plus-48.png");
QIcon *plus_icon = new QIcon(*plus_pixmap);
const QPixmap *minus_pixmap = new QPixmap(":/res/minus-48.png");
QIcon *minus_icon = new QIcon(*minus_pixmap);
// create toolbar
QToolBar *fileToolBar = addToolBar("File");
// create actions
const QPixmap *new_pixmap = new QPixmap(":/res/create_new-48.png");
QIcon *new_icon = new QIcon(*new_pixmap);
QAction *newDocument = new QAction(*new_icon, "New document", this);
connect(newDocument, &QAction::triggered, this, &MainWindow::createNewUser);
const QPixmap *open_pixmap = new QPixmap(":/res/opened_folder-48.png");
QIcon *open_icon = new QIcon(*open_pixmap);
QAction *openDocument = new QAction(*open_icon, "Open document", this);
connect(openDocument, &QAction::triggered, this, &MainWindow::open);
const QPixmap *save_pixmap = new QPixmap(":/res/save-48.png");
QIcon *save_icon = new QIcon(*save_pixmap);
QAction *saveDocument = new QAction(*save_icon, "Save document", this);
const QPixmap *save_as_pixmap = new QPixmap(":/res/save_as-48.png");
QIcon *save_as_icon = new QIcon(*save_as_pixmap);
QAction *saveAsDocument = new QAction(*save_as_icon, "Save document as", this);
connect(saveAsDocument, &QAction::triggered, this, &MainWindow::saveAs);
QList<QAction*> *actions = new QList<QAction*>();
actions->append(newDocument);
actions->append(openDocument);
actions->append(saveDocument);
actions->append(saveAsDocument);
fileToolBar->addActions(*actions);
// create mainwindow layout
mainLayout = new QGridLayout;
// create column with list of users
QPushButton *addUser = new QPushButton(*plus_icon, "Add user", this);
connect(addUser, &QPushButton::clicked, this, &MainWindow::createNewUser);
removeUser = new QPushButton(*minus_icon, "Remove user", this);
connect(removeUser, &QPushButton::clicked, this, &MainWindow::removeSelectedUserEntry);
removeUser->setEnabled(false);
userColumn = new QListView;
userColumnModel = new QStringListModel;
QFont* columnFont = new QFont;
columnFont->setPointSize(14);
userColumn->setEditTriggers(QAbstractItemView::NoEditTriggers);
userColumn->setModel(userColumnModel);
userColumn->setFont(*columnFont);
connect(userdata, &UserData::userAdded, this, &MainWindow::addUserEntry);
connect(userColumn->selectionModel(), &QItemSelectionModel::selectionChanged, this, &MainWindow::userSelected);
// create password entry column
QPushButton *addPassword = new QPushButton(*plus_icon, "Add password entry", this);
connect(addPassword, &QPushButton::clicked, this, &MainWindow::createNewPassword);
removePassword = new QPushButton(*minus_icon, "Remove password entry", this);
connect(removePassword, &QPushButton::clicked, this, &MainWindow::removeSelectedPasswordEntry);
removePassword->setEnabled(false);
passwordColumn = new QListView;
passwordColumnModel= new QStringListModel;
passwordColumn->setEditTriggers(QAbstractItemView::NoEditTriggers);
passwordColumn->setModel(passwordColumnModel);
passwordColumn->setFont(*columnFont);
connect(userdata, &UserData::passwordEntryAdded, this, &MainWindow::addPasswordEntry);
// create details panel
serviceName = new QLabel;
username = new QLabel;
password = new QLabel;
notes = new QLabel;
connect(passwordColumn->selectionModel(), &QItemSelectionModel::selectionChanged, this, &MainWindow::passwordEntrySelected);
QGridLayout* userColumnLayout = new QGridLayout;
userColumnLayout->addWidget(addUser, 0, 0);
userColumnLayout->addWidget(removeUser, 0, 1);
userColumnLayout->addWidget(userColumn, 1, 0, 1, 0);
QGridLayout* passwordColumnLayout = new QGridLayout;
passwordColumnLayout->addWidget(addPassword, 0, 0);
passwordColumnLayout->addWidget(removePassword, 0, 1);
passwordColumnLayout->addWidget(passwordColumn, 1, 0, 1, 0);
QFormLayout* detailsLayout = new QFormLayout;
detailsLayout->addRow(tr("Service name:"), serviceName);
detailsLayout->addRow(tr("Username:"), username);
detailsLayout->addRow(tr("Password:"), password);
detailsLayout->addRow(tr("Notes:"), notes);
QWidget* userSection = new QWidget;
userSection->setLayout(userColumnLayout);
QWidget* passwordSection = new QWidget;
passwordSection->setLayout(passwordColumnLayout);
QWidget* detailsSection = new QWidget;
detailsSection->setLayout(detailsLayout);
int buttonHeight = addUser->height();
detailsSection->setContentsMargins(0, buttonHeight + 4, 0, 0);
QSplitter* mainSplitter = new QSplitter;
mainSplitter->addWidget(userSection);
mainSplitter->addWidget(passwordSection);
mainSplitter->addWidget(detailsSection);
mainLayout->addWidget(mainSplitter);
ui->centralWidget->setLayout(mainLayout);
}
void MainWindow::open() {
int rval;
QString filePath = QFileDialog::getOpenFileName(this);
if (!filePath.isEmpty()) {
// remove all current user rows
int numUserRows = userColumnModel->rowCount();
userColumnModel->removeRows(0, numUserRows);
rval = userdata->ParseUserFile(filePath);
if (rval != 0) {
QMessageBox *invalidFileMsgBox = new QMessageBox(this);
invalidFileMsgBox->setText("Unable to open file \"" + filePath + "\".");
invalidFileMsgBox->setIcon(QMessageBox::Critical);
invalidFileMsgBox->exec();
}
}
}
void MainWindow::saveAs() {
QString filePath = QFileDialog::getSaveFileName(this, tr("Save File As"),
Q_NULLPTR,
tr("Karabiner Account File (*.kbr)"));
if (!filePath.isEmpty()) {
userdata->SaveUserFile(filePath);
}
}
void MainWindow::createNewUser() {
NewUserDialog *dialog = new NewUserDialog(this);
dialog->exec();
}
void MainWindow::createNewPassword() {
NewPasswordDialog *dialog = new NewPasswordDialog(this);
dialog->exec();
}
void MainWindow::addUserEntry(QString usernameToAdd) {
int lastRow = userColumnModel->rowCount();
userColumnModel->insertRow(lastRow);
QModelIndex lastRowModelIndex = userColumnModel->index(lastRow);
userColumnModel->setData(lastRowModelIndex, usernameToAdd, Qt::DisplayRole);
userColumn->selectionModel()->select(lastRowModelIndex, QItemSelectionModel::ClearAndSelect);
}
void MainWindow::removeSelectedUserEntry() {
QList<QModelIndex> selectedRowIndexes = userColumn->selectionModel()->selectedRows();
QModelIndex selectedRowModelIndex = selectedRowIndexes.first();
QString usernameString = selectedRowModelIndex.data().toString();
userdata->DeleteUser(usernameString);
int selectedRow = selectedRowModelIndex.row();
userColumnModel->removeRow(selectedRow);
userColumn->selectionModel()->clear();
}
void MainWindow::userSelected(const QItemSelection &selectedUserItem, const QItemSelection &deselectedUserItem) {
QList<QModelIndex> selectedUserIndexes = selectedUserItem.indexes();
QList<QModelIndex> deselectedUserIndexes = deselectedUserItem.indexes();
if (selectedUserIndexes.size() == 0) {
removeUser->setEnabled(false);
refreshPasswordEntries();
return;
}
removeUser->setEnabled(true);
int selectedRow = selectedUserIndexes[0].row();
QString selectedUsername = userColumnModel->stringList()[selectedRow];
User* selectedUser = userdata->GetUser(selectedUsername);
// authenticate user if encrypted
if (!selectedUser->isDecrypted()) {
bool authenticated = 0;
while (!authenticated) {
bool accepted;
QString password = QInputDialog::getText(this, "Authentication", "Password:",
QLineEdit::Password, "", &accepted);
// if user presses cancel on the dialog
if (!accepted) {
if (deselectedUserIndexes.size() == 0) {
// clear selection if nothing was previously selected
userColumn->selectionModel()->clearSelection();
} else {
// select previously selected row
userColumn->selectionModel()->select(deselectedUserIndexes[0], QItemSelectionModel::ClearAndSelect);
}
return;
}
authenticated = selectedUser->Authenticate(password, User::Decrypt);
}
}
refreshPasswordEntries();
}
void MainWindow::addPasswordEntry(QString newServiceName) {
int lastRow = passwordColumnModel->rowCount();
passwordColumnModel->insertRow(lastRow);
QModelIndex lastRowModelIndex = passwordColumnModel->index(lastRow);
passwordColumnModel->setData(lastRowModelIndex, newServiceName, Qt::DisplayRole);
passwordColumn->selectionModel()->select(lastRowModelIndex, QItemSelectionModel::ClearAndSelect);
}
void MainWindow::removeSelectedPasswordEntry() {
QList<QModelIndex> selectedRowIndexes = passwordColumn->selectionModel()->selectedRows();
QModelIndex selectedRowModelIndex = selectedRowIndexes.first();
QString serviceName = selectedRowModelIndex.data().toString();
userdata->DeleteUser(serviceName);
int selectedRow = selectedRowModelIndex.row();
passwordColumnModel->removeRow(selectedRow);
passwordColumn->selectionModel()->clear();
}
void MainWindow::passwordEntrySelected(const QItemSelection &selectedPasswordItem, const QItemSelection &deselectedPasswordItem) {
QList<QModelIndex> selectedPasswordIndexes = selectedPasswordItem.indexes();
QList<QModelIndex> deselectedPasswordIndexes = deselectedPasswordItem.indexes();
if (selectedPasswordIndexes.length() != 0) {
removePassword->setEnabled(true);
} else {
removePassword->setEnabled(false);
}
refreshDetailsPane();
}
void MainWindow::refreshPasswordEntries() {
int numRows = passwordColumnModel->rowCount();
passwordColumnModel->removeRows(0, numRows);
// find the selected row
QList<QModelIndex> selectedRowIndexes = userColumn->selectionModel()->selectedRows();
if (selectedRowIndexes.size() == 0) {
return;
}
int selectedRow = selectedRowIndexes.first().row();
QString selectedUsername = userColumnModel->stringList()[selectedRow];
User* selectedUser = userdata->GetUser(selectedUsername);
int numPasswordEntries = selectedUser->password_entries.length();
passwordColumnModel->insertRows(0, numPasswordEntries);
int i;
QModelIndex curRowModelIndex;
for (i = 0; i < numPasswordEntries; i++) {
curRowModelIndex = passwordColumnModel->index(i);
passwordColumnModel->setData(curRowModelIndex, selectedUser->password_entries[i].service_name, Qt::DisplayRole);
}
}
void MainWindow::refreshDetailsPane() {
// find the selected user
QList<QModelIndex> selectedRowIndexes = userColumn->selectionModel()->selectedRows();
if (selectedRowIndexes.size() == 0) {
clearDetailsPane();
return;
}
int selectedRow = selectedRowIndexes[0].row();
QString selectedUsername = userColumnModel->stringList()[selectedRow];
User* selectedUser = userdata->GetUser(selectedUsername);
// find the selected password entry
selectedRowIndexes = passwordColumn->selectionModel()->selectedRows();
if (selectedRowIndexes.size() == 0) {
clearDetailsPane();
return;
}
selectedRow = selectedRowIndexes[0].row();
PwEntry selectedPwEntry = selectedUser->password_entries[selectedRow];
serviceName->setText(selectedPwEntry.service_name);
username->setText(selectedPwEntry.username);
password->setText(selectedPwEntry.password);
notes->setText(selectedPwEntry.notes);
}
void MainWindow::clearDetailsPane() {
serviceName->setText("");
username->setText("");
password->setText("");
notes->setText("");
}
<|endoftext|> |
<commit_before>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "version.h"
#include <QFileDialog>
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
ui->PauseResume_Button->setFocus();
planetCountLabel = new QLabel(ui->statusbar);
planetCountLabel->setFixedWidth(120);
ui->statusbar->addPermanentWidget(planetCountLabel);
fpsLabel = new QLabel(ui->statusbar);
fpsLabel->setFixedWidth(120);
ui->statusbar->addPermanentWidget(fpsLabel);
averagefpsLabel = new QLabel(ui->statusbar);
averagefpsLabel->setFixedWidth(160);
ui->statusbar->addPermanentWidget(averagefpsLabel);
connect(ui->actionCenter_All, SIGNAL(triggered()), &ui->centralwidget->universe, SLOT(centerAll()));
connect(ui->actionInteractive_Planet_Placement, SIGNAL(triggered()), ui->centralwidget, SLOT(beginInteractiveCreation()));
connect(ui->actionInteractive_Orbital_Placement, SIGNAL(triggered()), ui->centralwidget, SLOT(beginOrbitalCreation()));
connect(ui->actionToggle_Firing_Mode, SIGNAL(toggled(bool)), ui->centralwidget, SLOT(enableFiringMode(bool)));
connect(ui->actionTake_Screenshot, SIGNAL(triggered()), ui->centralwidget, SLOT(takeScreenshot()));
connect(ui->centralwidget, SIGNAL(updatePlanetCountStatusMessage(QString)), planetCountLabel, SLOT(setText(QString)));
connect(ui->centralwidget, SIGNAL(updateFPSStatusMessage(QString)), fpsLabel, SLOT(setText(QString)));
connect(ui->centralwidget, SIGNAL(updateAverageFPSStatusMessage(QString)), averagefpsLabel, SLOT(setText(QString)));
connect(ui->actionExit, SIGNAL(triggered()), this, SLOT(close()));
connect(ui->gridRangeSpinBox, SIGNAL(valueChanged(int)), ui->centralwidget, SLOT(setGridRange(int)));
connect(ui->actionNew_Planet, SIGNAL(toggled(bool)), ui->newPlanet_DockWidget, SLOT(setVisible(bool)));
connect(ui->newPlanet_DockWidget, SIGNAL(visibilityChanged(bool)), ui->actionNew_Planet, SLOT(setChecked(bool)));
connect(ui->actionSpeed_Control, SIGNAL(toggled(bool)), ui->speedControl_DockWidget, SLOT(setVisible(bool)));
connect(ui->speedControl_DockWidget, SIGNAL(visibilityChanged(bool)), ui->actionSpeed_Control, SLOT(setChecked(bool)));
connect(ui->actionCamera_Location, SIGNAL(toggled(bool)), ui->camera_DockWidget, SLOT(setVisible(bool)));
connect(ui->camera_DockWidget, SIGNAL(visibilityChanged(bool)), ui->actionCamera_Location, SLOT(setChecked(bool)));
connect(ui->actionView_Settings, SIGNAL(toggled(bool)), ui->viewSettings_DockWidget, SLOT(setVisible(bool)));
connect(ui->viewSettings_DockWidget, SIGNAL(visibilityChanged(bool)), ui->actionView_Settings, SLOT(setChecked(bool)));
connect(ui->actionFiring_Mode_Settings, SIGNAL(toggled(bool)), ui->firingSettings_DockWidget, SLOT(setVisible(bool)));
connect(ui->firingSettings_DockWidget, SIGNAL(visibilityChanged(bool)), ui->actionFiring_Mode_Settings, SLOT(setChecked(bool)));
}
MainWindow::~MainWindow(){
delete ui;
delete planetCountLabel;
delete averagefpsLabel;
delete fpsLabel;
}
void MainWindow::closeEvent(QCloseEvent *e){
if(ui->centralwidget->universe.planets.count() > 0){
float tmpsimspeed = ui->centralwidget->universe.simspeed;
ui->centralwidget->universe.simspeed = 0.0f;
if(QMessageBox::warning(this, tr("Are You Sure?"), tr("Are you sure you wish to exit? (universe will not be saved...)"),
QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::No){
ui->centralwidget->universe.simspeed = tmpsimspeed;
e->ignore();
return;
}
}
e->accept();
}
void MainWindow::on_createPlanet_PushButton_clicked(){
ui->centralwidget->universe.selected = ui->centralwidget->universe.addPlanet(
Planet(QVector3D(ui->newPosX_SpinBox->value(), ui->newPosY_SpinBox->value(), ui->newPosZ_SpinBox->value()),
QVector3D(ui->newVelocityX_SpinBox->value(), ui->newVelocityY_SpinBox->value(), ui->newVelocityZ_SpinBox->value()) * velocityfac,
ui->newMass_SpinBox->value()));
}
void MainWindow::on_actionDelete_triggered(){
ui->centralwidget->universe.planets.remove(ui->centralwidget->universe.selected);
}
void MainWindow::on_actionClear_Velocity_triggered(){
if(ui->centralwidget->universe.planets.contains(ui->centralwidget->universe.selected)){
ui->centralwidget->universe.planets[ui->centralwidget->universe.selected].velocity = QVector3D();
}
}
void MainWindow::on_speed_Dial_valueChanged(int value){
ui->centralwidget->universe.simspeed = (value * speeddialmax) / ui->speed_Dial->maximum();
ui->speedDisplay_lcdNumber->display(ui->centralwidget->universe.simspeed);
if(ui->centralwidget->universe.simspeed <= 0.0f){
ui->PauseResume_Button->setText(tr("Resume"));
ui->PauseResume_Button->setIcon(QIcon(":/icons/silk/control_play_blue.png"));
}else{
ui->PauseResume_Button->setText(tr("Pause"));
ui->PauseResume_Button->setIcon(QIcon(":/icons/silk/control_pause_blue.png"));
}
}
void MainWindow::on_PauseResume_Button_clicked(){
if(ui->speed_Dial->value() == 0){
ui->speed_Dial->setValue(ui->speed_Dial->maximum() / speeddialmax);
}else{
ui->speed_Dial->setValue(0);
}
}
void MainWindow::on_FastForward_Button_clicked(){
if(ui->speed_Dial->value() >= ui->speed_Dial->maximum() / 2){
ui->speed_Dial->setValue(ui->speed_Dial->maximum() / speeddialmax);
}else{
ui->speed_Dial->setValue(ui->speed_Dial->maximum());
}
}
void MainWindow::on_actionGridOff_triggered(){
ui->centralwidget->displaysettings &= ~PlanetsWidget::SolidLineGrid;
ui->centralwidget->displaysettings &= ~PlanetsWidget::PointGrid;
ui->actionGridLines->setChecked(false);
ui->actionGridPoints->setChecked(false);
ui->centralwidget->updateGrid();
}
void MainWindow::on_actionGridLines_triggered(){
ui->centralwidget->displaysettings |= PlanetsWidget::SolidLineGrid;
ui->centralwidget->displaysettings &= ~PlanetsWidget::PointGrid;
ui->actionGridLines->setChecked(true);
ui->actionGridPoints->setChecked(false);
ui->centralwidget->updateGrid();
}
void MainWindow::on_actionGridPoints_triggered(){
ui->centralwidget->displaysettings &= ~PlanetsWidget::SolidLineGrid;
ui->centralwidget->displaysettings |= PlanetsWidget::PointGrid;
ui->actionGridLines->setChecked(false);
ui->actionGridPoints->setChecked(true);
ui->centralwidget->updateGrid();
}
void MainWindow::on_actionDraw_Paths_triggered(){
ui->centralwidget->displaysettings ^= PlanetsWidget::PlanetTrails;
ui->actionDraw_Paths->setChecked(ui->centralwidget->displaysettings & PlanetsWidget::PlanetTrails);
}
void MainWindow::on_actionPlanet_Colors_triggered(){
ui->centralwidget->displaysettings ^= PlanetsWidget::PlanetColors;
ui->actionPlanet_Colors->setChecked(ui->centralwidget->displaysettings & PlanetsWidget::PlanetColors);
}
void MainWindow::on_actionNew_Simulation_triggered(){
float tmpsimspeed = ui->centralwidget->universe.simspeed;
ui->centralwidget->universe.simspeed = 0.0f;
if(QMessageBox::warning(this, tr("Are You Sure?"), tr("Are you sure you wish to destroy the universe? (i.e. delete all planets.)"),
QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes){
ui->centralwidget->universe.deleteAll();
}
ui->centralwidget->universe.simspeed = tmpsimspeed;
}
void MainWindow::on_actionOpen_Simulation_triggered(){
float tmpsimspeed = ui->centralwidget->universe.simspeed;
ui->centralwidget->universe.simspeed = 0.0f;
QString filename = QFileDialog::getOpenFileName(this, tr("Open Simulation"), "", tr("Simulation files (*.xml)"));
ui->centralwidget->universe.load(filename);
ui->centralwidget->universe.simspeed = tmpsimspeed;
}
void MainWindow::on_actionSave_Simulation_triggered(){
float tmpsimspeed = ui->centralwidget->universe.simspeed;
ui->centralwidget->universe.simspeed = 0.0f;
QString filename = QFileDialog::getSaveFileName(this, tr("Save Simulation"), "", tr("Simulation files (*.xml)"));
ui->centralwidget->universe.save(filename);
ui->centralwidget->universe.simspeed = tmpsimspeed;
}
void MainWindow::on_followPlanetPushButton_clicked(){
ui->centralwidget->following = ui->centralwidget->universe.selected;
ui->centralwidget->followState = PlanetsWidget::Single;
}
void MainWindow::on_clearFollowPushButton_clicked(){
ui->centralwidget->following = 0;
ui->centralwidget->followState = PlanetsWidget::FollowNone;
}
void MainWindow::on_followPlainAveragePushButton_clicked(){
ui->centralwidget->followState = PlanetsWidget::PlainAverage;
}
void MainWindow::on_followWeightedAveragePushButton_clicked(){
ui->centralwidget->followState = PlanetsWidget::WeightedAverage;
}
void MainWindow::on_actionAbout_triggered(){
QMessageBox::about(this, tr("About Planets3D"),
tr("<html><head/><body>"
"<h1>Planets3D %1</h1>"
"<p>Planets3D is a simple 3D gravitational simulator</p>"
"<p>Website: <a href=\"https://github.com/chipgw/planets-3d\">github.com/chipgw/planets-3d</a></p>"
"<p>Build Info:</p><ul>"
"<li>Git sha1: %2</li>"
"<li>Build type: %3</li>"
"</ul></body></html>").arg(version::getVersionString()).arg(version::git_revision).arg(version::build_type));
}
void MainWindow::on_actionAbout_Qt_triggered(){
QMessageBox::aboutQt(this);
}
void MainWindow::on_stepsPerFrameSpinBox_valueChanged(int value){
ui->centralwidget->universe.stepsPerFrame = value;
}
void MainWindow::on_trailLengthSpinBox_valueChanged(int value){
Planet::pathLength = value;
}
void MainWindow::on_firingVelocityDoubleSpinBox_valueChanged(double value){
ui->centralwidget->firingSpeed = value * velocityfac;
}
void MainWindow::on_firingMassSpinBox_valueChanged(int value){
ui->centralwidget->firingMass = value;
}
<commit_msg>don't save if there are no planets.<commit_after>#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "version.h"
#include <QFileDialog>
#include <QMessageBox>
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
ui->PauseResume_Button->setFocus();
planetCountLabel = new QLabel(ui->statusbar);
planetCountLabel->setFixedWidth(120);
ui->statusbar->addPermanentWidget(planetCountLabel);
fpsLabel = new QLabel(ui->statusbar);
fpsLabel->setFixedWidth(120);
ui->statusbar->addPermanentWidget(fpsLabel);
averagefpsLabel = new QLabel(ui->statusbar);
averagefpsLabel->setFixedWidth(160);
ui->statusbar->addPermanentWidget(averagefpsLabel);
connect(ui->actionCenter_All, SIGNAL(triggered()), &ui->centralwidget->universe, SLOT(centerAll()));
connect(ui->actionInteractive_Planet_Placement, SIGNAL(triggered()), ui->centralwidget, SLOT(beginInteractiveCreation()));
connect(ui->actionInteractive_Orbital_Placement, SIGNAL(triggered()), ui->centralwidget, SLOT(beginOrbitalCreation()));
connect(ui->actionToggle_Firing_Mode, SIGNAL(toggled(bool)), ui->centralwidget, SLOT(enableFiringMode(bool)));
connect(ui->actionTake_Screenshot, SIGNAL(triggered()), ui->centralwidget, SLOT(takeScreenshot()));
connect(ui->centralwidget, SIGNAL(updatePlanetCountStatusMessage(QString)), planetCountLabel, SLOT(setText(QString)));
connect(ui->centralwidget, SIGNAL(updateFPSStatusMessage(QString)), fpsLabel, SLOT(setText(QString)));
connect(ui->centralwidget, SIGNAL(updateAverageFPSStatusMessage(QString)), averagefpsLabel, SLOT(setText(QString)));
connect(ui->actionExit, SIGNAL(triggered()), this, SLOT(close()));
connect(ui->gridRangeSpinBox, SIGNAL(valueChanged(int)), ui->centralwidget, SLOT(setGridRange(int)));
connect(ui->actionNew_Planet, SIGNAL(toggled(bool)), ui->newPlanet_DockWidget, SLOT(setVisible(bool)));
connect(ui->newPlanet_DockWidget, SIGNAL(visibilityChanged(bool)), ui->actionNew_Planet, SLOT(setChecked(bool)));
connect(ui->actionSpeed_Control, SIGNAL(toggled(bool)), ui->speedControl_DockWidget, SLOT(setVisible(bool)));
connect(ui->speedControl_DockWidget, SIGNAL(visibilityChanged(bool)), ui->actionSpeed_Control, SLOT(setChecked(bool)));
connect(ui->actionCamera_Location, SIGNAL(toggled(bool)), ui->camera_DockWidget, SLOT(setVisible(bool)));
connect(ui->camera_DockWidget, SIGNAL(visibilityChanged(bool)), ui->actionCamera_Location, SLOT(setChecked(bool)));
connect(ui->actionView_Settings, SIGNAL(toggled(bool)), ui->viewSettings_DockWidget, SLOT(setVisible(bool)));
connect(ui->viewSettings_DockWidget, SIGNAL(visibilityChanged(bool)), ui->actionView_Settings, SLOT(setChecked(bool)));
connect(ui->actionFiring_Mode_Settings, SIGNAL(toggled(bool)), ui->firingSettings_DockWidget, SLOT(setVisible(bool)));
connect(ui->firingSettings_DockWidget, SIGNAL(visibilityChanged(bool)), ui->actionFiring_Mode_Settings, SLOT(setChecked(bool)));
}
MainWindow::~MainWindow(){
delete ui;
delete planetCountLabel;
delete averagefpsLabel;
delete fpsLabel;
}
void MainWindow::closeEvent(QCloseEvent *e){
if(ui->centralwidget->universe.planets.count() > 0){
float tmpsimspeed = ui->centralwidget->universe.simspeed;
ui->centralwidget->universe.simspeed = 0.0f;
if(QMessageBox::warning(this, tr("Are You Sure?"), tr("Are you sure you wish to exit? (universe will not be saved...)"),
QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::No){
ui->centralwidget->universe.simspeed = tmpsimspeed;
e->ignore();
return;
}
}
e->accept();
}
void MainWindow::on_createPlanet_PushButton_clicked(){
ui->centralwidget->universe.selected = ui->centralwidget->universe.addPlanet(
Planet(QVector3D(ui->newPosX_SpinBox->value(), ui->newPosY_SpinBox->value(), ui->newPosZ_SpinBox->value()),
QVector3D(ui->newVelocityX_SpinBox->value(), ui->newVelocityY_SpinBox->value(), ui->newVelocityZ_SpinBox->value()) * velocityfac,
ui->newMass_SpinBox->value()));
}
void MainWindow::on_actionDelete_triggered(){
ui->centralwidget->universe.planets.remove(ui->centralwidget->universe.selected);
}
void MainWindow::on_actionClear_Velocity_triggered(){
if(ui->centralwidget->universe.planets.contains(ui->centralwidget->universe.selected)){
ui->centralwidget->universe.planets[ui->centralwidget->universe.selected].velocity = QVector3D();
}
}
void MainWindow::on_speed_Dial_valueChanged(int value){
ui->centralwidget->universe.simspeed = (value * speeddialmax) / ui->speed_Dial->maximum();
ui->speedDisplay_lcdNumber->display(ui->centralwidget->universe.simspeed);
if(ui->centralwidget->universe.simspeed <= 0.0f){
ui->PauseResume_Button->setText(tr("Resume"));
ui->PauseResume_Button->setIcon(QIcon(":/icons/silk/control_play_blue.png"));
}else{
ui->PauseResume_Button->setText(tr("Pause"));
ui->PauseResume_Button->setIcon(QIcon(":/icons/silk/control_pause_blue.png"));
}
}
void MainWindow::on_PauseResume_Button_clicked(){
if(ui->speed_Dial->value() == 0){
ui->speed_Dial->setValue(ui->speed_Dial->maximum() / speeddialmax);
}else{
ui->speed_Dial->setValue(0);
}
}
void MainWindow::on_FastForward_Button_clicked(){
if(ui->speed_Dial->value() >= ui->speed_Dial->maximum() / 2){
ui->speed_Dial->setValue(ui->speed_Dial->maximum() / speeddialmax);
}else{
ui->speed_Dial->setValue(ui->speed_Dial->maximum());
}
}
void MainWindow::on_actionGridOff_triggered(){
ui->centralwidget->displaysettings &= ~PlanetsWidget::SolidLineGrid;
ui->centralwidget->displaysettings &= ~PlanetsWidget::PointGrid;
ui->actionGridLines->setChecked(false);
ui->actionGridPoints->setChecked(false);
ui->centralwidget->updateGrid();
}
void MainWindow::on_actionGridLines_triggered(){
ui->centralwidget->displaysettings |= PlanetsWidget::SolidLineGrid;
ui->centralwidget->displaysettings &= ~PlanetsWidget::PointGrid;
ui->actionGridLines->setChecked(true);
ui->actionGridPoints->setChecked(false);
ui->centralwidget->updateGrid();
}
void MainWindow::on_actionGridPoints_triggered(){
ui->centralwidget->displaysettings &= ~PlanetsWidget::SolidLineGrid;
ui->centralwidget->displaysettings |= PlanetsWidget::PointGrid;
ui->actionGridLines->setChecked(false);
ui->actionGridPoints->setChecked(true);
ui->centralwidget->updateGrid();
}
void MainWindow::on_actionDraw_Paths_triggered(){
ui->centralwidget->displaysettings ^= PlanetsWidget::PlanetTrails;
ui->actionDraw_Paths->setChecked(ui->centralwidget->displaysettings & PlanetsWidget::PlanetTrails);
}
void MainWindow::on_actionPlanet_Colors_triggered(){
ui->centralwidget->displaysettings ^= PlanetsWidget::PlanetColors;
ui->actionPlanet_Colors->setChecked(ui->centralwidget->displaysettings & PlanetsWidget::PlanetColors);
}
void MainWindow::on_actionNew_Simulation_triggered(){
float tmpsimspeed = ui->centralwidget->universe.simspeed;
ui->centralwidget->universe.simspeed = 0.0f;
if(QMessageBox::warning(this, tr("Are You Sure?"), tr("Are you sure you wish to destroy the universe? (i.e. delete all planets.)"),
QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes) == QMessageBox::Yes){
ui->centralwidget->universe.deleteAll();
}
ui->centralwidget->universe.simspeed = tmpsimspeed;
}
void MainWindow::on_actionOpen_Simulation_triggered(){
float tmpsimspeed = ui->centralwidget->universe.simspeed;
ui->centralwidget->universe.simspeed = 0.0f;
QString filename = QFileDialog::getOpenFileName(this, tr("Open Simulation"), "", tr("Simulation files (*.xml)"));
ui->centralwidget->universe.load(filename);
ui->centralwidget->universe.simspeed = tmpsimspeed;
}
void MainWindow::on_actionSave_Simulation_triggered(){
float tmpsimspeed = ui->centralwidget->universe.simspeed;
ui->centralwidget->universe.simspeed = 0.0f;
if(ui->centralwidget->universe.planets.count() > 0){
QString filename = QFileDialog::getSaveFileName(this, tr("Save Simulation"), "", tr("Simulation files (*.xml)"));
ui->centralwidget->universe.save(filename);
}else{
QMessageBox::warning(this, tr("Error Saving Simulation."), tr("No planets to save!"));
}
ui->centralwidget->universe.simspeed = tmpsimspeed;
}
void MainWindow::on_followPlanetPushButton_clicked(){
ui->centralwidget->following = ui->centralwidget->universe.selected;
ui->centralwidget->followState = PlanetsWidget::Single;
}
void MainWindow::on_clearFollowPushButton_clicked(){
ui->centralwidget->following = 0;
ui->centralwidget->followState = PlanetsWidget::FollowNone;
}
void MainWindow::on_followPlainAveragePushButton_clicked(){
ui->centralwidget->followState = PlanetsWidget::PlainAverage;
}
void MainWindow::on_followWeightedAveragePushButton_clicked(){
ui->centralwidget->followState = PlanetsWidget::WeightedAverage;
}
void MainWindow::on_actionAbout_triggered(){
QMessageBox::about(this, tr("About Planets3D"),
tr("<html><head/><body>"
"<h1>Planets3D %1</h1>"
"<p>Planets3D is a simple 3D gravitational simulator</p>"
"<p>Website: <a href=\"https://github.com/chipgw/planets-3d\">github.com/chipgw/planets-3d</a></p>"
"<p>Build Info:</p><ul>"
"<li>Git sha1: %2</li>"
"<li>Build type: %3</li>"
"</ul></body></html>").arg(version::getVersionString()).arg(version::git_revision).arg(version::build_type));
}
void MainWindow::on_actionAbout_Qt_triggered(){
QMessageBox::aboutQt(this);
}
void MainWindow::on_stepsPerFrameSpinBox_valueChanged(int value){
ui->centralwidget->universe.stepsPerFrame = value;
}
void MainWindow::on_trailLengthSpinBox_valueChanged(int value){
Planet::pathLength = value;
}
void MainWindow::on_firingVelocityDoubleSpinBox_valueChanged(double value){
ui->centralwidget->firingSpeed = value * velocityfac;
}
void MainWindow::on_firingMassSpinBox_valueChanged(int value){
ui->centralwidget->firingMass = value;
}
<|endoftext|> |
<commit_before>#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(this, SIGNAL(updateFilter(QString)),
ui->tabWidget, SLOT(updateFilter(QString)), Qt::UniqueConnection);
connect(this, SIGNAL(insertClimberInDB(Climber *&)),
ui->tabWidget, SLOT(insertClimberInDB(Climber *&)), Qt::UniqueConnection);
connect(this, SIGNAL(removeClimber()),
ui->tabWidget, SLOT(removeClimber()), Qt::UniqueConnection);
connect(this, SIGNAL(toggleActivity()),
ui->tabWidget, SLOT(toggleActivity()), Qt::UniqueConnection);
connect(this, SIGNAL(updateClimberInfo()),
ui->tabWidget, SLOT(updateClimberInfo()), Qt::UniqueConnection);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_actionNew_Climber_triggered()
{
ru = new RegisterUser(this);
ru->show();
}
void MainWindow::on_lineEdit_search_textChanged(const QString &str)
{
emit updateFilter(str);
}
void MainWindow::insertClimber(Climber *&climber)
{
emit insertClimberInDB(climber);
}
void MainWindow::on_actionRemove_Climber_triggered()
{
QMessageBox msgBox;
msgBox.setIcon(QMessageBox::Critical);
msgBox.setText("Deseja realmente apagar o escalador?");
msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::No);
if(msgBox.exec() == QMessageBox::Yes)
emit removeClimber();
}
void MainWindow::rowSelected(QModelIndex x, QModelIndex y)
{
Q_UNUSED(y);
if (x.isValid())
ui->actionRemove_Climber->setEnabled(true);
else
ui->actionRemove_Climber->setEnabled(false);
}
void MainWindow::on_actionToggleActivity_Climber_triggered()
{
emit toggleActivity();
}
void MainWindow::on_actionPay_Climber_triggered()
{
payment = new PaymentWindow(this);
connect(this, SIGNAL(updateClimberInfo(Climber *&)),
payment, SLOT(updateClimberInfo(Climber *&)), Qt::UniqueConnection);
connect(payment, SIGNAL(setPayment(QDate, double)),
ui->tabWidget, SLOT(setPayment(QDate, double)), Qt::UniqueConnection);
emit updateClimberInfo();
payment->show();
}
void MainWindow::recvClimberInfo(Climber *&climber)
{
emit updateClimberInfo(climber);
}
void MainWindow::updateActivateOption(int idx)
{
ui->actionToggleActivity_Climber->setEnabled(true);
if (idx == 0)
ui->actionToggleActivity_Climber->setText(tr("Inativar"));
else if (idx == 1)
ui->actionToggleActivity_Climber->setEnabled(false);
else
ui->actionToggleActivity_Climber->setText(tr("Ativar"));
}
void MainWindow::on_actionExport_triggered()
{
QString DBName = QFileDialog::getSaveFileName(this, tr("Salvar como..."), QString(), tr("DB (*.db)"));
if (!(DBName.endsWith(".db", Qt::CaseInsensitive)))
DBName += ".db";
QMessageBox msgBox;
if (QFile::copy("vertsys.db", DBName))
{
msgBox.setIcon(QMessageBox::Information);
msgBox.setText("Banco de dados exportado com sucesso!");
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setDefaultButton(QMessageBox::Ok);
}
else
{
msgBox.setIcon(QMessageBox::Critical);
msgBox.setText("Nao foi possivel exportar o banco de dados!");
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setDefaultButton(QMessageBox::Ok);
}
msgBox.exec();
}
void MainWindow::on_actionImport_triggered()
{
QString DBName = QFileDialog::getOpenFileName(this, tr("Abrir"), QString(), tr("DB (*.db)"));
if (!(DBName.endsWith(".db", Qt::CaseInsensitive)))
DBName += ".db";
QMessageBox msgBox;
QFile::remove("vertsys.db");
if (QFile::copy(DBName, "vertsys.db"))
{
msgBox.setIcon(QMessageBox::Information);
msgBox.setText("Banco de dados importado com sucesso!");
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setDefaultButton(QMessageBox::Ok);
qApp->exit(MainWindow::EXIT_CODE_REBOOT);
}
else
{
msgBox.setIcon(QMessageBox::Critical);
msgBox.setText("Nao foi possivel importar o banco de dados!");
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setDefaultButton(QMessageBox::Ok);
}
msgBox.exec();
}
<commit_msg>Verifications in import/export<commit_after>#include "mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(this, SIGNAL(updateFilter(QString)),
ui->tabWidget, SLOT(updateFilter(QString)), Qt::UniqueConnection);
connect(this, SIGNAL(insertClimberInDB(Climber *&)),
ui->tabWidget, SLOT(insertClimberInDB(Climber *&)), Qt::UniqueConnection);
connect(this, SIGNAL(removeClimber()),
ui->tabWidget, SLOT(removeClimber()), Qt::UniqueConnection);
connect(this, SIGNAL(toggleActivity()),
ui->tabWidget, SLOT(toggleActivity()), Qt::UniqueConnection);
connect(this, SIGNAL(updateClimberInfo()),
ui->tabWidget, SLOT(updateClimberInfo()), Qt::UniqueConnection);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_actionNew_Climber_triggered()
{
ru = new RegisterUser(this);
ru->show();
}
void MainWindow::on_lineEdit_search_textChanged(const QString &str)
{
emit updateFilter(str);
}
void MainWindow::insertClimber(Climber *&climber)
{
emit insertClimberInDB(climber);
}
void MainWindow::on_actionRemove_Climber_triggered()
{
QMessageBox msgBox;
msgBox.setIcon(QMessageBox::Critical);
msgBox.setText("Deseja realmente apagar o escalador?");
msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::No);
if(msgBox.exec() == QMessageBox::Yes)
emit removeClimber();
}
void MainWindow::rowSelected(QModelIndex x, QModelIndex y)
{
Q_UNUSED(y);
if (x.isValid())
ui->actionRemove_Climber->setEnabled(true);
else
ui->actionRemove_Climber->setEnabled(false);
}
void MainWindow::on_actionToggleActivity_Climber_triggered()
{
emit toggleActivity();
}
void MainWindow::on_actionPay_Climber_triggered()
{
payment = new PaymentWindow(this);
connect(this, SIGNAL(updateClimberInfo(Climber *&)),
payment, SLOT(updateClimberInfo(Climber *&)), Qt::UniqueConnection);
connect(payment, SIGNAL(setPayment(QDate, double)),
ui->tabWidget, SLOT(setPayment(QDate, double)), Qt::UniqueConnection);
emit updateClimberInfo();
payment->show();
}
void MainWindow::recvClimberInfo(Climber *&climber)
{
emit updateClimberInfo(climber);
}
void MainWindow::updateActivateOption(int idx)
{
ui->actionToggleActivity_Climber->setEnabled(true);
if (idx == 0)
ui->actionToggleActivity_Climber->setText(tr("Inativar"));
else if (idx == 1)
ui->actionToggleActivity_Climber->setEnabled(false);
else
ui->actionToggleActivity_Climber->setText(tr("Ativar"));
}
void MainWindow::on_actionExport_triggered()
{
QString DBName = QFileDialog::getSaveFileName(this, tr("Salvar como..."), QString(), tr("DB (*.db)"));
if (DBName == NULL)
return;
if (!(DBName.endsWith(".db", Qt::CaseInsensitive)))
DBName += ".db";
QMessageBox msgBox;
if (QFile::copy("vertsys.db", DBName))
{
msgBox.setIcon(QMessageBox::Information);
msgBox.setText("Banco de dados exportado com sucesso!");
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setDefaultButton(QMessageBox::Ok);
}
else
{
msgBox.setIcon(QMessageBox::Critical);
msgBox.setText("Nao foi possivel exportar o banco de dados!");
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setDefaultButton(QMessageBox::Ok);
}
msgBox.exec();
}
void MainWindow::on_actionImport_triggered()
{
QString DBName = QFileDialog::getOpenFileName(this, tr("Abrir"), QString(), tr("DB (*.db)"));
if (DBName == NULL)
return;
QString DBPath = QDir::currentPath() + "/vertsys.db";
if (DBName == DBPath)
return;
if (!(DBName.endsWith(".db", Qt::CaseInsensitive)))
DBName += ".db";
QMessageBox msgBox;
QFile::remove("vertsys.db");
if (QFile::copy(DBName, "vertsys.db"))
{
msgBox.setIcon(QMessageBox::Information);
msgBox.setText("Banco de dados importado com sucesso!");
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setDefaultButton(QMessageBox::Ok);
qApp->exit(MainWindow::EXIT_CODE_REBOOT);
}
else
{
msgBox.setIcon(QMessageBox::Critical);
msgBox.setText("Nao foi possivel importar o banco de dados!");
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setDefaultButton(QMessageBox::Ok);
}
msgBox.exec();
}
<|endoftext|> |
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of mhome.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mainwindow.h"
#include "homeapplication.h"
#include <QGLWidget>
#include <QDBusInterface>
#include <QX11Info>
#include <QDeclarativeEngine>
#include "x11wrapper.h"
#include "windowpixmapprovider.h"
MainWindow *MainWindow::mainWindowInstance = NULL;
const QString MainWindow::CONTENT_SEARCH_DBUS_SERVICE = "com.nokia.maemo.meegotouch.ContentSearch";
const QString MainWindow::CONTENT_SEARCH_DBUS_PATH = "/";
const QString MainWindow::CONTENT_SEARCH_DBUS_INTERFACE = "com.nokia.maemo.meegotouch.ContentSearchInterface";
const QString MainWindow::CONTENT_SEARCH_DBUS_METHOD = "launch";
const QString MainWindow::CALL_UI_DBUS_SERVICE = "com.nokia.telephony.callhistory";
const QString MainWindow::CALL_UI_DBUS_PATH = "/callhistory";
const QString MainWindow::CALL_UI_DBUS_INTERFACE = "com.nokia.telephony.callhistory";
const QString MainWindow::CALL_UI_DBUS_METHOD = "dialer";
MainWindow::MainWindow(QWidget *parent) :
QDeclarativeView(parent),
home(NULL),
externalServiceService(NULL),
externalServicePath(NULL),
externalServiceInterface(NULL),
externalServiceMethod(NULL)
{
mainWindowInstance = this;
if (qgetenv("MEEGOHOME_DESKTOP") != "0") {
// Dont Set the window type to desktop if MEEGOHOME_DESKTOP is set to 0
setAttribute(Qt::WA_X11NetWmWindowTypeDesktop);
}
#ifdef Q_WS_X11
// Visibility change messages are required to make the appVisible() signal work
WId window = winId();
XWindowAttributes attributes;
Display *display = QX11Info::display();
X11Wrapper::XGetWindowAttributes(display, window, &attributes);
X11Wrapper::XSelectInput(display, window, attributes.your_event_mask | VisibilityChangeMask);
#endif
excludeFromTaskBar();
// TODO: disable this for non-debug builds
if (QFile::exists("main.qml"))
setSource(QUrl::fromLocalFile("./main.qml"));
else
setSource(QUrl("qrc:/qml/main.qml"));
setResizeMode(SizeRootObjectToView);
setAttribute(Qt::WA_OpaquePaintEvent);
setAttribute(Qt::WA_NoSystemBackground);
QDeclarativeEngine *e = engine();
e->addImageProvider(QLatin1String("windows"), new WindowPixmapProvider);
}
MainWindow::~MainWindow()
{
mainWindowInstance = NULL;
}
MainWindow *MainWindow::instance(bool create)
{
if (mainWindowInstance == NULL && create) {
// The static instance variable is set in the constructor
new MainWindow;
}
return mainWindowInstance;
}
void MainWindow::excludeFromTaskBar()
{
// Tell the window to not to be shown in the switcher
Atom skipTaskbarAtom = X11Wrapper::XInternAtom(QX11Info::display(), "_NET_WM_STATE_SKIP_TASKBAR", False);
changeNetWmState(true, skipTaskbarAtom);
// Also set the _NET_WM_STATE window property to ensure Home doesn't try to
// manage this window in case the window manager fails to set the property in time
Atom netWmStateAtom = X11Wrapper::XInternAtom(QX11Info::display(), "_NET_WM_STATE", False);
QVector<Atom> atoms;
atoms.append(skipTaskbarAtom);
X11Wrapper::XChangeProperty(QX11Info::display(), internalWinId(), netWmStateAtom, XA_ATOM, 32, PropModeReplace, (unsigned char *)atoms.data(), atoms.count());
}
void MainWindow::changeNetWmState(bool set, Atom one, Atom two)
{
XEvent e;
e.xclient.type = ClientMessage;
Display *display = QX11Info::display();
Atom netWmStateAtom = X11Wrapper::XInternAtom(display, "_NET_WM_STATE", FALSE);
e.xclient.message_type = netWmStateAtom;
e.xclient.display = display;
e.xclient.window = internalWinId();
e.xclient.format = 32;
e.xclient.data.l[0] = set ? 1 : 0;
e.xclient.data.l[1] = one;
e.xclient.data.l[2] = two;
e.xclient.data.l[3] = 0;
e.xclient.data.l[4] = 0;
X11Wrapper::XSendEvent(display, RootWindow(display, x11Info().screen()), FALSE, (SubstructureNotifyMask | SubstructureRedirectMask), &e);
}
bool MainWindow::isCallUILaunchingKey(int key)
{
// Numbers, *, + and # will launch the call UI
return ((key >= Qt::Key_0 && key <= Qt::Key_9) || key == Qt::Key_Asterisk || key == Qt::Key_Plus || key == Qt::Key_NumberSign);
}
void MainWindow::keyPressEvent(QKeyEvent *event)
{
int key = event->key();
if (key < Qt::Key_Escape && !event->modifiers().testFlag(Qt::ControlModifier)) {
// Special keys and CTRL-anything should do nothing
QString keyPresses = event->text();
if (!keyPresses.isEmpty()) {
// Append keypresses to the presses to be sent
keyPressesToBeSent.append(keyPresses);
if (keyPressesBeingSent.isEmpty()) {
// Select the service to send the keypresses to
if (isCallUILaunchingKey(key)) {
setupExternalService(CALL_UI_DBUS_SERVICE, CALL_UI_DBUS_PATH, CALL_UI_DBUS_INTERFACE, CALL_UI_DBUS_METHOD);
} else {
setupExternalService(CONTENT_SEARCH_DBUS_SERVICE, CONTENT_SEARCH_DBUS_PATH, CONTENT_SEARCH_DBUS_INTERFACE, CONTENT_SEARCH_DBUS_METHOD);
}
// Call the external service
sendKeyPresses();
}
}
}
}
void MainWindow::closeEvent(QCloseEvent *event)
{
// Don't allow closing the main window
event->ignore();
}
void MainWindow::setupExternalService(const QString &service, const QString &path, const QString &interface, const QString &method)
{
externalServiceService = &service;
externalServicePath = &path;
externalServiceInterface = &interface;
externalServiceMethod = &method;
}
void MainWindow::sendKeyPresses()
{
// Only one external service launch may be active at a time
if (keyPressesBeingSent.isEmpty() && !keyPressesToBeSent.isEmpty() && externalServiceService != NULL && externalServicePath != NULL && externalServiceInterface != NULL && externalServiceMethod != NULL) {
// Make an asynchronous call to the external service and send the keypresses to be sent
QDBusInterface interface(*externalServiceService, *externalServicePath, *externalServiceInterface, QDBusConnection::sessionBus());
interface.callWithCallback(*externalServiceMethod, (QList<QVariant>() << keyPressesToBeSent), this, SLOT(markKeyPressesSentAndSendRemainingKeyPresses()), SLOT(markKeyPressesNotSent()));
// Keypresses that need to be sent are now being sent
keyPressesBeingSent = keyPressesToBeSent;
keyPressesToBeSent.clear();
}
}
void MainWindow::markKeyPressesSentAndSendRemainingKeyPresses()
{
// The keypresses that were being sent have now been sent
keyPressesBeingSent.clear();
// Send the remaining keypresses still to be sent (if any)
sendKeyPresses();
}
void MainWindow::markKeyPressesNotSent()
{
// Since the external service didn't launch prepend the sent keypresses to the keypresses to be sent but don't retry
keyPressesToBeSent.prepend(keyPressesBeingSent);
keyPressesBeingSent.clear();
}
<commit_msg>last minute changes: never a good idea<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of mhome.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "mainwindow.h"
#include "homeapplication.h"
#include <QGLWidget>
#include <QDBusInterface>
#include <QX11Info>
#include <QFile>
#include <QDeclarativeEngine>
#include "x11wrapper.h"
#include "windowpixmapprovider.h"
MainWindow *MainWindow::mainWindowInstance = NULL;
const QString MainWindow::CONTENT_SEARCH_DBUS_SERVICE = "com.nokia.maemo.meegotouch.ContentSearch";
const QString MainWindow::CONTENT_SEARCH_DBUS_PATH = "/";
const QString MainWindow::CONTENT_SEARCH_DBUS_INTERFACE = "com.nokia.maemo.meegotouch.ContentSearchInterface";
const QString MainWindow::CONTENT_SEARCH_DBUS_METHOD = "launch";
const QString MainWindow::CALL_UI_DBUS_SERVICE = "com.nokia.telephony.callhistory";
const QString MainWindow::CALL_UI_DBUS_PATH = "/callhistory";
const QString MainWindow::CALL_UI_DBUS_INTERFACE = "com.nokia.telephony.callhistory";
const QString MainWindow::CALL_UI_DBUS_METHOD = "dialer";
MainWindow::MainWindow(QWidget *parent) :
QDeclarativeView(parent),
home(NULL),
externalServiceService(NULL),
externalServicePath(NULL),
externalServiceInterface(NULL),
externalServiceMethod(NULL)
{
mainWindowInstance = this;
if (qgetenv("MEEGOHOME_DESKTOP") != "0") {
// Dont Set the window type to desktop if MEEGOHOME_DESKTOP is set to 0
setAttribute(Qt::WA_X11NetWmWindowTypeDesktop);
}
#ifdef Q_WS_X11
// Visibility change messages are required to make the appVisible() signal work
WId window = winId();
XWindowAttributes attributes;
Display *display = QX11Info::display();
X11Wrapper::XGetWindowAttributes(display, window, &attributes);
X11Wrapper::XSelectInput(display, window, attributes.your_event_mask | VisibilityChangeMask);
#endif
excludeFromTaskBar();
// TODO: disable this for non-debug builds
if (QFile::exists("main.qml"))
setSource(QUrl::fromLocalFile("./main.qml"));
else
setSource(QUrl("qrc:/qml/main.qml"));
setResizeMode(SizeRootObjectToView);
setAttribute(Qt::WA_OpaquePaintEvent);
setAttribute(Qt::WA_NoSystemBackground);
QDeclarativeEngine *e = engine();
e->addImageProvider(QLatin1String("windows"), new WindowPixmapProvider);
}
MainWindow::~MainWindow()
{
mainWindowInstance = NULL;
}
MainWindow *MainWindow::instance(bool create)
{
if (mainWindowInstance == NULL && create) {
// The static instance variable is set in the constructor
new MainWindow;
}
return mainWindowInstance;
}
void MainWindow::excludeFromTaskBar()
{
// Tell the window to not to be shown in the switcher
Atom skipTaskbarAtom = X11Wrapper::XInternAtom(QX11Info::display(), "_NET_WM_STATE_SKIP_TASKBAR", False);
changeNetWmState(true, skipTaskbarAtom);
// Also set the _NET_WM_STATE window property to ensure Home doesn't try to
// manage this window in case the window manager fails to set the property in time
Atom netWmStateAtom = X11Wrapper::XInternAtom(QX11Info::display(), "_NET_WM_STATE", False);
QVector<Atom> atoms;
atoms.append(skipTaskbarAtom);
X11Wrapper::XChangeProperty(QX11Info::display(), internalWinId(), netWmStateAtom, XA_ATOM, 32, PropModeReplace, (unsigned char *)atoms.data(), atoms.count());
}
void MainWindow::changeNetWmState(bool set, Atom one, Atom two)
{
XEvent e;
e.xclient.type = ClientMessage;
Display *display = QX11Info::display();
Atom netWmStateAtom = X11Wrapper::XInternAtom(display, "_NET_WM_STATE", FALSE);
e.xclient.message_type = netWmStateAtom;
e.xclient.display = display;
e.xclient.window = internalWinId();
e.xclient.format = 32;
e.xclient.data.l[0] = set ? 1 : 0;
e.xclient.data.l[1] = one;
e.xclient.data.l[2] = two;
e.xclient.data.l[3] = 0;
e.xclient.data.l[4] = 0;
X11Wrapper::XSendEvent(display, RootWindow(display, x11Info().screen()), FALSE, (SubstructureNotifyMask | SubstructureRedirectMask), &e);
}
bool MainWindow::isCallUILaunchingKey(int key)
{
// Numbers, *, + and # will launch the call UI
return ((key >= Qt::Key_0 && key <= Qt::Key_9) || key == Qt::Key_Asterisk || key == Qt::Key_Plus || key == Qt::Key_NumberSign);
}
void MainWindow::keyPressEvent(QKeyEvent *event)
{
int key = event->key();
if (key < Qt::Key_Escape && !event->modifiers().testFlag(Qt::ControlModifier)) {
// Special keys and CTRL-anything should do nothing
QString keyPresses = event->text();
if (!keyPresses.isEmpty()) {
// Append keypresses to the presses to be sent
keyPressesToBeSent.append(keyPresses);
if (keyPressesBeingSent.isEmpty()) {
// Select the service to send the keypresses to
if (isCallUILaunchingKey(key)) {
setupExternalService(CALL_UI_DBUS_SERVICE, CALL_UI_DBUS_PATH, CALL_UI_DBUS_INTERFACE, CALL_UI_DBUS_METHOD);
} else {
setupExternalService(CONTENT_SEARCH_DBUS_SERVICE, CONTENT_SEARCH_DBUS_PATH, CONTENT_SEARCH_DBUS_INTERFACE, CONTENT_SEARCH_DBUS_METHOD);
}
// Call the external service
sendKeyPresses();
}
}
}
}
void MainWindow::closeEvent(QCloseEvent *event)
{
// Don't allow closing the main window
event->ignore();
}
void MainWindow::setupExternalService(const QString &service, const QString &path, const QString &interface, const QString &method)
{
externalServiceService = &service;
externalServicePath = &path;
externalServiceInterface = &interface;
externalServiceMethod = &method;
}
void MainWindow::sendKeyPresses()
{
// Only one external service launch may be active at a time
if (keyPressesBeingSent.isEmpty() && !keyPressesToBeSent.isEmpty() && externalServiceService != NULL && externalServicePath != NULL && externalServiceInterface != NULL && externalServiceMethod != NULL) {
// Make an asynchronous call to the external service and send the keypresses to be sent
QDBusInterface interface(*externalServiceService, *externalServicePath, *externalServiceInterface, QDBusConnection::sessionBus());
interface.callWithCallback(*externalServiceMethod, (QList<QVariant>() << keyPressesToBeSent), this, SLOT(markKeyPressesSentAndSendRemainingKeyPresses()), SLOT(markKeyPressesNotSent()));
// Keypresses that need to be sent are now being sent
keyPressesBeingSent = keyPressesToBeSent;
keyPressesToBeSent.clear();
}
}
void MainWindow::markKeyPressesSentAndSendRemainingKeyPresses()
{
// The keypresses that were being sent have now been sent
keyPressesBeingSent.clear();
// Send the remaining keypresses still to be sent (if any)
sendKeyPresses();
}
void MainWindow::markKeyPressesNotSent()
{
// Since the external service didn't launch prepend the sent keypresses to the keypresses to be sent but don't retry
keyPressesToBeSent.prepend(keyPressesBeingSent);
keyPressesBeingSent.clear();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: PaneChildWindows.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: hr $ $Date: 2005-10-24 16:15:40 $
*
* 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
*
************************************************************************/
#include "PaneChildWindows.hxx"
#include "PaneDockingWindow.hrc"
#include "app.hrc"
#include "sdresid.hxx"
#include <sfx2/app.hxx>
#include <sfx2/dockwin.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/dispatch.hxx>
namespace sd
{
// We use SID_LEFT_PANE_IMPRESS and SID_LEFT_PANE_IMPRESS_DRAW to have
// separate strings. Internally we use SID_LEFT_PANE_IMPESS for
// controlling the visibility of the left pane.
SFX_IMPL_DOCKINGWINDOW(LeftPaneChildWindow, SID_LEFT_PANE_IMPRESS)
SFX_IMPL_DOCKINGWINDOW(RightPaneChildWindow, SID_RIGHT_PANE)
}
#include "PaneDockingWindow.hxx"
#include "ViewShellBase.hxx"
namespace sd {
//===== LeftPaneChildWindow ===================================================
LeftPaneChildWindow::LeftPaneChildWindow (
::Window* pParentWindow,
USHORT nId,
SfxBindings* pBindings,
SfxChildWinInfo* pInfo)
: SfxChildWindow (pParentWindow, nId)
{
ViewShellBase* pBase = ViewShellBase::GetViewShellBase(pBindings->GetDispatcher()->GetFrame());
if (pBase != NULL)
{
PaneManager& rPaneManager (pBase->GetPaneManager());
pWindow = new PaneDockingWindow (
pBindings,
this,
pParentWindow,
rPaneManager.GetDockingWindowTitle(PaneManager::PT_LEFT),
PaneManager::PT_LEFT,
rPaneManager.GetWindowTitle(PaneManager::PT_LEFT));
eChildAlignment = SFX_ALIGN_LEFT;
static_cast<SfxDockingWindow*>(pWindow)->Initialize (pInfo);
SetHideNotDelete (TRUE);
rPaneManager.SetWindow(PaneManager::PT_LEFT, pWindow);
}
}
LeftPaneChildWindow::~LeftPaneChildWindow (void)
{
ViewShellBase* pBase = NULL;
PaneDockingWindow* pDockingWindow = dynamic_cast<PaneDockingWindow*>(pWindow);
if (pDockingWindow != NULL)
pBase = ViewShellBase::GetViewShellBase(
pDockingWindow->GetBindings().GetDispatcher()->GetFrame());
if (pBase != NULL)
{
// Tell the ViewShellBase that the window of this slide sorter is
// not available anymore.
pBase->GetPaneManager().SetWindow(PaneManager::PT_LEFT, NULL);
}
}
//===== RightPaneChildWindow ==================================================
RightPaneChildWindow::RightPaneChildWindow (
::Window* pParentWindow,
USHORT nId,
SfxBindings* pBindings,
SfxChildWinInfo* pInfo)
: SfxChildWindow (pParentWindow, nId)
{
ViewShellBase* pBase = ViewShellBase::GetViewShellBase(pBindings->GetDispatcher()->GetFrame());
if (pBase != NULL)
{
PaneManager& rPaneManager (pBase->GetPaneManager());
pWindow = new PaneDockingWindow (
pBindings,
this,
pParentWindow,
rPaneManager.GetDockingWindowTitle(PaneManager::PT_RIGHT),
PaneManager::PT_RIGHT,
rPaneManager.GetWindowTitle(PaneManager::PT_RIGHT));
eChildAlignment = SFX_ALIGN_RIGHT;
static_cast<SfxDockingWindow*>(pWindow)->Initialize (pInfo);
SetHideNotDelete (TRUE);
rPaneManager.SetWindow(PaneManager::PT_RIGHT, pWindow);
}
};
RightPaneChildWindow::~RightPaneChildWindow (void)
{
ViewShellBase* pBase = NULL;
PaneDockingWindow* pDockingWindow = dynamic_cast<PaneDockingWindow*>(pWindow);
if (pDockingWindow != NULL)
pBase = ViewShellBase::GetViewShellBase(
pDockingWindow->GetBindings().GetDispatcher()->GetFrame());
if (pBase != NULL)
{
// Tell the ViewShellBase that the window of this slide sorter is
// not available anymore.
pBase->GetPaneManager().SetWindow(PaneManager::PT_RIGHT, NULL);
}
}
} // end of namespace ::sd
<commit_msg>INTEGRATION: CWS pchfix02 (1.5.248); FILE MERGED 2006/09/01 17:36:56 kaib 1.5.248.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: PaneChildWindows.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: obo $ $Date: 2006-09-16 18:34:11 $
*
* 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
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sd.hxx"
#include "PaneChildWindows.hxx"
#include "PaneDockingWindow.hrc"
#include "app.hrc"
#include "sdresid.hxx"
#include <sfx2/app.hxx>
#include <sfx2/dockwin.hxx>
#include <sfx2/bindings.hxx>
#include <sfx2/dispatch.hxx>
namespace sd
{
// We use SID_LEFT_PANE_IMPRESS and SID_LEFT_PANE_IMPRESS_DRAW to have
// separate strings. Internally we use SID_LEFT_PANE_IMPESS for
// controlling the visibility of the left pane.
SFX_IMPL_DOCKINGWINDOW(LeftPaneChildWindow, SID_LEFT_PANE_IMPRESS)
SFX_IMPL_DOCKINGWINDOW(RightPaneChildWindow, SID_RIGHT_PANE)
}
#include "PaneDockingWindow.hxx"
#include "ViewShellBase.hxx"
namespace sd {
//===== LeftPaneChildWindow ===================================================
LeftPaneChildWindow::LeftPaneChildWindow (
::Window* pParentWindow,
USHORT nId,
SfxBindings* pBindings,
SfxChildWinInfo* pInfo)
: SfxChildWindow (pParentWindow, nId)
{
ViewShellBase* pBase = ViewShellBase::GetViewShellBase(pBindings->GetDispatcher()->GetFrame());
if (pBase != NULL)
{
PaneManager& rPaneManager (pBase->GetPaneManager());
pWindow = new PaneDockingWindow (
pBindings,
this,
pParentWindow,
rPaneManager.GetDockingWindowTitle(PaneManager::PT_LEFT),
PaneManager::PT_LEFT,
rPaneManager.GetWindowTitle(PaneManager::PT_LEFT));
eChildAlignment = SFX_ALIGN_LEFT;
static_cast<SfxDockingWindow*>(pWindow)->Initialize (pInfo);
SetHideNotDelete (TRUE);
rPaneManager.SetWindow(PaneManager::PT_LEFT, pWindow);
}
}
LeftPaneChildWindow::~LeftPaneChildWindow (void)
{
ViewShellBase* pBase = NULL;
PaneDockingWindow* pDockingWindow = dynamic_cast<PaneDockingWindow*>(pWindow);
if (pDockingWindow != NULL)
pBase = ViewShellBase::GetViewShellBase(
pDockingWindow->GetBindings().GetDispatcher()->GetFrame());
if (pBase != NULL)
{
// Tell the ViewShellBase that the window of this slide sorter is
// not available anymore.
pBase->GetPaneManager().SetWindow(PaneManager::PT_LEFT, NULL);
}
}
//===== RightPaneChildWindow ==================================================
RightPaneChildWindow::RightPaneChildWindow (
::Window* pParentWindow,
USHORT nId,
SfxBindings* pBindings,
SfxChildWinInfo* pInfo)
: SfxChildWindow (pParentWindow, nId)
{
ViewShellBase* pBase = ViewShellBase::GetViewShellBase(pBindings->GetDispatcher()->GetFrame());
if (pBase != NULL)
{
PaneManager& rPaneManager (pBase->GetPaneManager());
pWindow = new PaneDockingWindow (
pBindings,
this,
pParentWindow,
rPaneManager.GetDockingWindowTitle(PaneManager::PT_RIGHT),
PaneManager::PT_RIGHT,
rPaneManager.GetWindowTitle(PaneManager::PT_RIGHT));
eChildAlignment = SFX_ALIGN_RIGHT;
static_cast<SfxDockingWindow*>(pWindow)->Initialize (pInfo);
SetHideNotDelete (TRUE);
rPaneManager.SetWindow(PaneManager::PT_RIGHT, pWindow);
}
};
RightPaneChildWindow::~RightPaneChildWindow (void)
{
ViewShellBase* pBase = NULL;
PaneDockingWindow* pDockingWindow = dynamic_cast<PaneDockingWindow*>(pWindow);
if (pDockingWindow != NULL)
pBase = ViewShellBase::GetViewShellBase(
pDockingWindow->GetBindings().GetDispatcher()->GetFrame());
if (pBase != NULL)
{
// Tell the ViewShellBase that the window of this slide sorter is
// not available anymore.
pBase->GetPaneManager().SetWindow(PaneManager::PT_RIGHT, NULL);
}
}
} // end of namespace ::sd
<|endoftext|> |
<commit_before>#ifndef ENGINE_UTIL_MATH_HPP
#define ENGINE_UTIL_MATH_HPP
#include <SFML/System.hpp>
#include <Box2D/Box2D.h>
namespace engine {
const float fPI = 3.141592654f;
float b2AngleDeg(b2Vec2 from, b2Vec2 to);
inline bool floatEqual(float a, float b, float epsilon) {
return fabsf(a - b) < epsilon;
}
inline bool floatEqual(const b2Vec2& a, const b2Vec2& b, float epsilon) {
return floatEqual(a.x, b.x, epsilon) && floatEqual(a.y, b.y, epsilon);
}
inline float b2Angle(b2Vec2 from, b2Vec2 to) {
to -= from;
return atan2f(to.y, to.x);
}
inline float b2Angle(sf::Vector2f from, sf::Vector2f to) {
to -= from;
return atan2f(to.y, to.x);
}
}
#endif
<commit_msg>Distance helper function<commit_after>#ifndef ENGINE_UTIL_MATH_HPP
#define ENGINE_UTIL_MATH_HPP
#include <SFML/System.hpp>
#include <Box2D/Box2D.h>
namespace engine {
const float fPI = 3.141592654f;
float b2AngleDeg(b2Vec2 from, b2Vec2 to);
inline bool floatEqual(float a, float b, float epsilon) {
return fabsf(a - b) < epsilon;
}
inline bool floatEqual(const b2Vec2& a, const b2Vec2& b, float epsilon) {
return floatEqual(a.x, b.x, epsilon) && floatEqual(a.y, b.y, epsilon);
}
inline float b2Angle(b2Vec2 from, b2Vec2 to) {
to -= from;
return atan2f(to.y, to.x);
}
inline float b2Angle(sf::Vector2f from, sf::Vector2f to) {
to -= from;
return atan2f(to.y, to.x);
}
template<typename T>
inline float distance(sf::Vector2<T> from, sf::Vector2<T> to) {
return static_cast<T>(sqrt(
static_cast<double>(
(to.x - from.x) * (to.x - from.x) +
(to.y - from.y) * (to.y - from.y)
)
));
}
}
#endif
<|endoftext|> |
<commit_before>#pragma once
/**
* \file environment.hpp
*
* This header provides an object that can be used to retrieve the necessary
* information about the parallel environment of a layer.
*/
#include <functional>
namespace bulk {
class world;
/**
* This object encodes the parallel environment of this layer, and
* provides information on the system.
*/
class environment {
public:
/**
* Start an spmd section on a given number of processors.
*
* \param processors the number of processors to run on
* \param spmd the spmd function that gets run on each (virtual) processor
*/
virtual void spawn(int processors,
std::function<void(bulk::world&, int, int)> spmd) = 0;
/**
* Retrieve the total number of processors available on the system
*
* \returns the number of available processors
*/
virtual int available_processors() const = 0;
/**
* Set a callback that receives output from `world::log` and
* `world::log_direct`. If no callback is set, the results will
* be printed to standard output.
*
* The first argument to the callback is the processor id
* and the second argument is the logged message.
*
* The callback must be set before calling `spawn`.
*
* On multicore systems the callback could be called from a different
* thread. It is guaranteed that there will not be two calls to the
* callback at the same time, so there is no need for further
* synchronization or locking mechanisms.
*/
virtual void set_log_callback(std::function<void(int, const std::string&)> f) = 0;
};
} // namespace bulk
<commit_msg>Add virtual deconstructor to environment<commit_after>#pragma once
/**
* \file environment.hpp
*
* This header provides an object that can be used to retrieve the necessary
* information about the parallel environment of a layer.
*/
#include <functional>
namespace bulk {
class world;
/**
* This object encodes the parallel environment of this layer, and
* provides information on the system.
*/
class environment {
public:
virtual ~environment() = default;
/**
* Start an spmd section on a given number of processors.
*
* \param processors the number of processors to run on
* \param spmd the spmd function that gets run on each (virtual) processor
*/
virtual void spawn(int processors,
std::function<void(bulk::world&, int, int)> spmd) = 0;
/**
* Retrieve the total number of processors available on the system
*
* \returns the number of available processors
*/
virtual int available_processors() const = 0;
/**
* Set a callback that receives output from `world::log` and
* `world::log_direct`. If no callback is set, the results will
* be printed to standard output.
*
* The first argument to the callback is the processor id
* and the second argument is the logged message.
*
* The callback must be set before calling `spawn`.
*
* On multicore systems the callback could be called from a different
* thread. It is guaranteed that there will not be two calls to the
* callback at the same time, so there is no need for further
* synchronization or locking mechanisms.
*/
virtual void set_log_callback(
std::function<void(int, const std::string&)> f) = 0;
};
} // namespace bulk
<|endoftext|> |
<commit_before>
#pragma once
#include "utils.hpp"
#include "cookie_builder.hpp"
#include <boost/noncopyable.hpp>
#include <boost/asio/streambuf.hpp>
#include "lexical_cast.hpp"
#include <boost/format.hpp>
#include <functional>
#include <cassert>
#include <map>
#include <sstream>
#include <time.h>
namespace cinatra
{
class Response : boost::noncopyable
{
friend class Connection;
public:
Response()
:status_code_(200),
version_major_(1),
version_minor_(0),
is_complete_(false),
is_chunked_encoding_(false),
has_chunked_encoding_header_(false)
{}
NcaseMultiMap header;
bool write(const char* data, std::size_t len)
{
assert(!is_chunked_encoding_);
assert(!is_complete_);
if (is_chunked_encoding_ && is_complete_)
{
return false;
}
return size_t(buffer_.sputn(data, len)) == len;
}
bool write(const std::string& text)
{
return write(text.data(), text.size());
}
bool direct_write(const char* data, std::size_t len)
{
assert(buffer_.size() == 0);
assert(!is_complete_);
if (buffer_.size() != 0 || is_complete_)
{
return false;
}
is_chunked_encoding_ = true;
boost::asio::streambuf buf;
if (!has_chunked_encoding_header_)
{
header.add("Transfer-Encoding", "chunked");
has_chunked_encoding_header_ = true;
std::string str = get_header_str();
buf.sputn(str.data(), str.size());
}
//要发送数据的长度.
std::stringstream ss;
ss << std::hex << len;
std::string str;
ss >> str;
str += "\r\n";
buf.sputn(str.data(), str.size());
buf.sputn(data, len);
buf.sputn("\r\n", 2);
boost::asio::const_buffer b = buf.data();
const char* p = boost::asio::buffer_cast<const char*>(b);
return direct_write_func_(p,buf.size());
}
bool direct_write(const std::string& text)
{
return direct_write(text.data(), text.size());
}
bool end(const char* data, std::size_t len)
{
return write(data, len) && end();
}
bool end(const std::string& text)
{
return end(text.data(), text.size());
}
bool end()
{
assert(!is_complete_);
if (is_complete_)
{
return false;
}
if (is_chunked_encoding_)
{
if (!direct_write_func_("0\r\n\r\n", 5))
{
return false;
}
}
is_complete_ = true;
return true;
}
void set_status_code(int code)
{
status_code_ = code;
}
void set_version(int major, int minor)
{
version_major_ = major;
version_minor_ = minor;
}
std::string get_header_str()
{
header_str.clear();
auto s = status_header(status_code_);
string shttp = "";
if (version_minor_ == 1)
shttp = "HTTP/1.1 ";
else
shttp = "HTTP/1.0 ";
header_str.reserve(shttp.length() + s.second.length() + header_date_str().length() + 38);
header_str = shttp + s.second + "\r\nServer: cinatra/0.1\r\nDate: " + header_date_str() + "\r\n";
if (!is_chunked_encoding_)
{
header_str += "Content-Length: ";
header_str += lexical_cast<std::string>(buffer_.size());
header_str += "\r\n";
}
for (auto& iter : header.get_all())
{
header_str += iter.first;
header_str += ": ";
header_str += iter.second;
header_str += "\r\n";
}
header_str += cookie_builder_.to_string();
header_str += "\r\n";
return header_str;
}
cookie_builder& cookies()
{
return cookie_builder_;
}
void redirect(const std::string& url)
{
set_status_code(302);
header.add("Location", url);
end("<p>Moved Temporarily. Redirecting to <a href=\"" + url + "\">/</a></p>");
}
bool is_complete() const
{
return is_complete_;
}
private:
int status_code_;
int version_major_;
int version_minor_;
std::function < bool(const char*, std::size_t) >
direct_write_func_;
bool is_complete_;
boost::asio::streambuf buffer_;
// 是否是chunked编码.
bool is_chunked_encoding_;
// 是否已经在header中添加了Transfer-Encoding: chunked.
bool has_chunked_encoding_header_;
cookie_builder cookie_builder_;
string header_str;
};
}
<commit_msg>增加context<commit_after>
#pragma once
#include "utils.hpp"
#include "cookie_builder.hpp"
#include <boost/noncopyable.hpp>
#include <boost/asio/streambuf.hpp>
#include "lexical_cast.hpp"
#include <boost/format.hpp>
#include <boost/any.hpp>
#include <functional>
#include <cassert>
#include <map>
#include <sstream>
#include <time.h>
namespace cinatra
{
class Response : boost::noncopyable
{
friend class Connection;
public:
Response()
:status_code_(200),
version_major_(1),
version_minor_(0),
is_complete_(false),
is_chunked_encoding_(false),
has_chunked_encoding_header_(false)
{}
NcaseMultiMap header;
bool write(const char* data, std::size_t len)
{
assert(!is_chunked_encoding_);
assert(!is_complete_);
if (is_chunked_encoding_ && is_complete_)
{
return false;
}
return size_t(buffer_.sputn(data, len)) == len;
}
bool write(const std::string& text)
{
return write(text.data(), text.size());
}
bool direct_write(const char* data, std::size_t len)
{
assert(buffer_.size() == 0);
assert(!is_complete_);
if (buffer_.size() != 0 || is_complete_)
{
return false;
}
is_chunked_encoding_ = true;
boost::asio::streambuf buf;
if (!has_chunked_encoding_header_)
{
header.add("Transfer-Encoding", "chunked");
has_chunked_encoding_header_ = true;
std::string str = get_header_str();
buf.sputn(str.data(), str.size());
}
//要发送数据的长度.
std::stringstream ss;
ss << std::hex << len;
std::string str;
ss >> str;
str += "\r\n";
buf.sputn(str.data(), str.size());
buf.sputn(data, len);
buf.sputn("\r\n", 2);
boost::asio::const_buffer b = buf.data();
const char* p = boost::asio::buffer_cast<const char*>(b);
return direct_write_func_(p,buf.size());
}
bool direct_write(const std::string& text)
{
return direct_write(text.data(), text.size());
}
bool end(const char* data, std::size_t len)
{
return write(data, len) && end();
}
bool end(const std::string& text)
{
return end(text.data(), text.size());
}
bool end()
{
assert(!is_complete_);
if (is_complete_)
{
return false;
}
if (is_chunked_encoding_)
{
if (!direct_write_func_("0\r\n\r\n", 5))
{
return false;
}
}
is_complete_ = true;
return true;
}
void set_status_code(int code)
{
status_code_ = code;
}
void set_version(int major, int minor)
{
version_major_ = major;
version_minor_ = minor;
}
std::string get_header_str()
{
header_str.clear();
auto s = status_header(status_code_);
string shttp = "";
if (version_minor_ == 1)
shttp = "HTTP/1.1 ";
else
shttp = "HTTP/1.0 ";
header_str.reserve(shttp.length() + s.second.length() + header_date_str().length() + 38);
header_str = shttp + s.second + "\r\nServer: cinatra/0.1\r\nDate: " + header_date_str() + "\r\n";
if (!is_chunked_encoding_)
{
header_str += "Content-Length: ";
header_str += lexical_cast<std::string>(buffer_.size());
header_str += "\r\n";
}
for (auto& iter : header.get_all())
{
header_str += iter.first;
header_str += ": ";
header_str += iter.second;
header_str += "\r\n";
}
header_str += cookie_builder_.to_string();
header_str += "\r\n";
return header_str;
}
cookie_builder& cookies()
{
return cookie_builder_;
}
void redirect(const std::string& url)
{
set_status_code(302);
header.add("Location", url);
end("<p>Moved Temporarily. Redirecting to <a href=\"" + url + "\">/</a></p>");
}
bool is_complete() const
{
return is_complete_;
}
std::map<int, boost::any>& context()
{
return context_;
}
private:
int status_code_;
int version_major_;
int version_minor_;
std::function < bool(const char*, std::size_t) >
direct_write_func_;
bool is_complete_;
boost::asio::streambuf buffer_;
// 是否是chunked编码.
bool is_chunked_encoding_;
// 是否已经在header中添加了Transfer-Encoding: chunked.
bool has_chunked_encoding_header_;
cookie_builder cookie_builder_;
string header_str;
std::map<int, boost::any> context_;
};
}
<|endoftext|> |
<commit_before>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008, 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef FLUSSPFERD_VALUE_HPP
#define FLUSSPFERD_VALUE_HPP
#include "spidermonkey/value.hpp"
#include <string>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/is_integral.hpp>
#include <boost/type_traits/is_floating_point.hpp>
#include <boost/type_traits/is_convertible.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/mpl/logical.hpp>
namespace flusspferd {
class object;
class string;
template<typename T> class convert;
/**
* Any Javascript value.
*
* @ingroup value_types
*/
class value : public Impl::value_impl {
public:
/// Create a new value (Javascript: <code>undefined</code>).
value();
/// Copy constructor.
value(value const &o)
: Impl::value_impl(o)
{}
#ifndef IN_DOXYGEN
template<typename BoolType>
explicit value(
BoolType const &x,
typename boost::enable_if<
typename boost::is_same<BoolType, bool>::type
>::type * = 0)
: Impl::value_impl(Impl::value_impl::from_boolean(x))
{}
template<typename IntegralType>
explicit value(
IntegralType const &num,
typename boost::enable_if<
typename boost::mpl::and_<
typename boost::is_integral<IntegralType>::type,
typename boost::mpl::not_<
typename boost::is_same<IntegralType, bool>::type
>::type
>::type
>::type * = 0)
: Impl::value_impl(Impl::value_impl::from_integer(num))
{}
template<typename FloatingPointType>
explicit value(
FloatingPointType const &num,
typename boost::enable_if<
typename boost::is_floating_point<FloatingPointType>::type
>::type * = 0)
: Impl::value_impl(Impl::value_impl::from_double(num))
{}
template<typename OtherType>
explicit value(
OtherType const &val,
typename boost::disable_if<
typename boost::mpl::or_<
typename boost::is_integral<OtherType>::type,
typename boost::is_floating_point<OtherType>::type,
typename boost::is_convertible<OtherType, object>::type
>::type
>::type * = 0)
{
typename convert<OtherType>::to_value converter;
*this = converter.perform(val);
}
#else
/**
* Create a new boolean value.
*
* @param b The value.
*/
explicit value(bool b);
/**
* Create a new number value from an integer.
*
* @param num The integer value.
*/
template<typename IntegralType>
explicit value(IntegralType const &num);
/**
* Create a new number value from a floating point number.
*
* @param num The floating point value.
*/
template<typename FloatingPointType>
explicit value(FloatingPointType const &num);
#endif
/**
* Create a new object value.
*
* @param o The object.
*/
value(object const &o)
: Impl::value_impl(Impl::value_impl::from_object(o))
{}
/**
* Create a new string value.
*
* @param s The string.
*/
value(string const &s)
: Impl::value_impl(Impl::value_impl::from_string(s))
{}
/// Destructor.
~value();
#ifndef IN_DOXYGEN
value(Impl::value_impl const &v)
: Impl::value_impl(v)
{ }
#endif
// Assignment operator.
value &operator=(value const &v) {
*static_cast<Impl::value_impl*>(this) = v;
return *this;
}
// Assignment operator.
template<typename T>
value &operator=(T const &x) {
*this = value(x);
return *this;
}
/**
* Bind to another value.
*
* The value will act as a reference to @p o.
*
* @param o The value to bind to.
*/
void bind(value o);
/**
* Unbind the value.
*
* If the value is a reference to another value, the binding will be removed.
* Also, the value will be reset to (Javascript) <code>undefined</code>.
*/
void unbind();
/// Check if the value is <code>null</code>.
bool is_null() const;
// Check if the value is <code>undefined</code>.
bool is_undefined() const;
// Check if the value is <code>undefined</code> or <code>null</code>.
bool is_undefined_or_null() const { return is_null() || is_undefined(); }
/// Check if the value is an int.
bool is_int() const;
/// Check if the value is a double.
bool is_double() const;
/// Check if the value is a number.
bool is_number() const;
/// Check if the value is boolean.
bool is_boolean() const;
/// Check if the value is a string.
bool is_string() const;
/// Check if the value is an object.
bool is_object() const;
/// Check if the value is a function.
bool is_function() const;
/// Check if the value is boolean.
bool is_bool() const { return is_boolean(); }
/// Get the boolean value.
bool get_boolean() const;
/// Get the boolean value.
bool get_bool() const { return get_boolean(); }
/// Get the int value.
int get_int() const;
/// Get the double value.
double get_double() const;
/// Get the object value.
object get_object() const;
/// Get the string value.
string get_string() const;
/// Convert the value to a string.
string to_string() const;
/// Convert the value to a C++ standard library string (std::string)
std::string to_std_string() const;
/// Convert the number to a number.
double to_number() const;
/// Convert the value to an integral number.
double to_integral_number(int bits, bool has_negative) const;
/// Convert the value to a boolean.
bool to_boolean() const;
/// Convert the value to an object.
object to_object() const;
};
}
#include "convert.hpp"
#endif /* FLUSSPFERD_VALUE_HPP */
<commit_msg>core: value: add documentation for converting constructor<commit_after>// vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:
/*
Copyright (c) 2008, 2009 Aristid Breitkreuz, Ash Berlin, Ruediger Sonderfeld
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef FLUSSPFERD_VALUE_HPP
#define FLUSSPFERD_VALUE_HPP
#include "spidermonkey/value.hpp"
#include <string>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/is_integral.hpp>
#include <boost/type_traits/is_floating_point.hpp>
#include <boost/type_traits/is_convertible.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/mpl/logical.hpp>
namespace flusspferd {
class object;
class string;
template<typename T> class convert;
/**
* Any Javascript value.
*
* @ingroup value_types
*/
class value : public Impl::value_impl {
public:
/// Create a new value (Javascript: <code>undefined</code>).
value();
/// Copy constructor.
value(value const &o)
: Impl::value_impl(o)
{}
#ifndef IN_DOXYGEN
template<typename BoolType>
explicit value(
BoolType const &x,
typename boost::enable_if<
typename boost::is_same<BoolType, bool>::type
>::type * = 0)
: Impl::value_impl(Impl::value_impl::from_boolean(x))
{}
template<typename IntegralType>
explicit value(
IntegralType const &num,
typename boost::enable_if<
typename boost::mpl::and_<
typename boost::is_integral<IntegralType>::type,
typename boost::mpl::not_<
typename boost::is_same<IntegralType, bool>::type
>::type
>::type
>::type * = 0)
: Impl::value_impl(Impl::value_impl::from_integer(num))
{}
template<typename FloatingPointType>
explicit value(
FloatingPointType const &num,
typename boost::enable_if<
typename boost::is_floating_point<FloatingPointType>::type
>::type * = 0)
: Impl::value_impl(Impl::value_impl::from_double(num))
{}
template<typename OtherType>
explicit value(
OtherType const &val,
typename boost::disable_if<
typename boost::mpl::or_<
typename boost::is_integral<OtherType>::type,
typename boost::is_floating_point<OtherType>::type,
typename boost::is_convertible<OtherType, object>::type
>::type
>::type * = 0)
{
typename convert<OtherType>::to_value converter;
*this = converter.perform(val);
}
#else
/**
* Create a new boolean value.
*
* @param b The value.
*/
explicit value(bool b);
/**
* Create a new number value from an integer.
*
* @param num The integer value.
*/
template<typename IntegralType>
explicit value(IntegralType const &num);
/**
* Create a new number value from a floating point number.
*
* @param num The floating point value.
*/
template<typename FloatingPointType>
explicit value(FloatingPointType const &num);
/**
* Create a new value from a (nearly) arbitrary C++ type value.
*
* Works with any type supported by flusspferd::convert. This overload will
* not be used for integral types, floating point types or types convertible
* to flusspferd::object.
*
* @param val The value to convert.
*/
template<typename OtherType>
explicit value(OtherType const &val);
#endif
/**
* Create a new object value.
*
* @param o The object.
*/
value(object const &o)
: Impl::value_impl(Impl::value_impl::from_object(o))
{}
/**
* Create a new string value.
*
* @param s The string.
*/
value(string const &s)
: Impl::value_impl(Impl::value_impl::from_string(s))
{}
/// Destructor.
~value();
#ifndef IN_DOXYGEN
value(Impl::value_impl const &v)
: Impl::value_impl(v)
{ }
#endif
// Assignment operator.
value &operator=(value const &v) {
*static_cast<Impl::value_impl*>(this) = v;
return *this;
}
// Assignment operator.
template<typename T>
value &operator=(T const &x) {
*this = value(x);
return *this;
}
/**
* Bind to another value.
*
* The value will act as a reference to @p o.
*
* @param o The value to bind to.
*/
void bind(value o);
/**
* Unbind the value.
*
* If the value is a reference to another value, the binding will be removed.
* Also, the value will be reset to (Javascript) <code>undefined</code>.
*/
void unbind();
/// Check if the value is <code>null</code>.
bool is_null() const;
// Check if the value is <code>undefined</code>.
bool is_undefined() const;
// Check if the value is <code>undefined</code> or <code>null</code>.
bool is_undefined_or_null() const { return is_null() || is_undefined(); }
/// Check if the value is an int.
bool is_int() const;
/// Check if the value is a double.
bool is_double() const;
/// Check if the value is a number.
bool is_number() const;
/// Check if the value is boolean.
bool is_boolean() const;
/// Check if the value is a string.
bool is_string() const;
/// Check if the value is an object.
bool is_object() const;
/// Check if the value is a function.
bool is_function() const;
/// Check if the value is boolean.
bool is_bool() const { return is_boolean(); }
/// Get the boolean value.
bool get_boolean() const;
/// Get the boolean value.
bool get_bool() const { return get_boolean(); }
/// Get the int value.
int get_int() const;
/// Get the double value.
double get_double() const;
/// Get the object value.
object get_object() const;
/// Get the string value.
string get_string() const;
/// Convert the value to a string.
string to_string() const;
/// Convert the value to a C++ standard library string (std::string)
std::string to_std_string() const;
/// Convert the number to a number.
double to_number() const;
/// Convert the value to an integral number.
double to_integral_number(int bits, bool has_negative) const;
/// Convert the value to a boolean.
bool to_boolean() const;
/// Convert the value to an object.
object to_object() const;
};
}
#include "convert.hpp"
#endif /* FLUSSPFERD_VALUE_HPP */
<|endoftext|> |
<commit_before>#include "../utils/utils.hpp"
#include <cstdio>
#include <vector>
#include <algorithm>
struct DockRobot {
struct Pile;
struct Cranes;
struct Loc {
bool operator==(const Loc &o) const {
return cranes == o.cranes && piles == o.piles;
}
bool operator!=(const Loc &o) const {
return !(*this == o);
}
// pop pops the given pile, returning the box.
unsigned int pop(unsigned int p);
// push pushes the given box into the given pile
// If the pile number is greater than the current
// number of piles then a new pile is created.
void push(unsigned int b, unsigned int p);
// rmcrane removes the crane, returning its box.
unsigned int rmcrane(unsigned int);
// addcrane adds a new crane with the given box.
void addcrane(unsigned int);
// findpile returns the index of the pile with the
// given bottom box.
int findpile(unsigned int box) {
unsigned int l = 0, u = piles.size();
if (u == 0)
return -1;
// define: piles[-1] ≡ -∞ and piles[piles.size] ≡ ∞
// invariant: l - 1 < box and u ≥ box
while (l < u) {
unsigned int m = ((u - l) >> 1) + l;
if (piles[m].stack[0] < box)
l = m + 1; // l - 1 < box
else
u = m; // u >= box
}
return (l < piles.size() && piles[l].stack[0] == box) ? l : -1;
}
// findcrane returns the index of the crane with the
// given box.
int findcrane(unsigned int box) {
unsigned int l = 0, u = cranes.size();
if (u == 0)
return -1;
while (l < u) {
unsigned int m = ((u - l) >> 1) + l;
if (cranes[m] < box)
l = m + 1;
else
u = m;
}
return (l < cranes.size() && cranes[l] == box) ? l : -1;
}
std::vector<unsigned int> cranes;
std::vector<Pile> piles;
};
struct Pile {
Pile() { }
// Construct a new pile with a single box.
Pile(unsigned int b) : stack(1) {
stack[0] = b;
}
// operator< orders piles by their bottom stack element.
bool operator<(const Pile &o) const {
return stack[0] < o.stack[0];
}
bool operator==(const Pile &o) const {
return stack == o.stack;
}
// stack is the stack of boxes in this pile.
std::vector<unsigned int> stack;
};
typedef float Cost;
struct Oper {
enum OpType { None, Push, Pop, Load, Unload, Move };
Oper(OpType t = None, unsigned int x0 = 0, unsigned int y0 = 0) :
type(t), x(x0), y(y0) { }
bool operator==(const Oper &o) const {
return x == o.x && type == o.type && y == o.y;
}
OpType type;
unsigned int x, y;
};
static const Oper Nop;
// creates a dummy instance with the given number of locations.
DockRobot(unsigned int);
DockRobot(FILE*);
class State {
public:
State() { }
State(const DockRobot&, const std::vector<Loc>&&, int, unsigned int);
State(const State &o) :
locs(o.locs),
boxlocs(o.boxlocs),
rbox(o.rbox),
rloc(o.rloc),
h(o.h),
d(o.d),
nleft(o.nleft) {
}
State(const State &&o) :
locs(std::move(o.locs)),
boxlocs(std::move(o.boxlocs)),
rbox(o.rbox),
rloc(o.rloc),
h(o.h),
d(o.d),
nleft(o.nleft) {
}
bool operator==(const State &o) const {
if (rloc != o.rloc || rbox != o.rbox || nleft != o.nleft)
return false;
for (unsigned int i = 0; i < locs.size(); i++) {
if (locs[i] != o.locs[i])
return false;
}
return true;
}
// locs is the state of each location.
std::vector<Loc> locs;
// boxlocs is the location of each box.
std::vector<unsigned int> boxlocs;
// rbox is the robot's contents (-1 is empty).
int rbox;
// rloc is the robot's location.
unsigned int rloc;
// h and d are the heuristic and distance estimates.
Cost h, d;
// nleft is the number of packages out of their goal location.
unsigned int nleft;
};
class PackedState {
public:
PackedState() : sz(0), pos(0) { }
~PackedState() {
if (pos) delete[] pos;
}
bool operator==(const PackedState &o) const {
for (unsigned int i = 0; i < sz; i++) {
if (pos[i] != o.pos[i])
return false;
}
return true;
}
unsigned int sz;
unsigned int *pos;
};
State initialstate();
unsigned long hash(const PackedState &p) const {
return hashbytes(reinterpret_cast<unsigned char*>(p.pos),
sizeof(p.pos[0])*p.sz);
}
Cost h(State &s) const {
if (s.h < Cost(0)) {
std::pair<float,float> p = hd(s);
s.h = p.first;
s.d = p.second;
}
return s.h;
}
Cost d(State &s) const {
if (s.d < Cost(0)) {
std::pair<float,float> p = hd(s);
s.h = p.first;
s.d = p.second;
}
return s.d;
}
// Is the given state a goal state?
bool isgoal(const State &s) const {
return s.nleft == 0;
}
struct Operators {
Operators(const DockRobot&, const State&);
unsigned int size() const {
return ops.size();
}
Oper operator[](unsigned int i) const {
return ops[i];
}
private:
std::vector<Oper> ops;
};
struct Edge {
Cost cost;
Oper revop;
State &state;
Cost oldh, oldd;
Edge(const DockRobot &d, State &s, const Oper &o) : state(s), dom(d) {
apply(state, o);
oldh = state.h;
oldd = state.d;
state.h = state.d = Cost(-1);
}
~Edge() {
apply(state, revop);
state.h = oldh;
state.d = oldd;
}
private:
void apply(State&, const Oper&);
// needed to reverse an operator application.
const DockRobot &dom;
};
void pack(PackedState&, const State&);
State &unpack(State&, const PackedState&);
void dumpstate(FILE*, const State&) const;
Cost pathcost(const std::vector<State>&, const std::vector<Oper>&);
private:
friend class State;
friend bool compute_moves_test();
friend bool compute_loads_test();
// initheuristic initializes the heuristic values by computing
// the shortest path between all locations.
void initheuristic();
std::pair<float, float> hd(const State&) const;
// paths holds shortest path information between
// locations used for computing the heuristic.
std::vector< std::pair<float, float> > shortest;
// The number of various things in the dockyard.
unsigned int nlocs, nboxes;
// maxpiles is the maximum number of piles at a given location.
std::vector<unsigned int> maxpiles;
// ncranes is the number of cranes at each location.
std::vector<unsigned int> maxcranes;
// adj is the adjacency matrix for locations.
std::vector< std::vector<float> > adj;
// initlocs is the initial location configurations.
std::vector<Loc> initlocs;
// goal is a vector of the desired location for each box
std::vector<int> goal;
};
<commit_msg>*sigh* fixes for clang.<commit_after>#include "../utils/utils.hpp"
#include <cstdio>
#include <vector>
#include <algorithm>
#include <utility>
struct DockRobot {
struct Pile;
struct Cranes;
struct Loc {
bool operator==(const Loc &o) const {
return cranes == o.cranes && piles == o.piles;
}
bool operator!=(const Loc &o) const {
return !(*this == o);
}
// pop pops the given pile, returning the box.
unsigned int pop(unsigned int p);
// push pushes the given box into the given pile
// If the pile number is greater than the current
// number of piles then a new pile is created.
void push(unsigned int b, unsigned int p);
// rmcrane removes the crane, returning its box.
unsigned int rmcrane(unsigned int);
// addcrane adds a new crane with the given box.
void addcrane(unsigned int);
// findpile returns the index of the pile with the
// given bottom box.
int findpile(unsigned int box) {
unsigned int l = 0, u = piles.size();
if (u == 0)
return -1;
// define: piles[-1] ≡ -∞ and piles[piles.size] ≡ ∞
// invariant: l - 1 < box and u ≥ box
while (l < u) {
unsigned int m = ((u - l) >> 1) + l;
if (piles[m].stack[0] < box)
l = m + 1; // l - 1 < box
else
u = m; // u >= box
}
return (l < piles.size() && piles[l].stack[0] == box) ? l : -1;
}
// findcrane returns the index of the crane with the
// given box.
int findcrane(unsigned int box) {
unsigned int l = 0, u = cranes.size();
if (u == 0)
return -1;
while (l < u) {
unsigned int m = ((u - l) >> 1) + l;
if (cranes[m] < box)
l = m + 1;
else
u = m;
}
return (l < cranes.size() && cranes[l] == box) ? l : -1;
}
std::vector<unsigned int> cranes;
std::vector<Pile> piles;
};
struct Pile {
Pile() { }
// Construct a new pile with a single box.
Pile(unsigned int b) : stack(1) {
stack[0] = b;
}
// operator< orders piles by their bottom stack element.
bool operator<(const Pile &o) const {
return stack[0] < o.stack[0];
}
bool operator==(const Pile &o) const {
return stack == o.stack;
}
// stack is the stack of boxes in this pile.
std::vector<unsigned int> stack;
};
typedef float Cost;
struct Oper {
enum OpType { None, Push, Pop, Load, Unload, Move };
Oper(OpType t = None, unsigned int x0 = 0, unsigned int y0 = 0) :
type(t), x(x0), y(y0) { }
bool operator==(const Oper &o) const {
return x == o.x && type == o.type && y == o.y;
}
OpType type;
unsigned int x, y;
};
static const Oper Nop;
// creates a dummy instance with the given number of locations.
DockRobot(unsigned int);
DockRobot(FILE*);
class State {
public:
State() { }
State(const DockRobot&, const std::vector<Loc>&&, int, unsigned int);
State(const State &o) :
locs(o.locs),
boxlocs(o.boxlocs),
rbox(o.rbox),
rloc(o.rloc),
h(o.h),
d(o.d),
nleft(o.nleft) {
}
State(State &&o) :
locs(std::move(o.locs)),
boxlocs(std::move(o.boxlocs)),
rbox(o.rbox),
rloc(o.rloc),
h(o.h),
d(o.d),
nleft(o.nleft) {
}
State &operator =(const State &o) {
locs = o.locs;
boxlocs = o.boxlocs;
rbox = o.rbox;
rloc = o.rloc;
h = o.h;
d = o.d;
nleft = o.nleft;
return *this;
}
State &operator =(State &&o) {
std::swap(locs, o.locs);
std::swap(boxlocs, o.boxlocs);
rbox = o.rbox;
rloc = o.rloc;
h = o.h;
d = o.d;
nleft = o.nleft;
return *this;
}
bool operator==(const State &o) const {
if (rloc != o.rloc || rbox != o.rbox || nleft != o.nleft)
return false;
for (unsigned int i = 0; i < locs.size(); i++) {
if (locs[i] != o.locs[i])
return false;
}
return true;
}
// locs is the state of each location.
std::vector<Loc> locs;
// boxlocs is the location of each box.
std::vector<unsigned int> boxlocs;
// rbox is the robot's contents (-1 is empty).
int rbox;
// rloc is the robot's location.
unsigned int rloc;
// h and d are the heuristic and distance estimates.
Cost h, d;
// nleft is the number of packages out of their goal location.
unsigned int nleft;
};
class PackedState {
public:
PackedState() : sz(0), pos(0) { }
~PackedState() {
if (pos) delete[] pos;
}
bool operator==(const PackedState &o) const {
for (unsigned int i = 0; i < sz; i++) {
if (pos[i] != o.pos[i])
return false;
}
return true;
}
unsigned int sz;
unsigned int *pos;
};
State initialstate();
unsigned long hash(const PackedState &p) const {
return hashbytes(reinterpret_cast<unsigned char*>(p.pos),
sizeof(p.pos[0])*p.sz);
}
Cost h(State &s) const {
if (s.h < Cost(0)) {
std::pair<float,float> p = hd(s);
s.h = p.first;
s.d = p.second;
}
return s.h;
}
Cost d(State &s) const {
if (s.d < Cost(0)) {
std::pair<float,float> p = hd(s);
s.h = p.first;
s.d = p.second;
}
return s.d;
}
// Is the given state a goal state?
bool isgoal(const State &s) const {
return s.nleft == 0;
}
struct Operators {
Operators(const DockRobot&, const State&);
unsigned int size() const {
return ops.size();
}
Oper operator[](unsigned int i) const {
return ops[i];
}
private:
std::vector<Oper> ops;
};
struct Edge {
Cost cost;
Oper revop;
State &state;
Cost oldh, oldd;
Edge(const DockRobot &d, State &s, const Oper &o) : state(s), dom(d) {
apply(state, o);
oldh = state.h;
oldd = state.d;
state.h = state.d = Cost(-1);
}
~Edge() {
apply(state, revop);
state.h = oldh;
state.d = oldd;
}
private:
void apply(State&, const Oper&);
// needed to reverse an operator application.
const DockRobot &dom;
};
void pack(PackedState&, const State&);
State &unpack(State&, const PackedState&);
void dumpstate(FILE*, const State&) const;
Cost pathcost(const std::vector<State>&, const std::vector<Oper>&);
private:
friend class State;
friend bool compute_moves_test();
friend bool compute_loads_test();
// initheuristic initializes the heuristic values by computing
// the shortest path between all locations.
void initheuristic();
std::pair<float, float> hd(const State&) const;
// paths holds shortest path information between
// locations used for computing the heuristic.
std::vector< std::pair<float, float> > shortest;
// The number of various things in the dockyard.
unsigned int nlocs, nboxes;
// maxpiles is the maximum number of piles at a given location.
std::vector<unsigned int> maxpiles;
// ncranes is the number of cranes at each location.
std::vector<unsigned int> maxcranes;
// adj is the adjacency matrix for locations.
std::vector< std::vector<float> > adj;
// initlocs is the initial location configurations.
std::vector<Loc> initlocs;
// goal is a vector of the desired location for each box
std::vector<int> goal;
};
<|endoftext|> |
<commit_before>/*
Copyright (C) 2014-2018 Nicolas Brown
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 "../assembly.hpp"
#include "../virtualmachine.hpp"
#include <string>
using namespace loris;
namespace DSUtilsLib
{
Value NativeStr(VirtualMachine* vm,Object* self)
{
Value val = vm->GetArg(0);
switch(val.type)
{
case ValueType::Bool:
if(val.val.b)
return Value::CreateBool(true);
return Value::CreateBool(false);
break;
case ValueType::Number:
return Value::CreateString(std::to_string(val.val.num).c_str());
break;
case ValueType::String:
return val;
break;
case ValueType::Object:
return Value::CreateString((std::string("<")+val.val.obj->typeName+">").c_str());
break;
case ValueType::Null:
return Value::CreateString("null");
break;
}
return Value::CreateNull();//shouldnt be here, throw error instead
}
Value NativeArray(VirtualMachine* vm,Object* self)
{
//ignore args at the moment
return Value::CreateArray();
}
void Install(Assembly* lib)
{
lib->AddFunction("str",NativeStr);
lib->AddFunction("array",NativeArray);
}
}<commit_msg>Loris' util array can now be initialized with elements<commit_after>/*
Copyright (C) 2014-2018 Nicolas Brown
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 "../assembly.hpp"
#include "../virtualmachine.hpp"
#include <string>
using namespace loris;
namespace DSUtilsLib
{
Value NativeStr(VirtualMachine* vm,Object* self)
{
Value val = vm->GetArg(0);
switch(val.type)
{
case ValueType::Bool:
if(val.val.b)
return Value::CreateBool(true);
return Value::CreateBool(false);
break;
case ValueType::Number:
return Value::CreateString(std::to_string(val.val.num).c_str());
break;
case ValueType::String:
return val;
break;
case ValueType::Object:
return Value::CreateString((std::string("<")+val.val.obj->typeName+">").c_str());
break;
case ValueType::Null:
return Value::CreateString("null");
break;
}
return Value::CreateNull();//shouldnt be here, throw error instead
}
Value NativeArray(VirtualMachine* vm,Object* self)
{
auto arrayVar = Value::CreateArray();
auto arrayObj = arrayVar.AsArray();
for (int i = 0; i < vm->NumArgs(); i++)
arrayObj->elements.push_back(vm->GetArg(i));
//ignore args at the moment
return arrayVar;
}
void Install(Assembly* lib)
{
lib->AddFunction("str",NativeStr);
lib->AddFunction("array",NativeArray);
}
}<|endoftext|> |
<commit_before>#include "vertex.hpp"
namespace mos{
Vertex::Vertex(const glm::vec3 position,
const glm::vec3 normal,
const glm::vec2 uv,
const glm::vec2 uv_lightmap)
: position(position),
normal(normal),
uv(uv),
uv_lightmap(uv_lightmap) {
}
Vertex::Vertex(const float position_x, const float position_y, const float position_z,
const float normal_x = 0.0f, const float normal_y = 0.0f, const float normal_z = 0.0f,
const float uv_x = 0.0f, const float uv_y = 0.0f,
const float uv_lightmap_x = 0.0f, const float uv_lightmap_y = 0.0f)
: Vertex(glm::vec3(position_x, position_y, position_z),
glm::vec3(normal_x, normal_y, normal_z),
glm::vec2(uv_x, uv_y),
glm::vec2(uv_lightmap_x, uv_lightmap_y)) {}
Vertex::~Vertex(){
}
Vertex Vertex::operator+(const Vertex & vertex) const {
return Vertex(position + vertex.position, normal + vertex.normal, uv + vertex.uv, uv_lightmap + vertex.uv_lightmap);
}
Vertex Vertex::operator-(const Vertex & vertex) const {
return Vertex(position - vertex.position, normal - vertex.normal, uv - vertex.uv, uv_lightmap - vertex.uv_lightmap);
}
Vertex Vertex::operator*(const Vertex & vertex) const {
return Vertex(position * vertex.position, normal * vertex.normal, uv * vertex.uv, uv_lightmap * vertex.uv_lightmap);
}
Vertex Vertex::operator*(const float number) const {
return Vertex(position * number, normal * number, uv * number, uv_lightmap * number);
}
Vertex Vertex::operator/(const float number) const {
return Vertex(position / number, normal / number, uv / number, uv_lightmap / number);
}
Vertex Vertex::operator/(const Vertex & vertex) const {
return Vertex(position / vertex.position, normal / vertex.normal, uv / vertex.uv, uv_lightmap / vertex.uv_lightmap);
}
}
<commit_msg>Compile error fix.<commit_after>#include "vertex.hpp"
namespace mos{
Vertex::Vertex(const glm::vec3 position,
const glm::vec3 normal,
const glm::vec2 uv,
const glm::vec2 uv_lightmap)
: position(position),
normal(normal),
uv(uv),
uv_lightmap(uv_lightmap) {
}
Vertex::Vertex(const float position_x, const float position_y, const float position_z,
const float normal_x, const float normal_y, const float normal_z,
const float uv_x, const float uv_y,
const float uv_lightmap_x, const float uv_lightmap_y)
: Vertex(glm::vec3(position_x, position_y, position_z),
glm::vec3(normal_x, normal_y, normal_z),
glm::vec2(uv_x, uv_y),
glm::vec2(uv_lightmap_x, uv_lightmap_y)) {}
Vertex::~Vertex(){
}
Vertex Vertex::operator+(const Vertex & vertex) const {
return Vertex(position + vertex.position, normal + vertex.normal, uv + vertex.uv, uv_lightmap + vertex.uv_lightmap);
}
Vertex Vertex::operator-(const Vertex & vertex) const {
return Vertex(position - vertex.position, normal - vertex.normal, uv - vertex.uv, uv_lightmap - vertex.uv_lightmap);
}
Vertex Vertex::operator*(const Vertex & vertex) const {
return Vertex(position * vertex.position, normal * vertex.normal, uv * vertex.uv, uv_lightmap * vertex.uv_lightmap);
}
Vertex Vertex::operator*(const float number) const {
return Vertex(position * number, normal * number, uv * number, uv_lightmap * number);
}
Vertex Vertex::operator/(const float number) const {
return Vertex(position / number, normal / number, uv / number, uv_lightmap / number);
}
Vertex Vertex::operator/(const Vertex & vertex) const {
return Vertex(position / vertex.position, normal / vertex.normal, uv / vertex.uv, uv_lightmap / vertex.uv_lightmap);
}
}
<|endoftext|> |
<commit_before>// For stat, getcwd
#include <cerrno>
#include <sys/types.h>
#include <sys/stat.h>
#include <libport/unistd.h>
#include <fcntl.h>
// For bad_alloc
#include <exception>
#include <boost/format.hpp>
#include <object/directory.hh>
#include <object/file.hh>
#include <object/path.hh>
namespace object
{
using boost::format;
/*------------.
| C++ methods |
`------------*/
const Path::value_type& Path::value_get() const
{
return path_;
}
/*-------------.
| Urbi methods |
`-------------*/
// Construction
Path::Path()
: path_("/")
{
proto_add(proto);
}
Path::Path(rPath)
: path_("/")
{
throw PrimitiveError(SYMBOL(clone),
"`Path' objects cannot be cloned");
}
Path::Path(const std::string& value)
: path_(value)
{
proto_add(proto);
}
void Path::init(const std::string& path)
{
path_ = path;
}
// Global informations
rPath Path::cwd()
{
// C *sucks*
static char buf[PATH_MAX];
char* res = getcwd(buf, PATH_MAX);
if (!res)
throw PrimitiveError(SYMBOL(pwd),
"Current directory name too long.");
return new Path(res);
}
// Stats
bool Path::absolute()
{
return path_.absolute_get();
}
bool Path::exists()
{
struct stat dummy;
if (!::stat(path_.to_string().c_str(), &dummy))
return true;
handle_hard_error(SYMBOL(exists));
switch (errno)
{
case EACCES:
// Permission denied on one of the parent directory.
case ENOENT:
// No such file or directory.
case ENOTDIR:
// One component isn't a directory
return false;
default:
unhandled_error(SYMBOL(exists));
}
}
struct stat Path::stat(const libport::Symbol& msg)
{
struct stat res;
if (::stat(path_.to_string().c_str(), &res))
{
handle_hard_error(msg);
handle_access_error(msg);
handle_perm_error(msg);
unhandled_error(msg);
}
return res;
}
bool Path::is_dir()
{
return stat(SYMBOL(isDir)).st_mode & S_IFDIR;
}
bool Path::is_reg()
{
return stat(SYMBOL(isReg)).st_mode & S_IFREG;
}
bool Path::readable()
{
int fd = ::open(path_.to_string().c_str(), O_RDONLY | O_LARGEFILE);
if (fd != -1)
{
close(fd);
return true;
}
else if (errno == EACCES)
return false;
handle_hard_error(SYMBOL(readable));
handle_access_error(SYMBOL(readable));
unhandled_error(SYMBOL(readable));
// Not handled errors, because neither NOATIME or NONBLOCK is used:
// EPERM: The O_NOATIME flag was specified, but the effective user
// ID of the caller did not match the owner of the file and the
// caller was not privileged (CAP_FOWNER).
// EWOULDBLOCK: The O_NONBLOCK flag was specified, and an
// incompatible lease was held on the file (see fcntl(2)).
}
bool Path::writable()
{
int fd = ::open(path_.to_string().c_str(),
O_WRONLY | O_LARGEFILE | O_APPEND);
if (fd != -1)
{
close(fd);
return true;
}
// EROFS = file is on a read only file system.
else if (errno == EACCES || errno == EROFS)
return false;
handle_hard_error(SYMBOL(readable));
handle_access_error(SYMBOL(readable));
handle_perm_error(SYMBOL(readable));
unhandled_error(SYMBOL(readable));
// EPERM and EWOULDBLOCK not handled, see readable().
}
// Operations
std::string Path::basename()
{
return path_.basename();
}
rPath Path::cd()
{
if (chdir(as_string().c_str()))
handle_any_error(SYMBOL(cd));
return cwd();
}
rPath Path::concat(rPath other)
{
return new Path(path_ / (*other).path_);
}
std::string Path::dirname()
{
return path_.dirname();
}
rObject Path::open()
{
if (is_dir())
return new Directory(path_);
if (is_reg())
return new File(path_);
throw PrimitiveError
(SYMBOL(open),
str(format("Unsupported file type: %s.") % path_));
}
// Conversions
std::string Path::as_string()
{
return path_.to_string();
}
std::string Path::as_printable()
{
return str(format("\"%s\"") % as_string());
}
rList Path::as_list()
{
List::value_type res;
foreach (const std::string& c, path_.components())
res << new String(c);
return new List(res);
}
/*--------.
| Details |
`--------*/
void Path::handle_any_error(const libport::Symbol& msg)
{
handle_hard_error(msg);
handle_access_error(msg);
handle_perm_error(msg);
unhandled_error(msg);
}
void Path::handle_hard_error(const libport::Symbol& msg)
{
switch (errno)
{
case EBADF:
// Theoretically impossible.
throw PrimitiveError
(msg,
"Unhandled error: bad file descriptor");
case EFAULT:
// Theoretically impossible.
throw PrimitiveError
(msg,
"Unhandled error: bad address");
case EFBIG:
// Theoretically impossible, since O_LARGEFILE is always used
throw PrimitiveError
(msg,
str(format("Unhandled error: file too big: %s.") % path_));
case EINTR:
// Theoretically impossible.
throw PrimitiveError
(msg,
"Unhandled error: file opening interrupted by a signal");
case ELOOP:
throw PrimitiveError
(msg,
str(format("Too many symbolic link: %s.") % path_));
case EMFILE:
throw PrimitiveError
(msg,
str(format("The kernel has reached"
" its maximum opened file limit: %s.") % path_));
case ENAMETOOLONG:
throw PrimitiveError
(msg,
str(format("File name too long: %s.") % path_));
case ENFILE:
throw PrimitiveError
(msg,
str(format("The system has reached"
" its maximum opened file limit: %s.") % path_));
case ENOMEM:
// Out of memory.
throw std::bad_alloc();
case ENOSPC:
throw PrimitiveError
(msg,
str(format("No space left on device: %s.") % path_));
default:
// Nothing
break;
}
}
void Path::handle_access_error(const libport::Symbol& msg)
{
switch (errno)
{
case EACCES:
throw PrimitiveError
(msg, str(format("Permission denied "
"for a parent directory: %s.")
% path_));
case ENOENT:
throw PrimitiveError
(msg, str(format("No such file or directory: %s.")
% path_));
case ENOTDIR:
throw PrimitiveError
(msg, str(format("One component is not a directory: %s.")
% path_));
default:
// Nothing
break;
}
}
void Path::handle_perm_error(const libport::Symbol& msg)
{
switch (errno)
{
case EEXIST:
throw PrimitiveError
(msg, str(format("File already exists: %s.")
% path_));
case EISDIR:
throw PrimitiveError
(msg, str(format("File is a directory: %s.")
% path_));
case EROFS:
throw PrimitiveError
(msg, str(format("File is on a read only file-system: %s.")
% path_));
case ETXTBSY:
throw PrimitiveError
(msg, str(format("File is currently being executed: %s.")
% path_));
case ENODEV:
case ENXIO:
throw PrimitiveError
(msg, str(format("File is an unopened FIFO "
"or an orphaned device: %s.")
% path_));
default:
// Nothing
break;
}
}
void Path::unhandled_error(const libport::Symbol& msg)
{
throw PrimitiveError
(msg,
str(format("Unhandled errno for stat(2): %i (%s).")
% errno
% strerror(errno)));
}
/*---------------.
| Binding system |
`---------------*/
void Path::initialize(CxxObject::Binder<Path>& bind)
{
bind(SYMBOL(absolute), &Path::absolute);
bind(SYMBOL(asList), &Path::as_list);
bind(SYMBOL(asPrintable), &Path::as_printable);
bind(SYMBOL(asString), &Path::as_string);
bind(SYMBOL(basename), &Path::basename);
bind(SYMBOL(cd), &Path::cd);
bind(SYMBOL(cwd), &Path::cwd);
bind(SYMBOL(dirname), &Path::dirname);
bind(SYMBOL(exists), &Path::exists);
bind(SYMBOL(init), &Path::init);
bind(SYMBOL(isDir), &Path::is_dir);
bind(SYMBOL(isReg), &Path::is_reg);
bind(SYMBOL(open), &Path::open);
bind(SYMBOL(readable), &Path::readable);
bind(SYMBOL(SLASH), &Path::concat);
bind(SYMBOL(writable), &Path::writable);
}
std::string Path::type_name_get() const
{
return type_name;
}
bool Path::path_added = CxxObject::add<Path>("Path", Path::proto);
const std::string Path::type_name = "Path";
rObject Path::proto;
}
<commit_msg>Use boost::filesystem to retrieve the current path, for portability.<commit_after>// For stat, getcwd
#include <cerrno>
#include <sys/types.h>
#include <sys/stat.h>
#include <libport/unistd.h>
#include <fcntl.h>
#include <libport/filesystem.hh>
// For bad_alloc
#include <exception>
#include <boost/filesystem.hpp>
#include <boost/format.hpp>
#include <object/directory.hh>
#include <object/file.hh>
#include <object/path.hh>
namespace object
{
using boost::format;
/*------------.
| C++ methods |
`------------*/
const Path::value_type& Path::value_get() const
{
return path_;
}
/*-------------.
| Urbi methods |
`-------------*/
// Construction
Path::Path()
: path_("/")
{
proto_add(proto);
}
Path::Path(rPath)
: path_("/")
{
throw PrimitiveError(SYMBOL(clone),
"`Path' objects cannot be cloned");
}
Path::Path(const std::string& value)
: path_(value)
{
proto_add(proto);
}
void Path::init(const std::string& path)
{
path_ = path;
}
// Global informations
rPath Path::cwd()
{
return new Path(boost::filesystem::current_path().string());
}
// Stats
bool Path::absolute()
{
return path_.absolute_get();
}
bool Path::exists()
{
struct stat dummy;
if (!::stat(path_.to_string().c_str(), &dummy))
return true;
handle_hard_error(SYMBOL(exists));
switch (errno)
{
case EACCES:
// Permission denied on one of the parent directory.
case ENOENT:
// No such file or directory.
case ENOTDIR:
// One component isn't a directory
return false;
default:
unhandled_error(SYMBOL(exists));
}
}
struct stat Path::stat(const libport::Symbol& msg)
{
struct stat res;
if (::stat(path_.to_string().c_str(), &res))
{
handle_hard_error(msg);
handle_access_error(msg);
handle_perm_error(msg);
unhandled_error(msg);
}
return res;
}
bool Path::is_dir()
{
return stat(SYMBOL(isDir)).st_mode & S_IFDIR;
}
bool Path::is_reg()
{
return stat(SYMBOL(isReg)).st_mode & S_IFREG;
}
bool Path::readable()
{
int fd = ::open(path_.to_string().c_str(), O_RDONLY | O_LARGEFILE);
if (fd != -1)
{
close(fd);
return true;
}
else if (errno == EACCES)
return false;
handle_hard_error(SYMBOL(readable));
handle_access_error(SYMBOL(readable));
unhandled_error(SYMBOL(readable));
// Not handled errors, because neither NOATIME or NONBLOCK is used:
// EPERM: The O_NOATIME flag was specified, but the effective user
// ID of the caller did not match the owner of the file and the
// caller was not privileged (CAP_FOWNER).
// EWOULDBLOCK: The O_NONBLOCK flag was specified, and an
// incompatible lease was held on the file (see fcntl(2)).
}
bool Path::writable()
{
int fd = ::open(path_.to_string().c_str(),
O_WRONLY | O_LARGEFILE | O_APPEND);
if (fd != -1)
{
close(fd);
return true;
}
// EROFS = file is on a read only file system.
else if (errno == EACCES || errno == EROFS)
return false;
handle_hard_error(SYMBOL(readable));
handle_access_error(SYMBOL(readable));
handle_perm_error(SYMBOL(readable));
unhandled_error(SYMBOL(readable));
// EPERM and EWOULDBLOCK not handled, see readable().
}
// Operations
std::string Path::basename()
{
return path_.basename();
}
rPath Path::cd()
{
if (chdir(as_string().c_str()))
handle_any_error(SYMBOL(cd));
return cwd();
}
rPath Path::concat(rPath other)
{
return new Path(path_ / (*other).path_);
}
std::string Path::dirname()
{
return path_.dirname();
}
rObject Path::open()
{
if (is_dir())
return new Directory(path_);
if (is_reg())
return new File(path_);
throw PrimitiveError
(SYMBOL(open),
str(format("Unsupported file type: %s.") % path_));
}
// Conversions
std::string Path::as_string()
{
return path_.to_string();
}
std::string Path::as_printable()
{
return str(format("\"%s\"") % as_string());
}
rList Path::as_list()
{
List::value_type res;
foreach (const std::string& c, path_.components())
res << new String(c);
return new List(res);
}
/*--------.
| Details |
`--------*/
void Path::handle_any_error(const libport::Symbol& msg)
{
handle_hard_error(msg);
handle_access_error(msg);
handle_perm_error(msg);
unhandled_error(msg);
}
void Path::handle_hard_error(const libport::Symbol& msg)
{
switch (errno)
{
case EBADF:
// Theoretically impossible.
throw PrimitiveError
(msg,
"Unhandled error: bad file descriptor");
case EFAULT:
// Theoretically impossible.
throw PrimitiveError
(msg,
"Unhandled error: bad address");
case EFBIG:
// Theoretically impossible, since O_LARGEFILE is always used
throw PrimitiveError
(msg,
str(format("Unhandled error: file too big: %s.") % path_));
case EINTR:
// Theoretically impossible.
throw PrimitiveError
(msg,
"Unhandled error: file opening interrupted by a signal");
case ELOOP:
throw PrimitiveError
(msg,
str(format("Too many symbolic link: %s.") % path_));
case EMFILE:
throw PrimitiveError
(msg,
str(format("The kernel has reached"
" its maximum opened file limit: %s.") % path_));
case ENAMETOOLONG:
throw PrimitiveError
(msg,
str(format("File name too long: %s.") % path_));
case ENFILE:
throw PrimitiveError
(msg,
str(format("The system has reached"
" its maximum opened file limit: %s.") % path_));
case ENOMEM:
// Out of memory.
throw std::bad_alloc();
case ENOSPC:
throw PrimitiveError
(msg,
str(format("No space left on device: %s.") % path_));
default:
// Nothing
break;
}
}
void Path::handle_access_error(const libport::Symbol& msg)
{
switch (errno)
{
case EACCES:
throw PrimitiveError
(msg, str(format("Permission denied "
"for a parent directory: %s.")
% path_));
case ENOENT:
throw PrimitiveError
(msg, str(format("No such file or directory: %s.")
% path_));
case ENOTDIR:
throw PrimitiveError
(msg, str(format("One component is not a directory: %s.")
% path_));
default:
// Nothing
break;
}
}
void Path::handle_perm_error(const libport::Symbol& msg)
{
switch (errno)
{
case EEXIST:
throw PrimitiveError
(msg, str(format("File already exists: %s.")
% path_));
case EISDIR:
throw PrimitiveError
(msg, str(format("File is a directory: %s.")
% path_));
case EROFS:
throw PrimitiveError
(msg, str(format("File is on a read only file-system: %s.")
% path_));
case ETXTBSY:
throw PrimitiveError
(msg, str(format("File is currently being executed: %s.")
% path_));
case ENODEV:
case ENXIO:
throw PrimitiveError
(msg, str(format("File is an unopened FIFO "
"or an orphaned device: %s.")
% path_));
default:
// Nothing
break;
}
}
void Path::unhandled_error(const libport::Symbol& msg)
{
throw PrimitiveError
(msg,
str(format("Unhandled errno for stat(2): %i (%s).")
% errno
% strerror(errno)));
}
/*---------------.
| Binding system |
`---------------*/
void Path::initialize(CxxObject::Binder<Path>& bind)
{
bind(SYMBOL(absolute), &Path::absolute);
bind(SYMBOL(asList), &Path::as_list);
bind(SYMBOL(asPrintable), &Path::as_printable);
bind(SYMBOL(asString), &Path::as_string);
bind(SYMBOL(basename), &Path::basename);
bind(SYMBOL(cd), &Path::cd);
bind(SYMBOL(cwd), &Path::cwd);
bind(SYMBOL(dirname), &Path::dirname);
bind(SYMBOL(exists), &Path::exists);
bind(SYMBOL(init), &Path::init);
bind(SYMBOL(isDir), &Path::is_dir);
bind(SYMBOL(isReg), &Path::is_reg);
bind(SYMBOL(open), &Path::open);
bind(SYMBOL(readable), &Path::readable);
bind(SYMBOL(SLASH), &Path::concat);
bind(SYMBOL(writable), &Path::writable);
}
std::string Path::type_name_get() const
{
return type_name;
}
bool Path::path_added = CxxObject::add<Path>("Path", Path::proto);
const std::string Path::type_name = "Path";
rObject Path::proto;
}
<|endoftext|> |
<commit_before>//
// $Id$
//
#include "AVGImage.h"
#include "IAVGDisplayEngine.h"
#include "AVGPlayer.h"
#include "AVGLogger.h"
#include "IAVGSurface.h"
#include <paintlib/plbitmap.h>
#include <paintlib/planybmp.h>
#include <paintlib/plpngenc.h>
#include <paintlib/planydec.h>
#include <paintlib/Filter/plfilterresizebilinear.h>
#include <paintlib/Filter/plfilterfliprgb.h>
#include <paintlib/Filter/plfilterfill.h>
#include <nsMemory.h>
#include <xpcom/nsComponentManagerUtils.h>
#include <iostream>
#include <sstream>
using namespace std;
NS_IMPL_ISUPPORTS1_CI(AVGImage, IAVGNode);
AVGImage * AVGImage::create()
{
return createNode<AVGImage>("@c-base.org/avgimage;1");
}
AVGImage::AVGImage ()
: m_pSurface(0)
{
NS_INIT_ISUPPORTS();
}
AVGImage::~AVGImage ()
{
if (m_pSurface) {
delete m_pSurface;
}
}
NS_IMETHODIMP
AVGImage::GetType(PRInt32 *_retval)
{
*_retval = NT_IMAGE;
return NS_OK;
}
void AVGImage::init (const std::string& id, const std::string& filename,
int bpp, IAVGDisplayEngine * pEngine, AVGContainer * pParent,
AVGPlayer * pPlayer)
{
AVGNode::init(id, pEngine, pParent, pPlayer);
m_Filename = filename;
AVG_TRACE(AVGPlayer::DEBUG_PROFILE, "Loading " << m_Filename);
m_pSurface = getEngine()->createSurface();
PLAnyPicDecoder decoder;
PLAnyBmp TempBmp;
// TODO: Decode directly to surface using PLPicDec::GetImage();
decoder.MakeBmpFromFile(m_Filename.c_str(), &TempBmp, 32);
if (!pEngine->hasRGBOrdering()) {
TempBmp.ApplyFilter(PLFilterFlipRGB());
}
int DestBPP = bpp;
if (!pEngine->supportsBpp(bpp)) {
DestBPP = 32;
}
m_pSurface->create(TempBmp.GetWidth(), TempBmp.GetHeight(),
DestBPP, TempBmp.HasAlpha());
PLPixel32** ppSrcLines = TempBmp.GetLineArray32();
PLBmpBase * pDestBmp = m_pSurface->getBmp();
PLPixel32** ppDestLines = pDestBmp->GetLineArray32();
for (int y=0; y<TempBmp.GetHeight(); y++) {
memcpy (ppDestLines[y], ppSrcLines[y], TempBmp.GetWidth()*4);
}
getEngine()->surfaceChanged(m_pSurface);
}
void AVGImage::render (const AVGDRect& Rect)
{
getEngine()->blt32(m_pSurface, &getAbsViewport(), getEffectiveOpacity(),
getAngle(), getPivot());
}
bool AVGImage::obscures (const AVGDRect& Rect, int z)
{
return (getEffectiveOpacity() > 0.999 && !m_pSurface->getBmp()->HasAlpha()
&& getZ() > z && getVisibleRect().Contains(Rect));
}
string AVGImage::getTypeStr ()
{
return "AVGImage";
}
AVGDPoint AVGImage::getPreferredMediaSize()
{
return AVGDPoint(m_pSurface->getBmp()->GetSize());
}
<commit_msg>Refactored to use CopyPixels()<commit_after>//
// $Id$
//
#include "AVGImage.h"
#include "IAVGDisplayEngine.h"
#include "AVGPlayer.h"
#include "AVGLogger.h"
#include "IAVGSurface.h"
#include <paintlib/plbitmap.h>
#include <paintlib/planybmp.h>
#include <paintlib/plpngenc.h>
#include <paintlib/planydec.h>
#include <paintlib/Filter/plfilterresizebilinear.h>
#include <paintlib/Filter/plfilterfliprgb.h>
#include <paintlib/Filter/plfilterfill.h>
#include <nsMemory.h>
#include <xpcom/nsComponentManagerUtils.h>
#include <iostream>
#include <sstream>
using namespace std;
NS_IMPL_ISUPPORTS1_CI(AVGImage, IAVGNode);
AVGImage * AVGImage::create()
{
return createNode<AVGImage>("@c-base.org/avgimage;1");
}
AVGImage::AVGImage ()
: m_pSurface(0)
{
NS_INIT_ISUPPORTS();
}
AVGImage::~AVGImage ()
{
if (m_pSurface) {
delete m_pSurface;
}
}
NS_IMETHODIMP
AVGImage::GetType(PRInt32 *_retval)
{
*_retval = NT_IMAGE;
return NS_OK;
}
void AVGImage::init (const std::string& id, const std::string& filename,
int bpp, IAVGDisplayEngine * pEngine, AVGContainer * pParent,
AVGPlayer * pPlayer)
{
AVGNode::init(id, pEngine, pParent, pPlayer);
m_Filename = filename;
AVG_TRACE(AVGPlayer::DEBUG_PROFILE, "Loading " << m_Filename);
m_pSurface = getEngine()->createSurface();
PLAnyPicDecoder decoder;
PLAnyBmp TempBmp;
decoder.MakeBmpFromFile(m_Filename.c_str(), &TempBmp, 32);
if (!pEngine->hasRGBOrdering()) {
TempBmp.ApplyFilter(PLFilterFlipRGB());
}
int DestBPP = bpp;
if (!pEngine->supportsBpp(bpp)) {
DestBPP = 32;
}
m_pSurface->create(TempBmp.GetWidth(), TempBmp.GetHeight(),
DestBPP, TempBmp.HasAlpha());
m_pSurface->getBmp()->CopyPixels(TempBmp);
getEngine()->surfaceChanged(m_pSurface);
}
void AVGImage::render (const AVGDRect& Rect)
{
getEngine()->blt32(m_pSurface, &getAbsViewport(), getEffectiveOpacity(),
getAngle(), getPivot());
}
bool AVGImage::obscures (const AVGDRect& Rect, int z)
{
return (getEffectiveOpacity() > 0.999 && !m_pSurface->getBmp()->HasAlpha()
&& getZ() > z && getVisibleRect().Contains(Rect));
}
string AVGImage::getTypeStr ()
{
return "AVGImage";
}
AVGDPoint AVGImage::getPreferredMediaSize()
{
return AVGDPoint(m_pSurface->getBmp()->GetSize());
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2009-2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/**
** \file object/uvar.cc
** \brief Creation of the Urbi object UVar.
*/
# include <kernel/userver.hh>
# include <kernel/uvalue-cast.hh>
# include <object/symbols.hh>
# include <object/urbi-exception.hh>
# include <object/uvalue.hh>
# include <object/uvar.hh>
# include <urbi/object/global.hh>
# include <urbi/object/list.hh>
# include <urbi/object/lobby.hh>
# include <runner/runner.hh>
# include <runner/interpreter.hh>
namespace urbi
{
namespace object
{
static inline void
show_exception_message(runner::Runner& r, rObject self,
const char* m1, const char* m2 = "")
{
std::string msg =
libport::format("!!! %s %s.%s%s",
m1,
(self->slot_get(SYMBOL(ownerName))
->as<String>()->value_get()),
(self->slot_get(SYMBOL(initialName))
->as<String>()->value_get()),
m2);
r.lobby_get()->call(SYMBOL(send),
new String(msg),
new String("error"));
}
static inline void
callNotify(runner::Runner& r, rObject self,
libport::Symbol notifyList)
{
rList l =
self->slot_get(notifyList)->slot_get(SYMBOL(values))->as<List>();
objects_type args;
args.push_back(self);
List::value_type& callbacks = l->value_get();
for (List::value_type::iterator i = callbacks.begin();
i != callbacks.end(); )
{
bool failed = true;
try
{
r.apply(*i, SYMBOL(NOTIFY), args);
failed = false;
}
catch(UrbiException& e)
{
show_exception_message
(r, self,
"Exception caught while processing notify on", ":");
runner::Interpreter& in = dynamic_cast<runner::Interpreter&>(r);
in.show_exception(e);
}
catch(sched::exception& e)
{
throw;
}
catch(...)
{
show_exception_message
(r, self,
"Unknown exception called while processing notify on");
}
if (failed && self->slot_get(SYMBOL(eraseThrowingCallbacks))->as_bool())
{
// 'value' is just a cache, not the actual storage location.
self->slot_get(notifyList)->call(SYMBOL(remove), *i);
i = callbacks.erase(i);
}
else
++i;
}
}
static rObject
update_bounce(objects_type args)
{
//called with self slotname slotval
check_arg_count(args.size() - 1, 2);
libport::intrusive_ptr<UVar> rvar =
args.front()
->slot_get(libport::Symbol(args[1]->as<String>()->value_get())).value()
.unsafe_cast<UVar>();
if (!rvar)
RAISE("UVar updatehook called on non-uvar slot");
rvar->update_(args[2]);
return void_class;
}
UVar::UVar()
: Primitive( boost::bind(&UVar::accessor, this))
, looping_(false)
, inAccess_(false)
, waiterCount_(0)
{
protos_set(new List);
proto_add(proto ? rPrimitive(proto) : Primitive::proto);
slot_set(SYMBOL(waiterTag), new Tag());
}
UVar::UVar(libport::intrusive_ptr<UVar>)
: Primitive( boost::bind(&UVar::accessor, this))
, looping_(false)
, inAccess_(false)
, waiterCount_(0)
{
protos_set(new List);
proto_add(proto ? rPrimitive(proto) : Primitive::proto);
slot_set(SYMBOL(waiterTag), new Tag());
}
void
UVar::changeAccessLoop()
{
// Prepare a call to System.period. Keep its computation in the
// loop, so that we can change it at run time.
CAPTURE_GLOBAL(System);
runner::Runner& r = ::kernel::urbiserver->getCurrentRunner();
while (true)
{
callNotify(r, rObject(this), SYMBOL(accessInLoop));
rObject period = System->call(SYMBOL(period));
r.yield_until(libport::utime() +
libport::utime_t(period->as<Float>()->value_get()
* 1000000.0));
}
}
void
UVar::loopCheck()
{
runner::Runner& r = ::kernel::urbiserver->getCurrentRunner();
bool prevState = r.non_interruptible_get();
FINALLY(((runner::Runner&, r))((bool, prevState)),
r.non_interruptible_set(prevState));
r.non_interruptible_set(true);
// Loop if we have both notifychange and notifyaccess callbacs.
// Listeners on the changed event counts as notifychange
if (!looping_
&&
(!slot_get(SYMBOL(change))->call(SYMBOL(empty))->as_bool()
|| slot_get(SYMBOL(changed))->call(SYMBOL(hasSubscribers))->as_bool()
)
&& !slot_get(SYMBOL(access))->call(SYMBOL(empty))->as_bool())
{
// There is no need to keep an accessor present if we are
// going to trigger it periodicaly.
slot_update(SYMBOL(accessInLoop),
slot_get(SYMBOL(access)));
slot_update(SYMBOL(access),
slot_get(SYMBOL(WeakDictionary))->call(SYMBOL(new)));
looping_ = true;
runner::Interpreter* nr =
new runner::Interpreter(r.lobby_get(),
r.scheduler_get(),
boost::bind(&UVar::changeAccessLoop, this),
this, SYMBOL(changeAccessLoop));
nr->tag_stack_clear();
nr->start_job();
}
}
void
UVar::checkBypassCopy()
{
// If there are blocked reads, call extract to force caching of the
// temporary value, and unblock them.
if (waiterCount_)
{
rUValue val = slot_get(slot_get(SYMBOL(owned))->as_bool()
? SYMBOL(valsensor)
: SYMBOL(val))
->as<UValue>();
if (val)
val->extract();
slot_get(SYMBOL(waiterTag))->call(SYMBOL(stop));
}
}
rObject
UVar::update_(rObject val)
{
// Do not bother with UValue for numeric types.
if (rUValue uval = val->as<UValue>())
if (uval->value_get().type == urbi::DATA_DOUBLE)
val = uval->extract();
runner::Runner& r = ::kernel::urbiserver->getCurrentRunner();
slot_update(SYMBOL(val), val);
if (slot_get(SYMBOL(owned))->as_bool())
callNotify(r, rObject(this), SYMBOL(changeOwned));
else
{
checkBypassCopy();
std::set<void*>::iterator i = inChange_.find(&r);
if (i == inChange_.end())
{
// callNotify does not throw, this is safe.
i = inChange_.insert(&r).first;
callNotify(r, rObject(this), SYMBOL(change));
inChange_.erase(i);
}
slot_get(SYMBOL(changed))->call("emit");
}
return val;
}
rObject
UVar::accessor()
{
return getter(false);
}
rObject
UVar::getter(bool fromCXX)
{
runner::Runner& r = ::kernel::urbiserver->getCurrentRunner();
if (this == proto.get())
return this;
if (!inAccess_)
{
inAccess_ = true;
callNotify(r, rObject(this), SYMBOL(access));
inAccess_ = false;
}
rObject res = slot_get(slot_get(SYMBOL(owned))->as_bool()
? SYMBOL(valsensor)
: SYMBOL(val));
if (!fromCXX)
{
if (rUValue bv = res->as<UValue>())
{
if (bv->bypassMode_ && bv->extract() == nil_class)
{
// This is a read on a bypass-mode UVar, from outside any
// notifychange: the value is not available.
// So we mark that we wait by inc-ing waiterCount, and wait
// on waiterTag until we timeout, or someone writes to the UVar
// and unlock us.
// free the shared ptrs
res.reset();
bv.reset();
++waiterCount_;
slot_get(SYMBOL(waiterTag))->call(SYMBOL(waitUntilStopped),
new Float(0.5));
--waiterCount_;
// The val slot likely changed, fetch it again.
res = slot_get(slot_get(SYMBOL(owned))->as_bool()
? SYMBOL(valsensor)
: SYMBOL(val));
if (rUValue bv = res->as<UValue>())
return bv->extract();
else
return res;
}
return bv->extract();
}
}
return res;
}
rObject
UVar::writeOwned(rObject newval)
{
runner::Runner& r = ::kernel::urbiserver->getCurrentRunner();
slot_update(SYMBOL(valsensor), newval);
checkBypassCopy();
callNotify(r, rObject(this), SYMBOL(change));
slot_get(SYMBOL(changed))->call("emit");
return newval;
}
void
UVar::initialize(CxxObject::Binder<UVar>& bind)
{
bind(SYMBOL(writeOwned), &UVar::writeOwned);
bind(SYMBOL(update_), &UVar::update_);
bind(SYMBOL(loopCheck), &UVar::loopCheck);
bind(SYMBOL(accessor), &UVar::accessor);
proto->slot_set(SYMBOL(updateBounce), new Primitive(&update_bounce));
}
URBI_CXX_OBJECT_REGISTER(UVar)
: Primitive( boost::bind(&UVar::accessor, this))
, looping_(false)
, inAccess_(false)
{}
}
}
<commit_msg>Work around g++-4.3.3 erroneous warning.<commit_after>/*
* Copyright (C) 2009-2010, Gostai S.A.S.
*
* This software is provided "as is" without warranty of any kind,
* either expressed or implied, including but not limited to the
* implied warranties of fitness for a particular purpose.
*
* See the LICENSE file for more information.
*/
/**
** \file object/uvar.cc
** \brief Creation of the Urbi object UVar.
*/
# include <kernel/userver.hh>
# include <kernel/uvalue-cast.hh>
# include <object/symbols.hh>
# include <object/urbi-exception.hh>
# include <object/uvalue.hh>
# include <object/uvar.hh>
# include <urbi/object/global.hh>
# include <urbi/object/list.hh>
# include <urbi/object/lobby.hh>
# include <runner/runner.hh>
# include <runner/interpreter.hh>
namespace urbi
{
namespace object
{
static inline void
show_exception_message(runner::Runner& r, rObject self,
const char* m1, const char* m2 = "")
{
std::string msg =
libport::format("!!! %s %s.%s%s",
m1,
(self->slot_get(SYMBOL(ownerName))
->as<String>()->value_get()),
(self->slot_get(SYMBOL(initialName))
->as<String>()->value_get()),
m2);
r.lobby_get()->call(SYMBOL(send),
new String(msg),
new String("error"));
}
static inline void
callNotify(runner::Runner& r, rObject self,
libport::Symbol notifyList)
{
rList l =
self->slot_get(notifyList)->slot_get(SYMBOL(values))->as<List>();
objects_type args;
args.push_back(self);
List::value_type& callbacks = l->value_get();
for (List::value_type::iterator i = callbacks.begin();
i != callbacks.end(); )
{
bool failed = true;
try
{
r.apply(*i, SYMBOL(NOTIFY), args);
failed = false;
}
catch(UrbiException& e)
{
show_exception_message
(r, self,
"Exception caught while processing notify on", ":");
runner::Interpreter& in = dynamic_cast<runner::Interpreter&>(r);
in.show_exception(e);
}
catch(sched::exception& e)
{
throw;
}
catch(...)
{
show_exception_message
(r, self,
"Unknown exception called while processing notify on");
}
if (failed && self->slot_get(SYMBOL(eraseThrowingCallbacks))->as_bool())
{
// 'value' is just a cache, not the actual storage location.
self->slot_get(notifyList)->call(SYMBOL(remove), *i);
i = callbacks.erase(i);
}
else
++i;
}
}
static rObject
update_bounce(objects_type args)
{
//called with self slotname slotval
check_arg_count(args.size() - 1, 2);
libport::intrusive_ptr<UVar> rvar =
args.front()
->slot_get(libport::Symbol(args[1]->as<String>()->value_get())).value()
.unsafe_cast<UVar>();
if (!rvar)
RAISE("UVar updatehook called on non-uvar slot");
rvar->update_(args[2]);
return void_class;
}
UVar::UVar()
: Primitive( boost::bind(&UVar::accessor, this))
, looping_(false)
, inAccess_(false)
, waiterCount_(0)
{
protos_set(new List);
proto_add(proto ? rPrimitive(proto) : Primitive::proto);
slot_set(SYMBOL(waiterTag), new Tag());
}
UVar::UVar(libport::intrusive_ptr<UVar>)
: Primitive( boost::bind(&UVar::accessor, this))
, looping_(false)
, inAccess_(false)
, waiterCount_(0)
{
protos_set(new List);
proto_add(proto ? rPrimitive(proto) : Primitive::proto);
slot_set(SYMBOL(waiterTag), new Tag());
}
void
UVar::changeAccessLoop()
{
// Prepare a call to System.period. Keep its computation in the
// loop, so that we can change it at run time.
CAPTURE_GLOBAL(System);
runner::Runner& r = ::kernel::urbiserver->getCurrentRunner();
while (true)
{
callNotify(r, rObject(this), SYMBOL(accessInLoop));
rObject period = System->call(SYMBOL(period));
r.yield_until(libport::utime() +
libport::utime_t(period->as<Float>()->value_get()
* 1000000.0));
}
}
void
UVar::loopCheck()
{
runner::Runner& r = ::kernel::urbiserver->getCurrentRunner();
bool prevState = r.non_interruptible_get();
FINALLY(((runner::Runner&, r))((bool, prevState)),
r.non_interruptible_set(prevState));
r.non_interruptible_set(true);
// Loop if we have both notifychange and notifyaccess callbacs.
// Listeners on the changed event counts as notifychange
if (!looping_
&&
(!slot_get(SYMBOL(change))->call(SYMBOL(empty))->as_bool()
|| slot_get(SYMBOL(changed))->call(SYMBOL(hasSubscribers))->as_bool()
)
&& !slot_get(SYMBOL(access))->call(SYMBOL(empty))->as_bool())
{
// There is no need to keep an accessor present if we are
// going to trigger it periodicaly.
slot_update(SYMBOL(accessInLoop),
slot_get(SYMBOL(access)));
slot_update(SYMBOL(access),
slot_get(SYMBOL(WeakDictionary))->call(SYMBOL(new)));
looping_ = true;
runner::Interpreter* nr =
new runner::Interpreter(r.lobby_get(),
r.scheduler_get(),
boost::bind(&UVar::changeAccessLoop, this),
this, SYMBOL(changeAccessLoop));
nr->tag_stack_clear();
nr->start_job();
}
}
void
UVar::checkBypassCopy()
{
// If there are blocked reads, call extract to force caching of the
// temporary value, and unblock them.
if (waiterCount_)
{
/* Split val declaration and assignment to work around g++ 4.3.3 wich warns:
* intrusive-ptr.hxx:89: error: 'val.libport::intrusive_ptr<urbi::object::UValue>::pointee_'
* may be used uninitialized in this function.
*/
rUValue val;
val = slot_get(slot_get(SYMBOL(owned))->as_bool()
? SYMBOL(valsensor)
: SYMBOL(val))->as<UValue>();
if (val)
val->extract();
slot_get(SYMBOL(waiterTag))->call(SYMBOL(stop));
}
}
rObject
UVar::update_(rObject val)
{
// Do not bother with UValue for numeric types.
if (rUValue uval = val->as<UValue>())
if (uval->value_get().type == urbi::DATA_DOUBLE)
val = uval->extract();
runner::Runner& r = ::kernel::urbiserver->getCurrentRunner();
slot_update(SYMBOL(val), val);
if (slot_get(SYMBOL(owned))->as_bool())
callNotify(r, rObject(this), SYMBOL(changeOwned));
else
{
checkBypassCopy();
std::set<void*>::iterator i = inChange_.find(&r);
if (i == inChange_.end())
{
// callNotify does not throw, this is safe.
i = inChange_.insert(&r).first;
callNotify(r, rObject(this), SYMBOL(change));
inChange_.erase(i);
}
slot_get(SYMBOL(changed))->call("emit");
}
return val;
}
rObject
UVar::accessor()
{
return getter(false);
}
rObject
UVar::getter(bool fromCXX)
{
runner::Runner& r = ::kernel::urbiserver->getCurrentRunner();
if (this == proto.get())
return this;
if (!inAccess_)
{
inAccess_ = true;
callNotify(r, rObject(this), SYMBOL(access));
inAccess_ = false;
}
rObject res = slot_get(slot_get(SYMBOL(owned))->as_bool()
? SYMBOL(valsensor)
: SYMBOL(val));
if (!fromCXX)
{
if (rUValue bv = res->as<UValue>())
{
if (bv->bypassMode_ && bv->extract() == nil_class)
{
// This is a read on a bypass-mode UVar, from outside any
// notifychange: the value is not available.
// So we mark that we wait by inc-ing waiterCount, and wait
// on waiterTag until we timeout, or someone writes to the UVar
// and unlock us.
// free the shared ptrs
res.reset();
bv.reset();
++waiterCount_;
slot_get(SYMBOL(waiterTag))->call(SYMBOL(waitUntilStopped),
new Float(0.5));
--waiterCount_;
// The val slot likely changed, fetch it again.
res = slot_get(slot_get(SYMBOL(owned))->as_bool()
? SYMBOL(valsensor)
: SYMBOL(val));
if (rUValue bv = res->as<UValue>())
return bv->extract();
else
return res;
}
return bv->extract();
}
}
return res;
}
rObject
UVar::writeOwned(rObject newval)
{
runner::Runner& r = ::kernel::urbiserver->getCurrentRunner();
slot_update(SYMBOL(valsensor), newval);
checkBypassCopy();
callNotify(r, rObject(this), SYMBOL(change));
slot_get(SYMBOL(changed))->call("emit");
return newval;
}
void
UVar::initialize(CxxObject::Binder<UVar>& bind)
{
bind(SYMBOL(writeOwned), &UVar::writeOwned);
bind(SYMBOL(update_), &UVar::update_);
bind(SYMBOL(loopCheck), &UVar::loopCheck);
bind(SYMBOL(accessor), &UVar::accessor);
proto->slot_set(SYMBOL(updateBounce), new Primitive(&update_bounce));
}
URBI_CXX_OBJECT_REGISTER(UVar)
: Primitive( boost::bind(&UVar::accessor, this))
, looping_(false)
, inAccess_(false)
{}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2014 Eran Pe'er.
*
* This program is made available under the terms of the MIT License.
*
* Created on Mar 10, 2014
*/
#include <string>
#include <queue>
#include "tpunit++.hpp"
#include "fakeit.hpp"
using namespace fakeit;
struct Miscellaneous : tpunit::TestFixture
{
Miscellaneous() :
TestFixture(
TEST(Miscellaneous::pass_mock_by_ref), //
TEST(Miscellaneous::can_mock_class_without_default_constructor), //
TEST(Miscellaneous::can_mock_class_with_protected_constructor), //
TEST(Miscellaneous::mock_virtual_methods_of_base_class), //
TEST(Miscellaneous::create_and_delete_fakit_instatnce), //
TEST(Miscellaneous::testStubFuncWithRightValueParameter),
TEST(Miscellaneous::testStubProcWithRightValueParameter)
)
{
}
struct SomeStruct
{
SomeStruct(int)
{
}
virtual void foo() = 0;
};
void can_mock_class_without_default_constructor()
{
Mock<SomeStruct> mock;
Fake(Method(mock, foo));
}
void can_mock_class_with_protected_constructor()
{
struct SomeClass
{
virtual void foo() = 0;
protected:
SomeClass(int)
{
}
};
Mock<SomeClass> mock;
Fake(Method(mock, foo));
}
void create_and_delete_fakit_instatnce()
{
class MyFakeit :public DefaultFakeit {
fakeit::EventHandler &accessTestingFrameworkAdapter() override {
throw "not implemented";
}
};
{
StandaloneFakeit s;
MyFakeit f;
}
}
struct Change
{
virtual void change(uint8_t r, uint8_t g, uint8_t b) = 0;
};
void assertChanged(Mock<Change>& mock, uint8_t v1, uint8_t v2, uint8_t v3)
{
Verify(Method(mock, change).Using(v1, v2, v3));
}
void pass_mock_by_ref()
{
Mock<Change> mock;
Change* change = &mock.get();
When(Method(mock, change)).AlwaysReturn();
change->change(1, 2, 3);
assertChanged(mock, 1, 2, 3);
}
struct A
{
//~A() = 0;
virtual int a1() = 0;
virtual int a2() = 0;
};
struct B : public A
{
virtual ~B() {}
virtual int b1() = 0;
virtual int b2() = 0;
};
void mock_virtual_methods_of_base_class() {
Mock<B> mock;
When(Method(mock, b1)).Return(1);
When(Method(mock, b2)).Return(2);
When(Method(mock, a1)).Return(3);
When(Method(mock, a2)).Return(4);
ASSERT_EQUAL(1, mock().b1());
ASSERT_EQUAL(2, mock().b2());
ASSERT_EQUAL(3, mock().a1());
ASSERT_EQUAL(4, mock().a2());
}
void testStubFuncWithRightValueParameter() {
struct foo {
virtual int bar(int &&) = 0;
};
Mock<foo> foo_mock;
When(Method(foo_mock, bar)).AlwaysReturn(100);
When(Method(foo_mock, bar).Using(1)).AlwaysReturn(1);
When(Method(foo_mock, bar).Using(2)).AlwaysDo([](int &){return 2; });
When(Method(foo_mock, bar).Using(3)).Do([](int){return 3; });
Method(foo_mock, bar).Using(4) = 4;
ASSERT_EQUAL(100, foo_mock.get().bar(5));
ASSERT_EQUAL(1, foo_mock.get().bar(1));
ASSERT_EQUAL(2, foo_mock.get().bar(2));
ASSERT_EQUAL(3, foo_mock.get().bar(3));
ASSERT_EQUAL(4, foo_mock.get().bar(4));
}
void testStubProcWithRightValueParameter() {
struct foo {
virtual void bar(int &&) = 0;
};
int rv3 = 0;
int rv4 = 0;
int rv5 = 0;
Mock<foo> foo_mock;
When(Method(foo_mock, bar).Using(1)).Return();
When(Method(foo_mock, bar)).AlwaysReturn();
When(Method(foo_mock, bar).Using(3)).AlwaysDo([&](int &){rv3 = 3; });
When(Method(foo_mock, bar).Using(4)).Do([&](int &){rv4 = 4; });
Method(foo_mock, bar).Using(5) = [&](int &){rv5 = 5; };
foo_mock.get().bar(1);
foo_mock.get().bar(2);
foo_mock.get().bar(3);
ASSERT_EQUAL(3, rv3);
foo_mock.get().bar(4);
ASSERT_EQUAL(4, rv4);
foo_mock.get().bar(5);
ASSERT_EQUAL(5, rv5);
}
template <int discriminator>
struct DummyType {
int value;
};
template <typename T>
class ClassToMock {
public:
virtual unsigned int method() {
return 0;
}
};
template <typename T>
class MockProxyClass {
Mock<ClassToMock<T> > mock;
public:
MockProxyClass(unsigned int value) {
When(Method(mock, method)).AlwaysReturn(value);
}
Mock<ClassToMock<T> >& getMock() {
return mock;
}
};
void testRemoveAmbiguityInDependentName()
{
// this is a compilation test. the following code should compile!!
MockProxyClass<DummyType<2> > proxy(3);
}
} __Miscellaneous;<commit_msg>ADD(TEST): Reproduce error of stubbing method after Reset<commit_after>/*
* Copyright (c) 2014 Eran Pe'er.
*
* This program is made available under the terms of the MIT License.
*
* Created on Mar 10, 2014
*/
#include <string>
#include <queue>
#include "tpunit++.hpp"
#include "fakeit.hpp"
using namespace fakeit;
struct Miscellaneous : tpunit::TestFixture
{
Miscellaneous() :
TestFixture(
TEST(Miscellaneous::pass_mock_by_ref), //
TEST(Miscellaneous::can_mock_class_without_default_constructor), //
TEST(Miscellaneous::can_mock_class_with_protected_constructor), //
TEST(Miscellaneous::mock_virtual_methods_of_base_class), //
TEST(Miscellaneous::create_and_delete_fakit_instatnce), //
TEST(Miscellaneous::testStubFuncWithRightValueParameter),
TEST(Miscellaneous::testStubProcWithRightValueParameter),
TEST(Miscellaneous::can_stub_method_after_reset)
)
{
}
struct SomeStruct
{
SomeStruct(int)
{
}
virtual void foo() = 0;
};
void can_mock_class_without_default_constructor()
{
Mock<SomeStruct> mock;
Fake(Method(mock, foo));
}
void can_mock_class_with_protected_constructor()
{
struct SomeClass
{
virtual void foo() = 0;
protected:
SomeClass(int)
{
}
};
Mock<SomeClass> mock;
Fake(Method(mock, foo));
}
void create_and_delete_fakit_instatnce()
{
class MyFakeit :public DefaultFakeit {
fakeit::EventHandler &accessTestingFrameworkAdapter() override {
throw "not implemented";
}
};
{
StandaloneFakeit s;
MyFakeit f;
}
}
struct Change
{
virtual void change(uint8_t r, uint8_t g, uint8_t b) = 0;
};
void assertChanged(Mock<Change>& mock, uint8_t v1, uint8_t v2, uint8_t v3)
{
Verify(Method(mock, change).Using(v1, v2, v3));
}
void pass_mock_by_ref()
{
Mock<Change> mock;
Change* change = &mock.get();
When(Method(mock, change)).AlwaysReturn();
change->change(1, 2, 3);
assertChanged(mock, 1, 2, 3);
}
struct A
{
//~A() = 0;
virtual int a1() = 0;
virtual int a2() = 0;
};
struct B : public A
{
virtual ~B() {}
virtual int b1() = 0;
virtual int b2() = 0;
};
void mock_virtual_methods_of_base_class() {
Mock<B> mock;
When(Method(mock, b1)).Return(1);
When(Method(mock, b2)).Return(2);
When(Method(mock, a1)).Return(3);
When(Method(mock, a2)).Return(4);
ASSERT_EQUAL(1, mock().b1());
ASSERT_EQUAL(2, mock().b2());
ASSERT_EQUAL(3, mock().a1());
ASSERT_EQUAL(4, mock().a2());
}
void testStubFuncWithRightValueParameter() {
struct foo {
virtual int bar(int &&) = 0;
};
Mock<foo> foo_mock;
When(Method(foo_mock, bar)).AlwaysReturn(100);
When(Method(foo_mock, bar).Using(1)).AlwaysReturn(1);
When(Method(foo_mock, bar).Using(2)).AlwaysDo([](int &){return 2; });
When(Method(foo_mock, bar).Using(3)).Do([](int){return 3; });
Method(foo_mock, bar).Using(4) = 4;
ASSERT_EQUAL(100, foo_mock.get().bar(5));
ASSERT_EQUAL(1, foo_mock.get().bar(1));
ASSERT_EQUAL(2, foo_mock.get().bar(2));
ASSERT_EQUAL(3, foo_mock.get().bar(3));
ASSERT_EQUAL(4, foo_mock.get().bar(4));
}
void testStubProcWithRightValueParameter() {
struct foo {
virtual void bar(int &&) = 0;
};
int rv3 = 0;
int rv4 = 0;
int rv5 = 0;
Mock<foo> foo_mock;
When(Method(foo_mock, bar).Using(1)).Return();
When(Method(foo_mock, bar)).AlwaysReturn();
When(Method(foo_mock, bar).Using(3)).AlwaysDo([&](int &){rv3 = 3; });
When(Method(foo_mock, bar).Using(4)).Do([&](int &){rv4 = 4; });
Method(foo_mock, bar).Using(5) = [&](int &){rv5 = 5; };
foo_mock.get().bar(1);
foo_mock.get().bar(2);
foo_mock.get().bar(3);
ASSERT_EQUAL(3, rv3);
foo_mock.get().bar(4);
ASSERT_EQUAL(4, rv4);
foo_mock.get().bar(5);
ASSERT_EQUAL(5, rv5);
}
struct foo_bar {
virtual ~foo_bar() {}
virtual int foo() = 0;
virtual int bar() = 0;
};
void can_stub_method_after_reset() {
Mock<foo_bar> mock;
mock.Reset();
When(Method(mock, bar)).Return(42);
ASSERT_EQUAL(mock.get().bar(), 42);
Verify(Method(mock, bar)).Once();
}
template <int discriminator>
struct DummyType {
int value;
};
template <typename T>
class ClassToMock {
public:
virtual unsigned int method() {
return 0;
}
};
template <typename T>
class MockProxyClass {
Mock<ClassToMock<T> > mock;
public:
MockProxyClass(unsigned int value) {
When(Method(mock, method)).AlwaysReturn(value);
}
Mock<ClassToMock<T> >& getMock() {
return mock;
}
};
void testRemoveAmbiguityInDependentName()
{
// this is a compilation test. the following code should compile!!
MockProxyClass<DummyType<2> > proxy(3);
}
} __Miscellaneous;
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** 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.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QApplication>
#include <QDebug>
#include "qsysteminfo.h"
using namespace QtMobility;
#define X(expr) qDebug() << #expr << "->" << (expr);
struct symbol_t
{
const char *key;
int val;
};
int lookup(const symbol_t *stab, const char *key, int def)
{
for(;stab->key;++stab) {
if(!strcmp(stab->key,key)) return stab->val;
}
return def;
}
const char *rlookup(const symbol_t *stab, int val, const char *def)
{
for(;stab->key; ++stab) {
if(stab->val == val) return stab->key;
}
return def;
}
#define SYM(x) { #x, x }
static const symbol_t Version_lut[] =
{
SYM(QSystemInfo::Os),
SYM(QSystemInfo::QtCore),
SYM(QSystemInfo::Firmware),
SYM(QSystemInfo::QtMobility),
{0,0}
};
static const symbol_t Feature_lut[] =
{
SYM(QSystemInfo::BluetoothFeature),
SYM(QSystemInfo::CameraFeature),
SYM(QSystemInfo::FmradioFeature),
SYM(QSystemInfo::IrFeature),
SYM(QSystemInfo::LedFeature),
SYM(QSystemInfo::MemcardFeature),
SYM(QSystemInfo::UsbFeature),
SYM(QSystemInfo::VibFeature),
SYM(QSystemInfo::WlanFeature),
SYM(QSystemInfo::SimFeature),
SYM(QSystemInfo::LocationFeature),
SYM(QSystemInfo::VideoOutFeature),
SYM(QSystemInfo::HapticsFeature),
SYM(QSystemInfo::FmTransmitterFeature),
{0,0}
};
static const symbol_t NetworkStatus_lut[] =
{
SYM(QSystemNetworkInfo::UndefinedStatus),
SYM(QSystemNetworkInfo::NoNetworkAvailable),
SYM(QSystemNetworkInfo::EmergencyOnly),
SYM(QSystemNetworkInfo::Searching),
SYM(QSystemNetworkInfo::Busy),
SYM(QSystemNetworkInfo::Connected),
SYM(QSystemNetworkInfo::HomeNetwork),
SYM(QSystemNetworkInfo::Denied),
SYM(QSystemNetworkInfo::Roaming),
{0,0}
};
static const symbol_t NetworkMode_lut[] =
{
SYM(QSystemNetworkInfo::UnknownMode),
SYM(QSystemNetworkInfo::GsmMode),
SYM(QSystemNetworkInfo::CdmaMode),
SYM(QSystemNetworkInfo::WcdmaMode),
SYM(QSystemNetworkInfo::WlanMode),
SYM(QSystemNetworkInfo::EthernetMode),
SYM(QSystemNetworkInfo::BluetoothMode),
SYM(QSystemNetworkInfo::WimaxMode),
SYM(QSystemNetworkInfo::GprsMode),
SYM(QSystemNetworkInfo::EdgeMode),
SYM(QSystemNetworkInfo::HspaMode),
SYM(QSystemNetworkInfo::LteMode),
{0,0}
};
/* ------------------------------------------------------------------------- *
* test_systeminfo
* ------------------------------------------------------------------------- */
static void test_systeminfo(void)
{
QSystemInfo info;
X(info.currentLanguage());
X(info.availableLanguages());
X(info.currentCountryCode());
X(info.version(QSystemInfo::Os));
X(info.version(QSystemInfo::QtCore));
X(info.version(QSystemInfo::Firmware));
X(info.version(QSystemInfo::QtMobility));
X(info.hasFeatureSupported(QSystemInfo::BluetoothFeature));
X(info.hasFeatureSupported(QSystemInfo::CameraFeature));
X(info.hasFeatureSupported(QSystemInfo::FmradioFeature));
X(info.hasFeatureSupported(QSystemInfo::IrFeature));
X(info.hasFeatureSupported(QSystemInfo::LedFeature));
X(info.hasFeatureSupported(QSystemInfo::MemcardFeature));
X(info.hasFeatureSupported(QSystemInfo::UsbFeature));
X(info.hasFeatureSupported(QSystemInfo::VibFeature));
X(info.hasFeatureSupported(QSystemInfo::WlanFeature));
X(info.hasFeatureSupported(QSystemInfo::SimFeature));
X(info.hasFeatureSupported(QSystemInfo::LocationFeature));
X(info.hasFeatureSupported(QSystemInfo::VideoOutFeature));
X(info.hasFeatureSupported(QSystemInfo::HapticsFeature));
X(info.hasFeatureSupported(QSystemInfo::FmTransmitterFeature));
}
/* ------------------------------------------------------------------------- *
* test_systemdeviceinfo
* ------------------------------------------------------------------------- */
static void test_systemdeviceinfo(void)
{
QSystemDeviceInfo deviceinfo;
X(deviceinfo.batteryLevel());
X(deviceinfo.batteryStatus());
X(deviceinfo.currentBluetoothPowerState());
X(deviceinfo.currentPowerState());
X(deviceinfo.currentProfile());
X(deviceinfo.imei());
X(deviceinfo.imsi());
X(deviceinfo.inputMethodType());
X(deviceinfo.isDeviceLocked());
X(deviceinfo.isKeyboardFlipOpen());
X(deviceinfo.isWirelessKeyboardConnected());
X(deviceinfo.keyboardType());
X(deviceinfo.manufacturer());
X(deviceinfo.model());
X(deviceinfo.productName());
X(deviceinfo.simStatus());
X(deviceinfo.lockStatus());
}
/* ------------------------------------------------------------------------- *
* test_systemdisplayinfo
* ------------------------------------------------------------------------- */
static void test_systemdisplayinfo(void)
{
QSystemDisplayInfo displayinfo;
for( int display = 0; display < 4; ++display )
{
qDebug() << "";
qDebug() << "Display:" << display;
int depth = displayinfo.colorDepth(display);
qDebug() << " displayinfo.colorDepth() ->" << depth;
int value = displayinfo.displayBrightness(display);
qDebug() << " displayinfo.displayBrightness() ->" << value;
QSystemDisplayInfo::DisplayOrientation orientation = displayinfo.getOrientation(display);
qDebug() << " displayinfo.getOrientation() ->" << orientation;
float contrast = displayinfo.contrast(display);
qDebug() << " displayinfo.getContrast() ->" << contrast;
int dpiWidth = displayinfo.getDPIWidth(display);
qDebug() << " displayinfo.getDPIWidth() ->" << dpiWidth;
int dpiHeight = displayinfo.getDPIHeight(display);
qDebug() << " displayinfo.getDPIHeight() ->" << dpiHeight;
int physicalHeight = displayinfo.physicalHeight(display);
qDebug() << " displayinfo.physicalHeight() ->" << physicalHeight;
int physicalWidth = displayinfo.physicalWidth(display);
qDebug() << " displayinfo.physicalWidth() ->" << physicalWidth;
QSystemDisplayInfo::BacklightState state = displayinfo.backlightStatus(display);
qDebug() << " displayinfo.backlightStatus() ->" << state;
}
}
/* ------------------------------------------------------------------------- *
* test_systemstorageinfo
* ------------------------------------------------------------------------- */
static const char *human_size(qlonglong n)
{
if(n == 0) return "0B";
static char buf[256];
char *pos = buf;
char *end = buf + sizeof buf;
int b = n & 1023; n >>= 10;
int k = n & 1023; n >>= 10;
int m = n & 1023; n >>= 10;
int g = n & 1023; n >>= 10;
*pos = 0;
#if defined(Q_WS_WIN)
if(g) _snprintf_s(pos, sizeof(pos), end-pos,"%s%dGB", *buf?" ":"", g), pos = strchr(pos,0);
if(m) _snprintf_s(pos, sizeof(pos), end-pos,"%s%dMB", *buf?" ":"", m), pos = strchr(pos,0);
if(k) _snprintf_s(pos, sizeof(pos), end-pos,"%s%dkB", *buf?" ":"", k), pos = strchr(pos,0);
if(b) _snprintf_s(pos, sizeof(pos), end-pos,"%s%dB", *buf?" ":"", b), pos = strchr(pos,0);
#else
if(g) snprintf(pos, end-pos, "%s%dGB", *buf?" ":"", g), pos = strchr(pos,0);
if(m) snprintf(pos, end-pos, "%s%dMB", *buf?" ":"", m), pos = strchr(pos,0);
if(k) snprintf(pos, end-pos, "%s%dkB", *buf?" ":"", k), pos = strchr(pos,0);
if(b) snprintf(pos, end-pos, "%s%dB", *buf?" ":"", b), pos = strchr(pos,0);
#endif
return buf;
}
static void test_systemstorageinfo(void)
{
QSystemStorageInfo storageinfo;
QStringList lst = storageinfo.logicalDrives();
qDebug() << "storageinfo.logicalDrives ->" << lst;
for(int i = 0; i < lst.size(); ++i) {
const QString &drv = lst.at(i);
qDebug() << "Logical drive:" << drv;
qlonglong avail = storageinfo.availableDiskSpace(drv);
qDebug() << " storageinfo.availableDiskSpace() ->" << human_size(avail);
qlonglong total = storageinfo.totalDiskSpace(drv);
qDebug() << " storageinfo.totalDiskSpace() ->" << human_size(total);
QSystemStorageInfo::DriveType dtype = storageinfo.typeForDrive(drv);
qDebug() << " storageinfo.typeForDrive() ->" << dtype;
QString duri = storageinfo.uriForDrive(drv);
qDebug() << " storageinfo.uriForDrive() ->" << duri;
QSystemStorageInfo::StorageState dstate = storageinfo.getStorageState(drv);
qDebug() << " storageinfo.getStorageState() ->" << dstate;
}
}
/* ------------------------------------------------------------------------- *
* test_systemnetworkinfo
* ------------------------------------------------------------------------- */
static void test_systemnetworkinfo(void)
{
QSystemNetworkInfo networkinfo;
X(networkinfo.cellId());
X(networkinfo.currentMobileCountryCode());
X(networkinfo.currentMobileNetworkCode());
X(networkinfo.homeMobileCountryCode());
X(networkinfo.homeMobileNetworkCode());
X(networkinfo.locationAreaCode());
for(const symbol_t *sym = NetworkMode_lut; sym->key; ++sym) {
QtMobility::QSystemNetworkInfo::NetworkMode mode =
(QtMobility::QSystemNetworkInfo::NetworkMode) sym->val;
qDebug() << "";
qDebug() << "NetworkMode:" << sym->key;
QNetworkInterface iface = networkinfo.interfaceForMode(mode);
qDebug() << " networkinfo.interfaceForMode() ->" << iface;
QString macaddr = networkinfo.macAddress(mode);
qDebug() << " networkinfo.macAddress() ->" << macaddr;
QSystemNetworkInfo::NetworkStatus status = networkinfo.networkStatus(mode);
qDebug() << " networkinfo.networkStatus() ->" << status;
QString network = networkinfo.networkName(mode);
qDebug() << " networkinfo.netwoerkName() ->" << network;
int sigstr = networkinfo.networkSignalStrength(mode);
qDebug() << " networkinfo.networkSignalStrength() ->" << sigstr;
}
}
static void test_systemscreensaver(void)
{
QSystemScreenSaver screensaver;
X(screensaver.screenSaverInhibited());
X(screensaver.setScreenSaverInhibit());
}
static void test_systembatteryinfo(void)
{
QSystemBatteryInfo batInfo;
X(batInfo.chargerType());
X(batInfo.chargingState() );
X(batInfo.nominalCapacity());
X(batInfo.remainingCapacityPercent());
X(batInfo.remainingCapacity());
X(batInfo.voltage());
X(batInfo.remainingChargingTime());
X(batInfo.currentFlow());
X(batInfo.remainingCapacityBars());
X(batInfo.maxBars());
X(batInfo.batteryStatus());
X(batInfo.energyMeasurementUnit());
}
struct dummy_t
{
const char *name;
void (*func)(void);
} lut[] = {
#define ADD(x) {#x, test_##x }
ADD(systeminfo),
ADD(systemdeviceinfo),
ADD(systemstorageinfo),
ADD(systemnetworkinfo),
ADD(systemscreensaver),
ADD(systemdisplayinfo),
ADD(systembatteryinfo),
#undef ADD
{0,0}
};
static bool endswith(const char *str, const char *pat)
{
int slen = strlen(str);
int plen = strlen(pat);
return (slen >= plen) && !strcmp(str+slen-plen, pat);
}
int lookup_test(const char *name)
{
for(int i = 0; lut[i].name; ++i) {
if(!strcmp(lut[i].name, name)) return i;
}
for(int i = 0; lut[i].name; ++i) {
if(endswith(lut[i].name, name)) return i;
}
for(int i = 0; lut[i].name; ++i) {
if(strstr(lut[i].name, name)) return i;
}
return -1;
}
int main(int ac, char **av)
{
#if !defined(Q_WS_WIN)
if(!getenv("DISPLAY")) {
qDebug() << "$DISPLAY not set, assuming :0";
setenv("DISPLAY", ":0", 1);
}
if(!getenv("DBUS_SESSION_BUS_ADDRESS")) {
qDebug() << "session bus not configured";
}
#endif
QApplication app(ac, av, true);
if(ac < 2) {
qDebug() << "available tests:";
for(int k = 0; lut[k].name; ++k) {
qDebug() << *av << lut[k].name;
}
exit(0);
}
for(int i = 1; i < ac; ++i) {
const char *name = av[i];
int k = lookup_test(name);
if(k != -1) {
qDebug() << "";
qDebug() << "----(" << lut[k].name << ")----";
qDebug() << "";
lut[k].func();
} else if( !strcmp(name, "all")) {
for(int k = 0; lut[k].name; ++k) {
qDebug() << "";
qDebug() << "----(" << lut[k].name << ")----";
qDebug() << "";
lut[k].func();
}
} else {
break;
}
}
}
// EOF
<commit_msg>use screenCount.<commit_after>/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** 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.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QApplication>
#include <QDebug>
#include <QDesktopWidget>
#include "qsysteminfo.h"
using namespace QtMobility;
#define X(expr) qDebug() << #expr << "->" << (expr);
struct symbol_t
{
const char *key;
int val;
};
int lookup(const symbol_t *stab, const char *key, int def)
{
for(;stab->key;++stab) {
if(!strcmp(stab->key,key)) return stab->val;
}
return def;
}
const char *rlookup(const symbol_t *stab, int val, const char *def)
{
for(;stab->key; ++stab) {
if(stab->val == val) return stab->key;
}
return def;
}
#define SYM(x) { #x, x }
static const symbol_t Version_lut[] =
{
SYM(QSystemInfo::Os),
SYM(QSystemInfo::QtCore),
SYM(QSystemInfo::Firmware),
SYM(QSystemInfo::QtMobility),
{0,0}
};
static const symbol_t Feature_lut[] =
{
SYM(QSystemInfo::BluetoothFeature),
SYM(QSystemInfo::CameraFeature),
SYM(QSystemInfo::FmradioFeature),
SYM(QSystemInfo::IrFeature),
SYM(QSystemInfo::LedFeature),
SYM(QSystemInfo::MemcardFeature),
SYM(QSystemInfo::UsbFeature),
SYM(QSystemInfo::VibFeature),
SYM(QSystemInfo::WlanFeature),
SYM(QSystemInfo::SimFeature),
SYM(QSystemInfo::LocationFeature),
SYM(QSystemInfo::VideoOutFeature),
SYM(QSystemInfo::HapticsFeature),
SYM(QSystemInfo::FmTransmitterFeature),
{0,0}
};
static const symbol_t NetworkStatus_lut[] =
{
SYM(QSystemNetworkInfo::UndefinedStatus),
SYM(QSystemNetworkInfo::NoNetworkAvailable),
SYM(QSystemNetworkInfo::EmergencyOnly),
SYM(QSystemNetworkInfo::Searching),
SYM(QSystemNetworkInfo::Busy),
SYM(QSystemNetworkInfo::Connected),
SYM(QSystemNetworkInfo::HomeNetwork),
SYM(QSystemNetworkInfo::Denied),
SYM(QSystemNetworkInfo::Roaming),
{0,0}
};
static const symbol_t NetworkMode_lut[] =
{
SYM(QSystemNetworkInfo::UnknownMode),
SYM(QSystemNetworkInfo::GsmMode),
SYM(QSystemNetworkInfo::CdmaMode),
SYM(QSystemNetworkInfo::WcdmaMode),
SYM(QSystemNetworkInfo::WlanMode),
SYM(QSystemNetworkInfo::EthernetMode),
SYM(QSystemNetworkInfo::BluetoothMode),
SYM(QSystemNetworkInfo::WimaxMode),
SYM(QSystemNetworkInfo::GprsMode),
SYM(QSystemNetworkInfo::EdgeMode),
SYM(QSystemNetworkInfo::HspaMode),
SYM(QSystemNetworkInfo::LteMode),
{0,0}
};
/* ------------------------------------------------------------------------- *
* test_systeminfo
* ------------------------------------------------------------------------- */
static void test_systeminfo(void)
{
QSystemInfo info;
X(info.currentLanguage());
X(info.availableLanguages());
X(info.currentCountryCode());
X(info.version(QSystemInfo::Os));
X(info.version(QSystemInfo::QtCore));
X(info.version(QSystemInfo::Firmware));
X(info.version(QSystemInfo::QtMobility));
X(info.hasFeatureSupported(QSystemInfo::BluetoothFeature));
X(info.hasFeatureSupported(QSystemInfo::CameraFeature));
X(info.hasFeatureSupported(QSystemInfo::FmradioFeature));
X(info.hasFeatureSupported(QSystemInfo::IrFeature));
X(info.hasFeatureSupported(QSystemInfo::LedFeature));
X(info.hasFeatureSupported(QSystemInfo::MemcardFeature));
X(info.hasFeatureSupported(QSystemInfo::UsbFeature));
X(info.hasFeatureSupported(QSystemInfo::VibFeature));
X(info.hasFeatureSupported(QSystemInfo::WlanFeature));
X(info.hasFeatureSupported(QSystemInfo::SimFeature));
X(info.hasFeatureSupported(QSystemInfo::LocationFeature));
X(info.hasFeatureSupported(QSystemInfo::VideoOutFeature));
X(info.hasFeatureSupported(QSystemInfo::HapticsFeature));
X(info.hasFeatureSupported(QSystemInfo::FmTransmitterFeature));
}
/* ------------------------------------------------------------------------- *
* test_systemdeviceinfo
* ------------------------------------------------------------------------- */
static void test_systemdeviceinfo(void)
{
QSystemDeviceInfo deviceinfo;
X(deviceinfo.batteryLevel());
X(deviceinfo.batteryStatus());
X(deviceinfo.currentBluetoothPowerState());
X(deviceinfo.currentPowerState());
X(deviceinfo.currentProfile());
X(deviceinfo.imei());
X(deviceinfo.imsi());
X(deviceinfo.inputMethodType());
X(deviceinfo.isDeviceLocked());
X(deviceinfo.isKeyboardFlipOpen());
X(deviceinfo.isWirelessKeyboardConnected());
X(deviceinfo.keyboardType());
X(deviceinfo.manufacturer());
X(deviceinfo.model());
X(deviceinfo.productName());
X(deviceinfo.simStatus());
X(deviceinfo.lockStatus());
}
/* ------------------------------------------------------------------------- *
* test_systemdisplayinfo
* ------------------------------------------------------------------------- */
static void test_systemdisplayinfo(void)
{
QSystemDisplayInfo displayinfo;
QDesktopWidget wid;
for( int display = 0; display < wid.screenCount(); ++display )
{
qDebug() << "";
qDebug() << "Display:" << display;
int depth = displayinfo.colorDepth(display);
qDebug() << " displayinfo.colorDepth() ->" << depth;
int value = displayinfo.displayBrightness(display);
qDebug() << " displayinfo.displayBrightness() ->" << value;
QSystemDisplayInfo::DisplayOrientation orientation = displayinfo.getOrientation(display);
qDebug() << " displayinfo.getOrientation() ->" << orientation;
float contrast = displayinfo.contrast(display);
qDebug() << " displayinfo.getContrast() ->" << contrast;
int dpiWidth = displayinfo.getDPIWidth(display);
qDebug() << " displayinfo.getDPIWidth() ->" << dpiWidth;
int dpiHeight = displayinfo.getDPIHeight(display);
qDebug() << " displayinfo.getDPIHeight() ->" << dpiHeight;
int physicalHeight = displayinfo.physicalHeight(display);
qDebug() << " displayinfo.physicalHeight() ->" << physicalHeight;
int physicalWidth = displayinfo.physicalWidth(display);
qDebug() << " displayinfo.physicalWidth() ->" << physicalWidth;
QSystemDisplayInfo::BacklightState state = displayinfo.backlightStatus(display);
qDebug() << " displayinfo.backlightStatus() ->" << state;
}
}
/* ------------------------------------------------------------------------- *
* test_systemstorageinfo
* ------------------------------------------------------------------------- */
static const char *human_size(qlonglong n)
{
if(n == 0) return "0B";
static char buf[256];
char *pos = buf;
char *end = buf + sizeof buf;
int b = n & 1023; n >>= 10;
int k = n & 1023; n >>= 10;
int m = n & 1023; n >>= 10;
int g = n & 1023; n >>= 10;
*pos = 0;
#if defined(Q_WS_WIN)
if(g) _snprintf_s(pos, sizeof(pos), end-pos,"%s%dGB", *buf?" ":"", g), pos = strchr(pos,0);
if(m) _snprintf_s(pos, sizeof(pos), end-pos,"%s%dMB", *buf?" ":"", m), pos = strchr(pos,0);
if(k) _snprintf_s(pos, sizeof(pos), end-pos,"%s%dkB", *buf?" ":"", k), pos = strchr(pos,0);
if(b) _snprintf_s(pos, sizeof(pos), end-pos,"%s%dB", *buf?" ":"", b), pos = strchr(pos,0);
#else
if(g) snprintf(pos, end-pos, "%s%dGB", *buf?" ":"", g), pos = strchr(pos,0);
if(m) snprintf(pos, end-pos, "%s%dMB", *buf?" ":"", m), pos = strchr(pos,0);
if(k) snprintf(pos, end-pos, "%s%dkB", *buf?" ":"", k), pos = strchr(pos,0);
if(b) snprintf(pos, end-pos, "%s%dB", *buf?" ":"", b), pos = strchr(pos,0);
#endif
return buf;
}
static void test_systemstorageinfo(void)
{
QSystemStorageInfo storageinfo;
QStringList lst = storageinfo.logicalDrives();
qDebug() << "storageinfo.logicalDrives ->" << lst;
for(int i = 0; i < lst.size(); ++i) {
const QString &drv = lst.at(i);
qDebug() << "Logical drive:" << drv;
qlonglong avail = storageinfo.availableDiskSpace(drv);
qDebug() << " storageinfo.availableDiskSpace() ->" << human_size(avail);
qlonglong total = storageinfo.totalDiskSpace(drv);
qDebug() << " storageinfo.totalDiskSpace() ->" << human_size(total);
QSystemStorageInfo::DriveType dtype = storageinfo.typeForDrive(drv);
qDebug() << " storageinfo.typeForDrive() ->" << dtype;
QString duri = storageinfo.uriForDrive(drv);
qDebug() << " storageinfo.uriForDrive() ->" << duri;
QSystemStorageInfo::StorageState dstate = storageinfo.getStorageState(drv);
qDebug() << " storageinfo.getStorageState() ->" << dstate;
}
}
/* ------------------------------------------------------------------------- *
* test_systemnetworkinfo
* ------------------------------------------------------------------------- */
static void test_systemnetworkinfo(void)
{
QSystemNetworkInfo networkinfo;
X(networkinfo.cellId());
X(networkinfo.currentMobileCountryCode());
X(networkinfo.currentMobileNetworkCode());
X(networkinfo.homeMobileCountryCode());
X(networkinfo.homeMobileNetworkCode());
X(networkinfo.locationAreaCode());
for(const symbol_t *sym = NetworkMode_lut; sym->key; ++sym) {
QtMobility::QSystemNetworkInfo::NetworkMode mode =
(QtMobility::QSystemNetworkInfo::NetworkMode) sym->val;
qDebug() << "";
qDebug() << "NetworkMode:" << sym->key;
QNetworkInterface iface = networkinfo.interfaceForMode(mode);
qDebug() << " networkinfo.interfaceForMode() ->" << iface;
QString macaddr = networkinfo.macAddress(mode);
qDebug() << " networkinfo.macAddress() ->" << macaddr;
QSystemNetworkInfo::NetworkStatus status = networkinfo.networkStatus(mode);
qDebug() << " networkinfo.networkStatus() ->" << status;
QString network = networkinfo.networkName(mode);
qDebug() << " networkinfo.netwoerkName() ->" << network;
int sigstr = networkinfo.networkSignalStrength(mode);
qDebug() << " networkinfo.networkSignalStrength() ->" << sigstr;
}
}
static void test_systemscreensaver(void)
{
QSystemScreenSaver screensaver;
X(screensaver.screenSaverInhibited());
X(screensaver.setScreenSaverInhibit());
}
static void test_systembatteryinfo(void)
{
QSystemBatteryInfo batInfo;
X(batInfo.chargerType());
X(batInfo.chargingState() );
X(batInfo.nominalCapacity());
X(batInfo.remainingCapacityPercent());
X(batInfo.remainingCapacity());
X(batInfo.voltage());
X(batInfo.remainingChargingTime());
X(batInfo.currentFlow());
X(batInfo.remainingCapacityBars());
X(batInfo.maxBars());
X(batInfo.batteryStatus());
X(batInfo.energyMeasurementUnit());
}
struct dummy_t
{
const char *name;
void (*func)(void);
} lut[] = {
#define ADD(x) {#x, test_##x }
ADD(systeminfo),
ADD(systemdeviceinfo),
ADD(systemstorageinfo),
ADD(systemnetworkinfo),
ADD(systemscreensaver),
ADD(systemdisplayinfo),
ADD(systembatteryinfo),
#undef ADD
{0,0}
};
static bool endswith(const char *str, const char *pat)
{
int slen = strlen(str);
int plen = strlen(pat);
return (slen >= plen) && !strcmp(str+slen-plen, pat);
}
int lookup_test(const char *name)
{
for(int i = 0; lut[i].name; ++i) {
if(!strcmp(lut[i].name, name)) return i;
}
for(int i = 0; lut[i].name; ++i) {
if(endswith(lut[i].name, name)) return i;
}
for(int i = 0; lut[i].name; ++i) {
if(strstr(lut[i].name, name)) return i;
}
return -1;
}
int main(int ac, char **av)
{
#if !defined(Q_WS_WIN)
if(!getenv("DISPLAY")) {
qDebug() << "$DISPLAY not set, assuming :0";
setenv("DISPLAY", ":0", 1);
}
if(!getenv("DBUS_SESSION_BUS_ADDRESS")) {
qDebug() << "session bus not configured";
}
#endif
QApplication app(ac, av, true);
if(ac < 2) {
qDebug() << "available tests:";
for(int k = 0; lut[k].name; ++k) {
qDebug() << *av << lut[k].name;
}
exit(0);
}
for(int i = 1; i < ac; ++i) {
const char *name = av[i];
int k = lookup_test(name);
if(k != -1) {
qDebug() << "";
qDebug() << "----(" << lut[k].name << ")----";
qDebug() << "";
lut[k].func();
} else if( !strcmp(name, "all")) {
for(int k = 0; lut[k].name; ++k) {
qDebug() << "";
qDebug() << "----(" << lut[k].name << ")----";
qDebug() << "";
lut[k].func();
}
} else {
break;
}
}
}
// EOF
<|endoftext|> |
<commit_before>#include "CNetwork.hpp"
#include "CLog.hpp"
#include <beast/core/to_string.hpp>
#include <json.hpp>
using json = nlohmann::json;
void CNetwork::Initialize(std::string &&token)
{
m_Token = std::move(token);
m_HttpsStream.set_verify_mode(asio::ssl::verify_none);
// connect to REST API
asio::ip::tcp::resolver r{ m_IoService };
boost::system::error_code resolve_error;
auto target = r.resolve({ "discordapp.com", "https" }, resolve_error);
if (resolve_error)
{
CLog::Get()->Log(LogLevel::ERROR, "Can't resolve Discord API URL: {} ({})",
resolve_error.message(), resolve_error.value());
CSingleton::Destroy();
return;
}
asio::connect(m_HttpsStream.lowest_layer(), target);
// SSL handshake
m_HttpsStream.handshake(asio::ssl::stream_base::client);
// retrieve WebSocket host URL
HttpGet("", "/gateway", [this](HttpGetResponse res)
{
if (res.status != 200)
{
CLog::Get()->Log(LogLevel::ERROR, "Can't retrieve Discord gateway URL: {} ({})",
res.reason, res.status);
return;
}
auto gateway_res = json::parse(res.body);
std::string url = gateway_res["url"];
// get rid of protocol
size_t protocol_pos = url.find("wss://");
if (protocol_pos != std::string::npos)
url.erase(protocol_pos, 6); // 6 = length of "wss://"
m_WssStream.set_verify_mode(asio::ssl::verify_none);
// connect to gateway
asio::ip::tcp::resolver r{ m_IoService };
boost::system::error_code error;
auto target = r.resolve({ url, "https" }, error);
if (error)
{
CLog::Get()->Log(LogLevel::ERROR, "Can't resolve Discord gateway URL '{}': {} ({})",
url, error.message(), error.value());
return;
}
asio::connect(m_WssStream.lowest_layer(), target);
m_WssStream.handshake(asio::ssl::stream_base::client);
error.clear();
m_WebSocket.handshake(url, "/", error);
if (error)
{
CLog::Get()->Log(LogLevel::ERROR, "Can't upgrade to WSS protocol: {} ({})",
error.message(), error.value());
return;
}
Read();
json identify_payload = {
{ "op", 2 },
{ "d", {
{ "token", m_Token },
{ "v", 5 },
{ "compress", false },
{ "large_threshold", 100 },
{ "properties", {
{ "$os", "Windows" },
{ "$browser", "boost::asio" },
{ "$device", "SA-MP DCC plugin" },
{ "$referrer", "" },
{ "$referring_domain", "" }
}}
}}
};
CLog::Get()->Log(LogLevel::DEBUG, "identify payload: {}", identify_payload.dump(4));
m_WebSocket.write(asio::buffer(identify_payload.dump()));
});
m_IoThread = new std::thread([this]()
{
m_IoService.run();
});
}
CNetwork::~CNetwork()
{
if (m_IoThread)
{
m_IoThread->join();
delete m_IoThread;
m_IoThread = nullptr;
}
}
void CNetwork::Read()
{
m_WebSocket.async_read(m_WebSocketOpcode, m_WebSocketBuffer,
std::bind(&CNetwork::OnRead, this, std::placeholders::_1));
}
void CNetwork::OnRead(boost::system::error_code ec)
{
if (ec)
{
CLog::Get()->Log(LogLevel::ERROR, "Can't read from Discord websocket gateway: {} ({})",
ec.message(), ec.value());
}
else
{
json result = json::parse(beast::to_string(m_WebSocketBuffer.data()));
CLog::Get()->Log(LogLevel::DEBUG, "OnRead: data: {}", result.dump(4));
m_WebSocketBuffer.consume(m_WebSocketBuffer.size());
}
Read();
}
void CNetwork::HttpWriteRequest(std::string const &token, std::string const &method,
std::string const &url, std::string const &content, std::function<void()> &&callback)
{
beast::http::request<beast::http::string_body> req;
req.method = method;
req.url = "/api" + url;
req.version = 11;
req.headers.replace("Host", "discordapp.com");
if (!token.empty())
req.headers.replace("Authorization", "Bot " + token);
req.body = content;
beast::http::prepare(req);
beast::http::async_write(
m_HttpsStream,
req,
[url, method, callback](boost::system::error_code ec)
{
if (ec)
{
CLog::Get()->Log(LogLevel::ERROR, "Error while sending HTTP {} request to '{}': {}",
method, url, ec.message());
return;
}
if (callback)
callback();
}
);
}
void CNetwork::HttpReadResponse(HttpReadResponseCallback_t &&callback)
{
auto sb = std::make_shared<beast::streambuf>();
auto response = std::make_shared<beast::http::response<beast::http::streambuf_body>>();
beast::http::async_read(
m_HttpsStream,
*sb,
*response,
[callback, sb, response](boost::system::error_code ec)
{
if (ec)
{
CLog::Get()->Log(LogLevel::ERROR, "Error while retrieving HTTP response: {}",
ec.message());
return;
}
callback(sb, response);
}
);
}
void CNetwork::HttpGet(const std::string &token, std::string const &url,
HttpGetCallback_t &&callback)
{
HttpWriteRequest(token, "GET", url, "", [this, callback]()
{
HttpReadResponse([callback](SharedStreambuf_t sb, SharedResponse_t resp)
{
callback({ resp->status, resp->reason, beast::to_string(resp->body.data()),
beast::to_string(sb->data()) });
});
});
}
void CNetwork::HttpPost(const std::string &token, std::string const &url, std::string const &content)
{
HttpWriteRequest(token, "POST", url, content, nullptr);
}
<commit_msg>improve error handling<commit_after>#include "CNetwork.hpp"
#include "CLog.hpp"
#include <beast/core/to_string.hpp>
#include <json.hpp>
using json = nlohmann::json;
void CNetwork::Initialize(std::string &&token)
{
m_Token = std::move(token);
m_HttpsStream.set_verify_mode(asio::ssl::verify_none);
// connect to REST API
asio::ip::tcp::resolver r{ m_IoService };
boost::system::error_code error;
auto target = r.resolve({ "discordapp.com", "https" }, error);
if (error)
{
CLog::Get()->Log(LogLevel::ERROR, "Can't resolve Discord API URL: {} ({})",
error.message(), error.value());
CSingleton::Destroy();
return;
}
error.clear();
asio::connect(m_HttpsStream.lowest_layer(), target, error);
if (error)
{
CLog::Get()->Log(LogLevel::ERROR, "Can't connect to Discord API: {} ({})",
error.message(), error.value());
CSingleton::Destroy();
return;
}
// SSL handshake
error.clear();
m_HttpsStream.handshake(asio::ssl::stream_base::client, error);
if (error)
{
CLog::Get()->Log(LogLevel::ERROR, "Can't establish secured connection to Discord API: {} ({})",
error.message(), error.value());
CSingleton::Destroy();
return;
}
// retrieve WebSocket host URL
HttpGet("", "/gateway", [this](HttpGetResponse res)
{
if (res.status != 200)
{
CLog::Get()->Log(LogLevel::ERROR, "Can't retrieve Discord gateway URL: {} ({})",
res.reason, res.status);
return;
}
auto gateway_res = json::parse(res.body);
std::string url = gateway_res["url"];
// get rid of protocol
size_t protocol_pos = url.find("wss://");
if (protocol_pos != std::string::npos)
url.erase(protocol_pos, 6); // 6 = length of "wss://"
m_WssStream.set_verify_mode(asio::ssl::verify_none);
// connect to gateway
asio::ip::tcp::resolver r{ m_IoService };
boost::system::error_code error;
auto target = r.resolve({ url, "https" }, error);
if (error)
{
CLog::Get()->Log(LogLevel::ERROR, "Can't resolve Discord gateway URL '{}': {} ({})",
url, error.message(), error.value());
return;
}
error.clear();
asio::connect(m_WssStream.lowest_layer(), target, error);
if (error)
{
CLog::Get()->Log(LogLevel::ERROR, "Can't connect to Discord gateway: {} ({})",
error.message(), error.value());
return;
}
error.clear();
m_WssStream.handshake(asio::ssl::stream_base::client, error);
if (error)
{
CLog::Get()->Log(LogLevel::ERROR, "Can't establish secured connection to Discord gateway: {} ({})",
error.message(), error.value());
return;
}
error.clear();
m_WebSocket.handshake(url, "/", error);
if (error)
{
CLog::Get()->Log(LogLevel::ERROR, "Can't upgrade to WSS protocol: {} ({})",
error.message(), error.value());
return;
}
Read();
json identify_payload = {
{ "op", 2 },
{ "d", {
{ "token", m_Token },
{ "v", 5 },
{ "compress", false },
{ "large_threshold", 100 },
{ "properties", {
{ "$os", "Windows" },
{ "$browser", "boost::asio" },
{ "$device", "SA-MP DCC plugin" },
{ "$referrer", "" },
{ "$referring_domain", "" }
}}
}}
};
CLog::Get()->Log(LogLevel::DEBUG, "identify payload: {}", identify_payload.dump(4));
m_WebSocket.write(asio::buffer(identify_payload.dump()));
});
m_IoThread = new std::thread([this]()
{
m_IoService.run();
});
}
CNetwork::~CNetwork()
{
if (m_IoThread)
{
m_IoThread->join();
delete m_IoThread;
m_IoThread = nullptr;
}
}
void CNetwork::Read()
{
m_WebSocket.async_read(m_WebSocketOpcode, m_WebSocketBuffer,
std::bind(&CNetwork::OnRead, this, std::placeholders::_1));
}
void CNetwork::OnRead(boost::system::error_code ec)
{
if (ec)
{
CLog::Get()->Log(LogLevel::ERROR, "Can't read from Discord websocket gateway: {} ({})",
ec.message(), ec.value());
}
else
{
json result = json::parse(beast::to_string(m_WebSocketBuffer.data()));
CLog::Get()->Log(LogLevel::DEBUG, "OnRead: data: {}", result.dump(4));
m_WebSocketBuffer.consume(m_WebSocketBuffer.size());
}
Read();
}
void CNetwork::HttpWriteRequest(std::string const &token, std::string const &method,
std::string const &url, std::string const &content, std::function<void()> &&callback)
{
beast::http::request<beast::http::string_body> req;
req.method = method;
req.url = "/api" + url;
req.version = 11;
req.headers.replace("Host", "discordapp.com");
if (!token.empty())
req.headers.replace("Authorization", "Bot " + token);
req.body = content;
beast::http::prepare(req);
beast::http::async_write(
m_HttpsStream,
req,
[url, method, callback](boost::system::error_code ec)
{
if (ec)
{
CLog::Get()->Log(LogLevel::ERROR, "Error while sending HTTP {} request to '{}': {}",
method, url, ec.message());
return;
}
if (callback)
callback();
}
);
}
void CNetwork::HttpReadResponse(HttpReadResponseCallback_t &&callback)
{
auto sb = std::make_shared<beast::streambuf>();
auto response = std::make_shared<beast::http::response<beast::http::streambuf_body>>();
beast::http::async_read(
m_HttpsStream,
*sb,
*response,
[callback, sb, response](boost::system::error_code ec)
{
if (ec)
{
CLog::Get()->Log(LogLevel::ERROR, "Error while retrieving HTTP response: {}",
ec.message());
return;
}
callback(sb, response);
}
);
}
void CNetwork::HttpGet(const std::string &token, std::string const &url,
HttpGetCallback_t &&callback)
{
HttpWriteRequest(token, "GET", url, "", [this, callback]()
{
HttpReadResponse([callback](SharedStreambuf_t sb, SharedResponse_t resp)
{
callback({ resp->status, resp->reason, beast::to_string(resp->body.data()),
beast::to_string(sb->data()) });
});
});
}
void CNetwork::HttpPost(const std::string &token, std::string const &url, std::string const &content)
{
HttpWriteRequest(token, "POST", url, content, nullptr);
}
<|endoftext|> |
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osg/CopyOp>
#include <osg/Node>
#include <osg/StateSet>
#include <osg/Texture>
#include <osg/Drawable>
#include <osg/Array>
#include <osg/PrimitiveSet>
#include <osg/Shape>
#include <osg/StateAttribute>
#include <osg/Callback>
using namespace osg;
#define COPY_OP( TYPE, FLAG ) \
TYPE* CopyOp::operator() (const TYPE* obj) const \
{ \
if (obj && _flags&FLAG) \
return osg::clone(obj, *this); \
else \
return const_cast<TYPE*>(obj); \
}
COPY_OP( Object, DEEP_COPY_OBJECTS )
COPY_OP( Node, DEEP_COPY_NODES )
COPY_OP( StateSet, DEEP_COPY_STATESETS )
COPY_OP( Image, DEEP_COPY_IMAGES )
COPY_OP( Uniform, DEEP_COPY_UNIFORMS )
COPY_OP( StateAttributeCallback, DEEP_COPY_CALLBACKS )
COPY_OP( Drawable, DEEP_COPY_DRAWABLES )
COPY_OP( Texture, DEEP_COPY_TEXTURES )
COPY_OP( Array, DEEP_COPY_ARRAYS )
COPY_OP( PrimitiveSet, DEEP_COPY_PRIMITIVES )
COPY_OP( Shape, DEEP_COPY_SHAPES )
Referenced* CopyOp::operator() (const Referenced* ref) const
{
return const_cast<Referenced*>(ref);
}
StateAttribute* CopyOp::operator() (const StateAttribute* attr) const
{
if (attr && _flags&DEEP_COPY_STATEATTRIBUTES)
{
const Texture* textbase = dynamic_cast<const Texture*>(attr);
if (textbase)
{
return operator()(textbase);
}
else
{
return osg::clone(attr, *this);
}
}
else
return const_cast<StateAttribute*>(attr);
}
Callback* CopyOp::operator() (const Callback* nc) const
{
if (nc && _flags&DEEP_COPY_CALLBACKS)
{
// deep copy the full chain of callback
Callback* first = osg::clone(nc, *this);
if (!first) return 0;
first->setNestedCallback(0);
nc = nc->getNestedCallback();
while (nc)
{
Callback* ucb = osg::clone(nc, *this);
if (ucb)
{
ucb->setNestedCallback(0);
first->addNestedCallback(ucb);
}
nc = nc->getNestedCallback();
}
return first;
}
else
return const_cast<Callback*>(nc);
}
<commit_msg>Added testing for Drawables in the CopyOp::operator(Node*) to replicate the old functionality.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
*
* This library is open source and may be redistributed and/or modified under
* the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
* (at your option) any later version. The full license is in LICENSE file
* included with this distribution, and on the openscenegraph.org website.
*
* 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
* OpenSceneGraph Public License for more details.
*/
#include <osg/CopyOp>
#include <osg/Node>
#include <osg/StateSet>
#include <osg/Texture>
#include <osg/Drawable>
#include <osg/Array>
#include <osg/PrimitiveSet>
#include <osg/Shape>
#include <osg/StateAttribute>
#include <osg/Callback>
using namespace osg;
#define COPY_OP( TYPE, FLAG ) \
TYPE* CopyOp::operator() (const TYPE* obj) const \
{ \
if (obj && _flags&FLAG) \
return osg::clone(obj, *this); \
else \
return const_cast<TYPE*>(obj); \
}
COPY_OP( Object, DEEP_COPY_OBJECTS )
COPY_OP( StateSet, DEEP_COPY_STATESETS )
COPY_OP( Image, DEEP_COPY_IMAGES )
COPY_OP( Uniform, DEEP_COPY_UNIFORMS )
COPY_OP( StateAttributeCallback, DEEP_COPY_CALLBACKS )
COPY_OP( Drawable, DEEP_COPY_DRAWABLES )
COPY_OP( Texture, DEEP_COPY_TEXTURES )
COPY_OP( Array, DEEP_COPY_ARRAYS )
COPY_OP( PrimitiveSet, DEEP_COPY_PRIMITIVES )
COPY_OP( Shape, DEEP_COPY_SHAPES )
Referenced* CopyOp::operator() (const Referenced* ref) const
{
return const_cast<Referenced*>(ref);
}
Node* CopyOp::operator() (const Node* node) const
{
if (!node) return 0;
const Drawable* drawable = node->asDrawable();
if (drawable) return operator()(drawable);
else if (_flags&DEEP_COPY_NODES) return osg::clone(node, *this);
else return const_cast<Node*>(node);
}
StateAttribute* CopyOp::operator() (const StateAttribute* attr) const
{
if (attr && _flags&DEEP_COPY_STATEATTRIBUTES)
{
const Texture* textbase = dynamic_cast<const Texture*>(attr);
if (textbase)
{
return operator()(textbase);
}
else
{
return osg::clone(attr, *this);
}
}
else
return const_cast<StateAttribute*>(attr);
}
Callback* CopyOp::operator() (const Callback* nc) const
{
if (nc && _flags&DEEP_COPY_CALLBACKS)
{
// deep copy the full chain of callback
Callback* first = osg::clone(nc, *this);
if (!first) return 0;
first->setNestedCallback(0);
nc = nc->getNestedCallback();
while (nc)
{
Callback* ucb = osg::clone(nc, *this);
if (ucb)
{
ucb->setNestedCallback(0);
first->addNestedCallback(ucb);
}
nc = nc->getNestedCallback();
}
return first;
}
else
return const_cast<Callback*>(nc);
}
<|endoftext|> |
<commit_before>#include <map>
#include <gtest/gtest.h>
#include "uint128_t.h"
static const std::map <uint32_t, std::string> tests = {
std::make_pair(2, "10000100000101011000010101101100"),
std::make_pair(3, "12201102210121112101"),
std::make_pair(4, "2010011120111230"),
std::make_pair(5, "14014244043144"),
std::make_pair(6, "1003520344444"),
std::make_pair(7, "105625466632"),
std::make_pair(8, "20405302554"),
std::make_pair(9, "5642717471"),
std::make_pair(10, "2216002924"),
std::make_pair(11, "a3796a883"),
std::make_pair(12, "51a175124"),
std::make_pair(13, "294145645"),
std::make_pair(14, "170445352"),
std::make_pair(15, "ce82d6d4"),
std::make_pair(16, "8415856c"),
// std::make_pair(256, "uint128_t"),
};
TEST(Function, str){
// number of leading 0s
const std::string::size_type leading = 5;
// make sure all of the test strings create the ASCII version of the string
const uint128_t original(2216002924);
for(std::pair <uint32_t const, std::string> t : tests){
EXPECT_EQ(original.str(t.first), t.second);
}
// add leading zeros
for(uint32_t base = 2; base <= 16; base++){
EXPECT_EQ(original.str(base, tests.at(base).size() + leading), std::string(leading, '0') + tests.at(base));
}
}
TEST(External, ostream){
const uint128_t value(0xfedcba9876543210ULL);
// write out octal uint128_t
std::stringstream oct; oct << std::oct << value;
EXPECT_EQ(oct.str(), "1773345651416625031020");
// write out decimal uint128_t
std::stringstream dec; dec << std::dec << value;
EXPECT_EQ(dec.str(), "18364758544493064720");
// write out hexadecimal uint128_t
std::stringstream hex; hex << std::hex << value;
EXPECT_EQ(hex.str(), "fedcba9876543210");
// zero
std::stringstream zero; zero << uint128_t();
EXPECT_EQ(zero.str(), "0");
}
<commit_msg>added test for export_bits<commit_after>#include <map>
#include <gtest/gtest.h>
#include "uint128_t.h"
static const std::map <uint32_t, std::string> tests = {
std::make_pair(2, "10000100000101011000010101101100"),
std::make_pair(3, "12201102210121112101"),
std::make_pair(4, "2010011120111230"),
std::make_pair(5, "14014244043144"),
std::make_pair(6, "1003520344444"),
std::make_pair(7, "105625466632"),
std::make_pair(8, "20405302554"),
std::make_pair(9, "5642717471"),
std::make_pair(10, "2216002924"),
std::make_pair(11, "a3796a883"),
std::make_pair(12, "51a175124"),
std::make_pair(13, "294145645"),
std::make_pair(14, "170445352"),
std::make_pair(15, "ce82d6d4"),
std::make_pair(16, "8415856c"),
// std::make_pair(256, "uint128_t"),
};
TEST(Function, str){
// number of leading 0s
const std::string::size_type leading = 5;
// make sure all of the test strings create the ASCII version of the string
const uint128_t original(2216002924);
for(std::pair <uint32_t const, std::string> t : tests){
EXPECT_EQ(original.str(t.first), t.second);
}
// add leading zeros
for(uint32_t base = 2; base <= 16; base++){
EXPECT_EQ(original.str(base, tests.at(base).size() + leading), std::string(leading, '0') + tests.at(base));
}
}
TEST(Function, export_bits){
const uint64_t u64 = 0x0123456789abcdefULL;
const uint128_t value = u64;
EXPECT_EQ(value, u64);
const std::vector<uint8_t> full = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef
};
std::vector<uint8_t> bits;
value.export_bits(bits);
EXPECT_EQ(bits, full);
}
TEST(External, ostream){
const uint128_t value(0xfedcba9876543210ULL);
// write out octal uint128_t
std::stringstream oct; oct << std::oct << value;
EXPECT_EQ(oct.str(), "1773345651416625031020");
// write out decimal uint128_t
std::stringstream dec; dec << std::dec << value;
EXPECT_EQ(dec.str(), "18364758544493064720");
// write out hexadecimal uint128_t
std::stringstream hex; hex << std::hex << value;
EXPECT_EQ(hex.str(), "fedcba9876543210");
// zero
std::stringstream zero; zero << uint128_t();
EXPECT_EQ(zero.str(), "0");
}
<|endoftext|> |
<commit_before>#include <ROOT/TDFUtils.hxx>
#include <ROOT/TRootDS.hxx>
#include <ROOT/TSeq.hxx>
#include <TClass.h>
#include <algorithm>
#include <vector>
namespace ROOT {
namespace Experimental {
namespace TDF {
std::vector<void *> TRootDS::GetColumnReadersImpl(std::string_view name, const std::type_info &)
{
const auto index = std::distance(fListOfBranches.begin(), std::find(fListOfBranches.begin(), fListOfBranches.end(), name));
std::vector<void *> ret(fNSlots);
for (auto slot : ROOT::TSeqU(fNSlots)) {
ret[slot] = (void *)&fBranchAddresses[index][slot];
}
return ret;
}
TRootDS::TRootDS(std::string_view treeName, std::string_view fileNameGlob)
: fTreeName(treeName), fFileNameGlob(fileNameGlob), fModelChain(std::string(treeName).c_str())
{
fModelChain.Add(fFileNameGlob.c_str());
auto &lob = *fModelChain.GetListOfBranches();
fListOfBranches.resize(lob.GetEntries());
std::transform(lob.begin(), lob.end(), fListOfBranches.begin(), [](TObject *o) { return o->GetName(); });
}
TRootDS::~TRootDS()
{
for (auto addr : fAddressesToFree) {
delete addr;
}
}
std::string TRootDS::GetTypeName(std::string_view colName) const
{
if (!HasColumn(colName)) {
std::string e = "The dataset does not have column ";
e += colName;
throw std::runtime_error(e);
}
// TODO: we need to factor out the routine for the branch alone...
// Maybe a cache for the names?
auto typeName = ROOT::Internal::TDF::ColumnName2ColumnTypeName(std::string(colName).c_str(), &fModelChain,
nullptr /*TCustomColumnBase here*/);
// We may not have yet loaded the library where the dictionary of this type
// is
TClass::GetClass(typeName.c_str());
return typeName;
}
const std::vector<std::string> &TRootDS::GetColumnNames() const
{
return fListOfBranches;
}
bool TRootDS::HasColumn(std::string_view colName) const
{
if (!fListOfBranches.empty())
GetColumnNames();
return fListOfBranches.end() != std::find(fListOfBranches.begin(), fListOfBranches.end(), colName);
}
void TRootDS::InitSlot(unsigned int slot, ULong64_t firstEntry)
{
auto chain = new TChain(fTreeName.c_str());
fChains[slot].reset(chain);
chain->Add(fFileNameGlob.c_str());
chain->GetEntry(firstEntry);
TString setBranches;
for (auto i : ROOT::TSeqU(fListOfBranches.size())) {
auto colName = fListOfBranches[i].c_str();
auto &addr = fBranchAddresses.at(i).at(slot);
auto typeName = GetTypeName(colName);
auto typeClass = TClass::GetClass(typeName.c_str());
if (typeClass) {
chain->SetBranchAddress(colName,&addr, nullptr, typeClass, EDataType(0), true);
} else {
if (!addr) {
addr = new double();
fAddressesToFree.emplace_back((double *)addr);
}
chain->SetBranchAddress(colName, addr);
}
}
}
const std::vector<std::pair<ULong64_t, ULong64_t>> &TRootDS::GetEntryRanges() const
{
if (fEntryRanges.empty()) {
throw std::runtime_error("No ranges are available. Did you set the number of slots?");
}
return fEntryRanges;
}
void TRootDS::SetEntry(unsigned int slot, ULong64_t entry)
{
fChains[slot]->GetEntry(entry);
}
void TRootDS::SetNSlots(unsigned int nSlots)
{
assert(0U == fNSlots && "Setting the number of slots even if the number of slots is different from zero.");
fNSlots = nSlots;
const auto nColumns = fListOfBranches.size();
// Initialise the entire set of addresses
fBranchAddresses.resize(nColumns, std::vector<void *>(fNSlots, nullptr));
fChains.resize(fNSlots);
auto nentries = fModelChain.GetEntries();
auto chunkSize = nentries / fNSlots;
auto reminder = 1U == fNSlots ? 0 : nentries % fNSlots;
auto start = 0UL;
auto end = 0UL;
for (auto i : ROOT::TSeqU(fNSlots)) {
start = end;
end += chunkSize;
fEntryRanges.emplace_back(start, end);
(void)i;
}
fEntryRanges.back().second += reminder;
}
} // ns TDF
} // ns Experimental
} // ns ROOT
<commit_msg>[TDF] We need to safely create the chains<commit_after>#include <ROOT/TDFUtils.hxx>
#include <ROOT/TRootDS.hxx>
#include <ROOT/TSeq.hxx>
#include <TClass.h>
#include <TROOT.h> // For the gROOTMutex
#include <TVirtualMutex.h> // For the R__LOCKGUARD
#include <algorithm>
#include <vector>
namespace ROOT {
namespace Experimental {
namespace TDF {
std::vector<void *> TRootDS::GetColumnReadersImpl(std::string_view name, const std::type_info &)
{
const auto index = std::distance(fListOfBranches.begin(), std::find(fListOfBranches.begin(), fListOfBranches.end(), name));
std::vector<void *> ret(fNSlots);
for (auto slot : ROOT::TSeqU(fNSlots)) {
ret[slot] = (void *)&fBranchAddresses[index][slot];
}
return ret;
}
TRootDS::TRootDS(std::string_view treeName, std::string_view fileNameGlob)
: fTreeName(treeName), fFileNameGlob(fileNameGlob), fModelChain(std::string(treeName).c_str())
{
fModelChain.Add(fFileNameGlob.c_str());
auto &lob = *fModelChain.GetListOfBranches();
fListOfBranches.resize(lob.GetEntries());
std::transform(lob.begin(), lob.end(), fListOfBranches.begin(), [](TObject *o) { return o->GetName(); });
}
TRootDS::~TRootDS()
{
for (auto addr : fAddressesToFree) {
delete addr;
}
}
std::string TRootDS::GetTypeName(std::string_view colName) const
{
if (!HasColumn(colName)) {
std::string e = "The dataset does not have column ";
e += colName;
throw std::runtime_error(e);
}
// TODO: we need to factor out the routine for the branch alone...
// Maybe a cache for the names?
auto typeName = ROOT::Internal::TDF::ColumnName2ColumnTypeName(std::string(colName).c_str(), &fModelChain,
nullptr /*TCustomColumnBase here*/);
// We may not have yet loaded the library where the dictionary of this type
// is
TClass::GetClass(typeName.c_str());
return typeName;
}
const std::vector<std::string> &TRootDS::GetColumnNames() const
{
return fListOfBranches;
}
bool TRootDS::HasColumn(std::string_view colName) const
{
if (!fListOfBranches.empty())
GetColumnNames();
return fListOfBranches.end() != std::find(fListOfBranches.begin(), fListOfBranches.end(), colName);
}
void TRootDS::InitSlot(unsigned int slot, ULong64_t firstEntry)
{
TChain *chain;
{
R__LOCKGUARD(gROOTMutex);
chain = new TChain(fTreeName.c_str());
}
chain->ResetBit(kMustCleanup);
chain->Add(fFileNameGlob.c_str());
chain->GetEntry(firstEntry);
TString setBranches;
for (auto i : ROOT::TSeqU(fListOfBranches.size())) {
auto colName = fListOfBranches[i].c_str();
auto &addr = fBranchAddresses.at(i).at(slot);
auto typeName = GetTypeName(colName);
auto typeClass = TClass::GetClass(typeName.c_str());
if (typeClass) {
chain->SetBranchAddress(colName,&addr, nullptr, typeClass, EDataType(0), true);
} else {
if (!addr) {
addr = new double();
fAddressesToFree.emplace_back((double *)addr);
}
chain->SetBranchAddress(colName, addr);
}
}
fChains[slot].reset(chain);
}
const std::vector<std::pair<ULong64_t, ULong64_t>> &TRootDS::GetEntryRanges() const
{
if (fEntryRanges.empty()) {
throw std::runtime_error("No ranges are available. Did you set the number of slots?");
}
return fEntryRanges;
}
void TRootDS::SetEntry(unsigned int slot, ULong64_t entry)
{
fChains[slot]->GetEntry(entry);
}
void TRootDS::SetNSlots(unsigned int nSlots)
{
assert(0U == fNSlots && "Setting the number of slots even if the number of slots is different from zero.");
fNSlots = nSlots;
const auto nColumns = fListOfBranches.size();
// Initialise the entire set of addresses
fBranchAddresses.resize(nColumns, std::vector<void *>(fNSlots, nullptr));
fChains.resize(fNSlots);
auto nentries = fModelChain.GetEntries();
auto chunkSize = nentries / fNSlots;
auto reminder = 1U == fNSlots ? 0 : nentries % fNSlots;
auto start = 0UL;
auto end = 0UL;
for (auto i : ROOT::TSeqU(fNSlots)) {
start = end;
end += chunkSize;
fEntryRanges.emplace_back(start, end);
(void)i;
}
fEntryRanges.back().second += reminder;
}
} // ns TDF
} // ns Experimental
} // ns ROOT
<|endoftext|> |
<commit_before><commit_msg>Create solution.cpp<commit_after><|endoftext|> |
<commit_before><commit_msg>Add clusqmgr<commit_after><|endoftext|> |
<commit_before>#include <vpr/vprConfig.h>
#include <cppunit/TestSuite.h>
#include <cppunit/TextTestRunner.h>
#include <cppunit/extensions/MetricRegistry.h>
// Common (sim and real) tests.
#include <TestCases/Socket/SocketTest.h>
#include <TestCases/Socket/NonBlockingSocketsTest.h>
#include <TestCases/Socket/SocketCopyConstructorTest.h>
#include <TestCases/Socket/SocketConnectorAcceptorTest.h>
#include <TestCases/Thread/ThreadTest.h>
#include <TestCases/IO/Socket/InetAddrTest.h>
#include <TestCases/IO/SelectorTest.h>
#include <TestCases/IO/Stats/SocketBandwidthIOStatsTest.h>
#include <TestCases/Util/ReturnStatusTest.h>
#include <TestCases/Util/IntervalTest.h>
#include <TestCases/Util/GUIDTest.h>
// Simulator tests.
#ifdef VPR_SIMULATOR
# include <TestCases/Simulator/SimSelectorTest.h>
# include <TestCases/Simulator/SocketSimulatorTest.h>
// Real tests.
#else
#endif
#include <TestCases/BoostTest.h>
#include <TestCases/SystemTest.h>
#include <vpr/Thread/Thread.h>
#include <vpr/Util/Debug.h>
#include <vpr/System.h>
//#define vprtest_RANDOM_SEED 1
#ifdef VPR_SIMULATOR
static void run (void* arg)
{
while ( true )
{
vpr::sim::Controller::instance()->processNextEvent();
vpr::Thread::yield();
}
}
#endif
int main (int ac, char **av)
{
vprDEBUG(vprDBG_ALL,0) << "\n\n-----------------------------------------\n" << vprDEBUG_FLUSH;
vprDEBUG(vprDBG_ALL,0) << "Starting test\n" << vprDEBUG_FLUSH; // Do this here to get init text out of the way
// Init random number generation
unsigned int random_seed;
#ifdef vprtest_RANDOM_SEED
timeval cur_time;
vpr::System::gettimeofday(&cur_time);
random_seed = cur_time.tv_usec;
vprDEBUG(vprDBG_ALL,0) << "timeval.usec: " << cur_time.tv_usec << std::endl << vprDEBUG_FLUSH;
#else
random_seed = 1; // Use this for repeatability
#endif
vprDEBUG(vprDBG_ALL,0) << " Random seed: " << random_seed << std::endl
<< vprDEBUG_FLUSH;
srandom(random_seed);
srand(random_seed);
#ifdef VPR_SIMULATOR // ------ CONFIGURE SIM NETWORK ------ //
std::string path_base;
if ( ! vpr::System::getenv("VPR_TEST_DIR", path_base).success() )
{
vprDEBUG(vprDBG_ALL, vprDBG_WARNING_LVL)
<< clrOutBOLD(clrRED, "WARNING: Could not construct sim network graph -- $VPR_TEST_DIR not set\n")
<< vprDEBUG_FLUSH;
}
else
{
vpr::sim::Controller::instance()->constructNetwork(path_base.append("/test_network.tiers"));
}
vpr::Thread sim_thread(run);
#endif
// -------- CONFIGURE METRIC REGISTRY ------- //
CppUnit::MetricRegistry* metric_reg = CppUnit::MetricRegistry::instance();
std::string metric_prefix; // Prefix for all metric labels (mode/hostname)
std::string host_name = vpr::System::getHostname();
metric_prefix = host_name + "/";
#ifdef _DEBUG
metric_prefix += "Debug/";
#endif
#ifdef _OPT
metric_prefix += "Opt/";
#endif
#ifdef VPR_SIMULATOR
metric_prefix += "Sim/";
#endif
std::cout << "Setting up metrics for host: " << host_name << std::endl;
std::cout << " prefix: " << metric_prefix << std::endl;
metric_reg->setPrefix(metric_prefix);
metric_reg->setFilename("vapor_metrics.txt");
metric_reg->setMetric("Main/MetricTest", 1221.75f);
CppUnit::TextTestRunner runner;
//------------------------------------
// noninteractive
//------------------------------------
// create non-interactive test suite
CppUnit::TestSuite* noninteractive_suite = new CppUnit::TestSuite("noninteractive");
// add tests to the suite
#ifdef VPR_SIMULATOR
// Simulator tests.
noninteractive_suite->addTest(vprTest::SocketSimulatorTest::suite());
noninteractive_suite->addTest(vprTest::SimSelectorTest::suite());
#else
// Real tests.
#endif
// Common tests (both real and simulator).
noninteractive_suite->addTest(vprTest::ReturnStatusTest::suite());
noninteractive_suite->addTest(vprTest::BoostTest::suite());
noninteractive_suite->addTest(vprTest::SystemTest::suite());
noninteractive_suite->addTest(vprTest::IntervalTest::suite());
noninteractive_suite->addTest(vprTest::GUIDTest::suite());
noninteractive_suite->addTest(vprTest::InetAddrTest::suite());
noninteractive_suite->addTest(vprTest::SocketTest::suite());
noninteractive_suite->addTest(vprTest::NonBlockingSocketTest::suite());
// noninteractive_suite->addTest(vprTest::SocketCopyConstructorTest::suite());
noninteractive_suite->addTest(vprTest::SocketConnectorAcceptorTest::suite());
noninteractive_suite->addTest(vprTest::SelectorTest::suite());
// Add the test suite to the runner
runner.addTest( noninteractive_suite );
// ------------------------------
// METRICS
// ------------------------------
CppUnit::TestSuite* metrics_suite = new CppUnit::TestSuite("metrics");
metrics_suite->addTest(vprTest::IntervalTest::metric_suite());
metrics_suite->addTest(vprTest::GUIDTest::metric_suite());
metrics_suite->addTest(vprTest::SocketBandwidthIOStatsTest::metric_suite());
runner.addTest(metrics_suite);
//noninteractive_suite->addTest(metrics_suite);
// -------------------------------
// INTERACTIVE
// -------------------------------
CppUnit::TestSuite* interactive_suite = new CppUnit::TestSuite("interactive");
interactive_suite->addTest(vprTest::ThreadTest::suite());
runner.addTest(interactive_suite);
// run all test suites
if ( ac > 1 )
{
if ( strcmp(av[1], "interactive") == 0 )
{
runner.run("interactive");
}
else if ( strcmp(av[1], "noninteractive") == 0 )
{
runner.run("noninteractive");
}
else if ( strcmp(av[1], "metrics") == 0 )
{
runner.run("metrics");
}
else if ( strcmp(av[1], "all") == 0 )
{
runner.run("noninteractive");
runner.run("metrics");
runner.run("interactive");
}
}
else
{
runner.run("noninteractive");
runner.run("metrics");
runner.run("interactive");
}
return 0;
}
<commit_msg>Make the error critical if VPR_TEST_DIR is not set.<commit_after>#include <vpr/vprConfig.h>
#include <cppunit/TestSuite.h>
#include <cppunit/TextTestRunner.h>
#include <cppunit/extensions/MetricRegistry.h>
// Common (sim and real) tests.
#include <TestCases/Socket/SocketTest.h>
#include <TestCases/Socket/NonBlockingSocketsTest.h>
#include <TestCases/Socket/SocketCopyConstructorTest.h>
#include <TestCases/Socket/SocketConnectorAcceptorTest.h>
#include <TestCases/Thread/ThreadTest.h>
#include <TestCases/IO/Socket/InetAddrTest.h>
#include <TestCases/IO/SelectorTest.h>
#include <TestCases/IO/Stats/SocketBandwidthIOStatsTest.h>
#include <TestCases/Util/ReturnStatusTest.h>
#include <TestCases/Util/IntervalTest.h>
#include <TestCases/Util/GUIDTest.h>
// Simulator tests.
#ifdef VPR_SIMULATOR
# include <TestCases/Simulator/SimSelectorTest.h>
# include <TestCases/Simulator/SocketSimulatorTest.h>
// Real tests.
#else
#endif
#include <TestCases/BoostTest.h>
#include <TestCases/SystemTest.h>
#include <vpr/Thread/Thread.h>
#include <vpr/Util/Debug.h>
#include <vpr/System.h>
//#define vprtest_RANDOM_SEED 1
#ifdef VPR_SIMULATOR
static void run (void* arg)
{
while ( true )
{
vpr::sim::Controller::instance()->processNextEvent();
vpr::Thread::yield();
}
}
#endif
int main (int ac, char **av)
{
vprDEBUG(vprDBG_ALL,0) << "\n\n-----------------------------------------\n" << vprDEBUG_FLUSH;
vprDEBUG(vprDBG_ALL,0) << "Starting test\n" << vprDEBUG_FLUSH; // Do this here to get init text out of the way
// Init random number generation
unsigned int random_seed;
#ifdef vprtest_RANDOM_SEED
timeval cur_time;
vpr::System::gettimeofday(&cur_time);
random_seed = cur_time.tv_usec;
vprDEBUG(vprDBG_ALL,0) << "timeval.usec: " << cur_time.tv_usec << std::endl << vprDEBUG_FLUSH;
#else
random_seed = 1; // Use this for repeatability
#endif
vprDEBUG(vprDBG_ALL,0) << " Random seed: " << random_seed << std::endl
<< vprDEBUG_FLUSH;
srandom(random_seed);
srand(random_seed);
#ifdef VPR_SIMULATOR // ------ CONFIGURE SIM NETWORK ------ //
std::string path_base;
if ( ! vpr::System::getenv("VPR_TEST_DIR", path_base).success() )
{
vprDEBUG(vprDBG_ALL, vprDBG_CRITICAL_LVL)
<< clrOutBOLD(clrRED, "WARNING: Could not construct sim network graph -- $VPR_TEST_DIR not set\n")
<< vprDEBUG_FLUSH;
exit(0);
}
else
{
vpr::sim::Controller::instance()->constructNetwork(path_base.append("/test_network.tiers"));
}
vpr::Thread sim_thread(run);
#endif
// -------- CONFIGURE METRIC REGISTRY ------- //
CppUnit::MetricRegistry* metric_reg = CppUnit::MetricRegistry::instance();
std::string metric_prefix; // Prefix for all metric labels (mode/hostname)
std::string host_name = vpr::System::getHostname();
metric_prefix = host_name + "/";
#ifdef _DEBUG
metric_prefix += "Debug/";
#endif
#ifdef _OPT
metric_prefix += "Opt/";
#endif
#ifdef VPR_SIMULATOR
metric_prefix += "Sim/";
#endif
std::cout << "Setting up metrics for host: " << host_name << std::endl;
std::cout << " prefix: " << metric_prefix << std::endl;
metric_reg->setPrefix(metric_prefix);
metric_reg->setFilename("vapor_metrics.txt");
metric_reg->setMetric("Main/MetricTest", 1221.75f);
CppUnit::TextTestRunner runner;
//------------------------------------
// noninteractive
//------------------------------------
// create non-interactive test suite
CppUnit::TestSuite* noninteractive_suite = new CppUnit::TestSuite("noninteractive");
// add tests to the suite
#ifdef VPR_SIMULATOR
// Simulator tests.
noninteractive_suite->addTest(vprTest::SocketSimulatorTest::suite());
noninteractive_suite->addTest(vprTest::SimSelectorTest::suite());
#else
// Real tests.
#endif
// Common tests (both real and simulator).
noninteractive_suite->addTest(vprTest::ReturnStatusTest::suite());
noninteractive_suite->addTest(vprTest::BoostTest::suite());
noninteractive_suite->addTest(vprTest::SystemTest::suite());
noninteractive_suite->addTest(vprTest::IntervalTest::suite());
noninteractive_suite->addTest(vprTest::GUIDTest::suite());
noninteractive_suite->addTest(vprTest::InetAddrTest::suite());
noninteractive_suite->addTest(vprTest::SocketTest::suite());
noninteractive_suite->addTest(vprTest::NonBlockingSocketTest::suite());
// noninteractive_suite->addTest(vprTest::SocketCopyConstructorTest::suite());
noninteractive_suite->addTest(vprTest::SocketConnectorAcceptorTest::suite());
noninteractive_suite->addTest(vprTest::SelectorTest::suite());
// Add the test suite to the runner
runner.addTest( noninteractive_suite );
// ------------------------------
// METRICS
// ------------------------------
CppUnit::TestSuite* metrics_suite = new CppUnit::TestSuite("metrics");
metrics_suite->addTest(vprTest::IntervalTest::metric_suite());
metrics_suite->addTest(vprTest::GUIDTest::metric_suite());
metrics_suite->addTest(vprTest::SocketBandwidthIOStatsTest::metric_suite());
runner.addTest(metrics_suite);
//noninteractive_suite->addTest(metrics_suite);
// -------------------------------
// INTERACTIVE
// -------------------------------
CppUnit::TestSuite* interactive_suite = new CppUnit::TestSuite("interactive");
interactive_suite->addTest(vprTest::ThreadTest::suite());
runner.addTest(interactive_suite);
// run all test suites
if ( ac > 1 )
{
if ( strcmp(av[1], "interactive") == 0 )
{
runner.run("interactive");
}
else if ( strcmp(av[1], "noninteractive") == 0 )
{
runner.run("noninteractive");
}
else if ( strcmp(av[1], "metrics") == 0 )
{
runner.run("metrics");
}
else if ( strcmp(av[1], "all") == 0 )
{
runner.run("noninteractive");
runner.run("metrics");
runner.run("interactive");
}
}
else
{
runner.run("noninteractive");
runner.run("metrics");
runner.run("interactive");
}
return 0;
}
<|endoftext|> |
<commit_before>/**
Copyright (c) 2017 Ryan Porter
*/
#include "polyDeformerWeights.h"
#include "polyFlipCmd.h"
#include "polyMirrorCmd.h"
#include "polySkinWeights.h"
#include "polySymmetryTool.h"
#include "polySymmetryCmd.h"
#include "polySymmetryNode.h"
#include "sceneCache.h"
#include <maya/MFnPlugin.h>
#include <maya/MGlobal.h>
#include <maya/MTypeId.h>
#include <maya/MString.h>
#include <maya/MStatus.h>
const char* kAUTHOR = "Ryan Porter";
const char* kVERSION = "0.3.0";
const char* kREQUIRED_API_VERSION = "Any";
MString PolyDeformerWeightsCommand::COMMAND_NAME = "polyDeformerWeights";
MString PolyFlipCommand::COMMAND_NAME = "polyFlip";
MString PolyMirrorCommand::COMMAND_NAME = "polyMirror";
MString PolySkinWeightsCommand::COMMAND_NAME = "polySkinWeights";
MString PolySymmetryContextCmd::COMMAND_NAME = "polySymmetryCtx";
MString PolySymmetryCommand::COMMAND_NAME = "polySymmetry";
MString PolySymmetryNode::NODE_NAME = "polySymmetryData";
MTypeId PolySymmetryNode::NODE_ID = 0x00126b0d;
#define REGISTER_COMMAND(CMD) CHECK_MSTATUS_AND_RETURN_IT(fnPlugin.registerCommand(CMD::COMMAND_NAME, CMD::creator, CMD::getSyntax));
#define DEREGISTER_COMMAND(CMD) CHECK_MSTATUS_AND_RETURN_IT(fnPlugin.deregisterCommand(CMD::COMMAND_NAME))
bool menuCreated = false;
MStatus initializePlugin(MObject obj)
{
MStatus status;
MFnPlugin fnPlugin(obj, kAUTHOR, kVERSION, kREQUIRED_API_VERSION);
status = fnPlugin.registerContextCommand(
PolySymmetryContextCmd::COMMAND_NAME,
PolySymmetryContextCmd::creator,
PolySymmetryCommand::COMMAND_NAME,
PolySymmetryCommand::creator,
PolySymmetryCommand::getSyntax
);
CHECK_MSTATUS_AND_RETURN_IT(status);
status = fnPlugin.registerNode(
PolySymmetryNode::NODE_NAME,
PolySymmetryNode::NODE_ID,
PolySymmetryNode::creator,
PolySymmetryNode::initialize,
MPxNode::kDependNode
);
CHECK_MSTATUS_AND_RETURN_IT(status);
REGISTER_COMMAND(PolyDeformerWeightsCommand);
REGISTER_COMMAND(PolyFlipCommand);
REGISTER_COMMAND(PolyMirrorCommand);
REGISTER_COMMAND(PolySkinWeightsCommand);
status = PolySymmetryCache::initialize();
CHECK_MSTATUS_AND_RETURN_IT(status);
if (MGlobal::mayaState() == MGlobal::kInteractive)
{
status = MGlobal::executePythonCommand("import polySymmetry");
if (status)
{
MGlobal::executePythonCommand("polySymmetry._initializePlugin()");
menuCreated = true;
} else {
MGlobal::displayWarning("polySymmetry module has not been installed - cannot create a tools menu.");
}
}
return MS::kSuccess;
}
MStatus uninitializePlugin(MObject obj)
{
MStatus status;
MFnPlugin fnPlugin(obj, kAUTHOR, kVERSION, kREQUIRED_API_VERSION);
status = PolySymmetryCache::uninitialize();
CHECK_MSTATUS_AND_RETURN_IT(status);
status = fnPlugin.deregisterContextCommand(
PolySymmetryContextCmd::COMMAND_NAME,
PolySymmetryCommand::COMMAND_NAME
);
CHECK_MSTATUS_AND_RETURN_IT(status);
DEREGISTER_COMMAND(PolyDeformerWeightsCommand);
DEREGISTER_COMMAND(PolyFlipCommand);
DEREGISTER_COMMAND(PolyMirrorCommand);
DEREGISTER_COMMAND(PolySkinWeightsCommand);
status = fnPlugin.deregisterNode(PolySymmetryNode::NODE_ID);
CHECK_MSTATUS_AND_RETURN_IT(status);
if (MGlobal::mayaState() == MGlobal::kInteractive && menuCreated)
{
status = MGlobal::executePythonCommand("import polySymmetry");
if (status)
{
MGlobal::executePythonCommand("polySymmetry._uninitializePlugin()");
}
}
return MS::kSuccess;
}<commit_msg>Change plugin version to 0.4.0<commit_after>/**
Copyright (c) 2017 Ryan Porter
*/
#include "polyDeformerWeights.h"
#include "polyFlipCmd.h"
#include "polyMirrorCmd.h"
#include "polySkinWeights.h"
#include "polySymmetryTool.h"
#include "polySymmetryCmd.h"
#include "polySymmetryNode.h"
#include "sceneCache.h"
#include <maya/MFnPlugin.h>
#include <maya/MGlobal.h>
#include <maya/MTypeId.h>
#include <maya/MString.h>
#include <maya/MStatus.h>
const char* kAUTHOR = "Ryan Porter";
const char* kVERSION = "0.4.0";
const char* kREQUIRED_API_VERSION = "Any";
MString PolyDeformerWeightsCommand::COMMAND_NAME = "polyDeformerWeights";
MString PolyFlipCommand::COMMAND_NAME = "polyFlip";
MString PolyMirrorCommand::COMMAND_NAME = "polyMirror";
MString PolySkinWeightsCommand::COMMAND_NAME = "polySkinWeights";
MString PolySymmetryContextCmd::COMMAND_NAME = "polySymmetryCtx";
MString PolySymmetryCommand::COMMAND_NAME = "polySymmetry";
MString PolySymmetryNode::NODE_NAME = "polySymmetryData";
MTypeId PolySymmetryNode::NODE_ID = 0x00126b0d;
#define REGISTER_COMMAND(CMD) CHECK_MSTATUS_AND_RETURN_IT(fnPlugin.registerCommand(CMD::COMMAND_NAME, CMD::creator, CMD::getSyntax));
#define DEREGISTER_COMMAND(CMD) CHECK_MSTATUS_AND_RETURN_IT(fnPlugin.deregisterCommand(CMD::COMMAND_NAME))
bool menuCreated = false;
MStatus initializePlugin(MObject obj)
{
MStatus status;
MFnPlugin fnPlugin(obj, kAUTHOR, kVERSION, kREQUIRED_API_VERSION);
status = fnPlugin.registerContextCommand(
PolySymmetryContextCmd::COMMAND_NAME,
PolySymmetryContextCmd::creator,
PolySymmetryCommand::COMMAND_NAME,
PolySymmetryCommand::creator,
PolySymmetryCommand::getSyntax
);
CHECK_MSTATUS_AND_RETURN_IT(status);
status = fnPlugin.registerNode(
PolySymmetryNode::NODE_NAME,
PolySymmetryNode::NODE_ID,
PolySymmetryNode::creator,
PolySymmetryNode::initialize,
MPxNode::kDependNode
);
CHECK_MSTATUS_AND_RETURN_IT(status);
REGISTER_COMMAND(PolyDeformerWeightsCommand);
REGISTER_COMMAND(PolyFlipCommand);
REGISTER_COMMAND(PolyMirrorCommand);
REGISTER_COMMAND(PolySkinWeightsCommand);
status = PolySymmetryCache::initialize();
CHECK_MSTATUS_AND_RETURN_IT(status);
if (MGlobal::mayaState() == MGlobal::kInteractive)
{
status = MGlobal::executePythonCommand("import polySymmetry");
if (status)
{
MGlobal::executePythonCommand("polySymmetry._initializePlugin()");
menuCreated = true;
} else {
MGlobal::displayWarning("polySymmetry module has not been installed - cannot create a tools menu.");
}
}
return MS::kSuccess;
}
MStatus uninitializePlugin(MObject obj)
{
MStatus status;
MFnPlugin fnPlugin(obj, kAUTHOR, kVERSION, kREQUIRED_API_VERSION);
status = PolySymmetryCache::uninitialize();
CHECK_MSTATUS_AND_RETURN_IT(status);
status = fnPlugin.deregisterContextCommand(
PolySymmetryContextCmd::COMMAND_NAME,
PolySymmetryCommand::COMMAND_NAME
);
CHECK_MSTATUS_AND_RETURN_IT(status);
DEREGISTER_COMMAND(PolyDeformerWeightsCommand);
DEREGISTER_COMMAND(PolyFlipCommand);
DEREGISTER_COMMAND(PolyMirrorCommand);
DEREGISTER_COMMAND(PolySkinWeightsCommand);
status = fnPlugin.deregisterNode(PolySymmetryNode::NODE_ID);
CHECK_MSTATUS_AND_RETURN_IT(status);
if (MGlobal::mayaState() == MGlobal::kInteractive && menuCreated)
{
status = MGlobal::executePythonCommand("import polySymmetry");
if (status)
{
MGlobal::executePythonCommand("polySymmetry._uninitializePlugin()");
}
}
return MS::kSuccess;
}<|endoftext|> |
<commit_before>///
/// @file primecount.cpp
/// @brief primecount C++ API
///
/// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount-internal.hpp>
#include <primecount.hpp>
#include <calculator.hpp>
#include <int128.hpp>
#include <pmath.hpp>
#include <algorithm>
#include <ctime>
#include <cmath>
#include <limits>
#include <sstream>
#include <string>
#include <stdint.h>
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
namespace {
int threads_ = primecount::MAX_THREADS;
int status_precision_ = -1;
double alpha_ = -1;
}
namespace primecount {
int64_t pi(int64_t x)
{
return pi(x, threads_);
}
int64_t pi(int64_t x, int threads)
{
return pi_deleglise_rivat(x, threads);
}
#ifdef HAVE_INT128_T
int128_t pi(int128_t x)
{
return pi(x, threads_);
}
int128_t pi(int128_t x, int threads)
{
return pi_deleglise_rivat(x, threads);
}
#endif
/// Alias for the fastest prime counting function in primecount.
/// @param x integer or arithmetic expression like "10^12".
/// @pre x <= get_max_x().
///
string pi(const string& x)
{
return pi(x, threads_);
}
/// Alias for the fastest prime counting function in primecount.
/// @param x integer or arithmetic expression like "10^12".
/// @pre x <= get_max_x().
///
string pi(const string& x, int threads)
{
maxint_t n = to_maxint(x);
maxint_t pin = pi(n, threads);
ostringstream oss;
oss << pin;
return oss.str();
}
/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
///
int64_t pi_deleglise_rivat(int64_t x)
{
return pi_deleglise_rivat(x, threads_);
}
/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
///
int64_t pi_deleglise_rivat(int64_t x, int threads)
{
return pi_deleglise_rivat_parallel2(x, threads);
}
#ifdef HAVE_INT128_T
/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
///
int128_t pi_deleglise_rivat(int128_t x)
{
return pi_deleglise_rivat(x, threads_);
}
/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
///
int128_t pi_deleglise_rivat(int128_t x, int threads)
{
// use 64-bit if possible
if (x <= numeric_limits<int64_t>::max())
return pi_deleglise_rivat((int64_t) x, threads);
return pi_deleglise_rivat_parallel3(x, threads);
}
#endif
/// Calculate the number of primes below x using Legendre's formula.
/// Run time: O(x) operations, O(x^(1/2)) space.
///
int64_t pi_legendre(int64_t x)
{
return pi_legendre(x, threads_);
}
/// Calculate the number of primes below x using Lehmer's formula.
/// Run time: O(x/(log x)^4) operations, O(x^(1/2)) space.
///
int64_t pi_lehmer(int64_t x)
{
return pi_lehmer(x, threads_);
}
/// Calculate the number of primes below x using the
/// Lagarias-Miller-Odlyzko algorithm.
/// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space.
///
int64_t pi_lmo(int64_t x)
{
return pi_lmo(x, threads_);
}
/// Parallel implementation of the Lagarias-Miller-Odlyzko
/// prime counting algorithm using OpenMP.
/// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space.
///
int64_t pi_lmo(int64_t x, int threads)
{
if (threads <= 1)
return pi_lmo5(x);
return pi_lmo_parallel3(x, threads);
}
/// Calculate the number of primes below x using Meissel's formula.
/// Run time: O(x/(log x)^3) operations, O(x^(1/2) / log x) space.
///
int64_t pi_meissel(int64_t x)
{
return pi_meissel(x, threads_);
}
/// Calculate the number of primes below x using an optimized
/// segmented sieve of Eratosthenes implementation.
/// Run time: O(x log log x) operations, O(x^(1/2)) space.
///
int64_t pi_primesieve(int64_t x)
{
return pi_primesieve(x, threads_);
}
/// Calculate the nth prime using a combination of an efficient prime
/// counting function implementation and the sieve of Eratosthenes.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/2)) space.
///
int64_t nth_prime(int64_t n)
{
return nth_prime(n, threads_);
}
/// Partial sieve function (a.k.a. Legendre-sum).
/// phi(x, a) counts the numbers <= x that are not divisible
/// by any of the first a primes.
///
int64_t phi(int64_t x, int64_t a)
{
return phi(x, a, threads_);
}
/// Returns the largest integer that can be used with
/// pi(string x). The return type is a string as max may be a
/// 128-bit integer which is not supported by all compilers.
///
string get_max_x(double alpha)
{
ostringstream oss;
#ifdef HAVE_INT128_T
// primecount is limited by:
// z < 2^62, with z = x^(2/3) / alpha
// x^(2/3) / alpha < 2^62
// x < (2^62 * alpha)^(3/2)
// safety buffer: use 61 instead of 62
double max_x = pow(pow(2.0, 61.0) * alpha, 3.0 / 2.0);
oss << (int128_t) max_x;
#else
unused_param(alpha);
oss << numeric_limits<int64_t>::max();
#endif
return oss.str();
}
/// Get the wall time in seconds.
double get_wtime()
{
#ifdef _OPENMP
return omp_get_wtime();
#else
return static_cast<double>(std::clock()) / CLOCKS_PER_SEC;
#endif
}
int validate_threads(int threads)
{
#ifdef _OPENMP
if (threads == MAX_THREADS)
threads = omp_get_max_threads();
return in_between(1, threads, omp_get_max_threads());
#else
threads = 1;
return threads;
#endif
}
int validate_threads(int threads, int64_t sieve_limit, int64_t thread_threshold)
{
threads = validate_threads(threads);
thread_threshold = max((int64_t) 1, thread_threshold);
threads = (int) min((int64_t) threads, sieve_limit / thread_threshold);
threads = max(1, threads);
return threads;
}
void set_alpha(double alpha)
{
alpha_ = alpha;
}
double get_alpha()
{
return alpha_;
}
double get_alpha(maxint_t x, int64_t y)
{
// y = x13 * alpha, thus alpha = y / x13
double x13 = (double) iroot<3>(x);
return (double) y / x13;
}
/// Calculate the Lagarias-Miller-Odlyzko alpha tuning factor.
/// alpha = a log(x)^2 + b log(x) + c
/// a, b and c are constants that should be determined empirically.
/// @see ../doc/alpha-factor-tuning.pdf
///
double get_alpha_lmo(maxint_t x)
{
double alpha = get_alpha();
// use default alpha if no command-line alpha provided
if (alpha < 1)
{
double a = 0.00156512;
double b = -0.0261411;
double c = 0.990948;
double logx = log((double) x);
alpha = a * pow(logx, 2) + b * logx + c;
}
return in_between(1, alpha, iroot<6>(x));
}
/// Calculate the Deleglise-Rivat alpha tuning factor.
/// alpha = a log(x)^3 + b log(x)^2 + c log(x) + d
/// a, b, c and d are constants that should be determined empirically.
/// @see ../doc/alpha-tuning-factor.pdf
///
double get_alpha_deleglise_rivat(maxint_t x)
{
double alpha = get_alpha();
double x2 = (double) x;
// use default alpha if no command-line alpha provided
if (alpha < 1)
{
if (x2 <= 1e21)
{
double a = 0.000711339;
double b = -0.0160586;
double c = 0.123034;
double d = 0.802942;
double logx = log(x2);
alpha = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d;
}
else
{
// Because of CPU cache misses sieving (S2_hard(x) and P2(x))
// becomes the main bottleneck above 10^21 . Hence we use a
// different alpha formula when x > 10^21 which returns a larger
// alpha which reduces sieving but increases S2_easy(x) work.
double a = 0.00149066;
double b = -0.0375705;
double c = 0.282139;
double d = 0.591972;
double logx = log(x2);
alpha = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d;
}
}
return in_between(1, alpha, iroot<6>(x));
}
void set_num_threads(int threads)
{
threads_ = validate_threads(threads);
}
int get_num_threads()
{
return validate_threads(threads_);
}
void set_status_precision(int precision)
{
status_precision_ = in_between(0, precision, 5);
}
int get_status_precision(maxint_t x)
{
// use default precision when no command-line precision provided
if (status_precision_ < 0)
{
if ((double) x >= 1e23)
return 2;
if ((double) x >= 1e21)
return 1;
}
return (status_precision_ > 0) ? status_precision_ : 0;
}
maxint_t to_maxint(const string& expr)
{
maxint_t n = calculator::eval<maxint_t>(expr);
return n;
}
} // namespace primecount
<commit_msg>Use pi_lmo(x) instead of pi_deleglise_rivat(x) for x < 10^7<commit_after>///
/// @file primecount.cpp
/// @brief primecount C++ API
///
/// Copyright (C) 2015 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///
#include <primecount-internal.hpp>
#include <primecount.hpp>
#include <calculator.hpp>
#include <int128.hpp>
#include <pmath.hpp>
#include <algorithm>
#include <ctime>
#include <cmath>
#include <limits>
#include <sstream>
#include <string>
#include <stdint.h>
#ifdef _OPENMP
#include <omp.h>
#endif
using namespace std;
namespace {
int threads_ = primecount::MAX_THREADS;
int status_precision_ = -1;
double alpha_ = -1;
// Below 10^7 the Deleglise-Rivat algorithm is slower than LMO
const int deleglise_rivat_threshold = 10000000;
}
namespace primecount {
int64_t pi(int64_t x)
{
return pi(x, threads_);
}
int64_t pi(int64_t x, int threads)
{
if (x < deleglise_rivat_threshold)
return pi_lmo(x, threads);
else
return pi_deleglise_rivat(x, threads);
}
#ifdef HAVE_INT128_T
int128_t pi(int128_t x)
{
return pi(x, threads_);
}
int128_t pi(int128_t x, int threads)
{
// use 64-bit if possible
if (x <= numeric_limits<int64_t>::max())
return pi((int64_t) x, threads);
return pi_deleglise_rivat(x, threads);
}
#endif
/// Alias for the fastest prime counting function in primecount.
/// @param x integer or arithmetic expression like "10^12".
/// @pre x <= get_max_x().
///
string pi(const string& x)
{
return pi(x, threads_);
}
/// Alias for the fastest prime counting function in primecount.
/// @param x integer or arithmetic expression like "10^12".
/// @pre x <= get_max_x().
///
string pi(const string& x, int threads)
{
maxint_t pi_x = pi(to_maxint(x), threads);
ostringstream oss;
oss << pi_x;
return oss.str();
}
/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
///
int64_t pi_deleglise_rivat(int64_t x)
{
return pi_deleglise_rivat(x, threads_);
}
/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
///
int64_t pi_deleglise_rivat(int64_t x, int threads)
{
return pi_deleglise_rivat_parallel2(x, threads);
}
#ifdef HAVE_INT128_T
/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
///
int128_t pi_deleglise_rivat(int128_t x)
{
return pi_deleglise_rivat(x, threads_);
}
/// Calculate the number of primes below x using the
/// Deleglise-Rivat algorithm.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/3) * (log x)^3) space.
///
int128_t pi_deleglise_rivat(int128_t x, int threads)
{
// use 64-bit if possible
if (x <= numeric_limits<int64_t>::max())
return pi_deleglise_rivat((int64_t) x, threads);
return pi_deleglise_rivat_parallel3(x, threads);
}
#endif
/// Calculate the number of primes below x using Legendre's formula.
/// Run time: O(x) operations, O(x^(1/2)) space.
///
int64_t pi_legendre(int64_t x)
{
return pi_legendre(x, threads_);
}
/// Calculate the number of primes below x using Lehmer's formula.
/// Run time: O(x/(log x)^4) operations, O(x^(1/2)) space.
///
int64_t pi_lehmer(int64_t x)
{
return pi_lehmer(x, threads_);
}
/// Calculate the number of primes below x using the
/// Lagarias-Miller-Odlyzko algorithm.
/// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space.
///
int64_t pi_lmo(int64_t x)
{
return pi_lmo(x, threads_);
}
/// Parallel implementation of the Lagarias-Miller-Odlyzko
/// prime counting algorithm using OpenMP.
/// Run time: O(x^(2/3) / log x) operations, O(x^(1/3) * (log x)^2) space.
///
int64_t pi_lmo(int64_t x, int threads)
{
if (threads <= 1)
return pi_lmo5(x);
return pi_lmo_parallel3(x, threads);
}
/// Calculate the number of primes below x using Meissel's formula.
/// Run time: O(x/(log x)^3) operations, O(x^(1/2) / log x) space.
///
int64_t pi_meissel(int64_t x)
{
return pi_meissel(x, threads_);
}
/// Calculate the number of primes below x using an optimized
/// segmented sieve of Eratosthenes implementation.
/// Run time: O(x log log x) operations, O(x^(1/2)) space.
///
int64_t pi_primesieve(int64_t x)
{
return pi_primesieve(x, threads_);
}
/// Calculate the nth prime using a combination of an efficient prime
/// counting function implementation and the sieve of Eratosthenes.
/// Run time: O(x^(2/3) / (log x)^2) operations, O(x^(1/2)) space.
///
int64_t nth_prime(int64_t n)
{
return nth_prime(n, threads_);
}
/// Partial sieve function (a.k.a. Legendre-sum).
/// phi(x, a) counts the numbers <= x that are not divisible
/// by any of the first a primes.
///
int64_t phi(int64_t x, int64_t a)
{
return phi(x, a, threads_);
}
/// Returns the largest integer that can be used with
/// pi(string x). The return type is a string as max may be a
/// 128-bit integer which is not supported by all compilers.
///
string get_max_x(double alpha)
{
ostringstream oss;
#ifdef HAVE_INT128_T
// primecount is limited by:
// z < 2^62, with z = x^(2/3) / alpha
// x^(2/3) / alpha < 2^62
// x < (2^62 * alpha)^(3/2)
// safety buffer: use 61 instead of 62
double max_x = pow(pow(2.0, 61.0) * alpha, 3.0 / 2.0);
oss << (int128_t) max_x;
#else
unused_param(alpha);
oss << numeric_limits<int64_t>::max();
#endif
return oss.str();
}
/// Get the wall time in seconds.
double get_wtime()
{
#ifdef _OPENMP
return omp_get_wtime();
#else
return static_cast<double>(std::clock()) / CLOCKS_PER_SEC;
#endif
}
int validate_threads(int threads)
{
#ifdef _OPENMP
if (threads == MAX_THREADS)
threads = omp_get_max_threads();
return in_between(1, threads, omp_get_max_threads());
#else
threads = 1;
return threads;
#endif
}
int validate_threads(int threads, int64_t sieve_limit, int64_t thread_threshold)
{
threads = validate_threads(threads);
thread_threshold = max((int64_t) 1, thread_threshold);
threads = (int) min((int64_t) threads, sieve_limit / thread_threshold);
threads = max(1, threads);
return threads;
}
void set_alpha(double alpha)
{
alpha_ = alpha;
}
double get_alpha()
{
return alpha_;
}
double get_alpha(maxint_t x, int64_t y)
{
// y = x13 * alpha, thus alpha = y / x13
double x13 = (double) iroot<3>(x);
return (double) y / x13;
}
/// Calculate the Lagarias-Miller-Odlyzko alpha tuning factor.
/// alpha = a log(x)^2 + b log(x) + c
/// a, b and c are constants that should be determined empirically.
/// @see ../doc/alpha-factor-tuning.pdf
///
double get_alpha_lmo(maxint_t x)
{
double alpha = get_alpha();
// use default alpha if no command-line alpha provided
if (alpha < 1)
{
double a = 0.00156512;
double b = -0.0261411;
double c = 0.990948;
double logx = log((double) x);
alpha = a * pow(logx, 2) + b * logx + c;
}
return in_between(1, alpha, iroot<6>(x));
}
/// Calculate the Deleglise-Rivat alpha tuning factor.
/// alpha = a log(x)^3 + b log(x)^2 + c log(x) + d
/// a, b, c and d are constants that should be determined empirically.
/// @see ../doc/alpha-tuning-factor.pdf
///
double get_alpha_deleglise_rivat(maxint_t x)
{
double alpha = get_alpha();
double x2 = (double) x;
// use default alpha if no command-line alpha provided
if (alpha < 1)
{
if (x2 <= 1e21)
{
double a = 0.000711339;
double b = -0.0160586;
double c = 0.123034;
double d = 0.802942;
double logx = log(x2);
alpha = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d;
}
else
{
// Because of CPU cache misses sieving (S2_hard(x) and P2(x))
// becomes the main bottleneck above 10^21 . Hence we use a
// different alpha formula when x > 10^21 which returns a larger
// alpha which reduces sieving but increases S2_easy(x) work.
double a = 0.00149066;
double b = -0.0375705;
double c = 0.282139;
double d = 0.591972;
double logx = log(x2);
alpha = a * pow(logx, 3) + b * pow(logx, 2) + c * logx + d;
}
}
return in_between(1, alpha, iroot<6>(x));
}
void set_num_threads(int threads)
{
threads_ = validate_threads(threads);
}
int get_num_threads()
{
return validate_threads(threads_);
}
void set_status_precision(int precision)
{
status_precision_ = in_between(0, precision, 5);
}
int get_status_precision(maxint_t x)
{
// use default precision when no command-line precision provided
if (status_precision_ < 0)
{
if ((double) x >= 1e23)
return 2;
if ((double) x >= 1e21)
return 1;
}
return (status_precision_ > 0) ? status_precision_ : 0;
}
maxint_t to_maxint(const string& expr)
{
maxint_t n = calculator::eval<maxint_t>(expr);
return n;
}
} // namespace primecount
<|endoftext|> |
<commit_before>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "common/platform_util.h"
#include <windows.h>
#include <commdlg.h>
#include <dwmapi.h>
#include <shellapi.h>
#include <shlobj.h>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/win/registry.h"
#include "base/win/scoped_co_mem.h"
#include "base/win/scoped_comptr.h"
#include "base/win/windows_version.h"
#include "googleurl/src/gurl.h"
#include "ui/base/win/shell.h"
namespace {
// Old ShellExecute crashes the process when the command for a given scheme
// is empty. This function tells if it is.
bool ValidateShellCommandForScheme(const std::string& scheme) {
base::win::RegKey key;
std::wstring registry_path = ASCIIToWide(scheme) +
L"\\shell\\open\\command";
key.Open(HKEY_CLASSES_ROOT, registry_path.c_str(), KEY_READ);
if (!key.Valid())
return false;
DWORD size = 0;
key.ReadValue(NULL, NULL, &size, NULL);
if (size <= 2)
return false;
return true;
}
} // namespace
namespace platform_util {
void ShowItemInFolder(const base::FilePath& full_path) {
base::FilePath dir = full_path.DirName().AsEndingWithSeparator();
// ParseDisplayName will fail if the directory is "C:", it must be "C:\\".
if (dir.empty())
return;
typedef HRESULT (WINAPI *SHOpenFolderAndSelectItemsFuncPtr)(
PCIDLIST_ABSOLUTE pidl_Folder,
UINT cidl,
PCUITEMID_CHILD_ARRAY pidls,
DWORD flags);
static SHOpenFolderAndSelectItemsFuncPtr open_folder_and_select_itemsPtr =
NULL;
static bool initialize_open_folder_proc = true;
if (initialize_open_folder_proc) {
initialize_open_folder_proc = false;
// The SHOpenFolderAndSelectItems API is exposed by shell32 version 6
// and does not exist in Win2K. We attempt to retrieve this function export
// from shell32 and if it does not exist, we just invoke ShellExecute to
// open the folder thus losing the functionality to select the item in
// the process.
HMODULE shell32_base = GetModuleHandle(L"shell32.dll");
if (!shell32_base) {
NOTREACHED() << " " << __FUNCTION__ << "(): Can't open shell32.dll";
return;
}
open_folder_and_select_itemsPtr =
reinterpret_cast<SHOpenFolderAndSelectItemsFuncPtr>
(GetProcAddress(shell32_base, "SHOpenFolderAndSelectItems"));
}
if (!open_folder_and_select_itemsPtr) {
ShellExecute(NULL, L"open", dir.value().c_str(), NULL, NULL, SW_SHOW);
return;
}
base::win::ScopedComPtr<IShellFolder> desktop;
HRESULT hr = SHGetDesktopFolder(desktop.Receive());
if (FAILED(hr))
return;
base::win::ScopedCoMem<ITEMIDLIST> dir_item;
hr = desktop->ParseDisplayName(NULL, NULL,
const_cast<wchar_t *>(dir.value().c_str()),
NULL, &dir_item, NULL);
if (FAILED(hr))
return;
base::win::ScopedCoMem<ITEMIDLIST> file_item;
hr = desktop->ParseDisplayName(NULL, NULL,
const_cast<wchar_t *>(full_path.value().c_str()),
NULL, &file_item, NULL);
if (FAILED(hr))
return;
const ITEMIDLIST* highlight[] = { file_item };
hr = (*open_folder_and_select_itemsPtr)(dir_item, arraysize(highlight),
highlight, NULL);
if (FAILED(hr)) {
// On some systems, the above call mysteriously fails with "file not
// found" even though the file is there. In these cases, ShellExecute()
// seems to work as a fallback (although it won't select the file).
if (hr == ERROR_FILE_NOT_FOUND) {
ShellExecute(NULL, L"open", dir.value().c_str(), NULL, NULL, SW_SHOW);
} else {
LPTSTR message = NULL;
DWORD message_length = FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
0, hr, 0, reinterpret_cast<LPTSTR>(&message), 0, NULL);
LOG(WARNING) << " " << __FUNCTION__
<< "(): Can't open full_path = \""
<< full_path.value() << "\""
<< " hr = " << hr
<< " " << reinterpret_cast<LPTSTR>(&message);
if (message)
LocalFree(message);
}
}
}
void OpenItem(const base::FilePath& full_path) {
ui::win::OpenItemViaShell(full_path);
}
void OpenExternal(const GURL& url) {
// Quote the input scheme to be sure that the command does not have
// parameters unexpected by the external program. This url should already
// have been escaped.
std::string escaped_url = url.spec();
escaped_url.insert(0, "\"");
escaped_url += "\"";
// According to Mozilla in uriloader/exthandler/win/nsOSHelperAppService.cpp:
// "Some versions of windows (Win2k before SP3, Win XP before SP1) crash in
// ShellExecute on long URLs (bug 161357 on bugzilla.mozilla.org). IE 5 and 6
// support URLS of 2083 chars in length, 2K is safe."
const size_t kMaxUrlLength = 2048;
if (escaped_url.length() > kMaxUrlLength) {
NOTREACHED();
return;
}
if (base::win::GetVersion() < base::win::VERSION_WIN7) {
if (!ValidateShellCommandForScheme(url.scheme()))
return;
}
if (reinterpret_cast<ULONG_PTR>(ShellExecuteA(NULL, "open",
escaped_url.c_str(), NULL, NULL,
SW_SHOWNORMAL)) <= 32) {
// We fail to execute the call. We could display a message to the user.
// TODO(nsylvain): we should also add a dialog to warn on errors. See
// bug 1136923.
return;
}
}
void MoveItemToTrash(const base::FilePath& path) {
// SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
// so we have to use wcscpy because wcscpy_s writes non-NULLs
// into the rest of the buffer.
wchar_t double_terminated_path[MAX_PATH + 1] = {0};
#pragma warning(suppress:4996) // don't complain about wcscpy deprecation
wcscpy(double_terminated_path, path.value().c_str());
SHFILEOPSTRUCT file_operation = {0};
file_operation.wFunc = FO_DELETE;
file_operation.pFrom = double_terminated_path;
file_operation.fFlags = FOF_ALLOWUNDO;
SHFileOperation(&file_operation);
}
void Beep() {
}
} // namespace platform_util
<commit_msg>Implement simple Beep() on Windows.<commit_after>// Copyright (c) 2013 GitHub, Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "common/platform_util.h"
#include <windows.h>
#include <commdlg.h>
#include <dwmapi.h>
#include <shellapi.h>
#include <shlobj.h>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/files/file_path.h"
#include "base/logging.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "base/win/registry.h"
#include "base/win/scoped_co_mem.h"
#include "base/win/scoped_comptr.h"
#include "base/win/windows_version.h"
#include "googleurl/src/gurl.h"
#include "ui/base/win/shell.h"
namespace {
// Old ShellExecute crashes the process when the command for a given scheme
// is empty. This function tells if it is.
bool ValidateShellCommandForScheme(const std::string& scheme) {
base::win::RegKey key;
std::wstring registry_path = ASCIIToWide(scheme) +
L"\\shell\\open\\command";
key.Open(HKEY_CLASSES_ROOT, registry_path.c_str(), KEY_READ);
if (!key.Valid())
return false;
DWORD size = 0;
key.ReadValue(NULL, NULL, &size, NULL);
if (size <= 2)
return false;
return true;
}
} // namespace
namespace platform_util {
void ShowItemInFolder(const base::FilePath& full_path) {
base::FilePath dir = full_path.DirName().AsEndingWithSeparator();
// ParseDisplayName will fail if the directory is "C:", it must be "C:\\".
if (dir.empty())
return;
typedef HRESULT (WINAPI *SHOpenFolderAndSelectItemsFuncPtr)(
PCIDLIST_ABSOLUTE pidl_Folder,
UINT cidl,
PCUITEMID_CHILD_ARRAY pidls,
DWORD flags);
static SHOpenFolderAndSelectItemsFuncPtr open_folder_and_select_itemsPtr =
NULL;
static bool initialize_open_folder_proc = true;
if (initialize_open_folder_proc) {
initialize_open_folder_proc = false;
// The SHOpenFolderAndSelectItems API is exposed by shell32 version 6
// and does not exist in Win2K. We attempt to retrieve this function export
// from shell32 and if it does not exist, we just invoke ShellExecute to
// open the folder thus losing the functionality to select the item in
// the process.
HMODULE shell32_base = GetModuleHandle(L"shell32.dll");
if (!shell32_base) {
NOTREACHED() << " " << __FUNCTION__ << "(): Can't open shell32.dll";
return;
}
open_folder_and_select_itemsPtr =
reinterpret_cast<SHOpenFolderAndSelectItemsFuncPtr>
(GetProcAddress(shell32_base, "SHOpenFolderAndSelectItems"));
}
if (!open_folder_and_select_itemsPtr) {
ShellExecute(NULL, L"open", dir.value().c_str(), NULL, NULL, SW_SHOW);
return;
}
base::win::ScopedComPtr<IShellFolder> desktop;
HRESULT hr = SHGetDesktopFolder(desktop.Receive());
if (FAILED(hr))
return;
base::win::ScopedCoMem<ITEMIDLIST> dir_item;
hr = desktop->ParseDisplayName(NULL, NULL,
const_cast<wchar_t *>(dir.value().c_str()),
NULL, &dir_item, NULL);
if (FAILED(hr))
return;
base::win::ScopedCoMem<ITEMIDLIST> file_item;
hr = desktop->ParseDisplayName(NULL, NULL,
const_cast<wchar_t *>(full_path.value().c_str()),
NULL, &file_item, NULL);
if (FAILED(hr))
return;
const ITEMIDLIST* highlight[] = { file_item };
hr = (*open_folder_and_select_itemsPtr)(dir_item, arraysize(highlight),
highlight, NULL);
if (FAILED(hr)) {
// On some systems, the above call mysteriously fails with "file not
// found" even though the file is there. In these cases, ShellExecute()
// seems to work as a fallback (although it won't select the file).
if (hr == ERROR_FILE_NOT_FOUND) {
ShellExecute(NULL, L"open", dir.value().c_str(), NULL, NULL, SW_SHOW);
} else {
LPTSTR message = NULL;
DWORD message_length = FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
0, hr, 0, reinterpret_cast<LPTSTR>(&message), 0, NULL);
LOG(WARNING) << " " << __FUNCTION__
<< "(): Can't open full_path = \""
<< full_path.value() << "\""
<< " hr = " << hr
<< " " << reinterpret_cast<LPTSTR>(&message);
if (message)
LocalFree(message);
}
}
}
void OpenItem(const base::FilePath& full_path) {
ui::win::OpenItemViaShell(full_path);
}
void OpenExternal(const GURL& url) {
// Quote the input scheme to be sure that the command does not have
// parameters unexpected by the external program. This url should already
// have been escaped.
std::string escaped_url = url.spec();
escaped_url.insert(0, "\"");
escaped_url += "\"";
// According to Mozilla in uriloader/exthandler/win/nsOSHelperAppService.cpp:
// "Some versions of windows (Win2k before SP3, Win XP before SP1) crash in
// ShellExecute on long URLs (bug 161357 on bugzilla.mozilla.org). IE 5 and 6
// support URLS of 2083 chars in length, 2K is safe."
const size_t kMaxUrlLength = 2048;
if (escaped_url.length() > kMaxUrlLength) {
NOTREACHED();
return;
}
if (base::win::GetVersion() < base::win::VERSION_WIN7) {
if (!ValidateShellCommandForScheme(url.scheme()))
return;
}
if (reinterpret_cast<ULONG_PTR>(ShellExecuteA(NULL, "open",
escaped_url.c_str(), NULL, NULL,
SW_SHOWNORMAL)) <= 32) {
// We fail to execute the call. We could display a message to the user.
// TODO(nsylvain): we should also add a dialog to warn on errors. See
// bug 1136923.
return;
}
}
void MoveItemToTrash(const base::FilePath& path) {
// SHFILEOPSTRUCT wants the path to be terminated with two NULLs,
// so we have to use wcscpy because wcscpy_s writes non-NULLs
// into the rest of the buffer.
wchar_t double_terminated_path[MAX_PATH + 1] = {0};
#pragma warning(suppress:4996) // don't complain about wcscpy deprecation
wcscpy(double_terminated_path, path.value().c_str());
SHFILEOPSTRUCT file_operation = {0};
file_operation.wFunc = FO_DELETE;
file_operation.pFrom = double_terminated_path;
file_operation.fFlags = FOF_ALLOWUNDO;
SHFileOperation(&file_operation);
}
void Beep() {
MessageBeep(MB_OK);
}
} // namespace platform_util
<|endoftext|> |
<commit_before>/*
Filename: JSUnsafe.cpp
Purpose: Native memory access and management for Javascript
Part of Engine2D
Copyright (C) 2014 Vbitz
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 "JSUnsafe.hpp"
#include "Util.hpp"
#include <stdlib.h>
#include <sys/mman.h>
namespace Engine {
namespace JsUnsafe {
ENGINE_JS_METHOD(GetNumberAddress) {
ENGINE_JS_SCOPE_OPEN;
int* numAddr = (int*) malloc(sizeof(int));
*numAddr = ENGINE_GET_ARG_INT32_VALUE(0);
// MEMORY LEAK: Kind of the point of this
ENGINE_JS_SCOPE_CLOSE(v8::Number::New(args.GetIsolate(), (long) numAddr));
}
ENGINE_JS_METHOD(GetNative) {
ENGINE_JS_SCOPE_OPEN;
long offset = (long) ENGINE_GET_ARG_NUMBER_VALUE(0);
int length = ENGINE_GET_ARG_INT32_VALUE(1);
v8::Handle<v8::Object> array = v8::Object::New(args.GetIsolate());
void* rawPointer = (void*) offset;
array->SetIndexedPropertiesToExternalArrayData(rawPointer, v8::kExternalUnsignedByteArray, length * sizeof(unsigned char));
ENGINE_JS_SCOPE_CLOSE(array);
}
typedef void* (*FARPROC)(void);
ENGINE_JS_METHOD(Call) {
ENGINE_JS_SCOPE_OPEN;
long address = (long) ENGINE_GET_ARG_NUMBER_VALUE(0);
FARPROC func = (FARPROC) address;
try {
func();
ENGINE_JS_SCOPE_CLOSE(v8::Boolean::New(args.GetIsolate(), true));
} catch (...) {
ENGINE_JS_SCOPE_CLOSE(v8::Boolean::New(args.GetIsolate(), false));
}
}
ENGINE_JS_METHOD(Malloc) {
ENGINE_JS_SCOPE_OPEN;
int arrayLength = ENGINE_GET_ARG_INT32_VALUE(0);
v8::Handle<v8::Object> array = v8::Object::New(args.GetIsolate());
char* rawArray = (char*) malloc(arrayLength);
array->SetIndexedPropertiesToExternalArrayData(rawArray, v8::kExternalByteArray, arrayLength * sizeof(char));
ENGINE_JS_SCOPE_CLOSE(array);
}
ENGINE_JS_METHOD(Free) {
ENGINE_JS_SCOPE_OPEN;
v8::Handle<v8::Array> arr = v8::Handle<v8::Array>(ENGINE_GET_ARG_ARRAY(0));
void* rawAddr = arr->GetIndexedPropertiesExternalArrayData();
free(rawAddr);
ENGINE_JS_SCOPE_CLOSE_UNDEFINED;
}
ENGINE_JS_METHOD(AddressOf) {
ENGINE_JS_SCOPE_OPEN;
v8::Handle<v8::Array> arr = v8::Handle<v8::Array>(ENGINE_GET_ARG_ARRAY(0));
void* rawAddr = arr->GetIndexedPropertiesExternalArrayData();
long address = (long) rawAddr;
ENGINE_JS_SCOPE_CLOSE(v8::Number::New(args.GetIsolate(), (double) address));
}
ENGINE_JS_METHOD(AddressOfExternal) {
ENGINE_JS_SCOPE_OPEN;
ENGINE_CHECK_ARGS_LENGTH(1);
ENGINE_CHECK_ARG_EXTERNAL(0, "Arg0 is the value to return the indexof");
long exAddr = (long) ENGINE_GET_ARG_EXTERNAL_VALUE(0);
ENGINE_JS_SCOPE_CLOSE(v8::Number::New(args.GetIsolate(), (double) exAddr));
}
ENGINE_JS_METHOD(MProtect) {
ENGINE_JS_SCOPE_OPEN;
long address = (long) ENGINE_GET_ARG_NUMBER_VALUE(0);
int length = ENGINE_GET_ARG_INT32_VALUE(1);
bool enable = ENGINE_GET_ARG_BOOLEAN_VALUE(2);
int res = -1;
if (enable) {
res = mprotect((void*) address, length, PROT_READ | PROT_EXEC);
} else {
res = mprotect((void*) address, length, PROT_READ | PROT_WRITE);
}
ENGINE_JS_SCOPE_CLOSE(v8::Boolean::New(args.GetIsolate(), res > -1));
}
ENGINE_JS_METHOD(GetPageSize) {
ENGINE_JS_SCOPE_OPEN;
ENGINE_JS_SCOPE_CLOSE(v8::Number::New(args.GetIsolate(), getpagesize()));
}
#define addItem(table, js_name, funct) table->Set(isolate, js_name, v8::FunctionTemplate::New(isolate, funct))
void InitUnsafe(v8::Handle<v8::ObjectTemplate> unsafeTable) {
v8::Isolate* isolate = v8::Isolate::GetCurrent();
addItem(unsafeTable, "getNumberAddress", GetNumberAddress);
addItem(unsafeTable, "getNative", GetNative);
addItem(unsafeTable, "call", Call);
addItem(unsafeTable, "malloc", Malloc);
addItem(unsafeTable, "free", Free);
addItem(unsafeTable, "addressOf", AddressOf);
addItem(unsafeTable, "addressOfExternal", AddressOfExternal);
addItem(unsafeTable, "mprotect", MProtect);
addItem(unsafeTable, "getPageSize", GetPageSize);
unsafeTable->Set(isolate, "pageSize", v8::Number::New(isolate, getpagesize()));
}
#undef addItem
}
}<commit_msg>Changed JSUnsafe to use gen3 script binding syntax<commit_after>/*
Filename: JSUnsafe.cpp
Purpose: Native memory access and management for Javascript
Part of Engine2D
Copyright (C) 2014 Vbitz
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 "JSUnsafe.hpp"
#include "ScriptingManager.hpp"
#include <stdlib.h>
#include <unistd.h>
#include <sys/mman.h>
namespace Engine {
namespace JsUnsafe {
void GetNumberAddress(const v8::FunctionCallbackInfo<v8::Value>& _args) {
ScriptingManager::Arguments args(_args);
int* numAddr = (int*) malloc(sizeof(int));
*numAddr = args.NumberValue(0);
// MEMORY LEAK: Kind of the point of this
args.SetReturnValue(args.NewNumber((long) numAddr));
}
void GetNative(const v8::FunctionCallbackInfo<v8::Value>& _args) {
ScriptingManager::Arguments args(_args);
long offset = (long) args.NumberValue(0);
int length = args.Int32Value(1);
v8::Handle<v8::Object> array = v8::Object::New(args.GetIsolate());
void* rawPointer = (void*) offset;
array->SetIndexedPropertiesToExternalArrayData(rawPointer, v8::kExternalUnsignedByteArray, length * sizeof(unsigned char));
args.SetReturnValue(array);
}
typedef void* (*FARPROC)(void);
void Call(const v8::FunctionCallbackInfo<v8::Value>& _args) {
ScriptingManager::Arguments args(_args);
long address = (long) args.NumberValue(0);
FARPROC func = (FARPROC) address;
try {
func();
args.SetReturnValue(args.NewBoolean(true));
} catch (...) {
args.SetReturnValue(args.NewBoolean(false));
}
}
void Malloc(const v8::FunctionCallbackInfo<v8::Value>& _args) {
ScriptingManager::Arguments args(_args);
int arrayLength = args.Int32Value(0);
v8::Handle<v8::Object> array = v8::Object::New(args.GetIsolate());
char* rawArray = (char*) malloc(arrayLength);
array->SetIndexedPropertiesToExternalArrayData(rawArray, v8::kExternalByteArray, arrayLength * sizeof(char));
args.SetReturnValue(array);
}
void Free(const v8::FunctionCallbackInfo<v8::Value>& _args) {
ScriptingManager::Arguments args(_args);
v8::Handle<v8::Array> arr = v8::Handle<v8::Array>::Cast(args[0]);
void* rawAddr = arr->GetIndexedPropertiesExternalArrayData();
free(rawAddr);
}
void AddressOf(const v8::FunctionCallbackInfo<v8::Value>& _args) {
ScriptingManager::Arguments args(_args);
v8::Handle<v8::Array> arr = v8::Handle<v8::Array>::Cast(args[0]);
void* rawAddr = arr->GetIndexedPropertiesExternalArrayData();
long address = (long) rawAddr;
args.SetReturnValue(args.NewNumber((double) address));
}
void AddressOfExternal(const v8::FunctionCallbackInfo<v8::Value>& _args) {
ScriptingManager::Arguments args(_args);
long exAddr = (long) args.ExternalValue(0);
args.SetReturnValue(args.NewNumber((double) exAddr));
}
void MProtect(const v8::FunctionCallbackInfo<v8::Value>& _args) {
ScriptingManager::Arguments args(_args);
long address = (long) args.NumberValue(0);
int length = args.Int32Value(1);
bool enable = args.BooleanValue(2);
int res = -1;
if (enable) {
res = mprotect((void*) address, length, PROT_READ | PROT_EXEC);
} else {
res = mprotect((void*) address, length, PROT_READ | PROT_WRITE);
}
args.SetReturnValue(args.NewBoolean(res > -1));
}
void GetPageSize(const v8::FunctionCallbackInfo<v8::Value>& _args) {
ScriptingManager::Arguments args(_args);
args.SetReturnValue(args.NewNumber(getpagesize()));
}
void InitUnsafe(v8::Handle<v8::ObjectTemplate> unsafeTable) {
ScriptingManager::Factory f(v8::Isolate::GetCurrent());
f.FillTemplate(unsafeTable, {
{FTT_Static, "getNumberAddress", f.NewFunctionTemplate(GetNumberAddress)},
{FTT_Static, "getNative", f.NewFunctionTemplate(GetNative)},
{FTT_Static, "call", f.NewFunctionTemplate(Call)},
{FTT_Static, "malloc", f.NewFunctionTemplate(Malloc)},
{FTT_Static, "free", f.NewFunctionTemplate(Free)},
{FTT_Static, "addressOf", f.NewFunctionTemplate(AddressOf)},
{FTT_Static, "addressOfExternal", f.NewFunctionTemplate(AddressOfExternal)},
{FTT_Static, "mprotect", f.NewFunctionTemplate(MProtect)},
{FTT_Static, "getPageSize", f.NewFunctionTemplate(GetPageSize)},
{FTT_Static, "pageSize", f.NewNumber(getpagesize())}
});
}
}
}<|endoftext|> |
<commit_before>// Copyright (C) 2019 Egor Pugin <egor.pugin@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <boost/algorithm/string.hpp>
#include <primitives/command.h>
#include <primitives/sw/main.h>
#include <primitives/sw/cl.h>
#include <primitives/sw/settings_program_name.h>
static cl::opt<path> git(cl::Positional, cl::Required);
static cl::opt<path> wdir(cl::Positional, cl::Required);
static cl::opt<path> outfn(cl::Positional, cl::Required);
int main(int argc, char *argv[])
{
cl::ParseCommandLineOptions(argc, argv);
String rev, status, time;
{
primitives::Command c;
c.working_directory = wdir;
c.arguments.push_back(git.u8string());
c.arguments.push_back("rev-parse");
c.arguments.push_back("HEAD");
error_code ec;
c.execute(ec);
if (ec)
{
rev = "unknown";
}
else
{
rev = boost::trim_copy(c.out.text);
}
}
{
primitives::Command c;
c.working_directory = wdir;
c.arguments.push_back(git.u8string());
c.arguments.push_back("status");
c.arguments.push_back("--porcelain");
c.arguments.push_back("-uno");
error_code ec;
c.execute(ec);
if (ec)
{
status = "0";
}
else
{
status = boost::trim_copy(c.out.text);
if (status.empty())
status = "0";
else
status = std::to_string(split_lines(status).size());
}
}
{
time = std::to_string(std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()));
}
String t;
t += "#define SW_GIT_REV \"" + rev + "\"\n";
t += "#define SW_GIT_CHANGED_FILES " + status + "\n";
t += "#define SW_BUILD_TIME_T " + time + "LL\n";
write_file(outfn, t);
return 0;
}
<commit_msg>Try to fix git rev issue on linux in CI.<commit_after>// Copyright (C) 2019 Egor Pugin <egor.pugin@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <boost/algorithm/string.hpp>
#include <primitives/command.h>
#include <primitives/sw/main.h>
#include <primitives/sw/cl.h>
#include <primitives/sw/settings_program_name.h>
static cl::opt<path> git(cl::Positional, cl::Required);
static cl::opt<path> wdir(cl::Positional, cl::Required);
static cl::opt<path> outfn(cl::Positional, cl::Required);
int main(int argc, char *argv[]) {
cl::ParseCommandLineOptions(argc, argv);
String rev, status, time;
{
primitives::Command c;
c.working_directory = wdir;
c.arguments.push_back(git.u8string());
c.arguments.push_back("rev-parse");
c.arguments.push_back("HEAD");
try {
error_code ec;
c.execute(ec);
if (ec) {
rev = "unknown";
} else {
rev = boost::trim_copy(c.out.text);
}
} catch (std::exception &) {
rev = "unknown";
}
}
{
primitives::Command c;
c.working_directory = wdir;
c.arguments.push_back(git.u8string());
c.arguments.push_back("status");
c.arguments.push_back("--porcelain");
c.arguments.push_back("-uno");
error_code ec;
c.execute(ec);
if (ec)
{
status = "0";
}
else
{
status = boost::trim_copy(c.out.text);
if (status.empty())
status = "0";
else
status = std::to_string(split_lines(status).size());
}
}
{
time = std::to_string(std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()));
}
String t;
t += "#define SW_GIT_REV \"" + rev + "\"\n";
t += "#define SW_GIT_CHANGED_FILES " + status + "\n";
t += "#define SW_BUILD_TIME_T " + time + "LL\n";
write_file(outfn, t);
return 0;
}
<|endoftext|> |
<commit_before>//! Copyright (c) 2013 ASMlover. 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 ofconditions 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 materialsprovided with the
//! distribution.
//!
//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//! "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//! COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//! INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//! BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//! ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//! POSSIBILITY OF SUCH DAMAGE.
#include <stdio.h>
int
main(int argc, char* argv[])
{
return 0;
}
<commit_msg>add demo for select server framework<commit_after>//! Copyright (c) 2013 ASMlover. 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 ofconditions 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 materialsprovided with the
//! distribution.
//!
//! THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
//! "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
//! LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
//! FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
//! COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//! INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
//! BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
//! LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
//! CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
//! LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
//! ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
//! POSSIBILITY OF SUCH DAMAGE.
#ifndef _WINDOWS_
# include <winsock2.h>
#endif
#include <stdio.h>
#include "net.h"
class ConnectorHandler : public EventHandler {
public:
virtual bool AcceptEvent(int fd, sockaddr* addr)
{
fprintf(stdout, "accept client from <%s> [%d]\n", addr->sa_data, fd);
return true;
}
virtual void CloseEvent(int fd)
{
fprintf(stdout, "client[%d] closeed\n", fd);
}
virtual bool ReadEvent(Socket* s)
{
char buf[128] = {0};
if (kNetTypeError == s->Read(sizeof(buf), buf)) {
s->Close();
return false;
}
fprintf(stdout, "recv from client: %s\n", buf);
s->Write(buf, strlen(buf));
return true;
}
};
static void
ServerMain(const char* ip = "127.0.0.1", unsigned short port = 5555)
{
ConnectorHandler ch;
SelectNetwork network;
network.Attach(&ch);
network.Init();
network.Listen(ip, port);
fprintf(stdout, "server <%s, %d> starting ...\n", ip, port);
while (true)
Sleep(100);
network.Destroy();
}
static void
ClientMain(const char* ip = "127.0.0.1", unsigned short port = 5555)
{
Socket s;
s.Open();
if (s.Connect(ip, port)) {
fprintf(stdout, "connect to server success ...\n");
}
else {
fprintf(stderr, "connect to server failed ...\n");
return;
}
SYSTEMTIME t;
char buf[128];
while (true) {
GetLocalTime(&t);
sprintf(buf, "[%04d-%02d-%02d %02d:%02d:%02d:%03d]",
t.wYear, t.wMonth, t.wDay,
t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);
if (kNetTypeError == s.Write(buf, strlen(buf)))
break;
memset(buf, 0, sizeof(buf));
if (kNetTypeError == s.Read(sizeof(buf), buf))
break;
fprintf(stdout, "recv from server: %s\n", buf);
Sleep(100);
}
s.Close();
}
int
main(int argc, char* argv[])
{
if (argc < 2)
return 0;
NetLibrary::Singleton().Init();
if (0 == strcmp("srv", argv[1]))
ServerMain();
else if (0 == strcmp("clt", argv[1]))
ClientMain();
NetLibrary::Singleton().Destroy();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2010 Rony Shapiro <ronys@users.sourceforge.net>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
/** \file PWSTreeCtrl.cpp
*
*/
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
////@begin includes
#include "wx/imaglist.h"
////@end includes
#include <utility> // for make_pair
#include <vector>
#include "PWStree.h"
#include "passwordsafeframe.h" // for DispatchDblClickAction()
#include "corelib/PWSprefs.h"
////@begin XPM images
////@end XPM images
#include "../graphics/wxWidgets/abase_exp.xpm"
#include "../graphics/wxWidgets/abase_warn.xpm"
#include "../graphics/wxWidgets/abase.xpm"
#include "../graphics/wxWidgets/alias.xpm"
#include "../graphics/wxWidgets/node.xpm"
#include "../graphics/wxWidgets/normal_exp.xpm"
#include "../graphics/wxWidgets/normal_warn.xpm"
#include "../graphics/wxWidgets/normal.xpm"
#include "../graphics/wxWidgets/sbase_exp.xpm"
#include "../graphics/wxWidgets/sbase_warn.xpm"
#include "../graphics/wxWidgets/sbase.xpm"
#include "../graphics/wxWidgets/shortcut.xpm"
/*!
* PWSTreeCtrl type definition
*/
IMPLEMENT_CLASS( PWSTreeCtrl, wxTreeCtrl )
// Image Indices - these match the order images are added
// in PWSTreeCtrl::CreateControls()
enum {
ABASE_EXP_II, // 0
ABASE_WARN_II, // 1
ABASE_II, // 2
ALIAS_II, // 3
NODE_II, // 4
NORMAL_EXP_II, // 5
NORMAL_WARN_II, // 6
NORMAL_II, // 7
SBASE_EXP_II, // 8
SBASE_WARN_II, // 9
SBASE_II, // 10
SHORTCUT_II, // 11
};
/*!
* PWSTreeCtrl event table definition
*/
BEGIN_EVENT_TABLE( PWSTreeCtrl, wxTreeCtrl )
////@begin PWSTreeCtrl event table entries
EVT_TREE_ITEM_ACTIVATED( ID_TREECTRL, PWSTreeCtrl::OnTreectrlItemActivated )
EVT_TREE_ITEM_MENU( ID_TREECTRL, PWSTreeCtrl::OnContextMenu )
EVT_CHAR( PWSTreeCtrl::OnChar )
////@end PWSTreeCtrl event table entries
EVT_TREE_ITEM_GETTOOLTIP( ID_TREECTRL, PWSTreeCtrl::OnGetToolTip )
END_EVENT_TABLE()
// helper class to match CItemData with wxTreeItemId
class PWTreeItemData : public wxTreeItemData
{
public:
PWTreeItemData(const CItemData &item)
{
item.GetUUID(m_uuid);
}
const uuid_array_t &GetUUID() const {return m_uuid;}
private:
uuid_array_t m_uuid;
};
/*!
* PWSTreeCtrl constructors
*/
PWSTreeCtrl::PWSTreeCtrl(PWScore &core) : m_core(core)
{
Init();
}
PWSTreeCtrl::PWSTreeCtrl(wxWindow* parent, PWScore &core,
wxWindowID id, const wxPoint& pos,
const wxSize& size, long style) : m_core(core)
{
Init();
Create(parent, id, pos, size, style);
}
/*!
* PWSTreeCtrl creator
*/
bool PWSTreeCtrl::Create(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style)
{
////@begin PWSTreeCtrl creation
wxTreeCtrl::Create(parent, id, pos, size, style);
CreateControls();
////@end PWSTreeCtrl creation
return true;
}
/*!
* PWSTreeCtrl destructor
*/
PWSTreeCtrl::~PWSTreeCtrl()
{
////@begin PWSTreeCtrl destruction
////@end PWSTreeCtrl destruction
}
/*!
* Member initialisation
*/
void PWSTreeCtrl::Init()
{
////@begin PWSTreeCtrl member initialisation
////@end PWSTreeCtrl member initialisation
}
/*!
* Control creation for PWSTreeCtrl
*/
void PWSTreeCtrl::CreateControls()
{
////@begin PWSTreeCtrl content construction
////@end PWSTreeCtrl content construction
const char **xpmList[] = {
abase_exp_xpm, // 0
abase_warn_xpm, // 1
abase_xpm, // 2
alias_xpm, // 3
node_xpm, // 4
normal_exp_xpm, // 5
normal_warn_xpm, // 6
normal_xpm, // 7
sbase_exp_xpm, // 8
sbase_warn_xpm, // 9
sbase_xpm, // 10
shortcut_xpm, // 11
};
const int Nimages = sizeof(xpmList)/sizeof(xpmList[0]);
wxImageList *iList = new wxImageList(9, 9, true, Nimages);
for (int i = 0; i < Nimages; i++)
iList->Add(wxIcon(xpmList[i]));
AssignImageList(iList);
}
// XXX taken from Windows PWSTreeCtrl.cpp
// XXX move to corelib
static StringX GetPathElem(StringX &path)
{
// Get first path element and chop it off, i.e., if
// path = "a.b.c.d"
// will return "a" and path will be "b.c.d"
// (assuming GROUP_SEP is '.')
const char GROUP_SEP = '.';
StringX retval;
StringX::size_type N = path.find(GROUP_SEP);
if (N == StringX::npos) {
retval = path;
path = _T("");
} else {
const StringX::size_type Len = path.length();
retval = path.substr(0, N);
path = path.substr(Len - N - 1);
}
return retval;
}
bool PWSTreeCtrl::ExistsInTree(wxTreeItemId node,
const StringX &s, wxTreeItemId &si)
{
// returns true iff s is a direct descendant of node
wxTreeItemIdValue cookie;
wxTreeItemId ti = GetFirstChild(node, cookie);
while (ti) {
const wxString itemText = GetItemText(ti);
if (itemText == s.c_str()) {
si = ti;
return true;
}
ti = GetNextSibling(ti);
}
return false;
}
wxTreeItemId PWSTreeCtrl::AddGroup(const StringX &group)
{
wxTreeItemId ti = GetRootItem();
if (!ti.IsOk())
ti=AddRoot(wxString());
// Add a group at the end of path
wxTreeItemId si;
if (!group.empty()) {
StringX path = group;
StringX s;
do {
s = GetPathElem(path);
if (!ExistsInTree(ti, s, si)) {
ti = AppendItem(ti, s.c_str());
wxTreeCtrl::SetItemImage(ti, NODE_II);
} else
ti = si;
} while (!path.empty());
}
return ti;
}
wxString PWSTreeCtrl::ItemDisplayString(const CItemData &item) const
{
PWSprefs *prefs = PWSprefs::GetInstance();
const wxString title = item.GetTitle().c_str();
wxString disp = title;
if (prefs->GetPref(PWSprefs::ShowUsernameInTree)) {
const wxString user = item.GetUser().c_str();
if (!user.empty())
disp += _T(" [") + user + _("]");
}
if (prefs->GetPref(PWSprefs::ShowPasswordInTree)) {
const wxString passwd = item.GetPassword().c_str();
if (!passwd.empty())
disp += _T(" {") + passwd + _("}");
}
return disp;
}
wxString PWSTreeCtrl::GetPath(const wxTreeItemId &node) const
{
wxString retval;
std::vector<wxString> v;
const wxTreeItemId root = GetRootItem();
wxTreeItemId parent = GetItemParent(node);
while (parent != root) {
v.push_back(GetItemText(parent));
parent = GetItemParent(parent);
}
std::vector<wxString>::reverse_iterator iter;
for(iter = v.rbegin(); iter != v.rend(); iter++) {
retval += *iter;
if ((iter + 1) != v.rend())
retval += _(".");
}
return retval;
}
void PWSTreeCtrl::UpdateItem(const CItemData &item)
{
const wxTreeItemId node = Find(item);
if (node.IsOk()) {
const wxString oldGroup = GetPath(node);
const wxString newGroup = item.GetGroup().c_str();
if (oldGroup == newGroup) {
const wxString disp = ItemDisplayString(item);
SetItemText(node, disp);
SetItemImage(node, item);
} else { // uh-oh - group's changed
uuid_array_t uuid;
item.GetUUID(uuid);
// remove old item
m_item_map.erase(CUUIDGen(uuid));
Delete(node);
// add new group
AddItem(item);
}
Update();
}
}
void PWSTreeCtrl::AddItem(const CItemData &item)
{
wxTreeItemData *data = new PWTreeItemData(item);
wxTreeItemId gnode = AddGroup(item.GetGroup());
const wxString disp = ItemDisplayString(item);
wxTreeItemId titem = AppendItem(gnode, disp, -1, -1, data);
SetItemImage(titem, item);
SortChildren(gnode);
uuid_array_t uuid;
item.GetUUID(uuid);
m_item_map.insert(std::make_pair(CUUIDGen(uuid), titem));
}
CItemData *PWSTreeCtrl::GetItem(const wxTreeItemId &id) const
{
if (!id.IsOk())
return NULL;
PWTreeItemData *itemData = dynamic_cast<PWTreeItemData *>(GetItemData(id));
// return if a group is selected
if (itemData == NULL)
return NULL;
ItemListIter itemiter = m_core.Find(itemData->GetUUID());
if (itemiter == m_core.GetEntryEndIter())
return NULL;
return &itemiter->second;
}
//overriden from base for case-insensitive sort
int PWSTreeCtrl::OnCompareItems(const wxTreeItemId& item1, const wxTreeItemId& item2)
{
const bool groupsFirst = PWSprefs::GetInstance()->GetPref(PWSprefs::ExplorerTypeTree),
item1isGroup = ItemHasChildren(item1),
item2isGroup = ItemHasChildren(item2);
if (groupsFirst) {
if (item1isGroup && !item2isGroup)
return -1;
else if (item2isGroup && !item1isGroup)
return 1;
}
const wxString text1 = GetItemText(item1);
const wxString text2 = GetItemText(item2);
return text1.CmpNoCase(text2);
}
wxTreeItemId PWSTreeCtrl::Find(const uuid_array_t &uuid) const
{
wxTreeItemId fail;
CUUIDGen cuuid(uuid);
UUIDTIMapT::const_iterator iter = m_item_map.find(cuuid);
if (iter != m_item_map.end())
return iter->second;
else
return fail;
}
wxTreeItemId PWSTreeCtrl::Find(const CItemData &item) const
{
uuid_array_t uuid;
item.GetUUID(uuid);
return Find(uuid);
}
bool PWSTreeCtrl::Remove(const uuid_array_t &uuid)
{
wxTreeItemId id = Find(uuid);
if (id.IsOk()) {
m_item_map.erase(CUUIDGen(uuid));
// if item's the only leaf of group, delete parent
// group as well. repeat up the tree...
wxTreeItemId parentId = GetItemParent(id);
Delete(id);
while (parentId != GetRootItem()) {
wxTreeItemId grandparentId = GetItemParent(parentId);
if (GetChildrenCount(parentId) == 0) {
Delete(parentId);
parentId = grandparentId;
} else
break;
} // while
Refresh();
Update();
return true;
} else {
return false;
}
}
void PWSTreeCtrl::SetItemImage(const wxTreeItemId &node,
const CItemData &item)
{
// XXX TBD: modify to display warning and expired states
int i = NORMAL_II;
switch (item.GetEntryType()) {
case CItemData::ET_NORMAL: i = NORMAL_II; break;
case CItemData::ET_ALIASBASE: i = ABASE_II; break;
case CItemData::ET_ALIAS: i = ALIAS_II; break;
case CItemData::ET_SHORTCUTBASE: i = SBASE_II; break;
case CItemData::ET_SHORTCUT: i = SHORTCUT_II; break;
case CItemData::ET_INVALID: ASSERT(0); break;
default: ASSERT(0);
}
wxTreeCtrl::SetItemImage(node, i);
}
/*!
* wxEVT_COMMAND_TREE_ITEM_ACTIVATED event handler for ID_TREECTRL
*/
void PWSTreeCtrl::OnTreectrlItemActivated( wxTreeEvent& evt )
{
const wxTreeItemId item = evt.GetItem();
if (ItemHasChildren(item) && GetChildrenCount(item) > 0){
if (IsExpanded(item))
Collapse(item);
else {
Expand(item);
//scroll the last child of this node into visibility
EnsureVisible(GetLastChild(item));
//but if that scrolled the parent out of the view, bring it back
EnsureVisible(item);
}
}
else {
CItemData *ci = GetItem(item);
if (ci != NULL)
dynamic_cast<PasswordSafeFrame *>(GetParent())->
DispatchDblClickAction(*ci);
}
}
/*!
* wxEVT_TREE_ITEM_MENU event handler for ID_TREECTRL
*/
void PWSTreeCtrl::OnContextMenu( wxTreeEvent& evt )
{
dynamic_cast<PasswordSafeFrame*>(GetParent())->OnContextMenu(GetItem(evt.GetItem()));
}
void PWSTreeCtrl::SelectItem(const CUUIDGen & uuid)
{
uuid_array_t uuid_array;
uuid.GetUUID(uuid_array);
wxTreeItemId id = Find(uuid_array);
if (id.IsOk())
wxTreeCtrl::SelectItem(id);
}
void PWSTreeCtrl::OnGetToolTip( wxTreeEvent& evt )
{ // Added manually
if (PWSprefs::GetInstance()->GetPref(PWSprefs::ShowNotesAsTooltipsInViews)) {
wxTreeItemId id = evt.GetItem();
const CItemData *ci = GetItem(id);
if (ci != NULL) {
const wxString note = ci->GetNotes().c_str();
evt.SetToolTip(note);
}
}
}
/*!
* wxEVT_CHAR event handler for ID_TREECTRL
*/
void PWSTreeCtrl::OnChar( wxKeyEvent& evt )
{
if (evt.GetKeyCode() == WXK_ESCAPE &&
PWSprefs::GetInstance()->GetPref(PWSprefs::EscExits)) {
GetParent()->Close();
}
evt.Skip();
}
<commit_msg>Fix incorrect (sub)group handling in wxWidgets build<commit_after>/*
* Copyright (c) 2003-2010 Rony Shapiro <ronys@users.sourceforge.net>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
/** \file PWSTreeCtrl.cpp
*
*/
// For compilers that support precompilation, includes "wx/wx.h".
#include "wx/wxprec.h"
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include "wx/wx.h"
#endif
////@begin includes
#include "wx/imaglist.h"
////@end includes
#include <utility> // for make_pair
#include <vector>
#include "PWStree.h"
#include "passwordsafeframe.h" // for DispatchDblClickAction()
#include "corelib/PWSprefs.h"
////@begin XPM images
////@end XPM images
#include "../graphics/wxWidgets/abase_exp.xpm"
#include "../graphics/wxWidgets/abase_warn.xpm"
#include "../graphics/wxWidgets/abase.xpm"
#include "../graphics/wxWidgets/alias.xpm"
#include "../graphics/wxWidgets/node.xpm"
#include "../graphics/wxWidgets/normal_exp.xpm"
#include "../graphics/wxWidgets/normal_warn.xpm"
#include "../graphics/wxWidgets/normal.xpm"
#include "../graphics/wxWidgets/sbase_exp.xpm"
#include "../graphics/wxWidgets/sbase_warn.xpm"
#include "../graphics/wxWidgets/sbase.xpm"
#include "../graphics/wxWidgets/shortcut.xpm"
/*!
* PWSTreeCtrl type definition
*/
IMPLEMENT_CLASS( PWSTreeCtrl, wxTreeCtrl )
// Image Indices - these match the order images are added
// in PWSTreeCtrl::CreateControls()
enum {
ABASE_EXP_II, // 0
ABASE_WARN_II, // 1
ABASE_II, // 2
ALIAS_II, // 3
NODE_II, // 4
NORMAL_EXP_II, // 5
NORMAL_WARN_II, // 6
NORMAL_II, // 7
SBASE_EXP_II, // 8
SBASE_WARN_II, // 9
SBASE_II, // 10
SHORTCUT_II, // 11
};
/*!
* PWSTreeCtrl event table definition
*/
BEGIN_EVENT_TABLE( PWSTreeCtrl, wxTreeCtrl )
////@begin PWSTreeCtrl event table entries
EVT_TREE_ITEM_ACTIVATED( ID_TREECTRL, PWSTreeCtrl::OnTreectrlItemActivated )
EVT_TREE_ITEM_MENU( ID_TREECTRL, PWSTreeCtrl::OnContextMenu )
EVT_CHAR( PWSTreeCtrl::OnChar )
////@end PWSTreeCtrl event table entries
EVT_TREE_ITEM_GETTOOLTIP( ID_TREECTRL, PWSTreeCtrl::OnGetToolTip )
END_EVENT_TABLE()
// helper class to match CItemData with wxTreeItemId
class PWTreeItemData : public wxTreeItemData
{
public:
PWTreeItemData(const CItemData &item)
{
item.GetUUID(m_uuid);
}
const uuid_array_t &GetUUID() const {return m_uuid;}
private:
uuid_array_t m_uuid;
};
/*!
* PWSTreeCtrl constructors
*/
PWSTreeCtrl::PWSTreeCtrl(PWScore &core) : m_core(core)
{
Init();
}
PWSTreeCtrl::PWSTreeCtrl(wxWindow* parent, PWScore &core,
wxWindowID id, const wxPoint& pos,
const wxSize& size, long style) : m_core(core)
{
Init();
Create(parent, id, pos, size, style);
}
/*!
* PWSTreeCtrl creator
*/
bool PWSTreeCtrl::Create(wxWindow* parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style)
{
////@begin PWSTreeCtrl creation
wxTreeCtrl::Create(parent, id, pos, size, style);
CreateControls();
////@end PWSTreeCtrl creation
return true;
}
/*!
* PWSTreeCtrl destructor
*/
PWSTreeCtrl::~PWSTreeCtrl()
{
////@begin PWSTreeCtrl destruction
////@end PWSTreeCtrl destruction
}
/*!
* Member initialisation
*/
void PWSTreeCtrl::Init()
{
////@begin PWSTreeCtrl member initialisation
////@end PWSTreeCtrl member initialisation
}
/*!
* Control creation for PWSTreeCtrl
*/
void PWSTreeCtrl::CreateControls()
{
////@begin PWSTreeCtrl content construction
////@end PWSTreeCtrl content construction
const char **xpmList[] = {
abase_exp_xpm, // 0
abase_warn_xpm, // 1
abase_xpm, // 2
alias_xpm, // 3
node_xpm, // 4
normal_exp_xpm, // 5
normal_warn_xpm, // 6
normal_xpm, // 7
sbase_exp_xpm, // 8
sbase_warn_xpm, // 9
sbase_xpm, // 10
shortcut_xpm, // 11
};
const int Nimages = sizeof(xpmList)/sizeof(xpmList[0]);
wxImageList *iList = new wxImageList(9, 9, true, Nimages);
for (int i = 0; i < Nimages; i++)
iList->Add(wxIcon(xpmList[i]));
AssignImageList(iList);
}
// XXX taken from Windows PWSTreeCtrl.cpp
// XXX move to corelib
static StringX GetPathElem(StringX &path)
{
// Get first path element and chop it off, i.e., if
// path = "a.b.c.d"
// will return "a" and path will be "b.c.d"
// (assuming GROUP_SEP is '.')
const TCHAR GROUP_SEP = _T('.');
StringX retval;
StringX::size_type N = path.find(GROUP_SEP);
if (N == StringX::npos) {
retval = path;
path = _T("");
} else {
retval = path.substr(0, N);
path = path.substr(N + 1);
}
return retval;
}
bool PWSTreeCtrl::ExistsInTree(wxTreeItemId node,
const StringX &s, wxTreeItemId &si)
{
// returns true iff s is a direct descendant of node
wxTreeItemIdValue cookie;
wxTreeItemId ti = GetFirstChild(node, cookie);
while (ti) {
const wxString itemText = GetItemText(ti);
if (itemText == s.c_str()) {
si = ti;
return true;
}
ti = GetNextSibling(ti);
}
return false;
}
wxTreeItemId PWSTreeCtrl::AddGroup(const StringX &group)
{
wxTreeItemId ti = GetRootItem();
if (!ti.IsOk())
ti=AddRoot(wxString());
// Add a group at the end of path
wxTreeItemId si;
if (!group.empty()) {
StringX path = group;
StringX s;
do {
s = GetPathElem(path);
if (!ExistsInTree(ti, s, si)) {
ti = AppendItem(ti, s.c_str());
wxTreeCtrl::SetItemImage(ti, NODE_II);
} else
ti = si;
} while (!path.empty());
}
return ti;
}
wxString PWSTreeCtrl::ItemDisplayString(const CItemData &item) const
{
PWSprefs *prefs = PWSprefs::GetInstance();
const wxString title = item.GetTitle().c_str();
wxString disp = title;
if (prefs->GetPref(PWSprefs::ShowUsernameInTree)) {
const wxString user = item.GetUser().c_str();
if (!user.empty())
disp += _T(" [") + user + _("]");
}
if (prefs->GetPref(PWSprefs::ShowPasswordInTree)) {
const wxString passwd = item.GetPassword().c_str();
if (!passwd.empty())
disp += _T(" {") + passwd + _("}");
}
return disp;
}
wxString PWSTreeCtrl::GetPath(const wxTreeItemId &node) const
{
wxString retval;
std::vector<wxString> v;
const wxTreeItemId root = GetRootItem();
wxTreeItemId parent = GetItemParent(node);
while (parent != root) {
v.push_back(GetItemText(parent));
parent = GetItemParent(parent);
}
std::vector<wxString>::reverse_iterator iter;
for(iter = v.rbegin(); iter != v.rend(); iter++) {
retval += *iter;
if ((iter + 1) != v.rend())
retval += _(".");
}
return retval;
}
void PWSTreeCtrl::UpdateItem(const CItemData &item)
{
const wxTreeItemId node = Find(item);
if (node.IsOk()) {
const wxString oldGroup = GetPath(node);
const wxString newGroup = item.GetGroup().c_str();
if (oldGroup == newGroup) {
const wxString disp = ItemDisplayString(item);
SetItemText(node, disp);
SetItemImage(node, item);
} else { // uh-oh - group's changed
uuid_array_t uuid;
item.GetUUID(uuid);
// remove old item
m_item_map.erase(CUUIDGen(uuid));
Delete(node);
// add new group
AddItem(item);
}
Update();
}
}
void PWSTreeCtrl::AddItem(const CItemData &item)
{
wxTreeItemData *data = new PWTreeItemData(item);
wxTreeItemId gnode = AddGroup(item.GetGroup());
const wxString disp = ItemDisplayString(item);
wxTreeItemId titem = AppendItem(gnode, disp, -1, -1, data);
SetItemImage(titem, item);
SortChildren(gnode);
uuid_array_t uuid;
item.GetUUID(uuid);
m_item_map.insert(std::make_pair(CUUIDGen(uuid), titem));
}
CItemData *PWSTreeCtrl::GetItem(const wxTreeItemId &id) const
{
if (!id.IsOk())
return NULL;
PWTreeItemData *itemData = dynamic_cast<PWTreeItemData *>(GetItemData(id));
// return if a group is selected
if (itemData == NULL)
return NULL;
ItemListIter itemiter = m_core.Find(itemData->GetUUID());
if (itemiter == m_core.GetEntryEndIter())
return NULL;
return &itemiter->second;
}
//overriden from base for case-insensitive sort
int PWSTreeCtrl::OnCompareItems(const wxTreeItemId& item1, const wxTreeItemId& item2)
{
const bool groupsFirst = PWSprefs::GetInstance()->GetPref(PWSprefs::ExplorerTypeTree),
item1isGroup = ItemHasChildren(item1),
item2isGroup = ItemHasChildren(item2);
if (groupsFirst) {
if (item1isGroup && !item2isGroup)
return -1;
else if (item2isGroup && !item1isGroup)
return 1;
}
const wxString text1 = GetItemText(item1);
const wxString text2 = GetItemText(item2);
return text1.CmpNoCase(text2);
}
wxTreeItemId PWSTreeCtrl::Find(const uuid_array_t &uuid) const
{
wxTreeItemId fail;
CUUIDGen cuuid(uuid);
UUIDTIMapT::const_iterator iter = m_item_map.find(cuuid);
if (iter != m_item_map.end())
return iter->second;
else
return fail;
}
wxTreeItemId PWSTreeCtrl::Find(const CItemData &item) const
{
uuid_array_t uuid;
item.GetUUID(uuid);
return Find(uuid);
}
bool PWSTreeCtrl::Remove(const uuid_array_t &uuid)
{
wxTreeItemId id = Find(uuid);
if (id.IsOk()) {
m_item_map.erase(CUUIDGen(uuid));
// if item's the only leaf of group, delete parent
// group as well. repeat up the tree...
wxTreeItemId parentId = GetItemParent(id);
Delete(id);
while (parentId != GetRootItem()) {
wxTreeItemId grandparentId = GetItemParent(parentId);
if (GetChildrenCount(parentId) == 0) {
Delete(parentId);
parentId = grandparentId;
} else
break;
} // while
Refresh();
Update();
return true;
} else {
return false;
}
}
void PWSTreeCtrl::SetItemImage(const wxTreeItemId &node,
const CItemData &item)
{
// XXX TBD: modify to display warning and expired states
int i = NORMAL_II;
switch (item.GetEntryType()) {
case CItemData::ET_NORMAL: i = NORMAL_II; break;
case CItemData::ET_ALIASBASE: i = ABASE_II; break;
case CItemData::ET_ALIAS: i = ALIAS_II; break;
case CItemData::ET_SHORTCUTBASE: i = SBASE_II; break;
case CItemData::ET_SHORTCUT: i = SHORTCUT_II; break;
case CItemData::ET_INVALID: ASSERT(0); break;
default: ASSERT(0);
}
wxTreeCtrl::SetItemImage(node, i);
}
/*!
* wxEVT_COMMAND_TREE_ITEM_ACTIVATED event handler for ID_TREECTRL
*/
void PWSTreeCtrl::OnTreectrlItemActivated( wxTreeEvent& evt )
{
const wxTreeItemId item = evt.GetItem();
if (ItemHasChildren(item) && GetChildrenCount(item) > 0){
if (IsExpanded(item))
Collapse(item);
else {
Expand(item);
//scroll the last child of this node into visibility
EnsureVisible(GetLastChild(item));
//but if that scrolled the parent out of the view, bring it back
EnsureVisible(item);
}
}
else {
CItemData *ci = GetItem(item);
if (ci != NULL)
dynamic_cast<PasswordSafeFrame *>(GetParent())->
DispatchDblClickAction(*ci);
}
}
/*!
* wxEVT_TREE_ITEM_MENU event handler for ID_TREECTRL
*/
void PWSTreeCtrl::OnContextMenu( wxTreeEvent& evt )
{
dynamic_cast<PasswordSafeFrame*>(GetParent())->OnContextMenu(GetItem(evt.GetItem()));
}
void PWSTreeCtrl::SelectItem(const CUUIDGen & uuid)
{
uuid_array_t uuid_array;
uuid.GetUUID(uuid_array);
wxTreeItemId id = Find(uuid_array);
if (id.IsOk())
wxTreeCtrl::SelectItem(id);
}
void PWSTreeCtrl::OnGetToolTip( wxTreeEvent& evt )
{ // Added manually
if (PWSprefs::GetInstance()->GetPref(PWSprefs::ShowNotesAsTooltipsInViews)) {
wxTreeItemId id = evt.GetItem();
const CItemData *ci = GetItem(id);
if (ci != NULL) {
const wxString note = ci->GetNotes().c_str();
evt.SetToolTip(note);
}
}
}
/*!
* wxEVT_CHAR event handler for ID_TREECTRL
*/
void PWSTreeCtrl::OnChar( wxKeyEvent& evt )
{
if (evt.GetKeyCode() == WXK_ESCAPE &&
PWSprefs::GetInstance()->GetPref(PWSprefs::EscExits)) {
GetParent()->Close();
}
evt.Skip();
}
<|endoftext|> |
<commit_before>// H264 receiver
// Author: Max Schwarz <max.schwarz@uni-bonn.de>
#include <ros/ros.h>
extern "C"
{
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>
}
#include <image_transport/image_transport.h>
#include <sensor_msgs/CompressedImage.h>
ros::Publisher g_pub;
AVCodecContext* g_codec = 0;
SwsContext* g_sws = 0;
void handleImage(const sensor_msgs::CompressedImageConstPtr& img)
{
//ROS_INFO("got data: %lu", img->data.size());
AVPacket packet;
av_init_packet(&packet);
packet.data = const_cast<uint8_t*>(img->data.data());
packet.size = img->data.size();
packet.pts = AV_NOPTS_VALUE;
packet.dts = AV_NOPTS_VALUE;
AVFrame frame;
memset(&frame, 0, sizeof(frame));
int gotPicture;
if(avcodec_decode_video2(g_codec, &frame, &gotPicture, &packet) < 0)
{
//ROS_ERROR("Could not decode frame");
return;
}
if(gotPicture)
{
g_sws = sws_getCachedContext(
g_sws,
frame.width, frame.height, AV_PIX_FMT_YUV420P,
frame.width, frame.height, AV_PIX_FMT_RGB24,
0, 0, 0, 0
);
sensor_msgs::ImagePtr img(new sensor_msgs::Image);
img->encoding = "rgb8";
img->data.resize(frame.width * frame.height * 3);
img->step = frame.width * 3;
img->width = frame.width;
img->height = frame.height;
img->header.frame_id = "cam";
img->header.stamp = ros::Time::now(); // FIXME
uint8_t* destData[1] = {img->data.data()};
int linesize[1] = {(int)img->step};
sws_scale(g_sws, frame.data, frame.linesize, 0, frame.height,
destData, linesize);
//ROS_DEBUG("frame");
g_pub.publish(img);
}
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "cam_receiver");
ros::NodeHandle nh("~");
avcodec_register_all();
AVCodec* decoder = avcodec_find_decoder(AV_CODEC_ID_H264);
if(!decoder)
throw std::runtime_error("H264 decoding not supported in this build of ffmpeg");
g_codec = avcodec_alloc_context3(decoder);
g_codec->flags |= CODEC_FLAG_LOW_DELAY;
g_codec->flags2 |= CODEC_FLAG2_SHOW_ALL;
g_codec->thread_type = 0;
if(avcodec_open2(g_codec, decoder, 0) != 0)
throw std::runtime_error("Could not open decoder");
g_pub = nh.advertise<sensor_msgs::Image>("image", 1);
ros::Subscriber sub = nh.subscribe("encoded", 5, &handleImage);
ros::spin();
return 0;
}
<commit_msg>nimbro_cam_transport: set ffmepg log level to quiet<commit_after>// H264 receiver
// Author: Max Schwarz <max.schwarz@uni-bonn.de>
#include <ros/ros.h>
extern "C"
{
#include <libavcodec/avcodec.h>
#include <libswscale/swscale.h>
}
#include <image_transport/image_transport.h>
#include <sensor_msgs/CompressedImage.h>
ros::Publisher g_pub;
AVCodecContext* g_codec = 0;
SwsContext* g_sws = 0;
void handleImage(const sensor_msgs::CompressedImageConstPtr& img)
{
//ROS_INFO("got data: %lu", img->data.size());
AVPacket packet;
av_init_packet(&packet);
packet.data = const_cast<uint8_t*>(img->data.data());
packet.size = img->data.size();
packet.pts = AV_NOPTS_VALUE;
packet.dts = AV_NOPTS_VALUE;
AVFrame frame;
memset(&frame, 0, sizeof(frame));
int gotPicture;
if(avcodec_decode_video2(g_codec, &frame, &gotPicture, &packet) < 0)
{
//ROS_ERROR("Could not decode frame");
return;
}
if(gotPicture)
{
g_sws = sws_getCachedContext(
g_sws,
frame.width, frame.height, AV_PIX_FMT_YUV420P,
frame.width, frame.height, AV_PIX_FMT_RGB24,
0, 0, 0, 0
);
sensor_msgs::ImagePtr img(new sensor_msgs::Image);
img->encoding = "rgb8";
img->data.resize(frame.width * frame.height * 3);
img->step = frame.width * 3;
img->width = frame.width;
img->height = frame.height;
img->header.frame_id = "cam";
img->header.stamp = ros::Time::now(); // FIXME
uint8_t* destData[1] = {img->data.data()};
int linesize[1] = {(int)img->step};
sws_scale(g_sws, frame.data, frame.linesize, 0, frame.height,
destData, linesize);
//ROS_DEBUG("frame");
g_pub.publish(img);
}
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "cam_receiver");
ros::NodeHandle nh("~");
avcodec_register_all();
av_log_set_level(AV_LOG_QUIET);
AVCodec* decoder = avcodec_find_decoder(AV_CODEC_ID_H264);
if(!decoder)
throw std::runtime_error("H264 decoding not supported in this build of ffmpeg");
g_codec = avcodec_alloc_context3(decoder);
g_codec->flags |= CODEC_FLAG_LOW_DELAY;
g_codec->flags2 |= CODEC_FLAG2_SHOW_ALL;
g_codec->thread_type = 0;
if(avcodec_open2(g_codec, decoder, 0) != 0)
throw std::runtime_error("Could not open decoder");
g_pub = nh.advertise<sensor_msgs::Image>("image", 1);
ros::Subscriber sub = nh.subscribe("encoded", 5, &handleImage);
ros::spin();
return 0;
}
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "integrators/photonvolume.h"
#include "renderers/samplerrenderer.h"
// #include "integrators/photonmap.cpp"
#include "paramset.h"
#include "montecarlo.h"
#include "rainbow.h"
void PhotonVolumeIntegrator::RequestSamples(Sampler *sampler, Sample *sample,
const Scene *scene){
tauSampleOffset = sample->Add1D(1);
scatterSampleOffset = sample->Add1D(1);
}
Spectrum PhotonVolumeIntegrator::Transmittance(const Scene *scene,
const Renderer *renderer, const RayDifferential &ray,
const Sample *sample, RNG &rng, MemoryArena &arena) const {
if (!scene->volumeRegion) return Spectrum(1.f);
float step, offset;
if (sample) {
step = stepSize;
offset = sample->oneD[tauSampleOffset][0];
}
else {
step = 4.f * stepSize;
offset = rng.RandomFloat();
}
Spectrum tau = scene->volumeRegion->tau(ray, step, offset);
return Exp(-tau);
}
float rainbowWavelength(const Vector &w, const Vector &wi){
//1. Calc wavelength depending on theta
float cosTheta = Dot(wi, -w);
const float radToDeg = 57.2957;
float theta = radToDeg * acosf(cosTheta);
//printf("%f\n", theta);
//printf("%f %f %f\n", p->wi.x, p->wi.y, p->wi.z);
//Water droplets modelled produce a
//primary rainbow when angle between incoming and outgoing
//rays are [40.4, 42.3] degrees.
//If not in this range, don't contribute to total flux
const float minTheta = 40.4, minWavelength = 400.0;
const float maxTheta = 42.3, maxWavelength = 700.0;
if (theta < minTheta || maxTheta < theta){
return 0;
}
const float thetaRange = maxTheta-minTheta;
const float wavelengthRange = maxWavelength-minWavelength;
float wavelength = minWavelength + (theta-minTheta) * wavelengthRange / thetaRange;
return wavelength;
}
Spectrum PhotonVolumeIntegrator::LPhoton(KdTree<Photon> *map, int nLookup, ClosePhoton *lookupBuf,
const Vector &w, const Point &pt, VolumeRegion *vr, float maxDistSquare, float t) const {
Spectrum L(0.);
if (!map) return L;
// Initialize _PhotonProcess_ object, _proc_, for photon map lookups
PhotonProcess proc(nLookup, lookupBuf);
proc.photons = (ClosePhoton *)alloca(nLookup * sizeof(ClosePhoton));
// Do photon map lookup
map->Lookup(pt, proc, maxDistSquare);
// // Accumulate light from nearby photons
// // Estimate reflected light from photons
ClosePhoton *photons = proc.photons;
int nFound = proc.nFound;
if (nFound<10)
return L;
Spectrum totalFlux(0.);
float maxmd = 0.0;
for (int i = 0; i < nFound; ++i) {
const Photon *p = photons[i].photon;
Point pt_i = p->p;
float distSq = photons[i].distanceSquared;
if (distSq>maxmd) maxmd = distSq;
totalFlux += p->alpha * vr->p(pt_i,p->wi,-w,t);
}
float distSq = maxmd;
float dV = distSq * sqrt(distSq);
Spectrum scale = vr->sigma_s(pt, w,t);
if (dV!=0.0 && scale!=0.0){
L += totalFlux/(4.0/3.0*M_PI*dV*scale);
}
return L;
}
Spectrum PhotonVolumeIntegrator::Li(const Scene *scene, const Renderer *renderer,
const RayDifferential &ray, const Sample *sample, RNG &rng,
Spectrum *T, MemoryArena &arena) const {
VolumeRegion *vr = scene->volumeRegion;
RainbowVolume* rv = dynamic_cast<RainbowVolume*>(vr);
KdTree<Photon>* volumeMap = photonShooter->volumeMap;
float t0, t1;
if (!vr || !vr->IntersectP(ray, &t0, &t1) || (t1-t0) == 0.f){
*T = 1.f;
return 0.f;
}
// Do single scattering & photon multiple scattering volume integration in _vr_
Spectrum Lv(0.);
// Prepare for volume integration stepping
int nSamples = Ceil2Int((t1-t0) / stepSize);
float step = (t1 - t0) / nSamples;
Spectrum Tr(1.f);
Point p = ray(t0), pPrev;
Vector w = -ray.d;
t0 += sample->oneD[scatterSampleOffset][0] * step;
float *lightNum = arena.Alloc<float>(nSamples);
LDShuffleScrambled1D(1, nSamples, lightNum, rng);
float *lightComp = arena.Alloc<float>(nSamples);
LDShuffleScrambled1D(1, nSamples, lightComp, rng);
float *lightPos = arena.Alloc<float>(2*nSamples);
LDShuffleScrambled2D(1, nSamples, lightPos, rng);
int sampOffset = 0;
ClosePhoton *lookupBuf = new ClosePhoton[nSamples];
for (int i = 0; i < nSamples; ++i, t0 += step) {
// Advance to sample at _t0_ and update _T_
pPrev = p;
p = ray(t0);
Ray tauRay(pPrev, p - pPrev, 0.f, 1.f, ray.time, ray.depth);
Spectrum stepTau = vr->tau(tauRay,.5f * stepSize, rng.RandomFloat());
Tr = Exp(-stepTau);
// Possibly terminate raymarching if transmittance is small.
if (Tr.y() < 1e-3) {
const float continueProb = .5f;
if (rng.RandomFloat() > continueProb){
Tr = 0.f;
break;
}
Tr /= continueProb;
}
// Compute single-scattering source term at _p_ & photon mapped MS
Spectrum L_i(0.);
Spectrum L_d(0.);
Spectrum L_ii(0.);
// Lv += Tr*vr->Lve(p, w, ray.time);
Spectrum ss = vr->sigma_s(p, w, ray.time);
Spectrum sa = vr->sigma_a(p, w, ray.time);
if (!ss.IsBlack() && scene->lights.size() > 0) {
int nLights = scene->lights.size();
int ln =
min(Floor2Int(lightNum[sampOffset] * nLights),
nLights-1);
Light *light = scene->lights[ln];
// Add contribution of _light_ due to scattering at _p_
float pdf;
VisibilityTester vis;
Vector wo;
LightSample ls(lightComp[sampOffset], lightPos[2*sampOffset],
lightPos[2*sampOffset+1]);
Spectrum L = light->Sample_L(p, 0.f, ls, ray.time, &wo, &pdf, &vis);
if (!L.IsBlack() && pdf > 0.f && vis.Unoccluded(scene)) {
Spectrum Ld = L * vis.Transmittance(scene,renderer, NULL, rng, arena);
L_d = vr->p(p, w, -wo, ray.time) * Ld * float(nLights)/pdf;
/* OUR CODE STARTS HERE */
if(rv){
L_d = rv->waterdropReflection(L_d, ray.d, wo);
}
/* OUR CODE ENDS HERE */
}
}
// Compute 'indirect' in-scattered radiance from photon map
L_ii += LPhoton(volumeMap, nUsed, lookupBuf, w, p, vr, maxDistSquared, ray.time);
// Compute total in-scattered radiance
if (sa.y()!=0.0 || ss.y()!=0.0)
L_i = L_d + (ss/(sa+ss))*L_ii;
else
L_i = L_d;
Spectrum nLv = (sa*vr->Lve(p,w,ray.time)*step) + (ss*L_i*step) + (Tr * L)v;
Lv = nLv;
sampOffset++;
}
*T = Tr;
return Lv;
}
PhotonVolumeIntegrator *CreatePhotonVolumeIntegrator(const ParamSet ¶ms, PhotonShooter* phs){
float stepSize = params.FindOneFloat("stepsize", 1.f);
int nUsed = params.FindOneInt("nused", 250);
float maxDist = params.FindOneFloat("maxdist", 0.1f);
return new PhotonVolumeIntegrator(stepSize, nUsed, maxDist, phs);
}<commit_msg>Small fix<commit_after>#include "stdafx.h"
#include "integrators/photonvolume.h"
#include "renderers/samplerrenderer.h"
// #include "integrators/photonmap.cpp"
#include "paramset.h"
#include "montecarlo.h"
#include "volumes/rainbow.h"
void PhotonVolumeIntegrator::RequestSamples(Sampler *sampler, Sample *sample,
const Scene *scene){
tauSampleOffset = sample->Add1D(1);
scatterSampleOffset = sample->Add1D(1);
}
Spectrum PhotonVolumeIntegrator::Transmittance(const Scene *scene,
const Renderer *renderer, const RayDifferential &ray,
const Sample *sample, RNG &rng, MemoryArena &arena) const {
if (!scene->volumeRegion) return Spectrum(1.f);
float step, offset;
if (sample) {
step = stepSize;
offset = sample->oneD[tauSampleOffset][0];
}
else {
step = 4.f * stepSize;
offset = rng.RandomFloat();
}
Spectrum tau = scene->volumeRegion->tau(ray, step, offset);
return Exp(-tau);
}
float rainbowWavelength(const Vector &w, const Vector &wi){
//1. Calc wavelength depending on theta
float cosTheta = Dot(wi, -w);
const float radToDeg = 57.2957;
float theta = radToDeg * acosf(cosTheta);
//printf("%f\n", theta);
//printf("%f %f %f\n", p->wi.x, p->wi.y, p->wi.z);
//Water droplets modelled produce a
//primary rainbow when angle between incoming and outgoing
//rays are [40.4, 42.3] degrees.
//If not in this range, don't contribute to total flux
const float minTheta = 40.4, minWavelength = 400.0;
const float maxTheta = 42.3, maxWavelength = 700.0;
if (theta < minTheta || maxTheta < theta){
return 0;
}
const float thetaRange = maxTheta-minTheta;
const float wavelengthRange = maxWavelength-minWavelength;
float wavelength = minWavelength + (theta-minTheta) * wavelengthRange / thetaRange;
return wavelength;
}
Spectrum PhotonVolumeIntegrator::LPhoton(KdTree<Photon> *map, int nLookup, ClosePhoton *lookupBuf,
const Vector &w, const Point &pt, VolumeRegion *vr, float maxDistSquare, float t) const {
Spectrum L(0.);
if (!map) return L;
// Initialize _PhotonProcess_ object, _proc_, for photon map lookups
PhotonProcess proc(nLookup, lookupBuf);
proc.photons = (ClosePhoton *)alloca(nLookup * sizeof(ClosePhoton));
// Do photon map lookup
map->Lookup(pt, proc, maxDistSquare);
// // Accumulate light from nearby photons
// // Estimate reflected light from photons
ClosePhoton *photons = proc.photons;
int nFound = proc.nFound;
if (nFound<10)
return L;
Spectrum totalFlux(0.);
float maxmd = 0.0;
for (int i = 0; i < nFound; ++i) {
const Photon *p = photons[i].photon;
Point pt_i = p->p;
float distSq = photons[i].distanceSquared;
if (distSq>maxmd) maxmd = distSq;
totalFlux += p->alpha * vr->p(pt_i,p->wi,-w,t);
}
float distSq = maxmd;
float dV = distSq * sqrt(distSq);
Spectrum scale = vr->sigma_s(pt, w,t);
if (dV!=0.0 && scale!=0.0){
L += totalFlux/(4.0/3.0*M_PI*dV*scale);
}
return L;
}
Spectrum PhotonVolumeIntegrator::Li(const Scene *scene, const Renderer *renderer,
const RayDifferential &ray, const Sample *sample, RNG &rng,
Spectrum *T, MemoryArena &arena) const {
VolumeRegion *vr = scene->volumeRegion;
RainbowVolume* rv = dynamic_cast<RainbowVolume*>(vr);
KdTree<Photon>* volumeMap = photonShooter->volumeMap;
float t0, t1;
if (!vr || !vr->IntersectP(ray, &t0, &t1) || (t1-t0) == 0.f){
*T = 1.f;
return 0.f;
}
// Do single scattering & photon multiple scattering volume integration in _vr_
Spectrum Lv(0.);
// Prepare for volume integration stepping
int nSamples = Ceil2Int((t1-t0) / stepSize);
float step = (t1 - t0) / nSamples;
Spectrum Tr(1.f);
Point p = ray(t0), pPrev;
Vector w = -ray.d;
t0 += sample->oneD[scatterSampleOffset][0] * step;
float *lightNum = arena.Alloc<float>(nSamples);
LDShuffleScrambled1D(1, nSamples, lightNum, rng);
float *lightComp = arena.Alloc<float>(nSamples);
LDShuffleScrambled1D(1, nSamples, lightComp, rng);
float *lightPos = arena.Alloc<float>(2*nSamples);
LDShuffleScrambled2D(1, nSamples, lightPos, rng);
int sampOffset = 0;
ClosePhoton *lookupBuf = new ClosePhoton[nSamples];
for (int i = 0; i < nSamples; ++i, t0 += step) {
// Advance to sample at _t0_ and update _T_
pPrev = p;
p = ray(t0);
Ray tauRay(pPrev, p - pPrev, 0.f, 1.f, ray.time, ray.depth);
Spectrum stepTau = vr->tau(tauRay,.5f * stepSize, rng.RandomFloat());
Tr = Exp(-stepTau);
// Possibly terminate raymarching if transmittance is small.
if (Tr.y() < 1e-3) {
const float continueProb = .5f;
if (rng.RandomFloat() > continueProb){
Tr = 0.f;
break;
}
Tr /= continueProb;
}
// Compute single-scattering source term at _p_ & photon mapped MS
Spectrum L_i(0.);
Spectrum L_d(0.);
Spectrum L_ii(0.);
// Lv += Tr*vr->Lve(p, w, ray.time);
Spectrum ss = vr->sigma_s(p, w, ray.time);
Spectrum sa = vr->sigma_a(p, w, ray.time);
if (!ss.IsBlack() && scene->lights.size() > 0) {
int nLights = scene->lights.size();
int ln =
min(Floor2Int(lightNum[sampOffset] * nLights),
nLights-1);
Light *light = scene->lights[ln];
// Add contribution of _light_ due to scattering at _p_
float pdf;
VisibilityTester vis;
Vector wo;
LightSample ls(lightComp[sampOffset], lightPos[2*sampOffset],
lightPos[2*sampOffset+1]);
Spectrum L = light->Sample_L(p, 0.f, ls, ray.time, &wo, &pdf, &vis);
if (!L.IsBlack() && pdf > 0.f && vis.Unoccluded(scene)) {
Spectrum Ld = L * vis.Transmittance(scene,renderer, NULL, rng, arena);
L_d = vr->p(p, w, -wo, ray.time) * Ld * float(nLights)/pdf;
/* OUR CODE STARTS HERE */
if(rv){
L_d = rv->waterdropReflection(L_d, ray.d, wo);
}
/* OUR CODE ENDS HERE */
}
}
// Compute 'indirect' in-scattered radiance from photon map
L_ii += LPhoton(volumeMap, nUsed, lookupBuf, w, p, vr, maxDistSquared, ray.time);
// Compute total in-scattered radiance
if (sa.y()!=0.0 || ss.y()!=0.0)
L_i = L_d + (ss/(sa+ss))*L_ii;
else
L_i = L_d;
Spectrum nLv = (sa*vr->Lve(p,w,ray.time)*step) + (ss*L_i*step) + (Tr * Lv);
Lv = nLv;
sampOffset++;
}
*T = Tr;
return Lv;
}
PhotonVolumeIntegrator *CreatePhotonVolumeIntegrator(const ParamSet ¶ms, PhotonShooter* phs){
float stepSize = params.FindOneFloat("stepsize", 1.f);
int nUsed = params.FindOneInt("nused", 250);
float maxDist = params.FindOneFloat("maxdist", 0.1f);
return new PhotonVolumeIntegrator(stepSize, nUsed, maxDist, phs);
}<|endoftext|> |
<commit_before>// nonpareil_sampling - Part of the nonpareil package
// @author Luis M. Rodriguez-R <lmrodriguezr at gmail dot com>
// @license artistic 2.0
// @version 1.0
#define _MULTI_THREADED
#include <iostream>
#include <fstream>
#include <unistd.h>
#include <stdio.h>
#include <math.h>
#include <pthread.h>
#include <vector>
#include <algorithm>
#include "universal.h"
// #include "multinode.h"
#include "sequence.h"
#include "nonpareil_sampling.h"
//extern int processID;
//extern int processes;
#define LARGEST_LABEL 128
#define LARGEST_LINE 2048
using namespace std;
int nonpareil_sample_portion(double *&result, int threads, samplepar_t samplepar){
// Vars
if(samplepar.replicates<threads) threads = samplepar.replicates;
samplejob_t samplejob[threads];
pthread_t thread[threads];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int rc, samples_per_thr, launched_replicates=0;
// Blank result
result = new double[samplepar.replicates];
for(int a=0; a<samplepar.replicates; a++) result[a] = 0.0;
// Set sample
//if(processID==0)
say("4sfs^", "Sampling at ", samplepar.portion*100, "%");
samples_per_thr = (int)ceil((double)samplepar.replicates/(double)threads);
threads = (int)ceil((double)samplepar.replicates/samples_per_thr);
// Launch samplings
for(int thr=0; thr<threads; thr++){
samplejob[thr].id = thr;
samplejob[thr].from_in_result = thr*samples_per_thr; // Zero-based index to start at in the results array
samplejob[thr].number = samplejob[thr].from_in_result+samples_per_thr > samplepar.replicates ? samplepar.replicates-samplejob[thr].from_in_result : samples_per_thr;
samplejob[thr].samplepar = samplepar;
samplejob[thr].result = &result;
samplejob[thr].mutex = &mutex;
launched_replicates += samplejob[thr].number;
if((rc=pthread_create(&thread[thr], NULL, &nonpareil_sample_portion_thr, (void *)&samplejob[thr] )))
error("Thread creation failed", (char)rc);
}
// Gather jobs
for(int thr=0; thr<threads; thr++){
//if(thr%processes == processID)
pthread_join(thread[thr], NULL);
}
// Return
return launched_replicates;
}
void *nonpareil_sample_portion_thr(void *samplejob_ref){
// Vars
samplejob_t *samplejob = (samplejob_t *)samplejob_ref;
int *&mates_ref = *samplejob->samplepar.mates, n;
double *result_cp = new double[samplejob->number], p, p_gt_0;
// Sample
for(int i=0; i<samplejob->number; i++){
int found=0, sample_size=0;
// For each read with known number of mates
for(int j=0; j<samplejob->samplepar.mates_size; j++){
// Include the read in the sample?
if(((double)rand()/(double)RAND_MAX) < samplejob->samplepar.portion){
sample_size++;
// Does the sample contain at least one mate?
// if((double)rand()/(double)RAND_MAX < 1.0-pow(1-samplejob->samplepar.portion, mates_ref[j]-1)) found++;
n=(int)floor((samplejob->samplepar.total_reads)*samplejob->samplepar.portion)-1; // -1 because we exclude the query read from the sample
if(n<0) n=0;
p=(double)(mates_ref[j]-1.0)/(samplejob->samplepar.total_reads-1.0); // Again, -1 in both terms because of the query read
p_gt_0 = 1.0 - pow(1.0-p, n);
//cout << "n=" << n << ", p=" << p << "P(X>0)=" << p_gt_0 << endl;
if((double)rand()/(double)RAND_MAX < p_gt_0) found++;
}
}
result_cp[i] = sample_size==0 ? 0.0 : (double)found/(double)sample_size;
}
// Transfer results to the external vector
pthread_mutex_lock( samplejob->mutex );
double *&result_ref = *samplejob->result;
// v--> position + first of the thread
for(int i=0; i<samplejob->number; i++) result_ref[i + samplejob->from_in_result] = result_cp[i];
pthread_mutex_unlock( samplejob->mutex );
return (void *)0;
}
sample_t nonpareil_sample_summary(double *&sample_result, int sample_number, char *alldata, char *outfile, samplepar_t samplepar){
// Vars
double x2=0;
vector<double> dataPoints;
FILE *alldatah, *summaryh;
bool reportAllData=false;
int reportSummary=0;
char *text, *label, *sep, *header=(char*)"";
sample_t s;
s.portion = samplepar.portion;
// File handlers
if(alldata && strlen(alldata)>0){
alldatah = fopen(alldata, (samplepar.portion==samplepar.portion_min ? "w" : "a+"));
if(alldatah==NULL) error("I cannot write on all-data file", alldata);
reportAllData=true;
}
if(strlen(outfile)>0 && strcmp(outfile, "-")!=0){
summaryh = fopen(outfile, (samplepar.portion==samplepar.portion_min ? "w" : "a+"));
if(summaryh==NULL) error("I cannot write on summary file", outfile);
reportSummary=1;
}else if(strlen(outfile)>0){
reportSummary=2;
}
if(samplepar.portion==samplepar.portion_min){
header = new char[LARGEST_LINE];
if(samplepar.type == 1) {
sprintf(header, "# @ksize: %d\n# @impl: Nonpareil\n# @version: %.2f\n# @maxL: %d\n# @L: %.3f\n# @R: %llu\n# @overlap: %.2f\n# @divide: %.2f\n",
samplepar.k,
samplepar.np_version,
samplepar.max_read_len,
samplepar.avg_read_len,
samplepar.total_reads,
samplepar.seq_overlap*100.0,
samplepar.divide);
}
else if(samplepar.type == 2) {
sprintf(header, "# @ksize: %d\n# @impl: Nonpareil\n# @version: %.2f\n# @L: %.3f\n# @AL: %.3f\n# @R: %llu\n# @overlap: %.2f\n# @divide: %.2f\n",
samplepar.k,
samplepar.np_version,
samplepar.avg_read_len,
samplepar.adj_avg_read_len,
samplepar.total_reads,
samplepar.seq_overlap*100.0,
samplepar.divide);
}
}
if(sample_number>0){
// Average & SD
s.avg = s.sd = x2 = 0.0;
for(int a=0; a<sample_number; a++){
s.avg += (double)sample_result[a];
x2 += pow((double)sample_result[a], 2.0);
dataPoints.push_back(sample_result[a]);
if(reportAllData) fprintf(alldatah, "%.2f\t%d\t%.10f\n", samplepar.portion, a, sample_result[a]);
}
fclose(alldatah);
s.avg /= (double)sample_number;
x2 /= (double)sample_number;
s.sd = sqrt(x2-pow(s.avg, 2.0));
// Quartiles
vector<double>::iterator firstDatum = dataPoints.begin();
vector<double>::iterator lastDatum = dataPoints.end();
vector<double>::iterator q1Datum = firstDatum + (lastDatum - firstDatum) / 4;
vector<double>::iterator q2Datum = firstDatum + (lastDatum - firstDatum) / 2;
vector<double>::iterator q3Datum = firstDatum + (lastDatum - firstDatum) * 3 / 4;
nth_element(firstDatum, q1Datum, lastDatum);
nth_element(firstDatum, q2Datum, lastDatum);
nth_element(firstDatum, q3Datum, lastDatum);
s.q1 = *q1Datum;
s.q2 = *q2Datum;
s.q3 = *q3Datum;
}else{
s.avg = 0;
s.sd = 0;
s.q1 = 0;
s.q2 = 0;
s.q3 = 0;
}
// Report summary
if(reportSummary==0) return s;
label = new char[LARGEST_LABEL];
text = new char[LARGEST_LINE];
sep = (char *)"\t";
sprintf(label, (samplepar.portion_as_label ? "%.6f" : "%.0f"), samplepar.portion*(samplepar.portion_as_label? 1.0 : samplepar.total_reads ));
sprintf(text, "%s%s%.5f%s%.5f%s%.5f%s%.5f%s%.5f",
label, sep, s.avg, sep, s.sd, sep, s.q1, sep, s.q2, sep, s.q3);
if(reportSummary==1) {
fprintf(summaryh, "%s%s\n", header, text);
fclose(summaryh);
} else if(reportSummary==2) printf("%s%s\n", header, text);
return s;
}
<commit_msg>removed kmer size for alignment mode<commit_after>// nonpareil_sampling - Part of the nonpareil package
// @author Luis M. Rodriguez-R <lmrodriguezr at gmail dot com>
// @license artistic 2.0
// @version 1.0
#define _MULTI_THREADED
#include <iostream>
#include <fstream>
#include <unistd.h>
#include <stdio.h>
#include <math.h>
#include <pthread.h>
#include <vector>
#include <algorithm>
#include "universal.h"
// #include "multinode.h"
#include "sequence.h"
#include "nonpareil_sampling.h"
//extern int processID;
//extern int processes;
#define LARGEST_LABEL 128
#define LARGEST_LINE 2048
using namespace std;
int nonpareil_sample_portion(double *&result, int threads, samplepar_t samplepar){
// Vars
if(samplepar.replicates<threads) threads = samplepar.replicates;
samplejob_t samplejob[threads];
pthread_t thread[threads];
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int rc, samples_per_thr, launched_replicates=0;
// Blank result
result = new double[samplepar.replicates];
for(int a=0; a<samplepar.replicates; a++) result[a] = 0.0;
// Set sample
//if(processID==0)
say("4sfs^", "Sampling at ", samplepar.portion*100, "%");
samples_per_thr = (int)ceil((double)samplepar.replicates/(double)threads);
threads = (int)ceil((double)samplepar.replicates/samples_per_thr);
// Launch samplings
for(int thr=0; thr<threads; thr++){
samplejob[thr].id = thr;
samplejob[thr].from_in_result = thr*samples_per_thr; // Zero-based index to start at in the results array
samplejob[thr].number = samplejob[thr].from_in_result+samples_per_thr > samplepar.replicates ? samplepar.replicates-samplejob[thr].from_in_result : samples_per_thr;
samplejob[thr].samplepar = samplepar;
samplejob[thr].result = &result;
samplejob[thr].mutex = &mutex;
launched_replicates += samplejob[thr].number;
if((rc=pthread_create(&thread[thr], NULL, &nonpareil_sample_portion_thr, (void *)&samplejob[thr] )))
error("Thread creation failed", (char)rc);
}
// Gather jobs
for(int thr=0; thr<threads; thr++){
//if(thr%processes == processID)
pthread_join(thread[thr], NULL);
}
// Return
return launched_replicates;
}
void *nonpareil_sample_portion_thr(void *samplejob_ref){
// Vars
samplejob_t *samplejob = (samplejob_t *)samplejob_ref;
int *&mates_ref = *samplejob->samplepar.mates, n;
double *result_cp = new double[samplejob->number], p, p_gt_0;
// Sample
for(int i=0; i<samplejob->number; i++){
int found=0, sample_size=0;
// For each read with known number of mates
for(int j=0; j<samplejob->samplepar.mates_size; j++){
// Include the read in the sample?
if(((double)rand()/(double)RAND_MAX) < samplejob->samplepar.portion){
sample_size++;
// Does the sample contain at least one mate?
// if((double)rand()/(double)RAND_MAX < 1.0-pow(1-samplejob->samplepar.portion, mates_ref[j]-1)) found++;
n=(int)floor((samplejob->samplepar.total_reads)*samplejob->samplepar.portion)-1; // -1 because we exclude the query read from the sample
if(n<0) n=0;
p=(double)(mates_ref[j]-1.0)/(samplejob->samplepar.total_reads-1.0); // Again, -1 in both terms because of the query read
p_gt_0 = 1.0 - pow(1.0-p, n);
//cout << "n=" << n << ", p=" << p << "P(X>0)=" << p_gt_0 << endl;
if((double)rand()/(double)RAND_MAX < p_gt_0) found++;
}
}
result_cp[i] = sample_size==0 ? 0.0 : (double)found/(double)sample_size;
}
// Transfer results to the external vector
pthread_mutex_lock( samplejob->mutex );
double *&result_ref = *samplejob->result;
// v--> position + first of the thread
for(int i=0; i<samplejob->number; i++) result_ref[i + samplejob->from_in_result] = result_cp[i];
pthread_mutex_unlock( samplejob->mutex );
return (void *)0;
}
sample_t nonpareil_sample_summary(double *&sample_result, int sample_number, char *alldata, char *outfile, samplepar_t samplepar){
// Vars
double x2=0;
vector<double> dataPoints;
FILE *alldatah, *summaryh;
bool reportAllData=false;
int reportSummary=0;
char *text, *label, *sep, *header=(char*)"";
sample_t s;
s.portion = samplepar.portion;
// File handlers
if(alldata && strlen(alldata)>0){
alldatah = fopen(alldata, (samplepar.portion==samplepar.portion_min ? "w" : "a+"));
if(alldatah==NULL) error("I cannot write on all-data file", alldata);
reportAllData=true;
}
if(strlen(outfile)>0 && strcmp(outfile, "-")!=0){
summaryh = fopen(outfile, (samplepar.portion==samplepar.portion_min ? "w" : "a+"));
if(summaryh==NULL) error("I cannot write on summary file", outfile);
reportSummary=1;
}else if(strlen(outfile)>0){
reportSummary=2;
}
if(samplepar.portion==samplepar.portion_min){
header = new char[LARGEST_LINE];
if(samplepar.type == 1) {
sprintf(header, "# @impl: Nonpareil\n# @version: %.2f\n# @maxL: %d\n# @L: %.3f\n# @R: %llu\n# @overlap: %.2f\n# @divide: %.2f\n",
samplepar.k,
samplepar.np_version,
samplepar.max_read_len,
samplepar.avg_read_len,
samplepar.total_reads,
samplepar.seq_overlap*100.0,
samplepar.divide);
}
else if(samplepar.type == 2) {
sprintf(header, "# @ksize: %d\n# @impl: Nonpareil\n# @version: %.2f\n# @L: %.3f\n# @AL: %.3f\n# @R: %llu\n# @overlap: %.2f\n# @divide: %.2f\n",
samplepar.k,
samplepar.np_version,
samplepar.avg_read_len,
samplepar.adj_avg_read_len,
samplepar.total_reads,
samplepar.seq_overlap*100.0,
samplepar.divide);
}
}
if(sample_number>0){
// Average & SD
s.avg = s.sd = x2 = 0.0;
for(int a=0; a<sample_number; a++){
s.avg += (double)sample_result[a];
x2 += pow((double)sample_result[a], 2.0);
dataPoints.push_back(sample_result[a]);
if(reportAllData) fprintf(alldatah, "%.2f\t%d\t%.10f\n", samplepar.portion, a, sample_result[a]);
}
fclose(alldatah);
s.avg /= (double)sample_number;
x2 /= (double)sample_number;
s.sd = sqrt(x2-pow(s.avg, 2.0));
// Quartiles
vector<double>::iterator firstDatum = dataPoints.begin();
vector<double>::iterator lastDatum = dataPoints.end();
vector<double>::iterator q1Datum = firstDatum + (lastDatum - firstDatum) / 4;
vector<double>::iterator q2Datum = firstDatum + (lastDatum - firstDatum) / 2;
vector<double>::iterator q3Datum = firstDatum + (lastDatum - firstDatum) * 3 / 4;
nth_element(firstDatum, q1Datum, lastDatum);
nth_element(firstDatum, q2Datum, lastDatum);
nth_element(firstDatum, q3Datum, lastDatum);
s.q1 = *q1Datum;
s.q2 = *q2Datum;
s.q3 = *q3Datum;
}else{
s.avg = 0;
s.sd = 0;
s.q1 = 0;
s.q2 = 0;
s.q3 = 0;
}
// Report summary
if(reportSummary==0) return s;
label = new char[LARGEST_LABEL];
text = new char[LARGEST_LINE];
sep = (char *)"\t";
sprintf(label, (samplepar.portion_as_label ? "%.6f" : "%.0f"), samplepar.portion*(samplepar.portion_as_label? 1.0 : samplepar.total_reads ));
sprintf(text, "%s%s%.5f%s%.5f%s%.5f%s%.5f%s%.5f",
label, sep, s.avg, sep, s.sd, sep, s.q1, sep, s.q2, sep, s.q3);
if(reportSummary==1) {
fprintf(summaryh, "%s%s\n", header, text);
fclose(summaryh);
} else if(reportSummary==2) printf("%s%s\n", header, text);
return s;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.