text
stringlengths 54
60.6k
|
---|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SlsPageEnumeration.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-09 06:21: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
*
************************************************************************/
#ifndef SD_SLIDESORTER_PAGE_ENUMERATION_HXX
#define SD_SLIDESORTER_PAGE_ENUMERATION_HXX
#include "pres.hxx"
#include "memory"
#include "SlsEnumeration.hxx"
namespace sd { namespace slidesorter { namespace model {
class PageDescriptor;
class SlideSorterModel;
/** Public class of page enumerations that delegates its calls to an
implementation object that can filter pages by using one of several
predicates.
*/
class PageEnumeration
: public Enumeration<PageDescriptor>
{
public:
/** The type of the predicate that is used to filter pages from the set
of all pages provided by the slide sorter model:
PET_ALL enumerates all pages.
PET_SELECTED gives access to only the selected pages.
PET_VISIBLE gives access to only the visible pages.
*/
enum PageEnumerationType { PET_ALL, PET_SELECTED, PET_VISIBLE };
/** Create a new page enumeration that enumerates a subset of the pages
of the given model.
@param rModel
The new page enumeration enumerates the pages of this model.
@param eType
This value determines which predicate/filter to use. See the
PageEnumerationType enum above for a description of the
available values.
*/
static PageEnumeration Create (
const SlideSorterModel& rModel,
PageEnumerationType eType);
/** This constructor expects an implementation object that implements
the predicate that filters the pages. If you do not know where to
get such an object from you may want to use the static Create()
factory method for creating a page enumeration. Otherwise you may
want to use that method as well.
*/
PageEnumeration (::std::auto_ptr<Enumeration<PageDescriptor> > pImpl);
/** This copy constructor creates a copy of the given enumeration. This
new enumeration points to the same element as the given one.
*/
PageEnumeration (const PageEnumeration& rEnumeration);
/** Create a new enumeration object. The ownership of the
implementation object goes to the new object. Use this copy
constructor only when you know what you are doing. When in doubt,
use the one argument version.
@param bCloneImpl
When <TRUE/> is given this constructor behaves exactly like its
one argument version. When <FALSE/> is given then the
implementation object is not copied but moved from the given
enumeration to the newly created one. The given enumeration
thus becomes empty.
*/
PageEnumeration (PageEnumeration& rEnumeration, bool bCloneImpl);
/** Create and return an exact copy of the called object.
*/
virtual PageEnumeration* Clone (void);
PageEnumeration& operator= (const PageEnumeration& rEnumeration);
/** Return <TRUE/> when the enumeration has more elements, i.e. it is
save to call GetNextElement() at least one more time.
*/
virtual bool HasMoreElements (void) const;
/** Return the next element of the enumeration. Call the
HasMoreElements() before to make sure that there exists at least one
more element. Calling this method with HasMoreElements() returning
<FALSE/> is an error.
*/
virtual PageDescriptor& GetNextElement (void);
/** Rewind the enumeration so that the next call to GetNextElement()
will return its first element.
*/
virtual void Rewind (void);
private:
/// Implementation object.
::std::auto_ptr<Enumeration<PageDescriptor> > mpImpl;
// Default constructor not implemented.
PageEnumeration (void);
};
} } } // end of namespace ::sd::slidesorter::model
#endif
<commit_msg>INTEGRATION: CWS impress89 (1.3.156); FILE MERGED 2006/03/20 10:52:55 af 1.3.156.1: #132646# Using shared_ptr to slidesorter PageDescriptor.<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: SlsPageEnumeration.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: vg $ $Date: 2006-04-06 16:24:26 $
*
* 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 SD_SLIDESORTER_PAGE_ENUMERATION_HXX
#define SD_SLIDESORTER_PAGE_ENUMERATION_HXX
#include "pres.hxx"
#include "memory"
#include "model/SlsEnumeration.hxx"
#include "model/SlsSharedPageDescriptor.hxx"
namespace sd { namespace slidesorter { namespace model {
class SlideSorterModel;
/** Public class of page enumerations that delegates its calls to an
implementation object that can filter pages by using one of several
predicates.
*/
class PageEnumeration
: public Enumeration<SharedPageDescriptor>
{
public:
/** The type of the predicate that is used to filter pages from the set
of all pages provided by the slide sorter model:
PET_ALL enumerates all pages.
PET_SELECTED gives access to only the selected pages.
PET_VISIBLE gives access to only the visible pages.
*/
enum PageEnumerationType { PET_ALL, PET_SELECTED, PET_VISIBLE };
/** Create a new page enumeration that enumerates a subset of the pages
of the given model.
@param rModel
The new page enumeration enumerates the pages of this model.
@param eType
This value determines which predicate/filter to use. See the
PageEnumerationType enum above for a description of the
available values.
*/
static PageEnumeration Create (
const SlideSorterModel& rModel,
PageEnumerationType eType);
/** This constructor expects an implementation object that implements
the predicate that filters the pages. If you do not know where to
get such an object from you may want to use the static Create()
factory method for creating a page enumeration. Otherwise you may
want to use that method as well.
*/
PageEnumeration (::std::auto_ptr<Enumeration<SharedPageDescriptor> > pImpl);
/** This copy constructor creates a copy of the given enumeration. This
new enumeration points to the same element as the given one.
*/
PageEnumeration (const PageEnumeration& rEnumeration);
/** Create a new enumeration object. The ownership of the
implementation object goes to the new object. Use this copy
constructor only when you know what you are doing. When in doubt,
use the one argument version.
@param bCloneImpl
When <TRUE/> is given this constructor behaves exactly like its
one argument version. When <FALSE/> is given then the
implementation object is not copied but moved from the given
enumeration to the newly created one. The given enumeration
thus becomes empty.
*/
PageEnumeration (PageEnumeration& rEnumeration, bool bCloneImpl);
/** Create and return an exact copy of the called object.
*/
virtual ::std::auto_ptr<Enumeration<SharedPageDescriptor> > Clone (void);
PageEnumeration& operator= (const PageEnumeration& rEnumeration);
/** Return <TRUE/> when the enumeration has more elements, i.e. it is
save to call GetNextElement() at least one more time.
*/
virtual bool HasMoreElements (void) const;
/** Return the next element of the enumeration. Call the
HasMoreElements() before to make sure that there exists at least one
more element. Calling this method with HasMoreElements() returning
<FALSE/> is an error.
*/
virtual SharedPageDescriptor GetNextElement (void);
/** Rewind the enumeration so that the next call to GetNextElement()
will return its first element.
*/
virtual void Rewind (void);
private:
/// Implementation object.
::std::auto_ptr<Enumeration<SharedPageDescriptor> > mpImpl;
// Default constructor not implemented.
PageEnumeration (void);
};
} } } // end of namespace ::sd::slidesorter::model
#endif
<|endoftext|> |
<commit_before>
#define BOOST_TEST_MODULE test_standard_license
#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
#include <licensecc/licensecc.h>
#include <licensecc_properties_test.h>
#include <licensecc_properties.h>
#include "../../src/library/ini/SimpleIni.h"
#include "generate-license.h"
#include "../../src/library/base/file_utils.hpp"
using namespace std;
namespace fs = boost::filesystem;
namespace license {
namespace test {
/**
* Test a generic license with no expiry neither client id. The license is read from file
*/
BOOST_AUTO_TEST_CASE(test_generic_license_read_file) {
const vector<string> extraArgs;
const string licLocation = generate_license("standard_license", extraArgs);
/* */
LicenseInfo license;
LicenseLocation location = {LICENSE_PATH};
std::copy(licLocation.begin(), licLocation.end(), location.licenseData);
const LCC_EVENT_TYPE result = acquire_license(nullptr, &location, &license);
BOOST_CHECK_EQUAL(result, LICENSE_OK);
BOOST_CHECK_EQUAL(license.has_expiry, false);
BOOST_CHECK_EQUAL(license.linked_to_pc, false);
}
/**
* Test a generic license with no expiry neither client id. The license is passed in trhough the licenseData structure.
*/
BOOST_AUTO_TEST_CASE(test_read_license_data) {
const vector<string> extraArgs;
const fs::path licLocation = fs::path(generate_license("standard_license1", extraArgs));
const string licLocationStr = licLocation.string();
string license_data = get_file_contents(licLocationStr.c_str(), 65536);
LicenseInfo license;
LicenseLocation location = {LICENSE_PLAIN_DATA};
std::copy(license_data.begin(), license_data.end(), location.licenseData);
const LCC_EVENT_TYPE result = acquire_license(nullptr, &location, &license);
BOOST_CHECK_EQUAL(result, LICENSE_OK);
BOOST_CHECK_EQUAL(license.has_expiry, false);
BOOST_CHECK_EQUAL(license.linked_to_pc, false);
}
/**
* Pass the license data to the application.
*/
/* lccgen bug #10 parameter -b is ignored.
BOOST_AUTO_TEST_CASE(base64_encoded) {
const string licLocation("standard_b64.lic");
vector<string> extraArgs;
extraArgs.push_back("-b");
const string lic_location = generate_license(licLocation, extraArgs);
const string license_data(license::get_file_contents(lic_location.c_str(), 65536));
LicenseInfo license;
LicenseLocation licenseLocation;
licenseLocation.license_data_type = LICENSE_ENCODED;
std::copy(license_data.begin(), license_data.end(), licenseLocation.licenseData);
const LCC_EVENT_TYPE result = acquire_license(nullptr, &licenseLocation, &license);
BOOST_CHECK_EQUAL(result, LCC_EVENT_TYPE::LICENSE_OK);
BOOST_CHECK_EQUAL(license.has_expiry, false);
BOOST_CHECK_EQUAL(license.linked_to_pc, false);
}
*/
BOOST_AUTO_TEST_CASE(multiple_features) {
vector<string> extraArgs;
extraArgs.push_back("-f");
extraArgs.push_back("feature1,feature2");
const fs::path licLocation = fs::path(generate_license("multi_feature", extraArgs));
const string licLocationStr = licLocation.string();
string license_data = get_file_contents(licLocationStr.c_str(), 65536);
LicenseInfo license;
LicenseLocation location = {LICENSE_PLAIN_DATA};
std::copy(license_data.begin(), license_data.end(), location.licenseData);
CallerInformations callInfo;
strcpy(callInfo.feature_name, "feature1");
callInfo.magic = 0;
callInfo.version[0] = '\0';
LCC_EVENT_TYPE result = acquire_license(&callInfo, &location, &license);
BOOST_CHECK_EQUAL(result, LCC_EVENT_TYPE::LICENSE_OK);
strcpy(callInfo.feature_name, "feature2");
result = acquire_license(&callInfo, &location, &license);
BOOST_CHECK_EQUAL(result, LCC_EVENT_TYPE::LICENSE_OK);
strcpy(callInfo.feature_name, "feature3");
result = acquire_license(&callInfo, &location, &license);
BOOST_CHECK_EQUAL(result, LCC_EVENT_TYPE::PRODUCT_NOT_LICENSED);
}
//
// BOOST_AUTO_TEST_CASE( hw_identifier ) {
// const string licLocation(PROJECT_TEST_TEMP_DIR "/hw_identifier.lic");
// const vector<string> extraArgs = { "-s", "Jaaa-aaaa-MG9F-ZhB1" };
// generate_license(licLocation, extraArgs);
//
// LicenseInfo license;
// LicenseLocation licenseLocation;
// licenseLocation.licenseFileLocation = licLocation.c_str();
// licenseLocation.licenseData = "";
// const EVENT_TYPE result = acquire_license("TEST", &licenseLocation,
// &license);
// BOOST_CHECK_EQUAL(result, IDENTIFIERS_MISMATCH);
// BOOST_CHECK_EQUAL(license.has_expiry, false);
// BOOST_CHECK_EQUAL(license.linked_to_pc, true);
//}
} // namespace test
} // namespace license
<commit_msg>missing commit<commit_after>
#define BOOST_TEST_MODULE test_standard_license
#include <boost/test/unit_test.hpp>
#include <boost/filesystem.hpp>
#include <licensecc/licensecc.h>
#include <licensecc_properties_test.h>
#include <licensecc_properties.h>
#include "../../src/library/ini/SimpleIni.h"
#include "generate-license.h"
#include "../../src/library/base/file_utils.hpp"
using namespace std;
namespace fs = boost::filesystem;
namespace license {
namespace test {
/**
* Test a generic license with no expiry neither client id. The license is read from file
*/
BOOST_AUTO_TEST_CASE(test_generic_license_read_file) {
const vector<string> extraArgs;
const string licLocation = generate_license("standard_license", extraArgs);
/* */
LicenseInfo license;
LicenseLocation location = {LICENSE_PATH};
std::copy(licLocation.begin(), licLocation.end(), location.licenseData);
const LCC_EVENT_TYPE result = acquire_license(nullptr, &location, &license);
BOOST_CHECK_EQUAL(result, LICENSE_OK);
BOOST_CHECK_EQUAL(license.has_expiry, false);
BOOST_CHECK_EQUAL(license.linked_to_pc, false);
}
/**
* Test a generic license with no expiry neither client id. The license is passed in trhough the licenseData structure.
*/
BOOST_AUTO_TEST_CASE(test_read_license_data) {
const vector<string> extraArgs;
const fs::path licLocation = fs::path(generate_license("standard_license1", extraArgs));
const string licLocationStr = licLocation.string();
string license_data = get_file_contents(licLocationStr.c_str(), 65536);
LicenseInfo license;
LicenseLocation location = {LICENSE_PLAIN_DATA};
std::copy(license_data.begin(), license_data.end(), location.licenseData);
const LCC_EVENT_TYPE result = acquire_license(nullptr, &location, &license);
BOOST_CHECK_EQUAL(result, LICENSE_OK);
BOOST_CHECK_EQUAL(license.has_expiry, false);
BOOST_CHECK_EQUAL(license.linked_to_pc, false);
}
/**
* Pass the license data to the application.
*/
/* lccgen bug #10 parameter -b is ignored.
BOOST_AUTO_TEST_CASE(base64_encoded) {
const string licLocation("standard_b64.lic");
vector<string> extraArgs;
extraArgs.push_back("-b");
const string lic_location = generate_license(licLocation, extraArgs);
const string license_data(license::get_file_contents(lic_location.c_str(), 65536));
LicenseInfo license;
LicenseLocation licenseLocation;
licenseLocation.license_data_type = LICENSE_ENCODED;
std::copy(license_data.begin(), license_data.end(), licenseLocation.licenseData);
const LCC_EVENT_TYPE result = acquire_license(nullptr, &licenseLocation, &license);
BOOST_CHECK_EQUAL(result, LCC_EVENT_TYPE::LICENSE_OK);
BOOST_CHECK_EQUAL(license.has_expiry, false);
BOOST_CHECK_EQUAL(license.linked_to_pc, false);
}
*/
BOOST_AUTO_TEST_CASE(multiple_features) {
vector<string> extraArgs;
extraArgs.push_back("-f");
extraArgs.push_back(LCC_PROJECT_NAME ",feature1,feature2");
const fs::path licLocation = fs::path(generate_license("multi_feature", extraArgs));
const string licLocationStr = licLocation.string();
string license_data = get_file_contents(licLocationStr.c_str(), 65536);
LicenseInfo license;
LicenseLocation location = {LICENSE_PLAIN_DATA};
std::copy(license_data.begin(), license_data.end(), location.licenseData);
CallerInformations callInfo;
strcpy(callInfo.feature_name, "feature1");
callInfo.magic = 0;
callInfo.version[0] = '\0';
LCC_EVENT_TYPE result = acquire_license(&callInfo, &location, &license);
BOOST_CHECK_EQUAL(result, LCC_EVENT_TYPE::LICENSE_OK);
strcpy(callInfo.feature_name, "feature2");
result = acquire_license(&callInfo, &location, &license);
BOOST_CHECK_EQUAL(result, LCC_EVENT_TYPE::LICENSE_OK);
strcpy(callInfo.feature_name, "feature3");
result = acquire_license(&callInfo, &location, &license);
BOOST_CHECK_EQUAL(result, LCC_EVENT_TYPE::PRODUCT_NOT_LICENSED);
}
//
// BOOST_AUTO_TEST_CASE( hw_identifier ) {
// const string licLocation(PROJECT_TEST_TEMP_DIR "/hw_identifier.lic");
// const vector<string> extraArgs = { "-s", "Jaaa-aaaa-MG9F-ZhB1" };
// generate_license(licLocation, extraArgs);
//
// LicenseInfo license;
// LicenseLocation licenseLocation;
// licenseLocation.licenseFileLocation = licLocation.c_str();
// licenseLocation.licenseData = "";
// const EVENT_TYPE result = acquire_license("TEST", &licenseLocation,
// &license);
// BOOST_CHECK_EQUAL(result, IDENTIFIERS_MISMATCH);
// BOOST_CHECK_EQUAL(license.has_expiry, false);
// BOOST_CHECK_EQUAL(license.linked_to_pc, true);
//}
} // namespace test
} // namespace license
<|endoftext|> |
<commit_before>
#include <stdlib.h>
#include <vector>
#include <set>
#include <functional>
#include <opengm/graphicalmodel/graphicalmodel.hxx>
#include <opengm/operations/adder.hxx>
#include <opengm/operations/multiplier.hxx>
#include <opengm/operations/minimizer.hxx>
#include <opengm/operations/maximizer.hxx>
#include <opengm/inference/graphcut.hxx>
#include <opengm/unittests/blackboxtester.hxx>
#include <opengm/unittests/blackboxtests/blackboxtestgrid.hxx>
#include <opengm/unittests/blackboxtests/blackboxtestfull.hxx>
#include <opengm/unittests/blackboxtests/blackboxteststar.hxx>
#ifdef WITH_BOOST
# include <opengm/inference/auxiliary/minstcutboost.hxx>
#endif
#ifdef WITH_MAXFLOW
# include <opengm/inference/auxiliary/minstcutkolmogorov.hxx>
#endif
#ifdef WITH_MAXFLOW_IBFS
# include <opengm/inference/auxiliary/minstcutibfs.hxx>
#endif
int main() {
typedef opengm::GraphicalModel<float, opengm::Adder> GraphicalModelType;
typedef opengm::GraphicalModel<float, opengm::Adder,
opengm::ExplicitFunction<float,unsigned short, unsigned char>,
opengm::DiscreteSpace<unsigned short, unsigned char> > SumGmType2;
typedef opengm::BlackBoxTestGrid<SumGmType2> SumGridTest2;
typedef opengm::BlackBoxTestFull<SumGmType2> SumFullTest2;
typedef opengm::BlackBoxTestStar<SumGmType2> SumStarTest2;
typedef opengm::BlackBoxTestGrid<GraphicalModelType> GridTest;
typedef opengm::BlackBoxTestFull<GraphicalModelType> FullTest;
typedef opengm::BlackBoxTestStar<GraphicalModelType> StarTest;
opengm::InferenceBlackBoxTester<SumGmType2> minTester2;
minTester2.addTest(new SumGridTest2(4, 4, 2, false, true, SumGridTest2::POTTS, opengm::OPTIMAL, 1));
opengm::InferenceBlackBoxTester<GraphicalModelType> minTester;
minTester.addTest(new GridTest(4, 4, 2, false, true, GridTest::POTTS, opengm::OPTIMAL, 1));
minTester.addTest(new GridTest(3, 3, 2, false, true, GridTest::POTTS, opengm::OPTIMAL, 3));
minTester.addTest(new GridTest(3, 3, 2, false, false,GridTest::POTTS, opengm::OPTIMAL, 3));
minTester.addTest(new StarTest(5, 2, false, true, StarTest::POTTS, opengm::OPTIMAL, 3));
minTester.addTest(new FullTest(5, 2, false, 3, FullTest::POTTS, opengm::OPTIMAL, 3));
opengm::InferenceBlackBoxTester<GraphicalModelType> maxTester;
maxTester.addTest(new GridTest(4, 4, 2, false, true, GridTest::IPOTTS, opengm::OPTIMAL, 1));
maxTester.addTest(new GridTest(3, 3, 2, false, true, GridTest::IPOTTS, opengm::OPTIMAL, 3));
maxTester.addTest(new GridTest(3, 3, 2, false, false,GridTest::IPOTTS, opengm::OPTIMAL, 3));
maxTester.addTest(new StarTest(5, 2, false, true, StarTest::IPOTTS, opengm::OPTIMAL, 3));
maxTester.addTest(new FullTest(5, 2, false, 3, FullTest::IPOTTS, opengm::OPTIMAL, 3));
std::cout << "Test Graphcut ..." << std::endl;
#ifdef WITH_MAXFLOW_IBFS
std::cout << " * Test Min-Sum with IBFS" << std::endl;
{
typedef opengm::external::MinSTCutIBFS<size_t, float> MinStCutType;
typedef opengm::GraphCut<GraphicalModelType, opengm::Minimizer, MinStCutType> MinGraphCut;
MinGraphCut::Parameter para;
minTester.test<MinGraphCut>(para);
}
std::cout << " * Test Min-Sum with IBFS (float,uint16,uint8) " << std::endl;
{
typedef opengm::external::MinSTCutIBFS<size_t, float> MinStCutType;
typedef opengm::GraphCut<SumGmType2, opengm::Minimizer, MinStCutType> MinGraphCut;
MinGraphCut::Parameter para;
minTester2.test<MinGraphCut>(para);
}
#endif
#ifdef WITH_MAXFLOW
std::cout << " * Test Min-Sum with Kolmogorov" << std::endl;
{
typedef opengm::external::MinSTCutKolmogorov<size_t, float> MinStCutType;
typedef opengm::GraphCut<GraphicalModelType, opengm::Minimizer, MinStCutType> MinGraphCut;
MinGraphCut::Parameter para;
minTester.test<MinGraphCut>(para);
}
std::cout << " * Test Min-Sum with Kolmogorov (float,uint16,uint8) " << std::endl;
{
typedef opengm::external::MinSTCutKolmogorov<size_t, float> MinStCutType;
typedef opengm::GraphCut<SumGmType2, opengm::Minimizer, MinStCutType> MinGraphCut;
MinGraphCut::Parameter para;
minTester2.test<MinGraphCut>(para);
}
#endif
#ifdef WITH_BOOST
std::cout << " * Test Min-Sum with BOOST-Push-Relabel" << std::endl;
{
typedef opengm::MinSTCutBoost<size_t, float, opengm::PUSH_RELABEL> MinStCutType;
typedef opengm::GraphCut<GraphicalModelType, opengm::Minimizer, MinStCutType> MinGraphCut;
MinGraphCut::Parameter para;
minTester.test<MinGraphCut>(para);
}
std::cout << " * Test Min-Sum with Interegr-BOOST-Push-Relabel" << std::endl;
{
typedef opengm::MinSTCutBoost<size_t, long, opengm::PUSH_RELABEL> MinStCutType;
typedef opengm::GraphCut<GraphicalModelType, opengm::Minimizer, MinStCutType> MinGraphCut;
MinGraphCut::Parameter para(1000000);
minTester.test<MinGraphCut>(para);
}
std::cout << " * Test Min-Sum with BOOST-Edmonds-Karp" << std::endl;
{
typedef opengm::MinSTCutBoost<size_t, float, opengm::EDMONDS_KARP> MinStCutType;
typedef opengm::GraphCut<GraphicalModelType, opengm::Minimizer, MinStCutType> MinGraphCut;
MinGraphCut::Parameter para;
minTester.test<MinGraphCut>(para);
}
std::cout << " * Test Min-Sum with BOOST-Kolmogorov" << std::endl;
{
typedef opengm::MinSTCutBoost<size_t, float, opengm::KOLMOGOROV> MinStCutType;
typedef opengm::GraphCut<GraphicalModelType, opengm::Minimizer, MinStCutType> MinGraphCut;
MinGraphCut::Parameter para;
minTester.test<MinGraphCut>(para);
}
#endif
#ifdef WITH_MAXFLOW_IBFS
std::cout << " * Test Max-Sum with IBFS" << std::endl;
{
typedef opengm::external::MinSTCutIBFS<size_t, float> MinStCutType;
typedef opengm::GraphCut<GraphicalModelType, opengm::Maximizer, MinStCutType> MaxGraphCut;
MaxGraphCut::Parameter para;
maxTester.test<MaxGraphCut>(para);
}
#endif
#ifdef WITH_MAXFLOW
std::cout << " * Test Max-Sum with Kolmogorov" << std::endl;
{
typedef opengm::external::MinSTCutKolmogorov<size_t, float> MinStCutType;
typedef opengm::GraphCut<GraphicalModelType, opengm::Maximizer, MinStCutType> MaxGraphCut;
MaxGraphCut::Parameter para;
maxTester.test<MaxGraphCut>(para);
}
#endif
#ifdef WITH_BOOST
std::cout << " * Test Max-Sum with BOOST-Push-Relabel" << std::endl;
{
typedef opengm::MinSTCutBoost<size_t, float, opengm::PUSH_RELABEL> MinStCutType;
typedef opengm::GraphCut<GraphicalModelType, opengm::Maximizer, MinStCutType> MaxGraphCut;
MaxGraphCut::Parameter para;
maxTester.test<MaxGraphCut>(para);
}
std::cout << " * Test Max-Sum with Integer-BOOST-Push-Relabel" << std::endl;
{
typedef opengm::MinSTCutBoost<size_t, int, opengm::PUSH_RELABEL> MinStCutType;
typedef opengm::GraphCut<GraphicalModelType, opengm::Maximizer, MinStCutType> MaxGraphCut;
MaxGraphCut::Parameter para(0.000000);
maxTester.test<MaxGraphCut>(para);
}
std::cout << " * Test Max-Sum with BOOST-Edmonds-Karp" << std::endl;
{
typedef opengm::MinSTCutBoost<size_t, float, opengm::EDMONDS_KARP> MinStCutType;
typedef opengm::GraphCut<GraphicalModelType, opengm::Maximizer, MinStCutType> MaxGraphCut;
MaxGraphCut::Parameter para;
maxTester.test<MaxGraphCut>(para);
}
std::cout << " * Test Max-Sum with BOOST-Kolmogorov" << std::endl;
{
typedef opengm::MinSTCutBoost<size_t, float, opengm::KOLMOGOROV> MinStCutType;
typedef opengm::GraphCut<GraphicalModelType, opengm::Maximizer, MinStCutType> MaxGraphCut;
MaxGraphCut::Parameter para;
maxTester.test<MaxGraphCut>(para);
}
#endif
return 0;
}
<commit_msg>bugfix typo in graphcut-test<commit_after>
#include <stdlib.h>
#include <vector>
#include <set>
#include <functional>
#include <opengm/graphicalmodel/graphicalmodel.hxx>
#include <opengm/operations/adder.hxx>
#include <opengm/operations/multiplier.hxx>
#include <opengm/operations/minimizer.hxx>
#include <opengm/operations/maximizer.hxx>
#include <opengm/inference/graphcut.hxx>
#include <opengm/unittests/blackboxtester.hxx>
#include <opengm/unittests/blackboxtests/blackboxtestgrid.hxx>
#include <opengm/unittests/blackboxtests/blackboxtestfull.hxx>
#include <opengm/unittests/blackboxtests/blackboxteststar.hxx>
#ifdef WITH_BOOST
# include <opengm/inference/auxiliary/minstcutboost.hxx>
#endif
#ifdef WITH_MAXFLOW
# include <opengm/inference/auxiliary/minstcutkolmogorov.hxx>
#endif
#ifdef WITH_MAXFLOW_IBFS
# include <opengm/inference/auxiliary/minstcutibfs.hxx>
#endif
int main() {
typedef opengm::GraphicalModel<float, opengm::Adder> GraphicalModelType;
typedef opengm::GraphicalModel<float, opengm::Adder,
opengm::ExplicitFunction<float,unsigned short, unsigned char>,
opengm::DiscreteSpace<unsigned short, unsigned char> > SumGmType2;
typedef opengm::BlackBoxTestGrid<SumGmType2> SumGridTest2;
typedef opengm::BlackBoxTestFull<SumGmType2> SumFullTest2;
typedef opengm::BlackBoxTestStar<SumGmType2> SumStarTest2;
typedef opengm::BlackBoxTestGrid<GraphicalModelType> GridTest;
typedef opengm::BlackBoxTestFull<GraphicalModelType> FullTest;
typedef opengm::BlackBoxTestStar<GraphicalModelType> StarTest;
opengm::InferenceBlackBoxTester<SumGmType2> minTester2;
minTester2.addTest(new SumGridTest2(4, 4, 2, false, true, SumGridTest2::POTTS, opengm::OPTIMAL, 1));
opengm::InferenceBlackBoxTester<GraphicalModelType> minTester;
minTester.addTest(new GridTest(4, 4, 2, false, true, GridTest::POTTS, opengm::OPTIMAL, 1));
minTester.addTest(new GridTest(3, 3, 2, false, true, GridTest::POTTS, opengm::OPTIMAL, 3));
minTester.addTest(new GridTest(3, 3, 2, false, false,GridTest::POTTS, opengm::OPTIMAL, 3));
minTester.addTest(new StarTest(5, 2, false, true, StarTest::POTTS, opengm::OPTIMAL, 3));
minTester.addTest(new FullTest(5, 2, false, 3, FullTest::POTTS, opengm::OPTIMAL, 3));
opengm::InferenceBlackBoxTester<GraphicalModelType> maxTester;
maxTester.addTest(new GridTest(4, 4, 2, false, true, GridTest::IPOTTS, opengm::OPTIMAL, 1));
maxTester.addTest(new GridTest(3, 3, 2, false, true, GridTest::IPOTTS, opengm::OPTIMAL, 3));
maxTester.addTest(new GridTest(3, 3, 2, false, false,GridTest::IPOTTS, opengm::OPTIMAL, 3));
maxTester.addTest(new StarTest(5, 2, false, true, StarTest::IPOTTS, opengm::OPTIMAL, 3));
maxTester.addTest(new FullTest(5, 2, false, 3, FullTest::IPOTTS, opengm::OPTIMAL, 3));
std::cout << "Test Graphcut ..." << std::endl;
#ifdef WITH_MAXFLOW_IBFS
std::cout << " * Test Min-Sum with IBFS" << std::endl;
{
typedef opengm::external::MinSTCutIBFS<size_t, float> MinStCutType;
typedef opengm::GraphCut<GraphicalModelType, opengm::Minimizer, MinStCutType> MinGraphCut;
MinGraphCut::Parameter para;
minTester.test<MinGraphCut>(para);
}
std::cout << " * Test Min-Sum with IBFS (float,uint16,uint8) " << std::endl;
{
typedef opengm::external::MinSTCutIBFS<size_t, float> MinStCutType;
typedef opengm::GraphCut<SumGmType2, opengm::Minimizer, MinStCutType> MinGraphCut;
MinGraphCut::Parameter para;
minTester2.test<MinGraphCut>(para);
}
#endif
#ifdef WITH_MAXFLOW
std::cout << " * Test Min-Sum with Kolmogorov" << std::endl;
{
typedef opengm::external::MinSTCutKolmogorov<size_t, float> MinStCutType;
typedef opengm::GraphCut<GraphicalModelType, opengm::Minimizer, MinStCutType> MinGraphCut;
MinGraphCut::Parameter para;
minTester.test<MinGraphCut>(para);
}
std::cout << " * Test Min-Sum with Kolmogorov (float,uint16,uint8) " << std::endl;
{
typedef opengm::external::MinSTCutKolmogorov<size_t, float> MinStCutType;
typedef opengm::GraphCut<SumGmType2, opengm::Minimizer, MinStCutType> MinGraphCut;
MinGraphCut::Parameter para;
minTester2.test<MinGraphCut>(para);
}
#endif
#ifdef WITH_BOOST
std::cout << " * Test Min-Sum with BOOST-Push-Relabel" << std::endl;
{
typedef opengm::MinSTCutBoost<size_t, float, opengm::PUSH_RELABEL> MinStCutType;
typedef opengm::GraphCut<GraphicalModelType, opengm::Minimizer, MinStCutType> MinGraphCut;
MinGraphCut::Parameter para;
minTester.test<MinGraphCut>(para);
}
std::cout << " * Test Min-Sum with Interegr-BOOST-Push-Relabel" << std::endl;
{
typedef opengm::MinSTCutBoost<size_t, long, opengm::PUSH_RELABEL> MinStCutType;
typedef opengm::GraphCut<GraphicalModelType, opengm::Minimizer, MinStCutType> MinGraphCut;
MinGraphCut::Parameter para(1000000);
minTester.test<MinGraphCut>(para);
}
std::cout << " * Test Min-Sum with BOOST-Edmonds-Karp" << std::endl;
{
typedef opengm::MinSTCutBoost<size_t, float, opengm::EDMONDS_KARP> MinStCutType;
typedef opengm::GraphCut<GraphicalModelType, opengm::Minimizer, MinStCutType> MinGraphCut;
MinGraphCut::Parameter para;
minTester.test<MinGraphCut>(para);
}
std::cout << " * Test Min-Sum with BOOST-Kolmogorov" << std::endl;
{
typedef opengm::MinSTCutBoost<size_t, float, opengm::KOLMOGOROV> MinStCutType;
typedef opengm::GraphCut<GraphicalModelType, opengm::Minimizer, MinStCutType> MinGraphCut;
MinGraphCut::Parameter para;
minTester.test<MinGraphCut>(para);
}
#endif
#ifdef WITH_MAXFLOW_IBFS
std::cout << " * Test Max-Sum with IBFS" << std::endl;
{
typedef opengm::external::MinSTCutIBFS<size_t, float> MinStCutType;
typedef opengm::GraphCut<GraphicalModelType, opengm::Maximizer, MinStCutType> MaxGraphCut;
MaxGraphCut::Parameter para;
maxTester.test<MaxGraphCut>(para);
}
#endif
#ifdef WITH_MAXFLOW
std::cout << " * Test Max-Sum with Kolmogorov" << std::endl;
{
typedef opengm::external::MinSTCutKolmogorov<size_t, float> MinStCutType;
typedef opengm::GraphCut<GraphicalModelType, opengm::Maximizer, MinStCutType> MaxGraphCut;
MaxGraphCut::Parameter para;
maxTester.test<MaxGraphCut>(para);
}
#endif
#ifdef WITH_BOOST
std::cout << " * Test Max-Sum with BOOST-Push-Relabel" << std::endl;
{
typedef opengm::MinSTCutBoost<size_t, float, opengm::PUSH_RELABEL> MinStCutType;
typedef opengm::GraphCut<GraphicalModelType, opengm::Maximizer, MinStCutType> MaxGraphCut;
MaxGraphCut::Parameter para;
maxTester.test<MaxGraphCut>(para);
}
std::cout << " * Test Max-Sum with Integer-BOOST-Push-Relabel" << std::endl;
{
typedef opengm::MinSTCutBoost<size_t, int, opengm::PUSH_RELABEL> MinStCutType;
typedef opengm::GraphCut<GraphicalModelType, opengm::Maximizer, MinStCutType> MaxGraphCut;
MaxGraphCut::Parameter para(1000000);
maxTester.test<MaxGraphCut>(para);
}
std::cout << " * Test Max-Sum with BOOST-Edmonds-Karp" << std::endl;
{
typedef opengm::MinSTCutBoost<size_t, float, opengm::EDMONDS_KARP> MinStCutType;
typedef opengm::GraphCut<GraphicalModelType, opengm::Maximizer, MinStCutType> MaxGraphCut;
MaxGraphCut::Parameter para;
maxTester.test<MaxGraphCut>(para);
}
std::cout << " * Test Max-Sum with BOOST-Kolmogorov" << std::endl;
{
typedef opengm::MinSTCutBoost<size_t, float, opengm::KOLMOGOROV> MinStCutType;
typedef opengm::GraphCut<GraphicalModelType, opengm::Maximizer, MinStCutType> MaxGraphCut;
MaxGraphCut::Parameter para;
maxTester.test<MaxGraphCut>(para);
}
#endif
return 0;
}
<|endoftext|> |
<commit_before>/*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2003 - 2007 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
/*
#ifdef WIN32
#define Sleep Sleep
#define INTERVAL 1000
#else
#define Sleep sleep
#define INTERVAL 1
#endif
*/
#ifdef ENABLE_INTEGRATION_TESTS
# include <cppunit/extensions/TestFactoryRegistry.h>
# include <cppunit/extensions/HelperMacros.h>
#include "base/fscapi.h"
#include "base/globalsdef.h"
#include "base/Log.h"
#include "base/util/StringBuffer.h"
#include "base/adapter/PlatformAdapter.h"
#include "client/DMTClientConfig.h"
#include "client/SyncClient.h"
#include "ConfigSyncSourceTest.h"
#include "client/ConfigSyncSource.h"
USE_NAMESPACE
ConfigSyncSourceTest::ConfigSyncSourceTest() {
LOG.setLogName("syncsourceconfig_tests.log");
LOG.reset();
}
DMTClientConfig* getConf(const char* name) {
const char *serverUrl = getenv("CLIENT_TEST_SERVER_URL");
const char *username = getenv("CLIENT_TEST_USERNAME");
const char *password = getenv("CLIENT_TEST_PASSWORD");
PlatformAdapter::init(name, true);
DMTClientConfig* config = new DMTClientConfig();
config->read();
DeviceConfig &dc(config->getDeviceConfig());
if (!strlen(dc.getDevID())) {
config->setClientDefaults();
config->setSourceDefaults("config");
StringBuffer devid("sc-pim-"); devid += name;
dc.setDevID(devid);
SyncSourceConfig* s = config->getSyncSourceConfig("config");
s->setEncoding("bin");
s->setURI("configuration");
s->setType("text/plain");
}
//set custom configuration
if(serverUrl) {
config->getAccessConfig().setSyncURL(serverUrl);
}
if(username) {
config->getAccessConfig().setUsername(username);
}
if(password) {
config->getAccessConfig().setPassword(password);
}
return config;
}
void ConfigSyncSourceTest::testConfigSource() {
// create the first configuration
DMTClientConfig* config1 = getConf("funambol_mappings_first");
SyncSourceConfig *csconfig = config1->getSyncSourceConfig("config");
//CPPUNIT_ASSERT(csconfig);
//ccontact1->setSync("refresh-from-client");
config1->save();
config1->open();
ConfigSyncSource source(TEXT("config"), "funambol_mappings_first", csconfig);
ArrayList properties;
StringBuffer pushstatus("./Push/Status");
StringBuffer filterstatus("./Email/FilterStatus");
StringBuffer emailaddress("./Email/Address");
StringBuffer displayname("./Email/DisplayName");
properties.add(pushstatus);
properties.add(filterstatus);
properties.add(emailaddress);
properties.add(displayname);
source.setConfigProperties(properties);
SyncSource* sources[2];
sources[0] = &source;
sources[1] = NULL;
SyncClient client;
int ret = 0;
ret = client.sync(*config1, sources);
CPPUNIT_ASSERT(!ret);
config1->save();
//Sleep(INTERVAL);
delete config1;
}
#endif // ENABLE_INTEGRATION_TESTS
<commit_msg>corrected config path<commit_after>/*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2003 - 2007 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* 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 Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
/*
#ifdef WIN32
#define Sleep Sleep
#define INTERVAL 1000
#else
#define Sleep sleep
#define INTERVAL 1
#endif
*/
#ifdef ENABLE_INTEGRATION_TESTS
# include <cppunit/extensions/TestFactoryRegistry.h>
# include <cppunit/extensions/HelperMacros.h>
#include "base/fscapi.h"
#include "base/globalsdef.h"
#include "base/Log.h"
#include "base/util/StringBuffer.h"
#include "base/adapter/PlatformAdapter.h"
#include "client/DMTClientConfig.h"
#include "client/SyncClient.h"
#include "ConfigSyncSourceTest.h"
#include "client/ConfigSyncSource.h"
USE_NAMESPACE
ConfigSyncSourceTest::ConfigSyncSourceTest() {
LOG.setLogName("syncsourceconfig_tests.log");
LOG.reset();
}
DMTClientConfig* getConf(const char* name) {
const char *serverUrl = getenv("CLIENT_TEST_SERVER_URL");
const char *username = getenv("CLIENT_TEST_USERNAME");
const char *password = getenv("CLIENT_TEST_PASSWORD");
PlatformAdapter::init(name, true);
DMTClientConfig* config = new DMTClientConfig();
config->read();
DeviceConfig &dc(config->getDeviceConfig());
if (!strlen(dc.getDevID())) {
config->setClientDefaults();
config->setSourceDefaults("config");
StringBuffer devid("sc-pim-"); devid += name;
dc.setDevID(devid);
SyncSourceConfig* s = config->getSyncSourceConfig("config");
s->setEncoding("bin");
s->setURI("configuration");
s->setType("text/plain");
}
//set custom configuration
if(serverUrl) {
config->getAccessConfig().setSyncURL(serverUrl);
}
if(username) {
config->getAccessConfig().setUsername(username);
}
if(password) {
config->getAccessConfig().setPassword(password);
}
return config;
}
void ConfigSyncSourceTest::testConfigSource() {
// create the first configuration
DMTClientConfig* config1 = getConf("funambol_configSyncSourceIntegration");
SyncSourceConfig *csconfig = config1->getSyncSourceConfig("config");
//CPPUNIT_ASSERT(csconfig);
//ccontact1->setSync("refresh-from-client");
config1->save();
config1->open();
ConfigSyncSource source(TEXT("config"), "funambol_configSyncSourceIntegration", csconfig);
ArrayList properties;
StringBuffer pushstatus("./Push/Status");
StringBuffer filterstatus("./Email/FilterStatus");
StringBuffer emailaddress("./Email/Address");
StringBuffer displayname("./Email/DisplayName");
properties.add(pushstatus);
properties.add(filterstatus);
properties.add(emailaddress);
properties.add(displayname);
source.setConfigProperties(properties);
SyncSource* sources[2];
sources[0] = &source;
sources[1] = NULL;
SyncClient client;
int ret = 0;
ret = client.sync(*config1, sources);
CPPUNIT_ASSERT(!ret);
config1->save();
//Sleep(INTERVAL);
delete config1;
}
#endif // ENABLE_INTEGRATION_TESTS
<|endoftext|> |
<commit_before>#include "accessibility.h"
#include <algorithm>
#include <cmath>
#include <utility>
#include "graphalg.h"
namespace MTC {
namespace accessibility {
using std::string;
using std::vector;
using std::pair;
using std::make_pair;
typedef std::pair<double, int> distance_node_pair;
bool distance_node_pair_comparator(const distance_node_pair& l,
const distance_node_pair& r)
{ return l.first < r.first; }
double exp_decay(const double &distance, const float &radius, const float &var)
{
return exp(-1*distance/radius) * var;
}
double linear_decay(const double &distance, const float &radius, const float &var)
{
return (1.0-distance/radius) * var;
}
double flat_decay(const double &distance, const float &radius, const float &var)
{
return var;
}
Accessibility::Accessibility(
int numnodes,
vector< vector<long>> edges,
vector< vector<double>> edgeweights,
bool twoway) {
this->aggregations.reserve(9);
this->aggregations.push_back("sum");
this->aggregations.push_back("mean");
this->aggregations.push_back("min");
this->aggregations.push_back("25pct");
this->aggregations.push_back("median");
this->aggregations.push_back("75pct");
this->aggregations.push_back("max");
this->aggregations.push_back("std");
this->aggregations.push_back("count");
this->decays.reserve(3);
this->decays.push_back("exp");
this->decays.push_back("linear");
this->decays.push_back("flat");
for (int i = 0 ; i < edgeweights.size() ; i++) {
this->addGraphalg(new Graphalg(numnodes, edges, edgeweights[i],
twoway));
}
this->numnodes = numnodes;
this->dmsradius = -1;
}
void Accessibility::addGraphalg(MTC::accessibility::Graphalg *g) {
std::shared_ptr<MTC::accessibility::Graphalg>ptr(g);
this->ga.push_back(ptr);
}
void
Accessibility::precomputeRangeQueries(float radius) {
dms.resize(ga.size());
for (int i = 0 ; i < ga.size() ; i++) {
dms[i].resize(numnodes);
}
#pragma omp parallel
{
#pragma omp for schedule(guided)
for (int i = 0 ; i < numnodes ; i++) {
for (int j = 0 ; j < ga.size() ; j++) {
ga[j]->Range(
i,
radius,
omp_get_thread_num(),
dms[j][i]);
}
}
}
dmsradius = radius;
}
std::vector<int>
Accessibility::Route(int src, int tgt, int graphno) {
vector<NodeID> ret = this->ga[graphno]->Route(src, tgt);
return vector<int> (ret.begin(), ret.end());
}
double
Accessibility::Distance(int src, int tgt, int graphno) {
return this->ga[graphno]->Distance(src, tgt);
}
std::vector<double>
Accessibility::Distances(vector<long> sources, vector<long> targets, int graphno)
{
vector<double> distances;
for (int i = 0 ; i < sources.size() ; i++) {
distances.push_back(this->ga[graphno]->Distance(sources[i], targets[i]));
}
/*
vector<long>::const_iterator target_it = targets.begin();
for(const long &src : sources) {
if(target_it == targets.end())
break;
distances.push_back(this->ga[graphno]->Distance(src, *target_it++));
}
*/
return distances;
}
/*
#######################
POI QUERIES
#######################
*/
void Accessibility::initializeCategory(const double maxdist, const int maxitems,
string category, vector<long> node_idx)
{
accessibility_vars_t av;
av.resize(this->numnodes);
this->maxdist = maxdist;
this->maxitems = maxitems;
// initialize for all subgraphs
for (int i = 0 ; i < ga.size() ; i++) {
ga[i]->initPOIIndex(category, this->maxdist, this->maxitems);
// initialize for each node
for (int j = 0 ; j < node_idx.size() ; j++) {
int node_id = node_idx[j];
ga[i]->addPOIToIndex(category, node_id);
assert(node_id << av.size());
av[node_id].push_back(j);
}
}
accessibilityVarsForPOIs[category] = av;
}
/* the return_nodeidx parameter determines whether to
return the nodeidx where the poi was found rather than
the distances - you can call this twice - once for the
distances and then again for the node idx */
vector<pair<double, int>>
Accessibility::findNearestPOIs(int srcnode, float maxradius, unsigned number,
string cat, int gno)
{
DistanceMap distancesmap = ga[gno]->NearestPOI(cat, srcnode,
maxradius, number, omp_get_thread_num());
vector<distance_node_pair> distance_node_pairs;
std::map<POIKeyType, accessibility_vars_t>::iterator cat_for_pois =
accessibilityVarsForPOIs.find(cat);
if(cat_for_pois == accessibilityVarsForPOIs.end())
return distance_node_pairs;
accessibility_vars_t &vars = cat_for_pois->second;
/* need to account for the possibility of having
multiple locations at single node */
for (DistanceMap::const_iterator itDist = distancesmap.begin();
itDist != distancesmap.end();
++itDist) {
int nodeid = itDist->first;
double distance = itDist->second;
for (int i = 0 ; i < vars[nodeid].size() ; i++) {
distance_node_pairs.push_back(
make_pair(distance, vars[nodeid][i]));
}
}
std::sort(distance_node_pairs.begin(), distance_node_pairs.end(),
distance_node_pair_comparator);
return distance_node_pairs;
}
/* the return_nodeds param is described above */
pair<vector<vector<double>>, vector<vector<int>>>
Accessibility::findAllNearestPOIs(float maxradius, unsigned num_of_pois,
string category,int gno)
{
vector<vector<double>>
dists(numnodes, vector<double> (num_of_pois));
vector<vector<int>>
poi_ids(numnodes, vector<int> (num_of_pois));
#pragma omp parallel for
for (int i = 0 ; i < numnodes ; i++) {
vector<pair<double, int>> d = findNearestPOIs(
i,
maxradius,
num_of_pois,
category,
gno);
for (int j = 0 ; j < num_of_pois ; j++) {
if (j < d.size()) {
dists[i][j] = d[j].first;
poi_ids[i][j] = d[j].second;
} else {
dists[i][j] = -1;
poi_ids[i][j] = -1;
}
}
}
return make_pair(dists, poi_ids);
}
/*
#######################
AGGREGATION/ACCESSIBILITY QUERIES
#######################
*/
void Accessibility::initializeAccVar(
string category,
vector<long> node_idx,
vector<double> values) {
accessibility_vars_t av;
av.resize(this->numnodes);
for (int i = 0 ; i < node_idx.size() ; i++) {
int node_id = node_idx[i];
double val = values[i];
assert(node_id << av.size());
av[node_id].push_back(val);
}
accessibilityVars[category] = av;
}
vector<double>
Accessibility::getAllAggregateAccessibilityVariables(
float radius,
string category,
string aggtyp,
string decay,
int graphno) {
if (accessibilityVars.find(category) == accessibilityVars.end() ||
std::find(aggregations.begin(), aggregations.end(), aggtyp)
== aggregations.end() ||
std::find(decays.begin(), decays.end(), decay) == decays.end()) {
// not found
return vector<double>();
}
vector<double> scores(numnodes);
#pragma omp parallel
{
#pragma omp for schedule(guided)
for (int i = 0 ; i < numnodes ; i++) {
scores[i] = aggregateAccessibilityVariable(
i,
radius,
accessibilityVars[category],
aggtyp,
decay,
graphno);
}
}
return scores;
}
double
Accessibility::quantileAccessibilityVariable(
DistanceVec &distances,
accessibility_vars_t &vars,
float quantile,
float radius) {
// first iterate through nodes in order to get count of items
int cnt = 0;
for (int i = 0 ; i < distances.size() ; i++) {
int nodeid = distances[i].first;
double distance = distances[i].second;
if (distance > radius) continue;
cnt += vars[nodeid].size();
}
if (cnt == 0) return -1;
vector<float> vals(cnt);
// make a second pass to put items in a single array for sorting
for (int i = 0, cnt = 0 ; i < distances.size() ; i++) {
int nodeid = distances[i].first;
double distance = distances[i].second;
if (distance > radius) continue;
// and then iterate through all items at the node
for (int j = 0 ; j < vars[nodeid].size() ; j++)
vals[cnt++] = vars[nodeid][j];
}
std::sort(vals.begin(), vals.end());
int ind = static_cast<int>(vals.size() * quantile);
if (quantile <= 0.0) ind = 0;
if (quantile >= 1.0) ind = vals.size()-1;
return vals[ind];
}
double
Accessibility::aggregateAccessibilityVariable(
int srcnode,
float radius,
accessibility_vars_t &vars,
string aggtyp,
string decay,
int gno) {
// I don't know if this is the best way to do this but I
// I don't want to copy memory in the precompute case - sometimes
// I need a reference and sometimes not
DistanceVec tmp;
DistanceVec &distances = tmp;
if (dmsradius > 0 && radius <= dmsradius) {
distances = dms[gno][srcnode];
} else {
ga[gno]->Range(
srcnode,
radius,
omp_get_thread_num(),
tmp);
}
if (distances.size() == 0) return -1;
if (aggtyp == "min") {
return this->quantileAccessibilityVariable(
distances, vars, 0.0, radius);
} else if (aggtyp == "25pct") {
return this->quantileAccessibilityVariable(
distances, vars, 0.25, radius);
} else if (aggtyp == "median") {
return this->quantileAccessibilityVariable(
distances, vars, 0.5, radius);
} else if (aggtyp == "75pct") {
return this->quantileAccessibilityVariable(
distances, vars, 0.75, radius);
} else if (aggtyp == "max") {
return this->quantileAccessibilityVariable(
distances, vars, 1.0, radius);
}
if (aggtyp == "std") decay = "flat";
int cnt = 0;
double sum = 0.0;
double sumsq = 0.0;
double (*sum_function_ptr)(const double &, const float &, const float &);
if(decay == "exp")
sum_function_ptr = &exp_decay;
if(decay == "linear")
sum_function_ptr = &linear_decay;
if(decay == "flat")
sum_function_ptr = &flat_decay;
for (int i = 0 ; i < distances.size() ; i++) {
int nodeid = distances[i].first;
double distance = distances[i].second;
// this can now happen since we're precomputing
if (distance > radius) continue;
for (int j = 0 ; j < vars[nodeid].size() ; j++) {
cnt++; // count items
sum += (*sum_function_ptr)(distance, radius, vars[nodeid][j]);
// stddev is always flat
sumsq += vars[nodeid][j] * vars[nodeid][j];
}
}
if (aggtyp == "count") return cnt;
if (aggtyp == "mean" && cnt != 0) sum /= cnt;
if (aggtyp == "std" && cnt != 0) {
double mean = sum / cnt;
return sqrt(sumsq / cnt - mean * mean);
}
return sum;
}
} // namespace accessibility
} // namespace MTC
<commit_msg>Multi-threading and list mismatch safety<commit_after>#include "accessibility.h"
#include <algorithm>
#include <cmath>
#include <utility>
#include "graphalg.h"
namespace MTC {
namespace accessibility {
using std::string;
using std::vector;
using std::pair;
using std::make_pair;
typedef std::pair<double, int> distance_node_pair;
bool distance_node_pair_comparator(const distance_node_pair& l,
const distance_node_pair& r)
{ return l.first < r.first; }
double exp_decay(const double &distance, const float &radius, const float &var)
{
return exp(-1*distance/radius) * var;
}
double linear_decay(const double &distance, const float &radius, const float &var)
{
return (1.0-distance/radius) * var;
}
double flat_decay(const double &distance, const float &radius, const float &var)
{
return var;
}
Accessibility::Accessibility(
int numnodes,
vector< vector<long>> edges,
vector< vector<double>> edgeweights,
bool twoway) {
this->aggregations.reserve(9);
this->aggregations.push_back("sum");
this->aggregations.push_back("mean");
this->aggregations.push_back("min");
this->aggregations.push_back("25pct");
this->aggregations.push_back("median");
this->aggregations.push_back("75pct");
this->aggregations.push_back("max");
this->aggregations.push_back("std");
this->aggregations.push_back("count");
this->decays.reserve(3);
this->decays.push_back("exp");
this->decays.push_back("linear");
this->decays.push_back("flat");
for (int i = 0 ; i < edgeweights.size() ; i++) {
this->addGraphalg(new Graphalg(numnodes, edges, edgeweights[i],
twoway));
}
this->numnodes = numnodes;
this->dmsradius = -1;
}
void Accessibility::addGraphalg(MTC::accessibility::Graphalg *g) {
std::shared_ptr<MTC::accessibility::Graphalg>ptr(g);
this->ga.push_back(ptr);
}
void
Accessibility::precomputeRangeQueries(float radius) {
dms.resize(ga.size());
for (int i = 0 ; i < ga.size() ; i++) {
dms[i].resize(numnodes);
}
#pragma omp parallel
{
#pragma omp for schedule(guided)
for (int i = 0 ; i < numnodes ; i++) {
for (int j = 0 ; j < ga.size() ; j++) {
ga[j]->Range(
i,
radius,
omp_get_thread_num(),
dms[j][i]);
}
}
}
dmsradius = radius;
}
std::vector<int>
Accessibility::Route(int src, int tgt, int graphno) {
vector<NodeID> ret = this->ga[graphno]->Route(src, tgt);
return vector<int> (ret.begin(), ret.end());
}
double
Accessibility::Distance(int src, int tgt, int graphno) {
return this->ga[graphno]->Distance(src, tgt);
}
std::vector<double>
Accessibility::Distances(vector<long> sources, vector<long> targets, int graphno) {
int n = std::min(sources.size(), targets.size()); // in case lists don't match
vector<double> distances (n);
#pragma omp parallel
#pragma omp for schedule(guided)
for (int i = 0 ; i < n ; i++) {
distances[i] = this->ga[graphno]->Distance(
sources[i],
targets[i],
omp_get_thread_num());
}
return distances;
}
/*
#######################
POI QUERIES
#######################
*/
void Accessibility::initializeCategory(const double maxdist, const int maxitems,
string category, vector<long> node_idx)
{
accessibility_vars_t av;
av.resize(this->numnodes);
this->maxdist = maxdist;
this->maxitems = maxitems;
// initialize for all subgraphs
for (int i = 0 ; i < ga.size() ; i++) {
ga[i]->initPOIIndex(category, this->maxdist, this->maxitems);
// initialize for each node
for (int j = 0 ; j < node_idx.size() ; j++) {
int node_id = node_idx[j];
ga[i]->addPOIToIndex(category, node_id);
assert(node_id << av.size());
av[node_id].push_back(j);
}
}
accessibilityVarsForPOIs[category] = av;
}
/* the return_nodeidx parameter determines whether to
return the nodeidx where the poi was found rather than
the distances - you can call this twice - once for the
distances and then again for the node idx */
vector<pair<double, int>>
Accessibility::findNearestPOIs(int srcnode, float maxradius, unsigned number,
string cat, int gno)
{
DistanceMap distancesmap = ga[gno]->NearestPOI(cat, srcnode,
maxradius, number, omp_get_thread_num());
vector<distance_node_pair> distance_node_pairs;
std::map<POIKeyType, accessibility_vars_t>::iterator cat_for_pois =
accessibilityVarsForPOIs.find(cat);
if(cat_for_pois == accessibilityVarsForPOIs.end())
return distance_node_pairs;
accessibility_vars_t &vars = cat_for_pois->second;
/* need to account for the possibility of having
multiple locations at single node */
for (DistanceMap::const_iterator itDist = distancesmap.begin();
itDist != distancesmap.end();
++itDist) {
int nodeid = itDist->first;
double distance = itDist->second;
for (int i = 0 ; i < vars[nodeid].size() ; i++) {
distance_node_pairs.push_back(
make_pair(distance, vars[nodeid][i]));
}
}
std::sort(distance_node_pairs.begin(), distance_node_pairs.end(),
distance_node_pair_comparator);
return distance_node_pairs;
}
/* the return_nodeds param is described above */
pair<vector<vector<double>>, vector<vector<int>>>
Accessibility::findAllNearestPOIs(float maxradius, unsigned num_of_pois,
string category,int gno)
{
vector<vector<double>>
dists(numnodes, vector<double> (num_of_pois));
vector<vector<int>>
poi_ids(numnodes, vector<int> (num_of_pois));
#pragma omp parallel for
for (int i = 0 ; i < numnodes ; i++) {
vector<pair<double, int>> d = findNearestPOIs(
i,
maxradius,
num_of_pois,
category,
gno);
for (int j = 0 ; j < num_of_pois ; j++) {
if (j < d.size()) {
dists[i][j] = d[j].first;
poi_ids[i][j] = d[j].second;
} else {
dists[i][j] = -1;
poi_ids[i][j] = -1;
}
}
}
return make_pair(dists, poi_ids);
}
/*
#######################
AGGREGATION/ACCESSIBILITY QUERIES
#######################
*/
void Accessibility::initializeAccVar(
string category,
vector<long> node_idx,
vector<double> values) {
accessibility_vars_t av;
av.resize(this->numnodes);
for (int i = 0 ; i < node_idx.size() ; i++) {
int node_id = node_idx[i];
double val = values[i];
assert(node_id << av.size());
av[node_id].push_back(val);
}
accessibilityVars[category] = av;
}
vector<double>
Accessibility::getAllAggregateAccessibilityVariables(
float radius,
string category,
string aggtyp,
string decay,
int graphno) {
if (accessibilityVars.find(category) == accessibilityVars.end() ||
std::find(aggregations.begin(), aggregations.end(), aggtyp)
== aggregations.end() ||
std::find(decays.begin(), decays.end(), decay) == decays.end()) {
// not found
return vector<double>();
}
vector<double> scores(numnodes);
#pragma omp parallel
{
#pragma omp for schedule(guided)
for (int i = 0 ; i < numnodes ; i++) {
scores[i] = aggregateAccessibilityVariable(
i,
radius,
accessibilityVars[category],
aggtyp,
decay,
graphno);
}
}
return scores;
}
double
Accessibility::quantileAccessibilityVariable(
DistanceVec &distances,
accessibility_vars_t &vars,
float quantile,
float radius) {
// first iterate through nodes in order to get count of items
int cnt = 0;
for (int i = 0 ; i < distances.size() ; i++) {
int nodeid = distances[i].first;
double distance = distances[i].second;
if (distance > radius) continue;
cnt += vars[nodeid].size();
}
if (cnt == 0) return -1;
vector<float> vals(cnt);
// make a second pass to put items in a single array for sorting
for (int i = 0, cnt = 0 ; i < distances.size() ; i++) {
int nodeid = distances[i].first;
double distance = distances[i].second;
if (distance > radius) continue;
// and then iterate through all items at the node
for (int j = 0 ; j < vars[nodeid].size() ; j++)
vals[cnt++] = vars[nodeid][j];
}
std::sort(vals.begin(), vals.end());
int ind = static_cast<int>(vals.size() * quantile);
if (quantile <= 0.0) ind = 0;
if (quantile >= 1.0) ind = vals.size()-1;
return vals[ind];
}
double
Accessibility::aggregateAccessibilityVariable(
int srcnode,
float radius,
accessibility_vars_t &vars,
string aggtyp,
string decay,
int gno) {
// I don't know if this is the best way to do this but I
// I don't want to copy memory in the precompute case - sometimes
// I need a reference and sometimes not
DistanceVec tmp;
DistanceVec &distances = tmp;
if (dmsradius > 0 && radius <= dmsradius) {
distances = dms[gno][srcnode];
} else {
ga[gno]->Range(
srcnode,
radius,
omp_get_thread_num(),
tmp);
}
if (distances.size() == 0) return -1;
if (aggtyp == "min") {
return this->quantileAccessibilityVariable(
distances, vars, 0.0, radius);
} else if (aggtyp == "25pct") {
return this->quantileAccessibilityVariable(
distances, vars, 0.25, radius);
} else if (aggtyp == "median") {
return this->quantileAccessibilityVariable(
distances, vars, 0.5, radius);
} else if (aggtyp == "75pct") {
return this->quantileAccessibilityVariable(
distances, vars, 0.75, radius);
} else if (aggtyp == "max") {
return this->quantileAccessibilityVariable(
distances, vars, 1.0, radius);
}
if (aggtyp == "std") decay = "flat";
int cnt = 0;
double sum = 0.0;
double sumsq = 0.0;
double (*sum_function_ptr)(const double &, const float &, const float &);
if(decay == "exp")
sum_function_ptr = &exp_decay;
if(decay == "linear")
sum_function_ptr = &linear_decay;
if(decay == "flat")
sum_function_ptr = &flat_decay;
for (int i = 0 ; i < distances.size() ; i++) {
int nodeid = distances[i].first;
double distance = distances[i].second;
// this can now happen since we're precomputing
if (distance > radius) continue;
for (int j = 0 ; j < vars[nodeid].size() ; j++) {
cnt++; // count items
sum += (*sum_function_ptr)(distance, radius, vars[nodeid][j]);
// stddev is always flat
sumsq += vars[nodeid][j] * vars[nodeid][j];
}
}
if (aggtyp == "count") return cnt;
if (aggtyp == "mean" && cnt != 0) sum /= cnt;
if (aggtyp == "std" && cnt != 0) {
double mean = sum / cnt;
return sqrt(sumsq / cnt - mean * mean);
}
return sum;
}
} // namespace accessibility
} // namespace MTC
<|endoftext|> |
<commit_before>/*=========================================================================
*
* Copyright 2011-2013 The University of North Carolina at Chapel Hill
* All rights reserved.
*
* Licensed under the MADAI Software License. You may obtain a copy of
* this license at
*
* https://madai-public.cs.unc.edu/software/license/
*
* 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.
*
*=========================================================================*/
/**
basicTrain
Set hyperparameters for a N-D Gaussian Process Model Emulator
ACKNOWLEDGMENTS:
This software was written in 2012-2013 by Hal Canary
<cs.unc.edu/~hal>, based off of the MADAIEmulator program (Copyright
2009-2012 Duke University) by C.Coleman-Smith <[email protected]>
in 2010-2012 while working for the MADAI project <http://madai.us/>.
USE:
For details on how to use basicTrain, consult the manpage via:
$ nroff -man < [PATH_TO/]basicTrain.1 | less
or, if the manual is installed:
$ man 1 basicTrain
*/
const char useage [] =
"Usage:\n"
" basicTrain StatisticsDirectory\n"
"\n"
"StatisticsDirectory is the directory in which all statistical data will\n"
"be stored. Contains the parameter file stat_params.dat\n"
"\n"
"Format of stat_params.dat\n"
"MODEL_OUTPUT_DIRECTORY <value>\n"
"EXPERIMENTAL_RESULTS_DIRECTORY <value>\n"
"EMULATOR_COVARIANCE_FUNCTION <value>\n"
"EMULATOR_REGRESSION_ORDER <value>\n"
"EMULATOR_NUGGET <value>\n"
"EMULATOR_AMPLITUDE <value>\n"
"EMULATOR_SCALE <value>\n"
"\n"
"Default values (if not specified) in order of listed:\n"
"model_output\n"
"experimental_results\n"
"SQUARE_EXPONENTIAL_FUNCTION\n"
"1\n"
"1e-3\n"
"1.0\n"
"1e-2\n"
"\n"
"This loads the model data and PCA information in order to train\n"
"the emulator.\n";
#include <iostream> // cout, cin
#include <fstream> // ifstream, ofstream
#include "ApplicationUtilities.h"
#include "RuntimeParameterFileReader.h"
#include "GaussianProcessEmulator.h"
#include "GaussianProcessEmulatorDirectoryReader.h"
#include "GaussianProcessEmulatorSingleFileReader.h"
#include "GaussianProcessEmulatorSingleFileWriter.h"
#include "Paths.h"
struct RuntimeOptions
{
std::string ModelOutputDirectory;
std::string ExperimentalResultsDirectory;
madai::GaussianProcessEmulator::CovarianceFunctionType covFunct;
int regressionOrder;
double Nugget;
double amplitude;
double scale;
};
bool parseRuntimeOptions( int argc, char* argv[], struct RuntimeOptions & options)
{
options.covFunct = madai::GaussianProcessEmulator::SQUARE_EXPONENTIAL_FUNCTION;
options.ModelOutputDirectory = madai::Paths::DEFAULT_MODEL_OUTPUT_DIRECTORY;
options.ExperimentalResultsDirectory = madai::Paths::DEFAULT_EXPERIMENTAL_RESULTS_DIRECTORY;
options.regressionOrder = 1;
options.Nugget = 1e-3;
options.amplitude = 1.0;
options.scale = 1e-2;
for ( unsigned int i = 0; i < argc; i++ ) {
std::string argString( argv[i] );
if ( argString == "EMULATOR_COVARIANCE_FUNCTION" ) {
std::string CovType( argv[i+1] );
if ( CovType == "POWER_EXPONENTIAL_FUNCTION" ) {
options.covFunct = madai::GaussianProcessEmulator::POWER_EXPONENTIAL_FUNCTION;
} else if ( CovType == "SQUARE_EXPONENTIAL_FUNCTION" ) {
options.covFunct = madai::GaussianProcessEmulator::SQUARE_EXPONENTIAL_FUNCTION;
} else if ( CovType == "MATERN_32_FUNCTION" ) {
options.covFunct = madai::GaussianProcessEmulator::MATERN_32_FUNCTION;
} else if ( CovType == "MATERN_52_FUNCTION" ) {
options.covFunct = madai::GaussianProcessEmulator::MATERN_52_FUNCTION;
} else {
std::cerr << "Unrecognized covariance function: " << CovType << "\n";
return false;
}
i++;
} else if ( argString == "MODEL_OUTPUT_DIRECTORY" ) {
options.ModelOutputDirectory = std::string( argv[i+1] );
i++;
} else if ( argString == "EXPERIMENTAL_RESULTS_DIRECTORY" ) {
options.ExperimentalResultsDirectory = std::string( argv[i+1] );
i++;
} else if ( argString == "EMULATOR_REGRESSION_ORDER" ) {
options.regressionOrder = atoi(argv[i+1]);
std::cout << "Using regression order = " << options.regressionOrder << "\n";
i++;
} else if ( argString == "EMULATOR_NUGGET" ) {
options.Nugget = atof(argv[i+1]);
std::cout << "Using nugget = " << options.Nugget << "\n";
i++;
} else if ( argString == "EMULATOR_AMPLITUDE" ) {
options.amplitude = atof(argv[i+1]);
std::cout << "Using amplitude = " << options.amplitude << "\n";
i++;
} else if ( argString == "EMULATOR_SCALE" ) {
options.scale = atof(argv[i+1]);
std::cout << "Using scale = " << options.scale << "\n";
i++;
}
}
return true;
}
int main(int argc, char ** argv) {
std::string StatisticsDirectory;
std::string ModelOutputDirectory;
std::string outputFile;
std::string PCAFile;
if (argc > 1) {
StatisticsDirectory = std::string(argv[1]);
} else {
std::cerr << useage << '\n';
return EXIT_FAILURE;
}
madai::GaussianProcessEmulator gpme;
struct RuntimeOptions options;
if ( StatisticsDirectory == "-" ) {
madai::GaussianProcessEmulatorSingleFileReader singleFileReader;
singleFileReader.LoadTrainingData( &gpme, std::cin);
} else {
madai::EnsurePathSeparatorAtEnd( StatisticsDirectory );
madai::RuntimeParameterFileReader RPFR;
RPFR.ParseFile( StatisticsDirectory +
madai::Paths::RUNTIME_PARAMETER_FILE );
char** Args = RPFR.GetArguments();
int NArgs = RPFR.GetNumberOfArguments();
if ( !parseRuntimeOptions( NArgs, Args, options ) ) {
std::cerr << "Error parsing runtime options\n";
return EXIT_FAILURE;
}
std::string MOD = StatisticsDirectory+options.ModelOutputDirectory;
std::string ERD = StatisticsDirectory+options.ExperimentalResultsDirectory;
madai::GaussianProcessEmulatorDirectoryReader directoryReader;
if ( !directoryReader.LoadTrainingData(&gpme, MOD, StatisticsDirectory, ERD) ) {
std::cerr << "Error Loading Training Data.\n";
return EXIT_FAILURE;
}
if ( !directoryReader.LoadPCA(&gpme, StatisticsDirectory) ) {
std::cerr << "Error Loading PCA Data.\n";
return EXIT_FAILURE;
}
}
outputFile = StatisticsDirectory + madai::Paths::EMULATOR_STATE_FILE;
if (! gpme.BasicTraining(
options.covFunct,
options.regressionOrder,
options.Nugget,
options.amplitude,
options.scale))
return EXIT_FAILURE;
std::ofstream os (outputFile.c_str());
madai::GaussianProcessEmulatorSingleFileWriter singleFileWriter;
singleFileWriter.Write(&gpme,os);
return EXIT_SUCCESS;
}
<commit_msg>Tweaked usage message<commit_after>/*=========================================================================
*
* Copyright 2011-2013 The University of North Carolina at Chapel Hill
* All rights reserved.
*
* Licensed under the MADAI Software License. You may obtain a copy of
* this license at
*
* https://madai-public.cs.unc.edu/software/license/
*
* 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.
*
*=========================================================================*/
/**
basicTrain
Set hyperparameters for a N-D Gaussian Process Model Emulator
ACKNOWLEDGMENTS:
This software was written in 2012-2013 by Hal Canary
<cs.unc.edu/~hal>, based off of the MADAIEmulator program (Copyright
2009-2012 Duke University) by C.Coleman-Smith <[email protected]>
in 2010-2012 while working for the MADAI project <http://madai.us/>.
USE:
For details on how to use basicTrain, consult the manpage via:
$ nroff -man < [PATH_TO/]basicTrain.1 | less
or, if the manual is installed:
$ man 1 basicTrain
*/
#include <iostream> // cout, cin
#include <fstream> // ifstream, ofstream
#include "ApplicationUtilities.h"
#include "RuntimeParameterFileReader.h"
#include "GaussianProcessEmulator.h"
#include "GaussianProcessEmulatorDirectoryReader.h"
#include "GaussianProcessEmulatorSingleFileReader.h"
#include "GaussianProcessEmulatorSingleFileWriter.h"
#include "Paths.h"
using madai::Paths;
struct RuntimeOptions
{
std::string ModelOutputDirectory;
std::string ExperimentalResultsDirectory;
madai::GaussianProcessEmulator::CovarianceFunctionType covFunct;
int regressionOrder;
double Nugget;
double amplitude;
double scale;
};
bool parseRuntimeOptions( int argc, char* argv[], struct RuntimeOptions & options)
{
options.covFunct = madai::GaussianProcessEmulator::SQUARE_EXPONENTIAL_FUNCTION;
options.ModelOutputDirectory = madai::Paths::DEFAULT_MODEL_OUTPUT_DIRECTORY;
options.ExperimentalResultsDirectory = madai::Paths::DEFAULT_EXPERIMENTAL_RESULTS_DIRECTORY;
options.regressionOrder = 1;
options.Nugget = 1e-3;
options.amplitude = 1.0;
options.scale = 1e-2;
for ( unsigned int i = 0; i < argc; i++ ) {
std::string argString( argv[i] );
if ( argString == "EMULATOR_COVARIANCE_FUNCTION" ) {
std::string CovType( argv[i+1] );
if ( CovType == "POWER_EXPONENTIAL_FUNCTION" ) {
options.covFunct = madai::GaussianProcessEmulator::POWER_EXPONENTIAL_FUNCTION;
} else if ( CovType == "SQUARE_EXPONENTIAL_FUNCTION" ) {
options.covFunct = madai::GaussianProcessEmulator::SQUARE_EXPONENTIAL_FUNCTION;
} else if ( CovType == "MATERN_32_FUNCTION" ) {
options.covFunct = madai::GaussianProcessEmulator::MATERN_32_FUNCTION;
} else if ( CovType == "MATERN_52_FUNCTION" ) {
options.covFunct = madai::GaussianProcessEmulator::MATERN_52_FUNCTION;
} else {
std::cerr << "Unrecognized covariance function: " << CovType << "\n";
return false;
}
i++;
} else if ( argString == "MODEL_OUTPUT_DIRECTORY" ) {
options.ModelOutputDirectory = std::string( argv[i+1] );
i++;
} else if ( argString == "EXPERIMENTAL_RESULTS_DIRECTORY" ) {
options.ExperimentalResultsDirectory = std::string( argv[i+1] );
i++;
} else if ( argString == "EMULATOR_REGRESSION_ORDER" ) {
options.regressionOrder = atoi(argv[i+1]);
std::cout << "Using regression order = " << options.regressionOrder << "\n";
i++;
} else if ( argString == "EMULATOR_NUGGET" ) {
options.Nugget = atof(argv[i+1]);
std::cout << "Using nugget = " << options.Nugget << "\n";
i++;
} else if ( argString == "EMULATOR_AMPLITUDE" ) {
options.amplitude = atof(argv[i+1]);
std::cout << "Using amplitude = " << options.amplitude << "\n";
i++;
} else if ( argString == "EMULATOR_SCALE" ) {
options.scale = atof(argv[i+1]);
std::cout << "Using scale = " << options.scale << "\n";
i++;
}
}
return true;
}
int main(int argc, char ** argv) {
std::string StatisticsDirectory;
std::string ModelOutputDirectory;
std::string outputFile;
std::string PCAFile;
if (argc > 1) {
StatisticsDirectory = std::string(argv[1]);
} else {
std::cerr << "Usage:\n"
<< " basicTrain <StatisticsDirectory>\n"
<< "\n"
<< "This loads the model data and PCA information computed with \n"
<< "PCADecompose and trains the emulator. It stores the results \n"
<< "in <StatisticsDirectory>" << Paths::SEPARATOR
<< Paths::EMULATOR_STATE_FILE << "\n"
<< "\n"
<< "<StatisticsDirectory> is the directory in which all \n"
<< "statistics data are stored. It contains the parameter file "
<< Paths::RUNTIME_PARAMETER_FILE << "\n"
<< "\n"
<< "Format of entries in " << Paths::RUNTIME_PARAMETER_FILE
<< ":\n\n"
<< "MODEL_OUTPUT_DIRECTORY <value> (default: "
<< Paths::DEFAULT_MODEL_OUTPUT_DIRECTORY << ")\n"
<< "EXPERIMENTAL_RESULTS_DIRECTORY <value> (default: "
<< Paths::DEFAULT_EXPERIMENTAL_RESULTS_DIRECTORY << ")\n"
<< "EMULATOR_COVARIANCE_FUNCTION <value> (default: SQUARE_EXPONENTIAL_FUNCTION)\n"
<< "EMULATOR_REGRESSION_ORDER <value> (default: 1)\n"
<< "EMULATOR_NUGGET <value> (default: 1e-3)\n"
<< "EMULATOR_AMPLITUDE <value> (default: 1.0)\n"
<< "EMULATOR_SCALE <value> (default: 1e-2)\n";
return EXIT_FAILURE;
}
madai::GaussianProcessEmulator gpme;
struct RuntimeOptions options;
if ( StatisticsDirectory == "-" ) {
madai::GaussianProcessEmulatorSingleFileReader singleFileReader;
singleFileReader.LoadTrainingData( &gpme, std::cin);
} else {
madai::EnsurePathSeparatorAtEnd( StatisticsDirectory );
madai::RuntimeParameterFileReader RPFR;
RPFR.ParseFile( StatisticsDirectory +
madai::Paths::RUNTIME_PARAMETER_FILE );
char** Args = RPFR.GetArguments();
int NArgs = RPFR.GetNumberOfArguments();
if ( !parseRuntimeOptions( NArgs, Args, options ) ) {
std::cerr << "Error parsing runtime options\n";
return EXIT_FAILURE;
}
std::string MOD = StatisticsDirectory+options.ModelOutputDirectory;
std::string ERD = StatisticsDirectory+options.ExperimentalResultsDirectory;
madai::GaussianProcessEmulatorDirectoryReader directoryReader;
if ( !directoryReader.LoadTrainingData(&gpme, MOD, StatisticsDirectory, ERD) ) {
std::cerr << "Error Loading Training Data.\n";
return EXIT_FAILURE;
}
if ( !directoryReader.LoadPCA(&gpme, StatisticsDirectory) ) {
std::cerr << "Error Loading PCA Data.\n";
return EXIT_FAILURE;
}
}
outputFile = StatisticsDirectory + madai::Paths::EMULATOR_STATE_FILE;
if (! gpme.BasicTraining(
options.covFunct,
options.regressionOrder,
options.Nugget,
options.amplitude,
options.scale))
return EXIT_FAILURE;
std::ofstream os (outputFile.c_str());
madai::GaussianProcessEmulatorSingleFileWriter singleFileWriter;
singleFileWriter.Write(&gpme,os);
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>#include "BasicGameListView.h"
#include "../ViewController.h"
#include "../../Renderer.h"
#include "../../Window.h"
#include "../../ThemeData.h"
#include "../../SystemData.h"
#include "../../Settings.h"
BasicGameListView::BasicGameListView(Window* window, FileData* root)
: ISimpleGameListView(window, root), mList(window)
{
mList.setSize(mSize.x(), mSize.y() * 0.8f);
mList.setPosition(0, mSize.y() * 0.2f);
addChild(&mList);
populateList(root->getChildren());
}
void BasicGameListView::onThemeChanged(const std::shared_ptr<ThemeData>& theme)
{
ISimpleGameListView::onThemeChanged(theme);
using namespace ThemeFlags;
mList.applyTheme(theme, getName(), "gamelist", ALL);
}
void BasicGameListView::onFileChanged(FileData* file, FileChangeType change)
{
if(change == FILE_METADATA_CHANGED)
{
// might switch to a detailed view
mWindow->getViewController()->reloadGameListView(this);
return;
}
ISimpleGameListView::onFileChanged(file, change);
}
void BasicGameListView::populateList(const std::vector<FileData*>& files)
{
mList.clear();
mHeaderText.setText(files.at(0)->getSystem()->getFullName());
for(auto it = files.begin(); it != files.end(); it++)
{
mList.add((*it)->getName(), *it, ((*it)->getType() == FOLDER));
}
}
FileData* BasicGameListView::getCursor()
{
return mList.getSelected();
}
void BasicGameListView::setCursor(FileData* cursor)
{
if(!mList.setCursor(cursor))
{
populateList(cursor->getParent()->getChildren());
mList.setCursor(cursor);
}
}
void BasicGameListView::launch(FileData* game)
{
mWindow->getViewController()->launch(game);
}
std::vector<HelpPrompt> BasicGameListView::getHelpPrompts()
{
std::vector<HelpPrompt> prompts;
if(Settings::getInstance()->getBool("QuickSystemSelect"))
prompts.push_back(HelpPrompt("left/right", "system"));
prompts.push_back(HelpPrompt("up/down", "choose"));
prompts.push_back(HelpPrompt("a", "launch"));
prompts.push_back(HelpPrompt("b", "back"));
prompts.push_back(HelpPrompt("select", "options"));
return prompts;
}
<commit_msg>Fix editing metadata in a nested folder causing back button to stop working.<commit_after>#include "BasicGameListView.h"
#include "../ViewController.h"
#include "../../Renderer.h"
#include "../../Window.h"
#include "../../ThemeData.h"
#include "../../SystemData.h"
#include "../../Settings.h"
BasicGameListView::BasicGameListView(Window* window, FileData* root)
: ISimpleGameListView(window, root), mList(window)
{
mList.setSize(mSize.x(), mSize.y() * 0.8f);
mList.setPosition(0, mSize.y() * 0.2f);
addChild(&mList);
populateList(root->getChildren());
}
void BasicGameListView::onThemeChanged(const std::shared_ptr<ThemeData>& theme)
{
ISimpleGameListView::onThemeChanged(theme);
using namespace ThemeFlags;
mList.applyTheme(theme, getName(), "gamelist", ALL);
}
void BasicGameListView::onFileChanged(FileData* file, FileChangeType change)
{
if(change == FILE_METADATA_CHANGED)
{
// might switch to a detailed view
mWindow->getViewController()->reloadGameListView(this);
return;
}
ISimpleGameListView::onFileChanged(file, change);
}
void BasicGameListView::populateList(const std::vector<FileData*>& files)
{
mList.clear();
mHeaderText.setText(files.at(0)->getSystem()->getFullName());
for(auto it = files.begin(); it != files.end(); it++)
{
mList.add((*it)->getName(), *it, ((*it)->getType() == FOLDER));
}
}
FileData* BasicGameListView::getCursor()
{
return mList.getSelected();
}
void BasicGameListView::setCursor(FileData* cursor)
{
if(!mList.setCursor(cursor))
{
populateList(cursor->getParent()->getChildren());
mList.setCursor(cursor);
// update our cursor stack in case our cursor just got set to some folder we weren't in before
if(mCursorStack.empty() || mCursorStack.top() != cursor->getParent())
{
std::stack<FileData*> tmp;
FileData* ptr = cursor->getParent();
while(ptr && ptr != mRoot)
{
tmp.push(ptr);
ptr = ptr->getParent();
}
// flip the stack and put it in mCursorStack
mCursorStack = std::stack<FileData*>();
while(!tmp.empty())
{
mCursorStack.push(tmp.top());
tmp.pop();
}
}
}
}
void BasicGameListView::launch(FileData* game)
{
mWindow->getViewController()->launch(game);
}
std::vector<HelpPrompt> BasicGameListView::getHelpPrompts()
{
std::vector<HelpPrompt> prompts;
if(Settings::getInstance()->getBool("QuickSystemSelect"))
prompts.push_back(HelpPrompt("left/right", "system"));
prompts.push_back(HelpPrompt("up/down", "choose"));
prompts.push_back(HelpPrompt("a", "launch"));
prompts.push_back(HelpPrompt("b", "back"));
prompts.push_back(HelpPrompt("select", "options"));
return prompts;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: provprox.cxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: rt $ $Date: 2005-09-09 15:15:13 $
*
* 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 _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _PROVPROX_HXX
#include "provprox.hxx"
#endif
using namespace rtl;
using namespace com::sun::star::lang;
using namespace com::sun::star::ucb;
using namespace com::sun::star::uno;
//=========================================================================
//=========================================================================
//
// UcbContentProviderProxyFactory Implementation.
//
//=========================================================================
//=========================================================================
UcbContentProviderProxyFactory::UcbContentProviderProxyFactory(
const Reference< XMultiServiceFactory >& rxSMgr )
: m_xSMgr( rxSMgr )
{
}
//=========================================================================
// virtual
UcbContentProviderProxyFactory::~UcbContentProviderProxyFactory()
{
}
//=========================================================================
//
// XInterface methods.
//
//=========================================================================
XINTERFACE_IMPL_3( UcbContentProviderProxyFactory,
XTypeProvider,
XServiceInfo,
XContentProviderFactory );
//=========================================================================
//
// XTypeProvider methods.
//
//=========================================================================
XTYPEPROVIDER_IMPL_3( UcbContentProviderProxyFactory,
XTypeProvider,
XServiceInfo,
XContentProviderFactory );
//=========================================================================
//
// XServiceInfo methods.
//
//=========================================================================
XSERVICEINFO_IMPL_1( UcbContentProviderProxyFactory,
OUString::createFromAscii(
"com.sun.star.comp.ucb.UcbContentProviderProxyFactory" ),
OUString::createFromAscii(
PROVIDER_FACTORY_SERVICE_NAME ) );
//=========================================================================
//
// Service factory implementation.
//
//=========================================================================
ONE_INSTANCE_SERVICE_FACTORY_IMPL( UcbContentProviderProxyFactory );
//=========================================================================
//
// XContentProviderFactory methods.
//
//=========================================================================
// virtual
Reference< XContentProvider > SAL_CALL
UcbContentProviderProxyFactory::createContentProvider(
const OUString& Service )
throw( RuntimeException )
{
return Reference< XContentProvider >(
new UcbContentProviderProxy( m_xSMgr, Service ) );
}
//=========================================================================
//=========================================================================
//
// UcbContentProviderProxy Implementation.
//
//=========================================================================
//=========================================================================
UcbContentProviderProxy::UcbContentProviderProxy(
const Reference< XMultiServiceFactory >& rxSMgr,
const OUString& Service )
: m_aService( Service ),
m_bReplace( sal_False ),
m_bRegister( sal_False ),
m_xSMgr( rxSMgr )
{
}
//=========================================================================
// virtual
UcbContentProviderProxy::~UcbContentProviderProxy()
{
}
//=========================================================================
//
// XInterface methods.
//
//=========================================================================
XINTERFACE_COMMON_IMPL( UcbContentProviderProxy );
//============================================================================
// virtual
Any SAL_CALL
UcbContentProviderProxy::queryInterface( const Type & rType )
throw ( RuntimeException )
{
Any aRet = cppu::queryInterface( rType,
static_cast< XTypeProvider * >( this ),
static_cast< XServiceInfo * >( this ),
static_cast< XContentProvider * >( this ),
static_cast< XParameterizedContentProvider * >( this ),
static_cast< XContentProviderSupplier * >( this ) );
if ( !aRet.hasValue() )
aRet = OWeakObject::queryInterface( rType );
if ( !aRet.hasValue() )
{
// Get original provider an forward the call...
osl::Guard< osl::Mutex > aGuard( m_aMutex );
Reference< XInterface > xProvider = getContentProvider();
if ( xProvider.is() )
aRet = xProvider->queryInterface( rType );
}
return aRet;
}
//=========================================================================
//
// XTypeProvider methods.
//
//=========================================================================
XTYPEPROVIDER_COMMON_IMPL( UcbContentProviderProxy );
//=========================================================================
Sequence< Type > SAL_CALL UcbContentProviderProxy::getTypes() \
throw( RuntimeException )
{
// Get original provider an forward the call...
osl::Guard< osl::Mutex > aGuard( m_aMutex );
Reference< XTypeProvider > xProvider( getContentProvider(), UNO_QUERY );
if ( xProvider.is() )
{
return xProvider->getTypes();
}
else
{
static cppu::OTypeCollection * pCollection = 0;
if ( !pCollection )
{
osl::Guard< osl::Mutex > aGuard( m_aMutex );
if ( !pCollection )
{
static cppu::OTypeCollection collection(
CPPU_TYPE_REF( XTypeProvider ),
CPPU_TYPE_REF( XServiceInfo ),
CPPU_TYPE_REF( XContentProvider ),
CPPU_TYPE_REF( XParameterizedContentProvider ),
CPPU_TYPE_REF( XContentProviderSupplier ) );
pCollection = &collection;
}
}
return (*pCollection).getTypes();
}
}
//=========================================================================
//
// XServiceInfo methods.
//
//=========================================================================
XSERVICEINFO_NOFACTORY_IMPL_1( UcbContentProviderProxy,
OUString::createFromAscii(
"com.sun.star.comp.ucb.UcbContentProviderProxy" ),
OUString::createFromAscii(
PROVIDER_PROXY_SERVICE_NAME ) );
//=========================================================================
//
// XContentProvider methods.
//
//=========================================================================
// virtual
Reference< XContent > SAL_CALL UcbContentProviderProxy::queryContent(
const Reference< XContentIdentifier >& Identifier )
throw( IllegalIdentifierException,
RuntimeException )
{
// Get original provider an forward the call...
osl::Guard< osl::Mutex > aGuard( m_aMutex );
Reference< XContentProvider > xProvider = getContentProvider();
if ( xProvider.is() )
return xProvider->queryContent( Identifier );
return Reference< XContent >();
}
//=========================================================================
// virtual
sal_Int32 SAL_CALL UcbContentProviderProxy::compareContentIds(
const Reference< XContentIdentifier >& Id1,
const Reference< XContentIdentifier >& Id2 )
throw( RuntimeException )
{
// Get original provider an forward the call...
osl::Guard< osl::Mutex > aGuard( m_aMutex );
Reference< XContentProvider > xProvider = getContentProvider();
if ( xProvider.is() )
return xProvider->compareContentIds( Id1, Id2 );
OSL_ENSURE( sal_False,
"UcbContentProviderProxy::compareContentIds - No provider!" );
// @@@ What else?
return 0;
}
//=========================================================================
//
// XParameterizedContentProvider methods.
//
//=========================================================================
// virtual
Reference< XContentProvider > SAL_CALL
UcbContentProviderProxy::registerInstance( const OUString& Template,
const OUString& Arguments,
sal_Bool ReplaceExisting )
throw( IllegalArgumentException,
RuntimeException )
{
// Just remember that this method was called ( and the params ).
osl::Guard< osl::Mutex > aGuard( m_aMutex );
if ( !m_bRegister )
{
// m_xTargetProvider = 0;
m_aTemplate = Template;
m_aArguments = Arguments;
m_bReplace = ReplaceExisting;
m_bRegister = sal_True;
}
return this;
}
//=========================================================================
// virtual
Reference< XContentProvider > SAL_CALL
UcbContentProviderProxy::deregisterInstance( const OUString& Template,
const OUString& Arguments )
throw( IllegalArgumentException,
RuntimeException )
{
osl::Guard< osl::Mutex > aGuard( m_aMutex );
// registerInstance called at proxy and at original?
if ( m_bRegister && m_xTargetProvider.is() )
{
m_bRegister = sal_False;
m_xTargetProvider = 0;
Reference< XParameterizedContentProvider >
xParamProvider( m_xProvider, UNO_QUERY );
if ( xParamProvider.is() )
{
try
{
xParamProvider->deregisterInstance( Template, Arguments );
}
catch ( IllegalIdentifierException const & )
{
OSL_ENSURE( sal_False,
"UcbContentProviderProxy::deregisterInstance - "
"Caught IllegalIdentifierException!" );
}
}
}
return this;
}
//=========================================================================
//
// XContentProviderSupplier methods.
//
//=========================================================================
// virtual
Reference< XContentProvider > SAL_CALL
UcbContentProviderProxy::getContentProvider()
throw( RuntimeException )
{
osl::Guard< osl::Mutex > aGuard( m_aMutex );
if ( !m_xProvider.is() )
{
try
{
m_xProvider
= Reference< XContentProvider >(
m_xSMgr->createInstance( m_aService ), UNO_QUERY );
}
catch ( RuntimeException const & )
{
throw;
}
catch ( Exception const & )
{
}
// registerInstance called at proxy, but not yet at original?
if ( m_xProvider.is() && m_bRegister )
{
Reference< XParameterizedContentProvider >
xParamProvider( m_xProvider, UNO_QUERY );
if ( xParamProvider.is() )
{
try
{
m_xTargetProvider
= xParamProvider->registerInstance( m_aTemplate,
m_aArguments,
m_bReplace );
}
catch ( IllegalIdentifierException const & )
{
OSL_ENSURE( sal_False,
"UcbContentProviderProxy::getContentProvider - "
"Caught IllegalIdentifierException!" );
}
OSL_ENSURE( m_xTargetProvider.is(),
"UcbContentProviderProxy::getContentProvider - "
"No provider!" );
}
}
if ( !m_xTargetProvider.is() )
m_xTargetProvider = m_xProvider;
}
OSL_ENSURE( m_xProvider.is(),
"UcbContentProviderProxy::getContentProvider - No provider!" );
return m_xTargetProvider;
}
<commit_msg>INTEGRATION: CWS fwk21 (1.4.96); FILE MERGED 2005/08/16 14:12:07 abi 1.4.96.1: #i47166# assertion wrong in case of no provider, because schemes are not determined during configuration time<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: provprox.cxx,v $
*
* $Revision: 1.6 $
*
* last change: $Author: hr $ $Date: 2005-09-30 10:09:44 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _OSL_DIAGNOSE_H_
#include <osl/diagnose.h>
#endif
#ifndef _PROVPROX_HXX
#include "provprox.hxx"
#endif
using namespace rtl;
using namespace com::sun::star::lang;
using namespace com::sun::star::ucb;
using namespace com::sun::star::uno;
//=========================================================================
//=========================================================================
//
// UcbContentProviderProxyFactory Implementation.
//
//=========================================================================
//=========================================================================
UcbContentProviderProxyFactory::UcbContentProviderProxyFactory(
const Reference< XMultiServiceFactory >& rxSMgr )
: m_xSMgr( rxSMgr )
{
}
//=========================================================================
// virtual
UcbContentProviderProxyFactory::~UcbContentProviderProxyFactory()
{
}
//=========================================================================
//
// XInterface methods.
//
//=========================================================================
XINTERFACE_IMPL_3( UcbContentProviderProxyFactory,
XTypeProvider,
XServiceInfo,
XContentProviderFactory );
//=========================================================================
//
// XTypeProvider methods.
//
//=========================================================================
XTYPEPROVIDER_IMPL_3( UcbContentProviderProxyFactory,
XTypeProvider,
XServiceInfo,
XContentProviderFactory );
//=========================================================================
//
// XServiceInfo methods.
//
//=========================================================================
XSERVICEINFO_IMPL_1( UcbContentProviderProxyFactory,
OUString::createFromAscii(
"com.sun.star.comp.ucb.UcbContentProviderProxyFactory" ),
OUString::createFromAscii(
PROVIDER_FACTORY_SERVICE_NAME ) );
//=========================================================================
//
// Service factory implementation.
//
//=========================================================================
ONE_INSTANCE_SERVICE_FACTORY_IMPL( UcbContentProviderProxyFactory );
//=========================================================================
//
// XContentProviderFactory methods.
//
//=========================================================================
// virtual
Reference< XContentProvider > SAL_CALL
UcbContentProviderProxyFactory::createContentProvider(
const OUString& Service )
throw( RuntimeException )
{
return Reference< XContentProvider >(
new UcbContentProviderProxy( m_xSMgr, Service ) );
}
//=========================================================================
//=========================================================================
//
// UcbContentProviderProxy Implementation.
//
//=========================================================================
//=========================================================================
UcbContentProviderProxy::UcbContentProviderProxy(
const Reference< XMultiServiceFactory >& rxSMgr,
const OUString& Service )
: m_aService( Service ),
m_bReplace( sal_False ),
m_bRegister( sal_False ),
m_xSMgr( rxSMgr )
{
}
//=========================================================================
// virtual
UcbContentProviderProxy::~UcbContentProviderProxy()
{
}
//=========================================================================
//
// XInterface methods.
//
//=========================================================================
XINTERFACE_COMMON_IMPL( UcbContentProviderProxy );
//============================================================================
// virtual
Any SAL_CALL
UcbContentProviderProxy::queryInterface( const Type & rType )
throw ( RuntimeException )
{
Any aRet = cppu::queryInterface( rType,
static_cast< XTypeProvider * >( this ),
static_cast< XServiceInfo * >( this ),
static_cast< XContentProvider * >( this ),
static_cast< XParameterizedContentProvider * >( this ),
static_cast< XContentProviderSupplier * >( this ) );
if ( !aRet.hasValue() )
aRet = OWeakObject::queryInterface( rType );
if ( !aRet.hasValue() )
{
// Get original provider an forward the call...
osl::Guard< osl::Mutex > aGuard( m_aMutex );
Reference< XInterface > xProvider = getContentProvider();
if ( xProvider.is() )
aRet = xProvider->queryInterface( rType );
}
return aRet;
}
//=========================================================================
//
// XTypeProvider methods.
//
//=========================================================================
XTYPEPROVIDER_COMMON_IMPL( UcbContentProviderProxy );
//=========================================================================
Sequence< Type > SAL_CALL UcbContentProviderProxy::getTypes() \
throw( RuntimeException )
{
// Get original provider an forward the call...
osl::Guard< osl::Mutex > aGuard( m_aMutex );
Reference< XTypeProvider > xProvider( getContentProvider(), UNO_QUERY );
if ( xProvider.is() )
{
return xProvider->getTypes();
}
else
{
static cppu::OTypeCollection * pCollection = 0;
if ( !pCollection )
{
osl::Guard< osl::Mutex > aGuard( m_aMutex );
if ( !pCollection )
{
static cppu::OTypeCollection collection(
CPPU_TYPE_REF( XTypeProvider ),
CPPU_TYPE_REF( XServiceInfo ),
CPPU_TYPE_REF( XContentProvider ),
CPPU_TYPE_REF( XParameterizedContentProvider ),
CPPU_TYPE_REF( XContentProviderSupplier ) );
pCollection = &collection;
}
}
return (*pCollection).getTypes();
}
}
//=========================================================================
//
// XServiceInfo methods.
//
//=========================================================================
XSERVICEINFO_NOFACTORY_IMPL_1( UcbContentProviderProxy,
OUString::createFromAscii(
"com.sun.star.comp.ucb.UcbContentProviderProxy" ),
OUString::createFromAscii(
PROVIDER_PROXY_SERVICE_NAME ) );
//=========================================================================
//
// XContentProvider methods.
//
//=========================================================================
// virtual
Reference< XContent > SAL_CALL UcbContentProviderProxy::queryContent(
const Reference< XContentIdentifier >& Identifier )
throw( IllegalIdentifierException,
RuntimeException )
{
// Get original provider an forward the call...
osl::Guard< osl::Mutex > aGuard( m_aMutex );
Reference< XContentProvider > xProvider = getContentProvider();
if ( xProvider.is() )
return xProvider->queryContent( Identifier );
return Reference< XContent >();
}
//=========================================================================
// virtual
sal_Int32 SAL_CALL UcbContentProviderProxy::compareContentIds(
const Reference< XContentIdentifier >& Id1,
const Reference< XContentIdentifier >& Id2 )
throw( RuntimeException )
{
// Get original provider an forward the call...
osl::Guard< osl::Mutex > aGuard( m_aMutex );
Reference< XContentProvider > xProvider = getContentProvider();
if ( xProvider.is() )
return xProvider->compareContentIds( Id1, Id2 );
// OSL_ENSURE( sal_False,
// "UcbContentProviderProxy::compareContentIds - No provider!" );
// @@@ What else?
return 0;
}
//=========================================================================
//
// XParameterizedContentProvider methods.
//
//=========================================================================
// virtual
Reference< XContentProvider > SAL_CALL
UcbContentProviderProxy::registerInstance( const OUString& Template,
const OUString& Arguments,
sal_Bool ReplaceExisting )
throw( IllegalArgumentException,
RuntimeException )
{
// Just remember that this method was called ( and the params ).
osl::Guard< osl::Mutex > aGuard( m_aMutex );
if ( !m_bRegister )
{
// m_xTargetProvider = 0;
m_aTemplate = Template;
m_aArguments = Arguments;
m_bReplace = ReplaceExisting;
m_bRegister = sal_True;
}
return this;
}
//=========================================================================
// virtual
Reference< XContentProvider > SAL_CALL
UcbContentProviderProxy::deregisterInstance( const OUString& Template,
const OUString& Arguments )
throw( IllegalArgumentException,
RuntimeException )
{
osl::Guard< osl::Mutex > aGuard( m_aMutex );
// registerInstance called at proxy and at original?
if ( m_bRegister && m_xTargetProvider.is() )
{
m_bRegister = sal_False;
m_xTargetProvider = 0;
Reference< XParameterizedContentProvider >
xParamProvider( m_xProvider, UNO_QUERY );
if ( xParamProvider.is() )
{
try
{
xParamProvider->deregisterInstance( Template, Arguments );
}
catch ( IllegalIdentifierException const & )
{
OSL_ENSURE( sal_False,
"UcbContentProviderProxy::deregisterInstance - "
"Caught IllegalIdentifierException!" );
}
}
}
return this;
}
//=========================================================================
//
// XContentProviderSupplier methods.
//
//=========================================================================
// virtual
Reference< XContentProvider > SAL_CALL
UcbContentProviderProxy::getContentProvider()
throw( RuntimeException )
{
osl::Guard< osl::Mutex > aGuard( m_aMutex );
if ( !m_xProvider.is() )
{
try
{
m_xProvider
= Reference< XContentProvider >(
m_xSMgr->createInstance( m_aService ), UNO_QUERY );
}
catch ( RuntimeException const & )
{
throw;
}
catch ( Exception const & )
{
}
// registerInstance called at proxy, but not yet at original?
if ( m_xProvider.is() && m_bRegister )
{
Reference< XParameterizedContentProvider >
xParamProvider( m_xProvider, UNO_QUERY );
if ( xParamProvider.is() )
{
try
{
m_xTargetProvider
= xParamProvider->registerInstance( m_aTemplate,
m_aArguments,
m_bReplace );
}
catch ( IllegalIdentifierException const & )
{
OSL_ENSURE( sal_False,
"UcbContentProviderProxy::getContentProvider - "
"Caught IllegalIdentifierException!" );
}
OSL_ENSURE( m_xTargetProvider.is(),
"UcbContentProviderProxy::getContentProvider - "
"No provider!" );
}
}
if ( !m_xTargetProvider.is() )
m_xTargetProvider = m_xProvider;
}
OSL_ENSURE( m_xProvider.is(),
"UcbContentProviderProxy::getContentProvider - No provider!" );
return m_xTargetProvider;
}
<|endoftext|> |
<commit_before>#include "store-api.hh"
#include "globals.hh"
#include "util.hh"
#include <climits>
namespace nix {
GCOptions::GCOptions()
{
action = gcDeleteDead;
ignoreLiveness = false;
maxFreed = ULLONG_MAX;
}
bool isInStore(const Path & path)
{
return isInDir(path, settings.nixStore);
}
bool isStorePath(const Path & path)
{
return isInStore(path)
&& path.find('/', settings.nixStore.size() + 1) == Path::npos;
}
void assertStorePath(const Path & path)
{
if (!isStorePath(path))
throw Error(format("path `%1%' is not in the Nix store") % path);
}
Path toStorePath(const Path & path)
{
if (!isInStore(path))
throw Error(format("path `%1%' is not in the Nix store") % path);
Path::size_type slash = path.find('/', settings.nixStore.size() + 1);
if (slash == Path::npos)
return path;
else
return Path(path, 0, slash);
}
Path followLinksToStore(const Path & _path)
{
Path path = absPath(_path);
while (!isInStore(path)) {
if (!isLink(path)) break;
string target = readLink(path);
path = absPath(target, dirOf(path));
}
if (!isInStore(path))
throw Error(format("path `%1%' is not in the Nix store") % path);
return path;
}
Path followLinksToStorePath(const Path & path)
{
return toStorePath(followLinksToStore(path));
}
string storePathToName(const Path & path)
{
assertStorePath(path);
return string(path, settings.nixStore.size() + 34);
}
void checkStoreName(const string & name)
{
string validChars = "+-._?=";
/* Disallow names starting with a dot for possible security
reasons (e.g., "." and ".."). */
if (string(name, 0, 1) == ".")
throw Error(format("illegal name: `%1%'") % name);
foreach (string::const_iterator, i, name)
if (!((*i >= 'A' && *i <= 'Z') ||
(*i >= 'a' && *i <= 'z') ||
(*i >= '0' && *i <= '9') ||
validChars.find(*i) != string::npos))
{
throw Error(format("invalid character `%1%' in name `%2%'")
% *i % name);
}
}
/* Store paths have the following form:
<store>/<h>-<name>
where
<store> = the location of the Nix store, usually /nix/store
<name> = a human readable name for the path, typically obtained
from the name attribute of the derivation, or the name of the
source file from which the store path is created. For derivation
outputs other than the default "out" output, the string "-<id>"
is suffixed to <name>.
<h> = base-32 representation of the first 160 bits of a SHA-256
hash of <s>; the hash part of the store name
<s> = the string "<type>:sha256:<h2>:<store>:<name>";
note that it includes the location of the store as well as the
name to make sure that changes to either of those are reflected
in the hash (e.g. you won't get /nix/store/<h>-name1 and
/nix/store/<h>-name2 with equal hash parts).
<type> = one of:
"text:<r1>:<r2>:...<rN>"
for plain text files written to the store using
addTextToStore(); <r1> ... <rN> are the references of the
path.
"source"
for paths copied to the store using addToStore() when recursive
= true and hashAlgo = "sha256"
"output:<id>"
for either the outputs created by derivations, OR paths copied
to the store using addToStore() with recursive != true or
hashAlgo != "sha256" (in that case "source" is used; it's
silly, but it's done that way for compatibility). <id> is the
name of the output (usually, "out").
<h2> = base-16 representation of a SHA-256 hash of:
if <type> = "text:...":
the string written to the resulting store path
if <type> = "source":
the serialisation of the path from which this store path is
copied, as returned by hashPath()
if <type> = "output:out":
for non-fixed derivation outputs:
the derivation (see hashDerivationModulo() in
primops.cc)
for paths copied by addToStore() or produced by fixed-output
derivations:
the string "fixed:out:<rec><algo>:<hash>:", where
<rec> = "r:" for recursive (path) hashes, or "" or flat
(file) hashes
<algo> = "md5", "sha1" or "sha256"
<hash> = base-16 representation of the path or flat hash of
the contents of the path (or expected contents of the
path for fixed-output derivations)
It would have been nicer to handle fixed-output derivations under
"source", e.g. have something like "source:<rec><algo>", but we're
stuck with this for now...
The main reason for this way of computing names is to prevent name
collisions (for security). For instance, it shouldn't be feasible
to come up with a derivation whose output path collides with the
path for a copied source. The former would have a <s> starting with
"output:out:", while the latter would have a <2> starting with
"source:".
*/
Path makeStorePath(const string & type,
const Hash & hash, const string & name)
{
/* e.g., "source:sha256:1abc...:/nix/store:foo.tar.gz" */
string s = type + ":sha256:" + printHash(hash) + ":"
+ settings.nixStore + ":" + name;
checkStoreName(name);
return settings.nixStore + "/"
+ printHash32(compressHash(hashString(htSHA256, s), 20))
+ "-" + name;
}
Path makeOutputPath(const string & id,
const Hash & hash, const string & name)
{
return makeStorePath("output:" + id, hash,
name + (id == "out" ? "" : "-" + id));
}
Path makeFixedOutputPath(bool recursive,
HashType hashAlgo, Hash hash, string name)
{
return hashAlgo == htSHA256 && recursive
? makeStorePath("source", hash, name)
: makeStorePath("output:out", hashString(htSHA256,
"fixed:out:" + (recursive ? (string) "r:" : "") +
printHashType(hashAlgo) + ":" + printHash(hash) + ":"),
name);
}
std::pair<Path, Hash> computeStorePathForPath(const Path & srcPath,
bool recursive, HashType hashAlgo, PathFilter & filter)
{
HashType ht(hashAlgo);
Hash h = recursive ? hashPath(ht, srcPath, filter).first : hashFile(ht, srcPath);
string name = baseNameOf(srcPath);
Path dstPath = makeFixedOutputPath(recursive, hashAlgo, h, name);
return std::pair<Path, Hash>(dstPath, h);
}
Path computeStorePathForText(const string & name, const string & s,
const PathSet & references)
{
Hash hash = hashString(htSHA256, s);
/* Stuff the references (if any) into the type. This is a bit
hacky, but we can't put them in `s' since that would be
ambiguous. */
string type = "text";
foreach (PathSet::const_iterator, i, references) {
type += ":";
type += *i;
}
return makeStorePath(type, hash, name);
}
/* Return a string accepted by decodeValidPathInfo() that
registers the specified paths as valid. Note: it's the
responsibility of the caller to provide a closure. */
string StoreAPI::makeValidityRegistration(const PathSet & paths,
bool showDerivers, bool showHash)
{
string s = "";
foreach (PathSet::iterator, i, paths) {
s += *i + "\n";
ValidPathInfo info = queryPathInfo(*i);
if (showHash) {
s += printHash(info.hash) + "\n";
s += (format("%1%\n") % info.narSize).str();
}
Path deriver = showDerivers ? info.deriver : "";
s += deriver + "\n";
s += (format("%1%\n") % info.references.size()).str();
foreach (PathSet::iterator, j, info.references)
s += *j + "\n";
}
return s;
}
void StoreAPI::serve(Source & in, Sink & out, bool sign)
{
string cmd = readString(in);
if (cmd == "query") {
for (cmd = readString(in); !cmd.empty(); cmd = readString(in)) {
PathSet paths = readStrings<PathSet>(in);
if (cmd == "have") {
writeStrings(queryValidPaths(paths), out);
} else if (cmd == "info") {
// !!! Maybe we want a queryPathInfos?
foreach (PathSet::iterator, i, paths) {
ValidPathInfo info = queryPathInfo(*i);
writeString(info.path, out);
writeString(info.deriver, out);
writeStrings(info.references, out);
// !!! Maybe we want compression?
writeLongLong(info.narSize, out); // downloadSize
writeLongLong(info.narSize, out);
}
writeString("", out);
} else
throw Error(format("Unknown serve query `%1%'") % cmd);
}
} else if (cmd == "substitute")
exportPath(readString(in), sign, out);
else
throw Error(format("Unknown serve command `%1%'") % cmd);
}
ValidPathInfo decodeValidPathInfo(std::istream & str, bool hashGiven)
{
ValidPathInfo info;
getline(str, info.path);
if (str.eof()) { info.path = ""; return info; }
if (hashGiven) {
string s;
getline(str, s);
info.hash = parseHash(htSHA256, s);
getline(str, s);
if (!string2Int(s, info.narSize)) throw Error("number expected");
}
getline(str, info.deriver);
string s; int n;
getline(str, s);
if (!string2Int(s, n)) throw Error("number expected");
while (n--) {
getline(str, s);
info.references.insert(s);
}
if (!str || str.eof()) throw Error("missing input");
return info;
}
string showPaths(const PathSet & paths)
{
string s;
foreach (PathSet::const_iterator, i, paths) {
if (s.size() != 0) s += ", ";
s += "`" + *i + "'";
}
return s;
}
void exportPaths(StoreAPI & store, const Paths & paths,
bool sign, Sink & sink)
{
foreach (Paths::const_iterator, i, paths) {
writeInt(1, sink);
store.exportPath(*i, sign, sink);
}
writeInt(0, sink);
}
}
#include "local-store.hh"
#include "serialise.hh"
#include "remote-store.hh"
namespace nix {
boost::shared_ptr<StoreAPI> store;
boost::shared_ptr<StoreAPI> openStore(bool reserveSpace)
{
if (getEnv("NIX_REMOTE") == "")
return boost::shared_ptr<StoreAPI>(new LocalStore(reserveSpace));
else
return boost::shared_ptr<StoreAPI>(new RemoteStore());
}
}
<commit_msg>nix-store --serve: Don't fail if asked for info about non-valid path<commit_after>#include "store-api.hh"
#include "globals.hh"
#include "util.hh"
#include <climits>
namespace nix {
GCOptions::GCOptions()
{
action = gcDeleteDead;
ignoreLiveness = false;
maxFreed = ULLONG_MAX;
}
bool isInStore(const Path & path)
{
return isInDir(path, settings.nixStore);
}
bool isStorePath(const Path & path)
{
return isInStore(path)
&& path.find('/', settings.nixStore.size() + 1) == Path::npos;
}
void assertStorePath(const Path & path)
{
if (!isStorePath(path))
throw Error(format("path `%1%' is not in the Nix store") % path);
}
Path toStorePath(const Path & path)
{
if (!isInStore(path))
throw Error(format("path `%1%' is not in the Nix store") % path);
Path::size_type slash = path.find('/', settings.nixStore.size() + 1);
if (slash == Path::npos)
return path;
else
return Path(path, 0, slash);
}
Path followLinksToStore(const Path & _path)
{
Path path = absPath(_path);
while (!isInStore(path)) {
if (!isLink(path)) break;
string target = readLink(path);
path = absPath(target, dirOf(path));
}
if (!isInStore(path))
throw Error(format("path `%1%' is not in the Nix store") % path);
return path;
}
Path followLinksToStorePath(const Path & path)
{
return toStorePath(followLinksToStore(path));
}
string storePathToName(const Path & path)
{
assertStorePath(path);
return string(path, settings.nixStore.size() + 34);
}
void checkStoreName(const string & name)
{
string validChars = "+-._?=";
/* Disallow names starting with a dot for possible security
reasons (e.g., "." and ".."). */
if (string(name, 0, 1) == ".")
throw Error(format("illegal name: `%1%'") % name);
foreach (string::const_iterator, i, name)
if (!((*i >= 'A' && *i <= 'Z') ||
(*i >= 'a' && *i <= 'z') ||
(*i >= '0' && *i <= '9') ||
validChars.find(*i) != string::npos))
{
throw Error(format("invalid character `%1%' in name `%2%'")
% *i % name);
}
}
/* Store paths have the following form:
<store>/<h>-<name>
where
<store> = the location of the Nix store, usually /nix/store
<name> = a human readable name for the path, typically obtained
from the name attribute of the derivation, or the name of the
source file from which the store path is created. For derivation
outputs other than the default "out" output, the string "-<id>"
is suffixed to <name>.
<h> = base-32 representation of the first 160 bits of a SHA-256
hash of <s>; the hash part of the store name
<s> = the string "<type>:sha256:<h2>:<store>:<name>";
note that it includes the location of the store as well as the
name to make sure that changes to either of those are reflected
in the hash (e.g. you won't get /nix/store/<h>-name1 and
/nix/store/<h>-name2 with equal hash parts).
<type> = one of:
"text:<r1>:<r2>:...<rN>"
for plain text files written to the store using
addTextToStore(); <r1> ... <rN> are the references of the
path.
"source"
for paths copied to the store using addToStore() when recursive
= true and hashAlgo = "sha256"
"output:<id>"
for either the outputs created by derivations, OR paths copied
to the store using addToStore() with recursive != true or
hashAlgo != "sha256" (in that case "source" is used; it's
silly, but it's done that way for compatibility). <id> is the
name of the output (usually, "out").
<h2> = base-16 representation of a SHA-256 hash of:
if <type> = "text:...":
the string written to the resulting store path
if <type> = "source":
the serialisation of the path from which this store path is
copied, as returned by hashPath()
if <type> = "output:out":
for non-fixed derivation outputs:
the derivation (see hashDerivationModulo() in
primops.cc)
for paths copied by addToStore() or produced by fixed-output
derivations:
the string "fixed:out:<rec><algo>:<hash>:", where
<rec> = "r:" for recursive (path) hashes, or "" or flat
(file) hashes
<algo> = "md5", "sha1" or "sha256"
<hash> = base-16 representation of the path or flat hash of
the contents of the path (or expected contents of the
path for fixed-output derivations)
It would have been nicer to handle fixed-output derivations under
"source", e.g. have something like "source:<rec><algo>", but we're
stuck with this for now...
The main reason for this way of computing names is to prevent name
collisions (for security). For instance, it shouldn't be feasible
to come up with a derivation whose output path collides with the
path for a copied source. The former would have a <s> starting with
"output:out:", while the latter would have a <2> starting with
"source:".
*/
Path makeStorePath(const string & type,
const Hash & hash, const string & name)
{
/* e.g., "source:sha256:1abc...:/nix/store:foo.tar.gz" */
string s = type + ":sha256:" + printHash(hash) + ":"
+ settings.nixStore + ":" + name;
checkStoreName(name);
return settings.nixStore + "/"
+ printHash32(compressHash(hashString(htSHA256, s), 20))
+ "-" + name;
}
Path makeOutputPath(const string & id,
const Hash & hash, const string & name)
{
return makeStorePath("output:" + id, hash,
name + (id == "out" ? "" : "-" + id));
}
Path makeFixedOutputPath(bool recursive,
HashType hashAlgo, Hash hash, string name)
{
return hashAlgo == htSHA256 && recursive
? makeStorePath("source", hash, name)
: makeStorePath("output:out", hashString(htSHA256,
"fixed:out:" + (recursive ? (string) "r:" : "") +
printHashType(hashAlgo) + ":" + printHash(hash) + ":"),
name);
}
std::pair<Path, Hash> computeStorePathForPath(const Path & srcPath,
bool recursive, HashType hashAlgo, PathFilter & filter)
{
HashType ht(hashAlgo);
Hash h = recursive ? hashPath(ht, srcPath, filter).first : hashFile(ht, srcPath);
string name = baseNameOf(srcPath);
Path dstPath = makeFixedOutputPath(recursive, hashAlgo, h, name);
return std::pair<Path, Hash>(dstPath, h);
}
Path computeStorePathForText(const string & name, const string & s,
const PathSet & references)
{
Hash hash = hashString(htSHA256, s);
/* Stuff the references (if any) into the type. This is a bit
hacky, but we can't put them in `s' since that would be
ambiguous. */
string type = "text";
foreach (PathSet::const_iterator, i, references) {
type += ":";
type += *i;
}
return makeStorePath(type, hash, name);
}
/* Return a string accepted by decodeValidPathInfo() that
registers the specified paths as valid. Note: it's the
responsibility of the caller to provide a closure. */
string StoreAPI::makeValidityRegistration(const PathSet & paths,
bool showDerivers, bool showHash)
{
string s = "";
foreach (PathSet::iterator, i, paths) {
s += *i + "\n";
ValidPathInfo info = queryPathInfo(*i);
if (showHash) {
s += printHash(info.hash) + "\n";
s += (format("%1%\n") % info.narSize).str();
}
Path deriver = showDerivers ? info.deriver : "";
s += deriver + "\n";
s += (format("%1%\n") % info.references.size()).str();
foreach (PathSet::iterator, j, info.references)
s += *j + "\n";
}
return s;
}
void StoreAPI::serve(Source & in, Sink & out, bool sign)
{
string cmd = readString(in);
if (cmd == "query") {
for (cmd = readString(in); !cmd.empty(); cmd = readString(in)) {
PathSet paths = readStrings<PathSet>(in);
if (cmd == "have") {
writeStrings(queryValidPaths(paths), out);
} else if (cmd == "info") {
// !!! Maybe we want a queryPathInfos?
foreach (PathSet::iterator, i, paths) {
if (!isValidPath(*i))
continue;
ValidPathInfo info = queryPathInfo(*i);
writeString(info.path, out);
writeString(info.deriver, out);
writeStrings(info.references, out);
// !!! Maybe we want compression?
writeLongLong(info.narSize, out); // downloadSize
writeLongLong(info.narSize, out);
}
writeString("", out);
} else
throw Error(format("Unknown serve query `%1%'") % cmd);
}
} else if (cmd == "substitute")
exportPath(readString(in), sign, out);
else
throw Error(format("Unknown serve command `%1%'") % cmd);
}
ValidPathInfo decodeValidPathInfo(std::istream & str, bool hashGiven)
{
ValidPathInfo info;
getline(str, info.path);
if (str.eof()) { info.path = ""; return info; }
if (hashGiven) {
string s;
getline(str, s);
info.hash = parseHash(htSHA256, s);
getline(str, s);
if (!string2Int(s, info.narSize)) throw Error("number expected");
}
getline(str, info.deriver);
string s; int n;
getline(str, s);
if (!string2Int(s, n)) throw Error("number expected");
while (n--) {
getline(str, s);
info.references.insert(s);
}
if (!str || str.eof()) throw Error("missing input");
return info;
}
string showPaths(const PathSet & paths)
{
string s;
foreach (PathSet::const_iterator, i, paths) {
if (s.size() != 0) s += ", ";
s += "`" + *i + "'";
}
return s;
}
void exportPaths(StoreAPI & store, const Paths & paths,
bool sign, Sink & sink)
{
foreach (Paths::const_iterator, i, paths) {
writeInt(1, sink);
store.exportPath(*i, sign, sink);
}
writeInt(0, sink);
}
}
#include "local-store.hh"
#include "serialise.hh"
#include "remote-store.hh"
namespace nix {
boost::shared_ptr<StoreAPI> store;
boost::shared_ptr<StoreAPI> openStore(bool reserveSpace)
{
if (getEnv("NIX_REMOTE") == "")
return boost::shared_ptr<StoreAPI>(new LocalStore(reserveSpace));
else
return boost::shared_ptr<StoreAPI>(new RemoteStore());
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2013-2014 INRA
*
* 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 "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 __VLE_KERNEL_CONTEXT_HPP__
#define __VLE_KERNEL_CONTEXT_HPP__
#include <vle/export.hpp>
#include <boost/any.hpp>
#include <algorithm>
#include <functional>
#include <memory>
#include <cstdio>
#include <cstdarg>
#include <cstdint>
#include <cinttypes>
namespace vle {
struct ContextImpl;
typedef std::shared_ptr <ContextImpl> Context;
}
void vle_log_null(const vle::Context& ctx, const char *format, ...)
{
(void)ctx;
(void)format;
}
#if defined __GNUC__
#define VLE_PRINTF(format__, args__) __attribute__ ((format (printf, format__, args__)))
#endif
#define vle_log_cond(ctx, prio, arg...) \
do { \
if (ctx->get_log_priority() >= prio) \
ctx->log(prio, __FILE__, __LINE__, __FUNCTION__, ## arg); \
} while (0)
#define LOG_DEBUG 3
#define LOG_INFO 2
#define LOG_ERR 1
#ifdef ENABLE_LOGGING
# ifdef ENABLE_DEBUG
# define vle_dbg(ctx, arg...) vle_log_cond(ctx, LOG_DEBUG, ## arg)
# else
# define vle_dbg(ctx, arg...) vle_log_null(ctx, ## arg)
# endif
# define vle_info(ctx, arg...) vle_log_cond(ctx, LOG_INFO, ## arg)
# define vle_err(ctx, arg...) vle_log_cond(ctx, LOG_ERR, ## arg)
#else
# define vle_dbg(ctx, arg...) vle_log_null(ctx, ## arg)
# define vle_info(ctx, arg...) vle_log_null(ctx, ## arg)
# define vle_err(ctx, arg...) vle_log_null(ctx, ## arg)
#endif
namespace vle {
void log_to_stderr(const ContextImpl& ctx, int priority, const char *file,
int line, const char *fn, const char *format, va_list args);
/**
* Default @e ContextImpl initializes logger system with the standard error
* output (@e stderr).
*/
struct ContextImpl
{
ContextImpl()
: m_log_fn(log_to_stderr)
, m_thread_number(0)
, m_log_priority(1)
{}
ContextImpl(const ContextImpl&) = default;
ContextImpl& operator=(const ContextImpl&) = default;
ContextImpl(ContextImpl&&) = default;
ContextImpl& operator=(ContextImpl&&) = default;
~ContextImpl() = default;
typedef std::function <void(const ContextImpl& ctx, int priority,
const char *file, int line, const char *fn,
const char *format, va_list args)> log_fn;
void set_log_fn(log_fn fn)
{
m_log_fn = fn;
}
void log(int priority, const char *file, int line,
const char *fn, const char *formats, ...) VLE_PRINTF(6, 7)
{
if (m_log_priority >= priority) {
va_list args;
va_start(args, formats);
try {
m_log_fn(*this, priority, file, line, fn, formats, args);
} catch (...) {
}
va_end(args);
}
}
int get_log_priority() const
{
return m_log_priority;
}
void set_log_priority(int priority)
{
m_log_priority = std::max(std::min(priority, 3), 0);
}
unsigned get_thread_number() const
{
return m_thread_number;
}
void set_thread_number(unsigned thread_number)
{
m_thread_number = thread_number;
}
void set_user_data(const boost::any &user_data)
{
m_user_data = user_data;
}
const boost::any& get_user_data() const { return m_user_data; }
boost::any& get_user_data() { return m_user_data; }
private:
boost::any m_user_data;
log_fn m_log_fn;
unsigned int m_thread_number = 0;
int m_log_priority = 1;
};
void log_to_stderr(const ContextImpl& ctx, int priority, const char *file,
int line, const char *fn, const char *format, va_list args)
{
(void)ctx;
(void)priority;
(void)file;
(void)line;
fprintf(stderr, "echll: %s ", fn);
vfprintf(stderr, format, args);
}
}
#endif
<commit_msg>context: add color in stderr on tty<commit_after>/*
* Copyright (C) 2013-2014 INRA
*
* 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 "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 __VLE_KERNEL_CONTEXT_HPP__
#define __VLE_KERNEL_CONTEXT_HPP__
#include <vle/export.hpp>
#include <boost/any.hpp>
#include <algorithm>
#include <functional>
#include <memory>
#include <cstdio>
#include <cstdarg>
#include <cstdint>
#include <cinttypes>
#include <unistd.h>
#define ECHLL_YELLOW "\x1b[33m"
#define ECHLL_RED "\x1b[31m"
#define ECHLL_NORMAL "\x1b[0m"
namespace vle {
struct ContextImpl;
typedef std::shared_ptr <ContextImpl> Context;
}
void vle_log_null(const vle::Context& ctx, const char *format, ...)
{
(void)ctx;
(void)format;
}
#if defined __GNUC__
#define VLE_PRINTF(format__, args__) __attribute__ ((format (printf, format__, args__)))
#endif
#define vle_log_cond(ctx, prio, arg...) \
do { \
if (ctx->get_log_priority() >= prio) \
ctx->log(prio, __FILE__, __LINE__, \
__PRETTY_FUNCTION__, ## arg); \
} while (0)
#define LOG_DEBUG 3
#define LOG_INFO 2
#define LOG_ERR 1
#ifdef ENABLE_LOGGING
# ifdef ENABLE_DEBUG
# define vle_dbg(ctx, arg...) vle_log_cond(ctx, LOG_DEBUG, ## arg)
# else
# define vle_dbg(ctx, arg...) vle_log_null(ctx, ## arg)
# endif
# define vle_info(ctx, arg...) vle_log_cond(ctx, LOG_INFO, ## arg)
# define vle_err(ctx, arg...) vle_log_cond(ctx, LOG_ERR, ## arg)
#else
# define vle_dbg(ctx, arg...) vle_log_null(ctx, ## arg)
# define vle_info(ctx, arg...) vle_log_null(ctx, ## arg)
# define vle_err(ctx, arg...) vle_log_null(ctx, ## arg)
#endif
namespace vle {
void log_to_stderr(const ContextImpl& ctx, int priority, const char *file,
int line, const char *fn, const char *format, va_list args);
/**
* Default @e ContextImpl initializes logger system with the standard error
* output (@e stderr).
*/
struct ContextImpl
{
ContextImpl()
: m_log_fn(log_to_stderr)
, m_thread_number(0)
, m_log_priority(1)
, m_is_a_tty(fileno(stderr))
{}
ContextImpl(const ContextImpl&) = default;
ContextImpl& operator=(const ContextImpl&) = default;
ContextImpl(ContextImpl&&) = default;
ContextImpl& operator=(ContextImpl&&) = default;
~ContextImpl() = default;
typedef std::function <void(const ContextImpl& ctx, int priority,
const char *file, int line, const char *fn,
const char *format, va_list args)> log_fn;
void set_log_fn(log_fn fn)
{
m_log_fn = fn;
}
void log(int priority, const char *file, int line,
const char *fn, const char *formats, ...) VLE_PRINTF(6, 7)
{
if (m_log_priority >= priority) {
va_list args;
va_start(args, formats);
try {
m_log_fn(*this, priority, file, line, fn, formats, args);
} catch (...) {
}
va_end(args);
}
}
int get_log_priority() const
{
return m_log_priority;
}
void set_log_priority(int priority)
{
m_log_priority = std::max(std::min(priority, 3), 0);
}
unsigned get_thread_number() const
{
return m_thread_number;
}
void set_thread_number(unsigned thread_number)
{
m_thread_number = thread_number;
}
void set_user_data(const boost::any &user_data)
{
m_user_data = user_data;
}
bool is_on_tty() const
{
return m_is_a_tty;
}
const boost::any& get_user_data() const { return m_user_data; }
boost::any& get_user_data() { return m_user_data; }
private:
boost::any m_user_data;
log_fn m_log_fn;
unsigned int m_thread_number = 0;
int m_log_priority = 1;
bool m_is_a_tty;
};
void log_to_stderr(const ContextImpl& ctx, int priority, const char *file,
int line, const char *fn, const char *format, va_list args)
{
(void)ctx;
(void)priority;
(void)file;
(void)line;
if (ctx.is_on_tty()) {
fprintf(stderr, ECHLL_YELLOW "echll:" ECHLL_RED " %s\n\t"
ECHLL_NORMAL, fn);
} else {
fprintf(stderr, "echll: %s\n\t", fn);
}
vfprintf(stderr, format, args);
}
}
#endif
<|endoftext|> |
<commit_before>#include "console.h"
#include <iostream>
#include <string>
#include <vector>
#include "person.h"
#include <algorithm>
#include "data.h"
#include <cctype>
#include <ctype.h>
using namespace std;
Console::Console()
{
}
bool Console::validYear(string s)
{
for (unsigned int i = 0; i < s.size(); i++)
if (!isdigit(s[i]))
return 0;
return 1;
}
void Console::getInfo()
{
_pers = _dat.readData();
string command;
string anotherOne;
do
{
menu(command);
if ((command == "Add") || (command == "add"))
{
add(anotherOne);
}
else if ((command == "View") || (command == "view"))
{
_pers = _dat.readData();
display();
}
else if ((command == "Search") || (command == "search"))
{
displaySearch();
}
else if ((command == "Sort") || (command == "sort"))
{
_pers = _dat.readData();
int sortType = getSort();
displaySort(sortType);
}
}while((command != "Exit") && (command != "exit"));
}
int Console::getSort()
{
int sort;
string sortInput;
do
{
cout << endl;
cout << "Please enter one of the following commands: " << endl;
cout << "-------------------------------------------" << endl;
cout << "1 - sort by alphabetical order" << endl;
cout << "2 - sort by year of birth" << endl;
cin >> sortInput;
if(atoi(sortInput.c_str()) != 1 && atoi(sortInput.c_str()) != 2)
cout << "Invalid input" << endl;
}while(atoi(sortInput.c_str()) != 1 && atoi(sortInput.c_str()) != 2);
sort = atoi(sortInput.c_str());
return sort;
}
void Console::displaySort(int& sort)
{
_dat.readData();
if(sort == 1)
{
_dom.alphabeticSort(_pers);
display();
}
else if (sort == 2)
{
_dom.ageSorting(_pers);
display();
}
}
void Console::display()
{
cout << endl;
cout << "NAME:" << "\t\t\t\t" << "GENDER:" << "\t" << "BORN:" << "\t" << "DIED:" << endl;
for(unsigned int i = 0; i < _pers.size(); i++)
{
//int nameSize = _p.getNameSize();
int nameSize = _pers[i].getNameSize();
if (nameSize >= 0 && nameSize <= 7)
{
cout << _pers[i].getName() << "\t\t\t\t";
}
else if (nameSize >= 8 && nameSize <= 15)
{
cout << _pers[i].getName() << "\t\t\t";
}
else if (nameSize >= 16 && nameSize <= 23)
{
cout << _pers[i].getName() << "\t\t";
}
else if (nameSize >= 24 && nameSize <= 31)
{
cout << _pers[i].getName() << "\t";
}
if (_pers[i].getGender() == 'm')
cout << "Male" << "\t";
else if (_pers[i].getGender() == 'f')
cout << "Female" << "\t";
cout << _pers[i].getGender() << "\t";
if(_pers[i].getDeath() == 0)
{
cout << "N/A" << endl;
}
else
{
cout << _pers[i].getDeath() << endl;
}
}cout << endl;
}
void Console::menu(string& command)
{
cout << endl << "--------------------------------------------" << endl;
cout << "Please enter one of the following commands: " << endl << endl;
cout << "Add - for adding scientist to the list" << endl;
cout << "View - for viewing the whole list" << endl;
cout << "Search - for searching for names in the list" << endl;
cout << "Sort - for sorting" << endl;
cout << "Exit - quits" << endl;
cout << "--------------------------------------------" << endl << endl;
cin >> command;
}
void Console::add(string& anotherOne)
{
do{
std::string name;
char gender;
int birth = 0;
int death = 0;
addName(name);
addGender(gender);
addBirth(birth);
addDeath(death, birth);
addAnother(anotherOne);
Person newData(name, gender, birth, death);
_dat.writeData(newData);
}while(anotherOne == "y" || anotherOne == "Y");
}
void Console::addName(std::string& name)
{
cout << endl << "Enter name of scientist: ";
cin.ignore();
std::getline(std::cin, name);
}
void Console::addGender(char& gender)
{
do
{
cout << "Gender (f/m): ";
cin >> gender;
if(!(gender == 'm') && !(gender == 'f'))
cout << "Invalid input!" << endl;
}while((gender != 'f') && (gender != 'm'));
}
void Console::addBirth(int& birth)
{
string birthInput;
do{
cout << "Enter year of birth: ";
cin >> birthInput;
if(!validYear(birthInput))
{
cout << "Invalid input!" <<endl;
}
else if (atoi(birthInput.c_str()) > 2016)
{
cout << "The scientist is not born yet.." << endl;
}
}
while(!validYear(birthInput) || atoi(birthInput.c_str()) > 2016);
birth = atoi(birthInput.c_str());
}
void Console::addDeath(int& death, int& birth)
{
string deathInput;
string status;
do
{
cout << "Is the person alive? (Y/N): ";
cin >> status;
if(!(status == "N" || status == "n") && !(status == "Y" || status == "y"))
cout << "Invalid Input!";
if(status == "N" || status == "n")
{
do
{
cout << "Enter year of death : ";
cin >> deathInput;
if((!validYear(deathInput)) || (atoi(deathInput.c_str()) < birth))
{
cout << "Invalid input!" <<endl;
}
}
while((!validYear(deathInput)) || (atoi(deathInput.c_str()) < birth));
death = atoi(deathInput.c_str());
}
cout << endl;
}
while(!(status == "N" || status == "n") && !(status == "Y" || status == "y"));
}
void Console::addAnother(string &anotherOne)
{
do
{
cout << "Add another? (Y/N): ";
cin >> anotherOne;
if(!(anotherOne == "N" || anotherOne == "n") && !(anotherOne == "Y" || anotherOne == "y"))
cout << "Invalid Input!" <<endl;
}
while(!(anotherOne == "N" || anotherOne == "n") && !(anotherOne == "Y" || anotherOne == "y"));
}
string Console::searchName()
{
string chosenName;
cout << "Who would you like to seach for? ";
cin >> chosenName;
return chosenName;
}
vector<Person> Console::getVector()
{
return _pers;
}
void Console::displaySearch()
{
string name = searchName();
cout << _dom.search(_pers, name).getName() << endl;
cout << _dom.search(_pers, name).getGender() << endl;
cout << _dom.search(_pers, name).getBirth() << endl;
cout << _dom.search(_pers, name).getDeath() << endl;
}
<commit_msg>Baett vid villutjekk a f\m, haegt ad gera stort F\M, ekki haegt ad setja death fram i timann lengur<commit_after>#include "console.h"
#include <iostream>
#include <string>
#include <vector>
#include "person.h"
#include <algorithm>
#include "data.h"
#include <cctype>
#include <ctype.h>
using namespace std;
Console::Console()
{
}
bool Console::validYear(string s)
{
for (unsigned int i = 0; i < s.size(); i++)
if (!isdigit(s[i]))
return 0;
return 1;
}
void Console::getInfo()
{
_pers = _dat.readData();
string command;
string anotherOne;
do
{
menu(command);
if ((command == "Add") || (command == "add"))
{
add(anotherOne);
}
else if ((command == "View") || (command == "view"))
{
_pers = _dat.readData();
display();
}
else if ((command == "Search") || (command == "search"))
{
displaySearch();
}
else if ((command == "Sort") || (command == "sort"))
{
_pers = _dat.readData();
int sortType = getSort();
displaySort(sortType);
}
}while((command != "Exit") && (command != "exit"));
}
int Console::getSort()
{
int sort;
string sortInput;
do
{
cout << endl;
cout << "Please enter one of the following commands: " << endl;
cout << "-------------------------------------------" << endl;
cout << "1 - sort by alphabetical order" << endl;
cout << "2 - sort by year of birth" << endl;
cin >> sortInput;
if(atoi(sortInput.c_str()) != 1 && atoi(sortInput.c_str()) != 2)
cout << "Invalid input" << endl;
}while(atoi(sortInput.c_str()) != 1 && atoi(sortInput.c_str()) != 2);
sort = atoi(sortInput.c_str());
return sort;
}
void Console::displaySort(int& sort)
{
_dat.readData();
if(sort == 1)
{
_dom.alphabeticSort(_pers);
display();
}
else if (sort == 2)
{
_dom.ageSorting(_pers);
display();
}
}
void Console::display()
{
cout << endl;
cout << "NAME:" << "\t\t\t\t" << "GENDER:" << "\t" << "BORN:" << "\t" << "DIED:" << endl;
for(unsigned int i = 0; i < _pers.size(); i++)
{
//int nameSize = _p.getNameSize();
int nameSize = _pers[i].getNameSize();
if (nameSize >= 0 && nameSize <= 7)
{
cout << _pers[i].getName() << "\t\t\t\t";
}
else if (nameSize >= 8 && nameSize <= 15)
{
cout << _pers[i].getName() << "\t\t\t";
}
else if (nameSize >= 16 && nameSize <= 23)
{
cout << _pers[i].getName() << "\t\t";
}
else if (nameSize >= 24 && nameSize <= 31)
{
cout << _pers[i].getName() << "\t";
}
if (_pers[i].getGender() == 'm' || _pers[i].getGender() == 'M')
cout << "Male" << "\t";
else if (_pers[i].getGender() == 'f' || _pers[i].getGender() == 'F')
cout << "Female" << "\t";
cout << _pers[i].getBirth() << "\t";
if(_pers[i].getDeath() == 0)
{
cout << "N/A" << endl;
}
else
{
cout << _pers[i].getDeath() << endl;
}
}cout << endl;
}
void Console::menu(string& command)
{
cout << endl << "--------------------------------------------" << endl;
cout << "Please enter one of the following commands: " << endl << endl;
cout << "Add - for adding scientist to the list" << endl;
cout << "View - for viewing the whole list" << endl;
cout << "Search - for searching for names in the list" << endl;
cout << "Sort - for sorting" << endl;
cout << "Exit - quits" << endl;
cout << "--------------------------------------------" << endl << endl;
cin >> command;
}
void Console::add(string& anotherOne)
{
do{
std::string name;
char gender;
int birth = 0;
int death = 0;
addName(name);
addGender(gender);
addBirth(birth);
addDeath(death, birth);
addAnother(anotherOne);
Person newData(name, gender, birth, death);
_dat.writeData(newData);
}while(anotherOne == "y" || anotherOne == "Y");
}
void Console::addName(std::string& name)
{
cout << endl << "Enter name of scientist: ";
cin.ignore();
std::getline(std::cin, name);
}
void Console::addGender(char& gender)
{
do
{
cout << "Gender (f/m): ";
std::string genderS;
std::getline(std::cin, genderS);
if(genderS.length() != 1)
cout << "Please only enter f or m." << endl;
else
{
gender = genderS[0];
if(!(gender == 'm' || gender == 'M') && !(gender == 'f' || gender == 'F'))
cout << "Please only enter f or m." << endl;
}
}while(!(gender == 'f' || gender == 'F') && !(gender == 'm' || gender == 'M'));
}
void Console::addBirth(int& birth)
{
string birthInput;
do{
cout << "Enter year of birth: ";
cin >> birthInput;
if(!validYear(birthInput))
{
cout << "Invalid input!" <<endl;
}
else if (atoi(birthInput.c_str()) > 2016)
{
cout << "The scientist is not born yet.." << endl;
}
}
while(!validYear(birthInput) || atoi(birthInput.c_str()) > 2016);
birth = atoi(birthInput.c_str());
}
void Console::addDeath(int& death, int& birth)
{
string deathInput;
string status;
do
{
cout << "Is the person alive? (Y/N): ";
cin >> status;
if(!(status == "N" || status == "n") && !(status == "Y" || status == "y"))
cout << "Invalid Input!";
if(status == "N" || status == "n")
{
do
{
cout << "Enter year of death : ";
cin >> deathInput;
if((!validYear(deathInput)) || (atoi(deathInput.c_str()) < birth))
{
cout << "Invalid input!" <<endl;
}
else if (atoi(deathInput.c_str()) > 2016)
{
cout << "So you think you know the future?" << endl;
}
}
while((!validYear(deathInput)) || (atoi(deathInput.c_str()) < birth) || (atoi(deathInput.c_str()) > 2016));
death = atoi(deathInput.c_str());
}
cout << endl;
}
while(!(status == "N" || status == "n") && !(status == "Y" || status == "y"));
}
void Console::addAnother(string &anotherOne)
{
do
{
cout << "Add another? (Y/N): ";
cin >> anotherOne;
if(!(anotherOne == "N" || anotherOne == "n") && !(anotherOne == "Y" || anotherOne == "y"))
cout << "Invalid Input!" <<endl;
}
while(!(anotherOne == "N" || anotherOne == "n") && !(anotherOne == "Y" || anotherOne == "y"));
}
string Console::searchName()
{
string chosenName;
cout << "Who would you like to seach for? ";
cin >> chosenName;
return chosenName;
}
vector<Person> Console::getVector()
{
return _pers;
}
void Console::displaySearch()
{
string name = searchName();
cout << _dom.search(_pers, name).getName() << endl;
cout << _dom.search(_pers, name).getGender() << endl;
cout << _dom.search(_pers, name).getBirth() << endl;
cout << _dom.search(_pers, name).getDeath() << endl;
}
<|endoftext|> |
<commit_before>#include "console.h"
#include <iostream>
#include <string>
using namespace std;
Console::Console()
{
}
void Console::getInfo()
{
string name;
char gender;
int birth;
int death;
cout << "Please enter name: ";
cin >> name;
cout << "Gender (f/m): ";
cin >> gender;
cout << "Year of birth: ";
cin >> birth;
cout << "Year of death, enter '0' if N/A: ";
cin >> death;
}
int Console::getSort()
{
int command;
cout << "Please enter one of the following commands: " << endl;
cout << "1 - for alphabetical order" << endl;
cout << "2 - sort by gender" << endl;
cout << "3 - sort by age (youngest to oldest)" << endl;
cin >> command;
return command;
}
<commit_msg>man ekki<commit_after>#include "console.h"
#include <iostream>
#include <string>
using namespace std;
Console::Console()
{
}
void Console::getInfo()
{
string name;
char gender;
int birth;
int death;
cout << "Please enter name: ";
cin >> name;
cout << "Gender (f/m): ";
cin >> gender;
cout << "Year of birth: ";
cin >> birth;
cout << "Year of death, enter '0' if N/A: ";
cin >> death;
}
int Console::getSort()
{
int command;
cout << "Please enter one of the following commands: " << endl;
cout << "1 - for alphabetical order" << endl;
cout << "2 - sort by gender" << endl;
cout << "3 - sort by age (youngest to oldest)" << endl;
cin >> command;
return command;
}
<|endoftext|> |
<commit_before>#include "objectmemory.hpp"
#include "gc/immix.hpp"
#include "instruments/stats.hpp"
#include "capi/handles.hpp"
#include "capi/tag.hpp"
#include "object_watch.hpp"
#include "configuration.hpp"
#ifdef ENABLE_LLVM
#include "llvm/state.hpp"
#endif
namespace rubinius {
void ImmixGC::ObjectDescriber::added_chunk(int count) {
#ifdef IMMIX_DEBUG
std::cout << "[GC IMMIX: Added a chunk: " << count << "]\n";
#endif
if(object_memory_) {
if(gc_->dec_chunks_left() <= 0) {
// object_memory_->collect_mature_now = true;
gc_->reset_chunks_left();
}
}
}
/**
* This means we're getting low on memory! Time to schedule a garbage
* collection.
*/
void ImmixGC::ObjectDescriber::last_block() {
if(object_memory_) {
object_memory_->collect_mature_now = true;
}
}
void ImmixGC::ObjectDescriber::set_forwarding_pointer(memory::Address from, memory::Address to) {
from.as<Object>()->set_forward(to.as<Object>());
}
ImmixGC::ImmixGC(ObjectMemory* om)
: GarbageCollector(om)
, allocator_(gc_.block_allocator())
, chunks_before_collection_(10)
{
gc_.describer().set_object_memory(om, this);
reset_chunks_left();
}
memory::Address ImmixGC::ObjectDescriber::copy(memory::Address original,
immix::Allocator& alloc) {
Object* orig = original.as<Object>();
memory::Address copy_addr = alloc.allocate(
orig->size_in_bytes(object_memory_->state()));
Object* copy = copy_addr.as<Object>();
copy->initialize_full_state(object_memory_->state(), orig, 0);
copy->set_zone(MatureObjectZone);
copy->set_in_immix();
return copy_addr;
}
int ImmixGC::ObjectDescriber::size(memory::Address addr) {
return addr.as<Object>()->size_in_bytes(object_memory_->state());
}
Object* ImmixGC::allocate(int bytes) {
if(bytes > immix::cMaxObjectSize) return 0;
Object* obj = allocator_.allocate(bytes).as<Object>();
obj->init_header(MatureObjectZone, InvalidType);
obj->set_in_immix();
return obj;
}
Object* ImmixGC::move_object(Object* orig, int bytes) {
if(bytes > immix::cMaxObjectSize) return 0;
Object* obj = allocator_.allocate(bytes).as<Object>();
memcpy(obj, orig, bytes);
obj->set_zone(MatureObjectZone);
obj->set_age(0);
obj->set_in_immix();
orig->set_forward(obj);
return obj;
}
Object* ImmixGC::saw_object(Object* obj) {
#ifdef ENABLE_OBJECT_WATCH
if(watched_p(obj)) {
std::cout << "detected " << obj << " during immix scanning.\n";
}
#endif
if(!obj->reference_p()) return obj;
memory::Address fwd = gc_.mark_address(memory::Address(obj), allocator_);
Object* copy = fwd.as<Object>();
// Check and update an inflated header
if(copy && copy != obj) {
obj->set_forward(copy);
}
return copy;
}
ObjectPosition ImmixGC::validate_object(Object* obj) {
if(gc_.allocated_address(memory::Address(obj))) {
if(obj->in_immix_p()) {
return cInImmix;
} else {
return cInImmixCorruptHeader;
}
}
return cUnknown;
}
/**
* Performs a garbage collection of the immix space.
*/
void ImmixGC::collect(GCData& data) {
gc_.clear_lines();
int via_handles_ = 0;
int via_roots = 0;
for(Roots::Iterator i(data.roots()); i.more(); i.advance()) {
Object* tmp = i->get();
if(tmp->reference_p()) saw_object(tmp);
via_roots++;
}
if(data.threads()) {
for(std::list<ManagedThread*>::iterator i = data.threads()->begin();
i != data.threads()->end();
++i) {
scan(*i, false);
}
}
for(Allocator<capi::Handle>::Iterator i(data.handles()->allocator()); i.more(); i.advance()) {
if(i->in_use_p() && !i->weak_p()) {
saw_object(i->object());
via_handles_++;
}
}
std::list<capi::GlobalHandle*>* gh = data.global_handle_locations();
if(gh) {
for(std::list<capi::GlobalHandle*>::iterator i = gh->begin();
i != gh->end();
++i) {
capi::Handle** loc = (*i)->handle();
if(capi::Handle* hdl = *loc) {
if(!REFERENCE_P(hdl)) continue;
if(hdl->valid_p()) {
Object* obj = hdl->object();
if(obj && obj->reference_p()) {
saw_object(obj);
via_handles_++;
}
} else {
std::cerr << "Detected bad handle checking global capi handles\n";
}
}
}
}
#ifdef ENABLE_LLVM
if(LLVMState* ls = data.llvm_state()) ls->gc_scan(this);
#endif
gc_.process_mark_stack(allocator_);
// We've now finished marking the entire object graph.
// Clean weakrefs before keeping additional objects alive
// for finalization, so people don't get a hold of finalized
// objects through weakrefs.
clean_weakrefs();
// Marking objects to be Finalized can cause more things to continue to
// live, so we must check the mark_stack again.
do {
walk_finalizers();
} while(gc_.process_mark_stack(allocator_));
// Remove unreachable locked objects still in the list
if(data.threads()) {
for(std::list<ManagedThread*>::iterator i = data.threads()->begin();
i != data.threads()->end();
++i) {
clean_locked_objects(*i, false);
}
}
// Sweep up the garbage
gc_.sweep_blocks();
// This resets the allocator state to sync it up with the BlockAllocator
// properly.
allocator_.get_new_block();
// Clear unreachable objects from the various remember sets
int cleared = 0;
unsigned int mark = object_memory_->mark();
cleared = object_memory_->unremember_objects(mark);
for(std::list<gc::WriteBarrier*>::iterator wbi = object_memory_->aux_barriers().begin();
wbi != object_memory_->aux_barriers().end();
++wbi) {
gc::WriteBarrier* wb = *wbi;
cleared += wb->unremember_objects(mark);
}
// Now, calculate how much space we're still using.
immix::Chunks& chunks = gc_.block_allocator().chunks();
immix::AllBlockIterator iter(chunks);
int live_bytes = 0;
int total_bytes = 0;
while(immix::Block* block = iter.next()) {
total_bytes += immix::cBlockSize;
live_bytes += block->bytes_from_lines();
}
double percentage_live = (double)live_bytes / (double)total_bytes;
if(object_memory_->state()->shared.config.gc_immix_debug) {
std::cerr << "[GC IMMIX: " << clear_marked_objects() << " marked"
<< ", "
<< via_roots << " roots "
<< via_handles_ << " handles "
<< (int)(percentage_live * 100) << "% live"
<< ", " << live_bytes << "/" << total_bytes
<< "]\n";
}
if(percentage_live >= 0.90) {
if(object_memory_->state()->shared.config.gc_immix_debug) {
std::cerr << "[GC IMMIX: expanding. "
<< (int)(percentage_live * 100)
<< "%]\n";
}
gc_.block_allocator().add_chunk();
}
#ifdef IMMIX_DEBUG
std::cout << "Immix: RS size cleared: " << cleared << "\n";
immix::Chunks& chunks = gc_.block_allocator().chunks();
std::cout << "chunks=" << chunks.size() << "\n";
immix::AllBlockIterator iter(chunks);
int blocks_seen = 0;
int total_objects = 0;
int total_object_bytes = 0;
while(immix::Block* block = iter.next()) {
blocks_seen++;
std::cout << "block " << block << ", holes=" << block->holes() << " "
<< "objects=" << block->objects() << " "
<< "object_bytes=" << block->object_bytes() << " "
<< "frag=" << block->fragmentation_ratio()
<< "\n";
total_objects += block->objects();
total_object_bytes += block->object_bytes();
}
std::cout << blocks_seen << " blocks\n";
std::cout << gc_.bytes_allocated() << " bytes allocated\n";
std::cout << total_object_bytes << " object bytes / " << total_objects << " objects\n";
int* holes = new int[10];
for(int i = 0; i < 10; i++) {
holes[i] = 0;
}
immix::AllBlockIterator iter2(chunks);
while(immix::Block* block = iter2.next()) {
int h = block->holes();
if(h > 9) h = 9;
holes[h]++;
}
std::cout << "== hole stats ==\n";
for(int i = 0; i < 10; i++) {
if(holes[i] > 0) {
std::cout << i << ": " << holes[i] << "\n";
}
}
delete[] holes;
holes = NULL;
#endif
}
void ImmixGC::walk_finalizers() {
FinalizerHandler* fh = object_memory_->finalizer_handler();
if(!fh) return;
for(FinalizerHandler::iterator i = fh->begin();
!i.end();
/* advance is handled in the loop */)
{
FinalizeObject& fi = i.current();
bool live = fi.object->marked_p(object_memory_->mark());
if(fi.ruby_finalizer) {
fi.ruby_finalizer = saw_object(fi.ruby_finalizer);
}
fi.object = saw_object(fi.object);
i.next(live);
}
}
}
<commit_msg>Sweep after unremembering objects<commit_after>#include "objectmemory.hpp"
#include "gc/immix.hpp"
#include "instruments/stats.hpp"
#include "capi/handles.hpp"
#include "capi/tag.hpp"
#include "object_watch.hpp"
#include "configuration.hpp"
#ifdef ENABLE_LLVM
#include "llvm/state.hpp"
#endif
namespace rubinius {
void ImmixGC::ObjectDescriber::added_chunk(int count) {
#ifdef IMMIX_DEBUG
std::cout << "[GC IMMIX: Added a chunk: " << count << "]\n";
#endif
if(object_memory_) {
if(gc_->dec_chunks_left() <= 0) {
// object_memory_->collect_mature_now = true;
gc_->reset_chunks_left();
}
}
}
/**
* This means we're getting low on memory! Time to schedule a garbage
* collection.
*/
void ImmixGC::ObjectDescriber::last_block() {
if(object_memory_) {
object_memory_->collect_mature_now = true;
}
}
void ImmixGC::ObjectDescriber::set_forwarding_pointer(memory::Address from, memory::Address to) {
from.as<Object>()->set_forward(to.as<Object>());
}
ImmixGC::ImmixGC(ObjectMemory* om)
: GarbageCollector(om)
, allocator_(gc_.block_allocator())
, chunks_before_collection_(10)
{
gc_.describer().set_object_memory(om, this);
reset_chunks_left();
}
memory::Address ImmixGC::ObjectDescriber::copy(memory::Address original,
immix::Allocator& alloc) {
Object* orig = original.as<Object>();
memory::Address copy_addr = alloc.allocate(
orig->size_in_bytes(object_memory_->state()));
Object* copy = copy_addr.as<Object>();
copy->initialize_full_state(object_memory_->state(), orig, 0);
copy->set_zone(MatureObjectZone);
copy->set_in_immix();
return copy_addr;
}
int ImmixGC::ObjectDescriber::size(memory::Address addr) {
return addr.as<Object>()->size_in_bytes(object_memory_->state());
}
Object* ImmixGC::allocate(int bytes) {
if(bytes > immix::cMaxObjectSize) return 0;
Object* obj = allocator_.allocate(bytes).as<Object>();
obj->init_header(MatureObjectZone, InvalidType);
obj->set_in_immix();
return obj;
}
Object* ImmixGC::move_object(Object* orig, int bytes) {
if(bytes > immix::cMaxObjectSize) return 0;
Object* obj = allocator_.allocate(bytes).as<Object>();
memcpy(obj, orig, bytes);
obj->set_zone(MatureObjectZone);
obj->set_age(0);
obj->set_in_immix();
orig->set_forward(obj);
return obj;
}
Object* ImmixGC::saw_object(Object* obj) {
#ifdef ENABLE_OBJECT_WATCH
if(watched_p(obj)) {
std::cout << "detected " << obj << " during immix scanning.\n";
}
#endif
if(!obj->reference_p()) return obj;
memory::Address fwd = gc_.mark_address(memory::Address(obj), allocator_);
Object* copy = fwd.as<Object>();
// Check and update an inflated header
if(copy && copy != obj) {
obj->set_forward(copy);
}
return copy;
}
ObjectPosition ImmixGC::validate_object(Object* obj) {
if(gc_.allocated_address(memory::Address(obj))) {
if(obj->in_immix_p()) {
return cInImmix;
} else {
return cInImmixCorruptHeader;
}
}
return cUnknown;
}
/**
* Performs a garbage collection of the immix space.
*/
void ImmixGC::collect(GCData& data) {
gc_.clear_lines();
int via_handles_ = 0;
int via_roots = 0;
for(Roots::Iterator i(data.roots()); i.more(); i.advance()) {
Object* tmp = i->get();
if(tmp->reference_p()) saw_object(tmp);
via_roots++;
}
if(data.threads()) {
for(std::list<ManagedThread*>::iterator i = data.threads()->begin();
i != data.threads()->end();
++i) {
scan(*i, false);
}
}
for(Allocator<capi::Handle>::Iterator i(data.handles()->allocator()); i.more(); i.advance()) {
if(i->in_use_p() && !i->weak_p()) {
saw_object(i->object());
via_handles_++;
}
}
std::list<capi::GlobalHandle*>* gh = data.global_handle_locations();
if(gh) {
for(std::list<capi::GlobalHandle*>::iterator i = gh->begin();
i != gh->end();
++i) {
capi::Handle** loc = (*i)->handle();
if(capi::Handle* hdl = *loc) {
if(!REFERENCE_P(hdl)) continue;
if(hdl->valid_p()) {
Object* obj = hdl->object();
if(obj && obj->reference_p()) {
saw_object(obj);
via_handles_++;
}
} else {
std::cerr << "Detected bad handle checking global capi handles\n";
}
}
}
}
#ifdef ENABLE_LLVM
if(LLVMState* ls = data.llvm_state()) ls->gc_scan(this);
#endif
gc_.process_mark_stack(allocator_);
// We've now finished marking the entire object graph.
// Clean weakrefs before keeping additional objects alive
// for finalization, so people don't get a hold of finalized
// objects through weakrefs.
clean_weakrefs();
// Marking objects to be Finalized can cause more things to continue to
// live, so we must check the mark_stack again.
do {
walk_finalizers();
} while(gc_.process_mark_stack(allocator_));
// Remove unreachable locked objects still in the list
if(data.threads()) {
for(std::list<ManagedThread*>::iterator i = data.threads()->begin();
i != data.threads()->end();
++i) {
clean_locked_objects(*i, false);
}
}
// Clear unreachable objects from the various remember sets
int cleared = 0;
unsigned int mark = object_memory_->mark();
cleared = object_memory_->unremember_objects(mark);
for(std::list<gc::WriteBarrier*>::iterator wbi = object_memory_->aux_barriers().begin();
wbi != object_memory_->aux_barriers().end();
++wbi) {
gc::WriteBarrier* wb = *wbi;
cleared += wb->unremember_objects(mark);
}
// Sweep up the garbage
gc_.sweep_blocks();
// This resets the allocator state to sync it up with the BlockAllocator
// properly.
allocator_.get_new_block();
// Now, calculate how much space we're still using.
immix::Chunks& chunks = gc_.block_allocator().chunks();
immix::AllBlockIterator iter(chunks);
int live_bytes = 0;
int total_bytes = 0;
while(immix::Block* block = iter.next()) {
total_bytes += immix::cBlockSize;
live_bytes += block->bytes_from_lines();
}
double percentage_live = (double)live_bytes / (double)total_bytes;
if(object_memory_->state()->shared.config.gc_immix_debug) {
std::cerr << "[GC IMMIX: " << clear_marked_objects() << " marked"
<< ", "
<< via_roots << " roots "
<< via_handles_ << " handles "
<< (int)(percentage_live * 100) << "% live"
<< ", " << live_bytes << "/" << total_bytes
<< "]\n";
}
if(percentage_live >= 0.90) {
if(object_memory_->state()->shared.config.gc_immix_debug) {
std::cerr << "[GC IMMIX: expanding. "
<< (int)(percentage_live * 100)
<< "%]\n";
}
gc_.block_allocator().add_chunk();
}
#ifdef IMMIX_DEBUG
std::cout << "Immix: RS size cleared: " << cleared << "\n";
immix::Chunks& chunks = gc_.block_allocator().chunks();
std::cout << "chunks=" << chunks.size() << "\n";
immix::AllBlockIterator iter(chunks);
int blocks_seen = 0;
int total_objects = 0;
int total_object_bytes = 0;
while(immix::Block* block = iter.next()) {
blocks_seen++;
std::cout << "block " << block << ", holes=" << block->holes() << " "
<< "objects=" << block->objects() << " "
<< "object_bytes=" << block->object_bytes() << " "
<< "frag=" << block->fragmentation_ratio()
<< "\n";
total_objects += block->objects();
total_object_bytes += block->object_bytes();
}
std::cout << blocks_seen << " blocks\n";
std::cout << gc_.bytes_allocated() << " bytes allocated\n";
std::cout << total_object_bytes << " object bytes / " << total_objects << " objects\n";
int* holes = new int[10];
for(int i = 0; i < 10; i++) {
holes[i] = 0;
}
immix::AllBlockIterator iter2(chunks);
while(immix::Block* block = iter2.next()) {
int h = block->holes();
if(h > 9) h = 9;
holes[h]++;
}
std::cout << "== hole stats ==\n";
for(int i = 0; i < 10; i++) {
if(holes[i] > 0) {
std::cout << i << ": " << holes[i] << "\n";
}
}
delete[] holes;
holes = NULL;
#endif
}
void ImmixGC::walk_finalizers() {
FinalizerHandler* fh = object_memory_->finalizer_handler();
if(!fh) return;
for(FinalizerHandler::iterator i = fh->begin();
!i.end();
/* advance is handled in the loop */)
{
FinalizeObject& fi = i.current();
bool live = fi.object->marked_p(object_memory_->mark());
if(fi.ruby_finalizer) {
fi.ruby_finalizer = saw_object(fi.ruby_finalizer);
}
fi.object = saw_object(fi.object);
i.next(live);
}
}
}
<|endoftext|> |
<commit_before>#include "jit.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/ExecutionEngine/JIT.h"
#include "llvm/Target/TargetSelect.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetData.h"
#include "llvm/PassManager.h"
// //#include "llvm/ModuleProvider.h"
#include "llvm/LinkAllPasses.h"
#include "primitives.h"
#include "llvm_code_generation.h"
#include "neko_module.h"
#include <iostream>
#include <stdio.h>
#include <sstream>
//C interface
extern "C" {
#include "neko.h"
#include "neko_vm.h"
#include "vm.h"
#include "neko_mod.h"
extern char *jit_boot_seq;
void llvm_jit_boot(neko_vm * vm, int_val * code, value, neko_module *) {
((void (*)(neko_vm *))code)(vm);
}
void llvm_cpp_jit(neko_vm * vm, neko_module * m) {
jit_boot_seq = (char *)&llvm_jit_boot;
neko::Module code_base(m);
if (vm->dump_neko) {
code_base.neko_dump();
}
llvm::Module * module = makeLLVMModule(code_base, m);
llvm::GuaranteedTailCallOpt = true;
llvm::JITEmitDebugInfo = true;
llvm::InitializeNativeTarget();
std::string error_string;
llvm::ExecutionEngine * ee = llvm::EngineBuilder(module)
.setEngineKind(llvm::EngineKind::JIT)
.setErrorStr(&error_string)
.create();
if (!ee) {
std::cerr << "Could not create ExecutionEngine: " << error_string << std::endl;
}
//register primitives
#define PRIMITIVE(name) ee->addGlobalMapping(ee->FindFunctionNamed(#name), (void *)p_##name);
#include "primitives_list.h"
#undef PRIMITIVE
if (vm->llvm_optimizations) {
llvm::PassManager OurFPM;
// Set up the optimizer pipeline. Start with registering info about how the
// target lays out data structures.
OurFPM.add(new llvm::TargetData(*ee->getTargetData()));
// Promote allocas to registers.
//OurFPM.add(llvm::createPromoteMemoryToRegisterPass());
// Reassociate expressions.
OurFPM.add(llvm::createReassociatePass());
//selected passes from brainfuck jit compiler
// http://www.remcobloemen.nl/2010/02/brainfuck-using-llvm/
//seems to be working good for us but we need more research on optimizations
OurFPM.add(llvm::createInstructionCombiningPass()); // Cleanup for scalarrepl.
// OurFPM.add(llvm::createLICMPass()); // Hoist loop invariants
OurFPM.add(llvm::createIndVarSimplifyPass()); // Canonicalize indvars
OurFPM.add(llvm::createLoopDeletionPass()); // Delete dead loops
// Simplify code
for(int repeat=0; repeat < 3; repeat++) {
// OurFPM.add(llvm::createGVNPass()); // Remove redundancies
OurFPM.add(llvm::createSCCPPass()); // Constant prop with SCCP
OurFPM.add(llvm::createCFGSimplificationPass()); // Merge & remove BBs
OurFPM.add(llvm::createInstructionCombiningPass());
OurFPM.add(llvm::createAggressiveDCEPass()); // Delete dead instructions
OurFPM.add(llvm::createCFGSimplificationPass()); // Merge & remove BBs
OurFPM.add(llvm::createDeadStoreEliminationPass()); // Delete dead stores
}
OurFPM.run(*module);
}
if (vm->dump_llvm) {
module->dump();
}
//converting globals
for (ptr_val k = 0; k < m->nglobals; k++) {
if (val_is_function(m->globals[k])) {
vfunction * f = (vfunction*)m->globals[k];
std::stringstream ss; ss << (int_val)f->addr;
std::string name = ss.str();
llvm::Function * F = module->getFunction(name);
if (F) {
llvm::verifyFunction(*F);
void *FPtr = ee->getPointerToFunction(F);
f->addr = FPtr;
f->t = VAL_LLVMJITFUN;
}
}
}
llvm::Function * main = module->getFunction("main");
llvm::verifyFunction(*main);
void *FPtr = ee->getPointerToFunction(main);
m->jit = FPtr;
}
}
<commit_msg>Enable optimizations<commit_after>#include "jit.h"
#include "llvm/Analysis/Verifier.h"
#include "llvm/ExecutionEngine/JIT.h"
#include "llvm/Target/TargetSelect.h"
#include "llvm/Target/TargetOptions.h"
#include "llvm/Target/TargetData.h"
#include "llvm/PassManager.h"
// //#include "llvm/ModuleProvider.h"
//#include "llvm/LinkAllPasses.h"
#include "llvm/Support/StandardPasses.h"
#include "primitives.h"
#include "llvm_code_generation.h"
#include "neko_module.h"
#include <iostream>
#include <stdio.h>
#include <sstream>
//C interface
extern "C" {
#include "neko.h"
#include "neko_vm.h"
#include "vm.h"
#include "neko_mod.h"
extern char *jit_boot_seq;
void llvm_jit_boot(neko_vm * vm, int_val * code, value, neko_module *) {
((void (*)(neko_vm *))code)(vm);
}
namespace {
//this is fixed in next llvm version
// but for now it is impossible to call this function with PassManager
static inline void createStandardFunctionPasses(llvm::PassManager *PM,
unsigned OptimizationLevel) {
if (OptimizationLevel > 0) {
PM->add(llvm::createCFGSimplificationPass());
if (OptimizationLevel == 1)
PM->add(llvm::createPromoteMemoryToRegisterPass());
else
PM->add(llvm::createScalarReplAggregatesPass());
PM->add(llvm::createInstructionCombiningPass());
}
}
}
void llvm_cpp_jit(neko_vm * vm, neko_module * m) {
jit_boot_seq = (char *)&llvm_jit_boot;
neko::Module code_base(m);
if (vm->dump_neko) {
code_base.neko_dump();
}
llvm::Module * module = makeLLVMModule(code_base, m);
llvm::GuaranteedTailCallOpt = true;
llvm::JITEmitDebugInfo = true;
llvm::InitializeNativeTarget();
std::string error_string;
llvm::ExecutionEngine * ee = llvm::EngineBuilder(module)
.setOptLevel((vm->llvm_optimizations)
?llvm::CodeGenOpt::Aggressive
:llvm::CodeGenOpt::None)
.setEngineKind(llvm::EngineKind::JIT)
.setErrorStr(&error_string)
.create();
//enable lazy compilation
ee->DisableLazyCompilation(false);
if (!ee) {
std::cerr << "Could not create ExecutionEngine: " << error_string << std::endl;
}
//register primitives
#define PRIMITIVE(name) ee->addGlobalMapping(ee->FindFunctionNamed(#name), (void *)p_##name);
#include "primitives_list.h"
#undef PRIMITIVE
llvm::PassManager OurFPM;
// Set up the optimizer pipeline. Start with registering info about how the
// target lays out data structures.
OurFPM.add(new llvm::TargetData(*ee->getTargetData()));
createStandardFunctionPasses(&OurFPM, (vm->llvm_optimizations)?3:0);
llvm::createStandardModulePasses(&OurFPM, (vm->llvm_optimizations)?0:0,
false, true,
vm->llvm_optimizations, vm->llvm_optimizations,
true, 0);
OurFPM.run(*module);
if (vm->dump_llvm) {
module->dump();
}
//converting globals
for (ptr_val k = 0; k < m->nglobals; k++) {
if (val_is_function(m->globals[k])) {
vfunction * f = (vfunction*)m->globals[k];
std::stringstream ss; ss << (int_val)f->addr;
std::string name = ss.str();
llvm::Function * F = module->getFunction(name);
if (F) {
llvm::verifyFunction(*F);
void *FPtr = ee->getPointerToFunction(F);
f->addr = FPtr;
f->t = VAL_LLVMJITFUN;
}
}
}
llvm::Function * main = module->getFunction("main");
llvm::verifyFunction(*main);
void *FPtr = ee->getPointerToFunction(main);
m->jit = FPtr;
}
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2016 zScale Technology GmbH <[email protected]>
* Authors:
* - Paul Asmuth <[email protected]>
* - Laura Schlimmer <[email protected]>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include <eventql/cli/commands/cluster_set_allocation_policy.h>
#include <eventql/util/cli/flagparser.h>
#include "eventql/config/config_directory.h"
#include "eventql/util/random.h"
namespace eventql {
namespace cli {
const String ClusterSetAllocationPolicy::kName_ = "cluster-set-allocation-policy";
const String ClusterSetAllocationPolicy::kDescription_ =
"Set allocation policy for a server.";
ClusterSetAllocationPolicy::ClusterSetAllocationPolicy(
RefPtr<ProcessConfig> process_cfg) :
process_cfg_(process_cfg) {}
Status ClusterSetAllocationPolicy::execute(
const std::vector<std::string>& argv,
FileInputStream* stdin_is,
OutputStream* stdout_os,
OutputStream* stderr_os) {
::cli::FlagParser flags;
flags.defineFlag(
"cluster_name",
::cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"node name",
"<string>");
flags.defineFlag(
"server_name",
::cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"node name",
"<string>");
try {
flags.parseArgv(argv);
bool remove_hard = flags.isSet("hard");
bool remove_soft = flags.isSet("soft");
if (!(remove_hard ^ remove_soft)) {
stderr_os->write("ERROR: either --hard or --soft must be set\n");
return Status(eFlagError);
}
ScopedPtr<ConfigDirectory> cdir;
{
auto rc = ConfigDirectoryFactory::getConfigDirectoryForClient(
process_cfg_.get(),
&cdir);
if (rc.isSuccess()) {
rc = cdir->start();
}
if (!rc.isSuccess()) {
stderr_os->write(StringUtil::format("ERROR: $0\n", rc.message()));
return rc;
}
}
auto cfg = cdir->getServerConfig(flags.getString("server_name"));
if (remove_soft) {
cfg.set_is_leaving(true);
}
if (remove_hard) {
cfg.set_is_dead(true);
}
cdir->updateServerConfig(cfg);
cdir->stop();
} catch (const Exception& e) {
stderr_os->write(StringUtil::format(
"$0: $1\n",
e.getTypeName(),
e.getMessage()));
return Status(e);
}
return Status::success();
}
const String& ClusterSetAllocationPolicy::getName() const {
return kName_;
}
const String& ClusterSetAllocationPolicy::getDescription() const {
return kDescription_;
}
void ClusterSetAllocationPolicy::printHelp(OutputStream* stdout_os) const {
stdout_os->write(StringUtil::format(
"\nevqlctl-$0 - $1\n\n", kName_, kDescription_));
stdout_os->write(
"Usage: evqlctl [OPTIONS]\n"
" --cluster_name <node name> The name of the cluster to add the server to.\n"
" --server_name <server name> The name of the server to add.\n");
}
} // namespace cli
} // namespace eventql
<commit_msg>cluster_set_allocation_policy.cc<commit_after>/**
* Copyright (c) 2016 zScale Technology GmbH <[email protected]>
* Authors:
* - Paul Asmuth <[email protected]>
* - Laura Schlimmer <[email protected]>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include <eventql/cli/commands/cluster_set_allocation_policy.h>
#include <eventql/util/cli/flagparser.h>
#include "eventql/config/config_directory.h"
#include "eventql/util/random.h"
namespace eventql {
namespace cli {
const String ClusterSetAllocationPolicy::kName_ = "cluster-set-allocation-policy";
const String ClusterSetAllocationPolicy::kDescription_ =
"Set allocation policy for a server.";
ClusterSetAllocationPolicy::ClusterSetAllocationPolicy(
RefPtr<ProcessConfig> process_cfg) :
process_cfg_(process_cfg) {}
Status ClusterSetAllocationPolicy::execute(
const std::vector<std::string>& argv,
FileInputStream* stdin_is,
OutputStream* stdout_os,
OutputStream* stderr_os) {
::cli::FlagParser flags;
flags.defineFlag(
"cluster_name",
::cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"node name",
"<string>");
flags.defineFlag(
"server_name",
::cli::FlagParser::T_STRING,
true,
NULL,
NULL,
"node name",
"<string>");
try {
flags.parseArgv(argv);
ScopedPtr<ConfigDirectory> cdir;
{
auto rc = ConfigDirectoryFactory::getConfigDirectoryForClient(
process_cfg_.get(),
&cdir);
if (rc.isSuccess()) {
rc = cdir->start();
}
if (!rc.isSuccess()) {
stderr_os->write(StringUtil::format("ERROR: $0\n", rc.message()));
return rc;
}
}
auto cfg = cdir->getServerConfig(flags.getString("server_name"));
cfg.set_allocation_policy(ALLOC_POLICY_NOALLOC);
cdir->updateServerConfig(cfg);
cdir->stop();
} catch (const Exception& e) {
stderr_os->write(StringUtil::format(
"$0: $1\n",
e.getTypeName(),
e.getMessage()));
return Status(e);
}
return Status::success();
}
const String& ClusterSetAllocationPolicy::getName() const {
return kName_;
}
const String& ClusterSetAllocationPolicy::getDescription() const {
return kDescription_;
}
void ClusterSetAllocationPolicy::printHelp(OutputStream* stdout_os) const {
stdout_os->write(StringUtil::format(
"\nevqlctl-$0 - $1\n\n", kName_, kDescription_));
stdout_os->write(
"Usage: evqlctl [OPTIONS]\n"
" --cluster_name <node name> The name of the cluster to add the server to.\n"
" --server_name <server name> The name of the server to add.\n");
}
} // namespace cli
} // namespace eventql
<|endoftext|> |
<commit_before>/**
*
* Copyright (c) 2020 Project CHIP Authors
* Copyright (c) 2018 Google LLC.
* Copyright (c) 2016-2017 Nest Labs, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "CommandPathIB.h"
#include "MessageDefHelper.h"
#include <inttypes.h>
#include <stdarg.h>
#include <stdio.h>
#include <app/AppBuildConfig.h>
using namespace chip;
using namespace chip::TLV;
namespace chip {
namespace app {
#if CHIP_CONFIG_IM_ENABLE_SCHEMA_CHECK
CHIP_ERROR CommandPathIB::Parser::CheckSchemaValidity() const
{
CHIP_ERROR err = CHIP_NO_ERROR;
int tagPresenceMask = 0;
TLV::TLVReader reader;
PRETTY_PRINT("CommandPathIB =");
PRETTY_PRINT("{");
// make a copy of the Path reader
reader.Init(mReader);
while (CHIP_NO_ERROR == (err = reader.Next()))
{
if (!TLV::IsContextTag(reader.GetTag()))
{
continue;
}
uint32_t tagNum = TLV::TagNumFromTag(reader.GetTag());
switch (tagNum)
{
case to_underlying(Tag::kEndpointId):
// check if this tag has appeared before
VerifyOrReturnError(!(tagPresenceMask & (1 << to_underlying(Tag::kEndpointId))), CHIP_ERROR_INVALID_TLV_TAG);
tagPresenceMask |= (1 << to_underlying(Tag::kEndpointId));
VerifyOrReturnError(TLV::kTLVType_UnsignedInteger == reader.GetType(), CHIP_ERROR_WRONG_TLV_TYPE);
#if CHIP_DETAIL_LOGGING
{
uint16_t endpointId;
ReturnErrorOnFailure(reader.Get(endpointId));
PRETTY_PRINT("\tEndpointId = 0x%x,", endpointId);
}
#endif // CHIP_DETAIL_LOGGING
break;
case to_underlying(Tag::kClusterId):
// check if this tag has appeared before
VerifyOrReturnError(!(tagPresenceMask & (1 << to_underlying(Tag::kClusterId))), CHIP_ERROR_INVALID_TLV_TAG);
tagPresenceMask |= (1 << to_underlying(Tag::kClusterId));
VerifyOrReturnError(TLV::kTLVType_UnsignedInteger == reader.GetType(), CHIP_ERROR_WRONG_TLV_TYPE);
#if CHIP_DETAIL_LOGGING
{
chip::ClusterId clusterId;
ReturnErrorOnFailure(reader.Get(clusterId));
PRETTY_PRINT("\tClusterId = 0x%" PRIx32 ",", clusterId);
}
#endif // CHIP_DETAIL_LOGGING
break;
case to_underlying(Tag::kCommandId):
// check if this tag has appeared before
VerifyOrReturnError(!(tagPresenceMask & (1 << to_underlying(Tag::kCommandId))), CHIP_ERROR_INVALID_TLV_TAG);
tagPresenceMask |= (1 << to_underlying(Tag::kCommandId));
VerifyOrReturnError(chip::TLV::kTLVType_UnsignedInteger == reader.GetType(), CHIP_ERROR_WRONG_TLV_TYPE);
#if CHIP_DETAIL_LOGGING
{
chip::CommandId commandId;
ReturnErrorOnFailure(reader.Get(commandId));
PRETTY_PRINT("\tCommandId = 0x%x,", commandId);
}
#endif // CHIP_DETAIL_LOGGING
break;
default:
PRETTY_PRINT("Unknown tag num %" PRIu32, tagNum);
break;
}
}
PRETTY_PRINT("},");
PRETTY_PRINT("");
// if we have exhausted this container
if (CHIP_END_OF_TLV == err)
{
// check for required fields:
const uint16_t requiredFields =
(1 << to_underlying(Tag::kEndpointId)) | (1 << to_underlying(Tag::kCommandId)) | (1 << to_underlying(Tag::kClusterId));
err = (tagPresenceMask & requiredFields) == requiredFields ? CHIP_NO_ERROR : CHIP_ERROR_IM_MALFORMED_COMMAND_PATH_IB;
}
ReturnErrorOnFailure(err);
return reader.ExitContainer(mOuterContainerType);
}
#endif // CHIP_CONFIG_IM_ENABLE_SCHEMA_CHECK
CHIP_ERROR CommandPathIB::Parser::GetEndpointId(chip::EndpointId * const apEndpointID) const
{
return GetUnsignedInteger(to_underlying(Tag::kEndpointId), apEndpointID);
}
CHIP_ERROR CommandPathIB::Parser::GetClusterId(chip::ClusterId * const apClusterId) const
{
return GetUnsignedInteger(to_underlying(Tag::kClusterId), apClusterId);
}
CHIP_ERROR CommandPathIB::Parser::GetCommandId(chip::CommandId * const apCommandId) const
{
return GetUnsignedInteger(to_underlying(Tag::kCommandId), apCommandId);
}
CommandPathIB::Builder & CommandPathIB::Builder::EndpointId(const chip::EndpointId aEndpointId)
{
// skip if error has already been set
if (mError == CHIP_NO_ERROR)
{
mError = mpWriter->Put(TLV::ContextTag(to_underlying(Tag::kEndpointId)), aEndpointId);
}
return *this;
}
CommandPathIB::Builder & CommandPathIB::Builder::ClusterId(const chip::ClusterId aClusterId)
{
// skip if error has already been set
if (mError == CHIP_NO_ERROR)
{
mError = mpWriter->Put(TLV::ContextTag(to_underlying(Tag::kClusterId)), aClusterId);
}
return *this;
}
CommandPathIB::Builder & CommandPathIB::Builder::CommandId(const chip::CommandId aCommandId)
{
// skip if error has already been set
if (mError == CHIP_NO_ERROR)
{
mError = mpWriter->Put(TLV::ContextTag(to_underlying(Tag::kCommandId)), aCommandId);
}
return *this;
}
CommandPathIB::Builder & CommandPathIB::Builder::EndOfCommandPathIB()
{
EndOfContainer();
return *this;
}
CHIP_ERROR CommandPathIB::Builder::Encode(const CommandPathParams & aCommandPathParams)
{
if (aCommandPathParams.mFlags.Has(CommandPathFlags::kEndpointIdValid))
{
EndpointId(aCommandPathParams.mEndpointId);
}
ClusterId(aCommandPathParams.mClusterId).CommandId(aCommandPathParams.mCommandId).EndOfCommandPathIB();
return GetError();
}
CHIP_ERROR CommandPathIB::Builder::Encode(const ConcreteCommandPath & aConcreteCommandPath)
{
EndpointId(aConcreteCommandPath.mEndpointId)
.ClusterId(aConcreteCommandPath.mClusterId)
.CommandId(aConcreteCommandPath.mCommandId)
.EndOfCommandPathIB();
return GetError();
}
}; // namespace app
}; // namespace chip
<commit_msg>temporarily remove endpointid check for command path IB (#19085)<commit_after>/**
*
* Copyright (c) 2020 Project CHIP Authors
* Copyright (c) 2018 Google LLC.
* Copyright (c) 2016-2017 Nest Labs, Inc.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "CommandPathIB.h"
#include "MessageDefHelper.h"
#include <inttypes.h>
#include <stdarg.h>
#include <stdio.h>
#include <app/AppBuildConfig.h>
using namespace chip;
using namespace chip::TLV;
namespace chip {
namespace app {
#if CHIP_CONFIG_IM_ENABLE_SCHEMA_CHECK
CHIP_ERROR CommandPathIB::Parser::CheckSchemaValidity() const
{
CHIP_ERROR err = CHIP_NO_ERROR;
int tagPresenceMask = 0;
TLV::TLVReader reader;
PRETTY_PRINT("CommandPathIB =");
PRETTY_PRINT("{");
// make a copy of the Path reader
reader.Init(mReader);
while (CHIP_NO_ERROR == (err = reader.Next()))
{
if (!TLV::IsContextTag(reader.GetTag()))
{
continue;
}
uint32_t tagNum = TLV::TagNumFromTag(reader.GetTag());
switch (tagNum)
{
case to_underlying(Tag::kEndpointId):
// check if this tag has appeared before
VerifyOrReturnError(!(tagPresenceMask & (1 << to_underlying(Tag::kEndpointId))), CHIP_ERROR_INVALID_TLV_TAG);
tagPresenceMask |= (1 << to_underlying(Tag::kEndpointId));
VerifyOrReturnError(TLV::kTLVType_UnsignedInteger == reader.GetType(), CHIP_ERROR_WRONG_TLV_TYPE);
#if CHIP_DETAIL_LOGGING
{
uint16_t endpointId;
ReturnErrorOnFailure(reader.Get(endpointId));
PRETTY_PRINT("\tEndpointId = 0x%x,", endpointId);
}
#endif // CHIP_DETAIL_LOGGING
break;
case to_underlying(Tag::kClusterId):
// check if this tag has appeared before
VerifyOrReturnError(!(tagPresenceMask & (1 << to_underlying(Tag::kClusterId))), CHIP_ERROR_INVALID_TLV_TAG);
tagPresenceMask |= (1 << to_underlying(Tag::kClusterId));
VerifyOrReturnError(TLV::kTLVType_UnsignedInteger == reader.GetType(), CHIP_ERROR_WRONG_TLV_TYPE);
#if CHIP_DETAIL_LOGGING
{
chip::ClusterId clusterId;
ReturnErrorOnFailure(reader.Get(clusterId));
PRETTY_PRINT("\tClusterId = 0x%" PRIx32 ",", clusterId);
}
#endif // CHIP_DETAIL_LOGGING
break;
case to_underlying(Tag::kCommandId):
// check if this tag has appeared before
VerifyOrReturnError(!(tagPresenceMask & (1 << to_underlying(Tag::kCommandId))), CHIP_ERROR_INVALID_TLV_TAG);
tagPresenceMask |= (1 << to_underlying(Tag::kCommandId));
VerifyOrReturnError(chip::TLV::kTLVType_UnsignedInteger == reader.GetType(), CHIP_ERROR_WRONG_TLV_TYPE);
#if CHIP_DETAIL_LOGGING
{
chip::CommandId commandId;
ReturnErrorOnFailure(reader.Get(commandId));
PRETTY_PRINT("\tCommandId = 0x%x,", commandId);
}
#endif // CHIP_DETAIL_LOGGING
break;
default:
PRETTY_PRINT("Unknown tag num %" PRIu32, tagNum);
break;
}
}
PRETTY_PRINT("},");
PRETTY_PRINT("");
// if we have exhausted this container
if (CHIP_END_OF_TLV == err)
{
// check for required fields:
const uint16_t requiredFields = (1 << to_underlying(Tag::kCommandId)) | (1 << to_underlying(Tag::kClusterId));
err = (tagPresenceMask & requiredFields) == requiredFields ? CHIP_NO_ERROR : CHIP_ERROR_IM_MALFORMED_COMMAND_PATH_IB;
}
ReturnErrorOnFailure(err);
return reader.ExitContainer(mOuterContainerType);
}
#endif // CHIP_CONFIG_IM_ENABLE_SCHEMA_CHECK
CHIP_ERROR CommandPathIB::Parser::GetEndpointId(chip::EndpointId * const apEndpointID) const
{
return GetUnsignedInteger(to_underlying(Tag::kEndpointId), apEndpointID);
}
CHIP_ERROR CommandPathIB::Parser::GetClusterId(chip::ClusterId * const apClusterId) const
{
return GetUnsignedInteger(to_underlying(Tag::kClusterId), apClusterId);
}
CHIP_ERROR CommandPathIB::Parser::GetCommandId(chip::CommandId * const apCommandId) const
{
return GetUnsignedInteger(to_underlying(Tag::kCommandId), apCommandId);
}
CommandPathIB::Builder & CommandPathIB::Builder::EndpointId(const chip::EndpointId aEndpointId)
{
// skip if error has already been set
if (mError == CHIP_NO_ERROR)
{
mError = mpWriter->Put(TLV::ContextTag(to_underlying(Tag::kEndpointId)), aEndpointId);
}
return *this;
}
CommandPathIB::Builder & CommandPathIB::Builder::ClusterId(const chip::ClusterId aClusterId)
{
// skip if error has already been set
if (mError == CHIP_NO_ERROR)
{
mError = mpWriter->Put(TLV::ContextTag(to_underlying(Tag::kClusterId)), aClusterId);
}
return *this;
}
CommandPathIB::Builder & CommandPathIB::Builder::CommandId(const chip::CommandId aCommandId)
{
// skip if error has already been set
if (mError == CHIP_NO_ERROR)
{
mError = mpWriter->Put(TLV::ContextTag(to_underlying(Tag::kCommandId)), aCommandId);
}
return *this;
}
CommandPathIB::Builder & CommandPathIB::Builder::EndOfCommandPathIB()
{
EndOfContainer();
return *this;
}
CHIP_ERROR CommandPathIB::Builder::Encode(const CommandPathParams & aCommandPathParams)
{
if (aCommandPathParams.mFlags.Has(CommandPathFlags::kEndpointIdValid))
{
EndpointId(aCommandPathParams.mEndpointId);
}
ClusterId(aCommandPathParams.mClusterId).CommandId(aCommandPathParams.mCommandId).EndOfCommandPathIB();
return GetError();
}
CHIP_ERROR CommandPathIB::Builder::Encode(const ConcreteCommandPath & aConcreteCommandPath)
{
EndpointId(aConcreteCommandPath.mEndpointId)
.ClusterId(aConcreteCommandPath.mClusterId)
.CommandId(aConcreteCommandPath.mCommandId)
.EndOfCommandPathIB();
return GetError();
}
}; // namespace app
}; // namespace chip
<|endoftext|> |
<commit_before>/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdlib.h>
#include <set>
#include <process/defer.hpp>
#include <process/delay.hpp>
#include <process/id.hpp>
#include <process/process.hpp>
#include <stout/foreach.hpp>
#include <stout/hashmap.hpp>
#include <stout/lambda.hpp>
#include <stout/none.hpp>
#include <stout/option.hpp>
#include "common/type_utils.hpp"
#include "log/catchup.hpp"
#include "log/recover.hpp"
#include "messages/log.hpp"
using namespace process;
using std::set;
namespace mesos {
namespace internal {
namespace log {
// This process is used to recover a replica. The flow of the recover
// process is described as follows:
// A) Check the status of the local replica.
// A1) If it is VOTING, exit.
// A2) If it is not VOTING, goto (B).
// B) Broadcast a RecoverRequest to all replicas in the network.
// B1) <<< Catch-up >>> If a quorum of replicas are found in VOTING
// status (no matter what the status of the local replica is),
// set the status of the local replica to RECOVERING, and start
// doing catch-up. If the local replica has been caught-up, set
// the status of the local replica to VOTING and exit.
// B2) If a quorum is not found, goto (B).
//
// In the following, we list a few scenarios and show how the recover
// process will respond in those scenarios. All the examples assume a
// quorum size of 2. Remember that a new replica is always put in
// EMPTY status initially.
//
// 1) Replica A, B and C are all in VOTING status. The operator adds
// replica D. In that case, D will go into RECOVERING status and
// then go into VOTING status. Therefore, we should avoid adding a
// new replica unless we know that one replica has been removed.
//
// 2) Replica A and B are in VOTING status. The operator adds replica
// C. In that case, C will go into RECOVERING status and then go
// into VOTING status, which is expected.
//
// 3) Replica A is in VOTING status. The operator adds replica B. In
// that case, B will stay in EMPTY status forever. This is expected
// because we cannot make progress if VOTING replicas are not
// enough (i.e., less than quorum).
//
// 4) Replica A is in VOTING status and B is in EMPTY status. The
// operator adds replica C. In that case, C will stay in EMPTY
// status forever similar to case 3).
class RecoverProcess : public Process<RecoverProcess>
{
public:
RecoverProcess(
size_t _quorum,
const Owned<Replica>& _replica,
const Shared<Network>& _network)
: ProcessBase(ID::generate("log-recover")),
quorum(_quorum),
replica(_replica),
network(_network) {}
Future<Owned<Replica> > future() { return promise.future(); }
protected:
virtual void initialize()
{
LOG(INFO) << "Start recovering a replica";
// Stop when no one cares.
promise.future().onDiscarded(lambda::bind(
static_cast<void(*)(const UPID&, bool)>(terminate), self(), true));
// Check the current status of the local replica and decide if
// recovery is needed. Recovery is needed if the local replica is
// not in VOTING status.
replica->status().onAny(defer(self(), &Self::checked, lambda::_1));
}
virtual void finalize()
{
LOG(INFO) << "Recover process terminated";
// Cancel all operations if they are still pending.
discard(responses);
catching.discard();
}
private:
void checked(const Future<Metadata::Status>& future)
{
if (!future.isReady()) {
promise.fail(
future.isFailed() ?
"Failed to get replica status: " + future.failure() :
"Not expecting discarded future");
terminate(self());
return;
}
status = future.get();
LOG(INFO) << "Replica is in " << status << " status";
if (status == Metadata::VOTING) {
promise.set(replica);
terminate(self());
} else {
recover();
}
}
void recover()
{
CHECK_NE(status, Metadata::VOTING);
// Wait until there are enough (i.e., quorum of) replicas in the
// network to avoid unnecessary retries.
network->watch(quorum, Network::GREATER_THAN_OR_EQUAL_TO)
.onAny(defer(self(), &Self::watched, lambda::_1));
}
void watched(const Future<size_t>& future)
{
if (!future.isReady()) {
promise.fail(
future.isFailed() ?
future.failure() :
"Not expecting discarded future");
terminate(self());
return;
}
CHECK_GE(future.get(), quorum);
// Broadcast recover request to all replicas.
network->broadcast(protocol::recover, RecoverRequest())
.onAny(defer(self(), &Self::broadcasted, lambda::_1));
}
void broadcasted(const Future<set<Future<RecoverResponse> > >& future)
{
if (!future.isReady()) {
promise.fail(
future.isFailed() ?
"Failed to broadcast the recover request: " + future.failure() :
"Not expecting discarded future");
terminate(self());
return;
}
responses = future.get();
if (responses.empty()) {
// Retry if no replica is currently in the network.
retry();
} else {
// Instead of using a for loop here, we use select to process
// responses one after another so that we can ignore the rest if
// we have collected enough responses.
select(responses)
.onReady(defer(self(), &Self::received, lambda::_1));
// Reset the counters.
responsesReceived.clear();
lowestBeginPosition = None();
highestEndPosition = None();
}
}
void received(const Future<RecoverResponse>& future)
{
// Enforced by the select semantics.
CHECK(future.isReady());
// Remove this future from 'responses' so that we do not listen on
// it the next time we invoke select.
responses.erase(future);
const RecoverResponse& response = future.get();
LOG(INFO) << "Received a recover response from a replica in "
<< response.status() << " status";
responsesReceived[response.status()]++;
// We need to remember the lowest begin position and highest end
// position seen from VOTING replicas.
if (response.status() == Metadata::VOTING) {
CHECK(response.has_begin() && response.has_end());
lowestBeginPosition = min(lowestBeginPosition, response.begin());
highestEndPosition = max(highestEndPosition, response.end());
}
// If we got responses from a quorum of VOTING replicas, the local
// replica will be put in RECOVERING status and start catching up.
// It is likely that the local replica is in RECOVERING status
// already. This is the case where the replica crashes during
// catch-up. When it restarts, we need to recalculate the lowest
// begin position and the highest end position since we haven't
// persisted this information on disk.
if (responsesReceived[Metadata::VOTING] >= quorum) {
discard(responses);
update(Metadata::RECOVERING);
return;
}
if (responses.empty()) {
// All responses have been received but neither have we received
// enough responses from VOTING replicas to do catch-up, nor are
// we in start-up case. This is either because we don't have
// enough replicas in the network (e.g. ZooKeeper blip), or we
// don't have enough VOTING replicas to proceed. We will retry
// the recovery in both cases.
retry();
} else {
// Wait for the next response.
select(responses)
.onReady(defer(self(), &Self::received, lambda::_1));
}
}
void update(const Metadata::Status& _status)
{
LOG(INFO) << "Updating replica status from "
<< status << " to " << _status;
replica->update(_status)
.onAny(defer(self(), &Self::updated, _status, lambda::_1));
}
void updated(const Metadata::Status& _status, const Future<bool>& future)
{
if (!future.isReady()) {
promise.fail(
future.isFailed() ?
"Failed to update replica status: " + future.failure() :
"Not expecting discarded future");
terminate(self());
return;
} else if (!future.get()) {
promise.fail("Failed to update replica status");
terminate(self());
return;
}
// The replica status has been updated successfully. Depending on
// the new status, we decide what the next action should be.
status = _status;
if (status == Metadata::VOTING) {
LOG(INFO) << "Successfully joined the Paxos group";
promise.set(replica);
terminate(self());
} else if (status == Metadata::RECOVERING) {
catchup();
} else {
// The replica should not be in any other status.
LOG(FATAL) << "Unexpected replica status";
}
}
void catchup()
{
// We reach here either because the log is empty (uninitialized),
// or the log is not empty but a previous unfinished catch-up
// attempt has been detected (the process crashes/killed when
// catching up). In either case, the local replica may have lost
// some data and Paxos states, and should not be allowed to vote.
// Otherwise, we may introduce inconsistency in the log as the
// local replica could have accepted a write which it would not
// have accepted if the data and the Paxos states were not lost.
// Now, the question is how many positions the local replica
// should catch up before it can be allowed to vote. We find that
// it is sufficient to catch-up positions from _begin_ to _end_
// where _begin_ is the smallest position seen in a quorum of
// VOTING replicas and _end_ is the largest position seen in a
// quorum of VOTING replicas. Here is the correctness argument.
// For a position _e_ larger than _end_, obviously no value has
// been agreed on for that position. Otherwise, we should find at
// least one VOTING replica in a quorum of replicas such that its
// end position is larger than _end_. For the same reason, a
// coordinator should not have collected enough promises for
// position _e_. Therefore, it's safe for the local replica to
// vote for that position. For a position _b_ smaller than
// _begin_, it should have already been truncated and the
// truncation should have already been agreed. Therefore, allowing
// the local replica to vote for that position is safe.
CHECK(lowestBeginPosition.isSome());
CHECK(highestEndPosition.isSome());
CHECK_LE(lowestBeginPosition.get(), highestEndPosition.get());
uint64_t begin = lowestBeginPosition.get();
uint64_t end = highestEndPosition.get();
set<uint64_t> positions;
for (uint64_t p = begin; p <= end; ++p) {
positions.insert(p);
}
// Share the ownership of the replica. From this point until the
// point where the ownership of the replica is regained, we should
// not access the 'replica' field.
Shared<Replica> shared = replica.share();
// Since we do not know what proposal number to use (the log is
// empty), we use proposal number 0 and leave log::catchup to
// automatically bump the proposal number.
catching = log::catchup(quorum, shared, network, 0, positions);
catching.onAny(defer(self(), &Self::caughtup, shared, lambda::_1));
}
void caughtup(Shared<Replica> shared, const Future<Nothing>& future)
{
if (!future.isReady()) {
promise.fail(
future.isFailed() ?
"Failed to catch-up: " + future.failure() :
"Not expecting discarded future");
terminate(self());
} else {
// Try to regain the ownership of the replica.
shared.own().onAny(defer(self(), &Self::owned, lambda::_1));
}
}
void owned(const Future<Owned<Replica> >& future)
{
if (!future.isReady()) {
promise.fail(
future.isFailed() ?
"Failed to own the replica: " + future.failure() :
"Not expecting discarded future");
terminate(self());
} else {
// Allow the replica to vote once the catch-up is done.
replica = future.get();
update(Metadata::VOTING);
}
}
void retry()
{
// We add a random delay before each retry because we do not want
// to saturate the network/disk IO in some cases (e.g., network
// size is less than quorum). The delay is chosen randomly to
// reduce the likelihood of conflicts (i.e., a replica receives a
// recover request while it is changing its status).
static const Duration T = Milliseconds(500);
Duration d = T * (1.0 + (double) ::random() / RAND_MAX);
delay(d, self(), &Self::recover);
}
const size_t quorum;
Owned<Replica> replica;
const Shared<Network> network;
Metadata::Status status;
set<Future<RecoverResponse> > responses;
hashmap<Metadata::Status, size_t> responsesReceived;
Option<uint64_t> lowestBeginPosition;
Option<uint64_t> highestEndPosition;
Future<Nothing> catching;
process::Promise<Owned<Replica> > promise;
};
Future<Owned<Replica> > recover(
size_t quorum,
const Owned<Replica>& replica,
const Shared<Network>& network)
{
RecoverProcess* process = new RecoverProcess(quorum, replica, network);
Future<Owned<Replica> > future = process->future();
spawn(process, true);
return future;
}
} // namespace log {
} // namespace internal {
} // namespace mesos {
<commit_msg>Added a logging message in log recover process.<commit_after>/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdlib.h>
#include <set>
#include <process/defer.hpp>
#include <process/delay.hpp>
#include <process/id.hpp>
#include <process/process.hpp>
#include <stout/foreach.hpp>
#include <stout/hashmap.hpp>
#include <stout/lambda.hpp>
#include <stout/none.hpp>
#include <stout/option.hpp>
#include "common/type_utils.hpp"
#include "log/catchup.hpp"
#include "log/recover.hpp"
#include "messages/log.hpp"
using namespace process;
using std::set;
namespace mesos {
namespace internal {
namespace log {
// This process is used to recover a replica. The flow of the recover
// process is described as follows:
// A) Check the status of the local replica.
// A1) If it is VOTING, exit.
// A2) If it is not VOTING, goto (B).
// B) Broadcast a RecoverRequest to all replicas in the network.
// B1) <<< Catch-up >>> If a quorum of replicas are found in VOTING
// status (no matter what the status of the local replica is),
// set the status of the local replica to RECOVERING, and start
// doing catch-up. If the local replica has been caught-up, set
// the status of the local replica to VOTING and exit.
// B2) If a quorum is not found, goto (B).
//
// In the following, we list a few scenarios and show how the recover
// process will respond in those scenarios. All the examples assume a
// quorum size of 2. Remember that a new replica is always put in
// EMPTY status initially.
//
// 1) Replica A, B and C are all in VOTING status. The operator adds
// replica D. In that case, D will go into RECOVERING status and
// then go into VOTING status. Therefore, we should avoid adding a
// new replica unless we know that one replica has been removed.
//
// 2) Replica A and B are in VOTING status. The operator adds replica
// C. In that case, C will go into RECOVERING status and then go
// into VOTING status, which is expected.
//
// 3) Replica A is in VOTING status. The operator adds replica B. In
// that case, B will stay in EMPTY status forever. This is expected
// because we cannot make progress if VOTING replicas are not
// enough (i.e., less than quorum).
//
// 4) Replica A is in VOTING status and B is in EMPTY status. The
// operator adds replica C. In that case, C will stay in EMPTY
// status forever similar to case 3).
class RecoverProcess : public Process<RecoverProcess>
{
public:
RecoverProcess(
size_t _quorum,
const Owned<Replica>& _replica,
const Shared<Network>& _network)
: ProcessBase(ID::generate("log-recover")),
quorum(_quorum),
replica(_replica),
network(_network) {}
Future<Owned<Replica> > future() { return promise.future(); }
protected:
virtual void initialize()
{
LOG(INFO) << "Start recovering a replica";
// Stop when no one cares.
promise.future().onDiscarded(lambda::bind(
static_cast<void(*)(const UPID&, bool)>(terminate), self(), true));
// Check the current status of the local replica and decide if
// recovery is needed. Recovery is needed if the local replica is
// not in VOTING status.
replica->status().onAny(defer(self(), &Self::checked, lambda::_1));
}
virtual void finalize()
{
LOG(INFO) << "Recover process terminated";
// Cancel all operations if they are still pending.
discard(responses);
catching.discard();
}
private:
void checked(const Future<Metadata::Status>& future)
{
if (!future.isReady()) {
promise.fail(
future.isFailed() ?
"Failed to get replica status: " + future.failure() :
"Not expecting discarded future");
terminate(self());
return;
}
status = future.get();
LOG(INFO) << "Replica is in " << status << " status";
if (status == Metadata::VOTING) {
promise.set(replica);
terminate(self());
} else {
recover();
}
}
void recover()
{
CHECK_NE(status, Metadata::VOTING);
// Wait until there are enough (i.e., quorum of) replicas in the
// network to avoid unnecessary retries.
network->watch(quorum, Network::GREATER_THAN_OR_EQUAL_TO)
.onAny(defer(self(), &Self::watched, lambda::_1));
}
void watched(const Future<size_t>& future)
{
if (!future.isReady()) {
promise.fail(
future.isFailed() ?
future.failure() :
"Not expecting discarded future");
terminate(self());
return;
}
CHECK_GE(future.get(), quorum);
// Broadcast recover request to all replicas.
network->broadcast(protocol::recover, RecoverRequest())
.onAny(defer(self(), &Self::broadcasted, lambda::_1));
}
void broadcasted(const Future<set<Future<RecoverResponse> > >& future)
{
if (!future.isReady()) {
promise.fail(
future.isFailed() ?
"Failed to broadcast the recover request: " + future.failure() :
"Not expecting discarded future");
terminate(self());
return;
}
responses = future.get();
if (responses.empty()) {
// Retry if no replica is currently in the network.
retry();
} else {
// Instead of using a for loop here, we use select to process
// responses one after another so that we can ignore the rest if
// we have collected enough responses.
select(responses)
.onReady(defer(self(), &Self::received, lambda::_1));
// Reset the counters.
responsesReceived.clear();
lowestBeginPosition = None();
highestEndPosition = None();
}
}
void received(const Future<RecoverResponse>& future)
{
// Enforced by the select semantics.
CHECK(future.isReady());
// Remove this future from 'responses' so that we do not listen on
// it the next time we invoke select.
responses.erase(future);
const RecoverResponse& response = future.get();
LOG(INFO) << "Received a recover response from a replica in "
<< response.status() << " status";
responsesReceived[response.status()]++;
// We need to remember the lowest begin position and highest end
// position seen from VOTING replicas.
if (response.status() == Metadata::VOTING) {
CHECK(response.has_begin() && response.has_end());
lowestBeginPosition = min(lowestBeginPosition, response.begin());
highestEndPosition = max(highestEndPosition, response.end());
}
// If we got responses from a quorum of VOTING replicas, the local
// replica will be put in RECOVERING status and start catching up.
// It is likely that the local replica is in RECOVERING status
// already. This is the case where the replica crashes during
// catch-up. When it restarts, we need to recalculate the lowest
// begin position and the highest end position since we haven't
// persisted this information on disk.
if (responsesReceived[Metadata::VOTING] >= quorum) {
discard(responses);
update(Metadata::RECOVERING);
return;
}
if (responses.empty()) {
// All responses have been received but neither have we received
// enough responses from VOTING replicas to do catch-up, nor are
// we in start-up case. This is either because we don't have
// enough replicas in the network (e.g. ZooKeeper blip), or we
// don't have enough VOTING replicas to proceed. We will retry
// the recovery in both cases.
retry();
} else {
// Wait for the next response.
select(responses)
.onReady(defer(self(), &Self::received, lambda::_1));
}
}
void update(const Metadata::Status& _status)
{
LOG(INFO) << "Updating replica status from "
<< status << " to " << _status;
replica->update(_status)
.onAny(defer(self(), &Self::updated, _status, lambda::_1));
}
void updated(const Metadata::Status& _status, const Future<bool>& future)
{
if (!future.isReady()) {
promise.fail(
future.isFailed() ?
"Failed to update replica status: " + future.failure() :
"Not expecting discarded future");
terminate(self());
return;
} else if (!future.get()) {
promise.fail("Failed to update replica status");
terminate(self());
return;
}
// The replica status has been updated successfully. Depending on
// the new status, we decide what the next action should be.
status = _status;
if (status == Metadata::VOTING) {
LOG(INFO) << "Successfully joined the Paxos group";
promise.set(replica);
terminate(self());
} else if (status == Metadata::RECOVERING) {
catchup();
} else {
// The replica should not be in any other status.
LOG(FATAL) << "Unexpected replica status";
}
}
void catchup()
{
// We reach here either because the log is empty (uninitialized),
// or the log is not empty but a previous unfinished catch-up
// attempt has been detected (the process crashes/killed when
// catching up). In either case, the local replica may have lost
// some data and Paxos states, and should not be allowed to vote.
// Otherwise, we may introduce inconsistency in the log as the
// local replica could have accepted a write which it would not
// have accepted if the data and the Paxos states were not lost.
// Now, the question is how many positions the local replica
// should catch up before it can be allowed to vote. We find that
// it is sufficient to catch-up positions from _begin_ to _end_
// where _begin_ is the smallest position seen in a quorum of
// VOTING replicas and _end_ is the largest position seen in a
// quorum of VOTING replicas. Here is the correctness argument.
// For a position _e_ larger than _end_, obviously no value has
// been agreed on for that position. Otherwise, we should find at
// least one VOTING replica in a quorum of replicas such that its
// end position is larger than _end_. For the same reason, a
// coordinator should not have collected enough promises for
// position _e_. Therefore, it's safe for the local replica to
// vote for that position. For a position _b_ smaller than
// _begin_, it should have already been truncated and the
// truncation should have already been agreed. Therefore, allowing
// the local replica to vote for that position is safe.
CHECK(lowestBeginPosition.isSome());
CHECK(highestEndPosition.isSome());
CHECK_LE(lowestBeginPosition.get(), highestEndPosition.get());
uint64_t begin = lowestBeginPosition.get();
uint64_t end = highestEndPosition.get();
LOG(INFO) << "Starting catch-up from position "
<< lowestBeginPosition.get() << " to "
<< highestEndPosition.get();
set<uint64_t> positions;
for (uint64_t p = begin; p <= end; ++p) {
positions.insert(p);
}
// Share the ownership of the replica. From this point until the
// point where the ownership of the replica is regained, we should
// not access the 'replica' field.
Shared<Replica> shared = replica.share();
// Since we do not know what proposal number to use (the log is
// empty), we use proposal number 0 and leave log::catchup to
// automatically bump the proposal number.
catching = log::catchup(quorum, shared, network, 0, positions);
catching.onAny(defer(self(), &Self::caughtup, shared, lambda::_1));
}
void caughtup(Shared<Replica> shared, const Future<Nothing>& future)
{
if (!future.isReady()) {
promise.fail(
future.isFailed() ?
"Failed to catch-up: " + future.failure() :
"Not expecting discarded future");
terminate(self());
} else {
// Try to regain the ownership of the replica.
shared.own().onAny(defer(self(), &Self::owned, lambda::_1));
}
}
void owned(const Future<Owned<Replica> >& future)
{
if (!future.isReady()) {
promise.fail(
future.isFailed() ?
"Failed to own the replica: " + future.failure() :
"Not expecting discarded future");
terminate(self());
} else {
// Allow the replica to vote once the catch-up is done.
replica = future.get();
update(Metadata::VOTING);
}
}
void retry()
{
// We add a random delay before each retry because we do not want
// to saturate the network/disk IO in some cases (e.g., network
// size is less than quorum). The delay is chosen randomly to
// reduce the likelihood of conflicts (i.e., a replica receives a
// recover request while it is changing its status).
static const Duration T = Milliseconds(500);
Duration d = T * (1.0 + (double) ::random() / RAND_MAX);
delay(d, self(), &Self::recover);
}
const size_t quorum;
Owned<Replica> replica;
const Shared<Network> network;
Metadata::Status status;
set<Future<RecoverResponse> > responses;
hashmap<Metadata::Status, size_t> responsesReceived;
Option<uint64_t> lowestBeginPosition;
Option<uint64_t> highestEndPosition;
Future<Nothing> catching;
process::Promise<Owned<Replica> > promise;
};
Future<Owned<Replica> > recover(
size_t quorum,
const Owned<Replica>& replica,
const Shared<Network>& network)
{
RecoverProcess* process = new RecoverProcess(quorum, replica, network);
Future<Owned<Replica> > future = process->future();
spawn(process, true);
return future;
}
} // namespace log {
} // namespace internal {
} // namespace mesos {
<|endoftext|> |
<commit_before><commit_msg>export showValue databar property<commit_after><|endoftext|> |
<commit_before>/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 "otbClassKMeansBase.h"
namespace otb
{
namespace Wrapper
{
class KMeansClassification: public ClassKMeansBase
{
public:
/** Standard class typedefs. */
typedef KMeansClassification Self;
typedef ClassKMeansBase Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(Self, Superclass);
private:
void DoInit() ITK_OVERRIDE
{
SetName("KMeansClassification");
SetDescription("Unsupervised KMeans image classification");
SetDocName("Unsupervised KMeans image classification");
SetDocLongDescription("Performs unsupervised KMeans image classification.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso(" ");
AddDocTag(Tags::Learning);
AddDocTag(Tags::Segmentation);
// Perform initialization
ClearApplications();
// initialisation parameters and synchronizes parameters
initKMParams();
if ( HasValue("vm") ) ConnectKMClassificationMask();
AddRANDParameter();
// Doc example parameter settings
SetDocExampleParameterValue("in", "QB_1_ortho.tif");
SetDocExampleParameterValue("ts", "1000");
SetDocExampleParameterValue("nc", "5");
SetDocExampleParameterValue("maxit", "1000");
SetDocExampleParameterValue("ct", "0.0001");
SetDocExampleParameterValue("out", "ClassificationFilterOutput.tif");
SetOfficialDocLink();
}
void DoUpdateParameters() ITK_OVERRIDE
{
}
void DoExecute() ITK_OVERRIDE
{
KMeansFileNamesHandler fileNames;
std::string fieldName = "field";
fileNames.CreateTemporaryFileNames(GetParameterString( "out" ));
// Create an image envelope
ComputeImageEnvelope(fileNames.tmpVectorFile);
// Add a new field at the ImageEnvelope output file
ComputeAddField(fileNames.tmpVectorFile, fieldName);
// Compute PolygonStatistics app
UpdateKMPolygonClassStatisticsParameters(fileNames.tmpVectorFile);
ComputePolygonStatistics(fileNames.polyStatOutput, fieldName);
// Compute number of sample max for KMeans
const int theoricNBSamplesForKMeans = GetParameterInt("ts");
const int upperThresholdNBSamplesForKMeans = 1000 * 1000;
const int actualNBSamplesForKMeans = std::min(theoricNBSamplesForKMeans,
upperThresholdNBSamplesForKMeans);
otbAppLogINFO(<< actualNBSamplesForKMeans << " is the maximum sample size that will be used." \
<< std::endl);
// Compute SampleSelection and SampleExtraction app
SelectAndExtractSamples(fileNames.polyStatOutput, fieldName,
fileNames.sampleSelectOutput,
fileNames.sampleExtractOutput,
actualNBSamplesForKMeans);
// Compute a train model with TrainVectorClassifier app
TrainKMModel(GetParameterImage("in"), fileNames.sampleExtractOutput,
fileNames.modelFile);
// Compute a classification of the input image according to a model file
KMeansClassif();
// remove all tempory files
if( IsParameterEnabled( "cleanup" ) )
{
otbAppLogINFO( <<"Final clean-up ..." );
fileNames.clear();
}
}
private :
void UpdateKMPolygonClassStatisticsParameters(const std::string &vectorFileName)
{
GetInternalApplication( "polystats" )->SetParameterString( "vec", vectorFileName, false );
UpdateInternalParameters( "polystats" );
}
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::KMeansClassification)
<commit_msg>ENH: test mask<commit_after>/*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.org/
*
* 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 "otbClassKMeansBase.h"
namespace otb
{
namespace Wrapper
{
class KMeansClassification: public ClassKMeansBase
{
public:
/** Standard class typedefs. */
typedef KMeansClassification Self;
typedef ClassKMeansBase Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(Self, Superclass);
private:
void DoInit() ITK_OVERRIDE
{
SetName("KMeansClassification");
SetDescription("Unsupervised KMeans image classification");
SetDocName("Unsupervised KMeans image classification");
SetDocLongDescription("Performs unsupervised KMeans image classification.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso(" ");
AddDocTag(Tags::Learning);
AddDocTag(Tags::Segmentation);
// Perform initialization
ClearApplications();
// initialisation parameters and synchronizes parameters
initKMParams();
if (IsParameterEnabled("vm") && HasValue("vm")) ConnectKMClassificationMask();
AddRANDParameter();
// Doc example parameter settings
SetDocExampleParameterValue("in", "QB_1_ortho.tif");
SetDocExampleParameterValue("ts", "1000");
SetDocExampleParameterValue("nc", "5");
SetDocExampleParameterValue("maxit", "1000");
SetDocExampleParameterValue("ct", "0.0001");
SetDocExampleParameterValue("out", "ClassificationFilterOutput.tif");
SetOfficialDocLink();
}
void DoUpdateParameters() ITK_OVERRIDE
{
}
void DoExecute() ITK_OVERRIDE
{
KMeansFileNamesHandler fileNames;
std::string fieldName = "field";
fileNames.CreateTemporaryFileNames(GetParameterString( "out" ));
// Create an image envelope
ComputeImageEnvelope(fileNames.tmpVectorFile);
// Add a new field at the ImageEnvelope output file
ComputeAddField(fileNames.tmpVectorFile, fieldName);
// Compute PolygonStatistics app
UpdateKMPolygonClassStatisticsParameters(fileNames.tmpVectorFile);
ComputePolygonStatistics(fileNames.polyStatOutput, fieldName);
// Compute number of sample max for KMeans
const int theoricNBSamplesForKMeans = GetParameterInt("ts");
const int upperThresholdNBSamplesForKMeans = 1000 * 1000;
const int actualNBSamplesForKMeans = std::min(theoricNBSamplesForKMeans,
upperThresholdNBSamplesForKMeans);
otbAppLogINFO(<< actualNBSamplesForKMeans << " is the maximum sample size that will be used." \
<< std::endl);
// Compute SampleSelection and SampleExtraction app
SelectAndExtractSamples(fileNames.polyStatOutput, fieldName,
fileNames.sampleSelectOutput,
fileNames.sampleExtractOutput,
actualNBSamplesForKMeans);
// Compute a train model with TrainVectorClassifier app
TrainKMModel(GetParameterImage("in"), fileNames.sampleExtractOutput,
fileNames.modelFile);
// Compute a classification of the input image according to a model file
KMeansClassif();
// remove all tempory files
if( IsParameterEnabled( "cleanup" ) )
{
otbAppLogINFO( <<"Final clean-up ..." );
fileNames.clear();
}
}
private :
void UpdateKMPolygonClassStatisticsParameters(const std::string &vectorFileName)
{
GetInternalApplication( "polystats" )->SetParameterString( "vec", vectorFileName, false );
UpdateInternalParameters( "polystats" );
}
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::KMeansClassification)
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date: 2007-07-09 18:14:41 +0200 (Mo, 09 Jul 2007) $
Version: $Revision: 11185 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkNavigationDataObjectVisualizationFilter.h"
#include "mitkDataStorage.h"
mitk::NavigationDataObjectVisualizationFilter::NavigationDataObjectVisualizationFilter()
: NavigationDataToNavigationDataFilter()
{
m_RepresentationList.clear();
}
mitk::NavigationDataObjectVisualizationFilter::~NavigationDataObjectVisualizationFilter()
{
m_RepresentationList.clear();
}
const mitk::BaseData* mitk::NavigationDataObjectVisualizationFilter::GetBaseData(unsigned int idx)
{
//if (idx >= this->GetNumberOfInputs())
// return NULL;
//const NavigationData* nd = this->GetInput(idx);
//if (nd == NULL)
// return NULL;
RepresentationPointerMap::const_iterator iter = m_RepresentationList.find(idx);
if (iter != m_RepresentationList.end())
return iter->second;
return NULL;
}
void mitk::NavigationDataObjectVisualizationFilter::SetBaseData(unsigned int idx, BaseData* data)
{
//if (idx >= this->GetNumberOfInputs())
// return false;
//const NavigationData* nd = this->GetInput(idx);
//if (nd == NULL || data == NULL)
// return false;
m_RepresentationList[idx] = RepresentationPointer(data);
//std::pair<RepresentationPointerMap::iterator, bool> returnEl; //pair for returning the result
//returnEl = m_RepresentationList.insert( RepresentationPointerMap::value_type(nd, data) ); //insert the given elements
//return returnEl.second; // return if insert was successful
}
void mitk::NavigationDataObjectVisualizationFilter::GenerateData()
{
/*get each input, lookup the associated BaseData and transfer the data*/
DataObjectPointerArray inputs = this->GetInputs(); //get all inputs
for (unsigned int index=0; index < inputs.size(); index++)
{
//get the needed variables
const mitk::NavigationData* nd = this->GetInput(index);
assert(nd);
mitk::NavigationData* output = this->GetOutput(index);
assert(output);
//check if the data is valid
if (!nd->IsDataValid())
{
output->SetDataValid(false);
continue;
}
output->Graft(nd); // copy all information from input to output
const mitk::BaseData* data = this->GetBaseData(index);
if (data == NULL)
{
itkWarningMacro("NavigationDataObjectVisualizationFilter: Wrong/No BaseData associated with input.");
return;
}
//get the transform from data
mitk::AffineTransform3D::Pointer affineTransform = data->GetGeometry()->GetIndexToWorldTransform();
if (affineTransform.IsNull())
{
//replace with mitk standard output
itkWarningMacro("NavigationDataObjectVisualizationFilter: AffineTransform IndexToWorldTransform not initialized!");
return;
}
//store the current scaling to set it after transformation
mitk::Vector3D spacing = data->GetGeometry()->GetSpacing();
//clear spacing of data to be able to set it again afterwards
float scale[] = {1.0, 1.0, 1.0};
data->GetGeometry()->SetSpacing(scale);
/*now bring quaternion to affineTransform by using vnl_Quaternion*/
affineTransform->SetIdentity();
//calculate the transform from the quaternions
static itk::QuaternionRigidTransform<double>::Pointer quatTransform = itk::QuaternionRigidTransform<double>::New();
mitk::NavigationData::OrientationType orientation = nd->GetOrientation();
// convert mitk::Scalartype quaternion to double quaternion because of itk bug
vnl_quaternion<double> doubleQuaternion(orientation.x(), orientation.y(), orientation.z(), orientation.r());
quatTransform->SetIdentity();
quatTransform->SetRotation(doubleQuaternion);
quatTransform->Modified();
/* because of an itk bug, the transform can not be calculated with float data type.
To use it in the mitk geometry classes, it has to be transfered to mitk::ScalarType which is float */
static AffineTransform3D::MatrixType m;
mitk::TransferMatrix(quatTransform->GetMatrix(), m);
affineTransform->SetMatrix(m);
///*set the offset by convert from itkPoint to itkVector and setting offset of transform*/
mitk::Vector3D pos;
pos.Set_vnl_vector(nd->GetPosition().Get_vnl_vector());
affineTransform->SetOffset(pos);
affineTransform->Modified();
//set the transform to data
data->GetGeometry()->SetIndexToWorldTransform(affineTransform);
//set the original spacing to keep scaling of the geometrical object
data->GetGeometry()->SetSpacing(spacing);
data->GetGeometry()->Modified();
data->Modified();
output->SetDataValid(true); // operation was successful, therefore data of output is valid.
}
}
<commit_msg>FIX (#2092): vtk transform inside the Geometry3D has to be updated too.<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date: 2007-07-09 18:14:41 +0200 (Mo, 09 Jul 2007) $
Version: $Revision: 11185 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkNavigationDataObjectVisualizationFilter.h"
#include "mitkDataStorage.h"
mitk::NavigationDataObjectVisualizationFilter::NavigationDataObjectVisualizationFilter()
: NavigationDataToNavigationDataFilter()
{
m_RepresentationList.clear();
}
mitk::NavigationDataObjectVisualizationFilter::~NavigationDataObjectVisualizationFilter()
{
m_RepresentationList.clear();
}
const mitk::BaseData* mitk::NavigationDataObjectVisualizationFilter::GetBaseData(unsigned int idx)
{
//if (idx >= this->GetNumberOfInputs())
// return NULL;
//const NavigationData* nd = this->GetInput(idx);
//if (nd == NULL)
// return NULL;
RepresentationPointerMap::const_iterator iter = m_RepresentationList.find(idx);
if (iter != m_RepresentationList.end())
return iter->second;
return NULL;
}
void mitk::NavigationDataObjectVisualizationFilter::SetBaseData(unsigned int idx, BaseData* data)
{
//if (idx >= this->GetNumberOfInputs())
// return false;
//const NavigationData* nd = this->GetInput(idx);
//if (nd == NULL || data == NULL)
// return false;
m_RepresentationList[idx] = RepresentationPointer(data);
//std::pair<RepresentationPointerMap::iterator, bool> returnEl; //pair for returning the result
//returnEl = m_RepresentationList.insert( RepresentationPointerMap::value_type(nd, data) ); //insert the given elements
//return returnEl.second; // return if insert was successful
}
void mitk::NavigationDataObjectVisualizationFilter::GenerateData()
{
/*get each input, lookup the associated BaseData and transfer the data*/
DataObjectPointerArray inputs = this->GetInputs(); //get all inputs
for (unsigned int index=0; index < inputs.size(); index++)
{
//get the needed variables
const mitk::NavigationData* nd = this->GetInput(index);
assert(nd);
mitk::NavigationData* output = this->GetOutput(index);
assert(output);
//check if the data is valid
if (!nd->IsDataValid())
{
output->SetDataValid(false);
continue;
}
output->Graft(nd); // copy all information from input to output
const mitk::BaseData* data = this->GetBaseData(index);
if (data == NULL)
{
itkWarningMacro("NavigationDataObjectVisualizationFilter: Wrong/No BaseData associated with input.");
return;
}
//get the transform from data
mitk::AffineTransform3D::Pointer affineTransform = data->GetGeometry()->GetIndexToWorldTransform();
if (affineTransform.IsNull())
{
//replace with mitk standard output
itkWarningMacro("NavigationDataObjectVisualizationFilter: AffineTransform IndexToWorldTransform not initialized!");
return;
}
//store the current scaling to set it after transformation
mitk::Vector3D spacing = data->GetGeometry()->GetSpacing();
//clear spacing of data to be able to set it again afterwards
float scale[] = {1.0, 1.0, 1.0};
data->GetGeometry()->SetSpacing(scale);
/*now bring quaternion to affineTransform by using vnl_Quaternion*/
affineTransform->SetIdentity();
//calculate the transform from the quaternions
static itk::QuaternionRigidTransform<double>::Pointer quatTransform = itk::QuaternionRigidTransform<double>::New();
mitk::NavigationData::OrientationType orientation = nd->GetOrientation();
// convert mitk::Scalartype quaternion to double quaternion because of itk bug
vnl_quaternion<double> doubleQuaternion(orientation.x(), orientation.y(), orientation.z(), orientation.r());
quatTransform->SetIdentity();
quatTransform->SetRotation(doubleQuaternion);
quatTransform->Modified();
/* because of an itk bug, the transform can not be calculated with float data type.
To use it in the mitk geometry classes, it has to be transfered to mitk::ScalarType which is float */
static AffineTransform3D::MatrixType m;
mitk::TransferMatrix(quatTransform->GetMatrix(), m);
affineTransform->SetMatrix(m);
///*set the offset by convert from itkPoint to itkVector and setting offset of transform*/
mitk::Vector3D pos;
pos.Set_vnl_vector(nd->GetPosition().Get_vnl_vector());
affineTransform->SetOffset(pos);
affineTransform->Modified();
//set the transform to data
data->GetGeometry()->SetIndexToWorldTransform(affineTransform);
//set the original spacing to keep scaling of the geometrical object
data->GetGeometry()->SetSpacing(spacing);
data->GetGeometry()->TransferItkToVtkTransform(); // update VTK Transform for rendering too
data->GetGeometry()->Modified();
data->Modified();
output->SetDataValid(true); // operation was successful, therefore data of output is valid.
}
}
<|endoftext|> |
<commit_before>AliAnalysisTask *AddTask_cbaumann_LMEEPbPb2011AODSemiCent(Bool_t runAll=kFALSE,Bool_t setMC=kFALSE,Bool_t getFromAlien=kFALSE, Bool_t PIDbaseline=kFALSE){
Bool_t bESDANA=kFALSE; //Autodetect via InputHandler
//get the current analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTask_cbaumann_LMEEPbPb2011", "No analysis manager found.");
return 0;
}
// create task and add it to the manager
// gSystem->AddIncludePath("$ALICE_ROOT/PWGDQ/dielectron/macrosLMEE");
TString configBasePath("$TRAIN_ROOT/cbaumann_dielectron/");
TString trainRoot=gSystem->Getenv("TRAIN_ROOT");
if (trainRoot.IsNull()) configBasePath= "$ALICE_ROOT/PWGDQ/dielectron/macrosLMEE/";
if (getFromAlien &&
(!gSystem->Exec("alien_cp alien:///alice/cern.ch/user/c/cbaumann/PWGDQ/dielectron/macrosLMEE/ConfigLMEEPbPb2011AOD.C .")) &&
(!gSystem->Exec("alien_cp alien:///alice/cern.ch/user/c/cbaumann/PWGDQ/dielectron/macrosLMEE/LMEECutLibAOD.C ."))
) {
configBasePath=Form("%s/",gSystem->pwd());
}
TString configFile("ConfigLMEEPbPb2011AOD.C");
TString configLMEECutLib("LMEECutLibAOD.C");
TString configFilePath(configBasePath+configFile);
TString configLMEECutLibPath(configBasePath+configLMEECutLib);
//AOD Usage currently tested with separate task, to be merged
if (mgr->GetInputEventHandler()->IsA()==AliAODInputHandler::Class()){
::Info("AddTaskLMEEPbPb2011", "no dedicated AOD configuration");
}
else if (mgr->GetInputEventHandler()->IsA()==AliESDInputHandler::Class()){
::Info("AddTaskLMEEPbPb2011AOD","switching on ESD specific code");
bESDANA=kTRUE;
}
//Do we have an MC handler?
Bool_t hasMC=setMC;
if (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0)
hasMC=kTRUE;
if (!gROOT->GetListOfGlobalFunctions()->FindObject(configLMEECutLib.Data()))
gROOT->LoadMacro(configLMEECutLibPath.Data());
if (!gROOT->GetListOfGlobalFunctions()->FindObject(configFile.Data()))
gROOT->LoadMacro(configFilePath.Data());
LMEECutLib* cutlib = new LMEECutLib();
AliAnalysisTaskMultiDielectron *task=new AliAnalysisTaskMultiDielectron("MultiDiEData");
if (!hasMC) task->UsePhysicsSelection();
task->SetTriggerMask(AliVEvent::kMB+AliVEvent::kCentral+AliVEvent::kSemiCentral);
// task->SelectCollisionCandidates(AliVEvent::kMB+AliVEvent::kCentral+AliVEvent::kSemiCentral);
// task->SetRejectPileup();
task->SelectCollisionCandidates(AliVEvent::kAny);
task->SetEventFilter(cutlib->GetEventCuts(LMEECutLib::kPbPb2011TPCandTOF)); //
//load dielectron configuration file
//add dielectron analysis with different cuts to the task
AliDielectron *lowmass2=ConfigLMEEPbPb2011AOD(2,hasMC,bESDANA);
task->AddDielectron(lowmass2);
printf("add: %s\n",lowmass2->GetName());
AliDielectron *lowmass5=ConfigLMEEPbPb2011AOD(5,hasMC,bESDANA);
task->AddDielectron(lowmass5);
printf("add: %s\n",lowmass5->GetName());
if (PIDbaseline) {
AliDielectron *lowmass7=ConfigLMEEPbPb2011AOD(7,hasMC,bESDANA);
task->AddDielectron(lowmass7);
printf("add: %s\n",lowmass7->GetName());
}
mgr->AddTask(task);
//create output container
AliAnalysisDataContainer *coutput1 =
mgr->CreateContainer("cbaumann_LMEEPbPb2011_tree",
TTree::Class(),
AliAnalysisManager::kExchangeContainer,
"cbaumann_LMEEPbPb2011_default.root");
AliAnalysisDataContainer *cOutputHist1 =
mgr->CreateContainer("cbaumann_LMEEPbPb2011_out",
TList::Class(),
AliAnalysisManager::kOutputContainer,
"cbaumann_LMEEPbPb2011_out.root");
/* AliAnalysisDataContainer *cOutputHist2 =
mgr->CreateContainer("cbaumann_lowmass_CF",
TList::Class(),
AliAnalysisManager::kOutputContainer,
"cbaumann_lowmass_CF.root");
*/
AliAnalysisDataContainer *cOutputHist2 =
mgr->CreateContainer("cbaumann_LMEEPbPb2011_CF",
TList::Class(),
AliAnalysisManager::kOutputContainer,
"cbaumann_LMEEPbPb2011_out.root");
AliAnalysisDataContainer *cOutputHist3 =
mgr->CreateContainer("cbaumann_EventStatPbPb2011",
TH1D::Class(),
AliAnalysisManager::kOutputContainer,
"cbaumann_LMEEPbPb2011_out.root");
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 0, coutput1 );
mgr->ConnectOutput(task, 1, cOutputHist1);
mgr->ConnectOutput(task, 2, cOutputHist2);
mgr->ConnectOutput(task, 3, cOutputHist3);
return task;
}
<commit_msg>Fix container name for SemiCent task<commit_after>AliAnalysisTask *AddTask_cbaumann_LMEEPbPb2011AODSemiCent(Bool_t runAll=kFALSE,Bool_t setMC=kFALSE,Bool_t getFromAlien=kFALSE, Bool_t PIDbaseline=kFALSE){
Bool_t bESDANA=kFALSE; //Autodetect via InputHandler
//get the current analysis manager
AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
if (!mgr) {
Error("AddTask_cbaumann_LMEEPbPb2011", "No analysis manager found.");
return 0;
}
// create task and add it to the manager
// gSystem->AddIncludePath("$ALICE_ROOT/PWGDQ/dielectron/macrosLMEE");
TString configBasePath("$TRAIN_ROOT/cbaumann_dielectron/");
TString trainRoot=gSystem->Getenv("TRAIN_ROOT");
if (trainRoot.IsNull()) configBasePath= "$ALICE_ROOT/PWGDQ/dielectron/macrosLMEE/";
if (getFromAlien &&
(!gSystem->Exec("alien_cp alien:///alice/cern.ch/user/c/cbaumann/PWGDQ/dielectron/macrosLMEE/ConfigLMEEPbPb2011AOD.C .")) &&
(!gSystem->Exec("alien_cp alien:///alice/cern.ch/user/c/cbaumann/PWGDQ/dielectron/macrosLMEE/LMEECutLibAOD.C ."))
) {
configBasePath=Form("%s/",gSystem->pwd());
}
TString configFile("ConfigLMEEPbPb2011AOD.C");
TString configLMEECutLib("LMEECutLibAOD.C");
TString configFilePath(configBasePath+configFile);
TString configLMEECutLibPath(configBasePath+configLMEECutLib);
//AOD Usage currently tested with separate task, to be merged
if (mgr->GetInputEventHandler()->IsA()==AliAODInputHandler::Class()){
::Info("AddTaskLMEEPbPb2011", "no dedicated AOD configuration");
}
else if (mgr->GetInputEventHandler()->IsA()==AliESDInputHandler::Class()){
::Info("AddTaskLMEEPbPb2011AOD","switching on ESD specific code");
bESDANA=kTRUE;
}
//Do we have an MC handler?
Bool_t hasMC=setMC;
if (AliAnalysisManager::GetAnalysisManager()->GetMCtruthEventHandler()!=0x0)
hasMC=kTRUE;
if (!gROOT->GetListOfGlobalFunctions()->FindObject(configLMEECutLib.Data()))
gROOT->LoadMacro(configLMEECutLibPath.Data());
if (!gROOT->GetListOfGlobalFunctions()->FindObject(configFile.Data()))
gROOT->LoadMacro(configFilePath.Data());
LMEECutLib* cutlib = new LMEECutLib();
AliAnalysisTaskMultiDielectron *task=new AliAnalysisTaskMultiDielectron("MultiDiEData");
if (!hasMC) task->UsePhysicsSelection();
task->SetTriggerMask(AliVEvent::kMB+AliVEvent::kCentral+AliVEvent::kSemiCentral);
// task->SelectCollisionCandidates(AliVEvent::kMB+AliVEvent::kCentral+AliVEvent::kSemiCentral);
// task->SetRejectPileup();
task->SelectCollisionCandidates(AliVEvent::kAny);
task->SetEventFilter(cutlib->GetEventCuts(LMEECutLib::kPbPb2011TPCandTOF)); //
//load dielectron configuration file
//add dielectron analysis with different cuts to the task
AliDielectron *lowmass2=ConfigLMEEPbPb2011AOD(2,hasMC,bESDANA);
task->AddDielectron(lowmass2);
printf("add: %s\n",lowmass2->GetName());
AliDielectron *lowmass5=ConfigLMEEPbPb2011AOD(5,hasMC,bESDANA);
task->AddDielectron(lowmass5);
printf("add: %s\n",lowmass5->GetName());
if (PIDbaseline) {
AliDielectron *lowmass7=ConfigLMEEPbPb2011AOD(7,hasMC,bESDANA);
task->AddDielectron(lowmass7);
printf("add: %s\n",lowmass7->GetName());
}
mgr->AddTask(task);
//create output container
AliAnalysisDataContainer *coutput1 =
mgr->CreateContainer("cbaumann_LMEEPbPb2011SemiCent_tree",
TTree::Class(),
AliAnalysisManager::kExchangeContainer,
"cbaumann_LMEEPbPb2011_default.root");
AliAnalysisDataContainer *cOutputHist1 =
mgr->CreateContainer("cbaumann_LMEEPbPb2011SemiCent_out",
TList::Class(),
AliAnalysisManager::kOutputContainer,
"cbaumann_LMEEPbPb2011_out.root");
/* AliAnalysisDataContainer *cOutputHist2 =
mgr->CreateContainer("cbaumann_lowmassSemiCent_CF",
TList::Class(),
AliAnalysisManager::kOutputContainer,
"cbaumann_lowmass_CF.root");
*/
AliAnalysisDataContainer *cOutputHist2 =
mgr->CreateContainer("cbaumann_LMEEPbPb2011SemiCent_CF",
TList::Class(),
AliAnalysisManager::kOutputContainer,
"cbaumann_LMEEPbPb2011_out.root");
AliAnalysisDataContainer *cOutputHist3 =
mgr->CreateContainer("cbaumann_EventStatPbPb2011SemiCent",
TH1D::Class(),
AliAnalysisManager::kOutputContainer,
"cbaumann_LMEEPbPb2011_out.root");
mgr->ConnectInput(task, 0, mgr->GetCommonInputContainer());
mgr->ConnectOutput(task, 0, coutput1 );
mgr->ConnectOutput(task, 1, cOutputHist1);
mgr->ConnectOutput(task, 2, cOutputHist2);
mgr->ConnectOutput(task, 3, cOutputHist3);
return task;
}
<|endoftext|> |
<commit_before>
#include <string>
#include <iostream>
#include <openvoronoi/medial_axis_filter.hpp>
#include <openvoronoi/medial_axis_walk.hpp>
#include <openvoronoi/voronoidiagram.hpp>
#include <openvoronoi/polygon_interior_filter.hpp>
#include <openvoronoi/utility/vd2svg.hpp>
#include <openvoronoi/version.hpp>
// OpenVoronoi example program. Uses MedialAxis filter to filter the complete Voronoi diagram
// down to the medial axis.
// then uses MedialAxisWalk to walk along the medial axis and draw clearance-disks
int main() {
ovd::VoronoiDiagram* vd = new ovd::VoronoiDiagram(1,100); // (r, bins)
// double r: radius of circle within which all input geometry must fall. use 1 (unit-circle). Scale geometry if necessary.
// int bins: bins for face-grid search. roughly sqrt(n), where n is the number of sites is good according to Held.
std::cout << ovd::version() << "\n"; // the git revision-string
ovd::Point p0(-0.1,-0.2);
ovd::Point p1(0.2,0.1);
ovd::Point p2(0.4,0.2);
ovd::Point p3(0.6,0.6);
ovd::Point p4(-0.6,0.3);
int id0 = vd->insert_point_site(p0);
int id1 = vd->insert_point_site(p1);
int id2 = vd->insert_point_site(p2);
int id3 = vd->insert_point_site(p3);
int id4 = vd->insert_point_site(p4);
vd->insert_line_site(id0, id1);
vd->insert_line_site(id1, id2);
vd->insert_line_site(id2, id3);
vd->insert_line_site(id3, id4);
vd->insert_line_site(id4, id0);
vd->check();
// try commenting-out the line below; massive exterior clearance discs will
// be drawn!
ovd::polygon_interior_filter pi(true);
vd->filter(&pi);
ovd::medial_axis_filter ma;
vd->filter(&ma);
// save drawing to svg file.
svg::Dimensions dimensions(1024, 1024);
svg::Document doc("medial_axis.svg", svg::Layout(dimensions, svg::Layout::BottomLeft));
ovd::HEGraph& g = vd->get_graph_reference();
BOOST_FOREACH( ovd::HEEdge e, g.edges() ) {
if( g[e].valid ) write_edge_to_svd(g,doc,e);
}
// walk the medial axis.
ovd::MedialAxisWalk maw(g);
ovd::MedialChainList chain_list = maw.walk();
std::cout << "walking " << int(chain_list.size()) << " medial axis chains." << std::endl;
BOOST_FOREACH( ovd::MedialChain chain, chain_list ) { // loop through each chain
std::cout << "new chain length:" << int(chain.size()) << std::endl;
BOOST_FOREACH( ovd::MedialPointList pt_list, chain ) { //loop through each medial-point list
std::cout << "new point list length:" << int(pt_list.size()) << std::endl;
BOOST_FOREACH( ovd::MedialPoint pt, pt_list ) { //loop through each medial-point
std::cout << "pt:p:" << pt.p << ", clearance_radius:" << pt.clearance_radius << std::endl;
if (pt.clearance_radius < 0.001) {
std::cout << "(the clearance radius is so small that the rendered circle will be too tiny to see.)" << std::endl;
}
ovd::Point ctr( scale( pt.p ) );
double radius( scale( pt.clearance_radius ) );
// draw a circle, centered on the medial-axis, with radius = clearance-disc
svg::Circle clearance_disc( svg::Point( ctr.x, ctr.y ), 2*radius, svg::Fill(), svg::Stroke( 1, svg::Color::Red ) );
doc << clearance_disc;
}
}
}
doc.save();
std::cout << vd->print();
delete vd;
return 0;
}
<commit_msg>make example work<commit_after>
#include <string>
#include <iostream>
#include <openvoronoi/medial_axis_filter.hpp>
#include <openvoronoi/medial_axis_walk.hpp>
#include <openvoronoi/voronoidiagram.hpp>
#include <openvoronoi/polygon_interior_filter.hpp>
#include <openvoronoi/utility/vd2svg.hpp>
#include <openvoronoi/version.hpp>
// OpenVoronoi example program. Uses MedialAxis filter to filter the complete Voronoi diagram
// down to the medial axis.
// then uses MedialAxisWalk to walk along the medial axis and draw clearance-disks
int main() {
ovd::VoronoiDiagram* vd = new ovd::VoronoiDiagram(1,100); // (r, bins)
// double r: radius of circle within which all input geometry must fall. use 1 (unit-circle). Scale geometry if necessary.
// int bins: bins for face-grid search. roughly sqrt(n), where n is the number of sites is good according to Held.
std::cout << ovd::version() << "\n"; // the git revision-string
ovd::Point p0(-0.1,-0.2);
ovd::Point p1(0.2,0.1);
ovd::Point p2(0.4,0.2);
ovd::Point p3(0.6,0.6);
ovd::Point p4(-0.6,0.3);
int id0 = vd->insert_point_site(p0);
int id1 = vd->insert_point_site(p1);
int id2 = vd->insert_point_site(p2);
int id3 = vd->insert_point_site(p3);
int id4 = vd->insert_point_site(p4);
vd->insert_line_site(id0, id1);
vd->insert_line_site(id1, id2);
vd->insert_line_site(id2, id3);
vd->insert_line_site(id3, id4);
vd->insert_line_site(id4, id0);
vd->check();
// try commenting-out the line below; massive exterior clearance discs will
// be drawn!
ovd::polygon_interior_filter pi(true);
vd->filter(&pi);
ovd::medial_axis_filter ma;
vd->filter(&ma);
// save drawing to svg file.
svg::Dimensions dimensions(1024, 1024);
svg::Document doc("medial_axis.svg", svg::Layout(dimensions, svg::Layout::BottomLeft));
ovd::HEGraph& g = vd->get_graph_reference();
BOOST_FOREACH( ovd::HEEdge e, g.edges() ) {
if( g[e].valid ) write_edge_to_svg(g,doc,e);
}
// walk the medial axis.
ovd::MedialAxisWalk maw(g);
ovd::MedialChainList chain_list = maw.walk();
std::cout << "walking " << int(chain_list.size()) << " medial axis chains." << std::endl;
BOOST_FOREACH( ovd::MedialChain chain, chain_list ) { // loop through each chain
std::cout << "new chain length:" << int(chain.size()) << std::endl;
BOOST_FOREACH( ovd::MedialPointList pt_list, chain ) { //loop through each medial-point list
std::cout << "new point list length:" << int(pt_list.size()) << std::endl;
BOOST_FOREACH( ovd::MedialPoint pt, pt_list ) { //loop through each medial-point
std::cout << "pt:p:" << pt.p << ", clearance_radius:" << pt.clearance_radius << std::endl;
if (pt.clearance_radius < 0.001) {
std::cout << "(the clearance radius is so small that the rendered circle will be too tiny to see.)" << std::endl;
}
ovd::Point ctr( scale( pt.p ) );
double radius( scale( pt.clearance_radius ) );
// draw a circle, centered on the medial-axis, with radius = clearance-disc
svg::Circle clearance_disc( svg::Point( ctr.x, ctr.y ), 2*radius, svg::Fill(), svg::Stroke( 1, svg::Color::Red ) );
doc << clearance_disc;
}
}
}
doc.save();
std::cout << vd->print();
delete vd;
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Explicit copy ctor avoiding copying singular iterators<commit_after><|endoftext|> |
<commit_before><commit_msg>Use OUString::startsWith where possible<commit_after><|endoftext|> |
<commit_before>// MachiavelliGame.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Socket.h"
#include <thread>
#include <memory>
#include <string>
using namespace std;
void connect_to_server()
{
int port = 1080;
ClientSocket client("localhost", port);
}
int _tmain(int argc, _TCHAR* argv[])
{
//std::thread connection{ connect_to_server };//start server
//connection.detach();
ClientSocket* client = new ClientSocket("localhost", 1080);
string input = "";
while (true)
{
cin >> input;
cout << input << "\n>";
}
return 0;
}
<commit_msg>ok client and server both work need to think of a better stucture but we have the basis for greatness hiiiikuuuuuuuuuuuuuh!<commit_after>// MachiavelliGame.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "Socket.h"
#include <thread>
#include <string>
using namespace std;
void connect_to_server()
{
int port = 1080;
ClientSocket client("localhost", port);
}
int _tmain(int argc, _TCHAR* argv[])
{
//std::thread connection{ connect_to_server };//start server
//connection.detach();
ClientSocket* client = new ClientSocket("localhost", 1080);
string input = "";
while (true)
{
string cmd = client->readline();
cerr << cmd << '\n';
getline(cin, input);
client->write(input + "\n");
}
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <ql/quantlib.hpp>
using namespace std;
using namespace QuantLib;
boost::shared_ptr<YieldTermStructure>
flatRate(const Date& today,
const boost::shared_ptr<Quote>& forward,
const DayCounter& dc) {
return boost::shared_ptr<YieldTermStructure>(
new FlatForward(today, Handle<Quote>(forward), dc));
}
int main() {
const Size maturity = 2;
DayCounter dc = Actual365Fixed();
const Date today = Date::todaysDate();
const Real upperBarrier = 1.02;
const Real lowerBarrier = 0.86;
Settings::instance().evaluationDate() = today;
Handle<Quote> spot(boost::shared_ptr<Quote>(new SimpleQuote(1.)));
boost::shared_ptr<SimpleQuote> qRate(new SimpleQuote(0.0));
Handle<YieldTermStructure> qTS(flatRate(today, qRate, dc));
boost::shared_ptr<SimpleQuote> rRate(new SimpleQuote(0.05));
Handle<YieldTermStructure> rTS(flatRate(today, rRate, dc));
boost::shared_ptr<SimpleQuote> sRate(new SimpleQuote(0.0));
Handle<YieldTermStructure> sTS(flatRate(today, sRate, dc));
Handle<BlackVolTermStructure> vTS(boost::shared_ptr<BlackVolTermStructure>(new BlackConstantVol(today, NullCalendar(), 0.15, dc)));
const boost::shared_ptr<GeneralizedBlackScholesProcess> underlyingProcess(
new GeneralizedBlackScholesProcess(spot, qTS, sTS, vTS));
const Period monitorPeriod = Period(1, Weeks);
Schedule schedule(today, today + Period(maturity, Years),
monitorPeriod, TARGET(),
Following, Following,
DateGeneration::Forward, false);
std::vector<Time> times(schedule.size());
std::transform(schedule.begin(), schedule.end(), times.begin(),
boost::bind(&Actual365Fixed::yearFraction,
dc, today, _1, Date(), Date()));
TimeGrid grid(times.begin(), times.end());
std::vector<Real> redemption(times.size());
for (Size i=0; i < redemption.size(); ++i) {
redemption[i] = 1. + 0.16 * times[i];
}
typedef PseudoRandom::rsg_type rsg_type;
typedef MultiPathGenerator<rsg_type>::sample_type sample_type;
BigNatural seed = 42;
rsg_type rsg = PseudoRandom::make_sequence_generator(grid.size()-1, seed);
MultiPathGenerator<rsg_type> generator(underlyingProcess, grid, rsg, false);
GeneralStatistics stat;
Real antitheticPayoff=0;
const Size nrTrails = 3000;
for (Size i=0; i < nrTrails; ++i) {
const bool antithetic = (i%2)==0 ? false : true;
sample_type path = antithetic ? generator.antithetic()
: generator.next();
Real payoff=0;
for (Size j=1; j < times.size(); ++j) {
if (path.value[0][j] > upperBarrier * spot->value()) {
payoff = redemption[j] * rTS->discount(times[j]);
break;
}
else if (path.value[0][j] < lowerBarrier * spot->value())
{
payoff = path.value[0][j] * rTS->discount(times[j]);
break;
}
else if (j == times.size() - 1) {
payoff = redemption[j] * rTS->discount(times[j]);
}
}
if (antithetic){
stat.add(0.5*(antitheticPayoff + payoff));
}
else {
antitheticPayoff = payoff;
}
}
const Real calculated = stat.mean();
const Real error = stat.errorEstimate();
cout << "Calculated: " << calculated << "\nError esi.: " << error << endl;
return 0;
}<commit_msg>FIX: error placeholders prefix<commit_after>#include <iostream>
#include <ql/quantlib.hpp>
using namespace std;
using namespace QuantLib;
boost::shared_ptr<YieldTermStructure>
flatRate(const Date& today,
const boost::shared_ptr<Quote>& forward,
const DayCounter& dc) {
return boost::shared_ptr<YieldTermStructure>(
new FlatForward(today, Handle<Quote>(forward), dc));
}
int main() {
const Size maturity = 2;
DayCounter dc = Actual365Fixed();
const Date today = Date::todaysDate();
const Real upperBarrier = 1.02;
const Real lowerBarrier = 0.86;
Settings::instance().evaluationDate() = today;
Handle<Quote> spot(boost::shared_ptr<Quote>(new SimpleQuote(1.)));
boost::shared_ptr<SimpleQuote> qRate(new SimpleQuote(0.0));
Handle<YieldTermStructure> qTS(flatRate(today, qRate, dc));
boost::shared_ptr<SimpleQuote> rRate(new SimpleQuote(0.05));
Handle<YieldTermStructure> rTS(flatRate(today, rRate, dc));
boost::shared_ptr<SimpleQuote> sRate(new SimpleQuote(0.0));
Handle<YieldTermStructure> sTS(flatRate(today, sRate, dc));
Handle<BlackVolTermStructure> vTS(boost::shared_ptr<BlackVolTermStructure>(new BlackConstantVol(today, NullCalendar(), 0.15, dc)));
const boost::shared_ptr<GeneralizedBlackScholesProcess> underlyingProcess(
new GeneralizedBlackScholesProcess(spot, qTS, sTS, vTS));
const Period monitorPeriod = Period(1, Weeks);
Schedule schedule(today, today + Period(maturity, Years),
monitorPeriod, TARGET(),
Following, Following,
DateGeneration::Forward, false);
std::vector<Time> times(schedule.size());
std::transform(schedule.begin(), schedule.end(), times.begin(),
boost::bind(&Actual365Fixed::yearFraction,
dc, today, boost::placeholders::_1, Date(), Date()));
TimeGrid grid(times.begin(), times.end());
std::vector<Real> redemption(times.size());
for (Size i=0; i < redemption.size(); ++i) {
redemption[i] = 1. + 0.16 * times[i];
}
typedef PseudoRandom::rsg_type rsg_type;
typedef MultiPathGenerator<rsg_type>::sample_type sample_type;
BigNatural seed = 42;
rsg_type rsg = PseudoRandom::make_sequence_generator(grid.size()-1, seed);
MultiPathGenerator<rsg_type> generator(underlyingProcess, grid, rsg, false);
GeneralStatistics stat;
Real antitheticPayoff=0;
const Size nrTrails = 3000;
for (Size i=0; i < nrTrails; ++i) {
const bool antithetic = (i%2)==0 ? false : true;
sample_type path = antithetic ? generator.antithetic()
: generator.next();
Real payoff=0;
for (Size j=1; j < times.size(); ++j) {
if (path.value[0][j] > upperBarrier * spot->value()) {
payoff = redemption[j] * rTS->discount(times[j]);
break;
}
else if (path.value[0][j] < lowerBarrier * spot->value())
{
payoff = path.value[0][j] * rTS->discount(times[j]);
break;
}
else if (j == times.size() - 1) {
payoff = redemption[j] * rTS->discount(times[j]);
}
}
if (antithetic){
stat.add(0.5*(antitheticPayoff + payoff));
}
else {
antitheticPayoff = payoff;
}
}
const Real calculated = stat.mean();
const Real error = stat.errorEstimate();
cout << "Calculated: " << calculated << "\nError esi.: " << error << endl;
return 0;
}<|endoftext|> |
<commit_before>
#include "AudioEffectFreqShift_FD_F32.h"
void AudioEffectFreqShift_FD_F32::update(void)
{
//get a pointer to the latest data
audio_block_f32_t *in_audio_block = AudioStream_F32::receiveReadOnly_f32();
if (!in_audio_block) return;
//simply return the audio if this class hasn't been enabled
if (!enabled) {
AudioStream_F32::transmit(in_audio_block);
AudioStream_F32::release(in_audio_block);
return;
}
//convert to frequency domain
myFFT.execute(in_audio_block, complex_2N_buffer); //FFT is in complex_2N_buffer, interleaved real, imaginary, real, imaginary, etc
unsigned long incoming_id = in_audio_block->id;
AudioStream_F32::release(in_audio_block); //We just passed ownership of in_audio_block to myFFT, so we can release it here as we won't use it here again.
// ////////////// Do your processing here!!!
//define some variables
int fftSize = myFFT.getNFFT();
int N_2 = fftSize / 2 + 1;
int source_ind; // neg_dest_ind;
//zero out DC and Nyquist
//complex_2N_buffer[0] = 0.0; complex_2N_buffer[1] = 0.0;
//complex_2N_buffer[N_2] = 0.0; complex_2N_buffer[N_2] = 0.0;
//do the shifting
if (shift_bins < 0) {
for (int dest_ind=0; dest_ind < N_2; dest_ind++) {
source_ind = dest_ind - shift_bins;
if (source_ind < N_2) {
complex_2N_buffer[2 * dest_ind] = complex_2N_buffer[2 * source_ind]; //real
complex_2N_buffer[(2 * dest_ind) + 1] = complex_2N_buffer[(2 * source_ind) + 1]; //imaginary
} else {
complex_2N_buffer[2 * dest_ind] = 0.0;
complex_2N_buffer[(2 * dest_ind) + 1] = 0.0;
}
}
} else if (shift_bins > 0) {
//do reverse order because, otherwise, we'd overwrite our source indices with zeros!
for (int dest_ind=N_2-1; dest_ind >= 0; dest_ind--) {
source_ind = dest_ind - shift_bins;
if (source_ind >= 0) {
complex_2N_buffer[2 * dest_ind] = complex_2N_buffer[2 * source_ind]; //real
complex_2N_buffer[(2 * dest_ind) + 1] = complex_2N_buffer[(2 * source_ind) +1]; //imaginary
} else {
complex_2N_buffer[2 * dest_ind] = 0.0;
complex_2N_buffer[(2 * dest_ind) + 1] = 0.0;
}
}
}
//here's the tricky bit! If the phase shift is an odd number of bins, we must manually evolve the phase through time
if ((abs(shift_bins) % 2) == 1) {
switch (overlap_amount) {
case NONE:
//no phase change needed
break;
case HALF:
//alternate adding 180 deg...which is flipping the sign
overlap_block_counter++;
if (overlap_block_counter == 2){
overlap_block_counter = 0;
for (int i=0; i < N_2; i++) {
complex_2N_buffer[2*i] = -complex_2N_buffer[2*i];
complex_2N_buffer[2*i+1] = -complex_2N_buffer[2*i+1];
}
}
break;
case THREE_QUARTERS:
overlap_block_counter++; //will be 1 to 4
float foo;
switch (overlap_block_counter) {
case 1:
//no rotation
break;
case 2:
//90 deg
for (int i=0; i < N_2; i++) {
foo = complex_2N_buffer[2*i+1];
complex_2N_buffer[2*i+1] = complex_2N_buffer[2*i];
complex_2N_buffer[2*i] = -foo;
}
break;
case 3:
//180 deg
for (int i=0; i < N_2; i++) {
complex_2N_buffer[2*i] = -complex_2N_buffer[2*i];
complex_2N_buffer[2*i+1] = -complex_2N_buffer[2*i+1];
}
break;
case 4:
//270 deg
for (int i=0; i < N_2; i++) {
foo = complex_2N_buffer[2*i+1];
complex_2N_buffer[2*i+1] = -complex_2N_buffer[2*i];
complex_2N_buffer[2*i] = foo;
}
overlap_block_counter = 0;
break;
}
}
}
//zero out the new DC and new nyquist
//complex_2N_buffer[0] = 0.0; complex_2N_buffer[1] = 0.0;
//complex_2N_buffer[N_2] = 0.0; complex_2N_buffer[N_2] = 0.0;
//rebuild the negative frequency space
myFFT.rebuildNegativeFrequencySpace(complex_2N_buffer); //set the negative frequency space based on the positive
// ///////////// End do your processing here
//call the IFFT
audio_block_f32_t *out_audio_block = myIFFT.execute(complex_2N_buffer); //out_block is pre-allocated in here.
//update the block number to match the incoming one
out_audio_block->id = incoming_id;
//send the returned audio block. Don't issue the release command here because myIFFT will re-use it
AudioStream_F32::transmit(out_audio_block); //don't release this buffer because myIFFT re-uses it within its own code
return;
};<commit_msg>FreqShift: beginning to fix the 75% overlap case?<commit_after>
#include "AudioEffectFreqShift_FD_F32.h"
void AudioEffectFreqShift_FD_F32::update(void)
{
//get a pointer to the latest data
audio_block_f32_t *in_audio_block = AudioStream_F32::receiveReadOnly_f32();
if (!in_audio_block) return;
//simply return the audio if this class hasn't been enabled
if (!enabled) {
AudioStream_F32::transmit(in_audio_block);
AudioStream_F32::release(in_audio_block);
return;
}
//convert to frequency domain
myFFT.execute(in_audio_block, complex_2N_buffer); //FFT is in complex_2N_buffer, interleaved real, imaginary, real, imaginary, etc
unsigned long incoming_id = in_audio_block->id;
AudioStream_F32::release(in_audio_block); //We just passed ownership of in_audio_block to myFFT, so we can release it here as we won't use it here again.
// ////////////// Do your processing here!!!
//define some variables
int fftSize = myFFT.getNFFT();
int N_2 = fftSize / 2 + 1;
int source_ind; // neg_dest_ind;
//zero out DC and Nyquist
//complex_2N_buffer[0] = 0.0; complex_2N_buffer[1] = 0.0;
//complex_2N_buffer[N_2] = 0.0; complex_2N_buffer[N_2] = 0.0;
//do the shifting
if (shift_bins < 0) {
for (int dest_ind=0; dest_ind < N_2; dest_ind++) {
source_ind = dest_ind - shift_bins;
if (source_ind < N_2) {
complex_2N_buffer[2 * dest_ind] = complex_2N_buffer[2 * source_ind]; //real
complex_2N_buffer[(2 * dest_ind) + 1] = complex_2N_buffer[(2 * source_ind) + 1]; //imaginary
} else {
complex_2N_buffer[2 * dest_ind] = 0.0;
complex_2N_buffer[(2 * dest_ind) + 1] = 0.0;
}
}
} else if (shift_bins > 0) {
//do reverse order because, otherwise, we'd overwrite our source indices with zeros!
for (int dest_ind=N_2-1; dest_ind >= 0; dest_ind--) {
source_ind = dest_ind - shift_bins;
if (source_ind >= 0) {
complex_2N_buffer[2 * dest_ind] = complex_2N_buffer[2 * source_ind]; //real
complex_2N_buffer[(2 * dest_ind) + 1] = complex_2N_buffer[(2 * source_ind) +1]; //imaginary
} else {
complex_2N_buffer[2 * dest_ind] = 0.0;
complex_2N_buffer[(2 * dest_ind) + 1] = 0.0;
}
}
}
//here's the tricky bit! If the phase shift is an odd number of bins, we must manually evolve the phase through time
switch (overlap_amount) {
case NONE:
//no phase change needed
break;
case HALF:
//we only need to adjust the phase if we're shifting by an odd number of bins
if ((abs(shift_bins) % 2) == 1) {
//Alternate between adding no phase shift and adding 180 deg phase shift.
//Adding 180 is the same as flipping the sign of both the real and imaginary components
overlap_block_counter++;
if (overlap_block_counter == 2){
overlap_block_counter = 0;
for (int i=0; i < N_2; i++) {
complex_2N_buffer[2*i] = -complex_2N_buffer[2*i];
complex_2N_buffer[2*i+1] = -complex_2N_buffer[2*i+1];
}
}
}
break;
case THREE_QUARTERS:
//The cycle of phase shifting is every 4 blocks insead of every two blocks.
overlap_block_counter++; //will be 1 to 4
if (overlap_block_counter == 4) overlap_block_counter = 0;
if ((abs(shift_bins) % 2) == 1) { //THIS ISN'T RIGHT ?!?!? Needs to be fancier, "% 4" instead of "% 2" ???
float foo;
switch (overlap_block_counter) {
case 0:
//no rotation
break;
case 1:
//90 deg rotation (swap real and imaginary and flip the sign when moving the real to imaginary)
for (int i=0; i < N_2; i++) {
foo = complex_2N_buffer[2*i+1];
complex_2N_buffer[2*i+1] = complex_2N_buffer[2*i];
complex_2N_buffer[2*i] = -foo;
}
break;
case 2:
//180 deg...flip the sign of both real and imaginary
for (int i=0; i < N_2; i++) {
complex_2N_buffer[2*i] = -complex_2N_buffer[2*i];
complex_2N_buffer[2*i+1] = -complex_2N_buffer[2*i+1];
}
break;
case 3:
//270 deg rotation (swap the real and imaginary and flip the sign when moving the imaginary to the real)
for (int i=0; i < N_2; i++) {
foo = complex_2N_buffer[2*i+1];
complex_2N_buffer[2*i+1] = -complex_2N_buffer[2*i];
complex_2N_buffer[2*i] = foo;
}
overlap_block_counter = 0;
break;
}
}
}
}
//zero out the new DC and new nyquist
//complex_2N_buffer[0] = 0.0; complex_2N_buffer[1] = 0.0;
//complex_2N_buffer[N_2] = 0.0; complex_2N_buffer[N_2] = 0.0;
//rebuild the negative frequency space
myFFT.rebuildNegativeFrequencySpace(complex_2N_buffer); //set the negative frequency space based on the positive
// ///////////// End do your processing here
//call the IFFT
audio_block_f32_t *out_audio_block = myIFFT.execute(complex_2N_buffer); //out_block is pre-allocated in here.
//update the block number to match the incoming one
out_audio_block->id = incoming_id;
//send the returned audio block. Don't issue the release command here because myIFFT will re-use it
AudioStream_F32::transmit(out_audio_block); //don't release this buffer because myIFFT re-uses it within its own code
return;
};<|endoftext|> |
<commit_before>#include "HM_base.h"
namespace kai
{
HM_base::HM_base()
{
m_pCAN = NULL;
m_pCMD = NULL;
m_pGPS = NULL;
m_strCMD = "";
m_rpmL = 0;
m_rpmR = 0;
m_motorRpmW = 0;
m_bSpeaker = false;
m_bMute = false;
m_canAddrStation = 0x301;
m_maxRpmT = 65535;
m_maxRpmW = 2500;
m_ctrlB0 = 0;
m_ctrlB1 = 0;
m_defaultRpmT = 3000;
m_wheelR = 0.1;
m_treadW = 0.4;
m_pinLEDl = 11;
m_pinLEDm = 12;
m_pinLEDr = 13;
m_dT.init();
m_dRot.init();
}
HM_base::~HM_base()
{
}
bool HM_base::init(void* pKiss)
{
IF_F(!this->ActionBase::init(pKiss));
Kiss* pK = (Kiss*)pKiss;
pK->m_pInst = this;
F_INFO(pK->v("maxSpeedT", &m_maxRpmT));
F_INFO(pK->v("maxSpeedW", &m_maxRpmW));
F_INFO(pK->v("motorRpmW", &m_motorRpmW));
F_INFO(pK->v("defaultRpmT", &m_defaultRpmT));
F_INFO(pK->v("wheelR", &m_wheelR));
F_INFO(pK->v("treadW", &m_treadW));
F_INFO(pK->v("bMute", &m_bMute));
F_INFO(pK->v("canAddrStation", &m_canAddrStation));
F_INFO(pK->v("pinLEDl", (int*)&m_pinLEDl));
F_INFO(pK->v("pinLEDm", (int*)&m_pinLEDm));
F_INFO(pK->v("pinLEDr", (int*)&m_pinLEDr));
Kiss* pI = pK->o("cmd");
IF_T(pI->empty());
m_pCMD = new TCP();
F_ERROR_F(m_pCMD->init(pI));
return true;
}
bool HM_base::link(void)
{
IF_F(!this->ActionBase::link());
Kiss* pK = (Kiss*)m_pKiss;
string iName;
iName = "";
F_ERROR_F(pK->v("_Canbus", &iName));
m_pCAN = (_Canbus*) (pK->root()->getChildInstByName(&iName));
iName = "";
F_ERROR_F(pK->v("_GPS", &iName));
m_pGPS = (_GPS*) (pK->root()->getChildInstByName(&iName));
return true;
}
void HM_base::update(void)
{
this->ActionBase::update();
NULL_(m_pAM);
NULL_(m_pCMD);
updateGPS();
updateCAN();
string* pStateName = m_pAM->getCurrentStateName();
if(*pStateName == "HM_STANDBY" || *pStateName == "HM_STATION" || *pStateName=="HM_FOLLOWME")
{
m_rpmL = 0;
m_rpmR = 0;
}
else
{
m_rpmL = m_defaultRpmT;
m_rpmR = m_defaultRpmT;
}
m_motorRpmW = 0;
m_bSpeaker = false;
cmd();
}
void HM_base::updateGPS(void)
{
NULL_(m_pGPS);
const static double tBase = 1.0/(USEC_1SEC*60.0);
//force rpm to only rot or translation at a time
if(abs(m_rpmL) != abs(m_rpmR))
{
int mid = (m_rpmL + m_rpmR)/2;
int absRpm = abs(m_rpmL - mid);
if(m_rpmL > m_rpmR)
{
m_rpmL = absRpm;
m_rpmR = -absRpm;
}
else
{
m_rpmL = -absRpm;
m_rpmR = absRpm;
}
m_dT.m_z = 0.0;
m_dRot.m_x = 360.0 * (((double)m_rpmL) * tBase * m_wheelR * 2 * PI) / (m_treadW * PI);
}
else if(m_rpmL != m_rpmR)
{
m_dT.m_z = 0.0;
m_dRot.m_x = 360.0 * (((double)m_rpmL) * tBase * m_wheelR * 2 * PI) / (m_treadW * PI);
}
else
{
m_dT.m_z = ((double)m_rpmL) * tBase * m_wheelR * 2 * PI;
m_dRot.m_x = 0.0;
}
//TODO:Temporal
m_dT.m_z *= 1000000;
m_pGPS->setSpeed(&m_dT,&m_dRot);
LOG_I("dZ="<<m_dT.m_z<<" dYaw="<<m_dRot.m_x);
}
void HM_base::cmd(void)
{
if (!m_pCMD->isOpen())
{
m_pCMD->open();
return;
}
char buf;
while (m_pCMD->read((uint8_t*) &buf, 1) > 0)
{
if (buf == ',')break;
IF_CONT(buf==LF);
IF_CONT(buf==CR);
m_strCMD += buf;
}
IF_(buf!=',');
LOG_I("CMD: "<<m_strCMD);
string stateName;
if(m_strCMD=="start")
{
stateName = *m_pAM->getCurrentStateName();
if(stateName=="HM_STATION")
{
stateName = "HM_KICKBACK";
m_pAM->transit(&stateName);
}
else if(stateName=="HM_STANDBY")
{
m_pAM->transit(m_pAM->getLastStateIdx());
}
}
else if(m_strCMD=="stop")
{
stateName = "HM_STANDBY";
m_pAM->transit(&stateName);
}
else if(m_strCMD=="work")
{
stateName = "HM_WORK";
m_pAM->transit(&stateName);
}
else if(m_strCMD=="back_to_home")
{
stateName = "HM_RTH";
m_pAM->transit(&stateName);
}
else if(m_strCMD=="follow_me")
{
stateName = "HM_FOLLOWME";
m_pAM->transit(&stateName);
}
else if(m_strCMD=="station")
{
stateName = "HM_STATION";
m_pGPS->reset();
m_pAM->transit(&stateName);
}
m_strCMD = "";
}
void HM_base::updateCAN(void)
{
NULL_(m_pCAN);
//send
if(m_bMute)m_bSpeaker = false;
unsigned long addr = 0x113;
unsigned char cmd[8];
m_ctrlB0 = 0;
m_ctrlB0 |= (m_rpmR<0)?(1 << 4):0;
m_ctrlB0 |= (m_rpmL<0)?(1 << 5):0;
m_ctrlB0 |= (m_motorRpmW<0)?(1 << 6):0;
uint16_t motorPwmL = abs(constrain(m_rpmL, m_maxRpmT, -m_maxRpmT));
uint16_t motorPwmR = abs(constrain(m_rpmR, m_maxRpmT, -m_maxRpmT));
uint16_t motorPwmW = abs(constrain(m_motorRpmW, m_maxRpmW, -m_maxRpmW));
m_ctrlB1 = 0;
m_ctrlB1 |= 1; //tracktion motor relay
m_ctrlB1 |= (1 << 1); //working motor relay
m_ctrlB1 |= (m_bSpeaker)?(1 << 5):0;//speaker
m_ctrlB1 |= (1 << 6); //external command
m_ctrlB1 |= (1 << 7); //0:pwm, 1:rpm
uint16_t bFilter = 0x00ff;
cmd[0] = m_ctrlB0;
cmd[1] = m_ctrlB1;
cmd[2] = motorPwmL & bFilter;
cmd[3] = (motorPwmL>>8) & bFilter;
cmd[4] = motorPwmR & bFilter;
cmd[5] = (motorPwmR>>8) & bFilter;
cmd[6] = motorPwmW & bFilter;
cmd[7] = (motorPwmW>>8) & bFilter;
m_pCAN->send(addr, 8, cmd);
//status LED
string stateName = *m_pAM->getCurrentStateName();
if(stateName=="HM_WORK" || stateName=="HM_RTH")
{
m_pCAN->pinOut(m_pinLEDl,0);
m_pCAN->pinOut(m_pinLEDm,1);
m_pCAN->pinOut(m_pinLEDr,0);
}
else if(stateName=="HM_FOLLOWME")
{
m_pCAN->pinOut(m_pinLEDl,1);
m_pCAN->pinOut(m_pinLEDm,0);
m_pCAN->pinOut(m_pinLEDr,0);
}
else if(stateName=="HM_STANDBY")
{
m_pCAN->pinOut(m_pinLEDl,0);
m_pCAN->pinOut(m_pinLEDm,0);
m_pCAN->pinOut(m_pinLEDr,1);
}
else if(stateName=="HM_KICKBACK")
{
m_pCAN->pinOut(m_pinLEDl,1);
m_pCAN->pinOut(m_pinLEDm,1);
m_pCAN->pinOut(m_pinLEDr,1);
}
else
{
m_pCAN->pinOut(m_pinLEDl,0);
m_pCAN->pinOut(m_pinLEDm,0);
m_pCAN->pinOut(m_pinLEDr,0);
}
//receive
uint8_t* pCanData = m_pCAN->get(m_canAddrStation);
NULL_(pCanData);
//CAN-ID301h 1byte 4bit "AC-input"
//1:ON-Docking/0:OFF-area
IF_(!((pCanData[1] >> 4) & 1));
IF_(stateName == "HM_KICKBACK");
stateName = "HM_STATION";
m_pGPS->reset();
m_pAM->transit(&stateName);
}
bool HM_base::draw(void)
{
IF_F(!this->ActionBase::draw());
Window* pWin = (Window*) this->m_pWindow;
Mat* pMat = pWin->getFrame()->getCMat();
NULL_F(pMat);
IF_F(pMat->empty());
string msg = *this->getName() + ": rpmL=" + i2str(m_rpmL)
+ ", rpmR=" + i2str(m_rpmR);
pWin->addMsg(&msg);
return true;
}
}
<commit_msg>Fixed HM LR rpm<commit_after>#include "HM_base.h"
namespace kai
{
HM_base::HM_base()
{
m_pCAN = NULL;
m_pCMD = NULL;
m_pGPS = NULL;
m_strCMD = "";
m_rpmL = 0;
m_rpmR = 0;
m_motorRpmW = 0;
m_bSpeaker = false;
m_bMute = false;
m_canAddrStation = 0x301;
m_maxRpmT = 65535;
m_maxRpmW = 2500;
m_ctrlB0 = 0;
m_ctrlB1 = 0;
m_defaultRpmT = 3000;
m_wheelR = 0.1;
m_treadW = 0.4;
m_pinLEDl = 11;
m_pinLEDm = 12;
m_pinLEDr = 13;
m_dT.init();
m_dRot.init();
}
HM_base::~HM_base()
{
}
bool HM_base::init(void* pKiss)
{
IF_F(!this->ActionBase::init(pKiss));
Kiss* pK = (Kiss*)pKiss;
pK->m_pInst = this;
F_INFO(pK->v("maxSpeedT", &m_maxRpmT));
F_INFO(pK->v("maxSpeedW", &m_maxRpmW));
F_INFO(pK->v("motorRpmW", &m_motorRpmW));
F_INFO(pK->v("defaultRpmT", &m_defaultRpmT));
F_INFO(pK->v("wheelR", &m_wheelR));
F_INFO(pK->v("treadW", &m_treadW));
F_INFO(pK->v("bMute", &m_bMute));
F_INFO(pK->v("canAddrStation", &m_canAddrStation));
F_INFO(pK->v("pinLEDl", (int*)&m_pinLEDl));
F_INFO(pK->v("pinLEDm", (int*)&m_pinLEDm));
F_INFO(pK->v("pinLEDr", (int*)&m_pinLEDr));
Kiss* pI = pK->o("cmd");
IF_T(pI->empty());
m_pCMD = new TCP();
F_ERROR_F(m_pCMD->init(pI));
return true;
}
bool HM_base::link(void)
{
IF_F(!this->ActionBase::link());
Kiss* pK = (Kiss*)m_pKiss;
string iName;
iName = "";
F_ERROR_F(pK->v("_Canbus", &iName));
m_pCAN = (_Canbus*) (pK->root()->getChildInstByName(&iName));
iName = "";
F_ERROR_F(pK->v("_GPS", &iName));
m_pGPS = (_GPS*) (pK->root()->getChildInstByName(&iName));
return true;
}
void HM_base::update(void)
{
this->ActionBase::update();
NULL_(m_pAM);
NULL_(m_pCMD);
updateGPS();
updateCAN();
string* pStateName = m_pAM->getCurrentStateName();
if(*pStateName == "HM_STANDBY" || *pStateName == "HM_STATION" || *pStateName=="HM_FOLLOWME")
{
m_rpmL = 0;
m_rpmR = 0;
}
else
{
m_rpmL = m_defaultRpmT;
m_rpmR = m_defaultRpmT;
}
m_motorRpmW = 0;
m_bSpeaker = false;
cmd();
}
void HM_base::updateGPS(void)
{
NULL_(m_pGPS);
const static double tBase = 1.0/(USEC_1SEC*60.0);
//force rpm to only rot or translation at a time
if(abs(m_rpmL) != abs(m_rpmR))
{
int mid = (m_rpmL + m_rpmR)/2;
int absRpm = abs(m_rpmL - mid);
// if(m_rpmL > m_rpmR)
// {
// m_rpmL = absRpm;
// m_rpmR = -absRpm;
// }
// else
// {
// m_rpmL = -absRpm;
// m_rpmR = absRpm;
// }
m_dT.m_z = 0.0;
m_dRot.m_x = 360.0 * (((double)m_rpmL) * tBase * m_wheelR * 2 * PI) / (m_treadW * PI);
}
else if(m_rpmL != m_rpmR)
{
m_dT.m_z = 0.0;
m_dRot.m_x = 360.0 * (((double)m_rpmL) * tBase * m_wheelR * 2 * PI) / (m_treadW * PI);
}
else
{
m_dT.m_z = ((double)m_rpmL) * tBase * m_wheelR * 2 * PI;
m_dRot.m_x = 0.0;
}
//TODO:Temporal
m_dT.m_z *= 1000000;
m_pGPS->setSpeed(&m_dT,&m_dRot);
LOG_I("dZ="<<m_dT.m_z<<" dYaw="<<m_dRot.m_x);
}
void HM_base::cmd(void)
{
if (!m_pCMD->isOpen())
{
m_pCMD->open();
return;
}
char buf;
while (m_pCMD->read((uint8_t*) &buf, 1) > 0)
{
if (buf == ',')break;
IF_CONT(buf==LF);
IF_CONT(buf==CR);
m_strCMD += buf;
}
IF_(buf!=',');
LOG_I("CMD: "<<m_strCMD);
string stateName;
if(m_strCMD=="start")
{
stateName = *m_pAM->getCurrentStateName();
if(stateName=="HM_STATION")
{
stateName = "HM_KICKBACK";
m_pAM->transit(&stateName);
}
else if(stateName=="HM_STANDBY")
{
m_pAM->transit(m_pAM->getLastStateIdx());
}
}
else if(m_strCMD=="stop")
{
stateName = "HM_STANDBY";
m_pAM->transit(&stateName);
}
else if(m_strCMD=="work")
{
stateName = "HM_WORK";
m_pAM->transit(&stateName);
}
else if(m_strCMD=="back_to_home")
{
stateName = "HM_RTH";
m_pAM->transit(&stateName);
}
else if(m_strCMD=="follow_me")
{
stateName = "HM_FOLLOWME";
m_pAM->transit(&stateName);
}
else if(m_strCMD=="station")
{
stateName = "HM_STATION";
m_pGPS->reset();
m_pAM->transit(&stateName);
}
m_strCMD = "";
}
void HM_base::updateCAN(void)
{
NULL_(m_pCAN);
//send
if(m_bMute)m_bSpeaker = false;
unsigned long addr = 0x113;
unsigned char cmd[8];
m_ctrlB0 = 0;
m_ctrlB0 |= (m_rpmR<0)?(1 << 4):0;
m_ctrlB0 |= (m_rpmL<0)?(1 << 5):0;
m_ctrlB0 |= (m_motorRpmW<0)?(1 << 6):0;
uint16_t motorPwmL = abs(constrain(m_rpmL, m_maxRpmT, -m_maxRpmT));
uint16_t motorPwmR = abs(constrain(m_rpmR, m_maxRpmT, -m_maxRpmT));
uint16_t motorPwmW = abs(constrain(m_motorRpmW, m_maxRpmW, -m_maxRpmW));
m_ctrlB1 = 0;
m_ctrlB1 |= 1; //tracktion motor relay
m_ctrlB1 |= (1 << 1); //working motor relay
m_ctrlB1 |= (m_bSpeaker)?(1 << 5):0;//speaker
m_ctrlB1 |= (1 << 6); //external command
m_ctrlB1 |= (1 << 7); //0:pwm, 1:rpm
uint16_t bFilter = 0x00ff;
cmd[0] = m_ctrlB0;
cmd[1] = m_ctrlB1;
cmd[2] = motorPwmL & bFilter;
cmd[3] = (motorPwmL>>8) & bFilter;
cmd[4] = motorPwmR & bFilter;
cmd[5] = (motorPwmR>>8) & bFilter;
cmd[6] = motorPwmW & bFilter;
cmd[7] = (motorPwmW>>8) & bFilter;
m_pCAN->send(addr, 8, cmd);
//status LED
string stateName = *m_pAM->getCurrentStateName();
if(stateName=="HM_WORK" || stateName=="HM_RTH")
{
m_pCAN->pinOut(m_pinLEDl,0);
m_pCAN->pinOut(m_pinLEDm,1);
m_pCAN->pinOut(m_pinLEDr,0);
}
else if(stateName=="HM_FOLLOWME")
{
m_pCAN->pinOut(m_pinLEDl,1);
m_pCAN->pinOut(m_pinLEDm,0);
m_pCAN->pinOut(m_pinLEDr,0);
}
else if(stateName=="HM_STANDBY")
{
m_pCAN->pinOut(m_pinLEDl,0);
m_pCAN->pinOut(m_pinLEDm,0);
m_pCAN->pinOut(m_pinLEDr,1);
}
else if(stateName=="HM_KICKBACK")
{
m_pCAN->pinOut(m_pinLEDl,1);
m_pCAN->pinOut(m_pinLEDm,1);
m_pCAN->pinOut(m_pinLEDr,1);
}
else
{
m_pCAN->pinOut(m_pinLEDl,0);
m_pCAN->pinOut(m_pinLEDm,0);
m_pCAN->pinOut(m_pinLEDr,0);
}
//receive
uint8_t* pCanData = m_pCAN->get(m_canAddrStation);
NULL_(pCanData);
//CAN-ID301h 1byte 4bit "AC-input"
//1:ON-Docking/0:OFF-area
IF_(!((pCanData[1] >> 4) & 1));
IF_(stateName == "HM_KICKBACK");
stateName = "HM_STATION";
m_pGPS->reset();
m_pAM->transit(&stateName);
}
bool HM_base::draw(void)
{
IF_F(!this->ActionBase::draw());
Window* pWin = (Window*) this->m_pWindow;
Mat* pMat = pWin->getFrame()->getCMat();
NULL_F(pMat);
IF_F(pMat->empty());
string msg = *this->getName() + ": rpmL=" + i2str(m_rpmL)
+ ", rpmR=" + i2str(m_rpmR);
pWin->addMsg(&msg);
return true;
}
}
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_PROB_LOGLOGISTIC_LPDF_HPP
#define STAN_MATH_PRIM_PROB_LOGLOGISTIC_LPDF_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/as_column_vector_or_scalar.hpp>
#include <stan/math/prim/fun/as_array_or_scalar.hpp>
#include <stan/math/prim/fun/as_value_column_array_or_scalar.hpp>
#include <stan/math/prim/fun/exp.hpp>
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/prim/fun/max_size.hpp>
#include <stan/math/prim/fun/size.hpp>
#include <stan/math/prim/fun/size_zero.hpp>
#include <stan/math/prim/fun/to_ref.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <stan/math/prim/functor/operands_and_partials.hpp>
#include <cmath>
namespace stan {
namespace math {
/** \ingroup prob_dists
* The log of the loglogistic density for the specified scalar(s)
* given the specified scales(s) and shape(s). y, alpha, or beta
* can each be either a scalar or a vector. Any vector inputs
* must be the same length.
*
* <p>The result log probability is defined to be the sum of the
* log probabilities for each observation/scale/shape triple.
*
* @tparam T_y type of scalar.
* @tparam T_scale type of scale parameter.
* @tparam T_shape type of shape parameter.
* @param y (Sequence of) scalar(s).
* @param alpha (Sequence of) scale parameter(s)
* for the loglogistic distribution.
* @param beta (Sequence of) shape parameter(s) for the
* loglogistic distribution.
* @return The log of the product of the densities.
* @throw std::domain_error if any of the inputs are not positive and finite.
*/
template <bool propto, typename T_y, typename T_scale, typename T_shape,
require_all_not_nonscalar_prim_or_rev_kernel_expression_t<
T_y, T_scale, T_shape>* = nullptr>
return_type_t<T_y, T_scale, T_shape> loglogistic_lpdf(const T_y& y,
const T_scale& alpha,
const T_shape& beta) {
using T_partials_return = partials_return_t<T_y, T_scale, T_shape>;
using T_y_ref = ref_type_if_t<!is_constant<T_y>::value, T_y>;
using T_scale_ref = ref_type_if_t<!is_constant<T_scale>::value, T_scale>;
using T_shape_ref = ref_type_if_t<!is_constant<T_shape>::value, T_shape>;
using std::pow;
static const char* function = "loglogistic_lpdf";
check_consistent_sizes(function, "Random variable", y, "Scale parameter",
alpha, "Shape parameter", beta);
T_y_ref y_ref = y;
T_scale_ref alpha_ref = alpha;
T_shape_ref beta_ref = beta;
decltype(auto) y_val = to_ref(as_value_column_array_or_scalar(y_ref));
decltype(auto) alpha_val = to_ref(as_value_column_array_or_scalar(alpha_ref));
decltype(auto) beta_val = to_ref(as_value_column_array_or_scalar(beta_ref));
check_positive_finite(function, "Random variable", y_val);
check_positive_finite(function, "Scale parameter", alpha_val);
check_positive_finite(function, "Shape parameter", beta_val);
if (size_zero(y, alpha, beta)) {
return 0.0;
}
if (!include_summand<propto, T_y, T_scale, T_shape>::value) {
return 0.0;
}
operands_and_partials<T_y_ref, T_scale_ref, T_shape_ref> ops_partials(
y_ref, alpha_ref, beta_ref);
const auto& inv_alpha
= to_ref_if<!is_constant_all<T_y, T_scale>::value>(inv(alpha_val));
const auto& y_div_alpha = to_ref_if<!is_constant_all<T_shape>::value>(y_val * inv_alpha);
const auto& y_div_alpha_pow_beta
= to_ref_if<!is_constant_all<T_shape>::value>(pow(y_div_alpha, beta_val));
const auto& log1_arg
= to_ref_if<!is_constant_all<T_y, T_scale, T_shape>::value>(
1 + y_div_alpha_pow_beta);
const auto& log_y = to_ref_if<!is_constant_all<T_shape>::value>(log(y_val));
const auto& log_alpha
= to_ref_if<include_summand<propto, T_scale, T_shape>::value>(
log(alpha_val));
const auto& beta_minus_one
= to_ref_if<(include_summand<propto, T_scale, T_shape>::value
|| !is_constant_all<T_y>::value)>(beta_val - 1.0);
size_t N = max_size(y, alpha, beta);
size_t N_alpha_beta = max_size(alpha, beta);
T_partials_return logp = sum(beta_minus_one * log_y - 2.0 * log(log1_arg));
if (include_summand<propto, T_scale, T_shape>::value) {
logp += sum(N * (log(beta_val) - log_alpha - beta_minus_one * log_alpha)
/ N_alpha_beta);
}
if (!is_constant_all<T_y, T_scale, T_shape>::value) {
const auto& two_inv_log1_arg
= to_ref_if<!is_constant_all<T_y>::value
+ !is_constant_all<T_scale>::value
+ !is_constant_all<T_shape>::value
>= 2>(2.0 * inv(log1_arg));
const auto& y_pow_beta = to_ref_if<!is_constant_all<T_y, T_scale>::value>(
pow(y_val, beta_val));
const auto& inv_alpha_pow_beta
= to_ref_if<!is_constant_all<T_y, T_scale>::value>(
pow(inv_alpha, beta_val));
if (!is_constant_all<T_y>::value) {
const auto& inv_y = inv(y_val);
const auto& y_deriv = beta_minus_one * inv_y
- two_inv_log1_arg * (beta_val * inv_alpha_pow_beta)
* y_pow_beta * inv_y;
ops_partials.edge1_.partials_ = y_deriv;
}
if (!is_constant_all<T_scale>::value) {
const auto& alpha_deriv = -beta_val * inv_alpha
- two_inv_log1_arg * y_pow_beta * (-beta_val)
* inv_alpha_pow_beta * inv_alpha;
ops_partials.edge2_.partials_ = alpha_deriv;
}
if (!is_constant_all<T_shape>::value) {
const auto& beta_deriv
= (1.0 * inv(beta_val)) + log_y - log_alpha
- two_inv_log1_arg * y_div_alpha_pow_beta * log(y_div_alpha);
ops_partials.edge3_.partials_ = beta_deriv;
}
}
return ops_partials.build(logp);
}
template <typename T_y, typename T_scale, typename T_shape>
inline return_type_t<T_y, T_scale, T_shape> loglogistic_lpdf(
const T_y& y, const T_scale& alpha, const T_shape& beta) {
return loglogistic_lpdf<false>(y, alpha, beta);
}
} // namespace math
} // namespace stan
#endif
<commit_msg>Update stan/math/prim/prob/loglogistic_lpdf.hpp<commit_after>#ifndef STAN_MATH_PRIM_PROB_LOGLOGISTIC_LPDF_HPP
#define STAN_MATH_PRIM_PROB_LOGLOGISTIC_LPDF_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
#include <stan/math/prim/fun/as_column_vector_or_scalar.hpp>
#include <stan/math/prim/fun/as_array_or_scalar.hpp>
#include <stan/math/prim/fun/as_value_column_array_or_scalar.hpp>
#include <stan/math/prim/fun/exp.hpp>
#include <stan/math/prim/fun/log.hpp>
#include <stan/math/prim/fun/max_size.hpp>
#include <stan/math/prim/fun/size.hpp>
#include <stan/math/prim/fun/size_zero.hpp>
#include <stan/math/prim/fun/to_ref.hpp>
#include <stan/math/prim/fun/value_of.hpp>
#include <stan/math/prim/functor/operands_and_partials.hpp>
#include <cmath>
namespace stan {
namespace math {
/** \ingroup prob_dists
* The log of the loglogistic density for the specified scalar(s)
* given the specified scales(s) and shape(s). y, alpha, or beta
* can each be either a scalar or a vector. Any vector inputs
* must be the same length.
*
* <p>The result log probability is defined to be the sum of the
* log probabilities for each observation/scale/shape triple.
*
* @tparam T_y type of scalar.
* @tparam T_scale type of scale parameter.
* @tparam T_shape type of shape parameter.
* @param y (Sequence of) scalar(s).
* @param alpha (Sequence of) scale parameter(s)
* for the loglogistic distribution.
* @param beta (Sequence of) shape parameter(s) for the
* loglogistic distribution.
* @return The log of the product of the densities.
* @throw std::domain_error if any of the inputs are not positive and finite.
*/
template <bool propto, typename T_y, typename T_scale, typename T_shape,
require_all_not_nonscalar_prim_or_rev_kernel_expression_t<
T_y, T_scale, T_shape>* = nullptr>
return_type_t<T_y, T_scale, T_shape> loglogistic_lpdf(const T_y& y,
const T_scale& alpha,
const T_shape& beta) {
using T_partials_return = partials_return_t<T_y, T_scale, T_shape>;
using T_y_ref = ref_type_if_t<!is_constant<T_y>::value, T_y>;
using T_scale_ref = ref_type_if_t<!is_constant<T_scale>::value, T_scale>;
using T_shape_ref = ref_type_if_t<!is_constant<T_shape>::value, T_shape>;
using std::pow;
static const char* function = "loglogistic_lpdf";
check_consistent_sizes(function, "Random variable", y, "Scale parameter",
alpha, "Shape parameter", beta);
T_y_ref y_ref = y;
T_scale_ref alpha_ref = alpha;
T_shape_ref beta_ref = beta;
decltype(auto) y_val = to_ref(as_value_column_array_or_scalar(y_ref));
decltype(auto) alpha_val = to_ref(as_value_column_array_or_scalar(alpha_ref));
decltype(auto) beta_val = to_ref(as_value_column_array_or_scalar(beta_ref));
check_positive_finite(function, "Random variable", y_val);
check_positive_finite(function, "Scale parameter", alpha_val);
check_positive_finite(function, "Shape parameter", beta_val);
if (size_zero(y, alpha, beta)) {
return 0.0;
}
if (!include_summand<propto, T_y, T_scale, T_shape>::value) {
return 0.0;
}
operands_and_partials<T_y_ref, T_scale_ref, T_shape_ref> ops_partials(
y_ref, alpha_ref, beta_ref);
const auto& inv_alpha
= to_ref_if<!is_constant_all<T_y, T_scale>::value>(inv(alpha_val));
const auto& y_div_alpha = to_ref_if<!is_constant_all<T_shape>::value>(y_val * inv_alpha);
const auto& y_div_alpha_pow_beta
= to_ref_if<!is_constant_all<T_shape>::value>(pow(y_div_alpha, beta_val));
const auto& log1_arg
= to_ref_if<!is_constant_all<T_y, T_scale, T_shape>::value>(
1 + y_div_alpha_pow_beta);
const auto& log_y = to_ref_if<!is_constant_all<T_shape>::value>(log(y_val));
const auto& log_alpha
= to_ref_if<include_summand<propto, T_scale, T_shape>::value>(
log(alpha_val));
const auto& beta_minus_one
= to_ref_if<(include_summand<propto, T_scale, T_shape>::value
|| !is_constant_all<T_y>::value)>(beta_val - 1.0);
size_t N = max_size(y, alpha, beta);
size_t N_alpha_beta = max_size(alpha, beta);
T_partials_return logp = sum(beta_minus_one * log_y - 2.0 * log(log1_arg));
if (include_summand<propto, T_scale, T_shape>::value) {
logp += sum(N * (log(beta_val) - log_alpha - beta_minus_one * log_alpha)
/ N_alpha_beta);
}
if (!is_constant_all<T_y, T_scale, T_shape>::value) {
const auto& two_inv_log1_arg
= to_ref_if<!is_constant_all<T_y>::value
+ !is_constant_all<T_scale>::value
+ !is_constant_all<T_shape>::value
>= 2>(2.0 * inv(log1_arg));
if(!is_constant_all<T_y, T_scale>::value){
const auto& y_pow_beta = to_ref_if<!is_constant_all<T_y, T_scale>::value>(
pow(y_val, beta_val));
const auto& inv_alpha_pow_beta
= to_ref_if<!is_constant_all<T_y, T_scale>::value>(
pow(inv_alpha, beta_val));
if (!is_constant_all<T_y>::value) {
const auto& inv_y = inv(y_val);
const auto& y_deriv = beta_minus_one * inv_y
- two_inv_log1_arg * (beta_val * inv_alpha_pow_beta)
* y_pow_beta * inv_y;
ops_partials.edge1_.partials_ = y_deriv;
}
if (!is_constant_all<T_scale>::value) {
const auto& alpha_deriv = -beta_val * inv_alpha
- two_inv_log1_arg * y_pow_beta * (-beta_val)
* inv_alpha_pow_beta * inv_alpha;
ops_partials.edge2_.partials_ = alpha_deriv;
}
if (!is_constant_all<T_shape>::value) {
const auto& beta_deriv
= (1.0 * inv(beta_val)) + log_y - log_alpha
- two_inv_log1_arg * y_div_alpha_pow_beta * log(y_div_alpha);
ops_partials.edge3_.partials_ = beta_deriv;
}
}
return ops_partials.build(logp);
}
template <typename T_y, typename T_scale, typename T_shape>
inline return_type_t<T_y, T_scale, T_shape> loglogistic_lpdf(
const T_y& y, const T_scale& alpha, const T_shape& beta) {
return loglogistic_lpdf<false>(y, alpha, beta);
}
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before>#ifndef STAN_MATH_PRIM_SCAL_FUN_INC_BETA_DERIVATIVES_HPP
#define STAN_MATH_PRIM_SCAL_FUN_INC_BETA_DERIVATIVES_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/scal/fun/lgamma.hpp>
#include <boost/math/special_functions/beta.hpp>
#include <cmath>
namespace stan {
namespace math {
/**
* Returns the partial derivative of the regularized
* incomplete beta function, I_{z}(a, b) with respect to z.
*
* @tparam T scalar types of arguments
* @param a a
* @param b b
* @param z upper bound of the integral
* @return partial derivative of the incomplete beta with respect to z
*
* @pre a > 0
* @pre b > 0
* @pre 0 < z <= 1
*/
template <typename T>
T inc_beta_ddz(T a, T b, T z) {
using std::exp;
using std::log;
return exp((b - 1) * log(1 - z) + (a - 1) * log(z) + lgamma(a + b) - lgamma(a)
- lgamma(b));
}
template <>
inline double inc_beta_ddz(double a, double b, double z) {
using boost::math::ibeta_derivative;
return ibeta_derivative(a, b, z);
}
} // namespace math
} // namespace stan
#endif
<commit_msg>Make compile guards match filename.<commit_after>#ifndef STAN_MATH_PRIM_SCAL_FUN_INC_BETA_DDZ_HPP
#define STAN_MATH_PRIM_SCAL_FUN_INC_BETA_DDZ_HPP
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/scal/fun/lgamma.hpp>
#include <boost/math/special_functions/beta.hpp>
#include <cmath>
namespace stan {
namespace math {
/**
* Returns the partial derivative of the regularized
* incomplete beta function, I_{z}(a, b) with respect to z.
*
* @tparam T scalar types of arguments
* @param a a
* @param b b
* @param z upper bound of the integral
* @return partial derivative of the incomplete beta with respect to z
*
* @pre a > 0
* @pre b > 0
* @pre 0 < z <= 1
*/
template <typename T>
T inc_beta_ddz(T a, T b, T z) {
using std::exp;
using std::log;
return exp((b - 1) * log(1 - z) + (a - 1) * log(z) + lgamma(a + b) - lgamma(a)
- lgamma(b));
}
template <>
inline double inc_beta_ddz(double a, double b, double z) {
using boost::math::ibeta_derivative;
return ibeta_derivative(a, b, z);
}
} // namespace math
} // namespace stan
#endif
<|endoftext|> |
<commit_before><commit_msg>Fix and resubmit 42959<commit_after><|endoftext|> |
<commit_before><commit_msg>DevTools: Style drive by<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/network_profile_bubble.h"
#include <windows.h>
#include <wtsapi32.h>
// Make sure we link the wtsapi lib file in.
#pragma comment(lib, "wtsapi32.lib")
#include "base/bind.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/time.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_list_observer.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/browser_thread.h"
namespace {
// The duration of the silent period before we start nagging the user again.
const int kSilenceDurationDays = 100;
// The number of warnings to be shown on consequtive starts of Chrome before the
// silent period starts.
const int kMaxWarnings = 2;
// Implementation of chrome::BrowserListObserver used to wait for a browser
// window.
class BrowserListObserver : public chrome::BrowserListObserver {
private:
virtual ~BrowserListObserver();
// Overridden from chrome::BrowserListObserver:
virtual void OnBrowserAdded(Browser* browser) OVERRIDE;
virtual void OnBrowserRemoved(Browser* browser) OVERRIDE;
virtual void OnBrowserSetLastActive(Browser* browser) OVERRIDE;
};
BrowserListObserver::~BrowserListObserver() {
}
void BrowserListObserver::OnBrowserAdded(Browser* browser) {
}
void BrowserListObserver::OnBrowserRemoved(Browser* browser) {
}
void BrowserListObserver::OnBrowserSetLastActive(Browser* browser) {
NetworkProfileBubble::ShowNotification(browser);
// No need to observe anymore.
BrowserList::RemoveObserver(this);
delete this;
}
// The name of the UMA histogram collecting our stats.
const char kMetricNetworkedProfileCheck[] = "NetworkedProfile.Check";
} // namespace
// static
bool NetworkProfileBubble::notification_shown_ = false;
// static
bool NetworkProfileBubble::ShouldCheckNetworkProfile(Profile* profile) {
PrefService* prefs = profile->GetPrefs();
if (prefs->GetInteger(prefs::kNetworkProfileWarningsLeft))
return !notification_shown_;
int64 last_check = prefs->GetInt64(prefs::kNetworkProfileLastWarningTime);
base::TimeDelta time_since_last_check =
base::Time::Now() - base::Time::FromTimeT(last_check);
if (time_since_last_check.InDays() > kSilenceDurationDays) {
prefs->SetInteger(prefs::kNetworkProfileWarningsLeft, kMaxWarnings);
return !notification_shown_;
}
return false;
}
// static
void NetworkProfileBubble::CheckNetworkProfile(Profile* profile) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE));
// On Windows notify the users if their profiles are located on a network
// share as we don't officially support this setup yet.
// However we don't want to bother users on Cytrix setups as those have no
// real choice and their admins must be well aware of the risks associated.
// Also the command line flag --no-network-profile-warning can stop this
// warning from popping up. In this case we can skip the check to make the
// start faster.
// Collect a lot of stats along the way to see which cases do occur in the
// wild often enough.
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kNoNetworkProfileWarning)) {
RecordUmaEvent(METRIC_CHECK_SUPPRESSED);
return;
}
LPWSTR buffer = NULL;
DWORD buffer_length = 0;
// Checking for RDP is cheaper than checking for a network drive so do this
// one first.
if (!WTSQuerySessionInformation(WTS_CURRENT_SERVER, WTS_CURRENT_SESSION,
WTSClientProtocolType,
&buffer, &buffer_length)) {
RecordUmaEvent(METRIC_CHECK_FAILED);
return;
}
unsigned short* type = reinterpret_cast<unsigned short*>(buffer);
// Zero means local session and we should warn the users if they have
// their profile on a network share.
if (*type == 0) {
bool profile_on_network = false;
if (!profile->GetPath().empty()) {
FilePath temp_file;
// Try to create some non-empty temp file in the profile dir and use
// it to check if there is a reparse-point free path to it.
if (file_util::CreateTemporaryFileInDir(profile->GetPath(), &temp_file) &&
file_util::WriteFile(temp_file, ".", 1)) {
FilePath normalized_temp_file;
if (!file_util::NormalizeFilePath(temp_file, &normalized_temp_file))
profile_on_network = true;
} else {
RecordUmaEvent(METRIC_CHECK_IO_FAILED);
}
file_util::Delete(temp_file, false);
}
if (profile_on_network) {
RecordUmaEvent(METRIC_PROFILE_ON_NETWORK);
content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
base::Bind(&NotifyNetworkProfileDetected));
} else {
RecordUmaEvent(METRIC_PROFILE_NOT_ON_NETWORK);
}
} else {
RecordUmaEvent(METRIC_REMOTE_SESSION);
}
WTSFreeMemory(buffer);
}
// static
void NetworkProfileBubble::SetNotificationShown(bool shown) {
notification_shown_ = shown;
}
// static
void NetworkProfileBubble::RegisterPrefs(PrefService* prefs) {
prefs->RegisterIntegerPref(prefs::kNetworkProfileWarningsLeft,
kMaxWarnings,
PrefService::UNSYNCABLE_PREF);
prefs->RegisterInt64Pref(prefs::kNetworkProfileLastWarningTime,
0,
PrefService::UNSYNCABLE_PREF);
}
// static
void NetworkProfileBubble::RecordUmaEvent(MetricNetworkedProfileCheck event) {
UMA_HISTOGRAM_ENUMERATION(kMetricNetworkedProfileCheck,
event,
METRIC_NETWORKED_PROFILE_CHECK_SIZE);
}
// static
void NetworkProfileBubble::NotifyNetworkProfileDetected() {
if (BrowserList::GetLastActive())
ShowNotification(BrowserList::GetLastActive());
else
BrowserList::AddObserver(new BrowserListObserver());
}
<commit_msg>Remove GetLastActive from NetworkProfileBubble.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/network_profile_bubble.h"
#include <windows.h>
#include <wtsapi32.h>
// Make sure we link the wtsapi lib file in.
#pragma comment(lib, "wtsapi32.lib")
#include "base/bind.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/logging.h"
#include "base/metrics/histogram.h"
#include "base/time.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_list_observer.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/pref_names.h"
#include "content/public/browser/browser_thread.h"
namespace {
// The duration of the silent period before we start nagging the user again.
const int kSilenceDurationDays = 100;
// The number of warnings to be shown on consequtive starts of Chrome before the
// silent period starts.
const int kMaxWarnings = 2;
// Implementation of chrome::BrowserListObserver used to wait for a browser
// window.
class BrowserListObserver : public chrome::BrowserListObserver {
private:
virtual ~BrowserListObserver();
// Overridden from chrome::BrowserListObserver:
virtual void OnBrowserAdded(Browser* browser) OVERRIDE;
virtual void OnBrowserRemoved(Browser* browser) OVERRIDE;
virtual void OnBrowserSetLastActive(Browser* browser) OVERRIDE;
};
BrowserListObserver::~BrowserListObserver() {
}
void BrowserListObserver::OnBrowserAdded(Browser* browser) {
}
void BrowserListObserver::OnBrowserRemoved(Browser* browser) {
}
void BrowserListObserver::OnBrowserSetLastActive(Browser* browser) {
NetworkProfileBubble::ShowNotification(browser);
// No need to observe anymore.
BrowserList::RemoveObserver(this);
delete this;
}
// The name of the UMA histogram collecting our stats.
const char kMetricNetworkedProfileCheck[] = "NetworkedProfile.Check";
} // namespace
// static
bool NetworkProfileBubble::notification_shown_ = false;
// static
bool NetworkProfileBubble::ShouldCheckNetworkProfile(Profile* profile) {
PrefService* prefs = profile->GetPrefs();
if (prefs->GetInteger(prefs::kNetworkProfileWarningsLeft))
return !notification_shown_;
int64 last_check = prefs->GetInt64(prefs::kNetworkProfileLastWarningTime);
base::TimeDelta time_since_last_check =
base::Time::Now() - base::Time::FromTimeT(last_check);
if (time_since_last_check.InDays() > kSilenceDurationDays) {
prefs->SetInteger(prefs::kNetworkProfileWarningsLeft, kMaxWarnings);
return !notification_shown_;
}
return false;
}
// static
void NetworkProfileBubble::CheckNetworkProfile(Profile* profile) {
DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE));
// On Windows notify the users if their profiles are located on a network
// share as we don't officially support this setup yet.
// However we don't want to bother users on Cytrix setups as those have no
// real choice and their admins must be well aware of the risks associated.
// Also the command line flag --no-network-profile-warning can stop this
// warning from popping up. In this case we can skip the check to make the
// start faster.
// Collect a lot of stats along the way to see which cases do occur in the
// wild often enough.
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kNoNetworkProfileWarning)) {
RecordUmaEvent(METRIC_CHECK_SUPPRESSED);
return;
}
LPWSTR buffer = NULL;
DWORD buffer_length = 0;
// Checking for RDP is cheaper than checking for a network drive so do this
// one first.
if (!WTSQuerySessionInformation(WTS_CURRENT_SERVER, WTS_CURRENT_SESSION,
WTSClientProtocolType,
&buffer, &buffer_length)) {
RecordUmaEvent(METRIC_CHECK_FAILED);
return;
}
unsigned short* type = reinterpret_cast<unsigned short*>(buffer);
// Zero means local session and we should warn the users if they have
// their profile on a network share.
if (*type == 0) {
bool profile_on_network = false;
if (!profile->GetPath().empty()) {
FilePath temp_file;
// Try to create some non-empty temp file in the profile dir and use
// it to check if there is a reparse-point free path to it.
if (file_util::CreateTemporaryFileInDir(profile->GetPath(), &temp_file) &&
file_util::WriteFile(temp_file, ".", 1)) {
FilePath normalized_temp_file;
if (!file_util::NormalizeFilePath(temp_file, &normalized_temp_file))
profile_on_network = true;
} else {
RecordUmaEvent(METRIC_CHECK_IO_FAILED);
}
file_util::Delete(temp_file, false);
}
if (profile_on_network) {
RecordUmaEvent(METRIC_PROFILE_ON_NETWORK);
content::BrowserThread::PostTask(content::BrowserThread::UI, FROM_HERE,
base::Bind(&NotifyNetworkProfileDetected));
} else {
RecordUmaEvent(METRIC_PROFILE_NOT_ON_NETWORK);
}
} else {
RecordUmaEvent(METRIC_REMOTE_SESSION);
}
WTSFreeMemory(buffer);
}
// static
void NetworkProfileBubble::SetNotificationShown(bool shown) {
notification_shown_ = shown;
}
// static
void NetworkProfileBubble::RegisterPrefs(PrefService* prefs) {
prefs->RegisterIntegerPref(prefs::kNetworkProfileWarningsLeft,
kMaxWarnings,
PrefService::UNSYNCABLE_PREF);
prefs->RegisterInt64Pref(prefs::kNetworkProfileLastWarningTime,
0,
PrefService::UNSYNCABLE_PREF);
}
// static
void NetworkProfileBubble::RecordUmaEvent(MetricNetworkedProfileCheck event) {
UMA_HISTOGRAM_ENUMERATION(kMetricNetworkedProfileCheck,
event,
METRIC_NETWORKED_PROFILE_CHECK_SIZE);
}
// static
void NetworkProfileBubble::NotifyNetworkProfileDetected() {
// TODO(robertshield): Eventually, we will need to figure out the correct
// desktop type for this for platforms that can have
// multiple desktop types (win8/metro).
Browser* browser = browser::FindLastActiveWithHostDesktopType(
chrome::HOST_DESKTOP_TYPE_NATIVE);
if (browser)
ShowNotification(browser);
else
BrowserList::AddObserver(new BrowserListObserver());
}
<|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/service_process_util.h"
#include <signal.h>
#include <unistd.h>
#include "base/file_util.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/message_loop_proxy.h"
#include "base/message_pump_libevent.h"
#include "base/path_service.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/multi_process_lock.h"
namespace {
int g_signal_socket = -1;
// Gets the name of the lock file for service process.
FilePath GetServiceProcessLockFilePath() {
FilePath user_data_dir;
PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
chrome::VersionInfo version_info;
std::string lock_file_name = version_info.Version() + "Service Process Lock";
return user_data_dir.Append(lock_file_name);
}
// Attempts to take a lock named |name|. If |waiting| is true then this will
// make multiple attempts to acquire the lock.
// Caller is responsible for ownership of the MultiProcessLock.
MultiProcessLock* TakeNamedLock(const std::string& name, bool waiting) {
scoped_ptr<MultiProcessLock> lock(MultiProcessLock::Create(name));
if (lock == NULL) return NULL;
bool got_lock = false;
for (int i = 0; i < 10; ++i) {
if (lock->TryLock()) {
got_lock = true;
break;
}
if (!waiting) break;
base::PlatformThread::Sleep(100 * i);
}
if (!got_lock) {
lock.reset();
}
return lock.release();
}
MultiProcessLock* TakeServiceRunningLock(bool waiting) {
std::string lock_name =
GetServiceProcessScopedName("_service_running");
return TakeNamedLock(lock_name, waiting);
}
MultiProcessLock* TakeServiceInitializingLock(bool waiting) {
std::string lock_name =
GetServiceProcessScopedName("_service_initializing");
return TakeNamedLock(lock_name, waiting);
}
// Watches for |kShutDownMessage| to be written to the file descriptor it is
// watching. When it reads |kShutDownMessage|, it performs |shutdown_task_|.
// Used here to monitor the socket listening to g_signal_socket.
class ServiceProcessShutdownMonitor
: public base::MessagePumpLibevent::Watcher {
public:
enum {
kShutDownMessage = 0xdecea5e
};
explicit ServiceProcessShutdownMonitor(Task* shutdown_task)
: shutdown_task_(shutdown_task) {
}
virtual ~ServiceProcessShutdownMonitor();
virtual void OnFileCanReadWithoutBlocking(int fd);
virtual void OnFileCanWriteWithoutBlocking(int fd);
private:
scoped_ptr<Task> shutdown_task_;
};
ServiceProcessShutdownMonitor::~ServiceProcessShutdownMonitor() {
}
void ServiceProcessShutdownMonitor::OnFileCanReadWithoutBlocking(int fd) {
if (shutdown_task_.get()) {
int buffer;
int length = read(fd, &buffer, sizeof(buffer));
if ((length == sizeof(buffer)) && (buffer == kShutDownMessage)) {
shutdown_task_->Run();
shutdown_task_.reset();
} else if (length > 0) {
LOG(ERROR) << "Unexpected read: " << buffer;
} else if (length == 0) {
LOG(ERROR) << "Unexpected fd close";
} else if (length < 0) {
PLOG(ERROR) << "read";
}
}
}
void ServiceProcessShutdownMonitor::OnFileCanWriteWithoutBlocking(int fd) {
NOTIMPLEMENTED();
}
// "Forced" Shutdowns on POSIX are done via signals. The magic signal for
// a shutdown is SIGTERM. "write" is a signal safe function. PLOG(ERROR) is
// not, but we don't ever expect it to be called.
void SigTermHandler(int sig, siginfo_t* info, void* uap) {
// TODO(dmaclach): add security here to make sure that we are being shut
// down by an appropriate process.
int message = ServiceProcessShutdownMonitor::kShutDownMessage;
if (write(g_signal_socket, &message, sizeof(message)) < 0) {
PLOG(ERROR) << "write";
}
}
} // namespace
// See comment for SigTermHandler.
bool ForceServiceProcessShutdown(const std::string& version,
base::ProcessId process_id) {
if (kill(process_id, SIGTERM) < 0) {
PLOG(ERROR) << "kill";
return false;
}
return true;
}
bool CheckServiceProcessReady() {
scoped_ptr<MultiProcessLock> running_lock(TakeServiceRunningLock(false));
return running_lock.get() == NULL;
}
struct ServiceProcessState::StateData
: public base::RefCountedThreadSafe<ServiceProcessState::StateData> {
scoped_ptr<MultiProcessLock> initializing_lock_;
scoped_ptr<MultiProcessLock> running_lock_;
scoped_ptr<ServiceProcessShutdownMonitor> shut_down_monitor_;
base::MessagePumpLibevent::FileDescriptorWatcher watcher_;
int sockets_[2];
struct sigaction old_action_;
bool set_action_;
// WatchFileDescriptor needs to be set up by the thread that is going
// to be monitoring it.
void SignalReady() {
CHECK(MessageLoopForIO::current()->WatchFileDescriptor(
sockets_[0], true, MessageLoopForIO::WATCH_READ,
&watcher_, shut_down_monitor_.get()));
g_signal_socket = sockets_[1];
// Set up signal handler for SIGTERM.
struct sigaction action;
action.sa_sigaction = SigTermHandler;
sigemptyset(&action.sa_mask);
action.sa_flags = SA_SIGINFO;
if (sigaction(SIGTERM, &action, &old_action_) == 0) {
// If the old_action is not default, somebody else has installed a
// a competing handler. Our handler is going to override it so it
// won't be called. If this occurs it needs to be fixed.
DCHECK_EQ(old_action_.sa_handler, SIG_DFL);
set_action_ = true;
initializing_lock_.reset();
} else {
PLOG(ERROR) << "sigaction";
}
}
};
bool ServiceProcessState::TakeSingletonLock() {
CHECK(!state_);
state_ = new StateData;
state_->AddRef();
state_->sockets_[0] = -1;
state_->sockets_[1] = -1;
state_->set_action_ = false;
state_->initializing_lock_.reset(TakeServiceInitializingLock(true));
return state_->initializing_lock_.get();
}
bool ServiceProcessState::SignalReady(
base::MessageLoopProxy* message_loop_proxy, Task* shutdown_task) {
CHECK(state_);
CHECK_EQ(g_signal_socket, -1);
state_->running_lock_.reset(TakeServiceRunningLock(true));
if (state_->running_lock_.get() == NULL) {
return false;
}
state_->shut_down_monitor_.reset(
new ServiceProcessShutdownMonitor(shutdown_task));
if (pipe(state_->sockets_) < 0) {
PLOG(ERROR) << "pipe";
return false;
}
message_loop_proxy->PostTask(FROM_HERE,
NewRunnableMethod(state_, &ServiceProcessState::StateData::SignalReady));
return true;
}
bool ServiceProcessState::AddToAutoRun() {
NOTIMPLEMENTED();
return false;
}
bool ServiceProcessState::RemoveFromAutoRun() {
NOTIMPLEMENTED();
return false;
}
void ServiceProcessState::TearDownState() {
g_signal_socket = -1;
if (state_) {
if (state_->sockets_[0] != -1) {
close(state_->sockets_[0]);
}
if (state_->sockets_[1] != -1) {
close(state_->sockets_[1]);
}
if (state_->set_action_) {
if (sigaction(SIGTERM, &state_->old_action_, NULL) < 0) {
PLOG(ERROR) << "sigaction";
}
}
state_->Release();
state_ = NULL;
}
}
<commit_msg>Fix the Xcode 3.1 gcc 4.2 compiler warning:<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/service_process_util.h"
#include <signal.h>
#include <unistd.h>
#include "base/file_util.h"
#include "base/logging.h"
#include "base/message_loop.h"
#include "base/message_loop_proxy.h"
#include "base/message_pump_libevent.h"
#include "base/path_service.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_version_info.h"
#include "chrome/common/multi_process_lock.h"
namespace {
int g_signal_socket = -1;
// Gets the name of the lock file for service process.
FilePath GetServiceProcessLockFilePath() {
FilePath user_data_dir;
PathService::Get(chrome::DIR_USER_DATA, &user_data_dir);
chrome::VersionInfo version_info;
std::string lock_file_name = version_info.Version() + "Service Process Lock";
return user_data_dir.Append(lock_file_name);
}
// Attempts to take a lock named |name|. If |waiting| is true then this will
// make multiple attempts to acquire the lock.
// Caller is responsible for ownership of the MultiProcessLock.
MultiProcessLock* TakeNamedLock(const std::string& name, bool waiting) {
scoped_ptr<MultiProcessLock> lock(MultiProcessLock::Create(name));
if (lock == NULL) return NULL;
bool got_lock = false;
for (int i = 0; i < 10; ++i) {
if (lock->TryLock()) {
got_lock = true;
break;
}
if (!waiting) break;
base::PlatformThread::Sleep(100 * i);
}
if (!got_lock) {
lock.reset();
}
return lock.release();
}
MultiProcessLock* TakeServiceRunningLock(bool waiting) {
std::string lock_name =
GetServiceProcessScopedName("_service_running");
return TakeNamedLock(lock_name, waiting);
}
MultiProcessLock* TakeServiceInitializingLock(bool waiting) {
std::string lock_name =
GetServiceProcessScopedName("_service_initializing");
return TakeNamedLock(lock_name, waiting);
}
} // namespace
// Watches for |kShutDownMessage| to be written to the file descriptor it is
// watching. When it reads |kShutDownMessage|, it performs |shutdown_task_|.
// Used here to monitor the socket listening to g_signal_socket.
class ServiceProcessShutdownMonitor
: public base::MessagePumpLibevent::Watcher {
public:
enum {
kShutDownMessage = 0xdecea5e
};
explicit ServiceProcessShutdownMonitor(Task* shutdown_task)
: shutdown_task_(shutdown_task) {
}
virtual ~ServiceProcessShutdownMonitor();
virtual void OnFileCanReadWithoutBlocking(int fd);
virtual void OnFileCanWriteWithoutBlocking(int fd);
private:
scoped_ptr<Task> shutdown_task_;
};
ServiceProcessShutdownMonitor::~ServiceProcessShutdownMonitor() {
}
void ServiceProcessShutdownMonitor::OnFileCanReadWithoutBlocking(int fd) {
if (shutdown_task_.get()) {
int buffer;
int length = read(fd, &buffer, sizeof(buffer));
if ((length == sizeof(buffer)) && (buffer == kShutDownMessage)) {
shutdown_task_->Run();
shutdown_task_.reset();
} else if (length > 0) {
LOG(ERROR) << "Unexpected read: " << buffer;
} else if (length == 0) {
LOG(ERROR) << "Unexpected fd close";
} else if (length < 0) {
PLOG(ERROR) << "read";
}
}
}
void ServiceProcessShutdownMonitor::OnFileCanWriteWithoutBlocking(int fd) {
NOTIMPLEMENTED();
}
// "Forced" Shutdowns on POSIX are done via signals. The magic signal for
// a shutdown is SIGTERM. "write" is a signal safe function. PLOG(ERROR) is
// not, but we don't ever expect it to be called.
static void SigTermHandler(int sig, siginfo_t* info, void* uap) {
// TODO(dmaclach): add security here to make sure that we are being shut
// down by an appropriate process.
int message = ServiceProcessShutdownMonitor::kShutDownMessage;
if (write(g_signal_socket, &message, sizeof(message)) < 0) {
PLOG(ERROR) << "write";
}
}
// See comment for SigTermHandler.
bool ForceServiceProcessShutdown(const std::string& version,
base::ProcessId process_id) {
if (kill(process_id, SIGTERM) < 0) {
PLOG(ERROR) << "kill";
return false;
}
return true;
}
bool CheckServiceProcessReady() {
scoped_ptr<MultiProcessLock> running_lock(TakeServiceRunningLock(false));
return running_lock.get() == NULL;
}
struct ServiceProcessState::StateData
: public base::RefCountedThreadSafe<ServiceProcessState::StateData> {
scoped_ptr<MultiProcessLock> initializing_lock_;
scoped_ptr<MultiProcessLock> running_lock_;
scoped_ptr<ServiceProcessShutdownMonitor> shut_down_monitor_;
base::MessagePumpLibevent::FileDescriptorWatcher watcher_;
int sockets_[2];
struct sigaction old_action_;
bool set_action_;
// WatchFileDescriptor needs to be set up by the thread that is going
// to be monitoring it.
void SignalReady() {
CHECK(MessageLoopForIO::current()->WatchFileDescriptor(
sockets_[0], true, MessageLoopForIO::WATCH_READ,
&watcher_, shut_down_monitor_.get()));
g_signal_socket = sockets_[1];
// Set up signal handler for SIGTERM.
struct sigaction action;
action.sa_sigaction = SigTermHandler;
sigemptyset(&action.sa_mask);
action.sa_flags = SA_SIGINFO;
if (sigaction(SIGTERM, &action, &old_action_) == 0) {
// If the old_action is not default, somebody else has installed a
// a competing handler. Our handler is going to override it so it
// won't be called. If this occurs it needs to be fixed.
DCHECK_EQ(old_action_.sa_handler, SIG_DFL);
set_action_ = true;
initializing_lock_.reset();
} else {
PLOG(ERROR) << "sigaction";
}
}
};
bool ServiceProcessState::TakeSingletonLock() {
CHECK(!state_);
state_ = new StateData;
state_->AddRef();
state_->sockets_[0] = -1;
state_->sockets_[1] = -1;
state_->set_action_ = false;
state_->initializing_lock_.reset(TakeServiceInitializingLock(true));
return state_->initializing_lock_.get();
}
bool ServiceProcessState::SignalReady(
base::MessageLoopProxy* message_loop_proxy, Task* shutdown_task) {
CHECK(state_);
CHECK_EQ(g_signal_socket, -1);
state_->running_lock_.reset(TakeServiceRunningLock(true));
if (state_->running_lock_.get() == NULL) {
return false;
}
state_->shut_down_monitor_.reset(
new ServiceProcessShutdownMonitor(shutdown_task));
if (pipe(state_->sockets_) < 0) {
PLOG(ERROR) << "pipe";
return false;
}
message_loop_proxy->PostTask(FROM_HERE,
NewRunnableMethod(state_, &ServiceProcessState::StateData::SignalReady));
return true;
}
bool ServiceProcessState::AddToAutoRun() {
NOTIMPLEMENTED();
return false;
}
bool ServiceProcessState::RemoveFromAutoRun() {
NOTIMPLEMENTED();
return false;
}
void ServiceProcessState::TearDownState() {
g_signal_socket = -1;
if (state_) {
if (state_->sockets_[0] != -1) {
close(state_->sockets_[0]);
}
if (state_->sockets_[1] != -1) {
close(state_->sockets_[1]);
}
if (state_->set_action_) {
if (sigaction(SIGTERM, &state_->old_action_, NULL) < 0) {
PLOG(ERROR) << "sigaction";
}
}
state_->Release();
state_ = NULL;
}
}
<|endoftext|> |
<commit_before><commit_msg>Try to force plugins to use software rendering until we can support hardware acceleration on the Mac. BUG=25406, 25092 TEST=Flash should no longer crash immediately after loading on sites with complex Flash applications.<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "chrome/browser/net/url_fixer_upper.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/chrome_process_util.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
#ifndef NDEBUG
#define TEST_ITERATIONS "2"
#else
#define TEST_ITERATIONS "10"
#endif
// URL at which data files may be found for HTTP tests. The document root of
// this URL's server should point to data/page_cycler/.
static const char kBaseUrl[] = "http://localhost:8000/";
namespace {
class PageCyclerTest : public UITest {
public:
PageCyclerTest() {
show_window_ = true;
// Expose garbage collection for the page cycler tests.
launch_arguments_.AppendSwitchWithValue(switches::kJavaScriptFlags,
L"--expose_gc");
}
// For HTTP tests, the name must be safe for use in a URL without escaping.
void RunPageCycler(const char* name, std::wstring* pages,
std::string* timings, bool use_http) {
GURL test_url;
if (use_http) {
test_url = GURL(std::string(kBaseUrl) + name + "/start.html");
} else {
FilePath test_path;
PathService::Get(base::DIR_EXE, &test_path);
test_path = test_path.DirName();
test_path = test_path.DirName();
test_path = test_path.Append(FILE_PATH_LITERAL("data"));
test_path = test_path.Append(FILE_PATH_LITERAL("page_cycler"));
test_path = test_path.AppendASCII(name);
test_path = test_path.Append(FILE_PATH_LITERAL("start.html"));
test_url = net::FilePathToFileURL(test_path);
}
// run N iterations
GURL::Replacements replacements;
const char query_string[] = "iterations=" TEST_ITERATIONS "&auto=1";
replacements.SetQuery(
query_string,
url_parse::Component(0, arraysize(query_string) - 1));
test_url = test_url.ReplaceComponents(replacements);
scoped_ptr<TabProxy> tab(GetActiveTab());
tab->NavigateToURL(test_url);
// Wait for the test to finish.
ASSERT_TRUE(WaitUntilCookieValue(tab.get(), test_url, "__pc_done",
3000, UITest::test_timeout_ms(), "1"));
std::string cookie;
ASSERT_TRUE(tab->GetCookieByName(test_url, "__pc_pages", &cookie));
pages->assign(UTF8ToWide(cookie));
ASSERT_FALSE(pages->empty());
ASSERT_TRUE(tab->GetCookieByName(test_url, "__pc_timings", &cookie));
timings->assign(cookie);
ASSERT_FALSE(timings->empty());
}
void PrintIOPerfInfo(const char* test_name) {
FilePath data_dir;
PathService::Get(chrome::DIR_USER_DATA, &data_dir);
int browser_process_pid = ChromeBrowserProcessId(data_dir);
ChromeProcessList chrome_processes(GetRunningChromeProcesses(data_dir));
ChromeProcessList::const_iterator it;
for (it = chrome_processes.begin(); it != chrome_processes.end(); ++it) {
base::ProcessHandle process_handle;
if (!base::OpenProcessHandle(*it, &process_handle)) {
NOTREACHED();
}
scoped_ptr<base::ProcessMetrics> process_metrics;
process_metrics.reset(
base::ProcessMetrics::CreateProcessMetrics(process_handle));
IoCounters io_counters;
memset(&io_counters, 0, sizeof(io_counters));
if (process_metrics.get()->GetIOCounters(&io_counters)) {
// Print out IO performance. We assume that the values can be
// converted to size_t (they're reported as ULONGLONG, 64-bit numbers).
std::string chrome_name = (*it == browser_process_pid) ? "_b" : "_r";
PrintResult("read_op", chrome_name,
"r_op" + chrome_name + test_name,
static_cast<size_t>(io_counters.ReadOperationCount), "",
false /* not important */);
PrintResult("write_op", chrome_name,
"w_op" + chrome_name + test_name,
static_cast<size_t>(io_counters.WriteOperationCount), "",
false /* not important */);
PrintResult("other_op", chrome_name,
"o_op" + chrome_name + test_name,
static_cast<size_t>(io_counters.OtherOperationCount), "",
false /* not important */);
size_t total = static_cast<size_t>(io_counters.ReadOperationCount +
io_counters.WriteOperationCount +
io_counters.OtherOperationCount);
PrintResult("total_op", chrome_name,
"IO_op" + chrome_name + test_name,
total, "", true /* important */);
PrintResult("read_byte", chrome_name,
"r_b" + chrome_name + test_name,
static_cast<size_t>(io_counters.ReadTransferCount / 1024),
"kb", false /* not important */);
PrintResult("write_byte", chrome_name,
"w_b" + chrome_name + test_name,
static_cast<size_t>(io_counters.WriteTransferCount / 1024),
"kb", false /* not important */);
PrintResult("other_byte", chrome_name,
"o_b" + chrome_name + test_name,
static_cast<size_t>(io_counters.OtherTransferCount / 1024),
"kb", false /* not important */);
total = static_cast<size_t>((io_counters.ReadTransferCount +
io_counters.WriteTransferCount +
io_counters.OtherTransferCount) / 1024);
PrintResult("total_byte", chrome_name,
"IO_b" + chrome_name + test_name,
total, "kb", true /* important */);
}
base::CloseProcessHandle(process_handle);
}
}
void PrintMemoryUsageInfo(const char* test_name) {
FilePath data_dir;
PathService::Get(chrome::DIR_USER_DATA, &data_dir);
int browser_process_pid = ChromeBrowserProcessId(data_dir);
ChromeProcessList chrome_processes(GetRunningChromeProcesses(data_dir));
ChromeProcessList::const_iterator it;
for (it = chrome_processes.begin(); it != chrome_processes.end(); ++it) {
base::ProcessHandle process_handle;
if (!base::OpenProcessHandle(*it, &process_handle)) {
NOTREACHED();
}
scoped_ptr<base::ProcessMetrics> process_metrics;
process_metrics.reset(
base::ProcessMetrics::CreateProcessMetrics(process_handle));
std::string chrome_name = (*it == browser_process_pid) ? "_b" : "_r";
std::string trace_name(test_name);
#if defined(OS_WIN)
PrintResult("vm_peak", chrome_name,
"vm_pk" + chrome_name + trace_name,
process_metrics->GetPeakPagefileUsage(), "bytes",
true /* important */);
PrintResult("vm_final", chrome_name,
"vm_f" + chrome_name + trace_name,
process_metrics->GetPagefileUsage(), "bytes",
false /* not important */);
PrintResult("ws_peak", chrome_name,
"ws_pk" + chrome_name + trace_name,
process_metrics->GetPeakWorkingSetSize(), "bytes",
true /* important */);
PrintResult("ws_final", chrome_name,
"ws_f" + chrome_name + trace_name,
process_metrics->GetWorkingSetSize(), "bytes",
false /* not important */);
#elif defined(OS_LINUX)
PrintResult("vm_size_final", chrome_name,
"vm_size_f" + chrome_name + trace_name,
process_metrics->GetPagefileUsage(), "bytes",
true /* important */);
PrintResult("vm_rss_final", chrome_name,
"vm_rss_f" + chrome_name + trace_name,
process_metrics->GetWorkingSetSize(), "bytes",
true /* important */);
#else
NOTIMPLEMENTED();
#endif
base::CloseProcessHandle(process_handle);
}
}
// When use_http is true, the test name passed here will be used directly in
// the path to the test data, so it must be safe for use in a URL without
// escaping. (No pound (#), question mark (?), semicolon (;), non-ASCII, or
// other funny stuff.)
void RunTest(const char* name, bool use_http) {
std::wstring pages;
std::string timings;
RunPageCycler(name, &pages, &timings, use_http);
if (timings.empty())
return;
PrintMemoryUsageInfo("");
PrintIOPerfInfo("");
wprintf(L"\nPages: [%ls]\n", pages.c_str());
PrintResultList("times", "", "t", timings, "ms",
true /* important */);
}
};
class PageCyclerReferenceTest : public PageCyclerTest {
public:
// override the browser directory that is used by UITest::SetUp to cause it
// to use the reference build instead.
void SetUp() {
FilePath dir;
PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
dir = dir.AppendASCII("reference_build");
#if defined(OS_WIN)
dir = dir.AppendASCII("chrome");
#elif defined(OS_LINUX)
dir = dir.AppendASCII("chrome_linux");
#elif defined(OS_MACOSX)
dir = dir.AppendASCII("chrome_mac");
#endif
browser_directory_ = dir;
UITest::SetUp();
}
void RunTest(const char* name, bool use_http) {
std::wstring pages;
std::string timings;
RunPageCycler(name, &pages, &timings, use_http);
if (timings.empty())
return;
PrintMemoryUsageInfo("_ref");
PrintIOPerfInfo("_ref");
PrintResultList("times", "", "t_ref", timings, "ms",
true /* important */);
}
};
// file-URL tests
TEST_F(PageCyclerTest, MozFile) {
RunTest("moz", false);
}
// TODO(port): Enable PageCyclerReferenceTest when reference build is
// available for non-windows
#if !defined(OS_MACOSX)
TEST_F(PageCyclerReferenceTest, MozFile) {
RunTest("moz", false);
}
// TODO(nirnimesh): Intl1File, Intl2File, Intl1Http, Intl2Http crash Chromium
// on Mac. Revisit later.
TEST_F(PageCyclerTest, Intl1File) {
RunTest("intl1", false);
}
TEST_F(PageCyclerReferenceTest, Intl1File) {
RunTest("intl1", false);
}
TEST_F(PageCyclerTest, Intl2File) {
RunTest("intl2", false);
}
TEST_F(PageCyclerReferenceTest, Intl2File) {
RunTest("intl2", false);
}
#endif // !defined(OS_MACOSX)
TEST_F(PageCyclerTest, DomFile) {
RunTest("dom", false);
}
#if !defined(OS_MACOSX)
TEST_F(PageCyclerReferenceTest, DomFile) {
RunTest("dom", false);
}
#endif
TEST_F(PageCyclerTest, DhtmlFile) {
RunTest("dhtml", false);
}
#if !defined(OS_MACOSX)
TEST_F(PageCyclerReferenceTest, DhtmlFile) {
RunTest("dhtml", false);
}
#endif
// http (localhost) tests
TEST_F(PageCyclerTest, MozHttp) {
RunTest("moz", true);
}
#if !defined(OS_MACOSX)
TEST_F(PageCyclerReferenceTest, MozHttp) {
RunTest("moz", true);
}
TEST_F(PageCyclerTest, Intl1Http) {
RunTest("intl1", true);
}
TEST_F(PageCyclerReferenceTest, Intl1Http) {
RunTest("intl1", true);
}
TEST_F(PageCyclerTest, Intl2Http) {
RunTest("intl2", true);
}
TEST_F(PageCyclerReferenceTest, Intl2Http) {
RunTest("intl2", true);
}
#endif // !defined(OS_MACOSX)
TEST_F(PageCyclerTest, DomHttp) {
RunTest("dom", true);
}
#if !defined(OS_MACOSX)
TEST_F(PageCyclerReferenceTest, DomHttp) {
RunTest("dom", true);
}
#endif
TEST_F(PageCyclerTest, BloatHttp) {
RunTest("bloat", true);
}
#if !defined(OS_MACOSX)
TEST_F(PageCyclerReferenceTest, BloatHttp) {
RunTest("bloat", true);
}
#endif
} // namespace
<commit_msg>Disable page cyclers on linux, they're crashing on Chromium Linux.<commit_after>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/string_util.h"
#include "chrome/browser/net/url_fixer_upper.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/automation/tab_proxy.h"
#include "chrome/test/automation/window_proxy.h"
#include "chrome/test/chrome_process_util.h"
#include "chrome/test/ui/ui_test.h"
#include "googleurl/src/gurl.h"
#include "net/base/net_util.h"
#ifndef NDEBUG
#define TEST_ITERATIONS "2"
#else
#define TEST_ITERATIONS "10"
#endif
// URL at which data files may be found for HTTP tests. The document root of
// this URL's server should point to data/page_cycler/.
static const char kBaseUrl[] = "http://localhost:8000/";
namespace {
class PageCyclerTest : public UITest {
public:
PageCyclerTest() {
show_window_ = true;
// Expose garbage collection for the page cycler tests.
launch_arguments_.AppendSwitchWithValue(switches::kJavaScriptFlags,
L"--expose_gc");
}
// For HTTP tests, the name must be safe for use in a URL without escaping.
void RunPageCycler(const char* name, std::wstring* pages,
std::string* timings, bool use_http) {
GURL test_url;
if (use_http) {
test_url = GURL(std::string(kBaseUrl) + name + "/start.html");
} else {
FilePath test_path;
PathService::Get(base::DIR_EXE, &test_path);
test_path = test_path.DirName();
test_path = test_path.DirName();
test_path = test_path.Append(FILE_PATH_LITERAL("data"));
test_path = test_path.Append(FILE_PATH_LITERAL("page_cycler"));
test_path = test_path.AppendASCII(name);
test_path = test_path.Append(FILE_PATH_LITERAL("start.html"));
test_url = net::FilePathToFileURL(test_path);
}
// run N iterations
GURL::Replacements replacements;
const char query_string[] = "iterations=" TEST_ITERATIONS "&auto=1";
replacements.SetQuery(
query_string,
url_parse::Component(0, arraysize(query_string) - 1));
test_url = test_url.ReplaceComponents(replacements);
scoped_ptr<TabProxy> tab(GetActiveTab());
tab->NavigateToURL(test_url);
// Wait for the test to finish.
ASSERT_TRUE(WaitUntilCookieValue(tab.get(), test_url, "__pc_done",
3000, UITest::test_timeout_ms(), "1"));
std::string cookie;
ASSERT_TRUE(tab->GetCookieByName(test_url, "__pc_pages", &cookie));
pages->assign(UTF8ToWide(cookie));
ASSERT_FALSE(pages->empty());
ASSERT_TRUE(tab->GetCookieByName(test_url, "__pc_timings", &cookie));
timings->assign(cookie);
ASSERT_FALSE(timings->empty());
}
void PrintIOPerfInfo(const char* test_name) {
FilePath data_dir;
PathService::Get(chrome::DIR_USER_DATA, &data_dir);
int browser_process_pid = ChromeBrowserProcessId(data_dir);
ChromeProcessList chrome_processes(GetRunningChromeProcesses(data_dir));
ChromeProcessList::const_iterator it;
for (it = chrome_processes.begin(); it != chrome_processes.end(); ++it) {
base::ProcessHandle process_handle;
if (!base::OpenProcessHandle(*it, &process_handle)) {
NOTREACHED();
}
scoped_ptr<base::ProcessMetrics> process_metrics;
process_metrics.reset(
base::ProcessMetrics::CreateProcessMetrics(process_handle));
IoCounters io_counters;
memset(&io_counters, 0, sizeof(io_counters));
if (process_metrics.get()->GetIOCounters(&io_counters)) {
// Print out IO performance. We assume that the values can be
// converted to size_t (they're reported as ULONGLONG, 64-bit numbers).
std::string chrome_name = (*it == browser_process_pid) ? "_b" : "_r";
PrintResult("read_op", chrome_name,
"r_op" + chrome_name + test_name,
static_cast<size_t>(io_counters.ReadOperationCount), "",
false /* not important */);
PrintResult("write_op", chrome_name,
"w_op" + chrome_name + test_name,
static_cast<size_t>(io_counters.WriteOperationCount), "",
false /* not important */);
PrintResult("other_op", chrome_name,
"o_op" + chrome_name + test_name,
static_cast<size_t>(io_counters.OtherOperationCount), "",
false /* not important */);
size_t total = static_cast<size_t>(io_counters.ReadOperationCount +
io_counters.WriteOperationCount +
io_counters.OtherOperationCount);
PrintResult("total_op", chrome_name,
"IO_op" + chrome_name + test_name,
total, "", true /* important */);
PrintResult("read_byte", chrome_name,
"r_b" + chrome_name + test_name,
static_cast<size_t>(io_counters.ReadTransferCount / 1024),
"kb", false /* not important */);
PrintResult("write_byte", chrome_name,
"w_b" + chrome_name + test_name,
static_cast<size_t>(io_counters.WriteTransferCount / 1024),
"kb", false /* not important */);
PrintResult("other_byte", chrome_name,
"o_b" + chrome_name + test_name,
static_cast<size_t>(io_counters.OtherTransferCount / 1024),
"kb", false /* not important */);
total = static_cast<size_t>((io_counters.ReadTransferCount +
io_counters.WriteTransferCount +
io_counters.OtherTransferCount) / 1024);
PrintResult("total_byte", chrome_name,
"IO_b" + chrome_name + test_name,
total, "kb", true /* important */);
}
base::CloseProcessHandle(process_handle);
}
}
void PrintMemoryUsageInfo(const char* test_name) {
FilePath data_dir;
PathService::Get(chrome::DIR_USER_DATA, &data_dir);
int browser_process_pid = ChromeBrowserProcessId(data_dir);
ChromeProcessList chrome_processes(GetRunningChromeProcesses(data_dir));
ChromeProcessList::const_iterator it;
for (it = chrome_processes.begin(); it != chrome_processes.end(); ++it) {
base::ProcessHandle process_handle;
if (!base::OpenProcessHandle(*it, &process_handle)) {
NOTREACHED();
}
scoped_ptr<base::ProcessMetrics> process_metrics;
process_metrics.reset(
base::ProcessMetrics::CreateProcessMetrics(process_handle));
std::string chrome_name = (*it == browser_process_pid) ? "_b" : "_r";
std::string trace_name(test_name);
#if defined(OS_WIN)
PrintResult("vm_peak", chrome_name,
"vm_pk" + chrome_name + trace_name,
process_metrics->GetPeakPagefileUsage(), "bytes",
true /* important */);
PrintResult("vm_final", chrome_name,
"vm_f" + chrome_name + trace_name,
process_metrics->GetPagefileUsage(), "bytes",
false /* not important */);
PrintResult("ws_peak", chrome_name,
"ws_pk" + chrome_name + trace_name,
process_metrics->GetPeakWorkingSetSize(), "bytes",
true /* important */);
PrintResult("ws_final", chrome_name,
"ws_f" + chrome_name + trace_name,
process_metrics->GetWorkingSetSize(), "bytes",
false /* not important */);
#elif defined(OS_LINUX)
PrintResult("vm_size_final", chrome_name,
"vm_size_f" + chrome_name + trace_name,
process_metrics->GetPagefileUsage(), "bytes",
true /* important */);
PrintResult("vm_rss_final", chrome_name,
"vm_rss_f" + chrome_name + trace_name,
process_metrics->GetWorkingSetSize(), "bytes",
true /* important */);
#else
NOTIMPLEMENTED();
#endif
base::CloseProcessHandle(process_handle);
}
}
// When use_http is true, the test name passed here will be used directly in
// the path to the test data, so it must be safe for use in a URL without
// escaping. (No pound (#), question mark (?), semicolon (;), non-ASCII, or
// other funny stuff.)
void RunTest(const char* name, bool use_http) {
std::wstring pages;
std::string timings;
RunPageCycler(name, &pages, &timings, use_http);
if (timings.empty())
return;
PrintMemoryUsageInfo("");
PrintIOPerfInfo("");
wprintf(L"\nPages: [%ls]\n", pages.c_str());
PrintResultList("times", "", "t", timings, "ms",
true /* important */);
}
};
class PageCyclerReferenceTest : public PageCyclerTest {
public:
// override the browser directory that is used by UITest::SetUp to cause it
// to use the reference build instead.
void SetUp() {
FilePath dir;
PathService::Get(chrome::DIR_TEST_TOOLS, &dir);
dir = dir.AppendASCII("reference_build");
#if defined(OS_WIN)
dir = dir.AppendASCII("chrome");
#elif defined(OS_LINUX)
dir = dir.AppendASCII("chrome_linux");
#elif defined(OS_MACOSX)
dir = dir.AppendASCII("chrome_mac");
#endif
browser_directory_ = dir;
UITest::SetUp();
}
void RunTest(const char* name, bool use_http) {
std::wstring pages;
std::string timings;
RunPageCycler(name, &pages, &timings, use_http);
if (timings.empty())
return;
PrintMemoryUsageInfo("_ref");
PrintIOPerfInfo("_ref");
PrintResultList("times", "", "t_ref", timings, "ms",
true /* important */);
}
};
#if !defined(OS_LINUX)
// file-URL tests
TEST_F(PageCyclerTest, MozFile) {
RunTest("moz", false);
}
// TODO(port): Enable PageCyclerReferenceTest when reference build is
// available for non-windows
#if !defined(OS_MACOSX)
TEST_F(PageCyclerReferenceTest, MozFile) {
RunTest("moz", false);
}
// TODO(nirnimesh): Intl1File, Intl2File, Intl1Http, Intl2Http crash Chromium
// on Mac. Revisit later.
TEST_F(PageCyclerTest, Intl1File) {
RunTest("intl1", false);
}
TEST_F(PageCyclerReferenceTest, Intl1File) {
RunTest("intl1", false);
}
TEST_F(PageCyclerTest, Intl2File) {
RunTest("intl2", false);
}
TEST_F(PageCyclerReferenceTest, Intl2File) {
RunTest("intl2", false);
}
#endif // !defined(OS_MACOSX)
TEST_F(PageCyclerTest, DomFile) {
RunTest("dom", false);
}
#if !defined(OS_MACOSX)
TEST_F(PageCyclerReferenceTest, DomFile) {
RunTest("dom", false);
}
#endif
TEST_F(PageCyclerTest, DhtmlFile) {
RunTest("dhtml", false);
}
#if !defined(OS_MACOSX)
TEST_F(PageCyclerReferenceTest, DhtmlFile) {
RunTest("dhtml", false);
}
#endif
// http (localhost) tests
TEST_F(PageCyclerTest, MozHttp) {
RunTest("moz", true);
}
#if !defined(OS_MACOSX)
TEST_F(PageCyclerReferenceTest, MozHttp) {
RunTest("moz", true);
}
TEST_F(PageCyclerTest, Intl1Http) {
RunTest("intl1", true);
}
TEST_F(PageCyclerReferenceTest, Intl1Http) {
RunTest("intl1", true);
}
TEST_F(PageCyclerTest, Intl2Http) {
RunTest("intl2", true);
}
TEST_F(PageCyclerReferenceTest, Intl2Http) {
RunTest("intl2", true);
}
#endif // !defined(OS_MACOSX)
TEST_F(PageCyclerTest, DomHttp) {
RunTest("dom", true);
}
#if !defined(OS_MACOSX)
TEST_F(PageCyclerReferenceTest, DomHttp) {
RunTest("dom", true);
}
#endif
TEST_F(PageCyclerTest, BloatHttp) {
RunTest("bloat", true);
}
#if !defined(OS_MACOSX)
TEST_F(PageCyclerReferenceTest, BloatHttp) {
RunTest("bloat", true);
}
#endif
#endif // !defined(OS_LINUX)
} // namespace
<|endoftext|> |
<commit_before>// ========================================================================== //
// This file is part of DO-CV, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2015 David Ok <[email protected]>
//
// 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/.
// ========================================================================== //
#define _USE_MATH_DEFINES
extern "C" {
# include <libavcodec/avcodec.h>
# include <libavformat/avformat.h>
# include <libavformat/avio.h>
# include <libavutil/file.h>
}
#include "VideoStream.hpp"
namespace DO { namespace Sara {
inline static Yuv8 get_yuv_pixel(const AVFrame *frame, int x, int y)
{
Yuv8 yuv;
yuv(0) = frame->data[0][y*frame->linesize[0] + x];
yuv(1) = frame->data[1][y / 2 * frame->linesize[1] + x / 2];
yuv(2) = frame->data[2][y / 2 * frame->linesize[2] + x / 2];
return yuv;
}
inline static unsigned char clamp(int value)
{
if (value < 0)
return 0;
if (value > 255)
return 255;
return value;
}
inline static Rgb8 convert(const Yuv8& yuv)
{
Rgb8 rgb;
int C = yuv(0) - 16;
int D = yuv(1) - 128;
int E = yuv(2) - 128;
rgb(0) = clamp((298 * C + 409 * E + 128) >> 8);
rgb(1) = clamp((298 * C - 100 * D - 208 * E + 128) >> 8);
rgb(2) = clamp((298 * C + 516 * D + 128) >> 8);
return rgb;
}
} /* namespace Sara */
} /* namespace DO */
namespace DO { namespace Sara {
bool VideoStream::_registered_all_codecs = false;
VideoStream::VideoStream()
{
if (!_registered_all_codecs)
{
av_register_all();
_registered_all_codecs = true;
}
}
VideoStream::VideoStream(const std::string& file_path)
: VideoStream()
{
open(file_path);
}
VideoStream::~VideoStream()
{
close();
}
void
VideoStream::open(const std::string& file_path)
{
// Read the video file.
if (avformat_open_input(&_video_format_context, file_path.c_str(),
nullptr, nullptr) != 0)
throw std::runtime_error("Could not open video file!");
// Read the video stream metadata.
if (avformat_find_stream_info(_video_format_context, nullptr) != 0)
throw std::runtime_error("Could not retrieve video stream info!");
av_dump_format(_video_format_context, 0, file_path.c_str(), 0);
// Retrieve video stream.
_video_stream = -1;
for (unsigned i = 0; i != _video_format_context->nb_streams; ++i)
{
if (_video_format_context->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
{
_video_stream = i;
break;
}
}
if (_video_stream == -1)
throw std::runtime_error("Could not retrieve video stream!");
// Retrieve the video codec context.
_video_codec_context = _video_format_context->streams[_video_stream]->codec;
// Retrieve the video codec.
_video_codec = avcodec_find_decoder(_video_codec_context->codec_id);
if (!_video_codec)
throw std::runtime_error("Could not find supported codec!");
// Open the video codec.
if (avcodec_open2(_video_codec_context, _video_codec, nullptr) < 0)
throw std::runtime_error("Could not open video codec!");
// Allocate video frame.
_video_frame = av_frame_alloc();
if (!_video_frame)
throw std::runtime_error("Could not allocate video frame!");
_video_frame_pos = 0;
}
void
VideoStream::close()
{
if (_video_frame)
{
av_frame_free(&_video_frame);
_video_frame = nullptr;
_video_frame_pos = std::numeric_limits<size_t>::max();
}
if (_video_codec_context)
{
avcodec_close(_video_codec_context);
#if (LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(55, 28, 1))
avcodec_free_context(&_video_codec_context);
#else
av_freep(&_video_codec_context);
#endif
_video_codec_context = nullptr;
_video_codec = nullptr;
}
if (_video_format_context)
_video_format_context = nullptr;
}
void
VideoStream::seek(std::size_t frame_pos)
{
av_seek_frame(_video_format_context, _video_stream, frame_pos,
AVSEEK_FLAG_BACKWARD);
}
bool
VideoStream::read(Image<Rgb8>& video_frame)
{
AVPacket _video_packet;
int length, got_video_frame;
while (av_read_frame(_video_format_context, &_video_packet) >= 0)
{
length = avcodec_decode_video2(_video_codec_context, _video_frame,
&got_video_frame, &_video_packet);
if (length < 0)
return false;
if (got_video_frame)
{
int w = _video_codec_context->width;
int h = _video_codec_context->height;
if (video_frame.width() != w || video_frame.height() != h)
video_frame.resize(w, h);
for (int y = 0; y < h; ++y)
{
for (int x = 0; x < w; ++x)
{
Yuv8 yuv = get_yuv_pixel(_video_frame, x, y);
video_frame(x, y) = Sara::convert(yuv);
}
}
++_video_frame_pos;
return true;
}
}
return false;
}
} /* namespace Sara */
} /* namespace DO */
<commit_msg>MAINT: make a stricter fix for backward compatibility with older FFmpeg versions.<commit_after>// ========================================================================== //
// This file is part of DO-CV, a basic set of libraries in C++ for computer
// vision.
//
// Copyright (C) 2015 David Ok <[email protected]>
//
// 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/.
// ========================================================================== //
#define _USE_MATH_DEFINES
extern "C" {
# include <libavcodec/avcodec.h>
# include <libavformat/avformat.h>
# include <libavformat/avio.h>
# include <libavutil/file.h>
}
#include "VideoStream.hpp"
namespace DO { namespace Sara {
inline static Yuv8 get_yuv_pixel(const AVFrame *frame, int x, int y)
{
Yuv8 yuv;
yuv(0) = frame->data[0][y*frame->linesize[0] + x];
yuv(1) = frame->data[1][y / 2 * frame->linesize[1] + x / 2];
yuv(2) = frame->data[2][y / 2 * frame->linesize[2] + x / 2];
return yuv;
}
inline static unsigned char clamp(int value)
{
if (value < 0)
return 0;
if (value > 255)
return 255;
return value;
}
inline static Rgb8 convert(const Yuv8& yuv)
{
Rgb8 rgb;
int C = yuv(0) - 16;
int D = yuv(1) - 128;
int E = yuv(2) - 128;
rgb(0) = clamp((298 * C + 409 * E + 128) >> 8);
rgb(1) = clamp((298 * C - 100 * D - 208 * E + 128) >> 8);
rgb(2) = clamp((298 * C + 516 * D + 128) >> 8);
return rgb;
}
} /* namespace Sara */
} /* namespace DO */
namespace DO { namespace Sara {
bool VideoStream::_registered_all_codecs = false;
VideoStream::VideoStream()
{
if (!_registered_all_codecs)
{
av_register_all();
_registered_all_codecs = true;
}
}
VideoStream::VideoStream(const std::string& file_path)
: VideoStream()
{
open(file_path);
}
VideoStream::~VideoStream()
{
close();
}
void
VideoStream::open(const std::string& file_path)
{
// Read the video file.
if (avformat_open_input(&_video_format_context, file_path.c_str(),
nullptr, nullptr) != 0)
throw std::runtime_error("Could not open video file!");
// Read the video stream metadata.
if (avformat_find_stream_info(_video_format_context, nullptr) != 0)
throw std::runtime_error("Could not retrieve video stream info!");
av_dump_format(_video_format_context, 0, file_path.c_str(), 0);
// Retrieve video stream.
_video_stream = -1;
for (unsigned i = 0; i != _video_format_context->nb_streams; ++i)
{
if (_video_format_context->streams[i]->codec->codec_type == AVMEDIA_TYPE_VIDEO)
{
_video_stream = i;
break;
}
}
if (_video_stream == -1)
throw std::runtime_error("Could not retrieve video stream!");
// Retrieve the video codec context.
_video_codec_context = _video_format_context->streams[_video_stream]->codec;
// Retrieve the video codec.
_video_codec = avcodec_find_decoder(_video_codec_context->codec_id);
if (!_video_codec)
throw std::runtime_error("Could not find supported codec!");
// Open the video codec.
if (avcodec_open2(_video_codec_context, _video_codec, nullptr) < 0)
throw std::runtime_error("Could not open video codec!");
// Allocate video frame.
_video_frame = av_frame_alloc();
if (!_video_frame)
throw std::runtime_error("Could not allocate video frame!");
_video_frame_pos = 0;
}
void
VideoStream::close()
{
if (_video_frame)
{
av_frame_free(&_video_frame);
_video_frame = nullptr;
_video_frame_pos = std::numeric_limits<size_t>::max();
}
if (_video_codec_context)
{
avcodec_close(_video_codec_context);
// For backward compatibility with older FFmpeg versions, don't use
//avcodec_free_context(&_video_codec_context);
// Instead call the following:
av_freep(&_video_codec_context);
_video_codec_context = nullptr;
_video_codec = nullptr;
}
if (_video_format_context)
_video_format_context = nullptr;
}
void
VideoStream::seek(std::size_t frame_pos)
{
av_seek_frame(_video_format_context, _video_stream, frame_pos,
AVSEEK_FLAG_BACKWARD);
}
bool
VideoStream::read(Image<Rgb8>& video_frame)
{
AVPacket _video_packet;
int length, got_video_frame;
while (av_read_frame(_video_format_context, &_video_packet) >= 0)
{
length = avcodec_decode_video2(_video_codec_context, _video_frame,
&got_video_frame, &_video_packet);
if (length < 0)
return false;
if (got_video_frame)
{
int w = _video_codec_context->width;
int h = _video_codec_context->height;
if (video_frame.width() != w || video_frame.height() != h)
video_frame.resize(w, h);
for (int y = 0; y < h; ++y)
{
for (int x = 0; x < w; ++x)
{
Yuv8 yuv = get_yuv_pixel(_video_frame, x, y);
video_frame(x, y) = Sara::convert(yuv);
}
}
++_video_frame_pos;
return true;
}
}
return false;
}
} /* namespace Sara */
} /* namespace DO */
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "otbVectorData.h"
#include "otbVectorDataFileReader.h"
#include "otbVectorDataFileWriter.h"
#include "otbLabeledSampleLocalizationGenerator.h"
int otbLabeledSampleLocalizationGeneratorNew(int argc, char* argv[])
{
typedef otb::VectorData<> VectorDataType;
typedef otb::LabeledSampleLocalizationGenerator<VectorDataType> GeneratorType;
// instantiation
GeneratorType::Pointer generator = GeneratorType::New();
std::cout << generator << std::endl;
return EXIT_SUCCESS;
}
int otbLabeledSampleLocalizationGenerator(int argc, char* argv[])
{
const char * inputVD1 = argv[1];
const char * inputVD2 = argv[2];
const char * outputVD = argv[3];
typedef otb::VectorData<> VectorDataType;
typedef otb::VectorDataFileReader<VectorDataType> VectorDataReaderType;
typedef otb::VectorDataFileWriter<VectorDataType> VectorDataWriterType;
typedef otb::LabeledSampleLocalizationGenerator<VectorDataType> GeneratorType;
// instantiation
VectorDataReaderType::Pointer reader1 = VectorDataReaderType::New();
VectorDataReaderType::Pointer reader2 = VectorDataReaderType::New();
VectorDataWriterType::Pointer writer = VectorDataWriterType::New();
GeneratorType::Pointer generator = GeneratorType::New();
reader1->SetFileName(inputVD1);
reader1->Update();
reader2->SetFileName(inputVD2);
reader2->Update();
generator->PushBackInput(reader1->GetOutput());
generator->PushBackInput(reader2->GetOutput());
generator->SetSeed(0); // enable reproducible random number sequence
generator->SetClassKey("Class");
generator->SetNoClassIdentifier(0);
generator->SetInhibitionRadius(5);
generator->SetRandomLocalizationDensity(0.004);
generator->SetNbMaxIteration(1000);
generator->Update();
std::cout << generator << std::endl;
writer->SetFileName(outputVD);
writer->SetInput(generator->GetOutput());
writer->Update();
return EXIT_SUCCESS;
}
<commit_msg>TEST:comment std::cout<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif
#include "otbVectorData.h"
#include "otbVectorDataFileReader.h"
#include "otbVectorDataFileWriter.h"
#include "otbLabeledSampleLocalizationGenerator.h"
int otbLabeledSampleLocalizationGeneratorNew(int argc, char* argv[])
{
typedef otb::VectorData<> VectorDataType;
typedef otb::LabeledSampleLocalizationGenerator<VectorDataType> GeneratorType;
// instantiation
GeneratorType::Pointer generator = GeneratorType::New();
std::cout << generator << std::endl;
return EXIT_SUCCESS;
}
int otbLabeledSampleLocalizationGenerator(int argc, char* argv[])
{
const char * inputVD1 = argv[1];
const char * inputVD2 = argv[2];
const char * outputVD = argv[3];
typedef otb::VectorData<> VectorDataType;
typedef otb::VectorDataFileReader<VectorDataType> VectorDataReaderType;
typedef otb::VectorDataFileWriter<VectorDataType> VectorDataWriterType;
typedef otb::LabeledSampleLocalizationGenerator<VectorDataType> GeneratorType;
// instantiation
VectorDataReaderType::Pointer reader1 = VectorDataReaderType::New();
VectorDataReaderType::Pointer reader2 = VectorDataReaderType::New();
VectorDataWriterType::Pointer writer = VectorDataWriterType::New();
GeneratorType::Pointer generator = GeneratorType::New();
reader1->SetFileName(inputVD1);
reader1->Update();
reader2->SetFileName(inputVD2);
reader2->Update();
generator->PushBackInput(reader1->GetOutput());
generator->PushBackInput(reader2->GetOutput());
generator->SetSeed(0); // enable reproducible random number sequence
generator->SetClassKey("Class");
generator->SetNoClassIdentifier(0);
generator->SetInhibitionRadius(5);
generator->SetRandomLocalizationDensity(0.004);
generator->SetNbMaxIteration(1000);
generator->Update();
//std::cout << generator << std::endl;
writer->SetFileName(outputVD);
writer->SetInput(generator->GetOutput());
writer->Update();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>//@author A0097630B
#include "stdafx.h"
#include "You-NLP/parse_tree/task_priority.h"
#include "internal/query_executor.h"
#include "internal/query_executor_builder_visitor.h"
#include "exceptions/context_index_out_of_range_exception.h"
#include "../mocks/task_list.h"
#include "../mocks/query.h"
using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
namespace Microsoft {
namespace VisualStudio {
namespace CppUnitTestFramework {
std::wstring ToString(You::Controller::Task::Priority priority) {
return ToString(static_cast<int>(priority));
}
} // namespace CppUnitTestFramework
} // namespace VisualStudio
} // namespace Microsoft
namespace You {
namespace Controller {
namespace Internal {
namespace UnitTests {
namespace Mocks {
// NOLINTNEXTLINE(build/namespaces)
using namespace You::Controller::UnitTests::Mocks;
}
using Task = You::Controller::Task;
using TaskPriority = You::NLP::TaskPriority;
TEST_CLASS(QueryExecutorBuilderVisitorTests) {
TEST_METHOD(getsCorrectTypeForAddQueries) {
Mocks::TaskList taskList;
QueryExecutorBuilderVisitor visitor(taskList);
You::NLP::QUERY query(Mocks::Queries::ADD_QUERY);
std::unique_ptr<QueryExecutor> executor(
boost::apply_visitor(visitor, query));
ADD_RESULT result(
boost::get<ADD_RESULT>(executor->execute()));
Assert::AreEqual(
Mocks::Queries::ADD_QUERY.description,
result.task.getDescription());
Assert::AreEqual(
Task::Priority::NORMAL,
result.task.getPriority());
Assert::AreEqual(
Mocks::Queries::ADD_QUERY.deadline.get(),
result.task.getDeadline());
You::NLP::ADD_QUERY queryWithoutDeadline(Mocks::Queries::ADD_QUERY);
queryWithoutDeadline.deadline = boost::none;
query = queryWithoutDeadline;
executor = boost::apply_visitor(visitor, query);
result = boost::get<ADD_RESULT>(executor->execute());
Assert::AreEqual(
Mocks::Queries::ADD_QUERY.description,
result.task.getDescription());
Assert::AreEqual(
Task::Priority::NORMAL,
result.task.getPriority());
Assert::AreEqual(
Task::DEFAULT_DEADLINE,
result.task.getDeadline());
You::NLP::ADD_QUERY queryWithPriority(Mocks::Queries::ADD_QUERY);
queryWithPriority.priority = TaskPriority::HIGH;
query = queryWithPriority;
executor = boost::apply_visitor(visitor, query);
result = boost::get<ADD_RESULT>(executor->execute());
Assert::AreEqual(
Mocks::Queries::ADD_QUERY.description,
result.task.getDescription());
Assert::AreEqual(
Task::Priority::HIGH,
result.task.getPriority());
Assert::AreEqual(
Mocks::Queries::ADD_QUERY.deadline.get(),
result.task.getDeadline());
You::NLP::ADD_QUERY queryWithSubtask(Mocks::Queries::ADD_QUERY);
queryWithSubtask.subtasks = {
You::NLP::ADD_QUERY {
Mocks::Queries::ADD_QUERY.description + L"S"
}
};
query = queryWithSubtask;
executor = boost::apply_visitor(visitor, query);
result = boost::get<ADD_RESULT>(executor->execute());
Assert::IsFalse(result.task.getSubtasks().empty());
}
TEST_METHOD(getsCorrectTypeForShowQueries) {
SHOW_RESULT result(
runShowQuery(Mocks::Queries::SHOW_QUERY));
Assert::IsTrue(
std::all_of(begin(result.tasks), end(result.tasks),
[](const Task& task) {
return task.getDeadline() >
boost::get<boost::posix_time::ptime>(
Mocks::Queries::SHOW_QUERY.predicates[0].value);
}));
Assert::IsTrue(
std::is_sorted(begin(result.tasks), end(result.tasks),
[](const Task& left, const Task& right) {
return left.getDeadline() > right.getDeadline();
}));
result = runShowQuery(
You::NLP::SHOW_QUERY {
{
{
You::NLP::TaskField::PRIORITY,
You::NLP::SHOW_QUERY::Predicate::EQ,
You::NLP::TaskPriority::NORMAL
}
},
{
{
You::NLP::TaskField::DESCRIPTION,
You::NLP::SHOW_QUERY::Order::ASCENDING
}
}
});
Assert::IsTrue(
std::all_of(begin(result.tasks), end(result.tasks),
std::bind(
std::equal_to<You::QueryEngine::Task::Priority>(),
std::bind(&Task::getPriority, std::placeholders::_1),
You::QueryEngine::Task::Priority::NORMAL)));
Assert::IsTrue(
std::is_sorted(begin(result.tasks), end(result.tasks),
[](const Task& left, const Task& right) {
return left.getDescription() < right.getDescription();
}));
result = runShowQuery(
You::NLP::SHOW_QUERY {
{
{
You::NLP::TaskField::COMPLETE,
You::NLP::SHOW_QUERY::Predicate::EQ,
false
}
},
{
{
You::NLP::TaskField::PRIORITY,
You::NLP::SHOW_QUERY::Order::DESCENDING
}
}
});
Assert::IsTrue(
std::all_of(begin(result.tasks), end(result.tasks),
std::bind(
std::not_equal_to<bool>(),
std::bind(&Task::isCompleted, std::placeholders::_1),
true)));
Assert::IsTrue(
std::is_sorted(begin(result.tasks), end(result.tasks),
std::bind(
std::greater<Task::Priority>(),
std::bind(&Task::getPriority, std::placeholders::_1),
std::bind(&Task::getPriority, std::placeholders::_1))));
appliesCorrectFilters();
}
void appliesCorrectFilters() {
// Test filters more rigourously
appliesCorrectFilters<You::NLP::TaskField::DESCRIPTION>(
std::bind(&Task::getDescription, std::placeholders::_1),
std::wstring(L"meh 1"));
auto runTime = boost::posix_time::second_clock::local_time();
appliesCorrectFilters<You::NLP::TaskField::DEADLINE>(
std::bind(&Task::getDeadline, std::placeholders::_1),
runTime + boost::posix_time::hours(1));
appliesCorrectFilters<You::NLP::TaskField::COMPLETE>(
std::bind(&Task::isCompleted, std::placeholders::_1),
true);
// TODO(lowjoel): Implement comparators for priorities.
appliesCorrectFilters<You::NLP::TaskField::PRIORITY>(
[](const Task& task) {
return Controller::queryEngineToNlpPriority(
task.getPriority());
},
You::NLP::TaskPriority::HIGH);
}
/// This is a very useful template function. Because it tests all 7
/// operators: equality, inequality, less than, less than or equal,
/// greater than, greater or equal on a type all at once.
///
/// \tparam field The field to access
/// \param getter The getter to access the record in the object.
/// \param value The value to compare against.
template<You::NLP::TaskField field, typename TGetter, typename TValue>
void appliesCorrectFilters(TGetter getter, const TValue& value) {
SHOW_RESULT result(runShowQuery(You::NLP::SHOW_QUERY {
{ { field, You::NLP::SHOW_QUERY::Predicate::EQ, value } }, {}
}));
Assert::IsTrue(
std::all_of(begin(result.tasks), end(result.tasks),
std::bind(
std::equal_to<TValue>(),
std::bind(getter, std::placeholders::_1),
value)));
result = runShowQuery(You::NLP::SHOW_QUERY {
{ { field, You::NLP::SHOW_QUERY::Predicate::NOT_EQ, value } }, {}
});
Assert::IsTrue(
std::all_of(begin(result.tasks), end(result.tasks),
std::bind(
std::not_equal_to<TValue>(),
std::bind(getter, std::placeholders::_1),
value)));
result = runShowQuery(You::NLP::SHOW_QUERY {
{ { field, You::NLP::SHOW_QUERY::Predicate::LESS_THAN, value } }, {}
});
Assert::IsTrue(
std::all_of(begin(result.tasks), end(result.tasks),
std::bind(
std::less<TValue>(),
std::bind(getter, std::placeholders::_1),
value)));
result = runShowQuery(You::NLP::SHOW_QUERY {
{ {
field,
You::NLP::SHOW_QUERY::Predicate::LESS_THAN_EQ,
value
} }, {}
});
Assert::IsTrue(
std::all_of(begin(result.tasks), end(result.tasks),
std::bind(
std::less_equal<TValue>(),
std::bind(getter, std::placeholders::_1),
value)));
result = runShowQuery(You::NLP::SHOW_QUERY {
{ {
field,
You::NLP::SHOW_QUERY::Predicate::GREATER_THAN,
value }
}, {}
});
Assert::IsTrue(
std::all_of(begin(result.tasks), end(result.tasks),
std::bind(
std::greater<TValue>(),
std::bind(getter, std::placeholders::_1),
value)));
result = runShowQuery(You::NLP::SHOW_QUERY {
{ {
field,
You::NLP::SHOW_QUERY::Predicate::GREATER_THAN_EQ,
value
} }, {}
});
Assert::IsTrue(
std::all_of(begin(result.tasks), end(result.tasks),
std::bind(
std::greater_equal<TValue>(),
std::bind(getter, std::placeholders::_1),
value)));
}
SHOW_RESULT runShowQuery(const You::NLP::QUERY& query) {
Mocks::TaskList taskList(5);
QueryExecutorBuilderVisitor visitor(taskList);
std::unique_ptr<QueryExecutor> executor =
boost::apply_visitor(visitor, query);
return boost::get<SHOW_RESULT>(executor->execute());
}
TEST_METHOD(getsCorrectTypeForEditQueries) {
NLP::EDIT_QUERY query = Mocks::Queries::EDIT_QUERY;
executesEditQueryProperly(query);
query.description = boost::none;
executesEditQueryProperly(query);
query = Mocks::Queries::EDIT_QUERY;
query.priority = boost::none;
executesEditQueryProperly(query);
query = Mocks::Queries::EDIT_QUERY;
query.deadline = boost::none;
executesEditQueryProperly(query);
query = Mocks::Queries::EDIT_QUERY;
query.complete = boost::none;
executesEditQueryProperly(query);
query = NLP::EDIT_QUERY {};
query.taskID = Mocks::Queries::EDIT_QUERY.taskID;
query.childTask = 1;
executesEditQueryProperly(query);
query = NLP::EDIT_QUERY {};
query.taskID = Mocks::Queries::EDIT_QUERY.taskID;
query.dependingTask = 1;
executesEditQueryProperly(query);
}
void executesEditQueryProperly(const NLP::EDIT_QUERY& editQuery) {
Mocks::TaskList taskList(5);
QueryExecutorBuilderVisitor visitor(taskList);
Task& first = taskList.front();
You::NLP::QUERY query = editQuery;
std::unique_ptr<QueryExecutor> executor(
boost::apply_visitor(visitor, query));
EDIT_RESULT result(
boost::get<EDIT_RESULT>(executor->execute()));
if (editQuery.dependingTask) {
Assert::AreNotEqual(first.getID(), result.task.getID());
Assert::IsFalse(result.task.getDependencies().empty());
} else {
Assert::AreEqual(first.getID(), result.task.getID());
Assert::AreEqual(editQuery.description ?
editQuery.description.get() : first.getDescription(),
result.task.getDescription());
Assert::AreEqual(editQuery.priority ?
Controller::nlpToQueryEnginePriority(editQuery.priority.get()) :
first.getPriority(),
result.task.getPriority());
Assert::AreEqual(editQuery.deadline ?
editQuery.deadline.get() : first.getDeadline(),
result.task.getDeadline());
Assert::AreEqual(editQuery.complete ?
editQuery.complete.get() : first.isCompleted(),
result.task.isCompleted());
Assert::AreEqual(editQuery.childTask ?
first.getSubtasks().size() + 1 :
first.getSubtasks().size(),
result.task.getSubtasks().size());
Assert::AreEqual(
first.getDependencies().size(),
result.task.getDependencies().size());
}
}
TEST_METHOD(editQueriesOutOfBoundsThrowsContextOutOfRange) {
Mocks::TaskList taskList(0);
QueryExecutorBuilderVisitor visitor(taskList);
You::NLP::QUERY query(Mocks::Queries::EDIT_QUERY);
Assert::ExpectException<ContextIndexOutOfRangeException>([&]() {
boost::apply_visitor(visitor, query);
});
}
TEST_METHOD(getsCorrectTypeForDeleteQueries) {
Mocks::TaskList taskList;
QueryExecutorBuilderVisitor visitor(taskList);
You::NLP::QUERY query(Mocks::Queries::DELETE_QUERY);
std::unique_ptr<QueryExecutor> executor(
boost::apply_visitor(visitor, query));
DELETE_RESULT result(
boost::get<DELETE_RESULT>(executor->execute()));
Assert::AreEqual(taskList.front().getID(),
result.task);
}
TEST_METHOD(deleteQueriesOutOfBoundsThrowsContextOutOfRange) {
Mocks::TaskList taskList(0);
QueryExecutorBuilderVisitor visitor(taskList);
You::NLP::QUERY query(Mocks::Queries::DELETE_QUERY);
Assert::ExpectException<ContextIndexOutOfRangeException>([&]() {
boost::apply_visitor(visitor, query);
});
}
TEST_METHOD(getsCorrectTypeForUndoQueries) {
Mocks::TaskList taskList;
QueryExecutorBuilderVisitor visitor(taskList);
You::NLP::QUERY query(Mocks::Queries::UNDO_QUERY);
std::unique_ptr<QueryExecutor> executor(
boost::apply_visitor(visitor, query));
UNDO_RESULT result(
boost::get<UNDO_RESULT>(executor->execute()));
// TODO(lowjoel): test for..?
}
};
} // namespace UnitTests
} // namespace Internal
} // namespace Controller
} // namespace You
<commit_msg>Test for the removal of subtasks and dependencies.<commit_after>//@author A0097630B
#include "stdafx.h"
#include "You-NLP/parse_tree/task_priority.h"
#include "internal/query_executor.h"
#include "internal/query_executor_builder_visitor.h"
#include "exceptions/context_index_out_of_range_exception.h"
#include "../mocks/task_list.h"
#include "../mocks/query.h"
using Assert = Microsoft::VisualStudio::CppUnitTestFramework::Assert;
namespace Microsoft {
namespace VisualStudio {
namespace CppUnitTestFramework {
std::wstring ToString(You::Controller::Task::Priority priority) {
return ToString(static_cast<int>(priority));
}
} // namespace CppUnitTestFramework
} // namespace VisualStudio
} // namespace Microsoft
namespace You {
namespace Controller {
namespace Internal {
namespace UnitTests {
namespace Mocks {
// NOLINTNEXTLINE(build/namespaces)
using namespace You::Controller::UnitTests::Mocks;
}
using Task = You::Controller::Task;
using TaskPriority = You::NLP::TaskPriority;
TEST_CLASS(QueryExecutorBuilderVisitorTests) {
TEST_METHOD(getsCorrectTypeForAddQueries) {
Mocks::TaskList taskList;
QueryExecutorBuilderVisitor visitor(taskList);
You::NLP::QUERY query(Mocks::Queries::ADD_QUERY);
std::unique_ptr<QueryExecutor> executor(
boost::apply_visitor(visitor, query));
ADD_RESULT result(
boost::get<ADD_RESULT>(executor->execute()));
Assert::AreEqual(
Mocks::Queries::ADD_QUERY.description,
result.task.getDescription());
Assert::AreEqual(
Task::Priority::NORMAL,
result.task.getPriority());
Assert::AreEqual(
Mocks::Queries::ADD_QUERY.deadline.get(),
result.task.getDeadline());
You::NLP::ADD_QUERY queryWithoutDeadline(Mocks::Queries::ADD_QUERY);
queryWithoutDeadline.deadline = boost::none;
query = queryWithoutDeadline;
executor = boost::apply_visitor(visitor, query);
result = boost::get<ADD_RESULT>(executor->execute());
Assert::AreEqual(
Mocks::Queries::ADD_QUERY.description,
result.task.getDescription());
Assert::AreEqual(
Task::Priority::NORMAL,
result.task.getPriority());
Assert::AreEqual(
Task::DEFAULT_DEADLINE,
result.task.getDeadline());
You::NLP::ADD_QUERY queryWithPriority(Mocks::Queries::ADD_QUERY);
queryWithPriority.priority = TaskPriority::HIGH;
query = queryWithPriority;
executor = boost::apply_visitor(visitor, query);
result = boost::get<ADD_RESULT>(executor->execute());
Assert::AreEqual(
Mocks::Queries::ADD_QUERY.description,
result.task.getDescription());
Assert::AreEqual(
Task::Priority::HIGH,
result.task.getPriority());
Assert::AreEqual(
Mocks::Queries::ADD_QUERY.deadline.get(),
result.task.getDeadline());
You::NLP::ADD_QUERY queryWithSubtask(Mocks::Queries::ADD_QUERY);
queryWithSubtask.subtasks = {
You::NLP::ADD_QUERY {
Mocks::Queries::ADD_QUERY.description + L"S"
}
};
query = queryWithSubtask;
executor = boost::apply_visitor(visitor, query);
result = boost::get<ADD_RESULT>(executor->execute());
Assert::IsFalse(result.task.getSubtasks().empty());
}
TEST_METHOD(getsCorrectTypeForShowQueries) {
SHOW_RESULT result(
runShowQuery(Mocks::Queries::SHOW_QUERY));
Assert::IsTrue(
std::all_of(begin(result.tasks), end(result.tasks),
[](const Task& task) {
return task.getDeadline() >
boost::get<boost::posix_time::ptime>(
Mocks::Queries::SHOW_QUERY.predicates[0].value);
}));
Assert::IsTrue(
std::is_sorted(begin(result.tasks), end(result.tasks),
[](const Task& left, const Task& right) {
return left.getDeadline() > right.getDeadline();
}));
result = runShowQuery(
You::NLP::SHOW_QUERY {
{
{
You::NLP::TaskField::PRIORITY,
You::NLP::SHOW_QUERY::Predicate::EQ,
You::NLP::TaskPriority::NORMAL
}
},
{
{
You::NLP::TaskField::DESCRIPTION,
You::NLP::SHOW_QUERY::Order::ASCENDING
}
}
});
Assert::IsTrue(
std::all_of(begin(result.tasks), end(result.tasks),
std::bind(
std::equal_to<You::QueryEngine::Task::Priority>(),
std::bind(&Task::getPriority, std::placeholders::_1),
You::QueryEngine::Task::Priority::NORMAL)));
Assert::IsTrue(
std::is_sorted(begin(result.tasks), end(result.tasks),
[](const Task& left, const Task& right) {
return left.getDescription() < right.getDescription();
}));
result = runShowQuery(
You::NLP::SHOW_QUERY {
{
{
You::NLP::TaskField::COMPLETE,
You::NLP::SHOW_QUERY::Predicate::EQ,
false
}
},
{
{
You::NLP::TaskField::PRIORITY,
You::NLP::SHOW_QUERY::Order::DESCENDING
}
}
});
Assert::IsTrue(
std::all_of(begin(result.tasks), end(result.tasks),
std::bind(
std::not_equal_to<bool>(),
std::bind(&Task::isCompleted, std::placeholders::_1),
true)));
Assert::IsTrue(
std::is_sorted(begin(result.tasks), end(result.tasks),
std::bind(
std::greater<Task::Priority>(),
std::bind(&Task::getPriority, std::placeholders::_1),
std::bind(&Task::getPriority, std::placeholders::_1))));
appliesCorrectFilters();
}
void appliesCorrectFilters() {
// Test filters more rigourously
appliesCorrectFilters<You::NLP::TaskField::DESCRIPTION>(
std::bind(&Task::getDescription, std::placeholders::_1),
std::wstring(L"meh 1"));
auto runTime = boost::posix_time::second_clock::local_time();
appliesCorrectFilters<You::NLP::TaskField::DEADLINE>(
std::bind(&Task::getDeadline, std::placeholders::_1),
runTime + boost::posix_time::hours(1));
appliesCorrectFilters<You::NLP::TaskField::COMPLETE>(
std::bind(&Task::isCompleted, std::placeholders::_1),
true);
// TODO(lowjoel): Implement comparators for priorities.
appliesCorrectFilters<You::NLP::TaskField::PRIORITY>(
[](const Task& task) {
return Controller::queryEngineToNlpPriority(
task.getPriority());
},
You::NLP::TaskPriority::HIGH);
}
/// This is a very useful template function. Because it tests all 7
/// operators: equality, inequality, less than, less than or equal,
/// greater than, greater or equal on a type all at once.
///
/// \tparam field The field to access
/// \param getter The getter to access the record in the object.
/// \param value The value to compare against.
template<You::NLP::TaskField field, typename TGetter, typename TValue>
void appliesCorrectFilters(TGetter getter, const TValue& value) {
SHOW_RESULT result(runShowQuery(You::NLP::SHOW_QUERY {
{ { field, You::NLP::SHOW_QUERY::Predicate::EQ, value } }, {}
}));
Assert::IsTrue(
std::all_of(begin(result.tasks), end(result.tasks),
std::bind(
std::equal_to<TValue>(),
std::bind(getter, std::placeholders::_1),
value)));
result = runShowQuery(You::NLP::SHOW_QUERY {
{ { field, You::NLP::SHOW_QUERY::Predicate::NOT_EQ, value } }, {}
});
Assert::IsTrue(
std::all_of(begin(result.tasks), end(result.tasks),
std::bind(
std::not_equal_to<TValue>(),
std::bind(getter, std::placeholders::_1),
value)));
result = runShowQuery(You::NLP::SHOW_QUERY {
{ { field, You::NLP::SHOW_QUERY::Predicate::LESS_THAN, value } }, {}
});
Assert::IsTrue(
std::all_of(begin(result.tasks), end(result.tasks),
std::bind(
std::less<TValue>(),
std::bind(getter, std::placeholders::_1),
value)));
result = runShowQuery(You::NLP::SHOW_QUERY {
{ {
field,
You::NLP::SHOW_QUERY::Predicate::LESS_THAN_EQ,
value
} }, {}
});
Assert::IsTrue(
std::all_of(begin(result.tasks), end(result.tasks),
std::bind(
std::less_equal<TValue>(),
std::bind(getter, std::placeholders::_1),
value)));
result = runShowQuery(You::NLP::SHOW_QUERY {
{ {
field,
You::NLP::SHOW_QUERY::Predicate::GREATER_THAN,
value }
}, {}
});
Assert::IsTrue(
std::all_of(begin(result.tasks), end(result.tasks),
std::bind(
std::greater<TValue>(),
std::bind(getter, std::placeholders::_1),
value)));
result = runShowQuery(You::NLP::SHOW_QUERY {
{ {
field,
You::NLP::SHOW_QUERY::Predicate::GREATER_THAN_EQ,
value
} }, {}
});
Assert::IsTrue(
std::all_of(begin(result.tasks), end(result.tasks),
std::bind(
std::greater_equal<TValue>(),
std::bind(getter, std::placeholders::_1),
value)));
}
SHOW_RESULT runShowQuery(const You::NLP::QUERY& query) {
Mocks::TaskList taskList(5);
QueryExecutorBuilderVisitor visitor(taskList);
std::unique_ptr<QueryExecutor> executor =
boost::apply_visitor(visitor, query);
return boost::get<SHOW_RESULT>(executor->execute());
}
TEST_METHOD(getsCorrectTypeForEditQueries) {
NLP::EDIT_QUERY query = Mocks::Queries::EDIT_QUERY;
executesEditQueryProperly(query);
query.description = boost::none;
executesEditQueryProperly(query);
query = Mocks::Queries::EDIT_QUERY;
query.priority = boost::none;
executesEditQueryProperly(query);
query = Mocks::Queries::EDIT_QUERY;
query.deadline = boost::none;
executesEditQueryProperly(query);
query = Mocks::Queries::EDIT_QUERY;
query.complete = boost::none;
executesEditQueryProperly(query);
query = NLP::EDIT_QUERY {};
query.taskID = Mocks::Queries::EDIT_QUERY.taskID;
query.childTask = 1;
executesEditQueryProperly(query);
query.childTask = -1;
executesEditQueryProperly(query);
query = NLP::EDIT_QUERY {};
query.taskID = Mocks::Queries::EDIT_QUERY.taskID;
query.dependingTask = 1;
executesEditQueryProperly(query);
query.dependingTask = -1;
executesEditQueryProperly(query);
}
void executesEditQueryProperly(const NLP::EDIT_QUERY& editQuery) {
Mocks::TaskList taskList(5);
QueryExecutorBuilderVisitor visitor(taskList);
Task& first = taskList.front();
You::NLP::QUERY query = editQuery;
std::unique_ptr<QueryExecutor> executor(
boost::apply_visitor(visitor, query));
EDIT_RESULT result(
boost::get<EDIT_RESULT>(executor->execute()));
if (editQuery.dependingTask) {
Assert::AreNotEqual(first.getID(), result.task.getID());
if (editQuery.dependingTask.get() > 0) {
Assert::IsFalse(result.task.getDependencies().empty());
}
} else {
Assert::AreEqual(first.getID(), result.task.getID());
Assert::AreEqual(editQuery.description ?
editQuery.description.get() : first.getDescription(),
result.task.getDescription());
Assert::AreEqual(editQuery.priority ?
Controller::nlpToQueryEnginePriority(editQuery.priority.get()) :
first.getPriority(),
result.task.getPriority());
Assert::AreEqual(editQuery.deadline ?
editQuery.deadline.get() : first.getDeadline(),
result.task.getDeadline());
Assert::AreEqual(editQuery.complete ?
editQuery.complete.get() : first.isCompleted(),
result.task.isCompleted());
if (editQuery.childTask) {
if (editQuery.childTask.get() > 0) {
Assert::AreEqual(first.getSubtasks().size() + 1,
result.task.getSubtasks().size());
}
} else {
Assert::AreEqual(first.getSubtasks().size(),
result.task.getSubtasks().size());
}
Assert::AreEqual(
first.getDependencies().size(),
result.task.getDependencies().size());
}
}
TEST_METHOD(editQueriesOutOfBoundsThrowsContextOutOfRange) {
Mocks::TaskList taskList(0);
QueryExecutorBuilderVisitor visitor(taskList);
You::NLP::QUERY query(Mocks::Queries::EDIT_QUERY);
Assert::ExpectException<ContextIndexOutOfRangeException>([&]() {
boost::apply_visitor(visitor, query);
});
}
TEST_METHOD(getsCorrectTypeForDeleteQueries) {
Mocks::TaskList taskList;
QueryExecutorBuilderVisitor visitor(taskList);
You::NLP::QUERY query(Mocks::Queries::DELETE_QUERY);
std::unique_ptr<QueryExecutor> executor(
boost::apply_visitor(visitor, query));
DELETE_RESULT result(
boost::get<DELETE_RESULT>(executor->execute()));
Assert::AreEqual(taskList.front().getID(),
result.task);
}
TEST_METHOD(deleteQueriesOutOfBoundsThrowsContextOutOfRange) {
Mocks::TaskList taskList(0);
QueryExecutorBuilderVisitor visitor(taskList);
You::NLP::QUERY query(Mocks::Queries::DELETE_QUERY);
Assert::ExpectException<ContextIndexOutOfRangeException>([&]() {
boost::apply_visitor(visitor, query);
});
}
TEST_METHOD(getsCorrectTypeForUndoQueries) {
Mocks::TaskList taskList;
QueryExecutorBuilderVisitor visitor(taskList);
You::NLP::QUERY query(Mocks::Queries::UNDO_QUERY);
std::unique_ptr<QueryExecutor> executor(
boost::apply_visitor(visitor, query));
UNDO_RESULT result(
boost::get<UNDO_RESULT>(executor->execute()));
// TODO(lowjoel): test for..?
}
};
} // namespace UnitTests
} // namespace Internal
} // namespace Controller
} // namespace You
<|endoftext|> |
<commit_before>#include "Genes/King_Confinement_Gene.h"
#include <cmath>
#include <array>
#include <memory>
#include <map>
#include "Genes/Gene.h"
#include "Game/Board.h"
#include "Game/Color.h"
#include "Game/Square.h"
#include "Game/Piece.h"
#include "Utility.h"
King_Confinement_Gene::King_Confinement_Gene() :
friendly_block_score(0.0),
enemy_block_score(0.0),
maximum_distance(1)
{
}
std::unique_ptr<Gene> King_Confinement_Gene::duplicate() const
{
return std::make_unique<King_Confinement_Gene>(*this);
}
std::string King_Confinement_Gene::name() const
{
return "King Confinement Gene";
}
void King_Confinement_Gene::load_properties()
{
Gene::load_properties();
friendly_block_score = properties["Friendly Block Score"];
enemy_block_score = properties["Enemy Block Score"];
maximum_distance = int(properties["Maximum Distance"]);
}
void King_Confinement_Gene::reset_properties() const
{
Gene::reset_properties();
properties["Friendly Block Score"] = friendly_block_score;
properties["Enemy Block Score"] = enemy_block_score;
properties["Maximum Distance"] = maximum_distance;
}
void King_Confinement_Gene::gene_specific_mutation()
{
make_priority_minimum_zero();
auto mutation_size = Random::random_laplace(2.0);
switch(Random::random_integer(1, 3))
{
case 1:
friendly_block_score += mutation_size;
break;
case 2:
enemy_block_score += mutation_size;
break;
case 3:
maximum_distance += int(mutation_size);
maximum_distance = Math::clamp(maximum_distance, 1, 63);
break;
default:
throw std::logic_error("Bad random value in King Confinement Gene");
}
}
double King_Confinement_Gene::score_board(const Board& board, const Board& opposite_board, size_t) const
{
// A flood-fill-like algorithm to count the squares that are reachable by the
// king from its current positions with unlimited consecutive moves. The
// boundaries of this area area squares attacked by the other color or occupied
// by pieces of the same color.
//
// The more moves it takes to reach a square, the less it adds to the score.
std::vector<Square> square_queue;
square_queue.reserve(64);
auto perspective = board.whose_turn();
const auto& king_square = board.find_king(perspective);
square_queue.push_back(king_square);
std::array<int, 64> distance;
distance.fill(-1); // never-visited value
distance[Board::square_index(king_square.file, king_square.rank)] = 0;
auto squares_safe_for_king = opposite_board.squares_safe_for_king();
double friendly_block_total = 0.0;
double enemy_block_total = 0.0;
int free_space_total = 0;
for(size_t i = 0; i < square_queue.size(); ++i)
{
auto square = square_queue[i];
auto square_index = Board::square_index(square.file, square.rank);
auto attacked_by_other = ! squares_safe_for_king[square_index];
auto dist = distance[square_index];
auto piece = board.piece_on_square(square.file, square.rank);
bool occupied_by_same = piece &&
piece->color() == perspective &&
piece->type() != KING;
if(occupied_by_same)
{
friendly_block_total += friendly_block_score;
}
else if(attacked_by_other)
{
enemy_block_total += enemy_block_score;
}
else
{
++free_space_total;
}
auto keep_going = (square == king_square) ||
(! occupied_by_same && ! attacked_by_other && dist < maximum_distance);
// Add surrounding squares to square_queue.
// always check the squares surrounding the king's current positions, even if
// it is not safe (i.e., the king is in check).
if(keep_going)
{
for(char new_file = square.file - 1; new_file <= square.file + 1; ++new_file)
{
if( ! board.inside_board(new_file))
{
continue;
}
for(int new_rank = square.rank - 1; new_rank <= square.rank + 1; ++new_rank)
{
if( ! board.inside_board(new_rank))
{
continue;
}
auto new_index = Board::square_index(new_file, new_rank);
if(distance[new_index] == -1) // never checked
{
square_queue.push_back(Square{new_file, new_rank});
distance[new_index] = dist + 1;
}
}
}
}
}
auto normalizer = std::abs(friendly_block_score) + std::abs(enemy_block_score);
return ((friendly_block_total + enemy_block_total)/free_space_total)/normalizer;
}
<commit_msg>Calculate search range instead of filtering<commit_after>#include "Genes/King_Confinement_Gene.h"
#include <cmath>
#include <array>
#include <memory>
#include <map>
#include <algorithm>
#include "Genes/Gene.h"
#include "Game/Board.h"
#include "Game/Color.h"
#include "Game/Square.h"
#include "Game/Piece.h"
#include "Utility.h"
King_Confinement_Gene::King_Confinement_Gene() :
friendly_block_score(0.0),
enemy_block_score(0.0),
maximum_distance(1)
{
}
std::unique_ptr<Gene> King_Confinement_Gene::duplicate() const
{
return std::make_unique<King_Confinement_Gene>(*this);
}
std::string King_Confinement_Gene::name() const
{
return "King Confinement Gene";
}
void King_Confinement_Gene::load_properties()
{
Gene::load_properties();
friendly_block_score = properties["Friendly Block Score"];
enemy_block_score = properties["Enemy Block Score"];
maximum_distance = int(properties["Maximum Distance"]);
}
void King_Confinement_Gene::reset_properties() const
{
Gene::reset_properties();
properties["Friendly Block Score"] = friendly_block_score;
properties["Enemy Block Score"] = enemy_block_score;
properties["Maximum Distance"] = maximum_distance;
}
void King_Confinement_Gene::gene_specific_mutation()
{
make_priority_minimum_zero();
auto mutation_size = Random::random_laplace(2.0);
switch(Random::random_integer(1, 3))
{
case 1:
friendly_block_score += mutation_size;
break;
case 2:
enemy_block_score += mutation_size;
break;
case 3:
maximum_distance += int(mutation_size);
maximum_distance = Math::clamp(maximum_distance, 1, 63);
break;
default:
throw std::logic_error("Bad random value in King Confinement Gene");
}
}
double King_Confinement_Gene::score_board(const Board& board, const Board& opposite_board, size_t) const
{
// A flood-fill-like algorithm to count the squares that are reachable by the
// king from its current positions with unlimited consecutive moves. The
// boundaries of this area area squares attacked by the other color or occupied
// by pieces of the same color.
//
// The more moves it takes to reach a square, the less it adds to the score.
std::vector<Square> square_queue;
square_queue.reserve(64);
auto perspective = board.whose_turn();
const auto& king_square = board.find_king(perspective);
square_queue.push_back(king_square);
std::array<int, 64> distance;
distance.fill(-1); // never-visited value
distance[Board::square_index(king_square.file, king_square.rank)] = 0;
auto squares_safe_for_king = opposite_board.squares_safe_for_king();
double friendly_block_total = 0.0;
double enemy_block_total = 0.0;
int free_space_total = 0;
for(size_t i = 0; i < square_queue.size(); ++i)
{
auto square = square_queue[i];
auto square_index = Board::square_index(square.file, square.rank);
auto attacked_by_other = ! squares_safe_for_king[square_index];
auto dist = distance[square_index];
auto piece = board.piece_on_square(square.file, square.rank);
bool occupied_by_same = piece &&
piece->color() == perspective &&
piece->type() != KING;
if(occupied_by_same)
{
friendly_block_total += friendly_block_score;
}
else if(attacked_by_other)
{
enemy_block_total += enemy_block_score;
}
else
{
++free_space_total;
}
auto keep_going = (square == king_square) ||
(! occupied_by_same && ! attacked_by_other && dist < maximum_distance);
// Add surrounding squares to square_queue.
// always check the squares surrounding the king's current positions, even if
// it is not safe (i.e., the king is in check).
if(keep_going)
{
auto left_file = std::max('a', char(square.file() - 1));
auto right_file = std::min('h', char(square.file() + 1));
auto low_rank = std::max(1, square.rank() - 1);
auto high_rank = std::min(8, square.rank() + 1);
for(char new_file = left_file; new_file <= right_file; ++new_file)
{
for(int new_rank = low_rank; new_rank <= high_rank; ++new_rank)
{
auto new_index = Board::square_index(new_file, new_rank);
if(distance[new_index] == -1) // never checked
{
square_queue.push_back(Square{new_file, new_rank});
distance[new_index] = dist + 1;
}
}
}
}
}
auto normalizer = std::abs(friendly_block_score) + std::abs(enemy_block_score);
return ((friendly_block_total + enemy_block_total)/free_space_total)/normalizer;
}
<|endoftext|> |
<commit_before>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <Core/Datatypes/Color.h>
#include <Graphics/Glyphs/GlyphGeom.h>
#include <Graphics/Widgets/ArrowWidget.h>
#include <Graphics/Widgets/WidgetFactory.h>
#include <Graphics/Widgets/WidgetBuilders.h>
using namespace SCIRun;
using namespace SCIRun::Core;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Graphics::Datatypes;
using namespace SCIRun::Core::Geometry;
namespace detail
{
static const ColorRGB deflPointColor = ColorRGB(0.54, 0.6, 1.0);
static const ColorRGB deflColor = ColorRGB(0.5, 0.5, 0.5);
static const ColorRGB resizeColor = ColorRGB(0.54, 1.0, 0.60);
static const double sphereRadius = 0.25;
static const double cylinderRadius = 0.12;
static const double coneRadius = 0.25;
static const double diskRadius = 0.25;
static const double diskDistFromCenter = 0.85;
static const double diskWidth = 0.05;
std::pair<Point, Point> diskPoints(const Point& bmin, const ArrowParameters& params)
{
Point diskPos = bmin + params.dir * params.common.scale * diskDistFromCenter;
Point dp1 = diskPos - diskWidth * params.dir * params.common.scale;
Point dp2 = diskPos + diskWidth * params.dir * params.common.scale;
return { dp1, dp2 };
}
void fixDegenerateBoxes(Point& bmin, Point& bmax)
{
const double size_estimate = std::max((bmax - bmin).length() * 0.01, 1.0e-5);
if (std::abs(bmax.x() - bmin.x()) < 1.0e-6)
{
bmin.x(bmin.x() - size_estimate);
bmax.x(bmax.x() + size_estimate);
}
if (std::abs(bmax.y() - bmin.y()) < 1.0e-6)
{
bmin.y(bmin.y() - size_estimate);
bmax.y(bmax.y() + size_estimate);
}
if (std::abs(bmax.z() - bmin.z()) < 1.0e-6)
{
bmin.z(bmin.z() - size_estimate);
bmax.z(bmax.z() + size_estimate);
}
}
std::tuple<Point, Point> adjustedBoundingBoxPoints(const ArrowParameters& params)
{
Point bmin = params.pos;
Point bmax = params.pos + params.dir * params.common.scale;
fixDegenerateBoxes(bmin, bmax);
return {bmin, bmax};
}
std::string makeName(const ArrowParameters& params)
{
std::stringstream ss;
ss << params.pos << params.dir << static_cast<int>(ColorScheme::COLOR_UNIFORM);
return "widget" + ss.str();
}
std::string widgetName(ArrowWidgetSection s, size_t id, size_t iter)
{
return "ArrowWidget(" + std::to_string(static_cast<int>(s)) + ")" + "(" + std::to_string(id) + ")" +
"(" + std::to_string(iter) + ")";
}
WidgetHandle makeSphere(const GeneralWidgetParameters& gen, const ArrowParameters& params, const Point& origin)
{
ColorRGB sphereCol = (params.show_as_vector) ? deflPointColor : resizeColor;
return SphereWidgetBuilder(gen.base.idGenerator)
.tag(widgetName(ArrowWidgetSection::SPHERE, params.widget_num, params.widget_iter))
.scale(sphereRadius * params.common.scale)
.defaultColor(sphereCol.toString())
.origin(origin)
.boundingBox(params.common.bbox)
.resolution(params.common.resolution)
.centerPoint(origin)
.build();
}
WidgetHandle makeCone(const GeneralWidgetParameters& gen, const ArrowParameters& params, const Point& origin, const Point& bmax)
{
Point center = origin + params.dir/2.0 * params.common.scale;
return ConeWidgetBuilder(gen.base.idGenerator)
.tag(widgetName(ArrowWidgetSection::CONE, params.widget_num, params.widget_iter))
.transformMapping({{WidgetInteraction::CLICK, WidgetMovement::ROTATE}})
.scale(coneRadius * params.common.scale)
.defaultColor(deflColor.toString())
.origin(origin)
.boundingBox(params.common.bbox)
.resolution(params.common.resolution)
.diameterPoints(center, bmax)
.renderBase(true)
.build();
}
WidgetHandle makeDisk(const GeneralWidgetParameters& gen, const ArrowParameters& params, const Point& origin)
{
auto diskDiameterPoints = diskPoints(origin, params);
return DiskWidgetBuilder(gen.base.idGenerator)
.tag(widgetName(ArrowWidgetSection::DISK, params.widget_num, params.widget_iter))
.transformMapping({
{WidgetInteraction::CLICK, WidgetMovement::SCALE}
//,{WidgetInteraction::RIGHT_CLICK, WidgetMovement::TRANSLATE}
})
.scale(diskRadius * params.common.scale)
.defaultColor(resizeColor.toString())
.origin(origin)
.boundingBox(params.common.bbox)
.resolution(params.common.resolution)
.diameterPoints(diskDiameterPoints.first, diskDiameterPoints.second)
.build();
}
WidgetHandle makeCylinder(const GeneralWidgetParameters& gen, const ArrowParameters& params, const Point& origin)
{
// Starts the cylinder position closer to the surface of the sphere
Point center = origin + params.dir/2.0 * params.common.scale;
Point cylinderStart = origin + 0.75 * (params.dir * params.common.scale * sphereRadius);
return CylinderWidgetBuilder(gen.base.idGenerator)
.tag(widgetName(ArrowWidgetSection::CYLINDER, params.widget_num, params.widget_iter))
.transformMapping({{WidgetInteraction::CLICK, WidgetMovement::TRANSLATE}})
.scale(cylinderRadius * params.common.scale)
.defaultColor(deflColor.toString())
.origin(origin)
.boundingBox(params.common.bbox)
.resolution(params.common.resolution)
.diameterPoints(cylinderStart, center)
.build();
}
}
ArrowWidget::ArrowWidget(const GeneralWidgetParameters& gen, ArrowParameters params)
: CompositeWidget(gen.base)
{
using namespace detail;
if (params.common.resolution < 3)
params.common.resolution = 10;
isVector_ = params.show_as_vector;
name_ = uniqueID() + makeName(params);
Point bmin, bmax;
std::tie(bmin, bmax) = adjustedBoundingBoxPoints(params);
const Point origin = bmin;
auto sphere = makeSphere(gen, params, origin);
widgets_.push_back(sphere);
setPosition(sphere->position());
if (isVector_)
{
auto cylinder = makeCylinder(gen, params, origin);
widgets_.push_back(cylinder);
auto cone = makeCone(gen, params, origin, bmax);
widgets_.push_back(cone);
setPosition(cone->position());
auto disk = makeDisk(gen, params, origin);
widgets_.push_back(disk);
//TODO: concern #1--how user interaction maps to transform type
//TODO: concern #2--how transform of "root" maps to siblings
//TODO: create cool operator syntax for wiring these up.
cylinder << propagatesEvent<WidgetMovement::TRANSLATE>::to << TheseWidgets { sphere, disk, cone };
sphere << propagatesEvent<WidgetMovement::TRANSLATE>::to << cylinder << disk << cone;
cone << propagatesEvent<WidgetMovement::ROTATE>::to << sphere << disk << cylinder;
disk << propagatesEvent<WidgetMovement::SCALE>::to << sphere << cylinder << cone;
//disk << propagatesEvent<WidgetMovement::TRANSLATE>::to << sphere << cylinder << cone;
//TODO: concern #3--what data transform of "root" requires
cone->addTransformParameters<Rotation>(origin);
Vector flipVec = params.dir.getArbitraryTangent().normal();
disk->addTransformParameters<Scaling>(origin, flipVec);
}
}
bool ArrowWidget::isVector() const
{
return isVector_;
}
<commit_msg>Adding TODO test interactions<commit_after>/*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2020 Scientific Computing and Imaging Institute,
University of Utah.
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
#include <Core/Datatypes/Color.h>
#include <Graphics/Glyphs/GlyphGeom.h>
#include <Graphics/Widgets/ArrowWidget.h>
#include <Graphics/Widgets/WidgetFactory.h>
#include <Graphics/Widgets/WidgetBuilders.h>
using namespace SCIRun;
using namespace SCIRun::Core;
using namespace SCIRun::Core::Datatypes;
using namespace SCIRun::Graphics::Datatypes;
using namespace SCIRun::Core::Geometry;
namespace detail
{
static const ColorRGB deflPointColor = ColorRGB(0.54, 0.6, 1.0);
static const ColorRGB deflColor = ColorRGB(0.5, 0.5, 0.5);
static const ColorRGB resizeColor = ColorRGB(0.54, 1.0, 0.60);
static const double sphereRadius = 0.25;
static const double cylinderRadius = 0.12;
static const double coneRadius = 0.25;
static const double diskRadius = 0.25;
static const double diskDistFromCenter = 0.85;
static const double diskWidth = 0.05;
std::pair<Point, Point> diskPoints(const Point& bmin, const ArrowParameters& params)
{
Point diskPos = bmin + params.dir * params.common.scale * diskDistFromCenter;
Point dp1 = diskPos - diskWidth * params.dir * params.common.scale;
Point dp2 = diskPos + diskWidth * params.dir * params.common.scale;
return { dp1, dp2 };
}
void fixDegenerateBoxes(Point& bmin, Point& bmax)
{
const double size_estimate = std::max((bmax - bmin).length() * 0.01, 1.0e-5);
if (std::abs(bmax.x() - bmin.x()) < 1.0e-6)
{
bmin.x(bmin.x() - size_estimate);
bmax.x(bmax.x() + size_estimate);
}
if (std::abs(bmax.y() - bmin.y()) < 1.0e-6)
{
bmin.y(bmin.y() - size_estimate);
bmax.y(bmax.y() + size_estimate);
}
if (std::abs(bmax.z() - bmin.z()) < 1.0e-6)
{
bmin.z(bmin.z() - size_estimate);
bmax.z(bmax.z() + size_estimate);
}
}
std::tuple<Point, Point> adjustedBoundingBoxPoints(const ArrowParameters& params)
{
Point bmin = params.pos;
Point bmax = params.pos + params.dir * params.common.scale;
fixDegenerateBoxes(bmin, bmax);
return {bmin, bmax};
}
std::string makeName(const ArrowParameters& params)
{
std::stringstream ss;
ss << params.pos << params.dir << static_cast<int>(ColorScheme::COLOR_UNIFORM);
return "widget" + ss.str();
}
std::string widgetName(ArrowWidgetSection s, size_t id, size_t iter)
{
return "ArrowWidget(" + std::to_string(static_cast<int>(s)) + ")" + "(" + std::to_string(id) + ")" +
"(" + std::to_string(iter) + ")";
}
WidgetHandle makeSphere(const GeneralWidgetParameters& gen, const ArrowParameters& params, const Point& origin)
{
ColorRGB sphereCol = (params.show_as_vector) ? deflPointColor : resizeColor;
return SphereWidgetBuilder(gen.base.idGenerator)
.tag(widgetName(ArrowWidgetSection::SPHERE, params.widget_num, params.widget_iter))
.scale(sphereRadius * params.common.scale)
.defaultColor(sphereCol.toString())
.origin(origin)
.boundingBox(params.common.bbox)
.resolution(params.common.resolution)
.centerPoint(origin)
.build();
}
WidgetHandle makeCone(const GeneralWidgetParameters& gen, const ArrowParameters& params, const Point& origin, const Point& bmax)
{
Point center = origin + params.dir/2.0 * params.common.scale;
return ConeWidgetBuilder(gen.base.idGenerator)
.tag(widgetName(ArrowWidgetSection::CONE, params.widget_num, params.widget_iter))
.transformMapping({{WidgetInteraction::CLICK, WidgetMovement::ROTATE}})
.scale(coneRadius * params.common.scale)
.defaultColor(deflColor.toString())
.origin(origin)
.boundingBox(params.common.bbox)
.resolution(params.common.resolution)
.diameterPoints(center, bmax)
.renderBase(true)
.build();
}
WidgetHandle makeDisk(const GeneralWidgetParameters& gen, const ArrowParameters& params, const Point& origin)
{
auto diskDiameterPoints = diskPoints(origin, params);
return DiskWidgetBuilder(gen.base.idGenerator)
.tag(widgetName(ArrowWidgetSection::DISK, params.widget_num, params.widget_iter))
.transformMapping({
{WidgetInteraction::CLICK, WidgetMovement::SCALE}
,{WidgetInteraction::RIGHT_CLICK, WidgetMovement::TRANSLATE}
})
.scale(diskRadius * params.common.scale)
.defaultColor(resizeColor.toString())
.origin(origin)
.boundingBox(params.common.bbox)
.resolution(params.common.resolution)
.diameterPoints(diskDiameterPoints.first, diskDiameterPoints.second)
.build();
}
WidgetHandle makeCylinder(const GeneralWidgetParameters& gen, const ArrowParameters& params, const Point& origin)
{
// Starts the cylinder position closer to the surface of the sphere
Point center = origin + params.dir/2.0 * params.common.scale;
Point cylinderStart = origin + 0.75 * (params.dir * params.common.scale * sphereRadius);
return CylinderWidgetBuilder(gen.base.idGenerator)
.tag(widgetName(ArrowWidgetSection::CYLINDER, params.widget_num, params.widget_iter))
.transformMapping({
{WidgetInteraction::CLICK, WidgetMovement::TRANSLATE},
{WidgetInteraction::RIGHT_CLICK, WidgetMovement::AXIS_TRANSLATE}
})
.scale(cylinderRadius * params.common.scale)
.defaultColor(deflColor.toString())
.origin(origin)
.boundingBox(params.common.bbox)
.resolution(params.common.resolution)
.diameterPoints(cylinderStart, center)
.build();
}
}
ArrowWidget::ArrowWidget(const GeneralWidgetParameters& gen, ArrowParameters params)
: CompositeWidget(gen.base)
{
using namespace detail;
if (params.common.resolution < 3)
params.common.resolution = 10;
isVector_ = params.show_as_vector;
name_ = uniqueID() + makeName(params);
Point bmin, bmax;
std::tie(bmin, bmax) = adjustedBoundingBoxPoints(params);
const Point origin = bmin;
auto sphere = makeSphere(gen, params, origin);
widgets_.push_back(sphere);
setPosition(sphere->position());
if (isVector_)
{
auto cylinder = makeCylinder(gen, params, origin);
widgets_.push_back(cylinder);
auto cone = makeCone(gen, params, origin, bmax);
widgets_.push_back(cone);
setPosition(cone->position());
auto disk = makeDisk(gen, params, origin);
widgets_.push_back(disk);
//TODO: concern #1--how user interaction maps to transform type
//TODO: concern #2--how transform of "root" maps to siblings
//TODO: create cool operator syntax for wiring these up.
cylinder << propagatesEvent<WidgetMovement::TRANSLATE>::to << TheseWidgets { sphere, disk, cone };
sphere << propagatesEvent<WidgetMovement::TRANSLATE>::to << cylinder << disk << cone;
cone << propagatesEvent<WidgetMovement::ROTATE>::to << sphere << disk << cylinder;
disk << propagatesEvent<WidgetMovement::SCALE>::to << sphere << cylinder << cone;
// toy example of more complicated interactions
cylinder << propagatesEvent<WidgetMovement::AXIS_TRANSLATE>::to << sphere << disk;
cylinder << propagatesEvent<WidgetMovement::SCALE>::to << cone;
//TODO: concern #3--what data transform of "root" requires
cone->addTransformParameters<Rotation>(origin);
Vector flipVec = params.dir.getArbitraryTangent().normal();
disk->addTransformParameters<Scaling>(origin, flipVec);
}
}
bool ArrowWidget::isVector() const
{
return isVector_;
}
<|endoftext|> |
<commit_before>/*
* libjingle
* Copyright 2004--2005, Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
#if defined(_MSC_VER) && _MSC_VER < 1300
#pragma warning(disable:4786)
#endif
#include "talk/base/asynctcpsocket.h"
#include "talk/base/byteorder.h"
#include "talk/base/common.h"
#include "talk/base/logging.h"
#if defined(_MSC_VER) && _MSC_VER < 1300
namespace std {
using ::strerror;
}
#endif
#ifdef POSIX
extern "C" {
#include <errno.h>
}
#endif // POSIX
namespace talk_base {
const size_t MAX_PACKET_SIZE = 64 * 1024;
typedef uint16 PacketLength;
const size_t PKT_LEN_SIZE = sizeof(PacketLength);
const size_t BUF_SIZE = MAX_PACKET_SIZE + PKT_LEN_SIZE;
AsyncTCPSocket::AsyncTCPSocket(AsyncSocket* socket) : AsyncPacketSocket(socket), insize_(BUF_SIZE), inpos_(0), outsize_(BUF_SIZE), outpos_(0) {
inbuf_ = new char[insize_];
outbuf_ = new char[outsize_];
ASSERT(socket_ != NULL);
socket_->SignalConnectEvent.connect(this, &AsyncTCPSocket::OnConnectEvent);
socket_->SignalReadEvent.connect(this, &AsyncTCPSocket::OnReadEvent);
socket_->SignalWriteEvent.connect(this, &AsyncTCPSocket::OnWriteEvent);
socket_->SignalCloseEvent.connect(this, &AsyncTCPSocket::OnCloseEvent);
}
AsyncTCPSocket::~AsyncTCPSocket() {
delete [] inbuf_;
delete [] outbuf_;
}
int AsyncTCPSocket::Send(const void *pv, size_t cb) {
if (cb > MAX_PACKET_SIZE) {
socket_->SetError(EMSGSIZE);
return -1;
}
// If we are blocking on send, then silently drop this packet
if (outpos_)
return static_cast<int>(cb);
PacketLength pkt_len = HostToNetwork16(static_cast<PacketLength>(cb));
memcpy(outbuf_, &pkt_len, PKT_LEN_SIZE);
memcpy(outbuf_ + PKT_LEN_SIZE, pv, cb);
outpos_ = PKT_LEN_SIZE + cb;
int res = Flush();
if (res <= 0) {
// drop packet if we made no progress
outpos_ = 0;
return res;
}
// We claim to have sent the whole thing, even if we only sent partial
return static_cast<int>(cb);
}
int AsyncTCPSocket::SendTo(const void *pv, size_t cb, const SocketAddress& addr) {
if (addr == GetRemoteAddress())
return Send(pv, cb);
ASSERT(false);
socket_->SetError(ENOTCONN);
return -1;
}
int AsyncTCPSocket::SendRaw(const void * pv, size_t cb) {
if (outpos_ + cb > outsize_) {
socket_->SetError(EMSGSIZE);
return -1;
}
memcpy(outbuf_ + outpos_, pv, cb);
outpos_ += cb;
return Flush();
}
void AsyncTCPSocket::ProcessInput(char * data, size_t& len) {
SocketAddress remote_addr(GetRemoteAddress());
while (true) {
if (len < PKT_LEN_SIZE)
return;
PacketLength pkt_len;
memcpy(&pkt_len, data, PKT_LEN_SIZE);
pkt_len = NetworkToHost16(pkt_len);
if (len < PKT_LEN_SIZE + pkt_len)
return;
SignalReadPacket(data + PKT_LEN_SIZE, pkt_len, remote_addr, this);
len -= PKT_LEN_SIZE + pkt_len;
if (len > 0) {
memmove(data, data + PKT_LEN_SIZE + pkt_len, len);
}
}
}
int AsyncTCPSocket::Flush() {
int res = socket_->Send(outbuf_, outpos_);
if (res <= 0) {
return res;
}
if (static_cast<size_t>(res) <= outpos_) {
outpos_ -= res;
} else {
ASSERT(false);
return -1;
}
if (outpos_ > 0) {
memmove(outbuf_, outbuf_ + res, outpos_);
}
return res;
}
void AsyncTCPSocket::OnConnectEvent(AsyncSocket* socket) {
SignalConnect(this);
}
void AsyncTCPSocket::OnReadEvent(AsyncSocket* socket) {
ASSERT(socket == socket_);
int len = socket_->Recv(inbuf_ + inpos_, insize_ - inpos_);
if (len < 0) {
// TODO: Do something better like forwarding the error to the user.
if (!socket_->IsBlocking()) {
LOG(LS_ERROR) << "recvfrom: " << errno << " " << std::strerror(errno);
}
return;
}
inpos_ += len;
ProcessInput(inbuf_, inpos_);
if (inpos_ >= insize_) {
LOG(INFO) << "input buffer overflow";
ASSERT(false);
inpos_ = 0;
}
}
void AsyncTCPSocket::OnWriteEvent(AsyncSocket* socket) {
ASSERT(socket == socket_);
if (outpos_ > 0) {
Flush();
}
}
void AsyncTCPSocket::OnCloseEvent(AsyncSocket* socket, int error) {
SignalClose(this, error);
}
} // namespace talk_base
<commit_msg>libjingle: add missing include in asynctcpsocket.cc<commit_after>/*
* libjingle
* Copyright 2004--2005, Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
#if defined(_MSC_VER) && _MSC_VER < 1300
#pragma warning(disable:4786)
#endif
#include <cstring>
#include "talk/base/asynctcpsocket.h"
#include "talk/base/byteorder.h"
#include "talk/base/common.h"
#include "talk/base/logging.h"
#if defined(_MSC_VER) && _MSC_VER < 1300
namespace std {
using ::strerror;
}
#endif
#ifdef POSIX
extern "C" {
#include <errno.h>
}
#endif // POSIX
namespace talk_base {
const size_t MAX_PACKET_SIZE = 64 * 1024;
typedef uint16 PacketLength;
const size_t PKT_LEN_SIZE = sizeof(PacketLength);
const size_t BUF_SIZE = MAX_PACKET_SIZE + PKT_LEN_SIZE;
AsyncTCPSocket::AsyncTCPSocket(AsyncSocket* socket) : AsyncPacketSocket(socket), insize_(BUF_SIZE), inpos_(0), outsize_(BUF_SIZE), outpos_(0) {
inbuf_ = new char[insize_];
outbuf_ = new char[outsize_];
ASSERT(socket_ != NULL);
socket_->SignalConnectEvent.connect(this, &AsyncTCPSocket::OnConnectEvent);
socket_->SignalReadEvent.connect(this, &AsyncTCPSocket::OnReadEvent);
socket_->SignalWriteEvent.connect(this, &AsyncTCPSocket::OnWriteEvent);
socket_->SignalCloseEvent.connect(this, &AsyncTCPSocket::OnCloseEvent);
}
AsyncTCPSocket::~AsyncTCPSocket() {
delete [] inbuf_;
delete [] outbuf_;
}
int AsyncTCPSocket::Send(const void *pv, size_t cb) {
if (cb > MAX_PACKET_SIZE) {
socket_->SetError(EMSGSIZE);
return -1;
}
// If we are blocking on send, then silently drop this packet
if (outpos_)
return static_cast<int>(cb);
PacketLength pkt_len = HostToNetwork16(static_cast<PacketLength>(cb));
memcpy(outbuf_, &pkt_len, PKT_LEN_SIZE);
memcpy(outbuf_ + PKT_LEN_SIZE, pv, cb);
outpos_ = PKT_LEN_SIZE + cb;
int res = Flush();
if (res <= 0) {
// drop packet if we made no progress
outpos_ = 0;
return res;
}
// We claim to have sent the whole thing, even if we only sent partial
return static_cast<int>(cb);
}
int AsyncTCPSocket::SendTo(const void *pv, size_t cb, const SocketAddress& addr) {
if (addr == GetRemoteAddress())
return Send(pv, cb);
ASSERT(false);
socket_->SetError(ENOTCONN);
return -1;
}
int AsyncTCPSocket::SendRaw(const void * pv, size_t cb) {
if (outpos_ + cb > outsize_) {
socket_->SetError(EMSGSIZE);
return -1;
}
memcpy(outbuf_ + outpos_, pv, cb);
outpos_ += cb;
return Flush();
}
void AsyncTCPSocket::ProcessInput(char * data, size_t& len) {
SocketAddress remote_addr(GetRemoteAddress());
while (true) {
if (len < PKT_LEN_SIZE)
return;
PacketLength pkt_len;
memcpy(&pkt_len, data, PKT_LEN_SIZE);
pkt_len = NetworkToHost16(pkt_len);
if (len < PKT_LEN_SIZE + pkt_len)
return;
SignalReadPacket(data + PKT_LEN_SIZE, pkt_len, remote_addr, this);
len -= PKT_LEN_SIZE + pkt_len;
if (len > 0) {
memmove(data, data + PKT_LEN_SIZE + pkt_len, len);
}
}
}
int AsyncTCPSocket::Flush() {
int res = socket_->Send(outbuf_, outpos_);
if (res <= 0) {
return res;
}
if (static_cast<size_t>(res) <= outpos_) {
outpos_ -= res;
} else {
ASSERT(false);
return -1;
}
if (outpos_ > 0) {
memmove(outbuf_, outbuf_ + res, outpos_);
}
return res;
}
void AsyncTCPSocket::OnConnectEvent(AsyncSocket* socket) {
SignalConnect(this);
}
void AsyncTCPSocket::OnReadEvent(AsyncSocket* socket) {
ASSERT(socket == socket_);
int len = socket_->Recv(inbuf_ + inpos_, insize_ - inpos_);
if (len < 0) {
// TODO: Do something better like forwarding the error to the user.
if (!socket_->IsBlocking()) {
LOG(LS_ERROR) << "recvfrom: " << errno << " " << std::strerror(errno);
}
return;
}
inpos_ += len;
ProcessInput(inbuf_, inpos_);
if (inpos_ >= insize_) {
LOG(INFO) << "input buffer overflow";
ASSERT(false);
inpos_ = 0;
}
}
void AsyncTCPSocket::OnWriteEvent(AsyncSocket* socket) {
ASSERT(socket == socket_);
if (outpos_ > 0) {
Flush();
}
}
void AsyncTCPSocket::OnCloseEvent(AsyncSocket* socket, int error) {
SignalClose(this, error);
}
} // namespace talk_base
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2013-2020 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include <fstream>
#include "cpp_utils/assert.hpp"
#include "config.hpp"
#include "utils.hpp"
#include "server.hpp"
#include "api.hpp"
#include "server_lock.hpp"
namespace budget {
template<typename T>
struct data_handler {
size_t next_id; // Note: No need to protect this since this is only accessed by GC (not run from server)
data_handler(const char* module, const char* path) : module(module), path(path) {
// Nothing else to init
};
//data_handler should never be copied
data_handler(const data_handler& rhs) = delete;
data_handler& operator=(const data_handler& rhs) = delete;
bool is_changed() const {
return changed;
}
void set_changed() {
server_lock_guard l(lock);
if (is_server_running()) {
force_save();
} else {
changed = true;
}
}
template<typename Functor>
void parse_stream(std::istream& file, Functor f){
next_id = 1;
std::string line;
while (file.good() && getline(file, line)) {
if (line.empty()) {
continue;
}
auto parts = split(line, ':');
T entry;
f(parts, entry);
if (entry.id >= next_id) {
next_id = entry.id + 1;
}
data_.push_back(std::move(entry));
}
}
template<typename Functor>
void load(Functor f){
//Make sure to clear the data first, as load_data can be called
//several times
data_.clear();
if(is_server_mode()){
auto res = budget::api_get(std::string("/") + module + "/list/");
if(res.success){
std::stringstream ss(res.result);
parse_stream(ss, f);
}
} else {
auto file_path = path_to_budget_file(path);
if (!file_exists(file_path)) {
next_id = 1;
} else {
std::ifstream file(file_path);
if (file.is_open()) {
if (file.good()) {
// We do not use the next_id saved anymore
// Simply consume it
size_t fake;
file >> fake;
file.get();
parse_stream(file, f);
}
}
}
}
}
void load(){
load([](std::vector<std::string>& parts, T& entry){ parts >> entry; });
}
void force_save() {
cpp_assert(!is_server_mode(), "force_save() should never be called in server mode");
if (budget::config_contains("random")) {
std::cerr << "budget: error: Saving is disabled in random mode" << std::endl;
return;
}
auto file_path = path_to_budget_file(path);
std::ofstream file(file_path);
// We still save the file ID so that it's still compatible with older versions for now
file << next_id << std::endl;
for (auto& entry : data_) {
file << entry << std::endl;
}
changed = false;
}
void save() {
// In server mode, there is nothing to do
if (is_server_mode()) {
// It shoud not be changed
cpp_assert(!is_changed(), "in server mode, is_changed() should never be true");
return;
}
// In other modes, save if it's changed
if (is_changed()) {
force_save();
}
}
bool edit(T& value){
server_lock_guard l(lock);
if(is_server_mode()){
auto params = value.get_params();
auto res = budget::api_post(std::string("/") + get_module() + "/edit/", params);
if (!res.success) {
std::cerr << "error: Failed to edit from " << get_module() << std::endl;
return false;
} else {
return true;
}
} else {
set_changed();
return true;
}
}
bool indirect_edit(const T& value, bool propagate = true) {
server_lock_guard l(lock);
if (is_server_mode()) {
auto params = value.get_params();
auto res = budget::api_post(std::string("/") + get_module() + "/edit/", params);
if (!res.success) {
std::cerr << "error: Failed to edit from " << get_module() << std::endl;
return false;
} else {
return true;
}
} else {
for (auto& v : data_) {
if (v.id == value.id) {
v = value;
if (propagate) {
set_changed();
}
return true;
}
}
return false;
}
}
template <typename TT>
size_t add(TT&& entry) {
server_lock_guard l(lock);
if (is_server_mode()) {
auto params = entry.get_params();
auto res = budget::api_post(std::string("/") + get_module() + "/add/", params);
if (!res.success) {
std::cerr << "error: Failed to add expense" << std::endl;
entry.id = 0;
} else {
entry.id = budget::to_number<size_t>(res.result);
data_.push_back(std::forward<T>(entry));
}
} else {
entry.id = next_id++;
data_.push_back(std::forward<T>(entry));
set_changed();
}
return entry.id;
}
void remove(size_t id) {
server_lock_guard l(lock);
data_.erase(std::remove_if(data_.begin(), data_.end(),
[id](const T& entry) { return entry.id == id; }),
data_.end());
if (is_server_mode()) {
auto res = budget::api_get(std::string("/") + get_module() + "/delete/?input_id=" + budget::to_string(id));
if (!res.success) {
std::cerr << "error: Failed to delete from " << get_module() << std::endl;
}
} else {
set_changed();
}
}
bool exists(size_t id) {
server_lock_guard l(lock);
for (auto& entry : data_) {
if (entry.id == id) {
return true;
}
}
return false;
}
T& operator[](size_t id) {
server_lock_guard l(lock);
for (auto& value : data_) {
if (value.id == id) {
return value;
}
}
cpp_unreachable("The data must exists");
}
size_t size() const {
return data_.size();
}
bool empty() const {
return data_.empty();
}
const char* get_module() const {
return module;
}
std::vector<T> data() const {
std::vector<T> copy;
copy.reserve(size());
{
server_lock_guard l(lock);
std::copy(data_.begin(), data_.end(), std::back_inserter(copy));
}
return copy;
}
// This can only be accessed during loading
std::vector<T> & unsafe_data() {
return data_;
}
private:
const char* module;
const char* path;
volatile bool changed = false;
mutable server_lock lock;
std::vector<T> data_;
};
} //end of namespace budget
<commit_msg>Fix basic reentrancy<commit_after>//=======================================================================
// Copyright (c) 2013-2020 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include <fstream>
#include "cpp_utils/assert.hpp"
#include "config.hpp"
#include "utils.hpp"
#include "server.hpp"
#include "api.hpp"
#include "server_lock.hpp"
namespace budget {
template<typename T>
struct data_handler {
size_t next_id; // Note: No need to protect this since this is only accessed by GC (not run from server)
data_handler(const char* module, const char* path) : module(module), path(path) {
// Nothing else to init
};
//data_handler should never be copied
data_handler(const data_handler& rhs) = delete;
data_handler& operator=(const data_handler& rhs) = delete;
bool is_changed() const {
return changed;
}
void set_changed() {
server_lock_guard l(lock);
set_changed_internal();
}
template<typename Functor>
void parse_stream(std::istream& file, Functor f){
next_id = 1;
std::string line;
while (file.good() && getline(file, line)) {
if (line.empty()) {
continue;
}
auto parts = split(line, ':');
T entry;
f(parts, entry);
if (entry.id >= next_id) {
next_id = entry.id + 1;
}
data_.push_back(std::move(entry));
}
}
template<typename Functor>
void load(Functor f){
//Make sure to clear the data first, as load_data can be called
//several times
data_.clear();
if(is_server_mode()){
auto res = budget::api_get(std::string("/") + module + "/list/");
if(res.success){
std::stringstream ss(res.result);
parse_stream(ss, f);
}
} else {
auto file_path = path_to_budget_file(path);
if (!file_exists(file_path)) {
next_id = 1;
} else {
std::ifstream file(file_path);
if (file.is_open()) {
if (file.good()) {
// We do not use the next_id saved anymore
// Simply consume it
size_t fake;
file >> fake;
file.get();
parse_stream(file, f);
}
}
}
}
}
void load(){
load([](std::vector<std::string>& parts, T& entry){ parts >> entry; });
}
void save() {
// In server mode, there is nothing to do
if (is_server_mode()) {
// It shoud not be changed
cpp_assert(!is_changed(), "in server mode, is_changed() should never be true");
return;
}
// In other modes, save if it's changed
if (is_changed()) {
force_save();
}
}
bool edit(T& value){
server_lock_guard l(lock);
if(is_server_mode()){
auto params = value.get_params();
auto res = budget::api_post(std::string("/") + get_module() + "/edit/", params);
if (!res.success) {
std::cerr << "error: Failed to edit from " << get_module() << std::endl;
return false;
} else {
return true;
}
} else {
set_changed_internal();
return true;
}
}
bool indirect_edit(const T& value, bool propagate = true) {
server_lock_guard l(lock);
if (is_server_mode()) {
auto params = value.get_params();
auto res = budget::api_post(std::string("/") + get_module() + "/edit/", params);
if (!res.success) {
std::cerr << "error: Failed to edit from " << get_module() << std::endl;
return false;
} else {
return true;
}
} else {
for (auto& v : data_) {
if (v.id == value.id) {
v = value;
if (propagate) {
set_changed_internal();
}
return true;
}
}
return false;
}
}
template <typename TT>
size_t add(TT&& entry) {
server_lock_guard l(lock);
if (is_server_mode()) {
auto params = entry.get_params();
auto res = budget::api_post(std::string("/") + get_module() + "/add/", params);
if (!res.success) {
std::cerr << "error: Failed to add expense" << std::endl;
entry.id = 0;
} else {
entry.id = budget::to_number<size_t>(res.result);
data_.push_back(std::forward<T>(entry));
}
} else {
entry.id = next_id++;
data_.push_back(std::forward<T>(entry));
set_changed_internal();
}
return entry.id;
}
void remove(size_t id) {
server_lock_guard l(lock);
data_.erase(std::remove_if(data_.begin(), data_.end(),
[id](const T& entry) { return entry.id == id; }),
data_.end());
if (is_server_mode()) {
auto res = budget::api_get(std::string("/") + get_module() + "/delete/?input_id=" + budget::to_string(id));
if (!res.success) {
std::cerr << "error: Failed to delete from " << get_module() << std::endl;
}
} else {
set_changed_internal();
}
}
bool exists(size_t id) {
server_lock_guard l(lock);
for (auto& entry : data_) {
if (entry.id == id) {
return true;
}
}
return false;
}
T& operator[](size_t id) {
server_lock_guard l(lock);
for (auto& value : data_) {
if (value.id == id) {
return value;
}
}
cpp_unreachable("The data must exists");
}
size_t size() const {
return data_.size();
}
bool empty() const {
return data_.empty();
}
const char* get_module() const {
return module;
}
std::vector<T> data() const {
std::vector<T> copy;
copy.reserve(size());
{
server_lock_guard l(lock);
std::copy(data_.begin(), data_.end(), std::back_inserter(copy));
}
return copy;
}
// This can only be accessed during loading
std::vector<T> & unsafe_data() {
return data_;
}
private:
void set_changed_internal() {
if (is_server_running()) {
force_save();
} else {
changed = true;
}
}
void force_save() {
cpp_assert(!is_server_mode(), "force_save() should never be called in server mode");
if (budget::config_contains("random")) {
std::cerr << "budget: error: Saving is disabled in random mode" << std::endl;
return;
}
auto file_path = path_to_budget_file(path);
std::ofstream file(file_path);
// We still save the file ID so that it's still compatible with older versions for now
file << next_id << std::endl;
for (auto& entry : data_) {
file << entry << std::endl;
}
changed = false;
}
const char* module;
const char* path;
volatile bool changed = false;
mutable server_lock lock;
std::vector<T> data_;
};
} //end of namespace budget
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright (c) 2013-2020 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include <ctime>
#include "utils.hpp"
namespace budget {
using date_type = unsigned short;
class date_exception: public std::exception {
protected:
std::string _message;
public:
date_exception(const std::string& message) : _message(message){}
/*!
* Return the error message.
* \return The error message.
*/
const std::string& message() const {
return _message;
}
virtual const char* what() const throw() {
return _message.c_str();
}
};
struct day {
date_type value;
day(date_type value) : value(value) {}
operator date_type() const { return value; }
bool is_default() const {
return value == 0;
}
};
struct month {
date_type value;
month(date_type value) : value(value) {}
operator date_type() const { return value; }
month& operator=(date_type value){
this->value = value;
return *this;
}
std::string as_short_string() const {
static constexpr const char* months[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
return months[value-1];
}
std::string as_long_string() const {
static constexpr const char* months[12] = {"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
return months[value-1];
}
bool is_default() const {
return value == 0;
}
};
struct year {
date_type value;
year(date_type value) : value(value) {}
operator date_type() const { return value; }
year& operator=(date_type value){
this->value = value;
return *this;
}
bool is_default() const {
return value == 0;
}
};
struct days {
date_type value;
explicit days(date_type value) : value(value) {}
operator date_type() const { return value; }
};
struct months {
date_type value;
explicit months(date_type value) : value(value) {}
operator date_type() const { return value; }
months& operator=(date_type value){
this->value = value;
return *this;
}
};
struct years {
date_type value;
explicit years(date_type value) : value(value) {}
operator date_type() const { return value; }
};
struct date;
std::ostream& operator<<(std::ostream& stream, const month& month);
std::ostream& operator<<(std::ostream& stream, const date& date);
struct date {
date_type _year;
date_type _month;
date_type _day;
explicit date(){}
date(date_type year, date_type month, date_type day) : _year(year), _month(month), _day(day){
if(year < 1400){
throw date_exception("Year not in the valid range: " + std::to_string(year));
}
if(month == 0 || month > 12){
throw date_exception("Invalid month: " + std::to_string(month));
}
if(day == 0 || day > days_month(year, month)){
throw date_exception("Invalid day: " + std::to_string(month));
}
}
date(const date& d) : _year(d._year), _month(d._month), _day(d._day) {
//Nothing else
}
date& operator=(const date& rhs) {
if (this != &rhs) {
_year = rhs._year;
_month = rhs._month;
_day = rhs._day;
}
return *this;
}
budget::year year() const {
return _year;
}
budget::month month() const {
return _month;
}
budget::day day() const {
return _day;
}
// The number of days of this year until today
// January 1 is 1
size_t year_days() const {
size_t result = 0;
for (size_t m = 1; m < _month; ++m) {
result += days_month(_year, m);
}
result += _day;
return result;
}
// The current week number
size_t week() const {
return 1 + year_days() / 7;
}
date start_of_week() {
date r = *this;
auto w = r.week();
auto d = r.year_days();
r -= days(d - (w - 1) * 7);
return r;
}
date_type day_of_the_week() const {
static constexpr const date_type t[12] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
// Thanks to leap years, this has to be complicated!
date_type y = _year - (_month < 3);
date_type dow = (y + y / 4 - y / 100 + y / 400 + t[_month - 1] + _day) % 7;
return dow ? dow : 7;
}
static date_type days_month(date_type year, date_type month){
static constexpr const date_type month_days[12] = {31,0,31,30,31,30,31,31,30,31,30,31};
if(month == 2){
return is_leap(year) ? 29 : 28;
} else {
return month_days[month - 1];
}
}
static bool is_leap(date_type year){
return
((year % 4 == 0) && year % 100 != 0)
|| year % 400 == 0;
}
bool is_leap() const {
return is_leap(_year);
}
date end_of_month(){
return {_year, _month, days_month(_year, _month)};
}
date& operator+=(years years){
if(years >= std::numeric_limits<date_type>::max() - _year){
throw date_exception("Year too high (will overflow)");
}
_year += years;
return *this;
}
date& operator+=(months months){
// Handle the NOP addition
if(months == 0){
return *this;
}
// First add several years if necessary
if (months >= 12) {
*this += years(months.value / 12);
months = months.value % 12;
}
// Add the remaining months
_month += months;
// Update the year if necessary
if(_month > 12){
*this += years((_month - 1) / 12);
_month = (_month) % 12;
}
// Update the day of month, if necessary
_day = std::min(_day, days_month(_year, _month));
return *this;
}
date& operator+=(days d){
while(d > 0){
++_day;
if(_day > days_month(_year, _month)){
_day = 1;
++_month;
if(_month > 12){
_month = 1;
++_year;
}
}
d = days(d - 1);
}
return *this;
}
date& operator-=(years years){
if(_year < years){
throw date_exception("Year too low");
}
_year -= years;
return *this;
}
date& operator-=(months months){
// Handle the NOP subtraction
if(months == 0){
return *this;
}
// First remove several years if necessary
if (months >= 12) {
*this -= years(months.value / 12);
months = months.value % 12;
}
if(_month == months){
*this -= years(1);
_month = 12;
} else if(_month < months){
*this -= years(1);
_month = 12 - (int(months) - _month);
} else {
_month -= months;
}
_day = std::min(_day, days_month(_year, _month));
return *this;
}
date& operator-=(days d){
while(d > 0){
--_day;
if(_day == 0){
--_month;
if(_month == 0){
--_year;
_month = 12;
}
_day = days_month(_year, _month);
}
d = days(d - 1);
}
return *this;
}
date operator+(years years) const {
date d(*this);
d += years;
return d;
}
date operator+(months months) const {
date d(*this);
d += months;
return d;
}
date operator+(days days) const {
date d(*this);
d += days;
return d;
}
date operator-(years years) const {
date d(*this);
d -= years;
return d;
}
date operator-(months months) const {
date d(*this);
d -= months;
return d;
}
date operator-(days days) const {
date d(*this);
d -= days;
return d;
}
bool operator==(const date& rhs) const {
return _year == rhs._year && _month == rhs._month && _day == rhs._day;
}
bool operator!=(const date& rhs) const {
return !(*this == rhs);
}
bool operator<(const date& rhs) const {
if(_year < rhs._year){
return true;
} else if(_year == rhs._year){
if(_month < rhs._month){
return true;
} else if(_month == rhs._month){
return _day < rhs._day;
}
}
return false;
}
bool operator<=(const date& rhs) const {
return (*this == rhs) || (*this < rhs);
}
bool operator>(const date& rhs) const {
if(_year > rhs._year){
return true;
} else if(_year == rhs._year){
if(_month > rhs._month){
return true;
} else if(_month == rhs._month){
return _day > rhs._day;
}
}
return false;
}
bool operator>=(const date& rhs) const {
return (*this == rhs) || (*this > rhs);
}
date_type operator-(const date& rhs) const {
if(*this == rhs){
return 0;
}
if(rhs > *this){
return -(rhs - *this);
}
auto x = *this;
size_t d = 0;
while(x != rhs){
x -= days(1);
++d;
}
return d;
}
};
date local_day();
date from_string(std::string_view str);
std::string date_to_string(date date);
template<>
inline std::string to_string(budget::date date){
return date_to_string(date);
}
unsigned short start_year();
unsigned short start_month(budget::year year);
} //end of namespace budget
<commit_msg>Slight improvements to date struct<commit_after>//=======================================================================
// Copyright (c) 2013-2020 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
#include <ctime>
#include "utils.hpp"
namespace budget {
using date_type = unsigned short;
class date_exception: public std::exception {
protected:
std::string _message;
public:
date_exception(const std::string& message) : _message(message){}
/*!
* Return the error message.
* \return The error message.
*/
const std::string& message() const {
return _message;
}
virtual const char* what() const throw() {
return _message.c_str();
}
};
struct day {
date_type value;
day(date_type value) : value(value) {}
operator date_type() const { return value; }
bool is_default() const {
return value == 0;
}
};
struct month {
date_type value;
month(date_type value) : value(value) {}
operator date_type() const { return value; }
month& operator=(date_type value){
this->value = value;
return *this;
}
std::string as_short_string() const {
static constexpr const char* months[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
return months[value-1];
}
std::string as_long_string() const {
static constexpr const char* months[12] = {"January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"};
return months[value-1];
}
bool is_default() const {
return value == 0;
}
};
struct year {
date_type value;
year(date_type value) : value(value) {}
operator date_type() const { return value; }
year& operator=(date_type value){
this->value = value;
return *this;
}
bool is_default() const {
return value == 0;
}
};
struct days {
date_type value;
explicit days(date_type value) : value(value) {}
operator date_type() const { return value; }
};
struct months {
date_type value;
explicit months(date_type value) : value(value) {}
operator date_type() const { return value; }
months& operator=(date_type value){
this->value = value;
return *this;
}
};
struct years {
date_type value;
explicit years(date_type value) : value(value) {}
operator date_type() const { return value; }
};
struct date;
std::ostream& operator<<(std::ostream& stream, const month& month);
std::ostream& operator<<(std::ostream& stream, const date& date);
struct date {
date_type _year;
date_type _month;
date_type _day;
explicit date(){}
date(date_type year, date_type month, date_type day) : _year(year), _month(month), _day(day){
if(year < 1400){
throw date_exception("Year not in the valid range: " + std::to_string(year));
}
if(month == 0 || month > 12){
throw date_exception("Invalid month: " + std::to_string(month));
}
if(day == 0 || day > days_month(year, month)){
throw date_exception("Invalid day: " + std::to_string(day));
}
}
date(const date& d) : _year(d._year), _month(d._month), _day(d._day) {
//Nothing else
}
date& operator=(const date& rhs) {
if (this != &rhs) {
_year = rhs._year;
_month = rhs._month;
_day = rhs._day;
}
return *this;
}
budget::year year() const {
return _year;
}
budget::month month() const {
return _month;
}
budget::day day() const {
return _day;
}
// The number of days of this year until today
// January 1 is 1
size_t year_days() const {
size_t result = 0;
for (size_t m = 1; m < _month; ++m) {
result += days_month(_year, m);
}
result += _day;
return result;
}
// The current week number
size_t week() const {
return 1 + year_days() / 7;
}
date start_of_week() const {
date r = *this;
auto w = r.week();
auto d = r.year_days();
r -= days(d - (w - 1) * 7);
return r;
}
date_type day_of_the_week() const {
static constexpr const date_type t[12] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
// Thanks to leap years, this has to be complicated!
date_type y = _year - (_month < 3);
date_type dow = (y + y / 4 - y / 100 + y / 400 + t[_month - 1] + _day) % 7;
return dow ? dow : 7;
}
static date_type days_month(date_type year, date_type month){
static constexpr const date_type month_days[12] = {31,0,31,30,31,30,31,31,30,31,30,31};
if(month == 2){
return is_leap(year) ? 29 : 28;
} else {
return month_days[month - 1];
}
}
static bool is_leap(date_type year){
return
((year % 4 == 0) && year % 100 != 0)
|| year % 400 == 0;
}
bool is_leap() const {
return is_leap(_year);
}
date end_of_month(){
return {_year, _month, days_month(_year, _month)};
}
date& operator+=(years years){
if(years >= std::numeric_limits<date_type>::max() - _year){
throw date_exception("Year too high (will overflow)");
}
_year += years;
return *this;
}
date& operator+=(months months){
// Handle the NOP addition
if(months == 0){
return *this;
}
// First add several years if necessary
if (months >= 12) {
*this += years(months.value / 12);
months = months.value % 12;
}
// Add the remaining months
_month += months;
// Update the year if necessary
if(_month > 12){
*this += years((_month - 1) / 12);
_month = (_month) % 12;
}
// Update the day of month, if necessary
_day = std::min(_day, days_month(_year, _month));
return *this;
}
date& operator+=(days d){
while(d > 0){
++_day;
if(_day > days_month(_year, _month)){
_day = 1;
++_month;
if(_month > 12){
_month = 1;
++_year;
}
}
d = days(d - 1);
}
return *this;
}
date& operator-=(years years){
if(_year < years){
throw date_exception("Year too low");
}
_year -= years;
return *this;
}
date& operator-=(months months){
// Handle the NOP subtraction
if(months == 0){
return *this;
}
// First remove several years if necessary
if (months >= 12) {
*this -= years(months.value / 12);
months = months.value % 12;
}
if(_month == months){
*this -= years(1);
_month = 12;
} else if(_month < months){
*this -= years(1);
_month = 12 - (int(months) - _month);
} else {
_month -= months;
}
_day = std::min(_day, days_month(_year, _month));
return *this;
}
date& operator-=(days d){
while(d > 0){
--_day;
if(_day == 0){
--_month;
if(_month == 0){
--_year;
_month = 12;
}
_day = days_month(_year, _month);
}
d = days(d - 1);
}
return *this;
}
date operator+(years years) const {
date d(*this);
d += years;
return d;
}
date operator+(months months) const {
date d(*this);
d += months;
return d;
}
date operator+(days days) const {
date d(*this);
d += days;
return d;
}
date operator-(years years) const {
date d(*this);
d -= years;
return d;
}
date operator-(months months) const {
date d(*this);
d -= months;
return d;
}
date operator-(days days) const {
date d(*this);
d -= days;
return d;
}
bool operator==(const date& rhs) const {
return _year == rhs._year && _month == rhs._month && _day == rhs._day;
}
bool operator!=(const date& rhs) const {
return !(*this == rhs);
}
bool operator<(const date& rhs) const {
if(_year < rhs._year){
return true;
} else if(_year == rhs._year){
if(_month < rhs._month){
return true;
} else if(_month == rhs._month){
return _day < rhs._day;
}
}
return false;
}
bool operator<=(const date& rhs) const {
return (*this == rhs) || (*this < rhs);
}
bool operator>(const date& rhs) const {
if(_year > rhs._year){
return true;
} else if(_year == rhs._year){
if(_month > rhs._month){
return true;
} else if(_month == rhs._month){
return _day > rhs._day;
}
}
return false;
}
bool operator>=(const date& rhs) const {
return (*this == rhs) || (*this > rhs);
}
date_type operator-(const date& rhs) const {
if(*this == rhs){
return 0;
}
if(rhs > *this){
return -(rhs - *this);
}
auto x = *this;
size_t d = 0;
while(x != rhs){
x -= days(1);
++d;
}
return d;
}
};
date local_day();
date from_string(std::string_view str);
std::string date_to_string(date date);
template<>
inline std::string to_string(budget::date date){
return date_to_string(date);
}
unsigned short start_year();
unsigned short start_month(budget::year year);
} //end of namespace budget
<|endoftext|> |
<commit_before>//===--- SILPassPipelineDumper.cpp ----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// \file
///
/// This is a simple tool that dumps out a yaml description of one of the
/// current list of pass pipelines. Meant to be used to script on top of
/// sil-opt.
///
//===----------------------------------------------------------------------===//
#include "swift/Basic/LLVM.h"
#include "swift/Basic/LLVMInitialize.h"
#include "swift/SILOptimizer/PassManager/PassPipeline.h"
#include "llvm/Support/CommandLine.h"
using namespace swift;
static llvm::cl::opt<PassPipelineKind>
PipelineKind(llvm::cl::desc("<pipeline kind>"), llvm::cl::values(
#define PASSPIPELINE(NAME, DESCRIPTION) \
clEnumValN(PassPipelineKind::NAME, #NAME, DESCRIPTION),
#include "swift/SILOptimizer/PassManager/PassPipeline.def"
clEnumValEnd));
namespace llvm {
llvm::raw_ostream &operator<<(llvm::raw_ostream &os, PassPipelineKind Kind) {
switch (Kind) {
#define PASSPIPELINE(NAME, DESCRIPTION) \
case PassPipelineKind::NAME: \
return os << #NAME;
#include "swift/SILOptimizer/PassManager/PassPipeline.def"
}
}
}
int main(int argc, char **argv) {
INITIALIZE_LLVM(argc, argv);
llvm::cl::ParseCommandLineOptions(argc, argv,
"Swift SIL Pass Pipeline Dumper\n");
// TODO: add options to manipulate this.
SILOptions Opt;
switch (PipelineKind) {
#define PASSPIPELINE(NAME, DESCRIPTION) \
case PassPipelineKind::NAME: { \
SILPassPipelinePlan::get##NAME##PassPipeline().print(llvm::outs()); \
break; \
}
#define PASSPIPELINE_WITH_OPTIONS(NAME, DESCRIPTION) \
case PassPipelineKind::NAME: { \
SILPassPipelinePlan::get##NAME##PassPipeline(Opt).print(llvm::outs()); \
break; \
}
#include "swift/SILOptimizer/PassManager/PassPipeline.def"
}
llvm::outs() << '\n';
return 0;
};
<commit_msg>Update for clang r283671: remove use of clEnumValEnd.<commit_after>//===--- SILPassPipelineDumper.cpp ----------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
/// \file
///
/// This is a simple tool that dumps out a yaml description of one of the
/// current list of pass pipelines. Meant to be used to script on top of
/// sil-opt.
///
//===----------------------------------------------------------------------===//
#include "swift/Basic/LLVM.h"
#include "swift/Basic/LLVMInitialize.h"
#include "swift/SILOptimizer/PassManager/PassPipeline.h"
#include "llvm/Support/CommandLine.h"
using namespace swift;
static llvm::cl::opt<PassPipelineKind>
PipelineKind(llvm::cl::desc("<pipeline kind>"), llvm::cl::values(
#define PASSPIPELINE(NAME, DESCRIPTION) \
clEnumValN(PassPipelineKind::NAME, #NAME, DESCRIPTION),
#include "swift/SILOptimizer/PassManager/PassPipeline.def"
clEnumValN(0, "", "")));
namespace llvm {
llvm::raw_ostream &operator<<(llvm::raw_ostream &os, PassPipelineKind Kind) {
switch (Kind) {
#define PASSPIPELINE(NAME, DESCRIPTION) \
case PassPipelineKind::NAME: \
return os << #NAME;
#include "swift/SILOptimizer/PassManager/PassPipeline.def"
}
}
}
int main(int argc, char **argv) {
INITIALIZE_LLVM(argc, argv);
llvm::cl::ParseCommandLineOptions(argc, argv,
"Swift SIL Pass Pipeline Dumper\n");
// TODO: add options to manipulate this.
SILOptions Opt;
switch (PipelineKind) {
#define PASSPIPELINE(NAME, DESCRIPTION) \
case PassPipelineKind::NAME: { \
SILPassPipelinePlan::get##NAME##PassPipeline().print(llvm::outs()); \
break; \
}
#define PASSPIPELINE_WITH_OPTIONS(NAME, DESCRIPTION) \
case PassPipelineKind::NAME: { \
SILPassPipelinePlan::get##NAME##PassPipeline(Opt).print(llvm::outs()); \
break; \
}
#include "swift/SILOptimizer/PassManager/PassPipeline.def"
}
llvm::outs() << '\n';
return 0;
};
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/kind.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file dimm.H
/// @brief Encapsulation for dimms of all types
///
// *HWP HWP Owner: Jacob Harvey <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP
#ifndef _MSS_DIMM_H_
#define _MSS_DIMM_H_
#include <fapi2.H>
#include <lib/mss_attribute_accessors.H>
#include <generic/memory/lib/utils/c_str.H>
namespace mss
{
namespace dimm
{
///
/// @class mss::dimm::kind
/// @brief A class containing information about a dimm like ranks, density, configuration - what kind of dimm is it?
///
class kind
{
public:
///
/// @brief Generate a vector of DIMM kind from a vector of DIMM
/// @param[in] i_dimm a vector of DIMM
/// @return std::vector of dimm::kind relating to the DIMM passed in
///
static std::vector<kind> vector(const std::vector<fapi2::Target<fapi2::TARGET_TYPE_DIMM>>& i_dimm)
{
std::vector<kind> l_kinds;
for (const auto& d : i_dimm)
{
l_kinds.push_back( kind(d) );
}
return l_kinds;
}
///
/// @brief operator=() - assign kinds (needed to sort vectors of kinds)
/// @param[in] i_rhs the right hand side of the assignment statement
/// @return reference to this
///
inline kind& operator=(const kind& i_rhs)
{
iv_target = i_rhs.iv_target;
iv_master_ranks = i_rhs.iv_master_ranks;
iv_total_ranks = i_rhs.iv_total_ranks;
iv_dram_density = i_rhs.iv_dram_density;
iv_dram_width = i_rhs.iv_dram_width;
iv_dram_generation = i_rhs.iv_dram_generation;
iv_dimm_type = i_rhs.iv_dimm_type;
iv_rows = i_rhs.iv_rows;
iv_size = i_rhs.iv_size;
iv_mfgid = i_rhs.iv_mfgid;
iv_stack_type = i_rhs.iv_stack_type;
return *this;
}
///
/// @brief operator==() - are two kinds the same?
/// @param[in] i_rhs the right hand side of the comparison statement
/// @return bool true iff the two kind are of the same kind
/// @warning this does not compare the targets (iv_target,) just the values
///
inline bool operator==(const kind& i_rhs) const
{
return ((iv_master_ranks == i_rhs.iv_master_ranks) &&
(iv_total_ranks == i_rhs.iv_total_ranks) &&
(iv_dram_density == i_rhs.iv_dram_density) &&
(iv_dram_width == i_rhs.iv_dram_width) &&
(iv_dram_generation == i_rhs.iv_dram_generation) &&
(iv_dimm_type == i_rhs.iv_dimm_type) &&
(iv_rows == i_rhs.iv_rows) &&
(iv_size == i_rhs.iv_size));
}
///
/// @brief Construct a dimm::kind data structure - information about the kind of DIMM this is
/// @param[in] i_target a DIMM target
///
kind(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target):
iv_target(i_target)
{
FAPI_TRY( mss::eff_dram_gen(i_target, iv_dram_generation) );
FAPI_TRY( mss::eff_dimm_type(i_target, iv_dimm_type) );
FAPI_TRY( mss::eff_dram_density(i_target, iv_dram_density) );
FAPI_TRY( mss::eff_dram_width(i_target, iv_dram_width) );
FAPI_TRY( mss::eff_num_master_ranks_per_dimm(i_target, iv_master_ranks) );
FAPI_TRY( mss::eff_num_ranks_per_dimm(i_target, iv_total_ranks) );
FAPI_TRY( mss::eff_dram_row_bits(i_target, iv_rows) );
FAPI_TRY( mss::eff_dimm_size(i_target, iv_size) );
FAPI_TRY( mss::eff_dram_mfg_id(i_target, iv_mfgid) );
FAPI_TRY( mss::eff_prim_stack_type( i_target, iv_stack_type) );
return;
fapi_try_exit:
// Not 100% sure what to do here ...
FAPI_ERR("error initializing DIMM structure: %s 0x%016lx", mss::c_str(i_target), uint64_t(fapi2::current_err));
fapi2::Assert(false);
}
///
/// @brief Construct a DIMM kind used to identify this DIMM for tables.
/// @param[in] i_master_ranks number of master ranks on the DIMM
/// @param[in] i_total_ranks total number of ranks on the DIMM
/// @param[in] i_dram_density density of the DRAM
/// @param[in] i_dram_width width of the DRAM
/// @param[in] i_dram_generation DRAM generation
/// @param[in] i_dimm_type DIMM type (e.g. RDIMM)
/// @param[in] i_rows number of rows in the DRAM
/// @param[in] i_size the overal size of the DIMM in GB
/// @param[in] i_mfgid the dram manufacturer id of the dimm, defaulted to 0
/// @param[in] i_stack_type dram die type, single die package or 3DS
/// @note can't be constexpr as fapi2::Target doesn't have a constexpr ctor.
///
kind( const uint8_t i_master_ranks,
const uint8_t i_total_ranks,
const uint8_t i_dram_density,
const uint8_t i_dram_width,
const uint8_t i_dram_generation,
const uint8_t i_dimm_type,
const uint8_t i_rows,
const uint32_t i_size,
const uint16_t i_mfgid = 0,
const uint8_t i_stack_type = fapi2::ENUM_ATTR_EFF_PRIM_STACK_TYPE_SDP):
iv_target(0),
iv_master_ranks(i_master_ranks),
iv_total_ranks(i_total_ranks),
iv_dram_density(i_dram_density),
iv_dram_width(i_dram_width),
iv_dram_generation(i_dram_generation),
iv_dimm_type(i_dimm_type),
iv_rows(i_rows),
// TK consider calculating size rather than requiring it be set.
iv_size(i_size),
iv_mfgid(i_mfgid),
iv_stack_type(i_stack_type)
{
// Bit of an idiot-check to be sure a hand-crafted dimm::kind make sense wrt slaves, masters, packages, etc.
// Both of these are checked in eff_config. If they are messed up, they should be caught there
if (iv_master_ranks > iv_total_ranks)
{
FAPI_ERR("Not enough total ranks? master: %d total: %d",
iv_master_ranks,
iv_total_ranks);
fapi2::Assert(false);
}
if ((iv_total_ranks % iv_master_ranks) != 0)
{
FAPI_ERR("total or master ranks seems incorrect. master: %d total: %d",
iv_master_ranks,
iv_total_ranks);
fapi2::Assert(false);
}
}
fapi2::Target<fapi2::TARGET_TYPE_DIMM> iv_target;
uint8_t iv_master_ranks;
uint8_t iv_total_ranks;
uint8_t iv_dram_density;
uint8_t iv_dram_width;
uint8_t iv_dram_generation;
uint8_t iv_dimm_type;
uint8_t iv_rows;
uint32_t iv_size;
uint16_t iv_mfgid;
uint8_t iv_stack_type;
};
}
}
#endif
<commit_msg>Adds in broadcast support for memdiags<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/dimm/kind.H $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file dimm.H
/// @brief Encapsulation for dimms of all types
///
// *HWP HWP Owner: Jacob Harvey <[email protected]>
// *HWP HWP Backup: Andre Marin <[email protected]>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP
#ifndef _MSS_DIMM_H_
#define _MSS_DIMM_H_
#include <fapi2.H>
#include <lib/mss_attribute_accessors.H>
#include <generic/memory/lib/utils/c_str.H>
namespace mss
{
namespace dimm
{
///
/// @class mss::dimm::kind
/// @brief A class containing information about a dimm like ranks, density, configuration - what kind of dimm is it?
///
class kind
{
public:
///
/// @brief Generate a vector of DIMM kind from a vector of DIMM
/// @param[in] i_dimm a vector of DIMM
/// @return std::vector of dimm::kind relating to the DIMM passed in
///
static std::vector<kind> vector(const std::vector<fapi2::Target<fapi2::TARGET_TYPE_DIMM>>& i_dimm)
{
std::vector<kind> l_kinds;
for (const auto& d : i_dimm)
{
l_kinds.push_back( kind(d) );
}
return l_kinds;
}
///
/// @brief operator=() - assign kinds (needed to sort vectors of kinds)
/// @param[in] i_rhs the right hand side of the assignment statement
/// @return reference to this
///
inline kind& operator=(const kind& i_rhs)
{
iv_target = i_rhs.iv_target;
iv_master_ranks = i_rhs.iv_master_ranks;
iv_total_ranks = i_rhs.iv_total_ranks;
iv_dram_density = i_rhs.iv_dram_density;
iv_dram_width = i_rhs.iv_dram_width;
iv_dram_generation = i_rhs.iv_dram_generation;
iv_dimm_type = i_rhs.iv_dimm_type;
iv_rows = i_rhs.iv_rows;
iv_size = i_rhs.iv_size;
iv_mfgid = i_rhs.iv_mfgid;
iv_stack_type = i_rhs.iv_stack_type;
return *this;
}
///
/// @brief operator==() - are two kinds the same?
/// @param[in] i_rhs the right hand side of the comparison statement
/// @return bool true iff the two kind are of the same kind
/// @warning this does not compare the targets (iv_target,) just the values
///
inline bool operator==(const kind& i_rhs) const
{
return ((iv_master_ranks == i_rhs.iv_master_ranks) &&
(iv_total_ranks == i_rhs.iv_total_ranks) &&
(iv_dram_density == i_rhs.iv_dram_density) &&
(iv_dram_width == i_rhs.iv_dram_width) &&
(iv_dram_generation == i_rhs.iv_dram_generation) &&
(iv_dimm_type == i_rhs.iv_dimm_type) &&
(iv_rows == i_rhs.iv_rows) &&
(iv_size == i_rhs.iv_size));
}
///
/// @brief operator!=() - are two kinds different?
/// @param[in] i_rhs the right hand side of the comparison statement
/// @return bool true iff the two kind are of different
/// @warning this does not compare the targets (iv_target,) just the values
///
inline bool operator!=(const kind& i_rhs) const
{
return !(this->operator==(i_rhs));
}
///
/// @brief Construct a dimm::kind data structure - information about the kind of DIMM this is
/// @param[in] i_target a DIMM target
///
kind(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target):
iv_target(i_target)
{
FAPI_TRY( mss::eff_dram_gen(i_target, iv_dram_generation) );
FAPI_TRY( mss::eff_dimm_type(i_target, iv_dimm_type) );
FAPI_TRY( mss::eff_dram_density(i_target, iv_dram_density) );
FAPI_TRY( mss::eff_dram_width(i_target, iv_dram_width) );
FAPI_TRY( mss::eff_num_master_ranks_per_dimm(i_target, iv_master_ranks) );
FAPI_TRY( mss::eff_num_ranks_per_dimm(i_target, iv_total_ranks) );
FAPI_TRY( mss::eff_dram_row_bits(i_target, iv_rows) );
FAPI_TRY( mss::eff_dimm_size(i_target, iv_size) );
FAPI_TRY( mss::eff_dram_mfg_id(i_target, iv_mfgid) );
FAPI_TRY( mss::eff_prim_stack_type( i_target, iv_stack_type) );
return;
fapi_try_exit:
// Not 100% sure what to do here ...
FAPI_ERR("error initializing DIMM structure: %s 0x%016lx", mss::c_str(i_target), uint64_t(fapi2::current_err));
fapi2::Assert(false);
}
///
/// @brief Construct a DIMM kind used to identify this DIMM for tables.
/// @param[in] i_master_ranks number of master ranks on the DIMM
/// @param[in] i_total_ranks total number of ranks on the DIMM
/// @param[in] i_dram_density density of the DRAM
/// @param[in] i_dram_width width of the DRAM
/// @param[in] i_dram_generation DRAM generation
/// @param[in] i_dimm_type DIMM type (e.g. RDIMM)
/// @param[in] i_rows number of rows in the DRAM
/// @param[in] i_size the overal size of the DIMM in GB
/// @param[in] i_mfgid the dram manufacturer id of the dimm, defaulted to 0
/// @param[in] i_stack_type dram die type, single die package or 3DS
/// @note can't be constexpr as fapi2::Target doesn't have a constexpr ctor.
///
kind( const uint8_t i_master_ranks,
const uint8_t i_total_ranks,
const uint8_t i_dram_density,
const uint8_t i_dram_width,
const uint8_t i_dram_generation,
const uint8_t i_dimm_type,
const uint8_t i_rows,
const uint32_t i_size,
const uint16_t i_mfgid = 0,
const uint8_t i_stack_type = fapi2::ENUM_ATTR_EFF_PRIM_STACK_TYPE_SDP):
iv_target(0),
iv_master_ranks(i_master_ranks),
iv_total_ranks(i_total_ranks),
iv_dram_density(i_dram_density),
iv_dram_width(i_dram_width),
iv_dram_generation(i_dram_generation),
iv_dimm_type(i_dimm_type),
iv_rows(i_rows),
// TK consider calculating size rather than requiring it be set.
iv_size(i_size),
iv_mfgid(i_mfgid),
iv_stack_type(i_stack_type)
{
// Bit of an idiot-check to be sure a hand-crafted dimm::kind make sense wrt slaves, masters, packages, etc.
// Both of these are checked in eff_config. If they are messed up, they should be caught there
if (iv_master_ranks > iv_total_ranks)
{
FAPI_ERR("Not enough total ranks? master: %d total: %d",
iv_master_ranks,
iv_total_ranks);
fapi2::Assert(false);
}
if ((iv_total_ranks % iv_master_ranks) != 0)
{
FAPI_ERR("total or master ranks seems incorrect. master: %d total: %d",
iv_master_ranks,
iv_total_ranks);
fapi2::Assert(false);
}
}
fapi2::Target<fapi2::TARGET_TYPE_DIMM> iv_target;
uint8_t iv_master_ranks;
uint8_t iv_total_ranks;
uint8_t iv_dram_density;
uint8_t iv_dram_width;
uint8_t iv_dram_generation;
uint8_t iv_dimm_type;
uint8_t iv_rows;
uint32_t iv_size;
uint16_t iv_mfgid;
uint8_t iv_stack_type;
};
}
}
#endif
<|endoftext|> |
<commit_before>#pragma once
u64 namehash(const strbuf<DIRSIZ>&);
class dirns : public rcu_freed
{
public:
dirns() : rcu_freed("dirns"), ns_(false) {}
bool remove(const strbuf<DIRSIZ>& name, const u32* vp = nullptr) {
return ns_.remove(name, vp);
}
int insert(const strbuf<DIRSIZ>& name, const u32& inum) {
return ns_.insert(name, inum);
}
u32 lookup(const strbuf<DIRSIZ>& name) {
return ns_.lookup(name);
}
template<class CB>
void enumerate(CB cb) {
return ns_.enumerate(cb);
}
virtual void do_gc(void) {
delete this;
}
NEW_DELETE_OPS(dirns);
private:
xns<strbuf<DIRSIZ>, u32, namehash> ns_;
};
<commit_msg>A dirns class that is an array of xns instances.<commit_after>#pragma once
u64 namehash(const strbuf<DIRSIZ>&);
#define NINS 251
// Prevent potentially non-scalable bucket groupings
static_assert(NINS != NHASH, "Bad NINS choice");
class dirns : public rcu_freed
{
typedef xns<strbuf<DIRSIZ>, u32, namehash> ins;
public:
dirns() : rcu_freed("dirns") {
for (int i = 0; i < NINS; i++)
a_[i].store(nullptr);
}
~dirns() {
for (int i = 0; i < NINS; i++)
if (a_[i].load() != nullptr) {
delete a_[i].load();
a_[i].store(nullptr);
}
}
bool remove(const strbuf<DIRSIZ>& name, const u32* vp = nullptr) {
u32 i = ah(name);
if (a_[i].load() != nullptr)
return a_[i].load()->remove(name, vp);
return false;
}
int insert(const strbuf<DIRSIZ>& name, const u32& inum) {
ins* ns;
u32 i;
i = ah(name);
retry:
if (a_[i].load() == nullptr) {
ns = new ins(false);
if (!cmpxch(&a_[i], (decltype(ns)) nullptr, ns)) {
delete ns;
goto retry;
}
} else {
ns = a_[i];
}
return ns->insert(name, inum);
}
u32 lookup(const strbuf<DIRSIZ>& name) const {
ins* ns;
u32 i;
i = ah(name);
ns = a_[i].load();
if (ns != nullptr)
return ns->lookup(name);
return 0;
}
template<class CB>
void enumerate(CB cb) const {
// XXX(sbw) not the same semantics as xns::enumerate.
// This continues if cb returns true.
for (int i = 0; i < NINS; i++) {
ins* ns = a_[i].load();
if (ns != nullptr)
ns->enumerate(cb);
}
}
virtual void do_gc(void) {
delete this;
}
NEW_DELETE_OPS(dirns);
private:
std::atomic<ins*> a_[NINS];
u32 ah(const strbuf<DIRSIZ>& name) const {
u64 h = namehash(name);
return h % NINS;
}
};
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_quad_power_off.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_quad_power_off.C
/// @brief Power off the EQ including the functional cores associatated with it.
///
//----------------------------------------------------------------------------
// *HWP HWP Owner : Greg Still <[email protected]>
// *HWP FW Owner : Sumit Kumar <[email protected]>
// *HWP Team : PM
// *HWP Level : 2
// *HWP Consumed by : OCC:CME:FSP
//----------------------------------------------------------------------------
//
// @verbatim
// High-level procedure flow:
// - For each good EC associated with the targeted EQ, power it off.
// - Power off the EQ.
// @endverbatim
//
//------------------------------------------------------------------------------
// ----------------------------------------------------------------------
// Includes
// ----------------------------------------------------------------------
#include <p9_quad_power_off.H>
// ----------------------------------------------------------------------
// Function definitions
// ----------------------------------------------------------------------
// Procedure p9_quad_power_off entry point, comments in header
fapi2::ReturnCode p9_quad_power_off(
const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target)
{
fapi2::buffer<uint64_t> l_data64;
constexpr uint64_t l_rawData = 0x1100000000000000ULL; // Bit 3 & 7 are set to be manipulated
constexpr uint32_t MAX_CORE_PER_QUAD = 4;
fapi2::ReturnCode rc = fapi2::FAPI2_RC_SUCCESS;
uint32_t l_cnt = 0;
FAPI_INF("p9_quad_power_off: Entering...");
// Print chiplet position
FAPI_INF("Quad power off chiplet no.%d", i_target.getChipletNumber());
FAPI_DBG("Disabling bits 20/22/24/26 in EQ_QPPM_QPMMR_CLEAR, to gain access"
" to PFET controller, otherwise Quad Power off scom will fail");
l_data64.setBit<20>();
l_data64.setBit<22>();
l_data64.setBit<24>();
l_data64.setBit<26>();
FAPI_TRY(fapi2::putScom(i_target, EQ_QPPM_QPMMR_CLEAR, l_data64));
// QPPM_QUAD_CTRL_REG
do
{
// EX0, Enables the EDRAM charge pumps in L3 EX0, on power down they
// must be de-asserted in the opposite order 3 -> 0
// EX1, Enables the EDRAM charge pumps in L3 EX1, on power down they
// must be de-asserted in the opposite order 7 -> 4
FAPI_DBG("De-asserting EDRAM charge pumps in Ex0 & Ex1 in Sequence for "
"Reg EQ_QPPM_QCCR_SCOM1, Data Value [0x%0X%0X]",
uint32_t((l_rawData << l_cnt) >> 32), uint32_t(l_rawData << l_cnt));
FAPI_TRY(fapi2::putScom(i_target, EQ_QPPM_QCCR_SCOM1, (l_rawData << l_cnt)));
}
while(++l_cnt < MAX_CORE_PER_QUAD);
// Call the procedure
FAPI_EXEC_HWP(rc, p9_pm_pfet_control_eq, i_target,
PM_PFET_TYPE_C::BOTH, PM_PFET_TYPE_C::OFF);
FAPI_TRY(rc);
fapi_try_exit:
FAPI_INF("p9_quad_power_off: ...Exiting");
return fapi2::current_err;
}
<commit_msg>Workaround to fix issue where Powerbus loses track of EQs in DD1<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_quad_power_off.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2015,2019 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_quad_power_off.C
/// @brief Power off the EQ including the functional cores associatated with it.
///
//----------------------------------------------------------------------------
// *HWP HWP Owner : Greg Still <[email protected]>
// *HWP FW Owner : Sumit Kumar <[email protected]>
// *HWP Team : PM
// *HWP Level : 2
// *HWP Consumed by : OCC:CME:FSP
//----------------------------------------------------------------------------
//
// @verbatim
// High-level procedure flow:
// - For each good EC associated with the targeted EQ, power it off.
// - Power off the EQ.
// @endverbatim
//
//------------------------------------------------------------------------------
// ----------------------------------------------------------------------
// Includes
// ----------------------------------------------------------------------
#include <p9_quad_power_off.H>
// ----------------------------------------------------------------------
// Function definitions
// ----------------------------------------------------------------------
#ifdef __PPE__
uint64_t G_ring_save[8] = {0, 0, 0, 0, 0, 0, 0, 0};
// {0, 0},
// {5039, 0xE000000000000000}, //3
// {5100, 0xC1E061FFED5F0000}, //29
// {5664, 0xE000000000000000}, //3
// {5725, 0xC1E061FFED5F0000}, //29
// {5973, 0xE000000000000000}, //3
// {6034, 0xC1E061FFED5F0000}, //29
// {6282, 0xE000000000000000}, //3
// {6343, 0xC1E061FFED5F0000}, //29
// {17871, 0} //128
const uint64_t G_ring_index[10] =
{
0, 5039, 5100, 5664, 5725, 5973, 6034, 6282, 6343, 17871,
};
#endif
// Procedure p9_quad_power_off entry point, comments in header
fapi2::ReturnCode p9_quad_power_off(
const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target)
{
fapi2::buffer<uint64_t> l_data64;
constexpr uint64_t l_rawData = 0x1100000000000000ULL; // Bit 3 & 7 are set to be manipulated
constexpr uint32_t MAX_CORE_PER_QUAD = 4;
fapi2::ReturnCode rc = fapi2::FAPI2_RC_SUCCESS;
uint32_t l_cnt = 0;
#ifdef __PPE__
uint8_t l_isMpipl = 0;
uint8_t l_isRingSaveMpipl = 0;
const fapi2::Target<fapi2::TARGET_TYPE_SYSTEM> FAPI_SYSTEM;
fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_chip =
i_target.getParent<fapi2::TARGET_TYPE_PROC_CHIP>();
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_IS_MPIPL, FAPI_SYSTEM, l_isMpipl), "fapiGetAttribute of ATTR_IS_MPIPL failed!");
FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_RING_SAVE_MPIPL, l_chip, l_isRingSaveMpipl),
"fapiGetAttribute of ATTR_CHIP_EC_FEATURE_RING_SAVE_MPIPL failed");
#endif
FAPI_INF("p9_quad_power_off: Entering...");
// Print chiplet position
FAPI_INF("Quad power off chiplet no.%d", i_target.getChipletNumber());
#ifdef __PPE__
if (l_isMpipl && l_isRingSaveMpipl)
{
l_data64.setBit<4>(); //SCAN_REGION_PERV - scan clock region perv
l_data64.setBit<5>(); //SCAN_REGION_UNIT1 - scan clock region eqpb - pb
l_data64.setBit<11>(); //SCAN_REGION_UNIT7 - scan clock region pbieq - pb
l_data64.setBit<59>(); //SCAN_TYPE_INEX - scan chain idex (c14 asic)
FAPI_TRY(fapi2::putScom(i_target,
EQ_SCAN_REGION_TYPE,
l_data64));
l_data64.flush<0>().set(0xa5a5a5a5a5a5a5a5);
FAPI_TRY(fapi2::putScom(i_target,
EQ_SCAN64,
l_data64));
for(uint32_t l_spin = 1; l_spin < 10; l_spin++)
{
uint64_t l_scandata = ((l_spin == 0) || (l_spin == 9)) ? 0x0 : (l_spin & 0x1) ?
0xE000000000000000 : 0xC1E061FFED5F0000;
l_data64.flush<0>().set((G_ring_index[l_spin] - G_ring_index[l_spin - 1]) << 32);
FAPI_TRY(fapi2::putScom(i_target,
EQ_SCAN_LONG_ROTATE,
l_data64));
l_data64.flush<0>();
do
{
FAPI_TRY(fapi2::getScom(i_target,
EQ_CPLT_STAT0,
l_data64));
}
while (l_data64.getBit<8>() == 0);
l_data64.flush<0>();
if (l_spin == 9)
{
FAPI_TRY(fapi2::getScom(i_target,
EQ_SCAN64,
l_data64));
if(l_data64 != 0xa5a5a5a5a5a5a5a5)
{
FAPI_ASSERT(false,
fapi2::P9_PM_QUAD_POWEROFF_INCORRECT_EQ_SCAN64_VAL()
.set_EQ_SCAN64_VAL(l_data64),
"Incorrect Value from EQ_SCAN64, Expected Value [0xa5a5a5a5a5a5a5a5]");
}
}
else
{
l_data64.flush<0>();
FAPI_TRY(fapi2::getScom(i_target,
EQ_SCAN64,
l_data64));
G_ring_save[l_spin - 1] = l_scandata & l_data64;
}
}
l_data64.flush<0>();
FAPI_TRY(fapi2::putScom(i_target,
EQ_SCAN_REGION_TYPE,
l_data64));
}
#endif
FAPI_DBG("Disabling bits 20/22/24/26 in EQ_QPPM_QPMMR_CLEAR, to gain access"
" to PFET controller, otherwise Quad Power off scom will fail");
l_data64.setBit<20>();
l_data64.setBit<22>();
l_data64.setBit<24>();
l_data64.setBit<26>();
FAPI_TRY(fapi2::putScom(i_target, EQ_QPPM_QPMMR_CLEAR, l_data64));
// QPPM_QUAD_CTRL_REG
do
{
// EX0, Enables the EDRAM charge pumps in L3 EX0, on power down they
// must be de-asserted in the opposite order 3 -> 0
// EX1, Enables the EDRAM charge pumps in L3 EX1, on power down they
// must be de-asserted in the opposite order 7 -> 4
FAPI_DBG("De-asserting EDRAM charge pumps in Ex0 & Ex1 in Sequence for "
"Reg EQ_QPPM_QCCR_SCOM1, Data Value [0x%0X%0X]",
uint32_t((l_rawData << l_cnt) >> 32), uint32_t(l_rawData << l_cnt));
FAPI_TRY(fapi2::putScom(i_target, EQ_QPPM_QCCR_SCOM1, (l_rawData << l_cnt)));
}
while(++l_cnt < MAX_CORE_PER_QUAD);
// Call the procedure
FAPI_EXEC_HWP(rc, p9_pm_pfet_control_eq, i_target,
PM_PFET_TYPE_C::BOTH, PM_PFET_TYPE_C::OFF);
FAPI_TRY(rc);
fapi_try_exit:
FAPI_INF("p9_quad_power_off: ...Exiting");
return fapi2::current_err;
}
<|endoftext|> |
<commit_before>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_quad_power_off.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2017 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_quad_power_off.C
/// @brief Power off the EQ including the functional cores associatated with it.
///
//----------------------------------------------------------------------------
// *HWP HWP Owner : Greg Still <[email protected]>
// *HWP FW Owner : Sumit Kumar <[email protected]>
// *HWP Team : PM
// *HWP Level : 2
// *HWP Consumed by : OCC:CME:FSP
//----------------------------------------------------------------------------
//
// @verbatim
// High-level procedure flow:
// - For each good EC associated with the targeted EQ, power it off.
// - Power off the EQ.
// @endverbatim
//
//------------------------------------------------------------------------------
// ----------------------------------------------------------------------
// Includes
// ----------------------------------------------------------------------
#include <p9_quad_power_off.H>
// ----------------------------------------------------------------------
// Function definitions
// ----------------------------------------------------------------------
// Procedure p9_quad_power_off entry point, comments in header
fapi2::ReturnCode p9_quad_power_off(
const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target)
{
fapi2::buffer<uint64_t> l_data64;
fapi2::ReturnCode rc = fapi2::FAPI2_RC_SUCCESS;
FAPI_INF("p9_quad_power_off: Entering...");
// Print chiplet position
FAPI_INF("Quad power off chiplet no.%d", i_target.getChipletNumber());
l_data64.setBit<20>();
l_data64.setBit<22>();
l_data64.setBit<24>();
l_data64.setBit<26>();
FAPI_TRY(fapi2::putScom(i_target,
EQ_QPPM_QPMMR_CLEAR,
l_data64));
// Call the procedure
FAPI_EXEC_HWP(rc, p9_pm_pfet_control_eq, i_target,
PM_PFET_TYPE_C::BOTH, PM_PFET_TYPE_C::OFF);
FAPI_TRY(rc);
fapi_try_exit:
FAPI_INF("p9_quad_power_off: ...Exiting");
return fapi2::current_err;
}
<commit_msg>Added Scom to de-assert EDRAM Charge Pumps in Power down sequence<commit_after>/* IBM_PROLOG_BEGIN_TAG */
/* This is an automatically generated prolog. */
/* */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_quad_power_off.C $ */
/* */
/* OpenPOWER HostBoot Project */
/* */
/* Contributors Listed Below - COPYRIGHT 2016,2017 */
/* [+] International Business Machines Corp. */
/* */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */
/* implied. See the License for the specific language governing */
/* permissions and limitations under the License. */
/* */
/* IBM_PROLOG_END_TAG */
///
/// @file p9_quad_power_off.C
/// @brief Power off the EQ including the functional cores associatated with it.
///
//----------------------------------------------------------------------------
// *HWP HWP Owner : Greg Still <[email protected]>
// *HWP FW Owner : Sumit Kumar <[email protected]>
// *HWP Team : PM
// *HWP Level : 2
// *HWP Consumed by : OCC:CME:FSP
//----------------------------------------------------------------------------
//
// @verbatim
// High-level procedure flow:
// - For each good EC associated with the targeted EQ, power it off.
// - Power off the EQ.
// @endverbatim
//
//------------------------------------------------------------------------------
// ----------------------------------------------------------------------
// Includes
// ----------------------------------------------------------------------
#include <p9_quad_power_off.H>
// ----------------------------------------------------------------------
// Function definitions
// ----------------------------------------------------------------------
// Procedure p9_quad_power_off entry point, comments in header
fapi2::ReturnCode p9_quad_power_off(
const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target)
{
fapi2::buffer<uint64_t> l_data64;
constexpr uint64_t l_rawData = 0x1100000000000000ULL; // Bit 3 & 7 are set to be manipulated
constexpr uint32_t MAX_CORE_PER_QUAD = 4;
fapi2::ReturnCode rc = fapi2::FAPI2_RC_SUCCESS;
uint32_t l_cnt = 0;
FAPI_INF("p9_quad_power_off: Entering...");
// Print chiplet position
FAPI_INF("Quad power off chiplet no.%d", i_target.getChipletNumber());
FAPI_DBG("Disabling bits 20/22/24/26 in EQ_QPPM_QPMMR_CLEAR, to gain access"
" to PFET controller, otherwise Quad Power off scom will fail");
l_data64.setBit<20>();
l_data64.setBit<22>();
l_data64.setBit<24>();
l_data64.setBit<26>();
FAPI_TRY(fapi2::putScom(i_target, EQ_QPPM_QPMMR_CLEAR, l_data64));
// QPPM_QUAD_CTRL_REG
do
{
// EX0, Enables the EDRAM charge pumps in L3 EX0, on power down they
// must be de-asserted in the opposite order 3 -> 0
// EX1, Enables the EDRAM charge pumps in L3 EX1, on power down they
// must be de-asserted in the opposite order 7 -> 4
FAPI_DBG("De-asserting EDRAM charge pumps in Ex0 & Ex1 in Sequence for "
"Reg EQ_QPPM_QCCR_SCOM1, Data Value [0x%0X%0X]",
uint32_t((l_rawData << l_cnt) >> 32), uint32_t(l_rawData << l_cnt));
FAPI_TRY(fapi2::putScom(i_target, EQ_QPPM_QCCR_SCOM1, (l_rawData << l_cnt)));
}
while(++l_cnt < MAX_CORE_PER_QUAD);
// Call the procedure
FAPI_EXEC_HWP(rc, p9_pm_pfet_control_eq, i_target,
PM_PFET_TYPE_C::BOTH, PM_PFET_TYPE_C::OFF);
FAPI_TRY(rc);
fapi_try_exit:
FAPI_INF("p9_quad_power_off: ...Exiting");
return fapi2::current_err;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2011, Willow Garage, Inc.
* (c) 2013, Mike Purvis
* 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 Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <interactive_markers/interactive_marker_server.h>
#include <geometry_msgs/Twist.h>
#include <geometry_msgs/Pose.h>
#include <ros/ros.h>
#include <tf/tf.h>
#include <algorithm>
#include <string>
using visualization_msgs::InteractiveMarker;
using visualization_msgs::InteractiveMarkerControl;
using visualization_msgs::InteractiveMarkerFeedback;
class MarkerServer
{
public:
MarkerServer()
: nh("~"), server("twist_marker_server")
{
std::string cmd_vel_topic;
nh.param<std::string>("link_name", link_name, "/base_footprint");
nh.param<std::string>("robot_name", robot_name, "robot");
nh.param<double>("linear_scale", linear_drive_scale, 1.0);
nh.param<double>("angular_scale", angular_drive_scale, 2.2);
nh.param<double>("marker_size_scale", marker_size_scale, 1.0);
nh.param<double>("max_positive_linear_velocity", max_positive_linear_velocity, 0.2);
nh.param<double>("max_negative_linear_velocity", max_negative_linear_velocity, -0.2);
nh.param<double>("max_angular_velocity", max_angular_velocity, 1.0);
vel_pub = nh.advertise<geometry_msgs::Twist>("cmd_vel", 1);
createInteractiveMarkers();
ROS_INFO("[twist_marker_server] Initialized.");
}
void processFeedback(
const InteractiveMarkerFeedback::ConstPtr &feedback);
private:
void createInteractiveMarkers();
ros::NodeHandle nh;
ros::Publisher vel_pub;
interactive_markers::InteractiveMarkerServer server;
double linear_drive_scale;
double angular_drive_scale;
double max_positive_linear_velocity;
double max_negative_linear_velocity;
double max_angular_velocity;
double marker_size_scale;
std::string link_name;
std::string robot_name;
};
void MarkerServer::processFeedback(
const InteractiveMarkerFeedback::ConstPtr &feedback )
{
// Handle angular change (yaw is the only direction in which you can rotate)
double yaw = tf::getYaw(feedback->pose.orientation);
geometry_msgs::Twist vel;
vel.angular.z = angular_drive_scale * yaw;
vel.linear.x = linear_drive_scale * feedback->pose.position.x;
// Enforce parameterized speed limits
vel.linear.x = std::min(vel.linear.x, max_positive_linear_velocity);
vel.linear.x = std::max(vel.linear.x, max_negative_linear_velocity);
vel.angular.z = std::min(vel.angular.z, max_angular_velocity);
vel.angular.z = std::max(vel.angular.z, -max_angular_velocity);
vel_pub.publish(vel);
// Make the marker snap back to robot
server.setPose(robot_name + "_twist_marker", geometry_msgs::Pose());
server.applyChanges();
}
void MarkerServer::createInteractiveMarkers()
{
// create an interactive marker for our server
InteractiveMarker int_marker;
int_marker.header.frame_id = link_name;
int_marker.name = robot_name + "_twist_marker";
int_marker.description = "twist controller for " + robot_name;
int_marker.scale = marker_size_scale;
InteractiveMarkerControl control;
control.orientation_mode = InteractiveMarkerControl::FIXED;
control.orientation.w = 1;
control.orientation.x = 1;
control.orientation.y = 0;
control.orientation.z = 0;
control.name = "move_x";
control.interaction_mode = InteractiveMarkerControl::MOVE_AXIS;
int_marker.controls.push_back(control);
control.orientation.w = 1;
control.orientation.x = 0;
control.orientation.y = 1;
control.orientation.z = 0;
control.name = "rotate_z";
control.interaction_mode = InteractiveMarkerControl::ROTATE_AXIS;
int_marker.controls.push_back(control);
// Commented out for non-holonomic robot. If holonomic, can move in y.
/*control.orientation.w = 1;
control.orientation.x = 0;
control.orientation.y = 0;
control.orientation.z = 1;
control.name = "move_y";
control.interaction_mode = InteractiveMarkerControl::MOVE_AXIS;
int_marker.controls.push_back(control);*/
server.insert(int_marker, boost::bind(&MarkerServer::processFeedback, this, _1));
server.applyChanges();
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "marker_server");
MarkerServer server;
ros::spin();
}
<commit_msg>Update marker_server.cpp<commit_after>/*
* Copyright (c) 2011, Willow Garage, Inc.
* (c) 2013, Mike Purvis
* 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 Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <interactive_markers/interactive_marker_server.h>
#include <geometry_msgs/Twist.h>
#include <geometry_msgs/Pose.h>
#include <ros/ros.h>
#include <tf/tf.h>
#include <algorithm>
#include <string>
using visualization_msgs::InteractiveMarker;
using visualization_msgs::InteractiveMarkerControl;
using visualization_msgs::InteractiveMarkerFeedback;
class MarkerServer
{
public:
MarkerServer()
: nh("~"), server("twist_marker_server")
{
std::string cmd_vel_topic;
nh.param<std::string>("link_name", link_name, "/base_footprint");
nh.param<std::string>("robot_name", robot_name, "robot");
nh.param<double>("linear_scale", linear_drive_scale, 1.0);
nh.param<double>("angular_scale", angular_drive_scale, 2.2);
nh.param<double>("marker_size_scale", marker_size_scale, 1.0);
nh.param<double>("max_positive_linear_velocity", max_positive_linear_velocity, 0.2);
nh.param<double>("max_negative_linear_velocity", max_negative_linear_velocity, -0.2);
nh.param<double>("max_angular_velocity", max_angular_velocity, 1.0);
vel_pub = nh.advertise<geometry_msgs::Twist>("cmd_vel", 1);
createInteractiveMarkers();
ROS_INFO("[twist_marker_server] Initialized.");
}
void processFeedback(
const InteractiveMarkerFeedback::ConstPtr &feedback);
private:
void createInteractiveMarkers();
ros::NodeHandle nh;
ros::Publisher vel_pub;
interactive_markers::InteractiveMarkerServer server;
double linear_drive_scale;
double angular_drive_scale;
double max_positive_linear_velocity;
double max_negative_linear_velocity;
double max_angular_velocity;
double marker_size_scale;
std::string link_name;
std::string robot_name;
};
void MarkerServer::processFeedback(
const InteractiveMarkerFeedback::ConstPtr &feedback )
{
// Handle angular change (yaw is the only direction in which you can rotate)
double yaw = tf::getYaw(feedback->pose.orientation);
geometry_msgs::Twist vel;
vel.angular.z = angular_drive_scale * yaw;
vel.linear.x = linear_drive_scale * feedback->pose.position.x;
// Enforce parameterized speed limits
vel.linear.x = std::min(vel.linear.x, max_positive_linear_velocity);
vel.linear.x = std::max(vel.linear.x, max_negative_linear_velocity);
vel.angular.z = std::min(vel.angular.z, max_angular_velocity);
vel.angular.z = std::max(vel.angular.z, -max_angular_velocity);
vel_pub.publish(vel);
// Make the marker snap back to robot
server.setPose(robot_name + "_twist_marker", geometry_msgs::Pose());
server.applyChanges();
}
void MarkerServer::createInteractiveMarkers()
{
// create an interactive marker for our server
InteractiveMarker int_marker;
int_marker.header.frame_id = link_name;
int_marker.name = robot_name + "_twist_marker";
int_marker.description = "twist controller for " + robot_name;
int_marker.scale = marker_size_scale;
InteractiveMarkerControl control;
control.orientation_mode = InteractiveMarkerControl::FIXED;
control.orientation.w = 1;
control.orientation.x = 1;
control.orientation.y = 0;
control.orientation.z = 0;
control.name = "move_x";
control.interaction_mode = InteractiveMarkerControl::MOVE_AXIS;
int_marker.controls.push_back(control);
control.orientation.w = 1;
control.orientation.x = 0;
control.orientation.y = 1;
control.orientation.z = 0;
control.name = "rotate_z";
control.interaction_mode = InteractiveMarkerControl::ROTATE_AXIS;
//control.interaction_mode = InteractiveMarkerControl::MOVE_ROTATE;
int_marker.controls.push_back(control);
// Commented out for non-holonomic robot. If holonomic, can move in y.
/*control.orientation.w = 1;
control.orientation.x = 0;
control.orientation.y = 0;
control.orientation.z = 1;
control.name = "move_y";
control.interaction_mode = InteractiveMarkerControl::MOVE_AXIS;
int_marker.controls.push_back(control);*/
server.insert(int_marker, boost::bind(&MarkerServer::processFeedback, this, _1));
server.applyChanges();
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "marker_server");
MarkerServer server;
ros::spin();
}
<|endoftext|> |
<commit_before>#pragma once
#include "kernel.hh"
#include "refcache.hh"
#include "chainhash.hh"
#include "radix_array.hh"
#include "page_info.hh"
#include "kalloc.hh"
#include "fs.h"
#include <limits.h>
class mdir;
class mfile;
class mdev;
class msock;
class mnode : public refcache::weak_referenced
{
private:
struct inumber {
u64 v_;
static const int type_bits = 4;
static const int cpu_bits = 8;
inumber(u64 v) : v_(v) {}
inumber(u8 type, u64 cpu, u64 count)
: v_(type | (cpu << type_bits) | (count << (type_bits + cpu_bits)))
{
assert(type < (1 << type_bits));
assert(cpu < (1 << cpu_bits));
}
u8 type() {
return v_ & ((1 << type_bits) - 1);
}
};
public:
struct types {
enum {
dir = 1,
file,
dev,
sock,
};
};
static sref<mnode> get(u64 n);
static sref<mnode> alloc(u8 type);
void cache_pin(bool flag);
u8 type() const { return inumber(inum_).type(); }
mdir* as_dir();
const mdir* as_dir() const;
mfile* as_file();
const mfile* as_file() const;
mdev* as_dev();
const mdev* as_dev() const;
msock* as_sock();
const msock* as_sock() const;
class linkcount : public FS_NLINK_REFCOUNT referenced {
public:
linkcount() : referenced(0) {};
void onzero() override;
};
const u64 inum_;
linkcount nlink_;
protected:
mnode(u64 inum);
private:
void onzero() override;
std::atomic<bool> cache_pin_;
std::atomic<bool> dirty_;
std::atomic<bool> valid_;
};
/*
* An mlinkref represents a link count reference on an mnode.
* The caller must ensure that mlinkref::acquire() is not called
* after mnode::nlink_ reaches stable zero, perhaps by blocking
* refcache epochs using cli when looking up the inode number in
* a directory.
*
* Each mlinkref holds a reference to the mnode as well, to ensure
* that the memory used to store the nlink_ count is not evicted
* before all of the refcache deltas are flushed. Otherwise this
* would just be an sref<linkcount>.
*/
class mlinkref {
public:
mlinkref() {}
mlinkref(sref<mnode> mref) : m_(mref) {}
sref<mnode> mn() {
return m_;
}
bool held() {
return !!l_;
}
/*
* Increment the link count on the mnode.
*/
void acquire() {
assert(m_ && !l_);
l_ = sref<mnode::linkcount>::newref(&m_->nlink_);
}
/*
* Transfer an existing link count on the mnode to this mlinkref.
*/
void transfer() {
assert(m_ && !l_);
l_ = sref<mnode::linkcount>::transfer(&m_->nlink_);
}
private:
/*
* The order is important due to C++ constructor/destructor
* rules: we must hold the mnode reference while manipulating
* the linkcount reference.
*/
sref<mnode> m_;
sref<mnode::linkcount> l_;
};
class mdir : public mnode {
private:
mdir(u64 inum) : mnode(inum), map_(257) {}
NEW_DELETE_OPS(mdir);
friend sref<mnode> mnode::get(u64);
chainhash<strbuf<DIRSIZ>, u64> map_;
public:
bool insert(const strbuf<DIRSIZ>& name, mlinkref* ilink) {
if (name == ".")
return false;
if (!map_.insert(name, ilink->mn()->inum_))
return false;
assert(ilink->held());
ilink->mn()->nlink_.inc();
return true;
}
bool remove(const strbuf<DIRSIZ>& name, sref<mnode> m) {
if (!map_.remove(name, m->inum_))
return false;
m->nlink_.dec();
return true;
}
bool replace(const strbuf<DIRSIZ>& name, sref<mnode> mold, mlinkref* ilinknew) {
if (mold->inum_ == ilinknew->mn()->inum_)
return true;
if (!map_.replace(name, mold->inum_, ilinknew->mn()->inum_))
return false;
assert(ilinknew->held());
ilinknew->mn()->nlink_.inc();
mold->nlink_.dec();
return true;
}
bool exists(const strbuf<DIRSIZ>& name) const {
if (name == ".")
return true;
return map_.lookup(name);
}
sref<mnode> lookup(const strbuf<DIRSIZ>& name) const {
if (name == ".")
return mnode::get(inum_);
u64 iprev = -1;
for (;;) {
u64 inum;
if (!map_.lookup(name, &inum))
return sref<mnode>();
sref<mnode> m = mnode::get(inum);
if (m)
return m;
/*
* The inode was GCed between the lookup and mnode::get().
* Retry the lookup. Crash if we repeatedly can't find
* the same inode (to make such bugs easier to track down).
*/
assert(inum != iprev);
iprev = inum;
}
}
mlinkref lookup_link(const strbuf<DIRSIZ>& name) const {
if (name == ".")
/*
* We cannot convert the name "." to a link count on the mnode,
* because "." does not hold a link count of its own.
*/
return mlinkref();
for (;;) {
sref<mnode> m = lookup(name);
if (!m)
return mlinkref();
scoped_cli cli;
/*
* Retry the lookup, now that we have an sref<mnode>, since
* we don't want to do lookup's mnode::get() under cli.
*/
u64 inum;
if (!map_.lookup(name, &inum) || inum != m->inum_)
/*
* The name has either been unlinked or changed to point
* to another inode. Retry.
*/
continue;
mlinkref ilink(m);
/*
* At this point, we know the inode had a non-zero link
* count prior to the second lookup. Since we are holding
* cli, refcache cannot advance its epoch, and will not
* garbage-collect the inode until after we release cli.
*
* Mild POSIX violation: an inode can appear to have a
* zero link count, according to fstat, but get a positive
* link counter later, because the fstat occurs after the
* last name has been unlinked, but before we increment
* the link count here.
*/
ilink.acquire();
/*
* Mild POSIX violation: an inode can appear to have a
* link count, according to fstat, that is higher than
* the number of all its names. For instance, sys_link()
* first grabs a mlinkref on the existing name, and then
* drops it if the new name already exists.
*/
return ilink;
}
}
bool enumerate(const strbuf<DIRSIZ>* prev, strbuf<DIRSIZ>* name) const {
if (!prev) {
*name = ".";
return true;
}
if (*prev == ".")
prev = nullptr;
return map_.enumerate(prev, name);
}
bool kill(sref<mnode> parent) {
if (!map_.remove_and_kill("..", parent->inum_))
return false;
parent->nlink_.dec();
return true;
}
bool killed() const {
return map_.killed();
}
};
inline mdir*
mnode::as_dir()
{
assert(type() == types::dir);
return static_cast<mdir*>(this);
}
inline const mdir*
mnode::as_dir() const
{
assert(type() == types::dir);
return static_cast<const mdir*>(this);
}
class mfile : public mnode {
private:
mfile(u64 inum) : mnode(inum), size_(0) {}
NEW_DELETE_OPS(mfile);
friend sref<mnode> mnode::get(u64);
struct page_state {
enum {
FLAG_LOCK_BIT = 0,
FLAG_LOCK = 1 << FLAG_LOCK_BIT,
FLAG_SET = 1 << 1,
};
page_state() : flags(0) {}
page_state(sref<page_info> p) : flags(FLAG_SET), pg(p) {}
bool is_set() const {
return flags & FLAG_SET;
}
bit_spinlock get_lock() {
return bit_spinlock(&flags, FLAG_LOCK_BIT);
}
u64 flags;
sref<page_info> pg;
};
enum { maxidx = ULONG_MAX / PGSIZE + 1 };
radix_array<page_state, maxidx, PGSIZE,
kalloc_allocator<page_state>> pages_;
spinlock resize_lock_;
seqcount<u32> size_seq_;
u64 size_;
public:
class resizer : public lock_guard<spinlock>,
public seq_writer {
private:
resizer(mfile* mf) : lock_guard<spinlock>(&mf->resize_lock_),
seq_writer(&mf->size_seq_),
mf_(mf) {}
mfile* mf_;
friend class mfile;
public:
resizer() : mf_(nullptr) {}
explicit operator bool () const { return !!mf_; }
u64 read_size() { return mf_->size_; }
void resize_nogrow(u64 size);
void resize_append(u64 size, sref<page_info> pi);
};
resizer write_size() {
return resizer(this);
}
seq_reader<u64> read_size() {
return seq_reader<u64>(&size_, &size_seq_);
}
sref<page_info> get_page(u64 pageidx);
};
inline mfile*
mnode::as_file()
{
assert(type() == types::file);
return static_cast<mfile*>(this);
}
inline const mfile*
mnode::as_file() const
{
assert(type() == types::file);
return static_cast<const mfile*>(this);
}
class mdev : public mnode {
private:
mdev(u64 inum) : mnode(inum), major_(0), minor_(0) {}
NEW_DELETE_OPS(mdev);
friend sref<mnode> mnode::get(u64);
u16 major_;
u16 minor_;
public:
u16 major() const { return major_; }
u16 minor() const { return minor_; }
void init(u16 major, u16 minor) {
assert(!major_ && !minor_);
major_ = major;
minor_ = minor;
}
};
inline mdev*
mnode::as_dev()
{
assert(type() == types::dev);
return static_cast<mdev*>(this);
}
inline const mdev*
mnode::as_dev() const
{
assert(type() == types::dev);
return static_cast<const mdev*>(this);
}
class msock : public mnode {
private:
msock(u64 inum) : mnode(inum), localsock_(nullptr) {}
NEW_DELETE_OPS(msock);
friend sref<mnode> mnode::get(u64);
localsock* localsock_;
public:
localsock* get_sock() const { return localsock_; }
void init(localsock* ls) {
assert(!localsock_);
localsock_ = ls;
}
};
inline msock*
mnode::as_sock()
{
assert(type() == types::sock);
return static_cast<msock*>(this);
}
inline const msock*
mnode::as_sock() const
{
assert(type() == types::sock);
return static_cast<const msock*>(this);
}
<commit_msg>a more x86-instruction-friendly inode number scheme<commit_after>#pragma once
#include "kernel.hh"
#include "refcache.hh"
#include "chainhash.hh"
#include "radix_array.hh"
#include "page_info.hh"
#include "kalloc.hh"
#include "fs.h"
#include <limits.h>
class mdir;
class mfile;
class mdev;
class msock;
class mnode : public refcache::weak_referenced
{
private:
struct inumber {
u64 v_;
static const int type_bits = 8;
static const int cpu_bits = 8;
inumber(u64 v) : v_(v) {}
inumber(u8 type, u64 cpu, u64 count)
: v_(type | (cpu << type_bits) | (count << (type_bits + cpu_bits)))
{
assert(type < (1 << type_bits));
assert(cpu < (1 << cpu_bits));
}
u8 type() {
return v_ & ((1 << type_bits) - 1);
}
};
public:
struct types {
enum {
dir = 1,
file,
dev,
sock,
};
};
static sref<mnode> get(u64 n);
static sref<mnode> alloc(u8 type);
void cache_pin(bool flag);
u8 type() const { return inumber(inum_).type(); }
mdir* as_dir();
const mdir* as_dir() const;
mfile* as_file();
const mfile* as_file() const;
mdev* as_dev();
const mdev* as_dev() const;
msock* as_sock();
const msock* as_sock() const;
class linkcount : public FS_NLINK_REFCOUNT referenced {
public:
linkcount() : referenced(0) {};
void onzero() override;
};
const u64 inum_;
linkcount nlink_;
protected:
mnode(u64 inum);
private:
void onzero() override;
std::atomic<bool> cache_pin_;
std::atomic<bool> dirty_;
std::atomic<bool> valid_;
};
/*
* An mlinkref represents a link count reference on an mnode.
* The caller must ensure that mlinkref::acquire() is not called
* after mnode::nlink_ reaches stable zero, perhaps by blocking
* refcache epochs using cli when looking up the inode number in
* a directory.
*
* Each mlinkref holds a reference to the mnode as well, to ensure
* that the memory used to store the nlink_ count is not evicted
* before all of the refcache deltas are flushed. Otherwise this
* would just be an sref<linkcount>.
*/
class mlinkref {
public:
mlinkref() {}
mlinkref(sref<mnode> mref) : m_(mref) {}
sref<mnode> mn() {
return m_;
}
bool held() {
return !!l_;
}
/*
* Increment the link count on the mnode.
*/
void acquire() {
assert(m_ && !l_);
l_ = sref<mnode::linkcount>::newref(&m_->nlink_);
}
/*
* Transfer an existing link count on the mnode to this mlinkref.
*/
void transfer() {
assert(m_ && !l_);
l_ = sref<mnode::linkcount>::transfer(&m_->nlink_);
}
private:
/*
* The order is important due to C++ constructor/destructor
* rules: we must hold the mnode reference while manipulating
* the linkcount reference.
*/
sref<mnode> m_;
sref<mnode::linkcount> l_;
};
class mdir : public mnode {
private:
mdir(u64 inum) : mnode(inum), map_(257) {}
NEW_DELETE_OPS(mdir);
friend sref<mnode> mnode::get(u64);
chainhash<strbuf<DIRSIZ>, u64> map_;
public:
bool insert(const strbuf<DIRSIZ>& name, mlinkref* ilink) {
if (name == ".")
return false;
if (!map_.insert(name, ilink->mn()->inum_))
return false;
assert(ilink->held());
ilink->mn()->nlink_.inc();
return true;
}
bool remove(const strbuf<DIRSIZ>& name, sref<mnode> m) {
if (!map_.remove(name, m->inum_))
return false;
m->nlink_.dec();
return true;
}
bool replace(const strbuf<DIRSIZ>& name, sref<mnode> mold, mlinkref* ilinknew) {
if (mold->inum_ == ilinknew->mn()->inum_)
return true;
if (!map_.replace(name, mold->inum_, ilinknew->mn()->inum_))
return false;
assert(ilinknew->held());
ilinknew->mn()->nlink_.inc();
mold->nlink_.dec();
return true;
}
bool exists(const strbuf<DIRSIZ>& name) const {
if (name == ".")
return true;
return map_.lookup(name);
}
sref<mnode> lookup(const strbuf<DIRSIZ>& name) const {
if (name == ".")
return mnode::get(inum_);
u64 iprev = -1;
for (;;) {
u64 inum;
if (!map_.lookup(name, &inum))
return sref<mnode>();
sref<mnode> m = mnode::get(inum);
if (m)
return m;
/*
* The inode was GCed between the lookup and mnode::get().
* Retry the lookup. Crash if we repeatedly can't find
* the same inode (to make such bugs easier to track down).
*/
assert(inum != iprev);
iprev = inum;
}
}
mlinkref lookup_link(const strbuf<DIRSIZ>& name) const {
if (name == ".")
/*
* We cannot convert the name "." to a link count on the mnode,
* because "." does not hold a link count of its own.
*/
return mlinkref();
for (;;) {
sref<mnode> m = lookup(name);
if (!m)
return mlinkref();
scoped_cli cli;
/*
* Retry the lookup, now that we have an sref<mnode>, since
* we don't want to do lookup's mnode::get() under cli.
*/
u64 inum;
if (!map_.lookup(name, &inum) || inum != m->inum_)
/*
* The name has either been unlinked or changed to point
* to another inode. Retry.
*/
continue;
mlinkref ilink(m);
/*
* At this point, we know the inode had a non-zero link
* count prior to the second lookup. Since we are holding
* cli, refcache cannot advance its epoch, and will not
* garbage-collect the inode until after we release cli.
*
* Mild POSIX violation: an inode can appear to have a
* zero link count, according to fstat, but get a positive
* link counter later, because the fstat occurs after the
* last name has been unlinked, but before we increment
* the link count here.
*/
ilink.acquire();
/*
* Mild POSIX violation: an inode can appear to have a
* link count, according to fstat, that is higher than
* the number of all its names. For instance, sys_link()
* first grabs a mlinkref on the existing name, and then
* drops it if the new name already exists.
*/
return ilink;
}
}
bool enumerate(const strbuf<DIRSIZ>* prev, strbuf<DIRSIZ>* name) const {
if (!prev) {
*name = ".";
return true;
}
if (*prev == ".")
prev = nullptr;
return map_.enumerate(prev, name);
}
bool kill(sref<mnode> parent) {
if (!map_.remove_and_kill("..", parent->inum_))
return false;
parent->nlink_.dec();
return true;
}
bool killed() const {
return map_.killed();
}
};
inline mdir*
mnode::as_dir()
{
assert(type() == types::dir);
return static_cast<mdir*>(this);
}
inline const mdir*
mnode::as_dir() const
{
assert(type() == types::dir);
return static_cast<const mdir*>(this);
}
class mfile : public mnode {
private:
mfile(u64 inum) : mnode(inum), size_(0) {}
NEW_DELETE_OPS(mfile);
friend sref<mnode> mnode::get(u64);
struct page_state {
enum {
FLAG_LOCK_BIT = 0,
FLAG_LOCK = 1 << FLAG_LOCK_BIT,
FLAG_SET = 1 << 1,
};
page_state() : flags(0) {}
page_state(sref<page_info> p) : flags(FLAG_SET), pg(p) {}
bool is_set() const {
return flags & FLAG_SET;
}
bit_spinlock get_lock() {
return bit_spinlock(&flags, FLAG_LOCK_BIT);
}
u64 flags;
sref<page_info> pg;
};
enum { maxidx = ULONG_MAX / PGSIZE + 1 };
radix_array<page_state, maxidx, PGSIZE,
kalloc_allocator<page_state>> pages_;
spinlock resize_lock_;
seqcount<u32> size_seq_;
u64 size_;
public:
class resizer : public lock_guard<spinlock>,
public seq_writer {
private:
resizer(mfile* mf) : lock_guard<spinlock>(&mf->resize_lock_),
seq_writer(&mf->size_seq_),
mf_(mf) {}
mfile* mf_;
friend class mfile;
public:
resizer() : mf_(nullptr) {}
explicit operator bool () const { return !!mf_; }
u64 read_size() { return mf_->size_; }
void resize_nogrow(u64 size);
void resize_append(u64 size, sref<page_info> pi);
};
resizer write_size() {
return resizer(this);
}
seq_reader<u64> read_size() {
return seq_reader<u64>(&size_, &size_seq_);
}
sref<page_info> get_page(u64 pageidx);
};
inline mfile*
mnode::as_file()
{
assert(type() == types::file);
return static_cast<mfile*>(this);
}
inline const mfile*
mnode::as_file() const
{
assert(type() == types::file);
return static_cast<const mfile*>(this);
}
class mdev : public mnode {
private:
mdev(u64 inum) : mnode(inum), major_(0), minor_(0) {}
NEW_DELETE_OPS(mdev);
friend sref<mnode> mnode::get(u64);
u16 major_;
u16 minor_;
public:
u16 major() const { return major_; }
u16 minor() const { return minor_; }
void init(u16 major, u16 minor) {
assert(!major_ && !minor_);
major_ = major;
minor_ = minor;
}
};
inline mdev*
mnode::as_dev()
{
assert(type() == types::dev);
return static_cast<mdev*>(this);
}
inline const mdev*
mnode::as_dev() const
{
assert(type() == types::dev);
return static_cast<const mdev*>(this);
}
class msock : public mnode {
private:
msock(u64 inum) : mnode(inum), localsock_(nullptr) {}
NEW_DELETE_OPS(msock);
friend sref<mnode> mnode::get(u64);
localsock* localsock_;
public:
localsock* get_sock() const { return localsock_; }
void init(localsock* ls) {
assert(!localsock_);
localsock_ = ls;
}
};
inline msock*
mnode::as_sock()
{
assert(type() == types::sock);
return static_cast<msock*>(this);
}
inline const msock*
mnode::as_sock() const
{
assert(type() == types::sock);
return static_cast<const msock*>(this);
}
<|endoftext|> |
<commit_before>#pragma once
#include "util.hpp"
#include "math.hpp"
#include "asset.hpp"
#include "plugin.hpp"
#include "engine.hpp"
#include "gui.hpp"
#include "app.hpp"
#include "componentlibrary.hpp"
namespace rack {
////////////////////
// helpers
////////////////////
template <class TModuleWidget, typename... Tags>
Model *createModel(std::string manufacturer, std::string slug, std::string name, Tags... tags) {
struct TModel : Model {
ModuleWidget *createModuleWidget() override {
ModuleWidget *moduleWidget = new TModuleWidget();
moduleWidget->model = this;
return moduleWidget;
}
};
Model *model = new TModel();
model->manufacturer = manufacturer;
model->slug = slug;
model->name = name;
model->tags = {tags...};
return model;
}
template <class TScrew>
Widget *createScrew(Vec pos) {
Widget *screw = new TScrew();
screw->box.pos = pos;
return screw;
}
template <class TParamWidget>
ParamWidget *createParam(Vec pos, Module *module, int paramId, float minValue, float maxValue, float defaultValue) {
ParamWidget *param = new TParamWidget();
param->box.pos = pos;
param->module = module;
param->paramId = paramId;
param->setLimits(minValue, maxValue);
param->setDefaultValue(defaultValue);
return param;
}
template <class TPort>
Port *createInput(Vec pos, Module *module, int inputId) {
Port *port = new TPort();
port->box.pos = pos;
port->module = module;
port->type = Port::INPUT;
port->portId = inputId;
return port;
}
template <class TPort>
Port *createOutput(Vec pos, Module *module, int outputId) {
Port *port = new TPort();
port->box.pos = pos;
port->module = module;
port->type = Port::OUTPUT;
port->portId = outputId;
return port;
}
template<class TModuleLightWidget>
ModuleLightWidget *createLight(Vec pos, Module *module, int firstLightId) {
ModuleLightWidget *light = new TModuleLightWidget();
light->box.pos = pos;
light->module = module;
light->firstLightId = firstLightId;
return light;
}
} // namespace rack
<commit_msg>Return specialized type in rack.hpp helper functions<commit_after>#pragma once
#include "util.hpp"
#include "math.hpp"
#include "asset.hpp"
#include "plugin.hpp"
#include "engine.hpp"
#include "gui.hpp"
#include "app.hpp"
#include "componentlibrary.hpp"
namespace rack {
////////////////////
// helpers
////////////////////
template <class TModuleWidget, typename... Tags>
Model *createModel(std::string manufacturer, std::string slug, std::string name, Tags... tags) {
struct TModel : Model {
ModuleWidget *createModuleWidget() override {
ModuleWidget *moduleWidget = new TModuleWidget();
moduleWidget->model = this;
return moduleWidget;
}
};
Model *model = new TModel();
model->manufacturer = manufacturer;
model->slug = slug;
model->name = name;
model->tags = {tags...};
return model;
}
template <class TScrew>
TScrew *createScrew(Vec pos) {
TScrew *screw = new TScrew();
screw->box.pos = pos;
return screw;
}
template <class TParamWidget>
TParamWidget *createParam(Vec pos, Module *module, int paramId, float minValue, float maxValue, float defaultValue) {
TParamWidget *param = new TParamWidget();
param->box.pos = pos;
param->module = module;
param->paramId = paramId;
param->setLimits(minValue, maxValue);
param->setDefaultValue(defaultValue);
return param;
}
template <class TPort>
TPort *createInput(Vec pos, Module *module, int inputId) {
TPort *port = new TPort();
port->box.pos = pos;
port->module = module;
port->type = Port::INPUT;
port->portId = inputId;
return port;
}
template <class TPort>
TPort *createOutput(Vec pos, Module *module, int outputId) {
TPort *port = new TPort();
port->box.pos = pos;
port->module = module;
port->type = Port::OUTPUT;
port->portId = outputId;
return port;
}
template<class TModuleLightWidget>
TModuleLightWidget *createLight(Vec pos, Module *module, int firstLightId) {
TModuleLightWidget *light = new TModuleLightWidget();
light->box.pos = pos;
light->module = module;
light->firstLightId = firstLightId;
return light;
}
} // namespace rack
<|endoftext|> |
<commit_before>#ifndef UTIL_HPP
#define UTIL_HPP
#include <functional>
#ifndef FWD
#define FWD(X,Y) std::forward<X>(Y)
#endif
#ifndef SELF
#define SELF(Y) std::forward<decltype(Y)>(Y)
#endif
namespace Util { // --> util/types.hpp
/// A type representing no type
struct undef_t {};
/// A type delimiting a type pack
struct delim_t {};
/*! A type that allows a binary template to be infixed
* @tparam C The binary template type
* @tparam A The left hand side, used as the first template argument
* @tparam B The right hand side, used as the second template argument
*/
template<template<class... TN> class C,
class A = undef_t, class B = undef_t>
struct infix_t;
/*! A type used to find the static dimension of a type
* @tparam T A statically-sized type
*/
template<class T> struct sized_t;
/*! Reduces a variadic list of types to the sum of their sizes
* @tparam T1 The head of the argument types
* @tparam TN The remainder of the template arguments
*/
template<class T1, class... TN> struct sizes_t;
/*! Assigns each instance a unique sequential ID
* @tparam T The type of the instances to count
*/
template<typename T> struct counted_t;
/*! A tag type storing types with duplicates
* @tparam T The unordered list of types
*/
template<class... T> struct pack_t;
/*! A tag type storing integers with duplicates
* @tparam I The unordered list of integers
*/
template<int... I> struct pack_i;
/*! A tag type storing types without duplicates
* @tparam T The unordered list of unique types
*/
template<class... T> struct set_t;
/*! A tag representing a node in a graph
* @tparam T The type corresponding to the node
*/
template<class T> struct node_t;
/*! A tag representing an edge between two nodes in a graph
* @tparam U The ID of the source of the edge, or both
* @tparam V The ID of the destination of the edge, or both
*/
template<int U, int V> struct edge_t;
/*! A tag representing a graph
* @tparam V The pack of types containing the vertex endpoints
* @tparam E The pack of integer pairs containing the endpoint indices
*/
template<class V, class E, bool BIDI=false> struct graph_t;
/*! A type used to select a member of a type pack
* @tparam T The pack of types
* @tparam I The index into the pack
*/
template<class T, int I> struct pack_get_t;
/*! A structure that merges two type packs without introducing
* duplicates; does not prevent duplicates in general
* @tparam U The left operand, an unordered pack of types
* @tparam V The right operand, an unordered pack of types
*/
template<typename U, typename V> struct pack_merge;
/*! A structure that removes the types in one pack from another
* @tparam U The subtrahend pack of types
* @tparam V The minuend pack of types
* @tparam W The partial difference of the preceding packs
*/
template<typename U, typename V, typename W> struct pack_remove;
}
#include "util/types.hpp"
namespace Util { // --> util/functional.hpp
/*! A tag representing the signature of a function
* @tparam S A function or function object type
*/
template<class S>
struct sig_t;
/*! A type exposing an application function over a permutation
* of elements of array types
* @tparam SEQ The unique ID of the permutation
* @tparam CUR The index into the permutation
* @tparam TN The unordered list of array types
*/
template<int SEQ, int CUR, class... TN>
struct for_seq_t;
/*! A type exposing an application function over all permutations
* of elements of array types
* @tparam SEQ The unique ID of the current permutation
* @tparam FN The type of the function or function object to apply
* @tparam TN The unordered list of array types
*/
template<int SEQ, class FN, class... TN>
struct for_all_t;
/*! Maps each array to another type before applying a function to
* each permutation of the resulting elements.
* @tparam SEQ The unique ID of the current sequence
* @tparam FN The function to apply to each permutation
* @tparam T1 The head of the array types
* @tparam TN The remainder of the array types
*/
template<int SEQ, class FN, class T1, class... TN>
struct map_for_all_t;
/*! Applies a function to parallel sets of elements of the given
* statically-sized arrays
* @tparam SEQ The unique ID of the current sequence
* @tparam FN The function to apply to each selected permutation
* @tparam N The size of each array type
* @tparam T1 The head of the list of array types
* @tparam TN The remainder of the array types
*/
template<int SEQ, int N, class FN, class T1, class... TN>
struct for_zip_t;
}
#include "util/functional.hpp"
template<typename... S>
void zipper(std::function<void(S...)> fn) {}
template<typename S1, typename... SN, typename T1, typename... TN,
template<typename> class FN = std::function>
void zipper(FN<void(S1, SN...)> fn,
S1 && s1, SN &&... sn,
T1 && t1, TN &&... tn) {
fn(SELF(s1), SELF(sn)...);
zipper(fn, SELF(t1), SELF(tn)...);
}
template<typename FN, int N, typename T1, typename... TN>
void for_zip(FN fn, T1 (&t1)[N], TN (&...tn)[N]) {
using namespace Util;
for_zip_t<N, N, FN, T1, TN...>::apply(fn,
FWD(T1(&)[N],t1), FWD(TN(&)[N],tn)...);
}
template<typename T1, typename... TN>
constexpr int SizeProduct(void) {
return Util::sizes_t<T1, TN..., Util::delim_t>::SIZE;
}
template<typename T1, typename... TN>
constexpr int SizeProduct(T1 && t1, TN &&... tn) {
return SizeProduct<T1, TN...>();
}
/**! Applies fn to one element (SEQ) of the cartesian product of
* the argument arrays. */
template<int SEQ, typename FN, typename T1, typename... TN>
void for_seq(FN fn, T1 && t1, TN &&... tn) {
using namespace Util;
for_seq_t<SEQ, 1 + sizeof...(TN), FN, T1, TN...>
::apply(fn, FWD(T1,t1), FWD(TN,tn)...);
}
/**! Applies fn to each element of the cartesian product of the
* argument arrays. */
template<typename FN, typename T1, typename... TN,
int N = Util::sizes_t<T1, TN..., Util::delim_t>::SIZE>
void for_all(FN fn, T1 && t1, TN &&... tn) {
using namespace Util;
for_all_t<N, FN, T1, TN...>::apply(fn,
FWD(T1,t1), FWD(TN,tn)...);
}
template<typename FN0, typename FN1, typename... FN, typename T1,
typename... TN, int N = Util::sizes_t<T1, TN..., Util::delim_t>::SIZE>
void for_all(FN0 fn0, FN1 fn1, FN... fn, T1 && t1, TN &&... tn) {
for_all(fn0, SELF(t1), SELF(tn)...);
for_all(SELF(fn1), SELF(fn)..., SELF(t1), SELF(tn)...);
}
/** Applies fn to each element of the cartesian product of the
* argument arrays and stores the results sequentially in out. */
template<typename FN, typename T1, typename... TN,
typename RET = typename Util::sig_t<FN>::result_type,
int N = Util::sizes_t<T1, TN..., Util::delim_t>()>
auto map_for_all(FN fn, RET (&out)[N],
T1 && t1, TN &&... tn) -> decltype(out) {
using namespace Util;
map_for_all_t<N, FN, T1, TN...>::apply(fn,
FWD(RET (&)[N],out), FWD(T1,t1), FWD(TN,tn)...);
return FWD(RET (&)[N],out);
}
namespace Util {
namespace Test {
static bool run(void) {
using namespace Util;
// Base types
typedef pack_t<> T_void;
typedef pack_t<int> T_I;
typedef pack_t<float> T_F;
typedef pack_t<double> T_D;
typedef pack_t<int, float> T_IF;
typedef pack_t<int, float, double> T_IFD;
typedef pack_t<float, double, int> T_FDI;
T_void V0;
T_I VI; T_F VF; T_D VD;
T_IF VIF; T_IFD VIFD;
// Types with duplicates
typedef pack_t<int, int> T_II;
typedef pack_t<float, double, float> T_FDF;
// Union types
typedef typename pack_merge<T_IFD, T_void>::type T_u0;
typedef typename pack_merge<T_void, T_IFD>::type T_u1;
typedef typename pack_merge<T_I, T_FDF>::type T_u2;
static_assert(std::is_same<T_u0, T_IFD>::value, "");
static_assert(std::is_same<T_u1, T_IFD>::value, "");
static_assert(std::is_same<T_u2, T_IFD>::value, "");
// Index of first matching type (or -1)
static_assert(index_of(T_void {}, int {}) < 0, "");
static_assert(index_of(T_I {}, int {}) >= 0, "");
// Index of first matching type (or -1) for each type
static_assert(std::is_same<decltype(
indices_of(VIFD, VD + VI + pack_t<char>{})),
pack_i<2, 0, -1>>::value, "");
// Prune duplicates
static_assert(std::is_same<decltype(prune(VIFD)),
T_IFD>::value, "");
static_assert(std::is_same<decltype(prune(T_FDF {})),
decltype(VF+VD)>::value, "");
// Or
static_assert(std::is_same<decltype(VI+VF+VD),
T_IFD>::value, "");
static_assert(!std::is_same<decltype(VD+VF+VI),
T_IFD>::value, "");
// Not
static_assert(std::is_same<decltype(VIF-VF),
T_I>::value, "");
static_assert(std::is_same<decltype(VIF-VF-VI),
T_void>::value, "");
// Xor
static_assert(std::is_same<decltype(VI^VI),
decltype(VI-VI)>::value, "");
static_assert(std::is_same<decltype(VI^VF),
decltype(VI+VF)>::value, "");
// And
static_assert(std::is_same<decltype(VI & VI),
T_I>::value, "");
static_assert(std::is_same<decltype(VIF & VI),
T_I>::value, "");
// Permutations
static_assert(!std::is_same<decltype(VI+VF),
decltype(VF+VI)>::value, "");
static_assert(permutes(VI+VF, VF+VI), "");
static_assert(!permutes(VI+VF, VI), "");
// Infix operators/types/etc.
infix_t<pack_t> pack_with;
infix_t<pack_merge> merge_with;
infix_t<std::is_same> same_as;
auto packed1 = 1 <pack_with> 2;
static_assert(!inner_value(packed1 <same_as> VI), "");
static_assert(inner_value(prune(packed1) <same_as> VI), "");
auto packed2 = 3 <pack_with> 4.0f;
static_assert(inner_value(packed2 <same_as> VIF), "");
static_assert(inner_value(rotate(T_IFD{}) <same_as> T_FDI{}), "");
graph_t<T_void, T_void> G_void;
typedef decltype(G_void + node_t<T_void>{}
+ node_t<T_I>{} + node_t<T_F>{}) G_verts;
typedef decltype(G_verts {} + edge_t<0,1>{}) G_e01;
static_assert(!contains(G_verts::edges{}, edge_t<0, 1>{}), "");
static_assert(contains(G_e01::edges{}, edge_t<0, 1>{}), "");
static_assert(!contains(G_e01::edges{}, edge_t<1, 2>{}), "");
return true;
}
}
}
#endif
<commit_msg>Added inclusion for task<commit_after>#ifndef UTIL_HPP
#define UTIL_HPP
#include <functional>
#ifndef FWD
#define FWD(X,Y) std::forward<X>(Y)
#endif
#ifndef SELF
#define SELF(Y) std::forward<decltype(Y)>(Y)
#endif
namespace Util { // --> util/types.hpp
/// A type representing no type
struct undef_t {};
/// A type delimiting a type pack
struct delim_t {};
/*! A type that allows a binary template to be infixed
* @tparam C The binary template type
* @tparam A The left hand side, used as the first template argument
* @tparam B The right hand side, used as the second template argument
*/
template<template<class... TN> class C,
class A = undef_t, class B = undef_t>
struct infix_t;
/*! A type used to find the static dimension of a type
* @tparam T A statically-sized type
*/
template<class T> struct sized_t;
/*! Reduces a variadic list of types to the sum of their sizes
* @tparam T1 The head of the argument types
* @tparam TN The remainder of the template arguments
*/
template<class T1, class... TN> struct sizes_t;
/*! Assigns each instance a unique sequential ID
* @tparam T The type of the instances to count
*/
template<typename T> struct counted_t;
/*! A tag type storing types with duplicates
* @tparam T The unordered list of types
*/
template<class... T> struct pack_t;
/*! A tag type storing integers with duplicates
* @tparam I The unordered list of integers
*/
template<int... I> struct pack_i;
/*! A tag type storing types without duplicates
* @tparam T The unordered list of unique types
*/
template<class... T> struct set_t;
/*! A tag representing a node in a graph
* @tparam T The type corresponding to the node
*/
template<class T> struct node_t;
/*! A tag representing an edge between two nodes in a graph
* @tparam U The ID of the source of the edge, or both
* @tparam V The ID of the destination of the edge, or both
*/
template<int U, int V> struct edge_t;
/*! A tag representing a graph
* @tparam V The pack of types containing the vertex endpoints
* @tparam E The pack of integer pairs containing the endpoint indices
*/
template<class V, class E, bool BIDI=false> struct graph_t;
/*! A type used to select a member of a type pack
* @tparam T The pack of types
* @tparam I The index into the pack
*/
template<class T, int I> struct pack_get_t;
/*! A structure that merges two type packs without introducing
* duplicates; does not prevent duplicates in general
* @tparam U The left operand, an unordered pack of types
* @tparam V The right operand, an unordered pack of types
*/
template<typename U, typename V> struct pack_merge;
/*! A structure that removes the types in one pack from another
* @tparam U The subtrahend pack of types
* @tparam V The minuend pack of types
* @tparam W The partial difference of the preceding packs
*/
template<typename U, typename V, typename W> struct pack_remove;
}
#include "util/types.hpp"
namespace Util { // --> util/functional.hpp
/*! A tag representing the signature of a function
* @tparam S A function or function object type
*/
template<class S>
struct sig_t;
/*! A type exposing an application function over a permutation
* of elements of array types
* @tparam SEQ The unique ID of the permutation
* @tparam CUR The index into the permutation
* @tparam TN The unordered list of array types
*/
template<int SEQ, int CUR, class... TN>
struct for_seq_t;
/*! A type exposing an application function over all permutations
* of elements of array types
* @tparam SEQ The unique ID of the current permutation
* @tparam FN The type of the function or function object to apply
* @tparam TN The unordered list of array types
*/
template<int SEQ, class FN, class... TN>
struct for_all_t;
/*! Maps each array to another type before applying a function to
* each permutation of the resulting elements.
* @tparam SEQ The unique ID of the current sequence
* @tparam FN The function to apply to each permutation
* @tparam T1 The head of the array types
* @tparam TN The remainder of the array types
*/
template<int SEQ, class FN, class T1, class... TN>
struct map_for_all_t;
/*! Applies a function to parallel sets of elements of the given
* statically-sized arrays
* @tparam SEQ The unique ID of the current sequence
* @tparam FN The function to apply to each selected permutation
* @tparam N The size of each array type
* @tparam T1 The head of the list of array types
* @tparam TN The remainder of the array types
*/
template<int SEQ, int N, class FN, class T1, class... TN>
struct for_zip_t;
}
#include "util/functional.hpp"
#include "util/task.hpp"
template<typename... S>
void zipper(std::function<void(S...)> fn) {}
template<typename S1, typename... SN, typename T1, typename... TN,
template<typename> class FN = std::function>
void zipper(FN<void(S1, SN...)> fn,
S1 && s1, SN &&... sn,
T1 && t1, TN &&... tn) {
fn(SELF(s1), SELF(sn)...);
zipper(fn, SELF(t1), SELF(tn)...);
}
template<typename FN, int N, typename T1, typename... TN>
void for_zip(FN fn, T1 (&t1)[N], TN (&...tn)[N]) {
using namespace Util;
for_zip_t<N, N, FN, T1, TN...>::apply(fn,
FWD(T1(&)[N],t1), FWD(TN(&)[N],tn)...);
}
template<typename T1, typename... TN>
constexpr int SizeProduct(void) {
return Util::sizes_t<T1, TN..., Util::delim_t>::SIZE;
}
template<typename T1, typename... TN>
constexpr int SizeProduct(T1 && t1, TN &&... tn) {
return SizeProduct<T1, TN...>();
}
/**! Applies fn to one element (SEQ) of the cartesian product of
* the argument arrays. */
template<int SEQ, typename FN, typename T1, typename... TN>
void for_seq(FN fn, T1 && t1, TN &&... tn) {
using namespace Util;
for_seq_t<SEQ, 1 + sizeof...(TN), FN, T1, TN...>
::apply(fn, FWD(T1,t1), FWD(TN,tn)...);
}
/**! Applies fn to each element of the cartesian product of the
* argument arrays. */
template<typename FN, typename T1, typename... TN,
int N = Util::sizes_t<T1, TN..., Util::delim_t>::SIZE>
void for_all(FN fn, T1 && t1, TN &&... tn) {
using namespace Util;
for_all_t<N, FN, T1, TN...>::apply(fn,
FWD(T1,t1), FWD(TN,tn)...);
}
template<typename FN0, typename FN1, typename... FN, typename T1,
typename... TN, int N = Util::sizes_t<T1, TN..., Util::delim_t>::SIZE>
void for_all(FN0 fn0, FN1 fn1, FN... fn, T1 && t1, TN &&... tn) {
for_all(fn0, SELF(t1), SELF(tn)...);
for_all(SELF(fn1), SELF(fn)..., SELF(t1), SELF(tn)...);
}
/** Applies fn to each element of the cartesian product of the
* argument arrays and stores the results sequentially in out. */
template<typename FN, typename T1, typename... TN,
typename RET = typename Util::sig_t<FN>::result_type,
int N = Util::sizes_t<T1, TN..., Util::delim_t>()>
auto map_for_all(FN fn, RET (&out)[N],
T1 && t1, TN &&... tn) -> decltype(out) {
using namespace Util;
map_for_all_t<N, FN, T1, TN...>::apply(fn,
FWD(RET (&)[N],out), FWD(T1,t1), FWD(TN,tn)...);
return FWD(RET (&)[N],out);
}
namespace Util {
namespace Test {
static bool run(void) {
using namespace Util;
// Base types
typedef pack_t<> T_void;
typedef pack_t<int> T_I;
typedef pack_t<float> T_F;
typedef pack_t<double> T_D;
typedef pack_t<int, float> T_IF;
typedef pack_t<int, float, double> T_IFD;
typedef pack_t<float, double, int> T_FDI;
T_void V0;
T_I VI; T_F VF; T_D VD;
T_IF VIF; T_IFD VIFD;
// Types with duplicates
typedef pack_t<int, int> T_II;
typedef pack_t<float, double, float> T_FDF;
// Union types
typedef typename pack_merge<T_IFD, T_void>::type T_u0;
typedef typename pack_merge<T_void, T_IFD>::type T_u1;
typedef typename pack_merge<T_I, T_FDF>::type T_u2;
static_assert(std::is_same<T_u0, T_IFD>::value, "");
static_assert(std::is_same<T_u1, T_IFD>::value, "");
static_assert(std::is_same<T_u2, T_IFD>::value, "");
// Index of first matching type (or -1)
static_assert(index_of(T_void {}, int {}) < 0, "");
static_assert(index_of(T_I {}, int {}) >= 0, "");
// Index of first matching type (or -1) for each type
static_assert(std::is_same<decltype(
indices_of(VIFD, VD + VI + pack_t<char>{})),
pack_i<2, 0, -1>>::value, "");
// Prune duplicates
static_assert(std::is_same<decltype(prune(VIFD)),
T_IFD>::value, "");
static_assert(std::is_same<decltype(prune(T_FDF {})),
decltype(VF+VD)>::value, "");
// Or
static_assert(std::is_same<decltype(VI+VF+VD),
T_IFD>::value, "");
static_assert(!std::is_same<decltype(VD+VF+VI),
T_IFD>::value, "");
// Not
static_assert(std::is_same<decltype(VIF-VF),
T_I>::value, "");
static_assert(std::is_same<decltype(VIF-VF-VI),
T_void>::value, "");
// Xor
static_assert(std::is_same<decltype(VI^VI),
decltype(VI-VI)>::value, "");
static_assert(std::is_same<decltype(VI^VF),
decltype(VI+VF)>::value, "");
// And
static_assert(std::is_same<decltype(VI & VI),
T_I>::value, "");
static_assert(std::is_same<decltype(VIF & VI),
T_I>::value, "");
// Permutations
static_assert(!std::is_same<decltype(VI+VF),
decltype(VF+VI)>::value, "");
static_assert(permutes(VI+VF, VF+VI), "");
static_assert(!permutes(VI+VF, VI), "");
// Infix operators/types/etc.
infix_t<pack_t> pack_with;
infix_t<pack_merge> merge_with;
infix_t<std::is_same> same_as;
auto packed1 = 1 <pack_with> 2;
static_assert(!inner_value(packed1 <same_as> VI), "");
static_assert(inner_value(prune(packed1) <same_as> VI), "");
auto packed2 = 3 <pack_with> 4.0f;
static_assert(inner_value(packed2 <same_as> VIF), "");
static_assert(inner_value(rotate(T_IFD{}) <same_as> T_FDI{}), "");
graph_t<T_void, T_void> G_void;
typedef decltype(G_void + node_t<T_void>{}
+ node_t<T_I>{} + node_t<T_F>{}) G_verts;
typedef decltype(G_verts {} + edge_t<0,1>{}) G_e01;
static_assert(!contains(G_verts::edges{}, edge_t<0, 1>{}), "");
static_assert(contains(G_e01::edges{}, edge_t<0, 1>{}), "");
static_assert(!contains(G_e01::edges{}, edge_t<1, 2>{}), "");
return true;
}
}
}
#endif
<|endoftext|> |
<commit_before>/**
* \file
*
* \brief Interactive merge strategy asking for user input at each step
*
* \copyright BSD License (see doc/COPYING or http://www.libelektra.org)
*
*/
#ifndef INTERACTIVEMERGESTRATEGY_HPP_
#define INTERACTIVEMERGESTRATEGY_HPP_
#include <merging/mergeconflictstrategy.hpp>
using namespace std;
namespace kdb
{
namespace tools
{
namespace merging
{
class InteractiveMergeStrategy : public MergeConflictStrategy
{
public:
InteractiveMergeStrategy(istream& _inputStream, ostream& _outputStream) :
inputStream (_inputStream), outputStream (_outputStream)
{
}
virtual void resolveConflict(const MergeTask& task, Key& conflictKey, MergeResult& result);
private:
istream& inputStream;
ostream& outputStream;
};
}
}
}
#endif /* INTERACTIVEMERGESTRATEGY_HPP_ */
<commit_msg>fix include guards, using, style<commit_after>/**
* \file
*
* \brief Interactive merge strategy asking for user input at each step
*
* \copyright BSD License (see doc/COPYING or http://www.libelektra.org)
*
*/
#ifndef ELEKTRA_LIBTOOL_INTERACTIVEMERGESTRATEGY_HPP
#define ELEKTRA_LIBTOOL_INTERACTIVEMERGESTRATEGY_HPP
#include <merging/mergeconflictstrategy.hpp>
namespace kdb
{
namespace tools
{
namespace merging
{
class InteractiveMergeStrategy : public MergeConflictStrategy
{
public:
InteractiveMergeStrategy(std::istream & input,
std::ostream & output) :
inputStream (input),
outputStream (output)
{
}
virtual void resolveConflict(const MergeTask& task, Key& conflictKey, MergeResult& result);
private:
std::istream& inputStream;
std::ostream& outputStream;
};
}
}
}
#endif
<|endoftext|> |
<commit_before>#include "Offense.hpp"
using namespace std;
using namespace Geometry2d;
Gameplay::Plays::Offense::Offense(GameplayModule *gameplay):
Play(gameplay, 1),
_fullback1(gameplay),
_fullback2(gameplay),
_kicker1(gameplay),
_kicker2(gameplay)
{
}
bool Gameplay::Plays::Offense::applicable()
{
bool refApplicable =_gameplay->state()->gameState.playing();
bool gameplayApplicable = _gameplay->state()->stateID.posession == Packet::LogFrame::OFFENSE ||
_gameplay->state()->stateID.posession == Packet::LogFrame::FREEBALL;
return refApplicable && gameplayApplicable;
}
bool Gameplay::Plays::Offense::assign(set<Robot *> &available)
{
_robots = available;
_kicker1.assign(available);
_kicker2.assign(available);
_fullback1.assign(available);
_fullback2.assign(available);
Point ballPos = ball().pos;
// handle sides for fullbacks
if (_fullback1.assigned() && _fullback2.assigned())
{
if (_fullback1.robot()->pos().x < _fullback2.robot()->pos().x) {
_fullback1.side(Behaviors::Fullback::Left);
_fullback2.side(Behaviors::Fullback::Right);
} else {
_fullback1.side(Behaviors::Fullback::Right);
_fullback2.side(Behaviors::Fullback::Left);
}
// handle sides for fullbacks
if (_fullback1.robot()->pos().x < _fullback2.robot()->pos().x) {
_fullback1.side(Behaviors::Fullback::Left);
_fullback2.side(Behaviors::Fullback::Right);
} else {
_fullback1.side(Behaviors::Fullback::Right);
_fullback2.side(Behaviors::Fullback::Left);
}
}
if (_kicker1.assigned() && _kicker2.assigned())
{
// set which robot is the kicker first
_usingKicker1 = _kicker1.robot()->pos().distTo(ballPos) < _kicker2.robot()->pos().distTo(ballPos);
} else {
_usingKicker1 = true;
}
return _robots.size() >= _minRobots;
}
bool Gameplay::Plays::Offense::run()
{
// handle forward behavior
// basic approach: closest robot gets the ball, the other robot goes to the other side of the field
Point ballPos = ball().pos;
if (_kicker1.assigned() && _kicker2.assigned())
{
float kick1Dist, kick2Dist;
Point ballPos = ball().pos;
Robot * other;
kick1Dist = _kicker1.robot()->pos().distTo(ballPos);
kick2Dist = _kicker2.robot()->pos().distTo(ballPos);
// handle toggle cases
if (kick1Dist < kick2Dist) {
if (!_usingKicker1) {
_kicker1.restart();
}
_kicker1.run();
other = _kicker2.robot();
_usingKicker1 = true;
} else {
if (_usingKicker1) {
_kicker2.restart();
}
_kicker2.run();
other = _kicker1.robot();
_usingKicker1 = false;
}
// drive to other side of the field
float lag_y_dist = 0.5, x_offset = 1.5;
float newX = (ballPos.x < 0.0) ? ballPos.x + x_offset : ballPos.x - x_offset;
other->move(Point(newX, ballPos.y - lag_y_dist), false);
} else {
_kicker1.run(); // NOTE: this might not be correct
_kicker2.run();
}
// run standard fullback behavior
_fullback1.run();
_fullback2.run();
return true;
}
<commit_msg>Added hystersis to Offense<commit_after>#include "Offense.hpp"
using namespace std;
using namespace Geometry2d;
Gameplay::Plays::Offense::Offense(GameplayModule *gameplay):
Play(gameplay, 1),
_fullback1(gameplay),
_fullback2(gameplay),
_kicker1(gameplay),
_kicker2(gameplay)
{
}
bool Gameplay::Plays::Offense::applicable()
{
bool refApplicable =_gameplay->state()->gameState.playing();
bool gameplayApplicable = _gameplay->state()->stateID.posession == Packet::LogFrame::OFFENSE ||
_gameplay->state()->stateID.posession == Packet::LogFrame::FREEBALL;
return refApplicable && gameplayApplicable;
}
bool Gameplay::Plays::Offense::assign(set<Robot *> &available)
{
_robots = available;
_kicker1.assign(available);
_kicker2.assign(available);
_fullback1.assign(available);
_fullback2.assign(available);
Point ballPos = ball().pos;
// handle sides for fullbacks
if (_fullback1.assigned() && _fullback2.assigned())
{
if (_fullback1.robot()->pos().x < _fullback2.robot()->pos().x) {
_fullback1.side(Behaviors::Fullback::Left);
_fullback2.side(Behaviors::Fullback::Right);
} else {
_fullback1.side(Behaviors::Fullback::Right);
_fullback2.side(Behaviors::Fullback::Left);
}
// handle sides for fullbacks
if (_fullback1.robot()->pos().x < _fullback2.robot()->pos().x) {
_fullback1.side(Behaviors::Fullback::Left);
_fullback2.side(Behaviors::Fullback::Right);
} else {
_fullback1.side(Behaviors::Fullback::Right);
_fullback2.side(Behaviors::Fullback::Left);
}
}
if (_kicker1.assigned() && _kicker2.assigned())
{
// set which robot is the kicker first
_usingKicker1 = _kicker1.robot()->pos().distTo(ballPos) < _kicker2.robot()->pos().distTo(ballPos);
} else {
_usingKicker1 = true;
}
return _robots.size() >= _minRobots;
}
bool Gameplay::Plays::Offense::run()
{
// handle forward behavior
// basic approach: closest robot gets the ball, the other robot goes to the other side of the field
Point ballPos = ball().pos;
if (_kicker1.assigned() && _kicker2.assigned())
{
float kick1Dist, kick2Dist;
Point ballPos = ball().pos;
Robot * other;
kick1Dist = _kicker1.robot()->pos().distTo(ballPos);
kick2Dist = _kicker2.robot()->pos().distTo(ballPos);
// handle toggle cases
float percent = 0.85;
if (kick1Dist < percent * kick2Dist) {
if (!_usingKicker1) {
_kicker1.restart();
}
_kicker1.run();
other = _kicker2.robot();
_usingKicker1 = true;
} else if (kick2Dist < percent * kick1Dist) {
if (_usingKicker1) {
_kicker2.restart();
}
_kicker2.run();
other = _kicker1.robot();
_usingKicker1 = false;
} else if (_usingKicker1) {
_kicker1.run();
other = _kicker2.robot();
} else {
_kicker2.run();
other = _kicker1.robot();
}
// drive to other side of the field
float lag_y_dist = 0.5, x_offset = 1.5;
float newX = (ballPos.x < 0.0) ? ballPos.x + x_offset : ballPos.x - x_offset;
other->move(Point(newX, ballPos.y - lag_y_dist), false);
} else {
_kicker1.run();
_kicker2.run();
}
// run standard fullback behavior
_fullback1.run();
_fullback2.run();
return true;
}
<|endoftext|> |
<commit_before>#include <sirius.h>
using namespace sirius;
mdarray<int, 1> f1()
{
mdarray<int, 1> aa;
aa = mdarray<int, 1>(4);
for (int i = 0; i < 4; i++) aa(i) = 200 + i;
return aa;
}
void f2()
{
mdarray<int, 1> a1(4);
for (int i = 0; i < 4; i++) a1(i) = 100 + i;
mdarray<int, 1> a2 = f1();
for (int i = 0; i < 4; i++)
{
std::cout << "a1(" << i << ")=" << a1(i) << std::endl;
std::cout << "a2(" << i << ")=" << a2(i) << std::endl;
}
mdarray<int, 1> a3(std::move(a2));
//==
//== // a1.deallocate();
//== //
//== // std::cout << "Deallocate a1" << std::endl;
//== //
//== // for (int i = 0; i < 4; i++)
//== // {
//== // std::cout << "a2(" << i << ")=" << a2(i) << std::endl;
//== // }
//== //
//== //
//== // mdarray<int, 1> a3 = a2;
//== //
for (int i = 0; i < 4; i++)
{
std::cout << "a3(" << i << ")=" << a3(i) << std::endl;
}
mdarray<int, 1> a4;
a4 = std::move(a3);
a4 = mdarray<int, 1>(20);
#ifndef NDEBUG
std::cout << "Allocated memory : " << mdarray_mem_count::allocated().load() << std::endl;
#endif
}
void f3()
{
for (int i = 0; i < 100; i++) {
#pragma omp parallel
{
int tid = omp_get_thread_num();
mdarray<double_complex, 2> a(100, 100);
a(0, 0) = double_complex(tid, tid);
}
}
}
void f4()
{
mdarray<int, 1> buf;
buf = mdarray<int, 1>(100, memory_t::host, "buf");
buf = mdarray<int, 1>(200, memory_t::host, "buf");
//buf = mdarray<int, 1>(300, memory_t::host | memory_t::device, "buf");
}
void f5()
{
mdarray<double, 3> a;
if (a.size(0) != 0 || a.size(1) != 0 || a.size(2) != 0) {
printf("wrong sizes\n");
}
}
template <typename T, int N>
void f6(mdarray<T, N>& a)
{
std::array<mdarray_index_descriptor, N> dims;
for (int i = 0; i < N; i++) {
dims[i] = mdarray_index_descriptor(0, 10);
}
a = mdarray<T, N>(dims);
a[0] = 100;
a[a.size() - 1] = 200;
}
int main(int argn, char **argv)
{
sirius::initialize(1);
f2();
f3();
f4();
f5();
mdarray<double, 2> a;
f6(a);
#ifndef NDEBUG
std::cout << "Allocated memory : " << mdarray_mem_count::allocated().load() << std::endl;
#endif
sirius::finalize();
}
<commit_msg>fix test<commit_after>#include <sirius.h>
using namespace sirius;
mdarray<int, 1> f1()
{
mdarray<int, 1> aa;
aa = mdarray<int, 1>(4);
for (int i = 0; i < 4; i++) aa(i) = 200 + i;
return aa;
}
void f2()
{
mdarray<int, 1> a1(4);
for (int i = 0; i < 4; i++) a1(i) = 100 + i;
mdarray<int, 1> a2 = f1();
for (int i = 0; i < 4; i++)
{
std::cout << "a1(" << i << ")=" << a1(i) << std::endl;
std::cout << "a2(" << i << ")=" << a2(i) << std::endl;
}
mdarray<int, 1> a3(std::move(a2));
//==
//== // a1.deallocate();
//== //
//== // std::cout << "Deallocate a1" << std::endl;
//== //
//== // for (int i = 0; i < 4; i++)
//== // {
//== // std::cout << "a2(" << i << ")=" << a2(i) << std::endl;
//== // }
//== //
//== //
//== // mdarray<int, 1> a3 = a2;
//== //
for (int i = 0; i < 4; i++)
{
std::cout << "a3(" << i << ")=" << a3(i) << std::endl;
}
mdarray<int, 1> a4;
a4 = std::move(a3);
a4 = mdarray<int, 1>(20);
}
void f3()
{
for (int i = 0; i < 100; i++) {
#pragma omp parallel
{
int tid = omp_get_thread_num();
mdarray<double_complex, 2> a(100, 100);
a(0, 0) = double_complex(tid, tid);
}
}
}
void f4()
{
mdarray<int, 1> buf;
buf = mdarray<int, 1>(100, memory_t::host, "buf");
buf = mdarray<int, 1>(200, memory_t::host, "buf");
//buf = mdarray<int, 1>(300, memory_t::host | memory_t::device, "buf");
}
void f5()
{
mdarray<double, 3> a;
if (a.size(0) != 0 || a.size(1) != 0 || a.size(2) != 0) {
printf("wrong sizes\n");
}
}
template <typename T, int N>
void f6(mdarray<T, N>& a)
{
std::array<mdarray_index_descriptor, N> dims;
for (int i = 0; i < N; i++) {
dims[i] = mdarray_index_descriptor(0, 10);
}
a = mdarray<T, N>(dims);
a[0] = 100;
a[a.size() - 1] = 200;
}
int main(int argn, char **argv)
{
sirius::initialize(1);
f2();
f3();
f4();
f5();
mdarray<double, 2> a;
f6(a);
sirius::finalize();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: edit.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: vg $ $Date: 2007-04-11 17:52:22 $
*
* 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 _SV_EDIT_HXX
#define _SV_EDIT_HXX
#ifndef _SV_SV_H
#include <vcl/sv.h>
#endif
#ifndef _VCL_DLLAPI_H
#include <vcl/dllapi.h>
#endif
#ifndef _SV_TIMER_HXX
#include <vcl/timer.hxx>
#endif
#ifndef _SV_CTRL_HXX
#include <vcl/ctrl.hxx>
#endif
#ifndef _SV_MENU_HXX
#include <vcl/menu.hxx>
#endif
#ifndef _VCL_DNDHELP_HXX
#include <vcl/dndhelp.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
namespace com {
namespace sun {
namespace star {
namespace i18n {
class XBreakIterator;
class XExtendedInputSequenceChecker;
}}}}
class ImplSubEdit;
struct DDInfo;
struct Impl_IMEInfos;
// --------------
// - Edit-Types -
// --------------
#define EDIT_NOLIMIT STRING_LEN
#define EDIT_UPDATEDATA_TIMEOUT 350
typedef XubString (*FncGetSpecialChars)( Window* pWin, const Font& rFont );
// --------
// - Edit -
// --------
enum AutocompleteAction{ AUTOCOMPLETE_KEYINPUT, AUTOCOMPLETE_TABFORWARD, AUTOCOMPLETE_TABBACKWARD };
class VCL_DLLPUBLIC Edit : public Control, public vcl::unohelper::DragAndDropClient
{
private:
Edit* mpSubEdit;
Timer* mpUpdateDataTimer;
DDInfo* mpDDInfo;
Impl_IMEInfos* mpIMEInfos;
XubString maText;
XubString maSaveValue;
XubString maUndoText;
XubString maRedoText;
long mnXOffset;
Selection maSelection;
USHORT mnAlign;
xub_StrLen mnMaxTextLen;
AutocompleteAction meAutocompleteAction;
xub_Unicode mcEchoChar;
BOOL mbModified:1,
mbInternModified:1,
mbReadOnly:1,
mbInsertMode:1,
mbClickedInSelection:1,
mbIsSubEdit:1,
mbInMBDown:1,
mbActivePopup:1;
Link maModifyHdl;
Link maUpdateDataHdl;
Link maAutocompleteHdl;
//#if 0 // _SOLAR__PRIVATE
DECL_DLLPRIVATE_LINK( ImplUpdateDataHdl, Timer* );
SAL_DLLPRIVATE void ImplInitEditData();
SAL_DLLPRIVATE void ImplModified();
SAL_DLLPRIVATE XubString ImplGetText() const;
SAL_DLLPRIVATE void ImplRepaint( xub_StrLen nStart = 0, xub_StrLen nEnd = STRING_LEN, bool bLayout = false );
SAL_DLLPRIVATE void ImplDelete( const Selection& rSelection, BYTE nDirection, BYTE nMode );
SAL_DLLPRIVATE void ImplSetText( const XubString& rStr, const Selection* pNewSelection = 0 );
SAL_DLLPRIVATE void ImplInsertText( const XubString& rStr, const Selection* pNewSelection = 0, sal_Bool bIsUserInput = sal_False );
SAL_DLLPRIVATE String ImplGetValidString( const String& rString ) const;
SAL_DLLPRIVATE void ImplClearBackground( long nXStart, long nXEnd );
SAL_DLLPRIVATE void ImplShowCursor( BOOL bOnlyIfVisible = TRUE );
SAL_DLLPRIVATE void ImplAlign();
SAL_DLLPRIVATE void ImplAlignAndPaint();
SAL_DLLPRIVATE xub_StrLen ImplGetCharPos( const Point& rWindowPos ) const;
SAL_DLLPRIVATE void ImplSetCursorPos( xub_StrLen nChar, BOOL bSelect );
SAL_DLLPRIVATE void ImplShowDDCursor();
SAL_DLLPRIVATE void ImplHideDDCursor();
SAL_DLLPRIVATE BOOL ImplHandleKeyEvent( const KeyEvent& rKEvt );
SAL_DLLPRIVATE void ImplCopyToSelectionClipboard();
SAL_DLLPRIVATE void ImplCopy( ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboard >& rxClipboard );
SAL_DLLPRIVATE void ImplPaste( ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboard >& rxClipboard );
SAL_DLLPRIVATE long ImplGetExtraOffset() const;
SAL_DLLPRIVATE ::com::sun::star::uno::Reference < ::com::sun::star::i18n::XExtendedInputSequenceChecker > ImplGetInputSequenceChecker() const;
SAL_DLLPRIVATE ::com::sun::star::uno::Reference < ::com::sun::star::i18n::XBreakIterator > ImplGetBreakIterator() const;
//#endif
protected:
//#if 0 // _SOLAR__PRIVATE
using Window::ImplInit;
SAL_DLLPRIVATE void ImplInit( Window* pParent, WinBits nStyle );
SAL_DLLPRIVATE WinBits ImplInitStyle( WinBits nStyle );
SAL_DLLPRIVATE void ImplInitSettings( BOOL bFont, BOOL bForeground, BOOL bBackground );
SAL_DLLPRIVATE void ImplLoadRes( const ResId& rResId );
SAL_DLLPRIVATE void ImplSetSelection( const Selection& rSelection, BOOL bPaint = TRUE );
//#endif
SAL_DLLPRIVATE int ImplGetNativeControlType();
::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::dnd::XDragSourceListener > mxDnDListener;
// DragAndDropClient
using vcl::unohelper::DragAndDropClient::dragEnter;
using vcl::unohelper::DragAndDropClient::dragExit;
using vcl::unohelper::DragAndDropClient::dragOver;
virtual void dragGestureRecognized( const ::com::sun::star::datatransfer::dnd::DragGestureEvent& dge ) throw (::com::sun::star::uno::RuntimeException);
virtual void dragDropEnd( const ::com::sun::star::datatransfer::dnd::DragSourceDropEvent& dsde ) throw (::com::sun::star::uno::RuntimeException);
virtual void drop( const ::com::sun::star::datatransfer::dnd::DropTargetDropEvent& dtde ) throw (::com::sun::star::uno::RuntimeException);
virtual void dragEnter( const ::com::sun::star::datatransfer::dnd::DropTargetDragEnterEvent& dtdee ) throw (::com::sun::star::uno::RuntimeException);
virtual void dragExit( const ::com::sun::star::datatransfer::dnd::DropTargetEvent& dte ) throw (::com::sun::star::uno::RuntimeException);
virtual void dragOver( const ::com::sun::star::datatransfer::dnd::DropTargetDragEvent& dtde ) throw (::com::sun::star::uno::RuntimeException);
protected:
virtual void FillLayoutData() const;
Edit( WindowType nType );
public:
// public because needed in button.cxx
SAL_DLLPRIVATE bool ImplUseNativeBorder( WinBits nStyle );
Edit( Window* pParent, WinBits nStyle = WB_BORDER );
Edit( Window* pParent, const ResId& rResId );
virtual ~Edit();
virtual void MouseButtonDown( const MouseEvent& rMEvt );
virtual void MouseButtonUp( const MouseEvent& rMEvt );
virtual void KeyInput( const KeyEvent& rKEvt );
virtual void Paint( const Rectangle& rRect );
virtual void Resize();
virtual void Draw( OutputDevice* pDev, const Point& rPos, const Size& rSize, ULONG nFlags );
virtual void GetFocus();
virtual void LoseFocus();
virtual void Tracking( const TrackingEvent& rTEvt );
virtual void Command( const CommandEvent& rCEvt );
virtual void StateChanged( StateChangedType nType );
virtual void DataChanged( const DataChangedEvent& rDCEvt );
virtual Window* GetPreferredKeyInputWindow();
virtual void Modify();
virtual void UpdateData();
static BOOL IsCharInput( const KeyEvent& rKEvt );
virtual void SetModifyFlag();
virtual void ClearModifyFlag();
virtual BOOL IsModified() const { return mpSubEdit ? mpSubEdit->mbModified : mbModified; }
virtual void EnableUpdateData( ULONG nTimeout = EDIT_UPDATEDATA_TIMEOUT );
virtual void DisableUpdateData() { delete mpUpdateDataTimer; mpUpdateDataTimer = NULL; }
virtual ULONG IsUpdateDataEnabled() const;
void SetEchoChar( xub_Unicode c );
xub_Unicode GetEchoChar() const { return mcEchoChar; }
virtual void SetReadOnly( BOOL bReadOnly = TRUE );
virtual BOOL IsReadOnly() const { return mbReadOnly; }
void SetInsertMode( BOOL bInsert );
BOOL IsInsertMode() const;
virtual void SetMaxTextLen( xub_StrLen nMaxLen = EDIT_NOLIMIT );
virtual xub_StrLen GetMaxTextLen() const { return mnMaxTextLen; }
virtual void SetSelection( const Selection& rSelection );
virtual const Selection& GetSelection() const;
virtual void ReplaceSelected( const XubString& rStr );
virtual void DeleteSelected();
virtual XubString GetSelected() const;
virtual void Cut();
virtual void Copy();
virtual void Paste();
void Undo();
virtual void SetText( const XubString& rStr );
virtual void SetText( const XubString& rStr, const Selection& rNewSelection );
virtual XubString GetText() const;
void SaveValue() { maSaveValue = GetText(); }
const XubString& GetSavedValue() const { return maSaveValue; }
virtual void SetModifyHdl( const Link& rLink ) { maModifyHdl = rLink; }
virtual const Link& GetModifyHdl() const { return maModifyHdl; }
virtual void SetUpdateDataHdl( const Link& rLink ) { maUpdateDataHdl = rLink; }
virtual const Link& GetUpdateDataHdl() const { return maUpdateDataHdl; }
void SetSubEdit( Edit* pEdit );
Edit* GetSubEdit() const { return mpSubEdit; }
void SetAutocompleteHdl( const Link& rHdl );
const Link& GetAutocompleteHdl() const { return maAutocompleteHdl; }
AutocompleteAction GetAutocompleteAction() const { return meAutocompleteAction; }
virtual Size CalcMinimumSize() const;
virtual Size CalcSize( USHORT nChars ) const;
virtual xub_StrLen GetMaxVisChars() const;
xub_StrLen GetCharPos( const Point& rWindowPos ) const;
static void SetGetSpecialCharsFunction( FncGetSpecialChars fn );
static FncGetSpecialChars GetGetSpecialCharsFunction();
static PopupMenu* CreatePopupMenu();
static void DeletePopupMenu( PopupMenu* pMenu );
};
inline ULONG Edit::IsUpdateDataEnabled() const
{
if ( mpUpdateDataTimer )
return mpUpdateDataTimer->GetTimeout();
else
return FALSE;
}
#endif // _SV_EDIT_HXX
<commit_msg>INTEGRATION: CWS vcl75 (1.2.16); FILE MERGED 2007/04/18 17:29:31 pl 1.2.16.1: solving analyze alerts due to headabu removal<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: edit.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2007-04-26 10:34:39 $
*
* 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 _SV_EDIT_HXX
#define _SV_EDIT_HXX
#ifndef _SV_SV_H
#include <vcl/sv.h>
#endif
#ifndef _VCL_DLLAPI_H
#include <vcl/dllapi.h>
#endif
#ifndef _SV_TIMER_HXX
#include <vcl/timer.hxx>
#endif
#ifndef _SV_CTRL_HXX
#include <vcl/ctrl.hxx>
#endif
#ifndef _SV_MENU_HXX
#include <vcl/menu.hxx>
#endif
#ifndef _VCL_DNDHELP_HXX
#include <vcl/dndhelp.hxx>
#endif
#ifndef _COM_SUN_STAR_UNO_REFERENCE_H_
#include <com/sun/star/uno/Reference.h>
#endif
namespace com {
namespace sun {
namespace star {
namespace i18n {
class XBreakIterator;
class XExtendedInputSequenceChecker;
}}}}
class ImplSubEdit;
struct DDInfo;
struct Impl_IMEInfos;
// --------------
// - Edit-Types -
// --------------
#define EDIT_NOLIMIT STRING_LEN
#define EDIT_UPDATEDATA_TIMEOUT 350
typedef XubString (*FncGetSpecialChars)( Window* pWin, const Font& rFont );
// --------
// - Edit -
// --------
enum AutocompleteAction{ AUTOCOMPLETE_KEYINPUT, AUTOCOMPLETE_TABFORWARD, AUTOCOMPLETE_TABBACKWARD };
class VCL_DLLPUBLIC Edit : public Control, public vcl::unohelper::DragAndDropClient
{
private:
Edit* mpSubEdit;
Timer* mpUpdateDataTimer;
DDInfo* mpDDInfo;
Impl_IMEInfos* mpIMEInfos;
XubString maText;
XubString maSaveValue;
XubString maUndoText;
XubString maRedoText;
long mnXOffset;
Selection maSelection;
USHORT mnAlign;
xub_StrLen mnMaxTextLen;
AutocompleteAction meAutocompleteAction;
xub_Unicode mcEchoChar;
BOOL mbModified:1,
mbInternModified:1,
mbReadOnly:1,
mbInsertMode:1,
mbClickedInSelection:1,
mbIsSubEdit:1,
mbInMBDown:1,
mbActivePopup:1;
Link maModifyHdl;
Link maUpdateDataHdl;
Link maAutocompleteHdl;
//#if 0 // _SOLAR__PRIVATE
DECL_DLLPRIVATE_LINK( ImplUpdateDataHdl, Timer* );
SAL_DLLPRIVATE void ImplInitEditData();
SAL_DLLPRIVATE void ImplModified();
SAL_DLLPRIVATE XubString ImplGetText() const;
SAL_DLLPRIVATE void ImplRepaint( xub_StrLen nStart = 0, xub_StrLen nEnd = STRING_LEN, bool bLayout = false );
SAL_DLLPRIVATE void ImplInvalidateOrRepaint( xub_StrLen nStart = 0, xub_StrLen nEnd = STRING_LEN );
SAL_DLLPRIVATE void ImplDelete( const Selection& rSelection, BYTE nDirection, BYTE nMode );
SAL_DLLPRIVATE void ImplSetText( const XubString& rStr, const Selection* pNewSelection = 0 );
SAL_DLLPRIVATE void ImplInsertText( const XubString& rStr, const Selection* pNewSelection = 0, sal_Bool bIsUserInput = sal_False );
SAL_DLLPRIVATE String ImplGetValidString( const String& rString ) const;
SAL_DLLPRIVATE void ImplClearBackground( long nXStart, long nXEnd );
SAL_DLLPRIVATE void ImplShowCursor( BOOL bOnlyIfVisible = TRUE );
SAL_DLLPRIVATE void ImplAlign();
SAL_DLLPRIVATE void ImplAlignAndPaint();
SAL_DLLPRIVATE xub_StrLen ImplGetCharPos( const Point& rWindowPos ) const;
SAL_DLLPRIVATE void ImplSetCursorPos( xub_StrLen nChar, BOOL bSelect );
SAL_DLLPRIVATE void ImplShowDDCursor();
SAL_DLLPRIVATE void ImplHideDDCursor();
SAL_DLLPRIVATE BOOL ImplHandleKeyEvent( const KeyEvent& rKEvt );
SAL_DLLPRIVATE void ImplCopyToSelectionClipboard();
SAL_DLLPRIVATE void ImplCopy( ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboard >& rxClipboard );
SAL_DLLPRIVATE void ImplPaste( ::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::clipboard::XClipboard >& rxClipboard );
SAL_DLLPRIVATE long ImplGetExtraOffset() const;
SAL_DLLPRIVATE ::com::sun::star::uno::Reference < ::com::sun::star::i18n::XExtendedInputSequenceChecker > ImplGetInputSequenceChecker() const;
SAL_DLLPRIVATE ::com::sun::star::uno::Reference < ::com::sun::star::i18n::XBreakIterator > ImplGetBreakIterator() const;
//#endif
protected:
//#if 0 // _SOLAR__PRIVATE
using Window::ImplInit;
SAL_DLLPRIVATE void ImplInit( Window* pParent, WinBits nStyle );
SAL_DLLPRIVATE WinBits ImplInitStyle( WinBits nStyle );
SAL_DLLPRIVATE void ImplInitSettings( BOOL bFont, BOOL bForeground, BOOL bBackground );
SAL_DLLPRIVATE void ImplLoadRes( const ResId& rResId );
SAL_DLLPRIVATE void ImplSetSelection( const Selection& rSelection, BOOL bPaint = TRUE );
//#endif
SAL_DLLPRIVATE int ImplGetNativeControlType();
::com::sun::star::uno::Reference< ::com::sun::star::datatransfer::dnd::XDragSourceListener > mxDnDListener;
// DragAndDropClient
using vcl::unohelper::DragAndDropClient::dragEnter;
using vcl::unohelper::DragAndDropClient::dragExit;
using vcl::unohelper::DragAndDropClient::dragOver;
virtual void dragGestureRecognized( const ::com::sun::star::datatransfer::dnd::DragGestureEvent& dge ) throw (::com::sun::star::uno::RuntimeException);
virtual void dragDropEnd( const ::com::sun::star::datatransfer::dnd::DragSourceDropEvent& dsde ) throw (::com::sun::star::uno::RuntimeException);
virtual void drop( const ::com::sun::star::datatransfer::dnd::DropTargetDropEvent& dtde ) throw (::com::sun::star::uno::RuntimeException);
virtual void dragEnter( const ::com::sun::star::datatransfer::dnd::DropTargetDragEnterEvent& dtdee ) throw (::com::sun::star::uno::RuntimeException);
virtual void dragExit( const ::com::sun::star::datatransfer::dnd::DropTargetEvent& dte ) throw (::com::sun::star::uno::RuntimeException);
virtual void dragOver( const ::com::sun::star::datatransfer::dnd::DropTargetDragEvent& dtde ) throw (::com::sun::star::uno::RuntimeException);
protected:
virtual void FillLayoutData() const;
Edit( WindowType nType );
public:
// public because needed in button.cxx
SAL_DLLPRIVATE bool ImplUseNativeBorder( WinBits nStyle );
Edit( Window* pParent, WinBits nStyle = WB_BORDER );
Edit( Window* pParent, const ResId& rResId );
virtual ~Edit();
virtual void MouseButtonDown( const MouseEvent& rMEvt );
virtual void MouseButtonUp( const MouseEvent& rMEvt );
virtual void KeyInput( const KeyEvent& rKEvt );
virtual void Paint( const Rectangle& rRect );
virtual void Resize();
virtual void Draw( OutputDevice* pDev, const Point& rPos, const Size& rSize, ULONG nFlags );
virtual void GetFocus();
virtual void LoseFocus();
virtual void Tracking( const TrackingEvent& rTEvt );
virtual void Command( const CommandEvent& rCEvt );
virtual void StateChanged( StateChangedType nType );
virtual void DataChanged( const DataChangedEvent& rDCEvt );
virtual Window* GetPreferredKeyInputWindow();
virtual void Modify();
virtual void UpdateData();
static BOOL IsCharInput( const KeyEvent& rKEvt );
virtual void SetModifyFlag();
virtual void ClearModifyFlag();
virtual BOOL IsModified() const { return mpSubEdit ? mpSubEdit->mbModified : mbModified; }
virtual void EnableUpdateData( ULONG nTimeout = EDIT_UPDATEDATA_TIMEOUT );
virtual void DisableUpdateData() { delete mpUpdateDataTimer; mpUpdateDataTimer = NULL; }
virtual ULONG IsUpdateDataEnabled() const;
void SetEchoChar( xub_Unicode c );
xub_Unicode GetEchoChar() const { return mcEchoChar; }
virtual void SetReadOnly( BOOL bReadOnly = TRUE );
virtual BOOL IsReadOnly() const { return mbReadOnly; }
void SetInsertMode( BOOL bInsert );
BOOL IsInsertMode() const;
virtual void SetMaxTextLen( xub_StrLen nMaxLen = EDIT_NOLIMIT );
virtual xub_StrLen GetMaxTextLen() const { return mnMaxTextLen; }
virtual void SetSelection( const Selection& rSelection );
virtual const Selection& GetSelection() const;
virtual void ReplaceSelected( const XubString& rStr );
virtual void DeleteSelected();
virtual XubString GetSelected() const;
virtual void Cut();
virtual void Copy();
virtual void Paste();
void Undo();
virtual void SetText( const XubString& rStr );
virtual void SetText( const XubString& rStr, const Selection& rNewSelection );
virtual XubString GetText() const;
void SaveValue() { maSaveValue = GetText(); }
const XubString& GetSavedValue() const { return maSaveValue; }
virtual void SetModifyHdl( const Link& rLink ) { maModifyHdl = rLink; }
virtual const Link& GetModifyHdl() const { return maModifyHdl; }
virtual void SetUpdateDataHdl( const Link& rLink ) { maUpdateDataHdl = rLink; }
virtual const Link& GetUpdateDataHdl() const { return maUpdateDataHdl; }
void SetSubEdit( Edit* pEdit );
Edit* GetSubEdit() const { return mpSubEdit; }
void SetAutocompleteHdl( const Link& rHdl );
const Link& GetAutocompleteHdl() const { return maAutocompleteHdl; }
AutocompleteAction GetAutocompleteAction() const { return meAutocompleteAction; }
virtual Size CalcMinimumSize() const;
virtual Size CalcSize( USHORT nChars ) const;
virtual xub_StrLen GetMaxVisChars() const;
xub_StrLen GetCharPos( const Point& rWindowPos ) const;
static void SetGetSpecialCharsFunction( FncGetSpecialChars fn );
static FncGetSpecialChars GetGetSpecialCharsFunction();
static PopupMenu* CreatePopupMenu();
static void DeletePopupMenu( PopupMenu* pMenu );
};
inline ULONG Edit::IsUpdateDataEnabled() const
{
if ( mpUpdateDataTimer )
return mpUpdateDataTimer->GetTimeout();
else
return FALSE;
}
#endif // _SV_EDIT_HXX
<|endoftext|> |
<commit_before>/** @file
@brief Implementation of the "multiserver" plugin that offers the stock VRPN
devices.
@date 2014
@author
Ryan Pavlik
<[email protected]>
<http://sensics.com>
*/
// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
// Internal Includes
#include "VRPNMultiserver.h"
#include "DevicesWithParameters.h"
#include <osvr/PluginKit/PluginKit.h>
#include <osvr/Util/UniquePtr.h>
#include <osvr/VRPNServer/VRPNDeviceRegistration.h>
// Library/third-party includes
#include "hidapi/hidapi.h"
#include "vrpn_Connection.h"
#include "vrpn_Tracker_RazerHydra.h"
#include "vrpn_Tracker_Filter.h"
#include <boost/noncopyable.hpp>
// Standard includes
#include <iostream>
#include <map>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
class VRPNHardwareDetect : boost::noncopyable {
public:
VRPNHardwareDetect(VRPNMultiserverData &data) : m_data(data) {}
OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx) {
struct hid_device_info *enumData = hid_enumerate(0, 0);
for (struct hid_device_info *dev = enumData; dev != nullptr;
dev = dev->next) {
if (m_isPathHandled(dev->path)) {
continue;
}
if (dev->vendor_id == 0x1532 && dev->product_id == 0x0300) {
m_handlePath(dev->path);
/// Decorated name for Hydra
std::string name;
{
// Razer Hydra
osvr::vrpnserver::VRPNDeviceRegistration reg(ctx);
name = reg.useDecoratedName(m_data.getName("RazerHydra"));
reg.registerDevice(new vrpn_Tracker_RazerHydra(
name.c_str(), reg.getVRPNConnection()));
}
std::string localName = "*" + name;
{
// Corresponding filter
osvr::vrpnserver::VRPNDeviceRegistration reg(ctx);
reg.registerDevice(new vrpn_Tracker_FilterOneEuro(
reg.useDecoratedName(m_data.getName("OneEuroFilter"))
.c_str(),
reg.getVRPNConnection(), localName.c_str(), 2, 1.15,
1.0, 1.2, 1.5, 5.0, 1.2));
}
break;
}
}
hid_free_enumeration(enumData);
return OSVR_RETURN_SUCCESS;
}
private:
bool m_isPathHandled(const char *path) {
return std::find(begin(m_handledPaths), end(m_handledPaths),
std::string(path)) != end(m_handledPaths);
}
void m_handlePath(const char *path) {
m_handledPaths.push_back(std::string(path));
}
VRPNMultiserverData &m_data;
std::vector<std::string> m_handledPaths;
};
OSVR_PLUGIN(org_opengoggles_bundled_Multiserver) {
osvr::pluginkit::PluginContext context(ctx);
VRPNMultiserverData &data =
*context.registerObjectForDeletion(new VRPNMultiserverData);
context.registerHardwareDetectCallback(new VRPNHardwareDetect(data));
osvrRegisterDriverInstantiationCallback(
ctx, "YEI_3Space_Sensor", &wrappedConstructor<&createYEI>, &data);
return OSVR_RETURN_SUCCESS;
}
<commit_msg>Add auto-detect support to multiserver for HDK tracker.<commit_after>/** @file
@brief Implementation of the "multiserver" plugin that offers the stock VRPN
devices.
@date 2014
@author
Ryan Pavlik
<[email protected]>
<http://sensics.com>
*/
// Copyright 2014 Sensics, Inc.
//
// All rights reserved.
//
// (Final version intended to be licensed under
// the Apache License, Version 2.0)
// Internal Includes
#include "VRPNMultiserver.h"
#include "DevicesWithParameters.h"
#include <osvr/PluginKit/PluginKit.h>
#include <osvr/Util/UniquePtr.h>
#include <osvr/VRPNServer/VRPNDeviceRegistration.h>
// Library/third-party includes
#include "hidapi/hidapi.h"
#include "vrpn_Connection.h"
#include "vrpn_Tracker_RazerHydra.h"
#include "vrpn_Tracker_OSVRHackerDevKit.h"
#include "vrpn_Tracker_Filter.h"
#include <boost/noncopyable.hpp>
// Standard includes
#include <iostream>
#include <map>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
class VRPNHardwareDetect : boost::noncopyable {
public:
VRPNHardwareDetect(VRPNMultiserverData &data) : m_data(data) {}
OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx) {
struct hid_device_info *enumData = hid_enumerate(0, 0);
for (struct hid_device_info *dev = enumData; dev != nullptr;
dev = dev->next) {
if (m_isPathHandled(dev->path)) {
continue;
}
if (dev->vendor_id == 0x1532 && dev->product_id == 0x0300) {
m_handlePath(dev->path);
/// Decorated name for Hydra
std::string name;
{
// Razer Hydra
osvr::vrpnserver::VRPNDeviceRegistration reg(ctx);
name = reg.useDecoratedName(m_data.getName("RazerHydra"));
reg.registerDevice(new vrpn_Tracker_RazerHydra(
name.c_str(), reg.getVRPNConnection()));
}
std::string localName = "*" + name;
{
// Corresponding filter
osvr::vrpnserver::VRPNDeviceRegistration reg(ctx);
reg.registerDevice(new vrpn_Tracker_FilterOneEuro(
reg.useDecoratedName(m_data.getName("OneEuroFilter"))
.c_str(),
reg.getVRPNConnection(), localName.c_str(), 2, 1.15,
1.0, 1.2, 1.5, 5.0, 1.2));
}
break;
}
if ((dev->vendor_id == 0x1532 && dev->product_id == 0x0300) ||
(dev->vendor_id == 0x03EB && dev->product_id == 0x2421)) {
m_handlePath(dev->path);
// OSVR Hacker Dev Kit
osvr::vrpnserver::VRPNDeviceRegistration reg(ctx);
reg.constructAndRegisterDevice<vrpn_Tracker_OSVRHackerDevKit>(
m_data.getName("OSVRHackerDevKit"));
break;
}
}
hid_free_enumeration(enumData);
return OSVR_RETURN_SUCCESS;
}
private:
bool m_isPathHandled(const char *path) {
return std::find(begin(m_handledPaths), end(m_handledPaths),
std::string(path)) != end(m_handledPaths);
}
void m_handlePath(const char *path) {
m_handledPaths.push_back(std::string(path));
}
VRPNMultiserverData &m_data;
std::vector<std::string> m_handledPaths;
};
OSVR_PLUGIN(org_opengoggles_bundled_Multiserver) {
osvr::pluginkit::PluginContext context(ctx);
VRPNMultiserverData &data =
*context.registerObjectForDeletion(new VRPNMultiserverData);
context.registerHardwareDetectCallback(new VRPNHardwareDetect(data));
osvrRegisterDriverInstantiationCallback(
ctx, "YEI_3Space_Sensor", &wrappedConstructor<&createYEI>, &data);
return OSVR_RETURN_SUCCESS;
}
<|endoftext|> |
<commit_before>#include <BALL/CONCEPT/classTest.h>
#include <BALLTestConfig.h>
///////////////////////////
#include <BALL/FORMAT/dockResultFile.h>
#include <BALL/DOCKING/COMMON/flexibleMolecule.h>
#include <BALL/DOCKING/COMMON/conformation.h>
#include <BALL/DOCKING/COMMON/result.h>
#include <BALL/FORMAT/SDFile.h>
#include <BALL/KERNEL/forEach.h>
#include <BALL/KERNEL/bondIterator.h>
#include <BALL/KERNEL/PTE.h>
#include <BALL/KERNEL/atom.h>
#include <BALL/KERNEL/bond.h>
#include <BALL/KERNEL/system.h>
#include <BALL/KERNEL/molecule.h>
#include <BALL/MATHS/vector3.h>
#include <BALL/STRUCTURE/defaultProcessors.h>
#include <BALL/STRUCTURE/geometricTransformations.h>
#include <iostream>
///////////////////////////
using namespace BALL;
using namespace std;
using BALL::DockResultFile;
using BALL::Ligand;
using BALL::Result;
using BALL::Conformation;
bool compareMolecules(Molecule& mol1, Molecule& mol2)
{
if(mol1.countAtoms()!=mol2.countAtoms())
return false;
if(mol1.countBonds()!=mol2.countBonds())
return false;
AtomIterator ai;
vector<Vector3> pos1;
vector<float> q1;
BALL_FOREACH_ATOM(mol1, ai)
{
pos1.push_back(ai->getPosition());
q1.push_back(ai->getCharge());
}
vector<Vector3> pos2;
vector<float> q2;
BALL_FOREACH_ATOM(mol2, ai)
{
pos2.push_back(ai->getPosition());
q2.push_back(ai->getCharge());
}
for(unsigned int i=0;i<pos1.size();i++)
{
if( fabs(pos1[i].x-pos2[i].x)>1e-8 )
return false;
if( fabs(pos1[i].y-pos2[i].y)>1e-8 )
return false;
if( fabs(pos1[i].z-pos2[i].z)>1e-8 )
return false;
if( fabs(q1[i]-q2[i])>1e-8 )
return false;
}
AtomBondIterator bi;
vector<String> pairs1;
BALL_FOREACH_BOND(mol1, ai, bi)
{
Bond* bnd = &(*bi);
const Atom* at1 = bnd->getFirstAtom();
const Atom* at2 = bnd->getSecondAtom();
String pair = at1->getElement().getSymbol()+"-"+String(bnd->getOrder())+"-"+at2->getElement().getSymbol();
pairs1.push_back(pair);
}
vector<String> pairs2;
BALL_FOREACH_BOND(mol2, ai, bi)
{
Bond* bnd = &(*bi);
const Atom* at1 = bnd->getFirstAtom();
const Atom* at2 = bnd->getSecondAtom();
String pair = at1->getElement().getSymbol()+"-"+String(bnd->getOrder())+"-"+at2->getElement().getSymbol();
pairs2.push_back(pair);
}
if(pairs1.size()!=pairs2.size())
return false;
for(unsigned int i=0;i<pairs1.size();i++)
if(pairs1[i]!=pairs2[i])
return false;
return true;
}
START_TEST(DockResultFile)
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
CHECK(read/write DockResultFile)
SDFile f(BALL_TEST_DATA_PATH(QSAR_test.sdf));
Molecule* mol;
String tmpfile;
File::createTemporaryFilename(tmpfile);
DockResultFile df(tmpfile,File::MODE_OUT);
vector<Molecule*> mols;
int id=0;
while( (mol = f.read()) )
{
// skip this molecule because its
// conformation is contained twice
// in this set
if(mol->getName()=="THIOL_4")
continue;
mol->setProperty("ID",String(id));
df.write(*mol);
mols.push_back(mol);
id++;
}
df.close();
// now iterate molecule-by-molecule over the file
DockResultFile dfin(tmpfile,File::MODE_IN);
Molecule* mol2;
unsigned int i=0;
while( (mol2 = dfin.read()) )
{
bool cmp = compareMolecules(*mols[i],*mol2);
TEST_EQUAL(cmp,true)
TEST_EQUAL(mol2->getProperty("ID").getString(),mols[i]->getProperty("ID").getString())
delete mol2;
i++;
}
dfin.close();
DockResultFile dfin2(tmpfile,File::MODE_IN);
Ligand* lig = dfin2.readLigand();
TEST_EQUAL(lig->hasConformation("f5fdd18549299b09eedbe0131fb46fbc02b10efb"),true)
TEST_EQUAL(lig->getConformationId(0),"f5fdd18549299b09eedbe0131fb46fbc02b10efb")
TEST_EQUAL(lig->getNumberOfConformations(),1)
delete lig;
dfin2.close();
// now iterate ligand-by-ligand over the file
DockResultFile dfin3(tmpfile,File::MODE_IN);
i=0;
while( (lig=dfin3.readLigand()) )
{
Molecule* mol = lig->getConformer(0);
bool cmp = compareMolecules(*mols[i],*mol);
TEST_EQUAL(cmp,true)
// there is no second conformer so returned
// pointer should be NULL
TEST_EQUAL(lig->getConformer(1),0)
delete mol;
delete lig;
i++;
}
dfin3.close();
File::remove(tmpfile);
for(unsigned int i=0;i<mols.size();i++)
delete mols[i];
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>DockResultFile_test: explicitly check againt NULL<commit_after>#include <BALL/CONCEPT/classTest.h>
#include <BALLTestConfig.h>
///////////////////////////
#include <BALL/FORMAT/dockResultFile.h>
#include <BALL/DOCKING/COMMON/flexibleMolecule.h>
#include <BALL/DOCKING/COMMON/conformation.h>
#include <BALL/DOCKING/COMMON/result.h>
#include <BALL/FORMAT/SDFile.h>
#include <BALL/KERNEL/forEach.h>
#include <BALL/KERNEL/bondIterator.h>
#include <BALL/KERNEL/PTE.h>
#include <BALL/KERNEL/atom.h>
#include <BALL/KERNEL/bond.h>
#include <BALL/KERNEL/system.h>
#include <BALL/KERNEL/molecule.h>
#include <BALL/MATHS/vector3.h>
#include <BALL/STRUCTURE/defaultProcessors.h>
#include <BALL/STRUCTURE/geometricTransformations.h>
#include <iostream>
///////////////////////////
using namespace BALL;
using namespace std;
using BALL::DockResultFile;
using BALL::Ligand;
using BALL::Result;
using BALL::Conformation;
bool compareMolecules(Molecule& mol1, Molecule& mol2)
{
if(mol1.countAtoms()!=mol2.countAtoms())
return false;
if(mol1.countBonds()!=mol2.countBonds())
return false;
AtomIterator ai;
vector<Vector3> pos1;
vector<float> q1;
BALL_FOREACH_ATOM(mol1, ai)
{
pos1.push_back(ai->getPosition());
q1.push_back(ai->getCharge());
}
vector<Vector3> pos2;
vector<float> q2;
BALL_FOREACH_ATOM(mol2, ai)
{
pos2.push_back(ai->getPosition());
q2.push_back(ai->getCharge());
}
for(unsigned int i=0;i<pos1.size();i++)
{
if( fabs(pos1[i].x-pos2[i].x)>1e-8 )
return false;
if( fabs(pos1[i].y-pos2[i].y)>1e-8 )
return false;
if( fabs(pos1[i].z-pos2[i].z)>1e-8 )
return false;
if( fabs(q1[i]-q2[i])>1e-8 )
return false;
}
AtomBondIterator bi;
vector<String> pairs1;
BALL_FOREACH_BOND(mol1, ai, bi)
{
Bond* bnd = &(*bi);
const Atom* at1 = bnd->getFirstAtom();
const Atom* at2 = bnd->getSecondAtom();
String pair = at1->getElement().getSymbol()+"-"+String(bnd->getOrder())+"-"+at2->getElement().getSymbol();
pairs1.push_back(pair);
}
vector<String> pairs2;
BALL_FOREACH_BOND(mol2, ai, bi)
{
Bond* bnd = &(*bi);
const Atom* at1 = bnd->getFirstAtom();
const Atom* at2 = bnd->getSecondAtom();
String pair = at1->getElement().getSymbol()+"-"+String(bnd->getOrder())+"-"+at2->getElement().getSymbol();
pairs2.push_back(pair);
}
if(pairs1.size()!=pairs2.size())
return false;
for(unsigned int i=0;i<pairs1.size();i++)
if(pairs1[i]!=pairs2[i])
return false;
return true;
}
START_TEST(DockResultFile)
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
CHECK(read/write DockResultFile)
SDFile f(BALL_TEST_DATA_PATH(QSAR_test.sdf));
Molecule* mol;
String tmpfile;
File::createTemporaryFilename(tmpfile);
DockResultFile df(tmpfile,File::MODE_OUT);
vector<Molecule*> mols;
int id=0;
while((mol = f.read()) != NULL)
{
// skip this molecule because its
// conformation is contained twice
// in this set
if(mol->getName()=="THIOL_4")
continue;
mol->setProperty("ID",String(id));
df.write(*mol);
mols.push_back(mol);
id++;
}
df.close();
// now iterate molecule-by-molecule over the file
DockResultFile dfin(tmpfile,File::MODE_IN);
Molecule* mol2;
unsigned int i=0;
while( (mol2 = dfin.read()) )
{
bool cmp = compareMolecules(*mols[i],*mol2);
TEST_EQUAL(cmp,true)
TEST_EQUAL(mol2->getProperty("ID").getString(),mols[i]->getProperty("ID").getString())
delete mol2;
i++;
}
dfin.close();
DockResultFile dfin2(tmpfile,File::MODE_IN);
Ligand* lig = dfin2.readLigand();
TEST_EQUAL(lig->hasConformation("f5fdd18549299b09eedbe0131fb46fbc02b10efb"),true)
TEST_EQUAL(lig->getConformationId(0),"f5fdd18549299b09eedbe0131fb46fbc02b10efb")
TEST_EQUAL(lig->getNumberOfConformations(),1)
delete lig;
dfin2.close();
// now iterate ligand-by-ligand over the file
DockResultFile dfin3(tmpfile,File::MODE_IN);
i=0;
while( (lig=dfin3.readLigand()) )
{
Molecule* mol = lig->getConformer(0);
bool cmp = compareMolecules(*mols[i],*mol);
TEST_EQUAL(cmp,true)
// there is no second conformer so returned
// pointer should be NULL
TEST_EQUAL(lig->getConformer(1),0)
delete mol;
delete lig;
i++;
}
dfin3.close();
File::remove(tmpfile);
for(unsigned int i=0;i<mols.size();i++)
delete mols[i];
RESULT
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|> |
<commit_before>#include "ARVersion.h"
#if !defined(__CINT__) || defined(__MAKECINT__)
#include "TSystem.h"
#include "TROOT.h"
#include "TGeoManager.h"
#include "TObjString.h"
#include "TClonesArray.h"
#include "TError.h"
#include "AliGeomManager.h"
#include "AliCDBManager.h"
#include "AliCDBStorage.h"
#include "AliCDBPath.h"
#include "AliCDBEntry.h"
#include "AliCDBId.h"
#include "AliCDBMetaData.h"
#include "AliMisAligner.h"
#include "AliHMPIDMisAligner.h"
#include "AliITSMisAligner.h"
#include "AliPMDMisAligner.h"
#include "AliT0MisAligner.h"
#include "AliTPCMisAligner.h"
#include "AliVZEROMisAligner.h"
#include "AliZDCMisAligner.h"
#include <TString.h>
#endif
void MakeAlignmentObjs(const char* detList="ALL", const char* ocdbOrDir = "local://$HOME/ResidualMisAlignment", const char* misalType="residual", Bool_t partialGeom=kFALSE){
// Make alignment objects for all detectors listed in "detList"
// for the misalignment scenario passed as argument "misalType".
// "ocdbUriDirPath" argument is used as URI for an OCDB if it contains
// either the string "local;//" or the string "alien://folder=",
// otherwise it is used as the path of the directory where to
// put the files containing the alignment objects.
// The geometry used is the one produced with $ALICE_ROOT/macros/Config.C
// unless "partialGeom" is set to true (=> $ALICE_ROOT/test/fpprod/Config.C).
//
const char* macroName = "MakeAlignmentObjs";
Bool_t toOCDB = kFALSE;
TString fileName("");
TString ocdbUriDirPath(ocdbOrDir);
if(ocdbUriDirPath.IsNull() || ocdbUriDirPath.IsWhitespace())
{
Error(macroName, "Output undefined! Set it either to a valid OCDB storage or to the output directory!");
return;
}else if(ocdbUriDirPath.Contains("local://") || ocdbUriDirPath.Contains("alien://folder=")){
// else ocdbUriDirPath is to be interpreted as an OCDB URI
toOCDB=kTRUE;
Printf("Objects will be saved in the OCDB %s",ocdbUriDirPath.Data());
}else{ // else ocdbUriDirPath is to be interpreted as a directory path
Printf("Objects will be saved in the file %s",ocdbUriDirPath.Data());
}
TMap misAligners;
TString modList(detList);
if(modList=="ALL") modList="ACORDE EMCAL FMD HMPID ITS MUON PMD PHOS T0 TRD TPC TOF VZERO ZDC";
Info(macroName, "Processing detectors: %s \n", modList.Data());
Printf("Creating %s misalignment for detectors: %s \n", misalType, modList.Data());
if(modList.Contains("EMCAL")){
AliEMCALMisAligner* misAlignerEMCAL = new AliEMCALMisAligner();
misAligners.Add(new TObjString("EMCAL"), misAlignerEMCAL);
}
if(modList.Contains("HMPID")){
AliHMPIDMisAligner* misAlignerHMPID = new AliHMPIDMisAligner();
misAligners.Add(new TObjString("HMPID"), misAlignerHMPID);
}
if(modList.Contains("ITS")){
AliITSMisAligner* misAlignerITS = new AliITSMisAligner();
misAligners.Add(new TObjString("ITS"), misAlignerITS);
}
if(modList.Contains("PMD")){
AliPMDMisAligner* misAlignerPMD = new AliPMDMisAligner();
misAligners.Add(new TObjString("PMD"), misAlignerPMD);
}
if(modList.Contains("T0")){
AliT0MisAligner* misAlignerT0 = new AliT0MisAligner();
misAligners.Add(new TObjString("T0"), misAlignerT0);
}
if(modList.Contains("TPC")){
AliTPCMisAligner* misAlignerTPC = new AliTPCMisAligner();
misAligners.Add(new TObjString("TPC"), misAlignerTPC);
}
if(modList.Contains("VZERO")){
AliVZEROMisAligner* misAlignerVZERO = new AliVZEROMisAligner();
misAligners.Add(new TObjString("VZERO"), misAlignerVZERO);
}
if(modList.Contains("ZDC")){
AliZDCMisAligner* misAlignerZDC = new AliZDCMisAligner();
misAligners.Add(new TObjString("ZDC"), misAlignerZDC);
}
// Load geometry from OCDB; update geometry before loading it if we are going to load
// the alignment objects to the OCDB
AliCDBManager* cdb = AliCDBManager::Instance();
if(!cdb->IsDefaultStorageSet()) cdb->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
cdb->SetRun(0);
AliCDBStorage* storage = 0;
if(!toOCDB){ //if we produce the objects into a file
AliGeomManager::LoadGeometry(); //load geom from default OCDB storage
}else{ // if we produce the objects in a OCDB storage
// update geometry in it
Info(macroName, "Updating geometry in OCDB storage %s",ocdbUriDirPath.Data());
gROOT->ProcessLine(".L $ALICE_ROOT/GRP/UpdateCDBIdealGeom.C");
if(partialGeom){
UpdateCDBIdealGeom(ocdbUriDirPath.Data(),"$ALICE_ROOT/test/fpprod/Config.C");
}else{
UpdateCDBIdealGeom(ocdbUriDirPath.Data(),"$ALICE_ROOT/macros/Config.C");
}
// load the same geometry from given OCDB storage
AliCDBPath path("GRP","Geometry","Data");
storage = cdb->GetStorage(ocdbUriDirPath.Data());
AliCDBEntry *entry = storage->Get(path.GetPath(),cdb->GetRun());
if(!entry) Fatal(macroName,"Couldn't load geometry data from OCDB!");
entry->SetOwner(0);
TGeoManager* geom = (TGeoManager*) entry->GetObject();
if (!geom) Fatal(macroName,"Couldn't find TGeoManager in the specified OCDB entry!");
AliGeomManager::SetGeometry(geom);
}
// run macro for non-sensitive modules
// (presently generates only FRAME alignment objects)
// gSystem->Exec("aliroot -b -q $ALICE_ROOT/GRP/MakeSTRUCTResMisAlignment.C"); !!!!!!!!!!!!!!!!!!!!!!!!!
// run macros for sensitive modules
TObjString *ostr;
TString strId;
TClonesArray* objsArray = 0;
TObjArray *detArray = modList.Tokenize(' ');
TIter iter(detArray);
while((ostr = (TObjString*) iter.Next())){
TString str(ostr->String()); // DET
TString arName(str.Data()); // name of the array in case saved into the file
arName += "AlignObjs";
AliMisAligner* misAligner = dynamic_cast<AliMisAligner*> (misAligners.GetValue(str));
misAligner->SetMisalType(misalType);
objsArray = misAligner->MakeAlObjsArray();
if(toOCDB)
{
strId=str;
strId+="/Align/Data";
AliCDBId id(strId.Data(),0,AliCDBRunRange::Infinity());
AliCDBMetaData *md = misAligner->GetCDBMetaData();
md->SetAliRootVersion(ALIROOT_SVN_BRANCH);
storage->Put(objsArray, id, md);
}else{
// save on file
fileName = ocdbUriDirPath;
fileName += str.Data();
fileName += misalType;
fileName += "MisAlignment.root";
TFile file(fileName.Data(),"RECREATE");
if(!file){
Error(macroName,"cannot open file for output\n");
return;
}
Info(macroName,"Saving alignment objects to the file %s", fileName);
file.cd();
file.WriteObject(objsArray,arName.Data(),"kSingleKey");
file.Close();
}
}
return;
}
<commit_msg>correctly handling the output directory path<commit_after>#include "ARVersion.h"
#if !defined(__CINT__) || defined(__MAKECINT__)
#include "TSystem.h"
#include "TROOT.h"
#include "TGeoManager.h"
#include "TObjString.h"
#include "TClonesArray.h"
#include "TError.h"
#include "AliGeomManager.h"
#include "AliCDBManager.h"
#include "AliCDBStorage.h"
#include "AliCDBPath.h"
#include "AliCDBEntry.h"
#include "AliCDBId.h"
#include "AliCDBMetaData.h"
#include "AliMisAligner.h"
#include "AliHMPIDMisAligner.h"
#include "AliITSMisAligner.h"
#include "AliPMDMisAligner.h"
#include "AliT0MisAligner.h"
#include "AliTPCMisAligner.h"
#include "AliVZEROMisAligner.h"
#include "AliZDCMisAligner.h"
#include <TString.h>
#endif
void MakeAlignmentObjs(const char* detList="ALL", const char* ocdbOrDir = "local://$HOME/ResidualMisAlignment", const char* misalType="residual", Bool_t partialGeom=kFALSE){
// Make alignment objects for all detectors listed in "detList"
// for the misalignment scenario passed as argument "misalType".
// "ocdbUriDirPath" argument is used as URI for an OCDB if it contains
// either the string "local;//" or the string "alien://folder=",
// otherwise it is used as the path of the directory where to
// put the files containing the alignment objects.
// The geometry used is the one produced with $ALICE_ROOT/macros/Config.C
// unless "partialGeom" is set to true (=> $ALICE_ROOT/test/fpprod/Config.C).
//
const char* macroName = "MakeAlignmentObjs";
Bool_t toOCDB = kFALSE;
TString fileName("");
TString ocdbUriDirPath(ocdbOrDir);
if(ocdbUriDirPath.IsNull() || ocdbUriDirPath.IsWhitespace())
{
Error(macroName, "Output undefined! Set it either to a valid OCDB storage or to the output directory!");
return;
}else if(ocdbUriDirPath.Contains("local://") || ocdbUriDirPath.Contains("alien://folder=")){
// else ocdbUriDirPath is to be interpreted as an OCDB URI
toOCDB=kTRUE;
Printf("Objects will be saved in the OCDB %s",ocdbUriDirPath.Data());
}else{ // else ocdbUriDirPath is to be interpreted as a directory path
gSystem->ExpandPathName(ocdbUriDirPath);
if(gSystem->AccessPathName(ocdbUriDirPath.Data()))
{
Printf("Directory \"%s\" where to save files does not yet exist! ... exiting!",ocdbUriDirPath.Data());
return;
}else{
Printf("Files with alignment objects will be saved in the directory %s",ocdbUriDirPath.Data());
}
}
TMap misAligners;
TString modList(detList);
if(modList=="ALL") modList="ACORDE EMCAL FMD HMPID ITS MUON PMD PHOS T0 TRD TPC TOF VZERO ZDC";
Info(macroName, "Processing detectors: %s \n", modList.Data());
Printf("Creating %s misalignment for detectors: %s \n", misalType, modList.Data());
if(modList.Contains("EMCAL")){
AliEMCALMisAligner* misAlignerEMCAL = new AliEMCALMisAligner();
misAligners.Add(new TObjString("EMCAL"), misAlignerEMCAL);
}
if(modList.Contains("HMPID")){
AliHMPIDMisAligner* misAlignerHMPID = new AliHMPIDMisAligner();
misAligners.Add(new TObjString("HMPID"), misAlignerHMPID);
}
if(modList.Contains("ITS")){
AliITSMisAligner* misAlignerITS = new AliITSMisAligner();
misAligners.Add(new TObjString("ITS"), misAlignerITS);
}
if(modList.Contains("PMD")){
AliPMDMisAligner* misAlignerPMD = new AliPMDMisAligner();
misAligners.Add(new TObjString("PMD"), misAlignerPMD);
}
if(modList.Contains("T0")){
AliT0MisAligner* misAlignerT0 = new AliT0MisAligner();
misAligners.Add(new TObjString("T0"), misAlignerT0);
}
if(modList.Contains("TPC")){
AliTPCMisAligner* misAlignerTPC = new AliTPCMisAligner();
misAligners.Add(new TObjString("TPC"), misAlignerTPC);
}
if(modList.Contains("VZERO")){
AliVZEROMisAligner* misAlignerVZERO = new AliVZEROMisAligner();
misAligners.Add(new TObjString("VZERO"), misAlignerVZERO);
}
if(modList.Contains("ZDC")){
AliZDCMisAligner* misAlignerZDC = new AliZDCMisAligner();
misAligners.Add(new TObjString("ZDC"), misAlignerZDC);
}
// Load geometry from OCDB; update geometry before loading it if we are going to load
// the alignment objects to the OCDB
AliCDBManager* cdb = AliCDBManager::Instance();
if(!cdb->IsDefaultStorageSet()) cdb->SetDefaultStorage("local://$ALICE_ROOT/OCDB");
cdb->SetRun(0);
AliCDBStorage* storage = 0;
if(!toOCDB){ //if we produce the objects into a file
AliGeomManager::LoadGeometry(); //load geom from default OCDB storage
}else{ // if we produce the objects in a OCDB storage
// update geometry in it
Info(macroName, "Updating geometry in OCDB storage %s",ocdbUriDirPath.Data());
gROOT->ProcessLine(".L $ALICE_ROOT/GRP/UpdateCDBIdealGeom.C");
if(partialGeom){
UpdateCDBIdealGeom(ocdbUriDirPath.Data(),"$ALICE_ROOT/test/fpprod/Config.C");
}else{
UpdateCDBIdealGeom(ocdbUriDirPath.Data(),"$ALICE_ROOT/macros/Config.C");
}
// load the same geometry from given OCDB storage
AliCDBPath path("GRP","Geometry","Data");
storage = cdb->GetStorage(ocdbUriDirPath.Data());
AliCDBEntry *entry = storage->Get(path.GetPath(),cdb->GetRun());
if(!entry) Fatal(macroName,"Couldn't load geometry data from OCDB!");
entry->SetOwner(0);
TGeoManager* geom = (TGeoManager*) entry->GetObject();
if (!geom) Fatal(macroName,"Couldn't find TGeoManager in the specified OCDB entry!");
AliGeomManager::SetGeometry(geom);
}
// run macro for non-sensitive modules
// (presently generates only FRAME alignment objects)
// gSystem->Exec("aliroot -b -q $ALICE_ROOT/GRP/MakeSTRUCTResMisAlignment.C"); !!!!!!!!!!!!!!!!!!!!!!!!!
// run macros for sensitive modules
TObjString *ostr;
TString strId;
TClonesArray* objsArray = 0;
TObjArray *detArray = modList.Tokenize(' ');
TIter iter(detArray);
while((ostr = (TObjString*) iter.Next())){
TString str(ostr->String()); // DET
TString arName(str.Data()); // name of the array in case saved into the file
arName += "AlignObjs";
AliMisAligner* misAligner = dynamic_cast<AliMisAligner*> (misAligners.GetValue(str));
misAligner->SetMisalType(misalType);
objsArray = misAligner->MakeAlObjsArray();
if(toOCDB)
{
strId=str;
strId+="/Align/Data";
AliCDBId id(strId.Data(),0,AliCDBRunRange::Infinity());
AliCDBMetaData *md = misAligner->GetCDBMetaData();
md->SetAliRootVersion(ALIROOT_SVN_BRANCH);
storage->Put(objsArray, id, md);
}else{
// save on file
fileName = ocdbUriDirPath;
fileName += "/";
fileName += str.Data();
fileName += misalType;
fileName += "MisAlignment.root";
TFile file(fileName.Data(),"RECREATE");
if(!file){
Error(macroName,"cannot open file for output\n");
return;
}
Info(macroName,"Saving alignment objects to the file %s", fileName.Data());
file.cd();
file.WriteObject(objsArray,arName.Data(),"kSingleKey");
file.Close();
}
}
return;
}
<|endoftext|> |
<commit_before>
#include "itkAdvancedBSplineDeformableTransform.h"
#include "itkGridScheduleComputer.h"
#include <ctime>
#include <iomanip>
//-------------------------------------------------------------------------------------
int main( int argc, char *argv[] )
{
/** Some basic type definitions.
* NOTE: don't change the dimension or the spline order, since the
* hard-coded ground truth depends on this.
*/
const unsigned int Dimension = 3;
const unsigned int SplineOrder = 3;
typedef float CoordinateRepresentationType;
//const double distance = 1e-3; // the allowable distance
//const double allowedTimeDifference = 0.1; // 10% is considered within limits
/** The number of calls to Evaluate(). This number gives reasonably
* fast test results in Release mode.
*/
unsigned int N = 1e5;
/** Check. */
if ( argc != 2 )
{
std::cerr << "ERROR: You should specify a text file with the B-spline "
<< "transformation parameters." << std::endl;
return 1;
}
/** Other typedefs. */
typedef itk::AdvancedBSplineDeformableTransform<
CoordinateRepresentationType, Dimension, SplineOrder > TransformType;
typedef TransformType::JacobianType JacobianType;
typedef TransformType::SpatialJacobianType SpatialJacobianType;
typedef TransformType::SpatialHessianType SpatialHessianType;
typedef TransformType::JacobianOfSpatialJacobianType JacobianOfSpatialJacobianType;
typedef TransformType::JacobianOfSpatialHessianType JacobianOfSpatialHessianType;
typedef TransformType::NonZeroJacobianIndicesType NonZeroJacobianIndicesType;
typedef TransformType::InputPointType InputPointType;
typedef TransformType::ParametersType ParametersType;
typedef itk::Image< CoordinateRepresentationType,
Dimension > InputImageType;
typedef InputImageType::RegionType RegionType;
typedef InputImageType::SizeType SizeType;
typedef InputImageType::IndexType IndexType;
typedef InputImageType::SpacingType SpacingType;
typedef InputImageType::PointType OriginType;
/** Create the transform. */
TransformType::Pointer transform = TransformType::New();
/** Setup the B-spline transform:
* (GridSize 44 43 35)
* (GridIndex 0 0 0)
* (GridSpacing 10.7832773148 11.2116431394 11.8648235177)
* (GridOrigin -237.6759555555 -239.9488431747 -344.2315805162)
*/
SizeType gridSize;
gridSize[ 0 ] = 44; gridSize[ 1 ] = 43; gridSize[ 2 ] = 35;
IndexType gridIndex;
gridIndex.Fill( 0 );
RegionType gridRegion;
gridRegion.SetSize( gridSize );
gridRegion.SetIndex( gridIndex );
SpacingType gridSpacing;
gridSpacing[ 0 ] = 10.7832773148;
gridSpacing[ 1 ] = 11.2116431394;
gridSpacing[ 2 ] = 11.8648235177;
OriginType gridOrigin;
gridOrigin[ 0 ] = -237.6759555555;
gridOrigin[ 1 ] = -239.9488431747;
gridOrigin[ 2 ] = -344.2315805162;
transform->SetGridOrigin( gridOrigin );
transform->SetGridSpacing( gridSpacing );
transform->SetGridRegion( gridRegion );
/** Now read the parameters as defined in the file par.txt. */
ParametersType parameters( transform->GetNumberOfParameters() );
//std::ifstream input( "D:/toolkits/elastix/src/Testing/par.txt" );
std::ifstream input( argv[ 1 ] );
if ( input.is_open() )
{
for ( unsigned int i = 0; i < parameters.GetSize(); ++i )
{
input >> parameters[ i ];
}
}
else
{
std::cerr << "ERROR: could not open the text file containing the "
<< "parameter values." << std::endl;
return 1;
}
transform->SetParameters( parameters );
/** Get the number of nonzero Jacobian indices. */
unsigned long nonzji = transform->GetNumberOfNonZeroJacobianIndices();
/** Declare variables. */
InputPointType inputPoint;
inputPoint.Fill( 4.1 );
JacobianType jacobian;
SpatialJacobianType spatialJacobian;
SpatialHessianType spatialHessian;
JacobianOfSpatialJacobianType jacobianOfSpatialJacobian;
JacobianOfSpatialHessianType jacobianOfSpatialHessian;
NonZeroJacobianIndicesType nzji;
/** Resize some of the variables. */
nzji.resize( nonzji );
jacobian.SetSize( Dimension, nonzji );
jacobianOfSpatialJacobian.resize( nonzji );
jacobianOfSpatialHessian.resize( nonzji );
/**
*
* Call functions for testing that they don't crash.
*
*/
/** The Jacobian. */
transform->GetJacobian( inputPoint, jacobian, nzji );
/** The spatial Jacobian. */
transform->GetSpatialJacobian( inputPoint, spatialJacobian );
/** The spatial Hessian. */
transform->GetSpatialHessian( inputPoint, spatialHessian );
/** The Jacobian of the spatial Jacobian. */
transform->GetJacobianOfSpatialJacobian( inputPoint,
jacobianOfSpatialJacobian, nzji );
transform->GetJacobianOfSpatialJacobian( inputPoint,
spatialJacobian, jacobianOfSpatialJacobian, nzji );
/** The Jacobian of the spatial Hessian. */
transform->GetJacobianOfSpatialHessian( inputPoint,
jacobianOfSpatialHessian, nzji );
transform->GetJacobianOfSpatialHessian( inputPoint,
spatialHessian, jacobianOfSpatialHessian, nzji );
/***
transform->GetSpatialHessian( inputPoint, spatialHessian );
for ( unsigned int i = 0; i < Dimension; ++i )
{
std::cerr << spatialHessian[ i ] << std::endl;
}
/***
transform->GetJacobianOfSpatialHessian( inputPoint,
spatialHessian, jacobianOfSpatialHessian, nzji );
for ( unsigned int mu = 0; mu < 2; ++mu )
{
for ( unsigned int i = 0; i < Dimension; ++i )
{
std::cerr << jacobianOfSpatialHessian[ mu ][ i ] << std::endl;
}
}
/**
*
* Call functions for timing.
*
*/
/** Time the implementation of the spatial Jacobian. */
clock_t startClock = clock();
for ( unsigned int i = 0; i < N; ++i )
{
transform->GetSpatialJacobian( inputPoint, spatialJacobian );
}
clock_t endClock = clock();
clock_t clockITK = endClock - startClock;
std::cerr << "The elapsed time for the spatial Jacobian is: "
<< clockITK << std::endl;
/** Time the implementation of the spatial Hessian. */
startClock = clock();
for ( unsigned int i = 0; i < N; ++i )
{
transform->GetSpatialHessian( inputPoint, spatialHessian );
}
endClock = clock();
clockITK = endClock - startClock;
std::cerr << "The elapsed time for the spatial Hessian is: "
<< clockITK << std::endl;
/** Time the implementation of the Jacobian of the spatial Jacobian. */
startClock = clock();
for ( unsigned int i = 0; i < N; ++i )
{
transform->GetJacobianOfSpatialJacobian( inputPoint,
jacobianOfSpatialJacobian, nzji );
// transform->GetJacobianOfSpatialJacobian( inputPoint,
// spatialJacobian, jacobianOfSpatialJacobian, nzji );
}
endClock = clock();
clockITK = endClock - startClock;
std::cerr << "The elapsed time for the Jacobian of the spatial Jacobian is: "
<< clockITK << std::endl;
/** Time the implementation of the Jacobian of the spatial Hessian. */
startClock = clock();
for ( unsigned int i = 0; i < N; ++i )
{
transform->GetJacobianOfSpatialHessian( inputPoint,
jacobianOfSpatialHessian, nzji );
// transform->GetJacobianOfSpatialHessian( inputPoint,
// spatialHessian, jacobianOfSpatialHessian, nzji );
}
endClock = clock();
clockITK = endClock - startClock;
std::cerr << "The elapsed time for the Jacobian of the spatial Hessian is: "
<< clockITK << std::endl;
/** Return a value. */
return 0;
} // end main
<commit_msg>MS:<commit_after>
#include "itkAdvancedBSplineDeformableTransform.h"
#include "itkGridScheduleComputer.h"
#include <ctime>
#include <iomanip>
//-------------------------------------------------------------------------------------
int main( int argc, char *argv[] )
{
/** Some basic type definitions.
* NOTE: don't change the dimension or the spline order, since the
* hard-coded ground truth depends on this.
*/
const unsigned int Dimension = 3;
const unsigned int SplineOrder = 3;
typedef float CoordinateRepresentationType;
//const double distance = 1e-3; // the allowable distance
//const double allowedTimeDifference = 0.1; // 10% is considered within limits
/** The number of calls to Evaluate(). This number gives reasonably
* fast test results in Release mode.
*/
unsigned int N = 1e5;
/** Check. */
if ( argc != 2 )
{
std::cerr << "ERROR: You should specify a text file with the B-spline "
<< "transformation parameters." << std::endl;
return 1;
}
/** Other typedefs. */
typedef itk::AdvancedBSplineDeformableTransform<
CoordinateRepresentationType, Dimension, SplineOrder > TransformType;
typedef TransformType::JacobianType JacobianType;
typedef TransformType::SpatialJacobianType SpatialJacobianType;
typedef TransformType::SpatialHessianType SpatialHessianType;
typedef TransformType::JacobianOfSpatialJacobianType JacobianOfSpatialJacobianType;
typedef TransformType::JacobianOfSpatialHessianType JacobianOfSpatialHessianType;
typedef TransformType::NonZeroJacobianIndicesType NonZeroJacobianIndicesType;
typedef TransformType::InputPointType InputPointType;
typedef TransformType::ParametersType ParametersType;
typedef itk::Image< CoordinateRepresentationType,
Dimension > InputImageType;
typedef InputImageType::RegionType RegionType;
typedef InputImageType::SizeType SizeType;
typedef InputImageType::IndexType IndexType;
typedef InputImageType::SpacingType SpacingType;
typedef InputImageType::PointType OriginType;
/** Create the transform. */
TransformType::Pointer transform = TransformType::New();
/** Setup the B-spline transform:
* (GridSize 44 43 35)
* (GridIndex 0 0 0)
* (GridSpacing 10.7832773148 11.2116431394 11.8648235177)
* (GridOrigin -237.6759555555 -239.9488431747 -344.2315805162)
*/
SizeType gridSize;
gridSize[ 0 ] = 44; gridSize[ 1 ] = 43; gridSize[ 2 ] = 35;
IndexType gridIndex;
gridIndex.Fill( 0 );
RegionType gridRegion;
gridRegion.SetSize( gridSize );
gridRegion.SetIndex( gridIndex );
SpacingType gridSpacing;
gridSpacing[ 0 ] = 10.7832773148;
gridSpacing[ 1 ] = 11.2116431394;
gridSpacing[ 2 ] = 11.8648235177;
OriginType gridOrigin;
gridOrigin[ 0 ] = -237.6759555555;
gridOrigin[ 1 ] = -239.9488431747;
gridOrigin[ 2 ] = -344.2315805162;
transform->SetGridOrigin( gridOrigin );
transform->SetGridSpacing( gridSpacing );
transform->SetGridRegion( gridRegion );
/** Now read the parameters as defined in the file par.txt. */
ParametersType parameters( transform->GetNumberOfParameters() );
//std::ifstream input( "D:/toolkits/elastix/src/Testing/par.txt" );
std::ifstream input( argv[ 1 ] );
if ( input.is_open() )
{
for ( unsigned int i = 0; i < parameters.GetSize(); ++i )
{
input >> parameters[ i ];
}
}
else
{
std::cerr << "ERROR: could not open the text file containing the "
<< "parameter values." << std::endl;
return 1;
}
transform->SetParameters( parameters );
/** Get the number of nonzero Jacobian indices. */
unsigned long nonzji = transform->GetNumberOfNonZeroJacobianIndices();
/** Declare variables. */
InputPointType inputPoint;
inputPoint.Fill( 4.1 );
JacobianType jacobian;
SpatialJacobianType spatialJacobian;
SpatialHessianType spatialHessian;
JacobianOfSpatialJacobianType jacobianOfSpatialJacobian;
JacobianOfSpatialHessianType jacobianOfSpatialHessian;
NonZeroJacobianIndicesType nzji;
/** Resize some of the variables. */
nzji.resize( nonzji );
jacobian.SetSize( Dimension, nonzji );
jacobianOfSpatialJacobian.resize( nonzji );
jacobianOfSpatialHessian.resize( nonzji );
/**
*
* Call functions for testing that they don't crash.
*
*/
/** The Jacobian. */
transform->GetJacobian( inputPoint, jacobian, nzji );
/** The spatial Jacobian. */
transform->GetSpatialJacobian( inputPoint, spatialJacobian );
/** The spatial Hessian. */
transform->GetSpatialHessian( inputPoint, spatialHessian );
/** The Jacobian of the spatial Jacobian. */
transform->GetJacobianOfSpatialJacobian( inputPoint,
jacobianOfSpatialJacobian, nzji );
transform->GetJacobianOfSpatialJacobian( inputPoint,
spatialJacobian, jacobianOfSpatialJacobian, nzji );
/** The Jacobian of the spatial Hessian. */
transform->GetJacobianOfSpatialHessian( inputPoint,
jacobianOfSpatialHessian, nzji );
transform->GetJacobianOfSpatialHessian( inputPoint,
spatialHessian, jacobianOfSpatialHessian, nzji );
/***
transform->GetSpatialHessian( inputPoint, spatialHessian );
for ( unsigned int i = 0; i < Dimension; ++i )
{
std::cerr << spatialHessian[ i ] << std::endl;
}
/***
transform->GetJacobianOfSpatialHessian( inputPoint,
spatialHessian, jacobianOfSpatialHessian, nzji );
for ( unsigned int mu = 0; mu < 2; ++mu )
{
for ( unsigned int i = 0; i < Dimension; ++i )
{
std::cerr << jacobianOfSpatialHessian[ mu ][ i ] << std::endl;
}
}
/**
*
* Call functions for timing.
*
*/
/** Time the implementation of the spatial Jacobian. */
clock_t startClock = clock();
for ( unsigned int i = 0; i < N; ++i )
{
transform->GetSpatialJacobian( inputPoint, spatialJacobian );
}
clock_t endClock = clock();
clock_t clockITK = endClock - startClock;
std::cerr << "The elapsed time for the spatial Jacobian is: "
<< clockITK << std::endl;
/** Time the implementation of the spatial Hessian. */
startClock = clock();
for ( unsigned int i = 0; i < N; ++i )
{
transform->GetSpatialHessian( inputPoint, spatialHessian );
}
endClock = clock();
clockITK = endClock - startClock;
std::cerr << "The elapsed time for the spatial Hessian is: "
<< clockITK << std::endl;
/** Time the implementation of the Jacobian of the spatial Jacobian. */
startClock = clock();
for ( unsigned int i = 0; i < N; ++i )
{
transform->GetJacobianOfSpatialJacobian( inputPoint,
jacobianOfSpatialJacobian, nzji );
// transform->GetJacobianOfSpatialJacobian( inputPoint,
// spatialJacobian, jacobianOfSpatialJacobian, nzji );
}
endClock = clock();
clockITK = endClock - startClock;
std::cerr << "The elapsed time for the Jacobian of the spatial Jacobian is: "
<< clockITK << std::endl;
/** Time the implementation of the Jacobian of the spatial Hessian. */
startClock = clock();
for ( unsigned int i = 0; i < N; ++i )
{
transform->GetJacobianOfSpatialHessian( inputPoint,
jacobianOfSpatialHessian, nzji );
// transform->GetJacobianOfSpatialHessian( inputPoint,
// spatialHessian, jacobianOfSpatialHessian, nzji );
}
endClock = clock();
clockITK = endClock - startClock;
std::cerr << "The elapsed time for the Jacobian of the spatial Hessian is: "
<< clockITK << std::endl;
/** Time the implementation of the spatial Jacobian and its Jacobian. */
startClock = clock();
for ( unsigned int i = 0; i < N; ++i )
{
transform->GetSpatialJacobian( inputPoint, spatialJacobian );
transform->GetJacobianOfSpatialJacobian( inputPoint,
jacobianOfSpatialJacobian, nzji );
}
endClock = clock();
clockITK = endClock - startClock;
std::cerr << "The elapsed time for the spatial Jacobian (2 func) is: "
<< clockITK << std::endl;
/** Time the implementation of the spatial Jacobian and its Jacobian. */
startClock = clock();
for ( unsigned int i = 0; i < N; ++i )
{
transform->GetJacobianOfSpatialJacobian( inputPoint,
spatialJacobian, jacobianOfSpatialJacobian, nzji );
}
endClock = clock();
clockITK = endClock - startClock;
std::cerr << "The elapsed time for the spatial Jacobian (1 func) is: "
<< clockITK << std::endl;
/** Time the implementation of the spatial Hessian. */
startClock = clock();
for ( unsigned int i = 0; i < N; ++i )
{
transform->GetSpatialHessian( inputPoint, spatialHessian );
transform->GetJacobianOfSpatialHessian( inputPoint,
jacobianOfSpatialHessian, nzji );
}
endClock = clock();
clockITK = endClock - startClock;
std::cerr << "The elapsed time for the spatial Hessian (2 func) is: "
<< clockITK << std::endl;
/** Time the implementation of the Jacobian of the spatial Hessian. */
startClock = clock();
for ( unsigned int i = 0; i < N; ++i )
{
transform->GetJacobianOfSpatialHessian( inputPoint,
spatialHessian, jacobianOfSpatialHessian, nzji );
}
endClock = clock();
clockITK = endClock - startClock;
std::cerr << "The elapsed time for the spatial Hessian (1 func) is: "
<< clockITK << std::endl;
/** Return a value. */
return 0;
} // end main
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: ToolPanel.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: kz $ $Date: 2005-07-14 10:23:39 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include "taskpane/ToolPanel.hxx"
#include "TaskPaneFocusManager.hxx"
#include "taskpane/TitleBar.hxx"
#include "taskpane/TitledControl.hxx"
#include "taskpane/ControlContainer.hxx"
#include "TaskPaneViewShell.hxx"
#include "taskpane/TaskPaneControlFactory.hxx"
#include "AccessibleTaskPane.hxx"
#include "strings.hrc"
#include "sdresid.hxx"
#ifndef _SV_DECOVIEW_HXX
#include <vcl/decoview.hxx>
#endif
#ifndef _SV_MENU_HXX
#include <vcl/menu.hxx>
#endif
namespace sd { namespace toolpanel {
/** Use WB_DIALOGCONTROL as argument for the Control constructor to
let VCL handle focus traveling. In addition the control
descriptors have to use WB_TABSTOP.
*/
ToolPanel::ToolPanel (
Window* pParentWindow,
TaskPaneViewShell& rViewShell)
: Control (pParentWindow, WB_DIALOGCONTROL),
mrViewShell(rViewShell),
TreeNode (NULL),
mbRearrangeActive(false)
{
SetBackground (Wallpaper ());
}
ToolPanel::~ToolPanel (void)
{
}
sal_uInt32 ToolPanel::AddControl (
::std::auto_ptr<ControlFactory> pControlFactory,
const String& rTitle,
ULONG nHelpId)
{
TitledControl* pTitledControl = new TitledControl (
this,
pControlFactory,
rTitle,
TitleBar::TBT_CONTROL_TITLE);
::std::auto_ptr<TreeNode> pChild (pTitledControl);
// Get the (grand) parent window which is focus-wise our parent.
Window* pParent = GetParent();
if (pParent != NULL)
pParent = pParent->GetParent();
FocusManager& rFocusManager (FocusManager::Instance());
int nControlCount (mpControlContainer->GetControlCount());
// Add a link up from every control to the parent. A down link is added
// only for the first control so that when entering the sub tool panel
// the focus is set to the first control.
if (pParent != NULL)
{
if (nControlCount == 1)
rFocusManager.RegisterDownLink(pParent, pChild->GetWindow());
rFocusManager.RegisterUpLink(pChild->GetWindow(), pParent);
}
// Replace the old links for cycling between first and last child by
// current ones.
if (nControlCount > 0)
{
::Window* pFirst = mpControlContainer->GetControl(0)->GetWindow();
::Window* pLast = mpControlContainer->GetControl(nControlCount-1)->GetWindow();
rFocusManager.RemoveLinks(pFirst,pLast);
rFocusManager.RemoveLinks(pLast,pFirst);
rFocusManager.RegisterLink(pFirst,pChild->GetWindow(), KEY_UP);
rFocusManager.RegisterLink(pChild->GetWindow(),pFirst, KEY_DOWN);
}
pTitledControl->GetTitleBar()->SetHelpId(nHelpId);
return mpControlContainer->AddControl (pChild);
}
void ToolPanel::ListHasChanged (void)
{
mpControlContainer->ListHasChanged ();
Rearrange ();
}
void ToolPanel::Resize (void)
{
Control::Resize();
Rearrange ();
}
void ToolPanel::RequestResize (void)
{
Invalidate();
Rearrange ();
}
/** Subtract the space for the title bars from the available space and
give the remaining space to the active control.
*/
void ToolPanel::Rearrange (void)
{
// Prevent recursive calls.
if ( ! mbRearrangeActive && mpControlContainer->GetVisibleControlCount()>0)
{
mbRearrangeActive = true;
SetBackground (Wallpaper ());
// Make the area that is covered by the children a little bit
// smaller so that a frame is visible arround them.
Rectangle aAvailableArea (Point(0,0), GetOutputSizePixel());
int nWidth = aAvailableArea.GetWidth();
sal_uInt32 nControlCount (mpControlContainer->GetControlCount());
sal_uInt32 nActiveControlIndex (
mpControlContainer->GetActiveControlIndex());
// Place title bars of controls above the active control and thereby
// determine the top of the active control.
sal_uInt32 nIndex;
for (nIndex=mpControlContainer->GetFirstIndex();
nIndex<nActiveControlIndex;
nIndex=mpControlContainer->GetNextIndex(nIndex))
{
TreeNode* pChild = mpControlContainer->GetControl(nIndex);
if (pChild != NULL)
{
sal_uInt32 nHeight = pChild->GetPreferredHeight (nWidth);
pChild->GetWindow()->SetPosSizePixel (
aAvailableArea.TopLeft(),
Size(nWidth, nHeight));
aAvailableArea.Top() += nHeight;
}
}
// Place title bars of controls below the active control and thereby
// determine the bottom of the active control.
for (nIndex=mpControlContainer->GetLastIndex();
nIndex<nControlCount && nIndex!=nActiveControlIndex;
nIndex=mpControlContainer->GetPreviousIndex(nIndex))
{
TreeNode* pChild = mpControlContainer->GetControl(nIndex);
if (pChild != NULL)
{
sal_uInt32 nHeight = pChild->GetPreferredHeight (nWidth);
pChild->GetWindow()->SetPosSizePixel (
Point(aAvailableArea.Left(),
aAvailableArea.Bottom()-nHeight+1),
Size(nWidth, nHeight));
aAvailableArea.Bottom() -= nHeight;
}
}
// Finally place the active control.
TreeNode* pChild = mpControlContainer->GetControl(nActiveControlIndex);
if (pChild != NULL)
pChild->GetWindow()->SetPosSizePixel (
aAvailableArea.TopLeft(),
aAvailableArea.GetSize());
mbRearrangeActive = false;
}
else
SetBackground (
Application::GetSettings().GetStyleSettings().GetDialogColor());
}
Size ToolPanel::GetPreferredSize (void)
{
return Size(300,300);
}
sal_Int32 ToolPanel::GetPreferredWidth (sal_Int32 nHeight)
{
return 300;
}
sal_Int32 ToolPanel::GetPreferredHeight (sal_Int32 nWidth)
{
return 300;
}
bool ToolPanel::IsResizable (void)
{
return true;
}
::Window* ToolPanel::GetWindow (void)
{
return this;
}
TaskPaneShellManager* ToolPanel::GetShellManager (void)
{
return &mrViewShell.GetSubShellManager();
}
::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible> ToolPanel::CreateAccessibleObject (
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible>& rxParent)
{
return new ::accessibility::AccessibleTaskPane (
rxParent,
String(SdResId(STR_RIGHT_PANE_TITLE)),
String(SdResId(STR_RIGHT_PANE_TITLE)),
*this);
}
} } // end of namespace ::sd::toolpanel
<commit_msg>INTEGRATION: CWS ooo19126 (1.7.62); FILE MERGED 2005/09/05 13:24:51 rt 1.7.62.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: ToolPanel.cxx,v $
*
* $Revision: 1.8 $
*
* last change: $Author: rt $ $Date: 2005-09-09 06:36:25 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#include "taskpane/ToolPanel.hxx"
#include "TaskPaneFocusManager.hxx"
#include "taskpane/TitleBar.hxx"
#include "taskpane/TitledControl.hxx"
#include "taskpane/ControlContainer.hxx"
#include "TaskPaneViewShell.hxx"
#include "taskpane/TaskPaneControlFactory.hxx"
#include "AccessibleTaskPane.hxx"
#include "strings.hrc"
#include "sdresid.hxx"
#ifndef _SV_DECOVIEW_HXX
#include <vcl/decoview.hxx>
#endif
#ifndef _SV_MENU_HXX
#include <vcl/menu.hxx>
#endif
namespace sd { namespace toolpanel {
/** Use WB_DIALOGCONTROL as argument for the Control constructor to
let VCL handle focus traveling. In addition the control
descriptors have to use WB_TABSTOP.
*/
ToolPanel::ToolPanel (
Window* pParentWindow,
TaskPaneViewShell& rViewShell)
: Control (pParentWindow, WB_DIALOGCONTROL),
mrViewShell(rViewShell),
TreeNode (NULL),
mbRearrangeActive(false)
{
SetBackground (Wallpaper ());
}
ToolPanel::~ToolPanel (void)
{
}
sal_uInt32 ToolPanel::AddControl (
::std::auto_ptr<ControlFactory> pControlFactory,
const String& rTitle,
ULONG nHelpId)
{
TitledControl* pTitledControl = new TitledControl (
this,
pControlFactory,
rTitle,
TitleBar::TBT_CONTROL_TITLE);
::std::auto_ptr<TreeNode> pChild (pTitledControl);
// Get the (grand) parent window which is focus-wise our parent.
Window* pParent = GetParent();
if (pParent != NULL)
pParent = pParent->GetParent();
FocusManager& rFocusManager (FocusManager::Instance());
int nControlCount (mpControlContainer->GetControlCount());
// Add a link up from every control to the parent. A down link is added
// only for the first control so that when entering the sub tool panel
// the focus is set to the first control.
if (pParent != NULL)
{
if (nControlCount == 1)
rFocusManager.RegisterDownLink(pParent, pChild->GetWindow());
rFocusManager.RegisterUpLink(pChild->GetWindow(), pParent);
}
// Replace the old links for cycling between first and last child by
// current ones.
if (nControlCount > 0)
{
::Window* pFirst = mpControlContainer->GetControl(0)->GetWindow();
::Window* pLast = mpControlContainer->GetControl(nControlCount-1)->GetWindow();
rFocusManager.RemoveLinks(pFirst,pLast);
rFocusManager.RemoveLinks(pLast,pFirst);
rFocusManager.RegisterLink(pFirst,pChild->GetWindow(), KEY_UP);
rFocusManager.RegisterLink(pChild->GetWindow(),pFirst, KEY_DOWN);
}
pTitledControl->GetTitleBar()->SetHelpId(nHelpId);
return mpControlContainer->AddControl (pChild);
}
void ToolPanel::ListHasChanged (void)
{
mpControlContainer->ListHasChanged ();
Rearrange ();
}
void ToolPanel::Resize (void)
{
Control::Resize();
Rearrange ();
}
void ToolPanel::RequestResize (void)
{
Invalidate();
Rearrange ();
}
/** Subtract the space for the title bars from the available space and
give the remaining space to the active control.
*/
void ToolPanel::Rearrange (void)
{
// Prevent recursive calls.
if ( ! mbRearrangeActive && mpControlContainer->GetVisibleControlCount()>0)
{
mbRearrangeActive = true;
SetBackground (Wallpaper ());
// Make the area that is covered by the children a little bit
// smaller so that a frame is visible arround them.
Rectangle aAvailableArea (Point(0,0), GetOutputSizePixel());
int nWidth = aAvailableArea.GetWidth();
sal_uInt32 nControlCount (mpControlContainer->GetControlCount());
sal_uInt32 nActiveControlIndex (
mpControlContainer->GetActiveControlIndex());
// Place title bars of controls above the active control and thereby
// determine the top of the active control.
sal_uInt32 nIndex;
for (nIndex=mpControlContainer->GetFirstIndex();
nIndex<nActiveControlIndex;
nIndex=mpControlContainer->GetNextIndex(nIndex))
{
TreeNode* pChild = mpControlContainer->GetControl(nIndex);
if (pChild != NULL)
{
sal_uInt32 nHeight = pChild->GetPreferredHeight (nWidth);
pChild->GetWindow()->SetPosSizePixel (
aAvailableArea.TopLeft(),
Size(nWidth, nHeight));
aAvailableArea.Top() += nHeight;
}
}
// Place title bars of controls below the active control and thereby
// determine the bottom of the active control.
for (nIndex=mpControlContainer->GetLastIndex();
nIndex<nControlCount && nIndex!=nActiveControlIndex;
nIndex=mpControlContainer->GetPreviousIndex(nIndex))
{
TreeNode* pChild = mpControlContainer->GetControl(nIndex);
if (pChild != NULL)
{
sal_uInt32 nHeight = pChild->GetPreferredHeight (nWidth);
pChild->GetWindow()->SetPosSizePixel (
Point(aAvailableArea.Left(),
aAvailableArea.Bottom()-nHeight+1),
Size(nWidth, nHeight));
aAvailableArea.Bottom() -= nHeight;
}
}
// Finally place the active control.
TreeNode* pChild = mpControlContainer->GetControl(nActiveControlIndex);
if (pChild != NULL)
pChild->GetWindow()->SetPosSizePixel (
aAvailableArea.TopLeft(),
aAvailableArea.GetSize());
mbRearrangeActive = false;
}
else
SetBackground (
Application::GetSettings().GetStyleSettings().GetDialogColor());
}
Size ToolPanel::GetPreferredSize (void)
{
return Size(300,300);
}
sal_Int32 ToolPanel::GetPreferredWidth (sal_Int32 nHeight)
{
return 300;
}
sal_Int32 ToolPanel::GetPreferredHeight (sal_Int32 nWidth)
{
return 300;
}
bool ToolPanel::IsResizable (void)
{
return true;
}
::Window* ToolPanel::GetWindow (void)
{
return this;
}
TaskPaneShellManager* ToolPanel::GetShellManager (void)
{
return &mrViewShell.GetSubShellManager();
}
::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible> ToolPanel::CreateAccessibleObject (
const ::com::sun::star::uno::Reference<
::com::sun::star::accessibility::XAccessible>& rxParent)
{
return new ::accessibility::AccessibleTaskPane (
rxParent,
String(SdResId(STR_RIGHT_PANE_TITLE)),
String(SdResId(STR_RIGHT_PANE_TITLE)),
*this);
}
} } // end of namespace ::sd::toolpanel
<|endoftext|> |
<commit_before>#include "CanGateway.h"
//Output to a serial CAN adapter instead of directly to a CAN bus
#define SERIALTEST 0
#define DEBUG 0
/******************************************************************
* CanGateway()
* Constructor
*
* Initializes the queues and ports necessary for communication
* with ROS. Does not initialize CAN communication.
******************************************************************/
CanGateway::CanGateway(const std::string& name):
TaskContext(name){
this->upQueue = new queue<canMsg>();
this->downQueue = new queue<canMsg>();
this->inPort = new InputPort<hubomsg::CanMessage>("can_down");
this->outPort = new OutputPort<hubomsg::CanMessage>("can_up");
this->addEventPort(*inPort);
this->addPort(*outPort);
tempYaw = 0;
tempRoll = 0;
}
CanGateway::~CanGateway(){
}
/******************************************************************
* strToSerial()
*
* Converts a std::string formatted CAN packet into a character
* array for communication over USB. Adds a 0x0D (carriage return)
* onto the end of the array as per the protocol.
*
* Protocol is tested for the EasySync USB2-F-7x01 adapter
*
* Paramters:
* packet - a string representation of a CAN packet
*
* Returns a character array representation of the input string
* with a trailing carriage return.
******************************************************************/
char* CanGateway::strToSerial(string packet){
char* data = new char[packet.length() + 1];
strcpy(data, packet.c_str());
data[packet.length()] = (char) 0x0D;
return data;
}
/******************************************************************
* transmit()
*
* Sends a canmsg_t (can4linux) packet over a hardware channel.
*
* Parameters:
* packet - a canmsg_t formatted packet to transmit to hardware
*
* Returns true if data was sent successfully, false otherwise.
******************************************************************/
bool CanGateway::transmit(canmsg_t* packet){
int sent = 0;
//Make sure there's an outbound channel
if (this->channel > 0){
//Amount to send is always 1 for canmsg_t (see can4linux.h)
sent = write(this->channel, packet, 1);
}
if (sent < 1){
//Not all the data was sent
std::cout << "Data transmission error" << std::endl;
return false;
}
return true;
}
/******************************************************************
* transmit()
*
* Sends a char* packet over a hardware channel.
*
* Parameters:
* packet - a char* formatted packet to transmit to hardware
*
* Returns true if data was sent successfully, false otherwise.
******************************************************************/
bool CanGateway::transmit(char* packet){
int sent = 0;
//Make sure there's an outbound channel
if (this->channel > 0){
sent = write(this->channel, packet, strlen(packet));
}
if (sent < strlen(packet)){
//Not all the data was sent
return false;
}
return true;
}
/******************************************************************
* openCanConnection()
*
* Opens a hardware channel file descriptor for communication.
*
* Parameters:
* path - the path to a file descriptor (e.g. /dev/ttyUSB0)
*
* Returns the channel number to use for communication.
******************************************************************/
int CanGateway::openCanConnection(char* path){
//Read/Write and non-blocking. Should be the same for
//serial or CAN hardware.
int channel = open(path, O_RDWR | O_NONBLOCK);
return channel;
}
/******************************************************************
* initConnection()
*
* Initializes a CAN connection. Sends the appropriate packets to
* set channel speed and open a connection, if necessary.
*
* Paramters:
* channel - the channel to initialize. obtained by a successful
* call to openCanConnection()
******************************************************************/
void CanGateway::initConnection(int channel, int bitrate){
if (SERIALTEST){
//Send speed and open packet
transmit(strToSerial("s8"));
transmit(strToSerial("O"));
}
else{
Config_par_t cfg;
volatile Command_par_t cmd;
cmd.cmd = CMD_STOP;
ioctl(channel, CAN_IOCTL_COMMAND, &cmd);
cfg.target = CONF_TIMING;
cfg.val1 = (unsigned int)bitrate;
ioctl(channel, CAN_IOCTL_CONFIG, &cfg);
cmd.cmd = CMD_START;
ioctl(channel, CAN_IOCTL_COMMAND, &cmd);
}
}
/******************************************************************
* closeCanConnection()
*
* Closes a CAN connection. Sends the appropriate packets to close
* the connection if necessary.
*
* Parameters:
* channel - the channel to close. obtained by a successful call
* to openCanConnection()
******************************************************************/
void CanGateway::closeCanConnection(int channel){
if (SERIALTEST){
//Send close packet
transmit(strToSerial("C"));
}
else{
volatile Command_par_t cmd;
cmd.cmd = CMD_STOP;
ioctl(channel, CAN_IOCTL_COMMAND, &cmd);
}
close(channel);
}
/******************************************************************
* recvFromRos()
*
* Attempts to receive new data from the subscribed ROS topic. Adds
* new data (if available) to the hardware send queue.
******************************************************************/
void CanGateway::recvFromRos(){
hubomsg::CanMessage inMsg = hubomsg::CanMessage();
canMsg can_message;
//If a new message has come in from ROS, grab the CAN information
while (NewData==this->inPort->read(inMsg)){
can_message = canMsg((boardNum)inMsg.bno, (messageType)inMsg.mType, (cmdType)inMsg.cmdType,
inMsg.r1, inMsg.r2, inMsg.r3, inMsg.r4, inMsg.r5, inMsg.r6, inMsg.r7, inMsg.r8);
//Add message to queue
//if (!this->downQueue->empty())
//this->downQueue->pop();
if (inMsg.bno == BNO_R_HIP_YAW_ROLL && inMsg.mType == TX_REF && inMsg.cmdType == 2) {
tempYaw = inMsg.r1;
tempRoll = inMsg.r2;
} else
this->downQueue->push(can_message);
//std::cout << this->downQueue->size() << std::endl;
}
}
/******************************************************************
* transmitToRos()
*
* Transmits all queued messages from hardware back up to ROS.
******************************************************************/
void CanGateway::transmitToRos(){
//Flush our upstream queue out to the ROS bus
canMsg out;
for (int i = 0; i < upQueue->size(); i++){
hubomsg::CanMessage upstream = hubomsg::CanMessage();
out = upQueue->front();
upQueue->pop();
//Set up ROS message parameters
upstream.bno = out.getBNO();
upstream.mType = out.getType();
upstream.cmdType = out.getCmd();
upstream.r1 = out.getR1();
upstream.r2 = out.getR2();
upstream.r3 = out.getR3();
upstream.r4 = out.getR4();
upstream.r5 = out.getR5();
upstream.r6 = out.getR6();
upstream.r7 = out.getR7();
upstream.r8 = out.getR8();
this->outPort->write(upstream);
}
}
/******************************************************************
* getInputPort()
*
* Returns the InputPort used for ROS communication.
******************************************************************/
InputPort<hubomsg::CanMessage>* CanGateway::getInputPort(){
return this->inPort;
}
/******************************************************************
* getOutputPort()
*
* Returns the OutputPort used for ROS communication.
******************************************************************/
OutputPort<hubomsg::CanMessage>* CanGateway::getOutputPort(){
return this->outPort;
}
/******************************************************************
* runTick()
*
* Called each clock interval. Sends the next message in the queue
* to the hardware.
******************************************************************/
void CanGateway::runTick(){
canmsg_t** rx = new canmsg_t*[5];
//At each clock interval (50 ms?) send a message out to the hardware.
if (downQueue->empty()){
downQueue->push(canMsg((boardNum)BNO_R_HIP_YAW_ROLL, (messageType)TX_REF, (cmdType)2,
temp_yaw, temp_roll, 0, 0, 0, 0, 0, 0));
}
canMsg out_message = this->downQueue->front();
this->downQueue->pop();
if (SERIALTEST){
//Format message for serial output
char* data = strToSerial(out_message.toSerial());
this->transmit(data);
}
else {
//Format message for CAN output
canmsg_t* data = out_message.toCAN();
this->transmit(data);
}
int messages_read = 0;
//Also make an attempt to read in from hardware
if (SERIALTEST){
}
else {
messages_read = read(this->channel, &rx, 5);
if (messages_read > 0){
for (int i = 0; i < messages_read; i++){
//Rebuild a canMsg and add it to the upstream buffer
this->upQueue->push(canMsg::fromLineType(rx[i]));
//std::cout << "read in a message from CAN" << std::endl;
}
}
}
}
/******************************************************************
* startHook()
*
* Called at start.
******************************************************************/
bool CanGateway::startHook(){
//@TODO: This should be some sort of parameter...not hardcoded
this->channel = openCanConnection("/dev/can0");
std::cout << "Opened CAN connection on channel " << channel << std::endl;
if (this->channel > -1){
initConnection(this->channel, 1000);
canMsg name_info = canMsg(BNO_R_HIP_YAW_ROLL, TX_MOTOR_CMD, CMD_SETREQ_BOARD_INFO,
0x05, 0, 0, 0, 0, 0, 0, 0);
canMsg hip_on = canMsg(BNO_R_HIP_YAW_ROLL, TX_MOTOR_CMD, CMD_HIP_ENABLE,
0x01, 0, 0, 0, 0, 0, 0, 0);
canMsg run = canMsg(BNO_R_HIP_YAW_ROLL, TX_MOTOR_CMD, CMD_CONTROLLER_ON,
0, 0, 0, 0, 0, 0, 0, 0);
name_info.printme();
hip_on.printme();
run.printme();
// transmit(name_info.toCAN());
// transmit(hip_on.toCAN());
// transmit(run.toCAN());
// write(channel, name_info.toCAN(), 1);
// write(channel, hip_on.toCAN(), 1);
// write(channel, run.toCAN(), 1);
return 1;
}
return 0;
}
/******************************************************************
* updateHook()
*
* Called each iteration.
******************************************************************/
void CanGateway::updateHook(){
//runTick();
recvFromRos();
canmsg_t rx[5];
if (!this->downQueue->empty()){
transmit(this->downQueue->front().toCAN());
this->downQueue->pop();
}
if (this->channel > 0){
int messages_read = read(this->channel, &rx, 5);
if (messages_read > 0){
//std::cout << "read in a message from CAN" << std::endl;
for (int i = 0; i < messages_read; i++){
//Rebuild a canMsg and add it to the upstream buffer
this->upQueue->push(canMsg::fromLineType(&rx[i]));
//std::cout << "read in a message from CAN" << std::endl;
}
}
}
transmitToRos();
}
/******************************************************************
* startHook()
*
* Called at shutdown.
******************************************************************/
void CanGateway::stopHook(){
closeCanConnection(this->channel);
}
ORO_LIST_COMPONENT_TYPE(CanGateway)
<commit_msg>Oops... Don't ask what I forgot.<commit_after>#include "CanGateway.h"
//Output to a serial CAN adapter instead of directly to a CAN bus
#define SERIALTEST 0
#define DEBUG 0
/******************************************************************
* CanGateway()
* Constructor
*
* Initializes the queues and ports necessary for communication
* with ROS. Does not initialize CAN communication.
******************************************************************/
CanGateway::CanGateway(const std::string& name):
TaskContext(name){
this->upQueue = new queue<canMsg>();
this->downQueue = new queue<canMsg>();
this->inPort = new InputPort<hubomsg::CanMessage>("can_down");
this->outPort = new OutputPort<hubomsg::CanMessage>("can_up");
this->addEventPort(*inPort);
this->addPort(*outPort);
tempYaw = 0;
tempRoll = 0;
}
CanGateway::~CanGateway(){
}
/******************************************************************
* strToSerial()
*
* Converts a std::string formatted CAN packet into a character
* array for communication over USB. Adds a 0x0D (carriage return)
* onto the end of the array as per the protocol.
*
* Protocol is tested for the EasySync USB2-F-7x01 adapter
*
* Paramters:
* packet - a string representation of a CAN packet
*
* Returns a character array representation of the input string
* with a trailing carriage return.
******************************************************************/
char* CanGateway::strToSerial(string packet){
char* data = new char[packet.length() + 1];
strcpy(data, packet.c_str());
data[packet.length()] = (char) 0x0D;
return data;
}
/******************************************************************
* transmit()
*
* Sends a canmsg_t (can4linux) packet over a hardware channel.
*
* Parameters:
* packet - a canmsg_t formatted packet to transmit to hardware
*
* Returns true if data was sent successfully, false otherwise.
******************************************************************/
bool CanGateway::transmit(canmsg_t* packet){
int sent = 0;
//Make sure there's an outbound channel
if (this->channel > 0){
//Amount to send is always 1 for canmsg_t (see can4linux.h)
sent = write(this->channel, packet, 1);
}
if (sent < 1){
//Not all the data was sent
std::cout << "Data transmission error" << std::endl;
return false;
}
return true;
}
/******************************************************************
* transmit()
*
* Sends a char* packet over a hardware channel.
*
* Parameters:
* packet - a char* formatted packet to transmit to hardware
*
* Returns true if data was sent successfully, false otherwise.
******************************************************************/
bool CanGateway::transmit(char* packet){
int sent = 0;
//Make sure there's an outbound channel
if (this->channel > 0){
sent = write(this->channel, packet, strlen(packet));
}
if (sent < strlen(packet)){
//Not all the data was sent
return false;
}
return true;
}
/******************************************************************
* openCanConnection()
*
* Opens a hardware channel file descriptor for communication.
*
* Parameters:
* path - the path to a file descriptor (e.g. /dev/ttyUSB0)
*
* Returns the channel number to use for communication.
******************************************************************/
int CanGateway::openCanConnection(char* path){
//Read/Write and non-blocking. Should be the same for
//serial or CAN hardware.
int channel = open(path, O_RDWR | O_NONBLOCK);
return channel;
}
/******************************************************************
* initConnection()
*
* Initializes a CAN connection. Sends the appropriate packets to
* set channel speed and open a connection, if necessary.
*
* Paramters:
* channel - the channel to initialize. obtained by a successful
* call to openCanConnection()
******************************************************************/
void CanGateway::initConnection(int channel, int bitrate){
if (SERIALTEST){
//Send speed and open packet
transmit(strToSerial("s8"));
transmit(strToSerial("O"));
}
else{
Config_par_t cfg;
volatile Command_par_t cmd;
cmd.cmd = CMD_STOP;
ioctl(channel, CAN_IOCTL_COMMAND, &cmd);
cfg.target = CONF_TIMING;
cfg.val1 = (unsigned int)bitrate;
ioctl(channel, CAN_IOCTL_CONFIG, &cfg);
cmd.cmd = CMD_START;
ioctl(channel, CAN_IOCTL_COMMAND, &cmd);
}
}
/******************************************************************
* closeCanConnection()
*
* Closes a CAN connection. Sends the appropriate packets to close
* the connection if necessary.
*
* Parameters:
* channel - the channel to close. obtained by a successful call
* to openCanConnection()
******************************************************************/
void CanGateway::closeCanConnection(int channel){
if (SERIALTEST){
//Send close packet
transmit(strToSerial("C"));
}
else{
volatile Command_par_t cmd;
cmd.cmd = CMD_STOP;
ioctl(channel, CAN_IOCTL_COMMAND, &cmd);
}
close(channel);
}
/******************************************************************
* recvFromRos()
*
* Attempts to receive new data from the subscribed ROS topic. Adds
* new data (if available) to the hardware send queue.
******************************************************************/
void CanGateway::recvFromRos(){
hubomsg::CanMessage inMsg = hubomsg::CanMessage();
canMsg can_message;
//If a new message has come in from ROS, grab the CAN information
while (NewData==this->inPort->read(inMsg)){
can_message = canMsg((boardNum)inMsg.bno, (messageType)inMsg.mType, (cmdType)inMsg.cmdType,
inMsg.r1, inMsg.r2, inMsg.r3, inMsg.r4, inMsg.r5, inMsg.r6, inMsg.r7, inMsg.r8);
//Add message to queue
//if (!this->downQueue->empty())
//this->downQueue->pop();
if (inMsg.bno == BNO_R_HIP_YAW_ROLL && inMsg.mType == TX_REF && inMsg.cmdType == 2) {
tempYaw = inMsg.r1;
tempRoll = inMsg.r2;
} else
this->downQueue->push(can_message);
//std::cout << this->downQueue->size() << std::endl;
}
}
/******************************************************************
* transmitToRos()
*
* Transmits all queued messages from hardware back up to ROS.
******************************************************************/
void CanGateway::transmitToRos(){
//Flush our upstream queue out to the ROS bus
canMsg out;
for (int i = 0; i < upQueue->size(); i++){
hubomsg::CanMessage upstream = hubomsg::CanMessage();
out = upQueue->front();
upQueue->pop();
//Set up ROS message parameters
upstream.bno = out.getBNO();
upstream.mType = out.getType();
upstream.cmdType = out.getCmd();
upstream.r1 = out.getR1();
upstream.r2 = out.getR2();
upstream.r3 = out.getR3();
upstream.r4 = out.getR4();
upstream.r5 = out.getR5();
upstream.r6 = out.getR6();
upstream.r7 = out.getR7();
upstream.r8 = out.getR8();
this->outPort->write(upstream);
}
}
/******************************************************************
* getInputPort()
*
* Returns the InputPort used for ROS communication.
******************************************************************/
InputPort<hubomsg::CanMessage>* CanGateway::getInputPort(){
return this->inPort;
}
/******************************************************************
* getOutputPort()
*
* Returns the OutputPort used for ROS communication.
******************************************************************/
OutputPort<hubomsg::CanMessage>* CanGateway::getOutputPort(){
return this->outPort;
}
/******************************************************************
* runTick()
*
* Called each clock interval. Sends the next message in the queue
* to the hardware.
******************************************************************/
void CanGateway::runTick(){
canmsg_t** rx = new canmsg_t*[5];
//At each clock interval (50 ms?) send a message out to the hardware.
if (downQueue->empty()){
downQueue->push(canMsg((boardNum)BNO_R_HIP_YAW_ROLL, (messageType)TX_REF, (cmdType)2,
tempYaw, tempRoll, 0, 0, 0, 0, 0, 0));
}
canMsg out_message = this->downQueue->front();
this->downQueue->pop();
if (SERIALTEST){
//Format message for serial output
char* data = strToSerial(out_message.toSerial());
this->transmit(data);
}
else {
//Format message for CAN output
canmsg_t* data = out_message.toCAN();
this->transmit(data);
}
int messages_read = 0;
//Also make an attempt to read in from hardware
if (SERIALTEST){
}
else {
messages_read = read(this->channel, &rx, 5);
if (messages_read > 0){
for (int i = 0; i < messages_read; i++){
//Rebuild a canMsg and add it to the upstream buffer
this->upQueue->push(canMsg::fromLineType(rx[i]));
//std::cout << "read in a message from CAN" << std::endl;
}
}
}
}
/******************************************************************
* startHook()
*
* Called at start.
******************************************************************/
bool CanGateway::startHook(){
//@TODO: This should be some sort of parameter...not hardcoded
this->channel = openCanConnection("/dev/can0");
std::cout << "Opened CAN connection on channel " << channel << std::endl;
if (this->channel > -1){
initConnection(this->channel, 1000);
canMsg name_info = canMsg(BNO_R_HIP_YAW_ROLL, TX_MOTOR_CMD, CMD_SETREQ_BOARD_INFO,
0x05, 0, 0, 0, 0, 0, 0, 0);
canMsg hip_on = canMsg(BNO_R_HIP_YAW_ROLL, TX_MOTOR_CMD, CMD_HIP_ENABLE,
0x01, 0, 0, 0, 0, 0, 0, 0);
canMsg run = canMsg(BNO_R_HIP_YAW_ROLL, TX_MOTOR_CMD, CMD_CONTROLLER_ON,
0, 0, 0, 0, 0, 0, 0, 0);
name_info.printme();
hip_on.printme();
run.printme();
// transmit(name_info.toCAN());
// transmit(hip_on.toCAN());
// transmit(run.toCAN());
// write(channel, name_info.toCAN(), 1);
// write(channel, hip_on.toCAN(), 1);
// write(channel, run.toCAN(), 1);
return 1;
}
return 0;
}
/******************************************************************
* updateHook()
*
* Called each iteration.
******************************************************************/
void CanGateway::updateHook(){
//runTick();
recvFromRos();
canmsg_t rx[5];
if (!this->downQueue->empty()){
transmit(this->downQueue->front().toCAN());
this->downQueue->pop();
}
if (this->channel > 0){
int messages_read = read(this->channel, &rx, 5);
if (messages_read > 0){
//std::cout << "read in a message from CAN" << std::endl;
for (int i = 0; i < messages_read; i++){
//Rebuild a canMsg and add it to the upstream buffer
this->upQueue->push(canMsg::fromLineType(&rx[i]));
//std::cout << "read in a message from CAN" << std::endl;
}
}
}
transmitToRos();
}
/******************************************************************
* startHook()
*
* Called at shutdown.
******************************************************************/
void CanGateway::stopHook(){
closeCanConnection(this->channel);
}
ORO_LIST_COMPONENT_TYPE(CanGateway)
<|endoftext|> |
<commit_before>#include <stan/math/prim.hpp>
#include <gtest/gtest.h>
#include <cmath>
#include <limits>
#include <type_traits>
#include <vector>
TEST(MathFunctions, value_of) {
using stan::math::value_of;
double x = 5.0;
EXPECT_FLOAT_EQ(5.0, value_of(x));
EXPECT_FLOAT_EQ(5.0, value_of(5));
}
TEST(MathFunctions, value_of_nan) {
double nan = std::numeric_limits<double>::quiet_NaN();
EXPECT_TRUE(std::isnan(stan::math::value_of(nan)));
}
TEST(MathMatrixPrimArr, value_of) {
using stan::math::value_of;
using std::vector;
vector<double> a;
for (size_t i = 0; i < 10; ++i)
a.push_back(i + 1);
vector<double> b;
for (size_t i = 10; i < 15; ++i)
b.push_back(i + 1);
vector<double> d_a = value_of(a);
vector<double> d_b = value_of(b);
for (int i = 0; i < 5; ++i)
EXPECT_FLOAT_EQ(b[i], d_b[i]);
for (int i = 0; i < 10; ++i)
EXPECT_FLOAT_EQ(a[i], d_a[i]);
}
TEST(MathFunctions, value_of_int_return_type_short_circuit) {
std::vector<int> a(5, 0);
EXPECT_FALSE((std::is_same<decltype(stan::math::value_of(a)),
std::vector<int>>::value));
EXPECT_FALSE((std::is_same<decltype(stan::math::value_of(a)),
std::vector<int>&>::value));
EXPECT_FALSE((std::is_same<decltype(stan::math::value_of(a)),
const std::vector<int>>::value));
EXPECT_TRUE((std::is_same<decltype(stan::math::value_of(a)),
const std::vector<int>&>::value));
}
TEST(MathFunctions, value_of_double_return_type_short_circuit) {
std::vector<double> a(5, 0);
EXPECT_FALSE((std::is_same<decltype(stan::math::value_of(a)),
std::vector<double>>::value));
EXPECT_FALSE((std::is_same<decltype(stan::math::value_of(a)),
std::vector<double>&>::value));
EXPECT_FALSE((std::is_same<decltype(stan::math::value_of(a)),
const std::vector<double>>::value));
EXPECT_TRUE((std::is_same<decltype(stan::math::value_of(a)),
const std::vector<double>&>::value));
}
TEST(MathMatrixPrimMat, value_of) {
using stan::math::value_of;
Eigen::Matrix<double, 2, 5> a;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 5; j++)
a(i, j) = i * 5 + j;
Eigen::Matrix<double, 5, 1> b;
for (int i = 0; i < 5; i++)
for (int j = 0; j < 1; j++)
b(i, j) = 10 + i * 5 + j;
Eigen::MatrixXd d_a = value_of(a);
Eigen::VectorXd d_b = value_of(b);
for (int i = 0; i < 5; ++i)
EXPECT_FLOAT_EQ(b(i), d_b(i));
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 5; ++j)
EXPECT_FLOAT_EQ(a(i, j), d_a(i, j));
}
TEST(MathFunctions, value_of_return_type_short_circuit_vector_xd) {
Eigen::Matrix<double, Eigen::Dynamic, 1> a(5);
EXPECT_FALSE((std::is_same<decltype(stan::math::value_of(a)),
Eigen::Matrix<double, Eigen::Dynamic, 1>>::value));
EXPECT_FALSE(
(std::is_same<decltype(stan::math::value_of(a)),
Eigen::Matrix<double, Eigen::Dynamic, 1>&>::value));
EXPECT_FALSE(
(std::is_same<decltype(stan::math::value_of(a)),
const Eigen::Matrix<double, Eigen::Dynamic, 1>>::value));
EXPECT_TRUE(
(std::is_same<decltype(stan::math::value_of(a)),
const Eigen::Matrix<double, Eigen::Dynamic, 1>&>::value));
}
TEST(MathFunctions, value_of_return_type_short_circuit_row_vector_xd) {
Eigen::Matrix<double, 1, Eigen::Dynamic> a(5);
EXPECT_FALSE((std::is_same<decltype(stan::math::value_of(a)),
Eigen::Matrix<double, 1, Eigen::Dynamic>>::value));
EXPECT_FALSE(
(std::is_same<decltype(stan::math::value_of(a)),
Eigen::Matrix<double, 1, Eigen::Dynamic>&>::value));
EXPECT_FALSE(
(std::is_same<decltype(stan::math::value_of(a)),
const Eigen::Matrix<double, 1, Eigen::Dynamic>>::value));
EXPECT_TRUE(
(std::is_same<decltype(stan::math::value_of(a)),
const Eigen::Matrix<double, 1, Eigen::Dynamic>&>::value));
}
TEST(MathFunctions, value_of_return_type_short_circuit_matrix_xd) {
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> a(5, 4);
EXPECT_FALSE((std::is_same<
decltype(stan::math::value_of(a)),
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>>::value));
EXPECT_FALSE(
(std::is_same<
decltype(stan::math::value_of(a)),
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>&>::value));
EXPECT_FALSE(
(std::is_same<
decltype(stan::math::value_of(a)),
const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic>>::value));
EXPECT_TRUE((std::is_same<decltype(stan::math::value_of(a)),
const Eigen::Matrix<double, Eigen::Dynamic,
Eigen::Dynamic>&>::value));
}
TEST(MathFunctions, value_of_return_type_short_circuit_static_sized_matrix) {
Eigen::Matrix<double, 5, 4> a;
EXPECT_FALSE((std::is_same<decltype(stan::math::value_of(a)),
Eigen::Matrix<double, 5, 4>>::value));
EXPECT_FALSE((std::is_same<decltype(stan::math::value_of(a)),
Eigen::Matrix<double, 5, 4>&>::value));
EXPECT_FALSE((std::is_same<decltype(stan::math::value_of(a)),
const Eigen::Matrix<double, 5, 4>>::value));
EXPECT_TRUE((std::is_same<decltype(stan::math::value_of(a)),
const Eigen::Matrix<double, 5, 4>&>::value));
}
<commit_msg>fixed value_of tests<commit_after>#include <stan/math/prim.hpp>
#include <gtest/gtest.h>
#include <cmath>
#include <limits>
#include <type_traits>
#include <vector>
TEST(MathFunctions, value_of) {
using stan::math::value_of;
double x = 5.0;
EXPECT_FLOAT_EQ(5.0, value_of(x));
EXPECT_FLOAT_EQ(5.0, value_of(5));
}
TEST(MathFunctions, value_of_nan) {
double nan = std::numeric_limits<double>::quiet_NaN();
EXPECT_TRUE(std::isnan(stan::math::value_of(nan)));
}
TEST(MathMatrixPrimArr, value_of) {
using stan::math::value_of;
using std::vector;
vector<double> a;
for (size_t i = 0; i < 10; ++i)
a.push_back(i + 1);
vector<double> b;
for (size_t i = 10; i < 15; ++i)
b.push_back(i + 1);
vector<double> d_a = value_of(a);
vector<double> d_b = value_of(b);
for (int i = 0; i < 5; ++i)
EXPECT_FLOAT_EQ(b[i], d_b[i]);
for (int i = 0; i < 10; ++i)
EXPECT_FLOAT_EQ(a[i], d_a[i]);
}
TEST(MathFunctions, value_of_int_return_type_short_circuit) {
std::vector<int> a(5, 0);
const std::vector<int> b(5, 0);
EXPECT_TRUE((std::is_same<decltype(stan::math::value_of(a)),
std::vector<int>&>::value));
EXPECT_TRUE((std::is_same<decltype(stan::math::value_of(b)),
const std::vector<int>&>::value));
}
TEST(MathFunctions, value_of_double_return_type_short_circuit) {
std::vector<double> a(5, 0);
const std::vector<double> b(5, 0);
EXPECT_TRUE((std::is_same<decltype(stan::math::value_of(a)),
std::vector<double>&>::value));
EXPECT_TRUE((std::is_same<decltype(stan::math::value_of(b)),
const std::vector<double>&>::value));
}
TEST(MathMatrixPrimMat, value_of) {
using stan::math::value_of;
Eigen::Matrix<double, 2, 5> a;
for (int i = 0; i < 2; i++)
for (int j = 0; j < 5; j++)
a(i, j) = i * 5 + j;
Eigen::Matrix<double, 5, 1> b;
for (int i = 0; i < 5; i++)
for (int j = 0; j < 1; j++)
b(i, j) = 10 + i * 5 + j;
Eigen::MatrixXd d_a = value_of(a);
Eigen::VectorXd d_b = value_of(b);
for (int i = 0; i < 5; ++i)
EXPECT_FLOAT_EQ(b(i), d_b(i));
for (int i = 0; i < 2; ++i)
for (int j = 0; j < 5; ++j)
EXPECT_FLOAT_EQ(a(i, j), d_a(i, j));
}
TEST(MathFunctions, value_of_return_type_short_circuit_vector_xd) {
Eigen::Matrix<double, Eigen::Dynamic, 1> a(5);
const Eigen::Matrix<double, Eigen::Dynamic, 1> b(5);
EXPECT_TRUE(
(std::is_same<decltype(stan::math::value_of(a)),
Eigen::Matrix<double, Eigen::Dynamic, 1>&>::value));
EXPECT_TRUE(
(std::is_same<decltype(stan::math::value_of(b)),
const Eigen::Matrix<double, Eigen::Dynamic, 1>&>::value));
}
TEST(MathFunctions, value_of_return_type_short_circuit_row_vector_xd) {
Eigen::Matrix<double, 1, Eigen::Dynamic> a(5);
const Eigen::Matrix<double, 1, Eigen::Dynamic> b(5);
EXPECT_TRUE(
(std::is_same<decltype(stan::math::value_of(a)),
Eigen::Matrix<double, 1, Eigen::Dynamic>&>::value));
EXPECT_TRUE(
(std::is_same<decltype(stan::math::value_of(b)),
const Eigen::Matrix<double, 1, Eigen::Dynamic>&>::value));
}
TEST(MathFunctions, value_of_return_type_short_circuit_matrix_xd) {
Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> a(5, 4);
const Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic> b(5, 4);
EXPECT_TRUE((std::is_same<decltype(stan::math::value_of(a)),
Eigen::Matrix<double, Eigen::Dynamic,
Eigen::Dynamic>&>::value));
EXPECT_TRUE((std::is_same<decltype(stan::math::value_of(b)),
const Eigen::Matrix<double, Eigen::Dynamic,
Eigen::Dynamic>&>::value));
}
TEST(MathFunctions, value_of_return_type_short_circuit_static_sized_matrix) {
Eigen::Matrix<double, 5, 4> a;
const Eigen::Matrix<double, 5, 4> b;
EXPECT_TRUE((std::is_same<decltype(stan::math::value_of(a)),
Eigen::Matrix<double, 5, 4>&>::value));
EXPECT_TRUE((std::is_same<decltype(stan::math::value_of(b)),
const Eigen::Matrix<double, 5, 4>&>::value));
}
<|endoftext|> |
<commit_before>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include "gtest/gtest.h"
#include <hspp/Cards/Cards.hpp>
#include <hspp/Managers/GameAgent.hpp>
#include <hspp/Tasks/SimpleTasks/DrawTask.hpp>
using namespace Hearthstonepp;
using namespace SimpleTasks;
TEST(DrawTask, GetTaskID)
{
const DrawTask draw(1);
EXPECT_EQ(draw.GetTaskID(), +TaskID::DRAW);
}
TEST(DrawTask, Run)
{
std::vector<Card> cards;
std::vector<Entity*> entities;
GameAgent agent(CardClass::ROGUE, CardClass::DRUID, PlayerType::PLAYER1);
Player& p = agent.GetPlayer1();
const auto Generate = [&](std::string&& id) -> Entity* {
cards.emplace_back(Card());
Card card = cards.back();
card.id = std::move(id);
entities.emplace_back(new Entity(&agent, card));
return entities.back();
};
const std::string id = "card";
for (char i = '0'; i < '3'; ++i)
{
p.GetDeck().emplace_back(Generate(id + i));
}
DrawTask draw(3);
MetaData result = draw.Run(p);
EXPECT_EQ(result, MetaData::DRAW_SUCCESS);
EXPECT_EQ(p.GetHand().size(), static_cast<size_t>(3));
for (size_t i = 0; i < 3; ++i)
{
EXPECT_EQ(p.GetHand()[i]->card->id,
id + static_cast<char>(2 - i + 0x30));
}
}
TEST(DrawTask, RunExhaust)
{
GameAgent agent(CardClass::ROGUE, CardClass::DRUID, PlayerType::PLAYER1);
Player& p = agent.GetPlayer1();
EXPECT_EQ(p.GetDeck().size(), static_cast<size_t>(0));
DrawTask draw(3);
MetaData result = draw.Run(agent.GetPlayer1());
EXPECT_EQ(result, MetaData::DRAW_EXHAUST);
EXPECT_EQ(p.GetHand().size(), static_cast<size_t>(0));
EXPECT_EQ(p.GetDeck().size(), static_cast<size_t>(0));
EXPECT_EQ(p.GetNumCardAfterExhaust(), 3);
// Health: 30 - (1 + 2 + 3)
EXPECT_EQ(p.GetHero()->health, static_cast<size_t>(24));
Card card;
card.id = "card1";
auto entity = new Entity(&agent, card);
p.GetDeck().emplace_back(entity);
result = draw.Run(agent.GetPlayer1());
EXPECT_EQ(result, MetaData::DRAW_EXHAUST);
EXPECT_EQ(p.GetHand().size(), static_cast<size_t>(1));
EXPECT_EQ(p.GetHand()[0]->card->id, "card1");
EXPECT_EQ(p.GetDeck().size(), static_cast<size_t>(0));
EXPECT_EQ(p.GetNumCardAfterExhaust(), 5);
// Health: 30 - (1 + 2 + 3 + 4 + 5)
EXPECT_EQ(p.GetHero()->health, static_cast<size_t>(15));
}
TEST(DrawTask, RunOverDraw)
{
std::vector<Card> cards;
std::vector<Entity*> entities;
GameAgent agent(CardClass::ROGUE, CardClass::DRUID, PlayerType::PLAYER1);
Player& p = agent.GetPlayer1();
const auto Generate = [&](std::string&& id) -> Entity* {
cards.emplace_back(Card());
Card card = cards.back();
card.id = std::move(id);
entities.emplace_back(new Entity(&agent, card));
return entities.back();
};
const std::string id = "card";
for (char i = '0'; i < '3'; ++i)
{
p.GetDeck().emplace_back(Generate(id + i));
}
p.GetHand().resize(10);
DrawTask draw(3);
MetaData result = draw.Run(p);
EXPECT_EQ(result, MetaData::DRAW_OVERDRAW);
EXPECT_EQ(p.GetDeck().size(), static_cast<size_t>(0));
EXPECT_EQ(p.GetHand().size(), static_cast<size_t>(10));
TaskMeta burnt;
agent.GetTaskMeta(burnt);
EXPECT_EQ(burnt.GetID(), +TaskID::OVERDRAW);
EXPECT_EQ(burnt.GetStatus(), MetaData::DRAW_OVERDRAW);
EXPECT_EQ(burnt.GetUserID(), p.GetID());
auto burntCard =
TaskMeta::ConvertTo<FlatData::EntityVector>(burnt)->vector();
EXPECT_EQ(burntCard->size(), static_cast<flatbuffers::uoffset_t>(3));
for (flatbuffers::uoffset_t i = 0; i < 3; ++i)
{
auto card = burntCard->Get(i)->card();
EXPECT_EQ(card->id()->str(), id + static_cast<char>(2 - i + 0x30));
}
}
TEST(DrawTask, RunExhaustOverdraw)
{
std::vector<Card> cards;
std::vector<Entity*> entities;
GameAgent agent(CardClass::ROGUE, CardClass::DRUID, PlayerType::PLAYER1);
Player& p = agent.GetPlayer1();
const auto Generate = [&](std::string&& id) -> Entity* {
cards.emplace_back(Card());
Card card = cards.back();
card.id = std::move(id);
entities.emplace_back(new Entity(&agent, card));
return entities.back();
};
const std::string id = "card";
for (char i = '0'; i < '3'; ++i)
{
p.GetDeck().emplace_back(Generate(id + i));
}
p.GetHand().resize(9);
DrawTask draw(4);
MetaData result = draw.Run(p);
EXPECT_EQ(result, MetaData::DRAW_EXHAUST_OVERDRAW);
EXPECT_EQ(p.GetDeck().size(), static_cast<size_t>(0));
EXPECT_EQ(p.GetHand().size(), static_cast<size_t>(10));
EXPECT_EQ(p.GetHand()[9]->card->id, "card0");
TaskMeta burnt;
agent.GetTaskMeta(burnt);
EXPECT_EQ(burnt.GetID(), +TaskID::OVERDRAW);
EXPECT_EQ(burnt.GetStatus(), MetaData::DRAW_EXHAUST_OVERDRAW);
EXPECT_EQ(burnt.GetUserID(), p.GetID());
auto burntCard =
TaskMeta::ConvertTo<FlatData::EntityVector>(burnt)->vector();
EXPECT_EQ(burntCard->size(), static_cast<flatbuffers::uoffset_t>(2));
for (flatbuffers::uoffset_t i = 0; i < 2; ++i)
{
auto card = burntCard->Get(i)->card();
EXPECT_EQ(card->id()->str(), id + static_cast<char>(2 - i + 0x30));
}
}
TEST(DrawCardTask, GetTaskID)
{
const Card card{};
const DrawCardTask draw(card);
EXPECT_EQ(draw.GetTaskID(), +TaskID::DRAW);
}
TEST(DrawCardTask, Run)
{
Cards& instance = Cards::GetInstance();
GameAgent agent(CardClass::ROGUE, CardClass::DRUID, PlayerType::PLAYER1);
Card nerubian = instance.FindCardByID("AT_036t");
EXPECT_NE(nerubian.id, "");
EXPECT_EQ(nerubian.name, "Nerubian");
Card poisonedBlade = instance.FindCardByID("AT_034");
EXPECT_NE(poisonedBlade.id, "");
EXPECT_EQ(poisonedBlade.name, "Poisoned Blade");
auto minionNerubian = new Entity(&agent, nerubian);
auto weaponPoisonedBlade = new Entity(&agent, poisonedBlade);
agent.GetPlayer1().GetDeck().emplace_back(weaponPoisonedBlade);
agent.GetPlayer1().GetDeck().emplace_back(minionNerubian);
DrawCardTask drawNerubian(nerubian);
MetaData result = drawNerubian.Run(agent.GetPlayer1());
EXPECT_EQ(result, MetaData::DRAW_SUCCESS);
EXPECT_EQ(agent.GetPlayer1().GetHand().size(), static_cast<size_t>(1));
EXPECT_EQ(agent.GetPlayer1().GetHand()[0]->card->id, nerubian.id);
EXPECT_EQ(agent.GetPlayer1().GetDeck().size(), static_cast<size_t>(1));
EXPECT_EQ(agent.GetPlayer1().GetDeck()[0]->card->id, poisonedBlade.id);
DrawCardTask drawPoisonedBlade(poisonedBlade);
result = drawPoisonedBlade.Run(agent.GetPlayer1());
EXPECT_EQ(result, MetaData::DRAW_SUCCESS);
EXPECT_EQ(agent.GetPlayer1().GetHand().size(), static_cast<size_t>(2));
EXPECT_EQ(agent.GetPlayer1().GetHand()[1]->card->id, poisonedBlade.id);
EXPECT_EQ(agent.GetPlayer1().GetDeck().size(), static_cast<size_t>(0));
delete minionNerubian;
delete weaponPoisonedBlade;
}
<commit_msg>[ci skip] refactor: Apply changes of throwing exception<commit_after>// Copyright (c) 2018 Chris Ohk, Youngjoong Kim, SeungHyun Jeon
// We are making my contributions/submissions to this project solely in our
// personal capacity and are not conveying any rights to any intellectual
// property of any third parties.
#include "gtest/gtest.h"
#include <hspp/Cards/Cards.hpp>
#include <hspp/Managers/GameAgent.hpp>
#include <hspp/Tasks/SimpleTasks/DrawTask.hpp>
using namespace Hearthstonepp;
using namespace SimpleTasks;
TEST(DrawTask, GetTaskID)
{
const DrawTask draw(1);
EXPECT_EQ(draw.GetTaskID(), +TaskID::DRAW);
}
TEST(DrawTask, Run)
{
std::vector<Card> cards;
std::vector<Entity*> minions;
GameAgent agent(CardClass::ROGUE, CardClass::DRUID, PlayerType::PLAYER1);
Player& p = agent.GetPlayer1();
const auto Generate = [&](std::string&& id) -> Entity* {
cards.emplace_back(Card());
Card card = cards.back();
card.id = std::move(id);
minions.emplace_back(new Minion(&agent, card));
return minions.back();
};
const std::string id = "card";
for (char i = '0'; i < '3'; ++i)
{
p.GetDeck().emplace_back(Generate(id + i));
}
DrawTask draw(3);
MetaData result = draw.Run(p);
EXPECT_EQ(result, MetaData::DRAW_SUCCESS);
EXPECT_EQ(p.GetHand().size(), 3u);
for (size_t i = 0; i < 3; ++i)
{
EXPECT_EQ(p.GetHand()[i]->card->id,
id + static_cast<char>(2 - i + 0x30));
}
}
TEST(DrawTask, RunExhaust)
{
GameAgent agent(CardClass::ROGUE, CardClass::DRUID, PlayerType::PLAYER1);
Player& p = agent.GetPlayer1();
EXPECT_EQ(p.GetDeck().size(), 0u);
DrawTask draw(3);
MetaData result = draw.Run(agent.GetPlayer1());
EXPECT_EQ(result, MetaData::DRAW_EXHAUST);
EXPECT_EQ(p.GetHand().size(), 0u);
EXPECT_EQ(p.GetDeck().size(), 0u);
EXPECT_EQ(p.GetNumCardAfterExhaust(), 3);
// Health: 30 - (1 + 2 + 3)
EXPECT_EQ(p.GetHero()->health, 24);
Card card;
card.id = "card1";
auto minion = new Minion(&agent, card);
p.GetDeck().emplace_back(minion);
result = draw.Run(agent.GetPlayer1());
EXPECT_EQ(result, MetaData::DRAW_EXHAUST);
EXPECT_EQ(p.GetHand().size(), 1u);
EXPECT_EQ(p.GetHand()[0]->card->id, "card1");
EXPECT_EQ(p.GetDeck().size(), 0u);
EXPECT_EQ(p.GetNumCardAfterExhaust(), 5);
// Health: 30 - (1 + 2 + 3 + 4 + 5)
EXPECT_EQ(p.GetHero()->health, 15);
}
TEST(DrawTask, RunOverDraw)
{
std::vector<Card> cards;
std::vector<Entity*> minions;
GameAgent agent(CardClass::ROGUE, CardClass::DRUID, PlayerType::PLAYER1);
Player& p = agent.GetPlayer1();
const auto Generate = [&](std::string&& id) -> Entity* {
cards.emplace_back(Card());
Card card = cards.back();
card.id = std::move(id);
minions.emplace_back(new Minion(&agent, card));
return minions.back();
};
const std::string id = "card";
for (char i = '0'; i < '3'; ++i)
{
p.GetDeck().emplace_back(Generate(id + i));
}
p.GetHand().resize(10);
DrawTask draw(3);
MetaData result = draw.Run(p);
EXPECT_EQ(result, MetaData::DRAW_OVERDRAW);
EXPECT_EQ(p.GetDeck().size(), 0u);
EXPECT_EQ(p.GetHand().size(), 10u);
TaskMeta burnt;
agent.GetTaskMeta(burnt);
EXPECT_EQ(burnt.GetID(), +TaskID::OVERDRAW);
EXPECT_EQ(burnt.GetStatus(), MetaData::DRAW_OVERDRAW);
EXPECT_EQ(burnt.GetUserID(), p.GetID());
auto burntCard =
TaskMeta::ConvertTo<FlatData::EntityVector>(burnt)->vector();
EXPECT_EQ(burntCard->size(), static_cast<flatbuffers::uoffset_t>(3));
for (flatbuffers::uoffset_t i = 0; i < 3; ++i)
{
auto card = burntCard->Get(i)->card();
EXPECT_EQ(card->id()->str(), id + static_cast<char>(2 - i + 0x30));
}
}
TEST(DrawTask, RunExhaustOverdraw)
{
std::vector<Card> cards;
std::vector<Minion*> minions;
GameAgent agent(CardClass::ROGUE, CardClass::DRUID, PlayerType::PLAYER1);
Player& p = agent.GetPlayer1();
const auto Generate = [&](std::string&& id) -> Entity* {
cards.emplace_back(Card());
Card card = cards.back();
card.id = std::move(id);
minions.emplace_back(new Minion(&agent, card));
return minions.back();
};
const std::string id = "card";
for (char i = '0'; i < '3'; ++i)
{
p.GetDeck().emplace_back(Generate(id + i));
}
p.GetHand().resize(9);
DrawTask draw(4);
MetaData result = draw.Run(p);
EXPECT_EQ(result, MetaData::DRAW_EXHAUST_OVERDRAW);
EXPECT_EQ(p.GetDeck().size(), 0u);
EXPECT_EQ(p.GetHand().size(), 10u);
EXPECT_EQ(p.GetHand()[9]->card->id, "card0");
TaskMeta burnt;
agent.GetTaskMeta(burnt);
EXPECT_EQ(burnt.GetID(), +TaskID::OVERDRAW);
EXPECT_EQ(burnt.GetStatus(), MetaData::DRAW_EXHAUST_OVERDRAW);
EXPECT_EQ(burnt.GetUserID(), p.GetID());
auto burntCard =
TaskMeta::ConvertTo<FlatData::EntityVector>(burnt)->vector();
EXPECT_EQ(burntCard->size(), static_cast<flatbuffers::uoffset_t>(2));
for (flatbuffers::uoffset_t i = 0; i < 2; ++i)
{
auto card = burntCard->Get(i)->card();
EXPECT_EQ(card->id()->str(), id + static_cast<char>(2 - i + 0x30));
}
}
TEST(DrawCardTask, GetTaskID)
{
const Card card{};
const DrawCardTask draw(card);
EXPECT_EQ(draw.GetTaskID(), +TaskID::DRAW);
}
TEST(DrawCardTask, Run)
{
Cards& instance = Cards::GetInstance();
GameAgent agent(CardClass::ROGUE, CardClass::DRUID, PlayerType::PLAYER1);
Card nerubian = instance.FindCardByID("AT_036t");
EXPECT_NE(nerubian.id, "");
EXPECT_EQ(nerubian.name, "Nerubian");
Card poisonedBlade = instance.FindCardByID("AT_034");
EXPECT_NE(poisonedBlade.id, "");
EXPECT_EQ(poisonedBlade.name, "Poisoned Blade");
auto minionNerubian = new Minion(&agent, nerubian);
auto weaponPoisonedBlade = new Weapon(&agent, poisonedBlade);
agent.GetPlayer1().GetDeck().emplace_back(weaponPoisonedBlade);
agent.GetPlayer1().GetDeck().emplace_back(minionNerubian);
DrawCardTask drawNerubian(nerubian);
MetaData result = drawNerubian.Run(agent.GetPlayer1());
EXPECT_EQ(result, MetaData::DRAW_SUCCESS);
EXPECT_EQ(agent.GetPlayer1().GetHand().size(), 1u);
EXPECT_EQ(agent.GetPlayer1().GetHand()[0]->card->id, nerubian.id);
EXPECT_EQ(agent.GetPlayer1().GetDeck().size(), 1u);
EXPECT_EQ(agent.GetPlayer1().GetDeck()[0]->card->id, poisonedBlade.id);
DrawCardTask drawPoisonedBlade(poisonedBlade);
result = drawPoisonedBlade.Run(agent.GetPlayer1());
EXPECT_EQ(result, MetaData::DRAW_SUCCESS);
EXPECT_EQ(agent.GetPlayer1().GetHand().size(), 2u);
EXPECT_EQ(agent.GetPlayer1().GetHand()[1]->card->id, poisonedBlade.id);
EXPECT_EQ(agent.GetPlayer1().GetDeck().size(), 0u);
delete minionNerubian;
delete weaponPoisonedBlade;
}
<|endoftext|> |
<commit_before>#include <osgDB/Registry>
USE_SERIALIZER_WRAPPER(osgAnimation_Action)
USE_SERIALIZER_WRAPPER(osgAnimation_ActionAnimation)
USE_SERIALIZER_WRAPPER(osgAnimation_ActionBlendIn)
USE_SERIALIZER_WRAPPER(osgAnimation_ActionBlendOut)
USE_SERIALIZER_WRAPPER(osgAnimation_ActionStripAnimation)
USE_SERIALIZER_WRAPPER(osgAnimation_Animation)
USE_SERIALIZER_WRAPPER(osgAnimation_AnimationManagerBase)
USE_SERIALIZER_WRAPPER(osgAnimation_BasicAnimationManager)
USE_SERIALIZER_WRAPPER(osgAnimation_Bone)
USE_SERIALIZER_WRAPPER(osgAnimation_MorphGeometry)
USE_SERIALIZER_WRAPPER(osgAnimation_RigComputeBoundingBoxCallback)
USE_SERIALIZER_WRAPPER(osgAnimation_RigGeometry)
USE_SERIALIZER_WRAPPER(osgAnimation_Skeleton)
USE_SERIALIZER_WRAPPER(osgAnimation_StackedMatrixElement)
USE_SERIALIZER_WRAPPER(osgAnimation_StackedQuaternionElement)
USE_SERIALIZER_WRAPPER(osgAnimation_StackedRotateAxisElement)
USE_SERIALIZER_WRAPPER(osgAnimation_StackedScaleElement)
USE_SERIALIZER_WRAPPER(osgAnimation_StackedTransformElement)
USE_SERIALIZER_WRAPPER(osgAnimation_StackedTranslateElement)
USE_SERIALIZER_WRAPPER(osgAnimation_Timeline)
USE_SERIALIZER_WRAPPER(osgAnimation_TimelineAnimationManager)
USE_SERIALIZER_WRAPPER(osgAnimation_UpdateBone)
USE_SERIALIZER_WRAPPER(osgAnimation_UpdateMaterial)
USE_SERIALIZER_WRAPPER(osgAnimation_UpdateMatrixTransform)
USE_SERIALIZER_WRAPPER(osgAnimation_UpdateMorph)
USE_SERIALIZER_WRAPPER(osgAnimation_UpdateSkeleton)
USE_SERIALIZER_WRAPPER(osgAnimation_UpdateMorphGeometry)
USE_SERIALIZER_WRAPPER(osgAnimation_UpdateRigGeometry)
USE_SERIALIZER_WRAPPER(osgAnimation_UpdateFloatUniform)
USE_SERIALIZER_WRAPPER(osgAnimation_UpdateMatrixfUniform)
USE_SERIALIZER_WRAPPER(osgAnimation_UpdateVec2fUniform)
USE_SERIALIZER_WRAPPER(osgAnimation_UpdateVec3fUniform)
USE_SERIALIZER_WRAPPER(osgAnimation_UpdateVec4fUniform)
extern "C" void wrapper_serializer_library_osgAnimation(void) {}
<commit_msg>osgAnimation serializes: static linking fix<commit_after>#include <osgDB/Registry>
USE_SERIALIZER_WRAPPER(osgAnimation_Action)
USE_SERIALIZER_WRAPPER(osgAnimation_ActionAnimation)
USE_SERIALIZER_WRAPPER(osgAnimation_ActionBlendIn)
USE_SERIALIZER_WRAPPER(osgAnimation_ActionBlendOut)
USE_SERIALIZER_WRAPPER(osgAnimation_ActionStripAnimation)
USE_SERIALIZER_WRAPPER(osgAnimation_Animation)
USE_SERIALIZER_WRAPPER(osgAnimation_AnimationManagerBase)
USE_SERIALIZER_WRAPPER(osgAnimation_BasicAnimationManager)
USE_SERIALIZER_WRAPPER(osgAnimation_Bone)
USE_SERIALIZER_WRAPPER(osgAnimation_MorphGeometry)
USE_SERIALIZER_WRAPPER(osgAnimation_RigComputeBoundingBoxCallback)
USE_SERIALIZER_WRAPPER(osgAnimation_RigGeometry)
USE_SERIALIZER_WRAPPER(osgAnimation_RigTransform)
USE_SERIALIZER_WRAPPER(osgAnimation_Skeleton)
USE_SERIALIZER_WRAPPER(osgAnimation_StackedMatrixElement)
USE_SERIALIZER_WRAPPER(osgAnimation_StackedQuaternionElement)
USE_SERIALIZER_WRAPPER(osgAnimation_StackedRotateAxisElement)
USE_SERIALIZER_WRAPPER(osgAnimation_StackedScaleElement)
USE_SERIALIZER_WRAPPER(osgAnimation_StackedTransformElement)
USE_SERIALIZER_WRAPPER(osgAnimation_StackedTranslateElement)
USE_SERIALIZER_WRAPPER(osgAnimation_Timeline)
USE_SERIALIZER_WRAPPER(osgAnimation_TimelineAnimationManager)
USE_SERIALIZER_WRAPPER(osgAnimation_UpdateBone)
USE_SERIALIZER_WRAPPER(osgAnimation_UpdateMaterial)
USE_SERIALIZER_WRAPPER(osgAnimation_UpdateMatrixTransform)
USE_SERIALIZER_WRAPPER(osgAnimation_UpdateMorph)
USE_SERIALIZER_WRAPPER(osgAnimation_UpdateSkeleton)
USE_SERIALIZER_WRAPPER(osgAnimation_UpdateMorphGeometry)
USE_SERIALIZER_WRAPPER(osgAnimation_UpdateRigGeometry)
USE_SERIALIZER_WRAPPER(osgAnimation_UpdateFloatUniform)
USE_SERIALIZER_WRAPPER(osgAnimation_UpdateMatrixfUniform)
USE_SERIALIZER_WRAPPER(osgAnimation_UpdateVec2fUniform)
USE_SERIALIZER_WRAPPER(osgAnimation_UpdateVec3fUniform)
USE_SERIALIZER_WRAPPER(osgAnimation_UpdateVec4fUniform)
extern "C" void wrapper_serializer_library_osgAnimation(void) {}
<|endoftext|> |
<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "buildsettingspropertiespage.h"
#include "buildstep.h"
#include "buildstepspage.h"
#include "project.h"
#include "target.h"
#include "buildconfiguration.h"
#include <coreplugin/coreconstants.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
#include <QtCore/QMargins>
#include <QtCore/QTimer>
#include <QtCore/QCoreApplication>
#include <QtGui/QComboBox>
#include <QtGui/QInputDialog>
#include <QtGui/QLabel>
#include <QtGui/QMenu>
#include <QtGui/QPushButton>
#include <QtGui/QVBoxLayout>
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
///
// BuildSettingsPanelFactory
///
QString BuildSettingsPanelFactory::id() const
{
return QLatin1String(BUILDSETTINGS_PANEL_ID);
}
QString BuildSettingsPanelFactory::displayName() const
{
return QCoreApplication::translate("BuildSettingsPanelFactory", "Build Settings");
}
bool BuildSettingsPanelFactory::supports(Target *target)
{
return target->buildConfigurationFactory();
}
IPropertiesPanel *BuildSettingsPanelFactory::createPanel(Target *target)
{
return new BuildSettingsPanel(target);
}
///
// BuildSettingsPanel
///
BuildSettingsPanel::BuildSettingsPanel(Target *target) :
m_widget(new BuildSettingsWidget(target)),
m_icon(":/projectexplorer/images/BuildSettings.png")
{
}
BuildSettingsPanel::~BuildSettingsPanel()
{
delete m_widget;
}
QString BuildSettingsPanel::displayName() const
{
return QCoreApplication::translate("BuildSettingsPanel", "Build Settings");
}
QWidget *BuildSettingsPanel::widget() const
{
return m_widget;
}
QIcon BuildSettingsPanel::icon() const
{
return m_icon;
}
///
// BuildSettingsWidget
///
BuildSettingsWidget::~BuildSettingsWidget()
{
clear();
}
BuildSettingsWidget::BuildSettingsWidget(Target *target) :
m_target(target),
m_buildConfiguration(0),
m_leftMargin(0)
{
Q_ASSERT(m_target);
setupUi();
}
void BuildSettingsWidget::setupUi()
{
m_leftMargin = Constants::PANEL_LEFT_MARGIN;
QVBoxLayout *vbox = new QVBoxLayout(this);
vbox->setContentsMargins(0, 0, 0, 0);
if (!m_target->buildConfigurationFactory()) {
QLabel * noSettingsLabel(new QLabel(this));
noSettingsLabel->setText(tr("No Build Settings available"));
{
QFont f(noSettingsLabel->font());
f.setPointSizeF(f.pointSizeF() * 1.2);
noSettingsLabel->setFont(f);
}
vbox->addWidget(noSettingsLabel);
return;
}
{ // Edit Build Configuration row
QHBoxLayout *hbox = new QHBoxLayout();
hbox->setContentsMargins(m_leftMargin, 0, 0, 0);
hbox->addWidget(new QLabel(tr("Edit Build Configuration:"), this));
m_buildConfigurationComboBox = new QComboBox(this);
m_buildConfigurationComboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
hbox->addWidget(m_buildConfigurationComboBox);
m_addButton = new QPushButton(this);
m_addButton->setText(tr("Add"));
m_addButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
hbox->addWidget(m_addButton);
m_addButtonMenu = new QMenu(this);
m_addButton->setMenu(m_addButtonMenu);
m_removeButton = new QPushButton(this);
m_removeButton->setText(tr("Remove"));
m_removeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
hbox->addWidget(m_removeButton);
hbox->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Fixed));
vbox->addLayout(hbox);
}
m_buildConfiguration = m_target->activeBuildConfiguration();
updateAddButtonMenu();
updateBuildSettings();
connect(m_buildConfigurationComboBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(currentIndexChanged(int)));
connect(m_removeButton, SIGNAL(clicked()),
this, SLOT(deleteConfiguration()));
connect(m_target, SIGNAL(activeBuildConfigurationChanged(ProjectExplorer::BuildConfiguration*)),
this, SLOT(updateActiveConfiguration()));
connect(m_target, SIGNAL(addedBuildConfiguration(ProjectExplorer::BuildConfiguration*)),
this, SLOT(addedBuildConfiguration(ProjectExplorer::BuildConfiguration*)));
connect(m_target, SIGNAL(removedBuildConfiguration(ProjectExplorer::BuildConfiguration*)),
this, SLOT(removedBuildConfiguration(ProjectExplorer::BuildConfiguration*)));
foreach (BuildConfiguration *bc, m_target->buildConfigurations()) {
connect(bc, SIGNAL(displayNameChanged()),
this, SLOT(buildConfigurationDisplayNameChanged()));
}
if (m_target->buildConfigurationFactory())
connect(m_target->buildConfigurationFactory(), SIGNAL(availableCreationIdsChanged()),
SLOT(updateAddButtonMenu()));
}
void BuildSettingsWidget::addedBuildConfiguration(BuildConfiguration *bc)
{
connect(bc, SIGNAL(displayNameChanged()),
this, SLOT(buildConfigurationDisplayNameChanged()));
}
void BuildSettingsWidget::removedBuildConfiguration(BuildConfiguration *bc)
{
disconnect(bc, SIGNAL(displayNameChanged()),
this, SLOT(buildConfigurationDisplayNameChanged()));
}
void BuildSettingsWidget::buildConfigurationDisplayNameChanged()
{
for (int i = 0; i < m_buildConfigurationComboBox->count(); ++i) {
BuildConfiguration *bc = m_buildConfigurationComboBox->itemData(i).value<BuildConfiguration *>();
m_buildConfigurationComboBox->setItemText(i, bc->displayName());
}
}
void BuildSettingsWidget::addSubWidget(const QString &name, BuildConfigWidget *widget)
{
widget->setContentsMargins(m_leftMargin, 10, 0, 0);
QLabel *label = new QLabel(this);
label->setText(name);
QFont f = label->font();
f.setBold(true);
f.setPointSizeF(f.pointSizeF() * 1.2);
label->setFont(f);
label->setContentsMargins(m_leftMargin, 10, 0, 0);
layout()->addWidget(label);
layout()->addWidget(widget);
m_labels.append(label);
m_subWidgets.append(widget);
}
void BuildSettingsWidget::clear()
{
qDeleteAll(m_subWidgets);
m_subWidgets.clear();
qDeleteAll(m_labels);
m_labels.clear();
}
QList<BuildConfigWidget *> BuildSettingsWidget::subWidgets() const
{
return m_subWidgets;
}
void BuildSettingsWidget::updateAddButtonMenu()
{
m_addButtonMenu->clear();
if (m_target &&
m_target->activeBuildConfiguration()) {
m_addButtonMenu->addAction(tr("&Clone Selected"),
this, SLOT(cloneConfiguration()));
}
IBuildConfigurationFactory *factory = m_target->buildConfigurationFactory();
if (factory) {
foreach (const QString &id, factory->availableCreationIds(m_target)) {
QAction *action = m_addButtonMenu->addAction(factory->displayNameForId(id), this, SLOT(createConfiguration()));
action->setData(id);
}
}
}
void BuildSettingsWidget::updateBuildSettings()
{
// Delete old tree items
bool blocked = m_buildConfigurationComboBox->blockSignals(true);
m_buildConfigurationComboBox->clear();
clear();
// update buttons
m_removeButton->setEnabled(m_target->buildConfigurations().size() > 1);
// Add pages
BuildConfigWidget *generalConfigWidget = m_target->project()->createConfigWidget();
addSubWidget(generalConfigWidget->displayName(), generalConfigWidget);
addSubWidget(tr("Build Steps"), new BuildStepsPage(m_target, Build));
addSubWidget(tr("Clean Steps"), new BuildStepsPage(m_target, Clean));
QList<BuildConfigWidget *> subConfigWidgets = m_target->project()->subConfigWidgets();
foreach (BuildConfigWidget *subConfigWidget, subConfigWidgets)
addSubWidget(subConfigWidget->displayName(), subConfigWidget);
// Add tree items
foreach (BuildConfiguration *bc, m_target->buildConfigurations()) {
m_buildConfigurationComboBox->addItem(bc->displayName(), QVariant::fromValue<BuildConfiguration *>(bc));
if (bc == m_buildConfiguration)
m_buildConfigurationComboBox->setCurrentIndex(m_buildConfigurationComboBox->count() - 1);
}
foreach (BuildConfigWidget *widget, subWidgets())
widget->init(m_buildConfiguration);
m_buildConfigurationComboBox->blockSignals(blocked);
}
void BuildSettingsWidget::currentIndexChanged(int index)
{
BuildConfiguration *buildConfiguration = m_buildConfigurationComboBox->itemData(index).value<BuildConfiguration *>();
m_target->setActiveBuildConfiguration(buildConfiguration);
}
void BuildSettingsWidget::updateActiveConfiguration()
{
if (!m_buildConfiguration || m_buildConfiguration == m_target->activeBuildConfiguration())
return;
m_buildConfiguration = m_target->activeBuildConfiguration();
for (int i = 0; i < m_buildConfigurationComboBox->count(); ++i) {
if (m_buildConfigurationComboBox->itemData(i).value<BuildConfiguration *>() == m_buildConfiguration) {
m_buildConfigurationComboBox->setCurrentIndex(i);
break;
}
}
foreach (QWidget *widget, subWidgets()) {
if (BuildConfigWidget *buildStepWidget = qobject_cast<BuildConfigWidget*>(widget)) {
buildStepWidget->init(m_buildConfiguration);
}
}
}
void BuildSettingsWidget::createConfiguration()
{
if (!m_target->buildConfigurationFactory())
return;
QAction *action = qobject_cast<QAction *>(sender());
const QString &id = action->data().toString();
BuildConfiguration *bc = m_target->buildConfigurationFactory()->create(m_target, id);
if (bc) {
m_buildConfiguration = bc;
updateBuildSettings();
}
}
void BuildSettingsWidget::cloneConfiguration()
{
cloneConfiguration(m_buildConfiguration);
}
void BuildSettingsWidget::deleteConfiguration()
{
deleteConfiguration(m_buildConfiguration);
}
void BuildSettingsWidget::cloneConfiguration(BuildConfiguration *sourceConfiguration)
{
if (!sourceConfiguration ||
!m_target->buildConfigurationFactory())
return;
QString newDisplayName(QInputDialog::getText(this, tr("Clone configuration"), tr("New Configuration Name:")));
if (newDisplayName.isEmpty())
return;
QStringList buildConfigurationDisplayNames;
foreach(BuildConfiguration *bc, m_target->buildConfigurations())
buildConfigurationDisplayNames << bc->displayName();
newDisplayName = Project::makeUnique(newDisplayName, buildConfigurationDisplayNames);
BuildConfiguration * bc(m_target->buildConfigurationFactory()->clone(m_target, sourceConfiguration));
if (!bc)
return;
bc->setDisplayName(newDisplayName);
m_target->addBuildConfiguration(bc);
updateBuildSettings();
m_target->setActiveBuildConfiguration(bc);
}
void BuildSettingsWidget::deleteConfiguration(BuildConfiguration *deleteConfiguration)
{
if (!deleteConfiguration ||
m_target->buildConfigurations().size() <= 1)
return;
m_target->removeBuildConfiguration(deleteConfiguration);
updateBuildSettings();
}
<commit_msg>Fixes crash on adding configurations<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation ([email protected])
**
** Commercial Usage
**
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at http://qt.nokia.com/contact.
**
**************************************************************************/
#include "buildsettingspropertiespage.h"
#include "buildstep.h"
#include "buildstepspage.h"
#include "project.h"
#include "target.h"
#include "buildconfiguration.h"
#include <coreplugin/coreconstants.h>
#include <extensionsystem/pluginmanager.h>
#include <utils/qtcassert.h>
#include <QtCore/QMargins>
#include <QtCore/QTimer>
#include <QtCore/QCoreApplication>
#include <QtGui/QComboBox>
#include <QtGui/QInputDialog>
#include <QtGui/QLabel>
#include <QtGui/QMenu>
#include <QtGui/QPushButton>
#include <QtGui/QVBoxLayout>
using namespace ProjectExplorer;
using namespace ProjectExplorer::Internal;
///
// BuildSettingsPanelFactory
///
QString BuildSettingsPanelFactory::id() const
{
return QLatin1String(BUILDSETTINGS_PANEL_ID);
}
QString BuildSettingsPanelFactory::displayName() const
{
return QCoreApplication::translate("BuildSettingsPanelFactory", "Build Settings");
}
bool BuildSettingsPanelFactory::supports(Target *target)
{
return target->buildConfigurationFactory();
}
IPropertiesPanel *BuildSettingsPanelFactory::createPanel(Target *target)
{
return new BuildSettingsPanel(target);
}
///
// BuildSettingsPanel
///
BuildSettingsPanel::BuildSettingsPanel(Target *target) :
m_widget(new BuildSettingsWidget(target)),
m_icon(":/projectexplorer/images/BuildSettings.png")
{
}
BuildSettingsPanel::~BuildSettingsPanel()
{
delete m_widget;
}
QString BuildSettingsPanel::displayName() const
{
return QCoreApplication::translate("BuildSettingsPanel", "Build Settings");
}
QWidget *BuildSettingsPanel::widget() const
{
return m_widget;
}
QIcon BuildSettingsPanel::icon() const
{
return m_icon;
}
///
// BuildSettingsWidget
///
BuildSettingsWidget::~BuildSettingsWidget()
{
clear();
}
BuildSettingsWidget::BuildSettingsWidget(Target *target) :
m_target(target),
m_buildConfiguration(0),
m_leftMargin(0)
{
Q_ASSERT(m_target);
setupUi();
}
void BuildSettingsWidget::setupUi()
{
m_leftMargin = Constants::PANEL_LEFT_MARGIN;
QVBoxLayout *vbox = new QVBoxLayout(this);
vbox->setContentsMargins(0, 0, 0, 0);
if (!m_target->buildConfigurationFactory()) {
QLabel * noSettingsLabel(new QLabel(this));
noSettingsLabel->setText(tr("No Build Settings available"));
{
QFont f(noSettingsLabel->font());
f.setPointSizeF(f.pointSizeF() * 1.2);
noSettingsLabel->setFont(f);
}
vbox->addWidget(noSettingsLabel);
return;
}
{ // Edit Build Configuration row
QHBoxLayout *hbox = new QHBoxLayout();
hbox->setContentsMargins(m_leftMargin, 0, 0, 0);
hbox->addWidget(new QLabel(tr("Edit Build Configuration:"), this));
m_buildConfigurationComboBox = new QComboBox(this);
m_buildConfigurationComboBox->setSizeAdjustPolicy(QComboBox::AdjustToContents);
hbox->addWidget(m_buildConfigurationComboBox);
m_addButton = new QPushButton(this);
m_addButton->setText(tr("Add"));
m_addButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
hbox->addWidget(m_addButton);
m_addButtonMenu = new QMenu(this);
m_addButton->setMenu(m_addButtonMenu);
m_removeButton = new QPushButton(this);
m_removeButton->setText(tr("Remove"));
m_removeButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
hbox->addWidget(m_removeButton);
hbox->addSpacerItem(new QSpacerItem(0, 0, QSizePolicy::Expanding, QSizePolicy::Fixed));
vbox->addLayout(hbox);
}
m_buildConfiguration = m_target->activeBuildConfiguration();
updateAddButtonMenu();
updateBuildSettings();
connect(m_buildConfigurationComboBox, SIGNAL(currentIndexChanged(int)),
this, SLOT(currentIndexChanged(int)));
connect(m_removeButton, SIGNAL(clicked()),
this, SLOT(deleteConfiguration()));
connect(m_target, SIGNAL(activeBuildConfigurationChanged(ProjectExplorer::BuildConfiguration*)),
this, SLOT(updateActiveConfiguration()));
connect(m_target, SIGNAL(addedBuildConfiguration(ProjectExplorer::BuildConfiguration*)),
this, SLOT(addedBuildConfiguration(ProjectExplorer::BuildConfiguration*)));
connect(m_target, SIGNAL(removedBuildConfiguration(ProjectExplorer::BuildConfiguration*)),
this, SLOT(removedBuildConfiguration(ProjectExplorer::BuildConfiguration*)));
foreach (BuildConfiguration *bc, m_target->buildConfigurations()) {
connect(bc, SIGNAL(displayNameChanged()),
this, SLOT(buildConfigurationDisplayNameChanged()));
}
if (m_target->buildConfigurationFactory())
connect(m_target->buildConfigurationFactory(), SIGNAL(availableCreationIdsChanged()),
SLOT(updateAddButtonMenu()));
}
void BuildSettingsWidget::addedBuildConfiguration(BuildConfiguration *bc)
{
connect(bc, SIGNAL(displayNameChanged()),
this, SLOT(buildConfigurationDisplayNameChanged()));
}
void BuildSettingsWidget::removedBuildConfiguration(BuildConfiguration *bc)
{
disconnect(bc, SIGNAL(displayNameChanged()),
this, SLOT(buildConfigurationDisplayNameChanged()));
}
void BuildSettingsWidget::buildConfigurationDisplayNameChanged()
{
for (int i = 0; i < m_buildConfigurationComboBox->count(); ++i) {
BuildConfiguration *bc = m_buildConfigurationComboBox->itemData(i).value<BuildConfiguration *>();
m_buildConfigurationComboBox->setItemText(i, bc->displayName());
}
}
void BuildSettingsWidget::addSubWidget(const QString &name, BuildConfigWidget *widget)
{
widget->setContentsMargins(m_leftMargin, 10, 0, 0);
QLabel *label = new QLabel(this);
label->setText(name);
QFont f = label->font();
f.setBold(true);
f.setPointSizeF(f.pointSizeF() * 1.2);
label->setFont(f);
label->setContentsMargins(m_leftMargin, 10, 0, 0);
layout()->addWidget(label);
layout()->addWidget(widget);
m_labels.append(label);
m_subWidgets.append(widget);
}
void BuildSettingsWidget::clear()
{
qDeleteAll(m_subWidgets);
m_subWidgets.clear();
qDeleteAll(m_labels);
m_labels.clear();
}
QList<BuildConfigWidget *> BuildSettingsWidget::subWidgets() const
{
return m_subWidgets;
}
void BuildSettingsWidget::updateAddButtonMenu()
{
m_addButtonMenu->clear();
if (m_target &&
m_target->activeBuildConfiguration()) {
m_addButtonMenu->addAction(tr("&Clone Selected"),
this, SLOT(cloneConfiguration()));
}
IBuildConfigurationFactory *factory = m_target->buildConfigurationFactory();
if (factory) {
foreach (const QString &id, factory->availableCreationIds(m_target)) {
QAction *action = m_addButtonMenu->addAction(factory->displayNameForId(id), this, SLOT(createConfiguration()));
action->setData(id);
}
}
}
void BuildSettingsWidget::updateBuildSettings()
{
// Delete old tree items
bool blocked = m_buildConfigurationComboBox->blockSignals(true);
m_buildConfigurationComboBox->clear();
clear();
// update buttons
m_removeButton->setEnabled(m_target->buildConfigurations().size() > 1);
// Add pages
BuildConfigWidget *generalConfigWidget = m_target->project()->createConfigWidget();
addSubWidget(generalConfigWidget->displayName(), generalConfigWidget);
addSubWidget(tr("Build Steps"), new BuildStepsPage(m_target, Build));
addSubWidget(tr("Clean Steps"), new BuildStepsPage(m_target, Clean));
QList<BuildConfigWidget *> subConfigWidgets = m_target->project()->subConfigWidgets();
foreach (BuildConfigWidget *subConfigWidget, subConfigWidgets)
addSubWidget(subConfigWidget->displayName(), subConfigWidget);
// Add tree items
foreach (BuildConfiguration *bc, m_target->buildConfigurations()) {
m_buildConfigurationComboBox->addItem(bc->displayName(), QVariant::fromValue<BuildConfiguration *>(bc));
if (bc == m_buildConfiguration)
m_buildConfigurationComboBox->setCurrentIndex(m_buildConfigurationComboBox->count() - 1);
}
foreach (BuildConfigWidget *widget, subWidgets())
widget->init(m_buildConfiguration);
m_buildConfigurationComboBox->blockSignals(blocked);
}
void BuildSettingsWidget::currentIndexChanged(int index)
{
BuildConfiguration *buildConfiguration = m_buildConfigurationComboBox->itemData(index).value<BuildConfiguration *>();
m_target->setActiveBuildConfiguration(buildConfiguration);
}
void BuildSettingsWidget::updateActiveConfiguration()
{
if (!m_buildConfiguration || m_buildConfiguration == m_target->activeBuildConfiguration())
return;
m_buildConfiguration = m_target->activeBuildConfiguration();
for (int i = 0; i < m_buildConfigurationComboBox->count(); ++i) {
if (m_buildConfigurationComboBox->itemData(i).value<BuildConfiguration *>() == m_buildConfiguration) {
m_buildConfigurationComboBox->setCurrentIndex(i);
break;
}
}
foreach (QWidget *widget, subWidgets()) {
if (BuildConfigWidget *buildStepWidget = qobject_cast<BuildConfigWidget*>(widget)) {
buildStepWidget->init(m_buildConfiguration);
}
}
}
void BuildSettingsWidget::createConfiguration()
{
if (!m_target->buildConfigurationFactory())
return;
QAction *action = qobject_cast<QAction *>(sender());
const QString &id = action->data().toString();
BuildConfiguration *bc = m_target->buildConfigurationFactory()->create(m_target, id);
if (bc) {
m_target->setActiveBuildConfiguration(bc);
updateBuildSettings();
}
}
void BuildSettingsWidget::cloneConfiguration()
{
cloneConfiguration(m_buildConfiguration);
}
void BuildSettingsWidget::deleteConfiguration()
{
deleteConfiguration(m_buildConfiguration);
}
void BuildSettingsWidget::cloneConfiguration(BuildConfiguration *sourceConfiguration)
{
if (!sourceConfiguration ||
!m_target->buildConfigurationFactory())
return;
QString newDisplayName(QInputDialog::getText(this, tr("Clone configuration"), tr("New Configuration Name:")));
if (newDisplayName.isEmpty())
return;
QStringList buildConfigurationDisplayNames;
foreach(BuildConfiguration *bc, m_target->buildConfigurations())
buildConfigurationDisplayNames << bc->displayName();
newDisplayName = Project::makeUnique(newDisplayName, buildConfigurationDisplayNames);
BuildConfiguration * bc(m_target->buildConfigurationFactory()->clone(m_target, sourceConfiguration));
if (!bc)
return;
bc->setDisplayName(newDisplayName);
m_target->addBuildConfiguration(bc);
updateBuildSettings();
m_target->setActiveBuildConfiguration(bc);
}
void BuildSettingsWidget::deleteConfiguration(BuildConfiguration *deleteConfiguration)
{
if (!deleteConfiguration ||
m_target->buildConfigurations().size() <= 1)
return;
m_target->removeBuildConfiguration(deleteConfiguration);
updateBuildSettings();
}
<|endoftext|> |
<commit_before>/// @file
/// @author Boris Mikic
/// @version 2.62
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php
#ifdef HAVE_WAV
#include <string.h>
#include <hltypes/hresource.h>
#include "AudioManager.h"
#include "WAV_Source.h"
#include "xal.h"
namespace xal
{
WAV_Source::WAV_Source(chstr filename, Category* category) : Source(filename, category)
{
}
WAV_Source::~WAV_Source()
{
this->close();
}
bool WAV_Source::open()
{
this->streamOpen = Source::open();
if (!this->streamOpen)
{
return false;
}
unsigned char buffer[5] = {0};
this->stream->read_raw(buffer, 4); // RIFF
this->stream->read_raw(buffer, 4); // file size
this->stream->read_raw(buffer, 4); // WAVE
hstr tag;
int size = 0;
short value16;
int value32;
while (!this->stream->eof())
{
this->stream->read_raw(buffer, 4); // next tag
tag = (char*)buffer;
this->stream->read_raw(buffer, 4); // size of the chunk
#ifdef __BIG_ENDIAN__ // TODO - this should be tested properly
XAL_NORMALIZE_ENDIAN(*(uint32_t*)buffer);
#endif
memcpy(&size, buffer, 4);
if (tag == "fmt ")
{
/// TODO - implement hresource::read_little_endian and hresource::read_big_endian
// format
this->stream->read_raw(buffer, 2);
#ifdef __BIG_ENDIAN__ // TODO - this should be tested properly
XAL_NORMALIZE_ENDIAN(*(uint16_t*)buffer);
#endif
memcpy(&value16, buffer, 2);
if (size == 16 && value16 == 1)
{
// channels
this->stream->read_raw(buffer, 2);
#ifdef __BIG_ENDIAN__ // TODO - this should be tested properly
XAL_NORMALIZE_ENDIAN(*(uint16_t*)buffer);
#endif
memcpy(&value16, buffer, 2);
this->channels = value16;
// sampling rate
this->stream->read_raw(buffer, 4);
#ifdef __BIG_ENDIAN__ // TODO - this should be tested properly
XAL_NORMALIZE_ENDIAN(*(uint32_t*)buffer);
#endif
memcpy(&value32, buffer, 4);
this->samplingRate = value32;
// bytes rate
this->stream->read_raw(buffer, 4);
// blockalign
this->stream->read_raw(buffer, 2);
// bits per sample
this->stream->read_raw(buffer, 2);
#ifdef __BIG_ENDIAN__ // TODO - this should be tested properly
XAL_NORMALIZE_ENDIAN(*(uint16_t*)buffer);
#endif
memcpy(&value16, buffer, 2);
this->bitsPerSample = value16;
size = 0;
}
else // not PCM, some form of compressed format
{
size -= 2;
this->close();
break;
}
}
else if (tag == "data")
{
this->size += size;
}
if (size > 0)
{
this->stream->seek(size);
}
}
this->duration = (float)this->size / (this->samplingRate * this->channels * this->bitsPerSample / 8);
this->_findData();
return this->streamOpen;
}
void WAV_Source::rewind()
{
if (this->streamOpen)
{
this->_findData();
}
}
void WAV_Source::_findData()
{
this->stream->rewind();
unsigned char buffer[5] = {0};
this->stream->read_raw(buffer, 4); // RIFF
this->stream->read_raw(buffer, 4); // file size
this->stream->read_raw(buffer, 4); // WAVE
hstr tag;
int size = 0;
while (!this->stream->eof())
{
this->stream->read_raw(buffer, 4); // next tag
tag = (char*)buffer;
this->stream->read_raw(buffer, 4); // size of the chunk
#ifdef __BIG_ENDIAN__ // TODO - this should be tested properly
XAL_NORMALIZE_ENDIAN(*(uint32_t*)buffer);
#endif
memcpy(&size, buffer, 4);
if (tag == "data")
{
break;
}
if (size > 0)
{
this->stream->seek(size);
}
}
}
bool WAV_Source::load(unsigned char* output)
{
if (Source::load(output) == 0)
{
return 0;
}
return this->stream->read_raw(output, this->size);
}
int WAV_Source::loadChunk(unsigned char* output, int size)
{
if (Source::loadChunk(output, size) == 0)
{
return 0;
}
return this->stream->read_raw(output, size);
}
}
#endif
<commit_msg>- small update<commit_after>/// @file
/// @author Boris Mikic
/// @version 2.62
///
/// @section LICENSE
///
/// This program is free software; you can redistribute it and/or modify it under
/// the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php
#ifdef HAVE_WAV
#include <string.h>
#include <hltypes/hresource.h>
#include "AudioManager.h"
#include "WAV_Source.h"
#include "xal.h"
namespace xal
{
WAV_Source::WAV_Source(chstr filename, Category* category) : Source(filename, category)
{
}
WAV_Source::~WAV_Source()
{
this->close();
}
bool WAV_Source::open()
{
this->streamOpen = Source::open();
if (!this->streamOpen)
{
return false;
}
unsigned char buffer[5] = {0};
this->stream->read_raw(buffer, 4); // RIFF
this->stream->read_raw(buffer, 4); // file size
this->stream->read_raw(buffer, 4); // WAVE
hstr tag;
int size = 0;
short value16;
int value32;
while (!this->stream->eof())
{
this->stream->read_raw(buffer, 4); // next tag
tag = (char*)buffer;
this->stream->read_raw(buffer, 4); // size of the chunk
#ifdef __BIG_ENDIAN__ // TODO - this should be tested properly
XAL_NORMALIZE_ENDIAN(*(uint32_t*)buffer);
#endif
memcpy(&size, buffer, 4);
if (tag == "fmt ")
{
/// TODO - implement hresource::read_little_endian and hresource::read_big_endian
// format
this->stream->read_raw(buffer, 2);
#ifdef __BIG_ENDIAN__ // TODO - this should be tested properly
XAL_NORMALIZE_ENDIAN(*(uint16_t*)buffer);
#endif
memcpy(&value16, buffer, 2);
if (size == 16 && value16 == 1)
{
// channels
this->stream->read_raw(buffer, 2);
#ifdef __BIG_ENDIAN__ // TODO - this should be tested properly
XAL_NORMALIZE_ENDIAN(*(uint16_t*)buffer);
#endif
memcpy(&value16, buffer, 2);
this->channels = value16;
// sampling rate
this->stream->read_raw(buffer, 4);
#ifdef __BIG_ENDIAN__ // TODO - this should be tested properly
XAL_NORMALIZE_ENDIAN(*(uint32_t*)buffer);
#endif
memcpy(&value32, buffer, 4);
this->samplingRate = value32;
// bytes rate
this->stream->read_raw(buffer, 4);
// blockalign
this->stream->read_raw(buffer, 2);
// bits per sample
this->stream->read_raw(buffer, 2);
#ifdef __BIG_ENDIAN__ // TODO - this should be tested properly
XAL_NORMALIZE_ENDIAN(*(uint16_t*)buffer);
#endif
memcpy(&value16, buffer, 2);
this->bitsPerSample = value16;
size = 0;
}
else // not PCM, some form of compressed format
{
size -= 2;
this->close();
break;
}
}
else if (tag == "data")
{
this->size += size;
}
if (size > 0)
{
this->stream->seek(size);
}
}
this->duration = (float)this->size / (this->samplingRate * this->channels * this->bitsPerSample / 8);
this->_findData();
return this->streamOpen;
}
void WAV_Source::rewind()
{
if (this->streamOpen)
{
this->_findData();
}
}
void WAV_Source::_findData()
{
this->stream->rewind();
unsigned char buffer[5] = {0};
this->stream->read_raw(buffer, 4); // RIFF
this->stream->read_raw(buffer, 4); // file size
this->stream->read_raw(buffer, 4); // WAVE
hstr tag;
int size = 0;
while (!this->stream->eof())
{
this->stream->read_raw(buffer, 4); // next tag
tag = (char*)buffer;
this->stream->read_raw(buffer, 4); // size of the chunk
#ifdef __BIG_ENDIAN__ // TODO - this should be tested properly
XAL_NORMALIZE_ENDIAN(*(uint32_t*)buffer);
#endif
memcpy(&size, buffer, 4);
if (tag == "data")
{
break;
}
if (size > 0)
{
this->stream->seek(size);
}
}
}
bool WAV_Source::load(unsigned char* output)
{
if (Source::load(output) == 0)
{
return false;
}
this->stream->read_raw(output, this->size);
return true;
}
int WAV_Source::loadChunk(unsigned char* output, int size)
{
if (Source::loadChunk(output, size) == 0)
{
return 0;
}
return this->stream->read_raw(output, size);
}
}
#endif
<|endoftext|> |
<commit_before>/*
* Copyright (c) The Shogun Machine Learning Toolbox
* Written (W) 2013 Heiko Strathmann
* Written (w) 2014 - 2016 Soumyajit De
* 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.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the Shogun Development Team.
*/
#include <algorithm>
#include <shogun/lib/SGVector.h>
#include <shogun/lib/SGMatrix.h>
#include <shogun/kernel/Kernel.h>
#include <shogun/statistical_testing/MMD.h>
#include <shogun/statistical_testing/internals/MaxXValidation.h>
#include <shogun/statistical_testing/internals/KernelManager.h>
#include <shogun/statistical_testing/internals/DataManager.h>
using namespace shogun;
using namespace internal;
MaxXValidation::MaxXValidation(KernelManager& km, CMMD* est, const index_t& M, const float64_t& alp)
: KernelSelection(km, est), num_run(M), alpha(alp)
{
REQUIRE(num_run>0, "Number of runs is %d!\n", num_run);
REQUIRE(alpha>=0.0 && alpha<=1.0, "Threshold is %f!\n", alpha);
}
MaxXValidation::~MaxXValidation()
{
}
SGVector<float64_t> MaxXValidation::get_measure_vector()
{
return measures;
}
SGMatrix<float64_t> MaxXValidation::get_measure_matrix()
{
return rejections;
}
void MaxXValidation::init_measures()
{
const index_t num_kernels=kernel_mgr.num_kernels();
auto& data_mgr=estimator->get_data_mgr();
const index_t N=data_mgr.get_num_folds();
REQUIRE(N!=0, "Number of folds is not set!\n");
if (rejections.num_rows!=N*num_run || rejections.num_cols!=num_kernels)
rejections=SGMatrix<float64_t>(N*num_run, num_kernels);
std::fill(rejections.data(), rejections.data()+rejections.size(), 0);
if (measures.size()!=num_kernels)
measures=SGVector<float64_t>(num_kernels);
std::fill(measures.data(), measures.data()+measures.size(), 0);
}
void MaxXValidation::compute_measures()
{
auto& data_mgr=estimator->get_data_mgr();
data_mgr.set_cross_validation_mode(true);
const index_t N=data_mgr.get_num_folds();
SG_SINFO("Performing %d fold cross-validattion!\n", N);
const size_t num_kernels=kernel_mgr.num_kernels();
auto existing_kernel=estimator->get_kernel();
for (auto i=0; i<num_run; ++i)
{
data_mgr.shuffle_features();
for (auto j=0; j<N; ++j)
{
data_mgr.use_fold(j);
SG_SDEBUG("Running fold %d\n", j);
for (size_t k=0; k<num_kernels; ++k)
{
auto kernel=kernel_mgr.kernel_at(k);
estimator->set_kernel(kernel);
auto statistic=estimator->compute_statistic();
rejections(i*N+j, k)=estimator->compute_p_value(statistic)<alpha;
estimator->cleanup();
}
}
data_mgr.unshuffle_features();
}
data_mgr.set_cross_validation_mode(false);
estimator->set_kernel(existing_kernel);
for (auto j=0; j<rejections.num_cols; ++j)
{
auto begin=rejections.get_column_vector(j);
auto size=rejections.num_rows;
measures[j]=std::accumulate(begin, begin+size, 0)/size;
}
}
CKernel* MaxXValidation::select_kernel()
{
init_measures();
compute_measures();
auto max_element=std::max_element(measures.vector, measures.vector+measures.vlen);
auto max_idx=std::distance(measures.vector, max_element);
SG_SDEBUG("Selected kernel at %d position!\n", max_idx);
return kernel_mgr.kernel_at(max_idx);
}
<commit_msg>fixed cross validation bug<commit_after>/*
* Copyright (c) The Shogun Machine Learning Toolbox
* Written (W) 2013 Heiko Strathmann
* Written (w) 2014 - 2016 Soumyajit De
* 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.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the Shogun Development Team.
*/
#include <algorithm>
#include <shogun/lib/SGVector.h>
#include <shogun/lib/SGMatrix.h>
#include <shogun/kernel/Kernel.h>
#include <shogun/statistical_testing/MMD.h>
#include <shogun/statistical_testing/internals/MaxXValidation.h>
#include <shogun/statistical_testing/internals/KernelManager.h>
#include <shogun/statistical_testing/internals/DataManager.h>
using namespace shogun;
using namespace internal;
MaxXValidation::MaxXValidation(KernelManager& km, CMMD* est, const index_t& M, const float64_t& alp)
: KernelSelection(km, est), num_run(M), alpha(alp)
{
REQUIRE(num_run>0, "Number of runs is %d!\n", num_run);
REQUIRE(alpha>=0.0 && alpha<=1.0, "Threshold is %f!\n", alpha);
}
MaxXValidation::~MaxXValidation()
{
}
SGVector<float64_t> MaxXValidation::get_measure_vector()
{
return measures;
}
SGMatrix<float64_t> MaxXValidation::get_measure_matrix()
{
return rejections;
}
void MaxXValidation::init_measures()
{
const index_t num_kernels=kernel_mgr.num_kernels();
auto& data_mgr=estimator->get_data_mgr();
const index_t N=data_mgr.get_num_folds();
REQUIRE(N!=0, "Number of folds is not set!\n");
if (rejections.num_rows!=N*num_run || rejections.num_cols!=num_kernels)
rejections=SGMatrix<float64_t>(N*num_run, num_kernels);
std::fill(rejections.data(), rejections.data()+rejections.size(), 0);
if (measures.size()!=num_kernels)
measures=SGVector<float64_t>(num_kernels);
std::fill(measures.data(), measures.data()+measures.size(), 0);
}
void MaxXValidation::compute_measures()
{
auto& data_mgr=estimator->get_data_mgr();
data_mgr.set_cross_validation_mode(true);
const index_t N=data_mgr.get_num_folds();
SG_SINFO("Performing %d fold cross-validattion!\n", N);
const size_t num_kernels=kernel_mgr.num_kernels();
auto existing_kernel=estimator->get_kernel();
for (auto i=0; i<num_run; ++i)
{
data_mgr.shuffle_features();
for (auto j=0; j<N; ++j)
{
data_mgr.use_fold(j);
SG_SDEBUG("Running fold %d\n", j);
for (size_t k=0; k<num_kernels; ++k)
{
auto kernel=kernel_mgr.kernel_at(k);
estimator->set_kernel(kernel);
auto statistic=estimator->compute_statistic();
rejections(i*N+j, k)=estimator->compute_p_value(statistic)<alpha;
estimator->cleanup();
}
}
data_mgr.unshuffle_features();
}
data_mgr.set_cross_validation_mode(false);
estimator->set_kernel(existing_kernel);
for (auto j=0; j<rejections.num_cols; ++j)
{
auto begin=rejections.get_column_vector(j);
auto size=rejections.num_rows;
measures[j]=std::accumulate(begin, begin+size, 0)/float64_t(size);
}
}
CKernel* MaxXValidation::select_kernel()
{
init_measures();
compute_measures();
auto max_element=std::max_element(measures.vector, measures.vector+measures.vlen);
auto max_idx=std::distance(measures.vector, max_element);
SG_SDEBUG("Selected kernel at %d position!\n", max_idx);
return kernel_mgr.kernel_at(max_idx);
}
<|endoftext|> |
<commit_before>#ifndef STAN_LANG_GENERATOR_GENERATE_FUNCTION_INSTANTIATION_HPP
#define STAN_LANG_GENERATOR_GENERATE_FUNCTION_INSTANTIATION_HPP
#include <stan/lang/ast.hpp>
#include <stan/lang/generator/constants.hpp>
#include <stan/lang/generator/generate_function_inline_return_type.hpp>
#include <stan/lang/generator/generate_function_instantiation_body.hpp>
#include <stan/lang/generator/generate_function_instantiation_name.hpp>
#include <ostream>
#include <string>
namespace stan {
namespace lang {
/**
* Generate a non-variable (double only) instantiation of specified
* function and optionally its default for propto=false
* for functions ending in _log.
*
* Exact behavior differs for unmarked functions, and functions
* ending in one of "_rng", "_lp", or "_log".
*
* @param[in] fun function AST object
* @param[in, out] out output stream to which function definition
* is written
*/
void generate_function_instantiation(const function_decl_def& fun,
std::ostream& out) {
// Do not generate anything for forward decalrations
if (fun.body_.is_no_op_statement()) {
return;
}
// Functions that have only int args were not templated in the first place
// => they are already instantiated
if (has_only_int_args(fun)) {
return;
}
bool is_rng = ends_with("_rng", fun.name_);
bool is_lp = ends_with("_lp", fun.name_);
bool is_pf = ends_with("_log", fun.name_)
|| ends_with("_lpdf", fun.name_) || ends_with("_lpmf", fun.name_);
// scalar type is always double for instantiations
std::string scalar_t_name = "double";
std::string rng_class = "boost::ecuyer1988";
generate_function_inline_return_type(fun, scalar_t_name, 0, out);
generate_function_instantiation_name(fun, out);
generate_function_arguments(
fun, is_rng, is_lp, is_pf, out, true /*no templates*/, rng_class);
generate_function_instantiation_body(
fun, is_rng, is_lp, is_pf, rng_class, out);
out << EOL;
}
}
}
#endif
<commit_msg>Fixed header issues<commit_after>#ifndef STAN_LANG_GENERATOR_GENERATE_FUNCTION_INSTANTIATION_HPP
#define STAN_LANG_GENERATOR_GENERATE_FUNCTION_INSTANTIATION_HPP
#include <stan/lang/ast.hpp>
#include <stan/lang/generator/constants.hpp>
#include <stan/lang/generator/generate_function_inline_return_type.hpp>
#include <stan/lang/generator/generate_function_instantiation_body.hpp>
#include <stan/lang/generator/generate_function_instantiation_name.hpp>
#include <stan/lang/generator/generate_function_arguments.hpp>
#include <stan/lang/generator/has_only_int_args.hpp>
#include <ostream>
#include <string>
namespace stan {
namespace lang {
/**
* Generate a non-variable (double only) instantiation of specified
* function and optionally its default for propto=false
* for functions ending in _log.
*
* Exact behavior differs for unmarked functions, and functions
* ending in one of "_rng", "_lp", or "_log".
*
* @param[in] fun function AST object
* @param[in, out] out output stream to which function definition
* is written
*/
void generate_function_instantiation(const function_decl_def& fun,
std::ostream& out) {
// Do not generate anything for forward decalrations
if (fun.body_.is_no_op_statement()) {
return;
}
// Functions that have only int args were not templated in the first place
// => they are already instantiated
if (has_only_int_args(fun)) {
return;
}
bool is_rng = ends_with("_rng", fun.name_);
bool is_lp = ends_with("_lp", fun.name_);
bool is_pf = ends_with("_log", fun.name_)
|| ends_with("_lpdf", fun.name_) || ends_with("_lpmf", fun.name_);
// scalar type is always double for instantiations
std::string scalar_t_name = "double";
std::string rng_class = "boost::ecuyer1988";
generate_function_inline_return_type(fun, scalar_t_name, 0, out);
generate_function_instantiation_name(fun, out);
generate_function_arguments(
fun, is_rng, is_lp, is_pf, out, true /*no templates*/, rng_class);
generate_function_instantiation_body(
fun, is_rng, is_lp, is_pf, rng_class, out);
out << EOL;
}
}
}
#endif
<|endoftext|> |
<commit_before>// client.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <codecvt>
#include <algorithm>
#include "git2.h"
#include "ConsoleLogger.h"
#include "RemoteLink.h"
#include <TlHelp32.h>
#include <WinBase.h>
#include <process.h>
void killProcessByName(const wstring& name)
{
HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL);
PROCESSENTRY32 pEntry;
pEntry.dwSize = sizeof(pEntry);
BOOL hRes = Process32First(hSnapShot, &pEntry);
wstring nameToMatch = name;
std::transform(nameToMatch.begin(), nameToMatch.end(), nameToMatch.begin(), ::toupper);
while (hRes)
{
wstring procName = pEntry.szExeFile;
std::transform(procName.begin(), procName.end(), procName.begin(), ::toupper);
if (procName == nameToMatch)
{
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0,
(DWORD)pEntry.th32ProcessID);
if (hProcess != NULL)
{
TerminateProcess(hProcess, 9);
CloseHandle(hProcess);
}
}
hRes = Process32Next(hSnapShot, &pEntry);
}
CloseHandle(hSnapShot);
}
const wstring GetState(const CacheServiceResponse& response)
{
wstring result;
DWORD status = response.state;
switch (response.state)
{
case GIT_REPOSITORY_STATE_NONE:
result = L"";
break;
case GIT_REPOSITORY_STATE_MERGE:
result = L"Merge";
break;
case GIT_REPOSITORY_STATE_REVERT:
result = L"Revert";
break;
case GIT_REPOSITORY_STATE_CHERRY_PICK:
result = L"Cherry-pick";
break;
case GIT_REPOSITORY_STATE_BISECT:
result = L"Bisect";
break;
case GIT_REPOSITORY_STATE_REBASE:
result = L"Rebase";
break;
case GIT_REPOSITORY_STATE_REBASE_INTERACTIVE:
result = L"Rebase-i";
break;
case GIT_REPOSITORY_STATE_REBASE_MERGE:
result = L"Rebase-Merge";
break;
case GIT_REPOSITORY_STATE_APPLY_MAILBOX:
result = L"Apply-Mailbox";
break;
case GIT_REPOSITORY_STATE_APPLY_MAILBOX_OR_REBASE:
result = L"Apply-Mailbox/Rebase";
break;
default:
result = L"unknown";
break;
}
return result;
}
int _tmain(int argc, _TCHAR* argv[])
{
CRemoteLink remoteLink;
CacheServiceRequest request;
wchar_t* currentDir = new wchar_t[MAX_PATH];
int index = 1;
if (argc == 2)
{
wcscpy(currentDir, argv[index++]);
}
else
{
if (GetCurrentDirectory(MAX_PATH, currentDir) <= 0)
{
Logger::LogError(_T("Unable to get current directory."));
return 2;
}
}
CacheServiceResponse response;
remoteLink.GetStatus(currentDir, response);
wstring_convert<codecvt_utf8<wchar_t>> converter;
wstring branch(response.branch);
if (response.isSuccess)
{
UINT codePage = 65001; // UTF-8
if (IsValidCodePage(codePage))
SetConsoleOutputCP(codePage);
wprintf(L"(%S) i[+%d, -%d, ~%d] w[+%d, -%d, ~%d] (%s)", converter.to_bytes(branch).c_str(), response.n_addedIndex, response.n_deletedIndex, response.n_modifiedIndex, response.n_addedWorkDir, response.n_deletedWorkDir, response.n_modifiedWorkDir, GetState(response).c_str());
return 0;
}
return 1;
}
<commit_msg>Restore code page after writing to console.<commit_after>// client.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <codecvt>
#include <algorithm>
#include "git2.h"
#include "ConsoleLogger.h"
#include "RemoteLink.h"
#include <TlHelp32.h>
#include <WinBase.h>
#include <process.h>
void killProcessByName(const wstring& name)
{
HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, NULL);
PROCESSENTRY32 pEntry;
pEntry.dwSize = sizeof(pEntry);
BOOL hRes = Process32First(hSnapShot, &pEntry);
wstring nameToMatch = name;
std::transform(nameToMatch.begin(), nameToMatch.end(), nameToMatch.begin(), ::toupper);
while (hRes)
{
wstring procName = pEntry.szExeFile;
std::transform(procName.begin(), procName.end(), procName.begin(), ::toupper);
if (procName == nameToMatch)
{
HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0,
(DWORD)pEntry.th32ProcessID);
if (hProcess != NULL)
{
TerminateProcess(hProcess, 9);
CloseHandle(hProcess);
}
}
hRes = Process32Next(hSnapShot, &pEntry);
}
CloseHandle(hSnapShot);
}
const wstring GetState(const CacheServiceResponse& response)
{
wstring result;
DWORD status = response.state;
switch (response.state)
{
case GIT_REPOSITORY_STATE_NONE:
result = L"";
break;
case GIT_REPOSITORY_STATE_MERGE:
result = L"Merge";
break;
case GIT_REPOSITORY_STATE_REVERT:
result = L"Revert";
break;
case GIT_REPOSITORY_STATE_CHERRY_PICK:
result = L"Cherry-pick";
break;
case GIT_REPOSITORY_STATE_BISECT:
result = L"Bisect";
break;
case GIT_REPOSITORY_STATE_REBASE:
result = L"Rebase";
break;
case GIT_REPOSITORY_STATE_REBASE_INTERACTIVE:
result = L"Rebase-i";
break;
case GIT_REPOSITORY_STATE_REBASE_MERGE:
result = L"Rebase-Merge";
break;
case GIT_REPOSITORY_STATE_APPLY_MAILBOX:
result = L"Apply-Mailbox";
break;
case GIT_REPOSITORY_STATE_APPLY_MAILBOX_OR_REBASE:
result = L"Apply-Mailbox/Rebase";
break;
default:
result = L"unknown";
break;
}
return result;
}
int _tmain(int argc, _TCHAR* argv[])
{
CRemoteLink remoteLink;
CacheServiceRequest request;
wchar_t* currentDir = new wchar_t[MAX_PATH];
int index = 1;
if (argc == 2)
{
wcscpy(currentDir, argv[index++]);
}
else
{
if (GetCurrentDirectory(MAX_PATH, currentDir) <= 0)
{
Logger::LogError(_T("Unable to get current directory."));
return 2;
}
}
CacheServiceResponse response;
remoteLink.GetStatus(currentDir, response);
wstring_convert<codecvt_utf8<wchar_t>> converter;
wstring branch(response.branch);
if (response.isSuccess)
{
UINT codePage = 65001; // UTF-8
UINT oldCodePage = GetConsoleOutputCP();
if (IsValidCodePage(codePage))
SetConsoleOutputCP(codePage);
wprintf(L"(%S) i[+%d, -%d, ~%d] w[+%d, -%d, ~%d] (%s)", converter.to_bytes(branch).c_str(), response.n_addedIndex, response.n_deletedIndex, response.n_modifiedIndex, response.n_addedWorkDir, response.n_deletedWorkDir, response.n_modifiedWorkDir, GetState(response).c_str());
SetConsoleOutputCP(oldCodePage);
return 0;
}
return 1;
}
<|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 2011 Konstantin Oblaukhov <[email protected]>
//
#include "GeoPolygonGraphicsItem.h"
#include "GeoPainter.h"
#include "ViewportParams.h"
#include "GeoDataStyle.h"
namespace Marble
{
GeoPolygonGraphicsItem::GeoPolygonGraphicsItem( const GeoDataPolygon* polygon )
: GeoGraphicsItem(),
m_polygon( polygon ),
m_ring( 0 )
{
Q_ASSERT( ( m_ring == 0 ) ^ ( m_polygon == 0 ) && "You must not pass a 0 polygon ");
}
GeoPolygonGraphicsItem::GeoPolygonGraphicsItem( const GeoDataLinearRing* ring )
: GeoGraphicsItem(),
m_polygon( 0 ),
m_ring( ring )
{
Q_ASSERT( ( m_ring == 0 ) ^ ( m_polygon == 0 ) && "You must not pass a 0 ring ");
}
void GeoPolygonGraphicsItem::setPolygon( const GeoDataPolygon* polygon )
{
m_polygon = polygon;
m_ring = 0;
Q_ASSERT( ( m_ring == 0 ) ^ ( m_polygon == 0 ) && "You must not pass a 0 polygon ");
}
void GeoPolygonGraphicsItem::setLinearRing( const GeoDataLinearRing* ring )
{
m_polygon = 0;
m_ring = ring;
Q_ASSERT( ( m_ring == 0 ) ^ ( m_polygon == 0 ) && "You must not pass a 0 ring ");
}
GeoDataCoordinates GeoPolygonGraphicsItem::coordinate() const
{
if( m_polygon ) {
return m_polygon->latLonAltBox().center();
} else if ( m_ring ) {
return m_ring->latLonAltBox().center();
}
}
void GeoPolygonGraphicsItem::coordinate( qreal &longitude, qreal &latitude, qreal &altitude ) const
{
GeoDataCoordinates coords;
if( m_polygon ) {
coords = m_polygon->latLonAltBox().center();
} else if ( m_ring ) {
coords = m_ring->latLonAltBox().center();
}
longitude = coords.longitude();
latitude = coords.latitude();
altitude = coords.altitude();
}
GeoDataLatLonAltBox GeoPolygonGraphicsItem::latLonAltBox() const
{
if( m_polygon ) {
return m_polygon->latLonAltBox();
} else if ( m_ring ) {
return m_ring->latLonAltBox();
}
}
void GeoPolygonGraphicsItem::paint( GeoPainter* painter, ViewportParams* viewport,
const QString& renderPos, GeoSceneLayer* layer )
{
Q_UNUSED( viewport );
Q_UNUSED( renderPos );
Q_UNUSED( layer );
if ( !style() )
{
painter->save();
painter->setPen( QPen() );
if ( m_polygon ) {
painter->drawPolygon( *m_polygon );
} else if ( m_ring ) {
painter->drawPolygon( *m_ring );
}
painter->restore();
return;
}
painter->save();
QPen currentPen = painter->pen();
if ( !style()->polyStyle().outline() )
{
currentPen.setColor( Qt::transparent );
}
else
{
if ( currentPen.color() != style()->lineStyle().color() ||
currentPen.widthF() != style()->lineStyle().width() )
{
currentPen.setColor( style()->lineStyle().color() );
currentPen.setWidthF( style()->lineStyle().width() );
}
if ( currentPen.capStyle() != style()->lineStyle().capStyle() )
currentPen.setCapStyle( style()->lineStyle().capStyle() );
if ( currentPen.style() != style()->lineStyle().penStyle() )
currentPen.setStyle( style()->lineStyle().penStyle() );
if ( painter->mapQuality() != Marble::HighQuality
&& painter->mapQuality() != Marble::PrintQuality )
{
QColor penColor = currentPen.color();
penColor.setAlpha( 255 );
currentPen.setColor( penColor );
}
}
if ( painter->pen() != currentPen ) painter->setPen( currentPen );
if ( !style()->polyStyle().fill() )
{
if ( painter->brush().color() != Qt::transparent )
painter->setBrush( QColor( Qt::transparent ) );
}
else
{
if ( painter->brush().color() != style()->polyStyle().color() )
{
painter->setBrush( style()->polyStyle().color() );
}
}
if ( m_polygon ) {
painter->drawPolygon( *m_polygon );
} else if ( m_ring ) {
painter->drawPolygon( *m_ring );
}
painter->restore();
}
}
<commit_msg>Return empty values if nothing is set.<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 2011 Konstantin Oblaukhov <[email protected]>
//
#include "GeoPolygonGraphicsItem.h"
#include "GeoPainter.h"
#include "ViewportParams.h"
#include "GeoDataStyle.h"
namespace Marble
{
GeoPolygonGraphicsItem::GeoPolygonGraphicsItem( const GeoDataPolygon* polygon )
: GeoGraphicsItem(),
m_polygon( polygon ),
m_ring( 0 )
{
Q_ASSERT( ( m_ring == 0 ) ^ ( m_polygon == 0 ) && "You must not pass a 0 polygon ");
}
GeoPolygonGraphicsItem::GeoPolygonGraphicsItem( const GeoDataLinearRing* ring )
: GeoGraphicsItem(),
m_polygon( 0 ),
m_ring( ring )
{
Q_ASSERT( ( m_ring == 0 ) ^ ( m_polygon == 0 ) && "You must not pass a 0 ring ");
}
void GeoPolygonGraphicsItem::setPolygon( const GeoDataPolygon* polygon )
{
m_polygon = polygon;
m_ring = 0;
Q_ASSERT( ( m_ring == 0 ) ^ ( m_polygon == 0 ) && "You must not pass a 0 polygon ");
}
void GeoPolygonGraphicsItem::setLinearRing( const GeoDataLinearRing* ring )
{
m_polygon = 0;
m_ring = ring;
Q_ASSERT( ( m_ring == 0 ) ^ ( m_polygon == 0 ) && "You must not pass a 0 ring ");
}
GeoDataCoordinates GeoPolygonGraphicsItem::coordinate() const
{
if( m_polygon ) {
return m_polygon->latLonAltBox().center();
} else if ( m_ring ) {
return m_ring->latLonAltBox().center();
} else {
return GeoDataCoordinates();
}
}
void GeoPolygonGraphicsItem::coordinate( qreal &longitude, qreal &latitude, qreal &altitude ) const
{
GeoDataCoordinates coords;
if( m_polygon ) {
coords = m_polygon->latLonAltBox().center();
} else if ( m_ring ) {
coords = m_ring->latLonAltBox().center();
}
longitude = coords.longitude();
latitude = coords.latitude();
altitude = coords.altitude();
}
GeoDataLatLonAltBox GeoPolygonGraphicsItem::latLonAltBox() const
{
if( m_polygon ) {
return m_polygon->latLonAltBox();
} else if ( m_ring ) {
return m_ring->latLonAltBox();
} else {
return GeoDataLatLonAltBox::fromLineString( GeoDataLineString() << GeoDataCoordinates() );
}
}
void GeoPolygonGraphicsItem::paint( GeoPainter* painter, ViewportParams* viewport,
const QString& renderPos, GeoSceneLayer* layer )
{
Q_UNUSED( viewport );
Q_UNUSED( renderPos );
Q_UNUSED( layer );
if ( !style() )
{
painter->save();
painter->setPen( QPen() );
if ( m_polygon ) {
painter->drawPolygon( *m_polygon );
} else if ( m_ring ) {
painter->drawPolygon( *m_ring );
}
painter->restore();
return;
}
painter->save();
QPen currentPen = painter->pen();
if ( !style()->polyStyle().outline() )
{
currentPen.setColor( Qt::transparent );
}
else
{
if ( currentPen.color() != style()->lineStyle().color() ||
currentPen.widthF() != style()->lineStyle().width() )
{
currentPen.setColor( style()->lineStyle().color() );
currentPen.setWidthF( style()->lineStyle().width() );
}
if ( currentPen.capStyle() != style()->lineStyle().capStyle() )
currentPen.setCapStyle( style()->lineStyle().capStyle() );
if ( currentPen.style() != style()->lineStyle().penStyle() )
currentPen.setStyle( style()->lineStyle().penStyle() );
if ( painter->mapQuality() != Marble::HighQuality
&& painter->mapQuality() != Marble::PrintQuality )
{
QColor penColor = currentPen.color();
penColor.setAlpha( 255 );
currentPen.setColor( penColor );
}
}
if ( painter->pen() != currentPen ) painter->setPen( currentPen );
if ( !style()->polyStyle().fill() )
{
if ( painter->brush().color() != Qt::transparent )
painter->setBrush( QColor( Qt::transparent ) );
}
else
{
if ( painter->brush().color() != style()->polyStyle().color() )
{
painter->setBrush( style()->polyStyle().color() );
}
}
if ( m_polygon ) {
painter->drawPolygon( *m_polygon );
} else if ( m_ring ) {
painter->drawPolygon( *m_ring );
}
painter->restore();
}
}
<|endoftext|> |
<commit_before>#pragma once
namespace blackhole {
namespace sink {
namespace files {
template<class Backend>
class flusher_t {
bool autoflush;
Backend& backend;
public:
flusher_t(bool autoflush, Backend& backend) :
autoflush(autoflush),
backend(backend)
{}
void flush() {
if (autoflush) {
backend.flush();
}
}
};
} // namespace files
} // namespace sink
} // namespace blackhole
<commit_msg>[Code Style] File flusher.<commit_after>#pragma once
namespace blackhole {
namespace sink {
namespace files {
template<class Backend>
class flusher_t {
public:
typedef Backend backend_type;
private:
bool autoflush;
backend_type& backend;
public:
flusher_t(bool autoflush, backend_type& backend) :
autoflush(autoflush),
backend(backend)
{}
void flush() {
if (autoflush) {
backend.flush();
}
}
};
} // namespace files
} // namespace sink
} // namespace blackhole
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "arith_uint256.h"
#include "crypto/common.h"
#include "uint256.h"
#include "utilstrencodings.h"
#include <stdio.h>
#include <string.h>
template <unsigned int BITS>
base_uint<BITS>::base_uint(const std::string &str)
{
SetHex(str);
}
template <unsigned int BITS>
base_uint<BITS> &base_uint<BITS>::operator<<=(unsigned int shift)
{
base_uint<BITS> a(*this);
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
int k = shift / 32;
shift = shift % 32;
for (int i = 0; i < WIDTH; i++)
{
if (i + k + 1 < WIDTH && shift != 0)
pn[i + k + 1] |= (a.pn[i] >> (32 - shift));
if (i + k < WIDTH)
pn[i + k] |= (a.pn[i] << shift);
}
return *this;
}
template <unsigned int BITS>
base_uint<BITS> &base_uint<BITS>::operator>>=(unsigned int shift)
{
base_uint<BITS> a(*this);
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
int k = shift / 32;
shift = shift % 32;
for (int i = 0; i < WIDTH; i++)
{
if (i - k - 1 >= 0 && shift != 0)
pn[i - k - 1] |= (a.pn[i] << (32 - shift));
if (i - k >= 0)
pn[i - k] |= (a.pn[i] >> shift);
}
return *this;
}
template <unsigned int BITS>
base_uint<BITS> &base_uint<BITS>::operator*=(uint32_t b32)
{
uint64_t carry = 0;
for (int i = 0; i < WIDTH; i++)
{
uint64_t n = carry + (uint64_t)b32 * pn[i];
pn[i] = n & 0xffffffff;
carry = n >> 32;
}
return *this;
}
template <unsigned int BITS>
base_uint<BITS> &base_uint<BITS>::operator*=(const base_uint &b)
{
base_uint<BITS> a = *this;
*this = 0;
for (int j = 0; j < WIDTH; j++)
{
uint64_t carry = 0;
for (int i = 0; i + j < WIDTH; i++)
{
uint64_t n = carry + pn[i + j] + (uint64_t)a.pn[j] * b.pn[i];
pn[i + j] = n & 0xffffffff;
carry = n >> 32;
}
}
return *this;
}
template <unsigned int BITS>
base_uint<BITS> &base_uint<BITS>::operator/=(const base_uint &b)
{
base_uint<BITS> div = b; // make a copy, so we can shift.
base_uint<BITS> num = *this; // make a copy, so we can subtract.
*this = 0; // the quotient.
int num_bits = num.bits();
int div_bits = div.bits();
if (div_bits == 0)
throw uint_error("Division by zero");
if (div_bits > num_bits) // the result is certainly 0.
return *this;
int shift = num_bits - div_bits;
div <<= shift; // shift so that div and num align.
while (shift >= 0)
{
if (num >= div)
{
num -= div;
pn[shift / 32] |= (1 << (shift & 31)); // set a bit of the result.
}
div >>= 1; // shift back.
shift--;
}
// num now contains the remainder of the division.
return *this;
}
template <unsigned int BITS>
int base_uint<BITS>::CompareTo(const base_uint<BITS> &b) const
{
for (int i = WIDTH - 1; i >= 0; i--)
{
if (pn[i] < b.pn[i])
return -1;
if (pn[i] > b.pn[i])
return 1;
}
return 0;
}
template <unsigned int BITS>
bool base_uint<BITS>::EqualTo(uint64_t b) const
{
for (int i = WIDTH - 1; i >= 2; i--)
{
if (pn[i])
return false;
}
if (pn[1] != (b >> 32))
return false;
if (pn[0] != (b & 0xfffffffful))
return false;
return true;
}
template <unsigned int BITS>
double base_uint<BITS>::getdouble() const
{
double ret = 0.0;
double fact = 1.0;
for (int i = 0; i < WIDTH; i++)
{
ret += fact * pn[i];
fact *= 4294967296.0;
}
return ret;
}
template <unsigned int BITS>
std::string base_uint<BITS>::GetHex() const
{
return ArithToUint256(*this).GetHex();
}
template <unsigned int BITS>
void base_uint<BITS>::SetHex(const char *psz)
{
*this = UintToArith256(uint256S(psz));
}
template <unsigned int BITS>
void base_uint<BITS>::SetHex(const std::string &str)
{
SetHex(str.c_str());
}
template <unsigned int BITS>
std::string base_uint<BITS>::ToString() const
{
return (GetHex());
}
template <unsigned int BITS>
unsigned int base_uint<BITS>::bits() const
{
for (int pos = WIDTH - 1; pos >= 0; pos--)
{
if (pn[pos])
{
for (int bits = 31; bits > 0; bits--)
{
if (pn[pos] & 1 << bits)
return 32 * pos + bits + 1;
}
return 32 * pos + 1;
}
}
return 0;
}
// Explicit instantiations for base_uint<256>
template base_uint<256>::base_uint(const std::string &);
template base_uint<256> &base_uint<256>::operator<<=(unsigned int);
template base_uint<256> &base_uint<256>::operator>>=(unsigned int);
template base_uint<256> &base_uint<256>::operator*=(uint32_t b32);
template base_uint<256> &base_uint<256>::operator*=(const base_uint<256> &b);
template base_uint<256> &base_uint<256>::operator/=(const base_uint<256> &b);
template int base_uint<256>::CompareTo(const base_uint<256> &) const;
template bool base_uint<256>::EqualTo(uint64_t) const;
template double base_uint<256>::getdouble() const;
template std::string base_uint<256>::GetHex() const;
template std::string base_uint<256>::ToString() const;
template void base_uint<256>::SetHex(const char *);
template void base_uint<256>::SetHex(const std::string &);
template unsigned int base_uint<256>::bits() const;
// This implementation directly uses shifts instead of going
// through an intermediate MPI representation.
arith_uint256 &arith_uint256::SetCompact(uint32_t nCompact, bool *pfNegative, bool *pfOverflow)
{
int nSize = nCompact >> 24;
uint32_t nWord = nCompact & 0x007fffff;
if (nSize <= 3)
{
nWord >>= 8 * (3 - nSize);
*this = nWord;
}
else
{
*this = nWord;
*this <<= 8 * (nSize - 3);
}
if (pfNegative)
*pfNegative = nWord != 0 && (nCompact & 0x00800000) != 0;
if (pfOverflow)
*pfOverflow = nWord != 0 && ((nSize > 34) || (nWord > 0xff && nSize > 33) || (nWord > 0xffff && nSize > 32));
return *this;
}
uint32_t arith_uint256::GetCompact(bool fNegative) const
{
int nSize = (bits() + 7) / 8;
uint32_t nCompact = 0;
if (nSize <= 3)
{
nCompact = GetLow64() << 8 * (3 - nSize);
}
else
{
arith_uint256 bn = *this >> 8 * (nSize - 3);
nCompact = bn.GetLow64();
}
// The 0x00800000 bit denotes the sign.
// Thus, if it is already set, divide the mantissa by 256 and increase the exponent.
if (nCompact & 0x00800000)
{
nCompact >>= 8;
nSize++;
}
assert((nCompact & ~0x007fffff) == 0);
assert(nSize < 256);
nCompact |= nSize << 24;
nCompact |= (fNegative && (nCompact & 0x007fffff) ? 0x00800000 : 0);
return nCompact;
}
uint256 ArithToUint256(const arith_uint256 &a)
{
uint256 b;
for (int x = 0; x < a.WIDTH; ++x)
WriteLE32(b.begin() + x * 4, a.pn[x]);
return b;
}
arith_uint256 UintToArith256(const uint256 &a)
{
arith_uint256 b;
for (int x = 0; x < b.WIDTH; ++x)
b.pn[x] = ReadLE32(a.begin() + x * 4);
return b;
}
<commit_msg>Avoid triggering undefined behaviour in base_uint<BITS>::bits()<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "arith_uint256.h"
#include "crypto/common.h"
#include "uint256.h"
#include "utilstrencodings.h"
#include <stdio.h>
#include <string.h>
template <unsigned int BITS>
base_uint<BITS>::base_uint(const std::string &str)
{
SetHex(str);
}
template <unsigned int BITS>
base_uint<BITS> &base_uint<BITS>::operator<<=(unsigned int shift)
{
base_uint<BITS> a(*this);
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
int k = shift / 32;
shift = shift % 32;
for (int i = 0; i < WIDTH; i++)
{
if (i + k + 1 < WIDTH && shift != 0)
pn[i + k + 1] |= (a.pn[i] >> (32 - shift));
if (i + k < WIDTH)
pn[i + k] |= (a.pn[i] << shift);
}
return *this;
}
template <unsigned int BITS>
base_uint<BITS> &base_uint<BITS>::operator>>=(unsigned int shift)
{
base_uint<BITS> a(*this);
for (int i = 0; i < WIDTH; i++)
pn[i] = 0;
int k = shift / 32;
shift = shift % 32;
for (int i = 0; i < WIDTH; i++)
{
if (i - k - 1 >= 0 && shift != 0)
pn[i - k - 1] |= (a.pn[i] << (32 - shift));
if (i - k >= 0)
pn[i - k] |= (a.pn[i] >> shift);
}
return *this;
}
template <unsigned int BITS>
base_uint<BITS> &base_uint<BITS>::operator*=(uint32_t b32)
{
uint64_t carry = 0;
for (int i = 0; i < WIDTH; i++)
{
uint64_t n = carry + (uint64_t)b32 * pn[i];
pn[i] = n & 0xffffffff;
carry = n >> 32;
}
return *this;
}
template <unsigned int BITS>
base_uint<BITS> &base_uint<BITS>::operator*=(const base_uint &b)
{
base_uint<BITS> a = *this;
*this = 0;
for (int j = 0; j < WIDTH; j++)
{
uint64_t carry = 0;
for (int i = 0; i + j < WIDTH; i++)
{
uint64_t n = carry + pn[i + j] + (uint64_t)a.pn[j] * b.pn[i];
pn[i + j] = n & 0xffffffff;
carry = n >> 32;
}
}
return *this;
}
template <unsigned int BITS>
base_uint<BITS> &base_uint<BITS>::operator/=(const base_uint &b)
{
base_uint<BITS> div = b; // make a copy, so we can shift.
base_uint<BITS> num = *this; // make a copy, so we can subtract.
*this = 0; // the quotient.
int num_bits = num.bits();
int div_bits = div.bits();
if (div_bits == 0)
throw uint_error("Division by zero");
if (div_bits > num_bits) // the result is certainly 0.
return *this;
int shift = num_bits - div_bits;
div <<= shift; // shift so that div and num align.
while (shift >= 0)
{
if (num >= div)
{
num -= div;
pn[shift / 32] |= (1 << (shift & 31)); // set a bit of the result.
}
div >>= 1; // shift back.
shift--;
}
// num now contains the remainder of the division.
return *this;
}
template <unsigned int BITS>
int base_uint<BITS>::CompareTo(const base_uint<BITS> &b) const
{
for (int i = WIDTH - 1; i >= 0; i--)
{
if (pn[i] < b.pn[i])
return -1;
if (pn[i] > b.pn[i])
return 1;
}
return 0;
}
template <unsigned int BITS>
bool base_uint<BITS>::EqualTo(uint64_t b) const
{
for (int i = WIDTH - 1; i >= 2; i--)
{
if (pn[i])
return false;
}
if (pn[1] != (b >> 32))
return false;
if (pn[0] != (b & 0xfffffffful))
return false;
return true;
}
template <unsigned int BITS>
double base_uint<BITS>::getdouble() const
{
double ret = 0.0;
double fact = 1.0;
for (int i = 0; i < WIDTH; i++)
{
ret += fact * pn[i];
fact *= 4294967296.0;
}
return ret;
}
template <unsigned int BITS>
std::string base_uint<BITS>::GetHex() const
{
return ArithToUint256(*this).GetHex();
}
template <unsigned int BITS>
void base_uint<BITS>::SetHex(const char *psz)
{
*this = UintToArith256(uint256S(psz));
}
template <unsigned int BITS>
void base_uint<BITS>::SetHex(const std::string &str)
{
SetHex(str.c_str());
}
template <unsigned int BITS>
std::string base_uint<BITS>::ToString() const
{
return (GetHex());
}
template <unsigned int BITS>
unsigned int base_uint<BITS>::bits() const
{
for (int pos = WIDTH - 1; pos >= 0; pos--)
{
if (pn[pos])
{
for (int bits = 31; bits > 0; bits--)
{
if (pn[pos] & 1U << bits)
return 32 * pos + bits + 1;
}
return 32 * pos + 1;
}
}
return 0;
}
// Explicit instantiations for base_uint<256>
template base_uint<256>::base_uint(const std::string &);
template base_uint<256> &base_uint<256>::operator<<=(unsigned int);
template base_uint<256> &base_uint<256>::operator>>=(unsigned int);
template base_uint<256> &base_uint<256>::operator*=(uint32_t b32);
template base_uint<256> &base_uint<256>::operator*=(const base_uint<256> &b);
template base_uint<256> &base_uint<256>::operator/=(const base_uint<256> &b);
template int base_uint<256>::CompareTo(const base_uint<256> &) const;
template bool base_uint<256>::EqualTo(uint64_t) const;
template double base_uint<256>::getdouble() const;
template std::string base_uint<256>::GetHex() const;
template std::string base_uint<256>::ToString() const;
template void base_uint<256>::SetHex(const char *);
template void base_uint<256>::SetHex(const std::string &);
template unsigned int base_uint<256>::bits() const;
// This implementation directly uses shifts instead of going
// through an intermediate MPI representation.
arith_uint256 &arith_uint256::SetCompact(uint32_t nCompact, bool *pfNegative, bool *pfOverflow)
{
int nSize = nCompact >> 24;
uint32_t nWord = nCompact & 0x007fffff;
if (nSize <= 3)
{
nWord >>= 8 * (3 - nSize);
*this = nWord;
}
else
{
*this = nWord;
*this <<= 8 * (nSize - 3);
}
if (pfNegative)
*pfNegative = nWord != 0 && (nCompact & 0x00800000) != 0;
if (pfOverflow)
*pfOverflow = nWord != 0 && ((nSize > 34) || (nWord > 0xff && nSize > 33) || (nWord > 0xffff && nSize > 32));
return *this;
}
uint32_t arith_uint256::GetCompact(bool fNegative) const
{
int nSize = (bits() + 7) / 8;
uint32_t nCompact = 0;
if (nSize <= 3)
{
nCompact = GetLow64() << 8 * (3 - nSize);
}
else
{
arith_uint256 bn = *this >> 8 * (nSize - 3);
nCompact = bn.GetLow64();
}
// The 0x00800000 bit denotes the sign.
// Thus, if it is already set, divide the mantissa by 256 and increase the exponent.
if (nCompact & 0x00800000)
{
nCompact >>= 8;
nSize++;
}
assert((nCompact & ~0x007fffff) == 0);
assert(nSize < 256);
nCompact |= nSize << 24;
nCompact |= (fNegative && (nCompact & 0x007fffff) ? 0x00800000 : 0);
return nCompact;
}
uint256 ArithToUint256(const arith_uint256 &a)
{
uint256 b;
for (int x = 0; x < a.WIDTH; ++x)
WriteLE32(b.begin() + x * 4, a.pn[x]);
return b;
}
arith_uint256 UintToArith256(const uint256 &a)
{
arith_uint256 b;
for (int x = 0; x < b.WIDTH; ++x)
b.pn[x] = ReadLE32(a.begin() + x * 4);
return b;
}
<|endoftext|> |
<commit_before>#include <v8.h>
#include <sys/stat.h>
#include <common.h>
v8::Handle<v8::Value> _file(const v8::Arguments& args) {
v8::HandleScope handle_scope;
if (args.Length() < 1 || args.This()->InternalFieldCount() == 0) {
return v8::ThrowException(v8::String::New("Invalid call format. Use 'new File(name)'"));
}
args.This()->SetInternalField(0, args[0]);
args.This()->SetInternalField(1, v8::Boolean::New(false));
return args.This();
}
v8::Handle<v8::Value> _open(const v8::Arguments& args) {
v8::HandleScope handle_scope;
if (args.Length() < 1) {
return v8::ThrowException(v8::String::New("Bad argument count. Use 'file.open(mode)'"));
}
v8::String::Utf8Value mode(args[0]);
v8::String::Utf8Value name(args.This()->GetInternalField(0));
v8::Handle<v8::Value> file = args.This()->GetInternalField(1);
if (!file->IsFalse()) {
return v8::ThrowException(v8::String::New("File already opened"));
}
FILE * f;
f = fopen(*name, *mode);
if (!f) {
return v8::ThrowException(v8::String::New("Cannot open file"));
}
struct stat st;
if (stat(*name, &st) == 0) {
args.This()->SetInternalField(2, v8::Integer::New(st.st_size));
}
args.This()->SetInternalField(1, v8::External::New((void *)f));
args.This()->SetInternalField(3, v8::Integer::New(0));
return args.This();
}
v8::Handle<v8::Value> _close(const v8::Arguments& args) {
v8::HandleScope handle_scope;
v8::Handle<v8::Value> file = args.This()->GetInternalField(1);
if (file->IsFalse()) {
return v8::ThrowException(v8::String::New("Cannot close non-opened file"));
}
FILE * f = reinterpret_cast<FILE *>(v8::Handle<v8::External>::Cast(file)->Value());
fclose(f);
args.This()->SetInternalField(1, v8::Boolean::New(false));
return args.This();
}
v8::Handle<v8::Value> _read(const v8::Arguments& args) {
v8::HandleScope handle_scope;
v8::Handle<v8::Value> file = args.This()->GetInternalField(1);
if (file->IsFalse()) {
return v8::ThrowException(v8::String::New("File must be opened before reading"));
}
long size = args.This()->GetInternalField(2)->IntegerValue();
long pos = args.This()->GetInternalField(3)->IntegerValue();
FILE * f = reinterpret_cast<FILE *>(v8::Handle<v8::External>::Cast(file)->Value());
long avail = size-pos;
if (!avail) { return v8::Boolean::New(false); }
if (args.Length() && args[0]->IsNumber()) {
int len = args[0]->IntegerValue();
if (len < avail) { avail = len; }
}
char buf[avail];
fread(buf, sizeof(char), avail, f);
pos += avail;
args.This()->SetInternalField(3, v8::Integer::New(pos));
if (args.Length() > 1 && args[1]->IsTrue()) {
return char2array(buf, avail);
} else {
return char2string(buf, avail);
}
}
v8::Handle<v8::Value> _rewind(const v8::Arguments& args) {
v8::HandleScope handle_scope;
v8::Handle<v8::Value> file = args.This()->GetInternalField(1);
if (file->IsFalse()) {
return v8::ThrowException(v8::String::New("File must be opened before rewinding"));
}
FILE * f = reinterpret_cast<FILE *>(v8::Handle<v8::External>::Cast(file)->Value());
rewind(f);
args.This()->SetInternalField(3, v8::Integer::New(0));
return args.This();
}
v8::Handle<v8::Value> _write(const v8::Arguments& args) {
v8::HandleScope handle_scope;
v8::Handle<v8::Value> file = args.This()->GetInternalField(1);
if (file->IsFalse()) {
return v8::ThrowException(v8::String::New("File must be opened before writing"));
}
if (args.Length() < 1) {
return v8::ThrowException(v8::String::New("Bad argument count. Use 'file.write(data)'"));
}
FILE * f = reinterpret_cast<FILE *>(v8::Handle<v8::External>::Cast(file)->Value());
if (args[0]->IsArray()) {
v8::Handle<v8::Array> arr = v8::Handle<v8::Array>::Cast(args[0]);
int len = arr->Length();
int max = 4096;
int current = 0;
char buf[max];
for (int i=0;i<len;i++) {
v8::Handle<v8::Integer> a = v8::Integer::New(arr->Get(v8::Integer::New(i))->IntegerValue());
buf[current++] = (char) a->Int32Value();
if (current == max) {
fwrite(buf, sizeof(char), current, f);
current = 0;
}
}
if (current) { fwrite(buf, sizeof(char), current, f); }
} else {
v8::String::Utf8Value data(args[0]);
fwrite(*data, sizeof(char), args[0]->ToString()->Utf8Length(), f);
}
return args.This();
}
v8::Handle<v8::Value> _remove(const v8::Arguments& args) {
v8::HandleScope handle_scope;
v8::String::Utf8Value name(args.This()->GetInternalField(0));
v8::Handle<v8::Value> file = args.This()->GetInternalField(1);
if (!file->IsFalse()) {
return v8::ThrowException(v8::String::New("File must be closed before deleting"));
}
if (!remove(*name)) {
return v8::ThrowException(v8::String::New("Cannot remove file"));
}
return args.This();
}
v8::Handle<v8::Value> _getsize(const v8::Arguments& args) {
v8::HandleScope handle_scope;
v8::String::Utf8Value name(args.This()->GetInternalField(0));
struct stat st;
if (stat(*name, &st) == 0) {
return v8::Integer::New(st.st_size);
} else {
return v8::Boolean::New(false);
}
}
v8::Handle<v8::Value> _tostring(const v8::Arguments& args) {
v8::HandleScope handle_scope;
return args.This()->GetInternalField(0);
}
void SetupIo(v8::Handle<v8::Object> target) {
v8::HandleScope handle_scope;
v8::Handle<v8::FunctionTemplate> ft = v8::FunctionTemplate::New(_file);
ft->SetClassName(v8::String::New("File"));
v8::Handle<v8::ObjectTemplate> ot = ft->InstanceTemplate();
ot->SetInternalFieldCount(4); /* filename, handle, size, position */
v8::Handle<v8::ObjectTemplate> pt = ft->PrototypeTemplate();
pt->Set("open", v8::FunctionTemplate::New(_open));
pt->Set("read", v8::FunctionTemplate::New(_read));
pt->Set("rewind", v8::FunctionTemplate::New(_rewind));
pt->Set("close", v8::FunctionTemplate::New(_close));
pt->Set("write", v8::FunctionTemplate::New(_write));
pt->Set("remove", v8::FunctionTemplate::New(_remove));
pt->Set("getSize", v8::FunctionTemplate::New(_getsize));
pt->Set("toString", v8::FunctionTemplate::New(_tostring));
target->Set(v8::String::New("File"), ft->GetFunction());
}
<commit_msg>Basic directory support<commit_after>#include <v8.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <common.h>
#include <dirent.h>
#include <string.h>
v8::Handle<v8::Value> _directory(const v8::Arguments& args) {
v8::HandleScope handle_scope;
if (args.Length() < 1 || args.This()->InternalFieldCount() == 0) {
return v8::ThrowException(v8::String::New("Invalid call format. Use 'new Directory(name)'"));
}
args.This()->SetInternalField(0, args[0]);
return args.This();
}
v8::Handle<v8::Value> _create(const v8::Arguments& args) {
v8::HandleScope handle_scope;
v8::String::Utf8Value name(args.This()->GetInternalField(0));
int mode;
if (args.Length() == 0) {
mode = 0777;
} else {
mode = args[0]->Int32Value();
}
int result = mkdir(*name, mode);
if (result != 0) {
return v8::ThrowException(v8::String::New("Cannot create directory'"));
}
return args.This();
}
v8::Handle<v8::Value> _listfiles(const v8::Arguments& args) {
v8::HandleScope handle_scope;
v8::String::Utf8Value name(args.This()->GetInternalField(0));
DIR * dp;
struct dirent * ep;
v8::Handle<v8::Array> result = v8::Array::New();
dp = opendir(*name);
if (dp == NULL) { return v8::ThrowException(v8::String::New("Directory cannot be opened")); }
int cnt = 0;
while ((ep = readdir(dp))) {
if (ep->d_type == DT_REG) {
result->Set(v8::Integer::New(cnt++), v8::String::New(ep->d_name));
}
}
closedir(dp);
return result;
}
v8::Handle<v8::Value> _listdirectories(const v8::Arguments& args) {
v8::HandleScope handle_scope;
v8::String::Utf8Value name(args.This()->GetInternalField(0));
DIR * dp;
struct dirent * ep;
v8::Handle<v8::Array> result = v8::Array::New();
dp = opendir(*name);
if (dp == NULL) { return v8::ThrowException(v8::String::New("Directory cannot be opened")); }
int cnt = 0;
while ((ep = readdir(dp))) {
if (ep->d_type == DT_DIR) {
if (strcmp(ep->d_name, ".") != 0 && strcmp(ep->d_name, "..") != 0) {
result->Set(v8::Integer::New(cnt++), v8::String::New(ep->d_name));
}
}
}
closedir(dp);
return result;
}
v8::Handle<v8::Value> _file(const v8::Arguments& args) {
v8::HandleScope handle_scope;
if (args.Length() < 1 || args.This()->InternalFieldCount() == 0) {
return v8::ThrowException(v8::String::New("Invalid call format. Use 'new File(name)'"));
}
args.This()->SetInternalField(0, args[0]);
args.This()->SetInternalField(1, v8::Boolean::New(false));
return args.This();
}
v8::Handle<v8::Value> _open(const v8::Arguments& args) {
v8::HandleScope handle_scope;
if (args.Length() < 1) {
return v8::ThrowException(v8::String::New("Bad argument count. Use 'file.open(mode)'"));
}
v8::String::Utf8Value mode(args[0]);
v8::String::Utf8Value name(args.This()->GetInternalField(0));
v8::Handle<v8::Value> file = args.This()->GetInternalField(1);
if (!file->IsFalse()) {
return v8::ThrowException(v8::String::New("File already opened"));
}
FILE * f;
f = fopen(*name, *mode);
if (!f) {
return v8::ThrowException(v8::String::New("Cannot open file"));
}
struct stat st;
if (stat(*name, &st) == 0) {
args.This()->SetInternalField(2, v8::Integer::New(st.st_size));
}
args.This()->SetInternalField(1, v8::External::New((void *)f));
args.This()->SetInternalField(3, v8::Integer::New(0));
return args.This();
}
v8::Handle<v8::Value> _close(const v8::Arguments& args) {
v8::HandleScope handle_scope;
v8::Handle<v8::Value> file = args.This()->GetInternalField(1);
if (file->IsFalse()) {
return v8::ThrowException(v8::String::New("Cannot close non-opened file"));
}
FILE * f = reinterpret_cast<FILE *>(v8::Handle<v8::External>::Cast(file)->Value());
fclose(f);
args.This()->SetInternalField(1, v8::Boolean::New(false));
return args.This();
}
v8::Handle<v8::Value> _read(const v8::Arguments& args) {
v8::HandleScope handle_scope;
v8::Handle<v8::Value> file = args.This()->GetInternalField(1);
if (file->IsFalse()) {
return v8::ThrowException(v8::String::New("File must be opened before reading"));
}
long size = args.This()->GetInternalField(2)->IntegerValue();
long pos = args.This()->GetInternalField(3)->IntegerValue();
FILE * f = reinterpret_cast<FILE *>(v8::Handle<v8::External>::Cast(file)->Value());
long avail = size-pos;
if (!avail) { return v8::Boolean::New(false); }
if (args.Length() && args[0]->IsNumber()) {
int len = args[0]->IntegerValue();
if (len < avail) { avail = len; }
}
char buf[avail];
fread(buf, sizeof(char), avail, f);
pos += avail;
args.This()->SetInternalField(3, v8::Integer::New(pos));
if (args.Length() > 1 && args[1]->IsTrue()) {
return char2array(buf, avail);
} else {
return char2string(buf, avail);
}
}
v8::Handle<v8::Value> _rewind(const v8::Arguments& args) {
v8::HandleScope handle_scope;
v8::Handle<v8::Value> file = args.This()->GetInternalField(1);
if (file->IsFalse()) {
return v8::ThrowException(v8::String::New("File must be opened before rewinding"));
}
FILE * f = reinterpret_cast<FILE *>(v8::Handle<v8::External>::Cast(file)->Value());
rewind(f);
args.This()->SetInternalField(3, v8::Integer::New(0));
return args.This();
}
v8::Handle<v8::Value> _write(const v8::Arguments& args) {
v8::HandleScope handle_scope;
v8::Handle<v8::Value> file = args.This()->GetInternalField(1);
if (file->IsFalse()) {
return v8::ThrowException(v8::String::New("File must be opened before writing"));
}
if (args.Length() < 1) {
return v8::ThrowException(v8::String::New("Bad argument count. Use 'file.write(data)'"));
}
FILE * f = reinterpret_cast<FILE *>(v8::Handle<v8::External>::Cast(file)->Value());
if (args[0]->IsArray()) {
v8::Handle<v8::Array> arr = v8::Handle<v8::Array>::Cast(args[0]);
int len = arr->Length();
int max = 4096;
int current = 0;
char buf[max];
for (int i=0;i<len;i++) {
v8::Handle<v8::Integer> a = v8::Integer::New(arr->Get(v8::Integer::New(i))->IntegerValue());
buf[current++] = (char) a->Int32Value();
if (current == max) {
fwrite(buf, sizeof(char), current, f);
current = 0;
}
}
if (current) { fwrite(buf, sizeof(char), current, f); }
} else {
v8::String::Utf8Value data(args[0]);
fwrite(*data, sizeof(char), args[0]->ToString()->Utf8Length(), f);
}
return args.This();
}
v8::Handle<v8::Value> _remove(const v8::Arguments& args) {
v8::HandleScope handle_scope;
v8::String::Utf8Value name(args.This()->GetInternalField(0));
v8::Handle<v8::Value> file = args.This()->GetInternalField(1);
if (!file->IsFalse()) {
return v8::ThrowException(v8::String::New("File must be closed before deleting"));
}
if (!remove(*name)) {
return v8::ThrowException(v8::String::New("Cannot remove file"));
}
return args.This();
}
v8::Handle<v8::Value> _getsize(const v8::Arguments& args) {
v8::HandleScope handle_scope;
v8::String::Utf8Value name(args.This()->GetInternalField(0));
struct stat st;
if (stat(*name, &st) == 0) {
return v8::Integer::New(st.st_size);
} else {
return v8::Boolean::New(false);
}
}
v8::Handle<v8::Value> _tostring(const v8::Arguments& args) {
v8::HandleScope handle_scope;
return args.This()->GetInternalField(0);
}
void SetupIo(v8::Handle<v8::Object> target) {
v8::HandleScope handle_scope;
v8::Handle<v8::FunctionTemplate> ft = v8::FunctionTemplate::New(_file);
ft->SetClassName(v8::String::New("File"));
v8::Handle<v8::ObjectTemplate> ot = ft->InstanceTemplate();
ot->SetInternalFieldCount(4); /* filename, handle, size, position */
v8::Handle<v8::ObjectTemplate> pt = ft->PrototypeTemplate();
pt->Set("open", v8::FunctionTemplate::New(_open));
pt->Set("read", v8::FunctionTemplate::New(_read));
pt->Set("rewind", v8::FunctionTemplate::New(_rewind));
pt->Set("close", v8::FunctionTemplate::New(_close));
pt->Set("write", v8::FunctionTemplate::New(_write));
pt->Set("remove", v8::FunctionTemplate::New(_remove));
pt->Set("getSize", v8::FunctionTemplate::New(_getsize));
pt->Set("toString", v8::FunctionTemplate::New(_tostring));
target->Set(v8::String::New("File"), ft->GetFunction());
ft = v8::FunctionTemplate::New(_directory);
ft->SetClassName(v8::String::New("Directory"));
ot = ft->InstanceTemplate();
ot->SetInternalFieldCount(1); /* dirname */
pt = ft->PrototypeTemplate();
pt->Set("create", v8::FunctionTemplate::New(_create));
pt->Set("listFiles", v8::FunctionTemplate::New(_listfiles));
pt->Set("listDirectories", v8::FunctionTemplate::New(_listdirectories));
pt->Set("toString", v8::FunctionTemplate::New(_tostring));
target->Set(v8::String::New("Directory"), ft->GetFunction());
}
<|endoftext|> |
<commit_before>/*
* Copyright 2015 WebAssembly Community Group participants
*
* 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.
*/
//
// asm2wasm console tool
//
#include "support/colors.h"
#include "support/command-line.h"
#include "support/file.h"
#include "wasm-printing.h"
#include "asm2wasm.h"
using namespace cashew;
using namespace wasm;
int main(int argc, const char *argv[]) {
Options options("asm2wasm", "Translate asm.js files to .wast files");
options
.add("--output", "-o", "Output file (stdout if not specified)",
Options::Arguments::One,
[](Options *o, const std::string &argument) {
o->extra["output"] = argument;
Colors::disable();
})
.add("--mapped-globals", "-m", "Mapped globals", Options::Arguments::One,
[](Options *o, const std::string &argument) {
o->extra["mapped globals"] = argument;
})
.add_positional("INFILE", Options::Arguments::One,
[](Options *o, const std::string &argument) {
o->extra["infile"] = argument;
});
options.parse(argc, argv);
const auto &mg_it = options.extra.find("mapped globals");
const char *mappedGlobals =
mg_it == options.extra.end() ? nullptr : mg_it->second.c_str();
Asm2WasmPreProcessor pre;
auto input(
read_file<std::vector<char>>(options.extra["infile"], options.debug));
char *start = pre.process(input.data());
if (options.debug) std::cerr << "parsing..." << std::endl;
cashew::Parser<Ref, DotZeroValueBuilder> builder;
Ref asmjs = builder.parseToplevel(start);
if (options.debug) {
std::cerr << "parsed:" << std::endl;
asmjs->stringify(std::cerr, true);
std::cerr << std::endl;
}
if (options.debug) std::cerr << "wasming..." << std::endl;
AllocatingModule wasm;
wasm.memory.initial = wasm.memory.max =
16 * 1024 * 1024; // we would normally receive this from the compiler
Asm2WasmBuilder asm2wasm(wasm, pre.memoryGrowth, options.debug);
asm2wasm.processAsm(asmjs);
if (options.debug) std::cerr << "optimizing..." << std::endl;
asm2wasm.optimize();
if (options.debug) std::cerr << "printing..." << std::endl;
Output output(options.extra["output"], options.debug);
printWasm(&wasm, output.getStream());
if (mappedGlobals) {
if (options.debug)
std::cerr << "serializing mapped globals..." << std::endl;
asm2wasm.serializeMappedGlobals(mappedGlobals);
}
if (options.debug) std::cerr << "done." << std::endl;
}
<commit_msg>allow setting total memory in asm2wasm<commit_after>/*
* Copyright 2015 WebAssembly Community Group participants
*
* 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.
*/
//
// asm2wasm console tool
//
#include "support/colors.h"
#include "support/command-line.h"
#include "support/file.h"
#include "wasm-printing.h"
#include "asm2wasm.h"
using namespace cashew;
using namespace wasm;
int main(int argc, const char *argv[]) {
Options options("asm2wasm", "Translate asm.js files to .wast files");
options
.add("--output", "-o", "Output file (stdout if not specified)",
Options::Arguments::One,
[](Options *o, const std::string &argument) {
o->extra["output"] = argument;
Colors::disable();
})
.add("--mapped-globals", "-m", "Mapped globals", Options::Arguments::One,
[](Options *o, const std::string &argument) {
o->extra["mapped globals"] = argument;
})
.add("--total-memory", "-m", "Total memory size", Options::Arguments::One,
[](Options *o, const std::string &argument) {
o->extra["total memory"] = argument;
})
.add_positional("INFILE", Options::Arguments::One,
[](Options *o, const std::string &argument) {
o->extra["infile"] = argument;
});
options.parse(argc, argv);
const auto &mg_it = options.extra.find("mapped globals");
const char *mappedGlobals =
mg_it == options.extra.end() ? nullptr : mg_it->second.c_str();
const auto &tm_it = options.extra.find("total memory");
size_t totalMemory =
tm_it == options.extra.end() ? 16 * 1024 * 1024 : atoi(tm_it->second.c_str());
Asm2WasmPreProcessor pre;
auto input(
read_file<std::vector<char>>(options.extra["infile"], options.debug));
char *start = pre.process(input.data());
if (options.debug) std::cerr << "parsing..." << std::endl;
cashew::Parser<Ref, DotZeroValueBuilder> builder;
Ref asmjs = builder.parseToplevel(start);
if (options.debug) {
std::cerr << "parsed:" << std::endl;
asmjs->stringify(std::cerr, true);
std::cerr << std::endl;
}
if (options.debug) std::cerr << "wasming..." << std::endl;
AllocatingModule wasm;
wasm.memory.initial = wasm.memory.max = totalMemory;
Asm2WasmBuilder asm2wasm(wasm, pre.memoryGrowth, options.debug);
asm2wasm.processAsm(asmjs);
if (options.debug) std::cerr << "optimizing..." << std::endl;
asm2wasm.optimize();
if (options.debug) std::cerr << "printing..." << std::endl;
Output output(options.extra["output"], options.debug);
printWasm(&wasm, output.getStream());
if (mappedGlobals) {
if (options.debug)
std::cerr << "serializing mapped globals..." << std::endl;
asm2wasm.serializeMappedGlobals(mappedGlobals);
}
if (options.debug) std::cerr << "done." << std::endl;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2016 The Zcash developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "asyncrpcqueue.h"
static std::atomic<size_t> workerCounter(0);
/**
* Static method to return the shared/default queue.
*/
shared_ptr<AsyncRPCQueue> AsyncRPCQueue::sharedInstance() {
// Thread-safe in C+11 and gcc 4.3
static shared_ptr<AsyncRPCQueue> q = std::make_shared<AsyncRPCQueue>();
return q;
}
AsyncRPCQueue::AsyncRPCQueue() : closed_(false), finish_(false) {
}
AsyncRPCQueue::~AsyncRPCQueue() {
closeAndWait(); // join on all worker threads
}
/**
* A worker will execute this method on a new thread
*/
void AsyncRPCQueue::run(size_t workerId) {
while (true) {
AsyncRPCOperationId key;
std::shared_ptr<AsyncRPCOperation> operation;
{
std::unique_lock< std::mutex > guard(lock_);
while (operation_id_queue_.empty() && !isClosed() && !isFinishing()) {
this->condition_.wait(guard);
}
// Exit if the queue is empty and we are finishing up
if (isFinishing() && operation_id_queue_.empty()) {
break;
}
// Exit if the queue is closing.
if (isClosed()) {
while (!operation_id_queue_.empty()) {
operation_id_queue_.pop();
}
break;
}
// Get operation id
key = operation_id_queue_.front();
operation_id_queue_.pop();
// Search operation map
AsyncRPCOperationMap::const_iterator iter = operation_map_.find(key);
if (iter != operation_map_.end()) {
operation = iter->second;
}
}
if (!operation) {
// cannot find operation in map, may have been removed
} else if (operation->isCancelled()) {
// skip cancelled operation
} else {
operation->main();
}
}
}
/**
* Add shared_ptr to operation.
*
* To retain polymorphic behaviour, i.e. main() method of derived classes is invoked,
* caller should create the shared_ptr like this:
*
* std::shared_ptr<AsyncRPCOperation> ptr(new MyCustomAsyncRPCOperation(params));
*
* Don't use std::make_shared<AsyncRPCOperation>().
*/
void AsyncRPCQueue::addOperation(const std::shared_ptr<AsyncRPCOperation> &ptrOperation) {
std::lock_guard<std::mutex> guard(lock_);
// Don't add if queue is closed or finishing
if (isClosed() || isFinishing()) {
return;
}
AsyncRPCOperationId id = ptrOperation->getId();
operation_map_.emplace(id, ptrOperation);
operation_id_queue_.push(id);
this->condition_.notify_one();
}
/**
* Return the operation for a given operation id.
*/
std::shared_ptr<AsyncRPCOperation> AsyncRPCQueue::getOperationForId(AsyncRPCOperationId id) const {
std::shared_ptr<AsyncRPCOperation> ptr;
std::lock_guard<std::mutex> guard(lock_);
AsyncRPCOperationMap::const_iterator iter = operation_map_.find(id);
if (iter != operation_map_.end()) {
ptr = iter->second;
}
return ptr;
}
/**
* Return the operation for a given operation id and then remove the operation from internal storage.
*/
std::shared_ptr<AsyncRPCOperation> AsyncRPCQueue::popOperationForId(AsyncRPCOperationId id) {
std::shared_ptr<AsyncRPCOperation> ptr = getOperationForId(id);
if (ptr) {
std::lock_guard<std::mutex> guard(lock_);
// Note: if the id still exists in the operationIdQueue, when it gets processed by a worker
// there will no operation in the map to execute, so nothing will happen.
operation_map_.erase(id);
}
return ptr;
}
/**
* Return true if the queue is closed to new operations.
*/
bool AsyncRPCQueue::isClosed() const {
return closed_.load();
}
/**
* Close the queue and cancel all existing operations
*/
void AsyncRPCQueue::close() {
closed_.store(true);
cancelAllOperations();
}
/**
* Return true if the queue is finishing up
*/
bool AsyncRPCQueue::isFinishing() const {
return finish_.load();
}
/**
* Close the queue but finish existing operations. Do not accept new operations.
*/
void AsyncRPCQueue::finish() {
finish_.store(true);
}
/**
* Call cancel() on all operations
*/
void AsyncRPCQueue::cancelAllOperations() {
std::lock_guard<std::mutex> guard(lock_);
for (auto key : operation_map_) {
key.second->cancel();
}
this->condition_.notify_all();
}
/**
* Return the number of operations in the queue
*/
size_t AsyncRPCQueue::getOperationCount() const {
std::lock_guard<std::mutex> guard(lock_);
return operation_id_queue_.size();
}
/**
* Spawn a worker thread
*/
void AsyncRPCQueue::addWorker() {
std::lock_guard<std::mutex> guard(lock_);
workers_.emplace_back( std::thread(&AsyncRPCQueue::run, this, ++workerCounter) );
}
/**
* Return the number of worker threads spawned by the queue
*/
size_t AsyncRPCQueue::getNumberOfWorkers() const {
std::lock_guard<std::mutex> guard(lock_);
return workers_.size();
}
/**
* Return a list of all known operation ids found in internal storage.
*/
std::vector<AsyncRPCOperationId> AsyncRPCQueue::getAllOperationIds() const {
std::lock_guard<std::mutex> guard(lock_);
std::vector<AsyncRPCOperationId> v;
for(auto & entry: operation_map_) {
v.push_back(entry.first);
}
return v;
}
/**
* Calling thread will close and wait for worker threads to join.
*/
void AsyncRPCQueue::closeAndWait() {
close();
wait_for_worker_threads();
}
/**
* Block current thread until all workers have finished their tasks.
*/
void AsyncRPCQueue::finishAndWait() {
finish();
wait_for_worker_threads();
}
/**
* Block current thread until all operations are finished or the queue has closed.
*/
void AsyncRPCQueue::wait_for_worker_threads() {
// Notify any workers who are waiting, so they see the updated queue state
{
std::lock_guard<std::mutex> guard(lock_);
this->condition_.notify_all();
}
for (std::thread & t : this->workers_) {
if (t.joinable()) {
t.join();
}
}
}
<commit_msg>Fix formatting<commit_after>// Copyright (c) 2016 The Zcash developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "asyncrpcqueue.h"
static std::atomic<size_t> workerCounter(0);
/**
* Static method to return the shared/default queue.
*/
shared_ptr<AsyncRPCQueue> AsyncRPCQueue::sharedInstance() {
// Thread-safe in C+11 and gcc 4.3
static shared_ptr<AsyncRPCQueue> q = std::make_shared<AsyncRPCQueue>();
return q;
}
AsyncRPCQueue::AsyncRPCQueue() : closed_(false), finish_(false) {
}
AsyncRPCQueue::~AsyncRPCQueue() {
closeAndWait(); // join on all worker threads
}
/**
* A worker will execute this method on a new thread
*/
void AsyncRPCQueue::run(size_t workerId) {
while (true) {
AsyncRPCOperationId key;
std::shared_ptr<AsyncRPCOperation> operation;
{
std::unique_lock<std::mutex> guard(lock_);
while (operation_id_queue_.empty() && !isClosed() && !isFinishing()) {
this->condition_.wait(guard);
}
// Exit if the queue is empty and we are finishing up
if (isFinishing() && operation_id_queue_.empty()) {
break;
}
// Exit if the queue is closing.
if (isClosed()) {
while (!operation_id_queue_.empty()) {
operation_id_queue_.pop();
}
break;
}
// Get operation id
key = operation_id_queue_.front();
operation_id_queue_.pop();
// Search operation map
AsyncRPCOperationMap::const_iterator iter = operation_map_.find(key);
if (iter != operation_map_.end()) {
operation = iter->second;
}
}
if (!operation) {
// cannot find operation in map, may have been removed
} else if (operation->isCancelled()) {
// skip cancelled operation
} else {
operation->main();
}
}
}
/**
* Add shared_ptr to operation.
*
* To retain polymorphic behaviour, i.e. main() method of derived classes is invoked,
* caller should create the shared_ptr like this:
*
* std::shared_ptr<AsyncRPCOperation> ptr(new MyCustomAsyncRPCOperation(params));
*
* Don't use std::make_shared<AsyncRPCOperation>().
*/
void AsyncRPCQueue::addOperation(const std::shared_ptr<AsyncRPCOperation> &ptrOperation) {
std::lock_guard<std::mutex> guard(lock_);
// Don't add if queue is closed or finishing
if (isClosed() || isFinishing()) {
return;
}
AsyncRPCOperationId id = ptrOperation->getId();
operation_map_.emplace(id, ptrOperation);
operation_id_queue_.push(id);
this->condition_.notify_one();
}
/**
* Return the operation for a given operation id.
*/
std::shared_ptr<AsyncRPCOperation> AsyncRPCQueue::getOperationForId(AsyncRPCOperationId id) const {
std::shared_ptr<AsyncRPCOperation> ptr;
std::lock_guard<std::mutex> guard(lock_);
AsyncRPCOperationMap::const_iterator iter = operation_map_.find(id);
if (iter != operation_map_.end()) {
ptr = iter->second;
}
return ptr;
}
/**
* Return the operation for a given operation id and then remove the operation from internal storage.
*/
std::shared_ptr<AsyncRPCOperation> AsyncRPCQueue::popOperationForId(AsyncRPCOperationId id) {
std::shared_ptr<AsyncRPCOperation> ptr = getOperationForId(id);
if (ptr) {
std::lock_guard<std::mutex> guard(lock_);
// Note: if the id still exists in the operationIdQueue, when it gets processed by a worker
// there will no operation in the map to execute, so nothing will happen.
operation_map_.erase(id);
}
return ptr;
}
/**
* Return true if the queue is closed to new operations.
*/
bool AsyncRPCQueue::isClosed() const {
return closed_.load();
}
/**
* Close the queue and cancel all existing operations
*/
void AsyncRPCQueue::close() {
closed_.store(true);
cancelAllOperations();
}
/**
* Return true if the queue is finishing up
*/
bool AsyncRPCQueue::isFinishing() const {
return finish_.load();
}
/**
* Close the queue but finish existing operations. Do not accept new operations.
*/
void AsyncRPCQueue::finish() {
finish_.store(true);
}
/**
* Call cancel() on all operations
*/
void AsyncRPCQueue::cancelAllOperations() {
std::lock_guard<std::mutex> guard(lock_);
for (auto key : operation_map_) {
key.second->cancel();
}
this->condition_.notify_all();
}
/**
* Return the number of operations in the queue
*/
size_t AsyncRPCQueue::getOperationCount() const {
std::lock_guard<std::mutex> guard(lock_);
return operation_id_queue_.size();
}
/**
* Spawn a worker thread
*/
void AsyncRPCQueue::addWorker() {
std::lock_guard<std::mutex> guard(lock_);
workers_.emplace_back( std::thread(&AsyncRPCQueue::run, this, ++workerCounter) );
}
/**
* Return the number of worker threads spawned by the queue
*/
size_t AsyncRPCQueue::getNumberOfWorkers() const {
std::lock_guard<std::mutex> guard(lock_);
return workers_.size();
}
/**
* Return a list of all known operation ids found in internal storage.
*/
std::vector<AsyncRPCOperationId> AsyncRPCQueue::getAllOperationIds() const {
std::lock_guard<std::mutex> guard(lock_);
std::vector<AsyncRPCOperationId> v;
for(auto & entry: operation_map_) {
v.push_back(entry.first);
}
return v;
}
/**
* Calling thread will close and wait for worker threads to join.
*/
void AsyncRPCQueue::closeAndWait() {
close();
wait_for_worker_threads();
}
/**
* Block current thread until all workers have finished their tasks.
*/
void AsyncRPCQueue::finishAndWait() {
finish();
wait_for_worker_threads();
}
/**
* Block current thread until all operations are finished or the queue has closed.
*/
void AsyncRPCQueue::wait_for_worker_threads() {
// Notify any workers who are waiting, so they see the updated queue state
{
std::lock_guard<std::mutex> guard(lock_);
this->condition_.notify_all();
}
for (std::thread & t : this->workers_) {
if (t.joinable()) {
t.join();
}
}
}
<|endoftext|> |
<commit_before>
#include "SMESHGUI_Selection.h"
#include "SMESHGUI_Utils.h"
#include "SMESHGUI_VTKUtils.h"
#include "SMESHGUI_MeshUtils.h"
#include "SMESHGUI_GEOMGenUtils.h"
#include "SMESH_Type.h"
#include "SMESH_Actor.h"
#include "SalomeApp_SelectionMgr.h"
#include "SalomeApp_Study.h"
#include "SalomeApp_VTKSelector.h"
#include "SUIT_Session.h"
#include "SVTK_RenderWindowInteractor.h"
#include "SVTK_ViewWindow.h"
#include CORBA_SERVER_HEADER(SMESH_Mesh)
#include CORBA_SERVER_HEADER(SMESH_Group)
//=======================================================================
//function : SMESHGUI_Selection
//purpose :
//=======================================================================
SMESHGUI_Selection::SMESHGUI_Selection()
: SalomeApp_Selection()
{
}
//=======================================================================
//function : ~SMESHGUI_Selection
//purpose :
//=======================================================================
SMESHGUI_Selection::~SMESHGUI_Selection()
{
}
//=======================================================================
//function : init
//purpose :
//=======================================================================
void SMESHGUI_Selection::init( const QString& client, SalomeApp_SelectionMgr* mgr )
{
SalomeApp_Selection::init( client, mgr );
if( mgr && study() )
{
_PTR(Study) aStudy = study()->studyDS();
SUIT_DataOwnerPtrList sel;
mgr->selected( sel, client );
myDataOwners = sel;
SUIT_DataOwnerPtrList::const_iterator anIt = sel.begin(),
aLast = sel.end();
for( ; anIt!=aLast; anIt++ )
{
SUIT_DataOwner* owner = ( SUIT_DataOwner* )( (*anIt ).get() );
SalomeApp_DataOwner* sowner = dynamic_cast<SalomeApp_DataOwner*>( owner );
if( sowner )
myTypes.append( typeName( type( sowner, aStudy ) ) );
else
myTypes.append( "Unknown" );
}
}
}
//=======================================================================
//function : param
//purpose :
//=======================================================================
QtxValue SMESHGUI_Selection::param( const int ind, const QString& p ) const
{
QtxValue val;
if ( p=="client" ) val = QtxValue( globalParam( p ) );
else if ( p=="type" ) val = QtxValue( myTypes[ind] );
else if ( p=="elemTypes" ) val = QtxValue( elemTypes( ind ) );
else if ( p=="numberOfNodes" ) val = QtxValue( numberOfNodes( ind ) );
else if ( p=="labeledTypes" ) val = QtxValue( labeledTypes( ind ) );
else if ( p=="shrinkMode" ) val = QtxValue( shrinkMode( ind ) );
else if ( p=="entityMode" ) val = QtxValue( entityMode( ind ) );
else if ( p=="controlMode" ) val = QtxValue( controlMode( ind ) );
else if ( p=="displayMode" ) val = QtxValue( displayMode( ind ) );
else if ( p=="isComputable" ) val = QtxValue( isComputable( ind ) );
else if ( p=="hasReference" ) val = QtxValue( hasReference( ind ) );
else if ( p=="isVisible" ) val = QtxValue( isVisible( ind ) );
printf( "--> param() : [%s] = %s (%s)\n", p.latin1(), val.toString().latin1(), val.typeName() );
if ( val.type() == QVariant::List )
cout << "size: " << val.toList().count() << endl;
return val;
}
//=======================================================================
//function : getVtkOwner
//purpose :
//=======================================================================
SMESH_Actor* SMESHGUI_Selection::getActor( int ind ) const
{
if ( ind >= 0 && ind < myDataOwners.count() ) {
const SalomeApp_SVTKDataOwner* owner =
dynamic_cast<const SalomeApp_SVTKDataOwner*> ( myDataOwners[ ind ].get() );
if ( owner )
return dynamic_cast<SMESH_Actor*>( owner->GetActor() );
}
return 0;
}
//=======================================================================
//function : elemTypes
//purpose : may return {'Edge' 'Face' 'Volume'} at most
//=======================================================================
QValueList<QVariant> SMESHGUI_Selection::elemTypes( int ind ) const
{
QValueList<QVariant> types;
SMESH_Actor* actor = getActor( ind );
if ( actor ) {
TVisualObjPtr object = actor->GetObject();
if ( object ) {
if ( object->GetNbEntities( SMDSAbs_Edge )) types.append( "Edge" );
if ( object->GetNbEntities( SMDSAbs_Face )) types.append( "Face" );
if ( object->GetNbEntities( SMDSAbs_Volume )) types.append( "Volume" );
}
}
return types;
}
//=======================================================================
//function : labeledTypes
//purpose : may return {'Point' 'Cell'} at most
//=======================================================================
QValueList<QVariant> SMESHGUI_Selection::labeledTypes( int ind ) const
{
QValueList<QVariant> types;
SMESH_Actor* actor = getActor( ind );
if ( actor ) {
if ( actor->GetPointsLabeled()) types.append( "Point" );
if ( actor->GetCellsLabeled()) types.append( "Cell" );
}
return types;
}
//=======================================================================
//function : displayMode
//purpose : return SMESH_Actor::EReperesent
//=======================================================================
QString SMESHGUI_Selection::displayMode( int ind ) const
{
SMESH_Actor* actor = getActor( ind );
if ( actor ) {
switch( actor->GetRepresentation() ) {
case SMESH_Actor::eEdge: return "eEdge";
case SMESH_Actor::eSurface: return "eSurface";
case SMESH_Actor::ePoint: return "ePoint";
default:;
}
}
return "Unknown";
}
//=======================================================================
//function : shrinkMode
//purpose : return either 'IsSrunk', 'IsNotShrunk' or 'IsNotShrinkable'
//=======================================================================
QString SMESHGUI_Selection::shrinkMode( int ind ) const
{
SMESH_Actor* actor = getActor( ind );
if ( actor && actor->IsShrunkable() ) {
if ( actor->IsShrunk() )
return "IsShrunk";
return "IsNotShrunk";
}
return "IsNotShrinkable";
}
//=======================================================================
//function : entityMode
//purpose : may return {'Edge' 'Face' 'Volume'} at most
//=======================================================================
QValueList<QVariant> SMESHGUI_Selection::entityMode( int ind ) const
{
QValueList<QVariant> types;
SMESH_Actor* actor = getActor( ind );
if ( actor ) {
unsigned int aMode = actor->GetEntityMode();
if ( aMode & SMESH_Actor::eVolumes) types.append( "Volume");
if ( aMode & SMESH_Actor::eFaces ) types.append( "Face" );
if ( aMode & SMESH_Actor::eEdges ) types.append( "Edge" );
}
return types;
}
//=======================================================================
//function : controlMode
//purpose : return SMESH_Actor::eControl
//=======================================================================
QString SMESHGUI_Selection::controlMode( int ind ) const
{
SMESH_Actor* actor = getActor( ind );
if ( actor ) {
switch( actor->GetControlMode() ) {
case SMESH_Actor::eLength: return "eLength";
case SMESH_Actor::eLength2D: return "eLength2D";
case SMESH_Actor::eFreeEdges: return "eFreeEdges";
case SMESH_Actor::eFreeBorders: return "eFreeBorders";
case SMESH_Actor::eMultiConnection: return "eMultiConnection";
case SMESH_Actor::eMultiConnection2D: return "eMultiConnection2D";
case SMESH_Actor::eArea: return "eArea";
case SMESH_Actor::eTaper: return "eTaper";
case SMESH_Actor::eAspectRatio: return "eAspectRatio";
case SMESH_Actor::eAspectRatio3D: return "eAspectRatio3D";
case SMESH_Actor::eMinimumAngle: return "eMinimumAngle";
case SMESH_Actor::eWarping: return "eWarping";
case SMESH_Actor::eSkew: return "eSkew";
default:;
}
}
return "eNone";
}
//=======================================================================
//function : numberOfNodes
//purpose :
//=======================================================================
int SMESHGUI_Selection::numberOfNodes( int ind ) const
{
if ( ind >= 0 && ind < myTypes.count() && myTypes[ind] != "Unknown" )
{
CORBA::Object_var obj =
SMESH::DataOwnerToObject( static_cast<SalomeApp_DataOwner*>( myDataOwners[ ind ].get() ));
if ( ! CORBA::is_nil( obj )) {
SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( obj );
if ( ! mesh->_is_nil() )
return mesh->NbNodes();
SMESH::SMESH_subMesh_var aSubMeshObj = SMESH::SMESH_subMesh::_narrow( obj );
if ( !aSubMeshObj->_is_nil() )
return aSubMeshObj->GetNumberOfNodes(true);
SMESH::SMESH_GroupBase_var aGroupObj = SMESH::SMESH_GroupBase::_narrow( obj );
if ( !aGroupObj->_is_nil() )
return aGroupObj->Size();
}
}
return 0;
}
//=======================================================================
//function : isComputable
//purpose :
//=======================================================================
QVariant SMESHGUI_Selection::isComputable( int ind ) const
{
if ( ind >= 0 && ind < myTypes.count() && myTypes[ind] != "Unknown" )
{
Handle(SALOME_InteractiveObject) io =
static_cast<SalomeApp_DataOwner*>( myDataOwners[ ind ].get() )->IO();
if ( !io.IsNull() ) {
SMESH::SMESH_Mesh_var mesh = SMESH::GetMeshByIO(io) ; // m,sm,gr->m
if ( !mesh->_is_nil() ) {
_PTR(SObject) so = SMESH::FindSObject( mesh );
if ( so ) {
GEOM::GEOM_Object_var shape = SMESH::GetShapeOnMeshOrSubMesh( so );
return QVariant( !shape->_is_nil(), 0 );
}
}
}
}
return QVariant( false, 0 );
}
//=======================================================================
//function : hasReference
//purpose :
//=======================================================================
QVariant SMESHGUI_Selection::hasReference( int ind ) const
{
if ( ind >= 0 && ind < myTypes.count() && myTypes[ind] != "Unknown" )
{
Handle(SALOME_InteractiveObject) io =
static_cast<SalomeApp_DataOwner*>( myDataOwners[ ind ].get() )->IO();
if ( !io.IsNull() )
return QVariant( io->hasReference(), 0 );
}
return QVariant( false, 0 );
}
//=======================================================================
//function : isVisible
//purpose :
//=======================================================================
QVariant SMESHGUI_Selection::isVisible( int ind ) const
{
if ( ind >= 0 && ind < myTypes.count() && myTypes[ind] != "Unknown" )
{
QString entry = static_cast<SalomeApp_DataOwner*>( myDataOwners[ ind ].get() )->entry();
SMESH_Actor* actor = SMESH::FindActorByEntry( entry.latin1() );
if ( actor && actor->hasIO() ) {
SVTK_RenderWindowInteractor* renderInter = SMESH::GetCurrentVtkView()->getRWInteractor();
return QVariant( renderInter->isVisible( actor->getIO() ), 0 );
}
}
return QVariant( false, 0 );
}
//=======================================================================
//function : type
//purpose :
//=======================================================================
int SMESHGUI_Selection::type( SalomeApp_DataOwner* owner,
_PTR(Study) study )
{
QString entry = owner->entry();
_PTR(SObject) obj (study->FindObjectID(entry.latin1()));
if( !obj )
return -1;
_PTR(SObject) objFather = obj->GetFather();
_PTR(SComponent) objComponent = obj->GetFatherComponent();
int aLevel = obj->Depth() - objComponent->Depth(),
aFTag = objFather->Tag(),
anOTag = obj->Tag(),
res = -1;
switch( aLevel )
{
case 1:
if( anOTag>=3 )
res = MESH;
break;
case 2:
switch( aFTag )
{
case 1:
res = HYPOTHESIS;
break;
case 2:
res = ALGORITHM;
break;
}
break;
case 3:
switch( aFTag )
{
case 4:
res = SUBMESH_VERTEX;
break;
case 5:
res = SUBMESH_EDGE;
break;
case 7:
res = SUBMESH_FACE;
break;
case 9:
res = SUBMESH_SOLID;
break;
case 10:
res = SUBMESH_COMPOUND;
break;
}
if( aFTag>10 )
res = GROUP;
break;
}
return res;
}
//=======================================================================
//function : typeName
//purpose :
//=======================================================================
QString SMESHGUI_Selection::typeName( const int t )
{
switch( t )
{
case HYPOTHESIS:
return "Hypothesis";
case ALGORITHM:
return "Algorithm";
case MESH:
return "Mesh";
case SUBMESH:
return "SubMesh";
case MESHorSUBMESH:
return "Mesh or submesh";
case SUBMESH_VERTEX:
return "Mesh vertex";
case SUBMESH_EDGE:
return "Mesh edge";
case SUBMESH_FACE:
return "Mesh face";
case SUBMESH_SOLID:
return "Mesh solid";
case SUBMESH_COMPOUND:
return "Mesh compound";
case GROUP:
return "Group";
default:
return "Unknown";
}
}
<commit_msg>Remove debug information.<commit_after>
#include "SMESHGUI_Selection.h"
#include "SMESHGUI_Utils.h"
#include "SMESHGUI_VTKUtils.h"
#include "SMESHGUI_MeshUtils.h"
#include "SMESHGUI_GEOMGenUtils.h"
#include "SMESH_Type.h"
#include "SMESH_Actor.h"
#include "SalomeApp_SelectionMgr.h"
#include "SalomeApp_Study.h"
#include "SalomeApp_VTKSelector.h"
#include "SUIT_Session.h"
#include "SVTK_RenderWindowInteractor.h"
#include "SVTK_ViewWindow.h"
#include CORBA_SERVER_HEADER(SMESH_Mesh)
#include CORBA_SERVER_HEADER(SMESH_Group)
//=======================================================================
//function : SMESHGUI_Selection
//purpose :
//=======================================================================
SMESHGUI_Selection::SMESHGUI_Selection()
: SalomeApp_Selection()
{
}
//=======================================================================
//function : ~SMESHGUI_Selection
//purpose :
//=======================================================================
SMESHGUI_Selection::~SMESHGUI_Selection()
{
}
//=======================================================================
//function : init
//purpose :
//=======================================================================
void SMESHGUI_Selection::init( const QString& client, SalomeApp_SelectionMgr* mgr )
{
SalomeApp_Selection::init( client, mgr );
if( mgr && study() )
{
_PTR(Study) aStudy = study()->studyDS();
SUIT_DataOwnerPtrList sel;
mgr->selected( sel, client );
myDataOwners = sel;
SUIT_DataOwnerPtrList::const_iterator anIt = sel.begin(),
aLast = sel.end();
for( ; anIt!=aLast; anIt++ )
{
SUIT_DataOwner* owner = ( SUIT_DataOwner* )( (*anIt ).get() );
SalomeApp_DataOwner* sowner = dynamic_cast<SalomeApp_DataOwner*>( owner );
if( sowner )
myTypes.append( typeName( type( sowner, aStudy ) ) );
else
myTypes.append( "Unknown" );
}
}
}
//=======================================================================
//function : param
//purpose :
//=======================================================================
QtxValue SMESHGUI_Selection::param( const int ind, const QString& p ) const
{
QtxValue val;
if ( p=="client" ) val = QtxValue( globalParam( p ) );
else if ( p=="type" ) val = QtxValue( myTypes[ind] );
else if ( p=="elemTypes" ) val = QtxValue( elemTypes( ind ) );
else if ( p=="numberOfNodes" ) val = QtxValue( numberOfNodes( ind ) );
else if ( p=="labeledTypes" ) val = QtxValue( labeledTypes( ind ) );
else if ( p=="shrinkMode" ) val = QtxValue( shrinkMode( ind ) );
else if ( p=="entityMode" ) val = QtxValue( entityMode( ind ) );
else if ( p=="controlMode" ) val = QtxValue( controlMode( ind ) );
else if ( p=="displayMode" ) val = QtxValue( displayMode( ind ) );
else if ( p=="isComputable" ) val = QtxValue( isComputable( ind ) );
else if ( p=="hasReference" ) val = QtxValue( hasReference( ind ) );
else if ( p=="isVisible" ) val = QtxValue( isVisible( ind ) );
// printf( "--> param() : [%s] = %s (%s)\n", p.latin1(), val.toString().latin1(), val.typeName() );
//if ( val.type() == QVariant::List )
//cout << "size: " << val.toList().count() << endl;
return val;
}
//=======================================================================
//function : getVtkOwner
//purpose :
//=======================================================================
SMESH_Actor* SMESHGUI_Selection::getActor( int ind ) const
{
if ( ind >= 0 && ind < myDataOwners.count() ) {
const SalomeApp_SVTKDataOwner* owner =
dynamic_cast<const SalomeApp_SVTKDataOwner*> ( myDataOwners[ ind ].get() );
if ( owner )
return dynamic_cast<SMESH_Actor*>( owner->GetActor() );
}
return 0;
}
//=======================================================================
//function : elemTypes
//purpose : may return {'Edge' 'Face' 'Volume'} at most
//=======================================================================
QValueList<QVariant> SMESHGUI_Selection::elemTypes( int ind ) const
{
QValueList<QVariant> types;
SMESH_Actor* actor = getActor( ind );
if ( actor ) {
TVisualObjPtr object = actor->GetObject();
if ( object ) {
if ( object->GetNbEntities( SMDSAbs_Edge )) types.append( "Edge" );
if ( object->GetNbEntities( SMDSAbs_Face )) types.append( "Face" );
if ( object->GetNbEntities( SMDSAbs_Volume )) types.append( "Volume" );
}
}
return types;
}
//=======================================================================
//function : labeledTypes
//purpose : may return {'Point' 'Cell'} at most
//=======================================================================
QValueList<QVariant> SMESHGUI_Selection::labeledTypes( int ind ) const
{
QValueList<QVariant> types;
SMESH_Actor* actor = getActor( ind );
if ( actor ) {
if ( actor->GetPointsLabeled()) types.append( "Point" );
if ( actor->GetCellsLabeled()) types.append( "Cell" );
}
return types;
}
//=======================================================================
//function : displayMode
//purpose : return SMESH_Actor::EReperesent
//=======================================================================
QString SMESHGUI_Selection::displayMode( int ind ) const
{
SMESH_Actor* actor = getActor( ind );
if ( actor ) {
switch( actor->GetRepresentation() ) {
case SMESH_Actor::eEdge: return "eEdge";
case SMESH_Actor::eSurface: return "eSurface";
case SMESH_Actor::ePoint: return "ePoint";
default:;
}
}
return "Unknown";
}
//=======================================================================
//function : shrinkMode
//purpose : return either 'IsSrunk', 'IsNotShrunk' or 'IsNotShrinkable'
//=======================================================================
QString SMESHGUI_Selection::shrinkMode( int ind ) const
{
SMESH_Actor* actor = getActor( ind );
if ( actor && actor->IsShrunkable() ) {
if ( actor->IsShrunk() )
return "IsShrunk";
return "IsNotShrunk";
}
return "IsNotShrinkable";
}
//=======================================================================
//function : entityMode
//purpose : may return {'Edge' 'Face' 'Volume'} at most
//=======================================================================
QValueList<QVariant> SMESHGUI_Selection::entityMode( int ind ) const
{
QValueList<QVariant> types;
SMESH_Actor* actor = getActor( ind );
if ( actor ) {
unsigned int aMode = actor->GetEntityMode();
if ( aMode & SMESH_Actor::eVolumes) types.append( "Volume");
if ( aMode & SMESH_Actor::eFaces ) types.append( "Face" );
if ( aMode & SMESH_Actor::eEdges ) types.append( "Edge" );
}
return types;
}
//=======================================================================
//function : controlMode
//purpose : return SMESH_Actor::eControl
//=======================================================================
QString SMESHGUI_Selection::controlMode( int ind ) const
{
SMESH_Actor* actor = getActor( ind );
if ( actor ) {
switch( actor->GetControlMode() ) {
case SMESH_Actor::eLength: return "eLength";
case SMESH_Actor::eLength2D: return "eLength2D";
case SMESH_Actor::eFreeEdges: return "eFreeEdges";
case SMESH_Actor::eFreeBorders: return "eFreeBorders";
case SMESH_Actor::eMultiConnection: return "eMultiConnection";
case SMESH_Actor::eMultiConnection2D: return "eMultiConnection2D";
case SMESH_Actor::eArea: return "eArea";
case SMESH_Actor::eTaper: return "eTaper";
case SMESH_Actor::eAspectRatio: return "eAspectRatio";
case SMESH_Actor::eAspectRatio3D: return "eAspectRatio3D";
case SMESH_Actor::eMinimumAngle: return "eMinimumAngle";
case SMESH_Actor::eWarping: return "eWarping";
case SMESH_Actor::eSkew: return "eSkew";
default:;
}
}
return "eNone";
}
//=======================================================================
//function : numberOfNodes
//purpose :
//=======================================================================
int SMESHGUI_Selection::numberOfNodes( int ind ) const
{
if ( ind >= 0 && ind < myTypes.count() && myTypes[ind] != "Unknown" )
{
CORBA::Object_var obj =
SMESH::DataOwnerToObject( static_cast<SalomeApp_DataOwner*>( myDataOwners[ ind ].get() ));
if ( ! CORBA::is_nil( obj )) {
SMESH::SMESH_Mesh_var mesh = SMESH::SMESH_Mesh::_narrow( obj );
if ( ! mesh->_is_nil() )
return mesh->NbNodes();
SMESH::SMESH_subMesh_var aSubMeshObj = SMESH::SMESH_subMesh::_narrow( obj );
if ( !aSubMeshObj->_is_nil() )
return aSubMeshObj->GetNumberOfNodes(true);
SMESH::SMESH_GroupBase_var aGroupObj = SMESH::SMESH_GroupBase::_narrow( obj );
if ( !aGroupObj->_is_nil() )
return aGroupObj->Size();
}
}
return 0;
}
//=======================================================================
//function : isComputable
//purpose :
//=======================================================================
QVariant SMESHGUI_Selection::isComputable( int ind ) const
{
if ( ind >= 0 && ind < myTypes.count() && myTypes[ind] != "Unknown" )
{
Handle(SALOME_InteractiveObject) io =
static_cast<SalomeApp_DataOwner*>( myDataOwners[ ind ].get() )->IO();
if ( !io.IsNull() ) {
SMESH::SMESH_Mesh_var mesh = SMESH::GetMeshByIO(io) ; // m,sm,gr->m
if ( !mesh->_is_nil() ) {
_PTR(SObject) so = SMESH::FindSObject( mesh );
if ( so ) {
GEOM::GEOM_Object_var shape = SMESH::GetShapeOnMeshOrSubMesh( so );
return QVariant( !shape->_is_nil(), 0 );
}
}
}
}
return QVariant( false, 0 );
}
//=======================================================================
//function : hasReference
//purpose :
//=======================================================================
QVariant SMESHGUI_Selection::hasReference( int ind ) const
{
if ( ind >= 0 && ind < myTypes.count() && myTypes[ind] != "Unknown" )
{
Handle(SALOME_InteractiveObject) io =
static_cast<SalomeApp_DataOwner*>( myDataOwners[ ind ].get() )->IO();
if ( !io.IsNull() )
return QVariant( io->hasReference(), 0 );
}
return QVariant( false, 0 );
}
//=======================================================================
//function : isVisible
//purpose :
//=======================================================================
QVariant SMESHGUI_Selection::isVisible( int ind ) const
{
if ( ind >= 0 && ind < myTypes.count() && myTypes[ind] != "Unknown" )
{
QString entry = static_cast<SalomeApp_DataOwner*>( myDataOwners[ ind ].get() )->entry();
SMESH_Actor* actor = SMESH::FindActorByEntry( entry.latin1() );
if ( actor && actor->hasIO() ) {
SVTK_RenderWindowInteractor* renderInter = SMESH::GetCurrentVtkView()->getRWInteractor();
return QVariant( renderInter->isVisible( actor->getIO() ), 0 );
}
}
return QVariant( false, 0 );
}
//=======================================================================
//function : type
//purpose :
//=======================================================================
int SMESHGUI_Selection::type( SalomeApp_DataOwner* owner,
_PTR(Study) study )
{
QString entry = owner->entry();
_PTR(SObject) obj (study->FindObjectID(entry.latin1()));
if( !obj )
return -1;
_PTR(SObject) objFather = obj->GetFather();
_PTR(SComponent) objComponent = obj->GetFatherComponent();
int aLevel = obj->Depth() - objComponent->Depth(),
aFTag = objFather->Tag(),
anOTag = obj->Tag(),
res = -1;
switch( aLevel )
{
case 1:
if( anOTag>=3 )
res = MESH;
break;
case 2:
switch( aFTag )
{
case 1:
res = HYPOTHESIS;
break;
case 2:
res = ALGORITHM;
break;
}
break;
case 3:
switch( aFTag )
{
case 4:
res = SUBMESH_VERTEX;
break;
case 5:
res = SUBMESH_EDGE;
break;
case 7:
res = SUBMESH_FACE;
break;
case 9:
res = SUBMESH_SOLID;
break;
case 10:
res = SUBMESH_COMPOUND;
break;
}
if( aFTag>10 )
res = GROUP;
break;
}
return res;
}
//=======================================================================
//function : typeName
//purpose :
//=======================================================================
QString SMESHGUI_Selection::typeName( const int t )
{
switch( t )
{
case HYPOTHESIS:
return "Hypothesis";
case ALGORITHM:
return "Algorithm";
case MESH:
return "Mesh";
case SUBMESH:
return "SubMesh";
case MESHorSUBMESH:
return "Mesh or submesh";
case SUBMESH_VERTEX:
return "Mesh vertex";
case SUBMESH_EDGE:
return "Mesh edge";
case SUBMESH_FACE:
return "Mesh face";
case SUBMESH_SOLID:
return "Mesh solid";
case SUBMESH_COMPOUND:
return "Mesh compound";
case GROUP:
return "Group";
default:
return "Unknown";
}
}
<|endoftext|> |
<commit_before>/*-------------------------------------------------------------------------
*
* mapper_seq_scan.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /peloton/src/backend/bridge/dml/mapper/mapper_seq_scan.cpp
*
*-------------------------------------------------------------------------
*/
#include "backend/bridge/dml/mapper/mapper.h"
#include "backend/planner/nested_loop_join_node.h"
namespace peloton {
namespace bridge {
//===--------------------------------------------------------------------===//
// Nested Loop Join
//===--------------------------------------------------------------------===//
/**
* @brief Convert a Postgres NestLoop into a Peloton SeqScanNode.
* @return Pointer to the constructed AbstractPlanNode.
*/
planner::AbstractPlanNode* PlanTransformer::TransformNestLoop(
const NestLoopState* nl_plan_state) {
const JoinState *js = &(nl_plan_state->js);
PelotonJoinType jointype = PlanTransformer::TransformJoinType(js->jointype);
if (jointype == JOIN_TYPE_INVALID) {
LOG_ERROR("unsupported join type: %d", js->jointype);
return nullptr;
}
expression::AbstractExpression *join_filter = ExprTransformer::TransformExpr(
reinterpret_cast<ExprState *>(js->joinqual));
expression::AbstractExpression *plan_filter = ExprTransformer::TransformExpr(
reinterpret_cast<ExprState *>(js->ps.qual));
/* TODO: do we need to consider target list here? */
planner::AbstractPlanNode *outer = PlanTransformer::TransformPlan(outerPlanState(nl_plan_state));
planner::AbstractPlanNode *inner = PlanTransformer::TransformPlan(innerPlanState(nl_plan_state));
/* Construct and return the Peloton plan node */
auto plan_node = new planner::NestedLoopJoinNode(
expression::ConjunctionFactory(EXPRESSION_TYPE_CONJUNCTION_AND,
join_filter, plan_filter));
plan_node->SetJoinType(jointype);
plan_node->AddChild(outer);
plan_node->AddChild(inner);
return plan_node;
}
} // namespace bridge
} // namespace peloton
<commit_msg>do not create null conjunction predicate if no qulifier exists in the original plan<commit_after>/*-------------------------------------------------------------------------
*
* mapper_seq_scan.cpp
* file description
*
* Copyright(c) 2015, CMU
*
* /peloton/src/backend/bridge/dml/mapper/mapper_seq_scan.cpp
*
*-------------------------------------------------------------------------
*/
#include "backend/bridge/dml/mapper/mapper.h"
#include "backend/planner/nested_loop_join_node.h"
namespace peloton {
namespace bridge {
//===--------------------------------------------------------------------===//
// Nested Loop Join
//===--------------------------------------------------------------------===//
/**
* @brief Convert a Postgres NestLoop into a Peloton SeqScanNode.
* @return Pointer to the constructed AbstractPlanNode.
*/
planner::AbstractPlanNode* PlanTransformer::TransformNestLoop(
const NestLoopState* nl_plan_state) {
const JoinState *js = &(nl_plan_state->js);
PelotonJoinType join_type = PlanTransformer::TransformJoinType(js->jointype);
if (join_type == JOIN_TYPE_INVALID) {
LOG_ERROR("unsupported join type: %d", js->jointype);
return nullptr;
}
expression::AbstractExpression *join_filter = ExprTransformer::TransformExpr(
reinterpret_cast<ExprState *>(js->joinqual));
expression::AbstractExpression *plan_filter = ExprTransformer::TransformExpr(
reinterpret_cast<ExprState *>(js->ps.qual));
expression::AbstractExpression *predicate = nullptr;
if (join_filter && plan_filter) {
predicate = expression::ConjunctionFactory(EXPRESSION_TYPE_CONJUNCTION_AND,
join_filter, plan_filter);
} else if (join_filter) {
predicate = join_filter;
} else {
predicate = plan_filter;
}
/* TODO: do we need to consider target list here? */
planner::AbstractPlanNode *outer = PlanTransformer::TransformPlan(outerPlanState(nl_plan_state));
planner::AbstractPlanNode *inner = PlanTransformer::TransformPlan(innerPlanState(nl_plan_state));
/* Construct and return the Peloton plan node */
auto plan_node = new planner::NestedLoopJoinNode(predicate);
plan_node->SetJoinType(join_type);
plan_node->AddChild(outer);
plan_node->AddChild(inner);
LOG_INFO("Handle Nested loop join, JoinType: %d", join_type);
return plan_node;
}
} // namespace bridge
} // namespace peloton
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// The PasswordManagerAutocompleteTests in this file test only the
// PasswordAutocompleteListener class implementation (and not any of the
// higher level dom autocomplete framework).
#include <string>
#include "base/string_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/glue/form_field.h"
#include "webkit/glue/webpasswordautocompletelistener_impl.h"
using WebKit::WebString;
using webkit_glue::FormField;
using webkit_glue::PasswordFormDomManager;
using webkit_glue::WebInputElementDelegate;
using webkit_glue::WebPasswordAutocompleteListenerImpl;
class TestWebInputElementDelegate : public WebInputElementDelegate {
public:
TestWebInputElementDelegate() : WebInputElementDelegate(),
did_call_on_finish_(false),
did_set_value_(false),
did_set_selection_(false),
selection_start_(0),
selection_end_(0),
is_editable_(true) {
}
// Override those methods we implicitly invoke in the tests.
virtual bool IsEditable() {
return is_editable_;
}
virtual void SetValue(const string16& value) {
value_ = value;
did_set_value_ = true;
}
virtual void OnFinishedAutocompleting() {
did_call_on_finish_ = true;
}
virtual void SetSelectionRange(size_t start, size_t end) {
selection_start_ = start;
selection_end_ = end;
did_set_selection_ = true;
}
// Testing-only methods.
void ResetTestState() {
did_call_on_finish_ = false;
did_set_value_ = false;
did_set_selection_ = false;
}
void set_is_editable(bool editable) {
is_editable_ = editable;
}
string16 value() const {
return value_;
}
bool did_call_on_finish() const {
return did_call_on_finish_;
}
bool did_set_value() const {
return did_set_value_;
}
bool did_set_selection() const {
return did_set_selection_;
}
size_t selection_start() const {
return selection_start_;
}
size_t selection_end() const {
return selection_end_;
}
private:
bool did_call_on_finish_;
bool did_set_value_;
bool did_set_selection_;
string16 value_;
size_t selection_start_;
size_t selection_end_;
bool is_editable_;
};
namespace {
class PasswordManagerAutocompleteTests : public testing::Test {
public:
virtual void SetUp() {
// Add a preferred login and an additional login to the FillData.
username1_ = ASCIIToUTF16("alice");
password1_ = ASCIIToUTF16("password");
username2_ = ASCIIToUTF16("bob");
password2_ = ASCIIToUTF16("bobsyouruncle");
data_.basic_data.fields.push_back(FormField(string16(),
string16(),
username1_,
string16()));
data_.basic_data.fields.push_back(FormField(string16(),
string16(),
password1_,
string16()));
data_.additional_logins[username2_] = password2_;
testing::Test::SetUp();
}
string16 username1_;
string16 password1_;
string16 username2_;
string16 password2_;
PasswordFormDomManager::FillData data_;
};
TEST_F(PasswordManagerAutocompleteTests, OnBlur) {
TestWebInputElementDelegate* username_delegate =
new TestWebInputElementDelegate();
TestWebInputElementDelegate* password_delegate =
new TestWebInputElementDelegate();
scoped_ptr<WebPasswordAutocompleteListenerImpl> listener(
new WebPasswordAutocompleteListenerImpl(username_delegate,
password_delegate,
data_));
// Clear the password field.
password_delegate->SetValue(string16());
// Make the password field read-only.
password_delegate->set_is_editable(false);
// Simulate a blur event on the username field, but r/o password won't fill.
listener->didBlurInputElement(username1_);
EXPECT_EQ(string16(), password_delegate->value());
password_delegate->set_is_editable(true);
// Simulate a blur event on the username field and expect a password autofill.
listener->didBlurInputElement(username1_);
EXPECT_EQ(password1_, password_delegate->value());
// Now the user goes back and changes the username to something we don't
// have saved. The password should remain unchanged.
listener->didBlurInputElement(ASCIIToUTF16("blahblahblah"));
EXPECT_EQ(password1_, password_delegate->value());
// Now they type in the additional login username.
listener->didBlurInputElement(username2_);
EXPECT_EQ(password2_, password_delegate->value());
}
TEST_F(PasswordManagerAutocompleteTests, OnInlineAutocompleteNeeded) {
TestWebInputElementDelegate* username_delegate =
new TestWebInputElementDelegate();
TestWebInputElementDelegate* password_delegate =
new TestWebInputElementDelegate();
scoped_ptr<WebPasswordAutocompleteListenerImpl> listener(
new WebPasswordAutocompleteListenerImpl(username_delegate,
password_delegate,
data_));
password_delegate->SetValue(string16());
// Simulate the user typing in the first letter of 'alice', a stored username.
listener->performInlineAutocomplete(ASCIIToUTF16("a"), false, false);
// Both the username and password delegates should reflect selection
// of the stored login.
EXPECT_EQ(username1_, username_delegate->value());
EXPECT_EQ(password1_, password_delegate->value());
// And the selection should have been set to 'lice', the last 4 letters.
EXPECT_EQ(1U, username_delegate->selection_start());
EXPECT_EQ(username1_.length(), username_delegate->selection_end());
// And both fields should have observed OnFinishedAutocompleting.
EXPECT_TRUE(username_delegate->did_call_on_finish());
EXPECT_TRUE(password_delegate->did_call_on_finish());
// Now the user types the next letter of the same username, 'l'.
listener->performInlineAutocomplete(ASCIIToUTF16("al"), false, false);
// Now the fields should have the same value, but the selection should have a
// different start value.
EXPECT_EQ(username1_, username_delegate->value());
EXPECT_EQ(password1_, password_delegate->value());
EXPECT_EQ(2U, username_delegate->selection_start());
EXPECT_EQ(username1_.length(), username_delegate->selection_end());
// Now lets say the user goes astray from the stored username and types
// the letter 'f', spelling 'alf'. We don't know alf (that's just sad),
// so in practice the username should no longer be 'alice' and the selected
// range should be empty. In our case, when the autocomplete code doesn't
// know the text, it won't set the value or the selection and hence our
// delegate methods won't get called. The WebCore::HTMLInputElement's value
// and selection would be set directly by WebCore in practice.
// Reset the delegate's test state so we can determine what, if anything,
// was invoked during performInlineAutocomplete.
username_delegate->ResetTestState();
password_delegate->ResetTestState();
listener->performInlineAutocomplete(ASCIIToUTF16("alf"), false, false);
EXPECT_FALSE(username_delegate->did_set_selection());
EXPECT_FALSE(username_delegate->did_set_value());
EXPECT_FALSE(username_delegate->did_call_on_finish());
EXPECT_FALSE(password_delegate->did_set_value());
EXPECT_FALSE(password_delegate->did_call_on_finish());
// Ok, so now the user removes all the text and enters the letter 'b'.
listener->performInlineAutocomplete(ASCIIToUTF16("b"), false, false);
// The username and password fields should match the 'bob' entry.
EXPECT_EQ(username2_, username_delegate->value());
EXPECT_EQ(password2_, password_delegate->value());
EXPECT_EQ(1U, username_delegate->selection_start());
EXPECT_EQ(username2_.length(), username_delegate->selection_end());
}
TEST_F(PasswordManagerAutocompleteTests, TestWaitUsername) {
TestWebInputElementDelegate* username_delegate =
new TestWebInputElementDelegate();
TestWebInputElementDelegate* password_delegate =
new TestWebInputElementDelegate();
// If we had an action authority mismatch (for example), we don't want to
// automatically autofill anything without some user interaction first.
// We require an explicit blur on the username field, and that a valid
// matching username is in the field, before we autofill passwords.
data_.wait_for_username = true;
scoped_ptr<WebPasswordAutocompleteListenerImpl> listener(
new WebPasswordAutocompleteListenerImpl(username_delegate,
password_delegate,
data_));
string16 empty;
// In all cases, username_delegate should remain empty because we should
// never modify it when wait_for_username is true; only the user can by
// typing into (in real life) the HTMLInputElement.
password_delegate->SetValue(string16());
listener->performInlineAutocomplete(ASCIIToUTF16("a"), false, false);
EXPECT_EQ(empty, username_delegate->value());
EXPECT_EQ(empty, password_delegate->value());
listener->performInlineAutocomplete(ASCIIToUTF16("al"), false, false);
EXPECT_EQ(empty, username_delegate->value());
EXPECT_EQ(empty, password_delegate->value());
listener->performInlineAutocomplete(ASCIIToUTF16("alice"), false, false);
EXPECT_EQ(empty, username_delegate->value());
EXPECT_EQ(empty, password_delegate->value());
listener->didBlurInputElement(ASCIIToUTF16("a"));
EXPECT_EQ(empty, username_delegate->value());
EXPECT_EQ(empty, password_delegate->value());
listener->didBlurInputElement(ASCIIToUTF16("ali"));
EXPECT_EQ(empty, username_delegate->value());
EXPECT_EQ(empty, password_delegate->value());
// Blur with 'alice' should allow password autofill.
listener->didBlurInputElement(ASCIIToUTF16("alice"));
EXPECT_EQ(empty, username_delegate->value());
EXPECT_EQ(password1_, password_delegate->value());
}
} // namespace
<commit_msg>Compile fix for CL: Form AutoFill Phone number should be displayed as xxx-xxx-xxxx<commit_after>// Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// The PasswordManagerAutocompleteTests in this file test only the
// PasswordAutocompleteListener class implementation (and not any of the
// higher level dom autocomplete framework).
#include <string>
#include "base/string_util.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/glue/form_field.h"
#include "webkit/glue/webpasswordautocompletelistener_impl.h"
using WebKit::WebString;
using webkit_glue::FormField;
using webkit_glue::PasswordFormDomManager;
using webkit_glue::WebInputElementDelegate;
using webkit_glue::WebPasswordAutocompleteListenerImpl;
class TestWebInputElementDelegate : public WebInputElementDelegate {
public:
TestWebInputElementDelegate() : WebInputElementDelegate(),
did_call_on_finish_(false),
did_set_value_(false),
did_set_selection_(false),
selection_start_(0),
selection_end_(0),
is_editable_(true) {
}
// Override those methods we implicitly invoke in the tests.
virtual bool IsEditable() {
return is_editable_;
}
virtual void SetValue(const string16& value) {
value_ = value;
did_set_value_ = true;
}
virtual void OnFinishedAutocompleting() {
did_call_on_finish_ = true;
}
virtual void SetSelectionRange(size_t start, size_t end) {
selection_start_ = start;
selection_end_ = end;
did_set_selection_ = true;
}
// Testing-only methods.
void ResetTestState() {
did_call_on_finish_ = false;
did_set_value_ = false;
did_set_selection_ = false;
}
void set_is_editable(bool editable) {
is_editable_ = editable;
}
string16 value() const {
return value_;
}
bool did_call_on_finish() const {
return did_call_on_finish_;
}
bool did_set_value() const {
return did_set_value_;
}
bool did_set_selection() const {
return did_set_selection_;
}
size_t selection_start() const {
return selection_start_;
}
size_t selection_end() const {
return selection_end_;
}
private:
bool did_call_on_finish_;
bool did_set_value_;
bool did_set_selection_;
string16 value_;
size_t selection_start_;
size_t selection_end_;
bool is_editable_;
};
namespace {
class PasswordManagerAutocompleteTests : public testing::Test {
public:
virtual void SetUp() {
// Add a preferred login and an additional login to the FillData.
username1_ = ASCIIToUTF16("alice");
password1_ = ASCIIToUTF16("password");
username2_ = ASCIIToUTF16("bob");
password2_ = ASCIIToUTF16("bobsyouruncle");
data_.basic_data.fields.push_back(FormField(string16(),
string16(),
username1_,
string16(),
0));
data_.basic_data.fields.push_back(FormField(string16(),
string16(),
password1_,
string16(),
0));
data_.additional_logins[username2_] = password2_;
testing::Test::SetUp();
}
string16 username1_;
string16 password1_;
string16 username2_;
string16 password2_;
PasswordFormDomManager::FillData data_;
};
TEST_F(PasswordManagerAutocompleteTests, OnBlur) {
TestWebInputElementDelegate* username_delegate =
new TestWebInputElementDelegate();
TestWebInputElementDelegate* password_delegate =
new TestWebInputElementDelegate();
scoped_ptr<WebPasswordAutocompleteListenerImpl> listener(
new WebPasswordAutocompleteListenerImpl(username_delegate,
password_delegate,
data_));
// Clear the password field.
password_delegate->SetValue(string16());
// Make the password field read-only.
password_delegate->set_is_editable(false);
// Simulate a blur event on the username field, but r/o password won't fill.
listener->didBlurInputElement(username1_);
EXPECT_EQ(string16(), password_delegate->value());
password_delegate->set_is_editable(true);
// Simulate a blur event on the username field and expect a password autofill.
listener->didBlurInputElement(username1_);
EXPECT_EQ(password1_, password_delegate->value());
// Now the user goes back and changes the username to something we don't
// have saved. The password should remain unchanged.
listener->didBlurInputElement(ASCIIToUTF16("blahblahblah"));
EXPECT_EQ(password1_, password_delegate->value());
// Now they type in the additional login username.
listener->didBlurInputElement(username2_);
EXPECT_EQ(password2_, password_delegate->value());
}
TEST_F(PasswordManagerAutocompleteTests, OnInlineAutocompleteNeeded) {
TestWebInputElementDelegate* username_delegate =
new TestWebInputElementDelegate();
TestWebInputElementDelegate* password_delegate =
new TestWebInputElementDelegate();
scoped_ptr<WebPasswordAutocompleteListenerImpl> listener(
new WebPasswordAutocompleteListenerImpl(username_delegate,
password_delegate,
data_));
password_delegate->SetValue(string16());
// Simulate the user typing in the first letter of 'alice', a stored username.
listener->performInlineAutocomplete(ASCIIToUTF16("a"), false, false);
// Both the username and password delegates should reflect selection
// of the stored login.
EXPECT_EQ(username1_, username_delegate->value());
EXPECT_EQ(password1_, password_delegate->value());
// And the selection should have been set to 'lice', the last 4 letters.
EXPECT_EQ(1U, username_delegate->selection_start());
EXPECT_EQ(username1_.length(), username_delegate->selection_end());
// And both fields should have observed OnFinishedAutocompleting.
EXPECT_TRUE(username_delegate->did_call_on_finish());
EXPECT_TRUE(password_delegate->did_call_on_finish());
// Now the user types the next letter of the same username, 'l'.
listener->performInlineAutocomplete(ASCIIToUTF16("al"), false, false);
// Now the fields should have the same value, but the selection should have a
// different start value.
EXPECT_EQ(username1_, username_delegate->value());
EXPECT_EQ(password1_, password_delegate->value());
EXPECT_EQ(2U, username_delegate->selection_start());
EXPECT_EQ(username1_.length(), username_delegate->selection_end());
// Now lets say the user goes astray from the stored username and types
// the letter 'f', spelling 'alf'. We don't know alf (that's just sad),
// so in practice the username should no longer be 'alice' and the selected
// range should be empty. In our case, when the autocomplete code doesn't
// know the text, it won't set the value or the selection and hence our
// delegate methods won't get called. The WebCore::HTMLInputElement's value
// and selection would be set directly by WebCore in practice.
// Reset the delegate's test state so we can determine what, if anything,
// was invoked during performInlineAutocomplete.
username_delegate->ResetTestState();
password_delegate->ResetTestState();
listener->performInlineAutocomplete(ASCIIToUTF16("alf"), false, false);
EXPECT_FALSE(username_delegate->did_set_selection());
EXPECT_FALSE(username_delegate->did_set_value());
EXPECT_FALSE(username_delegate->did_call_on_finish());
EXPECT_FALSE(password_delegate->did_set_value());
EXPECT_FALSE(password_delegate->did_call_on_finish());
// Ok, so now the user removes all the text and enters the letter 'b'.
listener->performInlineAutocomplete(ASCIIToUTF16("b"), false, false);
// The username and password fields should match the 'bob' entry.
EXPECT_EQ(username2_, username_delegate->value());
EXPECT_EQ(password2_, password_delegate->value());
EXPECT_EQ(1U, username_delegate->selection_start());
EXPECT_EQ(username2_.length(), username_delegate->selection_end());
}
TEST_F(PasswordManagerAutocompleteTests, TestWaitUsername) {
TestWebInputElementDelegate* username_delegate =
new TestWebInputElementDelegate();
TestWebInputElementDelegate* password_delegate =
new TestWebInputElementDelegate();
// If we had an action authority mismatch (for example), we don't want to
// automatically autofill anything without some user interaction first.
// We require an explicit blur on the username field, and that a valid
// matching username is in the field, before we autofill passwords.
data_.wait_for_username = true;
scoped_ptr<WebPasswordAutocompleteListenerImpl> listener(
new WebPasswordAutocompleteListenerImpl(username_delegate,
password_delegate,
data_));
string16 empty;
// In all cases, username_delegate should remain empty because we should
// never modify it when wait_for_username is true; only the user can by
// typing into (in real life) the HTMLInputElement.
password_delegate->SetValue(string16());
listener->performInlineAutocomplete(ASCIIToUTF16("a"), false, false);
EXPECT_EQ(empty, username_delegate->value());
EXPECT_EQ(empty, password_delegate->value());
listener->performInlineAutocomplete(ASCIIToUTF16("al"), false, false);
EXPECT_EQ(empty, username_delegate->value());
EXPECT_EQ(empty, password_delegate->value());
listener->performInlineAutocomplete(ASCIIToUTF16("alice"), false, false);
EXPECT_EQ(empty, username_delegate->value());
EXPECT_EQ(empty, password_delegate->value());
listener->didBlurInputElement(ASCIIToUTF16("a"));
EXPECT_EQ(empty, username_delegate->value());
EXPECT_EQ(empty, password_delegate->value());
listener->didBlurInputElement(ASCIIToUTF16("ali"));
EXPECT_EQ(empty, username_delegate->value());
EXPECT_EQ(empty, password_delegate->value());
// Blur with 'alice' should allow password autofill.
listener->didBlurInputElement(ASCIIToUTF16("alice"));
EXPECT_EQ(empty, username_delegate->value());
EXPECT_EQ(password1_, password_delegate->value());
}
} // namespace
<|endoftext|> |
<commit_before>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 "types/typeops.h"
#include "compiler/expression/expr.h"
#include "compiler/expression/var_expr.h"
#include "compiler/expression/flwor_expr.h"
#include "compiler/expression/expr_visitor.h"
#include "zorbaserialization/serialization_engine.h"
#include "zorbaerrors/Assert.h"
namespace zorba
{
SERIALIZABLE_CLASS_VERSIONS(var_expr)
END_SERIALIZABLE_CLASS_VERSIONS(var_expr)
ulong var_expr::theVarCounter = 0; //used for giving var_exprs unique ids
Mutex var_expr::theVarCounterMutex;
/*******************************************************************************
********************************************************************************/
std::string var_expr::decode_var_kind(enum var_kind k)
{
switch (k)
{
case for_var: return "FOR"; break;
case let_var: return "LET"; break;
case win_var: return "WIN"; break;
case pos_var: return "POS"; break;
case wincond_out_var: return "WINCOND"; break;
case wincond_in_var: return "WINCOND IN"; break;
case wincond_out_pos_var: return "WINCOND POS"; break;
case wincond_in_pos_var: return "WINCOND IN POS"; break;
case count_var: return "CNT"; break;
case score_var: return "SCORE"; break;
case prolog_var: return "PROLOG"; break;
case local_var: return "LOCAL"; break;
case catch_var: return "CATCH"; break;
case copy_var: return "COPY"; break;
case groupby_var: return "GROUPBY"; break;
case non_groupby_var: return "NON-GROUPBY"; break;
case arg_var: return "ARG"; break;
default: return "???";
}
}
/*******************************************************************************
********************************************************************************/
var_expr::var_expr(
static_context* sctx,
const QueryLoc& loc,
var_kind k,
store::Item* name)
:
expr(sctx, loc, var_expr_kind),
theKind(k),
theName(name),
theDeclaredType(NULL),
theFlworClause(NULL),
theCopyClause(NULL)
{
theVarCounterMutex.lock();
theUniqueId = theVarCounter++;
theVarCounterMutex.unlock();
compute_scripting_kind();
setUnfoldable(ANNOTATION_TRUE_FIXED);
}
/*******************************************************************************
********************************************************************************/
void var_expr::serialize(::zorba::serialization::Archiver& ar)
{
serialize_baseclass(ar, (expr*)this);
SERIALIZE_ENUM(var_kind, theKind);
ar & theName;
ar & theDeclaredType;
//ar & theFlworClause;
//ar & theCopyClause;
//if(!ar.is_serializing_out())
//{
// theFlworClause = NULL;
// theCopyClause = NULL;
//}
ar & theUniqueId;
if(!ar.is_serializing_out())
{
theVarCounterMutex.lock();
if(theUniqueId >= theVarCounter)
theVarCounter = theUniqueId+1;
theVarCounterMutex.unlock();
}
}
/*******************************************************************************
********************************************************************************/
store::Item* var_expr::get_name() const
{
return theName.getp();
}
/*******************************************************************************
********************************************************************************/
xqtref_t var_expr::get_type() const
{
return theDeclaredType;
}
/*******************************************************************************
********************************************************************************/
void var_expr::set_type(xqtref_t t)
{
theDeclaredType = t;
}
/*******************************************************************************
********************************************************************************/
const var_expr* var_expr::get_pos_var() const
{
if (theKind == for_var)
{
return reinterpret_cast<for_clause*>(theFlworClause)->get_pos_var();
}
else
{
return NULL;
}
}
/*******************************************************************************
********************************************************************************/
expr* var_expr::get_domain_expr() const
{
if (theFlworClause)
{
if (theKind == for_var ||
theKind == let_var ||
theKind == win_var ||
theKind == wincond_in_var ||
theKind == wincond_out_var)
{
return reinterpret_cast<forletwin_clause*>(theFlworClause)->get_expr();
}
else if (theKind == groupby_var)
{
return reinterpret_cast<group_clause*>(theFlworClause)->
get_input_for_group_var(this);
}
else if (theKind == non_groupby_var)
{
return reinterpret_cast<group_clause*>(theFlworClause)->
get_input_for_nongroup_var(this);
}
}
else if (theCopyClause)
{
return theCopyClause->getExpr();
}
return NULL;
}
/*******************************************************************************
********************************************************************************/
forletwin_clause* var_expr::get_forletwin_clause() const
{
return dynamic_cast<forletwin_clause*>(theFlworClause);
}
/*******************************************************************************
********************************************************************************/
for_clause* var_expr::get_for_clause() const
{
return dynamic_cast<for_clause*>(theFlworClause);
}
/*******************************************************************************
********************************************************************************/
bool var_expr::is_context_item() const
{
return *theName->getLocalName() == ".";
}
/*******************************************************************************
********************************************************************************/
void var_expr::compute_scripting_kind()
{
theScriptingKind = SIMPLE_EXPR;
}
/*******************************************************************************
********************************************************************************/
expr::expr_t var_expr::clone(expr::substitution_t& subst) const
{
expr::subst_iter_t i = subst.find(this);
if (i == subst.end())
return const_cast<var_expr*>(this);
return i->second;
}
/*******************************************************************************
********************************************************************************/
void var_expr::accept(expr_visitor& v)
{
if (v.begin_visit(*this))
accept_children(v);
v.end_visit(*this);
}
/*******************************************************************************
********************************************************************************/
void global_binding::serialize(::zorba::serialization::Archiver& ar)
{
serialize_baseclass(ar, (std::pair<varref_t, expr_t>*)this);
ar & ext;
}
}
<commit_msg>Fix in plan serialization of var_expr.<commit_after>/*
* Copyright 2006-2008 The FLWOR Foundation.
*
* 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 "types/typeops.h"
#include "compiler/expression/expr.h"
#include "compiler/expression/var_expr.h"
#include "compiler/expression/flwor_expr.h"
#include "compiler/expression/expr_visitor.h"
#include "zorbaserialization/serialization_engine.h"
#include "zorbaerrors/Assert.h"
namespace zorba
{
SERIALIZABLE_CLASS_VERSIONS(var_expr)
END_SERIALIZABLE_CLASS_VERSIONS(var_expr)
ulong var_expr::theVarCounter = 0; //used for giving var_exprs unique ids
Mutex var_expr::theVarCounterMutex;
/*******************************************************************************
********************************************************************************/
std::string var_expr::decode_var_kind(enum var_kind k)
{
switch (k)
{
case for_var: return "FOR"; break;
case let_var: return "LET"; break;
case win_var: return "WIN"; break;
case pos_var: return "POS"; break;
case wincond_out_var: return "WINCOND"; break;
case wincond_in_var: return "WINCOND IN"; break;
case wincond_out_pos_var: return "WINCOND POS"; break;
case wincond_in_pos_var: return "WINCOND IN POS"; break;
case count_var: return "CNT"; break;
case score_var: return "SCORE"; break;
case prolog_var: return "PROLOG"; break;
case local_var: return "LOCAL"; break;
case catch_var: return "CATCH"; break;
case copy_var: return "COPY"; break;
case groupby_var: return "GROUPBY"; break;
case non_groupby_var: return "NON-GROUPBY"; break;
case arg_var: return "ARG"; break;
default: return "???";
}
}
/*******************************************************************************
********************************************************************************/
var_expr::var_expr(
static_context* sctx,
const QueryLoc& loc,
var_kind k,
store::Item* name)
:
expr(sctx, loc, var_expr_kind),
theKind(k),
theName(name),
theDeclaredType(NULL),
theFlworClause(NULL),
theCopyClause(NULL)
{
theVarCounterMutex.lock();
theUniqueId = theVarCounter++;
theVarCounterMutex.unlock();
compute_scripting_kind();
setUnfoldable(ANNOTATION_TRUE_FIXED);
}
/*******************************************************************************
********************************************************************************/
void var_expr::serialize(::zorba::serialization::Archiver& ar)
{
serialize_baseclass(ar, (expr*)this);
SERIALIZE_ENUM(var_kind, theKind);
ar & theName;
ar & theDeclaredType;
//ar & theFlworClause;
//ar & theCopyClause;
if(!ar.is_serializing_out())
{
theFlworClause = NULL;
theCopyClause = NULL;
}
ar & theUniqueId;
if(!ar.is_serializing_out())
{
theVarCounterMutex.lock();
if(theUniqueId >= theVarCounter)
theVarCounter = theUniqueId+1;
theVarCounterMutex.unlock();
}
}
/*******************************************************************************
********************************************************************************/
store::Item* var_expr::get_name() const
{
return theName.getp();
}
/*******************************************************************************
********************************************************************************/
xqtref_t var_expr::get_type() const
{
return theDeclaredType;
}
/*******************************************************************************
********************************************************************************/
void var_expr::set_type(xqtref_t t)
{
theDeclaredType = t;
}
/*******************************************************************************
********************************************************************************/
const var_expr* var_expr::get_pos_var() const
{
if (theKind == for_var)
{
return reinterpret_cast<for_clause*>(theFlworClause)->get_pos_var();
}
else
{
return NULL;
}
}
/*******************************************************************************
********************************************************************************/
expr* var_expr::get_domain_expr() const
{
if (theFlworClause)
{
if (theKind == for_var ||
theKind == let_var ||
theKind == win_var ||
theKind == wincond_in_var ||
theKind == wincond_out_var)
{
return reinterpret_cast<forletwin_clause*>(theFlworClause)->get_expr();
}
else if (theKind == groupby_var)
{
return reinterpret_cast<group_clause*>(theFlworClause)->
get_input_for_group_var(this);
}
else if (theKind == non_groupby_var)
{
return reinterpret_cast<group_clause*>(theFlworClause)->
get_input_for_nongroup_var(this);
}
}
else if (theCopyClause)
{
return theCopyClause->getExpr();
}
return NULL;
}
/*******************************************************************************
********************************************************************************/
forletwin_clause* var_expr::get_forletwin_clause() const
{
return dynamic_cast<forletwin_clause*>(theFlworClause);
}
/*******************************************************************************
********************************************************************************/
for_clause* var_expr::get_for_clause() const
{
return dynamic_cast<for_clause*>(theFlworClause);
}
/*******************************************************************************
********************************************************************************/
bool var_expr::is_context_item() const
{
return *theName->getLocalName() == ".";
}
/*******************************************************************************
********************************************************************************/
void var_expr::compute_scripting_kind()
{
theScriptingKind = SIMPLE_EXPR;
}
/*******************************************************************************
********************************************************************************/
expr::expr_t var_expr::clone(expr::substitution_t& subst) const
{
expr::subst_iter_t i = subst.find(this);
if (i == subst.end())
return const_cast<var_expr*>(this);
return i->second;
}
/*******************************************************************************
********************************************************************************/
void var_expr::accept(expr_visitor& v)
{
if (v.begin_visit(*this))
accept_children(v);
v.end_visit(*this);
}
/*******************************************************************************
********************************************************************************/
void global_binding::serialize(::zorba::serialization::Archiver& ar)
{
serialize_baseclass(ar, (std::pair<varref_t, expr_t>*)this);
ar & ext;
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: helpinterceptor.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: gt $ $Date: 2001-11-01 16:02:22 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include "helpinterceptor.hxx"
#include "helpdispatch.hxx"
#include "newhelp.hxx"
#include "sfxuno.hxx"
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_H_
#include <cppuhelper/interfacecontainer.h>
#endif
#include <vcl/window.hxx>
#include <limits.h>
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::util;
extern void AppendConfigToken_Impl( String& rURL, sal_Bool bQuestionMark ); // sfxhelp.cxx
// class HelpInterceptor_Impl --------------------------------------------
HelpInterceptor_Impl::HelpInterceptor_Impl() :
m_pHistory ( NULL ),
m_nCurPos ( 0 )
{
}
// -----------------------------------------------------------------------
HelpInterceptor_Impl::~HelpInterceptor_Impl()
{
for ( USHORT i = 0; m_pHistory && i < m_pHistory->Count(); ++i )
delete m_pHistory->GetObject(i);
delete m_pHistory;
if ( m_xIntercepted.is() )
m_xIntercepted->releaseDispatchProviderInterceptor( (XDispatchProviderInterceptor*)this );
}
// -----------------------------------------------------------------------
Reference< XController > HelpInterceptor_Impl::getController() const throw( RuntimeException )
{
Reference< XController > xRet;
if( m_pWindow )
{
Reference< XFrame > xFrame = m_pWindow->getTextFrame();
if( xFrame.is() )
xRet = xFrame->getController();
}
return xRet;
}
// -----------------------------------------------------------------------
void HelpInterceptor_Impl::addURL( const String& rURL )
{
if ( !m_pHistory )
m_pHistory = new HelpHistoryList_Impl;
ULONG nCount = m_pHistory->Count();
if ( nCount && m_nCurPos < ( nCount - 1 ) )
{
for ( ULONG i = nCount - 1; i > m_nCurPos; i-- )
delete m_pHistory->Remove(i);
}
m_aCurrentURL = rURL;
m_pHistory->Insert( new HelpHistoryEntry_Impl( rURL ), LIST_APPEND );
m_nCurPos = m_pHistory->Count() - 1;
if ( m_xListener.is() )
{
::com::sun::star::frame::FeatureStateEvent aEvent;
URL aURL;
aURL.Complete = rURL;
aEvent.FeatureURL = aURL;
aEvent.Source = (::com::sun::star::frame::XDispatch*)this;
m_xListener->statusChanged( aEvent );
}
m_pWindow->UpdateToolbox();
}
// -----------------------------------------------------------------------
void HelpInterceptor_Impl::LeavePage()
{
if( m_pHistory )
{
// get view position of _current_ URL
HelpHistoryEntry_Impl* pCurEntry = m_pHistory->GetObject( m_nCurPos );
if( pCurEntry )
{
try
{
Reference< XController > xContr( getController() );
if( xContr.is() )
pCurEntry->aViewData = xContr->getViewData();
}
catch( const Exception& ) {}
}
}
}
// -----------------------------------------------------------------------
void HelpInterceptor_Impl::setInterception( Reference< XFrame > xFrame )
{
m_xIntercepted = Reference< XDispatchProviderInterception>( xFrame, UNO_QUERY );
if ( m_xIntercepted.is() )
m_xIntercepted->registerDispatchProviderInterceptor( (XDispatchProviderInterceptor*)this );
}
// -----------------------------------------------------------------------
void HelpInterceptor_Impl::SetStartURL( const String& rURL )
{
DBG_ASSERT( !m_pHistory, "invalid history" );
if ( !m_pHistory )
{
m_pHistory = new HelpHistoryList_Impl;
m_pHistory->Insert( new HelpHistoryEntry_Impl( rURL ), ((ULONG)0x0) );
m_nCurPos = m_pHistory->Count() - 1;
m_pWindow->UpdateToolbox();
}
m_aCurrentURL = rURL;
}
// -----------------------------------------------------------------------
sal_Bool HelpInterceptor_Impl::HasHistoryPred() const
{
return m_pHistory && ( m_nCurPos > 0 );
}
// -----------------------------------------------------------------------
sal_Bool HelpInterceptor_Impl::HasHistorySucc() const
{
return m_pHistory && ( m_nCurPos < ( m_pHistory->Count() - 1 ) );
}
// -----------------------------------------------------------------------
// XDispatchProvider
Reference< XDispatch > SAL_CALL HelpInterceptor_Impl::queryDispatch(
const URL& aURL, const ::rtl::OUString& aTargetFrameName, sal_Int32 nSearchFlags )
throw( RuntimeException )
{
Reference< XDispatch > xResult;
if ( m_xSlaveDispatcher.is() )
xResult = m_xSlaveDispatcher->queryDispatch( aURL, aTargetFrameName, nSearchFlags );
INetURLObject aObj( aURL.Complete );
sal_Bool bHelpURL = ( aObj.GetProtocol() == INET_PROT_VND_SUN_STAR_HELP );
if ( bHelpURL )
{
DBG_ASSERT( xResult.is(), "invalid dispatch" );
HelpDispatch_Impl* pHelpDispatch = new HelpDispatch_Impl( *this, xResult );
xResult = Reference< XDispatch >( static_cast< ::cppu::OWeakObject* >(pHelpDispatch), UNO_QUERY );
}
return xResult;
}
// -----------------------------------------------------------------------
Sequence < Reference < XDispatch > > SAL_CALL HelpInterceptor_Impl::queryDispatches(
const Sequence< DispatchDescriptor >& aDescripts )
throw( RuntimeException )
{
Sequence< Reference< XDispatch > > aReturn( aDescripts.getLength() );
Reference< XDispatch >* pReturn = aReturn.getArray();
const DispatchDescriptor* pDescripts = aDescripts.getConstArray();
for ( sal_Int16 i = 0; i < aDescripts.getLength(); ++i, ++pReturn, ++pDescripts )
{
*pReturn = queryDispatch( pDescripts->FeatureURL, pDescripts->FrameName, pDescripts->SearchFlags );
}
return aReturn;
}
// -----------------------------------------------------------------------
// XDispatchProviderInterceptor
Reference< XDispatchProvider > SAL_CALL HelpInterceptor_Impl::getSlaveDispatchProvider()
throw( RuntimeException )
{
return m_xSlaveDispatcher;
}
// -----------------------------------------------------------------------
void SAL_CALL HelpInterceptor_Impl::setSlaveDispatchProvider( const Reference< XDispatchProvider >& xNewSlave )
throw( RuntimeException )
{
m_xSlaveDispatcher = xNewSlave;
}
// -----------------------------------------------------------------------
Reference< XDispatchProvider > SAL_CALL HelpInterceptor_Impl::getMasterDispatchProvider()
throw( RuntimeException )
{
return m_xMasterDispatcher;
}
// -----------------------------------------------------------------------
void SAL_CALL HelpInterceptor_Impl::setMasterDispatchProvider( const Reference< XDispatchProvider >& xNewMaster )
throw( RuntimeException )
{
m_xMasterDispatcher = xNewMaster;
}
// -----------------------------------------------------------------------
// XInterceptorInfo
Sequence< ::rtl::OUString > SAL_CALL HelpInterceptor_Impl::getInterceptedURLs()
throw( RuntimeException )
{
Sequence< ::rtl::OUString > aURLList( 1 );
aURLList[0] = DEFINE_CONST_UNICODE("vnd.sun.star.help://*");
return aURLList;
}
// -----------------------------------------------------------------------
// XDispatch
void SAL_CALL HelpInterceptor_Impl::dispatch(
const URL& aURL, const Sequence< ::com::sun::star::beans::PropertyValue >& aArgs ) throw( RuntimeException )
{
sal_Bool bBack = ( String( DEFINE_CONST_UNICODE(".uno:Backward") ) == String( aURL.Complete ) );
if ( bBack || String( DEFINE_CONST_UNICODE(".uno:Forward") ) == String( aURL.Complete ) )
{
if ( m_pHistory )
{
LeavePage(); // save actual position
ULONG nPos = ( bBack && m_nCurPos > 0 ) ? --m_nCurPos
: ( !bBack && m_nCurPos < m_pHistory->Count() - 1 )
? ++m_nCurPos
: ULONG_MAX;
if ( nPos < ULONG_MAX )
{
HelpHistoryEntry_Impl* pEntry = m_pHistory->GetObject( nPos );
if ( pEntry )
{
URL aURL;
aURL.Complete = pEntry->aURL;
Reference < XDispatch > xDisp = m_xSlaveDispatcher->queryDispatch( aURL, String(), 0 );
if ( xDisp.is() )
{
if ( m_pOpenListener && m_pWindow )
{
if ( !m_pWindow->IsWait() )
m_pWindow->EnterWait();
m_pOpenListener->AddListener( xDisp, aURL );
}
m_aCurrentURL = aURL.Complete;
Sequence< PropertyValue > aPropSeq( 1 );
aPropSeq[ 0 ].Name = ::rtl::OUString::createFromAscii( "ViewData" );
aPropSeq[ 0 ].Value = pEntry->aViewData;
xDisp->dispatch( aURL, aPropSeq );
}
}
}
m_pWindow->UpdateToolbox();
}
}
}
// -----------------------------------------------------------------------
void SAL_CALL HelpInterceptor_Impl::addStatusListener(
const Reference< XStatusListener >& xControl, const URL& aURL ) throw( RuntimeException )
{
DBG_ASSERT( !m_xListener.is(), "listener already exists" );
m_xListener = xControl;
}
// -----------------------------------------------------------------------
void SAL_CALL HelpInterceptor_Impl::removeStatusListener(
const Reference< XStatusListener >& xControl, const URL& aURL ) throw( RuntimeException )
{
m_xListener = 0;
}
// HelpListener_Impl -----------------------------------------------------
HelpListener_Impl::HelpListener_Impl( HelpInterceptor_Impl* pInter )
{
pInterceptor = pInter;
pInterceptor->addStatusListener( this, ::com::sun::star::util::URL() );
}
// -----------------------------------------------------------------------
void SAL_CALL HelpListener_Impl::statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event )
throw( ::com::sun::star::uno::RuntimeException )
{
INetURLObject aObj( Event.FeatureURL.Complete );
aFactory = aObj.GetHost();
aChangeLink.Call( this );
}
// -----------------------------------------------------------------------
void SAL_CALL HelpListener_Impl::disposing( const ::com::sun::star::lang::EventObject& obj )
throw( ::com::sun::star::uno::RuntimeException )
{
pInterceptor->removeStatusListener( this, ::com::sun::star::util::URL() );
pInterceptor = NULL;
}
<commit_msg>fix: #95228# use DispatchResultListener instead of StatusListener<commit_after>/*************************************************************************
*
* $RCSfile: helpinterceptor.cxx,v $
*
* $Revision: 1.16 $
*
* last change: $Author: pb $ $Date: 2001-11-30 14:34:24 $
*
* 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): _______________________________________
*
*
************************************************************************/
#include "helpinterceptor.hxx"
#include "helpdispatch.hxx"
#include "newhelp.hxx"
#include "sfxuno.hxx"
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _TOOLS_DEBUG_HXX
#include <tools/debug.hxx>
#endif
#ifndef _COM_SUN_STAR_BEANS_PROPERTYVALUE_HPP_
#include <com/sun/star/beans/PropertyValue.hpp>
#endif
#ifndef _COM_SUN_STAR_FRAME_XNOTIFYINGDISPATCH_HPP_
#include <com/sun/star/frame/XNotifyingDispatch.hpp>
#endif
#ifndef _CPPUHELPER_INTERFACECONTAINER_H_
#include <cppuhelper/interfacecontainer.h>
#endif
#include <vcl/window.hxx>
#include <limits.h>
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::frame;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::util;
extern void AppendConfigToken_Impl( String& rURL, sal_Bool bQuestionMark ); // sfxhelp.cxx
// class HelpInterceptor_Impl --------------------------------------------
HelpInterceptor_Impl::HelpInterceptor_Impl() :
m_pHistory ( NULL ),
m_nCurPos ( 0 )
{
}
// -----------------------------------------------------------------------
HelpInterceptor_Impl::~HelpInterceptor_Impl()
{
for ( USHORT i = 0; m_pHistory && i < m_pHistory->Count(); ++i )
delete m_pHistory->GetObject(i);
delete m_pHistory;
if ( m_xIntercepted.is() )
m_xIntercepted->releaseDispatchProviderInterceptor( (XDispatchProviderInterceptor*)this );
}
// -----------------------------------------------------------------------
Reference< XController > HelpInterceptor_Impl::getController() const throw( RuntimeException )
{
Reference< XController > xRet;
if( m_pWindow )
{
Reference< XFrame > xFrame = m_pWindow->getTextFrame();
if( xFrame.is() )
xRet = xFrame->getController();
}
return xRet;
}
// -----------------------------------------------------------------------
void HelpInterceptor_Impl::addURL( const String& rURL )
{
if ( !m_pHistory )
m_pHistory = new HelpHistoryList_Impl;
ULONG nCount = m_pHistory->Count();
if ( nCount && m_nCurPos < ( nCount - 1 ) )
{
for ( ULONG i = nCount - 1; i > m_nCurPos; i-- )
delete m_pHistory->Remove(i);
}
m_aCurrentURL = rURL;
m_pHistory->Insert( new HelpHistoryEntry_Impl( rURL ), LIST_APPEND );
m_nCurPos = m_pHistory->Count() - 1;
if ( m_xListener.is() )
{
::com::sun::star::frame::FeatureStateEvent aEvent;
URL aURL;
aURL.Complete = rURL;
aEvent.FeatureURL = aURL;
aEvent.Source = (::com::sun::star::frame::XDispatch*)this;
m_xListener->statusChanged( aEvent );
}
m_pWindow->UpdateToolbox();
}
// -----------------------------------------------------------------------
void HelpInterceptor_Impl::LeavePage()
{
if( m_pHistory )
{
// get view position of _current_ URL
HelpHistoryEntry_Impl* pCurEntry = m_pHistory->GetObject( m_nCurPos );
if( pCurEntry )
{
try
{
Reference< XController > xContr( getController() );
if( xContr.is() )
pCurEntry->aViewData = xContr->getViewData();
}
catch( const Exception& ) {}
}
}
}
// -----------------------------------------------------------------------
void HelpInterceptor_Impl::setInterception( Reference< XFrame > xFrame )
{
m_xIntercepted = Reference< XDispatchProviderInterception>( xFrame, UNO_QUERY );
if ( m_xIntercepted.is() )
m_xIntercepted->registerDispatchProviderInterceptor( (XDispatchProviderInterceptor*)this );
}
// -----------------------------------------------------------------------
void HelpInterceptor_Impl::SetStartURL( const String& rURL )
{
DBG_ASSERT( !m_pHistory, "invalid history" );
if ( !m_pHistory )
{
m_pHistory = new HelpHistoryList_Impl;
m_pHistory->Insert( new HelpHistoryEntry_Impl( rURL ), ((ULONG)0x0) );
m_nCurPos = m_pHistory->Count() - 1;
m_pWindow->UpdateToolbox();
}
m_aCurrentURL = rURL;
}
// -----------------------------------------------------------------------
sal_Bool HelpInterceptor_Impl::HasHistoryPred() const
{
return m_pHistory && ( m_nCurPos > 0 );
}
// -----------------------------------------------------------------------
sal_Bool HelpInterceptor_Impl::HasHistorySucc() const
{
return m_pHistory && ( m_nCurPos < ( m_pHistory->Count() - 1 ) );
}
// -----------------------------------------------------------------------
// XDispatchProvider
Reference< XDispatch > SAL_CALL HelpInterceptor_Impl::queryDispatch(
const URL& aURL, const ::rtl::OUString& aTargetFrameName, sal_Int32 nSearchFlags )
throw( RuntimeException )
{
Reference< XDispatch > xResult;
if ( m_xSlaveDispatcher.is() )
xResult = m_xSlaveDispatcher->queryDispatch( aURL, aTargetFrameName, nSearchFlags );
INetURLObject aObj( aURL.Complete );
sal_Bool bHelpURL = ( aObj.GetProtocol() == INET_PROT_VND_SUN_STAR_HELP );
if ( bHelpURL )
{
DBG_ASSERT( xResult.is(), "invalid dispatch" );
HelpDispatch_Impl* pHelpDispatch = new HelpDispatch_Impl( *this, xResult );
xResult = Reference< XDispatch >( static_cast< ::cppu::OWeakObject* >(pHelpDispatch), UNO_QUERY );
}
return xResult;
}
// -----------------------------------------------------------------------
Sequence < Reference < XDispatch > > SAL_CALL HelpInterceptor_Impl::queryDispatches(
const Sequence< DispatchDescriptor >& aDescripts )
throw( RuntimeException )
{
Sequence< Reference< XDispatch > > aReturn( aDescripts.getLength() );
Reference< XDispatch >* pReturn = aReturn.getArray();
const DispatchDescriptor* pDescripts = aDescripts.getConstArray();
for ( sal_Int16 i = 0; i < aDescripts.getLength(); ++i, ++pReturn, ++pDescripts )
{
*pReturn = queryDispatch( pDescripts->FeatureURL, pDescripts->FrameName, pDescripts->SearchFlags );
}
return aReturn;
}
// -----------------------------------------------------------------------
// XDispatchProviderInterceptor
Reference< XDispatchProvider > SAL_CALL HelpInterceptor_Impl::getSlaveDispatchProvider()
throw( RuntimeException )
{
return m_xSlaveDispatcher;
}
// -----------------------------------------------------------------------
void SAL_CALL HelpInterceptor_Impl::setSlaveDispatchProvider( const Reference< XDispatchProvider >& xNewSlave )
throw( RuntimeException )
{
m_xSlaveDispatcher = xNewSlave;
}
// -----------------------------------------------------------------------
Reference< XDispatchProvider > SAL_CALL HelpInterceptor_Impl::getMasterDispatchProvider()
throw( RuntimeException )
{
return m_xMasterDispatcher;
}
// -----------------------------------------------------------------------
void SAL_CALL HelpInterceptor_Impl::setMasterDispatchProvider( const Reference< XDispatchProvider >& xNewMaster )
throw( RuntimeException )
{
m_xMasterDispatcher = xNewMaster;
}
// -----------------------------------------------------------------------
// XInterceptorInfo
Sequence< ::rtl::OUString > SAL_CALL HelpInterceptor_Impl::getInterceptedURLs()
throw( RuntimeException )
{
Sequence< ::rtl::OUString > aURLList( 1 );
aURLList[0] = DEFINE_CONST_UNICODE("vnd.sun.star.help://*");
return aURLList;
}
// -----------------------------------------------------------------------
// XDispatch
void SAL_CALL HelpInterceptor_Impl::dispatch(
const URL& aURL, const Sequence< ::com::sun::star::beans::PropertyValue >& aArgs ) throw( RuntimeException )
{
sal_Bool bBack = ( String( DEFINE_CONST_UNICODE(".uno:Backward") ) == String( aURL.Complete ) );
if ( bBack || String( DEFINE_CONST_UNICODE(".uno:Forward") ) == String( aURL.Complete ) )
{
if ( m_pHistory )
{
LeavePage(); // save actual position
ULONG nPos = ( bBack && m_nCurPos > 0 ) ? --m_nCurPos
: ( !bBack && m_nCurPos < m_pHistory->Count() - 1 )
? ++m_nCurPos
: ULONG_MAX;
if ( nPos < ULONG_MAX )
{
HelpHistoryEntry_Impl* pEntry = m_pHistory->GetObject( nPos );
if ( pEntry )
{
URL aURL;
aURL.Complete = pEntry->aURL;
Reference < XDispatch > xDisp = m_xSlaveDispatcher->queryDispatch( aURL, String(), 0 );
if ( xDisp.is() )
{
if ( m_pWindow && !m_pWindow->IsWait() )
m_pWindow->EnterWait();
m_aCurrentURL = aURL.Complete;
Sequence< PropertyValue > aPropSeq( 1 );
aPropSeq[ 0 ].Name = ::rtl::OUString::createFromAscii( "ViewData" );
aPropSeq[ 0 ].Value = pEntry->aViewData;
Reference < XNotifyingDispatch > xNotifyingDisp( xDisp, UNO_QUERY );
if ( xNotifyingDisp.is() )
{
OpenStatusListener_Impl* pListener = (OpenStatusListener_Impl*)m_pWindow->getOpenListener().get();
DBG_ASSERT( pListener, "invalid XDispatchResultListener" );
pListener->SetURL( aURL.Complete );
xNotifyingDisp->dispatchWithNotification( aURL, aPropSeq, pListener );
}
}
}
}
m_pWindow->UpdateToolbox();
}
}
}
// -----------------------------------------------------------------------
void SAL_CALL HelpInterceptor_Impl::addStatusListener(
const Reference< XStatusListener >& xControl, const URL& aURL ) throw( RuntimeException )
{
DBG_ASSERT( !m_xListener.is(), "listener already exists" );
m_xListener = xControl;
}
// -----------------------------------------------------------------------
void SAL_CALL HelpInterceptor_Impl::removeStatusListener(
const Reference< XStatusListener >& xControl, const URL& aURL ) throw( RuntimeException )
{
m_xListener = 0;
}
// HelpListener_Impl -----------------------------------------------------
HelpListener_Impl::HelpListener_Impl( HelpInterceptor_Impl* pInter )
{
pInterceptor = pInter;
pInterceptor->addStatusListener( this, ::com::sun::star::util::URL() );
}
// -----------------------------------------------------------------------
void SAL_CALL HelpListener_Impl::statusChanged( const ::com::sun::star::frame::FeatureStateEvent& Event )
throw( ::com::sun::star::uno::RuntimeException )
{
INetURLObject aObj( Event.FeatureURL.Complete );
aFactory = aObj.GetHost();
aChangeLink.Call( this );
}
// -----------------------------------------------------------------------
void SAL_CALL HelpListener_Impl::disposing( const ::com::sun::star::lang::EventObject& obj )
throw( ::com::sun::star::uno::RuntimeException )
{
pInterceptor->removeStatusListener( this, ::com::sun::star::util::URL() );
pInterceptor = NULL;
}
<|endoftext|> |
<commit_before>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* ADIOS1Reader.cpp
*
* Created on: Feb 27, 2017
* Author: Norbert Podhorszki [email protected]
*/
#include "ADIOS1Reader.h"
#include "ADIOS1Reader.tcc"
#include <adios_error.h>
#include "adios2/helper/adiosFunctions.h" // CSVToVector
namespace adios2
{
ADIOS1Reader::ADIOS1Reader(IO &io, const std::string &name, const Mode openMode,
MPI_Comm mpiComm)
: Engine("ADIOS1Reader", io, name, openMode, mpiComm),
m_ADIOS1(name, mpiComm, io.m_DebugMode)
{
m_EndMessage = " in call to IO Open ADIOS1Reader " + m_Name + "\n";
Init();
m_ADIOS1.Open(); // adios_read_init_method(m_ReadMethod, mpiComm, "");
m_ADIOS1.GenerateVariables(io);
}
ADIOS1Reader::~ADIOS1Reader()
{
/* m_ADIOS1 deconstructor does close and finalize */
}
AdvanceStatus ADIOS1Reader::BeginStep(AdvanceMode mode, const float timeout_sec)
{
return m_ADIOS1.AdvanceStep(mode, timeout_sec);
}
// PRIVATE
#define declare_type(T) \
void ADIOS1Reader::DoGetSync(Variable<T> &variable, T *values) \
{ \
m_ADIOS1.ScheduleReadCommon( \
variable.m_Name, variable.m_Start, variable.m_Count, \
variable.GetAvailableStepsStart(), \
variable.GetAvailableStepsStart(), variable.m_ReadAsLocalValue, \
variable.m_ReadAsJoined, (void *)values); \
m_ADIOS1.PerformReads(); \
} \
void ADIOS1Reader::DoGetDeferred(Variable<T> &variable, T *values) \
{ \
m_ADIOS1.ScheduleReadCommon( \
variable.m_Name, variable.m_Start, variable.m_Count, \
variable.GetAvailableStepsStart(), \
variable.GetAvailableStepsStart(), variable.m_ReadAsLocalValue, \
variable.m_ReadAsJoined, (void *)values); \
}
ADIOS2_FOREACH_TYPE_1ARG(declare_type)
#undef declare_type
void ADIOS1Reader::PerformGets() { m_ADIOS1.PerformReads(); }
void ADIOS1Reader::EndStep() { m_ADIOS1.ReleaseStep(); }
void ADIOS1Reader::Close(const int transportIndex) { m_ADIOS1.Close(); }
// PRIVATE
void ADIOS1Reader::Init()
{
if (m_DebugMode)
{
if (m_OpenMode != Mode::Read)
{
throw std::invalid_argument(
"ERROR: ADIOS1Reader only supports OpenMode::r (read) access "
"mode " +
m_EndMessage);
}
}
InitParameters();
InitTransports();
}
void ADIOS1Reader::InitParameters()
{
m_ADIOS1.InitParameters(m_IO.m_Parameters);
}
void ADIOS1Reader::InitTransports()
{
m_ADIOS1.InitTransports(m_IO.m_TransportsParameters);
}
} // end namespace
<commit_msg>Bp1read (#24)<commit_after>/*
* Distributed under the OSI-approved Apache License, Version 2.0. See
* accompanying file Copyright.txt for details.
*
* ADIOS1Reader.cpp
*
* Created on: Feb 27, 2017
* Author: Norbert Podhorszki [email protected]
*/
#include "ADIOS1Reader.h"
#include "ADIOS1Reader.tcc"
#include <adios_error.h>
#include "adios2/helper/adiosFunctions.h" // CSVToVector
namespace adios2
{
ADIOS1Reader::ADIOS1Reader(IO &io, const std::string &name, const Mode openMode,
MPI_Comm mpiComm)
: Engine("ADIOS1Reader", io, name, openMode, mpiComm),
m_ADIOS1(name, mpiComm, io.m_DebugMode)
{
m_EndMessage = " in call to IO Open ADIOS1Reader " + m_Name + "\n";
Init();
m_ADIOS1.Open(); // adios_read_init_method(m_ReadMethod, mpiComm, "");
m_ADIOS1.GenerateVariables(io);
}
ADIOS1Reader::~ADIOS1Reader()
{
/* m_ADIOS1 deconstructor does close and finalize */
}
AdvanceStatus ADIOS1Reader::BeginStep(AdvanceMode mode, const float timeout_sec)
{
return m_ADIOS1.AdvanceStep(mode, timeout_sec);
}
// PRIVATE
#define declare_type(T) \
void ADIOS1Reader::DoGetSync(Variable<T> &variable, T *values) \
{ \
m_ADIOS1.ScheduleReadCommon(variable.m_Name, variable.m_Start, \
variable.m_Count, variable.m_StepStart, \
variable.m_StepCount, \
variable.m_ReadAsLocalValue, \
variable.m_ReadAsJoined, (void *)values); \
m_ADIOS1.PerformReads(); \
} \
void ADIOS1Reader::DoGetDeferred(Variable<T> &variable, T *values) \
{ \
m_ADIOS1.ScheduleReadCommon(variable.m_Name, variable.m_Start, \
variable.m_Count, variable.m_StepStart, \
variable.m_StepCount, \
variable.m_ReadAsLocalValue, \
variable.m_ReadAsJoined, (void *)values); \
}
ADIOS2_FOREACH_TYPE_1ARG(declare_type)
#undef declare_type
void ADIOS1Reader::PerformGets() { m_ADIOS1.PerformReads(); }
void ADIOS1Reader::EndStep() { m_ADIOS1.ReleaseStep(); }
void ADIOS1Reader::Close(const int transportIndex) { m_ADIOS1.Close(); }
// PRIVATE
void ADIOS1Reader::Init()
{
if (m_DebugMode)
{
if (m_OpenMode != Mode::Read)
{
throw std::invalid_argument(
"ERROR: ADIOS1Reader only supports OpenMode::r (read) access "
"mode " +
m_EndMessage);
}
}
InitParameters();
InitTransports();
}
void ADIOS1Reader::InitParameters()
{
m_ADIOS1.InitParameters(m_IO.m_Parameters);
}
void ADIOS1Reader::InitTransports()
{
m_ADIOS1.InitTransports(m_IO.m_TransportsParameters);
}
} // end namespace
<|endoftext|> |
<commit_before>// ***************************************************************************
// TcpSocket_p.cpp (c) 2011 Derek Barnett
// Marth Lab, Department of Biology, Boston College
// ---------------------------------------------------------------------------
// Last modified: 5 January 2012 (DB)
// ---------------------------------------------------------------------------
// Provides basic TCP I/O interface
// ***************************************************************************
#include "api/internal/io/TcpSocket_p.h"
#include "api/internal/io/ByteArray_p.h"
#include "api/internal/io/TcpSocketEngine_p.h"
using namespace BamTools;
using namespace BamTools::Internal;
#include <algorithm>
#include <climits>
#include <cstddef>
#include <sstream>
#include <vector>
// ------------------------------------
// static utility methods & constants
// ------------------------------------
namespace BamTools {
namespace Internal {
// constants
static const std::size_t DEFAULT_BUFFER_SIZE = 0x10000;
static const int64_t DEFAULT_BUFFER_SIZE64 = DEFAULT_BUFFER_SIZE;
} // namespace Internal
} // namespace BamTools
// --------------------------
// TcpSocket implementation
// --------------------------
TcpSocket::TcpSocket()
: m_mode(IBamIODevice::NotOpen)
// , m_localPort(0)
, m_remotePort(0)
, m_engine(0)
, m_cachedSocketDescriptor(-1)
, m_readBuffer(DEFAULT_BUFFER_SIZE)
, m_error(TcpSocket::NoError)
, m_state(TcpSocket::UnconnectedState)
{}
TcpSocket::~TcpSocket()
{
if (m_state == TcpSocket::ConnectedState) DisconnectFromHost();
}
std::size_t TcpSocket::BufferBytesAvailable() const
{
return m_readBuffer.Size();
}
bool TcpSocket::CanReadLine() const
{
return m_readBuffer.CanReadLine();
}
void TcpSocket::ClearBuffer()
{
m_readBuffer.Clear();
}
bool TcpSocket::ConnectImpl(const HostInfo& hostInfo, const std::string& port,
IBamIODevice::OpenMode mode)
{
// skip if we're already connected
if (m_state == TcpSocket::ConnectedState) {
m_error = TcpSocket::SocketResourceError;
m_errorString = "socket already connected";
return false;
}
// reset socket state
m_hostName = hostInfo.HostName();
m_mode = mode;
m_state = TcpSocket::UnconnectedState;
m_error = TcpSocket::NoError;
// m_localPort = 0;
m_remotePort = 0;
// m_localAddress.Clear();
m_remoteAddress.Clear();
m_readBuffer.Clear();
// fetch candidate addresses for requested host
std::vector<HostAddress> addresses = hostInfo.Addresses();
if (addresses.empty()) {
m_error = TcpSocket::HostNotFoundError;
m_errorString = "no IP addresses found for host";
return false;
}
// convert port string to integer
std::stringstream ss(port);
uint16_t portNumber(0);
ss >> portNumber;
// iterate through adddresses
std::vector<HostAddress>::const_iterator addrIter = addresses.begin();
std::vector<HostAddress>::const_iterator addrEnd = addresses.end();
for (; addrIter != addrEnd; ++addrIter) {
const HostAddress& addr = (*addrIter);
// try to initialize socket engine with this address
if (!InitializeSocketEngine(addr.GetProtocol())) {
// failure to initialize is OK here
// we'll just try the next available address
continue;
}
// attempt actual connection
if (m_engine->Connect(addr, portNumber)) {
// if connection successful, update our state & return true
m_mode = mode;
// m_localAddress = m_engine->GetLocalAddress();
// m_localPort = m_engine->GetLocalPort();
m_remoteAddress = m_engine->GetRemoteAddress();
m_remotePort = m_engine->GetRemotePort();
m_cachedSocketDescriptor = m_engine->GetSocketDescriptor();
m_state = TcpSocket::ConnectedState;
return true;
}
}
// if we get here, no connection could be made
m_error = TcpSocket::HostNotFoundError;
m_errorString = "could not connect to any host addresses";
return false;
}
bool TcpSocket::ConnectToHost(const std::string& hostName, uint16_t port,
IBamIODevice::OpenMode mode)
{
std::stringstream ss;
ss << port;
return ConnectToHost(hostName, ss.str(), mode);
}
bool TcpSocket::ConnectToHost(const std::string& hostName, const std::string& port,
IBamIODevice::OpenMode mode)
{
// create new address object with requested host name
HostAddress hostAddress;
hostAddress.SetAddress(hostName);
HostInfo info;
// if host name was IP address ("x.x.x.x" or IPv6 format)
// otherwise host name was 'plain-text' ("www.foo.bar")
// we need to look up IP address(es)
if (hostAddress.HasIPAddress())
info.SetAddresses(std::vector<HostAddress>(1, hostAddress));
else
info = HostInfo::Lookup(hostName, port);
// attempt connection on requested port
return ConnectImpl(info, port, mode);
}
void TcpSocket::DisconnectFromHost()
{
// close socket engine & delete
if (m_state == TcpSocket::ConnectedState) ResetSocketEngine();
// reset connection state
// m_localPort = 0;
m_remotePort = 0;
// m_localAddress.Clear();
m_remoteAddress.Clear();
m_hostName.clear();
m_cachedSocketDescriptor = -1;
// for future, make sure there's outgoing data that needs to be flushed
m_readBuffer.Clear();
}
TcpSocket::SocketError TcpSocket::GetError() const
{
return m_error;
}
std::string TcpSocket::GetErrorString() const
{
return m_errorString;
}
std::string TcpSocket::GetHostName() const
{
return m_hostName;
}
//HostAddress TcpSocket::GetLocalAddress() const {
// return m_localAddress;
//}
//uint16_t TcpSocket::GetLocalPort() const {
// return m_localPort;
//}
HostAddress TcpSocket::GetRemoteAddress() const
{
return m_remoteAddress;
}
uint16_t TcpSocket::GetRemotePort() const
{
return m_remotePort;
}
TcpSocket::SocketState TcpSocket::GetState() const
{
return m_state;
}
bool TcpSocket::InitializeSocketEngine(HostAddress::NetworkProtocol protocol)
{
ResetSocketEngine();
m_engine = new TcpSocketEngine;
return m_engine->Initialize(protocol);
}
bool TcpSocket::IsConnected() const
{
if (m_engine == 0) return false;
return (m_engine->IsValid() && (m_state == TcpSocket::ConnectedState));
}
// may be read in a look until desired data amount has been read
// returns: number of bytes read, or -1 if error
int64_t TcpSocket::Read(char* data, const unsigned int numBytes)
{
// if we have data in buffer, just return it
if (!m_readBuffer.IsEmpty()) {
const std::size_t bytesRead = m_readBuffer.Read(data, numBytes);
return static_cast<int64_t>(bytesRead);
}
// otherwise, we'll need to fetch data from socket
// first make sure we have a valid socket engine
if (m_engine == 0) {
// TODO: set error string/state?
return -1;
}
// fetch data from socket, return 0 for success, -1 for failure
// since this should be called in a loop,
// we'll pull the actual bytes from the buffer on next iteration
const int64_t socketBytesRead = ReadFromSocket();
if (socketBytesRead < 0) {
// TODO: set error string/state ?
return -1;
}
// we should have data now in buffer, try to fetch requested amount
// if nothing in buffer, we will return 0 bytes read (signals EOF reached)
const std::size_t numBytesRead = m_readBuffer.Read(data, numBytes);
return static_cast<int64_t>(numBytesRead);
}
int64_t TcpSocket::ReadFromSocket()
{
// check for any socket engine errors
if (!m_engine->IsValid()) {
m_errorString = "TcpSocket::ReadFromSocket - socket disconnected";
ResetSocketEngine();
return -1;
}
// wait for ready read
bool timedOut;
const bool isReadyRead = m_engine->WaitForRead(5000, &timedOut);
// if not ready
if (!isReadyRead) {
// if we simply timed out
if (timedOut) {
// TODO: get add'l error info from engine ?
m_errorString = "TcpSocket::ReadFromSocket - timed out waiting for ready read";
}
// otherwise, there was some other error
else {
// TODO: get add'l error info from engine ?
m_errorString =
"TcpSocket::ReadFromSocket - encountered error while waiting for ready read";
}
// return failure
return -1;
}
// get number of bytes available from socket
const int64_t bytesToRead = m_engine->NumBytesAvailable();
if (bytesToRead < 0) {
// TODO: get add'l error info from engine ?
m_errorString =
"TcpSocket::ReadFromSocket - encountered error while determining numBytesAvailable";
return -1;
}
// make space in buffer & read from socket
char* buffer = m_readBuffer.Reserve(bytesToRead);
const int64_t numBytesRead = m_engine->Read(buffer, bytesToRead);
if (numBytesRead == -1) {
// TODO: get add'l error info from engine ?
m_errorString = "TcpSocket::ReadFromSocket - encountered error while reading bytes";
}
// return number of bytes actually read
return numBytesRead;
}
std::string TcpSocket::ReadLine(int64_t max)
{
// prep result byte buffer
ByteArray result;
std::size_t bufferMax =
((max > static_cast<int64_t>(UINT_MAX)) ? UINT_MAX : static_cast<std::size_t>(max));
result.Resize(bufferMax);
// read data
int64_t readBytes(0);
if (result.Size() == 0) {
if (bufferMax == 0) bufferMax = UINT_MAX;
result.Resize(1);
int64_t readResult;
do {
result.Resize(
static_cast<std::size_t>(std::min(bufferMax, result.Size() + DEFAULT_BUFFER_SIZE)));
readResult = ReadLine(result.Data() + readBytes, result.Size() - readBytes);
if (readResult > 0 || readBytes == 0) readBytes += readResult;
} while (readResult == DEFAULT_BUFFER_SIZE64 &&
result[static_cast<std::size_t>(readBytes - 1)] != '\n');
} else
readBytes = ReadLine(result.Data(), result.Size());
// clean up byte buffer
if (readBytes <= 0)
result.Clear();
else
result.Resize(static_cast<std::size_t>(readBytes));
// return byte buffer as string
return std::string(result.ConstData(), result.Size());
}
int64_t TcpSocket::ReadLine(char* dest, std::size_t max)
{
// wait for buffer to contain line contents
if (!WaitForReadLine()) {
m_errorString = "TcpSocket::ReadLine - error waiting for read line";
return -1;
}
// leave room for null term
if (max < 2) return -1;
--max;
// read from buffer, handle newlines
int64_t readSoFar = m_readBuffer.ReadLine(dest, max);
if (readSoFar && dest[readSoFar - 1] == '\n') {
// adjust for windows-style '\r\n'
if (readSoFar > 1 && dest[readSoFar - 2] == '\r') {
--readSoFar;
dest[readSoFar - 1] = '\n';
}
}
// null terminate & return number of bytes read
dest[readSoFar] = '\0';
return readSoFar;
}
void TcpSocket::ResetSocketEngine()
{
// shut down socket engine
if (m_engine) {
m_engine->Close();
delete m_engine;
m_engine = 0;
}
// reset our state & cached socket handle
m_state = TcpSocket::UnconnectedState;
m_cachedSocketDescriptor = -1;
}
bool TcpSocket::WaitForReadLine()
{
// wait until we can read a line (will return immediately if already capable)
while (!CanReadLine()) {
if (!ReadFromSocket()) return false;
}
// if we get here, success
return true;
}
int64_t TcpSocket::Write(const char* data, const unsigned int numBytes)
{
// single-shot attempt at write (not buffered, just try to shove the data through socket)
// this method purely exists to send 'small' HTTP requests/FTP commands from client to server
// wait for our socket to be write-able
bool timedOut;
const bool isReadyWrite = m_engine->WaitForWrite(3000, &timedOut);
// if ready, return number of bytes written
if (isReadyWrite) return m_engine->Write(data, numBytes);
// otherwise, socket not ready for writing
// set error string depending on reason & return failure
if (!timedOut) {
// TODO: get add'l error info from engine ??
m_errorString = "TcpSocket::Write - timed out waiting for ready-write";
} else {
// TODO: get add'l error info from engine ??
m_errorString = "TcpSocket::Write - error encountered while waiting for ready-write";
}
return -1;
}
<commit_msg>Fix Windows `std::min` idiosyncrasy<commit_after>// ***************************************************************************
// TcpSocket_p.cpp (c) 2011 Derek Barnett
// Marth Lab, Department of Biology, Boston College
// ---------------------------------------------------------------------------
// Last modified: 5 January 2012 (DB)
// ---------------------------------------------------------------------------
// Provides basic TCP I/O interface
// ***************************************************************************
#include "api/internal/io/TcpSocket_p.h"
#include "api/internal/io/ByteArray_p.h"
#include "api/internal/io/TcpSocketEngine_p.h"
using namespace BamTools;
using namespace BamTools::Internal;
#include <algorithm>
#include <climits>
#include <cstddef>
#include <sstream>
#include <vector>
// Windows is brain-damaged and pollutes the entire global namespace with
// its min() macro, which in turn causes MSVC to go haywire on std::min.
#undef min
// ------------------------------------
// static utility methods & constants
// ------------------------------------
namespace BamTools {
namespace Internal {
// constants
static const std::size_t DEFAULT_BUFFER_SIZE = 0x10000;
static const int64_t DEFAULT_BUFFER_SIZE64 = DEFAULT_BUFFER_SIZE;
} // namespace Internal
} // namespace BamTools
// --------------------------
// TcpSocket implementation
// --------------------------
TcpSocket::TcpSocket()
: m_mode(IBamIODevice::NotOpen)
// , m_localPort(0)
, m_remotePort(0)
, m_engine(0)
, m_cachedSocketDescriptor(-1)
, m_readBuffer(DEFAULT_BUFFER_SIZE)
, m_error(TcpSocket::NoError)
, m_state(TcpSocket::UnconnectedState)
{}
TcpSocket::~TcpSocket()
{
if (m_state == TcpSocket::ConnectedState) DisconnectFromHost();
}
std::size_t TcpSocket::BufferBytesAvailable() const
{
return m_readBuffer.Size();
}
bool TcpSocket::CanReadLine() const
{
return m_readBuffer.CanReadLine();
}
void TcpSocket::ClearBuffer()
{
m_readBuffer.Clear();
}
bool TcpSocket::ConnectImpl(const HostInfo& hostInfo, const std::string& port,
IBamIODevice::OpenMode mode)
{
// skip if we're already connected
if (m_state == TcpSocket::ConnectedState) {
m_error = TcpSocket::SocketResourceError;
m_errorString = "socket already connected";
return false;
}
// reset socket state
m_hostName = hostInfo.HostName();
m_mode = mode;
m_state = TcpSocket::UnconnectedState;
m_error = TcpSocket::NoError;
// m_localPort = 0;
m_remotePort = 0;
// m_localAddress.Clear();
m_remoteAddress.Clear();
m_readBuffer.Clear();
// fetch candidate addresses for requested host
std::vector<HostAddress> addresses = hostInfo.Addresses();
if (addresses.empty()) {
m_error = TcpSocket::HostNotFoundError;
m_errorString = "no IP addresses found for host";
return false;
}
// convert port string to integer
std::stringstream ss(port);
uint16_t portNumber(0);
ss >> portNumber;
// iterate through adddresses
std::vector<HostAddress>::const_iterator addrIter = addresses.begin();
std::vector<HostAddress>::const_iterator addrEnd = addresses.end();
for (; addrIter != addrEnd; ++addrIter) {
const HostAddress& addr = (*addrIter);
// try to initialize socket engine with this address
if (!InitializeSocketEngine(addr.GetProtocol())) {
// failure to initialize is OK here
// we'll just try the next available address
continue;
}
// attempt actual connection
if (m_engine->Connect(addr, portNumber)) {
// if connection successful, update our state & return true
m_mode = mode;
// m_localAddress = m_engine->GetLocalAddress();
// m_localPort = m_engine->GetLocalPort();
m_remoteAddress = m_engine->GetRemoteAddress();
m_remotePort = m_engine->GetRemotePort();
m_cachedSocketDescriptor = m_engine->GetSocketDescriptor();
m_state = TcpSocket::ConnectedState;
return true;
}
}
// if we get here, no connection could be made
m_error = TcpSocket::HostNotFoundError;
m_errorString = "could not connect to any host addresses";
return false;
}
bool TcpSocket::ConnectToHost(const std::string& hostName, uint16_t port,
IBamIODevice::OpenMode mode)
{
std::stringstream ss;
ss << port;
return ConnectToHost(hostName, ss.str(), mode);
}
bool TcpSocket::ConnectToHost(const std::string& hostName, const std::string& port,
IBamIODevice::OpenMode mode)
{
// create new address object with requested host name
HostAddress hostAddress;
hostAddress.SetAddress(hostName);
HostInfo info;
// if host name was IP address ("x.x.x.x" or IPv6 format)
// otherwise host name was 'plain-text' ("www.foo.bar")
// we need to look up IP address(es)
if (hostAddress.HasIPAddress())
info.SetAddresses(std::vector<HostAddress>(1, hostAddress));
else
info = HostInfo::Lookup(hostName, port);
// attempt connection on requested port
return ConnectImpl(info, port, mode);
}
void TcpSocket::DisconnectFromHost()
{
// close socket engine & delete
if (m_state == TcpSocket::ConnectedState) ResetSocketEngine();
// reset connection state
// m_localPort = 0;
m_remotePort = 0;
// m_localAddress.Clear();
m_remoteAddress.Clear();
m_hostName.clear();
m_cachedSocketDescriptor = -1;
// for future, make sure there's outgoing data that needs to be flushed
m_readBuffer.Clear();
}
TcpSocket::SocketError TcpSocket::GetError() const
{
return m_error;
}
std::string TcpSocket::GetErrorString() const
{
return m_errorString;
}
std::string TcpSocket::GetHostName() const
{
return m_hostName;
}
//HostAddress TcpSocket::GetLocalAddress() const {
// return m_localAddress;
//}
//uint16_t TcpSocket::GetLocalPort() const {
// return m_localPort;
//}
HostAddress TcpSocket::GetRemoteAddress() const
{
return m_remoteAddress;
}
uint16_t TcpSocket::GetRemotePort() const
{
return m_remotePort;
}
TcpSocket::SocketState TcpSocket::GetState() const
{
return m_state;
}
bool TcpSocket::InitializeSocketEngine(HostAddress::NetworkProtocol protocol)
{
ResetSocketEngine();
m_engine = new TcpSocketEngine;
return m_engine->Initialize(protocol);
}
bool TcpSocket::IsConnected() const
{
if (m_engine == 0) return false;
return (m_engine->IsValid() && (m_state == TcpSocket::ConnectedState));
}
// may be read in a look until desired data amount has been read
// returns: number of bytes read, or -1 if error
int64_t TcpSocket::Read(char* data, const unsigned int numBytes)
{
// if we have data in buffer, just return it
if (!m_readBuffer.IsEmpty()) {
const std::size_t bytesRead = m_readBuffer.Read(data, numBytes);
return static_cast<int64_t>(bytesRead);
}
// otherwise, we'll need to fetch data from socket
// first make sure we have a valid socket engine
if (m_engine == 0) {
// TODO: set error string/state?
return -1;
}
// fetch data from socket, return 0 for success, -1 for failure
// since this should be called in a loop,
// we'll pull the actual bytes from the buffer on next iteration
const int64_t socketBytesRead = ReadFromSocket();
if (socketBytesRead < 0) {
// TODO: set error string/state ?
return -1;
}
// we should have data now in buffer, try to fetch requested amount
// if nothing in buffer, we will return 0 bytes read (signals EOF reached)
const std::size_t numBytesRead = m_readBuffer.Read(data, numBytes);
return static_cast<int64_t>(numBytesRead);
}
int64_t TcpSocket::ReadFromSocket()
{
// check for any socket engine errors
if (!m_engine->IsValid()) {
m_errorString = "TcpSocket::ReadFromSocket - socket disconnected";
ResetSocketEngine();
return -1;
}
// wait for ready read
bool timedOut;
const bool isReadyRead = m_engine->WaitForRead(5000, &timedOut);
// if not ready
if (!isReadyRead) {
// if we simply timed out
if (timedOut) {
// TODO: get add'l error info from engine ?
m_errorString = "TcpSocket::ReadFromSocket - timed out waiting for ready read";
}
// otherwise, there was some other error
else {
// TODO: get add'l error info from engine ?
m_errorString =
"TcpSocket::ReadFromSocket - encountered error while waiting for ready read";
}
// return failure
return -1;
}
// get number of bytes available from socket
const int64_t bytesToRead = m_engine->NumBytesAvailable();
if (bytesToRead < 0) {
// TODO: get add'l error info from engine ?
m_errorString =
"TcpSocket::ReadFromSocket - encountered error while determining numBytesAvailable";
return -1;
}
// make space in buffer & read from socket
char* buffer = m_readBuffer.Reserve(bytesToRead);
const int64_t numBytesRead = m_engine->Read(buffer, bytesToRead);
if (numBytesRead == -1) {
// TODO: get add'l error info from engine ?
m_errorString = "TcpSocket::ReadFromSocket - encountered error while reading bytes";
}
// return number of bytes actually read
return numBytesRead;
}
std::string TcpSocket::ReadLine(int64_t max)
{
// prep result byte buffer
ByteArray result;
std::size_t bufferMax =
((max > static_cast<int64_t>(UINT_MAX)) ? UINT_MAX : static_cast<std::size_t>(max));
result.Resize(bufferMax);
// read data
int64_t readBytes(0);
if (result.Size() == 0) {
if (bufferMax == 0) bufferMax = UINT_MAX;
result.Resize(1);
int64_t readResult;
do {
result.Resize(
static_cast<std::size_t>(std::min(bufferMax, result.Size() + DEFAULT_BUFFER_SIZE)));
readResult = ReadLine(result.Data() + readBytes, result.Size() - readBytes);
if (readResult > 0 || readBytes == 0) readBytes += readResult;
} while (readResult == DEFAULT_BUFFER_SIZE64 &&
result[static_cast<std::size_t>(readBytes - 1)] != '\n');
} else
readBytes = ReadLine(result.Data(), result.Size());
// clean up byte buffer
if (readBytes <= 0)
result.Clear();
else
result.Resize(static_cast<std::size_t>(readBytes));
// return byte buffer as string
return std::string(result.ConstData(), result.Size());
}
int64_t TcpSocket::ReadLine(char* dest, std::size_t max)
{
// wait for buffer to contain line contents
if (!WaitForReadLine()) {
m_errorString = "TcpSocket::ReadLine - error waiting for read line";
return -1;
}
// leave room for null term
if (max < 2) return -1;
--max;
// read from buffer, handle newlines
int64_t readSoFar = m_readBuffer.ReadLine(dest, max);
if (readSoFar && dest[readSoFar - 1] == '\n') {
// adjust for windows-style '\r\n'
if (readSoFar > 1 && dest[readSoFar - 2] == '\r') {
--readSoFar;
dest[readSoFar - 1] = '\n';
}
}
// null terminate & return number of bytes read
dest[readSoFar] = '\0';
return readSoFar;
}
void TcpSocket::ResetSocketEngine()
{
// shut down socket engine
if (m_engine) {
m_engine->Close();
delete m_engine;
m_engine = 0;
}
// reset our state & cached socket handle
m_state = TcpSocket::UnconnectedState;
m_cachedSocketDescriptor = -1;
}
bool TcpSocket::WaitForReadLine()
{
// wait until we can read a line (will return immediately if already capable)
while (!CanReadLine()) {
if (!ReadFromSocket()) return false;
}
// if we get here, success
return true;
}
int64_t TcpSocket::Write(const char* data, const unsigned int numBytes)
{
// single-shot attempt at write (not buffered, just try to shove the data through socket)
// this method purely exists to send 'small' HTTP requests/FTP commands from client to server
// wait for our socket to be write-able
bool timedOut;
const bool isReadyWrite = m_engine->WaitForWrite(3000, &timedOut);
// if ready, return number of bytes written
if (isReadyWrite) return m_engine->Write(data, numBytes);
// otherwise, socket not ready for writing
// set error string depending on reason & return failure
if (!timedOut) {
// TODO: get add'l error info from engine ??
m_errorString = "TcpSocket::Write - timed out waiting for ready-write";
} else {
// TODO: get add'l error info from engine ??
m_errorString = "TcpSocket::Write - error encountered while waiting for ready-write";
}
return -1;
}
<|endoftext|> |
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_privsep_helper.h"
#include "condor_debug.h"
// the methods in this file are all stubbed out for now, until we
// have support for privilege separation on Windows
bool CondorPrivSepHelper::s_instantiated = false;
CondorPrivSepHelper::CondorPrivSepHelper() :
m_user_initialized(false),
m_user_name(NULL),
m_sandbox_initialized(false),
m_sandbox_path(NULL)
{
ASSERT(!s_instantiated);
s_instantiated = true;
}
CondorPrivSepHelper::~CondorPrivSepHelper()
{
if (m_sandbox_path != NULL) {
free(m_sandbox_path);
}
if( m_user_name ) {
free(m_user_name);
}
}
void
CondorPrivSepHelper::initialize_user(const char* name)
{
m_user_name = strdup(name);
EXCEPT("CondorPrivSepHelper: Windows support not implemented");
}
void
CondorPrivSepHelper::initialize_sandbox(const char* path)
{
EXCEPT("CondorPrivSepHelper: Windows support not implemented");
}
void
CondorPrivSepHelper::chown_sandbox_to_user()
{
EXCEPT("CondorPrivSepHelper: Windows support not implemented");
}
void
CondorPrivSepHelper::chown_sandbox_to_condor()
{
EXCEPT("CondorPrivSepHelper: Windows support not implemented");
}
int
CondorPrivSepHelper::create_process(const char*,
ArgList&,
Env&,
const char*,
int[3],
const char*[3],
int,
size_t*,
int,
int,
FamilyInfo*,
int *affinity_mask,
MyString * error_msg = NULL)
{
EXCEPT("CondorPrivSepHelper: Windows support not implemented");
return 0;
}
<commit_msg>fix Windows build break in condor_privsep_helper.windows.cpp<commit_after>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_privsep_helper.h"
#include "condor_debug.h"
// the methods in this file are all stubbed out for now, until we
// have support for privilege separation on Windows
bool CondorPrivSepHelper::s_instantiated = false;
CondorPrivSepHelper::CondorPrivSepHelper() :
m_user_initialized(false),
m_user_name(NULL),
m_sandbox_initialized(false),
m_sandbox_path(NULL)
{
ASSERT(!s_instantiated);
s_instantiated = true;
}
CondorPrivSepHelper::~CondorPrivSepHelper()
{
if (m_sandbox_path != NULL) {
free(m_sandbox_path);
}
if( m_user_name ) {
free(m_user_name);
}
}
void
CondorPrivSepHelper::initialize_user(const char* name)
{
m_user_name = strdup(name);
EXCEPT("CondorPrivSepHelper: Windows support not implemented");
}
void
CondorPrivSepHelper::initialize_sandbox(const char* path)
{
EXCEPT("CondorPrivSepHelper: Windows support not implemented");
}
void
CondorPrivSepHelper::chown_sandbox_to_user()
{
EXCEPT("CondorPrivSepHelper: Windows support not implemented");
}
void
CondorPrivSepHelper::chown_sandbox_to_condor()
{
EXCEPT("CondorPrivSepHelper: Windows support not implemented");
}
int
CondorPrivSepHelper::create_process(const char*,
ArgList&,
Env&,
const char*,
int[3],
const char*[3],
int,
size_t*,
int,
int,
FamilyInfo*,
int *affinity_mask,
MyString * error_msg /* = NULL*/)
{
EXCEPT("CondorPrivSepHelper: Windows support not implemented");
return 0;
}
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Build Suite.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "commandlinefrontend.h"
#include "application.h"
#include "consoleprogressobserver.h"
#include "showproperties.h"
#include "status.h"
#include <qbs.h>
#include <api/runenvironment.h>
#include <QDir>
#include <QProcessEnvironment>
#include <cstdlib>
namespace qbs {
CommandLineFrontend::CommandLineFrontend(const CommandLineParser &parser, QObject *parent)
: QObject(parent), m_parser(parser), m_observer(0)
{
}
void CommandLineFrontend::cancel()
{
foreach (AbstractJob * const job, m_resolveJobs)
job->cancel();
foreach (AbstractJob * const job, m_buildJobs)
job->cancel();
}
void CommandLineFrontend::start()
{
try {
if (m_parser.showProgress())
m_observer = new ConsoleProgressObserver;
foreach (const QVariantMap &buildConfig, m_parser.buildConfigurations()) {
SetupProjectJob * const job = Project::setupProject(m_parser.projectFileName(),
buildConfig, QDir::currentPath(), this);
connectJob(job);
m_resolveJobs << job;
}
/*
* Progress reporting on the terminal gets a bit tricky when resolving several projects
* concurrently, since we cannot show multiple progress bars at the same time. Instead,
* we just set the total effort to the number of projects and increase the progress
* every time one of them finishes, ingoring the progress reports from the jobs themselves.
* (Yes, that does mean it will take disproportionately long for the first progress
* notification to arrive.)
*/
if (m_parser.showProgress() && resolvingMultipleProjects())
m_observer->initialize(tr("Setting up projects"), m_resolveJobs.count());
} catch (const Error &error) {
qbsError() << error.toString();
if (m_buildJobs.isEmpty() && m_resolveJobs.isEmpty())
qApp->exit(EXIT_FAILURE);
else
cancel();
}
}
void CommandLineFrontend::handleJobFinished(bool success, AbstractJob *job)
{
job->deleteLater();
if (!success) {
qbsError() << job->error().toString();
m_resolveJobs.removeOne(job);
m_buildJobs.removeOne(job);
if (m_resolveJobs.isEmpty() && m_buildJobs.isEmpty()) {
qApp->exit(EXIT_FAILURE);
return;
}
cancel();
} else if (SetupProjectJob * const setupJob = qobject_cast<SetupProjectJob *>(job)) {
m_resolveJobs.removeOne(job);
m_projects << setupJob->project();
if (m_observer && resolvingMultipleProjects())
m_observer->incrementProgressValue();
if (m_resolveJobs.isEmpty())
handleProjectsResolved();
} else { // Build or clean.
m_buildJobs.removeOne(job);
if (m_buildJobs.isEmpty()) {
if (m_parser.command() == CommandLineParser::RunCommand)
qApp->exit(runTarget());
else
qApp->quit();
}
}
}
void CommandLineFrontend::handleNewTaskStarted(const QString &description, int totalEffort)
{
if (isBuilding()) {
m_totalBuildEffort += totalEffort;
if (++m_buildEffortsRetrieved == m_buildEffortsNeeded) {
m_observer->initialize(tr("Building"), m_totalBuildEffort);
if (m_currentBuildEffort > 0)
m_observer->setProgressValue(m_currentBuildEffort);
}
} else if (!resolvingMultipleProjects()) {
m_observer->initialize(description, totalEffort);
}
}
void CommandLineFrontend::handleTaskProgress(int value, AbstractJob *job)
{
if (isBuilding()) {
int ¤tJobEffort = m_buildEfforts[job];
m_currentBuildEffort += value - currentJobEffort;
currentJobEffort = value;
if (m_buildEffortsRetrieved == m_buildEffortsNeeded)
m_observer->setProgressValue(m_currentBuildEffort);
} else if (!resolvingMultipleProjects()) {
m_observer->setProgressValue(value);
}
}
bool CommandLineFrontend::resolvingMultipleProjects() const
{
return isResolving() && m_resolveJobs.count() + m_projects.count() > 1;
}
bool CommandLineFrontend::isResolving() const
{
return !m_resolveJobs.isEmpty();
}
bool CommandLineFrontend::isBuilding() const
{
return !m_buildJobs.isEmpty();
}
CommandLineFrontend::ProductMap CommandLineFrontend::productsToUse() const
{
ProductMap products;
QStringList productNames;
const bool useAll = m_parser.products().isEmpty();
foreach (const Project &project, m_projects) {
QList<ProductData> &productList = products[project];
const ProjectData projectData = project.projectData();
foreach (const ProductData &product, projectData.products()) {
if (useAll || m_parser.products().contains(product.name())) {
productList << product;
productNames << product.name();
}
}
}
foreach (const QString &productName, m_parser.products()) {
if (!productNames.contains(productName)) {
qbsWarning() << QCoreApplication::translate("qbs", "No such product '%1'.")
.arg(productName);
}
}
return products;
}
void CommandLineFrontend::handleProjectsResolved()
{
try {
switch (m_parser.command()) {
case CommandLineParser::CleanCommand:
makeClean();
break;
case CommandLineParser::StartShellCommand:
qApp->exit(runShell());
break;
case CommandLineParser::StatusCommand: {
QList<ProjectData> projects;
foreach (const Project &project, m_projects)
projects << project.projectData();
qApp->exit(printStatus(projects));
break;
}
case CommandLineParser::PropertiesCommand: {
QList<ProductData> products;
const ProductMap &p = productsToUse();
foreach (const QList<ProductData> &pProducts, p)
products << pProducts;
qApp->exit(showProperties(products));
break;
}
case CommandLineParser::BuildCommand:
case CommandLineParser::RunCommand:
build();
break;
}
} catch (const Error &error) {
qbsError() << error.toString();
qApp->exit(EXIT_FAILURE);
}
}
void CommandLineFrontend::makeClean()
{
if (m_parser.products().isEmpty()) {
foreach (const Project &project, m_projects) {
m_buildJobs << project.cleanAllProducts(m_parser.buildOptions(),
Project::CleanupTemporaries, this);
}
} else {
const ProductMap &products = productsToUse();
for (ProductMap::ConstIterator it = products.begin(); it != products.end(); ++it) {
m_buildJobs << it.key().cleanSomeProducts(it.value(), m_parser.buildOptions(),
Project::CleanupTemporaries, this);
}
}
connectBuildJobs();
}
int CommandLineFrontend::runShell()
{
// TODO: Don't take a random product.
const Project &project = m_projects.first();
RunEnvironment runEnvironment = project.getRunEnvironment(project.projectData().products().first(),
QProcessEnvironment::systemEnvironment());
return runEnvironment.runShell();
}
void CommandLineFrontend::build()
{
if (m_parser.products().isEmpty()) {
foreach (const Project &project, m_projects)
m_buildJobs << project.buildAllProducts(m_parser.buildOptions(), this);
} else {
const ProductMap &products = productsToUse();
for (ProductMap::ConstIterator it = products.begin(); it != products.end(); ++it)
m_buildJobs << it.key().buildSomeProducts(it.value(), m_parser.buildOptions(), this);
}
connectBuildJobs();
/*
* Progress reporting for the build jobs works as follows: We know that for every job,
* the newTaskStarted() signal is emitted exactly once (unless there's an error). So we add up
* the respective total efforts as they come in. Once all jobs have reported their total
* efforts, we can start the overall progress report.
*/
m_buildEffortsNeeded = m_buildJobs.count();
m_buildEffortsRetrieved = 0;
m_totalBuildEffort = 0;
m_currentBuildEffort = 0;
}
// TODO: Don't pick a random project
int CommandLineFrontend::runTarget()
{
ProductData productToRun;
QString productFileName;
const QString targetName = m_parser.runTargetName();
const Project &project = m_projects.first();
foreach (const ProductData &product, productsToUse().value(project)) {
const QString executable = project.targetExecutable(product);
if (executable.isEmpty())
continue;
if (!targetName.isEmpty() && !executable.endsWith(targetName))
continue;
if (!productFileName.isEmpty()) {
qbsError() << tr("There is more than one executable target in "
"the project. Please specify which target "
"you want to run.");
return EXIT_FAILURE;
}
productFileName = executable;
productToRun = product;
}
if (productToRun.name().isEmpty()) {
if (targetName.isEmpty())
qbsError() << tr("Can't find a suitable product to run.");
else
qbsError() << tr("No such target: '%1'").arg(targetName);
return EXIT_FAILURE;
}
RunEnvironment runEnvironment = project.getRunEnvironment(productToRun,
QProcessEnvironment::systemEnvironment());
return runEnvironment.runTarget(productFileName, m_parser.runArgs());
}
void CommandLineFrontend::connectBuildJobs()
{
foreach (AbstractJob * const job, m_buildJobs)
connectJob(job);
}
void CommandLineFrontend::connectJob(AbstractJob *job)
{
connect(job, SIGNAL(finished(bool, qbs::AbstractJob*)),
SLOT(handleJobFinished(bool, qbs::AbstractJob*)));
if (m_parser.showProgress()) {
connect(job, SIGNAL(taskStarted(QString,int,qbs::AbstractJob*)),
SLOT(handleNewTaskStarted(QString,int)));
connect(job, SIGNAL(taskProgress(int,qbs::AbstractJob*)),
SLOT(handleTaskProgress(int,qbs::AbstractJob*)));
}
}
} // namespace qbs
<commit_msg>Do not allow more than one build configuration with "run" and "shell".<commit_after>/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the Qt Build Suite.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 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, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "commandlinefrontend.h"
#include "application.h"
#include "consoleprogressobserver.h"
#include "showproperties.h"
#include "status.h"
#include <qbs.h>
#include <api/runenvironment.h>
#include <logging/translator.h>
#include <QDir>
#include <QProcessEnvironment>
#include <cstdlib>
namespace qbs {
CommandLineFrontend::CommandLineFrontend(const CommandLineParser &parser, QObject *parent)
: QObject(parent), m_parser(parser), m_observer(0)
{
}
void CommandLineFrontend::cancel()
{
foreach (AbstractJob * const job, m_resolveJobs)
job->cancel();
foreach (AbstractJob * const job, m_buildJobs)
job->cancel();
}
void CommandLineFrontend::start()
{
try {
if (m_parser.buildConfigurations().count() > 1) {
QString command;
if (m_parser.command() == CommandLineParser::RunCommand)
command = QLatin1String("run");
else if (m_parser.command() == CommandLineParser::StartShellCommand)
command = QLatin1String("shell");
if (!command.isEmpty()) {
throw Error(Tr::tr("Ambiguous command: '%1' needs exactly one "
"build configuration.").arg(command));
}
}
if (m_parser.showProgress())
m_observer = new ConsoleProgressObserver;
foreach (const QVariantMap &buildConfig, m_parser.buildConfigurations()) {
SetupProjectJob * const job = Project::setupProject(m_parser.projectFileName(),
buildConfig, QDir::currentPath(), this);
connectJob(job);
m_resolveJobs << job;
}
/*
* Progress reporting on the terminal gets a bit tricky when resolving several projects
* concurrently, since we cannot show multiple progress bars at the same time. Instead,
* we just set the total effort to the number of projects and increase the progress
* every time one of them finishes, ingoring the progress reports from the jobs themselves.
* (Yes, that does mean it will take disproportionately long for the first progress
* notification to arrive.)
*/
if (m_parser.showProgress() && resolvingMultipleProjects())
m_observer->initialize(tr("Setting up projects"), m_resolveJobs.count());
} catch (const Error &error) {
qbsError() << error.toString();
if (m_buildJobs.isEmpty() && m_resolveJobs.isEmpty())
qApp->exit(EXIT_FAILURE);
else
cancel();
}
}
void CommandLineFrontend::handleJobFinished(bool success, AbstractJob *job)
{
job->deleteLater();
if (!success) {
qbsError() << job->error().toString();
m_resolveJobs.removeOne(job);
m_buildJobs.removeOne(job);
if (m_resolveJobs.isEmpty() && m_buildJobs.isEmpty()) {
qApp->exit(EXIT_FAILURE);
return;
}
cancel();
} else if (SetupProjectJob * const setupJob = qobject_cast<SetupProjectJob *>(job)) {
m_resolveJobs.removeOne(job);
m_projects << setupJob->project();
if (m_observer && resolvingMultipleProjects())
m_observer->incrementProgressValue();
if (m_resolveJobs.isEmpty())
handleProjectsResolved();
} else { // Build or clean.
m_buildJobs.removeOne(job);
if (m_buildJobs.isEmpty()) {
if (m_parser.command() == CommandLineParser::RunCommand)
qApp->exit(runTarget());
else
qApp->quit();
}
}
}
void CommandLineFrontend::handleNewTaskStarted(const QString &description, int totalEffort)
{
if (isBuilding()) {
m_totalBuildEffort += totalEffort;
if (++m_buildEffortsRetrieved == m_buildEffortsNeeded) {
m_observer->initialize(tr("Building"), m_totalBuildEffort);
if (m_currentBuildEffort > 0)
m_observer->setProgressValue(m_currentBuildEffort);
}
} else if (!resolvingMultipleProjects()) {
m_observer->initialize(description, totalEffort);
}
}
void CommandLineFrontend::handleTaskProgress(int value, AbstractJob *job)
{
if (isBuilding()) {
int ¤tJobEffort = m_buildEfforts[job];
m_currentBuildEffort += value - currentJobEffort;
currentJobEffort = value;
if (m_buildEffortsRetrieved == m_buildEffortsNeeded)
m_observer->setProgressValue(m_currentBuildEffort);
} else if (!resolvingMultipleProjects()) {
m_observer->setProgressValue(value);
}
}
bool CommandLineFrontend::resolvingMultipleProjects() const
{
return isResolving() && m_resolveJobs.count() + m_projects.count() > 1;
}
bool CommandLineFrontend::isResolving() const
{
return !m_resolveJobs.isEmpty();
}
bool CommandLineFrontend::isBuilding() const
{
return !m_buildJobs.isEmpty();
}
CommandLineFrontend::ProductMap CommandLineFrontend::productsToUse() const
{
ProductMap products;
QStringList productNames;
const bool useAll = m_parser.products().isEmpty();
foreach (const Project &project, m_projects) {
QList<ProductData> &productList = products[project];
const ProjectData projectData = project.projectData();
foreach (const ProductData &product, projectData.products()) {
if (useAll || m_parser.products().contains(product.name())) {
productList << product;
productNames << product.name();
}
}
}
foreach (const QString &productName, m_parser.products()) {
if (!productNames.contains(productName)) {
qbsWarning() << QCoreApplication::translate("qbs", "No such product '%1'.")
.arg(productName);
}
}
return products;
}
void CommandLineFrontend::handleProjectsResolved()
{
try {
switch (m_parser.command()) {
case CommandLineParser::CleanCommand:
makeClean();
break;
case CommandLineParser::StartShellCommand:
qApp->exit(runShell());
break;
case CommandLineParser::StatusCommand: {
QList<ProjectData> projects;
foreach (const Project &project, m_projects)
projects << project.projectData();
qApp->exit(printStatus(projects));
break;
}
case CommandLineParser::PropertiesCommand: {
QList<ProductData> products;
const ProductMap &p = productsToUse();
foreach (const QList<ProductData> &pProducts, p)
products << pProducts;
qApp->exit(showProperties(products));
break;
}
case CommandLineParser::BuildCommand:
case CommandLineParser::RunCommand:
build();
break;
}
} catch (const Error &error) {
qbsError() << error.toString();
qApp->exit(EXIT_FAILURE);
}
}
void CommandLineFrontend::makeClean()
{
if (m_parser.products().isEmpty()) {
foreach (const Project &project, m_projects) {
m_buildJobs << project.cleanAllProducts(m_parser.buildOptions(),
Project::CleanupTemporaries, this);
}
} else {
const ProductMap &products = productsToUse();
for (ProductMap::ConstIterator it = products.begin(); it != products.end(); ++it) {
m_buildJobs << it.key().cleanSomeProducts(it.value(), m_parser.buildOptions(),
Project::CleanupTemporaries, this);
}
}
connectBuildJobs();
}
int CommandLineFrontend::runShell()
{
Q_ASSERT(m_projects.count() == 1);
const Project &project = m_projects.first();
// TODO: Don't take a random product.
RunEnvironment runEnvironment = project.getRunEnvironment(project.projectData().products().first(),
QProcessEnvironment::systemEnvironment());
return runEnvironment.runShell();
}
void CommandLineFrontend::build()
{
if (m_parser.products().isEmpty()) {
foreach (const Project &project, m_projects)
m_buildJobs << project.buildAllProducts(m_parser.buildOptions(), this);
} else {
const ProductMap &products = productsToUse();
for (ProductMap::ConstIterator it = products.begin(); it != products.end(); ++it)
m_buildJobs << it.key().buildSomeProducts(it.value(), m_parser.buildOptions(), this);
}
connectBuildJobs();
/*
* Progress reporting for the build jobs works as follows: We know that for every job,
* the newTaskStarted() signal is emitted exactly once (unless there's an error). So we add up
* the respective total efforts as they come in. Once all jobs have reported their total
* efforts, we can start the overall progress report.
*/
m_buildEffortsNeeded = m_buildJobs.count();
m_buildEffortsRetrieved = 0;
m_totalBuildEffort = 0;
m_currentBuildEffort = 0;
}
int CommandLineFrontend::runTarget()
{
ProductData productToRun;
QString productFileName;
const QString targetName = m_parser.runTargetName();
Q_ASSERT(m_projects.count() == 1);
const Project &project = m_projects.first();
foreach (const ProductData &product, productsToUse().value(project)) {
const QString executable = project.targetExecutable(product);
if (executable.isEmpty())
continue;
if (!targetName.isEmpty() && !executable.endsWith(targetName))
continue;
if (!productFileName.isEmpty()) {
qbsError() << tr("There is more than one executable target in "
"the project. Please specify which target "
"you want to run.");
return EXIT_FAILURE;
}
productFileName = executable;
productToRun = product;
}
if (productToRun.name().isEmpty()) {
if (targetName.isEmpty())
qbsError() << tr("Can't find a suitable product to run.");
else
qbsError() << tr("No such target: '%1'").arg(targetName);
return EXIT_FAILURE;
}
RunEnvironment runEnvironment = project.getRunEnvironment(productToRun,
QProcessEnvironment::systemEnvironment());
return runEnvironment.runTarget(productFileName, m_parser.runArgs());
}
void CommandLineFrontend::connectBuildJobs()
{
foreach (AbstractJob * const job, m_buildJobs)
connectJob(job);
}
void CommandLineFrontend::connectJob(AbstractJob *job)
{
connect(job, SIGNAL(finished(bool, qbs::AbstractJob*)),
SLOT(handleJobFinished(bool, qbs::AbstractJob*)));
if (m_parser.showProgress()) {
connect(job, SIGNAL(taskStarted(QString,int,qbs::AbstractJob*)),
SLOT(handleNewTaskStarted(QString,int)));
connect(job, SIGNAL(taskProgress(int,qbs::AbstractJob*)),
SLOT(handleTaskProgress(int,qbs::AbstractJob*)));
}
}
} // namespace qbs
<|endoftext|> |
<commit_before>/*
* Copyright 2016, Simula Research Laboratory
*
* 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/.
*/
#define png_infopp_NULL (png_infopp)NULL
#define int_p_NULL (int*)NULL
#include <boost/gil/extension/io/png_io.hpp>
#include "cctag/utils/FileDebug.hpp"
#include "cctag/utils/VisualDebug.hpp"
#include "cctag/utils/Exceptions.hpp"
#include "cctag/Detection.hpp"
#include "CmdLine.hpp"
#ifdef WITH_CUDA
#include "cuda/device_prop.hpp"
#include "cuda/debug_macros.hpp"
#endif // WITH_CUDA
#include <boost/filesystem/convenience.hpp>
#include <boost/filesystem.hpp>
#include <boost/progress.hpp>
#include <boost/exception/all.hpp>
#include <boost/ptr_container/ptr_list.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <opencv/cv.h>
#include <opencv2/videoio.hpp>
#include <opencv2/core/core.hpp>
#include "opencv2/opencv.hpp"
#include <sstream>
#include <iostream>
#include <string>
#include <fstream>
#include <exception>
#include <regex>
#include <tbb/tbb.h>
#define PRINT_TO_CERR
using namespace cctag;
using boost::timer;
using namespace boost::gil;
namespace bfs = boost::filesystem;
/**
* @brief Check if a string is an integer number.
*
* @param[in] s The string to check.
* @return Return true if the string is an integer number
*/
bool isInteger(std::string &s)
{
std::regex e("^-?\\d+");
return std::regex_match(s, e);
}
/**
* @brief Draw the detected marker int the given image. The markers are drawn as a
* circle centered in the center of the marker and with its id. It draws the
* well identified markers in green, the unknown / badly detected markers in red.
*
* @param[in] markers The list of markers to draw.
* @param[out] image The image in which to draw the markers.
*/
void drawMarkers(const boost::ptr_list<CCTag> &markers, cv::Mat &image)
{
BOOST_FOREACH(const cctag::CCTag & marker, markers)
{
const cv::Point center = cv::Point(marker.x(), marker.y());
const int radius = 10;
if(marker.getStatus() == 1)
{
const cv::Scalar color = cv::Scalar(0, 255, 0 , 255);
cv::circle(image, center, radius, color, 3);
cv::putText(image, std::to_string(marker.id()), center, cv::FONT_HERSHEY_SIMPLEX, 5, color, 3);
}
else
{
const cv::Scalar color = cv::Scalar(0, 0, 255 , 255);
cv::circle(image, center, radius, color, 2);
cv::putText(image, std::to_string(marker.id()), center, cv::FONT_HERSHEY_SIMPLEX, 4, color, 3);
}
}
}
void detection(std::size_t frameId,
int pipeId,
const cv::Mat & src,
const cctag::Parameters & params,
const cctag::CCTagMarkersBank & bank,
boost::ptr_list<CCTag> &markers,
std::ostream & output,
std::string debugFileName = "")
{
if(debugFileName == "")
{
debugFileName = "00000";
}
// Process markers detection
boost::timer t;
CCTagVisualDebug::instance().initBackgroundImage(src);
CCTagVisualDebug::instance().setImageFileName(debugFileName);
CCTagFileDebug::instance().setPath(CCTagVisualDebug::instance().getPath());
static cctag::logtime::Mgmt* durations = 0;
//Call the main CCTag detection function
cctagDetection(markers, pipeId, frameId, src, params, bank, true, durations);
if(durations)
{
durations->print(std::cerr);
}
CCTagFileDebug::instance().outPutAllSessions();
CCTagFileDebug::instance().clearSessions();
CCTagVisualDebug::instance().outPutAllSessions();
CCTagVisualDebug::instance().clearSessions();
std::cout << "Total time: " << t.elapsed() << std::endl;
CCTAG_COUT_NOENDL("Id : ");
std::size_t counter = 0;
std::size_t nMarkers = 0;
output << "#frame " << frameId << '\n';
output << "Detected " << markers.size() << " candidates" << '\n';
BOOST_FOREACH(const cctag::CCTag & marker, markers)
{
output << marker.x() << " " << marker.y() << " " << marker.id() << " " << marker.getStatus() << '\n';
++counter;
if(marker.getStatus() == 1)
++nMarkers;
}
counter = 0;
BOOST_FOREACH(const cctag::CCTag & marker, markers)
{
if(counter == 0)
{
CCTAG_COUT_NOENDL(marker.id() + 1);
}
else
{
CCTAG_COUT_NOENDL(", " << marker.id() + 1);
}
++counter;
}
std::cout << std::endl << nMarkers << " markers detected and identified" << std::endl;
}
/*************************************************************/
/* Main entry */
/*************************************************************/
int main(int argc, char** argv)
{
CmdLine cmdline;
if(cmdline.parse(argc, argv) == false)
{
cmdline.usage(argv[0]);
return EXIT_FAILURE;
}
cmdline.print(argv[0]);
bool useCamera = false;
// Check input path
if(!cmdline._filename.empty())
{
if(isInteger(cmdline._filename))
{
useCamera = true;
}
else if(!boost::filesystem::exists(cmdline._filename))
{
std::cerr << std::endl
<< "The input file \"" << cmdline._filename << "\" is missing" << std::endl;
return EXIT_FAILURE;
}
}
else
{
std::cerr << std::endl
<< "An input file is required" << std::endl;
cmdline.usage(argv[0]);
return EXIT_FAILURE;
}
#ifdef WITH_CUDA
popart::pop_cuda_only_sync_calls(cmdline._switchSync);
#endif
// Check the (optional) parameters path
const std::size_t nCrowns = std::atoi(cmdline._nCrowns.c_str());
cctag::Parameters params(nCrowns);
if(!cmdline._paramsFilename.empty())
{
if(!boost::filesystem::exists(cmdline._paramsFilename))
{
std::cerr << std::endl
<< "The input file \"" << cmdline._paramsFilename << "\" is missing" << std::endl;
return EXIT_FAILURE;
}
// Read the parameter file provided by the user
std::ifstream ifs(cmdline._paramsFilename);
boost::archive::xml_iarchive ia(ifs);
ia >> boost::serialization::make_nvp("CCTagsParams", params);
CCTAG_COUT(params._nCrowns);
CCTAG_COUT(nCrowns);
assert(nCrowns == params._nCrowns);
}
else
{
// Use the default parameters and save them in defaultParameters.xml
cmdline._paramsFilename = "defaultParameters.xml";
std::ofstream ofs(cmdline._paramsFilename);
boost::archive::xml_oarchive oa(ofs);
oa << boost::serialization::make_nvp("CCTagsParams", params);
CCTAG_COUT("Parameter file not provided. Default parameters are used.");
}
CCTagMarkersBank bank(params._nCrowns);
if(!cmdline._cctagBankFilename.empty())
{
bank = CCTagMarkersBank(cmdline._cctagBankFilename);
}
#ifdef WITH_CUDA
if(cmdline._useCuda)
{
params.setUseCuda(true);
}
else
{
params.setUseCuda(false);
}
if(cmdline._debugDir != "")
{
params.setDebugDir(cmdline._debugDir);
}
popart::device_prop_t deviceInfo(false);
#endif // WITH_CUDA
bfs::path myPath(cmdline._filename);
std::string ext(myPath.extension().string());
const bfs::path parentPath(myPath.parent_path() == "" ? "." : myPath.parent_path());
std::string outputFileName;
if(!bfs::is_directory(myPath))
{
CCTagVisualDebug::instance().initializeFolders(parentPath, cmdline._outputFolderName, params._nCrowns);
outputFileName = parentPath.string() + "/" + cmdline._outputFolderName + "/cctag" + std::to_string(nCrowns) + "CC.out";
}
else
{
CCTagVisualDebug::instance().initializeFolders(myPath, cmdline._outputFolderName, params._nCrowns);
outputFileName = myPath.string() + "/" + cmdline._outputFolderName + "/cctag" + std::to_string(nCrowns) + "CC.out";
}
std::ofstream outputFile;
outputFile.open(outputFileName);
if((ext == ".png") || (ext == ".jpg") || (ext == ".PNG") || (ext == ".JPG"))
{
std::cout << "******************* Image mode **********************" << std::endl;
POP_INFO("looking at image " << myPath.string());
// Gray scale conversion
cv::Mat src = cv::imread(cmdline._filename);
cv::Mat graySrc;
cv::cvtColor(src, graySrc, CV_BGR2GRAY);
const int pipeId = 0;
boost::ptr_list<CCTag> markers;
#ifdef PRINT_TO_CERR
detection(0, pipeId, graySrc, params, bank, markers, std::cerr, myPath.stem().string());
#else
detection(0, pipeId, graySrc, params, bank, markers, outputFile, myPath.stem().string());
#endif
}
else if(ext == ".avi" || ext == ".mov" || useCamera)
{
CCTAG_COUT("*** Video mode ***");
POP_INFO("looking at video " << myPath.string());
// open video and check
cv::VideoCapture video;
if(useCamera)
video.open(std::atoi(cmdline._filename.c_str()));
else
video.open(cmdline._filename);
if(!video.isOpened())
{
CCTAG_COUT("Unable to open the video : " << cmdline._filename);
return EXIT_FAILURE;
}
const std::string windowName = "Detection result";
cv::namedWindow(windowName, cv::WINDOW_NORMAL);
std::cerr << "Starting to read video frames" << std::endl;
std::size_t frameId = 0;
// time to wait in milliseconds for keyboard input, used to switch from
// live to debug mode
int delay = 10;
while(true)
{
cv::Mat frame;
video >> frame;
if(frame.empty())
break;
cv::Mat imgGray;
if(frame.channels() == 3 || frame.channels() == 4)
cv::cvtColor(frame, imgGray, cv::COLOR_BGR2GRAY);
else
frame.copyTo(imgGray);
boost::timer t;
// Set the output folder
std::stringstream outFileName;
outFileName << std::setfill('0') << std::setw(5) << frameId;
boost::ptr_list<CCTag> markers;
// Invert the image for the projection scenario
//cv::Mat imgGrayInverted;
//bitwise_not ( imgGray, imgGrayInverted );
// Call the CCTag detection
const int pipeId = 0;
#ifdef PRINT_TO_CERR
detection(frameId, pipeId, imgGray, params, bank, markers, std::cerr, outFileName.str());
#else
detection(frameId, pipeId, imgGray, params, bank, markers, outputFile, outFileName.str());
#endif
// if the original image is b/w convert it to BGRA so we can draw colors
if(frame.channels() == 1)
cv::cvtColor(imgGray, frame, cv::COLOR_GRAY2BGRA);
drawMarkers(markers, frame);
cv::imshow(windowName, frame);
if( cv::waitKey(delay) == 27 ) break;
char key = (char) cv::waitKey(delay);
// stop capturing by pressing ESC
if(key == 27)
break;
if(key == 'l' || key == 'L')
delay = 10;
// delay = 0 will wait for a key to be pressed
if(key == 'd' || key == 'D')
delay = 0;
++frameId;
}
}
else if(bfs::is_directory(myPath))
{
CCTAG_COUT("*** Image sequence mode ***");
std::vector<bfs::path> vFileInFolder;
std::copy(bfs::directory_iterator(myPath), bfs::directory_iterator(), std::back_inserter(vFileInFolder)); // is directory_entry, which is
std::sort(vFileInFolder.begin(), vFileInFolder.end());
std::size_t frameId = 0;
std::map<int, bfs::path> files[2];
for(const auto & fileInFolder : vFileInFolder)
{
files[frameId & 1].insert(std::pair<int, bfs::path>(frameId, fileInFolder));
frameId++;
}
tbb::parallel_for(0, 2, [&](size_t fileListIdx)
{
for(const auto & fileInFolder : files[fileListIdx])
{
const std::string subExt(bfs::extension(fileInFolder.second));
if((subExt == ".png") || (subExt == ".jpg") || (subExt == ".PNG") || (subExt == ".JPG"))
{
std::cerr << "Processing image " << fileInFolder.second.string() << std::endl;
cv::Mat src;
src = cv::imread(fileInFolder.second.string());
cv::Mat imgGray;
cv::cvtColor(src, imgGray, CV_BGR2GRAY);
// Call the CCTag detection
int pipeId = (fileInFolder.first & 1);
boost::ptr_list<CCTag> markers;
#ifdef PRINT_TO_CERR
detection(fileInFolder.first, pipeId, imgGray, params, bank, markers, std::cerr, fileInFolder.second.stem().string());
#else
detection(fileInFolder.first, pipeId, imgGray, params, bank, markers, outputFile, fileInFolder.second.stem().string());
#endif
std::cerr << "Done processing image " << fileInFolder.second.string() << std::endl;
}
}
});
}
else
{
throw std::logic_error("Unrecognized input.");
}
outputFile.close();
return EXIT_SUCCESS;
}
<commit_msg>[applications] doc and renaming<commit_after>/*
* Copyright 2016, Simula Research Laboratory
*
* 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/.
*/
#define png_infopp_NULL (png_infopp)NULL
#define int_p_NULL (int*)NULL
#include <boost/gil/extension/io/png_io.hpp>
#include "cctag/utils/FileDebug.hpp"
#include "cctag/utils/VisualDebug.hpp"
#include "cctag/utils/Exceptions.hpp"
#include "cctag/Detection.hpp"
#include "CmdLine.hpp"
#ifdef WITH_CUDA
#include "cuda/device_prop.hpp"
#include "cuda/debug_macros.hpp"
#endif // WITH_CUDA
#include <boost/filesystem/convenience.hpp>
#include <boost/filesystem.hpp>
#include <boost/progress.hpp>
#include <boost/exception/all.hpp>
#include <boost/ptr_container/ptr_list.hpp>
#include <boost/archive/xml_oarchive.hpp>
#include <boost/archive/xml_iarchive.hpp>
#include <boost/thread/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <opencv/cv.h>
#include <opencv2/videoio.hpp>
#include <opencv2/core/core.hpp>
#include "opencv2/opencv.hpp"
#include <sstream>
#include <iostream>
#include <string>
#include <fstream>
#include <exception>
#include <regex>
#include <tbb/tbb.h>
#define PRINT_TO_CERR
using namespace cctag;
using boost::timer;
using namespace boost::gil;
namespace bfs = boost::filesystem;
/**
* @brief Check if a string is an integer number.
*
* @param[in] s The string to check.
* @return Return true if the string is an integer number
*/
bool isInteger(std::string &s)
{
std::regex e("^-?\\d+");
return std::regex_match(s, e);
}
/**
* @brief Draw the detected marker int the given image. The markers are drawn as a
* circle centered in the center of the marker and with its id. It draws the
* well identified markers in green, the unknown / badly detected markers in red.
*
* @param[in] markers The list of markers to draw.
* @param[out] image The image in which to draw the markers.
*/
void drawMarkers(const boost::ptr_list<CCTag> &markers, cv::Mat &image)
{
BOOST_FOREACH(const cctag::CCTag & marker, markers)
{
const cv::Point center = cv::Point(marker.x(), marker.y());
const int radius = 10;
if(marker.getStatus() == 1)
{
const cv::Scalar color = cv::Scalar(0, 255, 0 , 255);
cv::circle(image, center, radius, color, 3);
cv::putText(image, std::to_string(marker.id()), center, cv::FONT_HERSHEY_SIMPLEX, 5, color, 3);
}
else
{
const cv::Scalar color = cv::Scalar(0, 0, 255 , 255);
cv::circle(image, center, radius, color, 2);
cv::putText(image, std::to_string(marker.id()), center, cv::FONT_HERSHEY_SIMPLEX, 4, color, 3);
}
}
}
/**
* @brief Extract the cctag from an image.
*
* @param[in] frameId The number of the frame.
* @param[in] pipeId The pipe id (used for multiple streams).
* @param[in] src The image to process.
* @param[in] params The parameters for the detection.
* @param[in] bank The marker bank.
* @param[out] markers The list of detected markers.
* @param[out] outStream The output stream on which to write debug information.
* @param[out] debugFileName The filename for the image to save with the detected
* markers.
*/
void detection(std::size_t frameId,
int pipeId,
const cv::Mat & src,
const cctag::Parameters & params,
const cctag::CCTagMarkersBank & bank,
boost::ptr_list<CCTag> &markers,
std::ostream & outStream,
std::string debugFileName = "")
{
if(debugFileName == "")
{
debugFileName = "00000";
}
// Process markers detection
boost::timer t;
CCTagVisualDebug::instance().initBackgroundImage(src);
CCTagVisualDebug::instance().setImageFileName(debugFileName);
CCTagFileDebug::instance().setPath(CCTagVisualDebug::instance().getPath());
static cctag::logtime::Mgmt* durations = 0;
//Call the main CCTag detection function
cctagDetection(markers, pipeId, frameId, src, params, bank, true, durations);
if(durations)
{
durations->print(std::cerr);
}
CCTagFileDebug::instance().outPutAllSessions();
CCTagFileDebug::instance().clearSessions();
CCTagVisualDebug::instance().outPutAllSessions();
CCTagVisualDebug::instance().clearSessions();
std::cout << "Total time: " << t.elapsed() << std::endl;
CCTAG_COUT_NOENDL("Id : ");
std::size_t counter = 0;
std::size_t nMarkers = 0;
outStream << "#frame " << frameId << '\n';
outStream << "Detected " << markers.size() << " candidates" << '\n';
BOOST_FOREACH(const cctag::CCTag & marker, markers)
{
outStream << marker.x() << " " << marker.y() << " " << marker.id() << " " << marker.getStatus() << '\n';
++counter;
if(marker.getStatus() == 1)
++nMarkers;
}
counter = 0;
BOOST_FOREACH(const cctag::CCTag & marker, markers)
{
if(counter == 0)
{
CCTAG_COUT_NOENDL(marker.id() + 1);
}
else
{
CCTAG_COUT_NOENDL(", " << marker.id() + 1);
}
++counter;
}
std::cout << std::endl << nMarkers << " markers detected and identified" << std::endl;
}
/*************************************************************/
/* Main entry */
/*************************************************************/
int main(int argc, char** argv)
{
CmdLine cmdline;
if(cmdline.parse(argc, argv) == false)
{
cmdline.usage(argv[0]);
return EXIT_FAILURE;
}
cmdline.print(argv[0]);
bool useCamera = false;
// Check input path
if(!cmdline._filename.empty())
{
if(isInteger(cmdline._filename))
{
useCamera = true;
}
else if(!boost::filesystem::exists(cmdline._filename))
{
std::cerr << std::endl
<< "The input file \"" << cmdline._filename << "\" is missing" << std::endl;
return EXIT_FAILURE;
}
}
else
{
std::cerr << std::endl
<< "An input file is required" << std::endl;
cmdline.usage(argv[0]);
return EXIT_FAILURE;
}
#ifdef WITH_CUDA
popart::pop_cuda_only_sync_calls(cmdline._switchSync);
#endif
// Check the (optional) parameters path
const std::size_t nCrowns = std::atoi(cmdline._nCrowns.c_str());
cctag::Parameters params(nCrowns);
if(!cmdline._paramsFilename.empty())
{
if(!boost::filesystem::exists(cmdline._paramsFilename))
{
std::cerr << std::endl
<< "The input file \"" << cmdline._paramsFilename << "\" is missing" << std::endl;
return EXIT_FAILURE;
}
// Read the parameter file provided by the user
std::ifstream ifs(cmdline._paramsFilename);
boost::archive::xml_iarchive ia(ifs);
ia >> boost::serialization::make_nvp("CCTagsParams", params);
CCTAG_COUT(params._nCrowns);
CCTAG_COUT(nCrowns);
assert(nCrowns == params._nCrowns);
}
else
{
// Use the default parameters and save them in defaultParameters.xml
cmdline._paramsFilename = "defaultParameters.xml";
std::ofstream ofs(cmdline._paramsFilename);
boost::archive::xml_oarchive oa(ofs);
oa << boost::serialization::make_nvp("CCTagsParams", params);
CCTAG_COUT("Parameter file not provided. Default parameters are used.");
}
CCTagMarkersBank bank(params._nCrowns);
if(!cmdline._cctagBankFilename.empty())
{
bank = CCTagMarkersBank(cmdline._cctagBankFilename);
}
#ifdef WITH_CUDA
if(cmdline._useCuda)
{
params.setUseCuda(true);
}
else
{
params.setUseCuda(false);
}
if(cmdline._debugDir != "")
{
params.setDebugDir(cmdline._debugDir);
}
popart::device_prop_t deviceInfo(false);
#endif // WITH_CUDA
bfs::path myPath(cmdline._filename);
std::string ext(myPath.extension().string());
const bfs::path parentPath(myPath.parent_path() == "" ? "." : myPath.parent_path());
std::string outputFileName;
if(!bfs::is_directory(myPath))
{
CCTagVisualDebug::instance().initializeFolders(parentPath, cmdline._outputFolderName, params._nCrowns);
outputFileName = parentPath.string() + "/" + cmdline._outputFolderName + "/cctag" + std::to_string(nCrowns) + "CC.out";
}
else
{
CCTagVisualDebug::instance().initializeFolders(myPath, cmdline._outputFolderName, params._nCrowns);
outputFileName = myPath.string() + "/" + cmdline._outputFolderName + "/cctag" + std::to_string(nCrowns) + "CC.out";
}
std::ofstream outputFile;
outputFile.open(outputFileName);
if((ext == ".png") || (ext == ".jpg") || (ext == ".PNG") || (ext == ".JPG"))
{
std::cout << "******************* Image mode **********************" << std::endl;
POP_INFO("looking at image " << myPath.string());
// Gray scale conversion
cv::Mat src = cv::imread(cmdline._filename);
cv::Mat graySrc;
cv::cvtColor(src, graySrc, CV_BGR2GRAY);
const int pipeId = 0;
boost::ptr_list<CCTag> markers;
#ifdef PRINT_TO_CERR
detection(0, pipeId, graySrc, params, bank, markers, std::cerr, myPath.stem().string());
#else
detection(0, pipeId, graySrc, params, bank, markers, outputFile, myPath.stem().string());
#endif
}
else if(ext == ".avi" || ext == ".mov" || useCamera)
{
CCTAG_COUT("*** Video mode ***");
POP_INFO("looking at video " << myPath.string());
// open video and check
cv::VideoCapture video;
if(useCamera)
video.open(std::atoi(cmdline._filename.c_str()));
else
video.open(cmdline._filename);
if(!video.isOpened())
{
CCTAG_COUT("Unable to open the video : " << cmdline._filename);
return EXIT_FAILURE;
}
const std::string windowName = "Detection result";
cv::namedWindow(windowName, cv::WINDOW_NORMAL);
std::cerr << "Starting to read video frames" << std::endl;
std::size_t frameId = 0;
// time to wait in milliseconds for keyboard input, used to switch from
// live to debug mode
int delay = 10;
while(true)
{
cv::Mat frame;
video >> frame;
if(frame.empty())
break;
cv::Mat imgGray;
if(frame.channels() == 3 || frame.channels() == 4)
cv::cvtColor(frame, imgGray, cv::COLOR_BGR2GRAY);
else
frame.copyTo(imgGray);
boost::timer t;
// Set the output folder
std::stringstream outFileName;
outFileName << std::setfill('0') << std::setw(5) << frameId;
boost::ptr_list<CCTag> markers;
// Invert the image for the projection scenario
//cv::Mat imgGrayInverted;
//bitwise_not ( imgGray, imgGrayInverted );
// Call the CCTag detection
const int pipeId = 0;
#ifdef PRINT_TO_CERR
detection(frameId, pipeId, imgGray, params, bank, markers, std::cerr, outFileName.str());
#else
detection(frameId, pipeId, imgGray, params, bank, markers, outputFile, outFileName.str());
#endif
// if the original image is b/w convert it to BGRA so we can draw colors
if(frame.channels() == 1)
cv::cvtColor(imgGray, frame, cv::COLOR_GRAY2BGRA);
drawMarkers(markers, frame);
cv::imshow(windowName, frame);
if( cv::waitKey(delay) == 27 ) break;
char key = (char) cv::waitKey(delay);
// stop capturing by pressing ESC
if(key == 27)
break;
if(key == 'l' || key == 'L')
delay = 10;
// delay = 0 will wait for a key to be pressed
if(key == 'd' || key == 'D')
delay = 0;
++frameId;
}
}
else if(bfs::is_directory(myPath))
{
CCTAG_COUT("*** Image sequence mode ***");
std::vector<bfs::path> vFileInFolder;
std::copy(bfs::directory_iterator(myPath), bfs::directory_iterator(), std::back_inserter(vFileInFolder)); // is directory_entry, which is
std::sort(vFileInFolder.begin(), vFileInFolder.end());
std::size_t frameId = 0;
std::map<int, bfs::path> files[2];
for(const auto & fileInFolder : vFileInFolder)
{
files[frameId & 1].insert(std::pair<int, bfs::path>(frameId, fileInFolder));
frameId++;
}
tbb::parallel_for(0, 2, [&](size_t fileListIdx)
{
for(const auto & fileInFolder : files[fileListIdx])
{
const std::string subExt(bfs::extension(fileInFolder.second));
if((subExt == ".png") || (subExt == ".jpg") || (subExt == ".PNG") || (subExt == ".JPG"))
{
std::cerr << "Processing image " << fileInFolder.second.string() << std::endl;
cv::Mat src;
src = cv::imread(fileInFolder.second.string());
cv::Mat imgGray;
cv::cvtColor(src, imgGray, CV_BGR2GRAY);
// Call the CCTag detection
int pipeId = (fileInFolder.first & 1);
boost::ptr_list<CCTag> markers;
#ifdef PRINT_TO_CERR
detection(fileInFolder.first, pipeId, imgGray, params, bank, markers, std::cerr, fileInFolder.second.stem().string());
#else
detection(fileInFolder.first, pipeId, imgGray, params, bank, markers, outputFile, fileInFolder.second.stem().string());
#endif
std::cerr << "Done processing image " << fileInFolder.second.string() << std::endl;
}
}
});
}
else
{
throw std::logic_error("Unrecognized input.");
}
outputFile.close();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2008, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_debug.h"
#include "subsystem_info.h"
//
// Simple class to manage a single lookup item
//
class SubsystemInfoLookup
{
public:
SubsystemInfoLookup( SubsystemType, SubsystemClass,
const char *, const char * );
~SubsystemInfoLookup( void ) { };
SubsystemType getType( void ) const { return m_Type; };
SubsystemClass getClass( void ) const { return m_Class; } ;
const char * getTypeName( void ) const { return m_TypeName; };
const char * getTypeSubstr( void ) const { return m_TypeSubstr; };
bool match( SubsystemType _type ) const { return m_Type == _type; };
bool match( SubsystemClass _class ) const { return m_Class == _class; };
bool match( const char *_name ) const;
bool matchSubstr( const char *_name ) const;
bool isValid( ) const { return m_Type != SUBSYSTEM_TYPE_INVALID; };
private:
SubsystemType m_Type;
SubsystemClass m_Class;
const char *m_TypeName;
const char *m_TypeSubstr;
};
SubsystemInfoLookup::SubsystemInfoLookup(
SubsystemType _type, SubsystemClass _class,
const char *_type_name, const char *_type_substr = NULL )
{
m_Type = _type; m_Class = _class;
m_TypeName = _type_name, m_TypeSubstr = _type_substr;
}
bool
SubsystemInfoLookup::match( const char *_name ) const
{
return ( strcasecmp(_name, m_TypeName) == 0 );
};
bool
SubsystemInfoLookup::matchSubstr( const char *_name ) const
{
const char *substr = m_TypeSubstr ? m_TypeSubstr : m_TypeName;
return ( strcasestr(_name, substr) != NULL );
};
//
// Simple class to manage the lookup table
//
class SubsystemInfoTable
{
public:
SubsystemInfoTable( void );
~SubsystemInfoTable( void ) { };
const SubsystemInfoLookup *lookup( SubsystemType ) const;
const SubsystemInfoLookup *lookup( SubsystemClass ) const;
const SubsystemInfoLookup *lookup( const char * ) const;
const SubsystemInfoLookup *Invalid( void ) const { return m_Invalid; };
private:
const SubsystemInfoLookup *m_Invalid;
static const SubsystemInfoLookup m_Table[];
};
// -----------------------------------------------------------------
// **** README README README README README README README README ****
// -----------------------------------------------------------------
// Make SURE that you read the README at the top of the include file
// subsystem_info.h before editing this file.
//
// SubsystemInfoLookup(
// <subsystem type>, SUBSYSTEM_TYPE_XXXX
// <subsystem class>, SUBSYSTEM_CLASS_XXXX
// <subsystem type name> Type name string
// [,<subsystem substr>]) Type substring (passed to strcasestr())
//
// By default, the lookup will use the <subsystem type name> for
// subsystem "fuzzy" matching, otherwise it will use the substr
// that you provide as the type name.
//
// The second to last entry in the table has an empty string so
// that it'll match any name passed in.
// -----------------------------------------------------------------
const SubsystemInfoLookup SubsystemInfoTable::m_Table[] =
{
SubsystemInfoLookup( SUBSYSTEM_TYPE_MASTER, SUBSYSTEM_CLASS_DAEMON,
"MASTER" ),
SubsystemInfoLookup( SUBSYSTEM_TYPE_COLLECTOR, SUBSYSTEM_CLASS_DAEMON,
"COLLECTOR" ),
SubsystemInfoLookup( SUBSYSTEM_TYPE_NEGOTIATOR, SUBSYSTEM_CLASS_DAEMON,
"NEGOTIATOR" ),
SubsystemInfoLookup( SUBSYSTEM_TYPE_SCHEDD, SUBSYSTEM_CLASS_DAEMON,
"SCHEDD" ),
SubsystemInfoLookup( SUBSYSTEM_TYPE_SHADOW, SUBSYSTEM_CLASS_DAEMON,
"SHADOW" ),
SubsystemInfoLookup( SUBSYSTEM_TYPE_STARTD, SUBSYSTEM_CLASS_DAEMON,
"STARTD" ),
SubsystemInfoLookup( SUBSYSTEM_TYPE_STARTER, SUBSYSTEM_CLASS_DAEMON,
"STARTER" ),
SubsystemInfoLookup( SUBSYSTEM_TYPE_GAHP, SUBSYSTEM_CLASS_DAEMON,
"GAHP" ),
SubsystemInfoLookup( SUBSYSTEM_TYPE_TOOL, SUBSYSTEM_CLASS_CLIENT,
"TOOL" ),
SubsystemInfoLookup( SUBSYSTEM_TYPE_SUBMIT, SUBSYSTEM_CLASS_CLIENT,
"SUBMIT" ),
SubsystemInfoLookup( SUBSYSTEM_TYPE_JOB, SUBSYSTEM_CLASS_JOB,
"JOB" ),
SubsystemInfoLookup( SUBSYSTEM_TYPE_DAEMON, SUBSYSTEM_CLASS_DAEMON,
"DAEMON", "" /* empty string, match anything */ ),
SubsystemInfoLookup( SUBSYSTEM_TYPE_INVALID, SUBSYSTEM_CLASS_NONE,
"INVALID" )
};
SubsystemInfoTable::SubsystemInfoTable(void)
{
int num = ( sizeof(m_Table) / sizeof(SubsystemInfoLookup) );
m_Invalid = &m_Table[num - 1];
ASSERT( m_Invalid != NULL );
ASSERT( m_Invalid->match(SUBSYSTEM_TYPE_INVALID) );
}
// Internal method to lookup by SubsystemType
const SubsystemInfoLookup *
SubsystemInfoTable::lookup( SubsystemType _type ) const
{
const SubsystemInfoLookup *cur;
for ( cur = m_Table; cur->isValid(); cur++ ) {
if ( cur->match(_type) ) {
return cur;
}
}
return m_Invalid;
}
// Internal method to lookup by SubsystemClass
const SubsystemInfoLookup *
SubsystemInfoTable::lookup( SubsystemClass _class ) const
{
const SubsystemInfoLookup *cur;
for ( cur = m_Table; cur->isValid(); cur++ ) {
if ( cur->match(_class) ) {
return cur;
}
}
return m_Invalid;
}
const SubsystemInfoLookup *
// Lookup by name
SubsystemInfoTable::lookup( const char *_name ) const
{
const SubsystemInfoLookup *cur;
for ( cur = m_Table; cur->isValid(); cur++ ) {
if ( cur->match(_name) ) {
return cur;
}
}
for ( cur = m_Table; cur->isValid(); cur++ ) {
if ( cur->matchSubstr(_name) ) {
return cur;
}
}
// Return the invalid entry
return m_Invalid;
}
static const SubsystemInfoTable *infoTable = new SubsystemInfoTable( );
//
// C++ SubsystemInfo methods
//
SubsystemInfo::SubsystemInfo( const char *_name, SubsystemType _type )
{
m_Name = NULL;
m_TempName = NULL;
m_LocalName = NULL;
if ( _type == SUBSYSTEM_TYPE_AUTO ) {
setTypeFromName( _name );
}
else {
setType( _type );
}
}
SubsystemInfo::~SubsystemInfo( void )
{
if ( m_Name ) {
free( const_cast<char *>( m_Name ) );
m_Name = NULL;
}
}
bool
SubsystemInfo::nameMatch( const char *_name ) const
{
return ( strcasecmp(_name, m_Name) == 0 );
}
const char *
SubsystemInfo::setName( const char *_name )
{
if ( _name ) {
m_Name = strdup(_name);
m_NameValid = true ;
}
else {
m_Name = strdup("UNKNOWN"); // Fill in a value so it's not NULL
m_NameValid = false;
}
return m_Name;
}
// Temp name handling
const char *
SubsystemInfo::setTempName( const char *_name )
{
resetTempName( );
if ( _name ) {
m_TempName = strdup( _name );
}
return m_TempName;
}
void
SubsystemInfo::resetTempName( void )
{
if ( m_TempName ) {
free( const_cast<char*>(m_TempName) );
m_TempName = NULL;
}
}
// Public interface to set the type from a name
SubsystemType
SubsystemInfo::setTypeFromName( const char *_type_name )
{
if ( NULL == _type_name ) {
_type_name = m_Name;
}
if ( NULL == _type_name ) {
return setType( SUBSYSTEM_TYPE_DAEMON );
}
// First, look for an exact match
const SubsystemInfoLookup *match = infoTable->lookup( _type_name );
if ( match ) {
return setType( match, _type_name );
}
return setType( SUBSYSTEM_TYPE_DAEMON, _type_name );
}
// Public set type method
SubsystemType
SubsystemInfo::setType( SubsystemType _type )
{
return setType( _type, NULL );
}
// Internal set type method
SubsystemType
SubsystemInfo::setType( SubsystemType _type, const char *_type_name )
{
return setType( infoTable->lookup(_type), _type_name );
}
// Internal set type method
SubsystemType
SubsystemInfo::setType( const SubsystemInfoLookup *info,
const char *type_name )
{
m_Type = info->getType();
setClass( info );
m_Info = info;
if ( type_name != NULL ) {
m_TypeName = type_name;
}
else {
m_TypeName = info->getTypeName();
}
return m_Type;
}
// Internal set class method
SubsystemClass
SubsystemInfo::setClass( const SubsystemInfoLookup *info )
{
static const char *_class_names[] = {
"None",
"DAEMON",
"CLIENT",
"JOB"
};
static int _num = ( sizeof(_class_names) / sizeof(const char *) );
m_Class = info->getClass();
ASSERT ( ( m_Class >= 0 ) && ( m_Class <= _num ) );
m_ClassName = _class_names[m_Class];
return m_Class;
}
// Methods to get/set the local name
const char *
SubsystemInfo::getLocalName( const char * _default ) const
{
if ( m_LocalName ) {
return m_LocalName;
}
else {
return _default;
}
}
const char *
SubsystemInfo::setLocalName( const char * _name )
{
if ( m_LocalName ) {
free( const_cast<char *>( m_LocalName ) );
m_LocalName = NULL;
}
m_LocalName = strdup(_name);
return m_LocalName;
}
// Public dprintf / printf methods
void
SubsystemInfo::dprintf( int level ) const
{
::dprintf( level, "%s\n", getString() );
}
void
SubsystemInfo::printf( void ) const
{
::printf( "%s\n", getString() );
}
const char *
SubsystemInfo::getString( void ) const
{
static char buf[128];
const char *type_name = "UNKNOWN";
if ( m_Info ) {
type_name = m_Info->getTypeName();
}
snprintf( buf, sizeof(buf),
"SubsystemInfo: name=%s type=%s(%d) class=%s(%d)",
m_Name, type_name, m_Type, m_ClassName, m_Class );
return buf;
}
/* Helper function to retrieve the value of mySubSystem global variable
* from C functions. This is helpful because mySubSystem is decorated w/ C++
* linkage.
*/
extern "C" {
const char* get_mySubSystem(void) { return mySubSystem->getName(); }
SubsystemType get_mySubsystemType(void) { return mySubSystem->getType(); }
}
<commit_msg>Fixed a bug in the SubsystemInfo constructor<commit_after>/***************************************************************
*
* Copyright (C) 1990-2008, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_debug.h"
#include "subsystem_info.h"
//
// Simple class to manage a single lookup item
//
class SubsystemInfoLookup
{
public:
SubsystemInfoLookup( SubsystemType, SubsystemClass,
const char *, const char * );
~SubsystemInfoLookup( void ) { };
SubsystemType getType( void ) const { return m_Type; };
SubsystemClass getClass( void ) const { return m_Class; } ;
const char * getTypeName( void ) const { return m_TypeName; };
const char * getTypeSubstr( void ) const { return m_TypeSubstr; };
bool match( SubsystemType _type ) const { return m_Type == _type; };
bool match( SubsystemClass _class ) const { return m_Class == _class; };
bool match( const char *_name ) const;
bool matchSubstr( const char *_name ) const;
bool isValid( ) const { return m_Type != SUBSYSTEM_TYPE_INVALID; };
private:
SubsystemType m_Type;
SubsystemClass m_Class;
const char *m_TypeName;
const char *m_TypeSubstr;
};
SubsystemInfoLookup::SubsystemInfoLookup(
SubsystemType _type, SubsystemClass _class,
const char *_type_name, const char *_type_substr = NULL )
{
m_Type = _type; m_Class = _class;
m_TypeName = _type_name, m_TypeSubstr = _type_substr;
}
bool
SubsystemInfoLookup::match( const char *_name ) const
{
return ( strcasecmp(_name, m_TypeName) == 0 );
};
bool
SubsystemInfoLookup::matchSubstr( const char *_name ) const
{
const char *substr = m_TypeSubstr ? m_TypeSubstr : m_TypeName;
return ( strcasestr(_name, substr) != NULL );
};
//
// Simple class to manage the lookup table
//
class SubsystemInfoTable
{
public:
SubsystemInfoTable( void );
~SubsystemInfoTable( void ) { };
const SubsystemInfoLookup *lookup( SubsystemType ) const;
const SubsystemInfoLookup *lookup( SubsystemClass ) const;
const SubsystemInfoLookup *lookup( const char * ) const;
const SubsystemInfoLookup *Invalid( void ) const { return m_Invalid; };
private:
const SubsystemInfoLookup *m_Invalid;
static const SubsystemInfoLookup m_Table[];
};
// -----------------------------------------------------------------
// **** README README README README README README README README ****
// -----------------------------------------------------------------
// Make SURE that you read the README at the top of the include file
// subsystem_info.h before editing this file.
//
// SubsystemInfoLookup(
// <subsystem type>, SUBSYSTEM_TYPE_XXXX
// <subsystem class>, SUBSYSTEM_CLASS_XXXX
// <subsystem type name> Type name string
// [,<subsystem substr>]) Type substring (passed to strcasestr())
//
// By default, the lookup will use the <subsystem type name> for
// subsystem "fuzzy" matching, otherwise it will use the substr
// that you provide as the type name.
//
// The second to last entry in the table has an empty string so
// that it'll match any name passed in.
// -----------------------------------------------------------------
const SubsystemInfoLookup SubsystemInfoTable::m_Table[] =
{
SubsystemInfoLookup( SUBSYSTEM_TYPE_MASTER, SUBSYSTEM_CLASS_DAEMON,
"MASTER" ),
SubsystemInfoLookup( SUBSYSTEM_TYPE_COLLECTOR, SUBSYSTEM_CLASS_DAEMON,
"COLLECTOR" ),
SubsystemInfoLookup( SUBSYSTEM_TYPE_NEGOTIATOR, SUBSYSTEM_CLASS_DAEMON,
"NEGOTIATOR" ),
SubsystemInfoLookup( SUBSYSTEM_TYPE_SCHEDD, SUBSYSTEM_CLASS_DAEMON,
"SCHEDD" ),
SubsystemInfoLookup( SUBSYSTEM_TYPE_SHADOW, SUBSYSTEM_CLASS_DAEMON,
"SHADOW" ),
SubsystemInfoLookup( SUBSYSTEM_TYPE_STARTD, SUBSYSTEM_CLASS_DAEMON,
"STARTD" ),
SubsystemInfoLookup( SUBSYSTEM_TYPE_STARTER, SUBSYSTEM_CLASS_DAEMON,
"STARTER" ),
SubsystemInfoLookup( SUBSYSTEM_TYPE_GAHP, SUBSYSTEM_CLASS_DAEMON,
"GAHP" ),
SubsystemInfoLookup( SUBSYSTEM_TYPE_TOOL, SUBSYSTEM_CLASS_CLIENT,
"TOOL" ),
SubsystemInfoLookup( SUBSYSTEM_TYPE_SUBMIT, SUBSYSTEM_CLASS_CLIENT,
"SUBMIT" ),
SubsystemInfoLookup( SUBSYSTEM_TYPE_JOB, SUBSYSTEM_CLASS_JOB,
"JOB" ),
SubsystemInfoLookup( SUBSYSTEM_TYPE_DAEMON, SUBSYSTEM_CLASS_DAEMON,
"DAEMON", "" /* empty string, match anything */ ),
SubsystemInfoLookup( SUBSYSTEM_TYPE_INVALID, SUBSYSTEM_CLASS_NONE,
"INVALID" )
};
SubsystemInfoTable::SubsystemInfoTable(void)
{
int num = ( sizeof(m_Table) / sizeof(SubsystemInfoLookup) );
m_Invalid = &m_Table[num - 1];
ASSERT( m_Invalid != NULL );
ASSERT( m_Invalid->match(SUBSYSTEM_TYPE_INVALID) );
}
// Internal method to lookup by SubsystemType
const SubsystemInfoLookup *
SubsystemInfoTable::lookup( SubsystemType _type ) const
{
const SubsystemInfoLookup *cur;
for ( cur = m_Table; cur->isValid(); cur++ ) {
if ( cur->match(_type) ) {
return cur;
}
}
return m_Invalid;
}
// Internal method to lookup by SubsystemClass
const SubsystemInfoLookup *
SubsystemInfoTable::lookup( SubsystemClass _class ) const
{
const SubsystemInfoLookup *cur;
for ( cur = m_Table; cur->isValid(); cur++ ) {
if ( cur->match(_class) ) {
return cur;
}
}
return m_Invalid;
}
const SubsystemInfoLookup *
// Lookup by name
SubsystemInfoTable::lookup( const char *_name ) const
{
const SubsystemInfoLookup *cur;
for ( cur = m_Table; cur->isValid(); cur++ ) {
if ( cur->match(_name) ) {
return cur;
}
}
for ( cur = m_Table; cur->isValid(); cur++ ) {
if ( cur->matchSubstr(_name) ) {
return cur;
}
}
// Return the invalid entry
return m_Invalid;
}
static const SubsystemInfoTable *infoTable = new SubsystemInfoTable( );
//
// C++ SubsystemInfo methods
//
SubsystemInfo::SubsystemInfo( const char *_name, SubsystemType _type )
{
m_Name = NULL;
m_TempName = NULL;
m_LocalName = NULL;
setName( _name );
if ( _type == SUBSYSTEM_TYPE_AUTO ) {
setTypeFromName( _name );
}
else {
setType( _type );
}
}
SubsystemInfo::~SubsystemInfo( void )
{
if ( m_Name ) {
free( const_cast<char *>( m_Name ) );
m_Name = NULL;
}
}
bool
SubsystemInfo::nameMatch( const char *_name ) const
{
return ( strcasecmp(_name, m_Name) == 0 );
}
const char *
SubsystemInfo::setName( const char *_name )
{
if ( _name != NULL ) {
m_Name = strdup(_name);
m_NameValid = true ;
}
else {
m_Name = strdup("UNKNOWN"); // Fill in a value so it's not NULL
m_NameValid = false;
}
return m_Name;
}
// Temp name handling
const char *
SubsystemInfo::setTempName( const char *_name )
{
resetTempName( );
if ( _name ) {
m_TempName = strdup( _name );
}
return m_TempName;
}
void
SubsystemInfo::resetTempName( void )
{
if ( m_TempName ) {
free( const_cast<char*>(m_TempName) );
m_TempName = NULL;
}
}
// Public interface to set the type from a name
SubsystemType
SubsystemInfo::setTypeFromName( const char *_type_name )
{
if ( NULL == _type_name ) {
_type_name = m_Name;
}
if ( NULL == _type_name ) {
return setType( SUBSYSTEM_TYPE_DAEMON );
}
// First, look for an exact match
const SubsystemInfoLookup *match = infoTable->lookup( _type_name );
if ( match ) {
return setType( match, _type_name );
}
return setType( SUBSYSTEM_TYPE_DAEMON, _type_name );
}
// Public set type method
SubsystemType
SubsystemInfo::setType( SubsystemType _type )
{
return setType( _type, NULL );
}
// Internal set type method
SubsystemType
SubsystemInfo::setType( SubsystemType _type, const char *_type_name )
{
return setType( infoTable->lookup(_type), _type_name );
}
// Internal set type method
SubsystemType
SubsystemInfo::setType( const SubsystemInfoLookup *info,
const char *type_name )
{
m_Type = info->getType();
setClass( info );
m_Info = info;
if ( type_name != NULL ) {
m_TypeName = type_name;
}
else {
m_TypeName = info->getTypeName();
}
return m_Type;
}
// Internal set class method
SubsystemClass
SubsystemInfo::setClass( const SubsystemInfoLookup *info )
{
static const char *_class_names[] = {
"None",
"DAEMON",
"CLIENT",
"JOB"
};
static int _num = ( sizeof(_class_names) / sizeof(const char *) );
m_Class = info->getClass();
ASSERT ( ( m_Class >= 0 ) && ( m_Class <= _num ) );
m_ClassName = _class_names[m_Class];
return m_Class;
}
// Methods to get/set the local name
const char *
SubsystemInfo::getLocalName( const char * _default ) const
{
if ( m_LocalName ) {
return m_LocalName;
}
else {
return _default;
}
}
const char *
SubsystemInfo::setLocalName( const char * _name )
{
if ( m_LocalName ) {
free( const_cast<char *>( m_LocalName ) );
m_LocalName = NULL;
}
m_LocalName = strdup(_name);
return m_LocalName;
}
// Public dprintf / printf methods
void
SubsystemInfo::dprintf( int level ) const
{
::dprintf( level, "%s\n", getString() );
}
void
SubsystemInfo::printf( void ) const
{
::printf( "%s\n", getString() );
}
const char *
SubsystemInfo::getString( void ) const
{
static char buf[128];
const char *type_name = "UNKNOWN";
if ( m_Info ) {
type_name = m_Info->getTypeName();
}
snprintf( buf, sizeof(buf),
"SubsystemInfo: name=%s type=%s(%d) class=%s(%d)",
m_Name, type_name, m_Type, m_ClassName, m_Class );
return buf;
}
/* Helper function to retrieve the value of mySubSystem global variable
* from C functions. This is helpful because mySubSystem is decorated w/ C++
* linkage.
*/
extern "C" {
const char* get_mySubSystem(void) { return mySubSystem->getName(); }
SubsystemType get_mySubsystemType(void) { return mySubSystem->getType(); }
}
<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
//////////////////////////////////////////////////////////////////////////
#include "stdsneezy.h"
#include "statistics.h"
#include "database.h"
extern FILE *obj_f;
extern FILE *mob_f;
vector<mobIndexData>mob_index(0);
vector<objIndexData>obj_index(0);
indexData::indexData() :
virt(0),
pos(0),
number(0),
name(NULL),
short_desc(NULL),
long_desc(NULL),
description(NULL),
max_exist(-99),
spec(0),
weight(0)
{
}
indexData & indexData::operator= (const indexData &a)
{
if (this == &a)
return *this;
virt = a.virt;
pos = a.pos;
number = a.number;
delete [] name;
delete [] short_desc;
delete [] long_desc;
delete [] description;
name = mud_str_dup(a.name);
short_desc = mud_str_dup(a.short_desc);
long_desc = mud_str_dup(a.long_desc);
description = mud_str_dup(a.description);
max_exist = a.max_exist;
spec = a.spec;
weight = a.weight;
return *this;
}
indexData::indexData(const indexData &a) :
virt(a.virt),
pos(a.pos),
number(a.number),
max_exist(a.max_exist),
spec(a.spec),
weight(a.weight)
{
name = mud_str_dup(a.name);
short_desc = mud_str_dup(a.short_desc);
long_desc = mud_str_dup(a.long_desc);
description = mud_str_dup(a.description);
}
indexData::~indexData()
{
delete [] name;
delete [] short_desc;
delete [] long_desc;
delete [] description;
}
mobIndexData::mobIndexData() :
faction(-99),
Class(-99),
level(-99),
race(-99),
doesLoad(false)
{
}
mobIndexData & mobIndexData::operator= (const mobIndexData &a)
{
if (this == &a)
return *this;
indexData::operator=(a);
faction = a.faction;
Class = a.Class;
level = a.level;
race = a.race;
doesLoad = a.doesLoad;
return *this;
}
mobIndexData::mobIndexData(const mobIndexData &a) :
indexData(a),
faction(a.faction),
Class(a.Class),
level(a.level),
race(a.race),
doesLoad(a.doesLoad)
{
}
mobIndexData::~mobIndexData()
{
}
objIndexData::objIndexData() :
ex_description(NULL),
max_struct(-99),
armor(-99),
where_worn(0),
itemtype(MAX_OBJ_TYPES),
value(-99)
{
}
objIndexData & objIndexData::operator= (const objIndexData &a)
{
if (this == &a)
return *this;
indexData::operator=(a);
// use copy operator;
if (a.ex_description)
ex_description = new extraDescription(*a.ex_description);
else
ex_description = NULL;
max_struct = a.max_struct;
armor = a.armor;
where_worn = a.where_worn;
itemtype = a.itemtype;
value = a.value;
int i;
for(i=0;i<MAX_OBJ_AFFECT;++i){
affected[i]=a.affected[i];
}
return *this;
}
objIndexData::objIndexData(const objIndexData &a) :
indexData(a),
max_struct(a.max_struct),
armor(a.armor),
where_worn(a.where_worn),
itemtype(a.itemtype),
value(a.value)
{
// use copy operator;
if (a.ex_description)
ex_description = new extraDescription(*a.ex_description);
else
ex_description = NULL;
int i;
for(i=0;i<MAX_OBJ_AFFECT;++i){
affected[i]=a.affected[i];
}
}
objIndexData::~objIndexData()
{
extraDescription *tmp;
while ((tmp = ex_description)) {
ex_description = tmp->next;
delete tmp;
}
}
// generate index table for object
void generate_obj_index()
{
objIndexData *tmpi = NULL;
extraDescription *new_descr;
int i=0;
// to prevent constant resizing (slows boot), declare an appropriate initial
// size. Should be smallest power of 2 that will hold everything
obj_index.reserve(8192);
/****** extra ******/
TDatabase extra_db(DB_SNEEZY);
extra_db.query("select vnum, name, description from objextra order by vnum");
extra_db.fetchRow();
/****** affect ******/
TDatabase affect_db(DB_SNEEZY);
affect_db.query("select vnum, type, mod1, mod2 from objaffect order by vnum");
affect_db.fetchRow();
/********************/
TDatabase db(DB_SNEEZY);
db.query("select vnum, name, short_desc, long_desc, max_exist, spec_proc, weight, max_struct, wear_flag, type, price, action_desc from obj order by vnum");
while(db.fetchRow()){
tmpi = new objIndexData();
if (!tmpi) {
perror("indexData");
exit(0);
}
tmpi->virt=convertTo<int>(db["vnum"]);
tmpi->name=mud_str_dup(db["name"]);
tmpi->short_desc=mud_str_dup(db["short_desc"]);
tmpi->long_desc=mud_str_dup(db["long_desc"]);
tmpi->max_exist=convertTo<int>(db["max_exist"]);
// use 327 so we don't go over 32765 in calculation
if (tmpi->max_exist < 327) {
tmpi->max_exist *= (sh_int) (stats.max_exist * 100);
tmpi->max_exist /= 100;
}
if (tmpi->max_exist)
tmpi->max_exist = max(tmpi->max_exist, (short int) (gamePort == BETA_GAMEPORT ? 9999 : 1));
tmpi->spec=convertTo<int>(db["spec_proc"]);
tmpi->weight=convertTo<float>(db["weight"]);
tmpi->max_struct=convertTo<int>(db["max_struct"]);
tmpi->where_worn=convertTo<int>(db["wear_flag"]);
tmpi->itemtype=convertTo<int>(db["type"]);
tmpi->value=convertTo<int>(db["price"]);
if(strcmp(db["action_desc"], "")) tmpi->description=mud_str_dup(db["action_desc"]);
else tmpi->description=NULL;
while(extra_db["vnum"] && convertTo<int>(extra_db["vnum"])==tmpi->virt){
new_descr = new extraDescription();
new_descr->keyword = mud_str_dup(extra_db["name"]);
new_descr->description = mud_str_dup(extra_db["description"]);
new_descr->next = tmpi->ex_description;
tmpi->ex_description = new_descr;
extra_db.fetchRow();
}
i=0;
while(affect_db["vnum"] && convertTo<int>(affect_db["vnum"])==tmpi->virt){
tmpi->affected[i].location = mapFileToApply(convertTo<int>(affect_db["type"]));
if (tmpi->affected[i].location == APPLY_SPELL)
tmpi->affected[i].modifier = mapFileToSpellnum(convertTo<int>(affect_db["mod1"]));
else
tmpi->affected[i].modifier = convertTo<int>(affect_db["mod1"]);
tmpi->affected[i].modifier2 = convertTo<int>(affect_db["mod2"]);
tmpi->affected[i].type = TYPE_UNDEFINED;
tmpi->affected[i].level = 0;
tmpi->affected[i].bitvector = 0;
affect_db.fetchRow();
i++;
}
obj_index.push_back(*tmpi);
delete tmpi;
}
return;
}
// generate index table for monster file
void generate_mob_index()
{
char buf[256];
mobIndexData *tmpi = NULL;
// to prevent constant resizing (slows boot), declare an appropriate initial
// size. Should be smallest power of 2 that will hold everything
mob_index.reserve(4096);
rewind(mob_f);
// start by reading
if (fgets(buf, sizeof(buf)-1, mob_f) == NULL)
return;
for (;;) {
int bc;
if (*buf == '#') {
if (tmpi) {
// push the previous one into the stack
mob_index.push_back(*tmpi);
delete tmpi;
}
sscanf(buf, "#%d", &bc);
if (bc >= 99999) // terminator
break;
// start a new data member
tmpi = new mobIndexData();
if (!tmpi) {
perror("mobIndexData");
exit(0);
}
tmpi->virt = bc;
tmpi->pos = ftell(mob_f);
// read the sstrings
tmpi->name = fread_string(mob_f);
tmpi->short_desc = fread_string(mob_f);
tmpi->long_desc = fread_string(mob_f);
tmpi->description = fread_string(mob_f);
int rc;
long spac;
long spaf;
long fac;
float facp;
char let;
float mult;
rc = fscanf(mob_f, "%ld %ld %ld %f %c %f\n",
&spac, &spaf, &fac, &facp, &let, &mult);
if (rc != 6) {
vlogf(LOG_BUG, "Error during mobIndexSetup(1) %d", bc);
exit(0);
}
tmpi->faction = fac;
long Class;
long lev;
long hitr;
float arm;
float hp;
float daml;
int damp;
rc = fscanf(mob_f, "%ld %ld %ld %f %f %f+%d \n",
&Class, &lev, &hitr, &arm, &hp, &daml, &damp);
if (rc != 7) {
vlogf(LOG_BUG, "Error during mobIndexSetup(2) %d (rc=%d)", bc, rc);
exit(0);
}
lev = (long)((arm + hp + daml) / 3);
tmpi->Class = Class;
tmpi->level = lev;
long mon;
long race;
long wgt;
long hgt;
rc = fscanf(mob_f, "%ld %ld %ld %ld \n",
&mon, &race, &wgt, &hgt);
if (rc != 4) {
vlogf(LOG_BUG, "Error during mobIndexSetup(3) %d", bc);
exit(0);
}
tmpi->race = race;
tmpi->weight = wgt;
long some_stat;
statTypeT local_stat;
for (local_stat = MIN_STAT; local_stat < MAX_STATS_USED; local_stat++)
fscanf(mob_f, " %ld ", &some_stat);
long mpos;
long dpos;
long sex;
long spec;
rc = fscanf(mob_f, "%ld %ld %ld %ld \n",
&mpos, &dpos, &sex, &spec);
if (rc != 4) {
vlogf(LOG_BUG, "Error during mobIndexSetup(4) %d", bc);
exit(0);
}
tmpi->spec = spec;
long some_imm;
immuneTypeT local_imm;
for (local_imm = MIN_IMMUNE; local_imm < MAX_IMMUNES; local_imm++)
fscanf(mob_f, " %ld ", &some_imm);
long mat;
long cbs;
long vis;
long maxe;
rc = fscanf(mob_f, "%ld %ld %ld %ld \n",
&mat, &cbs, &vis, &maxe);
if (rc != 4) {
vlogf(LOG_BUG, "Error during mobIndexSetup(5) %d", bc);
exit(0);
}
tmpi->max_exist = (gamePort == BETA_GAMEPORT ? 9999 : maxe);
// check for sounds and just account for them if found
if (let == 'L') {
char * snds = fread_string(mob_f);
char * dsts = fread_string(mob_f);
delete [] snds;
delete [] dsts;
}
// handle some stat counters
if (lev <= 5) {
stats.mobs_1_5++;
} else if (lev <= 10) {
stats.mobs_6_10++;
} else if (lev <= 15) {
stats.mobs_11_15++;
} else if (lev <= 20) {
stats.mobs_16_20++;
} else if (lev <= 25) {
stats.mobs_21_25++;
} else if (lev <= 30) {
stats.mobs_26_30++;
} else if (lev <= 40) {
stats.mobs_31_40++;
} else if (lev <= 50) {
stats.mobs_41_50++;
} else if (lev <= 60) {
stats.mobs_51_60++;
} else if (lev <= 70) {
stats.mobs_61_70++;
} else if (lev <= 100) {
stats.mobs_71_100++;
} else {
stats.mobs_101_127++;
}
// end stat counters
}
// setup for next critter
if (fgets(buf, sizeof(buf)-1, mob_f) == NULL) {
vlogf(LOG_BUG, "Error during mobIndexSetup(6) %d", bc);
exit(0);
}
}
return;
}
<commit_msg>put in a fix so that we don't get screwed up loading the object index if an object has affects/extras but no actual object entry<commit_after>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
//////////////////////////////////////////////////////////////////////////
#include "stdsneezy.h"
#include "statistics.h"
#include "database.h"
extern FILE *obj_f;
extern FILE *mob_f;
vector<mobIndexData>mob_index(0);
vector<objIndexData>obj_index(0);
indexData::indexData() :
virt(0),
pos(0),
number(0),
name(NULL),
short_desc(NULL),
long_desc(NULL),
description(NULL),
max_exist(-99),
spec(0),
weight(0)
{
}
indexData & indexData::operator= (const indexData &a)
{
if (this == &a)
return *this;
virt = a.virt;
pos = a.pos;
number = a.number;
delete [] name;
delete [] short_desc;
delete [] long_desc;
delete [] description;
name = mud_str_dup(a.name);
short_desc = mud_str_dup(a.short_desc);
long_desc = mud_str_dup(a.long_desc);
description = mud_str_dup(a.description);
max_exist = a.max_exist;
spec = a.spec;
weight = a.weight;
return *this;
}
indexData::indexData(const indexData &a) :
virt(a.virt),
pos(a.pos),
number(a.number),
max_exist(a.max_exist),
spec(a.spec),
weight(a.weight)
{
name = mud_str_dup(a.name);
short_desc = mud_str_dup(a.short_desc);
long_desc = mud_str_dup(a.long_desc);
description = mud_str_dup(a.description);
}
indexData::~indexData()
{
delete [] name;
delete [] short_desc;
delete [] long_desc;
delete [] description;
}
mobIndexData::mobIndexData() :
faction(-99),
Class(-99),
level(-99),
race(-99),
doesLoad(false)
{
}
mobIndexData & mobIndexData::operator= (const mobIndexData &a)
{
if (this == &a)
return *this;
indexData::operator=(a);
faction = a.faction;
Class = a.Class;
level = a.level;
race = a.race;
doesLoad = a.doesLoad;
return *this;
}
mobIndexData::mobIndexData(const mobIndexData &a) :
indexData(a),
faction(a.faction),
Class(a.Class),
level(a.level),
race(a.race),
doesLoad(a.doesLoad)
{
}
mobIndexData::~mobIndexData()
{
}
objIndexData::objIndexData() :
ex_description(NULL),
max_struct(-99),
armor(-99),
where_worn(0),
itemtype(MAX_OBJ_TYPES),
value(-99)
{
}
objIndexData & objIndexData::operator= (const objIndexData &a)
{
if (this == &a)
return *this;
indexData::operator=(a);
// use copy operator;
if (a.ex_description)
ex_description = new extraDescription(*a.ex_description);
else
ex_description = NULL;
max_struct = a.max_struct;
armor = a.armor;
where_worn = a.where_worn;
itemtype = a.itemtype;
value = a.value;
int i;
for(i=0;i<MAX_OBJ_AFFECT;++i){
affected[i]=a.affected[i];
}
return *this;
}
objIndexData::objIndexData(const objIndexData &a) :
indexData(a),
max_struct(a.max_struct),
armor(a.armor),
where_worn(a.where_worn),
itemtype(a.itemtype),
value(a.value)
{
// use copy operator;
if (a.ex_description)
ex_description = new extraDescription(*a.ex_description);
else
ex_description = NULL;
int i;
for(i=0;i<MAX_OBJ_AFFECT;++i){
affected[i]=a.affected[i];
}
}
objIndexData::~objIndexData()
{
extraDescription *tmp;
while ((tmp = ex_description)) {
ex_description = tmp->next;
delete tmp;
}
}
// generate index table for object
void generate_obj_index()
{
objIndexData *tmpi = NULL;
extraDescription *new_descr;
int i=0;
// to prevent constant resizing (slows boot), declare an appropriate initial
// size. Should be smallest power of 2 that will hold everything
obj_index.reserve(8192);
/****** extra ******/
TDatabase extra_db(DB_SNEEZY);
extra_db.query("select vnum, name, description from objextra order by vnum");
extra_db.fetchRow();
/****** affect ******/
TDatabase affect_db(DB_SNEEZY);
affect_db.query("select vnum, type, mod1, mod2 from objaffect order by vnum");
affect_db.fetchRow();
/********************/
TDatabase db(DB_SNEEZY);
db.query("select vnum, name, short_desc, long_desc, max_exist, spec_proc, weight, max_struct, wear_flag, type, price, action_desc from obj order by vnum");
while(db.fetchRow()){
tmpi = new objIndexData();
if (!tmpi) {
perror("indexData");
exit(0);
}
tmpi->virt=convertTo<int>(db["vnum"]);
tmpi->name=mud_str_dup(db["name"]);
tmpi->short_desc=mud_str_dup(db["short_desc"]);
tmpi->long_desc=mud_str_dup(db["long_desc"]);
tmpi->max_exist=convertTo<int>(db["max_exist"]);
// use 327 so we don't go over 32765 in calculation
if (tmpi->max_exist < 327) {
tmpi->max_exist *= (sh_int) (stats.max_exist * 100);
tmpi->max_exist /= 100;
}
if (tmpi->max_exist)
tmpi->max_exist = max(tmpi->max_exist, (short int) (gamePort == BETA_GAMEPORT ? 9999 : 1));
tmpi->spec=convertTo<int>(db["spec_proc"]);
tmpi->weight=convertTo<float>(db["weight"]);
tmpi->max_struct=convertTo<int>(db["max_struct"]);
tmpi->where_worn=convertTo<int>(db["wear_flag"]);
tmpi->itemtype=convertTo<int>(db["type"]);
tmpi->value=convertTo<int>(db["price"]);
if(strcmp(db["action_desc"], "")) tmpi->description=mud_str_dup(db["action_desc"]);
else tmpi->description=NULL;
while(extra_db["vnum"] && convertTo<int>(extra_db["vnum"]) < tmpi->virt){
extra_db.fetchRow();
}
while(extra_db["vnum"] && convertTo<int>(extra_db["vnum"])==tmpi->virt){
new_descr = new extraDescription();
new_descr->keyword = mud_str_dup(extra_db["name"]);
new_descr->description = mud_str_dup(extra_db["description"]);
new_descr->next = tmpi->ex_description;
tmpi->ex_description = new_descr;
extra_db.fetchRow();
}
while(affect_db["vnum"] && convertTo<int>(affect_db["vnum"]) < tmpi->virt){
affect_db.fetchRow();
}
i=0;
while(affect_db["vnum"] && convertTo<int>(affect_db["vnum"])==tmpi->virt){
tmpi->affected[i].location = mapFileToApply(convertTo<int>(affect_db["type"]));
if (tmpi->affected[i].location == APPLY_SPELL)
tmpi->affected[i].modifier = mapFileToSpellnum(convertTo<int>(affect_db["mod1"]));
else
tmpi->affected[i].modifier = convertTo<int>(affect_db["mod1"]);
tmpi->affected[i].modifier2 = convertTo<int>(affect_db["mod2"]);
tmpi->affected[i].type = TYPE_UNDEFINED;
tmpi->affected[i].level = 0;
tmpi->affected[i].bitvector = 0;
affect_db.fetchRow();
i++;
}
obj_index.push_back(*tmpi);
delete tmpi;
}
return;
}
// generate index table for monster file
void generate_mob_index()
{
char buf[256];
mobIndexData *tmpi = NULL;
// to prevent constant resizing (slows boot), declare an appropriate initial
// size. Should be smallest power of 2 that will hold everything
mob_index.reserve(4096);
rewind(mob_f);
// start by reading
if (fgets(buf, sizeof(buf)-1, mob_f) == NULL)
return;
for (;;) {
int bc;
if (*buf == '#') {
if (tmpi) {
// push the previous one into the stack
mob_index.push_back(*tmpi);
delete tmpi;
}
sscanf(buf, "#%d", &bc);
if (bc >= 99999) // terminator
break;
// start a new data member
tmpi = new mobIndexData();
if (!tmpi) {
perror("mobIndexData");
exit(0);
}
tmpi->virt = bc;
tmpi->pos = ftell(mob_f);
// read the sstrings
tmpi->name = fread_string(mob_f);
tmpi->short_desc = fread_string(mob_f);
tmpi->long_desc = fread_string(mob_f);
tmpi->description = fread_string(mob_f);
int rc;
long spac;
long spaf;
long fac;
float facp;
char let;
float mult;
rc = fscanf(mob_f, "%ld %ld %ld %f %c %f\n",
&spac, &spaf, &fac, &facp, &let, &mult);
if (rc != 6) {
vlogf(LOG_BUG, "Error during mobIndexSetup(1) %d", bc);
exit(0);
}
tmpi->faction = fac;
long Class;
long lev;
long hitr;
float arm;
float hp;
float daml;
int damp;
rc = fscanf(mob_f, "%ld %ld %ld %f %f %f+%d \n",
&Class, &lev, &hitr, &arm, &hp, &daml, &damp);
if (rc != 7) {
vlogf(LOG_BUG, "Error during mobIndexSetup(2) %d (rc=%d)", bc, rc);
exit(0);
}
lev = (long)((arm + hp + daml) / 3);
tmpi->Class = Class;
tmpi->level = lev;
long mon;
long race;
long wgt;
long hgt;
rc = fscanf(mob_f, "%ld %ld %ld %ld \n",
&mon, &race, &wgt, &hgt);
if (rc != 4) {
vlogf(LOG_BUG, "Error during mobIndexSetup(3) %d", bc);
exit(0);
}
tmpi->race = race;
tmpi->weight = wgt;
long some_stat;
statTypeT local_stat;
for (local_stat = MIN_STAT; local_stat < MAX_STATS_USED; local_stat++)
fscanf(mob_f, " %ld ", &some_stat);
long mpos;
long dpos;
long sex;
long spec;
rc = fscanf(mob_f, "%ld %ld %ld %ld \n",
&mpos, &dpos, &sex, &spec);
if (rc != 4) {
vlogf(LOG_BUG, "Error during mobIndexSetup(4) %d", bc);
exit(0);
}
tmpi->spec = spec;
long some_imm;
immuneTypeT local_imm;
for (local_imm = MIN_IMMUNE; local_imm < MAX_IMMUNES; local_imm++)
fscanf(mob_f, " %ld ", &some_imm);
long mat;
long cbs;
long vis;
long maxe;
rc = fscanf(mob_f, "%ld %ld %ld %ld \n",
&mat, &cbs, &vis, &maxe);
if (rc != 4) {
vlogf(LOG_BUG, "Error during mobIndexSetup(5) %d", bc);
exit(0);
}
tmpi->max_exist = (gamePort == BETA_GAMEPORT ? 9999 : maxe);
// check for sounds and just account for them if found
if (let == 'L') {
char * snds = fread_string(mob_f);
char * dsts = fread_string(mob_f);
delete [] snds;
delete [] dsts;
}
// handle some stat counters
if (lev <= 5) {
stats.mobs_1_5++;
} else if (lev <= 10) {
stats.mobs_6_10++;
} else if (lev <= 15) {
stats.mobs_11_15++;
} else if (lev <= 20) {
stats.mobs_16_20++;
} else if (lev <= 25) {
stats.mobs_21_25++;
} else if (lev <= 30) {
stats.mobs_26_30++;
} else if (lev <= 40) {
stats.mobs_31_40++;
} else if (lev <= 50) {
stats.mobs_41_50++;
} else if (lev <= 60) {
stats.mobs_51_60++;
} else if (lev <= 70) {
stats.mobs_61_70++;
} else if (lev <= 100) {
stats.mobs_71_100++;
} else {
stats.mobs_101_127++;
}
// end stat counters
}
// setup for next critter
if (fgets(buf, sizeof(buf)-1, mob_f) == NULL) {
vlogf(LOG_BUG, "Error during mobIndexSetup(6) %d", bc);
exit(0);
}
}
return;
}
<|endoftext|> |
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2010, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_debug.h"
#include "condor_config.h"
#include "condor_string.h"
#include "env.h"
#include "condor_cron_param.h"
#include "condor_cron_job_mgr.h"
#include "condor_cron_job_mode.h"
#include "condor_cron_job_params.h"
CronJobParams::CronJobParams( const char *job_name,
const CronJobMgr &mgr )
: CronParamBase( *(mgr.GetName()) ),
m_mgr( mgr ),
m_mode( CRON_ILLEGAL ),
m_modestr( NULL ),
m_job( NULL ),
m_name( job_name ),
m_period( UINT_MAX ),
m_jobLoad( CronJobDefaultLoad ), // Default near zero
m_optKill( false ),
m_optReconfig( false ),
m_optReconfigRerun( false ),
m_optIdle( false )
{
}
CronJobParams::~CronJobParams( void )
{
}
const char *
CronJobParams::GetParamName( const char *item ) const
{
// Build the name of the parameter to read
unsigned len = ( strlen( &m_base ) +
1 + // '_'
m_name.Length( ) +
1 + // '_'
strlen( item ) +
1 ); // '\0'
if ( len > sizeof(m_name_buf) ) {
return NULL;
}
strcpy( m_name_buf, &m_base );
strcat( m_name_buf, "_" );
strcat( m_name_buf, m_name.Value() );
strcat( m_name_buf, "_" );
strcat( m_name_buf, item );
return m_name_buf;
}
bool
CronJobParams::Initialize( void )
{
MyString param_prefix;
MyString param_executable;
MyString param_period;
MyString param_mode;
bool param_reconfig = false;
bool param_reconfig_rerun = false;
bool param_kill_mode = false;
MyString param_args;
MyString param_env;
MyString param_cwd;
double param_job_load;
Lookup( "PREFIX", param_prefix );
Lookup( "EXECUTABLE", param_executable );
Lookup( "PERIOD", param_period );
Lookup( "MODE", param_mode );
Lookup( "RECONFIG", param_reconfig );
Lookup( "RECONFIG_RERUN", param_reconfig_rerun );
Lookup( "KILL", param_kill_mode );
Lookup( "ARGS", param_args );
Lookup( "ENV", param_env );
Lookup( "CWD", param_cwd );
Lookup( "JOB_LOAD", param_job_load, 0.01, 0, 100.0 );
// Some quick sanity checks
if ( param_executable.IsEmpty() ) {
dprintf( D_ALWAYS,
"CronJobParams: No path found for job '%s'; skipping\n",
GetName() );
return false;
}
// Parse the job mode
m_mode = DefaultJobMode( );
if ( ! param_mode.IsEmpty() ) {
const CronJobModeTable &mt = GetCronJobModeTable( );
const CronJobModeTableEntry *mte = mt.Find( param_mode.Value() );
if ( NULL == mte ) {
dprintf( D_ALWAYS,
"CronJobParams: Unknown job mode for '%s'\n",
GetName() );
return false;
} else {
m_mode = mte->Mode();
m_modestr = mte->Name();
}
}
// Initialize the period
if ( !InitPeriod( param_period ) ) {
dprintf( D_ALWAYS,
"CronJobParams: Failed to initialize period for job %s\n",
GetName() );
return false;
}
// Are there arguments for it?
if ( !InitArgs( param_args ) ) {
dprintf( D_ALWAYS,
"CronJobParams: Failed to initialize arguments for job %s\n",
GetName() );
return false;
}
// Parse the environment.
if ( !InitEnv( param_args ) ) {
dprintf( D_ALWAYS,
"CronJobParams: Failed to initialize arguments for job %s\n",
GetName() );
return false;
}
m_prefix = param_prefix;
m_executable = param_executable;
m_cwd = param_cwd;
m_jobLoad = param_job_load;
m_optKill = param_kill_mode;
m_optReconfig = param_reconfig;
m_optReconfigRerun = param_reconfig_rerun;
return true;
}
bool
CronJobParams::InitArgs( const MyString ¶m_args )
{
ArgList args;
MyString args_errors;
// Force the first arg to be the "Job Name"..
m_args.Clear();
if( !args.AppendArgsV1RawOrV2Quoted( param_args.Value(),
&args_errors ) ) {
dprintf( D_ALWAYS,
"CronJobParams: Job '%s': "
"Failed to parse arguments: '%s'\n",
GetName(), args_errors.Value());
return false;
}
return AddArgs( args );
}
bool
CronJobParams::InitEnv( const MyString ¶m_env )
{
Env env_object;
MyString env_error_msg;
m_env.Clear();
if( !env_object.MergeFromV1RawOrV2Quoted( param_env.Value(),
&env_error_msg ) ) {
dprintf( D_ALWAYS,
"CronJobParams: Job '%s': "
"Failed to parse environment: '%s'\n",
GetName(), env_error_msg.Value());
return false;
}
return AddEnv( env_object );
}
// Set job's period
bool
CronJobParams::InitPeriod( const MyString ¶m_period )
{
// Find the job period
m_period = 0;
if ( ( m_mode == CRON_ONE_SHOT) || ( m_mode == CRON_ON_DEMAND) ) {
if ( ! param_period.IsEmpty() ) {
dprintf( D_ALWAYS,
"CronJobParams: Warning:"
"Ignoring job period specified for '%s'\n",
GetName() );
return true;
}
}
else if ( param_period.IsEmpty() ) {
dprintf( D_ALWAYS,
"CronJobParams: No job period found for job '%s': skipping\n",
GetName() );
return false;
} else {
char modifier = 'S';
int num = sscanf( param_period.Value(), "%d%c",
&m_period, &modifier );
if ( num < 1 ) {
dprintf( D_ALWAYS,
"CronJobParams: Invalid job period found "
"for job '%s' (%s): skipping\n",
GetName(), param_period.Value() );
return false;
} else {
// Check the modifier
modifier = toupper( modifier );
if ( ( 'S' == modifier ) ) { // Seconds
// Do nothing
} else if ( 'M' == modifier ) {
m_period *= 60;
} else if ( 'H' == modifier ) {
m_period *= ( 60 * 60 );
} else {
dprintf( D_ALWAYS,
"CronJobParams: Invalid period modifier "
"'%c' for job %s (%s)\n",
modifier, GetName(), param_period.Value() );
return false;
}
}
}
// Verify that the mode seleted is valid
if ( IsPeriodic() && (0 == m_period) ) {
dprintf( D_ALWAYS,
"Cron: Job '%s'; Periodic requires non-zero period\n",
GetName() );
return false;
}
// Verify that the mode seleted is valid
if ( IsPeriodic() && (0 == m_period) ) {
dprintf( D_ALWAYS,
"Cron: Job '%s'; Periodic requires non-zero period\n",
GetName() );
return false;
}
return true;
}
bool
CronJobParams::AddEnv( Env const &env )
{
m_env.MergeFrom( env );
return true;
}
// Add to the job's arg list
bool
CronJobParams::AddArgs( const ArgList &new_args )
{
m_args.AppendArgsFromArgList(new_args);
return true;
}
const char *
CronJobParams::GetModeString( void ) const
{
return m_modestr;
}
<commit_msg>Fixed a bug that caused the Daemon ClassAd Hooks to param for job parameters using the wrong name (only if the sepcific Hook manager is not 'named') #1947<commit_after>/***************************************************************
*
* Copyright (C) 1990-2010, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* 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 "condor_common.h"
#include "condor_debug.h"
#include "condor_config.h"
#include "condor_string.h"
#include "env.h"
#include "condor_cron_param.h"
#include "condor_cron_job_mgr.h"
#include "condor_cron_job_mode.h"
#include "condor_cron_job_params.h"
CronJobParams::CronJobParams( const char *job_name,
const CronJobMgr &mgr )
: CronParamBase( *(mgr.GetParamBase()) ),
m_mgr( mgr ),
m_mode( CRON_ILLEGAL ),
m_modestr( NULL ),
m_job( NULL ),
m_name( job_name ),
m_period( UINT_MAX ),
m_jobLoad( CronJobDefaultLoad ), // Default near zero
m_optKill( false ),
m_optReconfig( false ),
m_optReconfigRerun( false ),
m_optIdle( false )
{
}
CronJobParams::~CronJobParams( void )
{
}
const char *
CronJobParams::GetParamName( const char *item ) const
{
// Build the name of the parameter to read
unsigned len = ( strlen( &m_base ) +
1 + // '_'
m_name.Length( ) +
1 + // '_'
strlen( item ) +
1 ); // '\0'
if ( len > sizeof(m_name_buf) ) {
return NULL;
}
strcpy( m_name_buf, &m_base );
strcat( m_name_buf, "_" );
strcat( m_name_buf, m_name.Value() );
strcat( m_name_buf, "_" );
strcat( m_name_buf, item );
return m_name_buf;
}
bool
CronJobParams::Initialize( void )
{
MyString param_prefix;
MyString param_executable;
MyString param_period;
MyString param_mode;
bool param_reconfig = false;
bool param_reconfig_rerun = false;
bool param_kill_mode = false;
MyString param_args;
MyString param_env;
MyString param_cwd;
double param_job_load;
Lookup( "PREFIX", param_prefix );
Lookup( "EXECUTABLE", param_executable );
Lookup( "PERIOD", param_period );
Lookup( "MODE", param_mode );
Lookup( "RECONFIG", param_reconfig );
Lookup( "RECONFIG_RERUN", param_reconfig_rerun );
Lookup( "KILL", param_kill_mode );
Lookup( "ARGS", param_args );
Lookup( "ENV", param_env );
Lookup( "CWD", param_cwd );
Lookup( "JOB_LOAD", param_job_load, 0.01, 0, 100.0 );
// Some quick sanity checks
if ( param_executable.IsEmpty() ) {
dprintf( D_ALWAYS,
"CronJobParams: No path found for job '%s'; skipping\n",
GetName() );
return false;
}
// Parse the job mode
m_mode = DefaultJobMode( );
if ( ! param_mode.IsEmpty() ) {
const CronJobModeTable &mt = GetCronJobModeTable( );
const CronJobModeTableEntry *mte = mt.Find( param_mode.Value() );
if ( NULL == mte ) {
dprintf( D_ALWAYS,
"CronJobParams: Unknown job mode for '%s'\n",
GetName() );
return false;
} else {
m_mode = mte->Mode();
m_modestr = mte->Name();
}
}
// Initialize the period
if ( !InitPeriod( param_period ) ) {
dprintf( D_ALWAYS,
"CronJobParams: Failed to initialize period for job %s\n",
GetName() );
return false;
}
// Are there arguments for it?
if ( !InitArgs( param_args ) ) {
dprintf( D_ALWAYS,
"CronJobParams: Failed to initialize arguments for job %s\n",
GetName() );
return false;
}
// Parse the environment.
if ( !InitEnv( param_args ) ) {
dprintf( D_ALWAYS,
"CronJobParams: Failed to initialize arguments for job %s\n",
GetName() );
return false;
}
m_prefix = param_prefix;
m_executable = param_executable;
m_cwd = param_cwd;
m_jobLoad = param_job_load;
m_optKill = param_kill_mode;
m_optReconfig = param_reconfig;
m_optReconfigRerun = param_reconfig_rerun;
return true;
}
bool
CronJobParams::InitArgs( const MyString ¶m_args )
{
ArgList args;
MyString args_errors;
// Force the first arg to be the "Job Name"..
m_args.Clear();
if( !args.AppendArgsV1RawOrV2Quoted( param_args.Value(),
&args_errors ) ) {
dprintf( D_ALWAYS,
"CronJobParams: Job '%s': "
"Failed to parse arguments: '%s'\n",
GetName(), args_errors.Value());
return false;
}
return AddArgs( args );
}
bool
CronJobParams::InitEnv( const MyString ¶m_env )
{
Env env_object;
MyString env_error_msg;
m_env.Clear();
if( !env_object.MergeFromV1RawOrV2Quoted( param_env.Value(),
&env_error_msg ) ) {
dprintf( D_ALWAYS,
"CronJobParams: Job '%s': "
"Failed to parse environment: '%s'\n",
GetName(), env_error_msg.Value());
return false;
}
return AddEnv( env_object );
}
// Set job's period
bool
CronJobParams::InitPeriod( const MyString ¶m_period )
{
// Find the job period
m_period = 0;
if ( ( m_mode == CRON_ONE_SHOT) || ( m_mode == CRON_ON_DEMAND) ) {
if ( ! param_period.IsEmpty() ) {
dprintf( D_ALWAYS,
"CronJobParams: Warning:"
"Ignoring job period specified for '%s'\n",
GetName() );
return true;
}
}
else if ( param_period.IsEmpty() ) {
dprintf( D_ALWAYS,
"CronJobParams: No job period found for job '%s': skipping\n",
GetName() );
return false;
} else {
char modifier = 'S';
int num = sscanf( param_period.Value(), "%d%c",
&m_period, &modifier );
if ( num < 1 ) {
dprintf( D_ALWAYS,
"CronJobParams: Invalid job period found "
"for job '%s' (%s): skipping\n",
GetName(), param_period.Value() );
return false;
} else {
// Check the modifier
modifier = toupper( modifier );
if ( ( 'S' == modifier ) ) { // Seconds
// Do nothing
} else if ( 'M' == modifier ) {
m_period *= 60;
} else if ( 'H' == modifier ) {
m_period *= ( 60 * 60 );
} else {
dprintf( D_ALWAYS,
"CronJobParams: Invalid period modifier "
"'%c' for job %s (%s)\n",
modifier, GetName(), param_period.Value() );
return false;
}
}
}
// Verify that the mode seleted is valid
if ( IsPeriodic() && (0 == m_period) ) {
dprintf( D_ALWAYS,
"Cron: Job '%s'; Periodic requires non-zero period\n",
GetName() );
return false;
}
// Verify that the mode seleted is valid
if ( IsPeriodic() && (0 == m_period) ) {
dprintf( D_ALWAYS,
"Cron: Job '%s'; Periodic requires non-zero period\n",
GetName() );
return false;
}
return true;
}
bool
CronJobParams::AddEnv( Env const &env )
{
m_env.MergeFrom( env );
return true;
}
// Add to the job's arg list
bool
CronJobParams::AddArgs( const ArgList &new_args )
{
m_args.AppendArgsFromArgList(new_args);
return true;
}
const char *
CronJobParams::GetModeString( void ) const
{
return m_modestr;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2015, Tiaan Louw
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
#include <memory>
#include <thread>
#include <gtest/gtest.h>
#include "nucleus/message_loop/message_loop.h"
#include "nucleus/message_loop/message_pump_default.h"
namespace nu {
namespace {
class Foo {
public:
Foo() {}
~Foo() {}
void test0() { ++m_testCount; }
void test1ConstRef(const std::string& a) {
++m_testCount;
m_result.append(a);
}
void test1Ptr(std::string* a) {
++m_testCount;
m_result.append(*a);
}
void test1Int(int a) { m_testCount += a; }
void test2Ptr(std::string* a, std::string* b) {
++m_testCount;
m_result.append(*a);
m_result.append(*b);
}
void test2Mixed(const std::string& a, std::string* b) {
++m_testCount;
m_result.append(a);
m_result.append(*b);
}
int getTestCount() const { return m_testCount; }
const std::string& getResult() const { return m_result; }
private:
int m_testCount = 0;
std::string m_result;
DISALLOW_COPY_AND_ASSIGN(Foo);
};
// This function runs slowly to simulate a large amount of work being done.
void slowFunc(MessageLoop* messageLoop, const std::chrono::milliseconds& delay,
int* quitCounter) {
std::this_thread::sleep_for(delay);
if (--(*quitCounter) == 0) {
messageLoop->quitWhenIdle();
}
}
// This function records the time when run was called, which is useful for
// building a variety of MessageLoop tests.
void recordRunTimeFunc(
MessageLoop* messageLoop,
std::chrono::time_point<std::chrono::high_resolution_clock>* runTime,
int* quitCounter) {
*runTime = std::chrono::high_resolution_clock::now();
// Cause our run function to take some time to execute. As a result we can
// count on subsequent recordRunTimeFunc() running at a future time wihout
// worry about the resolution of our system clock being an issue.
slowFunc(messageLoop, std::chrono::milliseconds(100), quitCounter);
}
} // namespace
TEST(MessageLoopTest, PostTask) {
MessageLoop loop(std::make_unique<MessagePumpDefault>());
// Add tests to message loop.
auto foo = std::make_shared<Foo>();
std::string a("a"), b("b"), c("c"), d("d");
loop.postTask(std::bind(&Foo::test0, foo));
loop.postTask(std::bind(&Foo::test1ConstRef, foo, a));
loop.postTask(std::bind(&Foo::test1Ptr, foo, &b));
loop.postTask(std::bind(&Foo::test1Int, foo, 100));
loop.postTask(std::bind(&Foo::test2Ptr, foo, &a, &c));
loop.postTask(std::bind(&Foo::test2Mixed, foo, a, &d));
// After all tests, post a message that will shut down the message loop.
loop.postTask(std::bind(&MessageLoop::quitWhenIdle, &loop));
// Now run the loop.
loop.run();
EXPECT_EQ(foo->getTestCount(), 105);
EXPECT_EQ(foo->getResult(), "abacad");
}
TEST(MessageLoopTest, PostDelayedTask_Basic) {
using Time = std::chrono::time_point<std::chrono::high_resolution_clock>;
MessageLoop loop(std::make_unique<MessagePumpDefault>());
// Test that postDelayedTask results in a delayed task.
const std::chrono::milliseconds kDelay{100};
int numTasks = 1;
Time runTime;
loop.postDelayedTask(
std::bind(&recordRunTimeFunc, &loop, &runTime, &numTasks), kDelay);
Time timeBeforeRun = std::chrono::high_resolution_clock::now();
loop.run();
Time timeAfterRun = std::chrono::high_resolution_clock::now();
EXPECT_EQ(0, numTasks);
EXPECT_LT(kDelay, timeAfterRun - timeBeforeRun);
}
} // namespace nu
<commit_msg>More tests.<commit_after>// Copyright (c) 2015, Tiaan Louw
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
// AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
// OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
// PERFORMANCE OF THIS SOFTWARE.
#include <memory>
#include <thread>
#include <gtest/gtest.h>
#include "nucleus/message_loop/message_loop.h"
#include "nucleus/message_loop/message_pump_default.h"
namespace nu {
namespace {
class Foo {
public:
Foo() {}
~Foo() {}
void test0() { ++m_testCount; }
void test1ConstRef(const std::string& a) {
++m_testCount;
m_result.append(a);
}
void test1Ptr(std::string* a) {
++m_testCount;
m_result.append(*a);
}
void test1Int(int a) { m_testCount += a; }
void test2Ptr(std::string* a, std::string* b) {
++m_testCount;
m_result.append(*a);
m_result.append(*b);
}
void test2Mixed(const std::string& a, std::string* b) {
++m_testCount;
m_result.append(a);
m_result.append(*b);
}
int getTestCount() const { return m_testCount; }
const std::string& getResult() const { return m_result; }
private:
int m_testCount = 0;
std::string m_result;
DISALLOW_COPY_AND_ASSIGN(Foo);
};
// This function runs slowly to simulate a large amount of work being done.
void slowFunc(MessageLoop* messageLoop, const std::chrono::milliseconds& delay,
int* quitCounter) {
std::this_thread::sleep_for(delay);
if (--(*quitCounter) == 0) {
messageLoop->quitWhenIdle();
}
}
// This function records the time when run was called, which is useful for
// building a variety of MessageLoop tests.
void recordRunTimeFunc(
MessageLoop* messageLoop,
std::chrono::time_point<std::chrono::high_resolution_clock>* runTime,
int* quitCounter) {
*runTime = std::chrono::high_resolution_clock::now();
// Cause our run function to take some time to execute. As a result we can
// count on subsequent recordRunTimeFunc() running at a future time wihout
// worry about the resolution of our system clock being an issue.
slowFunc(messageLoop, std::chrono::milliseconds(100), quitCounter);
}
} // namespace
TEST(MessageLoopTest, PostTask) {
MessageLoop loop(std::make_unique<MessagePumpDefault>());
// Add tests to message loop.
auto foo = std::make_shared<Foo>();
std::string a("a"), b("b"), c("c"), d("d");
loop.postTask(std::bind(&Foo::test0, foo));
loop.postTask(std::bind(&Foo::test1ConstRef, foo, a));
loop.postTask(std::bind(&Foo::test1Ptr, foo, &b));
loop.postTask(std::bind(&Foo::test1Int, foo, 100));
loop.postTask(std::bind(&Foo::test2Ptr, foo, &a, &c));
loop.postTask(std::bind(&Foo::test2Mixed, foo, a, &d));
// After all tests, post a message that will shut down the message loop.
loop.postTask(std::bind(&MessageLoop::quitWhenIdle, &loop));
// Now run the loop.
loop.run();
EXPECT_EQ(foo->getTestCount(), 105);
EXPECT_EQ(foo->getResult(), "abacad");
}
TEST(MessageLoopTest, PostDelayedTask_Basic) {
using Time = std::chrono::time_point<std::chrono::high_resolution_clock>;
MessageLoop loop(std::make_unique<MessagePumpDefault>());
// Test that postDelayedTask results in a delayed task.
const std::chrono::milliseconds kDelay{100};
int numTasks = 1;
Time runTime;
loop.postDelayedTask(
std::bind(&recordRunTimeFunc, &loop, &runTime, &numTasks), kDelay);
Time timeBeforeRun = std::chrono::high_resolution_clock::now();
loop.run();
Time timeAfterRun = std::chrono::high_resolution_clock::now();
EXPECT_EQ(0, numTasks);
EXPECT_LT(kDelay, timeAfterRun - timeBeforeRun);
}
TEST(MessageLoopTest, PostDelayedTask_InDelayOrder) {
using Time = std::chrono::time_point<std::chrono::high_resolution_clock>;
MessageLoop loop(std::make_unique<MessagePumpDefault>());
// Test that two tasks with different delays run in the right order.
int numTasks = 2;
Time runTime1, runTime2;
loop.postDelayedTask(
std::bind(&recordRunTimeFunc, &loop, &runTime1, &numTasks),
std::chrono::milliseconds{200});
// If we get a large pause in execution (due to a context switch) here, this
// test could fail.
loop.postDelayedTask(
std::bind(&recordRunTimeFunc, &loop, &runTime2, &numTasks),
std::chrono::milliseconds{10});
loop.run();
EXPECT_EQ(0, numTasks);
EXPECT_TRUE(runTime2 < runTime1);
}
TEST(MessageLoopTest, PostDelayedTask_InPostOrder) {
using Time = std::chrono::time_point<std::chrono::high_resolution_clock>;
MessageLoop loop(std::make_unique<MessagePumpDefault>());
// Test that two tasks with the same delay run in the order in which they were
// posted.
const std::chrono::milliseconds kDelay{100};
int numTasks = 2;
Time runTime1, runTime2;
loop.postDelayedTask(
std::bind(&recordRunTimeFunc, &loop, &runTime1, &numTasks), kDelay);
loop.postDelayedTask(
std::bind(&recordRunTimeFunc, &loop, &runTime2, &numTasks), kDelay);
loop.run();
EXPECT_EQ(0, numTasks);
EXPECT_TRUE(runTime1 < runTime2);
}
TEST(MessageLoopTest, PostDelayedTask_InPostOrder_2) {
using Time = std::chrono::time_point<std::chrono::high_resolution_clock>;
MessageLoop loop(std::make_unique<MessagePumpDefault>());
// Test that a delayed task still runs after normal tasks even if the normal
// tasks take a long time to run.
const std::chrono::milliseconds kPause{50};
int numTasks = 2;
Time runTime;
loop.postTask(std::bind(&slowFunc, &loop, kPause, &numTasks));
loop.postDelayedTask(
std::bind(&recordRunTimeFunc, &loop, &runTime, &numTasks),
std::chrono::milliseconds{10});
Time timeBeforeRun = std::chrono::high_resolution_clock::now();
loop.run();
Time timeAfterRun = std::chrono::high_resolution_clock::now();
EXPECT_EQ(0, numTasks);
EXPECT_LT(kPause, timeAfterRun - timeBeforeRun);
}
TEST(MessageLoopTest, PostDelayedTask_InPostOrder_3) {
using Time = std::chrono::time_point<std::chrono::high_resolution_clock>;
MessageLoop loop(std::make_unique<MessagePumpDefault>());
// Test that a delayed task still runs after a pile of normal tasks. The key
// difference between this test and the previous one is that here we return
// the MessageLoop a lot so we give the MessageLoop plenty of opportunities to
// maybe run the delayed task. It should know not to do so until the delayed
// task's delay has passed.
int numTasks = 11;
Time runTime1, runTime2;
// Clutter the MessageLoop with tasks.
for (int i = 1; i < numTasks; ++i) {
loop.postTask(std::bind(&recordRunTimeFunc, &loop, &runTime1, &numTasks));
}
loop.postDelayedTask(
std::bind(&recordRunTimeFunc, &loop, &runTime2, &numTasks),
std::chrono::milliseconds{1});
loop.run();
EXPECT_EQ(0, numTasks);
EXPECT_TRUE(runTime2 > runTime1);
}
TEST(MessageLoopTest, PostDelayedTask_SharedTimer) {
using Time = std::chrono::time_point<std::chrono::high_resolution_clock>;
MessageLoop loop(std::make_unique<MessagePumpDefault>());
// Test that the interval of the timer, used to run the next delayed task, is
// set to a value corresponding to when the next delayed task should run.
// By setting numTasks to 1, we ensure that the first task to run causes the
// run loop to exit.
int numTasks = 1;
Time runTime1, runTime2;
loop.postDelayedTask(
std::bind(&recordRunTimeFunc, &loop, &runTime1, &numTasks),
std::chrono::milliseconds{1000});
loop.postDelayedTask(
std::bind(&recordRunTimeFunc, &loop, &runTime2, &numTasks),
std::chrono::milliseconds{10});
Time startTime = std::chrono::high_resolution_clock::now();
loop.run();
EXPECT_EQ(0, numTasks);
// Ensure that we ran in far less time than the slower timer.
std::chrono::milliseconds totalTime =
std::chrono::duration_cast<std::chrono::milliseconds>(
std::chrono::high_resolution_clock::now() - startTime);
EXPECT_GT(5000, totalTime.count());
// In case both timers somehow run at nearly the same time, sleep a little and
// then run all pending to force them both to have run.
std::this_thread::sleep_for(std::chrono::milliseconds{100});
loop.runUntilIdle();
EXPECT_TRUE(runTime1 == Time());
EXPECT_FALSE(runTime2 == Time());
}
} // namespace nu
<|endoftext|> |
<commit_before>//===-- sanitizer_common_test.cc ------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of ThreadSanitizer/AddressSanitizer runtime.
//
//===----------------------------------------------------------------------===//
#include "sanitizer_common/sanitizer_allocator_internal.h"
#include "sanitizer_common/sanitizer_common.h"
#include "sanitizer_common/sanitizer_libc.h"
#include "sanitizer_common/sanitizer_platform.h"
#include "gtest/gtest.h"
namespace __sanitizer {
static bool IsSorted(const uptr *array, uptr n) {
for (uptr i = 1; i < n; i++) {
if (array[i] < array[i - 1]) return false;
}
return true;
}
TEST(SanitizerCommon, SortTest) {
uptr array[100];
uptr n = 100;
// Already sorted.
for (uptr i = 0; i < n; i++) {
array[i] = i;
}
SortArray(array, n);
EXPECT_TRUE(IsSorted(array, n));
// Reverse order.
for (uptr i = 0; i < n; i++) {
array[i] = n - 1 - i;
}
SortArray(array, n);
EXPECT_TRUE(IsSorted(array, n));
// Mixed order.
for (uptr i = 0; i < n; i++) {
array[i] = (i % 2 == 0) ? i : n - 1 - i;
}
SortArray(array, n);
EXPECT_TRUE(IsSorted(array, n));
// All equal.
for (uptr i = 0; i < n; i++) {
array[i] = 42;
}
SortArray(array, n);
EXPECT_TRUE(IsSorted(array, n));
// All but one sorted.
for (uptr i = 0; i < n - 1; i++) {
array[i] = i;
}
array[n - 1] = 42;
SortArray(array, n);
EXPECT_TRUE(IsSorted(array, n));
// Minimal case - sort three elements.
array[0] = 1;
array[1] = 0;
SortArray(array, 2);
EXPECT_TRUE(IsSorted(array, 2));
}
TEST(SanitizerCommon, MmapAlignedOrDie) {
uptr PageSize = GetPageSizeCached();
for (uptr size = 1; size <= 32; size *= 2) {
for (uptr alignment = 1; alignment <= 32; alignment *= 2) {
for (int iter = 0; iter < 100; iter++) {
uptr res = (uptr)MmapAlignedOrDie(
size * PageSize, alignment * PageSize, "MmapAlignedOrDieTest");
EXPECT_EQ(0U, res % (alignment * PageSize));
internal_memset((void*)res, 1, size * PageSize);
UnmapOrDie((void*)res, size * PageSize);
}
}
}
}
#if SANITIZER_LINUX
TEST(SanitizerCommon, SanitizerSetThreadName) {
const char *names[] = {
"0123456789012",
"01234567890123",
"012345678901234", // Larger names will be truncated on linux.
};
for (size_t i = 0; i < ARRAY_SIZE(names); i++) {
EXPECT_TRUE(SanitizerSetThreadName(names[i]));
char buff[100];
EXPECT_TRUE(SanitizerGetThreadName(buff, sizeof(buff) - 1));
EXPECT_EQ(0, internal_strcmp(buff, names[i]));
}
}
#endif
TEST(SanitizerCommon, InternalMmapVector) {
InternalMmapVector<uptr> vector(1);
for (uptr i = 0; i < 100; i++) {
EXPECT_EQ(i, vector.size());
vector.push_back(i);
}
for (uptr i = 0; i < 100; i++) {
EXPECT_EQ(i, vector[i]);
}
for (int i = 99; i >= 0; i--) {
EXPECT_EQ((uptr)i, vector.back());
vector.pop_back();
EXPECT_EQ((uptr)i, vector.size());
}
}
void TestThreadInfo(bool main) {
uptr stk_addr = 0;
uptr stk_size = 0;
uptr tls_addr = 0;
uptr tls_size = 0;
GetThreadStackAndTls(main, &stk_addr, &stk_size, &tls_addr, &tls_size);
int stack_var;
EXPECT_NE(stk_addr, (uptr)0);
EXPECT_NE(stk_size, (uptr)0);
EXPECT_GT((uptr)&stack_var, stk_addr);
EXPECT_LT((uptr)&stack_var, stk_addr + stk_size);
#if SANITIZER_LINUX && defined(__x86_64__)
static __thread int thread_var;
EXPECT_NE(tls_addr, (uptr)0);
EXPECT_NE(tls_size, (uptr)0);
EXPECT_GT((uptr)&thread_var, tls_addr);
EXPECT_LT((uptr)&thread_var, tls_addr + tls_size);
// Ensure that tls and stack do not intersect.
uptr tls_end = tls_addr + tls_size;
EXPECT_TRUE(tls_addr < stk_addr || tls_addr >= stk_addr + stk_size);
EXPECT_TRUE(tls_end < stk_addr || tls_end >= stk_addr + stk_size);
EXPECT_TRUE((tls_addr < stk_addr) == (tls_end < stk_addr));
#endif
}
static void *WorkerThread(void *arg) {
TestThreadInfo(false);
return 0;
}
TEST(SanitizerCommon, ThreadStackTlsMain) {
InitTlsSize();
TestThreadInfo(true);
}
TEST(SanitizerCommon, ThreadStackTlsWorker) {
InitTlsSize();
pthread_t t;
pthread_create(&t, 0, WorkerThread, 0);
pthread_join(t, 0);
}
bool UptrLess(uptr a, uptr b) {
return a < b;
}
TEST(SanitizerCommon, InternalBinarySearch) {
static const uptr kSize = 5;
uptr arr[kSize];
for (uptr i = 0; i < kSize; i++) arr[i] = i * i;
for (uptr i = 0; i < kSize; i++)
ASSERT_EQ(InternalBinarySearch(arr, 0, kSize, i * i, UptrLess), i);
ASSERT_EQ(InternalBinarySearch(arr, 0, kSize, 7, UptrLess), kSize + 1);
}
#if SANITIZER_LINUX
TEST(SanitizerCommon, FindPathToBinary) {
char *true_path = FindPathToBinary("true");
EXPECT_NE((char*)0, internal_strstr(true_path, "/bin/true"));
InternalFree(true_path);
EXPECT_EQ(0, FindPathToBinary("unexisting_binary.ergjeorj"));
}
#endif
} // namespace __sanitizer
<commit_msg>Disable FindPathToBinary test on Android<commit_after>//===-- sanitizer_common_test.cc ------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of ThreadSanitizer/AddressSanitizer runtime.
//
//===----------------------------------------------------------------------===//
#include "sanitizer_common/sanitizer_allocator_internal.h"
#include "sanitizer_common/sanitizer_common.h"
#include "sanitizer_common/sanitizer_libc.h"
#include "sanitizer_common/sanitizer_platform.h"
#include "gtest/gtest.h"
namespace __sanitizer {
static bool IsSorted(const uptr *array, uptr n) {
for (uptr i = 1; i < n; i++) {
if (array[i] < array[i - 1]) return false;
}
return true;
}
TEST(SanitizerCommon, SortTest) {
uptr array[100];
uptr n = 100;
// Already sorted.
for (uptr i = 0; i < n; i++) {
array[i] = i;
}
SortArray(array, n);
EXPECT_TRUE(IsSorted(array, n));
// Reverse order.
for (uptr i = 0; i < n; i++) {
array[i] = n - 1 - i;
}
SortArray(array, n);
EXPECT_TRUE(IsSorted(array, n));
// Mixed order.
for (uptr i = 0; i < n; i++) {
array[i] = (i % 2 == 0) ? i : n - 1 - i;
}
SortArray(array, n);
EXPECT_TRUE(IsSorted(array, n));
// All equal.
for (uptr i = 0; i < n; i++) {
array[i] = 42;
}
SortArray(array, n);
EXPECT_TRUE(IsSorted(array, n));
// All but one sorted.
for (uptr i = 0; i < n - 1; i++) {
array[i] = i;
}
array[n - 1] = 42;
SortArray(array, n);
EXPECT_TRUE(IsSorted(array, n));
// Minimal case - sort three elements.
array[0] = 1;
array[1] = 0;
SortArray(array, 2);
EXPECT_TRUE(IsSorted(array, 2));
}
TEST(SanitizerCommon, MmapAlignedOrDie) {
uptr PageSize = GetPageSizeCached();
for (uptr size = 1; size <= 32; size *= 2) {
for (uptr alignment = 1; alignment <= 32; alignment *= 2) {
for (int iter = 0; iter < 100; iter++) {
uptr res = (uptr)MmapAlignedOrDie(
size * PageSize, alignment * PageSize, "MmapAlignedOrDieTest");
EXPECT_EQ(0U, res % (alignment * PageSize));
internal_memset((void*)res, 1, size * PageSize);
UnmapOrDie((void*)res, size * PageSize);
}
}
}
}
#if SANITIZER_LINUX
TEST(SanitizerCommon, SanitizerSetThreadName) {
const char *names[] = {
"0123456789012",
"01234567890123",
"012345678901234", // Larger names will be truncated on linux.
};
for (size_t i = 0; i < ARRAY_SIZE(names); i++) {
EXPECT_TRUE(SanitizerSetThreadName(names[i]));
char buff[100];
EXPECT_TRUE(SanitizerGetThreadName(buff, sizeof(buff) - 1));
EXPECT_EQ(0, internal_strcmp(buff, names[i]));
}
}
#endif
TEST(SanitizerCommon, InternalMmapVector) {
InternalMmapVector<uptr> vector(1);
for (uptr i = 0; i < 100; i++) {
EXPECT_EQ(i, vector.size());
vector.push_back(i);
}
for (uptr i = 0; i < 100; i++) {
EXPECT_EQ(i, vector[i]);
}
for (int i = 99; i >= 0; i--) {
EXPECT_EQ((uptr)i, vector.back());
vector.pop_back();
EXPECT_EQ((uptr)i, vector.size());
}
}
void TestThreadInfo(bool main) {
uptr stk_addr = 0;
uptr stk_size = 0;
uptr tls_addr = 0;
uptr tls_size = 0;
GetThreadStackAndTls(main, &stk_addr, &stk_size, &tls_addr, &tls_size);
int stack_var;
EXPECT_NE(stk_addr, (uptr)0);
EXPECT_NE(stk_size, (uptr)0);
EXPECT_GT((uptr)&stack_var, stk_addr);
EXPECT_LT((uptr)&stack_var, stk_addr + stk_size);
#if SANITIZER_LINUX && defined(__x86_64__)
static __thread int thread_var;
EXPECT_NE(tls_addr, (uptr)0);
EXPECT_NE(tls_size, (uptr)0);
EXPECT_GT((uptr)&thread_var, tls_addr);
EXPECT_LT((uptr)&thread_var, tls_addr + tls_size);
// Ensure that tls and stack do not intersect.
uptr tls_end = tls_addr + tls_size;
EXPECT_TRUE(tls_addr < stk_addr || tls_addr >= stk_addr + stk_size);
EXPECT_TRUE(tls_end < stk_addr || tls_end >= stk_addr + stk_size);
EXPECT_TRUE((tls_addr < stk_addr) == (tls_end < stk_addr));
#endif
}
static void *WorkerThread(void *arg) {
TestThreadInfo(false);
return 0;
}
TEST(SanitizerCommon, ThreadStackTlsMain) {
InitTlsSize();
TestThreadInfo(true);
}
TEST(SanitizerCommon, ThreadStackTlsWorker) {
InitTlsSize();
pthread_t t;
pthread_create(&t, 0, WorkerThread, 0);
pthread_join(t, 0);
}
bool UptrLess(uptr a, uptr b) {
return a < b;
}
TEST(SanitizerCommon, InternalBinarySearch) {
static const uptr kSize = 5;
uptr arr[kSize];
for (uptr i = 0; i < kSize; i++) arr[i] = i * i;
for (uptr i = 0; i < kSize; i++)
ASSERT_EQ(InternalBinarySearch(arr, 0, kSize, i * i, UptrLess), i);
ASSERT_EQ(InternalBinarySearch(arr, 0, kSize, 7, UptrLess), kSize + 1);
}
#if SANITIZER_LINUX && !SANITIZER_ANDROID
TEST(SanitizerCommon, FindPathToBinary) {
char *true_path = FindPathToBinary("true");
EXPECT_NE((char*)0, internal_strstr(true_path, "/bin/true"));
InternalFree(true_path);
EXPECT_EQ(0, FindPathToBinary("unexisting_binary.ergjeorj"));
}
#endif
} // namespace __sanitizer
<|endoftext|> |
<commit_before>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef CONTAINERS_DISK_BACKED_QUEUE_HPP_
#define CONTAINERS_DISK_BACKED_QUEUE_HPP_
#include <string>
#include <vector>
#include "concurrency/fifo_checker.hpp"
#include "concurrency/mutex.hpp"
#include "containers/buffer_group.hpp"
#include "containers/archive/buffer_group_stream.hpp"
#include "containers/archive/vector_stream.hpp"
#include "containers/scoped.hpp"
#include "perfmon/core.hpp"
#include "serializer/types.hpp"
class cache_balancer_t;
class cache_conn_t;
class cache_t;
class txn_t;
class io_backender_t;
class perfmon_collection_t;
struct queue_block_t {
block_id_t next;
int32_t data_size, live_data_offset;
char data[0];
} __attribute__((__packed__));
class value_acquisition_object_t;
class buffer_group_viewer_t {
public:
virtual void view_buffer_group(const const_buffer_group_t *group) = 0;
protected:
buffer_group_viewer_t() { }
virtual ~buffer_group_viewer_t() { }
DISABLE_COPYING(buffer_group_viewer_t);
};
class internal_disk_backed_queue_t {
public:
internal_disk_backed_queue_t(io_backender_t *io_backender, const serializer_filepath_t& filename, perfmon_collection_t *stats_parent);
~internal_disk_backed_queue_t();
// TODO: order_token_t::ignore. This should take an order token and store it.
void push(const write_message_t &value);
void push(const scoped_array_t<write_message_t> &values);
// TODO: order_token_t::ignore. This should output an order token (that was passed in to push).
void pop(buffer_group_viewer_t *viewer);
bool empty();
int64_t size();
private:
void add_block_to_head(txn_t *txn);
void remove_block_from_tail(txn_t *txn);
void push_single(txn_t *txn, const write_message_t &value);
mutex_t mutex;
// Serves more as sanity-checking for the cache than this type's ordering.
order_source_t cache_order_source;
perfmon_collection_t perfmon_collection;
perfmon_membership_t perfmon_membership;
int64_t queue_size;
// The end we push onto.
block_id_t head_block_id;
// The end we pop from.
block_id_t tail_block_id;
scoped_ptr_t<standard_serializer_t> serializer;
scoped_ptr_t<cache_balancer_t> balancer;
scoped_ptr_t<cache_t> cache;
scoped_ptr_t<cache_conn_t> cache_conn;
DISABLE_COPYING(internal_disk_backed_queue_t);
};
template <class T>
class deserializing_viewer_t : public buffer_group_viewer_t {
public:
explicit deserializing_viewer_t(T *value_out) : value_out_(value_out) { }
virtual ~deserializing_viewer_t() { }
virtual void view_buffer_group(const const_buffer_group_t *group) {
// RSI: We assume here that _other_ code uses LATEST. We should
// instead templatize this type.
deserialize_from_group<cluster_version_t::LATEST>(group, value_out_);
}
private:
T *value_out_;
DISABLE_COPYING(deserializing_viewer_t);
};
template <class T>
class disk_backed_queue_t {
public:
disk_backed_queue_t(io_backender_t *io_backender, const serializer_filepath_t& filename, perfmon_collection_t *stats_parent)
: internal_(io_backender, filename, stats_parent) { }
void push(const T &t) {
// TODO: There's an unnecessary copying of data here (which would require a
// serialization_size overloaded function to be implemented in order to eliminate).
// RSI: We have such a serialization_size function.
// RSI: LATEST? Who are we to assume this is correct or wanted?
// (RSI: Double-check that _all_ disk backed queues are ephemeral.)
write_message_t wm;
serialize<cluster_version_t::LATEST>(&wm, t);
internal_.push(wm);
}
void pop(T *out) {
deserializing_viewer_t<T> viewer(out);
internal_.pop(&viewer);
}
bool empty() {
return internal_.empty();
}
int64_t size() {
return internal_.size();
}
private:
internal_disk_backed_queue_t internal_;
DISABLE_COPYING(disk_backed_queue_t);
};
#endif /* CONTAINERS_DISK_BACKED_QUEUE_HPP_ */
<commit_msg>Removed TODO and RSI comments.<commit_after>// Copyright 2010-2014 RethinkDB, all rights reserved.
#ifndef CONTAINERS_DISK_BACKED_QUEUE_HPP_
#define CONTAINERS_DISK_BACKED_QUEUE_HPP_
#include <string>
#include <vector>
#include "concurrency/fifo_checker.hpp"
#include "concurrency/mutex.hpp"
#include "containers/buffer_group.hpp"
#include "containers/archive/buffer_group_stream.hpp"
#include "containers/archive/vector_stream.hpp"
#include "containers/scoped.hpp"
#include "perfmon/core.hpp"
#include "serializer/types.hpp"
class cache_balancer_t;
class cache_conn_t;
class cache_t;
class txn_t;
class io_backender_t;
class perfmon_collection_t;
struct queue_block_t {
block_id_t next;
int32_t data_size, live_data_offset;
char data[0];
} __attribute__((__packed__));
class value_acquisition_object_t;
class buffer_group_viewer_t {
public:
virtual void view_buffer_group(const const_buffer_group_t *group) = 0;
protected:
buffer_group_viewer_t() { }
virtual ~buffer_group_viewer_t() { }
DISABLE_COPYING(buffer_group_viewer_t);
};
class internal_disk_backed_queue_t {
public:
internal_disk_backed_queue_t(io_backender_t *io_backender, const serializer_filepath_t& filename, perfmon_collection_t *stats_parent);
~internal_disk_backed_queue_t();
void push(const write_message_t &value);
void push(const scoped_array_t<write_message_t> &values);
void pop(buffer_group_viewer_t *viewer);
bool empty();
int64_t size();
private:
void add_block_to_head(txn_t *txn);
void remove_block_from_tail(txn_t *txn);
void push_single(txn_t *txn, const write_message_t &value);
mutex_t mutex;
// Serves more as sanity-checking for the cache than this type's ordering.
order_source_t cache_order_source;
perfmon_collection_t perfmon_collection;
perfmon_membership_t perfmon_membership;
int64_t queue_size;
// The end we push onto.
block_id_t head_block_id;
// The end we pop from.
block_id_t tail_block_id;
scoped_ptr_t<standard_serializer_t> serializer;
scoped_ptr_t<cache_balancer_t> balancer;
scoped_ptr_t<cache_t> cache;
scoped_ptr_t<cache_conn_t> cache_conn;
DISABLE_COPYING(internal_disk_backed_queue_t);
};
template <class T>
class deserializing_viewer_t : public buffer_group_viewer_t {
public:
explicit deserializing_viewer_t(T *value_out) : value_out_(value_out) { }
virtual ~deserializing_viewer_t() { }
virtual void view_buffer_group(const const_buffer_group_t *group) {
// RSI: We assume here that _other_ code uses LATEST. We should
// instead templatize this type.
deserialize_from_group<cluster_version_t::LATEST>(group, value_out_);
}
private:
T *value_out_;
DISABLE_COPYING(deserializing_viewer_t);
};
template <class T>
class disk_backed_queue_t {
public:
disk_backed_queue_t(io_backender_t *io_backender, const serializer_filepath_t& filename, perfmon_collection_t *stats_parent)
: internal_(io_backender, filename, stats_parent) { }
void push(const T &t) {
// TODO: There's an unnecessary copying of data here (which would require a
// serialization_size overloaded function to be implemented in order to eliminate).
// RSI: We have such a serialization_size function.
write_message_t wm;
serialize<cluster_version_t::LATEST>(&wm, t);
internal_.push(wm);
}
void pop(T *out) {
deserializing_viewer_t<T> viewer(out);
internal_.pop(&viewer);
}
bool empty() {
return internal_.empty();
}
int64_t size() {
return internal_.size();
}
private:
internal_disk_backed_queue_t internal_;
DISABLE_COPYING(disk_backed_queue_t);
};
#endif /* CONTAINERS_DISK_BACKED_QUEUE_HPP_ */
<|endoftext|> |
<commit_before>#ifndef CONTAINERS_DISK_BACKED_QUEUE_HPP_
#define CONTAINERS_DISK_BACKED_QUEUE_HPP_
#define MAX_REF_SIZE 251
#include <string>
#include <vector>
#include "arch/io/disk.hpp"
#include "buffer_cache/blob.hpp"
#include "buffer_cache/mirrored/mirrored.hpp"
#include "buffer_cache/semantic_checking.hpp"
#include "concurrency/queue/passive_producer.hpp"
#include "containers/archive/vector_stream.hpp"
#include "serializer/config.hpp"
#include "serializer/types.hpp"
//TODO there are extra copies all over the place mostly stemming from having a
//vector<char> from the serialization code and strings from the blob code.
struct queue_block_t {
block_id_t next;
int data_size, live_data_offset;
char data[0];
};
template <class T>
class disk_backed_queue_t {
public:
disk_backed_queue_t(io_backender_t *io_backender, std::string filename, perfmon_collection_t *stats_parent) :
queue_size(0), head_block_id(NULL_BLOCK_ID), tail_block_id(NULL_BLOCK_ID)
{
/* We're going to register for writes, however those writes won't be able
* to find their way in to the btree until we're done backfilling. Thus we
* need to set up a serializer and cache for them to go in to. */
//perfmon_collection_t backfill_stats_collection("queue-" + filename, NULL, true, true);
standard_serializer_t::create(
io_backender,
standard_serializer_t::private_dynamic_config_t(filename),
standard_serializer_t::static_config_t()
);
serializer.init(new standard_serializer_t(
standard_serializer_t::dynamic_config_t(),
io_backender,
standard_serializer_t::private_dynamic_config_t(filename),
stats_parent
));
/* Remove the file we just created from the filesystem, so that it will
get deleted as soon as the serializer is destroyed or if the process
crashes */
int res = unlink(filename.c_str());
guarantee_err(res == 0, "unlink() failed");
/* Create the cache. */
mirrored_cache_static_config_t cache_static_config;
cache_t::create(serializer.get(), &cache_static_config);
mirrored_cache_config_t cache_dynamic_config;
cache_dynamic_config.max_size = MEGABYTE;
cache_dynamic_config.max_dirty_size = MEGABYTE / 2;
cache.init(new cache_t(serializer.get(), &cache_dynamic_config, stats_parent));
}
void push(const T &t) {
mutex_t::acq_t mutex_acq(&mutex);
//first we need a transaction
transaction_t txn(cache.get(), rwi_write, 2, repli_timestamp_t::distant_past, order_token_t::ignore);
if (head_block_id == NULL_BLOCK_ID) {
add_block_to_head(&txn);
}
scoped_ptr_t<buf_lock_t> _head(new buf_lock_t(&txn, head_block_id, rwi_write));
queue_block_t* head = reinterpret_cast<queue_block_t *>(_head->get_data_major_write());
write_message_t wm;
wm << t;
vector_stream_t stream;
int res = send_write_message(&stream, &wm);
guarantee(res == 0);
char buffer[MAX_REF_SIZE];
bzero(buffer, MAX_REF_SIZE);
blob_t blob(buffer, MAX_REF_SIZE);
blob.append_region(&txn, stream.vector().size());
std::string sered_data(stream.vector().begin(), stream.vector().end());
blob.write_from_string(sered_data, &txn, 0);
if (((char *)(head->data + head->data_size) - (char *)(head)) + blob.refsize(cache->get_block_size()) > cache->get_block_size().value()) {
//The data won't fit in our current head block, so it's time to make a new one
head = NULL;
_head.reset();
add_block_to_head(&txn);
_head.init(new buf_lock_t(&txn, head_block_id, rwi_write));
head = reinterpret_cast<queue_block_t *>(_head->get_data_major_write());
}
memcpy(head->data + head->data_size, buffer, blob.refsize(cache->get_block_size()));
head->data_size += blob.refsize(cache->get_block_size());
queue_size++;
}
T pop() {
mutex_t::acq_t mutex_acq(&mutex);
char buffer[MAX_REF_SIZE];
transaction_t txn(cache.get(), rwi_write, 2, repli_timestamp_t::distant_past, order_token_t::ignore);
scoped_ptr_t<buf_lock_t> _tail(new buf_lock_t(&txn, tail_block_id, rwi_write));
queue_block_t *tail = reinterpret_cast<queue_block_t *>(_tail->get_data_major_write());
rassert(tail->data_size != tail->live_data_offset);
/* Grab the data from the blob and delete it. */
memcpy(buffer, tail->data + tail->live_data_offset, blob::ref_size(cache->get_block_size(), tail->data + tail->live_data_offset, MAX_REF_SIZE));
blob_t blob(buffer, MAX_REF_SIZE);
std::string data = blob.read_to_string(&txn, 0, blob.valuesize());
/* Record how far along in the blob we are. */
tail->live_data_offset += blob.refsize(cache->get_block_size());
blob.clear(&txn);
queue_size--;
/* If that was the last blob in this block move on to the next one. */
if (tail->live_data_offset == tail->data_size) {
_tail.reset();
remove_block_from_tail(&txn);
}
/* Deserialize the value and return it. */
std::vector<char> data_vec(data.begin(), data.end());
vector_read_stream_t read_stream(&data_vec);
T t;
int res = deserialize(&read_stream, &t);
guarantee_err(res == 0, "corruption in disk-backed queue");
return t;
}
bool empty() {
return queue_size == 0;
}
int size() {
return queue_size;
}
private:
void add_block_to_head(transaction_t *txn) {
buf_lock_t _new_head(txn);
queue_block_t *new_head = reinterpret_cast<queue_block_t *>(_new_head.get_data_major_write());
if (head_block_id == NULL_BLOCK_ID) {
rassert(tail_block_id == NULL_BLOCK_ID);
head_block_id = tail_block_id = _new_head.get_block_id();
} else {
buf_lock_t _old_head(txn, head_block_id, rwi_write);
queue_block_t *old_head = reinterpret_cast<queue_block_t *>(_old_head.get_data_major_write());
rassert(old_head->next == NULL_BLOCK_ID);
old_head->next = _new_head.get_block_id();
head_block_id = _new_head.get_block_id();
}
new_head->next = NULL_BLOCK_ID;
new_head->data_size = 0;
new_head->live_data_offset = 0;
}
void remove_block_from_tail(transaction_t *txn) {
rassert(tail_block_id != NULL_BLOCK_ID);
buf_lock_t _old_tail(txn, tail_block_id, rwi_write);
queue_block_t *old_tail = reinterpret_cast<queue_block_t *>(_old_tail.get_data_major_write());
if (old_tail->next == NULL_BLOCK_ID) {
rassert(head_block_id == _old_tail.get_block_id());
tail_block_id = head_block_id = NULL_BLOCK_ID;
} else {
tail_block_id = old_tail->next;
}
_old_tail.mark_deleted();
}
mutex_t mutex;
int64_t queue_size;
block_id_t head_block_id, tail_block_id;
scoped_ptr_t<standard_serializer_t> serializer;
scoped_ptr_t<cache_t> cache;
};
#endif /* CONTAINERS_DISK_BACKED_QUEUE_HPP_ */
<commit_msg>Added DISABLE_COPYING and made fields actually be private in disk_backed_queue_t.<commit_after>#ifndef CONTAINERS_DISK_BACKED_QUEUE_HPP_
#define CONTAINERS_DISK_BACKED_QUEUE_HPP_
#define MAX_REF_SIZE 251
#include <string>
#include <vector>
#include "arch/io/disk.hpp"
#include "buffer_cache/blob.hpp"
#include "buffer_cache/mirrored/mirrored.hpp"
#include "buffer_cache/semantic_checking.hpp"
#include "concurrency/queue/passive_producer.hpp"
#include "containers/archive/vector_stream.hpp"
#include "serializer/config.hpp"
#include "serializer/types.hpp"
//TODO there are extra copies all over the place mostly stemming from having a
//vector<char> from the serialization code and strings from the blob code.
struct queue_block_t {
block_id_t next;
int data_size, live_data_offset;
char data[0];
};
template <class T>
class disk_backed_queue_t {
public:
disk_backed_queue_t(io_backender_t *io_backender, std::string filename, perfmon_collection_t *stats_parent) :
queue_size(0), head_block_id(NULL_BLOCK_ID), tail_block_id(NULL_BLOCK_ID)
{
/* We're going to register for writes, however those writes won't be able
* to find their way in to the btree until we're done backfilling. Thus we
* need to set up a serializer and cache for them to go in to. */
//perfmon_collection_t backfill_stats_collection("queue-" + filename, NULL, true, true);
standard_serializer_t::create(
io_backender,
standard_serializer_t::private_dynamic_config_t(filename),
standard_serializer_t::static_config_t()
);
serializer.init(new standard_serializer_t(
standard_serializer_t::dynamic_config_t(),
io_backender,
standard_serializer_t::private_dynamic_config_t(filename),
stats_parent
));
/* Remove the file we just created from the filesystem, so that it will
get deleted as soon as the serializer is destroyed or if the process
crashes */
int res = unlink(filename.c_str());
guarantee_err(res == 0, "unlink() failed");
/* Create the cache. */
mirrored_cache_static_config_t cache_static_config;
cache_t::create(serializer.get(), &cache_static_config);
mirrored_cache_config_t cache_dynamic_config;
cache_dynamic_config.max_size = MEGABYTE;
cache_dynamic_config.max_dirty_size = MEGABYTE / 2;
cache.init(new cache_t(serializer.get(), &cache_dynamic_config, stats_parent));
}
void push(const T &t) {
mutex_t::acq_t mutex_acq(&mutex);
//first we need a transaction
transaction_t txn(cache.get(), rwi_write, 2, repli_timestamp_t::distant_past, order_token_t::ignore);
if (head_block_id == NULL_BLOCK_ID) {
add_block_to_head(&txn);
}
scoped_ptr_t<buf_lock_t> _head(new buf_lock_t(&txn, head_block_id, rwi_write));
queue_block_t* head = reinterpret_cast<queue_block_t *>(_head->get_data_major_write());
write_message_t wm;
wm << t;
vector_stream_t stream;
int res = send_write_message(&stream, &wm);
guarantee(res == 0);
char buffer[MAX_REF_SIZE];
bzero(buffer, MAX_REF_SIZE);
blob_t blob(buffer, MAX_REF_SIZE);
blob.append_region(&txn, stream.vector().size());
std::string sered_data(stream.vector().begin(), stream.vector().end());
blob.write_from_string(sered_data, &txn, 0);
if (((char *)(head->data + head->data_size) - (char *)(head)) + blob.refsize(cache->get_block_size()) > cache->get_block_size().value()) {
//The data won't fit in our current head block, so it's time to make a new one
head = NULL;
_head.reset();
add_block_to_head(&txn);
_head.init(new buf_lock_t(&txn, head_block_id, rwi_write));
head = reinterpret_cast<queue_block_t *>(_head->get_data_major_write());
}
memcpy(head->data + head->data_size, buffer, blob.refsize(cache->get_block_size()));
head->data_size += blob.refsize(cache->get_block_size());
queue_size++;
}
T pop() {
mutex_t::acq_t mutex_acq(&mutex);
char buffer[MAX_REF_SIZE];
transaction_t txn(cache.get(), rwi_write, 2, repli_timestamp_t::distant_past, order_token_t::ignore);
scoped_ptr_t<buf_lock_t> _tail(new buf_lock_t(&txn, tail_block_id, rwi_write));
queue_block_t *tail = reinterpret_cast<queue_block_t *>(_tail->get_data_major_write());
rassert(tail->data_size != tail->live_data_offset);
/* Grab the data from the blob and delete it. */
memcpy(buffer, tail->data + tail->live_data_offset, blob::ref_size(cache->get_block_size(), tail->data + tail->live_data_offset, MAX_REF_SIZE));
blob_t blob(buffer, MAX_REF_SIZE);
std::string data = blob.read_to_string(&txn, 0, blob.valuesize());
/* Record how far along in the blob we are. */
tail->live_data_offset += blob.refsize(cache->get_block_size());
blob.clear(&txn);
queue_size--;
/* If that was the last blob in this block move on to the next one. */
if (tail->live_data_offset == tail->data_size) {
_tail.reset();
remove_block_from_tail(&txn);
}
/* Deserialize the value and return it. */
std::vector<char> data_vec(data.begin(), data.end());
vector_read_stream_t read_stream(&data_vec);
T t;
int res = deserialize(&read_stream, &t);
guarantee_err(res == 0, "corruption in disk-backed queue");
return t;
}
bool empty() {
return queue_size == 0;
}
int size() {
return queue_size;
}
private:
void add_block_to_head(transaction_t *txn) {
buf_lock_t _new_head(txn);
queue_block_t *new_head = reinterpret_cast<queue_block_t *>(_new_head.get_data_major_write());
if (head_block_id == NULL_BLOCK_ID) {
rassert(tail_block_id == NULL_BLOCK_ID);
head_block_id = tail_block_id = _new_head.get_block_id();
} else {
buf_lock_t _old_head(txn, head_block_id, rwi_write);
queue_block_t *old_head = reinterpret_cast<queue_block_t *>(_old_head.get_data_major_write());
rassert(old_head->next == NULL_BLOCK_ID);
old_head->next = _new_head.get_block_id();
head_block_id = _new_head.get_block_id();
}
new_head->next = NULL_BLOCK_ID;
new_head->data_size = 0;
new_head->live_data_offset = 0;
}
void remove_block_from_tail(transaction_t *txn) {
rassert(tail_block_id != NULL_BLOCK_ID);
buf_lock_t _old_tail(txn, tail_block_id, rwi_write);
queue_block_t *old_tail = reinterpret_cast<queue_block_t *>(_old_tail.get_data_major_write());
if (old_tail->next == NULL_BLOCK_ID) {
rassert(head_block_id == _old_tail.get_block_id());
tail_block_id = head_block_id = NULL_BLOCK_ID;
} else {
tail_block_id = old_tail->next;
}
_old_tail.mark_deleted();
}
private:
mutex_t mutex;
int64_t queue_size;
block_id_t head_block_id, tail_block_id;
scoped_ptr_t<standard_serializer_t> serializer;
scoped_ptr_t<cache_t> cache;
DISABLE_COPYING(disk_backed_queue_t);
};
#endif /* CONTAINERS_DISK_BACKED_QUEUE_HPP_ */
<|endoftext|> |
<commit_before>/** dataset_context.cc
Jeremy Barnes, 24 February 2015
Copyright (c) 2015 Datacratic Inc. All rights reserved.
Context to bind a row expression to a dataset.
*/
#include "mldb/server/dataset_context.h"
#include "mldb/core/dataset.h"
#include "mldb/types/basic_value_descriptions.h"
#include "mldb/server/mldb_server.h"
#include "mldb/server/function_collection.h"
#include "mldb/server/dataset_collection.h"
#include "mldb/http/http_exception.h"
#include "mldb/jml/utils/lightweight_hash.h"
using namespace std;
namespace Datacratic {
namespace MLDB {
/*****************************************************************************/
/* ROW EXPRESSION MLDB CONTEXT */
/*****************************************************************************/
SqlExpressionMldbContext::
SqlExpressionMldbContext(const MldbServer * mldb)
: mldb(const_cast<MldbServer *>(mldb))
{
ExcAssert(mldb);
}
BoundFunction
SqlExpressionMldbContext::
doGetFunction(const Utf8String & tableName,
const Utf8String & functionName,
const std::vector<BoundSqlExpression> & args)
{
return SqlBindingScope::doGetFunction(tableName, functionName, args);
}
std::shared_ptr<Function>
SqlExpressionMldbContext::
doGetFunctionEntity(const Utf8String & functionName)
{
return mldb->functions->getExistingEntity(functionName.rawString());
}
std::shared_ptr<Dataset>
SqlExpressionMldbContext::
doGetDataset(const Utf8String & datasetName)
{
return mldb->datasets->getExistingEntity(datasetName.rawString());
}
std::shared_ptr<Dataset>
SqlExpressionMldbContext::
doGetDatasetFromConfig(const Any & datasetConfig)
{
return obtainDataset(mldb, datasetConfig.convert<PolyConfig>());
}
// defined in table_expression_operations.cc
BoundTableExpression
bindDataset(std::shared_ptr<Dataset> dataset, Utf8String asName);
TableOperations
SqlExpressionMldbContext::
doGetTable(const Utf8String & tableName)
{
return bindDataset(doGetDataset(tableName), Utf8String()).table;
}
MldbServer *
SqlExpressionMldbContext::
getMldbServer() const
{
return mldb;
}
/*****************************************************************************/
/* ROW EXPRESSION DATASET CONTEXT */
/*****************************************************************************/
SqlExpressionDatasetContext::
SqlExpressionDatasetContext(std::shared_ptr<Dataset> dataset, const Utf8String& alias)
: SqlExpressionMldbContext(dataset->server), dataset(*dataset), alias(alias)
{
dataset->getChildAliases(childaliases);
}
SqlExpressionDatasetContext::
SqlExpressionDatasetContext(const Dataset & dataset, const Utf8String& alias)
: SqlExpressionMldbContext(dataset.server), dataset(dataset), alias(alias)
{
dataset.getChildAliases(childaliases);
}
SqlExpressionDatasetContext::
SqlExpressionDatasetContext(const BoundTableExpression& boundDataset)
: SqlExpressionMldbContext(boundDataset.dataset->server), dataset(*boundDataset.dataset), alias(boundDataset.asName)
{
boundDataset.dataset->getChildAliases(childaliases);
}
//This is for the single-dataset context, when binding a variable
//If we know the alias of the dataset we are working on, this will remove it from the variable's name
//since it is not needed in this context.
//It will also verify that the variable identifier does not explicitly specify an dataset that is not of this context.
//Aka "unknown".identifier
Utf8String
SqlExpressionDatasetContext::
removeTableName(const Utf8String & variableName) const
{
Utf8String shortVariableName = variableName;
if (!alias.empty() && !variableName.empty()) {
Utf8String aliasWithDot = alias + ".";
if (!shortVariableName.removePrefix(aliasWithDot)) {
//check if there is a quoted prefix
auto it1 = shortVariableName.begin();
if (*it1 == '\"')
{
++it1;
auto end1 = shortVariableName.end();
auto it2 = alias.begin(), end2 = alias.end();
while (it1 != end1 && it2 != end2 && *it1 == *it2) {
++it1;
++it2;
}
if (it2 == end2 && it1 != end1 && *(it1) == '\"') {
shortVariableName.erase(shortVariableName.begin(), it1);
it1 = shortVariableName.begin();
end1 = shortVariableName.end();
//if the context's dataset name is specified we requite a .identifier to follow
if (it1 == end1 || *(++it1) != '.')
throw HttpReturnException(400, "Expected a dot '.' after table name " + alias);
else
shortVariableName.erase(shortVariableName.begin(), ++it1);
}
else {
//no match, but return an error on an unknown explicit table name.
while (it1 != end1) {
if (*it1 == '\"') {
if (++it1 != end1)
{
Utf8String datasetName(shortVariableName.begin(), it1);
throw HttpReturnException(400, "Unknown dataset '" + datasetName + "'");
}
}
else {
++it1;
}
}
}
}
}
}
return std::move(shortVariableName);
}
//After putting the variable name in context, this will remove unneeded outer quotes
//from the variable part of the identifier.
Utf8String
SqlExpressionDatasetContext::
removeQuotes(const Utf8String & variableName) const
{
if (!variableName.empty()) {
auto begin = variableName.begin();
auto last = boost::prior(variableName.end());
if ( *begin == '\"' && *last == '\"' && begin != last) {
++begin;
Utf8String shortVariableName(begin, last);
return std::move(shortVariableName);
}
}
return variableName;
}
//This is for the context where we have several datasets
//resolve ambiguity of different table names
//by finding the dataset name that resolves first.
Utf8String
SqlExpressionDatasetContext::
resolveTableName(const Utf8String& variable) const
{
if (variable.empty())
return Utf8String();
auto it = variable.begin();
if (*it == '"') {
//identifier starts in quote
//we want to remove the quotes if they are extraneous (now that we have context)
//and we want to remove the quotes around the variable's name (if any)
Utf8String quoteString = "\"";
++it;
it = std::search(it, variable.end(), quoteString.begin(), quoteString.end());
if (it != variable.end()) {
auto next = it;
next ++;
if (next != variable.end() && *next == '.') {
//Found something like "text".
//which is an explicit dataset name
//remove the quotes around the table name if there is no ambiguity (i.e, a "." inside)
Utf8String tableName(variable.begin(), next);
if (tableName.find(".") == tableName.end())
tableName = removeQuotes(tableName);
//remove the quote aroud the variable's name
next++;
if (next != variable.end()) {
Utf8String shortVariableName(next, variable.end());
shortVariableName = tableName + "." + removeQuotes(shortVariableName);
return shortVariableName;
}
}
}
}
else {
Utf8String dotString = ".";
do {
it = std::search(it, variable.end(), dotString.begin(), dotString.end());
if (it != variable.end()) {
//check if this portion of the identifier correspond to a dataset name within this context
Utf8String tableName(variable.begin(), it);
for (auto& datasetName: childaliases) {
if (tableName == datasetName) {
if (datasetName.find('.') != datasetName.end()) {
//we need to enclose it in quotes to resolve any potential ambiguity
Utf8String quotedVariableName(++it, variable.end());
quotedVariableName = "\"" + tableName + "\"" + "." + removeQuotes(quotedVariableName);
return quotedVariableName;
}
else {
//keep it unquoted
return variable;
}
}
}
++it;
}
} while (it != variable.end());
}
return variable;
}
VariableGetter
SqlExpressionDatasetContext::
doGetVariable(const Utf8String & tableName,
const Utf8String & variableName)
{
Utf8String simplifiedVariableName;
if (!childaliases.empty())
simplifiedVariableName = resolveTableName(variableName);
else
simplifiedVariableName = removeQuotes(removeTableName(variableName));
ColumnName columnName(simplifiedVariableName);
return {[=] (const SqlRowScope & context,
ExpressionValue & storage,
const VariableFilter & filter) -> const ExpressionValue &
{
auto & row = static_cast<const RowContext &>(context);
const ExpressionValue * fromOutput
= searchRow(row.row.columns, columnName, filter, storage);
if (fromOutput)
return *fromOutput;
return storage = std::move(ExpressionValue::null(Date::negativeInfinity()));
},
std::make_shared<AtomValueInfo>()};
}
BoundFunction
SqlExpressionDatasetContext::
doGetFunction(const Utf8String & tableName,
const Utf8String & functionName,
const std::vector<BoundSqlExpression> & args)
{
// First, let the dataset either override or implement the function
// itself.
auto fnoverride = dataset.overrideFunction(functionName, *this);
if (fnoverride)
return fnoverride;
if (functionName == "rowName") {
return {[=] (const std::vector<ExpressionValue> & args,
const SqlRowScope & context)
{
auto & row = static_cast<const RowContext &>(context);
return ExpressionValue(row.row.rowName.toUtf8String(),
Date::negativeInfinity());
},
std::make_shared<Utf8StringValueInfo>()
};
}
if (functionName == "rowHash") {
return {[=] (const std::vector<ExpressionValue> & args,
const SqlRowScope & context)
{
auto & row = static_cast<const RowContext &>(context);
return ExpressionValue(row.row.rowHash,
Date::negativeInfinity());
},
std::make_shared<Uint64ValueInfo>()
};
}
/* columnCount function: return number of columns with explicit values set
in the current row.
*/
if (functionName == "columnCount") {
return {[=] (const std::vector<ExpressionValue> & args,
const SqlRowScope & context)
{
auto & row = static_cast<const RowContext &>(context);
ML::Lightweight_Hash_Set<ColumnHash> columns;
Date ts = Date::negativeInfinity();
for (auto & c: row.row.columns) {
columns.insert(std::get<0>(c));
ts.setMax(std::get<2>(c));
}
return ExpressionValue(columns.size(), ts);
},
std::make_shared<Uint64ValueInfo>()};
}
return SqlBindingScope::doGetFunction(tableName, functionName, args);
}
VariableGetter
SqlExpressionDatasetContext::
doGetBoundParameter(const Utf8String & paramName)
{
return {[=] (const SqlRowScope & context,
ExpressionValue & storage,
const VariableFilter & filter) -> const ExpressionValue &
{
ExcAssert(canIgnoreIfExactlyOneValue(filter));
auto & row = static_cast<const RowContext &>(context);
if (!row.params || !*row.params)
throw HttpReturnException(400, "Bound parameters requested but none passed");
return storage = std::move((*row.params)(paramName));
},
std::make_shared<AnyValueInfo>()};
}
GetAllColumnsOutput
SqlExpressionDatasetContext::
doGetAllColumns(const Utf8String & tableName,
std::function<Utf8String (const Utf8String &)> keep)
{
if (!tableName.empty()
&& std::find(childaliases.begin(), childaliases.end(), tableName)
== childaliases.end()
&& tableName != alias)
throw HttpReturnException(400, "Unknown dataset " + tableName);
auto columns = dataset.getMatrixView()->getColumnNames();
std::sort(columns.begin(), columns.end(),
[] (const ColumnName & c1, const ColumnName & c2)
{ return c1.toString() < c2.toString(); });
auto filterColumnName = [&] (const Utf8String & inputColumnName) -> Utf8String
{
if (!tableName.empty() && !childaliases.empty() && !inputColumnName.startsWith(tableName)) {
return "";
}
return keep(inputColumnName);
};
std::unordered_map<ColumnHash, ColumnName> index;
std::vector<KnownColumn> columnsWithInfo;
for (auto & columnName: columns) {
ColumnName outputName(filterColumnName(columnName.toUtf8String()));
if (outputName == ColumnName())
continue;
// Ask the dataset to describe this column
columnsWithInfo.emplace_back(std::move(dataset.getKnownColumnInfo(columnName)));
// Change the name to the output name
columnsWithInfo.back().columnName = outputName;
index[columnName] = outputName;
}
auto exec = [=] (const SqlRowScope & context)
{
auto & row = static_cast<const RowContext &>(context);
RowValue result;
for (auto & c: row.row.columns) {
auto it = index.find(std::get<0>(c));
if (it == index.end()) {
continue;
}
result.emplace_back(it->second, std::get<1>(c), std::get<2>(c));
}
return std::move(result);
};
GetAllColumnsOutput result;
result.exec = exec;
result.info = std::make_shared<RowValueInfo>(std::move(columnsWithInfo),
SCHEMA_CLOSED);
return result;
}
GenerateRowsWhereFunction
SqlExpressionDatasetContext::
doCreateRowsWhereGenerator(const SqlExpression & where,
ssize_t offset,
ssize_t limit)
{
auto res = dataset.generateRowsWhere(*this, where, offset, limit);
if (!res)
throw HttpReturnException(500, "Dataset returned null generator",
"datasetType", ML::type_name(dataset));
return res;
}
ColumnFunction
SqlExpressionDatasetContext::
doGetColumnFunction(const Utf8String & functionName)
{
if (functionName == "columnName") {
return {[=] (const ColumnName & columnName,
const std::vector<ExpressionValue> & args)
{
return ExpressionValue(columnName.toUtf8String(),
Date::negativeInfinity());
}};
}
if (functionName == "columnHash") {
return {[=] (const ColumnName & columnName,
const std::vector<ExpressionValue> & args)
{
return ExpressionValue(columnName.hash(),
Date::negativeInfinity());
}};
}
if (functionName == "rowCount") {
return {[=] (const ColumnName & columnName,
const std::vector<ExpressionValue> & args)
{
return ExpressionValue
(dataset.getColumnIndex()->getColumnRowCount(columnName),
Date::notADate());
}};
}
return nullptr;
}
/*****************************************************************************/
/* ROW EXPRESSION ORDER BY CONTEXT */
/*****************************************************************************/
VariableGetter
SqlExpressionOrderByContext::
doGetVariable(const Utf8String & tableName, const Utf8String & variableName)
{
/** An order by clause can read through both what was selected and what
was in the underlying row. So we first look in what was selected,
and then fall back to the underlying row.
*/
ColumnName columnName(variableName);
auto innerGetVariable
= ReadThroughBindingContext::doGetVariable(tableName, variableName);
return {[=] (const SqlRowScope & context,
ExpressionValue & storage,
const VariableFilter & filter) -> const ExpressionValue &
{
auto & row = static_cast<const RowContext &>(context);
const ExpressionValue * fromOutput
= searchRow(row.output.columns, columnName, filter, storage);
if (fromOutput)
return *fromOutput;
return innerGetVariable(context, storage);
},
std::make_shared<AtomValueInfo>()};
}
} // namespace MLDB
} // namespace Datacratic
<commit_msg>Optimized DatasetContext::doGetAllColumns() (MLDB-1290)<commit_after>/** dataset_context.cc
Jeremy Barnes, 24 February 2015
Copyright (c) 2015 Datacratic Inc. All rights reserved.
Context to bind a row expression to a dataset.
*/
#include "mldb/server/dataset_context.h"
#include "mldb/core/dataset.h"
#include "mldb/types/basic_value_descriptions.h"
#include "mldb/server/mldb_server.h"
#include "mldb/server/function_collection.h"
#include "mldb/server/dataset_collection.h"
#include "mldb/http/http_exception.h"
#include "mldb/jml/utils/lightweight_hash.h"
using namespace std;
namespace Datacratic {
namespace MLDB {
/*****************************************************************************/
/* ROW EXPRESSION MLDB CONTEXT */
/*****************************************************************************/
SqlExpressionMldbContext::
SqlExpressionMldbContext(const MldbServer * mldb)
: mldb(const_cast<MldbServer *>(mldb))
{
ExcAssert(mldb);
}
BoundFunction
SqlExpressionMldbContext::
doGetFunction(const Utf8String & tableName,
const Utf8String & functionName,
const std::vector<BoundSqlExpression> & args)
{
return SqlBindingScope::doGetFunction(tableName, functionName, args);
}
std::shared_ptr<Function>
SqlExpressionMldbContext::
doGetFunctionEntity(const Utf8String & functionName)
{
return mldb->functions->getExistingEntity(functionName.rawString());
}
std::shared_ptr<Dataset>
SqlExpressionMldbContext::
doGetDataset(const Utf8String & datasetName)
{
return mldb->datasets->getExistingEntity(datasetName.rawString());
}
std::shared_ptr<Dataset>
SqlExpressionMldbContext::
doGetDatasetFromConfig(const Any & datasetConfig)
{
return obtainDataset(mldb, datasetConfig.convert<PolyConfig>());
}
// defined in table_expression_operations.cc
BoundTableExpression
bindDataset(std::shared_ptr<Dataset> dataset, Utf8String asName);
TableOperations
SqlExpressionMldbContext::
doGetTable(const Utf8String & tableName)
{
return bindDataset(doGetDataset(tableName), Utf8String()).table;
}
MldbServer *
SqlExpressionMldbContext::
getMldbServer() const
{
return mldb;
}
/*****************************************************************************/
/* ROW EXPRESSION DATASET CONTEXT */
/*****************************************************************************/
SqlExpressionDatasetContext::
SqlExpressionDatasetContext(std::shared_ptr<Dataset> dataset, const Utf8String& alias)
: SqlExpressionMldbContext(dataset->server), dataset(*dataset), alias(alias)
{
dataset->getChildAliases(childaliases);
}
SqlExpressionDatasetContext::
SqlExpressionDatasetContext(const Dataset & dataset, const Utf8String& alias)
: SqlExpressionMldbContext(dataset.server), dataset(dataset), alias(alias)
{
dataset.getChildAliases(childaliases);
}
SqlExpressionDatasetContext::
SqlExpressionDatasetContext(const BoundTableExpression& boundDataset)
: SqlExpressionMldbContext(boundDataset.dataset->server), dataset(*boundDataset.dataset), alias(boundDataset.asName)
{
boundDataset.dataset->getChildAliases(childaliases);
}
//This is for the single-dataset context, when binding a variable
//If we know the alias of the dataset we are working on, this will remove it from the variable's name
//since it is not needed in this context.
//It will also verify that the variable identifier does not explicitly specify an dataset that is not of this context.
//Aka "unknown".identifier
Utf8String
SqlExpressionDatasetContext::
removeTableName(const Utf8String & variableName) const
{
Utf8String shortVariableName = variableName;
if (!alias.empty() && !variableName.empty()) {
Utf8String aliasWithDot = alias + ".";
if (!shortVariableName.removePrefix(aliasWithDot)) {
//check if there is a quoted prefix
auto it1 = shortVariableName.begin();
if (*it1 == '\"')
{
++it1;
auto end1 = shortVariableName.end();
auto it2 = alias.begin(), end2 = alias.end();
while (it1 != end1 && it2 != end2 && *it1 == *it2) {
++it1;
++it2;
}
if (it2 == end2 && it1 != end1 && *(it1) == '\"') {
shortVariableName.erase(shortVariableName.begin(), it1);
it1 = shortVariableName.begin();
end1 = shortVariableName.end();
//if the context's dataset name is specified we requite a .identifier to follow
if (it1 == end1 || *(++it1) != '.')
throw HttpReturnException(400, "Expected a dot '.' after table name " + alias);
else
shortVariableName.erase(shortVariableName.begin(), ++it1);
}
else {
//no match, but return an error on an unknown explicit table name.
while (it1 != end1) {
if (*it1 == '\"') {
if (++it1 != end1)
{
Utf8String datasetName(shortVariableName.begin(), it1);
throw HttpReturnException(400, "Unknown dataset '" + datasetName + "'");
}
}
else {
++it1;
}
}
}
}
}
}
return std::move(shortVariableName);
}
//After putting the variable name in context, this will remove unneeded outer quotes
//from the variable part of the identifier.
Utf8String
SqlExpressionDatasetContext::
removeQuotes(const Utf8String & variableName) const
{
if (!variableName.empty()) {
auto begin = variableName.begin();
auto last = boost::prior(variableName.end());
if ( *begin == '\"' && *last == '\"' && begin != last) {
++begin;
Utf8String shortVariableName(begin, last);
return std::move(shortVariableName);
}
}
return variableName;
}
//This is for the context where we have several datasets
//resolve ambiguity of different table names
//by finding the dataset name that resolves first.
Utf8String
SqlExpressionDatasetContext::
resolveTableName(const Utf8String& variable) const
{
if (variable.empty())
return Utf8String();
auto it = variable.begin();
if (*it == '"') {
//identifier starts in quote
//we want to remove the quotes if they are extraneous (now that we have context)
//and we want to remove the quotes around the variable's name (if any)
Utf8String quoteString = "\"";
++it;
it = std::search(it, variable.end(), quoteString.begin(), quoteString.end());
if (it != variable.end()) {
auto next = it;
next ++;
if (next != variable.end() && *next == '.') {
//Found something like "text".
//which is an explicit dataset name
//remove the quotes around the table name if there is no ambiguity (i.e, a "." inside)
Utf8String tableName(variable.begin(), next);
if (tableName.find(".") == tableName.end())
tableName = removeQuotes(tableName);
//remove the quote aroud the variable's name
next++;
if (next != variable.end()) {
Utf8String shortVariableName(next, variable.end());
shortVariableName = tableName + "." + removeQuotes(shortVariableName);
return shortVariableName;
}
}
}
}
else {
Utf8String dotString = ".";
do {
it = std::search(it, variable.end(), dotString.begin(), dotString.end());
if (it != variable.end()) {
//check if this portion of the identifier correspond to a dataset name within this context
Utf8String tableName(variable.begin(), it);
for (auto& datasetName: childaliases) {
if (tableName == datasetName) {
if (datasetName.find('.') != datasetName.end()) {
//we need to enclose it in quotes to resolve any potential ambiguity
Utf8String quotedVariableName(++it, variable.end());
quotedVariableName = "\"" + tableName + "\"" + "." + removeQuotes(quotedVariableName);
return quotedVariableName;
}
else {
//keep it unquoted
return variable;
}
}
}
++it;
}
} while (it != variable.end());
}
return variable;
}
VariableGetter
SqlExpressionDatasetContext::
doGetVariable(const Utf8String & tableName,
const Utf8String & variableName)
{
Utf8String simplifiedVariableName;
if (!childaliases.empty())
simplifiedVariableName = resolveTableName(variableName);
else
simplifiedVariableName = removeQuotes(removeTableName(variableName));
ColumnName columnName(simplifiedVariableName);
return {[=] (const SqlRowScope & context,
ExpressionValue & storage,
const VariableFilter & filter) -> const ExpressionValue &
{
auto & row = static_cast<const RowContext &>(context);
const ExpressionValue * fromOutput
= searchRow(row.row.columns, columnName, filter, storage);
if (fromOutput)
return *fromOutput;
return storage = std::move(ExpressionValue::null(Date::negativeInfinity()));
},
std::make_shared<AtomValueInfo>()};
}
BoundFunction
SqlExpressionDatasetContext::
doGetFunction(const Utf8String & tableName,
const Utf8String & functionName,
const std::vector<BoundSqlExpression> & args)
{
// First, let the dataset either override or implement the function
// itself.
auto fnoverride = dataset.overrideFunction(functionName, *this);
if (fnoverride)
return fnoverride;
if (functionName == "rowName") {
return {[=] (const std::vector<ExpressionValue> & args,
const SqlRowScope & context)
{
auto & row = static_cast<const RowContext &>(context);
return ExpressionValue(row.row.rowName.toUtf8String(),
Date::negativeInfinity());
},
std::make_shared<Utf8StringValueInfo>()
};
}
if (functionName == "rowHash") {
return {[=] (const std::vector<ExpressionValue> & args,
const SqlRowScope & context)
{
auto & row = static_cast<const RowContext &>(context);
return ExpressionValue(row.row.rowHash,
Date::negativeInfinity());
},
std::make_shared<Uint64ValueInfo>()
};
}
/* columnCount function: return number of columns with explicit values set
in the current row.
*/
if (functionName == "columnCount") {
return {[=] (const std::vector<ExpressionValue> & args,
const SqlRowScope & context)
{
auto & row = static_cast<const RowContext &>(context);
ML::Lightweight_Hash_Set<ColumnHash> columns;
Date ts = Date::negativeInfinity();
for (auto & c: row.row.columns) {
columns.insert(std::get<0>(c));
ts.setMax(std::get<2>(c));
}
return ExpressionValue(columns.size(), ts);
},
std::make_shared<Uint64ValueInfo>()};
}
return SqlBindingScope::doGetFunction(tableName, functionName, args);
}
VariableGetter
SqlExpressionDatasetContext::
doGetBoundParameter(const Utf8String & paramName)
{
return {[=] (const SqlRowScope & context,
ExpressionValue & storage,
const VariableFilter & filter) -> const ExpressionValue &
{
ExcAssert(canIgnoreIfExactlyOneValue(filter));
auto & row = static_cast<const RowContext &>(context);
if (!row.params || !*row.params)
throw HttpReturnException(400, "Bound parameters requested but none passed");
return storage = std::move((*row.params)(paramName));
},
std::make_shared<AnyValueInfo>()};
}
GetAllColumnsOutput
SqlExpressionDatasetContext::
doGetAllColumns(const Utf8String & tableName,
std::function<Utf8String (const Utf8String &)> keep)
{
if (!tableName.empty()
&& std::find(childaliases.begin(), childaliases.end(), tableName)
== childaliases.end()
&& tableName != alias)
throw HttpReturnException(400, "Unknown dataset " + tableName);
auto columns = dataset.getMatrixView()->getColumnNames();
std::sort(columns.begin(), columns.end(),
[] (const ColumnName & c1, const ColumnName & c2)
{ return c1.toString() < c2.toString(); });
auto filterColumnName = [&] (const Utf8String & inputColumnName) -> Utf8String
{
if (!tableName.empty() && !childaliases.empty() && !inputColumnName.startsWith(tableName)) {
return "";
}
return keep(inputColumnName);
};
std::unordered_map<ColumnHash, ColumnName> index;
std::vector<KnownColumn> columnsWithInfo;
bool allWereKept = true;
bool noneWereRenamed = true;
vector<ColumnName> columnsNeedingInfo;
for (auto & columnName: columns) {
ColumnName outputName(filterColumnName(columnName.toUtf8String()));
if (outputName == ColumnName()) {
allWereKept = false;
continue;
}
if (outputName != columnName)
noneWereRenamed = false;
columnsNeedingInfo.push_back(columnName);
index[columnName] = outputName;
// Ask the dataset to describe this column later, null ptr for now
columnsWithInfo.emplace_back(outputName, nullptr,
COLUMN_IS_DENSE);
// Change the name to the output name
//columnsWithInfo.back().columnName = outputName;
}
auto allInfo = dataset.getKnownColumnInfos(columnsNeedingInfo);
// Now put in the value info
for (unsigned i = 0; i < allInfo.size(); ++i) {
ColumnName outputName = columnsWithInfo[i].columnName;
columnsWithInfo[i] = allInfo[i];
columnsWithInfo[i].columnName = std::move(outputName);
}
std::function<ExpressionValue (const SqlRowScope &)> exec;
if (allWereKept && noneWereRenamed) {
// We can pass right through; we have a select *
exec = [=] (const SqlRowScope & context) -> ExpressionValue
{
auto & row = static_cast<const RowContext &>(context);
// TODO: if one day we are able to prove that this is
// the only expression that touches the row, we could
// move it into place
return row.row.columns;
};
}
else {
// Some are excluded or renamed; we need to go one by one
exec = [=] (const SqlRowScope & context)
{
auto & row = static_cast<const RowContext &>(context);
RowValue result;
for (auto & c: row.row.columns) {
auto it = index.find(std::get<0>(c));
if (it == index.end()) {
continue;
}
result.emplace_back(it->second, std::get<1>(c), std::get<2>(c));
}
return std::move(result);
};
}
GetAllColumnsOutput result;
result.exec = exec;
result.info = std::make_shared<RowValueInfo>(std::move(columnsWithInfo),
SCHEMA_CLOSED);
return result;
}
GenerateRowsWhereFunction
SqlExpressionDatasetContext::
doCreateRowsWhereGenerator(const SqlExpression & where,
ssize_t offset,
ssize_t limit)
{
auto res = dataset.generateRowsWhere(*this, where, offset, limit);
if (!res)
throw HttpReturnException(500, "Dataset returned null generator",
"datasetType", ML::type_name(dataset));
return res;
}
ColumnFunction
SqlExpressionDatasetContext::
doGetColumnFunction(const Utf8String & functionName)
{
if (functionName == "columnName") {
return {[=] (const ColumnName & columnName,
const std::vector<ExpressionValue> & args)
{
return ExpressionValue(columnName.toUtf8String(),
Date::negativeInfinity());
}};
}
if (functionName == "columnHash") {
return {[=] (const ColumnName & columnName,
const std::vector<ExpressionValue> & args)
{
return ExpressionValue(columnName.hash(),
Date::negativeInfinity());
}};
}
if (functionName == "rowCount") {
return {[=] (const ColumnName & columnName,
const std::vector<ExpressionValue> & args)
{
return ExpressionValue
(dataset.getColumnIndex()->getColumnRowCount(columnName),
Date::notADate());
}};
}
return nullptr;
}
/*****************************************************************************/
/* ROW EXPRESSION ORDER BY CONTEXT */
/*****************************************************************************/
VariableGetter
SqlExpressionOrderByContext::
doGetVariable(const Utf8String & tableName, const Utf8String & variableName)
{
/** An order by clause can read through both what was selected and what
was in the underlying row. So we first look in what was selected,
and then fall back to the underlying row.
*/
ColumnName columnName(variableName);
auto innerGetVariable
= ReadThroughBindingContext::doGetVariable(tableName, variableName);
return {[=] (const SqlRowScope & context,
ExpressionValue & storage,
const VariableFilter & filter) -> const ExpressionValue &
{
auto & row = static_cast<const RowContext &>(context);
const ExpressionValue * fromOutput
= searchRow(row.output.columns, columnName, filter, storage);
if (fromOutput)
return *fromOutput;
return innerGetVariable(context, storage);
},
std::make_shared<AtomValueInfo>()};
}
} // namespace MLDB
} // namespace Datacratic
<|endoftext|> |
<commit_before>/** dataset_context.cc
Jeremy Barnes, 24 February 2015
Copyright (c) 2015 Datacratic Inc. All rights reserved.
Context to bind a row expression to a dataset.
*/
#include "mldb/server/dataset_context.h"
#include "mldb/core/dataset.h"
#include "mldb/types/basic_value_descriptions.h"
#include "mldb/server/mldb_server.h"
#include "mldb/server/function_collection.h"
#include "mldb/server/dataset_collection.h"
#include "mldb/http/http_exception.h"
#include "mldb/jml/utils/lightweight_hash.h"
#include "mldb/sql/sql_utils.h"
using namespace std;
namespace Datacratic {
namespace MLDB {
/*****************************************************************************/
/* SQL EXPRESSION MLDB SCOPE */
/*****************************************************************************/
SqlExpressionMldbScope::
SqlExpressionMldbScope(const MldbServer * mldb)
: mldb(const_cast<MldbServer *>(mldb))
{
ExcAssert(mldb);
}
BoundFunction
SqlExpressionMldbScope::
doGetFunction(const Utf8String & tableName,
const Utf8String & functionName,
const std::vector<BoundSqlExpression> & args,
SqlBindingScope & argScope)
{
// User functions don't live in table scope
if (tableName.empty()) {
// 1. Try to get a function entity
auto fn = mldb->functions->tryGetExistingEntity(functionName.rawString());
if (fn) {
// We found one. Now wrap it up as a normal function.
if (args.size() > 1)
throw HttpReturnException(400, "User function " + functionName
+ " expected a single row { } argument");
std::shared_ptr<FunctionApplier> applier;
if (args.empty()) {
applier.reset
(fn->bind(argScope,
std::make_shared<RowValueInfo>(std::vector<KnownColumn>()))
.release());
}
else {
if (!args[0].info->isRow()) {
throw HttpReturnException(400, "User function " + functionName
+ " expects a row argument ({ }), "
+ "got " + args[0].expr->print() );
}
applier.reset(fn->bind(argScope, ExpressionValueInfo::toRow(args[0].info))
.release());
}
auto exec = [=] (const std::vector<ExpressionValue> & args,
const SqlRowScope & scope)
-> ExpressionValue
{
if (args.empty()) {
return applier->apply(ExpressionValue());
}
else {
return applier->apply(args[0]);
}
};
return BoundFunction(exec, applier->info.output);
}
}
return SqlBindingScope::doGetFunction(tableName, functionName, args,
argScope);
}
std::shared_ptr<Dataset>
SqlExpressionMldbScope::
doGetDataset(const Utf8String & datasetName)
{
return mldb->datasets->getExistingEntity(datasetName.rawString());
}
std::shared_ptr<Dataset>
SqlExpressionMldbScope::
doGetDatasetFromConfig(const Any & datasetConfig)
{
return obtainDataset(mldb, datasetConfig.convert<PolyConfig>());
}
// defined in table_expression_operations.cc
BoundTableExpression
bindDataset(std::shared_ptr<Dataset> dataset, Utf8String asName);
TableOperations
SqlExpressionMldbScope::
doGetTable(const Utf8String & tableName)
{
return bindDataset(doGetDataset(tableName), Utf8String()).table;
}
MldbServer *
SqlExpressionMldbScope::
getMldbServer() const
{
return mldb;
}
ColumnGetter
SqlExpressionMldbScope::
doGetColumn(const Utf8String & tableName,
const ColumnName & columnName)
{
throw HttpReturnException(400, "Cannot read column \"" + columnName.toUtf8String() + "\" with no dataset.");
}
/*****************************************************************************/
/* ROW EXPRESSION DATASET CONTEXT */
/*****************************************************************************/
SqlExpressionDatasetScope::
SqlExpressionDatasetScope(std::shared_ptr<Dataset> dataset, const Utf8String& alias)
: SqlExpressionMldbScope(dataset->server), dataset(*dataset), alias(alias)
{
dataset->getChildAliases(childaliases);
}
SqlExpressionDatasetScope::
SqlExpressionDatasetScope(const Dataset & dataset, const Utf8String& alias)
: SqlExpressionMldbScope(dataset.server), dataset(dataset), alias(alias)
{
dataset.getChildAliases(childaliases);
}
SqlExpressionDatasetScope::
SqlExpressionDatasetScope(const BoundTableExpression& boundDataset)
: SqlExpressionMldbScope(boundDataset.dataset->server),
dataset(*boundDataset.dataset),
alias(boundDataset.asName)
{
boundDataset.dataset->getChildAliases(childaliases);
}
ColumnGetter
SqlExpressionDatasetScope::
doGetColumn(const Utf8String & tableName,
const ColumnName & columnName)
{
ColumnName simplified;
if (tableName.empty() && columnName.size() > 1) {
if (!alias.empty() && columnName.startsWith(alias)) {
simplified = columnName.removePrefix();
}
}
if (simplified.empty())
simplified = columnName;
//cerr << "doGetColumn: " << tableName << " " << columnName << endl;
//cerr << columnName.size() << endl;
//cerr << "alias " << alias << endl;
//for (auto & c: childaliases)
// cerr << " child " << c << endl;
//cerr << "simplified = " << simplified << endl;
return {[=] (const SqlRowScope & context,
ExpressionValue & storage,
const VariableFilter & filter) -> const ExpressionValue &
{
auto & row = context.as<RowScope>();
const ExpressionValue * fromOutput
= searchRow(row.row.columns, simplified, filter, storage);
if (fromOutput)
return *fromOutput;
return storage = std::move(ExpressionValue::null(Date::negativeInfinity()));
},
std::make_shared<AtomValueInfo>()};
}
BoundFunction
SqlExpressionDatasetScope::
doGetFunction(const Utf8String & tableName,
const Utf8String & functionName,
const std::vector<BoundSqlExpression> & args,
SqlBindingScope & argScope)
{
// First, let the dataset either override or implement the function
// itself.
auto fnoverride = dataset.overrideFunction(tableName, functionName, argScope);
if (fnoverride)
return fnoverride;
// Look for a derived function
auto fnderived
= getDatasetDerivedFunction(tableName, functionName, args, argScope,
*this, "row");
if (fnderived)
return fnderived;
if (functionName == "rowName") {
return {[=] (const std::vector<ExpressionValue> & args,
const SqlRowScope & context)
{
auto & row = context.as<RowScope>();
return ExpressionValue(row.row.rowName.toUtf8String(),
Date::negativeInfinity());
},
std::make_shared<Utf8StringValueInfo>()
};
}
if (functionName == "rowPath") {
return {[=] (const std::vector<ExpressionValue> & args,
const SqlRowScope & context)
{
auto & row = context.as<RowScope>();
return ExpressionValue(CellValue(row.row.rowName),
Date::negativeInfinity());
},
std::make_shared<PathValueInfo>()
};
}
if (functionName == "rowHash") {
return {[=] (const std::vector<ExpressionValue> & args,
const SqlRowScope & context)
{
auto & row = context.as<RowScope>();
return ExpressionValue(row.row.rowHash,
Date::negativeInfinity());
},
std::make_shared<Uint64ValueInfo>()
};
}
/* columnCount function: return number of columns with explicit values set
in the current row.
*/
if (functionName == "columnCount") {
return {[=] (const std::vector<ExpressionValue> & args,
const SqlRowScope & context)
{
auto & row = context.as<RowScope>();
ML::Lightweight_Hash_Set<ColumnHash> columns;
Date ts = Date::negativeInfinity();
for (auto & c: row.row.columns) {
columns.insert(std::get<0>(c));
ts.setMax(std::get<2>(c));
}
return ExpressionValue(columns.size(), ts);
},
std::make_shared<Uint64ValueInfo>()};
}
return SqlExpressionMldbScope
::doGetFunction(tableName, functionName,
args, argScope);
}
ColumnGetter
SqlExpressionDatasetScope::
doGetBoundParameter(const Utf8String & paramName)
{
return {[=] (const SqlRowScope & context,
ExpressionValue & storage,
const VariableFilter & filter) -> const ExpressionValue &
{
ExcAssert(canIgnoreIfExactlyOneValue(filter));
auto & row = context.as<RowScope>();
if (!row.params || !*row.params)
throw HttpReturnException(400, "Bound parameters requested but none passed");
return storage = std::move((*row.params)(paramName));
},
std::make_shared<AnyValueInfo>()};
}
GetAllColumnsOutput
SqlExpressionDatasetScope::
doGetAllColumns(const Utf8String & tableName,
std::function<ColumnName (const ColumnName &)> keep)
{
if (!tableName.empty()
&& std::find(childaliases.begin(), childaliases.end(), tableName)
== childaliases.end()
&& tableName != alias)
throw HttpReturnException(400, "Unknown dataset " + tableName);
auto columns = dataset.getMatrixView()->getColumnNames();
auto filterColumnName = [&] (const ColumnName & inputColumnName)
-> ColumnName
{
if (!tableName.empty() && !childaliases.empty()) {
// We're in a join. The columns will all be prefixed with their
// child table name, but we don't want to use that.
// eg, in x inner join y, we will have variables like
// x.a and y.b, but when we select them we want them to be
// like a and b.
if (!inputColumnName.startsWith(tableName)) {
return ColumnName();
}
// Otherwise, check if we need it
ColumnName result = keep(inputColumnName);
return std::move(result);
}
return keep(inputColumnName);
};
std::unordered_map<ColumnHash, ColumnName> index;
std::vector<KnownColumn> columnsWithInfo;
bool allWereKept = true;
bool noneWereRenamed = true;
vector<ColumnName> columnsNeedingInfo;
for (auto & columnName: columns) {
ColumnName outputName(filterColumnName(columnName));
if (outputName == ColumnName()) {
allWereKept = false;
continue;
}
if (outputName != columnName)
noneWereRenamed = false;
columnsNeedingInfo.push_back(columnName);
index[columnName] = outputName;
// Ask the dataset to describe this column later, null ptr for now
columnsWithInfo.emplace_back(outputName, nullptr,
COLUMN_IS_DENSE);
// Change the name to the output name
//columnsWithInfo.back().columnName = outputName;
}
auto allInfo = dataset.getKnownColumnInfos(columnsNeedingInfo);
// Now put in the value info
for (unsigned i = 0; i < allInfo.size(); ++i) {
ColumnName outputName = columnsWithInfo[i].columnName;
columnsWithInfo[i] = allInfo[i];
columnsWithInfo[i].columnName = std::move(outputName);
}
std::function<ExpressionValue (const SqlRowScope &, const VariableFilter &)> exec;
if (allWereKept && noneWereRenamed) {
// We can pass right through; we have a select *
exec = [=] (const SqlRowScope & context, const VariableFilter & filter) -> ExpressionValue
{
auto & row = context.as<RowScope>();
// TODO: if one day we are able to prove that this is
// the only expression that touches the row, we could
// move it into place
ExpressionValue val(row.row.columns);
return val.getFilteredDestructive(filter);
};
}
else {
// Some are excluded or renamed; we need to go one by one
exec = [=] (const SqlRowScope & context, const VariableFilter & filter)
{
auto & row = context.as<RowScope>();
RowValue result;
for (auto & c: row.row.columns) {
auto it = index.find(std::get<0>(c));
if (it == index.end()) {
continue;
}
result.emplace_back(it->second, std::get<1>(c), std::get<2>(c));
}
ExpressionValue val(std::move(result));
return val.getFilteredDestructive(filter);
};
}
GetAllColumnsOutput result;
result.exec = exec;
result.info = std::make_shared<RowValueInfo>(std::move(columnsWithInfo),
SCHEMA_CLOSED);
return result;
}
GenerateRowsWhereFunction
SqlExpressionDatasetScope::
doCreateRowsWhereGenerator(const SqlExpression & where,
ssize_t offset,
ssize_t limit)
{
auto res = dataset.generateRowsWhere(*this, alias, where, offset, limit);
if (!res)
throw HttpReturnException(500, "Dataset returned null generator",
"datasetType", ML::type_name(dataset));
return res;
}
ColumnFunction
SqlExpressionDatasetScope::
doGetColumnFunction(const Utf8String & functionName)
{
if (functionName == "columnName") {
return {[=] (const ColumnName & columnName,
const std::vector<ExpressionValue> & args)
{
return ExpressionValue(columnName.toUtf8String(),
Date::negativeInfinity());
}};
}
if (functionName == "columnHash") {
return {[=] (const ColumnName & columnName,
const std::vector<ExpressionValue> & args)
{
return ExpressionValue(columnName.hash(),
Date::negativeInfinity());
}};
}
if (functionName == "rowCount") {
return {[=] (const ColumnName & columnName,
const std::vector<ExpressionValue> & args)
{
return ExpressionValue
(dataset.getColumnIndex()->getColumnRowCount(columnName),
Date::notADate());
}};
}
return nullptr;
}
ColumnName
SqlExpressionDatasetScope::
doResolveTableName(const ColumnName & fullColumnName, Utf8String &tableName) const
{
if (!childaliases.empty()) {
for (auto & a: childaliases) {
if (fullColumnName.startsWith(a)) {
tableName = a;
return fullColumnName.removePrefix();
}
}
}
else {
if (!alias.empty() && fullColumnName.startsWith(alias)) {
tableName = alias;
return fullColumnName.removePrefix();
}
}
tableName = Utf8String();
return fullColumnName;
}
/*****************************************************************************/
/* ROW EXPRESSION ORDER BY CONTEXT */
/*****************************************************************************/
ColumnGetter
SqlExpressionOrderByScope::
doGetColumn(const Utf8String & tableName, const ColumnName & columnName)
{
/** An order by clause can read through both what was selected and what
was in the underlying row. So we first look in what was selected,
and then fall back to the underlying row.
*/
auto innerGetVariable
= ReadThroughBindingScope::doGetColumn(tableName, columnName);
return {[=] (const SqlRowScope & context,
ExpressionValue & storage,
const VariableFilter & filter) -> const ExpressionValue &
{
auto & row = context.as<RowScope>();
const ExpressionValue * fromOutput
= searchRow(row.output.columns, columnName.front(),
filter, storage);
if (fromOutput) {
if (columnName.size() == 1) {
return *fromOutput;
}
else {
ColumnName tail = columnName.removePrefix();
return storage = fromOutput->getNestedColumn(tail, filter);
}
}
return innerGetVariable(context, storage);
},
std::make_shared<AtomValueInfo>()};
}
} // namespace MLDB
} // namespace Datacratic
<commit_msg>Use reasonable form of implementation of rowPath() function that doesn't parse rowName() (MLDB-1765)<commit_after>/** dataset_context.cc
Jeremy Barnes, 24 February 2015
Copyright (c) 2015 Datacratic Inc. All rights reserved.
Context to bind a row expression to a dataset.
*/
#include "mldb/server/dataset_context.h"
#include "mldb/core/dataset.h"
#include "mldb/types/basic_value_descriptions.h"
#include "mldb/server/mldb_server.h"
#include "mldb/server/function_collection.h"
#include "mldb/server/dataset_collection.h"
#include "mldb/http/http_exception.h"
#include "mldb/jml/utils/lightweight_hash.h"
#include "mldb/sql/sql_utils.h"
using namespace std;
namespace Datacratic {
namespace MLDB {
/*****************************************************************************/
/* SQL EXPRESSION MLDB SCOPE */
/*****************************************************************************/
SqlExpressionMldbScope::
SqlExpressionMldbScope(const MldbServer * mldb)
: mldb(const_cast<MldbServer *>(mldb))
{
ExcAssert(mldb);
}
BoundFunction
SqlExpressionMldbScope::
doGetFunction(const Utf8String & tableName,
const Utf8String & functionName,
const std::vector<BoundSqlExpression> & args,
SqlBindingScope & argScope)
{
// User functions don't live in table scope
if (tableName.empty()) {
// 1. Try to get a function entity
auto fn = mldb->functions->tryGetExistingEntity(functionName.rawString());
if (fn) {
// We found one. Now wrap it up as a normal function.
if (args.size() > 1)
throw HttpReturnException(400, "User function " + functionName
+ " expected a single row { } argument");
std::shared_ptr<FunctionApplier> applier;
if (args.empty()) {
applier.reset
(fn->bind(argScope,
std::make_shared<RowValueInfo>(std::vector<KnownColumn>()))
.release());
}
else {
if (!args[0].info->isRow()) {
throw HttpReturnException(400, "User function " + functionName
+ " expects a row argument ({ }), "
+ "got " + args[0].expr->print() );
}
applier.reset(fn->bind(argScope, ExpressionValueInfo::toRow(args[0].info))
.release());
}
auto exec = [=] (const std::vector<ExpressionValue> & args,
const SqlRowScope & scope)
-> ExpressionValue
{
if (args.empty()) {
return applier->apply(ExpressionValue());
}
else {
return applier->apply(args[0]);
}
};
return BoundFunction(exec, applier->info.output);
}
}
return SqlBindingScope::doGetFunction(tableName, functionName, args,
argScope);
}
std::shared_ptr<Dataset>
SqlExpressionMldbScope::
doGetDataset(const Utf8String & datasetName)
{
return mldb->datasets->getExistingEntity(datasetName.rawString());
}
std::shared_ptr<Dataset>
SqlExpressionMldbScope::
doGetDatasetFromConfig(const Any & datasetConfig)
{
return obtainDataset(mldb, datasetConfig.convert<PolyConfig>());
}
// defined in table_expression_operations.cc
BoundTableExpression
bindDataset(std::shared_ptr<Dataset> dataset, Utf8String asName);
TableOperations
SqlExpressionMldbScope::
doGetTable(const Utf8String & tableName)
{
return bindDataset(doGetDataset(tableName), Utf8String()).table;
}
MldbServer *
SqlExpressionMldbScope::
getMldbServer() const
{
return mldb;
}
ColumnGetter
SqlExpressionMldbScope::
doGetColumn(const Utf8String & tableName,
const ColumnName & columnName)
{
throw HttpReturnException(400, "Cannot read column \"" + columnName.toUtf8String() + "\" with no dataset.");
}
/*****************************************************************************/
/* ROW EXPRESSION DATASET CONTEXT */
/*****************************************************************************/
SqlExpressionDatasetScope::
SqlExpressionDatasetScope(std::shared_ptr<Dataset> dataset, const Utf8String& alias)
: SqlExpressionMldbScope(dataset->server), dataset(*dataset), alias(alias)
{
dataset->getChildAliases(childaliases);
}
SqlExpressionDatasetScope::
SqlExpressionDatasetScope(const Dataset & dataset, const Utf8String& alias)
: SqlExpressionMldbScope(dataset.server), dataset(dataset), alias(alias)
{
dataset.getChildAliases(childaliases);
}
SqlExpressionDatasetScope::
SqlExpressionDatasetScope(const BoundTableExpression& boundDataset)
: SqlExpressionMldbScope(boundDataset.dataset->server),
dataset(*boundDataset.dataset),
alias(boundDataset.asName)
{
boundDataset.dataset->getChildAliases(childaliases);
}
ColumnGetter
SqlExpressionDatasetScope::
doGetColumn(const Utf8String & tableName,
const ColumnName & columnName)
{
ColumnName simplified;
if (tableName.empty() && columnName.size() > 1) {
if (!alias.empty() && columnName.startsWith(alias)) {
simplified = columnName.removePrefix();
}
}
if (simplified.empty())
simplified = columnName;
//cerr << "doGetColumn: " << tableName << " " << columnName << endl;
//cerr << columnName.size() << endl;
//cerr << "alias " << alias << endl;
//for (auto & c: childaliases)
// cerr << " child " << c << endl;
//cerr << "simplified = " << simplified << endl;
return {[=] (const SqlRowScope & context,
ExpressionValue & storage,
const VariableFilter & filter) -> const ExpressionValue &
{
auto & row = context.as<RowScope>();
const ExpressionValue * fromOutput
= searchRow(row.row.columns, simplified, filter, storage);
if (fromOutput)
return *fromOutput;
return storage = std::move(ExpressionValue::null(Date::negativeInfinity()));
},
std::make_shared<AtomValueInfo>()};
}
BoundFunction
SqlExpressionDatasetScope::
doGetFunction(const Utf8String & tableName,
const Utf8String & functionName,
const std::vector<BoundSqlExpression> & args,
SqlBindingScope & argScope)
{
// First, let the dataset either override or implement the function
// itself.
auto fnoverride = dataset.overrideFunction(tableName, functionName, argScope);
if (fnoverride)
return fnoverride;
if (functionName == "rowName") {
return {[=] (const std::vector<ExpressionValue> & args,
const SqlRowScope & context)
{
auto & row = context.as<RowScope>();
return ExpressionValue(row.row.rowName.toUtf8String(),
Date::negativeInfinity());
},
std::make_shared<Utf8StringValueInfo>()
};
}
if (functionName == "rowPath") {
return {[=] (const std::vector<ExpressionValue> & args,
const SqlRowScope & context)
{
auto & row = context.as<RowScope>();
return ExpressionValue(CellValue(row.row.rowName),
Date::negativeInfinity());
},
std::make_shared<PathValueInfo>()
};
}
if (functionName == "rowHash") {
return {[=] (const std::vector<ExpressionValue> & args,
const SqlRowScope & context)
{
auto & row = context.as<RowScope>();
return ExpressionValue(row.row.rowHash,
Date::negativeInfinity());
},
std::make_shared<Uint64ValueInfo>()
};
}
// Look for a derived function. We do it here so that it's only done
// if the function can't be found higher up.
auto fnderived
= getDatasetDerivedFunction(tableName, functionName, args, argScope,
*this, "row");
if (fnderived)
return fnderived;
/* columnCount function: return number of columns with explicit values set
in the current row.
*/
if (functionName == "columnCount") {
return {[=] (const std::vector<ExpressionValue> & args,
const SqlRowScope & context)
{
auto & row = context.as<RowScope>();
ML::Lightweight_Hash_Set<ColumnHash> columns;
Date ts = Date::negativeInfinity();
for (auto & c: row.row.columns) {
columns.insert(std::get<0>(c));
ts.setMax(std::get<2>(c));
}
return ExpressionValue(columns.size(), ts);
},
std::make_shared<Uint64ValueInfo>()};
}
return SqlExpressionMldbScope
::doGetFunction(tableName, functionName,
args, argScope);
}
ColumnGetter
SqlExpressionDatasetScope::
doGetBoundParameter(const Utf8String & paramName)
{
return {[=] (const SqlRowScope & context,
ExpressionValue & storage,
const VariableFilter & filter) -> const ExpressionValue &
{
ExcAssert(canIgnoreIfExactlyOneValue(filter));
auto & row = context.as<RowScope>();
if (!row.params || !*row.params)
throw HttpReturnException(400, "Bound parameters requested but none passed");
return storage = std::move((*row.params)(paramName));
},
std::make_shared<AnyValueInfo>()};
}
GetAllColumnsOutput
SqlExpressionDatasetScope::
doGetAllColumns(const Utf8String & tableName,
std::function<ColumnName (const ColumnName &)> keep)
{
if (!tableName.empty()
&& std::find(childaliases.begin(), childaliases.end(), tableName)
== childaliases.end()
&& tableName != alias)
throw HttpReturnException(400, "Unknown dataset " + tableName);
auto columns = dataset.getMatrixView()->getColumnNames();
auto filterColumnName = [&] (const ColumnName & inputColumnName)
-> ColumnName
{
if (!tableName.empty() && !childaliases.empty()) {
// We're in a join. The columns will all be prefixed with their
// child table name, but we don't want to use that.
// eg, in x inner join y, we will have variables like
// x.a and y.b, but when we select them we want them to be
// like a and b.
if (!inputColumnName.startsWith(tableName)) {
return ColumnName();
}
// Otherwise, check if we need it
ColumnName result = keep(inputColumnName);
return std::move(result);
}
return keep(inputColumnName);
};
std::unordered_map<ColumnHash, ColumnName> index;
std::vector<KnownColumn> columnsWithInfo;
bool allWereKept = true;
bool noneWereRenamed = true;
vector<ColumnName> columnsNeedingInfo;
for (auto & columnName: columns) {
ColumnName outputName(filterColumnName(columnName));
if (outputName == ColumnName()) {
allWereKept = false;
continue;
}
if (outputName != columnName)
noneWereRenamed = false;
columnsNeedingInfo.push_back(columnName);
index[columnName] = outputName;
// Ask the dataset to describe this column later, null ptr for now
columnsWithInfo.emplace_back(outputName, nullptr,
COLUMN_IS_DENSE);
// Change the name to the output name
//columnsWithInfo.back().columnName = outputName;
}
auto allInfo = dataset.getKnownColumnInfos(columnsNeedingInfo);
// Now put in the value info
for (unsigned i = 0; i < allInfo.size(); ++i) {
ColumnName outputName = columnsWithInfo[i].columnName;
columnsWithInfo[i] = allInfo[i];
columnsWithInfo[i].columnName = std::move(outputName);
}
std::function<ExpressionValue (const SqlRowScope &, const VariableFilter &)> exec;
if (allWereKept && noneWereRenamed) {
// We can pass right through; we have a select *
exec = [=] (const SqlRowScope & context, const VariableFilter & filter) -> ExpressionValue
{
auto & row = context.as<RowScope>();
// TODO: if one day we are able to prove that this is
// the only expression that touches the row, we could
// move it into place
ExpressionValue val(row.row.columns);
return val.getFilteredDestructive(filter);
};
}
else {
// Some are excluded or renamed; we need to go one by one
exec = [=] (const SqlRowScope & context, const VariableFilter & filter)
{
auto & row = context.as<RowScope>();
RowValue result;
for (auto & c: row.row.columns) {
auto it = index.find(std::get<0>(c));
if (it == index.end()) {
continue;
}
result.emplace_back(it->second, std::get<1>(c), std::get<2>(c));
}
ExpressionValue val(std::move(result));
return val.getFilteredDestructive(filter);
};
}
GetAllColumnsOutput result;
result.exec = exec;
result.info = std::make_shared<RowValueInfo>(std::move(columnsWithInfo),
SCHEMA_CLOSED);
return result;
}
GenerateRowsWhereFunction
SqlExpressionDatasetScope::
doCreateRowsWhereGenerator(const SqlExpression & where,
ssize_t offset,
ssize_t limit)
{
auto res = dataset.generateRowsWhere(*this, alias, where, offset, limit);
if (!res)
throw HttpReturnException(500, "Dataset returned null generator",
"datasetType", ML::type_name(dataset));
return res;
}
ColumnFunction
SqlExpressionDatasetScope::
doGetColumnFunction(const Utf8String & functionName)
{
if (functionName == "columnName") {
return {[=] (const ColumnName & columnName,
const std::vector<ExpressionValue> & args)
{
return ExpressionValue(columnName.toUtf8String(),
Date::negativeInfinity());
}};
}
if (functionName == "columnHash") {
return {[=] (const ColumnName & columnName,
const std::vector<ExpressionValue> & args)
{
return ExpressionValue(columnName.hash(),
Date::negativeInfinity());
}};
}
if (functionName == "rowCount") {
return {[=] (const ColumnName & columnName,
const std::vector<ExpressionValue> & args)
{
return ExpressionValue
(dataset.getColumnIndex()->getColumnRowCount(columnName),
Date::notADate());
}};
}
return nullptr;
}
ColumnName
SqlExpressionDatasetScope::
doResolveTableName(const ColumnName & fullColumnName, Utf8String &tableName) const
{
if (!childaliases.empty()) {
for (auto & a: childaliases) {
if (fullColumnName.startsWith(a)) {
tableName = a;
return fullColumnName.removePrefix();
}
}
}
else {
if (!alias.empty() && fullColumnName.startsWith(alias)) {
tableName = alias;
return fullColumnName.removePrefix();
}
}
tableName = Utf8String();
return fullColumnName;
}
/*****************************************************************************/
/* ROW EXPRESSION ORDER BY CONTEXT */
/*****************************************************************************/
ColumnGetter
SqlExpressionOrderByScope::
doGetColumn(const Utf8String & tableName, const ColumnName & columnName)
{
/** An order by clause can read through both what was selected and what
was in the underlying row. So we first look in what was selected,
and then fall back to the underlying row.
*/
auto innerGetVariable
= ReadThroughBindingScope::doGetColumn(tableName, columnName);
return {[=] (const SqlRowScope & context,
ExpressionValue & storage,
const VariableFilter & filter) -> const ExpressionValue &
{
auto & row = context.as<RowScope>();
const ExpressionValue * fromOutput
= searchRow(row.output.columns, columnName.front(),
filter, storage);
if (fromOutput) {
if (columnName.size() == 1) {
return *fromOutput;
}
else {
ColumnName tail = columnName.removePrefix();
return storage = fromOutput->getNestedColumn(tail, filter);
}
}
return innerGetVariable(context, storage);
},
std::make_shared<AtomValueInfo>()};
}
} // namespace MLDB
} // namespace Datacratic
<|endoftext|> |
<commit_before>/**
* @file
* @copyright defined in eos/LICENSE.txt
*/
#pragma once
#include <eosio/chain/action.hpp>
#include <numeric>
namespace eosio { namespace chain {
/**
* The transaction header contains the fixed-sized data
* associated with each transaction. It is separated from
* the transaction body to facilitate partial parsing of
* transactions without requiring dynamic memory allocation.
*
* All transactions have an expiration time after which they
* may no longer be included in the blockchain. Once a block
* with a block_header::timestamp greater than expiration is
* deemed irreversible, then a user can safely trust the transaction
* will never be included.
*
* Each region is an independent blockchain, it is included as routing
* information for inter-blockchain communication. A contract in this
* region might generate or authorize a transaction intended for a foreign
* region.
*/
struct transaction_header {
time_point_sec expiration; ///< the time at which a transaction expires
uint16_t ref_block_num = 0U; ///< specifies a block num in the last 2^16 blocks.
uint32_t ref_block_prefix = 0UL; ///< specifies the lower 32 bits of the blockid at get_ref_blocknum
fc::unsigned_int max_net_usage_words = 0UL; /// upper limit on total network bandwidth (in 8 byte words) billed for this transaction
uint8_t max_cpu_usage_ms = 0; /// upper limit on the total CPU time billed for this transaction
fc::unsigned_int delay_sec = 0UL; /// number of seconds to delay this transaction for during which it may be canceled.
/**
* @return the absolute block number given the relative ref_block_num
*/
block_num_type get_ref_blocknum( block_num_type head_blocknum )const {
return ((head_blocknum/0xffff)*0xffff) + head_blocknum%0xffff;
}
void set_reference_block( const block_id_type& reference_block );
bool verify_reference_block( const block_id_type& reference_block )const;
void validate()const;
};
/**
* A transaction consits of a set of messages which must all be applied or
* all are rejected. These messages have access to data within the given
* read and write scopes.
*/
struct transaction : public transaction_header {
vector<action> context_free_actions;
vector<action> actions;
extensions_type transaction_extensions;
transaction_id_type id()const;
digest_type sig_digest( const chain_id_type& chain_id, const vector<bytes>& cfd = vector<bytes>() )const;
flat_set<public_key_type> get_signature_keys( const vector<signature_type>& signatures,
const chain_id_type& chain_id,
const vector<bytes>& cfd = vector<bytes>(),
bool allow_duplicate_keys = false,
bool use_cache = true )const;
uint32_t total_actions()const { return context_free_actions.size() + actions.size(); }
account_name first_authorizor()const {
for( const auto& a : actions ) {
for( const auto& u : a.authorization )
return u.actor;
}
return account_name();
}
};
struct signed_transaction : public transaction
{
signed_transaction() = default;
// signed_transaction( const signed_transaction& ) = default;
// signed_transaction( signed_transaction&& ) = default;
signed_transaction( transaction&& trx, const vector<signature_type>& signatures, const vector<bytes>& context_free_data)
: transaction(std::move(trx))
, signatures(signatures)
, context_free_data(context_free_data)
{
}
vector<signature_type> signatures;
vector<bytes> context_free_data; ///< for each context-free action, there is an entry here
const signature_type& sign(const private_key_type& key, const chain_id_type& chain_id);
signature_type sign(const private_key_type& key, const chain_id_type& chain_id)const;
flat_set<public_key_type> get_signature_keys( const chain_id_type& chain_id, bool allow_duplicate_keys = false, bool use_cache = true )const;
};
struct packed_transaction {
enum compression_type {
none = 0,
zlib = 1,
};
packed_transaction() = default;
explicit packed_transaction(const transaction& t, compression_type _compression = none)
{
set_transaction(t, _compression);
}
explicit packed_transaction(const signed_transaction& t, compression_type _compression = none)
:signatures(t.signatures)
{
set_transaction(t, t.context_free_data, _compression);
}
explicit packed_transaction(signed_transaction&& t, compression_type _compression = none)
:signatures(std::move(t.signatures))
{
set_transaction(t, std::move(t.context_free_data), _compression);
}
uint32_t get_unprunable_size()const;
uint32_t get_prunable_size()const;
digest_type packed_digest()const;
vector<signature_type> signatures;
fc::enum_type<uint8_t,compression_type> compression;
bytes packed_context_free_data;
bytes packed_trx;
time_point_sec expiration()const;
transaction_id_type id()const;
transaction_id_type get_uncached_id()const; // thread safe
bytes get_raw_transaction()const; // thread safe
vector<bytes> get_context_free_data()const;
transaction get_transaction()const;
signed_transaction get_signed_transaction()const;
void set_transaction(const transaction& t, compression_type _compression = none);
void set_transaction(const transaction& t, const vector<bytes>& cfd, compression_type _compression = none);
private:
mutable optional<transaction> unpacked_trx; // <-- intermediate buffer used to retrieve values
void local_unpack()const;
};
using packed_transaction_ptr = std::shared_ptr<packed_transaction>;
/**
* When a transaction is generated it can be scheduled to occur
* in the future. It may also fail to execute for some reason in
* which case the sender needs to be notified. When the sender
* sends a transaction they will assign it an ID which will be
* passed back to the sender if the transaction fails for some
* reason.
*/
struct deferred_transaction : public signed_transaction
{
uint128_t sender_id; /// ID assigned by sender of generated, accessible via WASM api when executing normal or error
account_name sender; /// receives error handler callback
account_name payer;
time_point_sec execute_after; /// delayed execution
deferred_transaction() = default;
deferred_transaction(uint128_t sender_id, account_name sender, account_name payer,time_point_sec execute_after,
const signed_transaction& txn)
: signed_transaction(txn),
sender_id(sender_id),
sender(sender),
payer(payer),
execute_after(execute_after)
{}
};
struct deferred_reference {
deferred_reference(){}
deferred_reference( const account_name& sender, const uint128_t& sender_id)
:sender(sender),sender_id(sender_id)
{}
account_name sender;
uint128_t sender_id;
};
uint128_t transaction_id_to_sender_id( const transaction_id_type& tid );
} } /// namespace eosio::chain
FC_REFLECT( eosio::chain::transaction_header, (expiration)(ref_block_num)(ref_block_prefix)
(max_net_usage_words)(max_cpu_usage_ms)(delay_sec) )
FC_REFLECT_DERIVED( eosio::chain::transaction, (eosio::chain::transaction_header), (context_free_actions)(actions)(transaction_extensions) )
FC_REFLECT_DERIVED( eosio::chain::signed_transaction, (eosio::chain::transaction), (signatures)(context_free_data) )
FC_REFLECT_ENUM( eosio::chain::packed_transaction::compression_type, (none)(zlib))
FC_REFLECT( eosio::chain::packed_transaction, (signatures)(compression)(packed_context_free_data)(packed_trx) )
FC_REFLECT_DERIVED( eosio::chain::deferred_transaction, (eosio::chain::signed_transaction), (sender_id)(sender)(payer)(execute_after) )
FC_REFLECT( eosio::chain::deferred_reference, (sender)(sender_id) )
<commit_msg>Remove copy assignment operator. Remove used std::move.<commit_after>/**
* @file
* @copyright defined in eos/LICENSE.txt
*/
#pragma once
#include <eosio/chain/action.hpp>
#include <numeric>
namespace eosio { namespace chain {
/**
* The transaction header contains the fixed-sized data
* associated with each transaction. It is separated from
* the transaction body to facilitate partial parsing of
* transactions without requiring dynamic memory allocation.
*
* All transactions have an expiration time after which they
* may no longer be included in the blockchain. Once a block
* with a block_header::timestamp greater than expiration is
* deemed irreversible, then a user can safely trust the transaction
* will never be included.
*
* Each region is an independent blockchain, it is included as routing
* information for inter-blockchain communication. A contract in this
* region might generate or authorize a transaction intended for a foreign
* region.
*/
struct transaction_header {
time_point_sec expiration; ///< the time at which a transaction expires
uint16_t ref_block_num = 0U; ///< specifies a block num in the last 2^16 blocks.
uint32_t ref_block_prefix = 0UL; ///< specifies the lower 32 bits of the blockid at get_ref_blocknum
fc::unsigned_int max_net_usage_words = 0UL; /// upper limit on total network bandwidth (in 8 byte words) billed for this transaction
uint8_t max_cpu_usage_ms = 0; /// upper limit on the total CPU time billed for this transaction
fc::unsigned_int delay_sec = 0UL; /// number of seconds to delay this transaction for during which it may be canceled.
/**
* @return the absolute block number given the relative ref_block_num
*/
block_num_type get_ref_blocknum( block_num_type head_blocknum )const {
return ((head_blocknum/0xffff)*0xffff) + head_blocknum%0xffff;
}
void set_reference_block( const block_id_type& reference_block );
bool verify_reference_block( const block_id_type& reference_block )const;
void validate()const;
};
/**
* A transaction consits of a set of messages which must all be applied or
* all are rejected. These messages have access to data within the given
* read and write scopes.
*/
struct transaction : public transaction_header {
vector<action> context_free_actions;
vector<action> actions;
extensions_type transaction_extensions;
transaction_id_type id()const;
digest_type sig_digest( const chain_id_type& chain_id, const vector<bytes>& cfd = vector<bytes>() )const;
flat_set<public_key_type> get_signature_keys( const vector<signature_type>& signatures,
const chain_id_type& chain_id,
const vector<bytes>& cfd = vector<bytes>(),
bool allow_duplicate_keys = false,
bool use_cache = true )const;
uint32_t total_actions()const { return context_free_actions.size() + actions.size(); }
account_name first_authorizor()const {
for( const auto& a : actions ) {
for( const auto& u : a.authorization )
return u.actor;
}
return account_name();
}
};
struct signed_transaction : public transaction
{
signed_transaction() = default;
// signed_transaction( const signed_transaction& ) = default;
// signed_transaction( signed_transaction&& ) = default;
signed_transaction( transaction&& trx, const vector<signature_type>& signatures, const vector<bytes>& context_free_data)
: transaction(std::move(trx))
, signatures(signatures)
, context_free_data(context_free_data)
{
}
vector<signature_type> signatures;
vector<bytes> context_free_data; ///< for each context-free action, there is an entry here
const signature_type& sign(const private_key_type& key, const chain_id_type& chain_id);
signature_type sign(const private_key_type& key, const chain_id_type& chain_id)const;
flat_set<public_key_type> get_signature_keys( const chain_id_type& chain_id, bool allow_duplicate_keys = false, bool use_cache = true )const;
};
struct packed_transaction {
enum compression_type {
none = 0,
zlib = 1,
};
packed_transaction() = default;
packed_transaction(packed_transaction&&) = default;
explicit packed_transaction(const packed_transaction&) = default;
packed_transaction& operator=(const packed_transaction&) = delete;
packed_transaction& operator=(packed_transaction&&) = default;
explicit packed_transaction(const transaction& t, compression_type _compression = none)
{
set_transaction(t, _compression);
}
explicit packed_transaction(const signed_transaction& t, compression_type _compression = none)
:signatures(t.signatures)
{
set_transaction(t, t.context_free_data, _compression);
}
explicit packed_transaction(signed_transaction&& t, compression_type _compression = none)
:signatures(std::move(t.signatures))
{
set_transaction(t, t.context_free_data, _compression);
}
uint32_t get_unprunable_size()const;
uint32_t get_prunable_size()const;
digest_type packed_digest()const;
vector<signature_type> signatures;
fc::enum_type<uint8_t,compression_type> compression;
bytes packed_context_free_data;
bytes packed_trx;
time_point_sec expiration()const;
transaction_id_type id()const;
transaction_id_type get_uncached_id()const; // thread safe
bytes get_raw_transaction()const; // thread safe
vector<bytes> get_context_free_data()const;
transaction get_transaction()const;
signed_transaction get_signed_transaction()const;
void set_transaction(const transaction& t, compression_type _compression = none);
void set_transaction(const transaction& t, const vector<bytes>& cfd, compression_type _compression = none);
private:
mutable optional<transaction> unpacked_trx; // <-- intermediate buffer used to retrieve values
void local_unpack()const;
};
using packed_transaction_ptr = std::shared_ptr<packed_transaction>;
/**
* When a transaction is generated it can be scheduled to occur
* in the future. It may also fail to execute for some reason in
* which case the sender needs to be notified. When the sender
* sends a transaction they will assign it an ID which will be
* passed back to the sender if the transaction fails for some
* reason.
*/
struct deferred_transaction : public signed_transaction
{
uint128_t sender_id; /// ID assigned by sender of generated, accessible via WASM api when executing normal or error
account_name sender; /// receives error handler callback
account_name payer;
time_point_sec execute_after; /// delayed execution
deferred_transaction() = default;
deferred_transaction(uint128_t sender_id, account_name sender, account_name payer,time_point_sec execute_after,
const signed_transaction& txn)
: signed_transaction(txn),
sender_id(sender_id),
sender(sender),
payer(payer),
execute_after(execute_after)
{}
};
struct deferred_reference {
deferred_reference(){}
deferred_reference( const account_name& sender, const uint128_t& sender_id)
:sender(sender),sender_id(sender_id)
{}
account_name sender;
uint128_t sender_id;
};
uint128_t transaction_id_to_sender_id( const transaction_id_type& tid );
} } /// namespace eosio::chain
FC_REFLECT( eosio::chain::transaction_header, (expiration)(ref_block_num)(ref_block_prefix)
(max_net_usage_words)(max_cpu_usage_ms)(delay_sec) )
FC_REFLECT_DERIVED( eosio::chain::transaction, (eosio::chain::transaction_header), (context_free_actions)(actions)(transaction_extensions) )
FC_REFLECT_DERIVED( eosio::chain::signed_transaction, (eosio::chain::transaction), (signatures)(context_free_data) )
FC_REFLECT_ENUM( eosio::chain::packed_transaction::compression_type, (none)(zlib))
FC_REFLECT( eosio::chain::packed_transaction, (signatures)(compression)(packed_context_free_data)(packed_trx) )
FC_REFLECT_DERIVED( eosio::chain::deferred_transaction, (eosio::chain::signed_transaction), (sender_id)(sender)(payer)(execute_after) )
FC_REFLECT( eosio::chain::deferred_reference, (sender)(sender_id) )
<|endoftext|> |
<commit_before>/*
* Quick wrapper for the OK light.
*
* Authors:
* Scott Linder
*/
#include "ok.hh"
auto OK::on() -> void {
regs_.write(kSelect1, 1 << 18);
regs_.write(kClear0, 1 << 16);
}
auto OK::off() -> void {
regs_.write(kSelect1, 1 << 18);
regs_.write(kSet0, 1 << 16);
}
<commit_msg>Moved OK to new MMIO write methods.<commit_after>/*
* Quick wrapper for the OK light.
*
* Authors:
* Scott Linder
*/
#include "ok.hh"
auto OK::on() -> void {
regs_.write(kSelect1, 18, true);
regs_.write(kClear0, 16, true);
}
auto OK::off() -> void {
regs_.write(kSelect1, 18, true);
regs_.write(kSet0, 16, true);
}
<|endoftext|> |
<commit_before>#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <SDL_mixer.h>
#include "JAM/Texture.h"
#include "JAM/StateManager.h"
#include "Game.h"
int main(int argc, char *argv[])
{
#ifdef _WIN32
/*Initialise SDL needed for desktop*/
if (SDL_Init(SDL_INIT_VIDEO) < 0) //Check SDL initialisation
{
//Failed initialisation
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to initialise SDL");
return -1;
}
#endif
/*Initialise SDL_ttf*/
if (TTF_Init() < 0) /*Check SDL_ttf initialisation*/
{
/*Failed initialisation*/
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to initialise SDL_ttf");
return -1;
}
/*Initialise SDL_mixer*/
Mix_Init(MIX_INIT_OGG);
if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0)
{
/*Failed initialisation*/
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to initialise SDL_Mixer");
return -1;
}
/*Initialize PNG loading*/
int imgFlags = IMG_INIT_PNG;
if (!(IMG_Init(imgFlags) & imgFlags))
{
/*Failed initialisation*/
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to initialise SDL_image");
return -1;
}
/*Time Check*/
unsigned int lastTime = SDL_GetTicks();
SDL_Window* window;
SDL_Renderer* renderer;
int winWidth;
int winHeight;
#ifdef __ANDROID__
if(SDL_CreateWindowAndRenderer(0, 0, 0, &window, &renderer) < 0)
exit(2);
SDL_GetWindowSize(window, &winWidth, &winHeight);
#elif _WIN32
/*Create Window*/
int winPosX = 100;
int winPosY = 100;
winWidth = 640;
winHeight = 480;
window = SDL_CreateWindow("MGPDemo", /*The first parameter is the window title*/
winPosX, winPosY,
winWidth, winHeight,
SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
/*Create Renderer from the window*/
renderer = SDL_CreateRenderer(window, -1, 0);
#endif
/*setup state manager*/
JAM_StateManager * stateManager = new JAM_StateManager();
/*set the initial state*/
stateManager->addState(new Game(stateManager, renderer, winWidth, winHeight));
/*Start Game Loop*/
bool go = true;
while (go)
{
/*Time Check*/
unsigned int current = SDL_GetTicks();
float deltaTime = (float)(current - lastTime) / 1000.0f;
lastTime = current;
/*handle the current state inputs*/
go = stateManager->input();
/*update the current state*/
stateManager->update(deltaTime);
/*set draw colour to white*/
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
/*Clear the entire screen to the set colour*/
SDL_RenderClear(renderer);
/*draw the states*/
stateManager->draw();
/*display renderer*/
SDL_RenderPresent(renderer);
/*Time Limiter*/
if (deltaTime < (1.0f / 50.0f))
{
SDL_Delay((unsigned int)(((1.0f / 50.0f) - deltaTime)*1000.0f));
}
}
/*destroy data*/
delete stateManager;
SDL_DestroyWindow(window);
SDL_Quit();
exit(0);
return 0;
}<commit_msg>Updated the game title.<commit_after>#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <SDL_mixer.h>
#include "JAM/Texture.h"
#include "JAM/StateManager.h"
#include "Game.h"
int main(int argc, char *argv[])
{
#ifdef _WIN32
/*Initialise SDL needed for desktop*/
if (SDL_Init(SDL_INIT_VIDEO) < 0) //Check SDL initialisation
{
//Failed initialisation
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to initialise SDL");
return -1;
}
#endif
/*Initialise SDL_ttf*/
if (TTF_Init() < 0) /*Check SDL_ttf initialisation*/
{
/*Failed initialisation*/
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to initialise SDL_ttf");
return -1;
}
/*Initialise SDL_mixer*/
Mix_Init(MIX_INIT_OGG);
if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 2048) < 0)
{
/*Failed initialisation*/
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to initialise SDL_Mixer");
return -1;
}
/*Initialize PNG loading*/
int imgFlags = IMG_INIT_PNG;
if (!(IMG_Init(imgFlags) & imgFlags))
{
/*Failed initialisation*/
SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Failed to initialise SDL_image");
return -1;
}
/*Time Check*/
unsigned int lastTime = SDL_GetTicks();
SDL_Window* window;
SDL_Renderer* renderer;
int winWidth;
int winHeight;
#ifdef __ANDROID__
if(SDL_CreateWindowAndRenderer(0, 0, 0, &window, &renderer) < 0)
exit(2);
SDL_GetWindowSize(window, &winWidth, &winHeight);
#elif _WIN32
/*Create Window*/
int winPosX = 100;
int winPosY = 100;
winWidth = 640;
winHeight = 480;
window = SDL_CreateWindow("MGPDemoAStar", /*The first parameter is the window title*/
winPosX, winPosY,
winWidth, winHeight,
SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
/*Create Renderer from the window*/
renderer = SDL_CreateRenderer(window, -1, 0);
#endif
/*setup state manager*/
JAM_StateManager * stateManager = new JAM_StateManager();
/*set the initial state*/
stateManager->addState(new Game(stateManager, renderer, winWidth, winHeight));
/*Start Game Loop*/
bool go = true;
while (go)
{
/*Time Check*/
unsigned int current = SDL_GetTicks();
float deltaTime = (float)(current - lastTime) / 1000.0f;
lastTime = current;
/*handle the current state inputs*/
go = stateManager->input();
/*update the current state*/
stateManager->update(deltaTime);
/*set draw colour to white*/
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
/*Clear the entire screen to the set colour*/
SDL_RenderClear(renderer);
/*draw the states*/
stateManager->draw();
/*display renderer*/
SDL_RenderPresent(renderer);
/*Time Limiter*/
if (deltaTime < (1.0f / 50.0f))
{
SDL_Delay((unsigned int)(((1.0f / 50.0f) - deltaTime)*1000.0f));
}
}
/*destroy data*/
delete stateManager;
SDL_DestroyWindow(window);
SDL_Quit();
exit(0);
return 0;
}<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.14 2003/05/15 18:29:49 knoaman
* Partial implementation of the configurable memory manager.
*
* Revision 1.13 2003/03/09 16:42:05 peiyongz
* PanicHandler
*
* Revision 1.12 2003/02/20 20:20:11 peiyongz
* Allow set user specified error message file location in PlatformUtils::Initialize().
*
* Revision 1.11 2002/12/12 16:46:18 peiyongz
* MsgCatalog file name changed.
*
* Revision 1.10 2002/12/06 16:49:47 peiyongz
* $XERCESCROOT/msg created as home directory for message files.
*
* Revision 1.9 2002/12/04 18:03:13 peiyongz
* use $XERCESCROOT to search for msg catalog file if XERCESC_NLS_HOME
* undefined
*
* Revision 1.8 2002/12/02 21:58:43 peiyongz
* nls support
*
* Revision 1.7 2002/11/12 17:27:12 tng
* DOM Message: add new domain for DOM Messages.
*
* Revision 1.6 2002/11/05 16:54:46 peiyongz
* Using XERCESC_NLS_HOME
*
* Revision 1.5 2002/11/04 15:10:41 tng
* C++ Namespace Support.
*
* Revision 1.4 2002/09/24 19:58:33 tng
* Performance: use XMLString::equals instead of XMLString::compareString
*
* Revision 1.3 2002/09/23 21:05:40 peiyongz
* remove debugging code
*
* Revision 1.2 2002/09/23 21:03:06 peiyongz
* Build MsgCatalog on Solaris
*
* Revision 1.1.1.1 2002/02/01 22:22:21 peiyongz
* sane_include
*
* Revision 1.7 2001/10/09 12:19:44 tng
* Leak fix: can call transcode directly instead of using copyString.
*
* Revision 1.6 2000/07/25 22:28:40 aruna1
* Char definitions in XMLUni moved to XMLUniDefs
*
* Revision 1.5 2000/03/02 19:55:16 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.4 2000/02/06 07:48:22 rahulj
* Year 2K copyright swat.
*
* Revision 1.3 2000/01/05 22:00:22 aruna1
* Modified message 'set' attribute reading sequence. Removed dependencies on hard coded constants
*
* Revision 1.2 1999/12/23 01:43:37 aruna1
* MsgCatalog support added for solaris
*
* Revision 1.1.1.1 1999/11/09 01:07:16 twl
* Initial checkin
*
* Revision 1.2 1999/11/08 20:45:27 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLMsgLoader.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/XMLUni.hpp>
#include "MsgCatalogLoader.hpp"
#include "XMLMsgCat_Ids.hpp"
#include <locale.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Public Constructors and Destructor
// ---------------------------------------------------------------------------
MsgCatalogLoader::MsgCatalogLoader(const XMLCh* const msgDomain)
:fCatalogHandle(0)
,fMsgSet(0)
{
if (!XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain)
&& !XMLString::equals(msgDomain, XMLUni::fgExceptDomain)
&& !XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain)
&& !XMLString::equals(msgDomain, XMLUni::fgValidityDomain))
{
XMLPlatformUtils::panic(PanicHandler::Panic_UnknownMsgDomain);
}
// Prepare the path info
char locationBuf[1024];
memset(locationBuf, 0, sizeof locationBuf);
const char *nlsHome = XMLMsgLoader::getNLSHome();
if (nlsHome)
{
strcpy(locationBuf, nlsHome);
strcat(locationBuf, "/");
}
else
{
nlsHome = getenv("XERCESC_NLS_HOME");
if (nlsHome)
{
strcpy(locationBuf, nlsHome);
strcat(locationBuf, "/");
}
else
{
nlsHome = getenv("XERCESCROOT");
if (nlsHome)
{
strcpy(locationBuf, nlsHome);
strcat(locationBuf, "/msg/");
}
}
}
// Prepare user-specified locale specific cat file
char catuser[1024];
memset(catuser, 0, sizeof catuser);
strcpy(catuser, locationBuf);
strcat(catuser, "XercesMessages_");
strcat(catuser, XMLMsgLoader::getLocale());
strcat(catuser, ".cat");
char catdefault[1024];
memset(catdefault, 0, sizeof catdefault);
strcpy(catdefault, locationBuf);
strcat(catdefault, "XercesMessages_en_US.cat");
/**
* To open user-specified locale specific cat file
* and default cat file if necessary
*/
if ( ((int)(fCatalogHandle=catopen(catuser, 0)) == -1) &&
((int)(fCatalogHandle=catopen(catdefault, 0)) == -1) )
{
// Probably have to call panic here
printf("Could not open catalog:\n %s\n or %s\n", catuser, catdefault);
exit(1);
}
if (XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain))
fMsgSet = CatId_XMLErrs;
else if (XMLString::equals(msgDomain, XMLUni::fgExceptDomain))
fMsgSet = CatId_XMLExcepts;
else if (XMLString::equals(msgDomain, XMLUni::fgValidityDomain))
fMsgSet = CatId_XMLValid;
else if (XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain))
fMsgSet = CatId_XMLDOMMsg;
}
MsgCatalogLoader::~MsgCatalogLoader()
{
catclose(fCatalogHandle);
}
// ---------------------------------------------------------------------------
// Implementation of the virtual message loader API
// ---------------------------------------------------------------------------
bool MsgCatalogLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars)
{
char msgString[100];
sprintf(msgString, "Could not find message ID %d from message set %d\n", msgToLoad, fMsgSet);
char* catMessage = catgets( fCatalogHandle, fMsgSet, (int)msgToLoad, msgString);
// catgets returns a pointer to msgString if it fails to locate the message
// from the message catalog
if (XMLString::equals(catMessage, msgString))
return false;
else
{
XMLString::transcode(catMessage, toFill, maxChars);
return true;
}
}
bool MsgCatalogLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars
, const XMLCh* const repText1
, const XMLCh* const repText2
, const XMLCh* const repText3
, const XMLCh* const repText4)
{
// Call the other version to load up the message
if (!loadMsg(msgToLoad, toFill, maxChars))
return false;
// And do the token replacement
XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4);
return true;
}
bool MsgCatalogLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars
, const char* const repText1
, const char* const repText2
, const char* const repText3
, const char* const repText4)
{
//
// Transcode the provided parameters and call the other version,
// which will do the replacement work.
//
XMLCh* tmp1 = 0;
XMLCh* tmp2 = 0;
XMLCh* tmp3 = 0;
XMLCh* tmp4 = 0;
bool bRet = false;
if (repText1)
tmp1 = XMLString::transcode(repText1, XMLPlatformUtils::fgMemoryManager);
if (repText2)
tmp2 = XMLString::transcode(repText2, XMLPlatformUtils::fgMemoryManager);
if (repText3)
tmp3 = XMLString::transcode(repText3, XMLPlatformUtils::fgMemoryManager);
if (repText4)
tmp4 = XMLString::transcode(repText4, XMLPlatformUtils::fgMemoryManager);
bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4);
if (tmp1)
XMLPlatformUtils::fgMemoryManager->deallocate(tmp1);//delete [] tmp1;
if (tmp2)
XMLPlatformUtils::fgMemoryManager->deallocate(tmp2);//delete [] tmp2;
if (tmp3)
XMLPlatformUtils::fgMemoryManager->deallocate(tmp3);//delete [] tmp3;
if (tmp4)
XMLPlatformUtils::fgMemoryManager->deallocate(tmp4);//delete [] tmp4;
return bRet;
}
XERCES_CPP_NAMESPACE_END
<commit_msg>use PlatformUtils::panic()<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Log$
* Revision 1.15 2003/08/21 16:36:08 peiyongz
* use PlatformUtils::panic()
*
* Revision 1.14 2003/05/15 18:29:49 knoaman
* Partial implementation of the configurable memory manager.
*
* Revision 1.13 2003/03/09 16:42:05 peiyongz
* PanicHandler
*
* Revision 1.12 2003/02/20 20:20:11 peiyongz
* Allow set user specified error message file location in PlatformUtils::Initialize().
*
* Revision 1.11 2002/12/12 16:46:18 peiyongz
* MsgCatalog file name changed.
*
* Revision 1.10 2002/12/06 16:49:47 peiyongz
* $XERCESCROOT/msg created as home directory for message files.
*
* Revision 1.9 2002/12/04 18:03:13 peiyongz
* use $XERCESCROOT to search for msg catalog file if XERCESC_NLS_HOME
* undefined
*
* Revision 1.8 2002/12/02 21:58:43 peiyongz
* nls support
*
* Revision 1.7 2002/11/12 17:27:12 tng
* DOM Message: add new domain for DOM Messages.
*
* Revision 1.6 2002/11/05 16:54:46 peiyongz
* Using XERCESC_NLS_HOME
*
* Revision 1.5 2002/11/04 15:10:41 tng
* C++ Namespace Support.
*
* Revision 1.4 2002/09/24 19:58:33 tng
* Performance: use XMLString::equals instead of XMLString::compareString
*
* Revision 1.3 2002/09/23 21:05:40 peiyongz
* remove debugging code
*
* Revision 1.2 2002/09/23 21:03:06 peiyongz
* Build MsgCatalog on Solaris
*
* Revision 1.1.1.1 2002/02/01 22:22:21 peiyongz
* sane_include
*
* Revision 1.7 2001/10/09 12:19:44 tng
* Leak fix: can call transcode directly instead of using copyString.
*
* Revision 1.6 2000/07/25 22:28:40 aruna1
* Char definitions in XMLUni moved to XMLUniDefs
*
* Revision 1.5 2000/03/02 19:55:16 roddey
* This checkin includes many changes done while waiting for the
* 1.1.0 code to be finished. I can't list them all here, but a list is
* available elsewhere.
*
* Revision 1.4 2000/02/06 07:48:22 rahulj
* Year 2K copyright swat.
*
* Revision 1.3 2000/01/05 22:00:22 aruna1
* Modified message 'set' attribute reading sequence. Removed dependencies on hard coded constants
*
* Revision 1.2 1999/12/23 01:43:37 aruna1
* MsgCatalog support added for solaris
*
* Revision 1.1.1.1 1999/11/09 01:07:16 twl
* Initial checkin
*
* Revision 1.2 1999/11/08 20:45:27 rahul
* Swat for adding in Product name and CVS comment log variable.
*
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/util/XercesDefs.hpp>
#include <xercesc/util/PlatformUtils.hpp>
#include <xercesc/util/XMLMsgLoader.hpp>
#include <xercesc/util/XMLString.hpp>
#include <xercesc/util/XMLUniDefs.hpp>
#include <xercesc/util/XMLUni.hpp>
#include "MsgCatalogLoader.hpp"
#include "XMLMsgCat_Ids.hpp"
#include <locale.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Public Constructors and Destructor
// ---------------------------------------------------------------------------
MsgCatalogLoader::MsgCatalogLoader(const XMLCh* const msgDomain)
:fCatalogHandle(0)
,fMsgSet(0)
{
if (!XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain)
&& !XMLString::equals(msgDomain, XMLUni::fgExceptDomain)
&& !XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain)
&& !XMLString::equals(msgDomain, XMLUni::fgValidityDomain))
{
XMLPlatformUtils::panic(PanicHandler::Panic_UnknownMsgDomain);
}
// Prepare the path info
char locationBuf[1024];
memset(locationBuf, 0, sizeof locationBuf);
const char *nlsHome = XMLMsgLoader::getNLSHome();
if (nlsHome)
{
strcpy(locationBuf, nlsHome);
strcat(locationBuf, "/");
}
else
{
nlsHome = getenv("XERCESC_NLS_HOME");
if (nlsHome)
{
strcpy(locationBuf, nlsHome);
strcat(locationBuf, "/");
}
else
{
nlsHome = getenv("XERCESCROOT");
if (nlsHome)
{
strcpy(locationBuf, nlsHome);
strcat(locationBuf, "/msg/");
}
}
}
// Prepare user-specified locale specific cat file
char catuser[1024];
memset(catuser, 0, sizeof catuser);
strcpy(catuser, locationBuf);
strcat(catuser, "XercesMessages_");
strcat(catuser, XMLMsgLoader::getLocale());
strcat(catuser, ".cat");
char catdefault[1024];
memset(catdefault, 0, sizeof catdefault);
strcpy(catdefault, locationBuf);
strcat(catdefault, "XercesMessages_en_US.cat");
/**
* To open user-specified locale specific cat file
* and default cat file if necessary
*/
if ( ((int)(fCatalogHandle=catopen(catuser, 0)) == -1) &&
((int)(fCatalogHandle=catopen(catdefault, 0)) == -1) )
{
// Probably have to call panic here
printf("Could not open catalog:\n %s\n or %s\n", catuser, catdefault);
XMLPlatformUtils::panic(PanicHandler::Panic_CantLoadMsgDomain);
}
if (XMLString::equals(msgDomain, XMLUni::fgXMLErrDomain))
fMsgSet = CatId_XMLErrs;
else if (XMLString::equals(msgDomain, XMLUni::fgExceptDomain))
fMsgSet = CatId_XMLExcepts;
else if (XMLString::equals(msgDomain, XMLUni::fgValidityDomain))
fMsgSet = CatId_XMLValid;
else if (XMLString::equals(msgDomain, XMLUni::fgXMLDOMMsgDomain))
fMsgSet = CatId_XMLDOMMsg;
}
MsgCatalogLoader::~MsgCatalogLoader()
{
catclose(fCatalogHandle);
}
// ---------------------------------------------------------------------------
// Implementation of the virtual message loader API
// ---------------------------------------------------------------------------
bool MsgCatalogLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars)
{
char msgString[100];
sprintf(msgString, "Could not find message ID %d from message set %d\n", msgToLoad, fMsgSet);
char* catMessage = catgets( fCatalogHandle, fMsgSet, (int)msgToLoad, msgString);
// catgets returns a pointer to msgString if it fails to locate the message
// from the message catalog
if (XMLString::equals(catMessage, msgString))
return false;
else
{
XMLString::transcode(catMessage, toFill, maxChars);
return true;
}
}
bool MsgCatalogLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars
, const XMLCh* const repText1
, const XMLCh* const repText2
, const XMLCh* const repText3
, const XMLCh* const repText4)
{
// Call the other version to load up the message
if (!loadMsg(msgToLoad, toFill, maxChars))
return false;
// And do the token replacement
XMLString::replaceTokens(toFill, maxChars, repText1, repText2, repText3, repText4);
return true;
}
bool MsgCatalogLoader::loadMsg(const XMLMsgLoader::XMLMsgId msgToLoad
, XMLCh* const toFill
, const unsigned int maxChars
, const char* const repText1
, const char* const repText2
, const char* const repText3
, const char* const repText4)
{
//
// Transcode the provided parameters and call the other version,
// which will do the replacement work.
//
XMLCh* tmp1 = 0;
XMLCh* tmp2 = 0;
XMLCh* tmp3 = 0;
XMLCh* tmp4 = 0;
bool bRet = false;
if (repText1)
tmp1 = XMLString::transcode(repText1, XMLPlatformUtils::fgMemoryManager);
if (repText2)
tmp2 = XMLString::transcode(repText2, XMLPlatformUtils::fgMemoryManager);
if (repText3)
tmp3 = XMLString::transcode(repText3, XMLPlatformUtils::fgMemoryManager);
if (repText4)
tmp4 = XMLString::transcode(repText4, XMLPlatformUtils::fgMemoryManager);
bRet = loadMsg(msgToLoad, toFill, maxChars, tmp1, tmp2, tmp3, tmp4);
if (tmp1)
XMLPlatformUtils::fgMemoryManager->deallocate(tmp1);//delete [] tmp1;
if (tmp2)
XMLPlatformUtils::fgMemoryManager->deallocate(tmp2);//delete [] tmp2;
if (tmp3)
XMLPlatformUtils::fgMemoryManager->deallocate(tmp3);//delete [] tmp3;
if (tmp4)
XMLPlatformUtils::fgMemoryManager->deallocate(tmp4);//delete [] tmp4;
return bRet;
}
XERCES_CPP_NAMESPACE_END
<|endoftext|> |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.