hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6644e5f3b6c49b0976c495bab7be771a88ab79eb | 2,224 | cpp | C++ | aws-cpp-sdk-apigatewayv2/source/ApiGatewayV2Errors.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-apigatewayv2/source/ApiGatewayV2Errors.cpp | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-apigatewayv2/source/ApiGatewayV2Errors.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2022-03-23T15:17:18.000Z | 2022-03-23T15:17:18.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/core/client/AWSError.h>
#include <aws/core/utils/HashingUtils.h>
#include <aws/apigatewayv2/ApiGatewayV2Errors.h>
#include <aws/apigatewayv2/model/NotFoundException.h>
#include <aws/apigatewayv2/model/TooManyRequestsException.h>
using namespace Aws::Client;
using namespace Aws::Utils;
using namespace Aws::ApiGatewayV2;
using namespace Aws::ApiGatewayV2::Model;
namespace Aws
{
namespace ApiGatewayV2
{
template<> AWS_APIGATEWAYV2_API NotFoundException ApiGatewayV2Error::GetModeledError()
{
assert(this->GetErrorType() == ApiGatewayV2Errors::NOT_FOUND);
return NotFoundException(this->GetJsonPayload().View());
}
template<> AWS_APIGATEWAYV2_API TooManyRequestsException ApiGatewayV2Error::GetModeledError()
{
assert(this->GetErrorType() == ApiGatewayV2Errors::TOO_MANY_REQUESTS);
return TooManyRequestsException(this->GetJsonPayload().View());
}
namespace ApiGatewayV2ErrorMapper
{
static const int CONFLICT_HASH = HashingUtils::HashString("ConflictException");
static const int NOT_FOUND_HASH = HashingUtils::HashString("NotFoundException");
static const int TOO_MANY_REQUESTS_HASH = HashingUtils::HashString("TooManyRequestsException");
static const int BAD_REQUEST_HASH = HashingUtils::HashString("BadRequestException");
AWSError<CoreErrors> GetErrorForName(const char* errorName)
{
int hashCode = HashingUtils::HashString(errorName);
if (hashCode == CONFLICT_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(ApiGatewayV2Errors::CONFLICT), false);
}
else if (hashCode == NOT_FOUND_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(ApiGatewayV2Errors::NOT_FOUND), false);
}
else if (hashCode == TOO_MANY_REQUESTS_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(ApiGatewayV2Errors::TOO_MANY_REQUESTS), true);
}
else if (hashCode == BAD_REQUEST_HASH)
{
return AWSError<CoreErrors>(static_cast<CoreErrors>(ApiGatewayV2Errors::BAD_REQUEST), false);
}
return AWSError<CoreErrors>(CoreErrors::UNKNOWN, false);
}
} // namespace ApiGatewayV2ErrorMapper
} // namespace ApiGatewayV2
} // namespace Aws
| 32.705882 | 102 | 0.782824 | [
"model"
] |
664534b4d14604e9d126ec83a44f768697539475 | 1,499 | hpp | C++ | src/ArduinoJson/Operators/VariantSubscripts.hpp | iamdev/ESP8266-SmartRelay | 297453d4c05aec8f93012b6cb0a24ecf493ca2bf | [
"MIT"
] | 2 | 2020-01-14T08:38:42.000Z | 2020-10-06T15:22:23.000Z | src/ArduinoJson/Operators/VariantSubscripts.hpp | iamdev/ESP8266-SmartRelay | 297453d4c05aec8f93012b6cb0a24ecf493ca2bf | [
"MIT"
] | 1 | 2019-06-03T00:22:00.000Z | 2019-06-03T00:22:00.000Z | src/ArduinoJson/Operators/VariantSubscripts.hpp | iamdev/ESP8266-SmartRelay | 297453d4c05aec8f93012b6cb0a24ecf493ca2bf | [
"MIT"
] | null | null | null | // ArduinoJson - arduinojson.org
// Copyright Benoit Blanchon 2014-2018
// MIT License
#pragma once
#include "../Polyfills/attributes.hpp"
#include "../Polyfills/type_traits.hpp"
#include "../Strings/StringWrappers.hpp"
#include "../Variant/VariantAs.hpp"
namespace ARDUINOJSON_NAMESPACE {
class ArrayRef;
class ObjectRef;
// Forward declarations.
class ArraySubscript;
template <typename TKey>
class ObjectSubscript;
template <typename TImpl>
class VariantSubscripts {
public:
// Mimics an array.
// Returns the element at specified index if the variant is an array.
FORCE_INLINE ArraySubscript operator[](size_t index) const;
// Mimics an object.
// Returns the value associated with the specified key if the variant is
// an object.
//
// ObjectSubscript operator[](TKey) const;
// TKey = const std::string&, const String&
template <typename TString>
FORCE_INLINE typename enable_if<IsString<TString>::value,
ObjectSubscript<const TString &> >::type
operator[](const TString &key) const;
//
// ObjectSubscript operator[](TKey) const;
// TKey = const char*, const char[N], const __FlashStringHelper*
template <typename TString>
FORCE_INLINE typename enable_if<IsString<TString *>::value,
ObjectSubscript<TString *> >::type
operator[](TString *key) const;
private:
const TImpl *impl() const {
return static_cast<const TImpl *>(this);
}
};
} // namespace ARDUINOJSON_NAMESPACE
| 28.826923 | 74 | 0.701801 | [
"object"
] |
6646646655c5e5cf87d6fce6959c0359e46bfbda | 17,833 | cpp | C++ | tests/ami_test/derived/client.cpp | ClausKlein/taox11 | 669cfd2d0be258722c7ee32b23f2e5cb83e4520f | [
"MIT"
] | 20 | 2019-11-13T12:31:20.000Z | 2022-02-27T12:30:39.000Z | tests/ami_test/derived/client.cpp | ClausKlein/taox11 | 669cfd2d0be258722c7ee32b23f2e5cb83e4520f | [
"MIT"
] | 46 | 2019-11-15T20:40:18.000Z | 2022-03-31T19:04:36.000Z | tests/ami_test/derived/client.cpp | ClausKlein/taox11 | 669cfd2d0be258722c7ee32b23f2e5cb83e4520f | [
"MIT"
] | 5 | 2019-11-12T15:00:50.000Z | 2022-01-17T17:33:05.000Z | /**
* @file client.cpp
* @author Marijke Hengstmengel
*
* @brief CORBA C++11 client ami test
*
* @copyright Copyright (c) Remedy IT Expertise BV
*/
#include "ace/Get_Opt.h"
#include "ace/Task.h"
#include "ami_testAmiC.h"
#include <thread>
#include "testlib/taox11_testlog.h"
const ACE_TCHAR *ior = ACE_TEXT("file://server.ior");
int16_t result = 0;
int16_t nr_of_replies = 0;
int16_t myfoo_foo = 0;
int16_t mybar_foo = 0;
int16_t myfoo_attrib = 0;
int16_t mybar_attrib = 0;
int16_t myfoo_foo_excep = 0;
int16_t mybar_foo_excep = 0;
bool
parse_args (int argc, ACE_TCHAR *argv[])
{
ACE_Get_Opt get_opts (argc, argv, ACE_TEXT("k:"));
int c;
while ((c = get_opts ()) != -1)
switch (c)
{
case 'k':
ior = get_opts.opt_arg ();
break;
case '?':
default:
TAOX11_TEST_ERROR << "usage: -k <ior>"
<< std::endl;
return false;
}
// Indicates successful parsing of the command line
return true;
}
class MyFooHandler
: public virtual CORBA::amic_traits<A::MyFoo>::replyhandler_base_type
{
public:
/// Constructor.
MyFooHandler () = default;
/// Destructor.
~MyFooHandler () = default;
void foo (int32_t ami_return_val) override
{
TAOX11_TEST_INFO << "Callback method <MyFooHandler::foo> called: ret "
<< ami_return_val << std::endl;
nr_of_replies--;
myfoo_foo++;
}
void foo_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type excep_holder) override
{
try
{
excep_holder->raise_exception ();
}
catch (const A::InternalError& ex)
{
myfoo_foo_excep++;
TAOX11_TEST_INFO << "Callback method <MyFoo::foo_excep> exception received successfully <"
<< ex.id() << "> and <" << ex.error_string() << ">." << std::endl;
if (ex.id() != 2)
{
TAOX11_TEST_ERROR
<< "ERROR: Callback method <MyFoo::foo_excep> exception ex.id not 2 but "
<< ex.id() << std::endl;
result = 1;
}
if (ex.error_string() != "Hello from foo")
{
TAOX11_TEST_ERROR
<< "ERROR: Callback method <MyFoo::foo_excep> exception ex.error_string() not ok: "
<< ex.error_string() << std::endl;
result = 1;
}
}
catch (const CORBA::Exception& )
{
TAOX11_TEST_ERROR
<< "ERROR: Callback method <MyFoo::foo_excep> caught the wrong exception"
<< std::endl;
result = 1;
}
nr_of_replies--;
}
void get_my_foo_attrib (int32_t ret) override
{
TAOX11_TEST_INFO << "Callback method <MyFooHandler::get_my_foo_attrib> called: ret " << ret << std::endl;
if (ret != 3)
{
TAOX11_TEST_ERROR
<< "ERROR: Callback method <MyFooHandler::get_my_foo_attrib> ret not 3 but "
<< ret << std::endl;
result = 1;
}
nr_of_replies--;
myfoo_attrib++;
}
void get_my_foo_attrib_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override
{
TAOX11_TEST_INFO << "Callback method <get_my_foo_attrib_excep> called." << std::endl;
}
void set_my_foo_attrib () override
{
TAOX11_TEST_INFO << "Callback method <MyFooHandler::set_my_foo_attrib> called:"<< std::endl;
nr_of_replies--;
myfoo_attrib++;
}
void set_my_foo_attrib_excep (IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override
{
TAOX11_TEST_INFO << "Callback method <set_my_foo_attrib_excep> called:" << std::endl;
}
};
class MyBarHandler
: public virtual CORBA::amic_traits<A::MyBar>::replyhandler_base_type
{
public:
/// Constructor.
MyBarHandler () = default;
/// Destructor.
~MyBarHandler () = default;
void bye (int32_t ami_return_val, int32_t /*answer*/) override
{
nr_of_replies--;
TAOX11_TEST_INFO << "Callback method <MyBarHandler::bye> called: ret "
<< ami_return_val << std::endl;
}
void bye_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override
{
TAOX11_TEST_INFO << "Callback method <bye_excep> called."<< std::endl;
}
void foo (int32_t ami_return_val) override
{
TAOX11_TEST_INFO << "Callback method <MyBarHandler::foo> called: ret "
<< ami_return_val << std::endl;
nr_of_replies--;
mybar_foo++;
}
void foo_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type excep_holder) override
{
try
{
excep_holder->raise_exception ();
}
catch (const A::InternalError& ex)
{
mybar_foo_excep++;
TAOX11_TEST_INFO << "Callback method <MyBar::foo_excep> exception received successfully <"
<< ex.id() << "> and <" << ex.error_string() << ">." << std::endl;
if (ex.id() != 3)
{
TAOX11_TEST_ERROR
<< "ERROR: Callback method <MyBar::foo_excep> exception ex.id not 3 but "
<< ex.id() << std::endl;
result = 1;
}
if (ex.error_string() != "Hello from bar")
{
TAOX11_TEST_ERROR
<< "ERROR: Callback method <MyBar::foo_excep> exception ex.error_string() not ok: "
<< ex.error_string() << std::endl;
result = 1;
}
}
catch (const CORBA::Exception& )
{
TAOX11_TEST_ERROR
<< "ERROR: Callback method <MyFoo::foo_excep> caught the wrong exception"
<< std::endl;
result = 1;
}
nr_of_replies--;
}
void get_my_foo_attrib (int32_t ret) override
{
TAOX11_TEST_INFO << "Callback method <MyBarHandler::get_my_foo_attrib> called: ret "
<< ret << std::endl;
if (ret != 11)
{
TAOX11_TEST_ERROR
<< "ERROR: Callback method <MyBarHandler::get_my_foo_attrib> ret not 11 but "
<< ret << std::endl;
result = 1;
}
nr_of_replies--;
mybar_attrib++;
}
void get_my_foo_attrib_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override
{
TAOX11_TEST_INFO << "Callback method <get_my_foo_attrib_excep> called." << std::endl;
}
void set_my_foo_attrib () override
{
TAOX11_TEST_INFO << "Callback method <MyBarHandler::set_my_foo_attrib> called:"<< std::endl;
nr_of_replies--;
mybar_attrib++;
}
void set_my_foo_attrib_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override
{
TAOX11_TEST_INFO << "Callback method <set_my_foo_attrib_excep> called:" << std::endl;
}
void do_something (int32_t /*ami_return_val*/) override
{
}
void do_something_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override
{
TAOX11_TEST_INFO << "Callback method <do_someting_excep> called."<< std::endl;
}
void get_my_derived_attrib (int32_t ret) override
{
TAOX11_TEST_INFO << "Callback method <get_my_derived_attrib> called: ret " << ret << std::endl;
}
void get_my_derived_attrib_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override
{
TAOX11_TEST_INFO << "Callback method <get_my_derived_attrib_excep> called." << std::endl;
}
void set_my_derived_attrib () override
{
TAOX11_TEST_INFO << "Callback method <set_my_derived_attrib> called." << std::endl;
}
void set_my_derived_attrib_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override
{
TAOX11_TEST_INFO << "Callback method <set_my_derived_attrib_excep> called:" << std::endl;
}
void get_my_bar_attrib (int32_t ret) override
{
nr_of_replies--;
TAOX11_TEST_INFO << "Callback method <get_my_bar_attrib> called: ret " << ret << std::endl;
if (ret != 9)
{
TAOX11_TEST_ERROR
<< "ERROR: Callback method <MyBarHandler::get_my_foo_attrib> ret not 9 but "
<< ret << std::endl;
result = 1;
}
}
void get_my_bar_attrib_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override
{
TAOX11_TEST_INFO << "Callback method <get_my_bar_attrib_excep> called." << std::endl;
}
void set_my_bar_attrib () override
{
nr_of_replies--;
TAOX11_TEST_INFO << "Callback method <set_my_bar_attrib> called:"<< std::endl;
}
void set_my_bar_attrib_excep (
IDL::traits< ::Messaging::ExceptionHolder>::ref_type /*excep_holder*/) override
{
TAOX11_TEST_INFO << "Callback method <set_my_bar_attrib_excep> called:" << std::endl;
}
};
int main(int argc, char* argv[])
{
try
{
IDL::traits<CORBA::ORB>::ref_type _orb = CORBA::ORB_init (argc, argv);
if (_orb == nullptr)
{
TAOX11_TEST_ERROR << "ERROR: CORBA::ORB_init (argc, argv) returned null ORB."
<< std::endl;
return 1;
}
if (parse_args (argc, argv) == false)
return 1;
IDL::traits<CORBA::Object>::ref_type obj = _orb->string_to_object (ior);
if (!obj)
{
TAOX11_TEST_ERROR << "ERROR: string_to_object(<ior>) returned null reference."
<< std::endl;
return 1;
}
TAOX11_TEST_INFO << "client:retrieved object reference" << std::endl;
IDL::traits<A::Hello>::ref_type ami_test_var = IDL::traits<A::Hello>::narrow (obj);
if (!ami_test_var)
{
TAOX11_TEST_ERROR << "ERROR: IDL::traits<A::Hello>::narrow (obj) returned null object."
<< std::endl;
return 1;
}
TAOX11_TEST_INFO << "narrowed ::A::Hello interface" << std::endl;
// Instantiate the ReplyHandlers and register that with the POA.
IDL::traits<CORBA::Object>::ref_type poa_obj =
_orb->resolve_initial_references ("RootPOA");
if (!poa_obj)
{
TAOX11_TEST_ERROR
<< "ERROR: resolve_initial_references (\"RootPOA\") returned null reference."
<< std::endl;
return 1;
}
TAOX11_TEST_INFO << "retrieved RootPOA object reference" << std::endl;
IDL::traits<PortableServer::POA>::ref_type root_poa =
IDL::traits<PortableServer::POA>::narrow (poa_obj);
if (!root_poa)
{
TAOX11_TEST_ERROR
<< "ERROR: IDL::traits<PortableServer::POA>::narrow (obj) returned null object."
<< std::endl;
return 1;
}
TAOX11_TEST_INFO << "narrowed POA interface" << std::endl;
IDL::traits<PortableServer::POAManager>::ref_type poaman =
root_poa->the_POAManager ();
if (!poaman)
{
TAOX11_TEST_ERROR
<< "ERROR: root_poa->the_POAManager () returned null object."
<< std::endl;
return 1;
}
//Handler for interface MyBar
CORBA::amic_traits<A::MyBar>::replyhandler_servant_ref_type test_handler_impl_bar =
CORBA::make_reference<MyBarHandler> ();
TAOX11_TEST_INFO << "created MyBarHandler servant" << std::endl;
PortableServer::ObjectId id_bar = root_poa->activate_object (test_handler_impl_bar);
TAOX11_TEST_INFO << "activated MyBarHandler servant" << std::endl;
IDL::traits<CORBA::Object>::ref_type test_handler_bar_obj =
root_poa->id_to_reference (id_bar);
if (test_handler_bar_obj == nullptr)
{
TAOX11_TEST_ERROR
<< "ERROR: root_poa->id_to_reference (id) returned null reference."
<< std::endl;
return 1;
}
CORBA::amic_traits<A::MyBar>::replyhandler_ref_type test_handler_bar =
CORBA::amic_traits<A::MyBar>::replyhandler_traits::narrow (test_handler_bar_obj);
if (test_handler_bar == nullptr)
{
TAOX11_TEST_ERROR
<< "ERROR: CORBA::amic_traits<A::MyBar>::replyhandler_traits::narrow (test_handler_bar_obj) returned null reference."
<< std::endl;
return 1;
}
//Handler for interface MyFoo
CORBA::amic_traits<A::MyFoo>::replyhandler_servant_ref_type test_handler_impl_foo =
CORBA::make_reference<MyFooHandler> ();
TAOX11_TEST_INFO << "created MyFooHandler servant" << std::endl;
PortableServer::ObjectId id_foo = root_poa->activate_object (test_handler_impl_foo);
TAOX11_TEST_INFO << "activated MyFooHandler servant" << std::endl;
IDL::traits<CORBA::Object>::ref_type test_handler_foo_obj =
root_poa->id_to_reference (id_foo);
if (test_handler_foo_obj == nullptr)
{
TAOX11_TEST_ERROR
<< "ERROR: root_poa->id_to_reference (id) returned null reference."
<< std::endl;
return 1;
}
CORBA::amic_traits<A::MyFoo>::replyhandler_ref_type test_handler_foo =
CORBA::amic_traits<A::MyFoo>::replyhandler_traits::narrow (test_handler_foo_obj);
if (test_handler_foo == nullptr)
{
TAOX11_TEST_ERROR
<< "ERROR: CORBA::amic_traits<A::MyFoo>::replyhandler_traits::narrow (test_handler_foo_obj) returned null reference."
<< std::endl;
return 1;
}
poaman->activate ();
A::MyBar::_ref_type i_bar = ami_test_var->get_iMyBar();
if (!i_bar)
{
TAOX11_TEST_ERROR << "ERROR: Retrieve of iMyBar returned null object." << std::endl;
return 1;
}
CORBA::amic_traits<A::MyBar>::ref_type i_bar_async = CORBA::amic_traits<A::MyBar>::narrow (i_bar);
if (!i_bar_async)
{
TAOX11_TEST_ERROR << "ERROR: CORBA::amic_traitsA::MyBar>::narrow (i_bar) returned null object."
<< std::endl;
return 1;
}
A::MyFoo::_ref_type i_foo = ami_test_var->get_iMyFoo();
if (!i_foo)
{
TAOX11_TEST_ERROR << "ERROR: Retrieve of iMyFoo returned null object." << std::endl;
return 1;
}
CORBA::amic_traits<A::MyFoo>::ref_type i_foo_async = CORBA::amic_traits<A::MyFoo>::narrow (i_foo);
if (!i_foo_async)
{
TAOX11_TEST_ERROR << "ERROR: CORBA::amic_traitsA::MyFoo>::narrow (i_foo) returned null object."
<< std::endl;
return 1;
}
TAOX11_TEST_INFO << "Client: Sending 3 asynch messages MyBar::bye, MyBar::foo and MyFoo::foo." << std::endl;
i_bar_async->sendc_bye (test_handler_bar);
i_bar_async->sendc_foo (test_handler_bar, 12);
i_foo_async->sendc_foo (test_handler_foo, 11);
TAOX11_TEST_INFO << "Client: Sending 2 asynch messages for MyBar::my_bar_attrib attributes." << std::endl;
i_bar_async->sendc_set_my_bar_attrib (test_handler_bar, 101);
i_bar_async->sendc_get_my_bar_attrib (test_handler_bar);
TAOX11_TEST_INFO << "Client: Sending 2 asynch messages for MyBar::my_foo_attrib attributes." << std::endl;
i_bar_async->sendc_set_my_foo_attrib (test_handler_bar, 101);
i_bar_async->sendc_get_my_foo_attrib (test_handler_bar);
TAOX11_TEST_INFO << "Client: Sending 2 asynch messages for MyFoo::my_foo_attrib attributes." << std::endl;
i_foo_async->sendc_set_my_foo_attrib (test_handler_foo, 101);
i_foo_async->sendc_get_my_foo_attrib (test_handler_foo);
TAOX11_TEST_INFO << "Client: Sending asynch messages MyBar::foo (2) and MyFoo::foo (1) to trigger exceptions." << std::endl;
i_bar_async->sendc_foo (test_handler_bar, 0);
i_foo_async->sendc_foo (test_handler_foo, 0);
i_bar_async->sendc_foo (test_handler_bar, 0);
nr_of_replies = 12;
TAOX11_TEST_INFO << "Client: Do something else before coming back for the replies." << std::endl;
for (int i = 0; i < 10; i ++)
{
TAOX11_TEST_INFO << " ...";
std::this_thread::sleep_for (std::chrono::milliseconds (10));
}
TAOX11_TEST_INFO << std::endl << "Client: Now let's look for the replies." << std::endl;
std::this_thread::sleep_for (std::chrono::seconds (2));
while ((nr_of_replies > 0))
{
bool pending = _orb->work_pending();
if (pending)
{
_orb->perform_work ();
}
}
if ((nr_of_replies != 0) || (myfoo_foo != 1) || (mybar_foo != 1))
{
TAOX11_TEST_ERROR << "ERROR: Client didn't receive expected replies. Expected -12- , received -"
<< (5 - nr_of_replies) << "-. " << " Expected MyFoo- foo <1> , received <"
<< myfoo_foo << ">. Expected MyBar- foo <1>, received <" << mybar_foo << ">." << std::endl;
result = 1;
}
if ((myfoo_attrib != 2) || (mybar_attrib != 2))
{
TAOX11_TEST_ERROR << "ERROR: Client didn't receive expected replies on my_foo_attrib. "
<< "Expected MyFoo- my_foo_attrib <2> , received <"
<< myfoo_attrib << ">. Expected MyBar- my_foo_attrib <2>, received <"
<< mybar_attrib << ">." << std::endl;
result = 1;
}
if ((myfoo_foo_excep != 1) || (mybar_foo_excep != 2))
{
TAOX11_TEST_ERROR << "ERROR: Client didn't receive expected exceptions on my_foo. "
<< "Expected MyFoo- my_foo_excep <1> , received <"
<< myfoo_foo_excep << ">. Expected MyBar- my_foo_excep <2>, received <"
<< mybar_foo_excep << ">." << std::endl;
result = 1;
}
ami_test_var->shutdown ();
root_poa->destroy (true, false);
_orb->destroy ();
}
catch (const std::exception& e)
{
TAOX11_TEST_ERROR << "exception caught: " << e << std::endl;
return 1;
}
return result;
}
| 31.674956 | 130 | 0.600965 | [
"object"
] |
664e9184f67a3a2e797342a4fb56495eba719ce9 | 2,032 | cpp | C++ | MyImage/Source/PluginEditor.cpp | DASTUDIO/Juce_Audio_Tutorial | e9cdb3fc68c54c24d05b8f38b8384e947f269949 | [
"MIT"
] | 9 | 2020-06-18T16:00:26.000Z | 2021-07-05T07:15:22.000Z | MyImage/Source/PluginEditor.cpp | DASTUDIO/Juce_Audio_Tutorial | e9cdb3fc68c54c24d05b8f38b8384e947f269949 | [
"MIT"
] | null | null | null | MyImage/Source/PluginEditor.cpp | DASTUDIO/Juce_Audio_Tutorial | e9cdb3fc68c54c24d05b8f38b8384e947f269949 | [
"MIT"
] | 1 | 2021-06-06T03:02:36.000Z | 2021-06-06T03:02:36.000Z | /*
==============================================================================
This file was auto-generated!
It contains the basic framework code for a JUCE plugin editor.
==============================================================================
*/
#include "PluginProcessor.h"
#include "PluginEditor.h"
//==============================================================================
MyImageAudioProcessorEditor::MyImageAudioProcessorEditor (MyImageAudioProcessor& p)
: AudioProcessorEditor (&p), processor (p)
{
myImageComponent.setImage(ImageCache::getFromMemory(BinaryData::background_png, BinaryData::background_pngSize));
myImageComponent.setImagePlacement(RectanglePlacement(RectanglePlacement::stretchToFit));
addAndMakeVisible(myImageComponent);
myImageComponent.setBounds(getLocalBounds());
setSize (837, 526);
mySlider.setBounds(0, 0, 837, 526);
mySlider.setSliderStyle(Slider::SliderStyle::RotaryVerticalDrag);
mySlider.setTextBoxStyle(Slider::NoTextBox, false, 0, 0);
mySlider.setRange(0, 1,0.01);
myLookAndFeel = new MyLookAndFeel();
mySlider.setLookAndFeel(myLookAndFeel);
addAndMakeVisible(mySlider);
}
MyImageAudioProcessorEditor::~MyImageAudioProcessorEditor()
{
}
//==============================================================================
void MyImageAudioProcessorEditor::paint (Graphics& g)
{
// (Our component is opaque, so we must completely fill the background with a solid colour)
// g.fillAll (getLookAndFeel().findColour (ResizableWindow::backgroundColourId));
//
// g.setColour (Colours::white);
// g.setFont (15.0f);
// g.drawFittedText ("Hello World!", getLocalBounds(), Justification::centred, 1);
}
void MyImageAudioProcessorEditor::resized()
{
myImageComponent.setBounds(getLocalBounds());
// This is generally where you'll want to lay out the positions of any
// subcomponents in your editor..
}
| 34.440678 | 118 | 0.596457 | [
"solid"
] |
5941bdf106f9e53fb1e92d2f8964cee4da417c30 | 4,228 | hpp | C++ | vector.hpp | DoubleEspresso/math-lib | 68ce2be021d28e7321385956cca951e2c3115388 | [
"MIT"
] | null | null | null | vector.hpp | DoubleEspresso/math-lib | 68ce2be021d28e7321385956cca951e2c3115388 | [
"MIT"
] | null | null | null | vector.hpp | DoubleEspresso/math-lib | 68ce2be021d28e7321385956cca951e2c3115388 | [
"MIT"
] | null | null | null | #include "vector.cuh"
namespace Math
{
namespace Vector {
template<typename T>
void dot_cpu(const T * a, const T * b, T * c, const int dim) {
#ifdef _WIN32
LARGE_INTEGER frequency;
LARGE_INTEGER t1, t2;
double elapsedTime;
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&t1);
#endif
const int bs = 4; // possibly 8 with AVX-instructions.
int r = dim - dim / bs * bs; int dim4 = dim - r;
T dot1 = 0; T dot2 = 0; T dot3 = 0; T dot4 = 0;
*c = 0;
for (int j = 0; j < dim4; j += bs) {
//_mm_prefetch(((char *)(a)) + 64, _MM_HINT_T0); _mm_prefetch(((char *)(b)) + 64, _MM_HINT_T0);
dot1 += a[j] * b[j];
dot2 += a[j + 1] * b[j + 1];
dot3 += a[j + 2] * b[j + 2];
dot4 += a[j + 3] * b[j + 3];
}
int s = dim - r;
if (r >= 1) dot1 += a[s] * b[s];
if (r >= 2) dot2 += a[s + 1] * b[s + 1];
if (r >= 3) dot3 += a[s + 2] * b[s + 2];
(*c) += dot1 + dot2 + dot3 + dot4;
#ifdef _WIN32
QueryPerformanceCounter(&t2);
elapsedTime = (t2.QuadPart - t1.QuadPart) * 1000.0 / frequency.QuadPart;
//printf("..cpu(%3.1fms) (1-thread)\n", (float)elapsedTime);
#endif
}
template<typename T>
struct vd_tdata {
MUTEX * m;
unsigned long tid;
int tstride;
const T * a;
const T * b;
T * c;
T dot1, dot2, dot3, dot4;
int dim;
};
template<typename T>
void dot_cpup(const T * a, const T * b, T * c, const int dim) {
int nb_threads = 4; // todo.
THREAD_HANDLE * threads = new THREAD_HANDLE[nb_threads];
std::vector< vd_tdata<T> > tdata;
(*c) = 0;
#ifdef _WIN32
LARGE_INTEGER frequency;
LARGE_INTEGER t1, t2;
double elapsedTime;
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&t1);
#endif
MUTEX mutex_vec;
mutex_init(mutex_vec);
for (int j = 0; j < nb_threads; ++j) {
vd_tdata<T> d;
d.tid = (unsigned long)j; d.tstride = nb_threads * 4;
d.a = a; d.b = b; d.dim = dim; d.c = c;
d.m = &mutex_vec;
tdata.push_back(d);
}
for (int j = 0; j < nb_threads; ++j) threads[j] = start_thread((thread_fnc)dot_task<T>, (void*)&tdata[j], j);
wait_threads_finish(threads, nb_threads);
if (threads) { delete[] threads; threads = 0; }
#ifdef _WIN32
QueryPerformanceCounter(&t2);
elapsedTime = (t2.QuadPart - t1.QuadPart) * 1000.0 / frequency.QuadPart;
printf("..cpu(%3.1fms) (%d-threads)\n", (float)elapsedTime, nb_threads);
#endif
}
template<typename T>
void dot_task(void * p) {
vd_tdata<T> * d = (vd_tdata<T>*) p;
int bs = 4;
int r = d->dim - d->dim / bs * bs; int dim4 = d->dim - r;
d->dot1 = 0; d->dot2 = 0; d->dot3 = 0; d->dot4 = 0;
for (int j = d->tid * bs; j < dim4; j += d->tstride) {
d->dot1 += d->a[j] * d->b[j];
d->dot2 += d->a[j + 1] * d->b[j + 1];
d->dot3 += d->a[j + 2] * d->b[j + 2];
d->dot4 += d->a[j + 3] * d->b[j + 3];
}
if (r > 0 && d->tid == 0) {
int s = d->dim - r;
if (r == 1) d->dot1 += d->a[s] * d->b[s];
else if (r == 2) {
d->dot1 += d->a[s] * d->b[s];
d->dot2 += d->a[s + 1] * d->b[s + 1];
}
else if (r == 3) {
d->dot1 += d->a[s] * d->b[s];
d->dot2 += d->a[s + 1] * d->b[s + 1];
d->dot3 += d->a[s + 2] * d->b[s + 2];
}
}
mutex_lock(*(d->m));
(*d->c) += d->dot1 + d->dot2 + d->dot3 + d->dot4;
mutex_unlock(*(d->m));
}
template<typename T>
void adotb_ref(const T * a, const T * b, T * c, const int dim) {
#ifdef _WIN32
LARGE_INTEGER frequency;
LARGE_INTEGER t1, t2;
double elapsedTime;
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&t1);
#endif
(*c) = 0;
for (int j = 0; j < dim; ++j) (*c) += a[j] * b[j];
#ifdef _WIN32
QueryPerformanceCounter(&t2);
elapsedTime = (t2.QuadPart - t1.QuadPart) * 1000.0 / frequency.QuadPart;
printf("..cpu_ref(%3.1fms) (1-thread)\n", (float)elapsedTime);
#endif
}
template<typename T>
void dot_gpu(const T * a, const T * b, T * c, const int dim) {
dot_device(a, b, c, dim);
}
}
}
| 28.186667 | 115 | 0.517975 | [
"vector"
] |
5942ba9d4c534f97360e1a5a26c6f2ad1b3c9bad | 13,831 | cpp | C++ | source/windows/brwindowsxinput.cpp | Olde-Skuul/burgerlib | 80848a4dfa17c5c05095ecea14a9bd87f86dfb9d | [
"Zlib"
] | 115 | 2015-01-18T17:29:30.000Z | 2022-01-30T04:31:48.000Z | source/windows/brwindowsxinput.cpp | Olde-Skuul/burgerlib | 80848a4dfa17c5c05095ecea14a9bd87f86dfb9d | [
"Zlib"
] | 9 | 2015-01-22T04:53:38.000Z | 2015-01-31T13:52:40.000Z | source/windows/brwindowsxinput.cpp | Olde-Skuul/burgerlib | 80848a4dfa17c5c05095ecea14a9bd87f86dfb9d | [
"Zlib"
] | 9 | 2015-01-23T20:06:46.000Z | 2020-05-20T16:06:00.000Z | /***************************************
Shims for xinput1_4.dll or xinput1_3.dll
Copyright (c) 1995-2021 by Rebecca Ann Heineman <becky@burgerbecky.com>
It is released under an MIT Open Source license. Please see LICENSE for
license details. Yes, you can use it in a commercial title without paying
anything, just give me a credit.
Please? It's not like I'm asking you for money!
***************************************/
#include "brwindowstypes.h"
#if defined(BURGER_WINDOWS) || defined(DOXYGEN)
#if !defined(DOXYGEN)
//
// Handle some annoying defines that some windows SDKs may or may not have
//
#if !defined(WIN32_LEAN_AND_MEAN)
#define WIN32_LEAN_AND_MEAN
#endif
#if !defined(_WIN32_WINNT)
#define _WIN32_WINNT 0x0501 // Windows XP
#endif
#include <Windows.h>
#include <Xinput.h>
typedef DWORD(WINAPI* XInputGetStatePtr)(
DWORD dwUserIndex, XINPUT_STATE* pState);
typedef DWORD(WINAPI* XInputSetStatePtr)(
DWORD dwUserIndex, XINPUT_VIBRATION* pVibration);
typedef DWORD(WINAPI* XInputGetCapabilitiesPtr)(
DWORD dwUserIndex, DWORD dwFlags, XINPUT_CAPABILITIES* pCapabilities);
typedef void(WINAPI* XInputEnablePtr)(BOOL enable);
typedef DWORD(WINAPI* XInputGetDSoundAudioDeviceGuidsPtr)(
DWORD dwUserIndex, GUID* pDSoundRenderGuid, GUID* pDSoundCaptureGuid);
typedef DWORD(WINAPI* XInputGetBatteryInformationPtr)(DWORD dwUserIndex,
BYTE devType, XINPUT_BATTERY_INFORMATION* pBatteryInformation);
typedef DWORD(WINAPI* XInputGetKeystrokePtr)(
DWORD dwUserIndex, DWORD dwReserved, PXINPUT_KEYSTROKE pKeystroke);
typedef DWORD(WINAPI* XInputGetAudioDeviceIdsPtr)(DWORD dwUserIndex,
LPWSTR pRenderDeviceId, UINT* pRenderCount, LPWSTR pCaptureDeviceId,
UINT* pCaptureCount);
// Unit tests for pointers
// XInputGetStatePtr gXInputGetState = ::XInputGetState;
// XInputSetStatePtr gXInputSetState = ::XInputSetState;
// XInputGetCapabilitiesPtr gXInputGetCapabilities = ::XInputGetCapabilities;
// XInputEnablePtr gXInputEnable = ::XInputEnable;
// XInputGetDSoundAudioDeviceGuidsPtr gXInputGetDSoundAudioDeviceGuids =
// ::XInputGetDSoundAudioDeviceGuids;
// XInputGetBatteryInformationPtr gXInputGetBatteryInformation =
// ::XInputGetBatteryInformation;
// XInputGetKeystrokePtr gXInputGetKeystroke = ::XInputGetKeystroke;
// XInputGetAudioDeviceIdsPtr gXInputGetAudioDeviceIds =
// ::XInputGetAudioDeviceIds;
#endif
/*! ************************************
\brief Load in xinput1_4.dll and call XInputGetState
To allow maximum compatibility, this function will manually load
xinput1_4.dll or xinput1_3.dll and then invoke XInputGetState if present.
https://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx_sdk.reference.xinputgetstate(v=vs.85).aspx
\windowsonly
\param dwUserIndex Index of the user's controller. Can be a value from 0
to 3.
\param pState Pointer to an XINPUT_STATE structure that receives the current
state of the controller.
\return Zero if no error. Any other value means an error occurred,
ERROR_CALL_NOT_IMPLEMENTED means the function was not found
***************************************/
uint32_t BURGER_API Burger::Windows::XInputGetState(
uint32_t dwUserIndex, _XINPUT_STATE* pState)
{
// Get the function pointer
void* pXInputGetState = LoadFunctionIndex(CALL_XInputGetState);
uint32_t uResult = ERROR_CALL_NOT_IMPLEMENTED;
if (pXInputGetState) {
uResult = static_cast<XInputGetStatePtr>(pXInputGetState)(
dwUserIndex, pState);
}
return uResult;
}
/*! ************************************
\brief Load in xinput1_4.dll and call XInputSetState
To allow maximum compatibility, this function will manually load
xinput1_4.dll or xinput1_3.dll and then invoke XInputSetState if present.
https://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx_sdk.reference.xinputsetstate(v=vs.85).aspx
\windowsonly
\param dwUserIndex Index of the user's controller. Can be a value from 0
to 3.
\param pVibration Pointer to an XINPUT_VIBRATION structure containing the
vibration information to send to the controller.
\return Zero if no error. Any other value means an error occurred,
ERROR_CALL_NOT_IMPLEMENTED means the function was not found
***************************************/
uint32_t BURGER_API Burger::Windows::XInputSetState(
uint32_t dwUserIndex, _XINPUT_VIBRATION* pVibration)
{
// Get the function pointer
void* pXInputSetState = LoadFunctionIndex(CALL_XInputSetState);
uint32_t uResult = ERROR_CALL_NOT_IMPLEMENTED;
if (pXInputSetState) {
uResult = static_cast<XInputSetStatePtr>(pXInputSetState)(
dwUserIndex, pVibration);
}
return uResult;
}
/*! ************************************
\brief Load in xinput1_4.dll and call XInputGetCapabilities
To allow maximum compatibility, this function will manually load
xinput1_4.dll or xinput1_3.dll and then invoke XInputGetCapabilities if
present.
https://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx_sdk.reference.xinputgetcapabilities(v=vs.85).aspx
\windowsonly
\param dwUserIndex Index of the user's controller. Can be a value from 0
to 3.
\param dwFlags Input flags that identify the controller type. If this
value is 0, then the capabilities of all controllers connected to the
system are returned.
\param pCapabilities Pointer to an XINPUT_CAPABILITIES structure that
receives the controller capabilities.
\return Zero if no error. Any other value means an error occurred,
ERROR_CALL_NOT_IMPLEMENTED means the function was not found
***************************************/
uint32_t BURGER_API Burger::Windows::XInputGetCapabilities(
uint32_t dwUserIndex, uint32_t dwFlags, _XINPUT_CAPABILITIES* pCapabilities)
{
// Get the function pointer
void* pXInputGetCapabilities =
LoadFunctionIndex(CALL_XInputGetCapabilities);
uint32_t uResult = ERROR_CALL_NOT_IMPLEMENTED;
if (pXInputGetCapabilities) {
uResult = static_cast<XInputGetCapabilitiesPtr>(pXInputGetCapabilities)(
dwUserIndex, dwFlags, pCapabilities);
}
return uResult;
}
/*! ************************************
\brief Load in xinput1_4.dll and call XInputGetDSoundAudioDeviceGuids
To allow maximum compatibility, this function will manually load
xinput1_4.dll or xinput1_3.dll and then invoke
XInputGetDSoundAudioDeviceGuids if present.
https://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx_sdk.reference.xinputgetdsoundaudiodeviceguids(v=vs.85).aspx
\note This function is deprecated as of Windows 8 (DLL XInput 1.4 or later)
\windowsonly
\param dwUserIndex Index of the user's controller. Can be a value from 0
to 3.
\param pDSoundRenderGuid Pointer that receives the GUID of the headset
sound rendering device. \param pDSoundCaptureGuid Pointer that receives
the GUID of the headset sound capture device.
\return Zero if no error. Any other value means an error occurred,
ERROR_CALL_NOT_IMPLEMENTED means the function was not found
***************************************/
uint32_t BURGER_API Burger::Windows::XInputGetDSoundAudioDeviceGuids(
uint32_t dwUserIndex, GUID* pDSoundRenderGuid, GUID* pDSoundCaptureGuid)
{
// Get the function pointer
void* pXInputGetDSoundAudioDeviceGuids =
LoadFunctionIndex(CALL_XInputGetDSoundAudioDeviceGuids);
uint32_t uResult = ERROR_CALL_NOT_IMPLEMENTED;
if (pXInputGetDSoundAudioDeviceGuids) {
uResult = static_cast<XInputGetDSoundAudioDeviceGuidsPtr>(
pXInputGetDSoundAudioDeviceGuids)(
dwUserIndex, pDSoundRenderGuid, pDSoundCaptureGuid);
}
return uResult;
}
/*! ************************************
\brief Load in xinput1_4.dll and call XInputEnable
To allow maximum compatibility, this function will manually load
xinput1_4.dll or xinput1_3.dll and then invoke XInputEnable if present.
https://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx_sdk.reference.xinputenable(v=vs.85).aspx
\windowsonly
\param bEnable If enable is \ref FALSE, XInput will only send neutral data
in response to XInputGetState() (all buttons up, axes centered, and
triggers at 0). Sending any value other than \ref FALSE will restore
reading and writing functionality to normal.
***************************************/
void BURGER_API Burger::Windows::XInputEnable(uint_t bEnable)
{
// Get the function pointer
void* pXInputEnable = LoadFunctionIndex(CALL_XInputEnable);
if (pXInputEnable) {
static_cast<XInputEnablePtr>(pXInputEnable)(bEnable != 0);
}
}
/*! ************************************
\brief Load in xinput1_4.dll and call XInputGetAudioDeviceIds
To allow maximum compatibility, this function will manually load
xinput1_4.dll or xinput1_3.dll and then invoke XInputGetAudioDeviceIds if
present.
https://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx_sdk.reference.xinputgetaudiodeviceids(v=vs.85).aspx
\note This function is only available as of Windows 8 (DLL XInput 1.4 or
later)
\windowsonly
\param dwUserIndex Index of the gamer associated with the device.
\param pRenderDeviceId Pointer that receives Windows Core Audio device ID
string for render (speakers).
\param pRenderCount Pointer that receives the size, in wide-chars, of the
render device ID string buffer.
\param pCaptureDeviceId Pointer that receives Windows Core Audio device ID
string for capture (microphone).
\param pCaptureCount Pointer that receives the size, in wide-chars, of
capture device ID string buffer.
\return Zero if no error. Any other value means an error occurred,
ERROR_CALL_NOT_IMPLEMENTED means the function was not found
***************************************/
uint32_t BURGER_API Burger::Windows::XInputGetAudioDeviceIds(uint32_t dwUserIndex,
uint16_t* pRenderDeviceId, uint_t* pRenderCount, uint16_t* pCaptureDeviceId,
uint_t* pCaptureCount)
{
// Get the function pointer
void* pXInputGetAudioDeviceIds =
LoadFunctionIndex(CALL_XInputGetAudioDeviceIds);
uint32_t uResult = ERROR_CALL_NOT_IMPLEMENTED;
if (pXInputGetAudioDeviceIds) {
uResult = static_cast<XInputGetAudioDeviceIdsPtr>(
pXInputGetAudioDeviceIds)(dwUserIndex, (LPWSTR)pRenderDeviceId,
pRenderCount, (LPWSTR)pCaptureDeviceId, pCaptureCount);
}
return uResult;
}
/*! ************************************
\brief Load in xinput1_4.dll and call XInputGetBatteryInformation
To allow maximum compatibility, this function will manually load
xinput1_4.dll or xinput1_3.dll and then invoke XInputGetBatteryInformation
if present.
https://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx_sdk.reference.xinputgetbatteryinformation(v=vs.85).aspx
\windowsonly
\param dwUserIndex Index of the signed-in gamer associated with the device.
Can be a value in the range 0-XUSER_MAX_COUNT - 1.
\param devType Input Specifies which device associated with this user index
should be queried. Must be BATTERY_DEVTYPE_GAMEPAD or
BATTERY_DEVTYPE_HEADSET.
\param pBatteryInformation Pointer to an XINPUT_BATTERY_INFORMATION
structure that receives the battery information.
\return Zero if no error. Any other value means an error occurred,
ERROR_CALL_NOT_IMPLEMENTED means the function was not found
***************************************/
uint32_t BURGER_API Burger::Windows::XInputGetBatteryInformation(
uint32_t dwUserIndex, uint_t devType,
_XINPUT_BATTERY_INFORMATION* pBatteryInformation)
{
// Get the function pointer
void* pXInputGetBatteryInformation =
LoadFunctionIndex(CALL_XInputGetBatteryInformation);
uint32_t uResult = ERROR_CALL_NOT_IMPLEMENTED;
if (pXInputGetBatteryInformation) {
uResult = static_cast<XInputGetBatteryInformationPtr>(
pXInputGetBatteryInformation)(
dwUserIndex, static_cast<BYTE>(devType), pBatteryInformation);
}
return uResult;
}
/*! ************************************
\brief Load in xinput1_4.dll and call XInputGetKeystroke
To allow maximum compatibility, this function will manually load
xinput1_4.dll or xinput1_3.dll and then invoke XInputGetKeystroke if
present.
https://msdn.microsoft.com/en-us/library/windows/desktop/microsoft.directx_sdk.reference.xinputgetkeystroke(v=vs.85).aspx
\windowsonly
\param dwUserIndex Index of the signed-in gamer associated with the device.
Can be a value in the range 0-XUSER_MAX_COUNT - 1 or XUSER_INDEX_ANY to
fetch the next available input event from any user.
\param dwReserved Set to zero.
\param pKeystroke Pointer to an XINPUT_KEYSTROKE structure that receives
an input event.
\return Zero if no error. Any other value means an error occurred,
ERROR_CALL_NOT_IMPLEMENTED means the function was not found
***************************************/
uint32_t BURGER_API Burger::Windows::XInputGetKeystroke(
uint32_t dwUserIndex, uint32_t dwReserved, _XINPUT_KEYSTROKE* pKeystroke)
{
// Get the function pointer
void* pXInputGetKeystroke = LoadFunctionIndex(CALL_XInputGetKeystroke);
uint32_t uResult = ERROR_CALL_NOT_IMPLEMENTED;
if (pXInputGetKeystroke) {
uResult = static_cast<XInputGetKeystrokePtr>(pXInputGetKeystroke)(
dwUserIndex, dwReserved, pKeystroke);
}
return uResult;
}
#endif
| 37.997253 | 138 | 0.717952 | [
"render"
] |
594eca48d024efe604b08eadd96d1c602b576a50 | 4,385 | cc | C++ | tgt-dfg/src/dot_graph.cc | timothytrippel/bomberman | 517114a062e3b3160858af86b06334891a7e4554 | [
"BSD-2-Clause"
] | 1 | 2022-01-18T06:50:54.000Z | 2022-01-18T06:50:54.000Z | tgt-dfg/src/dot_graph.cc | timothytrippel/bomberman | 517114a062e3b3160858af86b06334891a7e4554 | [
"BSD-2-Clause"
] | 3 | 2021-03-26T20:45:07.000Z | 2022-01-13T03:30:40.000Z | tgt-dfg/src/dot_graph.cc | timothytrippel/bomberman | 517114a062e3b3160858af86b06334891a7e4554 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright © 2019, Massachusetts Institute of Technology
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "tgt-dfg/include/dot_graph.h"
#include <cassert>
#include <string>
#include "tgt-dfg/include/connection.h"
#include "tgt-dfg/include/dfg_typedefs.h"
#include "tgt-dfg/include/error.h"
// Constructors
DotGraph::DotGraph() : file_path_(NULL), file_ptr_(NULL) {}
DotGraph::DotGraph(std::string p) : file_ptr_(NULL) { set_file_path(p); }
// Destructors
DotGraph::~DotGraph() {
DEBUG_DESTRUCTORS(fprintf(DESTRUCTOR_PRINTS_FILE_PTR,
"Executing DotGraph destructor...\n");)
// Close file if its open and not STDOUT
if (file_ptr_ && (file_ptr_ != stdout)) {
close_file();
}
}
// Getters
std::string DotGraph::get_file_path() const { return file_path_; }
// Setters
void DotGraph::set_file_path(std::string p) { file_path_ = p; }
// Graph Construction
void DotGraph::init_graph() {
open_file();
fprintf(file_ptr_, "digraph G {\n");
}
void DotGraph::add_node(Signal* signal,
std::string ws __attribute__((unused))) const {
if (file_ptr_) {
DEBUG_PRINT(fprintf(DEBUG_PRINTS_FILE_PTR, "%sADDING NODE (%s)\n",
ws.c_str(), signal->get_fullname().c_str());)
// Print to dot file
fprintf(file_ptr_, "\t\"%s\" [shape=%s, label=\"%s%s\"];\n",
signal->get_fullname().c_str(), signal->get_dot_shape().c_str(),
signal->get_fullname().c_str(), signal->get_dot_label().c_str());
} else {
fprintf(stderr, "ERROR: dot graph file (%s) not open.\n",
!file_path_.empty() ? file_path_.c_str() : "stdout");
exit(FILE_ERROR);
}
}
void DotGraph::add_connection(Connection* conn,
std::string ws __attribute__((unused))) const {
if (file_ptr_) {
DEBUG_PRINT(fprintf(DEBUG_PRINTS_FILE_PTR,
"%sADDING CONNECTION: %s[%u:%u] --> %s[%u:%u]\n",
ws.c_str(), conn->get_source()->get_fullname().c_str(),
conn->get_source_msb(), conn->get_source_lsb(),
conn->get_sink()->get_fullname().c_str(),
conn->get_sink_msb(), conn->get_sink_lsb());)
// Add connection to .dot file
fprintf(file_ptr_, "\t\"%s\" -> \"%s\"[label=\"%s\"];\n",
conn->get_source()->get_fullname().c_str(),
conn->get_sink()->get_fullname().c_str(),
conn->get_dot_label().c_str());
} else {
fprintf(stderr, "ERROR: dot graph file (%s) not open.\n",
!file_path_.empty() ? file_path_.c_str() : "stdout");
exit(FILE_ERROR);
}
}
// File Operations
void DotGraph::save_graph() {
if (file_ptr_) {
fprintf(file_ptr_, "}\n");
close_file();
}
}
void DotGraph::open_file() {
file_ptr_ = fopen(file_path_.c_str(), "w");
if (!file_ptr_) {
fprintf(stderr, "ERROR: Could not open file %s\n",
!file_path_.empty() ? file_path_.c_str() : "stdout");
exit(FILE_ERROR);
}
}
void DotGraph::close_file() {
fclose(file_ptr_);
file_ptr_ = NULL;
}
| 35.942623 | 79 | 0.651539 | [
"shape"
] |
595380724849861fd186be8e39e0ee0bb1c8fb2e | 2,016 | cpp | C++ | 00138_copy-list-with-random-pointer/200211-1.cpp | yanlinlin82/leetcode | ddcc0b9606d951cff9c08d1f7dfbc202067c8d65 | [
"MIT"
] | 6 | 2019-10-23T01:07:29.000Z | 2021-12-05T01:51:16.000Z | 00138_copy-list-with-random-pointer/200211-1.cpp | yanlinlin82/leetcode | ddcc0b9606d951cff9c08d1f7dfbc202067c8d65 | [
"MIT"
] | null | null | null | 00138_copy-list-with-random-pointer/200211-1.cpp | yanlinlin82/leetcode | ddcc0b9606d951cff9c08d1f7dfbc202067c8d65 | [
"MIT"
] | 1 | 2021-12-03T06:54:57.000Z | 2021-12-03T06:54:57.000Z | // https://leetcode-cn.com/problems/copy-list-with-random-pointer/
#include <cstdio>
#include <vector>
#include <unordered_map>
using namespace std;
class Node {
public:
int val;
Node* next;
Node* random;
Node(int _val) {
val = _val;
next = NULL;
random = NULL;
}
};
class Solution {
public:
Node* copyRandomList(Node* head) {
if (!head) return NULL;
unordered_map<Node*, Node*> m;
Node* t = new Node(head->val);
m[head] = t;
for (Node *p = t, *q = head; q->next; p = p->next, q = q->next) {
p->next = new Node(q->next->val);
m[q->next] = p->next;
}
for (Node *p = t, *q = head; q; p = p->next, q = q->next) {
p->random = q->random ? m[q->random] : NULL;
}
return t;
}
};
void print(Node* t)
{
unordered_map<Node*, int> m;
int c = 0;
for (Node* p = t; p; p = p->next) m[p] = c++;
printf("[");
for (Node* p = t; p; p = p->next) {
printf("[%d,", p->val);
if (p->random) printf("%d", m[p->random]); else printf("null");
printf("]");
}
printf("]\n");
}
void release(Node* t)
{
if (t) {
if (t->next) release(t->next);
delete t;
}
}
int main()
{
Solution s;
{
Node* t0 = new Node(7);
Node* t1 = new Node(13);
Node* t2 = new Node(11);
Node* t3 = new Node(10);
Node* t4 = new Node(1);
t0->next = t1; t1->next = t2; t2->next = t3; t3->next = t4;
t1->random = t0; t2->random = t4; t3->random = t2; t4->random = t0;
print(t0);
Node* p = s.copyRandomList(t0);
print(p);
release(p);
release(t0);
}
{
Node* t0 = new Node(1);
Node* t1 = new Node(2);
t0->next = t1;
t1->random = t1;
print(t0);
Node* p = s.copyRandomList(t0);
print(p);
release(p);
release(t0);
}
{
Node* t0 = new Node(3);
Node* t1 = new Node(3);
Node* t2 = new Node(3);
t0->next = t1; t1->next = t2;
t1->random = t0;
print(t0);
Node* p = s.copyRandomList(t0);
print(p);
release(p);
release(t0);
}
{
Node* t0 = NULL;
print(t0);
Node* p = s.copyRandomList(t0);
print(p);
release(p);
release(t0);
}
return 0;
}
| 18.327273 | 70 | 0.549107 | [
"vector"
] |
5959c197680461986560538dad29f4c670ffc754 | 22,368 | cpp | C++ | DeviceCode/Targets/OS/Toppers/fmp/cfg/toppers/oil/factory.cpp | Sirokujira/MicroFrameworkPK_v4_3 | a0d80b4fd8eeda6dbdb58f6f7beb4f07f7ef563e | [
"Apache-2.0"
] | null | null | null | DeviceCode/Targets/OS/Toppers/fmp/cfg/toppers/oil/factory.cpp | Sirokujira/MicroFrameworkPK_v4_3 | a0d80b4fd8eeda6dbdb58f6f7beb4f07f7ef563e | [
"Apache-2.0"
] | null | null | null | DeviceCode/Targets/OS/Toppers/fmp/cfg/toppers/oil/factory.cpp | Sirokujira/MicroFrameworkPK_v4_3 | a0d80b4fd8eeda6dbdb58f6f7beb4f07f7ef563e | [
"Apache-2.0"
] | 1 | 2019-12-05T18:59:01.000Z | 2019-12-05T18:59:01.000Z | /*
* TOPPERS Software
* Toyohashi Open Platform for Embedded Real-Time Systems
*
* Copyright (C) 2007-2012 by TAKAGI Nobuhisa
* Copyright (C) 2010 by Meika Sugimoto
*
* 上記著作権者は,以下の(1)〜(4)の条件を満たす場合に限り,本ソフトウェ
* ア(本ソフトウェアを改変したものを含む.以下同じ)を使用・複製・改
* 変・再配布(以下,利用と呼ぶ)することを無償で許諾する.
* (1) 本ソフトウェアをソースコードの形で利用する場合には,上記の著作
* 権表示,この利用条件および下記の無保証規定が,そのままの形でソー
* スコード中に含まれていること.
* (2) 本ソフトウェアを,ライブラリ形式など,他のソフトウェア開発に使
* 用できる形で再配布する場合には,再配布に伴うドキュメント(利用
* 者マニュアルなど)に,上記の著作権表示,この利用条件および下記
* の無保証規定を掲載すること.
* (3) 本ソフトウェアを,機器に組み込むなど,他のソフトウェア開発に使
* 用できない形で再配布する場合には,次のいずれかの条件を満たすこ
* と.
* (a) 再配布に伴うドキュメント(利用者マニュアルなど)に,上記の著
* 作権表示,この利用条件および下記の無保証規定を掲載すること.
* (b) 再配布の形態を,別に定める方法によって,TOPPERSプロジェクトに
* 報告すること.
* (4) 本ソフトウェアの利用により直接的または間接的に生じるいかなる損
* 害からも,上記著作権者およびTOPPERSプロジェクトを免責すること.
* また,本ソフトウェアのユーザまたはエンドユーザからのいかなる理
* 由に基づく請求からも,上記著作権者およびTOPPERSプロジェクトを
* 免責すること.
*
* 本ソフトウェアは,無保証で提供されているものである.上記著作権者お
* よびTOPPERSプロジェクトは,本ソフトウェアに関して,特定の使用目的
* に対する適合性も含めて,いかなる保証も行わない.また,本ソフトウェ
* アの利用により直接的または間接的に生じたいかなる損害に関しても,そ
* の責任を負わない.
*
*/
#include <cstring>
#include <cstdlib>
#include <fstream>
#include <boost/lexical_cast.hpp>
#include <boost/spirit/include/classic_spirit.hpp>
#include "toppers/misc.hpp"
#include "toppers/global.hpp"
#include "toppers/csv.hpp"
#include "toppers/nm_symbol.hpp"
#include "toppers/s_record.hpp"
#include "toppers/diagnostics.hpp"
#include "toppers/macro_processor.hpp"
#include "toppers/io.hpp"
#include "toppers/cpp.hpp"
#include "toppers/oil/factory.hpp"
#include "toppers/oil/cfg1_out.hpp"
namespace toppers
{
namespace oil
{
namespace
{
object_definition* find_object(string name , cfg1_out::cfg_obj_map const& obj_def_map)
{
// modified by takuya 110823
//std::map< std::string, std::vector<object_definition*>>::const_iterator p;
std::map< std::string, std::vector<object_definition*> >::const_iterator p;
std::vector<object_definition*>::const_iterator q;
// 名前が一致するオブジェクトを検索
for(p = obj_def_map.begin() ; p != obj_def_map.end() ; p++)
{
for(q = (*p).second.begin() ; q != (*p).second.end() ; q++)
{
if((*q)->get_name() == name)
{
return (*q);
}
}
}
return NULL;
}
// カーネルオブジェクト生成・定義用静的APIの各パラメータをマクロプロセッサの変数として設定する。
void set_object_vars( cfg1_out::cfg_obj_map const& obj_def_map, macro_processor& mproc )
{
typedef macro_processor::element element;
typedef macro_processor::var_t var_t;
std::map< std::string, var_t > order_list_map , obj_parameter;
std::map< std::string, long > id_map;
using namespace toppers::oil::oil_definition;
// modified by takuya 110823
//std::map< std::string, std::vector<object_definition*>>::const_iterator p;
std::map< std::string, std::vector<object_definition*> >::const_iterator p;
std::vector<object_definition*>::const_iterator q;
std::vector<object_parameter_def*>::const_iterator r;
for ( p = obj_def_map.begin() ; p != obj_def_map.end() ; p++)
{
element e;
var_t t;
string name;
long obj_id;
long param_id;
// パラメータの値代入
for(q = (*p).second.begin() ; q != (*p).second.end() ; q++)
{
std::map< std::string, var_t > obj_parameter;
std::map< std::string, var_t >::iterator s;
obj_id = (*q)->get_id();
name = (*p).first;
std::map<std::string , long> id_count;
std::map<std::string , long>::iterator id_iter;
// 値の取り出し
e.i = (*q)->get_id();
e.s = (*q)->get_name();
// 出現順リスト用の情報作成
order_list_map[ name ].push_back(e);
// オブジェクト自身の値代入
mproc.set_var( toppers::toupper(name), obj_id, var_t( 1, e ) );
// オブジェクトメンバの値代入
for(r = (*q)->get_params()->begin() ; r != (*q)->get_params()->end() ; r++)
{
name = (*p).first+ string(".") + (*r)->get_parameter_name();
e.s = (*r)->get_value();
if(e.s == string(""))
{
continue;
}
// メンバのIDを検索
id_iter = id_count.find(name);
if(id_iter == id_count.end())
{
id_count[name] = 0;
param_id = 0;
}
else
{
param_id = (*id_iter).second + 1;
id_count[name] = (*id_iter).second + 1;
}
if((*r)->get_type() == oil::TYPE_UINT)
{
string value_str(((*r)->get_value()));
try
{
e.i = boost::lexical_cast<uint64_t>((*r)->get_value());
}
catch( std::exception& exception)
{
uint64_t temp;
// 16進の場合があるので変換
/// きれいじゃないのでなんとかしたい
if(value_str.find("0x") == 0)
{
// modified by takuya 110823
//sscanf_s(value_str.c_str() , "0x%I64x" , &temp);
sscanf(value_str.c_str() , "0x%llx" , &temp);
e.i = temp;
}
else if(value_str.find("0X") == 0)
{
// modified by takuya 110823
//sscanf_s(value_str.c_str() , "0X%I64x" , &temp);
sscanf(value_str.c_str() , "0X%llx" , &temp);
e.i = temp;
}
else
{
// キャストに失敗したら0にしておく
e.i = 0;
}
}
}
else if((*r)->get_type() == oil::TYPE_INT)
{
string value_str(((*r)->get_value()));
try
{
e.i = boost::lexical_cast<int64_t>(value_str);
}
catch(std::exception& exception)
{
int64_t temp;
// 16進の場合があるので変換
/// きれいじゃないのでなんとかしたい
if(value_str.find("0x") == 0)
{
// modified by takuya 110823
//sscanf_s(value_str.c_str() , "0x%I64x" , &temp);
sscanf(value_str.c_str() , "0x%llx" , &temp);
e.i = temp;
}
else if(value_str.find("0X") == 0)
{
// modified by takuya 110823
//sscanf_s(value_str.c_str() , "0X%I64x" , &temp);
sscanf(value_str.c_str() , "0X%llx" , &temp);
e.i = temp;
}
else
{
// キャストに失敗したら0にしておく
e.i = 0;
}
}
}
else if((*r)->get_type() == oil::TYPE_REF)
{
object_definition *obj;
string refefence_obj_type;
// オブジェクトIDの探索
e.i = 0;
obj = find_object((*r)->get_value() , obj_def_map);
if(obj != NULL)
{
e.i = obj->get_id();
}
}
else
{
e.i = 0;
}
obj_parameter[name].push_back(e);
}
for(s = obj_parameter.begin() ; s != obj_parameter.end() ; s++)
{
mproc.set_var((*s).first , obj_id , (*s).second );
}
}
}
// 順序リストの作成
for ( std::map< std::string, var_t >::const_iterator iter( order_list_map.begin() ), last( order_list_map.end() );
iter != last;
++iter )
{
// 出現順リスト $OBJ.ORDER_LIST$ -- ID番号の並び
mproc.set_var( toppers::toupper( iter->first + ".order_list" ), iter->second );
var_t rorder_list( iter->second );
// 逆順リスト $OBJ.RORDER_LIST$ -- ID番号の並び
std::reverse( rorder_list.begin(), rorder_list.end() );
mproc.set_var( toppers::toupper( iter->first + ".rorder_list" ), rorder_list );
// ID番号リスト $OBJ.ID_LIST$ -- ID番号の並び
var_t id_list( iter->second );
std::sort( id_list.begin(), id_list.end() );
mproc.set_var( toppers::toupper( iter->first + ".id_list" ), id_list );
}
}
// カーネルオブジェクト生成・定義用静的APIの各パラメータをマクロプロセッサの変数として設定する。
void set_object_vars( std::vector< object_definition* > const& obj_array, macro_processor& mproc )
{
typedef macro_processor::element element;
typedef macro_processor::var_t var_t;
long order = 1;
var_t order_list;
for ( std::vector< object_definition* >::const_iterator v_iter( obj_array.begin() ), v_last( obj_array.end() );
v_iter != v_last;
++v_iter )
{
var_t params;
var_t args;
#if 0
// 静的APIが出現した行番号
element e;
// e.s = v_iter->line().file;
// e.i = v_iter->line().line;
// mproc.set_var( "API.TEXT_LINE", order, var_t( 1, e ) );
// 静的API名
e.s = v_iter->get_name();
e.i = boost::none;
mproc.set_var( "OBJ.NAME", order, var_t( 1, e ) );
// オブジェクトタイプ("TSK", "SEM", ...)
e.s = toppers::toupper( v_iter->object_type );
mproc.set_var( "OBJ.TYPE", order, var_t( 1 , e ) );
// 各パラメータ
for ( static_api::const_iterator api_iter( v_iter->begin() ), api_last( v_iter->end() );
api_iter != api_last;
++api_iter )
{
std::string name( toppers::toupper( ( boost::format( "%s.%s" ) % info->type % ( api_iter->symbol.c_str() + 1 ) ).str() ) );
// 末尾の ? を除去
if ( *name.rbegin() == '\?' )
{
name.resize( name.size() - 1 );
}
// 末尾の ... を除去 & order を付加
if ( name.size() > 3 && name.substr( name.size() - 3 ) == "..." )
{
name.resize( name.size() - 3 );
name += boost::lexical_cast< std::string >( api_iter->order );
}
element e;
e.s = api_iter->text; // ソースの字面
if ( api_iter->symbol[0] != '&' ) // 一般定数式パラメータは値が特定できない
{
if ( api_iter->symbol[0] == '$' ) // 文字列定数式パラメータ
{
e.v = api_iter->string; // 展開後の文字列
}
else
{
e.i = api_iter->value;
}
}
args.push_back( e );
e.s = name;
e.i = boost::none;
params.push_back( e );
if ( api_iter->symbol[0] == '%' )
{
continue;
}
}
mproc.set_var( "API.ARGS", order, args );
mproc.set_var( "API.PARAMS", order, params );
e.s.clear();
e.i = order;
order_list.push_back( e );
#endif
++order;
}
mproc.set_var( "API.ORDER_LIST", order_list );
element external_id;
external_id.i = get_global_bool( "external-id" );
mproc.set_var( "USE_EXTERNAL_ID", var_t( 1, external_id ) );
}
// プラットフォーム・コンパイラ依存の値をマクロプロセッサの変数として設定する。
void set_platform_vars( cfg1_out const& cfg1out, macro_processor& mproc )
{
typedef macro_processor::element element;
typedef macro_processor::var_t var_t;
cfg1_out::cfg1_def_table const* def_table = cfg1out.get_def_table();
std::size_t sizeof_signed_t;
std::size_t sizeof_pointer;
static cfg1_out::cfg1_def_t const limit_defs[] =
{
{ false, "TOPPERS_cfg_CHAR_BIT", "CHAR_BIT" },
{ false, "TOPPERS_cfg_CHAR_MAX", "CHAR_MAX" },
{ true, "TOPPERS_cfg_CHAR_MIN", "CHAR_MIN" },
{ false, "TOPPERS_cfg_SCHAR_MAX", "SCHAR_MAX" }, // 本来は符号付きだが、負になることはない
{ false, "TOPPERS_cfg_SHRT_MAX", "SHRT_MAX" }, // 本来は符号付きだが、負になることはない
{ false, "TOPPERS_cfg_INT_MAX", "INT_MAX" }, // 本来は符号付きだが、負になることはない
{ false, "TOPPERS_cfg_LONG_MAX", "LONG_MAX" }, // 本来は符号付きだが、負になることはない
};
nm_symbol::entry nm_entry = cfg1out.get_syms()->find( "TOPPERS_cfg_sizeof_signed_t" );
sizeof_signed_t = static_cast< std::size_t >( cfg1out.get_srec()->get_value( nm_entry.address, 4, cfg1out.is_little_endian() ) );
nm_entry = cfg1out.get_syms()->find( "TOPPERS_cfg_sizeof_pointer" );
sizeof_pointer = static_cast< std::size_t >( cfg1out.get_srec()->get_value( nm_entry.address, 4, cfg1out.is_little_endian() ) );
for ( std::size_t i = 0; i < sizeof limit_defs / sizeof limit_defs[ 0 ]; ++i )
{
element e;
e.s = limit_defs[ i ].expression;
nm_entry = cfg1out.get_syms()->find( limit_defs[ i ].name );
std::tr1::int64_t value = cfg1out.get_srec()->get_value( nm_entry.address, sizeof_signed_t, cfg1out.is_little_endian() );
if ( sizeof_signed_t < 8 && limit_defs[ i ].is_signed )
{
value = cfg1_out::make_signed( static_cast< std::tr1::uint32_t >( value ) );
}
mproc.set_var( e.s, var_t( 1, e ) );
}
for ( cfg1_out::cfg1_def_table::const_iterator iter( def_table->begin() ), last( def_table->end() );
iter != last;
++iter )
{
element e;
std::tr1::int64_t value;
nm_entry = cfg1out.get_syms()->find( "TOPPERS_cfg_" + iter->name );
if ( nm_entry.type >= 0 )
{
if ( !iter->expression.empty() && iter->expression[ 0 ] == '@' ) // 式が'@'で始まる場合はアドレス定数式
{
value = cfg1out.get_srec()->get_value( nm_entry.address, sizeof_pointer, cfg1out.is_little_endian() );
if ( sizeof_signed_t < 8 && iter->is_signed )
{
value = cfg1_out::make_signed( static_cast< std::tr1::uint32_t >( value ) );
}
// 先ほど取り出したアドレスを使って間接参照
value = cfg1out.get_srec()->get_value( value, 8, cfg1out.is_little_endian() ); // 取り出す値は型に関係なく常に8バイト
if ( sizeof_signed_t < 8 && iter->is_signed )
{
value = cfg1_out::make_signed( static_cast< std::tr1::uint32_t >( value ) );
}
e.s = iter->expression.c_str() + 1; // 先頭の'@'を除去
}
else // アドレスではない通常の整数定数式
{
value = cfg1out.get_srec()->get_value( nm_entry.address, sizeof_signed_t, cfg1out.is_little_endian() );
if ( sizeof_signed_t < 8 && iter->is_signed )
{
value = cfg1_out::make_signed( static_cast< std::tr1::uint32_t >( value ) );
}
e.s = iter->expression;
}
e.i = value;
mproc.set_var( iter->name, var_t( 1, e ) );
}
}
// バイトオーダー
{
bool little_endian = cfg1out.is_little_endian();
element e;
e.i = little_endian;
mproc.set_var( "LITTLE_ENDIAN", var_t( 1, e ) );
e.i = !little_endian;
mproc.set_var( "BIG_ENDIAN", var_t( 1, e ) );
}
}
}
//! コンストラクタ
factory::factory( std::string const& kernel )
: kernel_( tolower( kernel ) )
{
}
//! デストラクタ
factory::~factory()
{
}
//! サポートしているオブジェクト情報の取得
std::vector<std::string> const* factory::get_object_definition_info() const
{
// CSVから静的API情報を読み取り、登録するためのローカルクラス
struct init_t
{
init_t()
{
boost::any t = global( "api-table" );
if ( !t.empty() )
{
std::vector< std::string > api_tables( boost::any_cast< std::vector< std::string >& >( t ) );
for ( std::vector< std::string >::const_iterator iter( api_tables.begin() ), last( api_tables.end() );
iter != last;
++iter )
{
std::string buf;
std::string api_table_filename = *iter;
read( api_table_filename.c_str(), buf );
csv data( buf.begin(), buf.end() );
for ( csv::const_iterator d_iter( data.begin() ), d_last( data.end() );
d_iter != d_last;
++d_iter )
{
unsigned int i;
for(i = 0 ; i < d_iter->size() ; i++)
{
volatile int x = 1;
object_definition_table.push_back((*d_iter)[i].c_str());
}
}
}
}
}
~init_t()
{
}
std::vector<std::string> object_definition_table;
};
static init_t init;
std::vector<std::string> const* result = &init.object_definition_table;
return result;
}
/*!
* \brief cfg1_out.c への出力情報テーブルの生成
* \return 生成した cfg1_out::cfg1_def_table オブジェクトへのポインタ
* \note この関数が返すポインタは delete してはならない
*
* --cfg1-def-table オプションで指定したファイルから、cfg1_out.c へ出力する情報を読み取り、
* cfg1_out::cfg1_def_table オブジェクトを生成する。
*
* CSV の形式は以下の通り
*
* シンボル名,式[,s|signed]
*
* 末尾の s または signed は省略可能。省略時は符号無し整数とみなす。s または signed 指定時は
* 符号付き整数とみなす。\n
* 「式」の最初に # があれば前処理式とみなす。
*/
cfg1_out::cfg1_def_table const* factory::get_cfg1_def_table() const
{
struct init_t
{
init_t()
{
boost::any t = global( "cfg1-def-table" );
if ( !t.empty() )
{
std::vector< std::string > cfg1_def_table = boost::any_cast< std::vector< std::string >& >( t );
for ( std::vector< std::string >::const_iterator iter( cfg1_def_table.begin() ), last( cfg1_def_table.end() );
iter != last;
++iter )
{
std::string buf;
read( iter->c_str(), buf );
csv data( buf.begin(), buf.end() );
for ( csv::const_iterator d_iter( data.begin() ), d_last( data.end() );
d_iter != d_last;
++d_iter )
{
csv::size_type len = d_iter->size();
if ( len < 2 )
{
toppers::fatal( _( "too little fields in `%1%\'" ), *iter );
}
cfg1_out::cfg1_def_t def = { 0 };
def.name = ( *d_iter )[ 0 ];
def.expression = ( *d_iter )[ 1 ];
if ( len >= 3 )
{
std::string is_signed( ( *d_iter )[ 2 ] );
def.is_signed = ( is_signed == "s" || is_signed == "signed" );
}
if ( len >= 4)
{
def.value1 = ( *d_iter )[ 3 ];
}
if ( len >= 5)
{
def.value2 = ( *d_iter )[ 4 ];
}
cfg1_def_table_.push_back( def );
}
}
}
}
cfg1_out::cfg1_def_table cfg1_def_table_;
};
static init_t init;
cfg1_out::cfg1_def_table const* result = &init.cfg1_def_table_;
return result;
}
//! オブジェクトの交換
void factory::do_swap( factory& other )
{
kernel_.swap( other.kernel_ );
}
/*!
* \brief マクロプロセッサの生成
* \param[in] cfg1out cfg1_out オブジェクト
* \param[in] api_map .cfg ファイルに記述された静的API情報
* \return マクロプロセッサへのポインタ
*/
std::auto_ptr< macro_processor > factory::do_create_macro_processor( cfg1_out const& cfg1out, cfg1_out::cfg_obj_map const& obj_def_map ) const
{
typedef macro_processor::element element;
typedef macro_processor::var_t var_t;
std::auto_ptr< macro_processor > mproc( new macro_processor );
element e;
e.s = " "; mproc->set_var( "SPC", var_t( 1, e ) ); // $SPC$
e.s = "\t"; mproc->set_var( "TAB", var_t( 1, e ) ); // $TAB$
e.s = "\n"; mproc->set_var( "NL", var_t( 1, e ) ); // $NL$
// バージョン情報
e.s = toppers::get_global_string( "version" );
e.i = toppers::get_global< std::tr1::int64_t >( "timestamp" );
mproc->set_var( "CFG_VERSION", var_t( 1, e ) ); // $CFG_VERSION$
// その他の組み込み変数の設定
set_object_vars( obj_def_map, *mproc );
set_platform_vars( cfg1out, *mproc );
e.s = cfg1out.get_includes();
mproc->set_var( "INCLUDES", var_t( 1, e ) );
// パス情報
e.s = boost::lexical_cast< std::string >( toppers::get_global< int >( "pass" ) );
e.i = toppers::get_global< int >( "pass" );
mproc->set_var( "CFG_PASS", var_t( 1, e ) );
return mproc;
}
/*!
* \brief マクロプロセッサの生成
* \param[in] cfg1out cfg1_out オブジェクト
* \param[in] api_array .cfg ファイルに記述された静的API情報
* \return マクロプロセッサへのポインタ
*/
std::auto_ptr< macro_processor > factory::do_create_macro_processor( cfg1_out const& cfg1out, std::vector< object_definition* > const& obj_array ) const
{
typedef macro_processor::element element;
typedef macro_processor::var_t var_t;
std::auto_ptr< macro_processor > mproc( new macro_processor );
element e;
e.s = " "; mproc->set_var( "SPC", var_t( 1, e ) ); // $SPC$
e.s = "\t"; mproc->set_var( "TAB", var_t( 1, e ) ); // $TAB$
e.s = "\n"; mproc->set_var( "NL", var_t( 1, e ) ); // $NL$
// バージョン情報
e.s = toppers::get_global_string( "version" );
e.i = toppers::get_global< std::tr1::int64_t >( "timestamp" );
mproc->set_var( "CFG_VERSION", var_t( 1, e ) ); // $CFG_VERSION$
// その他の組み込み変数の設定
set_object_vars( obj_array, *mproc );
set_platform_vars( cfg1out, *mproc );
e.s = cfg1out.get_includes();
mproc->set_var( "INCLUDES", var_t( 1, e ) );
// パス情報
e.s = boost::lexical_cast< std::string >( toppers::get_global< int >( "pass" ));
e.i = toppers::get_global< int >( "pass" );
mproc->set_var( "CFG_PASS", var_t( 1, e ) );
return mproc;
}
std::auto_ptr< cfg1_out > factory::do_create_cfg1_out( std::string const& filename ) const
{
return std::auto_ptr< oil::cfg1_out >( new cfg1_out( filename, get_cfg1_def_table() ) );
}
std::auto_ptr< checker > factory::do_create_checker() const
{
return std::auto_ptr< oil::checker >( new checker );
}
}
}
| 33.737557 | 156 | 0.511221 | [
"vector"
] |
595a6733a67a99b589b1d1c08f000442fab2897d | 5,569 | cc | C++ | diagnostics/cros_healthd/fetchers/storage/device_manager_test.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | diagnostics/cros_healthd/fetchers/storage/device_manager_test.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | diagnostics/cros_healthd/fetchers/storage/device_manager_test.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2020 The Chromium OS 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 "diagnostics/cros_healthd/fetchers/storage/device_manager.h"
#include <cstdint>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <base/files/file_path.h>
#include <brillo/udev/mock_udev.h>
#include <brillo/udev/mock_udev_device.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "diagnostics/cros_healthd/fetchers/storage/mock/mock_device_lister.h"
#include "diagnostics/cros_healthd/fetchers/storage/mock/mock_device_resolver.h"
#include "diagnostics/cros_healthd/fetchers/storage/mock/mock_platform.h"
#include "diagnostics/mojom/public/cros_healthd_probe.mojom.h"
namespace diagnostics {
namespace {
namespace mojo_ipc = ::chromeos::cros_healthd::mojom;
using testing::_;
using testing::ByMove;
using testing::DoAll;
using testing::Return;
using testing::SetArgPointee;
using testing::StrictMock;
using testing::UnorderedElementsAre;
// Tests that the StorageDeviceInfo structures are correctly populated and
// preserved between fetch calls.
TEST(StorageDeviceManagerTest, NoRecreation) {
const base::FilePath kFakeRoot("cros_healthd/fetchers/storage/testdata/");
const base::FilePath kNvme = kFakeRoot.Append("sys/block/nvme0n1");
const base::FilePath kEmmc = kFakeRoot.Append("sys/block/mmcblk0");
const base::FilePath kNvmeDev = kFakeRoot.Append("dev/nvme0n1");
const base::FilePath kEmmcDev = kFakeRoot.Append("dev/mmcblk0");
const std::string kBlockClass = "block";
const std::string kNvmeClass = "nvme";
const std::string kEmmcClass = "mmc";
constexpr mojo_ipc::StorageDevicePurpose kNvmePurpose =
mojo_ipc::StorageDevicePurpose::kSwapDevice;
constexpr mojo_ipc::StorageDevicePurpose kEmmcPurpose =
mojo_ipc::StorageDevicePurpose::kBootDevice;
const uint64_t kNvmeSize = 1024;
const uint64_t kEmmcSize = 768;
const uint64_t kBlockSize = 512;
std::vector<std::string> listed = {"mmcblk0", "nvme0n1"};
auto mock_platform = std::make_unique<StrictMock<MockPlatform>>();
// TODO(dlunev) querying size shall be cached as well and allow WillOnce.
EXPECT_CALL(*mock_platform, GetDeviceSizeBytes(kNvmeDev))
.WillRepeatedly(Return(kNvmeSize));
EXPECT_CALL(*mock_platform, GetDeviceBlockSizeBytes(kNvmeDev))
.WillRepeatedly(Return(kBlockSize));
EXPECT_CALL(*mock_platform, GetDeviceSizeBytes(kEmmcDev))
.WillRepeatedly(Return(kEmmcSize));
EXPECT_CALL(*mock_platform, GetDeviceBlockSizeBytes(kEmmcDev))
.WillRepeatedly(Return(kBlockSize));
auto mock_nvme_udev = std::make_unique<StrictMock<brillo::MockUdevDevice>>();
auto mock_nvme_parent_udev =
std::make_unique<StrictMock<brillo::MockUdevDevice>>();
EXPECT_CALL(*mock_nvme_udev, GetDeviceNode())
.Times(1)
.WillOnce(Return(kNvmeDev.value().c_str()));
EXPECT_CALL(*mock_nvme_udev, GetSubsystem())
.Times(1)
.WillOnce(Return(kBlockClass.c_str()));
EXPECT_CALL(*mock_nvme_parent_udev, GetSubsystem())
.Times(1)
.WillOnce(Return(kNvmeClass.c_str()));
EXPECT_CALL(*mock_nvme_parent_udev, GetParent())
.Times(1)
.WillOnce(Return(ByMove(nullptr)));
EXPECT_CALL(*mock_nvme_udev, GetParent())
.Times(1)
.WillOnce(Return(ByMove(std::move(mock_nvme_parent_udev))));
auto mock_emmc_udev = std::make_unique<StrictMock<brillo::MockUdevDevice>>();
auto mock_emmc_parent_udev =
std::make_unique<StrictMock<brillo::MockUdevDevice>>();
EXPECT_CALL(*mock_emmc_udev, GetDeviceNode())
.Times(1)
.WillOnce(Return(kEmmcDev.value().c_str()));
EXPECT_CALL(*mock_emmc_udev, GetSubsystem())
.Times(1)
.WillOnce(Return(kBlockClass.c_str()));
EXPECT_CALL(*mock_emmc_parent_udev, GetSubsystem())
.Times(1)
.WillOnce(Return(kEmmcClass.c_str()));
EXPECT_CALL(*mock_emmc_parent_udev, GetParent())
.Times(1)
.WillOnce(Return(ByMove(nullptr)));
EXPECT_CALL(*mock_emmc_udev, GetParent())
.Times(1)
.WillOnce(Return(ByMove(std::move(mock_emmc_parent_udev))));
auto mock_udev = std::make_unique<StrictMock<brillo::MockUdev>>();
EXPECT_CALL(*mock_udev, CreateDeviceFromSysPath(_))
.Times(2)
.WillOnce(Return(ByMove(std::move(mock_emmc_udev))))
.WillOnce(Return(ByMove(std::move(mock_nvme_udev))));
auto mock_resolver =
std::make_unique<StrictMock<MockStorageDeviceResolver>>();
EXPECT_CALL(*mock_resolver, GetDevicePurpose(_))
.WillOnce(Return(kNvmePurpose))
.WillOnce(Return(kEmmcPurpose));
auto mock_lister = std::make_unique<StrictMock<MockStorageDeviceLister>>();
EXPECT_CALL(*mock_lister, ListDevices(base::FilePath(kFakeRoot)))
.WillRepeatedly(Return(listed));
StorageDeviceManager manager(std::move(mock_lister), std::move(mock_resolver),
std::move(mock_udev), std::move(mock_platform));
// Do multiple cycles. If the device info preservation is not working,
// the WillOnce of udev mock will fail.
for (int i = 0; i < 5; i++) {
auto result_or = manager.FetchDevicesInfo(kFakeRoot);
ASSERT_TRUE(result_or.ok()) << result_or.status().message();
auto& result = result_or.value();
std::vector<std::string> result_devs;
for (const auto& info_ptr : result) {
result_devs.push_back(info_ptr->path);
}
EXPECT_THAT(result_devs,
UnorderedElementsAre(kNvmeDev.value(), kEmmcDev.value()));
}
}
} // namespace
} // namespace diagnostics
| 38.406897 | 80 | 0.73155 | [
"vector"
] |
5967bcfd25742bad4a231299608e256ec9245ef1 | 7,328 | cpp | C++ | project7/osm.cpp | JSneak/UIC-Pathfinder | 68d492ec7bef87a604027f1497534333fa68421b | [
"MIT"
] | null | null | null | project7/osm.cpp | JSneak/UIC-Pathfinder | 68d492ec7bef87a604027f1497534333fa68421b | [
"MIT"
] | null | null | null | project7/osm.cpp | JSneak/UIC-Pathfinder | 68d492ec7bef87a604027f1497534333fa68421b | [
"MIT"
] | null | null | null | /*osm.cpp*/
//
// Prof. Joe Hummel
// U. of Illinois, Chicago
// CS 251: Spring 2020
// Project #07: open street maps, graphs, and Dijkstra's alg
//
// References:
// TinyXML: https://github.com/leethomason/tinyxml2
// OpenStreetMap: https://www.openstreetmap.org
// OpenStreetMap docs:
// https://wiki.openstreetmap.org/wiki/Main_Page
// https://wiki.openstreetmap.org/wiki/Map_Features
// https://wiki.openstreetmap.org/wiki/Node
// https://wiki.openstreetmap.org/wiki/Way
// https://wiki.openstreetmap.org/wiki/Relation
//
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <cstdlib>
#include <cstring>
#include <cassert>
#include "tinyxml2.h"
#include "osm.h"
using namespace std;
using namespace tinyxml2;
//
// LoadOpenStreetMap
//
bool LoadOpenStreetMap(string filename, XMLDocument& xmldoc)
{
//
// load the XML document:
//
xmldoc.LoadFile(filename.c_str());
if (xmldoc.ErrorID() != 0) // failed:
{
cout << "**ERROR: unable to open map file '" << filename << "'." << endl;
return false;
}
//
// top-level element should be "osm" if the file is a valid open
// street map:
//
XMLElement* osm = xmldoc.FirstChildElement("osm");
if (osm == nullptr)
{
cout << "**ERROR: unable to find top-level 'osm' XML element." << endl;
return false;
}
//
// success:
//
return true;
}
//
// ReadMapNodes
//
int ReadMapNodes(XMLDocument& xmldoc, map<long long, Coordinates>& Nodes)
{
XMLElement* osm = xmldoc.FirstChildElement("osm");
assert(osm != nullptr);
//
// Parse the XML document node by node:
//
int nodeCount = 0;
XMLElement* node = osm->FirstChildElement("node");
while (node != nullptr)
{
const XMLAttribute* attrId = node->FindAttribute("id");
const XMLAttribute* attrLat = node->FindAttribute("lat");
const XMLAttribute* attrLon = node->FindAttribute("lon");
assert(attrId != nullptr);
assert(attrLat != nullptr);
assert(attrLon != nullptr);
long long id = attrId->Int64Value();
double latitude = attrLat->DoubleValue();
double longitude = attrLon->DoubleValue();
nodeCount++;
//
// store node in the map:
//
Nodes[id] = Coordinates(id, latitude, longitude);
//
// next node element in the XML doc:
//
node = node->NextSiblingElement("node");
}
//
// done:
//
return nodeCount;
}
//
// ReadFootways
//
int ReadFootways(XMLDocument& xmldoc, vector<FootwayInfo>& Footways)
{
XMLElement* osm = xmldoc.FirstChildElement("osm");
assert(osm != nullptr);
//
// Parse the XML document way by way, looking for footways:
//
int footwayCount = 0;
XMLElement* way = osm->FirstChildElement("way");
while (way != nullptr)
{
const XMLAttribute* attr = way->FindAttribute("id");
assert(attr != nullptr);
long long id = attr->Int64Value();
//
// we have to loop through all the tag attributes and
// see if this is a footway:
//
bool isFootway = false;
XMLElement* tag = way->FirstChildElement("tag");
while (tag != nullptr)
{
const XMLAttribute* attrk = tag->FindAttribute("k");
const XMLAttribute* attrv = tag->FindAttribute("v");
if (attrk != nullptr && attrv != nullptr)
{
const char* k_value = attrk->Value();
const char* v_value = attrv->Value();
if ((strcmp(k_value, "highway") == 0) && (strcmp(v_value, "footway") == 0))
{
footwayCount++;
isFootway = true;
break;
}
}
tag = tag->NextSiblingElement("tag");
}
//
// if this is a footway, collect the node ids and store another
// footway object in the vector:
//
if (isFootway)
{
FootwayInfo footway(id);
XMLElement* nd = way->FirstChildElement("nd");
while (nd != nullptr)
{
const XMLAttribute* ndref = nd->FindAttribute("ref");
assert(ndref != nullptr);
long long id = ndref->Int64Value();
footway.Nodes.push_back(id);
// advance to next node ref:
nd = nd->NextSiblingElement("nd");
}
Footways.push_back(footway);
}//if
way = way->NextSiblingElement("way");
}//while
//
// done:
//
return footwayCount;
}
//
// ReadUniversityBuildings
//
int ReadUniversityBuildings(XMLDocument& xmldoc,
map<long long, Coordinates>& Nodes,
vector<BuildingInfo>& Buildings)
{
XMLElement* osm = xmldoc.FirstChildElement("osm");
assert(osm != nullptr);
//
// Parse the XML document way by way, looking for university buildings:
//
int buildingCount = 0;
XMLElement* way = osm->FirstChildElement("way");
while (way != nullptr)
{
const XMLAttribute* attr = way->FindAttribute("id");
assert(attr != nullptr);
long long id = attr->Int64Value();
bool isBuilding = false;
const char* buildingName = nullptr;
XMLElement* tag = way->FirstChildElement("tag");
while (tag != nullptr)
{
const XMLAttribute* attrk = tag->FindAttribute("k");
const XMLAttribute* attrv = tag->FindAttribute("v");
if (attrk != nullptr && attrv != nullptr)
{
const char* k_value = attrk->Value();
const char* v_value = attrv->Value();
if ((strcmp(k_value, "building") == 0) && (strcmp(v_value, "university") == 0))
{
buildingCount++;
isBuilding = true;
}
if (strcmp(k_value, "name") == 0)
{
buildingName = v_value;
}
}
tag = tag->NextSiblingElement("tag");
}
//
// if this is a building, store info into vector:
//
if (isBuilding)
{
XMLElement* nd = way->FirstChildElement("nd");
//
// we need to compute a (lat, lon) for the building, so we compute
// the average based on the nodes that define the perimiter to the
// building. We would be better if the XML defined the position
// of the door(s)?
//
double totalLat = 0.0;
double totalLon = 0.0;
int numNodes = 0;
while (nd != nullptr)
{
const XMLAttribute* ndref = nd->FindAttribute("ref");
assert(ndref != nullptr);
long long id = ndref->Int64Value();
assert(Nodes.find(id) != Nodes.end());
totalLat += Nodes[id].Lat;
totalLon += Nodes[id].Lon;
numNodes++;
// advance to next node ref:
nd = nd->NextSiblingElement("nd");
}//while
//
// compute average to get a rough position of building, and store
// building info into vector:
//
double lat = totalLat / numNodes;
double lon = totalLon / numNodes;
assert(buildingName != nullptr);
string fullname(buildingName);
//
// do we have an abbreviation? Appears as "... (SEO)" in the string:
//
string abbrev = "?";
size_t left = fullname.find('(');
size_t right = fullname.find(')');
if (left != string::npos && right != string::npos && left < right)
{
abbrev = fullname.substr(left + 1, right - left - 1);
}
Buildings.push_back(BuildingInfo(fullname, abbrev, id, lat, lon));
}//if
way = way->NextSiblingElement("way");
}//while
//
// done:
//
return buildingCount;
}
| 22.341463 | 87 | 0.595524 | [
"object",
"vector"
] |
5977b74e39da4984a648d51dafc26a0b41b64e1d | 2,875 | hpp | C++ | Libraries/Utility/GEK/Utility/Context.hpp | xycsoscyx/gekengine | cb9c933c6646169c0af9c7e49be444ff6f97835d | [
"MIT"
] | 1 | 2019-04-22T00:10:49.000Z | 2019-04-22T00:10:49.000Z | Libraries/Utility/GEK/Utility/Context.hpp | xycsoscyx/gekengine | cb9c933c6646169c0af9c7e49be444ff6f97835d | [
"MIT"
] | null | null | null | Libraries/Utility/GEK/Utility/Context.hpp | xycsoscyx/gekengine | cb9c933c6646169c0af9c7e49be444ff6f97835d | [
"MIT"
] | 2 | 2017-10-16T15:40:55.000Z | 2019-04-22T00:10:50.000Z | /// @file
/// @author Todd Zupan <toddzupan@gmail.com>
/// @version $Revision$
/// @section LICENSE
/// https://en.wikipedia.org/wiki/MIT_License
/// @section DESCRIPTION
/// Last Changed: $Date$
#pragma once
#include "GEK/Utility/String.hpp"
#include "GEK/Utility/FileSystem.hpp"
#include "GEK/Utility/Profiler.hpp"
#include "GEK/Utility/Hash.hpp"
#include <functional>
#include <typeindex>
#include <iostream>
#include <memory>
#include <vector>
#define GEK_PREDECLARE(TYPE) struct TYPE; using TYPE##Ptr = std::unique_ptr<TYPE>;
#define GEK_INTERFACE(TYPE) struct TYPE; using TYPE##Ptr = std::unique_ptr<TYPE>; struct TYPE
namespace Gek
{
GEK_PREDECLARE(ContextUser);
GEK_INTERFACE(Context)
{
static ContextPtr Create(std::vector<FileSystem::Path> const &pluginSearchList);
virtual ~Context(void) = default;
virtual void startProfiler(std::string_view output) = 0;
virtual void stopProfiler(void) = 0;
virtual Profiler * const getProfiler(void) const = 0;
virtual void synchronizeClock(Hash processIdentifier, Hash threadIdentifier, Profiler::TimeFormat time) = 0;
virtual void setCachePath(FileSystem::Path const &path) = 0;
virtual FileSystem::Path getCachePath(FileSystem::Path const &path) = 0;
virtual void addDataPath(FileSystem::Path const &path) = 0;
virtual FileSystem::Path findDataPath(FileSystem::Path const &path, bool includeCache = true) const = 0;
virtual void findDataFiles(FileSystem::Path const &path, std::function<bool(FileSystem::Path const &filePath)> onFileFound, bool includeCache = true) const = 0;
virtual ContextUserPtr createBaseClass(std::string_view className, void *typelessArguments, std::vector<Hash> &argumentTypes) const = 0;
template <typename TYPE, typename... PARAMETERS>
std::unique_ptr<TYPE> createClass(std::string_view className, PARAMETERS... arguments) const
{
std::tuple<PARAMETERS...> packedArguments(arguments...);
std::vector<Hash> argumentTypes = { typeid(PARAMETERS).hash_code()... };
ContextUserPtr baseClass = createBaseClass(className, static_cast<void *>(&packedArguments), argumentTypes);
if (!baseClass)
{
return nullptr;
}
auto derivedClass = dynamic_cast<TYPE *>(baseClass.get());
if (!derivedClass)
{
LockedWrite{ std::cerr } << "Unable to cast " << className << " from base context user to requested class of " << typeid(TYPE).name();
return nullptr;
}
std::unique_ptr<TYPE> result(derivedClass);
baseClass.release();
return result;
}
virtual void listTypes(std::string_view typeName, std::function<void(std::string_view )> onType) const = 0;
};
}; // namespace Gek
| 38.851351 | 162 | 0.668174 | [
"vector"
] |
597e0eef8ffe5e415a7bded8e37c9296d8e9532d | 4,540 | cpp | C++ | src/Libs/CodecUtils/FastMotionVectorVlcDecoderImpl1.cpp | miseri/rtp_plus_plus | 244ddd86f40f15247dd39ae7f9283114c2ef03a2 | [
"BSD-3-Clause"
] | 1 | 2021-07-14T08:15:05.000Z | 2021-07-14T08:15:05.000Z | src/Libs/CodecUtils/FastMotionVectorVlcDecoderImpl1.cpp | 7956968/rtp_plus_plus | 244ddd86f40f15247dd39ae7f9283114c2ef03a2 | [
"BSD-3-Clause"
] | null | null | null | src/Libs/CodecUtils/FastMotionVectorVlcDecoderImpl1.cpp | 7956968/rtp_plus_plus | 244ddd86f40f15247dd39ae7f9283114c2ef03a2 | [
"BSD-3-Clause"
] | 2 | 2021-07-14T08:15:02.000Z | 2021-07-14T08:56:10.000Z | /** @file
MODULE : FastMotionVectorVlcDecoderImpl1
TAG : FMVVDI1
FILE NAME : FastMotionVectorVlcDecoderImpl1.cpp
DESCRIPTION : A fast motion vector Vlc decoder implementation with an
IVlcDecoder Interface and derived from MotionVlcDecoder.
REVISION HISTORY :
:
COPYRIGHT :
RESTRICTIONS :
===========================================================================
*/
#ifdef _WINDOWS
#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers
#include <windows.h>
#else
#include <stdio.h>
#endif
#include "FastMotionVectorVlcDecoderImpl1.h"
#define FMVVDI1_TREE_SIZE 133
FastMotionVectorVlcDecoderImpl1::FastMotionVectorVlcDecoderImpl1() : MotionVectorVlcDecoder()
{
_onesTree = NULL;
_zeroTree = NULL;
_indexTree = NULL;
Create();
}//end constructor.
FastMotionVectorVlcDecoderImpl1::~FastMotionVectorVlcDecoderImpl1()
{
Destroy();
}//end destructor.
int FastMotionVectorVlcDecoderImpl1::Create(void)
{
int i,j;
int tableLen = MVVD_TABLE_SIZE;
// Alloc mem for the fast huffman decode binary tree.
// Note: Only deleted in Destroy().
_onesTree = new int[FMVVDI1_TREE_SIZE];
_zeroTree = new int[FMVVDI1_TREE_SIZE];
_indexTree = new int[FMVVDI1_TREE_SIZE];
if(!_onesTree || !_zeroTree || !_indexTree)
return(0);
for(i = 0; i < FMVVDI1_TREE_SIZE; i++)
{
_onesTree[i] = -1;
_zeroTree[i] = -1;
_indexTree[i] = -1;
}//end for i...
// Loop through all of the run codes
int treeNextIndex = 1;
for (i = 0; i < tableLen; ++i)
{
// Get the code and depth (number of bits) for the current Huffman code
int code = VLC_TABLE[i][MVVD_BIT_CODE];
int depth = VLC_TABLE[i][MVVD_NUM_BITS];
// Create the path to the current code
int cIndex = 0;
for(j = 0; j < depth; j++)
{
// Get the next bit
int bit = code & (1 << j);
// Branch and allocate new tree member if necessary
if(bit) // bit 1
{
if (_onesTree[cIndex] == -1)
_onesTree[cIndex] = treeNextIndex++;
cIndex = _onesTree[cIndex];
}//end if bit...
else // bit 0
{
if (_zeroTree[cIndex] == -1)
_zeroTree[cIndex] = treeNextIndex++;
cIndex = _zeroTree[cIndex];
}//end else...
if (j == depth-1)
_indexTree[cIndex] = i;
}//end for j...
}//end for i...
return(1);
}//end Create.
void FastMotionVectorVlcDecoderImpl1::Destroy(void)
{
if(_onesTree != NULL)
delete[] _onesTree;
_onesTree = NULL;
if(_zeroTree != NULL)
delete[] _zeroTree;
_zeroTree = NULL;
if(_indexTree != NULL)
delete[] _indexTree;
_indexTree = NULL;
}//end Destroy();
/*
---------------------------------------------------------------------------
Interface Methods.
---------------------------------------------------------------------------
*/
int FastMotionVectorVlcDecoderImpl1::Decode(IBitStreamReader* bsr)
{
int tblPos = 0;
int found = 0;
int bitsSoFar = 0;
int bits = 0;
int index = 0;
while(1)
{
// Get the current bit
int bit = bsr->Read();
// Branch
if(bit) // bit 1
{
//if (_onesTree[index] == -1)
// break; // Failed.
//index = _onesTree[index];
// Aid branch prediction by most likely being true.
if (_onesTree[index] != -1)
index = _onesTree[index];
else
break;
}//end if bit...
else // bit 0
{
//if (_zeroTree[index] == -1)
// break; // Failed.
//index = _zeroTree[index];
if (_zeroTree[index] != -1)
index = _zeroTree[index];
else
break;
}//end else...
if (_indexTree[index] != -1)
{
tblPos = _indexTree[index];
found = 1;
break;
}//end if _indexTree...
}//end while 1...
// If not found then there is an error.
if( !found )
{
_numDecodedBits = 0; // Implies an error.
return(0);
}//end if !found...
bitsSoFar = VLC_TABLE[tblPos][MVVD_NUM_BITS];
bits = VLC_TABLE[tblPos][MVVD_BIT_CODE];
// Check for escape sequence at the appropriate numbits pos.
if((bits == ESC_BIT_CODE)&&(bitsSoFar == NUM_ESC_BITS))
{
int bit = bsr->Read(ESC_LENGTH);
bitsSoFar += ESC_LENGTH;
tblPos = bit - 128;
}//end if bits...
else
{
// Get the signed codeword from the table.
int sgn = tblPos % 2;
tblPos = tblPos / 2;
if (sgn == 1)
tblPos++;
else
tblPos = -tblPos;
}//end else...
_numDecodedBits = bitsSoFar;
return(tblPos);
}//end Decode.
| 21.722488 | 94 | 0.577313 | [
"vector"
] |
598de6140cf54684b79aa0231c54e2a131280ff5 | 1,205 | cc | C++ | experiment.cc | mesorangerxx/Randomization-Sorting | b4dcdf83601a4022618a7692a2cf222d1538635b | [
"MIT"
] | null | null | null | experiment.cc | mesorangerxx/Randomization-Sorting | b4dcdf83601a4022618a7692a2cf222d1538635b | [
"MIT"
] | null | null | null | experiment.cc | mesorangerxx/Randomization-Sorting | b4dcdf83601a4022618a7692a2cf222d1538635b | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
// experiment.cc
//
// Example code showing how to run an algorithm once and measure its elapsed
// time precisely. You should modify this program to gather all of your
// experimental data.
//
///////////////////////////////////////////////////////////////////////////////
#include <iostream>
#include "project2.hh"
#include "timer.hh"
#include <vector>
#include <fstream>
using namespace std;
int main() {
string_vector all_words;
if ( ! load_words(all_words, "words.txt") ) {
cerr << "error: cannot open \"words.txt\"" << endl;
return 1;
}
//ofstream used to store data into a text file
ofstream fout;
fout.open("mergesortData.txt");
int n = 99171;
//for loop used to run the experiment 300 times
for (size_t i = 0; i < 300; i++)
{
string_vector n_words(all_words.begin(), all_words.begin() + n);
randomize_list(n_words);
Timer timer;
mergesort(n_words);
/*quicksort(n_words);*/
double elapsed = timer.elapsed();
cout << "quicksort, "
<< "n=" << n << ", "
<< "elapsed time = " << elapsed << " seconds" << endl;
fout << elapsed << endl;
}
return 0;
}
| 21.140351 | 79 | 0.554357 | [
"vector"
] |
599b1ce63faabad7b8f8f100e5c31f7d0153f728 | 813 | cpp | C++ | CodeWars/Fundamentals/BuildTower/BuildTower.cpp | CajetanP/programming-exercises | aee01ff3208ab14e7d0e0a7077798342123bc3e6 | [
"MIT"
] | 1 | 2017-06-23T16:39:17.000Z | 2017-06-23T16:39:17.000Z | CodeWars/Fundamentals/BuildTower/BuildTower.cpp | CajetanP/coding-exercises | aee01ff3208ab14e7d0e0a7077798342123bc3e6 | [
"MIT"
] | 10 | 2021-05-09T00:06:22.000Z | 2021-09-02T12:07:41.000Z | CodeWars/Fundamentals/BuildTower/BuildTower.cpp | mrkajetanp/programming-exercises | aee01ff3208ab14e7d0e0a7077798342123bc3e6 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <cassert>
class Kata {
public:
static std::vector<std::string> towerBuilder (int nFloors);
};
std::vector<std::string> Kata::towerBuilder (int nFloors) {
std::vector<std::string> res;
for (int i = 0 ; i < nFloors ; ++i)
res.push_back (std::string (nFloors-i-1, ' ') +
std::string (i*2+1, '*') +
std::string (nFloors-i-1, ' '));
return res;
}
void tests () {
Kata kata;
std::vector<std::string> expected = { "*" };
assert (kata.towerBuilder(1) == expected);
expected = { " * ", "***" };
assert (kata.towerBuilder(2) == expected);
expected = { " * ", " *** ", "*****" };
assert (kata.towerBuilder(3) == expected);
}
int main () {
tests ();
return 0;
}
| 21.972973 | 63 | 0.522755 | [
"vector"
] |
59a27b8bf61afad7be492b777d44016fe768c564 | 2,135 | cc | C++ | dune/stuff/test/common_ranges.cc | ftalbrecht/dune-stuff-simplified | fc1f80dedaa78fae6e6d67e8f5424a6b3ec86b5d | [
"BSD-2-Clause"
] | null | null | null | dune/stuff/test/common_ranges.cc | ftalbrecht/dune-stuff-simplified | fc1f80dedaa78fae6e6d67e8f5424a6b3ec86b5d | [
"BSD-2-Clause"
] | null | null | null | dune/stuff/test/common_ranges.cc | ftalbrecht/dune-stuff-simplified | fc1f80dedaa78fae6e6d67e8f5424a6b3ec86b5d | [
"BSD-2-Clause"
] | null | null | null |
// This file is part of the dune-stuff project:
// https://github.com/wwu-numerik/dune-stuff
// Copyright holders: Rene Milk, Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#include "main.hxx"
#if HAVE_DUNE_GRID
#include <dune/grid/yaspgrid.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/common/ranges.hh>
using namespace Dune;
using namespace Dune::Stuff;
using namespace Dune::Stuff::Common;
using namespace Dune::Stuff::Grid;
using namespace std;
//! \TODO enable embedded grids
typedef testing::Types<YaspGrid<1, EquidistantOffsetCoordinates<double, 1>>,
YaspGrid<2, EquidistantOffsetCoordinates<double, 2>>,
YaspGrid<3, EquidistantOffsetCoordinates<double, 3>>,
YaspGrid<4, EquidistantOffsetCoordinates<double, 4>>> Grids;
template <class T>
struct CornerRangeTest : public ::testing::Test
{
static const size_t level = 4;
typedef T GridType;
static const size_t dim_grid = GridType::dimension;
const DSG::Providers::Cube<GridType> grid_prv;
CornerRangeTest() : grid_prv(0., 1., level) {}
template <typename Entity, typename RangeType>
void check_range(const Entity& e, RangeType range)
{
auto i = e.geometry().corners();
auto ci = std::pow(2, dim_grid);
EXPECT_EQ(i, ci);
for (auto corner : range) {
for (auto c : corner) {
EXPECT_FALSE(DSC::FloatCmp::lt(c, decltype(c)(0)));
EXPECT_FALSE(DSC::FloatCmp::gt(c, decltype(c)(1)));
}
i--;
}
EXPECT_EQ(i, 0);
}
void check()
{
const auto gv = grid_prv.grid().leafGridView();
const auto DUNE_UNUSED(entities) = gv.size(0);
const auto end = gv.template end<0>();
for (auto it = gv.template begin<0>(); it != end; ++it) {
check_range(*it, cornerRange(it->geometry()));
check_range(*it, cornerRange(*it));
}
for (auto v : DSC::valueRange(T::dimensionworld)) {
EXPECT_GE(v, 0);
}
}
};
TYPED_TEST_CASE(CornerRangeTest, Grids);
TYPED_TEST(CornerRangeTest, Misc) { this->check(); }
#endif // #if HAVE_DUNE_GRID
| 29.652778 | 83 | 0.659953 | [
"geometry"
] |
59a410936145f18fc3025ae1bbcb48b4e6ee3b6e | 5,003 | hpp | C++ | src/instance/resource.hpp | kit-algo/TCPSPSuite | 01499b4fb0f28bda72115a699cd762c70d7fff63 | [
"MIT"
] | 3 | 2018-05-02T11:45:57.000Z | 2020-09-14T08:35:43.000Z | src/instance/resource.hpp | kit-algo/TCPSPSuite | 01499b4fb0f28bda72115a699cd762c70d7fff63 | [
"MIT"
] | null | null | null | src/instance/resource.hpp | kit-algo/TCPSPSuite | 01499b4fb0f28bda72115a699cd762c70d7fff63 | [
"MIT"
] | null | null | null | #ifndef RESOURCE_HPP
#define RESOURCE_HPP
#include "generated_config.hpp"
#include <boost/container/small_vector.hpp>
#include <type_traits>
#include <utility> // for pair
#include <vector> // for allocator, vector
// one term: coefficient, exponent
typedef std::pair<double, double> poly_term;
// list of terms
// TODO make number of optimized poly-terms a compile-time variable?
typedef std::vector<poly_term> polynomial;
double apply_polynomial(const polynomial & poly, double x);
// TODO add moving variant for efficiency
polynomial add_poly(const polynomial & lhs, const polynomial & rhs);
// Forwards
class Instance;
class Availability {
public:
Availability(double start_amount);
Availability(const Availability & other) = default; // copy constructor
void set(std::vector<std::pair<unsigned int, double>> && new_points);
double get_at(unsigned int point) const noexcept;
double get_flat_available() const;
std::vector<std::pair<unsigned int, double>>::const_iterator begin() const;
std::vector<std::pair<unsigned int, double>>::const_iterator end() const;
private:
/* Each pair in the points vector is one step of a stepwise function
* indicating the availability of a resource. The first member of every point
* indicates from which time step on the amount is available, the second
* member indicates the amount. The first point (i.e., the first member of the
* first point) must be 0. The points must be sorted by ascending time steps.
*/
std::vector<std::pair<unsigned int, double>> points;
};
class FlexCost {
public:
FlexCost(polynomial base);
void
set_flexible(std::vector<std::pair<unsigned int, polynomial>> && new_points);
const polynomial & get_at(unsigned int point) const noexcept;
const polynomial & get_base() const noexcept;
bool is_flat() const;
std::vector<std::pair<unsigned int, polynomial>>::const_iterator
begin() const;
std::vector<std::pair<unsigned int, polynomial>>::const_iterator end() const;
private:
polynomial base;
// Same idea as for Availability
std::vector<std::pair<unsigned int, polynomial>> points;
};
class Resource {
public:
explicit Resource(unsigned int id);
void set_availability(Availability && availability);
void set_overshoot_costs(FlexCost && cost);
void set_investment_costs(polynomial costs);
const Availability & get_availability() const;
const FlexCost & get_flex_overshoot() const;
const polynomial & get_overshoot_costs(unsigned int pos) const;
// This only works if the instance has flat costs!
const polynomial & get_overshoot_costs() const;
bool is_overshoot_flat() const;
const polynomial & get_investment_costs() const;
unsigned int get_rid();
void set_id(unsigned int id);
bool
operator==(const Resource & other) const
{
return other.rid == this->rid;
// TODO in debug mode, compare everything!
}
// deepcopy
Resource clone() const;
private:
unsigned int rid;
Availability availability;
polynomial investment_costs;
FlexCost overshoot_costs;
};
class ResVec
: public boost::container::small_vector<double, OPTIMAL_RESOURCE_COUNT> {
public:
using boost::container::small_vector<double,
OPTIMAL_RESOURCE_COUNT>::small_vector;
};
class Resources {
public:
Resources();
Resources(double usage);
Resources(const Instance * instance, const ResVec & usage);
Resources(const Instance * instance, const std::vector<double> & usage);
Resources(const Instance * instance, ResVec && usage);
Resources(const Instance * instance);
const ResVec & getUsage() const;
ResVec & getUsage();
Resources operator+(const Resources & other) const;
Resources operator-(const Resources & other) const;
Resources operator*(const Resources & other) const;
Resources operator/(const Resources & other) const;
void operator+=(const Resources & other);
void operator-=(const Resources & other);
void operator*=(const Resources & other);
void operator/=(const Resources & other);
bool operator<(const Resources & other) const;
bool operator>(const Resources & other) const;
bool operator<=(const Resources & other) const;
bool operator>=(const Resources & other) const;
bool operator!=(const Resources & other) const;
bool operator==(const Resources & other) const;
template <typename T>
inline friend std::enable_if_t<std::is_integral_v<T>, Resources>
operator*(const T & scalar, const Resources & resource);
private:
const Instance * instance;
mutable bool cached;
mutable double cache;
ResVec usage;
double getCosts() const;
};
template <typename T>
inline std::enable_if_t<std::is_integral_v<T>, Resources>
operator*(const T & scalar, const Resources & resource)
{
Resources res(resource.instance, resource.usage);
for (size_t i = 0; i < resource.usage.size(); i++) {
res.usage[i] *= scalar;
}
return res;
}
template <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>
Resources
operator*(const Resources & resource, const T & scalar)
{
return scalar * resource;
}
#endif
| 28.265537 | 79 | 0.740955 | [
"vector"
] |
59ae501d5bf5ff457d1719a528dc4537653c2baf | 1,622 | cpp | C++ | SMOL/main.cpp | all500234765/SMOL | d6f1e9401105cd1bf2209f30311dc90bcc78e43b | [
"MIT"
] | null | null | null | SMOL/main.cpp | all500234765/SMOL | d6f1e9401105cd1bf2209f30311dc90bcc78e43b | [
"MIT"
] | null | null | null | SMOL/main.cpp | all500234765/SMOL | d6f1e9401105cd1bf2209f30311dc90bcc78e43b | [
"MIT"
] | null | null | null | #include "pc.h"
#include "Engine.h"
#include "Platform/Pipeline.h"
#include <pspdebug.h>
PSP_MODULE_INFO("smol_test", PSP_MODULE_USER, 1, 0);
class MyGame final: public Game {
private:
Data data;
VertexBuffer vb;
Mesh mesh;
public:
virtual void GameStart() override {
/*pspDebugScreenInit();
pspDebugScreenClear(); // Clears screen pixels
pspDebugScreenSetXY(0, 0); // Reset where we draw
pspDebugScreenPrintf("Hello world!");*/
struct V: public DataAlignedPool {
ColorLowNoAlpha c; // 16
short x, y, z; // 48
};
V* SMOL_DATA_ALIGN b = new V[3];
data.size = sizeof(V) * 3;
data.ptr = ToPtr<u8*>(b);
b[0].x = 0;
b[0].y = 0;
b[0].z = 0;
b[0].c.SetColor(SMOL_COLOR(255, 0, 0, 255));
b[1].x = 128;
b[1].y = 0;
b[1].z = 0;
b[1].c.SetColor(SMOL_COLOR(0, 255, 0, 255));
b[2].x = 128;
b[2].y = 0;
b[2].z = 0;
b[2].c.SetColor(SMOL_COLOR(0, 0, 255, 255));
vb.Create(3, VertexFormat(VFVertex16 | VFColorLowNoAlpha), data);
pspDebugScreenPrintf("AWAWAWA???\n");
mesh.Create(&vb);
pspDebugScreenPrintf("AWAWAWA!!!\n");
}
virtual void Step(f32 delta_time) override {
//mesh.Draw(false);
pspDebugScreenPrintf("FPS: %f\n", delta_time);
}
virtual void GameEnd() override {
}
};
int main(int argc, char** argv) {
MyGame game;
EngineInit(argc, argv);
EngineRun(&game);
return 0;
}
| 20.794872 | 73 | 0.53021 | [
"mesh"
] |
59b2c9ccb6220809b55bba82c95d1c342451a27d | 10,870 | cpp | C++ | lumino/Graphics/src/Rendering/RenderView.cpp | lriki/Lumino | 1a80430f4a83dbdfbe965b3d5b16064991b3edb0 | [
"MIT"
] | 30 | 2016-01-24T05:35:45.000Z | 2020-03-03T09:54:27.000Z | lumino/Graphics/src/Rendering/RenderView.cpp | lriki/Lumino | 1a80430f4a83dbdfbe965b3d5b16064991b3edb0 | [
"MIT"
] | 35 | 2016-04-18T06:14:08.000Z | 2020-02-09T15:51:58.000Z | lumino/Graphics/src/Rendering/RenderView.cpp | lriki/Lumino | 1a80430f4a83dbdfbe965b3d5b16064991b3edb0 | [
"MIT"
] | 5 | 2016-04-03T02:52:05.000Z | 2018-01-02T16:53:06.000Z | /*
[2022/5/8] 描画先は RenderTatget で指定るるべきか? RenderPass で指定するべきか?
----------
外部 OpenGL のバックバッファへの直接描画を行うときは、RenderPass を使わざるを得ない。
そういった時は中間の RenderTarget を1枚用意してくれ、という仕様にするのもアリだが、VRAM がすごく無駄になるのが気になる。
RenderPass を受け取るということは、内部での beginRenderPass 呼び出し時にクリア処理が走る可能性を考慮する必要がある、ということ。
-> これに関しては今もそんなに変わらなくて、SceneRenderPass を複数回 begin/end してはならない制約がある。
RenderPass で指定する場合、 RenderView でクリアができなくなる。
-> RenderPass のクローンをサポートするのもありか?
手動で RenderTarget などを付け替えるのではなく、コピー用の関数を用意する。
-> ただ、クリア方法が内部の都合で変わるので、外部で作った RenderPass が単なる RenderTarget の入れ物にしかならない点が混乱しないか心配。
RenderView に、2通りの render() を用意する。(RenderPass と RenderTarget)
-> わかりやすいけど冗長か?間違いづらくなるならアリだが…。
GLRenderPass を bind するとき、RT[0] がバックバッファを示す RenderTarget であれば、強制的に FBO 0 を使う。
-> とりあえずこれで逃げる。
*/
#include "Internal.hpp"
#include <LuminoGraphics/Rendering/RenderingContext.hpp>
#include <LuminoGraphics/Rendering/RenderView.hpp>
#include <LuminoGraphics/Rendering/RenderingPipeline/StandardRenderingPipeline.hpp>
#include <LuminoGraphics/Rendering/detail/RenderingManager.hpp>
#include "RenderStage.hpp"
#include "SceneRenderer.hpp"
namespace ln {
//==============================================================================
// RenderViewPoint
void RenderViewPoint::resetUnproject(const Size& viewPixelSize_) {
worldMatrix = Matrix::Identity;
viewPixelSize = viewPixelSize_;
viewPosition = Vector3::Zero;
viewDirection = Vector3::UnitZ;
viewMatrix = Matrix::Identity;
projMatrix = Matrix::Identity;
viewProjMatrix = Matrix::Identity;
viewFrustum = ViewFrustum();
fovY = 1.0f;
nearClip = 0.0f;
farClip = 1.0f;
dpiScale = 1.0f;
}
void RenderViewPoint::resetPerspective(const Vector3& viewPos, const Vector3& viewDir, float fovY, const Size& size, float n, float f) {
worldMatrix = Matrix::Identity; // TODO: Lookat
viewPixelSize = size;
viewPosition = viewPos;
viewDirection = viewDir;
#ifdef LN_COORD_RH
viewMatrix = Matrix::makeLookAtRH(viewPos, viewPos + viewDir, Vector3::UnitY);
// projMatrix = Matrix::makeOrthoRH(size.width, size.height, n, f);//Matrix::makePerspectiveFovLH(fovY, size.width / size.height, n, f);
projMatrix = Matrix::makePerspectiveFovRH(fovY, size.width / size.height, n, f);
#else
viewMatrix = Matrix::makeLookAtLH(viewPos, viewPos + viewDir, Vector3::UnitY);
// projMatrix = Matrix::makeOrthoLH(size.width, size.height, n, f);//Matrix::makePerspectiveFovLH(fovY, size.width / size.height, n, f);
projMatrix = Matrix::makePerspectiveFovLH(fovY, size.width / size.height, n, f);
#endif
viewProjMatrix = viewMatrix * projMatrix;
viewFrustum = ViewFrustum(viewProjMatrix);
// zSortDistanceBase = ZSortDistanceBase::CameraScreenDistance;
this->fovY = fovY;
nearClip = n;
farClip = f;
dpiScale = 1.0f;
}
void RenderViewPoint::copyFrom(const RenderViewPoint* other) {
LN_DCHECK(other);
worldMatrix = other->worldMatrix;
viewPixelSize = other->viewPixelSize;
viewPosition = other->viewPosition;
viewDirection = other->viewDirection;
viewMatrix = other->viewMatrix;
projMatrix = other->projMatrix;
viewProjMatrix = other->viewProjMatrix;
viewFrustum = other->viewFrustum;
fovY = other->fovY;
nearClip = other->nearClip;
farClip = other->farClip;
dpiScale = other->dpiScale;
}
void RenderViewPoint::makeCameraInfo(detail::CameraInfo* cameraInfo) const {
LN_DCHECK(cameraInfo);
cameraInfo->viewPixelSize = viewPixelSize;
cameraInfo->viewPosition = viewPosition;
cameraInfo->viewDirection = viewDirection;
cameraInfo->viewMatrix = viewMatrix;
cameraInfo->projMatrix = projMatrix;
cameraInfo->viewProjMatrix = viewProjMatrix;
cameraInfo->viewFrustum = viewFrustum;
cameraInfo->nearClip = nearClip;
cameraInfo->farClip = farClip;
cameraInfo->dpiScale = dpiScale;
}
//==============================================================================
// RenderView
/*
* 必要性について
* ----------
* Camera = RenderView じゃないの?
*
* そうなっているのは Unity くらいかも。 Urho3D や Xenko では分かれている。(Camera,View や CameraComponent,RenderView)
* UE4 は SceneCapture2D がこれに相当するが、WorldPointToScreenPoint などはある程度自分で書く必要があるようだ
* https://usagi.hatenablog.jp/entry/2018/03/01/131939
* http://miyahuji111.hatenablog.com/entry/2016/10/17/193434
*
* デバッグ用のビューを実装するときは Camera と RenderView は分かれていると便利。
* だけど、実際にゲームをつくというときに、ユーザーが RenderView の機能をフルに使うかは微妙。
*
* 後はユーザーに公開するべきかってところだけど、ほかのエンジンたちは
* - Unity: Screen.Width
* - UE4: GEngine->GameViewport->GetViewportSize(Result);
* みたいに、Camera ではないインターフェイスからビューサイズをとったりする。
* ひとまずはこの一点だけの利用になりそうだけど、分ける方向で考えてみよう。
*/
LN_OBJECT_IMPLEMENT(RenderView, Object) {
}
RenderView::RenderView()
: m_clearMode(SceneClearMode::None)
, m_backgroundColor(Color::White)
, m_currentCommandList(nullptr)
, m_currentRenderTarget(nullptr)
, m_viewProjections{}
, m_builtinRenderTextures{} {
}
RenderView::~RenderView() {
}
void RenderView::init(RenderingContext* renderingContext) {
Object::init();
m_manager = detail::RenderingManager::instance();
if (renderingContext) {
m_renderingContext = renderingContext;
}
else {
m_renderingContext = makeObject<RenderingContext>();
}
for (auto i = 0; i < m_viewProjections.size(); i++) {
m_viewProjections[i] = makeObject<RenderViewPoint>();
}
m_viewPoint = makeObject<RenderViewPoint>();
}
void RenderView::makeViewProjections(const RenderViewPoint* base) {
m_viewProjections[static_cast<int>(RenderPart::Geometry)]->copyFrom(base);
m_viewProjections[static_cast<int>(RenderPart::Gizmo)]->copyFrom(base);
m_viewProjections[static_cast<int>(RenderPart::PostEffect)]->resetUnproject(base->viewPixelSize);
// info = &m_viewProjections[static_cast<int>(detail::ProjectionKind::Physical2D)];
// info->viewPixelSize = base.viewPixelSize;
// info->viewPosition = Vector3::Zero;
// info->viewDirection = Vector3::UnitZ;
//#ifdef LN_COORD_RH
// info->viewMatrix = Matrix::makeLookAtRH(Vector3::Zero, -Vector3::UnitZ, Vector3::UnitY);
// info->projMatrix = Matrix::makePerspective2DRH(base.viewPixelSize.width, base.viewPixelSize.height, 0, 1000);
//#else
// info->viewMatrix = Matrix::makeLookAtLH(Vector3::Zero, Vector3::UnitZ, Vector3::UnitY);
// info->projMatrix = Matrix::makePerspective2DLH(base.viewPixelSize.width, base.viewPixelSize.height, 0, 1000);
//#endif
// info->viewProjMatrix = info->viewMatrix * info->projMatrix;
// info->viewFrustum = ViewFrustum(info->viewProjMatrix);
// info->nearClip = 0;
// info->farClip = 1000;
RenderViewPoint* info = m_viewProjections[static_cast<int>(RenderPart::Gizmo2D)];
info->viewPixelSize = base->viewPixelSize;
info->viewPosition = Vector3::Zero;
info->viewDirection = Vector3::UnitZ;
#ifdef LN_COORD_RH
info->viewMatrix = Matrix::makeLookAtRH(Vector3::Zero, /*-*/ Vector3::UnitZ, Vector3::UnitY);
info->projMatrix = Matrix::makePerspective2DRH(base->viewPixelSize.width / base->dpiScale, base->viewPixelSize.height / base->dpiScale, 0, 1000);
#else
info->viewMatrix = Matrix::makeLookAtLH(Vector3::Zero, Vector3::UnitZ, Vector3::UnitY);
info->projMatrix = Matrix::makePerspective2DLH(base.viewPixelSize.width / dpiScale, base.viewPixelSize.height / dpiScale, 0, 1000);
#endif
info->viewProjMatrix = info->viewMatrix * info->projMatrix;
info->viewFrustum = ViewFrustum(info->viewProjMatrix);
info->nearClip = 0;
info->farClip = 1000;
// Vector3 pos1 = Vector3::transformCoord(Vector3(0, 0, 0), info->viewProjMatrix);
// Vector3 pos2 = Vector3::transformCoord(Vector3(0, 0, 1), info->viewProjMatrix);;
// Vector3 pos3 = Vector3::transformCoord(Vector3(0, 0, -1), info->viewProjMatrix);
// printf("");
}
Vector3 RenderView::transformProjection(const Vector3& pos, RenderPart from, RenderPart to) const {
const RenderViewPoint* fromView = m_viewProjections[static_cast<int>(from)];
const auto clipPos = Vector3::transformCoord(pos, fromView->viewProjMatrix);
const RenderViewPoint* toView = m_viewProjections[static_cast<int>(to)];
const auto inv = Matrix::makeInverse(toView->viewProjMatrix);
return Vector3::transformCoord(clipPos, inv);
}
RenderingPipeline* RenderView::renderingPipeline() const {
return m_renderingPipeline;
}
void RenderView::setRenderingPipeline(RenderingPipeline* value) {
m_renderingPipeline = value;
}
void RenderView::clearBuiltinRenderTextures() {
m_builtinRenderTextures = {};
}
RenderingContext* RenderView::getContext() const {
return m_renderingContext;
}
void RenderView::updateFrame(float elapsedSeconds) {
onUpdateFrame(elapsedSeconds);
}
void RenderView::renderPipeline(GraphicsCommandList* graphicsContext, /*RenderingContext* renderingContext,*/ RenderTargetTexture* renderTarget) {
beginRenderPipeline(graphicsContext, renderTarget);
endRenderPipeline();
}
RenderingContext* RenderView::beginRenderPipeline(GraphicsCommandList* graphicsContext, RenderTargetTexture* renderTarget) {
if (LN_ASSERT(m_renderingPipeline)) return nullptr;
if (LN_ASSERT(!m_currentCommandList)) return nullptr;
m_currentCommandList = graphicsContext;
m_currentRenderTarget = renderTarget;
m_viewPoint->viewPixelSize = Size(renderTarget->width(), renderTarget->height());
onUpdateViewPoint(m_viewPoint, renderTarget);
makeViewProjections(m_viewPoint);
clearBuiltinRenderTextures();
m_renderingPipeline->prepare(this, renderTarget);
m_renderingContext->resetForBeginRendering(m_viewPoint);
onRender(graphicsContext, m_renderingContext, renderTarget);
return m_renderingContext;
}
void RenderView::endRenderPipeline() {
if (LN_ASSERT(m_currentCommandList)) return;
m_renderingPipeline->render(m_currentCommandList, m_renderingContext, m_currentRenderTarget, this, nullptr);
m_currentCommandList = nullptr;
m_currentRenderTarget = nullptr;
}
//void RenderView::onUpdateViewPoint(RenderViewPoint* viewPoint) {
//}
void RenderView::onUpdateFrame(float elapsedSeconds) {
}
void RenderView::setActualSize(const Size& size) {
m_actualSize = size;
}
// void RenderView::render(GraphicsCommandList* graphicsContext, const FrameBuffer& frameBuffer, detail::SceneRenderer* sceneRenderer)
//{
// m_renderingFrameBufferSize = SizeI(frameBuffer.renderTarget[0]->width(), frameBuffer.renderTarget[0]->height());
//
// sceneRenderer->render(graphicsContext, this, frameBuffer);
//
// // 誤用防止
// m_renderingFrameBufferSize = SizeI();
// }
} // namespace ln
| 38.409894 | 150 | 0.711408 | [
"geometry",
"render",
"object"
] |
59b5171eeb15611a48ffdf245a8f6b0f62e58129 | 770 | hpp | C++ | src/math/vec3.hpp | simonfxr/gl | 11705f718d27657fc76243d59a251f49c0a41486 | [
"MIT"
] | null | null | null | src/math/vec3.hpp | simonfxr/gl | 11705f718d27657fc76243d59a251f49c0a41486 | [
"MIT"
] | null | null | null | src/math/vec3.hpp | simonfxr/gl | 11705f718d27657fc76243d59a251f49c0a41486 | [
"MIT"
] | null | null | null | #ifndef MATH_VEC3_HPP
#define MATH_VEC3_HPP
#include "math/genvec.hpp"
namespace math {
using vec3_t = genvec<real, 3>;
inline constexpr vec3_t
vec3(real x, real y, real z)
{
return vec3_t::make(x, y, z);
}
template<typename T>
inline constexpr vec3_t
vec3(const genvec<T, 3> &v)
{
return vec3_t::convert(v);
}
inline constexpr vec3_t
vec3(real x)
{
return vec3_t::fill(x);
}
inline constexpr vec3_t
vec3(const vec3_t::buffer b)
{
return vec3_t::load(b);
}
template<typename T>
inline constexpr vec3_t
vec3(const genvec<T, 4> &v)
{
return vec3(v[0], v[1], v[2]);
}
using point3_t = vec3_t;
using direction3_t = vec3_t; // a unit vector
using normal3_t = vec3_t; // a unit vector, perdendicular to some surface
} // namespace math
#endif
| 15.098039 | 73 | 0.694805 | [
"vector"
] |
59bc5ed52f53922e3009d383567aa111a1950280 | 7,251 | cpp | C++ | src/Samples/src/samples/meshes/super_ellipsoid_scene.cpp | sacceus/BabylonCpp | 94669cf7cbe3214ec6e905cbf249fa0c9daf6222 | [
"Apache-2.0"
] | 277 | 2017-05-18T08:27:10.000Z | 2022-03-26T01:31:37.000Z | src/Samples/src/samples/meshes/super_ellipsoid_scene.cpp | sacceus/BabylonCpp | 94669cf7cbe3214ec6e905cbf249fa0c9daf6222 | [
"Apache-2.0"
] | 77 | 2017-09-03T15:35:02.000Z | 2022-03-28T18:47:20.000Z | src/Samples/src/samples/meshes/super_ellipsoid_scene.cpp | sacceus/BabylonCpp | 94669cf7cbe3214ec6e905cbf249fa0c9daf6222 | [
"Apache-2.0"
] | 37 | 2017-03-30T03:36:24.000Z | 2022-01-28T08:28:36.000Z | #include <babylon/babylon_stl_util.h>
#include <babylon/cameras/arc_rotate_camera.h>
#include <babylon/interfaces/irenderable_scene.h>
#include <babylon/lights/hemispheric_light.h>
#include <babylon/materials/standard_material.h>
#include <babylon/maths/color3.h>
#include <babylon/maths/scalar.h>
#include <babylon/meshes/mesh.h>
#include <babylon/meshes/vertex_data.h>
#include <babylon/samples/babylon_register_sample.h>
namespace BABYLON {
namespace Samples {
class SuperEllipsoidScene : public IRenderableScene {
public:
SuperEllipsoidScene(ICanvas* iCanvas) : IRenderableScene(iCanvas)
{
}
~SuperEllipsoidScene() override = default;
const char* getName() override
{
return "Super Ellipsoid Scene";
}
void initializeScene(ICanvas* canvas, Scene* scene) override
{
// Create a rotating camera
auto camera = ArcRotateCamera::New("Camera", 0.f, Math::PI_2, 12.f, Vector3::Zero(), scene);
camera->setPosition(Vector3(-5.f, 5.f, 5.f));
// Attach it to handle user inputs (keyboard, mouse, touch)
camera->attachControl(canvas, false);
// Add a light
auto light = HemisphericLight::New("hemi", Vector3(0.f, 1.f, 0.f), scene);
light->intensity = 0.95f;
// Create super ellipsoid and material
auto mat = StandardMaterial::New("mat", scene);
mat->diffuseColor = Color3::Purple();
mat->backFaceCulling = false;
auto mat2 = StandardMaterial::New("mat2", scene);
mat2->diffuseColor = Color3::Red();
mat2->backFaceCulling = false;
auto mat3 = StandardMaterial::New("mat3", scene);
mat3->diffuseColor = Color3::Green();
mat3->backFaceCulling = false;
auto mat4 = StandardMaterial::New("mat4", scene);
mat4->diffuseColor = Color3::Blue();
mat4->backFaceCulling = false;
auto mat5 = StandardMaterial::New("mat5", scene);
mat5->diffuseColor = Color3::Yellow();
mat5->backFaceCulling = false;
auto superello1 = _createSuperEllipsoid(48, 0.2f, 0.2f, 1, 1, 1, scene);
superello1->material = mat2;
auto superello2 = _createSuperEllipsoid(48, 0.2f, 0.2f, 1, 1, 1, scene);
superello2->position().x += 2.5f;
superello2->material = mat;
superello2->material()->wireframe = true;
auto superello3 = _createSuperEllipsoid(48, 1.8f, 0.2f, 1, 1, 1, scene);
superello3->position().x -= 2.5f;
superello3->material = mat3;
auto superello4 = _createSuperEllipsoid(48, 1.8f, 0.2f, 1, 1, 1, scene);
superello4->position().z += 2.5f;
superello4->material = mat4;
superello4->material()->wireframe = true;
auto superello5 = _createSuperEllipsoid(48, 0.2f, 2.9f, 1, 1, 1, scene);
superello5->position().z -= 2.5f;
superello5->material = mat5;
}
private:
[[nodiscard]] Vector3 _sampleSuperEllipsoid(float phi, float beta, float n1, float n2,
float scaleX, float scaleY, float scaleZ) const
{
Vector3 vertex;
float cosPhi = std::cos(phi);
float cosBeta = std::cos(beta);
float sinPhi = std::sin(phi);
float sinBeta = std::sin(beta);
vertex.x = scaleX * Scalar::Signf(cosPhi) * std::pow(std::abs(cosPhi), n1)
* Scalar::Signf(cosBeta) * std::pow(std::abs(cosBeta), n2);
vertex.z = scaleY * Scalar::Signf(cosPhi) * std::pow(std::abs(cosPhi), n1)
* Scalar::Signf(sinBeta) * std::pow(std::abs(sinBeta), n2);
vertex.y = scaleZ * Scalar::Signf(sinPhi) * std::pow(std::abs(sinPhi), n1);
return vertex;
}
[[nodiscard]] Vector3 _calculateNormal(float phi, float beta, float n1, float n2, float scaleX,
float scaleY, float scaleZ) const
{
Vector3 normal;
float cosPhi = std::cos(phi);
float cosBeta = std::cos(beta);
float sinPhi = std::sin(phi);
float sinBeta = std::sin(beta);
normal.x = Scalar::Signf(cosPhi) * std::pow(std::abs(cosPhi), 2 - n1) * Scalar::Signf(cosBeta)
* std::pow(std::abs(cosBeta), 2 - n2) / scaleX;
normal.z = Scalar::Signf(cosPhi) * std::pow(std::abs(cosPhi), 2 - n1) * Scalar::Signf(sinBeta)
* std::pow(std::abs(sinBeta), 2 - n2) / scaleY;
normal.y = Scalar::Signf(sinPhi) * std::pow(std::abs(sinPhi), 2 - n1) / scaleZ;
normal.normalize();
return normal;
}
MeshPtr _createSuperEllipsoid(size_t samples, float n1, float n2, float scalex, float scaley,
float scalez, Scene* scene)
{
auto superello = Mesh::New("superello", scene);
float phi = 0.f, beta = 0.f;
float dB = Math::PI2 / static_cast<float>(samples);
float dP = Math::PI2 / static_cast<float>(samples);
phi = -Math::PI_2;
std::vector<Vector3> vertices;
std::vector<Vector3> normals;
for (size_t j = 0; j <= samples / 2; j++) {
beta = -Math::PI;
for (size_t i = 0; i <= samples; i++) {
// Triangle #1
vertices.emplace_back(_sampleSuperEllipsoid(phi, beta, n1, n2, scalex, scaley, scalez));
normals.emplace_back(_calculateNormal(phi, beta, n1, n2, scalex, scaley, scalez));
vertices.emplace_back(
_sampleSuperEllipsoid(phi + dP, beta, n1, n2, scalex, scaley, scalez));
normals.emplace_back(_calculateNormal(phi + dP, beta, n1, n2, scalex, scaley, scalez));
vertices.emplace_back(
_sampleSuperEllipsoid(phi + dP, beta + dB, n1, n2, scalex, scaley, scalez));
normals.emplace_back(_calculateNormal(phi + dP, beta + dB, n1, n2, scalex, scaley, scalez));
// Triangle #2
vertices.emplace_back(_sampleSuperEllipsoid(phi, beta, n1, n2, scalex, scaley, scalez));
normals.emplace_back(_calculateNormal(phi, beta, n1, n2, scalex, scaley, scalez));
vertices.emplace_back(
_sampleSuperEllipsoid(phi + dP, beta + dB, n1, n2, scalex, scaley, scalez));
normals.emplace_back(_calculateNormal(phi + dP, beta + dB, n1, n2, scalex, scaley, scalez));
vertices.emplace_back(
_sampleSuperEllipsoid(phi, beta + dB, n1, n2, scalex, scaley, scalez));
normals.emplace_back(_calculateNormal(phi, beta + dB, n1, n2, scalex, scaley, scalez));
beta += dB;
}
phi += dP;
}
auto shapeReturned = std::make_unique<VertexData>();
shapeReturned->positions.clear();
shapeReturned->normals.clear();
shapeReturned->indices.clear();
shapeReturned->uvs.clear();
int32_t indice = 0;
for (size_t i = 0; i < vertices.size(); ++i) {
shapeReturned->indices.emplace_back(indice++);
shapeReturned->positions.emplace_back(vertices[i].x);
shapeReturned->positions.emplace_back(vertices[i].y);
shapeReturned->positions.emplace_back(vertices[i].z);
shapeReturned->normals.emplace_back(normals[i].x);
shapeReturned->normals.emplace_back(normals[i].y);
shapeReturned->normals.emplace_back(normals[i].z);
}
shapeReturned->applyToMesh(*superello);
return superello;
}
}; // end of class SuperEllipsoidScene
BABYLON_REGISTER_SAMPLE("Meshes", SuperEllipsoidScene)
} // end of namespace Samples
} // end of namespace BABYLON
| 42.403509 | 100 | 0.633292 | [
"mesh",
"vector"
] |
59bce6421d87a065f4ca818203f12c5ec42bcb39 | 4,477 | cpp | C++ | MCM/MCMEncoder.cpp | StephanBusch/7-Zip | 35c215fbc3efc16951182f6127885d22d11a018e | [
"Apache-2.0"
] | 14 | 2016-08-17T09:45:30.000Z | 2021-12-01T23:06:20.000Z | MCM/MCMEncoder.cpp | StephanBusch/7-Zip | 35c215fbc3efc16951182f6127885d22d11a018e | [
"Apache-2.0"
] | 2 | 2018-06-03T07:17:39.000Z | 2021-12-14T22:30:10.000Z | MCM/MCMEncoder.cpp | StephanBusch/7-Zip | 35c215fbc3efc16951182f6127885d22d11a018e | [
"Apache-2.0"
] | 5 | 2016-07-21T05:08:55.000Z | 2021-11-16T02:18:45.000Z | // MCMEncoder.cpp
#define NOMINMAX
#include "CPP/7zip/Compress/StdAfx.h"
#include "C/Alloc.h"
#include "CPP/7zip/Common/CWrappers.h"
#include "CPP/7zip/Common/StreamUtils.h"
#include "MCMEncoder.h"
#include "PackjpgCoder.h"
namespace NCompress {
namespace NMCM {
using namespace NCompress::NPackjpg;
CEncoder::CEncoder()
{
}
CEncoder::~CEncoder()
{
}
STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs,
const PROPVARIANT *coderProps, UInt32 numProps)
{
uint64_t nReduceSize = 0;
for (UInt32 i = 0; i < numProps; i++)
{
const PROPVARIANT &prop = coderProps[i];
PROPID propID = propIDs[i];
if (propID > NCoderPropID::kReduceSize)
continue;
if (prop.vt != VT_UI4 && prop.vt != VT_UI8)
return E_INVALIDARG;
UInt32 v = (UInt32)prop.ulVal;
switch (propID)
{
case NCoderPropID::kDictionarySize:
if (prop.vt != VT_UI4)
return E_INVALIDARG;
block_size = v;
break;
case NCoderPropID::kUsedMemorySize:
{
size_t i = 0;
v = (v + 2 * MB - 1) / 2 / MB;
while (v > 0) {
v >>= 1;
i++;
}
options_.mem_usage_ = i;
}
break;
case NCoderPropID::kLevel:
v = (v + 1) / 2;
options_.comp_level_ = (CompLevel)v;
break;
case NCoderPropID::kNumThreads:
threads = v;
break;
case NCoderPropID::kReduceSize:
nReduceSize = prop.uhVal.QuadPart;
break;
default: return E_INVALIDARG;
}
}
if (nReduceSize > 0 && nReduceSize < block_size)
block_size = nReduceSize;
return S_OK;
}
STDMETHODIMP CEncoder::WriteCoderProperties(ISequentialOutStream *outStream)
{
Byte bt;
bt = (Byte)options_.mem_usage_; RINOK(WriteStream(outStream, &bt, 1));
bt = (Byte)options_.comp_level_; RINOK(WriteStream(outStream, &bt, 1));
bt = (Byte)options_.filter_type_; RINOK(WriteStream(outStream, &bt, 1));
bt = (Byte)options_.lzp_type_; RINOK(WriteStream(outStream, &bt, 1));
UInt32 bs = (UInt32)((block_size + MB - 1) / MB); RINOK(WriteStream(outStream, &bs, 4));
return S_OK;
}
STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress)
{
UInt64 inSizeProcessed = 0, outSizeProcessed = 0;
std::vector<uint8_t> plain_buffer;
WriteVectorStream wvs_plain(&plain_buffer);
{
uint8_t buff[512];
size_t processedSize = sizeof(buff);
while (processedSize > 0) {
processedSize = sizeof(buff);
RINOK(ReadStream(inStream, buff, &processedSize));
wvs_plain.write(buff, processedSize);
inSizeProcessed += processedSize;
}
}
ReadMemoryStream rms(&plain_buffer[0], &plain_buffer[0] + plain_buffer.size());
Stream *in = &rms;
RINOK(write_int(outStream, major_version_, &outSizeProcessed));
RINOK(write_int(outStream, minor_version_, &outSizeProcessed));
Analyzer analyzer;
// Analyzing
analyzer.analyze(in);
constructBlocks(in, &analyzer);
writeBlocks(outStream, &outSizeProcessed);
UInt64 inSizeCompressed = 0;
std::vector<uint8_t> compressed_buffer;
WriteVectorStream wvs_compressed(&compressed_buffer);
for (auto *block : blocks_.blocks_) {
std::vector<uint8_t> temp_buffer;
WriteVectorStream wvs_temp(&temp_buffer);
FileSegmentStream segstream(&block->segments_, 0u);
Algorithm *algo = &block->algorithm_;
// Compressing
std::unique_ptr<Filter> filter(algo->createFilter(&segstream, &analyzer));
Stream *in_stream = &segstream;
if (filter.get() != nullptr) in_stream = filter.get();
auto in_start = in_stream->tell();
std::unique_ptr<Compressor> comp(algo->createCompressor());
comp->setOpt(opt_var_);
{
ProgressThread thr(&segstream, &wvs_temp, &inSizeCompressed, &outSizeProcessed, progress);
comp->compress(in_stream, &wvs_temp);
inSizeCompressed += in_stream->tell();
}
const auto filter_size = in_stream->tell() - in_start;
wvs_compressed.leb128Encode(filter_size);
wvs_compressed.write(temp_buffer.data(), temp_buffer.size());
}
RINOK(write_int(outStream, compressed_buffer.size(), &outSizeProcessed));
RINOK(WriteStream(outStream, compressed_buffer.data(), compressed_buffer.size()));
outSizeProcessed += compressed_buffer.size();
if (progress != NULL)
RINOK(progress->SetRatioInfo(&inSizeProcessed, &outSizeProcessed));
return S_OK;
}
} // namespace NMCM
} // namespace NCompress
| 28.157233 | 96 | 0.684164 | [
"vector"
] |
59de9dbd320bdae9b9a890880694b86a0ebff1a4 | 741 | cpp | C++ | src/line-fill-format.cpp | dashboardvision/aspose-php | e2931773cbb1f47ae4086d632faa3012bd952b99 | [
"MIT"
] | null | null | null | src/line-fill-format.cpp | dashboardvision/aspose-php | e2931773cbb1f47ae4086d632faa3012bd952b99 | [
"MIT"
] | null | null | null | src/line-fill-format.cpp | dashboardvision/aspose-php | e2931773cbb1f47ae4086d632faa3012bd952b99 | [
"MIT"
] | 1 | 2021-06-23T08:02:03.000Z | 2021-06-23T08:02:03.000Z | #include "../include/aspose.h"
#include "../include/line-fill-format.h"
#include "../include/color-format.h"
#include <phpcpp.h>
using namespace Aspose::Slides;
using namespace std;
namespace AsposePhp {
void LineFillFormat::set_FillType(Php::Parameters ¶ms)
{
FillType type = (FillType)params[0].numericValue();
_asposeObj->set_FillType(type);
}
/**
* Sets a single-line title.
*
* @param string $title A text for the title.
*
* @return void
*/
Php::Value LineFillFormat::get_SolidFillColor()
{
return Php::Object("AsposePhp\\Slides\\ColorFormat", wrapObject<IColorFormat, AsposePhp::ColorFormat, &ILineFillFormat::get_SolidFillColor>());
}
}
| 21.794118 | 151 | 0.651822 | [
"object"
] |
59e7a8bf070de25629acd3e2272758fa8b624401 | 1,558 | cpp | C++ | src/TwoSum.cpp | evagle/leetcode | 8309c6b89ed377f5882d7453691a6b3842cf9586 | [
"Apache-2.0"
] | null | null | null | src/TwoSum.cpp | evagle/leetcode | 8309c6b89ed377f5882d7453691a6b3842cf9586 | [
"Apache-2.0"
] | null | null | null | src/TwoSum.cpp | evagle/leetcode | 8309c6b89ed377f5882d7453691a6b3842cf9586 | [
"Apache-2.0"
] | null | null | null | /**
* Brian
* 2014.9.11
*/
#include <iostream>
#include <vector>
#include <map>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
std::map<int, vector<int>> smap ;
vector<int> result;
for (int i = 0; i < numbers.size(); i++) {
if (smap.find(numbers.at(i)) != smap.end()) {
smap[numbers.at(i)].push_back( i + 1);
} else {
vector<int> tmp ;
tmp.push_back(i + 1);
smap[numbers.at(i)] = tmp;
}
}
for (int i = 0; i < numbers.size(); i++) {
int v = numbers.at(i);
if (smap.find(target - v) != smap.end()) {
vector<int> matched = smap[target - v];
for (int k = 0; k < matched.size(); k++) {
if (matched.at(k) > i+1) {
result.push_back(i+1);
result.push_back(matched.at(k));
break;
}
}
}
if (result.size() > 0)
break;
}
return result;
}
};
int main()
{
Solution s;
vector<int> numbers;
numbers.push_back(0);
numbers.push_back(2);
numbers.push_back(4);
numbers.push_back(0);
vector<int> a = s.twoSum(numbers , 0);
if (a.at(0) > a.at(1)) {
swap(a[0], a[1]);
}
for (int i = 0; i < a.size(); i++) {
cout<< a.at(i) << endl;
}
return 0;
}
| 23.969231 | 63 | 0.422336 | [
"vector"
] |
59efb32b4c5f457faf780b44ccf9d1fd918ff398 | 2,751 | cpp | C++ | Game/grid.cpp | maxPrakken/Intake | 42f861292887a14bd1bb8c5aa8b5fdd5deee8e9e | [
"MIT"
] | null | null | null | Game/grid.cpp | maxPrakken/Intake | 42f861292887a14bd1bb8c5aa8b5fdd5deee8e9e | [
"MIT"
] | null | null | null | Game/grid.cpp | maxPrakken/Intake | 42f861292887a14bd1bb8c5aa8b5fdd5deee8e9e | [
"MIT"
] | null | null | null | #include "Grid.h"
Grid::Grid() : Entity()
{
grid = Vector2(2, 2);
spawnPos = Vector2(0, 0);
startX = spawnPos.x;
size = Vector2(0, 0);
firstTile = true;
tileTexture = "assets/INA.png";
buildgrid();
}
Grid::Grid(Vector2 gridSize, std::string tiletexture)
{
grid = gridSize;
spawnPos = Vector2(0, 0);
pos = spawnPos;
startX = spawnPos.x;
firstTile = true;
tileTexture = tiletexture;
buildgrid();
}
Grid::Grid(Vector2 gridSize, Vector2 tilesize)
{
grid = gridSize;
spawnPos2 = Vector2(0, 0);
pos = spawnPos2;
startX2 = spawnPos2.x;
firstTile = true;
tileTexture = "assets/INA.png";
buildgrid(tilesize);
}
Grid::Grid(Vector2 gridSize, std::string tiletexture, Vector2 tilesize, bool isRandom, Vector2 rowAmound)
{
grid = gridSize;
spawnPos2 = Vector2(0, 0);
pos = spawnPos2;
startX2 = spawnPos2.x;
firstTile = true;
tileTexture = tiletexture;
if (!isRandom)
buildgrid(tilesize);
else
buildgrid(tilesize, isRandom, rowAmound);
}
Grid::~Grid()
{
std::vector<Entity*>::iterator it = tileVector.begin();
while (it != tileVector.end()) {
Entity* e = (*it);
it = tileVector.erase(it);
delete e;
}
}
void Grid::update(double deltatime)
{
Entity::update(deltatime);
}
void Grid::buildgrid()
{
for (int i = 0; i < grid.x * grid.y; i++) {
spawnTile();
}
}
void Grid::buildgrid(Vector2 tilesize, bool isRandom, Vector2 rows)
{
for (int i = 0; i < grid.x * grid.y; i++) {
if (!isRandom)
spawnTile(tilesize);
else
spawnTile(tilesize, isRandom, rows);
}
}
void Grid::spawnTile()
{
Entity* tile = new Entity();
tile->texturePath = tileTexture;
tile->size = Vector2(100, 100);
addchild(tile);
tileVector.push_back(tile);
tile->pos = spawnPos;
if (spawnPos.x <= grid.x * tile->size.x) {
spawnPos += Vector2(tile->size.x, 0);
}
else if (spawnPos.x > grid.x * tile->size.x) {
spawnPos.x = startX;
spawnPos.y += tile->size.y;
}
size = Vector2(grid.x * tile->size.x, grid.y * tile->size.y);
}
void Grid::spawnTile(Vector2 tilesize, bool isRandom, Vector2 rows)
{
Entity* tile = new Entity();
if (isRandom && rows.x > 0)
{
int tilesAmount = rows.x * rows.y;
int randomInt = rand() % tilesAmount;
tile->spitesheetPath = tileTexture;
tile->animator.rows = rows;
tile->animator.paused = true;
tile->animator.switchAfter = 1;
tile->animator.cur = randomInt;
}
else
{
tile->texturePath = tileTexture;
}
tile->size = tilesize;
addchild(tile);
tileVector.push_back(tile);
if (spawnPos2.x < grid.x * tile->size.x) {
spawnPos2 += Vector2(tile->size.x, 0);
}
tile->pos = spawnPos2;
if (spawnPos2.x >= grid.x * tile->size.x) {
spawnPos2.x = startX2;
spawnPos2.y += tile->size.y;
}
size = Vector2(grid.x * tile->size.x, grid.y * tile->size.y);
}
| 18.463087 | 105 | 0.652126 | [
"vector"
] |
59f38c5d683efd01c93c6445776f4808aae8ec21 | 11,405 | cc | C++ | iioservice/daemon/sensor_device_impl_test.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | null | null | null | iioservice/daemon/sensor_device_impl_test.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | null | null | null | iioservice/daemon/sensor_device_impl_test.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2020 The Chromium OS 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 <gtest/gtest.h>
#include <set>
#include <utility>
#include <base/run_loop.h>
#include <base/task/single_thread_task_executor.h>
#include <base/threading/thread.h>
#include <mojo/core/embedder/embedder.h>
#include <mojo/core/embedder/scoped_ipc_support.h>
#include <libmems/common_types.h>
#include <libmems/test_fakes.h>
#include "iioservice/daemon/sensor_device_impl.h"
#include "iioservice/daemon/test_fakes.h"
#include "mojo/sensor.mojom.h"
namespace iioservice {
namespace {
constexpr char kDeviceAttrName[] = "FakeDeviceAttr";
constexpr char kDeviceAttrValue[] = "FakeDeviceAttrValue";
constexpr char kChnAttrName[] = "FakeChnAttr";
constexpr char kChnAttrValue[] = "FakeChnValue";
constexpr char kFakeDeviceName[] = "FakeDevice";
constexpr int kFakeDeviceId = 2;
constexpr char kFakeChannelId[] = "FakeChannel";
constexpr int kFakeChannelRawValue = 2020;
class SensorDeviceImplTest : public ::testing::Test {
public:
SensorDeviceImplTest()
: ipc_thread_(std::make_unique<base::Thread>("IPCThread")),
remote_thread_(std::make_unique<base::Thread>("PtrThread")) {}
void SetTimeoutOnThread() {
CHECK(remote_thread_->task_runner()->BelongsToCurrentThread());
remote_->SetTimeout(0);
}
void GetAttributeOnThread() {
CHECK(remote_thread_->task_runner()->BelongsToCurrentThread());
remote_->GetAttribute(
kDeviceAttrName,
base::BindOnce([](const base::Optional<std::string>& value) {
EXPECT_TRUE(value.has_value());
EXPECT_EQ(value.value().compare(kDeviceAttrValue), 0);
}));
}
void SetFrequencyOnThread() {
CHECK(remote_thread_->task_runner()->BelongsToCurrentThread());
remote_->SetFrequency(libmems::fakes::kFakeSamplingFrequency,
base::BindOnce([](double result_freq) {
EXPECT_EQ(result_freq,
libmems::fakes::kFakeSamplingFrequency);
}));
}
void ReadSamplesOnThread(base::RepeatingClosure closure) {
CHECK(remote_thread_->task_runner()->BelongsToCurrentThread());
CHECK(remote_thread_->task_runner()->BelongsToCurrentThread());
double frequency = libmems::fakes::kFakeSamplingFrequency;
remote_->SetFrequency(frequency, base::BindOnce([](double result_freq) {
EXPECT_EQ(result_freq,
libmems::fakes::kFakeSamplingFrequency);
}));
remote_->SetChannelsEnabled(
std::vector<int32_t>{0, 2, 3}, true,
base::BindOnce([](const std::vector<int32_t>& failed_indices) {
EXPECT_TRUE(failed_indices.empty());
}));
// No pause: setting pause_index_ to the size of fake data
fake_observer_ = fakes::FakeSamplesObserver::Create(
remote_thread_->task_runner(), std::move(closure), device_,
std::multiset<std::pair<int, cros::mojom::ObserverErrorType>>(),
frequency, frequency, frequency, frequency,
base::size(libmems::fakes::kFakeAccelSamples));
remote_->StartReadingSamples(fake_observer_->GetRemote());
}
void SetChannelsOnThread() {
CHECK(remote_thread_->task_runner()->BelongsToCurrentThread());
remote_->GetAllChannelIds(
base::BindOnce([](const std::vector<std::string>& chn_ids) {
EXPECT_EQ(chn_ids.size(), base::size(libmems::fakes::kFakeAccelChns));
for (int i = 0; i < chn_ids.size(); ++i)
EXPECT_EQ(chn_ids[i], libmems::fakes::kFakeAccelChns[i]);
}));
std::vector<int32_t> indices = {0, 2};
remote_->SetChannelsEnabled(
indices, true,
base::BindOnce([](const std::vector<int32_t>& failed_indices) {
EXPECT_TRUE(failed_indices.empty());
}));
indices.clear();
for (int i = 0; i < base::size(libmems::fakes::kFakeAccelChns); ++i)
indices.push_back(i);
remote_->GetChannelsEnabled(
indices, base::BindOnce([](const std::vector<bool>& enabled) {
EXPECT_EQ(enabled.size(), base::size(libmems::fakes::kFakeAccelChns));
for (int i = 0; i < enabled.size(); ++i)
EXPECT_EQ(enabled[i], i % 2 == 0);
}));
}
void GetChannelsAttributesOnThread() {
CHECK(remote_thread_->task_runner()->BelongsToCurrentThread());
std::vector<int32_t> indices;
for (int i = 0; i < base::size(libmems::fakes::kFakeAccelChns); ++i)
indices.push_back(i);
remote_->GetChannelsAttributes(
indices, kChnAttrName,
base::BindOnce(
[](const std::vector<base::Optional<std::string>>& values) {
EXPECT_EQ(values.size(),
base::size(libmems::fakes::kFakeAccelChns));
for (int i = 0; i < values.size(); ++i) {
if (i % 2 == 0) {
EXPECT_TRUE(values[i].has_value());
EXPECT_EQ(values[i].value().compare(kChnAttrValue), 0);
}
}
}));
}
protected:
void SetUp() override {
context_ = std::make_unique<libmems::fakes::FakeIioContext>();
auto device = std::make_unique<libmems::fakes::FakeIioDevice>(
nullptr, fakes::kAccelDeviceName, fakes::kAccelDeviceId);
EXPECT_TRUE(device->WriteStringAttribute(
kSamplingFrequencyAvailable, fakes::kFakeSamplingFrequencyAvailable));
EXPECT_TRUE(device->WriteDoubleAttribute(libmems::kHWFifoTimeoutAttr, 0.0));
EXPECT_TRUE(
device->WriteStringAttribute(kDeviceAttrName, kDeviceAttrValue));
auto chn_accel_x = std::make_unique<libmems::fakes::FakeIioChannel>(
libmems::fakes::kFakeAccelChns[0], true);
auto chn_accel_y = std::make_unique<libmems::fakes::FakeIioChannel>(
libmems::fakes::kFakeAccelChns[1], true);
auto chn_accel_z = std::make_unique<libmems::fakes::FakeIioChannel>(
libmems::fakes::kFakeAccelChns[2], true);
auto chn_timestamp = std::make_unique<libmems::fakes::FakeIioChannel>(
libmems::fakes::kFakeAccelChns[3], true);
chn_accel_x->WriteStringAttribute(kChnAttrName, kChnAttrValue);
chn_accel_z->WriteStringAttribute(kChnAttrName, kChnAttrValue);
device->AddChannel(std::move(chn_accel_x));
device->AddChannel(std::move(chn_accel_y));
device->AddChannel(std::move(chn_accel_z));
device->AddChannel(std::move(chn_timestamp));
device_ = device.get();
context_->AddDevice(std::move(device));
auto fake_device = std::make_unique<libmems::fakes::FakeIioDevice>(
nullptr, kFakeDeviceName, kFakeDeviceId);
EXPECT_TRUE(fake_device->WriteStringAttribute(
kSamplingFrequencyAvailable, fakes::kFakeSamplingFrequencyAvailable));
EXPECT_TRUE(
fake_device->WriteDoubleAttribute(libmems::kHWFifoTimeoutAttr, 0.0));
auto fake_chn =
std::make_unique<libmems::fakes::FakeIioChannel>(kFakeChannelId, true);
fake_chn->WriteNumberAttribute(libmems::kRawAttr, kFakeChannelRawValue);
fake_device->AddChannel(std::move(fake_chn));
fake_device_ = fake_device.get();
context_->AddDevice(std::move(fake_device));
task_executor_ = std::make_unique<base::SingleThreadTaskExecutor>(
base::MessagePumpType::IO);
EXPECT_TRUE(ipc_thread_->Start());
EXPECT_TRUE(remote_thread_->Start());
ipc_support_ = std::make_unique<mojo::core::ScopedIPCSupport>(
ipc_thread_->task_runner(),
mojo::core::ScopedIPCSupport::ShutdownPolicy::CLEAN);
}
void TearDown() override {
remote_thread_->task_runner()->PostTask(
FROM_HERE, base::BindOnce(&SensorDeviceImplTest::ResetRemote,
base::Unretained(this)));
remote_thread_->Stop();
sensor_device_.reset();
ipc_support_.reset();
ipc_thread_->Stop();
task_executor_.reset();
}
void SetupDevice() {
base::RunLoop run_loop;
ipc_thread_->task_runner()->PostTask(
FROM_HERE,
base::BindOnce(&SensorDeviceImplTest::CreateDeviceOnThread,
base::Unretained(this), run_loop.QuitClosure()));
run_loop.Run();
}
void CreateDeviceOnThread(base::RepeatingClosure closure) {
CHECK(ipc_thread_->task_runner()->BelongsToCurrentThread());
sensor_device_ =
SensorDeviceImpl::Create(ipc_thread_->task_runner(), context_.get());
EXPECT_TRUE(sensor_device_);
remote_thread_->task_runner()->PostTask(
FROM_HERE, base::BindOnce(&SensorDeviceImplTest::BindRemote,
base::Unretained(this), std::move(closure)));
}
void BindRemote(base::RepeatingClosure closure) {
CHECK(remote_thread_->task_runner()->BelongsToCurrentThread());
sensor_device_->AddReceiver(
fakes::kAccelDeviceId,
remote_.BindNewPipeAndPassReceiver(remote_thread_->task_runner()));
EXPECT_TRUE(remote_);
closure.Run();
}
void ResetRemote() {
CHECK(remote_thread_->task_runner()->BelongsToCurrentThread());
remote_.reset();
}
std::unique_ptr<libmems::fakes::FakeIioContext> context_;
libmems::fakes::FakeIioDevice* device_;
libmems::fakes::FakeIioDevice* fake_device_;
std::unique_ptr<base::SingleThreadTaskExecutor> task_executor_;
std::unique_ptr<base::Thread> ipc_thread_;
std::unique_ptr<base::Thread> remote_thread_;
std::unique_ptr<mojo::core::ScopedIPCSupport> ipc_support_;
SensorDeviceImpl::ScopedSensorDeviceImpl sensor_device_ = {
nullptr, SensorDeviceImpl::SensorDeviceImplDeleter};
mojo::Remote<cros::mojom::SensorDevice> remote_;
fakes::FakeSamplesObserver::ScopedFakeSamplesObserver fake_observer_ = {
nullptr, fakes::FakeSamplesObserver::ObserverDeleter};
};
TEST_F(SensorDeviceImplTest, SetTimeout) {
SetupDevice();
remote_thread_->task_runner()->PostTask(
FROM_HERE, base::BindOnce(&SensorDeviceImplTest::SetTimeoutOnThread,
base::Unretained(this)));
}
TEST_F(SensorDeviceImplTest, GetAttribute) {
SetupDevice();
remote_thread_->task_runner()->PostTask(
FROM_HERE, base::BindOnce(&SensorDeviceImplTest::GetAttributeOnThread,
base::Unretained(this)));
}
TEST_F(SensorDeviceImplTest, SetFrequency) {
SetupDevice();
remote_thread_->task_runner()->PostTask(
FROM_HERE, base::BindOnce(&SensorDeviceImplTest::SetFrequencyOnThread,
base::Unretained(this)));
}
TEST_F(SensorDeviceImplTest, ReadSamples) {
SetupDevice();
base::RunLoop run_loop;
remote_thread_->task_runner()->PostTask(
FROM_HERE,
base::BindOnce(&SensorDeviceImplTest::ReadSamplesOnThread,
base::Unretained(this), run_loop.QuitClosure()));
run_loop.Run();
}
TEST_F(SensorDeviceImplTest, SetChannels) {
SetupDevice();
remote_thread_->task_runner()->PostTask(
FROM_HERE, base::BindOnce(&SensorDeviceImplTest::SetChannelsOnThread,
base::Unretained(this)));
}
TEST_F(SensorDeviceImplTest, GetChannelsAttributes) {
SetupDevice();
remote_thread_->task_runner()->PostTask(
FROM_HERE,
base::BindOnce(&SensorDeviceImplTest::GetChannelsAttributesOnThread,
base::Unretained(this)));
}
} // namespace
} // namespace iioservice
| 34.456193 | 80 | 0.671811 | [
"vector"
] |
59f6f83b431cabc54e350c8416a2b60df9038a7b | 47,271 | cpp | C++ | Source/Gadgets/Statistics/Histogram/Histogram.cpp | spxuw/RFIM | 32b78fbb90c7008b1106b0cff4f8023ae83c9b6d | [
"MIT"
] | null | null | null | Source/Gadgets/Statistics/Histogram/Histogram.cpp | spxuw/RFIM | 32b78fbb90c7008b1106b0cff4f8023ae83c9b6d | [
"MIT"
] | null | null | null | Source/Gadgets/Statistics/Histogram/Histogram.cpp | spxuw/RFIM | 32b78fbb90c7008b1106b0cff4f8023ae83c9b6d | [
"MIT"
] | null | null | null | #include "Histogram.h"
// P(k) = C(N-1,k) p^k (1-p)^(N-1-k)
double Binomial(int N, double p, int k)
{
double Pk = 1;
for (int i=1; i<=k ; i++)
Pk *= (N-i)*p/(double)i;
for (int i=1; i<=N-1-k; i++)
Pk *= (1-p);
return Pk;
}
///////////////////////////////////////////////////////////////////////////
// case 3: log bin for discrete distribution
void GetHistogram(const vector<int>& X, double ratio, char* fname)
{
int N = X.size();
double Xmax, Xmin, Xave, Xvar, Xerror;
Statistics(X, Xmax, Xmin, Xave, Xvar, Xerror);
if(Xmin==0) {
cout << "Note that Xmin = 0.\n";
Xmin=1;
}
int Nbins = (int)(floor(log(Xmax/Xmin)/log(ratio))) + 1;
Bin* Binarray = new Bin [Nbins];
for(int i=0; i<Nbins; i++) // initialize these bins
{
if(i==0)
Binarray[i].below = Xmin;
else
Binarray[i].below = Binarray[i-1].above;
Binarray[i].above = Binarray[i].below*ratio;
Binarray[i].count = 0;
}// end of initializing these bins
//cout << "test" << endl;
int b = 0;
for(int i=0;i<N;i++) {
if(X[i]>0) { // Note that we don't consider isolated nodes (X[i]=0)
b = (int)( floor( log(X[i]/Xmin)/log(ratio) ) ); // get the index of the areabin
Binarray[b].count++; // for this bin, update it with new data point
}
}
int Dmax = 0;
int Dsum = 0;
for(int b=0;b<Nbins;b++) {
Dsum += Binarray[b].count;
if(Binarray[b].count>Dmax)
Dmax = Binarray[b].count;
}
//cout << "\n Dsum = " << Dsum;
//cout << "\n Dmax = " << Dmax << endl;
// save the distribution to file
char filename[256];
sprintf(filename,"%s", fname);
ofstream fout(filename, ios_base::out);
for(int b=0; b<Nbins; b++) {
Binarray[b].normalized_count = Binarray[b].count/(double)N;
fout << b << ' ';
fout.width(8); fout << Binarray[b].below << ' ';
fout.width(8); fout << Binarray[b].above << ' ';
fout.width(8); fout << Binarray[b].count << ' ';
fout.width(8); fout << Binarray[b].normalized_count << ' ';
fout << endl;
}// end of writing data for each bin
fout.close();
delete [] Binarray;
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// case 3: log bin for discrete distribution
void GetHistogram_Accumulatively(const vector<int>& X, double ratio, char* label, char* fname)
{
int N = X.size();
double Xmax, Xmin, Xave, Xvar, Xerror;
Statistics(X, Xmax, Xmin, Xave, Xvar, Xerror);
if(Xmin==0) {
cout << "Note that Xmin = 0.\n";
Xmin=1;
}
int Nbins = (int)(floor(log(Xmax/Xmin)/log(ratio))) + 1;
Bin* Binarray = new Bin [Nbins];
for(int i=0; i<Nbins; i++) // initialize these bins
{
if(i==0)
Binarray[i].below = Xmin;
else
Binarray[i].below = Binarray[i-1].above;
Binarray[i].above = Binarray[i].below*ratio;
Binarray[i].count = 0;
}// end of initializing these bins
//cout << "test" << endl;
int b = 0;
for(int i=0;i<N;i++) {
if(X[i]>0) { // Note that we don't consider isolated nodes (X[i]=0)
b = (int)( floor( log(X[i]/Xmin)/log(ratio) ) ); // get the index of the areabin
Binarray[b].count++; // for this bin, update it with new data point
}
}
int Dmax = 0;
int Dsum = 0;
for(int b=0;b<Nbins;b++) {
Dsum += Binarray[b].count;
if(Binarray[b].count>Dmax)
Dmax = Binarray[b].count;
}
//cout << "\n Dsum = " << Dsum;
//cout << "\n Dmax = " << Dmax << endl;
// save the distribution to file
char filename[256];
sprintf(filename,"%s", fname);
ofstream fout(filename, ios_base::app);
fout << "\n######### " << label << " ##########" << endl;
for(int b=0; b<Nbins; b++) {
Binarray[b].normalized_count = Binarray[b].count/(double)N;
fout << b << ' ';
fout.width(8); fout << Binarray[b].below << ' ';
fout.width(8); fout << Binarray[b].above << ' ';
fout.width(8); fout << Binarray[b].count << ' ';
fout.width(8); fout << Binarray[b].normalized_count << ' ';
fout << endl;
}// end of writing data for each bin
fout.close();
delete [] Binarray;
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// log bin for discrete distribution, for GKK model
void GetHistogram(const vector<int>& X, double ratio, char* fname, double& Kmean, double& K2mean)
{
int N = X.size();
double Xmax, Xmin, Xave, Xvar, Xerror;
Statistics(X, Xmax, Xmin, Xave, Xvar, Xerror);
Kmean = Xave;
K2mean = Xvar + Xave*Xave;
//cout << "\n Kmean = " << Kmean << endl; //test
if(Xmin==0) {
cout << "Note that Xmin = 0.\n";
Xmin=1;
}
int Nbins = (int)(floor(log(Xmax/Xmin)/log(ratio))) + 1;
Bin* Binarray = new Bin [Nbins];
for(int i=0; i<Nbins; i++) { // initialize these bins
if(i==0)
Binarray[i].below = Xmin;
else
Binarray[i].below = Binarray[i-1].above;
Binarray[i].above = Binarray[i].below*ratio;
Binarray[i].count = 0;
}// end of initializing these bins
//cout << "test" << endl;
int b = 0;
for(int i=0;i<N;i++) {
if(X[i]>0) {// Note that we don't consider isolated nodes (X[i]=0)
b = (int)( floor( log(X[i]/Xmin)/log(ratio) ) ); // get the index of the areabin
Binarray[b].count++; // for this bin, update it with new data point
}
}
int Dmax = 0;
int Dsum = 0;
for(int b=0;b<Nbins;b++) {
Dsum += Binarray[b].count;
if(Binarray[b].count>Dmax)
Dmax = Binarray[b].count;
}
//cout << "\n Dsum = " << Dsum;
//cout << "\n Dmax = " << Dmax << endl;
// save the distribution to file
char filename[256];
sprintf(filename,"%s", fname);
ofstream fout(filename, ios_base::out);
for(int b=0; b<Nbins; b++) {
Binarray[b].normalized_count = Binarray[b].count/(double)N;
fout << b << ' ';
fout.width(8); fout << Binarray[b].below << ' ';
fout.width(8); fout << Binarray[b].above << ' ';
fout.width(8); fout << Binarray[b].count << ' ';
fout.width(8); fout << Binarray[b].normalized_count << ' ';
fout << endl;
}// end of writing data for each bin
fout.close();
delete [] Binarray;
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// log bin for discrete distribution
void GetHistogram(const vector<int>& X, double ratio, char* fname, double& Kmean, double& K2mean, double& Kmax)
{
int N = X.size();
double Xmax, Xmin, Xave, Xvar, Xerror;
Statistics(X, Xmax, Xmin, Xave, Xvar, Xerror);
Kmax = Xmax;
Kmean = Xave;
K2mean = Xvar + Xave*Xave;
//cout << "\n Kmean = " << Kmean << endl; //test
if(Xmin==0) {
cout << "Note that Xmin = 0.\n";
Xmin=1;
}
int Nbins = (int)(floor(log(Xmax/Xmin)/log(ratio))) + 1;
Bin* Binarray = new Bin [Nbins];
for(int i=0; i<Nbins; i++) { // initialize these bins
if(i==0)
Binarray[i].below = Xmin;
else
Binarray[i].below = Binarray[i-1].above;
Binarray[i].above = Binarray[i].below*ratio;
Binarray[i].count = 0;
}// end of initializing these bins
//cout << "test" << endl;
int b = 0;
for(int i=0;i<N;i++) {
if(X[i]>0) { // Note that we don't consider isolated nodes (X[i]=0)
b = (int)( floor( log(X[i]/Xmin)/log(ratio) ) ); // get the index of the areabin
Binarray[b].count++; // for this bin, update it with new data point
}
}
int Dmax = 0;
int Dsum = 0;
for(int b=0;b<Nbins;b++) {
Dsum += Binarray[b].count;
if(Binarray[b].count>Dmax)
Dmax = Binarray[b].count;
}
//cout << "\n Dsum = " << Dsum;
//cout << "\n Dmax = " << Dmax << endl;
// save the distribution to file
char filename[256];
sprintf(filename,"%s", fname);
ofstream fout(filename, ios_base::out);
for(int b=0; b<Nbins; b++) {
Binarray[b].normalized_count = Binarray[b].count/(double)N;
fout << b << ' ';
fout.width(8); fout << Binarray[b].below << ' ';
fout.width(8); fout << Binarray[b].above << ' ';
fout.width(8); fout << Binarray[b].count << ' ';
fout.width(8); fout << Binarray[b].normalized_count << ' ';
fout << endl;
}// end of writing data for each bin
fout.close();
delete [] Binarray;
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// linear bin for discrete distribution
void GetHistogram(const vector<int>& X)
{
int N = X.size();
double Xmax, Xmin, Xave, Xvar, Xerror;
Statistics(X, Xmax, Xmin, Xave, Xvar, Xerror);
double Xbinwidth = 1;//(Xmax-Xmin)/Nbins; // h bin's width
int Nbins = Xmax-Xmin+1;
vector<int> D(Nbins,0); // the bin vector
for(int i=0;i<N;i++) {
int b = (int)floor((X[i]-Xmin)/Xbinwidth);
if(b>=Nbins) {
cout << "\n (X[i]-Xmin)/Xbinwidth = " << (X[i]-Xmin)/Xbinwidth << " b = " << b << endl; //test
b = Nbins-1;
}
if(b<0) {
cout << "\n (X[i]-Xmin)/Xbinwidth = " << (X[i]-Xmin)/Xbinwidth << " b = " << b << endl; //test
b = 0;
}
D[b]++; // get the histogram
}
int Dmax = 0;
int Dsum = 0;
for(int b=0;b<Nbins;b++) {
Dsum += D[b];
if(D[b]>Dmax)
Dmax = D[b];
}
//cout << "\n Dsum = " << Dsum;
//cout << "\n Dmax = " << Dmax << endl;
// save the distribution to file
char filename[256];
sprintf(filename,"Dist.dat");
ofstream fout(filename, ios_base::out);
for(int b=0; b<Nbins; b++) {
//fout << Xmin+(b)*Xbinwidth << ' ' << D[b]/(double)Dsum << endl;
//fout << Xmin+(b+0.5)*Xbinwidth << ' ' << D[b]/(double)N << endl;
//fout << Xmin+(b+0.5)*Xbinwidth << ' ' << D[b]/(double)(N*Xbinwidth) << endl; // this way we get a normalized histogram, i.e. including a total surface area equal to unity
fout << Xmin+(b+0.5)*Xbinwidth << ' ' << D[b]/(double)N << ' ' << D[b]/(double)(N*Xbinwidth) << endl;
}
fout.close();
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// case 1: linear bin for discrete distribution
void GetHistogram(const vector<int>& X, char* fname)
{
int N = X.size();
double Xmax, Xmin, Xave, Xvar, Xerror;
Statistics(X, Xmax, Xmin, Xave, Xvar, Xerror);
double Xbinwidth = 1;//(Xmax-Xmin)/Nbins; // h bin's width
int Nbins = Xmax-Xmin+1;
vector<int> D(Nbins,0); // the bin vector
for(int i=0;i<N;i++) {
int b = (int)floor((X[i]-Xmin)/Xbinwidth);
if(b>=Nbins) {
cout << "\n (X[i]-Xmin)/Xbinwidth = " << (X[i]-Xmin)/Xbinwidth << " b = " << b << endl; //test
b = Nbins-1;
}
if(b<0) {
cout << "\n (X[i]-Xmin)/Xbinwidth = " << (X[i]-Xmin)/Xbinwidth << " b = " << b << endl; //test
b = 0;
}
D[b]++; // get the histogram
}
int Dmax = 0;
int Dsum = 0;
for(int b=0;b<Nbins;b++) {
Dsum += D[b];
if(D[b]>Dmax)
Dmax = D[b];
}
//cout << "\n Dsum = " << Dsum;
//cout << "\n Dmax = " << Dmax << endl;
// save the distribution to file
char filename[256];
sprintf(filename,"%s", fname);
ofstream fout(filename, ios_base::out);
for(int b=0; b<Nbins; b++) {
//fout << Xmin+(b)*Xbinwidth << ' ' << D[b]/(double)Dsum << endl;
if(D[b]>0)
//fout << Xmin+(b)*Xbinwidth << " " << D[b]/(double)N << " " << D[b] << endl;
//fout << Xmin+(b+0.5)*Xbinwidth << ' ' << D[b]/(double)(N*Xbinwidth) << endl; // this way we get a normalized histogram, i.e. including a total surface area equal to unity
fout << Xmin+(b)*Xbinwidth << " " << D[b]/(double)N << " " << D[b]/(double)(N*Xbinwidth) << endl;
}
fout.close();
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// linear bin for discrete distribution
void GetHistogram(const vector<int>& X, char* fname, double& Kmean, double& K2mean, double& Kmax)
{
int N = X.size();
double Xmax, Xmin, Xave, Xvar, Xerror;
Statistics(X, Xmax, Xmin, Xave, Xvar, Xerror);
Kmax = Xmax;
Kmean = Xave;
K2mean = Xvar + Xave*Xave;
double Xbinwidth = 1;//(Xmax-Xmin)/Nbins; // h bin's width
int Nbins = Xmax-Xmin+1;
vector<int> D(Nbins,0); // the bin vector
for(int i=0;i<N;i++) {
int b = (int)floor((X[i]-Xmin)/Xbinwidth);
if(b>=Nbins) {
cout << "\n (X[i]-Xmin)/Xbinwidth = " << (X[i]-Xmin)/Xbinwidth << " b = " << b << endl; //test
b = Nbins-1;
}
if(b<0) {
cout << "\n (X[i]-Xmin)/Xbinwidth = " << (X[i]-Xmin)/Xbinwidth << " b = " << b << endl; //test
b = 0;
}
D[b]++; // get the histogram
}
int Dmax = 0;
int Dsum = 0;
for(int b=0;b<Nbins;b++) {
Dsum += D[b];
if(D[b]>Dmax)
Dmax = D[b];
}
//cout << "\n Dsum = " << Dsum;
//cout << "\n Dmax = " << Dmax << endl;
// save the distribution to file
char filename[256];
sprintf(filename,"%s", fname);
ofstream fout(filename, ios_base::out);
for(int b=0; b<Nbins; b++) {
//fout << Xmin+(b)*Xbinwidth << ' ' << D[b]/(double)Dsum << endl;
//fout << Xmin+(b)*Xbinwidth << " " << D[b]/(double)N << endl;
//fout << Xmin+(b+0.5)*Xbinwidth << ' ' << D[b]/(double)(N*Xbinwidth) << endl; // this way we get a normalized histogram, i.e. including a total surface area equal to unity
fout << Xmin+(b)*Xbinwidth << " " << D[b]/(double)N << ' ' << D[b]/(double)(N*Xbinwidth) << endl;
}
fout.close();
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// linear bin for discrete distribution, for Erdos-Renyi model. p is the connection probability
void GetHistogram_ER(const vector<int>& X, double p, char* fname)
{
int N = X.size();
double Xmax, Xmin, Xave, Xvar, Xerror;
Statistics(X, Xmax, Xmin, Xave, Xvar, Xerror);
double Xbinwidth = 1;//(Xmax-Xmin)/Nbins; // h bin's width
int Nbins = Xmax-Xmin+1;
vector<int> D(Nbins,0); // the bin vector
for(int i=0;i<N;i++) {
int b = (int)floor((X[i]-Xmin)/Xbinwidth);
if(b>=Nbins) {
cout << "\n (X[i]-Xmin)/Xbinwidth = " << (X[i]-Xmin)/Xbinwidth << " b = " << b << endl; //test
b = Nbins-1;
}
if(b<0) {
cout << "\n (X[i]-Xmin)/Xbinwidth = " << (X[i]-Xmin)/Xbinwidth << " b = " << b << endl; //test
b = 0;
}
D[b]++; // get the histogram
}
int Dmax = 0;
int Dsum = 0;
for(int b=0;b<Nbins;b++) {
Dsum += D[b];
if(D[b]>Dmax)
Dmax = D[b];
}
//cout << "\n Dsum = " << Dsum;
//cout << "\n Dmax = " << Dmax << endl;
// save the distribution to file
//char filename[256];
//sprintf(filename,"Dist.dat");
ofstream fout(fname, ios_base::out);
for(int b=0; b<Nbins; b++) {
int k = Xmin + b;
//fout << Xmin+(b)*Xbinwidth << ' ' << D[b]/(double)Dsum << endl;
//fout << Xmin+(b)*Xbinwidth << " " << D[b]/(double)N << " " << Binomial(N, p, k) << endl;
fout << Xmin+(b)*Xbinwidth << " "
<< D[b]/(double)N << " "
<< Poisson(Xave, k) << " "
<< Binomial(N, p, k) << endl;
}
fout.close();
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// linear bin for discrete distribution, for Erdos-Renyi model. p is the connection probability
void GetHistogram_ER(const vector<int>& X, double p, char* fname, double& Kmean, double& K2mean, double& Kmax)
{
int N = X.size();
double Xmax, Xmin, Xave, Xvar, Xerror;
Statistics(X, Xmax, Xmin, Xave, Xvar, Xerror);
Kmax = Xmax;
Kmean = Xave;
K2mean = Xvar + Xave*Xave;
double Xbinwidth = 1;//(Xmax-Xmin)/Nbins; // h bin's width
int Nbins = Xmax-Xmin+1;
vector<int> D(Nbins,0); // the bin vector
for(int i=0;i<N;i++) {
int b = (int)floor((X[i]-Xmin)/Xbinwidth);
if(b>=Nbins) {
cout << "\n (X[i]-Xmin)/Xbinwidth = " << (X[i]-Xmin)/Xbinwidth << " b = " << b << endl; //test
b = Nbins-1;
}
if(b<0) {
cout << "\n (X[i]-Xmin)/Xbinwidth = " << (X[i]-Xmin)/Xbinwidth << " b = " << b << endl; //test
b = 0;
}
D[b]++; // get the histogram
}
int Dmax = 0;
int Dsum = 0;
for(int b=0;b<Nbins;b++) {
Dsum += D[b];
if(D[b]>Dmax)
Dmax = D[b];
}
//cout << "\n Dsum = " << Dsum;
//cout << "\n Dmax = " << Dmax << endl;
// save the distribution to file
ofstream fout(fname, ios_base::out);
for(int b=0; b<Nbins; b++) {
int k = Xmin + b;
//fout << Xmin+(b)*Xbinwidth << ' ' << D[b]/(double)Dsum << endl;
//fout << Xmin+(b)*Xbinwidth << " " << D[b]/(double)N << " " << Binomial(N, p, k) << endl;
fout << Xmin+(b)*Xbinwidth << " "
<< D[b]/(double)N << " "
<< Poisson(Xave, k) << " "
<< Binomial(N, p, k) << endl;
}
fout.close();
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// linear bin for continuous distribution
void GetHistogram(const vector<int>& X, int Nbins)
{
int N = X.size();
double Xmax, Xmin, Xave, Xvar, Xerror;
Statistics(X, Xmax, Xmin, Xave, Xvar, Xerror);
double Xbinwidth = (Xmax-Xmin)/Nbins; // h bin's width
vector<int> D(Nbins,0); // the bin vector
for(int i=0;i<N;i++) {
int b = (int)floor((X[i]-Xmin)/Xbinwidth);
if(b>=Nbins) {
cout << "\n (X[i]-Xmin)/Xbinwidth = " << (X[i]-Xmin)/Xbinwidth << " b = " << b << endl; //test
b = Nbins-1;
}
if(b<0) {
cout << "\n (X[i]-Xmin)/Xbinwidth = " << (X[i]-Xmin)/Xbinwidth << " b = " << b << endl; //test
b = 0;
}
D[b]++; // get the histogram
}
int Dmax = 0;
int Dsum = 0;
for(int b=0;b<Nbins;b++) {
Dsum += D[b];
if(D[b]>Dmax)
Dmax = D[b];
}
//cout << "\n Dsum = " << Dsum;
//cout << "\n Dmax = " << Dmax << endl;
// save the distribution to file
char filename[256];
sprintf(filename,"Dist.dat");
ofstream fout(filename, ios_base::out);
for(int b=0; b<Nbins; b++) {
//fout << Xmin+(b+0.5)*Xbinwidth << ' ' << D[b]/(double)Dmax << endl;
//fout << Xmin+(b+0.5)*Xbinwidth << ' ' << D[b] << endl;
//fout << Xmin+(b+0.5)*Xbinwidth << ' ' << D[b]/(double)(N*Xbinwidth) << endl; // this way we get a normalized histogram, i.e. including a total surface area equal to unity
fout << Xmin+(b+0.5)*Xbinwidth << ' ' << D[b] << ' ' << D[b]/(double)(N*Xbinwidth) << endl;
}
fout.close();
}
///////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
// case 4: log bin for continous distribution, e.g. the distribution of betweeness
void GetHistogram(const vector<double>& X, double ratio, char* fname)
{
int N = X.size();
double Xmax, Xmin, Xave, Xvar, Xerror;
Statistics(X, Xmax, Xmin, Xave, Xvar, Xerror);
double Xsmin;
if(Xmin==0) {
cout << "Note that Xmin = 0.\n";
Xsmin = GetXsecondmin(X, Xmin);
cout << "We get the second minimum value: " << Xsmin << endl;
}
else {
Xsmin = Xmin;
}
int Nbins = int(floor(log(Xmax/Xsmin)/log(ratio))) + 1;
Bin* Binarray = new Bin [Nbins];
for(int i=0; i<Nbins; i++){ // initialize these bins
if(i==0)
Binarray[i].below = Xsmin;
else
Binarray[i].below = Binarray[i-1].above;
Binarray[i].above = Binarray[i].below*ratio;
Binarray[i].count = 0;
}// end of initializing these bins
vector<double> Bin0;
int b = 0;
for(int i=0;i<N;i++) {
if(X[i]>0) {// Note that we don't consider isolated nodes (X[i]=0)
b = (int)( floor( log(X[i]/Xsmin)/log(ratio) ) ); // get the index of the areabin
Binarray[b].count++; // for this bin, update it with new data point
}
else {
Bin0.push_back(X[i]);
}
}
int Dmax = 0;
int Dsum = 0;
for(int b=0;b<Nbins;b++) {
Dsum += Binarray[b].count;
if(Binarray[b].count>Dmax)
Dmax = Binarray[b].count;
}
//cout << "\n Dsum = " << Dsum;
//cout << "\n Dmax = " << Dmax << endl;
// save the distribution to file
char filename[256];
sprintf(filename,"%s", fname);
ofstream fout(filename, ios_base::out);
if(Xmin<Xsmin) {
fout << -1 << ' ';
fout.width(8); fout << 0 << ' ';
fout.width(8); fout << 0 << ' ';
fout.width(8); fout << Bin0.size() << ' ';
fout.width(8); fout << Bin0.size()/(double)N << ' ';
fout << endl;
}
for(int b=0; b<Nbins; b++) {
Binarray[b].normalized_count = Binarray[b].count/(double)N;
fout << b << ' ';
fout.width(8); fout << Binarray[b].below << ' ';
fout.width(8); fout << Binarray[b].above << ' ';
fout.width(8); fout << Binarray[b].count << ' ';
fout.width(8); fout << Binarray[b].normalized_count << ' ';
fout << endl;
}// end of writing data for each bin
fout.close();
delete [] Binarray;
}
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////
// log bin for continous distribution, e.g. the distribution of Cs
void GetHistogram(const vector<double>& X, double ratio, char* fname, double& Xmin)
{
int N = X.size();
double Xmax, Xave, Xvar, Xerror;
Statistics(X, Xmax, Xmin, Xave, Xvar, Xerror);
//cout << "Xmin = " << Xmin << endl;
int Nbins = int(floor(log(Xmax/Xmin)/log(ratio))) + 1;
Bin* Binarray = new Bin [Nbins];
for(int i=0; i<Nbins; i++) { // initialize these bins
if(i==0)
Binarray[i].below = Xmin;
else
Binarray[i].below = Binarray[i-1].above;
Binarray[i].above = Binarray[i].below*ratio;
Binarray[i].count = 0;
}// end of initializing these bins
int b = 0;
for(int i=0;i<N;i++) {
if(X[i]>0) // Note that we don't consider isolated nodes (X[i]=0)
b = (int)( floor( log(X[i]/Xmin)/log(ratio) ) ); // get the index of the areabin
Binarray[b].count++; // for this bin, update it with new data point
}
int Dmax = 0;
int Dsum = 0;
for(int b=0;b<Nbins;b++) {
Dsum += Binarray[b].count;
if(Binarray[b].count>Dmax)
Dmax = Binarray[b].count;
}
//cout << "\n Dsum = " << Dsum;
//cout << "\n Dmax = " << Dmax << endl;
// save the distribution to file
char filename[256];
sprintf(filename,"%s", fname);
ofstream fout(filename, ios_base::out);
for(int b=0; b<Nbins; b++) {
Binarray[b].normalized_count = Binarray[b].count/(double)N;
fout << b << ' ';
fout.width(8); fout << Binarray[b].below << ' ';
fout.width(8); fout << Binarray[b].above << ' ';
fout.width(8); fout << Binarray[b].count << ' ';
fout.width(8); fout << Binarray[b].normalized_count << ' ';
fout << endl;
}// end of writing data for each bin
fout.close();
delete [] Binarray;
}
///////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// case 2: linear bin for continuous distribution, e.g. the eigenvalue distribution or the Csl distribution
void GetHistogram(const vector<double>& X, int Nbins, char* fname)
{
int N = X.size();
//cout << "Size= " << N << endl; //test
double Xmax, Xmin, Xave, Xvar, Xerror;
Statistics(X, Xmax, Xmin, Xave, Xvar, Xerror);
// save the distribution to file
char filename[256];
sprintf(filename,"%s", fname);
//ofstream fout(filename, ios_base::app);
ofstream fout(filename, ios_base::out);
double Xbinwidth = (Xmax-Xmin)/Nbins; // h bin's width
if(Xbinwidth>1e-10) {
vector<int> D(Nbins,0); // the bin vector
for(int i=0;i<N;i++) {
int b = (int)floor((X[i]-Xmin)/Xbinwidth);
if(b>=Nbins){
//cout << "\n (X[i]-Xmin)/Xbinwidth = " << (X[i]-Xmin)/Xbinwidth << " b = " << b << endl; //test
b = Nbins-1;
}
if(b<0){
//cout << "\n (X[i]-Xmin)/Xbinwidth = " << (X[i]-Xmin)/Xbinwidth << " b = " << b << endl; //test
b = 0;
}
D[b]++; // get the histogram
}
int Dmax = 0;
int Dsum = 0;
for(int b=0;b<Nbins;b++){
Dsum += D[b];
if(D[b]>Dmax)
Dmax = D[b];
}
//cout << "\n Dsum = " << Dsum;
//cout << "\n Dmax = " << Dmax << endl;
for(int b=0; b<Nbins; b++) {
//fout << Xmin+(b+0.5)*Xbinwidth << ' ' << D[b]/(double)Dmax << endl;
//fout << Xmin+(b+0.5)*Xbinwidth << ' ' << D[b]/(double)(N) << endl;
//fout << Xmin+(b+0.5)*Xbinwidth << ' ' << D[b]/(double)(N*Xbinwidth) << endl; // this way we get a normalized histogram, i.e. including a total surface area equal to unity. Be careful if X is small, we will get a P(X) larger than 1.
fout << Xmin+(b+0.5)*Xbinwidth << ' ' << D[b]/(double)(N) << ' ' << D[b]/(double)(N*Xbinwidth) << endl;
}
}
else // if Xmin=Xmax, then this is a delta peak. To show this, we need the following trick.
{
fout << Xmin-1e-10 << ' ' << 0 << endl;
fout << Xmin << ' ' << 1 << endl;
fout << Xmax+1e-10 << ' ' << 0 << endl;
}
fout << endl;
fout << endl;
fout.close();
}
///////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// linear bin for continuous distribution,
// also export the result to two vectors:
// P: each element is a pair value: (w, P(w))
// Q: each element is a pair value: (w, wP(w)/<w>)
void GetPQw(const vector<double>& W, int Nbins, vector<ProbofW>& P, vector<ProbofW>& Q)
{
int N = W.size();
//cout << "Size= " << N << endl; //test
double Wmax, Wmin, Wave, Wvar, Werror;
Statistics(W, Wmax, Wmin, Wave, Wvar, Werror);
double Wbinwidth = (Wmax-Wmin)/Nbins; // h bin's width
if(Wbinwidth>1e-10) {
vector<int> D(Nbins,0); // the bin vector
for(int i=0;i<N;i++) {
int b = (int)floor((W[i]-Wmin)/Wbinwidth);
if(b>=Nbins) b = Nbins-1;
if(b<0) b = 0;
D[b]++; // get the histogram
}
int Dmax = 0;
int Dsum = 0;
for(int b=0;b<Nbins;b++){
Dsum += D[b];
if(D[b]>Dmax)
Dmax = D[b];
}
for(int b=0; b<Nbins; b++) {
ProbofW prob;
prob.w = Wmin+(b+0.5)*Wbinwidth;
prob.p = D[b]/(double)(N);
P.push_back(prob);
prob.p = prob.w * prob.p /Wave;
Q.push_back(prob);
}
}
else {// if Xmin=Xmax, then this is a delta peak. To show this, we need the following trick.
ProbofW prob;
//prob.w = Wmin-1e-10;
//prob.p = 0;
//P.push_back(prob);
//Q.push_back(prob);
prob.w = Wmin;
prob.p = 1;
P.push_back(prob);
Q.push_back(prob);
//prob.w = Wmin+1e-10;
//prob.p = 0;
//P.push_back(prob);
//Q.push_back(prob);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// linear bin for continuous distribution,
// also export the result to one vector:
// P: each element is a pair value: (w, P(w))
void GetPw(const vector<double>& W, int Nbins, vector<ProbofW>& P)
{
int N = W.size();
//cout << "Size= " << N << endl; //test
double Wmax, Wmin, Wave, Wvar, Werror;
Statistics(W, Wmax, Wmin, Wave, Wvar, Werror);
// force w in [0,1] (this is used in the edgetyping project, where the inner-module index z is in [0,1])
Wmin = 0;
Wmax = 1;
double Wbinwidth = (Wmax-Wmin)/Nbins; // h bin's width
if(Wbinwidth>1e-10) {
vector<int> D(Nbins,0); // the bin vector
for(int i=0;i<N;i++) {
int b = (int)floor((W[i]-Wmin)/Wbinwidth);
if(b>=Nbins) b = Nbins-1;
if(b<0) b = 0;
D[b]++; // get the histogram
}
int Dmax = 0;
int Dsum = 0;
for(int b=0;b<Nbins;b++){
Dsum += D[b];
if(D[b]>Dmax)
Dmax = D[b];
}
for(int b=0; b<Nbins; b++) {
ProbofW prob;
prob.w = Wmin + (b+0.5)*Wbinwidth;
prob.p = D[b]/(double)(N);
P.push_back(prob);
}
}
else {// if Xmin=Xmax, then this is a delta peak. To show this, we need the following trick.
ProbofW prob;
//prob.w = Wmin-1e-10;
//prob.p = 0;
//P.push_back(prob);
//Q.push_back(prob);
prob.w = Wmin;
prob.p = 1;
P.push_back(prob);
//prob.w = Wmin+1e-10;
//prob.p = 0;
//P.push_back(prob);
//Q.push_back(prob);
}
}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// The following is to get the discrete P(X) distribution (especially useful for small networks)
// It is copied from void Network::ClassifyCSL(vector<double>& CSL,
// vector<int>& CSLtype,
// int& NCSLtype,
// vector<double>& CSL_of_type,
// vector<int>& NUM_of_type)
// This template function doesn't work.
// Compiling error:
// Network.cpp:(.text+0x405d): undefined reference to `void GetDiscreteDistribution<int>(std::vector<int, std::allocator<int> >&, char*)'
// why??????????
/*
template <typename T>
void GetDiscreteDistribution(vector<T>& X, char* fname)
{
vector<int> Xtype;
int NXtype;
vector<T> X_of_type;
vector<int> NUM_of_type;
int N = X.size();
vector<T> Xtemp(N);
copy(X.begin(), X.end(), Xtemp.begin()); // copy X to Xtemp
sort(Xtemp.begin(), Xtemp.end() );// sort those X values in Xtemp
// get the number of X types
X_of_type.push_back(Xtemp[0]);
for(int i=1; i<N; i++) {
if(fabs(Xtemp[i]-Xtemp[i-1])>1e-10)
X_of_type.push_back(Xtemp[i]);
}
NXtype = X_of_type.size();
NUM_of_type.resize(NXtype, 0);
// get the Xtype for each node
Xtype.resize(N);
for(int i=0; i<N; i++) {
for(int type=0; type<NXtype; type++) {
if(fabs(X[i]-X_of_type[type])<=1e-10) {
Xtype[i] = type;
NUM_of_type[type]++;
break;
}
}
//cout << i << ' ' << Xl[i] << ' ' << Xltype[i] << endl; //debug
}
char filename [256];
sprintf(filename,"%s.discrete", fname);
ofstream fout(filename, ios_base::out);
cout.precision(10);
for(int type=0; type<NXtype; type++) {
cout << " X[" << type << "] = " << X_of_type[type]
<< " Num[" << type << "] = " << NUM_of_type[type]
<< " density[" << type << "] = " << NUM_of_type[type]/(double)N
<< endl;
fout << X_of_type[type] << " " << NUM_of_type[type]/(double)N << endl;
}
fout.close();
sprintf(filename,"%s.discrete.u", fname);
ofstream fout2(filename, ios_base::out);
for(int type=0; type<NXtype; type++) {
// to show these peaks in a better way, we add some ghost zeros around those peaks
double eps=1e-10;
fout2 << X_of_type[type] - eps << " " << 0 << endl;
fout2 << X_of_type[type] << " " << NUM_of_type[type]/(double)N << endl;
fout2 << X_of_type[type] + eps << " " << 0 << endl;
}
fout2.close();
}
*/
///////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////
//case 5: discrete without binning
void GetDiscreteDistribution(vector<double>& X, char* fname)
{
double Xmax, Xmin, Xave, Xvar, Xerror;
Statistics(X, Xmax, Xmin, Xave, Xvar, Xerror);
//////// designed for the calculation of Zscore:= (Xreal- <Xrand>)/ SigmaX ///////////////////////
ofstream Xout("X.dat", ios_base::app);
Xout << Xave << ' ' << sqrt(Xvar) << ' ' << Xerror << endl;
Xout.close();
///////////////////////////////////////////////////////////////////////////////////////////////////////
vector<int> Xtype;
int NXtype;
vector<double> X_of_type;
vector<int> NUM_of_type;
int N = X.size();
vector<double> Xtemp(X.begin(), X.end());
sort(Xtemp.begin(), Xtemp.end() );// sort those X values in Xtemp
// get the number of X types
X_of_type.push_back(Xtemp[0]);
for(int i=1; i<N; i++) {
if(fabs(Xtemp[i]-Xtemp[i-1])>1e-10)
X_of_type.push_back(Xtemp[i]);
}
NXtype = X_of_type.size();
NUM_of_type.resize(NXtype, 0);
// get the Xtype for each node
Xtype.resize(N);
for(int i=0; i<N; i++) {
for(int type=0; type<NXtype; type++) {
if(fabs(X[i]-X_of_type[type])<=1e-10) {
Xtype[i] = type;
NUM_of_type[type]++;
break;
}
}
//cout << i << ' ' << Xl[i] << ' ' << Xltype[i] << endl; //debug
}
// get Pr(X>x) i.e. the Complementary cumulative distribution function
vector<double> CCDF1(NXtype);
double temp = 0;
for(int type=0; type<NXtype; type++) {
temp += NUM_of_type[type];
CCDF1[type] = N-temp;
}
// Note that if we use this definition, then for the largest Xtype,
// CCDF[type] = 0, because Pr(X>xmax)=0
// Since eventually we want to plot CCDF on log-log plot, y=0 will cause trouble.
// To solve this issue, we can define CCDF to be Pr(X>=x), as Aaron Clauset did in his paper
// "Power-law distribution in emphricial data". If we use this definition we have
// get Pr(X>=x), another definition of the Complementary cumulative distribution function
vector<double> CCDF2(NXtype);
CCDF2[0] = N;
temp = 0;
for(int type=1; type<NXtype; type++) {
temp += NUM_of_type[type-1];
CCDF2[type] = N-temp;
}
char filename [256];
sprintf(filename,"%s.discrete", fname);
ofstream fout(filename, ios_base::out);
for(int type=0; type<NXtype; type++) {
fout << X_of_type[type] << " " // 1
<< NUM_of_type[type] << " " // 2
<< NUM_of_type[type]/(double)N << " " // 3
<< CCDF1[type] << " " // 4
<< CCDF1[type]/(double)N << " " // 5
<< CCDF2[type] << " " // 6
<< CCDF2[type]/(double)N << endl; // 7
}
fout.close();
sprintf(filename,"%s.discrete.u", fname);
ofstream fout2(filename, ios_base::out);
//ofstream fout2(filename, ios_base::app);
fout2 << endl << endl;
for(int type=0; type<NXtype; type++) {
// to show these peaks in a better way, we add some ghost zeros around those peaks
double eps=1e-10;
fout2 << X_of_type[type] - eps << " " << 0 << endl;
fout2 << X_of_type[type] << " " << NUM_of_type[type]/(double)N << endl;
fout2 << X_of_type[type] + eps << " " << 0 << endl;
}
fout2.close();
}
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
// comparison, not case sensitive.
bool compare_nocase (string first, string second)
{
unsigned int i=0;
while ( (i<first.length()) && (i<second.length()) )
{
if (tolower(first[i])<tolower(second[i])) return true;
else if (tolower(first[i])>tolower(second[i])) return false;
++i;
}
if (first.length()<second.length()) return true;
else return false;
}
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
void GetDiscreteDistribution(vector<string>& X, char* fname)
{
int N = X.size();
cout << "\n There are in total " << N << " items.\n";
set<string> itemset;
for(int i=0; i<N; i++) {
if(X[i]==" ") X[i]=" Unassigned ";
if(X[i]!=" subsystem " && X[i]!=" compartment ")
itemset.insert(X[i]);
}
list<string> liststr(itemset.begin(), itemset.end());
liststr.sort(compare_nocase);
vector<string> basket(liststr.begin(), liststr.end());
int Ntype = basket.size();
vector<int> count(Ntype,0);
int Ncount = 0;
for(int i=0; i<N; i++) {
for(int j=0; j<Ntype; j++) {
if(X[i]==basket[j]) { // how can we make sure that "tRNA charging" and "tRNA Charging" are the same
count[j]++;
Ncount++;
}
}
}
for(int j=0; j<Ntype; j++) {
if(basket[j]==" ") {
cout << j << ',' << basket[j] << endl;
}
}
char filename [256];
sprintf(filename,"%s.discrete", fname);
ofstream fout(filename, ios_base::out);
char filename1 [256];
sprintf(filename1,"%s.discrete.u", fname);
ofstream fout1(filename1, ios_base::out);
for(int j=0; j<Ntype; j++) {
cout << basket[j] << " ; " << count[j] << " ; " << count[j]/(double)Ncount << endl;
fout1 << basket[j] << " ; " << count[j] << " ; " << count[j]/(double)Ncount << endl;
fout << count[j] << " " << count[j]/(double)Ncount << endl;
}
fout.close();
fout1.close();
char filename2 [256];
sprintf(filename2,"%s.discrete.plotscript", fname);
ofstream gout(filename2, ios_base::out);
gout << "set terminal postscript eps enhanced color solid" << endl;
gout << "set size 1.0,2.75" << endl;
gout << "set ytics nomirror" << endl;
gout << "set boxwidth 0.4" << endl;
gout << "set yrange [0:*]" << endl;
gout << "set xlabel ' ' " << endl;
gout << "set xrange [*:*]" << endl;
gout << "set xtics nomirror rotate by -90 ( \\" << endl;
for(int j=0; j<Ntype-1; j++) {
gout << "\"" << basket[j] << "\" " << j << ",\\" << endl;
}
gout << "\"" << basket[Ntype-1] << "\" " << Ntype-1 << ")" << endl;
gout << "set ylabel '#' font 'Times, 25' " << endl;
gout << "set style data histogram" << endl;
gout << "set style histogram rowstacked" << endl;
gout << "set style fill solid border -1" << endl;
gout << "set key horizontal " << endl;
gout << "set output '" << filename << ".eps'" << endl;
gout << "plot \\" << endl;
gout << "'"<< filename << "' u 2 noti" << endl;
gout.close();
}
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
void GetPz(vector<int>& K, vector<double>& P, double& z)
{
int N = K.size();
//int kmin = 0; // by default
int kmax = 0;
double kave = 0;
for(int i=0; i<N; i++) {
if(K[i]>kmax)
kmax = K[i];
kave += K[i];
}
kave /= (double)N;
z = kave;
P.clear();
P.resize(kmax+1,0);
for(int k=0; k<=kmax; k++) {
P[k] = count(K.begin(), K.end(), k)/(double)N;
//cout << "P[k=" << k << "]=" << P[k] << endl;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
// P[k] : the degree distribution
// Q[k] : the remaining degree distribution
// z: the mean degree
void GetPQz(vector<int>& K, vector<double>& P, vector<double>& Q, double& z)
{
int N = K.size();
//int kmin = 0; // by default
int kmax = 0;
double kave = 0;
for(int i=0; i<N; i++) {
if(K[i]>kmax)
kmax = K[i];
kave += K[i];
}
kave /= (double)N;
z = kave;
P.clear();
P.resize(kmax+1,0);
for(int k=0; k<=kmax; k++) {
P[k] = count(K.begin(), K.end(), k)/(double)N;
//cout << "P[k=" << k << "]=" << P[k] << endl;
}
Q.clear();
//Q.resize(kmax,0);
//for(int k=0; k<kmax; k++) {
//Q[k] = (k+1)*P[k+1]/kave;
//}
Q.resize(kmax+1,0);
for(int k=0; k<=kmax; k++) {
Q[k] = k*P[k]/kave;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
// Count[k] : the degree histogram
// P[k] : the degree distribution
// Q[k] : the remaining degree distribution
// z: the mean degree
// v: the variance
void GetPQz(vector<int>& K, vector<int>& Count, vector<double>& P, vector<double>& Q, double& z, double& v)
{
int N = K.size();
//int kmin = 0; // by default
int kmax = 0;
double kave = 0;
for(int i=0; i<N; i++) {
if(K[i]>kmax)
kmax = K[i];
kave += K[i];
}
kave /= (double)N;
z = kave;
////////// variance
double ep = 0.0;
double kvar = 0.0;
double s = 0.0;
for (int i=0; i<N; i++) {
ep += (s=K[i]-kave);
kvar += s*s;
}
kvar=(kvar-ep*ep/N)/(N-1); // Corrected two-pass algorithm
v= kvar;
//cout << z << ' ' << v << endl; //test
Count.clear();
Count.resize(kmax+1,0);
P.clear();
P.resize(kmax+1,0);
for(int k=0; k<=kmax; k++) {
Count[k] = count(K.begin(), K.end(), k);
P[k] = Count[k]/(double)N;
//P[k] = count(K.begin(), K.end(), k)/(double)N;
//cout << "P[k=" << k << "]=" << P[k] << endl;
}
Q.clear();
//Q.resize(kmax,0);
//for(int k=0; k<kmax; k++) {
//Q[k] = (k+1)*P[k+1]/kave;
//}
Q.resize(kmax+1,0);
//double sum = 0;
for(int k=0; k<=kmax; k++) {
Q[k] = k*P[k]/kave;
//sum += Q[k];
}
//cout << "sumQ[k] = " << sum << endl; //test
}
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
// P[k] : the degree distribution
// Q[k] : the remaining degree distribution
// z: the mean degree
// v: the variance
void GetPQz(vector<int>& K, vector<double>& P, vector<double>& Q, double& z, double& v)
{
int N = K.size();
//int kmin = 0; // by default
int kmax = 0;
double kave = 0;
for(int i=0; i<N; i++) {
if(K[i]>kmax)
kmax = K[i];
kave += K[i];
}
kave /= (double)N;
z = kave;
////////// variance
double ep = 0.0;
double kvar = 0.0;
double s = 0.0;
for (int i=0; i<N; i++) {
ep += (s=K[i]-kave);
kvar += s*s;
}
kvar=(kvar-ep*ep/N)/(N-1); // Corrected two-pass algorithm
v= kvar;
//cout << z << ' ' << v << endl; //test
P.clear();
P.resize(kmax+1,0);
for(int k=0; k<=kmax; k++) {
P[k] = count(K.begin(), K.end(), k)/(double)N;
//cout << "P[k=" << k << "]=" << P[k] << endl;
}
Q.clear();
//Q.resize(kmax,0);
//for(int k=0; k<kmax; k++) {
//Q[k] = (k+1)*P[k+1]/kave;
//}
Q.resize(kmax+1,0);
//double sum = 0;
for(int k=0; k<=kmax; k++) {
Q[k] = k*P[k]/kave;
//sum += Q[k];
}
//cout << "sumQ[k] = " << sum << endl; //test
}
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
// Count[k] : the degree histogram
// P[k] : the degree distribution
// Q[k] : the remaining degree distribution
// z: the mean degree
// v: the variance
void GetPQz(vector<int>& K, vector<int>& Count, vector<long double>& P, vector<long double>& Q, double& z, double& v)
{
int N = K.size();
//int kmin = 0; // by default
int kmax = 0;
double kave = 0;
for(int i=0; i<N; i++) {
if(K[i]>kmax)
kmax = K[i];
kave += K[i];
}
kave /= (double)N;
z = kave;
////////// variance
double ep = 0.0;
double kvar = 0.0;
double s = 0.0;
for (int i=0; i<N; i++) {
ep += (s=K[i]-kave);
kvar += s*s;
}
kvar=(kvar-ep*ep/N)/(N-1); // Corrected two-pass algorithm
v= kvar;
//cout << z << ' ' << v << endl; //test
Count.clear();
Count.resize(kmax+1,0);
P.clear();
P.resize(kmax+1,0);
for(int k=0; k<=kmax; k++) {
Count[k] = count(K.begin(), K.end(), k);
P[k] = Count[k]/(double)N;
//P[k] = count(K.begin(), K.end(), k)/(double)N;
//cout << "P[k=" << k << "]=" << P[k] << endl;
}
Q.clear();
//Q.resize(kmax,0);
//for(int k=0; k<kmax; k++) {
//Q[k] = (k+1)*P[k+1]/kave;
//}
Q.resize(kmax+1,0);
//double sum = 0;
for(int k=0; k<=kmax; k++) {
Q[k] = k*P[k]/kave;
//sum += Q[k];
}
//cout << "sumQ[k] = " << sum << endl; //test
}
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
// P[k] : the degree distribution
// Q[k] : the remaining degree distribution
// z: the mean degree
// v: the variance
void GetPQz(vector<int>& K, vector<long double>& P, vector<long double>& Q, double& z, double& v)
{
int N = K.size();
//int kmin = 0; // by default
int kmax = 0;
double kave = 0;
for(int i=0; i<N; i++) {
if(K[i]>kmax)
kmax = K[i];
kave += K[i];
}
kave /= (double)N;
z = kave;
////////// variance
double ep = 0.0;
double kvar = 0.0;
double s = 0.0;
for (int i=0; i<N; i++) {
ep += (s=K[i]-kave);
kvar += s*s;
}
kvar=(kvar-ep*ep/N)/(N-1); // Corrected two-pass algorithm
v= kvar;
//cout << z << ' ' << v << endl; //test
P.clear();
P.resize(kmax+1,0);
for(int k=0; k<=kmax; k++) {
P[k] = count(K.begin(), K.end(), k)/(double)N;
//cout << "P[k=" << k << "]=" << P[k] << endl;
}
Q.clear();
//Q.resize(kmax,0);
//for(int k=0; k<kmax; k++) {
//Q[k] = (k+1)*P[k+1]/kave;
//}
Q.resize(kmax+1,0);
//double sum = 0;
for(int k=0; k<=kmax; k++) {
Q[k] = k*P[k]/kave;
//sum += Q[k];
}
//cout << "sumQ[k] = " << sum << endl; //test
}
/////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////
/*
// P[k] : the degree distribution
// Q[k] : the remaining degree distribution
// z: the mean degree
void GetPQz(vector<int>& Kin, vector<int>& Kout, vector<double>& P, vector<double>& Q, double& z)
{
Rand rand;
rand.seed(1);
int N = Kin.size();
vector<int> K(N);
int kmin = 0; // by default
int kmax = 0;
double kave = 0;
for(int i=0; i<N; i++) {
int a = rand.discrete(0,N-1);
int b = rand.discrete(0,N-1);
int c = rand.discrete(0,N-1);
int d = rand.discrete(0,N-1);
K[i] = Kin[a] + Kout[b] + Kin[c] + Kout[d]; // what does this mean??????
//cout << a << ' ' << b << ' ' << c << ' ' << d << ' ' << K[i] << endl;
if(K[i]>kmax)
kmax = K[i];
kave += K[i];
}
kave /= (double)N;
z = kave;
P.clear();
P.resize(kmax+1,0);
for(int k=0; k<=kmax; k++) {
P[k] = count(K.begin(), K.end(), k)/(double)N;
//cout << "P[k=" << k << "]=" << P[k] << endl;
}
Q.clear();
//Q.resize(kmax,0);
//for(int k=0; k<kmax; k++) {
//Q[k] = (k+1)*P[k+1]/kave;
//}
Q.resize(kmax+1,0);
for(int k=0; k<=kmax; k++) {
Q[k] = k*P[k]/kave;
}
}
*/
/////////////////////////////////////////////////////////////////////////////////////////////////
| 26.797619 | 240 | 0.478116 | [
"vector",
"model",
"solid"
] |
9404ca33bcb04ee99c410ffa957cdd1639ad4ad8 | 2,718 | cpp | C++ | Crossy_Roads/CubeMesh.cpp | Daryan7/Crossy_Roads | af816aa73ba29241fb1db4722940e42be8a76102 | [
"MIT"
] | 1 | 2018-04-18T12:54:33.000Z | 2018-04-18T12:54:33.000Z | Crossy_Roads/CubeMesh.cpp | Daryan7/Crossy_Roads | af816aa73ba29241fb1db4722940e42be8a76102 | [
"MIT"
] | null | null | null | Crossy_Roads/CubeMesh.cpp | Daryan7/Crossy_Roads | af816aa73ba29241fb1db4722940e42be8a76102 | [
"MIT"
] | null | null | null | #include "CubeMesh.h"
using namespace glm;
#include "Scene.h"
void CubeMesh::render() const {
Scene::sceneTriangles += totalTriangles;
Scene::sceneDrawCalls += 1;
glDrawElements(renderMode, nVertices, GL_UNSIGNED_INT, (void*)0);
}
void CubeMesh::init() {
static const float vertices[] = {
-1.0f, -1.0f, -1.f,
1.0f, -1.0f, -1.f,
-1.0f, 1.0f, -1.f,
1.0f, 1.0f, -1.f,
-1.0f, -1.0f, 1.f,
1.0f, -1.0f, 1.f,
-1.0f, 1.0f, 1.f,
1.0f, 1.0f, 1.f,
-1.0f, -1.f, -1.0f,
1.0f, -1.f, -1.0f,
-1.0f, -1.f, 1.0f,
1.0f, -1.f, 1.0f,
-1.0f, 1.f, -1.0f,
1.0f, 1.f, -1.0f,
-1.0f, 1.f, 1.0f,
1.0f, 1.f, 1.0f,
-1.f, -1.0f, -1.0f,
-1.f, 1.0f, -1.0f,
-1.f, -1.0f, 1.0f,
-1.f, 1.0f, 1.0f,
1.f, -1.0f, -1.0f,
1.f, 1.0f, -1.0f,
1.f, -1.0f, 1.0f,
1.f, 1.0f, 1.0f,
};
static const float normals[] = {
0,0,-1,
0,0,-1,
0,0,-1,
0,0,-1,
0,0,1,
0,0,1,
0,0,1,
0,0,1,
0,-1,0,
0,-1,0,
0,-1,0,
0,-1,0,
0,1,0,
0,1,0,
0,1,0,
0,1,0,
-1,0,0,
-1,0,0,
-1,0,0,
-1,0,0,
1,0,0,
1,0,0,
1,0,0,
1,0,0
};
//0-0.5 0-0.33 cara y
//0.5-1 0-0.33 cara -y
//0-0.5 0.33-0.66 cara -z
//0.5-1 0-33-0.66 cara z
//0-0.5 0.66-1 cara -x
//0.5-1 0.66-1 cara x
/*static const float st = 0.1;
static const float sX = 0.5f;
static const float sY = 1.f / 3;
static const float x0 = 0;
static const float x1 = sX;
static const float y0 = 0;
static const float y1 = sY;*/
static const float texCoords[] = {
0,0,
1,0,
0,1,
1,1,
0,0,
1,0,
0,1,
1,1,
0,0,
1,0,
0,1,
1,1,
0,0,
1,0,
0,1,
1,1,
0,0,
1,0,
0,1,
1,1,
0,0,
1,0,
0,1,
1,1
};
static const GLuint indices[] = {
0,1,2,
1,2,3,
4,5,6,
5,6,7,
8,9,10,
9,10,11,
12,13,14,
13,14,15,
16,17,18,
17,18,19,
20,21,22,
21,22,23
};
bbox[0] = vec3(-1);
bbox[1] = vec3(1);
generateAllbbPoints();
height = 2;
center = vec3(0);
glGenVertexArrays(1, &VAO);
glBindVertexArray(VAO);
glGenBuffers(1, &VBOvert);
glBindBuffer(GL_ARRAY_BUFFER, VBOvert);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glGenBuffers(1, &VBOnorm);
glBindBuffer(GL_ARRAY_BUFFER, VBOnorm);
glBufferData(GL_ARRAY_BUFFER, sizeof(normals), normals, GL_STATIC_DRAW);
glGenBuffers(1, &VBOtex);
glBindBuffer(GL_ARRAY_BUFFER, VBOtex);
glBufferData(GL_ARRAY_BUFFER, sizeof(texCoords), texCoords, GL_STATIC_DRAW);
glGenBuffers(1, &VBOind);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, VBOind);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
nVertices = sizeof(indices)/sizeof(GLuint);
totalTriangles = 12;
}
CubeMesh::CubeMesh()
{
}
CubeMesh::~CubeMesh()
{
}
| 15.1 | 81 | 0.562914 | [
"render"
] |
9406df0c9d38030f9064a118f9cb11408c902584 | 574 | hpp | C++ | core/include/utility/Cubic_Hermite_Spline.hpp | ddkn/spirit | 8e51bcdd78ee05d433d000c7e389fe1e6c3716bc | [
"MIT"
] | 92 | 2016-10-02T16:17:27.000Z | 2022-02-22T11:23:49.000Z | core/include/utility/Cubic_Hermite_Spline.hpp | ddkn/spirit | 8e51bcdd78ee05d433d000c7e389fe1e6c3716bc | [
"MIT"
] | 590 | 2016-09-24T12:46:36.000Z | 2022-03-24T18:27:18.000Z | core/include/utility/Cubic_Hermite_Spline.hpp | ddkn/spirit | 8e51bcdd78ee05d433d000c7e389fe1e6c3716bc | [
"MIT"
] | 46 | 2016-09-26T07:20:17.000Z | 2022-02-17T19:55:17.000Z | #pragma once
#ifndef UTILITY_CUBIC_HERMITE_SPLINE_H
#define UTILITY_CUBIC_HERMITE_SPLINE_H
#include "Spirit_Defines.h"
#include <vector>
namespace Utility
{
namespace Cubic_Hermite_Spline
{
// Interplation by cubic Hermite spline, see http://de.wikipedia.org/wiki/Kubisch_Hermitescher_Spline
std::vector<std::vector<scalar>> Interpolate(const std::vector<scalar> & x, const std::vector<scalar> & p, const std::vector<scalar> & m, int n_interpolations);
};//end namespace Cubic_Hermite_Spline
}//end namespace Utility
#endif
| 30.210526 | 169 | 0.729965 | [
"vector"
] |
940bcc9c4207b7b5ae1b8e350f237e3c5803b781 | 1,321 | cpp | C++ | code/indexed_sort-now.cpp | ldionne/cppnow-2015-hana | 2f9e86996b61b11e19486741f59ef217ea9125a7 | [
"MIT"
] | 2 | 2021-07-02T22:23:54.000Z | 2022-01-22T19:44:15.000Z | code/indexed_sort-now.cpp | ldionne/cppnow-2015-hana | 2f9e86996b61b11e19486741f59ef217ea9125a7 | [
"MIT"
] | null | null | null | code/indexed_sort-now.cpp | ldionne/cppnow-2015-hana | 2f9e86996b61b11e19486741f59ef217ea9125a7 | [
"MIT"
] | null | null | null | // Copyright Louis Dionne 2015
// Distributed under the Boost Software License, Version 1.0.
#include <boost/hana.hpp>
#include <cstddef>
using namespace boost::hana;
using namespace boost::hana::literals;
// sample(indexed_sort-now-impl)
auto indexed_sort = [](auto list, auto predicate) {
auto indices = to<Tuple>(range(0_c, size(list)));
auto indexed_list = zip.with(make_pair, list, indices);
auto sorted = sort(indexed_list, [&](auto const& x, auto const& y) {
return predicate(first(x), first(y));
});
return make_pair(transform(sorted, first), transform(sorted, second));
};
// end-sample
int main() {
// sample(indexed_sort-now-usage1)
auto types = tuple_t<int[3], int[2], int[1]>;
auto indexed = indexed_sort(types, [](auto t, auto u) {
return sizeof_(t) < sizeof_(u);
});
auto sorted = first(indexed);
auto indices = second(indexed);
static_assert(sorted == tuple_t<int[1], int[2], int[3]>, "");
static_assert(indices == tuple_c<std::size_t, 2, 1, 0>, "");
// end-sample
// sample(indexed_sort-now-usage2)
using Sequence = decltype(unpack(sorted, template_<_tuple>))::type;
auto index_map = second(indexed_sort(indices, less));
Sequence s;
int (&a)[3] = s[index_map[0_c]];
int (&b)[2] = s[index_map[1_c]];
int (&c)[1] = s[index_map[2_c]];
// end-sample
(void)a;
(void)b;
(void)c;
}
| 25.901961 | 72 | 0.679788 | [
"transform"
] |
940c607d0a7d52bc4becf2ac97842e746a00c607 | 6,288 | hpp | C++ | src/libv/ui/property_access_context.hpp | cpplibv/libv | 293e382f459f0acbc540de8ef6283782b38d2e63 | [
"Zlib"
] | 2 | 2018-04-11T03:07:03.000Z | 2019-03-29T15:24:12.000Z | src/libv/ui/property_access_context.hpp | cpplibv/libv | 293e382f459f0acbc540de8ef6283782b38d2e63 | [
"Zlib"
] | null | null | null | src/libv/ui/property_access_context.hpp | cpplibv/libv | 293e382f459f0acbc540de8ef6283782b38d2e63 | [
"Zlib"
] | 1 | 2021-06-13T06:39:06.000Z | 2021-06-13T06:39:06.000Z | // Project: libv.ui, File: src/libv/ui/property_access_context.hpp, Author: Császár Mátyás [Vader]
#pragma once
// libv
#include <libv/utility/observer_ptr.hpp>
// std
#include <string_view>
#include <type_traits>
// pro
//#include <libv/ui/core_component.hpp>
#include <libv/ui/style.hpp>
namespace libv {
namespace ui {
// -------------------------------------------------------------------------------------------------
class ContextUI;
class CoreComponent;
//struct BasePropertyInfo {
// std::string group;
// std::string name;
// std::string description;
//
// virtual std::shared_ptr<CoreComponent> makeEditor() = 0;
// virtual std::string toString() = 0;
// virtual ~BasePropertyInfo() = default;
//};
//
//template <typename T, typename Set, typename Get>
//struct PropertyInfo : BasePropertyInfo {
//// owner Property
// Set set;
// Get get;
//// setter
//// getter
//// fallback
//// init
//
// virtual std::shared_ptr<CoreComponent> makeEditor() override { }
// virtual std::string toString() override { }
//};
//struct ComponentPropertyDescription {
// std::vector<std::unique_ptr<BasePropertyInfo>> properties;
//};
// -------------------------------------------------------------------------------------------------
/// Style setter
template <typename Owner>
struct PropertyAccessContext {
Owner& owner;
CoreComponent& component;
libv::observer_ptr<Style> style;
ContextUI& context;
private:
template <typename Access>
using access_value_type_t = typename std::remove_cvref_t<decltype(std::declval<const Access&>()(std::declval<Owner&>()))>::value_type;
template <typename Get>
using get_value_type_t = std::remove_cvref_t<decltype(std::declval<const Get&>()(std::declval<Owner&>()))>;
// template <typename Access>
// static constexpr bool is_access_v = false;
// template <typename Access>
// static constexpr bool is_init_funciton_v = false;
// template <typename Access>
// static constexpr bool is_set_v = false;
// template <typename Access>
// static constexpr bool is_get_v = false;
public:
template <typename Access>
void property(Access&& access, access_value_type_t<Access> init, std::string_view group, std::string_view name, std::string_view description) {
// static_assert(Access yields PropertyA);
// static_assert(Init can be assigned to property);
(void) group;
(void) description;
using value_type = access_value_type_t<Access>;
auto& property = access(owner);
if (AccessProperty::driver(property) != PropertyDriver::style)
return;
if (style != nullptr) {
const value_type* value_opt = style->get_optional<value_type>(name);
if (value_opt) {
if (*value_opt != property())
AccessProperty::value(component, property, *value_opt);
return;
}
}
if (init != property())
AccessProperty::value(component, property, std::move(init));
}
template <typename Access, typename Init>
WISH_REQUIRES(std::is_invocable_v<Init, ContextUI&>)
void property(Access&& access, Init&& init, std::string_view group, std::string_view name, std::string_view description) {
// static_assert(Access yields PropertyA);
// static_assert(Init invoke with ContextUI& result can be assigned to property);
static_assert(std::is_convertible_v<std::invoke_result_t<Init, ContextUI&>, access_value_type_t<Access>>, "Init function object has incorrect return type");
(void) group;
(void) description;
using value_type = access_value_type_t<Access>;
auto& property = access(owner);
if (AccessProperty::driver(property) != PropertyDriver::style)
return;
if (style != nullptr) {
const value_type* value_opt = style->get_optional<value_type>(name);
if (value_opt) {
if (*value_opt != property())
AccessProperty::value(component, property, *value_opt);
return;
}
}
auto value = init(context);
if (value != property())
AccessProperty::value(component, property, std::move(value));
}
template <typename Access, typename Set, typename Get, typename Init>
void indirect(Access&& access, Set&& set, Get&& get, Init&& init, std::string_view group, std::string_view name, std::string_view description) {
// static_assert(Access yields Property<void>);
// static_assert(Set is callable with invoke result of Get + driver);
// static_assert(Get yields a non void);
// static_assert(Init can be passed to Set);
(void) group;
(void) description;
using value_type = get_value_type_t<Get>;
auto& property = access(owner);
if (AccessProperty::driver(property) != PropertyDriver::style)
return;
if (style != nullptr) {
const value_type* value_opt = style->get_optional<value_type>(name);
if (value_opt) {
if (*value_opt != get(owner))
set(owner, *value_opt);
return;
}
}
if (init != get(owner))
set(owner, std::move(init));
}
template <typename Access, typename Set, typename Get, typename Init>
WISH_REQUIRES(std::is_invocable_v<Init, ContextUI&>)
void indirect(Access&& access, Set&& set, Get&& get, Init&& init, std::string_view group, std::string_view name, std::string_view description) {
// static_assert(Access yields Property<void>);
// static_assert(Set is callable with invoke result of Get + driver);
// static_assert(Get yields a non void);
// static_assert(Init invoke with ContextUI& result can be passed to Set);
(void) group;
(void) description;
using value_type = get_value_type_t<Get>;
auto& property = access(owner);
if (AccessProperty::driver(property) != PropertyDriver::style)
return;
if (style != nullptr) {
const value_type* value_opt = style->get_optional<value_type>(name);
if (value_opt) {
if (*value_opt != get(owner))
set(owner, *value_opt);
return;
}
}
auto value = init(context);
if (value != get(owner))
set(owner, std::move(value));
}
template <typename Set, typename Get>
void synthetize(Set&& set, Get&& get, std::string_view group, std::string_view name, std::string_view description) {
// static_assert(Set is callable with invoke result of Get);
// static_assert(Get yields a non void);
(void) set;
(void) get;
(void) group;
(void) name;
(void) description;
}
};
// -------------------------------------------------------------------------------------------------
} // namespace ui
} // namespace libv
| 29.660377 | 158 | 0.672551 | [
"object",
"vector"
] |
940d46baf73f2d600cff6edc37c29a3a36bf5d90 | 5,302 | cpp | C++ | paddle/legacy/gserver/tests/test_Upsample.cpp | jerrywgz/Paddle | 85c4912755b783dd7554a9d6b9dae4a7e40371bc | [
"Apache-2.0"
] | 9 | 2017-12-04T02:58:01.000Z | 2020-12-03T14:46:30.000Z | paddle/legacy/gserver/tests/test_Upsample.cpp | jerrywgz/Paddle | 85c4912755b783dd7554a9d6b9dae4a7e40371bc | [
"Apache-2.0"
] | 7 | 2017-12-05T20:29:08.000Z | 2018-10-15T08:57:40.000Z | paddle/legacy/gserver/tests/test_Upsample.cpp | jerrywgz/Paddle | 85c4912755b783dd7554a9d6b9dae4a7e40371bc | [
"Apache-2.0"
] | 6 | 2018-03-19T22:38:46.000Z | 2019-11-01T22:28:27.000Z | /* Copyright (c) 2016 PaddlePaddle Authors. All Rights Reserve.
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 <gtest/gtest.h>
#include <string>
#include <vector>
#include "LayerGradUtil.h"
#include "paddle/legacy/math/MathUtils.h"
#include "paddle/testing/TestUtil.h"
void setPoolConfig(paddle::TestConfig* config,
paddle::PoolConfig* pool,
const string& poolType) {
(*config).biasSize = 0;
(*config).layerConfig.set_type("pool");
(*config).layerConfig.set_num_filters(1);
int kw = 2, kh = 2;
int pw = 0, ph = 0;
int sw = 2, sh = 2;
pool->set_pool_type(poolType);
pool->set_channels(2);
pool->set_size_x(kw);
pool->set_size_y(kh);
pool->set_start(0);
pool->set_padding(pw);
pool->set_padding_y(ph);
pool->set_stride(sw);
pool->set_stride_y(sh);
int ow =
paddle::outputSize(pool->img_size(), kw, pw, sw, /* caffeMode */ false);
int oh =
paddle::outputSize(pool->img_size_y(), kh, ph, sh, /* caffeMode */ false);
pool->set_output_x(ow);
pool->set_output_y(oh);
}
paddle::LayerPtr doOneUpsampleTest(const paddle::MatrixPtr& inputMat,
const string& poolType,
bool use_gpu,
real* tempGradData) {
/* prepare maxPoolWithMaskLayer */
paddle::TestConfig config;
config.inputDefs.push_back({paddle::INPUT_DATA, "layer_0", 128, 0});
paddle::LayerInputConfig* input = config.layerConfig.add_inputs();
paddle::PoolConfig* pool = input->mutable_pool_conf();
pool->set_img_size(8);
pool->set_img_size_y(8);
setPoolConfig(&config, pool, "max-pool-with-mask");
config.layerConfig.set_size(pool->output_x() * pool->output_y() *
pool->channels());
config.layerConfig.set_name("MaxPoolWithMask");
std::vector<paddle::DataLayerPtr> dataLayers;
paddle::LayerMap layerMap;
vector<paddle::Argument> datas;
initDataLayer(config,
&dataLayers,
&datas,
&layerMap,
"MaxPoolWithMask",
1,
false,
use_gpu);
dataLayers[0]->getOutputValue()->copyFrom(*inputMat);
FLAGS_use_gpu = use_gpu;
std::vector<paddle::ParameterPtr> parameters;
paddle::LayerPtr maxPoolingWithMaskOutputLayer;
initTestLayer(config, &layerMap, ¶meters, &maxPoolingWithMaskOutputLayer);
maxPoolingWithMaskOutputLayer->forward(paddle::PASS_GC);
/* prepare the upsample layer */
paddle::LayerConfig upsampleLayerConfig;
upsampleLayerConfig.set_type("upsample");
paddle::LayerInputConfig* input1 = upsampleLayerConfig.add_inputs();
upsampleLayerConfig.add_inputs();
paddle::UpsampleConfig* upsampleConfig = input1->mutable_upsample_conf();
upsampleConfig->set_scale(2);
paddle::ImageConfig* imageConfig = upsampleConfig->mutable_image_conf();
imageConfig->set_channels(2);
imageConfig->set_img_size(4);
imageConfig->set_img_size_y(4);
upsampleLayerConfig.set_size(2 * 8 * 8);
upsampleLayerConfig.set_name("upsample");
for (size_t i = 0; i < 2; i++) {
paddle::LayerInputConfig& inputTemp =
*(upsampleLayerConfig.mutable_inputs(i));
inputTemp.set_input_layer_name("MaxPoolWithMask");
}
paddle::LayerPtr upsampleLayer;
paddle::ParameterMap parameterMap;
upsampleLayer = paddle::Layer::create(upsampleLayerConfig);
layerMap[upsampleLayerConfig.name()] = upsampleLayer;
upsampleLayer->init(layerMap, parameterMap);
upsampleLayer->setNeedGradient(true);
upsampleLayer->forward(paddle::PASS_GC);
upsampleLayer->getOutputGrad()->copyFrom(tempGradData, 128);
upsampleLayer->backward();
return upsampleLayer;
}
TEST(Layer, maxPoolingWithMaskOutputLayerFwd) {
bool useGpu = false;
paddle::MatrixPtr inputMat;
paddle::MatrixPtr inputGPUMat;
paddle::MatrixPtr tempGradMat;
inputMat = paddle::Matrix::create(1, 128, false, useGpu);
inputMat->randomizeUniform();
tempGradMat = paddle::Matrix::create(1, 128, false, useGpu);
tempGradMat->randomizeUniform();
real* tempGradData = tempGradMat->getData();
paddle::LayerPtr upsampleLayerCPU =
doOneUpsampleTest(inputMat, "max-pool-with-mask", useGpu, tempGradData);
#ifdef PADDLE_WITH_CUDA
useGpu = true;
real* data = inputMat->getData();
inputGPUMat = paddle::Matrix::create(1, 128, false, useGpu);
inputGPUMat->copyFrom(data, 128);
paddle::LayerPtr upsampleLayerGPU = doOneUpsampleTest(
inputGPUMat, "max-pool-with-mask", useGpu, tempGradData);
paddle::checkMatrixEqual(upsampleLayerCPU->getOutput("").value,
upsampleLayerGPU->getOutput("").value);
paddle::checkMatrixEqual(upsampleLayerCPU->getPrev(0)->getOutputGrad(),
upsampleLayerGPU->getPrev(0)->getOutputGrad());
#endif
}
| 34.428571 | 80 | 0.693512 | [
"vector"
] |
9411f141d31799962711d4456b0f0dc851aca04d | 778 | cpp | C++ | multiprecision/MPEncArray.cpp | fionser/MDLHElib | 3c686ab35d7b26a893213a6e9d4249cd46c2969d | [
"MIT"
] | 5 | 2017-01-16T06:20:07.000Z | 2018-05-17T12:36:34.000Z | multiprecision/MPEncArray.cpp | fionser/MDLHElib | 3c686ab35d7b26a893213a6e9d4249cd46c2969d | [
"MIT"
] | null | null | null | multiprecision/MPEncArray.cpp | fionser/MDLHElib | 3c686ab35d7b26a893213a6e9d4249cd46c2969d | [
"MIT"
] | 2 | 2017-08-26T13:16:35.000Z | 2019-03-15T02:08:20.000Z | #include "MPEncArray.hpp"
#include "MPContext.hpp"
MPEncArray::MPEncArray(const MPContext &context)
: m_r(context.getR()),
m_plainSpace(context.plainSpace()),
m_primes(context.primes())
{
auto parts = context.partsNum();
arrays.reserve(parts);
for (long i = 0; i < parts; i++) {
auto cntxt = context.get(i);
auto G = cntxt->alMod.getFactorsOverZZ()[0];
arrays.push_back(std::make_shared<EncryptedArray>(*cntxt, G));
if (minimumSlot == 0 || minimumSlot > arrays[i]->size()) {
minimumSlot = arrays[i]->size();
}
}
}
std::vector<long> MPEncArray::rPrimes() const
{
std::vector<long> rprimes = m_primes;
for (auto &p : rprimes) {
p = std::pow(p, m_r);
}
return rprimes;
}
| 26.827586 | 70 | 0.595116 | [
"vector"
] |
9413e90694f5f94c3d1b85e58cd10d4c2440ed5f | 15,011 | cpp | C++ | libmesh/plugins/nvtt/TextureAtlasFilter.cpp | pathorn/sirikata | 5d366a822ef2fb57cd9f64cc4f6085c0a635fdfa | [
"BSD-3-Clause"
] | 1 | 2016-05-09T03:34:51.000Z | 2016-05-09T03:34:51.000Z | libmesh/plugins/nvtt/TextureAtlasFilter.cpp | pathorn/sirikata | 5d366a822ef2fb57cd9f64cc4f6085c0a635fdfa | [
"BSD-3-Clause"
] | null | null | null | libmesh/plugins/nvtt/TextureAtlasFilter.cpp | pathorn/sirikata | 5d366a822ef2fb57cd9f64cc4f6085c0a635fdfa | [
"BSD-3-Clause"
] | null | null | null | /* Sirikata
* TextureAtlasFilter.cpp
*
* Copyright (c) 2011, Ewen Cheslack-Postava
* 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 Sirikata 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 "TextureAtlasFilter.hpp"
#include "FreeImage.hpp"
#include <nvtt/nvtt.h>
namespace Sirikata {
namespace Mesh {
namespace {
struct Rect;
struct Region;
// Rect is used to define the size in pixels of a rectangular region
struct Rect {
int32 min_x;
int32 min_y;
int32 max_x;
int32 max_y;
int32 width() const { return max_x - min_x + 1; }
int32 height() const { return max_y - min_y + 1; }
int32 x() const { return min_x; }
int32 y() const { return min_y; }
static Rect fromBaseOffset(int32 _min_x, int32 _min_y, int32 _width, int32 _height) {
Rect ret;
ret.min_x = _min_x;
ret.min_y = _min_y;
ret.max_x = _min_x + _width - 1;
ret.max_y = _min_y + _height - 1;
return ret;
}
static Rect fromBounds(int32 _min_x, int32 _min_y, int32 _max_x, int32 _max_y) {
Rect ret;
ret.min_x = _min_x;
ret.min_y = _min_y;
ret.max_x = _max_x;
ret.max_y = _max_y;
return ret;
}
Region region(const Rect& subrect);
Rect region(const Region& subreg);
};
// Region is used to define a region of a Rect. It's values are always in the
// range 0 to 1
struct Region {
float min_x;
float min_y;
float max_x;
float max_y;
static Region fromBaseOffset(float _min_x, float _min_y, float _width, float _height) {
Region ret;
ret.min_x = _min_x;
ret.min_y = _min_y;
ret.max_x = _min_x + _width;
ret.max_y = _min_y + _height;
return ret;
}
static Region fromBounds(float _min_x, float _min_y, float _max_x, float _max_y) {
Region ret;
ret.min_x = _min_x;
ret.min_y = _min_y;
ret.max_x = _max_x;
ret.max_y = _max_y;
return ret;
}
float width() const { return max_x - min_x; }
float height() const { return max_y - min_y; }
float x() const { return min_x; }
float y() const { return min_y; }
// Convert a (u,v) in this region's coordinates (u and v between 0 and 1) to
// parent coordinates.
void convert(float u, float v, float* u_out, float* v_out) {
float u_o = min_x + u * width();
float v_o = min_y + v * height();
*u_out = min_x + u * width();
*v_out = min_y + v * height();
}
};
Region Rect::region(const Rect& subrect) {
return Region::fromBounds(
(subrect.min_x/(float)width()), (subrect.min_y/(float)height()),
((subrect.max_x+1)/(float)width()), ((subrect.max_y+1)/(float)height())
);
}
Rect Rect::region(const Region& subreg) {
return Rect::fromBaseOffset(
(int32)(subreg.min_x * width()), (int32)(subreg.min_y * height()),
(int32)(subreg.width() * width()), (int32)(subreg.height() * height())
);
}
// Track some information about the texture that we need as we process it.
struct TexInfo {
String url;
Rect orig_size;
FIBITMAP* image;
Region atlas_region;
};
// Compute a hash value for texture sets in a Meshdata.
int TextureSetHash(MeshdataPtr md, int sub_mesh_idx, int tex_set_idx) {
return (tex_set_idx * md->geometry.size()) + sub_mesh_idx;
}
} // namespace
TextureAtlasFilter::TextureAtlasFilter(const String& args) {
}
MeshdataPtr TextureAtlasFilter::apply(MeshdataPtr md) {
// Currently we use a very simple approach: take all textures and
// tile them into equal size regions, tiling in 2D.
typedef std::map<String, TexInfo> TexInfoMap;
TexInfoMap tex_info;
// We only know how to handle local files
if (md->uri.size() < 7 || md->uri.substr(0, 7) != "file://") return md;
String uri_dir = md->uri.substr(7);
size_t slash_pos = uri_dir.rfind("/");
if (slash_pos == std::string::npos || slash_pos == uri_dir.size()-1)
uri_dir = "./";
else
uri_dir = uri_dir.substr(0, slash_pos+1);
// If the same texUVs in a SubMeshGeometry are referenced by instances with
// different materials, then this code doesn't know how to handle them (we'd
// probably have to duplicate texUVs, and in doing so, decide whether the
// memory increase is worth it).
std::map<int, int> tex_set_materials; // Unique tex coord hash -> material
// idx
{
// We need to run through all instances and look for conflicts. A
// texture coordinate set is uniquely identified by SubMeshGeometry
// index and the index in SubMeshGeometry::texUVs. Since we know the
// number of SubMeshGeometries, we use
// (tex coord index * num sub mesh geometries) + sub mesh geo index
// to generate a unique index. Many instances may map to one of these
// and we just want to check that no two instances use different textures
Meshdata::GeometryInstanceIterator geo_inst_it = md->getGeometryInstanceIterator();
uint32 geo_inst_idx;
Matrix4x4f pos_xform;
bool conflicts = false;
while( geo_inst_it.next(&geo_inst_idx, &pos_xform) ) {
GeometryInstance& geo_inst = md->instances[geo_inst_idx];
int sub_mesh_idx = geo_inst.geometryIndex;
for(GeometryInstance::MaterialBindingMap::iterator mat_it = geo_inst.materialBindingMap.begin(); mat_it != geo_inst.materialBindingMap.end(); mat_it++) {
int texset_idx = mat_it->first;
int mat_idx = mat_it->second;
int tex_set_hash = TextureSetHash(md, sub_mesh_idx, texset_idx);
if (tex_set_materials.find(tex_set_hash) != tex_set_materials.end() &&
tex_set_materials[tex_set_hash] != mat_idx)
{
// Conflict, can't handle, pass on without any processing
SILOG(textureatlas, error, "[TEXTUREATLAS] Found two instances using different materials referencing the same geometry -- can't safely generate atlas.");
return md;
}
tex_set_materials[tex_set_hash] = mat_idx;
}
}
}
// First compute some stats.
for(uint32 tex_i = 0; tex_i < md->textures.size(); tex_i++) {
String tex_url = md->textures[tex_i];
String texfile = uri_dir + tex_url;
tex_info[tex_url] = TexInfo();
tex_info[tex_url].url = tex_url;
// Load the data from the original file
FIBITMAP* input_image = GenericLoader(texfile.c_str(), 0);
if (input_image == NULL) { // Couldn't figure out how to load it
tex_info[tex_url].image = NULL;
continue;
}
// Make sure we get the data in BGRA 8UB and properly packed
FIBITMAP* input_image_32 = FreeImage_ConvertTo32Bits(input_image);
FreeImage_Unload(input_image);
tex_info[tex_url].image = input_image_32;
int32 width = FreeImage_GetWidth(input_image_32);
int32 height = FreeImage_GetHeight(input_image_32);
tex_info[tex_url].orig_size = Rect::fromBaseOffset(0, 0, width, height);
}
// Select the block size and layout, create target image
int ntextures = tex_info.size();
int ntextures_side = (int)(sqrtf((float)ntextures) + 1.f);
// FIXME
uint32 atlas_element_width = 256, atlas_element_height = 256;
uint32 atlas_width = ntextures_side * atlas_element_width,
atlas_height = ntextures_side * atlas_element_height;
FIBITMAP* atlas = FreeImage_Allocate(atlas_width, atlas_height, 32);
// Scale images to desired size, copy data into the target image
int idx = 0;
Rect atlas_rect = Rect::fromBaseOffset(0, 0, atlas_width, atlas_height);
for(TexInfoMap::iterator tex_it = tex_info.begin(); tex_it != tex_info.end(); tex_it++) {
TexInfo& tex = tex_it->second;
// Resize
uint32 new_width = atlas_element_width, new_height = atlas_element_height; // FIXME
FIBITMAP* resized = FreeImage_Rescale(tex.image, new_width, new_height, FILTER_LANCZOS3);
// Copy into place
int x_idx = idx % ntextures_side;
int y_idx = idx / ntextures_side;
Rect tex_sub_rect = Rect::fromBaseOffset(
x_idx * atlas_element_width, y_idx * atlas_element_height,
atlas_element_width, atlas_element_height
);
tex.atlas_region = atlas_rect.region(tex_sub_rect);
FreeImage_Paste(atlas, resized, tex_sub_rect.min_x, tex_sub_rect.min_y, 256);
FreeImage_Unload(resized);
FreeImage_Unload(tex_it->second.image);
tex_it->second.image = NULL;
idx++;
}
// Generate the texture atlas
String atlas_url = uri_dir + "atlas.png";
FreeImage_Save(FIF_PNG, atlas, atlas_url.c_str());
FreeImage_Unload(atlas);
// Now we need to run through and fix up texture references and texture
// coordinates
// 1. Replace old textures with new one
TextureList orig_texture_list = md->textures;
md->textures.clear();
md->textures.push_back(atlas_url);
// 2. Update texture coordinates. Since we've stored texture set hash ->
// material indices, we can easily work from this to quickly iterate over
// items and transform the coordinates.
for(uint32 geo_idx = 0; geo_idx < md->geometry.size(); geo_idx++) {
// Each submesh has texUVs that need updating
SubMeshGeometry& submesh = md->geometry[geo_idx];
// We need to modify each texture coordinate set in this geometry. We
// put this as the outer loop so we replace the entire uv set with a
// new, filtered copy so we make sure we don't double-transform any of
// the coordinates.
for(uint32 tex_set_idx = 0; tex_set_idx < submesh.texUVs.size(); tex_set_idx++) {
SubMeshGeometry::TextureSet& tex_set = submesh.texUVs[tex_set_idx];
std::vector<float> new_uvs = tex_set.uvs;
// Each prim defines a material mapping, so we need to split the
// texture coordinates up by prim.
for(uint32 prim_idx = 0; prim_idx < submesh.primitives.size(); prim_idx++) {
SubMeshGeometry::Primitive& prim = submesh.primitives[prim_idx];
int mat_id = prim.materialId;
int tex_set_hash = TextureSetHash(md, geo_idx, mat_id);
// We stored up the correct material index to find it in the
// Meshdata in the tex_set_materials when we were sanity checking
// that there were no conflicts.
int mat_idx = tex_set_materials[tex_set_hash];
// Finally, having extracted all the material mapping info, we
// can loop through referenced indices and transform them.
MaterialEffectInfo& mat = md->materials[mat_idx];
// Do transformation for each texture that has a URI. Some may
// be duplicates, some may not have a URI, but doing them all
// ensures we catch everything.
for(uint32 mat_tex_idx = 0; mat_tex_idx < mat.textures.size(); mat_tex_idx++) {
MaterialEffectInfo::Texture& real_tex = mat.textures[mat_tex_idx];
if (tex_info.find(real_tex.uri) == tex_info.end()) continue;
TexInfo& final_tex_info = tex_info[real_tex.uri];
for(uint32 index_idx = 0; index_idx < prim.indices.size(); index_idx++) {
int index = prim.indices[index_idx];
float new_u, new_v;
assert(tex_set.stride >= 2);
final_tex_info.atlas_region.convert(
tex_set.uvs[index * tex_set.stride],
(1.f-tex_set.uvs[index * tex_set.stride + 1]), // inverted
// v coords
&new_u, &new_v);
new_uvs[ index * tex_set.stride ] = new_u;
new_uvs[ index * tex_set.stride + 1 ] = 1.f - new_v; // inverted
// v coords
}
}
}
tex_set.uvs = new_uvs;
}
}
// 3. Replace references in materials to old URI's with new one
for(MaterialEffectInfoList::iterator mat_it = md->materials.begin(); mat_it != md->materials.end(); mat_it++) {
MaterialEffectInfo& mat_info = *mat_it;
for(MaterialEffectInfo::TextureList::iterator tex_it = mat_info.textures.begin(); tex_it != mat_info.textures.end(); tex_it++) {
if (!tex_it->uri.empty())
tex_it->uri = atlas_url;
}
}
return md;
}
FilterDataPtr TextureAtlasFilter::apply(FilterDataPtr input) {
using namespace nvtt;
InitFreeImage();
MutableFilterDataPtr output(new FilterData());
for(FilterData::const_iterator mesh_it = input->begin(); mesh_it != input->end(); mesh_it++) {
VisualPtr vis = *mesh_it;
MeshdataPtr mesh( std::tr1::dynamic_pointer_cast<Meshdata>(vis));
if (!mesh) {
// Unsupported
output->push_back(vis);
}
else {
MeshdataPtr ta_mesh = apply(mesh);
output->push_back(ta_mesh);
}
}
return output;
}
} // namespace Mesh
} // namespace Sirikata
| 40.352151 | 173 | 0.628206 | [
"mesh",
"geometry",
"vector",
"transform"
] |
94176fafa12997c7936e66f52ecba499b165c1bf | 1,614 | cpp | C++ | project1/sectE/cart_coord.cpp | wood-b/CompBook | 5a0d5764d1d9ed97b54b7ce91048471b70dadb7d | [
"BSD-3-Clause"
] | 2 | 2015-07-13T21:55:22.000Z | 2015-07-20T17:04:40.000Z | project1/sectD/cart_coord.cpp | wood-b/CompBook | 5a0d5764d1d9ed97b54b7ce91048471b70dadb7d | [
"BSD-3-Clause"
] | 1 | 2015-07-13T22:06:43.000Z | 2015-07-16T16:54:43.000Z | project1/sectE/cart_coord.cpp | wood-b/CompBook | 5a0d5764d1d9ed97b54b7ce91048471b70dadb7d | [
"BSD-3-Clause"
] | null | null | null | #include "cart_coord.h"
#include <iostream>
cart_coord::cart_coord() {}
std::vector<double>& cart_coord::atom(int n) {
return m_coord[n];
}
void cart_coord::setAtom_xyz(double x, double y, double z) {
std::vector<double> xyz = {x, y, z};
m_coord.push_back(xyz);
}
double& cart_coord::atom_x(int n) {
return m_coord[n][0];
}
double& cart_coord::atom_y(int n) {
return m_coord[n][1];
}
double& cart_coord::atom_z(int n) {
return m_coord[n][2];
}
//must write x coordinate first
void cart_coord::setAtom_x(double x) {
std::vector<double> x1 = {x};
m_coord.push_back(x1);
}
void cart_coord::setAtom_y(int n, double y) {
m_coord.at(n).push_back(y);
}
void cart_coord::setAtom_z(int n, double z) {
m_coord.at(n).push_back(z);
}
void cart_coord::replaceAtom_xyz(int n, double x, double y, double z) {
std::vector<double> new_xyz = {x, y, z};
m_coord.at(n) = new_xyz;
}
void cart_coord::insertAtom_xyz(int n, double x, double y, double z) {
std::vector<double> insert_xyz = {x, y, z};
//n+1 so it inserts after the desired position
m_coord.insert(m_coord.begin()+n, insert_xyz);
}
/*int main() {
cart_coord test;
test.setAtom_xyz(0.0, 0.0, 0.0);
test.setAtom_xyz(0.0, 1.5, 0.0);
test.setAtom_x(0.2);
test.setAtom_y(2, 0.3);
test.setAtom_z(2, 0.4);
test.insertAtom_xyz(3, 12.1, 12.2, 12.3);
for (int i; i < 4; i++) {
//std::cout << test.atom_x(i) << test.atom_y(i) << test.atom_z(i) << std::endl;
std::cout << test.atom(i)[0] << test.atom(i)[1] << test.atom(i)[2] << std::endl;
}
return 0;
}*/
| 25.619048 | 88 | 0.621437 | [
"vector"
] |
941dc2a7dd8fe979bd1da18920e06c1cb056a10b | 1,629 | cpp | C++ | src/wiztk/system/threading/thread/private.cpp | wiztk/framework | 179baf8a24406b19d3f4ea28e8405358b21f8446 | [
"Apache-2.0"
] | 37 | 2017-11-22T14:15:33.000Z | 2021-11-25T20:39:39.000Z | src/wiztk/system/threading/thread/private.cpp | wiztk/framework | 179baf8a24406b19d3f4ea28e8405358b21f8446 | [
"Apache-2.0"
] | 3 | 2018-03-01T12:44:22.000Z | 2021-01-04T23:14:41.000Z | src/wiztk/system/threading/thread/private.cpp | wiztk/framework | 179baf8a24406b19d3f4ea28e8405358b21f8446 | [
"Apache-2.0"
] | 10 | 2017-11-25T19:09:11.000Z | 2020-12-02T02:05:47.000Z | /*
* Copyright 2017 - 2018 The WizTK Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "private.hpp"
namespace wiztk {
namespace system {
namespace threading {
Thread::ID Thread::Private::kMainThreadID;
void *Thread::Private::StartRoutine(Thread *thread) {
thread->p_->state = kRunning;
auto *specific = Specific::Create();
specific->thread = thread;
Specific::kPerThreadStorage.Set(specific);
if (thread->p_->delegate) thread->p_->delegate->Run();
else thread->Run();
auto *obj = Specific::kPerThreadStorage.Get();
Specific::kPerThreadStorage.Set(nullptr);
delete obj;
thread->p_->state = kTerminated;
pthread_exit((void *) thread);
}
// -----
ThreadLocal<Thread::Specific> Thread::Specific::kPerThreadStorage;
Thread::Specific *Thread::Specific::GetCurrent() {
return kPerThreadStorage.Get();
}
Thread::Specific *Thread::Specific::Create() {
if (nullptr != kPerThreadStorage.Get())
throw std::runtime_error("Error! Only on Specific can be created per thread!");
auto *object = new Specific();
kPerThreadStorage.Set(object);
return object;
}
}
}
}
| 25.857143 | 83 | 0.717004 | [
"object"
] |
9425e3ea3fd3b25f212ce261f2aabd1bb13a9a88 | 3,134 | cpp | C++ | aws-cpp-sdk-ssm-incidents/source/model/IncidentRecordSummary.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-ssm-incidents/source/model/IncidentRecordSummary.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-ssm-incidents/source/model/IncidentRecordSummary.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/ssm-incidents/model/IncidentRecordSummary.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace SSMIncidents
{
namespace Model
{
IncidentRecordSummary::IncidentRecordSummary() :
m_arnHasBeenSet(false),
m_creationTimeHasBeenSet(false),
m_impact(0),
m_impactHasBeenSet(false),
m_incidentRecordSourceHasBeenSet(false),
m_resolvedTimeHasBeenSet(false),
m_status(IncidentRecordStatus::NOT_SET),
m_statusHasBeenSet(false),
m_titleHasBeenSet(false)
{
}
IncidentRecordSummary::IncidentRecordSummary(JsonView jsonValue) :
m_arnHasBeenSet(false),
m_creationTimeHasBeenSet(false),
m_impact(0),
m_impactHasBeenSet(false),
m_incidentRecordSourceHasBeenSet(false),
m_resolvedTimeHasBeenSet(false),
m_status(IncidentRecordStatus::NOT_SET),
m_statusHasBeenSet(false),
m_titleHasBeenSet(false)
{
*this = jsonValue;
}
IncidentRecordSummary& IncidentRecordSummary::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("arn"))
{
m_arn = jsonValue.GetString("arn");
m_arnHasBeenSet = true;
}
if(jsonValue.ValueExists("creationTime"))
{
m_creationTime = jsonValue.GetDouble("creationTime");
m_creationTimeHasBeenSet = true;
}
if(jsonValue.ValueExists("impact"))
{
m_impact = jsonValue.GetInteger("impact");
m_impactHasBeenSet = true;
}
if(jsonValue.ValueExists("incidentRecordSource"))
{
m_incidentRecordSource = jsonValue.GetObject("incidentRecordSource");
m_incidentRecordSourceHasBeenSet = true;
}
if(jsonValue.ValueExists("resolvedTime"))
{
m_resolvedTime = jsonValue.GetDouble("resolvedTime");
m_resolvedTimeHasBeenSet = true;
}
if(jsonValue.ValueExists("status"))
{
m_status = IncidentRecordStatusMapper::GetIncidentRecordStatusForName(jsonValue.GetString("status"));
m_statusHasBeenSet = true;
}
if(jsonValue.ValueExists("title"))
{
m_title = jsonValue.GetString("title");
m_titleHasBeenSet = true;
}
return *this;
}
JsonValue IncidentRecordSummary::Jsonize() const
{
JsonValue payload;
if(m_arnHasBeenSet)
{
payload.WithString("arn", m_arn);
}
if(m_creationTimeHasBeenSet)
{
payload.WithDouble("creationTime", m_creationTime.SecondsWithMSPrecision());
}
if(m_impactHasBeenSet)
{
payload.WithInteger("impact", m_impact);
}
if(m_incidentRecordSourceHasBeenSet)
{
payload.WithObject("incidentRecordSource", m_incidentRecordSource.Jsonize());
}
if(m_resolvedTimeHasBeenSet)
{
payload.WithDouble("resolvedTime", m_resolvedTime.SecondsWithMSPrecision());
}
if(m_statusHasBeenSet)
{
payload.WithString("status", IncidentRecordStatusMapper::GetNameForIncidentRecordStatus(m_status));
}
if(m_titleHasBeenSet)
{
payload.WithString("title", m_title);
}
return payload;
}
} // namespace Model
} // namespace SSMIncidents
} // namespace Aws
| 20.754967 | 105 | 0.731015 | [
"model"
] |
942fefe3efe25338f5032f999a93a2751638baa0 | 525 | cpp | C++ | source/A-small-0.cpp | amirasaad/codejam-commandline | f49eccee781358a0af61ad85862147cf065ded63 | [
"Apache-2.0"
] | 4 | 2016-04-11T08:53:54.000Z | 2017-04-08T21:22:02.000Z | source/A-small-0.cpp | amirasaad/codejam-commandline | f49eccee781358a0af61ad85862147cf065ded63 | [
"Apache-2.0"
] | 1 | 2018-01-12T09:51:07.000Z | 2018-01-14T17:13:02.000Z | source/A-small-0.cpp | amirasaad/codejam-commandline | f49eccee781358a0af61ad85862147cf065ded63 | [
"Apache-2.0"
] | 13 | 2017-01-12T11:13:40.000Z | 2019-04-19T10:02:34.000Z | #include "cmath"
#include "cstdio"
#include "algorithm"
#include "map"
#include "numeric"
#include "queue"
#include "set"
#include "string"
#include "utility"
#include "vector"
using namespace std;
typedef long long i64;
int main() {
int T; scanf("%d", &T);
for (int Ti = 1; Ti <= T; ++Ti) {
fprintf(stderr, "Case #%d of %d...\n", Ti, T);
int n; i64 k; scanf("%d %lld", &n, &k);
if ((k + 1) % (1 << n) == 0) printf("Case #%d: %s\n", Ti, "ON");
else printf("Case #%d: %s\n", Ti, "OFF");
}
return 0;
}
| 21.875 | 68 | 0.554286 | [
"vector"
] |
9431a9fa640700bf1d2a63cd529ab97da8e2b470 | 1,707 | cpp | C++ | Tools/Toolsets.cpp | lpuls/UnU | 0d8b4b5200cff68795dd8e961e56f12ea7c7ea7f | [
"MIT"
] | 2 | 2016-05-02T08:59:45.000Z | 2021-10-10T09:28:51.000Z | Tools/Toolsets.cpp | lpuls/UnU | 0d8b4b5200cff68795dd8e961e56f12ea7c7ea7f | [
"MIT"
] | null | null | null | Tools/Toolsets.cpp | lpuls/UnU | 0d8b4b5200cff68795dd8e961e56f12ea7c7ea7f | [
"MIT"
] | null | null | null | #include "Toolsets.hpp"
#include "TypeConversion/TypeConversion.hpp"
using namespace XpLib;
Toolsets* Toolsets::__instance = nullptr;
XpLib::Toolsets::Toolsets()
{
// ʵ������־��
this->__log = new ToolLog();
}
XpLib::Toolsets::~Toolsets()
{
if (nullptr != this->__log)
delete(this->__log);
this->__log = nullptr;
}
Toolsets * XpLib::Toolsets::getInstance()
{
if (nullptr == Toolsets::__instance)
Toolsets::__instance = new Toolsets();
return Toolsets::__instance;
}
void XpLib::Toolsets::releaseInstance()
{
if (nullptr != Toolsets::__instance)
delete(Toolsets::__instance);
Toolsets::__instance = nullptr;
}
bool XpLib::Toolsets::addSwitch(std::string switchName)
{
if (this->__log->addSwitch(switchName))
return true;
return false;
}
void XpLib::Toolsets::setSwitch(std::string switchName, bool switchValue)
{
this->__log->setSwitch(switchName, switchValue);
}
void XpLib::Toolsets::log(std::string logValue, std::string switchName)
{
this->__log->log(logValue, switchName);
}
std::string XpLib::Toolsets::intToStr(int value)
{
return TypeConversion::intToStr(value);
}
int XpLib::Toolsets::strToInt(std::string value)
{
return TypeConversion::strToInt(value);
}
std::string XpLib::Toolsets::doubleToStr(double value)
{
return TypeConversion::doubleToStr(value);
}
double XpLib::Toolsets::strToDouble(std::string value)
{
return TypeConversion::strToDouble(value);
}
std::string XpLib::Toolsets::boolToStr(bool value)
{
return TypeConversion::boolToStr(value);
}
std::string XpLib::Toolsets::charToStr(char value)
{
return TypeConversion::charToStr(value);
}
std::vector<std::string> XpLib::Toolsets::reader(std::string file)
{
return FileReader::reader(file);
}
| 19.848837 | 73 | 0.729936 | [
"vector"
] |
94352d480655467491477c5cd8311a81db110493 | 2,736 | cc | C++ | commands/ir.cc | finiteloop/compiler | 700f5d2956d2024764f4677fc733e9e7bef70167 | [
"Apache-2.0"
] | 35 | 2020-08-24T23:24:09.000Z | 2021-12-17T17:22:21.000Z | commands/ir.cc | finiteloop/compiler | 700f5d2956d2024764f4677fc733e9e7bef70167 | [
"Apache-2.0"
] | 1 | 2020-12-26T09:59:57.000Z | 2020-12-31T20:00:42.000Z | commands/ir.cc | finiteloop/compiler | 700f5d2956d2024764f4677fc733e9e7bef70167 | [
"Apache-2.0"
] | 2 | 2020-12-29T06:21:09.000Z | 2021-11-19T12:43:04.000Z | // Copyright 2020 Bret Taylor
//
// 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 "ir.h"
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/Module.h>
#include <llvm/Support/FileSystem.h>
#include <stdlib.h>
#include <unistd.h>
#include "../checker/check.h"
#include "../emitter/emit.h"
#include "../emitter/optimize.h"
#include "../parser/parse.h"
namespace compiler::commands {
IR::IR()
: Command(
"ir", "Emit LLVM assembly language for a program",
{Option("output", "Write IR code to the given path", Option::OPTION),
Option("strict", "Treat warnings as fatal errors"),
Option("unoptimized", "Do not optimize the program")},
"path") {
}
bool IR::execute(const filesystem::path& executable, map<string, bool>& flags,
map<string, string>& options, vector<string>& arguments) {
if (arguments.size() < 1) {
print_help(executable);
return false;
}
// Parse the program
auto error = make_shared<Error::Terminal>();
auto fail_level = flags["strict"] ? Error::WARNING : Error::ERROR;
auto module = parser::parse(error, arguments[0]);
if (!module) {
return false;
}
// Check for correctness
auto symbols = checker::check(error, module);
if (!symbols || error->count(fail_level) > 0) {
return false;
}
// Emit LLVM IR code
llvm::LLVMContext llvm_context;
auto llvm_module = new llvm::Module(arguments[0], llvm_context);
auto llvm_function = emitter::emit(module, llvm_module);
if (!llvm_function) {
return false;
}
if (!flags["unoptimized"]) {
emitter::optimize(llvm_module);
}
// Write the LLVM IR
shared_ptr<llvm::raw_fd_ostream> out;
if (!options["output"].empty()) {
std::error_code file_error;
out = make_shared<llvm::raw_fd_ostream>(options["output"], file_error,
llvm::sys::fs::F_None);
if (file_error) {
error->report(Error::ERROR, "Could not write " + options["output"] +
": " + file_error.message());
return false;
}
} else {
out = make_shared<llvm::raw_fd_ostream>(STDOUT_FILENO, false);
}
llvm_module->print(*out, nullptr);
return true;
}
}
| 30.4 | 79 | 0.647295 | [
"vector"
] |
9453214cc0c987a1ad78daa163750fdcd06a7159 | 2,473 | cc | C++ | Codeforces/291 Division 2/Problem C/C.cc | VastoLorde95/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 170 | 2017-07-25T14:47:29.000Z | 2022-01-26T19:16:31.000Z | Codeforces/291 Division 2/Problem C/C.cc | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | null | null | null | Codeforces/291 Division 2/Problem C/C.cc | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 55 | 2017-07-28T06:17:33.000Z | 2021-10-31T03:06:22.000Z | #include<stdio.h>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<map>
#include<unordered_set>
#include<vector>
#include<utility>
#include<math.h>
#define sd(x) scanf("%d",&x);
#define sd2(x,y) scanf("%d%d",&x,&y);
#define sd3(x,y,z) scanf("%d%d%d",&x,&y,&z);
using namespace std;
int n, m, l, flag;
char c;
unordered_set<long long> x;
long long h, MOD = 10000000009, p;
char temp[7000000];
int main(){
cin>>n>>m;
scanf("%c",&c);
for(int i = 0; i < n; i++){
h = 0;
scanf("%s",temp);
int j = 0;
while(temp[j] != '\0'){
h = (h*11 + temp[j])%MOD;
j++;
}
x.insert(h);
//cout<<h<<endl;
}
for(int i = 0; i < m; i++){
h = 0;
scanf("%s",temp);
int k = 0;
l = 0;
while(temp[k] != '\0'){
h = (h*11 + temp[k])%MOD;
k++;
l++;
}
//cout<<h<<endl;
p = 1;
flag = 0;
for(int j = l-1; j >= 0; j--){
if(temp[j] == 'a'){
if(x.find( (h + p)%MOD ) != x.end()){
cout<<"YES\n";
flag = 1;
j = -1;
}
else{
if(x.find( (h + p + p)%MOD ) != x.end()){
cout<<"YES\n";
flag = 1;
j = -1;
}
}
}
else if(temp[j] == 'b'){
if(x.find( (h - p + MOD)%MOD ) != x.end()){
cout<<"YES\n";
flag = 1;
j = -1;
}
else{
if(x.find( (h + p + MOD)%MOD ) != x.end()){
cout<<"YES\n";
flag = 1;
j = -1;
}
}
}
else{
if(x.find( (h - p + MOD)%MOD ) != x.end()){
cout<<"YES\n";
flag = 1;
j = -1;
}
else{
if(x.find( (h - p - p + MOD + MOD)%MOD ) != x.end()){
cout<<"YES\n";
flag = 1;
j = -1;
}
}
}
p = (p*11)%MOD;
}
if(flag == 0) cout<<"NO\n";
}
return 0;
}
| 24.245098 | 73 | 0.294784 | [
"vector"
] |
9453adaf688e2e9d674ef21356b8487685d78a08 | 1,363 | cc | C++ | node_modules/face-recognition/cc/FrontalFaceDetector.cc | osman-demirci/digital-guard-app-ipcamera | 397a105d34194e2ce1ab7a31f34d03631a316b44 | [
"Apache-2.0"
] | 1 | 2020-12-01T10:15:31.000Z | 2020-12-01T10:15:31.000Z | node_modules/face-recognition/cc/FrontalFaceDetector.cc | osman-demirci/digital-guard-app-ipcamera | 397a105d34194e2ce1ab7a31f34d03631a316b44 | [
"Apache-2.0"
] | null | null | null | node_modules/face-recognition/cc/FrontalFaceDetector.cc | osman-demirci/digital-guard-app-ipcamera | 397a105d34194e2ce1ab7a31f34d03631a316b44 | [
"Apache-2.0"
] | null | null | null | #include "FrontalFaceDetector.h"
#include "ImageRGB.h"
#include "Rect.h"
Nan::Persistent<v8::FunctionTemplate> FrontalFaceDetector::constructor;
NAN_MODULE_INIT(FrontalFaceDetector::Init) {
v8::Local<v8::FunctionTemplate> ctor = Nan::New<v8::FunctionTemplate>(FrontalFaceDetector::New);
constructor.Reset(ctor);
ctor->InstanceTemplate()->SetInternalFieldCount(1);
ctor->SetClassName(Nan::New("FrontalFaceDetector").ToLocalChecked());
Nan::SetPrototypeMethod(ctor, "detect", Detect);
target->Set(Nan::New("FrontalFaceDetector").ToLocalChecked(), ctor->GetFunction());
};
NAN_METHOD(FrontalFaceDetector::New) {
FrontalFaceDetector* self = new FrontalFaceDetector();
self->detector = dlib::get_frontal_face_detector();
self->Wrap(info.Holder());
info.GetReturnValue().Set(info.Holder());
};
NAN_METHOD(FrontalFaceDetector::Detect) {
dlib::matrix<dlib::rgb_pixel> img;
double adjustThreshold;
FF_TRY_UNWRAP_ARGS(
"FrontalFaceDetector::Detect",
ImageRGB::Converter::arg(0, &img, info)
|| DoubleConverter::optArg(1, &adjustThreshold, info)
);
dlib::frontal_face_detector detector = FrontalFaceDetector::Converter::unwrap(info.This());
std::vector<dlib::rectangle> rects = detector(img, adjustThreshold);
info.GetReturnValue().Set(ObjectArrayConverter<Rect, dlib::rectangle>::wrap(rects));
};
| 34.075 | 99 | 0.735143 | [
"vector"
] |
9456e27b77526e03d2f9e42e1fb638b430345e63 | 7,534 | cpp | C++ | Samples/XNA_XNB_Format/Example XNB Parser/ParseXnb/TypeReaderManager.cpp | SimonDarksideJ/XNAGameStudio | 5b79efb0b110140419056b0146ba066f2104f985 | [
"MIT"
] | 422 | 2018-03-20T07:46:35.000Z | 2022-03-31T19:37:43.000Z | Samples/XNA_XNB_Format/Example XNB Parser/ParseXnb/TypeReaderManager.cpp | SimonDarksideJ/XNAGameStudio | 5b79efb0b110140419056b0146ba066f2104f985 | [
"MIT"
] | 11 | 2018-09-10T01:05:45.000Z | 2022-03-10T17:27:02.000Z | Samples/XNA_XNB_Format/Example XNB Parser/ParseXnb/TypeReaderManager.cpp | SimonDarksideJ/XNAGameStudio | 5b79efb0b110140419056b0146ba066f2104f985 | [
"MIT"
] | 72 | 2018-09-08T09:51:55.000Z | 2022-03-04T17:38:53.000Z | #include "stdafx.h"
#include "TypeReaderManager.h"
#include "PrimitiveTypeReaders.h"
#include "SystemTypeReaders.h"
#include "MathTypeReaders.h"
#include "GraphicsTypeReaders.h"
#include "MediaTypeReaders.h"
TypeReaderManager::~TypeReaderManager()
{
for each (TypeReader* reader in typeReaders)
{
delete reader;
}
for each (GenericTypeReaderFactory* factory in genericReaders)
{
delete factory;
}
}
void TypeReaderManager::RegisterStandardTypes()
{
// Primitive types.
RegisterTypeReader<ByteReader>();
RegisterTypeReader<SByteReader>();
RegisterTypeReader<Int16Reader>();
RegisterTypeReader<UInt16Reader>();
RegisterTypeReader<Int32Reader>();
RegisterTypeReader<UInt32Reader>();
RegisterTypeReader<Int64Reader>();
RegisterTypeReader<UInt64Reader>();
RegisterTypeReader<SingleReader>();
RegisterTypeReader<DoubleReader>();
RegisterTypeReader<BooleanReader>();
RegisterTypeReader<CharReader>();
RegisterTypeReader<StringReader>();
RegisterTypeReader<ObjectReader>();
// System types.
RegisterGenericReader<EnumReader>();
RegisterGenericReader<NullableReader>();
RegisterGenericReader<ArrayReader>();
RegisterGenericReader<ListReader>();
RegisterGenericReader<DictionaryReader>();
RegisterTypeReader<TimeSpanReader>();
RegisterTypeReader<DateTimeReader>();
RegisterTypeReader<DecimalReader>();
RegisterTypeReader<ExternalReferenceReader>();
RegisterGenericReader<ReflectiveReader>();
// Math types.
RegisterTypeReader<Vector2Reader>();
RegisterTypeReader<Vector3Reader>();
RegisterTypeReader<Vector4Reader>();
RegisterTypeReader<MatrixReader>();
RegisterTypeReader<QuaternionReader>();
RegisterTypeReader<ColorReader>();
RegisterTypeReader<PlaneReader>();
RegisterTypeReader<PointReader>();
RegisterTypeReader<RectangleReader>();
RegisterTypeReader<BoundingBoxReader>();
RegisterTypeReader<BoundingSphereReader>();
RegisterTypeReader<BoundingFrustumReader>();
RegisterTypeReader<RayReader>();
RegisterTypeReader<CurveReader>();
// Graphics types.
RegisterTypeReader<TextureReader>();
RegisterTypeReader<Texture2DReader>();
RegisterTypeReader<Texture3DReader>();
RegisterTypeReader<TextureCubeReader>();
RegisterTypeReader<IndexBufferReader>();
RegisterTypeReader<VertexBufferReader>();
RegisterTypeReader<VertexDeclarationReader>();
RegisterTypeReader<EffectReader>();
RegisterTypeReader<EffectMaterialReader>();
RegisterTypeReader<BasicEffectReader>();
RegisterTypeReader<AlphaTestEffectReader>();
RegisterTypeReader<DualTextureEffectReader>();
RegisterTypeReader<EnvironmentMapEffectReader>();
RegisterTypeReader<SkinnedEffectReader>();
RegisterTypeReader<SpriteFontReader>();
RegisterTypeReader<ModelReader>();
// Media types.
RegisterTypeReader<SoundEffectReader>();
RegisterTypeReader<SongReader>();
RegisterTypeReader<VideoReader>();
}
TypeReader* TypeReaderManager::GetByReaderName(wstring const& readerName)
{
wstring wanted = StripAssemblyVersion(readerName);
// Look for a type reader with this name.
for each (TypeReader* reader in typeReaders)
{
if (reader->ReaderName() == wanted)
{
return reader;
}
}
// Could this be a specialization of a generic reader?
wstring genericReaderName;
vector<wstring> genericArguments;
if (SplitGenericTypeName(wanted, &genericReaderName, &genericArguments))
{
// Look for a generic reader factory with this name.
for each (GenericTypeReaderFactory* factory in genericReaders)
{
if (factory->GenericReaderName() == genericReaderName)
{
// Create a specialized generic reader instance.
GenericTypeReader* reader = factory->CreateTypeReader(genericArguments);
assert(reader->ReaderName() == wanted);
typeReaders.push_back(reader);
return reader;
}
}
}
// Fatal error if we cannot find a suitable reader.
char message[256];
sprintf_s(message, "Can't find type reader '%S'.", wanted.c_str());
throw exception(message);
}
TypeReader* TypeReaderManager::GetByTargetType(wstring const& targetType)
{
wstring wanted = StripAssemblyVersion(targetType);
// Look for a reader with this target type name.
for each (TypeReader* reader in typeReaders)
{
if (reader->TargetType() == wanted)
{
return reader;
}
}
// Fatal error if we cannot find a suitable reader.
char message[256];
sprintf_s(message, "Can't find reader for target type '%S'.", wanted.c_str());
throw exception(message);
}
wstring TypeReaderManager::StripAssemblyVersion(wstring typeName)
{
// Maps "foo, key=bar" -> "foo"
// Maps "foo[bar, key=baz], key=barg" -> "foo[bar]"
size_t commaIndex = 0;
while ((commaIndex = typeName.find(',', commaIndex)) != wstring::npos)
{
if (commaIndex + 1 < typeName.npos && typeName[commaIndex + 1] == '[')
{
// Skip past the comma in the ],[ part of a generic type argument list.
commaIndex++;
}
else
{
// Strip trailing assembly version information after other commas.
size_t closeBracket = typeName.find(']', commaIndex);
if (closeBracket != wstring::npos)
{
typeName.erase(commaIndex, closeBracket - commaIndex);
}
else
{
typeName.erase(commaIndex);
}
}
}
return typeName;
}
bool TypeReaderManager::SplitGenericTypeName(wstring const& typeName, wstring* genericName, vector<wstring>* genericArguments)
{
// Splits "foo`2[[bar],[baz]]" into genericName = "foo", genericArguments = { "bar", "baz" }
// Look for the ` generic marker character.
size_t pos = typeName.find('`');
if (pos == wstring::npos)
return false;
// Everything to the left of ` is the generic type name.
*genericName = typeName.substr(0, pos);
// Advance to the start of the generic argument list.
pos++;
while (pos < typeName.size() && iswdigit(typeName[pos]))
pos++;
while (pos < typeName.size() && typeName[pos] == '[')
pos++;
// Split up the list of generic type arguments.
while (pos < typeName.size() && typeName[pos] != ']')
{
// Locate the end of the current type name argument.
int nesting = 0;
size_t end;
for (end = pos; end < typeName.size(); end++)
{
// Handle nested types in case we have eg. "List`1[[List`1[[Int]]]]".
if (typeName[end] == '[')
{
nesting++;
}
else if (typeName[end] == ']')
{
if (nesting > 0)
nesting--;
else
break;
}
}
// Extract the type name argument.
genericArguments->push_back(typeName.substr(pos, end - pos));
// Skip past the type name, plus any subsequent "],[" goo.
pos = end;
if (pos < typeName.size() && typeName[pos] == ']')
pos++;
if (pos < typeName.size() && typeName[pos] == ',')
pos++;
if (pos < typeName.size() && typeName[pos] == '[')
pos++;
}
return true;
}
| 29.088803 | 126 | 0.638174 | [
"vector"
] |
946dff36ed4f0b87e626fdacf48e385a3d3a6020 | 1,943 | cpp | C++ | leetcode/30_days_challenge/2020_6_June/day19.cpp | bvbasavaraju/competitive_programming | a82ffc1b639588a84f4273b44285d57cdc2f4b11 | [
"Apache-2.0"
] | 1 | 2020-05-05T13:06:51.000Z | 2020-05-05T13:06:51.000Z | leetcode/30_days_challenge/2020_6_June/day19.cpp | bvbasavaraju/competitive_programming | a82ffc1b639588a84f4273b44285d57cdc2f4b11 | [
"Apache-2.0"
] | null | null | null | leetcode/30_days_challenge/2020_6_June/day19.cpp | bvbasavaraju/competitive_programming | a82ffc1b639588a84f4273b44285d57cdc2f4b11 | [
"Apache-2.0"
] | null | null | null | /****************************************************
Date: June 19th
link: https://leetcode.com/explore/challenge/card/june-leetcoding-challenge/541/week-3-june-15th-june-21st/3365/
****************************************************/
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <string>
#include <stack>
#include <queue>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <cmath>
#include <limits.h>
#include <string_view>
using namespace std;
/*
Q: Longest Duplicate Substring
Given a string S, consider all duplicated substrings: (contiguous) substrings of S that occur 2 or more times (The occurrences may overlap).
Return any duplicated substring that has the longest possible length. (If S does not have a duplicated substring, the answer is "".)
Example 1:
Input: "banana"
Output: "ana"
Example 2:
Input: "abcd"
Output: ""
Note:
2 <= S.length <= 10^5
S consists of lowercase English letters.
Hide Hint #1
Binary search for the length of the answer. (If there's an answer of length 10, then there are answers of length 9, 8, 7, ...)
Hide Hint #2
To check whether an answer of length K exists, we can use Rabin-Karp 's algorithm.
*/
class Solution
{
public:
string longestDupSubstring(string S)
{
std::string_view str;
unordered_set<string_view> strs;
int lo = 1;
int hi = S.size() - 1;
while(lo <= hi)
{
int m = lo + (hi - lo)/2;
bool found_dup = false;
for(int i = 0; i < S.size() - m + 1; ++i)
{
auto[it, inserted] = strs.emplace(S.data() + i, m);
if(!inserted)
{
found_dup = true;
str = *it;
break;
}
}
if(found_dup)
{
lo = m + 1;
}
else
{
hi = m - 1;
}
}
return {str.begin(), str.end()};
}
}; | 22.593023 | 142 | 0.564591 | [
"vector"
] |
20e3dd6f1d55793e41c1d8160f50f0ada1c5ee3b | 2,628 | cpp | C++ | leetcode/30_days_challenge/2020_10_October/1.cpp | bvbasavaraju/competitive_programming | a82ffc1b639588a84f4273b44285d57cdc2f4b11 | [
"Apache-2.0"
] | 1 | 2020-05-05T13:06:51.000Z | 2020-05-05T13:06:51.000Z | leetcode/30_days_challenge/2020_10_October/1.cpp | bvbasavaraju/competitive_programming | a82ffc1b639588a84f4273b44285d57cdc2f4b11 | [
"Apache-2.0"
] | null | null | null | leetcode/30_days_challenge/2020_10_October/1.cpp | bvbasavaraju/competitive_programming | a82ffc1b639588a84f4273b44285d57cdc2f4b11 | [
"Apache-2.0"
] | null | null | null | /****************************************************
Date: Oct 1st
link: https://leetcode.com/explore/challenge/card/september-leetcoding-challenge/554/week-1-september-1st-september-7th/3448/
****************************************************/
#include <iostream>
#include <vector>
#include <list>
#include <algorithm>
#include <string>
#include <stack>
#include <queue>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <cmath>
#include <limits.h>
using namespace std;
/*
Q: Number of Recent Calls
You have a RecentCounter class which counts the number of recent requests within a certain time frame.
Implement the RecentCounter class:
+ RecentCounter() Initializes the counter with zero recent requests.
+ int ping(int t) Adds a new request at time t, where t represents some time in milliseconds,
and returns the number of requests that has happened in the past 3000 milliseconds (including the new request).
Specifically, return the number of requests that have happened in the inclusive range [t - 3000, t].
It is guaranteed that every call to ping uses a strictly larger value of t than the previous call.
Example 1:
Input
["RecentCounter", "ping", "ping", "ping", "ping"]
[[], [1], [100], [3001], [3002]]
Output
[null, 1, 2, 3, 3]
Explanation
RecentCounter recentCounter = new RecentCounter();
recentCounter.ping(1); // requests = [1], range is [-2999,1], return 1
recentCounter.ping(100); // requests = [1, 100], range is [-2900,100], return 2
recentCounter.ping(3001); // requests = [1, 100, 3001], range is [1,3001], return 3
recentCounter.ping(3002); // requests = [1, 100, 3001, 3002], range is [2,3002], return 3
Constraints:
1 <= t <= 109
Each test case will call ping with strictly increasing values of t.
At most 104 calls will be made to ping.
*/
class RecentCounter
{
private:
class MyComparator_t
{
public:
bool operator()(const int &item1, const int &item2)
{
return item1 > item2;
}
};
priority_queue<int, vector<int>, MyComparator_t> pq;
public:
RecentCounter()
{
}
int ping(int t)
{
pq.push(t);
while (pq.top() < (t - 3000))
{
pq.pop();
}
return pq.size();
}
};
/**
* Your RecentCounter object will be instantiated and called as such:
* RecentCounter* obj = new RecentCounter();
* int param_1 = obj->ping(t);
*/ | 29.2 | 125 | 0.596271 | [
"object",
"vector"
] |
20e59fb5869c0e33fe695cd01e15db6313d8bab0 | 41,472 | cpp | C++ | groups/bdl/bdlat/bdlat_arrayfunctions.t.cpp | cmaggu/bde | 016dff5d5d2fbbed9570f4c1011af7b1a4c55a0d | [
"Apache-2.0"
] | 1 | 2021-11-10T16:53:42.000Z | 2021-11-10T16:53:42.000Z | groups/bdl/bdlat/bdlat_arrayfunctions.t.cpp | cmaggu/bde | 016dff5d5d2fbbed9570f4c1011af7b1a4c55a0d | [
"Apache-2.0"
] | null | null | null | groups/bdl/bdlat/bdlat_arrayfunctions.t.cpp | cmaggu/bde | 016dff5d5d2fbbed9570f4c1011af7b1a4c55a0d | [
"Apache-2.0"
] | null | null | null | // bdlat_arrayfunctions.t.cpp -*-C++-*-
// ----------------------------------------------------------------------------
// NOTICE
//
// This component is not up to date with current BDE coding standards, and
// should not be used as an example for new development.
// ----------------------------------------------------------------------------
#include <bdlat_arrayfunctions.h>
#include <bslim_testutil.h>
#include <bdlat_typetraits.h>
#include <bslalg_typetraits.h>
#include <bslmf_assert.h>
#include <bslmf_if.h>
#include <bslmf_issame.h> // for testing only
#include <bsl_algorithm.h> // 'bsl::max', 'bsl::copy', 'bsl::fill'
#include <bsl_cstdlib.h> // 'bsl::free', 'bsl::malloc'
#include <bsl_cstring.h> // 'bsl::memcpy', 'bsl::memset'
#include <bsl_iostream.h>
#include <bsl_sstream.h> // 'bsl::ostringstream'
#include <bsl_vector.h>
using namespace BloombergLP;
using namespace bsl; // automatically added by script
//=============================================================================
// TEST PLAN
//-----------------------------------------------------------------------------
// Overview
// --------
// TBD doc
//-----------------------------------------------------------------------------
// [ 2] struct IsArray<TYPE>
// [ 2] struct ElementType<TYPE>
// [ 1] METHOD FORWARDING TEST
//-----------------------------------------------------------------------------
// [ 3] USAGE EXAMPLE
// ============================================================================
// STANDARD BDE ASSERT TEST FUNCTION
// ----------------------------------------------------------------------------
namespace {
int testStatus = 0;
void aSsErT(bool condition, const char *message, int line)
{
if (condition) {
cout << "Error " __FILE__ "(" << line << "): " << message
<< " (failed)" << endl;
if (0 <= testStatus && testStatus <= 100) {
++testStatus;
}
}
}
} // close unnamed namespace
// ============================================================================
// STANDARD BDE TEST DRIVER MACRO ABBREVIATIONS
// ----------------------------------------------------------------------------
#define ASSERT BSLIM_TESTUTIL_ASSERT
#define ASSERTV BSLIM_TESTUTIL_ASSERTV
#define LOOP_ASSERT BSLIM_TESTUTIL_LOOP_ASSERT
#define LOOP0_ASSERT BSLIM_TESTUTIL_LOOP0_ASSERT
#define LOOP1_ASSERT BSLIM_TESTUTIL_LOOP1_ASSERT
#define LOOP2_ASSERT BSLIM_TESTUTIL_LOOP2_ASSERT
#define LOOP3_ASSERT BSLIM_TESTUTIL_LOOP3_ASSERT
#define LOOP4_ASSERT BSLIM_TESTUTIL_LOOP4_ASSERT
#define LOOP5_ASSERT BSLIM_TESTUTIL_LOOP5_ASSERT
#define LOOP6_ASSERT BSLIM_TESTUTIL_LOOP6_ASSERT
#define Q BSLIM_TESTUTIL_Q // Quote identifier literally.
#define P BSLIM_TESTUTIL_P // Print identifier and value.
#define P_ BSLIM_TESTUTIL_P_ // P(X) without '\n'.
#define T_ BSLIM_TESTUTIL_T_ // Print a tab (w/o newline).
#define L_ BSLIM_TESTUTIL_L_ // current Line number
// ============================================================================
// GLOBAL TYPEDEFS/CONSTANTS FOR TESTING
// ----------------------------------------------------------------------------
namespace Obj = bdlat_ArrayFunctions;
// ============================================================================
// CLASSES FOR TESTING
// ----------------------------------------------------------------------------
// ===========================
// class GetValue<LVALUE_TYPE>
// ===========================
template <class LVALUE_TYPE>
class GetValue {
// This visitor assigns the value of the visited member to
// 'd_destination_p'.
// PRIVATE DATA MEMBERS
LVALUE_TYPE *d_lValue_p; // held, not owned
public:
// CREATORS
explicit GetValue(LVALUE_TYPE *lValue);
// ACCESSORS
int operator()(const LVALUE_TYPE& object) const;
// Assign the specified 'object' to '*d_destination_p'.
template <class RVALUE_TYPE>
int operator()(const RVALUE_TYPE& object) const;
// Do nothing with the specified 'object'.
};
// ==============================
// class AssignValue<RVALUE_TYPE>
// ==============================
template <class RVALUE_TYPE>
class AssignValue {
// This visitor assigns 'd_value' to the visited member.
// PRIVATE DATA MEMBERS
RVALUE_TYPE d_value;
public:
// CREATORS
explicit AssignValue(const RVALUE_TYPE& value);
// ACCESSORS
int operator()(RVALUE_TYPE *object) const;
// Assign 'd_value' to the specified '*object'.
template <class LVALUE_TYPE>
int operator()(LVALUE_TYPE *object) const;
// Do nothing with the specified 'object'.
};
// ================
// class FixedArray
// ================
namespace Test {
template <int SIZE, class TYPE>
class FixedArray
{
// Fixed-sized array that conforms to the 'bdlat_ArrayFunctions'
// interface.
TYPE d_values[SIZE];
int d_length;
public:
FixedArray();
// Compiler-generated functions:
// FixedArray(const FixedArray&);
// FixedArray& operator=(const FixedArray&);
// ~FixedArray();
// MANIPULATORS
void append(const TYPE& v);
void resize(int newSize);
template <class MANIPULATOR>
int manipulateElement(MANIPULATOR& manip, int index);
// ACCESSORS
int length() const;
template <class ACCESSOR>
int accessElement(ACCESSOR& acc, int index) const;
};
// FREE MANIPULATORS
template <int SIZE, class TYPE, class MANIPULATOR>
int bdlat_arrayManipulateElement(FixedArray<SIZE, TYPE> *array,
MANIPULATOR& manipulator,
int index);
template <int SIZE, class TYPE>
void bdlat_arrayResize(FixedArray<SIZE, TYPE> *array, int newSize);
// FREE ACCESSORS
template <int SIZE, class TYPE, class ACCESSOR>
int bdlat_arrayAccessElement(const FixedArray<SIZE, TYPE>& array,
ACCESSOR& accessor,
int index);
template <int SIZE, class TYPE>
bsl::size_t bdlat_arraySize(const FixedArray<SIZE, TYPE>& array);
// Return the number of elements in the specified 'array'.
} // close namespace Test
namespace BloombergLP {
namespace bdlat_ArrayFunctions {
// META FUNCTIONS
template <int SIZE, class TYPE>
struct ElementType<Test::FixedArray<SIZE, TYPE> > {
typedef TYPE Type;
};
template <int SIZE, class TYPE>
struct IsArray<Test::FixedArray<SIZE, TYPE> > : public bslmf::MetaInt<1> {
};
} // close namespace bdlat_ArrayFunctions
} // close enterprise namespace
// ---------------------------
// class GetValue<LVALUE_TYPE>
// ---------------------------
// CREATORS
template <class LVALUE_TYPE>
GetValue<LVALUE_TYPE>::GetValue(LVALUE_TYPE *lValue)
: d_lValue_p(lValue)
{
}
// ACCESSORS
template <class LVALUE_TYPE>
int GetValue<LVALUE_TYPE>::operator()(const LVALUE_TYPE& object) const
{
*d_lValue_p = object;
return 0;
}
template <class LVALUE_TYPE>
template <class RVALUE_TYPE>
int GetValue<LVALUE_TYPE>::operator()(const RVALUE_TYPE& object) const
{
return -1;
}
// ------------------------------
// class AssignValue<RVALUE_TYPE>
// ------------------------------
// CREATORS
template <class RVALUE_TYPE>
AssignValue<RVALUE_TYPE>::AssignValue(const RVALUE_TYPE& value)
: d_value(value)
{
}
// ACCESSORS
template <class RVALUE_TYPE>
int AssignValue<RVALUE_TYPE>::operator()(RVALUE_TYPE *object) const
{
*object = d_value;
return 0;
}
template <class RVALUE_TYPE>
template <class LVALUE_TYPE>
int AssignValue<RVALUE_TYPE>::operator()(LVALUE_TYPE *object) const
{
return -1;
}
// ----------------------
// class Test::FixedArray
// ----------------------
template <int SIZE, class TYPE>
inline
Test::FixedArray<SIZE, TYPE>::FixedArray()
: d_length(0)
{
}
template <int SIZE, class TYPE>
inline
void Test::FixedArray<SIZE, TYPE>::append(const TYPE& v)
{
d_values[d_length++] = v;
}
template <int SIZE, class TYPE>
void Test::FixedArray<SIZE, TYPE>::resize(int newSize)
{
// If growing, then null out new elements
for (int i = d_length; i < newSize; ++i) {
d_values[i] = TYPE();
}
d_length = newSize;
}
template <int SIZE, class TYPE>
template <class MANIPULATOR>
inline
int Test::FixedArray<SIZE, TYPE>::manipulateElement(MANIPULATOR& manip,
int index)
{
return manip(&d_values[index]);
}
template <int SIZE, class TYPE>
inline
int Test::FixedArray<SIZE, TYPE>::length() const
{
return d_length;
}
template <int SIZE, class TYPE>
template <class ACCESSOR>
inline
int Test::FixedArray<SIZE, TYPE>::accessElement(ACCESSOR& acc, int index) const
{
return acc(d_values[index]);
}
// FREE MANIPULATORS
template <int SIZE, class TYPE, class MANIPULATOR>
int Test::bdlat_arrayManipulateElement(Test::FixedArray<SIZE, TYPE> *array,
MANIPULATOR& manip,
int index)
{
return array->manipulateElement(manip, index);
}
template <int SIZE, class TYPE>
void Test::bdlat_arrayResize(Test::FixedArray<SIZE, TYPE> *array, int newSize)
{
array->resize(newSize);
}
// FREE ACCESSORS
template <int SIZE, class TYPE, class ACCESSOR>
int Test::bdlat_arrayAccessElement(const Test::FixedArray<SIZE, TYPE>& array,
ACCESSOR& acc,
int index)
{
return array.accessElement(acc, index);
}
template <int SIZE, class TYPE>
bsl::size_t Test::bdlat_arraySize(const Test::FixedArray<SIZE, TYPE>& array)
{
return array.length();
}
// ============================================================================
// USAGE EXAMPLE
// ----------------------------------------------------------------------------
namespace BloombergLP {
namespace your {
class YourFloatArray {
float *d_data_p;
bsl::size_t d_size;
bsl::size_t d_capacity;
public:
// CREATORS
YourFloatArray()
: d_data_p(0)
, d_size(0)
{
}
~YourFloatArray()
{
delete[] d_data_p;
}
// MANIPULATORS
void setSize(bsl::size_t newSize); // Too large for inline.
float& element(bsl::size_t index)
{
ASSERT(index < d_size);
return d_data_p[index];
}
// ACCESSORS
const float& element(bsl::size_t index) const
{
ASSERT(index < d_size);
return d_data_p[index];
}
bsl::size_t numElements() const
{
return d_size;
}
bsl::size_t capacity() const
{
return d_capacity;
}
};
void YourFloatArray::setSize(bsl::size_t newSize)
{
if (d_size == newSize) {
return; // RETURN
}
if (!d_data_p) {
d_data_p = new float[newSize](); // allocate and initialize
d_size = newSize;
d_capacity = newSize;
return; // RETURN
}
if (newSize < d_size) {
return; // RETURN
}
if (newSize <= d_capacity) {
bsl::fill(d_data_p + d_size, d_data_p + newSize, 0.0);
d_size = newSize;
return; // RETURN
}
d_capacity = bsl::max(static_cast<bsl::size_t>(1u), d_capacity * 2);
float *newData = new float[d_capacity];
bsl::copy(d_data_p, d_data_p + d_size, newData);
bsl::fill(newData + d_size, newData + newSize, 0.0);
delete[] d_data_p;
d_data_p = newData;
d_size = newSize;
}
// MANIPULATORS
template <class MANIPULATOR>
int bdlat_arrayManipulateElement(YourFloatArray *array,
MANIPULATOR& manipulator,
int index);
// Invoke the specified 'manipulator' on the address of the element at
// the specified 'index' of the specified 'array'. Return the value
// from the invocation of 'manipulator'. The behavior is undefined
// unless '0 <= index' and 'index < bdlat_arraySize(*array)'.
void bdlat_arrayResize(YourFloatArray *array, int newSize);
// Set the size of the specified modifiable 'array' to the specified
// 'newSize'. If 'newSize > size(array)', then 'newSize - size(array)'
// elements with default values (i.e., 'ElementType()') are appended to
// 'array'. If 'newSize < size(array)', then the
// 'size(array) - newSize' elements at the end of 'array' are
// destroyed. The behavior is undefined unless '0 <= newSize'.
// ACCESSORS
template <class ACCESSOR>
int bdlat_arrayAccessElement(const YourFloatArray& array,
ACCESSOR& accessor,
int index);
// Invoke the specified 'accessor' on a 'const'-reference to the
// element at the specified 'index' of the specified 'array'. Return
// the value from the invocation of 'accessor'. The behavior is
// undefined unless '0 <= index' and 'index < bdlat_arraySize(array)'.
bsl::size_t bdlat_arraySize(const YourFloatArray& array);
// Return the number of elements in the specified 'array'.
// MANIPULATORS
template <class MANIPULATOR>
int bdlat_arrayManipulateElement(YourFloatArray *array,
MANIPULATOR& manipulator,
int index)
{
ASSERT(array);
ASSERT(0 <= index);
ASSERT(static_cast<bsl::size_t>(index) < array->numElements());
return manipulator(&array->element(index));
}
void bdlat_arrayResize(YourFloatArray *array, int newSize)
{
ASSERT(array);
ASSERT(0 <= newSize);
array->setSize(newSize);
}
// ACCESSORS
template <class ACCESSOR>
int bdlat_arrayAccessElement(const YourFloatArray& array,
ACCESSOR& accessor,
int index)
{
ASSERT(0 <= index);
ASSERT(static_cast<bsl::size_t>(index) < array.numElements());
return accessor(array.element(index));
}
bsl::size_t bdlat_arraySize(const YourFloatArray& array)
{
return array.numElements();
}
} // close namespace your
namespace bdlat_ArrayFunctions {
// TRAITS
template <>
struct IsArray<your::YourFloatArray> {
enum { VALUE = 1 };
};
template <>
struct ElementType<your::YourFloatArray> {
typedef float Type;
};
} // close namespace bdlat_ArrayFunctions
} // close enterprise namespace
///Usage
//------
// The following code illustrate the usage of this component.
//
///Example 1: Defining an "Array" Type
// - - - - - - - - - - - - - - - - - -
// Suppose you had a type, 'mine::MyIntArray', that provides the essential
// features of an "array" type.
//..
namespace BloombergLP {
namespace mine {
class MyIntArray {
int *d_data_p;
bsl::size_t d_size;
public:
// CREATORS
MyIntArray()
: d_data_p(0)
, d_size(0)
{
}
~MyIntArray()
{
bsl::free(d_data_p);
}
// MANIPULATORS
void resize(bsl::size_t newSize);
int& value(bsl::size_t index)
{
ASSERT(index < d_size);
return d_data_p[index];
}
// ACCESSORS
const int& value(bsl::size_t index) const
{
ASSERT(index < d_size);
return d_data_p[index];
}
bsl::size_t size() const
{
return d_size;
}
};
void MyIntArray::resize(bsl::size_t newSize)
{
// Always match buffer to size exactly.
if (d_size == newSize) {
return; // RETURN
}
int *newData = static_cast<int *>(bsl::malloc(sizeof(int)
* newSize));
if (d_size < newSize) {
bsl::memcpy(newData, d_data_p, d_size * sizeof(int));
std::memset(newData + d_size,
0,
(newSize - d_size) * sizeof(int));
} else {
bsl::memcpy(newData, d_data_p, newSize);
}
bsl::free(d_data_p);
d_data_p = newData;
d_size = newSize;
}
} // close namespace mine
} // close enterprise namespace
//.
// We can now make 'mine::MyIntArray' expose "array" behavior by implementing
// the necessary 'bdlat_ArrayFunctions' for 'MyIntArray' inside the 'mine'
// namespace and defining the required meta-functions withing the
// 'bdlat_ArrayFunctions' namespace.
//
// First, we should forward declare all the functions that we will implement
// inside the 'mine' namespace:
//..
namespace BloombergLP {
namespace mine {
// MANIPULATORS
template <class MANIPULATOR>
int bdlat_arrayManipulateElement(MyIntArray *array,
MANIPULATOR& manipulator,
int index);
// Invoke the specified 'manipulator' on the address of the element at
// the specified 'index' of the specified 'array'. Return the value
// from the invocation of 'manipulator'. The behavior is undefined
// unless '0 <= index' and 'index < bdlat_arraySize(*array)'.
void bdlat_arrayResize(MyIntArray *array, int newSize);
// Set the size of the specified modifiable 'array' to the specified
// 'newSize'. If 'newSize > bdlat_arraySize(*array)', then
// 'newSize - bdlat_arraySize(*array)' elements with default values
// (i.e., 'ElementType()') are appended to 'array'. If
// 'newSize < bdlat_arraySize(*array)', then the
// 'bdlat_arraySize(*array) - newSize' elements at the end of 'array'
// are destroyed. The behavior is undefined unless '0 <= newSize'.
// ACCESSORS
template <class ACCESSOR>
int bdlat_arrayAccessElement(const MyIntArray& array,
ACCESSOR& accessor,
int index);
// Invoke the specified 'accessor' on a 'const'-reference to the
// element at the specified 'index' of the specified 'array'. Return
// the value from the invocation of 'accessor'. The behavior is
// undefined unless '0 <= index' and 'index < bdlat_arraySize(array)'.
bsl::size_t bdlat_arraySize(const MyIntArray& array);
// Return the number of elements in the specified 'array'.
} // close namespace mine
} // close enterprise namespace
//..
// Then, we will implement these functions. Recall that the two (non-template)
// functions should be defined in some '.cpp' file, unless you choose to make
// them 'inline' functions.
//..
namespace BloombergLP {
namespace mine {
// MANIPULATORS
template <class MANIPULATOR>
int bdlat_arrayManipulateElement(MyIntArray *array,
MANIPULATOR& manipulator,
int index)
{
ASSERT(array);
ASSERT(0 <= index);
ASSERT(static_cast<bsl::size_t>(index) < array->size());
return manipulator(&array->value(index));
}
void bdlat_arrayResize(MyIntArray *array, int newSize)
{
ASSERT(array);
ASSERT(0 <= newSize);
array->resize(newSize);
}
// ACCESSORS
template <class ACCESSOR>
int bdlat_arrayAccessElement(const MyIntArray& array,
ACCESSOR& accessor,
int index)
{
ASSERT(0 <= index);
ASSERT(static_cast<bsl::size_t>(index) < array.size());
return accessor(array.value(index));
}
bsl::size_t bdlat_arraySize(const MyIntArray& array)
{
return array.size();
}
} // close namespace mine
} // close enterprise namespace
//..
// Finally, we specialize the 'IsArray' and 'ElementType' meta-functions
// in the 'bdlat_ArrayFunctions' namespace for the
// 'mine::MyIntArray' type:
//..
namespace BloombergLP {
namespace bdlat_ArrayFunctions {
// TRAITS
template <>
struct IsArray<mine::MyIntArray> {
enum { VALUE = 1 };
};
template <>
struct ElementType<mine::MyIntArray> {
typedef int Type;
};
} // close namespace bdlat_ArrayFunctions
} // close enterprise namespace
//..
// This completes the 'bdlat' infrastructure for 'mine::MyIntArray' and
// allows the generic software to recognize the type as an array abstraction.
//
///Example 2: Using the Infrastructure Via General Methods
///- - - - - - - - - - - - - - - - - - - - - - - - - - - -
// The 'bdlat' "array" framework provides a set of fundamental operations
// common to any "array" type. We can build upon these operations to make our
// own utilities, or use them on our own types that are plugged into the
// framework, like 'mine::MyIntArray', which we created in {Example 1}. For
// example, we can use the (fundamental) operations in the
// 'bdlat_ArrayFunctions' namespace to operate on 'mine::MyIntArray', even
// though they have no knowledge of that type in particular:
//..
void usageMakeArray()
{
BSLMF_ASSERT(bdlat_ArrayFunctions::IsArray<mine::MyIntArray>::VALUE);
mine::MyIntArray array;
ASSERT(0 == bdlat_ArrayFunctions::size(array));
bdlat_ArrayFunctions::resize(&array, 8);
ASSERT(8 == bdlat_ArrayFunctions::size(array));
bdlat_ArrayFunctions::resize(&array, 4);
ASSERT(4 == bdlat_ArrayFunctions::size(array));
}
//..
// To perform operations on the elements of an array requires use of the
// functions that employ accessor and manipulator functors. For example:
//..
template <class ELEMENT_TYPE>
class GetElementAccessor {
// DATA
ELEMENT_TYPE *d_element_p;
public:
// CREATORS
explicit GetElementAccessor(ELEMENT_TYPE *value)
: d_element_p(value)
{
}
// MANIPULATORS
int operator()(const ELEMENT_TYPE& elementValue)
{
*d_element_p = elementValue;
return 0;
}
};
template<class ELEMENT_TYPE>
class SetElementManipulator {
// DATA
ELEMENT_TYPE d_value;
public:
// CREATORS
SetElementManipulator(const ELEMENT_TYPE& value)
: d_value(value)
{
}
// ACCESSOR
int operator()(ELEMENT_TYPE *element) const
{
*element = d_value;
return 0;
}
};
//..
// Notice that these functors make few assumptions of 'ELEMENT_TYPE', merely
// that it is copy constructable and copy assignable.
//
// With these definitions we can now use the generic functions to set and
// get values from an 'mine::MyIntArray' object:
//..
void usageArrayElements()
{
mine::MyIntArray array;
bdlat_ArrayFunctions::resize(&array, 4);
// Confirm initial array elements from resize.
int value;
GetElementAccessor<int> accessor(&value);
for (int index = 0; index < 4; ++index) {
int rc = bdlat_ArrayFunctions::accessElement(array,
accessor,
index);
ASSERT(0 == rc);
ASSERT(0 == value)
}
// Set element 'index * 10' as its value;
for (int index = 0; index < 4; ++index) {
SetElementManipulator<int> manipulator(index * 10);
int rc = bdlat_ArrayFunctions::manipulateElement(&array,
manipulator,
index);
ASSERT(0 == rc);
}
// Confirm new value of each element.
for (int index = 0; index < 4; ++index) {
int rc = bdlat_ArrayFunctions::accessElement(array,
accessor,
index);
ASSERT(0 == rc);
ASSERT(index * 10 == value);
}
}
//..
//
///Example 3: Defining Utility Functions
///- - - - - - - - - - - - - - - - - - -
// Creating functor objects for each operation can be tedious and error prone;
// consequently, those types are often executed via utility functions.
//
// Suppose we want to create utilities for getting and setting the elements of
// an arbitrary "array" type. We might define a utility 'struct', 'ArrayUtil',
// a namespace for those functions:
//..
struct ArrayUtil {
// CLASS METHODS
template <class ARRAY_TYPE>
static int getElement(typename bdlat_ArrayFunctions
::ElementType<ARRAY_TYPE>::Type *value,
const ARRAY_TYPE& object,
int index)
// Load to the specified 'value' the element at the specified
// 'index' of the specified 'object' array. Return 0 if the
// element is successfully loaded to 'value', and a non-zero value
// otherwise. This function template requires that the specified
// 'ARRAY_TYPE' is a 'bdlat' "array" type. The behavior is
// undefined unless '0 <= index' and
// 'index < bdlat_ArrayFunctions::size(object)'.
{
BSLMF_ASSERT(bdlat_ArrayFunctions::IsArray<ARRAY_TYPE>::VALUE);
typedef typename bdlat_ArrayFunctions
::ElementType<ARRAY_TYPE>::Type ElementType;
GetElementAccessor<ElementType> elementAccessor(value);
return bdlat_ArrayFunctions::accessElement(object,
elementAccessor,
index);
}
template <class ARRAY_TYPE>
static int setElement(
ARRAY_TYPE *object,
int index,
const typename bdlat_ArrayFunctions::ElementType<ARRAY_TYPE>
::Type& value)
// Assign the specified 'value' to the element of the specified
// 'object' array at the specified 'index'. Return 0 if the
// element is successfully assigned to 'value', and a non-zero
// value otherwise. This function template requires that the
// specified 'ARRAY_TYPE' is a 'bdlat' "array" type. The behavior
// is undefined unless '0 <= index' and
// 'index < bdlat_ArrayFunctions::size(*object)'.
{
BSLMF_ASSERT(bdlat_ArrayFunctions::IsArray<ARRAY_TYPE>::VALUE);
typedef typename bdlat_ArrayFunctions::ElementType<ARRAY_TYPE>
::Type ElementType;
SetElementManipulator<ElementType> manipulator(value);
return bdlat_ArrayFunctions::manipulateElement(object,
manipulator,
index);
}
};
//..
// Now, we can use these functors to write generic utility functions for
// getting and setting the value types of arbitrary "array" classes.
//..
void myUsageScenario()
{
mine::MyIntArray array;
bdlat_ArrayFunctions::resize(&array, 4);
// Confirm initial values.
for (int index = 0; index < 4; ++index) {
int value;
int rc = ArrayUtil::getElement(&value, array, index);
ASSERT(0 == rc);
ASSERT(0 == value);
}
// Set element 'index * 10' as its value;
for (int index = 0; index < 4; ++index) {
int value = index * 10;
int rc = ArrayUtil::setElement(&array, index, value);
ASSERT(0 == rc);
}
// Confirm value of each element.
for (int index = 0; index < 4; ++index) {
int value;
int rc = ArrayUtil::getElement(&value, array, index);
ASSERT(0 == rc);
ASSERT(index * 10 == value);
}
}
//..
//
///Example 4: Achieving Type Independence
/// - - - - - - - - - - - - - - - - - - -
// Suppose we have another type such as 'your::YourFloatArray', shown below:
//..
// namespace BloombergLP {
// namespace your {
//
// class MyFloatArray {
//
// float *d_data_p;
// bsl::size_t d_size;
// bsl::size_t d_capacity;
//
// public:
// // CREATORS
// MyFloatArray()
// : d_data_p(0)
// , d_size(0)
// {
// }
//
// ~MyFloatArray()
// {
// delete[] d_data_p;
// }
//
// // MANIPULATORS
// void setSize(bsl::size_t newSize); // Too large for inline.
//
// float& element(bsl::size_t index)
// {
// ASSERT(index < d_size);
//
// return d_data_p[index];
// }
//
// // ACCESSORS
// const float& element(bsl::size_t index) const
// {
// ASSERT(index < d_size);
//
// return d_data_p[index];
// }
//
// bsl::size_t numElements() const
// {
// return d_size;
// }
//
// bsl::size_t capacity() const
// {
// return d_capacity;
// }
// };
//..
// Notice that while there are many similarities to 'mine::MyIntArray', there
// are also significant differences:
//: o The element type is 'float', not 'int'.
//: o Many of the accessors are named differently (e.g., 'numElements' instead
//: of 'size', 'setSize' instead of 'resize').
//: o There is an additional attribute, 'capacity', because this class has a
//: 'setSize' method (not shown) that reduces calls to the heap by over
//: allocating when the size is increased beyond the current capacity.
//
// Nevertheless, since 'your::YourFloatArray' also provides the functions
// and types expected by the 'bdlat' infrastructure (not shown) we can
// successfully use 'your::FloatArray' value instead of 'mine::MyIntArray'
// in the previous usage scenario, with no other changes:
//..
void yourUsageScenario()
{
your::YourFloatArray array;
bdlat_ArrayFunctions::resize(&array, 4);
// Confirm initial values.
for (int index = 0; index < 4; ++index) {
float value;
int rc = ArrayUtil::getElement(&value, array, index);
ASSERT(0 == rc);
ASSERT(0.0 == value);
}
// Set element 'index * 10' as its value;
for (int index = 0; index < 4; ++index) {
float value = static_cast<float>(index * 10);
int rc = ArrayUtil::setElement(&array, index, value);
ASSERT(0 == rc);
}
// Confirm value of each element.
for (int index = 0; index < 4; ++index) {
float value;
int rc = ArrayUtil::getElement(&value, array, index);
ASSERT(0 == rc);
ASSERT(static_cast<float>(index * 10) == value);
}
}
//..
// Notice that syntax and order of 'bdlat_ArrayFunctions' function
// calls have not been changed. The only difference is that the element
// type has changed from 'int' to 'float'.
//
// Finally, instead of defining a new "array" type, we could substitute the
// existing type template 'bsl::vector'. Note that this component
// provides specializations of the 'bdlat_ArrayFunctions' for that
// type. Since the accessor and manipulator functions we created earlier are
// type neutral, we can simply drop 'bsl::vector<bsl::string>' into our
// familiar scenario:
//..
void anotherUsageScenario()
{
bsl::vector<bsl::string> array; // STANDARD ARRAY TYPE
bdlat_ArrayFunctions::resize(&array, 4);
// Confirm initial values.
for (int index = 0; index < 4; ++index) {
bsl::string value;
int rc = ArrayUtil::getElement(&value, array, index);
ASSERT(0 == rc);
ASSERT("" == value);
}
// Set element 'index * 10' as its value;
for (int index = 0; index < 4; ++index) {
bsl::ostringstream oss; oss << (index * 10);
int rc = ArrayUtil::setElement(&array, index, oss.str());
ASSERT(0 == rc);
}
// Confirm value of each element.
for (int index = 0; index < 4; ++index) {
bsl::string value;
int rc = ArrayUtil::getElement(&value, array, index);
bsl::ostringstream oss; oss << (index * 10);
ASSERT(0 == rc);
ASSERT(oss.str() == value);
}
}
//..
// ============================================================================
// MAIN PROGRAM
// ----------------------------------------------------------------------------
int main(int argc, char *argv[])
{
int test = argc > 1 ? atoi(argv[1]) : 0;
int verbose = argc > 2;
// int veryVerbose = argc > 3;
// int veryVeryVerbose = argc > 4;
cout << "TEST " << __FILE__ << " CASE " << test << endl;
switch (test) { case 0: // Zero is always the leading case.
case 3: {
// --------------------------------------------------------------------
// USAGE EXAMPLE
//
// Testing:
// USAGE EXAMPLE
// --------------------------------------------------------------------
if (verbose) cout << "\nTesting Usage Example"
<< "\n=====================" << endl;
usageMakeArray();
usageArrayElements();
myUsageScenario();
yourUsageScenario();
anotherUsageScenario();
} break;
case 2: {
// --------------------------------------------------------------------
// TESTING META-FUNCTIONS
//
// Concerns:
//
// Plan:
//
// Testing:
// struct IsArray
// struct ElementType
// --------------------------------------------------------------------
if (verbose) cout << "\nTesting meta-functions"
<< "\n======================" << endl;
ASSERT(0 == bdlat_ArrayFunctions::IsArray<int>::VALUE);
typedef
Obj::ElementType<Test::FixedArray<9, short> >::Type FAElementType;
ASSERT(1 ==
(bdlat_ArrayFunctions::IsArray<Test::FixedArray<3, char> >::VALUE));
ASSERT(1 == (bslmf::IsSame<FAElementType, short>::VALUE));
typedef Obj::ElementType<bsl::vector<int> >::Type VecElementType;
ASSERT(1 == bdlat_ArrayFunctions::IsArray<bsl::vector<int> >::VALUE);
ASSERT(1 == (bslmf::IsSame<VecElementType, int>::VALUE));
} break;
case 1: {
// --------------------------------------------------------------------
// METHOD FORWARDING TEST
//
// Concerns:
//
// Plan:
//
// Testing:
// --------------------------------------------------------------------
if (verbose) cout << endl
<< "METHOD FORWARDING TEST" << endl
<< "======================" << endl;
{
if (verbose) cout << "Testing forwarding with Test::FixedArray"
<< endl;
Test::FixedArray<10, int> mV; Test::FixedArray<10, int>& V = mV;
mV.append(66);
mV.append(77);
ASSERT(2 == Obj::size(V));
int value;
GetValue<int> getter(&value);
AssignValue<int> setter1(33);
AssignValue<int> setter2(44);
Obj::accessElement(V, getter, 0); ASSERT(66 == value);
Obj::accessElement(V, getter, 1); ASSERT(77 == value);
Obj::manipulateElement(&mV, setter1, 0);
Obj::manipulateElement(&mV, setter2, 1);
Obj::accessElement(V, getter, 0); ASSERT(33 == value);
Obj::accessElement(V, getter, 1); ASSERT(44 == value);
Obj::resize(&mV, 5);
ASSERT(5 == Obj::size(V));
Obj::accessElement(V, getter, 0); ASSERT(33 == value);
Obj::accessElement(V, getter, 1); ASSERT(44 == value);
Obj::accessElement(V, getter, 2); ASSERT( 0 == value);
Obj::accessElement(V, getter, 3); ASSERT( 0 == value);
Obj::accessElement(V, getter, 4); ASSERT( 0 == value);
Obj::resize(&mV, 3);
ASSERT(3 == Obj::size(V));
Obj::accessElement(V, getter, 0); ASSERT(33 == value);
Obj::accessElement(V, getter, 1); ASSERT(44 == value);
Obj::accessElement(V, getter, 2); ASSERT( 0 == value);
Obj::resize(&mV, 0);
ASSERT(0 == Obj::size(V));
}
{
if (verbose) cout << "Testing vector specialization" << endl;
bsl::vector<int> mV; const bsl::vector<int>& V = mV;
mV.push_back(66);
mV.push_back(77);
ASSERT(2 == Obj::size(V));
int value;
GetValue<int> getter(&value);
AssignValue<int> setter1(33);
AssignValue<int> setter2(44);
Obj::accessElement(V, getter, 0); ASSERT(66 == value);
Obj::accessElement(V, getter, 1); ASSERT(77 == value);
Obj::manipulateElement(&mV, setter1, 0);
Obj::manipulateElement(&mV, setter2, 1);
Obj::accessElement(V, getter, 0); ASSERT(33 == value);
Obj::accessElement(V, getter, 1); ASSERT(44 == value);
Obj::resize(&mV, 5);
ASSERT(5 == Obj::size(V));
Obj::accessElement(V, getter, 0); ASSERT(33 == value);
Obj::accessElement(V, getter, 1); ASSERT(44 == value);
Obj::accessElement(V, getter, 2); ASSERT( 0 == value);
Obj::accessElement(V, getter, 3); ASSERT( 0 == value);
Obj::accessElement(V, getter, 4); ASSERT( 0 == value);
Obj::resize(&mV, 3);
ASSERT(3 == Obj::size(V));
Obj::accessElement(V, getter, 0); ASSERT(33 == value);
Obj::accessElement(V, getter, 1); ASSERT(44 == value);
Obj::accessElement(V, getter, 2); ASSERT( 0 == value);
Obj::resize(&mV, 0);
ASSERT(0 == Obj::size(V));
}
} break;
default: {
cerr << "WARNING: CASE `" << test << "' NOT FOUND." << endl;
testStatus = -1;
}
}
if (testStatus > 0) {
cerr << "Error, non-zero test status = " << testStatus << "." << endl;
}
return testStatus;
}
// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
| 32.198758 | 79 | 0.516517 | [
"object",
"vector"
] |
20ec8623093bdd2585c4818f05c679043c247ea3 | 1,020 | cpp | C++ | daily_challenge/August_LeetCoding_Challenge_2021/paintFence.cpp | archit-1997/LeetCode | 7c0f74da0836d3b0855f09bae8960f81a384f3f3 | [
"MIT"
] | 1 | 2021-01-27T16:37:36.000Z | 2021-01-27T16:37:36.000Z | daily_challenge/August_LeetCoding_Challenge_2021/paintFence.cpp | archit-1997/LeetCode | 7c0f74da0836d3b0855f09bae8960f81a384f3f3 | [
"MIT"
] | null | null | null | daily_challenge/August_LeetCoding_Challenge_2021/paintFence.cpp | archit-1997/LeetCode | 7c0f74da0836d3b0855f09bae8960f81a384f3f3 | [
"MIT"
] | null | null | null | /**
* @author : archit
* @GitHub : archit-1997
* @Email : architsingh456@gmail.com
* @file : paintFence.cpp
* @created : Saturday Aug 14, 2021 10:11:15 IST
*/
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int numWays(int n, int k) {
if(n==1)
return k;
else if(n==2)
return (k+k*(k-1));
else{
vector<vector<int>> dp(2,vector<int> (n,0));
dp[0][1]=k;
dp[1][1]=k*(k-1);
for(int j=2;j<n;j++){
//for the two last fences of the same color, we can use the one with last two with different color
dp[0][j]=dp[1][j-1];
//for the two with different colors, we can how many we had till this point and then we can just have
//one less color
int sum=dp[0][j-1]+dp[1][j-1];
dp[1][j]=sum*(k-1);
}
return dp[0][n-1]+dp[1][n-1];
}
}
};
| 28.333333 | 117 | 0.466667 | [
"vector"
] |
20f1accc3801f369b11f415ac61ee8ac54f1ffca | 8,587 | cpp | C++ | optionFileSet.cpp | easyeagel/ezsh | 5fb627978cf38ec1c375eb51b60954b0dfa86031 | [
"MIT"
] | null | null | null | optionFileSet.cpp | easyeagel/ezsh | 5fb627978cf38ec1c375eb51b60954b0dfa86031 | [
"MIT"
] | null | null | null | optionFileSet.cpp | easyeagel/ezsh | 5fb627978cf38ec1c375eb51b60954b0dfa86031 | [
"MIT"
] | 1 | 2019-06-07T10:03:20.000Z | 2019-06-07T10:03:20.000Z | // Copyright [2014] <lgb (LiuGuangBao)>
//=====================================================================================
//
// Filename: fileset.cpp
//
// Description: 文件集合操作
//
// Version: 1.0
// Created: 2014年12月29日 16时00分33秒
// Revision: none
// Compiler: gcc
//
// Author: lgb (LiuGuangBao), easyeagel@gmx.com
// Organization: ezbty.org
//
//=====================================================================================
//
#include"optionFileSet.hpp"
#include<cctype>
#include<deque>
#include<locale>
#include<algorithm>
#include<core/encode.hpp>
#include<boost/algorithm/string/predicate.hpp>
#include"glob.hpp"
namespace ezsh
{
FileUnit::FileUnit(const Path& selfIn, const Path& baseIn, bool scanedIn)
:scaned(scanedIn), self(selfIn), base(baseIn), total(normalize(baseIn/selfIn))
{
refresh();
}
void FileUnit::refresh()
{
ErrorCode ec;
status=bf::status(total, ec);
if(status.type()==bf::file_type::file_not_found)
return;
ec.clear();
size=bf::file_size(total, ec);
if(size==static_cast<uint64_t>(-1) || ec)
size=0;
ctime=bf::last_write_time(total);
}
Path FileUnit::normalize(const Path& path)
{
if(path.empty())
return path;
//删除路径中多余的 . ..
std::deque<Path> stk;
for(auto itr=path.begin(), end=path.end(); itr!=end; ++itr)
{
if(*itr==".")
continue;
if(*itr==".." && !stk.empty() && stk.back()!="..")
{
stk.pop_back();
continue;
}
stk.push_back(*itr);
}
bf::path ret;
for(auto& p: stk)
ret /= p;
if(ret.empty())
return ".";
return ret;
}
Path FileUnit::sub(const Path& path, const Path& base)
{
auto count=std::distance(base.begin(), base.end());
auto itr=path.begin(), end=path.end();
while(count-- && itr!=end)
++itr;
bf::path ret;
for(; itr!=end; ++itr)
ret /= *itr;
if(ret.empty())
return Path(".");
return ret;
}
static uint64_t sizeRead(const std::string& input)
{
uint64_t const K=1024, M=1024*1024, G=1024*1024*1024;
auto msg=input.c_str();
const char* str=nullptr;
unsigned n=0, k=0, m=0, g=0;
for(; *msg; msg += 1)
{
if(*msg>='0' && *msg<='9')
{
if(str==nullptr)
str=msg;
continue;
} else if(std::isspace(*msg)) {
continue;
} else {
if(str==nullptr)
throw bp::error("invalid file size pattern");
switch(*msg)
{
case 'G':
case 'g':
g=std::strtoul(str, nullptr, 10);
break;
case 'M':
case 'm':
m=std::strtoul(str, nullptr, 10);
break;
case 'K':
case 'k':
k=std::strtoul(str, nullptr, 10);
break;
}
str=nullptr;
}
}
if(str!=nullptr)
n=std::strtoul(str, nullptr, 0);
return g*G + m*M + k*K + n;
}
void FileSet::sizeEqual(const std::vector<std::string>& sizes, bool n)
{
std::vector<uint64_t> sz;
for(auto s: sizes)
sz.push_back(sizeRead(s));
predications_.emplace_back([sz, n](const FileUnit& u)
{
return std::any_of(sz.begin(), sz.end(), [&u, n](uint64_t s){ return n ? s!=u.size : s==u.size; });
}
);
}
void FileSet::afterParse(const bp::variables_map& vm)
{
auto itr=vm.find("fsSizeEqual");
if(itr!=vm.end())
sizeEqual(itr->second.as<std::vector<std::string>>(), false);
itr=vm.find("fsSizeNotEqual");
if(itr!=vm.end())
sizeEqual(itr->second.as<std::vector<std::string>>(), true);
#define MD(CppParam, CppOpt) \
itr=vm.find(#CppParam); \
if(itr!=vm.end()) \
{ \
const auto sz=sizeRead(itr->second.as<std::string>()); \
predications_.emplace_back([sz](const FileUnit& u) \
{ \
return u.size CppOpt sz; \
} \
); \
}
MD(fsSizeLess, < )
MD(fsSizeGreater, > )
MD(fsSizeLessEqual, <= )
MD(fsSizeGreaterEqual, >= )
#undef MD
}
void FileSet::Component::options(bp::options_description& opt, bp::positional_options_description& pos)
{
opt.add_options()
("fsFile", bp::value<std::vector<std::string>>(), "files to set")
("fsGlob", bp::value<std::vector<std::string>>(), "glob parttern include in set")
("fsGlobNot", bp::value<std::vector<std::string>>(), "glob parttern not include in set")
("fsInclude", bp::value<std::vector<std::string>>(), "regex parttern included in set")
("fsExclude", bp::value<std::vector<std::string>>(), "regex parttern excluded from set")
("fsSizeEqual", bp::value<std::vector<std::string>>(), "size equal to, may many times")
("fsSizeNotEqual", bp::value<std::vector<std::string>>(), "size not equal to, may many times")
("fsSizeLess", bp::value<std::string>(), "size less than")
("fsSizeGreater", bp::value<std::string>(), "size greater than")
("fsSizeLessEqual", bp::value<std::string>(), "size less or equal to")
("fsSizeGreaterEqual", bp::value<std::string>(), "size greater or equal to")
("fsRecursive", bp::value<size_t>()
->default_value(0)
->implicit_value(eRecursiveDefault),
"operate recursively")
;
pos.add("fsFile", -1);
}
void FileSet::Component::longHelp (std::ostream& strm)
{
bp::options_description opt;
bp::positional_options_description pos;
options(opt, pos);
strm << "fileset - select files with parttern or regex\n";
strm << opt << std::endl;
}
void FileSet::Component::shortHelp(std::ostream& strm)
{
strm << " *fileset - rules for file select, \"option fileset\" for details" << std::endl;
}
void FileSet::init(const bp::variables_map& vm)
{
recursive_=vm["fsRecursive"].as<size_t>();
auto itr =vm.find("fsFile");
if(itr!=vm.end())
files_=itr->second.as<std::vector<std::string>>();
itr =vm.find("fsGlob");
if(itr!=vm.end())
glob_=itr->second.as<std::vector<std::string>>();
itr =vm.find("fsGlobNot");
if(itr!=vm.end())
globNot_=itr->second.as<std::vector<std::string>>();
itr =vm.find("fsInclude");
if(itr!=vm.end())
{
auto const& t=itr->second.as<std::vector<std::string>>();
includes_.reserve(t.size());
for(const auto& r: t )
includes_.emplace_back(core::WCharConverter::from(r));
}
itr =vm.find("fsExclude");
if(itr!=vm.end())
{
auto const& t=itr->second.as<std::vector<std::string>>();
includes_.reserve(t.size());
for(const auto& r: t )
excludes_.emplace_back(core::WCharConverter::from(r));
}
for(const auto& file: files_)
{
FileUnit fu(file);
if(!isRight(fu))
continue;
sets_.emplace_back(std::move(fu));
}
}
bool FileSet::isRight(const FileUnit& fu) const
{
if (!globNot_.empty() || !glob_.empty())
{
const auto& file = fu.self.has_parent_path() ? fu.self.filename() : fu.self.path();
const auto& utf8File = core::WCharConverter::to(file.native());
for (const auto& g : glob_)
{
if (!Glob::match(g, utf8File))
return false;
}
for (const auto& g : globNot_)
{
if (Glob::match(g, utf8File))
return false;
}
}
//------------------------------------------------------------------
if (!includes_.empty() || !excludes_.empty())
{
const auto& wpath = core::WCharConverter::from(fu.self.native());
for (const auto& reg : includes_)
{
if (!std::regex_search(wpath, reg))
return false;
}
for (const auto& reg : excludes_)
{
if (std::regex_search(wpath, reg))
return false;
}
}
for(const auto& prd: predications_)
{
if(!prd(fu))
return false;
}
return true;
}
void FileSet::config(CmdBase& cmd)
{
cmd.componentPush(componentGet());
cmd.afterParseCall(std::bind(&FileSet::afterParse, this, std::placeholders::_1));
}
void FileSet::subtreeDone(const FileUnit& u)
{
for(auto& s: sets_)
{
if(s.isChild(u))
s.doneSet();
}
}
namespace
{
static ezsh::OptionRegisterT<ezsh::FileSet> gsOptionFileSet;
}
} // namespace ezsh
| 25.181818 | 111 | 0.533364 | [
"vector"
] |
20f518f411efb627f41165815671c59eefc80566 | 4,943 | cpp | C++ | Source/core/rendering/RenderTextFragment.cpp | Fusion-Rom/android_external_chromium_org_third_party_WebKit | 8865f83aaf400ef5f7c234a70da404d3fc5e1272 | [
"BSD-3-Clause"
] | 2 | 2016-05-19T10:37:25.000Z | 2019-09-18T04:37:14.000Z | Source/core/rendering/RenderTextFragment.cpp | Fusion-Rom/android_external_chromium_org_third_party_WebKit | 8865f83aaf400ef5f7c234a70da404d3fc5e1272 | [
"BSD-3-Clause"
] | null | null | null | Source/core/rendering/RenderTextFragment.cpp | Fusion-Rom/android_external_chromium_org_third_party_WebKit | 8865f83aaf400ef5f7c234a70da404d3fc5e1272 | [
"BSD-3-Clause"
] | 7 | 2015-09-23T09:56:29.000Z | 2022-01-20T10:36:06.000Z | /*
* (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 2000 Dirk Mueller (mueller@kde.org)
* Copyright (C) 2004, 2005, 2006, 2007 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "config.h"
#include "core/rendering/RenderTextFragment.h"
#include "core/dom/Text.h"
#include "core/rendering/HitTestResult.h"
#include "core/rendering/RenderBlock.h"
namespace blink {
RenderTextFragment::RenderTextFragment(Node* node, StringImpl* str, int startOffset, int length)
: RenderText(node, str ? str->substring(startOffset, length) : PassRefPtr<StringImpl>(nullptr))
, m_start(startOffset)
, m_end(length)
, m_firstLetter(nullptr)
{
}
RenderTextFragment::RenderTextFragment(Node* node, StringImpl* str)
: RenderText(node, str)
, m_start(0)
, m_end(str ? str->length() : 0)
, m_contentString(str)
, m_firstLetter(nullptr)
{
}
RenderTextFragment::~RenderTextFragment()
{
}
void RenderTextFragment::trace(Visitor* visitor)
{
visitor->trace(m_firstLetter);
RenderText::trace(visitor);
}
RenderText* RenderTextFragment::firstRenderTextInFirstLetter() const
{
for (RenderObject* current = m_firstLetter; current; current = current->nextInPreOrder(m_firstLetter)) {
if (current->isText())
return toRenderText(current);
}
return 0;
}
PassRefPtr<StringImpl> RenderTextFragment::originalText() const
{
Node* e = node();
RefPtr<StringImpl> result = ((e && e->isTextNode()) ? toText(e)->dataImpl() : contentString());
if (!result)
return nullptr;
return result->substring(start(), end());
}
void RenderTextFragment::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
{
RenderText::styleDidChange(diff, oldStyle);
if (RenderBlock* block = blockForAccompanyingFirstLetter()) {
block->style()->removeCachedPseudoStyle(FIRST_LETTER);
block->updateFirstLetter();
}
}
void RenderTextFragment::willBeDestroyed()
{
if (m_firstLetter)
m_firstLetter->destroy();
RenderText::willBeDestroyed();
}
void RenderTextFragment::setText(PassRefPtr<StringImpl> text, bool force)
{
RenderText::setText(text, force);
m_start = 0;
m_end = textLength();
if (m_firstLetter) {
// FIXME: We should not modify the structure of the render tree during
// layout. crbug.com/370458
DeprecatedDisableModifyRenderTreeStructureAsserts disabler;
ASSERT(!m_contentString);
m_firstLetter->destroy();
m_firstLetter = nullptr;
if (Node* t = node()) {
ASSERT(!t->renderer());
t->setRenderer(this);
}
}
}
void RenderTextFragment::transformText()
{
// Don't reset first-letter here because we are only transforming the truncated fragment.
if (RefPtr<StringImpl> textToTransform = originalText())
RenderText::setText(textToTransform.release(), true);
}
UChar RenderTextFragment::previousCharacter() const
{
if (start()) {
Node* e = node();
StringImpl* original = ((e && e->isTextNode()) ? toText(e)->dataImpl() : contentString());
if (original && start() <= original->length())
return (*original)[start() - 1];
}
return RenderText::previousCharacter();
}
RenderBlock* RenderTextFragment::blockForAccompanyingFirstLetter() const
{
if (!m_firstLetter)
return 0;
for (RenderObject* block = m_firstLetter->parent(); block; block = block->parent()) {
if (block->style()->hasPseudoStyle(FIRST_LETTER) && block->canHaveChildren() && block->isRenderBlock())
return toRenderBlock(block);
}
return 0;
}
void RenderTextFragment::updateHitTestResult(HitTestResult& result, const LayoutPoint& point)
{
if (result.innerNode())
return;
RenderObject::updateHitTestResult(result, point);
if (m_firstLetter || !node())
return;
RenderObject* nodeRenderer = node()->renderer();
if (!nodeRenderer || !nodeRenderer->isText() || !toRenderText(nodeRenderer)->isTextFragment())
return;
if (isDescendantOf(toRenderTextFragment(nodeRenderer)->m_firstLetter))
result.setIsFirstLetter(true);
}
} // namespace blink
| 30.512346 | 111 | 0.68683 | [
"render"
] |
20f938b3ee20dcbbd026cd0e745832c702ea830f | 924 | cpp | C++ | src/FolderHandler.cpp | adbailey4/embed_fast5 | 4416fab3927a4f3deae2f4637ff6c7344b4098c9 | [
"MIT"
] | null | null | null | src/FolderHandler.cpp | adbailey4/embed_fast5 | 4416fab3927a4f3deae2f4637ff6c7344b4098c9 | [
"MIT"
] | 1 | 2021-12-14T13:31:42.000Z | 2022-03-12T17:41:30.000Z | src/FolderHandler.cpp | adbailey4/embed_fast5 | 4416fab3927a4f3deae2f4637ff6c7344b4098c9 | [
"MIT"
] | null | null | null | //
// Created by Andrew Bailey on 2019-07-26.
//
// Embed
#include "FolderHandler.hpp"
#include "EmbedUtils.hpp"
// Boost libraries.
#include <boost/filesystem.hpp>
// Standard library.
#include <string>
using namespace boost::filesystem;
using namespace boost::coroutines2;
using namespace std;
using namespace embed_utils;
//FolderHandler::FolderHandler(path input_dir, uint64_t batch_size, string ext) :
// input_dir(std::move(input_dir)), batch_size(batch_size), ext(std::move(ext))
//{
// dir_coro::pull_type wp = list_files_in_dir(this->input_dir, this->ext);
//
//// shared_ptr<dir_coro::pull_type> sp = wp.lock();
////
////
//// generator = &tmp;
//}
//
//FolderHandler::~FolderHandler(){
// delete(generator);
//}
//
//vector<string> FolderHandler::get_batch(){
// vector<string> batch;
// batch.resize(this->batch_size);
// path something = generator->get();
// cout << something << "\n";
//
//}
| 21 | 82 | 0.681818 | [
"vector"
] |
20f9f8b4b9234c82c2c822eb3efbde0403f5a306 | 987 | hpp | C++ | Headers/Object_Methods.hpp | 777moneymaker/classProject | 8eac5cd5366a6a6c986eedb9553778e8e94ff4e8 | [
"MIT"
] | null | null | null | Headers/Object_Methods.hpp | 777moneymaker/classProject | 8eac5cd5366a6a6c986eedb9553778e8e94ff4e8 | [
"MIT"
] | null | null | null | Headers/Object_Methods.hpp | 777moneymaker/classProject | 8eac5cd5366a6a6c986eedb9553778e8e94ff4e8 | [
"MIT"
] | null | null | null | //
// Created by Miłosz Chodkowski on 2019-03-17.
//
#ifndef PROJEKT_PPO_OBJECTFUNCTIONS_H
#define PROJEKT_PPO_OBJECTFUNCTIONS_H
#include <iostream>
#include <fstream>
#include "Headers/Class_Base.hpp"
#include "Headers/Menu_Methods.hpp"
#include "Headers/Global_Variables.hpp"
namespace List{
void insertNode(std::string name); // insertion depends on actual level
void printObjects(); // prints every object in actual level
void deleteNodeByName(std::string name); // deletes node by name in actual level
void printObjectInfo(std::string name); // prints objects by given name
void modObject(std::string name); // modificates object by given name
void saveObjects(); // saves objects at current level. Clears file before saving
void readObjects(); // reads objects at current level. Doesn't clear existing objects
}
#endif //PROJEKT_PPO_OBJECTFUNCTIONS_H
| 37.961538 | 113 | 0.683891 | [
"object"
] |
20fb56adb948f1b869577bede4526aeb04997c87 | 15,341 | cxx | C++ | private/inet/wininet/auth/test/httpauth.cxx | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 11 | 2017-09-02T11:27:08.000Z | 2022-01-02T15:25:24.000Z | private/inet/wininet/auth/test/httpauth.cxx | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | null | null | null | private/inet/wininet/auth/test/httpauth.cxx | King0987654/windows2000 | 01f9c2e62c4289194e33244aade34b7d19e7c9b8 | [
"MIT"
] | 14 | 2019-01-16T01:01:23.000Z | 2022-02-20T15:54:27.000Z | // ===========================================================================
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright 1996 Microsoft Corporation. All Rights Reserved.
// ===========================================================================
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <io.h>
#include <wininet.h>
BOOL g_fAllowCustomUI;
DWORD g_dwConnectFlags;
BOOL g_fPreload;
BOOL g_fMonolithicUpload = FALSE;
DWORD g_dwPort = INTERNET_INVALID_PORT_NUMBER;
LPSTR g_szVerb = NULL;
//==============================================================================
BOOL NeedAuth (HINTERNET hRequest, DWORD *pdwStatus)
{
// Get status code.
DWORD dwStatus;
DWORD cbStatus = sizeof(dwStatus);
HttpQueryInfo
(
hRequest,
HTTP_QUERY_FLAG_NUMBER | HTTP_QUERY_STATUS_CODE,
&dwStatus,
&cbStatus,
NULL
);
fprintf (stderr, "Status: %d\n", dwStatus);
*pdwStatus = dwStatus;
// Look for 401 or 407.
DWORD dwFlags;
switch (dwStatus)
{
case HTTP_STATUS_DENIED:
dwFlags = HTTP_QUERY_WWW_AUTHENTICATE;
break;
case HTTP_STATUS_PROXY_AUTH_REQ:
dwFlags = HTTP_QUERY_PROXY_AUTHENTICATE;
break;
default:
return FALSE;
}
// Enumerate the authentication types.
BOOL fRet;
char szScheme[64];
DWORD dwIndex = 0;
do
{
DWORD cbScheme = sizeof(szScheme);
fRet = HttpQueryInfo
(hRequest, dwFlags, szScheme, &cbScheme, &dwIndex);
if (fRet)
fprintf (stderr, "Found auth scheme: %s\n", szScheme);
}
while (fRet);
return TRUE;
}
//==============================================================================
DWORD DoCustomUI (HINTERNET hRequest, BOOL fProxy)
{
// Prompt for username and password.
char szUser[64], szPass[64];
fprintf (stderr, "Enter Username: ");
if (!fscanf (stdin, "%s", szUser))
return ERROR_INTERNET_LOGIN_FAILURE;
fprintf (stderr, "Enter Password: ");
if (!fscanf (stdin, "%s", szPass))
return ERROR_INTERNET_LOGIN_FAILURE;
// Set the values in the handle.
if (fProxy)
{
InternetSetOption
(hRequest, INTERNET_OPTION_PROXY_USERNAME, szUser, sizeof(szUser));
InternetSetOption
(hRequest, INTERNET_OPTION_PROXY_PASSWORD, szPass, sizeof(szPass));
}
else
{
InternetSetOption
(hRequest, INTERNET_OPTION_USERNAME, szUser, sizeof(szUser));
InternetSetOption
(hRequest, INTERNET_OPTION_PASSWORD, szPass, sizeof(szPass));
}
return ERROR_INTERNET_FORCE_RETRY;
}
//==============================================================================
int RequestLoop (int argc, char **argv)
{
HINTERNET hInternet = NULL;
HINTERNET hConnect = NULL;
HINTERNET hRequest = NULL;
PSTR pPostData = NULL;
DWORD cbPostData = 0;
PSTR pszErr = NULL;
BOOL fRet;
#define CHECK_ERROR(cond, err) if (!(cond)) {pszErr=(err); goto done;}
PSTR pszHost = argv[0];
PSTR pszObject = argc >= 2 ? argv[1] : "/";
PSTR pszUser = argc >= 3 ? argv[2] : NULL;
PSTR pszPass = argc >= 4 ? argv[3] : NULL;
PSTR pszPostFile = argc >= 5 ? argv[4] : NULL;
if (pszPostFile)
g_dwConnectFlags |= INTERNET_FLAG_RELOAD;
//#ifdef MONOLITHIC_UPLOAD
if(g_fMonolithicUpload)
{
// Read any POST data into a buffer.
if (pszPostFile)
{
HANDLE hf =
CreateFile
(
pszPostFile,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
NULL
);
if (hf != INVALID_HANDLE_VALUE)
{
cbPostData = GetFileSize (hf, NULL);
pPostData = (PSTR) LocalAlloc (LMEM_FIXED, cbPostData + 1);
if (pPostData)
ReadFile (hf, pPostData, cbPostData, &cbPostData, NULL);
pPostData[cbPostData] = 0;
CloseHandle (hf);
}
}
} // g_fMonolithicUpload
//#endif
// Initialize wininet.
hInternet = InternetOpen
(
//"HttpAuth Sample", // user agent
"Mozilla/4.0 (compatible; MSIE 4.0b2; Windows 95",
INTERNET_OPEN_TYPE_PRECONFIG, // access type
NULL, // proxy server
0, // proxy port
0 // flags
);
CHECK_ERROR (hInternet, "InternetOpen");
// Connect to host.
hConnect = InternetConnect
(
hInternet, // wininet handle,
pszHost, // host
g_dwPort, // port
pszUser, // user
NULL, // password
INTERNET_SERVICE_HTTP, // service
g_dwConnectFlags, // flags
0 // context
);
CHECK_ERROR (hConnect, "InternetConnect");
// Use SetOption to set the password since it handles empty strings.
if (pszPass)
{
InternetSetOption
(hConnect, INTERNET_OPTION_PASSWORD, pszPass, lstrlen(pszPass)+1);
}
if(!g_szVerb) {
if(pszPostFile) {
g_szVerb = "PUT";
} else {
g_szVerb = "GET";
}
}
// Create request.
hRequest = HttpOpenRequest
(
hConnect, // connect handle
g_szVerb, // pszPostFile? "PUT" : "GET", // request method
pszObject, // object name
NULL, // version
NULL, // referer
NULL, // accept types
g_dwConnectFlags // flags
| INTERNET_FLAG_KEEP_CONNECTION
| SECURITY_INTERNET_MASK, // ignore SSL warnings
0 // context
);
CHECK_ERROR (hRequest, "HttpOpenRequest");
resend:
// if (!pszPostFile || pPostData)
if(g_fMonolithicUpload)
{
// Send request.
fRet = HttpSendRequest
(
hRequest, // request handle
"", // header string
0, // header length
pPostData, // post data
cbPostData // post length
);
}
else
{
HANDLE hf = CreateFile
(
pszPostFile,
GENERIC_READ,
FILE_SHARE_READ,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN,
NULL
);
if (hf != INVALID_HANDLE_VALUE)
{
cbPostData = GetFileSize (hf, NULL);
INTERNET_BUFFERS BufferIn;
BufferIn.dwStructSize = sizeof( INTERNET_BUFFERSA );
BufferIn.Next = NULL;
BufferIn.lpcszHeader = NULL;
BufferIn.dwHeadersLength = 0;
BufferIn.dwHeadersTotal = 0;
BufferIn.lpvBuffer = NULL;
BufferIn.dwBufferLength = 0;
BufferIn.dwBufferTotal = cbPostData;
BufferIn.dwOffsetLow = 0;
BufferIn.dwOffsetHigh = 0;
fRet = HttpSendRequestEx (hRequest, &BufferIn, NULL, 0, 0);
CHECK_ERROR (fRet, "HttpSendRequestEx");
while (1)
{
CHAR szTemp[512];
DWORD cbRead;
fRet = ReadFile (hf, szTemp, sizeof(szTemp), &cbRead, 0);
CHECK_ERROR (fRet, "ReadFile");
if (!fRet || !cbRead)
break;
DWORD cbRead2;
fRet = InternetWriteFile (hRequest, szTemp, cbRead, &cbRead2);
CHECK_ERROR (fRet, "InternetWriteFile");
}
CloseHandle (hf);
fRet = HttpEndRequest (hRequest, NULL, 0, 0);
if (!fRet && GetLastError() == ERROR_INTERNET_FORCE_RETRY)
goto resend;
}
}
DWORD dwStatus;
// Check if the status code is 401 or 407
if (NeedAuth (hRequest, &dwStatus) && (g_fAllowCustomUI))
{
// Prompt for username and password.
if (DoCustomUI (hRequest, dwStatus != HTTP_STATUS_DENIED))
goto resend;
}
else
{
DWORD dwSendErr = fRet? ERROR_SUCCESS : GetLastError();
DWORD dwDlgErr = InternetErrorDlg(
GetDesktopWindow(),
hRequest,
dwSendErr,
FLAGS_ERROR_UI_FILTER_FOR_ERRORS |
FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS |
FLAGS_ERROR_UI_FLAGS_GENERATE_DATA,
NULL
);
switch (dwSendErr)
{
case ERROR_SUCCESS:
case ERROR_INTERNET_NAME_NOT_RESOLVED:
case ERROR_INTERNET_CANNOT_CONNECT:
if (dwDlgErr == ERROR_INTERNET_FORCE_RETRY)
goto resend;
else
break;
case ERROR_HTTP_REDIRECT_NEEDS_CONFIRMATION:
default:
if (dwDlgErr == ERROR_SUCCESS)
goto resend;
else
break;
}
}
// Dump some bytes.
BYTE bBuf[1024];
DWORD cbBuf;
DWORD cbRead;
cbBuf = sizeof(bBuf);
_setmode( _fileno( stdout ), _O_BINARY );
while (InternetReadFile (hRequest, bBuf, cbBuf, &cbRead) && cbRead)
fwrite (bBuf, 1, cbRead, stdout);
done: // Clean up.
if (pszErr)
fprintf (stderr, "Failed on %s, last error %d\n", pszErr, GetLastError());
if (hRequest)
InternetCloseHandle (hRequest);
if (hConnect)
InternetCloseHandle (hConnect);
if (hInternet)
InternetCloseHandle (hInternet);
if (pPostData)
LocalFree (pPostData);
return 0;
}
//==============================================================================
void ParseArguments
(
LPSTR InBuffer,
LPSTR* CArgv,
DWORD* CArgc
)
{
LPSTR CurrentPtr = InBuffer;
DWORD i = 0;
DWORD Cnt = 0;
for ( ;; ) {
//
// skip blanks.
//
while( *CurrentPtr == ' ' ) {
CurrentPtr++;
}
if( *CurrentPtr == '\0' ) {
break;
}
CArgv[i++] = CurrentPtr;
//
// go to next space.
//
while( (*CurrentPtr != '\0') &&
(*CurrentPtr != '\n') ) {
if( *CurrentPtr == '"' ) { // Deal with simple quoted args
if( Cnt == 0 )
CArgv[i-1] = ++CurrentPtr; // Set arg to after quote
else
*CurrentPtr = '\0'; // Remove end quote
Cnt = !Cnt;
}
if( (Cnt == 0) && (*CurrentPtr == ' ') || // If we hit a space and no quotes yet we are done with this arg
(*CurrentPtr == '\0') )
break;
CurrentPtr++;
}
if( *CurrentPtr == '\0' ) {
break;
}
*CurrentPtr++ = '\0';
}
*CArgc = i;
return;
}
//==============================================================================
int __cdecl main (int argc, char **argv)
{
g_fAllowCustomUI = 0; //FALSE;
g_dwConnectFlags = 0;
HMODULE hmodShlwapi = NULL;
char * port ;
// Discard program arg.
argv++;
argc--;
// Parse options.
while (argc && argv[0][0] == '-')
{
switch (tolower(argv[0][1]))
{
case 'c':
g_fAllowCustomUI = TRUE;
break;
case 's':
g_dwConnectFlags = INTERNET_FLAG_SECURE;
break;
case 'p':
g_fPreload = TRUE;
break;
case 'o':
port = *argv;
port +=2;
fprintf(stderr,"Port: %s\n", port);
if(port) {
g_dwPort = atol(port);
}
break;
case 'v':
port = *argv;
port +=2;
fprintf(stderr,"Verb: %s\n", port);
if(port) {
g_szVerb = port;
}
break;
case 'm':
g_fMonolithicUpload = TRUE;
break;
default:
fprintf (stderr, "\nUsage: httpauth [-c] [-s] <server> [<object> [<user> [<pass> [<POST-file>]]]]");
fprintf (stderr, "\n -c: Custom UI to prompt for user/pass");
fprintf (stderr, "\n -s: Secure connection (ssl or pct)");
fprintf (stderr, "\n -m: Monolithic upload");
fprintf (stderr, "\n -o<port#> : Port Number");
exit (1);
}
argv++;
argc--;
}
if (g_fPreload)
{
//Get the current directory in case the user selects -p to preload shlwapi from current dir
char buf[256];
GetCurrentDirectory((DWORD)256, buf);
strcat(buf,"\\shlwapi.dll");
fprintf(stderr, "\nPreloading shlwapi.dll from %s", buf);
if (!(hmodShlwapi=LoadLibrary(buf))) fprintf(stderr, "\nPreload of shlwapi.dll failed");
}
if (argc)
RequestLoop (argc, argv);
else // Enter command prompt loop
{
fprintf (stderr, "\nUsage: <server> [<object> [<user> [<pass> [<POST-file>]]]]");
fprintf (stderr, "\n quit - exit the command loop");
fprintf (stderr, "\n flush - flush pwd cache and authenticated sockets");
while (1)
{
char szIn[1024];
DWORD argcIn;
LPSTR argvIn[10];
fprintf (stderr, "\nhttpauth> ");
gets (szIn);
if (!lstrcmpi (szIn, "quit"))
break;
else if (!lstrcmpi (szIn, "flush"))
{
InternetSetOption
(NULL, INTERNET_OPTION_END_BROWSER_SESSION, NULL, 0);
continue;
}
argcIn = 0;
ParseArguments (szIn, argvIn, &argcIn);
if (!argcIn)
break;
RequestLoop (argcIn, argvIn);
}
}
//unload shlwapi if loaded
if (hmodShlwapi) FreeLibrary(hmodShlwapi);
}
| 29.276718 | 121 | 0.467505 | [
"object"
] |
20fbc960ec69e877a9e2aa268f69bbc75a76fb5b | 927 | cpp | C++ | src/editors/xrWeatherEditor/property_boolean_reference.cpp | clayne/xray-16 | 32ebf81a252c7179e2824b2874f911a91e822ad1 | [
"OML",
"Linux-OpenIB"
] | 2 | 2015-02-23T10:43:02.000Z | 2015-06-11T14:45:08.000Z | src/editors/xrWeatherEditor/property_boolean_reference.cpp | clayne/xray-16 | 32ebf81a252c7179e2824b2874f911a91e822ad1 | [
"OML",
"Linux-OpenIB"
] | 17 | 2022-01-25T08:58:23.000Z | 2022-03-28T17:18:28.000Z | src/editors/xrWeatherEditor/property_boolean_reference.cpp | clayne/xray-16 | 32ebf81a252c7179e2824b2874f911a91e822ad1 | [
"OML",
"Linux-OpenIB"
] | 1 | 2015-06-05T20:04:00.000Z | 2015-06-05T20:04:00.000Z | ////////////////////////////////////////////////////////////////////////////
// Module : property_boolean_reference.cpp
// Created : 13.12.2007
// Modified : 13.12.2007
// Author : Dmitriy Iassenev
// Description : boolean property reference implementation class
////////////////////////////////////////////////////////////////////////////
#include "pch.hpp"
#include "property_boolean_reference.hpp"
property_boolean_reference::property_boolean_reference(bool& value) : m_value(xr_new<value_holder<bool>>(value)) {}
property_boolean_reference::~property_boolean_reference() { this->!property_boolean_reference(); }
property_boolean_reference::!property_boolean_reference() { delete (m_value); }
System::Object ^ property_boolean_reference::GetValue() { return (m_value->get()); }
void property_boolean_reference::SetValue(System::Object ^ object)
{
bool value = safe_cast<bool>(object);
m_value->set(value);
}
| 44.142857 | 115 | 0.639698 | [
"object"
] |
20fc40bf69c3ed0c86561c4e4c8edee6c36ebc8e | 20,757 | cpp | C++ | src/CQChartsCreateAnnotationDlg.cpp | Qt-Widgets/CQCharts | 0ee923c5a2794b9e3845d0d88fa519fcdea7694a | [
"MIT"
] | null | null | null | src/CQChartsCreateAnnotationDlg.cpp | Qt-Widgets/CQCharts | 0ee923c5a2794b9e3845d0d88fa519fcdea7694a | [
"MIT"
] | null | null | null | src/CQChartsCreateAnnotationDlg.cpp | Qt-Widgets/CQCharts | 0ee923c5a2794b9e3845d0d88fa519fcdea7694a | [
"MIT"
] | null | null | null | #include <CQChartsCreateAnnotationDlg.h>
#include <CQChartsAnnotation.h>
#include <CQChartsArrow.h>
#include <CQChartsView.h>
#include <CQChartsPlot.h>
#include <CQChartsPositionEdit.h>
#include <CQChartsRectEdit.h>
#include <CQChartsLengthEdit.h>
#include <CQChartsSymbolDataEdit.h>
#include <CQChartsTextDataEdit.h>
#include <CQChartsSidesEdit.h>
#include <CQChartsPolygonEdit.h>
#include <CQChartsFillDataEdit.h>
#include <CQChartsStrokeDataEdit.h>
#include <CQChartsArrowDataEdit.h>
#include <CQChartsColorEdit.h>
#include <CQChartsWidgetUtil.h>
#include <CQRealSpin.h>
#include <CQCheckBox.h>
#include <CQGroupBox.h>
#include <CQLineEdit.h>
#include <CQUtil.h>
#include <QFrame>
#include <QStackedWidget>
#include <QComboBox>
#include <QRadioButton>
#include <QLabel>
#include <QPushButton>
#include <QVBoxLayout>
CQChartsCreateAnnotationDlg::
CQChartsCreateAnnotationDlg(QWidget *parent, CQChartsView *view) :
QDialog(parent), view_(view)
{
initWidgets();
}
CQChartsCreateAnnotationDlg::
CQChartsCreateAnnotationDlg(QWidget *parent, CQChartsPlot *plot) :
QDialog(parent), plot_(plot)
{
initWidgets();
}
void
CQChartsCreateAnnotationDlg::
initWidgets()
{
setWindowTitle("Create rect Annotation");
//---
QVBoxLayout *layout = CQUtil::makeLayout<QVBoxLayout>(this, 2, 2);
//----
// type combo
typeCombo_ = CQUtil::makeWidget<QComboBox>("type");
typeCombo_->addItems(CQChartsAnnotation::typeNames());
connect(typeCombo_, SIGNAL(currentIndexChanged(int)), this, SLOT(typeSlot(int)));
addLabelWidget(layout, "Type", typeCombo_);
//----
QGridLayout *gridLayout = CQUtil::makeLayout<QGridLayout>(2, 2);
layout->addLayout(gridLayout);
int row = 0;
//--
// id, tip edits
idEdit_ = CQUtil::makeWidget<CQLineEdit>("id");
tipEdit_ = CQUtil::makeWidget<CQLineEdit>("tip");
//--
CQChartsWidgetUtil::addGridLabelWidget(gridLayout, "Id" , idEdit_ , row);
CQChartsWidgetUtil::addGridLabelWidget(gridLayout, "Tip", tipEdit_, row);
//----
// per type widgets stack
typeStack_ = CQUtil::makeWidget<QStackedWidget>("typeStack");
layout->addWidget(typeStack_);
createRectFrame ();
createEllipseFrame ();
createPolygonFrame ();
createPolyLineFrame();
createTextFrame ();
createArrowFrame ();
createPointFrame ();
typeStack_->addWidget(rectWidgets_ .frame);
typeStack_->addWidget(ellipseWidgets_ .frame);
typeStack_->addWidget(polygonWidgets_ .frame);
typeStack_->addWidget(polylineWidgets_.frame);
typeStack_->addWidget(textWidgets_ .frame);
typeStack_->addWidget(arrowWidgets_ .frame);
typeStack_->addWidget(pointWidgets_ .frame);
//---
// OK, Apply, Cancel Buttons
CQChartsDialogButtons *buttons = CQUtil::makeWidget<CQChartsDialogButtons>("buttons");
buttons->connect(this, SLOT(okSlot()), SLOT(applySlot()), SLOT(cancelSlot()));
layout->addWidget(buttons);
}
void
CQChartsCreateAnnotationDlg::
createRectFrame()
{
rectWidgets_.frame = CQUtil::makeWidget<QFrame>("rectFrame");
QVBoxLayout *frameLayout = CQUtil::makeLayout<QVBoxLayout>(rectWidgets_.frame, 2, 2);
//----
QGridLayout *gridLayout = CQUtil::makeLayout<QGridLayout>(2, 2);
frameLayout->addLayout(gridLayout);
int row = 0;
//--
// rect
rectWidgets_.rectEdit = CQUtil::makeWidget<CQChartsRectEdit>("rectEdit");
rectWidgets_.rectEdit->setRect(CQChartsRect());
CQChartsWidgetUtil::addGridLabelWidget(gridLayout, "Rect", rectWidgets_.rectEdit, row);
//--
// margin
rectWidgets_.marginEdit = CQUtil::makeWidget<CQRealSpin>("marginEdit");
CQChartsWidgetUtil::addGridLabelWidget(gridLayout, "Margin", rectWidgets_.marginEdit, row);
//--
// padding
rectWidgets_.paddingEdit = CQUtil::makeWidget<CQRealSpin>("paddingEdit");
CQChartsWidgetUtil::addGridLabelWidget(gridLayout, "Padding", rectWidgets_.paddingEdit, row);
//---
addFillWidgets (rectWidgets_, frameLayout);
addStrokeWidgets(rectWidgets_, frameLayout, /*cornerSize*/true);
addSidesWidget(rectWidgets_, frameLayout);
//---
frameLayout->addStretch(1);
}
void
CQChartsCreateAnnotationDlg::
createEllipseFrame()
{
ellipseWidgets_.frame = CQUtil::makeWidget<QFrame>("ellipseFrame");
QVBoxLayout *frameLayout = CQUtil::makeLayout<QVBoxLayout>(ellipseWidgets_.frame, 2, 2);
//---
ellipseWidgets_.centerEdit = new CQChartsPositionEdit;
ellipseWidgets_.rxEdit = new CQChartsLengthEdit;
ellipseWidgets_.ryEdit = new CQChartsLengthEdit;
//---
QGridLayout *gridLayout = CQUtil::makeLayout<QGridLayout>(2, 2);
frameLayout->addLayout(gridLayout);
int row = 0;
//--
CQChartsWidgetUtil::addGridLabelWidget(gridLayout, "Center" , ellipseWidgets_.centerEdit, row);
CQChartsWidgetUtil::addGridLabelWidget(gridLayout, "Radius X", ellipseWidgets_.rxEdit , row);
CQChartsWidgetUtil::addGridLabelWidget(gridLayout, "Radius Y", ellipseWidgets_.ryEdit , row);
//---
addFillWidgets (ellipseWidgets_, frameLayout);
addStrokeWidgets(ellipseWidgets_, frameLayout, /*cornerSize*/true);
addSidesWidget(ellipseWidgets_, frameLayout);
//---
frameLayout->addStretch(1);
}
void
CQChartsCreateAnnotationDlg::
createPolygonFrame()
{
polygonWidgets_.frame = CQUtil::makeWidget<QFrame>("polygonFrame");
QVBoxLayout *frameLayout = CQUtil::makeLayout<QVBoxLayout>(polygonWidgets_.frame, 2, 2);
//---
polygonWidgets_.pointsEdit = new CQChartsPolygonEdit;
addLabelWidget(frameLayout, "Points", polygonWidgets_.pointsEdit);
//---
addFillWidgets (polygonWidgets_, frameLayout);
addStrokeWidgets(polygonWidgets_, frameLayout, /*cornerSize*/false);
//---
frameLayout->addStretch(1);
}
void
CQChartsCreateAnnotationDlg::
createPolyLineFrame()
{
polylineWidgets_.frame = CQUtil::makeWidget<QFrame>("polylineFrame");
QVBoxLayout *frameLayout = CQUtil::makeLayout<QVBoxLayout>(polylineWidgets_.frame, 2, 2);
//---
polylineWidgets_.pointsEdit = new CQChartsPolygonEdit;
addLabelWidget(frameLayout, "Points", polylineWidgets_.pointsEdit);
//---
addFillWidgets (polylineWidgets_, frameLayout);
addStrokeWidgets(polylineWidgets_, frameLayout, /*cornerSize*/false);
//---
frameLayout->addStretch(1);
}
void
CQChartsCreateAnnotationDlg::
createTextFrame()
{
textWidgets_.frame = CQUtil::makeWidget<QFrame>("textFrame");
QVBoxLayout *frameLayout = CQUtil::makeLayout<QVBoxLayout>(textWidgets_.frame, 2, 2);
//---
QFrame *positionRectFrame = CQUtil::makeWidget<QFrame>("positionRectFrame");
QHBoxLayout *positionRectLayout = CQUtil::makeLayout<QHBoxLayout>(positionRectFrame, 2, 2);
textWidgets_.positionRadio = CQUtil::makeLabelWidget<QRadioButton>("Position", "position");
textWidgets_.rectRadio = CQUtil::makeLabelWidget<QRadioButton>("Rect", "rect");
positionRectLayout->addWidget(textWidgets_.positionRadio);
positionRectLayout->addWidget(textWidgets_.rectRadio);
positionRectLayout->addStretch(1);
connect(textWidgets_.positionRadio, SIGNAL(toggled(bool)), this, SLOT(textPositionSlot(bool)));
textWidgets_.positionEdit = new CQChartsPositionEdit;
textWidgets_.rectEdit = new CQChartsRectEdit;
textWidgets_.positionRadio->setChecked(true);
frameLayout->addWidget(positionRectFrame);
textPositionSlot(true);
//---
QGridLayout *gridLayout1 = CQUtil::makeLayout<QGridLayout>(2, 2);
frameLayout->addLayout(gridLayout1);
int row1 = 0;
//--
CQChartsWidgetUtil::addGridLabelWidget(gridLayout1, "Position", textWidgets_.positionEdit, row1);
CQChartsWidgetUtil::addGridLabelWidget(gridLayout1, "Rect" , textWidgets_.rectEdit , row1);
//---
textWidgets_.textEdit = CQUtil::makeWidget<CQLineEdit>("edit");
//---
QGridLayout *gridLayout = CQUtil::makeLayout<QGridLayout>(2, 2);
frameLayout->addLayout(gridLayout);
int row = 0;
//--
CQChartsWidgetUtil::addGridLabelWidget(gridLayout, "Text", textWidgets_.textEdit, row);
//---
textWidgets_.dataEdit = new CQChartsTextDataEdit(nullptr, /*optional*/false);
textWidgets_.dataEdit->setPlot(plot());
textWidgets_.dataEdit->setView(view());
//--
frameLayout->addWidget(textWidgets_.dataEdit);
//---
addFillWidgets (textWidgets_, frameLayout);
addStrokeWidgets(textWidgets_, frameLayout, /*cornerSize*/true);
addSidesWidget(textWidgets_, frameLayout);
//---
frameLayout->addStretch(1);
}
void
CQChartsCreateAnnotationDlg::
createArrowFrame()
{
arrowWidgets_.frame = CQUtil::makeWidget<QFrame>("arrowFrame");
QVBoxLayout *frameLayout = CQUtil::makeLayout<QVBoxLayout>(arrowWidgets_.frame, 2, 2);
//---
QGridLayout *gridLayout = CQUtil::makeLayout<QGridLayout>(2, 2);
frameLayout->addLayout(gridLayout);
int row = 0;
//--
// start, end point
arrowWidgets_.startEdit = new CQChartsPositionEdit;
arrowWidgets_.endEdit = new CQChartsPositionEdit;
arrowWidgets_.startEdit->setPosition(CQChartsPosition(QPointF(0, 0)));
arrowWidgets_.endEdit ->setPosition(CQChartsPosition(QPointF(1, 1)));
CQChartsWidgetUtil::addGridLabelWidget(gridLayout, "Start", arrowWidgets_.startEdit, row);
CQChartsWidgetUtil::addGridLabelWidget(gridLayout, "End" , arrowWidgets_.endEdit , row);
//---
// arrow data edit
arrowWidgets_.dataEdit = new CQChartsArrowDataEdit;
arrowWidgets_.dataEdit->setPlot(plot());
arrowWidgets_.dataEdit->setView(view());
frameLayout->addWidget(arrowWidgets_.dataEdit);
//---
QGridLayout *gridLayout1 = CQUtil::makeLayout<QGridLayout>(2, 2);
frameLayout->addLayout(gridLayout1);
int row1 = 0;
//--
// stroke width, stroke color, filled and fill color
arrowWidgets_.strokeWidthEdit = new CQChartsLengthEdit;
arrowWidgets_.strokeColorEdit = new CQChartsColorLineEdit;
arrowWidgets_.filledCheck = CQUtil::makeWidget<CQCheckBox>("filledCheck");
arrowWidgets_.fillColorEdit = new CQChartsColorLineEdit;
CQChartsWidgetUtil::addGridLabelWidget(gridLayout1, "Stroke Width",
arrowWidgets_.strokeWidthEdit, row1);
CQChartsWidgetUtil::addGridLabelWidget(gridLayout1, "Stroke Color",
arrowWidgets_.strokeColorEdit, row1);
CQChartsWidgetUtil::addGridLabelWidget(gridLayout1, "Filled" ,
arrowWidgets_.filledCheck , row1);
CQChartsWidgetUtil::addGridLabelWidget(gridLayout1, "Fill Color" ,
arrowWidgets_.fillColorEdit , row1);
//---
frameLayout->addStretch(1);
}
void
CQChartsCreateAnnotationDlg::
createPointFrame()
{
pointWidgets_.frame = CQUtil::makeWidget<QFrame>("pointFrame");
QVBoxLayout *frameLayout = CQUtil::makeLayout<QVBoxLayout>(pointWidgets_.frame, 2, 2);
//---
QGridLayout *gridLayout = CQUtil::makeLayout<QGridLayout>(2, 2);
frameLayout->addLayout(gridLayout);
int row = 0;
//---
pointWidgets_.positionEdit = new CQChartsPositionEdit;
CQChartsWidgetUtil::addGridLabelWidget(gridLayout, "Position", pointWidgets_.positionEdit, row);
//---
pointWidgets_.dataEdit = new CQChartsSymbolDataEdit(nullptr, /*optional*/false);
pointWidgets_.dataEdit->setPlot(plot());
pointWidgets_.dataEdit->setView(view());
frameLayout->addWidget(pointWidgets_.dataEdit);
//---
frameLayout->addStretch(1);
}
void
CQChartsCreateAnnotationDlg::
addFillWidgets(Widgets &widgets, QBoxLayout *playout)
{
widgets.backgroundDataEdit = new CQChartsFillDataEdit;
widgets.backgroundDataEdit->setTitle("Fill");
playout->addWidget(widgets.backgroundDataEdit);
}
void
CQChartsCreateAnnotationDlg::
addStrokeWidgets(Widgets &widgets, QBoxLayout *playout, bool cornerSize)
{
widgets.strokeDataEdit =
new CQChartsStrokeDataEdit(nullptr,
CQChartsStrokeDataEditConfig().setCornerSize(cornerSize));
widgets.strokeDataEdit->setTitle("Stroke");
playout->addWidget(widgets.strokeDataEdit);
}
void
CQChartsCreateAnnotationDlg::
addSidesWidget(Widgets &widgets, QBoxLayout *playout)
{
QGridLayout *gridLayout = CQUtil::makeLayout<QGridLayout>(2, 2);
int row = 0;
//--
widgets.borderSidesEdit = CQUtil::makeWidget<CQChartsSidesEdit>("borderSidesEdit");
CQChartsWidgetUtil::addGridLabelWidget(gridLayout, "Border Sides", widgets.borderSidesEdit, row);
//--
playout->addLayout(gridLayout);
}
QHBoxLayout *
CQChartsCreateAnnotationDlg::
addLabelWidget(QBoxLayout *playout, const QString &label, QWidget *widget)
{
QHBoxLayout *layout = CQUtil::makeLayout<QHBoxLayout>(0, 2);
QLabel *qlabel = CQUtil::makeLabelWidget<QLabel>(label, "label" + label);
layout->addWidget (qlabel);
layout->addWidget (widget);
layout->addStretch(1);
playout->addLayout(layout);
return layout;
}
void
CQChartsCreateAnnotationDlg::
typeSlot(int ind)
{
if (view_)
setWindowTitle(QString("Create View %1 Annotation").
arg(typeCombo_->currentText()));
else if (plot_)
setWindowTitle(QString("Create Plot %1 Annotation (%2)").
arg(typeCombo_->currentText()).arg(plot_->id()));
typeStack_->setCurrentIndex(ind);
}
void
CQChartsCreateAnnotationDlg::
textPositionSlot(bool)
{
if (textWidgets_.positionRadio->isChecked()) {
textWidgets_.positionEdit->setEnabled(true);
textWidgets_.rectEdit ->setEnabled(false);
}
else {
textWidgets_.positionEdit->setEnabled(false);
textWidgets_.rectEdit ->setEnabled(true);
}
}
void
CQChartsCreateAnnotationDlg::
okSlot()
{
if (applySlot())
cancelSlot();
}
bool
CQChartsCreateAnnotationDlg::
applySlot()
{
int ind = typeStack_->currentIndex();
bool rc = false;
if (ind == 0) rc = createRectangleAnnotation();
else if (ind == 1) rc = createEllipseAnnotation();
else if (ind == 2) rc = createPolygonAnnotation();
else if (ind == 3) rc = createPolylineAnnotation();
else if (ind == 4) rc = createTextAnnotation();
else if (ind == 5) rc = createArrowAnnotation();
else if (ind == 6) rc = createPointAnnotation();
return rc;
}
bool
CQChartsCreateAnnotationDlg::
createRectangleAnnotation()
{
CQChartsBoxData boxData;
CQChartsShapeData &shapeData = boxData.shape();
//---
QString id = idEdit_ ->text();
QString tipId = tipEdit_->text();
CQChartsRect rect = rectWidgets_.rectEdit->rect();
boxData.setMargin (rectWidgets_.marginEdit ->value());
boxData.setPadding(rectWidgets_.paddingEdit->value());
CQChartsFillData fill = rectWidgets_.backgroundDataEdit->data();
CQChartsStrokeData stroke = rectWidgets_.strokeDataEdit ->data();
shapeData.setFill (fill);
shapeData.setStroke(stroke);
boxData.setBorderSides(rectWidgets_.borderSidesEdit->sides());
//---
CQChartsRectangleAnnotation *annotation = nullptr;
if (view_)
annotation = view_->addRectangleAnnotation(rect);
else if (plot_)
annotation = plot_->addRectangleAnnotation(rect);
else
return false;
annotation->setId(id);
annotation->setTipId(tipId);
annotation->setBoxData(boxData);
return true;
}
bool
CQChartsCreateAnnotationDlg::
createEllipseAnnotation()
{
CQChartsBoxData boxData;
CQChartsShapeData &shapeData = boxData.shape();
//---
QString id = idEdit_ ->text();
QString tipId = tipEdit_->text();
CQChartsPosition center = ellipseWidgets_.centerEdit->position();
CQChartsLength rx = ellipseWidgets_.rxEdit->length();
CQChartsLength ry = ellipseWidgets_.ryEdit->length();
CQChartsFillData fill = ellipseWidgets_.backgroundDataEdit->data();
CQChartsStrokeData stroke = ellipseWidgets_.strokeDataEdit ->data();
shapeData.setFill (fill);
shapeData.setStroke(stroke);
boxData.setBorderSides(ellipseWidgets_.borderSidesEdit->sides());
//---
CQChartsEllipseAnnotation *annotation = nullptr;
if (view_)
annotation = view_->addEllipseAnnotation(center, rx, ry);
else if (plot_)
annotation = plot_->addEllipseAnnotation(center, rx, ry);
else
return false;
annotation->setId(id);
annotation->setTipId(tipId);
annotation->setBoxData(boxData);
return true;
}
bool
CQChartsCreateAnnotationDlg::
createPolygonAnnotation()
{
CQChartsBoxData boxData;
CQChartsShapeData &shapeData = boxData.shape();
//---
QString id = idEdit_ ->text();
QString tipId = tipEdit_->text();
CQChartsPolygon polygon = polygonWidgets_.pointsEdit->polygon();
CQChartsFillData fill = polygonWidgets_.backgroundDataEdit->data();
CQChartsStrokeData stroke = polygonWidgets_.strokeDataEdit ->data();
shapeData.setFill (fill);
shapeData.setStroke(stroke);
//---
CQChartsPolygonAnnotation *annotation = nullptr;
if (view_)
annotation = view_->addPolygonAnnotation(polygon);
else if (plot_)
annotation = plot_->addPolygonAnnotation(polygon);
else
return false;
annotation->setId(id);
annotation->setTipId(tipId);
annotation->setBoxData(boxData);
return true;
}
bool
CQChartsCreateAnnotationDlg::
createPolylineAnnotation()
{
CQChartsBoxData boxData;
CQChartsShapeData &shapeData = boxData.shape();
//---
QString id = idEdit_ ->text();
QString tipId = tipEdit_->text();
CQChartsPolygon polygon = polylineWidgets_.pointsEdit->polygon();
CQChartsFillData fill = polylineWidgets_.backgroundDataEdit->data();
CQChartsStrokeData stroke = polylineWidgets_.strokeDataEdit ->data();
shapeData.setFill (fill);
shapeData.setStroke(stroke);
//---
CQChartsPolylineAnnotation *annotation = nullptr;
if (view_)
annotation = view_->addPolylineAnnotation(polygon);
else if (plot_)
annotation = plot_->addPolylineAnnotation(polygon);
else
return false;
annotation->setId(id);
annotation->setTipId(tipId);
annotation->setBoxData(boxData);
return true;
}
bool
CQChartsCreateAnnotationDlg::
createTextAnnotation()
{
CQChartsBoxData boxData;
CQChartsShapeData &shapeData = boxData.shape();
//---
QString id = idEdit_ ->text();
QString tipId = tipEdit_->text();
CQChartsPosition pos = textWidgets_.positionEdit->position();
CQChartsRect rect = textWidgets_.rectEdit ->rect();
QString text = textWidgets_.textEdit->text();
const CQChartsTextData &textData = textWidgets_.dataEdit->data();
CQChartsFillData fill = textWidgets_.backgroundDataEdit->data();
CQChartsStrokeData stroke = textWidgets_.strokeDataEdit ->data();
shapeData.setFill (fill);
shapeData.setStroke(stroke);
boxData.setBorderSides(textWidgets_.borderSidesEdit->sides());
//---
CQChartsTextAnnotation *annotation = nullptr;
if (view_) {
if (textWidgets_.positionRadio->isChecked())
annotation = view_->addTextAnnotation(pos, text);
else
annotation = view_->addTextAnnotation(rect, text);
}
else if (plot_) {
if (textWidgets_.positionRadio->isChecked())
annotation = view_->addTextAnnotation(pos, text);
else
annotation = view_->addTextAnnotation(rect, text);
}
if (! annotation)
return false;
annotation->setId(id);
annotation->setTipId(tipId);
annotation->setTextData(textData);
annotation->setBoxData (boxData );
return true;
}
bool
CQChartsCreateAnnotationDlg::
createArrowAnnotation()
{
CQChartsShapeData shapeData;
CQChartsStrokeData &stroke = shapeData.stroke();
CQChartsFillData &fill = shapeData.fill();
//---
QString id = idEdit_ ->text();
QString tipId = tipEdit_->text();
CQChartsPosition start = arrowWidgets_.startEdit->position();
CQChartsPosition end = arrowWidgets_.endEdit ->position();
const CQChartsArrowData &arrowData = arrowWidgets_.dataEdit->data();
stroke.setWidth(arrowWidgets_.strokeWidthEdit->length());
stroke.setColor(arrowWidgets_.strokeColorEdit->color());
fill.setVisible(arrowWidgets_.filledCheck->isChecked());
fill.setColor (arrowWidgets_.fillColorEdit->color());
//---
CQChartsArrowAnnotation *annotation = nullptr;
if (view_)
annotation = view_->addArrowAnnotation(start, end);
else if (plot_)
annotation = plot_->addArrowAnnotation(start, end);
else
return false;
annotation->setId(id);
annotation->setTipId(tipId);
annotation->setArrowData(arrowData);
annotation->arrow()->setShapeData(shapeData);
return true;
}
bool
CQChartsCreateAnnotationDlg::
createPointAnnotation()
{
QString id = idEdit_ ->text();
QString tipId = tipEdit_->text();
CQChartsPosition pos = pointWidgets_.positionEdit->position();
const CQChartsSymbolData &symbolData = pointWidgets_.dataEdit->data();
//---
CQChartsPointAnnotation *annotation = nullptr;
if (view_)
annotation = view_->addPointAnnotation(pos, symbolData.type());
else if (plot_)
annotation = plot_->addPointAnnotation(pos, symbolData.type());
else
return false;
annotation->setId(id);
annotation->setTipId(tipId);
annotation->setSymbolData(symbolData);
return true;
}
void
CQChartsCreateAnnotationDlg::
cancelSlot()
{
close();
}
| 23.886076 | 99 | 0.729296 | [
"shape"
] |
1f04b61d7bc92c3071084aeee821c509278c4b6a | 1,634 | hpp | C++ | application.hpp | lyrahgames/fractal-render | 4e64270462a58b8701a12a317ca40c5946cfcdfd | [
"MIT"
] | null | null | null | application.hpp | lyrahgames/fractal-render | 4e64270462a58b8701a12a317ca40c5946cfcdfd | [
"MIT"
] | null | null | null | application.hpp | lyrahgames/fractal-render | 4e64270462a58b8701a12a317ca40c5946cfcdfd | [
"MIT"
] | null | null | null | #pragma once
#include <SFML/Graphics.hpp>
#include <array>
#include <chrono>
#include <cmath>
#include <complex>
#include <iostream>
#include <vector>
#include <julia_set.hpp>
class application {
using color = std::array<float, 4>;
public:
// Default constructor and destructor explicitly generated by the compiler.
// Otherwise, it would be implicitly generated.
// application() = default;
~application() = default;
// Default constructor written by the programmer.
application();
void execute();
private:
void draw_gradient();
void draw_mandelbrot();
void draw_julia();
void animate_julia(float dt);
void compute_viewport();
private:
int screen_width = 600;
int screen_height = 400;
float origin_x = -0.5;
float origin_y = 0;
float height = 2;
float width = static_cast<float>(screen_width) / screen_height * height;
float x_min = origin_x - 0.5 * width;
float y_min = origin_y - 0.5 * height;
float x_max = origin_x + 0.5 * width;
float y_max = origin_y + 0.5 * height;
std::vector<color> pixel_buffer;
std::chrono::time_point<std::chrono::high_resolution_clock> start_time =
std::chrono::high_resolution_clock::now();
// decltype returns the type of given expression.
decltype(start_time) old_time = start_time;
// std::complex<float> julia_coeff{};
julia_set js{};
sf::RenderWindow window{{screen_width, screen_height},
"OpenGL",
sf::Style::Default,
sf::ContextSettings{32}};
sf::Texture texture;
sf::Sprite sprite;
int old_mouse_x = 0;
int old_mouse_y = 0;
}; | 25.138462 | 77 | 0.668911 | [
"vector"
] |
1f058d4ad8227282653a65312285f0b0e9c934c5 | 3,879 | cpp | C++ | C++Server/Tools/src/messages/GetSatelliteMessage.cpp | IncompleteWorlds/01_gs4cubesat | 4386a3a8b984e96cab364bab83fc2fb49aa5cc3d | [
"RSA-MD"
] | null | null | null | C++Server/Tools/src/messages/GetSatelliteMessage.cpp | IncompleteWorlds/01_gs4cubesat | 4386a3a8b984e96cab364bab83fc2fb49aa5cc3d | [
"RSA-MD"
] | null | null | null | C++Server/Tools/src/messages/GetSatelliteMessage.cpp | IncompleteWorlds/01_gs4cubesat | 4386a3a8b984e96cab364bab83fc2fb49aa5cc3d | [
"RSA-MD"
] | null | null | null | /**
* CubeGS
* An online Ground Segment for Cubesats and Small Sats
* (c) 2017 Incomplete Worlds
*
*/
#include "ToolsDatabase.h"
#include "LogManager.h"
#include "GSException.h"
#include "MessageUtils.h"
#include "messages/GetSatelliteMessage.h"
GetSatelliteMessage::GetSatelliteMessage()
{
}
GetSatelliteMessage::~GetSatelliteMessage()
{
}
ServerMessage GetSatelliteMessage::processMessage(const ServerMessage &inMessage, ServerWorker& inParent)
{
// Create reply message
ServerMessage outputMessage;
// Check message code
if (inMessage.getOperationCode() == OperationCodeEnum::CODE_GET_SATELLITE)
{
// Extract the AVRO message from body
IW::MsgGetSatellite avroInputMessage;
try
{
// ----------------------------------------------------------------------
extractMessageVector<IW::MsgGetSatellite>(static_cast<ServerMessage>(inMessage).getData(), avroInputMessage);
LogManager::getInstance().debug("Reading satellites for mission: " + avroInputMessage.missionName);
// Get Mission
if (avroInputMessage.missionName.empty() == false)
{
IW::ListSatellites listSatellite;
bool errorFlag = false;
if (avroInputMessage.satelliteName.empty() == false)
{
IW::Satellite aSatellite = ToolsDatabase::getInstance().getSatelliteByName(avroInputMessage.missionName,
avroInputMessage.satelliteName);
listSatellite.listSatellites.push_back(aSatellite);
}
else
{
if (avroInputMessage.satelliteCode.empty() == false)
{
IW::Satellite aSatellite = ToolsDatabase::getInstance().getSatelliteByCode(avroInputMessage.missionName,
avroInputMessage.satelliteCode);
listSatellite.listSatellites.push_back(aSatellite);
}
else
{
// If no code or name is used, it will return all satellites of the mission
listSatellite.listSatellites = ToolsDatabase::getInstance().getSatellites(avroInputMessage.missionName);
}
}
if (errorFlag == false)
{
// Generate response
std::vector<uint8_t> avroOutputMessage;
avroOutputMessage = buildMessageVector<IW::ListSatellites>(listSatellite);
outputMessage.setOperationCode(OperationCodeEnum::CODE_GET_SATELLITE_RESPONSE);
outputMessage.setData(avroOutputMessage);
}
}
else
{
createReply(outputMessage, -1, "Mission name is null or empty");
}
// ----------------------------------------------------------------------
} catch(GSException& gsExc)
{
LogManager::getInstance().error("Exception: " + gsExc.getErrorMessage());
createReply(outputMessage, gsExc.getErrorCode(), gsExc.getErrorMessage());
}
}
else
{
string errorMessage = "Invalid received message: " + static_cast<ServerMessage>(inMessage).toString();
LogManager::getInstance().error(errorMessage);
createReply(outputMessage, -1, errorMessage);
}
outputMessage.setCorrelationId(inMessage.getCorrelationId());
LogManager::getInstance().debug("Get Satellite response: " + outputMessage.toString());
return outputMessage;
}
| 36.59434 | 131 | 0.542923 | [
"vector"
] |
1f108417f6b7a382ebcced5abc8f2ffbf2baa775 | 5,488 | cc | C++ | cpp/secretcode/VolatilityTracker.cc | CodeApprenticeRai/newt | 0e07a87aa6b8d4b238c1a9fd3fef363133866c57 | [
"Apache-2.0"
] | 1 | 2021-06-21T12:23:55.000Z | 2021-06-21T12:23:55.000Z | cpp/secretcode/VolatilityTracker.cc | CodeApprenticeRai/newt | 0e07a87aa6b8d4b238c1a9fd3fef363133866c57 | [
"Apache-2.0"
] | null | null | null | cpp/secretcode/VolatilityTracker.cc | CodeApprenticeRai/newt | 0e07a87aa6b8d4b238c1a9fd3fef363133866c57 | [
"Apache-2.0"
] | 6 | 2019-10-17T21:16:21.000Z | 2020-10-19T08:27:01.000Z | #include "VolatilityTracker.h"
#include "OpenTracker.h"
#include "DataManager.h"
#include "HFUtils.h"
#include "AlphaSignal.h"
const string RELEVANT_LOG_FILE = "misc";
VolatilityTracker::VolatilityTracker(int sampleMilliSeconds, int numSamplePoints,
int minSamplePoints, AlphaSignal *fvSignal)
:
_sampleMilliSeconds(sampleMilliSeconds),
_numSamplePoints(numSamplePoints),
_minSamplePoints(minSamplePoints),
_sampleNumber(0),
_retBufV(0),
_lastPriceV(0),
_sampleStartTime(),
_marketOpen(false),
_fvSignal(fvSignal)
{
_dm = factory<DataManager>::find(only::one);
if( !_dm )
throw std::runtime_error( "Failed to get DataManager from factory (in VolatilityTracker::VolatilityTracker)" );
_openT = factory<OpenTracker>::get(only::one);
if( !_openT )
throw std::runtime_error( "Failed to get OpenTracker from factory (in VolatilityTracker::VolatilityTracker)" );
_exchangeT = factory<ExchangeTracker>::get(only::one) ;
if( !_exchangeT )
throw std::runtime_error( "Failed to get ExchangeTracker from factory (in VolatilityTracker::VolatilityTracker)" );
_ddebug = factory<debug_stream>::get( RELEVANT_LOG_FILE );
if( !_ddebug )
throw std::runtime_error( "Failed to get DebugStream from factory (in VolatilityTracker::VolatilityTracker)" );
_retBufV.resize(_dm->cidsize());
_lastPriceV.assign(_dm->cidsize(), 0.0);
//_sampleStartTime = _dm->curtv(); Unclear what happens when _dm->curtv() is called before event loop starts.
// with this commented out, need to ensure that addSample() sets _sampleStartTime on the 1st received sample.
for (int i=0;i<_dm->cidsize();i++) {
_retBufV[i] = new CircBuffer<double>(numSamplePoints);
}
_dm->add_listener(this);
}
VolatilityTracker::~VolatilityTracker() {
for (int i=0;i<_dm->cidsize();i++) {
delete _retBufV[i];
}
}
void VolatilityTracker::addSample() {
// 1st sample:
// Just get mid-prices.
if (_sampleNumber++ == 0) {
populateCurrentPrices();
//_sampleStartTime = _dm->curtv(); Should be set from market open TimerUpdate.tv(),
// not _dm_>curtv(), as these two timers can sometimes have different usec resolution,
// and as other timer-based widgets generally use market open TimerUpdate.tv() for
// sample start TV.
} else {
// Subsequent sample:
// Copy last sample point mid prices, so that they can be used
// to compute returns.
vector<double> lastMidPriceV = _lastPriceV;
// Compute current sample point mid prices.
populateCurrentPrices();
// Use last sample point mid prices + current mid prices to compute
// per period returns.
vector<double> returnV;
populateReturns(lastMidPriceV, _lastPriceV, returnV);
// Append computed returns to each ret buf.
addReturnSamples(returnV);
}
}
void VolatilityTracker::populateCurrentPrices() {
vector<double> cpy = _lastPriceV;
HFUtils::bestMids(_dm.get(), cpy, _lastPriceV, _fvSignal);
}
void VolatilityTracker::addReturnSamples(vector<double> &retV) {
unsigned int rvs = retV.size();
assert(rvs == (unsigned int)_dm->cidsize());
for (unsigned int i=0;i<rvs;i++) {
// Check whether stock has opened for trading.
ECN::ECN e = _exchangeT -> getExchange( i );
if (!_openT->hasOpened(i, e)) {
continue;
}
double tsample = retV[i];
CBD *tbuf = _retBufV[i];
tbuf->add(tsample);
// Temporary - For Debugging.
//std::cout << "VolatilityTracker::addReturnSamples - adding sample: stock " << i
// << " sample " << tsample << std::endl;
}
}
void VolatilityTracker::flushReturnSamples() {
unsigned int sz = _retBufV.size();
for (unsigned int i=0;i<sz;i++) {
CBD *tbuf = _retBufV[i];
tbuf ->clear();
}
}
void VolatilityTracker::populateReturns(vector<double> &lastMidV,
vector<double> &curMidV,
vector<double> &retV) {
double tret;
unsigned int sz = lastMidV.size();
assert(curMidV.size() == sz);
retV.resize(sz);
for (unsigned int i = 0;i < sz; i++) {
if (lastMidV[i] > 0) {
tret = ((curMidV[i] - lastMidV[i])/lastMidV[i]);
} else {
tret = 0.0;
}
retV[i] = tret;
}
}
bool VolatilityTracker::getVolatility(int cid, double &fv) {
assert((cid >= 0) && (((unsigned int)cid) < _retBufV.size()));
CBD *tbuf = _retBufV[cid];
int nsp = tbuf->size();
if (nsp < _minSamplePoints) {
return false;
}
double fvt;
if (!tbuf->getStdev(&fvt)) {
return false;
}
// Convert unscaled volatility to per minute volatility.
double speriod = ((double)60000.0)/((double)_sampleMilliSeconds);
double scale = sqrt(speriod);
fv = fvt * scale;
if (isnan(fv) || isinf(fv)) {
return false;
}
return true;
}
/*
UpdateListener functions
*/
void VolatilityTracker::update(const TimeUpdate &au) {
if (au.timer() == _dm->marketOpen()) {
onMarketOpen(au);
} else if (au.timer() == _dm->marketClose()) {
onMarketClose(au);
}
onTimerUpdate(au);
}
void VolatilityTracker::onMarketOpen(const TimeUpdate &au) {
_marketOpen = true;
_sampleStartTime = au.tv();
_sampleNumber = 0;
flushReturnSamples();
}
void VolatilityTracker::onMarketClose(const TimeUpdate &au) {
_marketOpen = false;
}
void VolatilityTracker::onTimerUpdate(const TimeUpdate &au) {
if (!_marketOpen) {
return;
}
double msdiff = HFUtils::milliSecondsBetween(_sampleStartTime, au.tv());
if (msdiff >= (_sampleNumber * _sampleMilliSeconds)) {
addSample();
}
}
| 30.488889 | 120 | 0.675109 | [
"vector"
] |
1f1be706b10e6ee25cdf03aa4e3b25f586bae213 | 3,923 | hpp | C++ | src/core/runtime/src/level_zero_runtime.hpp | intel/cassian | 8e9594f053f9b9464066c8002297346580e4aa2a | [
"MIT"
] | 1 | 2021-10-05T14:15:34.000Z | 2021-10-05T14:15:34.000Z | src/core/runtime/src/level_zero_runtime.hpp | intel/cassian | 8e9594f053f9b9464066c8002297346580e4aa2a | [
"MIT"
] | null | null | null | src/core/runtime/src/level_zero_runtime.hpp | intel/cassian | 8e9594f053f9b9464066c8002297346580e4aa2a | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#ifndef CASSIAN_RUNTIME_LEVEL_ZERO_RUNTIME_HPP
#define CASSIAN_RUNTIME_LEVEL_ZERO_RUNTIME_HPP
#include <array>
#include <cassian/runtime/access_qualifier.hpp>
#include <cassian/runtime/device_properties.hpp>
#include <cassian/runtime/feature.hpp>
#include <cassian/runtime/program_descriptor.hpp>
#include <cassian/runtime/runtime.hpp>
#include <cstddef>
#include <cstdint>
#include <level_zero_wrapper.hpp>
#include <string>
#include <unordered_map>
#include <ze_api.h>
namespace cassian {
class LevelZeroRuntime : public Runtime {
public:
~LevelZeroRuntime();
void initialize() override;
Buffer create_buffer(size_t size, AccessQualifier access) override;
Image create_image(const ImageDimensions dim, const ImageType type,
const ImageFormat format, const ImageChannelOrder order,
AccessQualifier access) override;
Sampler create_sampler(SamplerCoordinates coordinates,
SamplerAddressingMode address_mode,
SamplerFilterMode filter_mode) override;
void read_buffer(const Buffer &buffer, void *data) override;
void read_image(const Image &image, void *data) override;
void write_buffer(const Buffer &buffer, const void *data) override;
void write_image(const Image &image, const void *data) override;
void release_buffer(const Buffer &buffer) override;
void release_image(const Image &image) override;
void release_sampler(const Sampler &sampler) override;
Kernel
create_kernel(const std::string &kernel_name, const std::string &source,
const std::string &build_options,
const std::string &program_type,
const std::optional<std::string> &spirv_options) override;
Kernel create_kernel_from_multiple_programs(
const std::string &kernel_name,
const std::vector<ProgramDescriptor> &program_descriptors,
const std::string &linker_options) override;
void set_kernel_argument(const Kernel &kernel, int argument_index,
const Buffer &buffer) override;
void set_kernel_argument(const Kernel &kernel, int argument_index,
const Image &image) override;
void set_kernel_argument(const Kernel &kernel, int argument_index,
const Sampler &sampler) override;
void release_kernel(const Kernel &kernel) override;
bool is_feature_supported(Feature feature) const override;
int get_device_property(DeviceProperty property) const override;
std::string name() const override;
protected:
void set_kernel_argument(const Kernel &kernel, int argument_index,
size_t argument_size, const void *argument) override;
void run_kernel_common(const Kernel &kernel,
std::array<size_t, 3> global_work_size,
const std::array<size_t, 3> *local_work_size) override;
private:
LevelZeroWrapper wrapper_;
ze_driver_handle_t driver_ = nullptr;
ze_device_handle_t device_ = nullptr;
ze_context_handle_t context_ = nullptr;
ze_command_queue_handle_t queue_ = nullptr;
std::unordered_map<std::uintptr_t, void *> buffers_;
std::unordered_map<std::uintptr_t, ze_image_handle_t> images_;
std::unordered_multimap<std::uintptr_t, ze_module_handle_t> modules_;
std::unordered_map<std::uintptr_t, ze_kernel_handle_t> kernels_;
std::unordered_map<std::uintptr_t, ze_sampler_handle_t> samplers_;
uint32_t ze_get_device_id() const;
std::string ze_get_module_build_log(
const ze_module_build_log_handle_t &build_log_handle) const;
ze_module_handle_t
ze_create_module(const std::string &source, const std::string &build_options,
const std::string &program_type,
const std::optional<std::string> &spirv_options);
};
} // namespace cassian
#endif
| 38.087379 | 80 | 0.725465 | [
"vector"
] |
1f1cf31877c6c411b5b26facc348588a7294a4d3 | 3,235 | cc | C++ | test/test_argument_parser.cc | abhishekpratapa/Compiler | 487176c61fa2efe6694d8f9257747e0f68023016 | [
"MIT"
] | null | null | null | test/test_argument_parser.cc | abhishekpratapa/Compiler | 487176c61fa2efe6694d8f9257747e0f68023016 | [
"MIT"
] | 2 | 2019-07-23T08:02:01.000Z | 2019-07-23T08:35:15.000Z | test/test_argument_parser.cc | abhishekpratapa/Compiler | 487176c61fa2efe6694d8f9257747e0f68023016 | [
"MIT"
] | null | null | null | #ifdef INDEPENDENT_TESTS
#include "test_main.h"
#define BOOST_TEST_MODULE main
#endif
#include <boost/test/unit_test.hpp>
#include <utils/argument_parser.h>
using namespace acc::utils;
BOOST_AUTO_TEST_SUITE(argument_parser)
BOOST_AUTO_TEST_CASE(default_output_file) {
// MOCK `argc` and `argv`
int argc = 2;
char **argv;
argv = (char **)malloc(argc * sizeof(char *));
argv[0] = (char *)malloc(100 * sizeof(char));
argv[1] = (char *)malloc(100 * sizeof(char));
std::string FILE_NAME = "main.cc";
strcpy(argv[0], "./acc");
strcpy(argv[1], FILE_NAME.c_str());
// Run tests on expected output
std::string output_program_name;
std::vector<std::string> file_list;
ERROR_CODE code = argument_parse(output_program_name, file_list, argc, argv);
BOOST_CHECK_EQUAL(code, NO_ERROR);
BOOST_CHECK_EQUAL(DEFAULT_PROGRAM_NAME, output_program_name);
BOOST_CHECK_EQUAL(file_list.size(), 1);
BOOST_CHECK_EQUAL(file_list.at(0), FILE_NAME);
// Free allocated memory
free(argv[0]);
free(argv[1]);
free(argv);
}
BOOST_AUTO_TEST_CASE(no_output_file) {
// MOCK `argc` and `argv`
int argc = 2;
char **argv;
argv = (char **)malloc(argc * sizeof(char *));
argv[0] = (char *)malloc(100 * sizeof(char));
argv[1] = (char *)malloc(100 * sizeof(char));
strcpy(argv[0], "./acc");
strcpy(argv[1], "-o");
// Run tests on expected output
std::string output_program_name;
std::vector<std::string> file_list;
ERROR_CODE code = argument_parse(output_program_name, file_list, argc, argv);
BOOST_CHECK_EQUAL(code, OUTPUT_FILE_ERROR);
// Free allocated memory
free(argv[0]);
free(argv[1]);
free(argv);
}
BOOST_AUTO_TEST_CASE(no_source_files) {
// MOCK `argc` and `argv`
int argc = 1;
char **argv;
argv = (char **)malloc(argc * sizeof(char *));
argv[0] = (char *)malloc(100 * sizeof(char));
strcpy(argv[0], "./acc");
// Run tests on expected output
std::string output_program_name;
std::vector<std::string> file_list;
ERROR_CODE code = argument_parse(output_program_name, file_list, argc, argv);
BOOST_CHECK_EQUAL(code, SOURCE_FILES_ERROR);
// Free allocated memory
free(argv[0]);
free(argv);
}
BOOST_AUTO_TEST_CASE(correct_input) {
// MOCK `argc` and `argv`
int argc = 4;
char **argv;
argv = (char **)malloc(argc * sizeof(char *));
argv[0] = (char *)malloc(100 * sizeof(char));
argv[1] = (char *)malloc(100 * sizeof(char));
argv[2] = (char *)malloc(100 * sizeof(char));
argv[3] = (char *)malloc(100 * sizeof(char));
std::string FILE_NAME = "main.cc";
std::string OUTPUT_NAME = "main";
strcpy(argv[0], "./acc");
strcpy(argv[1], "-o");
strcpy(argv[2], OUTPUT_NAME.c_str());
strcpy(argv[3], FILE_NAME.c_str());
// Run tests on expected output
std::string output_program_name;
std::vector<std::string> file_list;
ERROR_CODE code = argument_parse(output_program_name, file_list, argc, argv);
BOOST_CHECK_EQUAL(code, NO_ERROR);
BOOST_CHECK_EQUAL(OUTPUT_NAME, output_program_name);
BOOST_CHECK_EQUAL(file_list.size(), 1);
BOOST_CHECK_EQUAL(file_list.at(0), FILE_NAME);
// Free allocated memory
free(argv[0]);
free(argv[1]);
free(argv[2]);
free(argv[3]);
free(argv);
}
BOOST_AUTO_TEST_SUITE_END() | 25.472441 | 79 | 0.681607 | [
"vector"
] |
1f2364b97f30efd3c178a1508b2fd5e0ca208e48 | 898 | cpp | C++ | Demo/CommandDemo.cpp | Photorithm/Events | 3d57db33905555003643b9b4dd6b22e8e6342ebe | [
"MIT"
] | null | null | null | Demo/CommandDemo.cpp | Photorithm/Events | 3d57db33905555003643b9b4dd6b22e8e6342ebe | [
"MIT"
] | null | null | null | Demo/CommandDemo.cpp | Photorithm/Events | 3d57db33905555003643b9b4dd6b22e8e6342ebe | [
"MIT"
] | 1 | 2022-01-14T20:25:36.000Z | 2022-01-14T20:25:36.000Z | /**
* Created by TekuConcept on June 12, 2017
*/
#include <iostream>
#include <EventCommand.h>
#define DMSG(x) std::cout << x << std::endl
class CustomArgs : public EventArgs {
public:
CustomArgs() : X(0) {}
CustomArgs(int val) : X(val) {}
int X;
};
template <class Args>
class DummyEventCommand : public EventCommand<Args> {
public:
void invoke(object& sender, Args e) {
DMSG("Event executed!");
if(typeid(Args) == typeid(CustomArgs)) {
DMSG("Event arguments are { x: " << e.X << " }");
}
}
};
void testEvent(EventCommand<CustomArgs> &event) {
Object obj(typeid(int), NULL);
CustomArgs e(2);
event.invoke(obj, e);
}
int main() {
DMSG("- COMMAND DEMO -");
DummyEventCommand<CustomArgs> dummy;
testEvent(dummy);
DMSG("- DEMO FINISHED -");
return 0;
} | 20.883721 | 62 | 0.565702 | [
"object"
] |
1f255e77d432edb21f3ef19a0d1336ba0517c007 | 6,582 | cpp | C++ | src/errors.cpp | dmlys/extlib | faf725464164d30aa197d53eba8d2c870faf2767 | [
"BSL-1.0"
] | 1 | 2018-05-14T13:36:09.000Z | 2018-05-14T13:36:09.000Z | src/errors.cpp | dmlys/extlib | faf725464164d30aa197d53eba8d2c870faf2767 | [
"BSL-1.0"
] | null | null | null | src/errors.cpp | dmlys/extlib | faf725464164d30aa197d53eba8d2c870faf2767 | [
"BSL-1.0"
] | null | null | null | #include <ext/errors.hpp>
#include <ext/itoa.hpp>
namespace ext
{
namespace
{
template <class ErrCode>
static std::string format_error_impl(const ErrCode & err)
{
static_assert(std::is_same<decltype(err.value()), int>::value, "error code should be int");
std::string msg;
int errc = err.value();
auto & cat = err.category();
int radix = BOOST_OS_WINDOWS && errc & 0x80000000 ? 16 : 10;
// +2 for sign and null terminator
const std::size_t bufsize = std::numeric_limits<int>::digits10 + 3;
char buffer[bufsize];
const char * start = ext::unsafe_itoa(errc, buffer, bufsize, radix);
const char * end = buffer + bufsize - 1; // -1 to exclude null terminator
msg += cat.name();
msg += ':';
msg.append(start, end);
msg += ", ";
msg += cat.message(errc);
return msg;
}
template <class SystemError, class ErrorCode>
static std::string format_system_error(SystemError & ex, ErrorCode code)
{
std::string result;
std::string_view msg = ex.what();
int errc = code.value();
auto code_msg = code.message();
int radix = BOOST_OS_WINDOWS && errc & 0x80000000 ? 16 : 10;
constexpr auto buffer_size = ext::itoa_required<int>();
char buffer[buffer_size];
auto * number_str = ext::unsafe_itoa(errc, buffer, buffer_size, radix);
#if BOOST_OS_WINDOWS
// on windows what message will be localized, so we must search localized version of it
// and replace with utf-8 version
auto loc_msg = ex.code().message();
auto replace_size = loc_msg.size();
auto pos = msg.find(loc_msg);
if (pos == msg.npos) pos = msg.find(code_msg), replace_size = code_msg.size();
if (pos == msg.npos) return std::string(msg);
result.append(msg, 0, pos);
result.append(code.category().name());
result.push_back(':');
result.append(number_str);
result.append(", ");
result.append(code_msg);
result.append(msg, pos + replace_size);
#else
// find message substring
auto pos = msg.find(code_msg);
assert(pos != msg.npos);
// replace it with <category>:<code>, <message>
result.append(msg, 0, pos);
result.append(code.category().name());
result.push_back(':');
result.append(number_str);
result.append(", ");
result.append(msg, pos);
#endif
return result;
}
} // 'anonymous' namespace
std::string format_error(std::error_code err)
{
#if BOOST_OS_WINDOWS
if (err.category() == std::system_category())
err.assign(err.value(), ext::system_utf8_category());
#endif
return format_error_impl(err);
}
std::string format_error(boost::system::error_code err)
{
#if BOOST_OS_WINDOWS
if (err.category() == boost::system::system_category())
err.assign(err.value(), ext::boost_system_utf8_category());
#endif
return format_error_impl(err);
}
std::string format_error(std::system_error & err)
{
auto code = err.code();
#if BOOST_OS_WINDOWS
if (code.category() == std::system_category())
code.assign(code.value(), ext::system_utf8_category());
#endif
return format_system_error(err, code);
}
std::string format_error(boost::system::system_error err)
{
auto code = err.code();
#if BOOST_OS_WINDOWS
if (code.category() == boost::system::system_category())
code.assign(code.value(), ext::boost_system_utf8_category());
#endif
return format_system_error(err, code);
}
}
/************************************************************************/
/* Windows specific part */
/************************************************************************/
#if BOOST_OS_WINDOWS
#include <windows.h>
#include <vector>
#include <boost/locale.hpp>
#include <boost/algorithm/string.hpp>
namespace ext
{
namespace
{
std::string GetMessage(int ev)
{
//http://msdn.microsoft.com/en-us/library/windows/desktop/ms679351%28v=vs.85%29.aspx
//64k from MSDN: "The output buffer cannot be larger than 64K bytes."
const size_t bufSz = 64 * 1024;
wchar_t errBuf[bufSz];
//std::unique_ptr<wchar_t[]> errBufPtr(new wchar_t[bufSz]);
//auto errBuf = errBufPtr.get();
DWORD res = ::FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, ev,
MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US),
errBuf, bufSz,
nullptr);
if (!res)
return "FormatMessageW failed with " + std::to_string(GetLastError());
else
{
std::string err = boost::locale::conv::utf_to_utf<char>(errBuf, errBuf + res);
/// message often contain "\r\n." at the end, delete them
boost::trim_right_if(err, boost::is_any_of("\r\n."));
return err;
}
}
struct system_utf8_category : std::error_category
{
std::string message(int err) const override;
const char * name() const noexcept override {return "system";}
std::error_condition default_error_condition(int code) const noexcept override;
};
struct boost_system_utf8_category : boost::system::error_category
{
std::string message(int err) const override;
const char * name() const noexcept override {return "system";}
boost::system::error_condition default_error_condition(int code) const noexcept override;
};
std::string system_utf8_category::message(int err) const
{
return GetMessage(err);
}
std::error_condition system_utf8_category::default_error_condition(int code) const noexcept
{
// forward to standard implementation
return std::system_category().default_error_condition(code);
}
std::string boost_system_utf8_category::message(int err) const
{
return GetMessage(err);
}
boost::system::error_condition boost_system_utf8_category::default_error_condition(int code) const noexcept
{
// forward to standard implementation
return boost::system::system_category().default_error_condition(code);
}
const system_utf8_category system_utf8_category_instance {};
const boost_system_utf8_category boost_system_utf8_category_instance {};
} //anonymous namespace
std::error_category const & system_utf8_category() noexcept
{
return system_utf8_category_instance;
}
boost::system::error_category const & boost_system_utf8_category() noexcept
{
return boost_system_utf8_category_instance;
}
void throw_last_system_error(const std::string & errMsg)
{
throw std::system_error(GetLastError(), std::system_category(), errMsg);
}
void throw_last_system_error(const char * errMsg)
{
throw std::system_error(GetLastError(), std::system_category(), errMsg);
}
}
#endif
| 28.248927 | 109 | 0.669401 | [
"vector"
] |
1f258f06fe450fc4416db95b8f28e033b2dbf2dd | 5,951 | cpp | C++ | tcss/src/v20201101/model/RiskSyscallWhiteListInfo.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | tcss/src/v20201101/model/RiskSyscallWhiteListInfo.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | tcss/src/v20201101/model/RiskSyscallWhiteListInfo.cpp | suluner/tencentcloud-sdk-cpp | a56c73cc3f488c4d1e10755704107bb15c5e000d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/tcss/v20201101/model/RiskSyscallWhiteListInfo.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Tcss::V20201101::Model;
using namespace std;
RiskSyscallWhiteListInfo::RiskSyscallWhiteListInfo() :
m_imageIdsHasBeenSet(false),
m_syscallNamesHasBeenSet(false),
m_processPathHasBeenSet(false),
m_idHasBeenSet(false)
{
}
CoreInternalOutcome RiskSyscallWhiteListInfo::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("ImageIds") && !value["ImageIds"].IsNull())
{
if (!value["ImageIds"].IsArray())
return CoreInternalOutcome(Core::Error("response `RiskSyscallWhiteListInfo.ImageIds` is not array type"));
const rapidjson::Value &tmpValue = value["ImageIds"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
m_imageIds.push_back((*itr).GetString());
}
m_imageIdsHasBeenSet = true;
}
if (value.HasMember("SyscallNames") && !value["SyscallNames"].IsNull())
{
if (!value["SyscallNames"].IsArray())
return CoreInternalOutcome(Core::Error("response `RiskSyscallWhiteListInfo.SyscallNames` is not array type"));
const rapidjson::Value &tmpValue = value["SyscallNames"];
for (rapidjson::Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr)
{
m_syscallNames.push_back((*itr).GetString());
}
m_syscallNamesHasBeenSet = true;
}
if (value.HasMember("ProcessPath") && !value["ProcessPath"].IsNull())
{
if (!value["ProcessPath"].IsString())
{
return CoreInternalOutcome(Core::Error("response `RiskSyscallWhiteListInfo.ProcessPath` IsString=false incorrectly").SetRequestId(requestId));
}
m_processPath = string(value["ProcessPath"].GetString());
m_processPathHasBeenSet = true;
}
if (value.HasMember("Id") && !value["Id"].IsNull())
{
if (!value["Id"].IsString())
{
return CoreInternalOutcome(Core::Error("response `RiskSyscallWhiteListInfo.Id` IsString=false incorrectly").SetRequestId(requestId));
}
m_id = string(value["Id"].GetString());
m_idHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void RiskSyscallWhiteListInfo::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_imageIdsHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ImageIds";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_imageIds.begin(); itr != m_imageIds.end(); ++itr)
{
value[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);
}
}
if (m_syscallNamesHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "SyscallNames";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(rapidjson::kArrayType).Move(), allocator);
for (auto itr = m_syscallNames.begin(); itr != m_syscallNames.end(); ++itr)
{
value[key.c_str()].PushBack(rapidjson::Value().SetString((*itr).c_str(), allocator), allocator);
}
}
if (m_processPathHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ProcessPath";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_processPath.c_str(), allocator).Move(), allocator);
}
if (m_idHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Id";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_id.c_str(), allocator).Move(), allocator);
}
}
vector<string> RiskSyscallWhiteListInfo::GetImageIds() const
{
return m_imageIds;
}
void RiskSyscallWhiteListInfo::SetImageIds(const vector<string>& _imageIds)
{
m_imageIds = _imageIds;
m_imageIdsHasBeenSet = true;
}
bool RiskSyscallWhiteListInfo::ImageIdsHasBeenSet() const
{
return m_imageIdsHasBeenSet;
}
vector<string> RiskSyscallWhiteListInfo::GetSyscallNames() const
{
return m_syscallNames;
}
void RiskSyscallWhiteListInfo::SetSyscallNames(const vector<string>& _syscallNames)
{
m_syscallNames = _syscallNames;
m_syscallNamesHasBeenSet = true;
}
bool RiskSyscallWhiteListInfo::SyscallNamesHasBeenSet() const
{
return m_syscallNamesHasBeenSet;
}
string RiskSyscallWhiteListInfo::GetProcessPath() const
{
return m_processPath;
}
void RiskSyscallWhiteListInfo::SetProcessPath(const string& _processPath)
{
m_processPath = _processPath;
m_processPathHasBeenSet = true;
}
bool RiskSyscallWhiteListInfo::ProcessPathHasBeenSet() const
{
return m_processPathHasBeenSet;
}
string RiskSyscallWhiteListInfo::GetId() const
{
return m_id;
}
void RiskSyscallWhiteListInfo::SetId(const string& _id)
{
m_id = _id;
m_idHasBeenSet = true;
}
bool RiskSyscallWhiteListInfo::IdHasBeenSet() const
{
return m_idHasBeenSet;
}
| 30.055556 | 154 | 0.684087 | [
"vector",
"model"
] |
1f270cd81f4fb6d56bfb57aaef1f1a89dd1c9bb6 | 31,189 | cc | C++ | xic/src/sced/sced_run.cc | bernardventer/xictools | 4ea72c118679caed700dab3d49a8d36445acaec3 | [
"Apache-2.0"
] | 3 | 2020-01-26T14:18:52.000Z | 2020-12-09T20:07:22.000Z | xic/src/sced/sced_run.cc | chris-ayala/xictools | 4ea72c118679caed700dab3d49a8d36445acaec3 | [
"Apache-2.0"
] | null | null | null | xic/src/sced/sced_run.cc | chris-ayala/xictools | 4ea72c118679caed700dab3d49a8d36445acaec3 | [
"Apache-2.0"
] | 2 | 2020-01-26T14:19:02.000Z | 2021-08-14T16:33:28.000Z | /*========================================================================*
* *
* Distributed by Whiteley Research Inc., Sunnyvale, California, USA *
* http://wrcad.com *
* Copyright (C) 2017 Whiteley Research Inc., all rights reserved. *
* Author: Bernard H. Venter, March 2019 *
* Author: Stephen R. Whiteley, except as indicated. *
* *
* As fully as possible recognizing licensing terms and conditions *
* imposed by earlier work from which this work was derived, if any, *
* this work is released under the Apache License, Version 2.0 (the *
* "License"). You may not use this file except in compliance with *
* the License, and compliance with inherited licenses which are *
* specified in a sub-header below this one if applicable. A copy *
* of the License is provided with this distribution, or you may *
* obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* See the License for the specific language governing permissions *
* and limitations under the License. *
* *
* 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 NON- *
* INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED *
* OR STEPHEN R. WHITELEY 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. *
* *
*========================================================================*
* XicTools Integrated Circuit Design System *
* *
* Xic Integrated Circuit Layout and Schematic Editor *
* *
*========================================================================*
$Id:$
*========================================================================*/
#include "main.h"
#include "sced.h"
#include "dsp_inlines.h"
#include "events.h"
#include "menu.h"
#include "ebtn_menu.h"
#include "promptline.h"
#include "cvrt.h"
#include "editif.h"
#include "fio.h"
#include "fio_gdsii.h"
#include "fio_alias.h"
#include "cd_digest.h"
#include "scedif.h"
#include "dsp_layer.h"
#include "cvrt_menu.h"
#include "tech.h"
#include "layertab.h"
#include "tech_kwords.h"
#include "miscutil/filestat.h"
#include <sys/stat.h>
#include "sced_spiceipc.h"
#include "dsp_tkif.h"
#include "errorlog.h"
#include "select.h"
#include "miscutil/pathlist.h"
#ifdef WIN32
#include <winsock2.h>
#else
#include <arpa/inet.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <bits/stdc++.h>
// The pull-down menu entries.
// These keywords are the menu labels, and are also used as help system
// tags "run_spice:xxx".
// The order MUST match the RunType enum!
//
namespace {
const char * run_spice[] = {
"JoSIM",
"WRSpice",
"InductEx",
0
};
}
const char *const *
cSced::runList()
{
return (run_spice);
}
namespace {
// Return a tokens to use as the "cellname" in a filename.
//
void
def_cellname(char *buf, const stringlist *list)
{
if (Cvt()->WriteFilename())
strcpy(buf, Cvt()->WriteFilename());
else {
if (!strcmp(list->string, FIO_CUR_SYMTAB))
strcpy(buf, "symtab_cells");
else
strcpy(buf, list->string);
char *s = strrchr(buf,'.');
if (s && s != buf)
*s = '\0';
if (FIO()->IsStripForExport())
strcat(buf, ".phys");
}
}
// creates and dumps a GDSII file of the current circiut to be used
// in InductEx. the function returns the address of the GDSII file
// that was created.
//
char *
outGDS( bool allcells, void*)
{
// // Clear pushed filename and AOI params, if any.
// if (Cvt()->WriteFilename()) {
// Cvt()->SetWriteFilename(0);
// Cvt()->SetupWriteCut(0);
// }
stringlist *namelist = new stringlist(lstring::copy(
allcells ? FIO_CUR_SYMTAB : Tstring(DSP()->CurCellName())), 0);
GCdestroy<stringlist> gc_namelist(namelist);
CDcbin cbin(DSP()->CurCellName());
if (!cbin.isSubcell())
EditIf()->assignGlobalProperties(&cbin);
FIOcvtPrms prms;
prms.set_scale(FIO()->WriteScale());
prms.set_alias_mask(CVAL_CASE | CVAL_PFSF | CVAL_FILE);
if (!allcells && FIO()->OutFlatten()) {
prms.set_flatten(true);
if (FIO()->OutUseWindow()) {
prms.set_use_window(true);
prms.set_window(FIO()->OutWindow());
prms.set_clip(FIO()->OutClip());
}
}
char buf[256];
def_cellname(buf, namelist);
strcat(buf, "_new.gds");
PL()->ErasePrompt();
// save and get address of file
char *s = pathlist::expand_path(buf, true, true);
s = lstring::strip_space(s);
pathlist::path_canon(s);
char *gdsname = pathlist::expand_path(s, false, true);
prms.set_destination(gdsname, Fgds);
FIO()->ConvertToGds(namelist, &prms);
return(gdsname);
}
}
//
//-----------------------------------------------------------------------------
// The function parces a line from the XIC circuit file into one InductEX
// can use. The .param is removed and the calculated values are added inline
// with the component name and coordinates.
//
void
Param_val(char * inLine, char *INbuffer, char *newLine, FILE *OUT,std::vector<std::string> &Ts,std::vector<std::string> &TsCoord){
char *tokens = strtok (inLine," =\n");
char comp ='o';
int coord_flag = 0;
char Hold[20];
char Coord[20];
double TempPval = 0;
// JJ or Inductor
if(!(strncmp(inLine,"B",1))){ // for JJ
tokens[0] = 'J';
comp = 'B';
}
else if (!(strncmp(inLine,"L",1))){ // for inductor
comp = 'L';
}
else if (!(strncmp(inLine,"R",1))){ // for resistor
comp = 'R';
}
strcpy(newLine,tokens);
//Get the coords
for(int i = 0; i < 2 ; ++i){
strcat(newLine," ");
tokens = strtok (NULL, " =\n");
if(!(strncmp(tokens,"P",1))){ //if port is given as node name
if(!(std::find(Ts.begin(),Ts.end(),tokens) != Ts.end())){
Ts.push_back(tokens);
if(i && !coord_flag && (comp == 'R')){ // only applicable to resistors
TsCoord.push_back(Hold);
}
else
{
strcpy(Coord,"N_");
strcat(Coord,tokens);
TsCoord.push_back(Coord);
coord_flag = 1;
}
}
strcat(newLine,"N_");
}
strcpy(Hold,tokens); // save coord
strcat(newLine,tokens);
}
strcat(newLine," ");
tokens = strtok (NULL, " =\n");
//Get param value name
if (comp == 'B') {
tokens = strtok (NULL, " =\n");
tokens = strtok (NULL, " =\n");
tokens = strtok (NULL, " =\n");
strcpy(Hold,tokens);
}
else if ((comp == 'L')&&(strstr(tokens, "p") == NULL)){
strcpy(Hold,tokens);
}
// Rewrite component values to match InductEx input format
if (strstr(tokens, "p") != NULL) {
tokens[strlen(tokens)-1] = ' '; //removes the p
strcat(newLine,tokens);
strcat(newLine,"\n");
}
else if(strncmp(Hold,"B",1)&&(comp == 'B')){ // parse values from JJ
TempPval = atof(tokens);
TempPval = TempPval *100;
gcvt(TempPval,10,tokens);
strcat(newLine,tokens);
strcat(newLine,"\n");
}
else if (strstr(tokens, "n") != NULL) {
tokens[strlen(tokens)-1] = ' '; //removes the n and convert to p
TempPval = atof(tokens);
TempPval = TempPval * pow(10,(-3));
gcvt(TempPval,10,tokens);
strcat(newLine,tokens);
strcat(newLine,"\n");
}
else if (strstr(tokens, "u") != NULL) {
tokens[strlen(tokens)-1] = ' '; //removes the u and convert to p
TempPval = atof(tokens);
TempPval = TempPval * pow(10,(-6));
gcvt(TempPval,10,tokens);
strcat(newLine,tokens);
strcat(newLine,"\n");
}
else if (strstr(tokens, "e") != NULL) { // using e-xx in component value
char vals[20];
char pw[4];
sscanf( tokens, "%[^e]e%[^\n]\n", vals, pw);
int powers = atoi(pw);
TempPval = atof(vals);
TempPval = TempPval * pow(10,(12+powers));
gcvt(TempPval,10,tokens);
strcat(newLine,tokens);
strcat(newLine,"\n");
}
else if (strstr(tokens, "E") != NULL) { // using E-xx in component value
char vals[20];
char pw[4];
sscanf( tokens, "%[^E]E%[^\n]\n", vals, pw);
int powers = atoi(pw);
TempPval = atof(vals);
TempPval = TempPval * pow(10,(12+powers));
gcvt(TempPval,10,tokens);
strcat(newLine,tokens);
strcat(newLine,"\n");
}
else if(strstr(INbuffer,Hold)){
strcat(Hold,"="); //last caracter must be =
char *ParLine = strstr(INbuffer,Hold);
char Pname[20];
char Pval[30];
char Pscale[20];
char Pwr[4];
double Cval;
if(comp == 'L'){ //
if(strncmp(ParLine,"Scaling",7) == 0){
if(strstr(tokens, "E") != NULL){
sscanf( ParLine, "%[^=]=%[^E]E%[^*]*", Pname, Pval, Pwr);
}
else{
sscanf( ParLine, "%[^=]=%[^e]e%[^*]*", Pname, Pval, Pwr);
}
}
else
{
if(strstr(tokens, "E") != NULL){
sscanf( ParLine, "%[^=]=%[^E]E%[^\n]\n", Pname, Pval, Pwr);
}
else{
sscanf( ParLine, "%[^=]=%[^e]e%[^\n]\n", Pname, Pval, Pwr);
}
}
int power = atoi(Pwr);
Cval = atof(Pval);
Cval = Cval * pow(10,(12+power));
}
else if(comp == 'B'){
if(strncmp(ParLine,"Scaling",7) == 0){
sscanf( ParLine, "%[^=]=%[^*]*%[^\n]\n", Pname, Pval,Pscale);
}
else
{
sscanf( ParLine, "%[^=]=%[^\n]\n", Pname, Pval);
}
Cval = atof(Pval);
Cval = Cval * 100; // change for ic * a
}
gcvt(Cval,10,tokens);
strcat(newLine,tokens);
strcat(newLine,"\n");
}
// Remove resistance
if(!(comp == 'R'))
fputs(newLine,OUT);
// delete [] tokens;
return;
}
// load the data from the XIC generated circuit file to the buffer.
//
char
*LoadBuf(char * dataIN){
FILE *Din = fopen (dataIN , "r");
if (dataIN==NULL){
PL()->ShowPromptV("ERROR: Circuit file not read");
Errs()->sys_error("ERROR: Circuit file not read");
return 0;
}
// find file size
fseek(Din , 0 , SEEK_END);
size_t Csize = ftell(Din);
rewind(Din);
// alocate memory and store data in buffer
char * CIRbuf = (char*) malloc(sizeof(char)*Csize);
if (CIRbuf == NULL){
PL()->ShowPromptV("ERROR: No data to read");
Errs()->sys_error("ERROR: No data to read");
return 0;
}
//read data
size_t CIRdata = fread (CIRbuf,1,Csize,Din);
if(CIRdata != Csize){
PL()->ShowPromptV("ERROR: Circuit file is empty");
Errs()->sys_error("ERROR: Circuit file is empty");
return 0;
}
fclose (Din);
return (char *) CIRbuf;
}
// The function create port for selected components.
//
void
Port_val(int portNumber, const char * PortName,char *NewLine, char *fileLine,FILE *OUT){
char PortNum [10];
char Hold[20];
sprintf(PortNum, "%d", portNumber);
strcpy(NewLine,PortName);
strcat(NewLine,PortNum);
portNumber++;
strcat(NewLine," ");
char *seg = strtok (fileLine," ");
seg = strtok (NULL, " ");
if(!(strncmp(PortName,"PB",2))){
strcpy(Hold,seg);
seg = strtok (NULL, " ");
strcat(NewLine,seg);
strcat(NewLine," ");
strcat(NewLine,Hold);
} else if(!(strncmp(PortName,"PR",2))){
strcat(NewLine,seg);
strcat(NewLine," ");
seg = strtok (NULL, " ");
strcat(NewLine,seg);
} else {
strcat(NewLine,seg);
strcat(NewLine," 0");
}
strcat(NewLine,"\n");
fputs(NewLine,OUT);
//delete [] seg;
return;
}
// The function process the XIC generated circuit file and
// write it into a format acceptable by InductEX
//
void
inductexOUT(char * cirIN, char * cirOUT)
{
char fileString [256];
char ParLine [256];
char New_line [256];
char VecTest [256];
int pn = 1; // port count
int rn = 1; // resistor port count
int ib = 1; // curretnt port count
char * INbuff = LoadBuf(cirIN);
FILE *pOUT = fopen (cirOUT , "w");
FILE *pIN = fopen (cirIN , "r");
//Fix rest using vector
std::vector<std::string> PortID;
std::vector<std::string> PortCoord;
while ( fgets (fileString , 256 , pIN) != NULL ){
if(!(strncmp(fileString,"*",1))){
fputs(fileString,pOUT);
}
if(!(strncmp(fileString,"K",1)) || !(strncmp(fileString,"k",1))){ // includes the Mutual Inductance term for inductEx
fputs(fileString,pOUT);
}
if(!(strncmp(fileString,".",1))){
// do Nothing,avoids false positives from param
}
else if(!(strncmp(fileString,"B",1))){
Param_val(fileString, INbuff,New_line, pOUT,PortID,PortCoord);
}
else if(!(strncmp(fileString,"IB",1))){
Port_val(ib,"PB",New_line,fileString,pOUT);
ib++;
}
// clk is named first and is the first port always.
else if (strstr(fileString, "CLK") != NULL){
strcpy(ParLine,fileString);
Param_val(fileString, INbuff,New_line, pOUT,PortID,PortCoord);
Port_val(pn,"P",New_line,ParLine,pOUT);
pn++;
}
else if ((strstr(fileString, " IN ") != NULL) || (strstr(fileString, "IN_") != NULL)){
strcpy(ParLine,fileString);
Param_val(fileString, INbuff,New_line, pOUT,PortID,PortCoord);
Port_val(pn,"P",New_line,ParLine,pOUT);
pn++;
}
else if (strstr(fileString, "RP") != NULL){
Port_val(rn,"PR",New_line,fileString,pOUT);
rn++;
}
else if ((strstr(fileString, " OUT ") != NULL) || (strstr(fileString, "OUT_") != NULL)){
Port_val(pn,"P",New_line,fileString,pOUT);
pn++;
}
else if (!(strncmp(fileString,"L",1))){
if (strstr(fileString, "LRB") == NULL){
Param_val(fileString, INbuff,New_line, pOUT,PortID,PortCoord);
}
}
else if (!(strncmp(fileString,"R",1)) && (strstr(fileString, " P") != NULL)){
Param_val(fileString, INbuff,New_line, pOUT,PortID,PortCoord);
}
}
// Add ports to output file
int np = 0;
std::vector<std::string>::iterator i;
for ( i = PortID.begin() ; i < PortID.end() ; ++i ){
strcpy(VecTest,PortID[np].c_str());
strcat(VecTest," ");
strcat(VecTest,PortCoord[np].c_str());
strcat(VecTest," 0\n");
fputs(VecTest,pOUT);
np++;
}
PortID.clear();
fclose (pIN);
fclose (pOUT);
free (INbuff);
return;
}
//-----------------------------------------------------------------------------
// The Parse JoSIM Input.
//
// Dump the .cir file in a format compatible with JoSIM.
//
void ParseJosim(char * cirIN, char * cirOUT)
{
char JosimString [256];
char ParLineJJ [256];
char PlotVol [256];
char PlotPhase [256];
bool CirBreak = 0;
// char PlotCurrent [256];
char * INbuffJJ = LoadBuf(cirIN);
FILE *jOUT = fopen (cirOUT , "w");
FILE *jIN = fopen (cirIN , "r");
std::vector<std::string> PlotData;
std::vector<std::string> PlotJJ;
// std::vector<std::string> PlotTest;
while ( fgets (JosimString , 256 , jIN) != NULL ){
if(!(strncmp(JosimString,".plot",5))){
strcpy(ParLineJJ,JosimString);
char *tokens = strtok (ParLineJJ," v()\n\""); // .plot
tokens = strtok (NULL," v()\n\""); // tran
for(tokens = strtok (NULL," v()\n\"");tokens != NULL;tokens = strtok (NULL," v()\n\""))
{
PlotData.push_back(tokens);
}
}
else
{
fputs(JosimString,jOUT);
}
if(!(strncmp(JosimString,".subckt",7))){ // skip sub-circuit
CirBreak = 1;
}
if (!(strncmp(JosimString,"B",1)) && !CirBreak){
strcpy(ParLineJJ,JosimString);
char *tokenb = strtok (ParLineJJ," ");
PlotJJ.push_back(tokenb);
tokenb = strtok (NULL," ");
tokenb = strtok (NULL," ");
tokenb = strtok (NULL," ");
PlotJJ.push_back(tokenb);
}
}
// Add ports to output file
int kp = 0;
// strcpy(PlotCurrent,".plot ");
std::vector<std::string>::iterator i;
std::vector<std::string>::iterator j;
for ( j = PlotData.begin() ; j < PlotData.end() ; ++j ){
i = std::find (PlotJJ.begin(), PlotJJ.end(), PlotData[kp]);
if (i != PlotJJ.end())
{
strcpy(PlotPhase,".plot PHASE ");
strcat(PlotPhase,PlotJJ[i - PlotJJ.begin() - 1].c_str());
strcat(PlotPhase," \n");
fputs(PlotPhase,jOUT);
}
else //add branch
{
strcpy(PlotVol,".plot tran ");
strcat(PlotVol,"v(");
strcat(PlotVol, PlotData[kp].c_str());
strcat(PlotVol,") \n");
fputs(PlotVol,jOUT);
}
kp++;
}
PlotData.clear();
PlotJJ.clear();
fclose (jIN);
fclose (jOUT);
free (INbuffJJ);
return;
}
//-----------------------------------------------------------------------------
// The RUN WRspice command.
//
// Submenu command for running WRspice. In asynchronous mode, the run button
// is left active while simulation continues.
void runWRspiceExec(CmdDesc* cmd)
{
Deselector ds( cmd);
if (!XM()->CheckCurMode(Electrical))
return;
if (!XM()->CheckCurCell(false, false, Electrical))
return;
if (cmd && Menu()->GetStatus(cmd->caller)) {
if (!SCD()->spif()->RunSpice(cmd))
return;
ds.clear();
}
}
//-----------------------------------------------------------------------------
// The RUN JoSIM command.
//
// Submenu command for running JoSIM. The circuit file is dumped in the current
// directory and simulated using JoSIM. The location of JoSIM is selected via the
// open dialog.
void
runJoSIMExec(CmdDesc* cmd)
{
if (!XM()->CheckCurMode(Electrical))
return;
if (!XM()->CheckCurCell(false, false, Electrical))
return;
if (CurCell()->isEmpty()) {
PL()->ShowPrompt("No electrical data found in current cell.");
return;
}
if (DSP()->CurCellName() == DSP()->TopCellName()) {
char *s = SCD()->getAnalysis(false);
if (!s || strcmp(s, "run")) {
char *in =
PL()->EditPrompt("Enter optional analysis command: ", s);
if (!in) {
PL()->ErasePrompt();
delete [] s;
return;
}
while (isspace(*in))
in++;
if (*in)
SCD()->setAnalysis(in);
}
delete [] s;
}
PL()->ErasePrompt();
char tbuf[256];
char jbuf[256];
strcpy(tbuf, Tstring(DSP()->CurCellName()));
char *s;
if ((s = strrchr(tbuf, '.')) != 0) {
if (!strcmp(s+1, "cir"))
strcpy(s+1, "deck");
else
strcpy(s+1, "cir");
}
else
strcat(tbuf, ".cir");
char *in = pathlist::expand_path(tbuf, true, true);
in = lstring::strip_space(in);
pathlist::path_canon(in);
char *filename = pathlist::expand_path(in, false, true);
SCD()->dumpSpiceFile(filename);
PL()->ShowPrompt("DONE");
// create path for JoSIM output file
char oubuf[256];
strcpy(oubuf, Tstring(DSP()->CurCellName()));
char *scj;
if ((scj = strrchr(oubuf, '.')) != 0) {
if (!strcmp(scj, "_josim.cir"))
strcpy(scj, "_josim.deck");
else
strcpy(scj, "_josim.cir");
}
else
strcat(oubuf, "_josim.cir");
char *outJJ = pathlist::expand_path(oubuf, true, true);
outJJ = lstring::strip_space(outJJ);
pathlist::path_canon(outJJ);
char *cirJJ = pathlist::expand_path(outJJ, false, true);
//delete [] sc
const char *JoSim_file = "josim";
const char *JoSim_file_cap = "josim-cli";
char *inJoSIM = pathlist::expand_path("/usr/local/bin", false, true);
bool JoSIM_check_linux = pathlist::find_path_file(JoSim_file, "/usr/local/bin",NULL,true);
bool JoSIM_check_mac = pathlist::find_path_file(JoSim_file_cap, "/usr/local/bin",NULL,true);
//check path
bool inJoSIMlib = false;
// Choose the location of JoSIM
if(JoSIM_check_linux)
inJoSIM = pathlist::expand_path("/usr/local/bin/josim", false, true);
else if(JoSIM_check_mac)
inJoSIM = pathlist::expand_path("/usr/local/bin/josim-cli", false, true);
else {
inJoSIMlib = true;
// strcpy (jbuf, "");
// char *inJo = XM()->OpenFileDlg("Open JoSIM Install Location: ", jbuf);
// inJoSIM = pathlist::expand_path(inJo, false, true);
// if (!inJoSIM || !*inJoSIM) {
// PL()->ErasePrompt();
// return;
// }
}
// Test if JoSIM has been selected
const char *loc_J1 = inJoSIM + strlen(inJoSIM) - strlen(JoSim_file);
const char *loc_J2 = inJoSIM + strlen(inJoSIM) - strlen(JoSim_file_cap);
if ((strcmp(JoSim_file, loc_J1) != 0) && (strcmp(JoSim_file_cap, loc_J2) != 0) &&!(inJoSIMlib)){
PL()->ShowPromptV("ERROR: JOSIM Not Found");
Errs()->sys_error("ERROR: JOSIM Not Found");
return;
}
// Load plotting data
JoSIM_Flag = 1;
// Fork process to run Josim
int cpid = fork();
if (cpid == -1) {
Errs()->sys_error("init_local: fork");
return;
}
if (!cpid) {
ParseJosim(filename, cirJJ); // parse josim file
if(inJoSIMlib){
execlp("josim","josim","-c", "1", "-o","output", cirJJ, (char *) 0);
}
else
execl(inJoSIM,inJoSIM,"-c", "1", "-o","output", cirJJ, (char *) 0);
Errs()->sys_error("JoSIM execution failed");
return;
}
}
RunType Run_option();
//-----------------------------------------------------------------------------
// The RUN InductEx command
//
// Submenu command for running InductEx. The circuit file and GDSII file is dumped
// in the current directory. They are simulated using InductEx. The location of Inductex
// is the default as specified for windows.
void runInductExec(CmdDesc* cmd)
{
if (!XM()->CheckCurMode(Electrical))
return;
if (!XM()->CheckCurCell(false, false, Electrical))
return;
if (CurCell()->isEmpty()) {
PL()->ShowPrompt("No electrical data found in current cell.");
return;
}
// dump spice netlist and load file name and address
if (DSP()->CurCellName() == DSP()->TopCellName()) {
char *s = SCD()->getAnalysis(false);
if (!s || strcmp(s, "run")) {
char *in =
PL()->EditPrompt("Enter optional analysis command: ", s);
if (!in) {
PL()->ErasePrompt();
delete [] s;
return;
}
while (isspace(*in))
in++;
if (*in)
SCD()->setAnalysis(in);
}
delete [] s;
}
char tbuf[256];
strcpy(tbuf, Tstring(DSP()->CurCellName()));
char *s;
if ((s = strrchr(tbuf, '.')) != 0) {
if (!strcmp(s+1, "cir"))
strcpy(s+1, "deck");
else
strcpy(s+1, "cir");
}
else
strcat(tbuf, ".cir");
char *in = pathlist::expand_path(tbuf, true, true);
in = lstring::strip_space(in);
pathlist::path_canon(in);
char *cirfile = pathlist::expand_path(in, false, true);
SCD()->dumpSpiceFile(cirfile);
//delete [] s
// create path for IDX output file
char obuf[256];
strcpy(obuf, Tstring(DSP()->CurCellName()));
char *sc;
if ((sc = strrchr(obuf, '.')) != 0) {
if (!strcmp(sc, "_idx.cir"))
strcpy(sc, "_idx.deck");
else
strcpy(sc, "_idx.cir");
}
else
strcat(obuf, "_idx.cir");
char *outC = pathlist::expand_path(obuf, true, true);
outC = lstring::strip_space(outC);
pathlist::path_canon(outC);
char *cirIDX = pathlist::expand_path(outC, false, true);
//delete [] sc
// dump GDSII file
if (cmd && Menu()->GetStatus(cmd->caller)) {
if (!DSP()->CurCellName()) {
PL()->ShowPrompt("No current cell!");
if (cmd)
Menu()->Deselect(cmd->caller);
return;
}
CDvdb()->setVariable(VA_PCellKeepSubMasters, ""); // change the keep pcell option
char * GDSloc = outGDS(0, 0); // no variables need can remove
CDvdb()->clearVariable(VA_PCellKeepSubMasters); // clean up pcell option
// check if inductex is in default location
const char *inductEXE = "inductex";
bool Inductex_check = pathlist::find_path_file(inductEXE, "/usr/local/bin",NULL,true); // /utils/inductex/bin
char *Induct = pathlist::expand_path("/usr/local/bin/inductex", false, true); // /utils/inductex/bin
bool inIDXlib = false; // look for in PATH
if(!(Inductex_check)){
inIDXlib = true;
// PL()->ShowPromptV("ERROR: InductEx Not Found");
// Errs()->sys_error("ERROR: InductEx Not Found");
// return;
}
// open ldf file
char Ibuf[256];
strcpy (Ibuf, "");
char *inI = XM()->OpenFileDlg("Open InductEx LDF File: ", Ibuf);
char *inIDX = pathlist::expand_path(inI, false, true);
if (!strstr(inIDX, ".ldf")){
PL()->ShowPromptV("ERROR: LDF File Not Found");
Errs()->sys_error("ERROR: LDF File Not Found");
return;
}
// delete inI [];
const char *methodIDX;
char * met = PL()->EditPrompt("Choose Numerical Engine. TetraHenry-> t and FFH-> f : ", "");
met = lstring::strip_space(met);
if (met && (*met == 'f' || *met == 'F')){
methodIDX = "-fh";
}
else if (met && (*met == 't' || *met == 'T')){
methodIDX = "-th";
}
else{
PL()->ShowPromptV("ERROR: Choose valid numerical engine");
Errs()->sys_error("ERROR: Choose valid numerical engine");
return;
}
PL()->ErasePrompt();
PL()->ShowPrompt("Simulating in cmd terminal window");
// Fork process to run Inductex
int cpid = fork();
if (cpid == -1) {
Errs()->sys_error("init_local: fork");
return;
}
if (!cpid) {
inductexOUT(cirfile,cirIDX); //run cir to inductex cir
if(inIDXlib){
execlp("inductex","inductex",GDSloc, "-l", inIDX,"-i", "IDXout.inp",methodIDX,"-n", cirIDX,"-xic", (char *) 0); // replace cirTEST with cirfile and select ldf file option? //"mitll_sfq5ee_set1.ldf"
}
else
execl(Induct,Induct,GDSloc, "-l", inIDX,"-i", "IDXout.inp",methodIDX,"-n", cirIDX,"-xic", (char *) 0); // replace cirTEST with cirfile and select ldf file option? //"mitll_sfq5ee_set1.ldf"
Errs()->sys_error("Inductex Execution Failed");
return;
}
else
return;
}
}
// This is called in response to the pull-down menu of run templates.
//
void
cSced::RunCom(int Run_option,CmdDesc* cmd)
{
switch (Run_option) {
case runJoSIM:
runJoSIMExec(cmd);
break;
case runWRspice:
runWRspiceExec(cmd);
break;
case runInductEx:
runInductExec(cmd);
break;
default:
if (!XM()->CheckCurMode(Electrical))
return;
if (!XM()->CheckCurLayer())
return;
if (!XM()->CheckCurCell(true, true, Electrical))
return;
break;
}
// typedef std::map<std::string, std::string> StringMap;
// StringMap map;
// map.insert(StringMap::value_type("",""));
// StringMap::iterator it = map.find("");
// std::strimg value = it->second;
}
| 33.392934 | 213 | 0.492257 | [
"vector"
] |
1f28decf63a8a9d63e2e29c182ac6daffb78b2de | 1,217 | cpp | C++ | src/XML.cpp | JesseMaurais/SGe | f73bd03d30074a54642847b05f82151128481371 | [
"MIT"
] | 1 | 2017-04-20T06:27:36.000Z | 2017-04-20T06:27:36.000Z | src/XML.cpp | JesseMaurais/SGe | f73bd03d30074a54642847b05f82151128481371 | [
"MIT"
] | null | null | null | src/XML.cpp | JesseMaurais/SGe | f73bd03d30074a54642847b05f82151128481371 | [
"MIT"
] | null | null | null | #include "XML.hpp"
#include "SDL.hpp"
#include "Error.hpp"
#include <stdexcept>
XML::XML(char const *encoding)
{
auto start = [](void *user, char const *name, char const **attributes)
{
union {
void *address;
XML *object;
};
address = user;
object->Start(name, attributes);
};
auto end = [](void *user, char const *name)
{
union {
void *address;
XML *object;
};
address = user;
object->End(name);
};
parser = XML_ParserCreate(encoding);
if (not parser) throw std::runtime_error(String(CannotCreateParser));
XML_SetElementHandler(parser, start, end);
XML_SetUserData(parser, this);
}
XML::~XML(void)
{
if (parser) XML_ParserFree(parser);
}
bool XML::Parse(SDL_RWops *ops)
{
void *buffer;
std::size_t size;
do
{
buffer = XML_GetBuffer(parser, BUFSIZ);
size = SDL_RWread(ops, buffer, sizeof(char), BUFSIZ);
if (not XML_ParseBuffer(parser, size, 0 == size))
{
XML_Error code = XML_GetErrorCode(parser);
char const *string = XML_ErrorString(code);
int line = XML_GetCurrentLineNumber(parser);
int col = XML_GetCurrentColumnNumber(parser);
SDL::SetError("XML (%1, %2) %3", line, col, string);
return false;
}
}
while (size > 0);
return true;
}
| 20.283333 | 71 | 0.665571 | [
"object"
] |
1f2c0fe80f5dc70f2986bafc2aa5b2e523004bf8 | 14,168 | cpp | C++ | component/oai-amf/src/ngap/ngapMsgs/PduSessionResourceModifyResponse.cpp | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | component/oai-amf/src/ngap/ngapMsgs/PduSessionResourceModifyResponse.cpp | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | component/oai-amf/src/ngap/ngapMsgs/PduSessionResourceModifyResponse.cpp | kukkalli/oai-cn5g-fed | 15634fac935ac8671b61654bdf75bf8af07d3c3a | [
"Apache-2.0"
] | null | null | null | /*
* Licensed to the OpenAirInterface (OAI) Software Alliance under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The OpenAirInterface Software Alliance licenses this file to You under
* the OAI Public License, Version 1.1 (the "License"); you may not use this
* file except in compliance with the License. You may obtain a copy of the
* License at
*
* http://www.openairinterface.org/?page_id=698
*
* 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.
*-------------------------------------------------------------------------------
* For more information about the OpenAirInterface (OAI) Software Alliance:
* contact@openairinterface.org
*/
/*! \file
\brief
\author
\date 2021
\email: contact@openairinterface.org
*/
#include "PduSessionResourceModifyResponse.hpp"
#include "amf.hpp"
#include "logger.hpp"
extern "C" {
#include "asn_codecs.h"
#include "constr_TYPE.h"
#include "constraints.h"
#include "dynamic_memory_check.h"
#include "per_decoder.h"
#include "per_encoder.h"
}
#include <iostream>
using namespace std;
namespace ngap {
//------------------------------------------------------------------------------
PduSessionResourceModifyResponseMsg::PduSessionResourceModifyResponseMsg() {
// Set Message Type
pduSessionResourceModifyResponsePdu =
(Ngap_NGAP_PDU_t*) calloc(1, sizeof(Ngap_NGAP_PDU_t));
MessageType pdu = {};
pdu.setProcedureCode(Ngap_ProcedureCode_id_PDUSessionResourceModify);
pdu.setTypeOfMessage(Ngap_NGAP_PDU_PR_successfulOutcome);
pdu.setCriticality(Ngap_Criticality_reject);
pdu.setValuePresent(
Ngap_SuccessfulOutcome__value_PR_PDUSessionResourceModifyResponse);
pdu.encode2pdu(pduSessionResourceModifyResponsePdu);
pduSessionResourceModifyResponseIEs =
&(pduSessionResourceModifyResponsePdu->choice.successfulOutcome->value
.choice.PDUSessionResourceModifyResponse);
}
//------------------------------------------------------------------------------
PduSessionResourceModifyResponseMsg::~PduSessionResourceModifyResponseMsg() {
// TODO:
}
//------------------------------------------------------------------------------
void PduSessionResourceModifyResponseMsg::setMessageType() {
if (!pduSessionResourceModifyResponsePdu)
pduSessionResourceModifyResponsePdu =
(Ngap_NGAP_PDU_t*) calloc(1, sizeof(Ngap_NGAP_PDU_t));
MessageType pdu = {};
pdu.setProcedureCode(Ngap_ProcedureCode_id_PDUSessionResourceModify);
pdu.setTypeOfMessage(Ngap_NGAP_PDU_PR_successfulOutcome);
pdu.setCriticality(Ngap_Criticality_reject);
pdu.setValuePresent(
Ngap_SuccessfulOutcome__value_PR_PDUSessionResourceModifyResponse);
pdu.encode2pdu(pduSessionResourceModifyResponsePdu);
pduSessionResourceModifyResponseIEs =
&(pduSessionResourceModifyResponsePdu->choice.successfulOutcome->value
.choice.PDUSessionResourceModifyResponse);
}
//------------------------------------------------------------------------------
void PduSessionResourceModifyResponseMsg::setAmfUeNgapId(unsigned long id) {
amfUeNgapId.setAMF_UE_NGAP_ID(id);
Ngap_PDUSessionResourceModifyResponseIEs_t* ie =
(Ngap_PDUSessionResourceModifyResponseIEs_t*) calloc(
1, sizeof(Ngap_PDUSessionResourceModifyResponseIEs_t));
ie->id = Ngap_ProtocolIE_ID_id_AMF_UE_NGAP_ID;
ie->criticality = Ngap_Criticality_ignore;
ie->value.present =
Ngap_PDUSessionResourceModifyResponseIEs__value_PR_AMF_UE_NGAP_ID;
int ret = amfUeNgapId.encode2AMF_UE_NGAP_ID(ie->value.choice.AMF_UE_NGAP_ID);
if (!ret) {
Logger::ngap().error("Encode NGAP AMF_UE_NGAP_ID IE error");
free_wrapper((void**) &ie);
return;
}
ret = ASN_SEQUENCE_ADD(
&pduSessionResourceModifyResponseIEs->protocolIEs.list, ie);
if (ret != 0) Logger::ngap().error("Encode NGAP AMF_UE_NGAP_ID IE error");
// free_wrapper((void**) &ie);
}
//------------------------------------------------------------------------------
void PduSessionResourceModifyResponseMsg::setRanUeNgapId(
uint32_t ran_ue_ngap_id) {
ranUeNgapId.setRanUeNgapId(ran_ue_ngap_id);
Ngap_PDUSessionResourceModifyResponseIEs_t* ie =
(Ngap_PDUSessionResourceModifyResponseIEs_t*) calloc(
1, sizeof(Ngap_PDUSessionResourceModifyResponseIEs_t));
ie->id = Ngap_ProtocolIE_ID_id_RAN_UE_NGAP_ID;
ie->criticality = Ngap_Criticality_ignore;
ie->value.present =
Ngap_PDUSessionResourceModifyResponseIEs__value_PR_RAN_UE_NGAP_ID;
int ret = ranUeNgapId.encode2RAN_UE_NGAP_ID(ie->value.choice.RAN_UE_NGAP_ID);
if (!ret) {
Logger::ngap().error("Encode NGAP RAN_UE_NGAP_ID IE error");
free_wrapper((void**) &ie);
return;
}
ret = ASN_SEQUENCE_ADD(
&pduSessionResourceModifyResponseIEs->protocolIEs.list, ie);
if (ret != 0) Logger::ngap().error("Encode NGAP RAN_UE_NGAP_ID IE error");
// free_wrapper((void**) &ie);
}
//------------------------------------------------------------------------------
void PduSessionResourceModifyResponseMsg::
setPduSessionResourceModifyResponseList(
std::vector<PDUSessionResourceModifyResponseItem_t> list) {
std::vector<PDUSessionResourceModifyItemModRes>
m_pduSessionResourceModifyItemModRes;
for (int i = 0; i < list.size(); i++) {
PDUSessionID m_pDUSessionID = {};
m_pDUSessionID.setPDUSessionID(list[i].pduSessionId);
PDUSessionResourceModifyItemModRes item = {};
item.setPDUSessionResourceModifyItemModRes(
m_pDUSessionID, list[i].pduSessionResourceModifyResponseTransfer);
m_pduSessionResourceModifyItemModRes.push_back(item);
}
pduSessionResourceModifyList.setPDUSessionResourceModifyListModRes(
m_pduSessionResourceModifyItemModRes);
Ngap_PDUSessionResourceModifyResponseIEs_t* ie =
(Ngap_PDUSessionResourceModifyResponseIEs_t*) calloc(
1, sizeof(Ngap_PDUSessionResourceModifyResponseIEs_t));
ie->id = Ngap_ProtocolIE_ID_id_PDUSessionResourceModifyListModRes;
ie->criticality = Ngap_Criticality_reject;
ie->value.present =
Ngap_PDUSessionResourceModifyResponseIEs__value_PR_PDUSessionResourceModifyListModRes;
int ret =
pduSessionResourceModifyList.encode2PDUSessionResourceModifyListModRes(
ie->value.choice.PDUSessionResourceModifyListModRes);
if (!ret) {
Logger::ngap().error(
"Encode NGAP PDUSessionResourceModifyListModRes IE error");
free_wrapper((void**) &ie);
return;
}
ret = ASN_SEQUENCE_ADD(
&pduSessionResourceModifyResponseIEs->protocolIEs.list, ie);
if (ret != 0)
Logger::ngap().error(
"Encode NGAP PDUSessionResourceSetupListSUReq IE error");
// free_wrapper((void**) &ie);
}
//------------------------------------------------------------------------------
int PduSessionResourceModifyResponseMsg::encode2buffer(
uint8_t* buf, int buf_size) {
asn_fprint(
stderr, &asn_DEF_Ngap_NGAP_PDU, pduSessionResourceModifyResponsePdu);
asn_enc_rval_t er = aper_encode_to_buffer(
&asn_DEF_Ngap_NGAP_PDU, NULL, pduSessionResourceModifyResponsePdu, buf,
buf_size);
Logger::ngap().debug("er.encoded (%d)", er.encoded);
return er.encoded;
}
//------------------------------------------------------------------------------
void PduSessionResourceModifyResponseMsg::encode2buffer_new(
char* buf, int& encoded_size) {
char* buffer = (char*) calloc(1, BUFFER_SIZE_1024);
asn_fprint(
stderr, &asn_DEF_Ngap_NGAP_PDU, pduSessionResourceModifyResponsePdu);
encoded_size = aper_encode_to_new_buffer(
&asn_DEF_Ngap_NGAP_PDU, NULL, pduSessionResourceModifyResponsePdu,
(void**) &buffer);
Logger::ngap().debug("er.encoded (%d)", encoded_size);
memcpy((void*) buf, (void*) buffer, encoded_size);
free(buffer);
}
//------------------------------------------------------------------------------
bool PduSessionResourceModifyResponseMsg::decodefrompdu(
Ngap_NGAP_PDU_t* ngap_msg_pdu) {
pduSessionResourceModifyResponsePdu = ngap_msg_pdu;
if (pduSessionResourceModifyResponsePdu->present ==
Ngap_NGAP_PDU_PR_successfulOutcome) {
if (pduSessionResourceModifyResponsePdu->choice.successfulOutcome &&
pduSessionResourceModifyResponsePdu->choice.successfulOutcome
->procedureCode ==
Ngap_ProcedureCode_id_PDUSessionResourceModify &&
pduSessionResourceModifyResponsePdu->choice.successfulOutcome
->criticality == Ngap_Criticality_reject &&
pduSessionResourceModifyResponsePdu->choice.successfulOutcome->value
.present ==
Ngap_SuccessfulOutcome__value_PR_PDUSessionResourceModifyResponse) {
pduSessionResourceModifyResponseIEs =
&pduSessionResourceModifyResponsePdu->choice.successfulOutcome->value
.choice.PDUSessionResourceModifyResponse;
} else {
Logger::ngap().error(
"Check PDUSessionResourceModifyResponse message error!");
return false;
}
} else {
Logger::ngap().error("MessageType error!");
return false;
}
for (int i = 0;
i < pduSessionResourceModifyResponseIEs->protocolIEs.list.count; i++) {
switch (
pduSessionResourceModifyResponseIEs->protocolIEs.list.array[i]->id) {
case Ngap_ProtocolIE_ID_id_AMF_UE_NGAP_ID: {
if (pduSessionResourceModifyResponseIEs->protocolIEs.list.array[i]
->criticality == Ngap_Criticality_ignore &&
pduSessionResourceModifyResponseIEs->protocolIEs.list.array[i]
->value.present ==
Ngap_PDUSessionResourceModifyResponseIEs__value_PR_AMF_UE_NGAP_ID) {
if (!amfUeNgapId.decodefromAMF_UE_NGAP_ID(
pduSessionResourceModifyResponseIEs->protocolIEs.list
.array[i]
->value.choice.AMF_UE_NGAP_ID)) {
Logger::ngap().error("Decoded NGAP AMF_UE_NGAP_ID IE error");
return false;
}
} else {
Logger::ngap().error("Decoded NGAP AMF_UE_NGAP_ID IE error");
return false;
}
} break;
case Ngap_ProtocolIE_ID_id_RAN_UE_NGAP_ID: {
if (pduSessionResourceModifyResponseIEs->protocolIEs.list.array[i]
->criticality == Ngap_Criticality_reject &&
pduSessionResourceModifyResponseIEs->protocolIEs.list.array[i]
->value.present ==
Ngap_PDUSessionResourceModifyResponseIEs__value_PR_RAN_UE_NGAP_ID) {
if (!ranUeNgapId.decodefromRAN_UE_NGAP_ID(
pduSessionResourceModifyResponseIEs->protocolIEs.list
.array[i]
->value.choice.RAN_UE_NGAP_ID)) {
Logger::ngap().error("Decoded NGAP RAN_UE_NGAP_ID IE error");
return false;
}
} else {
Logger::ngap().error("Decoded NGAP RAN_UE_NGAP_ID IE error");
return false;
}
} break;
case Ngap_ProtocolIE_ID_id_PDUSessionResourceModifyListModRes: {
if (pduSessionResourceModifyResponseIEs->protocolIEs.list.array[i]
->criticality == Ngap_Criticality_ignore &&
pduSessionResourceModifyResponseIEs->protocolIEs.list.array[i]
->value.present ==
Ngap_PDUSessionResourceModifyResponseIEs__value_PR_PDUSessionResourceModifyListModRes) {
if (!pduSessionResourceModifyList
.decodefromPDUSessionResourceModifyListModRes(
pduSessionResourceModifyResponseIEs->protocolIEs.list
.array[i]
->value.choice.PDUSessionResourceModifyListModRes)) {
Logger::ngap().error(
"Decoded NGAP PDUSessionResourceModifyListModRes IE error");
return false;
}
} else {
Logger::ngap().error(
"Decoded NGAP PDUSessionResourceModifyListModRes IE error");
return false;
}
} break;
default: {
Logger::ngap().error("Decoded NGAP Message PDU error");
return false;
}
}
}
return true;
}
//------------------------------------------------------------------------------
unsigned long PduSessionResourceModifyResponseMsg::getAmfUeNgapId() {
return amfUeNgapId.getAMF_UE_NGAP_ID();
}
//------------------------------------------------------------------------------
uint32_t PduSessionResourceModifyResponseMsg::getRanUeNgapId() {
return ranUeNgapId.getRanUeNgapId();
}
//------------------------------------------------------------------------------
bool PduSessionResourceModifyResponseMsg::
getPduSessionResourceModifyResponseList(
std::vector<PDUSessionResourceModifyResponseItem_t>& list) {
std::vector<PDUSessionResourceModifyItemModRes>
m_pduSessionResourceModifyItemModRes;
int num = 0;
pduSessionResourceModifyList.getPDUSessionResourceModifyListModRes(
m_pduSessionResourceModifyItemModRes);
for (int i = 0; i < m_pduSessionResourceModifyItemModRes.size(); i++) {
PDUSessionResourceModifyResponseItem_t response;
PDUSessionID m_pDUSessionID = {};
m_pduSessionResourceModifyItemModRes[i]
.getPDUSessionResourceModifyItemModRes(
m_pDUSessionID, response.pduSessionResourceModifyResponseTransfer);
m_pDUSessionID.getPDUSessionID(response.pduSessionId);
list.push_back(response);
}
return true;
}
} // namespace ngap
| 39.686275 | 105 | 0.651892 | [
"vector"
] |
1f310d088d0c7c54e88dcce5d569584e73eae489 | 5,373 | cpp | C++ | Code/Source/Tools/Browse3D/Mesh.cpp | christinazavou/Thea | f68293c4a4f5ddc3abda18e2e0b679bcf5163e93 | [
"BSD-3-Clause"
] | 77 | 2016-11-06T17:25:54.000Z | 2022-03-29T16:30:34.000Z | Code/Source/Tools/Browse3D/Mesh.cpp | christinazavou/Thea | f68293c4a4f5ddc3abda18e2e0b679bcf5163e93 | [
"BSD-3-Clause"
] | 1 | 2017-04-22T16:47:04.000Z | 2017-04-22T16:47:04.000Z | Code/Source/Tools/Browse3D/Mesh.cpp | christinazavou/Thea | f68293c4a4f5ddc3abda18e2e0b679bcf5163e93 | [
"BSD-3-Clause"
] | 20 | 2015-10-17T20:38:50.000Z | 2022-02-18T09:56:27.000Z | //============================================================================
//
// This file is part of the Thea toolkit.
//
// This software is distributed under the BSD license, as detailed in the
// accompanying LICENSE.txt file. Portions are derived from other works:
// their respective licenses and copyright information are reproduced in
// LICENSE.txt and/or in the relevant source files.
//
// Author: Siddhartha Chaudhuri
// First version: 2015
//
//============================================================================
#include "Mesh.hpp"
#include "../../Algorithms/CentroidN.hpp"
#include "../../Math.hpp"
namespace Browse3D {
Mesh::IndexVertexMap Mesh::index_to_vertex;
Mesh::IndexFaceMap Mesh::index_to_face;
MeshGroup *
Mesh::getAncestor(intx generations) const
{
if (generations < 1)
{
THEA_ERROR << getName() << ": Ancestor generation gap must be >= 1";
return nullptr;
}
MeshGroup * anc = parent;
if (!anc)
return anc;
while (--generations > 0 && anc->getParent())
anc = anc->getParent();
return anc;
}
bool
Mesh::hasAncestor(MeshGroup const * anc) const
{
MeshGroup const * a = parent;
while (a)
{
if (anc == a)
return true;
a = a->getParent();
}
return false;
}
void
Mesh::updateFeatures() const
{
if (valid_features)
return;
static size_t const NUM_BINS = 64;
features.resize(NUM_BINS + 1);
std::fill(features.begin(), features.end(), 0.0);
valid_features = true;
if (numVertices() <= 0)
{
THEA_CONSOLE << getName() << ": No vertices, zero feature vector";
return;
}
Vector3 centroid = Algorithms::CentroidN<Vertex, 3>::compute(verticesBegin(), verticesEnd());
Array<Real> all_dists;
for (VertexConstIterator vi = verticesBegin(); vi != verticesEnd(); ++vi)
all_dists.push_back((vi->getPosition() - centroid).norm());
Real dmax = *std::max_element(all_dists.begin(), all_dists.end());
if (dmax <= 1e-20)
{
THEA_CONSOLE << getName() << ": Coincident vertices, zero feature vector";
return;
}
double bin_size = dmax / NUM_BINS;
for (size_t i = 0; i < all_dists.size(); ++i)
{
int bin = Math::clamp((int)std::floor(all_dists[i] / bin_size), 0, (int)NUM_BINS - 1);
double bin_max = (bin + 1) * bin_size;
features[(size_t)bin] += (all_dists[i] / bin_max); // make it more discriminative by not binning 1
}
features.back() = dmax; // keep track of the overall scale of the mesh
// THEA_CONSOLE << getName() << ": Features: [" << seqStr(features.begin(), features.end()) << ']';
}
namespace MeshInternal {
bool
areSimilarFeatureVectors(Array<double> const & f0, intx nv0, Array<double> const & f1, intx nv1)
{
if (nv0 != nv1)
return false;
alwaysAssertM(f0.size() == f1.size(), "Feature vectors have different sizes");
// Compare histograms
double diff = 0;
for (size_t i = 0; i + 1 < f0.size(); ++i)
diff += std::fabs(f0[i] - f1[i]);
static double const HIST_THRESHOLD = 1e-2;
if (diff > HIST_THRESHOLD * nv0)
return false;
// Compare scales
static double const SCALE_THRESHOLD = 1e-2;
if (!Math::fuzzyEq(f0.back(), f1.back(), SCALE_THRESHOLD * (std::fabs(f0.back()) + 1)))
return false;
return true;
}
void
countVertices(MeshGroup const & mg, intx & num_vertices)
{
for (MeshGroup::MeshConstIterator mi = mg.meshesBegin(); mi != mg.meshesEnd(); ++mi)
num_vertices += (*mi)->numVertices();
for (MeshGroup::GroupConstIterator ci = mg.childrenBegin(); ci != mg.childrenEnd(); ++ci)
countVertices(**ci, num_vertices);
}
// A rather hacky way of forming a joint descriptor, suitable only for exact matches like we want here
void
accumGroupFeatures(MeshGroup const & mg, Array<double> & features)
{
for (MeshGroup::MeshConstIterator mi = mg.meshesBegin(); mi != mg.meshesEnd(); ++mi)
{
Array<double> const & mf = (*mi)->getFeatures();
if (features.empty())
features.resize(mf.size());
alwaysAssertM(mf.size() == features.size(), "Feature vectors have different sizes");
for (size_t j = 0; j < features.size(); ++j)
features[j] += mf[j];
}
for (MeshGroup::GroupConstIterator ci = mg.childrenBegin(); ci != mg.childrenEnd(); ++ci)
accumGroupFeatures(**ci, features);
}
} // namespace MeshInternal
bool
isSimilarTo(Mesh const & lhs, Mesh const & rhs)
{
if (&lhs == &rhs)
return true;
return MeshInternal::areSimilarFeatureVectors(lhs.getFeatures(), lhs.numVertices(), rhs.getFeatures(), rhs.numVertices());
}
bool
isSimilarTo(MeshGroup const & lhs, MeshGroup const & rhs)
{
using namespace MeshInternal;
if (&lhs == &rhs)
return true;
intx nv0 = 0, nv1 = 0;
countVertices(lhs, nv0);
countVertices(rhs, nv1);
if (nv0 != nv1)
return false;
Array<double> f0, f1;
accumGroupFeatures(lhs, f0);
accumGroupFeatures(rhs, f1);
return areSimilarFeatureVectors(f0, nv0, f1, nv1);
}
bool
isSimilarTo(Mesh const & lhs, MeshGroup const & rhs)
{
using namespace MeshInternal;
intx nv0 = lhs.numVertices();
intx nv1 = 0;
countVertices(rhs, nv1);
if (nv0 != nv1)
return false;
Array<double> const & f0 = lhs.getFeatures();
Array<double> f1;
accumGroupFeatures(rhs, f1);
return areSimilarFeatureVectors(f0, nv0, f1, nv1);
}
bool
isSimilarTo(MeshGroup const & lhs, Mesh const & rhs)
{
return isSimilarTo(rhs, lhs);
}
} // namespace Browse3D
| 24.646789 | 124 | 0.641727 | [
"mesh",
"vector"
] |
1f34abd90344959daf924f5565cc2121fd4af0d9 | 8,206 | cc | C++ | src/lib/tcp.cc | GeniusDai/cppev | 20c186f4572b2fb1cbfa3c81d0a8be346957f19d | [
"BSD-3-Clause"
] | 7 | 2022-01-19T11:17:53.000Z | 2022-02-28T14:14:55.000Z | src/lib/tcp.cc | GeniusDai/cppev | 20c186f4572b2fb1cbfa3c81d0a8be346957f19d | [
"BSD-3-Clause"
] | null | null | null | src/lib/tcp.cc | GeniusDai/cppev | 20c186f4572b2fb1cbfa3c81d0a8be346957f19d | [
"BSD-3-Clause"
] | 1 | 2022-01-27T02:40:18.000Z | 2022-01-27T02:40:18.000Z | #include "cppev/tcp.h"
namespace cppev
{
namespace tcp
{
// Idle function for callback
tcp_event_cb idle_handler = [](std::shared_ptr<nsocktcp>) -> void {};
tp_shared_data::tp_shared_data()
:
on_accept(idle_handler),
on_connect(idle_handler),
on_read_complete(idle_handler),
on_write_complete(idle_handler),
on_closed(idle_handler)
{}
event_loop *tp_shared_data::random_get_evlp()
{
std::random_device rd;
std::default_random_engine rde(rd());
std::uniform_int_distribution<int> dist(0, evls.size()-1);
return evls[dist(rde)];
}
event_loop *tp_shared_data::minloads_get_evlp()
{
int minloads = INT32_MAX;
event_loop *minloads_evp;
for (auto evp : evls)
{
// This is not thread safe but it's okay
if (evp->fd_loads() < minloads)
{
minloads_evp = evp;
minloads = evp->fd_loads();
}
}
return minloads_evp;
}
void async_write(std::shared_ptr<nsocktcp> iopt)
{
tp_shared_data *dp = static_cast<tp_shared_data *>(iopt->evlp()->data());
iopt->write_all(sysconfig::buffer_io_step);
if (0 == iopt->wbuf()->size())
{
dp->on_write_complete(iopt);
}
else
{
std::shared_ptr<nio> iop = std::dynamic_pointer_cast<nio>(iopt);
if (iop == nullptr)
{
throw_logic_error("dynamic_cast error");
}
iopt->evlp()->fd_remove(iop, false);
iopt->evlp()->fd_register(iop, fd_event::fd_writable);
}
}
void safely_close(std::shared_ptr<nsocktcp> iopt)
{
std::shared_ptr<cppev::nio> iop = std::dynamic_pointer_cast<cppev::nio>(iopt);
// epoll/kqueue will remove fd when it's closed
iopt->evlp()->fd_remove(iop, true, false);
iopt->close();
}
void iohandler::on_readable(std::shared_ptr<nio> iop)
{
std::shared_ptr<nsocktcp> iopt = std::dynamic_pointer_cast<nsocktcp>(iop);
if (iopt == nullptr)
{
throw_logic_error("dynamic_cast error");
}
tp_shared_data *dp = static_cast<tp_shared_data *>(iop->evlp()->data());
iopt->read_all(sysconfig::buffer_io_step);
dp->on_read_complete(iopt);
iopt->rbuf()->clear();
if (iopt->eof() || iopt->is_reset())
{
dp->on_closed(iopt);
iop->evlp()->fd_remove(iop, true);
}
}
void iohandler::on_writable(std::shared_ptr<nio> iop)
{
std::shared_ptr<nsocktcp> iopt = std::dynamic_pointer_cast<nsocktcp>(iop);
if (iopt.get() == nullptr)
{
throw_logic_error("dynamic_cast error");
}
tp_shared_data *dp = static_cast<tp_shared_data *>(iop->evlp()->data());
iopt->write_all(sysconfig::buffer_io_step);
if (0 == iopt->wbuf()->size())
{
iop->evlp()->fd_remove(iop, false);
dp->on_write_complete(iopt);
if (!iop->is_closed())
{
iop->evlp()->fd_register(iop, fd_event::fd_readable);
}
}
if (iopt->eop() || iopt->is_reset())
{
dp->on_closed(iopt);
iop->evlp()->fd_remove(iop, true);
}
}
void acceptor::listen(int port, family f, const char *ip)
{
sock_ = nio_factory::get_nsocktcp(f);
sock_->listen(port, ip);
}
void acceptor::on_readable(std::shared_ptr<nio> iop)
{
std::shared_ptr<nsocktcp> iopt = std::dynamic_pointer_cast<nsocktcp>(iop);
if (iopt.get() == nullptr)
{
throw_logic_error("dynamic_cast error");
}
std::vector<std::shared_ptr<nsocktcp> > conns = iopt->accept();
tp_shared_data *d = static_cast<tp_shared_data *>(iop->evlp()->data());
for (auto &p : conns)
{
log::info << "new fd " << p->fd() << " accepted" << log::endl;
event_loop *io_evlp = d->minloads_get_evlp();
io_evlp->fd_register(std::dynamic_pointer_cast<nio>(p),
fd_event::fd_writable, acceptor::on_writable, true);
}
}
void acceptor::on_writable(std::shared_ptr<nio> iop)
{
std::shared_ptr<nsocktcp> iopt = std::dynamic_pointer_cast<nsocktcp>(iop);
if (iopt.get() == nullptr)
{
throw_logic_error("dynamic_cast error");
}
tp_shared_data *d = static_cast<tp_shared_data *>(iop->evlp()->data());
iop->evlp()->fd_remove(iop, true);
// The sequence CANNOT be changed, since on_accept may call async_write
iop->evlp()->fd_register(iop, fd_event::fd_writable, iohandler::on_writable, false);
d->on_accept(iopt);
iop->evlp()->fd_register(iop, fd_event::fd_readable, iohandler::on_readable, true);
}
void acceptor::run_impl()
{
evp_->fd_register(std::dynamic_pointer_cast<nio>(sock_),
fd_event::fd_readable, acceptor::on_readable, true);
evp_->loop();
}
void connector::add(std::string ip, int port, family f, int t)
{
tp_shared_data *d = static_cast<tp_shared_data *>(evp_->data());
auto h = std::make_tuple<>(ip, port, f);
if (d->hosts.count(h))
{
d->hosts[h] += t;
}
else
{
d->hosts[h] = t;
}
wrp_->wbuf()->put("0");
wrp_->write_all(1);
}
void connector::on_readable(std::shared_ptr<nio> iop)
{
nstream *iops = dynamic_cast<nstream *>(iop.get());
if (iops == nullptr)
{
throw_logic_error("dynamic_cast error");
}
tp_shared_data *d = static_cast<tp_shared_data *>(iop->evlp()->data());
iops->read_all(1);
for (auto iter = d->hosts.begin(); iter != d->hosts.end(); )
{
for (int i = 0; i < iter->second; ++i)
{
std::shared_ptr<nsocktcp> sock =
nio_factory::get_nsocktcp(std::get<2>(iter->first));
sock->connect(std::get<0>(iter->first), std::get<1>(iter->first));
event_loop *io_evlp = d->minloads_get_evlp();
io_evlp->fd_register(std::dynamic_pointer_cast<nio>(sock),
fd_event::fd_writable, connector::on_writable, true);
}
iter = d->hosts.erase(iter);
}
}
void connector::on_writable(std::shared_ptr<nio> iop)
{
std::shared_ptr<nsocktcp> iopt = std::dynamic_pointer_cast<nsocktcp>(iop);
if (iopt.get() == nullptr)
{
throw_logic_error("dynamic_cast error");
}
tp_shared_data *d = static_cast<tp_shared_data *>(iop->evlp()->data());
iop->evlp()->fd_remove(iop, true); // remove previous callback
if (!iopt->check_connect())
{
std::tuple<std::string, int, family> h = iopt->connpeer();
log::error << "connect failed with " << std::get<0>(h)
<< " " << std::get<1>(h) << log::endl;
if (d->failures.count(h))
{
d->failures[h] += 1;
}
else
{
d->failures[h] = 1;
}
return;
}
// The sequence CANNOT be changed since on_connect may call aysnc_write
iop->evlp()->fd_register(iop, fd_event::fd_writable, iohandler::on_writable, false);
d->on_connect(iopt);
iop->evlp()->fd_register(iop, fd_event::fd_readable, iohandler::on_readable, true);
}
void connector::run_impl()
{
evp_->fd_register(std::dynamic_pointer_cast<nio>(rdp_),
fd_event::fd_readable, connector::on_readable, true);
evp_->loop();
}
tcp_server::tcp_server(int thr_num)
{
data_ = std::shared_ptr<tp_shared_data>(new tp_shared_data);
tp_ = std::shared_ptr<thread_pool<iohandler, tp_shared_data *> >
(new thread_pool<iohandler, tp_shared_data *>(thr_num, data_.get()));
for (int i = 0; i < tp_->size(); ++i)
{
data_->evls.push_back((*tp_)[i]->evp_.get());
}
acpt_ = std::shared_ptr<acceptor>(new acceptor(data_.get()));
}
void tcp_server::run()
{
utils::ignore_signal(SIGPIPE);
tp_->run();
acpt_->run();
tp_->join();
acpt_->join();
}
tcp_client::tcp_client(int thr_num)
{
data_ = std::shared_ptr<tp_shared_data>(new tp_shared_data);
tp_ = std::shared_ptr<thread_pool<iohandler, tp_shared_data *> >
(new thread_pool<iohandler, tp_shared_data *>(thr_num, data_.get()));
for (int i = 0; i < tp_->size(); ++i)
{
data_->evls.push_back((*tp_)[i]->evp_.get());
}
cont_ = std::shared_ptr<connector>(new connector(data_.get()));
}
void tcp_client::run()
{
utils::ignore_signal(SIGPIPE);
tp_->run();
cont_->run();
tp_->join();
cont_->join();
}
} // namespace tcp
} // namespace cppev
| 28.792982 | 88 | 0.611382 | [
"vector"
] |
1f37c3b5cbfec2b1978fe0320b11291a37f0a9f3 | 2,340 | cpp | C++ | test/test_1.cpp | active911/fastcache | a845449b54bee4555ed957ccfe373c34333389cb | [
"Apache-2.0"
] | 9 | 2016-03-16T06:18:02.000Z | 2021-02-07T20:59:19.000Z | test/test_1.cpp | iamrameshkumar/fastcache | a845449b54bee4555ed957ccfe373c34333389cb | [
"Apache-2.0"
] | null | null | null | test/test_1.cpp | iamrameshkumar/fastcache | a845449b54bee4555ed957ccfe373c34333389cb | [
"Apache-2.0"
] | 6 | 2016-08-29T23:55:09.000Z | 2020-10-11T18:43:03.000Z |
// Test1
// Prove that the mutexes are working by causing the cache to block while reading.
// Read from the cache using 2 threads and observe the delay as they wait for each other.
// Slow down the cache
#define FASTCACHE_SLOW
// Run with 3 threads
#define THREAD_COUNT 3
// Clock source
#define CLOCKSRC CLOCK_MONOTONIC_RAW
#include <iostream>
#include <string>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/detail/atomic_count.hpp>
#include "../Fastcache.h"
#include "TestClass.h"
#include <time.h>
using namespace std;
using namespace active911;
using boost::shared_ptr;
using boost::thread;
// Counter for thread runloop
boost::detail::atomic_count run(1);
// The cache
Fastcache<string, TestClass>cache;
// Timer
struct timespec start;
struct timespec end;
void thread_function(int thread_number) {
// Create a cache object
{
shared_ptr<TestClass>obj=shared_ptr<TestClass>(new TestClass());
// cout << "Thread " << thread_number << " BEGIN storing data" << endl;
cout << "w" << flush;
cache.set("MyDataKey", obj);
// cout << "Thread " << thread_number << " END storing data" << endl;
cout << "W" << flush;
// cout << "Thread " << thread_number << " BEGIN reading data" << endl;
cout << "r" << flush;
shared_ptr<TestClass>read=cache.get("MyDataKey");
// cout << "Thread " << thread_number << " END reading data" << endl;
cout << "R" << flush;
}
while(run) { sleep(1); }
}
int main(int argc, char **argv) {
// Setup cout
cout.precision(5);
// Start test
cout << "Testing locks..." << flush;
clock_gettime(CLOCKSRC, &start);
// Start several threads, each accessing the cache
vector<shared_ptr<boost::thread> > threads;
for(int n=0; n<THREAD_COUNT; n++){
threads.push_back(shared_ptr<boost::thread>(new boost::thread(&thread_function,n)));
}
// Join the threads
--run;
for(int n=0; n<THREAD_COUNT; n++){
threads[n]->join();
}
// End the test
clock_gettime(CLOCKSRC, &end);
double start_time=(double)start.tv_sec+((double)start.tv_nsec/1000000000.0);
double end_time=(double)end.tv_sec+((double)end.tv_nsec/1000000000.0);
double elapsed_time=end_time-start_time;
if(elapsed_time > (THREAD_COUNT*2)-1) {
cout << "...OK";
} else {
cout << "...FAIL";
}
cout << " (" << elapsed_time << " sec)" << endl;
return 0;
}
| 20 | 89 | 0.673932 | [
"object",
"vector"
] |
1f3950b2a17c6d963d6dbf79b9875d8282f44af0 | 1,383 | hpp | C++ | source/core/application.hpp | GanbaraKnight/light-field-renderer | 5b161a32ded80078f564d9177e12d19c44c6003b | [
"MIT"
] | null | null | null | source/core/application.hpp | GanbaraKnight/light-field-renderer | 5b161a32ded80078f564d9177e12d19c44c6003b | [
"MIT"
] | null | null | null | source/core/application.hpp | GanbaraKnight/light-field-renderer | 5b161a32ded80078f564d9177e12d19c44c6003b | [
"MIT"
] | null | null | null | #include <nanogui/nanogui.h>
#include "config.hpp"
class LightFieldRenderer;
class Application : public nanogui::Screen
{
public:
Application();
virtual bool keyboard_event(int key, int scancode, int action, int modifiers);
virtual void draw(NVGcontext *ctx);
private:
LightFieldRenderer *light_field_renderer;
std::shared_ptr<Config> cfg;
struct PropertySlider
{
PropertySlider(nanogui::Widget* window, Config::Property* p, const std::string &name,
const std::string &unit, size_t precision);
nanogui::Slider* slider;
nanogui::TextBox* text_box;
Config::Property* const prop;
float last_value;
size_t precision;
bool initiated = false;
void updateValue();
};
struct PropertyBoxRow
{
PropertyBoxRow(nanogui::Widget* window, const std::vector<Config::Property*> &properties,
const std::string &name, const std::string &unit, size_t precision, float step,
std::string tooltip = "", size_t total_width = 270);
std::vector<Config::Property*> properties;
std::vector<nanogui::FloatBox<float>*> float_boxes;
std::vector<float> last_values;
void updateValues();
};
std::vector<PropertySlider> sliders;
std::vector<PropertyBoxRow> float_box_rows;
}; | 27.117647 | 102 | 0.639913 | [
"vector"
] |
1f40b370271c61cb3c9d21be3960f5c0d4d84b50 | 1,197 | cpp | C++ | N1790-Check-if-One-String-Swap-Can-Make-Strings-Equal/solution1.cpp | loyio/leetcode | 366393c29a434a621592ef6674a45795a3086184 | [
"CC0-1.0"
] | null | null | null | N1790-Check-if-One-String-Swap-Can-Make-Strings-Equal/solution1.cpp | loyio/leetcode | 366393c29a434a621592ef6674a45795a3086184 | [
"CC0-1.0"
] | null | null | null | N1790-Check-if-One-String-Swap-Can-Make-Strings-Equal/solution1.cpp | loyio/leetcode | 366393c29a434a621592ef6674a45795a3086184 | [
"CC0-1.0"
] | 2 | 2022-01-25T05:31:31.000Z | 2022-02-26T07:22:23.000Z | //
// main.cpp
// LeetCode-Solution
//
// Created by Loyio Hex on 3/11/22.
//
#include <iostream>
#include <chrono>
#include <vector>
using namespace std;
using namespace std::chrono;
class Solution {
public:
bool areAlmostEqual(string s1, string s2) {
if (s1.size() != s2.size()){
return false;
}
int cnt = 0, m = -1, n = -1;
for (int i = 0, j = 0; i < s1.size(); ++i, ++j) {
if (s1[i] != s2[j]){
cnt++;
if (m == -1) m = i;
if (n == -1 && m != i) n = j;
}
}
if (cnt == 0) return true;
if (cnt == 2 && s1[m] == s2[n] && s2[m] == s1[n]){
return true;
}
return false;
}
};
int main(int argc, const char * argv[]) {
auto start = high_resolution_clock::now();
// Main Start
string s1 = "bank";
string s2 = "kanb";
Solution solution;
cout << solution.areAlmostEqual(s1, s2);
// Main End
auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop - start);
cout << endl << "Runnig time : " << duration.count() << "ms;" << endl;
return 0;
}
| 22.166667 | 74 | 0.487886 | [
"vector"
] |
1f4f1e12bc29f827cb8b19d9668d432032df40e2 | 1,599 | cpp | C++ | aws-cpp-sdk-config/source/model/AggregateConformancePackComplianceSummary.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-config/source/model/AggregateConformancePackComplianceSummary.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-config/source/model/AggregateConformancePackComplianceSummary.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/config/model/AggregateConformancePackComplianceSummary.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace ConfigService
{
namespace Model
{
AggregateConformancePackComplianceSummary::AggregateConformancePackComplianceSummary() :
m_complianceSummaryHasBeenSet(false),
m_groupNameHasBeenSet(false)
{
}
AggregateConformancePackComplianceSummary::AggregateConformancePackComplianceSummary(JsonView jsonValue) :
m_complianceSummaryHasBeenSet(false),
m_groupNameHasBeenSet(false)
{
*this = jsonValue;
}
AggregateConformancePackComplianceSummary& AggregateConformancePackComplianceSummary::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("ComplianceSummary"))
{
m_complianceSummary = jsonValue.GetObject("ComplianceSummary");
m_complianceSummaryHasBeenSet = true;
}
if(jsonValue.ValueExists("GroupName"))
{
m_groupName = jsonValue.GetString("GroupName");
m_groupNameHasBeenSet = true;
}
return *this;
}
JsonValue AggregateConformancePackComplianceSummary::Jsonize() const
{
JsonValue payload;
if(m_complianceSummaryHasBeenSet)
{
payload.WithObject("ComplianceSummary", m_complianceSummary.Jsonize());
}
if(m_groupNameHasBeenSet)
{
payload.WithString("GroupName", m_groupName);
}
return payload;
}
} // namespace Model
} // namespace ConfigService
} // namespace Aws
| 21.32 | 116 | 0.771732 | [
"model"
] |
1f5ae327f22db7f036224a27e6feb35e98fd4b1b | 52,069 | cpp | C++ | src/search_engine/relja_retrival/external/KMCode_relja/homography/homography.cpp | alexanderwilkinson/visenew | 8e494355b0f88466c0abb4b8f3bfecc150b91111 | [
"ImageMagick",
"BSD-2-Clause"
] | 43 | 2017-07-06T23:44:39.000Z | 2022-03-25T06:53:29.000Z | src/search_engine/relja_retrival/external/KMCode_relja/homography/homography.cpp | alexanderwilkinson/visenew | 8e494355b0f88466c0abb4b8f3bfecc150b91111 | [
"ImageMagick",
"BSD-2-Clause"
] | 2 | 2018-11-09T03:52:14.000Z | 2020-03-25T14:08:33.000Z | src/search_engine/relja_retrival/external/KMCode_relja/homography/homography.cpp | alexanderwilkinson/visenew | 8e494355b0f88466c0abb4b8f3bfecc150b91111 | [
"ImageMagick",
"BSD-2-Clause"
] | 9 | 2017-07-27T10:55:55.000Z | 2020-12-15T13:42:43.000Z | #include "homography.h"
void convertEllips(float a, float b, float c, float &scale, float &m11, float &m12, float &m21, float &m22){
Matrix U(2,2),Vi,V,D;
U(1,1)=a;
U(2,1)=b;U(1,2)=b;
U(2,2)=c;
U.svd(Vi,D,V);
D(1,1)=(1.0/sqrt(D(1,1)));
D(2,2)=(1.0/sqrt(D(2,2)));
scale=sqrt(D(2,2)*D(1,1));
D.tabMat[2][2]/=scale;
D.tabMat[1][1]/=scale;
U=V*D*V.transpose();
m11=U(1,1);
m12=U(1,2);
m21=U(2,1);
m22=U(2,2);
}
void loadVibesCorners(const char* points1, vector<CornerDescriptor*>& cor1) {
CornerDescriptor* cor;
ifstream input1(points1);
if (!input1)return;
float cor_nb1, size;
float x, y, a, b, c;
input1 >> x;//cout <<x<< endl;
input1 >> cor_nb1; //cout<< x<< endl;getchar();
if (cor_nb1 == 0)return;
float scale, m11, m12, m21, m22;
do {
cor = new CornerDescriptor();
input1 >> x; input1 >> y; input1 >> a; input1 >> b; input1 >> c;
//cout << a << " " << b << " "<< c << endl;
convertEllips(a, b, c, scale, m11, m12, m21, m22);
//cout << m11 <<" "<< m12 << " "<< m21 << " " << m22<< endl;getchar();
cor->setX_Y(x, y); cor->setCornerScale(scale);
cor->setMi(m11, m12, m21, m22);
cor1.push_back(cor);
} while (!input1.eof());
delete cor1[(int)cor1.size() - 1];
//cor1.erase((std::vector<CornerDescriptor*>::iterator) & cor1[(int)cor1.size() - 1]);
cor1.erase(cor1.begin() + (cor1.size() - 1));
if ((int)cor_nb1 != (int)cor1.size()) {
cout << "warning:" << endl << "in header: " << cor_nb1 << ", in file: " << cor1.size() << endl;
}
}
void getAffMat(CornerDescriptor * cor, Matrix *H, Matrix &AFF);
/*************computes homography correspondence**************/
void getHPoint(float x_in, float y_in, Matrix *H, float &x_out, float &y_out){
x_out = H->tabMat[1][1]*x_in + H->tabMat[1][2]*y_in +H->tabMat[1][3];
y_out = H->tabMat[2][1]*x_in + H->tabMat[2][2]*y_in +H->tabMat[2][3];
float t= H->tabMat[3][1]*x_in + H->tabMat[3][2]*y_in +H->tabMat[3][3];
x_out /=t;
y_out /=t;
}
int checkIfCorrect(float x, float y, float scale, CornerDescriptor *cd,
float dist_max, float orig_scale, float scale_error){
float dist_x=cd->getX()-x;
float dist_y=cd->getY()-y;
float dist=sqrt(dist_x*dist_x+dist_y*dist_y);
float sc = scale/(cd->getCornerScale());
if(dist<dist_max && (fabs(sc-orig_scale)/orig_scale) < scale_error)
return 1;
else
return 0;
}
/*********** returns angle and scale from homography**************/
void getScaleAngle(Matrix *H, float &scale, float &angle){
float x3=(100*H->tabMat[1][1]+H->tabMat[1][3])/(100*H->tabMat[3][1]+H->tabMat[3][3]);
float y3=(100*H->tabMat[2][1]+H->tabMat[2][3])/(100*H->tabMat[3][1]+H->tabMat[3][3]);
float x2=H->tabMat[1][3]/H->tabMat[3][3];
float y2=H->tabMat[2][3]/H->tabMat[3][3];
float dx=x3-x2;
float dy=y3-y2;
scale=fabs(100.0/(sqrt(dx*dx+dy*dy)));
angle=atan2(dy,dx);
}
/*********** returns angle and scale from homography**************/
void getScaleAngle( float x, float y, Matrix *H, float &scale, float &angle){
float x2=x+10;
float y2=y;
float xH,yH,x2H,y2H;
getHPoint(x,y,H,xH,yH);
getHPoint(x2,y2,H,x2H,y2H);
float dxH=x2H-xH;
float dyH=y2H-yH;
scale=(10.0/(sqrt(dxH*dxH+dyH*dyH)));
angle=atan2(dyH,dxH);
}
/*********** returns angle and scale from homography**************/
void getAngle(CornerDescriptor* cor1, Matrix *H, float &angle){
float x,y,x2,y2;
float dx=2*cor1->getCornerScale();
getHPoint(cor1->getX(), cor1->getY(), H, x, y);
getHPoint(cor1->getX()+dx, cor1->getY(), H, x2, y2);
float dx2=x2-x;
float dy2=y2-y;
angle=atan2(dy2,dx2);
}
/**************check if angle is correct******************************/
int checkAngle(CornerDescriptor* cor1, CornerDescriptor* cor2, float orig_angle, float max_error){
int score=0;
float da=cor2->getAngle()-cor1->getAngle();
if(da<(-M_PI))da+=M_2PI;
if(da>(M_PI))da-=M_2PI;
if(fabs(da-orig_angle)<max_error)score=1;//max_error=0.17
return score;
}
/************check if matches agree with homography******************/
int checkHomog(CornerDescriptor* cor1,CornerDescriptor* cor2,Matrix *H, float dist_max, float &dist){
float x,y;//cout << "OK"<< endl;
getHPoint(cor1->getX(),cor1->getY(),H,x,y);
float dist_x=cor2->getX()-x;
float dist_y=cor2->getY()-y;
dist=sqrt(dist_x*dist_x+dist_y*dist_y);
if(dist<dist_max)return 1;
else return 0;
}
/************check if is near to epipolar line******************/
int checkEpip(CornerDescriptor* cor1,CornerDescriptor* cor2,Matrix *F,float dist_max, float &dist){
float *point = new float[3];
float *abc = new float[3];
abc[0]=0;abc[1]=0;abc[2]=0;
point[0]=cor1->getX();
point[1]=cor1->getY();
point[2]=1;
for (int j=0;j<3;j++){
for (int i=0;i<3;i++){
abc[j]+=F->tabMat[j+1][i+1]*point[i];
}
}
dist=fabs((abc[0]*cor2->getX()+abc[1]*cor2->getY()+abc[2])/sqrt(abc[0]*abc[0]+abc[1]*abc[1]));
delete [] point; delete [] abc;
// cout << point[0] << " " <<point[1] << " " << cor2->getX() << " " << cor2->getY();
// cout << " dist "<<dist <<" a "<< abc[0] <<" b "<<abc[1]<< " c "<<abc[2]<< endl;
if(dist<dist_max)return 1;
else return 0;
}
void removeFloatMatches(vector<CornerDescriptor*> &cor1,
vector<CornerDescriptor*> &cor2){
for(unsigned int i=0;i<cor2.size()-1;i++){
for(unsigned int j=i+1;j<cor2.size();j++){
if(cor2[i]==cor2[j] || cor1[i]==cor1[j]){
//cor2.erase((std::vector<CornerDescriptor*>::iterator)&cor2[j]);
//cor1.erase((std::vector<CornerDescriptor*>::iterator)&cor1[j]);
cor1.erase(cor1.begin() + j);
cor2.erase(cor2.begin() + j);
j--;
}
}
}
}
void removeOutLiers(vector<CornerDescriptor*> &cor1, Matrix *H, float width, float height, float margin){
float x,y;
for(unsigned int c1=0;c1<cor1.size();c1++){
getHPoint(cor1[c1]->getX(),cor1[c1]->getY(),H,x,y);
if(x<margin || y<margin ||
x>(width-margin) || y>(height-margin)){
//cor1.erase((std::vector<CornerDescriptor*>::iterator)&cor1[c1]);
cor1.erase(cor1.begin() + c1);
c1--;
}
}
}
/**************check angles, removes wrong angles, computes mean error*****************/
float checkAngleByHomography(vector<CornerDescriptor*> &cor1,
vector<CornerDescriptor*> &cor2,
Matrix *H,float max_angle_error){
if(cor1.size()!=cor2.size()){cout << " different list size " << endl;return 0.0;}
float scale,orig_angle;
float da;
float sum=0;
for(unsigned int c=0;c<cor1.size();c++){
getScaleAngle(cor1[c]->getX(),cor1[c]->getY(),H, scale , orig_angle);
da=cor2[c]->getAngle()-cor1[c]->getAngle();
if(da<(-M_PI))da+=M_2PI;
if(da>(M_PI))da-=M_2PI;
sum+=fabs(da-orig_angle);
if(fabs(da-orig_angle) > max_angle_error){
//cor2.erase((std::vector<CornerDescriptor*>::iterator)&cor2[c]);
//cor1.erase((std::vector<CornerDescriptor*>::iterator)&cor1[c]);
cor1.erase(cor1.begin() + c);
cor2.erase(cor2.begin() + c);
c--;
}
}
sum/=cor1.size();
return sum;
}
void checkScaleByHomography(vector<CornerDescriptor *> &cor1, vector<CornerDescriptor *> &cor2, Matrix *H, float max_scale_error){
if(cor1.size()!=cor2.size()){cout << " different list size " << endl;return;}
float sc;
float c1_scale;
float orig_scale,orig_angle;
float scale_error=0;
for(unsigned int c1=0;c1<cor1.size();c1++){
cout << "\r " << c1 << " of "<< cor1.size() << flush;
getScaleAngle(cor1[c1]->getX(),cor1[c1]->getY(),H,orig_scale, orig_angle);
c1_scale=cor1[c1]->getCornerScale();
sc = (cor1[c1]->getCornerScale())/(cor2[c1]->getCornerScale());
scale_error=sc/orig_scale;
scale_error=scale_error<1?scale_error:(1.0/scale_error);
scale_error=1-scale_error;
if(scale_error > max_scale_error){
//cor2.erase((std::vector<CornerDescriptor*>::iterator)&cor2[c1]);
//cor1.erase((std::vector<CornerDescriptor*>::iterator)&cor1[c1]);
cor1.erase(cor1.begin() + c1);
cor2.erase(cor2.begin() + c1);
c1--;
}
}
}
void checkPointsByEpipolar(vector<CornerDescriptor *> &cor1, vector<CornerDescriptor *> &cor2,
Matrix *F, float max_dist){
float dist;
if(cor1.size()!=cor2.size()){cout << " different list size " << endl;return;}
for(unsigned int c1=0;c1<cor1.size();c1++){
if(!checkEpip(cor1[c1],cor2[c1],F,max_dist,dist)){
//cor1.erase((std::vector<CornerDescriptor*>::iterator)&cor1[c1]);
//cor2.erase((std::vector<CornerDescriptor*>::iterator)&cor2[c1]);
cor1.erase(cor1.begin() + c1);
cor2.erase(cor2.begin() + c1);
c1--;
}
}
}
void checkPointsByHomography(vector<CornerDescriptor *> &cor1, vector<CornerDescriptor *> &cor2,
Matrix *F, float max_dist){
float dist;
if(cor1.size()!=cor2.size()){cout << " different list size " << endl;return;}
for(unsigned int c1=0;c1<cor1.size();c1++){
if(!checkHomog(cor1[c1],cor2[c1],F,max_dist,dist)){
//cor1.erase((std::vector<CornerDescriptor*>::iterator)&cor1[c1]);
//cor2.erase((std::vector<CornerDescriptor*>::iterator)&cor2[c1]);
cor1.erase(cor1.begin() + c1);
cor2.erase(cor2.begin() + c1);
c1--;
}
}
}
void matchPointsByHomography(vector<CornerDescriptor *> &cor1, vector<CornerDescriptor *> &cor2,
vector<CornerDescriptor *> &cor1_tmp, vector<CornerDescriptor *> &cor2_tmp,
Matrix *H, float max_dist){
float x,y;
float dist,dist_x,dist_y;
unsigned int size1=cor1.size();
unsigned int size2=cor2.size();
max_dist=max_dist*max_dist;
for(unsigned int c1=0;c1<size1;c1++){
cout << "\r " << c1 << " of "<< size1 << flush;
getHPoint(cor1[c1]->getX(),cor1[c1]->getY(),H,x,y);
//cout << cor1[c1]->getX()<< " " <<cor1[c1]->getY()<< " to "<<x<< " " << y<< endl;
//getchar();
for(unsigned int c2=0;c2<size2;c2++){
dist_x=cor2[c2]->getX()-x;
dist_y=cor2[c2]->getY()-y;
dist=(dist_x*dist_x+dist_y*dist_y);
if(dist<max_dist){
cor1_tmp.push_back(cor1[c1]);
cor2_tmp.push_back(cor2[c2]);
}
}
}
}
/************COMPUTES HOMOGRAPHY MATRIX******************/
void computeHomography2(vector<CornerDescriptor *> cor1,
vector<CornerDescriptor *> cor2, Matrix *H){
int nb_of_Tokens=cor1.size();
Matrix *A = new Matrix(nb_of_Tokens*2,8);
Matrix *B = new Matrix(nb_of_Tokens*2,1);
int row=0;
for(int i=0;i<nb_of_Tokens;i++){
row=2*i+1;
A->tabMat[row][1]=cor1[i]->getX();
A->tabMat[row][2]=cor1[i]->getY();
A->tabMat[row][3]=1.0;
A->tabMat[row][4]=0.0;
A->tabMat[row][5]=0.0;
A->tabMat[row][6]=0.0;
A->tabMat[row][7]=-(cor1[i]->getX()*cor2[i]->getX());
A->tabMat[row][8]=-(cor1[i]->getY()*cor2[i]->getX());
B->tabMat[row][1]=cor2[i]->getX();
row++;
A->tabMat[row][1]=0.0;
A->tabMat[row][2]=0.0;
A->tabMat[row][3]=0.0;
A->tabMat[row][4]=cor1[i]->getX();
A->tabMat[row][5]=cor1[i]->getY();
A->tabMat[row][6]=1.0;
A->tabMat[row][7]=-(cor1[i]->getX()*cor2[i]->getX());
A->tabMat[row][8]=-(cor1[i]->getY()*cor2[i]->getX());
B->tabMat[row][1]=cor2[i]->getY();
}
//Eigenvalues and eigenvectors
Matrix U,W,V;
A->svd(U,W,V);
float val;
float *vec = new float[9];
//Di-inverse * U-transpose * B
for(int nb=1; nb<9; nb++){
val=0;
for(int i=1; i<=row; i++)
val+=(U.tabMat[i][nb]*B->tabMat[i][1]);
vec[nb]=val/W(nb,nb);
}
//V*vec
float *X = new float[10];
for(int j=1; j<9; j++){
val=0;
for(int i=1; i<9; i++)
val+=(V.tabMat[j][i]*vec[i]);
X[j]=val;
}
X[9]=1;
for(int j=1,k=0;j<=3;j++,k+=3)
for(int i=1;i<=3;i++)
H->tabMat[j][i]=X[k+i]; //write the homography matrix
delete []vec; delete []X;//delete &U;delete &V;delete &W;
delete A, delete B;
}
/************COMPUTES HOMOGRAPHY MATRIX******************/
void computeHomography(vector<CornerDescriptor *> cor1,
vector<CornerDescriptor *> cor2, Matrix *H){
int nb_of_Tokens=cor1.size();
Matrix *A = new Matrix(nb_of_Tokens*2,9);
int row=0;
for(int i=0;i<nb_of_Tokens;i++){
row=2*i+1;
A->tabMat[row][1]=cor1[i]->getX();
A->tabMat[row][2]=cor1[i]->getY();
A->tabMat[row][3]=1.0;
A->tabMat[row][4]=0.0;
A->tabMat[row][5]=0.0;
A->tabMat[row][6]=0.0;
A->tabMat[row][7]=-(cor1[i]->getX()*cor2[i]->getX());
A->tabMat[row][8]=-(cor1[i]->getY()*cor2[i]->getX());
A->tabMat[row][9]=-cor2[i]->getX();
row++;
A->tabMat[row][1]=0.0;
A->tabMat[row][2]=0.0;
A->tabMat[row][3]=0.0;
A->tabMat[row][4]=cor1[i]->getX();
A->tabMat[row][5]=cor1[i]->getY();
A->tabMat[row][6]=1.0;
A->tabMat[row][7]=-(cor1[i]->getX()*cor2[i]->getY());
A->tabMat[row][8]=-(cor1[i]->getY()*cor2[i]->getY());
A->tabMat[row][9]=-cor2[i]->getY();
}
//Eigenvalues and eigenvectors
Matrix U,W,V;
A->svd(U,W,V);
// cout << "OK"<< U << W << V;
for(int j=1,k=0;j<=3;j++,k+=3)
for(int i=1;i<=3;i++)
H->tabMat[j][i]=V.tabMat[i+k][9]/V.tabMat[9][9]; //write the homography matrix
delete A;
}
/************COMPUTES HOMOGRAPHY MATRIX******************/
void computeAffine(vector<CornerDescriptor *> cor1,
vector<CornerDescriptor *> cor2, Matrix *AFF){
int nb_of_Tokens=cor1.size();
Matrix *A = new Matrix(nb_of_Tokens*2,7);
int row=0;
for(int i=0;i<nb_of_Tokens;i++){
row=2*i+1;
A->tabMat[row][1]=cor1[i]->getX();
A->tabMat[row][2]=cor1[i]->getY();
A->tabMat[row][3]=1.0;
A->tabMat[row][4]=0.0;
A->tabMat[row][5]=0.0;
A->tabMat[row][6]=0.0;
A->tabMat[row][7]=-cor2[i]->getX();
row++;
A->tabMat[row][1]=0.0;
A->tabMat[row][2]=0.0;
A->tabMat[row][3]=0.0;
A->tabMat[row][4]=cor1[i]->getX();
A->tabMat[row][5]=cor1[i]->getY();
A->tabMat[row][6]=1.0;
A->tabMat[row][7]=-cor2[i]->getY();
}
//Eigenvalues and eigenvectors
Matrix U,W,V;
A->svd(U,W,V);
for(int j=1,k=0;j<=2;j++,k+=3)
for(int i=1;i<=2;i++)
AFF->tabMat[j][i]=V.tabMat[i+k][7]/V.tabMat[7][7]; //write the homography matrix
// AFF->tabMat[3][1]=0;
//AFF->tabMat[3][2]=0;
// AFF->tabMat[3][3]=1;
delete A;
}
/*
*Compute the fundamental matrix
*/
void computeEpipolarMatrix(vector<CornerDescriptor *> cor1, vector<CornerDescriptor *> cor2, Matrix *F){
int nb_of_Tokens = cor1.size();
Matrix *matA = new Matrix(nb_of_Tokens,9);
Matrix *matAT = new Matrix(9,nb_of_Tokens);
Matrix *a = new Matrix(9,9);
Matrix *leftTokensXY =new Matrix(3,nb_of_Tokens);
Matrix *rightTokensXY =new Matrix(3,nb_of_Tokens);
for(int nb=1; nb<=nb_of_Tokens;nb++){
leftTokensXY->tabMat[1][nb]=cor1[nb-1]->getX();
leftTokensXY->tabMat[2][nb]=cor1[nb-1]->getY();
leftTokensXY->tabMat[3][nb]=1;
rightTokensXY->tabMat[1][nb]=cor2[nb-1]->getX();
rightTokensXY->tabMat[2][nb]=cor2[nb-1]->getY();
rightTokensXY->tabMat[3][nb]=1;
}
// A = TOKENS_LEFT * TOKENS_RIGHT
for(int nb=1; nb<=nb_of_Tokens;nb++){
for(int j=1,k=1; j<=3; j++){
for(int i=1; i<=3; i++,k++){
matA->tabMat[nb][k] = leftTokensXY->tabMat[j][nb] * rightTokensXY->tabMat[i][nb];
}
}
}
// A_TRANSPOSE
for(int nb=1; nb<= nb_of_Tokens; nb++){
for(int i=1; i<=9; i++){
matAT->tabMat[i][nb] = matA->tabMat[nb][i];
}
}
//a = A_TRANSPOSE * A
for(int j=1; j<=9; j++){
for(int i=1; i<=9; i++){
for(int nb=1; nb<= nb_of_Tokens; nb++){
a->tabMat[j][i]+=matAT->tabMat[j][nb]*matA->tabMat[nb][i];
}
}
}
//Eigenvalues and eigenvectors
Matrix U,W,V;
a->svd(U,W,V);
for(int j=1,k=0;j<=3;j++,k+=3)
for(int i=1;i<=3;i++)
F->tabMat[i][j]=V.tabMat[i+k][9]/V.tabMat[9][9]; //write the fundamental matrix
}
/********HOMOGRAPHY FROM IMAGES AND COARSE HOMOGRAPHY**************/
void computeHomographyPrec(vector<CornerDescriptor *> &cor1,vector<CornerDescriptor *> &cor2, Matrix *H,float max_dist){
vector<CornerDescriptor *> cor1_tmp;
vector<CornerDescriptor *> cor2_tmp;
vector<CornerDescriptor *> cor1_tmp_;
vector<CornerDescriptor *> cor2_tmp_;
// float max_scale_error=0.2;
for(int i=0;i<15;i++){
matchPointsByHomography(cor1, cor2,cor1_tmp,cor2_tmp, H, max_dist);
//matchScaleByHomography(cor1_tmp_, cor2_tmp_,cor1_tmp,cor2_tmp, H, max_scale_error);
cout << "max dist :"<< max_dist<< endl;
cout << "points1 :" << cor1.size()<< ", matched point: "<< cor1_tmp.size()<< endl;
cout << "points2 :" << cor2.size()<< ", matched point: "<< cor2_tmp.size()<< endl<< endl;
//writeCorners(cor1_tmp,"cor0.cor");
//writeCorners(cor2_tmp,"cor1.cor");
if(cor1_tmp.size()>10){
computeHomography(cor1_tmp,cor2_tmp, H);
if(max_dist>1)max_dist--;
}
else {
max_dist+=2;
}
if(getchar()=='y')break;
cor1_tmp.clear();
cor2_tmp.clear();
cor1_tmp_.clear();
cor2_tmp_.clear();
}
}
void getAffMat(CornerDescriptor * cor, Matrix *H, Matrix &AFF){
Matrix Mcor(2,2),Mcor2(2,2),U,D,V;
Mcor(1,1)=cor->getMi11();
Mcor(1,2)=cor->getMi12();
Mcor(2,1)=cor->getMi21();
Mcor(2,2)=cor->getMi22();
Mcor.svd(U,D,V);
float scale1=3*cor->getCornerScale();
float a=D(1,1)*scale1;
float b=D(2,2)*scale1;
float xe=cor->getX();
float ye=cor->getY();
vector<CornerDescriptor *> cor1;
vector<CornerDescriptor *> cor2;
float px,py,ax,ay;
float da=a/5.0;
float db=b/5.0;
for(float j=-b;j<=b;j+=db){
for(float i=-a;i<=a;i+=da){
px=xe+V(1,1)*i+V(1,2)*j;
py=ye+V(2,1)*i+V(2,2)*j;
getHPoint(px,py,H,ax,ay);
cor1.push_back(new CornerDescriptor(px,py));
cor2.push_back(new CornerDescriptor(ax,ay));
// writeCorners(cor1,"aff1.cor");
// writeCorners(cor2,"aff2.cor");
// cout << "OK"<< endl;
// getchar();
}
}
computeAffine(cor1,cor2, &AFF);
cor1.clear();
cor2.clear();
}
void displayEllipse(DARY *im, Matrix *M, int x, int y, int xc, int yc, float color){
Matrix Mi,U,V,D;
Mi =(*M);// M->inverse();
Mi.svd(U,D,V);
float sc=sqrt(D(1,1)*D(2,2));
D(1,1)/=sc;
D(2,2)/=sc;
//cout << "DE " << sc << endl << D;
Mi=U*D*V.transpose();
int size=(int)(rint(sc)),xi,yi;
// float color=255;
Matrix X(2,1),Xe;
for(int i=-2;i<=2;i++){
im->fel[y+i][x]=im->fel[y][x+i]=color;
}
for(int i=-4;i<=4;i++){
im->fel[y+yc+i][x+xc]=im->fel[y+yc][x+xc+i]=color;
im->fel[y+yc+i][x-xc]=im->fel[y+yc][x-xc+i]=color;
im->fel[y-yc+i][x+xc]=im->fel[y-yc][x+xc+i]=color;
im->fel[y-yc+i][x-xc]=im->fel[y-yc][x-xc+i]=color;
}
for(int i=-size;i<=size;i++){
X(1,1)=i;
X(2,1)=(sqrt((float)(size*size-i*i)));
Xe=Mi*X;
xi=(int)rint(Xe(1,1));
yi=(int)rint(Xe(2,1));
if(y+yi>0 && y+yi<im->y() && x+xi>0 && x+xi<im->x())
im->fel[y+yi][x+xi]=color;
if(y-yi>0 && y-yi<im->y()&& x-xi>0 && x-xi<im->x())
im->fel[y-yi][x-xi]=color;
X(1,1)=X(2,1);
X(2,1)=i;
Xe=Mi*X;
xi=(int)rint(Xe(1,1));
yi=(int)rint(Xe(2,1));
if(y+yi>0 && y+yi<im->y() && x+xi>0 && x+xi<im->x())
im->fel[y+yi][x+xi]=color;
if( y-yi>0 && y-yi<im->y()&& x-xi>0 && x-xi<im->x())
im->fel[y-yi][x-xi]=color;
X(1,1)=i;
X(2,1)=0;
Xe=V*X;
xi=(int)rint(Xe(1,1));
yi=(int)rint(Xe(2,1));
if(y+yi>0 && y+yi<im->y() && x+xi>0 && x+xi<im->x())
im->fel[y+yi][x+xi]=color;
}
}
float ellipsArea(Matrix D,Matrix I, int &xc, int &yc){
float a2=(D(1,1)*D(1,1));
float b2=(D(2,2)*D(2,2));
float r2=I(1,1)*I(1,1);
float y2=(r2-a2)/(1-a2/b2);
if(y2>0){
yc= (int)rint(sqrt((float)y2));
}else yc=0;
float x2=(a2-r2*(a2/b2))/(1-a2/b2);
if(x2>0 && yc>0){
xc= (int)rint(sqrt((float)x2));
}else {
yc=0;
xc=0;
}
float CA,EA,diff,angle,relativ;
CA=M_PI*r2;
EA=M_PI*D(1,1)*D(2,2);
if(yc==0 && xc==0){/****no intersection points******/
diff=fabs(EA-CA);
relativ=100.0*diff/((EA<CA)?CA:EA);
cout << "CA "<<CA << " EA " << EA << "diff " <<diff<< endl;
return relativ;
}
else{
float EA_aplha=asin(xc/D(1,1));
float CA_aplha=asin(xc/I(1,1));
angle=asin(xc/sqrt((float)(xc*xc+yc*yc)));
//cout << "angle " << 180*angle/M_PI<< endl;
float EA_integ=0.5*D(1,1)*D(2,2)*(EA_aplha+0.5*sin(2*EA_aplha));
float CA_integ= 0.5*r2*(CA_aplha+0.5*sin(2*CA_aplha));
float CA_out=4*(CA_integ-EA_integ);
float CA_in=CA-CA_out;
float EA_out=EA-CA_in;
diff=(EA_out+CA_out)/(CA_in+EA_out+CA_out);
relativ=100.0*diff;
// cout << "CA "<<CA << " EA " << EA << " CA_integ " <<CA_integ << " EA_integ " <<EA_integ<< " CA_in "<<CA_in<<" CA_out "<< CA_out<<endl;
return relativ;
}
return 0;
}
/********COMPARE AFFINE REGIONS**************/
float matchAffinePoints(CornerDescriptor * cor1,CornerDescriptor *cor2, Matrix AFF){
Matrix Mcor1(2,2),Mcor1q(2,2),Mcor2(2,2),U1,D1,D1q(2,2),V1,U2,D2,V2,U3,D3,V3,MAFF(2,2),U4,D4,V4,DIFF,BtMB,rot,I(2,2,0.0);
I(1,1)=I(2,2)=1;
float angle;
MAFF(1,1)=AFF(1,1);
MAFF(1,2)=AFF(1,2);
MAFF(2,1)=AFF(2,1);
MAFF(2,2)=AFF(2,2);
Mcor1(1,1)=cor1->getMi11();
Mcor1(1,2)=cor1->getMi12();
Mcor1(2,1)=cor1->getMi21();
Mcor1(2,2)=cor1->getMi22();
Mcor2(1,1)=cor2->getMi11();
Mcor2(1,2)=cor2->getMi12();
Mcor2(2,1)=cor2->getMi21();
Mcor2(2,2)=cor2->getMi22();
/*computing M pow(-1)*/
Mcor1.svd(U1,D1,V1);
D1=D1*cor1->getCornerScale();
Mcor1=U1*D1*V1.transpose();
D1(1,1)=(D1(1,1)*D1(1,1));
D1(2,2)=(D1(2,2)*D1(2,2));
Mcor1q=U1*D1*V1.transpose();
/*computing M pow(-1/2)*/
Mcor2.svd(U2,D2,V2);
D2=D2*cor2->getCornerScale();
Mcor2=U2*D2*V2.transpose();
float angle2=acos(V2(1,1));
/*
cout << "X " << cor1->getX() << " Y " << cor2->getY() << endl;
cout <<endl<< "Mcor2\n" << Mcor2 << endl;
cout << "U2\n" << U2;
cout << "D2\n" << D2;
cout << "V2\n" << V2;
cout << "angle " << 180*acos(rot(1,1))<< endl;
*/
/*computing sqrt(AFF*Mcorq1*AFF.transpose)
sqrt(M pow-1)=sqrt(AFF*Mcorq1*AFF.transpose)*/
BtMB=(MAFF*Mcor1q*MAFF.transpose());
BtMB.svd(U1,D1,V1);
D1(1,1)= sqrt(D1(1,1));
D1(2,2)= sqrt(D1(2,2));
BtMB=U1*D1*V1.transpose();
float angle1=acos(V1(1,1));
/* cout << "sqrt(BtMB)\n " << BtMB << endl;
cout << "U1a2\n" << U1;
cout << "D1a2\n" << D1;
cout << "V1a2\n" << V1;
cout << "angle " << 180*acos(rot(1,1))<< endl;
*/
/*computing difference */
DIFF=Mcor2.inverse()*BtMB;
DIFF.svd(U1,D1,V1);
angle=180*fabs(angle1-angle2)/M_PI;
float diff1 = fabs(D1(1,1)-1);
float diff2 = fabs(D1(2,2)-1);
float diff = ((diff1<diff2)?diff2:diff1);
D1*=80;
I*=80;
int xc,yc;
float da=ellipsArea( D1,I, xc, yc);
if(da<1000){//angle <2 && angle && diff<0.1){
/*
DARY *im = new DARY(300,300,0.0);
DARY *im2 = new DARY(300,300,0.0);
displayEllipse(im, &(10*Mcor2),150, 150,0,0,255);
displayEllipse(im, &(10*BtMB),150, 150,0,0,160);
cout <<endl << xc << " " << yc<< endl;
displayEllipse(im2, &D1,150, 150,0,0,255);
displayEllipse(im2, &I,150, 150,xc,yc,160);
im->write("comp.pgm");
im2->write("comp2.pgm");
delete im;delete im2;
cout << "relativ " << da<< endl;
cout << "DIFF\n" << DIFF << endl;
cout << "U1\n" << U1;
cout << "D1\n" << D1;
cout << "V1\n" << V1;
cout << "U1*V1.transpose\n" << rot;
cout << "angle " << angle<< endl;
cout << "diff1 " << diff1<< endl;
cout << "diff2 " << diff2<< endl;
cout << "diff " << diff<< endl;
getchar();
*/
return da;
} else
return (100);
}
// renamed square() to float_square() to avoid conflict with other declarations of squre()
// Abhishek Dutta <adutta@robots.ox.ac.uk>, 12 March 2020
float float_square(float a){
return a*a;
}
void getMeanAffine(vector<CornerDescriptor *> &cor1){
Matrix U(2,2),D(2,2),V(2,2),M(2,2),Dm(2,2,0.0);
//cout << "nb points "<<cor1.size()<<endl;
float nb=0,angle;
float scales=0;
float anV=0;
float anU=0;
float escales=0;
float x=0,y=0;
for(uint j=0;j<cor1.size();j++){
M(1,1)=cor1[j]->getMi11();
M(1,2)=cor1[j]->getMi12();
M(2,1)=cor1[j]->getMi21();
M(2,2)=cor1[j]->getMi22();
M.svd(U,D,V);
escales+=(D(1,1)/D(2,2));
scales+=(cor1[j]->getCornerScale());
angle=acos(V(1,1));
anV+=(angle);
/*
cout << U << endl;
cout << D << endl;
cout << V << endl;
cout <<cor1[j]->getX()<< " "<< cor1[j]->getY()<< " angle cos "<< (180*angle/M_PI) << endl;
*/
angle=acos(U(1,1));
anU+=(angle);
x+=cor1[j]->getX();
y+=cor1[j]->getY();
nb++;
}
scales/=nb;
escales/=nb;
anV/=nb;
anU/=nb;
x/=nb;
y/=nb;
D(1,1)=sqrt(escales);
D(2,2)=1.0/D(1,1);
V(1,1)=(V(1,1)>0)?fabs(cos(anV)):(-fabs(cos(anV)));
V(1,2)=(V(1,2)>0)?fabs(sin(anV)):(-fabs(sin(anV)));
V(2,1)=(V(2,1)>0)?fabs(sin(anV)):(-fabs(sin(anV)));
V(2,2)=(V(2,2)>0)?fabs(cos(anV)):(-fabs(cos(anV)));
U(1,1)=(U(1,1)>0)?fabs(cos(anU)):(-fabs(cos(anU)));
U(1,2)=(U(1,2)>0)?fabs(sin(anU)):(-fabs(sin(anU)));
U(2,1)=(U(2,1)>0)?fabs(sin(anU)):(-fabs(sin(anU)));
U(2,2)=(U(2,2)>0)?fabs(cos(anU)):(-fabs(cos(anU)));
/*
cout << endl<< U << endl;
cout << D << endl;
cout << V << endl;
cout <<endl << x << " "<<y<< "angle "<< (180*anV/M_PI)<< endl;
*/
M=U*D*V.transpose();
cor1[0]->setCornerScale(scales);
cor1[0]->setX_Y(x,y);
cor1[0]->setMi(M(1,1),M(1,2),M(2,1),M(2,2));
}
void removeSimilarPoints(vector<CornerDescriptor *> &cor1){
int csize=cor1.size();
CornerDescriptor *c1;
vector<CornerDescriptor *> csim;
vector<CornerDescriptor *> cmean;
float dist,sc_dif;
Matrix M(2,2),U,V,D;
float angle1,sc1,angle,sc,dist_max;
while(cor1.size()>0){
cout << "\rRemoving similar points " << cor1.size() << " "<<flush;
c1=cor1[0];
csim.push_back(cor1[0]);
//cor1.erase((std::vector<CornerDescriptor*>::iterator)&cor1[0]);
cor1.erase(cor1.begin());
M(1,1)=c1->getMi11();
M(1,2)=c1->getMi12();
M(2,1)=c1->getMi21();
M(2,2)=c1->getMi22();
M.svd(U,D,V);
angle=acos(V(1,1));
sc=D(1,1)/D(2,2);
dist_max=0.6*c1->getCornerScale();
for(uint j=0;j<cor1.size();j++){
dist=sqrt(float_square(cor1[j]->getX()-c1->getX())+float_square(cor1[j]->getY()-c1->getY()));
sc_dif=fabs(1-(c1->getCornerScale()/c1->getCornerScale()));
M(1,1)=cor1[j]->getMi11();
M(1,2)=cor1[j]->getMi12();
M(2,1)=cor1[j]->getMi21();
M(2,2)=cor1[j]->getMi22();
M.svd(U,D,V);
angle1=acos(V(1,1));
sc1=D(1,1)/D(2,2);
if(dist<dist_max && sc_dif<0.3 && fabs(angle1-angle)<0.2 && fabs(1-sc/sc1)<0.2){
csim.push_back(cor1[j]);
//cor1.erase((std::vector<CornerDescriptor*>::iterator)&cor1[j]);
cor1.erase(cor1.begin() + j);
j--;
}
}
if(csim.size()>1){
getMeanAffine(csim);
}
cmean.push_back(csim[0]);
for (size_t i= 1; i<csim.size(); ++i) delete csim[i];
csim.clear();
}
cout <<endl<< "size bef: " <<csize<<" aft: "<< cmean.size()<< endl;
cor1=cmean;
}
/********COMPARE AFFINE REGIONS of corresponding points**************/
void matchAffinePoints(vector<CornerDescriptor *> &cor1,vector<CornerDescriptor *> &cor2,
vector<CornerDescriptor *> &cor1_match,vector<CornerDescriptor *> &cor2_match,
Matrix *H, float max_error){
Matrix H1,U,V,D,AFF(2,2,0.0),N;
float error=1000,error2;
float dist,sc_dif;
float min_sc=100,max_sc=0;
CornerDescriptor *c1,*c2;
// for(uint j=0;j<cor1.size();j++){
while(cor1.size()>0){
cout << "\r" << " of " << cor1.size()<< flush;
getAffMat(cor1[0],H,AFF);
error=matchAffinePoints(cor1[0], cor2[0], AFF);
c1=cor1[0];
c2=cor2[0];
//cor1.erase((std::vector<CornerDescriptor*>::iterator)&cor1[0]);
//cor2.erase((std::vector<CornerDescriptor*>::iterator)&cor2[0]);
cor1.erase(cor1.begin());
cor2.erase(cor2.begin());
if(error<max_error){
for(uint i=0;i<cor1.size();i++){
dist=sqrt(float_square(cor1[i]->getX()-c1->getX())+float_square(cor1[i]->getY()-c1->getY()));
sc_dif=fabs(cor1[i]->getCornerScale()-c1->getCornerScale())/(c1->getCornerScale());
if(dist<4 && sc_dif<0.3){
//getAffMat(cor1[i],H,AFF2);
error2=matchAffinePoints(cor1[i], cor2[i], AFF);
if(error2 < error){
c1=cor1[i];
c2=cor2[i];
//cor1.erase((std::vector<CornerDescriptor*>::iterator)&cor1[i]);
//cor2.erase((std::vector<CornerDescriptor*>::iterator)&cor2[i]);
cor1.erase(cor1.begin() + i);
cor2.erase(cor2.begin() + i);
error=error2;
i--;
}else {
//cor1.erase((std::vector<CornerDescriptor*>::iterator)&cor1[i]);
//cor2.erase((std::vector<CornerDescriptor*>::iterator)&cor2[i]);
cor1.erase(cor1.begin() + i);
cor2.erase(cor2.begin() + i);
i--;
}
}
}
if(min_sc>c1->getCornerScale())min_sc=c1->getCornerScale();
else if(max_sc<c1->getCornerScale())max_sc=c1->getCornerScale();
cor1_match.push_back(c1);
cor2_match.push_back(c2);
}
}
//cout <<endl<< "max sc " << max_sc << "min sc " << min_sc << endl;
}
void projectAffineCorners(vector<CornerDescriptor *> &cor, vector<CornerDescriptor *> &cor2, Matrix *H){
CornerDescriptor *c2;
float x,y,c;
Matrix H1,U,V,D,AFF(2,2,0.0),N;
H1=(*H);
H1=H1/H1(3,3);
AFF(1,1)=H1(1,1);
AFF(1,2)=H1(1,2);
AFF(2,1)=H1(2,1);
AFF(2,2)=H1(2,2);
Matrix Mcor1(2,2,0.0), Mcor2,U1,V1,D1;
H1=(*H);
for(uint i=0;i<cor.size();i++){
getHPoint(cor[i]->getX(),cor[i]->getY() , H, x, y);
getAffMat(cor[i],H,AFF);
c2=new CornerDescriptor(x,y);
Mcor1(1,1)=cor[i]->getMi11();
Mcor1(1,2)=cor[i]->getMi12();
Mcor1(2,1)=cor[i]->getMi21();
Mcor1(2,2)=cor[i]->getMi22();
Mcor1.svd(U1,D1,V1);
D1=D1*cor[i]->getCornerScale();
D1(1,1)=(D1(1,1)*D1(1,1));
D1(2,2)=(D1(2,2)*D1(2,2));
Mcor1=U1*D1*V1.transpose();
Mcor2=AFF*Mcor1*AFF.transpose();
Mcor2.svd(U1,D1,V1);
D1(1,1)=sqrt(D1(1,1));
D1(2,2)=sqrt(D1(2,2));
c=sqrt(D1(1,1)*D1(2,2));
D1(1,1)=D1(1,1)/c;
D1(2,2)=D1(2,2)/c;
Mcor2=U1*D1*V1.transpose();
c2->setMi(Mcor2(1,1),Mcor2(1,2),Mcor2(2,1),Mcor2(2,2));
c2->setCornerScale(c);
cor2.push_back(c2);
}
//getchar();
}
/***************MATCHING DESCRIPTORS***************************/
/***************MATCHING DESCRIPTORS***************************/
/***************MATCHING DESCRIPTORS***************************/
void getNormPoint(DARY *img_in, CornerDescriptor *cor,DARY *imgn, float scmean){
float angle = cor->getAngle();
float lecos=cos(-angle);
float lesin=sin(-angle);
float scal=cor->getCornerScale()/scmean;
float m11=scal*(cor->getMi11()*lecos-cor->getMi12()*lesin);
float m12=scal*(cor->getMi11()*lesin+cor->getMi12()*lecos);
float m21=scal*(cor->getMi21()*lecos-cor->getMi22()*lesin);
float m22=scal*(cor->getMi21()*lesin+cor->getMi22()*lecos);
float x = (cor->getX());
float y = (cor->getY());
imgn->interpolate(img_in,x,y,m11,m12,m21,m22);
x=imgn->x()>>1;y=imgn->y()>>1;
normalize(imgn,(int)x,(int)y,x);
}
float SSD(DARY *img_in1, CornerDescriptor *cor1, DARY *img_in2, CornerDescriptor *cor2){
float scmean=10.0;
int im_size=2*(int)rint(GAUSS_CUTOFF*scmean)+3;
DARY * imgn1 = new DARY(im_size,im_size);
getNormPoint(img_in1, cor1, imgn1,scmean);
DARY * imgn2 = new DARY(im_size,im_size);
getNormPoint(img_in2, cor2, imgn2,scmean);
float sum=0;//,P=0,X=0;
for(int i=0;i<im_size;i++){
for(int j=0;j<im_size;j++){
//P+=float_square(imgn1->fel[i][j]);
//X+=float_square(imgn2->fel[i][j]);
//sum+=(imgn1->fel[i][j]*imgn2->fel[i][j]);
sum+=float_square(imgn1->fel[i][j]-imgn2->fel[i][j]);
}
}
/*
float NCC = sum/(P*X);
imgn1->write("cor1.pgm");
imgn2->write("cor2.pgm");
cout << "norm "<< sqrt(sum)<< endl;getchar();
*/
delete imgn1;delete imgn2;
return sqrt(sum);
}
void SSD(DARY* img_in1, vector<CornerDescriptor*>& cor1,
DARY* img_in2, vector<CornerDescriptor*>& cor2, float dist_cc) {
float ssd;
for (uint i = 0; i < cor1.size(); i++) {
ssd = SSD(img_in1, cor1[i], img_in2, cor2[i]);
cout << "\rSSD " << i << " of " << cor1.size() << " ssd " << ssd << " " << flush;//getchar();
//cout << cor1[i]->getX()<< " " << cor1[i]->getY()<< " to ";
//cout << cor2[i]->getX()<< " " << cor2[i]->getY()<<endl;
if (ssd > dist_cc) {
//cor1.erase((std::vector<CornerDescriptor*>::iterator) & cor1[i]);
//cor2.erase((std::vector<CornerDescriptor*>::iterator) & cor2[i]);
cor1.erase(cor1.begin() + i);
cor2.erase(cor2.begin() + i);
i--;
}
}
}
void checkMatches( vector<CornerDescriptor*> &cor1, vector<CornerDescriptor*> &cor2, Matrix *H,
float dist_max,int model){
vector<CornerDescriptor*> match1;
vector<CornerDescriptor*> match2;
if(cor1.size()!=cor2.size()){cout << "size not equal "<< endl;exit(0);}
float matched=0;
float dist;
for(unsigned int c1=0;c1<cor1.size();c1++){
if(model){
if(checkHomog(cor1[c1],cor2[c1],H,dist_max,dist)){
match1.push_back(cor1[c1]);
match2.push_back(cor2[c1]);
matched++;
}
}else{
if(checkEpip(cor1[c1],cor2[c1],H,dist_max,dist)){
match1.push_back(cor1[c1]);
match2.push_back(cor2[c1]);
matched++;
}
}
}
cor1.clear();
cor2.clear();
cor1=match1;
cor2=match2;
}
void matchDescriptors( vector<CornerDescriptor*> &cor1,
vector<CornerDescriptor*> &cor2, Matrix * invCovMat, Matrix * geom,
vector<CornerDescriptor*> &match1_tmp,
vector<CornerDescriptor*> &match2_tmp,
vector<CornerDescriptor*> &match3_tmp,
const float d_dist_max){
float d_dist,d_dist_min;
unsigned int size1=cor1.size();
unsigned int size2=cor2.size();
int c2_min,c2_min2;
float dist_max=5;
float dist;
for(unsigned int c1=0;c1<size1;c1++){
cout << "\rdescriptor " << c1 << flush;
d_dist_min=d_dist_max;
c2_min2=c2_min=-1;
for(unsigned int c2=0;c2<size2;c2++){
d_dist = distEuc(cor1[c1]->getVec(), cor2[c2]->getVec(),cor2[c2]->getSize());
//d_dist = distCSift(cor1[c1]->getVec(), cor2[c2]->getVec(),cor2[c2]->getSize());
//d_dist = distMahalanobis(cor1[c1]->getVec(), cor2[c2]->getVec(), invCovMat);
//cout << "d_dist " << d_dist_max<< endl;
if(d_dist<d_dist_min && checkEpip(cor1[c1],cor2[c2],geom,dist_max,dist)){
d_dist_min=d_dist;
c2_min2=c2_min;
c2_min=c2;
}
}
if(c2_min>=0){
match1_tmp.push_back(cor1[c1]);
match2_tmp.push_back(cor2[c2_min]);
if(c2_min2>=0)match3_tmp.push_back(cor2[c2_min2]);
else match3_tmp.push_back(cor2[c2_min]);
}
}
}
void checkMatchDescriptors( vector<CornerDescriptor*> &cor1,
vector<CornerDescriptor*> &cor2, Matrix * invCovMat, Matrix * geom,
const float d_dist_max){
vector<CornerDescriptor*> match1_tmp;
vector<CornerDescriptor*> match2_tmp;
float d_dist,d_dist_min;
unsigned int size1=cor1.size();
unsigned int size2=cor2.size();
int c2_min,c2_min2;
float dist_max=5;
float dist;
for(unsigned int c1=0;c1<size1;c1++){
cout << "\rdescriptor " << c1 << flush;
d_dist_min=d_dist_max;
c2_min=-1;
for(unsigned int c2=0;c2<size2;c2++){
d_dist = distEuc(cor1[c1]->getVec(), cor2[c2]->getVec(),cor2[c2]->getSize());
//d_dist = distCSift(cor1[c1]->getVec(), cor2[c2]->getVec(),cor2[c2]->getSize());
//d_dist = distMahalanobis(cor1[c1]->getVec(), cor2[c2]->getVec(), invCovMat);
//cout << "d_dist " << d_dist_max<< endl;
if(d_dist<d_dist_min && checkHomog(cor1[c1],cor2[c2],geom,dist_max,dist)){
d_dist_min=d_dist;
c2_min=c2;
}
}
if(c2_min>=0){
match1_tmp.push_back(cor1[c1]);
match2_tmp.push_back(cor2[c2_min]);
//cor1.erase((std::vector<CornerDescriptor*>::iterator)&cor1[c1]);
//cor2.erase((std::vector<CornerDescriptor*>::iterator)&cor2[c2_min]);
}
}
cor2.clear();
cor1.clear();
cor1=match1_tmp;
cor2=match2_tmp;
}
void matchDescriptorsSimilar( vector<CornerDescriptor*> &cor1,
vector<CornerDescriptor*> &cor2,
Matrix * invCovMat, Matrix * geom,
const float d_dist_max){
vector<CornerDescriptor*> match1_tmp;
vector<CornerDescriptor*> match2_tmp;
float d_dist,dist_max=3;
unsigned int size1=cor1.size();
unsigned int size2=cor2.size();
for(unsigned int c1=0;c1<size1;c1++){
cout << "\rdescriptor " << c1 << flush;
for(unsigned int c2=0;c2<size2;c2++){
d_dist = distEuc(cor1[c1]->getVec(), cor2[c2]->getVec(), cor2[c2]->getSize());
//d_dist = distMahalanobis(cor1[c1]->getVec(), cor2[c2]->getVec(), invCovMat);
if(d_dist<d_dist_max /*&& checkEpip(cor1[c1],cor2[c2],geom,dist_max)*/){
match1_tmp.push_back(cor1[c1]);
match2_tmp.push_back(cor2[c2]);
}
}
}
removeFloatMatches(match1_tmp,match2_tmp);
removeFloatMatches(match2_tmp,match1_tmp);
cor1=match1_tmp;
cor2=match2_tmp;
}
float matchSimilarDescriptors( vector<CornerDescriptor*> &cor1,
vector<CornerDescriptor*> &cor2,
Matrix * geom,
const float d_dist_max, ofstream &out){
vector<CornerDescriptor*> match1_tmp;
vector<CornerDescriptor*> match2_tmp;
vector<CornerDescriptor*> cor1_tmp;
vector<CornerDescriptor*> cor2_tmp;
float d_dist;
unsigned int size1=cor1.size();
unsigned int size2=cor2.size();
out << "Similarity threshold: "<<d_dist_max<< endl;
matchPointsByHomography(cor1, cor2,cor1_tmp,cor2_tmp,geom, 10);
out << "corners size 1: "<<size1<< " corners size 2: "<<size2<< endl;
out << "matched by loc.: "<<cor1_tmp.size()<< " of " << size1 << " " << 100.0*cor1_tmp.size()/size1 << "\%"<< endl;
checkScaleByHomography(cor1_tmp,cor2_tmp,geom,0.3);
out << "matched by loc., scale: "<< cor1_tmp.size() << " of " << size1 << " "<<100.0*cor1_tmp.size()/size1<< "\%"<< endl;
checkAngleByHomography(cor1_tmp,cor2_tmp,geom,0.15);
out << "matched by loc., scale, angle: "<< cor1_tmp.size() << " of " << size1 << " "<<100.0*cor1_tmp.size()/size1<< "\%"<< endl;
Matrix Hi;
Hi=geom->inverse();
vector<CornerDescriptor*> cor1_aff;
vector<CornerDescriptor*> cor2_aff;
// matchAffinePoints(cor1_tmp, cor2_tmp,cor1_aff,cor2_aff, geom, 60);
out <<endl<< "matched l-r "<< cor1_aff.size()<< endl;
//matchAffinePoints(cor2_aff, cor1_aff,cor2_tmp,cor1_tmp, &Hi, 60);
out <<endl<< "matched r-l "<< cor2_tmp.size()<< endl;
out << "matched / detected "<< ((100.0*cor1_tmp.size())/((size1<size2)?size1:size2))<< "\%"<<endl;
cor1_aff.clear();
cor2_aff.clear();
float correct=(float)cor1_tmp.size();
for(unsigned int c1=0;c1<size1;c1++){
cout << "\rdescriptor " << c1 << flush;
for(unsigned int c2=0;c2<size2;c2++){
d_dist = distEuc(cor1[c1]->getVec(), cor2[c2]->getVec(),cor2[c2]->getSize());
//d_dist = distMahalanobis(cor1[c1]->getVec(), cor2[c2]->getVec(), invCovMat);
if(d_dist<d_dist_max /*&& checkEpip(cor1[c1],cor2[c2],geom,dist_max)*/){
match1_tmp.push_back(cor1[c1]);
match2_tmp.push_back(cor2[c2]);
}
}
}
cor1_tmp.clear();
cor2_tmp.clear();
out << "matched by descriptor: "<<match1_tmp.size()<< " of all " << size1 << " "<<100.0*match1_tmp.size()/size1<< "\%"<< endl;
cout <<endl<< "matched by descriptor: "<<match1_tmp.size()<< " of all " << size1 << " "<<100.0*match1_tmp.size()/size1<< "\%"<< endl;
if(match1_tmp.size()!=0){
checkMatches(match1_tmp, match2_tmp,geom, 3,1);
checkScaleByHomography(match1_tmp,match2_tmp,geom,0.3);
checkAngleByHomography(match1_tmp,match2_tmp,geom,0.15);
//removeFloatMatches(match1_tmp,match2_tmp);
//removeFloatMatches(match2_tmp,match1_tmp);
//matchAffinePoints(match1_tmp, match2_tmp,cor1_aff,cor2_aff, geom, 60);
//matchAffinePoints(cor2_aff, cor1_aff,match2_tmp,match1_tmp, &Hi, 60);
}
out << "matched by descriptor: "<<match1_tmp.size()<< " correct of all " << size1 << " "<<100.0*match1_tmp.size()/size1<< "\%"<< endl;
out << "matched by descriptor: "<<match1_tmp.size()<< " correct of possible " << correct << " "<<100.0*match1_tmp.size()/correct<< "\%"<< endl;
cout << "matched by descriptor: "<<match1_tmp.size()<< " correct of possible " << correct << " "<<100.0*match1_tmp.size()/correct<< "\%"<< endl;
return (match1_tmp.size()/correct);
}
void matchDescriptorsNearest(vector<CornerDescriptor*> &cor1,
vector<CornerDescriptor*> &cor2,
Matrix *covMat, Matrix *geom,
const float d_dist_max){
vector<CornerDescriptor*> match3_tmp;
vector<CornerDescriptor*> match2_tmp;
vector<CornerDescriptor*> match1_tmp;
vector<CornerDescriptor*> matchi3_tmp;
vector<CornerDescriptor*> matchi2_tmp;
vector<CornerDescriptor*> matchi1_tmp;
Matrix invC;
invC=covMat->inverse();
matchDescriptors( cor1, cor2,&invC, geom, match1_tmp, match2_tmp, match3_tmp, d_dist_max);
Matrix geom_i=geom->transpose();
matchDescriptors( cor2, cor1,&invC, &geom_i, matchi1_tmp, matchi2_tmp, matchi3_tmp, d_dist_max);
vector<CornerDescriptor*> matched1;
vector<CornerDescriptor*> matched2;
for(unsigned int c1=0;c1<match1_tmp.size();c1++){
for(unsigned int c2=0;c2<matchi2_tmp.size();c2++){
if(match1_tmp[c1]==matchi2_tmp[c2]){
if(match2_tmp[c1]==matchi1_tmp[c2]){
matched1.push_back(match1_tmp[c1]);
matched2.push_back(match2_tmp[c1]);
}else if(match3_tmp[c1]==matchi1_tmp[c2]){
matched1.push_back(match1_tmp[c1]);
matched2.push_back(match2_tmp[c1]);
}else if(match1_tmp[c1]==matchi3_tmp[c2]){
matched1.push_back(match1_tmp[c1]);
matched2.push_back(match2_tmp[c1]);
}
}
}
}
removeFloatMatches(matched1,matched2);
removeFloatMatches(matched2,matched1);
cor1=matched1;
cor2=matched2;
/* for(unsigned int c1=0;c1<cor1.size();c1++){
float d_dist = distMahalanobis(cor1[c1]->getVec(), cor2[c1]->getVec(), &invC);
cout << cor1[c1]->getX()<< " " << cor1[c1]->getY()<<" " << cor2[c1]->getX();
cout << " " << cor2[c1]->getY()<< " "<<d_dist<< endl;
}*/
}
void angleOrder(vector<CornerDescriptor*> &cor1,int c1, vector<int> neigh1){
}
int computeVotes(vector<CornerDescriptor*> cor1,
vector<CornerDescriptor*> &cor2, int cr1, int cr2,
vector<int> neigh1,vector<int> neigh2,
DARY *rank){
// DARY *im1 = new DARY(768,700,0.0);
//DARY *im2 = new DARY(786,700,0.0);
DARY *nrank= new DARY(neigh1.size(),neigh2.size(),0.0);
CornerDescriptor *cd1, *cd2;
float angle1=0;
vector<int> n1;vector<int> n2;
for(int c1=0;c1<neigh1.size();c1++){
for(int c2=0;c2<neigh2.size();c2++){
if(rank->fel[neigh1[c1]][neigh2[c2]]<50){
n1.push_back(neigh1[c1]);n2.push_back(neigh2[c2]);
}
}
}
cout << neigh1.size()<< " " << neigh2.size()<< endl;
cout << n1.size()<< " " << n2.size()<< endl;
getchar();
//drawCorners(im1, n1, "n1.pgm",255);
//drawCorners(im2, n2, "n2.pgm",255);cout << "OK"<< endl;getchar();
delete nrank;
return 1;
}
void matchDescriptorsNearest(vector<CornerDescriptor*> &cor1,
vector<CornerDescriptor*> &cor2,
const float d_dist_max){
int size1=cor1.size();
int size2=cor2.size();
DARY *ddist = new DARY(size1,size2,0.0);
DARY *votes = new DARY(size1,size2,0.0);
DARY *rank = new DARY(size1,size2,200.0);
DARY *p1dist = new DARY(size1,size1,0.0);
DARY *p2dist = new DARY(size2,size2,0.0);
for(unsigned int c1=0;c1<size1;c1++){
//cout << "\rdescriptor " << c1 << flush;
for(unsigned int c2=0;c2<size2;c2++){
ddist->fel[c1][c2] = distEuc(cor1[c1]->getVec(), cor2[c2]->getVec(),cor2[c2]->getSize());
//d_dist = distMahalanobis(cor1[c1]->getVec(), cor2[c2]->getVec(), invCovMat);
}
}
//ddist->write("dist.pgm");
int flag=0;
int maxrank=40;
//ranking rows
vector<int> rank10;
for(unsigned int c1=0;c1<size1;c1++){
cout << "\rdescriptor " << c1 << flush;
rank10.push_back(0);
for(unsigned int c2=0;c2<size2;c2++){
if(ddist->fel[c1][c2]<d_dist_max){
flag=1;
for(int r=0;r<rank10.size() && r<maxrank && flag;r++){
if(ddist->fel[c1][c2] < ddist->fel[c1][rank10[r]]){
//cout << c2 << " " << rank10[r] << " "<<ddist->fel[c1][c2] <<" "<< ddist->fel[c1][rank10[r]]<< endl;
//rank10.insert((std::vector<int>::iterator)&(rank10[r]),c2);
rank10.insert(rank10.begin() + r, c2);
flag=0;
}
}
//cout<< c2<< " OK "<< rank10.size()<< endl;
if(flag && rank10.size()<maxrank)rank10.push_back(c2);
}
}
for(int r=0;r<rank10.size() && r<maxrank ;r++){
//cout << rank10.size()<< " " << rank10[r]<< " "<< ddist->fel[c1][rank10[r]]<< " "<<d_dist_max<<endl;
rank->fel[c1][rank10[r]]=r;
}
rank10.clear();
//getchar();
}
cout << endl;
//ranking columns
rank10.clear();
for(unsigned int c2=0;c2<size2;c2++){
cout << "\rdescriptor " << c2 << flush;
rank10.push_back(0);
for(unsigned int c1=0;c1<size1;c1++){
if(ddist->fel[c1][c2]<d_dist_max){
flag=1;
for(int r=0;r<rank10.size() && r<maxrank && flag;r++){
if(ddist->fel[c1][c2] < ddist->fel[rank10[r]][c2]){
//cout << c2 << " " << rank10[r] << " "<<ddist->fel[c1][c2] <<" "<< ddist->fel[c1][rank10[r]]<< endl;
//rank10.insert((std::vector<int>::iterator)&(rank10[r]),c1);
rank10.insert(rank10.begin() + r, c1);
flag=0;
}
}
if(flag && rank10.size()<maxrank)rank10.push_back(c1);
}
}
for(int r=0;r<rank10.size() && r<maxrank ;r++){
rank->fel[rank10[r]][c2]+=(r);
}
rank10.clear();
//getchar();
}
for(unsigned int c1=0;c1<size1;c1++){
for(unsigned int c2=c1+1;c2<size1;c2++){
p1dist->fel[c1][c2]=float_square(cor1[c1]->getX()-cor1[c2]->getX())+float_square(cor1[c1]->getY()-cor1[c2]->getY());
p1dist->fel[c2][c1]=p1dist->fel[c1][c2];
}
}
for(unsigned int c1=0;c1<size2;c1++){
for(unsigned int c2=c1+1;c2<size2;c2++){
p2dist->fel[c1][c2]=float_square(cor2[c1]->getX()-cor2[c2]->getX())+float_square(cor2[c1]->getY()-cor2[c2]->getY());
p2dist->fel[c2][c1]=p2dist->fel[c1][c2];
}
}
vector<int> neigh1;
vector<int> neigh2;int nb=0;int c0=-1;
vector<CornerDescriptor*> n1;
vector<CornerDescriptor*> n2;
int radius=0;
for(unsigned int c1=0;c1<size1;c1++){
cout << "\rdescriptor " << c1 << flush;
radius=float_square(5.0*cor1[c1]->getCornerScale());
for(unsigned int c=0;c<size1;c++){
if(p1dist->fel[c1][c]<radius && c1!=c){
neigh1.push_back(c);
}
}
for(unsigned int c2=0;c2<size2;c2++){
if(rank->fel[c1][c2]<50){
radius=float_square(5.0*cor2[c2]->getCornerScale());
for(unsigned int c=0;c<size2;c++){
if(p2dist->fel[c2][c]<radius && c2!=c){
neigh2.push_back(c);
}
}
votes->fel[c1][c2]=computeVotes(cor1, cor2,c1, c2, neigh1, neigh2, rank);
neigh2.clear();
}
}
neigh1.clear();
}
// rank->normalize(0,10);
//rank->write("rank.pgm");
cout << nb<< endl;
}
void putVote(DARY *Hsimil, float fx, float fy, float vote){
int ix = (int)floor(fx);
int iy = (int)floor(fy);
float dx = fx-ix;
float dy = fy-iy;
if(iy<Hsimil->y()-1 && ix<Hsimil->x()-1){
Hsimil->fel[iy][ix]+=(1.0 - dy)*(1.0 - dx)*vote;
Hsimil->fel[iy+1][ix]+=(dy)*(1.0 - dx)*vote;
Hsimil->fel[iy][ix+1]+=(1-dy)*dx*vote;
Hsimil->fel[iy+1][ix+1]+=dy*dx*vote;
}
}
/*************MATCH BIKES**********************/
void matchScale(vector<DARY* > &Hsimil,vector<CornerDescriptor *> &corners1,
vector<CornerDescriptor *> &corners2, vector<float> scales, int sc1){
DARY *mahal = new DARY(corners1.size(),corners2.size(),0.0);
int vsize = corners1[0]->getSize();
for(int c1=0;c1<corners1.size();c1++){
cout << "\r corner " << c1 << " of " << corners1.size()<<" "<< flush;
for(int c2=0;c2<corners2.size();c2++){
mahal->fel[c1][c2]=distEuc(corners1[c1]->getVec(),corners2[c2]->getVec(),vsize);
}
}
float sc = 1.0/scales[sc1];
float dx,dy, dx1,dy1, dxmax=0,dymax=0;
int nb=0,nb1=0;;
for(int c1=0;c1<corners1.size();c1++){
dx1=sc*(corners1[c1]->getX()-80);
dy1=sc*(corners1[c1]->getY()-80);
for(int c2=0;c2<corners2.size();c2++){
if(mahal->fel[c1][c2]<90000){
dx=(corners2[c2]->getX()-dx1);
dy=(corners2[c2]->getY()-dy1);
if(dx>0 && dy>0){// && (corners1[c1]->getAngle()-corners2[c2]->getAngle())<0.2){
//(dxmax<dx)dxmax=dx;
//if(dymax<dy)dymax=dy;
putVote( Hsimil[sc1], dx/10.0,dy/10.0, 1.0/(1.0+mahal->fel[c1][c2]));
//cout << " dx " << dx << " dy " << dy << endl;
//nb++;
}//else nb1++;
}
}
}
//cout << " nb- " << nb << " nb+ "<< nb1<< endl;
//cout << " dx- " << dxmax << " dy+ "<< dymax<< endl;
delete mahal;
}
void matchScale(vector<DARY* > &Hsimil,CornerDescSequence all_desc1,
CornerDescSequence all_desc2, vector<float> scales){
float d1sc,d2sc, sc, sc2;
DARY *sv = new DARY(1,scales.size(),0.0);
for(int d1=0;d1<all_desc1.size();d1++){
d1sc=all_desc1[d1][0]->getCornerScale();
for(int d2=0;d2<all_desc2.size();d2++){
d2sc=all_desc2[d2][0]->getCornerScale();
for(int i=0;i<scales.size();i++){
sc=(d1sc/d2sc)/scales[i];
if(sc>1)sc=1/sc;
if(sc>0.9){
cout <<endl<< " d1 " << d1sc << " d2 " << d2sc << " sc " << (d1sc/d2sc)<< endl;
matchScale(Hsimil,all_desc1[d1],all_desc2[d2],scales,i);
sv->fel[0][i]++;
//cout << " scales "<<scales[i]<< " " << i << endl;
}
}
}
}
//for(int i=0;i<scales.size();i++)
// cout << " scales "<<scales[i]<< " " << sv->fel[0][i] << endl;
for(int i=0;i<Hsimil.size();i++){
Hsimil[i]->normalize(0,0.01);
Hsimil[i]->write("Hsimil.pgm");
cout << "Hsimil " << scales[i] << endl;getchar();
}
delete sv;
}
void matchBikes(DARY *img1, DARY *img2, vector<CornerDescriptor *> &corners1 , vector<CornerDescriptor *> &corners2){
vector<DARY* > Hsimil;
vector<float > scales;
float sc=0.5;
for( sc=0.5;sc<2.5;sc*=1.4){
Hsimil.push_back(new DARY(img2->y()/10,img2->x()/10,0.0));
scales.push_back(sc);
}
CornerDescSequence all_desc1;
sc=corners1[0]->getCornerScale();
all_desc1.push_back(CornerDescList(0));
for(int i=0;i<corners1.size();i++){
if(corners1[i]->getCornerScale()!=sc){
all_desc1.push_back(CornerDescList(0));
sc=corners1[i]->getCornerScale();
}
all_desc1[all_desc1.size()-1].push_back(corners1[i]);
}
CornerDescSequence all_desc2;
sc=corners2[0]->getCornerScale();
all_desc2.push_back(CornerDescList(0));
for(int i=0;i<corners2.size();i++){
if(corners2[i]->getCornerScale()!=sc){
all_desc2.push_back(CornerDescList(0));
sc=corners2[i]->getCornerScale();
}
all_desc2[all_desc2.size()-1].push_back(corners2[i]);
}
/*
int nb=0;
for(int i=0;i<all_desc1.size();i++){
cout << " cor nb " << all_desc1[i].size()<< " scale "<< all_desc1[i][0]->getCornerScale() << endl;
nb+=all_desc1[i].size();
}
cout << " all points nb "<< nb<< endl;
nb=0;
for(int i=0;i<all_desc2.size();i++){
cout << " cor nb " << all_desc2[i].size()<< " scale "<< all_desc2[i][0]->getCornerScale() << endl;
nb+=all_desc2[i].size();
}
cout << " all points nb "<< nb<< endl;
*/
matchScale(Hsimil, all_desc1,all_desc2, scales);
Hsimil.clear();
}
| 31.518765 | 146 | 0.574853 | [
"vector",
"model"
] |
1f5b26a96a260b2cdc96db76930e57e1036562c4 | 3,904 | cc | C++ | ExtinctionMonitorFNAL/Analyses/src/MARSGenParticleHist_module.cc | resnegfk/Offline | 4ba81dad54486188fa83fea8c085438d104afbbc | [
"Apache-2.0"
] | 9 | 2020-03-28T00:21:41.000Z | 2021-12-09T20:53:26.000Z | ExtinctionMonitorFNAL/Analyses/src/MARSGenParticleHist_module.cc | resnegfk/Offline | 4ba81dad54486188fa83fea8c085438d104afbbc | [
"Apache-2.0"
] | 684 | 2019-08-28T23:37:43.000Z | 2022-03-31T22:47:45.000Z | ExtinctionMonitorFNAL/Analyses/src/MARSGenParticleHist_module.cc | resnegfk/Offline | 4ba81dad54486188fa83fea8c085438d104afbbc | [
"Apache-2.0"
] | 61 | 2019-08-16T23:28:08.000Z | 2021-12-20T08:29:48.000Z | // Andrei Gaponenko, 2012
#include <string>
#include <vector>
#include <cmath>
#include <map>
#include <set>
#include <algorithm>
#include <iterator>
#include "cetlib_except/exception.h"
#include "CLHEP/Vector/ThreeVector.h"
#include "CLHEP/Units/SystemOfUnits.h"
#include "messagefacility/MessageLogger/MessageLogger.h"
#include "fhiclcpp/ParameterSet.h"
#include "art/Framework/Core/EDAnalyzer.h"
#include "art/Framework/Principal/Event.h"
#include "art/Framework/Principal/Run.h"
#include "art/Framework/Principal/Provenance.h"
#include "art/Framework/Core/ModuleMacros.h"
#include "art_root_io/TFileService.h"
#include "Offline/MCDataProducts/inc/GenParticle.hh"
#include "Offline/GeometryService/inc/GeomHandle.hh"
#include "Offline/ProtonBeamDumpGeom/inc/ProtonBeamDump.hh"
#include "TDirectory.h"
#include "TH1.h"
#include "TH2.h"
namespace mu2e {
namespace ExtMonFNAL {
//================================================================
class MARSGenParticleHist : public art::EDAnalyzer {
// Geometry for coordinate conversion
std::string geomModuleLabel_;
// GenParticleCollection to operate on
std::string inputModuleLabel_;
std::string inputInstanceName_;
// Coordinate conversion
const ProtonBeamDump *dump_;
// Output histograms
TH2* hzx_;
TH2* hxy_;
TH2* hyz_;
public:
explicit MARSGenParticleHist(const fhicl::ParameterSet& pset);
virtual void beginJob();
virtual void beginRun(const art::Run& run);
virtual void analyze(const art::Event& event);
};
//================================================================
MARSGenParticleHist::MARSGenParticleHist(const fhicl::ParameterSet& pset)
: art::EDAnalyzer(pset)
, geomModuleLabel_(pset.get<std::string>("geomModuleLabel", ""))
, inputModuleLabel_(pset.get<std::string>("inputModuleLabel"))
, inputInstanceName_(pset.get<std::string>("inputInstanceName"))
, dump_(0)
, hzx_()
, hxy_()
, hyz_()
{}
//================================================================
void MARSGenParticleHist::beginJob() {
art::ServiceHandle<art::TFileService> tfs;
hzx_ = tfs->make<TH2D>("dumpzx", "dump x vs z", 40, -10400., -7000., 40, -2200., 3200.);
hxy_ = tfs->make<TH2D>("dumpxy", "dump y vs x", 40, -2200., 3200., 40, 1500., 4700.);
hyz_ = tfs->make<TH2D>("dumpyz", "dump y vs z", 40, -10400., -7000., 40, 1500., 4700.);
}
//================================================================
void MARSGenParticleHist::beginRun(const art::Run& run) {
if(geomModuleLabel_.empty()) {
dump_ = &*GeomHandle<ProtonBeamDump>();
}
else {
// Here we retrieve geometry objects from the
// input file, as opposed to using GeometryService that might have
// a different version than used to produce our input data.
art::Handle<ProtonBeamDump> dumph;
run.getByLabel(geomModuleLabel_, "", dumph);
dump_ = &*dumph;
}
}
//================================================================
void MARSGenParticleHist::analyze(const art::Event& event) {
art::Handle<GenParticleCollection> particlesh;
event.getByLabel(inputModuleLabel_, inputInstanceName_, particlesh);
const GenParticleCollection& particles(*particlesh);
for(unsigned i=0; i < particles.size(); ++i) {
CLHEP::Hep3Vector posDump = dump_->mu2eToBeamDump_position(particles[i].position());
hzx_->Fill(posDump.z(), posDump.x());
hxy_->Fill(posDump.x(), posDump.y());
hyz_->Fill(posDump.z(), posDump.y());
} // for()
} // analyze(event)
//================================================================
} // namespace ExtMonFNAL
} // namespace mu2e
DEFINE_ART_MODULE(mu2e::ExtMonFNAL::MARSGenParticleHist);
| 32.806723 | 94 | 0.59708 | [
"geometry",
"vector"
] |
1f5db275550d373d4d8b74448225b89a9121debf | 718 | cpp | C++ | 262/B/main.cpp | tamimcsedu19/codeforces | 8e61025b99bc0a5b32cb03f736123b39dcc23f61 | [
"Apache-2.0"
] | null | null | null | 262/B/main.cpp | tamimcsedu19/codeforces | 8e61025b99bc0a5b32cb03f736123b39dcc23f61 | [
"Apache-2.0"
] | null | null | null | 262/B/main.cpp | tamimcsedu19/codeforces | 8e61025b99bc0a5b32cb03f736123b39dcc23f61 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <bits/stdc++.h>
#define maxn 100005
using namespace std;
int a,b,c;
int sumDigit(int x)
{
int sum = 0;
while(x)
{
sum+=(x%10);
x/=10;
}
return sum;
}
long long int p(int x)
{
long long res = 1;
for(int i=1;i<=a;++i)
res*=x;
return res;
}
vector<int> res;
int main()
{
cin>>a>>b>>c;
for(int i=1;i<=81;++i)
{
long long int pow = p(i);
long long int x = pow*b+c;
if((pow*b+c)>=1 && (pow*b+c)<1000000000)
{
if(sumDigit(x) == i)
res.push_back(pow*b+c);
}
}
cout<<res.size()<<"\n";
for(int i=0;i<res.size();++i)
cout<<res[i]<<" ";
}
| 15.276596 | 48 | 0.455432 | [
"vector"
] |
48f23834d171c9bf631d94b0dee49b5ffef6f8b6 | 14,709 | hpp | C++ | include/Core/Castor3D/Binary/BinaryParser.hpp | Mu-L/Castor3D | 7b9c6e7be6f7373ad60c0811d136c0004e50e76b | [
"MIT"
] | 245 | 2015-10-29T14:31:45.000Z | 2022-03-31T13:04:45.000Z | include/Core/Castor3D/Binary/BinaryParser.hpp | Mu-L/Castor3D | 7b9c6e7be6f7373ad60c0811d136c0004e50e76b | [
"MIT"
] | 64 | 2016-03-11T19:45:05.000Z | 2022-03-31T23:58:33.000Z | include/Core/Castor3D/Binary/BinaryParser.hpp | Mu-L/Castor3D | 7b9c6e7be6f7373ad60c0811d136c0004e50e76b | [
"MIT"
] | 11 | 2018-05-24T09:07:43.000Z | 2022-03-21T21:05:20.000Z | /*
See LICENSE file in root folder
*/
#ifndef ___C3D_BinaryParser_H___
#define ___C3D_BinaryParser_H___
#pragma GCC diagnostic ignored "-Wundefined-var-template"
#include "Castor3D/Binary/ChunkParser.hpp"
#include "Castor3D/Miscellaneous/Logger.hpp"
#include "Castor3D/Miscellaneous/Version.hpp"
namespace castor3d
{
template< class TParsed >
class BinaryParserBase
{
template< typename T >
friend class BinaryParserBase;
public:
virtual ~BinaryParserBase() = default;
/**
*\~english
*\brief Creates a binary parser.
*\~french
*\brief Crée un parser binaire.
*/
template< typename T >
inline BinaryParser< T > createBinaryParser()
{
BinaryParser< T > parser;
parser.m_fileVersion = m_fileVersion;
return parser;
}
/**
*\~english
*\brief From file reader function
*\param[out] obj The object to read
*\param[in] file The file containing the chunk
*\return \p false if any error occured
*\~french
*\brief Fonction de lecture à partir d'un fichier
*\param[out] obj L'objet à lire
*\param[in] file Le fichier qui contient le chunk
*\return \p false si une erreur quelconque est arrivée
*/
inline bool parse( TParsed & obj
, castor::BinaryFile & file )
{
BinaryChunk header;
bool result = header.read( file );
if ( header.getChunkType() != ChunkType::eCmshFile )
{
result = false;
checkError( result, "Not a valid CMSH file." );
}
if ( result )
{
result = doParseHeader( header );
}
if ( result )
{
result = header.checkAvailable( 1 );
checkError( result, "No more data in chunk." );
}
BinaryChunk chunk;
if ( result )
{
result = header.getSubChunk( chunk );
checkError( result, "Couldn't retrieve subchunk." );
}
if ( result )
{
result = parse( obj, chunk );
checkError( result, "Couldn't parse chunk." );
}
return result;
}
/**
*\~english
*\brief From chunk reader function
*\param[out] obj The object to read
*\param[in] chunk The chunk
*\return \p false if any error occured
*\~french
*\brief Fonction de lecture à partir d'un chunk
*\param[out] obj L'objet à lire
*\param[in] chunk Le chunk
*\return \p false si une erreur quelconque est arrivée
*/
inline bool parse( TParsed & obj
, BinaryChunk & chunk )
{
bool result = true;
if ( chunk.getChunkType() == ChunkTyper< TParsed >::Value )
{
m_chunk = &chunk;
}
else
{
result = false;
checkError( result, "Not a valid chunk for parsed type." );
}
if ( result )
{
result = doParse_v1_1( obj );
if ( result )
{
m_chunk->resetParse();
result = doParse_v1_2( obj );
}
if ( result )
{
m_chunk->resetParse();
result = doParse_v1_3( obj );
}
if ( result )
{
m_chunk->resetParse();
result = doParse_v1_4( obj );
}
if ( result )
{
m_chunk->resetParse();
result = doParse( obj );
}
if ( !result )
{
m_chunk->endParse();
}
}
return result;
}
/**
*\~english
*\brief From chunk reader function
*\param[out] obj The object to read
*\param[in] chunk The chunk
*\return \p false if any error occured
*\~french
*\brief Fonction de lecture à partir d'un chunk
*\param[out] obj L'objet à lire
*\param[in] chunk Le chunk
*\return \p false si une erreur quelconque est arrivée
*/
inline bool parse_v1_1( TParsed & obj
, BinaryChunk & chunk )
{
bool result = true;
if ( chunk.getChunkType() == ChunkTyper< TParsed >::Value )
{
m_chunk = &chunk;
}
else
{
result = false;
checkError( result, "Not a valid chunk for parsed type." );
}
if ( result )
{
result = doParse_v1_1( obj );
checkError( result, "Couldn't parse chunk." );
if ( !result )
{
m_chunk->endParse();
}
}
return result;
}
/**
*\~english
*\brief From chunk reader function
*\param[out] obj The object to read
*\param[in] chunk The chunk
*\return \p false if any error occured
*\~french
*\brief Fonction de lecture à partir d'un chunk
*\param[out] obj L'objet à lire
*\param[in] chunk Le chunk
*\return \p false si une erreur quelconque est arrivée
*/
inline bool parse_v1_2( TParsed & obj
, BinaryChunk & chunk )
{
bool result = true;
if ( chunk.getChunkType() == ChunkTyper< TParsed >::Value )
{
m_chunk = &chunk;
}
else
{
result = false;
checkError( result, "Not a valid chunk for parsed type." );
}
if ( result )
{
result = doParse_v1_2( obj );
checkError( result, "Couldn't parse chunk." );
if ( !result )
{
m_chunk->endParse();
}
}
return result;
}
/**
*\~english
*\brief From chunk reader function
*\param[out] obj The object to read
*\param[in] chunk The chunk
*\return \p false if any error occured
*\~french
*\brief Fonction de lecture à partir d'un chunk
*\param[out] obj L'objet à lire
*\param[in] chunk Le chunk
*\return \p false si une erreur quelconque est arrivée
*/
inline bool parse_v1_3( TParsed & obj
, BinaryChunk & chunk )
{
bool result = true;
if ( chunk.getChunkType() == ChunkTyper< TParsed >::Value )
{
m_chunk = &chunk;
}
else
{
result = false;
checkError( result, "Not a valid chunk for parsed type." );
}
if ( result )
{
result = doParse_v1_3( obj );
checkError( result, "Couldn't parse chunk." );
if ( !result )
{
m_chunk->endParse();
}
}
return result;
}
/**
*\~english
*\brief From chunk reader function
*\param[out] obj The object to read
*\param[in] chunk The chunk
*\return \p false if any error occured
*\~french
*\brief Fonction de lecture à partir d'un chunk
*\param[out] obj L'objet à lire
*\param[in] chunk Le chunk
*\return \p false si une erreur quelconque est arrivée
*/
inline bool parse_v1_4( TParsed & obj
, BinaryChunk & chunk )
{
bool result = true;
if ( chunk.getChunkType() == ChunkTyper< TParsed >::Value )
{
m_chunk = &chunk;
}
else
{
result = false;
checkError( result, "Not a valid chunk for parsed type." );
}
if ( result )
{
result = doParse_v1_4( obj );
checkError( result, "Couldn't parse chunk." );
if ( !result )
{
m_chunk->endParse();
}
}
return result;
}
protected:
/**
*\~english
*\brief Parses the header chunk.
*\param[in,out] chunk The parent chunk.
*\return \p false if any error occured.
*\~french
*\brief Lit le chunk d'en-tête.
*\param[in,out] chunk Le chunk.
*\return \p false si une erreur quelconque est arrivée.
*/
inline bool doParseHeader( BinaryChunk & chunk )const
{
BinaryChunk schunk;
bool result = chunk.getSubChunk( schunk );
if ( schunk.getChunkType() != ChunkType::eCmshHeader )
{
result = false;
checkError( result, "Missing header chunk." );
}
castor::String name;
uint32_t version{ 0 };
while ( result && schunk.checkAvailable( 1 ) )
{
BinaryChunk subchunk;
result = schunk.getSubChunk( subchunk );
checkError( result, "Couldn't retrieve subchunk." );
switch ( subchunk.getChunkType() )
{
case ChunkType::eName:
result = doParseChunk( name, subchunk );
break;
case ChunkType::eCmshVersion:
result = doParseChunk( version, subchunk );
checkError( result, "Couldn't parse chunk." );
if ( result )
{
m_fileVersion = Version{ int( getCmshMajor( version ) )
, int( getCmshMinor( version ) )
, int( getCmshRevision( version ) ) };
Version latestVersion{ int( getCmshMajor( CurrentCmshVersion ) )
, int( getCmshMinor( CurrentCmshVersion ) )
, int( getCmshRevision( CurrentCmshVersion ) ) };
if ( m_fileVersion < latestVersion )
{
log::warn << cuT( "This file is using version " )
<< m_fileVersion
<< cuT( ", consider upgrading it to version " )
<< latestVersion
<< cuT( "." ) << std::endl;
}
}
break;
default:
break;
}
}
if ( !result )
{
checkError( result, "Couldn't parse chunk." );
chunk.endParse();
}
return result;
}
/**
*\~english
*\brief Retrieves a value array from a chunk
*\param[out] values Receives the parsed values
*\param[out] count The values count
*\param[in] chunk The chunk containing the values
*\return \p false if any error occured
*\~french
*\brief Récupère un tableau de valeurs à partir d'un chunk
*\param[out] values Reçoit les valeurs
*\param[out] count Le compte des valeurs
*\param[in] chunk Le chunk contenant les valeurs
*\return \p false si une erreur quelconque est arrivée
*/
template< typename T >
inline bool doParseChunk( T * values
, size_t count
, BinaryChunk & chunk )const
{
return ChunkParser< T >::parse( values, count, chunk );
}
/**
*\~english
*\brief Retrieves a value array from a chunk
*\param[out] values Receives the parsed values
*\param[in] chunk The chunk containing the values
*\return \p false if any error occured
*\~french
*\brief Récupère un tableau de valeurs à partir d'un chunk
*\param[out] values Reçoit les valeurs
*\param[in] chunk Le chunk contenant les valeurs
*\return \p false si une erreur quelconque est arrivée
*/
template< typename T, size_t Count >
inline bool doParseChunk( T( &values )[Count]
, BinaryChunk & chunk )const
{
return ChunkParser< T >::parse( values, Count, chunk );
}
/**
*\~english
*\brief Retrieves a value array from a chunk
*\param[out] values Receives the parsed values
*\param[in] chunk The chunk containing the values
*\return \p false if any error occured
*\~french
*\brief Récupère un tableau de valeurs à partir d'un chunk
*\param[out] values Reçoit les valeurs
*\param[in] chunk Le chunk contenant les valeurs
*\return \p false si une erreur quelconque est arrivée
*/
template< typename T, size_t Count >
inline bool doParseChunk( std::array< T, Count > & values
, BinaryChunk & chunk )const
{
return ChunkParser< T >::parse( values.data(), Count, chunk );
}
/**
*\~english
*\brief Retrieves a value array from a chunk
*\param[out] values Receives the parsed values
*\param[in] chunk The chunk containing the values
*\return \p false if any error occured
*\~french
*\brief Récupère un tableau de valeurs à partir d'un chunk
*\param[out] values Reçoit les valeurs
*\param[in] chunk Le chunk contenant les valeurs
*\return \p false si une erreur quelconque est arrivée
*/
template< typename T >
inline bool doParseChunk( std::vector< T > & values
, BinaryChunk & chunk )const
{
return ChunkParser< T >::parse( values.data(), values.size(), chunk );
}
/**
*\~english
*\brief Retrieves a value from a chunk
*\param[out] value Receives the parsed value
*\param[in] chunk The chunk containing the value
*\return \p false if any error occured
*\~french
*\brief Récupère une valeur à partir d'un chunk
*\param[out] value Reçoit la valeur
*\param[in] chunk Le chunk contenant la valeur
*\return \p false si une erreur quelconque est arrivée
*/
template< typename T >
inline bool doParseChunk( T & value
, BinaryChunk & chunk )const
{
return ChunkParser< T >::parse( value, chunk );
}
/**
*\~english
*\brief Retrieves a subchunk.
*\param[out] chunk Receives the subchunk.
*\return \p false if any error occured.
*\~french
*\brief Récupère un sous-chunk.
*\param[out] chunk Reçoit le sous-chunk.
*\return \p false si une erreur quelconque est arrivée.
*/
inline bool doGetSubChunk( BinaryChunk & chunk )
{
CU_Require( m_chunk );
bool result = m_chunk->checkAvailable( 1 );
if ( result )
{
result = m_chunk->getSubChunk( chunk );
}
return result;
}
private:
/**
*\~english
*\brief From chunk reader function
*\param[out] obj The object to read
*\return \p false if any error occured
*\~french
*\brief Fonction de lecture à partir d'un chunk
*\param[out] obj L'objet à lire
*\return \p false si une erreur quelconque est arrivée
*/
C3D_API virtual bool doParse( TParsed & obj ) = 0;
/**
*\~english
*\brief Chunk reader function from a chunk of version 1.1.
*\param[out] obj The object to read
*\return \p false if any error occured
*\~french
*\brief Fonction de lecture à partir d'un chunk en version 1.1.
*\param[out] obj L'objet à lire
*\return \p false si une erreur quelconque est arrivée
*/
C3D_API virtual bool doParse_v1_1( TParsed & obj )
{
return true;
}
/**
*\~english
*\brief Chunk reader function from a chunk of version 1.2.
*\param[out] obj The object to read
*\return \p false if any error occured
*\~french
*\brief Fonction de lecture à partir d'un chunk en version 1.2.
*\param[out] obj L'objet à lire
*\return \p false si une erreur quelconque est arrivée
*/
C3D_API virtual bool doParse_v1_2( TParsed & obj )
{
return true;
}
/**
*\~english
*\brief Chunk reader function from a chunk of version 1.3.
*\param[out] obj The object to read
*\return \p false if any error occured
*\~french
*\brief Fonction de lecture à partir d'un chunk en version 1.3.
*\param[out] obj L'objet à lire
*\return \p false si une erreur quelconque est arrivée
*/
C3D_API virtual bool doParse_v1_3( TParsed & obj )
{
return true;
}
/**
*\~english
*\brief Chunk reader function from a chunk of version 1.4.
*\param[out] obj The object to read
*\return \p false if any error occured
*\~french
*\brief Fonction de lecture à partir d'un chunk en version 1.4.
*\param[out] obj L'objet à lire
*\return \p false si une erreur quelconque est arrivée
*/
C3D_API virtual bool doParse_v1_4( TParsed & obj )
{
return true;
}
protected:
C3D_API static castor::String Name;
inline void checkError( bool result
, castor::String const & text )const
{
if ( !result )
{
log::error << "BinaryParser< " << Name << " >: " << text << std::endl;
}
}
protected:
//!\~english The writer's chunk.
//!\~french Le chunk du writer.
BinaryChunk * m_chunk{ nullptr };
//!\~english The chunk version from the file.
//!\~french La version du chunk dans le fichier.
mutable Version m_fileVersion;
};
}
#endif
| 24.762626 | 74 | 0.627167 | [
"object",
"vector"
] |
48f2dd912c60abe7365dd8e231b50eb95256e39a | 545 | cpp | C++ | cpp/medium/xor_queries_of_a_subarray.cpp | adamlm/leetcode-solutions | 1461058ea26a6a1debaec978e86b1b25f6cba9ea | [
"MIT"
] | null | null | null | cpp/medium/xor_queries_of_a_subarray.cpp | adamlm/leetcode-solutions | 1461058ea26a6a1debaec978e86b1b25f6cba9ea | [
"MIT"
] | null | null | null | cpp/medium/xor_queries_of_a_subarray.cpp | adamlm/leetcode-solutions | 1461058ea26a6a1debaec978e86b1b25f6cba9ea | [
"MIT"
] | null | null | null | class Solution {
public:
vector<int> xorQueries(vector<int>& arr, vector<vector<int>>& queries) {
vector<int> ret;
vector<int> deltas;
auto xor_sum{0};
for (const auto& a: arr) {
xor_sum ^= a;
deltas.push_back(xor_sum);
}
for (const auto& q: queries) {
auto begin{q[0]};
auto end{q[1]};
ret.push_back(arr[begin] ^ (deltas[begin] ^ deltas[end]));
}
return ret;
}
};
| 23.695652 | 84 | 0.451376 | [
"vector"
] |
48f3916328874d296f06324c4b79f49632cf93fd | 2,161 | hpp | C++ | Mem.hpp | Galenika/csgo-offsets-finder | 5fd13006bb5fe58bed4f0a35a99142fe5a279c72 | [
"MIT"
] | 2 | 2021-02-26T08:03:30.000Z | 2021-07-14T23:28:41.000Z | Mem.hpp | RequestFX/csgo-offsets-finder | 5fd13006bb5fe58bed4f0a35a99142fe5a279c72 | [
"MIT"
] | null | null | null | Mem.hpp | RequestFX/csgo-offsets-finder | 5fd13006bb5fe58bed4f0a35a99142fe5a279c72 | [
"MIT"
] | 4 | 2021-02-03T20:08:55.000Z | 2021-07-06T17:13:14.000Z | // Made by RequestFX#1541
#pragma once
#include <Windows.h>
#include <TlHelp32.h>
#include <vector>
struct module {
uintptr_t dwBase, dwSize;
};
class Mem {
private:
inline static HANDLE handle;
public:
inline static uintptr_t procID;
~Mem() {
CloseHandle(handle);
}
uintptr_t getProcessID(const char* proc) {
HANDLE hProcessId = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); // current process
uintptr_t procID;
PROCESSENTRY32 pEntry; // process list
pEntry.dwSize = sizeof(pEntry);
do {
if (!strcmp(pEntry.szExeFile, proc)) { // process from list != current process
procID = pEntry.th32ProcessID;
CloseHandle(hProcessId);
handle = OpenProcess(PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, false, procID);
return this->procID = procID;
}
} while (Process32Next(hProcessId, &pEntry)); // Retrieves information about the next process
return NULL;
}
module getModule(uintptr_t procID, const char* modName) {
HANDLE hModule = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE | TH32CS_SNAPMODULE32, procID);
MODULEENTRY32 mEntry;
mEntry.dwSize = sizeof(mEntry);
module mod = { NULL,NULL }; // set to NULL
do {
if (!strcmp(mEntry.szModule, modName)) {
CloseHandle(hModule);
mod = { (uintptr_t)mEntry.hModule, mEntry.modBaseSize };
return mod;
}
} while (Module32Next(hModule, &mEntry));
return mod;
}
uintptr_t getAddress(uintptr_t addr, std::vector<uintptr_t> vect) {
for (unsigned int i = 0; i < vect.size(); i++) {
Toolhelp32ReadProcessMemory(procID, (BYTE*)addr, &addr, sizeof(addr), 0);
addr += vect[i];
}
return addr;
}
template <class val>
void writeMem(uintptr_t addr, val value) {
WriteProcessMemory(handle, (LPBYTE*)addr, &value, sizeof(value), NULL);
}
template <class val>
val readMem(uintptr_t addr) {
val x;
Toolhelp32ReadProcessMemory(procID, (LPBYTE*)addr, &x, sizeof(x), NULL);
return x;
}
void readString(uintptr_t addr, char* buffer, SIZE_T size) {
Toolhelp32ReadProcessMemory(procID, (LPBYTE*)addr, buffer, size, NULL);
}
}; | 25.72619 | 100 | 0.677001 | [
"vector"
] |
48ffc2516f859696703ba511a903c3e7d9f5b570 | 787 | hpp | C++ | include/NVMeSensor.hpp | serve-bh-bmc/dbus-sensors | f69fbf998745bf006748c3b6ba6558443b560d21 | [
"Apache-2.0"
] | 15 | 2019-02-26T03:44:55.000Z | 2021-11-04T23:58:51.000Z | include/NVMeSensor.hpp | serve-bh-bmc/dbus-sensors | f69fbf998745bf006748c3b6ba6558443b560d21 | [
"Apache-2.0"
] | 17 | 2019-01-23T19:47:44.000Z | 2022-03-31T23:03:43.000Z | include/NVMeSensor.hpp | serve-bh-bmc/dbus-sensors | f69fbf998745bf006748c3b6ba6558443b560d21 | [
"Apache-2.0"
] | 21 | 2019-08-07T03:32:20.000Z | 2022-01-27T09:40:22.000Z | #pragma once
#include <boost/asio/io_service.hpp>
#include <sensor.hpp>
class NVMeSensor : public Sensor
{
public:
static constexpr const char* CONFIG_TYPE =
"xyz.openbmc_project.Configuration.NVME1000";
NVMeSensor(sdbusplus::asio::object_server& objectServer,
boost::asio::io_service& io,
std::shared_ptr<sdbusplus::asio::connection>& conn,
const std::string& sensorName,
std::vector<thresholds::Threshold>&& thresholds,
const std::string& sensorConfiguration, const int busNumber);
virtual ~NVMeSensor();
NVMeSensor& operator=(const NVMeSensor& other) = delete;
int bus;
private:
sdbusplus::asio::object_server& objServer;
void checkThresholds(void) override;
};
| 27.137931 | 76 | 0.664549 | [
"vector"
] |
5b04c9626e5416e3e0d0a6ceaf65a6db35edd5c2 | 927 | hpp | C++ | Spades Game/Game/Net/NetEventDecoder.hpp | jmasterx/StemwaterSpades | 05e5d7c6d380d2f5986bd91269887f16c3e71962 | [
"Unlicense"
] | 6 | 2017-01-04T22:40:50.000Z | 2019-11-24T15:37:46.000Z | Spades Game/Game/Net/NetEventDecoder.hpp | jmasterx/StemwaterSpades | 05e5d7c6d380d2f5986bd91269887f16c3e71962 | [
"Unlicense"
] | 1 | 2016-09-18T19:10:01.000Z | 2017-08-04T23:53:38.000Z | Spades Game/Game/Net/NetEventDecoder.hpp | jmasterx/StemwaterSpades | 05e5d7c6d380d2f5986bd91269887f16c3e71962 | [
"Unlicense"
] | 2 | 2015-11-21T16:42:18.000Z | 2019-04-21T20:41:39.000Z | #ifndef CGE_NET_EVENT_DECODER_HPP
#define CGE_NET_EVENT_DECODER_HPP
#include "Game/Net/NetEventListener.hpp"
#include "Game/Net/NetMessageParser.hpp"
#include "Game/Net/SharedPlayer.hpp"
#include "Game/Net/ServerPeer.hpp"
#include <stdlib.h>
#include <vector>
namespace cge
{
class NetEventDecoder
{
std::vector<NetEventListener*> m_listeners;
NetMessageParser m_parser;
std::vector<int> m_fillIntVec;
std::vector<std::string> m_fillStrVec;
int fillIntVec(int startIndex);
int fillStrVec(int startIndex);
int decodeSharedPlayer(SharedPlayer &player, int fst);
public:
void addListener(NetEventListener* listener);
void removeListener(NetEventListener* listener);
void dispatchMessage(const std::string& message, ServerPeer* client, bool hasAuthenticated);
void dispatchConnectionFailed(bool wasConnected);
void dispatchDisconnect();
NetEventDecoder(void);
~NetEventDecoder(void);
};
}
#endif
| 28.090909 | 94 | 0.783172 | [
"vector"
] |
5b0560e6a62fd00bcaf90be0142878c1c9bfadf5 | 3,508 | hpp | C++ | Plugins/Redis/cpp_redis/tacopie/includes/tacopie/network/tcp_socket.hpp | summonFox/unified | 47ab7d051fe52c26e2928b569e9fe7aec5aa8705 | [
"MIT"
] | 111 | 2018-01-16T18:49:19.000Z | 2022-03-13T12:33:54.000Z | Plugins/Redis/cpp_redis/tacopie/includes/tacopie/network/tcp_socket.hpp | summonFox/unified | 47ab7d051fe52c26e2928b569e9fe7aec5aa8705 | [
"MIT"
] | 636 | 2018-01-17T10:05:31.000Z | 2022-03-28T20:06:03.000Z | Plugins/Redis/cpp_redis/tacopie/includes/tacopie/network/tcp_socket.hpp | summonFox/unified | 47ab7d051fe52c26e2928b569e9fe7aec5aa8705 | [
"MIT"
] | 110 | 2018-01-16T19:05:54.000Z | 2022-03-28T03:44:16.000Z | // MIT License
//
// Copyright (c) 2016-2017 Simon Ninon <simon.ninon@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#pragma once
#include <cstdint>
#include <string>
#include <vector>
#include <tacopie/typedefs.hpp>
namespace tacopie {
class tcp_socket {
public:
//! possible types of a TCP socket, either a client or a server
//! type is used to prevent the used of client specific operations on a server socket (and vice-versa)
//!
//! UNKNOWN is used when socket type could not be determined for now
enum class type {
CLIENT,
SERVER,
UNKNOWN
};
public:
//! ctor & dtor
tcp_socket(void);
~tcp_socket(void) = default;
//! custom ctor
//! build socket from existing file descriptor
tcp_socket(fd_t fd, const std::string& host, std::uint32_t port, type t);
//! move ctor
tcp_socket(tcp_socket&&);
//! copy ctor & assignment operator
tcp_socket(const tcp_socket&) = delete;
tcp_socket& operator=(const tcp_socket&) = delete;
public:
//! comparison operator
bool operator==(const tcp_socket& rhs) const;
bool operator!=(const tcp_socket& rhs) const;
public:
//! client socket operations
std::vector<char> recv(std::size_t size_to_read);
std::size_t send(const std::vector<char>& data, std::size_t size_to_write);
void connect(const std::string& host, std::uint32_t port);
//! server socket operations
void bind(const std::string& host, std::uint32_t port);
void listen(std::size_t max_connection_queue);
tcp_socket accept(void);
//! general socket operations
void close(void);
public:
//! get socket name information
const std::string& get_host(void) const;
std::uint32_t get_port(void) const;
//! get socket type
type get_type(void) const;
//! set type, should be used if some operations determining socket type
//! have been done on the behalf of the tcp_socket instance
void set_type(type t);
//! direct access to the underlying fd
fd_t get_fd(void) const;
private:
//! create a new socket if no socket has been initialized yet
void create_socket_if_necessary(void);
//! check whether the current socket has an approriate type for that kind of operation
//! if current type is UNKNOWN, update internal type with given type
void check_or_set_type(type t);
private:
//! fd associated to the socket
fd_t m_fd;
//! socket name information
std::string m_host;
std::uint32_t m_port;
//! type of the socket
type m_type;
};
} //! tacopie
| 30.504348 | 104 | 0.726055 | [
"vector"
] |
5b08e42c8ed2eadd87ca4b7d01082c00a359e475 | 1,685 | cpp | C++ | Codeforces/1029/d.cpp | eyangch/competitive-programming | 59839efcec72cb792e61b7d316f83ad54f16a166 | [
"MIT"
] | 14 | 2019-08-14T00:43:10.000Z | 2021-12-16T05:43:31.000Z | Codeforces/1029/d.cpp | eyangch/competitive-programming | 59839efcec72cb792e61b7d316f83ad54f16a166 | [
"MIT"
] | null | null | null | Codeforces/1029/d.cpp | eyangch/competitive-programming | 59839efcec72cb792e61b7d316f83ad54f16a166 | [
"MIT"
] | 6 | 2020-12-30T03:30:17.000Z | 2022-03-11T03:40:02.000Z | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<ll> vi;
typedef pair<ll, ll> pii;
template <typename T1, typename T2>
ostream &operator <<(ostream &os, pair<T1, T2> p){os << p.first << " " << p.second; return os;}
template <typename T>
ostream &operator <<(ostream &os, vector<T> &v){for(T i : v)os << i << ", "; return os;}
template <typename T>
ostream &operator <<(ostream &os, set<T> s){for(T i : s) os << i << ", "; return os;}
template <typename T1, typename T2>
ostream &operator <<(ostream &os, map<T1, T2> m){for(pair<T1, T2> i : m) os << i << endl; return os;}
ll N, K, og[200000];
pii a[11][200000];
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> N >> K;
for(ll i = 0; i < N; i++){
cin >> a[0][i].first;
og[i] = a[0][i].first;
a[0][i].first %= K;
a[0][i].second = i;
for(ll j = 1; j < 11; j++){
a[j][i].first = (a[j-1][i].first * 10) % K;
a[j][i].second = i;
}
}
for(ll i = 0; i < 11; i++){
sort(a[i], a[i]+N);
}
ll ans = 0;
ll prev = -1;
for(ll i = 0; i < N; i++){
ll id = a[0][i].second;
ll val = a[0][i].first;
ll len = to_string(og[id]).length();
auto it1 = upper_bound(a[len],a[len]+N, pii((K-val)%K, INT_MAX));
auto it2 = lower_bound(a[len],a[len]+N, pii((K-val)%K, 0));
if(it1 - it2 < 0) continue;
for(ll j = 0; j < len; j++){
val *= 10;
val %= K;
}
if((val + a[0][i].first) % K == 0){
ans--;
}
ans += it1 - it2;
}
cout << ans << endl;
return 0;
}
| 28.083333 | 101 | 0.478338 | [
"vector"
] |
5b19c64c746d20235bbe9a5df56c4f7a8ba974fb | 4,720 | cpp | C++ | AdvancedGraphics/gameobject.cpp | Trodek/Advanced-Graphics-Subject | 5e89fa33a3bc5c4e0910cfae907a22f879be035a | [
"MIT"
] | null | null | null | AdvancedGraphics/gameobject.cpp | Trodek/Advanced-Graphics-Subject | 5e89fa33a3bc5c4e0910cfae907a22f879be035a | [
"MIT"
] | null | null | null | AdvancedGraphics/gameobject.cpp | Trodek/Advanced-Graphics-Subject | 5e89fa33a3bc5c4e0910cfae907a22f879be035a | [
"MIT"
] | null | null | null | #include "gameobject.h"
#include "transform.h"
#include "scene.h"
#include <QJsonObject>
#include <QJsonArray>
#include "appmanager.h"
#include "modelrender.h"
#include "light.h"
// All GameObjects start with a transform
GameObject::GameObject()
{
AddComponent(Component::Type::Transform);
}
GameObject::~GameObject()
{
for(Component* c : components)
{
delete c;
}
components.clear();
for(GameObject* go: children)
{
delete go;
}
children.clear();
}
const char *GameObject::GetName() const
{
return name.c_str();
}
void GameObject::SetName(const char *name)
{
this->name = name;
}
Component *GameObject::GetComponentByType(Component::Type type) const
{
Component* ret = nullptr;
for(Component* c : components)
{
if(c->GetType() == type)
{
ret = c;
break;
}
}
return ret;
}
Component *GameObject::GetComponentByID(int id) const
{
if(id < components.size())
return components[id];
return nullptr;
}
int GameObject::NumComponents() const
{
return components.size();
}
Component* GameObject::AddComponent(Component::Type type)
{
Component* ret = nullptr;
switch (type) {
case Component::Type::Transform:
if(GetComponentByType(type) == nullptr)
ret = new Transform();
break;
case Component::Type::ModelRenderer:
if(GetComponentByType(type) == nullptr)
ret = new ModelRender();
break;
case Component::Type::Light:
if(GetComponentByType(type) == nullptr)
ret = new Light();
default:
break;
}
if(ret != nullptr)
{
components.push_back(ret);
}
return ret;
}
// Removes all components of "type" from the gameobject
void GameObject::RemoveComponent(Component::Type type)
{
for(std::vector<Component*>::iterator c = components.begin(); c != components.end(); c++)
{
if((*c)->GetType() == type)
{
delete *c;
components.erase(c);
}
}
}
void GameObject::RemoveComponent(int id)
{
if(id < components.size() )
{
int i = 0;
for(std::vector<Component*>::iterator c = components.begin(); c != components.end(); c++)
{
if(i == id)
{
delete *c;
components.erase(c);
break;
}
i++;
}
}
}
GameObject *GameObject::GetChild(int id) const
{
if(id < children.size())
return children[id];
return nullptr;
}
GameObject *GameObject::GetChild(std::string name) const
{
GameObject* ret = nullptr;
for(GameObject* go : children)
{
if(go->name == name)
{
ret = go;
break;
}
}
return ret;
}
int GameObject::NumChildren() const
{
return children.size();
}
void GameObject::AddChild(GameObject *go)
{
if(go != nullptr)
children.push_back(go);
}
void GameObject::RemoveChild(GameObject *go)
{
for(std::vector<GameObject*>::iterator c = children.begin(); c != children.end();c++)
{
if(go == *c)
{
delete *c;
children.erase(c);
break;
}
}
}
void GameObject::RemoveChild(int id)
{
if(id < children.size())
{
int i = 0;
for(std::vector<GameObject*>::iterator c = children.begin(); c != children.end();c++)
{
if(i == id)
{
delete *c;
children.erase(c);
break;
}
i++;
}
}
}
void GameObject::Save(QJsonObject &file) const
{
file["name"] = name.c_str();
QJsonArray comp;
for(std::vector<Component*>::const_iterator c = components.begin(); c != components.end(); c++)
{
QJsonObject compObject;
(*c)->Save(compObject);
comp.append(compObject);
}
file["Components"] = comp;
}
void GameObject::Load(const QJsonObject &file)
{
if(file.contains("name") && file["name"].isString())
SetName(file["name"].toString().toUtf8());
if(file.contains("Components") && file["Components"].isArray())
{
QJsonArray compObjects = file["Components"].toArray();
for(int i = 0; i< compObjects.size();++i)
{
QJsonObject comp = compObjects[i].toObject();
Component::Type type = (Component::Type)comp["type"].toInt();
Component* c = nullptr;
if(type == Component::Type::Transform)
c = GetComponentByType(type);
else
c = AddComponent(type);
c->Load(comp);
}
}
}
| 20.611354 | 99 | 0.54428 | [
"vector",
"transform"
] |
5b1a285046f251656788c88d6f010c3f0cadf2a3 | 32,422 | cpp | C++ | cradle/src/alia/ui/utilities/styling.cpp | dotdecimal/open-cradle | f8b06f8d40b0f17ac8d2bf845a32fcd57bf5ce1d | [
"MIT"
] | null | null | null | cradle/src/alia/ui/utilities/styling.cpp | dotdecimal/open-cradle | f8b06f8d40b0f17ac8d2bf845a32fcd57bf5ce1d | [
"MIT"
] | null | null | null | cradle/src/alia/ui/utilities/styling.cpp | dotdecimal/open-cradle | f8b06f8d40b0f17ac8d2bf845a32fcd57bf5ce1d | [
"MIT"
] | 4 | 2018-09-28T17:12:54.000Z | 2022-03-20T14:22:29.000Z | #include <alia/ui/utilities/styling.hpp>
#include <alia/ui/utilities.hpp>
#include <sstream>
#include <cctype>
#include <utf8.h>
namespace alia {
// STYLE TREE MANIPULATION
static style_tree*
get_style_tree_child(style_tree& tree, string const& child_name,
bool create_if_missing)
{
if (create_if_missing)
{
style_tree_ptr& child = tree.substyles[child_name];
if (!child)
child.reset(new style_tree);
return child.get();
}
else
{
std::map<string,style_tree_ptr>::iterator child =
tree.substyles.find(child_name);
return child != tree.substyles.end() ? child->second.get() : 0;
}
}
static style_tree*
find_style_node(style_tree& tree, string const& subpath,
bool create_if_missing)
{
std::size_t first_slash = subpath.find('/');
if (first_slash == string::npos)
{
if (subpath.empty())
return &tree;
else
return get_style_tree_child(tree, subpath, create_if_missing);
}
string child_name = subpath.substr(0, first_slash),
rest_of_path = subpath.substr(first_slash + 1);
// This is a little too permissive, since it would accept paths like
// 'a///b', but there's nothing really wrong with that.
if (child_name.empty())
return find_style_node(tree, rest_of_path, create_if_missing);
style_tree* child = get_style_tree_child(tree, child_name, true);
return child ? find_style_node(*child, rest_of_path, true) : 0;
}
static std::list<style_tree*>
resolve_flattened_fallbacks(
style_tree& tree, std::list<string> const& flattened)
{
std::list<style_tree*> fallbacks;
for (std::list<string>::const_iterator
i = flattened.begin(); i != flattened.end(); ++i)
{
style_tree* node = find_style_node(tree, *i, false);
if (!node)
throw exception("style not found: " + *i);
fallbacks.push_back(node);
}
return fallbacks;
}
void set_style(style_tree& tree, string const& subpath,
flattened_style_node const& flattened)
{
std::list<style_tree*> fallbacks =
resolve_flattened_fallbacks(tree, flattened.fallbacks);
style_tree* node = find_style_node(tree, subpath, true);
node->properties = flattened.properties;
swap(node->fallbacks, fallbacks);
}
style_tree_ptr unflatten_style_tree(flattened_style_tree const& flattened)
{
style_tree_ptr tree;
tree.reset(new style_tree);
for (flattened_style_tree::const_iterator i = flattened.begin();
i != flattened.end(); ++i)
{
set_style(*tree, i->first, i->second);
}
return tree;
}
static string const*
get_style_property(style_tree const& tree, char const* property_name)
{
property_map::const_iterator i = tree.properties.find(property_name);
if (i != tree.properties.end())
return &i->second;
for (std::list<style_tree*>::const_iterator
i = tree.fallbacks.begin(); i != tree.fallbacks.end(); ++i)
{
string const* property = get_style_property(**i, property_name);
if (property)
return property;
}
return 0;
}
string const*
get_style_property(
style_search_path const* path, char const* property_name,
style_search_flag_set flags)
{
for (; path; path = path->rest)
{
if (!path->tree)
{
if (flags & INHERITED_PROPERTY)
continue;
else
break;
}
string const* property =
get_style_property(*path->tree, property_name);
if (property)
return property;
}
return 0;
}
static style_tree const*
find_substyle(
style_tree const& tree, string const& substyle_name)
{
std::map<string,style_tree_ptr>::const_iterator i =
tree.substyles.find(substyle_name);
if (i != tree.substyles.end())
return i->second.get();
for (std::list<style_tree*>::const_iterator
i = tree.fallbacks.begin(); i != tree.fallbacks.end(); ++i)
{
style_tree const* tree = find_substyle(**i, substyle_name);
if (tree)
return tree;
}
return 0;
}
static style_tree const*
find_substyle(
style_search_path const* path, string const& substyle_name)
{
for (; path; path = path->rest)
{
if (path->tree)
{
style_tree const* tree = find_substyle(*path->tree, substyle_name);
if (tree)
return tree;
}
}
return 0;
}
static string widget_state_string(widget_state state)
{
string s;
switch (state.code & WIDGET_PRIMARY_STATE_MASK_CODE)
{
case WIDGET_DISABLED_CODE:
s = ".disabled";
break;
case WIDGET_HOT_CODE:
s = ".hot";
break;
case WIDGET_DEPRESSED_CODE:
s = ".depressed";
break;
case WIDGET_SELECTED_CODE:
s = ".selected";
break;
case WIDGET_NORMAL_CODE:
default:
s = ".normal";
break;
}
if (state & WIDGET_FOCUSED)
s += ".focused";
return s;
}
static style_search_path const*
add_substyle_to_path(style_search_path* storage,
style_search_path const* path, style_tree const* substyle)
{
if (substyle)
{
storage->tree = substyle;
storage->rest = path;
return storage;
}
else
return path;
}
static style_search_path const*
add_path_separator(style_search_path* storage, style_search_path const* path)
{
storage->tree = 0;
storage->rest = path;
return storage;
}
style_search_path const*
add_substyle_to_path(
style_path_storage* storage,
style_search_path const* search_path,
style_search_path const* rest,
string const& substyle_name,
add_substyle_flag_set flags)
{
style_tree const* substyle = find_substyle(search_path, substyle_name);
return
(substyle || !(flags & ADD_SUBSTYLE_IFF_EXISTS))
? add_substyle_to_path(&storage->nodes[1],
(flags & ADD_SUBSTYLE_NO_PATH_SEPARATOR) ?
rest : add_path_separator(&storage->nodes[0], rest),
substyle)
: rest;
}
style_search_path const*
add_substyle_to_path(
stateful_style_path_storage* storage,
style_search_path const* search_path,
style_search_path const* rest,
string const& substyle_name,
widget_state state,
add_substyle_flag_set flags)
{
style_search_path const* path;
// Start off with the stateless version as a fallback.
path = add_substyle_to_path(&storage->nodes[1],
(flags & ADD_SUBSTYLE_NO_PATH_SEPARATOR) ?
rest : add_path_separator(&storage->nodes[0], rest),
find_substyle(search_path, substyle_name));
// If the state has multiple components, try them individually as
// fallbacks.
if (state & WIDGET_FOCUSED)
{
{
widget_state substate(state.code & ~WIDGET_FOCUSED_CODE);
path = add_substyle_to_path(&storage->nodes[2], path,
find_substyle(search_path,
substyle_name + widget_state_string(substate)));
}
if ((state & WIDGET_PRIMARY_STATE_MASK) != WIDGET_NORMAL)
{
widget_state substate(
state.code & ~WIDGET_PRIMARY_STATE_MASK_CODE);
path = add_substyle_to_path(&storage->nodes[3], path,
find_substyle(search_path,
substyle_name + widget_state_string(substate)));
}
}
// Add the original state itself.
path = add_substyle_to_path(&storage->nodes[4], path,
find_substyle(search_path,
substyle_name + widget_state_string(state)));
return path;
}
// WHOLE TREE I/O
unicode_char_t static
next_utf8_char(utf8_ptr* start, utf8_ptr const& end)
{
return utf8::next(*start, end);
}
unicode_char_t static
prev_utf8_char(utf8_ptr* start, utf8_ptr const& end)
{
return utf8::prior(*start, end);
}
static utf8_ptr skip_space(utf8_string const& text, int& line_count)
{
utf8_ptr p = text.begin;
while (p < text.end)
{
utf8_ptr q = p;
unicode_char_t c = next_utf8_char(&p, text.end);
if (!is_space(c))
return q;
if (is_line_terminator(c))
{
++line_count;
p = skip_line_terminator(utf8_string(q, text.end));
}
}
return text.end;
}
static utf8_ptr find_end_of_fallback_path(utf8_string const& text)
{
utf8_ptr p = text.begin;
while (p < text.end)
{
utf8_ptr q = p;
unicode_char_t c = next_utf8_char(&p, text.end);
if (is_space(c) || c == ',' || c == '{')
return q;
}
return text.end;
}
static std::list<string>
parse_fallbacks(char const* label, utf8_string const& text,
utf8_ptr& p, int& line_number)
{
std::list<string> fallbacks;
while (1)
{
p = skip_space(utf8_string(p, text.end), line_number);
utf8_ptr subpath_start = p;
p = find_end_of_fallback_path(utf8_string(p, text.end));
fallbacks.push_back(string(subpath_start, p - subpath_start));
p = skip_space(utf8_string(p, text.end), line_number);
utf8_ptr q = p;
unicode_char_t c = next_utf8_char(&p, text.end);
if (c == '{')
{
p = q;
break;
}
else if (c == ',')
{
continue;
}
else
{
throw parse_error(string(label) + ":" +
to_string(line_number) + ": syntax error");
}
}
return fallbacks;
}
static property_map
parse_style_properties(char const* label, utf8_string const& text,
utf8_ptr& p, int& line_number)
{
property_map properties;
while (1)
{
p = skip_space(utf8_string(p, text.end), line_number);
// Check for a closing brace.
SkUnichar c = peek(utf8_string(p, text.end));
if (c == '}')
{
next_utf8_char(&p, text.end);
break;
}
// Parse the name.
utf8_ptr name_start = p, name_end;
bool name_ended = false;
while (1)
{
utf8_ptr q = p;
unicode_char_t c = next_utf8_char(&p, text.end);
if (c == ':')
{
name_end = q;
break;
}
if (is_space(c))
{
throw parse_error(string(label) + ":" +
to_string(line_number) + ": syntax error");
}
}
string name(name_start, name_end - name_start);
p = skip_space(utf8_string(p, text.end), line_number);
// Parse the value.
utf8_ptr value_start = p, value_end;
while (1)
{
utf8_ptr q = p;
unicode_char_t c = next_utf8_char(&p, text.end);
if (c == '}')
{
// Don't consume the closing brace.
p = q;
value_end = q;
break;
}
if (c == ';')
{
value_end = q;
break;
}
if (is_line_terminator(c))
{
p = skip_line_terminator(utf8_string(q, text.end));
++line_number;
value_end = q;
break;
}
}
string value(value_start, value_end - value_start);
properties[name] = value;
}
return properties;
}
static void append_span(string& dst, utf8_ptr begin, utf8_ptr end)
{
while (begin != end)
{
dst.push_back(*begin);
++begin;
}
}
static string strip_comments(utf8_string const& text)
{
string code;
code.reserve(text.end - text.begin);
utf8_ptr p = text.begin;
int comment_depth = 0;
SkUnichar last_char = 0;
utf8_ptr span_start = text.begin;
while (p != text.end)
{
utf8_ptr q = p;
unicode_char_t c = next_utf8_char(&p, text.end);
switch (c)
{
case '*':
if (last_char == '/')
{
if (comment_depth == 0)
append_span(code, span_start, q - 1);
++comment_depth;
last_char = 0;
continue;
}
break;
case '/':
if (last_char == '*')
{
if (comment_depth > 0)
{
--comment_depth;
span_start = p;
last_char = 0;
continue;
}
}
break;
}
last_char = c;
if (comment_depth > 0 && is_line_terminator(c))
{
p = skip_line_terminator(utf8_string(q, text.end));
code.push_back('\n');
}
}
append_span(code, span_start, text.end);
return code;
}
style_tree_ptr
parse_style_description(char const* label, utf8_string const& text)
{
style_tree_ptr tree;
tree.reset(new style_tree);
int line_number = 1;
string stripped = strip_comments(text);
utf8_string stripped_text = as_utf8_string(stripped);
utf8_ptr p = stripped_text.begin;
while (1)
{
p = skip_space(utf8_string(p, stripped_text.end), line_number);
if (p == stripped_text.end)
break;
// Parse the substyle name.
utf8_ptr next_space =
find_next_space(utf8_string(p, stripped_text.end));
string subpath(p, next_space - p);
p = next_space;
p = skip_space(utf8_string(p, stripped_text.end), line_number);
flattened_style_node node;
// Check for fallbacks.
unicode_char_t c = next_utf8_char(&p, text.end);
if (c == ':')
{
node.fallbacks =
parse_fallbacks(label, stripped_text, p, line_number);
c = next_utf8_char(&p, text.end);
}
// Check for the opening brace of the property map.
if (c != '{')
{
throw parse_error(string(label) + ":" + to_string(line_number) +
": syntax error");
}
// Parse the property map.
node.properties =
parse_style_properties(label, stripped_text, p, line_number);
// Add the substyle to the tree.
set_style(*tree, subpath, node);
}
return tree;
}
style_tree_ptr parse_style_file(char const* path)
{
FILE* f = fopen(path, "rb");
if (!f)
throw open_file_error("unable to open file: " + string(path));
fseek(f, 0, SEEK_END);
int file_length = ftell(f);
fseek(f, 0, SEEK_SET);
// Is it really necessary to terminate the string?
std::vector<char> text(file_length + 1);
size_t count = fread(&text[0], 1, file_length, f);
fclose(f);
if (count != file_length)
throw parse_error("unable to read file: " + string(path));
text[file_length] = '\0';
return parse_style_description(path,
utf8_string(&text[0], &text[0] + file_length));
}
static int write_cpp_style_node(FILE* f, style_tree const& node,
int* index_counter)
{
int index = *index_counter;
++*index_counter;
fprintf(f, " alia::style_tree node_%i;\n", index);
for (property_map::const_iterator
i = node.properties.begin(); i != node.properties.end(); ++i)
{
fprintf(f, " node_%i.properties[\"%s\"] = \"%s\";\n",
index, i->first.c_str(), i->second.c_str());
}
for (std::map<string,style_tree_ptr>::const_iterator
i = node.substyles.begin(); i != node.substyles.end(); ++i)
{
int substyle_index =
write_cpp_style_node(f, *i->second, index_counter);
fprintf(f, " node_%i.substyles[\"%s\"] = node_%i;\n",
index, i->first.c_str(), substyle_index);
}
return index;
}
void write_style_cpp_file(char const* path, char const* label,
style_tree const& style)
{
FILE* f = fopen(path, "wb");
if (!f)
throw exception("unable to open file: " + string(path));
fprintf(f, "alia::style_tree %s()\n", label);
fprintf(f, "{\n");
int node_n = 0;
write_cpp_style_node(f, style, &node_n);
fprintf(f, " return node_0;\n");
fprintf(f, "}\n");
}
// LINE PARSING
void initialize_line_parser(line_parser& p, char const* text, size_t size)
{
p.text = text;
p.text_size = size;
p.p = text;
}
void initialize_line_parser(line_parser& p, std::string const& text)
{
initialize_line_parser(p, text.c_str(), text.length());
}
void throw_unexpected_char(line_parser& p)
{
char buf[64];
sprintf(buf, "unexpected character: \'%c\' (0x%02x)",
peek(p), int(peek(p)));
throw parse_error(buf);
}
void check_char(line_parser& p, char expected)
{
if (peek(p) != expected)
throw_unexpected_char(p);
advance(p);
}
void check_eol(line_parser& p)
{
if (!is_eol(p))
throw_unexpected_char(p);
}
bool is_empty(line_parser& p)
{
skip_space(p);
return is_eol(p);
}
void check_empty(line_parser& p)
{
if (!is_empty(p))
throw_unexpected_char(p);
}
void skip_space(line_parser& p)
{
while (std::isspace(peek(p)))
advance(p);
}
void parse(line_parser& p, double* x)
{
skip_space(p);
char* end;
double d = strtod(p.p, &end);
if (end == p.p)
throw parse_error("expected number");
p.p = end;
*x = d;
}
void parse(line_parser& p, float* x)
{
double d;
parse(p, &d);
*x = float(d);
}
void parse(line_parser& p, int* x)
{
skip_space(p);
char* end;
int i = int(strtol(p.p, &end, 10));
if (end == p.p)
throw parse_error("expected integer");
p.p = end;
*x = i;
}
string read_string(line_parser& p)
{
skip_space(p);
string s;
while (!is_eol(p))
{
char c = peek(p);
if (std::isspace(c))
break;
s.push_back(c);
advance(p);
}
return s;
}
// PROPERTY UTILITIES
// colors
void parse(line_parser& p, rgba8* color)
{
check_char(p, '#');
uint8_t digits[8];
int n_digits = 0;
while (1)
{
char c = peek(p);
uint8_t digit;
if (c == '\0' || isspace(c))
break;
else if (n_digits >= 8)
throw parse_error("too many digits in color code");
else if (c >= '0' && c <= '9')
digit = uint8_t(c - '0');
else if (c >= 'a' && c <= 'f')
digit = 10 + uint8_t(c - 'a');
else if (c >= 'A' && c <= 'F')
digit = 10 + uint8_t(c - 'A');
else
throw_unexpected_char(p);
digits[n_digits] = digit;
++n_digits;
advance(p);
}
switch (n_digits)
{
case 3:
*color = rgba8(
(digits[0] << 4) + digits[0],
(digits[1] << 4) + digits[1],
(digits[2] << 4) + digits[2],
0xff);
break;
case 4:
*color = rgba8(
(digits[0] << 4) + digits[0],
(digits[1] << 4) + digits[1],
(digits[2] << 4) + digits[2],
(digits[3] << 4) + digits[3]);
break;
case 6:
*color = rgba8(
(digits[0] << 4) + digits[1],
(digits[2] << 4) + digits[3],
(digits[4] << 4) + digits[5],
0xff);
break;
case 8:
*color = rgba8(
(digits[0] << 4) + digits[1],
(digits[2] << 4) + digits[3],
(digits[4] << 4) + digits[5],
(digits[6] << 4) + digits[7]);
break;
default:
throw parse_error("color code digit count is invalid");
}
}
rgba8
get_color_property(style_search_path const* path, char const* property_name)
{
return get_property(path, property_name, INHERITED_PROPERTY, rgba8(black));
}
rgba8
get_color_property(dataless_ui_context& ctx, char const* property_name)
{
return get_property(ctx.style.path, property_name, INHERITED_PROPERTY,
rgba8(black));
}
// layout properties
void parse(line_parser& p, layout_units* units)
{
skip_space(p);
char c0 = peek(p);
if (c0 == '\0')
throw parse_error("invalid units");
advance(p);
char c1 = peek(p);
if (c1 == '\0')
throw parse_error("invalid units");
advance(p);
if (!is_eol(p) && !std::isspace(peek(p)))
throw_unexpected_char(p);
switch (c0)
{
case 'i':
if (c1 == 'n')
{
*units = INCHES;
return;
}
break;
case 'c':
if (c1 == 'm')
{
*units = CM;
return;
}
break;
case 'm':
if (c1 == 'm')
{
*units = MM;
return;
}
break;
case 'e':
if (c1 == 'm')
{
*units = EM;
return;
}
if (c1 == 'x')
{
*units = EX;
return;
}
break;
case 'p':
if (c1 == 't')
{
*units = POINT;
return;
}
if (c1 == 'c')
{
*units = PICA;
return;
}
if (c1 == 'x')
{
*units = PIXELS;
return;
}
break;
}
throw parse_error("invalid units");
}
void parse(line_parser& p, absolute_length* spec)
{
skip_space(p);
parse(p, &spec->length);
skip_space(p);
parse(p, &spec->units);
}
void parse(line_parser& p, absolute_size* spec)
{
parse(p, &(*spec)[0]);
if (!is_empty(p))
parse(p, &(*spec)[1]);
else
(*spec)[1] = (*spec)[0];
}
void parse(line_parser& p, relative_length* spec)
{
skip_space(p);
parse(p, &spec->length);
skip_space(p);
if (peek(p) == '%')
{
spec->is_relative = true;
spec->length /= 100;
advance(p);
if (!is_eol(p) && !std::isspace(peek(p)))
throw_unexpected_char(p);
}
else
{
spec->is_relative = false;
parse(p, &spec->units);
}
}
void parse(line_parser& p, relative_size* spec)
{
parse(p, &(*spec)[0]);
if (!is_empty(p))
parse(p, &(*spec)[1]);
else
(*spec)[1] = (*spec)[0];
}
template<class Side>
void fill_in_missing_sides(Side* sides, int n_sides)
{
if (n_sides < 2)
sides[1] = sides[0];
if (n_sides < 3)
sides[2] = sides[0];
if (n_sides < 4)
sides[3] = sides[1];
}
void parse(line_parser& p, box_border_width<absolute_length>* border)
{
absolute_length sides[4];
int n_sides = 0;
while (1)
{
skip_space(p);
if (is_eol(p))
break;
if (n_sides >= 4)
throw_unexpected_char(p);
parse(p, &sides[n_sides++]);
}
if (n_sides == 0)
throw parse_error("empty border width list");
fill_in_missing_sides(sides, n_sides);
border->top = sides[0];
border->right = sides[1];
border->bottom = sides[2];
border->left = sides[3];
}
void parse(line_parser& p, box_corner_sizes* spec)
{
relative_length specs[2][4];
int n_specs[2] = { 0, 0 };
for (int i = 0; i != 2; ++i)
{
while (1)
{
skip_space(p);
if (is_eol(p))
break;
if (i == 0 && peek(p) == '/')
{
advance(p);
break;
}
if (n_specs[i] >= 4)
throw_unexpected_char(p);
parse(p, &specs[i][n_specs[i]++]);
}
}
if (n_specs[0] == 0)
throw parse_error("empty corner list");
fill_in_missing_sides(specs[0], n_specs[0]);
if (n_specs[1] == 0)
{
for (int i = 0; i != 4; ++i)
specs[1][i] = specs[0][i];
}
else
fill_in_missing_sides(specs[1], n_specs[1]);
for (int i = 0; i != 4; ++i)
spec->corners[i] = make_vector(specs[0][i], specs[1][i]);
}
resolved_box_corner_sizes
resolve_box_corner_sizes(layout_traversal& traversal,
box_corner_sizes const& spec, vector<2,float> const& full_size)
{
resolved_box_corner_sizes sizes;
for (int i = 0; i != 4; ++i)
{
sizes.corners[i] =
resolve_relative_size(traversal, spec.corners[i], full_size);
}
return sizes;
}
void parse(line_parser& p, side_selection* spec)
{
side_selection sides = NO_FLAGS;
while (1)
{
string s = read_string(p);
if (s.empty())
break;
if (s == "left")
sides |= LEFT_SIDE;
if (s == "right")
sides |= RIGHT_SIDE;
if (s == "top")
sides |= TOP_SIDE;
if (s == "bottom")
sides |= BOTTOM_SIDE;
}
*spec = sides;
}
box_border_width<absolute_length>
get_padding_property(
style_search_path const* path, absolute_length const& default_width)
{
box_border_width<absolute_length> unified =
get_property(path, "padding", UNINHERITED_PROPERTY,
box_border_width<absolute_length>(default_width));
return box_border_width<absolute_length>(
get_property(path, "padding-top", UNINHERITED_PROPERTY,
unified.top),
get_property(path, "padding-right", UNINHERITED_PROPERTY,
unified.right),
get_property(path, "padding-bottom", UNINHERITED_PROPERTY,
unified.bottom),
get_property(path, "padding-left", UNINHERITED_PROPERTY,
unified.left));
}
box_border_width<absolute_length>
get_margin_property(
style_search_path const* path, absolute_length const& default_width)
{
box_border_width<absolute_length> unified =
get_property(path, "margin", UNINHERITED_PROPERTY,
box_border_width<absolute_length>(default_width));
return box_border_width<absolute_length>(
get_property(path, "margin-top", UNINHERITED_PROPERTY,
unified.top),
get_property(path, "margin-right", UNINHERITED_PROPERTY,
unified.right),
get_property(path, "margin-bottom", UNINHERITED_PROPERTY,
unified.bottom),
get_property(path, "margin-left", UNINHERITED_PROPERTY,
unified.left));
}
box_border_width<absolute_length>
get_border_width_property(
style_search_path const* path, absolute_length const& default_width)
{
box_border_width<absolute_length> unified =
get_property(path, "border-width", UNINHERITED_PROPERTY,
box_border_width<absolute_length>(default_width));
return box_border_width<absolute_length>(
get_property(path, "border-top-width", UNINHERITED_PROPERTY,
unified.top),
get_property(path, "border-right-width", UNINHERITED_PROPERTY,
unified.right),
get_property(path, "border-bottom-width", UNINHERITED_PROPERTY,
unified.bottom),
get_property(path, "border-left-width", UNINHERITED_PROPERTY,
unified.left));
}
box_corner_sizes
get_border_radius_property(
style_search_path const* path, relative_length const& default_radius)
{
box_corner_sizes unified =
get_property(path, "border-radius", UNINHERITED_PROPERTY,
box_corner_sizes(
make_vector(default_radius, default_radius)));
return box_corner_sizes(
get_property(path, "border-top-left-radius", UNINHERITED_PROPERTY,
unified.corners[0]),
get_property(path, "border-top-right-radius", UNINHERITED_PROPERTY,
unified.corners[1]),
get_property(path, "border-bottom-right-radius", UNINHERITED_PROPERTY,
unified.corners[2]),
get_property(path, "border-bottom-left-radius", UNINHERITED_PROPERTY,
unified.corners[3]));
}
// higher-level retrieval
font get_font_properties(ui_system const& ui, style_search_path const* path)
{
return font(
get_property(path, "font-family", INHERITED_PROPERTY, string("arial")),
get_property(path, "font-size", INHERITED_PROPERTY, 13.f) *
ui.style.magnification,
(get_property(path, "font-bold", INHERITED_PROPERTY, false) ?
BOLD : NO_FLAGS) |
(get_property(path, "font-italic", INHERITED_PROPERTY, false) ?
ITALIC : NO_FLAGS) |
(get_property(path, "font-underline", INHERITED_PROPERTY, false) ?
UNDERLINE : NO_FLAGS) |
(get_property(path, "font-strikethrough", INHERITED_PROPERTY, false) ?
STRIKETHROUGH : NO_FLAGS));
}
void read_primary_style_properties(
ui_system const& ui,
primary_style_properties* props,
style_search_path const* path)
{
props->text_color = get_color_property(path, "color");
props->background_color = get_color_property(path, "background");
props->font = get_font_properties(ui, path);
}
// default_padding_spec is simply an absolute_size, but it parses height before
// width to be consistent with normal CSS-style padding specifications.
struct default_padding_spec
{
absolute_size padding;
default_padding_spec() {}
default_padding_spec(absolute_size const& padding) : padding(padding) {}
};
void parse(line_parser& p, default_padding_spec* spec)
{
parse(p, &spec->padding[1]);
if (!is_empty(p))
parse(p, &spec->padding[0]);
else
spec->padding[0] = spec->padding[1];
}
void read_layout_style_info(
dataless_ui_context& ctx, layout_style_info* style_info,
font const& font, style_search_path const* path)
{
style_info->magnification = ctx.system->style.magnification;
style_info->font_size = font.size;
// Skia supposedly supplies all the necessary font metrics, but they're
// not always valid.
//SkPaint paint;
//set_skia_font_info(paint, font);
//SkPaint::FontMetrics metrics;
//SkScalar line_spacing = paint.getFontMetrics(&metrics);
//style_info->character_size = make_vector(
// SkScalarToFloat(metrics.fAvgCharWidth),
// SkScalarToFloat(line_spacing));
//style_info->x_height = SkScalarToFloat(metrics.fXHeight);
// ... so do some approximations instead.
style_info->character_size = make_vector(font.size * 0.6f, font.size);
style_info->x_height = font.size * 0.5f;
// The padding size may be specified in terms of the above properties,
// so now that those are set, we can evaluated padding size using the
// style_info structure as a reference.
if (get_property(path, "disable-padding", UNINHERITED_PROPERTY, false))
{
style_info->padding_size = make_layout_vector(0, 0);
}
else
{
default_padding_spec default_padding =
get_property(path, "default-padding", INHERITED_PROPERTY,
default_padding_spec(make_vector(
absolute_length(0.2f, EM),
absolute_length(0.2f, EM))));
style_info->padding_size = as_layout_size(
resolve_absolute_size(ctx.layout->ppi, *style_info,
default_padding.padding));
}
}
void update_substyle_data(
dataless_ui_context& ctx, substyle_data& data,
style_search_path const* path,
string const& substyle_name, widget_state state,
add_substyle_flag_set flags)
{
inc_version(data.identity);
data.state.path =
add_substyle_to_path(&data.path_storage, path, path, substyle_name,
state, flags);
read_primary_style_properties(
*ctx.system, &data.properties, data.state.path);
data.state.properties = &data.properties;
data.state.theme = ctx.style.theme;
data.state.id = &data.id;
read_layout_style_info(ctx, &data.style_info, data.properties.font,
data.state.path);
data.id = get_id(data.identity);
}
keyed_data<substyle_data>*
get_substyle_data(
ui_context& ctx, accessor<string> const& substyle_name, widget_state state,
scoped_substyle_flag_set flags)
{
keyed_data<substyle_data>* data;
if (get_cached_data(ctx, &data) || is_refresh_pass(ctx))
{
refresh_keyed_data(*data, combine_ids(ref(ctx.style.id),
combine_ids(ref(&substyle_name.id()), make_id(state))));
}
if (!is_valid(*data))
{
update_substyle_data(ctx, data->value, ctx.style.path,
get(substyle_name), state,
(flags & SCOPED_SUBSTYLE_NO_PATH_SEPARATOR) ?
ADD_SUBSTYLE_NO_PATH_SEPARATOR : NO_FLAGS);
mark_valid(*data);
}
return data;
}
}
| 27.108696 | 79 | 0.581272 | [
"vector"
] |
5b1b9d6e8e9d00e919b9e82cbb1128ea4078d9f0 | 489 | cpp | C++ | OOP/Lab4/line_shape.cpp | samurai-of-honor/my-labs-1 | 111a9302093b1ad6a358560bd926544aa2479d80 | [
"MIT"
] | 1 | 2022-01-30T11:26:23.000Z | 2022-01-30T11:26:23.000Z | OOP/Lab4/line_shape.cpp | samurai-of-honor/my-labs-1 | 111a9302093b1ad6a358560bd926544aa2479d80 | [
"MIT"
] | 6 | 2022-01-20T16:59:03.000Z | 2022-02-12T22:30:55.000Z | OOP/Lab4/line_shape.cpp | samurai-of-honor/my-labs-1 | 111a9302093b1ad6a358560bd926544aa2479d80 | [
"MIT"
] | null | null | null | #include "framework.h"
#include "line_shape.h"
void LineShape::Show(HDC hdc, bool isDash) {
HPEN hPen, hPenOld;
if (isDash) {
hPen = CreatePen(PS_DOT, 1, RGB(255, 0, 0));
hPenOld = (HPEN)SelectObject(hdc, hPen);
}
else {
hPen = CreatePen(PS_SOLID, 1, RGB(0, 255, 0));
hPenOld = (HPEN)SelectObject(hdc, hPen);
}
MoveToEx(hdc, xs1, ys1, NULL);
LineTo(hdc, xs2, ys2);
SelectObject(hdc, hPenOld);
DeleteObject(hPen);
}
Shape* LineShape::Copy() {
return new LineShape();
}
| 20.375 | 48 | 0.660532 | [
"shape"
] |
5b1c777c2bab26d55959ae56161bab8444001f51 | 920 | cpp | C++ | src/Scene.cpp | jenningsm42/mini-mmo-client | 464d062814f17a2fff8938dc99c4061553c5b7a8 | [
"MIT"
] | 2 | 2020-04-03T05:41:59.000Z | 2022-03-13T20:26:42.000Z | src/Scene.cpp | jenningsm42/mini-mmo-client | 464d062814f17a2fff8938dc99c4061553c5b7a8 | [
"MIT"
] | null | null | null | src/Scene.cpp | jenningsm42/mini-mmo-client | 464d062814f17a2fff8938dc99c4061553c5b7a8 | [
"MIT"
] | 1 | 2020-04-03T05:42:00.000Z | 2020-04-03T05:42:00.000Z | #include "Scene.hpp"
bool Scene::handleMessage(Game& game, const Message& message) {
if (m_handlers.find(message.getType()) == m_handlers.end()) {
return false;
}
auto handler = m_handlers[message.getType()];
handler(game, m_objects, message);
return true;
}
void Scene::update(Game& game, float deltaTime) noexcept {
for (auto& object : m_objects) {
object->update(game, m_objects, deltaTime);
}
}
void Scene::draw(sf::RenderWindow& window) noexcept {
m_objects.sort();
for (auto& object : m_objects) {
window.draw(*object);
}
}
void Scene::addObject(const std::string& name, std::shared_ptr<GameObject> object) {
m_objects.add(name, object);
}
void Scene::removeObject(const std::string &name) {
m_objects.remove(name);
}
void Scene::addMessageHandler(MessageType type, MessageHandler handler) {
m_handlers.emplace(type, handler);
}
| 23.589744 | 84 | 0.671739 | [
"object"
] |
5b1e228059bfa8ab1576daa22ee1068ec2d938f4 | 3,375 | cpp | C++ | tools/polygonal/kpToolPolyline.cpp | mikefncu/ikPaint | ee787809c5df0a1b78995962ced4ec3870cc139c | [
"BSD-2-Clause"
] | null | null | null | tools/polygonal/kpToolPolyline.cpp | mikefncu/ikPaint | ee787809c5df0a1b78995962ced4ec3870cc139c | [
"BSD-2-Clause"
] | null | null | null | tools/polygonal/kpToolPolyline.cpp | mikefncu/ikPaint | ee787809c5df0a1b78995962ced4ec3870cc139c | [
"BSD-2-Clause"
] | null | null | null |
/*
Copyright (c) 2003-2007 Clarence Dang <dang@kde.org>
Modified by Maikel Diaz <ariguanabosoft@gmail.com>
Copyright (c) 2015-2018
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 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.
*/
#define DEBUG_KP_TOOL_POLYLINE 0
#include <kpToolPolyline.h>
#include <qdebug.h>
#include <qlocale.h>
#include <tools.h>
#include <kpPainter.h>
kpToolPolyline::kpToolPolyline (kpToolEnvironment *environ, QObject *parent)
: kpToolPolygonalBase (
i18n ("Connected Lines"),
i18n ("Draws connected lines"),
&DrawShape,
Qt::Key_N,
environ, parent,
"tool_polyline")
{
}
kpToolPolyline::~kpToolPolyline ()
{
}
// private virtual [base kpToolPolygonalBase]
QString kpToolPolyline::haventBegunShapeUserMessage () const
{
return i18n ("Drag to draw the first line.");
}
// public static
void kpToolPolyline::DrawShape (kpImage *image,
const QPolygon &points,
const kpColor &fcolor, int penWidth,
const kpColor &bcolor,
bool isFinal)
{
(void) bcolor;
(void) isFinal;
kpPainter::drawPolyline (image,
points,
fcolor, penWidth);
}
// public virtual [base kpTool]
void kpToolPolyline::endDraw (const QPoint &, const QRect &)
{
#if DEBUG_KP_TOOL_POLYLINE
kDebug () << "kpToolPolyline::endDraw() points="
<< points ()->toList () << endl;
#endif
// A click of the other mouse button (to finish shape, instead of adding
// another control point) would have caused endShape() to have been
// called in kpToolPolygonalBase::beginDraw(). The points list would now
// be empty. We are being called by kpTool::mouseReleaseEvent().
if (points ()->count () == 0)
return;
if (points ()->count () >= kpToolPolygonalBase::MaxPoints)
{
#if DEBUG_KP_TOOL_POLYLINE
kDebug () << "\tending shape";
#endif
endShape ();
return;
}
if (originatingMouseButton () == 0)
{
setUserMessage (i18n ("Left drag another line or right click to finish."));
}
else
{
setUserMessage (i18n ("Right drag another line or left click to finish."));
}
}
| 29.094828 | 83 | 0.689481 | [
"shape"
] |
5b1f60f3bfddfb724d763a9123e835a81d8614d9 | 36,047 | cxx | C++ | Utilities/ImMapAttic/Fl_VTK_Window.cxx | NIRALUser/AtlasWerks | a074ca208ab41a6ed89c1f0b70004998f7397681 | [
"BSD-3-Clause"
] | 3 | 2016-04-26T05:06:06.000Z | 2020-08-01T09:46:54.000Z | Utilities/ImMapAttic/Fl_VTK_Window.cxx | scalphunters/AtlasWerks | 9d224bf8db628805368fcb7973ac578937b6b595 | [
"BSD-3-Clause"
] | 1 | 2018-11-27T21:53:48.000Z | 2019-05-13T15:21:31.000Z | Utilities/ImMapAttic/Fl_VTK_Window.cxx | scalphunters/AtlasWerks | 9d224bf8db628805368fcb7973ac578937b6b595 | [
"BSD-3-Clause"
] | 2 | 2019-01-24T02:07:17.000Z | 2019-12-11T17:27:42.000Z | /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
*
* $Id: Fl_VTK_Window.cxx,v 1.46 2005/07/29 22:37:58 xpxqx Exp $
*
* Copyright (c) 2002 - 2005 Sean McInerney
* All rights reserved.
*
* See Copyright.txt or http://vtkfltk.sourceforge.net/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 notice for more information.
*
*/
#include "Fl_VTK_Window.H"
// FLTK
#include <FL/Fl.H>
#include <FL/x.H>
#include <FL/gl.h>
// VTK Common
#include "vtkObjectFactory.h"
#include "vtkObjectFactoryCollection.h"
#include "vtkCommand.h"
#include "vtkProp.h"
// VTK Rendering
#include "vtkRenderer.h"
#include "vtkRendererCollection.h"
// vtkFLTK
#include "vtkFLTKObjectFactory.h"
#include "vtkFLTKOpenGLRenderWindow.h"
#include "vtkFLTKRenderWindowInteractor.h"
// ----------------------------------------------------------------------------
// F l _ V T K _ W i n d o w
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Start of Fl_VTK_Window static initialization stuff
// ----------------------------------------------------------------------------
// Must NOT be initialized. Default initialization to zero is necessary.
unsigned int Fl_VTK_Window_Init::Count;
vtkObjectFactory* Fl_VTK_Window::Factory;
vtkObjectFactory*
FlVtkWindowCheckForVtkFLTKObjectFactory (void)
{
vtkObjectFactory* factory;
vtkObjectFactoryCollection* factories;
if ((factories = vtkObjectFactory::GetRegisteredFactories()) != NULL)
{
for ( factories->InitTraversal();
(factory = factories->GetNextItem()) != NULL; )
if (factory->IsA("vtkFLTKObjectFactory") != 0)
return factory;
// Create and register the specialized object factory which will be used
// to create the specialized Interactor vtkFLTKRenderWindowInteractor
factory = vtkFLTKObjectFactory::New();
vtkObjectFactory::RegisterFactory(factory);
factory->Delete(); // reference retained by vtkObjectFactory
if ((factories = vtkObjectFactory::GetRegisteredFactories()) != NULL)
{
for ( factories->InitTraversal();
(factory = factories->GetNextItem()) != NULL; )
if (factory->IsA("vtkFLTKObjectFactory") != 0)
return factory;
}
else
{
Fl::error("vtkObjectFactory::GetRegisteredFactories() returned NULL!");
return NULL;
}
}
else
{
Fl::error("vtkObjectFactory::GetRegisteredFactories() returned NULL!");
return NULL;
}
Fl::error("Could not find registered vtkFLTKObjectFactory!");
return NULL;
}
// ----------------------------------------------------------------------------
static inline int
VtkWindowTryForVisualMode (int aDoubleBuffer,
int aStereoCapable,
int aMultiSamples)
{
// setup the default stuff
int mode = (FL_RGB | FL_DEPTH);
if (aDoubleBuffer)
mode |= FL_DOUBLE;
if (aMultiSamples)
mode |= FL_MULTISAMPLE;
if (aStereoCapable)
mode |= FL_STEREO;
return (Fl_Gl_Window::can_do(mode) ? mode : 0);
}
int
Fl_VTK_Window::desired_mode (int& aDoubleBuffer,
int& aStereoCapable,
int& aMultiSamples)
{
int stereo;
int multi;
int m = 0;
// try every possibility stoping when we find one that works
for (stereo = aStereoCapable; !m && stereo >= 0; stereo--)
{
for (multi = aMultiSamples; !m && multi >= 0; multi--)
{
m = VtkWindowTryForVisualMode(aDoubleBuffer, stereo, multi);
if (m && aStereoCapable && !stereo)
{
// requested a stereo capable window but we could not get one
aStereoCapable = 0;
}
}
}
for (stereo = aStereoCapable; !m && stereo >= 0; stereo--)
{
for (multi = aMultiSamples; !m && multi >= 0; multi--)
{
m = VtkWindowTryForVisualMode(!aDoubleBuffer, stereo, multi);
if (m)
{
aDoubleBuffer = !aDoubleBuffer;
}
if (m && aStereoCapable && !stereo)
{
// requested a stereo capable window but we could not get one
aStereoCapable = 0;
}
}
}
return m;
}
// ----------------------------------------------------------------------------
Fl_VTK_Window_Init::Fl_VTK_Window_Init (void)
{
if (++Count == 1) Fl_VTK_Window::ClassInitialize();
}
Fl_VTK_Window_Init::~Fl_VTK_Window_Init()
{
if (--Count == 0) Fl_VTK_Window::ClassFinalize();
}
void
Fl_VTK_Window::ClassInitialize (void)
{
if ((Fl_VTK_Window::Factory=FlVtkWindowCheckForVtkFLTKObjectFactory())==NULL)
{
Fl::error("Fl_VTK_Window::ClassInitialize() Failed to get object factory.");
}
Fl_VTK_Window::Factory->Register(NULL); // increment reference count
}
void
Fl_VTK_Window::ClassFinalize (void)
{
if (Fl_VTK_Window::Factory != NULL)
{
Fl_VTK_Window::Factory->UnRegister(NULL); // decrement reference count
}
}
// ----------------------------------------------------------------------------
// End of Fl_VTK_Window static initialization stuff
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
void
Fl_VTK_Window::Fl_VTK_Window_ (vtkRenderWindowInteractor* aInteractor)
{
int stereo = 0;
int multiSample = 0;
int doubleBuffer = 1;
#if !defined(APPLE)
if ( fl_display == NULL
# if defined(UNIX)
|| fl_visual == NULL
# endif /* !UNIX */
)
#endif /* APPLE */
{
// If successful, XVisualInfo is retained in the global variable
// fl_visual. Similarly, an appropriate colormap is retained
// in fl_colormap.
// If the display was not already open, it should be now.
Fl::gl_visual(Fl_VTK_Window::desired_mode(doubleBuffer,stereo,multiSample));
}
this->type(VTK_WINDOW_TYPE);
this->xclass(VTK_WINDOW_XCLASS);
if (aInteractor == NULL)
{
aInteractor = vtkRenderWindowInteractor::New();
}
this->SetInteractor(aInteractor);
vtkRenderWindow* renderWindow;
if ((renderWindow = this->Interactor->GetRenderWindow()) == NULL)
{
renderWindow = vtkRenderWindow::New();
}
this->SetRenderWindow(renderWindow);
}
void
Fl_VTK_Window::Fl_VTK_Window_ (vtkRenderWindow* aRenderWindow)
{
int stereo = 0;
int multiSample = 0;
int doubleBuffer = 1;
#if !defined(APPLE)
if ( fl_display == NULL
# if defined(UNIX)
|| fl_visual == NULL
# endif /* !UNIX */
)
#endif /* APPLE */
{
// If successful, XVisualInfo is retained in the global variable
// fl_visual. Similarly, an appropriate colormap is retained
// in fl_colormap.
// If the display was not already open, it should be now.
Fl::gl_visual(Fl_VTK_Window::desired_mode(doubleBuffer,stereo,multiSample));
}
this->type(VTK_WINDOW_TYPE);
this->xclass(VTK_WINDOW_XCLASS);
if (aRenderWindow == NULL)
{
aRenderWindow = vtkRenderWindow::New();
}
vtkRenderWindowInteractor* interactor;
if ((interactor = aRenderWindow->GetInteractor()) == NULL)
{
interactor = vtkRenderWindowInteractor::New();
interactor->SetRenderWindow(aRenderWindow);
}
this->SetInteractor(interactor);
this->SetRenderWindow(aRenderWindow);
}
// ----------------------------------------------------------------------------
Fl_VTK_Window::Fl_VTK_Window (int w, int h, const char* label)
: Fl_Gl_Window(w,h,label),
Interactor(NULL), RenderWindow(NULL), QueuedRenderer(NULL)
{
this->Fl_VTK_Window_();
}
Fl_VTK_Window::Fl_VTK_Window (int x, int y, int w, int h, const char* label)
: Fl_Gl_Window(x,y,w,h,label),
Interactor(NULL), RenderWindow(NULL), QueuedRenderer(NULL)
{
this->Fl_VTK_Window_();
}
Fl_VTK_Window::Fl_VTK_Window (vtkRenderWindowInteractor* iren,
int x, int y, int w, int h, const char* label)
: Fl_Gl_Window(x,y,w,h,label),
Interactor(NULL), RenderWindow(NULL), QueuedRenderer(NULL)
{
this->Fl_VTK_Window_(iren);
}
Fl_VTK_Window::Fl_VTK_Window (vtkRenderWindow* rw,
int x, int y, int w, int h, const char* label)
: Fl_Gl_Window(x,y,w,h,label),
Interactor(NULL), RenderWindow(NULL), QueuedRenderer(NULL)
{
this->Fl_VTK_Window_(rw);
}
// ----------------------------------------------------------------------------
Fl_VTK_Window::~Fl_VTK_Window()
{
// according to the fltk docs, destroying a widget does NOT remove it from
// its parent, so we have to do that explicitly at destruction
// (and remember, NEVER delete() an instance of this class)
if (this->parent() != NULL)
{
(static_cast<Fl_Group*>(this->parent()))->
remove(*(static_cast<Fl_Widget*>(this)));
}
// Unestablish ownership (unofficially) by Fl_VTK_Window.
if (this->Interactor != NULL)
{
this->Interactor->UnRegister(NULL);
this->Interactor = NULL;
}
if (this->RenderWindow != NULL)
{
this->RenderWindow->UnRegister(NULL);
this->RenderWindow = NULL;
}
if (this->QueuedRenderer != NULL)
{
this->QueuedRenderer->UnRegister(NULL);
this->QueuedRenderer = NULL;
}
}
// ----------------------------------------------------------------------------
void
Fl_VTK_Window::Update (void)
{
if (this->RenderWindow != NULL) this->RenderWindow->SetForceMakeCurrent();
this->redraw();
}
// ----------------------------------------------------------------------------
void
Fl_VTK_Window::SetInteractor (vtkRenderWindowInteractor* aInteractor)
{
if (this->Interactor == aInteractor)
{
return;
}
// Decrement the reference count of any previously held Interactor.
if (this->Interactor != NULL)
{
this->Interactor->UnRegister(NULL);
}
if ((this->Interactor = aInteractor) != NULL)
{
this->Interactor->Register(NULL); // increment reference count
// Attend to FLTK specializations.
if (this->Interactor->IsA("vtkFLTKRenderWindowInteractor"))
{
(static_cast<vtkFLTKRenderWindowInteractor*>(this->Interactor))->
SetWidget(this);
}
if (this->Interactor->GetRenderWindow() != NULL)
{
this->SetRenderWindow(this->Interactor->GetRenderWindow());
}
else if (this->RenderWindow != NULL)
{
this->Interactor->SetRenderWindow(this->RenderWindow);
}
}
}
vtkRenderWindowInteractor*
Fl_VTK_Window::GetInteractor (void)
{
return this->Interactor;
}
// ----------------------------------------------------------------------------
void
Fl_VTK_Window::SetRenderWindow (vtkRenderWindow* aRenderWindow)
{
if (this->RenderWindow == aRenderWindow)
return;
// Decrement the reference count of any previously held RenderWindow.
if (this->RenderWindow != NULL)
{
this->RenderWindow->UnRegister(NULL);
}
if ((this->RenderWindow = aRenderWindow) != NULL)
{
this->RenderWindow->Register(NULL); // increment reference count
// Attend to FLTK specializations.
if (this->RenderWindow->IsA("vtkFLTKOpenGLRenderWindow") != 0)
{
(static_cast<vtkFLTKOpenGLRenderWindow*>(this->RenderWindow))->
SetFlWindow(this);
this->mode(
(static_cast<vtkFLTKOpenGLRenderWindow*>(this->RenderWindow))->
GetDesiredVisualMode() );
}
if (this->Interactor != NULL)
{
this->RenderWindow->SetInteractor(this->Interactor);
}
else if (this->RenderWindow->GetInteractor() != NULL)
{
this->SetInteractor(this->RenderWindow->GetInteractor());
}
// Force the dimensions of the new RenderWindow to match the widget.
this->RenderWindow->SetSize(this->w(), this->h());
}
}
vtkRenderWindow*
Fl_VTK_Window::GetRenderWindow (void)
{
return this->RenderWindow;
}
// ----------------------------------------------------------------------------
vtkRendererCollection*
Fl_VTK_Window::GetRenderers (void)
{
vtkRendererCollection* rendererCollection = NULL;
vtkRenderWindow* renderWindow;
if ((renderWindow = this->GetRenderWindow()) != NULL)
{
// Add any queued Renderer.
if (this->QueuedRenderer)
{
renderWindow->AddRenderer(this->QueuedRenderer);
this->QueuedRenderer->UnRegister(NULL);
this->QueuedRenderer = NULL;
}
if ((rendererCollection = renderWindow->GetRenderers()) != NULL)
{
if (rendererCollection->GetNumberOfItems() < 1)
{
vtkRenderer* renderer = vtkRenderer::New();
renderWindow->AddRenderer(renderer);
renderer->Delete();
}
}
else
{
Fl::error("GetRenderers() could not get Renderers!");
}
}
else
{
Fl::error("GetRenderers() could not get RenderWindow!");
}
return rendererCollection;
}
// ----------------------------------------------------------------------------
vtkRenderer*
Fl_VTK_Window::GetDefaultRenderer (void)
{
vtkRenderer* renderer = NULL;
// Return the queued Renderer if there is one.
if (this->QueuedRenderer != NULL)
{
renderer = this->QueuedRenderer;
}
else
{
vtkRenderWindow* renderWindow;
if ((renderWindow = this->GetRenderWindow()) != NULL)
{
vtkRendererCollection* rendererCollection;
if ((rendererCollection = renderWindow->GetRenderers()) != NULL)
{
if (rendererCollection->GetNumberOfItems() < 1)
{
renderer = vtkRenderer::New();
if (renderWindow->GetNeverRendered() != 0)
{
this->QueuedRenderer = renderer;
}
else
{
renderWindow->AddRenderer(renderer);
renderer->Delete();
}
}
else
{
rendererCollection->InitTraversal();
renderer = rendererCollection->GetNextItem();
}
}
else
{
Fl::error("GetDefaultRenderer() failed to get Renderers!");
}
}
else
{
Fl::error("GetDefaultRenderer() failed to get RenderWindow!");
}
}
return renderer;
}
// ----------------------------------------------------------------------------
vtkCamera*
Fl_VTK_Window::GetDefaultCamera (void)
{
vtkCamera* camera = NULL;
vtkRenderer* renderer;
if ((renderer = this->GetDefaultRenderer()) != NULL)
{
camera = renderer->GetActiveCamera();
}
return camera;
}
// ----------------------------------------------------------------------------
void
Fl_VTK_Window::AddViewProp (vtkProp* aProp)
{
if (aProp == NULL)
{
return;
}
vtkRenderer* renderer;
if ((renderer = this->GetDefaultRenderer()) != NULL)
{
#ifndef VTK_FLTK_VTK_5
renderer->AddProp(aProp);
#else
renderer->AddViewProp(aProp);
#endif
}
}
void
Fl_VTK_Window::RemoveViewProp (vtkProp* aProp)
{
if (aProp == NULL)
{
return;
}
vtkRenderer* renderer;
if ((renderer = this->GetDefaultRenderer()) != NULL)
{
#ifndef VTK_FLTK_VTK_5
renderer->RemoveProp(aProp);
#else
renderer->RemoveViewProp(aProp);
#endif
}
}
// ----------------------------------------------------------------------------
// FLTK event handlers
// ----------------------------------------------------------------------------
void
Fl_VTK_Window::flush (void)
{
if (this->QueuedRenderer != NULL)
{
this->RenderWindow->AddRenderer(this->QueuedRenderer);
this->QueuedRenderer->UnRegister(NULL);
this->QueuedRenderer = NULL;
}
this->draw();
#if 0
std::cerr << "Fl_VTK_Window::flush()\n"
<< "\t context()\t: " << this->context() << "\n"
<< "\t valid()\t: " << (this->valid()?"YES":"NO")<< "\n"
<< "\t shown()\t: " << (this->shown()?"YES":"NO")<< "\n"
<< "\t visible()\t: " << (this->visible()?"YES":"NO")<< "\n"
<< "\t mode()\t: ( "
<< ( (this->mode()&FL_INDEX) ? "FL_INDEX" :
((this->mode()&FL_RGB8) ? "FL_RGB8" : "FL_RGB") )
<< ((this->mode()&FL_DOUBLE) ? " | FL_DOUBLE" : " | FL_SINGLE")
<< ((this->mode()&FL_ACCUM) ? " | FL_ACCUM" : "")
<< ((this->mode()&FL_ALPHA) ? " | FL_ALPHA" : "")
<< ((this->mode()&FL_DEPTH) ? " | FL_DEPTH" : "")
<< ((this->mode()&FL_STENCIL) ? " | FL_STENCIL" : "")
<< ((this->mode()&FL_MULTISAMPLE) ? " | FL_MULTISAMPLE" : "")
<< ((this->mode()&FL_STEREO) ? " | FL_STEREO" : "")
<< " )\n"
<< "\t can_do()\t: " << (this->can_do() ? "YES" : "NO")
<< std::endl;
#endif
}
// ----------------------------------------------------------------------------
void
Fl_VTK_Window::draw (void)
{
if (this->Interactor != NULL)
this->Interactor->Render();
else if (this->RenderWindow != NULL)
this->RenderWindow->Render();
}
// ----------------------------------------------------------------------------
void
Fl_VTK_Window::resize_ (int aX, int aY, int aWidth, int aHeight)
{
this->Fl_Gl_Window::resize(aX, aY, aWidth, aHeight);
}
void
Fl_VTK_Window::resize (int aX, int aY, int aWidth, int aHeight)
{
// make sure VTK knows about the new situation
if (this->Interactor != NULL)
this->Interactor->UpdateSize(aWidth, aHeight);
else if (this->RenderWindow != NULL)
this->RenderWindow->SetSize(aWidth, aHeight);
// resize the FLTK window by calling ancestor method
this->resize_(aX, aY, aWidth, aHeight);
}
// ----------------------------------------------------------------------------
const char*
Fl_VTK_Window::GetEventAsString (int aEvent)
{
switch (aEvent)
{
case FL_NO_EVENT:
#if defined(UNIX) && !defined(APPLE)
if (fl_xevent != NULL)
{
switch (fl_xevent->type)
{
case KeyPress: return "NO_EVENT (KeyPress)";
case KeyRelease: return "NO_EVENT (KeyRelease)";
case ButtonPress: return "NO_EVENT (ButtonPress)";
case ButtonRelease: return "NO_EVENT (ButtonRelease)";
case MotionNotify: return "NO_EVENT (MotionNotify)";
case EnterNotify: return "NO_EVENT (EnterNotify)";
case LeaveNotify: return "NO_EVENT (LeaveNotify)";
case FocusIn: return "NO_EVENT (FocusIn)";
case FocusOut: return "NO_EVENT (FocusOut)";
case KeymapNotify: return "NO_EVENT (KeymapNotify)";
case Expose: return "NO_EVENT (Expose)";
case GraphicsExpose: return "NO_EVENT (GraphicsExpose)";
case NoExpose: return "NO_EVENT (NoExpose)";
case VisibilityNotify: return "NO_EVENT (VisibilityNotify)";
case CreateNotify: return "NO_EVENT (CreateNotify)";
case DestroyNotify: return "NO_EVENT (DestroyNotify)";
case UnmapNotify: return "NO_EVENT (UnmapNotify)";
case MapNotify: return "NO_EVENT (MapNotify)";
case MapRequest: return "NO_EVENT (MapRequest)";
case ReparentNotify: return "NO_EVENT (ReparentNotify)";
case ConfigureNotify: return "NO_EVENT (ConfigureNotify)";
case ConfigureRequest: return "NO_EVENT (ConfigureRequest)";
case GravityNotify: return "NO_EVENT (GravityNotify)";
case ResizeRequest: return "NO_EVENT (ResizeRequest)";
case CirculateNotify: return "NO_EVENT (CirculateNotify)";
case CirculateRequest: return "NO_EVENT (CirculateRequest)";
case PropertyNotify: return "NO_EVENT (PropertyNotify)";
case SelectionClear: return "NO_EVENT (SelectionClear)";
case SelectionRequest: return "NO_EVENT (SelectionRequest)";
case SelectionNotify: return "NO_EVENT (SelectionNotify)";
case ColormapNotify: return "NO_EVENT (ColormapNotify)";
case ClientMessage: return "NO_EVENT (ClientMessage)";
case MappingNotify: return "NO_EVENT (MappingNotify)";
} // switch (fl_xevent->type)
}
break;
#else
return "NO_EVENT";
#endif /* !UNIX */
case FL_PUSH: return "PUSH";
case FL_RELEASE: return "RELEASE";
case FL_ENTER: return "ENTER";
case FL_LEAVE: return "LEAVE";
case FL_DRAG: return "DRAG";
case FL_FOCUS: return "FOCUS";
case FL_UNFOCUS: return "UNFOCUS";
case FL_KEYDOWN: return "KEYDOWN";
case FL_KEYUP: return "KEYUP";
case FL_CLOSE: return "CLOSE";
case FL_MOVE: return "MOVE";
case FL_SHORTCUT: return "SHORTCUT";
case FL_DEACTIVATE: return "DEACTIVATE";
case FL_ACTIVATE: return "ACTIVATE";
case FL_HIDE: return "HIDE";
case FL_SHOW: return "SHOW";
case FL_PASTE: return "PASTE";
case FL_SELECTIONCLEAR: return "SELECTIONCLEAR";
case FL_MOUSEWHEEL: return "MOUSEWHEEL";
case FL_DND_ENTER: return "DND_ENTER";
case FL_DND_DRAG: return "DND_DRAG";
case FL_DND_LEAVE: return "DND_LEAVE";
case FL_DND_RELEASE: return "DND_RELEASE";
} // switch (aEvent)
return "<UnknownEvent>";
}
// ----------------------------------------------------------------------------
#if defined(UNIX) && !defined(APPLE)
static inline int
event_width (void)
{ return (reinterpret_cast<const XConfigureEvent *>(fl_xevent))->width; }
static inline int
event_height (void)
{ return (reinterpret_cast<const XConfigureEvent *>(fl_xevent))->height; }
#endif /* !UNIX */
// ----------------------------------------------------------------------------
int
Fl_VTK_Window::handle (int aEvent)
{
#if !defined(UNIX) || defined(APPLE)
if (aEvent == FL_NO_EVENT)
{
return this->Fl_Gl_Window::handle(aEvent);
}
#endif /* !UNIX */
#if 0
if (aEvent != FL_MOVE && aEvent != FL_DRAG)
{
// if printing type of event
std::cerr << "Fl_VTK_Window::handle( " << aEvent << " = "
<< Fl_VTK_Window::GetEventAsString(aEvent) << " )"
<< std::cerr;
}
#endif
// vtkInteractorStyle implements the "joystick" style of interaction. That
// is, holding down the mouse keys generates a stream of events that
// cause continuous actions (e.g., rotate, translate, pan, zoom). (The
// class vtkInteractorStyleTrackball implements a grab and move style.)
// The event bindings for this class include the following:
//
// * Keypress j / Keypress t: toggle between joystick (position
// sensitive) and trackball (motion sensitive) styles. In joystick
// style, motion occurs continuously as long as a mouse button is
// pressed. In trackball style, motion occurs when the mouse button is
// pressed and the mouse pointer moves.
// * Keypress c / Keypress o: toggle between camera and object (actor)
// modes. In camera mode, mouse events affect the camera position and
// focal point. In object mode, mouse events affect the actor that is
// under the mouse pointer.
// * Button 1: rotate the camera around its focal point (if camera mode)
// or rotate the actor around its origin (if actor mode). The rotation
// is in the direction defined from the center of the renderer's
// viewport towards the mouse position. In joystick mode, the magnitude
// of the rotation is determined by the distance the mouse is from the
// center of the render window.
// * Button 2: pan the camera (if camera mode) or translate the actor (if
// object mode). In joystick mode, the direction of pan or translation
// is from the center of the viewport towards the mouse position. In
// trackball mode, the direction of motion is the direction the mouse
// moves. (Note: with 2-button mice, pan is defined as <Shift>-Button 1.)
// * Button 3: zoom the camera (if camera mode) or scale the actor (if
// object mode). Zoom in/increase scale if the mouse position is in the
// top half of the viewport; zoom out/decrease scale if the mouse
// position is in the bottom half. In joystick mode, the amount of zoom
// is controlled by the distance of the mouse pointer from the
// horizontal centerline of the window.
// * Keypress 3: toggle the render window into and out of stereo mode. By
// default, red-blue stereo pairs are created. Some systems support
// Crystal Eyes LCD stereo glasses; you have to invoke
// SetStereoTypeToCrystalEyes() on the rendering window.
// * Keypress e: exit the application.
// * Keypress p: perform a pick operation. The render window interactor
// has an internal instance of vtkCellPicker that it uses to pick.
// * Keypress r: reset the camera view along the current view direction.
// Centers the actors and moves the camera so that all actors are visible.
// * Keypress s: modify the representation of all actors so that they
// are surfaces.
// * Keypress u: invoke the user-defined function. Typically, this
// keypress will bring up an interactor that you can type commands in.
// * Keypress w: modify the representation of all actors so that they
// are wireframe.
//
vtkRenderWindowInteractor* interactor;
vtkRenderWindow* renderWindow;
if ( ((interactor = this->GetInteractor()) == NULL) ||
((renderWindow = this->GetRenderWindow()) == NULL) ||
(this->shown() == 0) )
{
return this->Fl_Gl_Window::handle(aEvent);
}
int enabled = interactor->GetEnabled();;
int ctrl = Fl::event_state(FL_CTRL);
int shift = Fl::event_state(FL_SHIFT);
int ex = Fl::event_x();
int ey = Fl::event_y();
switch (aEvent)
{
//
// Focus Events ( FOCUS || UNFOCUS || ENTER || LEAVE )
//
case FL_FOCUS:
// Indicates an attempt to give a widget the keyboard focus (FocusIn).
// Returning non-zero from handle() means that the widget wants focus.
// It then becomes the Fl::focus() widget and gets KEYDOWN,
// KEYUP, and UNFOCUS events.
if (enabled)
{
return 1; // FOCUS
}
break;
case FL_UNFOCUS:
// This event is sent to the previous Fl::focus() widget when
// another widget gets the focus or the window loses focus (FocusOut).
if (enabled)
{
return 1; // UNFOCUS
}
break;
case FL_ENTER:
// The mouse has been moved to point at this widget (EnterNotify).
// Indicate that this wants an FOCUS sent to it.
{
if (this->window() != NULL)
{
// Sends this window a FOCUS event. It will return 1 (see above)
// affirming its desire to become the Fl::focus() widget receiving
// subsequent KEYBOARD events.
this->take_focus();
}
if (enabled)
{
interactor->SetEventInformationFlipY(ex, ey, ctrl, shift);
interactor->InvokeEvent(vtkCommand::EnterEvent, NULL);
// Returning non-zero indicates that we wish to track the mouse.
// This then becomes the Fl::belowmouse() widget and will receive
// MOVE and LEAVE events.
return 1; // ENTER
}
} break;
case FL_LEAVE:
// The mouse has moved out of the widget (LeaveNotify).
if (enabled)
{
interactor->SetEventInformationFlipY(ex, ey, ctrl, shift);
interactor->InvokeEvent(vtkCommand::LeaveEvent, NULL);
return 1; // LEAVE
}
break;
//
// Widget Events ( SHOW || HIDE || ACTIVATE || DEACTIVATE )
//
case FL_SHOW:
// This widget is visible again, due to show() being called on it or one
// of its parents, or due to a parent window being restored (MapNotify).
{
// By not checking to see if the interactor is enabled here,
// performing the Render() will end up enabling the interactor.
// This behavior may be undesirable.
if (renderWindow->GetNeverRendered())
{
renderWindow->Render();
}
// Child Fl_Windows respond to SHOW by actually creating the window
// if not done already, so if you subclass a window, be sure to pass
// SHOW to the base class handle() method!
} break;
#if 0
case FL_HIDE:
// Widget is no longer visible, due to hide() being called on it or one of
// its parents, or due to a parent window being minimized (UnmapNotify).
// visible() may still be true after this, but the widget is visible only
// if visible() is true for it and all its parents (use visible_r() to
// check this).
break; // HIDE
case FL_ACTIVATE:
// This widget is now active, due to activate() being called on it or
// one of its parents.
break; // ACTIVATE
case FL_DEACTIVATE:
// This widget is no longer active, due to deactivate() being called
// on it or one of its parents. active() may still be true after this,
// the widget is only active if active() is true on it and all its
// parents (use active_r() to check this).
break; // DEACTIVATE
#endif /* 0 */
//
// Mouse Events ( PUSH || RELEASE || DRAG || MOVE )
//
case FL_PUSH:
// A mouse button has gone down over this widget (ButtonPress).
if (enabled)
{
interactor->SetEventInformationFlipY(ex, ey, ctrl, shift);
switch (Fl::event_button())
{
case FL_LEFT_MOUSE:
interactor->InvokeEvent(vtkCommand::LeftButtonPressEvent, NULL);
break;
case FL_MIDDLE_MOUSE:
interactor->InvokeEvent(vtkCommand::MiddleButtonPressEvent, NULL);
break;
case FL_RIGHT_MOUSE:
interactor->InvokeEvent(vtkCommand::RightButtonPressEvent, NULL);
break;
} // switch (button)
// Indicate that we "want" the mouse click by returning non-zero.
// This will then become the Fl::pushed() widget and will get
// DRAG and the matching RELEASE events.
return 1;
}
break; // PUSH
case FL_RELEASE:
// A mouse button has been released (ButtonRelease).
if (enabled)
{
interactor->SetEventInformationFlipY(ex, ey, ctrl, shift);
switch (Fl::event_button())
{
case FL_LEFT_MOUSE:
interactor->InvokeEvent(vtkCommand::LeftButtonReleaseEvent, NULL);
break;
case FL_MIDDLE_MOUSE:
interactor->InvokeEvent(vtkCommand::MiddleButtonReleaseEvent, NULL);
break;
case FL_RIGHT_MOUSE:
interactor->InvokeEvent(vtkCommand::RightButtonReleaseEvent, NULL);
break;
} // switch (button)
return 1;
}
break; // RELEASE
// we test for both of these, as fltk classifies mouse moves as with or
// without button press whereas vtk wants all mouse movement (this bug took
// a while to find :) -cpbotha
case FL_DRAG:
// The mouse has moved with a button held down.
case FL_MOVE:
// The mouse has moved without any mouse buttons held down (MotionNotify).
if (enabled)
{
interactor->SetEventInformationFlipY(ex, ey, ctrl, shift);
interactor->InvokeEvent(vtkCommand::MouseMoveEvent, NULL);
return 1;
}
break; // DRAG || MOVE
//
// Keyboard Events
//
// now for possible controversy: there is no way to find out if the
// InteractorStyle actually did something with this event. To play it
// safe (and have working hotkeys), we return "0", which indicates to
// FLTK that we did NOTHING with this event. FLTK will send this
// keyboard event to other children in our group, meaning it should
// reach any FLTK keyboard callbacks (including hotkeys)
case FL_SHORTCUT:
// If the Fl::focus() widget is zero or ignores an KEYBOARD event
// then FLTK tries sending this event to every widget it can, until
// one of them returns non-zero. SHORTCUT is first sent to the
// Fl::belowmouse() widget, then its parents and siblings, and
// eventually to every widget in the window, trying to find an object
// that returns non-zero. FLTK tries really hard to not to ignore
// any keystrokes! ... FALLING THROUGH ...
// The key can be found in Fl::event_key(). The text that the key should
// insert can be found with Fl::event_text() and its length is in
// Fl::event_length(). If you use the key, handle() should return 1.
// If you return zero, FLTK assumes that you ignored the key and will
// attempt to send it to a parent widget. If none of them want it, it
// will change the event into a SHORTCUT event.
// To receive KEYBOARD events you must also respond to the FOCUS
// and UNFOCUS events.
case FL_KEYDOWN:
// A key was pressed (KeyPress).
if (enabled)
{
interactor->SetEventInformationFlipY( ex,ey, ctrl,shift,
Fl::event_key(), 1,
Fl::event_text() );
interactor->InvokeEvent(vtkCommand::KeyPressEvent, NULL);
interactor->InvokeEvent(vtkCommand::CharEvent, NULL);
return 0;
}
break; // KEYDOWN
case FL_KEYUP:
// A key was released (KeyRelease).
if (enabled)
{
interactor->SetEventInformationFlipY( ex,ey, ctrl,shift,
Fl::event_key(), 1,
Fl::event_text() );
interactor->InvokeEvent(vtkCommand::KeyReleaseEvent, NULL);
return 0;
}
break; // KEYUP
#if 0
# if defined(UNIX) && !defined(APPLE)
case FL_NO_EVENT:
//
// Other X Events not specifically enumerated by FLTK.
//
if (fl_xevent != NULL)
{
switch (fl_xevent->type)
{
case Expose:
// ignore child windows
if (this->parent() == NULL)
{
interactor->SetEventSize(event_width(), event_height());
interactor->SetEventPositionFlipY(ex, ey);
if (enabled)
{
// only render if we are currently accepting events
interactor->InvokeEvent(vtkCommand::ExposeEvent, NULL);
renderWindow->Render();
}
}
break; // Expose
case ConfigureNotify:
// ignore child windows
if (this->parent() == NULL)
{
if (event_width() != this->w() || event_height() != this->h())
{
interactor->UpdateSize(event_width(), event_height());
interactor->SetEventPositionFlipY(ex, ey);
if (enabled)
{
// only render if we are currently accepting events
interactor->InvokeEvent(vtkCommand::ConfigureEvent, NULL);
renderWindow->Render();
}
}
}
break; // ConfigureNotify
case EnterNotify:
break; // EnterNotify
case LeaveNotify:
break; // LeaveNotify
} // switch (fl_xevent->type)
}
break; // NO_EVENT
# endif /* !UNIX */
#endif /* 0 */
} // switch (aEvent)
//
// let the base class handle everything else
//
return this->Fl_Gl_Window::handle(aEvent);
}
/*
* End of: $Id: Fl_VTK_Window.cxx,v 1.46 2005/07/29 22:37:58 xpxqx Exp $.
*
*/
| 32.242397 | 80 | 0.580548 | [
"render",
"object"
] |
5b23372492e1138fb6e6ab4591c6181a4859736f | 7,879 | hpp | C++ | include/opentxs/api/client/Activity.hpp | pjz/opentxs | 04cb17a7d1870c4c3b264e4307b9e9f248f24c87 | [
"MIT"
] | null | null | null | include/opentxs/api/client/Activity.hpp | pjz/opentxs | 04cb17a7d1870c4c3b264e4307b9e9f248f24c87 | [
"MIT"
] | null | null | null | include/opentxs/api/client/Activity.hpp | pjz/opentxs | 04cb17a7d1870c4c3b264e4307b9e9f248f24c87 | [
"MIT"
] | null | null | null | // Copyright (c) 2018 The Open-Transactions developers
// 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/.
#ifndef OPENTXS_API_CLIENT_ACTIVITY_HPP
#define OPENTXS_API_CLIENT_ACTIVITY_HPP
#include "opentxs/Forward.hpp"
#include "opentxs/Proto.hpp"
#include "opentxs/Types.hpp"
#include <chrono>
#include <memory>
#include <string>
#include <tuple>
namespace opentxs
{
namespace api
{
namespace client
{
class Activity
{
public:
using ChequeData = std::pair<
std::unique_ptr<const class Cheque>,
std::shared_ptr<const UnitDefinition>>;
using TransferData = std::pair<
std::unique_ptr<const opentxs::Item>,
std::shared_ptr<const UnitDefinition>>;
EXPORT virtual bool AddBlockchainTransaction(
const Identifier& nymID,
const Identifier& threadID,
const StorageBox box,
const proto::BlockchainTransaction& transaction) const = 0;
EXPORT virtual bool AddPaymentEvent(
const Identifier& nymID,
const Identifier& threadID,
const StorageBox type,
const Identifier& itemID,
const Identifier& workflowID,
std::chrono::time_point<std::chrono::system_clock> time) const = 0;
EXPORT virtual bool MoveIncomingBlockchainTransaction(
const Identifier& nymID,
const Identifier& fromThreadID,
const Identifier& toThreadID,
const std::string& txid) const = 0;
/** Load a mail object
*
* \param[in] nym the identifier of the nym who owns the mail box
* \param[in] id the identifier of the mail object
* \param[in] box the box from which to retrieve the mail object
* \returns A smart pointer to the object. The smart pointer will not be
* instantiated if the object does not exist or is invalid.
*/
EXPORT virtual std::unique_ptr<Message> Mail(
const Identifier& nym,
const Identifier& id,
const StorageBox& box) const = 0;
/** Store a mail object
*
* \param[in] nym the identifier of the nym who owns the mail box
* \param[in] mail the mail object to be stored
* \param[in] box the box from which to retrieve the mail object
* \returns The id of the stored message. The string will be empty if
* the mail object can not be stored.
*/
EXPORT virtual std::string Mail(
const Identifier& nym,
const Message& mail,
const StorageBox box) const = 0;
/** Obtain a list of mail objects in a specified box
*
* \param[in] nym the identifier of the nym who owns the mail box
* \param[in] box the box to be listed
*/
EXPORT virtual ObjectList Mail(const Identifier& nym, const StorageBox box)
const = 0;
/** Delete a mail object
*
* \param[in] nym the identifier of the nym who owns the mail box
* \param[in] mail the mail object to be stored
* \param[in] box the box from which to retrieve the mail object
* \returns The id of the stored message. The string will be empty if
* the mail object can not be stored.
*/
EXPORT virtual bool MailRemove(
const Identifier& nym,
const Identifier& id,
const StorageBox box) const = 0;
/** Retrieve the text from a message
*
* \param[in] nym the identifier of the nym who owns the mail box
* \param[in] id the identifier of the mail object
* \param[in] box the box from which to retrieve the mail object
* \returns A smart pointer to the object. The smart pointer will not be
* instantiated if the object does not exist or is invalid.
*/
EXPORT virtual std::shared_ptr<const std::string> MailText(
const Identifier& nym,
const Identifier& id,
const StorageBox& box) const = 0;
/** Mark a thread item as read
*
* \param[in] nymId the identifier of the nym who owns the thread
* \param[in] threadId the thread containing the item to be marked
* \param[in] itemId the identifier of the item to be marked read
* \returns False if the nym, thread, or item does not exist
*/
EXPORT virtual bool MarkRead(
const Identifier& nymId,
const Identifier& threadId,
const Identifier& itemId) const = 0;
/** Mark a thread item as unread
*
* \param[in] nymId the identifier of the nym who owns the thread
* \param[in] threadId the thread containing the item to be marked
* \param[in] itemId the identifier of the item to be marked unread
* \returns False if the nym, thread, or item does not exist
*/
EXPORT virtual bool MarkUnread(
const Identifier& nymId,
const Identifier& threadId,
const Identifier& itemId) const = 0;
EXPORT virtual ChequeData Cheque(
const Identifier& nym,
const std::string& id,
const std::string& workflow) const = 0;
EXPORT virtual TransferData Transfer(
const Identifier& nym,
const std::string& id,
const std::string& workflow) const = 0;
/** Summarize a payment workflow event in human-friendly test form
*
* \param[in] nym the identifier of the nym who owns the thread
* \param[in] id the identifier of the payment item
* \param[in] workflow the identifier of the payment workflow
* \returns A smart pointer to the object. The smart pointer will not be
* instantiated if the object does not exist or is invalid.
*/
EXPORT virtual std::shared_ptr<const std::string> PaymentText(
const Identifier& nym,
const std::string& id,
const std::string& workflow) const = 0;
/** Asynchronously cache the most recent items in each of a nym's threads
*
* \param[in] nymID the identifier of the nym who owns the thread
* \param[in] count the number of items to preload in each thread
*/
EXPORT virtual void PreloadActivity(
const Identifier& nymID,
const std::size_t count) const = 0;
/** Asynchronously cache the items in an activity thread
*
* \param[in] nymID the identifier of the nym who owns the thread
* \param[in] threadID the thread containing the items to be cached
* \param[in] start the first item to be cached
* \param[in] count the number of items to cache
*/
EXPORT virtual void PreloadThread(
const Identifier& nymID,
const Identifier& threadID,
const std::size_t start,
const std::size_t count) const = 0;
EXPORT virtual std::shared_ptr<proto::StorageThread> Thread(
const Identifier& nymID,
const Identifier& threadID) const = 0;
/** Obtain a list of thread ids for the specified nym
*
* \param[in] nym the identifier of the nym
* \param[in] unreadOnly if true, only return threads with unread items
*/
EXPORT virtual ObjectList Threads(
const Identifier& nym,
const bool unreadOnly = false) const = 0;
/** Return the total number of unread thread items for a nym
*
* \param[in] nymId
*/
EXPORT virtual std::size_t UnreadCount(const Identifier& nym) const = 0;
EXPORT virtual std::string ThreadPublisher(const Identifier& nym) const = 0;
virtual ~Activity() = default;
protected:
Activity() = default;
private:
Activity(const Activity&) = delete;
Activity(Activity&&) = delete;
Activity& operator=(const Activity&) = delete;
Activity& operator=(Activity&&) = delete;
};
} // namespace client
} // namespace api
} // namespace opentxs
#endif
| 38.062802 | 80 | 0.644879 | [
"object"
] |
5b252330f28b24c8c22f1ec5408f3172810fce50 | 8,973 | cpp | C++ | tests_simple/lmartin/test_vector.cpp | ggjulio/ft_containers | 77e221965e9c0813a4e20673d82eaa84814fe369 | [
"MIT"
] | null | null | null | tests_simple/lmartin/test_vector.cpp | ggjulio/ft_containers | 77e221965e9c0813a4e20673d82eaa84814fe369 | [
"MIT"
] | null | null | null | tests_simple/lmartin/test_vector.cpp | ggjulio/ft_containers | 77e221965e9c0813a4e20673d82eaa84814fe369 | [
"MIT"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* test_vector.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lmartin <lmartin@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/08/09 20:39:11 by lmartin #+# #+# */
/* Updated: 2020/08/12 04:47:51 by lmartin ### ########.fr */
/* */
/* ************************************************************************** */
#include <iostream>
#include <limits>
#include <iomanip>
#include <vector>
#include "utils.hpp"
#include "colors.h"
#include "vector.hpp"
template <class T>
void error_diff(ft::vector<T> myv, std::vector<T> vector)
{
std::cout << _RED << "ERROR - DIFF" << _END << std::endl;
std::cout << std::setw(30) << "myv.empty(): " << myv.empty() << std::endl;
std::cout << std::setw(30) << "vector.empty(): " << vector.empty() << std::endl;
std::cout << std::setw(30) << "myv.size(): " << myv.size() << std::endl;
std::cout << std::setw(30) << "vector.size(): " << vector.size() << std::endl;
std::cout << std::setw(30) << "myv : ";
printContainer(myv);
std::cout << std::setw(30) << "vector : ";
printContainer(vector);
}
template <class T>
void compareVector(std::string function, ft::vector<T> myv, std::vector<T> vector)
{
std::cout << std::setw(30) << function << ": ";
if (myv.empty() != vector.empty())
error_diff(myv, vector);
else if (myv.size() != vector.size())
error_diff(myv, vector);
else
{
typename ft::vector<T>::iterator my_it;
typename std::vector<T>::iterator i;
my_it = myv.begin();
i = vector.begin();
while (i != vector.end())
{
if (*i != *my_it)
{
error_diff(myv, vector);
return ;
}
i++;
my_it++;
}
std::cout << _GREEN << "OK " << _END;
printContainer(myv);
}
}
void test_vector(void)
{
std::cout << _WHITE << "# test_vector" << _END << std::endl;
std::cout << _YELLOW << "/* ********************************************************************** */" << std::endl;
std::cout << "/* "<< _WHITE << "BASIC TESTS" << _YELLOW << " */" << std::endl;
std::cout << "/* ********************************************************************** */" << _END << std::endl;
std::cout << std::endl;
ft::vector<int> myv;
std::vector<int> vector;
std::cout << "ft::vector<" << _PURPLE << "int" << _END << "> myv;" << std::endl;
std::cout << "std::vector<" << _PURPLE << "int" << _END << "> vector;" << std::endl;
std::cout << std::endl;
std::cout << "myv.max_size(): " << myv.max_size() << std::endl;
std::cout << "vector.max_size(): " << vector.max_size() << std::endl;
std::cout << std::endl;
compareVector("vector.empty()", myv, vector);
compareVector("vector.size()", myv, vector);
// myv.pop_back();
//vector.pop_back(); --> if empty std::vector segfault
// myv.front();
//vector.front(); --> if empty std::vector segfault
myv.back();
vector.back();
std::cout << _WHITE << "# testing out_of_range exception" << _END << std::endl;
std::cout << "myv.at(0):" << std::endl;
try
{
myv.at(0);
}
catch (std::exception &e)
{
std::cerr << "Catching exception myv: " << e.what() << std::endl;
}
std::cout << "vector.at(0):" << std::endl;
try
{
vector.at(0);
}
catch (std::exception &e)
{
std::cerr << "Catching exception vector: " << e.what() << std::endl;
}
std::cout << std::endl;
std::cout << "myv.capacity(): " << myv.capacity() << std::endl;
std::cout << "vector.capacity(): " << vector.capacity() << std::endl;
myv.reserve(0);
vector.reserve(0);
std::cout << "myv.reserve(0);" << std::endl;
std::cout << "vector.reserve(0);" << std::endl;
std::cout << "myv.capacity(): " << myv.capacity() << std::endl;
std::cout << "vector.capacity(): " << vector.capacity() << std::endl;
myv.reserve(1);
vector.reserve(1);
std::cout << "myv.reserve(1);" << std::endl;
std::cout << "vector.reserve(1);" << std::endl;
std::cout << "myv.capacity(): " << myv.capacity() << std::endl;
std::cout << "vector.capacity(): " << vector.capacity() << std::endl;
std::cout << std::endl;
std::cout << _WHITE << "# testing reserve exception" << _END << std::endl;
std::cout << "myv.reserve(" << std::numeric_limits<size_t>::max() << ");" << std::endl;
try
{
myv.reserve(std::numeric_limits<size_t>::max());
}
catch (std::exception &e)
{
std::cerr << "Catching exception myv: " << e.what() << std::endl;
}
std::cout << "vector.reserve(" << std::numeric_limits<size_t>::max() << ");" << std::endl;
try
{
vector.reserve(std::numeric_limits<size_t>::max());
}
catch (std::exception &e)
{
std::cerr << "Catching exception vector: " << e.what() << std::endl;
}
std::cout << std::endl;
myv.resize(8);
vector.resize(8);
compareVector("vector.resize(8)", myv, vector);
std::cout << "myv.capacity(): " << myv.capacity() << std::endl;
std::cout << "vector.capacity(): " << vector.capacity() << std::endl;
myv.push_back(4);
vector.push_back(4);
compareVector("vector.push_back(4)", myv, vector);
std::cout << _WHITE << "# std::vector resize more on push_back but both works" << _END << std::endl;
std::cout << "myv.capacity(): " << myv.capacity() << std::endl;
std::cout << "vector.capacity(): " << vector.capacity() << std::endl;
myv.erase(myv.begin());
vector.erase(vector.begin());
compareVector("vector.erase(vector.begin())", myv, vector);
std::cout << _WHITE << "# launching clear twice" << _END << std::endl;
myv.clear();
vector.clear();
compareVector("vector.clear()", myv, vector);
myv.clear();
vector.clear();
compareVector("vector.clear()", myv, vector);
std::cout << "myv.capacity(): " << myv.capacity() << std::endl;
std::cout << "vector.capacity(): " << vector.capacity() << std::endl;
std::cout << _YELLOW << "/* ********************************************************************** */" << std::endl;
std::cout << "/* "<< _WHITE << "ADVANCED TESTS" << _YELLOW << " */" << std::endl;
std::cout << "/* ********************************************************************** */" << _END << std::endl;
std::cout << std::endl;
myv.assign((size_t)10, 8);
vector.assign((size_t)10, 8);
compareVector("vector.assign(10, 8)", myv, vector);
myv.assign(myv.begin(), myv.begin() + 4); // wtf that works
vector.assign(vector.begin(), vector.begin() + 4);
compareVector("vector.assign(vector.begin(), vector.begin() + 4)", myv, vector);
ft::vector<int> myv2;
std::vector<int> vector2;
std::cout << "ft::vector<" << _PURPLE << "int" << _END << "> myv2;" << std::endl;
std::cout << "std::vector<" << _PURPLE << "int" << _END << "> vector2;" << std::endl;
myv.swap(myv2);
vector.swap(vector2);
compareVector("vector.swap(vector2) - vector", myv, vector);
compareVector("vector2", myv2, vector2);
myv.swap(myv2);
vector.swap(vector2);
compareVector("vector.swap(vector2) - vector", myv, vector);
compareVector("vector2", myv2, vector2);
myv.erase(myv.begin() + 2);
vector.erase(vector.begin() + 2);
compareVector("vector.erase(this->begin() + 2", myv, vector);
myv2 = myv;
vector2 = vector;
compareVector("vector2 = vector", myv2, vector2);
myv.at(2) = 1;
vector.at(2) = 1;
compareVector("vector.at(2) = 1", myv, vector);
myv[1] = 0;
vector[1] = 0;
compareVector("vector[1] = 0", myv, vector);
std::cout << _WHITE << "# comparaisons tests" << _END << std::endl;
std::cout << std::setw(30) << "myv < myv2: " << (myv < myv2) << std::endl;
std::cout << std::setw(30) << "vector < vector2: " << (vector < vector2) << std::endl;
std::cout << std::endl;
std::cout << std::setw(30) << "myv > myv2: " << (myv > myv2) << std::endl;
std::cout << std::setw(30) << "vector > vector2: " << (vector > vector2) << std::endl;
std::cout << std::endl;
std::cout << std::setw(30) << "myv == myv2: " << (myv == myv2) << std::endl;
std::cout << std::setw(30) << "vector == vector2: " << (vector == vector2) << std::endl;
std::cout << std::endl;
std::cout << std::setw(30) << "myv != myv2: " << (myv == myv2) << std::endl;
std::cout << std::setw(30) << "vector != vector2: " << (vector == vector2) << std::endl;
std::cout << std::endl;
std::cout << std::setw(30) << "myv <= myv2: " << (myv <= myv2) << std::endl;
std::cout << std::setw(30) << "vector <= vector2: " << (vector <= vector2) << std::endl;
std::cout << std::endl;
std::cout << std::setw(30) << "myv >= myv2: " << (myv >= myv2) << std::endl;
std::cout << std::setw(30) << "vector >= vector2: " << (vector >= vector2) << std::endl;
}
| 38.182979 | 138 | 0.510309 | [
"vector"
] |
5b2cd0cbe2db645d8899c04f43ffd8f32fb85bf7 | 9,426 | cc | C++ | modules/video_coding/main/source/timing.cc | aleonliao/webrtc-3.31 | a282cc166883aea82a8149d64e82ca29aa9f27f1 | [
"DOC",
"BSD-3-Clause"
] | null | null | null | modules/video_coding/main/source/timing.cc | aleonliao/webrtc-3.31 | a282cc166883aea82a8149d64e82ca29aa9f27f1 | [
"DOC",
"BSD-3-Clause"
] | null | null | null | modules/video_coding/main/source/timing.cc | aleonliao/webrtc-3.31 | a282cc166883aea82a8149d64e82ca29aa9f27f1 | [
"DOC",
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/modules/video_coding/main/source/timing.h"
#include "webrtc/modules/video_coding/main/source/internal_defines.h"
#include "webrtc/modules/video_coding/main/source/jitter_buffer_common.h"
#include "webrtc/modules/video_coding/main/source/timestamp_extrapolator.h"
#include "webrtc/system_wrappers/interface/clock.h"
#include "webrtc/system_wrappers/interface/trace.h"
namespace webrtc {
VCMTiming::VCMTiming(Clock* clock,
int32_t vcmId,
int32_t timingId,
VCMTiming* masterTiming)
:
_critSect(CriticalSectionWrapper::CreateCriticalSection()),
_vcmId(vcmId),
_clock(clock),
_timingId(timingId),
_master(false),
_tsExtrapolator(),
_codecTimer(),
_renderDelayMs(kDefaultRenderDelayMs),
_minTotalDelayMs(0),
_requiredDelayMs(0),
_currentDelayMs(0),
_prevFrameTimestamp(0)
{
if (masterTiming == NULL)
{
_master = true;
_tsExtrapolator = new VCMTimestampExtrapolator(_clock, vcmId, timingId);
}
else
{
_tsExtrapolator = masterTiming->_tsExtrapolator;
}
}
VCMTiming::~VCMTiming()
{
if (_master)
{
delete _tsExtrapolator;
}
delete _critSect;
}
void
VCMTiming::Reset(int64_t nowMs /* = -1 */)
{
CriticalSectionScoped cs(_critSect);
if (nowMs > -1)
{
_tsExtrapolator->Reset(nowMs);
}
else
{
_tsExtrapolator->Reset();
}
_codecTimer.Reset();
_renderDelayMs = kDefaultRenderDelayMs;
_minTotalDelayMs = 0;
_requiredDelayMs = 0;
_currentDelayMs = 0;
_prevFrameTimestamp = 0;
}
void VCMTiming::ResetDecodeTime()
{
_codecTimer.Reset();
}
void
VCMTiming::SetRenderDelay(uint32_t renderDelayMs)
{
CriticalSectionScoped cs(_critSect);
_renderDelayMs = renderDelayMs;
}
void
VCMTiming::SetMinimumTotalDelay(uint32_t minTotalDelayMs)
{
CriticalSectionScoped cs(_critSect);
_minTotalDelayMs = minTotalDelayMs;
}
void
VCMTiming::SetRequiredDelay(uint32_t requiredDelayMs)
{
CriticalSectionScoped cs(_critSect);
if (requiredDelayMs != _requiredDelayMs)
{
if (_master)
{
WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, VCMId(_vcmId, _timingId),
"Desired jitter buffer level: %u ms", requiredDelayMs);
}
_requiredDelayMs = requiredDelayMs;
// When in initial state, set current delay to minimum delay.
if (_currentDelayMs == 0) {
_currentDelayMs = _requiredDelayMs;
}
}
}
void VCMTiming::UpdateCurrentDelay(uint32_t frameTimestamp)
{
CriticalSectionScoped cs(_critSect);
uint32_t targetDelayMs = TargetDelayInternal();
if (_currentDelayMs == 0)
{
// Not initialized, set current delay to target.
_currentDelayMs = targetDelayMs;
}
else if (targetDelayMs != _currentDelayMs)
{
int64_t delayDiffMs = static_cast<int64_t>(targetDelayMs) -
_currentDelayMs;
// Never change the delay with more than 100 ms every second. If we're changing the
// delay in too large steps we will get noticeable freezes. By limiting the change we
// can increase the delay in smaller steps, which will be experienced as the video is
// played in slow motion. When lowering the delay the video will be played at a faster
// pace.
int64_t maxChangeMs = 0;
if (frameTimestamp < 0x0000ffff && _prevFrameTimestamp > 0xffff0000)
{
// wrap
maxChangeMs = kDelayMaxChangeMsPerS * (frameTimestamp +
(static_cast<int64_t>(1)<<32) - _prevFrameTimestamp) / 90000;
}
else
{
maxChangeMs = kDelayMaxChangeMsPerS *
(frameTimestamp - _prevFrameTimestamp) / 90000;
}
if (maxChangeMs <= 0)
{
// Any changes less than 1 ms are truncated and
// will be postponed. Negative change will be due
// to reordering and should be ignored.
return;
}
delayDiffMs = std::max(delayDiffMs, -maxChangeMs);
delayDiffMs = std::min(delayDiffMs, maxChangeMs);
_currentDelayMs = _currentDelayMs + static_cast<int32_t>(delayDiffMs);
}
_prevFrameTimestamp = frameTimestamp;
}
void VCMTiming::UpdateCurrentDelay(int64_t renderTimeMs,
int64_t actualDecodeTimeMs)
{
CriticalSectionScoped cs(_critSect);
uint32_t targetDelayMs = TargetDelayInternal();
int64_t delayedMs = actualDecodeTimeMs -
(renderTimeMs - MaxDecodeTimeMs() - _renderDelayMs);
if (delayedMs < 0)
{
return;
}
if (_currentDelayMs + delayedMs <= targetDelayMs)
{
_currentDelayMs += static_cast<uint32_t>(delayedMs);
}
else
{
_currentDelayMs = targetDelayMs;
}
}
int32_t
VCMTiming::StopDecodeTimer(uint32_t timeStamp,
int64_t startTimeMs,
int64_t nowMs)
{
CriticalSectionScoped cs(_critSect);
const int32_t maxDecTime = MaxDecodeTimeMs();
int32_t timeDiffMs = _codecTimer.StopTimer(startTimeMs, nowMs);
if (timeDiffMs < 0)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCoding, VCMId(_vcmId, _timingId),
"Codec timer error: %d", timeDiffMs);
assert(false);
}
if (_master)
{
WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, VCMId(_vcmId, _timingId),
"Frame decoded: timeStamp=%u decTime=%d maxDecTime=%u, at %u",
timeStamp, timeDiffMs, maxDecTime, MaskWord64ToUWord32(nowMs));
}
return 0;
}
void
VCMTiming::IncomingTimestamp(uint32_t timeStamp, int64_t nowMs)
{
CriticalSectionScoped cs(_critSect);
_tsExtrapolator->Update(nowMs, timeStamp, _master);
}
int64_t
VCMTiming::RenderTimeMs(uint32_t frameTimestamp, int64_t nowMs) const
{
CriticalSectionScoped cs(_critSect);
const int64_t renderTimeMs = RenderTimeMsInternal(frameTimestamp, nowMs);
if (_master)
{
WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, VCMId(_vcmId, _timingId),
"Render frame %u at %u. Render delay %u, required delay %u,"
" max decode time %u, min total delay %u",
frameTimestamp, MaskWord64ToUWord32(renderTimeMs), _renderDelayMs,
_requiredDelayMs, MaxDecodeTimeMs(),_minTotalDelayMs);
}
return renderTimeMs;
}
int64_t
VCMTiming::RenderTimeMsInternal(uint32_t frameTimestamp, int64_t nowMs) const
{
int64_t estimatedCompleteTimeMs =
_tsExtrapolator->ExtrapolateLocalTime(frameTimestamp);
if (_master)
{
WEBRTC_TRACE(webrtc::kTraceDebug, webrtc::kTraceVideoCoding, VCMId(_vcmId, _timingId),
"ExtrapolateLocalTime(%u)=%u ms",
frameTimestamp, MaskWord64ToUWord32(estimatedCompleteTimeMs));
}
if (estimatedCompleteTimeMs == -1)
{
estimatedCompleteTimeMs = nowMs;
}
// Make sure that we have at least the total minimum delay.
uint32_t actual_delay = std::max(_currentDelayMs, _minTotalDelayMs);
return estimatedCompleteTimeMs + actual_delay;
}
// Must be called from inside a critical section
int32_t
VCMTiming::MaxDecodeTimeMs(FrameType frameType /*= kVideoFrameDelta*/) const
{
const int32_t decodeTimeMs = _codecTimer.RequiredDecodeTimeMs(frameType);
if (decodeTimeMs < 0)
{
WEBRTC_TRACE(webrtc::kTraceError, webrtc::kTraceVideoCoding, VCMId(_vcmId, _timingId),
"Negative maximum decode time: %d", decodeTimeMs);
return -1;
}
return decodeTimeMs;
}
uint32_t
VCMTiming::MaxWaitingTime(int64_t renderTimeMs, int64_t nowMs) const
{
CriticalSectionScoped cs(_critSect);
const int64_t maxWaitTimeMs = renderTimeMs - nowMs -
MaxDecodeTimeMs() - _renderDelayMs;
if (maxWaitTimeMs < 0)
{
return 0;
}
return static_cast<uint32_t>(maxWaitTimeMs);
}
bool
VCMTiming::EnoughTimeToDecode(uint32_t availableProcessingTimeMs) const
{
CriticalSectionScoped cs(_critSect);
int32_t maxDecodeTimeMs = MaxDecodeTimeMs();
if (maxDecodeTimeMs < 0)
{
// Haven't decoded any frames yet, try decoding one to get an estimate
// of the decode time.
return true;
}
else if (maxDecodeTimeMs == 0)
{
// Decode time is less than 1, set to 1 for now since
// we don't have any better precision. Count ticks later?
maxDecodeTimeMs = 1;
}
return static_cast<int32_t>(availableProcessingTimeMs) - maxDecodeTimeMs > 0;
}
uint32_t
VCMTiming::TargetVideoDelay() const
{
CriticalSectionScoped cs(_critSect);
return TargetDelayInternal();
}
uint32_t
VCMTiming::TargetDelayInternal() const
{
return std::max(_minTotalDelayMs,
_requiredDelayMs + MaxDecodeTimeMs() + _renderDelayMs);
}
}
| 29.641509 | 98 | 0.664333 | [
"render"
] |
5b2f1d025158666549cb2dab6aaac549723bcace | 17,363 | cpp | C++ | opencv_contrib/src/+cv/private/DisparityWLSFilter_.cpp | 1123852253/mexopencv | 17db690133299f561924a45e9092673a4df66c5b | [
"BSD-3-Clause"
] | 571 | 2015-01-04T06:23:19.000Z | 2022-03-31T07:37:19.000Z | opencv_contrib/src/+cv/private/DisparityWLSFilter_.cpp | 1123852253/mexopencv | 17db690133299f561924a45e9092673a4df66c5b | [
"BSD-3-Clause"
] | 362 | 2015-01-06T14:20:46.000Z | 2022-01-20T08:10:46.000Z | opencv_contrib/src/+cv/private/DisparityWLSFilter_.cpp | 1123852253/mexopencv | 17db690133299f561924a45e9092673a4df66c5b | [
"BSD-3-Clause"
] | 300 | 2015-01-20T03:21:27.000Z | 2022-03-31T07:36:37.000Z | /**
* @file DisparityWLSFilter_.cpp
* @brief mex interface for cv::ximgproc::DisparityWLSFilter
* @ingroup ximgproc
* @author Amro
* @date 2016
*/
#include "mexopencv.hpp"
#include "opencv2/ximgproc.hpp"
#include <typeinfo>
using namespace std;
using namespace cv;
using namespace cv::ximgproc;
// Persistent objects
namespace {
/// Last object id to allocate
int last_id = 0;
/// Object container
map<int,Ptr<DisparityWLSFilter> > obj_;
/// Option values for StereoBM PreFilterType
const ConstMap<string, int> PreFilerTypeMap = ConstMap<string, int>
("NormalizedResponse", cv::StereoBM::PREFILTER_NORMALIZED_RESPONSE)
("XSobel", cv::StereoBM::PREFILTER_XSOBEL);
/// Option values for StereoSGBM mode
const ConstMap<string, int> SGBMModeMap = ConstMap<string, int>
("SGBM", cv::StereoSGBM::MODE_SGBM)
("HH", cv::StereoSGBM::MODE_HH)
("SGBM3Way", cv::StereoSGBM::MODE_SGBM_3WAY)
("HH4", cv::StereoSGBM::MODE_HH4);
/** Convert a StereoMatcher to MxArray
* @param p smart poitner to an instance of cv::StereoMatcher
* @return output MxArray structure
*/
MxArray toStruct(Ptr<StereoMatcher> p)
{
MxArray s(MxArray::Struct());
if (!p.empty()) {
s.set("TypeId", string(typeid(*p).name()));
s.set("MinDisparity", p->getMinDisparity());
s.set("NumDisparities", p->getNumDisparities());
s.set("BlockSize", p->getBlockSize());
s.set("SpeckleWindowSize", p->getSpeckleWindowSize());
s.set("SpeckleRange", p->getSpeckleRange());
s.set("Disp12MaxDiff", p->getDisp12MaxDiff());
{
Ptr<StereoBM> pp = p.dynamicCast<StereoBM>();
if (!pp.empty()) {
s.set("PreFilterType", pp->getPreFilterType());
s.set("PreFilterSize", pp->getPreFilterSize());
s.set("PreFilterCap", pp->getPreFilterCap());
s.set("TextureThreshold", pp->getTextureThreshold());
s.set("UniquenessRatio", pp->getUniquenessRatio());
s.set("SmallerBlockSize", pp->getSmallerBlockSize());
s.set("ROI1", pp->getROI1());
s.set("ROI2", pp->getROI2());
}
}
{
Ptr<StereoSGBM> pp = p.dynamicCast<StereoSGBM>();
if (!pp.empty()) {
s.set("PreFilterCap", pp->getPreFilterCap());
s.set("UniquenessRatio", pp->getUniquenessRatio());
s.set("P1", pp->getP1());
s.set("P2", pp->getP2());
s.set("Mode", pp->getMode());
}
}
}
return s;
}
/** Create an instance of StereoBM using options in arguments
* @param first iterator at the beginning of the vector range
* @param last iterator at the end of the vector range
* @return smart pointer to created StereoBM
*/
Ptr<StereoBM> create_StereoBM(
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
ptrdiff_t len = std::distance(first, last);
nargchk((len%2)==0);
int numDisparities = 0;
int blockSize = 21;
int minDisparity = 0;
int speckleWindowSize = 0;
int speckleRange = 0;
int disp12MaxDiff = -1;
int preFilterType = cv::StereoBM::PREFILTER_XSOBEL;
int preFilterSize = 9;
int preFilterCap = 31;
int textureThreshold = 10;
int uniquenessRatio = 15;
int smallerBlockSize = 0;
Rect roi1;
Rect roi2;
for (; first != last; first += 2) {
string key(first->toString());
const MxArray& val = *(first + 1);
if (key == "NumDisparities")
numDisparities = val.toInt();
else if (key == "BlockSize")
blockSize = val.toInt();
else if (key == "MinDisparity")
minDisparity = val.toInt();
else if (key == "SpeckleWindowSize")
speckleWindowSize = val.toInt();
else if (key == "SpeckleRange")
speckleRange = val.toInt();
else if (key == "Disp12MaxDiff")
disp12MaxDiff = val.toInt();
else if (key == "PreFilterType")
preFilterType = (val.isChar() ?
PreFilerTypeMap[val.toString()] : val.toInt());
else if (key == "PreFilterSize")
preFilterSize = val.toInt();
else if (key == "PreFilterCap")
preFilterCap = val.toInt();
else if (key == "TextureThreshold")
textureThreshold = val.toInt();
else if (key == "UniquenessRatio")
uniquenessRatio = val.toInt();
else if (key == "SmallerBlockSize")
smallerBlockSize = val.toInt();
else if (key == "ROI1")
roi1 = val.toRect();
else if (key == "ROI2")
roi2 = val.toRect();
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
Ptr<StereoBM> p = StereoBM::create(numDisparities, blockSize);
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error", "Failed to create StereoBM");
p->setMinDisparity(minDisparity);
p->setSpeckleWindowSize(speckleWindowSize);
p->setSpeckleRange(speckleRange);
p->setDisp12MaxDiff(disp12MaxDiff);
p->setPreFilterType(preFilterType);
p->setPreFilterSize(preFilterSize);
p->setPreFilterCap(preFilterCap);
p->setTextureThreshold(textureThreshold);
p->setUniquenessRatio(uniquenessRatio);
p->setSmallerBlockSize(smallerBlockSize);
p->setROI1(roi1);
p->setROI2(roi2);
return p;
}
/** Create an instance of StereoSGBM using options in arguments
* @param first iterator at the beginning of the vector range
* @param last iterator at the end of the vector range
* @return smart pointer to created StereoSGBM
*/
Ptr<StereoSGBM> create_StereoSGBM(
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
ptrdiff_t len = std::distance(first, last);
nargchk((len%2)==0);
int minDisparity = 0;
int numDisparities = 16;
int blockSize = 3;
int P1 = 0;
int P2 = 0;
int disp12MaxDiff = 0;
int preFilterCap = 0;
int uniquenessRatio = 0;
int speckleWindowSize = 0;
int speckleRange = 0;
int mode = cv::StereoSGBM::MODE_SGBM;
for (; first != last; first += 2) {
string key(first->toString());
const MxArray& val = *(first + 1);
if (key == "MinDisparity")
minDisparity = val.toInt();
else if (key == "NumDisparities")
numDisparities = val.toInt();
else if (key == "BlockSize")
blockSize = val.toInt();
else if (key == "P1")
P1 = val.toInt();
else if (key == "P2")
P2 = val.toInt();
else if (key == "Disp12MaxDiff")
disp12MaxDiff = val.toInt();
else if (key == "PreFilterCap")
preFilterCap = val.toInt();
else if (key == "UniquenessRatio")
uniquenessRatio = val.toInt();
else if (key == "SpeckleWindowSize")
speckleWindowSize = val.toInt();
else if (key == "SpeckleRange")
speckleRange = val.toInt();
else if (key == "Mode")
mode = (val.isChar() ?
SGBMModeMap[val.toString()] : val.toInt());
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
return StereoSGBM::create(minDisparity, numDisparities,
blockSize, P1, P2, disp12MaxDiff, preFilterCap, uniquenessRatio,
speckleWindowSize, speckleRange, mode);
}
/** Create an instance of StereoMatcher using options in arguments
* @param type stereo matcher type, one of:
* - "StereoBM"
* - "StereoSGBM"
* @param first iterator at the beginning of the vector range
* @param last iterator at the end of the vector range
* @return smart pointer to created StereoMatcher
*/
Ptr<StereoMatcher> create_StereoMatcher(
const string& type,
vector<MxArray>::const_iterator first,
vector<MxArray>::const_iterator last)
{
Ptr<StereoMatcher> p;
if (type == "StereoBM")
p = create_StereoBM(first, last);
else if (type == "StereoSGBM")
p = create_StereoSGBM(first, last);
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized stereo matcher %s", type.c_str());
if (p.empty())
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to create StereoMatcher");
return p;
}
}
/**
* Main entry called from Matlab
* @param nlhs number of left-hand-side arguments
* @param plhs pointers to mxArrays in the left-hand-side
* @param nrhs number of right-hand-side arguments
* @param prhs pointers to mxArrays in the right-hand-side
*/
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// Check the number of arguments
nargchk(nrhs>=2 && nlhs<=1);
// Argument vector
vector<MxArray> rhs(prhs, prhs+nrhs);
int id = rhs[0].toInt();
string method(rhs[1].toString());
// Constructor is called. Create a new object from argument
if (method == "new") {
nargchk(nrhs==3 && nlhs<=1);
if (rhs[2].isLogicalScalar()) {
bool use_confidence = rhs[2].toBool();
obj_[++last_id] = createDisparityWLSFilterGeneric(use_confidence);
}
else {
vector<MxArray> args(rhs[2].toVector<MxArray>());
nargchk(args.size() >= 1);
Ptr<StereoMatcher> matcher_left = create_StereoMatcher(
args[0].toString(), args.begin() + 1, args.end());
obj_[++last_id] = createDisparityWLSFilter(matcher_left);
}
plhs[0] = MxArray(last_id);
mexLock();
return;
}
// static methods calls
else if (method == "createRightMatcher") {
nargchk(nrhs==3 && nlhs<=1);
vector<MxArray> args(rhs[2].toVector<MxArray>());
nargchk(args.size() >= 1);
Ptr<StereoMatcher> matcher_left = create_StereoMatcher(
args[0].toString(), args.begin() + 1, args.end());
Ptr<StereoMatcher> matcher_right = createRightMatcher(matcher_left);
plhs[0] = toStruct(matcher_right);
return;
}
else if (method == "readGT") {
nargchk(nrhs==3 && nlhs<=1);
Mat dst;
int code = readGT(rhs[2].toString(), dst);
if (code != 0)
mexErrMsgIdAndTxt("mexopencv:error",
"Failed to read ground-truth disparity map");
plhs[0] = MxArray(dst);
return;
}
else if (method == "computeMSE") {
nargchk(nrhs>=4 && (nrhs%2)==0 && nlhs<=1);
Rect ROI;
for (int i=4; i<nrhs; i+=2) {
string key(rhs[i].toString());
if (key == "ROI")
ROI = rhs[i+1].toRect();
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
Mat GT(rhs[2].toMat(rhs[2].isInt16() ? CV_16S : CV_32F)),
src(rhs[3].toMat(rhs[3].isInt16() ? CV_16S : CV_32F));
if (ROI.area() == 0)
ROI = Rect(0, 0, src.cols, src.rows);
double mse = computeMSE(GT, src, ROI);
plhs[0] = MxArray(mse);
return;
}
else if (method == "computeBadPixelPercent") {
nargchk(nrhs>=4 && (nrhs%2)==0 && nlhs<=1);
Rect ROI;
int thresh = 24;
for (int i=4; i<nrhs; i+=2) {
string key(rhs[i].toString());
if (key == "ROI")
ROI = rhs[i+1].toRect();
else if (key == "Thresh")
thresh = rhs[i+1].toInt();
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
Mat GT(rhs[2].toMat(rhs[2].isInt16() ? CV_16S : CV_32F)),
src(rhs[3].toMat(rhs[3].isInt16() ? CV_16S : CV_32F));
if (ROI.area() == 0)
ROI = Rect(0, 0, src.cols, src.rows);
double prcnt = computeBadPixelPercent(GT, src, ROI, thresh);
plhs[0] = MxArray(prcnt);
return;
}
else if (method == "getDisparityVis") {
nargchk(nrhs>=3 && (nrhs%2)==1 && nlhs<=1);
double scale = 1.0;
for (int i=3; i<nrhs; i+=2) {
string key(rhs[i].toString());
if (key == "Scale")
scale = rhs[i+1].toDouble();
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
Mat src(rhs[2].toMat(rhs[2].isInt16() ? CV_16S : CV_32F)),
dst;
getDisparityVis(src, dst, scale);
plhs[0] = MxArray(dst);
return;
}
// Big operation switch
Ptr<DisparityWLSFilter> obj = obj_[id];
if (obj.empty())
mexErrMsgIdAndTxt("mexopencv:error", "Object not found id=%d", id);
if (method == "delete") {
nargchk(nrhs==2 && nlhs==0);
obj_.erase(id);
mexUnlock();
}
else if (method == "clear") {
nargchk(nrhs==2 && nlhs==0);
obj->clear();
}
else if (method == "load") {
nargchk(nrhs>=3 && (nrhs%2)==1 && nlhs==0);
string objname;
bool loadFromString = false;
for (int i=3; i<nrhs; i+=2) {
string key(rhs[i].toString());
if (key == "ObjName")
objname = rhs[i+1].toString();
else if (key == "FromString")
loadFromString = rhs[i+1].toBool();
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
/*
obj_[id] = (loadFromString ?
Algorithm::loadFromString<DisparityWLSFilter>(rhs[2].toString(), objname) :
Algorithm::load<DisparityWLSFilter>(rhs[2].toString(), objname));
*/
///*
// HACK: workaround for missing DisparityWLSFilter::create()
FileStorage fs(rhs[2].toString(), FileStorage::READ +
(loadFromString ? FileStorage::MEMORY : 0));
if (!fs.isOpened())
mexErrMsgIdAndTxt("mexopencv:error", "Failed to open file");
FileNode fn(objname.empty() ? fs.getFirstTopLevelNode() : fs[objname]);
if (fn.empty())
mexErrMsgIdAndTxt("mexopencv:error", "Failed to get node");
obj->read(fn);
//*/
}
else if (method == "save") {
nargchk(nrhs==3 && nlhs==0);
obj->save(rhs[2].toString());
}
else if (method == "empty") {
nargchk(nrhs==2 && nlhs<=1);
plhs[0] = MxArray(obj->empty());
}
else if (method == "getDefaultName") {
nargchk(nrhs==2 && nlhs<=1);
plhs[0] = MxArray(obj->getDefaultName());
}
else if (method == "filter") {
nargchk(nrhs>=5 && (nrhs%2)==1 && nlhs<=1);
Rect ROI;
Mat right_view;
for (int i=5; i<nrhs; i+=2) {
string key(rhs[i].toString());
if (key == "ROI")
ROI = rhs[i+1].toRect();
else if (key == "RightView")
right_view = rhs[i+1].toMat(CV_8U);
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized option %s", key.c_str());
}
Mat disparity_map_left(rhs[2].toMat(rhs[2].isInt16() ? CV_16S : CV_32F)),
disparity_map_right(rhs[3].toMat(rhs[3].isInt16() ? CV_16S : CV_32F)),
left_view(rhs[4].toMat(CV_8U)),
filtered_disparity_map;
obj->filter(disparity_map_left, left_view, filtered_disparity_map,
disparity_map_right, ROI, right_view);
plhs[0] = MxArray(filtered_disparity_map);
}
else if (method == "getConfidenceMap") {
nargchk(nrhs==2 && nlhs<=1);
plhs[0] = MxArray(obj->getConfidenceMap());
}
else if (method == "getROI") {
nargchk(nrhs==2 && nlhs<=1);
plhs[0] = MxArray(obj->getROI());
}
else if (method == "get") {
nargchk(nrhs==3 && nlhs<=1);
string prop(rhs[2].toString());
if (prop == "Lambda")
plhs[0] = MxArray(obj->getLambda());
else if (prop == "SigmaColor")
plhs[0] = MxArray(obj->getSigmaColor());
else if (prop == "LRCthresh")
plhs[0] = MxArray(obj->getLRCthresh());
else if (prop == "DepthDiscontinuityRadius")
plhs[0] = MxArray(obj->getDepthDiscontinuityRadius());
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized property %s", prop.c_str());
}
else if (method == "set") {
nargchk(nrhs==4 && nlhs==0);
string prop(rhs[2].toString());
if (prop == "Lambda")
obj->setLambda(rhs[3].toDouble());
else if (prop == "SigmaColor")
obj->setSigmaColor(rhs[3].toDouble());
else if (prop == "LRCthresh")
obj->setLRCthresh(rhs[3].toInt());
else if (prop == "DepthDiscontinuityRadius")
obj->setDepthDiscontinuityRadius(rhs[3].toInt());
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized property %s", prop.c_str());
}
else
mexErrMsgIdAndTxt("mexopencv:error",
"Unrecognized operation %s", method.c_str());
}
| 36.553684 | 87 | 0.558256 | [
"object",
"vector"
] |
5b2f5601b8030e6934a0eb870facdd31d68a18bd | 295 | hpp | C++ | Sandbox/src/SandBox.hpp | ajp-9/nimble-engine | c81a650249231978b5c971956ec2881727869dff | [
"MIT"
] | 1 | 2021-03-07T22:50:28.000Z | 2021-03-07T22:50:28.000Z | Sandbox/src/SandBox.hpp | ajp-9/nimble-engine | c81a650249231978b5c971956ec2881727869dff | [
"MIT"
] | null | null | null | Sandbox/src/SandBox.hpp | ajp-9/nimble-engine | c81a650249231978b5c971956ec2881727869dff | [
"MIT"
] | null | null | null | #pragma once
#include <dex/Dexlite.hpp>
#include <memory>
class SandBox : public dex::Program
{
public:
virtual void Init() override;
virtual void Shutdown() override;
virtual void update() override;
virtual void render() override;
private:
};
DEXLITE_DEFINE_MAIN(SandBox);
| 16.388889 | 38 | 0.711864 | [
"render"
] |
5b3266de0dda452d0eae93331d313484f7932dbb | 132,333 | cpp | C++ | big_homework/mainwindow.cpp | caozhangjie/Graph-Visualization-System | 1b66ac9ea7662eddd33542039f66b75f480d2d0a | [
"MIT"
] | null | null | null | big_homework/mainwindow.cpp | caozhangjie/Graph-Visualization-System | 1b66ac9ea7662eddd33542039f66b75f480d2d0a | [
"MIT"
] | null | null | null | big_homework/mainwindow.cpp | caozhangjie/Graph-Visualization-System | 1b66ac9ea7662eddd33542039f66b75f480d2d0a | [
"MIT"
] | null | null | null | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include "pointcolor.h"
#include "filterdialog.h"
#include "filtertopicdialog.h"
#include <QPainter>
#include <QTimer>
#include <QTime>
#include <QColor>
#include<QKeyEvent>
#include<Qt>
#include<QPoint>
#include<QSize>
#include <QMessageBox>
#include <QFileDialog>
#include <QTextStream>
#include <QRect>
#include <QDebug>
#include "dialog.h"
#include "nobezierdialog.h"
#include "cartoondialog.h"
MainWindow::~MainWindow()
{
delete ui;
}
MainWindow::MainWindow(PaperConferenceAuthorGraph & temp, TopicGraph & temp1, QWidget * parent):QMainWindow(parent),
t_graph(temp1), p_graph(temp), layout_timer(this), ui(new Ui::MainWindow), strategy_num(9), edge_color(140)
{
ui->setupUi(this);
is_in_local = false;
int node_num = p_graph.getNodeNum();
//设置虚拟原点及放缩比
my_scale = 1;
Opoint = vector<int>(3);
Opoint[0] = 0;
Opoint[1] = 0;
Opoint[2] = 0;
height = 0;
radis = 5;
//设定初始布局
strategy = START;
//bool值得初始化
in_cartoon = false;
is_highlight = false;
is_pull = false;
is_key_v_pressed = false;
is_key_h_pressed = false;
is_in_filter = false;
is_dragging = false;
is_single = false;
is_mouse_pressed = false;
is_in_start = true;
is_spinBox_changed = false;
//选中的点的id的初始化
full_big = 0;
highlight_number = 0;
alpha_degree = -1;
data_change = 0;
//设置所有初始选定值
id_move_point = 0;
id_select_point = -1;
id_select_edge = -1;
//设置窗口大小及调节滚动条位置
resize(1920, 1000);
main_length = 1920;
main_width = 1000;
ui->verticalScrollBar->setSliderPosition(50);
ui->horizontalScrollBar->setSliderPosition(50);
last_posi_vertical = 50;
last_posi_horizantol = 50;
alpha_start = 0;
//设置背景色
setAutoFillBackground(true);
QPalette palette;
palette.setColor(QPalette::Background, QColor(0,0,0));
setPalette(palette);
//设置控件
QPalette my_palette;
my_palette.setColor(QPalette::WindowText, QColor(210,210,210));
ui->start_btn->setGeometry(920, 800, 80, 60);
ui->groupBox->setPalette(my_palette);
ui->node_out_slider->setRange(0, 72);
ui->node_in_slider->setRange(0, 32);
ui->node_sum_slider->setRange(0, 82);
ui->weight_slider->setRange(0, 73);
ui->toSpinBox->setMinimum(0);
ui->toSpinBox->setMaximum(72);
ui->fromSpinBox->setMinimum(0);
ui->fromSpinBox->setMaximum(82);
ui->sumSpinBox->setMinimum(0);
ui->sumSpinBox->setMaximum(73);
ui->weightSpinBox->setMinimum(0);
ui->weightSpinBox->setMaximum(0.73);
ui->weightSpinBox->setSingleStep(0.01);
//设置edge weight
int number = t_graph.getEdgeNum();
edge_state_t.resize(number);
for(int i =0 ;i < number; i++)
{
edge_weight.push_back(t_graph.getEdge()[i]->getWeight());
edge_state_t[i] = true;
}
//初始为paper图
has_weight = false;
//设置动画时间器间隔
layout_timer.setInterval(20);
connect(&layout_timer, SIGNAL(timeout()), this, SLOT(changeLayout()));
//设置切换数据渐变效果
data_timer.setInterval(10);
connect(&data_timer, SIGNAL(timeout()), this, SLOT(changeData()));
//设置开始动画
start_timer.setInterval(10);
connect(&start_timer, SIGNAL(timeout()), this, SLOT(changeDataStart()));
//设置两种数据三种度数
point_weight.resize(2);
point_weight[0].resize(3);
point_weight[1].resize(3);
point_num_edge_state.resize(2);
point_num_edge_state[0].resize(3);
point_num_edge_state[1].resize(3);
//设置各节点数组大小
setPointSize(node_num);
//设置个节点初始属性
for(int i= 0; i < node_num; i++)
{
point_num_edge_state[0][0][i] = true;
point_num_edge_state[0][1][i] = true;
point_num_edge_state[0][2][i] = true;
point_num_edge_state[1][0][i] = true;
point_num_edge_state[1][1][i] = true;
point_num_edge_state[1][2][i] = true;
velocity[i].resize(3);
temp_point[i].resize(3);
point_state[i] = true;
point_state_t[i] = true;
switch(p_graph.getNode()[i]->getType())
{
case PaperConferenceAuthorNode::PAPER:
point_type[i] = POINT_PAPER;
break;
case PaperConferenceAuthorNode::CONFERENCE:
point_type[i] = POINT_CONFERENCE;
break;
case PaperConferenceAuthorNode::AUTHOR:
point_type[i] = POINT_AUTHOR;
break;
}
point_weight[0][0][i] = p_graph.getSumNum(i);
point_weight[0][1][i] = p_graph.getInNum(i);
point_weight[0][2][i] = p_graph.getOutNum(i);
point_weight[1][0][i] = t_graph.getSumNum(i);
point_weight[1][1][i] = t_graph.getInNum(i);
point_weight[1][2][i] = t_graph.getOutNum(i);
}
//初始化各种布局算法
initializeForStrategyP();
initializeForStrategyT();
}
//初始化与Topic data相关的布局算法
void MainWindow::initializeForStrategyT()
{
const int strategy_num = 10; // strategy数量
double min_x = 0;
double min_y = 0;
double min_z = 0;
vtkSmartPointer<vtkMutableDirectedGraph> vtk_graph1 = vtkSmartPointer<vtkMutableDirectedGraph>::New();
vtkGraph* vtk_s_graph1;
vtkSmartPointer<vtkGraphLayout> layout = vtkSmartPointer<vtkGraphLayout>::New();
vtkSmartPointer<vtkForceDirectedLayoutStrategy> strategy2 = vtkSmartPointer<vtkForceDirectedLayoutStrategy>::New();
vtkSmartPointer<vtkCircularLayoutStrategy> strategy1 = vtkSmartPointer<vtkCircularLayoutStrategy>::New();
vtkSmartPointer<vtkClustering2DLayoutStrategy>strategy7 = vtkSmartPointer<vtkClustering2DLayoutStrategy>::New();
vtkSmartPointer<vtkFast2DLayoutStrategy> strategy4 = vtkSmartPointer<vtkFast2DLayoutStrategy>::New();
vtkSmartPointer<vtkRandomLayoutStrategy> strategy5 = vtkSmartPointer<vtkRandomLayoutStrategy>::New();
vtkSmartPointer<vtkSimple2DLayoutStrategy> strategy6 = vtkSmartPointer<vtkSimple2DLayoutStrategy>::New();
int node_num = p_graph.getNodeNum();
forceLayout my_layout1(t_graph, node_num);
weightLayout my_layout2(t_graph);
helloLayout start_layout(node_num);
double temp_point[3] = {0.0, 0.0, 0.0};
int edge_num = t_graph.getEdgeNum();
for(int i = 0; i < node_num; i++)
{
vtk_graph1->AddVertex();
}
for(int i = 0; i < edge_num; i++)
{
vtk_graph1->AddEdge(t_graph.getEdgeNode()[i][0], t_graph.getEdgeNode()[i][1]);
}
layout->SetInputData(vtk_graph1);
layout->SetLayoutStrategy(strategy1);
layout->Update();
vtk_s_graph1 = layout->GetOutput();
t_point.resize(strategy_num);
for(int i = 0; i < strategy_num; i++)
{
t_point[i].resize(node_num);
}
//自定义layout
start_layout.calcLayout();
start_layout.getPoint(t_point[START]);
my_layout1.calcLayout();
my_layout1.getPoint(t_point[MYLAYOUT2]);
my_layout2.setFactor(100);
my_layout2.calcLayout();
my_layout2.getPoint(t_point[MYLAYOUT1]);
min_x = 0;
min_y = 0;
for(int i = 0; i < node_num; i++)
{
min_x += t_point[MYLAYOUT2][i][0];
min_y += t_point[MYLAYOUT2][i][1];
}
min_x /= node_num;
min_y /= node_num;
for(int i = 0; i < node_num; i++)
{
t_point[MYLAYOUT2][i][0] -= min_x;
t_point[MYLAYOUT2][i][1] -= min_y;
}
min_x = 0;
min_y = 0;
for(int i = 0; i < node_num; i++)
{
min_x += t_point[MYLAYOUT1][i][0];
min_y += t_point[MYLAYOUT1][i][1];
}
min_x /= node_num;
min_y /= node_num;
for(int i = 0; i < node_num; i++)
{
t_point[MYLAYOUT1][i][0] -= min_x;
t_point[MYLAYOUT1][i][1] -= min_y;
}
//vtklayout
for(int i = 0; i < node_num; i++)
{
vtk_s_graph1->GetPoint(i, temp_point);
t_point[CICLE][i].resize(3);
t_point[CICLE][i][0] = temp_point[0] * main_length / 2.4;
t_point[CICLE][i][1] = temp_point[1] * main_width / 2.4;
t_point[CICLE][i][2] = temp_point[2];
}
layout->SetLayoutStrategy(strategy2);
layout->Update();
vtk_s_graph1 = layout->GetOutput();
for(int i = 0; i < node_num; i++)
{
vtk_s_graph1->GetPoint(i, temp_point);
t_point[FORCE][i].resize(3);
t_point[FORCE][i][0] = temp_point[0] * main_length / 1.1;
t_point[FORCE][i][1] = temp_point[1] * main_width / 1.1;
t_point[FORCE][i][2] = temp_point[2];
}
min_x = 0;
min_y = 0;
for(int i = 0; i < node_num; i++)
{
min_x += t_point[FORCE][i][0];
min_y += t_point[FORCE][i][1];
}
min_x /= node_num;
min_y /= node_num;
for(int i = 0; i < node_num; i++)
{
t_point[FORCE][i][0] -= min_x;
t_point[FORCE][i][1] -= min_y;
}
QTime time;
time= QTime::currentTime();
qsrand(time.msec()+time.second()*1000);
qrand() % 100 / 100 - 0.5;
for(int i = 0; i < node_num; i++)
{
t_point[MYLAYOUT1][i].resize(3);
t_point[MYLAYOUT1][i][0] = (double(qrand() % 100) / 100 - 0.5) * main_length / 1.5;
t_point[MYLAYOUT1][i][1] = (double(qrand() % 100) / 100 - 0.5) * main_width / 1.5;
t_point[MYLAYOUT1][i][2] = (double(qrand() % 100) / 100 - 0.5);
}
layout->SetLayoutStrategy(strategy4);
layout->Update();
vtk_s_graph1 = layout->GetOutput();
for(int i = 0; i < node_num; i++)
{
vtk_s_graph1->GetPoint(i, temp_point);
t_point[FAST2D][i].resize(3);
t_point[FAST2D][i][0] = temp_point[0] * main_length / 19;
t_point[FAST2D][i][1] = temp_point[1] * main_width / 19;
t_point[FAST2D][i][2] = temp_point[2];
}
min_x = 0;
min_y = 0;
for(int i = 0; i < node_num; i++)
{
min_x += t_point[FAST2D][i][0];
min_y += t_point[FAST2D][i][1];
}
min_x /= node_num;
min_y /= node_num;
for(int i = 0; i < node_num; i++)
{
t_point[FAST2D][i][0] -= min_x;
t_point[FAST2D][i][1] -= min_y;
}
layout->SetLayoutStrategy(strategy5);
layout->Update();
vtk_s_graph1 = layout->GetOutput();
for(int i = 0; i < node_num; i++)
{
vtk_s_graph1->GetPoint(i, temp_point);
t_point[RANDOM][i].resize(3);
t_point[RANDOM][i][0] = temp_point[0] * main_length / 1.3;
t_point[RANDOM][i][1] = temp_point[1] * main_width / 1.3;
t_point[RANDOM][i][2] = temp_point[2];
}
min_x = 0;
min_y = 0;
for(int i = 0; i < node_num; i++)
{
min_x += t_point[RANDOM][i][0];
min_y += t_point[RANDOM][i][1];
}
min_x /= node_num;
min_y /= node_num;
for(int i = 0; i < node_num; i++)
{
t_point[RANDOM][i][0] -= min_x;
t_point[RANDOM][i][1] -= min_y;
}
layout->SetLayoutStrategy(strategy6);
layout->Update();
vtk_s_graph1 = layout->GetOutput();
for(int i = 0; i < node_num; i++)
{
vtk_s_graph1->GetPoint(i, temp_point);
t_point[SIMPLE2D][i].resize(3);
t_point[SIMPLE2D][i][0] = temp_point[0] * main_length / 44;
t_point[SIMPLE2D][i][1] = temp_point[1] * main_width / 44;
t_point[SIMPLE2D][i][2] = temp_point[2];
}
min_x = 0;
min_y = 0;
for(int i = 0; i < node_num; i++)
{
min_x += t_point[SIMPLE2D][i][0];
min_y += t_point[SIMPLE2D][i][1];
}
min_x /= node_num;
min_y /= node_num;
for(int i = 0; i < node_num; i++)
{
t_point[SIMPLE2D][i][0] -= min_x;
t_point[SIMPLE2D][i][1] -= min_y;
}
layout->SetLayoutStrategy(strategy7);
layout->Update();
vtk_s_graph1 = layout->GetOutput();
for(int i = 0; i < node_num; i++)
{
vtk_s_graph1->GetPoint(i, temp_point);
t_point[CLUSTERING2D][i].resize(3);
t_point[CLUSTERING2D][i][0] = temp_point[0] * main_length / 23;
t_point[CLUSTERING2D][i][1] = temp_point[1] * main_width / 37;
t_point[CLUSTERING2D][i][2] = temp_point[2];
}
min_x = 0;
min_y = 0;
for(int i = 0; i < node_num; i++)
{
min_x += t_point[CLUSTERING2D][i][0];
min_y += t_point[CLUSTERING2D][i][1];
}
min_x /= node_num;
min_y /= node_num;
for(int i = 0; i < node_num; i++)
{
t_point[CLUSTERING2D][i][0] -= min_x;
t_point[CLUSTERING2D][i][1] -= min_y;
}
for(int i = 0; i < node_num; i++)
{
t_point[PASSTHROUGH][i].resize(3);
t_point[PASSTHROUGH][i][0] = 0;
t_point[PASSTHROUGH][i][1] = 0;
t_point[PASSTHROUGH][i][2] = 0;
}
t_point_copy = t_point;
}
//初始化与Paper Conference Author data相关的布局算法
void MainWindow::initializeForStrategyP()
{
const int strategy_num = 10;
double min_x = 0;
double min_y = 0;
vtkSmartPointer<vtkMutableDirectedGraph> vtk_graph1 = vtkSmartPointer<vtkMutableDirectedGraph>::New();
vtkGraph* vtk_s_graph1;
vtkSmartPointer<vtkGraphLayout> layout = vtkSmartPointer<vtkGraphLayout>::New();
vtkSmartPointer<vtkForceDirectedLayoutStrategy> strategy2 = vtkSmartPointer<vtkForceDirectedLayoutStrategy>::New();
vtkSmartPointer<vtkCircularLayoutStrategy> strategy1 = vtkSmartPointer<vtkCircularLayoutStrategy>::New();
vtkSmartPointer<vtkClustering2DLayoutStrategy>strategy7 = vtkSmartPointer<vtkClustering2DLayoutStrategy>::New();
vtkSmartPointer<vtkFast2DLayoutStrategy> strategy4 = vtkSmartPointer<vtkFast2DLayoutStrategy>::New();
vtkSmartPointer<vtkRandomLayoutStrategy> strategy5 = vtkSmartPointer<vtkRandomLayoutStrategy>::New();
vtkSmartPointer<vtkSimple2DLayoutStrategy> strategy6 = vtkSmartPointer<vtkSimple2DLayoutStrategy>::New();
circleLineLayout my_layout(p_graph);
lineLineLayout my_layout2(p_graph);
int node_num = p_graph.getNodeNum();
helloLayout start_layout(node_num);
double temp_point[3] = {0.0, 0.0, 0.0};
int edge_num = p_graph.getEdgeNum();
for(int i = 0; i < node_num; i++)
{
vtk_graph1->AddVertex();
}
for(int i = 0; i < edge_num; i++)
{
vtk_graph1->AddEdge(p_graph.getEdgeNode()[i][0], p_graph.getEdgeNode()[i][1]);
}
layout->SetInputData(vtk_graph1);
layout->SetLayoutStrategy(strategy1);
layout->Update();
vtk_s_graph1 = layout->GetOutput();
p_point.resize(strategy_num);
for(int i = 0; i < strategy_num; i++)
{
p_point[i].resize(node_num);
}
//mylayout加入
my_layout.calcLayout();
my_layout.getPoint(p_point[MYLAYOUT1]);
my_layout2.calcLayout();
my_layout2.getPoint(p_point[MYLAYOUT2]);
start_layout.calcLayout();
start_layout.getPoint(p_point[START]);
//vtklayout加入
for(int i = 0; i < node_num; i++)
{
vtk_s_graph1->GetPoint(i, temp_point);
p_point[CICLE][i].resize(3);
p_point[CICLE][i][0] = temp_point[0] * main_length / 2.5;
p_point[CICLE][i][1] = temp_point[1] * main_width / 2.5;
p_point[CICLE][i][2] = temp_point[2];
}
layout->SetLayoutStrategy(strategy2);
layout->Update();
vtk_s_graph1 = layout->GetOutput();
for(int i = 0; i < node_num; i++)
{
vtk_s_graph1->GetPoint(i, temp_point);
p_point[FORCE][i].resize(3);
p_point[FORCE][i][0] = temp_point[0] * main_length / 1.1;
p_point[FORCE][i][1] = temp_point[1] * main_width / 1.1;
p_point[FORCE][i][2] = temp_point[2];
}
min_x = 0;
min_y = 0;
for(int i = 0; i < node_num; i++)
{
min_x += p_point[FORCE][i][0];
min_y += p_point[FORCE][i][1];
}
min_x /= node_num;
min_y /= node_num;
for(int i = 0; i < node_num; i++)
{
p_point[FORCE][i][0] -= min_x;
p_point[FORCE][i][1] -= min_y;
}
//将坐标正规化
min_x = 0;
min_y = 0;
for(int i = 0; i < node_num; i++)
{
min_x += p_graph.getNode()[i]->getViewLayout()[0];
min_y += p_graph.getNode()[i]->getViewLayout()[1];
}
min_x /= node_num;
min_y /= node_num;
for(int i = 0; i < node_num; i++)
{
vtk_s_graph1->GetPoint(i, temp_point);
p_point[PASSTHROUGH][i].resize(3);
p_point[PASSTHROUGH][i][0] = (p_graph.getNode()[i]->getViewLayout()[0] - min_x) * 8;
p_point[PASSTHROUGH][i][1] = (p_graph.getNode()[i]->getViewLayout()[1] - min_y) * 4;
p_point[PASSTHROUGH][i][2] = p_graph.getNode()[i]->getViewLayout()[2];
}
layout->SetLayoutStrategy(strategy4);
layout->Update();
vtk_s_graph1 = layout->GetOutput();
for(int i = 0; i < node_num; i++)
{
vtk_s_graph1->GetPoint(i, temp_point);
p_point[FAST2D][i].resize(3);
p_point[FAST2D][i][0] = temp_point[0] * main_length / 3.5;
p_point[FAST2D][i][1] = temp_point[1] * main_width / 3.5;
p_point[FAST2D][i][2] = temp_point[2];
}
min_x = 0;
min_y = 0;
for(int i = 0; i < node_num; i++)
{
min_x += p_point[FAST2D][i][0];
min_y += p_point[FAST2D][i][1];
}
min_x /= node_num;
min_y /= node_num;
for(int i = 0; i < node_num; i++)
{
p_point[FAST2D][i][0] -= min_x;
p_point[FAST2D][i][1] -= min_y;
}
layout->SetLayoutStrategy(strategy5);
layout->Update();
vtk_s_graph1 = layout->GetOutput();
for(int i = 0; i < node_num; i++)
{
vtk_s_graph1->GetPoint(i, temp_point);
p_point[RANDOM][i].resize(3);
p_point[RANDOM][i][0] = temp_point[0] * main_length / 1.2;
p_point[RANDOM][i][1] = temp_point[1] * main_width / 1.2;
p_point[RANDOM][i][2] = temp_point[2];
}
min_x = 0;
min_y = 0;
for(int i = 0; i < node_num; i++)
{
min_x += p_point[RANDOM][i][0];
min_y += p_point[RANDOM][i][1];
}
min_x /= node_num;
min_y /= node_num;
for(int i = 0; i < node_num; i++)
{
p_point[RANDOM][i][0] -= min_x;
p_point[RANDOM][i][1] -= min_y;
}
layout->SetLayoutStrategy(strategy6);
layout->Update();
vtk_s_graph1 = layout->GetOutput();
for(int i = 0; i < node_num; i++)
{
vtk_s_graph1->GetPoint(i, temp_point);
p_point[SIMPLE2D][i].resize(3);
p_point[SIMPLE2D][i][0] = temp_point[0] * main_length / 13.7;
p_point[SIMPLE2D][i][1] = temp_point[1] * main_width / 13.7;
p_point[SIMPLE2D][i][2] = temp_point[2];
}
min_x = 0;
min_y = 0;
for(int i = 0; i < node_num; i++)
{
min_x += p_point[SIMPLE2D][i][0];
min_y += p_point[SIMPLE2D][i][1];
}
min_x /= node_num;
min_y /= node_num;
for(int i = 0; i < node_num; i++)
{
p_point[SIMPLE2D][i][0] -= min_x;
p_point[SIMPLE2D][i][1] -= min_y;
}
layout->SetLayoutStrategy(strategy7);
layout->Update();
vtk_s_graph1 = layout->GetOutput();
for(int i = 0; i < node_num; i++)
{
vtk_s_graph1->GetPoint(i, temp_point);
p_point[CLUSTERING2D][i].resize(3);
p_point[CLUSTERING2D][i][0] = temp_point[0] * main_length / 3;
p_point[CLUSTERING2D][i][1] = temp_point[1] * main_width / 2;
p_point[CLUSTERING2D][i][2] = temp_point[2];
}
min_x = 0;
min_y = 0;
for(int i = 0; i < node_num; i++)
{
min_x += p_point[CLUSTERING2D][i][0];
min_y += p_point[CLUSTERING2D][i][1];
}
min_x /= node_num;
min_y /= node_num;
for(int i = 0; i < node_num; i++)
{
p_point[CLUSTERING2D][i][0] -= min_x;
p_point[CLUSTERING2D][i][1] -= min_y;
}
p_point_copy = p_point;
}
//设置各种向量的大小
void MainWindow::setPointSize(int size)
{
for(int i = 0; i < 2; i++) //2,3均为该数据集相关参数,可根据数据集不同来修改,2代表两种数据,3代表总度数,出度以及入度
{
for(int j = 0; j < 3; j++)
{
point_weight[i][j].resize(size);
point_num_edge_state[i][j].resize(size);
}
}
point_state_t.resize(size);
point_type.resize(size);
velocity.resize(size);
point_state.resize(size);
point_highlight.resize(size);
temp_point.resize(size);
}
//放大缩小
void MainWindow::ChangeScale(double scale)
{
my_scale *= scale;
if(my_scale < 0.1)
{
if(full_big == 0)
{
full_big = 1;
my_last_scale = my_scale / scale;
}
else
{
full_big = 2;
}
my_scale = 0.1;
return;
}
else if(my_scale > 18)
{
if(full_big == 0)
{
full_big = 1;
my_last_scale = my_scale / scale;
}
else
{
full_big = 2;
}
my_scale = 18;
return;
}
full_big = 0;
length = int(length * scale);
width = int(width * scale);
height = int(height * scale);
radis *= scale;
}
//Event List
void MainWindow::keyPressEvent(QKeyEvent * ev)
{
if(is_in_start)
return;
switch(ev->key())
{
//放大键
case Qt::Key_Q:ChangeScale(1.1);
if(full_big == 0)
{
setOpoint(Opoint[0] + 0.1 * (Opoint[0] + main_length / 2 - QPoint(cursor().pos()).x()), Opoint[1] + 0.1 * (Opoint[1] + main_width / 2 - QPoint(cursor().pos()).y()));
update();
}
else if(full_big == 2)
return;
else
{
setOpoint(Opoint[0] + (my_scale / my_last_scale - 1) * (Opoint[0] + main_length / 2 - QPoint(cursor().pos()).x()), Opoint[1] + (my_scale / my_last_scale - 1) * (Opoint[1] + main_width / 2 - QPoint(cursor().pos()).y()));
update();
}
break;
//缩小键
case Qt::Key_R:ChangeScale(0.9);
if(full_big == 0)
{
setOpoint(Opoint[0] - 0.1 * (Opoint[0] + main_length / 2 - QPoint(cursor().pos()).x()), Opoint[1] - 0.1 * (Opoint[1] + main_width / 2 - QPoint(cursor().pos()).y()));
update();
}
else if(full_big == 2)
return;
else
{
setOpoint(Opoint[0] - (my_scale / my_last_scale - 1) * (Opoint[0] + main_length / 2 - QPoint(cursor().pos()).x()), Opoint[1] - (my_scale / my_last_scale - 1) * (Opoint[1] + main_width / 2 - QPoint(cursor().pos()).y()));
update();
}
break;
//左移键
case Qt::Key_A:
Opoint[0] += 200;
update();
break;
//右移键
case Qt::Key_D:
Opoint[0] -= 200;
update();
break;
//下移键
case Qt::Key_S:
Opoint[1] -= 200;
update();
break;
//上移键
case Qt::Key_W:
Opoint[1] += 200;
update();
break;
//单点拖移模式开启键
case Qt::Key_B:
if(is_single)
{
is_single = false;
update();
}
else
{
is_single = true;
update();
}
break;
//垂直滚动条控制键,按下可用滚轮控制垂直滚动条
case Qt::Key_V:
is_key_v_pressed = true;
break;
//水平滚动条控制键,按下可用滚轮控制水平滚动条
case Qt::Key_H:
is_key_h_pressed = true;
break;
//局部分析模式开启键,按下可忽略其他点,再按下可取消功能
case Qt::Key_C:
if(!is_in_local)
{
if(id_select_point == -1)
return;
is_in_local = true;
if(!has_weight)
{
if(is_single && id_select_point)
{
point_state_copy = point_state;
}
int node_num = p_graph.getNodeNum();
for(int i = 0; i < node_num; i++)
{
point_state[i] = false;
}
int neighbor_in_number = p_graph.getInNum(id_select_point);
int neighbor_out_number = p_graph.getOutNum(id_select_point);
for(int j = 0; j < neighbor_in_number; j++)
{
point_state[p_graph.getNodeIn()[id_select_point][j]] = true;
}
for(int j = 0; j < neighbor_out_number; j++)
{
point_state[p_graph.getNodeOut()[id_select_point][j]] = true;
}
point_state[id_select_point] = true;
update();
}
else
{
if(is_single && id_select_point)
{
point_state_t_copy = point_state_t;
}
int node_num = t_graph.getNodeNum();
for(int i = 0; i < node_num; i++)
{
point_state_t[i] = false;
}
int neighbor_in_number = t_graph.getInNum(id_select_point);
int neighbor_out_number = t_graph.getOutNum(id_select_point);
for(int j = 0; j < neighbor_in_number; j++)
{
point_state_t[t_graph.getNodeIn()[id_select_point][j]] = true;
}
for(int j = 0; j < neighbor_out_number; j++)
{
point_state_t[t_graph.getNodeOut()[id_select_point][j]] = true;
}
point_state_t[id_select_point] = true;
update();
}
break;
}
else
{
is_in_local = false;
if(!has_weight)
{
if(is_single)
{
point_state = point_state_copy;
}
update();
}
else
{
if(is_single)
{
point_state_t = point_state_t_copy;
}
update();
}
}
}
}
//键盘释放事件
void MainWindow::keyReleaseEvent(QKeyEvent * ev)
{
switch(ev->key())
{
//释放滚动条,滚轮重新控制放大缩小
case Qt::Key_V:
is_key_v_pressed = false;
break;
case Qt::Key_H:
is_key_h_pressed = false;
break;
}
}
//鼠标按下事件
void MainWindow::mousePressEvent(QMouseEvent * ev)
{
if(is_in_start)
return;
int candidate1 = -1;
int candidate2 = -1;
temp_x = ev->pos().x();
temp_y = ev->pos().y();
//paper下的鼠标事件,topic下相同
if(!has_weight)
{
//鼠标左键事件
if(ev->button() == Qt::LeftButton)
{
if(highlight_number > 0)
{
highlight_number = 0;
is_highlight = false;
update();
return;
}
//设置为鼠标左键已按下,若鼠标在点区,则拖点,次之在边区,拖边,次之拖图
is_mouse_pressed = true;
//寻找鼠标是否在点区
int len = p_point[0].size();
int i;
for(i = 0; i < len; i++)
{
if(isInCicle(ev->pos().x(), ev->pos().y(), calcX(my_scale * p_point[strategy][i][0]), calcY(my_scale * p_point[strategy][i][1]), radis))
{
if(candidate1 == -1)
{
candidate1 = i;
}
else if(candidate2 == -1)
{
candidate2 = i;
}
else
{
break;
}
}
}
if(candidate1 == -1)
{
if(id_select_edge != -1)
{
is_dragging = true;
setCursor(Qt::ClosedHandCursor);
}
return;
}
else if(candidate2 == -1)
{
is_dragging = true;
setCursor(Qt::ClosedHandCursor);
id_move_point = candidate1;
}
else
{
if(calcInstance(calcX(my_scale * p_point[strategy][candidate1][0]),ev->pos().x(), calcY(my_scale * p_point[strategy][candidate1][1]), ev->pos().y()) >
calcInstance(calcX(my_scale * p_point[strategy][candidate2][0]),ev->pos().x(), calcY(my_scale * p_point[strategy][candidate2][1]), ev->pos().y()))
{
is_dragging = true;
setCursor(Qt::ClosedHandCursor);
id_move_point = candidate2;
}
else
{
is_dragging = true;
setCursor(Qt::ClosedHandCursor);
id_move_point = candidate1;
}
}
}
//鼠标右键事件
else if(ev->button() == Qt::RightButton && !is_in_local)
{
//存储当前点坐标,为拉索准备
if(!is_highlight && highlight_number == 0)
{
pull_vector.push_back(QPoint(ev->pos().x(), ev->pos().y()));
is_pull = true; //将状态至于拉索模式
}
else //已拉索,可以拖移所有选中的点
{
temp_x_highlight = ev->pos().x();
temp_y_highlight = ev->pos().y();
is_highlight = true;
}
}
}
else
{
if(ev->button() == Qt::LeftButton)
{
if(highlight_number > 0)
{
highlight_number = 0;
is_highlight = false;
update();
return;
}
is_mouse_pressed = true;
temp_x = ev->pos().x();
temp_y = ev->pos().y();
int len = p_point[0].size();
int i;
for(i = 0; i < len; i++)
{
if(isInCicle(ev->pos().x(), ev->pos().y(), calcX(my_scale * t_point[strategy][i][0]), calcY(my_scale * t_point[strategy][i][1]), radis))
{
if(candidate1 == -1)
{
candidate1 = i;
}
else if(candidate2 == -1)
{
candidate2 = i;
}
else
{
break;
}
}
}
if(candidate1 == -1)
{
if(id_select_edge != -1)
{
is_dragging = true;
setCursor(Qt::ClosedHandCursor);
}
return;
}
else if(candidate2 == -1)
{
is_dragging = true;
setCursor(Qt::ClosedHandCursor);
id_move_point = candidate1;
}
else
{
if(calcInstance(calcX(my_scale * t_point[strategy][candidate1][0]),ev->pos().x(), calcY(my_scale * t_point[strategy][candidate1][1]), ev->pos().y()) >
calcInstance(calcX(my_scale * t_point[strategy][candidate2][0]),ev->pos().x(), calcY(my_scale * t_point[strategy][candidate2][1]), ev->pos().y()))
{
is_dragging = true;
id_move_point = candidate2;
setCursor(Qt::ClosedHandCursor);
}
else
{
is_dragging = true;
setCursor(Qt::ClosedHandCursor);
id_move_point = candidate1;
}
}
}
else if(ev->button() == Qt::RightButton && !is_in_local)
{
if(!is_highlight && highlight_number == 0)
{
is_pull = true;
temp_x_highlight = ev->pos().x();
temp_y_highlight = ev->pos().y();
}
else if(!is_highlight)
{
temp_x_highlight = ev->pos().x();
temp_y_highlight = ev->pos().y();
is_highlight = true;
}
}
}
}
//鼠标双击事件
void MainWindow::mouseDoubleClickEvent(QMouseEvent * ev)
{
if(is_in_start)
return;
if(!has_weight)
{
bool is_point = false;
//左键双击,显示属性
if(ev->button() == Qt::LeftButton)
{
int len = p_point[0].size();
int i;
for(i = 0; i < len; i++)
{
if(isInCicle(ev->pos().x(), ev->pos().y(), calcX(my_scale * p_point[strategy][i][0]), calcY(my_scale * p_point[strategy][i][1]), radis))
{
is_point = true;
break;
}
}
if(is_point)
{
listPaperInformation(i);
}
else
return;
}
//右键双击,将已拉索的点外的点过滤,或者恢复其他的点
else if(ev->button() == Qt::RightButton)
{
//过滤
if(highlight_number > 0)
{
highlight_number = 0;
point_state_copy_fil.push_back(point_state);
point_state = point_highlight;
}
//恢复
else
{
if(point_state_copy_fil.size() >= 1)
{
point_state = point_state_copy_fil[point_state_copy_fil.size() - 1];
point_state_copy_fil.pop_back();
}
}
}
}
else
{
if(ev->button() == Qt::LeftButton)
{
bool is_point = false;
int len = t_point[0].size();
int i;
for(i = 0; i < len; i++)
{
if(isInCicle(ev->pos().x(), ev->pos().y(), calcX(my_scale * t_point[strategy][i][0]), calcY(my_scale * t_point[strategy][i][1]), radis))
{
is_point = true;
break;
}
}
if(is_point)
{
listPaperInformation(i);
}
else
return;
}
else if(ev->button() == Qt::RightButton)
{
if(highlight_number > 0)
{
highlight_number = 0;
point_state_t_copy_fil.push_back(point_state_t);
point_state_t = point_highlight;
}
else
{
if(point_state_t_copy_fil.size() >= 1)
{
point_state_t = point_state_t_copy_fil[point_state_t_copy_fil.size() - 1];
point_state_t_copy_fil.pop_back();
}
}
}
}
}
//判断一个位置是否在某条边上,前四个参数代表边,后两个为位置
bool MainWindow::inEdgeArea(double src_x, double src_y, double des_x, double des_y, double pos_x, double pos_y)
{
if(!(fabs((des_y - pos_y) * (pos_x - src_x) - (des_x - pos_x) * (pos_y - src_y)) <= 1000 * my_scale))
{
return false;
}
else //防止点在边的延长线上
{
if((src_x - pos_x) * (des_x - pos_x) < 0)
{
return true;
}
else
{
return false;
}
}
}
//虚拟坐标到画布坐标的变换
int MainWindow::calcX(int x)
{
return (x + Opoint[0] + main_length / 2);
}
int MainWindow::calcY(int y)
{
return (y + Opoint[1] + main_width / 2);
}
//某位置是否在点区
bool MainWindow::isInCicle(int tx, int ty, int x, int y, int r)
{
if(((tx - x) * (tx - x) + (ty - y) * (ty - y)) > r * r)
return false;
else
return true;
}
//计算两个点的欧几里得距离
double MainWindow::calcInstance(double x1, double x2, double y1, double y2)
{
return ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
}
//展示点的属性,i为选中节点的id
void MainWindow::listPaperInformation(int i)
{
if(!has_weight)
{
InformationDialog dlg(*(p_graph.getNode()[i]));
dlg.exec();
}
else
{
*(t_graph.getNode()[i]);
topicdialog dlg(t_graph, *(t_graph.getNode()[i]));
dlg.exec();
}
}
//绘制事件,分为各种模式
void MainWindow::paintEvent(QPaintEvent * ev)
{
QPainter painter(this);
PointColor my_color;
QPen pen;
//画边用的点
QPointF point1;
QPointF point2;
QFont my_font;
vector<int> temp_pair;
painter.save();
int node_num = p_point[0].size();
//正在拉索模式
if(is_pull && !is_in_start)
{
pen.setColor(QColor(255,0,0,255));
pen.setWidth(2);
painter.setPen(pen);
painter.drawPolygon(poly);
painter.translate(Opoint[0] + main_length / 2, Opoint[1] + main_width / 2);
pen.setColor(QColor(0,0,0,232));
pen.setWidth(1);
painter.setPen(pen);
if(!has_weight)
{
for(int i = 0; i < node_num; i++)
{
if(!point_state[i])
continue;
if(point_highlight[i])
{
my_color.setColor(int(point_weight[0][0][i]), point_type[i], 200);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * p_point[strategy][i][0] - radis * 2, my_scale * p_point[strategy][i][1] - radis * 2,
radis * 4, radis * 4);
}
else
{
my_color.setColor(int(point_weight[0][0][i]), point_type[i], 200);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * p_point[strategy][i][0] - radis, my_scale * p_point[strategy][i][1] - radis,
radis * 2, radis * 2);
}
}
int edge_num = p_graph.getEdgeNum();
for(int j = 0; j < edge_num; j++)
{
if(point_state[p_graph.getEdgeNode()[j][0]] && point_state[p_graph.getEdgeNode()[j][1]])
{
pen.setColor(QColor(230,230,230,edge_color));
painter.setPen(pen);
point1.setX(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][0]][0]);
point1.setY(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][0]][1]);
point2.setX(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][1]][0]);
point2.setY(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][1]][1]);
painter.drawLine(point1, point2);
}
}
}
else
{
for(int i = 0; i < node_num; i++)
{
if(!point_state_t[i])
continue;
if(point_highlight[i])
{
my_color.setColor(int(point_weight[1][0][i]), 0, 200);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * t_point[strategy][i][0] - radis * 2, my_scale * t_point[strategy][i][1] - radis * 2,
radis * 4, radis * 4);
}
else
{
my_color.setColor(int(point_weight[1][0][i]), 0, 200);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * t_point[strategy][i][0] - radis, my_scale * t_point[strategy][i][1] - radis,
radis * 2, radis * 2);
}
}
int edge_num = t_graph.getEdgeNum();
for(int j = 0; j < edge_num; j++)
{
if(!edge_state_t[j])
continue;
if(point_state_t[t_graph.getEdgeNode()[j][0]] && point_state_t[t_graph.getEdgeNode()[j][1]])
{
pen.setColor(QColor(230,230,230, edge_color));
painter.setPen(pen);
point1.setX(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][0]][0]);
point1.setY(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][0]][1]);
point2.setX(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][1]][0]);
point2.setY(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][1]][1]);
painter.drawLine(point1, point2);
}
}
}
painter.restore();
return;
}
painter.translate(Opoint[0] + main_length / 2, Opoint[1] + main_width / 2);
//局部分析模式,只显示这个点和与其相连的边
if(is_in_local && is_single && !is_in_start && !in_cartoon)
{
if(!has_weight)
{
for(int i = 0; i < node_num; i++)
{
if(!point_state[i])
continue;
my_color.setColor(int(point_weight[0][0][i]), point_type[i]);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * p_point[strategy][i][0] - radis, my_scale * p_point[strategy][i][1] - radis,
radis * 2, radis * 2);
}
if(id_select_point != -1 && point_state[id_select_point])
{
pen.setColor(QColor(230,230,230,232));
painter.setPen(pen);
my_font.setBold(true);
my_font.setPointSize(9 * my_scale);
painter.setFont(my_font);
painter.drawText(my_scale * p_point[strategy][id_select_point][0] , my_scale * p_point[strategy][id_select_point][1] - radis * 4,
QString::number(p_graph.getNode()[id_select_point]->getIdOfNode(), 10));
pen.setColor(QColor(0,0,0,232));
painter.setPen(pen);
my_color.setColor(int(point_weight[0][0][id_select_point]), point_type[id_select_point]);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * p_point[strategy][id_select_point][0] - radis * 2, my_scale * p_point[strategy][id_select_point][1] - radis * 2,
radis * 4, radis * 4);
}
int edge_num = p_graph.getEdgeNum();
for(int j = 0; j < edge_num; j++)
{
if(point_state[p_graph.getEdgeNode()[j][0]] && point_state[p_graph.getEdgeNode()[j][1]])
{
pen.setColor(QColor(230,230,230,edge_color));
painter.setPen(pen);
point1.setX(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][0]][0]);
point1.setY(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][0]][1]);
point2.setX(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][1]][0]);
point2.setY(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][1]][1]);
painter.drawLine(point1, point2);
}
}
}
else
{
for(int i = 0; i < node_num; i++)
{
if(!point_state_t[i])
continue;
my_color.setColor(int(point_weight[1][0][i]), 0);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * t_point[strategy][i][0] - radis, my_scale * t_point[strategy][i][1] - radis,
radis * 2, radis * 2);
}
if(id_select_point != -1 && point_state_t[id_select_point])
{
pen.setColor(QColor(230,230,230,232));
painter.setPen(pen);
my_font.setBold(true);
my_font.setPointSize(9 * my_scale);
painter.setFont(my_font);
painter.drawText(my_scale * t_point[strategy][id_select_point][0] , my_scale * t_point[strategy][id_select_point][1] - radis * 4,
QString::number(t_graph.getNode()[id_select_point]->getIdOfNode(), 10));
pen.setColor(QColor(0,0,0,0));
painter.setPen(pen);
my_color.setColor(int(point_weight[1][0][id_select_point]), 0);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * t_point[strategy][id_select_point][0] - radis * 2, my_scale * t_point[strategy][id_select_point][1] - radis * 2,
radis * 4, radis * 4);
}
int edge_num = t_graph.getEdgeNum();
for(int j = 0; j < edge_num; j++)
{
if(!edge_state_t[j])
continue;
if(point_state_t[t_graph.getEdgeNode()[j][0]] && point_state_t[t_graph.getEdgeNode()[j][1]])
{
pen.setColor(QColor(230,230,230,edge_color));
painter.setPen(pen);
point1.setX(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][0]][0]);
point1.setY(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][0]][1]);
point2.setX(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][1]][0]);
point2.setY(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][1]][1]);
painter.drawLine(point1, point2);
}
}
}
if(id_select_edge != -1)
{
if(!has_weight && point_state[p_graph.getEdgeNode()[id_select_edge][1]]
&& point_state[p_graph.getEdgeNode()[id_select_edge][0]])
{
temp_pair.push_back(p_graph.getEdgeNode()[id_select_edge][1]);
temp_pair.push_back(p_graph.getEdgeNode()[id_select_edge][0]);
pen.setColor(QColor(255,0,0,232));
painter.setPen(pen);
my_font.setBold(true);
my_font.setPointSize(9 * my_scale);
painter.setFont(my_font);
painter.drawText(my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][0]][0] , my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][0]][1] + radis * 4, "source");
painter.drawText(my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][1]][0] , my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][1]][1] + radis * 4, "target");
if(p_graph.getNodeToEdge().find(temp_pair) != p_graph.getNodeToEdge().end())
{
painter.drawText(my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][0]][0] , my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][0]][1] - 9 * my_scale, "target");
painter.drawText(my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][1]][0] , my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][1]][1] - 9 * my_scale, "source");
}
pen.setColor(QColor(0,0,0,232));
painter.setPen(pen);
painter.setBrush(QColor(255,0,0,232));
painter.drawEllipse(my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][1]][0] - radis * 2, my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][1]][1] - radis * 2,
radis * 4, radis * 4);
painter.drawEllipse(my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][0]][0] - radis * 2, my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][0]][1] - radis * 2,
radis * 4, radis * 4);
pen.setColor(QColor(255,0,0,232));
pen.setWidth(3);
painter.setPen(pen);
point1.setX(my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][0]][0]);
point1.setY(my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][0]][1]);
point2.setX(my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][1]][0]);
point2.setY(my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][1]][1]);
painter.drawLine(point1, point2);
pen.setWidth(1);
painter.setPen(pen);
}
else if(has_weight && edge_state_t[id_select_edge]
&& point_state_t[t_graph.getEdgeNode()[id_select_edge][1]]
&& point_state_t[t_graph.getEdgeNode()[id_select_edge][0]])
{
pen.setColor(QColor(255,0,0,232));
painter.setPen(pen);
my_font.setBold(true);
my_font.setPointSize(9 * my_scale);
painter.setFont(my_font);
painter.drawText((my_scale * t_point[strategy][t_graph.getEdgeNode()[id_select_edge][0]][0] + my_scale * t_point[strategy][t_graph.getEdgeNode()[id_select_edge][1]][0]) / 2,
(my_scale * t_point[strategy][t_graph.getEdgeNode()[id_select_edge][0]][1] - radis * 4 + my_scale * t_point[strategy][t_graph.getEdgeNode()[id_select_edge][1]][1] - radis * 4) / 2,
QString::number(t_graph.getEdge()[id_select_edge]->getWeight()));
pen.setColor(QColor(0,0,0,0));
painter.setPen(pen);
painter.setBrush(QColor(255,0,0,232));
painter.drawEllipse(my_scale * t_point[strategy][t_graph.getEdgeNode()[id_select_edge][0]][0] - radis * 2, my_scale * t_point[strategy][t_graph.getEdgeNode()[id_select_edge][0]][1] - radis * 2,
radis * 4, radis * 4);
painter.setBrush(QColor(255,0,0,232));
painter.drawEllipse(my_scale * t_point[strategy][t_graph.getEdgeNode()[id_select_edge][1]][0] - radis * 2, my_scale * t_point[strategy][t_graph.getEdgeNode()[id_select_edge][1]][1] - radis * 2,
radis * 4, radis * 4);
pen.setColor(QColor(255,0,0,232));
pen.setWidth(3);
painter.setPen(pen);
point1.setX(my_scale * t_point[strategy][t_graph.getEdgeNode()[id_select_edge][0]][0]);
point1.setY(my_scale * t_point[strategy][t_graph.getEdgeNode()[id_select_edge][0]][1]);
point2.setX(my_scale * t_point[strategy][t_graph.getEdgeNode()[id_select_edge][1]][0]);
point2.setY(my_scale * t_point[strategy][t_graph.getEdgeNode()[id_select_edge][1]][1]);
painter.drawLine(point1, point2);
pen.setWidth(1);
painter.setPen(pen);
}
}
painter.restore();
return;
}
//数据切换模式
if(data_change > 0 && !is_in_start)
{
if(!has_weight)
{
for(int i = 0; i < node_num; i++)
{
if(!point_state[i])
continue;
my_color.setColor(int(point_weight[0][0][i]), point_type[i], alpha_degree * 1.3);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * p_point[strategy][i][0] - radis, my_scale * p_point[strategy][i][1] - radis,
radis * 2, radis * 2);
}
int edge_num = p_graph.getEdgeNum();
for(int j = 0; j < edge_num; j++)
{
if(point_state[p_graph.getEdgeNode()[j][0]] && point_state[p_graph.getEdgeNode()[j][1]])
{
pen.setColor(QColor(230,230,230,alpha_degree));
painter.setPen(pen);
point1.setX(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][0]][0]);
point1.setY(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][0]][1]);
point2.setX(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][1]][0]);
point2.setY(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][1]][1]);
painter.drawLine(point1, point2);
}
}
}
else
{
for(int i = 0; i < node_num; i++)
{
if(!point_state_t[i])
continue;
my_color.setColor(int(point_weight[1][0][i]), 0, alpha_degree * 1.3);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * t_point[strategy][i][0] - radis, my_scale * t_point[strategy][i][1] - radis,
radis * 2, radis * 2);
}
int edge_num = t_graph.getEdgeNum();
for(int j = 0; j < edge_num; j++)
{
if(!edge_state_t[j])
continue;
if(point_state_t[t_graph.getEdgeNode()[j][0]] && point_state_t[t_graph.getEdgeNode()[j][1]])
{
pen.setColor(QColor(230,230,230,alpha_degree));
painter.setPen(pen);
point1.setX(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][0]][0]);
point1.setY(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][0]][1]);
point2.setX(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][1]][0]);
point2.setY(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][1]][1]);
painter.drawLine(point1, point2);
}
}
}
painter.restore();
return;
}
//高亮态模式
if(highlight_number > 0 && !is_in_start)
{
if(!has_weight)
{
for(int i = 0; i < node_num; i++)
{
if(!point_state[i])
continue;
if(point_highlight[i])
{
my_color.setColor(int(point_weight[0][0][i]), point_type[i], 200);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * p_point[strategy][i][0] - radis * 2, my_scale * p_point[strategy][i][1] - radis * 2,
radis * 4, radis * 4);
}
else
{
my_color.setColor(int(point_weight[0][0][i]), point_type[i], 200);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * p_point[strategy][i][0] - radis, my_scale * p_point[strategy][i][1] - radis,
radis * 2, radis * 2);
}
}
int edge_num = p_graph.getEdgeNum();
for(int j = 0; j < edge_num; j++)
{
if(point_state[p_graph.getEdgeNode()[j][0]] && point_state[p_graph.getEdgeNode()[j][1]])
{
pen.setColor(QColor(230,230,230,edge_color));
painter.setPen(pen);
point1.setX(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][0]][0]);
point1.setY(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][0]][1]);
point2.setX(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][1]][0]);
point2.setY(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][1]][1]);
painter.drawLine(point1, point2);
}
}
}
else
{
for(int i = 0; i < node_num; i++)
{
if(!point_state_t[i])
continue;
if(point_highlight[i])
{
my_color.setColor(int(point_weight[1][0][i]), 0, 200);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * t_point[strategy][i][0] - radis * 2, my_scale * t_point[strategy][i][1] - radis * 2,
radis * 4, radis * 4);
}
else
{
my_color.setColor(int(point_weight[1][0][i]), 0, 200);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * t_point[strategy][i][0] - radis, my_scale * t_point[strategy][i][1] - radis,
radis * 2, radis * 2);
}
}
int edge_num = t_graph.getEdgeNum();
for(int j = 0; j < edge_num; j++)
{
if(!edge_state_t[j])
continue;
if(point_state_t[t_graph.getEdgeNode()[j][0]] && point_state_t[t_graph.getEdgeNode()[j][1]])
{
pen.setColor(QColor(230,230,230,edge_color));
painter.setPen(pen);
point1.setX(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][0]][0]);
point1.setY(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][0]][1]);
point2.setX(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][1]][0]);
point2.setY(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][1]][1]);
painter.drawLine(point1, point2);
}
}
}
painter.restore();
return;
}
//选中模式,被选中的点会放大
if(id_select_point != -1 && !is_single && !is_in_start)
{
if(!has_weight)
{
for(int i = 0; i < node_num; i++)
{
if(!point_state[i])
continue;
my_color.setColor(int(point_weight[0][0][i]), point_type[i]);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * p_point[strategy][i][0] - radis, my_scale * p_point[strategy][i][1] - radis,
radis * 2, radis * 2);
}
if(point_state[id_select_point])
{
pen.setColor(QColor(230,230,230,232));
painter.setPen(pen);
my_font.setBold(true);
my_font.setPointSize(9 * my_scale);
painter.setFont(my_font);
painter.drawText(my_scale * p_point[strategy][id_select_point][0] , my_scale * p_point[strategy][id_select_point][1] - radis * 4,
QString::number(p_graph.getNode()[id_select_point]->getIdOfNode(), 10));
pen.setColor(QColor(0,0,0,0));
painter.setPen(pen);
my_color.setColor(38, point_type[id_select_point]);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * p_point[strategy][id_select_point][0] - radis * 2, my_scale * p_point[strategy][id_select_point][1] - radis * 2,
radis * 4, radis * 4);
}
else
{
setCursor(Qt::ArrowCursor);
}
int edge_num = p_graph.getEdgeNum();
for(int j = 0; j < edge_num; j++)
{
if(point_state[p_graph.getEdgeNode()[j][0]] && point_state[p_graph.getEdgeNode()[j][1]])
{
pen.setColor(QColor(230,230,230,edge_color));
painter.setPen(pen);
point1.setX(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][0]][0]);
point1.setY(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][0]][1]);
point2.setX(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][1]][0]);
point2.setY(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][1]][1]);
painter.drawLine(point1, point2);
}
}
}
else
{
for(int i = 0; i < node_num; i++)
{
if(!point_state_t[i])
continue;
my_color.setColor(int(point_weight[1][0][i]), 0);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * t_point[strategy][i][0] - radis, my_scale * t_point[strategy][i][1] - radis,
radis * 2, radis * 2);
}
if(point_state_t[id_select_point])
{
pen.setColor(QColor(230,230,230,232));
painter.setPen(pen);
my_font.setBold(true);
my_font.setPointSize(9 * my_scale);
painter.setFont(my_font);
painter.drawText(my_scale * t_point[strategy][id_select_point][0] , my_scale * t_point[strategy][id_select_point][1] - radis * 4,
QString::number(t_graph.getNode()[id_select_point]->getIdOfNode(), 10));
pen.setColor(QColor(0,0,0,0));
painter.setPen(pen);
my_color.setColor(int(point_weight[1][0][id_select_point]), 0);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * t_point[strategy][id_select_point][0] - radis * 2, my_scale * t_point[strategy][id_select_point][1] - radis * 2,
radis * 4, radis * 4);
}
else
{
setCursor(Qt::ArrowCursor);
}
int edge_num = t_graph.getEdgeNum();
for(int j = 0; j < edge_num; j++)
{
if(!edge_state_t[j])
continue;
if(point_state_t[t_graph.getEdgeNode()[j][0]] && point_state_t[t_graph.getEdgeNode()[j][1]])
{
pen.setColor(QColor(230,230,230,edge_color));
painter.setPen(pen);
point1.setX(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][0]][0]);
point1.setY(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][0]][1]);
point2.setX(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][1]][0]);
point2.setY(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][1]][1]);
painter.drawLine(point1, point2);
}
}
}
painter.restore();
return;
}
//单点拖动模式,拖动时只显示这个点和与其相连的边
if(id_select_point != -1 && is_single && !is_in_start)
{
if(!has_weight)
{
if(!point_state[id_select_point])
{
setCursor(Qt::ArrowCursor);
painter.restore();
return;
}
int neighbor_in_number = p_graph.getInNum(id_select_point);
int neighbor_out_number = p_graph.getOutNum(id_select_point);
for(int j = 0; j < neighbor_in_number; j++)
{
my_color.setColor(38 , point_type[p_graph.getNodeIn()[id_select_point][j]]);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * p_point[strategy][p_graph.getNodeIn()[id_select_point][j]][0] - radis,
my_scale * p_point[strategy][p_graph.getNodeIn()[id_select_point][j]][1] - radis,
radis * 2, radis * 2);
}
for(int j = 0; j < neighbor_out_number; j++)
{
my_color.setColor(38 , point_type[p_graph.getNodeOut()[id_select_point][j]]);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * p_point[strategy][p_graph.getNodeOut()[id_select_point][j]][0] - radis,
my_scale * p_point[strategy][p_graph.getNodeOut()[id_select_point][j]][1] - radis,
radis * 2, radis * 2);
}
my_color.setColor(38, point_type[id_select_point]);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * p_point[strategy][id_select_point][0] - radis * 2, my_scale * p_point[strategy][id_select_point][1] - radis * 2,
radis * 4, radis * 4);
int edge_num = p_graph.getEdgeNum();
for(int j = 0; j < edge_num; j++)
{
if(p_graph.getEdgeNode()[j][0] == id_select_point || p_graph.getEdgeNode()[j][1] == id_select_point)
{
if(point_state[p_graph.getEdgeNode()[j][0]] && point_state[p_graph.getEdgeNode()[j][1]])
{
pen.setColor(QColor(230,230,230,edge_color));
painter.setPen(pen);
point1.setX(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][0]][0]);
point1.setY(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][0]][1]);
point2.setX(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][1]][0]);
point2.setY(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][1]][1]);
painter.drawLine(point1, point2);
}
}
}
}
else
{
if(!point_state[id_select_point])
{
setCursor(Qt::ArrowCursor);
painter.restore();
return;
}
int neighbor_in_number = t_graph.getInNum(id_select_point);
int neighbor_out_number = t_graph.getOutNum(id_select_point);
for(int j = 0; j < neighbor_in_number; j++)
{
my_color.setColor(int(point_weight[1][0][t_graph.getNodeIn()[id_select_point][j]]), 0);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * t_point[strategy][t_graph.getNodeIn()[id_select_point][j]][0] - radis,
my_scale * t_point[strategy][t_graph.getNodeIn()[id_select_point][j]][1] - radis,
radis * 2, radis * 2);
}
for(int j = 0; j < neighbor_out_number; j++)
{
my_color.setColor(int(point_weight[1][0][t_graph.getNodeIn()[id_select_point][j]]), 0);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * t_point[strategy][t_graph.getNodeOut()[id_select_point][j]][0] - radis,
my_scale * t_point[strategy][t_graph.getNodeOut()[id_select_point][j]][1] - radis,
radis * 2, radis * 2);
}
my_color.setColor(38, point_type[id_select_point]);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * t_point[strategy][id_select_point][0] - radis * 2, my_scale * t_point[strategy][id_select_point][1] - radis * 2,
radis * 4, radis * 4);
int edge_num = t_graph.getEdgeNum();
for(int j = 0; j < edge_num; j++)
{
if(!edge_state_t[j])
continue;
if(t_graph.getEdgeNode()[j][0] == id_select_point || t_graph.getEdgeNode()[j][1] == id_select_point)
{
if(point_state_t[t_graph.getEdgeNode()[j][0]] && point_state_t[t_graph.getEdgeNode()[j][1]])
{
pen.setColor(QColor(230,230,230,edge_color));
painter.setPen(pen);
point1.setX(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][0]][0]);
point1.setY(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][0]][1]);
point2.setX(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][1]][0]);
point2.setY(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][1]][1]);
painter.drawLine(point1, point2);
}
}
}
}
painter.restore();
return;
}
//切换layout动画模式
if(in_cartoon && !is_in_start)
{
if(!has_weight)
{
for(int i = 0; i < node_num; i++)
{
if(!point_state[i])
continue;
my_color.setColor(int(point_weight[0][0][i]), point_type[i]);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * temp_point[i][0] - radis , my_scale * temp_point[i][1] - radis,
radis * 2, radis * 2);
}
int edge_num = p_graph.getEdgeNum();
for(int j = 0; j < edge_num; j++)
{
if(point_state[p_graph.getEdgeNode()[j][0]] && point_state[p_graph.getEdgeNode()[j][1]])
{
pen.setColor(QColor(230,230,230,edge_color));
painter.setPen(pen);
point1.setX(my_scale * temp_point[p_graph.getEdgeNode()[j][0]][0]);
point1.setY(my_scale * temp_point[p_graph.getEdgeNode()[j][0]][1]);
point2.setX(my_scale * temp_point[p_graph.getEdgeNode()[j][1]][0]);
point2.setY(my_scale * temp_point[p_graph.getEdgeNode()[j][1]][1]);
painter.drawLine(point1, point2);
}
}
}
else
{
for(int i = 0; i < node_num; i++)
{
if(!point_state_t[i])
continue;
my_color.setColor(int(point_weight[1][0][i]), 0);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * temp_point[i][0] - radis , my_scale * temp_point[i][1] - radis,
radis * 2, radis * 2);
}
int edge_num = t_graph.getEdgeNum();
for(int j = 0; j < edge_num; j++)
{
if(!edge_state_t[j])
continue;
if(point_state_t[t_graph.getEdgeNode()[j][0]] && point_state_t[t_graph.getEdgeNode()[j][1]])
{
pen.setColor(QColor(230,230,230,edge_color));
painter.setPen(pen);
point1.setX(my_scale * temp_point[t_graph.getEdgeNode()[j][0]][0]);
point1.setY(my_scale * temp_point[t_graph.getEdgeNode()[j][0]][1]);
point2.setX(my_scale * temp_point[t_graph.getEdgeNode()[j][1]][0]);
point2.setY(my_scale * temp_point[t_graph.getEdgeNode()[j][1]][1]);
painter.drawLine(point1, point2);
}
}
}
}
//普通绘制模式
else
{
//初始界面
if(is_in_start)
{
if(!has_weight)
{
for(int i = 0; i < node_num; i++)
{
if(!point_state[i])
continue;
my_color.setColor(int(point_weight[0][0][i]), point_type[i]);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * p_point[strategy][i][0] - radis, my_scale * p_point[strategy][i][1] - radis,
radis * 2, radis * 2);
}
int edge_num = p_graph.getEdgeNum();
for(int j = 0; j < edge_num; j++)
{
pen.setColor(QColor(230,230,230,alpha_start));
painter.setPen(pen);
point1.setX(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][0]][0]);
point1.setY(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][0]][1]);
point2.setX(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][1]][0]);
point2.setY(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][1]][1]);
painter.drawLine(point1, point2);
}
}
else
{
for(int i = 0; i < node_num; i++)
{
if(!point_state_t[i])
continue;
my_color.setColor(int(point_weight[1][0][i]), 0);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * t_point[strategy][i][0] - radis, my_scale * t_point[strategy][i][1] - radis,
radis * 2, radis * 2);
}
int edge_num = t_graph.getEdgeNum();
for(int j = 0; j < edge_num; j++)
{
pen.setColor(QColor(230,230,230,alpha_start));
painter.setPen(pen);
point1.setX(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][0]][0]);
point1.setY(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][0]][1]);
point2.setX(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][1]][0]);
point2.setY(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][1]][1]);
painter.drawLine(point1, point2);
}
}
painter.restore();
return;
}
if(!has_weight)
{
for(int i = 0; i < node_num; i++)
{
if(!point_state[i])
continue;
my_color.setColor(int(point_weight[0][0][i]), point_type[i]);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * p_point[strategy][i][0] - radis, my_scale * p_point[strategy][i][1] - radis,
radis * 2, radis * 2);
}
int edge_num = p_graph.getEdgeNum();
for(int j = 0; j < edge_num; j++)
{
if(point_state[p_graph.getEdgeNode()[j][0]] && point_state[p_graph.getEdgeNode()[j][1]])
{
pen.setColor(QColor(230,230,230,edge_color));
painter.setPen(pen);
point1.setX(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][0]][0]);
point1.setY(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][0]][1]);
point2.setX(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][1]][0]);
point2.setY(my_scale * p_point[strategy][p_graph.getEdgeNode()[j][1]][1]);
painter.drawLine(point1, point2);
}
}
}
else
{
for(int i = 0; i < node_num; i++)
{
if(!point_state_t[i])
continue;
my_color.setColor(int(point_weight[1][0][i]), 0);
painter.setBrush(my_color.getColor());
painter.drawEllipse(my_scale * t_point[strategy][i][0] - radis, my_scale * t_point[strategy][i][1] - radis,
radis * 2, radis * 2);
}
int edge_num = t_graph.getEdgeNum();
for(int j = 0; j < edge_num; j++)
{
if(!edge_state_t[j])
continue;
if(point_state_t[t_graph.getEdgeNode()[j][0]] && point_state_t[t_graph.getEdgeNode()[j][1]])
{
pen.setColor(QColor(230,230,230,edge_color));
painter.setPen(pen);
point1.setX(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][0]][0]);
point1.setY(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][0]][1]);
point2.setX(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][1]][0]);
point2.setY(my_scale * t_point[strategy][t_graph.getEdgeNode()[j][1]][1]);
painter.drawLine(point1, point2);
}
}
}
}
if(id_select_edge != -1)
{
if(!has_weight && point_state[p_graph.getEdgeNode()[id_select_edge][1]]
&& point_state[p_graph.getEdgeNode()[id_select_edge][0]])
{
temp_pair.push_back(p_graph.getEdgeNode()[id_select_edge][1]);
temp_pair.push_back(p_graph.getEdgeNode()[id_select_edge][0]);
pen.setColor(QColor(255,0,0,232));
painter.setPen(pen);
my_font.setBold(true);
my_font.setPointSize(9 * my_scale);
painter.setFont(my_font);
painter.drawText(my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][0]][0] , my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][0]][1] + radis * 4, "source");
painter.drawText(my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][1]][0] , my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][1]][1] + radis * 4, "target");
if(p_graph.getNodeToEdge().find(temp_pair) != p_graph.getNodeToEdge().end())
{
painter.drawText(my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][0]][0] , my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][0]][1] - 9 * my_scale, "target");
painter.drawText(my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][1]][0] , my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][1]][1] - 9 * my_scale, "source");
}
pen.setColor(QColor(0,0,0,0));
painter.setPen(pen);
painter.setBrush(QColor(255,0,0,232));
painter.drawEllipse(my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][0]][0] - radis * 2, my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][0]][1] - radis * 2,
radis * 4, radis * 4);
painter.drawEllipse(my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][1]][0] - radis * 2, my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][1]][1] - radis * 2,
radis * 4, radis * 4);
pen.setColor(QColor(255,0,0,232));
pen.setWidth(3);
painter.setPen(pen);
point1.setX(my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][0]][0]);
point1.setY(my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][0]][1]);
point2.setX(my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][1]][0]);
point2.setY(my_scale * p_point[strategy][p_graph.getEdgeNode()[id_select_edge][1]][1]);
painter.drawLine(point1, point2);
pen.setWidth(1);
painter.setPen(pen);
}
else if(has_weight && edge_state_t[id_select_edge]
&& point_state_t[t_graph.getEdgeNode()[id_select_edge][1]]
&& point_state_t[t_graph.getEdgeNode()[id_select_edge][0]])
{
pen.setColor(QColor(255,0,0,232));
painter.setPen(pen);
my_font.setBold(true);
my_font.setPointSize(9 * my_scale);
painter.setFont(my_font);
painter.drawText((my_scale * t_point[strategy][t_graph.getEdgeNode()[id_select_edge][0]][0] + my_scale * t_point[strategy][t_graph.getEdgeNode()[id_select_edge][1]][0]) / 2,
(my_scale * t_point[strategy][t_graph.getEdgeNode()[id_select_edge][0]][1] - radis * 4 + my_scale * t_point[strategy][t_graph.getEdgeNode()[id_select_edge][1]][1] - radis * 4) / 2,
QString::number(t_graph.getEdge()[id_select_edge]->getWeight()));
pen.setColor(QColor(0,0,0,0));
painter.setPen(pen);
painter.setBrush(QColor(255,0,0,232));
painter.drawEllipse(my_scale * t_point[strategy][t_graph.getEdgeNode()[id_select_edge][0]][0] - radis * 2, my_scale * t_point[strategy][t_graph.getEdgeNode()[id_select_edge][0]][1] - radis * 2,
radis * 4, radis * 4);
painter.setBrush(QColor(255,0,0,232));
painter.drawEllipse(my_scale * t_point[strategy][t_graph.getEdgeNode()[id_select_edge][1]][0] - radis * 2, my_scale * t_point[strategy][t_graph.getEdgeNode()[id_select_edge][1]][1] - radis * 2,
radis * 4, radis * 4);
pen.setColor(QColor(255,0,0,232));
pen.setWidth(3);
painter.setPen(pen);
point1.setX(my_scale * t_point[strategy][t_graph.getEdgeNode()[id_select_edge][0]][0]);
point1.setY(my_scale * t_point[strategy][t_graph.getEdgeNode()[id_select_edge][0]][1]);
point2.setX(my_scale * t_point[strategy][t_graph.getEdgeNode()[id_select_edge][1]][0]);
point2.setY(my_scale * t_point[strategy][t_graph.getEdgeNode()[id_select_edge][1]][1]);
painter.drawLine(point1, point2);
pen.setWidth(1);
painter.setPen(pen);
}
}
painter.restore();
}
//鼠标移动事件
void MainWindow::mouseMoveEvent(QMouseEvent * ev)
{
if(is_in_start)
return;
//拖点拖边,更新位置
if (is_dragging && id_select_point != -1)
{
if(!has_weight)
{
if(!point_state[id_move_point])
return;
p_point[strategy][id_move_point][0] += (ev->pos().x() - temp_x) / my_scale;
p_point[strategy][id_move_point][1] += (ev->pos().y() - temp_y) / my_scale;
temp_x = ev->pos().x();
temp_y = ev->pos().y();
update();
}
else
{
if(!point_state_t[id_move_point])
return;
t_point[strategy][id_move_point][0] += (ev->pos().x() - temp_x) / my_scale;
t_point[strategy][id_move_point][1] += (ev->pos().y() - temp_y) / my_scale;
temp_x = ev->pos().x();
temp_y = ev->pos().y();
update();
}
}
else if(is_dragging && id_select_edge != -1)
{
if(!has_weight)
{
if(!point_state[p_graph.getEdgeNode()[id_select_edge][0]] ||
!point_state[p_graph.getEdgeNode()[id_select_edge][1]])
return;
p_point[strategy][p_graph.getEdgeNode()[id_select_edge][0]][0] += (ev->pos().x() - temp_x) / my_scale;
p_point[strategy][p_graph.getEdgeNode()[id_select_edge][1]][0] += (ev->pos().x() - temp_x) / my_scale;
p_point[strategy][p_graph.getEdgeNode()[id_select_edge][0]][1] += (ev->pos().y() - temp_y) / my_scale;
p_point[strategy][p_graph.getEdgeNode()[id_select_edge][1]][1] += (ev->pos().y() - temp_y) / my_scale;
temp_x = ev->pos().x();
temp_y = ev->pos().y();
update();
}
else
{
if(!point_state_t[t_graph.getEdgeNode()[id_select_edge][0]] ||
!point_state_t[t_graph.getEdgeNode()[id_select_edge][1]]
|| !edge_state_t[id_select_edge])
return;
t_point[strategy][t_graph.getEdgeNode()[id_select_edge][0]][0] += (ev->pos().x() - temp_x) / my_scale;
t_point[strategy][t_graph.getEdgeNode()[id_select_edge][1]][0] += (ev->pos().x() - temp_x) / my_scale;
t_point[strategy][t_graph.getEdgeNode()[id_select_edge][0]][1] += (ev->pos().y() - temp_y) / my_scale;
t_point[strategy][t_graph.getEdgeNode()[id_select_edge][1]][1] += (ev->pos().y() - temp_y) / my_scale;
temp_x = ev->pos().x();
temp_y = ev->pos().y();
update();
}
}
//拉索模式,存储拉索坐标,并寻找在拉索圈内的点
else if(is_pull)
{
pull_vector.push_back(QPoint(ev->pos().x(), ev->pos().y()));
QPolygon temp_poly(pull_vector);
poly = temp_poly;
int node_num = p_graph.getNodeNum();
if(!has_weight)
{
for(int i = 0; i < node_num; i++)
{
if(!point_state[i])
continue;
if(poly.containsPoint(QPoint(calcX(my_scale * p_point[strategy][i][0]), calcY(my_scale * p_point[strategy][i][1])), Qt::OddEvenFill))
{
point_highlight[i] = true;
highlight_number ++;
}
else
{
point_highlight[i] = false;
}
}
}
else
{
for(int i = 0; i < node_num; i++)
{
if(!point_state_t[i])
continue;
if(poly.containsPoint(QPoint(calcX(my_scale * t_point[strategy][i][0]), calcY(my_scale * t_point[strategy][i][1])), Qt::OddEvenFill))
{
point_highlight[i] = true;
highlight_number ++;
}
else
{
point_highlight[i] = false;
}
}
}
update();
}
//高亮模式下等点群的拖动
else if(is_highlight)
{
id_select_point = -1;
int node_num = p_graph.getNodeNum();
if(!has_weight)
{
for(int i = 0; i < node_num; i++)
{
if(point_highlight[i])
{
p_point[strategy][i][0] += (ev->pos().x() - temp_x_highlight) / my_scale;
p_point[strategy][i][1] += (ev->pos().y() - temp_y_highlight) / my_scale;
}
}
temp_x_highlight = ev->pos().x();
temp_y_highlight = ev->pos().y();
update();
}
else
{
for(int i = 0; i < node_num; i++)
{
if(point_highlight[i])
{
t_point[strategy][i][0] += (ev->pos().x() - temp_x_highlight) / my_scale;
t_point[strategy][i][1] += (ev->pos().y() - temp_y_highlight) / my_scale;
}
}
temp_x_highlight = ev->pos().x();
temp_y_highlight = ev->pos().y();
update();
}
}
//不再以上模式,但按下鼠标,进行整图拖动
else if(is_mouse_pressed)
{
Opoint[0] += ev->pos().x() - temp_x;
Opoint[1] += ev->pos().y() - temp_y;
temp_x = ev->pos().x();
temp_y = ev->pos().y();
update();
}
else if(highlight_number > 0)
{
id_select_point = -1;
}
//普通未按下鼠标模式,实时更新鼠标是否在某点区或边区
else
{
id_select_edge = -1;
int candidate1 = -1;
int candidate2 = -1;
if(!has_weight)
{
temp_x = ev->pos().x();
temp_y = ev->pos().y();
int len = p_point[0].size();
int i;
for(i = 0; i < len; i++)
{
if(isInCicle(ev->pos().x(), ev->pos().y(), calcX(my_scale * p_point[strategy][i][0]), calcY(my_scale * p_point[strategy][i][1]), radis))
{
if(candidate1 == -1)
{
candidate1 = i;
}
else if(candidate2 == -1)
{
candidate2 = i;
}
else
{
break;
}
}
}
if(candidate1 == -1)
{
if(id_select_point != -1)
{
id_select_point = -1;
}
setCursor(Qt::ArrowCursor);
int edge_num = p_graph.getEdgeNum();
for(int i = 0; i < edge_num; i++)
{
if(point_state[p_graph.getEdgeNode()[i][0]] && point_state[p_graph.getEdgeNode()[i][1]])
{
if(inEdgeArea(calcX(my_scale * p_point[strategy][p_graph.getEdgeNode()[i][0]][0]),
calcY(my_scale * p_point[strategy][p_graph.getEdgeNode()[i][0]][1]),
calcX(my_scale * p_point[strategy][p_graph.getEdgeNode()[i][1]][0]),
calcY(my_scale * p_point[strategy][p_graph.getEdgeNode()[i][1]][1]),
ev->pos().x(), ev->pos().y()))
{
id_select_edge = i;
setCursor(Qt::PointingHandCursor);
break;
}
}
}
update();
return;
}
else if(candidate2 == -1)
{
id_select_point = candidate1;
setCursor(Qt::PointingHandCursor);
update();
}
else
{
if(calcInstance(calcX(my_scale * p_point[strategy][candidate1][0]),ev->pos().x(), calcY(my_scale * p_point[strategy][candidate1][1]), ev->pos().y()) >
calcInstance(calcX(my_scale * p_point[strategy][candidate2][0]),ev->pos().x(), calcY(my_scale * p_point[strategy][candidate2][1]), ev->pos().y()))
{
id_select_point = candidate2;
}
else
{
id_select_point = candidate1;
}
setCursor(Qt::PointingHandCursor);
update();
}
}
else
{
temp_x = ev->pos().x();
temp_y = ev->pos().y();
int len = p_point[0].size();
int i;
for(i = 0; i < len; i++)
{
if(isInCicle(ev->pos().x(), ev->pos().y(), calcX(my_scale * t_point[strategy][i][0]), calcY(my_scale * t_point[strategy][i][1]), radis))
{
if(candidate1 == -1)
{
candidate1 = i;
}
else if(candidate2 == -1)
{
candidate2 = i;
}
else
{
break;
}
}
}
if(candidate1 == -1)
{
if(id_select_point != -1)
{
id_select_point = -1;
}
setCursor(Qt::ArrowCursor);
int edge_num = t_graph.getEdgeNum();
for(int i = 0; i < edge_num; i++)
{
if(point_state_t[t_graph.getEdgeNode()[i][0]] && point_state_t[t_graph.getEdgeNode()[i][1]])
{
if(inEdgeArea(calcX(my_scale * t_point[strategy][t_graph.getEdgeNode()[i][0]][0]),
calcY(my_scale * t_point[strategy][t_graph.getEdgeNode()[i][0]][1]),
calcX(my_scale * t_point[strategy][t_graph.getEdgeNode()[i][1]][0]),
calcY(my_scale * t_point[strategy][t_graph.getEdgeNode()[i][1]][1]),
ev->pos().x(), ev->pos().y()))
{
id_select_edge = i;
if(!edge_state_t[id_select_edge])
continue;
setCursor(Qt::PointingHandCursor);
break;
}
}
}
update();
return;
}
else if(candidate2 == -1)
{
id_select_point = candidate1;
setCursor(Qt::PointingHandCursor);
update();
}
else
{
if(calcInstance(calcX(my_scale * t_point[strategy][candidate1][0]),ev->pos().x(), calcY(my_scale * t_point[strategy][candidate1][1]), ev->pos().y()) >
calcInstance(calcX(my_scale * t_point[strategy][candidate2][0]),ev->pos().x(), calcY(my_scale * t_point[strategy][candidate2][1]), ev->pos().y()))
{
id_select_point = candidate2;
}
else
{
id_select_point = candidate1;
}
setCursor(Qt::PointingHandCursor);
update();
}
}
}
}
//鼠标释放事件
void MainWindow::mouseReleaseEvent(QMouseEvent * ev)
{
if(is_in_start)
return;
is_mouse_pressed = false;
//左键释放,解除拖动
if(ev->button() == Qt::LeftButton)
{
if(is_dragging)
{
if(!has_weight)
{
is_dragging = false;
setCursor(Qt::PointingHandCursor);
update();
}
else
{
is_dragging = false;
setCursor(Qt::PointingHandCursor);
update();
}
}
}
//右键释放
else if(ev->button() == Qt::RightButton)
{
is_pull = false;
//若正在拉索,则高亮圈内的点
if(!is_highlight)
{
highlight_number = 0;
int node_num = p_graph.getNodeNum();
pull_vector.push_back(QPoint(ev->pos().x(), ev->pos().y()));
QPolygon temp_poly(pull_vector);
poly = temp_poly;
if(!has_weight)
{
for(int i = 0; i < node_num; i++)
{
if(!point_state[i])
continue;
if(poly.containsPoint(QPoint(calcX(my_scale * p_point[strategy][i][0]), calcY(my_scale * p_point[strategy][i][1])), Qt::OddEvenFill))
{
point_highlight[i] = true;
highlight_number ++;
}
else
{
point_highlight[i] = false;
}
}
}
else
{
for(int i = 0; i < node_num; i++)
{
if(!point_state_t[i])
continue;
if(poly.containsPoint(QPoint(calcX(my_scale * t_point[strategy][i][0]), calcY(my_scale * t_point[strategy][i][1])), Qt::OddEvenFill))
{
point_highlight[i] = true;
highlight_number ++;
}
else
{
point_highlight[i] = false;
}
}
}
pull_vector.clear();
update();
}
//若在拖动高亮点,则停止拖动
else if(is_highlight)
{
is_highlight = false;
}
}
}
//滚轮事件
void MainWindow::wheelEvent(QWheelEvent * ev)
{
if(is_in_start)
return;
//键盘的v h键未按下,放大缩小
if(!is_key_v_pressed && !is_key_h_pressed)
{
if(ev->delta() > 0)
{
ChangeScale(1.1);
if(full_big == 0)
{
setOpoint(Opoint[0] + 0.1 * (Opoint[0] + main_length / 2 - QPoint(cursor().pos()).x()), Opoint[1] + 0.1 * (Opoint[1] + main_width / 2 - QPoint(cursor().pos()).y()));
update();
}
else if(full_big == 2)
return;
else
{
setOpoint(Opoint[0] + (my_scale / my_last_scale - 1) * (Opoint[0] + main_length / 2 - QPoint(cursor().pos()).x()), Opoint[1] + (my_scale / my_last_scale - 1) * (Opoint[1] + main_width / 2 - QPoint(cursor().pos()).y()));
update();
}
}
else
{
ChangeScale(0.9);
if(full_big == 0)
{
setOpoint(Opoint[0] - 0.1 * (Opoint[0] + main_length / 2 - QPoint(cursor().pos()).x()), Opoint[1] - 0.1 * (Opoint[1] + main_width / 2 - QPoint(cursor().pos()).y()));
update();
}
else if(full_big == 2)
return;
else
{
setOpoint(Opoint[0] - (my_scale / my_last_scale - 1) * (Opoint[0] + main_length / 2 - QPoint(cursor().pos()).x()), Opoint[1] - (my_scale / my_last_scale - 1) * (Opoint[1] + main_width / 2 - QPoint(cursor().pos()).y()));
update();
}
}
}
//键盘的v键按下,控制垂直滚动条
else if(is_key_v_pressed)
{
if(ev->delta() > 0)
{
ui->verticalScrollBar->setSliderPosition(last_posi_vertical - 1);
}
else
{
ui->verticalScrollBar->setSliderPosition(last_posi_vertical + 1);
}
}
//键盘的h键按下,控制水平滚动条
else if(is_key_h_pressed)
{
if(ev->delta() > 0)
{
ui->horizontalScrollBar->setSliderPosition(last_posi_horizantol - 1);
}
else
{
ui->horizontalScrollBar->setSliderPosition(last_posi_horizantol + 1);
}
}
}
//窗口大小重置事件,改变控件位置与大小
void MainWindow::resizeEvent(QResizeEvent *ev)
{
ui->verticalScrollBar->setGeometry(ev->size().width() - 25, 0, 25,
ev->size().height() - 25 - ui->menuBar->height());
ui->horizontalScrollBar->setGeometry(0, ev->size().height() - 50, ev->size().width() - 25, 25);
ui->groupBox->setGeometry(ev->size().width() - 545, 0, 490, 210);
}
//切换layout
void MainWindow::setStrategy(Strategy s)
{
if(is_in_start)
return;
if(s == strategy)
{
return;
}
else
{
in_cartoon = true;
int node_num = p_point[0].size();
if(has_weight)
{
direction.clear();
direction.resize(node_num);
for(int i = 0; i < node_num; i++)
{
//设置动画方向及动画初始位置(点)
temp_point[i][0] = t_point[strategy][i][0];
temp_point[i][1] = t_point[strategy][i][1];
temp_point[i][2] = t_point[strategy][i][2];
direction[i].push_back(t_point[s][i][0] - t_point[strategy][i][0]);
direction[i].push_back(t_point[s][i][1] - t_point[strategy][i][1]);
direction[i].push_back(t_point[s][i][2] - t_point[strategy][i][2]);
}
phase = 0;
for(int i = 0; i < node_num; i++)
{
//设置动画速度(点)
velocity[i][0] = direction[i][0] / 50;
velocity[i][1] = direction[i][1] / 50;
velocity[i][2] = direction[i][2] / 50;
}
layout_timer.start();
}
else
{
direction.clear();
direction.resize(node_num);
for(int i = 0; i < node_num; i++)
{
temp_point[i][0] = p_point[strategy][i][0];
temp_point[i][1] = p_point[strategy][i][1];
temp_point[i][2] = p_point[strategy][i][2];
direction[i].push_back(p_point[s][i][0] - p_point[strategy][i][0]);
direction[i].push_back(p_point[s][i][1] - p_point[strategy][i][1]);
direction[i].push_back(p_point[s][i][2] - p_point[strategy][i][2]);
}
phase = 0;
for(int i = 0; i < node_num; i++)
{
velocity[i][0] = direction[i][0] / 50;
velocity[i][1] = direction[i][1] / 50;
velocity[i][2] = direction[i][2] / 50;
}
layout_timer.start();
}
strategy = s;
}
}
//layout切换动画
void MainWindow::changeLayout()
{
int node_num = p_point[0].size();
phase ++;
if(phase <= 50) //50帧动画
{
for(int i = 0; i < node_num; i++)
{
changeX(i, velocity[i][0]);
changeY(i, velocity[i][1]);
changeZ(i, velocity[i][2]);
}
update();
}
else
{
layout_timer.stop();
in_cartoon = false;
update();
}
}
//切换数据动画
void MainWindow::changeData()
{
int delta;
//用alpha透明度大小来控制渐变
if(alpha_degree == 0)
{
if(has_weight)
{
ui->toSpinBox->setMaximum(72);
ui->fromSpinBox->setMaximum(82);
ui->sumSpinBox->setMaximum(73);
has_weight = false;
layout_timer.setInterval(20);
}
else
{
ui->toSpinBox->setMaximum(17);
ui->fromSpinBox->setMaximum(17);
ui->sumSpinBox->setMaximum(17);
has_weight = true;
layout_timer.setInterval(30);
}
}
//两边数据的动画渐变速度不同,由于绘制时间的问题
if(!has_weight)
{
delta = 10;
}
else
{
delta = 5;
}
if(alpha_degree == -1)
{
data_timer.start();
data_change = 1;
alpha_degree = edge_color; //在这里用到了可调alpha值
update();
}
else if(alpha_degree > 0 && data_change == 1)
{
alpha_degree -= delta;
update();
}
else if(alpha_degree <= 0)
{
alpha_degree += delta;
data_change = 2;
update();
}
else if(alpha_degree > 0 && alpha_degree < edge_color && data_change == 2)
{
alpha_degree += delta;
update();
}
else if(alpha_degree == edge_color && data_change == 2)
{
data_change = 0;
alpha_degree = -1;
data_timer.stop();
update();
}
}
//layout切换菜单
void MainWindow::on_actionCircular_triggered()
{
if(is_in_start)
return;
setStrategy(CICLE);
}
void MainWindow::on_actionPass_through_triggered()
{
if(is_in_start)
return;
setStrategy(PASSTHROUGH);
}
void MainWindow::on_actionFast_2D_triggered()
{
if(is_in_start)
return;
setStrategy(FAST2D);
}
void MainWindow::on_actionRandom_triggered()
{
if(is_in_start)
return;
setStrategy(RANDOM);
}
void MainWindow::on_actionSimple_2D_triggered()
{
if(is_in_start)
return;
setStrategy(SIMPLE2D);
}
void MainWindow::on_actionForce_triggered()
{
if(is_in_start)
return;
setStrategy(FORCE);
}
void MainWindow::on_actionClustering_2D_triggered()
{
if(is_in_start)
return;
setStrategy(CLUSTERING2D);
}
void MainWindow::on_actionCone_triggered()
{
if(is_in_start)
return;
setStrategy(MYLAYOUT1);
}
void MainWindow::on_actionCommunity_2D_triggered()
{
if(is_in_start)
return;
setStrategy(MYLAYOUT2);
}
void MainWindow::on_actionStart_triggered()
{
if(is_in_start)
return;
setStrategy(START);
}
//data切换菜单
void MainWindow::on_actionPaper_triggered()
{
if(is_in_local)
return;
if(is_in_start)
return;
if(has_weight)
{
changeData();
}
else
{
return;
}
}
void MainWindow::on_actionTopic_triggered()
{
if(is_in_local)
return;
if(is_in_start)
return;
if(has_weight)
{
return;
}
else
{
changeData();
}
}
//tools菜单
//属性过滤器
void MainWindow::on_actionFilter_triggered()
{
if(is_in_start)
return;
if(is_in_local)
return;
if(!has_weight)
{
filterDialog dlg(p_graph, point_state);
dlg.exec();
update();
}
else
{
filterTopicDialog dlg(t_graph, point_state_t);
dlg.exec();
update();
}
}
//search及列表显示
void MainWindow::on_actionSearch_triggered()
{
if(is_in_start)
return;
if(is_in_local)
return;
int node_num = p_graph.getNodeNum();
vector<int> temp;
if(!has_weight)
{
point_state_copy = point_state;
filterDialog dlg(p_graph, point_state);
dlg.exec();
for(int i = 0; i < node_num; i++)
{
if(point_state[i])
{
temp.push_back(i);
}
}
point_state = point_state_copy;
searchResultDialog dialog(p_graph, temp);
dialog.exec();
}
else
{
point_state_t_copy = point_state_t;
filterTopicDialog dlg(t_graph, point_state_t);
dlg.exec();
for(int i = 0; i < node_num; i++)
{
if(point_state_t[i])
{
temp.push_back(i);
}
}
point_state_t = point_state_t_copy;
searchResultDialog dialog(t_graph, temp);
dialog.exec();
}
}
//重置按钮
void MainWindow::on_actionReset_triggered()
{
is_in_local = false;
int node_num = p_graph.getNodeNum();
my_scale = 1;
Opoint[0] = 0;
Opoint[1] = 0;
Opoint[2] = 0;
height = 0;
radis = 5;
in_cartoon = false;
strategy = START;
is_highlight = false;
is_pull = false;
full_big = 0;
highlight_number = 0;
alpha_degree = -1;
is_key_v_pressed = false;
is_key_h_pressed = false;
data_change = 0;
is_in_filter = false;
is_dragging = false;
is_single = false;
id_move_point = 0;
id_select_point = -1;
id_select_edge = -1;
is_mouse_pressed = false;
alpha_start = 0;
ui->node_out_slider->setValue(0);
ui->node_in_slider->setValue(0);
ui->node_sum_slider->setValue(0);
ui->weight_slider->setValue(0);
//设置edge weight
int number = t_graph.getEdgeNum();
for(int i =0 ;i < number; i++)
{
edge_state_t[i] = true;
}
//初始为paper图
has_weight = false;
//设置个节点初始属性
for(int i= 0; i < node_num; i++)
{
point_num_edge_state[0][0][i] = true;
point_num_edge_state[0][1][i] = true;
point_num_edge_state[0][2][i] = true;
point_num_edge_state[1][0][i] = true;
point_num_edge_state[1][1][i] = true;
point_num_edge_state[1][2][i] = true;
point_state[i] = true;
point_state_t[i] = true;
}
update();
}
//带贝塞尔曲线的边束化,交互比较慢
void MainWindow::on_actionEdge_bundling_triggered()
{
int edge_num;
vector<int> temp1;
if(has_weight)
{
edge_num = t_graph.getEdgeNum();
vector<vector<int> > temp2(edge_num);
for(int i = 0; i < edge_num; i++)
{
temp1.push_back(t_graph.getEdgeNode()[i][0]);
temp1.push_back(t_graph.getEdgeNode()[i][1]);
temp2[i] = temp1;
temp1.clear();
}
Dialog meb(edge_num, t_point[strategy], temp2);
meb.calcXYZForPaint();
meb.exec();
}
else
{
edge_num = p_graph.getEdgeNum();
vector<vector<int> > temp2(edge_num);
for(int i = 0; i < edge_num; i++)
{
temp1.push_back(p_graph.getEdgeNode()[i][0]);
temp1.push_back(p_graph.getEdgeNode()[i][1]);
temp2[i] = temp1;
temp1.clear();
}
Dialog meb(edge_num, p_point[strategy], temp2);
meb.calcXYZForPaint();
meb.exec();
}
}
//不带贝塞尔曲线的边束化,交互较快
void MainWindow::on_actionInteraction_edge_bundling_triggered()
{
int edge_num;
vector<int> temp1;
if(has_weight)
{
edge_num = t_graph.getEdgeNum();
vector<vector<int> > temp2(edge_num);
for(int i = 0; i < edge_num; i++)
{
temp1.push_back(t_graph.getEdgeNode()[i][0]);
temp1.push_back(t_graph.getEdgeNode()[i][1]);
temp2[i] = temp1;
temp1.clear();
}
noBezierDialog meb(edge_num, t_point[strategy], temp2);
meb.calcXYZForPaint();
meb.exec();
}
else
{
edge_num = p_graph.getEdgeNum();
vector<vector<int> > temp2(edge_num);
for(int i = 0; i < edge_num; i++)
{
temp1.push_back(p_graph.getEdgeNode()[i][0]);
temp1.push_back(p_graph.getEdgeNode()[i][1]);
temp2[i] = temp1;
temp1.clear();
}
noBezierDialog meb(edge_num, p_point[strategy], temp2);
meb.calcXYZForPaint();
meb.exec();
}
}
//file菜单
//存储layout
void MainWindow::on_actionSave_triggered()
{
if(is_in_start)
return;
bool is_original;
QMessageBox msg_box(this);
msg_box.addButton(QMessageBox::Yes);
msg_box.addButton(QMessageBox::No);
msg_box.setText("Do you want to save all the modification ?\nPress \"Yes\" to save, \"No\" to save the original layout.");
msg_box.setWindowTitle("warning");
msg_box.addButton(QMessageBox::Cancel);
QString file_name; //要保存的文件名
QFile file; //打开的文件
int flag; //存储各种对话框返回值状态
while(1)
{
flag = msg_box.exec();
if(flag == QMessageBox::Cancel)
{
return;
}
else if(flag == QMessageBox::Yes)
{
is_original = false;
file_name = QFileDialog::getSaveFileName(this, "save", "", tr("*.txt"));
file.setFileName(file_name);
if(file.open(QFile::ReadOnly))
{
flag = QMessageBox::warning(this, "warning", "The file has existed. Do you want to replace it.",
QMessageBox::Yes, QMessageBox::No);
if(flag == QMessageBox::Yes)
{
break;
}
else
{
continue;
}
}
else
{
file.close();
break;
}
}
else
{
is_original = true;
file_name = QFileDialog::getSaveFileName(this, "save", "", tr("*.txt"));
file.setFileName(file_name);
if(file.open(QFile::ReadOnly))
{
flag = QMessageBox::warning(this, "warning", "The file has existed. Do you want to replace it.",
QMessageBox::Yes, QMessageBox::No);
if(flag == QMessageBox::Yes)
{
break;
}
else
{
continue;
}
}
else
{
file.close();
break;
}
}
}
file.open(QFile::WriteOnly);
QTextStream out(&file);
int node_num = p_graph.getNodeNum();
if(is_original)
{
out << "PaperConferenceAuthorGraph" << endl;
for(int j = 0; j < strategy_num; j++)
{
out << j << endl;
for(int i = 0; i < node_num; i++)
{
out << p_point_copy[j][i][0] << endl;
out << p_point_copy[j][i][1] << endl;
}
}
out << "TopicGraph" << endl;
for(int j = 0; j < strategy_num; j++)
{
out << j << endl;
for(int i = 0; i < node_num; i++)
{
out << t_point_copy[j][i][0] << endl;
out << t_point_copy[j][i][1] << endl;
}
}
QMessageBox::information(this, "save success", "The file has been saved successfully.");
}
else
{
out << "PaperConferenceAuthorGraph" << endl;
for(int j = 0; j < strategy_num; j++)
{
out << j << endl;
for(int i = 0; i < node_num; i++)
{
out << p_point[j][i][0] << endl;
out << p_point[j][i][1] << endl;
}
}
out << "TopicGraph" << endl;
for(int j = 0; j < strategy_num; j++)
{
out << j << endl;
for(int i = 0; i < node_num; i++)
{
out << t_point[j][i][0] << endl;
out << t_point[j][i][1] << endl;
}
}
QMessageBox::information(this, "save success", "The file has been saved successfully.");
}
}
//加载layout
void MainWindow::on_actionLoad_layout_triggered()
{
QString file_name = readFileName(); //要打开的文件名
QFile file; //打开的文件
if(!file_name.length() <= 0)
{
return;
}
else
{
file.setFileName(file_name);
QTextStream in(&file);
in.readLine();
int node_num = p_graph.getNodeNum();
for(int j = 0; j < strategy_num; j++)
{
in.readLine();
for(int i = 0; i < node_num; i++)
{
p_point_copy[j][i][0] = in.readLine().toDouble();
p_point_copy[j][i][1] = in.readLine().toDouble();
}
}
for(int j = 0; j < strategy_num; j++)
{
in.readLine();
for(int i = 0; i < node_num; i++)
{
t_point_copy[j][i][0] = in.readLine().toDouble();
t_point_copy[j][i][1] = in.readLine().toDouble();
}
}
QMessageBox::information(this, "load success", "The file has been loaded successfully.");
}
}
//存储data,五种选项
void MainWindow::on_actionSave_paper_node_triggered()
{
QString file_name = writeFileName(); //要保存的文件名
if(file_name.length() <= 0)
return;
QFile file(file_name); //打开的文件
file.open(QFile::WriteOnly);
QTextStream out(&file);
int node_num = p_graph.getNodeNum();
for(int j = 0; j < node_num; j++)
{
out << p_graph.getNode()[j]->getIdOfNode() << endl;
switch(p_graph.getNode()[j]->getType())
{
case PaperConferenceAuthorNode::PAPER:
out << "type: paper" << endl;
out << "year: " << p_graph.getNode()[j]->getYear() << endl;
out << "author: " << p_graph.getNode()[j]->getExtra().c_str() << endl;
out << "dateFrom: " << p_graph.getNode()[j]->getDateFrom() << endl;
out << "id: " << p_graph.getNode()[j]->getId().c_str() << endl;
out << "pageFrom: " << p_graph.getNode()[j]->getPageFrom() << endl;
out << "paperTitle: " << p_graph.getNode()[j]->getName().c_str() << endl;
out << "paperTitleShort: " << p_graph.getNode()[j]->getNameShort().c_str() << endl;
break;
case PaperConferenceAuthorNode::CONFERENCE:
out << "type: conference" << endl;
out << "year: " << p_graph.getNode()[j]->getYear() << endl;
out << "id: " << p_graph.getNode()[j]->getId().c_str() << endl;
out << "conferenceName: " << p_graph.getNode()[j]->getName().c_str() << endl;
out << "conferenceNameShort: " << p_graph.getNode()[j]->getNameShort().c_str() << endl;
break;
case PaperConferenceAuthorNode::AUTHOR:
out << "type: conference" << endl;
out << "year: " << p_graph.getNode()[j]->getYear() << endl;
out << "id: " << p_graph.getNode()[j]->getId().c_str() << endl;
out << "authorName: " << p_graph.getNode()[j]->getName().c_str() << endl;
out << "authorNameShort: " << p_graph.getNode()[j]->getNameShort().c_str() << endl;
break;
}
out << "viewColor: (" << p_graph.getNode()[j]->getViewColor()[0] << ","
<< p_graph.getNode()[j]->getViewColor()[1] << ","
<< p_graph.getNode()[j]->getViewColor()[2] << ","
<< p_graph.getNode()[j]->getViewColor()[3] << ")" << endl;
out << "viewLabel: " << p_graph.getNode()[j]->getViewLabel().c_str() << endl;
out << "viewLayout: (" << p_graph.getNode()[j]->getViewLayout()[0] << ","
<< p_graph.getNode()[j]->getViewLayout()[1] << ","
<< p_graph.getNode()[j]->getViewLayout()[2] << ")" << endl;
out << endl;
}
file.close();
QMessageBox::information(this, "save success", "The file has been saved successfully.");
}
void MainWindow::on_actionSave_paper_edge_triggered()
{
QString file_name = writeFileName(); //要保存的文件名
if(file_name.length() <= 0)
return;
QFile file(file_name); //打开的文件
file.open(QFile::WriteOnly);
QTextStream out(&file);
int edge_num = p_graph.getEdgeNum();
out.setDevice(&file);
for(int j = 0; j < edge_num; j++)
{
out << p_graph.getEdge()[j]->getSource() << " " << p_graph.getEdge()[j]->getTarget() << endl;
}
out << endl;
file.close();
QMessageBox::information(this, "save success", "The file has been saved successfully.");
}
void MainWindow::on_actionSave_topic_node_triggered()
{
QString file_name = writeFileName(); //要保存的文件名
if(file_name.length() <= 0)
return;
QFile file(file_name); //打开的文件
file.open(QFile::WriteOnly);
QTextStream out(&file);
int node_num = t_graph.getNodeNum();
out.setDevice(&file);
for(int j = 0; j < node_num; j++)
{
out << t_graph.getNode()[j]->getIdOfNode() << endl;
out << "TopicWords: ";
for(auto iter = t_graph.getNode()[j]->getWords().begin(); iter != t_graph.getNode()[j]->getWords().end(); iter++)
{
out << (*iter).c_str() << " ";
}
out << endl;
out << "TopicDocuments: ";
for(auto iter = t_graph.getNode()[j]->getDoc().begin(); iter != t_graph.getNode()[j]->getDoc().end(); iter++)
{
out << *iter << " ";
}
out << endl;
out << endl;
}
file.close();
QMessageBox::information(this, "save success", "The file has been saved successfully.");
}
void MainWindow::on_actionSave_topic_edge_triggered()
{
QString file_name = writeFileName(); //要保存的文件名
if(file_name.length() <= 0)
return;
QFile file(file_name); //打开的文件
file.open(QFile::WriteOnly);
QTextStream out(&file);
int edge_num = t_graph.getEdgeNum();
out.setDevice(&file);
for(int j = 0; j < edge_num; j++)
{
out << t_graph.getEdge()[j]->getSource() << " " << t_graph.getEdge()[j]->getTarget() << " " << t_graph.getEdge()[j]->getWeight() << endl;
}
out << endl;
file.close();
QMessageBox::information(this, "save success", "The file has been saved successfully.");
}
void MainWindow::on_actionSave_document_node_triggered()
{
QString file_name = writeFileName(); //要保存的文件名
if(file_name.length() <= 0)
return;
QFile file(file_name); //打开的文件
file.open(QFile::WriteOnly);
QTextStream out(&file);
out.setDevice(&file);
int node_num = t_graph.getAllDoc().size();
for(int j = 0; j < node_num; j++)
{
out << t_graph.getDocNode(j).getIdOfNode() << endl;
out << t_graph.getDocNode(j).getTitle().c_str() << endl;
out << t_graph.getDocNode(j).getContent().c_str() << endl;
out << endl;
}
out << endl;
file.close();
QMessageBox::information(this, "save success", "The file has been saved successfully.");
}
//加载data,五种选项
void MainWindow::on_actionLoad_paper_node_triggered()
{
string file_name = readFileName().toStdString();
if(file_name.length() <= 0)
return;
ifstream fin;
PaperConferenceAuthorNode * temp_base;
p_graph.deleteNode();
fin.open(file_name);
if(!fin.is_open())
{
cout << "The file isn't open." << endl;
return;
}
int id;
char * buffer = new char[1024];
int k = 0;
while(1)
{
p_graph.readSTD(fin, buffer, temp_base, id, k);
p_graph.addNode(temp_base);
if(!fin.eof())
{
}
else
{
break;
}
}
delete buffer;
p_graph.initialize();
update();
}
void MainWindow::on_actionLoad_paper_edge_triggered()
{
string file_name = readFileName().toStdString();
if(file_name.length() <= 0)
return;
p_graph.deleteEdge();
p_graph.readInEdge(file_name.c_str());
p_graph.initialize();
update();
}
void MainWindow::on_actionLoad_topic_node_triggered()
{
string file_name = readFileName().toStdString();
if(file_name.length() <= 0)
return;
ifstream fin;
TopicNode * temp_base;
t_graph.deleteNode();
fin.open(file_name);
if(!fin.is_open())
{
cout << "The file isn't open." << endl;
return;
}
int id;
char * buffer = new char[1024];
while(1)
{
t_graph.getNodeIn().push_back(vector<int>());
t_graph.getNodeOut().push_back(vector<int>());
t_graph.readSTD(fin, buffer, temp_base, id);
if(!fin.eof())
{
}
else
{
break;
}
}
delete buffer;
fin.close();
t_graph.initialize();
update();
}
void MainWindow::on_actionLoad_topic_edge_triggered()
{
string file_name = readFileName().toStdString();
if(file_name.length() <= 0)
return;
t_graph.deleteEdge();
t_graph.readInTopicEdge(file_name.c_str());
t_graph.initialize();
update();
}
void MainWindow::on_actionLoad_document_node_triggered()
{
string file_name = readFileName().toStdString();
if(file_name.length() <= 0)
return;
qDebug() << file_name.c_str();
t_graph.deleteDocNode();
t_graph.readInDocNode(file_name.c_str());
}
//存储辅助函数,获取文件名来写
QString MainWindow::writeFileName()
{
if(is_in_start)
return "";
QString file_name; //要保存的文件名
file_name = QFileDialog::getSaveFileName(this, "save topic edge", "", tr("*.txt"));
return file_name;
}
//存储辅助函数,获取文件名来读
QString MainWindow::readFileName()
{
if(is_in_start)
return "";
QString file_name; //要打开的文件名
QFile file; //打开的文件
int flag; //存储各种对话框返回值状态
while(1)
{
file_name = QFileDialog::getOpenFileName(this, "open", "", tr("*.txt"));
if(file_name.length() <= 0)
return "";
file.setFileName(file_name);
if(!file.open(QFile::ReadOnly))
{
flag = QMessageBox::warning(this, "warning", "The file isn't existed.\nPress \"ok\" to check.",
QMessageBox::Ok, QMessageBox::Cancel);
if(flag == QMessageBox::Ok)
{
continue;
}
else
{
return "";
}
}
else
{
break;
}
}
return file_name;
}
//滚动条控件变化对应图的平移并与滚轮事件连接
void MainWindow::on_horizontalScrollBar_valueChanged(int position)
{
if(is_in_start)
return;
if(last_posi_horizantol > position)
{
Opoint[0] += 50 * my_scale;
update();
}
else
{
Opoint[0] -= 50 * my_scale;
update();
}
last_posi_horizantol = position;
}
void MainWindow::on_verticalScrollBar_valueChanged(int position)
{
if(is_in_start)
return;
if(last_posi_vertical > position)
{
Opoint[1] += 50 * my_scale;
update();
}
else
{
Opoint[1] -= 50 * my_scale;
update();
}
last_posi_vertical = position;
}
//toolbox过滤器控件设置
void MainWindow::on_node_out_slider_valueChanged(int value)
{
if(is_in_start)
return;
if(is_in_local)
return;
int node_num = p_graph.getNodeNum();
if(!has_weight)
{
for(int i = 0; i < node_num; i++)
{
if(p_graph.getOutNum(i) >= value)
{
point_num_edge_state[0][2][i] = true;
}
else
{
point_num_edge_state[0][2][i] = false;
}
}
for(int i = 0; i < node_num; i++)
{
point_state[i] = point_num_edge_state[0][0][i] && point_num_edge_state[0][1][i] && point_num_edge_state[0][2][i];
}
}
else
{
for(int i = 0; i < node_num; i++)
{
if(t_graph.getOutNum(i) >= value / 4.1)
{
point_num_edge_state[1][2][i] = true;
}
else
{
point_num_edge_state[1][2][i] = false;
}
}
for(int i = 0; i < node_num; i++)
{
point_state_t[i] = point_num_edge_state[1][0][i] && point_num_edge_state[1][1][i] && point_num_edge_state[1][2][i];
}
}
if(!is_spinBox_changed)
{
is_spinBox_changed = true;
if(!has_weight)
ui->toSpinBox->setValue(value);
else
ui->toSpinBox->setValue(int(value / 4.1));
}
else
{
is_spinBox_changed = false;
}
update();
}
void MainWindow::on_node_in_slider_valueChanged(int value)
{
if(is_in_start)
return;
if(is_in_local)
return;
int node_num = p_graph.getNodeNum();
if(!has_weight)
{
for(int i = 0; i < node_num; i++)
{
if(p_graph.getInNum(i) >= value)
{
point_num_edge_state[0][1][i] = true;
}
else
{
point_num_edge_state[0][1][i] = false;
}
}
for(int i = 0; i < node_num; i++)
{
point_state[i] = point_num_edge_state[0][0][i] && point_num_edge_state[0][1][i] && point_num_edge_state[0][2][i];
}
}
else
{
for(int i = 0; i < node_num; i++)
{
if(t_graph.getInNum(i) >= value / 1.9)
{
point_num_edge_state[1][1][i]= true;
}
else
{
point_num_edge_state[1][1][i] = false;
}
}
for(int i = 0; i < node_num; i++)
{
point_state_t[i] = point_num_edge_state[1][0][i] && point_num_edge_state[1][1][i] && point_num_edge_state[1][2][i];
}
}
if(!is_spinBox_changed)
{
is_spinBox_changed = true;
if(!has_weight)
ui->fromSpinBox->setValue(value);
else
ui->fromSpinBox->setValue(int(value / 1.9));
}
else
{
is_spinBox_changed = false;
}
update();
}
void MainWindow::on_node_sum_slider_valueChanged(int value)
{
if(is_in_start)
return;
if(is_in_local)
return;
int node_num = p_graph.getNodeNum();
if(!has_weight)
{
for(int i = 0; i < node_num; i++)
{
if(p_graph.getSumNum(i) >= value)
{
point_num_edge_state[0][0][i] = true;
}
else
{
point_num_edge_state[0][0][i] = false;
}
}
for(int i = 0; i < node_num; i++)
{
point_state[i] = point_num_edge_state[0][0][i] && point_num_edge_state[0][1][i] && point_num_edge_state[0][2][i];
}
}
else
{
for(int i = 0; i < node_num; i++)
{
if(t_graph.getSumNum(i) >= value / 4.6)
{
point_num_edge_state[1][0][i] = true;
}
else
{
point_num_edge_state[1][0][i] = false;
}
}
for(int i = 0; i < node_num; i++)
{
point_state_t[i] = point_num_edge_state[1][0][i] && point_num_edge_state[1][1][i] && point_num_edge_state[1][2][i];
}
}
if(!is_spinBox_changed)
{
is_spinBox_changed = true;
if(!has_weight)
ui->sumSpinBox->setValue(value);
else
ui->sumSpinBox->setValue(int(value / 4.6));
}
else
{
is_spinBox_changed = false;
}
update();
}
void MainWindow::on_weight_slider_valueChanged(int value)
{
if(is_in_start)
return;
if(is_in_local)
return;
int edge_num = t_graph.getEdgeNum();
if(!has_weight)
{
return;
}
else
{
for(int i = 0; i < edge_num; i++)
{
if(t_graph.getEdge()[i]->getWeight() > (double)value / 100)
{
edge_state_t[i] = true;
}
else
{
edge_state_t[i] = false;
}
}
}
if(!is_spinBox_changed)
{
is_spinBox_changed = true;
if(!has_weight)
return;
else
ui->weightSpinBox->setValue(double(value) / 100);
}
else
{
is_spinBox_changed = false;
}
update();
}
//显示过滤器的数值,与其前面的slider过滤器连接
void MainWindow::on_toSpinBox_valueChanged(int value)
{
if(!is_spinBox_changed)
{
is_spinBox_changed = true;
if(!has_weight)
ui->node_out_slider->setValue(value);
else
ui->node_out_slider->setValue(int(4.1 * value));
}
else
is_spinBox_changed = false;
}
void MainWindow::on_fromSpinBox_valueChanged(int value)
{
if(!is_spinBox_changed)
{
is_spinBox_changed = true;
if(!has_weight)
ui->node_in_slider->setValue(value);
else
ui->node_in_slider->setValue(int(1.9 * value));
}
else
is_spinBox_changed = false;
}
void MainWindow::on_sumSpinBox_valueChanged(int value)
{
if(!is_spinBox_changed)
{
is_spinBox_changed = true;
if(!has_weight)
ui->node_sum_slider->setValue(value);
else
ui->node_sum_slider->setValue(int(4.6 * value));
}
else
is_spinBox_changed = false;
}
void MainWindow::on_weightSpinBox_valueChanged(double value)
{
if(!is_spinBox_changed)
{
is_spinBox_changed = true;
if(!has_weight)
return;
else
ui->weight_slider->setValue(int(value * 100));
}
else
is_spinBox_changed = false;
}
//开始键
void MainWindow::on_start_btn_clicked()
{
start_timer.start();
changeDataStart();
}
//开始动画,渐变效果
void MainWindow::changeDataStart()
{
if(alpha_start < edge_color)
alpha_start += 14;
else
{
is_in_start = false;
start_timer.stop();
ui->start_btn->setGeometry(3000, 2000, 10, 10);
}
update();
}
//布局算法变换动画
void MainWindow::on_actionCartoon_triggered()
{
cartoonDialog dlg(t_graph);
dlg.exec();
}
| 34.815312 | 236 | 0.489689 | [
"vector"
] |
5b3974f2fe537349cedf0f5c61d44edc5e520b88 | 12,657 | hpp | C++ | include/ufmt/text.hpp | ortfero/fb2md | 5764a79b672e311f9604c3e8e614c9c998cd9a06 | [
"MIT"
] | null | null | null | include/ufmt/text.hpp | ortfero/fb2md | 5764a79b672e311f9604c3e8e614c9c998cd9a06 | [
"MIT"
] | null | null | null | include/ufmt/text.hpp | ortfero/fb2md | 5764a79b672e311f9604c3e8e614c9c998cd9a06 | [
"MIT"
] | null | null | null | /* This file is part of ufmt library
* Copyright 2020-2022 Andrei Ilin <ortfero@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#pragma once
#include <charconv>
#include <string>
#include <string_view>
#include <vector>
namespace ufmt {
template<typename S>
class basic_text {
private:
S string_;
public:
using size_type = std::size_t;
using value_type = typename S::value_type;
template<typename... Args>
static basic_text of(Args&&... args) {
basic_text t;
t.format(std::forward<Args>(args)...);
return t;
}
basic_text() noexcept = default;
basic_text(basic_text const&) = default;
basic_text& operator=(basic_text const&) = default;
basic_text(basic_text&&) noexcept = default;
basic_text& operator=(basic_text&&) noexcept = default;
S const& string() const noexcept { return string_; }
value_type const* data() const noexcept { return string_.data(); }
size_type size() const noexcept { return string_.size(); }
bool empty() const noexcept { return string_.empty(); }
void clear() noexcept { string_.clear(); }
size_type capacity() const noexcept { return string_.capacity(); }
value_type operator[](size_type i) const noexcept { return string_[i]; }
value_type& operator[](size_type i) noexcept { return string_[i]; }
void reserve(size_type n) {
if(n <= string_.capacity())
return;
n = nearest_power_of_2(n);
string_.reserve(n);
}
value_type* allocate(size_type n) {
auto const original_size = string_.size();
auto const next_size = original_size + n;
if(next_size > string_.capacity()) {
auto const reserve_size = nearest_power_of_2(next_size);
string_.reserve(reserve_size);
if(string_.capacity() < reserve_size)
return nullptr;
}
string_.resize(next_size);
return string_.data() + original_size;
}
void free(value_type* p) {
string_.resize(size_type(p - string_.data()));
}
basic_text& append(value_type const* stringz, size_type n) {
if(n == 0)
return *this;
value_type* p = allocate(n);
if(!p)
return *this;
value_type const* end = stringz + n;
for(value_type const* from = stringz; from != end; ++from, ++p)
*p = *from;
free(p);
return *this;
}
void char_n(value_type ch, size_type n) {
value_type* p = allocate(n);
if(!p)
return;
for(value_type* end = p + n; p != end; ++p)
*p = ch;
free(p);
}
void format() {
}
template<typename Arg, typename... Args>
void format(Arg&& arg, Args&&... args) {
(*this) << arg;
format(std::forward<Args>(args)...);
}
template<std::size_t N> friend
basic_text& operator << (basic_text& self,
value_type const (&literal)[N]) {
return self.append(literal, N - 1);
}
private:
static uint64_t nearest_power_of_2(uint64_t n) {
if(n <= 2)
return 2;
n--;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
n |= n >> 32;
n++;
return n;
}
}; // basic_text
using text = basic_text<std::string>;
template<class String, class Stream>
Stream& operator << (Stream& stream,
basic_text<String> const& bt) {
return stream << bt.string();
}
template<class S>
basic_text<S>& operator << (basic_text<S>& self,
typename S::value_type ch) {
typename S::value_type* p = self.allocate(1);
if(!p)
return self;
*p++ = ch;
self.free(p);
return self;
}
template<class S>
basic_text<S>& operator << (basic_text<S>& self, std::string_view sv) {
return self.append(sv.data(), sv.size());
}
template<class S>
basic_text<S>& operator << (basic_text<S>& self, std::string const& s) {
return self.append(s.data(), s.size());
}
/*template<class S>
basic_text<S>& operator << (basic_text<S>& self, bool value) {
return value ? self.append("true", 4) : self.append("false", 5);
}*/
namespace detail {
template<std::size_t N, class S, typename T>
basic_text<S>& print_number(basic_text<S>& self, T value) {
typename S::value_type* p = self.allocate(N);
if(!p)
return self;
auto const r = std::to_chars(p, p + N, value);
self.free(r.ptr);
return self;
}
} // detail
template<class S>
basic_text<S>& operator << (basic_text<S>& self, std::int32_t value) {
return detail::print_number<10>(self, value);
}
template<class S>
basic_text<S>& operator << (basic_text<S>& self, std::uint32_t value) {
return detail::print_number<11>(self, value);
}
template<class S>
basic_text<S>& operator << (basic_text<S>& self, std::int64_t value) {
return detail::print_number<19>(self, value);
}
template<class S>
basic_text<S>& operator << (basic_text<S>& self, std::uint64_t value) {
return detail::print_number<18>(self, value);
}
template<class S>
basic_text<S>& operator << (basic_text<S>& self, float value) {
return detail::print_number<64>(self, value);
}
template<class S>
basic_text<S>& operator << (basic_text<S>& self, double value) {
return detail::print_number<64>(self, value);
}
template<class S, typename T>
basic_text<S>& operator << (basic_text<S>& self,
std::vector<T> const& value) {
self << '[';
if(!value.empty()) {
auto it = value.begin();
self << ' ' << *it;
++it;
for(; it != value.end(); ++it)
self << ", " << *it;
}
self << " ]";
return self;
}
namespace formatters {
template<typename T>
struct left {
T const& value;
std::size_t width;
};
template<class S, typename T>
basic_text<S>& operator << (basic_text<S>& self, left<T> l) {
auto const original_size = self.size();
self << l.value;
auto const next_size = self.size();
auto const value_size = next_size - original_size;
if(value_size >= l.width)
return self;
auto const spaces_count = l.width - value_size;
self.char_n(' ', spaces_count);
return self;
}
template<typename T>
struct right {
T const& value;
std::size_t width;
};
template<class S, typename T>
basic_text<S>& operator << (basic_text<S>& self, right<T> r) {
auto const original_size = self.size();
self << r.value;
auto const next_size = self.size();
auto const value_size = next_size - original_size;
if(value_size >= r.width)
return self;
auto const spaces_count = r.width - value_size;
self.char_n(' ', spaces_count);
for(auto i = next_size - 1; i != original_size - 1; --i)
self[i + spaces_count] = self[i];
for(std::size_t i = 0; i != spaces_count; ++i)
self[original_size + i] = ' ';
return self;
}
template<typename T>
struct float_fixed {
T value;
int precision;
};
template<class S, typename T>
basic_text<S>& operator << (basic_text<S>& self, float_fixed<T> f) {
constexpr auto float_digits = 64;
typename S::value_type* p = self.allocate(float_digits);
if(!p)
return self;
auto const r = std::to_chars(p, p + float_digits, f.value,
std::chars_format::fixed, f.precision);
self.free(r.ptr);
return self;
}
template<typename T>
struct integer_fixed {
T value;
std::size_t width;
};
template<class S, typename T>
basic_text<S>& operator << (basic_text<S>& self, integer_fixed<T> f) {
auto const original_size = self.size();
self << f.value;
auto const next_size = self.size();
auto const value_size = next_size - original_size;
if(value_size >= f.width)
return self;
auto const spaces_count = f.width - value_size;
self.char_n('0', spaces_count);
for(auto i = next_size - 1; i != original_size - 1; --i)
self[i + spaces_count] = self[i];
for(std::size_t i = 0; i != spaces_count; ++i)
self[original_size + i] = '0';
return self;
}
template<typename T>
struct quoted { T const& value; };
template<class S, typename T>
basic_text<S>& operator << (basic_text<S>& self, quoted<T> q) {
self << '\'';
self << q.value;
self << '\'';
return self;
}
template<typename T>
struct dquoted { T const& value; };
template<class S, typename T>
basic_text<S>& operator << (basic_text<S>& self, dquoted<T> q) {
self << '\"';
self << q.value;
self << '\"';
return self;
}
} // formatters
template<typename T>
formatters::left<T> left(T const& value, std::size_t width) {
return formatters::left<T>{value, width};
}
template<typename T>
formatters::right<T> right(T const& value, std::size_t width) {
return formatters::right<T>{value, width};
}
formatters::float_fixed<double> precised(double value, int precision) {
return formatters::float_fixed<double>{value, precision};
}
formatters::integer_fixed<std::uint64_t> fixed(std::uint64_t value, int width) {
return formatters::integer_fixed<std::uint64_t>{value, std::size_t(width)};
}
template<typename T>
formatters::quoted<T> quoted(T const& value) {
return formatters::quoted<T>{value};
}
template<typename T>
formatters::dquoted<T> dquoted(T const& value) {
return formatters::dquoted<T>{value};
}
} // ufmt
| 30.207637 | 84 | 0.515367 | [
"vector"
] |
5b48167e269126e0e043b3c70cb014a4f24945a6 | 2,286 | cpp | C++ | my04-Maze-Solver迷宫解密/maze.cpp | makelove/OpenCV-Python-Tutorial | e428d648f7aa50d6a0fb4f4d0fb1bd1a600fef41 | [
"MIT"
] | 2,875 | 2016-10-21T01:33:22.000Z | 2022-03-30T12:15:28.000Z | my04-Maze-Solver迷宫解密/maze.cpp | makelove/OpenCV-Python-Tutorial | e428d648f7aa50d6a0fb4f4d0fb1bd1a600fef41 | [
"MIT"
] | 12 | 2017-07-18T14:24:27.000Z | 2021-07-04T10:32:25.000Z | my04-Maze-Solver迷宫解密/maze.cpp | makelove/OpenCV-Python-Tutorial | e428d648f7aa50d6a0fb4f4d0fb1bd1a600fef41 | [
"MIT"
] | 1,066 | 2017-03-11T01:43:28.000Z | 2022-03-29T14:52:41.000Z | #include<iostream>
#include<cstdlib>
#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
using namespace std;
using namespace cv;
Mat kernel = Mat::ones(15, 15, CV_8UC1);
class Morph{
private:
int dilationElem,erodeElem;
int dilationSize,erodeSize;
public:
Morph(){
dilationElem=0;
erodeElem=0;
dilationSize=2;
erodeSize=2;
}
Mat dilateImage(Mat input){
Mat temp,element;
int dilationType;
if(dilationElem==0)
dilationType=MORPH_RECT;
else if(dilationElem==1)
dilationType=MORPH_CROSS;
else if(dilationElem==2)
dilationType=MORPH_ELLIPSE;
element= getStructuringElement(dilationType,Size(2*dilationSize+1,2*dilationSize+1),Point(dilationSize,dilationSize));
dilate(input,temp,kernel);
return temp;
}
Mat erodeImage(Mat input){
Mat temp,element;
int erodeType;
if(erodeElem==0)
erodeType=MORPH_RECT;
else if(erodeElem==1)
erodeType=MORPH_CROSS;
else if(erodeElem==2)
erodeType=MORPH_ELLIPSE;
element= getStructuringElement(erodeType,Size(2*erodeSize+1,2*erodeSize+1),Point(erodeSize,erodeSize));
dilate(input,temp,kernel);
return temp;
}
};
int main(int argc, char **argv){
if(argc!=2){
cout<<"Wait for an image"<<endl;
return -1;
}
vector<vector<Point> > contours;
Mat inputMaze,gray,binary,dilation,erosion,imgDiff,BGRcomp[3],imgDiff_inv,output,red,green;
Morph mp;
inputMaze=imread(argv[1],CV_LOAD_IMAGE_COLOR);
cvtColor(inputMaze,gray,CV_BGR2GRAY);
threshold(gray,binary,127,255,CV_THRESH_BINARY_INV);
findContours(binary,contours,CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
drawContours(binary, contours, 0, CV_RGB(255,255,255), CV_FILLED);
threshold(binary,binary,240,255,CV_THRESH_BINARY);
dilation=mp.dilateImage(binary);
erosion=mp.erodeImage(dilation);
absdiff(dilation,erosion,imgDiff);
bitwise_not(imgDiff,imgDiff_inv);
split(inputMaze,BGRcomp);
namedWindow("diff",WINDOW_AUTOSIZE);
imshow("diff",imgDiff);
bitwise_and(BGRcomp[2],BGRcomp[2],red,imgDiff_inv);
bitwise_and(BGRcomp[1],BGRcomp[1],green,imgDiff_inv);
BGRcomp[2]=red.clone();
BGRcomp[1]=green.clone();
merge(BGRcomp,3,output);
namedWindow("SolvedMaze",WINDOW_AUTOSIZE);
imshow("SolvedMaze",output);
//imwrite("OutputMaze.jpg",output);
waitKey(0);
return 0;
} | 27.878049 | 120 | 0.755906 | [
"vector"
] |
5b48ac3af4571a9a43b9f0e0d9747093d3e3b740 | 14,215 | cc | C++ | log/test/integration/query.cc | srmainwaring/ign-transport | f3c8f8b043c4cf2203ad0dd621181b882cae5667 | [
"ECL-2.0",
"Apache-2.0"
] | 21 | 2020-04-15T16:58:42.000Z | 2022-03-07T00:27:15.000Z | log/test/integration/query.cc | srmainwaring/ign-transport | f3c8f8b043c4cf2203ad0dd621181b882cae5667 | [
"ECL-2.0",
"Apache-2.0"
] | 164 | 2020-04-29T23:29:49.000Z | 2022-03-25T22:30:10.000Z | log/test/integration/query.cc | srmainwaring/ign-transport | f3c8f8b043c4cf2203ad0dd621181b882cae5667 | [
"ECL-2.0",
"Apache-2.0"
] | 23 | 2020-05-15T18:34:59.000Z | 2022-02-01T16:46:52.000Z | /*
* Copyright (C) 2017 Open Source Robotics 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 <chrono>
#include <regex>
#include <string>
#include <vector>
#include "ignition/transport/log/Log.hh"
#include "gtest/gtest.h"
using namespace ignition;
using namespace ignition::transport;
using namespace std::chrono_literals;
//////////////////////////////////////////////////
/// \brief container for test message data
typedef struct
{
std::chrono::nanoseconds time;
std::string topic;
std::string type;
std::string data;
} TestMessage;
//////////////////////////////////////////////////
std::vector<TestMessage> StandardTestMessages()
{
std::vector<TestMessage> messages;
messages.push_back({
1s,
"/topic/one",
"msg.type.1",
"topic1_type1_num1",
});
messages.push_back({
1250ms,
"/topic/one",
"msg.type.2",
"topic1_type2_num1",
});
messages.push_back({
1750ms,
"/topic/two",
"msg.type.1",
"topic2_type1_num1",
});
messages.push_back({
2s,
"/topic/one",
"msg.type.1",
"topic1_type1_num2",
});
messages.push_back({
2250ms,
"/topic/one",
"msg.type.2",
"topic1_type2_num2",
});
messages.push_back({
2750ms,
"/topic/two",
"msg.type.2",
"topic2_type1_num2",
});
messages.push_back({
3s,
"/topic/one",
"msg.type.1",
"topic1_type1_num3",
});
messages.push_back({
3250ms,
"/topic/one",
"msg.type.2",
"topic1_type2_num3",
});
messages.push_back({
3750ms,
"/topic/two",
"msg.type.1",
"topic2_type1_num3",
});
return messages;
}
//////////////////////////////////////////////////
void CheckEquality(const TestMessage &_golden, const log::Message &_uut)
{
EXPECT_EQ(_golden.time, _uut.TimeReceived());
EXPECT_EQ(_golden.topic, _uut.Topic());
EXPECT_EQ(_golden.type, _uut.Type());
EXPECT_EQ(_golden.data, _uut.Data());
}
//////////////////////////////////////////////////
void InsertMessages(log::Log &_log,
const std::vector<TestMessage> &_messages)
{
for (const TestMessage &msg : _messages)
{
ASSERT_TRUE(_log.InsertMessage(
msg.time,
msg.topic,
msg.type,
reinterpret_cast<const void *>(msg.data.c_str()),
msg.data.size()));
}
}
//////////////////////////////////////////////////
TEST(QueryMessages, QueryAllTopicsAfterInclusive)
{
log::Log logFile;
ASSERT_TRUE(logFile.Open(":memory:", std::ios_base::out));
auto testMessages = StandardTestMessages();
InsertMessages(logFile, testMessages);
log::QualifiedTime beginTime(2s, log::QualifiedTime::Qualifier::INCLUSIVE);
auto batch = logFile.QueryMessages(
log::AllTopics(log::QualifiedTimeRange::From(beginTime)));
std::size_t num_msgs = 0;
auto goldenIter = testMessages.begin() + 3;
auto uutIter = batch.begin();
for (; goldenIter != testMessages.end() && uutIter != batch.end();
++goldenIter, ++uutIter, ++num_msgs)
{
CheckEquality(*goldenIter, *uutIter);
}
EXPECT_EQ(6u, num_msgs);
}
//////////////////////////////////////////////////
TEST(QueryMessages, QueryAllTopicsAfterInclusiveCopy)
{
log::Log logFile;
ASSERT_TRUE(logFile.Open(":memory:", std::ios_base::out));
auto testMessages = StandardTestMessages();
InsertMessages(logFile, testMessages);
log::QualifiedTime beginTime(2s, log::QualifiedTime::Qualifier::INCLUSIVE);
log::AllTopics options_orig(log::QualifiedTimeRange::From(beginTime));
log::AllTopics options(options_orig);
auto batch = logFile.QueryMessages(options);
std::size_t num_msgs = 0;
auto goldenIter = testMessages.begin() + 3;
auto uutIter = batch.begin();
for (; goldenIter != testMessages.end() && uutIter != batch.end();
++goldenIter, ++uutIter, ++num_msgs)
{
CheckEquality(*goldenIter, *uutIter);
}
EXPECT_EQ(6u, num_msgs);
}
//////////////////////////////////////////////////
TEST(QueryMessages, QueryAllTopicsAfterInclusiveMove)
{
log::Log logFile;
ASSERT_TRUE(logFile.Open(":memory:", std::ios_base::out));
auto testMessages = StandardTestMessages();
InsertMessages(logFile, testMessages);
log::QualifiedTime beginTime(2s, log::QualifiedTime::Qualifier::INCLUSIVE);
log::AllTopics options_orig(log::QualifiedTimeRange::From(beginTime));
log::AllTopics options(std::move(options_orig));
auto batch = logFile.QueryMessages(options);
std::size_t num_msgs = 0;
auto goldenIter = testMessages.begin() + 3;
auto uutIter = batch.begin();
for (; goldenIter != testMessages.end() && uutIter != batch.end();
++goldenIter, ++uutIter, ++num_msgs)
{
CheckEquality(*goldenIter, *uutIter);
}
EXPECT_EQ(6u, num_msgs);
}
//////////////////////////////////////////////////
TEST(QueryMessages, QueryAllTopicsAfterExclusive)
{
log::Log logFile;
ASSERT_TRUE(logFile.Open(":memory:", std::ios_base::out));
auto testMessages = StandardTestMessages();
InsertMessages(logFile, testMessages);
log::QualifiedTime beginTime(2s, log::QualifiedTime::Qualifier::EXCLUSIVE);
auto batch = logFile.QueryMessages(
log::AllTopics(log::QualifiedTimeRange::From(beginTime)));
std::size_t num_msgs = 0;
auto goldenIter = testMessages.begin() + 4;
auto uutIter = batch.begin();
for (; goldenIter != testMessages.end() && uutIter != batch.end();
++goldenIter, ++uutIter, ++num_msgs)
{
CheckEquality(*goldenIter, *uutIter);
}
EXPECT_EQ(5u, num_msgs);
}
//////////////////////////////////////////////////
TEST(QueryMessages, QueryAllTopicsBeforeInclusive)
{
log::Log logFile;
ASSERT_TRUE(logFile.Open(":memory:", std::ios_base::out));
auto testMessages = StandardTestMessages();
InsertMessages(logFile, testMessages);
log::QualifiedTime endTime(3s, log::QualifiedTime::Qualifier::INCLUSIVE);
auto batch = logFile.QueryMessages(
log::AllTopics(log::QualifiedTimeRange::Until(endTime)));
std::size_t num_msgs = 0;
auto goldenIter = testMessages.begin();
auto uutIter = batch.begin();
for (; goldenIter != (testMessages.end() - 2) && uutIter != batch.end();
++goldenIter, ++uutIter, ++num_msgs)
{
CheckEquality(*goldenIter, *uutIter);
}
EXPECT_EQ(7u, num_msgs);
}
//////////////////////////////////////////////////
TEST(QueryMessages, QueryAllTopicsBeforeExclusive)
{
log::Log logFile;
ASSERT_TRUE(logFile.Open(":memory:", std::ios_base::out));
auto testMessages = StandardTestMessages();
InsertMessages(logFile, testMessages);
log::QualifiedTime endTime(3s, log::QualifiedTime::Qualifier::EXCLUSIVE);
auto batch = logFile.QueryMessages(
log::AllTopics(log::QualifiedTimeRange::Until(endTime)));
std::size_t num_msgs = 0;
auto goldenIter = testMessages.begin();
auto uutIter = batch.begin();
for (; goldenIter != (testMessages.end() - 3) && uutIter != batch.end();
++goldenIter, ++uutIter, ++num_msgs)
{
CheckEquality(*goldenIter, *uutIter);
}
EXPECT_EQ(6u, num_msgs);
}
//////////////////////////////////////////////////
TEST(QueryMessages, QueryAllTopicsBetweenInclusive)
{
log::Log logFile;
ASSERT_TRUE(logFile.Open(":memory:", std::ios_base::out));
auto testMessages = StandardTestMessages();
InsertMessages(logFile, testMessages);
log::QualifiedTime beginTime(2s, log::QualifiedTime::Qualifier::INCLUSIVE);
log::QualifiedTime endTime(3s, log::QualifiedTime::Qualifier::INCLUSIVE);
auto batch = logFile.QueryMessages(
log::AllTopics(log::QualifiedTimeRange(beginTime, endTime)));
std::size_t num_msgs = 0;
auto goldenIter = testMessages.begin() + 3;
auto uutIter = batch.begin();
for (; goldenIter != (testMessages.end() - 2) && uutIter != batch.end();
++goldenIter, ++uutIter, ++num_msgs)
{
CheckEquality(*goldenIter, *uutIter);
}
EXPECT_EQ(4u, num_msgs);
}
//////////////////////////////////////////////////
TEST(QueryMessages, QueryAllTopicsBetweenExclusive)
{
log::Log logFile;
ASSERT_TRUE(logFile.Open(":memory:", std::ios_base::out));
auto testMessages = StandardTestMessages();
InsertMessages(logFile, testMessages);
log::QualifiedTime beginTime(2s, log::QualifiedTime::Qualifier::EXCLUSIVE);
log::QualifiedTime endTime(3s, log::QualifiedTime::Qualifier::EXCLUSIVE);
auto batch = logFile.QueryMessages(
log::AllTopics(log::QualifiedTimeRange(beginTime, endTime)));
std::size_t num_msgs = 0;
auto goldenIter = testMessages.begin() + 4;
auto uutIter = batch.begin();
for (; goldenIter != (testMessages.end() - 3) && uutIter != batch.end();
++goldenIter, ++uutIter, ++num_msgs)
{
CheckEquality(*goldenIter, *uutIter);
}
EXPECT_EQ(2u, num_msgs);
}
//////////////////////////////////////////////////
TEST(QueryMessages, QueryTopicPatternAllTime)
{
log::Log logFile;
ASSERT_TRUE(logFile.Open(":memory:", std::ios_base::out));
auto testMessages = StandardTestMessages();
InsertMessages(logFile, testMessages);
auto batch = logFile.QueryMessages(log::TopicPattern(std::regex(".*/two")));
std::size_t num_msgs = 0;
auto goldenIter = testMessages.begin();
auto uutIter = batch.begin();
for (; goldenIter != testMessages.end() && uutIter != batch.end();
++goldenIter)
{
if (goldenIter->topic == "/topic/two")
{
CheckEquality(*goldenIter, *uutIter);
++uutIter;
++num_msgs;
}
}
EXPECT_EQ(3u, num_msgs);
}
//////////////////////////////////////////////////
TEST(QueryMessages, QueryTopicPatternAfterInclusive)
{
log::Log logFile;
ASSERT_TRUE(logFile.Open(":memory:", std::ios_base::out));
auto testMessages = StandardTestMessages();
InsertMessages(logFile, testMessages);
log::QualifiedTime beginTime(2s, log::QualifiedTime::Qualifier::INCLUSIVE);
auto batch = logFile.QueryMessages(log::TopicPattern(
std::regex(".*/one"), log::QualifiedTimeRange::From(beginTime)));
std::size_t num_msgs = 0;
auto goldenIter = testMessages.begin() + 3;
auto uutIter = batch.begin();
for (; goldenIter != testMessages.end() && uutIter != batch.end();
++goldenIter)
{
if (goldenIter->topic == "/topic/one")
{
CheckEquality(*goldenIter, *uutIter);
++uutIter;
++num_msgs;
}
}
EXPECT_EQ(4u, num_msgs);
}
//////////////////////////////////////////////////
TEST(QueryMessages, QueryTopicPatternBeforeInclusive)
{
log::Log logFile;
ASSERT_TRUE(logFile.Open(":memory:", std::ios_base::out));
auto testMessages = StandardTestMessages();
InsertMessages(logFile, testMessages);
log::QualifiedTime endTime(3s, log::QualifiedTime::Qualifier::INCLUSIVE);
auto batch = logFile.QueryMessages(log::TopicPattern(
std::regex(".*/one"), log::QualifiedTimeRange::Until(endTime)));
std::size_t num_msgs = 0;
auto goldenIter = testMessages.begin();
auto uutIter = batch.begin();
for (; goldenIter != (testMessages.end() - 2) && uutIter != batch.end();
++goldenIter)
{
if (goldenIter->topic == "/topic/one")
{
CheckEquality(*goldenIter, *uutIter);
++uutIter;
++num_msgs;
}
}
EXPECT_EQ(5u, num_msgs);
}
//////////////////////////////////////////////////
TEST(QueryMessages, QueryTopicListAllTime)
{
log::Log logFile;
ASSERT_TRUE(logFile.Open(":memory:", std::ios_base::out));
auto testMessages = StandardTestMessages();
InsertMessages(logFile, testMessages);
auto batch = logFile.QueryMessages(log::TopicList("/topic/two"));
std::size_t num_msgs = 0;
auto goldenIter = testMessages.begin();
auto uutIter = batch.begin();
for (; goldenIter != testMessages.end() && uutIter != batch.end();
++goldenIter)
{
if (goldenIter->topic == "/topic/two")
{
CheckEquality(*goldenIter, *uutIter);
++uutIter;
++num_msgs;
}
}
EXPECT_EQ(3u, num_msgs);
}
//////////////////////////////////////////////////
TEST(QueryMessages, QueryTopicListAfterInclusive)
{
log::Log logFile;
ASSERT_TRUE(logFile.Open(":memory:", std::ios_base::out));
auto testMessages = StandardTestMessages();
InsertMessages(logFile, testMessages);
log::QualifiedTime beginTime(2s, log::QualifiedTime::Qualifier::INCLUSIVE);
auto batch = logFile.QueryMessages(log::TopicList(
"/topic/one", log::QualifiedTimeRange::From(beginTime)));
std::size_t num_msgs = 0;
auto goldenIter = testMessages.begin() + 3;
auto uutIter = batch.begin();
for (; goldenIter != testMessages.end() && uutIter != batch.end();
++goldenIter)
{
if (goldenIter->topic == "/topic/one")
{
CheckEquality(*goldenIter, *uutIter);
++uutIter;
++num_msgs;
}
}
EXPECT_EQ(4u, num_msgs);
}
//////////////////////////////////////////////////
TEST(QueryMessages, QueryTopicListBeforeInclusive)
{
log::Log logFile;
ASSERT_TRUE(logFile.Open(":memory:", std::ios_base::out));
auto testMessages = StandardTestMessages();
InsertMessages(logFile, testMessages);
log::QualifiedTime endTime(3s, log::QualifiedTime::Qualifier::INCLUSIVE);
auto batch = logFile.QueryMessages(log::TopicList(
"/topic/one", log::QualifiedTimeRange::Until(endTime)));
std::size_t num_msgs = 0;
auto goldenIter = testMessages.begin();
auto uutIter = batch.begin();
for (; goldenIter != (testMessages.end() - 2) && uutIter != batch.end();
++goldenIter)
{
if (goldenIter->topic == "/topic/one")
{
CheckEquality(*goldenIter, *uutIter);
++uutIter;
++num_msgs;
}
}
EXPECT_EQ(5u, num_msgs);
}
//////////////////////////////////////////////////
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 28.486974 | 78 | 0.628772 | [
"vector"
] |
5b5ba60bd4960d1ff3332f93a4dc53d739773052 | 970 | cpp | C++ | contest/AtCoder/abc123/D.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 7 | 2018-04-14T14:55:51.000Z | 2022-01-31T10:49:49.000Z | contest/AtCoder/abc123/D.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | 5 | 2018-04-14T14:28:49.000Z | 2019-05-11T02:22:10.000Z | contest/AtCoder/abc123/D.cpp | not522/Competitive-Programming | be4a7d25caf5acbb70783b12899474a56c34dedb | [
"Unlicense"
] | null | null | null | #include "priority_queue.hpp"
#include "set.hpp"
#include "vector.hpp"
int main() {
int x(in), y(in), z(in), k(in);
Vector<int64_t> a(x, in), b(y, in), c(z, in);
a.rsort();
b.rsort();
c.rsort();
PriorityQueue<Tuple<int64_t, int, int, int>> que;
Set<Tuple<int, int, int>> s;
que.emplace(a[0] + b[0] + c[0], 0, 0, 0);
s.emplace(0, 0, 0);
for (int i = 0; i < k; ++i) {
auto [v, ai, bi, ci] = que.top();
cout << v << endl;
if (ai + 1 < x && !s.contains(Tuple<int, int, int>(ai + 1, bi, ci))) {
que.emplace(v - a[ai] + a[ai + 1], ai + 1, bi, ci);
s.emplace(ai + 1, bi, ci);
}
if (bi + 1 < y && !s.contains(Tuple<int, int, int>(ai, bi + 1, ci))) {
que.emplace(v - b[bi] + b[bi + 1], ai, bi + 1, ci);
s.emplace(ai, bi + 1, ci);
}
if (ci + 1 < z && !s.contains(Tuple<int, int, int>(ai, bi, ci + 1))) {
que.emplace(v - c[ci] + c[ci + 1], ai, bi, ci + 1);
s.emplace(ai, bi, ci + 1);
}
}
}
| 30.3125 | 74 | 0.482474 | [
"vector"
] |
5b67e3c466288a1084552382555d1a3e7d50cf59 | 861 | cpp | C++ | algorithms/cpp/393.cpp | viing937/leetcode | e21ca52c98bddf59e43522c0aace5e8cf84350eb | [
"MIT"
] | 3 | 2016-10-01T10:15:09.000Z | 2017-07-09T02:53:36.000Z | algorithms/cpp/393.cpp | viing937/leetcode | e21ca52c98bddf59e43522c0aace5e8cf84350eb | [
"MIT"
] | null | null | null | algorithms/cpp/393.cpp | viing937/leetcode | e21ca52c98bddf59e43522c0aace5e8cf84350eb | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool validUtf8(vector<int> &data) {
int n = data.size();
for (int i = 0; i < n; i++) {
int idx = -1;
for (int j = 0; j < 8; j++) {
if ((data[i] & (0x80>>j)) == 0x00) {
idx = j;
break;
}
}
if (idx < 0 || idx == 1 || idx > 4)
return false;
if (idx == 0)
continue;
for (int j = 1; j < idx; j++) {
if ((data[i+j] & 0x80) != 0x80)
return false;
}
i += idx-1;
}
return true;
}
};
int main() {
vector<int> data = {197,130,1};
Solution solution;
solution.validUtf8(data);
return 0;
}
| 19.568182 | 52 | 0.372822 | [
"vector"
] |
5b68a90b6d07b8d26a2249b3fdb4bd2321de3741 | 2,464 | hpp | C++ | MCTS.hpp | Roout/minimax | d4f20fbe9d6f19f8fb078874e2af8b45c92603e8 | [
"MIT"
] | null | null | null | MCTS.hpp | Roout/minimax | d4f20fbe9d6f19f8fb078874e2af8b45c92603e8 | [
"MIT"
] | 7 | 2020-10-26T22:58:07.000Z | 2021-04-06T11:48:18.000Z | MCTS.hpp | Roout/tic-tac-toe-solver | d4f20fbe9d6f19f8fb078874e2af8b45c92603e8 | [
"MIT"
] | null | null | null | #ifndef MCTS_HPP
#define MCTS_HPP
#include "Board.hpp"
#include "ElementPool.hpp"
#include "Solver.hpp"
#include <cstdint>
#include <random>
namespace solution {
// TODO: remove parent from the node
// TODO: get rid of the fucking std::vector
struct Node final {
Solver::State_t m_state {};
std::vector<Node*> m_children {};
Node* m_parent { nullptr };
uint32_t m_visits { 0u };
float m_reward { 0.f };
uint8_t m_player { 0 };
};
/**
* MCTS doesn't evaluate each node, only leaf
* Constrains: time & memory
*/
class MCTS final : public Solver {
public:
/**
* @param timeLimit (stop condition) timelimit for algorithm in microseconds
* @param iterations (stop condition) limit on number of algorithm's iterations (main while loop)
* @param treeSize (stop condition) max number of nodes algorithm can add to the tree
* @param player Define player identity for AI (next action in game is performed by htis player).
* Belongs to integer range [0, 1] inclusive
* @param playerMapping Maps player to board mark!
*/
MCTS(uint64_t timeLimit
, uint64_t iterations
, uint64_t treeSize
, uint8_t player
, Mapping_t && playerMapping
);
/**
* Run MCTS algorithm for the given board state
* @param board is a current game state
* @return the best move. To extract row and col do the following:
* - row = return_value / 3;
* - col = return_value % 3
*/
size_t Run(State_t board) override;
void Print(std::ostream& os) const override;
private:
void Expand(Node* node);
Node* Select(Node* node) const noexcept;
float Simulate(Node* node);
void Backup(Node* node, float reward);
void BackupNegamax(Node* node, float reward);
bool IsLeaf(const Node* node) const noexcept;
// upper confidence bound of the tree
float UCT(const Node* node, const Node* parent) const noexcept;
private:
// Time constrain for the algorithm (in microseconds)
// Default value: 0.1s
const uint64_t m_timeLimit { 100'000 };
const uint64_t m_iterations { 2000 };
const uint64_t m_treeSize { 10'000 };
ElementPool<Node> m_pool{};
std::mt19937 m_engine{};
};
inline bool MCTS::IsLeaf(const Node* node) const noexcept {
return node->m_children.empty();
}
} // namespace solution
#endif // MCTS_HPP | 27.076923 | 108 | 0.645698 | [
"vector"
] |
5b699b2d1bc6081f6d861c946d5ae237fbfed03b | 13,114 | cpp | C++ | mech/mechanics_driver.cpp | paulkefer/cardioid | 59c07b714d8b066b4f84eb50487c36f6eadf634c | [
"MIT-0",
"MIT"
] | 33 | 2018-12-12T20:05:06.000Z | 2021-09-26T13:30:16.000Z | mech/mechanics_driver.cpp | paulkefer/cardioid | 59c07b714d8b066b4f84eb50487c36f6eadf634c | [
"MIT-0",
"MIT"
] | 5 | 2019-04-25T11:34:43.000Z | 2021-11-14T04:35:37.000Z | mech/mechanics_driver.cpp | paulkefer/cardioid | 59c07b714d8b066b4f84eb50487c36f6eadf634c | [
"MIT-0",
"MIT"
] | 15 | 2018-12-21T22:44:59.000Z | 2021-08-29T10:30:25.000Z | #include "mfem.hpp"
#include "cardiac_physics.hpp"
#include "cardiac_integrators.hpp"
#include "mechanics_driver.hpp"
#include "ConstantTension.hpp"
#include "Lumens2009.hpp"
#include <memory>
#include <iostream>
#include <fstream>
#include <sys/stat.h>
#include <cerrno>
int main(int argc, char *argv[])
{
// Initialize MPI.
int num_procs, myid;
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &num_procs);
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
// Parse command-line options.
const char *mesh_file = "./beam-hex.mesh";
int ser_ref_levels = 0;
int par_ref_levels = 0;
int order = 2;
double newton_rel_tol = 1.0e-2;
double newton_abs_tol = 1.0e-12;
int newton_iter = 500;
double tf = 1.0;
double dt = 1.0;
bool slu = true;
OptionsParser args(argc, argv);
args.AddOption(&run_mode, "-rm", "--run-mode",
"Run mode. 1 is cantilever beam, 2 is inflated ventricle, and 3 is active tension beam.");
args.AddOption(&ser_ref_levels, "-rs", "--refine-serial",
"Number of times to refine the mesh uniformly in serial.");
args.AddOption(&par_ref_levels, "-rp", "--refine-parallel",
"Number of times to refine the mesh uniformly in parallel.");
args.AddOption(&order, "-o", "--order",
"Order (degree) of the finite elements.");
args.AddOption(&newton_rel_tol, "-rel", "--relative-tolerance",
"Relative tolerance for the Newton solve.");
args.AddOption(&newton_abs_tol, "-abs", "--absolute-tolerance",
"Absolute tolerance for the Newton solve.");
args.AddOption(&newton_iter, "-it", "--newton-iterations",
"Maximum iterations for the Newton solve.");
args.AddOption(&tf, "-tf", "--t-final",
"Final time.");
args.AddOption(&dt, "-dt", "--time-step",
"Length of time step.");
args.AddOption(&slu, "-slu", "--super-lu", "-no-slu", "--no-super-lu",
"Use direct solver.");
args.Parse();
if (!args.Good())
{
if (myid == 0)
{
args.PrintUsage(cout);
}
MPI_Finalize();
return 1;
}
if (myid == 0)
{
args.PrintOptions(cout);
}
// Open the mesh
Mesh *mesh = NULL;
if (run_mode == 1 || run_mode == 3) {
const char *mesh_file = "./beam-hex.mesh";
mesh = new Mesh(mesh_file, 1, 1);
}
if (run_mode == 2) {
const char *mesh_file = "./hollow-ball.vtk";
mesh = new Mesh(mesh_file, 1, 1);
setSurfaces(mesh);
}
if (run_mode == 4) {
const char *mesh_file = "./heart.vtk";
mesh = new Mesh(mesh_file, 1, 1);
setSurfaces(mesh);
}
ParMesh *pmesh = NULL;
for (int lev = 0; lev < ser_ref_levels; lev++)
{
mesh->UniformRefinement();
}
pmesh = new ParMesh(MPI_COMM_WORLD, *mesh);
for (int lev = 0; lev < par_ref_levels; lev++)
{
pmesh->UniformRefinement();
}
delete mesh;
int dim = pmesh->Dimension();
// Define the finite element spaces for displacement and pressure (Stokes elements)
H1_FECollection quad_coll(order, dim);
H1_FECollection lin_coll(order-1, dim);
ParFiniteElementSpace R_space(pmesh, &quad_coll, dim);
ParFiniteElementSpace W_space(pmesh, &lin_coll);
Array<ParFiniteElementSpace *> spaces(2);
spaces[0] = &R_space;
spaces[1] = &W_space;
HYPRE_Int glob_R_size = R_space.GlobalTrueVSize();
HYPRE_Int glob_W_size = W_space.GlobalTrueVSize();
// Define the Dirichlet conditions (set to boundary attribute 1)
// Outer index is varible (u or p)
// Inner index denotes whether boundary is a Dirichlet type.
Array<Array<int> *> ess_bdr(2);
// Boundary condition markers
// 1 - Dirichlet/Essential
// 2 - Free surface
// 3 - Traction (not currently used)
// 4 - Pressure (also for volume computation and constraint)
Array<int> ess_bdr_u(R_space.GetMesh()->bdr_attributes.Max());
Array<int> ess_bdr_p(W_space.GetMesh()->bdr_attributes.Max());
Array<int> pres_bdr(R_space.GetMesh()->bdr_attributes.Max());
// (Max is really size)
// These are bools for whether the boundary is Dirichlet
ess_bdr_p = 0;
ess_bdr_u = 0;
ess_bdr_u[0] = 1;
// These are bools for whether the boundary has a pressure load
pres_bdr = 0;
pres_bdr[3] = 1;
// Setting up the array of arrays for both variables
ess_bdr[0] = &ess_bdr_u;
ess_bdr[1] = &ess_bdr_p;
// Print the mesh statistics
if (myid == 0)
{
std::cout << "***********************************************************\n";
std::cout << "dim(u) = " << glob_R_size << "\n";
std::cout << "dim(p) = " << glob_W_size << "\n";
std::cout << "dim(u+p) = " << glob_R_size + glob_W_size << "\n";
std::cout << "***********************************************************\n";
}
// Define the block structure of the solution vector (u then p)
Array<int> block_trueOffsets(3);
block_trueOffsets[0] = 0;
block_trueOffsets[1] = R_space.TrueVSize();
block_trueOffsets[2] = W_space.TrueVSize();
block_trueOffsets.PartialSum();
BlockVector xp(block_trueOffsets);
// Define grid functions for the current configuration, reference configuration,
// final deformation, and pressure
ParGridFunction x_gf(&R_space);
ParGridFunction x_ref(&R_space);
ParGridFunction x_def(&R_space);
ParGridFunction p_gf(&W_space);
// Project the initial and reference configuration functions onto the appropriate grid functions
VectorFunctionCoefficient deform(dim, InitialDeformation);
VectorFunctionCoefficient refconfig(dim, ReferenceConfiguration);
x_gf.ProjectCoefficient(deform);
x_ref.ProjectCoefficient(refconfig);
p_gf = 0.0;
// Set up the block solution vectors
// Assigning to each xp region with the appropriate grid function
x_gf.GetTrueDofs(xp.GetBlock(0));
p_gf.GetTrueDofs(xp.GetBlock(1));
// Initialize the cardiac mechanics operator
CardiacOperator oper(spaces, ess_bdr, pres_bdr, block_trueOffsets,
newton_rel_tol, newton_abs_tol, newton_iter, dt, slu);
// Loop over the timesteps
for (double t = 0.0; t<tf; t += dt) {
// Solve the Newton system
oper.SetTime(t + dt);
oper.Solve(xp);
if (myid == 0) {
std::cout << "***********************************************************\n";
std::cout << "Solve at time " << t + dt << " complete\n";
std::cout << "***********************************************************\n";
}
}
// Distribute the ghost dofs
// Assogm to the grid functions
x_gf.Distribute(xp.GetBlock(0));
p_gf.Distribute(xp.GetBlock(1));
// Set the final deformation
subtract(x_gf, x_ref, x_def);
// Save the displaced mesh, the final deformation, and the pressure
{
GridFunction *nodes = &x_gf;
int owns_nodes = 0;
pmesh->SwapNodes(nodes, owns_nodes);
if (myid == 0)
{
int err = mkdir("output", 0777);
err = (err && (errno != EEXIST)) ? 1 : 0;
if (err == 1) {
std::cout << "Error creating output directory!\n";
}
}
ostringstream mesh_name, pressure_name, deformation_name;
mesh_name << "output/mesh." << setfill('0') << setw(6) << myid;
pressure_name << "output/pressure." << setfill('0') << setw(6) << myid;
deformation_name << "output/deformation." << setfill('0') << setw(6) << myid;
ofstream mesh_ofs(mesh_name.str().c_str());
mesh_ofs.precision(8);
pmesh->Print(mesh_ofs);
ofstream pressure_ofs(pressure_name.str().c_str());
pressure_ofs.precision(8);
p_gf.Save(pressure_ofs);
ofstream deformation_ofs(deformation_name.str().c_str());
deformation_ofs.precision(8);
x_def.Save(deformation_ofs);
}
// Free the used memory.
delete pmesh;
MPI_Finalize();
return 0;
}
CardiacOperator::CardiacOperator(Array<ParFiniteElementSpace *>&fes,
Array<Array<int> *>&ess_bdr,
Array<int> &pres_bdr,
Array<int> &block_trueOffsets,
double rel_tol,
double abs_tol,
int iter,
double timestep,
bool superlu)
: TimeDependentOperator(fes[0]->TrueVSize() + fes[1]->TrueVSize(), 0.0),
newton_solver(fes[0]->GetComm(), 0.8), dt(timestep), slu(superlu)
{
Array<Vector *> rhs(2);
rhs = NULL;
tension_func = NULL;
qat = NULL;
fes.Copy(spaces);
// Define the quadrature space for the active tension coefficient
Q_space = new QuadratureSpace(fes[0]->GetMesh(), 2*(fes[0]->GetOrder(0))+3);
// Define the forcing function coefficients
fib = new VectorFunctionCoefficient(3, FiberFunction);
pres = new FunctionCoefficient(PressureFunction);
vol = new VectorFunctionCoefficient(3, VolumeFunction);
// Define the active tension coefficients
if (run_mode == 3) {
tension_func = new ActiveTensionFunction(Q_space, fes[0], *fib);
tension_func->Initialize();
qat = new QuadratureFunctionCoefficient(tension_func);
}
// Initialize the Cardiac model (transversely isotropic)
if (run_mode == 1) {
model = new CardiacModel (2.0, 8.0, 2.0, 2.0, 4.0, 4.0, 2.0);
}
else {
model = new CardiacModel (10, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0);
}
// Define the mixed nonlinear form
Hform = new ParBlockNonlinearForm(spaces);
// Add the passive stress integrator
Hform->AddDomainIntegrator(new CardiacNLFIntegrator(model, *fib));
// Add the active tension integrator (only mode 3)
if (run_mode == 3) {
Hform->AddDomainIntegrator(new ActiveTensionNLFIntegrator(*qat, *fib));
}
// Add the pressure boundary integrators
if (run_mode == 1 || run_mode == 2 || run_mode == 4) {
Hform->AddBdrFaceIntegrator(new PressureBoundaryNLFIntegrator(*pres, *vol), pres_bdr);
}
// Set the essential boundary conditions
Hform->SetEssentialBC(ess_bdr, rhs);
if (slu) {
SuperLUSolver *superlu = NULL;
superlu = new SuperLUSolver(MPI_COMM_WORLD);
superlu->SetPrintStatistics(false);
superlu->SetSymmetricPattern(false);
superlu->SetColumnPermutation(superlu::PARMETIS);
J_solver = superlu;
J_prec = NULL;
}
else {
// Compute the pressure mass stiffness matrix
ParBilinearForm *a = new ParBilinearForm(spaces[1]);
ConstantCoefficient one(1.0);
OperatorHandle mass(Operator::Hypre_ParCSR);
a->AddDomainIntegrator(new MassIntegrator(one));
a->Assemble();
a->Finalize();
a->ParallelAssemble(mass);
delete a;
mass.SetOperatorOwner(false);
pressure_mass = mass.Ptr();
// Initialize the Jacobian preconditioner
JacobianPreconditioner *jac_prec =
new JacobianPreconditioner(fes, *pressure_mass, block_trueOffsets);
J_prec = jac_prec;
// Set up the Jacobian solver
GMRESSolver *j_gmres = new GMRESSolver(spaces[0]->GetComm());
j_gmres->iterative_mode = false;
j_gmres->SetRelTol(1e-10);
j_gmres->SetAbsTol(1e-10);
j_gmres->SetMaxIter(300);
j_gmres->SetPrintLevel(1);
j_gmres->SetPreconditioner(*J_prec);
J_solver = j_gmres;
}
// Set the newton solve parameters
newton_solver.iterative_mode = true;
newton_solver.SetSolver(*J_solver);
newton_solver.SetOperator(*this);
newton_solver.SetPrintLevel(1);
newton_solver.SetRelTol(rel_tol);
newton_solver.SetAbsTol(abs_tol);
newton_solver.SetMaxIter(iter);
}
// Solve the Newton system
void CardiacOperator::Solve(Vector &xp) const
{
Vector zero;
// Apply and find the root of the nonlinear operator
// Zero is the right hand size
// xp is already initialized with the first guess.
// This method updates it to the solution.
newton_solver.Mult(zero, xp);
if (run_mode == 3) {
tension_func->CommitStep(dt);
}
}
// compute: y = H(x,p)
void CardiacOperator::Mult(const Vector &k, Vector &y) const
{
// Apply the nonlinear form
if (run_mode == 1 || run_mode == 2) {
pres->SetTime(this->GetTime());
}
if (run_mode == 3) {
tension_func->TryStep(k, dt);
}
// This is the actual residual evaluation
Hform->Mult(k, y);
}
// Compute the Jacobian from the nonlinear form
Operator &CardiacOperator::GetGradient(const Vector &xp) const
{
Vector xg;
/*
double volume = Hform->GetVolume(xp);
int myid;
MPI_Comm_rank(MPI_COMM_WORLD, &myid);
if (myid == 0) {
std::cout << "volume: " << volume << std::endl;
}
*/
return Hform->GetGradient(xp);
}
CardiacOperator::~CardiacOperator()
{
delete J_solver;
delete fib;
delete pres;
delete Q_space;
if (J_prec != NULL) {
delete J_prec;
}
delete model;
}
| 31.22381 | 111 | 0.610569 | [
"mesh",
"vector",
"model"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.